def test_update(self):
        collapser = RedundantEdgeCollapser()
        net = NiceCXNetwork()
        ctext = {'pubmed': 'http://p/'}
        net.set_network_attribute('@context', values=json.dumps(ctext))
        collapser._set_pubmedurl_from_network(net)

        eid = net.create_edge(edge_source=0,
                              edge_target=1,
                              edge_interaction='something')

        net.set_edge_attribute(eid, 'sentence', 'sent1', type='string')
        net.set_edge_attribute(eid, 'direct', True, type='boolean')
        net.set_edge_attribute(eid, 'citation', 'pubmed:123', type='string')

        eidtwo = net.create_edge(edge_source=0,
                                 edge_target=1,
                                 edge_interaction='something')
        net.set_edge_attribute(eidtwo, 'sentence', 'sent2', type='string')
        net.set_edge_attribute(eidtwo, 'direct', True, type='boolean')
        net.set_edge_attribute(eidtwo, 'citation', 'pubmed:456', type='string')
        res = collapser.update(net)

        self.assertEqual([], res)

        edata = net.get_edge_attribute(eid, 'sentence')
        self.assertEqual(2, len(edata['v']))

        self.assertTrue('<a target="_blank" href="http://p/456">'
                        'pubmed:456</a>  sent2' in edata['v'])
        self.assertTrue('<a target="_blank" href="http://p/123">'
                        'pubmed:123</a> sent1' in edata['v'])
    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)
    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)
Example #4
0
    def get_nice_cx_network(self, netx_network):
        """

        :param netx_network:
        :return:
        """
        nice_cx = NiceCXNetwork()
        logger.info('Keys for graph: ' + str(netx_network.graph.keys()))
        for attr_name in netx_network.graph.keys():
            nice_cx.set_network_attribute(attr_name, values=netx_network.graph[attr_name])

        node_id_map = self._add_nodes(netx_network, nice_cx)
        self._add_edges(netx_network, nice_cx, node_id_map)

        return nice_cx
Example #5
0
    def test_set_network_attributes_from_style_network_complete_net(self):
        net = NiceCXNetwork()
        net.set_name(ndexloadncipid.COMPLETE_INTERACTION_NAME)

        templatenet = NiceCXNetwork()
        templatenet.set_name('well')
        templatenet.set_network_attribute('description', values='hi', type='string')
        templatenet.set_network_attribute('organism', values='some', type='string')
        loader = NDExNciPidLoader(None)
        loader._template = templatenet

        res = loader._set_network_attributes_from_style_network(net)
        self.assertEqual(0, len(res))

        self.assertTrue('This network' in net.get_network_attribute('description')['v'])
        self.assertEqual('some', net.get_network_attribute('organism')['v'])
Example #6
0
    def test_set_network_attributes_from_style_network_description_set_org_not(self):
        net = NiceCXNetwork()
        net.set_name('foo')

        templatenet = NiceCXNetwork()
        templatenet.set_name('well')
        templatenet.set_network_attribute('description', values='hi', type='string')
        loader = NDExNciPidLoader(None)
        loader._template = templatenet

        res = loader._set_network_attributes_from_style_network(net)
        self.assertEqual(1, len(res))
        self.assertTrue('organism network' in res[0])

        self.assertEqual('hi', net.get_network_attribute('description')['v'])
        self.assertEqual(None, net.get_network_attribute('organism'))
    def test_prepend_citation_to_sentences(self):
        collapser = RedundantEdgeCollapser()
        net = NiceCXNetwork()
        ctext = {'pubmed': 'http://p/'}
        net.set_network_attribute('@context', values=json.dumps(ctext))
        collapser._set_pubmedurl_from_network(net)

        res = collapser._prepend_citation_to_sentences({})
        self.assertEqual({}, res)
        res = collapser._prepend_citation_to_sentences(
            {'sentence': ('hi', 'string')})
        self.assertEqual({'sentence': ('hi', 'string')}, res)
        edge_dict = {
            'citation': (['pubmed:123'], 'list_of_string'),
            'sentence': ('sentence2', 'string')
        }
        res = collapser._prepend_citation_to_sentences(edge_dict)
        self.assertEqual(
            '<a target="_blank" href="http://p/123">'
            'pubmed:123</a> sentence2', res['sentence'][0])
        self.assertEqual('string', res['sentence'][1])
