def test_two_node_one_edge_network(self):
        net = NiceCXNetwork()
        net.create_node('first')
        net.create_node('second')
        net.create_edge(edge_source=0, edge_target=1)
        net.set_name('bob')
        fac = DefaultNetworkXFactory()
        g = fac.get_graph(net)
        self.assertEqual('bob', g.graph['name'])
        self.assertEqual(2, len(g))
        self.assertEqual(1, g.number_of_edges())
        self.assertTrue(0 in g)

        if float(networkx.__version__) >= 2:
            nodelist = list(g.nodes(data=True))
            edgelist = list(g.edges(data=True))
        else:
            nodelist = g.nodes(data=True)
            edgelist = g.edges(data=True)

        self.assertEqual('first', nodelist[0][1]['name'])
        self.assertEqual('second', nodelist[1][1]['name'])
        self.assertEqual(0, edgelist[0][0])
        self.assertEqual(1, edgelist[0][1])
        self.assertEqual(None, edgelist[0][2]['interaction'])
    def test_add_member_genes(self):

        net = NiceCXNetwork()
        aid = net.create_node('a')
        net.set_node_attribute(aid, NodeMemberUpdator.TYPE, 'proteinfamily')

        notinid = net.create_node('x')
        net.set_node_attribute(notinid, NodeMemberUpdator.TYPE,
                               'proteinfamily')

        mock = GeneSymbolSearcher(bclient=None)
        mock.get_symbol = MagicMock(side_effect=['', None])
        updator = NodeMemberUpdator(None, None, genesearcher=mock)

        aidnode = net.get_node(aid)
        res = updator._add_member_genes(net, aidnode, [])
        self.assertEqual(['No proteins obtained for node: ' + str(aidnode)],
                         res)

        notinidnode = net.get_node(notinid)
        res = updator._add_member_genes(net, notinidnode, ['x'])
        self.assertTrue('For node ' + str(notinidnode) +
                        ' No gene symbol found for x. Skipping.' in res)

        self.assertTrue('Not a single gene symbol found. Skipping insertion '
                        'of member attribute for node ' +
                        str(notinidnode) in res)
Exemplo n.º 3
0
def get_nice_cx_network_from_clusterfile(inputfile):
    """

    :param inputfile:
    :return:
    """
    network = NiceCXNetwork()
    network.set_name('clustertocx from ' + str(os.path.basename(os.path.dirname(inputfile))))
    with open(inputfile, 'r') as f:
        data = f.read()

    node_map = {}
    protein_map = {}
    for line in data.split(';'):
        slist = line.split(',')
        if len(slist) != 3:
            sys.stderr.write(line + ' does not have appropriate number of columns. skipping\n')
            continue

        if slist[2].startswith('c-c'):
            target_is_protein = False
        else:
            target_is_protein = True

        if slist[0] not in node_map:
            source_node_id = network.create_node(slist[0])
            node_map[slist[0]] = source_node_id
            network.add_node_attribute(property_of=source_node_id, name='suid', values=int(slist[0]), type='long')
            network.add_node_attribute(property_of=source_node_id, name='type', values='term', type='string')
        else:
            source_node_id = node_map[slist[0]]

        if target_is_protein:
            if slist[0] not in protein_map:
                protein_map[slist[0]] = set()
                protein_map[slist[0]].add(slist[1])
            else:
                if slist[1] not in protein_map[slist[0]]:
                    protein_map[slist[0]].add(slist[1])
        else:
            target_node_id = network.create_node(slist[1])
            network.create_edge(source_node_id, target_node_id, 'Child-Parent')
            network.add_node_attribute(property_of=target_node_id, name='suid', values=int(slist[1]), type='long')
            network.add_node_attribute(property_of=target_node_id, name='type', values='term', type='string')
            node_map[slist[1]] = target_node_id

    for nodename in protein_map:
        genelist = protein_map[nodename]
        if len(genelist) > 0:
            genesymbol_list = []
            for entry in genelist:
                genesymbol_list.append(entry)
            network.add_node_attribute(property_of=node_map[nodename], name='member', values=genesymbol_list,
                                       type='list_of_string')
            network.add_node_attribute(property_of=node_map[nodename], name='type', values='complex', type='string',
                                       overwrite=True)
    del node_map
    del protein_map

    return network
    def test_add_edge_to_network_using_src_target_node_ids(self):
        net = NiceCXNetwork()
        src_node = net.create_node('node1')
        target_node = net.create_node('node2')

        ne = NetworkEdge(edge_id=1,
                         source_node_id=src_node,
                         target_node_id=target_node,
                         interaction='activates')

        self.assertEqual(0, len(net.get_edges()))
        edge_id = ne.add_edge_to_network(net_cx=net)
        self.assertEqual(1, len(net.get_edges()))

        nef = NetworkEdgeFactory()
        new_ne = nef.get_network_edge_from_network(net_cx=net, edge_id=edge_id)
        self.assertEqual('node1', new_ne.get_source_node_name())
        self.assertEqual('node2', new_ne.get_target_node_name())
        self.assertEqual(src_node, new_ne.get_source_node_id())
        self.assertEqual(target_node, new_ne.get_target_node_id())
        self.assertEqual('activates', new_ne.get_interaction())

        self.assertEqual([], new_ne.get_attributes())
        new_ne.remove_edge_from_network(net_cx=net)
        self.assertEqual(0, len(net.get_edges()))
