Esempio n. 1
0
 def read_cobrapy_config(self):
     ''' Try to read data from cobrapy-config.txt into appdata'''
     config_parser = configparser.RawConfigParser()
     try:
         config_parser.read(self.appdata.cobrapy_conf_path)
         try:
             cobra.Configuration().solver = config_parser.get('cobrapy-config', 'solver')
         except Exception as e:
             print("Cannot set solver from cobrapy-config.txt file because:", e, 
                     "\nReverting solver to COBRApy base setting.")
         try:
             cobra.Configuration().processes = int(config_parser.get('cobrapy-config', 'processes'))
         except Exception as e:
             print("Cannot set number of processes from cobrapy-config.txt file because:", e, 
                     "\nReverting number of processes to COBRApy base setting.")
         try:
             val = float(config_parser.get('cobrapy-config', 'tolerance'))
             if 1e-9 <= val <= 0.1:
                 cobra.Configuration().tolerance = val
             else:
                 raise ValueError
         except Exception as e:
             print(e, "\nCannot set tolerance from cobrapy-config.txt file because it must be a vaule between 1e-9 and 0.1, reverting to COBRApy base setting.")
     except Exception as e:
         print('Could not read', self.appdata.cobrapy_conf_path, 'because:', e)
Esempio n. 2
0
def model_snapshot(model):
    """Run memote on the given model and create a snapshot report."""
    configuration = cobra.Configuration()
    configuration.processes = 1
    _, result = memote.test_model(
        model,
        results=True,
        pytest_args=["-vv", "--tb", "long"],
        solver_timeout=20,
        skip=("test_inconsistent_min_stoichiometry", ),
    )
    config = memote.ReportConfiguration.load()
    report = memote.SnapshotReport(result=result, configuration=config)
    return model, report
Esempio n. 3
0
    def apply(self):
        cobra.Configuration().solver = self.default_solver.currentText()
        cobra.Configuration().processes = int(self.num_processes.text())
        try:
            val = float(self.default_tolerance.text())
            if 1e-9 <= val <= 0.1:
                cobra.Configuration().tolerance = val
            else:
                raise ValueError
        except:
            QMessageBox.critical(self, "Cannot set default tolerance", "Choose a value between 0.1 and 1e-9 as default tolerance.")
            return
        try:
            self.appdata.project.cobra_py_model.solver = self.current_solver.currentText()
            self.appdata.project.cobra_py_model.tolerance = float(self.current_tolerance.text())
        except Exception as e:
            QMessageBox.critical(self, "Cannot set current solver/tolerance", str(e))
            return

        parser = configparser.ConfigParser()
        parser.add_section('cobrapy-config')
        parser.set('cobrapy-config', 'solver', interface_to_str(cobra.Configuration().solver))
        parser.set('cobrapy-config', 'processes', str(cobra.Configuration().processes))
        parser.set('cobrapy-config', 'tolerance', str(cobra.Configuration().tolerance))
        
        try:
            fp = open(self.appdata.cobrapy_conf_path, "w")
        except FileNotFoundError:
            os.makedirs(appdirs.user_config_dir(
                "cnapy", roaming=True, appauthor=False))
            fp = open(self.appdata.cobrapy_conf_path, "w")

        parser.write(fp)
        fp.close()

        self.accept()
