Example #1
0
def model(request, solver):
    if request.param == "empty":
        model = Model(id_or_model=request.param, name=request.param)
    elif request.param == "textbook":
        model = read_sbml_model(join(dirname(__file__), "data",
                                     "EcoliCore.xml.gz"))
    else:
        builder = getattr(request.module, "MODEL_REGISTRY")[request.param]
        model = builder(Model(id_or_model=request.param, name=request.param))
    model.solver = solver
    return model
Example #2
0
    def cobra_model(self, name, reversible=True, bound=1000):
        """Constructs a cobra model for the reconstruction.

        Args:
            name (str): The name of the cobra model.
            reversible (Optiona[bool]): Whether the returned model should
                be reversible. Default is yes.
            bound (Optional[float]): The default flux bound for the reactions.

        Returns:
            A cobra model containing the reconstruction. The original objective
            will be conserved if it is still included in the model.
        """
        new_mod = Model(name)
        m = deepcopy(self.model)
        for rid in self.conf:
            r = m.reactions.get_by_id(rid)
            if self.conf[rid] == 3 and "mock" not in r.notes:
                if r not in new_mod.reactions:
                    r.upper_bound = bound
                    new_mod.add_reaction(r)
                if "reflection" in r.notes:
                    rev = m.reactions.get_by_id(r.notes["reflection"])
                    if rev not in new_mod.reactions:
                        rev.upper_bound = bound
                        new_mod.add_reaction(rev)

        if reversible:
            revert_to_reversible(new_mod)
        still_valid = True
        for r in self.objective:
            still_valid &= (self.conf[r.id] == 3)
        if still_valid:
            new_mod.change_objective(self.objective)
        return new_mod
Example #3
0
def build_universal_model(path,
                          use_cache=True,
                          cache_location='.metacyc_universal.json'):
    """
    Constructs a universal model from all the reactions in the metacyc database

    :param path: path to folder containing metacyc dat files
    :param use_cache: optionally store the resulting model in cached form
    :return:
    """
    try:
        if use_cache and os.path.exists(cache_location):
            model = load_model(cache_location)
            return model
    except (IOError, TypeError):
        pass  # This means cached model couldn't be loaded, we'll create a new one

    db = parse_db(path)
    model = Model()
    for reaction_id in db['reactions']:
        try:
            add_reaction(model, reaction_id, db)
        except KeyError:
            # Exception handling ignores badly formatted reactions
            pass

    if use_cache:
        save_json_model(model, cache_location)

    return model
Example #4
0
    def get_ros_rxns(self,
                     rxn_file='spont_ros_rxns_me2.csv',
                     col_name='Rxn Name',
                     col_h2o2='Putative h2o2 Rxn',
                     col_o2s='Putative o2s Rxn',
                     verbosity=1):
        """
        Get ROS rxns but don't alter stoichiometry
        """
        me = self.me
        # Temp model object that holds all the ROS reactions
        mdl = Model('ros')
        # Load Brynildsen's reactions
        df_ros = pd.read_csv(
            self.pathto(rxn_file)).dropna(subset=[col_h2o2, col_o2s])

        ros_rxns = []

        for irow, row in df_ros.iterrows():
            rxn_name = row[col_name]
            if not me.stoichiometric_data.has_id(rxn_name):
                continue

            stoich = me.stoichiometric_data.get_by_id(rxn_name)
            for rxn in stoich.parent_reactions:
                # Make sure that ROS only generated, not consumed spontaneously
                if rxn.reverse:
                    if verbosity > 0:
                        print 'Skipping reverse rxn:', rxn.id
                else:
                    ros_rxns.append(rxn)

        self.ros_rxns = ros_rxns

        return ros_rxns
Example #5
0
 def test_solve_mip(self):
     solver = self.solver
     if not hasattr(solver, "_SUPPORTS_MILP") or not solver._SUPPORTS_MILP:
         self.skipTest("no milp support")
     cobra_model = Model('MILP_implementation_test')
     constraint = Metabolite("constraint")
     constraint._bound = 2.5
     x = Reaction("x")
     x.lower_bound = 0.
     x.objective_coefficient = 1.
     x.add_metabolites({constraint: 2.5})
     y = Reaction("y")
     y.lower_bound = 0.
     y.objective_coefficient = 1.
     y.add_metabolites({constraint: 1.})
     cobra_model.add_reactions([x, y])
     float_sol = solver.solve(cobra_model)
     # add an integer constraint
     y.variable_kind = "integer"
     int_sol = solver.solve(cobra_model)
     self.assertAlmostEqual(float_sol.f, 2.5)
     self.assertAlmostEqual(float_sol.x_dict["y"], 2.5)
     self.assertEqual(int_sol.status, "optimal")
     self.assertAlmostEqual(int_sol.f, 2.2)
     self.assertAlmostEqual(int_sol.x_dict["y"], 2.0)