Exemplo n.º 5
0
 def test_update_to_success(self):
     with requests_mock.mock() as m:
         resurl = client.DEFAULT_SERVER + '/v2/network/asdf'
         m.get(self.get_rest_admin_status_url(),
               json=self.get_rest_admin_status_dict("2.4.0"))
         m.put(client.DEFAULT_SERVER + '/v2/network/abcd',
               request_headers={'Connection': 'close'},
               status_code=1,
               text=resurl)
         net = NiceCXNetwork()
         net.create_node('bob')
         res = net.update_to('abcd', client.DEFAULT_SERVER,
                             'bob', 'warnerbrandis',
                             user_agent='jeez')
         self.assertEqual(res, resurl)
         decode_txt = m.last_request.text.read().decode('UTF-8')
         self.assertEqual(m.last_request.headers['User-Agent'],
                          client.userAgent + ' jeez')
         self.assertTrue('Content-Disposition: form-data; name='
                         '"CXNetworkStream"; filename='
                         '"filename"' in decode_txt)
         self.assertTrue('Content-Type: application/'
                         'octet-stream' in decode_txt)
         self.assertTrue('{"nodes": [{' in decode_txt)
         self.assertTrue('"@id": 0' in decode_txt)
         self.assertTrue('"n": "bob"' in decode_txt)
         self.assertTrue('"r": "bob"' in decode_txt)
         self.assertTrue('{"status": [{"' in decode_txt)
         self.assertTrue('"error": ""' in decode_txt)
         self.assertTrue('"success": true' in decode_txt)
Exemplo n.º 6
0
    def test_simple_create(self):
        niceCx_creatures = NiceCXNetwork()
        niceCx_creatures.set_name("Food Web")
        fox_node = niceCx_creatures.create_node(node_name='Fox')
        mouse_node = niceCx_creatures.create_node(node_name='Mouse')
        bird_node = niceCx_creatures.create_node(node_name='Bird')

        fox_bird_edge = niceCx_creatures.create_edge(
            edge_source=fox_node,
            edge_target=bird_node,
            edge_interaction='interacts-with')

        fox_mouse_edge = niceCx_creatures.create_edge(
            edge_source=fox_node,
            edge_target=mouse_node,
            edge_interaction='interacts-with')

        niceCx_creatures.add_node_attribute(property_of=fox_node,
                                            name='Color',
                                            values='Red')

        niceCx_creatures.add_node_attribute(property_of=mouse_node,
                                            name='Color',
                                            values='Gray')

        niceCx_creatures.add_node_attribute(property_of=bird_node,
                                            name='Color',
                                            values='Blue')

        niceCx_creatures.add_edge_attribute(property_of=fox_mouse_edge,
                                            name='Hunted',
                                            values='On the ground')

        print(niceCx_creatures.get_node_attribute(fox_node, 'Color'))
Exemplo n.º 7
0
    def test_two_node_one_edge_network(self):
        net = NiceCXNetwork()
        net.create_node('first')
        net.create_node('second')
        net.create_edge(edge_source=0, edge_target=1)
        net.set_name('bob')
        fac = DefaultNetworkXFactory()
        g = fac.get_graph(net)
        self.assertEqual('bob', g.graph['name'])
        self.assertEqual(2, len(g))
        self.assertEqual(1, g.number_of_edges())
        self.assertTrue(0 in g)

        if NETWORKX_MAJOR_VERSION >= 2:
            nodelist = list(g.nodes(data=True))
            edgelist = list(g.edges(data=True))
        else:
            nodelist = g.nodes(data=True)
            edgelist = g.edges(data=True)

        self.assertEqual('first', nodelist[0][1]['name'])
        self.assertEqual('second', nodelist[1][1]['name'])
        self.assertEqual(0, edgelist[0][0])
        self.assertEqual(1, edgelist[0][1])
        self.assertEqual(None, edgelist[0][2]['interaction'])
Exemplo n.º 8
0
 def test_context(self):
     niceCx_creatures = NiceCXNetwork()
     niceCx_creatures.set_name("Test")
     niceCx_creatures.create_node(node_name="Fox")
     try:
         self.assertRaises(Exception, niceCx_creatures.set_context("hkjhnk"))
     except Exception as e:
         print('Bad context exception was caught')
Exemplo n.º 9
0
 def test_context(self):
     niceCx_creatures = NiceCXNetwork()
     niceCx_creatures.set_name("Test")
     niceCx_creatures.create_node(node_name="Fox")
     try:
         self.assertRaises(Exception, niceCx_creatures.set_context("hkjhnk"))
     except Exception as e:
         print('Bad context exception was caught')
