def zero_charge(metabolite): """ The chemical formulas of the input metabolites are modified to not carry any charge Parameters ---------- metabolite : cobra.Metabolite A metabolite in the cobra format including additional information (formula, charge, elements) Returns ------- formula : str The formula of the metabolite """ formula = Formula(metabolite.formula) if metabolite.charge != 0: if "desulfurated" in metabolite.name: formula.elements["S"] += metabolite.charge / 2 formula = Formula(print_formula(formula.elements)) else: if "H" in formula.elements and not np.isnan(metabolite.charge): formula.elements["H"] += -metabolite.charge formula = Formula(print_formula(formula.elements)) return formula
def weight(exchanges, what): """Obtain elemental weights for metabolites.""" mets = [list(r.metabolites)[0] for r in exchanges] if what is None: weights = {m: 1.0 for m in mets} elif what == "mass": weights = {m: max(Formula(m.formula).weight, 1e-2) for m in mets} elif what in elements_and_molecular_weights: weights = {m: Formula(m.formula).elements.get(what, 1e-2) for m in mets} else: raise ValueError( "%s is not a valid elements. Must be one of: %s." % (what, ", ".join(elements_and_molecular_weights)) ) return weights
def safe_weight(met): """Get the weight of a molecule.""" try: with warnings.catch_warnings(): warnings.simplefilter("ignore") w = max(Formula(met.formula).weight, 1.0) except Exception: w = 1.0 return w
def add_metabolite(self, cid, formula, name, compartment='C'): try: self.metabolites.index(cid) except ValueError: met = Metabolite(id=cid, formula=Formula(formula), name=name, compartment=compartment) self.cobra_model.add_metabolites([met])
import_mapping_tsv, create_database, ) current_dir = str(pathlib.Path(__file__).parent.absolute()) pd.set_option("mode.chained_assignment", None) # Use pickle to save python variables filehandler = open("test_data.obj", "wb") # load data and assign variables needed for the functions model_celegans = cobra.io.read_sbml_model(current_dir + "/../wormjam-20180125.sbml") metabolites = model_celegans.metabolites metabolite = metabolites[87] formula = Formula(metabolite.formula) elements = formula.elements # run functions and produce output formula_print = print_formula(elements) formula_zero_charge = zero_charge(metabolite) formulas = [] ids = [] for m in metabolites: if not is_valid(m): continue formula = zero_charge(m) formulas.append(str(formula)) ids.append(m.id) df_formulas = make_struct(formulas, ids) df_mapping = make_mapping(df_formulas)
def construct_universal_model(list_of_db_prefixes, reac_xref, reac_prop, chem_prop): """"Construct a universal model based on metanetx. Parameters ---------- list_of_db_prefixes : list A list of database prefixes, e.g., ['bigg', 'rhea'] reac_xref : pandas.DataFrame A dataframe of http://www.metanetx.org/cgi-bin/mnxget/mnxref/reac_xref.tsv reac_prop : pandas.DataFrame A dataframe of http://www.metanetx.org/cgi-bin/mnxget/mnxref/reac_prop.tsv chem_prop : pandas.DataFrame A dataframe of http://www.metanetx.org/cgi-bin/mnxget/mnxref/chem_prop.tsv """ # Select which reactions to include in universal reaction database mnx_reaction_id_selection = set() for db_prefix in list_of_db_prefixes: mnx_reaction_id_selection.update( reac_xref[reac_xref.XREF.str.startswith(db_prefix)].MNX_ID) reaction_selection = reac_prop.loc[mnx_reaction_id_selection] reactions = list() for index, row in reaction_selection.iterrows(): try: stoichiometry = parse_reaction(row.Equation, rev_arrow='=') except ValueError: continue else: for met, coeff in stoichiometry.items(): met.name = chem_prop.loc[met.id]['name'] try: met.formula = Formula(chem_prop.loc[met.id].formula) except: logger.debug('Cannot parse formula %s. Skipping formula' % chem_prop.loc[met.id].formula) continue try: met.charge = int(chem_prop.loc[met.id].charge) except (ValueError, TypeError): logger.debug('Cannot parse charge %s. Skipping charge' % chem_prop.loc[met.id].charge) pass rest = chem_prop.loc[met.id].to_dict() met.annotation = dict((key, rest[key]) for key in rest if key in ('mass', 'InChI', 'source')) mets = [met.id for met in stoichiometry.keys()] if len(mets) != len(set(mets)): continue reaction = Reaction(index) reaction.add_metabolites(stoichiometry) try: if len(reaction.check_mass_balance()) != 0: continue except (AttributeError, ValueError) as e: logger.debug(str(e)) continue if row.Balance: reaction.lower_bound = -1 * reaction.upper_bound reaction.name = row['Source'] row = row.fillna("") rest = row.to_dict() reaction.annotation = dict((key, rest[key]) for key in rest if key in ('EC', 'Description')) reactions.append(reaction) model = Model('metanetx_universal_model_' + '_'.join(list_of_db_prefixes)) model.add_reactions(reactions) # Add demands for all metabolites for metabolite in model.metabolites: model.add_boundary(metabolite, type='demand') return model