Exemplo n.º 1
0
    def setUp(self):
        f = open('assets/data/map_data.json', 'r')
        decoded = json.loads(f.read())
        self.g = graph.Graph()
        self.g.build_nodes(decoded['metros'])
        self.g.build_edges(decoded['routes'])
        self.utils = GraphUtils()

        f = open('assets/data/test1_map_data.json', 'r')
        decoded = json.loads(f.read())
        self.gSmall = graph.Graph()
        self.gSmall.build_nodes(decoded['metros'])
        self.gSmall.build_edges(decoded['routes'])
Exemplo n.º 2
0
def grow_a_graph(G, filename):
    G = graph.Graph()
    with open(filename, 'r') as gfile:
        lines = gfile.readlines()
    verts = lines[0].strip().split()[0]
    contents = []
    for i in range(len(lines)):
        contents.append([int(n) for n in lines[i].strip().split()])
    print contents[0:10]

    vert_objs = []
    vert_objs.append(graph.Vertex(0))  #v0 used in BF
    print verts
    for i in range(1, int(verts) + 1):
        vert_objs.append(vertex.Vertex(i))

    j = 1  #current vertex (assumes the input file is sorted by tail vertex)
    for i in range(1, len(contents)):
        if contents[i][0] == vert_objs[j].v_id:
            vert_objs[j].addedge(
                edge.Edge(vert_objs[j], vert_objs[contents[i][1]],
                          int(contents[i][2]), int(contents[i][2])))

        else:
            j += 1
            vert_objs[j].addedge(
                edge.Edge(vert_objs[j], vert_objs[contents[i][1]],
                          int(contents[i][2]), int(contents[i][2])))
    return vert_objs
Exemplo n.º 3
0
def Johnson(infile):
    g = graph.Graph()
    vs = grow_a_graph(g, infile)
    v0 = vertex.Vertex(0)
    ix = 0
    for i in range(len(vs)):
        print ix
        ix += 1
        v0.addedge(edge.Edge(v0, vs[i], 0, 0))
    for e in v0.edges:
        print "v0 has edge to", e.v.v_id, " with len ", e.d
    vs = [v0] + vs[1:]

    for i in range(len(vs)):
        g.addvertices(vs[i])
    p_v = Bellman_Ford(g, vs[0])

    print p_v
    g.edges = g.edges[len(g.vertices[0].edges):]
    g.vertices = g.vertices[1:]  #remove artificial zero vertex
    gw = re_weigh(g, p_v)
    for e in gw.edges:
        print e[0].v_id, "->", e[1].v_id, "was", e[3], "now is", e[2]
    results = []
    for v in gw.vertices:
        gp = gw
        do_a_dijkstra(gp, v)
        gp = de_weigh(gp, p_v)
        results.append([v.value for v in gp.vertices])
    print results
    print min([min(x) for x in results])
Exemplo n.º 4
0
    def test_graph_add_vertex(self):
        """--- shall add one vertex to empty graph ---"""
        graph = gr.Graph()
        vertex = vx.Vertex("vertex_id", "vertex_value")

        graph.add_vertex(vertex)

        self.assertTrue(graph.vertices is not None)
        self.assertTrue(len(graph.vertices) == 1)
Exemplo n.º 5
0
 def _preprocess_map(self):
     # create the area map
     self.area_map = area_map.AreaMap(self.raw_map, self.pass_test)
     # create the influence map
     self.influence_map = influence_map.InfluenceMap(self.area_map)
     # create the graph
     self.graph = graph.Graph(self.area_map, self.influence_map)
     # create shortest path search
     self.shortest_path = pf_shortest_path.ShortestPathSearch(
         self.graph, self.area_map, self.precomputed_hops)
Exemplo n.º 6
0
def get_features(X, weight=1000):
    pixels = X
    g = graph.Graph(np.round(X))
    nunreachable = g.pocet_nedosazitelnych(0)
    ret = np.zeros(weight)

    if (nunreachable != 0):
        # visualize_matrix(X)
        ret += 0
    return ret
Exemplo n.º 7
0
def test_three_node_graph():
	g = graph.Graph()
	g.add_vertex('a')
	g.add_vertex('b')
	g.add_vertex('c')

	g.add_edge('a', 'b', '10')
	g.add_edge('a', 'c', '5')
	assert(g.get_vertex_count() == 3)
	assert(g.get_adjacent('a') == ['b','c'])
	assert(g.get_adjacent('b') == ['a'])
	assert(g.get_adjacent('c') == ['a'])
