Ejemplo n.º 1
0
def network_force_directed_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": 500
    }, {
        "name": "numIterationsEdgeRepulsive",
        "value": 500
    }]
    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)

    # 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
Ejemplo n.º 2
0
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)
Ejemplo n.º 3
0
    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
Ejemplo n.º 4
0
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)
Ejemplo n.º 5
0
 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')
Ejemplo n.º 6
0
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 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))
Ejemplo n.º 8
0
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)
Ejemplo n.º 9
0
    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())
Ejemplo n.º 10
0
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)
Ejemplo n.º 11
0
 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)
Ejemplo n.º 12
0
    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
Ejemplo n.º 13
0
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)
Ejemplo n.º 14
0
    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')
Ejemplo n.º 15
0
    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)
Ejemplo n.º 16
0
    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()
Ejemplo n.º 17
0
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)
Ejemplo n.º 18
0
 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()
Ejemplo n.º 19
0
 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)
Ejemplo n.º 20
0
class CytoscapeClient:
    """This is a wrapper to the py2cytoscape wrapper. The local installation of Py2cytoscape has been modified for it to work"""
    def __init__(self, host="localhost", port="1234", version="v1"):
        self.cy = CyRestClient(ip=host, port=port, version=version)

    def gc(self):
        self.cy.gc()

    def free_memory(self):
        self.cy.gc()
        X = self.cy.status()
        return max(
            X['memoryStatus']['maxMemory'] - X['memoryStatus']['usedMemory'],
            X['memoryStatus']['freeMemory'])

    def random_id(self, prefix="MY_"):
        import random
        s = "ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"
        return prefix + ''.join(
            [s[random.randint(0,
                              len(s) - 1)] for i in range(10)])

    def cynet_from_xgmml(self,
                         s_file,
                         name=None,
                         s_layout="force-directed",
                         l_bundle=True,
                         t_xy=None,
                         l_digraph=False):
        """If t_xy is provided, s_layout is ignored
        return CyNetwork"""
        import os
        if not os.path.exists(s_file):
            import util
            util.warn_msg('Missing file: %s' % s_file)
            return None
        if not l_digraph:
            net = xgmml.Network(s_file, name=name)
        else:
            import digraph
            net = digraph.Digraph(s_file, name=name)
        if t_xy is not None:
            net.set_XY(t_xy)
            s_layout = None
        S = net.T_node.header()
        #print "---------------->", S
        #S=[x for x in S if x not in ('Gene','Name','Symbol')]
        #net.T_node.drop(S, axis=1, inplace=True)
        ##############################
        return self.cynet_from_network(net,
                                       name=name,
                                       s_layout=s_layout,
                                       l_bundle=l_bundle)

    def cynet_from_network(self,
                           net,
                           name=None,
                           s_layout="force-directed",
                           l_bundle=True):
        """Input net: xgmml.Network object
        return CyNetwork"""
        #print "====>>>>>>>>", net.T_node.header()
        data = net.to_json()
        if name is None:
            name = data['data']['name']
        #cynet=self.cy.create(suid=net)
        cynet = None
        for trial in range(
                3):  # something Cytoscape errors, try up to three times
            try:
                if cynet is None:
                    cynet = self.cy.network.create(name=name, data=data)
            except:
                cynet = None
                print("Fail at trail %d" % (trial + 1))
                print("JSON data>", data)
        if cynet is None:
            import sys
            util.warn_msg('Error during plot_go_network(): %s' %
                          sys.exc_info()[0])
            print(traceback.format_exc())

        id = cynet.get_id()

        if s_layout is not None:
            #print "apply layout %s" % s_layout
            self.cy.layout.apply(name=s_layout, network=cynet)
        if l_bundle:
            self.cy.edgebundling.apply(cynet)
            #print "apply bundle %s" % s_layout
        self.cy.layout.fit(cynet)
        return cynet

    def delete_cynet(self, cynet=None):
        """None means delete all networks"""
        if cynet is None:
            self.cy.network.delete_all()
        else:
            self.cy.network.delete(cynet)

    def get_network(self, suid):
        """Get xgmml.Network with X,Y coordinates"""
        cynet = self.cy.network.create(suid=suid)
        net = xgmml.Network.from_json(cynet.to_json())
        net.T_node.drop([
            x for x in ['graphics_x', 'graphics_y', 'SUID', 'id_original']
            if x in net.T_node.header()
        ],
                        axis=1,
                        inplace=True)
        t_xy = self.cynet_get_XY(cynet)
        if t_xy is not None:
            t_xy.drop('Gene', axis=1, inplace=True)
            t_xy.rename2({'x': 'graphics_x', 'y': 'graphics_y'})
            net.T_node = net.T_node.merge(t_xy,
                                          left_on='id',
                                          right_on='id',
                                          how='left')
        return net

    def get_cynet(self, cynet):
        """make sure we return a cynet object"""
        if type(cynet) in (str, int):
            return self.cy.network.create(suid=int(cynet))
        return cynet

    def cynet_get_XY(self, cynet):
        cynet = self.get_cynet(cynet)
        data = cynet.get_first_view()
        if data is None: return None  # view does not exist
        nodes = data['elements']['nodes']
        X = []
        for node in nodes:
            # id is an internal id, Gene is our key
            X.append({
                'id': str(node['data']['id']),
                'x': node['position']['x'],
                'y': node['position']['y'],
                'Gene': node['data']['Gene']
            })
        t_xy = pd.DataFrame(X)
        return t_xy

    def cynet_save(self, cynet, s_file="x.png"):
        def save_image(s_file, data):
            f = open(s_file, 'wb')
            f.write(data)
            f.close()

        cynet = self.get_cynet(cynet)
        s_ext = s_file.upper()
        if s_ext.endswith('.PNG'):
            save_image(s_file, cynet.get_png())
        elif s_ext.endswith('.PDF'):
            save_image(s_file, cynet.get_pdf())
