def req3(catalog, pais_a, pais_b): #sacar capital a partir de país entry1 = mp.get(catalog['map_countries'], pais_a) vert1 = me.getValue(entry1)['CapitalName'] entry2 = mp.get(catalog['map_countries'], pais_b) vert2 = me.getValue(entry2)['CapitalName'] grafo = catalog['graph_landing_points'] lista_ruta = lt.newList() vertices = gr.vertices(catalog['graph_landing_points']) landing_point_a = None landing_point_b = None for vert in lt.iterator(vertices): vertexa = vert.split(sep='*') if vertexa[1] == vert1: landing_point_a = vert elif vertexa[1] == vert2: landing_point_b = vert for vert in lt.iterator(vertices): vertexb = vert.split(sep='*') if vertexb[1] == vert2: landing_point_b = vert elif vertexb[1] == vert1: landing_point_a = vert MST = dijsktra.Dijkstra(grafo, landing_point_a) distancia_total = dijsktra.distTo(MST, landing_point_b) camino_pila = dijsktra.pathTo(MST, landing_point_b) iterador = it.newIterator(camino_pila) while it.hasNext(iterador): ruta = st.pop(camino_pila) lt.addLast(lista_ruta, ruta) return distancia_total, lista_ruta
def connectCLP(catalog): i = 0 mapalp = catalog['info_lp'] grafo = catalog['connections'] listaCLP = catalog['nodos_capitales'] tamano = lt.size(listaCLP) mapa_paises = catalog['countries'] while i < tamano: nodo_capital = lt.getElement(listaCLP, i) pre = nodo_capital.split("*") pais = pre[(len(pre) - 1)] entry_pais = mp.get(mapa_paises, pais) if entry_pais == None: print(pais) minidic = me.getValue(entry_pais) loc_cap = ubicar_capital(minidic) lista = minidic['nodos_asoc'] lta_vacia = lt.isEmpty(lista) if lta_vacia == False: j = 0 tamano2 = lt.size(lista) while j < tamano2: nodo_pais = lt.getElement(lista, j) pre2 = nodo_pais.split("-") lp = pre2[0] loc2 = ubicarLp(lp, mapalp) dist = hs.haversine(loc_cap, loc2) addEdges(grafo, nodo_capital, nodo_pais, dist) j += 1 else: lista_vertices = gr.vertices(grafo) nodocercano = findNearest(lista_vertices, loc_cap, mapalp) if nodocercano[1] != None: addEdges(grafo, nodo_capital, nodocercano[0], nodocercano[1]) i += 1
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 req1(catalog, nombre1, nombre2): kosaraju = scc.KosarajuSCC(catalog['graph_landing_points']) vertices = gr.vertices(catalog['graph_landing_points']) vert1 = None vert2 = None for vertice in lt.iterator(vertices): if vertice.split(sep='*')[1] == nombre1: vert1 = vertice elif vertice.split(sep='*')[1] == nombre2: vert2 = vertice for vertice in lt.iterator(vertices): if vertice.split(sep='*')[1] == nombre2: vert2 = vertice elif vertice.split(sep='*')[1] == nombre1: vert1 = vertice vertice_x = lt.getElement(vertices, 0) num_componentes_conectados = scc.sccCount(catalog['graph_landing_points'], kosaraju, vertice_x) #mismo_cluster = scc.stronglyConnected(kosaraju, vert1, vert2) #if mismo_cluster: # respuesta = 'Los dos landing points están en el mismo clúster' #else: # respuesta = 'Los dos landing points no están en el mismo clúster' return num_componentes_conectados #, respuesta
def sameLP(catalog): ver=gr.vertices(catalog['connections']) verit=lt.iterator(ver) for v in verit: for ve in verit: p=ve.split('_') if p[0] in v: addConnection(catalog,v,ve,0.1)
def addVertex(catalog, vertexname, notcapital): if not gr.containsVertex(catalog['connections'], vertexname): preexistingvertices = gr.vertices(catalog['connections']) gr.insertVertex(catalog['connections'], vertexname) if notcapital: for vertex in lt.iterator(preexistingvertices): if vertexname.split('*')[0] == vertex.split('*')[0]: addEdge(catalog, vertexname, vertex, 0.1) preexistingvertices.clear()
def Requerimiento2(analyzer): vertic = gr.vertices(analyzer['connections']) listaR = lt.newList('SINGLE_LINKED') iterator = it.newIterator(vertic) while it.hasNext(iterator): posi = it.next(iterator) vert_adya = gr.degree(analyzer['connections'], posi) lt.addLast(listaR, (posi, vert_adya)) res = sorting2(listaR, 10, cmpfunction_merge) return res
def req2(catalog): maxvert = None maxdeg = 0 lista_vertices = gr.vertices(catalog['graph_landing_points']) for vert in lt.iterator(lista_vertices): degree = gr.degree(catalog['graph_landing_points'], vert) if (degree > maxdeg): maxvert = vert maxdeg = degree return maxvert, maxdeg
def compareLpUserLpGraph(analyzer, landing_point1): """ A partir de los landing points que ingresa el usuario, encuentra esos landing_point_id en los vértices y devuelve cada uno. Parámetros: analyzer: el catágologo donde está guardado todo. landing_point1: el landing point A ingresado por el usuario. Retorna: un string, que es el vértice correspondiente a landing_point1.. """ mapa = analyzer['connections'] lista_llaves = gr.vertices(mapa) size = lt.size(lista_llaves) informacion = analyzer['info_lp'] lista_lp = mp.keySet(informacion) tamaño_lp = lt.size(lista_lp) lpnumber = None i = 1 centinelaA = False while i < tamaño_lp and centinelaA == False: elemento = lt.getElement(lista_lp, i) pareja = mp.get(informacion, elemento) valor = me.getValue(pareja) ciudad_pais = valor['lp']['name'] cadena = ciudad_pais.split(',') nombre = cadena[0] if landing_point1 == nombre: #print('entré') lpnumber = elemento centinelaA = True i += 1 j = 1 centinelaB = False while j < size or centinelaB == False: cada_elemento = lt.getElement(lista_llaves, j) if cada_elemento[0] == '1' or cada_elemento[0] == '2' or cada_elemento[ 0] == '3' or cada_elemento[0] == '4' or cada_elemento[ 0] == '5' or cada_elemento[0] == '6' or cada_elemento[ 0] == '7' or cada_elemento[0] == '8' or cada_elemento[ 0] == '9' or cada_elemento[0] == '0': lp = cada_elemento.split('-')[0] if lp == lpnumber: centinelaB = True lpA = cada_elemento j += 1 return lpA
def initSearch(graph, source): """ Inicializa la estructura de busqueda y deja todos los arcos en infinito. Se inserta en la cola el vertice source Args: graph: El grafo a examinar source: El vertice fuente Returns: Estructura de busqueda inicializada Raises: Exception """ try: search = { 'source': source, 'edgeTo': None, 'distTo': None, 'qvertex': None, 'onQ': None, 'cost': 0, 'spt': None, 'cycle': False } search['edgeTo'] = map.newMap(numelements=g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction']) search['distTo'] = map.newMap(numelements=g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction']) search['onQ'] = map.newMap(numelements=g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction']) search['spt'] = g.newGraph(size=g.numVertices(graph), directed=True, comparefunction=graph['comparefunction']) vertices = g.vertices(graph) for vert in lt.iterator(vertices): map.put(search['distTo'], vert, math.inf) map.put(search['onQ'], vert, False) g.insertVertex(search['spt'], vert) newq = q.newQueue() search['qvertex'] = newq return search except Exception as exp: error.reraise(exp, 'bellman:init')
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 req4(catalog): grafo = catalog['graph_landing_points'] vertices_grafo = gr.vertices(grafo) vertice1 = lt.getElement(vertices_grafo, 0) MST = dijsktra.Dijkstra(grafo, vertice1) vertice2 = lt.getElement(vertices_grafo, (lt.size(vertices_grafo) - 1)) num_nodos = gr.numVertices(MST) #para hallar costo total hacer un dist to con vertice inicial y final distancia_total = dijsktra.distTo(MST, vertice2) return num_nodos, distancia_total
def prim_max_dist_vertex(self, graph): root = self.mas_grande[2] search = dij.Dijkstra(graph, root) vertex_it = ll_it.newIterator(gp.vertices(graph)) maximum = 0, 0 while ll_it.hasNext(vertex_it): vertex = ll_it.next(vertex_it) dist = dij.distTo(search, vertex) if dist != float('inf'): if dist > maximum[1]: maximum = vertex, dist return maximum
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 req_2(self): respuesta = lt.newList(datastructure='ARRAY_LIST') vertices = gp.vertices(self.connections_map) vertex_it = ll_it.newIterator(vertices) while ll_it.hasNext(vertex_it): vertex = ll_it.next(vertex_it) name = self.id_to_fullname(vertex) edges = gp.degree(self.connections_map, vertex) lt.addLast(respuesta, [name, vertex, edges]) mergesort.sort(respuesta, self.req_2_cmp_func) graphing_helper(self).graph_req_2(respuesta) respuesta = "\n".join([ "{} ({}): {} conexiones".format(*t) for t in respuesta['elements'] ]) return respuesta
def samelp(grafo): list_vert = gr.vertices(grafo) i = 0 tamano = lt.size(list_vert) while i < tamano: elemento = lt.getElement(list_vert, i) corte = elemento.split('-') lp = corte[0] j = 0 k = 0 while j < tamano: elemento2 = lt.getElement(list_vert, j) if elemento2 != elemento and (lp in elemento2): addEdges(grafo, elemento, elemento2, .100) j += 1 i += 1
def initSearch(graph): """ Inicializa la estructura de busqueda y deja todos los arcos en infinito. Se inserta en la cola el vertice source Args: graph: El grafo a examinar source: El vertice fuente Returns: Estructura de busqueda inicializada Raises: Exception """ try: search = { 'edgeTo': None, 'distTo': None, 'marked': None, 'pq': None, 'mst': None } search['edgeTo'] = map.newMap(numelements=g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction']) search['distTo'] = map.newMap(numelements=g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction']) search['marked'] = map.newMap(numelements=g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction']) vertices = g.vertices(graph) for vert in lt.iterator(vertices): map.put(search['distTo'], vert, math.inf) map.put(search['marked'], vert, False) search['pq'] = pq.newIndexMinPQ(cmpfunction=graph['comparefunction']) search['mst'] = q.newQueue() return search except Exception as exp: error.reraise(exp, 'bellman:init')
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 initStructures(graph): """ Args: graph: El grafo a examinar source: El vertice fuente Returns: Estructura de busqueda inicializada Raises: Exception """ try: search = { 'edgeTo': None, 'marked': None, 'onStack': None, 'cycle': None } search['edgeTo'] = map.newMap(numelements=g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction'] ) search['marked'] = map.newMap(numelements=g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction']) search['onStack'] = map.newMap(numelements=g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction'] ) search['cycle'] = st.newStack() vertices = g.vertices(graph) for vert in lt.iterator(vertices): map.put(search['marked'], vert, False) map.put(search['onStack'], vert, False) return search except Exception as exp: error.reraise(exp, 'cycle:init')
def initSearch(graph, source): """ Inicializa la estructura de busqueda y deja todos los arcos en infinito. Se inserta en la cola indexada el vertice source Args: graph: El grafo a examinar source: El vertice fuente Returns: Estructura de busqueda inicializada Raises: Exception """ try: search = { 'source': source, 'visited': None, 'iminpq': None } search['visited'] = map.newMap(numelements=g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction'] ) vertices = g.vertices(graph) itvertices = it.newIterator(vertices) while (it.hasNext(itvertices)): vert = it.next(itvertices) map.put(search['visited'], vert, {'marked': False, 'edgeTo': None, 'distTo': math.inf} ) map.put(search['visited'], source, {'marked': True, 'edgeTo': None, 'distTo': 0} ) pq = iminpq.newIndexMinPQ( cmpfunction=graph['comparefunction'] ) search['iminpq'] = pq iminpq.insert(search['iminpq'], source, 0) return search except Exception as exp: error.reraise(exp, 'dks:init')
def edgesMST(graph, search): """ Args: search: La estructura de busqueda vertex: El vertice de destino Returns: Una pila con el camino entre source y vertex Raises: Exception """ try: vertices = g.vertices(graph) for vert in lt.iterator(vertices): e = map.get(search['edgeTo'], vert) if (e is not None): q.enqueue(search['mst'], e['value']) return search except Exception as exp: error.reraise(exp, 'bellman:pathto')
def PrimMST(graph): """ Implementa el algoritmo de Prim Args: graph: El grafo de busqueda Returns: La estructura search con los MST Raises: Exception """ try: search = initSearch(graph) vertices = g.vertices(graph) for vert in lt.iterator(vertices): if not map.get(search['marked'], vert)['value']: prim(graph, search, vert) return search except Exception as exp: error.reraise(exp, 'prim:PrimMST')
def cluster_mas_grande(self): tamaños = lt.newList(datastructure="ARRAY_LIST") ref = lt.newList(datastructure='ARRAY_LIST') for i in range(self.cluster_number): lt.addLast(tamaños, 0) lt.addLast(ref, 0) vertices = gp.vertices(self.connections_map) vertex_it = ll_it.newIterator(vertices) while ll_it.hasNext(vertex_it): vertex = ll_it.next(vertex_it) cluster = self.vertex_cluster(vertex) new_value = lt.getElement(tamaños, cluster) + 1 lt.changeInfo(tamaños, cluster, new_value) if not lt.getElement(ref, cluster): lt.changeInfo(ref, cluster, vertex) maximo = 0, 0 for i in range(1, self.cluster_number + 1): if maximo[1] < lt.getElement(tamaños, i): maximo = i, lt.getElement(tamaños, i) self.mas_grande = *maximo, lt.getElement(ref, maximo[0])
def DepthFirstOrder(graph): try: search = { 'marked': None, 'pre': None, 'post': None, 'reversepost': None } search['pre'] = queue.newQueue() search['post'] = queue.newQueue() search['reversepost'] = stack.newStack() search['marked'] = map.newMap(numelements=g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction']) lstvert = g.vertices(graph) for vertex in lt.iterator(lstvert): if not (map.contains(search['marked'], vertex)): dfsVertex(graph, search, vertex) return search except Exception as exp: error.reraise(exp, 'dfo:DFO')
def conf(catalog): it=lt.iterator(catalog['reqc']) lpit=mp.keySet(catalog['landingpoints']) lpit1=lt.iterator(lpit) ver=gr.vertices(catalog['connections']) verit=lt.iterator(ver) for i in it: cll=mp.get(catalog['countries'],i)['value'] mayor=float('inf') refmayor='' if not gr.containsVertex(catalog['connections'],i): for lp in lpit1: lpinfo=mp.get(catalog['landingpoints'],lp)['value'] distance=extractDistance((cll['latitude'],cll['longitude']),(lpinfo['latitude'],lpinfo['longitude'])) if distance < mayor: mayor=distance refmayor=lp addLandingpointid(catalog,i) for v in verit: if refmayor in v: addConnection(catalog, v, i, mayor) addConnection(catalog,i, v, mayor)
def DirectedCycle(graph): """ Detecta ciclos en un grafo dirigido Args: graph: El grafo de busqueda Returns: El ciclo si existe Raises: Exception """ try: search = initStructures(graph) vertices = g.vertices(graph) for vert in lt.iterator(vertices): if (not map.get(search['marked'], vert)['value']): dfs(graph, search, vert) return search except Exception as exp: error.reraise(exp, 'directedcycle')
def req5(catalog, nombre_landing_point): grafo = catalog['graph_landing_points'] #paises = mp.keySet(catalog['map_countries']) lista_vertices = gr.vertices(catalog['graph_landing_points']) lista_ciudades_afectadas = lt.newList(datastructure='ARRAY_LIST') tabla_landing_points = catalog['map_landing_points'] #llaves_landing_points = mp.keySet(tabla_landing_points) lista_numvertice = lt.newList(datastructure='ARRAY_LIST') lista_paises_afectados = lt.newList(datastructure='ARRAY_LIST') lista_tablas = lt.newList(datastructure='ARRAY_LIST') vertice = None for vert in lt.iterator(lista_vertices): if nombre_landing_point == vert.split(sep='*')[1]: vertice = vert paises_afectados = gr.adjacents(grafo, vertice) for vertices in lt.iterator(paises_afectados): if (int( lt.isPresent(lista_ciudades_afectadas, vertices.split(sep='*')[1]))) == 0: lt.addLast(lista_ciudades_afectadas, vertices.split(sep='*')[1]) lt.addLast(lista_numvertice, vertices.split(sep='*')[0]) for numvertices in lt.iterator(lista_numvertice): entry1 = mp.get(tabla_landing_points, numvertices) tabla1 = me.getValue(entry1) valores = mp.valueSet(tabla1) values_iterator = it.newIterator(valores) elemento = it.next(values_iterator) ciudades_elemento = elemento['name'].split(sep=',') for ciudades in lt.iterator(lista_ciudades_afectadas): if ciudades in ciudades_elemento: pais = ciudades_elemento[-1] if (int( lt.isPresent(lista_paises_afectados, pais))) == 0: lt.addLast(lista_paises_afectados, pais) return lt.size(lista_paises_afectados), lista_paises_afectados['elements']
def findInterLandingPoints(analyzer): total = 0 iterator = lli.newIterator(gr.vertices(analyzer["arches"])) vList = lt.newList() while lli.hasNext(iterator): vertex = lli.next(iterator) inDeg = gr.indegree(analyzer["arches"], vertex) outDeg = gr.outdegree(analyzer["arches"], vertex) if inDeg >= 1 and outDeg > 1: total += 1 lt.addLast(vList, vertex) final = lt.newList() nIterator = lli.newIterator(vList) while lli.hasNext(nIterator): elt = lli.next(nIterator) cpl = mp.get(analyzer["countriesCodes"], elt) value = me.getValue(cpl) lt.addLast(final, value["id"]) lt.addLast(final, value["name"]) return total, final
def parteC(analyzer, area1, area2, hora_inicio, hora_fin): area1 = float(area1) area2 = float(area2) inicio = datetime.datetime.strptime(hora_inicio, '%H:%M').time() final = datetime.datetime.strptime(hora_fin, '%H:%M').time() vertices = gr.vertices(analyzer['graph']) iterator = it.newIterator(vertices) vertices_area1 = lt.newList() vertices_area2 = lt.newList() menor = [0, 0, 0, 0] while it.hasNext(iterator): actual = it.next(iterator) if actual[0] != "" and float( actual[0].strip()) == area1 and actual[1] > inicio: lt.addLast(vertices_area1, actual) elif actual[0] != "" and float( actual[0].strip()) == area2 and actual[1] < final: lt.addLast(vertices_area2, actual) iterator = it.newIterator(vertices_area1) while it.hasNext(iterator): actual = it.next(iterator) diks = djk.Dijkstra(analyzer['graph'], actual) iterator2 = it.newIterator(vertices_area2) while it.hasNext(iterator2): current = it.next(iterator2) cost = djk.distTo(diks, current) if menor[0] == 0: menor[0] = cost menor[1] = actual menor[2] = current menor[3] = djk.pathTo(diks, current) elif cost < menor[0]: menor[0] = cost menor[1] = actual menor[2] = current menor[3] = djk.pathTo(diks, current) return menor
def PrimMST(graph, origin=None): """ Implementa el algoritmo de Prim Args: graph: El grafo de busqueda Returns: La estructura search con los MST Raises: Exception """ try: search = initSearch(graph) vertices = g.vertices(graph) if origin is not None: pos = lt.isPresent(vertices, origin) if pos != 0: lt.exchange(vertices, 1, pos) for vert in lt.iterator(vertices): if not map.get(search['marked'], vert)['value']: prim(graph, search, vert) return search except Exception as exp: error.reraise(exp, 'prim:PrimMST')