Beispiel #1
0
def compute_graph(edges, x, y, precision, tollerance):

    if booldebug: print(x, y)
    graph = Graph('image')
    q = Queue('nodes')
    p_node = Point(x, y)
    node = Node(p_node)
    graph.nodes.append(node)
    q.push(node)

    while not q.empty():
        node = q.top()
        q.pop()
        links = []

        p_node = node.get_point()
        x = p_node.get_x()
        y = p_node.get_y()
        cell = generate_cell(edges, p_node, precision)
        links = find_lines(cell, edges, x - precision, y - precision,
                           tollerance)
        #if booldebug: print(links)
        delete(edges, cell, x - precision, y - precision)

        for p in links:
            graph.nodes.append(Node(p))
            q.push(Node(p))

        graph.manage_links(node, links)

    if len(graph.nodes) > 2:
        return DPS(graph)
Beispiel #2
0
def addnode():
    data = json.load(open('projects/'+project+'/graph.json'))
    graph = Graph(project, auto_connect=False)

    level = int(request.form.get('level'))
    x = int(request.form.get('x'))
    y = int(request.form.get('y'))
    room = graph.get_room(Node(None, None, level, x, y))
    if room is None:
        return json.dumps({'success': False})

    newname = hex(int(time.time()*100))[2:]
    data['nodes'][newname] = {
        'level': level,
        'x': x,
        'y': y
    }
    json.dump(data, open('projects/'+project+'/graph.json', 'w'), indent=4, sort_keys=True)

    return json.dumps({
        'success': True,
        'name': newname,
        'room': room.name,
        'node': data['nodes'][newname]
    })
def build_graph(im, fbasename):
    # get image dimensions
    nrow, ncol = im.shape[0], im.shape[1]

    # for keeping visual of points added to graph
    imdup = np.zeros(im.shape)

    # initiate graph
    graph = Graph()

    # find starting pixel (first nonzero pixel)
    currentrow, currentcol = find_start(im, nrow, ncol)
    prev_vertex = Vertex(currentrow, currentcol)
    graph.addVertex(prev_vertex)

    r = 1 # radius around current pixel to be checked
    prev_visited = set()
    prev_visited.add((currentrow, currentcol))

    # traverse through image and build graph
    imdup = traverse(im, graph, nrow, ncol, currentrow, currentcol, r, imdup, prev_vertex, prev_visited)

    # save to file
    fig1 = plt.gcf()
    plt.imshow(imdup, cmap='Greys')
    plt.draw()
    fig1.savefig(fbasename + "_graph.jpg")
    
    return graph
Beispiel #4
0
def makeTestGraph(numPoints=None):
    graph = Graph()
    # Pixels always between 33 x 48
    if not numPoints:
        numPoints = randint(5,10)
    for i in range(numPoints):
        v = Vertex(int(randint(0,33)), int(randint(0,48)))
        graph.addVertex(v)
    return graph
Beispiel #5
0
def createKnightGraph(boardSize):             #this function creates the graph that
    knightGraph = Graph()                     #will be used in the tour.  "boardSize" is the length of 
    for row in range(boardSize):              #a row or column of the chess board
        for col in range(boardSize):
            nodeId = assignNodeId(row,col,boardSize)         #calls helper function to create nodes in the graph
            newPositions = genLegalMoves(row,col,boardSize)  #calls helper function to generate legal moves from a node
            for e in newPositions:
                nid = assignNodeId(e[0],e[1],boardSize)
                knightGraph.addEdge(nodeId,nid)              #adds edge between initial node and all legal knight's moves
    return knightGraph
Beispiel #6
0
def extended_popularity_similarity_optimisation_model(N,
                                                      m,
                                                      L=0,
                                                      beta=1 / 2,
                                                      T=0):
    def distance(i, j):
        r_i, phi_i, r_j, phi_j = r[i], phi[i], r[j], phi[j]
        r_j = beta * r_i + (1 - beta) * r_j
        d_phi = pi - abs(pi - abs(phi_i - phi_j))
        return cosh(r_i) * cosh(r_j) + sinh(r_i) * sinh(r_j) * cos(d_phi)

    if beta == 0:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) * (1 - exp(-r_i / 2)) / m)
    elif beta == 1:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) * r_i / m)
    else:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) *
                                 (1 - exp(-r_i *
                                          (1 - beta) / 2)) / m / (1 - beta))

    def connection_probability(d_ij, cutoff_i):
        return 1 / (1 + exp((d_ij - cutoff_i) / 2 / T))

    G = Graph()
    r = [2 * math.log(i + 1) for i in range(N)]
    phi = [2 * math.pi * random.random() for _ in range(N)]

    for i in range(N):
        G.add_vertex(i, r=r[i], phi=phi[i])
        #G.add_vertex(i, x=r[i]*math.cos(phi[i]), y=r[i]*math.sin(phi[i]))

        m += 2 * L * (1 - beta) / (1 - N**(beta - 1))**2 / (2 * beta - 1) * (
            (N / i)**(2 * beta - 1) - 1) * (1 - i**(beta - 1))
        if i <= m:
            for j in range(i):
                G.add_edge(i, j)

        elif T == 0:
            neighbours = sorted(range(i), key=lambda j: distance(i, j))[m]
            for j in neighbours:
                G.add_edge(i, j)
        else:
            cutoff_i = cutoff(r[i])
            for j in range(i):
                d_ij = distance(r[i], phi[i], r[j], phi[j])
                if random.random() < connection_probability(d_ij, cutoff_i):
                    G.add_edge(i, j)

    return G
