source: CytoscapeRPC/scripts/LoadNetwork.py

Last change on this file was 66, checked in by j.j.bot@…, 7 years ago

First upload of the LoadNetwork?.py script.

File size: 4.5 KB
Line 
1
2#####################################################################################################
3# LoadNetwork.py
4# 13/08/2010
5# Jan Bot
6#
7# Module to easily load sif, noa and eda files into Cytoscape using CytocapeRPC.
8#
9# Usage: python LoadNetwork.py <port nr> <directory with the files>
10#
11#####################################################################################################
12
13import fnmatch
14import os
15import sys
16import xmlrpclib
17
18def parse_sif(filename):
19    """
20    Parser for sif files (basically the 'main' network file for Cytoscape
21    containing all the edges).
22    """
23    handle = open(filename, 'rb')
24   
25    nodes_from = []
26    nodes_type = []
27    nodes_to = []
28    ids = {}
29    for line in handle:
30        line = line.strip()
31        vars = line.split()
32        from_node = vars[0].strip()
33        node_type = vars[1].strip()
34        to_node = vars[2].strip()
35        ids[from_node] = ''
36        ids[to_node] = ''
37        nodes_from.append(from_node)
38        nodes_type.append(node_type)
39        nodes_to.append(to_node)
40    handle.close()
41    return (nodes_from, nodes_type, nodes_to, ids)
42
43def determine_type(var):
44    """
45    Helper function to determine the type of the parameters.
46    Not very cleanly implemented and does not support boolean values.
47    """
48    try:
49        int(var)
50        return ('INTEGER', int)
51    except ValueError:
52        try:
53            float(var)
54            return ('FLOATING', float)
55        except ValueError:
56            return ('STRING', str)
57
58def parse_attr_file(filename):
59    """
60    Very simple parser for attribute (noa / eda) files.
61    """
62    handle = open(filename, 'rb')
63    attrname = handle.readline().strip()
64    tvars = handle.readline().split('=')
65    (type, f)  = determine_type(tvars[1].strip())
66    handle.close()
67    handle = open(filename, 'rb')
68    handle.readline()
69    ids = []
70    attrs = []
71    com = {}
72    for line in handle:
73        vars = line.split('=')
74        id = vars[0].strip()
75        value = f(vars[1].strip())
76        ids.append(id)
77        attrs.append(value)
78        com[id] = value
79    handle.close()
80    return (attrname, ids, attrs, com, type)
81
82def find_files(dir, extension):
83    """
84    Helper function to list all the files in a dir with a certain file type.
85    """
86    files = []
87    for fileName in os.listdir ( dir ):
88        if fnmatch.fnmatch ( fileName, '*.' + extension ):
89            files.append(fileName)
90    return files
91
92def run():
93    """
94    Main function of script. Finds the files to load, calls the parsers and
95    handles the communication with Cytoscape.
96    """
97    port = int(sys.argv[1])
98    dir = sys.argv[2]
99    prefix = sys.argv[3]
100
101    server = xmlrpclib.ServerProxy("http://localhost:"+str(port))
102
103    sif_files = find_files(dir, 'sif')
104    for i, file in enumerate(sif_files):
105        print "Working on sif-file: " + file
106        sif_file = os.path.join(dir, file)
107        netid = server.Cytoscape.createNetwork(prefix + ' -- ' + str(i))
108        (nodes_from, nodes_type, nodes_to, ids) = parse_sif(sif_file)
109        node_ids = server.Cytoscape.createNodes(netid, ids.keys())
110        edge_ids = server.Cytoscape.createEdges(netid, nodes_from, nodes_to, nodes_type, [True]*len(nodes_to), True)
111        server.Cytoscape.performLayout(netid, 'force-directed')
112   
113    noa_files = find_files(dir, 'noa')
114    for file in noa_files:
115        print "Working on noa-file: " + file
116        noa_file = os.path.join(dir, file)
117        (attrname, ids, attrs, com, type) = parse_attr_file(noa_file)
118        server.Cytoscape.addNodeAttributes(attrname, type, com, False)
119
120    eda_files = find_files(dir, 'eda')
121    for file in eda_files:
122        print "Working on eda-file: " + file
123        eda_file = os.path.join(dir, file)
124        (attrname, ids, attrs, com, type) = parse_attr_file(eda_file)
125        server.Cytoscape.addEdgeAttributes(attrname, type, com)
126
127    # Example of how to set the node color based on an attribute files that has been loaded.   
128    # server.Cytoscape.discreteMapper(netid, 'default', 'NodeType', 'Node Color', '#000000',
129    #        ['inout','input','network','target'],
130    #        ['#00d300', '#00d300', '#00d300','#aa0000']
131    #)
132
133def usage():
134    print   "LoadNetworks.py, a tool to upload data to Cytoscape using the CytoscapeRPC plugin. " + \
135            "It can load sif, noa and eda files. " + "\n\n" + \
136            "Usage: python <port number of CytoscapeRPC> <directory with files> <Network name prefix>"
137
138if __name__ == '__main__':
139    if len(sys.argv) < 4:
140        usage()
141        exit(0)
142    run()
Note: See TracBrowser for help on using the repository browser.