Linked views¶

An alignment, a distance matrix and a tree that follow each other, and Python code that reacts to what you do in them. This builds on the tour, which introduces the widgets.

Every piece of interactive state is an ordinary traitlet you can read, write and observe from the kernel. In the exported HTML version of this notebook the widgets and the links between them work, but anything that runs Python (the printed output and the edits in sections 3 to 5) needs a live kernel.

Install

pip install react-bio-viz nj_py
In [1]:
from ipywidgets import Output, jsdlink, jslink
from nj_py import distance_matrix, nj

from react_bio_viz import MSA, DistanceMatrix, PhyloTree, parse_newick, read_fasta

1. Three views of one dataset¶

A stable id per row lets a renamed row keep its identity: selections and row order use it.

In [2]:
records = [{**r, "id": r["identifier"]} for r in read_fasta("data/aux_iaa.fasta")]

msa = MSA(msa=records, width=820, height=480, options={"tracks": ["conservation", "logo"]})
msa
Out[2]:
In [3]:
distances = distance_matrix(records, substitution_model="Lg")

matrix = DistanceMatrix(labels=distances["names"], matrix=distances["matrix"], width=820, height=520,
                        options={"showNumbers": False, "cellWidth": 20, "cellHeight": 20})
matrix
Out[3]:
In [4]:
tree = parse_newick(nj(records, substitution_model="Lg")["newick"])

phylo = PhyloTree(tree=tree, width=820, height=480, leaf_spacing=18, interactive=True)
phylo
Out[4]:

2. Link them¶

The alignment and the matrix take the same row_order, ids in display order, so linking the two traits keeps them in step. A tree's leaf_order reports its leaves in display order, which is a valid row order too, so the rows can follow the tree, as in a phylogenetic MSA viewer.

In [5]:
row_link = jslink((msa, "row_order"), (matrix, "row_order"))      # both ways
tree_link = jsdlink((phylo, "leaf_order"), (msa, "row_order"))    # rows follow the tree

Drag a label in the alignment or matrix, or a node in the tree.

jslink and jsdlink run in the browser, so they also work in exported HTML. traitlets.link and traitlets.dlink do the same in the kernel: use those when Python code should take part, for example to transform the value on the way.

3. Read, observe and drive state¶

What you do in a widget lands in its traits, such as viewport, selection and row_order, so the kernel can read it at any time…

In [6]:
msa.selection
Out[6]:
{'rows': [], 'columns': []}

…react to it as it happens (callbacks print into an Output widget, since they run outside any cell)…

In [7]:
log = Output()

@log.capture(clear_output=True)
def show_selection(change):
    selected = change["new"]
    print(f"{len(selected['columns'])} columns, {len(selected['rows'])} rows selected")

msa.observe(show_selection, names="selection")
log
Out[7]:

…and drive it. Writing a trait updates the widget above, so in exported HTML it shows the result of this cell:

In [8]:
msa.viewport = {**msa.viewport, "x0": 100, "x1": 160}           # jump to columns 101–160
msa.options = {**msa.options, "colorStyle": "AA Zappo"}          # a different colour scheme
msa.selection = {"rows": [], "columns": list(range(120, 130))}  # select ten columns

The tree's arrangement is state too: root placement, collapsed clades and child order. Collapse a clade in the tree and read it back, or reset it:

In [9]:
phylo.selection
Out[9]:
{'collapsed': []}
In [10]:
phylo.selection = {"collapsed": []}  # back to the tree as computed

4. Respond to clicks¶

Clicks arrive through callbacks with everything about the node: its leaves, all descendant ids, and a ready-made selection to reroot on it. Click a node in the tree:

In [11]:
clicks = Output()

@clicks.capture(clear_output=True)
def on_node(node):
    kind = "leaf" if node["isLeaf"] else f"clade of {len(node['leafNames'])}"
    print(f"{node['id']}: {kind} — {', '.join(node['leafNames'][:5])}{' …' if len(node['leafNames']) > 5 else ''}")

phylo.on_node_click(on_node)
clicks
Out[11]:

5. Edit the alignment¶

The widget never changes its data itself: renames and removals are reported through callbacks, and you apply them. Here each edit is applied to msa.msa, as new records rather than changes to the old ones, because traitlets only syncs a value that compares different. Double-click a label to rename it, hover a label for its ×, or select columns and press Delete.

In [12]:
def rename(row_id, name):
    msa.msa = [{**r, "identifier": name} if r["id"] == row_id else r for r in msa.msa]

def remove_rows(row_ids):
    msa.msa = [r for r in msa.msa if r["id"] not in row_ids]

def remove_columns(columns):
    drop = set(columns)
    msa.msa = [{**r, "sequence": "".join(c for i, c in enumerate(r["sequence"]) if i not in drop)} for r in msa.msa]

msa.on_rename_row(rename)
msa.on_remove_rows(remove_rows)
msa.on_remove_columns(remove_columns)