LatticeCore API

Lattice2D builds on LatticeCore.jl, which defines the abstract lattice vocabulary (the AbstractLattice hierarchy, Bond, boundary-condition singletons, indexing strategies, site types, …). These symbols are re-exported by Lattice2D, so using Lattice2D alone is enough to reach them.

They are documented here so that the @ref cross-references inside Lattice2D docstrings resolve to a real target (see issue #68).

LatticeCore.AbstractAxisBCType
AbstractAxisBC

Abstract supertype for per-axis boundary conditions. Concrete subtypes decide how a raw candidate cell index is wrapped into the lattice's index range along a single axis.

Subtypes:

  • PeriodicAxis — wraps via mod1
  • OpenAxis — rejects out-of-range indices
  • TwistedAxis — wraps like PeriodicAxis but attaches a phase factor to bonds that cross the boundary
source
LatticeCore.AbstractBoundaryConditionType
AbstractBoundaryCondition

Abstract supertype for lattice boundary conditions.

The canonical concrete type is LatticeBoundary, which composes:

The split is deliberate: an axis BC decides whether a candidate bond exists (and whether it carries a twist phase), while a modifier only reweights existing bonds (e.g. sine-square deformation). Multiple concerns are composed, not shoehorned into a single taxonomy.

See dev/note/04_architecture/03_boundary_and_coordinates/README.md for the design rationale.

source
LatticeCore.AbstractBoundaryModifierType
AbstractBoundaryModifier

Abstract supertype for boundary modifiers. A modifier does not change which bonds exist — it only reweights existing bonds through bond_weight. Examples: NoModifier, SSD.

Extending

Downstream packages may define their own modifier types by subtyping AbstractBoundaryModifier and overloading

bond_weight(::MyModifier, lat::AbstractLattice, i::Int, j::Int)::Float64

The two-argument default bond_weight(modifier, lat) may also be overloaded if a modifier wants to broadcast a single scalar over the whole lattice. AbstractBoundaryModifier and the concrete NoModifier / SSD types are part of the public exported API of LatticeCore precisely so downstream code can extend them.

source
LatticeCore.AbstractCoordinateType
AbstractCoordinate{D}

Abstract supertype for lattice coordinate representations. Concrete subtypes describe the same lattice point in different spaces:

D is the physical dimension (the dimension of the real space the lattice lives in), which is the same for every concrete subtype that describes a given lattice point.

Conversions between coordinate systems are performed by to_real, to_lattice, and to_hyper. These functions dispatch on the concrete lattice type because the conversion depends on the lattice basis and any higher-dimensional projection the lattice uses.

source
LatticeCore.AbstractIndexingType
AbstractIndexing

Abstract supertype for strategies that linearise a LatticeCoord into a 1-based site index. Concrete subtypes determine the ordering of sites along axes and the placement of sublattices within each cell.

The indexing method is deliberately decoupled from the coordinate system: a lattice may switch its AbstractIndexing without changing how it describes positions. See dev/note/04_architecture/03_boundary_and_coordinates/README.md for the design rationale.

Required interface (per concrete indexing / dimension)

  • site_index(indexing, dims::NTuple{D, Int}, nsub::Int, coord::LatticeCoord{D})::Int
  • lattice_coord(indexing, dims::NTuple{D, Int}, nsub::Int, i::Int)::LatticeCoord{D}

These two methods must round-trip: site_index ∘ lattice_coord is the identity on 1:prod(dims) * nsub.

Sublattice convention

The sublattice is the innermost (fastest) index: sites within a single cell are contiguous. For nsub == 1 this reduces to the usual single-sublattice formulas and can be read at a glance.

source
LatticeCore.AbstractLatticeType
AbstractLattice{D, T}

Abstract supertype for lattice types. Type parameters:

  • D: spatial dimension (integer literal)
  • T: numeric type for real-space positions (typically Float64)

Required interface (concrete subtypes must implement)

  • position(lat, i)::SVector{D, T}
  • neighbors(lat, i) — iterable of neighbor site indices
  • boundary(lat) — returns an AbstractBoundaryCondition
  • size_trait(lat)::AbstractSizeTrait
  • num_sites(lat)::Int — required for FiniteSize / QuasiInfiniteSize lattices; InfiniteSize lattices should throw DomainError.

Optional interface (defaults provided)

  • positions(lat) — defaults to an iterator built from position
  • bonds(lat) — defaults to an iterator built from neighbors
  • neighbor_bonds(lat, i) — defaults to an iterator built from neighbors
  • topology(lat)TopologyTrait{:unknown}()
  • periodicity(lat)Aperiodic()
  • is_bipartite(lat)false
  • reciprocal_support(lat)NoReciprocal()
  • is_finite(lat) — derived from size_trait

See dev/note/04_architecture/02_lattice_interface/README.md for the design rationale.

source
LatticeCore.AbstractLatticeElementType
AbstractLatticeElement

Abstract supertype identifying which geometric element of a lattice a given degree of freedom lives on. The default for every AbstractSiteType is VertexCenter; other element_type overrides let the interface describe bond / plaquette / cell-centered variables such as dimers, gauge links, and flux variables without breaking existing site-centered code.

See dev/note/04_architecture/04_site_type/README.md for the two-approach strategy (line-graph versus multi-layer) that uses this trait.

source
LatticeCore.AbstractMomentumLatticeType
AbstractMomentumLattice{D, T} <: AbstractLattice{D, T}

Abstract supertype for k-space lattices. A momentum lattice is itself an AbstractLattice — its "sites" are k-points, its "positions" are k-vectors in the reciprocal basis — so 02's lattice interface (num_sites, position, traits, test suite) can be re-used for k-space work. See dev/note/04_architecture/05_momentum_space.

Required interface for concrete subtypes

  • num_k_points(ml)::Int
  • k_point(ml, i::Int)::SVector{D, T}
  • reciprocal_basis(ml)::SMatrix{D, D, T}

The graph-neighbour side of AbstractLattice (neighbors, bonds) is deliberately vacuous for momentum lattices: k-space is not a graph in the same sense. Concrete momentum lattices return an empty neighbour list; MC code should never walk them as a graph.

source
LatticeCore.AbstractSiteLayoutType
AbstractSiteLayout

Abstract supertype for strategies that store the per-site AbstractSiteType of a lattice. Three concrete layouts are provided, each picking a different memory / flexibility trade-off:

  • UniformLayout — every site shares the same site type (stored once; zero per-site memory overhead)
  • SublatticeLayout — each geometric sublattice has its own site type (Vector{Int} of sublattice ids)
  • ExplicitLayout — one AbstractSiteType per site (for disordered / quenched-random configurations)

All layouts satisfy site_type(layout, i)::AbstractSiteType.

source
LatticeCore.AbstractSiteTypeType
AbstractSiteType

Abstract supertype for site types — value-level descriptors of the physical degree of freedom living on a lattice site.

Concrete subtypes are deliberately lightweight (typically singletons or thin parametric singletons) so they can be embedded in lattice structs and used as a dispatch key by MC models.

Required interface

  • state_type(st)::Type — the Julia type used to store a state
  • random_state(rng, st) — sample a uniformly random state

Optional interface

  • zero_state(st) — a canonical zero state (if defined)
  • domain(st) — iterable over the state space (for small discrete site types)
  • element_type(st)::AbstractLatticeElement — which geometric element the DOF lives on. Defaults to VertexCenter. Override for bond / plaquette-centered variables such as dimer or gauge fields.

See dev/note/04_architecture/04_site_type/README.md.

source
LatticeCore.AbstractSizeTraitType
AbstractSizeTrait

Trait describing whether a lattice has a finite, infinite, or finitely-materializable-but-conceptually-infinite extent.

Subtypes:

  • FiniteSize: ordinary finite lattice.
  • InfiniteSize: true infinite lattice (used for analytic/spectral work; MC is not applicable).
  • QuasiInfiniteSize: conceptually infinite but materialized up to a cutoff (e.g. Penrose radius, Fibonacci depth).
source
LatticeCore.AcceptanceWindowType
AcceptanceWindow

Abstract supertype for acceptance windows in the internal (perp) space of a cut-and-project quasicrystal. Concrete windows (PolygonalWindow, IntervalWindow, etc.) live in QuasiCrystal.jl.

source
LatticeCore.BondType
Bond{D, T}

A bond (edge) connecting two sites of a lattice.

Fields

  • i::Int — source site index
  • j::Int — target site index
  • vector::SVector{D, T} — displacement position(j) - position(i), wrapped by the lattice's boundary condition if applicable
  • type::Symbol — bond type tag (e.g. :nearest, :next_nearest, :dimer_strong). Used as a dispatch key by anisotropic models (see the 07 MC layer design note).
source
LatticeCore.BraggPeakSetType
BraggPeakSet{DPhys, T}

Finite materialisation of a HyperReciprocalLattice up to a cutoff radius: a list of physical-space k-positions with intensities and a back-pointer to the higher-dimensional indices that generated them.

Being a subtype of AbstractMomentumLattice, a BraggPeakSet can be passed straight to structure_factor or to a StructureFactorObserver so the same code paths work for periodic and quasiperiodic lattices.

source
LatticeCore.CellBondType
CellBond{D}(src::Int, dst::Int, offset::SVector{D, Int}, type::Symbol)

A bond of the unit-cell motif. It connects basis site src in the home cell to basis site dst in the cell displaced by offset (target cell = home cell + offset). type is a dispatch tag (e.g. :nearest).

By convention, each undirected bond of the lattice should appear exactly once in the motif returned by cell_bonds — this is the implementer's responsibility and is not validated. Listing a bond twice (e.g. both (1, 1, (1, 0)) and (1, 1, (-1, 0))) would double-count neighbours. The lazy accessor incident_cell_bonds re-anchors motif bonds to a requested site, orienting them outward from that site.

source
LatticeCore.CellSiteType
CellSite{D}(cell::SVector{D, Int}, basis::Int)

A single site of a translationally invariant lattice, addressed by its unit-cell coordinate cell ∈ ℤ^D and its basis index basis within the cell. This is the site identity used by the lazy accessors (neighbors_at, cell_position) — an infinite lattice has no linear 1:num_sites index, so sites are named by coordinate instead.

source
LatticeCore.EmptySiteType
EmptySite()

Vacancy / empty site: stores nothing. Useful for diluted models and as a placeholder where a site has no degrees of freedom.

source
LatticeCore.ExplicitLayoutType
ExplicitLayout(types::Vector{<:AbstractSiteType})

One site type per site. Use for quenched disorder or any configuration where the per-site type cannot be factored through a sublattice assignment.

source
LatticeCore.FiniteSizeType
FiniteSize{D}(dims::NTuple{D, Int})

Size trait for an ordinary finite lattice with the given per-axis cell counts.

source
LatticeCore.HeisenbergSiteType
HeisenbergSite{T <: AbstractFloat}()

Classical Heisenberg spin: state is a unit vector in ℝ³ stored as SVector{3, T} (default Float64).

source
LatticeCore.HigherDimCoordType
HigherDimCoord{DPhys, DHyper, T}(hyper::SVector{DHyper, T})

Higher-dimensional coordinate used by cut-and-project quasicrystals. DPhys is the physical dimension (the target of the projection) and DHyper is the host dimension (DHyper > DPhys). The lattice's projection matrix maps hyper back into DPhys-dimensional real space.

source
LatticeCore.HyperReciprocalLatticeType
HyperReciprocalLattice{DPhys, DHyper, T}

Infinite-abstract representation of a quasicrystal's reciprocal structure: the higher-dimensional reciprocal basis, the parallel and perpendicular projections, and the acceptance window used to decide peak intensities.

Concrete construction (building the projections, sampling peaks) lives in QuasiCrystal.jl.

source
LatticeCore.InfiniteSizeType
InfiniteSize()

Size trait for a true infinite lattice. MC cannot run on such a lattice; spectral / analytic calculations only.

source
LatticeCore.InfiniteSquareLatticeType
InfiniteSquareLattice{T, L <: AbstractSiteLayout}(; layout)

A truly infinite 2D square lattice with unit spacing — the thermodynamic-limit counterpart of SimpleSquareLattice under periodic boundary conditions.

It carries no size: size_trait is InfiniteSize and num_sites throws. It is not meant to be walked with the linear 1:num_sites site API. Instead it is described by its unit-cell motif and accessed lazily:

This is the substrate for building an infinite tensor network (e.g. the Ising partition function in the thermodynamic limit): place one tensor per site orbit and one per bond orbit, then contract along the motif.

Bridge to a finite lattice

If a finite approximation is ever needed, materialize tiles the motif into a periodic SimpleSquareLattice:

inf = InfiniteSquareLattice()
fin = materialize(inf; dims = (8, 8))   # 8×8 PBC SimpleSquareLattice

but the lazy accessors above never require this step.

Examples

inf = InfiniteSquareLattice()
site_orbits(inf)                       # 1:1  (one basis site)
collect(bond_orbits(inf))              # +x and +y CellBonds
s = CellSite((3, -2))                  # cell (3, -2), basis 1
cell_position(inf, s)                  # SVector(3.0, -2.0)
neighbors_at(inf, s)                   # the four nearest neighbours
source
LatticeCore.LatticeBoundaryType
LatticeBoundary{N, A, M}(axes::NTuple{N, <:AbstractAxisBC}, modifier)

Composite boundary condition for an N-dimensional lattice. Stores one AbstractAxisBC per axis plus a single AbstractBoundaryModifier. Supports mixed-axis boundary conditions natively — a cylinder is

LatticeBoundary((PeriodicAxis(), OpenAxis()))

The zero-modifier form is the default.

source
LatticeCore.LatticeCoordType
LatticeCoord{D}(cell::NTuple{D, Int}, sublattice::Int = 1)

Lattice coordinate: per-axis unit cell index plus the (1-based) geometric sublattice id within the cell.

The sublattice field refers strictly to the geometric sublattice (the honeycomb A/B positions, the Kagome A/B/C, ...), not to the physical AbstractSiteType living on the site. Site types live on a separate axis and are designed in the site-type chapter of the architecture notes.

source
LatticeCore.LineLatticeType
LineLattice{T, B, L}(N, boundary, layout)

A 1D linear chain of N sites with unit spacing.

LatticeCore's simplest reference implementation; paired with SimpleSquareLattice it is also the canonical mock used by downstream Monte Carlo unit tests.

Examples

# Default: PBC + UniformLayout(IsingSite())
line = LineLattice(5)

# Open boundary chain
chain = LineLattice(5, OpenAxis())

# Custom layout (e.g. XY sites)
xy = LineLattice(5; layout = UniformLayout(XYSite()))
source
LatticeCore.LinearScalingType
LinearScaling(factor::Int)

Trait: one scale step multiplies every per-axis cell count by factor. The ordinary Bravais case.

source
LatticeCore.PlaquetteType
Plaquette{D, T}

A plaquette (face) on a concrete lattice, materialised from a PlaquetteRule.

Fields

  • vertices::Vector{Int} — 1-based site indices of the boundary vertices, in cyclic order
  • center::SVector{D, T} — real-space centroid
  • type::Symbol — tag inherited from the rule

Obtained via plaquettes(lat) / neighbor_plaquettes(lat, i) / element_position(lat, PlaquetteCenter(), p) or the generic element-center API.

source
LatticeCore.PlaquetteRuleType
PlaquetteRule

Declarative description of a plaquette shape anchored in a unit cell, used as the input to the per-sample plaquette enumeration. A concrete topology stores one PlaquetteRule per plaquette kind (e.g. Square has one rule, Triangular has two — up-triangle and down-triangle, Kagome has three — up-triangle, down-triangle, hexagon).

Fields

  • corners::Vector{NTuple{3, Int}} — the boundary vertices of the plaquette in cyclic order, each expressed as (sublattice_id, dx, dy). sublattice_id is the 1-based sublattice index within the unit cell; (dx, dy) is the cell offset relative to the anchor cell. Every rule must include at least one corner at (_, 0, 0) (the anchor).
  • type::Symbol — bond-type-like tag for downstream dispatch (:square, :up_triangle, :down_triangle, :hexagon, …).

Example

# Unit square on a single-sublattice square lattice:
square_rule = PlaquetteRule(
    [(1, 0, 0), (1, 1, 0), (1, 1, 1), (1, 0, 1)],
    :square,
)

Mirrors the Connection / Bond pattern: PlaquetteRule is the topology-level template, Plaquette is the per-sample materialised value produced by applying the rule under a boundary condition.

source
LatticeCore.QuasiInfiniteSizeType
QuasiInfiniteSize{T}(cutoff::T)

Size trait for a conceptually infinite lattice that has been (or will be) materialized up to a finite cutoff. The cutoff may represent a radius, a substitution depth, or any other scale parameter native to the lattice family.

source
LatticeCore.RealSpaceType
RealSpace{D, T}(x::SVector{D, T})
RealSpace(x::NTuple{D, T})

Real-space Cartesian coordinate in D dimensions with element type T.

source
LatticeCore.SSDType
SSD(L)

Sine-square deformation modifier. L is a characteristic scale carried by the modifier; the canonical bond weight evaluation (bond_weight(::SSD, lat, i, j)) reads the per-axis lengths of the lattice from size_trait instead, so L is informational under finite, fully-specified geometries. It is retained for downstream packages that may want to override the default with an alternative scale (e.g. infinite-system extrapolations).

Canonical envelope

For a D-dimensional finite lattice with per-axis cell counts (L_1, …, L_D), the SSD envelope evaluated at a lattice cell with 1-based per-axis coordinate cx_d ∈ 1:L_d is

\[f(\mathbf{r}) = \prod_{d=1}^{D} \sin^{2}\!\left( \pi \, \frac{c_{x,d} - 1/2}{L_d} \right),\]

equivalent to the standard $\sin^2(\pi (i + 1/2) / L)$ on 0-indexed sites. The bond weight between sites i, j is the arithmetic mean of the two endpoint envelopes, $w(i, j) = (f(\mathbf{r}_i) + f(\mathbf{r}_j)) / 2$.

SSD is exported so downstream MC / TN packages can construct boundaries with SSD weighting and dispatch on the type. Custom deformations should subtype AbstractBoundaryModifier rather than re-using SSD.

source
LatticeCore.SimpleSquareLatticeType
SimpleSquareLattice{T, B <: LatticeBoundary}(Lx, Ly, boundary)

A 2D square lattice of Lx × Ly sites with unit spacing. boundary is a LatticeBoundary whose two axis components independently select between PeriodicAxis, OpenAxis, and TwistedAxis — so mixed BCs (e.g. cylinders) are supported natively.

LatticeCore's 2D reference implementation. It exists so that the core interface can be exercised end-to-end without depending on Lattice2D.jl. The production-grade 2D lattice, with the full topology catalogue (triangular, honeycomb, kagome, ...), sublattice site types, and reciprocal-lattice machinery, lives in Lattice2D.jl.

Site indexing

Sites are laid out in row-major order:

site_index(x, y) = (y - 1) * Lx + x     # 1 <= x <= Lx, 1 <= y <= Ly

so sites 1..Lx form the bottom row, Lx+1..2Lx the next, and so on.

Examples

# Default: 2D PBC
sq = SimpleSquareLattice(3, 3)

# Uniform open boundary
open_sq = SimpleSquareLattice(3, 3, OpenAxis())

# Cylinder: periodic in x, open in y
cylinder = SimpleSquareLattice(3, 3, LatticeBoundary((PeriodicAxis(), OpenAxis())))
source
LatticeCore.SnakeType
Snake

Boustrophedon (snake) indexing: row-major layout with alternating row direction. Useful when physical adjacency between neighbouring indices matters (e.g. for certain serialisation layouts).

source
LatticeCore.SublatticeLayoutType
SublatticeLayout(by_sublattice::NTuple{N, <:AbstractSiteType}, sublattice_of::Vector{Int})

Per-sublattice site type. by_sublattice is a tuple of site type instances, one per geometric sublattice; sublattice_of[i] tells which sublattice site i belongs to (1-based).

This is the natural layout for mixed-spin models (e.g. Ising on the A sublattice, XY on B).

Ownership / mutability contract

SublatticeLayout stores the sublattice_of::Vector{Int} argument by reference, not by copy. The caller MUST treat the vector as immutable for the lifetime of the SublatticeLayout: mutating it (push!, setindex!, resize!, etc.) after construction will silently corrupt site-type lookups, since site_type(layout, i) indexes directly into this storage.

If the caller wants to keep a mutable copy of the assignment, it should pass copy(sublattice_of) to the constructor explicitly. A future release may switch the field to a read-only container (e.g. an NTuple{M,Int} or a wrapper); doing so would be a breaking change and is tracked separately.

source
LatticeCore.SubstitutionScalingType
SubstitutionScaling(depth_step::Int = 1)

Trait: one scale step advances a substitution/inflation rule by depth_step. The aperiodic case — the sequence of admissible sizes is dictated by the rule (Fibonacci lengths, inflation radii, …) rather than by an integer side length.

source
LatticeCore.TopologyTraitType
TopologyTrait{Name}

Singleton trait carrying the topology name as a type parameter (e.g. TopologyTrait{:Square}, TopologyTrait{:Honeycomb}, TopologyTrait{:Penrose}). Used for dispatch in topology-specific helpers such as high-symmetry-point tables.

source
LatticeCore.UniformLayoutType
UniformLayout(st::AbstractSiteType)

Every site has the same site type. The type parameter carries the concrete site-type singleton so that downstream MC code can dispatch on it at compile time (constant folding in the hot loop).

source
LatticeCore.XYSiteType
XYSite{T <: AbstractFloat}()

Planar rotor: state is an angle θ ∈ [0, 2π) stored as T (default Float64).

source
Base.positionMethod
position(lat::AbstractLattice{D, T}, i::Int)::SVector{D, T}

Real-space position of site i. This extends Base.position so that downstream code can write position(lat, i) directly after using LatticeCore.

source
LatticeCore._has_known_gridMethod
LatticeCore._has_known_grid(lat::AbstractLattice) → Bool

Whether the lattice has a known, FFT-compatible grid layout that matches a PeriodicMomentumLattice mesh of the same dims.

Default: false. Concrete lattices opt in by adding a method that returns true, paired with a _reshape_state method that produces the corresponding D-dimensional grid view.

The FFT fast path in LatticeCoreFFTWExt only fires when this returns true; lattices without an opt-in stay on the naive helper.

source
LatticeCore._reshape_stateMethod
LatticeCore._reshape_state(lat, state, dims) → AbstractArray

Reshape a per-site state::AbstractVector into the lattice's natural D-dimensional grid of size dims, so that the FFT extension can take a single fft over the result.

Default: throws — concrete lattices that opt into _has_known_grid must also provide a method here.

source
LatticeCore._ssd_axis_envelopeMethod
_ssd_axis_envelope(cx::Real, L::Integer) → Float64

Single-axis SSD envelope sin²(π (cx - 1/2) / L) for a 1-based real-valued per-axis cell coordinate cx ∈ [1, L]. The shift by -1/2 converts the convention to the canonical 0-indexed form sin²(π (i + 1/2) / L) with i = cx - 1.

Internal helper for bond_weight(::SSD, lat, i, j).

source
LatticeCore._ssd_site_envelopeMethod
_ssd_site_envelope(lat::AbstractLattice, i::Int) → Float64

Multi-axis SSD envelope evaluated at site i: the product of _ssd_axis_envelope over the per-axis cell coordinates of i. Uses size_trait for per-axis lengths and to_latticeposition for the cell coordinate of the site.

The conversion to_lattice(lat, RealSpace(position(lat, i))) round-trips exactly for the reference lattices (which use unit spacing) and relies on the lattice's own to_lattice(::RealSpace) for any custom basis.

source
LatticeCore._structure_factor_naiveMethod
LatticeCore._structure_factor_naive(lat, state, ml) → Vector{Float64}

Reference O(N · M) loop. Kept as the unconditional fallback used by extensions when the regular-mesh / NUFFT preconditions don't hold.

source
LatticeCore.adjacency_matrixMethod
adjacency_matrix(lat::AbstractLattice; sparse::Bool=true)

Return the N × N undirected adjacency matrix of the lattice graph, where N = num_sites(lat). The matrix is symmetric; A[i, j] == true iff there is a bond between sites i and j.

Bonds are taken from elements(lat, BondCenter()), so concrete lattices that override bonds(lat) automatically get a consistent adjacency matrix without further work.

Keyword arguments

  • sparse=true (default): return a SparseMatrixCSC{Bool, Int}. This is the recommended form for large lattices.
  • sparse=false: return a dense Matrix{Bool} of the same content. Useful for tiny test lattices and notebooks.

Self-loops (a bond with i == j) are skipped. Duplicate bonds in the input are folded into a single entry.

Example

lat = SimpleSquareLattice(3, 3, OpenAxis())
A = adjacency_matrix(lat)        # 9×9 SparseMatrixCSC{Bool, Int}
A == transpose(A)                # true
source
LatticeCore.apply_axis_bcMethod
apply_axis_bc(axis_bc::AbstractAxisBC, idx::Int, L::Int) → (wrapped, is_valid)

Apply the axis-level BC to a raw cell index idx ∈ ℤ on an axis of length L. Returns a tuple (wrapped::Int, is_valid::Bool):

  • PeriodicAxis, TwistedAxis: (mod1(idx, L), true)
  • OpenAxis: (idx, 1 <= idx <= L)

The twist phase is intentionally reported separately by axis_phase: MC code paths that do not need phases (classical Ising / XY / Heisenberg) are not forced to traffic in complex numbers.

source
LatticeCore.axis_phaseMethod
axis_phase(axis_bc::AbstractAxisBC, idx::Int, L::Int) → ComplexF64

Phase factor attached to a bond that steps from a valid cell index to idx (possibly out of 1:L) along a single axis.

  • PeriodicAxis, OpenAxis: always 1 + 0im.
  • TwistedAxis(θ): cis(+θ) if idx > L, cis(-θ) if idx < 1, otherwise 1 + 0im.

Classical MC paths may ignore this; quantum / flux-carrying code should multiply bond contributions by the phase.

source
LatticeCore.basis_positionMethod
basis_position(lat::AbstractLattice{D, T}, b::Int) → SVector{D, T}

Real-space offset of basis site b relative to its cell origin. The default places a single basis site at the origin; multi-basis lattices (honeycomb, kagome, ...) must override.

source
LatticeCore.basis_vectorsMethod
basis_vectors(lat::LineLattice) → SMatrix{1, 1, T}

Real-space basis matrix. For the unit-spacing reference chain this is the 1×1 identity.

source
LatticeCore.basis_vectorsMethod
basis_vectors(lat::SimpleSquareLattice) → SMatrix{2, 2, T}

Real-space basis matrix. For the unit-spacing reference square this is the 2×2 identity.

source
LatticeCore.bond_centerMethod
bond_center(lat::AbstractLattice, bond::Bond) → SVector{D, T}

Geometric center (midpoint) of the bond in real space. Useful for bond-centered observables and for position-dependent bond modifiers such as sine-square deformation.

Uses the bond's stored displacement bond.vector rather than the literal positions of bond.i and bond.j. This matters under periodic boundary conditions: the wrapped target's position(j) is on the opposite side of the sample, so (position(i) + position(j))/2 would point to the sample interior instead of just outside the boundary. The bond carries the unwrapped displacement, so position(i) + bond.vector / 2 gives the true geometric midpoint.

source
LatticeCore.bond_orbitsMethod
bond_orbits(lat::AbstractLattice) → iterator of CellBond{D}

Representatives of the bond orbits under the translation group. Defaults to cell_bonds. A TN builder places one bond tensor per element of this iterator.

source
LatticeCore.bond_weightMethod
bond_weight(modifier::AbstractBoundaryModifier, lat, i::Int, j::Int) → Float64

Multiplicative weight applied to the bond (i, j) by a boundary modifier. Default implementation for NoModifier returns 1.0. SSD and other non-trivial modifiers will override this.

source
LatticeCore.bond_weightMethod
bond_weight(::SSD, lat::AbstractLattice, i::Int, j::Int) → Float64

Sine-square deformation envelope for the bond (i, j). Each axis contributes a sin²(π (c_d - 1/2) / L_d) factor, where c_d is the 1-based per-axis cell coordinate read from to_lattice(lat, RealSpace(position(lat, i))) and L_d is the matching component of size_trait(lat).dims. The bond weight is the arithmetic mean of the two endpoint envelopes,

\[w(i, j) = \tfrac{1}{2}\bigl(f(\mathbf{r}_i) + f(\mathbf{r}_j)\bigr).\]

Requires a FiniteSize lattice; an InfiniteSize / QuasiInfiniteSize lattice raises ArgumentError because the envelope has no canonical scale without finite per-axis lengths. Downstream packages may overload the method on a more specific lattice type to supply alternative scales.

Boundary-condition assumptions

SSD is most commonly paired with open boundaries (the envelope suppresses surface excitations of an OBC sample); the implementation itself is BC-agnostic and will weight any bond regardless of the axis BCs in LatticeBoundary.

source
LatticeCore.bondsMethod
bonds(lat::AbstractLattice)

Iterator of all bonds in the lattice. The default implementation builds Bond objects on the fly from neighbors(lat, i) using the :nearest tag. Concrete lattices may override this for efficiency or to attach non-default bond types (e.g. dimer-strong vs dimer-weak).

source
LatticeCore.boundaryFunction
boundary(lat::AbstractLattice)

The lattice's boundary condition (subtype of AbstractBoundaryCondition, defined in BoundaryCondition.jl).

source
LatticeCore.bulk_sitesMethod
bulk_sites(lat::AbstractLattice; depth::Int=1) -> Vector{Int}

Sorted site indices in the bulk region — the complement of edge_sites(lat; depth). On a fully periodic sample this is every site. depth ≥ 1.

source
LatticeCore.cell_bondsFunction
cell_bonds(lat::AbstractLattice) → iterator of CellBond{D}

The bond motif: a finite iterator of CellBond, which by convention lists each undirected bond of the lattice exactly once (see CellBond for the double-counting caveat). This is the bond analogue of the site basis and the key object for placing bond tensors in the thermodynamic limit.

Concrete translationally invariant lattices must implement this.

source
LatticeCore.cell_partitionFunction
cell_partition(lat::AbstractLattice, k::Integer = 1) -> Vector{Vector{Int}}

Group the sites of lat by which cell of the lattice k steps coarser — that is, of rescale(lat, -k) — they fall into. Entry c lists the site indices of lat belonging to cell c of that coarser lattice, and together the groups partition 1:num_sites(lat).

Note the direction: rescale(lat, k) goes up in size and has more cells than lat, so it is the -k lattice whose cells are unions of lat's. A family that cannot take the downward step (LinearScaling with cell counts not divisible by factor^k, say) should raise rather than round.

Useful whenever a quantity defined per site has to be compared across scales — cell averages of a local observable, cell-resolved densities, or transferring a configuration between two members of a size_sequence.

Concrete lattice packages implement this; the default throws.

source
LatticeCore.cell_positionMethod
cell_position(lat::AbstractLattice{D, T}, cell, b::Int=1) → SVector{D, T}

Real-space position of basis site b in unit cell cell (an NTuple{D,Int}, SVector{D,Int}, or CellSite), computed as translation_vectors(lat) * cell + basis_position(lat, b). Works for any cell coordinate — including cells far outside any finite sample — without materialising the lattice.

source
LatticeCore.connected_componentsMethod
connected_components(lat::AbstractLattice) -> Vector{Vector{Int}}

Return the connected components of the lattice graph, computed by BFS over neighbors(lat, ·). Each inner vector is sorted in ascending order of site index, and components are returned in order of their smallest member.

Useful for analysing diluted / defective lattices and for sanity checks on user-defined AbstractLattice subtypes.

Example

# A 3x3 open square stripped of one site is still connected:
length(connected_components(lat)) == 1
source
LatticeCore.default_plot_backendMethod
default_plot_backend() -> AbstractPlotBackend

The backend used by plot_lattice when backend is not given: the most recently loaded of Plots / Makie. Errors if neither is loaded.

source
LatticeCore.density_of_statesMethod
density_of_states(lat::AbstractLattice; t=1.0, onsite=0.0, nbins=100,
                  broadening=0.0) -> (centers, dos)

Density of states of the tight-binding spectrum, normalized so that sum(dos) * step ≈ num_sites(lat). broadening = 0 gives a histogram over nbins bins; broadening = σ > 0 smears each level by a Gaussian of width σ.

source
LatticeCore.distance_matrixMethod
distance_matrix(lat::AbstractLattice;
                weights::Function=identity_weight) → Matrix{Float64}

All-pairs shortest-path distance matrix on the lattice graph. Returns an N × N Matrix{Float64} with D[i, j] equal to the cost of the shortest path from site i to site j under weights. Diagonal entries are 0.0. Pairs of sites in distinct connected components are filled with Inf.

The default weights=identity_weight reproduces unweighted hop-count distances (Float64-promoted for uniformity with the weighted case). The callback signature is (lat, bond) -> Real — see identity_weight for the convention and an SSD example.

Algorithm

For lattices with num_sites(lat) <= floyd_warshall_threshold (default 64) the implementation uses dense Floyd–Warshall (O(N^3), arithmetic-only). For larger lattices it runs Dijkstra from each source (O(N · (V + E) log V)), which is asymptotically cheaper on sparse lattice graphs.

Keyword arguments

  • weights::Function=identity_weight — edge cost callback as above.
  • floyd_warshall_threshold::Int=64 — switch-over N between the two algorithms. Mostly a tuning knob; the default is conservative.

Example

lat = SimpleSquareLattice(4, 4, OpenAxis())
D = distance_matrix(lat)
@assert D == transpose(D)            # symmetric for undirected graph
@assert all(iszero, diag(D))
source
LatticeCore.domainFunction
domain(st::AbstractSiteType)

Iterable over the state space. Only meaningful for small discrete site types (Ising, Potts); continuous types leave this unimplemented.

source
LatticeCore.dynamic_structure_factorMethod
dynamic_structure_factor(lat::AbstractLattice,
                         kpoints::AbstractVector{<:AbstractVector};
                         t=1.0, onsite=0.0, omega=nothing, nomega=200,
                         broadening=0.05) -> (omegas, A)

Momentum-resolved single-particle spectral function of the tight-binding model on lat,

\[A(k, ω) = \sum_n |\langle k | ψ_n \rangle|^2 \, δ(ω - E_n), \qquad \langle k | ψ_n \rangle = \tfrac{1}{\sqrt N} \sum_l e^{-i k · r_l} ψ_n(l),\]

evaluated at every k-vector in kpoints. Returns the shared omegas grid (length nomega) and a length(kpoints) × nomega matrix A. Each δ-peak is a normalized Gaussian of width broadening, so sum(A[j, :]) * Δω ≈ 1 for every j (spectral-weight sum rule). On a periodic crystal A(k,ω) collapses onto the Bloch bands; on a quasicrystal it resolves the fragmented spectrum.

See also structure_factor, spectrum.

source
LatticeCore.edge_bondsMethod
edge_bonds(lat::AbstractLattice; depth::Int=1) -> Vector{Bond}

Bonds incident to at least one edge site (see edge_sites) — the bonds touching the boundary region. Empty on a fully periodic sample. depth ≥ 1.

source
LatticeCore.edge_sitesMethod
edge_sites(lat::AbstractLattice; depth::Int=1) -> Vector{Int}

Sorted site indices of the edge region: sites within graph distance depth - 1 of an under-coordinated boundary site (coordination below the bulk coordination of its sublattice). depth = 1 is the boundary ring; each increment peels one more layer inward. A fully periodic sample has an empty edge. depth ≥ 1.

See also bulk_sites, edge_bonds.

source
LatticeCore.eigenstatesMethod
eigenstates(lat::AbstractLattice; t=1.0, onsite=0.0)
    -> (values::Vector{Float64}, vectors::Matrix{Float64})

Full eigendecomposition of the tight-binding Hamiltonian: values ascending, vectors[:, n] the eigenvector for values[n].

source
LatticeCore.element_neighborsFunction
element_neighbors(lat, e::AbstractLatticeElement, i::Int)

Neighbours of the i-th element of centring e, under the adjacency appropriate to e:

  • VertexCenterneighbors(lat, i) (the usual graph)
  • BondCenterline graph: other bonds sharing a vertex with bond i
  • PlaquetteCenterdual graph: plaquettes sharing an edge with plaquette i
  • CellCenter → throws unless overridden

Concrete lattices may override any of these for efficiency or to support custom adjacency rules (e.g. "only same-type bonds").

source
LatticeCore.element_orbit_positionMethod
element_orbit_position(lat, e::AbstractLatticeElement, rep) → SVector{D,T}

Real-space position of an orbit representative rep of centring e, evaluated on the home unit cell via cell_position:

Consistent with bond_center / plaquette_center, but evaluated on the fundamental domain: it needs no boundary wrapping (the motif carries unwrapped cell offsets) and works for infinite lattices.

source
LatticeCore.element_positionFunction
element_position(lat, e::AbstractLatticeElement, i::Int)

Real-space position of the i-th element of centring e on lat. See Bond.jl for the default VertexCenter / BondCenter methods.

Indexing convention

The integer i follows the enumeration order of:

  • 1:num_sites(lat) for VertexCenter,
  • enumerate(bonds(lat)) for BondCenter,
  • enumerate(plaquettes(lat)) for PlaquetteCenter.

This means i is lattice-specific: a concrete lattice that overrides bonds(lat) / plaquettes(lat) (or returns them in a different order from another lattice type) implicitly redefines what i means here. Generic code that round-trips via integer indices is safe only within a single lattice instance; for cross-lattice identification of an element, materialise it through elements(lat, e) instead. A typed BondIndex / PlaquetteIndex wrapper that makes this contract type-level is tracked as a follow-up.

source
LatticeCore.element_positionsFunction
element_positions(lat, e::AbstractLatticeElement)

Iterator over the real-space positions of every element of centring e on lat. See Bond.jl for the default implementation.

source
LatticeCore.element_typeMethod
element_type(st::AbstractSiteType) → AbstractLatticeElement

Which geometric element the DOF lives on. Defaults to VertexCenter. Override for bond / plaquette / cell-centered site types.

source
LatticeCore.elementsFunction
elements(lat, e::AbstractLatticeElement)

Iterator over the underlying elements of centring e on lat. See Bond.jl for the default VertexCenter / BondCenter methods.

source
LatticeCore.fourier_moduleMethod
fourier_module(lat::AbstractLattice) → AbstractMomentumLattice

Quasicrystal-side entry point: construct the discrete Fourier module (Bragg peak set) for a cut-and-project lattice.

Trait contract

This method is a required override for any concrete lattice whose reciprocal_support(lat) returns HasFourierModule. Concrete quasicrystal lattices implement it in their own package (typically QuasiCrystal.jl); the fallback throws a MethodError so the trait/method mismatch is visible at the call site through momentum_lattice.

Lattices with HasReciprocal should implement reciprocal_lattice instead, and lattices with NoReciprocal should not override either.

The returned object is expected to be an AbstractMomentumLattice — typically a BraggPeakSet — so observers like structure_factor treat periodic and quasiperiodic lattices uniformly.

source
LatticeCore.gamma_centeredMethod
gamma_centered(basis::SMatrix{D, D, T}, mesh::NTuple{D, Int})
    → PeriodicMomentumLattice{D, T}

Construct a Γ-centred regular mesh. Fractional k-coordinates are n / N with n = 0, …, N - 1, so the mesh includes Γ and walks to but not through the BZ edge.

source
LatticeCore.identity_weightMethod
identity_weight(lat::AbstractLattice, bond::Bond) → 1.0

Default weights callback used by shortest_path and distance_matrix. Returns 1.0 for every bond.

This sentinel value is checked by === inside shortest_path: when weights === identity_weight, the unweighted BFS code path is selected for speed and to preserve the Int-distance return type introduced in PR #44. Any other callback runs the Dijkstra code path and yields Float64 costs.

The callback signature is (lat, bond) -> Real. A custom weight function should preserve this shape; for example, to use the boundary-modifier bond_weight from BoundaryCondition:

ssd_w(lat, b) = bond_weight(boundary(lat).modifier, lat, b.i, b.j)
shortest_path(lat, src, dst; weights=ssd_w)

identity_weight itself ignores its arguments.

source
LatticeCore.incidentFunction
incident(lat, from::AbstractLatticeElement, to::AbstractLatticeElement, i::Int)

Return the integer indices of elements of centring to that are incident to the i-th element of centring from. Defaults cover:

  • VertexCenterBondCenter: bond-site incidence
  • VertexCenterPlaquetteCenter: site-plaquette incidence
  • BondCenterPlaquetteCenter: bond-plaquette incidence

Same-centring pairs (from == to) fall through to element_neighbors so that incident(lat, E(), E(), i) is the adjacency under centring E.

Return type

The result is always an AbstractVector{Int} (iterable, indexable, length-supporting). When the cardinality is statically known, an SVector{N,Int} is returned to avoid heap allocation:

  • incident(lat, ::BondCenter, ::VertexCenter, i)SVector{2,Int} (a bond always has exactly 2 endpoints).

Otherwise (variable plaquette size, dynamic adjacency, etc.) a Vector{Int} is returned. Callers that previously did a, b = incident(lat, BondCenter(), VertexCenter(), k) continue to work because SVector supports tuple-style destructuring.

Concrete lattices may override any pair for O(1) access — the default implementations here are O(num_elements) materialisations meant for correctness, not hot-path use.

Indexing convention

Both the input index i (for centring from) and the integer indices in the returned vector (for centring to) follow the enumeration order of 1:num_sites(lat) / enumerate(bonds(lat)) / enumerate(plaquettes(lat)) — same convention as element_position. Indices are lattice-specific and not portable across lattice instances.

source
LatticeCore.incident_cell_bondsMethod
incident_cell_bonds(lat::AbstractLattice, s::CellSite) → Vector{CellBond}

The bonds incident to site s, each re-anchored so that src is s.basis and offset points from s.cell toward the neighbour's cell. Every motif bond contributes in both orientations (once where s plays the motif src, once where it plays the motif dst), so a site sees its full coordination shell. Computed lazily from cell_bonds; no global bond list is built.

source
LatticeCore.inverse_participation_ratioMethod
inverse_participation_ratio(ψ::AbstractVector) -> Float64

Inverse participation ratio Σ|ψ_i|⁴ / (Σ|ψ_i|²)² of a single state. Ranges in [1/N, 1]: 1/N for a fully extended state, 1 for a state on one site; the participation number 1/IPR estimates how many sites it occupies.

source
LatticeCore.inverse_participation_ratiosMethod
inverse_participation_ratios(lat::AbstractLattice; t=1.0, onsite=0.0)
    -> (energies::Vector{Float64}, iprs::Vector{Float64})

Per-eigenstate IPR of the tight-binding spectrum of lat, with energies.

source
LatticeCore.ipr_scalingMethod
ipr_scaling(lats; t=1.0, onsite=0.0, energy_window=nothing)
    -> (sizes::Vector{Int}, mean_iprs::Vector{Float64})

Mean IPR of each lattice in the size-ordered collection lats (uniform-hopping model), paired with num_sites. Feed to ipr_scaling_exponent for the localization exponent τ.

source
LatticeCore.ipr_scaling_exponentMethod
ipr_scaling_exponent(sizes, mean_iprs) -> Float64

Localization exponent τ from a least-squares fit of log(mean_iprs) = a - τ · log(sizes): τ ≈ 1 (extended), τ ≈ 0 (localized), 0 < τ < 1 (critical / multifractal). Needs ≥ 2 positive points.

source
LatticeCore.is_finiteMethod
is_finite(lat::AbstractLattice) → Bool

true if size_trait(lat) is a FiniteSize. Monte Carlo algorithms should guard against non-finite lattices with this predicate.

source
LatticeCore.k_pointFunction
k_point(ml::AbstractMomentumLattice, i::Int) → SVector{D, T}

The i-th k-vector in real (Cartesian) units — i.e. already multiplied through the reciprocal basis.

source
LatticeCore.makie_stateFunction
makie_state(lat::AbstractLattice, state::AbstractVector; colormap=:RdBu,
            arrows=false, markersize=15, kwargs...) -> Makie.Figure

Per-site state (length == num_sites(lat)) as a colour-mapped scatter with a colour bar. With arrows = true the entries are read as in-plane angles (XY spins) and drawn as unit arrows. Concrete method in LatticeCoreMakieExt.

source
LatticeCore.makie_structure_factorFunction
makie_structure_factor(lat::AbstractLattice, state::AbstractVector;
                       k_range=(-π, π), resolution=200, colormap=:viridis,
                       kwargs...) -> Makie.Figure

Heatmap of S(k) = |Σ_j state_j e^{-i k·r_j}|² / N over a resolution × resolution grid of k = (kx, ky). Concrete method in LatticeCoreMakieExt.

source
LatticeCore.materializeFunction
materialize(abstract; kwargs...) → AbstractLattice

Materialise an infinite / conceptually-infinite abstract lattice into a finite AbstractLattice up to the given cutoff.

This is the entry point for working with infinite structures (quasicrystals beyond a cutoff radius, Fibonacci / L-system substitutions beyond a certain depth, etc.) inside LatticeCore. It is intentionally generic with no typed supertype: any package can ship its own "infinite abstract" type and implement materialize without having to inherit from a LatticeCore hierarchy.

Cutoff convention

The meaning of the cutoff keyword argument(s) is implementation- defined. Typical choices are:

  • depth::Int — substitution depth (Fibonacci, L-system)
  • radius::Real — spatial radius (Penrose cut-and-project)
  • dims::NTuple{D, Int} — explicit per-axis sizes

The returned lattice must be is_finite == true, i.e. its size_trait should be a FiniteSize, so it can be fed directly into Monte Carlo algorithms guarded by require_finite.

See dev/note/04_architecture/06_lazy_infinite/README.md for the infinite-abstract ↔ finite-materialisation design pattern, and for the parallel pattern in 05 Part B (HyperReciprocalLattice → BraggPeakSet).

source
LatticeCore.materializeMethod
materialize(lat::InfiniteSquareLattice; dims::NTuple{2, Int}) → SimpleSquareLattice

Tile the motif into a dims[1] × dims[2] periodic SimpleSquareLattice, carrying the same site layout. This is the optional infinite-abstract → finite-materialisation bridge; the lazy translation-cell accessors do not require it.

source
LatticeCore.mean_inverse_participation_ratioMethod
mean_inverse_participation_ratio(lat::AbstractLattice; t=1.0, onsite=0.0,
                                 energy_window=nothing) -> Float64

Convenience method building the uniform-hopping / on-site-modulated tight-binding Hamiltonian of lat and returning its mean IPR. For bond-modulated models, build H with the per-bond tight_binding_hamiltonian and pass it to the matrix form.

source
LatticeCore.momentum_latticeMethod
momentum_lattice(lat::AbstractLattice) → AbstractMomentumLattice

Unified trait-dispatched entry point. Returns the reciprocal lattice for Bravais-like structures, the Fourier module for quasicrystals, and throws for lattices without any k-space representation.

source
LatticeCore.monkhorst_packMethod
monkhorst_pack(basis::SMatrix{D, D, T}, mesh::NTuple{D, Int})
    → PeriodicMomentumLattice{D, T}

Construct a Monkhorst–Pack half-shifted mesh over the Brillouin zone spanned by basis. For each axis the fractional k-coordinates are

frac_i ∈ { (n + 0.5) / N - 0.5 | n = 0, …, N - 1 }

so the mesh is centred at Γ and avoids the BZ edges.

source
LatticeCore.neighbor_bondsMethod
neighbor_bonds(lat::AbstractLattice, i::Int)

Iterator of bonds incident to site i. The default implementation builds Bond objects from neighbors(lat, i) using the :nearest tag. This is the canonical entry point the 07 MC layer uses to walk interactions involving a given site.

source
LatticeCore.neighbor_plaquettesMethod
neighbor_plaquettes(lat::AbstractLattice, i::Int)

Iterator over plaquettes that have site i on their boundary. Default implementation filters plaquettes(lat) by membership; concrete lattices may override for efficiency.

source
LatticeCore.neighborsFunction
neighbors(lat::AbstractLattice, i::Int)

Indices of sites adjacent to site i (nearest neighbors by default). Concrete types may additionally define neighbors(lat, i; shell) or neighbors(lat, i, shell::Int) to support higher shells.

source
LatticeCore.neighbors_atMethod
neighbors_at(lat::AbstractLattice, s::CellSite) → Vector{CellSite}

The neighbouring sites of s, computed on demand from the bond motif. This is the infinite-lattice analogue of neighbors: it works for any cell coordinate and never requires the lattice to be finite or materialised.

source
LatticeCore.num_elementsFunction
num_elements(lat, e::AbstractLatticeElement) → Int

Number of geometric elements of centring e on lat. See Bond.jl for the default VertexCenter / BondCenter methods.

source
LatticeCore.num_sitesFunction
num_sites(lat::AbstractLattice)::Int

Number of sites in the lattice. Must be implemented by finite concrete types. InfiniteSize lattices should throw DomainError.

source
LatticeCore.num_sublatticesMethod
num_sublattices(lat::AbstractLattice) → Int

Number of geometric sublattices in the lattice. Defaults to 1 so lattices that are not sublattice-aware need not override.

source
LatticeCore.plaquette_centerMethod
plaquette_center(p::Plaquette) → SVector

Geometric center of the plaquette. For a materialised Plaquette this is just a field read.

source
LatticeCore.plaquette_orbitsMethod
plaquette_orbits(lat::AbstractLattice) → iterator of PlaquetteRule

Representatives of the plaquette (face) orbits under the translation group — the unit cell's PlaquetteRules. Defaults to () (lattices with no plaquette notion). The bond / site analogues are bond_orbits / site_orbits.

source
LatticeCore.plaquettesFunction
plaquettes(lat::AbstractLattice)

Iterator over all plaquettes on lat. The default implementation throws MethodError — concrete lattices that have a notion of plaquettes must implement this method (e.g. by walking cells × PlaquetteRules under their boundary condition).

source
LatticeCore.positionsMethod
positions(lat::AbstractLattice)

Iterator over all positions. Default implementation lazily constructs from num_sites and position; works only for finite lattices. Concrete types may override for efficiency.

source
LatticeCore.reciprocal_basisFunction
reciprocal_basis(ml::AbstractMomentumLattice) → SMatrix{D, D, T}

Reciprocal-space basis matrix. Columns are the primitive reciprocal lattice vectors.

source
LatticeCore.reciprocal_latticeMethod
reciprocal_lattice(lat::AbstractLattice) → PeriodicMomentumLattice

Construct the reciprocal lattice for a Bravais-like lat.

Trait contract

This method is a required override for any concrete lattice whose reciprocal_support(lat) returns HasReciprocal. The fallback deliberately throws a MethodError so missing implementations surface immediately at the trait dispatch site (see momentum_lattice, which routes HasReciprocal lattices through reciprocal_lattice).

Lattices with reciprocal_support(lat) == NoReciprocal() MUST NOT override this method — they have no Bravais reciprocal structure and momentum_lattice will refuse to call them. Lattices with HasFourierModule() should implement fourier_module instead.

The returned object is expected to satisfy the AbstractMomentumLattice interface (num_k_points, k_point, reciprocal_basis); the canonical concrete return type is PeriodicMomentumLattice.

source
LatticeCore.require_finiteMethod
require_finite(lat::AbstractLattice)

Assert that lat is a finite lattice. Throws ArgumentError if is_finite returns false.

Intended as a guard at the entry point of Monte Carlo algorithms or any routine that cannot operate on an infinite or not-yet-materialised lattice. Returns nothing on success.

Example

function run!(rng, state, lat::AbstractLattice, model, alg; kwargs...)
    require_finite(lat)
    # ... safe to walk the full site list from here ...
end
source
LatticeCore.rescaleFunction
rescale(lat::AbstractLattice, k::Integer = 1) -> AbstractLattice

The same lattice k scale steps larger, in the sense of scaling_rule. k = 0 returns a lattice equivalent to lat; negative k steps down where the family supports it.

For LinearScaling(f) one step multiplies every per-axis cell count by f. For SubstitutionScaling(d) one step advances the substitution depth by d. The point of the common verb is that a routine which studies how some quantity behaves as the system grows can be written once and applied to periodic and aperiodic lattices alike, instead of threading (Lx, Ly) through code that a quasicrystal cannot supply.

Concrete lattice packages implement this; there is no meaningful generic fallback, so the default throws.

source
LatticeCore.scaling_ruleMethod
scaling_rule(lat::AbstractLattice) -> AbstractScalingRule

How this lattice family changes scale. Defaults to NoScaling, i.e. the lattice offers no canonical size sequence and rescale is unavailable.

A Bravais-like lattice normally reports LinearScaling — its per-axis cell counts simply multiply. An aperiodic lattice normally reports SubstitutionScaling, where the natural sequence of sizes is generated by its substitution rule rather than by an integer side length (Fibonacci lengths, Penrose inflation radii, …), so "the next size up" is a well defined notion even though there is no L to double.

See also rescale, size_sequence, cell_partition.

source
LatticeCore.shortest_pathMethod
shortest_path(lat::AbstractLattice, src::Int, dst::Int;
              weights::Function=identity_weight)
    -> (cost, path::Vector{Int})

Shortest path on the lattice graph from src to dst.

The implementation dispatches internally on the identity of the weights callback:

  • weights === identity_weight (the default) — the unweighted hop- count BFS introduced in PR #44 is used. Returns (dist::Int, path::Vector{Int}). dist is the number of bonds between src and dst (0 if src == dst); on disconnect it returns (typemax(Int), Int[]). The no-keyword call form shortest_path(lat, src, dst) resolves to this branch and is fully backward compatible with PR #44.
  • Any other callback — Dijkstra on the weighted graph. weights must be a callable (lat, bond) -> Real returning a non-negative edge cost. Returns (cost::Float64, path::Vector{Int}); on disconnect it returns (Inf, Int[]).

The weights callback is invoked once per directed edge traversal on bonds produced by neighbor_bonds(lat, u). The signature deliberately takes a Bond, not just (i, j), so callbacks can read bond.type, bond.vector, etc. and so the same callback can be passed to distance_matrix. To re-use the existing bond_weight of an AbstractBoundaryModifier, wrap it in a closure:

ssd_w(lat, b) = bond_weight(boundary(lat).modifier, lat, b.i, b.j)
shortest_path(lat, 1, 9; weights=ssd_w)

Negative-weight edges are not supported; behaviour is undefined if weights returns a negative value.

Examples

lat = SimpleSquareLattice(3, 3, OpenAxis())
d, p = shortest_path(lat, 1, 9)                       # BFS, Int distance
c, q = shortest_path(lat, 1, 9; weights=(lat, b) -> 1.0)  # Dijkstra, Float64 cost
c == Float64(d)                                        # true
source
LatticeCore.site_layoutFunction
site_layout(lat::AbstractLattice) → AbstractSiteLayout

Return the lattice's site layout. Concrete lattices must either implement this method directly or hold an AbstractSiteLayout in a field of that name.

source
LatticeCore.site_orbitsMethod
site_orbits(lat::AbstractLattice) → iterator

Representatives of the site orbits under the translation group — i.e. the basis sites 1:num_basis_sites(lat). A TN builder places one site tensor per element of this iterator regardless of the lattice's size or boundary condition.

source
LatticeCore.site_typeFunction
site_type(layout::AbstractSiteLayout, i::Int) → AbstractSiteType

Return the site type stored at site index i.

source
LatticeCore.site_typeMethod
site_type(lat::AbstractLattice, i::Int) → AbstractSiteType

Site type at site i. Defaults to site_type(site_layout(lat), i) so concrete lattices only need to implement site_layout.

source
LatticeCore.size_sequenceMethod
size_sequence(lat::AbstractLattice, n::Integer) -> Vector{<:AbstractLattice}

[rescale(lat, k) for k in 0:n] — the lattice at successive scales, for sweeping a quantity against system size without hard-coding how the family is parameterized.

for l in size_sequence(lat, 4)
    push!(xs, num_sites(l))
    push!(ys, measure_something(l))
end
source
LatticeCore.size_traitFunction
size_trait(lat::AbstractLattice) → AbstractSizeTrait

Size trait describing the lattice's extent. Must be implemented by concrete types.

source
LatticeCore.spectrumMethod
spectrum(lat::AbstractLattice; t=1.0, onsite=0.0) -> Vector{Float64}

Sorted eigenvalues of the tight-binding Hamiltonian of lat.

source
LatticeCore.structure_factorMethod
structure_factor(lat, state, ml::AbstractMomentumLattice) → Vector{Float64}

Evaluate the structure factor at every k-point of ml.

Dispatch is driven by reciprocal_support(lat):

  • HasReciprocal() (Bravais periodic lattices): uses an FFT-based fast path when LatticeCoreFFTWExt is loaded (using FFTW), otherwise falls back to the naive O(N · M) loop.
  • HasFourierModule() (cut-and-project quasicrystals): uses a NUFFT fast path when LatticeCoreNFFTExt is loaded (using NFFT), otherwise falls back to naive.
  • NoReciprocal() and any unhandled case: naive.

Extensions hook into the _structure_factor_fast indirection below; the default fallback simply runs the naive loop.

source
LatticeCore.structure_factorMethod
structure_factor(lat, state, k::SVector) → Float64

Scalar structure factor at a single k-point:

S(k) = (1/N) |⟨ Σ_i s_i exp(-i k · r_i) ⟩|²

computed on a single snapshot (no thermal averaging). The default implementation is naive O(N) per k-point; FFT- and NUFFT-based specialisations on regular meshes are provided in the optional LatticeCoreFFTWExt / LatticeCoreNFFTExt extensions and dispatch on reciprocal_support(lat).

source
LatticeCore.tight_binding_hamiltonianMethod
tight_binding_hamiltonian(lat::AbstractLattice, hoppings::AbstractVector;
                          onsite=0.0) -> SparseMatrixCSC{Float64,Int}

Per-bond hopping variant: hoppings[k] is the amplitude on the k-th bond of collect(bonds(lat)). Use this for bond-modulated models (e.g. a Fibonacci tL/tS chain). length(hoppings) must equal the number of bonds.

source
LatticeCore.to_hyperFunction
to_hyper(lat::AbstractLattice, coord::AbstractCoordinate) → HigherDimCoord

Convert coord into a higher-dimensional hyper coordinate. Only meaningful for cut-and-project quasicrystals; other lattices may leave this unimplemented.

source
LatticeCore.to_latticeFunction
to_lattice(lat::AbstractLattice, coord::AbstractCoordinate) → LatticeCoord

Convert coord into a lattice coordinate on lat. Concrete lattices should implement at least to_lattice(lat, ::RealSpace).

source
LatticeCore.to_latticeMethod
to_lattice(lat::LineLattice, rs::RealSpace{1}) → LatticeCoord{1}

Inverse of to_real: round the real-space x coordinate to the nearest integer cell index.

source
LatticeCore.to_latticeMethod
to_lattice(lat::SimpleSquareLattice, rs::RealSpace{2}) → LatticeCoord{2}

Inverse of to_real: round each real-space component to the nearest integer cell index.

source
LatticeCore.to_realFunction
to_real(lat::AbstractLattice, coord::AbstractCoordinate) → RealSpace

Convert coord into a real-space Cartesian coordinate on lat. Concrete lattices should implement at least to_real(lat, ::LatticeCoord) (and, for quasicrystals, to_real(lat, ::HigherDimCoord)).

source
LatticeCore.to_realMethod
to_real(lat::LineLattice, coord::LatticeCoord{1}) → RealSpace

Interpret the lattice coordinate as a unit-spacing Cartesian position.

source
LatticeCore.to_realMethod
to_real(lat::SimpleSquareLattice, coord::LatticeCoord{2}) → RealSpace

Interpret the lattice coordinate as a unit-spacing Cartesian position.

source
LatticeCore.translation_vectorsFunction
translation_vectors(lat::AbstractLattice{D, T}) → SMatrix{D, D, T}

The Bravais translation vectors of lat, as the columns of a D×D matrix. A unit-cell coordinate cell ∈ ℤ^D maps to the real-space cell origin translation_vectors(lat) * cell.

Concrete translationally invariant lattices must implement this. It has no universal default because the geometry is lattice-specific.

source
LatticeCore.zero_stateFunction
zero_state(st::AbstractSiteType)

Canonical zero state (e.g. 0 for Ising, 0.0 for XY). Not all site types have to define this.

source