Example #1
0
def initSearch(graph, source):
    """
    Inicializa la estructura de busqueda y deja
    todos los arcos en infinito.
    Se inserta en la cola el vertice source
    Args:
        graph: El grafo a examinar
        source: El vertice fuente
    Returns:
        Estructura de busqueda inicializada
    Raises:
        Exception
    """
    try:
        search = {
            'source': source,
            'edgeTo': None,
            'distTo': None,
            'qvertex': None,
            'onQ': None,
            'cost': 0,
            'spt': None,
            'cycle': False
        }

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

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

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

        search['spt'] = g.newGraph(size=g.numVertices(graph),
                                   directed=True,
                                   comparefunction=graph['comparefunction'])

        vertices = g.vertices(graph)
        for vert in lt.iterator(vertices):
            map.put(search['distTo'], vert, math.inf)
            map.put(search['onQ'], vert, False)
            g.insertVertex(search['spt'], vert)

        newq = q.newQueue()
        search['qvertex'] = newq

        return search

    except Exception as exp:
        error.reraise(exp, 'bellman:init')
def KosarajuUnicoSCC(graph, vertex):
    """
    Implementa el algoritmo de Kosaraju
    para encontrar los componentes conectados
    de un grafo dirigido
    Args:
        graph: El grafo a examinar
    Returns:
        Una estructura con los componentes
        conectados
    Raises:
        Exception
    """
    try:
        scc_u = {
            'idscc': None,
            'marked': None,
            'grmarked': None,
            'components': 0
        }

        scc_u['idscc'] = map.newMap(g.numVertices(graph),
                                    maptype='PROBING',
                                    comparefunction=graph['comparefunction'])

        scc_u['marked'] = map.newMap(g.numVertices(graph),
                                     maptype='PROBING',
                                     comparefunction=graph['comparefunction'])
        scc_u['grmarked'] = map.newMap(
            g.numVertices(graph),
            maptype='PROBING',
            comparefunction=graph['comparefunction'])

        # Se calcula el grafo reverso de graph
        greverse = reverseGraph(graph)

        # Se calcula el DFO del reverso de graph
        dforeverse = dfo.DepthFirstOrder(greverse)
        grevrevpost = dforeverse['reversepost']

        # Se recorre el grafo en el orden dado por reversepost (G-reverso)
        scc_u['components'] = 0
        while (not stack.isEmpty(grevrevpost)):
            vert = stack.pop(grevrevpost)
            if vert == str(vertex):
                if not map.contains(scc_u['marked'], vert):
                    scc_u['components'] += 1
                    sccCount(graph, scc_u, vert)
        return scc_u
    except Exception as exp:
        error.reraise(exp, 'scc_u:Kosaraju')
def reverseGraph(graph):
    """
        Retornar el reverso del grafo graph
    """
    try:
        greverse = g.newGraph(size=g.numVertices(graph),
                              directed=True,
                              comparefunction=graph['comparefunction'])

        lstvert = g.vertices(graph)
        itervert = it.newIterator(lstvert)
        while it.hasNext(itervert):
            vert = it.next(itervert)
            g.insertVertex(greverse, vert)

        itervert = it.newIterator(lstvert)
        while it.hasNext(itervert):
            vert = it.next(itervert)
            lstadj = g.adjacents(graph, vert)
            iteradj = it.newIterator(lstadj)
            while it.hasNext(iteradj):
                adj = it.next(iteradj)
                g.addEdge(greverse, adj, vert)
        return greverse
    except Exception as exp:
        error.reraise(exp, 'scc:reverse')
Example #4
0
def cargar_datos():
    data = model.landing_points("Data/landing_points.csv",
                                "Data/connections.csv", "Data/countries.csv")
    landing_points = gp.numVertices(data.connections_map)
    connections = gp.numEdges(data.connections_map) // 2
    countries = mp.size(data.countries)
    return data, landing_points, connections, countries
