def addConnection_directed(analyzer, connection):
    origin = connection['\ufefforigin']
    destination = connection['destination']
    cable_id = connection['cable_name']
    cable_lenght = DistanceHaversine(origin, destination, analyzer)

    verticeA = "<{}>-<{}>".format(origin, cable_id)
    verticeB = "<{}>-<{}>".format(destination, cable_id)

    containsA = gr.containsVertex(analyzer['connections_directed'], verticeA)
    containsB = gr.containsVertex(analyzer['connections_directed'], verticeB)
    if not containsA and not containsB:
        gr.insertVertex(analyzer['connections_directed'], verticeA)
        gr.insertVertex(analyzer['connections_directed'], verticeB)

        listilla = [origin, cable_id, verticeA]

        lt.addLast(analyzer['vertices'], listilla)

        mapa = analyzer['landing_points']
        pareja = om.get(mapa, origin)
        valor = me.getValue(pareja)
        lista_cables = valor['cables']
        lt.addLast(lista_cables, verticeA)

        gr.addEdge(analyzer['connections_directed'], verticeA, verticeB,
                   cable_lenght)
Example #2
0
def addVertexescomp(catalog, link):
    try:
        grafo = catalog['connections']
        lpo = link['origin']
        origin = formatVertex(link, lpo)
        lpd = link['destination']
        destination = formatVertex(link, lpd)
        weight = link['cable_length']
        exists_origin = gr.containsVertex(grafo, origin)
        exists_destin = gr.containsVertex(grafo, destination)
        addcableInfo(link, catalog)
        addConnectingLP(origin, destination, catalog, link)
        addConnectingLP(destination, origin, catalog, link)
        addCabletoLp(destination, catalog)
        addCabletoLp(origin, catalog)
        if exists_origin == False:
            gr.insertVertex(grafo, origin)
            pais = findLPtoCountry(catalog, origin)
            addLPtoCountry(pais, origin, catalog)

        if exists_destin == False:
            gr.insertVertex(grafo, destination)
            pais = findLPtoCountry(catalog, destination)
            addLPtoCountry(pais, destination, catalog)

        addEdges(grafo, origin, destination, weight)
        return catalog

    except Exception as exp:
        error.reraise(exp, 'model:addVertexescomp')
def addVertex(analyzer, vertex):
    try:
        if not gr.containsVertex(analyzer['graph'], vertex):
            gr.insertVertex(analyzer['graph'], vertex)
        return analyzer
    except Exception as exp:
        error.reraise(exp, 'model:addVertex')
Example #4
0
def addArch(analyzer, vtx):
    try:
        if gr.containsVertex(analyzer["arches"], vtx) == False:
            gr.insertVertex(analyzer["arches"], vtx)
        return analyzer
    except Exception as exp:
        error.reraise(exp, "model.addArch")
Example #5
0
def addPoint(analyzer, pID):
    try:
        # Se intenta crear un vertice. Primero se verifica si existe
        if gr.containsVertex(analyzer['connections'], pID) == False:
            gr.insertVertex(analyzer['connections'], pID)
        return analyzer
    except Exception as exp:
        error.reraise(exp, 'model:addPoint')
def addComArea(chicagoAnalyzer, vertex):
    """
    Inserta el vertice que representa a un Community Area en el grafo
    """
    if not gr.containsVertex(chicagoAnalyzer['communityTrip'], vertex):
        gr.insertVertex(chicagoAnalyzer['communityTrip'], vertex)

    return chicagoAnalyzer
Example #7
0
def addLandingPoint(analyzer, landingpoint):
    """
    Adiciona un punto de conexión como vértice al grafo
    """
    graph = analyzer['connections']
    if not gr.containsVertex(graph, landingpoint):
        gr.insertVertex(graph, landingpoint)
    return analyzer
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
Example #9
0
def addVertex(catalog, vertexname, notcapital):
    if not gr.containsVertex(catalog['connections'], vertexname):
        preexistingvertices = gr.vertices(catalog['connections'])
        gr.insertVertex(catalog['connections'], vertexname)
        if notcapital:
            for vertex in lt.iterator(preexistingvertices):
                if vertexname.split('*')[0] == vertex.split('*')[0]:
                    addEdge(catalog, vertexname, vertex, 0.1)
        preexistingvertices.clear()
 def graph_mst_prim(self, scan):
     graph = gp.newGraph(size=self.mas_grande[1])
     distTo = scan['distTo']
     edgeTo = scan['edgeTo']
     dist_it = ll_it.newIterator(mp.keySet(distTo))
     total_dist = 0
     while ll_it.hasNext(dist_it):
         vertex = ll_it.next(dist_it)
         dist = mp.get(distTo, vertex)['value']
         if dist:
             total_dist += dist
             edge = mp.get(edgeTo, vertex)['value']
             if not gp.containsVertex(graph, edge['vertexA']):
                 gp.insertVertex(graph, edge['vertexA'])
             if not gp.containsVertex(graph, edge['vertexB']):
                 gp.insertVertex(graph, edge['vertexB'])
             gp.addEdge(graph, edge['vertexA'], edge['vertexB'], dist)
     return graph, total_dist
