Exemplo n.º 1
0
def test_create_ports_dict():
    doc = create_port_doc()
    model = doc.getModel()

    comp.create_ports(
        model,
        portType=comp.PORT_TYPE_PORT,
        idRefs={
            "extern_port": "extern",
            "A_port": "A",
            "C_port": "C",
            "EX_A_port": "EX_A",
            "EX_C_port": "EX_C",
        },
    )

    comp_model = model.getPlugin("comp")
    ports = comp_model.getListOfPorts()
    assert ports is not None
    assert comp_model.getNumPorts() == 5
    assert comp_model.getPort("extern_port")
    assert comp_model.getPort("A_port")
    assert comp_model.getPort("C_port")
    assert comp_model.getPort("EX_A_port")
    assert comp_model.getPort("EX_C_port")
    assert comp_model.getPort("test") is None
Exemplo n.º 2
0
def create_dfba_species(model, model_fba, compartment_id, hasOnlySubstanceUnits=False, unit_amount=None, create_port=True,
                        exclude_sids=[]):
    """ Add DFBA species and compartments from fba model to model.
    Creates the dynamic species and respetive compartments with
    the necessary ports.
    This is used in the bounds submodel, update submodel and the
    and top model.

    :param model:
    :param model_fba:
    :return:
    """
    objects = []
    port_sids = []
    ex_rids = utils.find_exchange_reactions(model_fba)
    for ex_rid in ex_rids:

        r = model_fba.getReaction(ex_rid)
        sid = r.getReactant(0).getSpecies()
        if sid in exclude_sids:
            continue

        s = model_fba.getSpecies(sid)
        # exchange species to create
        objects.append(
            fac.Species(sid=sid, name=s.getName(), initialConcentration=1.0, substanceUnit=unit_amount,
                        hasOnlySubstanceUnits=hasOnlySubstanceUnits, compartment=compartment_id)
        )
        # port of exchange species
        port_sids.append(sid)

    fac.create_objects(model, objects)
    if create_port:
        comp.create_ports(model, idRefs=port_sids)
Exemplo n.º 3
0
def bounds_model(sbml_file, directory, doc_fba, annotations=None):
    """"
    Bounds model.
    """
    bounds_notes = notes.format("""
    <h2>BOUNDS submodel</h2>
    <p>Submodel for dynamically calculating the flux bounds.
    The dynamically changing flux bounds are the input to the
    FBA model.</p>
    """)
    doc = builder.template_doc_bounds(settings.MODEL_ID)
    model = doc.getModel()
    utils.set_model_info(model,
                         notes=bounds_notes,
                         creators=creators,
                         units=units, main_units=main_units)

    builder.create_dfba_dt(model, step_size=DT_SIM, time_unit=UNIT_TIME, create_port=True)

    # compartment
    compartment_id = 'extern'
    builder.create_dfba_compartment(model, compartment_id=compartment_id, unit_volume=UNIT_VOLUME,
                                    create_port=True)

    # species
    model_fba = doc_fba.getModel()
    builder.create_dfba_species(model, model_fba, compartment_id=compartment_id, unit_amount=UNIT_AMOUNT,
                                hasOnlySubstanceUnits=True, create_port=True)

    # exchange bounds
    builder.create_exchange_bounds(model, model_fba=model_fba, unit_flux=UNIT_FLUX, create_ports=True)


    objects = [
        # exchange bounds
        # FIXME: readout the FBA network bounds
        mc.Parameter(sid="lb_default", value=builder.LOWER_BOUND_DEFAULT, unit=UNIT_FLUX, constant=True),

        # kinetic bound parameter & calculation
        mc.Parameter(sid='ub_R1', value=1.0, unit=UNIT_FLUX, constant=False, sboTerm="SBO:0000625"),
        mc.Parameter(sid='k1', value=-0.2, unit="per_s", name="k1", constant=False),
        mc.RateRule(sid="ub_R1", value="k1*ub_R1"),

        # bound assignment rules
        mc.AssignmentRule(sid="lb_EX_A", value='max(lb_default, -A/dt)'),
        mc.AssignmentRule(sid="lb_EX_C", value='max(lb_default, -C/dt)'),
    ]
    mc.create_objects(model, objects)

    # ports
    comp.create_ports(model, portType=comp.PORT_TYPE_PORT,
                      idRefs=["ub_R1"])
    if annotations:
        annotation.annotate_sbml_doc(doc, annotations)
    sbmlio.write_sbml(doc, filepath=os.path.join(directory, sbml_file), validate=True)
