Пример #1
0
def get_model_from_bigg(id):
    try:
        response = requests.get('http://bigg.ucsd.edu/api/v2/models/{}/download'.format(id))
    except requests.ConnectionError as e:
        logger.error("Cannot reach http://bigg.ucsd.edu. Are you sure that you are connected to the internet?")
        raise e
    if response.ok:
        with io.StringIO(response.text) as f:
            return to_solver_based_model(load_json_model(f))
    else:
        raise Exception(
            "Could not download model {}. bigg.ucsd.edu returned status code {}".format(id, response.status_code))
Пример #2
0
def load_model(path_or_handle, solver_interface=optlang, sanitize=True):
    """Read a metabolic model .

    Parameters
    ----------
    path_or_handle : path, fhandle or name.
        One of:
            * file path of a model file;
            * file handle to a SBML or pickled model; or
            * the identifier of a model in a web database (optflux.org/models)
    solver_interface : solver_interface, optional
        E.g. optlang.glpk_interface or any other optlang interface.
    sanitize : boolean, optional
        If reaction and metabolite IDs should be sanitized (works only for SBML models).
    """
    solver_interface = solvers.get(solver_interface, solver_interface)

    if isinstance(path_or_handle, six.string_types) and not os.path.isfile(path_or_handle):
        from cameo.models.webmodels import load_webmodel
        logger.debug("Given path is not a file. Trying to load from webmodels")
        model = load_webmodel(path_or_handle, solver_interface)
    else:
        if isinstance(path_or_handle, six.string_types):
            # Open the given file
            path = path_or_handle
            handle = open(path_or_handle, 'rb')
        elif hasattr(path_or_handle, 'read'):
            # Argument is already an open file
            path = path_or_handle.name
            handle = path_or_handle
        else:
            raise ValueError('Provided argument %s has to be either a string or a file handle' % path_or_handle)
        model = _load_model_from_file(path, handle)  # Parse model from the file

    if sanitize:
        sanitize_ids(model)

    if not isinstance(model, SolverBasedModel):
        if solver_interface is not None:
            logger.debug("Changing solver interface to %s" % solver_interface)
            model = to_solver_based_model(model, solver_interface=solver_interface)
    else:
        if solver_interface is not None and not isinstance(model.solver, solver_interface.Model):
            logger.debug("Changing solver interface to %s" % solver_interface)
            model.solver = solver_interface

    return model
Пример #3
0
def get_model_from_uminho(index, host="http://darwin.di.uminho.pt/models"):
    sbml_file = get_sbml_file(index, host)
    sbml_file.close()
    return to_solver_based_model(read_sbml_model(sbml_file.name))
Пример #4
0
 def setUp(self):
     # Make Model pickable and then load a solver based version of test_pickle
     self.model = to_solver_based_model(create_test_model("textbook"))
def setUp(self):
    # Make Model pickable and then load a solver based version of test_pickle
    self.model = to_solver_based_model(create_test_model())
    self.model_class = SolverBasedModel
Пример #6
0
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.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 cobra.io import read_sbml_model
from optlang import glpk_interface
import inspyred

from cameo.strain_design.heuristic.multiprocess import MultiprocessReactionKnockoutOptimization
from cameo.strain_design.heuristic.objective_functions import biomass_product_coupled_yield
from cameo.flux_analysis.simulation import fba
from cameo.core.solver_based_model import to_solver_based_model

model = read_sbml_model("../tests/data/iJO1366.xml")
model = to_solver_based_model(model, solver_interface=glpk_interface)

of = biomass_product_coupled_yield("Ec_biomass_iJO1366_core_53p95M", "EX_ac_LPAREN_e_RPAREN_",
                                   "EX_glc_LPAREN_e_RPAREN_")

mp = MultiprocessReactionKnockoutOptimization(model=model, heuristic_method=inspyred.ec.GA,
                                              objective_function=of, simulation_method=fba)

mp.run(max_evaluations=300, n=2)
Пример #7
0
def model():
    return to_solver_based_model(create_test_model("textbook"))
