TMMC Class¶
The TMMC class serves as the main interface for handling TMMC simulation logic.
- class flames.tmmc.TMMC(model, framework_atoms, adsorbates, temperature, pressure, device, vdw_radii, vdw_factor=0.6, framework_energy=None, adsorbate_energy=None, max_translation=1.5, max_rotation=np.float64(1.5707963267948966), max_deltaE=1.555, save_frequency=100, output_to_file=True, output_folder=None, debug=False, random_seed=None, cutoff_radius=6.0, automatic_supercell=False)[source]
Bases:
BaseSimulatorBase class for transition matrix Monte Carlo (TMMC) simulations using ASE.
This class implements TMMC deletion/insertion moves, recording the deletion/insertion energies of the adsorbate.
- Parameters:
model (ase.calculators.calculator.Calculator) – The calculator to use for energy calculations. Can be any ASE-compatible calculator. The output of the calculator should be in eV.
framework_atoms (ase.Atoms) – The framework structure as an ASE Atoms object.
adsorbates (Adsorbate | list[Adsorbate]) – The adsorbate structure(s) as an Adsorbate object or list of Adsorbate objects.
temperature (float) – Temperature of the ideal reservoir in Kelvin.
pressure (float) – Pressure of the ideal reservoir in Pascal.
device (str) – Device to run the simulation on, e.g.,
'cpu'or'cuda'.vdw_radii (np.ndarray) – Van der Waals radii for the atoms in the framework and adsorbate. Should be an array of the same length as the number of atomic numbers in ASE.
vdw_factor (float, optional) – Factor to scale the Van der Waals radii. Default is
0.6.save_frequency (int, optional) – Frequency at which to save the simulation state and results. Default is
100.output_to_file (bool, optional) – If
True, writes the output to a file namedoutput_{temperature}_{pressure}.outin theresultsdirectory. Default isTrue.output_folder (str or None, optional) – Folder to save the output files. If
None, a folder namedresults_<T>_<P>will be created.debug (bool, optional) – If
True, prints detailed debug information during the simulation. Default isFalse.random_seed (int or None, optional) – Random seed for reproducibility. Default is
Noneand will generate a random seed automatically if not provided.cutoff_radius (float, optional) – Interaction potential cut-off radius used to estimate the minimum unit cell. Default is
6.0.
- check_tmmc_files_exist(file_path, max_loading, replicas=range(1, 5))[source]
Check if the required TMMC simulation data files exist for the specified replicas and loading.
- Parameters:
- Raises:
FileNotFoundError – If the specified directory or any required files do not exist.
- Return type:
- compute_isotherm(fugacities_Pa, uptake_units='nmol', show_progress=True)[source]
Computes uptakes and macrostate probability distributions (pi) for a list of fugacities.
- Parameters:
- Return type:
tuple[ndarray,ndarray,ndarray]- Returns:
uptakes_average (np.ndarray) – Array of expected uptake (in the specified units) averaged across replicas for each fugacity.
uptakes_sd (np.ndarray) – Array of standard error of the mean (SEM) for the uptake across replicas for each fugacity.
pi_average (np.ndarray) – 2D array of macrostate probability distributions averaged across replicas for each fugacity and loading.
- compute_isotherm_replica(ins_weights, del_weights, fugacities_Pa, show_progress=True)[source]
Computes uptakes and macrostate probability distributions (pi) for a given set of fugacities using pre-computed insertion and deletion weights.
This is a convenience wrapper combining compute_mpd and compute_uptake_from_mpd.
- Return type:
tuple[ndarray,ndarray]
- compute_mpd(ins_weights, del_weights, fugacities_Pa, show_progress=True)[source]
Computes the Macrostate Probability Distribution (MPD or Π) for a given set of fugacities.
At equilibrium, the system obeys the principle of detailed balance, meaning the probability flux between adjacent macrostates is equal:
Π(N) * P(N → N + 1) = Π(N + 1) * P(N + 1 → N)
By rearranging this equality, the true physical MPD (Π) can be constructed iteratively from the transition probabilities (P):
ln Π(N + 1) = ln Π(N) + ln( P(N → N + 1) / P(N + 1 → N) )
This function calculates those transition probabilities using the unbiased acceptance weights scaled by fugacity, and applies a Log-Sum-Exp (LSE) trick during normalization to guarantee numerical stability.
- Parameters:
ins_weights (list[np.ndarray]) – List of pre-computed insertion weights for each loading.
del_weights (list[np.ndarray]) – List of pre-computed deletion weights for each loading.
fugacities_Pa (np.ndarray) – Array of fugacities in Pascal.
show_progress (bool, optional) – If True, shows a progress bar. Default is True.
- Returns:
pi – 2D array of the MPD for each loading and fugacity. Shape: (max_loading, n_press).
- Return type:
np.ndarray
- compute_uptake_from_mpd(pi)[source]
Calculates the expected number of molecules (uptake) from the Macrostate Probability Distribution (MPD).
The MPD (Π) acts as the centerpiece of the ensemble thus the ensemble average of any physical property A can be derived directly from it via histogram reweighting:
⟨A⟩ = [ Σ_N A(N) * Π(N) ] / [ Σ_N Π(N) ]
For the adsorption isotherm (uptake), the physical property A(N) is simply the number of molecules N. Since Π is already normalized (Σ_N Π(N) = 1), the formula simplifies to the expected value:
⟨N⟩ = Σ_N (N * Π(N))
- Parameters:
pi (np.ndarray) – 2D array of the MPD. Expected shape: (max_loading, n_press).
- Returns:
uptakes – 1D array of expected number of molecules (uptake) for each fugacity. Shape: (n_press,).
- Return type:
np.ndarray
- get_adsorbates_index(tag=None)[source]
Get a list of indices of the adsorbate molecules in the current system.
- get_framework_mass()
Calculate the mass of the framework in kg.
- Returns:
The mass of the framework in kg.
- Return type:
- get_macrostate_str()[source]
Return a string representation of the current multi-component macrostate. Example: For a binary mixture with 1 CO2 and 2 H2O, returns “0001_0002”.
- Return type:
- get_number_of_adsorbates(system=None)[source]
Get the number of adsorbates in the current system. It considers the possibility of having multiple adsorbate species in the simulation.
- load_tmmc_weights(file_path, max_loading, replicas=range(1, 5), show_progress=True)[source]
Loads TMMC simulation data and pre-computes the fugacity-independent Boltzmann weights for a given temperature, returning them separated by replica.
- Parameters:
file_path (str) – Path to the directory containing the TMMC simulation data.
max_loading (int) – Maximum number of adsorbate molecules to consider for loading.
temperature_K (float) – Temperature in Kelvin for which to compute the Boltzmann weights.
replicas (list | range, optional) – List or range of replica indices to load. Default is range(1, 5).
show_progress (bool, optional) – If True, shows a progress bar during the loading of weights. Default is True.
- Return type:
- Returns:
ins_weights (dict[int, list[np.ndarray]]) – Dictionary containing the pre-computed insertion weights for each replica.
del_weights (dict[int, list[np.ndarray]]) – Dictionary containing the pre-computed deletion weights for each replica.
- Raises:
FileNotFoundError – If the specified directory or any required files do not exist.
- md(nsteps, atoms=None, time_step=0.5, ensemble='NVT', thermostat='NoseHoover', output_interval=100, movie_interval=100, calculator=None, update_state=True, trajectory_file=None, set_momenta=True, **kwargs)
Run a molecular dynamics simulation using the specified ensemble and thermostat.
- Parameters:
nsteps (int) – Number of steps to run the MD simulation.
time_step (float, optional) – Time step for the MD simulation in femtoseconds (default is 0.5 fs).
ensemble (str, optional) – The ensemble to use for the MD simulation (default is “NVT”). Can be one of “NVT” or “NPT”.
thermostat (str, optional) – The thermostat to use for the MD simulation (default is “NoseHoover”). For NVT, can be one of “Berendsen”, “NoseHoover”, or “Langevin”. For NPT, can be one of “Berendsen”, “NoseHoover”, or “MTKNPT”.
output_interval (int, optional) – The interval for logging output (default is 100 steps).
movie_interval (int, optional) – The interval for saving trajectory frames (default is 100 steps).
calculator (ase.calculators.calculator.Calculator or None, optional) – The calculator to use for energy calculations. If None, the default model will be used.
update_state (bool, optional) – If True, updates the current state of the simulation with the final state after MD. If False, returns the final state without updating. This difference is important for using the same method in the GCMC simulations when a MD step is used as a move. Default is True.
trajectory_file (str or None, optional) – If provided, saves the trajectory to the specified file instead of the default trajectory.
set_momenta (bool, optional) – Whether to set the atomic momenta to a Maxwell-Boltzmann distribution of the simulation temperature.
**kwargs (optional) –
Additional parameters passed directly to the specific MD thermostat (e.g., taut, tdamp, friction).
- NVT Berendsen:
- tautfloat, optional
Time constant for the Berendsen thermostat in fs (default is 1.0 fs).
- NVT Nose-Hoover:
- tdampfloat, optional
Time constant for the Nose-Hoover thermostat in fs (default is 50.0 fs).
- tchainint, optional
Number of thermostats in the Nose-Hoover chain (default is 3).
- tloopint, optional
Number of loops for the Nose-Hoover chain (default is 1).
- NVT Langevin:
- frictionfloat, optional
Friction coefficient for the Langevin dynamics (default is 0.01).
- NPT Berendsen:
- isotropicbool, optional
Whether to use isotropic pressure coupling (default is True).
- compressibilityfloat, optional
Compressibility of the material in bar^-1 (default is 1e-4 bar^-1).
- tautfloat, optional
Time constant for the Berendsen thermostat in fs (default is 10.0 fs).
- taupfloat, optional
Time constant for the Berendsen barostat in fs (default is 500.0 fs).
- NPT Nose-Hoover:
- ttimefloat, optional
Time constant for the Nose-Hoover thermostat in fs (default is 25.0 fs).
- ptimefloat, optional
Time constant for the Parrinello-Rahman barostat in fs (default is 75.0 fs).
- bulk_modulusfloat, optional
Bulk modulus of the material in GPa (default is 30.0 GPa).
- NPT MTK:
- tdampfloat, optional
Time constant for the Nose-Hoover thermostat in fs (default is 50.0 fs).
- pdampfloat, optional
Time constant for the Nose-Hoover barostat in fs (default is 500.0 fs).
- tchainint, optional
Number of thermostats in the Nose-Hoover chain (default is 3).
- pchainint, optional
Number of barostats in the Nose-Hoover chain (default is 3).
- tloopint, optional
Number of loops for the Nose-Hoover thermostat chain (default is 1).
- ploopint, optional
Number of loops for the Nose-Hoover barostat chain (default is 1).
- vol_constraintbool, optional
If True, the (N, V, sigma_a = 0, T)-ensemble is sampled, which allows for full cell fluctuations while keeping the cell volume fixed (default is False).
- Return type:
None|Atoms
- npt(nsteps, time_step=0.5, mode='iso_shape', driver='MTKNPT', set_momenta=True, output_interval=100, movie_interval=100, calculator=None, **kwargs)
Run a NPT simulation using the Berendsen thermostat and barostat.
- Parameters:
nsteps (int) – Number of steps to run the NPT simulation.
time_step (float, optional) – Time step for the NPT simulation (default is 0.5 fs).
mode (str, optional) – The mode of the NPT simulation (default is “iso_shape”). Can be one of “iso_shape”, “aniso_shape”, or “aniso_flex”.
driver (str, optional) – The driver to use for the NPT simulation. Can be Berendsen, NoseHoover or MTKNPT (default is “MTKNPT”).
set_momenta (bool, optional) – Whether to set the atomic momenta to a Maxwell-Boltzmann distribution of the simulation temperature.
output_interval (int, optional) – The interval for logging output (default is 100 steps).
movie_interval (int, optional) – The interval for saving trajectory frames (default is 100 step).
calculator (ase.calculators.calculator.Calculator or None, optional) – The calculator to use for energy calculations. If None, the default model will be used.
kwargs (optional) – Arguments passed to the ase molecular dynamics class.
- Return type:
None|Atoms
- nvt(nsteps, time_step=0.5, set_momenta=True, driver='NoseHoover', output_interval=100, movie_interval=100, calculator=None, **kwargs)
Run a NVT simulation using the specified thermostat.
- Parameters:
nsteps (int) – Number of steps to run the NVT simulation.
time_step (float, optional) – Time step for the NVT simulation in femtoseconds (default is 0.5 fs).
set_momenta (bool, optional) – Whether to set the atomic momenta to a Maxwell-Boltzmann distribution of the simulation temperature.
driver (str, optional) – The driver to use for the NVT simulation. Can be “NoseHoover” (default), Langevin, or “Berendsen” (Not recommended, for testing purposes only).
output_interval (int, optional) – The interval for logging output (default is 100 steps).
movie_interval (int, optional) – The interval for saving trajectory frames (default is 100 step).
calculator (ase.calculators.calculator.Calculator or None, optional) – The calculator to use for energy calculations. If None, the default model will be used.
kwargs (optional) – Arguments passed to the ase molecular dynamics class.
NoseHoover (For)
tdamp (-) – Time constant for the thermostat in fs (default is 50.0 fs).
tchain (-) – Length of the Nose-Hoover chain (default is 3).
tloop (-) – Number of loops for the Nose-Hoover chain (default is 1).
Langevin (For)
friction (-) – Friction coefficient for the Langevin thermostat in fs^-1 (default is 0.1 fs^-1).
Berendsen (For)
tau (-) – Time constant for the Berendsen thermostat in fs (default is 1.0 fs).
- optimize_adsorbate(max_steps=1000, max_force=0.05)
Optimize the adsorbate structure using the provided calculator.
- Parameters:
- Returns:
The optimized adsorbate structure.
- Return type:
ase.Atoms
- optimize_framework(max_steps=1000, opt_cell=True, fix_symmetry=True, hydrostatic_strain=True, symm_tol=0.001, max_force=0.05)
Optimize the framework structure using the provided calculator.
- run_tmmc(N_per_frame, trajectory_path)[source]
Run the transition matrix Monte Carlo simulation for N iterations in a given trajectory.
The trajectory is read from a file and the simulation is performed on each frame of the trajectory for N iterations.
For each iteration, no real move are actually performed on the system, but virtual insertion and deletion are performed and the corresponding energies and the unit cell volume are recorded.
- save_results(file_name=None)[source]
Save a json file with the main results of the simulation.
- set_adsorbates(adsorbates, adsorbate_energy=None)
Set the adsorbate structure for the simulation.
- Parameters:
- Return type:
- set_framework(framework_atoms, framework_energy=None)
Set the framework structure for the simulation.
- set_state(state)[source]
Set the current state of the simulation to a given ASE Atoms object. This method updates the current system, total energy, and number of adsorbates.
- Parameters:
state (ase.Atoms) – The ASE Atoms object representing the new state of the system.
- Return type:
- try_virtual_deletion(adsorbate_tag, ads_index=None)[source]
Try to delete an adsorbate molecule from the framework. This method randomly selects an adsorbate molecule and attempts deletion.
- Parameters:
adsorbate_tag (int) – The tag of the adsorbate molecule being deleted.
- Returns:
Deletion energy.
- Return type:
deltaE
- try_virtual_insertion(adsorbate_tag)[source]
Try to insert a new adsorbate molecule into the framework. This method randomly places the adsorbate in the framework and checks for van der Waals overlap. If there is no overlap, it calculates the new potential energy and decides whether to accept the insertion based on the acceptance criteria.