Skip to content

Notebook Views

SurveyView shows one gene of a survey in a notebook: the chart with its elites, the trace of a niche, and the tree of a niche. It works in Jupyter, JupyterLab, VS Code and marimo. These are the same views as on the page Try It in Your Browser.

pip install 'hifuku[notebook]'

A live run

Show the view in one cell. In the next cell, give it as the monitor of a run. The chart fills while the second cell runs.

from hifuku.widgets import SurveyView

view = SurveyView(run, gene="geneB", chart=0)      # run is a SurveyRun
view
run.execute(task, monitor=view)

The view shows only the tasks of its gene and chart, so one monitor can watch a loop over all the tasks of a run. A new task of the gene starts the view again.

A stored survey

view = SurveyView(survey, gene="geneB", chart=0)   # survey is a Survey
view

When the survey holds more than one chain of records for the gene, for example replicate runs, name one with run=, a run id or label.

What the views show

  • Hover over a niche to see the trace of its best log-likelihood and the tree of its elite. A live run adds a trace point when the niche is new or its log-likelihood changes, and a point at the last checkpoint. A stored survey has a point for each segment of the chain of records of the gene. A survey that ran in one segment has one point for each niche.
  • Before any niche is hovered, the trace of a stored survey shows the best log-likelihood of the survey at each checkpoint.
  • Click a niche to keep it: the trace and the tree follow it until you click it again, click where there is no niche, or press Escape with the chart in focus. During a live run, a tree can be read after the run ends.

The view sends the page only what changes. It sets the full trace rows and trees on its widgets at the last checkpoint of a run and when it is displayed. After a run that stops early, for example at an interrupt, call view.sync() so that a new display of the widgets is complete.

view.chart, view.trace and view.tree are the widgets themselves, so that you can put them in a layout of your own. The widgets of one view share hover and select events in the page, so a hover gets an answer while the kernel is busy.

The widgets are in widgets/ at the root of the repository, and they know nothing of surveys. hifuku.widgets.generic holds their Python classes.

SurveyView

The chart, the trace and the tree of one gene on one chart.

source is a :class:~hifuku.survey_io.SurveyRun for a live run, or a :class:~hifuku.survey_io.Survey for a stored one. For a live run, show the view in one cell and give it as the monitor in the next::

view = SurveyView(run, gene="geneB")
view

run.execute(task, monitor=view)

The view shows only the tasks of its gene and chart. A new task of the gene starts the view again.

A hover on the chart shows the niche's trace, and a click shows its tree. A live run adds a trace point when a niche is new or its log-likelihood changes, and a point at the last checkpoint. A stored survey has a trace point for each segment of its chain of records, and the survey-level rows of its history at each checkpoint. When the survey holds more than one chain for the gene (replicate runs), run names the run id or the label of the run whose chain to show.

