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#[derive(Clone, Debug, PartialEq)]
11pub enum ModelError {
12 Operator(OperatorError),
14 FieldLength {
16 expected: usize,
18 actual: usize,
20 },
21 ShellLength {
23 shell: &'static str,
25 expected: usize,
27 actual: usize,
29 },
30 UnsupportedBasis {
32 model: &'static str,
34 basis: SimulationBasis,
36 },
37 UnexpectedChannel {
39 model: &'static str,
41 channel: InteractionChannel,
43 },
44 NonFiniteParameter {
46 name: &'static str,
48 value: Real,
50 },
51 InvalidInput(String),
53}
54
55#[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#[derive(Clone, Debug, PartialEq)]
71pub enum ModelSpecification {
72 Tfim {
74 fields: Vec<Real>,
76 },
77 Heisenberg,
79 Rydberg {
81 omega: Vec<Real>,
83 detuning: Vec<Real>,
85 },
86 J1J2 {
88 geometry: RectangularGeometry,
90 j1: Vec<Real>,
92 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 pub const fn hamiltonian(&self) -> &Hamiltonian {
116 &self.hamiltonian
117 }
118
119 pub const fn family(&self) -> &'static str {
121 self.family
122 }
123
124 pub const fn basis(&self) -> SimulationBasis {
126 self.basis
127 }
128
129 pub fn interactions(&self) -> &[WeightedInteraction] {
131 &self.interactions
132 }
133
134 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 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
202pub 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
272pub 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
314pub 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
398pub 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
418pub 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}