Skip to content

dyceum package reference

dyceum.magic

IPython Magic(s) for the AnyDice interpreter.

Currently, this includes:

  • %%anyd - run cell body as legacy AnyDice source.
  • %anyd_load - fetch an AnyDice program by ID or URL and replace the cell with its source.

anyd(line: str, cell: str) -> None

Run the cell as legacy AnyDice source and display each output's distribution.

Examples:

1
2
3
4
5
6
7
8
%%anyd
output 3d6

%%anyd --bar
output 3d6

%%anyd --short --precision 32
output 1d100
Source code in dyceum/magic.py
 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
@magic_arguments()
@argument(
    f"--{_FORMAT_BAR}",
    action="store_const",
    const=_FORMAT_BAR,
    default=_FORMAT_TEXT,
    dest=_OUTPUT_FORMAT,
    help=f'use interactive visual formatting with "{_PLOTTER_NAMES_BY_FORMAT[_FORMAT_BAR]}" selected',
)
@argument(
    f"--{_FORMAT_BURST}",
    action="store_const",
    const=_FORMAT_BURST,
    dest=_OUTPUT_FORMAT,
    help=f'use interactive visual formatting with "{_PLOTTER_NAMES_BY_FORMAT[_FORMAT_BURST]}" selected',
)
@argument(
    f"--{_FORMAT_LINE}",
    action="store_const",
    const=_FORMAT_LINE,
    dest=_OUTPUT_FORMAT,
    help=f'use interactive visual formatting with "{_PLOTTER_NAMES_BY_FORMAT[_FORMAT_LINE]}" selected',
)
@argument(
    f"--{_FORMAT_TEXT}",
    action="store_const",
    const=_FORMAT_TEXT,
    dest=_OUTPUT_FORMAT,
    help="format each output as multi-line text",
)
@argument(
    f"--{_FORMAT_TEXT_SHORT}",
    action="store_const",
    const=_FORMAT_TEXT_SHORT,
    dest=_OUTPUT_FORMAT,
    help="format each output as single-line text",
)
@argument(
    "--precision",
    type=int,
    default=DEFAULT_PRECISION,
    help=f"number of decimal places used when formatting output values as text. Default: {DEFAULT_PRECISION}",
)
def anyd(line: str, cell: str) -> None:
    r"""
    Run the cell as legacy AnyDice source and display each output's distribution.

    Examples:

        %%anyd
        output 3d6

        %%anyd --bar
        output 3d6

        %%anyd --short --precision 32
        output 1d100
    """
    args = parse_argstring(anyd, line)

    with warnings.catch_warnings():
        # Everything other than a DeprecationWarning or ExperimentalWarning (e.g.,
        # TruncationWarning, etc.) should bubble up so Jupyter renders it next to the
        # cell output
        warnings.filterwarnings("ignore", category=DeprecationWarning)
        warnings.filterwarnings("ignore", category=ExperimentalWarning)
        # Seed the display precision from the CLI flag; `set "dyceum: display
        # precision"` inside the cell can override (the run() call mutates
        # settings in place). format_results then reads the final value.
        settings = Settings()
        settings.set("dyceum: display precision", args.precision)
        results = run(cell, settings=settings)
        if args.output_format in _PLOTTER_NAMES_BY_FORMAT:
            jupyter_visualize(
                results,
                selected_name=_PLOTTER_NAMES_BY_FORMAT[args.output_format],
            )
        else:
            print(
                format_results(
                    results,
                    settings=settings,
                    short=args.output_format == _FORMAT_TEXT_SHORT,
                )
            )

anyd_load(line: str) -> None

Fetch an AnyDice program by ID or URL and replace the cell with its source.

Examples:

1
2
%anyd_load 4d2
%anyd_load https://anydice.com/program/4d2

On success, the cell is replaced with an %%anyd cell containing the fetched program plus a comment header recording the source URL and fetch time. The replaced cell is not auto-executed. On failure (e.g., network error, missing program, etc.), the exception propagates to Jupyter and the original %anyd_load line is left in place.

Source code in dyceum/magic.py
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
@magic_arguments()
@argument(
    "location_or_id",
    help="an AnyDice program ID or URL",
)
def anyd_load(line: str) -> None:
    r"""
    Fetch an AnyDice program by ID or URL and replace the cell with its source.

    Examples:

        %anyd_load 4d2
        %anyd_load https://anydice.com/program/4d2

    On success, the cell is replaced with an `%%anyd` cell containing the fetched
    program plus a comment header recording the source URL and fetch time. The replaced
    cell is *not* auto-executed. On failure (e.g., network error, missing program,
    etc.), the exception propagates to Jupyter and the original `%anyd_load` line is
    left in place.
    """
    args = parse_argstring(anyd_load, line)
    program_id_hex, initial_url, _final_url, program = fetch_anydice_program(
        args.location_or_id
    )
    fetched_at = datetime.now(UTC).astimezone().isoformat(timespec="seconds")
    new_cell = (
        "%%anyd\n"
        "\\ ================================================================================ /\n"
        f"  AnyDice program {program_id_hex} fetched from {initial_url}\n"
        f"  at {fetched_at} using:\n"
        f"  %anyd_load {args.location_or_id}\n"
        "/ ================================================================================ \\\n"
        f"{program}"
    )
    if is_pyodide():
        # Insert a space after any `\\<LF>` or `\\<CR>` so Python's tokenizer doesn't
        # treat the `\\` as a line continuation.
        #
        # JupyterLite's pyodide-kernel eagerly tokenizes cell-magic bodies as Python.
        # `\\<LF>` collapses lines via line continuation, often producing mixed-
        # indentation `IndentationError`s. Adding a space after `\\` breaks the
        # continuation. AnyDice ignores trailing whitespace after a comment-closing
        # `\\`, so this is a no-op for AnyDice parsing.
        new_cell = new_cell.replace("\\\n", "\\ \n").replace("\\\r", "\\ \r")
    # Inside a magic, the shell is what just invoked us is guaranteed to exist
    if is_pyodide():
        _display_program_with_copy_button(new_cell)
    else:
        ipy = get_ipython()
        assert ipy
        ipy.set_next_input(new_cell, replace=True)

load_ipython_extension(ipy: InteractiveShell) -> None

IPython extension entry point. Registers Magics.

Invoked by %load_ext dyceum.magic from inside an IPython/Jupyter session.

Source code in dyceum/magic.py
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
def load_ipython_extension(ipy: InteractiveShell) -> None:
    r"""
    IPython extension entry point. Registers Magics.

    Invoked by `%load_ext dyceum.magic` from inside an IPython/Jupyter session.
    """
    # The expected ipython.register_magic_function works at runtime (as verified by our
    # load-extension tests), but type checkers get confused if we use it that way.
    # Apparently register_magic_function is unbound? Not sure. Anyway, this approach
    # seems to make everyone happy for now.
    type(ipy).register_magic_function(
        ipy,
        anyd,
        magic_kind="cell",
    )
    type(ipy).register_magic_function(
        ipy,
        anyd_load,
        magic_kind="line",
    )