Source code in src/hifuku/widgets/survey_view.py
class SurveyView:
    """The chart, the trace and the tree of one gene on one chart.

    ``source`` is a :class:`~hifuku.survey_io.SurveyRun` for a live run, or
    a :class:`~hifuku.survey_io.Survey` for a stored one.  For a live run,
    show the view in one cell and give it as the monitor in the next::

        view = SurveyView(run, gene="geneB")
        view

        run.execute(task, monitor=view)

    The view shows only the tasks of its gene and chart.  A new task of the
    gene starts the view again.

    A hover on the chart shows the niche's trace, and a click shows its
    tree.  A live run adds a trace point when a niche is new or its
    log-likelihood changes, and a point at the last checkpoint.  A stored
    survey has a trace point for each segment of its chain of records, and
    the survey-level rows of its history at each checkpoint.  When the
    survey holds more than one chain for the gene (replicate runs), ``run``
    names the run id or the label of the run whose chain to show.
    """

    def __init__(self, source, gene, chart=0, *, run=None, group=None):
        self.source, self.gene, self.chart_index, self.run = source, gene, chart, run
        # The page of a JupyterLab window holds the outputs of every notebook
        # in it, and the channels are global to the page, so a group name must
        # not repeat across kernels.
        group = group or f"hifuku-survey-{uuid.uuid4().hex}"
        framework_chart = source.framework.charts[chart]
        tri = framework_chart.triangle
        self._vertices = [[float(v) for v in np.asarray(p).ravel()[:2]]
                          for p in (tri.P1, tri.P2, tri.P3)]
        self._labels = [str(a) for a in framework_chart.anchors]
        self.chart = Simplex(geometry={}, group=group)
        self.trace = Trace(group=group, labels={"x": "variations", "y": "log-likelihood"},
                           empty="Hover over a niche to see how its best log-likelihood rose.")
        self.tree = Tree(group=group)
        self.tree.observe(self._answer, names="requested")
        self._task = _NO_TASK
        self._last = {}
        # The triangle and its labels show before the first checkpoint; the
        # grid (origin and cell side) comes with it.
        self._set_geometry(0.0, None)
        self._stored = hasattr(source, "records")
        if self._stored:
            self._replay()

    def _set_geometry(self, origin, cell) -> None:
        """Set the chart's geometry.  A cell side of None draws the triangle
        with no grid."""
        self.chart.geometry = {"vertices": self._vertices, "origin": float(origin),
                               "cell": None if cell is None else float(cell),
                               "labels": self._labels}

    def _start(self, task, grid) -> None:
        """Start the view again for a new task of its gene."""
        self._task = task
        self._last = {}
        self._set_geometry(*grid)
        self.trace.clear()
        self.tree.clear()
        self.tree.requested = None

    def __call__(self, iters, elite_ij, elite_logL, grid, final, task=None):
        """Show one checkpoint of a live run.  This is the monitor."""
        if task is not None and (task.chart, task.gene) != (self.chart_index, self.gene):
            return
        if self._task is _NO_TASK or (task is not None and task is not self._task):
            self._start(task, grid)
        self.chart.set_cells(elite_ij, elite_logL)
        points = []
        for (i, j), v in zip(elite_ij, elite_logL):
            key, v = _key(i, j), float(v)
            if self._last.get(key) != v:
                points.append((key, int(iters), v))
                self._last[key] = v
        if points:
            self.trace.extend(points)
        if final:
            self.trace.add([(key, int(iters), v) for key, v in self._last.items()
                            if self.trace.last_x(key) != int(iters)])
            self.sync()

    def sync(self) -> None:
        """Set the trace rows and the trees that the view keeps on its
        widgets, so that a display of the widgets holds all of them.

        The view does this at the last checkpoint of a run and when it is
        displayed.  Call it after a run that stopped before its last
        checkpoint, for example after an interrupt.
        """
        self.trace.sync()
        self.tree.sync()

    def _archive(self):
        """The archive that answers a tree request, or None before a live
        run ends."""
        if self._stored:
            return self._chain()[-1].archive
        record = self.source.record(self.chart_index, self.gene)
        return None if record is None else record.archive

    def _answer(self, change) -> None:
        key = change["new"]
        if key is None:
            return
        try:
            i, j = (int(x) for x in key.split(","))
            archive = self._archive()
            if archive is None:
                self.tree.add(key, "", caption=f"The tree of niche ({i}, {j}) can be read "
                                               "after the run ends.")
            elif (elite := archive.elites.get((i, j))) is None:
                self.tree.add(key, "", caption=f"Niche ({i}, {j}) has no elite.")
            else:
                self.tree.add(key, archive.newick_at((i, j)),
                              caption=f"The elite of niche ({i}, {j}), "
                                      f"log-likelihood {elite.logL:.2f}.")
        except Exception as error:      # an observer's exception is not shown
            self.tree.add(key, "", caption=f"The tree could not be read: {error}")
        finally:
            # A cleared request lets the page ask for the same key again.
            self.tree.requested = None

    def _chain(self) -> list:
        """The records of this gene and chart, from the first segment on."""
        by_run, label_of = {}, {}
        for run, rec in self.source.records():
            if rec.gene == self.gene and rec.chart == self.chart_index:
                by_run[run.run_id] = rec
                label_of[run.run_id] = getattr(run, "label", "") or run.run_id
        if not by_run:
            raise KeyError(f"no survey of {self.gene!r} on chart {self.chart_index}")
        if self.run is not None:
            ends = [rid for rid in by_run if self.run in (rid, label_of[rid])]
            if not ends:
                raise KeyError(f"no run {self.run!r} surveyed {self.gene!r} on chart "
                               f"{self.chart_index}; the runs are "
                               f"{sorted(label_of.values())}")
        else:
            parents = {rec.parent for rec in by_run.values()}
            ends = [rid for rid in by_run if rid not in parents]
            if len(ends) != 1:
                raise ValueError(f"{len(ends)} chains of records end in the survey of "
                                 f"{self.gene!r} on chart {self.chart_index}, at the runs "
                                 f"{sorted(label_of[rid] for rid in ends)}; name one with run=")
        chain, rid = [], ends[0]
        while rid in by_run:
            chain.append(by_run[rid])
            rid = by_run[rid].parent
            if rid == AB_INITIO:
                break
        return chain[::-1]

    def _replay(self) -> None:
        chain = self._chain()
        last = chain[-1]
        self._set_geometry(last.archive.origin, last.archive.cell)
        cells = list(last.archive.elites.items())
        self.chart.set_cells(np.array([k for k, _ in cells], dtype=np.int64).reshape(-1, 2),
                             np.array([e.logL for _, e in cells], dtype=np.float64))
        for rec in chain:
            if len(rec.history) == 0:       # a record with no checkpoint
                continue
            x = int(rec.history[-1, 0])
            self.trace.add([(_key(*k), x, float(e.logL)) for k, e in rec.archive.elites.items()])
        for name, column in _HISTORY_ROWS.items():
            self.trace.set_row(name, last.history[:, 0].astype(int).tolist(),
                               last.history[:, column].astype(float).tolist(), title=name)
        self.trace.sync()
        self.trace.fallback = "best log-likelihood"

    def display(self):
        """Return the three widgets, laid out as the browser page lays them
        out: the chart on the left, and the trace above the tree on the
        right.  The widgets hold every trace point and tree that the view
        keeps, so a view displayed again during a run is complete."""
        self.sync()
        try:
            import marimo as mo
            in_marimo = mo.running_in_notebook()
        except ImportError:
            in_marimo = False
        if in_marimo:
            return mo.hstack([mo.ui.anywidget(self.chart),
                              mo.vstack([mo.ui.anywidget(self.trace),
                                         mo.ui.anywidget(self.tree)])],
                             widths=[3, 2])
        import ipywidgets
        box = ipywidgets.HBox([self.chart, ipywidgets.VBox([self.trace, self.tree])])
        box.add_class("hifuku-survey-view")
        return box

    def _display_(self):
        """marimo shows the view as the last expression of a cell."""
        return self.display()

    def _ipython_display_(self):
        """Jupyter shows the view as the last expression of a cell."""
        from IPython.display import display
        display(self.display())

