示例#1
0
def get_medium(model, pflag=True):
    '''!
    Function to list the medium in a model, with Cameo.

    @model String: Model acceptable by Cameo (see 
    http://cameo.bio/02-import-models.html).
    @pflag Boolean: Flag to enable printing of results. Default = 
    True (results are printed).
    '''
    import cameo
    _cameo_header()
    print('Load model: %s' % str(model))
    model = cameo.load_model(model)
    medium = model.medium
    print('')
    count = 1
    result = []
    if pflag:
        print('Number : Component : Rate (mmol/gDW/h)')
    for cpd in medium:
        if pflag:
            print('%s : %s : %s' % \
                  (count, cpd, str(medium[cpd])))
        result.append([count, cpd, str(medium[cpd])])
        count = count + 1
    return result
示例#2
0
def flux_balance_analysis(model,
                          analysis='FBA',
                          result_type='objective',
                          pflag=True):
    '''!
    Function to simulate a model using Flux Balance Analysis (FBA) 
    or FBA-related methods, with Cameo.

    @model String: Model acceptable by Cameo (see 
    http://cameo.bio/02-import-models.html).
    @analysis String: Type of FBA to perform. Allowable types are 
    FBA (standard flux balance analysis) and pFBA (parsimonious 
    FBA). Default value = FBA.
    @pflag Boolean: Flag to enable printing of results. Default = 
    True (results are printed).
    @result_type String: Type of result to give. Allowable types 
    are objective (objective value from FBA) or flux (table of 
    fluxes).
    '''
    import cameo
    _cameo_header()
    print('Load model: %s' % str(model))
    model = cameo.load_model(model)
    result = _fba(model, analysis)
    result = _fba_result(result, result_type, analysis, pflag)
    return result
示例#3
0
def get_reaction_names(model, pflag=True):
    '''!
    Function to list the reaction names in a model, with Cameo.

    @model String: Model acceptable by Cameo (see 
    http://cameo.bio/02-import-models.html).
    @pflag Boolean: Flag to enable printing of results. Default = 
    True (results are printed).
    '''
    import cameo
    _cameo_header()
    print('Load model: %s' % str(model))
    model = cameo.load_model(model)
    print('')
    count = 1
    result = []
    if pflag:
        print(
            'Number : Reaction ID : Upper Bound : Lower Bound : Reaction Name')
    for rxn in model.reactions:
        if pflag:
            print('%s : %s : %s : %s : %s' % \
                  (count, rxn.id, rxn.upper_bound,
                   rxn.lower_bound, rxn.name))
        result.append(
            [count, rxn.id, rxn.upper_bound, rxn.lower_bound, rxn.name])
        count = count + 1
    return result
示例#4
0
def mutantFBA(model,
              mutation,
              analysis='FBA',
              result_type='objective',
              pflag=True):
    '''!
    Function to simulate a model after adding mutation(s) using 
    Flux Balance Analysis (FBA) or FBA-related methods, with Cameo.

    @model String: Model acceptable by Cameo (see 
    http://cameo.bio/02-import-models.html).
    @mutation String: String to define mutation(s). Each mutation 
    is defined as <reaction ID>:<upper bound>:<lower bound>. For 
    example, RBFK,0,0 will represent a knock out. Multiple mutations 
    are delimited using semicolon.
    @analysis String: Type of FBA to perform. Allowable types are 
    FBA (standard flux balance analysis) and pFBA (parsimonious 
    FBA). Default value = FBA.
    @pflag Boolean: Flag to enable printing of results. Default = 
    True (results are printed).
    @result_type String: Type of result to give. Allowable types 
    are objective (objective value from FBA) or flux (table of 
    fluxes).
    '''
    import cameo
    _cameo_header()
    print('Load model: %s' % str(model))
    model = cameo.load_model(model)
    mutation = _parse_mutation(mutation)
    model = _perform_mutation(model, mutation)
    result = _fba(model, analysis)
    result = _fba_result(result, result_type, analysis, pflag)
    return result
示例#5
0
文件: test_io.py 项目: ehukim/cameo
 def test_load_model_pickle_handle(self):
     with open(os.path.join(TESTDIR, 'data/iJO1366.pickle'),
               'rb') as handle:
         model = load_model(handle, solver_interface=self.interface)
     self.assertAlmostEqual(model.optimize().f,
                            0.9823718127269768,
                            places=6)
示例#6
0
def mediumFBA(model,
              change,
              analysis='FBA',
              result_type='objective',
              pflag=True):
    '''!
    Function to simulate a model after changing medium conditions(s) 
    using Flux Balance Analysis (FBA) or FBA-related methods, with 
    Cameo.

    @model String: Model acceptable by Cameo (see 
    http://cameo.bio/02-import-models.html).
    @change String: String to define medium change(s). Each change
    is defined as <compound ID>:<new value>. For example, EX_o2_e,0 
    will represent anaerobic condition. Multiple changes are delimited 
    using semicolon.
    @analysis String: Type of FBA to perform. Allowable types are 
    FBA (standard flux balance analysis) and pFBA (parsimonious 
    FBA). Default value = FBA.
    @pflag Boolean: Flag to enable printing of results. Default = 
    True (results are printed).
    @result_type String: Type of result to give. Allowable types 
    are objective (objective value from FBA) or flux (table of 
    fluxes).
    '''
    import cameo
    _cameo_header()
    print('Load model: %s' % str(model))
    model = cameo.load_model(model)
    change = _parse_medium_change(change)
    model = _perform_medium_change(model, change)
    result = _fba(model, analysis)
    result = _fba_result(result, result_type, analysis, pflag)
    return result
