Parallelized simulations

In medusa, ensemble Flux Balance Analysis (FBA) can be sped up thanks to the multiprocessing Python module. With this approach, each core (or processor) is assigned a subset of ensemble members for which to perform FBA, speeding up the computation in proportion to the number of additional processors allocated.

Let's load a test model to demonstrate parallel ensemble FBA. This ensemble has 1000 members, so each FBA step will return fluxes for each reaction in one of the 1000 members.


In [1]:
from medusa.flux_analysis import flux_balance
from medusa.test import create_test_ensemble
ensemble = create_test_ensemble("Staphylococcus aureus")

Next, perform the actual simulations. To parallelize, just indicate the number of cores you'd like to use with the num_processes argument. medusa will not automatically recognize that you have additional cores available. We'll use the time module to keep track of how long the simulation takes given the number of cores allocated.


In [3]:
import time

runtimes = {}
for num_processes in range(1,9):
    t0 = time.time()
    flux_balance.optimize_ensemble(ensemble, num_processes = num_processes)
    t1 = time.time()
    runtimes[num_processes] = t1-t0
    print(str(num_processes) + ' processors: ' + str(t1-t0) + 's')


1 processors: 175.3236665725708s
2 processors: 95.32818102836609s
3 processors: 68.18270087242126s
4 processors: 56.23384976387024s
5 processors: 53.41068649291992s
6 processors: 52.80183672904968s
7 processors: 50.88461422920227s
8 processors: 51.96336841583252s

In [5]:
import matplotlib.pylab as plt
fig,ax = plt.subplots()
plt.bar(runtimes.keys(), runtimes.values(), align = 'center')
plt.xlabel('Number of processors')
plt.ylabel('Runtime (s)')


Out[5]:
Text(0, 0.5, 'Runtime (s)')

As you can see from the printed output and the plots, a couple of additional cores really speeds things up. However, each core requires an additional copy of the ensemble for its independent simulations. This process (serialization and deserialization) leads to diminishing returns as the number of cores is increased. We are working on improving this, but for now, it is best to choose a modest number of cores (e.g. 2-4).