Exemplo n.º 10
0
    def test_add_bad_net_attrs(self):
        niceCx_creatures = NiceCXNetwork()
        niceCx_creatures.set_name("Test")
        niceCx_creatures.create_node(node_name="Fox")
        niceCx_creatures.set_network_attribute(name="version", values="1.0")
        print(niceCx_creatures)
        upload_message = niceCx_creatures.upload_to(upload_server, upload_username, upload_password)

        self.assertTrue(upload_message)
Exemplo n.º 11
0
 def test_to_networkx_simple_graph_default_mode(self):
     net = NiceCXNetwork(mode='default')
     net.set_name('mynetwork')
     net.create_node('node0')
     net.create_node('node1')
     net.create_edge(edge_source=0, edge_target=1)
     g = net.to_networkx()
     self.assertEqual(g.graph['name'], 'mynetwork')
     self.assertEqual(2, len(g))
Exemplo n.º 12
0
    def test_add_bad_net_attrs(self):
        niceCx_creatures = NiceCXNetwork()
        niceCx_creatures.set_name("Test")
        niceCx_creatures.create_node(node_name="Fox")
        niceCx_creatures.set_network_attribute(name="version", values="1.0")
        print(niceCx_creatures)
        upload_message = niceCx_creatures.upload_to(upload_server, upload_username, upload_password)

        self.assertTrue(upload_message)
Exemplo n.º 13
0
    def test__str__(self):
        net = NiceCXNetwork()
        self.assertEqual('nodes: 0 \n edges: 0', str(net))
        net.create_node('foo')
        self.assertEqual('nodes: 1 \n edges: 0', str(net))
        net.create_node('foo2')
        net.create_node('foo3')
        self.assertEqual('nodes: 3 \n edges: 0', str(net))

        net.create_edge(edge_source=0, edge_target=1)
        self.assertEqual('nodes: 3 \n edges: 1', str(net))
Exemplo n.º 14
0
    def test_update_network(self):
        client = self.get_ndex2_client()
        # create network and add it
        net = NiceCXNetwork()
        oneid = net.create_node('node1')
        twoid = net.create_node('node2')
        net.create_edge(oneid, twoid, 'hello')
        netname = 'ndex2-client integration test network' + str(datetime.now())
        net.set_name(netname)
        res = client.save_new_network(net.to_cx(), visibility='PRIVATE')
        try:
            self.assertTrue('http' in res)
            netid = re.sub('^.*/', '', res)

            netsum = client.get_network_summary(network_id=netid)
            self.assertEqual(netid, netsum['externalId'])
            self.assertEqual(netname, netsum['name'])
            self.assertEqual('PRIVATE', netsum['visibility'])
            self.assertEqual(False, netsum['isReadOnly'])
            self.assertEqual(1, netsum['edgeCount'])
            self.assertEqual(2, netsum['nodeCount'])
            self.assertEqual(False, netsum['isShowcase'])
            self.assertEqual('NONE', netsum['indexLevel'])

            net.create_node(node_name='hello', node_represents='something')
            net.create_node(node_name='hoho', node_represents='heheh')
            newnetname = 'update ' + netname
            self.assertEqual(4, len(net.get_nodes()))
            net.set_name(newnetname)
            if sys.version_info.major == 3:
                stream = io.BytesIO(json.dumps(net.to_cx(),
                                               cls=DecimalEncoder)
                                    .encode('utf-8'))
            else:
                stream = io.BytesIO(json.dumps(net.to_cx(),
                                               cls=DecimalEncoder))
            newres = client.update_cx_network(stream, netid)
            self.assertEqual('', newres)
            netsum = client.get_network_summary(network_id=netid)
            self.assertEqual(netid, netsum['externalId'])
            self.assertEqual(newnetname, netsum['name'])
            self.assertEqual('PRIVATE', netsum['visibility'])
            self.assertEqual(False, netsum['isReadOnly'])
            self.assertEqual(1, netsum['edgeCount'])
            self.assertEqual(4, netsum['nodeCount'])
            self.assertEqual(False, netsum['isShowcase'])
            self.assertEqual('NONE', netsum['indexLevel'])
        finally:
            client.delete_network(netid)
            try:
                client.get_network_as_cx_stream(netid)
                self.fail('Expected exception')
            except HTTPError:
                pass