sync

sync() -> None

Set the trace rows and the trees that the view keeps on its widgets, so that a display of the widgets holds all of them.

The view does this at the last checkpoint of a run and when it is displayed. Call it after a run that stopped before its last checkpoint, for example after an interrupt.

Source code in src/hifuku/widgets/survey_view.py
def sync(self) -> None:
    """Set the trace rows and the trees that the view keeps on its
    widgets, so that a display of the widgets holds all of them.

    The view does this at the last checkpoint of a run and when it is
    displayed.  Call it after a run that stopped before its last
    checkpoint, for example after an interrupt.
    """
    self.trace.sync()
    self.tree.sync()

display

display()

Return the three widgets, laid out as the browser page lays them out: the chart on the left, and the trace above the tree on the right. The widgets hold every trace point and tree that the view keeps, so a view displayed again during a run is complete.

Source code in src/hifuku/widgets/survey_view.py
def display(self):
    """Return the three widgets, laid out as the browser page lays them
    out: the chart on the left, and the trace above the tree on the
    right.  The widgets hold every trace point and tree that the view
    keeps, so a view displayed again during a run is complete."""
    self.sync()
    try:
        import marimo as mo
        in_marimo = mo.running_in_notebook()
    except ImportError:
        in_marimo = False
    if in_marimo:
        return mo.hstack([mo.ui.anywidget(self.chart),
                          mo.vstack([mo.ui.anywidget(self.trace),
                                     mo.ui.anywidget(self.tree)])],
                         widths=[3, 2])
    import ipywidgets
    box = ipywidgets.HBox([self.chart, ipywidgets.VBox([self.trace, self.tree])])
    box.add_class("hifuku-survey-view")
    return box