Example #8
0
    def _create_empty_hierarchy_network(self,
                                        docker_image=None,
                                        algo_name=None,
                                        source_network=None,
                                        arguments=None):
        """
        Creates an empty hierarchy network with appropriate network attributes

        :param docker_image: Docker image, used to set value
                             `prov:wasGeneratedBy`
                             network attribute
        :type docker_image: str
        :param algo_name: Name of algorithm, used in `description` network
                          attribute
        :type algo_name: str
        :param source_network: Source network, name is used to set name of
                               network returned by this method
        :type source_network: :py:class:`ndex2.nice_cx_network.NiceCXNetwork`
        :return: Empty network except for network attributes
        :rtype: :py:class:`ndex2.nice_cx_network.NiceCXNetwork`
        """

        cust_params = ''
        if arguments is not None:
            for a in arguments.keys():
                cust_params += a + ' '
                if arguments[a] is not None:
                    cust_params += arguments[a] + ' '

        hier_net = NiceCXNetwork()
        hier_net.set_name(algo_name + '_(none)_' + source_network.get_name())
        hier_net.set_network_attribute('__CD_OriginalNetwork',
                                       values='0',
                                       type='long')
        hier_net.set_network_attribute(
            'description',
            values='Original network: ' + source_network.get_name() + '\n ' +
            'Algorithm used for '
            'community detection: ' + algo_name + '\n ' +
            'Edge table column used '
            'as weight: (none)\n ' + 'CustomParameters: {' + cust_params + '}')
        hier_net.set_network_attribute('prov:wasDerivedFrom',
                                       values=source_network.get_name())
        hier_net.set_network_attribute('prov:wasGeneratedBy',
                                       values='cdapsutil ' +
                                       cdapsutil.__version__ + ' ' +
                                       'Docker image: ' + docker_image)
        return hier_net
    def test_get_citation_from_edge_dict(self):
        collapser = RedundantEdgeCollapser()

        # single citation pubmedurl is None
        edge_dict = {'citation': (['pubmed:123'], 'list_of_string')}
        res = collapser._get_citation_from_edge_dict(edge_dict)
        self.assertEqual(' ', res)

        # multiple citation pubmedurl is None
        edge_dict = {
            'citation': (['pubmed:123', 'pubmed:456'], 'list_of_string')
        }
        res = collapser._get_citation_from_edge_dict(edge_dict)
        self.assertEqual('  ', res)

        # single citation pubmedurl is set
        net = NiceCXNetwork()
        ctext = {'pubmed': 'http://p/'}
        net.set_network_attribute('@context', values=json.dumps(ctext))
        edge_dict = {'citation': (['pubmed:123'], 'list_of_string')}
        collapser._set_pubmedurl_from_network(net)
        res = collapser._get_citation_from_edge_dict(edge_dict)
        self.assertEqual(
            '<a target="_blank" '
            'href="http://p/123">pubmed:123</a> ', res)

        # multiple citation pubmedurl is set
        edge_dict = {
            'citation': (['pubmed:123', 'pubmed:456'], 'list_of_string')
        }
        res = collapser._get_citation_from_edge_dict(edge_dict)
        self.assertEqual(
            '<a target="_blank" '
            'href="http://p/123">pubmed:123</a> '
            '<a target="_blank" href="http://p/456">pubmed:'
            '456</a> ', res)