Exemplo n.º 15
0
 def test_one_node_no_edge_network(self):
     net = NiceCXNetwork()
     net.create_node('first')
     net.set_name('bob')
     fac = LegacyNetworkXVersionTwoPlusFactory()
     g = fac.get_graph(net)
     self.assertEqual('bob', g.graph['name'])
     self.assertEqual(1, len(g))
     self.assertEqual(0, g.number_of_edges())
     self.assertTrue('first' in g)
     nodelist = g.nodes(data=True)
     self.assertEqual('first', nodelist['first']['represents'])
    def test_remove_edge_from_network(self):
        net = NiceCXNetwork()
        src_node = net.create_node('node1')
        target_node = net.create_node('node2')
        edge_id = net.create_edge(edge_source=src_node,
                                  edge_target=target_node)
        self.assertEqual(1, len(net.get_edges()))
        nef = NetworkEdgeFactory()
        ne = nef.get_network_edge_from_network(net_cx=net, edge_id=edge_id)

        ne.remove_edge_from_network(net_cx=net)
        self.assertEqual(0, len(net.get_edges()))
 def test_one_node_no_edge_network(self):
     net = NiceCXNetwork()
     net.create_node('first')
     net.set_name('bob')
     fac = LegacyNetworkXVersionTwoPlusFactory()
     g = fac.get_graph(net)
     self.assertEqual('bob', g.graph['name'])
     self.assertEqual(1, len(g))
     self.assertEqual(0, g.number_of_edges())
     self.assertTrue('first' in g)
     nodelist = g.nodes(data=True)
     self.assertEqual('first', nodelist['first']['represents'])
Exemplo n.º 18
0
 def test_one_node_no_edge_network(self):
     net = NiceCXNetwork()
     net.create_node('first')
     net.set_name('bob')
     fac = DefaultNetworkXFactory()
     g = fac.get_graph(net)
     self.assertEqual('bob', g.graph['name'])
     self.assertEqual(1, len(g))
     self.assertEqual(0, g.number_of_edges())
     self.assertTrue(0 in g)
     nodelist = g.nodes(data=True)
     if NETWORKX_MAJOR_VERSION >= 2:
         self.assertEqual('first', nodelist[0]['name'])
     else:
         self.assertEqual('first', nodelist[0][1]['name'])
 def test_one_node_no_edge_network(self):
     net = NiceCXNetwork()
     net.create_node('first')
     net.set_name('bob')
     fac = DefaultNetworkXFactory()
     g = fac.get_graph(net)
     self.assertEqual('bob', g.graph['name'])
     self.assertEqual(1, len(g))
     self.assertEqual(0, g.number_of_edges())
     self.assertTrue(0 in g)
     nodelist = g.nodes(data=True)
     if float(networkx.__version__) >= 2:
         self.assertEqual('first', nodelist[0]['name'])
     else:
         self.assertEqual('first', nodelist[0][1]['name'])
Exemplo n.º 20
0
    def test_update_network_with_empty_network(self):
        client = self.get_ndex2_client()
        # create network and add it
        net = NiceCXNetwork()
        oneid = net.create_node('node1')
        twoid = net.create_node('node2')
        net.create_edge(oneid, twoid, 'hello')
        netname = 'NiceCXNetwork upload_to() test network' + str(
            datetime.now())
        net.set_name(netname)
        creds = self.get_ndex_credentials_as_tuple()
        res = net.upload_to(creds['server'],
                            creds['user'],
                            creds['password'],
                            user_agent=creds['user_agent'])
        try:
            self.assertTrue('http' in res)
            netid = re.sub('^.*/', '', res)
            netsum = self.wait_for_network_to_be_ready(client, netid)
            self.assertIsNotNone(
                netsum, 'Network is still not ready,'
                ' maybe server is busy?')
            self.assertEqual(netid, netsum['externalId'])
            self.assertTrue('name' in netsum, msg=str(netsum))
            self.assertEqual(netname, netsum['name'], str(netsum))
            self.assertEqual('PRIVATE', netsum['visibility'])
            self.assertEqual(False, netsum['isReadOnly'])
            self.assertEqual(1, netsum['edgeCount'])
            self.assertEqual(2, netsum['nodeCount'])
            self.assertEqual(False, netsum['isShowcase'])
            self.assertEqual('NONE', netsum['indexLevel'])
            newnet = NiceCXNetwork()

            newres = newnet.update_to(netid,
                                      creds['server'],
                                      creds['user'],
                                      creds['password'],
                                      user_agent=creds['user_agent'])
            self.assertEqual('', newres)
            netsum = self.wait_for_network_to_be_ready(client,
                                                       netid,
                                                       num_retries=5,
                                                       retry_weight=1)
            self.assertIsNotNone(
                netsum, 'Network is still not ready,'
                ' maybe server is busy?')
            self.assertEqual(netid, netsum['externalId'])
            self.assertEqual('PRIVATE', netsum['visibility'])
            self.assertEqual(False, netsum['isReadOnly'])
            self.assertEqual(0, netsum['edgeCount'])
            self.assertEqual(0, netsum['nodeCount'])
            self.assertEqual(False, netsum['isShowcase'])
            self.assertEqual('NONE', netsum['indexLevel'])
        finally:
            client.delete_network(netid)
            try:
                client.get_network_as_cx_stream(netid)
                self.fail('Expected exception')
            except HTTPError:
                pass
Exemplo n.º 21
0
    def test_bad_node_attr(self):
        niceCx_creatures = NiceCXNetwork()
        niceCx_creatures.set_name("Test Network")
        fox_node = niceCx_creatures.create_node(node_name=453)
        niceCx_creatures.add_node_attribute(property_of=fox_node, name='Color', values=['Red',"tree"])

        upload_message = niceCx_creatures.upload_to(upload_server, upload_username, upload_password)
        self.assertTrue(upload_message)
