コード例 #1
0
def reactions2nodes(get_r_comp, graph, id2n, input_model):
    # get_sp_comp = lambda _id: graph[COMPARTMENT][id2n[_id]]
    get_sp_comp = lambda _id: input_model.getSpecies(_id).getCompartment()

    def link_reaction_to_species(reaction_node,
                                 sp_ref,
                                 all_comps,
                                 is_reactant=True,
                                 reversible=False):
        s_id = sp_ref.getSpecies()

        all_comps.add(get_sp_comp(s_id))

        # todo:
        if SKIP_UBS and s_id not in id2n:
            return
        species_node = id2n[s_id]
        e = graph.addEdge(species_node,
                          reaction_node) if is_reactant else graph.addEdge(
                              reaction_node, species_node)
        stoich = sp_ref.getStoichiometry()
        if not stoich:
            stoich = sp_ref.getStoichiometryMath()
        if not stoich:
            stoich = 1
        graph[STOICHIOMETRY][e] = stoich
        graph[NAME][e] = input_model.getSpecies(s_id).getName()
        ub = graph[UBIQUITOUS][species_node]
        graph[UBIQUITOUS][e] = ub
        graph[REVERSIBLE][e] = reversible and not ub

    for r in input_model.getListOfReactions():
        name = r.getName()
        # do not add fake isa reactions
        # if name.find("isa ") != -1 and 1 == r.getNumReactants() == r.getNumProducts() and get_sp_comp(
        # r.getListOfReactants().get(0).getSpecies()) == get_sp_comp(
        # 		r.getListOfProducts().get(0).getSpecies()):
        # 	continue

        n = graph.addNode()
        graph[TERM][n] = get_gene_association(r)
        graph[ID][n] = r.getId()
        graph[NAME][n] = name
        graph[TYPE][n] = TYPE_REACTION
        graph[REVERSIBLE][n] = r.getReversible()

        graph[VIEW_SHAPE][n] = REACTION_SHAPE
        graph[VIEW_SIZE][n] = get_n_size(graph, n)

        all_comps = set()
        for sp_ref in r.getListOfReactants():
            link_reaction_to_species(n,
                                     sp_ref,
                                     all_comps,
                                     is_reactant=True,
                                     reversible=r.getReversible())
        for sp_ref in r.getListOfProducts():
            link_reaction_to_species(n,
                                     sp_ref,
                                     all_comps,
                                     is_reactant=False,
                                     reversible=r.getReversible())

        graph[TRANSPORT][n] = len(all_comps) > 1
        graph[COMPARTMENT_ID][n] = get_r_comp(all_comps)
