Exemplo n.º 1
0
def mostConnectedLandingPoint(analyzer):
    '''
    Calcula los landing points mas conectados
    '''
    landing_points = gr.vertices(analyzer['connections'])
    lp_degs = {}  # organize in dict
    for lp in lt.iterator(landing_points):
        deg_ = gr.degree(analyzer['connections'], lp)
        try:
            lp_degs[deg_].append(lp)
        except Exception as exp:
            lp_degs[deg_] = list()
            lp_degs[deg_].append(lp)
    degs_list = (lp_degs.keys())
    max_deg = max(degs_list)  # get max degree
    max_lps = lp_degs[max_deg]

    info_out = {}  # save info of each max landing point
    for lp in max_lps:
        _, _, info_lp = LandingPointNN(analyzer, lp)
        neigbors = [int(nn.split('*')[0]) for nn in info_lp.keys()]
        lp_id = int(lp.split('*')[0])
        lp_info = m.get(analyzer['landing_points'], lp_id)['value']
        info_out[lp] = {
            'name': lp_info['name'],
            'deg': max_deg,
            'lat': lp_info['latitude'],
            'lon': lp_info['longitude'],
            'neighbors': neigbors
        }
    return max_deg, max_lps, info_out
Exemplo n.º 2
0
def addCapitals(analyzer, country):
    capital = country['CapitalName'] + "-" + country['CountryName']
    addPoint(analyzer, capital)
    grado = gr.degree(analyzer['connections'], capital)
    if grado == 0:
        info = mp.get(analyzer['countries'], country['CountryName'])['value']
        latitud = info['CapitalLatitude']
        longitud = info['CapitalLongitude']
        listaPoints = mp.valueSet(analyzer["landing_points"])
        difMasCercana = 100
        for point in lt.iterator(listaPoints):
            difLat = abs(float(point['latitude']) - float(latitud))
            difLon = abs(float(point['longitude']) - float(longitud))
            difTot = difLat + difLon
            if difTot < difMasCercana:
                difMasCercana = difTot
                LPmasCercano = point
        listaVertices = mp.get(analyzer['points_vertices'],
                               LPmasCercano['landing_point_id'])['value']
        coordOrigen = (float(latitud), float(longitud))
        coordDestino = (float(LPmasCercano["latitude"]),
                        float(LPmasCercano["longitude"]))
        distancia = round(hs.haversine(coordOrigen, coordDestino), 2)
        for vertice in lt.iterator(listaVertices):
            addConnection(analyzer, capital, vertice, distancia)
            addConnection(analyzer, vertice, capital, distancia)
Exemplo n.º 3
0
def MostConnectionLPs(macrostructure):
    final = []
    answers = []
    vertices = gr.vertices(macrostructure['connections'])
    most_connections = 0
    for index in range(0, lt.size(vertices)):
        vertex = lt.getElement(vertices, int(index))
        connections = gr.degree(macrostructure['connections'], vertex)
        if connections == most_connections:
            answers.append(vertex)
        if connections > most_connections:
            answers = []
            most_connections = connections
            answers.append(vertex)
    for ver in answers:
        info = lt.newList("ARRAY_LIST")
        datos = mp.get(macrostructure['lp'], ver)['value']
        nom_pais = (lt.getElement(datos, 2)).split(', ')
        nombre = nom_pais[0]
        pais = nom_pais[1]
        lt.addLast(info, nombre)
        lt.addLast(info, pais)
        lt.addLast(info, ver)
        final.append(info)
    return final, most_connections
