def run_cobra_model(self):
     cobra_model = load_json_model(data_dir_tests + '/mini.json')
     convert_to_irreversible(cobra_model)
     solution = cobra_model.optimize()
     assert(solution.objective_value == 30.0)
     assert(solution.fluxes['ENO'] == 20.0)
     self.cobra_model = cobra_model
Example #2
0
def load_json_me(file_name):
    """
    Load ME model from json

    file_name : str or file-like object
    """
    me = load_json_model(file_name)

    # Re-convert stoichiometries back to sympy
    for rxn in me.reactions:
        for met in rxn.metabolites:
            s =rxn._metabolites[met]
            try:
                rxn._metabolites[met] = float(s)
            except ValueError:
                rxn._metabolites[met] = get_sympy_expression(s)
        try:
            rxn.lower_bound = float(rxn.lower_bound)
        except ValueError:
            rxn.lower_bound = get_sympy_expression(rxn.lower_bound)
        try:
            rxn.upper_bound = float(rxn.upper_bound)
        except ValueError:
            rxn.upper_bound = get_sympy_expression(rxn.upper_bound)

    for met in me.metabolites:
        b = met._bound
        try:
            met._bound = float(b)
        except ValueError:
            met._bound = get_sympy_expression(b)

    return me
    def make_Model(self,model_id_I=None,model_id_O=None,date_O=None,model_file_name_I=None,ko_list=[],flux_dict={},description=None):
        '''make a new model'''

        if model_id_I and model_id_O and date_O: #make a new model based off of a modification of an existing model in the database
            cobra_model_sbml = None;
            cobra_model_sbml = self.get_row_modelID_dataStage02IsotopomerModels(model_id_I);
            # write the model to a temporary file
            cobra_model = self.writeAndLoad_modelTable(cobra_model_sbml);
            # Constrain the model
            self.constrain_modelModelVariables(cobra_model=cobra_model,ko_list=ko_list,flux_dict=flux_dict);
            # Change description, if any:
            if description:
                cobra_model.description = description;
            # test the model
            if self.test_model(cobra_model):
                # write the model to a temporary file
                with open('cobra_model_tmp.xml','w') as file:
                    file.write(cobra_model);
                # upload the model to the database
                self.import_dataStage02Model_sbml(model_id_O, date_O, 'cobra_model_tmp.xml');
        elif model_file_name_I and model_id_O and date_O: #modify an existing model in not in the database
            # check for the file type
            if '.json' in model_file_name_I:
                # Read in the sbml file and define the model conditions
                cobra_model = load_json_model(model_file_name_I, print_time=True);
            elif '.xml' in model_file_name_I:
                # Read in the sbml file and define the model conditions
                cobra_model = create_cobra_model_from_sbml_file(model_file_name_I, print_time=True);
            else: print('file type not supported')
            # Constrain the model
            self.constrain_modelModelVariables(cobra_model=cobra_model,ko_list=ko_list,flux_dict=flux_dict);
            # Change description, if any:
            if description:
                cobra_model.description = description;
            # test the model
            if self.test_model(cobra_model):
                # write the model to a temporary file
                filename = '';
                if '.xml' in model_file_name_I:
                    filename = 'cobra_model_tmp.xml'
                    with open(filename,'w') as file:
                        file.write(cobra_model);
                        file.close()
                elif '.json' in model_file_name_I:
                    filename = 'cobra_model_tmp.json';
                    with open(filename,'w') as file:
                        file.write(cobra_model);
                        file.close()
                else: print('file type not supported')
                # upload the model to the database
                self.import_dataStage02Model_sbml(model_id_O, date_O, filename);
        else:
            print('need to specify either an existing model_id or model_file_name!')
 def load_model(self,model_file_name_I):
     '''load a cobra model from json or sbml
     INPUT:
     model_file_name_I = name of file
     OUTPUT:
     cobra_model
     '''
     
     cobra_model=None;
     # check for the file type
     if '.json' in model_file_name_I:
         # Read in the sbml file and define the model conditions
         cobra_model = load_json_model(model_file_name_I, print_time=True);
     elif '.xml' in model_file_name_I:
         # Read in the sbml file and define the model conditions
         cobra_model = create_cobra_model_from_sbml_file(model_file_name_I, print_time=True);
     else: 
         print('file type not supported');
     return cobra_model;
 def writeAndLoad_modelTable(self,cobra_model_table_I):
     '''Load a cobra model from models table'''
                        
     # write the model to a temporary file
     if cobra_model_table_I['file_type'] == 'sbml':
         with open('cobra_model_tmp.xml','w') as file:
             file.write(cobra_model_table_I['model_file']);
             file.close()
         cobra_model = None;
         cobra_model = create_cobra_model_from_sbml_file('cobra_model_tmp.xml', print_time=True);
     elif cobra_model_table_I['file_type'] == 'json':
         with open('cobra_model_tmp.json','w') as file:
             file.write(cobra_model_table_I['model_file']);
             file.close()
         cobra_model = None;
         cobra_model = load_json_model('cobra_model_tmp.json');
     else:
         print('file_type not supported')
         return None;
     return cobra_model;