Example #6
0
 def test_change_coefficient(self):
     solver = self.solver
     c = Metabolite("c")
     c._bound = 6
     x = Reaction("x")
     x.lower_bound = 1.
     y = Reaction("y")
     y.lower_bound = 0.
     x.add_metabolites({c: 1})
     #y.add_metabolites({c: 1})
     z = Reaction("z")
     z.add_metabolites({c: 1})
     z.objective_coefficient = 1
     m = Model("test_model")
     m.add_reactions([x, y, z])
     # change an existing coefficient
     lp = solver.create_problem(m)
     solver.solve_problem(lp)
     sol1 = solver.format_solution(lp, m)
     solver.change_coefficient(lp, 0, 0, 2)
     solver.solve_problem(lp)
     sol2 = solver.format_solution(lp, m)
     self.assertAlmostEqual(sol1.f, 5.0)
     self.assertAlmostEqual(sol2.f, 4.0)
     # change a new coefficient
     z.objective_coefficient = 0.
     y.objective_coefficient = 1.
     lp = solver.create_problem(m)
     solver.change_coefficient(lp, 0, 1, 2)
     solver.solve_problem(lp)
     solution = solver.format_solution(lp, m)
     self.assertAlmostEqual(solution.x_dict["y"], 2.5)
Example #7
0
    def __define_instance_variables(self):
        """
        Define instance variables

        :return:
        """

        self.__universal_model = Model("universal_model")
        self.__swapped = []

        self.__compounds_ontology = CompoundsDBAccessor()

        self.__compoundsAnnotationConfigs = file_utilities.read_conf_file(
            COMPOUNDS_ANNOTATION_CONFIGS_PATH)
        self.__reactionsAnnotationConfigs = file_utilities.read_conf_file(
            REACTIONS_ANNOTATION_CONFIGS_PATH)

        self.__compoundsIdConverter = CompoundsIDConverter()

        self.__compounds_revisor = CompoundsRevisor(self.model,
                                                    self.__universal_model)

        biocyc.set_organism("meta")

        self.mapper = ModelMapper(self.model,
                                  self.__compoundsAnnotationConfigs,
                                  self.__compoundsIdConverter)

        self.__compounds_revisor.set_model_mapper(self.mapper)

        self.granulator = Granulator(self.model, self.mapper,
                                     self.__database_format,
                                     self.__compoundsIdConverter,
                                     self.__compoundsAnnotationConfigs)
Example #8
0
def opposing_model() -> Model:
    """Generate a toy model with opposing reversible reactions.

    This toy model ensures that two opposing reversible reactions do not
    appear as blocked.

    """
    test_model = Model("opposing")
    v1 = Reaction("v1")
    v2 = Reaction("v2")
    v3 = Reaction("v3")
    v4 = Reaction("v4")

    test_model.add_reactions([v1, v2, v3, v4])

    v1.reaction = "-> 2 A"
    v2.reaction = "A -> C"  # Later made reversible via bounds.
    v3.reaction = "D -> C"  # Later made reversible via bounds.
    v4.reaction = "D ->"

    v1.bounds = 0.0, 3.0
    v2.bounds = -3.0, 3.0
    v3.bounds = -3.0, 3.0
    v4.bounds = 0.0, 3.0

    test_model.objective = v4
    return test_model
Example #9
0
 def test_inequality(self):
     # The space enclosed by the constraints is a 2D triangle with
     # vertexes as (3, 0), (1, 2), and (0, 1)
     solver = self.solver
     # c1 encodes y - x > 1 ==> y > x - 1
     # c2 encodes y + x < 3 ==> y < 3 - x
     c1 = Metabolite("c1")
     c2 = Metabolite("c2")
     x = Reaction("x")
     x.lower_bound = 0
     y = Reaction("y")
     y.lower_bound = 0
     x.add_metabolites({c1: -1, c2: 1})
     y.add_metabolites({c1: 1, c2: 1})
     c1._bound = 1
     c1._constraint_sense = "G"
     c2._bound = 3
     c2._constraint_sense = "L"
     m = Model()
     m.add_reactions([x, y])
     # test that optimal values are at the vertices
     m.change_objective("x")
     self.assertAlmostEqual(solver.solve(m).f, 1.0)
     self.assertAlmostEqual(solver.solve(m).x_dict["y"], 2.0)
     m.change_objective("y")
     self.assertAlmostEqual(solver.solve(m).f, 3.0)
     self.assertAlmostEqual(
         solver.solve(m, objective_sense="minimize").f, 1.0)