Exemplo n.º 22
0
 def test_bad_nodes_add_edge(self):
     niceCx_creatures = NiceCXNetwork()
     niceCx_creatures.set_name("Test Network")
     node1_id = niceCx_creatures.create_node(node_name=324)
     node2_id = niceCx_creatures.create_node(node_name=453)
     niceCx_creatures.create_edge(edge_source=node1_id, edge_target=node2_id, edge_interaction=['inte'])
     upload_message = niceCx_creatures.upload_to(upload_server, upload_username, upload_password)
     self.assertTrue(upload_message)
    def test_one_node_no_edge_network_legacytrue(self):
        net = NiceCXNetwork()
        net.create_node('first')
        net.set_name('bob')
        fac = DefaultNetworkXFactory(legacymode=True)
        g = fac.get_graph(net)
        self.assertEqual('bob', g.graph['name'])
        self.assertEqual(1, len(g))
        self.assertEqual(0, g.number_of_edges())
        self.assertTrue(0 in g)

        if float(networkx.__version__) >= 2:
            nodelist = list(g.nodes(data=True))
        else:
            nodelist = g.nodes(data=True)

        self.assertEqual('first', nodelist[0][1]['name'])
Exemplo n.º 24
0
 def test_bad_nodes_add_edge(self):
     niceCx_creatures = NiceCXNetwork()
     niceCx_creatures.set_name("Test Network")
     node1_id = niceCx_creatures.create_node(node_name=324)
     node2_id = niceCx_creatures.create_node(node_name=453)
     niceCx_creatures.create_edge(edge_source=node1_id, edge_target=node2_id, edge_interaction=['inte'])
     upload_message = niceCx_creatures.upload_to(upload_server, upload_username, upload_password)
     self.assertTrue(upload_message)
Exemplo n.º 25
0
    def test_bad_node_attr(self):
        niceCx_creatures = NiceCXNetwork()
        niceCx_creatures.set_name("Test Network")
        fox_node = niceCx_creatures.create_node(node_name=453)
        niceCx_creatures.add_node_attribute(property_of=fox_node, name='Color', values=['Red',"tree"])

        upload_message = niceCx_creatures.upload_to(upload_server, upload_username, upload_password)
        self.assertTrue(upload_message)
 def test_update_no_nodes_start_with_uniprot(self):
     updater = UniProtToGeneSymbolUpdater()
     net = NiceCXNetwork()
     nodeone = net.create_node(node_name='node1', node_represents='node1')
     nodetwo = net.create_node(node_name='node2', node_represents='node2')
     res = updater.update(net)
     self.assertEqual(0, len(res))
     self.assertEqual('node1', net.get_node(nodeone)['n'])
     self.assertEqual('node2', net.get_node(nodetwo)['n'])
    def test_two_node_one_edge_network(self):
        net = NiceCXNetwork()
        net.create_node('first')
        net.create_node('second')
        net.create_edge(edge_source=0, edge_target=1)
        net.set_name('bob')
        fac = LegacyNetworkXVersionTwoPlusFactory()
        g = fac.get_graph(net)
        self.assertEqual('bob', g.graph['name'])
        self.assertEqual(2, len(g))
        self.assertEqual(1, g.number_of_edges())
        self.assertTrue('first' in g)
        self.assertTrue('second' in g)
        edgelist = list(g.edges(data=True))

        self.assertTrue(('first' == edgelist[0][0] and 'second' == edgelist[0][1]) or
                        ('second' == edgelist[0][0] and 'first' == edgelist[0][1]))
        self.assertEqual(None, edgelist[0][2]['interaction'])
Exemplo n.º 28
0
    def test_remove_node_from_network_no_edges_no_attrs(self):
        net = NiceCXNetwork()
        node_id = net.create_node('node1', node_represents='ha')
        nef = NetworkNodeFactory()
        nn = nef.get_network_node_from_network(net_cx=net, node_id=node_id)

        nn.remove_node_from_network(net_cx=net)

        self.assertEqual(0, len(net.get_nodes()))
