Skip to content

API Reference

Generated from the docstrings in package/gifba/.

gifba.gifbaObject

gifbaObject(models, media, rel_abund='equal', **kwargs)

A microbial community simulated with greedy interaction FBA.

Wraps a list of cobra.Model instances (deep-copied on construction) and runs the giFBA fixed-point loop over a shared media. Can be used as a context manager (with gifbaObject(...) as community:), which is currently a no-op passthrough.

Parameters:

Name Type Description Default
models Model | list[Model]

The organism model(s) in the community. Deep-copied internally.

required
media dict[str, float] | str | list | None

Shared exchange media. A dict maps exchange IDs to fluxes (negative = uptake available). "complete" or None opens every exchange to -1000. A [base_media_dict, min_growth_float] list derives a minimal medium via utils.find_min_medium.

required
rel_abund str | array - like

Relative abundance per model. "equal" (default) splits evenly; otherwise a 1D array-like of length len(models), normalized to sum to 1.

'equal'

Other Parameters:

Name Type Description
threshold float

Convergence tolerance. Defaults to 1e-12.

oc_rounding int

Decimal places used when checking overconsumption. Defaults to config.ROUND (6).

oc_method str

Overconsumption-correction algorithm, "optim" for a scipy-based LP-optimization approach or "newton" for a Newton-Raphson approach. Defaults to "optim".

community_id str | None

Optional label for the community, used by utils.prepare_compartmentalized_model*.

debug bool

Verbose per-iteration/per-rerun debug printing - primarily included for development purposes. Defaults to False.

verbose bool

Print Iterations/convergence progress and overconsumption progress. Defaults to False.

Attributes:

Name Type Description
models list[Model]

The (copied) community models.

media dict[str, float]

Resolved media dict after validation.

num_models int

Number of organisms in the community.

rel_abund ndarray

Resolved relative abundance column-vector, shape (num_models, 1).

objective_rxns dict[int, str]

{model_index: objective_reaction_id} for each model's linear objective.

simulation_count int

Running count of LP solves that cleared the minimum growth cutoff.

env_fluxes DataFrame

Full media flux history, indexed by Iteration, columns are exchange IDs. Index 0 indicates based media for system. Set by run_gifba.

org_fluxes DataFrame

Full per-organism flux history, indexed by (Model, Iteration), columns are reaction IDs. Iteration 0 indices indicate growth/fluxes on the base media - iteration n simulates growht on the n-th iteration media of env_fluxes Set by run_gifba.

iter_converged int | None

Iteration where convergence/periodicity was detected, or None. Set by run_gifba.

periodicity int | None

Length of the detected attractor cycle (1 = true fixed point), or None if no convergence detected. Set by run_gifba.

exchange_ids list[str]

Unique exchange IDs across the whole community. Set by create_vars.

reaction_ids list[str]

Unique reaction IDs across the whole community. Set by create_vars.

exchange_to_metabolite_id dict[str, str]

Exchange ID to metabolite ID lookup, used for reporting. Set by create_vars.

metabolite_id_to_name dict[str, str]

Metabolite ID to name lookup, used for reporting. Set by create_vars.

model_names dict[int, str]

{model_index: model.name}. Set by create_vars.

run_gifba

run_gifba(n_iterations: int, method: Literal['pfba', 'fba'], threshold: float | None = None, attractor_size: float | None = None, relaxation_ratio: float | None = None, fp_method: Literal['picard', 'relaxation'] | None = None, verbose: bool = False, debug: bool = False) -> tuple[pd.Series, pd.DataFrame]

Run giFBA for a given number of iterations on the community of models with the given media.

[Flow / Hierarchy] Call create_vars() to initialize storage variables for the simulation. Call _update_media() for each iteration to simulate growth at each discrete step and update state variables in accordance with fixed point iteration-based solver method. See _update_media() for more details. Check fixed point convergence by comparing current iteration to all previous iterations to identify fixed points/periodic behavior. Upon completion/convergence, call average_periodicity() to perform element-wise average of state variables in fixed point/period/attractor.