Example #5
0
def relax(graph, search, v):
    """
    Relaja el peso de los arcos del grafo
    Args:
        search: La estructura de busqueda
        v: Vertice desde donde se relajan los pesos
    Returns:
        El grafo con los arcos relajados
    Raises:
        Exception
    """
    try:
        edges = g.adjacentEdges(graph, v)
        if edges is not None:
            for edge in lt.iterator(edges):
                v = e.either(edge)
                w = e.other(edge)
                distv = map.get(search['distTo'], v)['value']
                distw = map.get(search['distTo'], w)['value']
                distweight = distv + e.weight(edge)
                if (distw > distweight):
                    map.put(search['distTo'], w, distweight)
                    map.put(search['edgeTo'], w, edge)
                    if (not map.get(search['onQ'], w)['value']):
                        q.enqueue(search['qvertex'], w)
                        map.put(search['onQ'], w, True)
                cost = search['cost']
                if ((cost % g.numVertices(graph)) == 0):
                    findneg = findNegativeCycle(graph, search)
                    if (hasNegativecycle(findneg)):
                        return
                search['cost'] = cost + 1
        return search
    except Exception as exp:
        error.reraise(exp, 'bellman:relax')
def BreadhtFisrtSearch(graph, source, time, camino):
    """
    Genera un recorrido BFS sobre el grafo graph
    Args:
        graph:  El grafo a recorrer
        source: Vertice de inicio del recorrido.
    Returns:
        Una estructura para determinar los vertices
        conectados a source
    Raises:
        Exception
    """
    try:
        search = {'source': source, 'visited': None, 'caminos': []}
        search['visited'] = map.newMap(
            numelements=g.numVertices(graph),
            maptype='PROBING',
            comparefunction=graph['comparefunction'])
        map.put(search['visited'], source, {
            'marked': True,
            'edgeTo': None,
            'distTo': 0
        })
        bfsVertex(search, graph, source, time, camino)
        return search
    except Exception as exp:
        error.reraise(exp, 'bfs:BFS')
Example #7
0
def initSearch(graph):
    """
    Inicializa la estructura de busqueda y deja
    todos los arcos en infinito.
    Se inserta en la cola el vertice source
    Args:
        graph: El grafo a examinar
        source: El vertice fuente
    Returns:
        Estructura de busqueda inicializada
    Raises:
        Exception
    """
    try:
        search = {
            'edgeTo': None,
            'distTo': None,
            'marked': None,
            'pq': None,
            'mst': None
        }

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

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

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

        vertices = g.vertices(graph)
        for vert in lt.iterator(vertices):
            map.put(search['distTo'], vert, math.inf)
            map.put(search['marked'], vert, False)

        search['pq'] = pq.newIndexMinPQ(cmpfunction=graph['comparefunction'])
        search['mst'] = q.newQueue()

        return search

    except Exception as exp:
        error.reraise(exp, 'bellman:init')
Example #8
0
def test_insertVertex(graph):
    g.insertVertex(graph, 'Bogota')
    g.insertVertex(graph, 'Yopal')
    g.insertVertex(graph, 'Cali')
    g.insertVertex(graph, 'Medellin')
    g.insertVertex(graph, 'Pasto')
    g.insertVertex(graph, 'Barranquilla')
    g.insertVertex(graph, 'Manizales')
    assert g.numVertices(graph) == 7
Example #9
0
def initStructures(graph):
    """

    Args:
        graph: El grafo a examinar
        source: El vertice fuente
    Returns:
        Estructura de busqueda inicializada
    Raises:
        Exception
    """
    try:
        search = {
               'edgeTo': None,
               'marked': None,
               'onStack': None,
               'cycle': None
             }

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

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

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

        search['cycle'] = st.newStack()

        vertices = g.vertices(graph)
        for vert in lt.iterator(vertices):
            map.put(search['marked'], vert, False)
            map.put(search['onStack'], vert, False)

        return search

    except Exception as exp:
        error.reraise(exp, 'cycle:init')