Beispiel #7
0
def popularity_similarity_optimisation_model(N, m, beta=1 / 2, T=0):
    def distance(i, j):
        r_i, phi_i, r_j, phi_j = r[i], phi[i], r[j], phi[j]
        r_j = beta * r_i + (1 - beta) * r_j
        d_phi = pi - abs(pi - abs(phi_i - phi_j))
        return acosh(
            cosh(r_i) * cosh(r_j) + sinh(r_i) * sinh(r_j) * cos(d_phi))

    if beta == 0:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) * (1 - exp(-r_i / 2)) / m)
    elif beta == 1:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) * r_i / m)
    else:

        def cutoff(r_i):
            return r_i - 2 * log(T / sin(T * pi) *
                                 (1 - exp(-r_i *
                                          (1 - beta) / 2)) / m / (1 - beta))

    def connection_probability(d_ij, cutoff_i):
        return 1 / (1 + exp((d_ij - cutoff_i) / 2 / T))

    G = Graph()
    r = [2 * math.log(i) for i in range(1, N + 1)]
    phi = [2 * math.pi * random.random() for _ in range(N)]

    for i in range(N):

        G.add_vertex(i,
                     r=geometry.native_disk_to_hyperboloid(r[i]),
                     phi=phi[i])

        if i <= m:
            for j in range(i):
                G.add_edge(i, j)
        elif T == 0:
            print(i)
            print(sorted(range(i), key=lambda v: v))
            neighbours = sorted(range(i), key=lambda j: distance(i, j))[:m]
            for j in neighbours:
                G.add_edge(i, j)
        else:
            cutoff_i = cutoff(r[i])
            for j in range(i):
                d_ij = distance(r[i], phi[i], r[j], phi[j])
                if random.random() < connection_probability(d_ij, cutoff_i):
                    G.add_edge(i, j)

    return G
Beispiel #8
0
    def setUp(self):
        self.test_graph = Graph()
        self.test_node_0 = Node(0, 0.1, 1, 1, 1, 1, 1, 1)
        self.test_node_1 = Node(1, 0.2, 2, 2, 2, 2, 2, 2)
        self.test_node_2 = Node(2, 0.3, 1, 2, 3, 4, 5, 6)
        self.test_graph.add_vertex(self.test_node_0)
        self.test_graph.add_vertex(self.test_node_1)
        self.test_graph.add_vertex(self.test_node_2)
        self.test_graph.add_edge(self.test_node_0, self.test_node_1, 30)
        self.test_graph.add_edge(self.test_node_1, self.test_node_2, 50)

        self.test_sim = Simulation()
        self.test_sim.load_graph(self.test_graph)
Beispiel #9
0
def empty_graph(N=0, directed=False):
    '''
    Create an empty graph of given size.
    Parameters
    ----------
    N:int
        Number of vertices.
    Returns
    -------
    G : Graph
        Generated empty graph
    '''
    G = Graph() if not directed else DiGraph()
    for i in range(N):
        G.add_vertex(i)
    return G
def greedy_routing_annealing():
    A = Graph.from_saved('test/data/jazz')
    adj, vert = A.adj, A.vert
    num_targets, num_rounds, num_tries = 100, 10000
    distance = geometry.hyperboloid_distance
    vertex_list = list(vert)
    for _ in tqdm(range(num_rounds)):
        verts = random.sample(vertex_list, k=num_targets+1)
        source, targets = verts[0], verts[1:]
        neighbours = adj[source]
        r_source, theta_source = vert[source]['r'], vert[source]['theta']
        targets_coords = {target: (vert[target]['r'], vert[target]['theta']) for target in targets}
        neighbours_coords = {neighbour: (vert[neighbour]['r'], vert[neighbour]['theta']) for neighbour in neighbours}
        source_dist = {target: distance(target_x, target_y, r_source, theta_source) for target, (target_x, target_y) in targets_coords.items()}
        closest_neighbour_dist = {}
        for target, (target_x, target_y) in targets_coords.items():
            closest_dist = math.inf
            for neighbour, (neigh_x, neigh_y) in neighbours_coords.items():
                neigh_dist = distance(target_x, target_y, neigh_x, neigh_y)
                if neigh_dist < closest_dist:
                    closest_dist = neigh_dist
            closest_neighbour_dist[target] = closest_dist
        good = sum([closest_neighbour_dist[target] < source_dist[target] for target in targets])
        #r_source_new, theta_source_new = normalized_random_angular_move(r_source, theta_source)
        r_source_new, theta_source_new = normalized_random_move(r_source, theta_source)
        source_dist_new = {target: distance(target_x, target_y, r_source_new, theta_source_new) for target, (target_x, target_y) in targets_coords.items()}
        good_new = sum([closest_neighbour_dist[target] < source_dist_new[target] for target in targets])
        if good < good_new:
            A.vert[source]['r'] = r_source_new
            A.vert[source]['theta'] = theta_source_new
    print(utils.greedy_routing_score(A.adj, A.vert, representation='hyperboloid'))
    # 0.30126134440855257
    A.draw()
