Esempio n. 1
0
File: HW4.py Progetto: SolTB/Bio331
def post_graph(edge_list, T):
    graphspace = GraphSpace("*****@*****.**",
                            "solTB")  #Starting GraphSpace session
    G = GSGraph()
    G.set_name('Sol_MST_EGFR_Graph')
    G.set_tags(['HW 4'])

    seennodes = set(
    )  #keeps track of nodes which have been added since nodes can only be added once
    for e in edge_list:
        nodeA = e[0]
        nodeB = e[1]
        if nodeA not in seennodes:
            G.add_node(nodeA, label=nodeA)  #adds first node
            seennodes.add(nodeA)
        if nodeB not in seennodes:
            G.add_node(nodeB, label=nodeB)  #adds second node
            seennodes.add(nodeB)

        G.add_edge(nodeA, nodeB)  #adds edge
        edge_tup = (nodeA, nodeB)
        if edge_tup in T:
            G.add_edge_style(nodeA, nodeB, color='blue')

    graphspace.post_graph(G)
    print("Graph Posted")
Esempio n. 2
0
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
Esempio n. 3
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
Esempio n. 4
0
def test_post_graph(name=None):
    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')
    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'])
    response = graphspace.post_graph(graph1)
    assert 'name' in response and response['name'] == graph1.get_name()
Esempio 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
Esempio n. 6
0
def Convert(opts):
    nodes = set()
    uni2name = FileToDictionary(opts.unitproID)
    DSnodes = ConvertToNodes(opts.downstream)
    USnodes = ConvertToNodes(opts.upstream)
    OtherPath = ConvertToNodes(opts.OtherPathway)
    with open(opts.FileInput) as t:
        g = [line.split('\t') for line in t.readlines().copy()]
        for x in g:
            for y in [0, 2]:  ##Only care about columns 1 and 3.
                x[y] = x[y].strip('\n')
                if x[y] not in nodes:
                    nodes.add(x[y])
                    G.add_node(x[y], label=uni2name.get(x[y], x[y]))
                    print('Current Node=', uni2name.get(x[y]))
                    NodeShape, NodeColor = get_node_style(
                        x[y], USnodes, DSnodes, OtherPath)
                    G.add_node_style(x[y],
                                     shape=NodeShape,
                                     color=NodeColor,
                                     width=90,
                                     height=90)

            G.add_edge(x[0], x[2], directed=True)
            G.add_edge_style(x[0], x[2], directed=True, edge_style='dotted')

        G.set_name(opts.GraphName)

        G.set_data(
            data={
                'Graph Key':
                'Yellow Triangle = Upstream Input; Yellow Ellipse = Downstream Input; Red Rectangle = TieDie Result Path'
            })

        G.set_data(data={'Description': opts.GraphDescription})

        G.set_tags(['No Tags'])
        graphspace = GraphSpace(opts.GraphspaceLogin, opts.GraphspacePassword)
        graphspace.post_graph(G)
Esempio n. 7
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
Esempio n. 8
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
Esempio n. 9
0
# 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']:
    G.add_node(node['data']['id'], node['data'])
    G.set_node_position(node['data']['id'], node['position']['y'],
                        node['position']['x'])
for edge in graph_data['elements']['edges']:
    G.add_edge(edge['data']['source'], edge['data']['target'], edge['data'])

# Set style_json for the graph
G.set_style_json(style_json)

# Post graph to GraphSpace
graph = graphspace.post_graph(G)
print('Your graph has been saved on GraphSpace. You can view it at %s.' %
      graph.url)
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)
Esempio n. 11
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