def RutaMinima(catalog, paisA, paisB): mapaLP = catalog['landing_points'] mapaCountries = catalog['countries'] mapaCountries2 = catalog['countries2'] grafo = catalog['grafo'] capitalA = me.getValue(mp.get(mapaCountries, paisA))['CapitalName'] capitalB = me.getValue(mp.get(mapaCountries, paisB))['CapitalName'] dijkstra = djk.Dijkstra(grafo, capitalA) distancia_total = djk.distTo(dijkstra, capitalB) ruta_cruda = djk.pathTo(dijkstra, capitalB) ruta = qu.newQueue('ARRAY_LIST') previo = None while not stk.isEmpty(ruta_cruda): punto = stk.pop(ruta_cruda)['vertexB'] dist = djk.distTo(dijkstra, punto) if not mp.contains(mapaCountries2, punto): punto = 'Landing point ' + punto.split('-')[0] print(dist) print(punto) p_d = (punto, dist) if not previo == punto: qu.enqueue(ruta, p_d) previo = punto return ruta, distancia_total
def hora_adecuada(analyzer, hora_i, hora_f, estacion_i, estacion_f): mayor = 365 * 24 * 3600 mejor = None ruta = None for a in analyzer["rango"][estacion_i].keys(): hora = str(a.hour) minute = str(a.minute) comprar = hora + ":" + minute tiempo = datetime.datetime.strptime(comprar, '%H:%M') print(tiempo) print(hora_i) print(hora_f) if tiempo >= hora_i and tiempo <= hora_f: grafo = djk.Dijkstra(analyzer["connections"], analyzer["rango"][estacion_i][a]) for b in analyzer["rango"][estacion_f].keys(): if djk.hasPathTo(grafo, analyzer["rango"][estacion_f][b]): if mayor > djk.distTo(grafo, analyzer["rango"][estacion_f][b]): mayor = djk.distTo(grafo, analyzer["rango"][estacion_f][b]) ruta = djk.pathTo(grafo, analyzer["rango"][estacion_f][b]) mejor = analyzer["rango"][estacion_i][a] return ({"mejor hora: ": mejor, "ruta: ": ruta, "duracion: ": mayor})
def minDistanceBetweenCapitals(analyzer, countryA, countryB): ''' Calcula la distancia minima entre las capitales de dos paises dados ''' capitalA = getCapital(analyzer, countryA) capitalB = getCapital(analyzer, countryB) lpA = formatVertexCapitals(analyzer, capitalA) lpB = formatVertexCapitals(analyzer, capitalB) analyzer['min_dists_paths'] = djk.Dijkstra(analyzer['connections'], lpA) min_path = djk.pathTo(analyzer['min_dists_paths'], lpB) cost = djk.distTo(analyzer['min_dists_paths'], lpB) if min_path is not None: info_out = {} # save info of each landing point total_dist = 0 for lp in lt.iterator(min_path): total_dist += lp['weight'] for vertex in ['vertexA', 'vertexB']: vertex = InterruptedError(vertex.split('*')[0]) lp_info = m.get(analyzer['landing_points'], lp[vertex])['value'] info_out[lp[vertex]] = {'name': lp_info['name']} return [min_path, total_dist, info_out] else: return [min_path]
def theBestRoute(graph,station1,station2,timemin,timemax): best=None bestpath=None besttime=100000000 timemax=timechange(timemax) timemin=timechange(timemin) i=timemin while i<=timemax: stationstart=station1+";;"+str(i) stationend=station2+";;"+str(i) if gr.containsVertex(graph,stationstart): dijk=djk.Dijkstra(graph,stationstart) wa=djk.pathTo(dijk,stationend) y=djk.distTo(dijk,stationend) if wa!=None: if y<=besttime: besttime=y best =i bestpath= wa i+=15 if best!=None: best=timechangeback(best) way=[best,bestpath,besttime] return way
def Shortestway(citiTaxi, origin, destination, HoI, HoF): lst = [] dicc = {} lista = gra.vertices(citiTaxi['graph']) iterator = it.newIterator(lista) while it.hasNext(iterator): fila = it.next(iterator) origin1 = fila.split('-') timeO = datetime.datetime.strptime(origin1[1], '%H:%M').time() if origin1[0] == origin: if HoI <= timeO and timeO <= HoF: lst.append(fila) for i in range(0, len(lst)): source = djk.Dijkstra(citiTaxi['graph'], lst[i]) iterator = it.newIterator(lista) while it.hasNext(iterator): vertice = it.next(iterator) com = vertice.split('-') if com[0] == destination: camino = djk.hasPathTo(source, vertice) if camino == True: tiempo = djk.distTo(source, vertice) ruta = djk.pathTo(source, vertice) if lst[i] not in dicc: dicc[lst[i]] = {'tiempo': tiempo, 'ruta': ruta} else: if tiempo < dicc[lst[i]]['tiempo']: dicc[lst[i]] = {'tiempo': tiempo, 'ruta': ruta} menores(dicc)
def parteC(analyzer, communityAreaOrigin, communityAreaDestination, rangeTime): answer = {"bestTime": "No identificada", "route": None, "duration": inf} graph = analyzer['AreaGraph'] rangeTime2 = rangeTime.split("-") ls = aboutQuarterHour(rangeTime2[0]) totalq = allQuartersInRange(rangeTime) totalq.append(ls) endVertexes = [] vertexes = gr.vertices(graph) iterator = it.newIterator(vertexes) while it.hasNext(iterator): vertex2 = it.next(iterator) vertex2 = vertex2.split("-") if communityAreaDestination == vertex2[0]: endVertexes.append("-".join(vertex2)) for i in totalq: initialVertex = communityAreaOrigin + "-" + i if gr.containsVertex(graph, initialVertex): print("A") search = djk.Dijkstra(graph, initialVertex) print("B") for k in endVertexes: if djk.hasPathTo(search, k): duration = str(djk.distTo(search, k)) route = djk.pathTo(search, k) if float(duration) < float(answer["duration"]): answer["duration"] = duration answer["route"] = route answer["bestTime"] = i return answer
def distancia_minima_paises(analyzer, pais1, pais2): capital1 = pais_capital(analyzer, pais1) capital2 = pais_capital(analyzer, pais2) vertice1 = (capital1, 'capital') vertice2 = (capital2, 'capital') analyzer['MST_Dij'] = djk.Dijkstra(analyzer['connections_distancia'], vertice1) distancia_minima = djk.distTo(analyzer['MST_Dij'], vertice2) camino = djk.pathTo(analyzer['MST_Dij'], vertice2) camino_final = lt.newList() for conexion in lt.iterator(camino): try: int(conexion['vertexA'][0]) verticea = conexion['vertexA'][0] pareja1 = m.get(analyzer['landing_points'], verticea) nombrea = me.getValue(pareja1)['name'].split(',')[0] except: nombrea = conexion['vertexA'][0] try: int(conexion['vertexB'][0]) verticeb = conexion['vertexB'][0] pareja2 = m.get(analyzer['landing_points'], verticeb) nombreb = me.getValue(pareja2)['name'].split(',')[0] except: nombreb = conexion['vertexB'][0] conexion = (nombrea, nombreb, conexion['weight']) lt.addLast(camino_final, conexion) return distancia_minima, camino_final
def estaciones_por_rango(cont, rango): camino_mostrar=[] buscar_rango_hash=m.get(cont["births"],rango) if buscar_rango_hash == None: tupla = (0,0,0,0,0,0) else: variable1= me.getValue(buscar_rango_hash) variable2 =m.get(variable1, "Intro") variable3 = me.getValue(variable2) variable4 = m.get(variable3, "Max") variablesIntro = me.getValue(variable4) variable5 =m.get(variable1, "Outro") variable6 = me.getValue(variable5) variable7 = m.get(variable6, "Max") variablesOutro = me.getValue(variable7) if variablesIntro[1] != variablesOutro[1]: cont = minimumCostPaths(cont,variablesIntro[1]) camino = minimumCostPath(cont,variablesOutro[1]) tiempo = djk.distTo(cont["paths"],variablesOutro[1]) iterator = it.newIterator(camino) while it.hasNext(iterator): element=it.next(iterator) camino_mostrar.append(element) else: camino="NINGUNO porque la estacion " +str(variablesIntro[1]) +" es la que mas viajes recibe y más arroja" tiempo=0 tupla =(variablesIntro[1],variablesIntro[0],variablesOutro[1],variablesOutro[0],camino_mostrar,round(tiempo,2)) return tupla
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 touristicRoute(latIn, lonIn, latFn, lonFn, analyzer): vertexs = gr.vertices(analyzer["connections"]) iterator = it.newIterator(vertexs) sal = () lleg = () while it.hasNext(iterator): element = it.next(iterator) locationp = m.get(analyzer["location"],element) location = me.getValue(locationp) distance1 = distance(latIn,location[0],lonIn,location[1]) distance2 = distance(latFn,location[0],lonFn,location[1]) try: if sal == (): sal = (element,distance1) elif distance1 < sal[1] or (distance1<=sal[1] and gr.outdegree(analyzer["connections"],element)>gr.outdegree(analyzer["connections"],sal[1])): sal = (element,distance1) except: pass try: if lleg == (): lleg = (element,distance2) elif distance2 < lleg[1] or (distance2<=lleg[1] and gr.indegree(analyzer["connections"],element)>gr.indegree(analyzer["connections"],lleg[1])): lleg = (element,distance2) except: pass analyzer = minimumCostPaths(analyzer,sal[0]) minpath = minimumCostPath(analyzer,lleg[0]) time = djk.distTo(analyzer["paths"],lleg[0]) return (sal[0],lleg[0],minpath,time)
def routeByResistance(citibike, initialStation, resistanceTime): try: dijsktra = djk.Dijkstra(citibike["connections"], initialStation) vertices = gr.vertices(citibike["connections"]) iterator = it.newIterator(vertices) trueStations = st.newStack() stops = m.newMap(numelements=768, maptype="CHAINING", loadfactor=1, comparefunction=compareStopIds) while it.hasNext(iterator): element = it.next(iterator) if element != initialStation and djk.hasPathTo(dijsktra, element) is True: if m.get(stops, element) is None or getElement(m.get(stops, element))["value"] is False: if djk.distTo(dijsktra,element) <= resistanceTime: pila= djk.pathTo(dijsktra,element) pila2 = djk.pathTo(dijsktra,element) size_pila = 0 repetition = False lon_pila = st.size(pila) watcher = {"value": True} while size_pila < lon_pila and repetition == False: pop = st.pop(pila)["vertexB"] if m.get(stops,pop) is None or getElement(m.get(stops,pop))["value"] is False: m.put(stops,pop,watcher) else: repetition = True watcher["value"]=False size_pila +=1 if repetition == False: st.push(trueStations, pila2) return trueStations except: return None
def fourthRequirement(analyzer, station, resistencia, resistenciamin): #Se recorren todos los nodos del grafo. grafo = analyzer['graph'] recorrido = m.keySet(dfs.DepthFirstSearch(grafo, station)['visited']) iterator = it.newIterator(recorrido) rutas = lt.newList() while it.hasNext(iterator): element = it.next(iterator) mpa = djk.Dijkstra(grafo, station) if djk.hasPathTo(mpa, element): distance = djk.distTo(mpa, element) if int(distance) <= int(resistencia) and int(distance) >= int( resistenciamin): lt.addLast(rutas, djk.pathTo(mpa, element)) else: a = 1 if lt.isEmpty(rutas): return None return rutas """ distancia=djk.distTo(station,station2) if distancia <= resistencia: add.... """ return None
def Requerimiento3(analyzer, pais_a, pais_b): vertice_a = pais_a vertice_b = pais_b analyzer['caminos'] = dij.Dijkstra(analyzer['connections'], vertice_a) ruta = dij.pathTo(analyzer['connection'], vertice_b) distancia = dij.distTo(analyzer['connections'], vertice_b) return ruta, distancia
def distPais(analyzer, A, B): grafo = analyzer['cables'] nombres = mp.keySet(analyzer['LPnames']) #add dist de cap a ciudades, agrega al grafo ori1, ori2 = (mp.get(analyzer['paises'], A))['value'][3], (mp.get(analyzer['paises'], B))['value'][3] gr.insertVertex(grafo, 1) gr.insertVertex(grafo,2) for cable in lt.iterator(nombres): if A in cable: id = (mp.get(analyzer['LPnames'], cable))['value'] cor = (mp.get(analyzer['landingPoints'],id))['value'][0] peso = haversine(ori1, cor) gr.addEdge(grafo, 1,id, peso ) elif B in cable: id = (mp.get(analyzer['LPnames'], cable))['value'] cor = (mp.get(analyzer['landingPoints'],id))['value'][0] peso = haversine(ori2, cor) gr.addEdge(grafo, 2,id, peso ) #ruta con distancia de cada una #distancia total ruta = dj.Dijkstra(grafo, 1) camino = dj.pathTo(ruta, 2) ans = printRute(ruta, camino) print('Para recorrer en total: ', round(dj.distTo(ruta,2),2), ' km.')
def ruta_minima(analyzer,pais1,pais2): capital1=me.getValue(mp.get(analyzer['pais_capital'],pais1)) capital2=me.getValue(mp.get(analyzer['pais_capital'],pais2)) search=djk.Dijkstra(analyzer['connections'],(capital1,'1')) distancia_total=djk.distTo(search,(capital2,'1')) camino=djk.pathTo(search,(capital2,'1')) return camino,distancia_total
def theBestRoute(graph, station1, station2): best = djk.Dijkstra(graph, station1) wa = djk.pathTo(best, station2) y = djk.distTo(best, station2) if wa == None: way = "No existe ruta " way = [wa, y] return way
def Ruta_interes_turistico(grafo, latitud1, longitud1, latitud2, longitud2): Latitud1 = float(latitud1) / 57.29577951 Longitud1 = float(longitud1) / 57.29577951 Latitud2 = float(latitud2) / 57.29577951 Longitud2 = float(longitud2) / 57.29577951 menor = None menor_dist = 10000000000 menor2 = None menor_dist2 = 10000000000 estaciones = grafo["Estaciones"] entry = m.keySet(estaciones) iterador = it.newIterator(entry) while it.hasNext(iterador): elemento = it.next(iterador) entry = m.get(estaciones, elemento) valor = me.getValue(entry) latitud = float(valor["Latitud"]) / 57.29577951 longitud = float(valor["Longitud"]) / 57.29577951 dis_estacion_salida = 3963.0 * math.acos( math.sin(Latitud1) * math.sin(latitud) + math.cos(Latitud1) * math.cos(latitud) * math.cos(longitud - Longitud1)) dis_estacion_llegada = 3963.0 * math.acos( math.sin(Latitud2) * math.sin(latitud) + math.cos(Latitud2) * math.cos(latitud) * math.cos(longitud - Longitud2)) if dis_estacion_salida <= menor_dist: menor = elemento menor_dist = dis_estacion_salida if dis_estacion_llegada <= menor_dist2: menor2 = elemento menor_dist2 = dis_estacion_llegada lista = lt.newList("ARRAY_LIST", comparar_esta) path = djk.Dijkstra(grafo["graph"], menor) path_ = djk.pathTo(path, menor2) costo = djk.distTo(path, menor2) estaciones = grafo["Estaciones"] entry_sal = m.get(estaciones, menor) entry_lle = m.get(estaciones, menor2) estacion_sali = me.getValue(entry_sal)["Nombre"] estacion_lleg = me.getValue(entry_lle)["Nombre"] while (not st.isEmpty(path_)): stop = st.pop(path_) entryA = m.get(estaciones, stop["vertexA"]) estacion_1 = me.getValue(entryA)["Nombre"] if lt.isPresent(lista, estacion_1) == 0: lt.addLast(lista, estacion_1) entryB = m.get(estaciones, stop["vertexB"]) estacion_2 = me.getValue(entryB)["Nombre"] if lt.isPresent(lista, estacion_2) == 0: lt.addLast(lista, estacion_2) return lista, estacion_sali, estacion_lleg, costo
def test_dijkstra_armenia(graph): search = djk.Dijkstra(graph, 'Bogota') assert djk.hasPathTo(search, 'Armenia') is True path = djk.pathTo(search, 'Armenia') print('\n') while not stack.isEmpty(path): edge = stack.pop(path) print(edge['vertexA'] + "-->" + edge['vertexB'] + " costo: " + str(edge['weight'])) print(str(djk.distTo(search, 'Armenia')))
def req3(datos, pais_a, pais_b): a = mp.get(datos['pais'], pais_a) b = mp.get(datos['pais'], pais_b) #capitala = (a['value']['CapitalName']).lower() es bogota pero no esta en el archivo capitalb = (b['value']['CapitalName']).lower() vertices = gr.vertices(datos['cables']) tamano = lt.size(vertices) p = 0 mirar = {} pasar_funcion = [] while p < int(tamano): x = lt.getElement(vertices, p) ciudad = x.split('-') ciudad_comparar = ciudad[0] if capitalb in ciudad_comparar.lower(): mirar[ciudad_comparar] = x if ('tolu' in ciudad_comparar.lower()): mirar[ciudad_comparar] = x p += 1 for i in mirar: pasar_funcion.append(mirar[i]) vertice1 = 'jakartaindonesia-Matrix Cable System' vertice2 = 'tolucolombia-Colombian Festoon' #vertice1 = pasar_funcion[0] #vertice2 = pasar_funcion[1] distancia_vertices = {} t = di.Dijkstra(datos['cables'], vertice1) distancia_total = di.distTo(t, vertice2) pila_camino = di.pathTo(t, vertice2) h = 0 while h < st.size(pila_camino): D = st.pop(pila_camino) verta = D['vertexA'] vertb = D['vertexB'] U = di.Dijkstra(datos['cables'], verta) distancia = di.distTo(U, vertb) distancia_vertices[h] = (verta, vertb, distancia) h += 1 return (distancia_vertices, distancia_total)
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 distPaises (analyzer,paisA,paisB): pA=me.getValue(mp.get(analyzer['countries'],paisA)) minin=1000000 listi=lt.newList() loc1=(float(pA['CapitalLatitude']),float(pA['CapitalLongitude'])) for landingp in (analyzer['landingpoints']['table']['elements']): if landingp['key']!=None: land=me.getValue(mp.get(analyzer['landingpoints'], landingp['key'])) loc2=(float(land['latitude']),float(land['longitude'])) dist=hs.haversine(loc1,loc2) if dist<minin: minin=dist landeA=land['landing_point_id'] pB=me.getValue(mp.get(analyzer['countries'],paisB)) Lista=lt.newList() dist=0 mini=10000000 loc1=(float(pB['CapitalLatitude']),float(pB['CapitalLongitude'])) for landingp in (analyzer['landingpoints']['table']['elements']): if landingp['key']!=None: land=me.getValue(mp.get(analyzer['landingpoints'], landingp['key'])) loc2=(float(land['latitude']),float(land['longitude'])) dist=hs.haversine(loc1,loc2) if dist<mini: mini=dist landes=land['landing_point_id'] vertices=gr.vertices(analyzer['connections']) a=lit.newIterator(vertices) while lit.hasNext(a): c=lit.next(a) h=c.split("-") if h[0]==landes: lt.addLast(Lista, c) if h[0]==landeA: x=c lt.addLast(listi, c) dist=-1 path="No" disti=1000000000000000 pathh="No" t=lit.newIterator(listi) while lit.hasNext(t): y=lit.next(t) route=dij.Dijkstra(analyzer['connections'],y) a=lit.newIterator(Lista) while lit.hasNext(a): e=lit.next(a) path=dij.hasPathTo(route, e) if path==True: dist=dij.distTo(route, e) path=dij.pathTo(route, e) if path !=None and dist<disti: disti=dist return(path,disti)
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 hayarMinCiclos(cont, initialStation, estaciones): listaCiclos=[] for a in range(0,len(estaciones)): lista=[] cont = minimumCostPaths(cont, initialStation) tiempo1 = djk.distTo(cont["paths"],estaciones[a]) #tiempo de Inicio a V1 lista=["Hay un camino que empieza en "+str(initialStation)+" y va a " +str(estaciones[a]) +" en un tiempo de "+str(round(tiempo1))+" segundos que se conecta asi:"] cont = minimumCostPaths(cont, estaciones[a]) tiempo2 = djk.distTo(cont["paths"],initialStation) minimumCostPaths(cont, estaciones[a]) path2 = minimumCostPath(cont, initialStation) iterator = it.newIterator(path2) tiempo_visita=0 while it.hasNext(iterator): element=it.next(iterator) lista.append(element) tiempo_visita+=20 tiempo_total= tiempo1/60+tiempo2/60+tiempo_visita tupla=(lista,round(tiempo_total)) listaCiclos.append(tupla) return listaCiclos
def turistInteres(citibike, latitudActual, longitudActual, latitudDestino, longitudDestino): """ Estacion mas cercana a la posicion actual, Estacion mas cercana al destino, (Menor) Tiempo estimado, Lista de estaciones para llegar al destino """ actualNearStationID = destinyNearStationID = None coords = citibike['coords'] actualNear = destinyNear = float('INF') keyList = m.keySet(coords) #Conseguir las estaciones mas cercanas al destino for i in range(m.size(coords)): key = lt.getElement(keyList, i) lat, lon, s_e = m.get(coords, key)['value'] lat = float(lat) lon = float(lon) distanceToActual = distance(lat, lon, latitudActual, longitudActual) distanceToDestiny = distance(lat, lon, latitudDestino, longitudDestino) #s_e esta para verificar que sea entrada o salida if distanceToActual < actualNear and s_e == 0: actualNear = distanceToActual actualNearStationID = key if distanceToDestiny < destinyNear and s_e == 1: destinyNear = distanceToDestiny destinyNearStationID = key #Obtener el nombre actualNearStation = getStation(citibike, actualNearStationID) destinyNearStation = getStation(citibike, destinyNearStationID) #Usar Dijsktra para conseguir el resto de info structureActual = djk.Dijkstra(citibike['connections'], actualNearStationID) if djk.hasPathTo(structureActual, destinyNearStationID): tripTime = djk.distTo(structureActual, destinyNearStationID) stationStack = djk.pathTo(structureActual, destinyNearStationID) else: return (actualNearStation, destinyNearStation, float('INF'), None) #De stack a lista con la informacion pulida stationList = lt.newList(datastructure='ARRAY_LIST') for i in range(st.size(stationStack)): stationD = st.pop(stationStack) vA = getStation(citibike, stationD["vertexA"])[1] vB = getStation(citibike, stationD["vertexB"])[1] lt.addLast(stationList, (vA, vB)) return actualNearStation, destinyNearStation, tripTime, stationList
def seventhRequirement(analyzer, edad): grafo1 = analyzer['adjacente1'] grafo2 = analyzer['adjacente2'] mpa1 = djk.Dijkstra(grafo1, str(edad)) mpa2 = djk.Dijkstra(grafo2, str(edad)) res1 = lt.firstElement(djk.pathTo(mpa1, "salida"))['vertexB'] res2 = lt.firstElement(djk.pathTo(mpa2, "salida"))['vertexB'] lista1 = gr.adjacents(analyzer['graph'], res1) iterator = it.newIterator(lista1) while it.hasNext(iterator): element = it.next(iterator) if gr.containsVertex(grafo2, element) and element != res1: peso = min(djk.distTo(mpa2, res2), djk.distTo(mpa1, res1)) return {'vertexA': res1, 'vertexB': element, 'weight': 1.0 / peso} return None print( "Los usuarios con edad en los {}'s les gusta iniciar en la estación {} y terminar en la estación {}. Se recomienda la ruta siguiente: {}" .format(int(edad) * 10, res1, res2, ruta)) return None
def req3(catalog, pais1, pais2): mapa_paises = catalog["paises"] grafo = catalog["connections"] capital1 = lt.getElement(mp.get(mapa_paises, pais1)["value"], 1) capital2 = lt.getElement(mp.get(mapa_paises, pais2)["value"], 1) caminosMinimos = dijsktra.Dijkstra(grafo, capital1) costo = dijsktra.distTo(caminosMinimos, capital2) recorrido = dijsktra.pathTo(caminosMinimos, capital2) return costo, recorrido
def Function2(controller, time1, time2, stationid): station2 = input("a que estación quiere dirigirse? ") #CICLO road = djk.Dijkstra(controller["graph"], stationid) caminoida = djk.pathTo(road, station2) retorno = djk.Dijkstra(controller["graph"], station2) caminovuelta = djk.pathTo(retorno, stationid) cam1 = djk.distTo(road, station2) cam2 = djk.distTo(retorno, stationid) if lt.isEmpty(caminovuelta) or lt.isEmpty(caminoida): print("no hay camino conectado de " + stationid + " a " + station2) return lt.newList(datastructure='SINGLE_LINKED', cmpfunction=None) else: if (cam1 + ((int(djk.pathTo(road, station2)['size']) * 20))) + (cam2 + ( (int(djk.pathTo(retorno, stationid)['size']) * 20))) in range( time1, time2): print(djk.pathTo(road, station2)) print(djk.pathTo(retorno, stationid)) return ("se encontró el siguiente camino de ida y vuelta") else: print( "se encontró un camino, pero esta fuera de los parametros establecidos." ) return lt.newList(datastructure='SINGLE_LINKED', cmpfunction=None) #CICLO tup = (caminoida, caminovuelta) return tup
def getToStationFromCoordinates(citibike, Lat1, Lon1, Lat2, Lon2): """ RETO4 | REQ 6 Dada una latitud y longitud inicial, se halla la estación de Citibike más cercana. Dada una coordenada de destino, se halla la estación de Citibike más cercana. Se calcula la ruta de menor tiempo entre estas dos estaciones. """ stations_keys = m.keySet(citibike['Edges_Map']) initialStationSortedByDistance = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareValues) finalStationSortedByDistance = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareValues) iterator = it.newIterator(stations_keys) while it.hasNext(iterator): station = it.next(iterator) sta = m.get(citibike['Edges_Map'], station) staLat = float(sta['value']['Latitude']) staLon = float(sta['value']['Longitude']) distance_from_initial_point = distanceFromTo(Lat1, staLat, Lon1, staLon) distance_from_final_point = distanceFromTo(Lat2, staLat, Lon2, staLon) sta['value']['Distance_From_Initial_Point'] = round( distance_from_initial_point, 5) sta['value']['Distance_From_Final_Point'] = round( distance_from_final_point, 5) lt.addLast(initialStationSortedByDistance, sta) lt.addLast(finalStationSortedByDistance, sta) mg.mergesort(initialStationSortedByDistance, closerInitialStation) mg.mergesort(finalStationSortedByDistance, closerFinalStation) CloserStation1 = lt.lastElement(initialStationSortedByDistance) CloserStation2 = lt.lastElement(finalStationSortedByDistance) paths = djk.Dijkstra(citibike['graph'], CloserStation1['key']) pathTo = djk.pathTo(paths, CloserStation2['key']) cost = djk.distTo(paths, CloserStation2['key']) return CloserStation1, CloserStation2, pathTo, cost
def rutaminima(catalogo, paisa, paisb): if m.contains(catalogo["paises"], paisa) and m.contains( catalogo["paises"], paisb): capa = m.get(catalogo["paises"], paisa)["value"]["CapitalName"] capb = m.get(catalogo["paises"], paisb)["value"]["CapitalName"] recorrido = djk.Dijkstra(catalogo["conexiones"], capa) sihay = djk.hasPathTo(recorrido, capb) if sihay: result = djk.distTo(recorrido, capb) else: result = "No hay camino." return result else: return "No hay data para uno(s) de los paises dados"
def ruta(strupa,areaInicio, areaFinal): ruta = [] dijsktra = djk.Dijkstra(strupa['uniones'],areaInicio) if djk.hasPathTo(dijsktra, areaFinal): ruta.append(areaInicio) ruta_lt = djk.pathTo(dijsktra, areaFinal) iterador = it.newIterator(ruta_lt) while it.hasNext(iterador): element = it.next(iterador) ruta.append(element['vertexB']) else: ruta = ["No", "hay", "ruta"] timet=djk.distTo(dijsktra,areaFinal) return (ruta,timet)