Simplex

Bases: AnyWidget

Values on a triangular grid in barycentric coordinates.

geometry holds the three vertices, the grid origin, the cell side and a label for each vertex. The key of cell (i, j) is the string "i,j". selected is the key of the cell that the user clicked last.

Source code in src/hifuku/widgets/generic.py
class Simplex(anywidget.AnyWidget):
    """Values on a triangular grid in barycentric coordinates.

    ``geometry`` holds the three vertices, the grid origin, the cell side
    and a label for each vertex.  The key of cell ``(i, j)`` is the string
    ``"i,j"``.  ``selected`` is the key of the cell that the user clicked
    last.
    """

    _esm = module_source("simplex")
    geometry = traitlets.Dict().tag(sync=True)
    cells = traitlets.Bytes(b"").tag(sync=True)
    values = traitlets.Bytes(b"").tag(sync=True)
    selected = traitlets.Unicode(None, allow_none=True).tag(sync=True)
    group = traitlets.Unicode("").tag(sync=True)

    def set_cells(self, ij, values) -> None:
        """Show ``values`` in the cells ``ij``.

        ``ij`` is an integer array of shape ``(n, 2)``, and ``values`` has
        one value for each cell.  A NaN value is not drawn.
        """
        ij = np.asarray(ij, dtype="<i4").reshape(-1, 2)
        values = np.asarray(values, dtype="<f4").ravel()
        if len(ij) != len(values):
            raise ValueError(f"{len(ij)} cells and {len(values)} values")
        with self.hold_sync():
            self.cells = ij.tobytes()
            self.values = values.tobytes()

set_cells

set_cells(ij, values) -> None

Show values in the cells ij.

ij is an integer array of shape (n, 2), and values has one value for each cell. A NaN value is not drawn.

Source code in src/hifuku/widgets/generic.py
def set_cells(self, ij, values) -> None:
    """Show ``values`` in the cells ``ij``.

    ``ij`` is an integer array of shape ``(n, 2)``, and ``values`` has
    one value for each cell.  A NaN value is not drawn.
    """
    ij = np.asarray(ij, dtype="<i4").reshape(-1, 2)
    values = np.asarray(values, dtype="<f4").ravel()
    if len(ij) != len(values):
        raise ValueError(f"{len(ij)} cells and {len(values)} values")
    with self.hold_sync():
        self.cells = ij.tobytes()
        self.values = values.tobytes()

Trace

Bases: AnyWidget

A line plot of the row of the hovered key.

series maps a key to a row {"x": [...], "y": [...]} with an optional "title". fallback is the key of the row to show when the hovered key has no row.

