numerics 0.1.0
Loading...
Searching...
No Matches
PBCLattice2D

include/spatial/pbc_lattice.hpp provides num::PBCLattice2D, a small struct that precomputes the four periodic-boundary neighbor index arrays for an \(N \times N\) square lattice.


Motivation

Any 2D simulation on a periodic lattice (Ising, lattice-gas, MD) needs to look up the four neighbors of each site without calling the modulo operator in the hot path. This pattern appeared verbatim in the Ising app as a private build_neighbor_arrays() method with four std::vector<int> members (up, dn, lt, rt).

PBCLattice2D extracts the construction and encapsulates the four arrays.


API

int N;
std::vector<int> up, dn, lt, rt; // N*N each
explicit PBCLattice2D(int N);
};
4-neighbor periodic-boundary index arrays for an NxN lattice.
std::vector< int > up
std::vector< int > dn
std::vector< int > rt
up/dn = row +/-1, lt/rt = col +/-1 (PBC)
int N
Side length; total sites = N*N.
std::vector< int > lt

Construction is \(O(N^2)\) and done once; subsequent lookups are direct array reads.


Index Layout

Flat row-major layout: site \((row, col)\) has flat index \(i = row \cdot N + col\).

\[ \texttt{up}[i] = ((row - 1 + N) \bmod N) \cdot N + col \]

\[ \texttt{dn}[i] = ((row + 1) \bmod N) \cdot N + col \]

\[ \texttt{lt}[i] = row \cdot N + (col - 1 + N) \bmod N \]

\[ \texttt{rt}[i] = row \cdot N + (col + 1) \bmod N \]


Usage

// Metropolis sweep -- neighbor sum with no modulo arithmetic
real ns = spins[nbr.up[i]] + spins[nbr.dn[i]]
+ spins[nbr.lt[i]] + spins[nbr.rt[i]];
// BFS cluster detection
[&](int i) { return spins[i] < 0.0; },
[&](int i, auto&& visit) {
visit(nbr.up[i]); visit(nbr.dn[i]);
visit(nbr.lt[i]); visit(nbr.rt[i]);
});
ClusterResult connected_components(int n_sites, InCluster &&in_cluster, Neighbors &&neighbors)

Used by: Ising IsingLattice::sweep, IsingLattice::sweep_umbrella.