Exemplo n.º 29
0
    def test_one_node_network(self):
        net = NiceCXNetwork()
        node_one = net.create_node('first')

        net.set_node_attribute(node_one,
                               'booleanattrib',
                               'false',
                               type='boolean')
        net.set_node_attribute(node_one, 'integerattrib', '1', type='integer')
        net.set_node_attribute(node_one, 'doubleattrib', '2.0', type='double')
        net.set_node_attribute(node_one, 'longattrib', '3', type='long')
        net.set_node_attribute(node_one,
                               'stringattrib',
                               'false',
                               type='string')

        net.set_node_attribute(node_one,
                               'list_of_booleanattrib', ['True'],
                               type='list_of_boolean')
        net.set_node_attribute(node_one,
                               'list_of_doubleattrib', ['4.0'],
                               type='list_of_double')
        net.set_node_attribute(node_one,
                               'list_of_integerattrib', ['5'],
                               type='list_of_integer')
        net.set_node_attribute(node_one,
                               'list_of_longattrib', ['6'],
                               type='list_of_long')
        net.set_node_attribute(node_one,
                               'list_of_stringattrib', ['false'],
                               type='list_of_string')

        net.set_name('bob')
        fac = DefaultNetworkXFactory()
        g = fac.get_graph(net)
        self.assertEqual('bob', g.graph['name'])
        self.assertEqual(1, len(g))
        self.assertEqual(0, g.number_of_edges())
        self.assertTrue(0 in g)

        if NETWORKX_MAJOR_VERSION >= 2:
            nodelist = list(g.nodes(data=True))
        else:
            nodelist = g.nodes(data=True)

        self.assertEqual('false', nodelist[0][1]['booleanattrib'])
        self.assertEqual('1', nodelist[0][1]['integerattrib'])
        self.assertEqual('2.0', nodelist[0][1]['doubleattrib'])
        self.assertEqual('3', nodelist[0][1]['longattrib'])
        self.assertEqual('false', nodelist[0][1]['stringattrib'])

        self.assertEqual(['True'], nodelist[0][1]['list_of_booleanattrib'])
        self.assertEqual(['4.0'], nodelist[0][1]['list_of_doubleattrib'])
        self.assertEqual(['5'], nodelist[0][1]['list_of_integerattrib'])
        self.assertEqual(['6'], nodelist[0][1]['list_of_longattrib'])
        self.assertEqual(['false'], nodelist[0][1]['list_of_stringattrib'])
Exemplo n.º 30
0
    def test_bad_edge_attr(self):
        niceCx_creatures = NiceCXNetwork()
        niceCx_creatures.set_name("Test Network")
        node1_id = niceCx_creatures.create_node(node_name=324)
        node2_id = niceCx_creatures.create_node(node_name=453)
        edge = niceCx_creatures.create_edge(edge_source=node1_id, edge_target=node2_id, edge_interaction='inte')
        niceCx_creatures.add_edge_attribute(property_of=edge, name= "djks", values= "jfkl")

        upload_message = niceCx_creatures.upload_to(upload_server, upload_username, upload_password)
        self.assertTrue(upload_message)
Exemplo n.º 31
0
    def test_bad_edge_attr(self):
        niceCx_creatures = NiceCXNetwork()
        niceCx_creatures.set_name("Test Network")
        node1_id = niceCx_creatures.create_node(node_name=324)
        node2_id = niceCx_creatures.create_node(node_name=453)
        edge = niceCx_creatures.create_edge(edge_source=node1_id, edge_target=node2_id, edge_interaction='inte')
        niceCx_creatures.add_edge_attribute(property_of=edge, name= "djks", values= "jfkl")

        upload_message = niceCx_creatures.upload_to(upload_server, upload_username, upload_password)
        self.assertTrue(upload_message)
    def test_two_node_one_edge_network(self):
        net = NiceCXNetwork()
        net.create_node('first')
        net.create_node('second')
        net.create_edge(edge_source=0, edge_target=1)
        net.set_name('bob')
        fac = LegacyNetworkXVersionTwoPlusFactory()
        g = fac.get_graph(net)
        self.assertEqual('bob', g.graph['name'])
        self.assertEqual(2, len(g))
        self.assertEqual(1, g.number_of_edges())
        self.assertTrue('first' in g)
        self.assertTrue('second' in g)
        edgelist = list(g.edges(data=True))

        self.assertTrue(
            ('first' == edgelist[0][0] and 'second' == edgelist[0][1])
            or ('second' == edgelist[0][0] and 'first' == edgelist[0][1]))
        self.assertEqual(None, edgelist[0][2]['interaction'])
Exemplo n.º 33
0
 def test_apply_cytoscape_layout_networks_not_in_dict(self):
     temp_dir = tempfile.mkdtemp()
     try:
         p = MagicMock()
         p.layout = 'grid'
         p.sifdir = temp_dir
         mockpy4 = MagicMock()
         mockpy4.import_network_from_file = MagicMock(return_value={})
         loader = NDExNciPidLoader(p, py4cyto=mockpy4)
         net = NiceCXNetwork()
         for x in range(10):
             net.create_node('node' + str(x))
         try:
             loader._apply_cytoscape_layout(net)
             self.fail('Expected NDExNciPidLoaderError')
         except NDExNciPidLoaderError as e:
             self.assertTrue(str(e).startswith('Error network view'))
     finally:
         shutil.rmtree(temp_dir)