dyceum.viz

BurstHPlotter

Bases: HPlotter

Experimental

This class should be considered experimental and may change or disappear in future versions.

A plotter for creating one burst plot per primary histogram. If provided, associated secondary histograms are used for the outer rings.

Source code in dyceum/viz.py
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
class BurstHPlotter(HPlotter):
    r"""
    !!! warning "Experimental"

        This class should be considered experimental and may change or disappear in
        future versions.

    A plotter for creating one burst plot per primary histogram. If provided, associated
    secondary histograms are used for the outer rings.
    """

    NAME: str = "Burst Plots"

    def layout(self, plot_widgets: PlotWidgets) -> widgets.Widget:
        cutoff_layout_widget = super().layout(plot_widgets)

        return widgets.VBox(
            [
                widgets.HBox(
                    [
                        widgets.VBox(
                            [
                                cutoff_layout_widget,
                            ]
                        ),
                        widgets.VBox(
                            [
                                plot_widgets.burst_swap,
                                plot_widgets.burst_zero_fill_normalize,
                                plot_widgets.burst_cmap_inner,
                                plot_widgets.burst_cmap_outer,
                                plot_widgets.burst_cmap_use_midpoints,
                                plot_widgets.burst_cmap_link,
                            ]
                        ),
                        widgets.VBox(
                            [
                                plot_widgets.alpha,
                                plot_widgets.plot_style,
                                plot_widgets.burst_color_text,
                                plot_widgets.burst_color_bg,
                                plot_widgets.burst_color_bg_trnsp,
                                plot_widgets.burst_columns,
                            ]
                        ),
                    ]
                ),
            ]
        )

    def plot(
        self,
        hs: Sequence[tuple[str, H, H | None]],
        settings: SettingsDict,
    ) -> None:
        cols = settings["burst_columns"]
        assert cols > 0
        logical_rows = len(hs) // cols + (len(hs) % cols != 0)
        # Height of row gaps in relation to height of figs
        gap_size_ratio = Fraction(1, 5)
        total_gaps = max(0, logical_rows - 1)
        figsize = (
            settings["resolution"],
            float(
                settings["resolution"]
                * (logical_rows + total_gaps * gap_size_ratio)
                / cols
            ),
        )
        plt.figure(figsize=figsize)
        actual_rows_per_fig = gap_size_ratio.denominator
        actual_rows_per_gap = gap_size_ratio.numerator
        total_actual_rows = (
            logical_rows * actual_rows_per_fig + total_gaps * actual_rows_per_gap
        )

        def _zero_fill_normalize() -> Iterator[tuple[str, H, H | None]]:
            unique_outcomes: set[Any] = set()
            for _, first_h, second_h in hs:
                unique_outcomes.update(first_h)
                if second_h:
                    unique_outcomes.update(second_h)
            for label, first_h, second_h in hs:
                yield (
                    label,
                    first_h.zero_fill(unique_outcomes),
                    None if second_h is None else second_h.zero_fill(unique_outcomes),
                )

        if settings["burst_zero_fill_normalize"]:
            hs = tuple(_zero_fill_normalize())
        h_inner: H
        h_outer: H | None
        for i, (label, h_inner, h_outer) in enumerate(hs):
            if h_outer is not None and settings["burst_swap"]:
                h_inner, h_outer = h_outer, h_inner  # ruff: ignore[redefined-loop-name]
            logical_row = i // cols
            actual_row_start = logical_row * (actual_rows_per_gap + actual_rows_per_fig)
            ax = plt.subplot2grid(
                (total_actual_rows, cols),
                (actual_row_start, i % cols),
                rowspan=actual_rows_per_fig,
            )
            plot_burst(
                h_inner,
                h_outer,
                alpha=settings["alpha"],
                ax=ax,
                cmap=settings["burst_cmap_inner"],
                compare_cmap=(
                    settings["burst_cmap_inner"]
                    if settings["burst_cmap_link"]
                    else settings["burst_cmap_outer"]
                ),
                title=label,
                use_midpoints_for_colors=settings["burst_cmap_use_midpoints"],
            )
            ax.title.set_color(settings["burst_color_text"])
            for text in ax.texts:
                text.set_color(
                    settings["burst_color_text"]
                )  # wedge labels (both rings)
            for patch in ax.patches:
                patch.set_edgecolor(
                    settings["burst_color_text"]
                )  # wedge edges (both rings)
            ax.set_facecolor(settings["burst_color_bg"])

    def transparent(self, *, requested: bool) -> bool:
        return requested

HPlotter

Experimental

This class should be considered experimental and may change or disappear in future versions.

A plotter responsible for laying out control widgets and visualizing data provided by primary and optional secondary histograms. (See the plot method.)

Source code in dyceum/viz.py
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
class HPlotter:
    r"""
    !!! warning "Experimental"

        This class should be considered experimental and may change or disappear in
        future versions.

    A plotter responsible for laying out control widgets and visualizing data provided
    by primary and optional secondary histograms. (See the
    [*plot* method][dyceum.viz.HPlotter.plot].)
    """

    @property
    @abstractmethod
    def NAME(self) -> str:  # ruff: ignore[invalid-function-name]
        r"""
        The display name of the plotter.
        """
        raise NotImplementedError

    def layout(self, plot_widgets: PlotWidgets) -> widgets.Widget:
        r"""
        Takes a set of widgets (*plot_widgets*) and returns a container (layout) widget
        selecting those needed by the plotter.
        """
        return widgets.VBox(
            [
                plot_widgets.enable_cutoff,
                plot_widgets.cutoff,
                plot_widgets.resolution,
            ]
        )

    @abstractmethod
    def plot(
        self,
        hs: Sequence[tuple[str, H, H | None]],
        settings: SettingsDict,
    ) -> None:
        r"""
        Creates and displays a visualization of the provided histograms. *fig* is the
        [`#!python
        matplotlib.figure.Figure`](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure)
        in which the visualization should be constructed. *hs* is a sequence of
        three-tuples, a name, a primary histogram, and an optional secondary histogram
        (`None` if omitted). Plotters should implement this function to
        display at least the primary histogram and visually associate it with the name.
        """
        raise NotImplementedError

    def transparent(self, *, requested: bool) -> bool:  # ruff: ignore[unused-method-argument]
        r"""
        Returns whether this plotter produces plots which support transparency if
        *requested*. The default implementation always returns `False`.
        """
        return False

NAME: str abstractmethod property

The display name of the plotter.

layout(plot_widgets: PlotWidgets) -> widgets.Widget

Takes a set of widgets (plot_widgets) and returns a container (layout) widget selecting those needed by the plotter.

Source code in dyceum/viz.py
634
635
636
637
638
639
640
641
642
643
644
645
def layout(self, plot_widgets: PlotWidgets) -> widgets.Widget:
    r"""
    Takes a set of widgets (*plot_widgets*) and returns a container (layout) widget
    selecting those needed by the plotter.
    """
    return widgets.VBox(
        [
            plot_widgets.enable_cutoff,
            plot_widgets.cutoff,
            plot_widgets.resolution,
        ]
    )

