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). |
required |
rel_abund
|
str | array - like
|
Relative abundance per model. |
'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 |
oc_method |
str
|
Overconsumption-correction algorithm, |
community_id |
str | None
|
Optional label for the community, used by
|
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 |
objective_rxns |
dict[int, str]
|
|
simulation_count |
int
|
Running count of LP solves that cleared the minimum growth cutoff. |
env_fluxes |
DataFrame
|
Full media flux history, indexed by |
org_fluxes |
DataFrame
|
Full per-organism flux history, indexed by
|
iter_converged |
int | None
|
Iteration where convergence/periodicity was
detected, or None. Set by |
periodicity |
int | None
|
Length of the detected attractor cycle (1 = true fixed
point), or None if no convergence detected. Set by |
exchange_ids |
list[str]
|
Unique exchange IDs across the whole community. Set by
|
reaction_ids |
list[str]
|
Unique reaction IDs across the whole community. Set by
|
exchange_to_metabolite_id |
dict[str, str]
|
Exchange ID to metabolite ID lookup,
used for reporting. Set by |
metabolite_id_to_name |
dict[str, str]
|
Metabolite ID to name lookup, used for
reporting. Set by |
model_names |
dict[int, str]
|
|
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 |
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 |
'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]
|
|
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 |
required |
element
|
str
|
Chemical element (as in |
'C'
|
Attributes:
| Name | Type | Description |
|---|---|---|
flux |
DataFrame
|
Long-form per-organism flux table indexed by
|
total_flux |
DataFrame
|
The same columns aggregated across the whole community,
indexed by |
objective_rxns |
dict[int, str]
|
|
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 ( |
iter_converged |
int | None
|
Zero-based iteration at which convergence was
detected, matching the |
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]
|
|
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 |
required |
Returns:
| Type | Description |
|---|---|
tuple[list[Model], dict[str, float]]
|
|
Raises:
| Type | Description |
|---|---|
KeyError
|
If |
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 |
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 |
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. |
required |
n_models
|
int
|
Number of models in the community. |
required |
Returns:
| Type | Description |
|---|---|
ndarray
|
Relative abundances of shape |
Raises:
| Type | Description |
|---|---|
ValueError
|
If the length doesn't match |
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 |
required |
Returns:
| Type | Description |
|---|---|
dict[str, float]
|
A copy of the resolved media. |
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 |
check_method ¶
check_method(method)
Validate the FBA method name.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
method
|
str | None
|
|
required |
Returns:
| Type | Description |
|---|---|
str
|
The lower-case method name. |
Raises:
| Type | Description |
|---|---|
ValueError
|
If |
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 |
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 |
required |
rel_abund
|
list[float]
|
Abundance per organism. Defaults to an even split. |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Model, Community, dict]
|
|
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
|
required |
rel_abund
|
list[float] | ndarray
|
Abundance per organism, flat or
shaped |
None
|
obj_rxn_ids
|
list[str]
|
Reaction IDs (after renaming) to use as the
objective. Defaults to every per-organism |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Model, list[Reaction]]
|
|
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 |
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. |
None
|
rel_abund
|
list[float] | ndarray
|
Abundance per organism. Defaults
to |
None
|
obj_rxn_ids
|
list[str]
|
MICOM reaction IDs (with the |
None
|
Returns:
| Type | Description |
|---|---|
tuple[Model, list[Reaction]]
|
|
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).