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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030 | @experimental
@beartype
def jupyter_visualize(
histogram_specs: Iterable[
Union[HLikeT, Tuple[str, HLikeT], Tuple[str, HLikeT, HLikeT]]
],
default_breakout_type: Union[int, BreakoutType] = BreakoutType.NONE,
default_markers="<>v^dPXo",
default_main_plot_type: str = "line",
main_plot_funcs_by_type=_DEFAULT_MAIN_PLOT_FUNCS_BY_NAME,
):
r"""
!!! warning "Experimental"
This function should be considered experimental and may change or disappear in
future versions.
Takes a list of one or more *histogram_specs* and produces an interactive
visualization reminiscent of [AnyDice](https://anydice.com/), but with some extra
goodies.
Each item in *histogram_specs* can be a ``#!python dyce.H`` object, a 2-tuple, or a
3-tuple. 2-tuples are in the format ``#!python (str, H)``, where ``#!python str`` is
a name or description that will be used to identify the accompanying ``#!python H``
object where it appears in the visualization. 3-tuples are in the format ``#!python
(str, H, H)``. The second ``#!python H`` object is used for the interior ring in
“burst” break-out graphs, but otherwise ignored.
The “Powered by the _Apocalypse_ (PbtA)” example in the introduction notebook should
give an idea of the effect. (See [Interactive quick
start](index.md#interactive-quick-start).)
The *default_breakout_type* parameter indicates which break-out graphs to display
initially and defaults to [``BreakoutType.NONE``][anydyce.viz.BreakoutType.NONE].
This only affects the initial display. Break-out graphs can be hidden or changed
with the interactive controls.
"""
# TODO(posita): This is a hack-on-a-stream-of-consciousness-until-it-kind-of-works
# approach. It would be nice if we had some semblance of an architecture, especially
# one that allowed for better customization building blocks. Right now, it's pretty
# limited and fragile.
assert default_main_plot_type in main_plot_funcs_by_type
def _display(
scale: int,
enable_cutoff: bool,
cutoff: int,
breakouts: BreakoutType,
main_plot_type: str,
graph_type: GraphType,
main_plot_style: str,
alpha: float,
show_shadow: bool,
markers: str,
burst_graph_color: str,
burst_text_color: str,
burst_bg_color: str,
burst_swap: bool,
) -> None:
def _hs() -> Iterator[Tuple[str, H, Optional[H]]]:
if enable_cutoff:
cutoff_frac = Fraction(cutoff).limit_denominator(
_CUTOFF_BASE**_CUTOFF_EXP
)
else:
cutoff_frac = Fraction(0)
label: str
first_h_like: HLikeT
second_h_like: Optional[HLikeT]
for i, thing in enumerate(histogram_specs):
if isinstance(thing, (H, HableT)):
label = f"Histogram {i + 1}"
first_h_like = thing
second_h_like = None
else:
label, first_h_like = thing[:2]
if len(thing) < 3:
second_h_like = None
else:
second_h_like = thing[2] # type: ignore [misc]
assert isinstance(label, str)
first_h = limit_for_display(
first_h_like.h()
if isinstance(first_h_like, HableT)
else first_h_like,
cutoff_frac,
)
assert isinstance(
first_h, H
), f"unrecognized histogram type {first_h!r}"
if second_h_like is None:
second_h = None
else:
second_h = limit_for_display(
second_h_like.h()
if isinstance(second_h_like, HableT)
else second_h_like,
cutoff_frac,
)
assert second_h is None or isinstance(
second_h, H
), f"unrecognized histogram type {second_h!r}"
yield label, first_h, second_h
hs_list = list(_hs())
unique_outcomes = sorted(
set(chain.from_iterable(h.outcomes() for _, h, _ in hs_list))
)
def _csv_download_link() -> HTML:
labels = [label for label, _, _ in hs_list]
raw_buffer = io.BytesIO()
csv_buffer = io.TextIOWrapper(
raw_buffer, encoding="utf-8", newline="", write_through=True
)
csv_writer = csv.DictWriter(csv_buffer, fieldnames=["Outcome"] + labels)
csv_writer.writeheader()
for outcome in unique_outcomes:
row = {"Outcome": outcome}
row.update(
{
label: h[outcome] / h.total
for label, h, _ in hs_list
if outcome in h
}
)
csv_writer.writerow(row)
# Inspiration: <https://medium.com/@charles2588/how-to-upload-download-files-to-from-notebook-in-my-local-machine-6a4e65a15767>
csv_name = ", ".join(labels)
csv_name = csv_name if len(labels) <= 32 else (csv_name[:29] + "...")
payload = base64.standard_b64encode(raw_buffer.getvalue()).decode()
return HTML(
f"""
<a download="{csv_name}.csv" href="data:text/csv;base64,{payload}" target="_blank">
Download raw data as CSV
</a>
"""
)
display(_csv_download_link())
matplotlib.rcParams.update(matplotlib.rcParamsDefault)
matplotlib.pyplot.rcParams["figure.figsize"] = (
scale,
scale / 16 * 9,
)
matplotlib.style.use(main_plot_style)
_, ax = matplotlib.pyplot.subplots()
if main_plot_type == "scatter":
matplotlib.pyplot.rcParams["lines.markersize"] *= 2
main_plot_funcs_by_type[main_plot_type](
ax,
hs_list,
graph_type=graph_type,
alpha=alpha,
show_shadow=show_shadow,
markers=markers if markers else " ",
)
ax.set_xticks(unique_outcomes)
ax.legend()
with warnings.catch_warnings():
warnings.simplefilter("ignore")
matplotlib.pyplot.tight_layout()
matplotlib.pyplot.show()
cutoff_widget.disabled = not enable_cutoff
burst_graph_color_widget.disabled = True
burst_text_color_widget.disabled = True
burst_bg_color_widget.disabled = True
burst_swap_widget.disabled = True
if breakouts == BreakoutType.BARH:
per_outcome_height = 1
per_breakout_height = 1
total_height = per_breakout_height * len(hs_list) + sum(
per_outcome_height
for _ in chain.from_iterable(h.outcomes() for _, h, _ in hs_list)
)
inches_per_height_unit = scale / 64
matplotlib.pyplot.rcParams["figure.figsize"] = (
scale,
total_height * inches_per_height_unit,
)
grid = (total_height, 1)
top = 0
ax = None
src_ax = None
barh_kw: Dict[str, Any] = dict(alpha=alpha)
if show_shadow:
barh_kw.update(
dict(
path_effects=[
matplotlib.patheffects.withSimplePatchShadow(),
matplotlib.patheffects.Normal(),
]
)
)
for i, (label, h, _) in enumerate(hs_list):
outcomes, values = values_xy_for_graph_type(h, graph_type)
loc = (top, 0)
rowspan = per_breakout_height + per_outcome_height * len(outcomes)
top += rowspan
if src_ax is None:
src_ax = ax = matplotlib.pyplot.subplot2grid(
grid, loc, rowspan=rowspan
)
else:
ax = matplotlib.pyplot.subplot2grid(
grid, loc, rowspan=rowspan, sharex=src_ax
)
ax.set_yticks(outcomes)
ax.tick_params(labelbottom=False)
ax.barh(outcomes, values, label=label, **barh_kw)
ax.legend(loc="upper right")
if ax is not None:
ax.tick_params(labelbottom=True)
ax.xaxis.set_major_formatter(matplotlib.ticker.PercentFormatter(xmax=1))
with warnings.catch_warnings():
warnings.simplefilter("ignore")
matplotlib.pyplot.tight_layout()
matplotlib.pyplot.show()
elif breakouts == BreakoutType.BURST:
cols = 3
rows = len(hs_list) // cols + (len(hs_list) % cols != 0)
matplotlib.pyplot.rcParams["figure.figsize"] = (
scale,
scale / 16 * 5 * rows,
)
matplotlib.pyplot.figure(facecolor=burst_bg_color)
burst_graph_color_widget.disabled = False
burst_text_color_widget.disabled = False
burst_bg_color_widget.disabled = False
if any(
h_outer is not None and h_inner != h_outer
for _, h_inner, h_outer in hs_list
):
burst_swap_widget.disabled = False
for i, (label, h_inner, h_outer) in enumerate(hs_list):
plot_burst_kw: Dict[str, Any] = dict(
title=label,
inner_color=burst_graph_color,
text_color=burst_text_color,
alpha=alpha,
)
if h_outer is not None:
if not burst_swap:
h_inner, h_outer = h_outer, h_inner
plot_burst_kw.update(
dict(outer_formatter=_outcome_name_probability_formatter)
)
ax = matplotlib.pyplot.subplot2grid((rows, cols), (i // cols, i % cols))
plot_burst(
ax,
h_inner,
h_outer,
**plot_burst_kw,
)
with warnings.catch_warnings():
warnings.simplefilter("ignore")
matplotlib.pyplot.tight_layout()
matplotlib.pyplot.show()
else:
assert (
breakouts == BreakoutType.NONE
), f"unrecognized breakout type {breakouts!r}"
scale_widget = ipywidgets.widgets.IntSlider(
value=12,
min=8,
max=16,
step=1,
continuous_update=False,
description="Scale",
)
enable_cutoff_widget = ipywidgets.widgets.Checkbox(
value=False,
description="Hide Data",
)
cutoff_widget = ipywidgets.widgets.FloatLogSlider(
value=_CUTOFF_BASE ** -(_CUTOFF_EXP - 2),
base=_CUTOFF_BASE,
min=-_CUTOFF_EXP,
max=-(_CUTOFF_EXP - 3),
step=0.2,
continuous_update=False,
readout_format=".6f",
description="Hide up to",
)
breakouts_widget = ipywidgets.widgets.RadioButtons(
value=BreakoutType(default_breakout_type),
options=(
("None", BreakoutType.NONE),
("Horizontal Bar", BreakoutType.BARH),
("Burst", BreakoutType.BURST),
),
)
main_plot_type_widget = ipywidgets.widgets.Dropdown(
value=default_main_plot_type,
options=main_plot_funcs_by_type.keys(),
description="Main Type",
)
graph_type_widget = ipywidgets.widgets.RadioButtons(
value=GraphType.NORMAL,
options=(
("Normal", GraphType.NORMAL),
("At Least", GraphType.AT_LEAST),
("At Most", GraphType.AT_MOST),
),
)
main_plot_style_widget = ipywidgets.widgets.Dropdown(
value="bmh",
options=["default"] + matplotlib.style.available,
description="Main Colors",
)
alpha_widget = ipywidgets.widgets.FloatSlider(
value=0.6,
min=0.0,
max=1.0,
step=0.05,
continuous_update=False,
readout_format="0.0%",
description="Opacity",
)
show_shadow_widget = ipywidgets.widgets.Checkbox(
value=False,
description="Shadows",
)
markers_widget = ipywidgets.widgets.Text(
value=default_markers,
description="Markers",
)
burst_graph_color_widget = ipywidgets.widgets.Dropdown(
value=DEFAULT_GRAPH_COLOR,
options=sorted(matplotlib.cm.cmap_d.keys()),
disabled=True,
description="Burst Graph",
)
burst_text_color_widget = ipywidgets.widgets.Dropdown(
value=DEFAULT_TEXT_COLOR,
options=sorted(sorted(matplotlib.colors.CSS4_COLORS.keys())),
disabled=True,
description="Burst Text",
)
burst_bg_color_widget = ipywidgets.widgets.Dropdown(
value="white",
options=sorted(sorted(matplotlib.colors.CSS4_COLORS.keys())),
disabled=True,
description="Burst Bkgrd",
)
burst_swap_widget = ipywidgets.widgets.Checkbox(
value=False,
description="Burst Swap",
)
display(
ipywidgets.widgets.VBox(
[
ipywidgets.widgets.HBox(
[
ipywidgets.widgets.VBox(
[
scale_widget,
enable_cutoff_widget,
cutoff_widget,
ipywidgets.widgets.Label("Break-out Graphs:"),
breakouts_widget,
]
),
ipywidgets.widgets.VBox(
[
main_plot_type_widget,
ipywidgets.widgets.Label("Plot Type:"),
graph_type_widget,
main_plot_style_widget,
alpha_widget,
show_shadow_widget,
markers_widget,
]
),
ipywidgets.widgets.VBox(
[
burst_graph_color_widget,
burst_text_color_widget,
burst_bg_color_widget,
burst_swap_widget,
]
),
]
),
ipywidgets.widgets.interactive_output(
_display,
{
"scale": scale_widget,
"enable_cutoff": enable_cutoff_widget,
"cutoff": cutoff_widget,
"breakouts": breakouts_widget,
"main_plot_type": main_plot_type_widget,
"graph_type": graph_type_widget,
"main_plot_style": main_plot_style_widget,
"alpha": alpha_widget,
"show_shadow": show_shadow_widget,
"markers": markers_widget,
"burst_graph_color": burst_graph_color_widget,
"burst_text_color": burst_text_color_widget,
"burst_bg_color": burst_bg_color_widget,
"burst_swap": burst_swap_widget,
},
),
]
)
)
|