def create_graph(analyzer,file): for line in file: key=line['cable_name'] value=line['capacityTBPS'] mp.put(analyzer['cable_capacidad'],str(key),float(value)) vertice_origen=(line['\ufefforigin'],line['cable_name']) vertice_destino=(line['destination'],line['cable_name']) if gr.containsVertex(analyzer['connections'],vertice_origen) == False: gr.insertVertex(analyzer['connections'],vertice_origen) if gr.containsVertex(analyzer['connections'],vertice_destino) == False: gr.insertVertex(analyzer['connections'],vertice_destino) distancia=(line['cable_length'].replace(' km','')).replace(',','') if distancia == 'n.a.': distancia=500 else: distancia=float(distancia) gr.addEdge(analyzer['connections'],vertice_origen,vertice_destino,distancia) añadir_capitales(analyzer) vertices_por_paises(analyzer) nombre_codigo(analyzer) conexion_lp(analyzer) añadir_capitales_aburridas(analyzer) vertice_pais(analyzer)
def loadconnections_internet(analyzer, connection): grafo = analyzer["connections_internet"] mapa = analyzer["landing_points"] peso = 0 if not gr.containsVertex(grafo, (connection["origin"], connection["cable_id"])): gr.insertVertex(grafo, (connection["origin"], connection["cable_id"])) pareja1 = m.get(mapa, connection["origin"]) valor1 = me.getValue(pareja1) lt.addLast( valor1["conexiones"], { 'vertice': (connection["origin"], connection["cable_id"]), "capacityTBPS": connection["capacityTBPS"] }) if not gr.containsVertex( grafo, (connection["destination"], connection["cable_id"])): gr.insertVertex(grafo, (connection["destination"], connection["cable_id"])) pareja2 = m.get(mapa, connection["destination"]) valor2 = me.getValue(pareja2) lt.addLast( valor2["conexiones"], { 'vertice': (connection["destination"], connection["cable_id"]), "capacityTBPS": connection["capacityTBPS"] }) peso = float(connection["capacityTBPS"]) gr.addEdge(grafo, (connection["origin"], connection["cable_id"]), (connection["destination"], connection["cable_id"]), peso) gr.addEdge(grafo, (connection["destination"], connection["cable_id"]), (connection["origin"], connection["cable_id"]), peso)
def addLPToCapital(analyzer, country): vertexid = str(country['Internet users'])+'-'+ str(country['CountryCode']) if not gr.containsVertex(analyzer['connections'], vertexid): gr.insertVertex(analyzer['connections'], vertexid) keys = mp.keySet(analyzer["landingPoints"]) cName = str(country['CapitalName'])+','+str(country['CountryName']) lp = {'landing_point_id':country['Internet users'], 'id': country['Internet users'], 'name': str(cName), 'latitude':country['CapitalLatitude'] , 'longitude':country['CapitalLongitude']} if not mp.contains(analyzer["landingPoints"],country['Internet users']): mp.put(analyzer['landingPoints'], country['Internet users'], lp) existsEntry = mp.get(analyzer["lpVertices"], country['Internet users']) if existsEntry == None: dataentry = lt.newList('ARRAY_LIST', compareLandingPointIds) mp.put(analyzer["lpVertices"],country['Internet users'], dataentry) else: dataentry = me.getValue(existsEntry) lt.addLast(dataentry, vertexid) for key in lt.iterator(keys): name = (me.getValue(mp.get(analyzer["landingPoints"],key)))['name'] if country['CountryName'] in name: destinationName = str(key) + '-' + str(country['CountryCode']) if not gr.containsVertex(analyzer['connections'], destinationName): gr.insertVertex(analyzer['connections'], destinationName) existsEntry = mp.get(analyzer["lpVertices"], key) if existsEntry != None: dataentry = me.getValue(existsEntry) lt.addLast(dataentry, destinationName) origin = getCapitalCityCoordenates(analyzer, country) destination = getCoordinates(analyzer, key) distance = haversine(origin[0], origin[1], destination[0], destination[1]) addConnection(analyzer, vertexid, destinationName, distance) return analyzer
def sameCC(analyzer, station1, station2): vert1 = gr.containsVertex(analyzer["graph"], station1) vert2 = gr.containsVertex(analyzer["graph"], station2) if vert1 is False and vert2 is False: return "0" elif vert1 is False: return "1" elif vert2 is False: return "2" else: return scc.stronglyConnected(analyzer['components'], station1, station2)
def addStation(citibike, stationid): """ Adiciona una estación como un vertice del grafo """ if not gr.containsVertex(citibike['graph'], stationid): gr.insertVertex(citibike['graph'], stationid) if not gr.containsVertex(citibike['grafo'], stationid): gr.insertVertex(citibike['grafo'], stationid) return citibike
def sameCC(graph, station1, station2): """ RETO4 | REQ1 Consulta si dos vértices pertenecen al mismo componente fuertemente conectado. """ sc = scc.KosarajuSCC(graph) if gr.containsVertex(graph, station1) and gr.containsVertex( graph, station2): return scc.stronglyConnected(sc, station1, station2) else: return None
def IsItConnected(analyzer, verta, vertb): """ Calcula los componentes conectados del grafo Se utiliza el algoritmo de Kosaraju """ if gr.containsVertex(analyzer["graph"], verta) and gr.containsVertex( analyzer["graph"], vertb): analyzer['components'] = scc.KosarajuSCC(analyzer['graph']) return scc.stronglyConnected(analyzer['components'], verta, vertb) else: print("La estación no existe") return False
def findShortestCAs(analyzer, initCA, destCA, hourStart, hourEnd): if hourStart.minute >= 0 and hourStart.minute <= 15: horaIni = hourStart.replace(minute=0, second=0, microsecond=0) elif hourStart.minute > 15 and hourStart.minute <= 30: horaIni = hourStart.replace(minute=15, second=0, microsecond=0) elif hourStart.minute > 30 and hourStart.minute <= 45: horaIni = hourStart.replace(minute=45, second=0, microsecond=0) elif hourStart.minute > 45 and hourStart.minute <= 59: horaIni = hourStart.replace(minute=0, second=0, microsecond=0) if hourStart.hour == 23: hora = 0 else: hora = hourStart.hour + 1 horaIni = hourStart.replace(hour=hora, minute=0, second=0, microsecond=0) if hourEnd.minute >= 0 and hourEnd.minute <= 15: horaFin = hourEnd.replace(minute=0, second=0, microsecond=0) elif hourEnd.minute > 15 and hourEnd.minute <= 30: horaFin = hourEnd.replace(minute=15, second=0, microsecond=0) elif hourEnd.minute > 30 and hourEnd.minute <= 45: horaFin = hourEnd.replace(minute=45, second=0, microsecond=0) elif hourEnd.minute > 45 and hourEnd.minute <= 59: horaFin = hourEnd.replace(minute=0, second=0, microsecond=0) if hourEnd.hour == 23: hora = 0 else: hora = hourEnd.hour + 1 horaFin = hourEnd.replace(hour=hora, minute=0, second=0, microsecond=0) vertIni = str(initCA) + " - " + str(horaIni) vertDest = str(destCA) + " - " + str(horaFin) if gr.containsVertex(analyzer["communityAreas"], vertIni) == True and gr.containsVertex( analyzer["communityAreas"], vertDest) == True: minimumCostPaths(analyzer, vertIni) path = minimumCostPath(analyzer, vertDest) if path is not None: tiempo = 0 iterador2 = it.newIterator(path) while it.hasNext(iterador2): camino = it.next(iterador2) tiempo += camino["weight"] return path, tiempo else: return None, None else: return False, False
def addCapital_V_E(analyzer, element): graph_distance = analyzer["connections_distance"] graph_capacity = analyzer["connections_capacity"] country = element["CountryName"].lower() city = element["CapitalName"].lower() if not gr.containsVertex(graph_distance, (city, 0)): gr.insertVertex(graph_distance, (city, 0)) if not gr.containsVertex(graph_capacity, (city, 0)): gr.insertVertex(graph_capacity, (city, 0)) if mp.get(analyzer["vertices"], country) != None: mapa = mp.get(analyzer["vertices"], country)["value"] lista = mp.keySet(mapa) i = 1 while i <= lt.size(lista): lp_cable = lt.getElement(lista, i) info_lp_cable = mp.get(mapa, lp_cable)["value"] tuple_place_cablename = lp_cable id_place = tuple_place_cablename[0] location = mp.get(analyzer["location_dado_id"], id_place)["value"] edge_identifier = (tuple_place_cablename, (city, 0)) cost = {"distance": None, "capacity": None} cost["distance"] = float( hs.haversine(location, (float(element["CapitalLatitude"]), float(element["CapitalLongitude"])))) cost["capacity"] = float(info_lp_cable["capacityTBPS"]) mp.put(analyzer["edges"], edge_identifier, cost) gr.addEdge(graph_distance, tuple_place_cablename, (city, 0), cost["distance"]) gr.addEdge(graph_distance, (city, 0), tuple_place_cablename, cost["distance"]) gr.addEdge(graph_capacity, tuple_place_cablename, (city, 0), cost["capacity"]) gr.addEdge(graph_capacity, (city, 0), tuple_place_cablename, cost["capacity"]) i += 1 else: sinMar(analyzer, country, city)
def addStation(analyzer, stationid): """ Adiciona una estación como un vertice del grafo """ if not gr.containsVertex(analyzer ["uniones"], stationid): gr.insertVertex(analyzer ["uniones"], stationid) return analyzer
def addStation(citibike, station_id): """ Agrega el ID de una estación como vértice del grafo si es que este no existe. """ if not gr.containsVertex(citibike['graph'], station_id): gr.insertVertex(citibike['graph'], station_id)
def addStation(catalogo, area): """ Adiciona una estación como un vertice del grafo """ if not gr.containsVertex(catalogo["grafo"], area): gr.insertVertex(catalogo["grafo"], area) return catalogo
def theBestRoute(graph,station1,station2,timemin,timemax): best=None bestpath=None besttime=100000000 timemax=timechange(timemax) timemin=timechange(timemin) i=timemin while i<=timemax: stationstart=station1+";;"+str(i) stationend=station2+";;"+str(i) if gr.containsVertex(graph,stationstart): dijk=djk.Dijkstra(graph,stationstart) wa=djk.pathTo(dijk,stationend) y=djk.distTo(dijk,stationend) if wa!=None: if y<=besttime: besttime=y best =i bestpath= wa i+=15 if best!=None: best=timechangeback(best) way=[best,bestpath,besttime] return way
def parteC(analyzer, communityAreaOrigin, communityAreaDestination, rangeTime): answer = {"bestTime": "No identificada", "route": None, "duration": inf} graph = analyzer['AreaGraph'] rangeTime2 = rangeTime.split("-") ls = aboutQuarterHour(rangeTime2[0]) totalq = allQuartersInRange(rangeTime) totalq.append(ls) endVertexes = [] vertexes = gr.vertices(graph) iterator = it.newIterator(vertexes) while it.hasNext(iterator): vertex2 = it.next(iterator) vertex2 = vertex2.split("-") if communityAreaDestination == vertex2[0]: endVertexes.append("-".join(vertex2)) for i in totalq: initialVertex = communityAreaOrigin + "-" + i if gr.containsVertex(graph, initialVertex): print("A") search = djk.Dijkstra(graph, initialVertex) print("B") for k in endVertexes: if djk.hasPathTo(search, k): duration = str(djk.distTo(search, k)) route = djk.pathTo(search, k) if float(duration) < float(answer["duration"]): answer["duration"] = duration answer["route"] = route answer["bestTime"] = i return answer
def addVerMst(catalog, pointid): try: if not gr.containsVertex(catalog['mst'], pointid): gr.insertVertex(catalog['mst'], pointid) return catalog except Exception as exp: error.reraise(exp, 'model:addVerMst')
def req4(citibike, TiempoResistencia, IdEstacionI): tiempoRuta = 0 if gr.containsVertex(citibike["graph"], IdEstacionI): verticesAdy = gr.adjacents(citibike["graph"], IdEstacionI) z = m.get(citibike["namesI"], IdEstacionI) nombreX = en.getValue(z) nombreI = nombreX["nombre"] else: return ("La estación escogida no existe") listaFinal = [] if verticesAdy["size"] == 0: print("La estación escogida no tiene estaciones adyacentes") else: for i in range(0, (verticesAdy["size"] + 1)): tiempoRuta = 0 listaRuta = lt.newList("SINGLED_LINKED") listaArcos = [] vertice = lt.getElement(verticesAdy, i) lt.addLast(listaRuta, vertice) valorArco = gr.getEdge(citibike["graph"], IdEstacionI, vertice)["weight"]["duracion"] listaArcos.append(valorArco) tiempoRuta = int(valorArco) req4Parte2(citibike, TiempoResistencia, vertice, tiempoRuta, listaRuta, listaFinal, IdEstacionI, listaArcos, nombreI) return listaFinal
def minimumCostPaths(analyzer, initialStation): if gr.containsVertex(analyzer["communityAreas"], initialStation) == True: analyzer['paths'] = djk.Dijkstra(analyzer['communityAreas'], initialStation) return analyzer else: return "0"
def addpoint(analyzer, point): try: if not gr.containsVertex(analyzer["connections"], point): gr.insertVertex(analyzer["connections"], point) return analyzer except Exception as exp: error.reraise(exp, "model:addpoint")
def addVertex(analyzer, vertexid): try: if not gr.containsVertex(analyzer['connections'], vertexid): gr.insertVertex(analyzer['connections'], vertexid) return analyzer except Exception as exp: error.reraise(exp, 'model:addstop')
def connectSameCapital(analyzer): rela = analyzer['relatedVertex'] congr = analyzer['connections'] countries = analyzer['countries'] points = analyzer['points'] codes = m.keySet(rela) size = lt.size(codes) for i in range(0, size): key = lt.getElement(codes, i) landPoint = me.getValue(m.get(points, key)) location = landPoint['name'] country = location.split(',')[-1] country = country.strip() countryEntry = m.get(countries, country) if countryEntry is not None: countryInfo = me.getValue(countryEntry) capital = countryInfo['CapitalName'] if gr.containsVertex(congr, capital) == False: gr.insertVertex(congr, capital) cap_lat = countryInfo['CapitalLatitude'] cap_lon = countryInfo['CapitalLongitude'] cap = {'latitude': cap_lat, 'longitude': cap_lon} entry = m.get(rela, key) codeList = me.getValue(entry) codeSize = lt.size(codeList) distance = haversine(cap, landPoint) for j in range(0, codeSize): vertex = lt.getElement(codeList, j) addConnection(congr, capital, vertex, distance) return analyzer
def addLanding(macrostructure, landing): """ Adiciona una estación como un vertice del grafo """ if not gr.containsVertex(macrostructure['connections'], landing): gr.insertVertex(macrostructure['connections'], landing) return macrostructure
def segunda_consulta(citibike, time1, time2, identificador): present = gr.containsVertex(citibike['graph'], identificador) if present == True: nombre_inicial = identificador #nombre_final = "" dicc = {} lista = lt.newList(cmpfunction=compareroutes) tiempo_total = abs(int(time1) - int(time2)) citibike['components'] = numSCC_2(citibike['graph']) number = numSCC(citibike['graph']) key = gr.adjacents(citibike['graph'], nombre_inicial) tiempo = 0 ite = it.newIterator(key) while tiempo < tiempo_total and it.hasNext(ite): pro = it.next(ite) pertenecer = sameCC(citibike['components'], nombre_inicial, pro) if pertenecer == True: peso = gr.getEdge(citibike["graph"], nombre_inicial, pro) p = peso["weight"] res = abs(tiempo_total - (p + 20)) tiempo = res dicc["inicial"] = nombre_inicial dicc["final"] = pro dicc["tiempo"] = peso lt.addLast(lista, dicc) nombre_inicial = pro #nombre_final = pro answer = (number, lista) else: answer = "La estación no es válida, ingrese otra. " return answer
def addLandingVertexCapacity(analyzer, LandingId): try: if not gr.containsVertex(analyzer['connectionsCapacity'], LandingId): gr.insertVertex(analyzer['connectionsCapacity'], LandingId) return analyzer except Exception as exp: error.reraise(exp, 'model:addLandingVertex')
def addStation(bikes, stationid): if not gr.containsVertex(bikes["grafo"], stationid): gr.insertVertex(bikes["grafo"], stationid) iminpq.insert(bikes["topsalida"], stationid, 1) iminpq.insert(bikes["topllegada"], stationid, 1) iminpq.insert(bikes["topuso"], stationid, 1) return bikes
def addStation(catalog, stationId): """ Adiciona una estación como un vértice del grafo """ if not gr.containsVertex(catalog['graph'], stationId): gr.insertVertex(catalog['graph'], stationId) return catalog
def addComunity(graph, comunity): """ Adiciona una community area como un vertice del grafo """ if not gr.containsVertex(graph, comunity): gr.insertVertex(graph, comunity) return graph
def addLandPointNormal(analyzer,LandPoint): try: if not gr.containsVertex(analyzer['connections_normal'], LandPoint): gr.insertVertex(analyzer['connections_normal'], LandPoint) return analyzer except Exception as exp: error.reraise(exp, 'model:addLandPointNormal')
def addVertex(analyzer, stopid): if not gr.containsVertex(analyzer['connections_origin_destination'], stopid): gr.insertVertex(analyzer['connections_origin_destination'], stopid) return analyzer
def loadconnections_distancia(analyzer, connection): grafo = analyzer["connections_distancia"] mapa = analyzer["landing_points"] peso = 0 if not gr.containsVertex(grafo, (connection["origin"], connection["cable_id"])): gr.insertVertex(grafo, (connection["origin"], connection["cable_id"])) pareja1 = m.get(mapa, connection["origin"]) valor1 = me.getValue(pareja1) lt.addLast( valor1["conexiones"], { 'vertice': (connection["origin"], connection["cable_id"]), "capacityTBPS": connection["capacityTBPS"] }) lt.addLast(valor1["vecinos"], (connection["destination"], connection["cable_id"], connection['cable_length'][:-3].replace(',', ''))) if not gr.containsVertex( grafo, (connection["destination"], connection["cable_id"])): gr.insertVertex(grafo, (connection["destination"], connection["cable_id"])) pareja2 = m.get(mapa, connection["destination"]) valor2 = me.getValue(pareja2) lt.addLast( valor2["conexiones"], { 'vertice': (connection["destination"], connection["cable_id"]), "capacityTBPS": connection["capacityTBPS"] }) lt.addLast(valor2["vecinos"], (connection["origin"], connection["cable_id"], connection['cable_length'][:-3].replace(',', ''))) if connection["cable_length"] != 'n.a.': peso = float(connection["cable_length"][:-3].replace(',', '')) else: par1 = m.get(mapa, connection["origin"]) lat1 = me.getValue(par1)['latitude'] lon1 = me.getValue(par1)['longitude'] par2 = m.get(mapa, connection["destination"]) lat2 = me.getValue(par2)['latitude'] lon2 = me.getValue(par2)['longitude'] peso = hs.haversine((float(lat1), float(lon1)), ((float(lat2), float(lon2)))) gr.addEdge(grafo, (connection["origin"], connection["cable_id"]), (connection["destination"], connection["cable_id"]), peso) gr.addEdge(grafo, (connection["destination"], connection["cable_id"]), (connection["origin"], connection["cable_id"]), peso)
def grafoEdades(listaViajes): grafo = gr.newGraph(datastructure="ADJ_LIST", directed=True, size=1000, comparefunction=comparer) iteEdades = it.newIterator(listaViajes) while it.hasNext(iteEdades): viaje = it.next(iteEdades) estacion1 = viaje["start station id"] estacion2 = viaje["end station id"] duracion = int(viaje["tripduration"]) if not gr.containsVertex(grafo, estacion1): gr.insertVertex(grafo, estacion1) if not gr.containsVertex(grafo, estacion2): gr.insertVertex(grafo, estacion2) gr.addEdge(grafo, estacion1, estacion2, duracion) return grafo