ariadnetor-algorithms 0.0.2

Tensor-network algorithms built on ariadnetor
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
//! DMRG L/R environment tensors and their incremental update.
//!
//! Each env slot carries a rank-3 tensor of shape `(top-bra-bond,
//! W-bond, bot-ket-bond)` matching the axis convention used by the
//! `ariadnetor_mps::inner` braket family. Boundary slots (`left[0]` and
//! `right[N]`) hold the trivial 1×1×1 identity tensor; for the
//! BlockSparse variant they additionally carry QNIndex / direction /
//! flux metadata (`flux = S::identity()`).
//!
//! Index convention is **boundary-indexed**: `left(i)` is the L
//! tensor at the boundary just left of site `i` (sites `0..i` already
//! folded in), `right(j)` is the R tensor at the boundary just left
//! of site `j` (sites `j..N` folded from the right). A 2-site DMRG
//! step at sites `(i, i+1)` consumes `left(i)`, `W[i]`, `W[i+1]`, and
//! `right(i+2)`.
//!
//! Storage-specific dispatch is provided by [`DmrgEnvOps`], which is
//! implemented for the Dense `DmrgEnvs` chain in this module and for the
//! BlockSparse chain in a sibling module. The two boundary
//! helpers fail loudly with [`DmrgEnvError::MalformedEdgeBond`] when a
//! chain's edge bonds violate the dim-1 single-sector contract required
//! by the BlockSparse boundary; for the Dense path the helpers always
//! succeed.

use ariadnetor_core::Scalar;
use ariadnetor_linalg::{LinalgError, contract};
use ariadnetor_mps::{Mpo, Mps, TensorChain};
use ariadnetor_tensor::{
    DenseLayout, DenseStorage, Host, Storage, StorageFor, Tensor, TensorLayout,
};

/// Errors raised by [`DmrgEnvs`] construction and advance operations.
#[derive(Debug, thiserror::Error)]
#[non_exhaustive]
pub enum DmrgEnvError {
    /// MPS / MPO had zero sites.
    #[error("MPS / MPO has zero sites")]
    EmptyChain,
    /// MPS and MPO site counts differ.
    #[error("MPS and MPO site counts differ: mps = {mps}, mpo = {mpo}")]
    LengthMismatch {
        /// Site count reported by the MPS.
        mps: usize,
        /// Site count reported by the MPO.
        mpo: usize,
    },
    /// `advance_*` was called with a site index outside `0..n_sites`.
    #[error("site index {index} out of range for chain of length {n_sites}")]
    InvalidSite {
        /// The out-of-range site index.
        index: usize,
        /// Chain length the index was checked against.
        n_sites: usize,
    },
    /// `advance_*` could not proceed because the predecessor env slot
    /// (`left[i]` for `advance_left(i)`, `right[j+1]` for
    /// `advance_right(j)`) is `None`. Indicates the caller advanced
    /// out of order or never built the initial envs.
    #[error(
        "advance prerequisite {side} env at index {index} is stale (None); \
         build the initial envs or advance in order"
    )]
    StaleNeighbor {
        /// Which side the stale env is on (`"left"` / `"right"`).
        side: &'static str,
        /// Index of the stale (`None`) env slot.
        index: usize,
    },
    /// An underlying `ariadnetor_linalg::contract` call failed. The
    /// source is preserved so callers see the real cause (dimension
    /// mismatch, backend failure, etc.) rather than a panic.
    #[error("contract failure during DMRG environment update")]
    Contract(#[from] LinalgError),
    /// An MPS or MPO chain edge bond violated the dim-1 single-sector
    /// contract required by the BlockSparse boundary helper, or the
    /// chosen edge sectors yielded a flux-disallowed boundary block
    /// under `flux = S::identity()`. The `leg` field names the
    /// offending edge (`"mps_left"`, `"mpo_left"`, `"mps_right"`, or
    /// `"mpo_right"`).
    #[error("malformed edge bond on {leg}: {detail}", detail = edge_bond_detail(.leg))]
    MalformedEdgeBond {
        /// Names the offending edge (`"mps_left"`, `"mpo_left"`,
        /// `"mps_right"`, or `"mpo_right"`).
        leg: &'static str,
    },
}