Source code in src/hifuku/widgets/generic.py
class Trace(anywidget.AnyWidget):
    """A line plot of the row of the hovered key.

    ``series`` maps a key to a row ``{"x": [...], "y": [...]}`` with an
    optional ``"title"``.  ``fallback`` is the key of the row to show when
    the hovered key has no row.
    """

    _esm = module_source("trace")
    _css = module_css("trace")
    series = traitlets.Dict().tag(sync=True)
    fallback = traitlets.Unicode(None, allow_none=True).tag(sync=True)
    labels = traitlets.Dict({"x": "", "y": ""}).tag(sync=True)
    empty = traitlets.Unicode("").tag(sync=True)
    #: A smaller plot, with one line of text in place of the title.
    compact = traitlets.Bool(False).tag(sync=True)
    group = traitlets.Unicode("").tag(sync=True)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._rows = {}

    def add(self, points) -> list:
        """Add each ``(key, x, y)`` point to the row of its key, and return
        the points as lists.  Nothing goes to the page until :meth:`sync`."""
        points = [[str(k), x, y] for k, x, y in points]
        for key, x, y in points:
            row = self._rows.setdefault(key, {"x": [], "y": []})
            row["x"].append(x)
            row["y"].append(y)
        return points

    def extend(self, points) -> None:
        """Add each ``(key, x, y)`` point to the row of its key, and send
        the points to the page.

        The page adds the points to the rows that it shows.  ``series`` does
        not change until :meth:`sync`, so the rows are not all sent again.
        """
        self.send({"kind": "extend", "points": self.add(points)})

    def last_x(self, key):
        """Return the last x of the row of ``key``, or None."""
        row = self._rows.get(str(key))
        return row["x"][-1] if row and row["x"] else None

    def clear(self) -> None:
        """Remove every row, here and on the page."""
        self._rows = {}
        self.series = {}

    def set_row(self, key, x, y, title="") -> None:
        """Replace the row of ``key``.  :meth:`sync` sends it."""
        row = {"x": list(x), "y": list(y)}
        if title:
            row["title"] = title
        self._rows[str(key)] = row

    def sync(self) -> None:
        """Set ``series`` from the rows that this widget keeps, so that a new
        display of the widget shows all of them."""
        self.series = {k: dict(v, x=list(v["x"]), y=list(v["y"]))
                       for k, v in self._rows.items()}

add

add(points) -> list

Add each (key, x, y) point to the row of its key, and return the points as lists. Nothing goes to the page until :meth:sync.

Source code in src/hifuku/widgets/generic.py
def add(self, points) -> list:
    """Add each ``(key, x, y)`` point to the row of its key, and return
    the points as lists.  Nothing goes to the page until :meth:`sync`."""
    points = [[str(k), x, y] for k, x, y in points]
    for key, x, y in points:
        row = self._rows.setdefault(key, {"x": [], "y": []})
        row["x"].append(x)
        row["y"].append(y)
    return points

extend

extend(points) -> None

Add each (key, x, y) point to the row of its key, and send the points to the page.

The page adds the points to the rows that it shows. series does not change until :meth:sync, so the rows are not all sent again.

Source code in src/hifuku/widgets/generic.py
def extend(self, points) -> None:
    """Add each ``(key, x, y)`` point to the row of its key, and send
    the points to the page.

    The page adds the points to the rows that it shows.  ``series`` does
    not change until :meth:`sync`, so the rows are not all sent again.
    """
    self.send({"kind": "extend", "points": self.add(points)})

last_x

last_x(key)

Return the last x of the row of key, or None.

Source code in src/hifuku/widgets/generic.py
def last_x(self, key):
    """Return the last x of the row of ``key``, or None."""
    row = self._rows.get(str(key))
    return row["x"][-1] if row and row["x"] else None

clear

clear() -> None

Remove every row, here and on the page.

Source code in src/hifuku/widgets/generic.py
def clear(self) -> None:
    """Remove every row, here and on the page."""
    self._rows = {}
    self.series = {}

set_row

set_row(key, x, y, title='') -> None

