示例#1
0
def resistencia(graph, tiempo, estacion_inicio):
    rutas = lt.newList(comparar_data)
    borrar = lt.newList(comparar_data)
    estaciones = adj.adjacents(graph['grafo'], estacion_inicio)
    ite = it.newIterator(estaciones)
    no_repetir = m.newMap(numelements=17,
                          prime=109345121,
                          maptype='CHAINING',
                          loadfactor=0.5,
                          comparefunction=comparar_data)
    m.put(no_repetir, estacion_inicio, 1)
    while (it.hasNext(ite)):
        est = it.next(ite)
        edg = adj.getEdge(graph['grafo'], estacion_inicio, est)
        duracion = edg["weight"]
        if duracion < (tiempo * 60) and m.contains(no_repetir, est) == False:
            ruta = {}
            ruta["Estacion_final"] = est
            ruta["Estacion_inicio"] = estacion_inicio
            ruta["tiempo"] = duracion
            lt.addLast(rutas, ruta)
            lt.addLast(borrar, ruta)
            m.put(no_repetir, est, 1)
    ite2 = it.newIterator(borrar)
    while (it.hasNext(ite2)):
        est2 = it.next(ite2)
        estaciones2 = adj.adjacents(graph['grafo'], est2["Estacion_final"])
        ite3 = it.newIterator(estaciones2)
        while (it.hasNext(ite3)):
            est3 = it.next(ite3)
            edg2 = adj.getEdge(graph['grafo'], est2["Estacion_final"], est3)
            if m.contains(no_repetir, est3) == False:
                if "Tiempo_acumulado" not in est2.keys():
                    tiempo_acumulado = edg2["weight"] + est2["tiempo"]
                    if tiempo_acumulado < (tiempo * 60):
                        ruta = {}
                        ruta["Estacion_final"] = est3
                        ruta["Estacion_inicio"] = est2["Estacion_final"]
                        ruta["tiempo"] = edg2["weight"]
                        ruta["tiempo_acumulado"] = tiempo_acumulado
                        lt.addLast(rutas, ruta)
                        lt.addLast(borrar, ruta)
                        m.put(no_repetir, est3, 1)
                else:
                    tiempo_acumulado = edg2["weight"] + est2["tiempo_acumulado"]
                    if tiempo_acumulado < (tiempo * 60):
                        ruta = {}
                        ruta["Estacion_final"] = est3
                        ruta["Estacion_inicio"] = est2["Estacion_final"]
                        ruta["tiempo"] = edg2["weight"]
                        ruta["tiempo_acumulado"] = tiempo_acumulado
                        lt.addLast(rutas, ruta)
                        lt.addLast(borrar, ruta)
                        m.put(no_repetir, est3, 1)
            lt.removeFirst(borrar)
    return rutas
示例#2
0
def req2(analyzer):

    maximo=0
    #para manipular el mapa en formato html (mas que todo por si se hacen los bonos)
    ma=folium.Map()
    lis=lt.newList()
    lista = mp.keySet(analyzer['landingpoints'])
    for a in lt.iterator(lista):
        cont=0
        for b in lt.iterator(analyzer['list']):
            c = b.split("*")
            c = c[0]
            if a==c:
                x = adj.adjacents(analyzer['connections'], b):
                numero=lt.size(x)
                cont+= num
        if cont > maximo:
            maximo=cont
            dato=x
    dato1=mp.get(analyzer['landingpoints'],dato)
    valor= me.getValue(dato1)
    p1lat=float(valor['elements'][0]['latitude'])
    p1lon=float(valor['elements'][0]['longitude'])
    lp1(valor['elements'][0]['name'])
    #se crea el folio con los datos 
    folium.Marker(location=[p1lat,p1lon], popup=lp1).add_to(ma)

    for a in lt.iterator(analyzer['list']):
        b=x.split("*")
        b=b[0]
        if b==dato1:
            x= adj.adjacents(analyzer['connections'], a)
            for c in lt.iterator(x):
                c=c.split("*")
                c=c[0]
                if mp.contains(analyzer['landingpoints'],c):
                    dato2=mp.get(analyzer['landingpoints'],c)
                    valor2=me.getValue(dato2)
                p2lat=float(valor2['elemnts'][0]['latitude'])
                p2lon=float(valor2['elements'][0]['longitude'])
                lp2=(valor2['elements'][0]['name'])
                folium.Marker(location=[p2lat,p2lon], popup=lp2).add_to(ma)
                #Para que las lineas se añadan al folio como marcadores (necesita la ubicacion, peso y color)
                al=folium.PolyLine(locations=[(p1lat,p1lon),(p2lat,p2lon)],weight=2,color = 'blue')
                ma.add_child(al)

            if lt.isPresent(lis,a)==0:
                lt.addLast(lis,a)
    print("Cables conectados: " +str(maximo))
    print("Lista de landing points: " +str(lis))
    return maximo, lis