Exemplo n.º 4
0
def bounds_model(sbml_file, directory, doc_fba, annotations=None):
    """"
    Bounds model.
    """
    bounds_notes = notes.format("""
    <h2>BOUNDS submodel</h2>
    <p>Submodel for dynamically calculating the flux bounds.
    The dynamically changing flux bounds are the input to the
    FBA model.</p>
    """)
    doc = builder.template_doc_bounds(settings.MODEL_ID)
    model = doc.getModel()
    utils.set_model_info(model,
                         notes=bounds_notes,
                         creators=creators,
                         units=units, main_units=main_units)

    builder.create_dfba_dt(model, step_size=DT_SIM, time_unit=UNIT_TIME, create_port=True)

    # compartment
    compartment_id = 'extern'
    builder.create_dfba_compartment(model, compartment_id=compartment_id, unit_volume=UNIT_VOLUME,
                                    create_port=True)

    # species
    model_fba = doc_fba.getModel()
    builder.create_dfba_species(model, model_fba, compartment_id=compartment_id, unit_amount=UNIT_AMOUNT,
                                hasOnlySubstanceUnits=True, create_port=True)

    # exchange bounds
    builder.create_exchange_bounds(model, model_fba=model_fba, unit_flux=UNIT_FLUX, create_ports=True)


    objects = [
        # exchange bounds
        # FIXME: readout the FBA network bounds
        mc.Parameter(sid="lb_default", value=builder.LOWER_BOUND_DEFAULT, unit=UNIT_FLUX, constant=True),

        # kinetic bound parameter & calculation
        mc.Parameter(sid='ub_R1', value=1.0, unit=UNIT_FLUX, constant=False, sboTerm="SBO:0000625"),
        mc.Parameter(sid='k1', value=-0.2, unit="per_s", name="k1", constant=False),
        mc.RateRule(sid="ub_R1", value="k1*ub_R1"),

        # bound assignment rules
        mc.AssignmentRule(sid="lb_EX_A", value='max(lb_default, -A/dt)'),
        mc.AssignmentRule(sid="lb_EX_C", value='max(lb_default, -C/dt)'),
    ]
    mc.create_objects(model, objects)

    # ports
    comp.create_ports(model, portType=comp.PORT_TYPE_PORT,
                      idRefs=["ub_R1"])
    if annotations:
        annotator.annotate_sbml_doc(doc, annotations)
    sbmlio.write_sbml(doc, filepath=os.path.join(directory, sbml_file), validate=True)