Esempio n. 4
0
    def __init__(self, appdata: CnaData):
        QDialog.__init__(self)
        self.setWindowTitle("Configure COBRApy")

        self.appdata = appdata
        self.layout = QVBoxLayout()

        # allow MILP solvers only?
        avail_solvers = list(set(solvers.keys()) - {'scipy'}) # SCIPY currently not even usable for FBA

        h2 = QHBoxLayout()
        label = QLabel("Default solver:\n(set when loading a model)")
        h2.addWidget(label)
        self.default_solver = QComboBox()
        self.default_solver.addItems(avail_solvers)
        self.default_solver.setCurrentIndex(avail_solvers.index(interface_to_str(cobra.Configuration().solver)))
        h2.addWidget(self.default_solver)
        self.layout.addItem(h2)

        h9 = QHBoxLayout()
        label = QLabel("Solver for current model:")
        h9.addWidget(label)
        self.current_solver = QComboBox()
        self.current_solver.addItems(avail_solvers)
        self.current_solver.setCurrentIndex(avail_solvers.index(interface_to_str(appdata.project.cobra_py_model.problem)))
        h9.addWidget(self.current_solver)
        self.layout.addItem(h9)

        h7 = QHBoxLayout()
        label = QLabel(
            "Number of processes for multiprocessing (e.g. FVA):")
        h7.addWidget(label)
        self.num_processes = QLineEdit()
        self.num_processes.setFixedWidth(100)
        self.num_processes.setText(str(cobra.Configuration().processes))
        validator = QIntValidator(1, cpu_count(), self)
        self.num_processes.setValidator(validator)
        h7.addWidget(self.num_processes)
        self.layout.addItem(h7)

        h8 = QHBoxLayout()
        label = QLabel(
            "Default tolerance:\n(set when loading a model)")
        h8.addWidget(label)
        self.default_tolerance = QLineEdit()
        self.default_tolerance.setFixedWidth(100)
        self.default_tolerance.setText(str(cobra.Configuration().tolerance))
        validator = QDoubleValidator(self)
        validator.setBottom(1e-9) # probably a reasonable consensus value
        self.default_tolerance.setValidator(validator)
        h8.addWidget(self.default_tolerance)
        self.layout.addItem(h8)

        h10 = QHBoxLayout()
        label = QLabel(
            "Tolerance for current model:")
        h10.addWidget(label)
        self.current_tolerance = QLineEdit()
        self.current_tolerance.setFixedWidth(100)
        self.current_tolerance.setText(str(self.appdata.project.cobra_py_model.tolerance))
        validator = QDoubleValidator(self)
        validator.setBottom(0)
        self.current_tolerance.setValidator(validator)
        h10.addWidget(self.current_tolerance)
        self.layout.addItem(h10)

        l2 = QHBoxLayout()
        self.button = QPushButton("Apply Changes")
        self.cancel = QPushButton("Close")
        l2.addWidget(self.button)
        l2.addWidget(self.cancel)
        self.layout.addItem(l2)
        self.setLayout(self.layout)

        self.cancel.clicked.connect(self.reject)
        self.button.clicked.connect(self.apply)
Esempio n. 5
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)
Esempio n. 6
0
from __future__ import absolute_import

from collections import namedtuple
from os import unlink
from os.path import join, split
from pickle import load
from tempfile import gettempdir

import pytest

import cobra
from cobra import Model
from cobra.io import read_sbml_model, validate_sbml_model, write_sbml_model

config = cobra.Configuration()  # for default bounds

try:
    import jsonschema
except ImportError:
    jsonschema = None

