Skip to main content

qslib_core/
models.rs

1use crate::{
2    BondMultiplicity, Complex64, DenseCouplings, Hamiltonian, InteractionChannel,
3    InteractionIdentity, InteractionTable, LatticeKind, OperatorError, Pauli, PauliString, Real,
4    RectangularGeometry, ShellTolerance, SimulationBasis, SiteCount, SiteId, WeightedInteraction,
5};
6use std::fmt::{self, Display, Formatter};
7use std::ops::Deref;
8
9/// Errors raised while constructing a physical model.
10#[derive(Clone, Debug, PartialEq)]
11pub enum ModelError {
12    /// An operator constructor rejected a term.
13    Operator(OperatorError),
14    /// A site-dependent parameter has the wrong length.
15    FieldLength {
16        /// Required number of site parameters.
17        expected: usize,
18        /// Supplied number of site parameters.
19        actual: usize,
20    },
21    /// A J1 or J2 shell received the wrong number of resolved coefficients.
22    ShellLength {
23        /// Shell name.
24        shell: &'static str,
25        /// Required number of shell bonds.
26        expected: usize,
27        /// Supplied number of coefficients.
28        actual: usize,
29    },
30    /// A model was requested in a basis not supported by its conversion.
31    UnsupportedBasis {
32        /// Model name.
33        model: &'static str,
34        /// Requested simulation basis.
35        basis: SimulationBasis,
36    },
37    /// An interaction table contains a channel for another model family.
38    UnexpectedChannel {
39        /// Model name.
40        model: &'static str,
41        /// Supplied channel.
42        channel: InteractionChannel,
43    },
44    /// A physical scalar parameter is not finite.
45    NonFiniteParameter {
46        /// Parameter name.
47        name: &'static str,
48        /// Invalid value.
49        value: Real,
50    },
51    /// Geometry or interaction validation failed while building a model.
52    InvalidInput(String),
53}
54
55/// A validated Hamiltonian together with the physical inputs that resolved it.
56///
57/// The operator representation is useful for matrix and local-energy work,
58/// while this wrapper keeps the model family, simulation basis, weighted pair
59/// identities, and site parameters available for provenance and inspection.
60#[derive(Clone, Debug, PartialEq)]
61pub struct ResolvedModel {
62    hamiltonian: Hamiltonian,
63    family: &'static str,
64    basis: SimulationBasis,
65    interactions: Vec<WeightedInteraction>,
66    specification: ModelSpecification,
67}
68
69/// The original typed physical specification retained by a resolved model.
70#[derive(Clone, Debug, PartialEq)]
71pub enum ModelSpecification {
72    /// Inhomogeneous transverse fields for TFIM, in site order.
73    Tfim {
74        /// Per-site transverse fields.
75        fields: Vec<Real>,
76    },
77    /// Isotropic pair exchange with resolved weighted interactions.
78    Heisenberg,
79    /// Driven Rydberg fields, in site order.
80    Rydberg {
81        /// Per-site drive amplitudes.
82        omega: Vec<Real>,
83        /// Per-site detunings.
84        detuning: Vec<Real>,
85    },
86    /// J1 and J2 shell coefficients, in canonical shell order.
87    J1J2 {
88        /// Rectangular geometry including extents, boundaries, and kind.
89        geometry: RectangularGeometry,
90        /// Nearest-neighbour coefficients.
91        j1: Vec<Real>,
92        /// Diagonal next-nearest-neighbour coefficients.
93        j2: Vec<Real>,
94    },
95}
96
97impl ResolvedModel {
98    fn new(
99        hamiltonian: Hamiltonian,
100        family: &'static str,
101        basis: SimulationBasis,
102        interactions: Vec<WeightedInteraction>,
103        specification: ModelSpecification,
104    ) -> Self {
105        Self {
106            hamiltonian,
107            family,
108            basis,
109            interactions,
110            specification,
111        }
112    }
113
114    /// Return the resolved operator Hamiltonian.
115    pub const fn hamiltonian(&self) -> &Hamiltonian {
116        &self.hamiltonian
117    }
118
119    /// Return the stable model-family identifier.
120    pub const fn family(&self) -> &'static str {
121        self.family
122    }
123
124    /// Return the simulation basis used by the builder.
125    pub const fn basis(&self) -> SimulationBasis {
126        self.basis
127    }
128
129    /// Return all resolved weighted interactions, including zero coefficients.
130    pub fn interactions(&self) -> &[WeightedInteraction] {
131        &self.interactions
132    }
133
134    /// Return a copy of this model with the supplied real physical constant.
135    ///
136    /// Model constructors use a zero constant because their named parameters
137    /// describe non-identity terms. Durable configuration adapters can apply
138    /// an explicitly serialized constant through this method without
139    /// rebuilding or reinterpreting the operator terms.
140    pub fn with_physical_constant(mut self, constant: Real) -> Result<Self, ModelError> {
141        finite_parameter("physical constant", constant)?;
142        self.hamiltonian = Hamiltonian::new_hermitian(
143            self.hamiltonian.site_count(),
144            Complex64::new(constant, 0.0),
145            self.hamiltonian.terms().to_vec(),
146        )?;
147        Ok(self)
148    }
149
150    /// Return the original typed physical specification.
151    pub const fn specification(&self) -> &ModelSpecification {
152        &self.specification
153    }
154}
155
156impl Deref for ResolvedModel {
157    type Target = Hamiltonian;
158
159    fn deref(&self) -> &Self::Target {
160        &self.hamiltonian
161    }
162}
163
164impl Display for ModelError {
165    fn fmt(&self, formatter: &mut Formatter<'_>) -> fmt::Result {
166        match self {
167            Self::Operator(error) => error.fmt(formatter),
168            Self::FieldLength { expected, actual } => write!(
169                formatter,
170                "model needs {expected} site parameters, received {actual}"
171            ),
172            Self::ShellLength {
173                shell,
174                expected,
175                actual,
176            } => write!(
177                formatter,
178                "model shell {shell} needs {expected} coefficients, received {actual}"
179            ),
180            Self::UnsupportedBasis { model, basis } => write!(
181                formatter,
182                "model {model} does not support simulation basis {basis}"
183            ),
184            Self::UnexpectedChannel { model, channel } => write!(
185                formatter,
186                "model {model} cannot consume interaction channel {channel:?}"
187            ),
188            Self::NonFiniteParameter { name, value } => {
189                write!(formatter, "model parameter {name}={value:?} is non-finite")
190            }
191            Self::InvalidInput(message) => formatter.write_str(message),
192        }
193    }
194}
195impl std::error::Error for ModelError {}
196impl From<OperatorError> for ModelError {
197    fn from(error: OperatorError) -> Self {
198        Self::Operator(error)
199    }
200}
201
202/// Build the physical transverse-field Ising Hamiltonian.
203pub fn tfim(
204    table: &InteractionTable,
205    fields: &[Real],
206    basis: SimulationBasis,
207) -> Result<ResolvedModel, ModelError> {
208    let n = table.site_count().get();
209    if fields.len() != n {
210        return Err(ModelError::FieldLength {
211            expected: n,
212            actual: fields.len(),
213        });
214    }
215    let (bond_pauli, field_pauli) = match basis {
216        SimulationBasis::Z => (Pauli::Z, Pauli::X),
217        SimulationBasis::X => (Pauli::X, Pauli::Z),
218        SimulationBasis::Y => {
219            return Err(ModelError::UnsupportedBasis {
220                model: "tfim",
221                basis,
222            });
223        }
224    };
225    let mut terms = Vec::new();
226    for term in table.interactions() {
227        if *term.channel() != InteractionChannel::IsingZZ {
228            return Err(ModelError::UnexpectedChannel {
229                model: "tfim",
230                channel: term.channel().clone(),
231            });
232        }
233        terms.push((
234            Complex64::new(-term.coefficient(), 0.0),
235            PauliString::new(vec![
236                (term.bond().first(), bond_pauli),
237                (term.bond().second(), bond_pauli),
238            ])?,
239        ));
240    }
241    for (index, &field) in fields.iter().enumerate() {
242        finite_parameter("field", field)?;
243        terms.push((
244            Complex64::new(-field, 0.0),
245            PauliString::new(vec![(
246                SiteId::try_from_usize(index).map_err(|_| ModelError::FieldLength {
247                    expected: n,
248                    actual: fields.len(),
249                })?,
250                field_pauli,
251            )])?,
252        ));
253    }
254    let hamiltonian = Hamiltonian::new_hermitian(
255        SiteCount::new(n).map_err(|_| ModelError::InvalidInput("empty TFIM system".into()))?,
256        Complex64::new(0.0, 0.0),
257        terms,
258    )
259    .map_err(ModelError::from)?;
260    let interactions = table.interactions().to_vec();
261    Ok(ResolvedModel::new(
262        hamiltonian,
263        "tfim",
264        basis,
265        interactions,
266        ModelSpecification::Tfim {
267            fields: fields.to_vec(),
268        },
269    ))
270}
271
272/// Build isotropic pair-dependent Heisenberg exchange in any Pauli-axis basis.
273pub fn heisenberg(
274    table: &InteractionTable,
275    basis: SimulationBasis,
276) -> Result<ResolvedModel, ModelError> {
277    let n = table.site_count().get();
278    let mut terms = Vec::new();
279    for term in table.interactions() {
280        if *term.channel() != InteractionChannel::HeisenbergExchange {
281            return Err(ModelError::UnexpectedChannel {
282                model: "heisenberg",
283                channel: term.channel().clone(),
284            });
285        }
286        let coefficient = Complex64::new(term.coefficient() / 4.0, 0.0);
287        for pauli in [Pauli::X, Pauli::Y, Pauli::Z] {
288            terms.push((
289                coefficient,
290                PauliString::new(vec![
291                    (term.bond().first(), pauli),
292                    (term.bond().second(), pauli),
293                ])?,
294            ));
295        }
296    }
297    let _ = basis;
298    let hamiltonian = Hamiltonian::new_hermitian(
299        SiteCount::new(n)
300            .map_err(|_| ModelError::InvalidInput("empty Heisenberg system".into()))?,
301        Complex64::new(0.0, 0.0),
302        terms,
303    )
304    .map_err(ModelError::from)?;
305    Ok(ResolvedModel::new(
306        hamiltonian,
307        "heisenberg",
308        basis,
309        table.interactions().to_vec(),
310        ModelSpecification::Heisenberg,
311    ))
312}
313
314/// Build the canonical driven Rydberg Hamiltonian in the z simulation basis.
315pub fn rydberg(
316    couplings: &DenseCouplings,
317    omega: &[Real],
318    detuning: &[Real],
319    basis: SimulationBasis,
320) -> Result<ResolvedModel, ModelError> {
321    if basis != SimulationBasis::Z {
322        return Err(ModelError::UnsupportedBasis {
323            model: "rydberg",
324            basis,
325        });
326    }
327    let n = couplings.site_count().get();
328    if omega.len() != n {
329        return Err(ModelError::FieldLength {
330            expected: n,
331            actual: omega.len(),
332        });
333    }
334    if detuning.len() != n {
335        return Err(ModelError::FieldLength {
336            expected: n,
337            actual: detuning.len(),
338        });
339    }
340    let mut constant = 0.0;
341    let mut terms = Vec::new();
342    for index in 0..n {
343        let drive = omega[index];
344        let delta = detuning[index];
345        finite_parameter("omega", drive)?;
346        finite_parameter("detuning", delta)?;
347        constant -= delta / 2.0;
348        let site = SiteId::try_from_usize(index)
349            .map_err(|_| ModelError::InvalidInput("site identifier overflow".into()))?;
350        terms.push((
351            Complex64::new(-drive / 2.0, 0.0),
352            PauliString::new(vec![(site, Pauli::X)])?,
353        ));
354        terms.push((
355            Complex64::new(delta / 2.0, 0.0),
356            PauliString::new(vec![(site, Pauli::Z)])?,
357        ));
358    }
359    let interactions = couplings
360        .to_interactions(InteractionChannel::RydbergDensityDensity)
361        .map_err(|error| ModelError::InvalidInput(error.to_string()))?;
362    for term in &interactions {
363        let v = term.coefficient();
364        constant += v / 4.0;
365        let i = term.bond().first();
366        let j = term.bond().second();
367        terms.push((
368            Complex64::new(-v / 4.0, 0.0),
369            PauliString::new(vec![(i, Pauli::Z)])?,
370        ));
371        terms.push((
372            Complex64::new(-v / 4.0, 0.0),
373            PauliString::new(vec![(j, Pauli::Z)])?,
374        ));
375        terms.push((
376            Complex64::new(v / 4.0, 0.0),
377            PauliString::new(vec![(i, Pauli::Z), (j, Pauli::Z)])?,
378        ));
379    }
380    let hamiltonian = Hamiltonian::new_hermitian(
381        SiteCount::new(n).map_err(|_| ModelError::InvalidInput("empty Rydberg system".into()))?,
382        Complex64::new(constant, 0.0),
383        terms,
384    )
385    .map_err(ModelError::from)?;
386    Ok(ResolvedModel::new(
387        hamiltonian,
388        "rydberg",
389        basis,
390        interactions,
391        ModelSpecification::Rydberg {
392            omega: omega.to_vec(),
393            detuning: detuning.to_vec(),
394        },
395    ))
396}
397
398/// Build the square-lattice homogeneous J1-J2 Heisenberg shorthand.
399pub fn j1j2(
400    geometry: &RectangularGeometry,
401    j1: Real,
402    j2: Real,
403    basis: SimulationBasis,
404) -> Result<ResolvedModel, ModelError> {
405    finite_parameter("j1", j1)?;
406    finite_parameter("j2", j2)?;
407    let j1_count = geometry
408        .bonds(BondMultiplicity::Simple)
409        .map_err(|error| ModelError::InvalidInput(error.to_string()))?
410        .len();
411    let j2_count = geometry
412        .pairs_at_squared_distance(2.0, ShellTolerance::Absolute(0.0))
413        .map_err(|error| ModelError::InvalidInput(error.to_string()))?
414        .len();
415    j1j2_disordered(geometry, &vec![j1; j1_count], &vec![j2; j2_count], basis)
416}
417
418/// Build a J1-J2 Heisenberg model with one coefficient per resolved shell bond.
419///
420/// Coefficients are consumed in the deterministic order returned by the
421/// geometry. If a periodic geometry gives the same endpoint pair in both
422/// shells, the distinct `j1` and `j2` identities are retained and their
423/// operator contributions add by construction.
424pub fn j1j2_disordered(
425    geometry: &RectangularGeometry,
426    j1: &[Real],
427    j2: &[Real],
428    basis: SimulationBasis,
429) -> Result<ResolvedModel, ModelError> {
430    finite_slice("j1", j1)?;
431    finite_slice("j2", j2)?;
432    if geometry.kind() != LatticeKind::Square {
433        return Err(ModelError::InvalidInput(
434            "j1-j2 shorthand requires square rectangular geometry".into(),
435        ));
436    }
437    let j1_bonds = geometry
438        .bonds(BondMultiplicity::Simple)
439        .map_err(|error| ModelError::InvalidInput(error.to_string()))?;
440    let j2_bonds = geometry
441        .pairs_at_squared_distance(2.0, ShellTolerance::Absolute(0.0))
442        .map_err(|error| ModelError::InvalidInput(error.to_string()))?;
443    if j1.len() != j1_bonds.len() {
444        return Err(ModelError::ShellLength {
445            shell: "j1",
446            expected: j1_bonds.len(),
447            actual: j1.len(),
448        });
449    }
450    if j2.len() != j2_bonds.len() {
451        return Err(ModelError::ShellLength {
452            shell: "j2",
453            expected: j2_bonds.len(),
454            actual: j2.len(),
455        });
456    }
457    let mut terms = Vec::with_capacity(j1.len() + j2.len());
458    for (bond, coefficient) in j1_bonds.into_iter().zip(j1.iter().copied()) {
459        terms.push((
460            InteractionIdentity::named(bond, InteractionChannel::HeisenbergExchange, "j1")
461                .map_err(|error| ModelError::InvalidInput(error.to_string()))?,
462            coefficient,
463        ));
464    }
465    for (bond, coefficient) in j2_bonds.into_iter().zip(j2.iter().copied()) {
466        terms.push((
467            InteractionIdentity::named(bond, InteractionChannel::HeisenbergExchange, "j2")
468                .map_err(|error| ModelError::InvalidInput(error.to_string()))?,
469            coefficient,
470        ));
471    }
472    let table = InteractionTable::new_with_identities(geometry.site_count(), terms)
473        .map_err(|error| ModelError::InvalidInput(error.to_string()))?;
474    let hamiltonian = heisenberg(&table, basis)?.hamiltonian.clone();
475    Ok(ResolvedModel::new(
476        hamiltonian,
477        "j1j2",
478        basis,
479        table.interactions().to_vec(),
480        ModelSpecification::J1J2 {
481            geometry: geometry.clone(),
482            j1: j1.to_vec(),
483            j2: j2.to_vec(),
484        },
485    ))
486}
487
488fn finite_parameter(name: &'static str, value: Real) -> Result<(), ModelError> {
489    if value.is_finite() {
490        Ok(())
491    } else {
492        Err(ModelError::NonFiniteParameter { name, value })
493    }
494}
495
496fn finite_slice(name: &'static str, values: &[Real]) -> Result<(), ModelError> {
497    values
498        .iter()
499        .copied()
500        .try_for_each(|value| finite_parameter(name, value))
501}