コード例 #1
0
def arcosXvertex(grafo,word):
    """
    Retorna arcos del vertice
    """
    a=gr.indegree(grafo,word)
    b=gr.outdegree(grafo,word)
    return a+b
コード例 #2
0
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)
コード例 #3
0
def stationsUsage(analyzer):
    indegreePQ = pq.newMinPQ(cmpfunction=compareDegreeMax)
    outdegreePQ = pq.newMinPQ(cmpfunction=compareDegreeMax)
    lessUsedPQ = pq.newMinPQ(cmpfunction=compareDegreeMin)
    vortexLst = gr.vertices(analyzer["graph"])
    ite = it.newIterator(vortexLst)

    while it.hasNext(ite):
        station = it.next(ite)
        StationName = getName(analyzer["stationinfo"], station)
        #Se obtienen los valores de las estaciones que entran, que salen y su suma

        indegree = gr.indegree(analyzer["graph"], station)
        outdegree = gr.outdegree2(analyzer["graph"], station)
        usage = outdegree + indegree
        #Se crean entradas para organizar en el PQ

        indegreeEntry = {"key": indegree, "station": StationName}
        outdegreeEntry = {"key": outdegree, "station": StationName}
        usageEntry = {"key": usage, "station": StationName}

        #Se inserta cada entrada en los PQ correspondientes
        pq.insert(indegreePQ, indegreeEntry)
        pq.insert(lessUsedPQ, usageEntry)
        pq.insert(outdegreePQ, outdegreeEntry)

    return {"In": indegreePQ, "Out": outdegreePQ, "Usage": lessUsedPQ}
コード例 #4
0
def getMSTroots(catalog, mst_graph):
    roots = lt.newList(datastructure='ARRAY_LIST')
    mst_vertices = gr.vertices(mst_graph)
    i = 0
    # * Ecuentra todas las 'raices' del MST (nodos/vertices con un indegree de 0)
    while i <= lt.size(mst_vertices):
        vertex = lt.getElement(mst_vertices, i)
        indegree = gr.indegree(mst_graph, vertex)
        outdegree = gr.outdegree(mst_graph, vertex)
        if indegree == 0 and outdegree > 0:  # Outdegree > 0 para asegurar que si se conecta con algo más
            lt.addLast(roots, vertex)
        i += 1

    longest_branch_dist = 0
    longest_branch_bfs = None
    # Por cada raiz que se econtro, calcula la rama más larga entre esta y una hoja. Guarda la rama más larga entre todas las rices.

    for root in lt.iterator(roots):
        info = longestBranch(catalog, mst_graph, root)
        if info[0] > longest_branch_dist:
            longest_branch_dist = info[0]
            end_vertex = info[1]
            longest_branch_bfs = info[2]

    path = bfs.pathTo(
        longest_branch_bfs,
        end_vertex)  # Camino entre la raiz y hoja de la rama más larga

    return path, longest_branch_dist
コード例 #5
0
def numEdges (analyzer, vertex):
    
    outdegree = gr.outdegree(analyzer['connections'], vertex)
    indegree = gr.indegree(analyzer['connections'], vertex)
    numedges = outdegree + indegree

    return numedges
