示例#1
0
def load_matrix_to_ndex(x, x_cols, x_rows, server, username, password, name):
    """
    Testing 1
    :param X: param 1
    :type X:
    :param X_cols:
    :type X_cols:
    :param X_rows:
    :type X_rows:
    :param server:
    :type server:
    :param username:
    :type username:
    :param password:
    :type password:
    :param name:
    :type name:
    :return:
    :rtype:
    """
    if not isinstance(x, np.ndarray):
        raise Exception('Provided matrix is not of type numpy.ndarray')
    if not isinstance(x_cols, list):
        raise Exception(
            'Provided column header is not in the correct format.  Please provide a list of strings'
        )
    if not isinstance(x_rows, list):
        raise Exception(
            'Provided row header is not in the correct format.  Please provide a list of strings'
        )

    if not x.flags['C_CONTIGUOUS']:
        x = np.ascontiguousarray(x)

    serialized = base64.b64encode(x.tobytes())

    nice_cx_builder = NiceCXBuilder()
    nice_cx_builder.set_name(name)
    nice_cx_builder.add_node(name='Sim Matrix', represents='Sim Matrix')

    nice_cx_builder.add_opaque_aspect('matrix', [{'v': serialized}])
    nice_cx_builder.add_opaque_aspect('matrix_cols', [{'v': x_cols}])
    nice_cx_builder.add_opaque_aspect('matrix_rows', [{'v': x_rows}])
    nice_cx_builder.add_opaque_aspect('matrix_dtype', [{'v': x.dtype.name}])

    nice_cx = nice_cx_builder.get_nice_cx()

    #print(x)
    ont_url = nice_cx.upload_to(server, username, password)

    return ont_url
示例#2
0
def load_matrix_to_ndex(x, x_cols, x_rows, server, username, password, name):
    """
    Testing 1
    :param X: param 1
    :type X:
    :param X_cols:
    :type X_cols:
    :param X_rows:
    :type X_rows:
    :param server:
    :type server:
    :param username:
    :type username:
    :param password:
    :type password:
    :param name:
    :type name:
    :return:
    :rtype:
    """
    if not isinstance(x, np.ndarray):
        raise Exception('Provided matrix is not of type numpy.ndarray')
    if not isinstance(x_cols, list):
        raise Exception('Provided column header is not in the correct format.  Please provide a list of strings')
    if not isinstance(x_rows, list):
        raise Exception('Provided row header is not in the correct format.  Please provide a list of strings')

    if not x.flags['C_CONTIGUOUS']:
        x = np.ascontiguousarray(x)

    serialized = base64.b64encode(x.tobytes())

    nice_cx_builder = NiceCXBuilder()
    nice_cx_builder.set_name(name)
    nice_cx_builder.add_node(name='Sim Matrix', represents='Sim Matrix')

    nice_cx_builder.add_opaque_aspect('matrix', [{'v': serialized}])
    nice_cx_builder.add_opaque_aspect('matrix_cols', [{'v': x_cols}])
    nice_cx_builder.add_opaque_aspect('matrix_rows', [{'v': x_rows}])
    nice_cx_builder.add_opaque_aspect('matrix_dtype', [{'v': x.dtype.name}])

    nice_cx = nice_cx_builder.get_nice_cx()

    #print(x)
    ont_url = nice_cx.upload_to(server, username, password)

    return ont_url
