[med-svn] [Git][med-team/python-cobra][upstream] New upstream version 0.32.1

Andreas Tille (@tille) gitlab at salsa.debian.org
Mon Nov 9 12:16:49 GMT 2026



Andreas Tille pushed to branch upstream at Debian Med / python-cobra


Commits:
8ff4069c by Andreas Tille at 2026-11-09T11:15:19+01:00
New upstream version 0.32.1
- - - - -


18 changed files:

- .github/workflows/safety.yml
- .github/workflows/test.yml
- + release-notes/0.32.0.md
- + release-notes/0.32.1.md
- release-notes/next-release.md
- setup.cfg
- setup.py
- src/cobra/__init__.py
- src/cobra/core/configuration.py
- src/cobra/core/formula.py
- src/cobra/core/reaction.py
- src/cobra/sampling/__init__.py
- + src/cobra/sampling/hopsy.py
- src/cobra/sampling/sampling.py
- tests/test_core/test_formula.py
- + tests/test_sampling/test_chrr.py
- tests/test_sampling/test_sampling.py
- tox.ini


Changes:

=====================================
.github/workflows/safety.yml
=====================================
@@ -11,7 +11,7 @@ jobs:
       fail-fast: false
       matrix:
         os: [ubuntu-latest, windows-latest, macos-latest]
-        python-version: ["3.10", "3.13"]
+        python-version: ["3.10", "3.14"]
     timeout-minutes: 360
 
     steps:


=====================================
.github/workflows/test.yml
=====================================
@@ -10,7 +10,7 @@ jobs:
       fail-fast: false
       matrix:
         os: [ubuntu-latest]
-        python-version: ["3.13"]
+        python-version: ["3.14"]
     runs-on: ${{ matrix.os }}
     timeout-minutes: 60
 
@@ -42,7 +42,7 @@ jobs:
       fail-fast: false
       matrix:
         os: [ubuntu-latest, macos-latest, windows-latest]
-        python-version: ["3.10", "3.13"]
+        python-version: ["3.10", "3.14"]
     timeout-minutes: 360
 
     steps:


=====================================
release-notes/0.32.0.md
=====================================
@@ -0,0 +1,17 @@
+# Release notes for cobrapy 0.32.0
+
+## New features
+
+- Added `chrr` sampler for flux polytope sampling, which is guaranteed to yield uniformly distributed samples. Uses the optional dependency `hopsy`, installable with `pip install cobra[chrr]`.
+- COBRAPY now works on Python 3.14.
+
+## Fixes
+
+- Rare race condition in cache directory creation from running seperate processes loading cobrapy on clean machine fixed. (https://github.com/opencobra/cobrapy/issues/1476)
+- `Formula.__add__` now accepts a plain `str` for the right-hand operand, matching its documented type hint and docstring. Previously `Formula("H2O") + "C"` raised `AttributeError`.
+
+## Other
+
+## Deprecated features
+
+## Backwards incompatible changes


=====================================
release-notes/0.32.1.md
=====================================
@@ -0,0 +1,11 @@
+# Release notes for cobrapy x.y.z
+
+## New features
+
+## Fixes
+
+## Other
+
+## Deprecated features
+
+## Backwards incompatible changes


=====================================
release-notes/next-release.md
=====================================
@@ -1,11 +1,12 @@
-# Release notes for cobrapy x.y.z
+# Release notes for cobrapy 0.32.1
 
 ## New features
 
 ## Fixes
 
-## Other
+- fixed import failure when hopsy was not installed
 
+## Other
 
 ## Deprecated features
 


=====================================
setup.cfg
=====================================
@@ -1,5 +1,5 @@
 [bumpversion]
-current_version = 0.31.1
+current_version = 0.32.1
 commit = True
 tag = True
 parse = (?P<major>\d+)
@@ -82,6 +82,8 @@ cobra =
 [options.extras_require]
 array = 
 	scipy
+chrr = 
+	hopsy
 development = 
 	black
 	bumpversion


=====================================
setup.py
=====================================
@@ -19,4 +19,4 @@ if version_info[:2] < (3, 6):
 
 # All other arguments are defined in `setup.cfg`.
 if __name__ == "__main__":
-    setup(version="0.31.1")
+    setup(version="0.32.1")


=====================================
src/cobra/__init__.py
=====================================
@@ -1,5 +1,5 @@
 __author__ = "The cobrapy core development team."
-__version__ = "0.31.1"
+__version__ = "0.32.1"
 
 
 from cobra.core import (


=====================================
src/cobra/core/configuration.py
=====================================
@@ -168,9 +168,7 @@ class Configuration(metaclass=Singleton):
 
         """
         self._cache_directory = pathlib.Path(path)
-        if not self._cache_directory.is_dir():
-            logger.debug(f"Creating cache directory '{str(self._cache_directory)}'.")
-            self._cache_directory.mkdir(parents=True)
+        self._cache_directory.mkdir(parents=True, exist_ok=True)
 
     def __repr__(self) -> str:
         """Return a string representation of the current configuration values."""


=====================================
src/cobra/core/formula.py
=====================================
@@ -49,7 +49,9 @@ class Formula(Object):
         Formula: Formula
            The combined formula
         """
-        return Formula(self.formula + other_formula.formula)
+        if isinstance(other_formula, Formula):
+            other_formula = other_formula.formula
+        return Formula(self.formula + other_formula)
 
     def parse_composition(self) -> None:
         """Break the chemical formula down by element."""


=====================================
src/cobra/core/reaction.py
=====================================
@@ -3,7 +3,7 @@
 import hashlib
 import re
 from collections import defaultdict
-from copy import copy, deepcopy
+from copy import deepcopy
 from functools import partial
 from math import isclose, isinf
 from operator import attrgetter
@@ -246,33 +246,6 @@ class Reaction(Object):
         if self.flux_expression is not None:
             set_objective(self.model, {self: value}, additive=True)
 
-    def __copy__(self) -> "Reaction":
-        """Copy the Reaction.
-
-        Returns
-        -------
-        Reaction
-            A new reaction that is a copy of the original reaction.
-        """
-        cop = copy(super(Reaction, self))
-        return cop
-
-    def __deepcopy__(self, memo: dict) -> "Reaction":
-        """Copy the reaction with memo.
-
-        Parameters
-        ----------
-        memo: dict
-            Automatically passed parameter.
-
-        Returns
-        -------
-        Reaction
-            A new reaction that is a deep copy of the original reaction with memo.
-        """
-        cop = deepcopy(super(Reaction, self), memo)
-        return cop
-
     @staticmethod
     def _check_bounds(lb: float, ub: float) -> None:
         """Check if the lower and upper bounds are valid.


=====================================
src/cobra/sampling/__init__.py
=====================================
@@ -1,5 +1,15 @@
 from .hr_sampler import HRSampler, shared_np_array
 from .achr import ACHRSampler
 from .core import step
+
+try:
+    import hopsy  # noqa: F401
+except ModuleNotFoundError:
+    hopsy_is_available = False
+else:
+    from .hopsy import HopsySampler
+
+    hopsy_is_available = True
+
 from .optgp import OptGPSampler
 from .sampling import sample


=====================================
src/cobra/sampling/hopsy.py
=====================================
@@ -0,0 +1,210 @@
+"""Provide hopsy samplers."""
+
+from typing import TYPE_CHECKING, Optional
+
+
+if TYPE_CHECKING:
+    from cobra import Model
+
+import hopsy
+import numpy as np
+import pandas as pd
+
+from ..core.configuration import Configuration
+from .hr_sampler import HRSampler
+
+
+__all__ = "HopsySampler"
+
+configuration = Configuration()
+
+
+# for the time being while the updated hopsy version isn't released
+def back_transform(problem, samples):
+    """
+    Transform samples from the sampling space to the original parameter space.
+
+    Parameters
+    ----------
+    problem : hopsy.Problem
+      A hopsy.Problem with populated `problem.transformation` and `problem.shift` of
+      shape `(m, d)` and `(d, )`, respectively. If not populated, the identity
+      operation is performed.
+    samples : np.array
+      Parameter samples of shape `(..., d)` which are to be transformed.
+
+    Returns
+    -------
+    np.array
+      Transformed samples of shape `(..., m)`
+    """
+    S, h = problem.transformation, problem.shift
+    transformed = samples @ S.T if S is not None else samples
+    shifted = transformed + h if h is not None else transformed
+    return shifted
+
+
+class HopsySampler(HRSampler):
+    """
+    Generic sampling wrapper for hopsy samplers.
+
+    Parameters
+    ----------
+    model : cobra.Model
+        The cobra model from which to generate samples.
+    sampler : hopsy.Proposal, optional
+        The hopsy sampler for sampling the polytope
+        (default hopsy.UniformCoordinateHitAndRunProposal).
+    processes: int, optional
+        The number of processes used during sampling
+        (default cobra.Configuration.processes).
+    thinning : int, optional
+        The thinning factor of the generated sampling chain. A thinning of
+        10 means samples are returned every 10 steps (default 100).
+    nproj : int > 0, optional
+        How often to reproject the sampling point into the feasibility
+        space. Avoids numerical issues at the cost of lower sampling. If
+        you observe many equality constraint violations with
+        `sampler.validate` you should lower this number (default None).
+    rounding : bool, optional
+        Whether to precondition the sampling problem by applying an offline rounding
+        transformation.
+    seed : int > 0, optional
+        Sets the random number seed. Initialized to the current time stamp
+        if None (default None).
+
+    Attributes
+    ----------
+    n_samples : int
+        The total number of samples that have been generated by this
+        sampler instance.
+    problem : typing.NamedTuple
+        A NamedTuple whose attributes define the entire sampling problem in
+        matrix form.
+    fwd_idx : numpy.array
+        A numpy array having one entry for each reaction in the model,
+        containing the index of the respective forward variable.
+    rev_idx : numpy.array
+        A numpy array having one entry for each reaction in the model,
+        containing the index of the respective reverse variable.
+    sampler :
+        The hopsy sampler type.
+    mcs : list
+        List of length `processes` of hopsy.MarkovChain objects.
+    rngs : list
+        List of length `processes` of hopsy.RandomNumberGenerator objects.
+
+    """
+
+    def __init__(
+        self,
+        model: "Model",
+        sampler: hopsy.Proposal = hopsy.UniformCoordinateHitAndRunProposal,
+        thinning: int = 100,
+        processes: Optional[int] = None,
+        nproj: Optional[int] = None,
+        seed: Optional[int] = None,
+        rounding: bool = True,
+        **kwargs,
+    ) -> None:
+        """Initialize a new HopsySampler."""
+        super().__init__(model, thinning, nproj=nproj, seed=seed, **kwargs)
+
+        if self.problem.inequalities.shape[0] > 0:
+            A = self.problem.inequalities
+            lb, ub = self.problem.bounds
+            A, b = np.concat([-A, A], axis=0), np.concat([-lb, ub], axis=0)
+            A, b = A[~np.isinf(b)], b[~np.isinf(b)]
+        else:
+            # empty dummy constraint to set problem dimension
+            A = np.ones((0, self.problem.equalities.shape[1]))
+            b = np.ones(0)
+
+        problem = hopsy.Problem(A, b)
+        problem = hopsy.add_box_constraints(
+            problem,
+            self.problem.variable_bounds[0],
+            self.problem.variable_bounds[1],
+            simplify=False,
+        )
+        problem = hopsy.add_equality_constraints(
+            problem, self.problem.equalities, self.problem.b
+        )
+        problem = hopsy.round(problem, simplify=False) if rounding else problem
+
+        self.sampler = sampler
+
+        # batched transformation to better exploit vectorization
+        self.transformation = problem.transformation.copy()
+        self.shift = problem.shift.copy()
+
+        problem.transformation = None
+        problem.shift = None
+
+        self._problem = problem
+
+        if processes is None:
+            self.processes = configuration.processes
+        else:
+            self.processes = processes
+
+        self.mcs = None
+        self.rngs = None
+
+        self.mcs = [
+            hopsy.MarkovChain(self._problem, self.sampler)
+            for i in range(self.processes)
+        ]
+        self.rngs = [
+            hopsy.RandomNumberGenerator(self._seed, i) for i in range(self.processes)
+        ]
+
+    def sample(self, n: int, fluxes: bool = True) -> pd.DataFrame:
+        """Generate a set of samples by calling hopsy.
+
+        Parameters
+        ----------
+        n : int
+            The minimum number of samples that are generated at once.
+        fluxes : bool, optional
+            Whether to return fluxes or the internal solver variables. If
+            set to False, will return a variable for each forward and
+            backward flux as well as all additional variables you might
+            have defined in the model (default True).
+
+        Returns
+        -------
+        pandas.DataFrame
+            Returns a pandas DataFrame with `n` rows, each containing a
+            flux sample.
+        """
+        _, samples = hopsy.sample(
+            self.mcs,
+            self.rngs,
+            n_samples=int(np.ceil(n / self.processes)),
+            thinning=self.thinning,
+            n_procs=self.processes,
+        )
+
+        # batched transformation to better exploit vectorization
+        self._problem.transformation = self.transformation
+        self._problem.shift = self.shift
+
+        samples = back_transform(self._problem, samples)
+
+        self._problem.transformation = None
+        self._problem.shift = None
+
+        samples = samples.reshape(-1, samples.shape[-1])  # flatten chain dim
+
+        if fluxes:
+            names = [r.id for r in self.model.reactions]
+
+            return pd.DataFrame(
+                samples[:, self.fwd_idx] - samples[:, self.rev_idx],
+                columns=names,
+            )
+        else:
+            names = [v.name for v in self.model.variables]
+
+            return pd.DataFrame(samples, columns=names)


=====================================
src/cobra/sampling/sampling.py
=====================================
@@ -1,5 +1,6 @@
 """Provide a wrapper function for performing flux sampling of cobra models."""
 
+import logging
 from typing import TYPE_CHECKING, Optional
 
 import pandas as pd
@@ -8,6 +9,18 @@ from .achr import ACHRSampler
 from .optgp import OptGPSampler
 
 
+try:
+    import hopsy  # noqa: F401
+except ModuleNotFoundError:
+    hopsy_is_available = False
+else:
+    hopsy_is_available = True
+    from .hopsy import HopsySampler
+
+
+logger = logging.getLogger(__name__)
+
+
 if TYPE_CHECKING:
     from cobra import Model
 
@@ -15,22 +28,33 @@ if TYPE_CHECKING:
 def sample(
     model: "Model",
     n: int,
-    method: str = "optgp",
+    method: str = "auto",
     thinning: int = 100,
     processes: int = 1,
     seed: Optional[int] = None,
 ) -> pd.DataFrame:
     """Sample valid flux distributions from a cobra model.
 
-    Currently, two methods are supported:
+    Currently, three methods are supported:
 
-    1. 'optgp' (default) which uses the OptGPSampler that supports parallel
+    1. 'chrr' which uses a the coordinate Hit-and-Run algorithm
+        with rounding ([1]_), which has been shown to often outperform OptGP
+        and ACHR, refer [2]_, [3]_. The rounding transformation is performed
+        in an offline manner which inflicts a certain base cost, however
+        sampling is performed using the C++-based library ``hopsy`` ([4]_)
+        and is, thus, blazingly fast. Moreover, this method supports
+        parallel sampling.
+
+    2. 'optgp'  which uses the OptGPSampler that supports parallel
         sampling. Requires large numbers of samples to be performant
         (`n` > 1000). For smaller samples, 'achr' might be better suited.
-        For details, refer [1]_ .
+        For details, refer [5]_ .
+
+    3. 'achr' which uses artificial centering hit-and-run. This is a single
+       process method with good convergence. For details, refer [6]_ .
 
-    2. 'achr' which uses artificial centering hit-and-run. This is a single
-       process method with good convergence. For details, refer [2]_ .
+    A fourth 'auto' option is available, which tries to choose 'chrr' if ``hopsy``
+    is available. This is the default option.
 
     Parameters
     ----------
@@ -40,16 +64,16 @@ def sample(
         The number of samples to obtain. When using 'optgp', this must be a
         multiple of `processes`, otherwise a larger number of samples will
         be returned.
-    method : {"optgp", "achr"}, optional
-        The sampling algorithm to use (default "optgp").
+    method : {"auto", "chrr", "optgp", "achr"}, optional
+        The sampling algorithm to use (default "auto").
     thinning : int, optional
         The thinning factor of the generated sampling chain. A thinning of
         10 means samples are returned every 10 steps. Defaults to 100 which
         in benchmarks gives approximately uncorrelated samples. If set to 1
         will return all iterates (default 100).
     processes : int, optional
-        Only used for 'optgp'. The number of processes used to generate
-        samples (default 1).
+        Only used for 'optgp' and 'chrr'. The number of processes
+        used to generate samples (default 1).
     seed : int > 0, optional
         Sets the random number seed. Initialized to the current time stamp
         if None (default None).
@@ -69,28 +93,66 @@ def sample(
 
     References
     ----------
-    .. [1] Megchelenbrink W, Huynen M, Marchiori E (2014)
+    .. [1] Hulda S Haraldsdóttir, Ben Cousins, Ines Thiele, Ronan M.T Fleming,
+       Santosh Vempala,
+       CHRR: coordinate hit-and-run with rounding for uniform sampling of
+       constraint-based models,
+       Bioinformatics, Volume 33, Issue 11, June 2017, Pages 1741–1743,
+       https://doi.org/10.1093/bioinformatics/btx052
+
+    .. [2] Herrmann, H.A., Dyson, B.C., Vass, L. et al.
+       Flux sampling is a powerful tool to study metabolism under changing
+       environmental conditions.
+       npj Syst Biol Appl 5, 32 (2019).
+       https://doi.org/10.1038/s41540-019-0109-0
+
+    .. [3] Fallahi S, Skaug HJ, Alendal G (2020)
+       A comparison of Monte Carlo sampling methods for
+       metabolic network models.
+       PLoS ONE 15(7): e0235393.
+       https://doi.org/10.1371/journal.pone.0235393
+
+    .. [4] Richard D Paul, Johann F Jadebeck, Anton Stratmann, Wolfgang Wiechert,
+       Katharina Nöh,
+       hopsy — a methods marketplace for convex polytope sampling in Python,
+       Bioinformatics, Volume 40, Issue 7, July 2024, btae430,
+       https://doi.org/10.1093/bioinformatics/btae430
+
+    .. [5] Megchelenbrink W, Huynen M, Marchiori E (2014)
        optGpSampler: An Improved Tool for Uniformly Sampling the Solution-Space
        of Genome-Scale Metabolic Networks.
        PLoS ONE 9(2): e86587.
        https://doi.org/10.1371/journal.pone.0086587
 
-    .. [2] Direction Choice for Accelerated Convergence in Hit-and-Run Sampling
+    .. [6] Direction Choice for Accelerated Convergence in Hit-and-Run Sampling
        David E. Kaufman, Robert L. Smith
        Operations Research 199846:1 , 84-95
        https://doi.org/10.1287/opre.46.1.84
 
     """
+    if method == "auto":
+        if hopsy_is_available:
+            method = "chrr"
+        else:
+            method = "optgp"
+            logger.warn(
+                "hopsy is not available in your environment."
+                "Falling back to 'optgp' sampler.",
+                stacklevel=2,
+            )
+
     if method == "optgp":
         sampler = OptGPSampler(model, processes=processes, thinning=thinning, seed=seed)
     elif method == "achr":
         sampler = ACHRSampler(model, thinning=thinning, seed=seed)
+    elif method == "chrr":
+        sampler = HopsySampler(
+            model, processes=processes, thinning=thinning, seed=seed, rounding=True
+        )
     else:
         raise ValueError(
             f'Invalid value: "{method}" for method used. '
-            'The value must be "optgp" or "achr".'
+            'The value must be "optgp", "achr" or "chrr".'
         )
 
-    return pd.DataFrame(
-        columns=[rxn.id for rxn in model.reactions], data=sampler.sample(n)
-    )
+    return sampler.sample(n)


=====================================
tests/test_core/test_formula.py
=====================================
@@ -26,3 +26,15 @@ def test_formula_wrong() -> None:
     with pytest.warns(UserWarning):
         w = Formula("NOX").weight
         assert w is None
+
+
+def test_formula_add_formula() -> None:
+    """Test combining two Formula objects."""
+    f = Formula("H2O") + Formula("C")
+    assert f.formula == "H2OC"
+
+
+def test_formula_add_str() -> None:
+    """Test combining a Formula with a plain string, per the documented API."""
+    f = Formula("H2O") + "C"
+    assert f.formula == "H2OC"


=====================================
tests/test_sampling/test_chrr.py
=====================================
@@ -0,0 +1,40 @@
+"""Test functionalities of flux sampling methods."""
+
+import pytest
+
+from cobra.core import Metabolite, Model, Reaction
+from cobra.sampling import hopsy_is_available
+
+
+ at pytest.mark.skipif(not hopsy_is_available, reason="hopsy not installed")
+def test_complicated_model_chrr() -> None:
+    """Test a complicated model with CHRR.
+
+    Difficult model since the online mean calculation is numerically
+    unstable, so many samples weakly violate the equality constraints.
+
+    """
+    from cobra.sampling import HopsySampler
+
+    model = Model("flux_split")
+
+    reaction1 = Reaction("V1")
+    reaction2 = Reaction("V2")
+    reaction3 = Reaction("V3")
+    reaction1.bounds = (0, 6)
+    reaction2.bounds = (0, 8)
+    reaction3.bounds = (0, 10)
+
+    A = Metabolite("A")
+
+    reaction1.add_metabolites({A: -1})
+    reaction2.add_metabolites({A: -1})
+    reaction3.add_metabolites({A: 1})
+
+    model.add_reactions([reaction1, reaction2, reaction3])
+
+    chrr = HopsySampler(model, seed=42)
+    chrr_samples = chrr.sample(100)
+
+    assert any(chrr_samples.corr().abs() < 1.0)
+    assert sum(chrr.validate(chrr_samples) == "v") > 95


=====================================
tests/test_sampling/test_sampling.py
=====================================
@@ -7,7 +7,7 @@ import pytest
 
 from cobra.core import Metabolite, Model, Reaction
 from cobra.flux_analysis.parsimonious import pfba
-from cobra.sampling import ACHRSampler, OptGPSampler, sample
+from cobra.sampling import ACHRSampler, OptGPSampler, hopsy_is_available, sample
 
 
 def test_single_achr(model: Model) -> None:
@@ -16,16 +16,33 @@ def test_single_achr(model: Model) -> None:
     assert s.shape == (10, len(model.reactions))
 
 
+ at pytest.mark.skipif(not hopsy_is_available, reason="hopsy not installed")
+def test_single_chrr(model: Model) -> None:
+    """Test CHRR sampling (one sample)."""
+    s = sample(model, 10, processes=1, method="chrr")
+    assert s.shape == (10, len(model.reactions))
+
+
 def test_single_optgp(model: Model) -> None:
     """Test OptGP sampling (one sample)."""
-    s = sample(model, 10, processes=1)
+    s = sample(model, 10, processes=1, method="optgp")
+    assert s.shape == (10, len(model.reactions))
+
+
+ at pytest.mark.skipif(
+    "SKIP_MP" in os.environ or not hopsy_is_available,
+    reason="unsafe for parallel execution or hopsy not installed",
+)
+def test_multi_chrr(model: Model) -> None:  # pragma: no cover
+    """Test CHRR sampling (multi sample)."""
+    s = sample(model, 10, processes=2, method="chrr")
     assert s.shape == (10, len(model.reactions))
 
 
 @pytest.mark.skipif("SKIP_MP" in os.environ, reason="unsafe for parallel execution")
 def test_multi_optgp(model: Model) -> None:  # pragma: no cover
     """Test OptGP sampling (multi sample)."""
-    s = sample(model, 10, processes=2)
+    s = sample(model, 10, processes=2, method="optgp")
     assert s.shape == (10, len(model.reactions))
 
 
@@ -37,8 +54,20 @@ def test_wrong_method(model: Model) -> None:
 
 def test_fixed_seed(model: Model) -> None:
     """Test result of fixed seed for sampling."""
-    s1 = sample(model, 1, seed=42)
-    s2 = sample(model, 1, seed=42)
+    s1 = sample(model, 1, seed=42, method="achr")
+    s2 = sample(model, 1, seed=42, method="achr")
+    assert np.isclose(s1.TPI[0], s2.TPI[0])
+
+    s1 = sample(model, 1, seed=42, method="optgp")
+    s2 = sample(model, 1, seed=42, method="optgp")
+    assert np.isclose(s1.TPI[0], s2.TPI[0])
+
+
+ at pytest.mark.skipif(not hopsy_is_available, reason="hopsy not installed")
+def test_fixed_seed_chrr(model: Model) -> None:
+    """Test result of fixed seed for CHRR sampling."""
+    s1 = sample(model, 1, seed=42, method="chrr")
+    s2 = sample(model, 1, seed=42, method="chrr")
     assert np.isclose(s1.TPI[0], s2.TPI[0])
 
 
@@ -46,10 +75,19 @@ def test_equality_constraint(model: Model) -> None:
     """Test equality constraint."""
     model.reactions.ACALD.bounds = (-1.5, -1.5)
 
-    s = sample(model, 10)
+    s = sample(model, 10, method="achr")
     assert np.allclose(s.ACALD, -1.5, atol=1e-6, rtol=0)
 
-    s = sample(model, 10, method="achr")
+    s = sample(model, 10, method="optgp")
+    assert np.allclose(s.ACALD, -1.5, atol=1e-6, rtol=0)
+
+
+ at pytest.mark.skipif(not hopsy_is_available, reason="hopsy not installed")
+def test_equality_constraint_chrr(model: Model) -> None:
+    """Test equality constraint with CHRR."""
+    model.reactions.ACALD.bounds = (-1.5, -1.5)
+
+    s = sample(model, 10, method="chrr")
     assert np.allclose(s.ACALD, -1.5, atol=1e-6, rtol=0)
 
 
@@ -58,29 +96,52 @@ def test_inequality_constraint(model: Model) -> None:
     co = model.problem.Constraint(model.reactions.ACALD.flux_expression, lb=-0.5)
     model.add_cons_vars(co)
 
-    s = sample(model, 10)
+    s = sample(model, 10, method="achr")
+    assert all(s.ACALD > -0.5 - 1e-6)
+
+    s = sample(model, 10, method="optgp")
     assert all(s.ACALD > -0.5 - 1e-6)
 
-    s = sample(model, 10, method="achr")
+
+ at pytest.mark.skipif(not hopsy_is_available, reason="hopsy not installed")
+def test_inequality_constraint_chrr(model: Model) -> None:
+    """Test inequality constraint with CHRR."""
+    co = model.problem.Constraint(model.reactions.ACALD.flux_expression, lb=-0.5)
+    model.add_cons_vars(co)
+
+    s = sample(model, 10, method="chrr")
     assert all(s.ACALD > -0.5 - 1e-6)
 
 
 def test_inhomogeneous_sanity(model: Model) -> None:
     """Test standard deviation between inhomogeneous and homogeneous sampling."""
     model.reactions.ACALD.bounds = (-1.5, -1.5)
-    s_inhom = sample(model, 64)
+    s_inhom = sample(model, 64, method="achr")
 
     model.reactions.ACALD.bounds = (-1.5 - 1e-3, -1.5 + 1e-3)
-    s_hom = sample(model, 64)
+    s_hom = sample(model, 64, method="achr")
 
     relative_diff = (s_inhom.std() + 1e-12) / (s_hom.std() + 1e-12)
     assert 0.5 < relative_diff.abs().mean() < 2
 
     model.reactions.ACALD.bounds = (-1.5, -1.5)
-    s_inhom = sample(model, 64, method="achr")
+    s_inhom = sample(model, 64, method="optgp")
 
     model.reactions.ACALD.bounds = (-1.5 - 1e-3, -1.5 + 1e-3)
-    s_hom = sample(model, 64, method="achr")
+    s_hom = sample(model, 64, method="optgp")
+
+    relative_diff = (s_inhom.std() + 1e-12) / (s_hom.std() + 1e-12)
+    assert 0.5 < relative_diff.abs().mean() < 2
+
+
+ at pytest.mark.skipif(not hopsy_is_available, reason="hopsy not installed")
+def test_inhomogeneous_sanity_chrr(model: Model) -> None:
+    """Test standard deviation between inhomogeneous and homogeneous CHRR sampling."""
+    model.reactions.ACALD.bounds = (-1.5, -1.5)
+    s_inhom = sample(model, 64, method="chrr")
+
+    model.reactions.ACALD.bounds = (-1.5 - 1e-3, -1.5 + 1e-3)
+    s_hom = sample(model, 64, method="chrr")
 
     relative_diff = (s_inhom.std() + 1e-12) / (s_hom.std() + 1e-12)
     assert 0.5 < relative_diff.abs().mean() < 2


=====================================
tox.ini
=====================================
@@ -1,13 +1,13 @@
 [tox]
-envlist = isort, black, flake8, safety, py3{9,10,11,12,13}, coverage
+envlist = isort, black, flake8, safety, py3{10,11,12,13,14}, coverage
 
 [gh-actions]
 python =
-    3.9: install, safety, py39
-    3.10: install, py310, coverage
+    3.10: install, py310, safety, coverage
     3.11: install, py311
     3.12: install, py312
     3.13: install, py313
+    3.14: install, py314
 
 [testenv]
 extras =
@@ -16,6 +16,7 @@ deps=
     jsonschema
     osqp~=1.0
     highspy
+    hopsy
     pytest
     pytest-benchmark~=4.0
     pytest-mock
@@ -30,6 +31,7 @@ extras =
 deps=
     jsonschema
     osqp~=1.0
+    hopsy
     pytest
     pytest-benchmark~=4.0
     pytest-cov



View it on GitLab: https://salsa.debian.org/med-team/python-cobra/-/commit/8ff4069ca3d3ece94a7ebb86c869531d729ad9b4

-- 
View it on GitLab: https://salsa.debian.org/med-team/python-cobra/-/commit/8ff4069ca3d3ece94a7ebb86c869531d729ad9b4
You're receiving this email because of your account on salsa.debian.org. Manage all notifications: https://salsa.debian.org/-/profile/notifications | Help: https://salsa.debian.org/help


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://alioth-lists.debian.net/pipermail/debian-med-commit/attachments/20261109/a272bd70/attachment-0001.htm>


More information about the debian-med-commit mailing list