Exemplo n.º 1
0
def GraphMaker(V, E, nk, ek):
    graphspace = GraphSpace("*****@*****.**",
                            "solTB")  #Starting GraphSpace session
    G = GSGraph()
    G.set_name('Sol_BA_Graph')
    G.set_tags(['Lab 3'])
    for node in V:
        nkval = nk[node]
        G.add_node(node, label=node, k=nkval)
    for edge in E:
        ekval = ek[edge]
        G.add_edge(edge[0], edge[1], k=ekval)
    graphspace.update_graph(G)
    print("Graph Posted")
Exemplo n.º 2
0
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
Exemplo n.º 3
0
def test_update_graph(name):
    graphspace = GraphSpace('*****@*****.**', 'user1')
    graphspace.set_api_host('localhost:8000')

    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_data(data={'description': 'my sample graph'})
    response = graphspace.update_graph(name, graph=graph1, is_public=1)
    assert 'name' in response and response['name'] == graph1.get_name()
    assert response['is_public'] == 1
    assert len(response['graph_json']['elements']['edges']) == 0
    assert len(response['graph_json']['elements']['nodes']) == 2
Exemplo n.º 4
0
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
Exemplo n.º 5
0
def post_graph(G: GSGraph,
               username: str,
               password: str,
               directed=False) -> None:
    gs = GraphSpace(username, password)
    try:
        graph = gs.update_graph(G)
    except:
        graph = gs.post_graph(G)
    print('posted graph')
    return
Exemplo n.º 6
0
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
Exemplo n.º 7
0
def test_update_graph2(name):
    graphspace = GraphSpace('*****@*****.**', 'user1')
    # Retrieving graph
    graph = graphspace.get_graph(graph_name=name)
    # Modifying the retrieved graph
    graph.set_name(name)
    graph.add_node('z', popup='sample node popup text', label='Z')
    graph.set_is_public()
    # Updating graph
    graph1 = graphspace.update_graph(graph)
    assert type(graph1) is Graph
    assert graph1.get_name() == graph.get_name()
    assert 'z' in graph1.node
    assert graph1.is_public == 1
Exemplo n.º 8
0
def test_update_graph2(name):
    graphspace = GraphSpace('*****@*****.**', 'user1')
    graphspace.set_api_host('localhost:8000')
    # Retrieving graph
    graph = graphspace.get_graph(name)
    # Creating updated graph object
    G = GSGraph()
    G.set_graph_json(graph.get('graph_json'))
    G.set_style_json(graph.get('style_json'))
    G.set_name(graph.get('name'))
    G.set_tags(graph.get('name'))
    # Updating graph
    response = graphspace.update_graph(name, graph=G, is_public=1)
    assert 'name' in response and response['name'] == G.get_name()
    assert response['is_public'] == 1
Exemplo n.º 9
0
def post(G, username, password, group=None):
    '''
  Post a graph to graphspace.  If this graph is new, share it with
  the group.
  Inputs: Graph (GSGraph Object)
  Outputs: the graph ID (int)
  '''
    print('Posting graph...')

    # connect to GraphSpace with the username and password.
    gs = GraphSpace(username, password)
    try:
        # try updating the graph. If the graph does not exist,
        # this will throw an error.
        graph = gs.update_graph(G)
    except:
        # catch the error and try posting a new graph.
        graph = gs.post_graph(G)
        if group:
            # share this graph with the group.
            gs.share_graph(graph_id=graph.id, group_name=group)
    return graph.id
