MonteCarloMoves
Functions
FreeBird.MonteCarloMoves — Module
MonteCarloMovesModule containing functions for performing Monte Carlo moves on atomistic/lattice systems.
FreeBird.MonteCarloMoves.MC_cluster_walk! — Method
MC_cluster_walk!(n_steps::Int, lattice::LatticeWalker{C}, h::ClassicalHamiltonian, emax::Float64, cluster_p::Float64; energy_perturb::Float64=0.0)Perform a sequence of geometric cluster moves on the lattice system, accepting each if E < emax.
Arguments
n_steps::Int: The number of cluster move attempts to perform.lattice::LatticeWalker{C}: The walker to perform cluster moves on.h::ClassicalHamiltonian: The lattice Hamiltonian.emax::Float64: The maximum energy allowed for accepting a move (dimensionless).cluster_p::Float64: The growth probability for BFS cluster construction.energy_perturb::Float64=0.0: Energy perturbation to break degeneracies.
Returns
accept_this_walker::Bool: Whether at least one move was accepted.accept_rate::Float64: The fraction of accepted moves.lattice::LatticeWalker: The updated walker.
FreeBird.MonteCarloMoves.MC_galilean_walk! — Method
MC_galilean_walk!(n_steps::Int, at::AtomWalker{1}, pot::SingleComponentPotential{Pairwise},
emax::typeof(0.0u"eV"); step_size::Float64, n_refresh::Int=8)Perform a Galilean (reflective) Monte Carlo walk under a nested-sampling energy ceiling: n_steps trajectories, each drawing a fresh velocity uniformly on the 3N-sphere and running n_refresh straight-line segments of 3N-space length step_size (per-atom displacement scales as step_size/sqrt(3N)), reflecting specularly off the constraint boundary through the energy gradient at the first rejected trial and continuing through it, with velocity reversal when the reflected trial also fails. All free particles move collectively; segment energies are full interacting_energy recomputes (a collective move has no incremental path), so the walker's energy never accumulates drift. The gradient enters only through the reflection direction, so an inaccurate force degrades mixing but cannot bias the stationary measure.
Requirements: a single unfrozen component and a fully periodic orthorhombic cell (the position wrap mirrors coordinates at non-periodic walls without reversing the velocity, which would break reversibility); an empty walker returns unchanged.
Returns
accept_this_walker::Bool: Whether any segment ended inside the constraint.accept_rate::Float64: Fraction of segments ending inside the constraint.at::AtomWalker{1}: The updated walker.stats::NamedTuple: Integer segment counters, in order(galilean_attempted, galilean_accepted, galilean_reflect_attempted, galilean_reflect_evals, galilean_reflect_accepted): segments run (n_steps×n_refresh), segments ending inside (the rate numerator, sorate == galilean_accepted / galilean_attemptedis an identity), segments whose first trial failed (each computing exactly one gradient), reflections with a usable gradient (each evaluating the second trial energy, so full energy evaluations =galilean_attempted + galilean_reflect_evals), and reflected segments ending inside. A trailing addition: three-name destructures of the previous return keep working.
FreeBird.MonteCarloMoves.MC_grand_canonical_walk! — Method
MC_grand_canonical_walk!(n_steps::Int, at::AtomWalker{1}, pot::SingleComponentPotential{Pairwise}, emax::typeof(0.0u"eV");
z0V::Float64, species, p_move::Float64=0.5, p_insert::Float64=0.25,
step_size::Float64=0.5, n_max::Int=typemax(Int),
mu::typeof(0.0u"eV")=0.0u"eV")Perform a grand-canonical Monte Carlo walk on a continuous-space AtomWalker{1} below a nested-sampling ceiling on the ordering scalar E - mu*N (the energy ceiling at the default mu = 0): single-atom displacements mixed with uniform-in-cell insertions and uniform-among-particles deletions, under the Metropolis corrections that preserve the activity-z0-weighted reference measure. The continuous counterpart of the lattice MC_grand_canonical_walk! above; the site-counting acceptance ratios of the lattice kernel do not apply here and are replaced by the volume-and-activity forms of gc_insert_acceptance_ratio/gc_delete_acceptance_ratio (pre-move particle count in both).
Requirements: a single unfrozen component, and an orthorhombic cell (consistent with pbc_dist); both are validated on entry.
Random-number stream contract (fixed by tests): one channel draw per step; a displacement draws one particle index and the three walk displacements; an insertion draws three position uniforms (x, y, z) plus the Metropolis uniform only when its ratio is below one; a deletion draws one particle index plus the conditional Metropolis uniform. Guard skips (a displacement or deletion proposed at N = 0, an insertion proposed above n_max) consume only the channel draw and are not counted as attempts. The ceiling is checked before the Metropolis ratio, so ceiling rejections draw no Metropolis uniform. Energies are updated incrementally through single_site_energy on the same audited path the displacement walks use, with insertions evaluated by insert-then-revert.
Arguments
n_steps::Int: The number of Monte Carlo steps to perform.at::AtomWalker{1}: The walker to evolve; a single unfrozen component.pot::SingleComponentPotential{Pairwise}: The pairwise potential.emax::typeof(0.0u"eV"): The nested-sampling ceiling on the ordering scalarE - mu*N(strict-below acceptance); the energy ceiling at the defaultmu = 0.z0V::Float64: Dimensionless product of the reference activity and the cell volume.species: Chemical identity (aSymbolorChemicalSpecies) of inserted particles; passed explicitly because the configuration may be empty.p_move::Float64=0.5: Probability of a displacement move.p_insert::Float64=0.25: Probability of an insertion move (deletion takes the remainder).step_size::Float64=0.5: Maximum displacement per direction, in Angstrom.n_max::Int=typemax(Int): Upper bound on the particle count, for bounded constructions only. A finite cap truncates the unbounded particle-number support of the reference measure and biases the evidence; production callers must leave it inactive.mu::typeof(0.0u"eV")=0.0u"eV": Chemical potential of the ordering scalar. It enters only the ceiling indicator, evaluated on the proposal's own particle count (n,n + 1,n - 1per channel), never the acceptance ratios; at the default the added term is an exact zero and the random-number stream is unchanged.
Returns
accept_this_walker::Bool: Whether at least one move was accepted.accept_rate::Float64: Fraction of accepted moves overn_steps.at::AtomWalker{1}: The updated walker.move_stats::NamedTuple: Per-move-type attempt/accept counters (move_*,insert_*,delete_*); attempts are counted at proposal, ceiling rejections included, guard skips excluded.
FreeBird.MonteCarloMoves.MC_grand_canonical_walk! — Method
MC_grand_canonical_walk!(n_steps::Int, lattice::LatticeWalker{1},
h::ClassicalHamiltonian, omega_max::Float64,
mu::Float64;
p_move::Float64=0.5, p_insert::Float64=0.25,
energy_perturb::Float64=0.0, n_max::Int=typemax(Int),
clusters_freq::Int=0, swaps_freq::Int=1,
cluster_p::Float64=0.3, z0::Float64=1.0,
p_bias::Float64=0.0, bias_predicate::Symbol=:contact,
bias_shells::Int=1)Perform grand-canonical MCMC on a single-component lattice, mixing fixed-N moves (local swaps and/or geometric cluster moves) with single-site insertion and deletion.
Each step:
- With probability
p_move: propose a fixed-N move (local swap or cluster move, selected byswaps_freq:clusters_freqratio). - With probability
p_insert: propose inserting one particle. - With probability
1 - p_move - p_insert: propose deleting one particle.
Insert/delete proposals use a Metropolis correction to preserve the ideal-lattice-gas prior at reference fugacity z0 — the Bernoulli product measure giving each configuration with N particles weight z0^N — over all microstates with Ω < Ω_max:
- Insert ratio:
z0 * (p_delete / p_insert) * (M - N) / (N + 1) - Delete ratio:
(1 / z0) * (p_insert / p_delete) * N / (M - N + 1)
The default z0 = 1.0 reduces to the uniform prior over all 2^M microstates, matching the Ω-sorted grand-canonical nested sampling construction. z0 ≠ 1 is used by the ideal-gas-referenced (E-sorted) construction, where the walk runs with mu = 0 so the Ω ceiling reduces to an energy ceiling.
Cluster moves are symmetric (no Metropolis correction), accepted if Ω < Ω_max.
Arguments
n_steps::Int: Number of MCMC steps.lattice::LatticeWalker{1}: The walker (single component).h::ClassicalHamiltonian: The lattice Hamiltonian.omega_max::Float64: Upper bound on grand potential Ω = E − μN (unitless).mu::Float64: Chemical potential (unitless, in same energy units as Hamiltonian).p_move::Float64=0.5: Probability of a fixed-N move.p_insert::Float64=0.25: Probability of an insertion move.energy_perturb::Float64=0.0: Energy perturbation for degeneracy breaking.n_max::Int=typemax(Int): Upper bound on particle count.clusters_freq::Int=0: Relative weight of cluster moves within fixed-N branch (0 = disabled).swaps_freq::Int=1: Relative weight of local swaps within fixed-N branch.cluster_p::Float64=0.3: Current cluster growth probability.z0::Float64=1.0: Reference fugacity of the prior preserved by insert/delete (1.0 = uniform prior over microstates).p_bias::Float64=0.0: Probability that an insertion draws its site uniformly fromlattice_biased_sites(x; predicate=bias_predicate, shells=bias_shells)instead of from all empty sites. The acceptance then uses the composite proposal density evaluated for the actually chosen site, and the deletion acceptance uses the reverse composite density evaluated on the post-deletion configuration (every set quantity on the lower-N member of the pair; the delete ratio's particle countnis the pre-delete count), so thez0-weighted prior stays invariant. An empty biased set makes the biased sub-channel a null proposal (counted as attempted, nothing changes); a zero reverse density (p_bias = 1with the vacated site outside the biased set) is an immediate reject.0.0reproduces the legacy sampler bit-for-bit.bias_predicate::Symbol=:contact: Biased-set predicate,:contactor:cavity.bias_shells::Int=1: Neighbor shells scanned by the predicate.incremental::Bool=false: Opt-in incremental energy evaluation: non-cluster proposals under a Hamiltonian withsupports_site_deltasadvance a per-walk raw-energy anchor by exact O(z)site_flip_deltasums; cluster proposals and unsupported Hamiltonians fall back to the full recompute, which also re-anchors the accumulator. The default is draw-count and digit identical to the shipped arithmetic; the delta path accumulates in a different floating-point order, so same-seed trajectories differ from the default.swap_mode::Symbol=:uniform_pair: Local-swap proposal distribution.:uniform_pairkeeps the shipped uniform site-pair draw (equal-occupancy pairs are accepted no-ops, counted by theswap_null_*subset counters);:occupied_empty(opt-in, changes the random stream) drawshop_fromuniform over occupied andhop_touniform over empty sites, symmetric with no acceptance correction and zero nulls, guard-skipped on empty and full lattices.
Returns
accept_this_walker::Bool: Whether at least one move was accepted.accept_rate::Float64: Fraction of accepted moves.lattice::LatticeWalker{1}: The updated walker.cluster_accepted_count::Int: Number of accepted cluster moves (for adaptive tuning).cluster_total_count::Int: Number of attempted cluster moves (for adaptive tuning).move_stats::NamedTuple: Per-move-type attempt/accept counters for the walk:swap_*,swap_null_*(subsets of the swap pair: equal-occupancy no-op proposals),cluster_*(duplicating the two preceding elements),insert_uniform_*,insert_biased_*,delete_*. Attempts are counted at proposal: ceiling rejections included, guard skips excluded, and an empty-biased-set null proposal counts as an attempted biased insert.
FreeBird.MonteCarloMoves.MC_grand_canonical_walk! — Method
MC_grand_canonical_walk!(n_steps::Int, at::AtomWalker{1},
cps::CompositeParameterSets{C,P}, emax::typeof(0.0u"eV"),
surface::AtomWalker{CS};
z0V::Float64, species, p_move::Float64=0.5,
p_insert::Float64=0.25, step_size::Float64=0.5,
n_max::Int=typemax(Int), mu::typeof(0.0u"eV")=0.0u"eV")Surface-aware method of the continuous grand-canonical kernel: identical moves, acceptance ratios, and random-number stream contract as the plain method above, with every single-site energy evaluated against the frozen external surface as the appended LAST component of the composite parameter set (the LJSurfaceWalkers convention, CP = C + 1 with C = 2 here: adsorbate first, surface last). Insertion and deletion energy differences therefore include the adsorbate-surface term automatically. Insertions propose uniformly in the FULL cell, keeping the library's reference-measure convention: the substrate region is excluded by the energy ceiling, never by the proposal support, so z0V folds the full cell volume. The walker's energy carries energy_frozen_part as a constant offset, exactly as in the surface method of MC_random_walk!; incremental updates are unaffected by it. The mu keyword has the plain method's meaning: emax is the ceiling on E - mu*N, evaluated on the proposal's own particle count, the energy ceiling at the default.
The cavity-biased insertion channel and the Galilean burst are not surface-aware, so this method takes no p_bias/bias_radius/bias_grid kwargs — passing one is a loud kwarg MethodError rather than a silently wrong answer.
Requirements, validated on entry: a single unfrozen adsorbate component; a two-component parameter set (C == 2); an orthorhombic cell (consistent with pbc_dist); and the surface sharing the walker's cell.
Returns
The same 4-tuple as the plain method; the biased-insertion counters are present in the stats NamedTuple and always zero (the channel does not exist here).
FreeBird.MonteCarloMoves.MC_mixed_moves! — Method
MC_mixed_moves!(n_steps::Int, at::AtomWalker{C}, pot::AbstractPotential, step_size::Float64, emax::typeof(0.0u"eV"), freq::Vector{Int}) where CPerform a Monte Carlo mixed move consisting of random walks and atom swaps in the AtomWalker. Arguments
n_steps::Int: The number of Monte Carlo steps to perform.at::AtomWalker{C}: TheAtomWalkerobject.pot::AbstractPotential: The potential object for energy calculations.step_size::Float64: The step size for the random walk moves.emax::typeof(0.0u"eV"): The maximum energy allowed for accepting a move.freq::Vector{Int}: A vector containing the frequencies of random walk and swap moves. The first element is the frequency of random walk moves, and the second element is the frequency of swap moves.
Returns
accept_this_walker::Bool: Whether the walker is accepted or not.accept_rate::Float64: The acceptance rate of the mixed moves.at::AtomWalker{C}: The updatedAtomWalker.
FreeBird.MonteCarloMoves.MC_muVT_walk! — Method
MC_muVT_walk!(n_steps::Int, at::AtomWalker{1}, pot::SingleComponentPotential{Pairwise},
temperature::Float64;
zV::Float64, species, p_move::Float64=0.5, p_insert::Float64=0.25,
step_size::Float64=0.5, kb::Float64=8.617333262e-5)Perform a fixed-temperature grand-canonical (μVT) Metropolis walk on a continuous-space AtomWalker{1}: single-atom displacements under the Boltzmann acceptance min(1, e^(-βΔU)), mixed with uniform-in-cell insertions and uniform-among-particles deletions under min(1, ratio × e^(-βΔU)), where the ratio is the volume-and-activity form of gc_insert_acceptance_ratio/gc_delete_acceptance_ratio (pre-move particle count in both) and ΔU is the post-minus-pre energy change of the proposed move in every channel. The fixed-temperature sibling of the nested-sampling kernel above, sharing its entry validation, guard-skip discipline, incremental single_site_energy path, insert-evaluate-revert bookkeeping, and move_stats schema; the athermal energy ceiling is replaced by the Boltzmann factor, and the dimensionless activity-volume zV = e^(βμ) V / Λ(T)^3 is folded by the caller, mirroring the z0V convention (the kernel itself never sees μ or Λ).
Draw discipline: one channel draw per step; the Metropolis uniform is drawn only when the combined acceptance factor is below one (for displacements, only when ΔU > 0). An insertion landing exactly on a particle (a NaN pair energy) rejects without drawing; a +Inf overlap energy underflows the Boltzmann factor to a combined factor of exactly zero and rejects through the ordinary draw.
Arguments
n_steps::Int: The number of Monte Carlo steps to perform.at::AtomWalker{1}: The walker to evolve; a single unfrozen component.pot::SingleComponentPotential{Pairwise}: The pairwise potential.temperature::Float64: The temperature in Kelvin; must be positive.zV::Float64: Dimensionless product of the target activity and the cell volume.species: Chemical identity (aSymbolorChemicalSpecies) of inserted particles.p_move::Float64=0.5: Probability of a displacement move.p_insert::Float64=0.25: Probability of an insertion move (deletion takes the remainder).step_size::Float64=0.5: Maximum displacement per direction, in Angstrom.kb::Float64=8.617333262e-5: The Boltzmann constant in eV/K.
Returns
at::AtomWalker{1}: The updated walker.accept_rate::Float64: Fraction of accepted moves overn_steps.move_stats::NamedTuple: Per-move-type attempt/accept counters (move_*,insert_*,delete_*); attempts are counted at proposal, guard skips excluded.
FreeBird.MonteCarloMoves.MC_new_sample! — Method
MC_new_sample!(lattice::LatticeWalker, h::ClassicalHamiltonian, emax::Float64; energy_perturb::Float64=0.0)Generate a new sample for the lattice system.
Arguments
lattice::LatticeWalker: The walker to generate a new sample for.h::ClassicalHamiltonian: The Hamiltonian containing the on-site and nearest-neighbor interaction energies.emax::Float64: The maximum energy allowed for accepting a move.energy_perturb::Float64=0.0: The energy perturbation used to make degenerate configurations distinguishable.
Returns
accept_this_walker::Bool: Whether the walker is accepted or not.lattice::LatticeWalker: The updated walker.
FreeBird.MonteCarloMoves.MC_random_swap! — Method
MC_random_swap!(n_steps::Int, at::AtomWalker{C}, lj::LennardJonesParameterSets, emax::typeof(0.0u"eV"))Perform a Monte Carlo random swap of two atoms in the AtomWalker. Only works when there are two or more non-frozen components.
Arguments
n_steps::Int: The number of Monte Carlo steps to perform.at::AtomWalker{C}: TheAtomWalkerobject.lj::LennardJonesParameterSets: The Lennard-Jones parameters.emax::typeof(0.0u"eV"): The maximum energy allowed for accepting a move.
Returns
accept_this_walker::Bool: Whether the walker is accepted or not.accept_rate::Float64: The acceptance rate of the random walk.at::AtomWalker{C}: The updatedAtomWalker.
FreeBird.MonteCarloMoves.MC_random_walk! — Method
MC_random_walk!(n_steps::Int, at::AtomWalker{C}, pot::AbstractPotential, step_size::Float64, emax::typeof(0.0u"eV"), surface::AtomWalker{CS})Perform a Monte Carlo random walk on the atomic/molecular system with an external surface.
Arguments
n_steps::Int: The number of Monte Carlo steps to perform.at::AtomWalker{C}: The walker to perform the random walk on.pot::AbstractPotential: The potential energy function for the system.step_size::Float64: The maximum distance an atom can move in any direction.emax::typeof(0.0u"eV"): The maximum energy allowed for accepting a move.surface::AtomWalker{CS}: The surface walker object to consider in the energy calculation. Typically frozen.
Returns
accept_this_walker::Bool: Whether the walker is accepted or not.accept_rate::Float64: The acceptance rate of the random walk.
FreeBird.MonteCarloMoves.MC_random_walk! — Method
MC_random_walk!(n_steps::Int, at::AtomWalker, pot::AbstractPotential, step_size::Float64, emax::typeof(0.0u"eV"))Perform a Monte Carlo random walk on the atomic/molecular system.
Arguments
n_steps::Int: The number of Monte Carlo steps to perform.at::AtomWalker{C}: The walker to perform the random walk on.pot::AbstractPotential: The potential energy function for the system.step_size::Float64: The maximum distance an atom can move in any direction.emax::typeof(0.0u"eV"): The maximum energy allowed for accepting a move.
Returns
accept_this_walker::Bool: Whether the walker is accepted or not.accept_rate::Float64: The acceptance rate of the random walk.at::AtomWalker: The updated walker.
FreeBird.MonteCarloMoves.MC_random_walk! — Method
MC_random_walk!(n_steps::Int, at::AtomWalker, pot::LennardJonesParameterSets, step_size::Float64, emax::typeof(0.0u"eV"))Perform a Monte Carlo random walk on the atomic/molecular system. Specialized for Lennard-Jones potentials.
Arguments
n_steps::Int: The number of Monte Carlo steps to perform.at::AtomWalker{C}: The walker to perform the random walk on.pot::LennardJonesParameterSets: The potential energy function for the system.step_size::Float64: The maximum distance an atom can move in any direction.emax::typeof(0.0u"eV"): The maximum energy allowed for accepting a move.
Returns
accept_this_walker::Bool: Whether the walker is accepted or not.accept_rate::Float64: The acceptance rate of the random walk.at::AtomWalker: The updated walker.
FreeBird.MonteCarloMoves.MC_random_walk! — Method
MC_random_walk!(n_steps::Int, lattice::LatticeWalker, h::ClassicalHamiltonian, emax::Float64; energy_perturb::Float64=0.0)Perform a Monte Carlo random walk on the lattice system.
Arguments
n_steps::Int: The number of Monte Carlo steps to perform.lattice::LatticeWalker: The walker to perform the random walk on.h::ClassicalHamiltonian: The lattice gas Hamiltonian.emax::Float64: The maximum energy allowed for accepting a move.energy_perturb::Float64=0.0: The energy perturbation used to make degenerate configurations distinguishable.
Returns
accept_this_walker::Bool: Whether the walker is accepted or not.accept_rate::Float64: The acceptance rate of the random walk.lattice::LatticeWalker: The updated walker.
FreeBird.MonteCarloMoves.MC_random_walk_2D! — Method
MC_random_walk_2D!(n_steps::Int, at::AtomWalker, pot::AbstractPotential, step_size::Float64, emax::typeof(0.0u"eV"); dims::Vector{Int}=[1,2])Perform a Monte Carlo random walk on the atomic/molecular system in 2D.
Arguments
n_steps::Int: The number of Monte Carlo steps to perform.at::AtomWalker{C}: The walker to perform the random walk on.pot::AbstractPotential: The potential energy function for the system.step_size::Float64: The maximum distance an atom can move in any direction.emax::typeof(0.0u"eV"): The maximum energy allowed for accepting a move.dims::Vector{Int}=[1,2]: The dimensions in which the random walk is performed.
Returns
accept_this_walker::Bool: Whether the walker is accepted or not.accept_rate::Float64: The acceptance rate of the random walk.at::AtomWalker: The updated walker.
FreeBird.MonteCarloMoves.MC_rejection_sampling! — Method
MC_rejection_sampling!(lattice::LatticeWalker, h::ClassicalHamiltonian, emax::Float64; energy_perturb::Float64=0.0, max_iter=10_000)Perform a Monte Carlo rejection sampling on the lattice system.
Arguments
lattice::LatticeWalker: The walker to perform the rejection sampling on.h::ClassicalHamiltonian: The Hamiltonian containing the on-site and nearest-neighbor interaction energies.emax::Float64: The maximum energy allowed for accepting a move.energy_perturb::Float64=0.0: The energy perturbation used to make degenerate configurations distinguishable.max_iter::Int=10_000: The maximum number of iterations to perform.
Returns
accept_this_walker::Bool: Whether the walker is accepted or not.lattice::LatticeWalker: The updated walker.
FreeBird.MonteCarloMoves._apply_cluster_pairs! — Method
_apply_cluster_pairs!(lattice::MLattice{C,G}, pairs::Vector{Tuple{Int,Int}}) where {C,G}Apply the occupancy exchange for each (site, reflected_site) pair with distinct indices, across all components. Each pair swap is an involution, so re-applying the same pair list reverts a cluster move exactly; the copy-free kernels use it as the revert path for rejected cluster proposals.
FreeBird.MonteCarloMoves._build_geometric_cluster — Method
_build_geometric_cluster(lattice, seed, reflect, p) -> Vector{Tuple{Int,Int}}Grow a geometric cluster from seed using BFS with fixed growth probability p, pairing each visited site with its image under the reflect closure (a self-inverse site-index map supplied by the geometry-specific caller). Returns a vector of (site, reflected_site) pairs.
FreeBird.MonteCarloMoves._gc_revert_move! — Method
_gc_revert_move!(config, move_type, hop_from, hop_to, cluster_pairs,
insert_site, deleted_site)Internal: revert a rejected in-place grand-canonical proposal. Swap and cluster proposals revert by involution replay (_lattice_walk_apply!, _apply_cluster_pairs!); insertion and deletion revert by flipping the recorded site back. No random draws.
FreeBird.MonteCarloMoves._grid_to_site — Method
_grid_to_site(gx::Int, gy::Int, gz::Int, Lx::Int, Ly::Int) -> IntConvert 0-indexed 3D grid coordinates to a 1-indexed site index.
FreeBird.MonteCarloMoves._lattice_walk_apply! — Method
_lattice_walk_apply!(lattice, hop_from, hop_to)Internal: apply the conditional occupancy exchange of the hop-pair walk for an already-drawn pair, with no random draws. Self-inverse for every case (the empty/occupied exchange, the cross-component exchange, and the no-op), so a second call with the same pair reverts the first.
FreeBird.MonteCarloMoves._lattice_walk_draw! — Method
_lattice_walk_draw!(lattice) -> (hop_from, hop_to)Internal: perform one hop-pair walk step with exactly the draws of lattice_random_walk!, in the same order, returning the drawn pair so the copy-free kernels can revert a rejected proposal. The conditional exchange applied for a drawn pair is an involution, so replaying the pair through _lattice_walk_apply! reverts the step exactly.
FreeBird.MonteCarloMoves._reflect_site — Method
_reflect_site(site::Int, pivot_gx::Int, pivot_gy::Int, Lx::Int, Ly::Int, Lz::Int) -> IntCompute the point inversion of site through the pivot at grid coordinates (pivot_gx, pivot_gy) with periodic wrapping in x and y. The z-coordinate is preserved (no reflection in the non-periodic z direction).
FreeBird.MonteCarloMoves._site_to_grid — Method
_site_to_grid(site::Int, Lx::Int, Ly::Int) -> Tuple{Int,Int,Int}Convert a 1-indexed site index to 0-indexed 3D grid coordinates (gx, gy, gz) for a single-basis square lattice. Site ordering: x varies fastest, then y, then z.
FreeBird.MonteCarloMoves._tri_halfgrid_to_site — Method
_tri_halfgrid_to_site(hx::Int, hy::Int, nx::Int) -> IntInverse of _tri_site_to_halfgrid for in-range half-grid coordinates with hx ≡ hy (mod 2).
FreeBird.MonteCarloMoves._tri_reflect_site — Method
_tri_reflect_site(site::Int, hpx::Int, hpy::Int, nx::Int, ny::Int) -> IntPoint inversion of site through the pivot whose doubled half-grid position is (hpx, hpy) = h(s₁) + h(s₂) for two pivot sites s₁, s₂, with periodic wrapping: σ(h) = (hpx, hpy) − h mod (2·nx, 2·ny). Both pivot sites satisfy hx ≡ hy (mod 2), so hpx ≡ hpy (mod 2) and σ preserves the parity difference — the reflected point is always a site. Site pivots (s₁ = s₂, hpx even) preserve each site's basis index; midpoint pivots with hpx odd exchange the two basis sublattices. σ is an involution: σ(σ(h)) = h.
FreeBird.MonteCarloMoves._tri_site_to_halfgrid — Method
_tri_site_to_halfgrid(site::Int, nx::Int) -> Tuple{Int,Int}Half-grid coordinates (hx, hy) = (2·ci + b, 2·cj + b) of a site on the two-site-basis triangular lattice, in units of a/2 and √3·a/2, where b = basis index and (ci, cj) the 0-indexed cell. Under the standard site ordering (basis innermost, dimension 1 next), the site set is exactly {(hx, hy) : hx ≡ hy (mod 2)} on the (2·nx, 2·ny) torus — the centered-rectangular condition.
FreeBird.MonteCarloMoves.continuous_cavity_cells — Method
continuous_cavity_cells(config::AbstractSystem, box, grid::Int, r_cavity::Float64;
skip::Int=0)The cavity cells of a continuous configuration: the sorted linear indices (of the grid³ overlay, column-major) of cells whose centers clear the minimum-image distance test r ≥ r_cavity against every particle. skip excludes one particle index, evaluating the post-deletion cavity set without mutating (the deletion channel's mutate-nothing-until-accepted convention). The indicator is a deterministic function of the configuration, evaluated identically in the biased draw, the forward proposal density, and the reverse density; a stochastic cavity-volume estimate has no Metropolis-Hastings exactness result and is deliberately not offered. Marks cells by particle, O(grid³ + N (r_cavity/h)³) with h the cell edge.
FreeBird.MonteCarloMoves.free_component_index — Method
free_component_index(at::AtomWalker{C}) where CGet the indices of the free particles in each component of the AtomWalker.
Returns
ind_free_parts::Array{Vector{Int}}: An array of vectors containing the indices of the free particles in each component.
FreeBird.MonteCarloMoves.free_par_index — Method
free_par_index(at::AtomWalker{C}) where CGet the indices of the free particles in the AtomWalker.
FreeBird.MonteCarloMoves.gc_insert_acceptance_ratio — Method
gc_insert_acceptance_ratio(z0V::Float64, n::Int, p_insert::Float64, p_delete::Float64)
gc_delete_acceptance_ratio(z0V::Float64, n::Int, p_insert::Float64, p_delete::Float64)Metropolis acceptance ratios for the continuous-space grand-canonical kernel, with n the PRE-move particle count in both directions. z0V is the dimensionless product of the reference activity (dimension inverse volume) and the cell volume. The insertion ratio is the proposal-density form z0 * pdelete / ((n + 1) * pinsert * q(r)) with the uniform channel's q = 1/V folded in, so the shipped arithmetic is literally z0V * (pdelete / pinsert) / (n + 1); a future biased-insertion channel enters by evaluating a different proposal density q in place of the folded 1/V, mirroring the composite-density pattern of the lattice kernel above.
FreeBird.MonteCarloMoves.generate_random_new_lattice_sample! — Method
generate_random_new_lattice_sample!(lattice::SLattice)Generate a new random sample for the single-component lattice system.
FreeBird.MonteCarloMoves.generate_random_new_lattice_sample! — Method
generate_random_new_lattice_sample!(lattice::MLattice{C}) where CGenerate a new random sample for the multi-component lattice system.
Arguments
lattice::MLattice{C}: The lattice system to generate a new sample for.
Returns
lattice::MLattice{C}: The updated lattice system.
FreeBird.MonteCarloMoves.geometric_cluster_swap! — Method
geometric_cluster_swap!(lattice::MLattice{C,GenericLattice}, p::Float64)Guard method: geometric cluster moves are defined only for the square and triangular geometries, whose reflection maps are integer grid involutions on the site indices; a GenericLattice carries no such map, so this method always throws a descriptive ArgumentError before drawing any randomness. Use swap-only decorrelation (clusters_freq = 0) for generic geometries.
FreeBird.MonteCarloMoves.geometric_cluster_swap! — Method
geometric_cluster_swap!(lattice::MLattice{C,SquareLattice}, p::Float64) where CPerform a geometric cluster move on a square lattice by point inversion through a random pivot.
A random pivot site and seed site are chosen on the periodic lattice. A cluster of sites is grown from the seed via BFS, adding first-shell neighbors with fixed probability p (independent of the configuration). Each site in the cluster is paired with its reflection through the pivot, and the occupation states of each pair are swapped across all components.
Because cluster growth does not depend on the occupancy field, the proposal is symmetric: P(cluster | configA) = P(cluster | configB). This means no Metropolis correction is needed; in nested sampling, one simply checks Eproposed < Emax.
The parameter p controls the average cluster size: p ≈ 0 gives single-site moves, p → 1 gives lattice-spanning clusters.
Arguments
lattice::MLattice{C,SquareLattice}: The lattice to perform the cluster move on.p::Float64: Growth probability for BFS cluster construction (0 < p < 1).record::Union{Nothing,Vector{Tuple{Int,Int}}}=nothing: When a vector is supplied, every applied (site, reflected_site) pair is appended to it; re-applying the recorded pairs (each pair swap is an involution) reverts the move exactly. Thenothingdefault changes no behavior and no random-number draw.
Returns
lattice::MLattice{C,SquareLattice}: The mutated lattice after the cluster swap.
Notes
- Preserves per-component particle counts exactly.
- The move is self-inverse for a fixed cluster: applying the same cluster swap twice restores the original configuration.
- Supports 2D (
supercell_dimensions[3] == 1) and 3D lattices. In 3D, the reflection operates in the periodic xy-plane; the z-coordinate is preserved. - Requires the single-site basis (the site-index reflection assumes single-basis, x-fastest ordering); a multi-site basis throws an
ArgumentError.
References
- Heringa & Blöte, Phys. Rev. E 57, 4976 (1998) — geometric cluster MC framework.
- Adaptation uses fixed growth probability (configuration-independent) for symmetric proposals.
FreeBird.MonteCarloMoves.geometric_cluster_swap! — Method
geometric_cluster_swap!(lattice::MLattice{C,TriangularLattice}, p::Float64) where CGeometric cluster move on the two-site-basis triangular lattice by point inversion through a random centrosymmetry center.
The pivot is the midpoint of two random sites drawn with replacement, which covers exactly the two families of inversion centers of the triangular lattice (sites and half-lattice midpoints) and can never produce an invalid pivot: plaquette centers, whose doubled position is not a lattice vector, are unreachable by construction. The reflection runs in integer half-grid coordinates ((hx, hy) = (2·ci + b, 2·cj + b) on the (2·nx, 2·ny) torus), so no floating-point rounding or lookup table is involved. Cluster growth and the pair swap are shared with the square method via _build_geometric_cluster.
Detailed balance holds exactly as in the square case: the reflection is an involution on site indices, cluster growth is configuration-independent, and the swap is symmetric, so the proposal needs no Metropolis correction and nested sampling keeps its bare energy-ceiling accept test (Heringa & Blöte, Phys. Rev. E 57, 4976 (1998)).
Requires the two-site basis and a strictly two-dimensional supercell (supercell_dimensions[3] == 1); violations throw an ArgumentError.
FreeBird.MonteCarloMoves.lattice_biased_sites — Method
lattice_biased_sites(lattice::SLattice; predicate::Symbol=:contact, shells::Int=1)Return the indices of empty sites selected by an occupancy predicate over neighbor shells 1:shells:
:contact: empty sites with at least one occupied neighbor.:cavity: empty sites with no occupied neighbor.
For fixed shells the two predicates partition the empty sites: length(contact set) + length(cavity set) == M - N. Neighbor lists carrying periodic-image multiplicity (the same neighbor listed more than once) work as-is: any occupied appearance marks contact.
Useful as a nested-sampling observable, e.g. :n_cavity => cfg -> length(lattice_biased_sites(cfg; predicate=:cavity)).
Throws ArgumentError for an unknown predicate, shells < 1, or shells exceeding the lattice's neighbor-shell count.
FreeBird.MonteCarloMoves.lattice_delete_particle! — Method
lattice_delete_particle!(lattice::SLattice)Delete a particle from a random occupied site. Returns true if successful, false if the lattice is empty.
Arguments
lattice::SLattice: The single-component lattice.
Returns
success::Bool: Whether a particle was deleted.lattice::SLattice: The mutated lattice.site::Int: The vacated site index (0 when unsuccessful). A trailing addition: two-name destructures of the previous return keep working.
FreeBird.MonteCarloMoves.lattice_insert_particle! — Method
lattice_insert_particle!(lattice::SLattice)Insert a particle at a random empty site. Returns true if successful, false if the lattice is full.
Arguments
lattice::SLattice: The single-component lattice.
Returns
success::Bool: Whether a particle was inserted.lattice::SLattice: The mutated lattice.site::Int: The inserted site index (0 when unsuccessful). A trailing addition: two-name destructures of the previous return keep working.
FreeBird.MonteCarloMoves.lattice_random_walk! — Method
lattice_random_walk!(lattice::SLattice)Perform a Monte Carlo random walk on the single-component lattice system.
Arguments
lattice::SLattice: The single-component lattice system to perform the random walk on.
Returns
lattice::SLattice: The proposed lattice after the random walk.
FreeBird.MonteCarloMoves.lattice_random_walk! — Method
lattice_random_walk!(lattice::MLattice{C,G}) where {C,G}Perform a Monte Carlo random walk on the multi-component lattice system.
Arguments
lattice::MLattice{C,G}: The multi-component lattice system to perform the random walk on.
Returns
lattice::MLattice{C,G}: The proposed lattice after the random walk.
FreeBird.MonteCarloMoves.mean_sq_displacement — Method
mean_sq_displacement(at::AtomWalker, at_orig::AtomWalker)Calculate the mean squared displacement before and after random walk(s). Note that due to the current implementation of the periodic boundary wrap, this function is not appropriate to use for calculating mean displacements in a propagation.
Arguments
at::AtomWalker{C}: The currentAtomWalkerafter the random walk.at_orig::AtomWalker{C}: The originalAtomWalkerbefore the random walk.
Returns
distsq::typeof(0.0u"Å"^2): The mean squared displacement of all free particles.
FreeBird.MonteCarloMoves.periodic_boundary_wrap! — Method
periodic_boundary_wrap!(pos::SVector{3,T}, system::AbstractSystem) where TWrap the position vector pos according to the periodic boundary conditions of the system. If the boundary condition is Periodic(), the position is wrapped using the modulo operator. If the boundary condition is DirichletZero(), the position is wrapped by reflecting the position vector across the boundary.
Arguments
pos::SVector{3,T}: The position vector to be wrapped.system::AbstractSystem: The system containing the periodic boundary conditions.
Returns
The wrapped position vector.
FreeBird.MonteCarloMoves.random_microstate! — Method
random_microstate!(lattice::SLattice; p::Float64=0.5)Set each site occupied independently with probability p, producing a variable-N configuration suitable for grand-canonical sampling.
Arguments
lattice::SLattice: The single-component lattice to randomize.p::Float64=0.5: Per-site occupation probability.
Returns
lattice::SLattice: The mutated lattice with a random microstate.
FreeBird.MonteCarloMoves.single_atom_random_walk! — Method
single_atom_random_walk!(at::AtomWalker, pot::AbstractPotential, step_size::Float64)Perform a single atom random walk on the AtomWalker object at using the potential pot and a specified step_size.
Arguments
at::AtomWalker{C}: The walker to perform the random walk on.pot::AbstractPotential: The potential energy function for the system.step_size::Float64: The maximum distance an atom can move in any direction.
Returns
at::AtomWalker: The updated walker after the random walk.
FreeBird.MonteCarloMoves.single_atom_random_walk! — Method
single_atom_random_walk!(pos::SVector{3,T}, step_size::Float64) where TPerform a single atom random walk by updating the position pos in each direction by a random amount. The step_size determines the maximum distance the atom can move in any direction.
Arguments
pos::SVector{3,T}: The current position of the atom as a 3D vector.step_size::Float64: The maximum distance the atom can move in any direction.
Returns
pos: The updated position of the atom.
FreeBird.MonteCarloMoves.swap_empty_occupied_sites! — Method
swap_empty_occupied_sites!(lattice::MLattice{C,G}, hop_from::Int, hop_to::Int) where {C,G}Swap the occupation state of two sites in the lattice of any component.
Arguments
lattice::MLattice{C,G}: The lattice to perform the swap on.hop_from::Int: The index of the site to hop from.hop_to::Int: The index of the site to hop to.
Returns
lattice::MLattice{C,G}: The updated lattice after the swap.
FreeBird.MonteCarloMoves.swap_occupied_sites_across_components! — Method
swap_occupied_sites_across_components!(lattice::MLattice{C,G}, hop_from::Int, hop_to::Int) where {C,G}Swap the occupation state of two sites across different components in the lattice.
Arguments
lattice::MLattice{C,G}: The lattice to perform the swap on.hop_from::Int: The index of the site to hop from.hop_to::Int: The index of the site to hop to.
Returns
lattice::MLattice{C,G}: The updated lattice after the swap.
FreeBird.MonteCarloMoves.two_atoms_swap! — Method
two_atoms_swap!(at::AtomWalker{C}, ind1, ind2) where CSwap the positions of two atoms in the AtomWalker.
Arguments
at::AtomWalker{C}: TheAtomWalkerobject.ind1::Int: The index of the first atom.ind2::Int: The index of the second atom.
Returns
at::AtomWalker{C}: The updatedAtomWalker.