示例#7
0
def get_reaction_compounds(model, pflag=True):
    '''!
    Function to list the reactants and products for each reaction 
    in a model, with Cameo.

    @model String: Model acceptable by Cameo (see 
    http://cameo.bio/02-import-models.html).
    @pflag Boolean: Flag to enable printing of results. Default = 
    True (results are printed).
    '''
    import cameo
    _cameo_header()
    print('Load model: %s' % str(model))
    model = cameo.load_model(model)
    print('')
    count = 1
    result = []
    if pflag:
        print('Number : Reaction ID : Reactants : Products : Reaction Name')
    for rxn in model.reactions:
        rxn_id = rxn.id
        rxn_name = rxn.name
        reactants = [r.id for r in rxn.reactants]
        products = [p.id for p in rxn.products]
        if pflag:
            print('%s : %s : %s : %s : %s' % \
                  (count, rxn_id, '|'.join(reactants),
                   '|'.join(products), rxn.name))
        result.append([count, rxn_id, reactants, products, rxn.name])
        count = count + 1
    return result
def write_results():
  """optimize results and write out to a file"""
  from cameo import load_model, fba
  
  outF = open("KOFBAFluxes-2.txt","w")
  
  model = load_model('KOmodel.json')
  print(len(model.genes))
  print(len(model.metabolites))
  print(len(model.reactions))
  # new_solution = model.optimize()
  fba_result = fba(model)
  print(fba_result)
  # print(fba_result.data_frame)
  print(len(fba_result.data_frame))
  # print(model.reactions)
    
  print(dir(fba_result))
  print(fba_result.data_frame)
  fbaD = fba_result.data_frame.T.to_dict()
  fbaCorrD = {}
  for keyS, valueF in fbaD.items():
    fbaCorrD[keyS] = valueF["flux"]
 
  for keyS, valueF in fbaCorrD.items():
    # print(keyS, valueF)
    outF.write(str(keyS) + ", " + str(valueF) + "\n")
示例#9
0
 def setUpClass(cls):
     cls.model = load_model(os.path.join(TESTDIR, 'data', 'EcoliCore.xml'))
     cls.cad_reaction = Reaction(id="CAD", name="Cis-Aconitate Decarboxylase")
     acon_C_c = cls.model.metabolites.acon_dsh_C_c
     co2_c = cls.model.metabolites.co2_c
     ita_c = Metabolite(id="ita_c", name="Itaconate", compartment="c")
     cls.cad_reaction.add_metabolites({acon_C_c: -1, co2_c: 1, ita_c: 1})
示例#10
0
文件: test_io.py 项目: ehukim/cameo
 def test_load_model_sbml_path_set_none_interface(self):
     model = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'),
                        solver_interface=None)
     self.assertAlmostEqual(model.optimize().f,
                            0.8739215069684306,
                            places=6)
     self.assertTrue(isinstance(model, cobra.core.Model))
     self.assertFalse(hasattr(model, 'solver'))
示例#11
0
def find_pathway(model, product, max_prediction=4):
    import cameo
    _cameo_header()
    model = cameo.load_model(model)
    predictor = cameo.strain_design.pathway_prediction.PathwayPredictor(model)
    pathways = predictor.run(product=str(product),
                             max_predictions=max_predictions)
    for rxnID in pathways.pathways[0].data_frame['equation'].keys():
        print()
 def test_change_solver_to_cplex_and_check_copy_works(self):
     # First, load model from scratch
     model = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'), solver_interface='cplex')
     self.assertAlmostEqual(model.optimize().f, 0.8739215069684306)
     model_copy = model.copy()
     self.assertAlmostEqual(model_copy.optimize().f, 0.8739215069684306)
     # Second, change existing glpk based model to cplex
     self.model.solver = 'cplex'
     self.assertAlmostEqual(self.model.optimize().f, 0.8739215069684306)
     model_copy = copy.copy(self.model)
     self.assertAlmostEqual(model_copy.optimize().f, 0.8739215069684306)
示例#13
0
 def test_change_solver_to_cplex_and_check_copy_works(self):
     # First, load model from scratch
     model = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'),
                        solver_interface='cplex')
     self.assertAlmostEqual(model.optimize().f, 0.8739215069684306)
     model_copy = model.copy()
     self.assertAlmostEqual(model_copy.optimize().f, 0.8739215069684306)
     # Second, change existing glpk based model to cplex
     self.model.solver = 'cplex'
     self.assertAlmostEqual(self.model.optimize().f, 0.8739215069684306)
     model_copy = copy.copy(self.model)
     self.assertAlmostEqual(model_copy.optimize().f, 0.8739215069684306)
