def reverseGraph(graph): """ Retornar el reverso del grafo graph """ try: greverse = g.newGraph(size=g.numVertices(graph), directed=True, comparefunction=graph['comparefunction']) lstvert = g.vertices(graph) itervert = it.newIterator(lstvert) while it.hasNext(itervert): vert = it.next(itervert) g.insertVertex(greverse, vert) itervert = it.newIterator(lstvert) while it.hasNext(itervert): vert = it.next(itervert) lstadj = g.adjacents(graph, vert) iteradj = it.newIterator(lstadj) while it.hasNext(iteradj): adj = it.next(iteradj) g.addEdge(greverse, adj, vert) return greverse except Exception as exp: error.reraise(exp, 'scc:reverse')
def addEdge(analyzer, originPoint, destinationPoint, distance): edge = gr.getEdge(analyzer['connections'], originPoint, destinationPoint) # Se intenta crear un arco. Primero se verifica si existe if edge is None: gr.addEdge(analyzer['connections'], originPoint, destinationPoint, distance) return analyzer
def add_edges(self): edge_it = al_it.newIterator(self.connections_list) while al_it.hasNext(edge_it): temp = al_it.next(edge_it) new_edge = lt.getElement(temp, 1), lt.getElement(temp, 2) gp.addEdge(self.connections_map, *new_edge, self.haversine(*new_edge))
def addConnection_directed(analyzer, connection): origin = connection['\ufefforigin'] destination = connection['destination'] cable_id = connection['cable_name'] cable_lenght = DistanceHaversine(origin, destination, analyzer) verticeA = "<{}>-<{}>".format(origin, cable_id) verticeB = "<{}>-<{}>".format(destination, cable_id) containsA = gr.containsVertex(analyzer['connections_directed'], verticeA) containsB = gr.containsVertex(analyzer['connections_directed'], verticeB) if not containsA and not containsB: gr.insertVertex(analyzer['connections_directed'], verticeA) gr.insertVertex(analyzer['connections_directed'], verticeB) listilla = [origin, cable_id, verticeA] lt.addLast(analyzer['vertices'], listilla) mapa = analyzer['landing_points'] pareja = om.get(mapa, origin) valor = me.getValue(pareja) lista_cables = valor['cables'] lt.addLast(lista_cables, verticeA) gr.addEdge(analyzer['connections_directed'], verticeA, verticeB, cable_lenght)
def addConnection(analyzer, origin, destination, weight): """ Adiciona un arco entre dos vértices del grafo """ graph = analyzer['connections'] edge = gr.getEdge(graph, origin, destination) if edge is None: gr.addEdge(graph, origin, destination, weight) return analyzer
def addConnection(catalog, graph, origin, destination, weight): """ Adiciona un arco entre dos estaciones """ edge = gr.getEdge(catalog[graph], origin, destination) if edge is None: gr.addEdge(catalog[graph], origin, destination, weight) #gr.addEdge(catalog[graph], destination, origin, weight) return catalog
def existe_lp(catalog: dict, vertex: str) -> None: #TODO Aquí se debe crear un algoritmo que sea capaz de agregar arcos en vertices con un mismo lp # , se debe agregar un arco que vaya al siguiente vértice y un arco que se devuelva #Puede que la solución sea una función recursiva. vertices = gr.vertices(catalog["graph"]) for i in range(1, lt.size(vertices) + 1): elemento2 = lt.getElement(vertices, i) elemento = lt.getElement(vertices, i).split("-")[0] if (vertex.split("-")[0] == elemento and vertex != elemento2): gr.addEdge(catalog["graph"], vertex, elemento2, 0.1) add_info_cable(catalog, "", "<{}>-<{}>".format(vertex, elemento2))
def getRoute(self, area1, area2) -> Route: if not self.containsArea(area1): graph.insertVertex(self.Routes, area1) if not self.containsArea(area2): graph.insertVertex(self.Routes, area2) route = graph.getEdge(self.Routes, area1, area2) if route is None: route = Route() graph.addEdge(self.Routes, area1, area2, route) route = graph.getEdge(self.Routes, area1, area2) return route['weight']
def addTrip(chicagoAnalyzer, origin, destiny, tripTime, idTrip): """ Crea el arco(camino) entre los dos vertices(el de origen y el de destino) """ edge = gr.getEdge(chicagoAnalyzer['communityTrip'], origin, destiny) if edge is None: gr.addEdge(chicagoAnalyzer['communityTrip'], origin, destiny, tripTime) edge = gr.getEdge(chicagoAnalyzer['communityTrip'], origin, destiny) m.put(chicagoAnalyzer['tripID_edge'], idTrip, edge) return chicagoAnalyzer
def addArchConnections(analyzer, info): graph = analyzer["arches"] origin = info["origin"] destination = info["destination"] addArch(analyzer, origin) addArch(analyzer, destination) length = 0 if info["cable_length"] != "n.a.": final = ((info["cable_length"]).strip(" km")).split(",") if len(final) > 1: length = final[0] + final[1] gr.addEdge(graph, origin, destination, int(length))
def AddSameLanding_pointEdge(catalog): """ Unen los mismo landing_point """ # Obtener la lista de landing_point landing_point_list = mp.keySet(catalog['map_landing_points']) # Iterar sobre la lista de landing_point landing_point_iterator = it.newIterator(landing_point_list) while it.hasNext(landing_point_iterator): landing_point = it.next(landing_point_iterator) # Obtener el map de landing_point landing_point_mapEntry = mp.get(catalog['map_landing_points'], landing_point) landing_point_map = me.getValue(landing_point_mapEntry) # Obtener la lista de ciudades ciudades_list = mp.keySet(landing_point_map) # Iterar sobre ciudades i = 0 ciudades_iterator = it.newIterator(ciudades_list) while i < int(lt.size(ciudades_list)): ciudad = it.next(ciudades_iterator) # Crear la lista de vertex A vertexA_list = lt.newList('ARRAY_LIST') # Obtener la lista de vertex vertex_list = gr.vertices(catalog['graph_landing_points']) # iterar sobre la lista de vertices vertex_iterator = it.newIterator(vertex_list) while it.hasNext(vertex_iterator): vertex = it.next(vertex_iterator) # Separar el vertice vertex_separado = vertex.split("*") # Obtener la lista filtrada de vertices if vertex_separado[0] == landing_point and vertex_separado[ 1] == ciudad and not mp.contains( catalog['capitals'], vertex_separado[1]): lt.addLast(vertexA_list, vertex) # Iterar sobre vertexA_list vertexA_iterator = it.newIterator(vertexA_list) while it.hasNext(vertexA_iterator): vertexA = it.next(vertexA_iterator) # Iterar sobre vertexA_list vertexB_iterator = it.newIterator(vertexA_list) while it.hasNext(vertexB_iterator): vertexB = it.next(vertexB_iterator) if gr.getEdge(catalog['graph_landing_points'], vertexA, vertexB) == None: gr.addEdge(catalog['graph_landing_points'], vertexA, vertexB, float(0.1)) i += 1
def add_capital_edges(self, country): if country == "Colombia": country = country capital = self.get_capital_id_safe(country) cities = mp.get(self.point_country, country) if cities: city_it = ll_it.newIterator(cities['value']) while ll_it.hasNext(city_it): city = ll_it.next(city_it) if capital != city: if not gp.getEdge(self.connections_map, capital, city): gp.addEdge(self.connections_map, capital, city, self.haversine(capital, city)) gp.addEdge(self.connections_map, city, capital, self.haversine(capital, city))
def addConnection(analyzer, origin, destination, duration): """ Adiciona un arco entre dos estaciones """ edge = gr.getEdge(analyzer['graph'], origin, destination) if edge is not None: edge['pesos'] += duration edge['size'] += 1 edge['weight'] = round((edge['pesos'] / edge['size']), 2) else: gr.addEdge(analyzer['graph'], origin, destination, duration) edge = gr.getEdge(analyzer['graph'], origin, destination) edge['pesos'] += duration edge['size'] += 1 edge['weight'] = round((edge['pesos'] / edge['size']), 2)
def updateRoute(trip: dict, DataBase: dict) -> None: startId = int(trip["start station id"]) endId = int(trip["end station id"]) tripTime = int(trip["tripduration"]) edgeRoute = graph.getEdge(DataBase['graph'], startId, endId) if edgeRoute is None: weight = Structure.newWeight() graph.addEdge(DataBase['graph'], startId, endId, weight) edgeRoute = graph.getEdge(DataBase['graph'], startId, endId) weight = edge.weight(edgeRoute) weight['time'] = aveTime(weight, tripTime) weight['users'] += 1
def findNegativeCycle(graph, search): """ Identifica ciclos negativos en el grafo """ try: vertices = g.vertices(graph) for vert in lt.iterator(vertices): edge = map.get(search['edgeTo'], vert) if (edge is not None): edge = edge['value'] g.addEdge(search['spt'], e.either(edge), e.other(edge), e.weight(edge)) finder = c.DirectedCycle(search['spt']) search['cycle'] = not st.isEmpty(c.cycle(finder)) return search except Exception as exp: error.reraise(exp, 'bellman:pathto')
def addSameOrigin_directed(analyzer): info = om.valueSet(analyzer['landing_points']) for i in range(lt.size(info)): diccionario = lt.getElement(info, i) lista_cables = diccionario['cables'] for i in range(lt.size(lista_cables)): verticeA = lt.getElement(lista_cables, i) cont = 0 j = 1 while j + cont <= lt.size(lista_cables): verticeB = lt.getElement(lista_cables, j + cont) if verticeA != verticeB: gr.addEdge(analyzer['connections_directed'], verticeA, verticeB, 100) cont += 1
def graph_mst_prim(self, scan): graph = gp.newGraph(size=self.mas_grande[1]) distTo = scan['distTo'] edgeTo = scan['edgeTo'] dist_it = ll_it.newIterator(mp.keySet(distTo)) total_dist = 0 while ll_it.hasNext(dist_it): vertex = ll_it.next(dist_it) dist = mp.get(distTo, vertex)['value'] if dist: total_dist += dist edge = mp.get(edgeTo, vertex)['value'] if not gp.containsVertex(graph, edge['vertexA']): gp.insertVertex(graph, edge['vertexA']) if not gp.containsVertex(graph, edge['vertexB']): gp.insertVertex(graph, edge['vertexB']) gp.addEdge(graph, edge['vertexA'], edge['vertexB'], dist) return graph, total_dist
def addRouteConnections(analyzer, info): """ Por cada vertice (cada estacion) se recorre la lista de rutas servidas en dicha estación y se crean arcos entre ellas para representar el cambio de ruta que se puede realizar en una estación. """ grafo = analyzer["Arcos"] llegada = info["destination"] origen = info["origin"] addStop(analyzer, origen) addStop(analyzer, llegada) distancia = 0 if info["cable_length"] != "n.a.": final = ((info["cable_length"]).strip(" km")).split(",") if len(final) > 1: distancia = final[0] + final[1] addEdge(grafo, origen, llegada, int(distancia))
def crear_conexión(catalog: dict, linea: OrderedDict) -> None: vertexA = "<{}>-<{}>".format(linea["origin"], linea["cable_id"]) vertexB = "<{}>-<{}>".format(linea["destination"], linea["cable_id"]) latA = float( me.getValue(mp.get(catalog["ldp"], linea["origin"]))["latitude"]) lonA = float( me.getValue(mp.get(catalog["ldp"], linea["origin"]))["longitude"]) lonB = float( me.getValue(mp.get(catalog["ldp"], linea["destination"]))["longitude"]) latB = float( me.getValue(mp.get(catalog["ldp"], linea["destination"]))["latitude"]) peso = haversine(lonA, latA, lonB, latB) gr.insertVertex(catalog["graph"], vertexA) existe_lp(catalog, vertexA) gr.insertVertex(catalog["graph"], vertexB) existe_lp(catalog, vertexA) gr.addEdge(catalog["graph"], vertexA, vertexB, peso) add_info_cable(catalog, catalog["cable_name"], catalog["cable_id"], catalog["cable_length"], catalog["cable_rfs"], catalog["owners"], catalog["capacityTBPS"])
def addCountriestoCapitalCity(analyzer): vertices = analyzer['vertices'] map_landing = analyzer['landing_points'] for i in range(lt.size(vertices)): parejaA = lt.getElement(vertices, i) origenA = parejaA[0] vertice = parejaA[2] pareja = om.get(map_landing, origenA) info = me.getValue(pareja) pais = info['country'] contains = gr.containsVertex(analyzer['connections'], pais) if not contains: gr.insertVertex(analyzer['connections'], pais) gr.addEdge(analyzer['connections'], pais, vertice) lista_add = analyzer['vertices'] lt.addLast(lista_add, pais) if contains: gr.addEdge(analyzer['connections'], pais, vertice)
def getTargetEdge(trip: dict, DataBase: dict) -> edge: startId = int(trip["start station id"]) endId = int(trip["end station id"]) target = selectTarget(trip) if not (map.contains(DataBase['target'], target)): targetGraph = Structure.newTargetGraph() map.put(DataBase['target'], target, targetGraph) targetGraph = mapentry.getValue(map.get(DataBase['target'], target)) if not (graph.containsVertex(targetGraph, startId)): graph.insertVertex(targetGraph, startId) if not (graph.containsVertex(targetGraph, endId)): graph.insertVertex(targetGraph, endId) edgeRoute = graph.getEdge(targetGraph, startId, endId) if edgeRoute is None: graph.addEdge(targetGraph, startId, endId, 0) edgeRoute = graph.getEdge(targetGraph, startId, endId) return edgeRoute
def graph(): graph = g.newGraph(size=12, directed=True, comparefunction=compareVertices) g.insertVertex(graph, 'A1') g.insertVertex(graph, 'A2') g.insertVertex(graph, 'A3') g.insertVertex(graph, 'A4') g.insertVertex(graph, 'B1') g.insertVertex(graph, 'B2') g.insertVertex(graph, 'B3') g.insertVertex(graph, 'C1') g.insertVertex(graph, 'C2') g.insertVertex(graph, 'C3') g.insertVertex(graph, 'C4') g.insertVertex(graph, 'C5') g.addEdge(graph, 'A1', 'A2') g.addEdge(graph, 'A2', 'A3') g.addEdge(graph, 'A3', 'A2') g.addEdge(graph, 'A2', 'A1') g.addEdge(graph, 'A3', 'A4') g.addEdge(graph, 'A4', 'A3') g.addEdge(graph, 'C1', 'C5') g.addEdge(graph, 'C1', 'C2') g.addEdge(graph, 'C2', 'C3') g.addEdge(graph, 'C5', 'C2') g.addEdge(graph, 'C3', 'C4') g.addEdge(graph, 'C4', 'C1') g.addEdge(graph, 'B1', 'B2') g.addEdge(graph, 'B2', 'B3') g.addEdge(graph, 'B3', 'B1') g.addEdge(graph, 'B2', 'B1') g.addEdge(graph, 'A2', 'C1') g.addEdge(graph, 'C3', 'A4') g.addEdge(graph, 'C5', 'B2') g.addEdge(graph, 'B3', 'C2') return graph
def AddEdges(catalog): """ Agrega el arco entre 2 vertex """ # Obtener la lista de origen origin_keys_list = mp.keySet(catalog['map_connections']) # Iterar sobre la lista de origen origin_keys_iterator = it.newIterator(origin_keys_list) while it.hasNext(origin_keys_iterator): origin = it.next(origin_keys_iterator) # Obtener la tabla de hash de destination destination_map_Entry = mp.get(catalog['map_connections'], origin) destination_map = me.getValue(destination_map_Entry) # Obtener la lista destination destination_keys_list = mp.keySet(destination_map) # Iterar sobra la lista de destination destination_keys_iterator = it.newIterator(destination_keys_list) while it.hasNext(destination_keys_iterator): destination = it.next(destination_keys_iterator) # Obtener la tabla de cables cable_map_Entry = mp.get(destination_map, destination) cable_map = me.getValue(cable_map_Entry) # Obtener la lista de cables cable_keys_list = mp.keySet(cable_map) # Iterar sobre la lista de cables cable_keys_iterator = it.newIterator(cable_keys_list) while it.hasNext(cable_keys_iterator): cable = it.next(cable_keys_iterator) # Obtener los vertex vertex_list = gr.vertices(catalog['graph_landing_points']) # Vertex A vertexA_list = lt.newList('ARRAY_LIST') # Vertex B vertexB_list = lt.newList('ARRAY_LIST') # Vertex A capital vertexAcapital_list = lt.newList('ARRAY_LIST') # Vertex B capital vertexBcapital_list = lt.newList('ARRAY_LIST') # iterar sobre la lista de vertex vertex_list_iterator = it.newIterator(vertex_list) while it.hasNext(vertex_list_iterator): vertex = it.next(vertex_list_iterator) # Separar el vertex vertex_separado = vertex.split("*") # Ver si es origin o destination if vertex_separado[0] == origin and vertex_separado[ 2] == cable and not (mp.contains( catalog['capitals'], vertex_separado[1])): lt.addLast(vertexA_list, vertex) elif vertex_separado[0] == destination and vertex_separado[ 2] == cable and not (mp.contains( catalog['capitals'], vertex_separado[1])): lt.addLast(vertexB_list, vertex) if vertex_separado[0] == origin and mp.contains( catalog['capitals'], vertex_separado[1]): lt.addLast(vertexAcapital_list, vertex) elif vertex_separado[0] == origin and not (mp.contains( catalog['capitals'], vertex_separado[1])): lt.addLast(vertexBcapital_list, vertex) weightNocapital = weightConnection(catalog, origin, destination) # Iterar sobre list Vertex A para unir vertexA_iterator = it.newIterator(vertexA_list) while it.hasNext(vertexA_iterator): vertexA = it.next(vertexA_iterator) # Iterar sobre list Vertex B para unir vertexB_iterator = it.newIterator(vertexB_list) while it.hasNext(vertexB_iterator): vertexB = it.next(vertexB_iterator) gr.addEdge(catalog['graph_landing_points'], vertexA, vertexB, weightNocapital) # Iterar sobre list vertex A para unir vertexAcapital_iterator = it.newIterator(vertexAcapital_list) while it.hasNext(vertexAcapital_iterator): vertexAcapital = it.next(vertexAcapital_iterator) # Iterar sobre list vertex B para unir vertexBcapital_iterator = it.newIterator( vertexBcapital_list) while it.hasNext(vertexBcapital_iterator): vertexBcapital = it.next(vertexBcapital_iterator) gr.addEdge(catalog['graph_landing_points'], vertexAcapital, vertexBcapital, 585.31)
def graph(): graph = g.newGraph(size=12, directed=True, comparefunction=compareVertices) g.insertVertex(graph, 'Pedro') g.insertVertex(graph, 'Maria') g.insertVertex(graph, 'Carol') g.insertVertex(graph, 'Laura') g.insertVertex(graph, 'Felipe') g.insertVertex(graph, 'Jose') g.insertVertex(graph, 'Martin') g.insertVertex(graph, 'Camila') g.insertVertex(graph, 'Gloria') g.insertVertex(graph, 'Luz') g.insertVertex(graph, 'Tere') g.insertVertex(graph, 'Susana') g.addEdge(graph, 'Pedro', 'Jose') g.addEdge(graph, 'Jose', 'Felipe') g.addEdge(graph, 'Felipe', 'Laura') g.addEdge(graph, 'Laura', 'Carol') g.addEdge(graph, 'Carol', 'Maria') g.addEdge(graph, 'Maria', 'Pedro') g.addEdge(graph, 'Camila', 'Jose') g.addEdge(graph, 'Camila', 'Martin') g.addEdge(graph, 'Martin', 'Gloria') g.addEdge(graph, 'Gloria', 'Camila') g.addEdge(graph, 'Gloria', 'Luz') g.addEdge(graph, 'Luz', 'Tere') g.addEdge(graph, 'Tere', 'Susana') g.addEdge(graph, 'Susana', 'Luz') return graph
def addConnection(catalog, origin, destination, distance): edge = gr.getEdge(catalog['connections'], origin, destination) if edge is None: gr.addEdge(catalog['connections'], origin, destination, distance)
def graph(): graph = g.newGraph(size=10, comparefunction=compareVertices) g.insertVertex(graph, 'Bogota') g.insertVertex(graph, 'Yopal') g.insertVertex(graph, 'Cali') g.insertVertex(graph, 'Medellin') g.insertVertex(graph, 'Pasto') g.insertVertex(graph, 'Barranquilla') g.insertVertex(graph, 'Manizales') g.addEdge(graph, 'Bogota', 'Yopal') g.addEdge(graph, 'Bogota', 'Medellin') g.addEdge(graph, 'Bogota', 'Pasto') g.addEdge(graph, 'Bogota', 'Cali') g.addEdge(graph, 'Yopal', 'Medellin') g.addEdge(graph, 'Medellin', 'Pasto') g.addEdge(graph, 'Cali', 'Pasto') g.addEdge(graph, 'Cali', 'Barranquilla') g.addEdge(graph, 'Barranquilla', 'Manizales') g.addEdge(graph, 'Pasto', 'Manizales') return graph
from DISClib.ADT import graph as g from DISClib.DataStructures import listiterator # Hacer un metodo que imprima un grafo no dirigido de esta forma: # Vertice 1: Vertice-adyacente 1, Vertice-adyacente 2 # Vertice 2: Vertice-adyacente 1, Vertice-adyacente 2 # Vertice 3: Vertice-adyacente 1, Vertice-adyacente 2 def comparefunction(searchname, element): if (searchname == element['key']): return 0 elif (searchname < element['key']): return -1 return 1 grafo = g.newGraph(datastructure='ADJ_LIST', directed=False, size=14000, comparefunction=comparefunction) g.insertVertex(grafo, "1") g.insertVertex(grafo, "2") g.insertVertex(grafo, "3") g.addEdge(grafo, "1", "2") def toString(grafo): pass
def test_insertEdges(graph): g.insertVertex(graph, 'Bogota') g.insertVertex(graph, 'Yopal') g.insertVertex(graph, 'Cali') g.insertVertex(graph, 'Medellin') g.insertVertex(graph, 'Pasto') g.insertVertex(graph, 'Barranquilla') g.insertVertex(graph, 'Manizales') g.addEdge(graph, 'Bogota', 'Yopal') g.addEdge(graph, 'Bogota', 'Medellin') g.addEdge(graph, 'Bogota', 'Pasto') g.addEdge(graph, 'Bogota', 'Cali') g.addEdge(graph, 'Yopal', 'Medellin') g.addEdge(graph, 'Medellin', 'Pasto') g.addEdge(graph, 'Cali', 'Pasto') g.addEdge(graph, 'Cali', 'Barranquilla') g.addEdge(graph, 'Barranquilla', 'Manizales') g.addEdge(graph, 'Pasto', 'Manizales') assert g.numVertex(graph) == 7 assert g.numEdges(graph) == 10
from DISClib.Algorithms.Graphs import dfs from DISClib.ADT import list as lt #Ejemplo uso de DFS def comparefunction(searchname, element): if (searchname == element['key']): return 0 elif (searchname < element['key']): return -1 return 1 grafo = gr.newGraph(datastructure='ADJ_LIST', directed=False, size=14000, comparefunction=comparefunction) #DFS gr.insertVertex(grafo, "a") gr.insertVertex(grafo, "b") gr.insertVertex(grafo, "c") gr.addEdge(grafo, "a", "b") gr.addEdge(grafo, "c", "b") search = dfs.DepthFirstSearch(grafo, "b") path = dfs.pathTo(search, "a") for v in lt.iterator(path): print(v)
def graph(): graph = g.newGraph(size=7, comparefunction=compareVertices, directed=True) g.insertVertex(graph, 'Bogota') g.insertVertex(graph, 'Duitama') g.insertVertex(graph, 'Armenia') g.insertVertex(graph, 'Honda') g.insertVertex(graph, 'Espinal') g.insertVertex(graph, 'Florencia') g.insertVertex(graph, 'Cali') g.addEdge(graph, 'Bogota', 'Duitama', 3.5) g.addEdge(graph, 'Bogota', 'Honda', 3) g.addEdge(graph, 'Bogota', 'Espinal', 4.5) g.addEdge(graph, 'Duitama', 'Armenia', 1) g.addEdge(graph, 'Honda', 'Duitama', 1) g.addEdge(graph, 'Honda', 'Espinal', 1) g.addEdge(graph, 'Honda', 'Armenia', 2.5) g.addEdge(graph, 'Honda', 'Florencia', 5.5) g.addEdge(graph, 'Espinal', 'Florencia', 2.4) g.addEdge(graph, 'Honda', 'Cali', 6) g.addEdge(graph, 'Florencia', 'Cali', 1) g.addEdge(graph, 'Armenia', 'Cali', 4) return graph