示例#3
0
def create_nice_cx_from_server(server,
                               username=None,
                               password=None,
                               uuid=None):
    """
    Create a :py:func:`~ndex2.nice_cx_network.NiceCXNetwork` based on a network
    retrieved from NDEx, specified by its UUID.
    If the network is not public, then username and password arguments for an account on
    the server with permission to access the network must be supplied.

    :param server: the URL of the NDEx server hosting the network.
    :param username: the user name of an account with permission to access the network.
    :param password: the password of an account with permission to access the network.
    :param uuid: the UUID of the network.
    :return: NiceCXNetwork
    :rtype: :py:func:`~ndex2.nice_cx_network.NiceCXNetwork`
    """

    niceCxBuilder = NiceCXBuilder()

    if server and uuid:
        my_nicecx = NiceCXNetwork()

        # ===================
        # METADATA
        # ===================
        available_aspects = []
        md_aspect_iter = my_nicecx.get_aspect(uuid, 'metaData', server,
                                              username, password)
        if md_aspect_iter:
            for ae in (o for o in md_aspect_iter):
                available_aspects.append(ae.get('name'))
        else:
            if not username or not password:
                raise Exception(
                    'Network is not available.  Username and/or password not supplied'
                )
            else:
                raise Exception('Network not available')

        opaque_aspects = set(available_aspects).difference(known_aspects_min)

        # ====================
        # NETWORK ATTRIBUTES
        # ====================
        if 'networkAttributes' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'networkAttributes', server,
                                           username, password)
            for network_item in objects:
                niceCxBuilder._add_network_attributes_from_fragment(
                    network_item)
                #niceCxBuilder.add_network_attribute(network_item.get('n'), network_item.get('v'), network_item.get('d'))

        # ===================
        # @CONTEXT
        # ===================
        if '@context' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, '@context', server, username,
                                           password)

            niceCxBuilder.set_context(
                objects)  #nice_cx.set_namespaces(objects)
            #niceCxBuilder.set_context(objects)

        # ===================
        # NODES
        # ===================
        if 'nodes' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'nodes', server, username,
                                           password)
            for node_item in objects:
                niceCxBuilder._add_node_from_fragment(node_item)
                #niceCxBuilder.add_node(node_item.get('n'), node_item.get('r'), id=node_item.get('@id'))

        # ===================
        # EDGES
        # ===================
        if 'edges' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'edges', server, username,
                                           password)
            for edge_item in objects:
                niceCxBuilder._add_edge_from_fragment(edge_item)

                #niceCxBuilder.add_edge(source=edge_item.get('s'), target=edge_item.get('t'),
                #                       interaction=edge_item.get('i'), id=edge_item.get('@id'))

        # ===================
        # NODE ATTRIBUTES
        # ===================
        if 'nodeAttributes' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'nodeAttributes', server,
                                           username, password)
            for att in objects:
                niceCxBuilder._add_node_attribute_from_fragment(att)

                #niceCxBuilder.add_node_attribute(att.get('po'), att.get('n'), att.get('v'), type=att.get('d'))

        # ===================
        # EDGE ATTRIBUTES
        # ===================
        if 'edgeAttributes' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'edgeAttributes', server,
                                           username, password)
            for att in objects:
                niceCxBuilder._add_edge_attribute_from_fragment(att)

                #niceCxBuilder.add_edge_attribute(property_of=att.get('po'), name=att.get('n'),
                #                                 values=att.get('v'), type=att.get('d'))

        # ===================
        # CITATIONS
        # ===================
        if 'citations' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'citations', server, username,
                                           password)
            for cit in objects:
                niceCxBuilder._add_citation_from_fragment(cit)
                #my_nicecx.citations[cit.get('@id')] = cit

            #my_nicecx.add_metadata_stub('citations')

        # ===================
        # SUPPORTS
        # ===================
        if 'supports' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'supports', server, username,
                                           password)
            for sup in objects:
                niceCxBuilder._add_supports_from_fragment(sup)

                #my_nicecx.supports[sup.get('@id')] = sup

            #my_nicecx.add_metadata_stub('supports')

        # ===================
        # EDGE SUPPORTS
        # ===================
        if 'edgeSupports' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'edgeSupports', server,
                                           username, password)
            for add_this_edge_sup in objects:
                niceCxBuilder._add_edge_supports_from_fragment(
                    add_this_edge_sup)

                #for po_id in add_this_edge_sup.get('po'):
                #    my_nicecx.edgeSupports[po_id] = add_this_edge_sup.get('supports')

            #my_nicecx.add_metadata_stub('edgeSupports')

        # ===================
        # NODE CITATIONS
        # ===================
        if 'nodeCitations' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'nodeCitations', server,
                                           username, password)
            for node_cit in objects:
                niceCxBuilder._add_node_citations_from_fragment(node_cit)

                #for po_id in node_cit.get('po'):
                #    my_nicecx.nodeCitations[po_id] = node_cit.get('citations')

            #my_nicecx.add_metadata_stub('nodeCitations')

        # ===================
        # EDGE CITATIONS
        # ===================
        if 'edgeCitations' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'edgeCitations', server,
                                           username, password)
            for edge_cit in objects:
                niceCxBuilder._add_edge_citations_from_fragment(edge_cit)
                #for po_id in edge_cit.get('po'):
                #    my_nicecx.nodeCitations[po_id] = edge_cit.get('citations')

            #my_nicecx.add_metadata_stub('edgeCitations')

        # ===================
        # OPAQUE ASPECTS
        # ===================
        for oa in opaque_aspects:
            objects = my_nicecx.get_aspect(uuid, oa, server, username,
                                           password)
            niceCxBuilder.add_opaque_aspect(oa, objects)

    else:
        raise Exception('Server and uuid not specified')

    return niceCxBuilder.get_nice_cx()
