Beispiel #1
0
def solve(factory, method, input_file, output_file):

    print("Creating Graph/Maze")
    t0 = time.time()
    maze = Maze(input_file, output_file)
    t1 = time.time()
    total_time = t1 - t0
    print("Time to make maze: ", total_time, "\n")

    # Create and run solver
    [title, solver] = factory.createsolver(method)
    print("Starting Solve:", title)

    t0 = time.time()
    results = solver(maze)
    t1 = time.time()
    total_time = t1 - t0
    print("Time to solve maze: ", total_time, "\n")
    # print(results)

    # Render and save the returned path/solution
    t0 = time.time()
    maze.render(results, input_file, output_file)
    t1 = time.time()
    total_time = t1 - t0
    print("Time to render path: ", total_time, "\n")
def solve(maze, threaded):
    if threaded:
        methods = [
            threading.Thread(target=threaded_solve,
                             args=(depthfirst.solve, Maze(maze.image))),
            threading.Thread(target=threaded_solve,
                             args=(breadthfirst.solve, Maze(maze.image))),
            threading.Thread(target=threaded_solve,
                             args=(dijkstra.solve, Maze(maze.image))),
            threading.Thread(target=threaded_solve,
                             args=(Astar.solve, Maze(maze.image)))
        ]

        for x in methods:
            x.start()
        for x in methods:
            x.join()
    else:
        methods = [
            depthfirst.solve, breadthfirst.solve, dijkstra.solve, Astar.solve
        ]

        for method in methods:
            result = method(maze)

            maze.reset()
            print(result.name,
                  "Time Elapsed: " + str(result.completion_time),
                  "Algorithm Visited Nodes: " + str(len(result.visited)),
                  "Algorithm Path Distance " + str(result.distance),
                  "Algorithm Path Length: " + str(len(result.path)),
                  "",
                  sep="\n")

    return Result(None, None, None, None, None)
Beispiel #3
0
def imageMaze(filename, size):

    t0 = time.time()
    print("Computing Maze and Saving...")
    if size % 2 == 0:
        size += 1

    mz = Maze(size)

    data = []

    for c in mz.cells:
        if c.IN or not c.Wall:
            data.append((255, 255, 255))
        else:
            data.append(0)

    start = random.randrange(1, size, 2)
    end = random.randrange(1, size, 2)

    data[start] = (255, 255, 255)
    data[len(data) - 1 - end] = (255, 255, 255)

    img = Image.new('RGB', (size, size), color='black')
    img.putdata(data)
    img.save(filename)

    t1 = time.time()
    total = t1 - t0
    print("Time elapsed:", total)
Beispiel #4
0
def solve(factory, method, input_file, output_file):
    # Load Image
    print "Loading Image"
    im = Image.open(input_file)

    # Create maze
    print "Creating maze"
    t0 = time.time()
    maze = Maze(im)
    t1 = time.time()
    print "Node Count:", maze.count
    total = t1 - t0
    print "Time elapsed:", total, "\n"

    # Create and run solver
    [title, solver] = factory.createSolver(method)
    print "Starting solving"
    t0 = time.time()
    [result, stats] = solver(maze)
    t1 = time.time()

    total = t1 - t0

    print "Nodes explored:", stats[0]
    if stats[2]:
        print "Path found, length :", stats[1]
    else:
        print "No path found"
    print "Time elapsed: ", total, "\n"

    # Create and save output image

    print "Saving Image"
    im = im.convert('RGB')
    impixels = im.load()

    resultpath = [n.Position for n in result]

    length = len(resultpath)
    print float(1) / length

    for i in range(0, length - 1):
        a = resultpath[i]
        b = resultpath[i + 1]

        #Blue -> Red
        r = (float(i) / length) * 255.0
        px = (int(r), 0, 255 - int(r))

        if a[0] == b[0]:
            # Same Y -- horizontal line
            for x in range(min(a[1], b[1]), max(a[1], b[1])):
                impixels[x, a[0]] = px
        elif a[1] == b[1]:
            # Same X -- vertical line
            for y in range(min(a[0], b[0]), max(a[0], b[0]) + 1):
                impixels[a[1], y] = px

    im.save(output_file)