# ----------------------------------
# Definition of SBML files to test
# ----------------------------------
IOTrial = namedtuple('IOTrial', [
    'name', 'reference_file', 'test_file', 'read_function', 'write_function',
    'validation_function'
])
trials = [
    IOTrial('fbc2', 'mini.pickle', 'mini_fbc2.xml', read_sbml_model,
Esempio n. 7
0
def CreateModel(FBAmodel_path, target_bofs, species, params):
    """
    Load FBA models and define the medium in which these cells were grown.
    """

    # Load models
    models = list()

    for k in range(0, len(species)):

        print "Loading model..."
        models.append(
            cobra.io.read_sbml_model(FBAmodel_path + species[k] + '.xml'))

        if 'Thaps' in species[k]:
            models[k].id = 'Thalassiosira pseudonana CCMP 1335'

        print models[k].id, "loaded."

        print 'Configuring model...'
        cobra_config = cobra.Configuration()
        cobra_config.lower_bound = -10000. * params['conversion_factor']
        cobra_config.upper_bound = 10000. * params['conversion_factor']
        cobra_config.solver = 'glpk'
        cobra_config.tolerance = params['error_tol']
        print '...done!'

        if 'Thalassiosira' in models[k].id:

            if 'High light' in models[k].reactions.PHOA410_h.name:
                D1 = 1.36247E-08 * params['I'] + 4.94719E-06
            elif 'Medium light' in models[k].reactions.PHOA410_h.name:
                D1 = 1.16783E-08 * params['I'] + 4.24045E-06
            elif 'Low light' in models[k].reactions.PHOA410_h.name:
                D1 = 6.4751E-09 * params['I'] + 2.35114E-06
            else:
                D1 = 5.23188E-09 * params['I'] + 1.89972E-06
            models[
                k].reactions.PSII_u.reaction = '2.0 h2o_u + {1} h_h + 4.0 p680_exc_u + {2} pq_u + {0} ps2d1_u --> 4.0 h_u + o2_u + 4.0 p680_u + {2} pqh2_u + {0} ps2d1_exc_u'.format(
                    str(D1), str((2 - D1) * 2), str(2 - D1))
            models[k].reactions.PSII_u.upper_bound = 10000.

            bof_data = target_bofs[k]['ME'].to_dict()
            mgchla = bof_data['cholphya_h'] * 1e-9
            gDW = sum([
                val for bm, val in bof_data.items() if bm.startswith('biomass')
            ]) * 1e-12

            models[k].reactions.ATPM_c.upper_bound = params['Ic'] * params[
                'abs_coeff'] * 60 * 60 * (
                    mgchla / gDW) * 1e-6 * params['phi_m'] * 12. * (3. /
                                                                    14) * 1e3
            models[k].reactions.CEF_h.upper_bound = params['CEF_ub']
            models[k].remove_reactions(['DM_eps_c'])

            GAM = Reaction('GAM')
            models[k].add_reactions([GAM])
            models[k].reactions.GAM.build_reaction_from_string(
                'GAM_const_c + {0} atp_c + {0} h2o_c --> {0} adp_c + {0} pi_c + {0} h_c'
                .format(str(params['GAM_val'] * params['conversion_factor'])))
            obj_rxn = models[k].reactions.query('bof')[0]
            gam_met = models[k].metabolites.GAM_const_c
            obj_rxn.add_metabolites({gam_met: 1})

            reactions_to_convert = models[k].reactions.query('biomass')
            [
                reactions_to_convert.remove(r)
                for r in models[k].reactions.query('DM_biomass')
            ]

            for r in reactions_to_convert:
                tmp_dict = dict()
                r.lower_bound = r.lower_bound * params['conversion_factor']
                r.upper_bound = r.upper_bound * params['conversion_factor']
                for m, s in r.metabolites.iteritems():
                    stoich = s * -1
                    tmp_dict[m] = stoich
                    r.add_metabolites({m: stoich})
                for bm_met, bm_s in tmp_dict.iteritems():
                    if not bm_met.id.startswith('biomass'):
                        r.add_metabolites(
                            {bm_met: -1 * bm_s * params['conversion_factor']})
                    else:
                        r.add_metabolites({bm_met: -1 * bm_s})

            BuildBiomassReactions(models[k], params, bof_data)

            # Mobilize biomass
            mets = [
                'polyp_c', 'chitin_c', 'chryso_c', 'gly_c', 'atp_c', 'utp_c',
                'gtp_c', 'ctp_c', 'cholphya_h'
            ]
            for m in mets:
                rxn = Reaction('sink_' + m)
                models[k].add_reactions([rxn])
                models[k].reactions.get_by_id(
                    'sink_' + m).build_reaction_from_string(m + ' <=> ')

            for m in bof_data.keys():
                if m.endswith('trna_c'):
                    rxn = Reaction('sink_' + m)
                    models[k].add_reactions([rxn])
                    if m == 'glytrna_c':
                        models[k].reactions.get_by_id(
                            'sink_' + m).build_reaction_from_string(
                                m.replace('trna', '') + ' <=> ')
                    else:
                        models[k].reactions.get_by_id(
                            'sink_' + m).build_reaction_from_string(
                                m.replace('trna', '__L') + ' <=> ')
                if m.startswith('tag') or '__L_' in m:
                    rxn = Reaction('sink_' + m)
                    models[k].add_reactions([rxn])
                    models[k].reactions.get_by_id(
                        'sink_' + m).build_reaction_from_string(m + ' <=> ')

            DM_cholphya_h = Reaction('DM_cholphya_h')
            models[k].add_reactions([DM_cholphya_h])
            models[k].reactions.DM_cholphya_h.build_reaction_from_string(
                'cholphya_h --> ')

            # Add preliminary constraints
            for r in models[k].reactions:
                if r.id == 'EX_cncbl3_e' or r.id.startswith('EX_photon'):
                    models[k].reactions.get_by_id(r.id).lower_bound = 0.
                    models[k].reactions.get_by_id(r.id).upper_bound = 0.
                elif r.id.startswith('EX_'):
                    models[k].reactions.get_by_id(r.id).lower_bound = 0.
                    models[k].reactions.get_by_id(
                        r.id
                    ).upper_bound = 10000. * params['conversion_factor']
                elif r.id.startswith('sink_'):
                    if r.id == 'sink_Asn_X_Ser_Thr_c':
                        models[k].reactions.get_by_id(
                            r.id
                        ).lower_bound = -10000. * params['conversion_factor']
                        models[k].reactions.get_by_id(
                            r.id
                        ).upper_bound = 10000. * params['conversion_factor']
                    else:
                        models[k].reactions.get_by_id(r.id).lower_bound = 0.
                        models[k].reactions.get_by_id(r.id).upper_bound = 0.
                elif r.id.startswith('DM_'):
                    models[k].reactions.get_by_id(r.id).lower_bound = 0.
                    models[k].reactions.get_by_id(
                        r.id
                    ).upper_bound = 10000. * params['conversion_factor']
                else:
                    models[k].reactions.get_by_id(
                        r.id
                    ).upper_bound = r.upper_bound * params['conversion_factor']
                    models[k].reactions.get_by_id(
                        r.id
                    ).lower_bound = r.lower_bound * params['conversion_factor']

    return models
Esempio n. 8
0
def Solve(model, params, t, dark_h, mgchla, gDW):
    """
    Add model-specific constraints and objectives and solve
    """

    if 'Thalassiosira' in model.id:

        with model:

            aslice = 1. / params['slices']

            PR1 = model.problem.Constraint(
                model.reactions.RUBISO_h.flux_expression -
                0.025 * model.reactions.RUBISC_h.flux_expression,
                lb=-10000. * params['conversion_factor'] * aslice,
                ub=0.,
                name='photoresp_ub')

            PR2 = model.problem.Constraint(
                model.reactions.RUBISO_h.flux_expression -
                0.001 * model.reactions.RUBISC_h.flux_expression,
                lb=0.,
                ub=10000. * params['conversion_factor'] * aslice,
                name='photoresp_lb')

            PQub = calculatePQ(model.metabolites.biomass_c, 'NO3')
            PQlb = calculatePQ(model.metabolites.biomass_c, 'NH4')

            Q1 = model.problem.Constraint(
                model.reactions.EX_o2_e.flux_expression + params['f'] * PQlb *
                (model.reactions.EX_hco3_e.flux_expression +
                 model.reactions.EX_co2_e.flux_expression),
                lb=0.,
                ub=10000. * params['conversion_factor'] * aslice)

            Q2 = model.problem.Constraint(
                model.reactions.EX_o2_e.flux_expression + params['f'] * PQub *
                (model.reactions.EX_hco3_e.flux_expression +
                 model.reactions.EX_co2_e.flux_expression),
                lb=-10000. * params['conversion_factor'] * aslice,
                ub=0.)

            resp_day = model.problem.Constraint(
                (model.reactions.PSII_u.flux_expression -
                 model.reactions.EX_o2_e.flux_expression) -
                (model.reactions.RUBISO_h.flux_expression +
                 model.reactions.PTOX_h.flux_expression +
                 model.reactions.MEHLER_h.flux_expression +
                 model.reactions.GOX_m.flux_expression +
                 model.reactions.GOX_x.flux_expression +
                 model.reactions.AOX_m.flux_expression +
                 model.reactions.CYOO_m.flux_expression),
                lb=0.,
                ub=0.)

            resp_night = model.problem.Constraint(
                model.reactions.EX_o2_e.flux_expression +
                (model.reactions.RUBISO_h.flux_expression +
                 model.reactions.PTOX_h.flux_expression +
                 model.reactions.MEHLER_h.flux_expression +
                 model.reactions.GOX_m.flux_expression +
                 model.reactions.GOX_x.flux_expression +
                 model.reactions.AOX_m.flux_expression +
                 model.reactions.CYOO_m.flux_expression),
                lb=0.,
                ub=0.)

            if t not in dark_h:
                if model.reactions.DM_biomass_c.objective_coefficient == 1:
                    model.add_cons_vars([PR1, PR2, resp_day, Q1, Q2])
                    print 'Photosynthetic Quotient (Q):', PQlb, '-', PQub
                else:
                    model.add_cons_vars([PR1, PR2, resp_day])
            else:
                model.add_cons_vars([resp_night])

            if model.reactions.ATPM_c.objective_coefficient != 1.:
                model.reactions.DM_biomass_c.upper_bound = 10000. * params[
                    'conversion_factor'] * aslice
            else:
                model.reactions.DM_biomass_c.upper_bound = 0.

            model.reactions.H2Ot_m.lower_bound = 0.
            model.reactions.ITPA_c.upper_bound = 0.

            try:
                pfba = cobra.flux_analysis.parsimonious.pfba(
                    model, fraction_of_optimum=1.)
                # pfba = model.optimize()
                fluxes = pfba.fluxes
                status = pfba.status
                print status, pfba.objective_value
            except Infeasible:
                try:
                    cobra_config = cobra.Configuration()
                    cobra_config.tolerance = params['error_tol'] * 10.
                    pfba = cobra.flux_analysis.parsimonious.pfba(
                        model, fraction_of_optimum=1.)
                    fluxes = pfba.fluxes
                    status = pfba.status
                    print status, pfba.objective_value
                except Infeasible:
                    if params['verbose'] == 1:
                        print 'Infeasible'
                    fluxes = pd.Series(data=[0.] * len(model.reactions),
                                       index=[r.id for r in model.reactions])
                    status = 'infeasible'

            if params['verbose'] == 1:
                for r in fluxes.index:
                    if r.startswith('EX_') and abs(
                            fluxes.loc[r]) >= params['error_tol']:
                        print r, fluxes.loc[r]
                        if fluxes.loc[r] == model.reactions.get_by_id(
                                r
                        ).lower_bound and not r.startswith('EX_photon'):
                            print r, 'is limiting'
                    elif r.startswith('sink_') and abs(
                            fluxes.loc[r]) > params['error_tol']:
                        print r, fluxes.loc[r]
                        if fluxes.loc[r] == model.reactions.get_by_id(
                                r).lower_bound:
                            print r, 'is limiting'
                    elif r.startswith('DM_') and abs(
                            fluxes.loc[r]) >= params['error_tol']:
                        print(r, fluxes.loc[r])

    return fluxes, status
Esempio n. 9
0
###

if __name__ == '__main__':

    printt('WELCOME')

    ###
    ### 0. user defined variables
    ###

    flux_weights_file = '/home/hpce17/hpce17000/projects/hpc/data/expression/formatted_flux_change_results_file.csv'
    model_file = '/home/hpce17/hpce17000/projects/hpc/data/Recon3DModel_301.mat'

    threads = 48

    cobra_config = cobra.Configuration()
    cobra_config.processes = threads
    print(cobra.Configuration())

    ###
    ### 1. read information
    ###

    printt('read information')

    ### 1.1. read boundary weights
    printt('read boundary expression weights')
    weights = pandas.read_csv(flux_weights_file, index_col=0)
    print(weights.shape)
    print(weights.head())