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 (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 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'] for edge in lt.iterator(lst): if (graph['directed']): if (e.either(edge) == vertexa and (e.other(edge) == vertexb)): return edge elif (e.either(edge) == vertexa or (e.other(edge) == vertexa)): if (e.either(edge) == vertexb or (e.other(edge) == vertexb)): return edge return None except Exception as exp: error.reraise(exp, 'ajlist:getedge')
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) edges = lt.newList(datastructure='SINGLE_LINKED', cmpfunction=None) 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)) == vertexb)): lt.addLast(edges, edge) return edges except Exception as exp: error.reraise(exp, 'ajlist:getedge')
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 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 pathTo(search, vertex): """ Retorna el camino entre source y vertex en una pila. Args: search: La estructura de busqueda vertex: El vertice de destino Returns: Una pila con el camino entre source y vertex Raises: Exception """ try: if hasPathTo(search, vertex) is False: return None path = stack.newStack() while vertex != search['source']: visited_v = map.get(search['visited'], vertex)['value'] edge = visited_v['edgeTo'] stack.push(path, edge) vertex = e.either(edge) return path except Exception as exp: error.reraise(exp, 'dks:pathto')
def Dijkstra(graph, source, inicio, fin): """ Implementa el algoritmo de Dijkstra Args: graph: El grafo de busqueda source: El vertice de inicio Returns: Un nuevo grafo vacío Raises: Exception """ try: search = initSearch(graph, source) while not iminpq.isEmpty(search['iminpq']): v = iminpq.delMin(search['iminpq']) edges = g.adjacentEdges(graph, v) if edges is not None: edgesiter = it.newIterator(edges) while (it.hasNext(edgesiter)): edge = it.next(edgesiter) peso = e.weight(edge) v = e.either(edge) if v == source: if peso[0] < fin and peso[0] > inicio: relax(search, edge) else: relax(search, edge) return search except Exception as exp: error.reraise(exp, 'dks:dijkstra')
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 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 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.either(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 recreateBranch (mapvertex, entry, vertex): exist = mp.contains(mapvertex, vertex) if exist: edge = mp.get(mapvertex, vertex) edge = me.getValue(edge) lt.addLast(entry, edge) vertex = e.either(edge) recreateBranch (mapvertex, entry, vertex)
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 createMap(analyzer, lstconnections): map = folium.Map(location=[12.240859, -18.118127], tiles='CartoDB Positron', zoom_start=3, orldCopyJump=True) map.add_child(folium.LatLngPopup()) for edge in lt.iterator(lstconnections): origin = e.either(edge).split(',') destination = edge['vertexB'].split(',') coordinate1 = getCoordinate(analyzer, origin[0]) coordinate2 = getCoordinate(analyzer, destination[0]) route = (coordinate1, coordinate2) folium.PolyLine(route, color="#"+''.join([random.choice('0123456789ABCDEF') for j in range(6)])).add_to(map) map.save('mapa.html')
def announcementStation(analyzer, edad): edgelst = gr.edges(analyzer['graph']) edgeiterator = it.newIterator(edgelst) mayor = 0 r = [] e_mayor1 = { 'Estación Incio: ': 0, 'Esación llegada: ': 0, 'viajes_Totales: ': 0 } while it.hasNext(edgeiterator): e_mayor2 = { 'Estación Incio: ': 0, 'Esación llegada: ': 0, 'viajes_Totales: ': 0 } edge = it.next(edgeiterator) a_comparar = e.usertype(edge)[edad]['Customer'] if a_comparar > mayor: r = [] mayor = a_comparar e_mayor1['Estación Incio: '] = e.either(edge) e_mayor1['Esación llegada: '] = edge['vertexB'] e_mayor1['viajes_Totales: '] = e.getTotaltrips(edge) elif a_comparar == mayor: e_mayor2['Estación Incio: '] = e.either(edge) e_mayor2['Esación llegada: '] = edge['vertexB'] e_mayor2['viajes_Totales: '] = e.getTotaltrips(edge) r.append(e_mayor2) if e_mayor1 not in r: r.append(e_mayor1) return (r)
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 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 longuestBranch(analyzer): mapvertex = analyzer['MST']['edgeTo'] vertexs = mp.keySet(mapvertex) map = mp.newMap(numelements=2000,maptype='PROBING') maxbranch = None maxvertexs = 0 for vertex in lt.iterator(vertexs): edge = mp.get(mapvertex, vertex) edge = me.getValue(edge) entry = lt.newList('ARRAY_LIST') lt.addLast(entry, edge) vertex = e.either(edge) recreateBranch (mapvertex, entry, vertex) mp.put(map, vertex, entry) vertexs = mp.keySet(map) for vertex in lt.iterator(vertexs): entry = mp.get(map, vertex) value = me.getValue(entry) if lt.size(value) > maxvertexs: maxvertexs = lt.size(value) maxbranch = value return maxbranch
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