Exemplo n.º 5
0
def create_exchange_reaction(model, species_id, exchange_type=EXCHANGE, flux_unit=None):
    """ Factory method to create exchange reactions for species in the FBA model.

    Creates the exchange reaction, the upper and lower bounds,
    and the ports.

    :param model:
    :param species_id:
    :param exchange_type:
    :param flux_unit:

    :return:
    """
    if exchange_type not in [EXCHANGE, EXCHANGE_IMPORT, EXCHANGE_EXPORT]:
        raise ValueError("Wrong exchange_type: {}".format(exchange_type))

    # id (e.g. EX_A)
    ex_rid = EXCHANGE_REACTION_PREFIX + species_id
    lb_id = LOWER_BOUND_PREFIX + ex_rid
    ub_id = UPPER_BOUND_PREFIX + ex_rid

    lb_value = LOWER_BOUND_DEFAULT
    ub_value = UPPER_BOUND_DEFAULT
    if exchange_type == EXCHANGE_IMPORT:
        # negative flux through exchange reaction
        ub_value = ZERO_BOUND
    if exchange_type == EXCHANGE_EXPORT:
        lb_value = ZERO_BOUND

    parameters = [
        fac.Parameter(sid=lb_id,
                      value=lb_value,
                      unit=flux_unit, constant=True, sboTerm=FLUX_BOUND_SBO),
        fac.Parameter(sid=ub_id,
                      value=ub_value,
                      unit=flux_unit, constant=True, sboTerm=FLUX_BOUND_SBO),
    ]
    fac.create_objects(model, parameters)

    # exchange reactions are all reversible (it depends on the bounds in which direction they operate)
    ex_r = fac.create_reaction(model, rid=ex_rid, reversible=True,
                               reactants={species_id: 1}, sboTerm=EXCHANGE_REACTION_SBO)

    # exchange bounds
    fbc.set_flux_bounds(ex_r, lb=lb_id, ub=ub_id)

    # create ports
    comp.create_ports(model, portType=comp.PORT_TYPE_PORT,
                      idRefs=[ex_rid, lb_id, ub_id])

    return ex_r
Exemplo n.º 6
0
def create_dfba_dt(model, step_size=DT_SIM, time_unit=None, create_port=True):
    """ Creates the dt parameter in the model.

    :param model:
    :param create_port:
    :param step_size:
    :param time_unit:
    :return:
    """
    objects = [
        fac.Parameter(sid=DT_ID, value=step_size, unit=time_unit, constant=True, sboTerm=DT_SBO)
    ]
    fac.create_objects(model, objects)
    if create_port:
        comp.create_ports(model, idRefs=[DT_ID])
Exemplo n.º 7
0
def create_exchange_bounds(model_bounds,
                           model_fba,
                           unit_flux=None,
                           create_ports=True):
    """ Creates the exchange reaction flux bounds in the bounds model.

    :param model_bounds: the bounds model submodel
    :param model_fba: the fba submodel
    :param unit_flux: unit of fluxes
    :param create_ports: should ports be created.
    :return:
    """
    ex_rids = utils.find_exchange_reactions(model_fba)
    objects = []
    port_sids = []
    for ex_rid, sid in ex_rids.items():
        r = model_fba.getReaction(ex_rid)

        # lower & upper bound parameters
        r_fbc = r.getPlugin(SBML_FBC_NAME)
        lb_id = r_fbc.getLowerFluxBound()
        lb_value = model_fba.getParameter(lb_id).getValue()
        ub_id = r_fbc.getUpperFluxBound()
        ub_value = model_fba.getParameter(ub_id).getValue()

        # This creates the dynamical flux bound variables which are initialized with the
        # constant fba bounds
        objects.extend([
            # for assignments
            Parameter(sid=lb_id,
                      value=lb_value,
                      unit=unit_flux,
                      constant=False,
                      sboTerm=FLUX_BOUND_SBO),
            Parameter(sid=ub_id,
                      value=ub_value,
                      unit=unit_flux,
                      constant=False,
                      sboTerm=FLUX_BOUND_SBO),
        ])
        port_sids.extend([lb_id, ub_id])

    # create bounds
    factory.create_objects(model_bounds, objects)
    # create ports
    if create_ports:
        comp.create_ports(model_bounds, idRefs=port_sids)