コード例 #6
0
def requerimiento_3(citibike):
    lista = gr.vertices(citibike['grafo'])
    dicc1 = {}
    dicc2 = {}
    dicc3 = {}
    iterador = it.newIterator(lista)
    while it.hasNext(iterador):
        fila = it.next(iterador)
        out = gr.outdegree(citibike['grafo'], fila)
        ins = gr.indegree(citibike['grafo'], fila)
        dicc1[fila] = out
        dicc2[fila] = ins
        dicc3[fila] = out + ins
    salida = mayores(dicc1)
    llegada = mayores(dicc2)
    ambos = menores(dicc3)
    nombres_salida = encontrar(dicc1, salida)
    nombres_llegada = encontrar(dicc2, llegada)
    nombres_ambos = encontrar(dicc3, ambos)
    print("Las 3 mejores estaciones de salida son: ")
    nombresI(nombres_salida, citibike)
    print("\nLas 3 mejores estaciones de llegada son: ")
    nombresF(nombres_llegada, citibike)
    print("\nLas 3 peores estaciones de llegada/salida son: ")
    for i in range(0, 3):
        if mp.contains(citibike["namesI"], nombres_ambos[i]):
            z = m.get(citibike["namesI"], nombres_ambos[i])
            nombreX = en.getValue(z)
            nombreI = nombreX["nombre"]
            print(nombreI)
        else:
            z = m.get(citibike["namesF"], nombres_ambos[i])
            nombreX = en.getValue(z)
            nombreI = nombreX["nombre"]
            print(nombreI)
コード例 #7
0
def top3lessUsed(analyzer):
    totaltree = om.newMap(omaptype="RBT", comparefunction=compareIds)
    pqiterator = it.newIterator(vertexNames(analyzer))
    while it.hasNext(pqiterator):
        vert = int(it.next(pqiterator))
        salidas = gr.outdegree(analyzer["graph"], str(vert))
        destinos = gr.indegree(analyzer["graph"], str(vert))
        usototal = salidas + destinos
        if not om.contains(totaltree, usototal):
            om.put(totaltree, usototal, str(vert))
        else:
            A = om.get(totaltree, usototal)
            B = me.getValue(A)
            om.put(totaltree, usototal, str(B)+","+str(vert))
    estaciones = lt.newList(datastructure="ARRAY_LIST")
    while lt.size(estaciones) < 3:
        val = om.get(totaltree, om.minKey(totaltree))
        val1 = me.getValue(val)
        menortotal = val1.split(",")
        for i in menortotal:
            if lt.size(estaciones) < 3:
                K = m.get(analyzer["nameIndex"], i)
                L = me.getValue(K)
                lt.addLast(estaciones, L)
        om.deleteMin(totaltree)
    return estaciones
コード例 #8
0
def addConnection(citibike, origin, destination, duration):
    """
    Adiciona un arco entre dos estaciones
    """
    edge = gr.getEdge(citibike["graph"], origin, destination)
    if edge is None:
        gr.addEdge(citibike["graph"], origin, destination, duration)
        arrive = gr.indegree(citibike["graph"], destination)

    return citibike
コード例 #9
0
def addConnection(bikes, origin, destination, duration):
    edge = gr.getEdge(bikes["grafo"], origin, destination)
    if edge is None:
        gr.addEdge(bikes["grafo"], origin, destination, duration)
    else:
        initial = edge["weight"]
        edge["weight"] = ((int(initial) + int(duration)) / 2)
    llegada = gr.indegree(bikes["grafo"], destination)
    salida = gr.outdegree(bikes["grafo"], origin)
    llegadad = gr.indegree(bikes["grafo"], destination)
    salidad = salida = gr.outdegree(bikes["grafo"], origin)
    oruse = salida + llegadad
    desuse = llegada + salidad
    llegadainv = 1 / llegada
    salidainv = 1 / salida
    iminpq.increaseKey(bikes["topuso"], destination, desuse)
    iminpq.increaseKey(bikes["topuso"], origin, oruse)
    iminpq.decreaseKey(bikes["topllegada"], destination, llegadainv)
    iminpq.decreaseKey(bikes["topsalida"], origin, salidainv)
    return bikes
コード例 #10
0
def majorDestiny(grafo):
    intree = om.newMap(omaptype="RBT", comparefunction=compareIds)
    pqiterator = it.newIterator(vertexNamesAge(grafo))
    while it.hasNext(pqiterator):
        vert = it.next(pqiterator)
        salidas = gr.indegree(grafo, vert)
        om.put(intree, salidas, vert)
    if om.isEmpty(intree):
        return None
    else:
        mayor = om.get(intree, om.maxKey(intree))
        mayornombre = me.getValue(mayor)
        return mayornombre