示例#14
0
def update_local_models(model_id, model_store=None):
    """Update locally stored models.

    Annotate model metabolites with CHEBI identifiers and store them locally for easy access.
    :param model_id: string, model identifier
    :param model_store: path to directory where to store the processed models.
    """
    model_store = model_store or 'data/models'
    if model_id in LOCAL_MODELS:
        sbml_file = os.path.join(model_store, 'original',
                                 model_id + '.sbml.gz')
        model = read_sbml_model(sbml_file)
    else:
        model = load_model(model_id)

    # annotate metabolites
    namespace = storage.get(model_id).namespace
    metabolite_namespace = MODEL_METABOLITE_NAMESPACE[model_id]
    db_name = 'CHEBI'
    metabolites_missing_annotation = [
        m.id for m in model.metabolites
        if len(m.annotation.get(db_name, [])) < 1
    ]
    model_xref = sync_query_identifiers([
        strip_compartment[namespace](mid)
        for mid in metabolites_missing_annotation
    ], namespace, db_name)
    for metabolite_id in metabolites_missing_annotation:
        compound_id = strip_compartment[namespace](metabolite_id)
        if compound_id in model_xref:
            metabolite = model.metabolites.get_by_id(metabolite_id)
            if db_name not in metabolite.annotation:
                metabolite.annotation[db_name] = []
            metabolite.annotation[db_name].extend([
                f'{db_name}:{i}' if not i.startswith(f"{db_name}:") else i
                for i in model_xref[compound_id]
            ])
            # TODO: For some reason, id-mapper doesn't make this link, add manually for now
            if compound_id in GLUCOSE and db_name == 'CHEBI':
                metabolite.annotation[db_name].append('CHEBI:42758')
            if metabolite_namespace not in metabolite.annotation:
                metabolite.annotation[metabolite_namespace] = []
            metabolite.annotation[metabolite_namespace].append(compound_id)

    # gecko protein exchanges
    db_name = 'uniprot'
    protein_exchanges = model.reactions.query(
        lambda rxn: re.match(r'^prot_.*_exchange$', rxn.id))
    for rxn in protein_exchanges:
        rxn.annotation[db_name] = [
            re.findall('^prot_(.*)_exchange$', rxn.id)[0]
        ]
    write_sbml_model(model, os.path.join(model_store, model_id + '.sbml.gz'))
        def test_all_objects_point_to_all_other_correct_objects(self):
            model = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'))
            for reaction in model.reactions:
                self.assertEqual(reaction.model, model)
                for gene in reaction.genes:
                    self.assertEqual(gene, model.genes.get_by_id(gene.id))
                    self.assertEqual(gene.model, model)
                    for reaction2 in gene.reactions:
                        self.assertEqual(reaction2.model, model)
                        self.assertEqual(reaction2, model.reactions.get_by_id(reaction2.id))

                for metabolite in reaction.metabolites:
                    self.assertEqual(metabolite.model, model)
                    self.assertEqual(metabolite, model.metabolites.get_by_id(metabolite.id))
                    for reaction2 in metabolite.reactions:
                        self.assertEqual(reaction2.model, model)
                        self.assertEqual(reaction2, model.reactions.get_by_id(reaction2.id))
示例#16
0
        def test_all_objects_point_to_all_other_correct_objects(self):
            model = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'))
            for reaction in model.reactions:
                self.assertEqual(reaction.model, model)
                for gene in reaction.genes:
                    self.assertEqual(gene, model.genes.get_by_id(gene.id))
                    self.assertEqual(gene.model, model)
                    for reaction2 in gene.reactions:
                        self.assertEqual(reaction2.model, model)
                        self.assertEqual(
                            reaction2, model.reactions.get_by_id(reaction2.id))

                for metabolite in reaction.metabolites:
                    self.assertEqual(metabolite.model, model)
                    self.assertEqual(
                        metabolite, model.metabolites.get_by_id(metabolite.id))
                    for reaction2 in metabolite.reactions:
                        self.assertEqual(reaction2.model, model)
                        self.assertEqual(
                            reaction2, model.reactions.get_by_id(reaction2.id))