/// Per-edge well-formedness requirement rendered in
/// [`DmrgEnvError::MalformedEdgeBond`]'s message. MPS edges only need
/// dim-1 / single-sector (any charge is OK because `env_leg0` and
/// `env_leg2` carry the same MPS sector with opposite directions and
/// cancel). MPO edges additionally require an identity-fusing sector
/// to land a `(0, 0, 0)` boundary block under `flux = identity`.
fn edge_bond_detail(leg: &str) -> &'static str {
    match leg {
        "mps_left" | "mps_right" => "must be dim-1 / single-sector",
        "mpo_left" | "mpo_right" => {
            "must be dim-1 / single-sector with sector fusing to identity flux"
        }
        _ => "must be dim-1 / single-sector",
    }
}

/// Chain-keyed dispatch for DMRG env construction and per-site
/// updates.
///
/// Keyed on the [`DmrgEnvs<St, L>`](DmrgEnvs) chain and sealed (its
/// `sealed::Sealed` supertrait is crate-private), so the
/// storage / layout taxa are reachable only as the sealed associated types
/// rather than as free bounds on a public surface. The four trait methods
/// are the only points at which storage type matters; everything else in
/// [`DmrgEnvs`] is dispatched generically. Boundary helpers receive the
/// chain's edge site tensors (rather than just the backend) so the
/// BlockSparse implementation can extract QNIndex / direction / flux
/// metadata; the Dense implementation ignores the site arguments and
/// returns a constant 1×1×1 tensor.
///
/// Every operation runs on the [`Host`] substrate — DMRG is host-resident
/// in the CPU-only Stage B scope — so the concrete impls obtain the
/// backend from [`Host::shared`] rather than receiving one through the
/// call site.
pub trait DmrgEnvOps<T: Scalar>: super::sealed::Sealed {
    /// Layout type paired with this env chain.
    type Layout: TensorLayout;
    /// Storage type paired with this env chain (mirrors the
    /// `ariadnetor_mps::MpsOps::Storage` association).
    type Storage: Storage + StorageFor<Self::Layout>;

    /// Build the trivial L boundary tensor sitting just left of site 0.
    fn trivial_left_boundary(
        mps_left_edge: &Tensor<Self::Storage, Self::Layout>,
        mpo_left_edge: &Tensor<Self::Storage, Self::Layout>,
    ) -> Result<Tensor<Self::Storage, Self::Layout>, DmrgEnvError>;

    /// Build the trivial R boundary tensor sitting just right of site
    /// `n_sites - 1`.
    fn trivial_right_boundary(
        mps_right_edge: &Tensor<Self::Storage, Self::Layout>,
        mpo_right_edge: &Tensor<Self::Storage, Self::Layout>,
    ) -> Result<Tensor<Self::Storage, Self::Layout>, DmrgEnvError>;

    /// Absorb one site into the L environment, advancing it by one
    /// step to the right.
    fn extend_left_step(
        env: &Tensor<Self::Storage, Self::Layout>,
        site: &Tensor<Self::Storage, Self::Layout>,
        mpo_site: &Tensor<Self::Storage, Self::Layout>,
    ) -> Result<Tensor<Self::Storage, Self::Layout>, LinalgError>;

    /// Absorb one site into the R environment, advancing it by one
    /// step to the left.
    fn extend_right_step(
        env: &Tensor<Self::Storage, Self::Layout>,
        site: &Tensor<Self::Storage, Self::Layout>,
        mpo_site: &Tensor<Self::Storage, Self::Layout>,
    ) -> Result<Tensor<Self::Storage, Self::Layout>, LinalgError>;
}

// ============================================================================
// Dense (DmrgEnvs<DenseStorage<T>, DenseLayout>) implementation
// ============================================================================

impl<T: Scalar> DmrgEnvOps<T> for DmrgEnvs<DenseStorage<T>, DenseLayout> {
    type Layout = DenseLayout;
    type Storage = DenseStorage<T>;

    fn trivial_left_boundary(
        _mps_left_edge: &Tensor<Self::Storage, Self::Layout>,
        _mpo_left_edge: &Tensor<Self::Storage, Self::Layout>,
    ) -> Result<Tensor<Self::Storage, Self::Layout>, DmrgEnvError> {
        Ok(make_dense_one())
    }

    fn trivial_right_boundary(
        _mps_right_edge: &Tensor<Self::Storage, Self::Layout>,
        _mpo_right_edge: &Tensor<Self::Storage, Self::Layout>,
    ) -> Result<Tensor<Self::Storage, Self::Layout>, DmrgEnvError> {
        Ok(make_dense_one())
    }

    /// Per-site left extension for the Dense chain. Mirrors the loop
    /// body of `ariadnetor_mps::inner::braket_dense`: bra = `site.conj()`,
    /// then a 3-step contraction `(env, bra) → (·, mpo) → (·, site)`.
    fn extend_left_step(
        env: &Tensor<Self::Storage, Self::Layout>,
        site: &Tensor<Self::Storage, Self::Layout>,
        mpo_site: &Tensor<Self::Storage, Self::Layout>,
    ) -> Result<Tensor<Self::Storage, Self::Layout>, LinalgError> {
        let backend = Host::shared();
        let bra = site.conj();
        let t1 = contract(backend.as_ref(), env, &bra, "abc,ade->bcde")?;
        let t2 = contract(backend.as_ref(), &t1, mpo_site, "bcde,bfdg->cefg")?;
        contract(backend.as_ref(), &t2, site, "cefg,cfh->egh")
    }

    /// Per-site right extension for the Dense chain.
    fn extend_right_step(
        env: &Tensor<Self::Storage, Self::Layout>,
        site: &Tensor<Self::Storage, Self::Layout>,
        mpo_site: &Tensor<Self::Storage, Self::Layout>,
    ) -> Result<Tensor<Self::Storage, Self::Layout>, LinalgError> {
        let backend = Host::shared();
        let bra = site.conj();
        let t1 = contract(backend.as_ref(), env, site, "egh,cfh->egcf")?;
        let t2 = contract(backend.as_ref(), &t1, mpo_site, "egcf,bfdg->ecbd")?;
        contract(backend.as_ref(), &t2, &bra, "ecbd,ade->abc")
    }
}

fn make_dense_one<T>() -> Tensor<DenseStorage<T>, DenseLayout>
where
    T: Scalar,
{
    ariadnetor_tensor::DenseTensor::<T>::ones(vec![1, 1, 1])
}

// ============================================================================
// DmrgEnvs<St, L>
// ============================================================================

/// L/R environment tensors for 2-site DMRG, with incremental update
/// operations for left-to-right and right-to-left sweeps.
///
/// Generic over the storage / layout pair, which the
/// [`DmrgEnvOps<T>`] trait pins together via its `type Storage`
/// association. The struct itself is layout-agnostic; per-site
/// extension and boundary-tensor construction route through the trait.
///
/// See the module-level docs for the index convention.
#[derive(Debug, Clone)]
pub struct DmrgEnvs<St, L>
where
    St: Storage + StorageFor<L>,
    L: TensorLayout,
{
    /// `left[i]` for `i in 0..=n_sites`. `left[0]` is the trivial
    /// boundary; `left[i]` for `i > 0` carries sites `0..i`. `None`
    /// indicates the slot is stale relative to the current sweep
    /// position.
    left: Vec<Option<Tensor<St, L>>>,
    /// Mirror of `left` for the right sweep. `right[N]` is the
    /// trivial boundary; `right[j]` for `j < N` carries sites
    /// `j..N`.
    right: Vec<Option<Tensor<St, L>>>,
    n_sites: usize,
}

