def Clusters(analyzer,l1,l2): estructura=scc.KosarajuSCC(analyzer['connections']) idscc=estructura['idscc'] #print(idscc) numero=scc.connectedComponents(estructura) land1=lt.newList() land2=lt.newList() vertices=gr.vertices(analyzer['connections']) a=lit.newIterator(vertices) answer=False while lit.hasNext(a): c=lit.next(a) h=c.split("-") #print(h) #if h[0] not in Lista: if h[0]==l1: lt.addLast(land1, c) if h[0]==l2: lt.addLast(land2, c) la1=lit.newIterator(land1) while lit.hasNext(la1): b=lit.next(la1) entry=mp.get(idscc,b) cluster=me.getValue(entry) #print(cluster) la2=lit.newIterator(land2) while lit.hasNext(la2): c=lit.next(la2) entry=mp.get(idscc,c) cluster1=me.getValue(entry) if cluster1==cluster: #print(cluster1) answer=True return (answer,numero) return (answer,numero)
def Requerimiento1(analyzer, landing_point1, landing_point2): """ Retorna ... """ clusters = scc.KosarajuSCC(analyzer['connections']) numClusters = scc.connectedComponents(clusters) mismoCluster = -1 punto1 = None punto2 = None listaPuntos = mp.valueSet(analyzer['landing_points']) for punto in lt.iterator(listaPuntos): nombre = punto['name'].split(", ")[0] if nombre == landing_point1.title(): punto1 = punto['landing_point_id'] if nombre == landing_point2.title(): punto2 = punto['landing_point_id'] if punto1 is not None and punto2 is not None: entry = mp.get(analyzer["points_vertices"], punto1) if entry is not None: lstLP1 = me.getValue(entry) lp1 = lt.firstElement(lstLP1) entry = mp.get(analyzer["points_vertices"], punto2) if entry is not None: lstLP2 = me.getValue(entry) lp2 = lt.firstElement(lstLP2) if lp1 != "" and lp2 != "": mismoCluster = scc.stronglyConnected(clusters, lp1, lp2) return numClusters, mismoCluster
def connectedComponents(analyzer): """ Calcula los componentes conectados del grafo Se utiliza el algoritmo de Kosaraju """ analyzer['components'] = scc.KosarajuSCC(analyzer['connections']) return scc.connectedComponents(analyzer['components'])
def numSCC(graph): """ RETO4 | REQ1 Retorna el número de componentes fuertemente conectados. """ sc = scc.KosarajuSCC(graph) return scc.connectedComponents(sc)
def req1(catalog, lp1, lp2): grafo = catalog["connections"] landing_points = catalog["landing_points"] traductor = catalog["traduccion"] componentes = scc.KosarajuSCC(grafo) numComponentes = componentes["components"] try: lp1 = lt.getElement(mp.get(traductor, lp1)["value"], 1) vertice1 = lp1 + "|" + lt.getElement( mp.keySet(mp.get(landing_points, lp1)["value"][1]), 1) except TypeError: vertice1 = lp1 try: lp2 = lt.getElement(mp.get(traductor, lp2)["value"], 1) vertice2 = lp2 + "|" + lt.getElement( mp.keySet(mp.get(landing_points, lp2)["value"][1]), 1) except TypeError: vertice2 = lp2 areConnected = scc.stronglyConnected(componentes, vertice1, vertice2) return numComponentes, areConnected
def Requirement1(analyzer, landing_point1, landing_point2): tracemalloc.start() delta_time = -1.0 delta_memory = -1.0 start_time = getTime() start_memory = getMemory() analyzer['components'] = scc.KosarajuSCC( analyzer['connections_origin_destination']) connected_components = scc.connectedComponents(analyzer['components']) lp1 = matchLandingPoint(analyzer, landing_point1) lp2 = matchLandingPoint(analyzer, landing_point2) parameter1 = matchGraphKeyOrigin(analyzer, lp1) parameter2 = matchGraphKeyDestination(analyzer, lp2) same_cluster = scc.stronglyConnected(analyzer["components"], parameter1, parameter2) stop_memory = getMemory() stop_time = getTime() tracemalloc.stop() delta_time = stop_time - start_time delta_memory = deltaMemory(start_memory, stop_memory) return connected_components, same_cluster, delta_time, delta_memory
def clusters(catalogo, lp1, lp2): componentes = scc.KosarajuSCC(catalogo["conexiones"]) conexionlp = scc.stronglyConnected( componentes, m.get(catalogo["invertices"], lp1)["value"], m.get(catalogo["invertices"], lp2)["value"]) return componentes["components"], conexionlp
def req2(citibike, initial_time, final_time, initial_vertex): graph = scc.KosarajuSCC(citibike['graph']) components = graph['idscc'] grande=lt.newList('ARRAY_LIST',compareStations) cycles, weights = dfs.DepthFirstSearch2(citibike['graph'],initial_vertex, components) tiempos= lt.newList('ARRAY_LIST') for i in range(len(cycles)): if initial_time <= weights[i] <= final_time: normal=lt.newList('ARRAY_LIST',compareStations) tiempo_exacto=lt.newList('ARRAY_LIST') lt.addLast(tiempo_exacto,weights[i]) lt.addLast(tiempos,tiempo_exacto) for j in cycles[i]: lt.addLast(normal,j) lt.addLast(grande,normal) for p in range(1,lt.size(grande)+1): info= lt.getElement(grande,p) for e in range (1,lt.size(info)+1): changeInfo(citibike,info,e) for w in range(1,lt.size(grande)+1): estaciones = lt.getElement(grande,w) tiempo = lt.getElement(tiempos, w) print ('El ciclo demora: ') convertSecondsToDate(tiempo['elements'][0]) print('Su camino es: ') print(estaciones['elements']) print('Se encontraron: '+ str(lt.size(grande)) + ' rutas circulares')
def req2(analizer,limiteinf,limite,verticei): grafo=analizer['connections'] sc = scc.KosarajuSCC(grafo) componente_inicio=m.get(sc['idscc'],verticei)['value'] iterator=it.newIterator(m.keySet(sc['idscc'])) verticesfc=lt.newList(cmpfunction=compareroutes) while it.hasNext(iterator): proximo=it.next(iterator) c_proximo=m.get(sc['idscc'],proximo)['value'] if c_proximo == componente_inicio: #Que el componente sea el mismo lt.addLast(verticesfc,proximo) adyacentes=gr.adjacents(grafo,verticei) iterator=it.newIterator(verticesfc) rutasposibles=[] while it.hasNext(iterator): proximo=it.next(iterator) if lt.isPresent(adyacentes,proximo): dfs3 = dfs.DepthFirstSearchSCC(grafo,proximo,verticesfc) if dfs.pathTowithLimiter(dfs3,verticei,grafo,limite) != None: rutachikita,tiempo=dfs.pathTowithLimiter(dfs3,verticei,grafo,limite) lt.removeLast(rutachikita) if limiteinf<tiempo<limite: rutasposibles.append({"First":m.get(analizer['nameverteces'],lt.firstElement(rutachikita))['value'],"Last":m.get(analizer['nameverteces'],lt.lastElement(rutachikita))['value'],"Duracion":tiempo/60}) return rutasposibles
def req1(catalog, nombre1, nombre2): kosaraju = scc.KosarajuSCC(catalog['graph_landing_points']) vertices = gr.vertices(catalog['graph_landing_points']) vert1 = None vert2 = None for vertice in lt.iterator(vertices): if vertice.split(sep='*')[1] == nombre1: vert1 = vertice elif vertice.split(sep='*')[1] == nombre2: vert2 = vertice for vertice in lt.iterator(vertices): if vertice.split(sep='*')[1] == nombre2: vert2 = vertice elif vertice.split(sep='*')[1] == nombre1: vert1 = vertice vertice_x = lt.getElement(vertices, 0) num_componentes_conectados = scc.sccCount(catalog['graph_landing_points'], kosaraju, vertice_x) #mismo_cluster = scc.stronglyConnected(kosaraju, vert1, vert2) #if mismo_cluster: # respuesta = 'Los dos landing points están en el mismo clúster' #else: # respuesta = 'Los dos landing points no están en el mismo clúster' return num_componentes_conectados #, respuesta
def connectedComponents(catalog): """ Calcula los componentes conectados del grafo Se utiliza el algoritmo de Kosaraju """ catalog["components"] = scc.KosarajuSCC(catalog["connections"]) return scc.connectedComponents(catalog["components"])
def areConnected(analyzer, lp1, lp2): analyzer['components'] = scc.KosarajuSCC(analyzer['connections']) connected = scc.stronglyConnected(analyzer['components'], lp1, lp2) if connected: return 1 else: return 0
def Requerimiento1(analyzer, landing1, landing2): analyzer['element'] = scc.KosarajuSCC(analyzer['connections_directed']) cluster_number = scc.connectedComponents(analyzer['element']) get_landing1 = mp.get(analyzer['landing_names_id'], landing1) id_landing1 = me.getValue(get_landing1) dict_landing_pareja1 = om.get(analyzer['landing_points'], id_landing1) dict_landing1 = me.getValue(dict_landing_pareja1) lista_cables1 = dict_landing1['cables'] vectorA = lt.getElement(lista_cables1, 1) get_landing2 = mp.get(analyzer['landing_names_id'], landing2) id_landing2 = me.getValue(get_landing2) dict_landing_pareja2 = om.get(analyzer['landing_points'], id_landing2) dict_landing2 = me.getValue(dict_landing_pareja2) lista_cables2 = dict_landing1['cables'] vectorB = lt.getElement(lista_cables2, 1) inform_cluster = scc.stronglyConnected(analyzer['element'], vectorA, vectorB) if inform_cluster == False: print('Los landing points consultados no estan en el mismo cluster') else: print( 'Los landing points cosnultados se encuentran en el mismo cluster') print('El total de clústers presentes en la red es igual a ' + str(cluster_number))
def cantidadClusters(analyzer, id1, id2): #Req. 1 """ ----------REQUERIMIENTO 1------------ OUTPUTS: TUPLE: (1,2) 1: Clusters 2: Sí dos nodos están en el mismo clúster 3: Variable del algoritmo """ try: var = scc.KosarajuSCC(analyzer['graph']) vertices = gr.vertices(analyzer['graph']) clusters = {'size': 0} iterator = it.newIterator(vertices) while it.hasNext(iterator): current = it.next(iterator) cod = m.get(var['idscc'], current)['value'] if cod not in clusters: clusters[cod] = lt.newList(cmpfunction=compareConnections) clusters['size'] += 1 lt.addLast(clusters[cod], current) conected = False if m.get(var['idscc'], id1) != None and m.get(var['idscc'], id2) != None: conected = scc.stronglyConnected(var, id1, id2) return (clusters, conected, var) except: return -1
def requerimiento1(catalog, point1, point2): catalog['compo'] = scc.KosarajuSCC(catalog['connections']) k = 1 g = 1 tr1 = False tr2 = False while k <= lt.size(gr.vertices(catalog['connections'])) and not tr1: j = lt.getElement(gr.vertices(catalog['connections']), k) idd1 = j.split("-", 1) ll1 = mp.get(catalog['points'], idd1[0]) name1 = ll1['value']['name'] if point1.lower() in name1.lower(): ver1 = j tr1 = True k += 1 while g <= lt.size(gr.vertices(catalog['connections'])) and not tr2: i = lt.getElement(gr.vertices(catalog['connections']), g) idd2 = i.split("-", 1) ll2 = mp.get(catalog['points'], idd2[0]) name2 = ll2['value']['name'] if point2.lower() in name2.lower(): ver2 = i tr2 = True g += 1 con = scc.stronglyConnected(catalog['compo'], ver1, ver2) requerimiento8(catalog) return scc.connectedComponents(catalog['compo']), con
def req1(analyzer,landingp1,landingp2): kosaraju=scc.KosarajuSCC(analyzer['connections_normal']) num_clusters=kosaraju['components'] origin=str(cityname_to_id(analyzer,landingp1)) destination=str(cityname_to_id(analyzer,landingp2)) estan_o_no=scc.stronglyConnected(kosaraju,origin,destination) return (num_clusters,estan_o_no)
def clusteres(analyzer,lp1,lp2): cfc=scc.KosarajuSCC(analyzer['connections']) numero=scc.connectedComponents(cfc) vertice1=me.getValue(mp.get(analyzer['nombrelp_codigo'],lp1)) vertice2=me.getValue(mp.get(analyzer['nombrelp_codigo'],lp2)) conectados=scc.stronglyConnected(cfc,vertice1,vertice2) return(numero,conectados)
def requerimiento1(graph, station1, station2): sc = scc.KosarajuSCC(graph) MaxGraph = numSCC(graph) MaxStations = sameCC(sc, station1, station2) retorno = lt.newList("ARRAY_LIST", compareIds) lt.addLast(retorno, MaxGraph) lt.addLast(retorno, MaxStations) return retorno
def stronglyConnectedComponents(analyzer): """ Retorna el número de componentes fuertemente conectados del grafo """ graph = analyzer['connections'] analyzer['sccomponents'] = scc.KosarajuSCC(graph) return scc.connectedComponents(analyzer['sccomponents'])
def calcConnectedComponents(catalog, lp1, lp2): """ Usa el algoritmo de Kosaraju Para calcular los componentes connectados del grafo. El numero de clusters (componenetes conectados) y si dos lps estan fuertemente conectados (pertencecen al mismo cluster) """ catalog['components'] = scc.KosarajuSCC(catalog['internet_graph']) num_clusters = scc.connectedComponents(catalog['components']) landpts_cluster = scc.stronglyConnected(catalog['components'], lp1, lp2) return num_clusters, landpts_cluster
def comprobarCamino(cont, initialStation, salidas): lista=[] for a in range(0,len(salidas)): nuevo_scc= scc.KosarajuSCC(cont["connections"]) verdad = scc.stronglyConnected(nuevo_scc, initialStation, salidas[a]) if verdad: lista.append(salidas[a]) if lista == []: lista = "NO EXISTEN" return lista
def ClusterCheck(macrostructure, vertex1, vertex2): connected = scc.KosarajuSCC(macrostructure['connections']) lp1 = lt.getElement((mp.get(macrostructure['lp-names'], vertex1))['value'], 1) lp2 = lt.getElement((mp.get(macrostructure['lp-names'], vertex2))['value'], 1) pertains = scc.stronglyConnected(macrostructure['connections'], lp1, lp2) #pertains = None ans = (int(connected['components']), pertains) return ans
def vertexComponents(analyzer, verta, vertb): analyzer['components'] = scc.KosarajuSCC(analyzer['connections']) numero = scc.connectedComponents(analyzer['components']) try: connect = scc.stronglyConnected(analyzer['components'], verta, vertb) if connect: print("el numero de vertices es: " + str(numero)) return "estan conectados" except: print("el numero de vertices es: " + str(numero)) return "NO estan conectados"
def connectedComponents(analyzer) -> int: """ Calcula los componentes conectados del grafo Se utiliza el algoritmo de Kosaraju """ analyzer['connected'] = scc.KosarajuSCC( analyzer['landingPoints'] ) # Se utiliza Kosaraju para encontrar los componentes conectados en el grafo. return scc.connectedComponents(analyzer['connected'])
def loadFile(analyzer, file): """ """ file = cf.data_dir + file input_file = csv.DictReader(open(file, encoding="utf-8"), delimiter=",") for route in input_file: model.AñadirRuta(analyzer, route) model.AñadiralIndex(analyzer, route) analyzer['components'] = scc.KosarajuSCC(analyzer['graph']) return analyzer
def CantidadCluster(citibike, station1, station2): clusteres = { "No. de clusteres:": None, "Las estaciones están en el mismo cluster:": None, } sc = scc.KosarajuSCC(citibike["graph"]) cant = scc.connectedComponents(sc) cond = sameCC(sc, station1, station2) clusteres["No. de clusteres:"] = cant clusteres["Las estaciones están en el mismo cluster:"] = cond return clusteres
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 circularroutes(analyzer, startvertex, time1, time2): sc = scc.KosarajuSCC(analyzer['connections']) dfsdata = dfscircular(analyzer['connections'], startvertex, sc)['cycles'] dfsdatait = it.newIterator(dfsdata) respuesta = lt.newList() while it.hasNext(dfsdatait): x = it.next(dfsdatait) camino = filtrodetiempo(x, time1, time2, analyzer['connections']) if not camino == None: lt.addLast(respuesta, camino) return respuesta
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 req1(analyzer, lpId_1, lpId_2): try: estructura_kosaraju = scc.KosarajuSCC(analyzer["connections_distance"]) num_clusteres = scc.connectedComponents(estructura_kosaraju) cable_1 = lt.getElement( mp.keySet(mp.get(analyzer["cables_dado_lpid"], lpId_1)["value"]), 1) cable_2 = lt.getElement( mp.keySet(mp.get(analyzer["cables_dado_lpid"], lpId_2)["value"]), 1) valor = scc.stronglyConnected(estructura_kosaraju, (lpId_1, cable_1), (lpId_2, cable_2)) return num_clusteres, valor except: estructura_kosaraju = scc.KosarajuSCC(analyzer["connections_distance"]) num_clusteres = scc.connectedComponents(estructura_kosaraju) return num_clusteres, True