Exemplo n.º 8
0
 def testSave(self):
     self.utils.save_to_disk(self.g)
     f2 = open('assets/data/map_data_written.json', 'r')
     decoded = json.loads(f2.read())
     self.g2 = graph.Graph()
     self.g2.build_nodes(decoded['metros'])
     self.g2.build_edges(decoded['routes'])
     self.utils = GraphUtils()
     assert (self.utils.longest_flight(self.g2) == ('SYD', 'LAX', 12051))
     assert (self.utils.shortest_flight(self.g2) == ('NYC', 'WAS', 334))
     assert (self.utils.average_distance(self.g2) == 2300)
     assert self.utils.biggest_city(self.g2) == ('TYO', 34000000)
     assert self.utils.smallest_city(self.g2) == ('ESS', 589900)
Exemplo n.º 9
0
def test_all_paths():
	g = graph.Graph()
	g.add_vertex('a')
	g.add_vertex('b')
	g.add_vertex('c')
	g.add_vertex('d')
	g.add_vertex('e')

	g.add_edge('a', 'b', 10)
	g.add_edge('a', 'c', 5)
	g.add_edge('b', 'c', 15)
	g.add_edge('c', 'd', 4)
	g.add_edge('b', 'e', 20)
	print(g.find_all_paths('a', 'b'))
Exemplo n.º 10
0
def test_costs():
	g = graph.Graph()
	g.add_vertex('a')
	g.add_vertex('b')
	g.add_vertex('c')
	g.add_vertex('d')
	g.add_vertex('e')

	g.add_edge('a','b', 10)
	g.add_edge('a', 'c', 5)
	g.add_edge('c', 'd', 21)
	g.add_edge('b', 'e', 32)
	g.add_edge('d', 'b', 10)
	d1= { 'a':20,'b':10,'c':21, 'd':0, 'e':42  }
	assert(g.shortest_path('d') == d1)
Exemplo n.º 11
0
def test_graph():
	g = graph.Graph()
	g.add_vertex('a')
	g.add_vertex('b')
	g.add_vertex('c')
	g.add_vertex('d')
	g.add_vertex('e')

	g.add_edge('a', 'b', 10)
	g.add_edge('a', 'c', 5)
	g.add_edge('b', 'c', 15)
	g.add_edge('c', 'd', 4)
	g.add_edge('b', 'e', 20)
	assert(g.get_vertex_count()== 5)
	assert(g.get_edge_cost('a', 'b') == 10)
	assert(g.get_edge_cost('b', 'e') == 20)
Exemplo n.º 12
0
    def create_graph(self, exclusion_criterion=None):
        states = OrderedSet()
        transitions = []

        for trace in self.traces:
            for trans in trace.transitions:
                if exclusion_criterion is None or not exclusion_criterion.decide(
                        trans):
                    transitions.append(trans)

        # TODO maybe add only states that belong to a permitted transition
        for state in self.states:
            states.add(state)

        return graph.Graph(package_name=self.package_name,
                           states=states,
                           transitions=transitions,
                           home_state=self.home_state)
Exemplo n.º 13
0
def build_graph_from_vertices_edges(vertices, edges):
    g = graph.Graph()

    # 1. add all nodes and create mapping to 0 based index nodes
    vertex_ids = set([v.id for v in vertices])
    id_mapper = dict(zip(vertex_ids, range(len(vertex_ids))))
    for v in vertices:
        g.add_node(graph_types.Vertex(id_mapper[v.id], v.lat, v.lon))

    # 2. add all edges that are valid
    new_edges = [
        copy.deepcopy(e) for e in edges
        if e.s in vertex_ids and e.t in vertex_ids
    ]
    for e in new_edges:
        e.s = id_mapper[e.s]
        e.t = id_mapper[e.t]
        g.add_edge(e)

    return g
Exemplo n.º 14
0
def build_graph_from_osm(nodes, ways):

    assert isinstance(nodes, dict)
    assert isinstance(ways, list)

    g = graph.Graph()

    # 1. add all nodes and create mapping to 0 based index nodes
    node_ids = nodes.keys()
    id_mapper = dict(zip(node_ids, range(len(node_ids))))
    for n in nodes.values():
        g.add_node(graph_types.Vertex(id_mapper[n.osm_id], n.lat, n.lon))

    # 2. go through all ways and add edges accordingly
    for w in ways:
        for i in range(len(w.nodes) - 1):
            s_id, t_id = id_mapper[w.nodes[i]], id_mapper[w.nodes[i + 1]]
            s, t = g.vertices[s_id], g.vertices[t_id]
            length = geo_tools.distance(s.lat, s.lon, t.lat, t.lon)
            edge = graph_types.Edge(s_id, t_id, length, w.highway, w.max_speed,
                                    w.forward, w.backward, w.name)
            g.add_edge(edge)

    return g
Exemplo n.º 15
0
import graph.graph as g

# file = 'email-Eu-core'
file = 'com-amazon.ungraph'
graph = g.Graph(file)

# print(str(graph.neighbor_of_node(0)))
# print(str(graph.get_degree_of_node(0)))