Example #10
0
class NiceCxAssembler(object):
    """Assembles a Nice CX network from a set of INDRA Statements.

    Parameters
    ----------
    stmts : Optional[list[indra.statements.Statement]]
        A list of INDRA Statements to be assembled.
    network_name : Optional[str]
        The name of the network to be assembled. Default: indra_assembled

    Attributes
    ----------
    network : ndex2.nice_cx_network.NiceCXNetwork
        A Nice CX network object that is assembled from Statements.
    """
    def __init__(self, stmts=None, network_name=None):
        self.statements = stmts if stmts else []
        self.network = NiceCXNetwork()
        self.network.set_network_attribute(
            'name', (network_name if network_name else 'indra_assembled'))
        self.node_keys = {}
        self.context_prefixes = {
            'pubmed': 'https://identifiers.org/pubmed:',
            'hgnc.symbol': 'https://identifiers.org/hgnc.symbol:'
        }

    def make_model(self, self_loops=False, network_attributes=None):
        """Return a Nice CX network object after running assembly.

        Parameters
        ----------
        self_loops : Optional[bool]
            If False, self-loops are excluded from the network. Default: False
        network_attributes : Optional[dict]
            A dictionary containing attributes to be added to the
            assembled network.

        Returns
        -------
        ndex2.nice_cx_network.NiceCXNetwork
            The assembled Nice CX network.
        """
        for stmt in self.statements:
            agents = stmt.agent_list()
            not_none_agents = [a for a in agents if a is not None]
            if len(not_none_agents) < 2:
                continue
            for a1, a2 in itertools.combinations(not_none_agents, 2):
                a1_id = self.add_node(a1)
                a2_id = self.add_node(a2)
                if not self_loops and a1_id == a2_id:
                    continue
                edge_id = self.add_edge(a1_id, a2_id, stmt)

        self.network.set_network_attribute('@context',
                                           json.dumps(self.context_prefixes))
        if network_attributes:
            for k, v in network_attributes.items():
                self.network.set_network_attribute(k, v, 'string')
        return self.network

    def add_node(self, agent):
        """Add an Agent to the network as a node."""
        agent_key = self.get_agent_key(agent)
        # If the node already exists
        if agent_key in self.node_keys:
            return self.node_keys[agent_key]

        # If the node doesn't exist yet
        db_ns, db_id = agent.get_grounding()
        # TODO: handle more represents name spaces
        if db_ns == 'HGNC':
            represents = 'hgnc.symbol:%s' % agent.name
        else:
            represents = None
        node_id = self.network.create_node(agent.name,
                                           node_represents=represents)
        self.node_keys[agent_key] = node_id

        # Add db_refs as aliases
        db_refs_list = [
            '%s:%s' % (db_name, db_id)
            for db_name, db_id in agent.db_refs.items()
            if db_name in url_prefixes
        ]
        if db_refs_list:
            self.network.add_node_attribute(property_of=node_id,
                                            name='aliases',
                                            values=db_refs_list,
                                            type='list_of_string')

        # Add the type of the node, inferred from grounding
        if db_ns:
            mapped_type = db_ns_type_mappings.get(db_ns)
            if mapped_type:
                self.network.add_node_attribute(property_of=node_id,
                                                name='type',
                                                values=mapped_type,
                                                type='string')

        return node_id

    def add_edge(self, a1_id, a2_id, stmt):
        """Add a Statement to the network as an edge."""
        stmt_type = stmt.__class__.__name__
        edge_id = self.network.create_edge(a1_id, a2_id, stmt_type)
        evs = []
        for ev in stmt.evidence:
            # We skip evidences with no PMID
            if not ev.pmid:
                continue
            # We take a maximum 200 character snippet of the evidence text
            if not ev.text:
                ev_txt = 'Evidence text not available.'
            elif len(ev.text) > 200:
                ev_txt = ev.text[:200] + '...'
            else:
                ev_txt = ev.text
            # Construct a clickable PMID link with the source and evidence text
            ev_str = ('<a target="_blank" '
                      'href="https://identifiers.org/pubmed:%s">'
                      'pubmed:%s</a> (%s) %s') % (ev.pmid, ev.pmid,
                                                  ev.source_api, ev_txt)
            evs.append((ev_str, 0 if ev.text is None else 1))
        # Reorder to have ones with text first
        evs = sorted(evs, key=lambda x: x[1], reverse=True)
        # Cap at 10 pieces of evidence
        evs = [e[0] for e in evs[:10]]
        self.network.set_edge_attribute(edge_id,
                                        'citation',
                                        evs,
                                        type='list_of_string')
        return edge_id

    def print_model(self):
        """Return the CX string of the assembled model."""
        return self.network.to_cx()

    @staticmethod
    def get_agent_key(agent):
        return agent.name