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.AbstractAxisBC — Type
AbstractAxisBCAbstract 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 viamod1OpenAxis— rejects out-of-range indicesTwistedAxis— wraps likePeriodicAxisbut attaches a phase factor to bonds that cross the boundary
LatticeCore.AbstractBoundaryCondition — Type
AbstractBoundaryConditionAbstract supertype for lattice boundary conditions.
The canonical concrete type is LatticeBoundary, which composes:
- a tuple of per-axis boundary conditions (subtypes of
AbstractAxisBC:PeriodicAxis,OpenAxis,TwistedAxis) - a non-topological modifier (subtype of
AbstractBoundaryModifier:NoModifier,SSD)
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.
LatticeCore.AbstractBoundaryModifier — Type
AbstractBoundaryModifierAbstract 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)::Float64The 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.
LatticeCore.AbstractCoordinate — Type
AbstractCoordinate{D}Abstract supertype for lattice coordinate representations. Concrete subtypes describe the same lattice point in different spaces:
RealSpace— Cartesian coordinatesLatticeCoord— unit cell index + geometric sublatticeHigherDimCoord— higher-dimensional projection (for cut-and-project quasicrystals)
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.
LatticeCore.AbstractIndexing — Type
AbstractIndexingAbstract 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})::Intlattice_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.
LatticeCore.AbstractLattice — Type
AbstractLattice{D, T}Abstract supertype for lattice types. Type parameters:
D: spatial dimension (integer literal)T: numeric type for real-space positions (typicallyFloat64)
Required interface (concrete subtypes must implement)
position(lat, i)::SVector{D, T}neighbors(lat, i)— iterable of neighbor site indicesboundary(lat)— returns anAbstractBoundaryConditionsize_trait(lat)::AbstractSizeTraitnum_sites(lat)::Int— required forFiniteSize/QuasiInfiniteSizelattices;InfiniteSizelattices should throwDomainError.
Optional interface (defaults provided)
positions(lat)— defaults to an iterator built frompositionbonds(lat)— defaults to an iterator built fromneighborsneighbor_bonds(lat, i)— defaults to an iterator built fromneighborstopology(lat)—TopologyTrait{:unknown}()periodicity(lat)—Aperiodic()is_bipartite(lat)—falsereciprocal_support(lat)—NoReciprocal()is_finite(lat)— derived fromsize_trait
See dev/note/04_architecture/02_lattice_interface/README.md for the design rationale.
LatticeCore.AbstractLatticeElement — Type
AbstractLatticeElementAbstract 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.
LatticeCore.AbstractMomentumLattice — Type
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)::Intk_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.
LatticeCore.AbstractPlotBackend — Type
AbstractPlotBackendBase type for the plotting backends that the plot_* functions dispatch on. Concrete singletons PlotsBackend and MakieBackend are provided by LatticeCorePlotsExt / LatticeCoreMakieExt once Plots / Makie is loaded.
LatticeCore.AbstractReciprocalSupport — Type
AbstractReciprocalSupportTrait indicating what kind of k-space representation a lattice admits.
Subtypes:
HasReciprocal: standard Bravais reciprocal lattice.HasFourierModule: dense Fourier module arising from a cut-and-project quasicrystal.NoReciprocal: neither of the above (e.g. generic graph).
LatticeCore.AbstractScalingRule — Type
AbstractScalingRuleTrait describing how a lattice family generates a sequence of sizes, i.e. what "the same lattice, one step larger" means for it.
Subtypes:
NoScaling: no canonical size sequence.LinearScaling: per-axis cell counts multiply by a fixed factor.SubstitutionScaling: sizes come from a substitution/inflation rule, as for a quasicrystal, where there is no single side length to double.
See scaling_rule, rescale, size_sequence.
LatticeCore.AbstractSiteLayout — Type
AbstractSiteLayoutAbstract 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— oneAbstractSiteTypeper site (for disordered / quenched-random configurations)
All layouts satisfy site_type(layout, i)::AbstractSiteType.
LatticeCore.AbstractSiteType — Type
AbstractSiteTypeAbstract 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 staterandom_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 toVertexCenter. Override for bond / plaquette-centered variables such as dimer or gauge fields.
See dev/note/04_architecture/04_site_type/README.md.
LatticeCore.AbstractSizeTrait — Type
AbstractSizeTraitTrait 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).
LatticeCore.AcceptanceWindow — Type
AcceptanceWindowAbstract supertype for acceptance windows in the internal (perp) space of a cut-and-project quasicrystal. Concrete windows (PolygonalWindow, IntervalWindow, etc.) live in QuasiCrystal.jl.
LatticeCore.Aperiodic — Type
Periodicity trait marker for aperiodic structures (e.g. quasicrystals).
LatticeCore.Bond — Type
Bond{D, T}A bond (edge) connecting two sites of a lattice.
Fields
i::Int— source site indexj::Int— target site indexvector::SVector{D, T}— displacementposition(j) - position(i), wrapped by the lattice's boundary condition if applicabletype::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).
LatticeCore.BondCenter — Type
Bond-centered element: the midpoint of an edge.
LatticeCore.BraggPeakSet — Type
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.
LatticeCore.CellBond — Type
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.
LatticeCore.CellCenter — Type
Cell-centered element: the centre of a 3D (or higher) cell.
LatticeCore.CellSite — Type
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.
LatticeCore.ColMajor — Type
Column-major (Fortran-style): y is the fastest axis.
LatticeCore.EmptySite — Type
EmptySite()Vacancy / empty site: stores nothing. Useful for diluted models and as a placeholder where a site has no degrees of freedom.
LatticeCore.ExplicitLayout — Type
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.
LatticeCore.FiniteSize — Type
FiniteSize{D}(dims::NTuple{D, Int})Size trait for an ordinary finite lattice with the given per-axis cell counts.
LatticeCore.HasFourierModule — Type
Trait: the lattice has a Fourier module (quasicrystal).
LatticeCore.HasReciprocal — Type
Trait: the lattice has a standard Bravais reciprocal lattice.
LatticeCore.HeisenbergSite — Type
HeisenbergSite{T <: AbstractFloat}()Classical Heisenberg spin: state is a unit vector in ℝ³ stored as SVector{3, T} (default Float64).
LatticeCore.HigherDimCoord — Type
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.
LatticeCore.HyperReciprocalLattice — Type
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.
LatticeCore.InfiniteSize — Type
InfiniteSize()Size trait for a true infinite lattice. MC cannot run on such a lattice; spectral / analytic calculations only.
LatticeCore.InfiniteSquareLattice — Type
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:
site_orbits/bond_orbits— the finite fundamental domain (one basis site, two bonds+xand+y);cell_position,neighbors_at,incident_cell_bonds— on-demand access to any concreteCellSite, computed without materialising the lattice.
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 SimpleSquareLatticebut 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 neighboursLatticeCore.IsingSite — Type
IsingSite{T <: Integer}()Ising spin: state is ±1 stored as T (default Int8).
LatticeCore.LatticeBoundary — Type
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.
LatticeCore.LatticeBoundary — Method
LatticeBoundary(axes::NTuple{N, <:AbstractAxisBC})Convenience constructor: composite boundary with NoModifier.
LatticeCore.LatticeCoord — Type
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.
LatticeCore.LineLattice — Type
LineLattice{T, B, L}(N, boundary, layout)A 1D linear chain of N sites with unit spacing.
boundaryis aLatticeBoundarywhose single axis component is one ofPeriodicAxis,OpenAxis, orTwistedAxis.layoutis anAbstractSiteLayoutthat decides whichAbstractSiteTypelives on each site. The default isUniformLayout(IsingSite()).
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()))LatticeCore.LinearScaling — Type
LinearScaling(factor::Int)Trait: one scale step multiplies every per-axis cell count by factor. The ordinary Bravais case.
LatticeCore.MakieBackend — Type
MakieBackend() — dispatch tag selecting the `Makie.jl` backend.LatticeCore.NoModifier — Type
Identity modifier: every bond has weight 1.0.
LatticeCore.NoReciprocal — Type
Trait: the lattice has no k-space representation.
LatticeCore.NoScaling — Type
Trait: the lattice offers no canonical way to change scale.
LatticeCore.OpenAxis — Type
Open axis BC: bonds crossing the boundary are dropped.
LatticeCore.Periodic — Type
Periodicity trait marker for Bravais-lattice-like structures.
LatticeCore.PeriodicAxis — Type
Periodic axis BC: wrap-around via mod1.
LatticeCore.PeriodicMomentumLattice — Type
PeriodicMomentumLattice{D, T}Concrete momentum lattice for a Bravais periodic lattice. Stores the reciprocal basis, the mesh dimensions, the Γ-offset, and an explicit list of k-points (eager construction).
Construct via monkhorst_pack or gamma_centered rather than calling the struct directly.
LatticeCore.Plaquette — Type
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 ordercenter::SVector{D, T}— real-space centroidtype::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.
LatticeCore.PlaquetteCenter — Type
Plaquette-centered element: the centre of a face.
LatticeCore.PlaquetteRule — Type
PlaquetteRuleDeclarative 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_idis 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.
LatticeCore.PlotsBackend — Type
PlotsBackend() — dispatch tag selecting the `Plots.jl` backend.LatticeCore.PottsSite — Type
PottsSite{Q, T <: Integer}()Q-state Potts spin: state is an integer in 1..Q stored as T.
LatticeCore.QuasiInfiniteSize — Type
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.
LatticeCore.RealSpace — Type
RealSpace{D, T}(x::SVector{D, T})
RealSpace(x::NTuple{D, T})Real-space Cartesian coordinate in D dimensions with element type T.
LatticeCore.RowMajor — Type
Row-major (C-style): x is the fastest axis within a row.
LatticeCore.SSD — Type
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.
LatticeCore.SimpleSquareLattice — Type
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 <= Lyso 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())))LatticeCore.Snake — Type
SnakeBoustrophedon (snake) indexing: row-major layout with alternating row direction. Useful when physical adjacency between neighbouring indices matters (e.g. for certain serialisation layouts).
LatticeCore.SublatticeLayout — Type
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.
LatticeCore.SubstitutionScaling — Type
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.
LatticeCore.TopologyTrait — Type
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.
LatticeCore.TwistedAxis — Type
TwistedAxis(phase::Real)Periodic axis BC with a phase angle (radians) attached to boundary-crossing bonds. The connectivity is identical to PeriodicAxis; only the phase returned by axis_phase differs.
LatticeCore.UniformLayout — Type
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).
LatticeCore.VertexCenter — Type
Vertex-centered element: a site in the usual sense (default).
LatticeCore.XYSite — Type
XYSite{T <: AbstractFloat}()Planar rotor: state is an angle θ ∈ [0, 2π) stored as T (default Float64).
Base.position — Method
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.
LatticeCore._has_known_grid — Method
LatticeCore._has_known_grid(lat::AbstractLattice) → BoolWhether 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.
LatticeCore._reshape_state — Method
LatticeCore._reshape_state(lat, state, dims) → AbstractArrayReshape 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.
LatticeCore._ssd_axis_envelope — Method
_ssd_axis_envelope(cx::Real, L::Integer) → Float64Single-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).
LatticeCore._ssd_site_envelope — Method
_ssd_site_envelope(lat::AbstractLattice, i::Int) → Float64Multi-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_lattice ∘ position 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.
LatticeCore._structure_factor_naive — Method
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.
LatticeCore.adjacency_matrix — Method
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 aSparseMatrixCSC{Bool, Int}. This is the recommended form for large lattices.sparse=false: return a denseMatrix{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) # trueLatticeCore.apply_axis_bc — Method
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.
LatticeCore.axis_phase — Method
axis_phase(axis_bc::AbstractAxisBC, idx::Int, L::Int) → ComplexF64Phase 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: always1 + 0im.TwistedAxis(θ):cis(+θ)ifidx > L,cis(-θ)ifidx < 1, otherwise1 + 0im.
Classical MC paths may ignore this; quantum / flux-carrying code should multiply bond contributions by the phase.
LatticeCore.basis_position — Method
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.
LatticeCore.basis_vectors — Method
basis_vectors(::InfiniteSquareLattice) → SMatrix{2, 2, T}Real-space basis matrix (the 2×2 identity for unit spacing); equal to translation_vectors for this single-basis lattice.
LatticeCore.basis_vectors — Method
basis_vectors(lat::LineLattice) → SMatrix{1, 1, T}Real-space basis matrix. For the unit-spacing reference chain this is the 1×1 identity.
LatticeCore.basis_vectors — Method
basis_vectors(lat::SimpleSquareLattice) → SMatrix{2, 2, T}Real-space basis matrix. For the unit-spacing reference square this is the 2×2 identity.
LatticeCore.bond_center — Method
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.
LatticeCore.bond_orbits — Method
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.
LatticeCore.bond_weight — Method
bond_weight(modifier::AbstractBoundaryModifier, lat, i::Int, j::Int) → Float64Multiplicative 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.
LatticeCore.bond_weight — Method
bond_weight(::SSD, lat::AbstractLattice, i::Int, j::Int) → Float64Sine-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.
LatticeCore.bonds — Method
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).
LatticeCore.boundary — Function
boundary(lat::AbstractLattice)The lattice's boundary condition (subtype of AbstractBoundaryCondition, defined in BoundaryCondition.jl).
LatticeCore.bulk_sites — Method
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.
LatticeCore.cell_bonds — Function
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.
LatticeCore.cell_partition — Function
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.
LatticeCore.cell_position — Method
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.
LatticeCore.connected_components — Method
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)) == 1LatticeCore.default_plot_backend — Method
default_plot_backend() -> AbstractPlotBackendThe backend used by plot_lattice when backend is not given: the most recently loaded of Plots / Makie. Errors if neither is loaded.
LatticeCore.density_of_states — Method
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 σ.
LatticeCore.dimension — Method
dimension(lat) → IntSpatial dimension D of the lattice.
LatticeCore.distance_matrix — Method
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-overNbetween 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))LatticeCore.domain — Function
domain(st::AbstractSiteType)Iterable over the state space. Only meaningful for small discrete site types (Ising, Potts); continuous types leave this unimplemented.
LatticeCore.dynamic_structure_factor — Method
dynamic_structure_factor(lat::AbstractLattice, ml::AbstractMomentumLattice;
kwargs...)Take the k-points from a momentum lattice (e.g. a BraggPeakSet), matching the grid used by the static structure_factor.
LatticeCore.dynamic_structure_factor — Method
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.
LatticeCore.edge_bonds — Method
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.
LatticeCore.edge_sites — Method
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.
LatticeCore.eigenstates — Method
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].
LatticeCore.element_neighbors — Function
element_neighbors(lat, e::AbstractLatticeElement, i::Int)Neighbours of the i-th element of centring e, under the adjacency appropriate to e:
VertexCenter→neighbors(lat, i)(the usual graph)BondCenter→ line graph: other bonds sharing a vertex with bondiPlaquetteCenter→ dual graph: plaquettes sharing an edge with plaquetteiCellCenter→ throws unless overridden
Concrete lattices may override any of these for efficiency or to support custom adjacency rules (e.g. "only same-type bonds").
LatticeCore.element_orbit_position — Method
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:
VertexCenter,rep::Int(basis index) → the basis-site position;BondCenter,rep::CellBond→ the midpoint of the bond's two endpoints;PlaquetteCenter,rep::PlaquetteRule→ the centroid of its corner sites.
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.
LatticeCore.element_orbits — Method
element_orbits(lat::AbstractLattice, e::AbstractLatticeElement)Representatives of the orbits of centring e under the translation group: site_orbits for VertexCenter, bond_orbits for BondCenter, and plaquette_orbits for PlaquetteCenter. A finite fundamental domain — defined for infinite lattices, where the enumeration elements is not.
LatticeCore.element_position — Function
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)forVertexCenter,enumerate(bonds(lat))forBondCenter,enumerate(plaquettes(lat))forPlaquetteCenter.
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.
LatticeCore.element_positions — Function
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.
LatticeCore.element_type — Method
element_type(st::AbstractSiteType) → AbstractLatticeElementWhich geometric element the DOF lives on. Defaults to VertexCenter. Override for bond / plaquette / cell-centered site types.
LatticeCore.elements — Function
elements(lat, e::AbstractLatticeElement)Iterator over the underlying elements of centring e on lat. See Bond.jl for the default VertexCenter / BondCenter methods.
LatticeCore.fourier_module — Method
fourier_module(lat::AbstractLattice) → AbstractMomentumLatticeQuasicrystal-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.
LatticeCore.gamma_centered — Method
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.
LatticeCore.identity_weight — Method
identity_weight(lat::AbstractLattice, bond::Bond) → 1.0Default 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.
LatticeCore.incident — Function
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:
VertexCenter↔BondCenter: bond-site incidenceVertexCenter↔PlaquetteCenter: site-plaquette incidenceBondCenter↔PlaquetteCenter: 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.
LatticeCore.incident_cell_bonds — Method
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.
LatticeCore.inverse_participation_ratio — Method
inverse_participation_ratio(ψ::AbstractVector) -> Float64Inverse 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.
LatticeCore.inverse_participation_ratios — Method
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.
LatticeCore.ipr_scaling — Method
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 τ.
LatticeCore.ipr_scaling_exponent — Method
ipr_scaling_exponent(sizes, mean_iprs) -> Float64Localization 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.
LatticeCore.is_bipartite — Method
Default bipartite flag: false.
LatticeCore.is_finite — Method
is_finite(lat::AbstractLattice) → Booltrue if size_trait(lat) is a FiniteSize. Monte Carlo algorithms should guard against non-finite lattices with this predicate.
LatticeCore.k_point — Function
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.
LatticeCore.lattice_coord — Function
lattice_coord(indexing, dims, nsub, i) → LatticeCoordInverse of site_index.
LatticeCore.makie_state — Function
makie_state(lat::AbstractLattice, state::AbstractVector; colormap=:RdBu,
arrows=false, markersize=15, kwargs...) -> Makie.FigurePer-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.
LatticeCore.makie_structure_factor — Function
makie_structure_factor(lat::AbstractLattice, state::AbstractVector;
k_range=(-π, π), resolution=200, colormap=:viridis,
kwargs...) -> Makie.FigureHeatmap 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.
LatticeCore.materialize — Function
materialize(abstract; kwargs...) → AbstractLatticeMaterialise 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).
LatticeCore.materialize — Method
materialize(lat::InfiniteSquareLattice; dims::NTuple{2, Int}) → SimpleSquareLatticeTile 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.
LatticeCore.mean_inverse_participation_ratio — Method
mean_inverse_participation_ratio(lat::AbstractLattice; t=1.0, onsite=0.0,
energy_window=nothing) -> Float64Convenience 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.
LatticeCore.mean_inverse_participation_ratio — Method
mean_inverse_participation_ratio(H::AbstractMatrix; energy_window=nothing)
-> Float64Mean inverse_participation_ratio over the eigenstates of the real symmetric Hamiltonian H. With energy_window = (Emin, Emax) only eigenstates in that closed interval are averaged (mobility-edge probe); an empty window is an error.
LatticeCore.momentum_lattice — Method
momentum_lattice(lat::AbstractLattice) → AbstractMomentumLatticeUnified 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.
LatticeCore.monkhorst_pack — Method
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.
LatticeCore.neighbor_bonds — Method
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.
LatticeCore.neighbor_plaquettes — Method
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.
LatticeCore.neighbors — Function
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.
LatticeCore.neighbors_at — Method
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.
LatticeCore.num_basis_sites — Method
num_basis_sites(lat::AbstractLattice) → IntNumber of sites in one unit cell (the size of the site motif). Defaults to num_sublattices, which is 1 unless the lattice is sublattice-aware.
LatticeCore.num_elements — Function
num_elements(lat, e::AbstractLatticeElement) → IntNumber of geometric elements of centring e on lat. See Bond.jl for the default VertexCenter / BondCenter methods.
LatticeCore.num_k_points — Function
num_k_points(ml::AbstractMomentumLattice) → IntNumber of k-points stored in the lattice.
LatticeCore.num_sites — Function
num_sites(lat::AbstractLattice)::IntNumber of sites in the lattice. Must be implemented by finite concrete types. InfiniteSize lattices should throw DomainError.
LatticeCore.num_sites — Method
num_sites(::InfiniteSquareLattice)Always throws DomainError: an infinite lattice has no finite site count. Use site_orbits for the fundamental domain, or materialize to obtain a finite sample.
LatticeCore.num_sublattices — Method
num_sublattices(lat::AbstractLattice) → IntNumber of geometric sublattices in the lattice. Defaults to 1 so lattices that are not sublattice-aware need not override.
LatticeCore.periodicity — Method
Default periodicity: Aperiodic().
LatticeCore.plaquette_center — Method
plaquette_center(p::Plaquette) → SVectorGeometric center of the plaquette. For a materialised Plaquette this is just a field read.
LatticeCore.plaquette_orbits — Method
plaquette_orbits(lat::AbstractLattice) → iterator of PlaquetteRuleRepresentatives 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.
LatticeCore.plaquettes — Function
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).
LatticeCore.positions — Method
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.
LatticeCore.random_state — Function
random_state(rng, st::AbstractSiteType)Sample a uniformly random state on site type st.
LatticeCore.reciprocal_basis — Function
reciprocal_basis(ml::AbstractMomentumLattice) → SMatrix{D, D, T}Reciprocal-space basis matrix. Columns are the primitive reciprocal lattice vectors.
LatticeCore.reciprocal_lattice — Method
reciprocal_lattice(lat::AbstractLattice) → PeriodicMomentumLatticeConstruct 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.
LatticeCore.reciprocal_support — Method
Default reciprocal support: NoReciprocal().
LatticeCore.require_finite — Method
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 ...
endLatticeCore.rescale — Function
rescale(lat::AbstractLattice, k::Integer = 1) -> AbstractLatticeThe 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.
LatticeCore.scaling_rule — Method
scaling_rule(lat::AbstractLattice) -> AbstractScalingRuleHow 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.
LatticeCore.shortest_path — Method
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}).distis the number of bonds betweensrcanddst(0ifsrc == dst); on disconnect it returns(typemax(Int), Int[]). The no-keyword call formshortest_path(lat, src, dst)resolves to this branch and is fully backward compatible with PR #44.- Any other callback — Dijkstra on the weighted graph.
weightsmust be a callable(lat, bond) -> Realreturning 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) # trueLatticeCore.site_index — Function
site_index(indexing, dims, nsub, coord) → IntLinearise coord into a 1-based site index. See AbstractIndexing for the required contract.
LatticeCore.site_layout — Function
site_layout(lat::AbstractLattice) → AbstractSiteLayoutReturn the lattice's site layout. Concrete lattices must either implement this method directly or hold an AbstractSiteLayout in a field of that name.
LatticeCore.site_orbits — Method
site_orbits(lat::AbstractLattice) → iteratorRepresentatives 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.
LatticeCore.site_type — Function
site_type(layout::AbstractSiteLayout, i::Int) → AbstractSiteTypeReturn the site type stored at site index i.
LatticeCore.site_type — Method
site_type(lat::AbstractLattice, i::Int) → AbstractSiteTypeSite type at site i. Defaults to site_type(site_layout(lat), i) so concrete lattices only need to implement site_layout.
LatticeCore.size_sequence — Method
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))
endLatticeCore.size_trait — Function
size_trait(lat::AbstractLattice) → AbstractSizeTraitSize trait describing the lattice's extent. Must be implemented by concrete types.
LatticeCore.spectrum — Method
spectrum(lat::AbstractLattice; t=1.0, onsite=0.0) -> Vector{Float64}Sorted eigenvalues of the tight-binding Hamiltonian of lat.
LatticeCore.state_type — Function
state_type(st::AbstractSiteType) → TypeJulia type used to store a state of site type st.
LatticeCore.structure_factor — Method
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 whenLatticeCoreFFTWExtis loaded (using FFTW), otherwise falls back to the naiveO(N · M)loop.HasFourierModule()(cut-and-project quasicrystals): uses a NUFFT fast path whenLatticeCoreNFFTExtis 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.
LatticeCore.structure_factor — Method
structure_factor(lat, state, k::SVector) → Float64Scalar 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).
LatticeCore.sublattice — Method
sublattice(lat::AbstractLattice, i::Int) → IntGeometric sublattice id (1-based) of site i. Defaults to 1, matching the default num_sublattices of 1.
LatticeCore.tight_binding_hamiltonian — Method
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.
LatticeCore.tight_binding_hamiltonian — Method
tight_binding_hamiltonian(lat::AbstractLattice; t=1.0, onsite=0.0)
-> SparseMatrixCSC{Float64,Int}Real symmetric single-particle tight-binding Hamiltonian of lat with uniform hopping t on every nearest-neighbour bond,
\[H = \mathrm{diag}(ε) - t \, A,\]
where A is the adjacency_matrix. onsite is a scalar on-site energy or a length-num_sites(lat) vector. Requires a finite lattice.
See also spectrum, inverse_participation_ratio, density_of_states.
LatticeCore.to_hyper — Function
to_hyper(lat::AbstractLattice, coord::AbstractCoordinate) → HigherDimCoordConvert coord into a higher-dimensional hyper coordinate. Only meaningful for cut-and-project quasicrystals; other lattices may leave this unimplemented.
LatticeCore.to_lattice — Function
to_lattice(lat::AbstractLattice, coord::AbstractCoordinate) → LatticeCoordConvert coord into a lattice coordinate on lat. Concrete lattices should implement at least to_lattice(lat, ::RealSpace).
LatticeCore.to_lattice — Method
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.
LatticeCore.to_lattice — Method
to_lattice(lat::SimpleSquareLattice, rs::RealSpace{2}) → LatticeCoord{2}Inverse of to_real: round each real-space component to the nearest integer cell index.
LatticeCore.to_real — Function
to_real(lat::AbstractLattice, coord::AbstractCoordinate) → RealSpaceConvert 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)).
LatticeCore.to_real — Method
to_real(lat::LineLattice, coord::LatticeCoord{1}) → RealSpaceInterpret the lattice coordinate as a unit-spacing Cartesian position.
LatticeCore.to_real — Method
to_real(lat::SimpleSquareLattice, coord::LatticeCoord{2}) → RealSpaceInterpret the lattice coordinate as a unit-spacing Cartesian position.
LatticeCore.topology — Method
Default topology trait: TopologyTrait{:unknown}().
LatticeCore.translation_vectors — Function
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.
LatticeCore.zero_state — Function
zero_state(st::AbstractSiteType)Canonical zero state (e.g. 0 for Ising, 0.0 for XY). Not all site types have to define this.