Example #11
0
def addVertex(catalog, graph, vertice):
    """
    Adiciona una estación como un vertice del grafo
    """
    try:
        if not gr.containsVertex(catalog[graph], vertice):
            gr.insertVertex(catalog[graph], vertice)
        return catalog
    except Exception as exp:
        error.reraise(exp, 'model:addstop')
Example #12
0
def getTargetEdge(trip: dict, DataBase: dict) -> edge:
    startId = int(trip["start station id"])
    endId = int(trip["end station id"])
    target = selectTarget(trip)

    if not (map.contains(DataBase['target'], target)):
        targetGraph = Structure.newTargetGraph()
        map.put(DataBase['target'], target, targetGraph)
    targetGraph = mapentry.getValue(map.get(DataBase['target'], target))

    if not (graph.containsVertex(targetGraph, startId)):
        graph.insertVertex(targetGraph, startId)
    if not (graph.containsVertex(targetGraph, endId)):
        graph.insertVertex(targetGraph, endId)

    edgeRoute = graph.getEdge(targetGraph, startId, endId)

    if edgeRoute is None:
        graph.addEdge(targetGraph, startId, endId, 0)
        edgeRoute = graph.getEdge(targetGraph, startId, endId)
    return edgeRoute
Example #13
0
def addCountry(catalog, country):
    lista = catalog['nodos_capitales']
    grafo = catalog['connections']
    paises = catalog['countries']
    name = country['CountryName'].lower()
    if name != "":
        entry = newCountry(country)
        mp.put(paises, name, entry)
        vert_cap = country['CapitalName'].lower() + '*' + name
        existscap = gr.containsVertex(grafo, vert_cap)
        if existscap == False:
            gr.insertVertex(grafo, vert_cap)
            lt.addLast(lista, vert_cap)
def addCountriestoCapitalCity(analyzer):

    vertices = analyzer['vertices']
    map_landing = analyzer['landing_points']

    for i in range(lt.size(vertices)):
        parejaA = lt.getElement(vertices, i)
        origenA = parejaA[0]
        vertice = parejaA[2]
        pareja = om.get(map_landing, origenA)
        info = me.getValue(pareja)
        pais = info['country']

        contains = gr.containsVertex(analyzer['connections'], pais)
        if not contains:
            gr.insertVertex(analyzer['connections'], pais)
            gr.addEdge(analyzer['connections'], pais, vertice)
            lista_add = analyzer['vertices']
            lt.addLast(lista_add, pais)
        if contains:
            gr.addEdge(analyzer['connections'], pais, vertice)
Example #15
0
def conf(catalog):
    it=lt.iterator(catalog['reqc'])
    lpit=mp.keySet(catalog['landingpoints'])
    lpit1=lt.iterator(lpit)
    ver=gr.vertices(catalog['connections'])
    verit=lt.iterator(ver)
    for i in it:
        cll=mp.get(catalog['countries'],i)['value']
        mayor=float('inf')
        refmayor=''
        if not gr.containsVertex(catalog['connections'],i):
            for lp in lpit1:
                lpinfo=mp.get(catalog['landingpoints'],lp)['value']
                distance=extractDistance((cll['latitude'],cll['longitude']),(lpinfo['latitude'],lpinfo['longitude']))
                if distance < mayor:
                    mayor=distance
                    refmayor=lp
                addLandingpointid(catalog,i)
            for v in verit:
                if refmayor in v:
                    addConnection(catalog, v, i, mayor)
                    addConnection(catalog,i, v, mayor)
Example #16
0
def addlpConnections(catalog,connection):
    ldinfo=catalog['landingpoints']
    con=catalog['connections']
    country=catalog['countries']
    origin=str(connection['origin'])
    destination=str(connection['destination'])
    cable=str(connection['cable_id'])
    distance=extractDistance((mp.get(ldinfo,origin)['value']['latitude'],mp.get(ldinfo,origin)['value']['longitude']),
                            (mp.get(ldinfo,destination)['value']['latitude'],mp.get(ldinfo,destination)['value']['longitude']))
    addLandingpointid(catalog,origin+'_'+cable)
    addlpKeys(catalog,origin,cable)
    addLandingpointid(catalog,destination+'_'+cable)
    addlpKeys(catalog,destination,cable)
    c1=mp.get(ldinfo,origin)
    for c2 in c1['value']['name']:
        cap=mp.get(country, c2)
        if cap != None:
            if not gr.containsVertex(con,c2): 
                addLandingpointid(catalog,c2)
            dis=extractDistance((mp.get(ldinfo,origin)['value']['latitude'],mp.get(ldinfo,origin)['value']['longitude']),(cap['value']['latitude'],cap['value']['longitude']))
            addConnection(catalog, origin+'_'+cable,c2, distance)
            addConnection(catalog,c2,origin+'_'+cable, distance)
    addConnection(catalog, origin+'_'+cable, destination+'_'+cable, distance)
 def containsArea(self, area) -> bool:
     return graph.containsVertex(self.Routes, area)
Example #18
0
def addLandingpointid(catalog,landinfpointId):
    if not gr.containsVertex(catalog['connections'], landinfpointId):
           gr.insertVertex(catalog['connections'], landinfpointId)