Beispiel #11
0
 def setUp(self):
     self.g = Graph()
     self.g.add_node("A")
     self.g.add_node("B")
     self.g.add_node("C")
     self.g.add_node("D")
     self.g.add_node("E")
     self.g.add_distance("A", "B", 5)
     self.g.add_distance("B", "C", 4)
     self.g.add_distance("C", "D", 8)
     self.g.add_distance("D", "C", 8)
     self.g.add_distance("D", "E", 6)
     self.g.add_distance("A", "D", 5)
     self.g.add_distance("C", "E", 2)
     self.g.add_distance("E", "B", 3)
     self.g.add_distance("A", "E", 7)
Beispiel #12
0
def main():
    g = Graph()
    g = g.from_file('./graph.txt')

    # # Resolvemos primer grupo de preguntas 1-5
    print "The distance of the route A-B-C", distance(g, "A", "B", "C")
    print "The distance of the route A-D", distance(g, "A", "D")
    print "The distance of the route A-D-C", distance(g, "A", "D", "C")
    print "The distance of the route A-E-B-C-D", distance(
        g, "A", "E", "B", "C", "D")
    print "The distance of the route A-E-D", distance(g, "A", "E", "D")
    print

    # # Respondemos preguntas 8 y 9
    print "The length of the shortest route from A to C.", dist_to(g, "A", "C")
    print "The length of the shortest route from B to B.", dist_to(g, "B", "B")
    print "The length of the shortest route from E to A.", dist_to(g, "E", "A")
    print
Beispiel #13
0
    def __init__(self, bins, items, population, evaporation, limit=10000):
        self.bins = bins
        self.items = items

        self.ants = []
        for i in range(population):
            self.ants.append(Ant())

        self.graph = Graph(len(bins), len(items))

        self.evaporation = evaporation
        self.limit = limit

        self.numOfEvaluations = 0
        self.ran = False
        self.runtime = 0
        self.bestRun = None
        self.avgFitness = []
Beispiel #14
0
def addpoi():
    data = json.load(open('projects/' + project + '/pois.json'))
    graph = Graph(project, auto_connect=False)

    level = int(request.form.get('level'))
    x = int(request.form.get('x'))
    y = int(request.form.get('y'))
    name = request.form.get('name')
    room = graph.get_room(Position(level, x, y))
    if room is None:
        return json.dumps({'success': False})

    data[name] = {'level': level, 'x': x, 'y': y}
    json.dump(data,
              open('projects/' + project + '/pois.json', 'w'),
              indent=4,
              sort_keys=True)

    return 'ok'
Beispiel #15
0
def addpoi():
    data = json.load(open('projects/'+project+'/pois.json'))
    graph = Graph(project, auto_connect=False)

    level = int(request.form.get('level'))
    x = int(request.form.get('x'))
    y = int(request.form.get('y'))
    name = request.form.get('name')
    room = graph.get_room(Position(level, x, y))
    if room is None:
        return json.dumps({'success': False})

    data[name] = {
        'level': level,
        'x': x,
        'y': y
    }
    json.dump(data, open('projects/'+project+'/pois.json', 'w'), indent=4, sort_keys=True)

    return 'ok'
Beispiel #16
0
def addconnection():
    data = json.load(open('projects/' + project + '/graph.json'))
    graph = Graph(project, auto_connect=False)

    node1 = graph.nodes[graph.nodes_by_name[request.form.get('node1')]]
    node2 = graph.nodes[graph.nodes_by_name[request.form.get('node2')]]

    directed = request.form.get('directed') == '1'
    ctype = request.form.get('ctype')

    if graph.get_connection(node1, node2)[0] is not None:
        return json.dumps({'success': False})

    cdata = {
        'node0': request.form.get('node1'),
        'node1': request.form.get('node2'),
    }
    if ctype != 'default':
        cdata['ctype'] = ctype

    if directed:
        cdata['directed'] = True

    data['connections'].append(cdata)
    json.dump(data,
              open('projects/' + project + '/graph.json', 'w'),
              indent=4,
              sort_keys=True)

    return json.dumps({
        'success': True,
        'x1': node1.x,
        'y1': node1.y,
        'x2': node2.x,
        'y2': node2.y,
        'node1': node1.name,
        'node2': node2.name,
        'directed': directed,
        'ctype': ctype,
        'levels': list(set((node1.level, node2.level)))
    })
