def cyview(query, dataset='HMDB', connections='targets', name='', database=DATABASE): """ See HMDB/DrugBank graphs with Cytoscape runing on your local machine ` :param query: Query to select HMDB or DrugBank entries :param dataset: HMDB or DrugBank, not case sensitive :param connections: Connection type for DrugBank entries :param name: Name of the graph on Cytoscape, query is used as default value :param database: Name of the MongoDB database to connect """ from py2cytoscape.data.cyrest_client import CyRestClient from py2cytoscape.data.style import Style qc = parseinputquery(query) print(qc) # todo: tests with HMDB if dataset.upper() == 'HMDB': qry = QueryHMDB(index=database) pairs = qry.getconnectedmetabolites(qc) mn = qry.get_connections_graph(pairs, query) else: # assume DrugBank qry = QueryDrugBank(db, database, 'drugbank') mn = qry.get_connections_graph(qc, connections) crcl = CyRestClient() mn.name = json.dumps(qc) if name == '' else name cyn = crcl.network.create_from_networkx(mn) crcl.layout.apply('kamada-kawai', network=cyn) crcl.style.apply(Style('default'), network=cyn)
def setUp(self): self.client = CyRestClient() self.client.network.delete_all() locations = ['http://chianti.ucsd.edu/cytoscape-data/galFiltered.sif'] self.network = self.client.network.create_from(locations) view_id_list = self.network.get_views() self.view = self.network.get_view(view_id_list[0], format='view')
def graphml2cyto(col_filename, style_filename, outpath): cy = CyRestClient() cy.session.delete() net = cy.network.create_from(col_filename[:-4] + '.graphml') entireNetworkJson = requests.get('http://localhost:1234/v1/networks.json') entireNetwork = json.loads(entireNetworkJson.text) nodes = entireNetwork[0]['elements']['nodes'] numNodes = json.loads(requests.get('http://localhost:1234/v1/networks/' + str(entireNetwork[0]['data']['SUID']) + '/nodes/count').text)['count'] numEdges = json.loads(requests.get('http://localhost:1234/v1/networks/' + str(entireNetwork[0]['data']['SUID']) + '/edges/count').text)['count'] for d in merge_dicts: merge_ids = [n['data']['SUID'] for n in nodes if n['data']['name'] in d['members']] #pprint.pprint(nodes) requests.post('http://127.0.0.1:1234/v1/networks/' + str(entireNetwork[0]['data']['SUID']) + '/groups', data=json.dumps({'name': d['group'], 'nodes': merge_ids}), headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}) #with open(style_filename, 'r') as fstyle: # content = fstyle.read()[1:-1] # content = json.loads(content) # print(content) # styleResp = requests.post('http://127.0.0.1:1234/v1/styles/', # data=json.dumps(content), # headers = {'Accept': 'application/json', 'Content-Type': 'application/json'}) # styleName = json.loads(styleResp.text)['title'] # print('style name is: ' + styleName) # cy.style.apply(style=styleName, network=net) cy.layout.apply(name='circular', network=net) cy.session.save(outpath) cy.session.delete() return numNodes, numEdges
def draw_graph(page_links: List[PageLink], layout_name: str) -> None: log.info(f"Создаю граф из {len(page_links)} ссылок") graph_nodes: Set[str] = set() graph_edges: List[Tuple[str, str]] = [] for link in page_links: if link.from_url not in graph_nodes: graph_nodes.add(link.from_url) if link.to_url not in graph_nodes: graph_nodes.add(link.to_url) graph_edges.append((link.from_url, link.to_url)) log.info("Рисую граф ссылок с расположением " + layout_name) cytospace_client: CyRestClient = CyRestClient() graph: CyNetwork = cytospace_client.network.create() node_suids: Dict[str, int] = graph.add_nodes(list(graph_nodes)) graph.add_edges( list({ "source": node_suids[edge[0]], "target": node_suids[edge[1]] } for edge in graph_edges)) cytospace_client.layout.apply(layout_name, graph) # 24000 пикселей — максимальная высота изображения; это ограничение накладывает Cytospace image_height: int = min(max(len(graph_nodes) * 60, 600), 24000) graph_image: bytes = graph.get_png(image_height) with open(f"links-{layout_name}.png", "wb+") as png_file: png_file.write(graph_image)
def view_in_cytoscape(self, force_add_nodename=False): """Ports graph to Cytoscape Parameters ---------- force_add_nodename : bool If True, a node attribute called `nodename` will be added. This seems to fix the bug the py2cytoscape has where it would ignore the node names. """ if not hasattr(self, "cyrest"): self.cyrest = CyRestClient() if force_add_nodename: nodenames = { n: d[self.node_name] for n, d in self.get_node_attributes().items() } self.set_node_attributes({"nodename": nodenames}, namespace="nodeids") hdl = self.cyrest.network.create_from_networkx(self.network) self.cyrest.layout.apply(name='degree-circle', network=hdl) return self
def display_in_cytoscape(graph, network_name: str): """ Displays the graph in Cytoscape - if it is running :param graph: The graph to display :param network_name: Name of the network in Cytoscape """ try: cy = CyRestClient() cytoscape_network = cy.network.create_from_networkx( network=graph, name=network_name, collection="Cluster comparison") # add the layout cy.layout.apply(name='force-directed', network=cytoscape_network) # add the style # Step 6: Create Visual Style as code (or by hand if you prefer) comparison_style = cy.style.create('Cluster Comparison') basic_settings = { # You can set default values as key-value pairs. 'NODE_FILL_COLOR': '#6AACB8', 'NODE_SIZE': 55, 'NODE_BORDER_WIDTH': 0, 'NODE_LABEL_COLOR': '#555555', 'EDGE_WIDTH': 2, 'EDGE_TRANSPARENCY': 100, 'EDGE_STROKE_UNSELECTED_PAINT': '#333333', 'NETWORK_BACKGROUND_PAINT': '#FFFFFF' } comparison_style.update_defaults(basic_settings) # Create some mappings min_cluster_size = min([graph.node[c]["size"] for c in graph.nodes]) max_cluster_size = max([graph.node[c]["size"] for c in graph.nodes]) cluster_size_to_node_size = StyleUtil.create_slope( min=min_cluster_size, max=max_cluster_size, values=(30, 100)) comparison_style.create_continuous_mapping( column='size', vp='NODE_SIZE', col_type='Double', points=cluster_size_to_node_size) comparison_style.create_discrete_mapping(column='source', vp="NODE_FILL_COLOR", col_type="String", mappings={ "source1": "#FC8D62", "source2": "#A6D854" }) comparison_style.create_passthrough_mapping(column='weight', vp="EDGE_WIDTH", col_type="Integer") # apply the style cy.style.apply(style=comparison_style, network=cytoscape_network) except Exception as e: print("Please open Cytoscape to display the graph: " + str(e))
def cyview(query): """ See metabolite networks with Cytoscape runing on your local machine """ from py2cytoscape.data.cyrest_client import CyRestClient qc = parseinputquery(query) qry = QueryModelSEED() mn = qry.get_metabolite_network(qc) client = CyRestClient() client.network.create_from_networkx(mn)
def setUp(self): self.client = CyRestClient() self.client.style.delete_all() styles = self.client.style.get_all() self.assertEqual(1, len(styles)) self.style = self.client.style.create(STYLE_NAME) self.assertEqual(STYLE_NAME, self.style.get_name())
def view_withcytoscape(inf): from py2cytoscape.data.cyrest_client import CyRestClient from py2cytoscape.data.style import Style crcl = CyRestClient() r = json.load(open(inf)) g = get_cytoscape_graph(r, name=inf) cyn = crcl.network.create_from_networkx(g) crcl.layout.apply('kamada-kawai', network=cyn) crcl.style.apply(Style('default'), network=cyn)
def __init__(self, node_df, edge_df, interaction_or_edge): self.node_df = node_df self.edge_df = edge_df self.interaction_or_edge = interaction_or_edge self.json_file_name = 'json_file.json' self.json_file_path = os.path.join('../SampleData/InteractionGraph/', self.json_file_name) self.cy = CyRestClient() self.node_edge_network = None # = self.cy.network.create_from(self.json_file_path)
def view_in_cytoscape(self): """Ports graph to Cytoscape""" if not hasattr(self, "cyrest"): self.cyrest = CyRestClient() hdl = self.cyrest.network.create_from_networkx(self.network) self.cyrest.layout.apply(name='degree-circle', network=hdl) return self
def create_network(infile): cy = CyRestClient() # Reset cy.session.delete() # Step 2: Load network from somewhere ## entire path is needed net = cy.network.create_from(infile) return (net)
def network_firework_layout(G): '''POST the network to CyREST, then run layout algorithm, finally return the coordinates and the cy_network. ''' # Create Py2cytoscape client cy = CyRestClient(ip=IP, port=PORT) # Reset session cy.session.delete() # POST the graph to CyREST G_cy = cy.network.create_from_networkx(G) # Change the layout params layout_parameters = [{ "name": "numIterations", "value": 10 }, { "name": "numIterationsEdgeRepulsive", "value": 10 }] resp = requests.put(BASE_URL + '/apply/layouts/force-directed-cl/parameters', data=json.dumps(layout_parameters), headers=HEADERS) cy.layout.apply(name='force-directed-cl', network=G_cy) layout_parameters = [ { "name": "maxIterations", "value": 10000 }, { "name": "randomize", "value": True }, ] resp = requests.put( BASE_URL + '/apply/layouts/allegro-edge-repulsive-strong-clustering/parameters', data=json.dumps(layout_parameters), headers=HEADERS) cy.layout.apply(name='allegro-edge-repulsive-strong-clustering', network=G_cy) # Get current view view = G_cy.get_first_view() nodes = view['elements']['nodes'] # Get a coord matrix ordered by id_original ids_original = np.array([n['data']['id_original'] for n in nodes]).astype(np.int32) xs = [n['position']['x'] for n in nodes] ys = [n['position']['y'] for n in nodes] coords = np.array([xs, ys]).T return coords[ids_original], G_cy
def __init__(self, graph, layout="attributes-layout", style='Directed'): # name='FromMAGINE'): # force-directed # attributes-layout self.graph = graph self.cy = CyRestClient() self.cy.session.delete() self.cy.layout2 = LayoutClient() self.style = None self.edge_name2id = None self.node_name2id = None self.g_cy = None self.view1 = None for n, (i, j) in enumerate(self.graph.edges()): self.graph[i][j]['name'] = '{},{}'.format(i, j) self.g_cy = self.cy.network.create_from_networkx(self.graph) time.sleep(2) view_id_list = self.g_cy.get_views() self.view1 = self.g_cy.get_view(view_id_list[0], format='view') # Marquee Directed Simple self.style = self.cy.style.create(style) # self.style = self.cy.style.create('Marquee') options = { 'NODE_LABEL_FONT_SIZE': 24, 'EDGE_WIDTH': 2, 'EDGE_TRANSPARENCY': '150', # 'NETWORK_HEIGHT' : '2800', # 'NETWORK_WIDTH' : '2800', 'NODE_LABEL_COLOR': 'black', 'NODE_FILL_COLOR': 'red', 'NETWORK_BACKGROUND_PAINT': '#00FFFFFF', 'NODE_SIZE': 80, # 'NODE_LABEL_POSITION': 'C,C,c,0.00,-60.00', 'NETWORK_CENTER_X_LOCATION': 0.0, 'NETWORK_CENTER_Y_LOCATION': 0.0, } self.style.update_defaults(options) if layout == 'attributes-layout': self.cy.layout2.apply(name=layout, network=self.g_cy, params={'column': 'color'}) else: self.cy.layout2.apply(name=layout, network=self.g_cy) self.node_name2id = util.name2suid(self.g_cy, 'node') self.edge_name2id = util.name2suid(self.g_cy, 'edge')
def cyview(query, name='', limit=4000): """ See IntEnz enzyme graphs with Cytoscape runing on your local machine :param query: Query to select IntEnz entries :param name: Name of the graph on Cytoscape, query is used as default value :param limit """ from py2cytoscape.data.cyrest_client import CyRestClient from py2cytoscape.data.style import Style qc = parseinputquery(query) qry = QueryIntEnz() mn = qry.get_connections_graph(qc, limit) crcl = CyRestClient() mn.name = json.dumps(qc) if name == '' else name cyn = crcl.network.create_from_networkx(mn) crcl.layout.apply('kamada-kawai', network=cyn) crcl.style.apply(Style('default'), network=cyn)
def _setup_graph(self): self.cy = CyRestClient() self.cy.session.delete() self.CY_STYLE = self.cy.style.create("Sample3") defaults = { "NODE_BORDER_PAINT": "black", "NODE_LABEL_COLOR": "#33FF33", "NODE_LABEL_FONT_SIZE": "18", "NODE_SIZE": "30", "EDGE_SOURCE_ARROW_SHAPE": "arrow", "EDGE_SOURCE_ARROW_UNSELECTED_PAINT": "#9999FF", "EDGE_STROKE_COLOR": "#CCCCCC" } self.CY_STYLE.update_defaults(defaults) self.g = nx.DiGraph()
def __visualize_outputs(self): _annot_file = os.path.abspath(self.annotations.out_annot_file) _style_file = os.path.abspath(self.annotations.out_style_file) cyclient = cyrest.cyclient() cy = CyRestClient() #cy.session.delete() cy.network.create_from(self.runner.output_files['network-file']) time.sleep(2) style = cyclient.vizmap.load_file(_style_file) cyclient.vizmap.apply(style[0]) cyclient.table.import_file(afile=_annot_file, firstRowAsColumnNames=True, keyColumnIndex='1', startLoadRow='0', dataTypeList=self.data_types) cyclient.session.save_as(session_file=self.save_file)
def affichage(self): if not self.isRunning(): self.alerte() else: cy = CyRestClient() style1 = cy.style.create('sample_style1') #feuille de style cytoscape new_defaults = { # Node defaults 'NODE_FILL_COLOR': '#ff5500', 'NODE_SIZE': 20, 'NODE_BORDER_WIDTH': 0, 'NODE_TRANSPARENCY': 120, 'NODE_LABEL_COLOR': 'white', # Edge defaults 'EDGE_WIDTH': 3, 'EDGE_STROKE_UNSELECTED_PAINT': '#aaaaaa', #'EDGE_LINE_TYPE': 'LONG_DASH', 'EDGE_TRANSPARENCY': 120, # Network defaults 'NETWORK_BACKGROUND_PAINT': 'white' } # Update style1.update_defaults(new_defaults) kv_pair = { '-1': 'T', '1': 'Arrow' } style1.create_discrete_mapping(column='interaction', col_type='String', vp='EDGE_SOURCE_ARROW_SHAPE', mappings=kv_pair) self.fname = self.grapheLoc[self.graph.currentRow()] net1 = cy.network.create_from(self.grapheLoc[self.graph.currentRow()]) cy.style.apply(style1,net1)
def colorGraphe(self,tableTuple): if not self.isRunning(): self.alerte() else: cy = CyRestClient() net1 = cy.network.create_from(self.grapheLoc2[self.graph_3.currentRow()]) net1.create_node_column("composant", data_type='Integer',is_immutable=False) net1.create_node_column("signe",data_type='Integer',is_immutable=False) table=net1.get_node_table() nodeTable={} nodes=net1.get_nodes() for node in nodes: nodeTable[net1.get_node_value(node)['name']]=node for line in tableTuple: table.set_value(nodeTable[line[0]],"composant",line[1]) table.set_value(nodeTable[line[0]],"signe",line[2]) net1.update_node_table(table,network_key_col='name', data_key_col='name') style1 = cy.style.create('sample_style1') points = [{ 'value': '0.0', 'lesser':'blue', 'equal':'blue', 'greater': 'blue' },{ 'value': '1.0', 'lesser':'red', 'equal':'red', 'greater': 'red' }] points[1]["value"]=self.nbComposantes(tableTuple)-1 style1.create_continuous_mapping(column='composant', col_type='Integer', vp='NODE_FILL_COLOR',points=points) cy.style.apply(style1,net1) cy.layout.apply(name='organic',network=net1) self.doneC()
def __init__(self, host="localhost", port="1234", version="v1"): self.cy = CyRestClient(ip=host, port=port, version=version)
def get_client(): """Initialises connection with Cytoscape and returns client.""" return CyRestClient()
def network(G, name, outfile): #Connect with cytoscape cy = CyRestClient() # Reset #cy.session.delete() #To create the network in cytoscape network = cy.network.create_from_networkx(G, name=name, collection=str(outfile)) #print('New network created with py2cytoscape. Its SUID is ' + str(network.get_id())) #To get the SUID of all the components of the network all_suid = cy.network.get_all() net1 = cy.network.create(all_suid[0]) #print(net1.get_first_view()) #Styles cy.layout.apply(name='hierarchical', network=network) # Get all existing Visual Styles styles = cy.style.get_all() #print(json.dumps(styles, indent=4)) # Get a reference to the existing style default_style = cy.style.create('default') #print(default_style.get_name()) # Get all available Visual Properties #print(len(cy.style.vps.get_all())) node_vps = cy.style.vps.get_node_visual_props() edge_vps = cy.style.vps.get_edge_visual_props() network_vps = cy.style.vps.get_network_visual_props() #print(pd.Series(edge_vps).head()) #print(pd.Series(node_vps).head()) # Create a new style style1 = cy.style.create("My_style") #print(style1.get_name()) new_defaults = { # Node defaults 'NODE_FILL_COLOR': '#00ddee', 'NODE_SIZE': 20, 'NODE_BORDER_WIDTH': 0, 'NODE_LABEL_COLOR': 'black', # Edge defaults 'EDGE_WIDTH': 3, 'EDGE_STROKE_UNSELECTED_PAINT': '#aaaaaa', 'EDGE_LINE_TYPE': 'LONG_DASH', 'EDGE_TARGET_ARROW_SHAPE': 'DELTA', # Network defaults 'NETWORK_BACKGROUND_PAINT': 'white', } style1.update_defaults(new_defaults) #Apply style cy.style.apply(style1, network) # Passthrough mapping to get node labels style1.create_passthrough_mapping(column='name', col_type='String', vp='NODE_LABEL') # Discrete mapping for node colours: cat = {'reactant': '#4D833C', 'product': '#C04E5D'} style1.create_discrete_mapping(column='category', col_type='String', vp='NODE_FILL_COLOR', mappings=cat) # Discrete mapping for node shape: reac = {'reactions': 'RECTANGLE'} style1.create_discrete_mapping(column='category', col_type='String', vp='NODE_SHAPE', mappings=reac)
def make_cytoscpe_plot(df_sif, weights_file): """ provide sif file and weights of nodes to launch and generate directed cytoscape network Parameters ---------- df_sif: pandas dataframe sif file (can contain additional metadata on edge annotations) weights_file: string path to 2-column file of node weights """ # Useful documentation # -------------------- # http://nbviewer.jupyter.org/github/idekerlab/py2cytoscape/blob/develop/examples/New_wrapper_api_sample.ipynb cytoscape_path = '/Applications/Cytoscape_v3.4.0/Cytoscape.app' subprocess.call(['open', cytoscape_path]) webbrowser.open('http://localhost:1234/v1') G = nx.from_pandas_dataframe(df_sif, 'PARTICIPANT_A', 'PARTICIPANT_B', ['INTERACTION_TYPE']) df_weights = pd.read_csv(weights_file, sep='\t') df_weights.columns = ['Name', 'Weight'] df_weights.index = df_weights.Name.tolist() cy = CyRestClient() cy.session.delete() cynet = cy.network.create_from_networkx(G) network_style = cy.style.create('GAL style') cy.layout.apply(network=cynet) cy.style.apply(network_style, network=cynet) cynet.update_node_table(df=df_weights, network_key_col='name') basic_settings = { # You can set default values as key-value pairs. 'NODE_FILL_COLOR': '#6AACB8', 'NODE_SIZE': 20, 'NODE_BORDER_WIDTH': 0, 'NODE_TRANSPARENCY': 120, 'NODE_LABEL_COLOR': 'black', 'EDGE_WIDTH': 2, 'EDGE_TRANSPARENCY': 100, 'EDGE_STROKE_UNSELECTED_PAINT': 'red', 'EDGE_TARGET_ARROW_SHAPE': 'ARROW', 'EDGE_TARGET_ARROW_UNSELECTED_PAINT': 'red', 'NETWORK_BACKGROUND_PAINT': 'white' } network_style.update_defaults(basic_settings) network_style.create_passthrough_mapping(column='name', vp='NODE_LABEL', col_type='String') weights = cynet.get_node_column('Weight') color_gradients = StyleUtil.create_2_color_gradient(min=weights.min(), max=weights.max(), colors=('blue', 'red')) network_style.create_continuous_mapping(column='Weight', vp='NODE_FILL_COLOR', col_type='Double', points=color_gradients) edge_color_map = { 'controls-state-change-of': 'orange', 'controls-phosphorylation-of': 'green', 'controls-transport-of': 'yellow', 'in-complex-with': 'blue', 'controls-expression-of': 'red' } edge_shape_map1 = { 'controls-state-change-of': 'ARROW', 'controls-phosphorylation-of': 'ARROW', 'controls-transport-of': 'ARROW', 'in-complex-with': 'CIRCLE', 'controls-expression-of': 'ARROW' } edge_shape_map2 = { 'controls-state-change-of': 'NONE', 'controls-phosphorylation-of': 'NONE', 'controls-transport-of': 'NONE', 'in-complex-with': 'CIRCLE', 'controls-expression-of': 'NONE' } network_style.create_discrete_mapping(column='INTERACTION_TYPE', col_type='String', vp='EDGE_STROKE_UNSELECTED_PAINT', mappings=edge_color_map) network_style.create_discrete_mapping( column='INTERACTION_TYPE', col_type='String', vp='EDGE_TARGET_ARROW_UNSELECTED_PAINT', mappings=edge_color_map) network_style.create_discrete_mapping( column='INTERACTION_TYPE', col_type='String', vp='EDGE_SOURCE_ARROW_UNSELECTED_PAINT', mappings=edge_color_map) network_style.create_discrete_mapping(column='INTERACTION_TYPE', col_type='String', vp='EDGE_TARGET_ARROW_SHAPE', mappings=edge_shape_map1) network_style.create_discrete_mapping(column='INTERACTION_TYPE', col_type='String', vp='EDGE_SOURCE_ARROW_SHAPE', mappings=edge_shape_map2)
def main(): # ------------------------- # 1. キーワード文字列を取得 # ------------------------- keywords = __create_keywords_data() # ------------------------- # 2. 共起単語行列を作成する # ------------------------- Xc_norm, vocabulary, counter = __get_co_occurrence_matrix_from(keywords) # ------------------------- # 3. networkx 描画データを作成 # ------------------------- # 3-1.初期ノードの追加 G = nx.from_scipy_sparse_matrix( Xc_norm, parallel_edges=True, create_using=nx.DiGraph(), edge_attribute='weight') # 3-2.nodeに、count にcount属性を設定 value_key_dict = {} for key, value in vocabulary.items(): count = counter.get(key, 0) nx.set_node_attributes(G, "score", {value: count}) value_key_dict.update({value: key}) # 3-3.エッジと、ノードの削除 # 同一ノードに引かれたエッジと、出現回数の少ないエッジを削除 for (u, v, d) in G.edges(data=True): if u == v: G.remove_edge(u, v) if d["weight"] <= 0.0: G.remove_edge(u, v) # 出現回数の少ないノードを除去 for n, a in G.nodes(data=True): if a["score"] <= 10: G.remove_node(n) # 3-4 ラベルの張り替え、from_scipy_sparse_matrix 設定時はラベルとして1,2,3 等の数値が設定されている G = nx.relabel_nodes(G, value_key_dict) # ------------------------------------------------------ # 4 描画のために調整と、HTMLへのExport # ------------------------------------ # Cytoscape に送信して、描画する # http://localhost:1234/v1/apply/layouts でレイアウトアルゴリズムのリストを取得できる from py2cytoscape.data.cyrest_client import CyRestClient cy = CyRestClient(ip='127.0.0.1', port=1234) for layout_algorithm in ["attribute-circle", "stacked-node-layout", "degree-circle", "circular", "attributes-layout", "kamada-kawai", "force-directed", "cose", "grid", "hierarchical", "fruchterman-rheingold", "isom", "force-directed-cl"]: print("plot start layout_algorithm [" + layout_algorithm + "]...") g_cy = cy.network.create_from_networkx(G) cy.layout.apply(name=layout_algorithm, network=g_cy) directed = cy.style.create('Curved') cy.style.apply(directed, network=g_cy) # エッジを束ねて見やすくする cy.edgebundling.apply(g_cy) view = g_cy.get_first_view() import exporter as exporter exporter.exportHTML( view, "html/" + layout_algorithm + "_export.html", 'custermizedCurved', background='radial-gradient(#898989 15%, #DDDDDD 105%)') print("plot end")
def identificationColor(): Dico = {} DicoInverse = {} # Charger Dico des nodes file = open( "D:\\Documents\\Centrale\\Ei2\PAPPL\\App\\graphe_0.2_MEF-hash.txt", 'r') data = file.readlines() file.close() for i in data: #print(i) node = i.split(" : ")[0].split("\"")[1] #print(node) conversion = i.split(" : ")[1].split("\n")[0] #print(conversion) Dico[conversion] = node DicoInverse[node] = conversion # Charger le graphe # convertir le graphe en graphe networkX file = open( "D:\\Documents\\Centrale\\Ei2\PAPPL\\App\\graphe-coloration-processed.txt", 'r') data = file.readlines() file.close() #print(data) G = nx.Graph() # Pour chaque ligne : for i in data: # Identifier source & target : convertir source = Dico[i.split("(")[1].split(",")[0]] target = Dico[i.split(",")[1].split(")")[0]] # Identifier le type de correlation : signe de l'arc # cas positif if (len(i.split("Positif")) == 2): G.add_edge(source, target, edge_type=1) # cas négatif else: G.add_edge(source, target, edge_type=-1) listeTuples = [] listeNodes = [] #Identifier les noeuds hors graphe de corrélation : tuples simples ou non listés for i in DicoInverse.keys(): if (i in G.nodes()): listeNodes.append(i) else: listeTuples.append(i) # Pour chaque noeud : # Fonction recursive d'exploration : parametre : graphe, tuple actuel, while (len(listeNodes) != 0): for node in listeNodes: #print(node) nouveauTuple = node listeNodes.remove(node) # Appel fonction de recherche nouveauTuple = rechercheTuple(G, node, nouveauTuple, listeNodes, 1) listeTuples.append(nouveauTuple) # Affichage des tuples #for tuple in listeTuples: # print(tuple) # print(listeTuples) tableTuple = [] for i in range(len(listeTuples)): tuple = listeTuples[i] tuple = tuple.split(",") for node in tuple: if (node.split(" ")[1] == '-'): tableTuple.append([node.split(" ")[0], i, -1]) else: tableTuple.append([node.split(" ")[0], i, 1]) # print(tableTuple) cy = CyRestClient() # net1 = cy.network.create_from("D:\\Documents\\Centrale\\Ei2\\PAPPL\\App\\graphe_0.2_MEF.sif") # net1.create_node_column("composante", data_type='Integer',is_immutable=False) # net1.create_node_column("signe",data_type='Integer',is_immutable=False) # table=net1.get_node_table() # nodeTable={} # nodes=net1.get_nodes() # for node in nodes: # nodeTable[net1.get_node_value(node)['name']]=node # for line in tableTuple: # table.set_value(nodeTable[line[0]],"composante",line[1]) # table.set_value(nodeTable[line[0]],"signe",line[2]) # net1.update_node_table(table,network_key_col='name', data_key_col='name') n = nbComposantes(tableTuple) listeComposante = [[] for _ in range(n)] for line in tableTuple: listeComposante[line[1] - 1].append(line[0]) print(listeComposante) file = open("D:\\Documents\\Centrale\\Ei2\\PAPPL\\App\\graphe_0.2_MEF.sif", 'r') base = file.readlines() file.close() graphesComposantes = [] for compo in listeComposante: current = [] for line in base: lineSliced = line[:-1] edge = lineSliced.split("\t") if (edge[2] in compo and edge[2] in compo): current.append(line) graphesComposantes.append(current) print(current) directory = "D:\\Documents\\Centrale\\Ei2\\PAPPL\\App\\graph" if not os.path.exists(directory): os.makedirs(directory) for i in range(len(graphesComposantes)): strOpen = "D:\\Documents\\Centrale\\Ei2\\PAPPL\\App\\graph\\c" + str( i + 1) + ".sif" file = open(strOpen, 'w') for line in graphesComposantes[i]: file.write(line) file.write("\n")
""" THis would be the way to go without py2cytoscape # Standard JSON library import json # Basic Setup PORT_NUMBER = 8080 BASE = 'http://localhost:' + str(PORT_NUMBER) + '/v1/' # Header for posting data to the server as JSON HEADERS = {'Content-Type': 'application/json'} # Define dictionary of empty network empty_network = { 'data': { 'name': 'I\'m empty!' }, 'elements': { 'nodes':[], 'edges':[] } } res = requests.post(BASE + 'networks?collection=My%20Collection', data=json.dumps(empty_network), headers=HEADERS) new_network_id = res.json()['networkSUID'] print('Empty network created: SUID = ' + str(new_network_id)) """ cy = CyRestClient() def plot_cool_network(nx_graph): network = cy.network.create_from_networkx( nx_graph, collection='Generated by NetworkX') print(network.get_id())
def setUp(self): self.client = CyRestClient() # cleanup self.client.network.delete_all()
def cytoscape_successful(self, update): cytoscape_successful = True # Create client cy = CyRestClient() # Clear current session cy.session.delete() # Convert DataFrame to json file and save file self.dataframe_to_json() # Create network from json file node_edge_network = cy.network.create_from(self.json_file_path) cy.layout.apply(network=node_edge_network) # Add styles to the network my_style = cy.style.create('my_style') # Discrete mappings for specific regions order_colour_key_value_pair = { '1': '#c99e10', '2': '#9b4f0f', '3': '#1e434c', '4': '#8d230f' } edge_order_colour_key_value_pair = { '2': '#9b4f0f', '3': '#1e434c', '4': '#8d230f' } edge_order_size_key_value_pair = {'2': '5.0', '3': '3.0', '4': '1.0'} order_size_key_value_pair = { '1': '25.0', '2': '35.0', '3': '40.0', '4': '50.0' } order_shape_key_value_pair = { '1': 'Ellipse', '2': 'Diamond', '3': 'Triangle', '4': 'Hexagon' } # If the GUI is being loaded for the first time # Then create network with 'default' styles if not update: new_styles = { 'NODE_FILL_COLOR': '#363636', 'NODE_SIZE': 10, 'NODE_BORDER_WIDTH': 0, 'NODE_TRANSPARENCY': 255, 'NODE_LABEL_COLOR': '#323334', 'EDGE_WIDTH': 3, 'EDGE_STROKE_UNSELECTED_PAINT': '#a9a9a9', 'EDGE_LINE_TYPE': 'SOLID', 'EDGE_TRANSPARENCY': 120, 'NETWORK_BACKGROUND_PAINT': 'white' } my_style.update_defaults(new_styles) # Add these styles only if the network type is Interaction if self.interaction_or_edge == 1: my_style.create_discrete_mapping( column='order', col_type='String', vp='NODE_FILL_COLOR', mappings=order_colour_key_value_pair) my_style.create_discrete_mapping( column='order', col_type='String', vp='NODE_SIZE', mappings=order_size_key_value_pair) my_style.create_discrete_mapping( column='order', col_type='String', vp='NODE_SHAPE', mappings=order_shape_key_value_pair) my_style.create_discrete_mapping( column='order', col_type='String', vp='EDGE_STROKE_UNSELECTED_PAINT', mappings=edge_order_colour_key_value_pair) my_style.create_discrete_mapping( column='order', col_type='String', vp='EDGE_WIDTH', mappings=edge_order_size_key_value_pair) # TODO write the code for other styles # TODO If need to update then read the csv file with styles and tweak it as necessary else: print('No styles specified') cy.style.apply(my_style, node_edge_network) cy.layout.fit(network=node_edge_network) Image(node_edge_network.get_png(height=400)) return cytoscape_successful
parser.add_argument("--o", dest="ofile", help="output (CSV|TSV)") parser.add_argument("-v", "--verbose", action="count") args = parser.parse_args() if args.ifile: fin = open(args.ifile) else: fin = sys.stdin if args.ofile: fout = open(args.ofile, "w") else: fout = sys.stdout if args.op == 'ping': try: cy = CyRestClient(ip='127.0.0.1', port=1234) except Exception as e: print("Cytoscape connection failed: %s" % e, file=sys.stderr) exit() network = cy.network.create(name='My Network', collection='My network collection') print("Cytoscape current net_id: %d" % network.get_id()) elif args.op == 'cyjs2tsv': CyJS2TSV(fin, args, fout) else: parser.error('Unknown operation: %s' % args.op)
import os import SciKGraph as skg import pickle import OClustR as OCR import json import Analyses import copy import subprocess from py2cytoscape import cyrest from py2cytoscape import util as cy from py2cytoscape.data.cyrest_client import CyRestClient from IPython.display import Image cytoscape = cyrest.cyclient() cyjs = CyRestClient() app = Flask(__name__) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 0 UPLOAD_FOLDER = '/home/mauro/Documents/flask_app/static/temp/' app.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER Bootstrap(app) sKGraph = skg.SciKGraph() sKGraph1 = skg.SciKGraph() sKGraph2 = skg.SciKGraph() @app.route('/create', methods=['POST', 'GET']) def create(): ### ----------------------------------- Construct Graph -----------------------------------------###