/
likelihoodfns.py
1722 lines (1444 loc) · 76.7 KB
/
likelihoodfns.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
"""Functions related to computation of the log-likelihood."""
from __future__ import division, print_function, absolute_import, unicode_literals
#***************************************************************************************************
# 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.stats as _stats
import warnings as _warnings
import itertools as _itertools
import time as _time
import sys as _sys
from collections import OrderedDict as _OrderedDict
from . import basistools as _bt
from . import listtools as _lt
from . import jamiolkowski as _jam
from . import mpitools as _mpit
from . import slicetools as _slct
from ..baseobjs import smart_cached
TOL = 1e-20
# The log(Likelihood) within the standard (non-Poisson) picture is:
#
# L = prod_{i,sl} p_{i,sl}^N_{i,sl}
#
# Where i indexes the operation sequence, and sl indexes the spam label. N[i] is the total counts
# for the i-th circuit, and so sum_{sl} N_{i,sl} == N[i]. We can take the log:
#
# log L = sum_{i,sl} N_{i,sl} log(p_{i,sl})
#
# after patching (linear extrapolation below min_p and ignore f == 0 terms ( 0*log(0) == 0 ) ):
#
# logl = sum_{i,sl} N_{i,sl} log(p_{i,sl}) if p_{i,sl} >= min_p and N_{i,sl} > 0 # noqa
# N_{i,sl} log(min_p) + S * (p_{i,sl} - min_p) + S2 * (p_{i,sl} - min_p)**2 if p_{i,sl} < p_min and N_{i,sl} > 0 # noqa
# 0 if N_{i,sl} == 0 # noqa
#
# dlogL = sum_{i,sl} N_{i,sl} / p_{i,sl} * dp if p_{i,sl} >= min_p and N_{i,sl} > 0 # noqa
# (S + 2*S2*(p_{i,sl} - min_p)) * dp if p_{i,sl} < p_min and N_{i,sl} > 0 # noqa
# 0 if N_{i,sl} == 0 # noqa
#
# hlogL = sum_{i,sl} -N_{i,sl} / p_{i,sl}**2 * dp1 * dp2 + N_{i,sl} / p_{i,sl} *hp if p_{i,sl} >= min_p and N_{i,sl} > 0 # noqa
# 2*S2* dp1 * dp2 + (S + 2*S2*(p_{i,sl} - min_p)) * hp if p_{i,sl} < p_min and N_{i,sl} > 0 # noqa
# 0 if N_{i,sl} == 0 # noqa
#
# where S = N_{i,sl} / min_p is the slope of the line tangent to logl at min_p
# and S2 = 0.5*( -N_{i,sl} / min_p**2 ) is 1/2 the 2nd derivative of the logl term at min_p
# and hlogL == d/d1 ( d/d2 ( logl ) ) -- i.e. dp2 is the *first* derivative performed...
#Note: Poisson picture entered use when we allowed an EVec which was 1-{other EVecs} -- a
# (0,-1) spam index -- instead of assuming all probabilities of a given gat string summed
# to one -- a (-1,-1) spam index. The poisson picture gives a correct log-likelihood
# description when the probabilities (for a given operation sequence) may not sum to one, by
# interpreting them each as rates. In the standard picture, large circuit probabilities
# are not penalized (each standard logL term increases monotonically with each probability,
# and the reason this is ok when the probabilities sum to one is that for a probabilility
# that gets close to 1, there's another that is close to zero, and logL is very negative
# near zero.
# The log(Likelihood) within the Poisson picture is:
#
# L = prod_{i,sl} lambda_{i,sl}^N_{i,sl} e^{-lambda_{i,sl}} / N_{i,sl}!
#
# Where lamba_{i,sl} := p_{i,sl}*N[i] is a rate, i indexes the operation sequence,
# and sl indexes the spam label. N[i] is the total counts for the i-th circuit, and
# so sum_{sl} N_{i,sl} == N[i]. We can ignore the p-independent N_j! and take the log:
#
# log L = sum_{i,sl} N_{i,sl} log(N[i]*p_{i,sl}) - N[i]*p_{i,sl}
# = sum_{i,sl} N_{i,sl} log(p_{i,sl}) - N[i]*p_{i,sl} (where we ignore the p-independent log(N[i]) terms)
#
# after patching (linear extrapolation below min_p and "softening" f == 0 terms w/cubic below radius "a"):
#
# logl = sum_{i,sl} N_{i,sl} log(p_{i,sl}) - N[i]*p_{i,sl} if p_{i,sl} >= min_p and N_{i,sl} > 0 # noqa
# N_{i,sl} log(min_p) - N[i]*min_p + S * (p_{i,sl} - min_p) + S2 * (p_{i,sl} - min_p)**2 if p_{i,sl} < p_min and N_{i,sl} > 0 # noqa
# 0 - N[i]*p_{i,sl} if N_{i,sl} == 0 and p_{i,sl} >= a # noqa
# 0 - N[i]*( -(1/(3a**2))p_{i,sl}**3 + p_{i,sl}**2/a + (1/3)*a ) if N_{i,sl} == 0 and p_{i,sl} < a # noqa
# - N[i]*Y(1-sum(p_omitted)) added to "first" N_{i,sl} > 0 entry for omitted probabilities, where
# Y(p) = p if p >= a else ( -(1/(3a**2))p**3 + p**2/a + (1/3)*a )
#
# dlogL = sum_{i,sl} [ N_{i,sl} / p_{i,sl} - N[i] ] * dp if p_{i,sl} >= min_p and N_{i,sl} > 0 # noqa
# (S + 2*S2*(p_{i,sl} - min_p)) * dp if p_{i,sl} < p_min and N_{i,sl} > 0 # noqa
# -N[i] * dp if N_{i,sl} == 0 and p_{i,sl} >= a # noqa
# -N[i] * ( (-1/a**2)p_{i,sl}**2 + 2*p_{i,sl}/a ) * dp if N_{i,sl} == 0 and p_{i,sl} < a
# +N[i]*sum(dY/dp_omitted * dp_omitted) added to "first" N_{i,sl} > 0 entry for omitted probabilities
#
# hlogL = sum_{i,sl} -N_{i,sl} / p_{i,sl}**2 * dp1 * dp2 + [ N_{i,sl} / p_{i,sl} - N[i] ]*hp if p_{i,sl} >= min_p and N_{i,sl} > 0 # noqa
# 2*S2* dp1 * dp2 + (S + 2*S2*(p_{i,sl} - min_p)) * hp if p_{i,sl} < p_min and N_{i,sl} > 0 # noqa
# -N[i] * hp if N_{i,sl} == 0 and p_{i,sl} >= a # noqa
# -N[i]*( (-2/a**2)p_{i,sl} + 2/a ) * dp1 * dp2 # noqa
# - N[i]*( (-1/a**2)p_{i,sl}**2 + 2*p_{i,sl}/a ) * hp if N_{i,sl} == 0 and p_{i,sl} < a # noqa
# +N[i]*sum(d2Y/dp_omitted2 * dp_omitted1 * dp_omitted2 +
# dY/dp_omitted * hp_omitted) added to "first" N_{i,sl} > 0 entry for omitted probabilities # noqa
#
# where S = N_{i,sl} / min_p - N[i] is the slope of the line tangent to logl at min_p
# and S2 = 0.5*( -N_{i,sl} / min_p**2 ) is 1/2 the 2nd derivative of the logl term at min_p so
# logL_term = logL_term(min_p) + S * (p-min_p) + S2 * (p-min_p)**2
# and hlogL == d/d1 ( d/d2 ( logl ) ) -- i.e. dp2 is the *first* derivative performed...
#
# For cubic interpolation, use function F(p) (derived by Robin: match value, 1st-deriv, 2nd-deriv at p == r, and require
# min at p == 0):
# Given a radius r << 1 (but r>0):
# F(p) = piecewise{ if( p>r ) then p; else -(1/3)*p^3/r^2 + p^2/r + (1/3)*r }
# OLD: quadratic that doesn't match 2nd-deriv:
# F(p) = piecewise{ if( p>r ) then p; else (r-p)^2/(2*r) + p }
#@smart_cached
def logl_terms(model, dataset, circuit_list=None,
minProbClip=1e-6, probClipInterval=(-1e6, 1e6), radius=1e-4,
poissonPicture=True, check=False, opLabelAliases=None,
evaltree_cache=None, comm=None, smartc=None, wildcard=None):
"""
The vector of log-likelihood contributions for each operation sequence,
aggregated over outcomes.
Parameters
----------
This function takes the same arguments as :func:`logl` except it
doesn't perform the final sum over operation sequences and SPAM labels.
Returns
-------
numpy.ndarray
Array of length either `len(circuit_list)` or `len(dataset.keys())`.
Values are the log-likelihood contributions of the corresponding gate
string aggregated over outcomes.
"""
def smart(fn, *args, **kwargs):
if smartc:
return smartc.cached_compute(fn, args, kwargs)[1]
else:
if '_filledarrays' in kwargs: del kwargs['_filledarrays']
return fn(*args, **kwargs)
if circuit_list is None:
circuit_list = list(dataset.keys())
a = radius # parameterizes "roundness" of f == 0 terms
min_p = minProbClip
if evaltree_cache and 'evTree' in evaltree_cache:
evalTree = evaltree_cache['evTree']
lookup = evaltree_cache['lookup']
outcomes_lookup = evaltree_cache['outcomes_lookup']
#tree_circuit_list = evalTree.generate_circuit_list()
# Note: this is != circuit_list, as the tree hold *simplified* circuits
else:
#OLD: evalTree,lookup,outcomes_lookup = smart(model.bulk_evaltree,circuit_list, dataset=dataset)
evalTree, _, _, lookup, outcomes_lookup = smart(model.bulk_evaltree_from_resources,
circuit_list, comm, dataset=dataset)
#Fill cache dict if one was given
if evaltree_cache is not None:
evaltree_cache['evTree'] = evalTree
evaltree_cache['lookup'] = lookup
evaltree_cache['outcomes_lookup'] = outcomes_lookup
nEls = evalTree.num_final_elements()
probs = _np.zeros(nEls, 'd') # _np.empty( nEls, 'd' ) - .zeros b/c of caching
ds_circuit_list = _lt.find_replace_tuple_list(
circuit_list, opLabelAliases)
if evaltree_cache and 'cntVecMx' in evaltree_cache:
countVecMx = evaltree_cache['cntVecMx']
totalCntVec = evaltree_cache['totalCntVec']
else:
countVecMx = _np.empty(nEls, 'd')
totalCntVec = _np.empty(nEls, 'd')
for (i, opStr) in enumerate(ds_circuit_list):
cnts = dataset[opStr].counts
totalCntVec[lookup[i]] = sum(cnts.values()) # dataset[opStr].total
countVecMx[lookup[i]] = [cnts.get(x, 0) for x in outcomes_lookup[i]]
#could add to cache, but we don't have option of circuitWeights
# here yet, so let's be conservative and not do this:
#if evaltree_cache is not None:
# evaltree_cache['cntVecMx'] = countVecMx
# evaltree_cache['totalCntVec'] = totalCntVec
#Detect omitted frequences (assumed to be 0) so we can compute liklihood correctly
firsts = []; indicesOfCircuitsWithOmittedData = []
for i, c in enumerate(circuit_list):
lklen = _slct.length(lookup[i])
if 0 < lklen < model.get_num_outcomes(c):
firsts.append(_slct.as_array(lookup[i])[0])
indicesOfCircuitsWithOmittedData.append(i)
if len(firsts) > 0:
firsts = _np.array(firsts, 'i')
indicesOfCircuitsWithOmittedData = _np.array(indicesOfCircuitsWithOmittedData, 'i')
else:
firsts = None
smart(model.bulk_fill_probs, probs, evalTree, probClipInterval, check, comm, _filledarrays=(0,))
if wildcard:
probs_in = probs.copy()
wildcard.update_probs(probs_in, probs, countVecMx / totalCntVec, circuit_list, lookup)
pos_probs = _np.where(probs < min_p, min_p, probs)
# XXX: aren't the next blocks duplicated elsewhere?
if poissonPicture:
S = countVecMx / min_p - totalCntVec # slope term that is derivative of logl at min_p
S2 = -0.5 * countVecMx / (min_p**2) # 2nd derivative of logl term at min_p
v = countVecMx * _np.log(pos_probs) - totalCntVec * pos_probs # dim KM (K = nSpamLabels, M = nCircuits)
# remove small positive elements due to roundoff error (above expression *cannot* really be positive)
v = _np.minimum(v, 0)
# quadratic extrapolation of logl at min_p for probabilities < min_p
v = _np.where(probs < min_p, v + S * (probs - min_p) + S2 * (probs - min_p)**2, v)
v = _np.where(countVecMx == 0,
-totalCntVec * _np.where(probs >= a, probs,
(-1.0 / (3 * a**2)) * probs**3 + probs**2 / a + a / 3.0),
v)
#special handling for f == 0 poissonPicture terms using quadratic rounding of function with minimum:
#max(0,(a-p))^2/(2a) + p
if firsts is not None:
omitted_probs = 1.0 - _np.array([_np.sum(pos_probs[lookup[i]])
for i in indicesOfCircuitsWithOmittedData])
v[firsts] -= totalCntVec[firsts] * \
_np.where(omitted_probs >= a, omitted_probs,
(-1.0 / (3 * a**2)) * omitted_probs**3 + omitted_probs**2 / a + a / 3.0)
else:
# (the non-poisson picture requires that the probabilities of the spam labels for a given string are constrained
# to sum to 1)
S = countVecMx / min_p # slope term that is derivative of logl at min_p
S2 = -0.5 * countVecMx / (min_p**2) # 2nd derivative of logl term at min_p
v = countVecMx * _np.log(pos_probs) # dim KM (K = nSpamLabels, M = nCircuits)
# remove small positive elements due to roundoff error (above expression *cannot* really be positive)
v = _np.minimum(v, 0)
# quadratic extrapolation of logl at min_p for probabilities < min_p
v = _np.where(probs < min_p, v + S * (probs - min_p) + S2 * (probs - min_p)**2, v)
v = _np.where(countVecMx == 0, 0.0, v)
#Note: no need to account for omitted probs at all (they contribute nothing)
#DEBUG
#print "num clipped = ",_np.sum(probs < min_p)," of ",probs.shape
#print "min/max probs = ",min(probs.flatten()),",",max(probs.flatten())
#for i in range(v.shape[1]):
# print "%d %.0f (%f) %.0f (%g)" % (i,v[0,i],probs[0,i],v[1,i],probs[1,i])
#Aggregate over outcomes:
# v[iElement] contains all logl contributions - now aggregate over outcomes
# terms[iCircuit] wiil contain logl contributions for each original gate
# string (aggregated over outcomes)
nCircuits = len(circuit_list)
terms = _np.empty(nCircuits, 'd')
for i in range(nCircuits):
terms[i] = _np.sum(v[lookup[i]], axis=0)
return terms
#@smart_cached
def logl(model, dataset, circuit_list=None,
minProbClip=1e-6, probClipInterval=(-1e6, 1e6), radius=1e-4,
poissonPicture=True, check=False, opLabelAliases=None,
evaltree_cache=None, comm=None, smartc=None, wildcard=None):
"""
The log-likelihood function.
Parameters
----------
model : Model
Model of parameterized gates
dataset : DataSet
Probability data
circuit_list : list of (tuples or Circuits), optional
Each element specifies a operation sequence to include in the log-likelihood
sum. Default value of None implies all the operation sequences in dataset
should be used.
minProbClip : float, optional
The minimum probability treated normally in the evaluation of the log-likelihood.
A penalty function replaces the true log-likelihood for probabilities that lie
below this threshold so that the log-likelihood never becomes undefined (which improves
optimizer performance).
probClipInterval : 2-tuple or None, optional
(min,max) values used to clip the probabilities predicted by models during MLEGST's
search for an optimal model (if not None). if None, no clipping is performed.
radius : float, optional
Specifies the severity of rounding used to "patch" the zero-frequency
terms of the log-likelihood.
evalTree : evaluation tree, optional
given by a prior call to bulk_evaltree for the same circuit_list.
Significantly speeds up evaluation of log-likelihood, even more so
when accompanied by countVecMx (see below).
poissonPicture : boolean, optional
Whether the log-likelihood-in-the-Poisson-picture terms should be included
in the returned logl value.
check : boolean, optional
If True, perform extra checks within code to verify correctness. Used
for testing, and runs much slower when True.
opLabelAliases : dictionary, optional
Dictionary whose keys are operation label "aliases" and whose values are tuples
corresponding to what that operation label should be expanded into before querying
the dataset. Defaults to the empty dictionary (no aliases defined)
e.g. opLabelAliases['Gx^3'] = ('Gx','Gx','Gx')
evaltree_cache : dict, optional
A dictionary which server as a cache for the computed EvalTree used
in this computation. If an empty dictionary is supplied, it is filled
with cached values to speed up subsequent executions of this function
which use the *same* `model` and `circuit_list`.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
smartc : SmartCache, optional
A cache object to cache & use previously cached values inside this
function.
wildcard : WildcardBudget
A wildcard budget to apply to this log-likelihood computation.
This increases the returned log-likelihood value by adjusting
(by a maximal amount measured in TVD, given by the budget) the
probabilities produced by `model` to optimially match the data
(within the bugetary constraints) evaluating the log-likelihood.
Returns
-------
float
The log likelihood
"""
v = logl_terms(model, dataset, circuit_list,
minProbClip, probClipInterval, radius,
poissonPicture, check, opLabelAliases,
evaltree_cache, comm, smartc, wildcard)
return _np.sum(v) # sum over *all* dimensions
def logl_jacobian(model, dataset, circuit_list=None,
minProbClip=1e-6, probClipInterval=(-1e6, 1e6), radius=1e-4,
poissonPicture=True, check=False, comm=None,
memLimit=None, opLabelAliases=None, smartc=None,
verbosity=0):
"""
The jacobian of the log-likelihood function.
Parameters
----------
model : Model
Model of parameterized gates (including SPAM)
dataset : DataSet
Probability data
circuit_list : list of (tuples or Circuits), optional
Each element specifies a operation sequence to include in the log-likelihood
sum. Default value of None implies all the operation sequences in dataset
should be used.
minProbClip : float, optional
The minimum probability treated normally in the evaluation of the log-likelihood.
A penalty function replaces the true log-likelihood for probabilities that lie
below this threshold so that the log-likelihood never becomes undefined (which improves
optimizer performance).
probClipInterval : 2-tuple or None, optional
(min,max) values used to clip the probabilities predicted by models during MLEGST's
search for an optimal model (if not None). if None, no clipping is performed.
radius : float, optional
Specifies the severity of rounding used to "patch" the zero-frequency
terms of the log-likelihood.
evalTree : evaluation tree, optional
given by a prior call to bulk_evaltree for the same circuit_list.
Significantly speeds up evaluation of log-likelihood derivatives, even
more so when accompanied by countVecMx (see below). Defaults to None.
poissonPicture : boolean, optional
Whether the Poisson-picutre log-likelihood should be differentiated.
check : boolean, optional
If True, perform extra checks within code to verify correctness. Used
for testing, and runs much slower when True.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
memLimit : int, optional
A rough memory limit in bytes which restricts the amount of intermediate
values that are computed and stored.
opLabelAliases : dictionary, optional
Dictionary whose keys are operation label "aliases" and whose values are tuples
corresponding to what that operation label should be expanded into before querying
the dataset. Defaults to the empty dictionary (no aliases defined)
e.g. opLabelAliases['Gx^3'] = ('Gx','Gx','Gx')
smartc : SmartCache, optional
A cache object to cache & use previously cached values inside this
function.
verbosity : int, optional
How much detail to print to stdout.
Returns
-------
numpy array
array of shape (M,), where M is the length of the vectorized model.
"""
def smart(fn, *args, **kwargs):
if smartc:
return smartc.cached_compute(fn, args, kwargs)[1]
else:
if '_filledarrays' in kwargs: del kwargs['_filledarrays']
return fn(*args, **kwargs)
if circuit_list is None:
circuit_list = list(dataset.keys())
C = 1.0 / 1024.0**3; nP = model.num_params()
persistentMem = 8 * nP + 8 * len(circuit_list) * (nP + 1) # in bytes
if memLimit is not None and memLimit < persistentMem:
raise MemoryError("DLogL Memory limit (%g GB) is " % (memLimit * C)
+ "< memory required to hold final results (%g GB)"
% (persistentMem * C))
#OLD: evalTree,lookup,outcomes_lookup = model.bulk_evaltree(circuit_list)
mlim = None if (memLimit is None) else memLimit - persistentMem
# Note: simplify_circuits doesn't support aliased dataset (yet)
dstree = dataset if (opLabelAliases is None) else None
evalTree, blkSize, _, lookup, outcomes_lookup = \
smart(model.bulk_evaltree_from_resources,
circuit_list, comm, mlim, "deriv", ['bulk_fill_dprobs'],
dstree, verbosity)
a = radius # parameterizes "roundness" of f == 0 terms
min_p = minProbClip
# Allocate persistent memory
jac = _np.zeros([1, nP])
nEls = evalTree.num_final_elements()
probs = _np.empty(nEls, 'd')
dprobs = _np.empty((nEls, nP), 'd')
ds_circuit_list = _lt.find_replace_tuple_list(
circuit_list, opLabelAliases)
countVecMx = _np.empty(nEls, 'd')
totalCntVec = _np.empty(nEls, 'd')
for (i, opStr) in enumerate(ds_circuit_list):
cnts = dataset[opStr].counts
totalCntVec[lookup[i]] = sum(cnts.values()) # dataset[opStr].total
countVecMx[lookup[i]] = [cnts.get(x, 0) for x in outcomes_lookup[i]]
#Detect omitted frequences (assumed to be 0) so we can compute liklihood correctly
firsts = []; indicesOfCircuitsWithOmittedData = []
for i, c in enumerate(circuit_list):
lklen = _slct.length(lookup[i])
if 0 < lklen < model.get_num_outcomes(c):
firsts.append(_slct.as_array(lookup[i])[0])
indicesOfCircuitsWithOmittedData.append(i)
if len(firsts) > 0:
firsts = _np.array(firsts, 'i')
indicesOfCircuitsWithOmittedData = _np.array(indicesOfCircuitsWithOmittedData, 'i')
dprobs_omitted_rowsum = _np.empty((len(firsts), nP), 'd')
else:
firsts = None
smart(model.bulk_fill_dprobs, dprobs, evalTree, prMxToFill=probs,
clipTo=probClipInterval, check=check, comm=comm,
wrtBlockSize=blkSize, _filledarrays=(0, 'prMxToFill')) # FUTURE: set gatherMemLimit=?
pos_probs = _np.where(probs < min_p, min_p, probs)
if poissonPicture:
S = countVecMx / min_p - totalCntVec # slope term that is derivative of logl at min_p
S2 = -0.5 * countVecMx / (min_p**2) # 2nd derivative of logl term at min_p
#TODO: is v actualy needed/used here??
v = countVecMx * _np.log(pos_probs) - totalCntVec * pos_probs # dim KM (K = nSpamLabels, M = nCircuits)
# remove small positive elements due to roundoff error (above expression *cannot* really be positive)
v = _np.minimum(v, 0)
# quadratic extrapolation of logl at min_p for probabilities < min_p
v = _np.where(probs < min_p, v + S * (probs - min_p) + S2 * (probs - min_p)**2, v)
v = _np.where(countVecMx == 0,
-totalCntVec * _np.where(probs >= a, probs,
(-1.0 / (3 * a**2)) * probs**3 + probs**2 / a + a / 3.0),
v)
#special handling for f == 0 poissonPicture terms using quadratic rounding of function with minimum:
#max(0,(a-p))^2/(2a) + p
if firsts is not None:
omitted_probs = 1.0 - _np.array([_np.sum(pos_probs[lookup[i]])
for i in indicesOfCircuitsWithOmittedData])
v[firsts] -= totalCntVec[firsts] * \
_np.where(omitted_probs >= a, omitted_probs,
(-1.0 / (3 * a**2)) * omitted_probs**3 + omitted_probs**2 / a + a / 3.0)
dprobs_factor_pos = (countVecMx / pos_probs - totalCntVec)
dprobs_factor_neg = S + 2 * S2 * (probs - min_p)
dprobs_factor_zerofreq = -totalCntVec * _np.where(probs >= a, 1.0, (-1.0 / a**2) * probs**2 + 2 * probs / a)
dprobs_factor = _np.where(probs < min_p, dprobs_factor_neg, dprobs_factor_pos)
dprobs_factor = _np.where(countVecMx == 0, dprobs_factor_zerofreq, dprobs_factor)
if firsts is not None:
dprobs_factor_omitted = totalCntVec[firsts] * _np.where(
omitted_probs >= a, 1.0,
(-1.0 / a**2) * omitted_probs**2 + 2 * omitted_probs / a)
for ii, i in enumerate(indicesOfCircuitsWithOmittedData):
dprobs_omitted_rowsum[ii, :] = _np.sum(dprobs[lookup[i], :], axis=0)
jac = dprobs * dprobs_factor[:, None] # (KM,N) * (KM,1) (N = dim of vectorized model)
# need to multipy dprobs_factor_omitted[i] * dprobs[k] for k in lookup[i] and
# add to dprobs[firsts[i]] for i in indicesOfCircuitsWithOmittedData
if firsts is not None:
jac[firsts, :] += dprobs_factor_omitted[:, None] * dprobs_omitted_rowsum
# nCircuitsWithOmittedData x N
else:
# (the non-poisson picture requires that the probabilities of the spam labels for a given string are constrained
# to sum to 1)
S = countVecMx / min_p # slope term that is derivative of logl at min_p
S2 = -0.5 * countVecMx / (min_p**2) # 2nd derivative of logl term at min_p
v = countVecMx * _np.log(pos_probs) # dims K x M (K = nSpamLabels, M = nCircuits)
# remove small positive elements due to roundoff error (above expression *cannot* really be positive)
v = _np.minimum(v, 0)
# quadratic extrapolation of logl at min_p for probabilities < min_p
v = _np.where(probs < min_p, v + S * (probs - min_p) + S2 * (probs - min_p)**2, v)
v = _np.where(countVecMx == 0, 0.0, v)
dprobs_factor_pos = countVecMx / pos_probs
dprobs_factor_neg = S + 2 * S2 * (probs - min_p)
dprobs_factor = _np.where(probs < min_p, dprobs_factor_neg, dprobs_factor_pos)
dprobs_factor = _np.where(countVecMx == 0, 0.0, dprobs_factor)
jac = dprobs * dprobs_factor[:, None] # (KM,N) * (KM,1) (N = dim of vectorized model)
#Note: no correction from omitted probabilities needed in poissonPicture == False case.
# jac[iSpamLabel,iCircuit,iModelParam] contains all d(logl)/d(modelParam) contributions
return _np.sum(jac, axis=0) # sum over spam label and operation sequence dimensions
def logl_hessian(model, dataset, circuit_list=None, minProbClip=1e-6,
probClipInterval=(-1e6, 1e6), radius=1e-4, poissonPicture=True,
check=False, comm=None, memLimit=None,
opLabelAliases=None, smartc=None, verbosity=0):
"""
The hessian of the log-likelihood function.
Parameters
----------
model : Model
Model of parameterized gates (including SPAM)
dataset : DataSet
Probability data
circuit_list : list of (tuples or Circuits), optional
Each element specifies a operation sequence to include in the log-likelihood
sum. Default value of None implies all the operation sequences in dataset
should be used.
minProbClip : float, optional
The minimum probability treated normally in the evaluation of the log-likelihood.
A penalty function replaces the true log-likelihood for probabilities that lie
below this threshold so that the log-likelihood never becomes undefined (which improves
optimizer performance).
probClipInterval : 2-tuple or None, optional
(min,max) values used to clip the probabilities predicted by
models during MLEGST's search for an optimal model (if not None).
if None, no clipping is performed.
radius : float, optional
Specifies the severity of rounding used to "patch" the zero-frequency
terms of the log-likelihood.
poissonPicture : boolean, optional
Whether the Poisson-picutre log-likelihood should be differentiated.
check : boolean, optional
If True, perform extra checks within code to verify correctness. Used
for testing, and runs much slower when True.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
memLimit : int, optional
A rough memory limit in bytes which restricts the amount of intermediate
values that are computed and stored.
opLabelAliases : dictionary, optional
Dictionary whose keys are operation label "aliases" and whose values are tuples
corresponding to what that operation label should be expanded into before querying
the dataset. Defaults to the empty dictionary (no aliases defined)
e.g. opLabelAliases['Gx^3'] = ('Gx','Gx','Gx')
smartc : SmartCache, optional
A cache object to cache & use previously cached values inside this
function.
verbosity : int, optional
How much detail to print to stdout.
Returns
-------
numpy array
array of shape (M,M), where M is the length of the vectorized model.
"""
def smart(fn, *args, **kwargs):
if smartc:
return smartc.cached_compute(fn, args, kwargs)[1]
else:
if '_filledarrays' in kwargs: del kwargs['_filledarrays']
return fn(*args, **kwargs)
nP = model.num_params()
if circuit_list is None:
circuit_list = list(dataset.keys())
# Estimate & check persistent memory (from allocs directly below)
C = 1.0 / 1024.0**3; nP = model.num_params()
persistentMem = 8 * nP**2 # in bytes
if memLimit is not None and memLimit < persistentMem:
raise MemoryError("HLogL Memory limit (%g GB) is " % (memLimit * C)
+ "< memory required to hold final results (%g GB)"
% (persistentMem * C))
# Allocate persistent memory
final_hessian = _np.zeros((nP, nP), 'd')
# Estimate & check intermediate memory
# - figure out how many row & column partitions are needed
# to fit computation within available memory (and use all cpus)
mlim = None if (memLimit is None) else memLimit - persistentMem
# Note: simplify_circuits doesn't support aliased dataset (yet)
dstree = dataset if (opLabelAliases is None) else None
evalTree, blkSize1, blkSize2, lookup, outcomes_lookup = \
smart(model.bulk_evaltree_from_resources,
circuit_list, comm, mlim, "deriv", ['bulk_hprobs_by_block'],
dstree, verbosity)
rowParts = int(round(nP / blkSize1)) if (blkSize1 is not None) else 1
colParts = int(round(nP / blkSize2)) if (blkSize2 is not None) else 1
a = radius # parameterizes "roundness" of f == 0 terms
min_p = minProbClip
#Detect omitted frequences (assumed to be 0) so we can compute liklihood correctly
firsts = []; indicesOfCircuitsWithOmittedData = []
for i, c in enumerate(circuit_list):
lklen = _slct.length(lookup[i])
if 0 < lklen < model.get_num_outcomes(c):
firsts.append(_slct.as_array(lookup[i])[0])
indicesOfCircuitsWithOmittedData.append(i)
if len(firsts) > 0:
firsts = _np.array(firsts, 'i')
indicesOfCircuitsWithOmittedData = _np.array(indicesOfCircuitsWithOmittedData, 'i')
else:
firsts = None
if poissonPicture:
#NOTE: hessian_from_hprobs MAY modify hprobs and dprobs12 (to save mem)
def hessian_from_hprobs(hprobs, dprobs12, cntVecMx, totalCntVec, pos_probs):
""" Factored-out computation of hessian from raw components """
# Notation: (K=#spam, M=#strings, N=#wrtParams1, N'=#wrtParams2 )
totCnts = totalCntVec # shorthand
S = cntVecMx / min_p - totCnts # slope term that is derivative of logl at min_p
S2 = -0.5 * cntVecMx / (min_p**2) # 2nd derivative of logl term at min_p
#Allocate these above? Need to know block sizes of dprobs12 & hprobs...
if firsts is not None:
dprobs12_omitted_rowsum = _np.empty((len(firsts),) + dprobs12.shape[1:], 'd')
hprobs_omitted_rowsum = _np.empty((len(firsts),) + hprobs.shape[1:], 'd')
# # (K,M,1,1) * (K,M,N,N')
# hprobs_pos = (-cntVecMx / pos_probs**2)[:,:,None,None] * dprobs12
# # (K,M,1,1) * (K,M,N,N')
# hprobs_pos += (cntVecMx / pos_probs - totalCntVec[None,:])[:,:,None,None] * hprobs
# # (K,M,1,1) * (K,M,N,N')
# hprobs_neg = (2*S2)[:,:,None,None] * dprobs12 + (S + 2*S2*(probs - min_p))[:,:,None,None] * hprobs
# hprobs_zerofreq = _np.where( (probs >= a)[:,:,None,None],
# -totalCntVec[None,:,None,None] * hprobs,
# (-totalCntVec[None,:] * ( (-2.0/a**2)*probs + 2.0/a))[:,:,None,None] \
# * dprobs12
# - (totalCntVec[None,:] * ((-1.0/a**2)*probs**2 + 2*probs/a))[:,:,None,None] \
# * hprobs )
# hessian = _np.where( (probs < min_p)[:,:,None,None], hprobs_neg, hprobs_pos)
# hessian = _np.where( (cntVecMx == 0)[:,:,None,None], hprobs_zerofreq, hessian) # (K,M,N,N')
omitted_probs = 1.0 - _np.array([_np.sum(pos_probs[lookup[i]]) for i in indicesOfCircuitsWithOmittedData])
for ii, i in enumerate(indicesOfCircuitsWithOmittedData):
dprobs12_omitted_rowsum[ii, :, :] = _np.sum(dprobs12[lookup[i], :, :], axis=0)
hprobs_omitted_rowsum[ii, :, :] = _np.sum(hprobs[lookup[i], :, :], axis=0)
#Accomplish the same thing as the above commented-out lines,
# but with more memory effiency:
dprobs12_coeffs = \
_np.where(probs < min_p, 2 * S2, -cntVecMx / pos_probs**2)
zfc = _np.where(probs >= a, 0.0, -totCnts * ((-2.0 / a**2) * probs + 2.0 / a))
dprobs12_coeffs = _np.where(cntVecMx == 0, zfc, dprobs12_coeffs)
hprobs_coeffs = \
_np.where(probs < min_p, S + 2 * S2 * (probs - min_p),
cntVecMx / pos_probs - totCnts)
zfc = _np.where(probs >= a, -totCnts,
-totCnts * ((-1.0 / a**2) * probs**2 + 2 * probs / a))
hprobs_coeffs = _np.where(cntVecMx == 0, zfc, hprobs_coeffs)
if firsts is not None:
dprobs12_omitted_coeffs = totCnts[firsts] * _np.where(
omitted_probs >= a, 0.0, (-2.0 / a**2) * omitted_probs + 2.0 / a)
hprobs_omitted_coeffs = totCnts[firsts] * _np.where(
omitted_probs >= a, 1.0,
(-1.0 / a**2) * omitted_probs**2 + 2 * omitted_probs / a)
# hessian = hprobs_coeffs * hprobs + dprobs12_coeff * dprobs12
# but re-using dprobs12 and hprobs memory (which is overwritten!)
hprobs *= hprobs_coeffs[:, None, None]
dprobs12 *= dprobs12_coeffs[:, None, None]
if firsts is not None:
hprobs[firsts, :, :] += hprobs_omitted_coeffs[:, None, None] * hprobs_omitted_rowsum
dprobs12[firsts, :, :] += dprobs12_omitted_coeffs[:, None, None] * dprobs12_omitted_rowsum
hessian = dprobs12; hessian += hprobs
# hessian[iSpamLabel,iCircuit,iModelParam1,iModelParams2] contains all
# d2(logl)/d(modelParam1)d(modelParam2) contributions
return _np.sum(hessian, axis=0)
# sum over spam label and operation sequence dimensions (operation sequences in evalSubTree)
# adds current subtree contribution for (N,N')-sized block of Hessian
else:
#(the non-poisson picture requires that the probabilities of the spam labels for a given string are constrained
#to sum to 1)
#NOTE: hessian_from_hprobs MAY modify hprobs and dprobs12 (to save mem)
def hessian_from_hprobs(hprobs, dprobs12, cntVecMx, totalCntVec, pos_probs):
""" Factored-out computation of hessian from raw components """
S = cntVecMx / min_p # slope term that is derivative of logl at min_p
S2 = -0.5 * cntVecMx / (min_p**2) # 2nd derivative of logl term at min_p
# # (K,M,1,1) * (K,M,N,N')
# hprobs_pos = (-cntVecMx / pos_probs**2)[:,:,None,None] * dprobs12
# # (K,M,1,1) * (K,M,N,N')
# hprobs_pos += (cntVecMx / pos_probs)[:,:,None,None] * hprobs
# # (K,M,1,1) * (K,M,N,N')
# hprobs_neg = (2*S2)[:,:,None,None] * dprobs12 + (S + 2*S2*(probs - min_p))[:,:,None,None] * hprobs
# hessian = _np.where( (probs < min_p)[:,:,None,None], hprobs_neg, hprobs_pos)
# # (K,M,N,N')
# hessian = _np.where( (cntVecMx == 0)[:,:,None,None], 0.0, hessian)
#Accomplish the same thing as the above commented-out lines,
# but with more memory effiency:
dprobs12_coeffs = \
_np.where(probs < min_p, 2 * S2, -cntVecMx / pos_probs**2)
dprobs12_coeffs = _np.where(cntVecMx == 0, 0.0, dprobs12_coeffs)
hprobs_coeffs = \
_np.where(probs < min_p, S + 2 * S2 * (probs - min_p),
cntVecMx / pos_probs)
hprobs_coeffs = _np.where(cntVecMx == 0, 0.0, hprobs_coeffs)
# hessian = hprobs_coeffs * hprobs + dprobs12_coeff * dprobs12
# but re-using dprobs12 and hprobs memory (which is overwritten!)
hprobs *= hprobs_coeffs[:, None, None]
dprobs12 *= dprobs12_coeffs[:, None, None]
hessian = dprobs12; hessian += hprobs
#Note: no need to correct for omitted probs (zero contribution)
return _np.sum(hessian, axis=0) # see comments as above
#Note - we could in the future use comm to distribute over
# subtrees here. We currently don't because we parallelize
# over columns and it seems that in almost all cases of
# interest there will be more hessian columns than processors,
# so adding the additional ability to parallelize over
# subtrees would just add unnecessary complication.
#get distribution across subtrees (groups if needed)
subtrees = evalTree.get_sub_trees()
mySubTreeIndices, subTreeOwners, mySubComm = evalTree.distribute(comm)
# Allocate memory (alloc max required & take views)
max_nEls = max([subtrees[i].num_final_elements() for i in mySubTreeIndices])
probs_mem = _np.empty(max_nEls, 'd')
# Fill cntVecMx, totalCntVec for all elements (all subtrees)
nEls = evalTree.num_final_elements()
cntVecMx_all = _np.empty(nEls, 'd')
totalCntVec_all = _np.empty(nEls, 'd')
ds_subtree_circuit_list = _lt.find_replace_tuple_list(
circuit_list, opLabelAliases)
for (i, opStr) in enumerate(ds_subtree_circuit_list):
cnts = dataset[opStr].counts
totalCntVec_all[lookup[i]] = sum(cnts.values()) # dataset[opStr].total
cntVecMx_all[lookup[i]] = [cnts.get(x, 0) for x in outcomes_lookup[i]]
tStart = _time.time()
#Loop over subtrees
for iSubTree in mySubTreeIndices:
evalSubTree = subtrees[iSubTree]
sub_nEls = evalSubTree.num_final_elements()
if evalSubTree.myFinalElsToParentFinalElsMap is not None:
#Then `evalSubTree` is a nontrivial sub-tree and its .spamtuple_indices
# will index the *parent's* final index array space, which we
# usually want but NOT here, where we fill arrays just big
# enough for each subtree separately - so re-init spamtuple_indices
evalSubTree = evalSubTree.copy()
evalSubTree.recompute_spamtuple_indices(bLocal=True)
# Create views into pre-allocated memory
probs = probs_mem[0:sub_nEls]
# Take portions of count arrays for this subtree
cntVecMx = cntVecMx_all[evalSubTree.final_element_indices(evalTree)]
totalCntVec = totalCntVec_all[evalSubTree.final_element_indices(evalTree)]
assert(len(cntVecMx) == len(probs))
#compute pos_probs separately
smart(model.bulk_fill_probs, probs, evalSubTree,
clipTo=probClipInterval, check=check,
comm=mySubComm, _filledarrays=(0,))
pos_probs = _np.where(probs < min_p, min_p, probs)
nCols = model.num_params()
blocks1 = _mpit.slice_up_range(nCols, rowParts)
blocks2 = _mpit.slice_up_range(nCols, colParts)
sliceTupList_all = list(_itertools.product(blocks1, blocks2))
#cull out lower triangle blocks, which have no overlap with
# the upper triangle of the hessian
sliceTupList = [(slc1, slc2) for slc1, slc2 in sliceTupList_all
if slc1.start <= slc2.stop]
loc_iBlks, blkOwners, blkComm = \
_mpit.distribute_indices(list(range(len(sliceTupList))), mySubComm)
mySliceTupList = [sliceTupList[i] for i in loc_iBlks]
subtree_hessian = _np.zeros((nP, nP), 'd')
k, kmax = 0, len(mySliceTupList)
for (slice1, slice2, hprobs, dprobs12) in model.bulk_hprobs_by_block(
evalSubTree, mySliceTupList, True, blkComm):
rank = comm.Get_rank() if (comm is not None) else 0
if verbosity > 3 or (verbosity == 3 and rank == 0):
iSub = mySubTreeIndices.index(iSubTree)
print("rank %d: %gs: block %d/%d, sub-tree %d/%d, sub-tree-len = %d"
% (rank, _time.time() - tStart, k, kmax, iSub,
len(mySubTreeIndices), len(evalSubTree)))
_sys.stdout.flush(); k += 1
subtree_hessian[slice1, slice2] = \
hessian_from_hprobs(hprobs, dprobs12, cntVecMx,
totalCntVec, pos_probs)
#NOTE: hessian_from_hprobs MAY modify hprobs and dprobs12
#Gather columns from different procs and add to running final hessian
#_mpit.gather_slices_by_owner(slicesIOwn, subtree_hessian,[], (0,1), mySubComm)
_mpit.gather_slices(sliceTupList, blkOwners, subtree_hessian, [], (0, 1), mySubComm)
final_hessian += subtree_hessian
#gather (add together) final_hessians from different processors
if comm is not None and len(set(subTreeOwners.values())) > 1:
if comm.Get_rank() not in subTreeOwners.values():
# this proc is not the "owner" of its subtrees and should not send a contribution to the sum
final_hessian[:, :] = 0.0 # zero out hessian so it won't contribute
final_hessian = comm.allreduce(final_hessian)
#copy upper triangle to lower triangle (we only compute upper)
for i in range(final_hessian.shape[0]):
for j in range(i + 1, final_hessian.shape[1]):
final_hessian[j, i] = final_hessian[i, j]
return final_hessian # (N,N)
def logl_approximate_hessian(model, dataset, circuit_list=None,
minProbClip=1e-6, probClipInterval=(-1e6, 1e6), radius=1e-4,
poissonPicture=True, check=False, comm=None,
memLimit=None, opLabelAliases=None, smartc=None,
verbosity=0):
"""
An approximate Hessian of the log-likelihood function.
An approximation to the true Hessian is computed using just the Jacobian
(and *not* the Hessian) of the probabilities w.r.t. the model
parameters. Let `J = d(probs)/d(params)` and denote the Hessian of the
log-likelihood w.r.t. the probabilities as `d2(logl)/dprobs2` (a *diagonal*
matrix indexed by the term, i.e. probability, of the log-likelihood). Then
this function computes:
`H = J * d2(logl)/dprobs2 * J.T`
Which simply neglects the `d2(probs)/d(params)2` terms of the true Hessian.
Since this curvature is expected to be small at the MLE point, this
approximation can be useful for computing approximate error bars.
Parameters
----------
model : Model
Model of parameterized gates (including SPAM)
dataset : DataSet
Probability data
circuit_list : list of (tuples or Circuits), optional
Each element specifies a operation sequence to include in the log-likelihood
sum. Default value of None implies all the operation sequences in dataset
should be used.
minProbClip : float, optional
The minimum probability treated normally in the evaluation of the log-likelihood.
A penalty function replaces the true log-likelihood for probabilities that lie
below this threshold so that the log-likelihood never becomes undefined (which improves
optimizer performance).
probClipInterval : 2-tuple or None, optional
(min,max) values used to clip the probabilities predicted by models during MLEGST's
search for an optimal model (if not None). if None, no clipping is performed.
radius : float, optional
Specifies the severity of rounding used to "patch" the zero-frequency
terms of the log-likelihood.
evalTree : evaluation tree, optional
given by a prior call to bulk_evaltree for the same circuit_list.
Significantly speeds up evaluation of log-likelihood derivatives, even
more so when accompanied by countVecMx (see below). Defaults to None.
poissonPicture : boolean, optional
Whether the Poisson-picutre log-likelihood should be differentiated.
check : boolean, optional
If True, perform extra checks within code to verify correctness. Used
for testing, and runs much slower when True.
comm : mpi4py.MPI.Comm, optional
When not None, an MPI communicator for distributing the computation
across multiple processors.
memLimit : int, optional
A rough memory limit in bytes which restricts the amount of intermediate
values that are computed and stored.
opLabelAliases : dictionary, optional
Dictionary whose keys are operation label "aliases" and whose values are tuples
corresponding to what that operation label should be expanded into before querying
the dataset. Defaults to the empty dictionary (no aliases defined)
e.g. opLabelAliases['Gx^3'] = ('Gx','Gx','Gx')
smartc : SmartCache, optional
A cache object to cache & use previously cached values inside this
function.
verbosity : int, optional
How much detail to print to stdout.
Returns
-------
numpy array
array of shape (M,M), where M is the length of the vectorized model.
"""
def smart(fn, *args, **kwargs):
if smartc:
return smartc.cached_compute(fn, args, kwargs)[1]
else:
if '_filledarrays' in kwargs: del kwargs['_filledarrays']
return fn(*args, **kwargs)
if circuit_list is None:
circuit_list = list(dataset.keys())
C = 1.0 / 1024.0**3; nP = model.num_params()
persistentMem = 8 * nP**2 + 8 * len(circuit_list) * (nP + 1) # in bytes
if memLimit is not None and memLimit < persistentMem:
raise MemoryError("DLogL Memory limit (%g GB) is " % (memLimit * C)
+ "< memory required to hold final results (%g GB)"
% (persistentMem * C))
#OLD: evalTree,lookup,outcomes_lookup = model.bulk_evaltree(circuit_list)
mlim = None if (memLimit is None) else memLimit - persistentMem
# Note: simplify_circuits doesn't support aliased dataset (yet)
dstree = dataset if (opLabelAliases is None) else None