plot(hs: Sequence[tuple[str, H, H | None]], settings: SettingsDict) -> None abstractmethod

Creates and displays a visualization of the provided histograms. fig is the matplotlib.figure.Figure in which the visualization should be constructed. hs is a sequence of three-tuples, a name, a primary histogram, and an optional secondary histogram (None if omitted). Plotters should implement this function to display at least the primary histogram and visually associate it with the name.

Source code in dyceum/viz.py
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
@abstractmethod
def plot(
    self,
    hs: Sequence[tuple[str, H, H | None]],
    settings: SettingsDict,
) -> None:
    r"""
    Creates and displays a visualization of the provided histograms. *fig* is the
    [`#!python
    matplotlib.figure.Figure`](https://matplotlib.org/stable/api/figure_api.html#matplotlib.figure.Figure)
    in which the visualization should be constructed. *hs* is a sequence of
    three-tuples, a name, a primary histogram, and an optional secondary histogram
    (`None` if omitted). Plotters should implement this function to
    display at least the primary histogram and visually associate it with the name.
    """
    raise NotImplementedError

transparent(*, requested: bool) -> bool

Returns whether this plotter produces plots which support transparency if requested. The default implementation always returns False.

Source code in dyceum/viz.py
664
665
666
667
668
669
def transparent(self, *, requested: bool) -> bool:  # ruff: ignore[unused-method-argument]
    r"""
    Returns whether this plotter produces plots which support transparency if
    *requested*. The default implementation always returns `False`.
    """
    return False

HPlotterChooser

Experimental

This class should be considered experimental and may change or disappear in future versions.

A controller for coordinating the display of a histogram data set and selection of one or more plotters as well as triggering updates in response to either control or data changes. All parameters for the [initializer][dyceum.HPlotterChooser.__init__] are optional.