Exemplo n.º 10
0
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")
def post_graph_to_graphspace(G,
                             username,
                             password,
                             graph_name,
                             apply_layout=None,
                             layout_name='layout1',
                             group=None,
                             group_id=None,
                             make_public=None):
    """
    Post a graph to graphspace and perform other layout and sharing tasks
    *G*: Costructed GSGraph object
    *username*: GraphSpace username 
    *password*: GraphSpace password 
    *graph_name*: Name to give to graph when posting. If a graph with that name already exists, it will be updated
    *apply_layout*: Graph name to check for x and y positions of a layout (layout_name) and apply them to nodes of this graph 
    *layout_name*: Name of layout to check for in the apply_layout graph. Default: 'layout1' 
    *group*: Name of group to share graph with
    *group_id*: Not implemented yet. ID of group to share graph with. Could be useful if two groups have the same name
    *make_public*: Make the graph public
    """
    # post to graphspace
    gs = GraphSpace(username, password)
    print("\nPosting graph '%s' to graphspace\n" % (graph_name))
    gs_graph = gs.get_graph(graph_name, owner_email=username)

    layout = None
    # I often use the layout 'layout1', so I set that as the default
    # first check if the x and y coordinates should be set from another graph
    if apply_layout is not None:
        # if a layout was created for a different graph name, try to copy that layout here
        print("checking if layout '%s' exists for graph %s" %
              (layout_name, apply_layout))
        layout = gs.get_graph_layout(graph_name=apply_layout,
                                     layout_name=layout_name)
    # if the graph already exists, see if the layout can be copied
    if gs_graph is not None:
        print("checking if layout '%s' exists for this graph (%s)" %
              (layout_name, graph_name))
        layout = gs.get_graph_layout(graph=gs_graph, layout_name=layout_name)
    # now apply the layout if applicable
    if layout is not None:
        # set the x and y position of each node in the updated graph to the x and y positions of the layout you created
        print(
            "Setting the x and y coordinates of each node to the positions in %s"
            % (layout_name))
        for node, positions in layout.positions_json.items():
            G.set_node_position(node_name=node,
                                x=positions['x'],
                                y=positions['y'])
        # also check nodes that may have added a little more to the name
        for node in G.nodes():
            for n2, positions in layout.positions_json.items():
                # remove the newline from the node name if its there
                n2 = n2.split('\n')[0]
                if n2 in node:
                    G.set_node_position(node_name=node,
                                        x=positions['x'],
                                        y=positions['y'])

    if gs_graph is None:
        print("\nPosting graph '%s' to graphspace\n" % (graph_name))
        gsgraph = gs.post_graph(G)
    else:
        # "re-post" or update the graph
        print("\nGraph '%s' already exists. Updating it\n" % (graph_name))
        gsgraph = gs.update_graph(G,
                                  graph_name=graph_name,
                                  owner_email=username)
    if make_public is True:
        print("Making graph '%s' public." % (graph_name))
        gsgraph = gs.publish_graph(graph=G)
    print(gsgraph.url)

    # TODO implement the group_id. This will allow a user to share a graph with a group that is not their own
    if group is not None:
        # create the group if it doesn't exist
        #group = gs.post_group(GSGroup(name='icsb2017', description='sample group'))
        # or get the group you already created it
        print("sharing graph with group '%s'" % (group))
        group = gs.get_group(group_name=group)
        #print(group.url)
        gs.share_graph(graph=gs_graph, group=group)
