def getTest(): # # route pour tester si les choses fonctionnent bien comme on le veut # # test pour savoir si graphe_marvel_avec_comics fonctionne normalement # g = tlp.loadGraph('marvel.tlpb') # plabel = g.getStringProperty("viewLabel") # dico_nodes = graphe_marvel_avec_comics(g) # print(len(dico_nodes)) # s = 0 # for n in dico_nodes.keys(): #Les clés de dico_nodes sont les heros # print(len(dico_nodes[n])) # s += 1 # print("comparons mnt s et dico_nodes") # print(s) # print(len(dico_nodes)) # #dico_nodes est donc non vide, fonctionne # # Test pour voir suppression_node fonctionne # # On va supprimer spiderman de son univers # personnage = "Spider-Man" # (subG,node_p) = get_graph_from_char(g,personnage) # plabel = g.getStringProperty("viewLabel") # dico_nodes = graphe_marvel_sans_comics(subG) # Fonctionne # color = g.getColorProperty("viewColor") # (nodes,nodes_id) = creation_nodes(plabel,dico_nodes,color) #Fonctionne # links = liens(dico_nodes,nodes_id) # (dico_nodes_apres_suppression, links_apres_suppression) = suppression_node(dico_nodes,nodes_id,links, node_p) # output = "" # for n in dico_nodes.keys(): # output = output + plabel[n] + "<br>" # print("Les personnages dans dico_nodes apres suppression sont au nombre de :") # print(len(dico_nodes)) # #Quand on regarde les heros presents apres suppression, Spider-Man n'est pas present # #On a effectivement perdu 1 sur len dico_nodes # #Il faudrait s'assurer que c'est le cas aussi dans links graphe_marvel_tulip() g = tlp.loadGraph('heroes.tlpb') tlp.saveGraph(g, "heroes.tlpx") plabel = g.getStringProperty("viewLabel") output = "" compteur = 0 for n in g.getNodes(): output = output + plabel[n] + "<br>" compteur += 1 print(compteur) return output
def graphe_marvel_tulip(): g = tlp.loadGraph('marvel.tlpb') picon = g.getStringProperty("viewIcon") plabel = g.getStringProperty("viewLabel") g['viewSelection'].setAllNodeValue(False) heroes_dict = { } #Dictionnaire que l'on va utiliser pour augmenter le poids sur les arêtes for n in g.getNodes(): if picon[n] == 'md-book-open': voisins = list(tlp.Graph.getInOutNodes(g, n)) counter = 1 for x in voisins: for y in voisins[ counter:]: # On commence a counter pour ne pas repasser sur des nodes que l'on a deja vu edge_x_y = tlp.Graph.existEdge(g, x, y, directed=True) edge_y_x = tlp.Graph.existEdge(g, y, x, directed=True) if (tlp.edge.isValid(edge_x_y) or tlp.edge.isValid(edge_y_x) ): # On regarde si une des 2 edge existe if (tlp.edge.isValid(edge_x_y) ): #Cas 1 l'arête de x vers y existe heroes_dict = tlp.Graph.getEdgePropertiesValues( g, edge_x_y) heroes_dict[ 'poids'] += 1 # On augmente le poids de l'arête de 1 tlp.Graph.setEdgePropertiesValues( g, edge_x_y, heroes_dict) if (tlp.edge.isValid(edge_y_x) ): #Cas 2 l'arête de y vers x existe heroes_dict = tlp.Graph.getEdgePropertiesValues( g, edge_y_x) heroes_dict[ 'poids'] += 1 # On augmente le poids de l'arête de 1 tlp.Graph.setEdgePropertiesValues( g, edge_y_x, heroes_dict) else: tlp.Graph.addEdge(g, x, y, { "poids": 1 }) # On crée l'arête et on initialise son poids à 1 counter += 1 tlp.Graph.delNode(g, n) tlp.saveGraph(g, "heroes.tlpb")
def makeGraph(m,airportl,carL,dicoAir,airportperlay): graph=tlp.newGraph() latitude=graph.getDoubleProperty("latitude") longitude=graph.getDoubleProperty("longitude") name = graph.getStringProperty("nameCity") code = graph.getStringProperty("code") couche = graph.getStringVectorProperty("compagnie") color = graph.getColorProperty("viewColor") k=len(carL) colList=[(randint(0,255),randint(0,255),randint(0,255)) for i in range(k)] for n in range(len(airportl)): graph.addNode() no=graph.nodes()[n] code[no]=airportl[n] listeAttributs=dicoAir[airportl[n]] name[no]=listeAttributs[0] latitude[no]=float(listeAttributs[1]) longitude[no]=float(listeAttributs[2]) n=0 for lay in m.giveLayers().giveLayers(): car=lay.giveLayerLabel()[0] sub=graph.addSubGraph(car) nliste=airportperlay[car] for node1 in nliste : no=graph.nodes()[airportl.index(node1)] sub.addNode(no) #print(car,len(sub.nodes())) for e in m.giveLinks().giveListOfLinks(): n1=graph.nodes()[airportl.index(e.giveNodes()[0].giveNode())] n2=graph.nodes()[airportl.index(e.giveNodes()[1].giveNode())] graph.addEdge(n1,n2) ed=graph.edges()[n] n=n+1 couche[ed]=e.giveLabel()[2] color[ed]=colList[carL.index(e.giveLabel()[2][0])] sub=graph.subGraphs()[carL.index(e.giveLabel()[2][0])] car=e.giveLabel()[2][0] codenode=e.giveNodes()[0].giveNode() n1=sub.nodes()[airportperlay[car].index(codenode)] n2=sub.nodes()[airportperlay[e.giveLabel()[2][0]].index(e.giveNodes()[1].giveNode())] sub.addEdge(ed) tlp.saveGraph(graph,"output/grapheplanes.tlp") return(graph)
def getGraphVisualizationHTML(graph): vizid = 'fig_el' + str(int(random.random() * 1E10)) urls = copyNeededFilesToWebServer() dirpath = tempfile.mkdtemp() tmpGraphFile = os.path.join(dirpath, 'graph.tlpb.gz') tlp.saveGraph(graph, tmpGraphFile) tlpbgzGraphData = open(tmpGraphFile, 'rb').read() if sys.version_info[0] == 3: tlpbgzGraphDataBase64 = str(base64.b64encode(tlpbgzGraphData), 'utf-8') else: tlpbgzGraphDataBase64 = base64.b64encode(tlpbgzGraphData) shutil.rmtree(dirpath) return TULIPJS_HTML.render(vizid=vizid, tulipjs_url=urls['tulipjs'], base64utils_url=urls['base64utilsjs'], jquerytoolbarjs_url=urls['jquerytoolbarjs'], jquerytoolbarcss_url=urls['jquerytoolbarcss'], fontawesomecss_url=urls['fontawesomecss'], tlpbgz_graph_base64=tlpbgzGraphDataBase64)
def annealing(graph, cost_function, random_neighbour, temperature, maxsteps=1000, distance=.1, p=.9, debug=True): """ Optimize the black-box function 'cost_function' with the simulated annealing algorithm.""" state = graph cost = cost_function(state) states, costs = [get_position(graph)], [cost] tlp.saveGraph(state, './BSF.tlp') T = temperature sigma_temp = 1 # A CHANGER !!! for step in range(maxsteps): state = tlp.loadGraph('./BSF.tlp') fraction = step / float(maxsteps) # sigma_temp = np.std(costs) position = get_position(state) node = random_node(state) new_state, new_position, type = move_node_n3(state, position, node, p) new_cost = cost_function(new_state) if debug: print( "Step #{:>2}/{:>2} : T = {:>4.3g}, cost = {:>4.3g}, new_cost = {:>4.3g}, type {} ..." .format(step, maxsteps, T, cost, new_cost, type)) if acceptance_probability(cost, new_cost, T) > rn.random(): tlp.saveGraph(state, './BSF.tlp') state, cost = new_state, new_cost states.append(position) costs.append(cost) print(" ==> Accept it!") else: print(" ==> Reject it...") sigma_temp = 1 # A REVOIR !!!! T = new_temperature(T, sigma_temp, distance) return state, cost_function(state), states, costs
for project in small_projects: p = graph.addNode() cache['project'][project['id']] = p set_node('coordinatorCountry') set_node('coordinator') # set_node('participantCountries', cache_key='coordinatorCountry') set_node('participants') for project in small_projects: e = graph.addEdge( cache['project'][project['id']], cache['coordinatorCountry'][project['coordinatorCountry']]) viewLabel[e] = 'pays' graph.addEdge( cache['coordinatorCountry'][project['coordinatorCountry']], cache['coordinator'][project['coordinator']]) for participant, linked_node in cache['participants'].items(): graph.addEdge(cache['coordinator'][project['coordinator']], linked_node) print(graph.numberOfNodes()) params = tlp.getDefaultPluginParameters('Random layout') graph.applyLayoutAlgorithm('Random layout', params) tlp.saveGraph(graph, 'save/project.tlpbz') nodeLinkView = tlpgui.createView("Node Link Diagram view", graph, {}, True) nodeLinkView.centerView()
def save_graph(self, path): tlp.saveGraph(self.graph_post, path + '/post.tlpbz') tlp.saveGraph(self.graph_user, path + '/user.tlpbz')
def main(graph): Acronyme = graph.getStringProperty("Acronyme") Annee_de_financement = graph.getIntegerProperty("Année de financement") Code_du_programme = graph.getStringProperty("Code du programme") Code_du_projet = graph.getStringProperty("Code du projet") Code_du_type_de_partenaire = graph.getStringVectorProperty("Code du type de partenaire") Coordinateur_du_projet = graph.getStringProperty("Coordinateur du projet") Date_de_debut = graph.getIntegerProperty("Date de début") Duree_en_mois = graph.getIntegerProperty("Durée en mois") Identifiant_de_partenaire = graph.getStringVectorProperty("Identifiant de partenaire") Libelle_de_partenaire = graph.getStringVectorProperty("Libellé de partenaire") Lien_Programme = graph.getStringProperty("Lien Programme") Lien_Projet = graph.getStringProperty("Lien Projet") Montant = graph.getDoubleProperty("Montant") Perspectives = graph.getStringProperty("Perspectives") Programme = graph.getStringProperty("Programme") Publications_et_brevets = graph.getStringProperty("Publications et brevets") Resultats = graph.getStringProperty("Résultats") Resume = graph.getStringProperty("Résumé") Resume_de_la_soumission = graph.getStringProperty("Résumé de la soumission") Sigle_de_partenaire = graph.getStringVectorProperty("Sigle de partenaire") Titre = graph.getStringProperty("Titre") Type_didentifiant = graph.getStringVectorProperty("Type d'identifiant") Type_de_partenaire = graph.getStringVectorProperty("Type de partenaire") viewBorderColor = graph.getColorProperty("viewBorderColor") viewBorderWidth = graph.getDoubleProperty("viewBorderWidth") viewColor = graph.getColorProperty("viewColor") viewFont = graph.getStringProperty("viewFont") viewFontSize = graph.getIntegerProperty("viewFontSize") viewIcon = graph.getStringProperty("viewIcon") viewLabel = graph.getStringProperty("viewLabel") viewLabelBorderColor = graph.getColorProperty("viewLabelBorderColor") viewLabelBorderWidth = graph.getDoubleProperty("viewLabelBorderWidth") viewLabelColor = graph.getColorProperty("viewLabelColor") viewLabelPosition = graph.getIntegerProperty("viewLabelPosition") viewLayout = graph.getLayoutProperty("viewLayout") viewMetric = graph.getDoubleProperty("viewMetric") viewRotation = graph.getDoubleProperty("viewRotation") viewSelection = graph.getBooleanProperty("viewSelection") viewShape = graph.getIntegerProperty("viewShape") viewSize = graph.getSizeProperty("viewSize") viewSrcAnchorShape = graph.getIntegerProperty("viewSrcAnchorShape") viewSrcAnchorSize = graph.getSizeProperty("viewSrcAnchorSize") viewTexture = graph.getStringProperty("viewTexture") viewTgtAnchorShape = graph.getIntegerProperty("viewTgtAnchorShape") viewTgtAnchorSize = graph.getSizeProperty("viewTgtAnchorSize") start_time = time.time() partenaire=tlp.newGraph() list=[] print ('Cr�ation des noeuds:') for n in graph.getNodes(): libPart=Libelle_de_partenaire[n] for i in range (0,len(libPart)): if "Universit�" in libPart[i]: if libPart[i] not in list : #si on rencontre ce partenaire pour la première fois list.append(libPart[i]) node=partenaire.addNode() x=random.randrange(1,1025,1) y=random.randrange(1, 1025, 1) projet=[Acronyme[n]] communs=[] for j in range (0,len(libPart)): if libPart[j]!=libPart[i] and libPart[j] not in communs and "Universit�" in libPart[j]: communs.append(libPart[j]) dict={"Libell� de partenaire": libPart[i], "Projet" : projet ,"Partenaires communs": communs ,"viewColor":(200,150,80,230) ,"viewLayout":tlp.Coord(x,y,0)} partenaire.setNodePropertiesValues(node,dict) else : #ce partenaire a déjà un noeud, on le cherche alors parmi tous les noeuds du nouveau graphe, et on ajoute dans ses paramètres le projet n et les partenaires communs for o in partenaire.getNodes(): if libPart[i] == partenaire.getStringProperty("Libell� de partenaire")[o] and Acronyme[n] not in partenaire.getStringVectorProperty("Projet")[o] : communs=[] for j in range (0,len(libPart)): if libPart[j]!=libPart[i] and libPart[j] not in communs and libPart[j] not in partenaire.getStringVectorProperty("Partenaires communs")[o] and "Universit�" in libPart[j]: communs.append(libPart[j]) dict={"Libell� de partenaire": partenaire.getStringProperty("Libell� de partenaire")[o] , "Projet" : partenaire.getStringVectorProperty("Projet")[o]+[Acronyme[n]] , "Partenaires communs": partenaire.getStringVectorProperty("Partenaires communs")[o]+communs, "viewColor":(200,150,80,230)} partenaire.setNodePropertiesValues(o,dict) print ("Cr�ation des ar�tes") node1=0 for p in partenaire.getNodes(): node2=0 for q in partenaire.getNodes(): for i in partenaire.getStringVectorProperty("Projet")[p] : if i in partenaire.getStringVectorProperty("Projet")[q] and partenaire.getStringProperty("Libell� de partenaire")[q] in partenaire.getStringVectorProperty("Partenaires communs")[p] and p!=q and node2>=node1 : #node1 et node2 pour éviter que les arêtes soient en double e=partenaire.addEdge(p,q) dict={"Projet":[i],"Partenaires" :[partenaire.getStringProperty("Libell� de partenaire")[p],partenaire.getStringProperty("Libell� de partenaire")[q]]} partenaire.setEdgePropertiesValues(e,dict) node2+=1 node1+=1 print ("Louvain") params = tlp.getDefaultPluginParameters('Louvain', partenaire) partenaire.applyDoubleAlgorithm('Louvain', params) tlp.saveGraph(partenaire,"univlouv.tlp") interval = time.time() - start_time print ('Total time in seconds:', interval)
def process(self, project_id: str, filename: str, meta: OveAssetMeta, options: Dict): logging.info("Copying %s/%s/%s into the temp place ...", project_id, meta.id, filename) with TemporaryDirectory() as input_folder: with TemporaryDirectory() as output_folder: os.mkdir(os.path.join( input_folder, os.path.split(filename) [0])) # make subdirectory for asset version number network_file = os.path.join(input_folder, filename) open(network_file, 'a').close() self._file_controller.download_asset( project_id=project_id, asset_id=meta.id, filename=filename, down_filename=network_file) algorithm = options.get('algorithm', "FM^3 (OGDF)") params = tlp.getDefaultPluginParameters(algorithm) for param in params: params[param] = self.convert_param( options.get(algorithm + '_' + param, params[param])) logging.info("Received options %s ...", options) logging.info( "Performing layout using algorithm %s and options %s ...", algorithm, params) graph = tlp.loadGraph(network_file) graph.applyLayoutAlgorithm(algorithm, params) result_name = options.get('result_name') if not result_name: result_name = meta.id.split('.')[0] + '.gml' tlp.saveGraph(graph, os.path.join(output_folder, result_name)) with open( os.path.join(output_folder, result_name + ".options"), 'w') as fp: json.dump(options, fp) self._file_controller.upload_asset_folder( project_id=project_id, meta=meta, upload_folder=output_folder, worker_name=self.name) base_name = os.path.splitext(os.path.basename(filename))[0] meta.index_file = os.path.join(meta.worker_root + self.name, base_name, result_name) self._file_controller.set_asset_meta(project_id=project_id, asset_id=meta.id, meta=meta) logging.info("Finished generating %s/%s into the storage ...", project_id, meta.id)
def save_graph(graph, tulipfilename): tlp.saveGraph(graph, tulipfilename)
from tulip import tlp graph = tlp.newGraph() new_nodes = [graph.addNode()] for i in range(5): tmp_main_nodes, new_nodes = new_nodes, [] for main_node in tmp_main_nodes: for _ in range(5): new_nodes.append(graph.addNode()) graph.addEdge(main_node, new_nodes[-1]) tlp.saveGraph(graph, 'dataset/table.tlpbz')
print("DEBUG") if picon[n] == 'md-book-open': voisins = list(tlp.Graph.getInOutNodes(g, n)) counter = 1 for x in voisins: for y in voisins[counter:]: edge_x_y = tlp.Graph.existEdge(g, x, y, directed=True) edge_y_x = tlp.Graph.existEdge(g, y, x, directed=True) if (tlp.edge.isValid(edge_x_y) or tlp.edge.isValid(edge_y_x)): if (tlp.edge.isValid(edge_x_y)): heroes_dict = tlp.Graph.getEdgePropertiesValues( g, edge_x_y) heroes_dict['value'] += 1 tlp.Graph.setEdgePropertiesValues( g, edge_x_y, heroes_dict) elif (tlp.edge.isValid(edge_y_x)): heroes_dict = tlp.Graph.getEdgePropertiesValues( g, edge_y_x) heroes_dict['value'] += 1 tlp.Graph.setEdgePropertiesValues( g, edge_y_x, heroes_dict) else: tlp.Graph.addEdge(g, x, y, {"value": 1}) counter += 1 tlp.Graph.delNode(g, n) tlp.saveGraph(g, "heroes_final.tlpb") # tlp.Graph.getEdgePropertiesValues(edge) # tlp.Graph.setEdgePropertiesValues(edge, propertiesValues)
# Store all functions use in MinLa algorithm by Eduardo Rodriguez-Tello et al. # https://www.sciencedirect.com/science/article/pii/S0305054807000676 import MinLA_functions as MinLA from tulip import tlp import numpy graph = MinLA.main('test_V2.tlp', None) graph = MinLA.fim(graph, False) # initial placement best_solution = MinLA.tssa_objective_function(graph) # A REVOIR #MinLA_functions.Get_viewLayout(graph) tlp.saveGraph(graph, 'test_V2_done.tlp') position = MinLA.get_position(graph) C_inf, Sig_inf = MinLA.generate_independant_solutions(graph, position, 10**3) output = MinLA.annealing(MinLA.fim(graph, False), MinLA.cost_function, MinLA.random_node, MinLA.temperature(graph, position, C_inf, Sig_inf, best_solution), maxsteps=5000, distance=0.1, debug=True) # print("Mean Cost funct")