Exemplo n.º 8
0
def test_create_ports_list():
    doc = create_port_doc()
    model = doc.getModel()

    comp.create_ports(model, portType=comp.PORT_TYPE_PORT,
                      idRefs=["extern", "A", "C", "EX_A", "EX_C"])

    comp_model = model.getPlugin("comp")
    ports = comp_model.getListOfPorts()
    assert ports is not None
    assert comp_model.getNumPorts() == 5
    assert comp_model.getPort("extern_port")
    assert comp_model.getPort("A_port")
    assert comp_model.getPort("C_port")
    assert comp_model.getPort("EX_A_port")
    assert comp_model.getPort("EX_C_port")
    assert comp_model.getPort("test") is None
Exemplo n.º 9
0
def create_dfba_compartment(model, compartment_id, unit_volume=None, create_port=True):
    """ Creates the main compartment for the dynamic species.

    :param model:
    :param compartment_id: id
    :param unit_volume: unit
    :param create_port: flag to create port
    :return: created libsbml.Compartment
    """
    objects = [
        fac.Compartment(sid=compartment_id, value=1.0, unit=unit_volume, constant=True, name=compartment_id,
                        spatialDimensions=3),
    ]
    c = fac.create_objects(model, objects)
    if create_port:
        comp.create_ports(model, idRefs=[compartment_id])
    return c
Exemplo n.º 10
0
def create_biomass_species(model, sid, unit, cf_unit, compartment_id, create_port=True):
    """ Creates the biomass species.

    :param model:
    :return:
    """
    # FIXME: implement
    raise NotImplementedError
    pass

    fac.create_objects(model, [
        fac.Parameter(sid='cf_X', value=1.0, unit="g_per_mmol", name="biomass conversion factor", constant=True),
        fac.Species(sid='X', value=0.001, compartment='c', name='biomass', substanceUnit='g', hasOnlySubstanceUnits=True,
                    conversionFactor='cf_biomass')
    ])
    if create_port:
        comp.create_ports(model, idRefs=['X'])
Exemplo n.º 11
0
def test_create_ports_list() -> None:
    doc: libsbml.SBMLDocument = create_port_doc()
    model = doc.getModel()

    comp.create_ports(
        model, portType=comp.PORT_TYPE_PORT, idRefs=["extern", "A", "C", "EX_A", "EX_C"]
    )

    comp_model = model.getPlugin("comp")
    ports = comp_model.getListOfPorts()
    assert ports is not None
    assert comp_model.getNumPorts() == 5
    assert comp_model.getPort("extern_port")
    assert comp_model.getPort("A_port")
    assert comp_model.getPort("C_port")
    assert comp_model.getPort("EX_A_port")
    assert comp_model.getPort("EX_C_port")
    assert comp_model.getPort("test") is None
Exemplo n.º 12
0
def create_update_parameter(model, sid, unit_flux):
    """ Creates the update parameter.
    The update parameter correspond to the flux parameters
    in the top model.

    :param model:
    :type model:
    :param sid:
    :type sid:
    :param unit_flux:
    :type unit_flux:
    :return:
    :rtype:
    """
    pid = FLUX_PARAMETER_PREFIX + sid
    parameter = fac.Parameter(sid=pid, value=1.0, constant=True, unit=unit_flux, sboTerm=UPDATE_PARAMETER_SBO)
    fac.create_objects(model, [parameter])
    # create port
    comp.create_ports(model, portType=comp.PORT_TYPE_PORT,
                      idRefs=[pid])
    return pid