Beispiel #5
0
def solve(method, input_file):
    # Load Image
    print("Loading Image")
    im = Image.open(input_file)

    # Create the maze (and time it) - for many mazes this is more time consuming than solving the maze
    print("Creating Maze")
    t0 = time.time()
    maze = Maze(im)
    t1 = time.time()
    print("Node Count:", maze.count)
    total = t1 - t0
    print("Time elapsed:", total)

    # Create and run solver
    [title, solver] = getSolver(method)
    print("Starting Solve:", title, " on image ", input_file)

    t0 = time.time()
    [result, stats] = solver(maze)
    t1 = time.time()

    total = t1 - t0

    # Print solve stats
    print("Nodes explored: ", stats[0])
    if (stats[2]):
        print("Path found, length", stats[1])
    else:
        print("No Path Found")
    print("Time elapsed: ", total)

    print("Saving Image\n")
    im = im.convert('RGB')
    impixels = im.load()

    resultpath = [n.Position for n in result]

    length = len(resultpath)

    for i in range(0, length - 1):
        a = resultpath[i]
        b = resultpath[i + 1]

        # Blue - red
        r = int((i / length) * 255)
        px = (r, 0, 255 - r)

        if a[0] == b[0]:
            # Ys equal - horizontal line
            for x in range(min(a[1], b[1]), max(a[1], b[1])):
                impixels[x, a[0]] = px
        elif a[1] == b[1]:
            # Xs equal - vertical line
            for y in range(min(a[0], b[0]), max(a[0], b[0]) + 1):
                impixels[a[1], y] = px

    im.save(input_file[:-4] + "_sol_" + method + ".png")
Beispiel #6
0
def start(algorithm, input_file, output_name):
    img = Image.open(input_file)
    maze = Maze(img)

    # for x in maze.node_char_list:æ
    # print(x)

    draw_nodes([x.Position for x in maze.node_list], img, 'node_map')
    print("Total Nodes: " + str(len(maze.node_list)))

    visited, path = algorithm(maze)
    draw_nodes([x.Position for x in visited], img,
               f'./Solved Images/{output_name}_visited')
    draw_path([x.Position for x in path], img,
              f'./Solved Images/{output_name}_path')
    print("Algorithm Visited Nodes: " + str(len(visited)))
    print("Algorithm Path: " + str(len(path)))
Beispiel #7
0
def start(algorithm, input_file, output_name):
    img = Image.open(input_file)
    maze = Maze(img)

    # for x in maze.node_char_list:
    # print(x)

    # draw_nodes([x.Position for x in maze.node_list], img, './Solved Images/node_map')
    # print("Total Nodes: " + str(len(maze.node_list)))
    result = algorithm(maze)

    if result.path is not None and result.visited is not None:
        draw_nodes([x.Position for x in result.visited], img,
                   f'./Solved Images/{output_name}_visited')
        draw_path([x.Position for x in result.path], img,
                  f'./Solved Images/{output_name}_path')
        print(result.name,
              "Algorithm Visited Nodes: " + str(len(result.visited)),
              "Algorithm Path Length: " + str(len(result.path)),
              "Time Elapsed: " + str(result.completion_time),
              "Algorithm Path Distance " + str(result.path[-1].Distance),
              "",
              sep="\n")
Beispiel #8
0
def percolation(m, n, intervals, attempts):
    m = int(m)
    n = int(n)
    intervals = int(intervals)
    attempts = int(attempts)
    deltaP = 1 / intervals
    #Zalpha/2 para alpha = 99%
    ZAlphaHalf = 2.575

    pValues = np.arange(0, 1 + deltaP, deltaP)

    column_names = ["p", "theta", "error"]
    df = pd.DataFrame(columns=column_names)

    for p in pValues:
        #print('Probability',p)
        results = 0
        for attempt in range(0, attempts):

            M = np.zeros((m, n))
            s = np.random.uniform(0, 1, m * n)

            suma = 0
            #print(s.size)
            suave = 0
            for i in range(0, m):
                for j in range(0, n):
                    #print(s[index], p <= s[index])
                    if (p < s[(j + n * i)]):
                        M[i][j] = 1
                    else:
                        suave = suave + 1
                    suma = suma + s[(j + n * i)]

            # 0 is soft soil
            # 1 is hard soil
            #print('tamaño de la matriz: ',M.shape)
            #print('media de s', (suma/(n*m)))
            #print('probabilidad de que un bloque de tierra sea dura: ' ,p)
            #print('probabilidad de que un bloque de tierra sea suave: ' ,1-p)
            #print('porcentaje de tierra suave en la matriz:',(suave/(n*m)))
            A = Maze(M)
            solution = depthfirst.solve(A)[1][2]
            if (solution):
                results += 1
            #print(solution[1][2])
        #print('Result',results/200)
        percentage = results / attempts
        error = ZAlphaHalf * np.sqrt(
            (percentage * (1 - percentage)) / attempts)
        #print('theta(',p,') = ',percentage, '+-',error)
        dft = pd.DataFrame({
            "p": [p],
            "theta": [percentage],
            "error": [error]
        },
                           columns=column_names)
        #print(dft)
        df = df.append(dft, ignore_index=True)

    df.insert(3, "maxTheta", df["theta"] + df["error"])
    df.insert(4, "minTheta", df["theta"] - df["error"])
    print(df)
    df.to_csv('data.csv')
    #df.plot()

    df.plot(x='p', y=['theta', 'maxTheta', 'minTheta'])
    """
    plt.table(cellText= df.to_numpy(),
              rowLabels=range(0,intervals+1),
              colLabels=column_names,
              loc='center')
    plt.subplots_adjust(left=0.2, top=0.8)
    """
    plt.show()