示例#4
0
def create_nice_cx_from_raw_cx(cx):
    """
    Create a :py:func:`~ndex2.nice_cx_network.NiceCXNetwork` from a
    as a `list` of `dict` objects in
    `CX format <https://www.home.ndexbio.org/data-model/>`__

    Example:

    .. code-block:: python

        import json
        import ndex2

        # cx_as_str is a str containing JSON in CX format above
        net_cx = ndex2.create_nice_cx_from_raw_cx(json.loads(cx_as_str))



    :param cx: CX as a `list` of `dict` objects
    :type cx: list
    :return: NiceCXNetwork
    :rtype: :py:func:`~ndex2.nice_cx_network.NiceCXNetwork`
    """
    if not cx:
        raise Exception('CX is empty')

    niceCxBuilder = NiceCXBuilder()

    # ===================
    # METADATA
    # ===================
    available_aspects = []
    for ae in (
            o
            for o in niceCxBuilder.get_frag_from_list_by_key(cx, 'metaData')):
        available_aspects.append(ae.get('name'))

    opaque_aspects = set(available_aspects).difference(known_aspects_min)

    # ====================
    # NETWORK ATTRIBUTES
    # ====================
    if 'networkAttributes' in available_aspects:
        objects = niceCxBuilder.get_frag_from_list_by_key(
            cx, 'networkAttributes')
        for network_item in objects:
            niceCxBuilder._add_network_attributes_from_fragment(network_item)

    # ===================
    # NODES
    # ===================
    if 'nodes' in available_aspects:
        objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'nodes')
        for node_item in objects:
            niceCxBuilder._add_node_from_fragment(node_item)

    # ===================
    # EDGES
    # ===================
    if 'edges' in available_aspects:
        objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'edges')
        for edge_item in objects:
            niceCxBuilder._add_edge_from_fragment(edge_item)

    # ===================
    # NODE ATTRIBUTES
    # ===================
    if 'nodeAttributes' in available_aspects:
        objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'nodeAttributes')
        for att in objects:
            niceCxBuilder._add_node_attribute_from_fragment(att)

    # ===================
    # EDGE ATTRIBUTES
    # ===================
    if 'edgeAttributes' in available_aspects:
        objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'edgeAttributes')
        for att in objects:
            niceCxBuilder._add_edge_attribute_from_fragment(att)

    # ===================
    # CITATIONS
    # ===================
    if 'citations' in available_aspects:
        objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'citations')
        for cit in objects:
            niceCxBuilder._add_citation_from_fragment(cit)

    # ===================
    # SUPPORTS
    # ===================
    if 'supports' in available_aspects:
        objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'supports')
        for sup in objects:
            niceCxBuilder._add_supports_from_fragment(sup)

    # ===================
    # EDGE SUPPORTS
    # ===================
    if 'edgeSupports' in available_aspects:
        objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'edgeSupports')
        for add_this_edge_sup in objects:
            niceCxBuilder._add_edge_supports_from_fragment(add_this_edge_sup)

    # ===================
    # NODE CITATIONS
    # ===================
    if 'nodeCitations' in available_aspects:
        objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'nodeCitations')
        for node_cit in objects:
            niceCxBuilder._add_node_citations_from_fragment(node_cit)

    # ===================
    # EDGE CITATIONS
    # ===================
    if 'edgeCitations' in available_aspects:
        objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'edgeCitations')
        for edge_cit in objects:
            niceCxBuilder._add_edge_citations_from_fragment(edge_cit)

    # ===================
    # OPAQUE ASPECTS
    # ===================
    for oa in opaque_aspects:
        #TODO - Add context to builder
        if oa == '@context':
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, oa)
            niceCxBuilder.set_context(
                objects)  #nice_cx.set_namespaces(objects)
        else:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, oa)
            niceCxBuilder.add_opaque_aspect(oa, objects)

    return niceCxBuilder.get_nice_cx()