histogram_specs is the histogram data set which defaults to an empty tuple. If provided, each item therein can be a dyce.H object, a 2-tuple, or a 3-tuple. 2-tuples are in the format (str, H), where str is a name or description that will be used to identify the accompanying H object where it appears in the visualization. 3-tuples are in the format (str, H, H). The second H object is used for the interior ring in “burst” break-out graphs, but otherwise ignored. If an item is None, it is roughly synonymous with ("", H({}), None), with the exception that it does not advance the automatic naming counter. This can be useful as “blank” filler to achieve a desired layout (e.g., where one wants to compare across burst graphs that don't neatly fit into a particular row size).

The histogram data set can also be replaced via update_hs.

Plotter controls (including the selection tabs) are contained within an accordion interface. If controls_expanded is True, the accordion is initially expanded for the user. If it is False, it is initially collapsed.

plot_widgets allows object creators to customize the available control widgets, including their initial values. It defaults to None which results in a fresh PlotWidgets object being created during construction.

plotters_or_factories allows overriding which plotters are available. The default is to provide factories for all plotters currently available in dyceum.

selected_name is the name of the plotter to be displayed initially. It must match the NAME property of an available plotter provided by the plotters_or_factories parameter.

Source code in dyceum/viz.py
 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
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
class HPlotterChooser:
    r"""
    !!! warning "Experimental"

        This class should be considered experimental and may change or disappear in
        future versions.

    A controller for coordinating the display of a histogram data set and selection of
    one or more plotters as well as triggering updates in response to either control or
    data changes. All parameters for the [initializer][dyceum.HPlotterChooser.__init__]
    are optional.

    *histogram_specs* is the histogram data set which defaults to an empty tuple. If
    provided, each item therein can be a `dyce.H` object, a 2-tuple, or a
    3-tuple. 2-tuples are in the format `(str, H)`, where `str` is
    a name or description that will be used to identify the accompanying `H`
    object where it appears in the visualization. 3-tuples are in the format `#!python
    (str, H, H)`. The second `H` object is used for the interior ring in
    “burst” break-out graphs, but otherwise ignored. If an item is `None`, it
    is roughly synonymous with `("", H({}), None)`, with the exception that
    it does not advance the automatic naming counter. This can be useful as “blank”
    filler to achieve a desired layout (e.g., where one wants to compare across burst
    graphs that don't neatly fit into a particular row size).

    The histogram data set can also be replaced via
    [`update_hs`][dyceum.viz.HPlotterChooser.update_hs].

    Plotter controls (including the selection tabs) are contained within an accordion
    interface. If *controls_expanded* is `True`, the accordion is initially
    expanded for the user. If it is `False`, it is initially collapsed.

    *plot_widgets* allows object creators to customize the available control widgets,
    including their initial values. It defaults to `None` which results in a
    fresh [`PlotWidgets`][dyceum.viz.PlotWidgets] object being created during
    construction.

    *plotters_or_factories* allows overriding which plotters are available. The default
    is to provide factories for all plotters currently available in `dyceum`.

    *selected_name* is the name of the plotter to be displayed initially. It must match
    the `NAME` property of an available plotter provided by the
    *plotters_or_factories* parameter.
    """

    def __init__(
        self,
        histogram_specs: Iterable[
            HLikeT | tuple[str, HLikeT] | tuple[str, HLikeT, HLikeT | None] | None
        ] = (),
        *,
        controls_expanded: bool = False,
        plot_widgets: PlotWidgets | None = None,
        plotters_or_factories: Iterable[HPlotter | HPlotterFactoryT] = (
            BurstHPlotter,
            LineHPlotter,
            HorizontalBarHPlotter,
        ),
        selected_name: str | None = None,
    ) -> None:
        r"""Constructor."""
        plotters = tuple(
            plotter if isinstance(plotter, HPlotter) else plotter()
            for plotter in plotters_or_factories
        )

        if not plotters:
            raise ValueError("must provide at least one plotter")

        self._plotters_by_name: Mapping[str, HPlotter] = {
            plotter.NAME: plotter for plotter in plotters
        }

        assert self._plotters_by_name

        if selected_name is None:
            selected_name = _first_of(self._plotters_by_name)

        if selected_name is not None and selected_name not in self._plotters_by_name:
            raise ValueError(
                f"selected_name {selected_name!r} does not match any plotter"
            )

        if len(self._plotters_by_name) < len(plotters):
            duplicate_names = ", ".join(
                repr(plotter_name)
                for plotter_name, count in Counter(
                    plotter.NAME for plotter in plotters
                ).items()
                if count > 1
            )
            warnings.warn(
                f"ignoring redundant plotters with duplicate names {duplicate_names}",
                PlotWarning,
                stacklevel=1,
            )

        if plot_widgets is None:
            plot_widgets = PlotWidgets()

        self._plot_widgets = plot_widgets
        self._layouts_by_name: Mapping[str, widgets.Widget] = {}

        for plotter_name, plotter in self._plotters_by_name.items():
            self._layouts_by_name[plotter_name] = plotter.layout(plot_widgets)

        self.hs: tuple[tuple[str, H, H | None], ...] = ()
        self._hs_culled: tuple[tuple[str, H, H | None], ...] = ()
        self._cutoff: float | None = None
        self._csv_download_link_html = ""
        self.update_hs(histogram_specs)
        self._selected_plotter: HPlotter | None
        tab_names = tuple(self._plotters_by_name.keys())

        chooser_tab = widgets.Tab(
            children=tuple(self._layouts_by_name.values()),
            selected_index=(
                0 if selected_name is None else tab_names.index(selected_name)
            ),
        )

        for i, tab_name in enumerate(tab_names):
            chooser_tab.set_title(i, tab_name)

        def _handle_tab(change: _ChangeT) -> None:
            assert change["name"] == "selected_index"
            self._selected_plotter = next(
                islice(self._plotters_by_name.values(), change["new"], None)
            )
            self._trigger_update()

        chooser_tab.observe(_handle_tab, names="selected_index")

        self._selected_plotter = next(
            islice(self._plotters_by_name.values(), chooser_tab.selected_index, None)
        )

        self._out = widgets.VBox(
            [
                widgets.Accordion(
                    children=[chooser_tab],
                    titles=["Plot Controls"],
                    selected_index=0 if controls_expanded else None,
                ),
                # INVARIANT: This registers interactive_output's observers on every
                # control (incl. plot_style) *after* PlotWidgets.__init__ registers
                # _handle_plot_style. See the matching note there. Do not reorder these
                # so that interactive_output observes plot_style before
                # _handle_plot_style.
                widgets.interactive_output(self.plot, self._plot_widgets.asdict()),
            ]
        )

    def interact(self) -> None:
        r"""
        Displays the container responsible for selecting which plotter is used.
        """
        display(self._out)

    def plot(
        self,
        **kw,  # ruff: ignore[missing-type-kwargs]
    ) -> None:
        r"""
        Callback for updating the visualization in response to configuration or data
        changes. *settings* are the current values from all control widgets. (See
        [`PlotWidgets`][dyceum.viz.PlotWidgets].)
        """
        if self._plot_widgets.plot_updates_suspended:
            return
        settings = cast("SettingsDict", kw)
        cutoff = (
            self._plot_widgets.cutoff.value
            if self._plot_widgets.enable_cutoff.value
            else None
        )

        if self._cutoff != cutoff:
            self._cutoff = cutoff
            self._cull_data()

        with mstyle.context(settings["plot_style"]):
            if self._selected_plotter is not None:
                self._selected_plotter.plot(self._hs_culled, settings)
                transparent = self._selected_plotter.transparent(
                    requested=settings["burst_color_bg_trnsp"]
                )
            else:
                transparent = False
            buf = io.BytesIO()
            plt.savefig(
                buf,
                bbox_inches="tight",
                facecolor=mcolors.to_rgba(
                    settings["burst_color_bg"], alpha=0.0 if transparent else None
                ),
                format="SVG",
                transparent=transparent,
            )
            img_name = "-".join(label for label, _, _ in self.hs)
            svg_raw = buf.getvalue().decode()
            display(
                HTML(
                    rf"""
{self._csv_download_link_html} |
<a download="{img_name}.svg" href="data:image/svg+xml,{urllib.parse.quote(svg_raw)}" target="_blank">Download SVG image</a>
                """.strip()
                )
            )
            display(
                widgets.Image(
                    value=svg_raw.encode("utf-8"),
                    format="svg+xml",
                    width="100%",
                    height="auto",
                )
            )
            plt.clf()
            plt.close()

    def update_hs(
        self,
        histogram_specs: Iterable[
            HLikeT | tuple[str, HLikeT] | tuple[str, HLikeT, HLikeT | None] | None
        ],
    ) -> None:
        r"""
        Triggers an update to the histogram data. See
        [`HPlotterChooser`][dyceum.viz.HPlotterChooser] for a more detailed
        explanation of *histogram_specs*.
        """
        self.hs = _histogram_specs_to_h_tuples(histogram_specs, cutoff=None)
        self._csv_download_link_html = _csv_download_link(self.hs)

        self._plot_widgets.burst_swap.disabled = all(
            h_outer is None or h_inner == h_outer for _, h_inner, h_outer in self.hs
        )

        self._cull_data()
        self._trigger_update()

    def _cull_data(self) -> None:
        self._hs_culled = _histogram_specs_to_h_tuples(self.hs, self._cutoff)

    def _trigger_update(self) -> None:
        self._plot_widgets.rev_no.value += 1

__init__(histogram_specs: Iterable[HLikeT | tuple[str, HLikeT] | tuple[str, HLikeT, HLikeT | None] | None] = (), *, controls_expanded: bool = False, plot_widgets: PlotWidgets | None = None, plotters_or_factories: Iterable[HPlotter | HPlotterFactoryT] = (BurstHPlotter, LineHPlotter, HorizontalBarHPlotter), selected_name: str | None = None) -> None

Constructor.

Source code in dyceum/viz.py
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
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
def __init__(
    self,
    histogram_specs: Iterable[
        HLikeT | tuple[str, HLikeT] | tuple[str, HLikeT, HLikeT | None] | None
    ] = (),
    *,
    controls_expanded: bool = False,
    plot_widgets: PlotWidgets | None = None,
    plotters_or_factories: Iterable[HPlotter | HPlotterFactoryT] = (
        BurstHPlotter,
        LineHPlotter,
        HorizontalBarHPlotter,
    ),
    selected_name: str | None = None,
) -> None:
    r"""Constructor."""
    plotters = tuple(
        plotter if isinstance(plotter, HPlotter) else plotter()
        for plotter in plotters_or_factories
    )

    if not plotters:
        raise ValueError("must provide at least one plotter")

    self._plotters_by_name: Mapping[str, HPlotter] = {
        plotter.NAME: plotter for plotter in plotters
    }

    assert self._plotters_by_name

    if selected_name is None:
        selected_name = _first_of(self._plotters_by_name)

    if selected_name is not None and selected_name not in self._plotters_by_name:
        raise ValueError(
            f"selected_name {selected_name!r} does not match any plotter"
        )

    if len(self._plotters_by_name) < len(plotters):
        duplicate_names = ", ".join(
            repr(plotter_name)
            for plotter_name, count in Counter(
                plotter.NAME for plotter in plotters
            ).items()
            if count > 1
        )
        warnings.warn(
            f"ignoring redundant plotters with duplicate names {duplicate_names}",
            PlotWarning,
            stacklevel=1,
        )

    if plot_widgets is None:
        plot_widgets = PlotWidgets()

    self._plot_widgets = plot_widgets
    self._layouts_by_name: Mapping[str, widgets.Widget] = {}

    for plotter_name, plotter in self._plotters_by_name.items():
        self._layouts_by_name[plotter_name] = plotter.layout(plot_widgets)

    self.hs: tuple[tuple[str, H, H | None], ...] = ()
    self._hs_culled: tuple[tuple[str, H, H | None], ...] = ()
    self._cutoff: float | None = None
    self._csv_download_link_html = ""
    self.update_hs(histogram_specs)
    self._selected_plotter: HPlotter | None
    tab_names = tuple(self._plotters_by_name.keys())

    chooser_tab = widgets.Tab(
        children=tuple(self._layouts_by_name.values()),
        selected_index=(
            0 if selected_name is None else tab_names.index(selected_name)
        ),
    )

    for i, tab_name in enumerate(tab_names):
        chooser_tab.set_title(i, tab_name)

    def _handle_tab(change: _ChangeT) -> None:
        assert change["name"] == "selected_index"
        self._selected_plotter = next(
            islice(self._plotters_by_name.values(), change["new"], None)
        )
        self._trigger_update()

    chooser_tab.observe(_handle_tab, names="selected_index")

    self._selected_plotter = next(
        islice(self._plotters_by_name.values(), chooser_tab.selected_index, None)
    )

    self._out = widgets.VBox(
        [
            widgets.Accordion(
                children=[chooser_tab],
                titles=["Plot Controls"],
                selected_index=0 if controls_expanded else None,
            ),
            # INVARIANT: This registers interactive_output's observers on every
            # control (incl. plot_style) *after* PlotWidgets.__init__ registers
            # _handle_plot_style. See the matching note there. Do not reorder these
            # so that interactive_output observes plot_style before
            # _handle_plot_style.
            widgets.interactive_output(self.plot, self._plot_widgets.asdict()),
        ]
    )

interact() -> None

Displays the container responsible for selecting which plotter is used.

Source code in dyceum/viz.py
1113
1114
1115
1116
1117
def interact(self) -> None:
    r"""
    Displays the container responsible for selecting which plotter is used.
    """
    display(self._out)

plot(**kw) -> None

Callback for updating the visualization in response to configuration or data changes. settings are the current values from all control widgets. (See PlotWidgets.)

Source code in dyceum/viz.py
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
    def plot(
        self,
        **kw,  # ruff: ignore[missing-type-kwargs]
    ) -> None:
        r"""
        Callback for updating the visualization in response to configuration or data
        changes. *settings* are the current values from all control widgets. (See
        [`PlotWidgets`][dyceum.viz.PlotWidgets].)
        """
        if self._plot_widgets.plot_updates_suspended:
            return
        settings = cast("SettingsDict", kw)
        cutoff = (
            self._plot_widgets.cutoff.value
            if self._plot_widgets.enable_cutoff.value
            else None
        )

        if self._cutoff != cutoff:
            self._cutoff = cutoff
            self._cull_data()

        with mstyle.context(settings["plot_style"]):
            if self._selected_plotter is not None:
                self._selected_plotter.plot(self._hs_culled, settings)
                transparent = self._selected_plotter.transparent(
                    requested=settings["burst_color_bg_trnsp"]
                )
            else:
                transparent = False
            buf = io.BytesIO()
            plt.savefig(
                buf,
                bbox_inches="tight",
                facecolor=mcolors.to_rgba(
                    settings["burst_color_bg"], alpha=0.0 if transparent else None
                ),
                format="SVG",
                transparent=transparent,
            )
            img_name = "-".join(label for label, _, _ in self.hs)
            svg_raw = buf.getvalue().decode()
            display(
                HTML(
                    rf"""
{self._csv_download_link_html} |
<a download="{img_name}.svg" href="data:image/svg+xml,{urllib.parse.quote(svg_raw)}" target="_blank">Download SVG image</a>
                """.strip()
                )
            )
            display(
                widgets.Image(
                    value=svg_raw.encode("utf-8"),
                    format="svg+xml",
                    width="100%",
                    height="auto",
                )
            )
            plt.clf()
            plt.close()

update_hs(histogram_specs: Iterable[HLikeT | tuple[str, HLikeT] | tuple[str, HLikeT, HLikeT | None] | None]) -> None

Triggers an update to the histogram data. See HPlotterChooser for a more detailed explanation of histogram_specs.

Source code in dyceum/viz.py
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
def update_hs(
    self,
    histogram_specs: Iterable[
        HLikeT | tuple[str, HLikeT] | tuple[str, HLikeT, HLikeT | None] | None
    ],
) -> None:
    r"""
    Triggers an update to the histogram data. See
    [`HPlotterChooser`][dyceum.viz.HPlotterChooser] for a more detailed
    explanation of *histogram_specs*.
    """
    self.hs = _histogram_specs_to_h_tuples(histogram_specs, cutoff=None)
    self._csv_download_link_html = _csv_download_link(self.hs)

    self._plot_widgets.burst_swap.disabled = all(
        h_outer is None or h_inner == h_outer for _, h_inner, h_outer in self.hs
    )

    self._cull_data()
    self._trigger_update()

HorizontalBarHPlotter

Bases: HPlotter

Experimental

This class should be considered experimental and may change or disappear in future versions.

A plotter for creating one horizontal bar plot per primary histogram. Secondary histograms are ignored.

Source code in dyceum/viz.py
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
class HorizontalBarHPlotter(HPlotter):
    r"""
    !!! warning "Experimental"

        This class should be considered experimental and may change or disappear in
        future versions.

    A plotter for creating one horizontal bar plot per primary histogram. Secondary
    histograms are ignored.
    """

    NAME: str = "Horizontal Bar Plots"

    def layout(self, plot_widgets: PlotWidgets) -> widgets.Widget:
        cutoff_layout_widget = super().layout(plot_widgets)

        return widgets.VBox(
            [
                widgets.HBox(
                    [
                        cutoff_layout_widget,
                        plot_widgets.graph_type,
                        widgets.VBox(
                            [
                                plot_widgets.alpha,
                                plot_widgets.plot_style,
                            ]
                        ),
                    ]
                ),
            ]
        )

    def plot(
        self,
        hs: Sequence[tuple[str, H, H | None]],
        settings: SettingsDict,
    ) -> None:
        total_outcomes = sum(len(h) for _, h, _ in hs)
        total_height = total_outcomes + 1  # one extra to accommodate the axis
        figsize = (
            settings["resolution"],
            total_height * settings["resolution"] / 48,
        )
        plt.figure(figsize=figsize)
        barh_kw: dict[str, Any] = {"alpha": settings["alpha"]}
        plot_style = settings["plot_style"]

        if (
            plot_style in mstyle.library
            and "axes.prop_cycle" in mstyle.library[plot_style]
            and "color" in mstyle.library[plot_style]["axes.prop_cycle"]
        ):
            # Our current style has a cycler with colors, so use it
            cycler = mstyle.library[plot_style]["axes.prop_cycle"]
        else:
            # Revert to the global default
            cycler = mpl.rcParams["axes.prop_cycle"]

        color_iter = cycle(cycler.by_key().get("color", (None,)))
        row_start = 0
        first_ax = ax = None

        for label, h, _ in hs:
            if not h:
                continue

            outcomes, values = values_xy_for_graph_type(h, settings["graph_type"])
            rowspan = len(outcomes)

            if first_ax is None:
                first_ax = ax = plt.subplot2grid(
                    (total_height, 1), (row_start, 0), rowspan=rowspan
                )
            else:
                ax = plt.subplot2grid(
                    (total_height, 1), (row_start, 0), rowspan=rowspan, sharex=first_ax
                )

            ax.set_yticks(outcomes)
            ax.tick_params(labelbottom=False)
            ax.set_ylim((max(outcomes) + 0.5, min(outcomes) - 0.5))
            ax.barh(
                outcomes,
                tuple(float(v) for v in values),
                color=next(color_iter),
                label=label,
                **barh_kw,
            )
            ax.legend(loc="upper right")
            row_start += rowspan

        if ax is not None:
            ax.tick_params(labelbottom=True)
            ax.xaxis.set_major_formatter(mticker.PercentFormatter(xmax=1))

LineHPlotter

Bases: HPlotter

Experimental

This class should be considered experimental and may change or disappear in future versions.

A plotter for creating a single line plot visualizing all primary histograms. Secondary histograms are ignored.

Source code in dyceum/viz.py
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
class LineHPlotter(HPlotter):
    r"""
    !!! warning "Experimental"

        This class should be considered experimental and may change or disappear in
        future versions.

    A plotter for creating a single line plot visualizing all primary histograms.
    Secondary histograms are ignored.
    """

    NAME: str = "Line Plot"

    def layout(self, plot_widgets: PlotWidgets) -> widgets.Widget:
        cutoff_layout_widget = super().layout(plot_widgets)

        return widgets.VBox(
            [
                widgets.HBox(
                    [
                        cutoff_layout_widget,
                        plot_widgets.graph_type,
                        widgets.VBox(
                            [
                                plot_widgets.alpha,
                                plot_widgets.plot_style,
                                plot_widgets.markers,
                            ]
                        ),
                    ]
                ),
            ]
        )

    def plot(
        self,
        hs: Sequence[tuple[str, H, H | None]],
        settings: SettingsDict,
    ) -> None:
        _, ax = plt.subplots(
            figsize=(
                settings["resolution"],
                settings["resolution"] / 16 * 9,
            )
        )

        plot_line(
            *(h for _, h, _ in hs),
            alpha=settings["alpha"],
            ax=ax,
            graph_type=settings["graph_type"],
            labels=[label for label, _, _ in hs],
            markers=settings["markers"],
        )

        with warnings.catch_warnings():
            warnings.simplefilter("ignore")
            ax.legend()

PlotWarning

Bases: UserWarning

Issued when a plotter encounters unusual but non-fatal circumstances.

Source code in dyceum/viz.py
84
85
86
87
class PlotWarning(UserWarning):
    r"""
    Issued when a plotter encounters unusual but non-fatal circumstances.
    """

PlotWidgets

Bases: _PlotWidgetsDataclass

Experimental

This class should be considered experimental and may change or disappear in future versions.

Class to encapsulate interactive plot control widgets. All parameters for the [initializer][dyceum.viz.PlotWidgets.__init__] are optional.

  • initial_alpha is the starting alpha value for graphs (defaults to 0.75).

  • initial_burst_cmap_inner is the initially selected color map for inner burst graphs (defaults to "viridis").

  • initial_burst_cmap_link is the starting value for linking the color maps for inner and outer burst graphs (defaults to True).

  • initial_burst_cmap_outer is the initially selected color map for outer burst graphs (defaults to "viridis").

  • initial_burst_cmap_use_midpoints is the starting value for whether to map midpoints to color maps for burst graphs (defaults to True).

  • initial_burst_color_bg is the initially selected background color for burst graphs (defaults to "white").

  • initial_burst_color_bg_trnsp is the initially selected background transparency color burst graphs (defaults to False).

  • initial_burst_color_text is the initially selected text color for burst graphs (defaults to "black").

  • initial_burst_columns is the initially selected number of columns for displaying burst graphs (defaults to 3).

  • initial_burst_swap is whether the inner and outer burst graphs should be swapped at first (defaults to False).

  • initial_burst_zero_fill_normalize is whether all burst graphs should share a scale at first (i.e., so similar values share similar colors across burst graphs) (defaults to False).

  • initial_enable_cutoff is whether small values should be omitted from graphs at first (defaults to True).

  • initial_graph_type is the type of graph first shown (defaults to "normal".

  • initial_markers are the starting set of markers for line plots (defaults to "oX^v><dP").

  • initial_plot_style is the starting color style for non-burst graphs (defaults to "bmh").

  • initial_resolution is the starting value for the graph resolution (defaults to 12).

Source code in dyceum/viz.py
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
class PlotWidgets(_PlotWidgetsDataclass):
    r"""
    !!! warning "Experimental"

        This class should be considered experimental and may change or disappear in
        future versions.

    Class to encapsulate interactive plot control widgets. All parameters for the
    [initializer][dyceum.viz.PlotWidgets.__init__] are optional.

    - *initial_alpha* is the starting alpha value for graphs (defaults to `#!python
       0.75`).

    - *initial_burst_cmap_inner* is the initially selected color map for inner burst
       graphs (defaults to `"viridis"`).

    - *initial_burst_cmap_link* is the starting value for linking the color maps for
       inner and outer burst graphs (defaults to `True`).

    - *initial_burst_cmap_outer* is the initially selected color map for outer burst
       graphs (defaults to `"viridis"`).

    - *initial_burst_cmap_use_midpoints* is the starting value for whether to map
       midpoints to color maps for burst graphs (defaults to `True`).

    - *initial_burst_color_bg* is the initially selected background color for burst
       graphs (defaults to `"white"`).

    - *initial_burst_color_bg_trnsp* is the initially selected background transparency
       color burst graphs (defaults to `False`).

    - *initial_burst_color_text* is the initially selected text color for burst graphs
       (defaults to `"black"`).

    - *initial_burst_columns* is the initially selected number of columns for displaying
       burst graphs (defaults to `3`).

    - *initial_burst_swap* is whether the inner and outer burst graphs should be swapped
       at first (defaults to `False`).

    - *initial_burst_zero_fill_normalize* is whether all burst graphs should share a
       scale at first (i.e., so similar values share similar colors across burst graphs)
       (defaults to `False`).

    - *initial_enable_cutoff* is whether small values should be omitted from graphs at
       first (defaults to `True`).

    - *initial_graph_type* is the type of graph first shown (defaults to
       `"normal"`.

    - *initial_markers* are the starting set of markers for line plots (defaults to
       `"oX^v><dP"`).

    - *initial_plot_style* is the starting color style for non-burst graphs (defaults to
       `"bmh"`).

    - *initial_resolution* is the starting value for the graph resolution (defaults to
      `12`).
    """

    def __init__(
        self,
        *,
        initial_alpha: float = _DEFAULT_ALPHA,
        initial_burst_cmap_inner: str = _DEFAULT_CMAP,
        initial_burst_cmap_link: bool = True,
        initial_burst_cmap_outer: str = _DEFAULT_COMPARE_CMAP,
        initial_burst_cmap_use_midpoints: bool = True,
        initial_burst_columns: int = _DEFAULT_COLS_BURST,
        initial_burst_swap: bool = False,
        initial_burst_zero_fill_normalize: bool = False,
        initial_burst_color_bg: str = _DEFAULT_BURST_COLOR_BG,
        initial_burst_color_bg_trnsp: bool = False,
        initial_burst_color_text: str = _DEFAULT_BURST_COLOR_TEXT,
        initial_enable_cutoff: bool = True,
        initial_graph_type: GraphType = _DEFAULT_GRAPH_TYPE,
        initial_markers: str = _DEFAULT_MARKERS,
        initial_plot_style: str = _DEFAULT_PLOT_STYLE,
        initial_resolution: int = _DEFAULT_RESOLUTION,
    ) -> None:
        super().__init__()

        if (
            initial_plot_style != _DEFAULT_MPL_STYLE
            and initial_plot_style not in mstyle.available
        ):
            warnings.warn(
                f"unrecognized plot style {initial_plot_style!r}; reverting to {_DEFAULT_MPL_STYLE!r}",
                PlotWarning,
                stacklevel=1,
            )
            initial_plot_style = _DEFAULT_MPL_STYLE

        self.alpha.value = initial_alpha
        self.burst_cmap_inner.value = initial_burst_cmap_inner
        self.burst_cmap_link.value = initial_burst_cmap_link
        self.burst_cmap_outer.disabled = initial_burst_cmap_link
        self.burst_cmap_outer.value = initial_burst_cmap_outer
        self.burst_cmap_use_midpoints.value = initial_burst_cmap_use_midpoints
        self.burst_color_bg.value = initial_burst_color_bg
        self.burst_color_bg_trnsp.value = initial_burst_color_bg_trnsp
        self.burst_color_text.value = initial_burst_color_text
        self.burst_columns.value = initial_burst_columns
        self.burst_swap.value = initial_burst_swap
        self.burst_zero_fill_normalize.disabled = initial_burst_cmap_use_midpoints
        self.burst_zero_fill_normalize.value = initial_burst_zero_fill_normalize
        self.cutoff.disabled = not initial_enable_cutoff
        self.enable_cutoff.value = initial_enable_cutoff
        self.graph_type.value = initial_graph_type
        self.markers.value = initial_markers
        self.plot_style.value = initial_plot_style
        self.resolution.value = initial_resolution
        self._suspend_plot_updates_depth = 0

        def _handle_cutoff(change: _ChangeT) -> None:
            self.cutoff.disabled = not change["new"]

        self.enable_cutoff.observe(_handle_cutoff, names="value")

        def _handle_plot_style(change: _ChangeT) -> None:
            new_style = change["new"]
            with self.suspend_plot_updates():
                self.burst_cmap_outer.value = self.burst_cmap_inner.value = (
                    _get_param_for_style(new_style, "image.cmap")
                )
                burst_color_text = _get_param_for_style(new_style, "text.color")
                try:
                    self.burst_color_text.value = burst_color_text
                except TraitError:
                    self.burst_color_text.value = mcolors.to_hex(burst_color_text)
                burst_color_bg = _get_param_for_style(new_style, "figure.facecolor")
                try:
                    self.burst_color_bg.value = burst_color_bg
                except TraitError:
                    self.burst_color_bg.value = mcolors.to_hex(burst_color_bg)

        # INVARIANT: This observer must be registered on plot_style *before*
        # HPlotterChooser wires interactive_output (which also observes plot_style).
        # traitlets dispatches observers in registration order, so _handle_plot_style
        # runs first (suppressing its cascade), and interactive_output's trailing
        # plot_style notification is then the single redraw, with all cascaded values
        # already applied. If registration order ever inverts, the plot renders with the
        # new style but stale burst_* values, then the cascade updates them with no
        # redraw following, which would present an incorrect view.
        self.plot_style.observe(_handle_plot_style, names="value")

        def _handle_burst_cmap_link(change: _ChangeT) -> None:
            self.burst_cmap_outer.disabled = change["new"]

        self.burst_cmap_link.observe(_handle_burst_cmap_link, names="value")

        def _handle_burst_color_bg_trnsp(change: _ChangeT) -> None:
            self.burst_color_bg.disabled = change["new"]

        self.burst_color_bg_trnsp.observe(_handle_burst_color_bg_trnsp, names="value")

        def _handle_burst_cmap_use_midpoints(change: _ChangeT) -> None:
            self.burst_zero_fill_normalize.disabled = change["new"]

        self.burst_cmap_use_midpoints.observe(
            _handle_burst_cmap_use_midpoints, names="value"
        )

    def asdict(self) -> dict[str, Any]:
        return {field.name: getattr(self, field.name) for field in fields(self)}

    @property
    def plot_updates_suspended(self) -> bool:
        r"""
        Whether plot redraws are currently being suppressed by an active
        [`suspend_plot_updates`][dyceum.viz.PlotWidgets.suspend_plot_updates] block.
        """
        return self._suspend_plot_updates_depth > 0

    @contextmanager
    def suspend_plot_updates(self) -> Generator[None]:
        r"""
        Nesting-safe context manager to allow suppression of plot redraws for the
        duration of the block.

        This ***only*** manages a flag readable via
        [`plot_updates_suspended`][dyceum.viz.PlotWidgets.plot_updates_suspended]. No
        suppression or redraw logic is contained here.
        """
        self._suspend_plot_updates_depth += 1
        try:
            yield
        finally:
            self._suspend_plot_updates_depth -= 1

plot_updates_suspended: bool property

Whether plot redraws are currently being suppressed by an active suspend_plot_updates block.

suspend_plot_updates() -> Generator[None]

Nesting-safe context manager to allow suppression of plot redraws for the duration of the block.

This only manages a flag readable via plot_updates_suspended. No suppression or redraw logic is contained here.

Source code in dyceum/viz.py
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
@contextmanager
def suspend_plot_updates(self) -> Generator[None]:
    r"""
    Nesting-safe context manager to allow suppression of plot redraws for the
    duration of the block.

    This ***only*** manages a flag readable via
    [`plot_updates_suspended`][dyceum.viz.PlotWidgets.plot_updates_suspended]. No
    suppression or redraw logic is contained here.
    """
    self._suspend_plot_updates_depth += 1
    try:
        yield
    finally:
        self._suspend_plot_updates_depth -= 1

jupyter_visualize(histogram_specs: Iterable[HLikeT | tuple[str, HLikeT] | tuple[str, HLikeT, HLikeT | None] | None], *, controls_expanded: bool = False, initial_alpha: float = _DEFAULT_ALPHA, initial_burst_cmap_inner: str = _DEFAULT_CMAP, initial_burst_cmap_link: bool = True, initial_burst_cmap_outer: str = _DEFAULT_COMPARE_CMAP, initial_burst_cmap_use_midpoints: bool = True, initial_burst_color_bg: str = _DEFAULT_BURST_COLOR_BG, initial_burst_color_bg_trnsp: bool = False, initial_burst_color_text: str = _DEFAULT_BURST_COLOR_TEXT, initial_burst_columns: int = _DEFAULT_COLS_BURST, initial_burst_swap: bool = False, initial_burst_zero_fill_normalize: bool = False, initial_enable_cutoff: bool = True, initial_graph_type: GraphType = _DEFAULT_GRAPH_TYPE, initial_markers: str = _DEFAULT_MARKERS, initial_plot_style: str = _DEFAULT_PLOT_STYLE, initial_resolution: int = _DEFAULT_RESOLUTION, selected_name: str | None = None) -> None

Experimental

dyceum.viz.jupyter_visualize is experimental; its interface may change or it may be removed in a future release.

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, but with some extra goodies.

The “Powered by the Apocalypse (PbtA)” example in the introduction notebook should give an idea of the effect. (See Interactive quick start.)

Parameters have the same meanings as with HPlotterChooser and PlotWidgets.

Source code in dyceum/viz.py
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
@experimental
def jupyter_visualize(
    histogram_specs: Iterable[
        HLikeT | tuple[str, HLikeT] | tuple[str, HLikeT, HLikeT | None] | None
    ],
    *,
    controls_expanded: bool = False,
    initial_alpha: float = _DEFAULT_ALPHA,
    initial_burst_cmap_inner: str = _DEFAULT_CMAP,
    initial_burst_cmap_link: bool = True,
    initial_burst_cmap_outer: str = _DEFAULT_COMPARE_CMAP,
    initial_burst_cmap_use_midpoints: bool = True,
    initial_burst_color_bg: str = _DEFAULT_BURST_COLOR_BG,
    initial_burst_color_bg_trnsp: bool = False,
    initial_burst_color_text: str = _DEFAULT_BURST_COLOR_TEXT,
    initial_burst_columns: int = _DEFAULT_COLS_BURST,
    initial_burst_swap: bool = False,
    initial_burst_zero_fill_normalize: bool = False,
    initial_enable_cutoff: bool = True,
    initial_graph_type: GraphType = _DEFAULT_GRAPH_TYPE,
    initial_markers: str = _DEFAULT_MARKERS,
    initial_plot_style: str = _DEFAULT_PLOT_STYLE,
    initial_resolution: int = _DEFAULT_RESOLUTION,
    selected_name: str | None = None,
) -> None:
    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.

    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).)

    Parameters have the same meanings as with
    [`HPlotterChooser`][dyceum.viz.HPlotterChooser] and
    [`PlotWidgets`][dyceum.viz.PlotWidgets].
    """
    plotter_chooser = HPlotterChooser(
        histogram_specs,
        controls_expanded=controls_expanded,
        plot_widgets=PlotWidgets(
            initial_alpha=initial_alpha,
            initial_burst_cmap_inner=initial_burst_cmap_inner,
            initial_burst_cmap_link=initial_burst_cmap_link,
            initial_burst_cmap_outer=initial_burst_cmap_outer,
            initial_burst_cmap_use_midpoints=initial_burst_cmap_use_midpoints,
            initial_burst_color_bg=initial_burst_color_bg,
            initial_burst_color_bg_trnsp=initial_burst_color_bg_trnsp,
            initial_burst_color_text=initial_burst_color_text,
            initial_burst_columns=initial_burst_columns,
            initial_burst_swap=initial_burst_swap,
            initial_burst_zero_fill_normalize=initial_burst_zero_fill_normalize,
            initial_enable_cutoff=initial_enable_cutoff,
            initial_graph_type=initial_graph_type,
            initial_markers=initial_markers,
            initial_plot_style=initial_plot_style,
            initial_resolution=initial_resolution,
        ),
        selected_name=selected_name,
    )

    plotter_chooser.interact()

limit_for_display(h: H[_T], cutoff: Fraction) -> H

Experimental

dyceum.viz.limit_for_display is experimental; its interface may change or it may be removed in a future release.

Experimental

This function should be considered experimental and may change or disappear in future versions.

Discards outcomes in h, starting with the smallest counts as long as the total discarded in proportion to h.total does not exceed cutoff. This can be useful in speeding up plots where there are large number of negligible probabilities.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> from dyceum.viz import limit_for_display
>>> from dyce import H
>>> from fractions import Fraction
>>> h = H({1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6})
>>> h.total
21
>>> limit_for_display(h, cutoff=Fraction(5, 21))
H({3: 3, 4: 4, 5: 5, 6: 6})
>>> limit_for_display(h, cutoff=Fraction(6, 21))
H({4: 4, 5: 5, 6: 6})
Source code in dyceum/viz.py
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
@experimental
def limit_for_display(h: H[_T], cutoff: Fraction) -> H:
    r"""
    !!! warning "Experimental"

        This function should be considered experimental and may change or disappear in
        future versions.

    Discards outcomes in *h*, starting with the smallest counts as long as the total
    discarded in proportion to `h.total` does not exceed *cutoff*. This can
    be useful in speeding up plots where there are large number of negligible
    probabilities.

        >>> from dyceum.viz import limit_for_display
        >>> from dyce import H
        >>> from fractions import Fraction
        >>> h = H({1: 1, 2: 2, 3: 3, 4: 4, 5: 5, 6: 6})
        >>> h.total
        21
        >>> limit_for_display(h, cutoff=Fraction(5, 21))
        H({3: 3, 4: 4, 5: 5, 6: 6})
        >>> limit_for_display(h, cutoff=Fraction(6, 21))
        H({4: 4, 5: 5, 6: 6})
    """
    if cutoff < 0 or cutoff > 1:
        raise ValueError(f"cutoff ({cutoff}) must be between zero and one, inclusive")

    cutoff_count = int(cutoff * h.total)

    if cutoff_count == 0:
        return h

    def _cull() -> Iterator[tuple[_T, int]]:
        so_far = 0

        for outcome, count in sorted(h.items(), key=itemgetter(1)):
            so_far += count

            if so_far > cutoff_count:
                yield outcome, count

    return H(dict(_cull()))

values_xy_for_graph_type(h: H[_T], graph_type: GraphType) -> tuple[tuple[_T, ...], tuple[Fraction, ...]]

Experimental

dyceum.viz.values_xy_for_graph_type is experimental; its interface may change or it may be removed in a future release.

Source code in dyceum/viz.py
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
@experimental
def values_xy_for_graph_type(
    h: H[_T],
    graph_type: GraphType,
) -> tuple[tuple[_T, ...], tuple[Fraction, ...]]:
    outcomes, probabilities = (
        zip(*h.probability_items(), strict=True) if h else ((), ())
    )

    if graph_type == "at_least":
        probabilities = tuple(
            accumulate(
                probabilities,
                __sub__,
                initial=Fraction(1),
            )
        )[:-1]
    elif graph_type == "at_most":
        probabilities = tuple(
            accumulate(
                probabilities,
                __add__,
                initial=Fraction(0),
            )
        )[1:]
    elif graph_type == "normal":
        pass
    else:
        assert False, f"unrecognized graph type {graph_type}"  # ruff: ignore[assert-false, pytest-assert-always-false]

    return outcomes, probabilities