Exemplo n.º 34
0
    def test_get_nodes(self):
        net = NiceCXNetwork()

        # Verify correct operation on empty network
        res = list(net.get_nodes())
        self.assertEqual(0, len(res))

        # add a node
        net.create_node('foo')
        res = list(net.get_nodes())
        self.assertEqual(1, len(res))
        self.assertEqual(res[0], (0, {'@id': 0, 'n': 'foo', 'r': 'foo'}))

        # add another node
        net.create_node('bar')
        res = list(net.get_nodes())
        self.assertEqual(2, len(res))
        self.assertEqual(res[0], (0, {'@id': 0, 'n': 'foo', 'r': 'foo'}))
        self.assertEqual(res[1], (1, {'@id': 1, 'n': 'bar', 'r': 'bar'}))
Exemplo n.º 35
0
    def test_upload_network_with_no_network_attributes(self):
        """
        So if one uploads a network with NO network attributes
        to NDEx and then edits the network (setting name visibility, description)
        via [updateNetworkSummary]	[/v2/network/6b89b286-e142-11ec-b397-0ac135e8bacf/summary
        the CX2 endpoint shows the changed network attributes, but the CX1
        is missing the network attributes
        :return:
        """
        client = self.get_ndex2_client()
        # create network and add it
        net = NiceCXNetwork()
        oneid = net.create_node('node1')
        twoid = net.create_node('node2')
        net.create_edge(oneid, twoid, 'hello')

        res = client.save_new_network(net.to_cx(), visibility='PRIVATE')
        try:
            self.assertTrue('http' in res)
            netid = re.sub('^.*/', '', res)
            netsum = self.wait_for_network_to_be_ready(client, netid)
            self.assertIsNotNone(
                netsum, 'Network is still not ready,'
                ' maybe server is busy?')
            self.assertEqual(netid, netsum['externalId'])
            self.assertTrue('name' not in netsum, msg=str(netsum))

            # okay now we have the network, lets update the name
            # and description and then get the network back again
            # via cx1 and cx2 endpoints
            netname = 'ndex2-client integration test network' + str(
                datetime.now())
            client.update_network_profile(netid, {'name': netname})
            netsum = self.wait_for_network_to_be_ready(client, netid)
            self.assertIsNotNone(
                netsum, 'Network is still not ready,'
                ' maybe server is busy?')
            cx2_resp = client.get_network_as_cx2_stream(network_id=netid)
            cx2_json = json.loads(cx2_resp.content)
            net_attrs = None
            for aspect in cx2_json:
                print(aspect)
                if 'networkAttributes' in aspect:
                    net_attrs = aspect['networkAttributes']
                    break
            self.assertEqual([{'name': netname}], net_attrs)

            client_resp = client.get_network_as_cx_stream(network_id=netid)
            cx1_net = ndex2.create_nice_cx_from_raw_cx(
                json.loads(client_resp.content))
            self.assertEqual(netname, cx1_net.get_name(),
                             'Special test to expose '
                             'bug in NDEx server')
        finally:
            client.delete_network(netid)
Exemplo n.º 36
0
 def test_apply_cytoscape_layout_networks_success(self):
     temp_dir = tempfile.mkdtemp()
     try:
         p = MagicMock()
         p.layout = 'grid'
         p.sifdir = temp_dir
         mockpy4 = MagicMock()
         imp_res = {'networks': ['netid']}
         mockpy4.import_network_from_file = MagicMock(return_value=imp_res)
         mockpy4.export_network = MagicMock(return_value='')
         loader = NDExNciPidLoader(p, py4cyto=mockpy4)
         loader._ndexextra.extract_layout_aspect_from_cx = MagicMock(return_value={'cartesianLayout': []})
         net = NiceCXNetwork()
         for x in range(10):
             net.create_node('node' + str(x))
         loader._apply_cytoscape_layout(net)
         self.assertEqual([{'cartesianLayout': []}],
                          net.get_opaque_aspect('cartesianLayout'))
     finally:
         shutil.rmtree(temp_dir)
Exemplo n.º 37
0
    def test_create_edge_with_node_dict_passed_in_for_edge_ids(self):
        net = NiceCXNetwork()

        nodeone = net.get_node(net.create_node('node1'))
        nodetwo = net.get_node(net.create_node('node2'))
        edge_id = net.create_edge(edge_source=nodeone,
                                  edge_target=nodetwo)
        res = net.get_edge(edge_id)
        self.assertEqual(edge_id, res[constants.EDGE_ID])
        self.assertEqual(0, res[constants.EDGE_SOURCE])
        self.assertEqual(1, res[constants.EDGE_TARGET])
Exemplo n.º 38
0
    def test_add_int_attr(self):
        niceCx = NiceCXNetwork()
        int_node = niceCx.create_node(node_name="testint")
        niceCx.add_node_attribute(property_of=int_node, name='Size', values=1, type="integer")

        upload_message = niceCx.upload_to(upload_server, upload_username, upload_password)
        UUID = upload_message.split('/')[-1]
        time.sleep(1)
        imported_cx = ndex2.create_nice_cx_from_server(server='dev.ndexbio.org', uuid=UUID, username=upload_username, password=upload_password)
        for i in imported_cx.get_node_attributes(0):
            self.assertEqual(i.get('d'), "integer")
