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
Exemplo n.º 2
0
def RutasCirculares(analyzer, vertice, limiteInicial,
                    limiteFinal):  #REQUERIMIENTO 2
    peso = 0

    rutas_circulares_total = lt.newList(
        datastructure='SINGLE_LINKED',
        cmpfunction=None)  #agrupar todas las rutas cicrulares

    dijkstraIda = djk.Dijkstra(analyzer['connections'], vertice)
    vertices = gr.vertices(analyzer['connections'])

    iter2 = it.newIterator(vertices)
    while it.hasNext(iter2):
        datos_rutas = lt.newList(
            datastructure='SINGLE_LINKED',
            cmpfunction=None)  # info todas las rutas cicrulares
        ruta_circular = lt.newList(
            datastructure='SINGLE_LINKED', cmpfunction=None
        )  #lista de nombres de estaciones en la ruta circular
        vertice2 = it.next(iter2)
        caminos_ida = djk.pathTo(dijkstraIda,
                                 vertice2)  #grafo conocer vertices
        dijkstraVenida = djk.Dijkstra(analyzer['connections'], vertice2)
        caminos_venida = djk.pathTo(dijkstraVenida, vertice)
        if not caminos_venida or not caminos_ida:
            continue
        while not stack.isEmpty(caminos_ida):
            dato = stack.pop(caminos_ida)
            lt.addLast(ruta_circular, dato)

        while not stack.isEmpty(caminos_venida):
            dato = stack.pop(caminos_venida)
            lt.addLast(ruta_circular, dato)

    # lt.addLast(rutas_circulares_total, ruta_circular)

        iter = it.newIterator(ruta_circular)
        while it.hasNext(iter):
            arco = it.next(iter)
            duracion = arco['weight']
            if (int(limiteInicial) < duracion and duracion < int(limiteFinal)):
                estacion1 = m.get(analyzer['EstacionesXid'], arco['vertexA'])
                estacion2 = m.get(analyzer['EstacionesXid'], arco['vertexB'])
                lt.addLast(
                    datos_rutas, {
                        "estacion1": estacion1,
                        "estacion2": estacion2,
                        "duracion": duracion
                    })

        lt.addLast(rutas_circulares_total, datos_rutas)

    return (rutas_circulares_total)
Exemplo n.º 3
0
def caminoMenorCostoLp(analyzer, landingA, landingB):
    lpA = compareLpUserLpGraph(analyzer, landingA)
    lpB = compareLpUserLpGraph(analyzer, landingB)

    analyzer['paths'] = djk.Dijkstra(analyzer['connections'], lpA)
    camino = djk.pathTo(analyzer['paths'], lpB)
    return camino
Exemplo n.º 4
0
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
Exemplo n.º 5
0
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]
Exemplo n.º 6
0
def minimumCostPath(analyzer, vertexb):
    """
    Retorna la ruta de costo mínimo entre el punto de conexión
    inicial y un punto de conexión destino
    """
    paths = analyzer['minimumcostpaths']
    return djk.pathTo(paths, vertexb)
Exemplo n.º 7
0
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 getBestSchedule(graph, pickUp, dropOff, InitialTime, EndTime):
    bestSchedule = InitialTime
    currentStamp = InitialTime
    first = getTime(graph, pickUp, dropOff, currentStamp)
    bestTime = first[0]
    search = first[1]
    while currentStamp != EndTime:
        currentStamp = add15(currentStamp)
        time = getTime(graph, pickUp, dropOff, currentStamp)
        if time[0] < bestTime:
            bestSchedule = currentStamp
            bestTime = time[0]
            search = time[1]
    path = []
    pathTo = djk.pathTo(search, dropOff)
    if pathTo is None:
        path = None
    else:
        while not st.isEmpty(pathTo):
            edge = st.pop(pathTo)
            Com = edge["vertexA"]
            path.append(Com)
            if st.size(pathTo) == 0:
                Com2 = edge["vertexB"]
                path.append(Com2)
    return bestSchedule, path, bestTime