示例#5
0
def create_nice_cx_from_networkx(G):
    """
    Creates a :py:class:`~ndex2.nice_cx_network.NiceCXNetwork` based on a
    networkx graph.

    The resulting :py:class:`~ndex2.nice_cx_network.NiceCXNetwork`
    contains the nodes, edges and their attributes from the networkx graph and also
    preserves the graph 'pos' attribute as a CX cartesian coordinates aspect.

    The node name is taken from the networkx node id. Node 'represents' is
    taken from the networkx node attribute 'represents'

    :param G: networkx graph
    :type G: networkx graph
    :return: NiceCXNetwork
    :rtype: :py:class:`~ndex2.nice_cx_network.NiceCXNetwork`
    """

    niceCxBuilder = NiceCXBuilder()
    if G is None:
        raise Exception('Networkx input is empty')

    my_nicecx = NiceCXNetwork()

    if G.graph.get('name'):
        my_nicecx.set_name(G.graph.get('name'))
    else:
        my_nicecx.set_name('created from networkx')

    my_nicecx.add_metadata_stub('networkAttributes')

    #=========================================
    # Check to see if the node label is same
    # (case insensitive) as 'name' attribute
    #=========================================
    #use_node_label = False
    #for n, d in G.nodes_iter(data=True):
    #    if not isinstance(n, int) and d and d.get('name'):
    #        if n.lower() == d.get('name').lower():
    #            use_node_label = True

    #    break

    for n, d in G.nodes(data=True):
        # =============
        # ADD NODES
        # =============
        #if d and d.get('name'):
        #    if isinstance(n, int):
        #        node_id = niceCxBuilder.add_node(name=d.get('name'),represents=d.get('name'), id=n, map_node_ids=True)
        #    else:
        #        # If networkx node is of type string then maybe the 'name' atribute is no longer accurate
        #        if use_node_label:
        #            node_id = niceCxBuilder.add_node(name=n,represents=n, map_node_ids=True)
        #        else:
        #            node_id = niceCxBuilder.add_node(name=d.get('name'),represents=d.get('name'), map_node_ids=True)
        #else:
        if isinstance(n, int):
            node_id = niceCxBuilder.add_node(name=n,
                                             represents=d.get('represents'),
                                             id=n,
                                             map_node_ids=True)
        else:
            node_id = niceCxBuilder.add_node(name=n,
                                             represents=d.get('represents'),
                                             map_node_ids=True)

        # ======================
        # ADD NODE ATTRIBUTES
        # ======================
        for k, v in d.items():
            use_this_value, attr_type = niceCxBuilder._infer_data_type(
                v, split_string=True)

            if k == 'citation' and not isinstance(use_this_value, list):
                use_this_value = [use_this_value]
                attr_type = 'list_of_string'
            if use_this_value is not None:
                niceCxBuilder.add_node_attribute(node_id,
                                                 k,
                                                 use_this_value,
                                                 type=attr_type)

    index = 0
    for u, v, d in G.edges(data=True):
        # =============
        # ADD EDGES
        # =============
        if d.get('interaction') is None or d.get('interaction') == 'null':
            interaction = 'neighbor-of'
        else:
            interaction = d.get('interaction')

        if isinstance(u, int):
            niceCxBuilder.add_edge(source=u,
                                   target=v,
                                   interaction=interaction,
                                   id=index)
        else:
            niceCxBuilder.add_edge(source=niceCxBuilder.node_id_lookup.get(u),
                                   target=niceCxBuilder.node_id_lookup.get(v),
                                   interaction=interaction,
                                   id=index)

        # ==============================
        # ADD EDGE ATTRIBUTES
        # ==============================
        for k, val in d.items():
            if k != 'interaction':
                use_this_value, attr_type = niceCxBuilder._infer_data_type(
                    val, split_string=True)

                if k == 'citation' and not isinstance(use_this_value, list):
                    use_this_value = [use_this_value]
                    attr_type = 'list_of_string'

                if use_this_value is not None:
                    niceCxBuilder.add_edge_attribute(property_of=index,
                                                     name=k,
                                                     values=use_this_value,
                                                     type=attr_type)

        index += 1

    if hasattr(G, 'pos'):
        aspect = _create_cartesian_coordinates_aspect_from_networkx(G)
        niceCxBuilder.add_opaque_aspect('cartesianLayout', aspect)

    return niceCxBuilder.get_nice_cx()
示例#6
0
def create_nice_cx_from_raw_cx(cx):
    """
    Create a NiceCXNetwork from a CX json object. (see http://www.home.ndexbio.org/data-model)

    :param cx: a valid CX document
    :return: NiceCXNetwork
    """

    niceCxBuilder = NiceCXBuilder()

    #my_nicecx = NiceCXNetwork()

    if cx:
        # ===================
        # METADATA
        # ===================
        available_aspects = []
        for ae in (o for o in niceCxBuilder.get_frag_from_list_by_key(
                cx, 'metaData')):
            available_aspects.append(ae.get('name'))

        opaque_aspects = set(available_aspects).difference(known_aspects_min)

        # ====================
        # NETWORK ATTRIBUTES
        # ====================
        if 'networkAttributes' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(
                cx, 'networkAttributes')
            for network_item in objects:
                niceCxBuilder._add_network_attributes_from_fragment(
                    network_item)

        # ===================
        # NODES
        # ===================
        if 'nodes' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'nodes')
            for node_item in objects:
                niceCxBuilder._add_node_from_fragment(node_item)

        # ===================
        # EDGES
        # ===================
        if 'edges' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'edges')
            for edge_item in objects:
                niceCxBuilder._add_edge_from_fragment(edge_item)

        # ===================
        # NODE ATTRIBUTES
        # ===================
        if 'nodeAttributes' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(
                cx, 'nodeAttributes')
            for att in objects:
                niceCxBuilder._add_node_attribute_from_fragment(att)

        # ===================
        # EDGE ATTRIBUTES
        # ===================
        if 'edgeAttributes' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(
                cx, 'edgeAttributes')
            for att in objects:
                niceCxBuilder._add_edge_attribute_from_fragment(att)

        # ===================
        # CITATIONS
        # ===================
        if 'citations' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'citations')
            for cit in objects:
                niceCxBuilder._add_citation_from_fragment(cit)

        # ===================
        # SUPPORTS
        # ===================
        if 'supports' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'supports')
            for sup in objects:
                niceCxBuilder._add_supports_from_fragment(sup)

        # ===================
        # EDGE SUPPORTS
        # ===================
        if 'edgeSupports' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(
                cx, 'edgeSupports')
            for add_this_edge_sup in objects:
                niceCxBuilder._add_edge_supports_from_fragment(
                    add_this_edge_sup)

        # ===================
        # NODE CITATIONS
        # ===================
        if 'nodeCitations' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(
                cx, 'nodeCitations')
            for node_cit in objects:
                niceCxBuilder._add_node_citations_from_fragment(node_cit)

        # ===================
        # EDGE CITATIONS
        # ===================
        if 'edgeCitations' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(
                cx, 'edgeCitations')
            for edge_cit in objects:
                niceCxBuilder._add_edge_citations_from_fragment(edge_cit)

        # ===================
        # OPAQUE ASPECTS
        # ===================
        for oa in opaque_aspects:
            #TODO - Add context to builder
            if oa == '@context':
                objects = niceCxBuilder.get_frag_from_list_by_key(cx, oa)
                niceCxBuilder.set_context(
                    objects)  #nice_cx.set_namespaces(objects)
            else:
                objects = niceCxBuilder.get_frag_from_list_by_key(cx, oa)
                niceCxBuilder.add_opaque_aspect(oa, objects)

        return niceCxBuilder.get_nice_cx()
    else:
        raise Exception('CX is empty')