Beispiel #17
0
class TestSimulation(unittest.TestCase):
    def setUp(self):
        self.test_graph = Graph()
        self.test_node_0 = Node(0, 0.1, 1, 1, 1, 1, 1, 1)
        self.test_node_1 = Node(1, 0.2, 2, 2, 2, 2, 2, 2)
        self.test_node_2 = Node(2, 0.3, 1, 2, 3, 4, 5, 6)
        self.test_graph.add_vertex(self.test_node_0)
        self.test_graph.add_vertex(self.test_node_1)
        self.test_graph.add_vertex(self.test_node_2)
        self.test_graph.add_edge(self.test_node_0, self.test_node_1, 30)
        self.test_graph.add_edge(self.test_node_1, self.test_node_2, 50)

        self.test_sim = Simulation()
        self.test_sim.load_graph(self.test_graph)

    def test_spread(self):
        res1 = min(1, Simulation.sigmoid(30) * 0.15)
        res2 = min(1, Simulation.sigmoid(60) * 0.25 * 1.2)
        self.assertAlmostEqual(
            Simulation.spread(self.test_node_0, self.test_node_1), res1)
        self.assertAlmostEqual(
            Simulation.spread(self.test_node_1, self.test_node_2), res2)

    def test_calc_new_score(self):
        res = (Simulation.spread(self.test_node_0, self.test_node_1) +
               Simulation.spread(self.test_node_2, self.test_node_1)) / 2
        self.assertAlmostEqual(self.test_sim.calc_new_score(self.test_node_1),
                               res)

    def test_run_one_timestep(self):
        print(self.test_sim.graph.get_scores())
        self.test_sim.run_one_timestep()
        print(self.test_sim.graph.get_scores())
Beispiel #18
0
def addconnection():
    data = json.load(open('projects/'+project+'/graph.json'))
    graph = Graph(project, auto_connect=False)

    node1 = graph.nodes[graph.nodes_by_name[request.form.get('node1')]]
    node2 = graph.nodes[graph.nodes_by_name[request.form.get('node2')]]

    directed = request.form.get('directed') == '1'
    ctype = request.form.get('ctype')

    if graph.get_connection(node1, node2)[0] is not None:
        return json.dumps({'success': False})

    cdata = {
        'node0': request.form.get('node1'),
        'node1': request.form.get('node2'),
    }
    if ctype != 'default':
        cdata['ctype'] = ctype

    if directed:
        cdata['directed'] = True

    data['connections'].append(cdata)
    json.dump(data, open('projects/'+project+'/graph.json', 'w'), indent=4, sort_keys=True)

    return json.dumps({
        'success': True,
        'x1': node1.x,
        'y1': node1.y,
        'x2': node2.x,
        'y2': node2.y,
        'node1': node1.name,
        'node2': node2.name,
        'directed': directed,
        'ctype': ctype,
        'levels': list(set((node1.level, node2.level)))
    })
Beispiel #19
0
def main():

    number_of_ant = 10  #numarul de furnici
    generations = 100  #numarul de generatii
    alpha = 1.0  #controleaza importanta urmei (cate furnici au mai trecut pe muchia respectiva)
    beta = 10.0  #controleaza importanaa vizibilitatii (cat de aproape se afla următorul oras)
    rho = 0.5  #coeficient de degradare a feronomului
    q = 10  #intensitatea(cantitatea) unui feromon lasata de o furnica

    aco = ACO(number_of_ant, generations, alpha, beta, rho, q)
    graph = Graph(cost_matrix, rank)

    path, cost = aco.solve(graph)
    print('cost: {}, path: {}'.format(cost, path))
Beispiel #20
0
def addnode():
    data = json.load(open('projects/' + project + '/graph.json'))
    graph = Graph(project, auto_connect=False)

    level = int(request.form.get('level'))
    x = int(request.form.get('x'))
    y = int(request.form.get('y'))
    room = graph.get_room(Node(None, None, level, x, y))
    if room is None:
        return json.dumps({'success': False})

    newname = hex(int(time.time() * 100))[2:]
    data['nodes'][newname] = {'level': level, 'x': x, 'y': y}
    json.dump(data,
              open('projects/' + project + '/graph.json', 'w'),
              indent=4,
              sort_keys=True)

    return json.dumps({
        'success': True,
        'name': newname,
        'room': room.name,
        'node': data['nodes'][newname]
    })