Parameters:

Name Type Description Default
n_iterations int

Maximum number of iterations to run the simulation.

required
method str

The FBA method to use for the simulation - must be "pfba" (recommended) or "fba".

required
threshold float

The numerical threshold for convergence. Defaults to 1e-12 if None provided.

None
attractor_size float

The size of the attractor (in percentage of number of iterations) if convergence is not achieved. For a 10 iteration simulation, an attractor of size 0.9 would correspond to averaging over the last 9 iterations. Defaults to 0.9 if None provided.

None
relaxation_ratio float

Ratio value chosen for relaxation method used in fixed point solver. Defaults to 1.0 if None provided. Ignored when fp_method is "picard".

None
fp_method str

The fixed point solver method to use for the simulation - must be "picard" or "relaxation" (recommended). Defaults to "relaxation" if None provided, so relaxation_ratio still applies. "picard" is relaxation with relaxation_ratio forced to 1.0. "anderson" is reserved and not yet implemented.

None
v bool

Toggle verbose output. True will provide printed outputs for current iteration and any re-runs from overconsumption adjustment. Defaults to False.

required
debug bool

Development mode. True will provide additional debugging information detailing the simulation process (media & org. fluxes at each step, overconsumption ratio, overconsumption adjustment). Not recommended for real-world community models. Defaults to False.

False

Raises:

Type Description
NotImplementedError

If fp_method is "anderson". Raised before any solving starts.

State Modified (Side Effects): self.env_fluxes (pd.DataFrame): Full environmental fluxes DataFrame for all iterations and runs. Multi-indexed by iteration and run, with columns as unique exchange reaction IDs for the entire community (size=(n_iterations, n_exchanges)). (runs currently unused and part of future development). Units in ( mmol/(gT * hr) ). self.org_fluxes (pd.DataFrame): Full organism fluxes DataFrame for all iterations and runs. Multi-indexed by model, iteration, and run, with columns as unique (internal and exchange) reaction IDs for the entire community (size=(n_iterations*n_models, n_reactions)). (runs currently unused and part of future development). Units in ( mmol/(gT * hr) ). self.periodicity (int): Period of the system if convergence is achieved. If convergence is not achieved, this will be None. self.iter_converged (int): Iteration at which convergence is achieved. If convergence is not achieved, this will be None.

Returns:

Type Description
tuple[Series, DataFrame]

A tuple containing two pandas objects for simulation steady-state fluxes: - pd.Series: Media/Environment fluxes ($f_{n,j}$) at steady state in units of ( mmol/(gT * hr) ). Size=(n_exchanges,). Returns fixed points, average of periodic fixed points, or average of last * if convergence is not achieved. - pd.DataFrame: Per-organism fluxes ($V_{i,j}$) at steady state in units of ( mmol/(gT * hr) ). Size=(n_models, n_reactions). Returns fixed points, average of periodic fixed points, or average of last * if convergence is not achieved.

Calls
  • self.create_vars()
  • self._update_media()
  • self.average_periodicity()

create_vars

create_vars(m_vals=[1, 1])

Initialize storage for state variables, set initial media, and extract pertinent community details.

Called automatically at the start of run_gifba; only call directly if you need a freshly-initialized community without running it.

[Flow / Hierarchy] Setup method. Called at the beginning of the simulation before the iterative fixed-point solver begins.

Parameters:

Name Type Description Default
m_vals list[int]

Currently unused; reserved for future package development. Defaults to [1,1] representing each iteration uses 1 input run to modify 1 output run, per iteration. Standard giFBA currently only uses 1 run per iteration.

[1, 1]

State Inputs (Attributes Used): self.media (dict[str, float]): The baseline media conditions for the community. Keys are exchange IDs and values are fluxes (which must be negative). self.models (list[cb.Model]): A list of all Cobra models present in the community. self.n_iterations (int): The total number of iterations to run for the simulation. self.num_models (int): The total number of models in the community.

State Modified (Side Effects): self.env_fluxes (pd.DataFrame): Full environmental fluxes DataFrame for all iterations and runs. Multi-indexed by iteration and run, with columns as unique exchange reaction IDs for the entire community. Size is (n_iterations, n_exchanges). Units are mmol/(gT * hr). self.org_fluxes (pd.DataFrame): Full organism fluxes DataFrame for all iterations and runs. Multi-indexed by model, iteration, and run, with columns as unique (internal and exchange) reaction IDs for the entire community. Size is (n_iterations * n_models, n_reactions). Units are mmol/(gT * hr). self.exchange_to_metabolite_id (dict[str, str]): Mapping of exchange reaction IDs to their corresponding metabolite IDs. self.metabolite_id_to_name (dict[str, str]): Mapping of metabolite IDs to their human-readable names (or exchange reaction IDs). self.exchange_metabolites (list[cb.Metabolite]): A list of all Cobra Metabolite objects across the community. self.exchanges (list[str]): A list of all unique exchange reaction IDs in the community. self.exchange_ids (list[str]): A list of organism-specific exchange reaction IDs. self.biomass_exchange_ids (list[str]): A list of all unique biomass exchange reaction IDs in the community. self.model_names (dict[int, str]): A mapping of the community model index to its string model ID.

summarize

summarize(element: str = 'C') -> CommunitySummary

Build a summary of the community's final fluxes.

Parameters:

Name Type Description Default
element str

Chemical element (as in cobra.Metabolite.elements) used for the %-of-flux breakdowns. Defaults to "C" (carbon).

'C'

Returns:

Type Description
CommunitySummary

Uptake/secretion tables for the community and each organism.

average_periodicity

average_periodicity()

Average the flux history over the detected attractor.

Averages env_fluxes/org_fluxes over the detected period, or, absent convergence, over the last attractor_size fraction of iterations with a printed warning. Called automatically at the end of run_gifba.

Returns:

Type Description
tuple[Series, DataFrame]

(env_flux_avg, org_flux_avg), the averaged media fluxes indexed by exchange ID and the averaged per-organism fluxes indexed by model.

gifba.CommunitySummary

CommunitySummary(community: gifbaObject, *, element: str = 'C')

Uptake/secretion summary of a finished giFBA run.

Built by gifbaObject.summarize(). Formats a community's final fluxes into human-readable uptake/secretion tables, at both the whole-community and per-organism level, with optional elemental-flux weighting. str(summary) and repr(summary) return to_string(); in a Jupyter notebook the summary renders as HTML tables.

The tables always describe community.org_final, the fluxes averaged over the detected attractor (or over the trailing iterations when the run did not converge). There is no per-iteration view; use community.org_fluxes for the full history.

Parameters:

Name Type Description Default
community gifbaObject

A community that has already been run with run_gifba.

required
element str

Chemical element (as in cobra.Metabolite.elements) used to compute %-of-flux breakdowns. Keyword-only. Defaults to "C" (carbon).

'C'

Attributes:

Name Type Description
flux DataFrame

Long-form per-organism flux table indexed by (Model, Exchange), with Flux, Metabolite, {element}-Number and {element}-Flux columns. Zero fluxes are dropped.

total_flux DataFrame

The same columns aggregated across the whole community, indexed by Metabolite.

objective_rxns dict[int, str]

{model_index: objective_reaction_id}, copied from the community.

objective_vals list[float]

Final objective (growth) flux per model, in model order.

objective_total float

Sum of all models' objective fluxes.

method str

The FBA method ("pfba" or "fba") the community was run with.

iter_converged int | None

Zero-based iteration at which convergence was detected, matching the Iteration labels in community.org_fluxes. None if the run hit its iteration limit without converging.

periodicity int

Number of iterations averaged into the final fluxes: 1 for a fixed point, the cycle length for a periodic attractor, or the trailing window size when the run did not converge.

n_iterations int

Iteration limit the community was run with.

to_cytoscape

to_cytoscape() -> tuple[pd.DataFrame, pd.DataFrame]

Export the community's exchange network as Cytoscape tables.

Returns:

Type Description
tuple[DataFrame, DataFrame]

(edges_df, nodes_df). Edges have Source, Target, Type ("Uptake"/"Secretion") and Value columns; nodes have ID, Name and Type ("Organism"/"Metabolite") columns.

to_string

to_string() -> str

Format the full text report.

Returns:

Type Description
str

Community and per-organism uptake/secretion tables, with elemental-flux percentages.

gifba.utils

Validation helpers and standalone utilities.

Most check_* functions are used internally by gifbaObject.__init__ and gifbaObject.run_gifba but are safe to call directly.

load_simple_models

load_simple_models(case: str) -> tuple[list[cb.Model], dict[str, float]]

Load one of the bundled toy-model cases from gifba/Toy_Models.

Parameters:

Name Type Description Default
case str

Case name, one of "1_1_single", "1_2_single", "1_3_parallel", "2_1_crossfeed", "2_2_layered", "2_3_superfluous_crossfeed", "3_competition", "4_1_crossfeed_competition", "4_2_coupling" or "4_4_dynamical".

required

Returns:

Type Description
tuple[list[Model], dict[str, float]]

(models, media), the case's models and the media it is run on.

Raises:

Type Description
KeyError

If case is not a bundled case name.

find_min_medium

find_min_medium(community: gifbaObject | None = None, models: Model | list[Model] | None = None, base_media: dict[str, float] | None = None, min_growth: float | None = None) -> dict[str, float]

Derive a minimal medium that supports growth of every model.

Runs cobra.medium.minimal_medium on each model with base_media added as sinks, then takes the per-exchange maximum across models, unioned with base_media. Pass either a community or explicit models/base_media/min_growth.

Parameters:

Name Type Description Default
community gifbaObject

Community whose media is a [base_media, min_growth] list. Its models are used directly.

None
models Model | list[Model]

Models to use when no community is given. They are copied, so the caller's models are untouched.

None
base_media dict[str, float]

Exchange IDs to fluxes always included in the medium. Signs are ignored. Defaults to an empty medium.

None
min_growth float

Minimum growth each model must reach. Defaults to 0.1.

None

Returns:

Type Description
dict[str, float]

Media dict of negative (uptake) fluxes keyed by exchange ID.

Raises:

Type Description
ValueError

If neither community nor models is given.

check_rel_abund

check_rel_abund(rel_abund, n_models)

Validate and normalize relative abundances.

Parameters:

Name Type Description Default
rel_abund str | array - like | None

Abundance per model. None or any string (e.g. "equal") gives an even split. Values are normalized to sum to 1.

required
n_models int

Number of models in the community.

required

Returns:

Type Description
ndarray

Relative abundances of shape (n_models, 1) summing to 1.

Raises:

Type Description
ValueError

If the length doesn't match n_models, or values are negative or sum to zero.

check_n_iterations

check_n_iterations(n_iterations)

Coerce the iteration count to a positive integer.

Parameters:

Name Type Description Default
n_iterations int | float | None

Requested number of iterations. Defaults to 10 if None; values below 1 are raised to 1.

required

Returns:

Type Description
int

Number of iterations to run.

check_media

check_media(community)

Resolve a community's media into a plain flux dict.

Parameters:

Name Type Description Default
community gifbaObject

Community whose media is None, "complete", a [base_media, min_growth] list, or a dict of exchange IDs to fluxes. None and "complete" open every exchange in community.exchange_ids to -1000; a list is passed to find_min_medium.

required

Returns:

Type Description
dict[str, float]

A copy of the resolved media. community.media is also updated in place.

Raises:

Type Description
ValueError

If the media type is unsupported, or a key isn't a string or a value isn't a number.

check_models

check_models(models)

Validate and copy the community models.

Parameters:

Name Type Description Default
models Model | list[Model]

A single model or a list of models.

required

Returns:

Type Description
list[Model]

Copies of the input models.

Raises:

Type Description
ValueError

If models is None, not a model/list, or contains a non-model.

check_method

check_method(method)

Validate the FBA method name.