示例#7
0
def create_nice_cx_from_server(server, username=None, password=None, uuid=None):
    """
    Create a NiceCXNetwork based on a network retrieved from NDEx, specified by its UUID.
    If the network is not public, then username and password arguments for an account on
    the server with permission to access the network must be supplied.

    :param server: the URL of the NDEx server hosting the network.
    :param username: the user name of an account with permission to access the network.
    :param password: the password of an account with permission to access the network.
    :param uuid: the UUID of the network.
    :return: NiceCXNetwork
    """

    niceCxBuilder = NiceCXBuilder()

    if server and uuid:
        my_nicecx = NiceCXNetwork()

        # ===================
        # METADATA
        # ===================
        available_aspects = []
        md_aspect_iter = my_nicecx.get_aspect(uuid, 'metaData', server, username, password)
        if md_aspect_iter:
            for ae in (o for o in md_aspect_iter):
                available_aspects.append(ae.get('name'))
        else:
            if not username or not password:
                raise Exception('Network is not available.  Username and/or password not supplied')
            else:
                raise Exception('Network not available')

        opaque_aspects = set(available_aspects).difference(known_aspects_min)

        # ====================
        # NETWORK ATTRIBUTES
        # ====================
        if 'networkAttributes' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'networkAttributes', server, username, password)
            for network_item in objects:
                niceCxBuilder._add_network_attributes_from_fragment(network_item)
                #niceCxBuilder.add_network_attribute(network_item.get('n'), network_item.get('v'), network_item.get('d'))

        # ===================
        # @CONTEXT
        # ===================
        if '@context' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, '@context', server, username, password)

            niceCxBuilder.set_context(objects) #nice_cx.set_namespaces(objects)
            #niceCxBuilder.set_context(objects)

        # ===================
        # NODES
        # ===================
        if 'nodes' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'nodes', server, username, password)
            for node_item in objects:
                niceCxBuilder._add_node_from_fragment(node_item)
                #niceCxBuilder.add_node(node_item.get('n'), node_item.get('r'), id=node_item.get('@id'))

        # ===================
        # EDGES
        # ===================
        if 'edges' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'edges', server, username, password)
            for edge_item in objects:
                niceCxBuilder._add_edge_from_fragment(edge_item)

                #niceCxBuilder.add_edge(source=edge_item.get('s'), target=edge_item.get('t'),
                #                       interaction=edge_item.get('i'), id=edge_item.get('@id'))

        # ===================
        # NODE ATTRIBUTES
        # ===================
        if 'nodeAttributes' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'nodeAttributes', server, username, password)
            for att in objects:
                niceCxBuilder._add_node_attribute_from_fragment(att)

                #niceCxBuilder.add_node_attribute(att.get('po'), att.get('n'), att.get('v'), type=att.get('d'))

        # ===================
        # EDGE ATTRIBUTES
        # ===================
        if 'edgeAttributes' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'edgeAttributes', server, username, password)
            for att in objects:
                niceCxBuilder._add_edge_attribute_from_fragment(att)

                #niceCxBuilder.add_edge_attribute(property_of=att.get('po'), name=att.get('n'),
                #                                 values=att.get('v'), type=att.get('d'))

        # ===================
        # CITATIONS
        # ===================
        if 'citations' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'citations', server, username, password)
            for cit in objects:
                niceCxBuilder._add_citation_from_fragment(cit)
                #my_nicecx.citations[cit.get('@id')] = cit

            #my_nicecx.add_metadata_stub('citations')

        # ===================
        # SUPPORTS
        # ===================
        if 'supports' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'supports', server, username, password)
            for sup in objects:
                niceCxBuilder._add_supports_from_fragment(sup)

                #my_nicecx.supports[sup.get('@id')] = sup

            #my_nicecx.add_metadata_stub('supports')

        # ===================
        # EDGE SUPPORTS
        # ===================
        if 'edgeSupports' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'edgeSupports', server, username, password)
            for add_this_edge_sup in objects:
                niceCxBuilder._add_edge_supports_from_fragment(add_this_edge_sup)

                #for po_id in add_this_edge_sup.get('po'):
                #    my_nicecx.edgeSupports[po_id] = add_this_edge_sup.get('supports')

            #my_nicecx.add_metadata_stub('edgeSupports')

        # ===================
        # NODE CITATIONS
        # ===================
        if 'nodeCitations' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'nodeCitations', server, username, password)
            for node_cit in objects:
                niceCxBuilder._add_node_citations_from_fragment(node_cit)

                #for po_id in node_cit.get('po'):
                #    my_nicecx.nodeCitations[po_id] = node_cit.get('citations')

            #my_nicecx.add_metadata_stub('nodeCitations')

        # ===================
        # EDGE CITATIONS
        # ===================
        if 'edgeCitations' in available_aspects:
            objects = my_nicecx.get_aspect(uuid, 'edgeCitations', server, username, password)
            for edge_cit in objects:
                niceCxBuilder._add_edge_citations_from_fragment(edge_cit)
                #for po_id in edge_cit.get('po'):
                #    my_nicecx.nodeCitations[po_id] = edge_cit.get('citations')

            #my_nicecx.add_metadata_stub('edgeCitations')

        # ===================
        # OPAQUE ASPECTS
        # ===================
        for oa in opaque_aspects:
            objects = my_nicecx.get_aspect(uuid, oa, server, username, password)
            niceCxBuilder.add_opaque_aspect(oa, objects)

    else:
        raise Exception('Server and uuid not specified')

    return niceCxBuilder.get_nice_cx()
