8. Flux sampling¶

8.1. Basic usage¶

The easiest way to get started with flux sampling is using the sample function in the flux_analysis submodule. sample takes at least two arguments: a cobra model and the number of samples you want to generate.

[1]:

from cobra.io import load_model
from cobra.sampling import sample

model = load_model("textbook")
s = sample(model, 100)
s.head()

Scaling...
A: min|aij| =  1.000e+00  max|aij| =  1.000e+00  ratio =  1.000e+00
Problem data seem to be well scaled

[1]:

ACALD ACALDt ACKr ACONTa ACONTb ACt2r ADK1 AKGDH AKGt2r ALCD2x ... RPI SUCCt2_2 SUCCt3 SUCDi SUCOAS TALA THD2 TKT1 TKT2 TPI
0 -0.771296 -0.431093 -2.284246 6.735302 6.735302 -2.284246 2.273930 3.942050 -1.589360 -0.340203 ... -2.314416 6.997002 8.082133 335.977726 -3.942050 2.152983 12.850348 2.152983 2.088065 7.542984
1 -2.089680 -1.099843 -0.386453 10.477790 10.477790 -0.386453 3.396770 3.163168 -1.592767 -0.989837 ... -1.756359 3.093051 3.415053 540.804734 -3.163168 1.657479 56.649368 1.657479 1.617715 8.029587
2 -1.108346 -0.126460 -1.198639 5.057819 5.057819 -1.198639 7.154043 0.313155 -0.227554 -0.981886 ... -4.491355 7.873466 8.606818 558.331088 -0.313155 4.295540 12.141283 4.295540 4.216795 5.181243
3 -1.239111 -0.334024 -1.284023 12.035499 12.035499 -1.284023 19.790232 1.359155 -0.007846 -0.905088 ... -2.063827 9.002800 10.772472 647.037371 -1.359155 2.016495 26.609381 2.016495 1.997461 7.712080
4 -1.943290 -1.571257 -0.842072 11.035900 11.035900 -0.842072 15.963163 0.288986 -0.861444 -0.372033 ... -1.468256 7.188997 8.085781 368.039875 -0.288986 1.465663 5.730886 1.465663 1.464620 8.298285

5 rows × 95 columns

By default sample uses the optgp method based on the method presented here as it is suited for larger models and can run in parallel. By default the sampler uses a single process. This can be changed by using the processes argument.

[2]:

print("One process:")
%time s = sample(model, 1000)
print("Two processes:")
%time s = sample(model, 1000, processes=2)

One process:
CPU times: user 9.8 s, sys: 333 ms, total: 10.1 s
Wall time: 9.21 s
Two processes:
CPU times: user 186 ms, sys: 41.2 ms, total: 227 ms
Wall time: 5.26 s


Alternatively you can also user Artificial Centering Hit-and-Run for sampling by setting the method to achr. achr does not support parallel execution but has good convergence and is almost Markovian.

[3]:

s = sample(model, 100, method="achr")


In general setting up the sampler is expensive since initial search directions are generated by solving many linear programming problems. Thus, we recommend to generate as many samples as possible in one go. However, this might require finer control over the sampling procedure as described in the following section.

8.2. Advanced usage¶

8.2.1. Sampler objects¶

The sampling process can be controlled on a lower level by using the sampler classes directly.

[4]:

from cobra.sampling import OptGPSampler, ACHRSampler


Both sampler classes have standardized interfaces and take some additional argument. For instance the thinning factor. “Thinning” means only recording samples every n iterations. A higher thinning factors mean less correlated samples but also larger computation times. By default the samplers use a thinning factor of 100 which creates roughly uncorrelated samples. If you want less samples but better mixing feel free to increase this parameter. If you want to study convergence for your own model you might want to set it to 1 to obtain all iterates.

[5]:

achr = ACHRSampler(model, thinning=10)


OptGPSampler has an additional processes argument specifying how many processes are used to create parallel sampling chains. This should be in the order of your CPU cores for maximum efficiency. As noted before class initialization can take up to a few minutes due to generation of initial search directions. Sampling on the other hand is quick.

[6]:

optgp = OptGPSampler(model, processes=4)


8.2.2. Sampling and validation¶

Both samplers have a sample function that generates samples from the initialized object and act like the sample function described above, only that this time it will only accept a single argument, the number of samples. For OptGPSampler the number of samples should be a multiple of the number of processes, otherwise it will be increased to the nearest multiple automatically.

[7]:

s1 = achr.sample(100)

s2 = optgp.sample(100)


You can call sample repeatedly and both samplers are optimized to generate large amount of samples without falling into “numerical traps”. All sampler objects have a validate function in order to check if a set of points are feasible and give detailed information about feasibility violations in a form of a short code denoting feasibility. Here the short code is a combination of any of the following letters:

• “v” - valid point

• “l” - lower bound violation

• “u” - upper bound violation

• “e” - equality violation (meaning the point is not a steady state)

For instance for a random flux distribution (should not be feasible):

[8]:

import numpy as np

bad = np.random.uniform(-1000, 1000, size=len(model.reactions))
achr.validate(np.atleast_2d(bad))

[8]:

array(['le'], dtype='<U3')


And for our generated samples:

[9]:

achr.validate(s1)

[9]:

array(['v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v',
'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v', 'v'], dtype='<U3')


Even though most models are numerically stable enought that the sampler should only generate valid samples we still urge to check this. validate is pretty fast and works quickly even for large models and many samples. If you find invalid samples you do not necessarily have to rerun the entire sampling but can exclude them from the sample DataFrame.

[10]:

s1_valid = s1[achr.validate(s1) == "v"]
len(s1_valid)

[10]:

100


8.2.3. Batch sampling¶

Sampler objects are made for generating billions of samples, however using the sample function might quickly fill up your RAM when working with genome-scale models. Here, the batch method of the sampler objects might come in handy. batch takes two arguments, the number of samples in each batch and the number of batches. This will make sense with a small example.

Let’s assume we want to quantify what proportion of our samples will grow. For that we might want to generate 10 batches of 50 samples each and measure what percentage of the individual 100 samples show a growth rate larger than 0.1. Finally, we want to calculate the mean and standard deviation of those individual percentages.

[11]:

counts = [np.mean(s.Biomass_Ecoli_core > 0.1) for s in optgp.batch(100, 10)]
print("Usually {:.2f}% +- {:.2f}% grow...".format(
np.mean(counts) * 100.0, np.std(counts) * 100.0))

Usually 6.30% +- 1.49% grow...


8.3. Adding constraints¶

Flux sampling will respect additional contraints defined in the model. For instance we can add a constraint enforcing growth in asimilar manner as the section before.

[12]:

co = model.problem.Constraint(model.reactions.Biomass_Ecoli_core.flux_expression, lb=0.1)
model.add_cons_vars([co])


Note that this is only for demonstration purposes. usually you could set the lower bound of the reaction directly instead of creating a new constraint.

[13]:

s = sample(model, 10)
print(s.Biomass_Ecoli_core)

0    0.106248
1    0.116061
2    0.113978
3    0.179056
4    0.117057
5    0.111005
6    0.182250
7    0.114853
8    0.128597
9    0.160970
Name: Biomass_Ecoli_core, dtype: float64


As we can see our new constraint was respected.