def update_graph(request, graph_id, name=None, is_public=None, graph_json=None, style_json=None, owner_email=None, default_layout_id=None): graph = {} if name is not None: graph['name'] = name if owner_email is not None: graph['owner_email'] = owner_email if is_public is not None: graph['is_public'] = is_public if default_layout_id is not None: graph['default_layout_id'] = default_layout_id if default_layout_id != 0 else None if style_json is not None: GSGraph.validate_style_json(style_json) graph['style_json'] = json.dumps(style_json) if graph_json is not None: G = CyJSFormat.create_gsgraph(json.dumps(graph_json)) if name is not None: G.set_name(name) db.remove_nodes_by_graph_id(request.db_session, graph_id=graph_id) # Add graph nodes node_name_to_id_map = add_graph_nodes(request, graph_id, G.nodes(data=True)) # Add graph edges edge_name_to_id_map = add_graph_edges(request, graph_id, G.edges(data=True), node_name_to_id_map) graph['graph_json'] = json.dumps(G.get_graph_json()) settings.ELASTIC_CLIENT.index(index="graphs", doc_type='json', id=graph_id, body=map_attributes(G.get_graph_json()), refresh=True) return db.update_graph(request.db_session, id=graph_id, updated_graph=graph)
def get_legend(self): """Get a GSLegend Object having JSON representation of legend for a layout. Returns: object: GSLegend Object having JSON representation of legend. Examples: >>> from graphspace_python.graphs.classes.gslayout import GSLayout >>> from graphspace_python.graphs.classes.gslegend import GSLegend >>> Ld = GSLegend() >>> legend_json = { ... "legend":{ ... "nodes":{ ... "Source Receptor": { ... "shape":"ellipse", ... "background-color":"#ff1400" ... } ... }, ... "edges":{ ... "Enzymatic Reaction":{ ... "line-color":"#0fcf25", ... "line-style":"solid", ... "arrow-shape":"triangle" ... } ... } ... } ... } >>> Ld.set_legend_json(legend_json) >>> L = GSLayout() >>> L.set_legend(Ld) >>> L.get_legend() <graphspace_python.graphs.classes.gslegend.GSLegend at 0x7fdebc59d1d0> """ G = GSGraph() L = G._GSGraph__get_legend(self.style_json) return L
def create_gsgraph(json_string): """ Parameters ---------- json_string: json_string to be converted to GSGraph type. Returns ------- object: GSGraph Notes ------- """ graph_json = CyJSFormat.clean_graph_json(CyJSFormat.validate_json(json_string)) G = GSGraph() G.graph = graph_json["data"] for node in graph_json["elements"]["nodes"]: G.add_node(node["data"]["name"], attr_dict=node) for edge in graph_json["elements"]["edges"]: G.add_edge(edge["data"]["source"], edge["data"]["target"], attr_dict=edge) G.set_graph_json(graph_json) return G
def add_edge_style(self, source, target, attr_dict=None, directed=False, color='#000000', width=1.0, arrow_shape='triangle', edge_style='solid', arrow_fill='filled'): """Add styling for an edge whose source and target nodes are provided. Args: source (str): Unique ID of the source node. target (str): Unique ID of the target node. attr_dict (dict, optional): Json representation of style of edge. Defaults to None. color (str, optional): Hexadecimal representation of the color (e.g., #000000), or the color name. Defaults to black. directed (bool, optional): If True, draw the edge as directed. Defaults to False. width (float, optional): Width of the edge. Defaults to 1.0. arrow_shape (str, optional): Shape of arrow head. Defaults to 'triangle'. See :data:`ALLOWED_ARROW_SHAPES` for more details. edge_style (str, optional): Style of edge. Defaults to 'solid'. See :data:`ALLOWED_EDGE_STYLES` for more details. arrow_fill (str, optional): Fill of arrow. Defaults to 'filled'. See :data:`ALLOWED_ARROW_FILL` for more details. Examples: >>> from graphspace_python.graphs.classes.gslayout import GSLayout >>> L = GSLayout() >>> L.add_edge_style('a', 'b', directed=True, edge_style='dotted') >>> L.add_edge_style('b', 'c', arrow_shape='tee', arrow_fill='hollow') >>> L.get_style_json() {'style': [{'style': {'width': 1.0, 'line-color': '#000000', 'target-arrow-shape': 'triangle', 'line-style': 'dotted', 'target-arrow-fill': 'filled', 'target-arrow-color': '#000000'}, 'selector': 'edge[source="a"][target="b"]'}, {'style': {'width': 1.0, 'line-color': '#000000', 'target-arrow-shape': 'none', 'line-style': 'solid', 'target-arrow-fill': 'hollow', 'target-arrow-color': '#000000'}, 'selector': 'edge[source="b"][target="c"]'}]} """ data_properties = {} style_properties = {} data_properties.update({"source": source, "target": target}) style_properties = GSGraph.set_edge_color_property(style_properties, color) style_properties = GSGraph.set_edge_width_property(style_properties, width) style_properties = GSGraph.set_edge_target_arrow_shape_property(style_properties, arrow_shape) style_properties = GSGraph.set_edge_directionality_property(style_properties, directed, arrow_shape) style_properties = GSGraph.set_edge_line_style_property(style_properties, edge_style) style_properties = GSGraph.set_edge_target_arrow_fill(style_properties, arrow_fill) attr_dict = attr_dict if attr_dict is not None else dict() selector = 'edge[source="%s"][target="%s"]' % (source, target) attr_dict.update(style_properties) self.set_style_json({ 'style': self.get_style_json().get('style') + [{ 'selector': selector, 'style': attr_dict }] })
def gradient_overlap_survey(H, source_members, target_members, bdist, k): names = name_dict() G = GSGraph() for node in H.node_iterator(): name = names.get(node, 'NONE') name, orig_name, height, width = parse_name(name) if node in target_members: shape = 'star' height = 80 width = 80 else: shape = 'ellipse' height = 80 width = 80 if node not in bdist: layer_color = '#aab3c1' shape = 'ellipse' height = 40 width = 40 else: layer_color = assign_gradient([100, 100, 255], [0, 255, 0], bdist[node], k) popup = '%s<br>%s<br>InSource? %s<br>InTarget? %s<br>InConnectedSet? %s' % ( name, node, node in source_members, node in target_members, node in bdist.keys()) G.add_node(node, label=name, popup=popup) G.add_node_style(node, height=height, width=width, color=layer_color, shape=shape) for hedge_id in H.hyperedge_id_iterator(): #print('Adding hyperege ' + hedge_id) #print(' %d Tails:' % len(H.get_hyperedge_tail(hedge_id)),[names[n] for n in H.get_hyperedge_tail(hedge_id)]) #print(' %d Heads:'% len(H.get_hyperedge_head(hedge_id)),[names[n] for n in H.get_hyperedge_head(hedge_id)]) gs_add_hyperedge(G, H, hedge_id) return G
from graphspace_python.api.client import GraphSpace # Initialize client with your username and password graphspace = GraphSpace('*****@*****.**', 'user1') # Fetch the graph data data_url = 'https://cdn.rawgit.com/maxkfranz/934042c1ecc464a8de85/raw' response = urllib.urlopen(data_url) graph_data = json.loads(response.read()) # Load the style json file with open('style.json') as style_json_file: style_json = json.load(style_json_file) # Initialize graph G = GSGraph() # Set name, tags and visibility status G.set_name('Tokyo Railways') G.set_tags(['tokyo-railways', 'graphspace', 'demo']) G.set_is_public() # Define and set data data = { 'description': 'Graphical representation of railway network of Tokyo.<br>View functional demo of this graph at:\ <a href=\"http://js.cytoscape.org/demos/tokyo-railways/\">http://js.cytoscape.org/demos/tokyo-railways/</a>', 'directed': False } G.set_data(data) # Construct nodes and edges of the graph from graph data for node in graph_data['elements']['nodes']:
def Graph_Maker(node_list, edge_list, TimeDict): G = GSGraph() G.set_name('GroupProject_Test_w/positives') G.set_tags(['GroupProject']) #This section transforms and normalizes the data Timelist = [ ] #I'm just making a list of counts to use to calculate node color logList = [] NewTimeDict = {} for noden in TimeDict: #just making a list of values in the dictionary (useful for nodecolor) newval = TimeDict[noden] + 1 #adds 1 to each countso there are no zeros NewTimeDict[noden] = newval #adds the value if NewTimeDict[noden] not in Timelist: Timelist.append(NewTimeDict[noden]) #adds the value to a list for val in Timelist: #to figure out the max log transformed value logv = math.log(val) logList.append(logv) for n in NewTimeDict: #log transforms values and then normalizes logval = math.log(NewTimeDict[n]) NewTimeDict[n] = logval / max( logList ) #new value is the log of the count normalized by dividing by the max log value #This section makes the graph and updates on GraphSpace for n in node_list: poplabel = "Count: " + str(TimeDict[n]) + ";Normalized: " + str( NewTimeDict[n]) G.add_node(n, popup=poplabel, label=n) blue = NewTimeDict[ n] #a value between 0 and 1 (most visited = most blue) red = 1 - blue #opposite of blue nodecolor = rgb_to_hex(red, 0, blue) G.add_node_style( n, width=20, height=20, color=nodecolor, ) for e in edge_list: G.add_edge(e[0], e[1]) G.add_edge_style(e[0], e[1], width=2) graphspace.post_graph(G) print("Graph Updated")
def Graph_Maker(nodelist, edgelist, MCL_List, p_AR, p_MCL, p_FFL, MCL_count): G = GSGraph() G.set_name('Sol_YEAST_MCL_FULL_Graph') G.set_tags(['Lab 6']) desc_string = 'Fi MCL = ' + str(MCL_count) + ';r=20; t=20; p(AR) = ' + str( p_AR) + ' p(MCL) =' + str(p_MCL) + ' p(FFL) = ' + str(p_FFL) G.set_data(data={'description': desc_string}) for n in nodelist: G.add_node(n, label=n) for e in edgelist: G.add_edge(e[0], e[1]) if e in MCL_List: G.add_edge_style(e[0], e[1], width=2, directed=True, color='yellow') else: G.add_edge_style(e[0], e[1], width=2, directed=True) graphspace.post_graph(G) print("Graph Updated")
def post_graph(nodes,edges,positives,graphspace,graph_name,ranks=None,weight_edges=False): sizes = {} if ranks != None: max_size = max(ranks.values()) min_size = min(ranks.values()) for key in ranks: sizes[key] = (ranks[key]-min_size)/(max_size-min_size) G = GSGraph() G.set_name(graph_name) G.set_tags(['NMII']) G.set_data(data={'description': 'Nodes are proteins and edges are protein interactions. Gray nodes are positives.'}) for n in nodes: scale_factor = 1 rank_num = 'unranked' norm_num = 'unranked' if ranks != None: scale_factor = 1+sizes.get(n,0) rank_num = str(ranks.get(n,'unranked')) norm_num = str(sizes.get(n,'unranked')) if n in positives: color = '#AAAAAA' else: color = '#AA2255' G.add_node(n,label=n,popup='scale factor = %f<br>rank = %s<br>normalized rank = %s' % (scale_factor,rank_num,norm_num)) G.add_node_style(n,color=color,shape='ellipse',height=50*scale_factor,width=50*scale_factor) for e in edges: scale_factor = 1 color = 'k' max_norm_rank = -1 if ranks != None and weight_edges: max_norm_rank = max(sizes.get(e[0],0),sizes.get(e[1],0)) scale_factor = max((1-max_norm_rank)**2,0.3) print(e[0],e[1],[sizes.get(e[0],0),sizes.get(e[1],0)],scale_factor) color_max = min(max_norm_rank,0.5) color = rgb_to_hex(color_max,color_max,color_max) popup_str = 'linewidth = %f <br> max_norm_rank = %f<br> line color = (%f,%f,%f)' % (scale_factor,max_norm_rank,color_max,color_max,color_max) else: popup_str = 'linewidth = %f' % (scale_factor) G.add_edge(e[0],e[1],popup=popup_str) G.add_edge_style(e[0],e[1],color=color,width=scale_factor) # post graph post(G,graphspace) print('Done posting %s' % (graph_name)) return
def test_update_graph(name): graphspace = GraphSpace('*****@*****.**', 'user1') graph1 = GSGraph() if name is not None: graph1.set_name(name) graph1.add_node('a', popup='sample node popup text', label='A updated') graph1.add_node_style('a', shape='ellipse', color='green', width=90, height=90) graph1.add_node('b', popup='sample node popup text', label='B updated') graph1.add_node_style('b', shape='ellipse', color='yellow', width=40, height=40) graph1.set_is_public() graph1.set_data(data={'description': 'my sample graph'}) graph = graphspace.update_graph(graph1) assert type(graph) is Graph assert graph.get_name() == graph1.get_name() and graph.is_public == 1 assert len(graph.graph_json['elements']['edges']) == 0 assert len(graph.graph_json['elements']['nodes']) == 2
def post_graph(nodes, edges, SexDict, TBDict, GroupDict, DegreeDict, edgeDict): graphspace = GraphSpace("*****@*****.**", "solTB") #Starting GraphSpace session G = GSGraph() G.set_name('Sol_Badger_Graph') G.set_tags(['HW 1']) G.set_data( data={ 'description': 'Male: Rectangle; Female: Ellipse<br> TB+: Dotted Border; TB-: Solid Border<br> Group1: pink; Group2: red; Group3: orange; Group4: yellow; Group5: green;<br> Group6: light blue; Group7: indigo; Group8: purple <br> View in "Social_Groups" Layout' }) contactlist = [ ] #I'm going to use this list to come up with k values for the edges for item in edgeDict: if edgeDict[ item] not in contactlist: #each contact time value only added once contactlist = contactlist + [ edgeDict[item] ] #making a list with all the contact times contactlist.sort( reverse=True ) #sorting the list of contact times from largest to samllest for node in nodes: #adds all of the nodes sex = SexDict[node] TB = TBDict[node] Group = GroupDict[node] size = DegreeDict[node] * 3 popupstring = "<i>Sex</i>: " + sex + "<br> <i>TB Status</i>: " + TB + "<br> <i>Group</i>: " + Group G.add_node(node, label=node, popup=popupstring, k=0) if sex == "Male": nshape = 'rectangle' elif sex == "Female": nshape = 'ellipse' if TB == 'P': nborder = 'dotted' elif TB == 'N': nborder = 'solid' if Group == '1': ncolor = '#EF0FA6' #pink elif Group == '2': ncolor = '#EF0F16' #red elif Group == '3': ncolor = '#EF7A0F' #orange elif Group == '4': ncolor = '#EFDA0F' #yellow elif Group == '5': ncolor = '#0FEF38' #green elif Group == '6': ncolor = '#0FEFEC' #light blue elif Group == '7': ncolor = '#000ACB' #indigo elif Group == '8': ncolor = '#A614E2' #purple G.add_node_style(node, color=ncolor, style=nborder, border_width=5, shape=nshape, height=size, width=size) for edge in edges: #adds all of the edges callkey = edge[0] + edge[ 1] #constructs the keystring for the dictionary thickness = edgeDict[callkey] #badger contact time kval = contactlist.index( thickness ) #k value of edge = index of thickness in the list of contact time (sorted from biggest to smallest) logthick = math.log(thickness) #transforms it to log scale intlog = int(logthick) #easier to work with than a float popstring = "<i>Contact Time</i>: " + str( thickness) + "<br> <i>log(contact time)</i>: " + str(intlog) G.add_edge( edge[0], edge[1], popup=popstring, k=kval) #shows contact time and log(contact time) on edge popup G.add_edge_style( edge[0], edge[1], width=(intlog / 2)) #makes edge thickness = 1/2 of log(contact time) graphspace.update_graph(G) #makes updates to the existing graph print("Graph Updated")
from graphspace_python.graphs.classes.gsgraph import GSGraph from graphspace_python.api.client import GraphSpace # Initialize client with your username and password graphspace = GraphSpace('*****@*****.**', 'user1') # Load the graph json file with open('graph.json') as graph_json_file: graph_json = json.load(graph_json_file) # Load the style json file with open('style.json') as style_json_file: style_json = json.load(style_json_file) # Initialize graph G = GSGraph() # Set name, tags and visibility status G.set_name('Labels Demo') G.set_tags(['labels', 'graphspace', 'demo']) G.set_is_public() # Define and set data data = { 'description': 'This is a demo graph showing different labels. You can also view this demo graph at:\ <a href=\"http://js.cytoscape.org/demos/labels/\">http://js.cytoscape.org/demos/labels/</a>', 'directed': False } G.set_data(data) # Set graph_json and style_json G.set_graph_json(graph_json)
def constructGraph(edges, prednodes=None, node_labels={}, graph_attr={}, popups={}, edge_dirs={}): """ Posts the set of edges to graphspace *edges*: set of edges to post *graph_attr*: optional dictionary containing styles for nodes and edges. For example: n1: {color: red, border_width: 10} n1-n2: {line-color: blue} *node_labels*: optional dictionary containing the desired label for each node *popups*: optional dictionary containing html popups for nodes and edges *edge_dirs*: optional dictionary specifying if an edge is directed (True) or not (False). Default is not directed (False) returns the constructed GSGraph """ # NetworkX object #G = nx.DiGraph(directed=True) G = GSGraph() if prednodes is None: prednodes = set([t for t,h in edges]).union(set([h for t,h in edges])) # GSGraph does not allow adding multiple nodes with the same name. # Use this set to make sure each node has a different gene name. # if the gene name is the same, then use the gene + uniprot ID instead labels_added = set() # set of parent nodes to add to the graph #parents_to_add = {} ## add GraphSpace/Cytoscape.js attributes to all nodes. for n in prednodes: # this dictionary will pass along any extra parameters that are not usually handled by GraphSpace attr_dict = {} # A 'group' node is also known as a 'compound' or 'parent' node if n in graph_attr and 'parent' in graph_attr[n]: # set the group of this node group = graph_attr[n]['parent'] attr_dict['parent'] = group # if there is no popup, then have the popup just be the node name node_popup = popups.pop(n, n) # leave the gene name as the node ID if there are no node_labels provided node_label = node_labels.pop(n,n) # if this gene name node was already added, then add another node with the name: gene-uniprot if node_label in labels_added: node_label = "%s-%s" % (node_label, n) node_labels[n] = node_label labels_added.add(node_label) G.add_node(node_label, attr_dict=attr_dict, popup=node_popup, label=node_label) # these are the default values I like. Any styles set in the graph_attr dictionary will overwrite these defaults attr_dict = { #"border-color": "#7f8184" } #border_color = "#7f8184" # slightly darker grey shape = 'ellipse' color = '#D8D8D8' # grey - background-color #border_style = 'solid' width = 45 height = 45 border_width = 2 bubble = None # default is the node color if n in graph_attr: # any attribute can be set in the graph_attr dict and the defaults will be overwritten for style in graph_attr[n]: # for some reason, the text color is updated with this color... if style == 'color': continue attr_dict[style] = graph_attr[n][style] # get the color so the bubble is updated correctly # color is actually used for the background color if 'color' in graph_attr[n]: color = graph_attr[n]['color'] #if 'border_color' in graph_attr[n]: # border_color= graph_attr[n]['border_color'] #if 'bubble' in graph_attr[n]: # border_color= graph_attr[n]['bubble'] if 'border-color' not in attr_dict: attr_dict['border-color'] = color #border_color = color if border_color is None else border_color # I updated the bubble function in graphspace_python gsgraph.py so it wouldn't overwrite the border color. bubble = color if bubble is None else bubble #if n == "P11021": # print(attr_dict) # sys.exit() G.add_node_style(node_label, shape=shape, attr_dict=attr_dict, color=color, width=width, height=height, #style=border_style, #border_color=border_color, #border_width=border_width, bubble=bubble) # Add all of the edges and their Graphspace/Cytoscape.js attributes for (u,v) in edges: # if there is no popup, then have the popup just be the edge name edge_popup = popups.pop((u,v), "%s-%s" % (u,v)) directed = edge_dirs.pop((u,v), False) # TODO directed vs undirected edges into an option G.add_edge(node_labels[u],node_labels[v],directed=directed,popup=edge_popup) # edge style defaults: attr_dict = { 'width': 1.5, # this should be the default for directed edges #'target-arrow-shape': 'triangle', 'line-style': 'solid'} color = "#D8D8D8" # in the attr_dict, this is 'line-color' if (u,v) in graph_attr: # any attribute can be set in the graph_attr dict and the defaults will be overwritten for style in graph_attr[(u,v)]: attr_dict[style] = graph_attr[(u,v)][style] if 'color' in graph_attr[(u,v)]: color = graph_attr[(u,v)]['color'] #print(width, color, arrow_shape, edge_style) G.add_edge_style(node_labels[u], node_labels[v], attr_dict=attr_dict, directed=directed, color=color) return G
import json from graphspace_python.graphs.classes.gsgraph import GSGraph from graphspace_python.api.client import GraphSpace # Initialize client with your username and password graphspace = GraphSpace('*****@*****.**', 'user1') # Initialize graph G = GSGraph() # Set name, tags and visibility status G.set_name('Edge Types Demo') G.set_tags(['edge-types', 'graphspace', 'demo']) G.set_is_public() # Define and set data data = { 'description': 'This is a demo graph showing different types of edges. You can also view this demo graph at:\ <a href=\"http://js.cytoscape.org/demos/edge-types/\">http://js.cytoscape.org/demos/edge-types/</a>', 'directed': False } G.set_data(data) # Construct nodes and edges of the graph # Add nodes G.add_node('n01', label='bezier') G.add_node('n02') G.add_node('n03', label='unbundled-bezier') G.add_node('n04') G.add_node('n05', label='unbundled-bezier(multiple)') G.add_node('n06') G.add_node('n07', label='haystack')
def post_graph(gs_session,nodes,edges): G = GSGraph() G.set_name('Badger Graph - Doak') G.set_tags(['HW1']) badgerInfo = parse_info("BadgerInfo.txt") degreeOfNode = [0]*len(nodes) # Create a list of the same length as nodes # Then check node 1 in every edge, find its index in nodes, # and add one to its degree in the degreeOfNode list for edge in edges: indBadger = nodes.index(edge[0]) degreeOfNode[indBadger] += 1 nodeCount = 0 # For the index of each node as it iterates through, for finding # the degree of that node for node in nodes: if badgerInfo[node][1] == 'N': infoTwo = 'Negative for TB' else: infoTwo = 'Positive for TB' G.add_node(node, label = node, k = 1, popup = badgerInfo[node][0]+'<br>'+ infoTwo+'<br>'+ 'Social group '+badgerInfo[node][2]) borderStyle = 'solid' # Throws error if not defined early in the function if badgerInfo[node][0] == 'Male': shape = 'rectangle' elif badgerInfo[node][0] == 'Female': shape = 'ellipse' else: shape = 'triangle' if badgerInfo[node][1] == 'P': # positive for TB color = '#1786a3' elif badgerInfo[node][1] == 'N': # negative for TB color = '#97cddb' else: # unknown TB status color = 'white' if badgerInfo[node][2] in ['1','2','3']: borderColor = 'black' if badgerInfo[node][2] == '1': borderWidth = 2 elif badgerInfo[node][2] == '2': borderWidth = 5 elif badgerInfo[node][2] == '3': borderWidth = 9 elif badgerInfo[node][2] in ['4','5','6']: borderColor = 'black' borderStyle = 'dashed' if badgerInfo[node][2] == '4': borderWidth = 2 elif badgerInfo[node][2] == '5': borderWidth = 5 elif badgerInfo[node][2] == '6': borderWidth = 9 elif badgerInfo[node][2] in ['7','8']: borderColor = 'gray' if badgerInfo[node][2] == '7': borderWidth = 2 elif badgerInfo[node][2] == '8': borderWidth = 5 sizeMod = degreeOfNode[nodeCount]*3 # Degree * 3 to add to the size of each node G.add_node_style(node, height = 40+sizeMod, width = 60+sizeMod, shape = shape, color = color, border_color = borderColor, border_width = borderWidth, style = borderStyle) nodeCount += 1 for edge in edges: G.add_edge(edge[0],edge[1],k=10/(math.log(int(edge[2]),10)+0.1), popup='Number of seconds interacted: '+edge[2]) G.add_edge_style(edge[0],edge[1], width = int(edge[2])/10000 + 0.5) G.set_data(data = {'description': 'Males = rectangles, \ females = ellipses, \ unknown = triangles;<br>\ TB positive = dark blue, \ TB negative = light blue, \ unknown TB status = white;<br>\ social group 1-3 = black border (width 2,5,9);<br>\ social group 4-6 = black dashed border (width 2,5,9);<br>\ social group 7-8 = gray border (width 2,5);<br>\ size of node indicates degree;<br>\ size of edge indicates amount of time spent together'}) post(G, gs_session)
def get_gs_graph(graph_file: str, graph_name: str, directed=False) -> GSGraph: # read file as networkx graph nxG = load_graph(graph_file, directed=directed) # convert networkx graph to GraphSpace object G = GSGraph() G.set_name(graph_name) for n in nxG.nodes(): G.add_node(n, label=n, popup='Node %s' % (n)) G.add_node_style(n, color='#ACCE9A', shape='rectangle', width=30, height=30) for u, v in nxG.edges(): if directed: G.add_edge(u, v, directed=True, popup='Directed Edge %s-%s<br>Rank %d' % (u, v, nxG[u][v]['rank'])) G.add_edge_style(u, v, directed=True, width=2, color='#281D6A') else: G.add_edge(u, v, popup='Undirected Edge %s-%s<br>Rank %d' % (u, v, nxG[u][v]['rank'])) G.add_edge_style(u, v, width=2, color='#281D6A') return G
import json from graphspace_python.graphs.classes.gsgraph import GSGraph from graphspace_python.api.client import GraphSpace # Initialize client with your username and password graphspace = GraphSpace('*****@*****.**', 'user1') # Initialize graph G = GSGraph() # Set name, tags and visibility status G.set_name('Compound Nodes') G.set_tags(['compound-nodes', 'graphspace', 'demo']) G.set_is_public() # Define and set data data = { 'description': 'This is a demo graph having compund nodes. You can also view this demo graph at:\ <a href=\"http://js.cytoscape.org/demos/compound-nodes/\">http://js.cytoscape.org/demos/compound-nodes/</a>', 'directed': True } G.set_data(data) # Construct nodes and edges of the graph # Add nodes G.add_node('a', parent='b') G.add_node('b') G.add_node('c', parent='b') G.add_node('d') G.add_node('e') G.add_node('f', parent='e') # Set node positions
from graphspace_python.api.client import GraphSpace # Initialize client with your username and password graphspace = GraphSpace('*****@*****.**', 'user1') # Fetch the graph data data_url = 'https://raw.githubusercontent.com/cytoscape/wineandcheesemap/gh-pages/data.json' response = urllib.urlopen(data_url) graph_data = json.loads(response.read()) # Load the style json file with open('style.json') as style_json_file: style_json = json.load(style_json_file) # Initialize graph G = GSGraph() # Set name, tags and visibility status G.set_name('Wine and Cheese') G.set_tags(['wineandcheese', 'graphspace', 'demo']) G.set_is_public() # Define and set data data = { 'description': 'Network of wine and cheese pairing.<br>View functional demo of this graph at:\ <a href=\"http://www.wineandcheesemap.com/\">http://www.wineandcheesemap.com/</a>', 'directed': False } G.set_data(data) # Construct nodes and edges of the graph from graph data for node in graph_data['elements']['nodes']: G.add_node(node['data']['id'], node['data'], label=node['data']['name'])
def Graph_Maker(node_list, edge_list, TimeDict, interactDict): G = GSGraph() G.set_name('Sol_Self-Loop_Walk_Graph') G.set_tags(['HW3']) #This section transforms and normalizes the data Timelist = [ ] #I'm just making a list of counts to use to calculate node color logList = [] NewTimeDict = {} for noden in TimeDict: #just making a list of values in the dictionary (useful for nodecolor) newval = TimeDict[noden] + 1 #adds 1 to each countso there are no zeros NewTimeDict[noden] = newval #adds the value if NewTimeDict[noden] not in Timelist: Timelist.append(NewTimeDict[noden]) #adds the value to a list for val in Timelist: #to figure out the max log transformed value logv = math.log(val) logList.append(logv) for n in NewTimeDict: #log transforms values and then normalizes logval = math.log(NewTimeDict[n]) NewTimeDict[n] = logval / max( logList ) #new value is the log of the count normalized by dividing by the max log value #This section makes the graph and updates on GraphSpace seenedges = [ ] # a list of edges that have gone over so there aren't multiple edges between two nodes for n in node_list: poplabel = "Count: " + str(TimeDict[n]) + ";Normalized: " + str( NewTimeDict[n]) G.add_node(n, popup=poplabel, label=n) blue = NewTimeDict[ n] #a value between 0 and 1 (most visited = most blue) red = 1 - blue #opposite of blue nodecolor = rgb_to_hex(red, 0, blue) G.add_node_style( n, width=20, height=20, color=nodecolor, ) for e in edge_list: namecall = str(e[0] + e[1]) #to call up interaction type for the popup if namecall in interactDict: plabel = interactDict[namecall] else: plabel = "N/A" if [e[1], e[0]] in edge_list: #if the inverse exists if e not in seenedges: G.add_edge(e[0], e[1], popup=plabel, directed=False) seenedges.append(e) seenedges.append([e[1], e[0]]) else: #if the graph isn't bidirectional add an arrow G.add_edge(e[0], e[1], popup=plabel, directed=True) G.add_edge_style(e[0], e[1], width=2, directed=True) graphspace.post_graph(G) print("Graph Updated")
def test_post_graph(name=None): graphspace = GraphSpace('*****@*****.**', 'user1') graph1 = GSGraph() if name is not None: graph1.set_name(name) graph1.add_node('a', popup='sample node popup text', label='A') graph1.add_node_style('a', shape='ellipse', color='red', width=90, height=90) graph1.add_node('b', popup='sample node popup text', label='B') graph1.add_node_style('b', shape='ellipse', color='blue', width=40, height=40) graph1.add_edge('a', 'b', directed=True, popup='sample edge popup') graph1.add_edge_style('a', 'b', directed=True, edge_style='dotted') graph1.set_data(data={'description': 'my sample graph'}) graph1.set_tags(['sample']) graph = graphspace.post_graph(graph1) assert type(graph) is Graph assert graph.get_name() == graph1.get_name() return graph
def constructGraph(edges, node_labels={}, graph_attr={}, popups={}, edge_dirs={}): """ Posts the set of edges to graphspace *edges*: set of edges to post *graph_attr*: optional dictionary containing styles for nodes and edges. For example: n1: {color: red, border_width: 10} n1-n2: {line-color: blue} *node_labels*: optional dictionary containing the desired label for each node *popups*: optional dictionary containing html popups for nodes and edges *edge_dirs*: optional dictionary specifying if an edge is directed (True) or not (False). Default is not directed (False) returns the constructed GSGraph """ # NetworkX object #G = nx.DiGraph(directed=True) G = GSGraph() prednodes = set([t for t, h in edges]).union(set([h for t, h in edges])) # GSGraph does not allow adding multiple nodes with the same name. # Use this set to make sure each node has a different gene name. # if the gene name is the same, then use the gene + uniprot ID instead labels_added = set() # set of parent nodes to add to the graph #parents_to_add = {} ## add GraphSpace/Cytoscape.js attributes to all nodes. for n in prednodes: attr_dict = {} # TODO add the parent nodes functionality back # See the src/python/graphspace/trunk/graphspace-human/post_to_new_graphspace_evidence.py script #if PARENTNODES is True: # # set the parent if specified # if n in graph_attr and 'parent' in graph_attr[n]: # # set the parent of this node # parent = graph_attr[n]['parent'] # attr_dict['parent'] = parent # if there is no popup, then have the popup just be the node name node_popup = popups.pop(n, n) # leave the gene name as the node ID if there are no node_labels provided node_label = node_labels.pop(n, n) # if this gene name node was already added, then add another node with the name: gene-uniprot if node_label in labels_added: node_label = "%s-%s" % (node_label, n) node_labels[n] = node_label labels_added.add(node_label) G.add_node(node_label, attr_dict=attr_dict, popup=node_popup, label=node_label) attr_dict = {} # these are the default values I like. Any styles set in the graph_attr dictionary will overwrite these defaults shape = 'ellipse' color = '#D8D8D8' # grey - background-color border_style = 'solid' width = 45 height = 45 border_width = 2 border_color = "#7f8184" # slightly darker grey bubble = None # default is the node color if n in graph_attr: # any attribute can be set in the graph_attr dict and the defaults will be overwritten for style in graph_attr[n]: # for some reason, the text color is updated with this color... if style == 'color': continue attr_dict[style] = graph_attr[n][style] # get the color so the bubble is updated correctly # color is actually used for the background color if 'color' in graph_attr[n]: color = graph_attr[n]['color'] if 'border_color' in graph_attr[n]: border_color = graph_attr[n]['border_color'] if 'bubble' in graph_attr[n]: border_color = graph_attr[n]['bubble'] border_color = color if border_color is None else border_color # I updated the bubble function in graphspace_python gsgraph.py so it wouldn't overwrite the border color. bubble = color if bubble is None else bubble G.add_node_style(node_label, shape=shape, attr_dict=attr_dict, color=color, width=width, height=height, style=border_style, border_color=border_color, border_width=border_width, bubble=bubble) # Add all of the edges and their Graphspace/Cytoscape.js attributes for (u, v) in edges: # if there is no popup, then have the popup just be the edge name edge_popup = popups.pop((u, v), "%s-%s" % (u, v)) directed = edge_dirs.pop((u, v), False) # TODO directed vs undirected edges into an option G.add_edge(node_labels[u], node_labels[v], directed=directed, popup=edge_popup) attr_dict = {} arrow_shape = 'triangle' # target-arrow-shape color = "#D8D8D8" # line-color edge_style = 'solid' # line-style width = 1.5 # width if (u, v) in graph_attr: # any attribute can be set in the graph_attr dict and the defaults will be overwritten for style in graph_attr[(u, v)]: attr_dict[style] = graph_attr[(u, v)][style] if 'color' in graph_attr[(u, v)]: color = graph_attr[(u, v)]['color'] #print(width, color, arrow_shape, edge_style) G.add_edge_style(node_labels[u], node_labels[v], attr_dict=attr_dict, directed=directed, color=color, width=width, arrow_shape=arrow_shape, edge_style=edge_style) return G
def post_gn_graph(tree, title, gs_session): G = GSGraph() G.set_name(title) G.set_tags(['Lab8']) nodes = [] for pair in tree.keys(): if pair[0] not in nodes: nodes.append(pair[0]) if pair[1] not in nodes: nodes.append(pair[1]) for node in nodes: G.add_node(node, label=node) if '+' in node: G.add_node_style(node, color='pink', height=30, width=30 + 20 * (float(len(node)) - 1)) else: G.add_node_style(node, color='#98edfa', height=30, width=30) for edge, branch_dist in tree.items(): G.add_edge(edge[0], edge[1]) G.add_edge_style(edge[0], edge[1], width=float(branch_dist)) G.set_data( data={ 'description': 'original OTUs are blue, all others are pink; edge thickness is proportional to branch length' }) post(G, gs_session)
import urllib import json from graphspace_python.graphs.classes.gsgraph import GSGraph from graphspace_python.api.client import GraphSpace # Initialize client with your username and password graphspace = GraphSpace('*****@*****.**', 'user1') # Fetch the graph data data_url = 'https://raw.githubusercontent.com/cytoscape/cytoscape.js/master/documentation/demos/circle-layout/data.json' response = urllib.urlopen(data_url) graph_data = json.loads(response.read()) # Initialize graph G = GSGraph() # Set name, tags and visibility status G.set_name('Circle Layout') G.set_tags(['circle-layout', 'graphspace', 'demo']) G.set_is_public() # Define and set data data = { 'description': 'This is a demo graph having circular layout. You can also view this demo graph at:\ <a href=\"http://js.cytoscape.org/demos/circle-layout/\">http://js.cytoscape.org/demos/circle-layout/</a>', 'directed': True } G.set_data(data) # Construct nodes and edges of the graph from graph data for elem in graph_data: if elem['group'] == 'nodes':
def viz_graph(graphspace,nodes,edges,weights,title,communities): G = GSGraph() G.set_name(title + ' ' + str(time.time())) ## this name is timestamped G.set_tags(['Lab 6']) ## tags help you organize your graphs node_colors = {} if communities != None: k = len(communities) # number of communities for i in range(len(communities)): for j in range(len(communities[i])): node_colors[communities[i][j]] = rgb_to_hex(i/k,1-i/k,0.8) for n in nodes: G.add_node(n,label=n) G.add_node_style(n,color=node_colors.get(n,'#FFFFFF'),shape='roundrectangle',height=30,width=40) for u,v in edges: G.add_edge(u,v,popup='weight=%f' % (weights[u][v])) G.add_edge_style(u,v,width=weights[u][v]) post(G,graphspace) print('Done posting',title) return
def post_graph(nodes, edges, nonterminal_ST_nodes, terminals, steiner_tree, BFS_rank, title): ##Collaborative ## connect to GraphSpace USERNAME = '******' PASSWORD = '******' if USERNAME == 'FILL IN': sys.exit( 'ERROR: add your username and password in the post_graph() function. Exiting.' ) graphspace = GraphSpace(USERNAME, PASSWORD) # create Graph instance, set title and tags. G = GSGraph() m = 2 G.set_name(title) G.set_tags(['Hw5']) for n in nodes: if n in nonterminal_ST_nodes: color = rgb_to_hex(0, 1, 0) if n in BFS_rank: color = rgb_to_hex(1 * BFS_rank[n], 0, 0) if n in nonterminal_ST_nodes and n in BFS_rank: color = rgb_to_hex(1 * BFS_rank[n], 1, 0) popup = None if n in terminals: color = '#0C7999' popup = 'terminal node' G.add_node(n, label=n, popup=popup) G.add_node_style(n, color=color, shape='ellipse', height=30, width=30) for e in edges: G.add_edge(e[0], e[1]) G.add_edge_style(e[0], e[1], edge_style='dotted', color='#B1B1B1') for e in steiner_tree: G.add_edge_style(e[0], e[1], color='#000000', width=2) G.add_edge_style(e[1], e[0], color='#000000', width=2) G.set_data( data={ 'Regulators': 'Blue', 'top 100 Dijkstra Rank': 'Red', 'nonterminal_ST_nodes+': 'green', 'Spanning Tree Edge': 'Black', 'ST Node and Dijkstra ranked': 'Yellow (R+G)' }) try: graph = graphspace.update_graph(G) print('updated graph with title', title) except: graph = graphspace.post_graph(G) print('posted graph with title', title) return
def post_MST_graph(all_edges, MST_edges, name, list_tags, gs_session): nodes = get_nodes(all_edges) G = GSGraph() G.set_name(name) G.set_tags(list_tags) for node in nodes: G.add_node(node, label=node) G.add_node_style(node, color='#56b5bf', height=50, width=50) for edge in all_edges: G.add_edge(edge[0], edge[1], popup='weight: ' + str(edge[2])) if edge in MST_edges: G.add_edge_style(edge[0], edge[1], width=6 + edge[2], color='#6edfeb') else: G.add_edge_style(edge[0], edge[1], edge_style='dotted', width=6 + edge[2], color='#fc8f81') G.set_data( data={ 'description': 'Popups show the weights of the edges.\ Edges included in the MST are colored\ in blue, all excluded edges are in red.' }) post(G, gs_session)
def add_node_style(self, node_name, attr_dict=None, content=None, shape='ellipse', color='#FFFFFF', height=None, width=None, bubble=None, valign='center', halign='center', style="solid", border_color='#000000', border_width=1): """Add styling for a node belonging to the graph. Args: node_name (str): Name of node. attr_dict (dict, optional): Json representation of style of node. Defaults to None. shape (str, optional): Shape of node. Defaults to 'ellipse'. See :data:`ALLOWED_NODE_SHAPES` for more details. color (str, optional): Hexadecimal representation of the color (e.g., #FFFFFF) or color name. Defaults to white. height (int, optional): Height of the node's body, or None to determine height from the number of lines in the label. Defaults to None. width (int, optional): Width of the node's body, or None to determine width from length of label. Defaults to None. bubble (str, optional): Color of the text outline. Using this option gives a "bubble" effect; see the bubbleeffect() function. Defaults to None. valign (str, optional): Vertical alignment. Defaults to 'center'. See :data:`ALLOWED_TEXT_VALIGN` for more details. halign (str, optional): Horizontal alignment. Defaults to 'center'. See :data:`ALLOWED_TEXT_HALIGN` for more details. style (str, optional): Style of border. Defaults to 'solid'. If 'bubble' is specified, then style is overwritten. See :data:`ALLOWED_NODE_BORDER_STYLES` for more details. border_color (str, optional): Color of border. Defaults to '#000000'. If 'bubble' is specified, then style is overwritten. border_width (int, optional): Width of border. Defaults to 1. If 'bubble' is specified, then style is overwritten. Examples: >>> from graphspace_python.graphs.classes.gslayout import GSLayout >>> L = GSLayout() >>> L.add_node_style('a', shape='ellipse', color='red', width=90, height=90) >>> L.add_node_style('b', color='blue', width=90, height=90, border_color='#4f4f4f') >>> L.get_style_json() {'style': [{'style': {'border-color': '#000000', 'border-width': 1, 'height': 90, 'width': 90, 'shape': 'ellipse', 'border-style': 'solid', 'text-wrap': 'wrap', 'text-halign': 'center', 'text-valign': 'center', 'background-color': 'red'}, 'selector': 'node[name="a"]'}, {'style': {'border-color': '#4f4f4f', 'border-width': 1, 'height': 90, 'width': 90, 'shape': 'ellipse', 'border-style': 'solid', 'text-wrap': 'wrap', 'text-halign': 'center', 'text-valign': 'center', 'background-color': 'blue'}, 'selector': 'node[name="b"]'}]} """ attr_dict = attr_dict if attr_dict is not None else dict() selector = 'node[name="%s"]' % node_name style_properties = {} style_properties = GSGraph.set_node_shape_property( style_properties, shape) style_properties = GSGraph.set_node_color_property( style_properties, color) style_properties = GSGraph.set_node_label_property( style_properties, content) style_properties = GSGraph.set_node_width_property( style_properties, width) style_properties = GSGraph.set_node_height_property( style_properties, height) style_properties = GSGraph.set_node_vertical_alignment_property( style_properties, valign) style_properties = GSGraph.set_node_horizontal_alignment_property( style_properties, halign) style_properties = GSGraph.set_node_border_style_property( style_properties, style) style_properties = GSGraph.set_node_border_color_property( style_properties, border_color) style_properties = GSGraph.set_node_border_width_property( style_properties, border_width) # If bubble is specified, use the provided color, if bubble: style_properties = GSGraph.set_node_bubble_effect_property( style_properties, bubble, whitetext=False) attr_dict.update(style_properties) self.set_style_json({ 'style': self.get_style_json().get('style') + [{ 'selector': selector, 'style': attr_dict }] })
import json from graphspace_python.graphs.classes.gsgraph import GSGraph from graphspace_python.api.client import GraphSpace # Initialize client with your username and password graphspace = GraphSpace('*****@*****.**', 'user1') # Initialize graph G = GSGraph() # Set name, tags and visibility status G.set_name('Pie Style') G.set_tags(['pie-style', 'pie', 'graphspace', 'demo']) G.set_is_public() # Define and set data data = { 'description': 'A demo network where the nodes constitute of pie charts.<br>You can also view this demo graph at:\ <a href=\"http://js.cytoscape.org/demos/pie-style/\">http://js.cytoscape.org/demos/pie-style/</a>', 'directed': True } G.set_data(data) # Construct nodes and edges of the graph # Add nodes G.add_node('a', {"foo": 3, "bar": 5, "baz": 2}) G.add_node('b', {"foo": 6, "bar": 1, "baz": 3}) G.add_node('c', {"foo": 2, "bar": 3, "baz": 5}) G.add_node('d', {"foo": 7, "bar": 1, "baz": 2}) G.add_node('e', {"foo": 2, "bar": 3, "baz": 5}) # Set node positions G.set_node_position('a', y=60, x=550.5) G.set_node_position('b', y=193.2, x=733.8)
def main(graph_file, username, password): # read file as networkx graph nxG = nx.read_edgelist(graph_file) # convert networkx graph to GraphSpace object G = GSGraph() G.set_name('Docker Example %.4f' % (time.time())) for n in nxG.nodes(): G.add_node(n, label=n, popup='Node %s' % (n)) G.add_node_style(n, color='#ACCE9A', shape='rectangle', width=30, height=30) for u, v in nxG.edges(): G.add_edge(u, v, popup='Edge %s-%s' % (u, v)) G.add_edge_style(u, v, width=2, color='#281D6A') # post with unique timestamp gs = GraphSpace(username, password) try: graph = gs.update_graph(G) except: graph = gs.post_graph(G) print('posted graph') return
def graph_best_paths(gs_session,paths,labels,graph): G = GSGraph() G.set_name("Doak - Best Paths from Sqh to Fog") G.set_tags(['GP']) st_nodes = [paths[0][0],paths[0][-1]] nodes = {} edges = [] n_colors = ["#e76af7","#b767f5","#7666f2","#67aef5","#65d7eb","#62e391","#ade065"] for p in paths: for i in range(len(p)-1): if p[i] not in nodes.keys(): nodes[p[i]] = paths.index(p) if (p[i],p[i+1]) not in edges and (p[i+1],p[i]) not in edges: edges.append((p[i],p[i+1],graph[p[i]][p[i+1]])) if p[-1] not in nodes.keys(): nodes[p[-1]] = paths.index(p) for node,i in nodes.items(): G.add_node(node,label=node) if node in st_nodes: G.add_node_style(node, color = "#fa6bac", height = 30, width = max(30,15*(len(node)))) else: if node in labels.keys(): if labels[node] == "Positive": G.add_node_style(node, color = n_colors[nodes[node]], border_width = 3, border_color = 'green', style = 'dashed', height = 30, width = max(30,15*(len(node)))) elif labels[node] == "Negative": G.add_node_style(node, color = n_colors[nodes[node]], border_width = 3, border_color = 'red', style = 'dashed', height = 30, width = max(30,15*(len(node)))) else: G.add_node_style(node, color = n_colors[nodes[node]], border_width = 5, height = 30, width = max(30,15*(len(node)))) for edge in edges: G.add_edge(edge[0],edge[1]) G.add_edge_style(edge[0],edge[1],width=1+float(edge[2])) G.set_data(data={'description': 'shortest paths in fly interactome from sqh to fog, with sqh and fog highlighted in'\ ' pink. First shortest paths are warmer (closer to pink), shifting to purple, blue, then green'\ ' in order of when the paths were generated after removing previous nodes. Red-bordered nodes'\ ' are negative, green-bordered nodes are positive, and black-bordered nodes are unlabeled candidates.'}) post(G, gs_session)
(opts, args) = parser.parse_args() ## ##Input Validation ## ##Fatal Errors ## if opts.FileInput is None: sys.stderr.write("Warning: Must supply and input file") sys.exit(1) elif opts.GraphName is None: sys.stderr.write("Warning: Must supply a Graph name") sys.exit(1) G = GSGraph() ##OutputFile = opts.FileInput def ConvertToNodes( file ): ##Converts the Upstream/Downstream inputs into nodes so they can be compared to the nodes in the pathway to find overlaps. nodes = set() if file == None: return nodes with open(file) as t: g = [line.split('\t') for line in t.readlines().copy()] for x in g: