def load_yaml_model(filename): """ Load a cobra model from a file in YAML format. Parameters ---------- filename : str or file-like File path or descriptor that contains the YAML document describing the cobra model. Returns ------- cobra.Model The cobra model as represented in the YAML document. See Also -------- from_yaml : Load from a string. """ if isinstance(filename, string_types): with io.open(filename, "r") as file_handle: return model_from_dict(yaml.load(file_handle, yaml.RoundTripLoader)) else: return model_from_dict(yaml.load(filename, yaml.RoundTripLoader))
def _load_model(model_id): logger.debug(f"Requesting model {model_id} from the model warehouse") headers = {} # Check g for truthiness; false means there is no request context. This is necessary # in the production environment, where models are preloaded outside of any request # context. if g and g.jwt_valid: logger.debug(f"Forwarding provided JWT") headers["Authorization"] = f"Bearer {g.jwt_token}" response = requests.get( f"{app.config['MODEL_STORAGE_API']}/models/{model_id}", headers=headers) if response.status_code == 401: message = response.json().get("message", "No error message") raise Unauthorized(f"Invalid credentials ({message})") elif response.status_code == 403: message = response.json().get("message", "No error message") raise Forbidden( f"Insufficient permissions to access model {model_id} ({message})") elif response.status_code == 404: raise ModelNotFound(f"No model with id {model_id}") response.raise_for_status() logger.debug(f"Deserializing received model with cobrapy") model_data = response.json() _MODELS[model_id] = ModelWrapper( model_data["id"], model_from_dict(model_data["model_serialized"]), model_data["project_id"], model_data["organism_id"], model_data["default_biomass_reaction"], model_data["ec_model"], )
def load_json_model(filename): """ Load a cobra model from a file in JSON format. Parameters ---------- filename : str or file-like File path or descriptor that contains the JSON document describing the cobra model. Returns ------- cobra.Model The cobra model as represented in the JSON document. See Also -------- from_json : Load from a string. """ if isinstance(filename, str): with open(filename, "r") as file_handle: return model_from_dict(json.load(file_handle)) else: return model_from_dict(json.load(filename))
def load_yaml_model(filename): """ Load a cobra model from a file in YAML format. Parameters ---------- filename : str or file-like File path or descriptor that contains the YAML document describing the cobra model. Returns ------- cobra.Model The cobra model as represented in the YAML document. See Also -------- from_yaml : Load from a string. """ if isinstance(filename, string_types): with io.open(filename, "r") as file_handle: return model_from_dict(yaml.load(file_handle)) else: return model_from_dict(yaml.load(filename))
def validate_biomass(self, data): if "model_serialized" in data: # Validate that the model can be loaded by cobrapy try: model = model_from_dict(data["model_serialized"]) except Exception as error: raise ValidationError(str(error)) # Validate that given biomass reaction exists in the model if "default_biomass_reaction" in data: if data["default_biomass_reaction"] not in model.reactions: raise ValidationError( f"The biomass reaction " f"'{data['default_biomass_reaction']}' does not exist " f"in the corresponding model.")
def from_json(document): """ Load a cobra model from a JSON document. Parameters ---------- document : str The JSON document representation of a cobra model. Returns ------- cobra.Model The cobra model as represented in the JSON document. See Also -------- load_json_model : Load directly from a file. """ return model_from_dict(json.loads(document))
def from_yaml(document): """ Load a cobra model from a YAML document. Parameters ---------- document : str The YAML document representation of a cobra model. Returns ------- cobra.Model The cobra model as represented in the YAML document. See Also -------- load_yaml_model : Load directly from a file. """ return model_from_dict(yaml.load(document, yaml.RoundTripLoader))
def from_json(document): """ Load a cobra model from a JSON document. Parameters ---------- document : str The JSON document representation of a cobra model. Returns ------- cobra.Model The cobra model as represented in the JSON document. See Also -------- load_json_model : Load directly from a file. """ return model_from_dict(json.loads(document))
def from_yaml(document): """ Load a cobra model from a YAML document. Parameters ---------- document : str The YAML document representation of a cobra model. Returns ------- cobra.Model The cobra model as represented in the YAML document. See Also -------- load_yaml_model : Load directly from a file. """ content = StringIO(document) return model_from_dict(yaml.load(content))
def model_from_dict(obj, solver=None): # Take advantage of cobra's serialization of mets and reactions new = cbd.model_from_dict(obj) if solver is not None: try: new.solver = solver except SolverNotFound as snf: raise snf else: try: new.solver = obj['solver'] except KeyError: pass if obj['kind'] == 'ThermoModel': new = ThermoModel(thermo_data=obj['thermo_data'], model=new, name=obj['name'], temperature=obj['temperature'], min_ph=obj['min_ph'], max_ph=obj['max_ph']) new = init_thermo_model_from_dict(new, obj) new._update() for the_var_dict in obj['variables']: this_id = the_var_dict['id'] classname = the_var_dict['kind'] lb = the_var_dict['lb'] ub = the_var_dict['ub'] if classname in REACTION_VARIABLE_SUBCLASSES: hook = new.reactions.get_by_id(this_id) this_class = REACTION_VARIABLE_SUBCLASSES[classname] nv = new.add_variable(kind=this_class, hook=hook, ub=ub, lb=lb, queue=True) elif classname in METABOLITE_VARIABLE_SUBCLASSES: hook = new.metabolites.get_by_id(this_id) this_class = METABOLITE_VARIABLE_SUBCLASSES[classname] nv = new.add_variable(kind=this_class, hook=hook, ub=ub, lb=lb, queue=True) elif classname in ENZYME_VARIABLE_SUBCLASSES: hook = new.enzymes.get_by_id(this_id) this_class = ENZYME_VARIABLE_SUBCLASSES[classname] nv = new.add_variable(kind=this_class, hook=hook, ub=ub, lb=lb, queue=True) elif classname in MODEL_VARIABLE_SUBCLASSES: hook = new this_class = MODEL_VARIABLE_SUBCLASSES[classname] nv = new.add_variable(kind=this_class, hook=hook, id_=this_id, ub=ub, lb=lb, queue=True) else: raise TypeError( 'Class {} serialization not handled yet' \ .format(classname)) new._update() variable_parse_dict = {x.name: x for x in new.variables} for the_cons_dict in obj['constraints']: this_id = the_cons_dict['id'] classname = the_cons_dict['kind'] new_expr = parse_expr(the_cons_dict['expression'], local_dict=variable_parse_dict) # str_expr = the_cons_dict['expression'] # # # Sympify the expression so that we can substitute variables afterwards # sym_expr = sympify(str_expr) # # subs_dict = {x:new.variables.get(x.name) for x in sym_expr.free_symbols} # # new_expr = sym_expr.subs(subs_dict) lb = the_cons_dict['lb'] ub = the_cons_dict['ub'] if classname in REACTION_CONSTRAINT_SUBCLASSES: hook = new.reactions.get_by_id(this_id) this_class = REACTION_CONSTRAINT_SUBCLASSES[classname] nc = new.add_constraint(kind=this_class, hook=hook, expr=new_expr, ub=ub, lb=lb, queue=True) elif classname in METABOLITE_CONSTRAINT_SUBCLASSES: hook = new.metabolites.get_by_id(this_id) this_class = METABOLITE_CONSTRAINT_SUBCLASSES[classname] nc = new.add_constraint(kind=this_class, hook=hook, expr=new_expr, ub=ub, lb=lb, queue=True) elif classname in ENZYME_CONSTRAINT_SUBCLASSES: hook = new.enzymes.get_by_id(this_id) this_class = ENZYME_CONSTRAINT_SUBCLASSES[classname] nc = new.add_constraint(kind=this_class, hook=hook, expr=new_expr, ub=ub, lb=lb, queue=True) elif classname in MODEL_CONSTRAINT_SUBCLASSES: hook = new this_class = MODEL_CONSTRAINT_SUBCLASSES[classname] nc = new.add_constraint(kind=this_class, hook=hook, expr=new_expr, id_=this_id, ub=ub, lb=lb, queue=True) else: raise TypeError('Class {} serialization not handled yet' \ .format(classname)) new._update() new.repair() # Relaxation info try: new.relaxation = obj['relaxation'] except KeyError: pass return new
def model_from_dict(obj, solver=None, custom_hooks=None): """ Custom_hooks looks like .. code:: python custom_hooks = {<EnzymeVariable Class at 0xffffff> : 'enzymes', ... } :param obj: :param solver: :param custom_hooks: :return: """ # Take advantage of cobra's serialization of mets and reactions cbm = cbd.model_from_dict(obj) if solver is not None: try: cbm.solver = solver except SolverNotFound as snf: raise snf else: try: cbm.solver = obj['solver'] except KeyError: pass if custom_hooks is None: custom_hooks = dict() custom_hooks.update(BASE_NAME2HOOK) if obj['kind'] == 'ThermoModel': new = ThermoModel(thermo_data=obj['thermo_data'], model=cbm, name=obj['name'], temperature=obj['temperature'], min_ph=obj['min_ph'], max_ph=obj['max_ph']) new = init_thermo_model_from_dict(new, obj) else: new = ThermoModel(model=cbm, name=obj['name']) new._push_queue() name2class, name2hook = add_custom_classes(new, custom_hooks) for the_var_dict in obj['variables']: this_id = the_var_dict['id'] classname = the_var_dict['kind'] lb = the_var_dict['lb'] ub = the_var_dict['ub'] scaling_factor = the_var_dict['scaling_factor'] if classname in get_model_variable_subclasses(): hook = new this_class = get_model_variable_subclasses()[classname] nv = new.add_variable(kind=this_class, hook=hook, id_=this_id, ub=ub, lb=lb, queue=True, scaling_factor=scaling_factor) elif classname in name2class: hook = name2hook[classname].get_by_id(this_id) this_class = name2class[classname] nv = new.add_variable(kind=this_class, hook=hook, ub=ub, lb=lb, queue=True, scaling_factor=scaling_factor) else: raise TypeError( 'Class {} serialization not handled yet' \ .format(classname)) new._push_queue() variable_parse_dict = {x.name: x for x in new.variables} for the_cons_dict in obj['constraints']: this_id = the_cons_dict['id'] classname = the_cons_dict['kind'] new_expr = parse_expr(the_cons_dict['expression'], local_dict=variable_parse_dict) # str_expr = the_cons_dict['expression'] # # # Sympify the expression so that we can substitute variables afterwards # sym_expr = sympify(str_expr) # # subs_dict = {x:new.variables.get(x.name) for x in sym_expr.free_symbols} # # new_expr = sym_expr.subs(subs_dict) lb = the_cons_dict['lb'] ub = the_cons_dict['ub'] # Look for the corresponding class: if classname in get_model_constraint_subclasses(): hook = new this_class = get_model_constraint_subclasses()[classname] nc = new.add_constraint(kind=this_class, hook=hook, expr=new_expr, id_=this_id, ub=ub, lb=lb, queue=True) elif classname in name2class: hook = name2hook[classname].get_by_id(this_id) this_class = name2class[classname] nc = new.add_constraint(kind=this_class, hook=hook, expr=new_expr, ub=ub, lb=lb, queue=True) else: raise TypeError('Class {} serialization not handled yet' \ .format(classname)) new.repair() try: rebuild_obj_from_dict(new, obj['objective']) except KeyError: pass # Relaxation info try: new.relaxation = obj['relaxation'] except KeyError: pass return new
def model_from_dict(obj, solver=None): # Take advantage of cobra's serialization of mets and reactions new = cbd.model_from_dict(obj) if solver is not None: try: new.solver = solver except SolverNotFound as snf: raise snf else: try: new.solver = obj['solver'] except KeyError: pass # Populate variables and constraints if obj['kind'] == 'ThermoMEModel': new = ThermoMEModel(thermo_data=obj['thermo_data'], model=new, name=obj['name'], temperature=obj['temperature'], min_ph=obj['min_ph'], max_ph=obj['max_ph']) new = init_thermo_me_model_from_dict(new, obj) elif obj['kind'] == 'MEModel': # Cast to MEModel new = MEModel(new) new = init_me_model_from_dict(new, obj) elif obj['kind'] == 'ThermoModel': new = ThermoModel(thermo_data=obj['thermo_data'], model=new, name=obj['name'], temperature=obj['temperature'], min_ph=obj['min_ph'], max_ph=obj['max_ph']) new = init_thermo_model_from_dict(new, obj) new._push_queue() # Force update GPR info for rxn in new.reactions: rxn.gene_reaction_rule = rxn.gene_reaction_rule for the_var_dict in tqdm(obj['variables'], desc='rebuilding variables'): this_id = the_var_dict['id'] classname = the_var_dict['kind'] lb = the_var_dict['lb'] ub = the_var_dict['ub'] try: #Backward compat scaling_factor = the_var_dict['scaling_factor'] except KeyError: scaling_factor = 1 rebuild_variable(classname, new, this_id, lb, ub, scaling_factor) new._push_queue() variable_parse_dict = {x.name: x for x in new.variables} for the_cons_dict in tqdm(obj['constraints'], desc='rebuilding constraints'): this_id = the_cons_dict['id'] classname = the_cons_dict['kind'] new_expr = parse_expr(the_cons_dict['expression'], local_dict=variable_parse_dict) # str_expr = the_cons_dict['expression'] # # # Sympify the expression so that we can substitute variables afterwards # sym_expr = sympify(str_expr) # # subs_dict = {x:new.variables.get(x.name) for x in sym_expr.free_symbols} # # new_expr = sym_expr.subs(subs_dict) lb = the_cons_dict['lb'] ub = the_cons_dict['ub'] rebuild_constraint(classname, new, this_id, new_expr, lb, ub) # Mu variable handle for ME-models if obj['kind'] in ['ThermoMEModel', 'MEModel']: prostprocess_me(new) try: rebuild_obj_from_dict(new, obj['objective']) except KeyError: pass new.repair() return new