impl<St, L> DmrgEnvs<St, L>
where
    St: Storage + StorageFor<L>,
    L: TensorLayout,
{
    /// Initial right-sweep build. Computes `right[N-1..=1]` from the
    /// trivial right boundary down through the chain, leaving only
    /// `left[0]` populated.
    pub fn build<T>(mps: &Mps<St, L>, mpo: &Mpo<St, L>) -> Result<Self, DmrgEnvError>
    where
        T: Scalar,
        Self: DmrgEnvOps<T, Storage = St, Layout = L>,
    {
        let n_sites = mps.len();
        if n_sites == 0 {
            return Err(DmrgEnvError::EmptyChain);
        }
        if mpo.len() != n_sites {
            return Err(DmrgEnvError::LengthMismatch {
                mps: n_sites,
                mpo: mpo.len(),
            });
        }

        let mut left: Vec<Option<Tensor<St, L>>> = (0..=n_sites).map(|_| None).collect();
        let mut right: Vec<Option<Tensor<St, L>>> = (0..=n_sites).map(|_| None).collect();

        // Trivial boundary tensors at the chain edges. For Dense these
        // are constant 1×1×1 ones; for BlockSparse they additionally
        // validate the dim-1 / single-sector edge-bond contract.
        left[0] = Some(<Self as DmrgEnvOps<T>>::trivial_left_boundary(
            mps.site(0),
            mpo.site(0),
        )?);
        right[n_sites] = Some(<Self as DmrgEnvOps<T>>::trivial_right_boundary(
            mps.site(n_sites - 1),
            mpo.site(n_sites - 1),
        )?);

        // Build right envs from the right edge down to right[1].
        for j in (1..=n_sites).rev() {
            // right[j] is defined; absorb site j-1 to produce right[j-1].
            // We stop at j == 1 (computing right[0] is unused: a 2-site
            // step at the leftmost block (0, 1) consumes right(2), not
            // right(0); right(0) would equal the global braket scalar
            // and provides no useful intermediate). Keep right[0] as
            // None to make that explicit — building it would just
            // discard work.
            if j == 1 {
                break;
            }
            let prev = right[j].as_ref().expect("just initialized or computed");
            let new =
                <Self as DmrgEnvOps<T>>::extend_right_step(prev, mps.site(j - 1), mpo.site(j - 1))?;
            right[j - 1] = Some(new);
        }

        Ok(Self {
            left,
            right,
            n_sites,
        })
    }

    /// Number of MPS sites the env was built for.
    pub fn n_sites(&self) -> usize {
        self.n_sites
    }

    /// L tensor at the boundary just left of site `i`. Returns `None`
    /// when stale.
    pub fn left(&self, i: usize) -> Option<&Tensor<St, L>> {
        self.left.get(i).and_then(Option::as_ref)
    }

    /// R tensor at the boundary just left of site `j`.
    pub fn right(&self, j: usize) -> Option<&Tensor<St, L>> {
        self.right.get(j).and_then(Option::as_ref)
    }

    /// Absorb site `i` into the left environment.
    pub fn advance_left<T>(
        &mut self,
        mps: &Mps<St, L>,
        mpo: &Mpo<St, L>,
        i: usize,
    ) -> Result<(), DmrgEnvError>
    where
        T: Scalar,
        Self: DmrgEnvOps<T, Storage = St, Layout = L>,
    {
        if i >= self.n_sites {
            return Err(DmrgEnvError::InvalidSite {
                index: i,
                n_sites: self.n_sites,
            });
        }
        if mpo.len() != self.n_sites || mps.len() != self.n_sites {
            return Err(DmrgEnvError::LengthMismatch {
                mps: mps.len(),
                mpo: mpo.len(),
            });
        }
        let prev = match &self.left[i] {
            Some(t) => t,
            None => {
                return Err(DmrgEnvError::StaleNeighbor {
                    side: "left",
                    index: i,
                });
            }
        };
        let new = <Self as DmrgEnvOps<T>>::extend_left_step(prev, mps.site(i), mpo.site(i))?;
        self.left[i + 1] = Some(new);
        if i + 1 < self.n_sites {
            self.right[i + 1] = None;
        }
        Ok(())
    }

    /// Absorb site `j` into the right environment.
    pub fn advance_right<T>(
        &mut self,
        mps: &Mps<St, L>,
        mpo: &Mpo<St, L>,
        j: usize,
    ) -> Result<(), DmrgEnvError>
    where
        T: Scalar,
        Self: DmrgEnvOps<T, Storage = St, Layout = L>,
    {
        if j >= self.n_sites {
            return Err(DmrgEnvError::InvalidSite {
                index: j,
                n_sites: self.n_sites,
            });
        }
        if mpo.len() != self.n_sites || mps.len() != self.n_sites {
            return Err(DmrgEnvError::LengthMismatch {
                mps: mps.len(),
                mpo: mpo.len(),
            });
        }
        let prev = match &self.right[j + 1] {
            Some(t) => t,
            None => {
                return Err(DmrgEnvError::StaleNeighbor {
                    side: "right",
                    index: j + 1,
                });
            }
        };
        let new = <Self as DmrgEnvOps<T>>::extend_right_step(prev, mps.site(j), mpo.site(j))?;
        self.right[j] = Some(new);
        if j > 0 {
            self.left[j] = None;
        }
        Ok(())
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn malformed_edge_bond_mpo_detail_is_distinct() {
        // The mpo arm of `edge_bond_detail` adds the identity-flux clause that
        // the mps / wildcard text omits; rendering an mpo edge must surface it,
        // so deleting that arm (collapsing to the wildcard) is observable.
        let mpo = DmrgEnvError::MalformedEdgeBond { leg: "mpo_left" }.to_string();
        assert!(mpo.contains("fusing to identity flux"));

        let mps = DmrgEnvError::MalformedEdgeBond { leg: "mps_left" }.to_string();
        assert!(!mps.contains("fusing to identity flux"));
    }
}