示例#17
0
def find_gene():
  """create optimized model from json file and find genes and reactions in it"""
  from cameo import load_model
  
  # [('HGNC:1093', 0.8281729165648598), ('HGNC:8889', 0.8281729165648598), ('HGNC:8888', 0.8281729165648598), ('HGNC:8898', 0.8281729165648598), ('HGNC:8896', 0.8281729165648598), 
  # ('HGNC:16270', 0.6949058320029933), ('HGNC:8124', 0.6), ('HGNC:3700', 0.6), ('HGNC:4336', 0.6), ('HGNC:4335', 0.6)]
  
  model = load_model('WTmodel.json')
  print(len(model.genes))
  print(len(model.metabolites))
  print(len(model.reactions))
  
  model.optimize()
  
  for modelO in model.reactions:
    # print(dir(modelO))
    # print(modelO.name, modelO.reaction, modelO.nice_id, modelO.annotation)
    if str(modelO.nice_id) == "PGK":
      print(modelO.name, modelO.reaction, modelO.nice_id, modelO.annotation, modelO.flux)
    elif str(modelO.nice_id) == "O2t":
      print(modelO.name, modelO.reaction, modelO.nice_id, modelO.annotation, modelO.flux)
 def test_iMM904_4HGLSDm_problem(self):
     model = load_model(os.path.join(TESTDIR, 'data/iMM904.xml'))
     # set upper bound before lower bound after knockout
     cp = model.copy()
     rxn = cp.reactions.get_by_id('4HGLSDm')
     prev_lb, prev_ub = rxn.lower_bound, rxn.upper_bound
     rxn.lower_bound = 0
     rxn.upper_bound = 0
     rxn.upper_bound = prev_ub
     rxn.lower_bound = prev_lb
     self.assertEquals(rxn.lower_bound, prev_lb)
     self.assertEquals(rxn.upper_bound, prev_ub)
     # set lower bound before upper bound after knockout
     cp = model.copy()
     rxn = cp.reactions.get_by_id('4HGLSDm')
     prev_lb, prev_ub = rxn.lower_bound, rxn.upper_bound
     rxn.lower_bound = 0
     rxn.upper_bound = 0
     rxn.lower_bound = prev_lb
     rxn.upper_bound = prev_ub
     self.assertEquals(rxn.lower_bound, prev_lb)
     self.assertEquals(rxn.upper_bound, prev_ub)
示例#19
0
 def test_iMM904_4HGLSDm_problem(self):
     model = load_model(os.path.join(TESTDIR, 'data/iMM904.xml'))
     # set upper bound before lower bound after knockout
     cp = model.copy()
     rxn = cp.reactions.get_by_id('4HGLSDm')
     prev_lb, prev_ub = rxn.lower_bound, rxn.upper_bound
     rxn.lower_bound = 0
     rxn.upper_bound = 0
     rxn.upper_bound = prev_ub
     rxn.lower_bound = prev_lb
     self.assertEquals(rxn.lower_bound, prev_lb)
     self.assertEquals(rxn.upper_bound, prev_ub)
     # set lower bound before upper bound after knockout
     cp = model.copy()
     rxn = cp.reactions.get_by_id('4HGLSDm')
     prev_lb, prev_ub = rxn.lower_bound, rxn.upper_bound
     rxn.lower_bound = 0
     rxn.upper_bound = 0
     rxn.lower_bound = prev_lb
     rxn.upper_bound = prev_ub
     self.assertEquals(rxn.lower_bound, prev_lb)
     self.assertEquals(rxn.upper_bound, prev_ub)
示例#20
0
 def test_load_model_sbml_path_set_none_interface(self):
     model = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'),
                        solver_interface=None)
     assert abs(model.optimize().f - 0.8739215069684306) < 10e-6
     assert isinstance(model, cobra.core.Model)
     assert not hasattr(model, 'solver')
示例#21
0
 def test_load_model_sbml_path(self, solver_interface):
     model = load_model(os.path.join(TESTDIR, 'data/iJO1366.xml'),
                        solver_interface=solver_interface)
     assert abs(model.optimize().f - 0.9823718127269768) < 10e-6
示例#22
0
from cameo import load_model
from cameo.flux_analysis import phenotypic_phase_plane
import os

TESTDIR = os.path.dirname(__file__)
CORE_MODEL = load_model(os.path.join(TESTDIR, 'EcoliCore.xml'), sanitize=False)

model = CORE_MODEL.copy()
model.solver = 'glpk'
ppp = phenotypic_phase_plane(model, ['EX_o2_LPAREN_e_RPAREN_'])
ppp.data_frame.to_csv(os.path.join(TESTDIR, 'REFERENCE_PPP_o2_EcoliCore.csv'),
                      float_format='%.3f')

model = CORE_MODEL.copy()
model.solver = 'glpk'
ppp2d = phenotypic_phase_plane(
    model, ['EX_o2_LPAREN_e_RPAREN_', 'EX_glc_LPAREN_e_RPAREN_'])
ppp2d.data_frame.to_csv(os.path.join(TESTDIR,
                                     'REFERENCE_PPP_o2_glc_EcoliCore.csv'),
                        float_format='%.3f')

model = CORE_MODEL.copy()
model.solver = 'glpk'
objective = model.add_boundary(model.metabolites.ac_c, type='demand')
model.objective = objective
ppp = phenotypic_phase_plane(model, ['EX_o2_LPAREN_e_RPAREN_'])
ppp.data_frame.to_csv(os.path.join(TESTDIR,
                                   'REFERENCE_PPP_o2_EcoliCore_ac.csv'),
                      float_format='%.3f')
示例#23
0
def core_model(request, data_directory):
    ecoli_core = load_model(join(data_directory, 'EcoliCore.xml'), sanitize=False)
    ecoli_core.solver = request.param
    return ecoli_core
