/
objectivefns.py
6446 lines (5156 loc) · 270 KB
/
objectivefns.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 objective-function objects
"""
#***************************************************************************************************
# 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 itertools as _itertools
import sys as _sys
import time as _time
import pathlib as _pathlib
import numpy as _np
from pygsti import tools as _tools
from pygsti.layouts.distlayout import DistributableCOPALayout as _DistributableCOPALayout
from pygsti.tools import slicetools as _slct, mpitools as _mpit, sharedmemtools as _smt
from pygsti.circuits.circuitlist import CircuitList as _CircuitList
from pygsti.baseobjs.resourceallocation import ResourceAllocation as _ResourceAllocation
from pygsti.baseobjs.nicelyserializable import NicelySerializable as _NicelySerializable
from pygsti.baseobjs.verbosityprinter import VerbosityPrinter as _VerbosityPrinter
def _objfn(objfn_cls, model, dataset, circuits=None,
regularization=None, penalties=None, op_label_aliases=None,
comm=None, mem_limit=None, method_names=None, array_types=None,
mdc_store=None, verbosity=0, **addl_args):
"""
A convenience function for creating an objective function.
Takes a number of common parameters and automates the creation of
intermediate objects like a :class:`ResourceAllocation` and
:class:`CircuitList`.
Parameters
----------
objfn_cls : class
The :class:`MDCObjectiveFunction`-derived class to create.
model : Model
The model.
dataset : DataSet
The data.
circuits : list, optional
The circuits.
regularization : dict, optional
A dictionary of regularization values.
penalties : dict, optional
A dictionary of penalty values.
op_label_aliases : dict, optional
An alias dictionary.
comm : mpi4py.MPI.Comm, optional
For splitting load among processors.
mem_limit : int, optional
Rough memory limit in bytes.
method_names : tuple
A tuple of the method names of the returned objective function
that will be called (used to estimate memory and setup resource division)
array_types : tuple
A tuple of array types that will be allocated, in addition to those contained in
the returned objective functon itself and within the methods given by `method_names`.
mdc_store : ModelDatasetCircuitsStore, optional
An object that bundles cached quantities along with a given model, dataset, and circuit
list. If given, `model` and `dataset` and `circuits` should be set to None.
verbosity : int or VerbosityPrinter, optional
Amount of information printed to stdout.
Returns
-------
ObjectiveFunction
"""
if mdc_store is None:
if circuits is None:
circuits = list(dataset.keys())
if op_label_aliases:
circuits = _CircuitList(circuits, op_label_aliases)
resource_alloc = _ResourceAllocation(comm, mem_limit)
ofn = objfn_cls.create_from(model, dataset, circuits, regularization, penalties,
resource_alloc, verbosity=verbosity,
method_names=method_names if (method_names is not None) else ('fn',),
array_types=array_types if (array_types is not None) else (),
**addl_args)
else:
#Create directly from store object, which contains everything else
assert(model is None and dataset is None and circuits is None and comm is None and mem_limit is None)
# Note: allow method_names and array_types to be non-None and still work with mdc_store, since
# the way this function is used in chi2fns.py and likelihoodfns.py hard-codes these values.
ofn = objfn_cls(mdc_store, regularization, penalties, verbosity=0, **addl_args)
return ofn
#def __len__(self):
# return len(self.circuits)
class ObjectiveFunctionBuilder(_NicelySerializable):
"""
A factory class for building objective functions.
This is useful because often times the user will want to
specify some but not all of the information needed to create
an actual objective function object. Namely, regularization
and penalty values are known ahead of time, while the model,
dataset, and circuits are supplied later, internally, when
running a protocol.
Parameters
----------
cls_to_build : class
The :class:`MDCObjectiveFunction`-derived objective function class to build.
name : str, optional
A name for the built objective function (can be anything).
description : str, optional
A description for the built objective function (can be anything)
regularization : dict, optional
Regularization values (allowed keys depend on `cls_to_build`).
penalties : dict, optional
Penalty values (allowed keys depend on `cls_to_build`).
"""
@classmethod
def cast(cls, obj):
"""
Cast `obj` to an `ObjectiveFunctionBuilder` instance.
If `obj` is already an `ObjectiveFunctionBuilder` instance, it is simply returned.
Otherwise a new `ObjectiveFunctionBuilder` instance is created from `obj` if possible.
Parameters
----------
obj : None or str or dict or list or tuple or ObjectiveFunctionBuilder
Object to cast.
Returns
-------
ObjectiveFunctionBuilder
"""
if isinstance(obj, cls): return obj
elif obj is None: return cls.create_from()
elif isinstance(obj, str): return cls.create_from(objective=obj)
elif isinstance(obj, dict): return cls.create_from(**obj)
elif isinstance(obj, (list, tuple)): return cls(*obj)
else: raise ValueError("Cannot create an %s object from '%s'" % (cls.__name__, str(type(obj))))
@classmethod
def create_from(cls, objective='logl', freq_weighted_chi2=False):
"""
Creates common :class:`ObjectiveFunctionBuilder`s from a few arguments.
Parameters
----------
objective : {'logl', 'chi2'}, optional
The objective function type: log-likelihood or chi-squared.
freq_weighted_chi2 : bool, optional
Whether to use 1/frequency values as the weights in the `"chi2"` case.
Returns
-------
ObjectiveFunctionBuilder
"""
if objective == "chi2":
if freq_weighted_chi2:
builder = FreqWeightedChi2Function.builder(
name='fwchi2',
description="Freq-weighted sum of Chi^2",
regularization={'min_freq_clip_for_weighting': 1e-4})
else:
builder = Chi2Function.builder(
name='chi2',
description="Sum of Chi^2",
regularization={'min_prob_clip_for_weighting': 1e-4})
elif objective == "logl":
builder = PoissonPicDeltaLogLFunction.builder(
name='dlogl',
description="2*Delta(log(L))",
regularization={'min_prob_clip': 1e-4,
'radius': 1e-4},
penalties={'cptp_penalty_factor': 0,
'spam_penalty_factor': 0})
elif objective == "tvd":
builder = TVDFunction.builder(
name='tvd',
description="Total Variational Distance (TVD)")
else:
raise ValueError("Invalid objective: %s" % objective)
assert(isinstance(builder, cls)), "This function should always return an ObjectiveFunctionBuilder!"
return builder
def __init__(self, cls_to_build, name=None, description=None, regularization=None, penalties=None, **kwargs):
self.name = name if (name is not None) else cls_to_build.__name__
self.description = description if (description is not None) else "_objfn" # "Sum of Chi^2" OR "2*Delta(log(L))"
self.cls_to_build = cls_to_build
self.regularization = regularization
self.penalties = penalties
self.additional_args = kwargs
def _to_nice_serialization(self):
state = super()._to_nice_serialization()
state.update({'name': self.name,
'description': self.description,
'class_to_build': self.cls_to_build.__module__ + '.' + self.cls_to_build.__name__,
'regularization': self.regularization,
'penalties': self.penalties,
'additional_arguments': self.additional_args,
})
return state
@classmethod
def _from_nice_serialization(cls, state):
from pygsti.io.metadir import _class_for_name
return cls(_class_for_name(state['class_to_build']), state['name'], state['description'],
state['regularization'], state['penalties'], *state['additional_arguments'])
def compute_array_types(self, method_names, forwardsim):
return self.cls_to_build.compute_array_types(method_names, forwardsim)
def build(self, model, dataset, circuits, resource_alloc=None, verbosity=0):
"""
Build an objective function. This is the workhorse method of an :class:`ObjectiveFunctionBuilder`.
Arguments are the additional information needed to construct a
:class:`MDCObjectiveFunction` object, beyond what is stored in
this builder object.
Parameters
----------
model : Model
The model.
dataset : DataSet.
The data set.
circuits : list
The circuits.
resource_alloc : ResourceAllocation, optional
Available resources and how they should be allocated for objective
function computations.
verbosity : int, optional
Level of detail to print to stdout.
Returns
-------
MDCObjectiveFunction
"""
return self.cls_to_build.create_from(model=model, dataset=dataset, circuits=circuits,
resource_alloc=resource_alloc, verbosity=verbosity,
regularization=self.regularization, penalties=self.penalties,
name=self.name, description=self.description, **self.additional_args)
def build_from_store(self, mdc_store, verbosity=0):
"""
Build an objective function. This is a workhorse method of an :class:`ObjectiveFunctionBuilder`.
Takes a single "store" argument (apart from `verbosity`) that encapsulates all the remaining
ingredients needed to build a :class:`MDCObjectiveFunction` object (beyond what is stored in
this builder object).
Parameters
----------
mdc_store : ModelDatasetCircuitsStore
The store object, which doubles as a cache for reused information.
verbosity : int, optional
Level of detail to print to stdout.
Returns
-------
MDCObjectiveFunction
"""
return self.cls_to_build(mdc_store, verbosity=verbosity,
regularization=self.regularization, penalties=self.penalties,
name=self.name, description=self.description, **self.additional_args)
class ObjectiveFunction(object):
"""
So far, this is just a base class for organizational purposes
"""
def chi2k_distributed_qty(self, objective_function_value):
"""
Convert a value of this objective function to one that is expected to be chi2_k distributed.
For instance, if the objective function is DeltaLogL then this function would
multiply `objective_function_value` by 2, whereas in the case of a chi-squared
objective function this function just return `objective_function_value`.
Parameters
----------
objective_function_value : float
A value of this objective function, i.e. one returned from `self.fn(...)`.
Returns
-------
float
"""
raise ValueError("This objective function does not have chi2_k distributed values!")
class RawObjectiveFunction(ObjectiveFunction):
"""
An objective function that acts on probabilities and counts directly.
Every :class:`RawObjectiveFunction` is assumed to perform a "local" function
element-wise on the vectors of probabilities, counts (usually for a single outcome),
and total-counts (usually for all the outcomes in a group), and sum the results
to arrive at the final objective function's value.
That is, the function must be of the form:
`objective_function = sum_i local_function(probability_i, counts_i, total_counts_i)`.
Each element of this sum (`local_function(probability_i, counts_i, total_counts_i)`)
is called a *term* of the objective function. A vector contains the square-roots
of the terms is referred to as the *least-squares vector* (since least-squares
optimizers use this vector as their objective function) and is abbreviated "lsvec".
Parameters
----------
regularization : dict, optional
Regularization values.
resource_alloc : ResourceAllocation, optional
Available resources and how they should be allocated for computations.
name : str, optional
A name for this objective function (can be anything).
description : str, optional
A description for this objective function (can be anything)
verbosity : int, optional
Level of detail to print to stdout.
"""
def __init__(self, regularization=None, resource_alloc=None, name=None, description=None, verbosity=0):
"""
Create a raw objective function.
A raw objective function acts on "raw" probabilities and counts,
and is usually a statistic comparing the probabilities to count data.
Parameters
----------
regularization : dict, optional
Regularization values.
resource_alloc : ResourceAllocation, optional
Available resources and how they should be allocated for computations.
name : str, optional
A name for this objective function (can be anything).
description : str, optional
A description for this objective function (can be anything)
verbosity : int, optional
Level of detail to print to stdout.
"""
self.resource_alloc = _ResourceAllocation.cast(resource_alloc)
self.printer = _VerbosityPrinter.create_printer(verbosity, self.resource_alloc.comm)
self.name = name if (name is not None) else self.__class__.__name__
self.description = description if (description is not None) else "_objfn"
if regularization is None: regularization = {}
self.set_regularization(**regularization)
def set_regularization(self):
"""
Set regularization values.
"""
pass # no regularization parameters
def _intermediates(self, probs, counts, total_counts, freqs):
""" Intermediate values used by multiple functions (similar to a temporary cache) """
return () # no intermdiate values
def fn(self, probs, counts, total_counts, freqs):
"""
Evaluate the objective function.
Parameters
----------
probs : numpy.ndarray
Array of probability values.
counts : numpy.ndarray
Array of count values.
total_counts : numpy.ndarray
Array of total count values.
freqs : numpy.ndarray
Array of frequency values. This should always equal `counts / total_counts`
but is supplied separately to increase performance.
Returns
-------
float
"""
return _np.sum(self.terms(probs, counts, total_counts, freqs))
def jacobian(self, probs, counts, total_counts, freqs):
"""
Evaluate the derivative of the objective function with respect to the probabilities.
Parameters
----------
probs : numpy.ndarray
Array of probability values.
counts : numpy.ndarray
Array of count values.
total_counts : numpy.ndarray
Array of total count values.
freqs : numpy.ndarray
Array of frequency values. This should always equal `counts / total_counts`
but is supplied separately to increase performance.
Returns
-------
numpy.ndarray
A 1D array of length equal to that of each argument, corresponding to
the derivative with respect to each element of `probs`.
"""
return self.dterms(probs, counts, total_counts, freqs) # same as dterms b/c only i-th term depends on p_i
def hessian(self, probs, counts, total_counts, freqs):
"""
Evaluate the Hessian of the objective function with respect to the probabilities.
Parameters
----------
probs : numpy.ndarray
Array of probability values.
counts : numpy.ndarray
Array of count values.
total_counts : numpy.ndarray
Array of total count values.
freqs : numpy.ndarray
Array of frequency values. This should always equal `counts / total_counts`
but is supplied separately to increase performance.
Returns
-------
numpy.ndarray
A 1D array of length equal to that of each argument, corresponding to
the 2nd derivative with respect to each element of `probs`. Note that this
is not a 2D matrix because all off-diagonal elements of the Hessian are
zero (because only the i-th term depends on the i-th probability).
"""
return self.hterms(probs, counts, total_counts, freqs) # same as dterms b/c only i-th term depends on p_i
def terms(self, probs, counts, total_counts, freqs, intermediates=None):
"""
Compute the terms of the objective function.
The "terms" are the per-(probability, count, total-count) values
that get summed together to result in the objective function value.
These are the "local" or "per-element" values of the objective function.
Parameters
----------
probs : numpy.ndarray
Array of probability values.
counts : numpy.ndarray
Array of count values.
total_counts : numpy.ndarray
Array of total count values.
freqs : numpy.ndarray
Array of frequency values. This should always equal `counts / total_counts`
but is supplied separately to increase performance.
intermediates : tuple, optional
Used internally to speed up computations.
Returns
-------
numpy.ndarray
A 1D array of length equal to that of each array argument.
"""
return self.lsvec(probs, counts, total_counts, freqs, intermediates)**2
def lsvec(self, probs, counts, total_counts, freqs, intermediates=None):
"""
Compute the least-squares vector of the objective function.
This is the square-root of the terms-vector returned from :method:`terms`.
This vector is the objective function value used by a least-squares
optimizer when optimizing this objective function. Note that the existence
of this quantity requires that the terms be non-negative. If this is not
the case, an error is raised.
Parameters
----------
probs : numpy.ndarray
Array of probability values.
counts : numpy.ndarray
Array of count values.
total_counts : numpy.ndarray
Array of total count values.
freqs : numpy.ndarray
Array of frequency values. This should always equal `counts / total_counts`
but is supplied separately to increase performance.
intermediates : tuple, optional
Used internally to speed up computations.
Returns
-------
numpy.ndarray
A 1D array of length equal to that of each array argument.
"""
return _np.sqrt(self.terms(probs, counts, total_counts, freqs, intermediates))
def dterms(self, probs, counts, total_counts, freqs, intermediates=None):
"""
Compute the derivatives of the terms of this objective function.
Note that because each term only depends on the corresponding probability,
this is just an element-wise derivative (or, the diagonal of a jacobian matrix),
i.e. the resulting values are the derivatives of the `local_function` at
each (probability, count, total-count) value.
Parameters
----------
probs : numpy.ndarray
Array of probability values.
counts : numpy.ndarray
Array of count values.
total_counts : numpy.ndarray
Array of total count values.
freqs : numpy.ndarray
Array of frequency values. This should always equal `counts / total_counts`
but is supplied separately to increase performance.
intermediates : tuple, optional
Used internally to speed up computations.
Returns
-------
numpy.ndarray
A 1D array of length equal to that of each array argument.
"""
if intermediates is None:
intermediates = self._intermediates(probs, counts, total_counts, freqs)
return 2 * self.lsvec(probs, counts, total_counts, freqs, intermediates) \
* self.dlsvec(probs, counts, total_counts, freqs, intermediates)
def dlsvec(self, probs, counts, total_counts, freqs, intermediates=None):
"""
Compute the derivatives of the least-squares vector of this objective function.
Note that because each `lsvec` element only depends on the corresponding probability,
this is just an element-wise derivative (or, the diagonal of a jacobian matrix),
i.e. the resulting values are the derivatives of the `local_function` at
each (probability, count, total-count) value.
Parameters
----------
probs : numpy.ndarray
Array of probability values.
counts : numpy.ndarray
Array of count values.
total_counts : numpy.ndarray
Array of total count values.
freqs : numpy.ndarray
Array of frequency values. This should always equal `counts / total_counts`
but is supplied separately to increase performance.
intermediates : tuple, optional
Used internally to speed up computations.
Returns
-------
numpy.ndarray
A 1D array of length equal to that of each array argument.
"""
# lsvec = sqrt(terms)
# dlsvec = 0.5/lsvec * dterms
if intermediates is None:
intermediates = self._intermediates(probs, counts, total_counts, freqs)
lsvec = self.lsvec(probs, counts, total_counts, freqs, intermediates)
pt5_over_lsvec = _np.where(lsvec < 1e-100, 0.0, 0.5 / _np.maximum(lsvec, 1e-100)) # lsvec=0 is *min* w/0 deriv
dterms = self.dterms(probs, counts, total_counts, freqs, intermediates)
return pt5_over_lsvec * dterms
def dlsvec_and_lsvec(self, probs, counts, total_counts, freqs, intermediates=None):
"""
Compute the derivatives of the least-squares vector together with the vector itself.
This is sometimes more computationally efficient than calling :method:`dlsvec` and
:method:`lsvec` separately, as the former call may require computing the latter.
Parameters
----------
probs : numpy.ndarray
Array of probability values.
counts : numpy.ndarray
Array of count values.
total_counts : numpy.ndarray
Array of total count values.
freqs : numpy.ndarray
Array of frequency values. This should always equal `counts / total_counts`
but is supplied separately to increase performance.
intermediates : tuple, optional
Used internally to speed up computations.
Returns
-------
dlsvec: numpy.ndarray
A 1D array of length equal to that of each array argument.
lsvec: numpy.ndarray
A 1D array of length equal to that of each array argument.
"""
#Similar to above, just return lsvec too
if intermediates is None:
intermediates = self._intermediates(probs, counts, total_counts, freqs)
lsvec = self.lsvec(probs, counts, total_counts, freqs, intermediates)
dlsvec = self.dlsvec(probs, counts, total_counts, freqs, intermediates)
return dlsvec, lsvec
def hterms(self, probs, counts, total_counts, freqs, intermediates=None):
"""
Compute the 2nd derivatives of the terms of this objective function.
Note that because each term only depends on the corresponding probability,
this is just an element-wise 2nd derivative, i.e. the resulting values are
the 2nd-derivatives of the `local_function` at each
(probability, count, total-count) value.
Parameters
----------
probs : numpy.ndarray
Array of probability values.
counts : numpy.ndarray
Array of count values.
total_counts : numpy.ndarray
Array of total count values.
freqs : numpy.ndarray
Array of frequency values. This should always equal `counts / total_counts`
but is supplied separately to increase performance.
intermediates : tuple, optional
Used internally to speed up computations.
Returns
-------
numpy.ndarray
A 1D array of length equal to that of each array argument.
"""
# terms = lsvec**2
# dterms/dp = 2*lsvec*dlsvec/dp
# d2terms/dp2 = 2*[ (dlsvec/dp)^2 + lsvec*d2lsvec/dp2 ]
if intermediates is None:
intermediates = self._intermediates(probs, counts, total_counts, freqs)
return 2 * (self.dlsvec(probs, counts, total_counts, freqs, intermediates)**2
+ self.lsvec(probs, counts, total_counts, freqs, intermediates)
* self.hlsvec(probs, counts, total_counts, freqs, intermediates))
def hlsvec(self, probs, counts, total_counts, freqs, intermediates=None):
"""
Compute the 2nd derivatives of the least-squares vector of this objective function.
Note that because each `lsvec` element only depends on the corresponding probability,
this is just an element-wise 2nd derivative, i.e. the resulting values are
the 2nd-derivatives of `sqrt(local_function)` at each (probability, count, total-count) value.
Parameters
----------
probs : numpy.ndarray
Array of probability values.
counts : numpy.ndarray
Array of count values.
total_counts : numpy.ndarray
Array of total count values.
freqs : numpy.ndarray
Array of frequency values. This should always equal `counts / total_counts`
but is supplied separately to increase performance.
intermediates : tuple, optional
Used internally to speed up computations.
Returns
-------
numpy.ndarray
A 1D array of length equal to that of each array argument.
"""
# lsvec = sqrt(terms)
# dlsvec/dp = 0.5 * terms^(-0.5) * dterms/dp
# d2lsvec/dp2 = -0.25 * terms^(-1.5) * (dterms/dp)^2 + 0.5 * terms^(-0.5) * d2terms_dp2
# = 0.5 / sqrt(terms) * (d2terms_dp2 - 0.5 * (dterms/dp)^2 / terms)
if intermediates is None:
intermediates = self._intermediates(probs, counts, total_counts, freqs)
terms = self.terms(probs, counts, total_counts, freqs, intermediates)
dterms = self.dterms(probs, counts, total_counts, freqs, intermediates)
hterms = self.hterms(probs, counts, total_counts, freqs, intermediates)
return 0.5 / _np.sqrt(terms) * (hterms - 0.5 * dterms**2 / terms)
#Required zero-term methods for omitted probs support in model-based objective functions
def zero_freq_terms(self, total_counts, probs):
"""
Evaluate objective function terms with zero frequency (where count and frequency are zero).
Such terms are treated specially because, for some objective functions,
having zero frequency is a special case and must be handled differently.
Parameters
----------
total_counts : numpy.ndarray
The total counts.
probs : numpy.ndarray
The probabilities.
Returns
-------
numpy.ndarray
A 1D array of the same length as `total_counts` and `probs`.
"""
raise NotImplementedError("Derived classes must implement this!")
def zero_freq_dterms(self, total_counts, probs):
"""
Evaluate the derivative of zero-frequency objective function terms.
Zero frequency terms are treated specially because, for some objective functions,
these are a special case and must be handled differently. Derivatives are
evaluated element-wise, i.e. the i-th element of the returned array is the
derivative of the i-th term with respect to the i-th probability (derivatives
with respect to all other probabilities are zero because of the function structure).
Parameters
----------
total_counts : numpy.ndarray
The total counts.
probs : numpy.ndarray
The probabilities.
Returns
-------
numpy.ndarray
A 1D array of the same length as `total_counts` and `probs`.
"""
raise NotImplementedError("Derived classes must implement this!")
def zero_freq_hterms(self, total_counts, probs):
"""
Evaluate the 2nd derivative of zero-frequency objective function terms.
Zero frequency terms are treated specially because, for some objective functions,
these are a special case and must be handled differently. Derivatives are
evaluated element-wise, i.e. the i-th element of the returned array is the
2nd derivative of the i-th term with respect to the i-th probability (derivatives
with respect to all other probabilities are zero because of the function structure).
Parameters
----------
total_counts : numpy.ndarray
The total counts.
probs : numpy.ndarray
The probabilities.
Returns
-------
numpy.ndarray
A 1D array of the same length as `total_counts` and `probs`.
"""
raise NotImplementedError("Derived classes must implement this!")
class ModelDatasetCircuitsStore(object):
"""
Contains all the information that we'd like to persist when performing
(multiple) evaluations of the same circuits using the same model and
data set. For instance, the evaluation of mubltiple (different) objective
functions.
This class holds only quantities that do *not* depend on the contained
model's parameters. See :class:`EvaluatedObjectiveFunction` for a class (TODO??)
that holds the values of an objective function at a certain parameter-space
point.
"""
def __init__(self, model, dataset, circuits=None, resource_alloc=None, array_types=(),
precomp_layout=None, verbosity=0):
self.dataset = dataset
self.model = model
#self.opBasis = mdl.basis
self.resource_alloc = _ResourceAllocation.cast(resource_alloc)
# expand = ??? get from model based on fwdsim type?
circuit_list = circuits if (circuits is not None) else list(dataset.keys())
bulk_circuit_list = circuit_list if isinstance(
circuit_list, _CircuitList) else _CircuitList(circuit_list)
self.circuits = bulk_circuit_list
#The model's forward simulator gets to determine how the circuit outcome
# probabilities (and other results) are stored in arrays - this makes sense
# because it understands how to make this layout amenable to fast computation.
if precomp_layout is None:
self.layout = model.sim.create_layout(bulk_circuit_list, dataset, self.resource_alloc,
array_types, verbosity=verbosity) # a CircuitProbabilityArrayLayout
else:
self.layout = precomp_layout
self.array_types = array_types
if isinstance(self.layout, _DistributableCOPALayout): # then store global circuit liste separately
self.global_circuits = self.circuits
self.circuits = _CircuitList(self.layout.circuits, self.global_circuits.op_label_aliases,
self.global_circuits.circuit_weights, name=None)
else:
self.global_circuits = self.circuits
#self.circuits = bulk_circuit_list[:]
#self.circuit_weights = bulk_circuit_list.circuit_weights
self.ds_circuits = self.circuits.apply_aliases()
# computed by add_count_vectors
self.counts = None
self.total_counts = None
self.freqs = None
# computed by add_omitted_freqs
self.firsts = None
self.indicesOfCircuitsWithOmittedData = None
self.dprobs_omitted_rowsum = None
self.time_dependent = False # indicates whether the data should be treated as time-resolved
#if not self.cache.has_evaltree():
# subcalls = self.get_evaltree_subcalls()
# evt_resource_alloc = _ResourceAllocation(self.raw_objfn.comm, evt_mlim,
# self.raw_objfn.profiler, self.raw_objfn.distribute_method)
# self.cache.add_evaltree(self.mdl, self.dataset, bulk_circuit_list, evt_resource_alloc,
# subcalls, self.raw_objfn.printer - 1)
#self.eval_tree = self.cache.eval_tree
#self.lookup = self.cache.lookup
#self.outcomes_lookup = self.cache.outcomes_lookup
#self.wrt_block_size = self.cache.wrt_block_size
#self.wrt_block_size2 = self.cache.wrt_block_size2
#convenience attributes (could make properties?)
if isinstance(self.layout, _DistributableCOPALayout):
self.global_nelements = self.layout.global_num_elements
self.global_nparams = self.layout.global_num_params
self.global_nparams2 = self.layout.global_num_params2
self.host_nelements = self.layout.host_num_elements
self.host_nparams = self.layout.host_num_params
self.host_nparams2 = self.layout.host_num_params2
self.nelements = _slct.length(self.layout.host_element_slice) # just for *this* proc
self.nparams = _slct.length(self.layout.host_param_slice) \
if self.layout.host_param_slice else self.model.num_params
self.nparams2 = _slct.length(self.layout.host_param2_slice) \
if self.layout.host_param2_slice else self.model.num_params
assert(self.global_nparams is None or self.global_nparams == self.model.num_params)
else:
self.global_nelements = self.host_nelements = self.nelements = len(self.layout)
self.global_nparams = self.host_nparams = self.nparams = self.model.num_params
self.global_nparams2 = self.host_nparams2 = self.nparams2 = self.model.num_params
@property
def opBasis(self):
return self.model.basis
def num_data_params(self):
"""
The number of degrees of freedom in the data used by this objective function.
Returns
-------
int
"""
return self.dataset.degrees_of_freedom(self.ds_circuits,
aggregate_times=not self.time_dependent)
def add_omitted_freqs(self, printer=None, force=False):
"""
Detect omitted frequences (assumed to be 0) so we can compute objective fn correctly
"""
if self.firsts is None or force:
# FUTURE: add any tracked memory? self.resource_alloc.add_tracked_memory(...)
self.firsts = []; self.indicesOfCircuitsWithOmittedData = []
for i, c in enumerate(self.circuits):
indices = _slct.to_array(self.layout.indices_for_index(i))
lklen = _slct.length(self.layout.indices_for_index(i))
if 0 < lklen < self.model.compute_num_outcomes(c):
self.firsts.append(indices[0])
self.indicesOfCircuitsWithOmittedData.append(i)
if len(self.firsts) > 0:
self.firsts = _np.array(self.firsts, 'i')
self.indicesOfCircuitsWithOmittedData = _np.array(self.indicesOfCircuitsWithOmittedData, 'i')
self.dprobs_omitted_rowsum = _np.empty((len(self.firsts), self.nparams), 'd')
#if printer: printer.log("SPARSE DATA: %d of %d rows have sparse data" %
# (len(self.firsts), len(self.circuits)))
else:
self.firsts = None # no omitted probs
def add_count_vectors(self, force=False):
"""
Ensure this store contains count and total-count vectors.
"""
if self.counts is None or self.total_counts is None or force:
#Assume if an item is not None the appropriate amt of memory has already been tracked
if self.counts is None: self.resource_alloc.add_tracked_memory(self.nelements) # 'e'
if self.total_counts is None: self.resource_alloc.add_tracked_memory(self.nelements) # 'e'
if self.freqs is None: self.resource_alloc.add_tracked_memory(self.nelements) # 'e'
# Note: in distributed case self.layout only holds *local* quantities (e.g.
# the .ds_circuits are a subset of all the circuits and .nelements is the local
# number of elements).
counts = _np.empty(self.nelements, 'd')
totals = _np.empty(self.nelements, 'd')
for (i, circuit) in enumerate(self.ds_circuits):
cnts = self.dataset[circuit].counts
totals[self.layout.indices_for_index(i)] = sum(cnts.values()) # dataset[opStr].total
counts[self.layout.indices_for_index(i)] = [cnts.get(x, 0) for x in self.layout.outcomes_for_index(i)]
if self.circuits.circuit_weights is not None:
for i in range(len(self.ds_circuits)): # multiply N's by weights
counts[self.layout.indices_for_index(i)] *= self.circuits.circuit_weights[i]
totals[self.layout.indices_for_index(i)] *= self.circuits.circuit_weights[i]
self.counts = counts
self.total_counts = totals
self.freqs = counts / totals
class EvaluatedModelDatasetCircuitsStore(ModelDatasetCircuitsStore):
"""
Additionally holds quantities at a specific model-parameter-space point.
"""
def __init__(self, mdc_store, verbosity):
super().__init__(mdc_store.model, mdc_store.dataset, mdc_store.global_circuits, mdc_store.resource_alloc,
mdc_store.array_types, mdc_store.layout, verbosity)
# Memory check - see if there's enough memory to hold all the evaluated quantities
#persistent_mem = self.layout.memory_estimate()
#in_gb = 1.0 / 1024.0**3 # in gigabytes