-
Notifications
You must be signed in to change notification settings - Fork 55
/
operation.py
9651 lines (8105 loc) · 410 KB
/
operation.py
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
"""
Defines classes which represent gates, as well as supporting functions
"""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
# in compliance with the License. You may obtain a copy of the License at
# http://www.apache.org/licenses/LICENSE-2.0 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
import numpy as _np
import scipy.linalg as _spl
import scipy.sparse as _sps
import scipy.sparse.linalg as _spsl
import functools as _functools
import itertools as _itertools
import copy as _copy
import warnings as _warnings
import collections as _collections
import numbers as _numbers
from .. import optimize as _opt
from ..tools import matrixtools as _mt
from ..tools import optools as _gt
from ..tools import jamiolkowski as _jt
from ..tools import basistools as _bt
from ..tools import listtools as _lt
from ..tools import slicetools as _slct
from ..tools import symplectic as _symp
from ..tools import lindbladtools as _lbt
from . import gaugegroup as _gaugegroup
from . import modelmember as _modelmember
from . import stabilizer as _stabilizer
from .protectedarray import ProtectedArray as _ProtectedArray
from .basis import Basis as _Basis, BuiltinBasis as _BuiltinBasis, EmbeddedBasis as _EmbeddedBasis, \
ExplicitBasis as _ExplicitBasis
from .errorgencontainer import ErrorGeneratorContainer as _ErrorGeneratorContainer
from . import term as _term
from .polynomial import Polynomial as _Polynomial
from . import replib
from . import opcalc
from .opcalc import compact_deriv as _compact_deriv, \
bulk_eval_compact_polynomials_complex as _bulk_eval_compact_polynomials_complex, \
abs_sum_bulk_eval_compact_polynomials_complex as _abs_sum_bulk_eval_compact_polynomials_complex
TOL = 1e-12
IMAG_TOL = 1e-7 # tolerance for imaginary part being considered zero
def optimize_operation(op_to_optimize, target_op):
"""
Optimize the parameters of `op_to_optimize`.
Optimization is performed so that the the resulting operation matrix
is as close as possible to target_op's matrix.
This is trivial for the case of FullDenseOp
instances, but for other types of parameterization
this involves an iterative optimization over all the
parameters of op_to_optimize.
Parameters
----------
op_to_optimize : LinearOperator
The operation to optimize. This object gets altered.
target_op : LinearOperator
The operation whose matrix is used as the target.
Returns
-------
None
"""
#TODO: cleanup this code:
if isinstance(op_to_optimize, StaticDenseOp):
return # nothing to optimize
if isinstance(op_to_optimize, FullDenseOp):
if(target_op.dim != op_to_optimize.dim): # special case: operations can have different overall dimension
op_to_optimize.dim = target_op.dim # this is a HACK to allow model selection code to work correctly
op_to_optimize.set_dense(target_op) # just copy entire overall matrix since fully parameterized
return
assert(target_op.dim == op_to_optimize.dim) # operations must have the same overall dimension
targetMatrix = _np.asarray(target_op)
def _objective_func(param_vec):
op_to_optimize.from_vector(param_vec)
return _mt.frobeniusnorm(op_to_optimize - targetMatrix)
x0 = op_to_optimize.to_vector()
minSol = _opt.minimize(_objective_func, x0, method='BFGS', maxiter=10000, maxfev=10000,
tol=1e-6, callback=None)
op_to_optimize.from_vector(minSol.x)
#print("DEBUG: optimized operation to min frobenius distance %g" %
# _mt.frobeniusnorm(op_to_optimize-targetMatrix))
def compose(op1, op2, basis, parameterization="auto"):
"""
Returns a new LinearOperator that is the composition of op1 and op2.
The resulting operation's matrix == dot(op1, op2),
(so op1 acts *second* on an input) and the type of LinearOperator instance
returned will depend on how much of the parameterization in op1
and op2 can be preserved in the resulting operation.
Parameters
----------
op1 : LinearOperator
LinearOperator to compose as left term of matrix product (applied second).
op2 : LinearOperator
LinearOperator to compose as right term of matrix product (applied first).
basis : {'std', 'gm', 'pp', 'qt'} or Basis object
The source and destination basis, respectively. Allowed
values are Matrix-unit (std), Gell-Mann (gm), Pauli-product (pp),
and Qutrit (qt) (or a custom basis object).
parameterization : {"auto","full","TP","linear","static"}, optional
The parameterization of the resulting operations. The default, "auto",
attempts to convert to the most restrictive common parameterization.
Returns
-------
LinearOperator
The composed operation.
"""
#Find the most restrictive common parameterization that both op1
# and op2 can be cast/converted into. Utilized converstions are:
#
# Static => TP (sometimes)
# Static => Linear
# Static => Full
# Linear => TP (sometimes)
# Linear => Full
# TP => Full
if parameterization == "auto":
if any([isinstance(g, FullDenseOp) for g in (op1, op2)]):
paramType = "full"
elif any([isinstance(g, TPDenseOp) for g in (op1, op2)]):
paramType = "TP" # update to "full" below if TP-conversion
#not possible?
elif any([isinstance(g, LinearlyParamDenseOp)
for g in (op1, op2)]):
paramType = "linear"
else:
assert(isinstance(op1, StaticDenseOp)
and isinstance(op2, StaticDenseOp))
paramType = "static"
else:
paramType = parameterization # user-specified final parameterization
#Convert to paramType as necessary
cop1 = convert(op1, paramType, basis)
cop2 = convert(op2, paramType, basis)
# cop1 and cop2 are the same type, so can invoke the operation's compose method
return cop1.compose(cop2)
def convert(operation, to_type, basis, extra=None):
"""
Convert operation to a new type of parameterization.
This potentially creates a new LinearOperator object, and
Raises ValueError for invalid conversions.
Parameters
----------
operation : LinearOperator
LinearOperator to convert
to_type : {"full","TP","static","static unitary","clifford",LINDBLAD}
The type of parameterizaton to convert to. "LINDBLAD" is a placeholder
for the various Lindblad parameterization types. See
:method:`Model.set_all_parameterizations` for more details.
basis : {'std', 'gm', 'pp', 'qt'} or Basis object
The basis for `operation`. Allowed values are Matrix-unit (std),
Gell-Mann (gm), Pauli-product (pp), and Qutrit (qt)
(or a custom basis object).
extra : object, optional
Additional information for conversion.
Returns
-------
LinearOperator
The converted operation, usually a distinct
object from the operation object passed as input.
"""
if to_type == "full":
if isinstance(operation, FullDenseOp):
return operation # no conversion necessary
else:
return FullDenseOp(operation.to_dense())
elif to_type == "TP":
if isinstance(operation, TPDenseOp):
return operation # no conversion necessary
else:
return TPDenseOp(operation.to_dense())
# above will raise ValueError if conversion cannot be done
elif to_type == "linear":
if isinstance(operation, LinearlyParamDenseOp):
return operation # no conversion necessary
elif isinstance(operation, StaticDenseOp):
real = _np.isclose(_np.linalg.norm(operation.imag), 0)
return LinearlyParamDenseOp(operation.to_dense(), _np.array([]), {}, real)
else:
raise ValueError("Cannot convert type %s to LinearlyParamDenseOp"
% type(operation))
elif to_type == "static":
if isinstance(operation, StaticDenseOp):
return operation # no conversion necessary
else:
return StaticDenseOp(operation.to_dense())
elif to_type == "static unitary":
op_std = _bt.change_basis(operation, basis, 'std')
unitary = _gt.process_mx_to_unitary(op_std)
return StaticDenseOp(unitary, "statevec")
elif _gt.is_valid_lindblad_paramtype(to_type):
# e.g. "H+S terms","H+S clifford terms"
_, evotype = _gt.split_lindblad_paramtype(to_type)
LindbladOpType = LindbladOp \
if evotype in ("svterm", "cterm") else \
LindbladDenseOp
nQubits = _np.log2(operation.dim) / 2.0
bQubits = bool(abs(nQubits - round(nQubits)) < 1e-10) # integer # of qubits?
proj_basis = "pp" if (basis == "pp" or bQubits) else basis
#FUTURE: do something like this to get a guess for the post-op unitary factor
# (this commented code doesn't seem to work quite right). Such intelligence should
# help scenarios where the assertion below fails.
#if isinstance(operation, DenseOperator):
# J = _jt.jamiolkowski_iso(operation.to_dense(), opMxBasis=basis, choiMxBasis="std")
# ev, U = _np.linalg.eig(operation.to_dense())
# imax = _np.argmax(ev)
# J_unitary = _np.kron(U[:,imax:imax+1], U[:,imax:imax+1].T)
# postfactor = _jt.jamiolkowski_iso_inv(J_unitary, choiMxBasis="std", opMxBasis=basis)
# unitary = _gt.process_mx_to_unitary(postfactor)
#else:
postfactor = None
ret = LindbladOpType.from_operation_obj(operation, to_type, postfactor, proj_basis,
basis, truncate=True, lazy=True)
if ret.dim <= 16: # only do this for up to 2Q operations, otherwise to_dense is too expensive
assert(_np.linalg.norm(operation.to_dense() - ret.to_dense()) < 1e-6), \
"Failure to create CPTP operation (maybe due the complex log's branch cut?)"
return ret
elif to_type == "clifford":
if isinstance(operation, CliffordOp):
return operation # no conversion necessary
# assume operation represents a unitary op (otherwise
# would need to change Model dim, which isn't allowed)
return CliffordOp(operation)
else:
raise ValueError("Invalid to_type argument: %s" % to_type)
def finite_difference_deriv_wrt_params(operation, wrt_filter, eps=1e-7):
"""
Computes a finite-difference Jacobian for a LinearOperator object.
The returned value is a matrix whose columns are the vectorized
derivatives of the flattened operation matrix with respect to a single
operation parameter, matching the format expected from the operation's
`deriv_wrt_params` method.
Parameters
----------
operation : LinearOperator
The operation object to compute a Jacobian for.
wrt_filter : list or numpy.ndarray
List of parameter indices to filter the result by (as though
derivative is only taken with respect to these parameters).
eps : float, optional
The finite difference step to use.
Returns
-------
numpy.ndarray
An M by N matrix where M is the number of operation elements and
N is the number of operation parameters.
"""
dim = operation.dim
#operation.from_vector(operation.to_vector()) #ensure we call from_vector w/close=False first
op2 = operation.copy()
p = operation.to_vector()
fd_deriv = _np.empty((dim, dim, operation.num_params), operation.dtype)
for i in range(operation.num_params):
p_plus_dp = p.copy()
p_plus_dp[i] += eps
op2.from_vector(p_plus_dp)
fd_deriv[:, :, i] = (op2 - operation) / eps
fd_deriv.shape = [dim**2, operation.num_params]
if wrt_filter is None:
return fd_deriv
else:
return _np.take(fd_deriv, wrt_filter, axis=1)
def check_deriv_wrt_params(operation, deriv_to_check=None, wrt_filter=None, eps=1e-7):
"""
Checks the `deriv_wrt_params` method of a LinearOperator object.
This routine is meant to be used as an aid in testing and debugging
operation classes by comparing the finite-difference Jacobian that
*should* be returned by `operation.deriv_wrt_params` with the one that
actually is. A ValueError is raised if the two do not match.
Parameters
----------
operation : LinearOperator
The operation object to test.
deriv_to_check : numpy.ndarray or None, optional
If not None, the Jacobian to compare against the finite difference
result. If None, `operation.deriv_wrt_parms()` is used. Setting this
argument can be useful when the function is called *within* a LinearOperator
class's `deriv_wrt_params()` method itself as a part of testing.
wrt_filter : list or numpy.ndarray
List of parameter indices to filter the result by (as though
derivative is only taken with respect to these parameters).
eps : float, optional
The finite difference step to use.
Returns
-------
None
"""
fd_deriv = finite_difference_deriv_wrt_params(operation, wrt_filter, eps)
if deriv_to_check is None:
deriv_to_check = operation.deriv_wrt_params()
#print("Deriv shapes = %s and %s" % (str(fd_deriv.shape),
# str(deriv_to_check.shape)))
#print("finite difference deriv = \n",fd_deriv)
#print("deriv_wrt_params deriv = \n",deriv_to_check)
#print("deriv_wrt_params - finite diff deriv = \n",
# deriv_to_check - fd_deriv)
for i in range(deriv_to_check.shape[0]):
for j in range(deriv_to_check.shape[1]):
diff = abs(deriv_to_check[i, j] - fd_deriv[i, j])
if diff > 10 * eps:
print("deriv_chk_mismatch: (%d,%d): %g (comp) - %g (fd) = %g" %
(i, j, deriv_to_check[i, j], fd_deriv[i, j], diff)) # pragma: no cover
if _np.linalg.norm(fd_deriv - deriv_to_check) / fd_deriv.size > 10 * eps:
raise ValueError("Failed check of deriv_wrt_params:\n"
" norm diff = %g" %
_np.linalg.norm(fd_deriv - deriv_to_check)) # pragma: no cover
#Note on initialization sequence of Operations within a Model:
# 1) a Model is constructed (empty)
# 2) a LinearOperator is constructed - apart from a Model if it's locally parameterized,
# otherwise with explicit reference to an existing Model's labels/indices.
# All gates (ModelMember objs in general) have a "gpindices" member which
# can either be initialized upon construction or set to None, which signals
# that the Model must initialize it.
# 3) the LinearOperator is assigned/added to a dict within the Model. As a part of this
# process, the LinearOperator's 'gpindices' member is set, if it isn't already, and the
# Model's "global" parameter vector (and number of params) is updated as
# needed to accomodate new parameters.
#
# Note: gpindices may be None (before initialization) or any valid index
# into a 1D numpy array (e.g. a slice or integer array). It may NOT have
# any repeated elements.
#
# When a LinearOperator is removed from the Model, parameters only used by it can be
# removed from the Model, and the gpindices members of existing gates
# adjusted as needed.
#
# When derivatives are taken wrt. a model parameter (1 col of a jacobian)
# derivatives wrt each gate that includes that parameter in its gpindices
# must be processed.
class LinearOperator(_modelmember.ModelMember):
"""
Base class for all operation representations
Parameters
----------
rep : object
A representation object containing the core data for this operator.
evotype : str
The evolution type of this operator, for matching with forward simulators.
Attributes
----------
size : int
Return the number of independent elements in this operation (when viewed as a dense array)
dirty : bool
Whether this object has been modified in a way that could have affected its parameters.
A parent :class:`OpModel` uses this information to know when it needs to refresh it's
model-wide parameter vector.
"""
def __init__(self, rep, evotype):
""" Initialize a new LinearOperator """
if isinstance(rep, int): # For operators that have no representation themselves (term ops)
dim = rep # allow passing an integer as `rep`.
rep = None
else:
dim = rep.dim
super(LinearOperator, self).__init__(dim, evotype)
self._rep = rep
@property
def size(self):
"""
Return the number of independent elements in this operation (when viewed as a dense array)
Returns
-------
int
"""
return (self.dim)**2
def set_dense(self, m):
"""
Set the dense-matrix value of this operation.
Attempts to modify operation parameters so that the specified raw
operation matrix becomes mx. Will raise ValueError if this operation
is not possible.
Parameters
----------
m : array_like or LinearOperator
An array of shape (dim, dim) or LinearOperator representing the operation action.
Returns
-------
None
"""
raise ValueError("Cannot set the value of a %s directly!" % self.__class__.__name__)
def set_time(self, t):
"""
Sets the current time for a time-dependent operator.
For time-independent operators (the default), this function does nothing.
Parameters
----------
t : float
The current time.
Returns
-------
None
"""
pass
#def rep_at_time(self, t):
# """
# Retrieves a representation of this operator at time `t`.
#
# This is operationally equivalent to calling `self.set_time(t)` and
# then retrieving `self._rep`. However, what is returned from this function
# need not be the same rep object for different times, allowing the
# operator object to cache many reps for different times to increase performance
# (this avoids having to initialize the same rep at a given time).
#
# Parameters
# ----------
# t : float
# The time.
#
# Returns
# -------
# object
# """
# self.set_time(t)
# return self._rep
def to_dense(self):
"""
Return this operation as a dense matrix.
Returns
-------
numpy.ndarray
"""
raise NotImplementedError("to_dense(...) not implemented for %s objects!" % self.__class__.__name__)
def acton(self, state):
"""
Act with this operator upon `state`
Parameters
----------
state : SPAMVec
The state to act on
Returns
-------
SPAMVec
The output state
"""
from . import spamvec as _sv # can we move this to top?
assert(self._evotype in ('densitymx', 'statevec', 'stabilizer')), \
"acton(...) cannot be used with the %s evolution type!" % self._evotype
assert(self._rep is not None), "Internal Error: representation is None!"
assert(state._evotype == self._evotype), "Evolution type mismatch: %s != %s" % (self._evotype, state._evotype)
#Perform actual 'acton' operation
output_rep = self._rep.acton(state._rep)
#Build a SPAMVec around output_rep
if self._evotype in ("densitymx", "statevec"):
return _sv.StaticSPAMVec(output_rep.to_dense(), self._evotype, 'prep')
else: # self._evotype == "stabilizer"
return _sv.StabilizerSPAMVec(sframe=_stabilizer.StabilizerFrame(
output_rep.smatrix, output_rep.pvectors, output_rep.amps))
#def torep(self):
# """
# Return a "representation" object for this operation.
#
# Such objects are primarily used internally by pyGSTi to compute
# things like probabilities more efficiently.
#
# Returns
# -------
# OpRep
# """
# if self._evotype == "statevec":
# return replib.SVOpRepDense(_np.ascontiguousarray(self.todense(), complex))
# elif self._evotype == "densitymx":
# if LinearOperator.cache_reps: # cache reps to avoid recomputation
# if self._cachedrep is None:
# self._cachedrep = replib.DMOpRepDense(_np.ascontiguousarray(self.todense(), 'd'))
# return self._cachedrep
# else:
# return replib.DMOpRepDense(_np.ascontiguousarray(self.todense(), 'd'))
# else:
# raise NotImplementedError("torep(%s) not implemented for %s objects!" %
# (self._evotype, self.__class__.__name__))
@property
def dirty(self):
"""
Whether this operator is "dirty" - i.e. may have had its parameters changed.
"""
return _modelmember.ModelMember.dirty.fget(self) # call base class
@dirty.setter
def dirty(self, value):
"""
Whether this operator is "dirty" - i.e. may have had its parameters changed.
"""
if value:
self._cachedrep = None # clear cached rep
_modelmember.ModelMember.dirty.fset(self, value) # call base class setter
def __getstate__(self):
st = super(LinearOperator, self).__getstate__()
st['_cachedrep'] = None # can't pickle this!
return st
def copy(self, parent=None, memo=None):
"""
Copy this LinearOperator.
Parameters
----------
parent : Model, optional
The parent model to set for the copy.
"""
self._cachedrep = None # deepcopy in ModelMember.copy can't copy CReps!
return _modelmember.ModelMember.copy(self, parent, memo)
def to_sparse(self):
"""
Return this operation as a sparse matrix.
Returns
-------
scipy.sparse.csr_matrix
"""
raise NotImplementedError("to_sparse(...) not implemented for %s objects!" % self.__class__.__name__)
def taylor_order_terms(self, order, max_polynomial_vars=100, return_coeff_polys=False):
"""
Get the `order`-th order Taylor-expansion terms of this operation.
This function either constructs or returns a cached list of the terms at
the given order. Each term is "rank-1", meaning that its action on a
density matrix `rho` can be written:
`rho -> A rho B`
The coefficients of these terms are typically polynomials of the operation's
parameters, where the polynomial's variable indices index the *global*
parameters of the operation's parent (usually a :class:`Model`), not the
operation's local parameter array (i.e. that returned from `to_vector`).
Parameters
----------
order : int
The order of terms to get.
max_polynomial_vars : int, optional
maximum number of variables the created polynomials can have.
return_coeff_polys : bool
Whether a parallel list of locally-indexed (using variable indices
corresponding to *this* object's parameters rather than its parent's)
polynomial coefficients should be returned as well.
Returns
-------
terms : list
A list of :class:`RankOneTerm` objects.
coefficients : list
Only present when `return_coeff_polys == True`.
A list of *compact* polynomial objects, meaning that each element
is a `(vtape,ctape)` 2-tuple formed by concatenating together the
output of :method:`Polynomial.compact`.
"""
raise NotImplementedError("taylor_order_terms(...) not implemented for %s objects!" %
self.__class__.__name__)
def highmagnitude_terms(self, min_term_mag, force_firstorder=True, max_taylor_order=3, max_polynomial_vars=100):
"""
Get terms with magnitude above `min_term_mag`.
Get the terms (from a Taylor expansion of this operator) that have
magnitude above `min_term_mag` (the magnitude of a term is taken to
be the absolute value of its coefficient), considering only those
terms up to some maximum Taylor expansion order, `max_taylor_order`.
Note that this function also *sets* the magnitudes of the returned
terms (by calling `term.set_magnitude(...)`) based on the current
values of this operator's parameters. This is an essential step
to using these terms in pruned-path-integral calculations later on.
Parameters
----------
min_term_mag : float
the threshold for term magnitudes: only terms with magnitudes above
this value are returned.
force_firstorder : bool, optional
if True, then always return all the first-order Taylor-series terms,
even if they have magnitudes smaller than `min_term_mag`. This
behavior is needed for using GST with pruned-term calculations, as
we may begin with a guess model that has no error (all terms have
zero magnitude!) and still need to compute a meaningful jacobian at
this point.
max_taylor_order : int, optional
the maximum Taylor-order to consider when checking whether term-
magnitudes exceed `min_term_mag`.
max_polynomial_vars : int, optional
maximum number of variables the created polynomials can have.
Returns
-------
highmag_terms : list
A list of the high-magnitude terms that were found. These
terms are *sorted* in descending order by term-magnitude.
first_order_indices : list
A list of the indices into `highmag_terms` that mark which
of these terms are first-order Taylor terms (useful when
we're forcing these terms to always be present).
"""
#print("DB: OP get_high_magnitude_terms")
v = self.to_vector()
taylor_order = 0
terms = []; last_len = -1; first_order_magmax = 1.0
while len(terms) > last_len: # while we keep adding something
if taylor_order > 1 and first_order_magmax**taylor_order < min_term_mag:
break # there's no way any terms at this order reach min_term_mag - exit now!
MAX_CACHED_TERM_ORDER = 1
if taylor_order <= MAX_CACHED_TERM_ORDER:
terms_at_order, cpolys = self.taylor_order_terms(taylor_order, max_polynomial_vars, True)
coeffs = _bulk_eval_compact_polynomials_complex(
cpolys[0], cpolys[1], v, (len(terms_at_order),)) # an array of coeffs
terms_at_order = [t.copy_with_magnitude(abs(coeff)) for coeff, t in zip(coeffs, terms_at_order)]
# CHECK - to ensure term magnitudes are being set correctly (i.e. are in sync with evaluated coeffs)
# REMOVE later
# for t in terms_at_order:
# vt, ct = t._rep.coeff.compact_complex()
# coeff_array = _bulk_eval_compact_polynomials_complex(vt, ct, self.parent.to_vector(), (1,))
# if not _np.isclose(abs(coeff_array[0]), t._rep.magnitude): # DEBUG!!!
# print(coeff_array[0], "vs.", t._rep.magnitude)
# import bpdb; bpdb.set_trace()
if taylor_order == 1:
first_order_magmax = max([t.magnitude for t in terms_at_order])
last_len = len(terms)
for t in terms_at_order:
if t.magnitude >= min_term_mag or (taylor_order == 1 and force_firstorder):
terms.append((taylor_order, t))
else:
eff_min_term_mag = 0.0 if (taylor_order == 1 and force_firstorder) else min_term_mag
terms.extend(
[(taylor_order, t)
for t in self.taylor_order_terms_above_mag(taylor_order, max_polynomial_vars, eff_min_term_mag)]
)
#print("order ", taylor_order, " : ", len(terms_at_order), " maxmag=",
# max([t.magnitude for t in terms_at_order]), len(terms), " running terms ",
# len(terms)-last_len, "added at this order")
taylor_order += 1
if taylor_order > max_taylor_order: break
#Sort terms based on magnitude
sorted_terms = sorted(terms, key=lambda t: t[1].magnitude, reverse=True)
first_order_indices = [i for i, t in enumerate(sorted_terms) if t[0] == 1]
#DEBUG TODO REMOVE
#chk1 = sum([t[1].magnitude for t in sorted_terms])
#chk2 = self.total_term_magnitude
#print("HIGHMAG ",self.__class__.__name__, len(sorted_terms), " maxorder=",max_taylor_order,
# " minmag=",min_term_mag)
#print(" sum of magnitudes =",chk1, " <?= ", chk2)
#if chk1 > chk2:
# print("Term magnitudes = ", [t[1].magnitude for t in sorted_terms])
# egterms = self.errorgen.get_taylor_order_terms(0)
# #vtape, ctape = self.errorgen.Lterm_coeffs
# #coeffs = [ abs(x) for x in _bulk_eval_compact_polynomials_complex(vtape, ctape, self.errorgen.to_vector(),
# # (len(self.errorgen.Lterms),)) ]
# mags = [ abs(t.evaluate_coeff(self.errorgen.to_vector()).coeff) for t in egterms ]
# print("Errorgen ", self.errorgen.__class__.__name__, " term magnitudes (%d): " % len(egterms),
# "\n",list(sorted(mags, reverse=True)))
# print("Errorgen sum = ",sum(mags), " vs ", self.errorgen.get_total_term_magnitude())
#assert(chk1 <= chk2)
return [t[1] for t in sorted_terms], first_order_indices
def taylor_order_terms_above_mag(self, order, max_polynomial_vars, min_term_mag):
"""
Get the `order`-th order Taylor-expansion terms of this operation that have magnitude above `min_term_mag`.
This function constructs the terms at the given order which have a magnitude (given by
the absolute value of their coefficient) that is greater than or equal to `min_term_mag`.
It calls :method:`taylor_order_terms` internally, so that all the terms at order `order`
are typically cached for future calls.
The coefficients of these terms are typically polynomials of the operation's
parameters, where the polynomial's variable indices index the *global*
parameters of the operation's parent (usually a :class:`Model`), not the
operation's local parameter array (i.e. that returned from `to_vector`).
Parameters
----------
order : int
The order of terms to get (and filter).
max_polynomial_vars : int, optional
maximum number of variables the created polynomials can have.
min_term_mag : float
the minimum term magnitude.
Returns
-------
list
A list of :class:`Rank1Term` objects.
"""
v = self.to_vector()
terms_at_order, cpolys = self.taylor_order_terms(order, max_polynomial_vars, True)
coeffs = _bulk_eval_compact_polynomials_complex(
cpolys[0], cpolys[1], v, (len(terms_at_order),)) # an array of coeffs
terms_at_order = [t.copy_with_magnitude(abs(coeff)) for coeff, t in zip(coeffs, terms_at_order)]
#CHECK - to ensure term magnitudes are being set correctly (i.e. are in sync with evaluated coeffs) REMOVE later
#for t in terms_at_order:
# vt,ct = t._rep.coeff.compact_complex()
# coeff_array = _bulk_eval_compact_polynomials_complex(vt,ct,self.parent.to_vector(),(1,))
# if not _np.isclose(abs(coeff_array[0]), t._rep.magnitude): # DEBUG!!!
# print(coeff_array[0], "vs.", t._rep.magnitude)
# import bpdb; bpdb.set_trace()
return [t for t in terms_at_order if t.magnitude >= min_term_mag]
def frobeniusdist_squared(self, other_op, transform=None, inv_transform=None):
"""
Return the squared frobenius difference between this operation and `other_op`
Optionally transforms this operation first using matrices
`transform` and `inv_transform`. Specifically, this operation gets
transfomed as: `O => inv_transform * O * transform` before comparison with
`other_op`.
Parameters
----------
other_op : DenseOperator
The other operation.
transform : numpy.ndarray, optional
Transformation matrix.
inv_transform : numpy.ndarray, optional
Inverse of `transform`.
Returns
-------
float
"""
if transform is None and inv_transform is None:
return _gt.frobeniusdist_squared(self.to_dense(), other_op.to_dense())
else:
return _gt.frobeniusdist_squared(_np.dot(
inv_transform, _np.dot(self.to_dense(), transform)),
other_op.to_dense())
def frobeniusdist(self, other_op, transform=None, inv_transform=None):
"""
Return the frobenius distance between this operation and `other_op`.
Optionally transforms this operation first using matrices
`transform` and `inv_transform`. Specifically, this operation gets
transfomed as: `O => inv_transform * O * transform` before comparison with
`other_op`.
Parameters
----------
other_op : DenseOperator
The other operation.
transform : numpy.ndarray, optional
Transformation matrix.
inv_transform : numpy.ndarray, optional
Inverse of `transform`.
Returns
-------
float
"""
return _np.sqrt(self.frobeniusdist_squared(other_op, transform, inv_transform))
def residuals(self, other_op, transform=None, inv_transform=None):
"""
The per-element difference between this `DenseOperator` and `other_op`.
Optionally, tansforming this operation first as
`O => inv_transform * O * transform`.
Parameters
----------
other_op : DenseOperator
The operation to compare against.
transform : numpy.ndarray, optional
Transformation matrix.
inv_transform : numpy.ndarray, optional
Inverse of `transform`.
Returns
-------
numpy.ndarray
A 1D-array of size equal to that of the flattened operation matrix.
"""
if transform is None and inv_transform is None:
return _gt.residuals(self.to_dense(), other_op.to_dense())
else:
return _gt.residuals(_np.dot(
inv_transform, _np.dot(self.to_dense(), transform)),
other_op.to_dense())
def jtracedist(self, other_op, transform=None, inv_transform=None):
"""
Return the Jamiolkowski trace distance between this operation and `other_op`.
Optionally, tansforming this operation first as
`O => inv_transform * O * transform`.
Parameters
----------
other_op : DenseOperator
The operation to compare against.
transform : numpy.ndarray, optional
Transformation matrix.
inv_transform : numpy.ndarray, optional
Inverse of `transform`.
Returns
-------
float
"""
if transform is None and inv_transform is None:
return _gt.jtracedist(self.to_dense(), other_op.to_dense())
else:
return _gt.jtracedist(_np.dot(
inv_transform, _np.dot(self.to_dense(), transform)),
other_op.to_dense())
def diamonddist(self, other_op, transform=None, inv_transform=None):
"""
Return the diamond distance between this operation and `other_op`.
Optionally, tansforming this operation first as
`O => inv_transform * O * transform`.
Parameters
----------
other_op : DenseOperator
The operation to compare against.
transform : numpy.ndarray, optional
Transformation matrix.
inv_transform : numpy.ndarray, optional
Inverse of `transform`.
Returns
-------
float
"""
if transform is None and inv_transform is None:
return _gt.diamonddist(self.to_dense(), other_op.to_dense())
else:
return _gt.diamonddist(_np.dot(
inv_transform, _np.dot(self.to_dense(), transform)),
other_op.to_dense())
def transform_inplace(self, s):
"""
Update operation matrix `O` with `inv(s) * O * s`.
Generally, the transform function updates the *parameters* of
the operation such that the resulting operation matrix is altered as
described above. If such an update cannot be done (because
the operation parameters do not allow for it), ValueError is raised.
In this particular case *any* transform of the appropriate
dimension is possible, since all operation matrix elements are parameters.
Parameters
----------
s : GaugeGroupElement
A gauge group element which specifies the "s" matrix
(and it's inverse) used in the above similarity transform.
Returns
-------
None
"""
Smx = s.transform_matrix
Si = s.transform_matrix_inverse
self.set_dense(_np.dot(Si, _np.dot(self.to_dense(), Smx)))
def depolarize(self, amount):
"""
Depolarize this operation by the given `amount`.
Generally, the depolarize function updates the *parameters* of
the operation such that the resulting operation matrix is depolarized. If
such an update cannot be done (because the operation parameters do not
allow for it), ValueError is raised.
Parameters
----------
amount : float or tuple
The amount to depolarize by. If a tuple, it must have length
equal to one less than the dimension of the operation. In standard
bases, depolarization corresponds to multiplying the operation matrix