Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add progress to fva #1283

Open
wants to merge 3 commits into
base: devel
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions release-notes/next-release.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
## New features

* View number of genes in model notebook representation.
* Add progress bar to `flux_variability_analysis`.

## Fixes

Expand Down
79 changes: 60 additions & 19 deletions src/cobra/flux_analysis/variability.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
"""Provide variability based methods such as flux variability or gene essentiality."""


import logging
from typing import TYPE_CHECKING, List, Optional, Set, Tuple, Union
from warnings import warn

import numpy as np
import pandas as pd
from optlang.symbolics import Zero
from rich.progress import Progress

from ..core import Configuration, get_solution
from ..util import ProcessPool
Expand All @@ -26,6 +26,29 @@
configuration = Configuration()


class _FakeProgress:
def __enter__(self):
return self

def __exit__(self, *args):
pass

def add_task(self, *args, **kwargs):
return object()
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In rich, add_task returns an integer ID. So maybe just return 0 here.

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Do you need this at all? In rich Progress.add_task already has a visible flag that hides the progress bar. Does that have too much overhead?

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Didn't realize there was that option. Sounds good 🙂


def update(*args, **kwargs):
pass


def _update_progress_bar(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

What is the point of this function? It just seems like an unnecessary level of indirection.

progress_bar,
task,
advance: int,
) -> None:
"""Update progress bar."""
progress_bar.update(task, advance=advance)


def _init_worker(model: "Model", loopless: bool, sense: str) -> None:
"""Initialize a global model object for multiprocessing.

Expand Down Expand Up @@ -230,25 +253,43 @@ def flux_variability_analysis(
model.add_cons_vars([flux_sum, flux_sum_constraint])

model.objective = Zero # This will trigger the reset as well
for what in ("minimum", "maximum"):
if processes > 1:
# We create and destroy a new pool here in order to set the
# objective direction for all reactions. This creates a
# slight overhead but seems the most clean.
chunk_size = len(reaction_ids) // processes
with ProcessPool(
processes,
initializer=_init_worker,
initargs=(model, loopless, what[:3]),
) as pool:
for rxn_id, value in pool.imap_unordered(
_fva_step, reaction_ids, chunksize=chunk_size
):

_Progress = Progress
if logger.level != logging.INFO:
_Progress = _FakeProgress

with _Progress() as progress:
progress_task = progress.add_task(
"[cyan]Performing FVA...", total=num_reactions
)

for what in ("minimum", "maximum"):
if processes > 1:
# We create and destroy a new pool here in order to set the
# objective direction for all reactions. This creates a
# slight overhead but seems the most clean.
chunk_size = len(reaction_ids) // processes
with ProcessPool(
processes,
initializer=_init_worker,
initargs=(model, loopless, what[:3]),
) as pool:
for i, (rxn_id, value) in enumerate(
pool.imap_unordered(
_fva_step, reaction_ids, chunksize=chunk_size
)
):
fva_result.at[rxn_id, what] = value
_update_progress_bar(
progress, progress_task, (i + 1) / num_reactions
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I haven't tested this but does this actually show the right numbers? Like the bar is set to a maximum of nr steps but then you do 2*nr updates. Once for the min and once for the max...

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yep, agreed. Didn't mention it now because it seems like we want a different design anyway. Also, use enumerate(..., start=1) instead of adding + 1.

)
else:
_init_worker(model, loopless, what[:3])
for i, (rxn_id, value) in enumerate(map(_fva_step, reaction_ids)):
fva_result.at[rxn_id, what] = value
else:
_init_worker(model, loopless, what[:3])
for rxn_id, value in map(_fva_step, reaction_ids):
fva_result.at[rxn_id, what] = value
_update_progress_bar(
progress, progress_task, (i + 1) / num_reactions
)

return fva_result[["minimum", "maximum"]]

Expand Down