Example #10
0
    def swap_from_generic(self,
                          targets: list,
                          components: list,
                          same_components=False,
                          progress_bar_processes_left=1):
        """
        Swap compounds from a generic target and components. The algorithm acts as follows:

            1st: Starts for identifying the reactions present in the requested biosynthetic pathway;

            2nd: Creates a virtual model;

            3rd: Calls the granulator to granulate the biosynthetic pathway;

        :param list<str> targets: list of lipid targets
        :param list<str> components: list of components
        :param bool same_components: boolean for same or mix of components
        :param int progress_bar_processes_left:
        :return:
        """

        targets_generic_ontology_id, components_ont_ids = \
            self.transform_targets_and_components_into_boimmg_ids(targets,components)

        self.__virtual_model = Model("virtual_model")

        self.__add_hydrogen_to_virtual_model()

        self.__virtual_model_mapper = ModelMapper(
            self.__virtual_model, self.__compoundsAnnotationConfigs,
            self.__compoundsIdConverter)

        self.__virtual_compounds_revisor = CompoundsRevisor(
            self.__virtual_model, self.__universal_model,
            self.__compoundsAnnotationConfigs)

        self.__virtual_compounds_revisor.set_model_mapper(
            self.__virtual_model_mapper)

        self.granulator.set_virtual_model(self.__virtual_model,
                                          self.__virtual_model_mapper,
                                          self.__virtual_compounds_revisor)

        for target_generic_ontology_id in targets_generic_ontology_id:

            biosynthesis_reactions = self.granulator.identify_biosynthesis_pathway(
                target_generic_ontology_id)

            self.__biosynthesis_reactions = deepcopy(biosynthesis_reactions)

            self.__add_new_reactions_to_virtual_model(
                self.__biosynthesis_reactions)

            self.__model.remove_reactions(biosynthesis_reactions)

            self.granulator.granulate(target_generic_ontology_id,
                                      components_ont_ids, same_components,
                                      progress_bar_processes_left)

        self.generateISAreactions()
Example #11
0
def create_model_from_rxns(name, rxns_d5, objective_rxn_id):
    model = Model(name)
    for rxn_d4 in rxns_d5:
        new_rxn = create_rxn(rxn_d4)
        model.add_reactions([new_rxn])
    model.objective = objective_rxn_id
    return model
Example #12
0
def test_model_history(tmp_path):
    """Testing reading and writing of ModelHistory."""
    model = Model("test")
    model._sbml = {
        "creators": [{
            "familyName": "Mustermann",
            "givenName": "Max",
            "organisation": "Muster University",
            "email": "*****@*****.**",
        }]
    }

    sbml_path = join(str(tmp_path), "test.xml")
    with open(sbml_path, "w") as f_out:
        write_sbml_model(model, f_out)

    with open(sbml_path, "r") as f_in:
        model2 = read_sbml_model(f_in)

    assert "creators" in model2._sbml
    assert len(model2._sbml["creators"]) is 1
    c = model2._sbml["creators"][0]
    assert c["familyName"] == "Mustermann"
    assert c["givenName"] == "Max"
    assert c["organisation"] == "Muster University"
    assert c["email"] == "*****@*****.**"
Example #13
0
    def __init__(self,
                 thermo_data=None,
                 model=Model(),
                 name=None,
                 temperature=std.TEMPERATURE_0,
                 min_ph=std.MIN_PH,
                 max_ph=std.MAX_PH):
        """

        :param float temperature: the temperature (K) at which to perform the calculations
        :param dict thermo_data: The thermodynamic database
        :type temperature: float
        """

        LCSBModel.__init__(self, model, name)

        self.logger = get_bistream_logger('ME model' + str(self.name))

        self.TEMPERATURE = temperature
        self.thermo_data = thermo_data
        self.parent = model

        # CONSTANTS
        self.MAX_pH = max_ph
        self.MIN_pH = min_ph

        self._init_thermo()

        self.logger.info('# Model initialized with units {} and temperature {} K'  \
                    .format(self.thermo_unit, self.TEMPERATURE))