Parameters:

Name Type Description Default
method str | None

"pfba" or "fba", case-insensitive. Defaults to "pfba" if None.

required

Returns:

Type Description
str

The lower-case method name.

Raises:

Type Description
ValueError

If method isn't a string or isn't one of the two methods.

prep_micom_cfba

prep_micom_cfba(community_id, ids, paths, rel_abund=None)

Build a compartmentalized cFBA model from a MICOM community.

Requires the micom extra. The objective is the abundance-weighted sum of each organism's biomass reaction.

Parameters:

Name Type Description Default
community_id str

ID given to the returned cobra.Model.

required
ids list[str]

Organism IDs, used as suffixes on MICOM's reaction IDs.

required
paths list[str]

Model file paths, in the same order as ids.

required
rel_abund list[float]

Abundance per organism. Defaults to an even split.

None

Returns:

Type Description
tuple[Model, Community, dict]

(cfba_model, micom_community, objective_dict), where objective_dict maps each biomass reaction to its objective coefficient.

prepare_compartmentalized_model

prepare_compartmentalized_model(community: gifbaObject, rel_abund: list[float] | ndarray | None = None, obj_rxn_ids: list[str] | None = None) -> tuple[cb.Model, list[cb.Reaction]]

Build a compartmentalized cFBA model from a giFBA community.

Each organism gets its own compartments (c1, e1, c2, e2, ...) and e0 is the shared pool, so the result can be compared against giFBA. The objective is the unweighted sum of the organisms' objective reactions. The community's models are copied first and are left unchanged.

Parameters:

Name Type Description Default
community gifbaObject

Community providing the models, media and community_id.

required
rel_abund list[float] | ndarray

Abundance per organism, flat or shaped (n_models, 1). Defaults to community.rel_abund.

None
obj_rxn_ids list[str]

Reaction IDs (after renaming) to use as the objective. Defaults to every per-organism biomass(e...) reaction.

None

Returns:

Type Description
tuple[Model, list[Reaction]]

(comp_model, objective_reactions).

prepare_compartmentalized_model_with_micom

prepare_compartmentalized_model_with_micom(gifba_community: gifbaObject, model_paths: list[str], media: dict[str, float] | None = None, rel_abund: list[float] | ndarray | None = None, obj_rxn_ids: list[str] | None = None) -> tuple[cb.Model, list[cb.Reaction]]

Build a compartmentalized cFBA model from MICOM's reaction set.

Requires the micom extra. Same idea as prepare_compartmentalized_model, but the reactions come from a MICOM community built from model_paths, with internal reaction bounds copied from the giFBA models. The organisms are named Org1, Org2, ... so every per-organism reaction ID carries a __Org{i} suffix.

Parameters:

Name Type Description Default
gifba_community gifbaObject

Community providing the models, objective reactions, abundances and community_id. It is not modified.

required
model_paths list[str]

Model file paths, in the same order as the community's models.

required
media dict[str, float]

giFBA-style media, e.g. {"EX_A(e)": -10}. Converted to MICOM's EX_A_m form and applied to the shared exchanges; exchanges not listed are closed to uptake. Defaults to MICOM's medium, which is taken from the model files' exchange bounds.

None
rel_abund list[float] | ndarray

Abundance per organism. Defaults to gifba_community.rel_abund.

None
obj_rxn_ids list[str]

MICOM reaction IDs (with the __Org{i} suffix) to use as the objective. Defaults to each organism's objective reaction in gifba_community.

None

Returns:

Type Description
tuple[Model, list[Reaction]]

(comp_model, objective_reactions). The objective is the abundance-weighted sum of objective_reactions, matching MICOM's community growth rate.

gifba.config

Package-wide constants.

GROWTH_MIN_OBJ module-attribute

GROWTH_MIN_OBJ = 0.01

Minimum objective (growth) value for an organism's LP solution to be treated as growing and contribute flux each iteration.

ROUND module-attribute

ROUND = 6

Default decimal precision used when checking overconsumption ratios (gifbaObject's oc_rounding default).