示例#8
0
def create_nice_cx_from_raw_cx(cx):
    """
    Create a NiceCXNetwork from a CX json object. (see http://www.home.ndexbio.org/data-model)

    :param cx: a valid CX document
    :return: NiceCXNetwork
    """

    niceCxBuilder = NiceCXBuilder()

    #my_nicecx = NiceCXNetwork()

    if cx:
        # ===================
        # METADATA
        # ===================
        available_aspects = []
        for ae in (o for o in niceCxBuilder.get_frag_from_list_by_key(cx, 'metaData')):
            available_aspects.append(ae.get('name'))

        opaque_aspects = set(available_aspects).difference(known_aspects_min)

        # ====================
        # NETWORK ATTRIBUTES
        # ====================
        if 'networkAttributes' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'networkAttributes')
            for network_item in objects:
                niceCxBuilder._add_network_attributes_from_fragment(network_item)

        # ===================
        # NODES
        # ===================
        if 'nodes' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'nodes')
            for node_item in objects:
                niceCxBuilder._add_node_from_fragment(node_item)

        # ===================
        # EDGES
        # ===================
        if 'edges' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'edges')
            for edge_item in objects:
                niceCxBuilder._add_edge_from_fragment(edge_item)

        # ===================
        # NODE ATTRIBUTES
        # ===================
        if 'nodeAttributes' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'nodeAttributes')
            for att in objects:
                niceCxBuilder._add_node_attribute_from_fragment(att)

        # ===================
        # EDGE ATTRIBUTES
        # ===================
        if 'edgeAttributes' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'edgeAttributes')
            for att in objects:
                niceCxBuilder._add_edge_attribute_from_fragment(att)

        # ===================
        # CITATIONS
        # ===================
        if 'citations' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'citations')
            for cit in objects:
                niceCxBuilder._add_citation_from_fragment(cit)

        # ===================
        # SUPPORTS
        # ===================
        if 'supports' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'supports')
            for sup in objects:
                niceCxBuilder._add_supports_from_fragment(sup)

        # ===================
        # EDGE SUPPORTS
        # ===================
        if 'edgeSupports' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'edgeSupports')
            for add_this_edge_sup in objects:
                niceCxBuilder._add_edge_supports_from_fragment(add_this_edge_sup)

        # ===================
        # NODE CITATIONS
        # ===================
        if 'nodeCitations' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'nodeCitations')
            for node_cit in objects:
                niceCxBuilder._add_node_citations_from_fragment(node_cit)

        # ===================
        # EDGE CITATIONS
        # ===================
        if 'edgeCitations' in available_aspects:
            objects = niceCxBuilder.get_frag_from_list_by_key(cx, 'edgeCitations')
            for edge_cit in objects:
                niceCxBuilder._add_edge_citations_from_fragment(edge_cit)

        # ===================
        # OPAQUE ASPECTS
        # ===================
        for oa in opaque_aspects:
            #TODO - Add context to builder
            if oa == '@context':
                objects = niceCxBuilder.get_frag_from_list_by_key(cx, oa)
                niceCxBuilder.set_context(objects) #nice_cx.set_namespaces(objects)
            else:
                objects = niceCxBuilder.get_frag_from_list_by_key(cx, oa)
                niceCxBuilder.add_opaque_aspect(oa, objects)

        return niceCxBuilder.get_nice_cx()
    else:
        raise Exception('CX is empty')