Example #14
0
def online_example():
    model = Model('example_model')
    reaction = Reaction('30AS140')
    reaction.name = '3 oxoacyl acyl carrier protein synthase n C140 '
    reaction.subsystem = 'Cell Envelope Biosynthesis'
    reaction.lower_bound = 0.  # This is the default
    reaction.upper_bound = 1000.  # This is the default

    #creating the metabolites
    ACP_c = Metabolite('ACP_c',
                       formula='C11H21N2O7PRS',
                       name='acyl-carrier-protein',
                       compartment='c')

    omrsACP_c = Metabolite('3omrsACP_c',
                           formula='C25H45N2O9PRS',
                           name='3-Oxotetradecanoyl-acyl-carrier-protein',
                           compartment='c')
    co2_c = Metabolite('co2_c', formula='CO2', name='CO2', compartment='c')

    malACP_c = Metabolite('malACP_c',
                          formula='C14H22N2O10PRS',
                          name='Malonyl-acyl-carrier-protein',
                          compartment='c')
    h_c = Metabolite('h_c', formula='H', name='H', compartment='c')

    ddcaACP_c = Metabolite('ddcaACP_c',
                           formula='C23H43N2O8PRS',
                           name='Dodecanoyl-ACP-n-C120ACP',
                           compartment='c')

    #Adding stoichiometric coefficients to reaction.
    reaction.add_metabolites({
        malACP_c: -1.0,
        h_c: -1.0,
        ddcaACP_c: -1.0,
        co2_c: 1.0,
        ACP_c: 1.0,
        omrsACP_c: 1.0
    })

    #Gene Reaction Rule: A Boolean representation of the gene
    # Requirements for this reaction to be active.
    reaction.gene_reaction_rule = '( STM2378 or STM1197 )'

    #Adding reaction to the model:
    model.add_reactions([reaction])

    # Creating an objective for the model:
    model.objective = '30AS140'

    #Solution object has several attributes
    solution = model.optimize()

    print(solution.objective_value)  # The objective value
    print(solution.status)  # The status from the linear programming solver
    print(solution.fluxes
          )  # A pandas series with flux indexed by reaction identifier.
    print(solution.shadow_prices
          )  # A pandas series with shadow price indexed by the metabolite id
Example #15
0
 def test_loopless(self):
     try:
         solver = get_solver_name(mip=True)
     except:
         self.skipTest("no MILP solver found")
     test_model = Model()
     test_model.add_metabolites(Metabolite("A"))
     test_model.add_metabolites(Metabolite("B"))
     test_model.add_metabolites(Metabolite("C"))
     EX_A = Reaction("EX_A")
     EX_A.add_metabolites({test_model.metabolites.A: 1})
     DM_C = Reaction("DM_C")
     DM_C.add_metabolites({test_model.metabolites.C: -1})
     v1 = Reaction("v1")
     v1.add_metabolites({test_model.metabolites.A: -1,
                         test_model.metabolites.B: 1})
     v2 = Reaction("v2")
     v2.add_metabolites({test_model.metabolites.B: -1,
                         test_model.metabolites.C: 1})
     v3 = Reaction("v3")
     v3.add_metabolites({test_model.metabolites.C: -1,
                         test_model.metabolites.A: 1})
     DM_C.objective_coefficient = 1
     test_model.add_reactions([EX_A, DM_C, v1, v2, v3])
     feasible_sol = construct_loopless_model(test_model).optimize()
     v3.lower_bound = 1
     infeasible_sol = construct_loopless_model(test_model).optimize()
     self.assertEqual(feasible_sol.status, "optimal")
     self.assertEqual(infeasible_sol.status, "infeasible")
Example #16
0
def minimized_shuffle(small_model):
    model = small_model.copy()
    chosen = sample(list(set(model.reactions) - set(model.exchanges)), 10)
    new = Model("minimized_shuffle")
    new.add_reactions(chosen)
    LOGGER.debug("'%s' has %d metabolites, %d reactions, and %d genes.",
                 new.id, new.metabolites, new.reactions, new.genes)
    return new