コード例 #11
0
def criticalStations(analyzer):
    vertexs = gr.vertices(analyzer["connections"])
    indegree = mq.newMinPQ(compareinverted)
    outdegree = mq.newMinPQ(compareinverted)
    degree = mq.newMinPQ(comparenormal)
    iterator = it.newIterator(vertexs)
    res1 = lt.newList()
    res2 = lt.newList()
    res3 = lt.newList()
    while it.hasNext(iterator):
        element = it.next(iterator)
        ins = (element,int(gr.indegree(analyzer["connections"],element)))
        out = (element,int(gr.outdegree(analyzer["connections"],element)))
        deg = (element,int(gr.indegree(analyzer["connections"],element))+int(gr.outdegree(analyzer["connections"],element)))
        mq.insert(indegree,ins)
        mq.insert(outdegree,out)
        mq.insert(degree,deg)

    for a in range(1,4):
        lt.addLast(res1,mq.delMin(indegree))
        lt.addLast(res2,mq.delMin(outdegree))
        lt.addLast(res3,mq.delMin(degree)) 
        
    return (res1,res2,res3)
コード例 #12
0
def top3_estaciones_de_llegada(analyzer):
    "retorna el nombre de top3 estaciones de llegada"
    lista_vertices = gr.vertices(analyzer["connections"])
    first_iterator = it.newIterator(lista_vertices)
    dic_estaciones = {}
    while it.hasNext(first_iterator):
        estacion = it.next(first_iterator)
        viajes = gr.indegree(analyzer["connections"], estacion)
        dic_estaciones[estacion] = viajes
        estaciones = saber_los_mayores(dic_estaciones)
        rta_1 = buscar_info_estacion(estaciones[0], analyzer)
        rta_2 = buscar_info_estacion(estaciones[1], analyzer)
        rta_3 = buscar_info_estacion(estaciones[2], analyzer)
        rta = [rta_1["name"], rta_2["name"], rta_3["name"]]
        return rta
コード例 #13
0
def buscar_estaciones_top_ingreso(graph, reference_table):
    """"Funcion para hallar los viajes que llegan a una estacion!"""
    estaciones = lt.newList()
    vertices = gr.vertices(graph)
    it_vertice = it.newIterator(vertices)
    while it.hasNext(it_vertice):
        vert = it.next(it_vertice)
        estacion = gr.indegree(graph, vert)
        nombre = conversor_id_nombre(vert, reference_table)
        lt.addLast(estaciones, (estacion, nombre))
    merge.mergesort(estaciones, lessFunction)
    final_top = []
    for i in range(3):
        top = lt.lastElement(estaciones)
        final_top.append(top)
        lt.removeLast(estaciones)
    return final_top
コード例 #14
0
def tercera_consulta(citibike):
    tree = om.newMap(omaptype='RBT', comparefunction=compareroutes)
    diccionario = {}
    list_vertext = gr.vertices(citibike["graph"])
    ite = it.newIterator(list_vertext)
    while it.hasNext(ite):
        vertex = it.next(ite)
        arrive = gr.indegree(citibike["graph"], vertex)
        if arrive > 0:
            om.put(tree, arrive, vertex)
    l = []
    number = om.size(tree)
    resta = abs(number - 3)
    less = om.select(tree, resta)
    greater = om.maxKey(tree)
    ran = om.values(tree, less, greater)
    i = it.newIterator(ran)
    while it.hasNext(i):
        name = it.next(i)
        l.append(name)
    diccionario["llegadas"] = l

    tree_1 = om.newMap(omaptype='RBT', comparefunction=compareroutes)
    list_vertext_1 = gr.vertices(citibike["graph"])
    ite_1 = it.newIterator(list_vertext_1)
    while it.hasNext(ite_1):
        vertex_1 = it.next(ite_1)
        arrive_1 = gr.outdegree(citibike["graph"], vertex_1)
        if arrive_1 > 0:
            om.put(tree_1, arrive_1, vertex_1)
    print((citibike["graph"]))
    l_1 = []
    number_1 = om.size(tree_1)
    resta_1 = abs(number_1 - 3)
    less_1 = om.select(tree_1, resta_1)
    greater_1 = om.maxKey(tree_1)
    ran_1 = om.values(tree_1, less_1, greater_1)
    iterar = it.newIterator(ran_1)
    while it.hasNext(iterar):
        name_1 = it.next(iterar)
        l_1.append(name_1)
    diccionario["salidas"] = l_1

    return diccionario