Exemplo n.º 13
0
def create_exchange_bounds(model_bounds, model_fba, unit_flux=None, create_ports=True):
    """ Creates the exchange reaction flux bounds in the bounds model.

    :param model_bounds: the bounds model submodel
    :param model_fba: the fba submodel
    :param unit_flux: unit of fluxes
    :param create_ports: should ports be created.
    :return:
    """
    ex_rids = utils.find_exchange_reactions(model_fba)
    objects = []
    port_sids = []
    for ex_rid, sid in ex_rids.items():
        r = model_fba.getReaction(ex_rid)

        # lower & upper bound parameters
        r_fbc = r.getPlugin(SBML_FBC_NAME)
        lb_id = r_fbc.getLowerFluxBound()
        lb_value = model_fba.getParameter(lb_id).getValue()
        ub_id = r_fbc.getUpperFluxBound()
        ub_value = model_fba.getParameter(ub_id).getValue()

        # This creates the dynamical flux bound variables which are initialized with the
        # constant fba bounds
        objects.extend([
            # for assignments
            fac.Parameter(sid=lb_id, value=lb_value, unit=unit_flux, constant=False, sboTerm=FLUX_BOUND_SBO),
            fac.Parameter(sid=ub_id, value=ub_value, unit=unit_flux, constant=False, sboTerm=FLUX_BOUND_SBO),
        ])
        port_sids.extend([lb_id, ub_id])

    # create bounds
    fac.create_objects(model_bounds, objects)
    # create ports
    if create_ports:
        comp.create_ports(model_bounds, idRefs=port_sids)
Exemplo n.º 14
0
def update_exchange_reactions(model, flux_unit):
    """ Updates existing exchange reaction in FBA model.

    Sets all the necessary information and checks that correct.
    This is mainly used to prepare the exchange reactions of metabolites.

    :param flux_unit:
    :param model:
    :return:
    """

    # mapping of bounds to reactions
    bounds_dict = dict()

    ex_rids = utils.find_exchange_reactions(model)
    for ex_rid in ex_rids:
        r = model.getReaction(ex_rid)

        # make reversible
        if not r.getReversible():
            r.setReversible(True)
            logging.info("Exchange reaction set reversible: {}".format(
                r.getId()))

        # fix ids for exchange reactions
        sref = r.getReactant(0)
        sid = sref.getSpecies()
        rid = r.getId()
        if rid != EXCHANGE_REACTION_PREFIX + sid:
            r.setId(EXCHANGE_REACTION_PREFIX + sid)
            logging.warning("Exchange reaction fixd id: {} -> {}".format(
                rid, EXCHANGE_REACTION_PREFIX + sid))

    # new lookup necessary, due to possible changed ids
    ex_rids = utils.find_exchange_reactions(model)
    for ex_rid in ex_rids:
        r = model.getReaction(ex_rid)
        fbc_r = r.getPlugin(SBML_FBC_NAME)
        # store bounds in dictionary for value lookup
        for f_bound in ["getLowerFluxBound", "getUpperFluxBound"]:
            bound_id = getattr(fbc_r, f_bound).__call__()
            bound = model.getParameter(bound_id)
            bounds_dict[bound_id] = bound.getValue()

    # create unique bounds for exchange reactions
    for ex_rid in ex_rids:
        r = model.getReaction(ex_rid)
        fbc_r = r.getPlugin(SBML_FBC_NAME)
        lb_value = model.getParameter(fbc_r.getLowerFluxBound()).getValue()
        ub_value = model.getParameter(fbc_r.getUpperFluxBound()).getValue()

        lb_id = LOWER_BOUND_PREFIX + ex_rid
        ub_id = UPPER_BOUND_PREFIX + ex_rid

        parameters = [
            Parameter(sid=lb_id,
                      value=lb_value,
                      unit=flux_unit,
                      constant=True,
                      sboTerm=FLUX_BOUND_SBO),
            Parameter(sid=ub_id,
                      value=ub_value,
                      unit=flux_unit,
                      constant=True,
                      sboTerm=FLUX_BOUND_SBO),
        ]
        factory.create_objects(model, parameters)

        # set bounds
        fbc.set_flux_bounds(r, lb=lb_id, ub=ub_id)

        # create ports for bounds and reaction
        comp.create_ports(model,
                          portType=comp.PORT_TYPE_PORT,
                          idRefs=[ex_rid, lb_id, ub_id])

    # check all the exchange reactions
    for ex_rid in ex_rids:
        check_exchange_reaction(model, ex_rid)