Example #17
0
def gapfillfunc(model, database, runs):
    """ This function gapfills the model using the growMatch algorithm that is built into cobrapy

    Returns a dictionary which contains the pertinent information about the gapfilled model such as
    the reactions added, the major ins and outs of the system and the objective value of the gapfilled
    model.
    This function calls on two other functions sort_and_deduplicate to assure the uniqueness of the solutions
    and findInsAndOuts to find major ins and outs of the model when gapfilled when certain reactions
    Args:
        model: a model in SBML format
        database: an external database database of reactions to be used for gapfilling
        runs: integer number of iterations the gapfilling algorithm will run through
    """
    # Read model from SBML file and create Universal model to add reactions to
    func_model = create_cobra_model_from_sbml_file(model)
    Universal = Model("Universal Reactions")
    f = open(database, 'r')
    next(f)
    rxn_dict = {}
    # Creates a dictionary of the reactions from the tab delimited database, storing their ID and the reaction string
    for line in f:
        rxn_items = line.split('\t')
        rxn_dict[rxn_items[0]] = rxn_items[6], rxn_items[1]
    # Adds the reactions from the above dictionary to the Universal model
    for rxnName in rxn_dict.keys():
        rxn = Reaction(rxnName)
        Universal.add_reaction(rxn)
        rxn.reaction = rxn_dict[rxnName][0]
        rxn.name = rxn_dict[rxnName][1]

    # Runs the growMatch algorithm filling gaps from the Universal model
    result = flux_analysis.growMatch(func_model, Universal, iterations=runs)
    resultShortened = sort_and_deduplicate(uniq(result))
    rxns_added = {}
    rxn_met_list = []
    print resultShortened
    for x in range(len(resultShortened)):
        func_model_test = deepcopy(func_model)
        # print func_model_test.optimize().f
        for i in range(len(resultShortened[x])):
            addID = resultShortened[x][i].id
            rxn = Reaction(addID)
            func_model_test.add_reaction(rxn)
            rxn.reaction = resultShortened[x][i].reaction
            rxn.reaction = re.sub('\+ dummy\S+', '', rxn.reaction)
            rxn.name = resultShortened[x][i].name
            mets = re.findall('cpd\d{5}_c0|cpd\d{5}_e0', rxn.reaction)
            for met in mets:
                y = func_model_test.metabolites.get_by_id(met)
                rxn_met_list.append(y.name)
        obj_value = func_model_test.optimize().f
        fluxes = findInsAndOuts(func_model_test)
        sorted_outs = fluxes[0]
        sorted_ins = fluxes[1]
        rxns_added[x] = resultShortened[x], obj_value, sorted_ins, sorted_outs, rxn_met_list
        rxn_met_list = []
    return rxns_added
Example #18
0
 def setUp(self):
     self.model = Model("test model")
     A = Metabolite("A")
     r = Reaction("r")
     r.add_metabolites({A: -1})
     r.lower_bound = -1000
     r.upper_bound = 1000
     self.model.add_reaction(r)
     convert_to_irreversible(self.model)
     self.model.remove_reactions(["r"])
Example #19
0
def tiny_toy_model():
    tiny = Model("Toy Model")
    m1 = Metabolite("M1")
    d1 = Reaction("ex1")
    d1.add_metabolites({m1: -1})
    d1.upper_bound = 0
    d1.lower_bound = -1000
    tiny.add_reactions([d1])
    tiny.objective = "ex1"
    return tiny
Example #20
0
def dataframe_to_model(df_reactions,df_metabolites,model_id="myModel"):
    model = Model(model_id)
    metabolites_list=list()
    for index,row in df_metabolites.iterrows():
        compartment=row[MET_COMPARTMENT_IDX] if not pd.isna(row[MET_COMPARTMENT_IDX]) else DEFAULT_COMPARTMENT
        if not pd.isnull(row[MET_ID_IDX]):
            metabolite=Metabolite(id=row[MET_ID_IDX],
                  formula=row[MET_FORMULA_IDX],
                  name=row[MET_NAME_IDX],
                  compartment=compartment,
                  charge=row[MET_CHARGE_IDX])
            metabolites_list.append(metabolite)
    # Add metabolites to the model
        else:
            print("Metabolite: Error on line "+str(index)+", there is no ID");
    try:
        model.add_metabolites(metabolites_list)
    except Exception as e:
        print("Error adding metabolites")
        raise e

    for index,row in df_reactions.iterrows():
        if not pd.isna(row[RXN_ID_IDX]):
            lb=row[RXN_LOWER_BOUND_IDX] if not pd.isna(row[RXN_LOWER_BOUND_IDX]) else DEFAULT_LOWER_BOUND
            ub=row[RXN_UPPER_BOUND_IDX] if not pd.isna(row[RXN_UPPER_BOUND_IDX]) else DEFAULT_UPPER_BOUND
            objective_coeff=row[RXN_OBJECTIVE_IDX] if not pd.isna(row[RXN_OBJECTIVE_IDX]) else DEFAULT_OBJECTIVE_COEFF

            try:
                reaction=Reaction(id=row[RXN_ID_IDX],
                                 name=row[RXN_NAME_IDX],
                                 subsystem=row[RXN_SUBSYSTEM_IDX]
                                 )
                # Add Genes
                if not pd.isna(row[RXN_GPR_IDX]):
                    reaction.gene_reaction_rule=row[RXN_GPR_IDX]
                # Add the reaction to the model
                model.add_reaction(reaction)
                # Add the reaction formula            
            except:
                print("Reaction: Error on line "+str(index)+" "+str(row[RXN_ID_IDX]))
            

            try:
                model.reactions.get_by_id(row[RXN_ID_IDX]).build_reaction_from_string(row[RXN_REACTION_IDX])
            except Exception as e:
                print("Error parsing %s string '%s'" % (repr(row), row[RXN_ID_IDX]))
                raise e 

            # Include the objective coefficient and bounds
            model.reactions.get_by_id(row[RXN_ID_IDX]).objective_coefficient=objective_coeff
            model.reactions.get_by_id(row[RXN_ID_IDX]).lower_bound=lb
            model.reactions.get_by_id(row[RXN_ID_IDX]).upper_bound=ub
        else:
            print("The row: "+str(index)+" is empty or doesn't have id.")
    return(model)