コード例 #15
0
def buscar_estaciones_peor_top(graph, reference_table):
    """"Funcion para hallar los viajes que llegan a una estacion!"""
    estaciones = lt.newList()
    vertices = gr.vertices(graph)
    it_vertice = it.newIterator(vertices)
    while it.hasNext(it_vertice):
        vert = it.next(it_vertice)
        estacion = gr.indegree(graph, vert)
        estacion += gr.outdegree(graph, vert)
        lt.addLast(estaciones, (estacion, vert))
    merge.mergesort(estaciones, lessFunction)
    final_top = []
    for i in range(3):
        top = lt.firstElement(estaciones)
        nombre = conversor_id_nombre(top[1], reference_table,
                                     "end station name")
        final_top.append((top[0], nombre))
        lt.removeFirst(estaciones)
    return final_top
コード例 #16
0
def estacionesCriticas(analyzer):

    cuenta= 0
    estaciones= gr.vertices(analyzer["graph"])
    listaEntrada= lt.newList("ARRAY_LIST", comparestations)
    listaSalida= lt.newList("ARRAY_LIST", comparestations)
    listaSolitarias= lt.newList("ARRAY_LIST", comparestations)
    entradasConcurridas= lt.newList("ARRAY_LIST", compareSizes)
    salidasConcurridas= lt.newList("ARRAY_LIST", compareSizes)
    estacionesSolitarias= lt.newList("ARRAY_LIST", compareSizes)
    while cuenta<lt.size(estaciones):
        estacion= lt.getElement(estaciones, cuenta)
        entrada= gr.indegree(analyzer["graph"], estacion)        
        lt.addFirst(entradasConcurridas,entrada)
        salida= gr.outdegree(analyzer["graph"], estacion)
        lt.addFirst(salidasConcurridas,salida)
        bidireccional= gr.degree(analyzer["graph"], estacion)
        lt.addFirst(estacionesSolitarias,bidireccional)
        cuenta+= 1

    entradasOrg= sel.selectionSort(entradasConcurridas,lessequal)
    salidasOrg= sel.selectionSort(salidasConcurridas,lessequal)
    solitariasOrg= sel.selectionSort(estacionesSolitarias,lessequal)

    for conteo in range(0,3):
        if entrada == lt.getElement(entradasOrg, conteo):
            lt.insertElement(listaEntrada, estacion, conteo)
        if salida == lt.getElement(salidasOrg, conteo):
            lt.insertElement(listaSalida, estacion, conteo)
        if bidireccional == lt.getElement(solitariasOrg, conteo):
            lt.insertElement(listaSolitarias, estacion, conteo)
    if lt.size(listaEntrada) > 3:
        lt.removeLast(listaEntrada)
    if lt.size(listaSalida) > 3:
        lt.removeLast(listaSalida)
    if lt.size(listaSolitarias) > 3:
        lt.removeLast(listaSolitarias)

    return (listaEntrada, listaSalida, listaSolitarias)