示例#9
0
def create_nice_cx_from_networkx(G):
    """
    Creates a NiceCXNetwork based on a networkx graph. The resulting NiceCXNetwork
    contains the nodes edges and their attributes from the networkx graph and also
    preserves the graph 'pos' attribute as a CX cartesian coordinates aspect.
    Node name is taken from the networkx node id. Node 'represents' is
    taken from the networkx node attribute 'represents'

    :param G: networkx graph
    :type G: networkx graph
    :return: NiceCXNetwork
    :rtype: NiceCXNetwork
    """

    niceCxBuilder = NiceCXBuilder()
    if G is None:
        raise Exception('Networkx input is empty')

    my_nicecx = NiceCXNetwork()

    if G.graph.get('name'):
        my_nicecx.set_name(G.graph.get('name'))
    else:
        my_nicecx.set_name('created from networkx')

    my_nicecx.add_metadata_stub('networkAttributes')


    #=========================================
    # Check to see if the node label is same
    # (case insensitive) as 'name' attribute
    #=========================================
    #use_node_label = False
    #for n, d in G.nodes_iter(data=True):
    #    if not isinstance(n, int) and d and d.get('name'):
    #        if n.lower() == d.get('name').lower():
    #            use_node_label = True

    #    break

    for n, d in G.nodes(data=True):
        # =============
        # ADD NODES
        # =============
        #if d and d.get('name'):
        #    if isinstance(n, int):
        #        node_id = niceCxBuilder.add_node(name=d.get('name'),represents=d.get('name'), id=n, map_node_ids=True)
        #    else:
        #        # If networkx node is of type string then maybe the 'name' atribute is no longer accurate
        #        if use_node_label:
        #            node_id = niceCxBuilder.add_node(name=n,represents=n, map_node_ids=True)
        #        else:
        #            node_id = niceCxBuilder.add_node(name=d.get('name'),represents=d.get('name'), map_node_ids=True)
        #else:
        if isinstance(n, int):
            node_id = niceCxBuilder.add_node(name=n,represents=d.get('represents'), id=n, map_node_ids=True)
        else:
            node_id = niceCxBuilder.add_node(name=n, represents=d.get('represents'), map_node_ids=True)

        # ======================
        # ADD NODE ATTRIBUTES
        # ======================
        for k, v in d.items():
            use_this_value, attr_type = niceCxBuilder._infer_data_type(v, split_string=True)

            if k == 'citation' and not isinstance(use_this_value, list):
                use_this_value = [use_this_value]
                attr_type = 'list_of_string'
            if use_this_value is not None:
                niceCxBuilder.add_node_attribute(node_id, k, use_this_value, type=attr_type)

    index = 0
    for u, v, d in G.edges(data=True):
        # =============
        # ADD EDGES
        # =============
        if d.get('interaction') is None or d.get('interaction') == 'null':
            interaction = 'neighbor-of'
        else:
            interaction = d.get('interaction')

        if isinstance(u, int):
            niceCxBuilder.add_edge(source=u, target=v, interaction=interaction, id=index)
        else:
            niceCxBuilder.add_edge(source=niceCxBuilder.node_id_lookup.get(u), target=niceCxBuilder.node_id_lookup.get(v),
                               interaction=interaction, id=index)

        # ==============================
        # ADD EDGE ATTRIBUTES
        # ==============================
        for k, val in d.items():
            if k != 'interaction':
                use_this_value, attr_type = niceCxBuilder._infer_data_type(val, split_string=True)

                if k == 'citation' and not isinstance(use_this_value, list):
                    use_this_value = [use_this_value]
                    attr_type = 'list_of_string'

                if use_this_value is not None:
                    niceCxBuilder.add_edge_attribute(property_of=index, name=k, values=use_this_value, type=attr_type)

        index += 1

    if hasattr(G, 'pos'):
        aspect = _create_cartesian_coordinates_aspect_from_networkx(G)
        niceCxBuilder.add_opaque_aspect('cartesianLayout', aspect)

    return niceCxBuilder.get_nice_cx()