Exemplo n.º 15
0
def fba_model(sbml_file, directory, annotations=None):
    """ FBA model
    
    :param sbml_file: output file name 
    :param directory: output directory
    :return: SBMLDocument
    """
    fba_notes = notes.format("""
    <h2>FBA submodel</h2>
    <p>DFBA fba submodel. Unbalanced metabolites are encoded via exchange fluxes.</p>
    """)
    doc = builder.template_doc_fba(settings.MODEL_ID)
    model = doc.getModel()
    utils.set_model_info(model,
                         notes=fba_notes,
                         creators=creators,
                         units=units, main_units=main_units)

    objects = [
        # compartments
        mc.Compartment(sid='extern', value=1.0, unit=UNIT_VOLUME, constant=True, name='external compartment',
                       spatialDimensions=3),
        mc.Compartment(sid='cell', value=1.0, unit=UNIT_VOLUME, constant=True, name='cell', spatialDimensions=3),
        mc.Compartment(sid='membrane', value=1.0, unit=UNIT_AREA, constant=True, name='membrane', spatialDimensions=2),

        # exchange species
        mc.Species(sid='A', name="A", initialConcentration=0, substanceUnit=UNIT_AMOUNT, hasOnlySubstanceUnits=True,
                   compartment="extern"),
        mc.Species(sid='C', name="C", initialConcentration=0, substanceUnit=UNIT_AMOUNT, hasOnlySubstanceUnits=True,
                   compartment="extern"),

        # internal species
        mc.Species(sid='B1', name="B1", initialConcentration=0, substanceUnit=UNIT_AMOUNT, hasOnlySubstanceUnits=True,
                   compartment="cell"),
        mc.Species(sid='B2', name="B2", initialConcentration=0, substanceUnit=UNIT_AMOUNT, hasOnlySubstanceUnits=True,
                   compartment="cell"),

        # bounds
        mc.Parameter(sid="ub_R1", value=1.0, unit=UNIT_FLUX, constant=True, sboTerm=builder.FLUX_BOUND_SBO),
        mc.Parameter(sid="zero", value=0.0, unit=UNIT_FLUX, constant=True, sboTerm=builder.FLUX_BOUND_SBO),
        mc.Parameter(sid="ub_default", value=builder.UPPER_BOUND_DEFAULT, unit=UNIT_FLUX, constant=True,
                     sboTerm=builder.FLUX_BOUND_SBO),
    ]
    mc.create_objects(model, objects)

    # reactions
    r1 = mc.create_reaction(model, rid="R1", name="A import (R1)", fast=False, reversible=True,
                            reactants={"A": 1}, products={"B1": 1}, compartment='membrane')
    r2 = mc.create_reaction(model, rid="R2", name="B1 <-> B2 (R2)", fast=False, reversible=True,
                            reactants={"B1": 1}, products={"B2": 1}, compartment='cell')
    r3 = mc.create_reaction(model, rid="R3", name="B2 export (R3)", fast=False, reversible=True,
                            reactants={"B2": 1}, products={"C": 1}, compartment='membrane')

    # flux bounds
    fbc.set_flux_bounds(r1, lb="zero", ub="ub_R1")
    fbc.set_flux_bounds(r2, lb="zero", ub="ub_default")
    fbc.set_flux_bounds(r3, lb="zero", ub="ub_default")

    # exchange reactions
    builder.create_exchange_reaction(model, species_id="A", flux_unit=UNIT_FLUX)
    builder.create_exchange_reaction(model, species_id="C", flux_unit=UNIT_FLUX)

    # objective function
    model_fbc = model.getPlugin("fbc")
    fbc.create_objective(model_fbc, oid="R3_maximize", otype="maximize",
                        fluxObjectives={"R3": 1.0}, active=True)

    # create ports for kinetic bounds
    comp.create_ports(model, portType=comp.PORT_TYPE_PORT,
                      idRefs=["ub_R1"])

    # write SBML
    if annotations:
        annotation.annotate_sbml_doc(doc, annotations)
    sbmlio.write_sbml(doc, filepath=os.path.join(directory, sbml_file), validate=True)
    return doc