示例#24
0
def imm904(request, data_directory):
    imm = load_model(join(data_directory, 'iMM904.xml'))
    imm.solver = request.param
    return imm.copy()
示例#25
0
def iaf1260(data_directory):
    return load_model(join(data_directory, 'iAF1260.xml'))
示例#26
0
 def test_load_model_pickle_path(self, solver_interface):
     model = load_model(os.path.join(TESTDIR, 'data/iJO1366.pickle'), solver_interface=solver_interface)
     assert abs(model.optimize().objective_value - 0.9823718127269768) < 10e-6
示例#27
0
 def test_load_model_sbml_handle(self, solver_interface):
     with open(os.path.join(TESTDIR, 'data/iJO1366.xml')) as handle:
         model = load_model(handle, solver_interface=solver_interface)
     assert abs(model.slim_optimize() - 0.9823718127269768) < 10e-6
示例#28
0
 def test_load_model_sbml_path_set_none_interface(self):
     model = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'), solver_interface=None)
     assert abs(model.slim_optimize() - 0.8739215069684306) < 10e-6
     assert isinstance(model, cobra.Model)
示例#29
0
 def test_invalid_path(self):
     with pytest.raises(Exception):
         load_model("blablabla_model")
示例#30
0
# limitations under the License.

import os
import pickle
import re

import pytest

from cameo import api, load_model
from cameo import models, config
from cameo.api.hosts import Host
from cameo.api.products import Compound

MODELS = os.path.dirname(models.__file__)

UNIVERSALMODEL = load_model(os.path.join(MODELS, 'json/iJO1366.json'))
UNIVERSALMODEL.remove_reactions(UNIVERSALMODEL.boundary)


def test_api():
    mock_host = Host('core',
                     models=['e_coli_core'],
                     biomass=['BIOMASS_Ecoli_core_w_GAM'],
                     carbon_sources=['EX_glc__D_e'])

    api.design.debug = True
    pathways = api.design.predict_pathways(
        product=UNIVERSALMODEL.metabolites.ser__L_c,
        hosts=[mock_host],
        database=UNIVERSALMODEL,
        aerobic=True)
示例#31
0
                # If single knockout causes the constrained model to become infeasible, then no superset
                # of knockouts can be feasible either.
                with TimeMachine() as tm:
                    reaction.knock_out(tm)
                    try:
                        self._primal_model.solve()
                    except Infeasible:
                        illegal_knockouts.append(reaction.id)
            self._illegal_knockouts = illegal_knockouts
            return cloned_constraints


if __name__ == '__main__':
    from cameo import load_model

    model = load_model("e_coli_core")
    # model = load_model('../../tests/data/EcoliCore.xml')
    model.reactions.ATPM.lower_bound, model.reactions.ATPM.upper_bound = 0, 1000.
    model.reactions.BIOMASS_Ecoli_core_w_GAM.lower_bound = 1
    model.solver = 'cplex'
    shortest_emo = ShortestElementaryFluxModes(model)
    # s.model.solver.configuration.verbosity = 3
    count = 0
    for emo in shortest_emo:
        if count == 1000:
            break
        count += 1
        print(str(count) + " " + 80 * "#")
        print(len(emo))
        for reaction in emo:
            print(reaction, reaction.lower_bound, reaction.upper_bound)
# Smoketest for Docker images
# Execute few commands to see if cameo images function somehow

from aiozmq import rpc  # included because on Alpine Linux it leads to segfault
from cameo import models, load_model
model = load_model('iJO1366')  # does not rely on connection to BIGG database
model.solve()
print('Test OK')
def pathway_predictor(request, data_directory, universal_model):
    core_model = load_model(join(data_directory, 'EcoliCore.xml'), sanitize=False)
    core_model.solver = request.param
    predictor = PathwayPredictor(core_model, universal_model=universal_model)
    return core_model, predictor
示例#34
0
                # If single knockout causes the constrained model to become infeasible, then no superset
                # of knockouts can be feasible either.
                with TimeMachine() as tm:
                    reaction.knock_out(tm)
                    try:
                        self._primal_model.solve()
                    except Infeasible:
                        illegal_knockouts.append(reaction.id)
            self._illegal_knockouts = illegal_knockouts
            return cloned_constraints


if __name__ == '__main__':
    from cameo import load_model

    model = load_model("e_coli_core")
    # model = load_model('../../tests/data/EcoliCore.xml')
    model.reactions.ATPM.lower_bound, model.reactions.ATPM.upper_bound = 0, 1000.
    model.reactions.BIOMASS_Ecoli_core_w_GAM.lower_bound = 1
    model.solver = 'cplex'
    shortest_emo = ShortestElementaryFluxModes(model)
    # s.model.solver.configuration.verbosity = 3
    count = 0
    for emo in shortest_emo:
        if count == 1000:
            break
        count += 1
        print(str(count) + " " + 80 * "#")
        print(len(emo))
        for reaction in emo:
            print(reaction, reaction.lower_bound, reaction.upper_bound)
