forked from Qiskit/qiskit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathparameter_expression.rs
More file actions
2264 lines (2061 loc) · 78.9 KB
/
parameter_expression.rs
File metadata and controls
2264 lines (2061 loc) · 78.9 KB
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
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// This code is part of Qiskit.
//
// (C) Copyright IBM 2023, 2024
//
// This code is licensed under the Apache License, Version 2.0. You may
// obtain a copy of this license in the LICENSE.txt file in the root directory
// of this source tree or at https://www.apache.org/licenses/LICENSE-2.0.
//
// Any modifications or derivative works of this code must retain this
// copyright notice, and modified files need to carry a notice indicating
// that they have been altered from the originals.
use hashbrown::hash_map::Entry;
use hashbrown::{HashMap, HashSet};
use num_complex::Complex64;
use pyo3::exceptions::{PyRuntimeError, PyTypeError, PyValueError, PyZeroDivisionError};
use pyo3::types::{IntoPyDict, PyComplex, PyFloat, PyInt, PyNotImplemented, PySet, PyString};
use std::sync::Arc;
use thiserror::Error;
use uuid::Uuid;
use std::collections::hash_map::DefaultHasher;
use std::fmt;
use std::hash::{Hash, Hasher};
use pyo3::IntoPyObjectExt;
use pyo3::prelude::*;
use crate::circuit_data::CircuitError;
use crate::imports::{BUILTIN_HASH, SYMPIFY_PARAMETER_EXPRESSION, UUID};
use crate::parameter::symbol_expr;
use crate::parameter::symbol_expr::SymbolExpr;
use crate::parameter::symbol_parser::parse_expression;
use super::symbol_expr::{SYMEXPR_EPSILON, Symbol, Value};
/// Errors for dealing with parameters and parameter expressions.
#[derive(Error, Debug)]
pub enum ParameterError {
#[error("Division by zero.")]
ZeroDivisionError,
#[error("Binding to infinite value.")]
BindingInf,
#[error("Binding to NaN.")]
BindingNaN,
#[error("Invalid value: NaN or infinite.")]
InvalidValue,
#[error("Cannot bind following parameters not present in expression: {0:?}")]
UnknownParameters(HashSet<Symbol>),
#[error("Parameter expression with unbound parameters {0:?} is not numeric.")]
UnboundParameters(HashSet<Symbol>),
#[error("Name conflict adding parameters.")]
NameConflict,
#[error("Invalid cast to OpCode: {0}")]
InvalidU8ToOpCode(u8),
#[error("Could not cast to Symbol.")]
NotASymbol,
#[error("Derivative not supported on expression: {0}")]
DerivativeNotSupported(String),
}
impl From<ParameterError> for PyErr {
fn from(value: ParameterError) -> Self {
match value {
ParameterError::ZeroDivisionError => {
PyZeroDivisionError::new_err("zero division occurs while binding parameter")
}
ParameterError::BindingInf => {
PyZeroDivisionError::new_err("attempted to bind infinite value to parameter")
}
ParameterError::UnknownParameters(_) | ParameterError::NameConflict => {
CircuitError::new_err(value.to_string())
}
ParameterError::UnboundParameters(_) => PyTypeError::new_err(value.to_string()),
ParameterError::InvalidValue => PyValueError::new_err(value.to_string()),
_ => PyRuntimeError::new_err(value.to_string()),
}
}
}
/// A parameter expression.
///
/// This is backed by Qiskit's symbolic expression engine and a cache
/// for the parameters inside the expression.
#[derive(Clone, Debug)]
pub struct ParameterExpression {
// The symbolic expression.
expr: SymbolExpr,
// A map keeping track of all symbols, with their name. This map *must* have
// exactly one entry per symbol used in the expression (no more, no less).
name_map: HashMap<String, Symbol>,
}
impl Hash for ParameterExpression {
fn hash<H: Hasher>(&self, state: &mut H) {
// The string representation of a tree is unique.
self.expr.string_id().hash(state);
}
}
impl PartialEq for ParameterExpression {
fn eq(&self, other: &Self) -> bool {
self.expr.eq(&other.expr)
}
}
impl Eq for ParameterExpression {}
impl Default for ParameterExpression {
/// The default constructor returns zero.
fn default() -> Self {
Self {
expr: SymbolExpr::Value(Value::Int(0)),
name_map: HashMap::new(), // no parameters, hence empty name map
}
}
}
impl fmt::Display for ParameterExpression {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", {
if let SymbolExpr::Symbol(s) = &self.expr {
s.repr(false)
} else {
match self.expr.eval(true) {
Some(e) => e.to_string(),
None => self.expr.to_string(),
}
}
})
}
}
impl ParameterExpression {
pub fn qpy_replay(&self) -> Vec<OPReplay> {
let mut replay = Vec::new();
qpy_replay(self, &self.name_map, &mut replay);
replay
}
pub fn num_of_symbols(&self) -> usize {
self.name_map.len()
}
}
// This needs to be implemented manually, because PyO3 does not provide built-in
// conversions for the subclasses of ParameterExpression in Python. Specifically
// the Python classes Parameter and ParameterVector are subclasses of
// ParameterExpression and the default trait impl would not handle the specialization
// there.
impl<'py> IntoPyObject<'py> for ParameterExpression {
type Target = PyParameterExpression;
type Output = Bound<'py, Self::Target>;
type Error = PyErr;
fn into_pyobject(self, py: Python<'py>) -> Result<Self::Output, Self::Error> {
let expr = PyParameterExpression::from(self.clone());
expr.into_pyobject(py)
}
}
/// Lookup for which operations are binary (i.e. require two operands).
static BINARY_OPS: [OpCode; 8] = [
// a HashSet would be better but requires unstable features
OpCode::ADD,
OpCode::SUB,
OpCode::MUL,
OpCode::DIV,
OpCode::POW,
OpCode::RSUB,
OpCode::RDIV,
OpCode::RPOW,
];
impl ParameterExpression {
/// Initialize with an existing [SymbolExpr] and its valid name map.
///
/// Caution: The caller **guarantees** that ``name_map`` is consistent with ``expr``.
/// If uncertain, call [Self::from_symbol_expr], which automatically builds the correct name map.
pub fn new(expr: SymbolExpr, name_map: HashMap<String, Symbol>) -> Self {
Self { expr, name_map }
}
/// Construct from a [Symbol].
pub fn from_symbol(symbol: Symbol) -> Self {
Self {
expr: SymbolExpr::Symbol(Arc::new(symbol.clone())),
name_map: [(symbol.repr(false), symbol)].into(),
}
}
/// Try casting to a [Symbol].
///
/// This only succeeds if the underlying expression is, in fact, only a symbol.
pub fn try_to_symbol(&self) -> Result<Symbol, ParameterError> {
if let SymbolExpr::Symbol(symbol) = &self.expr {
Ok(symbol.as_ref().clone())
} else {
Err(ParameterError::NotASymbol)
}
}
/// Try casting to a [Symbol], returning a reference.
///
/// This only succeeds if the underlying expression is, in fact, only a symbol.
pub fn try_to_symbol_ref(&self) -> Result<&Symbol, ParameterError> {
if let SymbolExpr::Symbol(symbol) = &self.expr {
Ok(symbol.as_ref())
} else {
Err(ParameterError::NotASymbol)
}
}
/// Try casting to a [Value].
///
/// Attempt to evaluate the expression recursively and return a [Value] if fully bound.
///
/// # Arguments
///
/// * strict - If ``true``, only allow returning a value if all symbols are bound. If
/// ``false``, allow casting expressions to values, even though symbols might still exist.
/// For example, ``0 * x`` will return ``0`` for ``strict=false`` and otherwise return
/// an error.
pub fn try_to_value(&self, strict: bool) -> Result<Value, ParameterError> {
if strict && !self.name_map.is_empty() {
let free_symbols = self.expr.iter_symbols().cloned().collect();
return Err(ParameterError::UnboundParameters(free_symbols));
}
match self.expr.eval(true) {
Some(value) => {
// we try to restrict complex to real, if possible
if let Value::Complex(c) = value {
if (-symbol_expr::SYMEXPR_EPSILON..symbol_expr::SYMEXPR_EPSILON).contains(&c.im)
{
return Ok(Value::Real(c.re));
}
}
Ok(value)
}
None => {
let free_symbols = self.expr.iter_symbols().cloned().collect();
Err(ParameterError::UnboundParameters(free_symbols))
}
}
}
/// Construct from a [SymbolExpr].
///
/// This populates the name map with the symbols in the expression.
pub fn from_symbol_expr(expr: SymbolExpr) -> Self {
let name_map = expr.name_map();
Self { expr, name_map }
}
/// Initialize from an f64.
pub fn from_f64(value: f64) -> Self {
Self {
expr: SymbolExpr::Value(Value::Real(value)),
name_map: HashMap::new(),
}
}
/// Load from a sequence of [OPReplay]s. Used in serialization.
pub fn from_qpy(
replay: &[OPReplay],
subs_operations: Option<Vec<(usize, HashMap<Symbol, ParameterExpression>)>>,
additional_symbols: Option<&HashSet<Symbol>>,
) -> Result<Self, ParameterError> {
let mut symbols = match additional_symbols {
None => HashSet::new(),
Some(symbol_map) => symbol_map.clone(),
};
// the stack contains the latest lhs and rhs values
let mut stack: Vec<ParameterExpression> = Vec::new();
let subs_operations = subs_operations.unwrap_or_default();
let mut current_sub_operation = subs_operations.len(); // we avoid using a queue since we only make one pass anyway
for (i, inst) in replay.iter().enumerate() {
let OPReplay { op, lhs, rhs } = inst;
// put the values on the stack, if they exist
if let Some(value) = lhs {
stack.push(value.clone().into());
}
if let Some(value) = rhs {
stack.push(value.clone().into());
}
// if we need two operands, pop rhs from the stack
let rhs = if BINARY_OPS.contains(op) {
Some(stack.pop().expect("Pop from empty stack"))
} else {
None
};
// pop lhs from the stack, this we always need
let lhs = stack.pop().expect("Pop from empty stack");
// apply the operation and put the result onto the stack for the next replay
let result: ParameterExpression = match op {
OpCode::ADD => lhs.add(&rhs.unwrap())?,
OpCode::MUL => lhs.mul(&rhs.unwrap())?,
OpCode::SUB => lhs.sub(&rhs.unwrap())?,
OpCode::RSUB => rhs.unwrap().sub(&lhs)?,
OpCode::POW => lhs.pow(&rhs.unwrap())?,
OpCode::RPOW => rhs.unwrap().pow(&lhs)?,
OpCode::DIV => lhs.div(&rhs.unwrap())?,
OpCode::RDIV => rhs.unwrap().div(&lhs)?,
OpCode::ABS => lhs.abs(),
OpCode::SIN => lhs.sin(),
OpCode::ASIN => lhs.asin(),
OpCode::COS => lhs.cos(),
OpCode::ACOS => lhs.acos(),
OpCode::TAN => lhs.tan(),
OpCode::ATAN => lhs.atan(),
OpCode::CONJ => lhs.conjugate(),
OpCode::LOG => lhs.log(),
OpCode::EXP => lhs.exp(),
OpCode::SIGN => lhs.sign(),
OpCode::GRAD | OpCode::SUBSTITUTE => {
panic!("GRAD and SUBSTITUTE are not supported.")
}
};
stack.push(result);
//now check whether any substitutions need to be applied at this stage
let mut sub_operations_to_perform = Vec::new();
// since we go over the operations from last to first, we need to collect all the subs
// for this stage and go over them in reverse order (from first to last, for this stage)
while current_sub_operation > 0 && subs_operations[current_sub_operation - 1].0 == i + 1
{
sub_operations_to_perform
.push(subs_operations[current_sub_operation - 1].1.clone());
current_sub_operation -= 1;
}
for sub_operation in sub_operations_to_perform.iter().rev() {
if let Some(exp) = stack.pop() {
let sub_exp = exp.subs(sub_operation, true)?;
stack.push(sub_exp);
for key in sub_operation.keys() {
symbols.remove(key); // remove the symbols that were substituted away
}
}
}
}
// once we're done, just return the last element in the stack
let mut result = stack
.pop()
.expect("Invalid QPY replay encountered during deserialization: empty OPReplay.");
// need to account
result.extend_symbols(symbols);
Ok(result)
}
pub fn iter_symbols(&self) -> impl Iterator<Item = &Symbol> + '_ {
self.name_map.values()
}
/// Get the number of [Symbol]s in the expression.
pub fn num_symbols(&self) -> usize {
self.name_map.len()
}
/// Whether the expression represents a complex number. None if cannot be determined.
pub fn is_complex(&self) -> Option<bool> {
self.expr.is_complex()
}
/// Whether the expression represents a int. None if cannot be determined.
pub fn is_int(&self) -> Option<bool> {
self.expr.is_int()
}
/// Add an expression; ``self + rhs``.
pub fn add(&self, rhs: &ParameterExpression) -> Result<Self, ParameterError> {
let name_map = self.merged_name_map(rhs)?;
Ok(Self {
expr: &self.expr + &rhs.expr,
name_map,
})
}
/// Multiply with an expression; ``self * rhs``.
pub fn mul(&self, rhs: &ParameterExpression) -> Result<Self, ParameterError> {
let name_map = self.merged_name_map(rhs)?;
Ok(Self {
expr: &self.expr * &rhs.expr,
name_map,
})
}
/// Subtract another expression; ``self - rhs``.
pub fn sub(&self, rhs: &ParameterExpression) -> Result<Self, ParameterError> {
let name_map = self.merged_name_map(rhs)?;
Ok(Self {
expr: &self.expr - &rhs.expr,
name_map,
})
}
/// Divide by another expression; ``self / rhs``.
pub fn div(&self, rhs: &ParameterExpression) -> Result<Self, ParameterError> {
if rhs.expr.is_zero() {
return Err(ParameterError::ZeroDivisionError);
}
let name_map = self.merged_name_map(rhs)?;
Ok(Self {
expr: &self.expr / &rhs.expr,
name_map,
})
}
/// Raise this expression to a power; ``self ^ rhs``.
pub fn pow(&self, rhs: &ParameterExpression) -> Result<Self, ParameterError> {
let name_map = self.merged_name_map(rhs)?;
Ok(Self {
expr: self.expr.pow(&rhs.expr),
name_map,
})
}
/// Apply the sine to this expression; ``sin(self)``.
pub fn sin(&self) -> Self {
Self {
expr: self.expr.sin(),
name_map: self.name_map.clone(),
}
}
/// Apply the cosine to this expression; ``cos(self)``.
pub fn cos(&self) -> Self {
Self {
expr: self.expr.cos(),
name_map: self.name_map.clone(),
}
}
/// Apply the tangent to this expression; ``tan(self)``.
pub fn tan(&self) -> Self {
Self {
expr: self.expr.tan(),
name_map: self.name_map.clone(),
}
}
/// Apply the arcsine to this expression; ``asin(self)``.
pub fn asin(&self) -> Self {
Self {
expr: self.expr.asin(),
name_map: self.name_map.clone(),
}
}
/// Apply the arccosine to this expression; ``acos(self)``.
pub fn acos(&self) -> Self {
Self {
expr: self.expr.acos(),
name_map: self.name_map.clone(),
}
}
/// Apply the arctangent to this expression; ``atan(self)``.
pub fn atan(&self) -> Self {
Self {
expr: self.expr.atan(),
name_map: self.name_map.clone(),
}
}
/// Exponentiate this expression; ``exp(self)``.
pub fn exp(&self) -> Self {
Self {
expr: self.expr.exp(),
name_map: self.name_map.clone(),
}
}
/// Take the (natural) logarithm of this expression; ``log(self)``.
pub fn log(&self) -> Self {
Self {
expr: self.expr.log(),
name_map: self.name_map.clone(),
}
}
/// Take the absolute value of this expression; ``|self|``.
pub fn abs(&self) -> Self {
Self {
expr: self.expr.abs(),
name_map: self.name_map.clone(),
}
}
/// Return the sign of this expression; ``sign(self)``.
pub fn sign(&self) -> Self {
Self {
expr: self.expr.sign(),
name_map: self.name_map.clone(),
}
}
/// Complex conjugate the expression.
pub fn conjugate(&self) -> Self {
Self {
expr: self.expr.conjugate(),
name_map: self.name_map.clone(),
}
}
/// negate the expression.
pub fn neg(&self) -> Self {
Self {
expr: -&self.expr,
name_map: self.name_map.clone(),
}
}
/// Compute the derivative of the expression with respect to the provided symbol.
///
/// Note that this keeps the name map unchanged. Meaning that computing the derivative
/// of ``x`` will yield ``1`` but the expression still owns the symbol ``x``. This is
/// done such that we can still bind the value ``x`` in an automated process.
pub fn derivative(&self, param: &Symbol) -> Result<Self, ParameterError> {
Ok(Self {
expr: self
.expr
.derivative(param)
.map_err(ParameterError::DerivativeNotSupported)?,
name_map: self.name_map.clone(),
})
}
/// Substitute symbols with [ParameterExpression]s.
///
/// # Arguments
///
/// * map - A hashmap with [Symbol] keys and [ParameterExpression]s to replace these
/// symbols with.
/// * allow_unknown_parameters - If `false`, returns an error if any symbol in the
/// hashmap is not present in the expression. If `true`, unknown symbols are ignored.
/// Setting to `true` is slightly faster as it does not involve additional checks.
///
/// # Returns
///
/// * `Ok(Self)` - A parameter expression with the substituted expressions.
/// * `Err(ParameterError)` - An error if the substitution failed.
pub fn subs(
&self,
map: &HashMap<Symbol, Self>,
allow_unknown_parameters: bool,
) -> Result<Self, ParameterError> {
// Build the outgoing name map. In the process we check for any duplicates.
let mut name_map: HashMap<String, Symbol> = HashMap::new();
let mut symbol_map: HashMap<Symbol, SymbolExpr> = HashMap::new();
// If we don't allow for unknown parameters, check if there are any.
if !allow_unknown_parameters {
let existing: HashSet<&Symbol> = self.name_map.values().collect();
let to_replace: HashSet<&Symbol> = map.keys().collect();
let mut difference = to_replace.difference(&existing).peekable();
if difference.peek().is_some() {
let different_symbols = difference.map(|s| (**s).clone()).collect();
return Err(ParameterError::UnknownParameters(different_symbols));
}
}
for (name, symbol) in self.name_map.iter() {
// check if the symbol will get replaced
if let Some(replacement) = map.get(symbol) {
// If yes, update the name_map. This also checks for duplicates.
for (replacement_name, replacement_symbol) in replacement.name_map.iter() {
if let Some(duplicate) = name_map.get(replacement_name) {
// If a symbol with the same name already exists, check whether it is
// the same symbol (fine) or a different symbol with the same name (conflict)!
if duplicate != replacement_symbol {
return Err(ParameterError::NameConflict);
}
} else {
// SAFETY: We know the key does not exist yet.
unsafe {
name_map.insert_unique_unchecked(
replacement_name.clone(),
replacement_symbol.clone(),
)
};
}
}
// If we got until here, there were no duplicates, so we are safe to
// add this symbol to the internal replacement map.
symbol_map.insert(symbol.clone(), replacement.expr.clone());
} else {
// no replacement for this symbol, carry on
match name_map.entry(name.clone()) {
Entry::Occupied(duplicate) => {
if duplicate.get() != symbol {
return Err(ParameterError::NameConflict);
}
}
Entry::Vacant(e) => {
e.insert(symbol.clone());
}
}
}
}
let res = self.expr.subs(&symbol_map);
Ok(Self {
expr: res,
name_map,
})
}
/// Bind symbols to values.
///
/// # Arguments
///
/// * map - A hashmap with [Symbol] keys and [Value]s to replace these
/// symbols with.
/// * allow_unknown_parameter - If `false`, returns an error if any symbol in the
/// hashmap is not present in the expression. If `true`, unknown symbols are ignored.
/// Setting to `true` is slightly faster as it does not involve additional checks.
///
/// # Returns
///
/// * `Ok(Self)` - A parameter expression with the bound symbols.
/// * `Err(ParameterError)` - An error if binding failed.
pub fn bind(
&self,
map: &HashMap<&Symbol, Value>,
allow_unknown_parameters: bool,
) -> Result<Self, ParameterError> {
// The set of symbols we will bind. Used twice, hence pre-computed here.
let bind_symbols: HashSet<&Symbol> = map.keys().cloned().collect();
// If we don't allow for unknown parameters, check if there are any.
if !allow_unknown_parameters {
let existing: HashSet<&Symbol> = self.name_map.values().collect();
let mut difference = bind_symbols.difference(&existing).peekable();
if difference.peek().is_some() {
let different_symbols = difference.map(|s| (**s).clone()).collect();
return Err(ParameterError::UnknownParameters(different_symbols));
}
}
// bind the symbol expression and then check the outcome for inf/nan, or numeric values
let bound_expr = self.expr.bind(map);
let bound = match bound_expr.eval(true) {
Some(v) => match &v {
Value::Real(r) => {
if r.is_infinite() {
Err(ParameterError::BindingInf)
} else if r.is_nan() {
Err(ParameterError::BindingNaN)
} else {
Ok(SymbolExpr::Value(v))
}
}
Value::Int(_) => Ok(SymbolExpr::Value(v)),
Value::Complex(c) => {
if c.re.is_infinite() || c.im.is_infinite() {
Err(ParameterError::BindingInf)
} else if c.re.is_nan() || c.im.is_nan() {
Err(ParameterError::BindingNaN)
} else if (-symbol_expr::SYMEXPR_EPSILON..symbol_expr::SYMEXPR_EPSILON)
.contains(&c.im)
{
Ok(SymbolExpr::Value(Value::Real(c.re)))
} else {
Ok(SymbolExpr::Value(v))
}
}
},
None => Ok(bound_expr),
}?;
// update the name map by removing the bound parameters
let bound_name_map: HashMap<String, Symbol> = self
.name_map
.iter()
.filter(|(_, symbol)| !bind_symbols.contains(symbol))
.map(|(name, symbol)| (name.clone(), symbol.clone()))
.collect();
Ok(Self {
expr: bound,
name_map: bound_name_map,
})
}
/// Merge name maps.
///
/// # Arguments
///
/// * `other` - The other parameter expression whose symbols we add to self.
///
/// # Returns
///
/// * `Ok(HashMap<String, Symbol>)` - The merged name map.
/// * `Err(ParameterError)` - An error if there was a name conflict.
fn merged_name_map(&self, other: &Self) -> Result<HashMap<String, Symbol>, ParameterError> {
let mut merged = self.name_map.clone();
for (name, param) in other.name_map.iter() {
match merged.get(name) {
Some(existing_param) => {
if param != existing_param {
return Err(ParameterError::NameConflict);
}
}
None => {
// SAFETY: We ensured the key is unique
let _ = unsafe { merged.insert_unique_unchecked(name.clone(), param.clone()) };
}
}
}
Ok(merged)
}
/// Extend the symbol table with additional symbols
pub fn extend_symbols<I>(&mut self, symbols: I)
where
I: IntoIterator<Item = Symbol>,
{
for symbol in symbols {
let name = symbol.repr(false);
self.name_map.entry(name).or_insert(symbol);
}
}
}
/// A parameter expression.
///
/// This is backed by Qiskit's symbolic expression engine and a cache
/// for the parameters inside the expression.
#[pyclass(
subclass,
module = "qiskit._accelerate.circuit",
name = "ParameterExpression",
from_py_object
)]
#[derive(Clone, Debug)]
pub struct PyParameterExpression {
pub inner: ParameterExpression,
}
impl Default for PyParameterExpression {
/// The default constructor returns zero.
fn default() -> Self {
Self {
inner: ParameterExpression::default(),
}
}
}
impl fmt::Display for PyParameterExpression {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.inner.fmt(f)
}
}
impl From<ParameterExpression> for PyParameterExpression {
fn from(value: ParameterExpression) -> Self {
Self { inner: value }
}
}
impl PyParameterExpression {
/// Attempt to extract a `PyParameterExpression` from a bound `PyAny`.
///
/// This will try to coerce to the strictest data type:
/// Int - Real - Complex - PyParameterVectorElement - PyParameter - PyParameterExpression.
///
/// # Arguments:
///
/// * ob - The bound `PyAny` to extract from.
///
/// # Returns
///
/// * `Ok(Self)` - The extracted expression.
/// * `Err(PyResult)` - An error if extraction to all above types failed.
pub fn extract_coerce(ob: Borrowed<PyAny>) -> PyResult<Self> {
if let Ok(i) = ob.cast::<PyInt>() {
Ok(ParameterExpression::new(
SymbolExpr::Value(Value::from(i.extract::<i64>()?)),
HashMap::new(),
)
.into())
} else if let Ok(r) = ob.cast::<PyFloat>() {
let r: f64 = r.extract()?;
if r.is_infinite() || r.is_nan() {
return Err(ParameterError::InvalidValue.into());
}
Ok(ParameterExpression::new(SymbolExpr::Value(Value::from(r)), HashMap::new()).into())
} else if let Ok(c) = ob.cast::<PyComplex>() {
let c: Complex64 = c.extract()?;
if c.is_infinite() || c.is_nan() {
return Err(ParameterError::InvalidValue.into());
}
Ok(ParameterExpression::new(SymbolExpr::Value(Value::from(c)), HashMap::new()).into())
} else if let Ok(element) = ob.cast::<PyParameterVectorElement>() {
Ok(ParameterExpression::from_symbol(element.borrow().symbol.clone()).into())
} else if let Ok(parameter) = ob.cast::<PyParameter>() {
Ok(ParameterExpression::from_symbol(parameter.borrow().symbol.clone()).into())
} else {
ob.extract::<PyParameterExpression>().map_err(Into::into)
}
}
pub fn coerce_into_py(&self, py: Python) -> PyResult<Py<PyAny>> {
if let Ok(value) = self.inner.try_to_value(true) {
match value {
Value::Int(i) => Ok(PyInt::new(py, i).unbind().into_any()),
Value::Real(r) => Ok(PyFloat::new(py, r).unbind().into_any()),
Value::Complex(c) => Ok(PyComplex::from_complex_bound(py, c).unbind().into_any()),
}
} else if let Ok(symbol) = self.inner.try_to_symbol() {
if symbol.index.is_some() {
Ok(Py::new(py, PyParameterVectorElement::from_symbol(symbol))?.into_any())
} else {
Ok(Py::new(py, PyParameter::from_symbol(symbol))?.into_any())
}
} else {
self.clone().into_py_any(py)
}
}
}
#[pymethods]
impl PyParameterExpression {
/// This is a **strictly internal** constructor and **should not be used**.
/// It is subject to arbitrary change in between Qiskit versions and cannot be relied on.
/// Parameter expressions should always be constructed from applying operations on
/// parameters, or by loading via QPY.
///
/// The input values are allowed to be None for pickling purposes.
#[new]
#[pyo3(signature = (name_map=None, expr=None))]
pub fn py_new(
name_map: Option<HashMap<String, PyParameter>>,
expr: Option<String>,
) -> PyResult<Self> {
match (name_map, expr) {
(None, None) => Ok(Self::default()),
(Some(name_map), Some(expr)) => {
// We first parse the expression and then update the symbols with the ones
// the user provided. The replacement relies on the names to match.
// This is hacky and we likely want a more reliably conversion from a SymPy object,
// if we decide we want to continue supporting this.
let expr = parse_expression(&expr)
.map_err(|_| PyRuntimeError::new_err("Failed parsing input expression"))?;
let symbol_map: HashMap<String, Symbol> = name_map
.iter()
.map(|(string, param)| (string.clone(), param.symbol.clone()))
.collect();
let replaced_expr = symbol_expr::replace_symbol(&expr, &symbol_map);
let inner = ParameterExpression::new(replaced_expr, symbol_map);
Ok(Self { inner })
}
_ => Err(PyValueError::new_err(
"Pass either both a name_map and expr, or neither",
)),
}
}
#[allow(non_snake_case)]
#[staticmethod]
pub fn _Value(value: &Bound<PyAny>) -> PyResult<Self> {
Self::extract_coerce(value.as_borrowed())
}
/// Check if the expression corresponds to a plain symbol.
///
/// Returns:
/// ``True`` is this expression corresponds to a symbol, ``False`` otherwise.
pub fn is_symbol(&self) -> bool {
matches!(self.inner.expr, SymbolExpr::Symbol(_))
}
/// Cast this expression to a numeric value.
///
/// Args:
/// strict: If ``True`` (default) this function raises an error if there are any
/// unbound symbols in the expression. If ``False``, this allows casting
/// if the expression represents a numeric value, regardless of unbound symbols.
/// For example ``(0 * Parameter("x"))`` is 0 but has the symbol ``x`` present.
#[pyo3(signature = (strict=true))]
pub fn numeric(&self, py: Python, strict: bool) -> PyResult<Py<PyAny>> {
match self.inner.try_to_value(strict)? {
Value::Real(r) => r.into_py_any(py),
Value::Int(i) => i.into_py_any(py),
Value::Complex(c) => c.into_py_any(py),
}
}
/// Return a SymPy equivalent of this expression.
///
/// Returns:
/// A SymPy equivalent of this expression.
pub fn sympify(&self, py: Python) -> PyResult<Py<PyAny>> {
let py_sympify = SYMPIFY_PARAMETER_EXPRESSION.get(py);
py_sympify.call1(py, (self.clone(),))
}
/// The number of unbound parameters in the expression.
///
/// This is equivalent to ``len(expr.parameters)`` but does not involve the overhead of creating
/// a set and counting its length.
#[getter]
pub fn num_parameters(&self) -> usize {
self.inner.num_symbols()
}
/// Get the parameters present in the expression.
///
/// .. note::
///
/// Qiskit guarantees equality (via ``==``) of parameters retrieved from an expression
/// with the original :class:`.Parameter` objects used to create this expression,
/// but does **not guarantee** ``is`` comparisons to succeed.
///
#[getter]
pub fn parameters<'py>(&self, py: Python<'py>) -> PyResult<Bound<'py, PySet>> {
let py_parameters: Vec<Py<PyAny>> = self
.inner
.iter_symbols()
.map(|symbol| {
if symbol.is_vector_element() {
Ok(
Py::new(py, PyParameterVectorElement::from_symbol(symbol.clone()))?
.into_any(),
)
} else {
Ok(Py::new(py, PyParameter::from_symbol(symbol.clone()))?.into_any())
}
})
.collect::<PyResult<_>>()?;
PySet::new(py, py_parameters)
}
/// Sine of the expression.
#[inline]
#[pyo3(name = "sin")]
pub fn py_sin(&self) -> Self {
self.inner.sin().into()
}
/// Cosine of the expression.
#[inline]
#[pyo3(name = "cos")]
pub fn py_cos(&self) -> Self {
self.inner.cos().into()
}
/// Tangent of the expression.
#[inline]
#[pyo3(name = "tan")]
pub fn py_tan(&self) -> Self {
self.inner.tan().into()
}
/// Arcsine of the expression.
#[inline]
pub fn arcsin(&self) -> Self {
self.inner.asin().into()
}
/// Arccosine of the expression.
#[inline]
pub fn arccos(&self) -> Self {
self.inner.acos().into()
}
/// Arctangent of the expression.
#[inline]
pub fn arctan(&self) -> Self {
self.inner.atan().into()
}
/// Exponentiate the expression.
#[inline]
#[pyo3(name = "exp")]
pub fn py_exp(&self) -> Self {
self.inner.exp().into()
}
/// Take the natural logarithm of the expression.
#[inline]
#[pyo3(name = "log")]
pub fn py_log(&self) -> Self {
self.inner.log().into()
}
/// Take the absolute value of the expression.
#[inline]
#[pyo3(name = "abs")]
pub fn py_abs(&self) -> Self {