def requerimiento4(catalog): pri = prim.PrimMST(catalog['connections']) peso = prim.weightMST(catalog['connections'], pri) mst = prim.edgesMST(catalog['connections'], pri)['mst'] m = folium.Map(location=[4.6, -74.083333], tiles="Stamen Terrain") for st in lt.iterator(mst): cv = st['vertexA'].split("-", 1) ce = st['vertexB'].split("-", 1) infov = mp.get(catalog['points'], cv[0])['value'] infoe = mp.get(catalog['points'], ce[0])['value'] addPointConneMst(catalog, st['vertexA'], st['vertexB'], st['weight']) folium.PolyLine(locations=[(float(infov['latitude']), float(infov['longitude'])), (float(infoe['latitude']), float(infoe['longitude']))], tooltip=str(cv[1])).add_to(m) folium.Marker([float(infov['latitude']), float(infov['longitude'])], popup=str(infov['name'])).add_to(m) folium.Marker([float(infoe['latitude']), float(infoe['longitude'])], popup=str(infoe['name'])).add_to(m) m.save('mapa_req4.html') gramst = catalog['mst'] vert = gr.vertices(gramst) num = lt.size(vert) primero = lt.firstElement(vert) mayor = 0 camino = None dijta = djk.Dijkstra(catalog['mst'], primero) for v in lt.iterator(vert): ruta = djk.pathTo(dijta, v) x = lt.size(ruta) if x > mayor: mayor = x camino = ruta return num, peso, camino
def MST(analyzer): #req 4 analyzer['MST'] = prim.PrimMST(analyzer['connections']) peso = prim.weightMST(analyzer['connections'], analyzer['MST']) arcos = analyzer['MST']['mst'] mincon = ['', '', -1] maxcon = ['', '', -1] x = 0 for arco in lt.iterator(arcos): distance = arco['weight'] landing_id1 = arco['vertexA'].split('~')[0] landing_name1 = m.get(analyzer['landing_points_info'], landing_id1)['value']['name'] landing_id2 = arco['vertexB'].split('~')[0] landing_name2 = m.get(analyzer['landing_points_info'], landing_id2)['value']['name'] if landing_name1 != landing_name2: if mincon[2] == -1 or distance < mincon[2]: mincon[2] = distance mincon[0] = landing_name1 mincon[1] = landing_name2 if maxcon[2] == -1 or distance > maxcon[2]: maxcon[2] = distance maxcon[0] = landing_name1 maxcon[1] = landing_name2 numvertices = gr.numVertices(analyzer['connections']) ans = numvertices, peso, mincon, maxcon return ans
def req4(catalog): grf=catalog['connections'] prim=pm.PrimMST(grf) weight=pm.weightMST(grf,prim) print('La distancia total de la red de expansion minima es de '+str(round(weight,2))+' km.') edges = pm.edgesMST(grf,prim) print('El tamano de la red de expansion minima es de '+str(edges['mst']['size'])+' landing points.')
def test_prim2(graph2): search = prim.PrimMST(graph2) weight = prim.weightMST(graph2, search) print('\n') path = search['mst'] while not q.isEmpty(path): edge = q.dequeue(path) print(edge['vertexA'] + "-->" + edge['vertexB'] + " costo: " + str(edge['weight'])) print(str(weight))
def findGraphMST(catalog): """Usa Prim para crear el MST""" mst_structure = prim.PrimMST(catalog['internet_graph']) mst_structure = prim.edgesMST(catalog['internet_graph'], mst_structure) mst = mst_structure['mst'] edgesTo = mst_structure['edgeTo'] mst_weight = prim.weightMST(catalog['internet_graph'], mst_structure) nodes = lt.size(mst) mst_graph = createMSTgraph(catalog, mst) path = getMSTroots(catalog, mst_graph) return nodes, mst_weight, path
def criticalInfrastructure(analyzer): vertex = gr.numVertices(analyzer["connections"]) tree = pr.PrimMST(analyzer["connections"]) weight = pr.weightMST(analyzer["connections"], tree) branch = pr.edgesMST(analyzer["connections"], tree) branch = branch["edgeTo"]["table"]["elements"] max = 0 for i in range(len(branch)): value = branch[i]["value"] if (value != None) and (float(value["weight"]) > max): max = value["weight"] return vertex, weight, max
def criticalstructure(analyzer): analyzer["prim"] = pr.PrimMST(analyzer["cables"]) vlist = gr.vertices(analyzer["cables"]) randomvertex = lt.getElement(vlist, randint(0, lt.size(vlist))) mst = pr.prim(analyzer["cables"], analyzer["prim"], randomvertex) weight = pr.weightMST(analyzer["cables"], analyzer["prim"]) nlps = 0 totvertex = mp.keySet(mst["marked"]) for i in lt.iterator(totvertex): a = mp.get(mst["marked"], i) value = me.getValue(a) if value == True: nlps += 1 return (nlps, weight)
def costoTotalArcosMST(analyzer): """ Devuelve el costo total del árbol de expansión mínima. Parámetros: analyzer: el catálogo donde está guardado todo. Return: un entero, que representa el costo total del árbol de expansión mínima. """ grafo = analyzer['connections'] mst = analyzer['mst'] total = prim.weightMST(grafo, mst) return total
def minimumSpanningTree(ana): countries = ana['countries'] countryKeys = m.keySet(countries) points = ana['points'] search = prim.PrimMST(ana['connections']) relaxed = prim.prim(ana['connections'], search, 'Bogota') prim.edgesMST(ana['connections'], search) mst = relaxed['mst'] size = lt.size(mst) weight = round(prim.weightMST(ana['connections'], relaxed), 2) M = folium.Map() for i in range(0, lt.size(mst)): camino = lt.getElement(mst, i) punto = camino['vertexB'] code = punto.split('*')[0] try: int(code) lPoint = me.getValue(m.get(points, code)) pointLat = lPoint['latitude'] pointLon = lPoint['longitude'] pointLoc = pointLat, pointLon name = str(i) + '. ' + lPoint['name'] folium.Marker(pointLoc, name, icon=folium.Icon(color='blue')).add_to(M) except: capital = code n = 0 found = False while n < lt.size(countryKeys) and found == False: key = lt.getElement(countryKeys, n + 1) info = me.getValue(m.get(countries, key)) Capital = info['CapitalName'] if capital == Capital: found = True country = info['CountryName'] capLat = info['CapitalLatitude'] capLon = info['CapitalLongitude'] capLoc = capLat, capLon capName = str(i) + '. ' + country + ', ' + capital folium.Marker(capLoc, capName, icon=folium.Icon(color='pink')).add_to(M) n += 1 M.save('MST.html') return weight, size
def req4(analyzer): vertex= gr.numVertices(analyzer['connections']) arbol= pr.PrimMST(analyzer['connections']) weight= pr.weightMST(analyzer['connections'],arbol) branch= pr.edgesMST(analyzer['connections'],arbol) branch= branch['edgeTo']['table']['elements'] maximo=0 for a in range(len(branch)): valor= branch[a]['value'] if (valor != None) and (float(value['weight'])> max): maximo = value['weight'] print("Numero de nodos conectados a la red de expansión mínima: "+ str(vertex)) print("Costo total de la red de expansión mínima: "+ str(weight)) print("Rama más larga que hace parte de la red de expansión mínima: "+str(maximo)) return vertex,weight,maximo
def minExpansion(catalog): # numelements debería ser la mitad??? # Se crea un mapa {"#componente": {v1: None, v2:None, ...}, ...} mapa_componentes = mp.newMap(numelements=113, maptype="PROBING", loadfactor=0.4) for vertice in lt.iterator(mp.keySet(catalog["components"]["idscc"])): numero_componente = mp.get(catalog["components"]["idscc"], vertice)["value"] addComponente(mapa_componentes, numero_componente, vertice) mayor = None conteo_mayor = 0 for componente in lt.iterator(mp.keySet(mapa_componentes)): mapa_vertices = mp.get(mapa_componentes, componente)["value"] numero_vertices = mp.size(mapa_vertices) #print(componente, numero_vertices) if numero_vertices > conteo_mayor: #if numero_vertices == 10: mayor = componente conteo_mayor = numero_vertices #mayor = 106, conteo_mayor=1983 #print(type(mayor)) lista_vertices_mayor = mp.keySet(mp.get(mapa_componentes, mayor)["value"]) #verts_mayor = mp.keySet(mp.get(mapa_componentes, 82)["value"]) tamaño = lt.size(lista_vertices_mayor) tamaño, subgrafo = crearSubGrafo(catalog, lista_vertices_mayor, tamaño) search = prim.PrimMST(subgrafo) #print(search) peso = prim.weightMST(subgrafo, search) #print("peso",peso) mayor = buscarMayor(search) #print("mayor",mayor) menor = buscarMenor(search) #print("menor",menor) return tamaño, peso, mayor, menor
def Requirement4(analyzer): tracemalloc.start() delta_time = -1.0 delta_memory = -1.0 start_time = getTime() start_memory = getMemory() mst = prim.PrimMST(analyzer['connections_origin_destination']) size = lt.size(mp.keySet(mst['edgeTo'])) distance = prim.weightMST(analyzer['connections_origin_destination'], mst) stop_memory = getMemory() stop_time = getTime() tracemalloc.stop() delta_time = stop_time - start_time delta_memory = deltaMemory(start_memory, stop_memory) return (size, distance, delta_time, delta_memory)
def req4(analyzer): estructura = pr.PrimMST(analyzer["connections_distance"]) costo_total = pr.weightMST(analyzer["connections_distance"], estructura) grafo_mst = gr.newGraph(datastructure='ADJ_LIST', directed=True, size=5000, comparefunction=None) i = 1 while i <= lt.size(estructura["mst"]): arista = lt.getElement(estructura["mst"], i) verticeA = arista["vertexA"] verticeB = arista["vertexB"] weight = arista["weight"] if not gr.containsVertex(grafo_mst, verticeA): gr.insertVertex(grafo_mst, verticeA) if not gr.containsVertex(grafo_mst, verticeB): gr.insertVertex(grafo_mst, verticeB) gr.addEdge(grafo_mst, verticeA, verticeB, weight) gr.addEdge(grafo_mst, verticeB, verticeA, weight) i += 1 num_vertices = gr.numVertices(grafo_mst) vertices_mst = gr.vertices(grafo_mst) inicio = lt.firstElement(estructura["mst"])["vertexA"] final = lt.lastElement(estructura["mst"])["vertexB"] estructura_dfs = dfs.DepthFirstSearch(grafo_mst, inicio) caminoo = dfs.pathTo(estructura_dfs, final) return num_vertices, costo_total, caminoo
def infraestructura_critica(analyzer): arbol = p.PrimMST(analyzer["Arcos"]) vertices = gr.numVertices(analyzer["Arcos"]) Peso = p.weightMST(analyzer["Arcos"], arbol) rama = p.edgesMST(analyzer["Arcos"], arbol) rama = rama["edgeTo"]["table"]["elements"] maximo = 0 for i in range(len(rama)): valor = rama[i]["value"] if (valor is not None) and (float(valor["weight"]) > maximo): maximo = valor["weight"] vertice1 = valor["vertexA"] vertice2 = valor["vertexB"] cables = mp.valueSet(analyzer["cables_origen"]) iterador = it.newIterator(cables) while it.hasNext(iterador): elemento = it.next(iterador) if elemento["origin"] == vertice1 and vertice2 == elemento[ "destination"]: cable = elemento["cable_name"] return vertices, Peso, cable, maximo
def Requerimiento4(analyzer): mst = prim.PrimMST(analyzer['connections']) numNodos = mp.size(mst['marked']) pesoMst = prim.weightMST(analyzer['connections'], mst) return numNodos, round(pesoMst, 2)
def infraestructura_critica(analyzer): mst=prim.PrimMST(analyzer['connections']) cantidad_nodos=(mst['marked']['size']) peso=prim.weightMST(analyzer['connections'],mst) return cantidad_nodos,peso
def req4(analyzer): search=prim.PrimMST(analyzer['connections_normal']) distance=prim.weightMST(analyzer['connections_normal'],search) mst=search['mst'] numberofnodes=qu.size(mst) return(distance,numberofnodes)
def costMST (analyzer): cost = prim.weightMST(analyzer['connections'], analyzer['MST']) return cost
def redminima(catalogo): redmin = pr.PrimMST(catalogo["conexiones"]) peso = pr.weightMST(catalogo["conexiones"], redmin) verts = redmin["mst"]["size"] return verts, peso
def tot_peso_mst(grafo, mst): return prim.weightMST(grafo, mst)