Ejemplo n.º 21
0
 def setUp(self):
     self.client = CyRestClient()
     # cleanup
     self.client.network.delete_all()
Ejemplo n.º 22
0
class CyRestClientTests(unittest.TestCase):

    def setUp(self):
        self.client = CyRestClient()
        # cleanup
        self.client.network.delete_all()

    def test_cyrest_client(self):
        print('\n---------- Client status tests start -----------\n')
        # Make sure CyREST server is running
        status = self.client.status()
        self.assertIsNotNone(status)
        pp(status)
        self.assertEqual('v1', status['apiVersion'])

        print('\n---------- Client status tests finished! -----------\n')

    def test_create_network(self):
        print('\n---------- Create network Tests Start -----------\n')
        # Create empty network
        num_networks = 5
        for i in range(num_networks):
            self.client.network.create()

        networks = self.client.network.get_all()
        self.assertIsNotNone(networks)
        self.assertEqual(num_networks, len(networks))

    def test_create_from(self):
        print('\n---------- Loading network tests start -----------\n')
        # Create from URL
        locations = [
            'http://chianti.ucsd.edu/cytoscape-data/galFiltered.sif',
            'http://www.ebi.ac.uk/Tools/webservices/psicquic/intact/'
            + 'webservices/current/search/interactor/brca2_human?format=xml25'

        ]

        networks = self.client.network.create_from(locations)
        print(networks)
        self.assertIsNotNone(networks)
        print('---------- Loading networks done! -----------\n')

    def test_network_api(self):
        print('\n---------- Network API Tests Start -----------\n')
        # Create empty network
        for i in range(5):
            self.client.network.create()

        networks = self.client.network.get_all(format='json')
        self.assertIsNotNone(networks)
        pp(networks)

    def test_cynetwork(self):
        print('\n---------- CyNetwork Tests Start -----------\n')
        network = self.client.network.create()
        self.assertIsNotNone(network)
        nodes = network.get_nodes()
        pp(nodes)
        new_nodes = ['a', 'b', 'c']
        nd = network.add_nodes(new_nodes)

        self.assertIsNotNone(nd)
        pp(nd)

        edge = network.add_edge(nd['a'], nd['b'])
        self.assertIsNotNone(edge)
        print(edge)

        new_edges = ((nd['a'], nd['b'], 'i1'), (nd['a'], nd['c'], 'i1'))
        new_edges_result = network.add_edges(new_edges)
        print(new_edges_result)
        self.assertEqual(2, len(new_edges_result))

        node_table = network.get_node_table()
        print(node_table)
        node_table = network.get_node_table(format='tsv')
        print(node_table)
        node_table = network.get_node_table(format='csv')
        print(node_table)

        edge_table = network.get_edge_table()
        print(edge_table)

        print('\n---------- CyNetwork Tests Finished! -----------\n')

    def test_create_view(self):
        print('\n---------- CyNetworkView Tests Start -----------\n')
        network = self.client.network.create()
        self.assertIsNotNone(network)
        nodes = network.get_nodes()
        pp(nodes)
        new_nodes = ['a', 'b', 'c']
        nd = network.add_nodes(new_nodes)
        views = network.get_views()
        print('Views: ')
        print(views)
        view_id = views[0]
        view = network.get_view(view_id, format='view')
        self.assertIsNotNone(view)
        self.assertEqual(view_id, view.get_id())

        node_views = view.get_node_views()
        self.assertIsNotNone(node_views)
        self.assertEqual(3, len(node_views))

        view1 = node_views[0]
        self.assertIsNotNone(view1)
        all_values = view1.get_values()
        print(all_values)

    def test_view_api(self):
        print('\n---------- View API test start -----------\n')
        network = self.client.network.create()
        self.assertIsNotNone(network)
        nodes = network.get_nodes()
        pp(nodes)
        new_nodes = ['a', 'b', 'c']
        nd = network.add_nodes(new_nodes)
        print(nd)
        views = network.get_views()
        print('Views: ')
        print(views)
        view_id = views[0]
        view = network.get_view(view_id, format='view')
        self.assertIsNotNone(view)
        self.assertEqual(view_id, view.get_id())

        node_views = view.get_node_views()
        self.assertIsNotNone(node_views)
        self.assertEqual(3, len(node_views))

        view1 = node_views[0]
        self.assertIsNotNone(view1)
        self.assertEqual(0, view1.get_x())
        view1.set_x(100)
        self.assertEqual(100, view1.get_value('NODE_X_LOCATION'))

        new_values = {}
        for key in nd.keys():
            suid = nd[key]
            new_values[suid] = 'red'

        view.update_node_views('NODE_FILL_COLOR', new_values)

        new_values_name = {}
        for node_name in new_nodes:
            new_values_name[node_name] = 'pink'

        print('---------- New Fill colors -----------')
        print(new_values_name)

        view.update_node_views('NODE_FILL_COLOR', new_values_name, key_type='name')
        view.update_network_view('NETWORK_BACKGROUND_PAINT', 'red')
        net_view = view.get_network_view_as_dict()
        bg_paint = net_view['NETWORK_BACKGROUND_PAINT']
        self.assertEqual('#FF0000', bg_paint)

    def test_convert(self):
        print('\n---------- DataFrame Conversion Tests Start -----------\n')

        import os
        import pandas as pd

        # Clean up Cytoscape session
        self.client.session.delete()

        dir_name = os.path.dirname(os.path.realpath(__file__))
        df = pd.read_csv(
            dir_name + '/data/galFiltered.sif',
            names=['source', 'interaction', 'target'], sep=' ')
        print(df.head(3))
        net = df_util.from_dataframe(df)

        network = self.client.network.create(data=net, name='Created from DataFrame')

        original_column_count = len(network.get_node_columns())

        dir_name = os.path.dirname(os.path.realpath(__file__))
        file_name = dir_name + '/data/galFiltered.nodeAttrTable.txt'
        data_table = pd.read_csv(file_name, sep='\t')

        network.update_node_table(df=data_table, data_key_col='ID')
        table_column_count = len(data_table.columns)
        total_column_count = len(network.get_node_columns())

        self.assertEqual(total_column_count, (original_column_count+table_column_count-1))

        print('\n---------- DataFrame Conversion Tests Finished! -----------\n')

    def test_delete_network(self):
        network = self.client.network.create()
        suids = self.client.network.get_all()
        self.assertEqual(1, len(suids))
        self.client.network.delete(network)
        suids = self.client.network.get_all()
        self.assertEqual(0, len(suids))

    def test_create_from_networkx(self):
        networkx1 = nx.scale_free_graph(100)

        network = self.client.network.create_from_networkx(networkx1)
        self.assertIsNotNone(network)