Exemplo n.º 39
0
    def test_add_attribute_to_node(self):
        nef = Attribute(name='foo', value='someval')
        net = NiceCXNetwork()
        node_one = net.create_node('node1')

        nef.add_attribute_to_node(net_cx=net, node_id=node_one)

        e_attrs = net.get_node_attributes(node_one)
        self.assertEqual(1, len(e_attrs))
        self.assertEqual('foo', e_attrs[0]['n'])
        self.assertEqual('someval', e_attrs[0]['v'])
Exemplo n.º 40
0
    def test_simple_create(self):
        niceCx_creatures = NiceCXNetwork()
        niceCx_creatures.set_name("Food Web")
        fox_node = niceCx_creatures.create_node(node_name='Fox')
        mouse_node = niceCx_creatures.create_node(node_name='Mouse')
        bird_node = niceCx_creatures.create_node(node_name='Bird')

        fox_bird_edge = niceCx_creatures.create_edge(edge_source=fox_node, edge_target=bird_node, edge_interaction='interacts-with')

        fox_mouse_edge = niceCx_creatures.create_edge(edge_source=fox_node, edge_target=mouse_node, edge_interaction='interacts-with')

        niceCx_creatures.add_node_attribute(property_of=fox_node, name='Color', values='Red')

        niceCx_creatures.add_node_attribute(property_of=mouse_node, name='Color', values='Gray')

        niceCx_creatures.add_node_attribute(property_of=bird_node, name='Color', values='Blue')

        niceCx_creatures.add_edge_attribute(property_of=fox_mouse_edge, name='Hunted', values='On the ground')

        print(niceCx_creatures.get_node_attribute(fox_node, 'Color'))
Exemplo n.º 41
0
    def test_get_node_and_edge_items(self):
        net = NiceCXNetwork()

        nodeiter, edgeiter = net._get_node_and_edge_items()
        nodelist = list(nodeiter)
        self.assertEqual(0, len(nodelist))
        edgelist = list(edgeiter)
        self.assertEqual(0, len(edgelist))

        net.create_node('foo')
        net.create_edge(edge_source=0, edge_target=1)

        nodeiter, edgeiter = net._get_node_and_edge_items()
        nodelist = list(nodeiter)
        self.assertEqual(1, len(nodelist))
        self.assertEqual(nodelist[0], (0, {'@id': 0,
                                           'n': 'foo', 'r': 'foo'}))
        edgelist = list(edgeiter)

        self.assertEqual(1, len(edgelist))
        self.assertEqual(edgelist[0], (0, {'@id': 0, 's': 0, 't': 1}))
Exemplo n.º 42
0
    def test_add_lst_flt(self):
        niceCx = NiceCXNetwork()
        list_float_node = niceCx.create_node(node_name="testlstflt")

        niceCx.add_node_attribute(property_of=list_float_node, name='Too many scores', values=[15.3,43.6,-34.0,43.3], type="list_of_float")

        upload_message = niceCx.upload_to(upload_server, upload_username, upload_password)
        UUID = upload_message.split('/')[-1]
        time.sleep(1)
        imported_cx = ndex2.create_nice_cx_from_server(server='dev.ndexbio.org', uuid=UUID, username=upload_username,
                                                       password=upload_password)
        for i in imported_cx.get_node_attributes(0):
            self.assertEqual(i.get('d'), "list_of_double")
Exemplo n.º 43
0
    def test_load_edges(self):
        self.assertFalse(upload_username == 'username')

        nice_cx = NiceCXNetwork()

        node_id_1 = nice_cx.create_node(node_name='node%s' % str(1), node_represents='ABC')
        node_id_2 = nice_cx.create_node(node_name='node%s' % str(2), node_represents='DEF')

        edge_id_1 = nice_cx.create_edge(edge_source=node_id_1, edge_target=node_id_2, edge_interaction='neighbor')

        citation1 = nice_cx.add_citation(id=0, title='Hi 1', identifier='pmid:28947956')
        nice_cx.add_edge_citations(edge_id_1, citation1.get('@id'))

        supports1 = nice_cx.add_support(id=0, text='Hi supports 1')
        nice_cx.add_edge_supports(edge_id_1, supports1.get('@id'))

        nice_cx.set_name('Citation testing')
        upload_message = nice_cx.upload_to(upload_server, upload_username, upload_password)
        print(upload_message)
Exemplo n.º 44
0
 def test_set_name(self):
     niceCx_creatures = NiceCXNetwork()
     niceCx_creatures.set_name(43)
     niceCx_creatures.create_node(node_name="tree")
     upload_message = niceCx_creatures.upload_to(upload_server, upload_username, upload_password)
     self.assertTrue(upload_message)
Exemplo n.º 45
0
 def test_bad_name_add_node(self):
     niceCx_creatures = NiceCXNetwork()
     niceCx_creatures.set_name("Test Network")
     node1_id = niceCx_creatures.create_node(node_name=54, node_represents="Tree")
     upload_message = niceCx_creatures.upload_to(upload_server, upload_username, upload_password)
     self.assertTrue(upload_message)