def getEdge(graph, vertexa, vertexb): """ Retorna el arco asociado a los vertices vertexa ---- vertexb Args: graph: El grafo sobre el que se ejecuta la operacion vertexa: Vertice de inicio vertexb: Vertice destino Returns: El arco que une los verices vertexa y vertexb Raises: Exception """ try: element = map.get(graph['vertices'], vertexa) lst = element['value'] itvertex = it.newIterator(lst) while (it.hasNext(itvertex)): edge = it.next(itvertex) if (graph['directed']): if (e.either(edge) == vertexa and (e.other(edge, e.either(edge)) == vertexb)): return edge elif (e.either(edge) == vertexa or (e.other(edge, e.either(edge)) == vertexa)): if (e.either(edge) == vertexb or (e.other(edge, e.either(edge)) == vertexb)): return edge return None except Exception as exp: error.reraise(exp, 'ajlist:getedge')
def PaisesAfectados(catalog, nombreLanding): landing = mp.get(catalog["LandingPointN"], nombreLanding) listaPaises = "NE" if landing != None: #listaPaises = lt.newList('ARRAY_LIST') tablitaPaises = mp.newMap(numelements=10, maptype='PROBING', comparefunction=compareCountryNames) landing = me.getValue(landing) datosLanding = lt.getElement( me.getValue(mp.get(catalog["LandingPointI"], landing))['lstData'], 1) paisLanding = datosLanding["name"].split(",") paisLanding = paisLanding[len(paisLanding) - 1].strip() h = paisLanding edge = gr.getEdge(catalog["connectionsDistance"], paisLanding, landing) peso = e.weight(edge) / 1000 #lt.addLast(listaPaises,paisLanding) mp.put(tablitaPaises, paisLanding, peso) adyacentes = gr.adjacentEdges(catalog["connectionsDistance"], landing) for arco in lt.iterator(adyacentes): OtroVertex = e.other(arco, landing) if not mp.contains(catalog['countriesInfo'], OtroVertex): adyacentes2 = gr.adjacentEdges(catalog["connectionsDistance"], OtroVertex) for arco2 in lt.iterator(adyacentes2): OtroVertex2 = e.other(arco2, OtroVertex) if not mp.contains(catalog['countriesInfo'], OtroVertex2) and OtroVertex2 != landing: peso = e.weight(arco2) / 1000 id = OtroVertex2.split("*")[0] datosLanding = lt.getElement( me.getValue(mp.get(catalog["LandingPointI"], id))['lstData'], 1) paisLanding = datosLanding["name"].split(",") paisLanding = paisLanding[len(paisLanding) - 1].strip() #if lt.isPresent(listaPaises,paisLanding)==0: # lt.addLast(listaPaises,paisLanding) pais = mp.get(tablitaPaises, paisLanding) if pais != None: pais = me.getValue(pais) if (peso < pais): mp.put(tablitaPaises, paisLanding, peso) #ACA else: mp.put(tablitaPaises, paisLanding, peso) #ACA #heap = pq.newMinPQ(cmpfunction=compareDistance) listaPaises = lt.newList('ARRAY_LIST') for pais in lt.iterator(mp.keySet(tablitaPaises)): elemento = me.getValue(mp.get(tablitaPaises, pais)) #pq.insert(heap,(pais,elemento)) lt.addLast(listaPaises, (pais, elemento)) merge.sort(listaPaises, compareDistance) return listaPaises
def adjacents(graph, vertex): """ Retorna una lista con todos los vertices adyacentes al vertice vertex Args: graph: El grafo sobre el que se ejecuta la operacion vertex: El vertice del que se quiere la lista Returns: La lista de adyacencias Raises: Exception """ try: element = map.get(graph['vertices'], vertex) lst = element['value'] lstresp = lt.newList() iter = it.newIterator(lst) while (it.hasNext(iter)): edge = it.next(iter) v = e.either(edge) if (v == vertex): lt.addLast(lstresp, e.other(edge, v)) else: lt.addLast(lstresp, v) return lstresp except Exception as exp: error.reraise(exp, 'ajlist:adjacents')
def relax(search, edge): """ Relaja el peso de los arcos del grafo con la nueva de un nuevo arco Args: search: La estructura de busqueda edge: El nuevo arco Returns: El grafo con los arcos relajados Raises: Exception """ try: v = e.either(edge) w = e.other(edge, v) visited_v = map.get(search['visited'], v)['value'] visited_w = map.get(search['visited'], w)['value'] distw = visited_w['distTo'] distv = visited_v['distTo'] + e.weight(edge)[0] if (visited_w is None) or (distw > distv): distow = visited_v['distTo'] + e.weight(edge)[0] map.put(search['visited'], w, { 'marked': True, 'edgeTo': edge, 'distTo': distow }) if iminpq.contains(search['iminpq'], w): iminpq.decreaseKey(search['iminpq'], w, distow) else: iminpq.insert(search['iminpq'], w, distow) return search except Exception as exp: error.reraise(exp, 'dks:relax')
def scan(graph, search, vertex): """ Args: search: La estructura de busqueda vertex: El vertice destino Returns: El costo total para llegar de source a vertex. Infinito si no existe camino Raises: Exception """ try: map.put(search['marked'], vertex, True) edges = g.adjacentEdges(graph, vertex) for edge in lt.iterator(edges): w = e.other(edge, vertex) if (not map.get(search['marked'], w)['value']): if (e.weight(edge) < map.get(search['distTo'], w)['value']): map.put(search['distTo'], w, e.weight(edge)) map.put(search['edgeTo'], w, edge) if (pq.contains(search['pq'], w)): pq.decreaseKey(search['pq'], w, map.get(search['distTo'], w)['value']) else: pq.insert(search['pq'], w, map.get(search['distTo'], w)['value']) return search except Exception as exp: error.reraise(exp, 'bellman:disto')
def dfs(graph, search, v): """ DFS Args: search: La estructura de busqueda v: Vertice desde donde se relajan los pesos Returns: El grafo Raises: Exception """ try: map.put(search['marked'], v, True) map.put(search['onStack'], v, True) edges = g.adjacentEdges(graph, v) for edge in lt.iterator(edges): w = e.other(edge, v) if (not st.isEmpty(search['cycle'])): return search elif ((not map.get(search['marked'], w)['value'])): map.put(search['edgeTo'], w, edge) dfs(graph, search, w) elif (map.get(search['onStack'], w)['value']): f = edge while (e.either(f) != w): st.push(search['cycle'], f) f = map.get(search['edgeTo'], e.either(f))['value'] st.push(search['cycle'], f) return search map.put(search['onStack'], v, False) except Exception as exp: error.reraise(exp, 'cycle:dfs')
def relax(graph, search, v): """ Relaja el peso de los arcos del grafo Args: search: La estructura de busqueda v: Vertice desde donde se relajan los pesos Returns: El grafo con los arcos relajados Raises: Exception """ try: edges = g.adjacentEdges(graph, v) if edges is not None: for edge in lt.iterator(edges): v = e.either(edge) w = e.other(edge) distv = map.get(search['distTo'], v)['value'] distw = map.get(search['distTo'], w)['value'] distweight = distv + e.weight(edge) if (distw > distweight): map.put(search['distTo'], w, distweight) map.put(search['edgeTo'], w, edge) if (not map.get(search['onQ'], w)['value']): q.enqueue(search['qvertex'], w) map.put(search['onQ'], w, True) cost = search['cost'] if ((cost % g.numVertices(graph)) == 0): findneg = findNegativeCycle(graph, search) if (hasNegativecycle(findneg)): return search['cost'] = cost + 1 return search except Exception as exp: error.reraise(exp, 'bellman:relax')
def getEdge(graph, vertexa, vertexb): try: element = map.get(graph['vertices'], vertexa) lst = element['value'] itvertex = it.newIterator(lst) while (it.hasNext(itvertex)): edge = it.next(itvertex) if (e.either(edge) == vertexa) and (e.other(edge, e.either(edge)) == vertexb): return edge elif (not graph['directed']) and (e.either(edge) == vertexb) and ( e.other(edge, e.either(edge)) == vertexa): return edge return None except Exception as exp: error.reraise(exp, 'ajlist:getedge')
def numVertexsMST(analyzer): edges = analyzer['MST']['mst'] map = mp.newMap(numelements=2000,maptype='PROBING') for edge in lt.iterator(edges): vertexa = e.either(edge) vertexb = e.other(edge, vertexa) contains = mp.contains(map, vertexa) if not contains: mp.put(map, vertexb, 'Exist') contains = mp.contains(map, vertexb) if not contains: mp.put(map, vertexb, 'Exist') return lt.size(map)
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 caminoMin(caminosMinimos, pais1, pais2): """ Se consigue la distancia y el camino que conecta la fuente del grafo Caminos minimos con el Pais2. Si la distancia es infinito, lo cual indica que no hay camino, esta se remplaza por -1. #PROXIMAMENTE: Pasar el camino a una lista para que sea facil de imprimir en el view""" caminos = lt.newList('ARRAY_LIST', cmpfunction=compareCountryNames) camino = djk.pathTo(caminosMinimos, pais2) distancia = djk.distTo(caminosMinimos, pais2) if distancia == math.inf: distancia = -1 else: for elemento in lt.iterator(camino): dato = lt.newList('ARRAY_LIST') land1 = e.either(elemento) peso = e.weight(elemento) land2 = e.other(elemento, e.either(elemento)) lt.addLast(dato, land1) lt.addLast(dato, peso) lt.addLast(dato, land2) lt.addLast(caminos, dato) return caminos, distancia
def Requirement3(analyzer, country1, country2): tracemalloc.start() delta_time = -1.0 delta_memory = -1.0 start_time = getTime() start_memory = getMemory() capital1 = (mp.get(analyzer['countries_map'], country1)['value'])['CapitalName'] capital2 = (mp.get(analyzer['countries_map'], country2)['value'])['CapitalName'] analyzer['paths'] = djk.Dijkstra( analyzer['connections_origin_destination'], capital1) path = djk.pathTo(analyzer['paths'], capital2) distance = djk.distTo(analyzer['paths'], capital2) listKm = lt.newList('ARRAY_LIST') iterator1 = it.newIterator(path) while it.hasNext(iterator1): component = it.next(iterator1) vertexA = edge.either(component) vertexB = edge.other(component, vertexA) weight = edge.weight(component) string = 'Ir ' + str(weight) + ' Km desde ' + vertexA + ' a ' + vertexB lt.addLast(listKm, string) stop_memory = getMemory() stop_time = getTime() tracemalloc.stop() delta_time = stop_time - start_time delta_memory = deltaMemory(start_memory, stop_memory) return (listKm, distance, delta_time, delta_memory)
def test_edgeMethods(graph): edge = e.newEdge('Bogota', 'Cali') assert 'Bogota' == e.either(edge) assert 'Cali' == e.other(edge, e.either(edge)) assert e.weight(edge) == 0
def InfoMst(mst, catalog): maximo = 0 NodoMax = "" dist = prim.weightMST(catalog['connectionsDistance'], mst) NumNodos = lt.size(mp.keySet(mst['edgeTo'])) TablaVisitados = mp.newMap(numelements=NumNodos, maptype='PROBING', comparefunction=compareLanCableIds) lstNodosMST = mp.keySet(mst['edgeTo']) TamañosFinales = True while TamañosFinales: if (lt.size(lstNodosMST)) <= lt.size(mp.keySet(TablaVisitados)): TamañosFinales = False centinelaCorto = True while centinelaCorto: num = ran.randint(1, lt.size(lstNodosMST)) Origen = lt.getElement(lstNodosMST, num) if not (mp.contains(TablaVisitados, Origen)) or not TamañosFinales: centinelaCorto = False VertexToCompare = Origen Camino = lt.newList('ARRAY_LIST') lt.addLast(Camino, VertexToCompare) NodosVisitados = 0 verifica = True while verifica: VertexTrue = mp.contains(TablaVisitados, VertexToCompare) if not VertexTrue: NodosVisitados += 1 conexiones = mp.get(mst['edgeTo'], VertexToCompare) if not (conexiones == None): conexiones = me.getValue(conexiones) if VertexToCompare == e.either(conexiones): VertexToCompare = e.other(conexiones, VertexToCompare) else: VertexToCompare = e.either(conexiones) lt.addLast(Camino, VertexToCompare) else: if NodosVisitados > maximo: maximo = NodosVisitados NodoMax = Origen verifica = False i = 1 while i < lt.size(Camino): node = lt.getElement(Camino, i) infoNode = CreateInfo_Req4() infoNode['NodosHastaFin'] = NodosVisitados mp.put(TablaVisitados, node, infoNode) NodosVisitados -= 1 i += 1 else: ValueNode = mp.get(TablaVisitados, VertexToCompare) ValueNode = me.getValue(ValueNode) NodosHastaFinVisitado = ValueNode['NodosHastaFin'] i = 1 while i < lt.size(Camino): node = lt.getElement(Camino, i) infoNode = CreateInfo_Req4() NodosHastafinNuevo = NodosVisitados + NodosHastaFinVisitado if NodosHastafinNuevo > maximo: maximo = NodosHastafinNuevo NodoMax = Origen infoNode['NodosHastaFin'] = NodosHastafinNuevo mp.put(TablaVisitados, node, infoNode) NodosVisitados -= 1 i += 1 verifica = False Rama = lt.newList('ARRAY_LIST') VertexToCompare = NodoMax realidad = True while realidad: conexionesMasGrande = mp.get(mst['edgeTo'], VertexToCompare) lt.addLast(Rama, VertexToCompare) if not (conexionesMasGrande == None): conexionesMasGrande = me.getValue(conexionesMasGrande) if VertexToCompare == e.either(conexionesMasGrande): VertexToCompare = e.other(conexionesMasGrande, VertexToCompare) else: VertexToCompare = e.either(conexionesMasGrande) else: realidad = False return dist, NumNodos, Rama