Example #6
0
@author: noore
"""
from cobra.io.json import load_json_model
from cobra import Metabolite, Reaction
from stfba.find_energy_generating_cycle import stFBA
from cobra.flux_analysis.loopless import construct_loopless_model
from stfba import settings

model_name_to_obj = {'e_coli_core': 'BIOMASS_Ecoli_core_w_GAM',
                     'iAF1260':     'BIOMASS_Ec_iAF1260_core_59p81M',
                     'iJO1366':     'BIOMASS_Ec_iJO1366_core_53p95M'}

model_name = 'e_coli_core'

model = load_json_model('model/%s.json' % model_name)
model.objective = model_name_to_obj[model_name]
model.reactions.EX_glc__D_e.lower_bound = -10
model.reactions.EX_o2_e.lower_bound = 0
model.reactions.EX_o2_e.upper_bound = 0

if model_name == 'iJO1366':
    #model.reactions.SPODM.lower_bound = 0
    #model.reactions.SPODM.upper_bound = 0
    model.reactions.MOX.lower_bound = 0

print("Calculating anaerobic yield with original %s model" % model_name)

fba_sol = model.optimize(solver=settings.LP_SOLVER)
print("FBA max yield: %.3f" % fba_sol.f)
    def _parse_model_json(self,model_id_I,date_I,filename_I):
        # Read in the sbml file and define the model conditions
        cobra_model = load_json_model(filename_I);
        model_data = [];
        model_data_tmp = {};
        # parse out model metadata
        model_data_tmp['model_id'] = model_id_I;
        model_data_tmp['model_name'] = None;
        model_data_tmp['date'] = date_I;
        model_data_tmp['model_description'] = cobra_model.description;
        with open(filename_I, 'r') as f:
            model_data_tmp['model_file'] = f.read();
        model_data_tmp['file_type'] = 'json'
        model_data.append(model_data_tmp)
        reaction_data = [];
        # parse out reaction data
        for r in cobra_model.reactions:
            reaction_data_dict = {};
            reaction_data_dict['model_id'] = model_id_I
            reaction_data_dict['rxn_id'] = r.id
            reaction_data_dict['rxn_name'] = r.name
            reaction_data_dict['equation'] = r.build_reaction_string()
            reaction_data_dict['subsystem'] = r.subsystem
            reaction_data_dict['gpr'] = r.gene_reaction_rule
            reaction_data_dict['genes'] = []
            genes = r.genes;
            for g in genes:
                reaction_data_dict['genes'].append(g.id);
            reaction_data_dict['reactants_stoichiometry'] = [];
            reaction_data_dict['reactants_ids'] = [];
            reactants = r.reactants;
            for react in reactants:
                reaction_data_dict['reactants_stoichiometry'].append(r.get_coefficient(react.id));
                reaction_data_dict['reactants_ids'].append(react.id);
            reaction_data_dict['products_stoichiometry'] = [];
            reaction_data_dict['products_ids'] = [];
            products = r.products;
            for prod in products:
                reaction_data_dict['products_stoichiometry'].append(r.get_coefficient(prod.id));
                reaction_data_dict['products_ids'].append(prod.id);
            reaction_data_dict['lower_bound'] = r.lower_bound
            reaction_data_dict['upper_bound'] = r.upper_bound
            reaction_data_dict['objective_coefficient'] = r.objective_coefficient
            reaction_data_dict['flux_units'] = 'mmol*gDW-1*hr-1'
            reaction_data_dict['reversibility'] = r.reversibility
            #reaction_data_dict['reactants_stoichiometry_tracked'] = None;
            #reaction_data_dict['products_stoichiometry_tracked'] = None;
            #reaction_data_dict['reactants_ids_tracked'] = None;
            #reaction_data_dict['products_ids_tracked'] = None;
            #reaction_data_dict['reactants_mapping'] = None;
            #reaction_data_dict['products_mapping'] = None;
            #reaction_data_dict['rxn_equation'] = None;
            reaction_data_dict['fixed'] = None;
            reaction_data_dict['free'] = None;
            reaction_data_dict['weight'] = None;
            reaction_data_dict['used_'] = True
            reaction_data_dict['comment_'] = None;
            reaction_data.append(reaction_data_dict);
        metabolite_data = [];
        # parse out metabolite data
        for met in cobra_model.metabolites:
            metabolite_data_tmp = {};
            metabolite_data_tmp['model_id'] = model_id_I
            metabolite_data_tmp['met_name'] = met.name;
            metabolite_data_tmp['met_id'] = met.id;
            if met.formula:
                if met.formula != 'None' and met.formula.formula != 'None' and not 'X' in met.formula.formula:
                    try:
                        tmp = Formula(met.formula.formula);
                        metabolite_data_tmp['formula'] = tmp.formula;
                    except Exception as e:
                        print(e);
                        print(met.id)
                        metabolite_data_tmp['formula']= met.formula.formula;
                else: 
                    metabolite_data_tmp['formula'] = met.formula.formula;
            else: 
                metabolite_data_tmp['formula'] = None;
            metabolite_data_tmp['charge'] = met.charge
            metabolite_data_tmp['compartment'] = met.compartment
            metabolite_data_tmp['bound'] = met._bound
            metabolite_data_tmp['constraint_sense'] = met._constraint_sense
            #metabolite_data_tmp['met_elements'] = None;
            #metabolite_data_tmp['met_atompositions'] = None;
            metabolite_data_tmp['balanced'] = None;
            metabolite_data_tmp['fixed'] = None;
            #metabolite_data_tmp['met_symmetry'] = None;
            #metabolite_data_tmp['met_symmetry_atompositions'] = None;
            metabolite_data_tmp['used_'] = True
            metabolite_data_tmp['comment_'] = None;
            metabolite_data_tmp['lower_bound'] = None;
            metabolite_data_tmp['upper_bound'] = None;

            metabolite_data.append(metabolite_data_tmp);

        return model_data,reaction_data,metabolite_data
Example #8
0
 def init_model(self):
     cobra_model = load_json_model(data_dir_tests + '/mini.json')
     convert_to_irreversible(cobra_model)     
     solution = cobra_model.optimize()  
     self.cobra_model = cobra_model