The MonteCarlo class¶
The thermodynamic properties of substitutional systems can be computed by means of Monte Carlo simulations.
This module allows the realization of Monte Carlo simulations in various ensembles.
Initialization and methods¶
- class clusterx.thermodynamics.monte_carlo.MonteCarlo(energy_model: Model, scell: SuperCell, nsubs: dict | None = None, ensemble: str = 'canonical', sublattice_indices: list | None = None, chemical_potentials: dict | None = None, models: list = [], predict_swap: bool = False, reduce_structure: bool = False, energy_key: str = 'energy', save_atoms_every: int = 0, atoms_filename: str = 'metropolis.traj', filename: str = 'trajectory.json', seed: int | None = None, resume_from: str | PathLike | None = None, save_atoms_endpoints: bool = False, atoms_mode: str = 'auto', start_from: str | PathLike | None = None)¶
Monte Carlo class
Objects of this class are used to perform Monte Carlo samplings.
It is initialized with:
a Model object, that enables to calculate the energy of a structure,
a SuperCell object, in which the sampling is performed,
specification of the thermodynamic ensemble:
If
ensembleis ‘canonical’, the composition for the sampling is defined withnsubs. In case of multilattices, the sublattice for the sampling can be refined withsublattice_indices.If
ensembleis ‘grandcanonical’, the sublattice is defined withsublattices_indices.
- Parameters:
- energy_modelModel
Linear CE model used for acceptance and rejection. Its predictions retain the fitted target’s normalization and units. The user must convert them to total supercell energy with metropolis’s explicit energy_factor.
- scellSuperCell
Simulation cell in which the sampling is performed.
- ensemblestr, default canonical
canonicalallows for swaps of atoms that conserve the concentration defined withnsubs.semigrand-canonicalallows replacing atoms in sub-lattices defined withsublattice_indiceswith other atoms in said sub-lattice.- nsubsdict, default None
Defines the number of substituted atoms in each sub-lattice of the Supercell in which the sampling is performed.
The format of the dictionary is as follows:
{site_type1:[n11,n12,...], site_type2:[n21,n22,...], ...}
It indicates how many substitutional atoms of every kind (n#1, n#2, …) may replace the pristine species for sites of site_type# (see related documentation in SuperCell object).
- sublattice_indiceslist of int, default None
Defines the sublattices for the grand canonical sampling. Furthermore, it can be used to limit the canonical sampling to a reduced number of sublattices. E.g. in the case of nsubs = {0:[4,6], 1:[4]}. Here, sublattices 0 and 1 contain substitutional sites, but only a sampling in sublattice 0 is wanted. Then, put
sublattice_indices= [0].- chemical_potentialsdict, default None
Define additive chemical-potential costs for semigrand sampling, in the same energy unit as k_B*T. Supply one value per allowed species, including pristine species (usually reference cost zero). To use physical chemical potentials in E - sum(mu*N), supply their negatives.
The format of the dictionary is as follows
- {site_type1:[\(\Delta \mu_{11}\), \(\Delta \mu_{12}\),…],
site_type2:[\(\Delta \mu_{21}\), \(\Delta \mu_{22}\),…], …}
Here, \(\Delta \mu_{\#i}\) is the chemical potential difference of substitutional species i relative to the pristine species in sub-lattice with site_type#.
- modelsList of Model objects
The properties returned from these Model objects are additionally calculated during the sampling and stored with their corresponding
prop_nameto the dictionarykey_value_pairsfor each visited structure during the sampling.Properties from Model obejects can also be calculated after the sampling by using the MonteCarloTrajectory class.
- predict_swapbool, default False
If set to True, this parameter makes the sampling faster by calculating the correlation difference of the proposed structure with respect to the previous structure.
- reduce_structurebool, default False
If true, cluster orbits/correlations are computed and evaluated on subset of sigmas, in a box around central site in the structure. Incompatible with non-diagonal supercell shapes.
- energy_keystr, default energy
For a multi-linear model, one of the predictions needs to be the energy prediction, energy_key needs to match one of the strings in energy_model.property_names, so that the energy prediction can be indexed from prediction vector.
- filenamestr, default trajectory.json
Path at which to store the MonteCarloTrajectory.
- seedint or None, default None
seed value for random number generators. For reproducible results, pass integer seed, otherwise seed=None
- resume_fromstr or path-like, default None
Start from the final complete frame of an XYZ/extxyz trajectory. The physical configuration is resumed with the random streams initialized from
seed; the original random stream is not restored. Without start_from this file is always used, regardless of output existence.- start_fromstr or path-like, default None
Enable automatic first-run/continuation selection. At the first metropolis call, inspect atoms_filename BEFORE opening it: if absent, load the final complete frame of start_from; if present, load the final complete frame of resume_from. With start_from, omitted resume_from defaults to atoms_filename. Even with distinct resume/output paths, output existence is the switch. Invalid selected checkpoints raise an error, without falling back to the other file. Selection happens once after construction or reset_chain; continuing stages reuse memory state. Both checkpoint options conflict with an explicit initial_decoration.
For reusable annealing input, use start_from=”300K.xyz”, atoms_filename=”250K.xyz”, atoms_mode=”a” and an explicit temperature and proposal/sweep count. The first invocation reads 300K.xyz; later invocations read 250K.xyz. The separate 300 K source remains unchanged. Enable save_atoms_every or save_atoms_endpoints to create checkpoints. To choose a different continuation source, add resume_from=”restart.xyz”; existence of 250K.xyz still selects between that source and 300K.xyz. These options restore configurations, not exact original random streams.
- save_atoms_endpointsbool, default False
Write the initial configuration and each metropolis call’s endpoint. Continuing calls share one stage boundary frame. Periodic checkpoints set by
save_atoms_everyfollow the chain’s proposal counter.- atoms_modestr, default “auto”
Apply once per chain: “x” requires a new output file, “w” overwrites, “a” appends, and “auto” overwrites fresh runs and appends resumes. XYZ counters start at zero for each fresh start or file-based resume.
- accept_step(de: float, dmu: float, beta: float) bool¶
Stepwise helper: de and dmu must already be TOTAL energy changes.
beta is the inverse of k_B*T in the same energy unit. This helper performs no normalization or unit conversion; metropolis applies the required energy_factor before its own acceptance check.
- metropolis(no_of_sampling_steps: int = 100, *, energy_factor: float, temperature: float | list[float], boltzmann_constant: float, initial_decoration: list[int] | None = None, target_rate: float | None = None, n_clics: int = 1, serialize: bool = False, filename: str = 'trajectory.json', max_steps_per_batch: int = 100000, continue_chain: bool = False, metadata: dict | None = None, energy_observer=None, observation_interval: int = 1)¶
Perform Monte-Carlo Metropolis simulation
Perfom Monte-Carlo Metropolis sampling for
no_of_sampling_stepssampling steps.In the canonical ensemble, accept a proposal with probability \(\min(1,\exp[-s\Delta E_{model}/(k_B T)])\), where \(s\) is the required scalar
energy_factor. The user must choose this multiplier so that \(s\Delta E_{model}\) is the TOTAL energy change of the simulation supercell, in the SAME energy units asboltzmann_constant * temperature. CELL cannot infer model units, model normalization, or the temperature unit.For a model in eV/atom and temperature in K, supply
energy_factor=len(scell)and k_B in eV/K. For meV/atom with k_B in eV/K, supplyenergy_factor=len(scell)/1000. A model already predicting total supercell energy requires an explicit 1 if its energy unit agrees with k_B*T. No automatic conversion is performed. The formerscale_factorlist API has been removed.Semigrand sampling retains the existing additive chemical-potential cost convention: the acceptance change is s*delta_E + delta_mu. Chemical-potential costs must already use the total-energy unit of k_B*T; they are not multiplied by energy_factor. To express the conventional E - sum(mu*N), pass negative physical chemical potentials.
- Parameters:
- no_of_sampling_stepsint
Number of sampling steps
- temperaturefloat or list of float
Required positive temperature in units chosen by the user. If list, its length must equal
no_of_sampling_steps. Kelvin is not assumed.- boltzmann_constantfloat
Required finite positive k_B in energy per temperature unit. Its product with temperature must have the unit of the scaled TOTAL supercell energy change. There is no default unit system.
- energy_factorfloat
Required finite positive scalar multiplying model energy differences. Includes BOTH the extensive normalization (per atom, per parent cell, etc. to the full simulation supercell) and any energy-unit conversion. No list, reciprocal convention, or inferred atom count is accepted.
- initial_decorationlist of int
Atomic numbers of the initial structure, from which the sampling starts. If
None, sampling starts with a structure randomly generated.- target_ratefloat, default None
Real number between 0 and 1. Represents the targeted acceptance rate. If not
None, the initial temperature will be adjusted to match the given acceptance rate. The acceptance ratio during the simulation is computed using the last 1000 moves. This changes the effective sampling temperature. Setting it to None restores the explicitly supplied temperature for fixed-temperature sampling.- n_clicsint
Number of species flips (grandcanonical) or species swaps (canonical) per sampling step. Defaults to 1.
- serializebool, default False
Serialize the MonteCarloTrajectory object into a Json file after the sampling.
- filenamestr, default trajectory.json
Name of a Json file in which the trajectory is serialized after the sampling if
serializeis True.- max_steps_per_batchint, default 100000
Maximum number of proposal temperatures held in a temporary array at once. The Markov chain and random-number streams continue across these internal batches.
- continue_chainbool, default False
Continue the configuration and cached energy from the previous call. The default preserves the historical behavior of starting a new configuration for each call.
- metadatadict or None
Optional descriptive information saved with the trajectory. Sampling options must be explicit arguments; unknown keywords are errors.
- energy_observercallable or None
Optional callback
energy_observer(step, total_energy)after each observation interval, including rejected moves. Energy is absolute model energy multiplied by energy_factor, also for reduced MC. No initial-state observation is made. The callback must not mutate the chain. This permits averages without accepted-move histories.- observation_intervalpositive int
Proposal spacing for the observer, counted within this call.
- Returns:
- MonteCarloTrajectory object
Trajectory containing the complete information of the sampling trajectory.
- propose_step()¶
Propose a new structure by performing a random flip or swap.
- reset_chain(initial_decoration=None, seed=None, resume_from=None, start_from=None)¶
Discard the chain and caches, and optionally choose a new XYZ start.
No checkpoint arguments means a fresh random configuration, or the supplied initial_decoration. resume_from alone always loads that file. With start_from, select start_from if atoms_filename is absent, otherwise resume_from (defaulting to atoms_filename). Selection occurs at the next metropolis call, once, before opening the output. Checkpoint options and initial_decoration are mutually exclusive. All resets initialize new random streams from seed, not the saved run’s original random state.
Examples
mc.reset_chain(start_from=”300K.xyz”, seed=43), with mc configured to write 250K.xyz, loads 300K.xyz for a new output or resumes 250K.xyz if it exists. Pass resume_from=”restart.xyz” to use that alternate source when 250K.xyz exists. mc.reset_chain(seed=43) explicitly clears file-based initialization and starts fresh instead.
- run(n_steps: int, temperature: float | list[float] = 1.0)¶
The stepwise runner is unfinished; use metropolis with explicit physical inputs.
- step() bool¶
Perform one step of the Metropolis algorithm.
- update_state()¶
Update the state of the system after accepting a step.