示例#3
0
def dfsVertex(search, graph, vertex):
    """
    Funcion auxiliar para calcular un recorrido DFS
    Args:
        search: Estructura para almacenar el recorrido
        vertex: Vertice de inicio del recorrido.
    Returns:
        Una estructura para determinar los vertices
        conectados a source
    Raises:
        Exception
    """
    try:
        adjlst = g.adjacents(graph, vertex)
        adjslstiter = it.newIterator(adjlst)
        while (it.hasNext(adjslstiter)):
            w = it.next(adjslstiter)
            visited = map.get(search['visited'], w)
            if visited is None:
                map.put(search['visited'],
                        w, {'marked': True, 'edgeTo': vertex})
                dfsVertex(search, graph, w)
        return search
    except Exception as exp:
        error.reraise(exp, 'dfs:dfsVertex')
示例#4
0
def dfsVertexSCC(search, graph, vertex, scc):
    """
    Funcion auxiliar para calcular un recorrido DFS
    Args:
        search: Estructura para almacenar el recorrido
        vertex: Vertice de inicio del recorrido.
        scc: Una lista que contiene los vértices que están
        en una misma componente fuertemente conectada.
    Returns:
        Una estructura para determinar los vertices
        conectados a source
    Raises:
        Exception
    """
    try:
        adjlst = g.adjacents(graph, vertex)
        adjslstiter = it.newIterator(adjlst)
        while (it.hasNext(adjslstiter)):
            w = it.next(adjslstiter)
            if lt.isPresent(scc, w):
                visited = map.get(search['visited'], w)
                if visited is None:
                    map.put(search['visited'],
                            w, {'marked': True, 'edgeTo': vertex})
                    dfsVertexSCC(search, graph, w, scc)
        return search
    except Exception as exp:
        error.reraise(exp, 'dfs:dfsVertexSCC')
示例#5
0
def dfsVertexCycles(search, graph, vertex, vertex1):
    try:
        adjlst = g.adjacents(graph, vertex)
        adjslstiter = it.newIterator(adjlst)

        pos = lt.isPresent(adjlst, vertex1)  # Posición del vértice fijo
        fixed_edge = lt.getElement(
            adjlst,
            pos)  # Elemento que contiene el vértice dentro de la adjlst

        totalcycles = 0  # Inicio contador
        path = {}

        while (it.hasNext(adjslstiter)):
            w = it.next(adjslstiter)  # entro al vertice a analizar
            visited = map.get(search['visited'],
                              w)  # Pido la entrada en el mapa de los marcados
            if visited is None:
                map.put(search['visited'], w, {
                    'marked': True,
                    'edgeTo': vertex
                })
                dfsVertex(search, graph, w)
                path[w] = vertex
            elif visited == fixed_edge:
                totalcycles += 1
                print(path)
                path = {}

        search['total'] = totalcycles

        return search
    except Exception as exp:
        error.reraise(exp, 'dfs:dfsVertex')
示例#6
0
def GrafosPorCiclo(analyzer, origen, VDC):
    """
    Genera un grafo por cada ciclo diferente relacionado al origen y los añade a
    GPCC (diccionario)
    """
    #GPCC = Grafos Por Cada Ciclo
    GPCC = {}
    if VDC == False:
        return False
    else:
        for Valor in VDC:
            Cierre = False
            GPCC[Valor] = gr.newGraph(datastructure="ADJ_LIST",
                                        directed=True,
                                        size=6,
                                        comparefunction=comparer)
            gr.insertVertex(GPCC[Valor], origen)
            actual = origen
            mismo = origen
            Adjacentes = adj.adjacents(analyzer["graph"], actual)
            Adjacentes["cmpfunction"] = comparador
            while Cierre == False:
                a = it.newIterator(VDC[Valor])
                while it.hasNext(a):
                    b = it.next(a)
                    if actual != mismo:
                        Adjacentes = adj.adjacents(analyzer["graph"], actual)
                        Adjacentes["cmpfunction"] = comparador
                        mismo = actual
                    if not gr.containsVertex(GPCC[Valor], b):
                        if lt.isPresent(Adjacentes, origen) != 0 and actual != origen and b != origen:
                            gr.insertVertex(GPCC[Valor], b)
                            Tartalia = gr.getEdge(analyzer["graph"], actual, origen)
                            Peso = int(ed.weight(Tartalia)/Tartalia["Repeticiones"])
                            adj.addEdge(GPCC[Valor], actual, origen, Peso)
                            actual = b
                            Cierre = True
                        elif lt.isPresent(Adjacentes, b) != 0 and b != origen:
                            gr.insertVertex(GPCC[Valor], b)
                            Tartalia = gr.getEdge(analyzer["graph"], actual, b)
                            Peso = int(ed.weight(Tartalia)/Tartalia["Repeticiones"])
                            adj.addEdge(GPCC[Valor], actual, b, Peso)
                            actual = b  
                    elif actual == origen and lt.size(VDC[Valor]) == 1:
                            Cierre = True       
        return GPCC