Beispiel #21
0
def generate_graph():
    """ Generate the graph """
    edges: set = set()
    total_refs: int = 0
    successful_refs: int = 0
    errors_dict = init_errors_dict()
    laws, frbr_work_uri_to_law = build_laws_mapping()
    vertexes_map = {hash(law): law for law in laws}

    for from_law in laws:
        law_edges: set = set()
        for ref_element in from_law.get_ref_elements():
            from_vertex: Vertex = get_from_vertex(from_law, ref_element,
                                                  law_edges, vertexes_map)

            to_vertex: Vertex = get_to_vertex(from_law, ref_element,
                                              errors_dict,
                                              frbr_work_uri_to_law, law_edges,
                                              vertexes_map)
            if not to_vertex:
                total_refs += 1
                continue

            # setup an edge and maintain metadata
            edge: Edge = Edge(from_vertex, to_vertex, ref_element)
            law_edges.add(edge)
            from_vertex.add_out_edge(edge)
            to_vertex.add_in_edge(edge)

            successful_refs += 1
            total_refs += 1
            logging.info(
                f"{total_refs}. Succeed to handle href {ref_element.attrib[HREF]} in from_law {from_law.path}"
            )

        edges.update(law_edges)

    logging.info(
        f'{total_refs = }, {successful_refs = }, failed_not_handled_refs = {total_refs - successful_refs}'
    )
    write_to_errors_file(errors_dict)

    nodes = set(vertexes_map.values())

    edges_cleaned = clean_edges(edges)

    return Graph(nodes, edges_cleaned)
Beispiel #22
0
def main():

    screen_width, screen_height = 1440, 810
    screen = pygame.display.set_mode((screen_width, screen_height))
    pygame.display.set_caption('Sorting algorithm visualization')
    clock = pygame.time.Clock()

    graph = Graph(screen)  # pass surface to draw graph on
    graph.gen_array(rand_colors=True)

    running = True
    while running:

        running = events.keypress(
            graph)  # keypress calls some graph object methods
        graph.draw_bars()
        graph.display_helptext()
        clock.tick(6)

    pygame.quit()
Beispiel #23
0
	def test_new_instance(self):
		graph = new Graph()
		assertTrue(graph.nodes)
Beispiel #24
0
#!/usr/bin/env python

from classes import Node, Graph

graphobj = Graph()

n1 = Node(name="test")
graphobj.addNode(n1)
n2 = Node(name="Child1", parent=n1)
graphobj.addNode(n2)
n3 = Node(name="Child2", parent=n1)
graphobj.addNode(n3)
n1.addChildren(n2)
n1.addChildren(n3)

nodes = graphobj.nodes

print "^^^^^^^^^^^^^^^^"
selectnode = graphobj.getNode("Child2")
print selectnode.name
print "^^^^^^^^^^^^^^^^"

for eachnode in nodes:
    print eachnode.name
    children = eachnode.getChildren()
    if len(children) > 0:
        for i in children:
            print "name"
            print i.name
            print "Parent"
            print i.parent.name
Beispiel #25
0
 def __init__(self):
     self.g = Graph()
     self.vehiclesByZip = {}
     pass