Exemplo n.º 9
0
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})
Exemplo n.º 10
0
def recomendadorRutas(analizador,limiteinf,limitesup):
    listvertices=gr.vertices(analizador['connections'])
    iterator=it.newIterator(listvertices)
    mostsalida=[None,0]
    mostllegada=[None,0]
    ruta=[]
    while it.hasNext(iterator):
        verticerevisado=it.next(iterator)
        ctotal=0
        ctotal2=0
        for age in range(limiteinf,limitesup+1):
            if m.contains(analizador['agestartrank'],verticerevisado):
                diccionario=m.get(analizador['agestartrank'],verticerevisado)['value']
                cantidad=diccionario.get(age,0)
                ctotal+=cantidad
            if m.contains(analizador['agefinishrank'],verticerevisado):
                diccionario2=m.get(analizador['agefinishrank'],verticerevisado)['value']
                cantidad2=diccionario2.get(age,0)
                ctotal2+=cantidad2
        if ctotal>mostsalida[1]:
            mostsalida[1]=ctotal
            mostsalida[0]=verticerevisado
        if ctotal2>mostllegada[1]:
            mostllegada[1]=ctotal2
            mostllegada[0]=verticerevisado
    if mostsalida[0] != mostllegada[0]:
        search=djk.Dijkstra(analizador['connections'],mostsalida[0])
        resultado=djk.pathTo(search,mostllegada[0])
        iterator=it.newIterator(resultado)
        while it.hasNext(iterator):
            informacion=it.next(iterator)
            ruta.append({'Desde':m.get(analizador['nameverteces'],informacion['vertexA'])['value'],'Hasta':m.get(analizador['nameverteces'],informacion['vertexB'])['value'],'Duracion':informacion['weight']/60})
    return ruta
Exemplo n.º 11
0
def requerimiento4(catalog):
    pri = prim.PrimMST(catalog['connections'])
    peso = prim.weightMST(catalog['connections'], pri)
    mst = prim.edgesMST(catalog['connections'], pri)['mst']
    m = folium.Map(location=[4.6, -74.083333], tiles="Stamen Terrain")
    for st in lt.iterator(mst):
        cv = st['vertexA'].split("-", 1)
        ce = st['vertexB'].split("-", 1)
        infov = mp.get(catalog['points'], cv[0])['value']
        infoe = mp.get(catalog['points'], ce[0])['value']
        addPointConneMst(catalog, st['vertexA'], st['vertexB'], st['weight'])
        folium.PolyLine(locations=[(float(infov['latitude']), float(infov['longitude'])), (float(infoe['latitude']), float(infoe['longitude']))], tooltip=str(cv[1])).add_to(m)
        folium.Marker([float(infov['latitude']),  float(infov['longitude'])], popup=str(infov['name'])).add_to(m)
        folium.Marker([float(infoe['latitude']),  float(infoe['longitude'])], popup=str(infoe['name'])).add_to(m)
    m.save('mapa_req4.html')
    gramst = catalog['mst']
    vert = gr.vertices(gramst)
    num = lt.size(vert)
    primero = lt.firstElement(vert)
    mayor = 0
    camino = None
    dijta = djk.Dijkstra(catalog['mst'], primero)
    for v in lt.iterator(vert):
        ruta = djk.pathTo(dijta, v)
        x = lt.size(ruta)
        if x > mayor:
            mayor = x
            camino = ruta
    return num, peso, camino
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 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)
Exemplo n.º 14
0
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
Exemplo n.º 15
0
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
Exemplo n.º 16
0
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.')
Exemplo n.º 17
0
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 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 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 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 minimumCostPath(bikes, vertice):
    """
    Retorna el camino de costo minimo entre la estacion de inicio
    y la estacion destino
    Se debe ejecutar primero la funcion minimumCostPaths
    """
    path = djk.pathTo(bikes['paths'], vertice)
    return path
def getShortestRoute(analyzer, station1, station2):
    """
    Busca la ruta más corta con algoritmo
    dijsktra as djk
    """
    search = djk.Dijkstra(analyzer, station1)
    queuePath = djk.pathTo(search, station2)
    return queuePath
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
Exemplo n.º 24
0
def minimumCostPath(analyzer, destStation):
    """
    Retorna el camino de costo minimo entre la estacion de inicio
    y la estacion destino
    Se debe ejecutar primero la funcion minimumCostPaths
    """
    path = djk.pathTo(analyzer['paths'], destStation)
    return path
Exemplo n.º 25
0
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
Exemplo n.º 26
0
def viaje_por_coordenadas(analyzer, latitud_origen, longitud_origen,
                          latitud_destino, longitud_destino):
    estacion_llegada = analyzer['connections'][latitud_destino][
        longitud_destino]
    respuesta = djk.pathTo(
        analyzer['connections'][latitud_origen][longitud_origen],
        estacion_llegada)
    return respuesta
Exemplo n.º 27
0
def minimumCostPath(citibike,station):
    """
    Retorna el camino de costo mínimo entre la estacion de inicio
    y la estacion destino
    Se debe ejecutar primero la funcion minimumCostPaths
    """
    path = djk.pathTo(citibike['paths'],station)
    return path