Example #21
0
 def test_quadratic(self):
     solver = self.solver
     if not hasattr(solver, "set_quadratic_objective"):
         self.skipTest("no qp support")
     c = Metabolite("c")
     c._bound = 2
     x = Reaction("x")
     x.objective_coefficient = -0.5
     x.lower_bound = 0.
     y = Reaction("y")
     y.objective_coefficient = -0.5
     y.lower_bound = 0.
     x.add_metabolites({c: 1})
     y.add_metabolites({c: 1})
     m = Model()
     m.add_reactions([x, y])
     lp = self.solver.create_problem(m)
     quadratic_obj = scipy.sparse.eye(2) * 2
     solver.set_quadratic_objective(lp, quadratic_obj)
     solver.solve_problem(lp, objective_sense="minimize")
     solution = solver.format_solution(lp, m)
     self.assertEqual(solution.status, "optimal")
     # Respecting linear objectives also makes the objective value 1.
     self.assertAlmostEqual(solution.f, 1.)
     self.assertAlmostEqual(solution.x_dict["y"], 1.)
     self.assertAlmostEqual(solution.x_dict["y"], 1.)
     # When the linear objectives are removed the objective value is 2.
     solver.change_variable_objective(lp, 0, 0.)
     solver.change_variable_objective(lp, 1, 0.)
     solver.solve_problem(lp, objective_sense="minimize")
     solution = solver.format_solution(lp, m)
     self.assertEqual(solution.status, "optimal")
     self.assertAlmostEqual(solution.f, 2.)
     # test quadratic from solve function
     solution = solver.solve(m,
                             quadratic_component=quadratic_obj,
                             objective_sense="minimize")
     self.assertEqual(solution.status, "optimal")
     self.assertAlmostEqual(solution.f, 1.)
     c._bound = 6
     z = Reaction("z")
     x.objective_coefficient = 0.
     y.objective_coefficient = 0.
     z.lower_bound = 0.
     z.add_metabolites({c: 1})
     m.add_reaction(z)
     solution = solver.solve(m,
                             quadratic_component=scipy.sparse.eye(3),
                             objective_sense="minimize")
     # should be 12 not 24 because 1/2 (V^T Q V)
     self.assertEqual(solution.status, "optimal")
     self.assertAlmostEqual(solution.f, 6)
     self.assertAlmostEqual(solution.x_dict["x"], 2, places=6)
     self.assertAlmostEqual(solution.x_dict["y"], 2, places=6)
     self.assertAlmostEqual(solution.x_dict["z"], 2, places=6)
Example #22
0
    def test_gapfilling(self):
        try:
            solver = get_solver_name(mip=True)
        except:
            self.skipTest("no MILP solver found")
        m = Model()
        m.add_metabolites(map(Metabolite, ["a", "b", "c"]))
        r = Reaction("EX_A")
        m.add_reaction(r)
        r.add_metabolites({m.metabolites.a: 1})
        r = Reaction("r1")
        m.add_reaction(r)
        r.add_metabolites({m.metabolites.b: -1, m.metabolites.c: 1})
        r = Reaction("DM_C")
        m.add_reaction(r)
        r.add_metabolites({m.metabolites.c: -1})
        r.objective_coefficient = 1

        U = Model()
        r = Reaction("a2b")
        U.add_reaction(r)
        r.build_reaction_from_string("a --> b", verbose=False)
        r = Reaction("a2d")
        U.add_reaction(r)
        r.build_reaction_from_string("a --> d", verbose=False)

        # GrowMatch
        result = gapfilling.growMatch(m, U)[0]
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].id, "a2b")
        # SMILEY
        result = gapfilling.SMILEY(m, "b", U)[0]
        self.assertEqual(len(result), 1)
        self.assertEqual(result[0].id, "a2b")

        # 2 rounds of GrowMatch with exchange reactions
        result = gapfilling.growMatch(m, None, ex_rxns=True, iterations=2)
        self.assertEqual(len(result), 2)
        self.assertEqual(len(result[0]), 1)
        self.assertEqual(len(result[1]), 1)
        self.assertEqual({i[0].id for i in result},
                         {"SMILEY_EX_b", "SMILEY_EX_c"})
