def PaisesAfectados(catalog, nombreLanding): landing = mp.get(catalog["LandingPointN"], nombreLanding) listaPaises = "NE" if landing != None: #listaPaises = lt.newList('ARRAY_LIST') tablitaPaises = mp.newMap(numelements=10, maptype='PROBING', comparefunction=compareCountryNames) landing = me.getValue(landing) datosLanding = lt.getElement( me.getValue(mp.get(catalog["LandingPointI"], landing))['lstData'], 1) paisLanding = datosLanding["name"].split(",") paisLanding = paisLanding[len(paisLanding) - 1].strip() h = paisLanding edge = gr.getEdge(catalog["connectionsDistance"], paisLanding, landing) peso = e.weight(edge) / 1000 #lt.addLast(listaPaises,paisLanding) mp.put(tablitaPaises, paisLanding, peso) adyacentes = gr.adjacentEdges(catalog["connectionsDistance"], landing) for arco in lt.iterator(adyacentes): OtroVertex = e.other(arco, landing) if not mp.contains(catalog['countriesInfo'], OtroVertex): adyacentes2 = gr.adjacentEdges(catalog["connectionsDistance"], OtroVertex) for arco2 in lt.iterator(adyacentes2): OtroVertex2 = e.other(arco2, OtroVertex) if not mp.contains(catalog['countriesInfo'], OtroVertex2) and OtroVertex2 != landing: peso = e.weight(arco2) / 1000 id = OtroVertex2.split("*")[0] datosLanding = lt.getElement( me.getValue(mp.get(catalog["LandingPointI"], id))['lstData'], 1) paisLanding = datosLanding["name"].split(",") paisLanding = paisLanding[len(paisLanding) - 1].strip() #if lt.isPresent(listaPaises,paisLanding)==0: # lt.addLast(listaPaises,paisLanding) pais = mp.get(tablitaPaises, paisLanding) if pais != None: pais = me.getValue(pais) if (peso < pais): mp.put(tablitaPaises, paisLanding, peso) #ACA else: mp.put(tablitaPaises, paisLanding, peso) #ACA #heap = pq.newMinPQ(cmpfunction=compareDistance) listaPaises = lt.newList('ARRAY_LIST') for pais in lt.iterator(mp.keySet(tablitaPaises)): elemento = me.getValue(mp.get(tablitaPaises, pais)) #pq.insert(heap,(pais,elemento)) lt.addLast(listaPaises, (pais, elemento)) merge.sort(listaPaises, compareDistance) return listaPaises
def countries_to_landing_point(analyzer, landing_name): #req 5 landing_id = name_to_id(analyzer, landing_name) country_origin = m.get(analyzer['landing_points_info'], landing_id)['value']['country'] lstcables = m.get(analyzer['landing_points_cables'], landing_id)['value'] mapa = m.newMap() for cable in lt.iterator(lstcables): vertex = format_vertex(landing_id, cable) arcos = gr.adjacentEdges(analyzer['connections'], vertex) for arco in lt.iterator(arcos): landing_id2 = arco['vertexB'].split('~')[0] distance = arco['weight'] country = m.get(analyzer['landing_points_info'], landing_id2)['value']['country'] if country == country_origin: distance = 0 entry = (country, distance) if not m.contains(mapa, country): m.put(mapa, country, entry) else: entry2 = m.get(mapa, country)['value'] if distance < entry2[1]: m.put(mapa, country, entry) lista = merge.sort(m.valueSet(mapa), compare_entry_req5) numcountries = lt.size(lista) return numcountries, lista
def lpdamage(analyzer, lp): a = mp.get(analyzer['landing_points_cables'], lp) vertexs = me.getValue(a) countries = lt.newList(datastructure="ARRAY_LIST", cmpfunction=compareValue) for i in lt.iterator(vertexs): adj = gr.adjacentEdges(analyzer["cables"], i) for e in lt.iterator(adj): v = ["vertexA", "vertexB"] for z in v: nm = e[z].split("-")[0] name = nm.split(",") if len(name) == 3: country = name[2] elif len(name) == 2: country = name[1] else: country = name[0] if lt.isPresent(countries, country) == 0: if e["weight"] != 0.1: lt.addLast(countries, { "country": country, "distance": e["weight"] }) sort(countries, compareDistance) return (countries, lt.size(countries))
def recursiva(analyzer, vertex, cable, lista, mapa, original) -> None: """Función recursiva para encontrar los países del req6. Args: analyzer vertex (str): Vértice A cable (str): Nombre del cable. lista (ARRAY_LIST): Lista con los países. mapa (Hash Map): Mapa que contiene los vértices que ya han sido buscados. original (str): Vértice original. """ for arco in lt.iterator(gr.adjacentEdges(analyzer['landingPoints'], vertex)): if arco['vertexB'][0] not in '1234567890' and arco[ 'vertexB'] != original: # Si no empieza en un número lt.addLast( lista, arco['vertexB'] ) # Se agrega a la lista que es la que retorna la función "req6" if cable in arco['vertexB'] and not mp.contains(mapa, arco['vertexB']): mp.put(mapa, arco['vertexB'], None) recursiva(analyzer, arco['vertexB'], cable, lista, mapa, original) # Si tiene el cable repite el proceso.
def afectedCountries (analyzer, vertex): adjacentedges = gr.adjacentEdges(analyzer['connections'], vertex) map = mp.newMap(numelements=100,maptype='PROBING') lstedges = adjacentedges.copy() i = 1 while i <= lt.size(lstedges): edge = lt.getElement(lstedges, i) pais = edge['vertexB'].split(',') if len(pais) > 3: pais = pais[len(pais)-1] else: pais = pais[0] contains = mp.contains(map, pais) if contains: entry = mp.get(map, pais) entry = me.getValue(entry) if e.weight(edge) < entry[0]: mp.put(map, pais, (e.weight(edge), i)) lt.deleteElement(lstedges, entry[1]) else: lt.deleteElement(lstedges, i) else: mp.put(map, pais, (e.weight(edge), i)) i += 1 orderededges = mergeSortEdges(lstedges, lt.size(lstedges))[0] return (adjacentedges, orderededges)
def inpacto_landing(analyzer, landing): Entry1 = mp.get(analyzer["landing_points"], landing) Pais_id = me.getValue(Entry1) paises_id = gr.adjacentEdges(analyzer["Arcos"], str(Pais_id["landing_point_id"])) iterador = it.newIterator(paises_id) pesos = lt.newList() while it.hasNext(iterador): Pais_id = it.next(iterador) lt.addLast(pesos, Pais_id) merge.sort(pesos, comparar_pesos) iterador_2 = it.newIterator(pesos) IDs = lt.newList() unicos = 0 while it.hasNext(iterador_2): Pais_id = it.next(iterador_2) vertice_id = Pais_id["vertexB"] Entry2 = mp.get(analyzer["paises_codigos"], vertice_id) Pais_ciudad = me.getValue(Entry2) nombre = str(Pais_ciudad["name"]).split(",") nombre_pais = str(nombre[-1]) if not lt.isPresent(IDs, nombre_pais): lt.addLast(IDs, nombre_pais) unicos += 1 return unicos, IDs
def rutaTuristicaResistencia(analyzer, time, idstation): #Req. 4 vertices = {} res = gr.adjacentEdges(analyzer['graph'], str(idstation)) #res = lista iterator = it.newIterator(res) while it.hasNext(iterator): current = it.next(iterator) if current['weight'] < time: vertices[current['vertexB']] = current['weight'] return vertices
def hallarCiclasPorVertice(analyzer, values, vertices): iterator = it.newIterator(vertices) while it.hasNext(iterator): current = it.next(iterator) edges = gr.adjacentEdges(analyzer['graph'], current) iterator2 = it.newIterator(edges) while it.hasNext(iterator2): current2 = it.next(iterator2) """[cuantasciclassalen,cuantasciclasleentran]""" #print(current2) if current2['vertexB'] not in values: values[current2['vertexB']] = [0, current2['size']] else: values[current2['vertexB']][1] += current2['size'] if current not in values: values[current] = [current2['size'], 0] else: values[current][0] += current2['size']
def requerimiento7(citibike): Mayor = 0 Listav = gr.vertices(citibike["Age"]) EstacionesAd = lt.newList('SINGLE_LINKED', compareIds) ListaF = lt.newList('SINGLE_LINKED', compareIds) for i in range(1, int(lt.size(Listav)) + 1): vertice = lt.getElement(Listav, i) ListaAdj = gr.adjacentEdges(citibike["Age"], str(vertice)) for j in range(1, lt.size(ListaAdj) + 1): Arco = lt.getElement(ListaAdj, j) Numero = int(lt.getElement(ListaAdj, j)["count"]) if Numero >= Mayor: Mayor = Numero lt.addLast(EstacionesAd, Arco) for k in range(1, lt.size(EstacionesAd) + 1): Actuazion = lt.getElement(EstacionesAd, k) if int(lt.getElement(EstacionesAd, k)["count"]) >= Mayor: lt.addLast(ListaF, Actuazion) return ListaF
def LandingPointNN(analyzer, lp_vertex): ''' Calcula los landing points vecinos ''' adj_edges = gr.adjacentEdges(analyzer['connections'], lp_vertex) info_out = {} # save info of each landing point vert_dist = {} for edge_ in lt.iterator(adj_edges): nb = edge_['vertexB'] nb_id = int(nb.split('*')[0]) lp_info = m.get(analyzer['landing_points'], nb_id)['value'] info_out[edge_['vertexB']] = { 'name': lp_info['name'], 'dist': edge_['weight'], 'id': nb_id } vert_dist[edge_['vertexB']] = edge_['weight'] # sort_dist = sorted(vert_dist.items(), key=lambda x:x[1], reverse=True) return adj_edges, vert_dist, info_out
def Requerimiento5(analyzer, landing_point): listaPuntos = mp.valueSet(analyzer['landing_points']) for punto in lt.iterator(listaPuntos): nombre = punto['name'].split(", ")[0] if nombre == landing_point.title(): LPid = punto['landing_point_id'] vertices = mp.get(analyzer['points_vertices'], LPid)['value'] idsAdyacentes = lt.newList("ARRAY_LIST") for vertex in lt.iterator(vertices): adjacentsLst = gr.adjacentEdges(analyzer['connections'], vertex) for arco in lt.iterator(adjacentsLst): affectedLPid = arco['vertexB'].split("-")[0] if affectedLPid != LPid and affectedLPid[0] in "0123456789": if not lt.isPresent(idsAdyacentes, affectedLPid): lt.addLast(idsAdyacentes, affectedLPid) infoPunto = punto nombrePunto = infoPunto['name'].split(", ") if len(nombrePunto) > 2: paisPunto = nombrePunto[2] else: paisPunto = nombrePunto[1] listaPaises = lt.newList() for idLP in lt.iterator(idsAdyacentes): lpInfo = mp.get(analyzer['landing_points'], idLP)['value'] nombreLP = lpInfo['name'].split(", ") if len(nombreLP) > 2: pais = nombreLP[2] else: pais = nombreLP[1] verticesLP = mp.get(analyzer['points_vertices'], idLP)['value'] for verticeLP in lt.iterator(verticesLP): for vertex in lt.iterator(vertices): arco = gr.getEdge(analyzer['connections'], vertex, verticeLP) if arco is not None: infoCountry = [pais, float(arco['weight'])] if pais != paisPunto and not lt.isPresent(listaPaises, infoCountry): lt.addLast(listaPaises, infoCountry) numPaises = lt.size(listaPaises) sa.sort(listaPaises, cmpPesoPaises) return numPaises, listaPaises
def req5(analyzer,landingP): ident=cityname_to_id(analyzer,landingP) list_of_vertices=get_list_of_vertices(analyzer,ident) affected_countries=lt.newList('ARRAY_LIST') for vertex in lt.iterator(list_of_vertices): adjacents=gr.adjacentEdges(analyzer['connections'],vertex) for adjacent in lt.iterator(adjacents): ident1=adjacent['vertexB'].split('_')[0] aux=get_landingpointname_by_id(analyzer,ident1).split(',') if len(aux)>2: country=aux[2][1:] else: country=aux[1][1:] distance=adjacent['weight'] dato={'distance':distance,'country':country} esta=False for t in lt.iterator(affected_countries): if t==dato: esta=True if not esta: lt.addLast(affected_countries,dato) affected=mgs.sort(affected_countries,cmp_function_req5) return (lt.size(affected),affected)
def req2(analyzer): ''' Retorna una lista ordenada según la cantidad de arcos de cada vértice. ''' numMayor = 0 listaArcos = lt.newList( "ARRAY_LIST" ) # Lista para sacar el vértice con más arcos, puesto que es necesario recorrer todos. for vertex in lt.iterator(gr.vertices(analyzer['landingPoints'])): adyacentes = gr.adjacentEdges(analyzer['landingPoints'], vertex) if lt.size(adyacentes) >= numMayor: numMayor = lt.size( adyacentes ) # Cuando se encuentra el vértice con más arcos se obtienen sus adyacentes. verticeArcos = {'vertice': vertex, 'size': numMayor} lt.addLast(listaArcos, verticeArcos) return sortNumEdgesReq2( listaArcos) # Se realiza un Merge Sort de los LP con más adyacentes.
paisValue = mp.get(analyzer['countries'], pais)['value'] coordenadasPais = [ paisValue['CapitalLatitude'], paisValue['CapitalLongitude'] ] baseReq2 = Figure(width=750, height=550) mapaReq2 = folium.Map(location=coordenadasPais, tiles='cartodbpositron', zoom_start=4) grupoCaminos = folium.FeatureGroup("Req 2") for arco in lt.iterator( gr.adjacentEdges(analyzer['landingPoints'], verticeMasArcosReq2)): verticeB = arco['vertexB'] id_verticeB = arco['vertexB'].split('-')[0] ''' {'key': '4862', 'value': {'landing_point_id': '4862', 'id': 'virginia-beach-va-united-states', 'name': 'Virginia Beach, VA, United States', 'latitude': 36.755008, 'longitude': -76.059198, 'lista': {'elements': ['4862-BRUSA', '4862-BRUSA', '4862-Confluence-1', '4862-Confluence-1', '4862-Confluence-1', '4862-Confluence-1', '4862-Dunant', '4862-Dunant', '4862-MAREA', '4862-MAREA'], 'size': 10, 'type': 'ARRAY_LIST', 'cmpfunction': <function defaultfunction at 0x000001DC70E5EE58>, 'key': None}}} ''' infoVerticeB = mp.get(analyzer['infoLandingPoints'], id_verticeB) if infoVerticeB is not None: coordenadas = [ infoVerticeB['value']['latitude'], infoVerticeB['value']['longitude']
def requerimiento2(citibike, tiempo, idestacion): listaadyacentes = gr.adjacentEdges( citibike["graph"], idestacion) ##Haya los arcos del Vertice Inicial ## listaestaciones = lt.newList('SINGLE_LINKED', compareIds) ##Crea Lista for i in range(1, lt.size(listaadyacentes) + 1): ##Hace un recorrido por la lista de arcos arco = lt.getElement(listaadyacentes, i) if arco["vertexA"] == idestacion: lt.addLast(listaestaciones, arco["vertexB"] ) ##Agrefa El vetice B de los Arcos Iniciales ## ##No necesito supachato = scc.KosarajuSCC(citibike["graph"]) fuertementeconectados = lt.newList('SINGLE_LINKED', compareIds) for i in range(1, lt.size(listaestaciones) + 1): verticeB = lt.getElement(listaestaciones, i) if scc.stronglyConnected(supachato, idestacion, verticeB): lt.addLast(fuertementeconectados, verticeB) ##Agrega los fuertemente conectados a una lista listadepilas = lt.newList('SINGLE_LINKED', compareIds) for i in range(1, lt.size(fuertementeconectados) + 1): vertice = lt.getElement(fuertementeconectados, i) matenme = dfs.DepthFirstSearch(citibike["graph"], vertice) pila = dfs.pathTo(matenme, idestacion) lt.addLast(listadepilas, pila) listadeciclos = lt.newList('SINGLE_LINKED', compareIds) for i in range(1, lt.size(listadepilas) + 1): listanueva = lt.newList('SINGLE_LINKED', compareIds) pila = lt.getElement(listadepilas, i) for j in range(1, stack.size(pila) + 1): k = stack.pop(pila) lt.addLast(listanueva, k) lt.addLast(listadeciclos, listanueva) listadefinitiva = lt.newList('SINGLE_LINKED', compareIds) for i in range(1, lt.size(listadeciclos) + 1): ciclo = lt.getElement(listadeciclos, i) peso = 0 for j in range(1, lt.size(ciclo)): verticeA = lt.getElement(ciclo, j) verticeB = lt.getElement(ciclo, (j + 1)) arco = gr.getEdge(citibike["graph"], verticeA, verticeB) peso += int(arco["weight"]) peso = peso + ((lt.size(ciclo)) * 1200) peso = peso / 60 if peso <= tiempo: lt.addLast(listadefinitiva, ciclo) if lt.isEmpty(listadefinitiva): return False else: return listadefinitiva
def revisar(citibike, estacion, rango1, rango2): revisar = scc.KosarajuSCC(citibike["graph"]) estacion_base = m.get(revisar["idscc"], estacion) valores = m.keySet(revisar["idscc"]) elegidos = lt.newList("ARRAY_LIST") for i in range(1, lt.size(valores) + 1): llave = lt.getElement(valores, i) if me.getValue(m.get(revisar["idscc"], llave)) == me.getValue(estacion_base): lt.addLast(elegidos, llave) grafo_SCC = { "graph": gr.newGraph( datastructure="ADJ_LIST", directed=True, size=lt.size(elegidos) + 1, comparefunction=compareStations, ) } for i in range(1, lt.size(elegidos) + 1): vertex = lt.getElement(elegidos, i) adyacentes = gr.adjacentEdges(citibike["graph"], vertex) for o in range(lt.size(adyacentes) + 1): arco_adyacente = lt.getElement(adyacentes, o) for e in range(1, lt.size(elegidos) + 1): comprueba = lt.getElement(elegidos, e) if arco_adyacente["vertexB"] == comprueba: addStation(grafo_SCC, vertex) addStation(grafo_SCC, comprueba) addConnection(grafo_SCC, vertex, comprueba, arco_adyacente["weight"]) search = dfs.DepthFirstSearch(grafo_SCC["graph"], estacion) anexo = djk.Dijkstra(grafo_SCC["graph"], estacion) arcos = gr.edges(grafo_SCC["graph"]) elegidos = [] caminos_candidatos_DFS = lt.newList("ARRAY_LIST") caminos_candidatos_DJK = lt.newList("ARRAY_LIST") for i in range(1, lt.size(arcos) + 1): arco = lt.getElement(arcos, i) if arco["vertexB"] == estacion: elegidos.append(arco["vertexA"]) for i in elegidos: caminoDFS_pila = dfs.pathTo(search, i) caminoDFS_lista = lt.newList("ARRAY_LIST") caminoDJK_pila = djk.pathTo(anexo, i) caminoDJK_list = lt.newList("ARRAY_LIST") caminoDJK_final = lt.newList("ARRAY_LIST") for e in range(1, lt.size(caminoDJK_pila) + 1): add = sta.pop(caminoDJK_pila) lt.addLast(caminoDJK_list, add) for e in range(1, lt.size(caminoDFS_pila) + 1): add = sta.pop(caminoDFS_pila) lt.addLast(caminoDFS_lista, add) if lt.size(caminoDJK_list) > 0: for e in range(1, lt.size(caminoDJK_list) + 1): elemento = lt.getElement(caminoDJK_list, e) if e == 1: lt.addLast(caminoDJK_final, elemento["vertexA"]) lt.addLast(caminoDJK_final, elemento["vertexB"]) else: lt.addLast(caminoDJK_final, elemento["vertexB"]) if lt.size(caminoDJK_final) > 0: lt.addLast(caminoDJK_final, estacion) lt.addLast(caminos_candidatos_DJK, caminoDJK_final) if lt.size(caminoDFS_lista) > 0: lt.addLast(caminoDFS_lista, estacion) lt.addLast(caminos_candidatos_DFS, caminoDFS_lista) caminos_finales_pesos = lt.newList("ARRAY_LIST") caminos_candidatos(caminos_candidatos_DJK, grafo_SCC, caminos_finales_pesos, rango1, rango2) caminos_candidatos(caminos_candidatos_DFS, grafo_SCC, caminos_finales_pesos, rango1, rango2) return caminos_finales_pesos