示例#7
0
def dfsVertexCicles(search, graph, vertex):
    """
    Funcion auxiliar para calcular un recorrido DFS
    Args:
        search: Estructura para almacenar el recorrido
        vertex: Vertice de inicio del recorrido.

    Returns:
        Una estructura para determinar los vertices
        conectados a source
    Raises:
        Exception
    """
    try:

        search = {
                  'source': source,
                  'visited': None,
                  "camino":{}
                  }

        search['visited'] = map.newMap(numelements=g.numVertices(graph),
                                       maptype='PROBING',
                                       comparefunction=graph['comparefunction']
                                       )

        map.put(search['visited'], source, {'marked': True, 'edgeTo': None})
      
        dfsVertex2(search,graph,source,time)
        return search
    except Exception as exp:
        error.reraise(exp, 'dfs:DFS')

        ruta = 0
        adjlst = g.adjacents(graph, vertex)
        adjslstiter = it.newIterator(adjlst)
        while (it.hasNext(adjslstiter)):
            w = it.next(adjslstiter)
            visited = map.get(search['visited'], w)

            if visited == vertex:
                ruta += 1
                map.put(search['cicles'],
                        str(ruta), search['visited'])

            if visited is None:
                map.put(search['visited'],
                        w, {'marked': True, 'edgeTo': vertex})
                dfsVertex(search, graph, w)

        return search
    except Exception as exp:
        error.reraise(exp, 'dfs:dfsVertex')
示例#8
0
def adjacents(graph, vertex):
    """
    Retorna una lista con todos los vertices adyacentes al vertice vertex
    Args:
        graph: El grafo sobre el que se ejecuta la operacion
        vertex: El vertice del que se quiere la lista
    Returns:
        La lista de adyacencias
    Raises:
        Exception
    """
    if (graph['type'] == "ADJ_LIST"):
        return alt.adjacents(graph, vertex)
def dfs_extra(search, graph, vertex, components, path, cycles, weights):
    """
    Funcion auxiliar para calcular un recorrido DFS
    Args:
        search: Estructura para almacenar el recorrido
        vertex: Vertice de inicio del recorrido.
    Returns:
        Una estructura para determinar los vertices
        conectados a source
    Raises:
        Exception
    """
    try:
        if vertex is not None:
            stk.push(path, vertex)
        if vertex is not None:
            cycles[-1].append(vertex)
        adjlst = g.adjacents(graph, vertex)
        adjslstiter = it.newIterator(adjlst)
        while (it.hasNext(adjslstiter)):
            w = it.next(adjslstiter)
            if w is not None:
                visited = map.get(search['visited'], w)
                vertex_comp = map.get(components, vertex)['value']
                w_comp = map.get(components, w)['value']
                # if aun no he visitado todos mis hijos
                if visited is None and vertex_comp == w_comp:
                    map.put(search['visited'], w, {
                        'marked': True,
                        'edgeTo': vertex
                    })
                    edge = g.getEdge(graph, vertex, w)['weight']
                    current_weight = edge + 20
                    weights[-1] += current_weight
                    dfs_extra(search, graph, w, components, path, cycles,
                              weights)
                if g.outdegree(graph, vertex) > 1:
                    new_arr = []
                    new_arr.append(path['last']['info'])
                    dummy = path['first']
                    while dummy['next'] is not None:
                        new_arr.append(dummy['info'])
                        dummy = dummy['next']
                    if new_arr != cycles[-1]:
                        cycles.append(new_arr)
                        weights.append(weights[-1])

        map.put(search['visited'], vertex, None)
        stk.pop(path)
    except Exception as exp:
        error.reraise(exp, 'dfs:dfsVertex')