Exemplo n.º 16
0
def fba_model(sbml_file, directory, annotations=None):
    """ FBA model
    
    :param sbml_file: output file name 
    :param directory: output directory
    :return: SBMLDocument
    """
    fba_notes = notes.format("""
    <h2>FBA submodel</h2>
    <p>DFBA fba submodel. Unbalanced metabolites are encoded via exchange fluxes.</p>
    """)
    doc = builder.template_doc_fba(settings.MODEL_ID)
    model = doc.getModel()
    utils.set_model_info(model,
                         notes=fba_notes,
                         creators=creators,
                         units=units,
                         main_units=main_units)

    objects = [
        # compartments
        mc.Compartment(sid='extern',
                       value=1.0,
                       unit=UNIT_VOLUME,
                       constant=True,
                       name='external compartment',
                       spatialDimensions=3),
        mc.Compartment(sid='cell',
                       value=1.0,
                       unit=UNIT_VOLUME,
                       constant=True,
                       name='cell',
                       spatialDimensions=3),
        mc.Compartment(sid='membrane',
                       value=1.0,
                       unit=UNIT_AREA,
                       constant=True,
                       name='membrane',
                       spatialDimensions=2),

        # exchange species
        mc.Species(sid='A',
                   name="A",
                   initialConcentration=0,
                   substanceUnit=UNIT_AMOUNT,
                   hasOnlySubstanceUnits=True,
                   compartment="extern"),
        mc.Species(sid='C',
                   name="C",
                   initialConcentration=0,
                   substanceUnit=UNIT_AMOUNT,
                   hasOnlySubstanceUnits=True,
                   compartment="extern"),

        # internal species
        mc.Species(sid='B1',
                   name="B1",
                   initialConcentration=0,
                   substanceUnit=UNIT_AMOUNT,
                   hasOnlySubstanceUnits=True,
                   compartment="cell"),
        mc.Species(sid='B2',
                   name="B2",
                   initialConcentration=0,
                   substanceUnit=UNIT_AMOUNT,
                   hasOnlySubstanceUnits=True,
                   compartment="cell"),

        # bounds
        mc.Parameter(sid="ub_R1",
                     value=1.0,
                     unit=UNIT_FLUX,
                     constant=True,
                     sboTerm=builder.FLUX_BOUND_SBO),
        mc.Parameter(sid="zero",
                     value=0.0,
                     unit=UNIT_FLUX,
                     constant=True,
                     sboTerm=builder.FLUX_BOUND_SBO),
        mc.Parameter(sid="ub_default",
                     value=builder.UPPER_BOUND_DEFAULT,
                     unit=UNIT_FLUX,
                     constant=True,
                     sboTerm=builder.FLUX_BOUND_SBO),
    ]
    mc.create_objects(model, objects)

    # reactions
    r1 = mc.create_reaction(model,
                            rid="R1",
                            name="A import (R1)",
                            fast=False,
                            reversible=True,
                            reactants={"A": 1},
                            products={"B1": 1},
                            compartment='membrane')
    r2 = mc.create_reaction(model,
                            rid="R2",
                            name="B1 <-> B2 (R2)",
                            fast=False,
                            reversible=True,
                            reactants={"B1": 1},
                            products={"B2": 1},
                            compartment='cell')
    r3 = mc.create_reaction(model,
                            rid="R3",
                            name="B2 export (R3)",
                            fast=False,
                            reversible=True,
                            reactants={"B2": 1},
                            products={"C": 1},
                            compartment='membrane')

    # flux bounds
    fbc.set_flux_bounds(r1, lb="zero", ub="ub_R1")
    fbc.set_flux_bounds(r2, lb="zero", ub="ub_default")
    fbc.set_flux_bounds(r3, lb="zero", ub="ub_default")

    # exchange reactions
    builder.create_exchange_reaction(model,
                                     species_id="A",
                                     flux_unit=UNIT_FLUX)
    builder.create_exchange_reaction(model,
                                     species_id="C",
                                     flux_unit=UNIT_FLUX)

    # objective function
    model_fbc = model.getPlugin("fbc")
    fbc.create_objective(model_fbc,
                         oid="R3_maximize",
                         otype="maximize",
                         fluxObjectives={"R3": 1.0},
                         active=True)

    # create ports for kinetic bounds
    comp.create_ports(model, portType=comp.PORT_TYPE_PORT, idRefs=["ub_R1"])

    # write SBML
    if annotations:
        annotator.annotate_sbml_doc(doc, annotations)
    sbml.write_sbml(doc,
                    filepath=os.path.join(directory, sbml_file),
                    validate=True)
    return doc
