Batch Reactor Guide
The Batch class simulates 0-dimensional (0D) batch reactor experiments - closed systems where only reactions occur without spatial transport.
Creating a Batch
from porousmedialab.batch import Batch
batch = Batch(tend=40, dt=1)
Parameters:
tstart(float): Start time of simulation (default0)tend(float): End time of simulation (in your chosen time units)dt(float): Timestep for integrationode_method(str): Reaction solver. Options are'scipy'(default),'scipy_sequential','rk4'and'butcher5'.rtol,atol(float): Relative and absolute tolerances for the SciPy solvers. Defaults are1e-3and1e-6. Absolute tolerance is in concentration units.scipy_method(str): Integrator forode_method='scipy'. Options are'LSODA'(default),'BDF','Radau','RK45','RK23'and'DOP853'.'scipy_sequential'supports only'LSODA'.non_negative_rates(bool):True(default) sets negative rates to zero. Set it toFalseto keep both signs.
Adding Species
batch.add_species(name='O2', init_conc=0.2, allow_negative=False)
batch.add_species(name='CH4', init_conc=0.001)
batch.add_species(name='CO2', init_conc=0)
Parameters:
name(str): Name of the chemical species (used in rate expressions)init_conc(float): Initial concentrationallow_negative(bool): Set toTrueto skip the concentration floor for signed variables. The default isFalse.Temperaturecan go negative automatically.
Defining Constants
Constants are parameters used in rate expressions:
batch.constants['k1'] = 0.1 # Rate constant
batch.constants['Km'] = 0.001 # Half-saturation constant
batch.constants['T'] = 25 # Temperature
Defining Rate Expressions
Rate expressions are strings. The SciPy solvers compile them to NumPy code.
'rk4', 'butcher5' and their rate reconstruction evaluate them with
numexpr. Use the operators and functions below for compatibility with every
solver.
# First-order kinetics
batch.rates['R1'] = 'k1 * CH4'
# Michaelis-Menten kinetics
batch.rates['R2'] = 'k1 * O2 / (Km + O2)'
# Multiple terms
batch.rates['R3'] = 'k1 * CH4 * O2 / (Km + O2)'
# Inhibition term
batch.rates['R4'] = 'k1 * CH4 * Km / (Km + CO2)'
Available operators: +, -, *, /, ** (power)
Available functions: exp, log, log10, sqrt, sin, cos, tan, abs, where
Setting dcdt (Time Derivatives)
Define how each species concentration changes over time:
# Methane oxidation uses the R3 rate from above
batch.dcdt['CH4'] = '-R3'
batch.dcdt['O2'] = '-2 * R3'
batch.dcdt['CO2'] = 'R3'
Running the Simulation
batch.solve(verbose=True)
Parameters:
verbose(bool): IfTrue, prints progress and time estimates
Solver settings
Pass rtol, atol, scipy_method and non_negative_rates by keyword or assign
them on an existing model. Changes take effect at the next reaction step.
- Trace species. The default
atol=1e-6may be too large to resolve trace concentrations. Choose an absolute tolerance below the smallest concentration you need to resolve, for exampleBatch(tend, dt, atol=1e-12). PorousMediaLab floors concentrations for species that disallow negative values at1e-16with the SciPy engines and at0with'rk4'and'butcher5'. With LSODA, avoidrtol < 100 * eps(whereepsis machine epsilon) and extreme values such asatol <= 1e-155when any state component starts at zero, since these settings can cause solver warnings, a return code of-3in'scipy_sequential', or a stalled integration. - Reversible reactions. With
non_negative_rates=False, a rate such ask*(C_sat - C)ork*(Omega - 1)can describe a reaction in both directions. If the reverse (dissolution) rate persists after the consumed phaseMis depleted, the concentration floor hides the overshoot and silently creates mass. The indicator(M > 0)stays true at the SciPy engines’1e-16floor, so multiply the dissolution branch by a smooth factor that vanishes asMapproaches zero, such asMon any engine orM/(M + eps)with a small positiveepson adaptive SciPy solvers (use a sufficiently smalldtfor this second factor with'rk4'or'butcher5'). Review models that rely on the default rate clamp before enabling signed rates. To keep a particular rate one-directional, write its expression as(x)*((x) > 0)orwhere(x > 0, x, 0), replacingxwith that rate expression. Reconstructed rates also keep their sign. - Method.
'BDF'and'Radau'suit stiff systems.'RK45','RK23'and'DOP853'suit non-stiff systems. The'rk4'and'butcher5'engines ignorertol,atolandscipy_method. Their accuracy and stability depend ondt.
Accessing Results
Results are stored in species dictionaries:
# Get concentration time series (shape: [1, num_timesteps])
conc = batch.O2.concentration
# Get final concentration
final = batch.O2.concentration[0, -1]
# Get time array
time = batch.time
# Plot concentration vs time
import matplotlib.pyplot as plt
plt.plot(batch.time, batch.O2.concentration[0])
Plotting Methods
Built-in plotting methods:
# Plot single species
batch.plot('O2')
# Plot all species
batch.plot_profiles()
# Plot reaction rates
batch.reconstruct_rates()
batch.plot_rates()
# Plot rate of change (delta)
batch.plot_deltas()
The SciPy solvers leave estimated_rates at zero until reconstruction.
plot_deltas() works directly from concentration changes or stored
deltas. Use plot_rate(rate) for a single reaction, plot_delta(element)
for a single species and plot_fractions() for acid-base fractions.
Saving Results
Save results to HDF5 format:
batch.save_results_in_hdf5()
This creates results.h5 containing:
time: Time arrayconcentrations: All species concentrationsestimated_rates: Calculated ratesparameters: Constants used
Pass a filename to write somewhere else:
batch.save_results_in_hdf5('batch-results.h5')
Advanced: Henry Equilibrium
For gas-liquid partitioning, specify the dimensionless ratio
Hcc = C_aq / C_gas. The default gas_water_ratio=None assumes equal
volumes. henry_equilibrium is an alias for add_partition_equilibrium.
# Add both aqueous and gas species
batch.add_species(name='CO2_aq', init_conc=0.001)
batch.add_species(name='CO2_gas', init_conc=0)
# Set Henry equilibrium (Hcc is dimensionless Henry constant)
batch.add_partition_equilibrium(aq='CO2_aq', gas='CO2_gas', Hcc=0.83)
# For a headspace whose volume is 25% of the water volume, use this call instead:
# batch.add_partition_equilibrium(aq='CO2_aq', gas='CO2_gas', Hcc=0.83, gas_water_ratio=0.25)
Advanced: Acid-Base Equilibrium
For pH-dependent systems:
# Add carbonate species
batch.add_species(name='H2CO3', init_conc=0.001)
batch.add_species(name='HCO3', init_conc=0.01)
batch.add_species(name='CO3', init_conc=0.0001)
# Define acid with pKa values
batch.add_acid(
species=['H2CO3', 'HCO3', 'CO3'],
pKa=[6.35, 10.33],
charge=0 # Charge of fully protonated form
)
# Add non-dissociating ion
batch.add_species(name='Na', init_conc=0.1)
batch.add_ion(name='Na', charge=1)
# Create the acid-base system
batch.create_acid_base_system()
After create_acid_base_system(), a pH species is automatically created and tracked.
Complete Example
from porousmedialab.batch import Batch
# Create batch reactor
batch = Batch(tend=40, dt=1)
# Add species
batch.add_species(name='OM', init_conc=0.01) # Organic matter
batch.add_species(name='O2', init_conc=0.2) # Oxygen
batch.add_species(name='CO2', init_conc=0) # Carbon dioxide
# Set constants
batch.constants['k'] = 0.5 # Degradation rate
batch.constants['Km'] = 0.02 # Half-saturation
# Define rate
batch.rates['R_deg'] = 'k * OM * O2 / (Km + O2)'
# Set time derivatives
batch.dcdt['OM'] = '-R_deg'
batch.dcdt['O2'] = '-R_deg'
batch.dcdt['CO2'] = 'R_deg'
# Run and plot
batch.solve()
batch.plot_profiles()
Tips
- Timestep selection: Start with a larger
dtand decrease if you see numerical instabilities - Units: Be consistent with units throughout (e.g., mol/L for concentrations, 1/day for rates)
- Debugging: Use
verbose=Trueto see simulation progress - Rate expressions: Ensure all variables in rate expressions are defined as species or constants