Example #10
0
def req4(catalog):
    grafo = catalog['graph_landing_points']
    vertices_grafo = gr.vertices(grafo)
    vertice1 = lt.getElement(vertices_grafo, 0)
    MST = dijsktra.Dijkstra(grafo, vertice1)
    vertice2 = lt.getElement(vertices_grafo, (lt.size(vertices_grafo) - 1))
    num_nodos = gr.numVertices(MST)
    #para hallar costo total hacer un dist to con vertice inicial y final
    distancia_total = dijsktra.distTo(MST, vertice2)

    return num_nodos, distancia_total
Example #11
0
def criticalInfrastructure(analyzer):
    vertex = gr.numVertices(analyzer["connections"])
    tree = pr.PrimMST(analyzer["connections"])
    weight = pr.weightMST(analyzer["connections"], tree)
    branch = pr.edgesMST(analyzer["connections"], tree)
    branch = branch["edgeTo"]["table"]["elements"]
    max = 0

    for i in range(len(branch)):
        value = branch[i]["value"]
        if (value != None) and (float(value["weight"]) > max):
            max = value["weight"]

    return vertex, weight, max
Example #12
0
def initSearch(graph, source):
    """
    Inicializa la estructura de busqueda y deja
    todos los arcos en infinito.
    Se inserta en la cola indexada el vertice source
    Args:
        graph: El grafo a examinar
        source: El vertice fuente
    Returns:
        Estructura de busqueda inicializada
    Raises:
        Exception
    """
    try:
        search = {
            'source': source,
            'visited': None,
            'iminpq': None
        }

        search['visited'] = map.newMap(numelements=g.numVertices(graph),
                                       maptype='PROBING',
                                       comparefunction=graph['comparefunction']
                                       )
        vertices = g.vertices(graph)
        itvertices = it.newIterator(vertices)
        while (it.hasNext(itvertices)):
            vert = it.next(itvertices)
            map.put(search['visited'],
                    vert,
                    {'marked': False, 'edgeTo': None, 'distTo': math.inf}
                    )
        map.put(search['visited'],
                source,
                {'marked': True, 'edgeTo': None, 'distTo': 0}
                )
        pq = iminpq.newIndexMinPQ(
            cmpfunction=graph['comparefunction']
        )
        search['iminpq'] = pq
        iminpq.insert(search['iminpq'], source, 0)
        return search
    except Exception as exp:
        error.reraise(exp, 'dks:init')
def DepthFirstOrder(graph):
    try:
        search = {
            'marked': None,
            'pre': None,
            'post': None,
            'reversepost': None
        }
        search['pre'] = queue.newQueue()
        search['post'] = queue.newQueue()
        search['reversepost'] = stack.newStack()
        search['marked'] = map.newMap(numelements=g.numVertices(graph),
                                      maptype='PROBING',
                                      comparefunction=graph['comparefunction'])
        lstvert = g.vertices(graph)
        for vertex in lt.iterator(lstvert):
            if not (map.contains(search['marked'], vertex)):
                dfsVertex(graph, search, vertex)
        return search
    except Exception as exp:
        error.reraise(exp, 'dfo:DFO')
Example #14
0
def test_getEdgesGraph(graph):
    g.insertVertex(graph, 'Bogota')
    g.insertVertex(graph, 'Yopal')
    g.insertVertex(graph, 'Cali')
    g.insertVertex(graph, 'Medellin')
    g.insertVertex(graph, 'Pasto')
    g.insertVertex(graph, 'Barranquilla')
    g.insertVertex(graph, 'Manizales')
    g.addEdge(graph, 'Bogota', 'Yopal', 2)
    g.addEdge(graph, 'Bogota', 'Medellin', 3)
    g.addEdge(graph, 'Bogota', 'Pasto', 1)
    g.addEdge(graph, 'Bogota', 'Cali', 10)
    g.addEdge(graph, 'Yopal', 'Medellin', 20)
    g.addEdge(graph, 'Medellin', 'Pasto', 4)
    g.addEdge(graph, 'Cali', 'Pasto', 6)
    g.addEdge(graph, 'Cali', 'Barranquilla', 3)
    g.addEdge(graph, 'Barranquilla', 'Manizales', 10)
    g.addEdge(graph, 'Pasto', 'Manizales', 8)
    assert g.numVertices(graph) == 7
    assert g.numEdges(graph) == 10
    edge = g.getEdge(graph, 'Pasto', 'Medellin')
    assert edge['weight'] == 4