Example #23
0
 def test_add_metabolite(self):
     model = Model('bigg_test')
     cobrababel.add_bigg_metabolites([cobrababel.get_bigg_metabolite('h2o_c', 'iAF1260')], model)
     assert model.metabolites[0].id == 'h2o_c'
     assert model.metabolites[0].name == 'H2O'
     assert model.metabolites[0].compartment == 'c'
     cobrababel.add_bigg_metabolites([cobrababel.get_bigg_metabolite('10fthf')], model)
     assert model.metabolites[1].id == '10fthf_c'
     assert model.metabolites[1].name == '10-Formyltetrahydrofolate'
     assert model.metabolites[1].compartment == 'c'
     assert model.compartments['c'] == 'cytosol'
Example #24
0
def get_reference(mod, newR, delete_unbalanced, verbose=1):
    from cobra import Model, Reaction, Metabolite
    import pandas
    import re
    import os
    dir = os.path.dirname(__file__)
    seedmDB = pandas.read_csv(dir + "/../dat/seed_metabolites.tsv", sep="\t")
    seedrDB = pandas.read_csv(dir + "/../dat/seed_reactions.tsv", sep="\t")

    #refdb  = seedrDB.loc[seedrDB['abbreviation'].isin(newR)] # vmh
    refdb = seedrDB.loc[(seedrDB['id'].isin(newR)) &
                        (seedrDB['status'] == "OK"
                         )]  # only choose reaction which have status okay
    refmod = Model("reaction_database")
    Rmod = [re.sub("_.*$", "", r.id) for r in mod.reactions]
    print "Consider", len(refdb.index), "reactions"
    Cold = 0
    Calready = 0
    for i, row in refdb.iterrows():
        #rid = row["abbreviation"] # vmh
        rid = row["id"]
        if row["is_obsolete"] == 1:  # do not add old reactions
            Cold += 1
            continue
        #if rid in Rmod: # vmh
        elif rid in Rmod:
            Calready += 1
            continue
        r = Reaction(rid + "_c0")  # default seed model have compartment tag
        refmod.add_reaction(r)
        #rstr = row["formula"] # vmh
        rstr = row["equation"]
        #rstr = row["code"]
        rstr = rstr.replace("[0]", "_c0").replace("[1]", "_e0").replace(
            "[3]", "_p0").replace("[2]", "_m0")
        r.build_reaction_from_string(rstr, verbose=0)
        #r.reaction = rstr
    for m in refmod.metabolites:
        if verbose == 2:
            print m.id
        mid = re.sub("_.*$", "", m.id)
        hit = seedmDB.loc[seedmDB["id"] == mid]
        m.name = hit["name"].values[0]
        m.formula = hit["formula"].values[0]
        m.charge = hit["charge"].values[0]

    if verbose > 0:
        print Calready, "reactions already in the model"
        print Cold, "removed deprecated reactions"
    refmod = repair_mass_balance(refmod, delete_unbalanced, verbose)
    if verbose > 0:
        print len(
            refmod.reactions), "remaining reaction in reference database:",
    return (refmod)
Example #25
0
def createDict(file):
    Universal = Model("Universal Reactions")
    f = open('file', 'r')
    rxn_dict = {}
    for line in f:
        rxn_items = line.split('\t')
        rxn_dict[rxn_items[0]] = rxn_items[2]
    for rxnName in rxn_dict.keys():
        rxn = Reaction(rxnName)
        Universal.add_reaction(rxn)
        rxn.reaction = rxn_dict[rxnName]
    return Universal
Example #26
0
 def test_add_reaction(self):
     model = Model('bigg_test')
     cobrababel.add_bigg_metabolites([cobrababel.get_bigg_metabolite('cynt_p', 'iAF1260'),
                                      cobrababel.get_bigg_metabolite('h_p', 'iAF1260'),
                                      cobrababel.get_bigg_metabolite('cynt_c', 'iAF1260'),
                                      cobrababel.get_bigg_metabolite('h_c', 'iAF1260')], model)
     cobrababel.add_bigg_reactions([cobrababel.get_bigg_reaction('CYNTt2pp', 'iAF1260')], model)
     assert model.reactions[0].id == 'CYNTt2pp'
     assert model.reactions[0].name == 'Cyanate transport via proton symport (periplasm)'
     assert model.reactions[0].reaction == 'cynt_p + h_p --> cynt_c + h_c'
     assert len(model.reactions[0].metabolites) == 4
     assert len(model.compartments) == 2