Exemplo n.º 4
0
def greaterDegree(ana):
    congr = ana['connections']
    vertices = gr.vertices(congr)
    countries = ana['countries']
    points = ana['points']
    keysCountries = m.keySet(countries)
    mayor = -1
    llaves = []
    size = lt.size(vertices)
    for i in range(0, size):
        vertex = lt.getElement(vertices, i)
        degree = gr.degree(ana['connections'], vertex)
        if degree > mayor:
            mayor = degree
            llaves = []
            llaves.append(vertex)
        elif degree == mayor:
            llaves.append(vertex)
    mayores = lt.newList()
    M = folium.Map()
    for llave in llaves:
        encontrado = False
        i = 0
        while i < lt.size(keysCountries) and encontrado == False:
            country = lt.getElement(keysCountries, i)
            info = me.getValue(m.get(countries, country))
            cap = info['CapitalName']
            if cap == llave:
                encontrado = True
                lat = info['CapitalLatitude']
                lon = info['CapitalLongitude']
                loc = lat, lon
                name = country + ', ' + cap
                folium.Marker(loc,
                              name,
                              icon=folium.Icon(color='red',
                                               icon_color='white')).add_to(M)
                adj = gr.adjacents(congr, llave)
                for i in range(0, lt.size(adj)):
                    vert = lt.getElement(adj, i)
                    code = vert.split('*')[0]
                    info = me.getValue(m.get(points, code))
                    latP = info['latitude']
                    lonP = info['longitude']
                    locP = latP, lonP
                    name = info['name']
                    folium.Marker(
                        locP,
                        name,
                        icon=folium.Icon(color='green',
                                         icon_color='white')).add_to(M)
                M.save('greater.html')
            i += 1
        retorno = llave, country
        lt.addLast(mayores, retorno)
    return mayores, mayor
Exemplo n.º 5
0
def totalarcos(catalogo):
    lista = lt.newList("ARRAY_LIST")
    contador = 0
    for x in range(catalogo["listavertices"]["size"]):
        vertice = lt.getElement(catalogo["listavertices"], x)
        grado = gr.degree(catalogo["conexiones"], vertice)
        if grado > 1 and getvertexinfo(catalogo, vertice) != None:
            lt.addLast(lista, getvertexinfo(catalogo, vertice))
            contador += grado
    return lista, contador
Exemplo n.º 6
0
def req2(datos):
    vertices = gr.vertices(datos['cables'])
    tamano = lt.size(vertices)
    p = 0
    respuesta = {}
    while p < int(tamano):
        b = lt.getElement(vertices, p)
        numero = gr.degree(datos['cables'], b)
        respuesta[b] = numero
        p += 1
    return respuesta
Exemplo n.º 7
0
def LPs(analyzer):
    LPs = gr.vertices(analyzer['cables'])
    ltDeg = lt.newList('ARRAY_LIST', cmpfunction=LPids)
    try:
        for vertex in lt.iterator(LPs):
            lt.addLast(ltDeg, (vertex, gr.degree(analyzer['cables'], vertex)))

        ltDegO = sortMaster(ltDeg, cmpDeg)
        return ltDegO
        
    except Exception as exp:
        error.reraise(exp, 'model:LPs')