示例#35
0
def universal_model(data_directory):
    universal = load_model(join(data_directory, 'iJO1366.xml'), sanitize=False)
    universal.remove_reactions(universal.boundary)
    return universal
示例#36
0
# limitations under the License.

import os
import pickle
import re

import pytest

from cameo import api, load_model
from cameo import models, config
from cameo.api.hosts import Host
from cameo.api.products import Compound

MODELS = os.path.dirname(models.__file__)

UNIVERSALMODEL = load_model(os.path.join(MODELS, 'json/iJO1366.json'))
UNIVERSALMODEL.remove_reactions(UNIVERSALMODEL.boundary)


def test_api():
    mock_host = Host('core',
                     models=['e_coli_core'],
                     biomass=['BIOMASS_Ecoli_core_w_GAM'],
                     carbon_sources=['EX_glc__D_e'])

    api.design.debug = True
    pathways = api.design.predict_pathways(product=UNIVERSALMODEL.metabolites.ser__L_c, hosts=[mock_host],
                                           database=UNIVERSALMODEL, aerobic=True)
    optimization_reports = api.design.optimize_strains(pathways, config.default_view, aerobic=True)
    pickle.loads(pickle.dumps(optimization_reports))
    assert len(optimization_reports) > 0
示例#37
0
def toy_model(request, data_directory):
    toy = load_model(join(data_directory, "toy_model_Papin_2003.xml"))
    toy.solver = request.param
    return toy
示例#38
0
 def test_load_model_pickle_handle(self):
     with open(os.path.join(TESTDIR, 'data/iJO1366.pickle'), 'rb') as handle:
         model = load_model(handle, solver_interface=self.interface)
     self.assertAlmostEqual(model.optimize().f, 0.9823718127269768)
示例#39
0
文件: hosts.py 项目: weif000/cameo
 def lazy_model_init(path):
     model = load_model(path)
     setattr(model, "biomass", biomass)
     setattr(model, "carbon_source", carbon_source)
     return model
示例#40
0
except requests.ConnectionError:
    bigg.no_models_available = "Cameo couldn't reach http://bigg.ucsd.edu at initialization time. Are you connected to the internet?"
except Exception as e:
    bigg.no_models_available = "Cameo could reach http://bigg.ucsd.edu at initialization time but something went wrong while decoding the server response."
    logger.debug(e)
else:
    for id in model_ids:
        setattr(bigg, str_to_valid_variable_name(id), lazy_object_proxy.Proxy(partial(get_model_from_bigg, id)))

minho = ModelDB()
try:
    minho_models = index_models_minho()
except requests.ConnectionError as e:
    minho.no_models_available = "Cameo couldn't reach http://darwin.di.uminho.pt/models at initialization time. Are you connected to the internet?"
    logger.debug(e)
except Exception as e:
    minho.no_models_available = "Cameo could reach http://darwin.di.uminho.pt/models at initialization time but something went wrong while decoding the server response."
    logger.debug(e)
else:
    model_indices = minho_models.id
    model_ids = minho_models.name
    for index, id in zip(model_indices, model_ids):
        setattr(minho, str_to_valid_variable_name(id), lazy_object_proxy.Proxy(partial(get_model_from_uminho, index)))

if __name__ == "__main__":
    print(index_models_minho())
    from cameo import load_model

    model = load_model(get_sbml_file(2))
    print(model.objective)
    set_mutation, set_indel, multiple_chromosome_set_mutation, multiple_chromosome_set_indel
from cameo.util import RandomGenerator as Random

TRAVIS = os.getenv('TRAVIS', False)

if os.getenv('REDIS_PORT_6379_TCP_ADDR'):
    REDIS_HOST = os.getenv('REDIS_PORT_6379_TCP_ADDR')  # wercker
else:
    REDIS_HOST = 'localhost'

SEED = 1234

CURRENT_PATH = os.path.dirname(__file__)
MODEL_PATH = os.path.join(CURRENT_PATH, "data/EcoliCore.xml")

TEST_MODEL = load_model(MODEL_PATH, sanitize=False)

SOLUTIONS = [
    [[1, 2, 3], 0.1],
    [[1, 3, 2, 4], 0.1],
    [[2, 3, 4], 0.45],
    [[62, 51, 4], 0.2],
    [[5, 3, 4, 51], 0.9],
    [[5, 23, 41, 51], 0.9],
    [[5, 3, 4, 51, 31], 0.9],
    [[5, 3, 4, 51], 0.9],
    [[44, 12, 42, 51], 0.0],
    [[52, 22, 4, 11], 0.0]
]

示例#42
0
def pathway_predictor(request, data_directory, universal_model):
    core_model = load_model(join(data_directory, 'EcoliCore.xml'), sanitize=False)
    core_model.solver = request.param
    predictor = PathwayPredictor(core_model, universal_model=universal_model)
    return core_model, predictor
示例#43
0
 def test_load_model_sbml_handle(self, solver_interface):
     with open(os.path.join(TESTDIR, 'data/iJO1366.xml')) as handle:
         model = load_model(handle, solver_interface=solver_interface)
     assert abs(model.optimize().f - 0.9823718127269768) < 10e-6