示例#10
0
def create_nice_cx_from_networkx(G):
    """
    Creates a :py:class:`~ndex2.nice_cx_network.NiceCXNetwork` based on a
    :class:`networkx.Graph` graph.

    .. versionchanged:: 3.5.0
       Major refactor to fix multiple bugs #83, #84, #90

    .. code-block:: python

        import ndex2
        import networkx as nx

        G = nx.Graph()
        G.add_node(1, someval=1.5, name='node 1')
        G.add_node(2, someval=2.5, name='node 2')
        G.add_edge(1, 2, weight=5)

        print(ndex2.create_nice_cx_from_networkx(G).to_cx())

    The resulting :py:class:`~ndex2.nice_cx_network.NiceCXNetwork`
    contains the nodes, edges and their attributes from the
    :class:`networkx.Graph`
    graph and also preserves the graph 'pos' attribute as a CX
    cartesian coordinates aspect
    :py:const:`~ndex2.constants.CARTESIAN_LAYOUT_ASPECT`
    with the values of `Y` inverted

    Description of how conversion is performed:

    **Network:**

    * Network name is set value of ``G.graph.get('name')`` or to
      ``created from networkx by ndex2.create_nice_cx_networkx()`` if
      `name` is ``None`` or not present

    **Nodes:**

    * Node id is value of ``n`` from this for loop:
      ``for n, d G.nodes(data=True):`` if ``n`` is **NOT** an
      :py:class:`int`, new ids starting from ``0`` are used

    * Node name is value of `name` attribute on the node or is
      set to id of node if `name` is not present.

    * Node `represents` is value of `represents` attribute on the
      node or set is to node `name` if ``None`` or not present

    **Edges:**

    * Interaction is value of `interaction` attribute on the edge
      or is set to ``neighbor-of`` if ``None`` or not present

    .. note::

        Data types are inferred by using :py:func:`isinstance` and
        converted to corresponding CX data types. For list items,
        only the 1st item is examined to determine type

    :param G: Graph to convert
    :type G: :class:`networkx.Graph`
    :raises Exception: if **G** parameter is ``None`` or there is another error
                       in conversion
    :return: Converted network
    :rtype: :py:class:`~ndex2.nice_cx_network.NiceCXNetwork`
    """
    cx_builder = NiceCXBuilder()
    if G is None:
        raise Exception('Networkx input is empty')

    network_name = G.graph.get('name')
    if network_name is not None:
        cx_builder.set_name(network_name)
    else:
        cx_builder.set_name('created from networkx by '
                            'ndex2.create_nice_cx_networkx()')

    for n, d in G.nodes(data=True):
        if isinstance(n, int):
            n_name = d.get('name')
            if n_name is None:
                n_name = str(n)
            node_id = cx_builder.add_node(name=n_name,
                                          represents=d.get('represents'),
                                          id=n,
                                          map_node_ids=True)
        else:
            node_id = cx_builder.add_node(name=n,
                                          represents=d.get('represents'),
                                          map_node_ids=True)

        # ======================
        # ADD NODE ATTRIBUTES
        # ======================
        for k, v in d.items():

            # if node attribute is 'name' skip it cause that will be used
            # for name of node, also skip 'represents'
            # fix for https://github.com/ndexbio/ndex2-client/issues/84
            if k == 'name' or k == 'represents':
                continue

            use_this_value, attr_type = cx_builder._infer_data_type(
                v, split_string=False)

            # This might go away, waiting on response to
            # https://ndexbio.atlassian.net/browse/UD-2181
            if k == 'citation' and not isinstance(use_this_value, list):
                use_this_value = [str(use_this_value)]
                attr_type = constants.LIST_OF_STRING
            if use_this_value is not None:
                cx_builder.add_node_attribute(node_id,
                                              k,
                                              use_this_value,
                                              type=attr_type)

    index = 0
    for u, v, d in G.edges(data=True):
        # =============
        # ADD EDGES
        # =============
        if d.get('interaction') is None or d.get('interaction') == 'null':
            interaction = 'neighbor-of'
        else:
            interaction = d.get('interaction')

        if isinstance(u, int):
            cx_builder.add_edge(source=u,
                                target=v,
                                interaction=interaction,
                                id=index)
        else:
            cx_builder.add_edge(source=cx_builder.node_id_lookup.get(u),
                                target=cx_builder.node_id_lookup.get(v),
                                interaction=interaction,
                                id=index)

        # ==============================
        # ADD EDGE ATTRIBUTES
        # ==============================
        for k, val in d.items():
            if k == 'interaction':
                continue
            use_this_value, attr_type = cx_builder._infer_data_type(
                val, split_string=False)

            # This might go away, waiting on response to
            # https://ndexbio.atlassian.net/browse/UD-2181
            if k == 'citation' and not isinstance(use_this_value, list):
                use_this_value = [str(use_this_value)]
                attr_type = constants.LIST_OF_STRING

            if use_this_value is not None:
                cx_builder.add_edge_attribute(property_of=index,
                                              name=k,
                                              values=use_this_value,
                                              type=attr_type)

        index += 1

    if hasattr(G, 'pos'):
        aspect = _create_cartesian_coordinates_aspect_from_networkx(G)
        cx_builder.add_opaque_aspect(constants.CARTESIAN_LAYOUT_ASPECT, aspect)

    return cx_builder.get_nice_cx()