Exemplo n.º 8
0
def las3_menos_usadas(analyzer):
    "retorna el nombre de  top3 estaciones con menos uso"
    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.degree(analyzer["connections"], estacion)
        dic_estaciones[estacion] = viajes
        estaciones = saber_los_menores(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
Exemplo n.º 9
0
def affectedLPs(macrostructure, lp):
    answer = []
    affected = []
    vertex = lt.getElement((mp.get(macrostructure['lp-names'], lp))['value'],
                           2)
    x = gr.adjacents(macrostructure['connections'], vertex)
    y = gr.degree(macrostructure['connections'], vertex)
    answer.append(y)
    for index in range(1, int(lt.size(x)) + 1):
        data = lt.getElement(x, index)
        pais = lt.getElement(mp.get(macrostructure['lp'], data)['value'], 2)
        edge = gr.getEdge(macrostructure['connections'], vertex, data)
        print(edge)
        affected.append(pais)
    answer.append(affected)
    return answer
Exemplo n.º 10
0
def añadir_capitales_aburridas(analyzer):
    vertices = gr.vertices(analyzer['connections'])
    
    for i in range(lt.size(vertices)):
        vertice=(lt.getElement(vertices,i))
        mas_corto=10000000
        vertice_mas_cercano=('a',1)
        if gr.degree(analyzer['connections'],vertice)==0 and len(vertice[0]) > 0 and vertice[1]=='1':
            for j in range(lt.size(vertices)):
                vertice2=(lt.getElement(vertices,j))
                if mp.contains(analyzer['landing'],(vertice2[0])) == True:
                    pais=me.getValue(mp.get(analyzer['capital_pais'],vertice[0]))
                    largo_cable = largo_cables(analyzer,vertice2[0],pais)
                    if largo_cable < mas_corto:
                        vertice_mas_cercano = vertice2
                        mas_corto=largo_cable
            gr.addEdge(analyzer['connections'],vertice_mas_cercano,vertice,float(mas_corto))
            gr.addEdge(analyzer['connections'],vertice,vertice_mas_cercano,float(mas_corto))
Exemplo n.º 11
0
def landing_principales(analyzer):
    vertices = gr.vertices(analyzer['connections'])
    max=0
    lista=lt.newList('ARRAYLIST')
    
    for i in range(lt.size(vertices)):
        vertice=lt.getElement(vertices,i)
        grado=gr.degree(analyzer['connections'],vertice)
        
        if grado == max:
            lt.addLast(lista,vertice)

        if grado > max:
            max=grado
            lista=lt.newList('ARRAYLIST')
            lt.addFirst(lista,vertice)
    vermax=lt.getElement(lista,0)
 
    return vermax[0], max
Exemplo n.º 12
0
def req2(catalog):
    points = mp.valueSet(catalog['landing_points'])
    points_list = lt.newList()
    for point in lt.iterator(points):
        amount = gr.degree(catalog['connections'], point['landing_point_id'])
        if len(point['name'].split(",")) > 1:
            element = {
                'name': str(point['name']),
                'country': str((point['name'].split(",")[1])),
                'id': point['landing_point_id'],
                'amount': amount
            }
        else:
            element = {
                'name': str(point['name']),
                'country': str(point['name']),
                'id': point['landing_point_id'],
                'amount': amount
            }
        lt.addLast(points_list, element)
    return points_list
Exemplo n.º 13
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)
Exemplo n.º 14
0
def addContinentConnection(analyzer):
    """Se consultan cuales nodos del grafo tiene grado 0 y se les realizan las comparaciones necesarias
    para encontrar la distancia de los landing points para encontrar el camino más cercano en KM a las 
    capitales de interés."""
    ltVertices = gr.vertices(analyzer['connectionsDistance'])
    for element in lt.iterator(ltVertices):
        if gr.degree(analyzer['connectionsDistance'], element) == 0:
            primero = True
            minElement = ""
            minDistance = 0
            capacity = 0
            lstLandingPoints = mp.keySet(analyzer['LandingPointI'])
            for key in lt.iterator(lstLandingPoints):
                if not (key == element):
                    distance = CalculateDistance(analyzer, element, key)
                    if distance == 0:
                        distance = 100
                    if primero:
                        minDistance = distance
                        minElement = key
                        minElementInfo = mp.get(analyzer['LandingPointI'], key)
                        minElementInfo = me.getValue(minElementInfo)
                        capacity = minElementInfo['MinCapacity_Landing']
                        primero = False
                    elif minDistance < distance:
                        minDistance = distance
                        minElement = key
                        minElementInfo = mp.get(analyzer['LandingPointI'], key)
                        minElementInfo = me.getValue(minElementInfo)
                        capacity = minElementInfo['MinCapacity_Landing']
            addConnectionDistance(analyzer, element, minElement, minDistance)
            addConnectionDistance(analyzer, minElement, element, minDistance)
            addConnectionCapacity(analyzer, element, minElement, capacity)
            addConnectionCapacity(analyzer, minElement, element, capacity)
    ltVertices = gr.vertices(analyzer['connectionsDistance'])
    return analyzer
Exemplo n.º 15
0
def req2(analyzer):
    lista_vertices = gr.vertices(analyzer["connections_distance"])
    final = lt.newList(datastructure="ARRAY_LIST")
    i = 1
    while i <= lt.size(lista_vertices):
        elem = lt.getElement(lista_vertices, i)
        if gr.degree(analyzer["connections_distance"],
                     elem) > 1 and elem[1] != 0:
            lp_id = elem[0]
            lp_name = mp.get(analyzer["name_dado_id"], lp_id)["value"]
            lista_adyacentes = gr.adjacents(analyzer["connections_distance"],
                                            elem)

            ii = 1
            e = 0
            while ii <= lt.size(lista_adyacentes):
                adyacente = lt.getElement(lista_adyacentes, ii)
                if adyacente[0] == lp_id:
                    e += 1
                ii += 1
            if e >= 1:
                lt.addLast(final, (lp_name, e + 1))
        i += 1
    return final