示例#44
0
import pickle

import cobra.test
import optlang

from cameo import load_model

ijo = load_model('iJO1366.xml', solver_interface=optlang.glpk_interface)
with open('iJO1366.pickle', 'wb') as out:
    pickle.dump(ijo, out, protocol=2)

salmonella = cobra.test.create_test_model('salmonella')
salmonella.solver = 'glpk'
with open('salmonella.pickle', 'wb') as out:
    pickle.dump(salmonella, out, protocol=2)
示例#45
0
 def test_invalid_path(self):
     with pytest.raises(Exception):
         load_model("blablabla_model")
示例#46
0
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

from __future__ import absolute_import, print_function

import os
import unittest
from cameo import load_model
from cameo.strain_design.pathway_prediction import PathwayPredictor
from cameo.models import universal

TESTDIR = os.path.dirname(__file__)
TESTMODEL = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'))
UNIVERSALMODEL = load_model(os.path.join(TESTDIR, 'data/iJO1366.xml'))

TRAVIS = os.getenv('TRAVIS', False)

PATHWAYPREDICTOR = PathwayPredictor(TESTMODEL, universal_model=UNIVERSALMODEL)


class TestPathwayPredictor(unittest.TestCase):
    def setUp(self):
        self.pathway_predictor = PATHWAYPREDICTOR

    def test_setting_incorrect_universal_model_raises(self):
        with self.assertRaisesRegexp(ValueError, 'Provided universal_model.*'):
            PathwayPredictor(TESTMODEL, universal_model='Mickey_Mouse')
示例#47
0
import copy
from cameo import load_model
from cameo.methods import DifferentialFVA
from cameo.basics import production_envelope

model = load_model('../tests/data/EcoliCore.xml')

solution = model.optimize()
surrogate_experimental_fluxes = dict([(key, (val * .8, val * 1.2)) for key, val in solution.x_dict.iteritems()])

constraint_model = copy.copy(model)
for reaction_id, (lb, ub) in surrogate_experimental_fluxes.iteritems():
    reaction = constraint_model.reactions.get_by_id(reaction_id)
    reaction.lower_bound = lb
    reaction.upper_bound = ub

diffFVA = DifferentialFVA(design_space_model=model,
                          reference_model=constraint_model,
                          target='EX_succ_LPAREN_e_RPAREN_',
                          variables=[model.reactions.Biomass_Ecoli_core_N_LPAREN_w_FSLASH_GAM_RPAREN__Nmet2])

print diffFVA.run()
示例#48
0
def model(data_directory):
    return load_model(join(data_directory, 'EcoliCore.xml'))
import optlang
import pandas
from sympy import Eq

from cameo import load_model, Reaction, Model
from cameo.config import solvers
from cameo.exceptions import UndefinedSolution
from cameo.core.solver_based_model import Reaction
from cameo.util import TimeMachine
import six

TRAVIS = os.getenv('TRAVIS', False)
TESTDIR = os.path.dirname(__file__)
REFERENCE_FVA_SOLUTION_ECOLI_CORE = pandas.read_csv(os.path.join(TESTDIR, 'data/REFERENCE_flux_ranges_EcoliCore.csv'),
                                                    index_col=0)
TESTMODEL = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'), sanitize=False)
COBRAPYTESTMODEL = read_sbml_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'))
ESSENTIAL_GENES = ['b2779', 'b1779', 'b0720', 'b0451', 'b2416', 'b2926', 'b1136', 'b2415']
ESSENTIAL_REACTIONS = ['GLNS', 'Biomass_Ecoli_core_N_LPAREN_w_FSLASH_GAM_RPAREN__Nmet2', 'PIt2r', 'GAPD', 'ACONTb',
                       'EX_nh4_LPAREN_e_RPAREN_', 'ENO', 'EX_h_LPAREN_e_RPAREN_', 'EX_glc_LPAREN_e_RPAREN_', 'ICDHyr',
                       'CS', 'NH4t', 'GLCpts', 'PGM', 'EX_pi_LPAREN_e_RPAREN_', 'PGK', 'RPI', 'ACONTa']


class WrappedCommonGround:
    class CommonGround(unittest.TestCase):
        def setUp(self):
            self.model = TESTMODEL.copy()
            self.model.optimize()


class AbstractTestLazySolution(WrappedCommonGround.CommonGround):
示例#50
0
def ijo1366(request, data_directory):
    ijo = load_model(join(data_directory, 'iJO1366.xml'), sanitize=False)
    ijo.solver = request.param
    return ijo
# limitations under the License.

from __future__ import absolute_import, print_function

import os
import unittest

from cameo import load_model
from cameo.core.pathway import Pathway
from cameo.flux_analysis.analysis import PhenotypicPhasePlaneResult
from cameo.strain_design.pathway_prediction import PathwayPredictor
from cameo.strain_design.pathway_prediction.pathway_predictor import PathwayResult
from cameo.util import TimeMachine