Example #15
0
def TotalVertices(catalog):
    return gr.numVertices(catalog["connections"])
Example #16
0
        print(pais + " se encontraría afectado y tiene un Landing Point a " + str(distancia) + " kilómetros.")
        i += 1

catalog = None

"""
Menu principal
"""
while True:
    printMenu()
    inputs = input('Seleccione una opción para continuar\n')
    if int(inputs[0]) == 1:
        print("Cargando información de los archivos ....")
        analyzer = controller.initialize()
        controller.loadData(analyzer)
        vertices= gr.numVertices(analyzer['connections'])
        aristas= gr.numEdges(analyzer['connections'])
        print("El numero de vertices cargados es: " + str(vertices))
        print("El numero de arcos en el grafo es: " + str(aristas))
        

    elif int(inputs[0]) == 2:
        landing_point1 = input('Ingrese el landing point A: ')
        landing_point2 = input('Ingrese el landing point B: ')
        componentes = controller.componentesConectados(analyzer)
        estan = controller.estanLosDosLandingPoints(analyzer, landing_point1, landing_point2)
        print('*' * 25)
        print('El número de clústers es: ' + str(componentes))
        print_Req1(landing_point1, landing_point2, estan)

    elif int(inputs[0]) == 3:
Example #17
0
def test_insertEdges(graph):
    assert g.numVertices(graph) == 7
    assert g.numEdges(graph) == 10
Example #18
0
def getCriticalInfrastructure(catalog):
    mst = prim.PrimMST(catalog['connections'])
    print(gr.numVertices(mst))
    pass
Example #19
0
def numVertices(dataBase):
    return graph.numVertices(dataBase['graph'])
def totalStations(chicagoAnalyzer):
    """
    Retorna el total de vertices del grafo
    """
    return gr.numVertices(chicagoAnalyzer['communityTrip'])
Example #21
0
def totalStops(analyzer):
    """
    Retorna la cantidad total de vertices del grafo
    """
    return gr.numVertices(analyzer['connections'])
Example #22
0
Menú principal
"""
while True:
    printMenu()
    inputs = input("Seleccione una opción para continuar\n")
    if int(inputs[0]) == 1:
        print()
        print("Inicializando....\n")
        analyzer = initAnalyzer()

    elif int(inputs[0]) == 2:
        print()
        print("Cargando información de las conexiones....\n")
        data = loadData(analyzer)
        print("Total puntos de conexión: " +
              str(gr.numVertices(analyzer['connections'])))
        print("Total conexiones: " + str(gr.numEdges(analyzer['connections'])))
        print("Total países: " + str(mp.size(analyzer['countries'])) + "\n")
        printFirstLandingPoint(analyzer)
        printLastCountry(analyzer)

    elif int(inputs[0]) == 3:
        print()
        landingpointnamea = str(input("Ingrese punto de conexión: "))
        landingpointnameb = str(input("Ingrese punto de conexión: "))
        landingpointa = controller.getLandingPoint(analyzer, landingpointnamea)
        landingpointb = controller.getLandingPoint(analyzer, landingpointnameb)
        vertexa = controller.getVertexByLandingPoint(analyzer, landingpointa)
        vertexb = controller.getVertexByLandingPoint(analyzer, landingpointb)
        sccomponents = controller.stronglyConnectedComponents(analyzer)
        scvertexs = controller.stronglyConnectedVertexs(