Пример #8
0
def load_model(path_or_handle, solver_interface=optlang.glpk_interface, sanitize=True):
    """Read a metabolic model .

    Parameters
    ----------
    path_or_handle : path, fhandle or name.
        One of:
            * file path of a model file;
            * file handle to a SBML or pickled model; or
            * the identifier of a model in a web database (optflux.org/models)
    solver_interface : solver_interface, optional
        E.g. optlang.glpk_interface or any other optlang interface.
    sanitize : boolean, optional
        If reaction and metabolite IDs should be sanitized (works only for SBML models).
    """

    if isinstance(path_or_handle, str):
        path = path_or_handle
        try:
            handle = open(path_or_handle, 'rb')
        except IOError:
            logger.debug('%s not a file path. Querying webmodels ... trying http://bigg.ucsd.edu first' % path)
            try:
                return cameo.models.webmodels.get_model_from_bigg(path)
            except:
                logger.debug('%s not a file path. Querying webmodels ... trying minho next' % path)
                try:
                    df = cameo.models.webmodels.index_models_minho()
                except requests.ConnectionError as e:
                    logger.error("You need to be connected to the internet to load an online model.")
                    raise e
                except Exception as e:
                    logger.error("Something went wrong while looking up available webmodels.")
                    raise e
                try:
                    index = df.query('name == "%s"' % path_or_handle).id.values[0]
                    handle = cameo.models.webmodels.get_sbml_file(index)
                    path = handle.name
                except IndexError:
                    raise ValueError("%s is neither a file nor a model ID." % path)
    elif hasattr(path_or_handle, 'read'):
        path = path_or_handle.name
        handle = path_or_handle
    else:
        raise ValueError('Provided argument %s has to be either a file path or handle' % path_or_handle)
    logger.debug('Reading file from %s assuming pickled model.' % path)
    try:
        model = pickle.load(handle)
    except Exception:
        logger.debug('Cannot unpickle %s. Assuming json model next.' % path)
        try:
            model = load_json_model(path)
        except Exception:
            logger.debug("Cannot import %s as json model. Assuming sbml model next." % path)
            try:
                model = read_sbml_model(path)
            except AttributeError as e:
                logger.error("cobrapy doesn't raise a proper exception if a file does not contain an SBML model")
                raise e
            except Exception as e:
                logger.error(
                    "Looks like something blow up while trying to import {} as a SBML model. Try validating the model at http://sbml.org/Facilities/Validator/ to get more information.".format(
                        path))
                raise e
    if sanitize:
        sanitize_ids(model)

    if not isinstance(model, SolverBasedModel):
        if solver_interface is not None:
            logger.debug("Changing solver interface to %s" % solver_interface)
            model = to_solver_based_model(model, solver_interface=solver_interface)
    else:
        if model.interface is not solver_interface and solver_interface is not None:
            logger.debug("Changing solver interface to %s" % solver_interface)
            model.solver = solver_interface

    return model
def setUp(self):
    # Make Model pickable and then load a solver based version of test_pickle
    self.model = to_solver_based_model(create_test_model())
    self.model_class = SolverBasedModel
Пример #10
0
#     http://www.apache.org/licenses/LICENSE-2.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 cobra.io import read_sbml_model
from optlang import glpk_interface
import inspyred

from cameo.strain_design.heuristic.multiprocess import MultiprocessReactionKnockoutOptimization
from cameo.strain_design.heuristic.objective_functions import biomass_product_coupled_yield
from cameo.flux_analysis.simulation import fba
from cameo.core.solver_based_model import to_solver_based_model

model = read_sbml_model("../tests/data/iJO1366.xml")
model = to_solver_based_model(model, solver_interface=glpk_interface)

of = biomass_product_coupled_yield("Ec_biomass_iJO1366_core_53p95M",
                                   "EX_ac_LPAREN_e_RPAREN_",
                                   "EX_glc_LPAREN_e_RPAREN_")

mp = MultiprocessReactionKnockoutOptimization(model=model,
                                              heuristic_method=inspyred.ec.GA,
                                              objective_function=of,
                                              simulation_method=fba)

mp.run(max_evaluations=300, n=2)