コード例 #17
0
def servedRoutes(analyzer):
    iterador = it.newIterator(gr.vertices(analyzer["Arcos"]))
    lista = lt.newList()
    total = 0
    while it.hasNext(iterador):
        vertice = it.next(iterador)
        indegree = gr.indegree(analyzer["Arcos"], vertice)
        outdegree = gr.outdegree(analyzer["Arcos"], vertice)

        if indegree >= 1 and outdegree > 1:
            total += 1
            lt.addLast(lista, vertice)
    nombres = lt.newList()
    IDs = lt.newList()
    iterador_1 = it.newIterator(lista)
    while it.hasNext(iterador_1):
        elemento = it.next(iterador_1)
        pareja = mp.get(analyzer["paises_codigos"], elemento)
        valor = me.getValue(pareja)
        id = valor["landing_point_id"]
        name = valor["name"]
        lt.addLast(nombres, name)
        lt.addLast(IDs, id)
    return total, nombres, IDs
コード例 #18
0
def top3llegada(analyzer):
    intree = om.newMap(omaptype="RBT", comparefunction=compareIds)
    pqiterator = it.newIterator(vertexNames(analyzer))
    while it.hasNext(pqiterator):
        vert = int(it.next(pqiterator))
        llegadas = gr.indegree(analyzer["graph"], str(vert))
        if not om.contains(intree, llegadas):
            om.put(intree, llegadas, str(vert))
        else:
            A = om.get(intree, llegadas)
            B = me.getValue(A)
            om.put(intree, llegadas, str(B)+","+str(vert))
    estaciones = lt.newList(datastructure="ARRAY_LIST")
    while lt.size(estaciones) < 3:
        val = om.get(intree, om.maxKey(intree))
        val1 = me.getValue(val)
        mayorllegada = val1.split(",")
        for i in mayorllegada:
            if lt.size(estaciones) < 3:
                K = m.get(analyzer["nameIndex"], i)
                L = me.getValue(K)
                lt.addLast(estaciones, L)
        om.deleteMax(intree)
    return estaciones
コード例 #19
0
def entranviajes(grafo,word):
    """
    numero de arcos que entran al vertex (word)
    """
    return gr.indegree(grafo,word)
コード例 #20
0
def Estaciones_criticas(analyzer,vertice):

    
    vertices=gr.vertices(analyzer['connections']) 
    cont=it.newIterator(vertices)
    while it.hasNext(cont):
        
        llegada=lt.newList(datastructure='SINGLE_LINKED', cmpfunction=None) # llegada
        salida=lt.newList(datastructure='SINGLE_LINKED', cmpfunction=None) # salida
        menos= lt.newList(datastructure='SINGLE_LINKED', cmpfunction=None) # menos usadas
        
        if cont not in llegada :
            lleg=gr.indegree(grafo,cont)
            dato=stack.pop(lleg)
            lt.addLast(llegada, dato)
        if cont not in salida:
            sal=gr.outdegree(salida,cont)
            dato=stack.pop(sal)
            lt.addLast(salida,dato)
        if cont not in menos:
            tod=(gr.indegree(grafo,cont))+(gr.outdegree(salida,cont))
            dato=stack.pop(tod)
            lt.addLast(menos,dato)

        topl=lt.newList(datastructure='SINGLE_LINKED', cmpfunction=None)
        tops=lt.newList(datastructure='SINGLE_LINKED', cmpfunction=None)
        topu=lt.newList(datastructure='SINGLE_LINKED', cmpfunction=None)


        iter=it.newIterator(llegada)
        menor=1
            while it.hasNext(iter):
            if iter <=menor:
                menor=iter
                it.next(iter)
            lt.addLast(topl,menor)
        
        

        iter=it.newIterator(salida)
        menor=1
            while it.hasNext(iter):
            if iter <=menor:
                menor=iter
                it.next(iter)
            lt.addLast(tops,menor)

        iter=it.newIterator(menos)
        menor=1
            while it.hasNext(iter):
            if iter <=menor:
                menor=iter
                it.next(iter)
            lt.addLast(topu,menor)

            
        
        a= print("Estaciones top llegada: ",(for i in range(2)(topl)))
        b= print("estaciones top salida", (for i in range(2)(tops)))
        c= print("Estaciones menos usadas", (for i in range(2)(topu)))
        return a,b,c