"""Workflow to run cooperative tradeoff with various tradeoff values."""fromcobra.util.solverimportOptimizationErrorfrommicomimportload_picklefrommicom.loggerimportloggerfrommicom.workflows.coreimportworkflowfrommicom.workflows.mediaimportprocess_mediumimportnumpyasnpfromosimportpathimportpandasaspd
[docs]def_tradeoff(args):p,tradeoffs,medium,atol,rtol,presolve=argscom=load_pickle(p)ex_ids=[r.idforrincom.exchanges]logger.info("%d/%d import reactions found in model.",medium.index.isin(ex_ids).sum(),len(medium),)com.medium=medium[medium.index.isin(ex_ids)]com.solver.configuration.presolve=presolvetry:sol=com.optimize(rtol=rtol,atol=atol)exceptException:logger.error("Sample %s could not be optimized (%s)."%(com.id,com.solver.status),)returnNonerates=sol.membersrates["taxon"]=rates.indexrates["tradeoff"]=np.nanrates["sample_id"]=com.iddf=[rates]# Get growth ratestry:sol=com.cooperative_tradeoff(fraction=tradeoffs)exceptException:logger.warning("Sample %s could not be optimized with cooperative tradeoff (%s)."%(com.id,com.solver.status),)returnNonefori,sinenumerate(sol.solution):rates=s.membersrates["taxon"]=rates.indexrates["tradeoff"]=sol.tradeoff[i]rates["sample_id"]=com.iddf.append(rates)df=pd.concat(df)returndf[df.taxon!="medium"]
[docs]deftradeoff(manifest,model_folder,medium,tradeoffs=np.arange(0.1,1.0+1e-6,0.1),threads=1,atol=None,rtol=None,presolve=False,):"""Run growth rate predictions for varying tradeoff values. Parameters ---------- manifest : pandas.DataFrame The manifest as returned by the `build` workflow. model_folder : str The folder in which to find the files mentioned in the manifest. medium : pandas.DataFrame A growth medium. Must have columns "reaction" and "flux" denoting exchnage reactions and their respective maximum flux. tradeoffs : array of floats in (0.0, 1.0] An array of tradeoff vaues to be tested. One simulation without a tradeoff (no cooperative tradeoff) will always be run additionally and will have a tradeoff of "NaN". threads : int >=1 The number of parallel workers to use when building models. As a rule of thumb you will need around 1GB of RAM for each thread. atol : float Absolute tolerance for the growth rates. If None will use the solver tolerance. rtol : float Relative tolerqance for the growth rates. If None will use the solver tolerance. presolve : bool Whether to use the presolver/scaling. Can improve numerical accuracy in some cases. Returns ------- pandas.DataFrame The predicted growth rates. """samples=manifest.sample_id.unique()paths={s:path.join(model_folder,manifest[manifest.sample_id==s].file.iloc[0])forsinsamples}ifany(t<0.0ort>1.0fortintradeoffs):raiseValueError("tradeoff values must between 0 and 1 :(")medium=process_medium(medium,samples)args=[[p,tradeoffs,medium.flux[medium.sample_id==s],atol,rtol,presolve]fors,pinpaths.items()]results=workflow(_tradeoff,args,threads)ifall(risNoneforrinresults):raiseOptimizationError("All numerical optimizations failed. This indicates a problem ""with the solver or numerical instabilities. Check that you have ""CPLEX or Gurobi installed. You may also increase the abundance ""cutoff in `qiime micom build` to create simpler models or choose ""a more permissive solver tolerance.")results=pd.concat(results)returnresults