Beispiel #26
0
class ZipGraph:
    def __init__(self):
        self.g = Graph()
        self.vehiclesByZip = {}
        pass

    #Adds weighted edge to the graph by passing in a ZipDistance object. Adds key to vehicles dictionary.
    def addDist(self, zipDist: ZipDistance):
        self.g.add_edge(zipDist.zip1, zipDist.zip2, weight=zipDist.dist)
        for e in self.g.nodes:
            self.vehiclesByZip.update({str(e): []})

    #Constructs all the edges, weights, and vertices from a ZipDistanceList.
    def constructFromZDList(self, zList: ZipDistanceList):
        for d in zList.zList:
            self.addDist(d)

    #Dijkstras algorithm utilizing priority queue to find the distances to all other nodes (zips) from the current node.
    #Returns dictionary in the form of zip:shortestPathFromStart
    def dijkstras(self, startZip):
        pq = PriorityQueue()
        distance = {}
        for n in self.g.nodes:
            distance[n] = sys.maxsize
        pq.put((0, startZip))
        distance[startZip] = 0

        while not pq.empty():  #loop until no nodes are left
            u = pq.get()[1]
            for v in iter(self.g[u]):
                alt = distance[u] + int(self.g[u][v]['weight'])
                if alt < distance[v]:
                    distance[v] = alt
                    pq.put((distance[v], v))
        return distance

    #Takes in an EmergencyVehicleList and adds those vehicles to the dictionary of locations in the
    #current ZipGraph instance.
    def updateVehicleLocations(self, elist: EmergencyVehicleList):
        for vehicle in elist:
            try:
                zipList = self.vehiclesByZip[str(vehicle.zip)]
            except:
                self.vehiclesByZip.update({str(vehicle.zip): []})
                zipList = self.vehiclesByZip[str(vehicle.zip)]

            zipList.append(vehicle)

            self.vehiclesByZip.update({str(vehicle.zip): zipList})

    #Finds the closest vehicle of a requested type to a requested zip. Goes to nearest zip, sees if
    #vehicle type is there, then continues if not.
    def closestVehicle(self, startZip, vehicleType):
        dists = self.dijkstras(startZip)
        pq = PriorityQueue()
        for d in dists:
            pq.put((dists[d], d))
        while not pq.empty():
            u = pq.get()[1]
            for e in self.vehiclesByZip[str(u)]:
                if e.vType == str(vehicleType):
                    return e, dists[u]
            dists.pop(u)

    # Takes in request, finds closest available vehicle, updates request
    # vehicleID and distance, removes vehicle from ZipGraph(no double assignments)
    def fillReq(self, req: Request):
        closestV, distance = self.closestVehicle(req.zip, req.vType)
        req.distance = distance
        req.vehicle = closestV.id
        oldZipData = self.vehiclesByZip[closestV.zip]
        oldZipData.remove(closestV)
        self.vehiclesByZip[closestV.zip] = oldZipData
        return req

    # Takes a RequestList and processes each by calling fillReq()
    def fillReqList(self, reqL: RequestList):
        for r in reqL:
            r = self.fillReq(r)
        return reqL

    #Prints the graph of the Zips. Does not include vehicles at each zip.
    def __str__(self):
        return str(self.g)
Beispiel #27
0
import Tkinter as tk
import sys
import pyscreeze
import pygame
import os
from classes import Node, Graph
import termios
import tty

#Global Variables
childOffsetX = 20
screenWidth, screenHeight = pyautogui.size()
print screenHeight
print screenWidth

graphMaster = Graph()
parentRoot = Node(name="Root")
graphMaster.addNode(parentRoot)


class Application(tk.Frame):
    def __init__(self, master=None):
        tk.Frame.__init__(self, master=None)
        self.grid()
        self.master.minsize(width=200, height=100)
        self.master.bind("<Key>", self.show)
        self.filename = ""
        self.height = 0
        self.width = 0
        self.listele = ()
        self.createWidjet()
Beispiel #28
0
assets = Environment(app)
babel = Babel(app)

if 'C3NAVPROJECT' in os.environ:
    project = os.environ['C3NAVPROJECT']
elif len(sys.argv) > 1:
    project = sys.argv[1]
else:
    print(
        'Please specify project: run.py <project> or environment variable C3NAVPROJECT'
    )
    sys.exit(1)

starttime = time.time()
graph = Graph(project,
              auto_connect=True,
              load_wifi=(not os.environ.get('ROUTEONLY')))
print('Graph loaded in %.3fs' % (time.time() - starttime))


@babel.localeselector
def get_locale():
    locale = 'en'  # request.accept_languages.best_match(LANGUAGES.keys())
    if request.cookies.get('lang') in LANGUAGES.keys():
        locale = request.cookies.get('lang')
    if request.args.get('lang') in LANGUAGES.keys():
        locale = request.args.get('lang')
    return locale


@app.before_request
Beispiel #29
0
import classes.Graph as Gr
import classes.Algorithms as Algs
import random as rnd
import pandas as pd

city = 'NY'

gr = Gr.Graph()
print('read graph')
gr.read_graph_from_csv(city + '_nodes.csv', city + '_roads.csv')

print('init ALT')

# amount of marks хардкод этой константы есть в конструкторе Node и в heuristic альта
k = 16
print('Amount of landmarks:', k)
marks = rnd.sample(list(gr.nodes.values()), k)

# поиск всех кротчайших путей
counter = 0
for mark in marks:
    dists = Algs.dijkstra_alt(gr, mark)
    for node in list(gr.nodes.values()):
        node.dist_to_mark[counter] = dists[node.id]
    counter += 1
    print(counter, 'of', k)

# создание DataFrame нодов для записи в csv
ids = []
x = []
y = []
Beispiel #30
0
        active_time = graph.active_time / running_time
        active_time = round(100 * active_time, 2)
        var_active.set("Active Time : {}%".format(active_time))
    keys_clicks = graph.keypresses / max((graph.clicks + graph.keypresses), 1)
    keys_clicks = round(100 * keys_clicks, 2)
    var_cur.set("Current : {} APM".format(cur_apm))
    var_cur_hover.set("{} APM".format(cur_apm))
    var_max.set("Max : {} APM".format(max_apm))
    var_avg.set("Avg : {} APM".format(avg_apm))
    var_kc.set("Keypresses : {}%".format(keys_clicks))

    Fenetre.update_idletasks()

    if graph.active != "inactive":
        stats.after(100, update_stats)


