Exemple #1
0
def elasticities_by_medium(com, reactions, fraction, growth_rate, progress):
    """Get the elasticity coefficients for a set of variables.

    Arguments
    ---------
    com : micom.Community
        The community for wrhich to calculate elasticities.
    variables : list of optlang.Variable
        The variables for which to calculate the elasticities. All of these
        must have non-zero primal vaues in the previous solution.

    Returns
    -------
    pandas.Dataframe
        The long/tidy version of the elasticities. Contains columns variable,
        effector, and elasticity.
    """
    regularize_l2_norm(com, 0.0)
    sol = optimize_with_fraction(com, fraction, growth_rate, True)
    before = _get_fluxes(sol, reactions)
    import_fluxes = pd.Series()
    dfs = []

    for ex in com.exchanges:
        export = len(ex.reactants) == 1
        flux = sol.fluxes.loc[ex.community_id, ex.global_id]
        if export and (flux < -1e-6):
            import_fluxes[ex] = flux
        elif not export and (flux > 1e-6):
            import_fluxes[ex] = -flux
        else:
            continue

    fluxes = import_fluxes.index
    if progress:
        fluxes = track(fluxes, description="Metabolites")
    for r in fluxes:
        flux = import_fluxes[r]
        with com:
            if flux < -1e-6:
                r.lower_bound *= np.exp(STEP)
            else:
                r.upper_bound *= np.exp(STEP)
            sol = optimize_with_fraction(com, fraction, growth_rate, True)
            after = _get_fluxes(sol, reactions)
        deriv, dirs = _derivatives(before, after)
        res = pd.DataFrame({
            "reaction": [rx.global_id for rx in reactions],
            "taxon": [list(r.compartments)[0] for r in reactions],
            "effector":
            r.id,
            "direction":
            dirs,
            "elasticity":
            deriv,
        })
        dfs.append(res)

    return pd.concat(dfs)
Exemple #2
0
def elasticities_by_abundance(com, reactions, fraction, growth_rate, progress):
    """Get the elasticity coefficients for a set of variables.

    Arguments
    ---------
    com : micom.Community
        The community for which to calculate elasticities.
    variables : list of optlang.Variable
        The variables for which to calculate the elasticities. All of these
        must have non-zero primal vaues in the previous solution.

    Returns
    -------
    pandas.Dataframe
        The long/tidy version of the elasticities. Contains columns variable,
        effector, and elasticity.
    """
    regularize_l2_norm(com, 0.0)
    sol = optimize_with_fraction(com, fraction, growth_rate, True)
    before = _get_fluxes(sol, reactions)
    dfs = []

    abundance = com.abundances.copy()
    taxa = abundance.index

    if progress:
        taxa = track(taxa, description="Taxa")
    for sp in taxa:
        old = abundance[sp]
        abundance.loc[sp] *= np.exp(STEP)
        com.set_abundance(abundance, normalize=False)
        sol = optimize_with_fraction(com, fraction, growth_rate, True)
        after = _get_fluxes(sol, reactions)
        abundance.loc[sp] = old
        com.set_abundance(abundance, normalize=False)
        deriv, dirs = _derivatives(before, after)
        res = pd.DataFrame({
            "reaction": [r.global_id for r in reactions],
            "taxon": [list(r.compartments)[0] for r in reactions],
            "effector":
            sp,
            "direction":
            dirs,
            "elasticity":
            deriv,
        })
        dfs.append(res)

    return pd.concat(dfs)
Exemple #3
0
def knockout_taxa(
    community, taxa, fraction, method, progress, diag=True
):
    """Knockout a taxon from the community."""
    with community as com:
        check_modification(com)
        min_growth = _format_min_growth(0.0, com.taxa)
        _apply_min_growth(com, min_growth)

        com.objective = com.scale * com.variables.community_objective
        community_min_growth = (
            optimize_with_retry(com, "could not get community growth rate.")
            / com.scale
        )
        regularize_l2_norm(com, fraction * community_min_growth)
        old = com.optimize().members["growth_rate"]
        results = []

        iter = track(taxa, description="Knockouts") if progress else taxa
        for sp in iter:
            with com:
                logger.info("getting growth rates for " "%s knockout." % sp)
                [
                    r.knock_out()
                    for r in com.reactions.query(
                        lambda ri: ri.community_id == sp
                    )
                ]

                sol = optimize_with_fraction(com, fraction)
                new = sol.members["growth_rate"]
                if "change" in method:
                    new = new - old
                if "relative" in method:
                    new /= old
                results.append(new)

        ko = pd.DataFrame(results, index=taxa).drop("medium", 1)
        ko = ko.loc[ko.index.sort_values(), ko.columns.sort_values()]
        if not diag:
            np.fill_diagonal(ko.values, np.NaN)

        return ko
Exemple #4
0
def knockout_species(community,
                     species,
                     fraction,
                     method,
                     progress,
                     diag=True):
    """Knockout a species from the community."""
    with community as com:
        check_modification(com)
        min_growth = _format_min_growth(0.0, com.species)
        _apply_min_growth(com, min_growth)

        com.objective = 1000.0 * com.variables.community_objective
        community_min_growth = (
            optimize_with_retry(com, "could not get community growth rate.") /
            1000.0)
        regularize_l2_norm(com, fraction * community_min_growth)
        old = com.optimize().members["growth_rate"]
        results = []

        if progress:
            species = tqdm(species, unit="knockout(s)")
        for sp in species:
            with com:
                logger.info("getting growth rates for " "%s knockout." % sp)
                [
                    r.knock_out() for r in com.reactions.query(
                        lambda ri: ri.community_id == sp)
                ]

                sol = optimize_with_fraction(com, fraction)
                new = sol.members["growth_rate"]
                if "change" in method:
                    new = new - old
                if "relative" in method:
                    new /= old
                results.append(new)

        ko = pd.DataFrame(results, index=species).drop("medium", 1)
        if not diag:
            np.fill_diagonal(ko.values, np.NaN)

        return ko
Exemple #5
0
def test_fraction(community):
    sol = ms.optimize_with_fraction(community, 0.5)
    assert sol.growth_rate == approx(0.874, 0.001)