コード例 #2
0
def save_as_cytoscape_json(n2lo, model, out_json, ub_sp_ids):
    """
    Converts a model with the given node and edge layout to a json file readable by Cytoscape.
    :param ub_sp_ids: collection of ubiquitous species ids
    :param n2lo: node layout as a dictionary    {node_id: ((x, y), (w, h)) if node is not ubiquitous
                                                else node_id : {r_ids: ((x, y), (w, h)) for r_ids of
                                                reactions using each duplicated metabolite}}
    :param model: SBML model
    :param out_json: path where to save the resulting json file.
    """
    # let's scale the map so that a minimal node has a width == 16 (so that the labels fit)
    h_min, (x_shift, y_shift), _ = get_layout_characteristics(n2lo)
    scale_factor = MARGIN * 1.0 / h_min if h_min else 1
    (x_shift, y_shift) = shift(scale((x_shift, y_shift), scale_factor), MARGIN, MARGIN)

    nodes, edges = [], []

    for comp in model.getListOfCompartments():
        c_id = comp.getId()
        c_name = get_name(comp)
        if c_id in n2lo:
            (x, y), (w, h) = transform(n2lo[c_id], x_shift, y_shift, scale_factor)
            nodes.append(get_node(x=x + w / 2, y=y + h / 2, z=-1,
                                  **{NAME: c_name, ID: c_id, WEIGHT: w, HEIGHT: h, TYPE: TYPE_COMPARTMENT}))

    for species in model.getListOfSpecies():
        s_id = species.getId()
        s_name = get_name(species)
        glyph_type = UNSPECIFIED_ENTITY
        sbo_term = species.getSBOTermID()
        if sbo_term:
            sbo_term = sbo_term.upper().strip()
            if sbo_term in SBO_2_GLYPH_TYPE:
                glyph_type = SBO_2_GLYPH_TYPE[sbo_term]
        if s_id in n2lo:
            if isinstance(n2lo[s_id], dict):
                elements = n2lo[s_id].items()
            else:
                elements = [('', n2lo[s_id])]
            for r_ids, coords in elements:
                if not r_ids or next((it for it in (model.getReaction(r_id) for r_id in r_ids) if it), False):
                    (x, y), (w, h) = transform(coords, x_shift, y_shift, scale_factor)
                    nodes.append(
                        get_node(x=x + w / 2, y=y + h / 2, z=1,
                                 **{GLYPH_TYPE: glyph_type, ID: "%s_%s" % (s_id, '_'.join(r_ids)) if r_ids else s_id,
                                    COMPARTMENT: species.getCompartment(), NAME: s_name, WEIGHT: w, HEIGHT: h,
                                    TYPE: TYPE_SPECIES, UBIQUITOUS: s_id in ub_sp_ids,
                                    'ChEBI': get_chebi_id(species)}))

    def get_sref_id(s_id):
        if isinstance(n2lo[s_id], dict):
            for r_ids in n2lo[s_id].keys():
                if r_id in r_ids:
                    return "%s_%s" % (s_id, '_'.join(r_ids))
        return s_id

    for reaction in model.getListOfReactions():
        r_id = reaction.getId()
        r_name = get_name(reaction)
        ga = get_gene_association(reaction)
        if r_id in n2lo:
            (x, y), (w, h) = transform(n2lo[r_id], x_shift, y_shift, scale_factor)
            nodes.append(get_node(x=x + w / 2, y=y + h / 2, z=1,
                                  **{ID: r_id, NAME: ga, WEIGHT: w, HEIGHT: h, TYPE: TYPE_REACTION,
                                     REVERSIBLE: reaction.getReversible(),
                                     UBIQUITOUS:
                                         next((False for s_id in chain(get_reactants(reaction), get_products(reaction))
                                               if s_id not in ub_sp_ids), True),
                                     'genes': ga, 'r_name': r_name}))

            for s_id in get_reactants(reaction):
                edges.append(get_edge(**{ID: "%s_%s" % (r_id, s_id), SOURCE: r_id, TARGET: get_sref_id(s_id),
                                             NAME: '%s is a substrate of %s' % (get_name(model.getSpecies(s_id)), r_name),
                                             UBIQUITOUS: s_id in ub_sp_ids, INTERACTION: SUBSTRATE}))

            for s_id in get_products(reaction):
                edges.append(get_edge(**{ID: "%s_%s" % (r_id, s_id), SOURCE: r_id, TARGET: get_sref_id(s_id),
                                             NAME: '%s is a product of %s' % (get_name(model.getSpecies(s_id)), r_name),
                                             UBIQUITOUS: s_id in ub_sp_ids, INTERACTION: PRODUCT}))

    save_cyjson(nodes, edges, out_json)
コード例 #3
0
ファイル: main.py プロジェクト: annazhukova/mod_gen
                                    ch_term.get_id() if ch_term else ''])
            row += 1
            unm_l += 1
    print unm_l

    ws = wb.create_sheet(2, "Reaction Groups")
    row = 1
    add_values(ws, row, 1, ["Group Id", "Id", "Name", "Formula", "Gene Association"], HEADER_STYLE)
    row += 1
    processed_r_ids = set()
    for (g_id, g_name), r_ids in sorted(clu2r_ids.items(), key=lambda ((g_id, g_name), _): g_id):
        add_values(ws, row, 1, [g_id])
        for r_id in sorted(r_ids, key=lambda r_id: r_id[r_id.find('__'):]):
            r = model.getReaction(r_id)
            add_values(ws, row, 2, [r_id, r.getName(), get_sbml_r_formula(model, r, show_compartments=True, show_metabolite_ids=True),
                                    get_gene_association(r)])
            row += 1
        processed_r_ids |= r_ids
    ws = wb.create_sheet(3, "Ungrouped reactions")
    row = 1
    add_values(ws, row, 1, ["Id", "Name", "Formula", "Gene Association"], HEADER_STYLE)
    row += 1
    unm_l = 0
    for r in sorted(model.getListOfReactions(), key=lambda r: r.getId()[r.getId().find('__'):]):
        if r.getId() not in processed_r_ids:
            add_values(ws, row, 1, [r.getId(), r.getName(), get_sbml_r_formula(model, r, show_compartments=True, show_metabolite_ids=True),
                                    get_gene_association(r)])
            row += 1
            unm_l += 1
    print unm_l