def test_top_pop(): """ Este test prueba la creacion de una cola y que el orden de salida sea el correcto para la estructura en cuestion, y que el tamaño se reduzca para cada salida de objeto """ stack = st.newStack(list_type) assert st.size(stack) == 0 assert st.isEmpty(stack) st.push(stack, book5) st.push(stack, book6) st.push(stack, book3) st.push(stack, book10) st.push(stack, book1) st.push(stack, book2) st.push(stack, book8) st.push(stack, book4) st.push(stack, book7) st.push(stack, book9) total = st.size(stack) while not (st.isEmpty(stack)): top = st.top(stack) assert (st.pop(stack) == top) total -= 1 assert (total == st.size(stack))
def RutasCirculares(analyzer, vertice, limiteInicial, limiteFinal): #REQUERIMIENTO 2 peso = 0 rutas_circulares_total = lt.newList( datastructure='SINGLE_LINKED', cmpfunction=None) #agrupar todas las rutas cicrulares dijkstraIda = djk.Dijkstra(analyzer['connections'], vertice) vertices = gr.vertices(analyzer['connections']) iter2 = it.newIterator(vertices) while it.hasNext(iter2): datos_rutas = lt.newList( datastructure='SINGLE_LINKED', cmpfunction=None) # info todas las rutas cicrulares ruta_circular = lt.newList( datastructure='SINGLE_LINKED', cmpfunction=None ) #lista de nombres de estaciones en la ruta circular vertice2 = it.next(iter2) caminos_ida = djk.pathTo(dijkstraIda, vertice2) #grafo conocer vertices dijkstraVenida = djk.Dijkstra(analyzer['connections'], vertice2) caminos_venida = djk.pathTo(dijkstraVenida, vertice) if not caminos_venida or not caminos_ida: continue while not stack.isEmpty(caminos_ida): dato = stack.pop(caminos_ida) lt.addLast(ruta_circular, dato) while not stack.isEmpty(caminos_venida): dato = stack.pop(caminos_venida) lt.addLast(ruta_circular, dato) # lt.addLast(rutas_circulares_total, ruta_circular) iter = it.newIterator(ruta_circular) while it.hasNext(iter): arco = it.next(iter) duracion = arco['weight'] if (int(limiteInicial) < duracion and duracion < int(limiteFinal)): estacion1 = m.get(analyzer['EstacionesXid'], arco['vertexA']) estacion2 = m.get(analyzer['EstacionesXid'], arco['vertexB']) lt.addLast( datos_rutas, { "estacion1": estacion1, "estacion2": estacion2, "duracion": duracion }) lt.addLast(rutas_circulares_total, datos_rutas) return (rutas_circulares_total)
def RutaMinima(catalog, paisA, paisB): mapaLP = catalog['landing_points'] mapaCountries = catalog['countries'] mapaCountries2 = catalog['countries2'] grafo = catalog['grafo'] capitalA = me.getValue(mp.get(mapaCountries, paisA))['CapitalName'] capitalB = me.getValue(mp.get(mapaCountries, paisB))['CapitalName'] dijkstra = djk.Dijkstra(grafo, capitalA) distancia_total = djk.distTo(dijkstra, capitalB) ruta_cruda = djk.pathTo(dijkstra, capitalB) ruta = qu.newQueue('ARRAY_LIST') previo = None while not stk.isEmpty(ruta_cruda): punto = stk.pop(ruta_cruda)['vertexB'] dist = djk.distTo(dijkstra, punto) if not mp.contains(mapaCountries2, punto): punto = 'Landing point ' + punto.split('-')[0] print(dist) print(punto) p_d = (punto, dist) if not previo == punto: qu.enqueue(ruta, p_d) previo = punto return ruta, distancia_total
def recorrido_resistencia(analyzer, initStation, Tmax): newGraph = bfs.BreadhtFisrtSearch(analyzer["graph"], initStation, Tmax) #archivo=open("perro.txt","w") #archivo.write(str(newGraph)) #print(newGraph["visited"]["table"]) keys = m.keySet(newGraph["visited"]) iterator = it.newIterator(keys) rutas = [] while it.hasNext(iterator): station = it.next(iterator) #for el in newGraph["visited"]["table"]["elements"]: #if el["key"]!=None and el["value"]["final"]==True: if me.getValue(m.get(newGraph["visited"], station))["final"] == True: ruta = [] path = bfs.pathTo(newGraph, station) i = 0 while not st.isEmpty(path): entry = st.pop(path) if entry == initStation: ruta = {"Estaciones": [entry], "Duraciones": []} else: ruta["Estaciones"].append(entry) edge = gr.getEdge(analyzer["graph"], ruta["Estaciones"][i - 1], entry) duration = edge['weight'] / 60 ruta["Duraciones"].append(duration) i += 1 rutas.append(ruta) return rutas
def getBestSchedule(graph, pickUp, dropOff, InitialTime, EndTime): bestSchedule = InitialTime currentStamp = InitialTime first = getTime(graph, pickUp, dropOff, currentStamp) bestTime = first[0] search = first[1] while currentStamp != EndTime: currentStamp = add15(currentStamp) time = getTime(graph, pickUp, dropOff, currentStamp) if time[0] < bestTime: bestSchedule = currentStamp bestTime = time[0] search = time[1] path = [] pathTo = djk.pathTo(search, dropOff) if pathTo is None: path = None else: while not st.isEmpty(pathTo): edge = st.pop(pathTo) Com = edge["vertexA"] path.append(Com) if st.size(pathTo) == 0: Com2 = edge["vertexB"] path.append(Com2) return bestSchedule, path, bestTime
def optionSix(cont, destStation): delta_time = -1.0 tracemalloc.start() start_time = getTime() jose = m.newMap() path = controller.minimumCostPath(cont, destStation) if path is not None: pathlen = stack.size(path) while (not stack.isEmpty(path)): stop = stack.pop(path) if m.contains(jose, stop['vertexB']) == False: m.put(jose, stop['vertexB'], 1) pacho = m.keySet(jose) arias = lt.size(pacho) print('Numero de vertices: ' + str(arias)) print("El numero de arcos es: ", pathlen) else: print('No hay camino') stop_time = getTime() tracemalloc.stop() delta_time = stop_time - start_time print("Tiempo [ms]: ", f"{delta_time:.3f}")
def test_infoElements(stack, books): assert (st.size(stack) == 0) assert (st.isEmpty(stack)) st.push(stack, books[5]) st.push(stack, books[6]) st.push(stack, books[3]) st.push(stack, books[10]) st.push(stack, books[1]) st.push(stack, books[2]) st.push(stack, books[8]) st.push(stack, books[4]) st.push(stack, books[7]) st.push(stack, books[9]) elem = st.top(stack) assert (st.size(stack) == 10) assert (elem == books[9]) elem = st.pop(stack) assert (st.size(stack) == 9) assert (elem == books[9]) elem = st.pop(stack) assert (st.size(stack) == 8) assert (elem == books[7]) elem = st.top(stack) assert (st.size(stack) == 8) assert (elem == books[4]) st.push(stack, books[9]) assert (st.size(stack) == 9) elem = st.top(stack) assert (elem == books[9])
def print_req3(catalog, pais1, pais2): path = controller.req3(catalog, pais1, pais2) recorrido = 0 print_separador_gigante() print("Ruta:") print_separador_sensillo() if path is not None: if "No se ha encontrado los/el pais que está buscando " not in path: while (not stack.isEmpty(path)): point = stack.pop(path) recorrido += int(point["weight"]) print("Landig Point A: " + str(controller.des_vertice(point["vertexA"])) + ", " + " Landig Point B: " + str(controller.des_vertice(point["vertexB"])) + ", " + " Distancia: " + str(point["weight"]) + " km") print_separador_sensillo() print("El recorrido total es de: " + str(recorrido) + " km") print_separador_gigante() else: print(path) print_separador_gigante else: print_separador_sensillo() print("No se ha encontrado un camino") print_separador_gigante()
def optionFour(catalog, country_1, country_2): "Req 3 - Dijkstra" capital_1 = controller.getCapitalCity(catalog, country_1) capital_2 = controller.getCapitalCity(catalog, country_2) if (capital_1 is not None) and (capital_2 is not None): path = controller.minimumDistanceCountries(catalog, capital_1, capital_2) if path is not None: path_folium = path.copy() printMapDijkstra(catalog, path_folium) print("\nPresione 'enter' para ver el siguente\n") total_dist = 0.0 while not stack.isEmpty(path): edge = stack.pop(path) total_dist += edge['weight'] print(edge['vertexA'] + "-->" + edge['vertexB'] + " costo: " + str(edge['weight']) + " km") input() print('El costo total es de ', total_dist, 'km') else: print('No existe el camino entre', capital_1, 'y', capital_2) else: print('Alguno de los paises no fue valido')
def dfs(graph, search, v): """ DFS Args: search: La estructura de busqueda v: Vertice desde donde se relajan los pesos Returns: El grafo Raises: Exception """ try: map.put(search['marked'], v, True) map.put(search['onStack'], v, True) edges = g.adjacentEdges(graph, v) for edge in lt.iterator(edges): w = e.other(edge, v) if (not st.isEmpty(search['cycle'])): return search elif ((not map.get(search['marked'], w)['value'])): map.put(search['edgeTo'], w, edge) dfs(graph, search, w) elif (map.get(search['onStack'], w)['value']): f = edge while (e.either(f) != w): st.push(search['cycle'], f) f = map.get(search['edgeTo'], e.either(f))['value'] st.push(search['cycle'], f) return search map.put(search['onStack'], v, False) except Exception as exp: error.reraise(exp, 'cycle:dfs')
def optionFour(): verticeCentral = input( "Ingrese la estación para la cual desea realizar la consulta (Ejemplo 3661, 477): " ) LimiteInferior = (int( input("Ingrese el limite inferior del rango a consultar (Ej 120): ")) ) * 60 LimiteSuperior = (int( input("Ingrese el limite superior del rango a consultar (Ej 240): ")) ) * 60 listaAdyacentes = controller.ListaAdyacentes(cont, verticeCentral, LimiteInferior, LimiteSuperior) print("\nSe encontraron en total {} rutas cíclicas:\n ".format( listaAdyacentes[0])) while (not stack.isEmpty(listaAdyacentes[1])): stop = stack.pop(listaAdyacentes[1]) print( "Esta ruta tarda en total {} minutos, tiene {} estaciones, teniendo en cuenta un tiempo de 20 minutos por estacion. " .format( (round((stop["PesoPorRuta"] / 60), 2)), str(queue.size(stop)), )) while stop and (not queue.isEmpty(stop)): stopDOS = queue.dequeue(stop) print( "-> Parte de la estacion {}, hasta la estación {} y tarda {} minutos en el trayecto. " .format(stopDOS['vertexA'], stopDOS['vertexB'], round((stopDOS['weight'] / 60), 2))) print("\n")
def printOptionSeven(route): """ RETO4 | REQ5 Imprime el requerimiento 5. """ if route is not None: departure_station, arrival_station, pathTo, age_range, cost = route print('\nLa edad ingresada se encuentra en el rango de: ' + str(age_range) + ' años.') print('Estación inicial más común para la edad ingresada: ' + str(departure_station['key']) + ' con: ' + str(departure_station['value']['Departure_Ages'][age_range]) + ' viajes.') print('Estación final más común para la edad ingresada: ' + str(arrival_station['key']) + ' con: ' + str(arrival_station['value']['Arrival_Ages'][age_range]) + ' viajes.') if pathTo is None: print('No hay ruta válida que conecte a las dos estaciones.') else: print( 'La ruta más corta entre estas dos estaciones, tiene un costo de: ' + str(cost) + ' segundos, el recorrido es: ') while (not stack.isEmpty(pathTo)): station = stack.pop(pathTo) print( str(station['vertexA']) + ' - ' + str(station['vertexB'])) else: print('La edad ingresada no es válida.')
def test_dfo(graph): search = dfo.DepthFirstOrder(graph) assert stack.size(search['reversepost']) == 10 print('') while not stack.isEmpty(search['reversepost']): top = stack.pop(search['reversepost']) print(top)
def hayarEstaciones(cont, initialStation): informacion = gr.adjacents(cont["connections"], initialStation) lista=[] if stack.isEmpty(informacion) == False: for i in range(0, stack.size(informacion)): sub_pila = stack.pop(informacion) lista.append(sub_pila) return lista
def Ruta_interes_turistico(grafo, latitud1, longitud1, latitud2, longitud2): Latitud1 = float(latitud1) / 57.29577951 Longitud1 = float(longitud1) / 57.29577951 Latitud2 = float(latitud2) / 57.29577951 Longitud2 = float(longitud2) / 57.29577951 menor = None menor_dist = 10000000000 menor2 = None menor_dist2 = 10000000000 estaciones = grafo["Estaciones"] entry = m.keySet(estaciones) iterador = it.newIterator(entry) while it.hasNext(iterador): elemento = it.next(iterador) entry = m.get(estaciones, elemento) valor = me.getValue(entry) latitud = float(valor["Latitud"]) / 57.29577951 longitud = float(valor["Longitud"]) / 57.29577951 dis_estacion_salida = 3963.0 * math.acos( math.sin(Latitud1) * math.sin(latitud) + math.cos(Latitud1) * math.cos(latitud) * math.cos(longitud - Longitud1)) dis_estacion_llegada = 3963.0 * math.acos( math.sin(Latitud2) * math.sin(latitud) + math.cos(Latitud2) * math.cos(latitud) * math.cos(longitud - Longitud2)) if dis_estacion_salida <= menor_dist: menor = elemento menor_dist = dis_estacion_salida if dis_estacion_llegada <= menor_dist2: menor2 = elemento menor_dist2 = dis_estacion_llegada lista = lt.newList("ARRAY_LIST", comparar_esta) path = djk.Dijkstra(grafo["graph"], menor) path_ = djk.pathTo(path, menor2) costo = djk.distTo(path, menor2) estaciones = grafo["Estaciones"] entry_sal = m.get(estaciones, menor) entry_lle = m.get(estaciones, menor2) estacion_sali = me.getValue(entry_sal)["Nombre"] estacion_lleg = me.getValue(entry_lle)["Nombre"] while (not st.isEmpty(path_)): stop = st.pop(path_) entryA = m.get(estaciones, stop["vertexA"]) estacion_1 = me.getValue(entryA)["Nombre"] if lt.isPresent(lista, estacion_1) == 0: lt.addLast(lista, estacion_1) entryB = m.get(estaciones, stop["vertexB"]) estacion_2 = me.getValue(entryB)["Nombre"] if lt.isPresent(lista, estacion_2) == 0: lt.addLast(lista, estacion_2) return lista, estacion_sali, estacion_lleg, costo
def test_cycle(cgraph): search = c.DirectedCycle(cgraph) assert c.hasCycle(search) is True path = c.cycle(search) print('\n') while not stack.isEmpty(path): edge = stack.pop(path) print(edge['vertexA'] + "-->" + edge['vertexB'] + " costo: " + str(edge['weight']))
def test_dijkstra_armenia(graph): search = djk.Dijkstra(graph, 'Bogota') assert djk.hasPathTo(search, 'Armenia') is True path = djk.pathTo(search, 'Armenia') print('\n') while not stack.isEmpty(path): edge = stack.pop(path) print(edge['vertexA'] + "-->" + edge['vertexB'] + " costo: " + str(edge['weight'])) print(str(djk.distTo(search, 'Armenia')))
def test_top_pop(stack, books): assert st.size(stack) == 0 assert st.isEmpty(stack) st.push(stack, books[5]) st.push(stack, books[6]) st.push(stack, books[3]) st.push(stack, books[10]) st.push(stack, books[1]) st.push(stack, books[2]) st.push(stack, books[8]) st.push(stack, books[4]) st.push(stack, books[7]) st.push(stack, books[9]) total = st.size(stack) while not (st.isEmpty(stack)): top = st.top(stack) assert (st.pop(stack) == top) total -= 1 assert (total == st.size(stack))
def test_bellman_bogotaac(acgraph): search = bf.BellmanFord(acgraph, 'S1') assert bf.hasPathTo(search, 'S6') is True path = bf.pathTo(search, 'S6') print('\n') while not stack.isEmpty(path): edge = stack.pop(path) print(edge['vertexA'] + "-->" + edge['vertexB'] + " costo: " + str(edge['weight'])) print(str(bf.distTo(search, 'S6')))
def optionSix(): path = controller.minimumCostPath(cont, destStation) if path is not None: pathlen = stack.size(path) print('El camino es de longitud: ' + str(pathlen)) while (not stack.isEmpty(path)): stop = stack.pop(path) print(stop) else: print('No hay camino')
def test_error_pop(): """ Este test busca comprobar que es imposible eliminar un objeto de una pila vacia """ stack = st.newStack(list_type) assert (st.size(stack) == 0) assert (st.isEmpty(stack)) with pytest.raises(Exception): st.pop(stack)
def optionTen(): edad = input("Escriba edad para generar una ruta recomendada: ") recommendedPath = controller.recommendedPathsBono(cont, edad) lstIterator = it.newIterator(recommendedPath) while it.hasNext(lstIterator): it.next(lstIterator) each = it.next(lstIterator) while (not stack.isEmpty(each)): stop = stack.pop(each) print(("es el par de estaciones {} y {} ".format( stop["vertexA"], stop["vertexB"])))
def print_Req3(camino): if camino is not None: distCamino = stk.size(camino) longitud = 0 while (not stk.isEmpty(camino)): cada_vertice = stk.pop(camino) longitud += cada_vertice['weight'] print(cada_vertice) print('El camino es de longitud [km]: ' + str(longitud) + '.') else: print('No hay camino.')
def optionfive(cont, p1, p2): info = controller.minroute(cont, p1, p2) totdis = info[1] path = info[0] print("\nLa distancia total del recorrido es: " + str(totdis) + " km") print("\nLa ruta mínima es: ") n = 1 while st.isEmpty(path) == False: step = st.pop(path) print(str(n) + ". "+ step["vertexA"] + "-" + step["vertexB"] + ", Distancia: " + str(step["weight"]) + " km") n+=1
def optionSix(cont, destStation): path1 = controller.minimumCostPath(cont, destStation) path = path1[1] if path is not None: pathlen = stack.size(path) print('El camino es de longitud: ' + str(pathlen)) while (not stack.isEmpty(path)): stop = stack.pop(path) print(stop) else: print('No hay camino') print('Tiempo de ejecucion:', ((path1[0]) / 1000))
def test_push_pop(): """ Este test prueba que la cola pueda manejar inserciones y eliminaciones de forma correcta siguiendo un orden establecido, y que no quede referencia al objeto sacado despues de haberlo removido de la cola """ stack = st.newStack(list_type) assert (st.size(stack) == 0) assert (st.isEmpty(stack)) st.push(stack, book5) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book6) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book3) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book10) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book1) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book2) assert (st.size(stack) == 1) assert (st.top(stack) == st.pop(stack)) assert (st.size(stack) == 0) st.push(stack, book8) st.push(stack, book4) st.push(stack, book7) st.push(stack, book9) assert (st.size(stack) == 4) assert book9 == st.pop(stack) assert book7 == st.pop(stack) assert book4 == st.pop(stack) assert book8 == st.pop(stack) assert (st.size(stack) == 0)
def req3(catalog,vera,verb): con=catalog['connections'] s=djk.Dijkstra(con,vera) f=djk.pathTo(s,verb) init=0 t=True while t: y=stack.pop(f) t= not stack.isEmpty(f) print('De el landing point '+y['vertexA']+' y el landing point '+y['vertexB']+' hay '+str(round(y['weight'],2))+' km.') init+=y['weight'] print('La distancia total entre '+vera+' y '+verb+' es de '+str(round(init,2))+' km.')
def optionSix(cont, destStation): respuesta = controller.minimumCostPath(cont, destStation) path = respuesta[1] if path is not None: pathlen = stack.size(path) print('El camino es de longitud: ' + str(pathlen)) while (not stack.isEmpty(path)): stop = stack.pop(path) print(stop) print("Tiempo [ms]: " + str(respuesta[0])) else: print('No hay camino')
def optionSix(cont, destStation): ti = time.time() path = controller.minimumCostPath(cont, destStation) if path is not None: pathlen = stack.size(path) print('El camino es de longitud: ' + str(pathlen)) while (not stack.isEmpty(path)): stop = stack.pop(path) print(stop) else: print('No hay camino') tf = time.time() print('Tiempo de ejecución:', tf - ti)
def KosarajuUnicoSCC(graph, vertex): """ Implementa el algoritmo de Kosaraju para encontrar los componentes conectados de un grafo dirigido Args: graph: El grafo a examinar Returns: Una estructura con los componentes conectados Raises: Exception """ try: scc_u = { 'idscc': None, 'marked': None, 'grmarked': None, 'components': 0 } scc_u['idscc'] = map.newMap(g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction']) scc_u['marked'] = map.newMap(g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction']) scc_u['grmarked'] = map.newMap( g.numVertices(graph), maptype='PROBING', comparefunction=graph['comparefunction']) # Se calcula el grafo reverso de graph greverse = reverseGraph(graph) # Se calcula el DFO del reverso de graph dforeverse = dfo.DepthFirstOrder(greverse) grevrevpost = dforeverse['reversepost'] # Se recorre el grafo en el orden dado por reversepost (G-reverso) scc_u['components'] = 0 while (not stack.isEmpty(grevrevpost)): vert = stack.pop(grevrevpost) if vert == str(vertex): if not map.contains(scc_u['marked'], vert): scc_u['components'] += 1 sccCount(graph, scc_u, vert) return scc_u except Exception as exp: error.reraise(exp, 'scc_u:Kosaraju')