def req5(citibike, edad): if edad in range(0, 11): key = '0-10' elif edad in range(11, 21): key = '11-20' elif edad in range(21, 31): key = '21-30' elif edad in range(31, 41): key = '31-40' elif edad in range(41, 51): key = '41-50' elif edad in range(51, 61): key = '51-60' else: key = '60+' iterador = it.newIterator(m.keySet(citibike['stops'])) estacion_salida = 'Ninguna' max_salida = 0 estacion_llegada = 'Ninguna' llegada_2 = 'Ninguna' max_llegada = 0 while it.hasNext(iterador): element = it.next(iterador) dicc = m.get(citibike['stops'], element) salida = dicc['value'][2] llegada = dicc['value'][3] if salida[key] > max_salida: max_salida = salida[key] estacion_salida = dicc['key'] if llegada[key] > max_llegada: llegada_2 = estacion_llegada max_llegada = llegada[key] estacion_llegada = dicc['key'] if estacion_llegada == estacion_salida: estacion_llegada = llegada_2 ruta = [] dijsktra = djk.Dijkstra(citibike['graph'], str(estacion_salida)) if djk.hasPathTo(dijsktra, estacion_llegada): if djk.hasPathTo(dijsktra, estacion_llegada): ruta_lt = djk.pathTo(dijsktra, estacion_llegada) iterador = it.newIterator(ruta_lt) ruta.append(estacion_salida) while it.hasNext(iterador): element = it.next(iterador) ruta.append(element['vertexB']) else: ruta = 'No hay ruta' return (estacion_salida, estacion_llegada, ruta)
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 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 minimum_path(analyzer, pais1, pais2): #req 3 """ Calcula los caminos de costo mínimo desde la estacion initialStation a todos los demas vertices del grafo """ countries = analyzer['countries'] capital1 = m.get(countries, pais1)['value']['CapitalName'] cable1 = lt.getElement( m.get(analyzer['landing_points_cables'], capital1)['value'], 1) verta = format_vertex(capital1, cable1) capital2 = m.get(countries, pais2)['value']['CapitalName'] cable2 = lt.getElement( m.get(analyzer['landing_points_cables'], capital2)['value'], 1) vertb = format_vertex(capital2, cable2) path = None camino = None total = 0 analyzer['paths'] = djk.Dijkstra(analyzer['connections'], verta) if djk.hasPathTo(analyzer['paths'], vertb): path = djk.pathTo(analyzer['paths'], vertb) camino = lt.newList('ARRAY_LIST') for arco in lt.iterator(path): landing_id1 = arco['vertexA'].split('~')[0] landing_name1 = m.get(analyzer['landing_points_info'], landing_id1)['value']['name'] landing_id2 = arco['vertexB'].split('~')[0] landing_name2 = m.get(analyzer['landing_points_info'], landing_id2)['value']['name'] distance = arco['weight'] total += distance if landing_id1 != landing_id2: entry = (landing_name1, landing_name2, distance) lt.addLast(camino, entry) return camino, total
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 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 MejorHora(Taxis, límite_Inferior, límite_Superior, vertexA, vertexB): Mejor = 200000 lstHours = lt.newList("SINGLE_LINKED") for i in Taxis["lst"]: timeHash = datetime.datetime.strptime(i, "%H:%M") if (timeHash.hour > límite_Inferior.hour) and (timeHash.hour < límite_Superior.hour): lt.addLast(lstHours, timeHash) if (timeHash.hour == límite_Inferior.hour and timeHash.minute >= límite_Inferior.minute): lt.addLast(lstHours, timeHash) if (timeHash.hour == límite_Superior and timeHash.minute <= límite_Superior.minute): lt.addLast(lstHours, timeHash) listiterator = it.newIterator(lstHours) while it.hasNext(listiterator): start_time = it.next(listiterator) Graph = me.getValue(m.get(Taxis["Hash"], start_time.time())) dijsktra = djk.Dijkstra(Graph, vertexA) if djk.hasPathTo(dijsktra, vertexB): path = djk.pathTo(dijsktra, vertexB) path = lt.firstElement(path) if path["weight"] < Mejor: Mejor = path["weight"] Tiempo = start_time.time() return (Tiempo, Mejor)
def hasPathTo(analyzer, vertexb): """ Retorna si existe una ruta entre el punto de conexión inicial y un punto de conexión destino """ paths = analyzer['minimumcostpaths'] return djk.hasPathTo(paths, vertexb)
def minimumDistanceCountries(catalog, capital_1, capital_2): """ Usa el algoritmo de Dijkstra para calcular los caminos mas baratos desde la capital 1 Luego, con la estructura del Dijstra revisa si hay un camino entre la capital 1 y la capital 2 """ catalog['paths'] = djk.Dijkstra(catalog['internet_graph'], capital_1) path_exists = djk.hasPathTo(catalog['paths'], capital_2) path = djk.pathTo(catalog['paths'], capital_2) return path
def CaminoMasCorto(latO, lonO, latD, lonD, analyzer): EstacionInicio = EstaciónMasProxima(latO, lonO, analyzer) EstacionMeta = EstaciónMasProxima(latD, lonD, analyzer) M = djk.Dijkstra(analyzer["graph"], EstacionInicio[1]) if djk.hasPathTo(M, EstacionMeta[1]): F = djk.pathTo(M, EstacionMeta[1]) return F else: return False
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 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 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 hasPath(analyzer, paisB): """ Indica si existe un camino desde el país base a país B. Se debe ejecutar primero la funcion minimumCostPaths """ capitalPaisB = mp.get(analyzer["countries"], paisB)["value"] # PAIS B nombrePaisB = capitalPaisB['CapitalName'] + '-' + capitalPaisB[ 'CountryName'] return dijsktra.hasPathTo( analyzer['paths'], nombrePaisB) # Se confirma que exista un camnino entre paísA y paísB
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)
def recommendedPaths(bikes, edad): old = changeyear(edad) entry = m.get(bikes["mayoressalida"], old) value = me.getValue(entry) vertex1 = value["vertex"] entry = m.get(bikes["mayoresllegada"], old) value = me.getValue(entry) vertex2 = value["vertex"] dijsktra = djk.Dijkstra(bikes["grafo"], vertex1) if djk.hasPathTo(dijsktra, vertex2): path = djk.pathTo(dijsktra, vertex2) return (path) else: return ("Se produjo un error")
def requerimiento6(paralati, paralongi, paralatf, paralongf, graph, maplonglat, mapid): coordenadaini = (float(paralati), float(paralongi)) coordenadafin = (float(paralatf), float(paralongf)) vertices = m.keySet(maplonglat) difeinicial = float("inf") idinicial = 0 difefinal = float("inf") idfinal = 0 for i in range(1, m.size(maplonglat) + 1): vertice = lt.getElement(vertices, i) llavevalor = m.get(maplonglat, vertice) coordenada = me.getValue(llavevalor) ide = me.getKey(llavevalor) diferenciaini = hv(coordenadaini, coordenada) diferenciafinal = hv(coordenadafin, coordenada) if diferenciaini <= difeinicial: difeinicial = diferenciaini idinicial = ide if diferenciafinal <= difefinal: difefinal = diferenciafinal idfinal = ide nombrefinal = m.get(mapid, idfinal) nombrefinal = me.getValue(nombrefinal) nombreinicial = m.get(mapid, idinicial) nombreinicial = me.getValue(nombreinicial) source = djk.Dijkstra(graph, idinicial) exist = djk.hasPathTo(source, idfinal) if nombrefinal == nombreinicial: retorno = ( "La estacion más cercana de su ubicación y su lugar de interés es la misma: " + nombrefinal) elif exist: retorno = {} retorno["estacioninicial"] = nombreinicial retorno["estacionfinal"] = nombrefinal retorno["tiempo"] = djk.distTo(source, idfinal) retorno["ruta"] = djk.pathTo(source, idfinal) else: retorno = ("Estacion cercana a usted: " + nombreinicial + ", estación cercana a su sitio de interés:" + nombrefinal + ". " " No existe camino entre " + nombreinicial + " y " + nombrefinal) return retorno
def RutaMasRapida(analyzer, rangoA, rangoB, origen, destino): origen = origen+".0" destino = destino+".0" Lista = gr.vertices(analyzer["Grafo por CA"]) ite = it.newIterator(Lista) while it.hasNext(ite): A = it.next(ite) B = A.split("-") if B[0] == origen and RangodeHorayMinuto(rangoA, rangoB, B[1]): N = djk.Dijkstra(analyzer["Grafo por CA"], A) ite2 = it.newIterator(Lista) while it.hasNext(ite2): C = it.next(ite2) D = C.split("-") if D[0] == destino and djk.hasPathTo(N, C): return [djk.pathTo(N, C), djk.distTo(N, C)]
def max_rama(mst): grafo = mst['grafo'] max_rama = 0 for vertice1 in lt.iterator(gr.vertices(grafo)): dijsktra = djk.initSearch(grafo, vertice1) # print('iniciando dijsktra para el vertice {}'.format(vertice1)) for vertice2 in lt.iterator(gr.vertices(grafo)): # print('revisando camino hacia el vertice {}'.format(vertice2)) if not vertice1 == vertice2: if djk.hasPathTo(dijsktra, vertice2): # print('el vertice {} tiene camino'.format(vertice2)) rama = djk.distTo(dijsktra, vertice2) # print(rama) if rama > max_rama: max_rama = rama return max_rama
def recommendedPathsBono(bikes, edad): paths = lt.newList('SINGLE_LINKED') old = int(edad) VerticeA = (me.getValue(m.get(bikes["ageTrips"], old)))["VerticeA"] lstVerticeA = it.newIterator(VerticeA) while it.hasNext(lstVerticeA): vertex1 = it.next(lstVerticeA) VerticeB = (me.getValue(m.get(bikes["ageTrips"], old)))["VerticeB"] lstVerticeB = it.newIterator(VerticeB) while it.hasNext(lstVerticeB): vertex2 = it.next(lstVerticeB) vertex1 = it.next(lstVerticeA) dijsktra = djk.Dijkstra(bikes["grafo"], vertex1) if djk.hasPathTo(dijsktra, vertex2): path = djk.pathTo(dijsktra, vertex2) lt.addLast(paths, path) return (paths)
def sixthRequirement(analyzer, latitud, longitud, latitud2, longitud2): grafo = analyzer['graph'] station1 = getCloserStation(analyzer, latitud, longitud) station2 = getCloserStation(analyzer, latitud2, longitud2) mpa = djk.Dijkstra(grafo, station1) ruta = None distance = -1 if djk.hasPathTo(mpa, station2): distance = djk.distTo(mpa, station2) ruta = djk.pathTo(mpa, station2) dict = { "ruta": ruta, "origen": station1, "destino": station2, "duracion": distance } return dict
def parteC(analyzer, zonaSalida, zonaLlegada, horaInicial, horaFinal): lstVertices = gr.vertices(analyzer["grafoAreas"]) lstvertorg = lt.newList('ARRAY_LIST', compareElements) lstvertlle = lt.newList('ARRAY_LIST', compareElements) mindist = 0 minestorg = "" minroute = None lstit = it.newIterator(lstVertices) while it.hasNext(lstit) == True: sig = it.next(lstit) sigdiv = sig.split() sigArea = sigdiv[0] sigHora = sigdiv[1] if sigArea == zonaSalida and sigHora >= horaInicial and sigHora <= horaFinal: lt.addLast(lstvertorg, sig) elif sigArea == zonaLlegada: lt.addLast(lstvertlle, sig) lstitver = it.newIterator(lstvertorg) while it.hasNext(lstitver) == True: vertorg = it.next(lstitver) #print(vertorg) analyzer['paths'] = djk.Dijkstra(analyzer['paths'], vertorg) lstirlle = it.newIterator(lstvertlle) while it.hasNext(lstvertlle) == True: vertdes = it.next(lstvertlle) if djk.hasPathTo(analyzer['paths'], vertdes) == True: dist = djk.distTo(analyzer['paths'], vertdes) if dist < mindist: mindist = dist minestorg = vertorg minroute = djk.pathTo(analyzer['paths'], vertdes) analyzer["paths"] = None #print(minestorg) divmin = minestorg.split() #print(divmin) hora = divmin[1] if minroute is not None: cadena= "La mejor hora para partir de la zona "+zonaSalida+" a "+zonaLlegada+" es "+hora+", con una duración de "\ +str(mindist)+" segundos, esta es la ruta recomendada para llegar a su destino: \n" + minroute elif minroute == None: cadena = "No hay una ruta disponible para llegar a su destino desde su ubicación" return cadena
def Req3MejorHorario(chicagoAnalyzer, inferior, superior, idStart, idEnd): """ Req C\n Returns: Tiempo de inicio del trayecto, las community areas en medio del trayecto, la duracion del trayecto """ #Si no contiene el vertice el proceso se corta de raiz y no hace mas operaciones innecesarias DE MORGAN if not (gr.containsVertex(chicagoAnalyzer['communityTrip'], idStart) and gr.containsVertex(chicagoAnalyzer['communityTrip'], idStart)): return 0 #Lista con las community areas, se entregara como parte de la respuesta comRoute = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareDict) #Conseguir los viajes que sucedieron en el rango de hora especificado keysInRange = om.keys(chicagoAnalyzer['timeTrip'], inferior, superior) #Si el rango de horas no contiene alguna hora de trayecto if (lt.isEmpty(keysInRange)): return 1 #Dijkstra para conseguir la duracion y las comunnity areas para llegar al destino structure = djk.Dijkstra(chicagoAnalyzer['communityTrip'], idStart) tripDuration = djk.distTo(structure, idEnd) path = djk.pathTo(structure, idEnd) if djk.hasPathTo( structure, idEnd) else st.newStack() #Se usa _ porque la variable no importa en si, solo es necesario hacerle pop al stack for _ in range(st.size(path)): lt.addLast(comRoute, st.pop(path)) #Para conseguir el tiempo en formato Hora:Minuto #Dado que hay dos for anidados, en comparacion a la complejidad del resto del algoritmo startTime = None for time in range(lt.size(keysInRange)): #starTime antes de hacerle format startTimeb4F = lt.getElement(keysInRange, time) route = om.get(chicagoAnalyzer['timeTrip'], startTimeb4F)['value'] #Para conseguir la id del trayecto y con la funcion de getEdgebyTripID() se conseguir ambos vertices for timeID in range(lt.size(route)): start, end = getEdgebyTripID(chicagoAnalyzer, lt.getElement(route, timeID)) #Verificar que sea el arco que buscamos if start == idStart and lt.isPresent(comRoute, end): startTime = f'{startTimeb4F.hour:02}:{startTimeb4F.minute:02}' return startTime, comRoute, tripDuration return startTime, comRoute, tripDuration
def touristInterestPath(bikes, strcoord, endcoord): rbt = bikes["stationtree"] values = {"list": None} values["list"] = lt.newList('SINGLELINKED', rbt['cmpfunction']) distance = 0.01 while lt.size(values["list"]) == 0: values = keyrange(rbt['root'], lat(-distance, float(strcoord["lat"])), lat(distance, float(strcoord["lat"])), values, strcoord, distance) distance += 0.01 menor = 500000000000000000000000000000000 id = "" tops = it.newIterator(values["list"]) while it.hasNext(tops): eachtop = it.next(tops) if haversine(float(eachtop["lat"]), float(eachtop["lon"]), float(strcoord["lat"]), float(strcoord["lat"])) < menor: menor = haversine(float(eachtop["lat"]), float(eachtop["lon"]), float(strcoord["lat"]), float(strcoord["lat"])) id = eachtop["id"] estacioninicio = str(int(id)) values["list"] = lt.newList('SINGLELINKED', rbt['cmpfunction']) distance = 0.01 while lt.size(values["list"]) == 0: values = keyrange(rbt['root'], lat(-distance, float(endcoord["lat"])), lat(distance, float(endcoord["lat"])), values, endcoord, distance) distance += 0.01 menor = 500000000000000000000000000000000 id = "" tops = it.newIterator(values["list"]) while it.hasNext(tops): eachtop = it.next(tops) if haversine(float(eachtop["lat"]), float(eachtop["lon"]), float(endcoord["lat"]), float(endcoord["lat"])) < menor: menor = haversine(float(eachtop["lat"]), float(eachtop["lon"]), float(endcoord["lat"]), float(endcoord["lat"])) id = eachtop["id"] estacionfinal = str(int(id)) dijsktra = djk.Dijkstra(bikes["grafo"], estacioninicio) if djk.hasPathTo(dijsktra, estacionfinal): path = djk.pathTo(dijsktra, estacionfinal) return path else: return {"start": estacioninicio, "end": estacionfinal}
def req6(citibike, lon1, lat1, lon2, lat2): mapa = { "masCercanaStart": None, "masCercanaEnd": None, "tiempo": 0, "estaciones": None } StartStation = estacionMasCercana(citibike, lon1, lat1) EndStation = estacionMasCercana(citibike, lon2, lat2) search = djk.Dijkstra(citibike["graph"], StartStation) if djk.hasPathTo(search, EndStation): mapa["tiempo"] = str(djk.distTo(search, EndStation)) mapa["estaciones"] = djk.pathTo(search, EndStation) else: mapa["tiempo"] = "Infinito" mapa["masCercanaStart"] = StartStation mapa["masCercanaEnd"] = EndStation return mapa
def recomendadorRutas(analyzer, edad): #Req. 5 funcion_hash = hash_function(edad) dic_estaciones_inicio = estacionesinicio(analyzer) dic_estaciones_final = estacionesfin(analyzer) max_inicio = maximoinicio(dic_estaciones_inicio) max_final = maximofinal(dic_estaciones_final) estacion_inicio = str(max_inicio[str(funcion_hash)]) #int: estacion_final = str(max_final[str(funcion_hash)]) # int: orden = djk.Dijkstra(analyzer['graph'], estacion_inicio) ans = [] camino = djk.hasPathTo(orden, estacion_final) if camino == True: res = djk.pathTo(orden, estacion_final) iterator = it.newIterator(res) while it.hasNext(iterator): vertice = it.next(iterator)['vertexB'] ans.append(vertice) return (estacion_inicio, estacion_final, ans)
def requerimiento3(analyzer, horainicio, horafinal, communityareainicio, communityareafinal): listavertices = gr.vertices(analyzer["grafo"]) listainiciales = lt.newList("ARRAY_LIST") listafinales = lt.newList("ARRAY_LIST") distToMenor = float('inf') verticeinicialmenor = "" verticefinalmenor = "" for i in range(1, lt.size(listavertices) + 1): vertex = lt.getElement(listavertices, i) vertexlista = vertex.split("-") vertice = float(vertexlista[0]) if vertice == communityareainicio: lt.addLast(listainiciales, vertex) elif vertice == communityareafinal: lt.addLast(listafinales, vertex) for i in range(1, lt.size(listainiciales) + 1): verticeinicial = lt.getElement(listainiciales, i) daistra = djk.Dijkstra(analyzer["grafo"], verticeinicial) for j in range(1, lt.size(listafinales) + 1): verticefinal = lt.getElement(listafinales, j) if djk.hasPathTo(daistra, verticefinal): distancia = djk.distTo(daistra, verticefinal) if distancia < distToMenor: distToMenor = distancia verticeinicialmenor = verticeinicial verticefinalmenor = verticefinal daistra = djk.Dijkstra(analyzer["grafo"], verticeinicialmenor) rutapila = djk.pathTo(daistra, verticefinalmenor) ruta = lt.newList("ARRAY_LIST") for j in range(1, stack.size(rutapila) + 1): k = stack.pop(rutapila) lt.addLast(ruta, k) retorno = lt.newList("ARRAY_LIST") lt.addLast(retorno, distToMenor) lt.addLast(retorno, ruta) analyzer['grafo'] = gr.newGraph(datastructure='ADJ_LIST', directed=True, size=300, comparefunction=comparecompany) return retorno
def req6(citibike, lat1, lon1, lat2, lon2): iterador = it.newIterator(m.keySet(citibike['stops'])) radio_salida = 10000 radio_llegada = 10000 estacion_salida = '' estacion_llegada = '' while it.hasNext(iterador): llave = it.next(iterador) diccCoord = m.get(citibike['stops'], llave) lat = diccCoord['value'][0] lon = diccCoord['value'][1] haver_salida = (math.sin(math.radians((lat - lat1)) / 2))**2 \ + math.cos(math.radians(lat)) \ * math.cos(math.radians(lat)) \ * (math.sin(math.radians((lon - lon1)) / 2))**2 d_s = 2 * 6371 * math.asin(math.sqrt(haver_salida)) if d_s <= radio_salida: radio_salida = d_s estacion_salida = diccCoord['key'] haver_llegada = (math.sin(math.radians((lat - lat2)) / 2))**2 \ + math.cos(math.radians(lat)) \ * math.cos(math.radians(lat)) \ * (math.sin(math.radians((lon - lon2)) / 2))**2 d_ll = 2 * 6371 * math.asin(math.sqrt(haver_llegada)) if d_ll <= radio_llegada: radio_llegada = d_ll estacion_llegada = diccCoord['key'] if estacion_llegada != '' and estacion_salida != '': ruta = [] dijsktra = djk.Dijkstra(citibike['graph'], str(estacion_salida)) if djk.hasPathTo(dijsktra, estacion_llegada): ruta_lt = djk.pathTo(dijsktra, estacion_llegada) iterador = it.newIterator(ruta_lt) ruta.append(estacion_salida) while it.hasNext(iterador): element = it.next(iterador) ruta.append(element['vertexB']) else: ruta = 'No hay ruta' return (estacion_salida, estacion_llegada, ruta)