diff --git a/src/PEPSKit.jl b/src/PEPSKit.jl index 2aeb865b6..1114b5116 100644 --- a/src/PEPSKit.jl +++ b/src/PEPSKit.jl @@ -28,7 +28,9 @@ using ChainRulesCore, Zygote import TupleTools using MPSKit -using MPSKit: MPSTensor, MPOTensor, GenericMPSTensor, MPSBondTensor, ProductTransferMatrix +using MPSKit: + MPSTensor, MPOTensor, GenericMPSTensor, MPSBondTensor, + ProductTransferMatrix using MPSKit: InfiniteEnvironments using MPSKit: DynamicTol using MPSKit.DynamicTols: adapt_solver @@ -37,6 +39,7 @@ using MPSKit.IterativeLoggers: with_verbosity import MPSKit.DynamicTols: _updatetol import MPSKit: tensorexpr, leading_boundary, loginit!, logiter!, logfinish!, logcancel!, physicalspace import MPSKit: infinite_temperature_density_matrix +import MPSKit: fuser using TensorKitTensors: fuse_charge import TensorKitTensors.SpinOperators as SO @@ -85,6 +88,7 @@ include("operators/localoperator/dense.jl") include("operators/localoperator/tensorproduct.jl") include("operators/localoperator/mpo.jl") include("operators/localcircuit.jl") + include("operators/lattices/squarelattice.jl") include("operators/models.jl") @@ -126,6 +130,12 @@ include("algorithms/contractions/correlator/peps.jl") include("algorithms/contractions/correlator/pepo_purified.jl") include("algorithms/contractions/correlator/pepo_1layer.jl") +include("algorithms/contractions/mpo_path/routing.jl") +include("algorithms/contractions/mpo_path/pepo_1layer.jl") +include("algorithms/expectation_value/algorithms.jl") +include("algorithms/contractions/patch/tools.jl") +include("algorithms/contractions/patch/pepo_1layer.jl") + include("algorithms/ctmrg/sparse_environments.jl") include("algorithms/ctmrg/ctmrg.jl") include("algorithms/ctmrg/projectors/projectors.jl") @@ -166,6 +176,7 @@ include("algorithms/expectation_value/network_value.jl") include("algorithms/expectation_value/correlator_adapters.jl") include("algorithms/expectation_value/correlators.jl") include("algorithms/toolbox.jl") +include("algorithms/expectation_value/boundary_mps.jl") include("algorithms/optimization/implicit_differentiation.jl") include("algorithms/optimization/preconditioning.jl") @@ -184,9 +195,10 @@ export FixedSpaceTruncation, SiteDependentTruncation export HalfInfiniteProjector, FullInfiniteProjector export C4vCTMRG, C4vEighProjector, C4vQRProjector export initialize_random_c4v_env, initialize_singlet_c4v_env -export LocalOperator, physicalspace +export LocalOperator, MPOTerm, physicalspace export product_peps -export reduced_densitymatrix, expectation_value, network_value, cost_function +export reduced_densitymatrix, ExactContract, BoundaryMPSContract +export expectation_value, network_value, cost_function export correlator, correlation_length export leading_boundary export PEPSOptimize, FixedPointGradient, GeomSum, ManualIter, ImplicitGradient diff --git a/src/algorithms/contractions/mpo_path/pepo_1layer.jl b/src/algorithms/contractions/mpo_path/pepo_1layer.jl new file mode 100644 index 000000000..e93e8dbad --- /dev/null +++ b/src/algorithms/contractions/mpo_path/pepo_1layer.jl @@ -0,0 +1,247 @@ +""" +Check that the physical legs of a first OBC-MPO tensor match the PEPO site's physical space. +""" +function _check_pepo_first_physicalspace(A, op) + physicalspace(A) == space(op, 1) == space(op, 2)' || + throw(SpaceMismatch("first MPO tensor physical space does not match PEPO site")) + return nothing +end + +""" +Check that the physical legs of a last OBC-MPO tensor match the PEPO site's physical space. +""" +function _check_pepo_last_physicalspace(A, op) + physicalspace(A) == space(op, 2) == space(op, 3)' || + throw(SpaceMismatch("last MPO tensor physical space does not match PEPO site")) + return nothing +end + +""" +Check that the physical legs of a middle MPO tensor match the PEPO site's physical space. +""" +function _check_pepo_middle_physicalspace(A, op) + physicalspace(A) == space(op, 2) == space(op, 3)' || + throw(SpaceMismatch("middle MPO tensor physical space does not match PEPO site")) + return nothing +end + +""" +Convert a symbolic cardinal path direction to the corresponding PEPO virtual-leg index. +""" +function _mpo_path_direction(direction::Symbol) + direction === :north && return NORTH + direction === :east && return EAST + direction === :south && return SOUTH + direction === :west && return WEST + throw(ArgumentError("invalid MPO path direction: $direction")) +end + +""" +Return the tensor-expression label for the PEPO virtual leg in a cardinal direction. +""" +function _mpo_path_virtual_label(direction::Symbol) + direction === :north && return :N + direction === :east && return :E + direction === :south && return :S + direction === :west && return :W + throw(ArgumentError("invalid MPO path direction: $direction")) +end + +""" +Canonicalize an incoming MPO fuser so its fused PEPO leg has standard dualness. +""" +function _mpo_path_incoming_fuser(F, direction::Int) + direction in (NORTH, EAST) && return F + direction in (SOUTH, WEST) && return twist(flip(F, 1), 1) + throw(ArgumentError("invalid MPO path direction index: $direction")) +end + +""" +Canonicalize an outgoing MPO fuser so its fused PEPO leg has standard dualness and braiding. +""" +function _mpo_path_outgoing_fuser(F, direction::Int) + direction in (NORTH, EAST) && return twist(flip(F, 1), 1) + direction in (SOUTH, WEST) && return twist(F, 3) + throw(ArgumentError("invalid MPO path direction index: $direction")) +end + +""" +Build the `@tensor` labels from `(direction, suffix)` pairs +used to fuse MPO virtual strings. + +- Each direction is `:north`, `:east`, `:south`, or `:west`. +- Suffix `:l` marks an incoming MPO bond and `:r` an outgoing one. + +Examples: + +- `((:east, :r),)` produces `[W S; N Er]`. +- `((:west, :l), (:north, :r))` produces `[Wl S; Nr E]`. +""" +function _mpo_path_result_expr(directions) + labels = [:N, :E, :S, :W] + for (direction, suffix) in directions + index = _mpo_path_direction(direction) + labels[index] = Symbol(labels[index], suffix) + end + return tensorexpr(:t, (labels[WEST], labels[SOUTH]), (labels[NORTH], labels[EAST])) +end + +""" +Act the first tensor `op` of an OBC-MPO on PEPO tensor `A` and fuse the outgoing MPO string with the virtual space of `A` along `direction`. +""" +function mpo_path_first(A::PEPOTensor, op, direction::Val{D}) where {D} + _check_pepo_first_physicalspace(A, op) + direction_index = _mpo_path_direction(D) + A′ = twistdual(A, 2) + F = _mpo_path_outgoing_fuser( + fuser(storagetype(A), domain(A, direction_index)', space(op, 3)), + direction_index, + ) + return _mpo_path_first(A′, op, F, direction) +end + +""" +Contract a prepared PEPO tensor with the first MPO tensor and its outgoing fuser. +""" +@generated function _mpo_path_first(A, op, F, ::Val{direction}) where {direction} + virtual_label = _mpo_path_virtual_label(direction) + fused_label = Symbol(virtual_label, :r) + + result_e = _mpo_path_result_expr(((direction, :r),)) + op_e = tensorexpr(:op, :dout, (:din, :r)) + A_e = tensorexpr(:A, (:din, :dout), (:N, :E, :S, :W)) + F_e = tensorexpr(:F, fused_label, (virtual_label, :r)) + rhs = Expr(:call, :*, op_e, A_e, F_e) + return macroexpand( + @__MODULE__, :(return @tensoropt $result_e := $rhs) + ) +end + +""" +Act the last tensor `op` of an OBC-MPO on PEPO tensor `A` and fuse the incoming MPO string with the virtual space of `A` along `direction`. +""" +function mpo_path_last(A::PEPOTensor, op, direction::Val{D}) where {D} + _check_pepo_last_physicalspace(A, op) + direction_index = _mpo_path_direction(D) + A′ = twistdual(A, 2) + F = _mpo_path_incoming_fuser( + fuser(storagetype(A), domain(A, direction_index), space(op, 1)'), + direction_index, + ) + return _mpo_path_last(A′, op, F, direction) +end + +""" +Contract a prepared PEPO tensor with the last MPO tensor and its incoming fuser. +""" +@generated function _mpo_path_last(A, op, F, ::Val{direction}) where {direction} + virtual_label = _mpo_path_virtual_label(direction) + fused_label = Symbol(virtual_label, :l) + + result_e = _mpo_path_result_expr(((direction, :l),)) + F_e = Expr(:call, :conj, tensorexpr(:F, fused_label, (virtual_label, :l))) + op_e = tensorexpr(:op, (:l, :dout), :din) + A_e = tensorexpr(:A, (:din, :dout), (:N, :E, :S, :W)) + rhs = Expr(:call, :*, F_e, op_e, A_e) + return macroexpand( + @__MODULE__, :(return @tensoropt $result_e := $rhs) + ) +end + +""" +Act the middle tensor `op` of an MPO on PEPO tensor `A` and fuse the incoming and outgoing MPO strings with the virtual space of `A` along `directions = (incoming, outgoing)`. +""" +function mpo_path_middle(A::PEPOTensor, op, directions::Val{D}) where {D} + incoming, outgoing = D + incoming == outgoing && + throw(ArgumentError("MPO path should enter and exit in different directions")) + _check_pepo_middle_physicalspace(A, op) + incoming_index = _mpo_path_direction(incoming) + outgoing_index = _mpo_path_direction(outgoing) + A′ = twistdual(A, 2) + Fin = _mpo_path_incoming_fuser( + fuser(storagetype(A), domain(A, incoming_index), space(op, 1)'), + incoming_index, + ) + Fout = _mpo_path_outgoing_fuser( + fuser(storagetype(A), domain(A, outgoing_index)', space(op, 4)), + outgoing_index, + ) + return _mpo_path_middle(A′, op, Fin, Fout, directions) +end + +""" +Contract a prepared PEPO tensor with a middle MPO tensor and its incoming and outgoing fusers. +""" +@generated function _mpo_path_middle( + A, op, Fin, Fout, ::Val{directions} + ) where {directions} + incoming, outgoing = directions + incoming_label = _mpo_path_virtual_label(incoming) + outgoing_label = _mpo_path_virtual_label(outgoing) + fused_incoming_label = Symbol(incoming_label, :l) + fused_outgoing_label = Symbol(outgoing_label, :r) + + result_e = _mpo_path_result_expr(((incoming, :l), (outgoing, :r))) + Fin_e = Expr( + :call, :conj, + tensorexpr(:Fin, fused_incoming_label, (incoming_label, :l)), + ) + op_e = tensorexpr(:op, (:l, :dout), (:din, :r)) + A_e = tensorexpr(:A, (:din, :dout), (:N, :E, :S, :W)) + Fout_e = tensorexpr( + :Fout, fused_outgoing_label, (outgoing_label, :r) + ) + rhs = Expr(:call, :*, Fin_e, op_e, A_e, Fout_e) + return macroexpand( + @__MODULE__, :(return @tensoropt $result_e := $rhs) + ) +end + +""" +Route an MPO virtual string with `stringspace` through a PEPO tensor `A` +along `directions = (incoming, outgoing)`. +""" +@generated function mpo_path_string( + A::PEPOTensor, stringspace::ElementarySpace, ::Val{directions} + ) where {directions} + incoming, outgoing = directions + incoming == outgoing && + throw(ArgumentError("MPO path should enter and exit in different directions")) + + incoming_index = _mpo_path_direction(incoming) + outgoing_index = _mpo_path_direction(outgoing) + incoming_label = _mpo_path_virtual_label(incoming) + outgoing_label = _mpo_path_virtual_label(outgoing) + fused_incoming_label = Symbol(incoming_label, :l) + fused_outgoing_label = Symbol(outgoing_label, :r) + + result_e = _mpo_path_result_expr(((incoming, :l), (outgoing, :r))) + Fin_e = Expr( + :call, :conj, + tensorexpr(:Fin, fused_incoming_label, (incoming_label, :l)), + ) + O_e = tensorexpr(:O, (:W, :S), (:N, :E)) + I_e = tensorexpr(:I, :l, :r) + Fout_e = tensorexpr( + :Fout, fused_outgoing_label, (outgoing_label, :r) + ) + rhs = Expr(:call, :*, Fin_e, O_e, I_e, Fout_e) + contraction = macroexpand( + @__MODULE__, :(return @tensoropt $result_e := $rhs) + ) + + return quote + O = trace_physicalspaces(A) + I = id(storagetype(A), stringspace) + Fin = _mpo_path_incoming_fuser( + fuser(storagetype(A), domain(A, $incoming_index), stringspace'), + $incoming_index, + ) + Fout = _mpo_path_outgoing_fuser( + fuser(storagetype(A), domain(A, $outgoing_index)', stringspace'), + $outgoing_index, + ) + $contraction + end +end diff --git a/src/algorithms/contractions/mpo_path/routing.jl b/src/algorithms/contractions/mpo_path/routing.jl new file mode 100644 index 000000000..ef091ed49 --- /dev/null +++ b/src/algorithms/contractions/mpo_path/routing.jl @@ -0,0 +1,223 @@ +""" +A `path => mpo` pair with one MPO tensor per site of a non-self-intersecting nearest-neighbor lattice path. +Intermediate sites carry inserted braiding tensors that propagate the MPO bond. +These properties are checked by routing validation, not enforced by this alias. +""" +const RoutedMPOTerm = Pair{<:LatticePath, <:MPOTerm} + +""" +Convert a dense term to an exact MPO in column-snake order and expand its nearest-neighbor path. + +Visit occupied columns from left to right, alternating between increasing and decreasing row indices within each column. +Permute the operator's physical legs into this order before decomposing it into an MPO. +For example, the six operator sites below are visited as `A → B → C → D → E → F`, with row indices increasing downward: + +```text + col 1 col 2 col 3 +row 1 A + --→-- E + ↓ ↑ ↓ +row 2 + D + + ↓ ↑ ↓ +row 3 B + F + ↓ ↑ +row 4 + --→-- C +``` + +The path is constructed successively between these ordered sites: + +1. `A → B`: descend from `(1, 1)` through `(2, 1)` to `(3, 1)`. +2. `B → C`: connect the column bottoms at row `max(3, 4) = 4`, passing through `(4, 1)` before reaching `(4, 2)`. +3. `C → D`: ascend through `(3, 2)` to `(2, 2)`. +4. `D → E`: connect the column tops at row `min(2, 1) = 1`, passing through `(1, 2)` before reaching `(1, 3)`. +5. `E → F`: descend through `(2, 3)` to `(3, 3)`. + +The `+` sites carry inserted braiding tensors that propagate the MPO bond without an additional physical operator. +Connecting successive columns at their outermost endpoint row avoids retracing the path: a horizontal-first connection from `B` to `C` would visit `(3, 2)`, which the later `C → D` segment needs. +""" +function _route_mpo_term( + sites::LatticePath, op::AbstractTensorMap, + lattice::Matrix{<:ElementarySpace}, + ) + isempty(sites) && throw(ArgumentError("an operator term requires at least one site")) + allunique(sites) || throw(ArgumentError("operator sites should be unique")) + length(sites) == numout(op) == numin(op) || + throw(ArgumentError("number of operator legs should match the number of sites")) + Nr, Nc = size(lattice) + for (k, site) in enumerate(sites) + V = lattice[mod1(site[1], Nr), mod1(site[2], Nc)] + V == codomain(op)[k] == domain(op)[k] || + throw(SpaceMismatch("operator physical space does not match lattice site $site")) + end + length(sites) == 1 && return copy(sites) => [op] + + columns = sort!(unique(site[2] for site in sites)) + permutation = Int[] + for (k, col) in enumerate(columns) + indices = findall(site -> site[2] == col, sites) + sort!(indices; by = i -> sites[i][1], rev = iseven(k)) + append!(permutation, indices) + end + ordered_sites = sites[permutation] + N = length(sites) + ordered_op = permute(op, (Tuple(permutation), Tuple(permutation .+ N))) + mpo = gate_to_mpo(ordered_op; trunc = notrunc()) + path = _dense_mpo_path(ordered_sites) + return _expand_mpo_path(ordered_sites, mpo, path, lattice) +end + +""" +Add trivial MPO bonds to tensor-product factors before routing them in their stored site order. +""" +function _route_mpo_term( + sites::LatticePath, factors::TensorProductTerm, + lattice::Matrix{<:ElementarySpace}, + ) + length(sites) == length(factors) || + throw(ArgumentError("number of tensor-product factors should match the number of sites")) + length(factors) == 1 && return _route_mpo_term(sites, only(factors), lattice) + mpo = map(enumerate(factors)) do (k, op) + tensor = k == 1 ? op : insertleftunit(op, 1) + return k == length(factors) ? tensor : insertrightunit(tensor, numind(tensor)) + end + return _route_mpo_term(sites, mpo, lattice) +end + +""" +Preserve an explicit MPO's factor order while connecting its sites with simple nearest-neighbor paths. +""" +function _route_mpo_term( + sites::LatticePath, mpo::MPOTerm, + lattice::Matrix{<:ElementarySpace}, + ) + _validate_mpo_term(sites, mpo, lattice) + path = _ordered_mpo_path(sites) + return _expand_mpo_path(sites, mpo, path, lattice) +end + +""" +Connect snake-ordered columns beyond their bottom or top endpoints to avoid retracing sparse columns. +""" +function _dense_mpo_path(sites::LatticePath) + path = CartesianIndex{2}[first(sites)] + column_index = 1 + for (from, to) in zip(sites, Iterators.drop(sites, 1)) + if from[2] == to[2] + append!(path, Iterators.drop(_l_path(from, to), 1)) + else + row = isodd(column_index) ? max(from[1], to[1]) : min(from[1], to[1]) + corners = (CartesianIndex(row, from[2]), CartesianIndex(row, to[2]), to) + for corner in corners + last(path) == corner && continue + append!(path, Iterators.drop(_l_path(last(path), corner), 1)) + end + column_index += 1 + end + end + return path +end + +""" +Route ordered sites with horizontal-first L paths, falling back to vertical-first paths without backtracking. +""" +function _ordered_mpo_path(sites::LatticePath) + isempty(sites) && throw(ArgumentError("an MPO term requires at least one site")) + allunique(sites) || throw(ArgumentError("operator sites should be unique")) + path = CartesianIndex{2}[first(sites)] + measured = Set(sites) + visited = Set(path) + for (from, to) in zip(sites, Iterators.drop(sites, 1)) + segment = _l_path(from, to) + if !_mpo_segment_is_free(segment, measured, visited) + segment = _l_path(from, to; horizontal_first = false) + _mpo_segment_is_free(segment, measured, visited) || throw( + ArgumentError( + "routing this MPO ordering is not implemented: no nonintersecting L path from $from to $to", + ), + ) + end + append!(path, Iterators.drop(segment, 1)) + union!(visited, segment) + end + return path +end + +""" +Check that a connecting segment neither revisits a site nor crosses another operator site. +""" +function _mpo_segment_is_free(segment, measured::Set, visited::Set) + any(site -> site in visited, @view segment[2:end]) && return false + return all(site -> !(site in measured), @view segment[2:(end - 1)]) +end + +""" +Insert braiding tensors at unmeasured path sites using periodic physical spaces and the neighboring MPO bond. +""" +function _expand_mpo_path( + sites::LatticePath, mpo::MPOTerm, + path::LatticePath, lattice::Matrix{<:ElementarySpace}, + ) + _validate_mpo_term(sites, mpo, lattice) + allunique(path) || throw(ArgumentError("the MPO path should not intersect itself")) + positions = indexin(sites, path) + all(!isnothing, positions) && issorted(positions) || + throw(ArgumentError("the MPO path should contain operator sites in MPO order")) + first(positions) == 1 && last(positions) == length(path) || + throw(ArgumentError("the MPO path should start and end at operator sites")) + for (from, to) in zip(path, Iterators.drop(path, 1)) + _step_direction(from, to) + end + + Nr, Nc = size(lattice) + k = 1 + expanded_mpo = AbstractTensorMap[] + for site in path + if site == sites[k] + op = mpo[k] + k += 1 + push!(expanded_mpo, op) + continue + end + previous = mpo[k - 1] + V = lattice[mod1(site[1], Nr), mod1(site[2], Nc)] + bond = _mpo_right_stringspace(previous)' + braid = TensorKit.BraidingTensor{scalartype(previous)}(V, bond) + push!(expanded_mpo, copy!(similar(previous, scalartype(previous), space(braid)), braid)) + end + return copy(path) => expanded_mpo +end + +""" +Return the right MPO string space in the local tensor's stored leg orientation. +""" +_mpo_right_stringspace(op::AbstractTensorMap) = space(op, numind(op)) + +""" +Build a shortest nearest-neighbor L path with the chosen horizontal or vertical first step. +""" +function _l_path( + start::CartesianIndex{2}, stop::CartesianIndex{2}; horizontal_first::Bool = true + ) + start == stop && throw(ArgumentError("MPO path sites should be unique")) + path = CartesianIndex{2}[start] + axes = horizontal_first ? (2, 1) : (1, 2) + for axis in axes + while last(path)[axis] != stop[axis] + step = sign(stop[axis] - last(path)[axis]) + delta = axis == 1 ? CartesianIndex(step, 0) : CartesianIndex(0, step) + push!(path, last(path) + delta) + end + end + return path +end + +""" +Return the cardinal direction of a nearest-neighbor step, rejecting longer or stationary steps. +""" +function _step_direction(from::CartesianIndex{2}, to::CartesianIndex{2}) + delta = to - from + delta == CartesianIndex(0, 1) && return :east + delta == CartesianIndex(0, -1) && return :west + delta == CartesianIndex(1, 0) && return :south + delta == CartesianIndex(-1, 0) && return :north + throw(ArgumentError("MPO path should use nearest-neighbor steps")) +end diff --git a/src/algorithms/contractions/patch/pepo_1layer.jl b/src/algorithms/contractions/patch/pepo_1layer.jl new file mode 100644 index 000000000..10294ffc4 --- /dev/null +++ b/src/algorithms/contractions/patch/pepo_1layer.jl @@ -0,0 +1,169 @@ +# Approximate finite-patch contractions for single-layer PEPO networks. + +""" +Return a PEPO and CTMRG environment with standard virtual-space dualness without mutating the inputs. +""" +function standardize_dualness(ρ::InfinitePEPO, env::CTMRGEnv) + isdual_easts, isdual_norths = _check_virtual_dualness(ρ) + all(isdual_easts) && all(isdual_norths) && return ρ, env + + nrows, ncols = size(ρ, 1), size(ρ, 2) + tensors = map(CartesianIndices(unitcell(ρ))) do site + row, col, layer = Tuple(site) + directions = Int[] + !isdual_norths[row, col, layer] && push!(directions, NORTH) + !isdual_easts[row, col, layer] && push!(directions, EAST) + !isdual_norths[_next(row, nrows), col, layer] && push!(directions, SOUTH) + !isdual_easts[row, _prev(col, ncols), layer] && push!(directions, WEST) + A = unitcell(ρ)[site] + return isempty(directions) ? A : flip_virtualspace(A, directions) + end + ρ′ = InfinitePEPO(tensors) + + edges = map(CartesianIndices(env.edges)) do index + direction, row, col = Tuple(index) + should_flip = if direction == NORTH + !isdual_norths[_next(row, nrows), col, 1] + elseif direction == EAST + !isdual_easts[row, _prev(col, ncols), 1] + elseif direction == SOUTH + !isdual_norths[row, col, 1] + else + !isdual_easts[row, col, 1] + end + E = env.edges[index] + return should_flip ? flip(E, 2) : E + end + env′ = CTMRGEnv(copy(env.corners), edges) + return ρ′, env′ +end + +""" +Contract a routed MPO term in its enclosing patch, rotating column sweeps into row sweeps. +""" +function _expectation_value( + ρ::InfinitePEPO, routed::RoutedMPOTerm, env::CTMRGEnv, + alg::BoundaryMPSContract, + ) + direction = alg.direction + rowrange, colrange = _patch_ranges(first(routed)) + sweep = if direction === :auto + length(colrange) >= length(rowrange) ? :rows : :columns + else + direction + end + if sweep === :rows + return _expectation_value_rows( + ρ, routed, env, rowrange, colrange, alg + ) + else + unitcell = size(ρ)[1:2] + path, mpo = routed + rotated = siterotl90.(path, Ref(unitcell)) => mpo + rotated_rowrange, rotated_colrange = _patch_ranges(first(rotated)) + return _expectation_value_rows( + rotl90(ρ), rotated, rotl90(env), + rotated_rowrange, rotated_colrange, alg + ) + end +end + +""" +Build a local tensor for row MPOs without observables by tracing the PEPO physical legs. +""" +function _patch_site_tensor( + ρ::InfinitePEPO, ::Nothing, row::Int, col::Int, + ) + return trace_physicalspaces(ρ[row, col, 1]) +end + +""" +Insert the MPO factor at a path site, or trace the PEPO physical legs at an off-path site. +""" +function _patch_site_tensor( + ρ::InfinitePEPO, routed::RoutedMPOTerm, + row::Int, col::Int, + ) + A = ρ[row, col, 1] + path, mpo = routed + k = findfirst(==(CartesianIndex(row, col)), path) + isnothing(k) && return trace_physicalspaces(A) + + if k == 1 + direction = _step_direction(path[1], path[2]) + return mpo_path_first(A, mpo[k], Val(direction)) + elseif k == length(path) + direction = _step_direction(path[end], path[end - 1]) + return mpo_path_last(A, mpo[k], Val(direction)) + else + incoming = _step_direction(path[k], path[k - 1]) + outgoing = _step_direction(path[k], path[k + 1]) + return mpo_path_middle(A, mpo[k], Val((incoming, outgoing))) + end +end + +""" +Contract and normalize a routed MPO term using row-oriented patch boundary contractions. +""" +function _expectation_value_rows( + ρ::InfinitePEPO, routed::RoutedMPOTerm, env::CTMRGEnv, + rowrange::UnitRange{Int}, colrange::UnitRange{Int}, alg::BoundaryMPSContract, + ) + ρ, env = standardize_dualness(ρ, env) + numerator = _contract_patch_rows(ρ, routed, env, rowrange, colrange, alg) + norm = _contract_patch_rows(ρ, nothing, env, rowrange, colrange, alg) + return numerator / norm +end + +""" +Contract a complete PEPO patch row by row from north to south, optionally inserting a routed MPO term. +""" +function _contract_patch_rows( + ρ::InfinitePEPO, routed::Union{Nothing, RoutedMPOTerm}, + env::CTMRGEnv, rowrange::UnitRange{Int}, colrange::UnitRange{Int}, + alg::BoundaryMPSContract, + ) + ψ = _north_boundary_mps(env, first(rowrange), colrange) + for row in rowrange + W = _row_mpo(ρ, routed, env, row, colrange) + ψ = _contract_row(W, ψ, alg) + end + south = _south_boundary_mps(env, last(rowrange), colrange) + return dot_noconj(south, ψ) +end + +""" +Build one finite row MPO from west/east CTMRG edges and the PEPO tensors inside the patch. + +Convention of west, east CTM edges and the PF tensors: +``` + [1 2; 3] [1 2; 3 4] [1 2; 3] + 3 3 1 + ↓ ↓ ↑ + E₄-←-2 1-←-O-←-4 2-←-C₂ + ↓ ↓ ↑ + 1 2 3 +``` +Legs 1, 3 need to be flipped to match standard MPS convention +""" +function _row_mpo( + ρ::InfinitePEPO, routed::Union{Nothing, RoutedMPOTerm}, + env::CTMRGEnv, row::Int, colrange::UnitRange{Int}, + ) + cmin, cmax = first(colrange), last(colrange) + W = repartition(edge(env, WEST, row, cmin - 1), 1, 2) + tensors = [insertleftunit(W, 1)] + append!( + tensors, + ( + _patch_site_tensor(ρ, routed, row, col) + for col in colrange + ), + ) + E = permute( + flip(edge(env, EAST, row, cmax + 1), (1, 3)), + ((2, 3), (1,)) + ) + push!(tensors, insertrightunit(E, 3)) + return FiniteMPO(tensors) +end diff --git a/src/algorithms/contractions/patch/tools.jl b/src/algorithms/contractions/patch/tools.jl new file mode 100644 index 000000000..98511aca7 --- /dev/null +++ b/src/algorithms/contractions/patch/tools.jl @@ -0,0 +1,71 @@ +# TODO: generalize the following to multi-layer networks + +""" +Apply a finite MPO to a finite MPS with zip-up truncation and optional DMRG refinement. +""" +function _contract_row(W::FiniteMPO, ψ::FiniteMPS, alg::BoundaryMPSContract) + ψ′, = approximate((W, ψ), alg.zipup) + isnothing(alg.dmrg) && return ψ′ + ψ′, = approximate(ψ′, (W, ψ), alg.dmrg) + return ψ′ +end + +""" +Build the finite MPS representing the north CTMRG boundary of a patch. + +Convention of CTM tensors on the north boundary is +``` + [1; 2] [1 2; 3] [1; 2] + C₁-←-2 1-←-E₁-←-3 1-←-C₂ + ↓ ↓ ↑ + 1 2 2 +``` +Leg 2 of C₂ needs to be flipped to have a non-dual physical space. +""" +function _north_boundary_mps( + env::CTMRGEnv, row::Int, colrange::UnitRange{Int}, + ) + r = row - 1 + cmin, cmax = first(colrange), last(colrange) + Cwest = insertleftunit(corner(env, NORTHWEST, r, cmin - 1), 1) + tensors = [Cwest] + append!(tensors, (edge(env, NORTH, r, col) for col in colrange)) + Ceast = repartition( + flip(corner(env, NORTHEAST, r, cmax + 1), 2), 2, 0 + ) + push!(tensors, insertleftunit(Ceast, 3)) + return FiniteMPS(tensors) +end + +""" +Build the finite MPS representing the south CTMRG boundary of a patch, +but with dual physical legs, and sites ordered from east to west. + +Convention of CTM tensors on the south boundary is +``` + [1; 2] [1 2; 3] [1; 2] + 2 2 1 + ↓ ↓ ↑ + C₄-→-1 3-→-E₃-→-1 2-→-C₃ +``` +Leg 1 of C₃ needs to be flipped to have a dual physical space. + +North site `k` pairs with south site `N + 1 - k`. +``` + west east + north: 1 ← … ← N - 1 ← N + south: N → … → 2 → 1 +``` +Viewed after a 180° rotation of the entire network, this is a north boundary ordered from west to east as usual, only with dual physical legs. +Because of this reversed site order, `AL` tensors lie to the right (east) of the canonical center in the patch, while `AR` tensors lie to its left (west). +""" +function _south_boundary_mps(env::CTMRGEnv, row::Int, colrange::UnitRange{Int}) + r = row + 1 + cmin, cmax = first(colrange), last(colrange) + Ceast = insertleftunit(flip(corner(env, SOUTHEAST, r, cmax + 1), 1), 1) + tensors = [Ceast] + append!(tensors, (edge(env, SOUTH, r, col) for col in reverse(colrange))) + Cwest = repartition(corner(env, SOUTHWEST, r, cmin - 1), 2, 0) + push!(tensors, insertleftunit(Cwest, 3)) + return FiniteMPS(tensors) +end diff --git a/src/algorithms/contractions/transfer.jl b/src/algorithms/contractions/transfer.jl index 19ac6db38..59a79d301 100644 --- a/src/algorithms/contractions/transfer.jl +++ b/src/algorithms/contractions/transfer.jl @@ -247,3 +247,25 @@ function edge_transfer_right( Ebot[χ_SE D_S; χ_SW] * O[D_W D_S; D_N D_E] end + +""" +Map north-boundary site `k` to the corresponding site in the east-to-west south boundary. +`N` is the finite patch length, including the two boundary sites. +""" +south_site(k::Int, N::Int) = N + 1 - k + +""" +Contract opposite-oriented boundary MPSs without conjugation. +""" +function dot_noconj(south::FiniteMPS, north::FiniteMPS) + N = length(north) + length(south) == N || throw(DimensionMismatch("boundary lengths must match")) + right = isomorphism(storagetype(north.AR[N]), domain(north.AR[N]), space(south.AL[1], 1)) + for k in N:-1:1 + top = k == 1 ? north.AC[k] : north.AR[k] + bottom = k == 1 ? south.AC[N] : south.AL[south_site(k, N)] + right = edge_transfermatrix(top, bottom) * right + end + left = isomorphism(storagetype(right), domain(south.AC[N]), space(north.AC[1], 1)) + return tr(left * right) +end diff --git a/src/algorithms/expectation_value/algorithms.jl b/src/algorithms/expectation_value/algorithms.jl new file mode 100644 index 000000000..1540c396f --- /dev/null +++ b/src/algorithms/expectation_value/algorithms.jl @@ -0,0 +1,53 @@ +""" +Select the contraction method used to evaluate local expectation values. +""" +abstract type ContractionAlgorithm end + +""" + ExactContract() + +Contract each local expectation-value patch exactly, without boundary-MPS truncation. +This is the default algorithm for [`expectation_value`](@ref). +""" +struct ExactContract <: ContractionAlgorithm end + +""" + BoundaryMPSContract(; trunc = nothing, maxiter = 1, direction = :auto) + BoundaryMPSContract(zipup, dmrg; direction = :auto) + +Approximately contract single-layer PEPO expectation values using boundary-MPS zipup sweeps. +Each term is normalized in its own enclosing patch. +Dense terms are reordered into a column-wise snake and decomposed into MPOs without truncation. +Explicit [`MPOTerm`](@ref) factors retain their order and are connected by non-self-intersecting nearest-neighbor paths. +Tensor-product terms are routed with trivial MPO bonds. +Routing tries horizontal-first and then vertical-first shortest connections; more complicated explicit MPO routes raise a not-implemented error. +Single-site terms are evaluated exactly. +The operator decomposition is exact; `trunc` controls only boundary-MPS truncation. +By default (`trunc = nothing`), the rank is limited to the largest CTMRG boundary dimension. +After each zipup step, `maxiter` single-site DMRG sweeps refine the result; use zero to disable refinement. +Alternatively, supply the zipup and DMRG algorithms directly, using `dmrg = nothing` to disable refinement. +The fields `zipup` and `dmrg` store these algorithms; `zipup = nothing` selects zipup truncation from the environment at evaluation time. + +With `direction = :auto`, wide and square patches are contracted north to south, and tall patches east to west. +Use `direction = :rows` or `:columns` to select an orientation explicitly. + +Pass this algorithm as `expectation_value(ρ, O, env, BoundaryMPSContract(; kwargs...))`. +""" +struct BoundaryMPSContract{Z, D} <: ContractionAlgorithm + zipup::Z + dmrg::D + direction::Symbol + + function BoundaryMPSContract(zipup, dmrg; direction::Symbol = :auto) + direction in (:auto, :rows, :columns) || + throw(ArgumentError("invalid sweep direction: $direction")) + return new{typeof(zipup), typeof(dmrg)}(zipup, dmrg, direction) + end +end + +function BoundaryMPSContract(; trunc = nothing, maxiter::Int = 1, direction::Symbol = :auto) + maxiter >= 0 || throw(ArgumentError("maxiter should be nonnegative")) + zipup = isnothing(trunc) ? nothing : Zipup(; trunc) + dmrg = iszero(maxiter) ? nothing : DMRG(; maxiter, verbosity = 0) + return BoundaryMPSContract(zipup, dmrg; direction) +end diff --git a/src/algorithms/expectation_value/boundary_mps.jl b/src/algorithms/expectation_value/boundary_mps.jl new file mode 100644 index 000000000..7b6ed4142 --- /dev/null +++ b/src/algorithms/expectation_value/boundary_mps.jl @@ -0,0 +1,46 @@ +# Boundary-MPS contraction of individual local terms +# -------------------------------------------------- + +""" +Validate a single-layer PEPO and resolve the default zipup truncation from its CTMRG environment. +""" +function _prepare_contract(ρ::InfinitePEPO, env::CTMRGEnv, alg::BoundaryMPSContract) + size(ρ, 3) == 1 || throw(DimensionMismatch("only single-layer PEPO contractions are supported")) + isnothing(alg.zipup) || return alg + return BoundaryMPSContract(Zipup(; trunc = _default_truncation(env, alg)), alg.dmrg; direction = alg.direction) +end + +""" +Evaluate a dense or MPO term, using exact single-site contractions and routing larger terms. +""" +function local_expectation_value( + sites::Vector{CartesianIndex{2}}, ρ::InfinitePEPO, + term::Union{AbstractTensorMap, MPOTerm}, env::CTMRGEnv, + alg::BoundaryMPSContract, + ) + if _local_term_iszero(term) + return zero(promote_type(scalartype(ρ), scalartype(env), scalartype(term))) + end + if length(sites) == 1 + return local_expectation_value(sites, ρ, term, env, ExactContract()) + end + routed = _route_mpo_term(sites, term, physicalspace(ρ)) + return _expectation_value(ρ, routed, env, alg) +end + + +""" +Return the largest CTMRG boundary-space dimension appearing in the corner tensors. +""" +function _ctmrg_boundary_chi(env::CTMRGEnv) + χ = 0 + for C in env.corners + χ = max(χ, dim(space(C, 1)), dim(space(C, 2))) + end + return χ +end + +""" +Construct the default rank truncation from the largest CTMRG boundary dimension. +""" +_default_truncation(env::CTMRGEnv, ::BoundaryMPSContract) = truncrank(_ctmrg_boundary_chi(env)) diff --git a/src/algorithms/expectation_value/expectation_value.jl b/src/algorithms/expectation_value/expectation_value.jl index 7c83aac90..71cb02ef5 100644 --- a/src/algorithms/expectation_value/expectation_value.jl +++ b/src/algorithms/expectation_value/expectation_value.jl @@ -2,54 +2,69 @@ # ------------------------------------ """ - expectation_value(state, O::LocalOperator, env) - expectation_value(bra, O::LocalOperator, ket, env) + expectation_value(state, O::LocalOperator, env, alg = ExactContract()) + expectation_value(bra, O::LocalOperator, ket, env, alg = ExactContract()) Compute the expectation value ⟨bra|O|ket⟩ / ⟨bra|ket⟩ or tr(O * state) / tr(state) of a [`LocalOperator`](@ref) `O`. This can be done either for a PEPS, or alternatively for a density matrix PEPO. -In the latter case the first signature corresponds to a single layer PEPO contraction, while -the second signature yields a bilayer contraction instead. +In the latter case the first signature corresponds to a single layer PEPO contraction, while the second signature yields a bilayer contraction instead. +The default [`ExactContract`](@ref) contracts each patch exactly. +For single-layer PEPOs with a CTMRG environment, use [`BoundaryMPSContract`](@ref) to select approximate boundary-MPS contractions. """ function MPSKit.expectation_value( - bra::S, O::LocalOperator, ket::S, env + bra::S, O::LocalOperator, ket::S, env, alg::ExactContract = ExactContract(), ) where {S <: InfiniteState} - checklattice(bra, O, ket) - term_vals = dtmap(collect(O.terms)) do (inds, operator) # OhMyThreads can't iterate over O.terms directly - return local_expectation_value(inds, bra, operator, ket, env) - end - return sum(term_vals) + return _expectation_value(bra, O, env, alg, ket) end -MPSKit.expectation_value(peps::InfinitePEPS, O::LocalOperator, env) = expectation_value(peps, O, peps, env) -function MPSKit.expectation_value(state::InfinitePEPO, O::LocalOperator, env) - checklattice(state, O) +MPSKit.expectation_value(peps::InfinitePEPS, O::LocalOperator, env, alg::ExactContract = ExactContract()) = + expectation_value(peps, O, peps, env, alg) +MPSKit.expectation_value(state::InfinitePEPO, O::LocalOperator, env, alg::ContractionAlgorithm = ExactContract()) = + _expectation_value(state, O, env, alg) + +""" +Validate the lattice, prepare the contraction algorithm, and sum independently normalized local terms. +""" +function _expectation_value(state::InfiniteState, O::LocalOperator, env, alg::ContractionAlgorithm, ket::InfiniteState...) + checklattice(state, O, ket...) + alg = _prepare_contract(state, env, alg) + isempty(O.terms) && return zero(promote_type(scalartype(state), scalartype(env))) term_vals = dtmap(collect(O.terms)) do (inds, operator) # OhMyThreads can't iterate over O.terms directly - return local_expectation_value(inds, state, operator, env) + return local_expectation_value(inds, state, operator, ket..., env, alg) end return sum(term_vals) end +""" +Prepare environment-dependent contraction settings, leaving exact contraction unchanged. +""" +_prepare_contract(state::InfiniteState, env, alg::ExactContract) = alg + # Expectation value of an individual local term # --------------------------------------------- """ - local_expectation_value(inds, bra, operator, ket, env) - local_expectation_value(inds, state, operator, env) + local_expectation_value(inds, bra, operator, ket, env, alg = ExactContract()) + local_expectation_value(inds, state, operator, env, alg = ExactContract()) Compute the contribution of a single term of a [`LocalOperator`](@ref) to the expectation value ⟨bra|O|ket⟩ / ⟨bra|ket⟩ or tr(O * state) / tr(state), where `operator` is the local term acting on the sites `inds`. -The implementation is overloaded based on the type of operator to be evaluated +Dispatch on the operator and contraction algorithm selects how each term is evaluated. """ function local_expectation_value end # AbstractTensorMap evaluation goes through reduced density matrix -function local_expectation_value(inds, bra, operator::AbstractTensorMap, ket, env) +function local_expectation_value( + inds, bra::S, operator::AbstractTensorMap, ket::S, env, ::ExactContract = ExactContract(), + ) where {S <: InfiniteState} ρ = reduced_densitymatrix(inds, ket, bra, env) return trmul(operator, ρ) end -function local_expectation_value(inds, state, operator::AbstractTensorMap, env) +function local_expectation_value( + inds, state::InfinitePEPO, operator::AbstractTensorMap, env, ::ExactContract = ExactContract(), + ) ρ = reduced_densitymatrix(inds, state, env) return trmul(operator, ρ) end @@ -61,24 +76,28 @@ Compute the contribution of an [`MPOTerm`](@ref), including a [`TensorProductTer For a PEPS or purified PEPO, compute ``⟨bra|O|ket⟩ / ⟨bra|ket⟩``; for a single-layer density matrix PEPO, compute ``tr(O * state) / tr(state)``. Insert the factors into the patch contraction directly and divide by the local norm of the same patch. """ -function local_expectation_value(inds, bra, operator::MPOTerm, ket, env) +function local_expectation_value( + inds, bra::S, operator::MPOTerm, ket::S, env, ::ExactContract = ExactContract(), + ) where {S <: InfiniteState} return contract_local_operator(inds, operator, ket, bra, env) / contract_local_norm(inds, ket, bra, env) end -function local_expectation_value(inds, state, operator::MPOTerm, env) +function local_expectation_value( + inds, state::InfinitePEPO, operator::MPOTerm, env, ::ExactContract = ExactContract(), + ) return contract_local_operator(inds, operator, state, env) / contract_local_norm(inds, state, env) end # TODO: Implement boundary_contraction_expr for BPEnv to contract its messages directly. -local_expectation_value(inds, bra, operator::MPOTerm, ket, env::BPEnv) = - local_expectation_value(inds, bra, operator, ket, CTMRGEnv(env)) +local_expectation_value(inds, bra::S, operator::MPOTerm, ket::S, env::BPEnv, alg::ExactContract = ExactContract()) where {S <: InfiniteState} = + local_expectation_value(inds, bra, operator, ket, CTMRGEnv(env), alg) # Expectation value of a local partition function tensor # ------------------------------------------------------ """ - expectation_value(pf::InfinitePartitionFunction, inds => O, env::CTMRGEnv) + expectation_value(pf::InfinitePartitionFunction, inds => O, env::CTMRGEnv, alg = ExactContract()) Compute the expectation value corresponding to inserting a local tensor(s) `O` at position `inds` in the partition function `pf` and contracting the whole using a given CTMRG @@ -91,13 +110,13 @@ convention. function MPSKit.expectation_value( pf::InfinitePartitionFunction, op::Pair{CartesianIndex{2}, <:AbstractTensorMap{T, S, 2, 2}}, - env, + env, ::ExactContract = ExactContract(), ) where {T, S} return contract_local_tensor(op[1], op[2], env) / contract_local_tensor(op[1], pf[op[1]], env) end function MPSKit.expectation_value( - pf::InfinitePartitionFunction, op::Pair{Tuple{Int, Int}}, env + pf::InfinitePartitionFunction, op::Pair{Tuple{Int, Int}}, env, alg::ExactContract = ExactContract(), ) - return expectation_value(pf, CartesianIndex(op[1]) => op[2], env) + return expectation_value(pf, CartesianIndex(op[1]) => op[2], env, alg) end diff --git a/src/utility/indexing.jl b/src/utility/indexing.jl index cc5fa1249..de0b166b8 100644 --- a/src/utility/indexing.jl +++ b/src/utility/indexing.jl @@ -1,3 +1,9 @@ +""" +An ordered sequence of sites on a two-dimensional lattice. +Nearest-neighbor connectivity and nonintersection are checked by routing functions, not enforced by this alias. +""" +const LatticePath = AbstractVector{CartesianIndex{2}} + # Get next and previous directional CTMRG environment index, respecting periodicity _next(i, total) = mod1(i + 1, total) _prev(i, total) = mod1(i - 1, total) diff --git a/test/testsuite/TestSuite.jl b/test/testsuite/TestSuite.jl index a1d493f41..12fda5d2a 100644 --- a/test/testsuite/TestSuite.jl +++ b/test/testsuite/TestSuite.jl @@ -253,6 +253,18 @@ module ToolboxDensityMatrices end using .ToolboxDensityMatrices +module ToolboxExpvalBoundaryMPS + include("toolbox/expval_boundary_mps.jl") + export toolbox_expval_boundary_mps, toolbox_expval_boundary_mps_localoperator +end +using .ToolboxExpvalBoundaryMPS + +module ToolboxMPORouting + include("toolbox/mpo_routing.jl") + export toolbox_mpo_routing_fusers, toolbox_mpo_routing_identities, toolbox_mpo_routing_paths +end +using .ToolboxMPORouting + module ToolboxTensorProductTerms include("toolbox/tensorproduct_terms.jl") export toolbox_tensorproduct_ising, toolbox_tensorproduct_bookkeeping diff --git a/test/testsuite/toolbox/expval_boundary_mps.jl b/test/testsuite/toolbox/expval_boundary_mps.jl new file mode 100644 index 000000000..f94ad3cf1 --- /dev/null +++ b/test/testsuite/toolbox/expval_boundary_mps.jl @@ -0,0 +1,142 @@ +using TensorKit +using PEPSKit +using MPSKit +using Test +using Adapt +using Random + +const CI = CartesianIndex + +spaces = Dict( + U1Irrep => ( + U1Space(1 => 2, -1 => 1), + U1Space(1 => 1, 0 => 1, -1 => 2), + U1Space(1 => 1, 0 => 1, -1 => 2), + ), + FermionParity => ( + Vect[FermionParity](0 => 1, 1 => 1), + Vect[FermionParity](0 => 1, 1 => 2), + Vect[FermionParity](0 => 2, 1 => 2), + ), +) + +sites_list = ( + [CI(1, 1), CI(1, 2)], # horizontal + [CI(1, 1), CI(2, 1)], # vertical + [CI(1, 1), CI(2, 2)], # turned + [CI(2, 2), CI(1, 1)], # reversed turned + [CI(2, 1), CI(1, 1), CI(1, 2), CI(2, 2)], # U-shaped +) + +""" +Check approximate expectation values against exact single-layer PEPO contractions. +""" +function toolbox_expval_boundary_mps(AT) + return @testset "Single-layer PEPO ($S) ($AT)" for S in keys(spaces) + Random.seed!(1234) + + d, D, χ = spaces[S] + ρ = adapt(AT, InfinitePEPO(d, D; unitcell = (2, 2, 1))) + env = CTMRGEnv(InfinitePartitionFunction(ρ), χ) + lattice = physicalspace(ρ) + trunc = notrunc() + + # Dense terms may change MPO order when forming a snake; explicit MPOs must keep theirs. + # Exact contractions expose permutation or braiding errors in both paths and sweep orientations. + for sites in sites_list + n = length(sites) + op = adapt(AT, randn(ComplexF64, d^n → d^n)) + mpo = PEPSKit.gate_to_mpo(op; trunc) + dense = LocalOperator(lattice, sites => op) + factorized = LocalOperator(lattice, sites => mpo) + exact = expectation_value(ρ, dense, env, ExactContract()) + for observable in (dense, factorized), direction in (:rows, :columns) + @test expectation_value(ρ, observable, env, BoundaryMPSContract(; trunc, maxiter = 0, direction)) ≈ exact + end + # Square patches must default to row sweeps. + if sites == sites_list[3] + auto = expectation_value(ρ, dense, env, BoundaryMPSContract(; trunc = truncrank(2), maxiter = 0)) + rows = expectation_value(ρ, dense, env, BoundaryMPSContract(; trunc = truncrank(2), maxiter = 0, direction = :rows)) + @test auto == rows + end + end + end +end + +""" +Check single-site dispatch, sparse snakes, and sums of independently normalized terms. +""" +function toolbox_expval_boundary_mps_localoperator(AT) + return @testset "LocalOperator interface ($AT)" begin + Random.seed!(4321) + d = Vect[FermionParity](0 => 1, 1 => 1) + ρ = adapt(AT, InfinitePEPO(d, d; unitcell = (2, 2, 1))) + env = CTMRGEnv(InfinitePartitionFunction(ρ), d) + lattice = physicalspace(ρ) + trunc = notrunc() + + # Single-site terms bypass MPO decomposition, which requires at least two sites. + op1 = adapt(AT, randn(ComplexF64, d → d)) + one_site = LocalOperator(lattice, [CI(1, 1)] => op1) + one_factor = LocalOperator(lattice, [CI(1, 1)] => [op1]) + for observable in (one_site, one_factor) + @test expectation_value(ρ, observable, env, BoundaryMPSContract(; trunc, maxiter = 0)) ≈ + expectation_value(ρ, one_site, env) + end + + # Default truncation is resolved from the environment when the algorithm is applied. + identity = LocalOperator(lattice, [CI(1, 1), CI(2, 1)] => id(d ⊗ d)) + @test expectation_value(ρ, identity, env, BoundaryMPSContract(; maxiter = 0)) ≈ 1 + for alg in ( + BoundaryMPSContract(; trunc = truncrank(2)), + BoundaryMPSContract(Zipup(; trunc = truncrank(2)), DMRG(; maxiter = 1, verbosity = 0)), + ) + @test expectation_value(ρ, identity, env, alg) ≈ 1 + end + @test_throws ArgumentError BoundaryMPSContract(; maxiter = -1) + @test_throws ArgumentError BoundaryMPSContract(; direction = :invalid) + + # A greedy horizontal-first route revisits a site for this support. + # The dense snake must connect outside the column's endpoints and preserve the operator. + op3 = adapt(AT, randn(ComplexF64, d^3 → d^3)) + snake = LocalOperator(lattice, [CI(1, 0), CI(0, 1), CI(2, 1)] => op3) + @test expectation_value(ρ, snake, env, BoundaryMPSContract(; trunc, maxiter = 0)) ≈ + expectation_value(ρ, snake, env) + + # These terms use different normalization patches; the gapped MPO also inserts a string. + # Non-unit-cell coordinates and both sweeps exercise translation and rotation of the expanded path. + op2 = adapt(AT, randn(ComplexF64, d^2 → d^2)) + sites2 = [CI(-1, 0), CI(-1, 2)] + mixed = LocalOperator(lattice, [CI(1, 1)] => op1, sites2 => PEPSKit.gate_to_mpo(op2; trunc)) + dense_sum = LocalOperator(lattice, [CI(1, 1)] => op1, sites2 => op2) + for direction in (:rows, :columns) + @test expectation_value(ρ, mixed, env, BoundaryMPSContract(; trunc, maxiter = 0, direction)) ≈ + expectation_value(ρ, dense_sum, env) + end + + # Tensor-product terms use trivial MPO bonds, including bulk factors and gapped paths. + for sites in ([CI(1, 1), CI(1, 3)], [CI(1, 1), CI(2, 1), CI(2, 3)]) + factors = [adapt(AT, randn(ComplexF64, d → d)) for _ in sites] + product = LocalOperator(lattice, sites => factors) + exact = expectation_value(ρ, product, env) + for direction in (:rows, :columns) + @test expectation_value(ρ, product, env, BoundaryMPSContract(; trunc, maxiter = 0, direction)) ≈ exact + end + end + + # Complex scaling leaves real factors in the MPO; expansion must retain a valid mixed-scalar container. + real_op = real(op2) + real_mpo = LocalOperator(lattice, sites2 => PEPSKit.gate_to_mpo(real_op; trunc)) + coefficient = 2 + 3im + @test expectation_value(ρ, coefficient * real_mpo, env, BoundaryMPSContract(; trunc, maxiter = 0)) ≈ + coefficient * expectation_value(ρ, LocalOperator(lattice, sites2 => real_op), env) + + # Constructors discard zero terms, so an empty sum must produce a scalar zero without contracting. + for alg in (ExactContract(), BoundaryMPSContract()) + @test iszero(expectation_value(ρ, LocalOperator(lattice), env, alg)) + end + # Reject a mismatched unit cell even when the individual operator's physical space matches. + wrong_lattice = LocalOperator(fill(d, 1, 1), [CI(1, 1)] => op1) + @test_throws ArgumentError expectation_value(ρ, wrong_lattice, env, BoundaryMPSContract()) + end +end diff --git a/test/testsuite/toolbox/mpo_routing.jl b/test/testsuite/toolbox/mpo_routing.jl new file mode 100644 index 000000000..96cbf851d --- /dev/null +++ b/test/testsuite/toolbox/mpo_routing.jl @@ -0,0 +1,153 @@ +using PEPSKit +using TensorKit +using Test +using Adapt +using Random + +const directions = (:north, :east, :south, :west) + +spaces = Dict( + U1Irrep => ( + Rep[U₁](0 => 1, 1 => 1), + Rep[U₁](0 => 1, 1 => 1, -1 => 1), + Rep[U₁](1 => 1), + ), + FermionParity => ( + Vect[FermionParity](0 => 1, 1 => 1), + Vect[FermionParity](0 => 1, 1 => 1), + Vect[FermionParity](1 => 1), + ), +) + +""" +Check fermionic fuser flips and twists for each MPO routing direction. +""" +function toolbox_mpo_routing_fusers(AT) + return @testset "Fuser flips and twists ($AT)" begin + d = Vect[FermionParity](0 => 1, 1 => 1) + D = Vect[FermionParity](0 => 1, 1 => 1) + ρ = adapt(AT, InfinitePEPO(d, D; unitcell = (2, 2, 1))) + A = ρ[1, 1, 1] + Bh = ρ[1, 2, 1] + Bv = ρ[2, 1, 1] + A′ = PEPSKit.twistdual(A, 2) + Bh′ = PEPSKit.twistdual(Bh, 2) + Bv′ = PEPSKit.twistdual(Bv, 2) + + op = adapt(AT, randn(ComplexF64, d^2 → d^2)) + mpo = PEPSKit.gate_to_mpo(op; trunc = notrunc()) + + first_tensor = PEPSKit.mpo_path_first(A, first(mpo), Val(:east)) + last_tensor = PEPSKit.mpo_path_last(Bh, last(mpo), Val(:west)) + @tensor exact[W1 S1 S2; N1 N2 E2] := op[po1 po2; pi1 pi2] * + A′[pi1 po1; N1 x S1 W1] * Bh′[pi2 po2; N2 E2 S2 x] + @tensor routed[W1 S1 S2; N1 N2 E2] := + first_tensor[W1 S1; N1 x] * last_tensor[x S2; N2 E2] + @test routed ≈ exact + + first_tensor = PEPSKit.mpo_path_first(Bh, first(mpo), Val(:west)) + last_tensor = PEPSKit.mpo_path_last(A, last(mpo), Val(:east)) + @tensor exact[W2 S1 S2; N1 E1 N2] := op[po1 po2; pi1 pi2] * + Bh′[pi1 po1; N1 E1 S1 x] * A′[pi2 po2; N2 x S2 W2] + @tensor routed[W2 S1 S2; N1 E1 N2] := + first_tensor[x S1; N1 E1] * last_tensor[W2 S2; N2 x] + @test routed ≈ exact + + first_tensor = PEPSKit.mpo_path_first(A, first(mpo), Val(:south)) + last_tensor = PEPSKit.mpo_path_last(Bv, last(mpo), Val(:north)) + @tensor exact[W1 W2 S2; N1 E1 E2] := op[po1 po2; pi1 pi2] * + A′[pi1 po1; N1 E1 x W1] * Bv′[pi2 po2; x E2 S2 W2] + @tensor routed[W1 W2 S2; N1 E1 E2] := + first_tensor[W1 x; N1 E1] * last_tensor[W2 S2; x E2] + @test routed ≈ exact + + first_tensor = PEPSKit.mpo_path_first(Bv, first(mpo), Val(:north)) + last_tensor = PEPSKit.mpo_path_last(A, last(mpo), Val(:south)) + @tensor exact[W1 S1 W2; E1 N2 E2] := op[po1 po2; pi1 pi2] * + Bv′[pi1 po1; x E1 S1 W1] * A′[pi2 po2; N2 E2 x W2] + @tensor routed[W1 S1 W2; E1 N2 E2] := + first_tensor[W1 S1; x E1] * last_tensor[W2 x; N2 E2] + @test routed ≈ exact + end +end + +""" +Check MPO endpoint shapes and string-routing identities for each symmetry. +""" +function toolbox_mpo_routing_identities(AT) + return @testset "Routing identities ($S) ($AT)" for S in keys(spaces) + Random.seed!(1234) + d, D, stringspace = spaces[S] + ρ = adapt(AT, InfinitePEPO(d, D; unitcell = (1, 1, 1))) + op = adapt(AT, rand(ComplexF64, d^2 → d^2)) + mpo = PEPSKit.gate_to_mpo(op; trunc = notrunc()) + + A = ρ[1, 1, 1] + for direction in directions + first_tensor = PEPSKit.mpo_path_first(A, first(mpo), Val(direction)) + last_tensor = PEPSKit.mpo_path_last(A, last(mpo), Val(direction)) + @test (numout(first_tensor), numin(first_tensor)) == (2, 2) + @test (numout(last_tensor), numin(last_tensor)) == (2, 2) + end + + middle = adapt(AT, TensorMap(TensorKit.BraidingTensor{ComplexF64}(d, stringspace))) + for incoming in directions, outgoing in directions + incoming == outgoing && continue + tensor = PEPSKit.mpo_path_middle(A, middle, Val((incoming, outgoing))) + string_tensor = PEPSKit.mpo_path_string( + A, stringspace, Val((incoming, outgoing)) + ) + @test (numout(tensor), numin(tensor)) == (2, 2) + @test string_tensor ≈ tensor + end + end +end + +""" +Check routing choices, dense leg permutations, and periodic string insertion. +""" +function toolbox_mpo_routing_paths(AT) + return @testset "MPO paths ($AT)" begin + Random.seed!(1234) + CI = CartesianIndex + + # The first horizontal L crosses a later operator site, so routing must try the vertical L. + # Conversely, a collinear out-of-order MPO cannot be connected by either supported L path. + fallback_sites = CI.([(1, 1), (3, 3), (1, 2)]) + @test PEPSKit._ordered_mpo_path(fallback_sites) == + CI.([(1, 1), (2, 1), (3, 1), (3, 2), (3, 3), (2, 3), (1, 3), (1, 2)]) + @test_throws r"routing this MPO ordering is not implemented" PEPSKit._ordered_mpo_path( + CI.([(1, 1), (1, 3), (1, 2)]) + ) + + # Reconstructing on unequal physical spaces catches mismatches between the snake order and either group of permuted physical legs. + lattice = [ℂ^2 ℂ^3; ℂ^1 ℂ^2] + sites = CI.([(2, 2), (1, 1), (1, 2), (2, 1)]) + physical = foldl(⊗, lattice[sites]) + op = adapt(AT, randn(ComplexF64, physical ← physical)) + path, expanded = PEPSKit._route_mpo_term(sites, op, lattice) + @test path == sites[[2, 4, 1, 3]] + @tensor reconstructed[p1 p2 p3 p4; q1 q2 q3 q4] := + expanded[1][p1; q1 a] * expanded[2][a p2; q2 b] * + expanded[3][b p3; q3 c] * expanded[4][c p4; q4] + @test reconstructed ≈ permute(op, ((2, 4, 1, 3), (6, 8, 5, 7))) + + # Intermediate sites have different physical spaces from the endpoints and lie outside the unit cell. + # Each inserted braid must therefore use periodic lookup and the MPO's storage type. + @testset "Periodic strings ($S)" for S in keys(spaces) + physical, _, _ = spaces[S] + intermediate = physical ⊕ physical + lattice = [physical intermediate; intermediate physical] + op = adapt(AT, randn(ComplexF64, physical^2 ← physical^2)) + mpo = PEPSKit.gate_to_mpo(op; trunc = notrunc()) + path, expanded = PEPSKit._route_mpo_term(CI.([(0, 0), (2, 2)]), mpo, lattice) + for k in 2:(length(path) - 1) + site = path[k] + V = lattice[mod1(site[1], 2), mod1(site[2], 2)] + braid = adapt(AT, TensorMap(TensorKit.BraidingTensor{ComplexF64}(V, space(mpo[2], 1)))) + @test expanded[k] ≈ braid + end + @test all(t -> storagetype(t) == storagetype(mpo[1]), expanded) + end + end +end diff --git a/test/toolbox/expval_boundary_mps.jl b/test/toolbox/expval_boundary_mps.jl new file mode 100644 index 000000000..821efd966 --- /dev/null +++ b/test/toolbox/expval_boundary_mps.jl @@ -0,0 +1,12 @@ +using Test +using PEPSKit + +@isdefined(TestSuite) || include("../testsuite/TestSuite.jl") +using .TestSuite + +is_buildkite = get(ENV, "BUILDKITE", "false") == "true" + +if !is_buildkite + TestSuite.toolbox_expval_boundary_mps(Vector) + TestSuite.toolbox_expval_boundary_mps_localoperator(Vector) +end diff --git a/test/toolbox/mpo_routing.jl b/test/toolbox/mpo_routing.jl new file mode 100644 index 000000000..49c08c02b --- /dev/null +++ b/test/toolbox/mpo_routing.jl @@ -0,0 +1,13 @@ +using Test +using PEPSKit + +@isdefined(TestSuite) || include("../testsuite/TestSuite.jl") +using .TestSuite + +is_buildkite = get(ENV, "BUILDKITE", "false") == "true" + +if !is_buildkite + TestSuite.toolbox_mpo_routing_fusers(Vector) + TestSuite.toolbox_mpo_routing_identities(Vector) + TestSuite.toolbox_mpo_routing_paths(Vector) +end diff --git a/test/types/localoperator.jl b/test/types/localoperator.jl index 89f487ddd..b790a8e02 100644 --- a/test/types/localoperator.jl +++ b/test/types/localoperator.jl @@ -54,6 +54,90 @@ if !is_buildkite @test length(op5.terms) == 2 end + @testset "LocalOperator MPO bookkeeping" begin + d = ℂ^2 + lattice = fill(d, 2, 2) + dense = randn(Float64, d ⊗ d ← d ⊗ d) + mpo = PEPSKit.gate_to_mpo(dense; trunc = notrunc()) + sites = CartesianIndex.([(3, 4), (3, 3)]) + original_sites, original_mpo = copy(sites), copy(mpo) + operator = LocalOperator(lattice, sites => mpo) + stored_sites, stored_mpo = only(operator.terms) + + # Construction translates a copy of the coordinates and must retain the caller's MPO order. + # Mutating either input container afterwards must not alter the stored term. + @test sites == original_sites + reverse!(sites) + reverse!(mpo) + @test stored_sites == CartesianIndex.([(1, 2), (1, 1)]) + @test stored_mpo == original_mpo + + # Scaling every factor would multiply the operator by α^N; only one factor may change. + # A complex coefficient must also widen the container without mutating the original tensors. + α = 2 + 3im + snapshot = deepcopy(stored_mpo) + scaled_mpo = last(only((α * operator).terms)) + @test first(scaled_mpo) ≈ α * first(stored_mpo) + @test last(scaled_mpo) ≈ last(stored_mpo) + @test scalartype(scaled_mpo) == ComplexF64 + @test stored_mpo == snapshot + onsite = randn(ComplexF64, d ← d) + mixed = operator + LocalOperator(lattice, ((2, 1),) => onsite) + @test scalartype(mixed) == ComplexF64 + + # Taking real/imaginary parts factorwise does not give the real/imaginary part of an MPO. + @test_throws ArgumentError real(mixed) + @test_throws ArgumentError imag(mixed) + + # Insertion and operator addition use different accumulation paths; both must reject MPO sums. + # Dense terms sharing the same sites must still accumulate normally. + inds = CartesianIndex.([(1, 1), (1, 2)]) + dense_operator = LocalOperator(lattice, inds => dense) + mpo_operator = LocalOperator(lattice, inds => original_mpo) + @test_throws ArgumentError PEPSKit.add_term!(mpo_operator, inds, dense) + @test_throws ArgumentError PEPSKit.add_term!(dense_operator, inds, original_mpo) + @test_throws ArgumentError mpo_operator + mpo_operator + @test_throws ArgumentError mpo_operator + dense_operator + @test_throws ArgumentError dense_operator + mpo_operator + @test last(only((dense_operator + dense_operator).terms)) ≈ 2 * dense + + # Drop zero factors before they reach boundary-MPS normalization, where they could cause 0/0. + @test isempty(LocalOperator(lattice, inds => [zero(first(original_mpo)), last(original_mpo)]).terms) + + # Unequal physical spaces expose accidental factor reordering during coordinate transformations. + lattice = [ℂ^2 ℂ^3 ℂ^4; ℂ^5 ℂ^6 ℂ^7] + dense = randn(Float64, ℂ^6 ⊗ ℂ^2 ← ℂ^6 ⊗ ℂ^2) + mpo = PEPSKit.gate_to_mpo(dense; trunc = notrunc()) + operator = LocalOperator(lattice, ((2, 2), (1, 1)) => mpo) + @test rotr90(rotl90(operator)) == operator + @test last(only(rotr90(operator).terms)) == mpo + sites, term = only(operator.terms) + @test repeat(operator, 2, 1).terms == Dict(sites => term, (sites .+ CartesianIndex(2, 0)) => term) + end + + @testset "MPO validation" begin + d, b1, b2 = ℂ^2, ℂ^3, ℂ^4 + lattice = fill(d, 2, 2) + first_tensor = randn(Float64, d ← d ⊗ b1) + last_tensor = randn(Float64, b1 ⊗ d ← d) + mpo = [first_tensor, last_tensor] + sites = ((1, 1), (1, 2)) + + # Reject malformed chains at construction, before any routing or contraction is attempted. + @test_throws ArgumentError LocalOperator(lattice, CartesianIndex{2}[] => AbstractTensorMap[]) + @test_throws ArgumentError LocalOperator(lattice, ((1, 1),) => mpo) + @test_throws ArgumentError LocalOperator(lattice, ((1, 1), (1, 1)) => mpo) + @test_throws ArgumentError LocalOperator(lattice, sites => reverse(mpo)) + + # Bond matching and the two physical legs are independent constraints. + wrong_bond = randn(Float64, b2 ⊗ d ← d) + wrong_input = randn(Float64, b1 ⊗ d ← ℂ^3) + wrong_output = randn(Float64, b1 ⊗ ℂ^3 ← d) + @test_throws SpaceMismatch LocalOperator(lattice, sites => [first_tensor, wrong_bond]) + @test_throws SpaceMismatch LocalOperator(lattice, sites => [first_tensor, wrong_input]) + @test_throws SpaceMismatch LocalOperator(lattice, sites => [first_tensor, wrong_output]) + end + @testset "Charge shifting" begin lattice = InfiniteSquare(1, 1) elt = ComplexF64 diff --git a/test/types/standardize_dualness.jl b/test/types/standardize_dualness.jl new file mode 100644 index 000000000..5b394e39f --- /dev/null +++ b/test/types/standardize_dualness.jl @@ -0,0 +1,39 @@ +using TensorKit +using PEPSKit +using Test + +@testset "Standardize virtual-space dualness" begin + d = U1Space(0 => 1) + D = U1Space(0 => 1) + χ = U1Space(0 => 1) + Pspaces = fill(d, 2, 2, 1) + + patterns = ( + (fill(D', 2, 2, 1), fill(D', 2, 2, 1)), + ( + reshape([D, D', D', D], 2, 2, 1), + reshape([D', D, D, D'], 2, 2, 1), + ), + ) + for (Nspaces, Espaces) in patterns + ρ = InfinitePEPO(randn, ComplexF64, Pspaces, Nspaces, Espaces) + env = CTMRGEnv(randn, ComplexF64, InfinitePartitionFunction(ρ), χ) + standardized_ρ, standardized_env = PEPSKit.standardize_dualness(ρ, env) + + for row in axes(ρ, 1), col in axes(ρ, 2) + A = standardized_ρ[row, col, 1] + edge_coordinates = ( + PEPSKit.NORTH => (row - 1, col), + PEPSKit.EAST => (row, col + 1), + PEPSKit.SOUTH => (row + 1, col), + PEPSKit.WEST => (row, col - 1), + ) + for (direction, coordinates) in edge_coordinates + V = PEPSKit.virtualspace(A, direction) + E = PEPSKit.edge(standardized_env, direction, coordinates...) + @test isdual(V) == (direction in (PEPSKit.NORTH, PEPSKit.EAST)) + @test V == space(E, 2)' + end + end + end +end