/
workspaceplots.py
3637 lines (3104 loc) · 148 KB
/
workspaceplots.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
""" Classes corresponding to plots within a Workspace context."""
#***************************************************************************************************
# 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 as _scipy
import warnings as _warnings
import collections as _collections
from scipy.stats import chi2 as _chi2
from .. import algorithms as _alg
from .. import tools as _tools
from .. import objects as _objs
from ..objects import objectivefns as _objfns
from .workspace import WorkspacePlot
from .figure import ReportFigure
from . import colormaps as _colormaps
from . import plothelpers as _ph
import plotly
import plotly.graph_objs as go
from ..objects.bulkcircuitlist import BulkCircuitList as _BulkCircuitList
#Plotly v3 changes heirarchy of graph objects
# Do this to avoid deprecation warning is plotly 3+
if int(plotly.__version__.split('.')[0]) >= 3: # Plotly 3+
go_x_axis = go.layout.XAxis
go_y_axis = go.layout.YAxis
go_margin = go.layout.Margin
go_annotation = go.layout.Annotation
else:
go_x_axis = go.XAxis
go_y_axis = go.YAxis
go_margin = go.Margin
go_annotation = go.Annotation
#DEBUG
#import time as _time #DEBUG TIMER
#from plotly.offline import download_plotlyjs, init_notebook_mode, plot, iplot
def color_boxplot(plt_data, colormap, colorbar=False, box_label_size=0,
prec=0, hover_label_fn=None, hover_labels=None):
"""
Create a color box plot.
Creates a plot.ly heatmap figure composed of colored boxes and
possibly labels.
Parameters
----------
plt_data : numpy array
A 2D array containing the values to be plotted. None values will
show up as white.
colormap : Colormap
The colormap used to determine box color.
colorbar : bool, optional
Whether or not to show the color scale bar.
box_label_size : int, optional
If greater than 0, display static labels on each box with font
size equal to `box_label_size`.
prec : int or {'compact','compacthp'}, optional
Precision for box labels. Allowed values are:
'compact' = round to nearest whole number using at most 3 characters
'compacthp' = show as much precision as possible using at most 3 characters
int >= 0 = fixed precision given by int
int < 0 = number of significant figures given by -int
hover_label_fn : function, optional
A function with signature `f(z,i,j)` where `z ==plt_data[i,j]` which
computes the hover label for the each element of `plt_data`. Cannot
be used with `hover_labels`.
hover_labels : list of lists, optional
Strings specifying the hover labels for each element of `plt_data`.
E.g. `hover_labels[i,j]` is the string for the i-th row (y-value)
and j-th column (x-value) of the plot.
Returns
-------
plotly.Figure
"""
masked_data = _np.ma.array(plt_data, mask=_np.isnan(plt_data))
heatmapArgs = {'z': colormap.normalize(masked_data),
'colorscale': colormap.get_colorscale(),
'showscale': colorbar, 'hoverinfo': 'none',
'zmin': colormap.hmin, 'zmax': colormap.hmax}
#if xlabels is not None: heatmapArgs['x'] = xlabels
#if ylabels is not None: heatmapArgs['y'] = ylabels
annotations = []
if box_label_size:
# Write values on colored squares
for y in range(plt_data.shape[0]):
for x in range(plt_data.shape[1]):
if _np.isnan(plt_data[y, x]): continue
annotations.append(
dict(
text=_ph._eformat(plt_data[y, x], prec),
x=x, y=y,
xref='x1', yref='y1',
font=dict(size=box_label_size,
color=colormap.besttxtcolor(plt_data[y, x])),
showarrow=False)
)
if hover_label_fn:
assert(not hover_labels), "Cannot specify hover_label_fn and hover_labels!"
hover_labels = []
for y in range(plt_data.shape[0]):
hover_labels.append([hover_label_fn(plt_data[y, x], y, x)
for x in range(plt_data.shape[1])])
if hover_labels:
heatmapArgs['hoverinfo'] = 'text'
heatmapArgs['text'] = hover_labels
trace = go.Heatmap(**heatmapArgs)
#trace = dict(type='heatmapgl', **heatmapArgs)
data = [trace]
xaxis = go_x_axis(
showgrid=False,
zeroline=False,
showline=True,
ticks="",
showticklabels=True,
mirror=True,
linewidth=2,
range=[-0.5, plt_data.shape[1] - 0.5]
)
yaxis = go_y_axis(
showgrid=False,
zeroline=False,
showline=True,
ticks="",
showticklabels=True,
mirror=True,
linewidth=2,
range=[-0.5, plt_data.shape[0] - 0.5]
)
layout = go.Layout(
xaxis=xaxis,
yaxis=yaxis,
annotations=annotations
)
fig = go.Figure(data=data, layout=layout)
return ReportFigure(fig, colormap, plt_data, plt_data=plt_data)
def nested_color_boxplot(plt_data_list_of_lists, colormap,
colorbar=False, box_label_size=0, prec=0,
hover_label_fn=None):
"""
Creates a "nested" color box plot by tiling the plaquettes given
by `plt_data_list_of_lists` onto a single heatmap.
Parameters
----------
plt_data_list_of_lists : list of lists of numpy arrays
A complete square 2D list of lists, such that each element is a
2D numpy array of the same size.
colormap : Colormap
The colormap used to determine box color.
colorbar : bool, optional
Whether or not to show the color scale bar.
box_label_size : int, optional
If greater than 0, display static labels on each box with font
size equal to `box_label_size`.
prec : int or {'compact','compacthp'}, optional
Precision for box labels. Allowed values are:
'compact' = round to nearest whole number using at most 3 characters
'compacthp' = show as much precision as possible using at most 3 characters
int >= 0 = fixed precision given by int
int < 0 = number of significant figures given by -int
hover_label_fn : function, optional
A function with signature `f(z,i,j)` where `z ==plt_data[i,j]` which
computes the hover label for the each element of `plt_data`. Cannot
be used with `hoverLabels`.
Returns
-------
plotly.Figure
"""
#Assemble the single 2D grid to pass to color_boxplot
# (assume a complete 2D rectangular list of lists, and that
# each element is a numpy array of the same size)
if len(plt_data_list_of_lists) == 0 or len(plt_data_list_of_lists[0]) == 0: return
elRows, elCols = plt_data_list_of_lists[0][0].shape # nE,nr
nRows = len(plt_data_list_of_lists)
nCols = len(plt_data_list_of_lists[0])
data = _np.zeros((elRows * nRows + (nRows - 1), elCols * nCols + (nCols - 1)))
for i in range(1, nRows):
data[(elRows + 1) * i - 1:(elRows + 1) * i, :] = _np.nan
for j in range(1, nCols):
data[:, (elCols + 1) * j - 1:(elCols + 1) * j] = _np.nan
for i in range(nRows):
for j in range(nCols):
data[(elRows + 1) * i:(elRows + 1) * (i + 1) - 1, (elCols + 1)
* j:(elCols + 1) * (j + 1) - 1] = plt_data_list_of_lists[i][j]
xtics = []; ytics = []
for i in range(nRows): ytics.append(float((elRows + 1) * i) - 0.5 + 0.5 * float(elRows))
for j in range(nCols): xtics.append(float((elCols + 1) * j) - 0.5 + 0.5 * float(elCols))
if hover_label_fn:
hoverLabels = []
for _ in range(elRows * nRows + (nRows - 1)):
hoverLabels.append([""] * (elCols * nCols + (nCols - 1)))
for i in range(nRows):
for j in range(nCols):
for ii in range(elRows):
for jj in range(elCols):
hoverLabels[(elRows + 1) * i + ii][(elCols + 1) * j + jj] = \
hover_label_fn(plt_data_list_of_lists[i][j][ii][jj], i, j, ii, jj)
else:
hoverLabels = None
fig = color_boxplot(data, colormap, colorbar, box_label_size,
prec, None, hoverLabels)
#Layout updates: add tic marks (but not labels - leave that to user)
fig.plotlyfig['layout']['xaxis'].update(tickvals=xtics)
fig.plotlyfig['layout']['yaxis'].update(tickvals=ytics)
return fig
def generate_boxplot(sub_mxs,
xlabels, ylabels, inner_xlabels, inner_ylabels,
xlabel, ylabel, inner_xlabel, inner_ylabel,
colormap, colorbar=False, box_labels=True, prec=0, hover_info=True,
sum_up=False, invert=False, scale=1.0, bgcolor='white'):
"""
A helper function for generating typical nested color box plots used in pyGSTi.
Given the list-of-lists, `sub_mxs`, along with x and y labels for both the "outer"
(i.e. the list-indices) and "inner" (i.e. the sub-matrix-indices) axes, this function
will produce a nested color box plot with the option of summing over the inner axes
or inverting (swapping) the inner and outer axes.
Parameters
----------
sub_mxs : list
A list of lists of 2D numpy.ndarrays. sub_mxs[iy][ix] specifies the matrix of values
or sum (if sum_up == True) displayed in iy-th row and ix-th column of the plot. NaNs
indicate elements should not be displayed.
x_labels, y_labels : list
Labels for the outer x- and y-axis values.
inner_x_labels, inner_y_labels : list
Labels for the inner x- and y-axis values.
xlabel, ylabel : str
Outer X and Y axis labels.
inner_xlabel, inner_ylabel : str
Inner X and Y axis labels.
colormap : Colormap
The colormap used to determine box color.
colorbar : bool, optional
Whether or not to show the color scale bar.
box_labels : bool, optional
Whether to display static value-labels over each box.
prec : int or {'compact','compacthp'}, optional
Precision for box labels. Allowed values are:
'compact' = round to nearest whole number using at most 3 characters
'compacthp' = show as much precision as possible using at most 3 characters
int >= 0 = fixed precision given by int
int < 0 = number of significant figures given by -int
hover_info : bool or function, optional
If a boolean, indicates whether to include interactive hover labels. If
a function, then must take arguments `(val, iy, ix, iiy, iix)` if
`sum_up == False` or `(val, iy, ix)` if `sum_up == True` and return a
label string, where `val` is the box value, `ix` and `iy` index
`xlabels` and `ylabels`, and `iix` and `iiy` index `inner_xlabels`
and `inner_ylabels`.
sum_up : bool, optional
False displays each matrix element as it's own color box
True sums the elements of each (x,y) matrix and displays
a single color box for the sum.
invert : bool, optional
If True, invert the nesting order of the nested color box plot
(applicable only when sum_up == False). E.g. use inner_x_labels and
inner_y_labels to label the x and y axes.
scale : float, optional
Scaling factor to adjust the size of the final figure.
bgcolor : str, optional
Background color for this plot. Can be common color names, e.g.
`"black"`, or string RGB values, e.g. `"rgb(255,128,0)"`.
Returns
-------
plotly.Figure
"""
nYs = len(sub_mxs)
nXs = len(sub_mxs[0]) if nYs > 0 else 0
nIYs = nIXs = 0
for ix in range(nXs):
for iy in range(nYs):
if sub_mxs[iy][ix] is not None:
nIYs, nIXs = sub_mxs[iy][ix].shape; break
# flip so [0,0] el of original sub_mxs is at *top*-left (FLIP)
sub_mxs = [[_np.flipud(subMx) for subMx in row] for row in sub_mxs]
inner_ylabels = list(reversed(inner_ylabels))
if invert:
if sum_up:
_warnings.warn("Cannot invert a summed-up plot. Ignoring invert=True.")
else:
invertedSubMxs = [] # will be indexed as invertedSubMxs[inner-y][inner-x]
for iny in range(nIYs):
invertedSubMxs.append([])
for inx in range(nIXs):
mx = _np.array([[sub_mxs[iy][ix][iny, inx] for ix in range(nXs)]
for iy in range(nYs)], 'd')
invertedSubMxs[-1].append(mx)
# flip the now-inverted mxs to counteract the flip that will occur upon
# entering generate_boxplot again (with invert=False this time), since we
# *don't* want the now-inner dimension (the germs) actually flipped (FLIP)
invertedSubMxs = [[_np.flipud(subMx) for subMx in row] for row in invertedSubMxs]
ylabels = list(reversed(ylabels))
return generate_boxplot(invertedSubMxs,
inner_xlabels, inner_ylabels,
xlabels, ylabels, inner_xlabel, inner_ylabel, xlabel, ylabel,
colormap, colorbar, box_labels, prec, hover_info,
sum_up, False, scale, bgcolor)
def val_filter(vals):
"""filter to latex-ify operation sequences. Later add filter as a possible parameter"""
formatted_vals = []
for val in vals:
if isinstance(val, _objs.Circuit):
if len(val) == 0:
#formatted_vals.append(r"$\{\}$")
formatted_vals.append(r"{}")
else:
#formatted_vals.append( "$" + "\\cdot".join([("\\mathrm{%s}" % el) for el in val]) + "$" )
formatted_vals.append(val.str)
else:
formatted_vals.append(str(val))
return formatted_vals
def sum_up_mx(mx):
""" Sum up `mx` in a NAN-ignoring way """
flat_mx = mx.flatten()
if any([_np.isnan(x) for x in flat_mx]):
if all([_np.isnan(x) for x in flat_mx]):
return _np.nan
# replace NaNs with zeros for purpose of summing (when there's at least one non-NaN)
return sum(_np.nan_to_num(flat_mx))
else:
return sum(flat_mx)
#Setup and create plotting functions
if sum_up:
subMxSums = _np.array([[sum_up_mx(sub_mxs[iy][ix]) for ix in range(nXs)] for iy in range(nYs)], 'd')
if hover_info is True:
def hover_label_fn(val, i, j):
""" Standard hover labels """
if _np.isnan(val): return ""
return "%s: %s<br>%s: %s<br>%g" % \
(xlabel, str(xlabels[j]), ylabel, str(ylabels[i]), val)
elif callable(hover_info):
hover_label_fn = hover_info
else: hover_label_fn = None
boxLabelSize = 8 * scale if box_labels else 0
fig = color_boxplot(subMxSums, colormap, colorbar, boxLabelSize,
prec, hover_label_fn)
#update tickvals b/c color_boxplot doesn't do this (unlike nested_color_boxplot)
if fig is not None:
fig.plotlyfig['layout']['xaxis'].update(tickvals=list(range(nXs)))
fig.plotlyfig['layout']['yaxis'].update(tickvals=list(range(nYs)))
xBoxes = nXs
yBoxes = nYs
else: # not summing up
if hover_info is True:
def hover_label_fn(val, i, j, ii, jj):
""" Standard hover labels """
if _np.isnan(val): return ""
return "%s: %s<br>%s: %s<br>%s: %s<br>%s: %s<br>%g" % \
(xlabel, str(xlabels[j]), ylabel, str(ylabels[i]),
inner_xlabel, str(inner_xlabels[jj]),
inner_ylabel, str(inner_ylabels[ii]), val)
elif callable(hover_info):
hover_label_fn = hover_info
else: hover_label_fn = None
boxLabelSize = 8 if box_labels else 0 # do not scale (OLD: 8*scale)
fig = nested_color_boxplot(sub_mxs, colormap, colorbar, boxLabelSize,
prec, hover_label_fn)
xBoxes = nXs * (nIXs + 1) - 1
yBoxes = nYs * (nIYs + 1) - 1
#assert(fig is not None), "No data to display!"
if fig is not None: # i.e., if there was data to plot
pfig = fig.plotlyfig
if xlabel: pfig['layout']['xaxis'].update(title=xlabel,
titlefont={'size': 12 * scale, 'color': "black"})
if ylabel: pfig['layout']['yaxis'].update(title=ylabel,
titlefont={'size': 12 * scale, 'color': "black"})
if xlabels:
pfig['layout']['xaxis'].update(tickmode="array",
ticktext=val_filter(xlabels),
tickfont={'size': 10 * scale, 'color': "black"})
if ylabels:
pfig['layout']['yaxis'].update(tickmode="array",
ticktext=val_filter(ylabels),
tickfont={'size': 10 * scale, 'color': "black"})
#Set plot size and margins
lmargin = rmargin = tmargin = bmargin = 20
if xlabel: bmargin += 30
if ylabel: lmargin += 30
if xlabels:
max_xl = max([len(xl) for xl in pfig['layout']['xaxis']['ticktext']])
if max_xl > 0: bmargin += max_xl * 5
if ylabels:
max_yl = max([len(yl) for yl in pfig['layout']['yaxis']['ticktext']])
if max_yl > 0: lmargin += max_yl * 5
if colorbar: rmargin = 100
#make sure there's enough margin for hover tooltips
if 10 * xBoxes < 200: rmargin = max(200 - 10 * xBoxes, rmargin)
if 10 * yBoxes < 200: bmargin = max(200 - 10 * xBoxes, bmargin)
width = lmargin + 10 * xBoxes + rmargin
height = tmargin + 10 * yBoxes + bmargin
width *= scale
height *= scale
lmargin *= scale
rmargin *= scale
tmargin *= scale
bmargin *= scale
pfig['layout'].update(width=width,
height=height,
margin=go_margin(l=lmargin, r=rmargin, b=bmargin, t=tmargin),
plot_bgcolor=bgcolor)
else: # fig is None => use a "No data to display" placeholder figure
trace = go.Heatmap(z=_np.zeros((10, 10), 'd'),
colorscale=[[0, 'white'], [1, 'black']],
showscale=False, zmin=0, zmax=1, hoverinfo='none')
layout = go.Layout(
width=100, height=100,
annotations=[go_annotation(x=5, y=5, text="NO DATA", showarrow=False,
font={'size': 20, 'color': "black"},
xref='x', yref='y')],
xaxis=dict(showline=False, zeroline=False,
showticklabels=False, showgrid=False,
ticks=""),
yaxis=dict(showline=False, zeroline=False,
showticklabels=False, showgrid=False,
ticks="")
)
fig = ReportFigure(go.Figure(data=[trace], layout=layout),
None, "No data!")
return fig
def circuit_color_boxplot(circuit_structure, sub_mxs, colormap,
colorbar=False, box_labels=True, prec='compact', hover_info=True,
sum_up=False, invert=False, scale=1.0, bgcolor="white", addl_hover_submxs=None):
"""
A wrapper around :func:`generate_boxplot` for creating color box plots
when the structure of the operation sequences is contained in a
`CircuitStructure` object.
Parameters
----------
circuit_structure : CircuitStructure
Specifies a set of operation sequences along with their outer and inner x,y
structure, e.g. fiducials, germs, and maximum lengths.
sub_mxs : list
A list of lists of 2D numpy.ndarrays. sub_mxs[iy][ix] specifies the matrix of values
or sum (if sum_up == True) displayed in iy-th row and ix-th column of the plot. NaNs
indicate elements should not be displayed.
colormap : Colormap
The colormap used to determine box color.
colorbar : bool, optional
Whether or not to show the color scale bar.
box_labels : bool, optional
Whether to display static value-labels over each box.
prec : int or {'compact','compacthp'}, optional
Precision for box labels. Allowed values are:
'compact' = round to nearest whole number using at most 3 characters
'compacthp' = show as much precision as possible using at most 3 characters
int >= 0 = fixed precision given by int
int < 0 = number of significant figures given by -int
hover_info : bool, optional
Whether to incude interactive hover labels.
sum_up : bool, optional
False displays each matrix element as it's own color box
True sums the elements of each (x,y) matrix and displays
a single color box for the sum.
invert : bool, optional
If True, invert the nesting order of the nested color box plot
(applicable only when sum_up == False). E.g. use inner_x_labels and
inner_y_labels to label the x and y axes.
scale : float, optional
Scaling factor to adjust the size of the final figure.
bgcolor : str, optional
Background color for this plot. Can be common color names, e.g.
`"black"`, or string RGB values, e.g. `"rgb(255,128,0)"`.
addl_hover_submxs : dict, optional
If not None, a dictionary whose values are lists-of-lists in the same
format as `sub_mxs` which specify additional values to add to the
hover-info of the corresponding boxes. The keys of this dictionary
are used as labels within the hover-info text.
Returns
-------
plotly.Figure
"""
g = circuit_structure
xvals = g.used_xvals()
yvals = g.used_yvals()
inner_xvals = g.minor_xvals()
inner_yvals = g.minor_yvals()
if addl_hover_submxs is None:
addl_hover_submxs = {}
# Note: invert == True case not handled yet, and the below hover label
# routines assume L,germ structure in particular
if hover_info and not invert and isinstance(g, _objs.LsGermsStructure):
if sum_up:
def hover_label_fn(val, iy, ix):
""" Standard hover labels """
if _np.isnan(val): return ""
L, germ = xvals[ix], yvals[iy]
baseStr = g.get_plaquette(L, germ, False).base
reps = (len(baseStr) // len(germ)) if len(germ) > 0 else 1
guess = germ * reps
if baseStr == guess:
if len(baseStr) == 0:
txt = "{}"
else:
txt = "(%s)<sup>%d</sup>" % (germ.str, reps)
else:
txt = "L: %s<br>germ: %s" % (str(L), germ.str)
txt += "<br>value: %g" % val
for lbl, addl_subMxs in addl_hover_submxs.items():
txt += "<br>%s: %s" % (lbl, str(addl_subMxs[iy][ix]))
return txt
else:
def hover_label_fn(val, iy, ix, iiy, iix):
""" Standard hover labels """
#Note: in this case, we need to "flip" the iiy index because
# the matrices being plotted are flipped within generate_boxplot(...)
if _np.isnan(val): return ""
N = len(inner_yvals)
L, germ = xvals[ix], yvals[iy]
rhofid, efid = inner_xvals[iix], inner_yvals[N - 1 - iiy] # FLIP
baseStr = g.get_plaquette(L, germ, False).base
reps = (len(baseStr) // len(germ)) if len(germ) > 0 else 1
guess = germ * reps
if baseStr == guess:
if len(baseStr) == 0:
txt = "%s+{}+%s" % (rhofid.str, efid.str)
else:
txt = "%s+(%s)<sup>%d</sup>+%s" % (
rhofid.str, germ.str, reps, efid.str)
else:
txt = "L: %s<br>germ: %s<br>rho<sub>i</sub>: %s<br>E<sub>i</sub>: %s" \
% (str(L), germ.str, rhofid.str, efid.str)
txt += ("<br>value: %g" % val)
for lbl, addl_subMxs in addl_hover_submxs.items():
N = len(addl_subMxs[iy][ix]) # flip so original [0,0] el is at top-left (FLIP)
txt += "<br>%s: %s" % (lbl, str(addl_subMxs[iy][ix][N - 1 - iiy][iix]))
return txt
hover_info = hover_label_fn # generate_boxplot can handle this
return generate_boxplot(sub_mxs,
g.used_xvals(), g.used_yvals(),
g.minor_xvals(), g.minor_yvals(),
"L", "germ", "rho", "E<sub>i</sub>", colormap,
colorbar, box_labels, prec, hover_info,
sum_up, invert, scale, bgcolor) # "$\\rho_i$","$\\E_i$"
def circuit_color_scatterplot(circuit_structure, sub_mxs, colormap,
colorbar=False, hover_info=True, sum_up=False,
ylabel="", scale=1.0, addl_hover_submxs=None):
"""
Similar to :func:`circuit_color_boxplot` except a scatter plot is created.
Parameters
----------
circuit_structure : CircuitStructure
Specifies a set of operation sequences along with their outer and inner x,y
structure, e.g. fiducials, germs, and maximum lengths.
sub_mxs : list
A list of lists of 2D numpy.ndarrays. sub_mxs[iy][ix] specifies the matrix of values
or sum (if sum_up == True) displayed in iy-th row and ix-th column of the plot. NaNs
indicate elements should not be displayed.
colormap : Colormap
The colormap used to determine box color.
colorbar : bool, optional
Whether or not to show the color scale bar.
box_labels : bool, optional
Whether to display static value-labels over each box.
prec : int or {'compact','compacthp'}, optional
Precision for box labels. Allowed values are:
'compact' = round to nearest whole number using at most 3 characters
'compacthp' = show as much precision as possible using at most 3 characters
int >= 0 = fixed precision given by int
int < 0 = number of significant figures given by -int
hover_info : bool, optional
Whether to incude interactive hover labels.
sum_up : bool, optional
False displays each matrix element as it's own color box
True sums the elements of each (x,y) matrix and displays
a single color box for the sum.
ylabel : str, optional
The y-axis label to use.
scale : float, optional
Scaling factor to adjust the size of the final figure.
addl_hover_submxs : dict, optional
If not None, a dictionary whose values are lists-of-lists in the same
format as `sub_mxs` which specify additional values to add to the
hover-info of the corresponding boxes. The keys of this dictionary
are used as labels within the hover-info text.
Returns
-------
plotly.Figure
"""
g = circuit_structure
xvals = g.used_xvals()
yvals = g.used_yvals()
inner_xvals = g.minor_xvals()
inner_yvals = g.minor_yvals()
if addl_hover_submxs is None:
addl_hover_submxs = {}
#TODO: move hover-function creation routines to new function since duplicated in
# circuit_color_boxplot
if hover_info and isinstance(g, _objs.LsGermsStructure):
if sum_up:
def hover_label_fn(val, iy, ix):
""" Standard hover labels """
if _np.isnan(val): return ""
L, germ = xvals[ix], yvals[iy]
baseStr = g.get_plaquette(L, germ, False).base
reps = (len(baseStr) // len(germ)) if len(germ) > 0 else 1
guess = germ * reps
if baseStr == guess:
if len(baseStr) == 0:
txt = "{}"
else:
txt = "(%s)<sup>%d</sup>" % (germ.str, reps)
else:
txt = "L: %s<br>germ: %s" % (str(L), germ.str)
txt += "<br>value: %g" % val
for lbl, addl_subMxs in addl_hover_submxs.items():
txt += "<br>%s: %s" % (lbl, str(addl_subMxs[iy][ix]))
return txt
else:
def hover_label_fn(val, iy, ix, iiy, iix):
""" Standard hover labels """
if _np.isnan(val): return ""
L, germ = xvals[ix], yvals[iy]
rhofid, efid = inner_xvals[iix], inner_yvals[iiy]
baseStr = g.get_plaquette(L, germ, False).base
reps = (len(baseStr) // len(germ)) if len(germ) > 0 else 1
guess = germ * reps
if baseStr == guess:
if len(baseStr) == 0:
txt = "%s+{}+%s" % (rhofid.str, efid.str)
else:
txt = "%s+(%s)<sup>%d</sup>+%s" % (
rhofid.str, germ.str, reps, efid.str)
else:
txt = "L: %s<br>germ: %s<br>rho<sub>i</sub>: %s<br>E<sub>i</sub>: %s" \
% (str(L), germ.str, rhofid.str, efid.str)
txt += ("<br>value: %g" % val)
for lbl, addl_subMxs in addl_hover_submxs.items():
txt += "<br>%s: %s" % (lbl, str(addl_subMxs[iy][ix][iiy][iix]))
return txt
hover_info = hover_label_fn # generate_boxplot can handle this
xs = []; ys = []; texts = []
gstrs = set() # to eliminate duplicate strings
for ix, x in enumerate(g.used_xvals()):
for iy, y in enumerate(g.used_yvals()):
plaq = g.get_plaquette(x, y)
if sum_up:
if plaq.base not in gstrs:
tot = sum([sub_mxs[iy][ix][iiy][iix] for iiy, iix, _ in plaq])
xs.append(len(plaq.base)) # x-coord is len of *base* string
ys.append(tot)
gstrs.add(plaq.base)
if hover_info:
if callable(hover_info):
texts.append(hover_info(tot, iy, ix))
else:
texts.append(str(tot))
else:
for iiy, iix, opstr in plaq:
if opstr in gstrs: continue # skip duplicates
xs.append(len(opstr))
ys.append(sub_mxs[iy][ix][iiy][iix])
gstrs.add(opstr)
if hover_info:
if callable(hover_info):
texts.append(hover_info(sub_mxs[iy][ix][iiy][iix], iy, ix, iiy, iix))
else:
texts.append(str(sub_mxs[iy][ix][iiy][iix]))
#This GL version works, but behaves badly, sometimes failing to render...
#trace = go.Scattergl(x=xs, y=ys, mode="markers",
# marker=dict(size=8,
# color=[colormap.get_color(y) for y in ys],
# #colorscale=colormap.get_colorscale(), #doesn't seem to work properly in GL?
# line=dict(width=1)))
trace = go.Scatter(x=xs, y=ys, mode="markers",
marker=dict(size=8,
color=[colormap.get_color(y) for y in ys],
colorscale=colormap.get_colorscale(),
line=dict(width=1)))
if hover_info:
trace['hoverinfo'] = 'text'
trace['text'] = texts
else:
trace['hoverinfo'] = 'none'
xaxis = go_x_axis(
title='sequence length',
showline=False,
zeroline=True,
)
yaxis = go_y_axis(
title=ylabel
)
layout = go.Layout(
#title="Sum = %.2f" % sum(ys), #DEBUG
width=400 * scale,
height=400 * scale,
hovermode='closest',
xaxis=xaxis,
yaxis=yaxis,
)
return ReportFigure(go.Figure(data=[trace], layout=layout), colormap,
{'x': xs, 'y': ys})
def circuit_color_histogram(circuit_structure, sub_mxs, colormap,
ylabel="", scale=1.0):
"""
Similar to :func:`circuit_color_boxplot` except a histogram is created.
Parameters
----------
circuit_structure : CircuitStructure
Specifies a set of operation sequences along with their outer and inner x,y
structure, e.g. fiducials, germs, and maximum lengths.
sub_mxs : list
A list of lists of 2D numpy.ndarrays. sub_mxs[iy][ix] specifies the matrix of values
or sum (if sum_up == True) displayed in iy-th row and ix-th column of the plot. NaNs
indicate elements should not be displayed.
colormap : Colormap
The colormap used to determine box color.
hover_info : bool, optional
Whether to incude interactive hover labels.
sum_up : bool, optional
False displays each matrix element as it's own color box
True sums the elements of each (x,y) matrix and displays
a single color box for the sum.
ylabel : str, optional
The y-axis label to use.
scale : float, optional
Scaling factor to adjust the size of the final figure.
Returns
-------
plotly.Figure
"""
g = circuit_structure
ys = [] # artificially add minval so
gstrs = set() # to eliminate duplicate strings
for ix, x in enumerate(g.used_xvals()):
for iy, y in enumerate(g.used_yvals()):
plaq = g.get_plaquette(x, y)
#TODO: if sum_up then need to sum before appending...
for iiy, iix, opstr in plaq:
if opstr in gstrs: continue # skip duplicates
ys.append(sub_mxs[iy][ix][iiy][iix])
gstrs.add(opstr)
if len(ys) == 0: ys = [0] # case of no data - dummy so max works below
minval = 0
maxval = max(minval + 1e-3, _np.max(ys)) # don't let minval==maxval
nvals = len(ys)
cumulative = dict(enabled=False)
# marker=dict(color=barcolor),
#barcolor = 'gray'
nbins = 50
binsize = (maxval - minval) / (nbins - 1)
bincenters = _np.linspace(minval, maxval, nbins)
bindelta = (maxval - minval) / (nbins - 1) # spacing between bin centers
trace = go.Histogram(
x=[bincenters[0]] + ys, # artificially add 1 count in lowest bin so plotly anchors histogram properly
autobinx=False,
xbins=dict(
start=minval - binsize / 2.0,
end=maxval + binsize / 2.0,
size=binsize
),
name="count",
marker=dict(
color=[colormap.get_color(t) for t in bincenters],
line=dict(
color='black',
width=1.0,
)
),
cumulative=cumulative,
opacity=1.00,
showlegend=False,
)
dof = colormap.dof if hasattr(colormap, "dof") else 1
line_trace = go.Scatter(
x=bincenters,
y=[nvals * bindelta * _chi2.pdf(xval, dof) for xval in bincenters],
name="expected",
showlegend=False,
line=dict(
color=('rgb(0, 0, 0)'),
width=1) # dash = 'dash') # dash options include 'dash', 'dot', and 'dashdot'
)
hist_values, np_bins = _np.histogram(ys, nbins, range=(minval - binsize / 2.0,
maxval + binsize / 2.0))
if len(hist_values) > 0 and len(hist_values[hist_values > 0]) > 0:
minlog = _np.log10(max(_np.min(hist_values[hist_values > 0]) / 10.0, 1e-3))
maxlog = _np.log10(1.5 * _np.max(hist_values))
else:
minlog, maxlog = -3, 0 # defaults to (1e-3,1) when there's no data
layout = go.Layout(
#title="Sum = %.2f" % sum(ys), #DEBUG
width=500 * scale,
height=350 * scale,
font=dict(size=10),
xaxis=dict(
title=ylabel, # b/c "y-values" are along x-axis in histogram
showline=True
),
yaxis=dict(
type='log',
#tickformat='g',
exponentformat='power',
showline=True,
range=[minlog, maxlog]
),
bargap=0,
bargroupgap=0,
legend=dict(orientation="h")
)
pythonVal = {'histogram values': ys}
return ReportFigure(go.Figure(data=[trace, line_trace], layout=layout),
colormap, pythonVal)
def opmatrix_color_boxplot(op_matrix, color_min, color_max, mx_basis=None, mx_basis_y=None,
xlabel=None, ylabel=None,
box_labels=False, colorbar=None, prec=0, scale=1.0,
eb_matrix=None, title=None):
"""
Creates a color box plot for visualizing a single matrix.
Parameters
----------
op_matrix : numpy array
The matrix to visualize.
color_min, color_max : float
Minimum and maximum of the color scale.
mx_basis, mx_basis_y : str or Basis, optional
The name abbreviation for the basis or a Basis object. Used to label the
columns & rows (x- and y-ticklabels). Typically in
{"pp","gm","std","qt"}. If you don't want labels, leave as None.
xlabel, ylabel : str, optional
Axis labels for the plot.
box_labels : bool, optional
Whether box labels are displayed.
colorbar : bool optional
Whether to display a color bar to the right of the box plot. If None,
then a colorbar is displayed when `box_labels == False`.
prec : int or {'compact','compacthp'}, optional
Precision for box labels. Only relevant when box_labels == True. Allowed
values are:
- 'compact' = round to nearest whole number using at most 3 characters
- 'compacthp' = show as much precision as possible using at most 3 characters
- int >= 0 = fixed precision given by int
- int < 0 = number of significant figures given by -int
scale : float, optional
Scaling factor to adjust the size of the final figure.
eb_matrix : numpy array, optional
An array, of the same size as `op_matrix`, which gives error bars to be
be displayed in the hover info.