Ejemplo n.º 23
0
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)
Ejemplo n.º 24
0
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")
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")
"""
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())
Ejemplo n.º 27
0
 def setUp(self):
     self.client = CyRestClient()
     # cleanup
     self.client.network.delete_all()
Ejemplo n.º 28
0
 def __init__(self, host="localhost", port="1234", version="v1"):
     self.cy = CyRestClient(ip=host, port=port, version=version)
Ejemplo n.º 29
0
g = Graph.Read_Adjacency('r_data_science_ch2_fig2.1.txt')
g.get_adjacency()
type(g.get_adjacency())
g.get_adjacency()._get_data()
type(g.get_adjacency()._get_data())
type(g.get_adjacency().data)
g.get_adjacency().data
g.get_adjacency()._hash_()
g.get_adjacency().__hash__()
g.get_adjacency().__hash__(h)
g.get_adjacency().__hash__(g)
g.get_adjacency().shape
pip install py2cytoscape
import json
from py2cytoscape.data.cyrest_client import CyRestClient
cy = CyRestClient()
print(json.dumps(cy.status(), indent=4))
from igraph import *
g = Graph.Read_Adjacency('r_data_science_ch2_fig2.1.txt')
cy.network.create_from_igraph(g)
help(Graph.Read_GML)
from lesmis import *
loadGraphFromGml()
g
from lesmis import LesMis as lm
lm._g
from lesmis import LesMis as lm
lm.getGraph()
from lesmis import LesMis as lm
from lesmis import LesMis
lm = LesMis()
Ejemplo n.º 30
0
def get_client():
    """Initialises connection with Cytoscape and returns client."""
    return CyRestClient()
Ejemplo n.º 31
0
    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
Ejemplo n.º 32
0
class CyRestClientTests(unittest.TestCase):

    def setUp(self):
        self.client = CyRestClient()
        # cleanup
        self.client.network.delete_all()

    def test_cyrest_client(self):
        print('\n---------- Client status tests start -----------\n')
        # Make sure CyREST server is running
        status = self.client.status()
        self.assertIsNotNone(status)
        pp(status)
        self.assertEqual('v1', status['apiVersion'])

        print('\n---------- Client status tests finished! -----------\n')

    def test_create_network(self):
        print('\n---------- Create network Tests Start -----------\n')
        # Create empty network
        num_networks = 5
        for i in range(num_networks):
            self.client.network.create()

        networks = self.client.network.get_all()
        self.assertIsNotNone(networks)
        self.assertEqual(num_networks, len(networks))

    def test_create_from(self):
        print('\n---------- Loading network tests start -----------\n')
        # Create from URL
        locations = [
            'http://chianti.ucsd.edu/cytoscape-data/galFiltered.sif',
            'http://www.ebi.ac.uk/Tools/webservices/psicquic/intact/'
            + 'webservices/current/search/interactor/brca2_human?format=xml25'

        ]

        networks = self.client.network.create_from(locations)
        print(networks)
        self.assertIsNotNone(networks)
        print('---------- Loading networks done! -----------\n')

    def test_network_api(self):
        print('\n---------- Network API Tests Start -----------\n')
        # Create empty network
        for i in range(5):
            self.client.network.create()

        networks = self.client.network.get_all(format='json')
        self.assertIsNotNone(networks)
        pp(networks)

    def test_cynetwork(self):
        print('\n---------- CyNetwork Tests Start -----------\n')
        network = self.client.network.create()
        self.assertIsNotNone(network)
        nodes = network.get_nodes()
        pp(nodes)
        new_nodes = ['a', 'b', 'c']
        nd = network.add_nodes(new_nodes)

        self.assertIsNotNone(nd)
        pp(nd)

        edge = network.add_edge(nd['a'], nd['b'])
        self.assertIsNotNone(edge)
        pp(edge)

        new_edges = ((nd['a'], nd['b'], 'i1'), (nd['a'], nd['c'], 'i1'))
        new_edges_result = network.add_edges(new_edges)
        print(new_edges_result)
        self.assertEqual(2, len(new_edges_result))

        node_table = network.get_node_table()
        print(node_table)
        node_table = network.get_node_table(format='tsv')
        print(node_table)
        node_table = network.get_node_table(format='csv')
        print(node_table)

        edge_table = network.get_edge_table()
        print(edge_table)

        print('\n---------- CyNetwork Tests Finished! -----------\n')

    def test_convert(self):
        print('\n---------- DataFrame Conversion Tests Start -----------\n')

        import os
        import pandas as pd

        # Clean up Cytoscape session
        self.client.session.delete()

        dir_name = os.path.dirname(os.path.realpath(__file__))
        df = pd.read_csv(
            dir_name + '/data/galFiltered.sif',
            names=['source', 'interaction', 'target'], sep=' ')
        print(df.head(3))
        net = df_util.from_dataframe(df)

        network = self.client.network.create(data=net, name='Created from DataFrame')

        original_column_count = len(network.get_node_columns())

        dir_name = os.path.dirname(os.path.realpath(__file__))
        file_name = dir_name + '/data/galFiltered.nodeAttrTable.txt'
        data_table = pd.read_csv(file_name, sep='\t')

        network.update_node_table(df=data_table, data_key_col='ID')
        table_column_count = len(data_table.columns)
        total_column_count = len(network.get_node_columns())

        self.assertEqual(total_column_count, (original_column_count+table_column_count-1))

        print('\n---------- DataFrame Conversion Tests Finished! -----------\n')

    def test_delete_network(self):
        network = self.client.network.create()
        suids = self.client.network.get_all()
        self.assertEqual(1, len(suids))
        self.client.network.delete(network)
        suids = self.client.network.get_all()
        self.assertEqual(0, len(suids))

    def test_create_from_networkx(self):
        networkx1 = nx.scale_free_graph(100)

        network = self.client.network.create_from_networkx(networkx1)
        self.assertIsNotNone(network)
Ejemplo n.º 33
0
class CyRestClientTests(unittest.TestCase):
    def setUp(self):
        self.client = CyRestClient()
        # cleanup
        self.client.network.delete_all()

    def test_cyrest_client(self):
        print('\n---------- Client status tests start -----------\n')
        # Make sure CyREST server is running
        status = self.client.status()
        self.assertIsNotNone(status)
        pp(status)
        self.assertEqual('v1', status['apiVersion'])

        print('\n---------- Client status tests finished! -----------\n')

    def test_create_network(self):
        print('\n---------- Create network Tests Start -----------\n')
        # Create empty network
        num_networks = 5
        for i in range(num_networks):
            self.client.network.create()

        networks = self.client.network.get_all()
        self.assertIsNotNone(networks)
        self.assertEqual(num_networks, len(networks))

    def test_create_from(self):
        print('\n---------- Loading network tests start -----------\n')
        # Create from URL
        locations = [
            'http://chianti.ucsd.edu/cytoscape-data/galFiltered.sif',
            'http://www.ebi.ac.uk/Tools/webservices/psicquic/intact/' +
            'webservices/current/search/interactor/brca2_human?format=xml25'
        ]

        networks = self.client.network.create_from(locations)
        print(networks)
        self.assertIsNotNone(networks)
        print('---------- Loading networks done! -----------\n')

    def test_network_api(self):
        print('\n---------- Network API Tests Start -----------\n')
        # Create empty network
        for i in range(5):
            self.client.network.create()

        networks = self.client.network.get_all(format='json')
        self.assertIsNotNone(networks)
        pp(networks)

    def test_cynetwork(self):
        print('\n---------- CyNetwork Tests Start -----------\n')
        network = self.client.network.create()
        self.assertIsNotNone(network)
        nodes = network.get_nodes()
        pp(nodes)
        new_nodes = ['a', 'b', 'c']
        nd = network.add_nodes(new_nodes)

        self.assertIsNotNone(nd)
        pp(nd)

        edge = network.add_edge(nd['a'], nd['b'])
        self.assertIsNotNone(edge)
        pp(edge)

        new_edges = ((nd['a'], nd['b'], 'i1'), (nd['a'], nd['c'], 'i1'))
        new_edges_result = network.add_edges(new_edges)
        print(new_edges_result)
        self.assertEqual(2, len(new_edges_result))

        node_table = network.get_node_table()
        print(node_table)
        node_table = network.get_node_table(format='tsv')
        print(node_table)
        node_table = network.get_node_table(format='csv')
        print(node_table)

        edge_table = network.get_edge_table()
        print(edge_table)

        print('\n---------- CyNetwork Tests Finished! -----------\n')

    def test_create_view(self):
        print('\n---------- CyNetworkView Tests Start -----------\n')
        network = self.client.network.create()
        self.assertIsNotNone(network)
        nodes = network.get_nodes()
        pp(nodes)
        new_nodes = ['a', 'b', 'c']
        nd = network.add_nodes(new_nodes)
        views = network.get_views()
        print('Views: ')
        print(views)
        view_id = views[0]
        view = network.get_view(view_id, format='view')
        self.assertIsNotNone(view)
        self.assertEqual(view_id, view.get_id())

        node_views = view.get_node_views()
        self.assertIsNotNone(node_views)
        self.assertEqual(3, len(node_views))

        view1 = node_views[0]
        self.assertIsNotNone(view1)
        all_values = view1.get_values()
        print(all_values)

    def test_view_api(self):
        print('\n---------- View API test start -----------\n')
        network = self.client.network.create()
        self.assertIsNotNone(network)
        nodes = network.get_nodes()
        pp(nodes)
        new_nodes = ['a', 'b', 'c']
        nd = network.add_nodes(new_nodes)
        print(nd)
        views = network.get_views()
        print('Views: ')
        print(views)
        view_id = views[0]
        view = network.get_view(view_id, format='view')
        self.assertIsNotNone(view)
        self.assertEqual(view_id, view.get_id())

        node_views = view.get_node_views()
        self.assertIsNotNone(node_views)
        self.assertEqual(3, len(node_views))

        view1 = node_views[0]
        self.assertIsNotNone(view1)
        self.assertEqual(0, view1.get_x())
        view1.set_x(100)
        self.assertEqual(100, view1.get_value('NODE_X_LOCATION'))

        new_values = {}
        for key in nd.keys():
            suid = nd[key]
            new_values[suid] = 'red'

        view.update_node_views('NODE_FILL_COLOR', new_values)

        new_values_name = {}
        for node_name in new_nodes:
            new_values_name[node_name] = 'pink'

        view.update_node_views('NODE_FILL_COLOR',
                               new_values_name,
                               key_type='name')
        view.update_network_view('NETWORK_BACKGROUND_PAINT', 'red')
        net_view = view.get_network_view_as_dict()
        bg_paint = net_view['NETWORK_BACKGROUND_PAINT']
        self.assertEqual('#FF0000', bg_paint)

    def test_convert(self):
        print('\n---------- DataFrame Conversion Tests Start -----------\n')

        import os
        import pandas as pd

        # Clean up Cytoscape session
        self.client.session.delete()

        dir_name = os.path.dirname(os.path.realpath(__file__))
        df = pd.read_csv(dir_name + '/data/galFiltered.sif',
                         names=['source', 'interaction', 'target'],
                         sep=' ')
        print(df.head(3))
        net = df_util.from_dataframe(df)

        network = self.client.network.create(data=net,
                                             name='Created from DataFrame')

        original_column_count = len(network.get_node_columns())

        dir_name = os.path.dirname(os.path.realpath(__file__))
        file_name = dir_name + '/data/galFiltered.nodeAttrTable.txt'
        data_table = pd.read_csv(file_name, sep='\t')

        network.update_node_table(df=data_table, data_key_col='ID')
        table_column_count = len(data_table.columns)
        total_column_count = len(network.get_node_columns())

        self.assertEqual(total_column_count,
                         (original_column_count + table_column_count - 1))

        print(
            '\n---------- DataFrame Conversion Tests Finished! -----------\n')

    def test_delete_network(self):
        network = self.client.network.create()
        suids = self.client.network.get_all()
        self.assertEqual(1, len(suids))
        self.client.network.delete(network)
        suids = self.client.network.get_all()
        self.assertEqual(0, len(suids))

    def test_create_from_networkx(self):
        networkx1 = nx.scale_free_graph(100)

        network = self.client.network.create_from_networkx(networkx1)
        self.assertIsNotNone(network)