# Real-time moving average apm graphing
graph = Graph(Fenetre,
              bg="black",
              width=width,
              height=3 * height // 4,
              max_x=10,
              max_y=10)
graph.place(x=0, y=height // 4)
graph.display(intro=True)

Fenetre.mainloop()
klistener.stop()
mlistener.stop()
Beispiel #31
0
def makeSpecificGraph():
    # Set up graph
    graph = Graph()

    v1 = Vertex(2,3)
    graph.addVertex(v1)

    v2 = Vertex(0,0)
    graph.addVertex(v2)
    
    dist = v1.EuclidDist(v2)
    e = Edge(v1, v2, dist, False)
    graph.addEdge(e)

    v3 = Vertex(4,5)
    graph.addVertex(v3)
    
    e2 = Edge(v1, v3, v3.EuclidDist(v1), True)
    graph.addEdge(e2)

    v4 = Vertex(10,20)
    graph.addVertex(v4)

    e3 = Edge(v3, v4, v3.EuclidDist(v4), False)
    graph.addEdge(e3)
    return graph
Beispiel #32
0
def tests():
    v1 = Vertex(2,3)
    v2 = Vertex(0,0)
    v1.print_out()
    v2.print_out()
    print "\n"
    
    dist = v1.EuclidDist(v2)
    e = Edge(v1, v2, dist, False)

    graph = Graph()

    graph.addVertex(v1)
    graph.addVertex(v2)
    graph.addEdge(e)
    graph.print_adjmatrix()
    graph.print_vertexlst()

    v3 = Vertex(4,5)
    graph.addVertex(v3)
    e2 = Edge(v1, v3, v3.EuclidDist(v1), True)
    graph.addEdge(e2)
    print("Real Print starts here ")
    graph.print_graph()
Beispiel #33
0
if 'C3NAVPROJECT' in os.environ:
    project = os.environ['C3NAVPROJECT']
elif len(sys.argv) > 1:
    project = sys.argv[1]
else:
    print('Please specify project: run.py <project> or environment variable C3NAVPROJECT')
    sys.exit(1)

if len(sys.argv) != 3:
    print('select language!')
    sys.exit(1)
lang = sys.argv[2]
print('translating into %s…' % lang)

data = Graph(project, auto_connect=False).data
rooms = list(data['rooms'].keys())
pois = list(data['pois'].keys())
superrooms = [room['superroom'] for room in data['rooms'].values() if 'superroom' in room]
roomgroups = list(sum((room.get('groups', []) for room in data['rooms'].values()), []))
roomgroups += [(':'+s) for s in roomgroups]
poigroups = list(sum((poi.get('groups', []) for poi in data['pois'].values()), []))
poigroups += [(':'+s) for s in poigroups]

for name in set(pois+roomgroups+rooms+superrooms+poigroups):
    data = json.load(open('projects/'+project+'/titles.json'))
    titles = data.get(name, {})

    if lang in titles:
        continue
    for l, t in titles.items():
Beispiel #34
0
class GraphTest(unittest.TestCase):
    def setUp(self):
        self.g = Graph()
        self.g.add_node("A")
        self.g.add_node("B")
        self.g.add_node("C")
        self.g.add_node("D")
        self.g.add_node("E")
        self.g.add_distance("A", "B", 5)
        self.g.add_distance("B", "C", 4)
        self.g.add_distance("C", "D", 8)
        self.g.add_distance("D", "C", 8)
        self.g.add_distance("D", "E", 6)
        self.g.add_distance("A", "D", 5)
        self.g.add_distance("C", "E", 2)
        self.g.add_distance("E", "B", 3)
        self.g.add_distance("A", "E", 7)

    def test_node_distance(self):
        self.assertEqual(5, self.g.distance("A", "B"))

    def test_near_to(self):
        self.assertTrue(self.g.near_to("B", "C"))

    def test_add_node(self):
        self.g.add_node("X")
        self.assertIn("X", self.g.nodes)

    def test_add_distance(self):
        self.g.add_distance("B", "A", 10)
        self.assertEqual(10, self.g.distance("B", "A"))
Beispiel #35
0
	def test_new_edge(self):
		graph = new Graph()

		node1 = 'prev'
		node2 = 'next'
		graph.add_edge(node1, node2, weight=1)
Beispiel #36
0
from classes import Graph

if 'C3NAVPROJECT' in os.environ:
    project = os.environ['C3NAVPROJECT']
elif len(sys.argv) > 1:
    project = sys.argv[1]
else:
    print(
        'Please specify project: run.py <project> or environment variable C3NAVPROJECT'
    )
    sys.exit(1)

starttime = time.time()

graph = Graph(project, auto_connect=False, load_wifi=True)

for sid in graph.wifi.sids:
    while True:
        print('')
        print(sid)
        f, axes = plt.subplots(graph.levels)

        vmin = graph.wifi.w_to_dbm(
            np.min(graph.wifi.matrix[:, :, :, graph.wifi.sid_ids[sid]]))
        vmax = graph.wifi.w_to_dbm(
            np.max(graph.wifi.matrix[:, :, :, graph.wifi.sid_ids[sid]]))
        for i, ax in enumerate(axes):
            ax.imshow(
                imread('static/img/levels/dev/level%d.jpg' %
                       i)[::graph.wifi.divide_by, ::graph.wifi.divide_by])
Beispiel #37
0
    project = os.environ['C3NAVPROJECT']
elif len(sys.argv) > 1:
    project = sys.argv[1]
else:
    print(
        'Please specify project: run.py <project> or environment variable C3NAVPROJECT'
    )
    sys.exit(1)

if len(sys.argv) != 3:
    print('select language!')
    sys.exit(1)
lang = sys.argv[2]
print('translating into %s…' % lang)

data = Graph(project, auto_connect=False).data
rooms = list(data['rooms'].keys())
pois = list(data['pois'].keys())
superrooms = [
    room['superroom'] for room in data['rooms'].values() if 'superroom' in room
]
roomgroups = list(
    sum((room.get('groups', []) for room in data['rooms'].values()), []))
roomgroups += [(':' + s) for s in roomgroups]
poigroups = list(
    sum((poi.get('groups', []) for poi in data['pois'].values()), []))
poigroups += [(':' + s) for s in poigroups]

for name in set(pois + roomgroups + rooms + superrooms + poigroups):
    data = json.load(open('projects/' + project + '/titles.json'))
    titles = data.get(name, {})
Beispiel #38
0
class ACO(object):
    def __init__(self, bins, items, population, evaporation, limit=10000):
        self.bins = bins
        self.items = items

        self.ants = []
        for i in range(population):
            self.ants.append(Ant())

        self.graph = Graph(len(bins), len(items))

        self.evaporation = evaporation
        self.limit = limit

        self.numOfEvaluations = 0
        self.ran = False
        self.runtime = 0
        self.bestRun = None
        self.avgFitness = []

    def run(self):
        """Runs a full ACO run."""
        self.ran = False
        self.bestFits = []
        self.avgFitness = []
        startTime = time()

        while self.numOfEvaluations < self.limit:
            self.explore()

        for ant in self.ants:
            if self.bestRun and ant.fitness < self.bestRun.fitness:
                self.bestRun = ant.copy()
            elif not self.bestRun:
                self.bestRun = ant.copy()

        self.ran = True
        self.runtime = time() - startTime

    def explore(self):
        """Create a route for all ants and evaporate the graph."""
        self.ants = [*map(self.createPath, self.ants)]
        best = None
        for ant in self.ants:
            ant.distributePheromones(self.graph)
        fitnesses = [ant.fitness for ant in self.ants]
        self.bestFits.append(min(fitnesses) / sum(self.items))
        self.avgFitness.append(sum(fitnesses) / len(fitnesses))
        self.graph.evaporate(self.evaporation)

    def createPath(self, ant):
        """Reset the bins and create a route for the given ant.
        
        :param ant: ant object
        :returns: ant with new path
        """
        for b in self.bins:
            b.empty()

        currentBin = 0
        ant.route = []
        for item in enumerate(self.items):
            currentBin, item = self.nextBin(currentBin, item)
            ant.route.append((currentBin, item))

        ant.fitness = self.getCurrentFitness()
        ant.bins = self.bins.copy()

        self.numOfEvaluations += 1

        return ant

    def nextBin(self, currentBin, item):
        """Get the index of the next bin to place the item in.
        
        :param currentBin: index of the current bin
        :param item: item weight
        :returns: next bin index 
        """
        column = self.graph.graph[currentBin][item[0]].tolist()
        total = sum(column)
        threshold = total * random()

        current = 0.0
        for index, weight in enumerate(column):
            if current + weight >= threshold:
                self.bins[index].addItem(item[1])
                return index, item[0]
            current += weight

    def getCurrentFitness(self):
        """Calculate the fitness of the current bin configuration.
        
        :returns: current fitness
        """
        maxWeight = self.bins[0].totalWeight
        minWeight = self.bins[0].totalWeight

        for b in self.bins:
            if b.totalWeight > maxWeight:
                maxWeight = b.totalWeight
            if b.totalWeight < minWeight:
                minWeight = b.totalWeight

        return maxWeight - minWeight
Beispiel #39
0
def map():
    graph = Graph(project, auto_connect=True)
    return render_template('map.html', levels=graph.get_by_levels(), name=graph.name)