Example #27
0
 def test_remove_breaks(self):
     model = Model("test model")
     A = Metabolite("A")
     r = Reaction("r")
     r.add_metabolites({A: -1})
     r.lower_bound = -1000
     r.upper_bound = 1000
     model.add_reaction(r)
     convert_to_irreversible(model)
     model.remove_reactions(["r"])
     with pytest.raises(KeyError):
         revert_to_reversible(model)
Example #28
0
def Test():
    model = Model('TEST')

    nombre = "test_reaction"
    reaction = Reaction(nombre)
    reaction.name = '3 oxoacyl acyl carrier protein synthase n C140 '
    reaction.subsystem = 'Cell Envelope Biosynthesis'
    reaction.lower_bound = 0.  # This is the default
    reaction.upper_bound = 1000.  # This is the default

    reaction.add_metabolites({
        Metabolite('malACP_c',
                   formula='C14H22N2O10PRS',
                   name='Malonyl-acyl-carrier-protein',
                   compartment='c'):
        -1.0,
        Metabolite('h_c', formula='H', name='H', compartment='c'):
        -1.0,
        Metabolite('ddcaACP_c',
                   formula='C23H43N2O8PRS',
                   name='Dodecanoyl-ACP-n-C120ACP',
                   compartment='c'):
        -1.0,
        Metabolite('co2_c', formula='CO2', name='CO2', compartment='c'):
        1.0,
        Metabolite('ACP_c',
                   formula='C11H21N2O7PRS',
                   name='acyl-carrier-protein',
                   compartment='c'):
        1.0,
        Metabolite('3omrsACP_c',
                   formula='C25H45N2O9PRS',
                   name='3-Oxotetradecanoyl-acyl-carrier-protein',
                   compartment='c'):
        1.0
    })

    reaction.reaction
    reaction.gene_reaction_rule = '( STM2378 or STM1197 )'
    reaction.genes

    model.add_reactions([reaction])

    print('%i reaction' % len(model.reactions))
    print('%i metabolites' % len(model.metabolites))
    print('%i genes' % len(model.genes))

    MostrarSistema()

    model.objective = nombre
    print(model.objective.expression)
    print(model.objective.direction)
Example #29
0
 def setUp(self):
     self.solver = solvers.solver_dict[self.solver_name]
     self.model = create_test_model()
     self.old_solution = 0.380008
     self.infeasible_model = Model()
     metabolite_1 = Metabolite("met1")
     reaction_1 = Reaction("rxn1")
     reaction_2 = Reaction("rxn2")
     reaction_1.add_metabolites({metabolite_1: 1})
     reaction_2.add_metabolites({metabolite_1: 1})
     reaction_1.lower_bound = 1
     reaction_2.upper_bound = 2
     self.infeasible_model.add_reactions([reaction_1, reaction_2])
Example #30
0
def build_model():
    m = Model("Blazier et al 2012")
    m1_e = Metabolite("M1_e")
    m1 = Metabolite("M1")
    m2 = Metabolite("M2")
    m3 = Metabolite("M3")
    m4_e = Metabolite("M4_e")
    m4 = Metabolite("M4")
    m5 = Metabolite("M5")

    r1 = Reaction("R1")
    r1.add_metabolites({m1_e: -1, m1: 1})

    r2 = Reaction("R2")
    r2.add_metabolites({m1: -1, m2: 1})
    r2.gene_reaction_rule = "Gene2"

    r3 = Reaction("R3")
    r3.add_metabolites({m2: -1, m3: 1})
    r3.gene_reaction_rule = "Gene3"

    r4 = Reaction("R4")
    r4.add_metabolites({m3: -1})

    r5 = Reaction("R5")
    r5.add_metabolites({m4_e: -1, m4: 1})

    r6 = Reaction("R6")
    r6.add_metabolites({m4: -1, m5: 1})
    r6.gene_reaction_rule = "Gene6"

    r7 = Reaction("R7")
    r7.add_metabolites({m5: -1, m2: 1})
    r7.lower_bound = -r7.upper_bound
    r7.gene_reaction_rule = "Gene7"

    r8 = Reaction("R8")
    r8.add_metabolites({m5: -1})

    m.add_reactions([r1, r2, r3, r4, r5, r6, r7, r8])

    EX_M1_e = m.add_boundary(m1_e)
    EX_M1_e.lower_bound = -10

    EX_M4_e = m.add_boundary(m4_e)
    EX_M4_e.lower_bound = -10

    m.objective = r4

    return m