Exemplo n.º 28
0
def minimumCostPath(analyzer, final, ini):
    """
    Retorna el camino de costo minimo entre la capital de inicio
    y la capital destino
    Se debe ejecutar primero la funcion minimumCostPaths
    """

    countries = analyzer['countries']
    countryKeys = m.keySet(countries)
    points = analyzer['points']
    iniInfo = me.getValue(m.get(countries, ini))
    iniLat = iniInfo['CapitalLatitude']
    iniLon = iniInfo['CapitalLongitude']
    iniLoc = iniLat, iniLon
    iniName = iniInfo['CountryName'] + ', ' + iniInfo['CapitalName']
    M = folium.Map()
    folium.Marker(iniLoc, iniName, icon=folium.Icon(color='purple')).add_to(M)
    destCapital = final['CapitalName']
    desLat = final['CapitalLatitude']
    desLon = final['CapitalLongitude']
    desLoc = desLat, desLon
    desName = final['CountryName'] + ', ' + final['CapitalName']
    folium.Marker(desLoc, desName, icon=folium.Icon(color='purple')).add_to(M)
    path = djk.pathTo(analyzer['paths'], destCapital)
    for i in range(0, lt.size(path)):
        camino = lt.getElement(path, i)
        punto = camino['vertexB']
        code = punto.split('*')[0]
        try:
            int(code)
            lPoint = me.getValue(m.get(points, code))
            pointLat = lPoint['latitude']
            pointLon = lPoint['longitude']
            pointLoc = pointLat, pointLon
            name = str(i) + '. ' + lPoint['name']
            folium.Marker(pointLoc, name,
                          icon=folium.Icon(color='blue')).add_to(M)
        except:
            capital = code
            n = 0
            found = False
            while n < lt.size(countryKeys) and found == False:
                key = lt.getElement(countryKeys, n + 1)
                info = me.getValue(m.get(countries, key))
                Capital = info['CapitalName']
                if capital == Capital:
                    found = True
                    country = info['CountryName']
                    capLat = info['CapitalLatitude']
                    capLon = info['CapitalLongitude']
                    capLoc = capLat, capLon
                    capName = str(i) + '. ' + country + ', ' + capital
                    folium.Marker(capLoc,
                                  capName,
                                  icon=folium.Icon(color='blue')).add_to(M)
                n += 1
    M.save('path.html')
    return path
Exemplo n.º 29
0
def IP(ana, IP1, IP2):
    congr = ana['connections']
    countries = ana['countries']
    countryKeys = m.keySet(countries)
    points = ana['points']
    info1 = ipapi.location(IP1)
    hav1 = {'latitude': info1['latitude'], 'longitude': info1['longitude']}
    info2 = ipapi.location(IP2)
    if IP2 == '8.8.8.8':
        lat2 = -122.08286045229197
        lon2 = 37.417661109182816
        hav2 = {'latitude': lat2, 'longitude': lon2}
    else:
        hav2 = {'latitude': info2['latitude'], 'longitude': info2['longitude']}
    vertices = gr.vertices(congr)
    point1 = None
    point2 = None
    menor1 = 9999999999999
    menor2 = 9999999999999
    for i in range(0, lt.size(vertices)):
        vert = lt.getElement(vertices, i)
        code = vert.split('*')[0]
        try:
            int(code)
            lPoint = me.getValue(m.get(points, code))
            dist1 = haversine(hav1, lPoint)
            dist2 = haversine(hav2, lPoint)
            if dist1 < menor1:
                menor1 = dist1
                point1 = vert
            if dist2 < menor2:
                menor2 = dist2
                point2 = vert
        except:
            capital = code
            n = 0
            found = False
            while n < lt.size(countryKeys) and found == False:
                key = lt.getElement(countryKeys, n + 1)
                info = me.getValue(m.get(countries, key))
                Capital = info['CapitalName']
                if capital == Capital:
                    found = True
                    capLat = info['CapitalLatitude']
                    capLon = info['CapitalLongitude']
                    hav = {'latitude': capLat, 'longitude': capLon}
                    dist1 = haversine(hav1, hav)
                    dist2 = haversine(hav2, hav)
                    if dist1 < menor1:
                        menor1 = dist1
                        point1 = vert
                    if dist2 < menor2:
                        menor2 = dist2
                        point2 = vert
                n += 1
    ana['IPs'] = djk.Dijkstra(ana['connections'], point1)
    path = djk.pathTo(ana['IPs'], point2)
    return path, point1, point2
Exemplo n.º 30
0
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