Replace the row of key. :meth:sync sends it.

Source code in src/hifuku/widgets/generic.py
def set_row(self, key, x, y, title="") -> None:
    """Replace the row of ``key``.  :meth:`sync` sends it."""
    row = {"x": list(x), "y": list(y)}
    if title:
        row["title"] = title
    self._rows[str(key)] = row

sync

sync() -> None

Set series from the rows that this widget keeps, so that a new display of the widget shows all of them.

Source code in src/hifuku/widgets/generic.py
def sync(self) -> None:
    """Set ``series`` from the rows that this widget keeps, so that a new
    display of the widget shows all of them."""
    self.series = {k: dict(v, x=list(v["x"]), y=list(v["y"]))
                   for k, v in self._rows.items()}

Tree

Bases: AnyWidget

An unrooted tree, from Newick, for the selected key.

When the page has no tree for the selected key, it sets requested to the key. The code that feeds the widget then calls :meth:add.

Source code in src/hifuku/widgets/generic.py
class Tree(anywidget.AnyWidget):
    """An unrooted tree, from Newick, for the selected key.

    When the page has no tree for the selected key, it sets ``requested``
    to the key.  The code that feeds the widget then calls :meth:`add`.
    """

    _esm = module_source("tree")
    trees = traitlets.Dict().tag(sync=True)
    requested = traitlets.Unicode(None, allow_none=True).tag(sync=True)
    #: Show the leaf labels.
    labels = traitlets.Bool(True).tag(sync=True)
    group = traitlets.Unicode("").tag(sync=True)

    def __init__(self, **kwargs):
        super().__init__(**kwargs)
        self._trees = {}

    def add(self, key, newick, caption="") -> None:
        """Send the page the tree of ``key``, with a caption, and keep it.

        Only this tree goes to the page.  ``trees`` does not change until
        :meth:`sync`, so the other trees are not sent again.
        """
        entry = {"newick": newick, "caption": caption}
        self._trees[str(key)] = entry
        self.send({"kind": "tree", "key": str(key), "entry": entry})

    def entry(self, key):
        """Return the tree entry of ``key`` that this widget keeps, or None."""
        return self._trees.get(str(key))

    def sync(self) -> None:
        """Set ``trees`` from the trees that this widget keeps, so that a new
        display of the widget has all of them."""
        self.trees = dict(self._trees)

    def clear(self) -> None:
        """Remove every tree, here and on the page."""
        self._trees = {}
        self.trees = {}

add

add(key, newick, caption='') -> None

Send the page the tree of key, with a caption, and keep it.

Only this tree goes to the page. trees does not change until :meth:sync, so the other trees are not sent again.

Source code in src/hifuku/widgets/generic.py
def add(self, key, newick, caption="") -> None:
    """Send the page the tree of ``key``, with a caption, and keep it.

    Only this tree goes to the page.  ``trees`` does not change until
    :meth:`sync`, so the other trees are not sent again.
    """
    entry = {"newick": newick, "caption": caption}
    self._trees[str(key)] = entry
    self.send({"kind": "tree", "key": str(key), "entry": entry})

entry

entry(key)

Return the tree entry of key that this widget keeps, or None.

Source code in src/hifuku/widgets/generic.py
def entry(self, key):
    """Return the tree entry of ``key`` that this widget keeps, or None."""
    return self._trees.get(str(key))

sync

sync() -> None

Set trees from the trees that this widget keeps, so that a new display of the widget has all of them.

Source code in src/hifuku/widgets/generic.py
def sync(self) -> None:
    """Set ``trees`` from the trees that this widget keeps, so that a new
    display of the widget has all of them."""
    self.trees = dict(self._trees)

clear

clear() -> None

Remove every tree, here and on the page.

Source code in src/hifuku/widgets/generic.py
def clear(self) -> None:
    """Remove every tree, here and on the page."""
    self._trees = {}
    self.trees = {}