Exemple #1
0
 def __init__(self,
              community,
              slim=False,
              reactions=None,
              metabolites=None):
     """Get the solution from a community model."""
     if reactions is None:
         reactions = community.reactions
     if metabolites is None:
         metabolites = community.metabolites
     rids = np.array([(r.global_id, r.community_id) for r in reactions])
     mids = np.array([(m.global_id, m.community_id) for m in metabolites])
     if not slim:
         var_primals = community.solver.primal_values
         fluxes = pd.Series(
             [
                 var_primals[r.id] - var_primals[r.reverse_id]
                 for r in reactions
             ],
             name="fluxes",
         )
         super(CommunitySolution, self).__init__(
             community.solver.objective.value,
             community.solver.status,
             _group_taxa(fluxes, rids[:, 0], rids[:, 1]),
             None,
             None,
         )
     else:
         super(CommunitySolution, self).__init__(
             community.solver.objective.value,
             community.solver.status,
             None,
             None,
             None,
         )
     gcs = pd.Series()
     for sp in community.taxa:
         gcs[sp] = community.constraints["objective_" + sp].primal
     # Workaround for an optlang bug (PR #120)
     if interface_to_str(community.problem) == "gurobi":
         gcs = gcs.abs()
     self.strategy = community.modification
     self.members = pd.DataFrame({
         "abundance":
         community.abundances,
         "growth_rate":
         gcs,
         "reactions":
         pd.Series(Counter(rids[:, 1])),
         "metabolites":
         pd.Series(Counter(mids[:, 1])),
     })
     self.members.index.name = "compartments"
     self.growth_rate = sum(community.abundances * gcs)
     # Save estimated accuracy for osqp
     if interface_to_str(community.problem) == "osqp":
         self.primal_residual = community.solver.problem.info.pri_res
         self.dual_residual = community.solver.problem.info.dua_res
Exemple #2
0
def cooperative_tradeoff(community, min_growth, fraction, fluxes, pfba):
    """Find the best tradeoff between community and individual growth."""
    with community as com:
        solver = interface_to_str(community.problem)
        check_modification(community)
        min_growth = _format_min_growth(min_growth, community.taxa)
        _apply_min_growth(community, min_growth)

        com.objective = com.scale * com.variables.community_objective
        min_growth = (optimize_with_retry(
            com, message="could not get community growth rate.") / com.scale)
        if not isinstance(fraction, Sized):
            fraction = [fraction]
        else:
            fraction = np.sort(fraction)[::-1]

        # Add needed variables etc.
        regularize_l2_norm(com, 0.0)
        results = []
        for fr in fraction:
            com.variables.community_objective.lb = fr * min_growth
            com.variables.community_objective.ub = min_growth
            sol = solve(community, fluxes=fluxes, pfba=pfba)
            # OSQP is better with QPs then LPs
            # so it won't get better with the crossover
            if (sol.status != OPTIMAL and solver != "osqp"):
                sol = crossover(com, sol, fluxes=fluxes, pfba=pfba)
            results.append((fr, sol))
        if len(results) == 1:
            return results[0][1]
        return pd.DataFrame.from_records(results,
                                         columns=["tradeoff", "solution"])
Exemple #3
0
def reset_solver(community):
    """Reset the solver."""
    interface = interface_to_str(community.solver.interface)
    logger.info("resetting solver, hoping for the best.")
    if interface == "cplex":
        logger.warning("switching cplex LP algorithm to `network`.")
        community.solver.configuration.lp_method = "network"
    elif interface == "gurobi":
        community.solver.problem.reset()
    elif interface == "glpk":
        glp_adv_basis(community.solver.problem, 0)
Exemple #4
0
def reset_solver(community):
    """Reset the solver."""
    interface = interface_to_str(community.solver.interface)
    logger.info("resetting solver, hoping for the best.")
    if interface == "cplex":
        community.solver.configuration.lp_method = "network"
        community.solver.configuration.lp_method = "barrier"
    elif interface == "gurobi":
        community.solver.problem.reset()
    elif interface == "glpk":
        glp_adv_basis(community.solver.problem, 0)
    elif interface == "osqp":
        community.solver.problem.reset()