# Analyzing
# degree_distribution = graph.get_degree_distribution()
# print('Degree Distribution <degree>:<probability> = ' + str(degree_distribution))
# clustering_coefficient = graph.get_clustering_coefficient()
# print('Clustering coefficient' + str(clustering_coefficient))


# degree_analyzer.plot_store_degree_distribution_log_log(file, degree_distribution)
# degree_analyzer.plot_store_degree_distribution(file, degree_distribution)
# clustering_analyzer.plot_store_clustering_coefficient_log_log(file, clustering_coefficient, node_degree)
# clustering_analyzer.plot_store_clustering_coefficient(file, clustering_coefficient, node_degree, )


print(str(graph.get_degree_correlation()))
graph.plot_store_degree_correlation()
Exemplo n.º 16
0
    for v in G.vertices:
        if v == root:
            continue
        v.value = float('inf')
        h.insert(v)
    while len(h.nodes) > 1:
        m = h.extractmin()
        ##Only works for directed graphs, otherwise would have to match
        for E in m.edges:
            if (E.v in h.nodes) and E.v.value > m.value + E.d:
                E.v.value = m.value + E.d
                h.check_parent(h.nodes.index(E.v))
        print ".",


g1 = graph.Graph()
g2 = graph.Graph()
vs = grow_a_graph(g1, "/home/apmechev/MOOCS/Algo2/s4/g1.txt")
#vs=grow_a_graph(g1,"test.txt")
g1.addvertices(vertex.Vertex(0))
for i in range(1, len(vs)):
    g1.addvertices(vs[i])

v0 = vertex.Vertex(0)
v1 = vertex.Vertex(1)
v2 = vertex.Vertex(2)
v3 = vertex.Vertex(3)
v4 = vertex.Vertex(4)
v5 = vertex.Vertex(5)
v6 = vertex.Vertex(6)
v7 = vertex.Vertex(7)
Exemplo n.º 17
0
def re_weigh(g, p_v):
    gp = graph.Graph()
    for e in g.edges:
        e[2] = e[3] + p_v[e[0].v_id] - p_v[e[1].v_id]
    return g
Exemplo n.º 18
0
from graph.interface_pb2 import InterfaceType
from icmplib import ping
from tcolorpy import tcolor


def exit_if_none(obj, msg):
    if obj is None:
        print(msg)
        sys.exit(0)


parser = argparse.ArgumentParser(description="Ping test midgress address reachability")
parser.add_argument("server", type=str, help="The server name to query for")
args = parser.parse_args()

g = graph.Graph("api.subspace.com:443")

# lookup server
s = g.get_server(args.server)
exit_if_none(s, f"Could not find server {args.server}")

p = g.get_pop(s.pop_id)
ifaces = g.list_interfaces_by_field(field="pop_bpf_id", value=str(s.pop_bpf_id))

print("\nTesting midgress reachability for:\n")
print(f"pop {p.name} {p.graph_id}")
print(f"svr {s.name} {s.guid} {s.pop_id} {s.pop_bpf_id}")

for iface in ifaces:

    if not iface.type == InterfaceType.TRANSIT:
Exemplo n.º 19
0
def test_empty_graph():
	g = graph.Graph()
	assert(g.get_vertex_count() == 0)
Exemplo n.º 20
0
 def test_graph_instantiation(self):
     """--- shall create valid graph instance ---"""
     graph = gr.Graph()
     self.assertTrue(graph.vertices is not None)
     self.assertTrue(graph.edges is not None)
Exemplo n.º 21
0
Arquivo: GA.py Projeto: hzfmax/ece457a
from graph import graph
'''
5 bits per gene:
    b0b1b2: directional movement
    b3: move up in z if 1
    b4: move down in zif 1
    if b3 == 0 and b4 == 0: stay on same level
    if b3 == 1 and b4 == 1: invalid gene, remove

generate N * M genes per chromosome (size of map)
'''

geneSet = " abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!.,"
target = "Hi, my name is Jake Si! I like apples."

test_map = graph.Graph()


class Chromosome:
    def __init__(self, gene, length, generation=0):
        self.gene = gene
        self.fitness = Chromosome.update_fitness(gene, length)
        self.generation = generation
        self.length = length

    def getGeneAtIndex(self, index):
        return int(self.gene[2 * index] + self.gene[2 * index + 1])

    def replaceGeneAtIndex(self, index, n):
        strN = str(n)
        if n < 10:
Exemplo n.º 22
0
def empty_graph():
    return graph.Graph()
Exemplo n.º 23
0
def show_recovered():
    filename = "recovered.png"
    graph = g.Graph()
    res = graph.graph_recovered()
    res.savefig(os.path.join(app.config["IMAGE"], filename))
    return render_template("image.html", filename=filename)
Exemplo n.º 24
0
def get_features(X, weight = 1000):
    pixels = X
    g = graph.Graph(np.round(X))
    unreachable = g.pozice_nedosazitelnych(0)
    
    return unreachable