Exemplo n.º 17
0
def update_exchange_reactions(model, flux_unit):
    """ Updates existing exchange reaction in FBA model.

    Sets all the necessary information and checks that correct.
    This is mainly used to prepare the exchange reactions of metabolites.

    :param flux_unit:
    :param model:
    :return:
    """

    # mapping of bounds to reactions
    bounds_dict = dict()

    ex_rids = utils.find_exchange_reactions(model)
    for ex_rid in ex_rids:
        r = model.getReaction(ex_rid)

        # make reversible
        if not r.getReversible():
            r.setReversible(True)
            logging.info("Exchange reaction set reversible: {}".format(r.getId()))

        # fix ids for exchange reactions
        sref = r.getReactant(0)
        sid = sref.getSpecies()
        rid = r.getId()
        if rid != EXCHANGE_REACTION_PREFIX + sid:
            r.setId(EXCHANGE_REACTION_PREFIX + sid)
            logging.warning("Exchange reaction fixd id: {} -> {}".format(rid, EXCHANGE_REACTION_PREFIX + sid))

    # new lookup necessary, due to possible changed ids
    ex_rids = utils.find_exchange_reactions(model)
    for ex_rid in ex_rids:
        r = model.getReaction(ex_rid)
        fbc_r = r.getPlugin(SBML_FBC_NAME)
        # store bounds in dictionary for value lookup
        for f_bound in ["getLowerFluxBound", "getUpperFluxBound"]:
            bound_id = getattr(fbc_r, f_bound).__call__()
            bound = model.getParameter(bound_id)
            bounds_dict[bound_id] = bound.getValue()

    # create unique bounds for exchange reactions
    for ex_rid in ex_rids:
        r = model.getReaction(ex_rid)
        fbc_r = r.getPlugin(SBML_FBC_NAME)
        lb_value = model.getParameter(fbc_r.getLowerFluxBound()).getValue()
        ub_value = model.getParameter(fbc_r.getUpperFluxBound()).getValue()

        lb_id = LOWER_BOUND_PREFIX + ex_rid
        ub_id = UPPER_BOUND_PREFIX + ex_rid

        parameters = [
            fac.Parameter(sid=lb_id,
                          value=lb_value,
                          unit=flux_unit, constant=True, sboTerm=FLUX_BOUND_SBO),
            fac.Parameter(sid=ub_id,
                          value=ub_value,
                          unit=flux_unit, constant=True, sboTerm=FLUX_BOUND_SBO),
        ]
        fac.create_objects(model, parameters)

        # set bounds
        fbc.set_flux_bounds(r, lb=lb_id, ub=ub_id)

        # create ports for bounds and reaction
        comp.create_ports(model, portType=comp.PORT_TYPE_PORT,
                          idRefs=[ex_rid, lb_id, ub_id])

    # check all the exchange reactions
    for ex_rid in ex_rids:
        check_exchange_reaction(model, ex_rid)