TESTDIR = os.path.dirname(__file__)
TESTMODEL = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'))
UNIVERSALMODEL = load_model(os.path.join(TESTDIR, 'data/iJO1366.xml'))
UNIVERSALMODEL.remove_reactions(UNIVERSALMODEL.exchanges)

TRAVIS = os.getenv('TRAVIS', False)

PATHWAYPREDICTOR = PathwayPredictor(TESTMODEL, universal_model=UNIVERSALMODEL)


class Wrapper:
    class AbstractPathwayPredictorTestCase(unittest.TestCase):

        def test_setting_incorrect_universal_model_raises(self):
            with self.assertRaisesRegexp(ValueError, 'Provided universal_model.*'):
                PathwayPredictor(TESTMODEL, universal_model='Mickey_Mouse')
import os
import unittest

import pandas
import six
from pandas import DataFrame
from pandas.util.testing import assert_frame_equal

import cameo
from cameo import load_model
from cameo.strain_design.deterministic.flux_variability_based import FSEOF, FSEOFResult, DifferentialFVA
from cameo.strain_design.deterministic.linear_programming import OptKnock

TRAVIS = os.getenv('TRAVIS', False)
TESTDIR = os.path.dirname(__file__)
ECOLICORE = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'))


def assert_dataframes_equal(df, expected):
    try:
        assert_frame_equal(df, expected, check_names=False)
        return True
    except AssertionError:
        return False


class TestFSEOF(unittest.TestCase):
    def setUp(self):
        self.model = ECOLICORE.copy()
        self.model.solver = 'glpk'
示例#53
0
import pickle

import cobra
from cobra.test import create_test_model
from optlang import glpk_interface

from cameo import load_model

config = cobra.Configuration()
config.solver = "glpk"

ijo = load_model('iJO1366.xml', glpk_interface)
with open('iJO1366.pickle', 'wb') as out:
    pickle.dump(ijo, out, protocol=2)

salmonella = create_test_model('salmonella')
with open('salmonella.pickle', 'wb') as out:
    pickle.dump(salmonella, out, protocol=2)
示例#54
0
 def test_load_model_pickle_path(self):
     model = load_model(os.path.join(TESTDIR, 'data/iJO1366.pickle'), solver_interface=self.interface)
     self.assertAlmostEqual(model.optimize().f, 0.9823718127269768, places=6)
示例#55
0
                builder.display_in_browser()

        except ImportError:
            print("Escher must be installed in order to visualize maps")


if __name__ == '__main__':
    import time
    from cobra.io import read_sbml_model
    from cameo import load_model

    # sbml_path = '../../tests/data/EcoliCore.xml'
    sbml_path = '../../tests/data/iJO1366.xml'

    cb_model = read_sbml_model(sbml_path)
    model = load_model(sbml_path)

    # model.solver = 'glpk'

    # print("cobra fba")
    # tic = time.time()
    # cb_model.optimize(solver='cglpk')
    # print("flux sum:", sum([abs(val) for val in list(cb_model.solution.x_dict.values())]))
    # print("cobra fba runtime:", time.time() - tic)

    # print("cobra pfba")
    # tic = time.time()
    # optimize_minimal_flux(cb_model, solver='cglpk')
    # print("flux sum:", sum([abs(val) for val in list(cb_model.solution.x_dict.values())]))
    # print("cobra pfba runtime:", time.time() - tic)
示例#56
0
 def test_load_model_sbml_handle(self):
     with open(os.path.join(TESTDIR, 'data/iJO1366.xml')) as handle:
         model = load_model(handle, solver_interface=self.interface)
     self.assertAlmostEqual(model.optimize().f, 0.9823718127269768, places=6)
示例#57
0
                builder.display_in_browser()

        except ImportError:
            print("Escher must be installed in order to visualize maps")


if __name__ == '__main__':
    import time
    from cobra.io import read_sbml_model
    from cameo import load_model

    # sbml_path = '../../tests/data/EcoliCore.xml'
    sbml_path = '../../tests/data/iJO1366.xml'

    cb_model = read_sbml_model(sbml_path)
    model = load_model(sbml_path)

    # model.solver = 'glpk'

    # print("cobra fba")
    # tic = time.time()
    # cb_model.optimize(solver='cglpk')
    # print("flux sum:", sum([abs(val) for val in list(cb_model.solution.fluxes.values())]))
    # print("cobra fba runtime:", time.time() - tic)

    # print("cobra pfba")
    # tic = time.time()
    # optimize_minimal_flux(cb_model, solver='cglpk')
    # print("flux sum:", sum([abs(val) for val in list(cb_model.solution.fluxes.values())]))
    # print("cobra pfba runtime:", time.time() - tic)
示例#58
0
 def test_load_model_sbml_path_set_none_interface(self):
     model = load_model(os.path.join(TESTDIR, 'data/EcoliCore.xml'), solver_interface=None)
     self.assertAlmostEqual(model.optimize().f, 0.8739215069684306, places=6)
     self.assertTrue(isinstance(model, cobra.core.Model))
     self.assertFalse(hasattr(model, 'solver'))