Exemplo n.º 12
0
def NetPath_GraphSpace(genPathway, genNode, graphName, graphDescription, nameChoice, nodeAnnotation, namedict, analysisType):
     # Input: Array of arrays containing concatenated data from a NetPath-edges.txt file in the format of [Input, Output, Pathway type].  nameChoice is either "Uniprot" or "Common" to determine what the name of the nodes are.
     # As well as a concatenated NetPath-nodes.txt files with additional information for node type.
     # Process: Create nodes with graphical information using NetPath-nodes.txt, and then connect them with graphically detailed connections from the edges information.


     #Initializing Graph
     from graphspace_python.graphs.classes.gsgraph import GSGraph
     G = GSGraph()
     G.set_name(graphName) #Applies name to graph
     G.set_data(data={'description': graphDescription}) #Applies graph description
     #Graph initialized

     #Initializing Uniprot <-> Common name dictionary
     for nodecounter in range(len(genNode)):
        if nameChoice == "Uniprot":
            node = genNode[nodecounter][0]
        elif nameChoice == "Common":
            node = genNode[nodecounter][2]
            #print("node is: ", node) #DB
        node_symbol = genNode[nodecounter][1]

        #Adding the node

        if analysisType == "FullPathway":
            datatype = "normalizedhueavg"
        elif analysisType == "Node":
            datatype = "normalizedavg"
        elif analysisType == "T-test":
            datatype = "tsignificance"
        print("THE NODE ANNOTATION IS:", nodeAnnotation[(node + datatype)]) #DB

        if nodeAnnotation == None:
            G.add_node(node, popup = "sample node popup", label = node)
        elif nodeAnnotation != None:
            #G.add_node(node, popup = ("On a scale of 0 to 1, the normalized average of mRNA sequencing activity of this gene compared to all other genes in this pathway is: " + str(nodeAnnotation[(node + datatype)])), label = node)
            G.add_node(node, popup = ("The p-value of a t-test for this protein's mRNA activity for normal tissue vs cancerous tissue is: " + str(nodeAnnotation[(node + datatype)])), label = node)
            # Adds an annotation using data gathered from fbget

        #Adding style to the node
        if node_symbol == "tf":
            G.add_node_style(node, shape = 'vee', color = nodeAnnotation[(node + "huevalue")], width = 90, height = 90)
        elif node_symbol == "receptor":
            G.add_node_style(node, shape = 'rectangle', color = nodeAnnotation[(node + "huevalue")], width = 90, height = 90)
        else:
            G.add_node_style(node, shape = 'ellipse', color = nodeAnnotation[(node + "huevalue")], width = 90, height = 90)
     #Initializing variables
     edgeCheck = []
     #Initialized.
     for edgecounter in range(len(genPathway)):
        if nameChoice == "Uniprot":
            node1 = genPathway[edgecounter][0]
            node2 = genPathway[edgecounter][1]
        elif nameChoice == "Common":
            #node1 = genPathway[edgecounter][0] #Reads out in Uniprot
            #node2 = genPathway[edgecounter][1]
            node1 = namedict[genPathway[edgecounter][0]] #Missing the Uniprot key
            node2 = namedict[genPathway[edgecounter][1]] #1 if normal, 2 is TieDIE
        #lineweight = nodeAnnotation[node1 + node2 + "lineweight"] #PLACEHOLDER, use for width variable below
        #print("node1 is: ", node1) #DB
        #print("node2 is: ", node2) #DB

        edgetype = genPathway[edgecounter][2] #2 if normal, 1 if TieDIE

        #Checks if an edge has already been added.
        edgeCheck.append(node1 + node2)
        if (node2 + node1) in edgeCheck:
            continue

        if edgetype == "Phosphorylation":
            G.add_edge(node1, node2, directed = True, popup = "Phosphorylation interaction.")
            G.add_edge_style(node1, node2, directed = True, width = 1, edge_style = "solid", color = "yellow")
        elif edgetype == "Dephosphorylation":
            G.add_edge(node1, node2, directed = True, popup = "Dephosphorylation interaction")
            G.add_edge_style(node1, node2, directed = True, width = 1, edge_style = "solid", color = "red")
        else:
            G.add_edge(node1, node2, directed = False, popup = "Physical connection")
            G.add_edge_style(node1, node2, directed = False, width = 1, edge_style = "solid")

     #Uploading graph to Graphspace
     from graphspace_python.api.client import GraphSpace
     graphspace = GraphSpace('*****@*****.**', 'Pitapop2@2')

     graphresults = graphspace.get_graph(graphName, "*****@*****.**") #Checks if graph already exists.

     if graphresults == None:
         graphspace.post_graph(G)
     else:
         graphspace.update_graph(graphName, graph = G)

     #graphspace.update_graph(graphName, graph = G)

     return