def EstacionesParaPublicidad(citibike, e1, e2): mapa1 = citibike["info1"] mapa2 = citibike["info2"] arcos = gr.edges(citibike["customers"]) stopiterator = it.newIterator(arcos) lista = lt.newList("ARRAY_LIST", compareRoutes) trip = 0 while it.hasNext(stopiterator): element = it.next(stopiterator) edad = element["weight"] viajes = element["division"] dicc = {} if (e1 <= edad <= e2) and viajes > trip: lista = lt.newList("ARRAY_LIST", compareRoutes) trip = viajes a = m.get(mapa1, element["vertexA"]) b = m.get(mapa2, element["vertexB"]) c = a["value"] d = b["value"] st1 = c["start station name"] st2 = d["end station name"] dicc = {st1: trip, st2: trip} lt.addLast(lista, dicc) elif (e1 <= edad <= e2) and viajes == trip: a = m.get(mapa1, element["vertexA"]) b = m.get(mapa2, element["vertexB"]) c = a["value"] d = b["value"] st1 = c["start station name"] st2 = d["end station name"] dicc = {st1: trip, st2: trip} lt.addLast(lista, dicc) return lista
def criticStations(citibike): """ Top 3 Llegada, Top 3 Salida y Top 3 menos usadas Req 3 """ #Listas respuesta topLlegada = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareroutes) topSalida = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareroutes) intopUsadas = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareroutes) #Listas temporales para obtener el top 3 top3LS = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareroutes) inTop3 = lt.newList(datastructure='ARRAY_LIST', cmpfunction=compareroutes) tempLT = lt.newList(cmpfunction=compareroutes) ltKeys = gr.edges(citibike['connections']) for arc in range(1, lt.size(ltKeys) + 1): lt.addLast(tempLT, lt.getElement(ltKeys, arc)['count']) ms.mergesort(tempLT, greatequal) for i in range(1, 10): lt.addLast(top3LS, lt.getElement(tempLT, i)) for i in range(3): lt.addLast(inTop3, lt.getElement(tempLT, lt.size(tempLT) - i)) vxl = 1 while vxl <= lt.size(tempLT) and lt.size(topLlegada) <= 3: if lt.isPresent(top3LS, lt.getElement(ltKeys, vxl)['count']): vxA = getStation(citibike, lt.getElement(ltKeys, vxl)['vertexA'])[1] if not lt.isPresent(topLlegada, vxA): lt.addLast(topLlegada, vxA) vxl += 1 vxs = 1 while vxs <= lt.size(tempLT) and lt.size(topSalida) <= 3: if lt.isPresent(top3LS, lt.getElement(ltKeys, vxs)['count']): vxB = getStation(citibike, lt.getElement(ltKeys, vxs)['vertexB'])[1] if not lt.isPresent(topLlegada, vxB): lt.addLast(topSalida, vxB) vxs += 1 vxin = 1 while vxin <= lt.size(tempLT) and lt.size(intopUsadas) <= 3: if lt.isPresent(inTop3, lt.getElement(ltKeys, vxin)['count']): vxA = getStation(citibike, lt.getElement(ltKeys, vxin)['vertexA'])[1] if not lt.isPresent(intopUsadas, vxA): lt.addLast(intopUsadas, vxA) vxin += 1 return topLlegada, topSalida, intopUsadas
def graphicateReq4(analyzer, minigraph): map4 = folium.Map() vertexes = gr.vertices(minigraph) edges = gr.edges(minigraph) for i in lt.iterator(vertexes): split = i.split('-') split = split[0] if float(split) < 20000: vertice = mp.get(analyzer['LP_lat_long'], split)['value'] folium.Marker(vertice).add_to(map4) else: split2 = i.split("Capital Connection ") split2 = split2[1] countri = mp.get(analyzer['countries2'], split2)['value'] verticei = [float(countri['CapitalLatitude']), float( countri['CapitalLongitude'])] folium.Marker(verticei).add_to(map4) for i in lt.iterator(edges): vertexA = i['vertexA'] vertexB = i['vertexB'] splitA = vertexA.split('-') splitA = splitA[0] splitB = vertexB.split('-') splitB = splitB[0] route = [] if float(splitA) < 20000: verticei = mp.get(analyzer['LP_lat_long'], splitA)['value'] route = [verticei] else: split2 = vertexA.split("Capital Connection ") split2 = split2[1] countri = mp.get(analyzer['countries2'], split2)['value'] verticei = [float(countri['CapitalLatitude']), float( countri['CapitalLongitude'])] route = [verticei] if float(splitB) < 20000: verticei = mp.get(analyzer['LP_lat_long'], splitB)['value'] route.append(verticei) else: split2 = vertexB.split("Capital Connection ") split2 = split2[1] countri = mp.get(analyzer['countries2'], split2)['value'] verticei = [float(countri['CapitalLatitude']), float( countri['CapitalLongitude'])] route.append(verticei) folium.PolyLine(route).add_to(map4) direction = cf.data_dir + 'MapREQ4.html' map4.save(direction)
def requerimiento8(citibike): Lista = gr.edges(citibike["Day"]) enmovimiento = 0 for i in range(1, lt.size(Lista) + 1): edge = lt.getElement(Lista, i) enmovimiento = enmovimiento + int(edge["weight"]) enestacionamiento = 86400 - enmovimiento estaciones = gr.vertices(citibike["Day"]) retorno = lt.newList('SINGLE_LINKED', compareIds) lt.addLast(retorno, enmovimiento) lt.addLast(retorno, enestacionamiento) lt.addLast(retorno, estaciones) return retorno
def req7(citibike, rango): lista = gr.edges(citibike['graph']) iterador = it.newIterator(lista) maximo = 0 pareja = 'No hay' while it.hasNext(iterador): elemento = it.next(iterador) diccA = m.get(citibike['stops'], elemento['vertexA']) diccB = m.get(citibike['stops'], elemento['vertexB']) if diccA['value'][4] == 'Customer' and diccB['value'][4] == 'Customer': suma = diccA['value'][2].get(rango) + diccB['value'][3].get(rango) if suma > maximo: pareja = elemento return (pareja)
def para_mantenimiento(citibike, fecha, ide): fecha = str_to_python_time(fecha) arbol = om.get(citibike["mapa_fecha"], fecha) arbol = me.getValue(arbol) mapa = m.get(arbol, ide) grafo = me.getValue(mapa) arcos = gr.edges(grafo) horas_organizadas = lt.newList("ARRAY_LIST") camino_organizado = lt.newList("ARRAY_LIST") for i in range(1, lt.size(arcos) + 1): elemento = lt.getElement(arcos, i) corre_hora = str(elemento["inicio"]) corre_hora = datetime.datetime.strptime(corre_hora, "%H:%M:%S.%f") corre_hora = datetime.datetime.time(corre_hora) lt.addLast(horas_organizadas, corre_hora) mge.mergesort(horas_organizadas, comparador_horas) for i in range(1, lt.size(horas_organizadas) + 1): hora = lt.getElement(horas_organizadas, i) for e in range(1, lt.size(arcos) + 1): arco = lt.getElement(arcos, e) corre_hora = str(arco["inicio"]) corre_hora = datetime.datetime.strptime(corre_hora, "%H:%M:%S.%f") corre_hora = datetime.datetime.time(corre_hora) arco["inicio"] = corre_hora if corre_hora == hora: lt.addLast(camino_organizado, arco) for i in range(1, lt.size(camino_organizado) + 1): elemento = lt.getElement(camino_organizado, i) if i == 1: parqueada = conver_to_seconds(elemento["inicio"]) usada = conver_to_seconds(elemento["final"]) - conver_to_seconds( elemento["inicio"]) else: usada += conver_to_seconds(elemento["final"]) - conver_to_seconds( elemento["inicio"]) parqueada += conver_to_seconds( elemento["inicio"]) - conver_to_seconds( (lt.getElement(camino_organizado, i - 1))["final"]) if i == lt.size(camino_organizado): resta = conver_to_seconds("23:59:59") parqueada += resta - conver_to_seconds(elemento["final"]) return (usada, parqueada, camino_organizado)
def avgDuration(citibike): """ Actualiza el valor de los arcos al promedio de la duración de los viajes entre dos estaciones """ edges = gr.edges(citibike['graph']) iterator = it.newIterator(edges) while it.hasNext(iterator): element = it.next(iterator) pair = str(element['vertexA']) + ',' + str(element['vertexB']) entry = m.get(citibike['pairs'], pair) repetitions = entry['value'] average = element['weight'] / repetitions # if str(element['vertexA']) == '72': # print(average) ed.updateWeight(element, average) return citibike
def TiempoNecesariomod(analyzer, GPCC, limites): if GPCC == False: return False else: Ideal = {} Pesos = {} for A in GPCC: Pesos[A] = 0 n = it.newIterator(gr.edges(GPCC[A])) if it.hasNext(n): d = it.next(n) Pesos[A] += ed.weight(d) LimiteInferior = 0*60 LimiteSuperior = limites*60 for B in Pesos: if Pesos[B] >= LimiteInferior and Pesos[B] <= LimiteSuperior: Ideal[B] = GPCC[B] if len(Ideal) == 0: return "Vacio" else: return Ideal
def rutaPorResistencia(citibike, tiempoMax, idEstacionInicial): """ Rutas turisticas por resistencia Req 4 """ ltEdges = gr.edges( citibike['connections'] ) #Retornar lista con todos los arcos del arco (Vertices - Peso Arco) rutas = lt.newList(datastructure='ARRAY_LIST' ) #Lista vacia para agregar las rutas -> return for i in range(1, lt.size(ltEdges) + 1): station = lt.getElement( ltEdges, i) #Estacion final - Estacion inicial (id) -> str if str(idEstacionInicial) == station[ 'vertexA']: #Identificar los que tienen el mismo idEstacionInicial duration = station[ 'weight'] / 60 #Duracion (tripduration) en minutos duration = round(duration, 2) if duration <= tiempoMax: lt.addLast(rutas, (station['vertexA'], station['vertexB'], duration)) return rutas['elements']
def announcementStation(analyzer, edad): edgelst = gr.edges(analyzer['graph']) edgeiterator = it.newIterator(edgelst) mayor = 0 r = [] e_mayor1 = { 'Estación Incio: ': 0, 'Esación llegada: ': 0, 'viajes_Totales: ': 0 } while it.hasNext(edgeiterator): e_mayor2 = { 'Estación Incio: ': 0, 'Esación llegada: ': 0, 'viajes_Totales: ': 0 } edge = it.next(edgeiterator) a_comparar = e.usertype(edge)[edad]['Customer'] if a_comparar > mayor: r = [] mayor = a_comparar e_mayor1['Estación Incio: '] = e.either(edge) e_mayor1['Esación llegada: '] = edge['vertexB'] e_mayor1['viajes_Totales: '] = e.getTotaltrips(edge) elif a_comparar == mayor: e_mayor2['Estación Incio: '] = e.either(edge) e_mayor2['Esación llegada: '] = edge['vertexB'] e_mayor2['viajes_Totales: '] = e.getTotaltrips(edge) r.append(e_mayor2) if e_mayor1 not in r: r.append(e_mayor1) return (r)
def circularRoutes(citibike, availableTime1, availableTime2, initialStation): """ Rutas circulares Req 2 """ ltEdges = gr.edges(citibike['connections']) numRutas = 0 ltCircularRoutes = lt.newList(datastructure='ARRAY_LIST') for i in range(1, lt.size(ltEdges) + 1): station = lt.getElement(ltEdges, i) if str(initialStation) == station['vertexA']: finalStation = station['vertexB'] try: arcoExiste = gr.getEdge(citibike['connections'], finalStation, initialStation) weightFinalStation = arcoExiste['weight'] duration = station['weight'] + weightFinalStation if duration + 20 >= availableTime1 and duration + 20 <= availableTime2: numRutas += 1 nameStartStation = getStation(citibike, initialStation)[1] nameEndStation = getStation(citibike, finalStation)[1] lt.addLast(ltCircularRoutes, (nameStartStation, nameEndStation, duration)) except: pass print("\nEl número de rutas circulares es " + str(numRutas) + " y estos son los datos: ") for i in range(1, lt.size(ltCircularRoutes) + 1): print("\nNombre de estación inicial: " + str(lt.getElement(ltCircularRoutes, i)[0])) print("\nNombre de estación final: " + str(lt.getElement(ltCircularRoutes, i)[1])) print("\nDuración estimada: " + str(lt.getElement(ltCircularRoutes, i)[2]) + " minutos")
def RecomendadorRutas(citibike, e1, e2): mapa1 = citibike["info1"] mapa2 = citibike["info2"] mapa3 = citibike["arrival"] mapa4 = citibike["exit"] mapa5 = citibike["year1"] mapa6 = citibike["year2"] arcos = gr.edges(citibike["graph"]) recorrerarcos = it.newIterator(arcos) maxviajesllegada = 0 maxviajessalida = 0 route = lt.newList("ARRAY_LIST", compareRoutes) edadfinal1 = None edadfinal2 = None id1 = None id2 = None while it.hasNext(recorrerarcos): arc = it.next(recorrerarcos) get1 = m.get(mapa3, arc["vertexA"]) get2 = m.get(mapa4, arc["vertexB"]) get3 = m.get(mapa5, arc["vertexA"]) get4 = m.get(mapa6, arc["vertexB"]) viajesllegada = get1["value"] viajessalida = get2["value"] edad1 = int(get3["value"] / viajesllegada) edad2 = int(get4["value"] / viajessalida) if (e1 <= edad1 <= e2) and viajesllegada > maxviajesllegada: edadfinal1 = edad1 maxviajesllegada = viajesllegada id1 = arc["vertexA"] if (e1 <= edad2 <= e2) and viajessalida > maxviajessalida: edadfinal2 = edad2 maxviajessalida = viajessalida id2 = arc["vertexB"] if id1 != None and id2 != None: g1 = m.get(mapa1, id1) g2 = m.get(mapa2, id2) v1 = g1["value"] v2 = g2["value"] nombre1 = v1["start station name"] nombre2 = v2["end station name"] cadena1 = "Estación de inicio:" + nombre1 lt.addLast(route, cadena1) cadena2 = "Estación de llegada:" + nombre2 lt.addLast(route, cadena2) cadena3 = "Estaciones a recorrer:" lt.addLast(route, cadena3) dijkstra = djk.Dijkstra(citibike["graph"], id1) ruta = djk.pathTo(dijkstra, id2) recorrerruta = it.newIterator(ruta) i = 0 while it.hasNext(recorrerruta): i += 1 segmento = it.next(recorrerruta) getter2 = m.get(mapa2, segmento["vertexB"]) value2 = getter2["value"] station2 = value2["end station name"] if segmento["vertexB"] != id2 and i != 1: lt.addLast(route, station2) elif segmento["vertexB"] == id2 and i == 1: lt.addLast(route, "Es un camino directo") else: lt.addLast(route, "No hay ruta") return route
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
def edges(analyzer): return gr.edges(analyzer)
def totalEdges(grafo): """ Retorna todos los arcos del grafo """ return gr.edges(grafo)