Beispiel #9
0
def solve(factory, method, input_file, output_file):
    # Load Image
    print("Loading Image")
    im = Image.open(input_file)

    # Create the maze (and time it) - for many mazes this is more time consuming than solving the maze
    print("Creating Maze")
    t0 = time.time()
    maze = Maze(im)
    t1 = time.time()
    print("Node Count:", maze.count)
    total = t1-t0
    print("Time elapsed:", total, "\n")

    # Create and run solver
    [title, solver] = factory.createsolver(method)
    print("Starting Solve:", title)

    t0 = time.time()
    [result, stats] = solver(maze)
    t1 = time.time()

    total = t1-t0

    # Print solve stats
    print("Nodes explored: ", stats[0])
    if (stats[2]):
        print("Path found, length", stats[1])
    else:
        print("No Path Found")
    print("Time elapsed: ", total, "\n")

    """
    Create and save the output image.
    This is simple drawing code that travels between each node in turn, drawing either
    a horizontal or vertical line as required. Line colour is roughly interpolated between
    blue and red depending on how far down the path this section is.
    """

    print("Saving Image")
    im = im.convert('RGB')
    impixels = im.load()

    resultpath = [n.Position for n in result]

    length = len(resultpath)

    for i in range(0, length - 1):
        a = resultpath[i]
        b = resultpath[i+1]

        # Blue - red
        r = int((i / length) * 255)
        px = (r, 0, 255 - r)
        nodepx = (255-r, 255, r)

        if a[0] == b[0]:
            # Ys equal - horizontal line
            for x in range(min(a[1], b[1]), max(a[1], b[1])):
                impixels[x, a[0]] = px
        elif a[1] == b[1]:
            # Xs equal - vertical line
            for y in range(min(a[0], b[0]), max(a[0], b[0]) + 1):
                impixels[a[1], y] = px
        # highlight the nodes used in the solution
        impixels[a[1], a[0]] = nodepx
        impixels[b[1], b[0]] = nodepx
    im.save(output_file)
Beispiel #10
0
def solve(factory, method, input_file, output_file):
    # Load Image
    print("Loading Image")
    im = Image.open(input_file)

    # Create the maze (and time it) - for many mazes this is more time consuming than solving the maze
    print("Creating Maze")
    t0 = time.time()
    maze = Maze(im)
    t1 = time.time()
    print("Node Count:", maze.count)
    total = t1 - t0
    print("Time elapsed:", total, "\n")

    # Create and run solver
    [title, solver] = factory.createsolver(method)
    print("Starting Solve:", title)

    t0 = time.time()
    [result, stats] = solver(maze)
    t1 = time.time()

    total = t1 - t0

    # Print solve stats
    print("Nodes explored: ", stats[0])
    if (stats[2]):
        print("Path found, length", stats[1])
    else:
        print("No Path Found")
    print("Time elapsed: ", total, "\n")
    """
    Create and save the output image.
    This is simple drawing code that travels between each node in turn, drawing either
    a horizontal or vertical line as required. Line colour is roughly interpolated between
    blue and red depending on how far down the path this section is. Dependency on numpy
    should be easy to remove at some point.
    """

    print("Saving Image")
    mazeimage = np.array(im)
    imout = np.array(mazeimage)
    imout[imout == 1] = 255
    out = imout[:, :, np.newaxis]

    out = np.repeat(out, 3, axis=2)

    resultpath = [n.Position for n in result]

    length = len(resultpath)

    px = [0, 0, 0]
    for i in range(0, length - 1):
        a = resultpath[i]
        b = resultpath[i + 1]

        # Blue - red
        px[0] = int((i / length) * 255)
        px[2] = 255 - px[0]

        if a[0] == b[0]:
            # Ys equal - horizontal line
            for x in range(min(a[1], b[1]), max(a[1], b[1])):
                out[a[0], x, :] = px
        elif a[1] == b[1]:
            # Xs equal - vertical line
            for y in range(min(a[0], b[0]), max(a[0], b[0]) + 1):
                out[y, a[1], :] = px

    img = Image.fromarray(out)
    img.save(output_file)
Beispiel #11
0
                    default=sf.Default,
                    choices=sf.Choices)
parser.add_argument("input_file")
parser.add_argument("output_file")
args = parser.parse_args()

method = args.method

# Load Image
print("Loading Image")
im = Image.open(args.input_file)

# Create the maze (and time it) - for many mazes this is more time consuming than solving the maze
print("Creating Maze")
t0 = time.time()
maze = Maze(im)
t1 = time.time()
print("Node Count:", maze.count)
total = t1 - t0
print("Time elapsed:", total, "\n")

# Create and run solver
[title, solver] = sf.createsolver(args.method)
print("Starting Solve:", title)

t0 = time.time()
[result, stats] = solver(maze)
t1 = time.time()

total = t1 - t0