mkt.databases.conservation.KLIFSConservationTreeFigure
- class mkt.databases.conservation.KLIFSConservationTreeFigure(*, names: list[str] = <factory>, pockets: list[str] = <factory>, groups: list[str] = <factory>, position_labels: list[str] = <factory>, metric: str = 'blosum', blosum_name: str = 'BLOSUM62', linkage_method: str = 'average', conservation_threshold: float = 0.8, min_child_members: int = 2, weighting: str = 'none', exclude_pseudokinases: bool = False, gap_chars: str = '-X', distance_matrix: ~numpy.ndarray | None = None, linkage_matrix: ~numpy.ndarray | None = None, tree: ~scipy.cluster.hierarchy.ClusterNode | None = None, min_cluster_size: int = 12, font_size: float = 4.0, split_index: int | None = 47)[source]
Bases:
KLIFSHierarchicalConservationStatic letter-page figure of the KLIFS conservation tree + per-leaf table.
The matplotlib sibling of the interactive Bokeh explorer (
mkt_impact.analysis.interactive.KLIFSTreeConservationApp): a thin multifurcating dendrogram of the human kinome (singleton-peel chains contracted, singletons aggregated by tree adjacency so no leaf row is a single sequence), homolog-collapsed leaf name boxes, and a per-leaf table rendering each row’s >=80% consensus residue at all 85 KLIFS positions colored by the amino-acid alphabet palette. Both views consume the one sharedbuild_display_tree()/members_consensus(), so the tree topology cannot diverge between them.Panel-only
KLIFSTreeView: construct standalone (defaults to the full human-kinome KLIFS panel) or viafrom_dataloaderin the pipeline, then callbuild_figure()(returns the figure) orplot()(saves svg/png/pdf to the structured output tree).- __init__(**data: Any) None
Create a new model by parsing and validating input data from keyword arguments.
Raises [ValidationError][pydantic_core.ValidationError] if the input data cannot be validated to form a valid model.
self is explicitly positional-only to allow self as a field name.
Methods
_aggregate_singletons(splits, leaves)Fold singleton leaves by tree adjacency so no leaf row holds one sequence.
_annotation_callouts(aa)Find the shared-residue columns for the curated kinases of interest.
_annotation_lines(kinases, pos, label)"{kinase} {residue}{uniprot_idx}"per kinase at KLIFS columnpos._blosum_distance_matrix()Substitution-score similarity distance (Metric A).
_build_summary_panel(tree, split_index)Horizontal (top-down) overview dendrogram: leaves along x as family-colored blocks, depth down the y-axis (root at top), split marked, group legend below.
_conserved_columns(conservation)Filter per-column conservation to the conserved consensus residues.
_dominant_color(members)Branch color: the family color if >=80% of members share it, else mixed-grey.
_draw_dendrogram(ax, splits, leaves, ...)Draw the thin multifurcating dendrogram, pruned to in-subset branches and rooted (relative depth) at the subset's spanning subtree.
_draw_name_boxes(ax, leaves, order, x_leaf, ...)Draw the homolog-collapsed leaf name boxes (measured widths).
_draw_table(ax, leaves, order, labels, ...)Draw the per-leaf >=80% consensus table with the KLIFS region header.
_drop_pseudokinases()Filter the panel to catalytically active kinases (in place).
_encode_pockets()Integer-encode the pocket panel against the substitution-matrix alphabet.
_family_label(i)Family used for the color: Lipid or Manning group (pseudo folds in).
_family_name(value)Label for a family field, which may be a
Familyenum or a bare string._group_legend_handles(fams)Kinase-group legend handles, ordered by the standard Manning-group order.
_henikoff_weights(sequences)Henikoff (1994) position-based sequence weights for a set of members.
_hover_families(i)(kinhub_family, klifs_family)labels for leafi's dot hover._identity_distance_matrix()Percent-identity distance (Metric B):
1 - matches / non_gap_columns._is_kept(node_id)True if both children of
node_idare clades (>=2 members each)._kinome_background()Kinome amino-acid background (20-vector) over all KLIFS panel pockets.
_leaf_groups(members)Collapse a leaf row's members into
(label, representative_index)boxes._member_style(i)(fill, edge, linewidth)for leafi's name box / dot._nodelist()Return the cached SciPy node list, indexed by node id.
Key separating homolog lumping by lipid / pseudokinase / Manning group.
_pseudocount_model([background])Cached pseudocount model for the requested KL background.
_render_panel(tree, subset, page, fs[, ...])Render a dendrogram + name boxes + conservation table for a leaf subset.
_split_index(tree)Leaf-order index to split the detail panels: the kinase-group boundary nearest the midpoint (so each panel is roughly half and starts a new group).
_table_consensus(members)Per-column >=threshold consensus INCLUDING gaps.
_uniprot_index_at(i, pos)1-based UniProt canonical index of leaf
iat KLIFS columnpos._walk_node(node, depth, records)Recursively score a node and its children, appending one record per node.
analyze_nodes()Walk the tree and compute per-node conservation, cached after first call.
build_display_tree([min_cluster_size, ...])Build the renderer-neutral display tree from the linkage.
Render the full conservation tree + per-leaf table on a US-letter portrait page.
build_residue_dot_figure([aa, figsize, ...])Static companion to
KLIFSResidueDotAppfor a single amino acid.build_split_figures([split_index])Build the three supplemental figures: horizontal summary + top / bottom detail panels, split at
split_index(default:INT_TREE_SPLIT_INDEX, the CMGC/CAMK boundary; falls back to_split_index()when the resolved index is None or out of range for the current panel).compute_distance_matrix()Dispatch to the configured pairwise distance metric.
cophenetic_correlation()Cophenetic correlation between the tree and the input distances.
critical_depth()Most ancestral node at which each KLIFS column still survives-up.
from_conservation_data(data, **kwargs)Build a renderer from a persisted
KLIFSConservationDataartifact.gather_children(node_id)Singleton-contracted multifurcating children of
node_id.group_concordance([n_clusters])Adjusted Rand index between flat clusters and Manning groups.
members_consensus(member_idx)Per-column >=threshold consensus residue for a member set (else None).
node_conservation(member_idx)Per-column conservation for a set of member leaves.
node_information(member_idx[, background])Per-column background-relative information content (bits) and effective count.
nodes_summary()Tabular summary of per-node conservation counts (internal nodes only).
plot(output_path[, formats])Render and save the single full-page figure to
output_path.plot_critical_depth([figsize, cmap])Plot per-KLIFS-column critical depth as an opaque track with a region bar.
plot_residue_dot(output_path[, aa, formats, ...])Render and save the static per-amino-acid dot-plot figure to
output_path.plot_split(output_path[, formats, split_index])Render and save the three split supplemental figures to
output_path.residue_dot_layout([min_cluster_size])Row/leaf assignment for the per-amino-acid dot plot.
to_conservation_data([min_cluster_size, ...])Package the clustering output as a serializable
KLIFSConservationData.tree_children(node_id)The two linkage children of an internal node id.
tree_count(node_id)Number of leaves under
node_id(1 for a leaf).tree_members(node_id)Leaf indices under
node_id(the node itself if it is a leaf).Attributes
Gathered subtrees with fewer members collapse to a single leaf bar.
Base font size; raising it widens the (measured) name boxes and narrows the table.
Leaf-order index splitting the top/bottom detail panels.
List of HGNC kinase names (one per pocket).
List of 85-character KLIFS pocket strings, column-aligned by construction.
Manning group per kinase, used for the external concordance check.
KLIFS region labels (e.g.
"g.l:4") for the 85 pocket columns."blosum"(default) or"identity".Substitution matrix name used by the
"blosum"metric."average"(UPGMA, default) or"complete".Minimum consensus-residue frequency for a column to count as conserved.
Minimum child-clade size considered in survives-up pruning; children smaller than this (e.g. singleton outliers peeled off at the root) are ignored.
"none"(default) or"henikoff".If True, drop predicted pseudokinases (
KinaseInfo.is_pseudokinase()) from the panel before clustering, so the tree and conservation reflect catalytically active kinases only (default: False).Characters treated as gap/unknown and excluded from scoring and conservation.
Square
N x Npairwise distance matrix; computed post-init unless supplied (e.g. injected byfrom_conservation_data()from a persisted artifact).SciPy linkage matrix; computed post-init unless supplied.
Root
ClusterNodeof the hierarchical tree, computed post-init._node_recordsCached per-node conservation records (see
analyze_nodes())._nodelist_cacheCached SciPy
to_tree(rd=True)node list, indexed by node id._kinome_bg_cacheCached kinome amino-acid background (from the KLIFS panel) for the IC measure.
_pssm_cacheCached substitution-aware pseudocount models, keyed by background choice.
- _build_summary_panel(tree: KLIFSDisplayTree, split_index: int) Figure[source]
Horizontal (top-down) overview dendrogram: leaves along x as family-colored blocks, depth down the y-axis (root at top), split marked, group legend below.
- _dominant_color(members: list[int]) str[source]
Branch color: the family color if >=80% of members share it, else mixed-grey.
- _draw_dendrogram(ax, splits, leaves, split_yc, base_depth, x_leaf, yof)[source]
Draw the thin multifurcating dendrogram, pruned to in-subset branches and rooted (relative depth) at the subset’s spanning subtree.
- _draw_name_boxes(ax, leaves, order, x_leaf, ch, fs)[source]
Draw the homolog-collapsed leaf name boxes (measured widths).
- _draw_table(ax, leaves, order, labels, x_table, colw, ch, fs)[source]
Draw the per-leaf >=80% consensus table with the KLIFS region header.
- _group_legend_handles(fams: set[str]) list[Patch][source]
Kinase-group legend handles, ordered by the standard Manning-group order.
Shared by the summary dendrogram and the top/bottom detail panels so their kinase-group legends match. Families outside the curated order are appended alphabetically.
- Parameters:
fams (set[str]) – Family labels present in the drawn subset (Manning group or Lipid).
- Returns:
One color swatch per present family, in display order.
- Return type:
list[matplotlib.patches.Patch]
- _leaf_groups(members: list[int]) list[tuple[str, int]][source]
Collapse a leaf row’s members into
(label, representative_index)boxes.Members are partitioned by family/pseudo/lipid key first (so e.g. a pseudo ERBB3 stays apart), then name-homologs within each partition are collapsed via the shared
mkt.schema.utils.group_name_homologs().
- _partition_key(i: int) tuple[source]
Key separating homolog lumping by lipid / pseudokinase / Manning group.
- _render_panel(tree, subset, page, fs, show_legend=False)[source]
Render a dendrogram + name boxes + conservation table for a leaf subset.
Shared by the full figure and each split detail panel.
subsetis a contiguous slice oftree.order; the dendrogram is pruned to (and rooted, via relative depth, at) the subset’s spanning subtree, the x-axis is laid out in inches so name boxes never overhang, the KLIFS table fills the remaining width, and the top margin is sized to the tallest rotated KLIFS label so there is no slack.- Parameters:
tree (KLIFSDisplayTree) – The display tree (from
build_display_tree()).subset (list[int]) – Leaf indices (into
tree.leaves) to draw, in display order.page (tuple[float, float]) – Figure size in inches.
fs (float) – Base font size for the boxes / table / KLIFS labels.
show_legend (bool, optional) – If True, reserve a bottom band and draw the kinase-group legend beneath the panel (used by the top/bottom detail panels; the caller must have added
FLOAT_TREE_DETAIL_LEGEND_INtopageheight). Default False.
- Return type:
tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
- _split_index(tree: KLIFSDisplayTree) int[source]
Leaf-order index to split the detail panels: the kinase-group boundary nearest the midpoint (so each panel is roughly half and starts a new group).
- _table_consensus(members: list[int]) list[str | None][source]
Per-column >=threshold consensus INCLUDING gaps.
Returns, per KLIFS column, an amino acid, a gap character (when a gap is the >=threshold consensus), or None when nothing reaches the threshold. Counting gaps means an all-but-absent pocket position reads as a gap rather than borrowing the consensus of the handful of members that do carry a residue.
- blosum_name: str
Substitution matrix name used by the
"blosum"metric.
- build_figure() tuple[Figure, Axes][source]
Render the full conservation tree + per-leaf table on a US-letter portrait page.
- Returns:
The figure and its single (axis-off) axes, sized to
TUP_TREE_PAGE.- Return type:
tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
- build_residue_dot_figure(aa: str = 'C', figsize: tuple[float, float] | None = None, highlight_targets: bool = False) tuple[Figure, Axes][source]
Static companion to
KLIFSResidueDotAppfor a single amino acid.A frequency dot plot: within each of the 85 KLIFS columns (x) the kinases carrying
aaare stacked one dot per kinase (y = count) in dendrogram leaf order, so empty columns simply have no dots. Dots are colored by Manning group / Lipid (black outline for pseudokinases); runs of :data:`INT_RESIDUE_DOT_MIN_ENCLOSE`+ consecutive same-clade dots within a column are enclosed in a light-grey rounded box. A KLIFS region color bar and rotated position labels run beneath, and the kinase-group legend sits below.- Parameters:
aa (str) – Amino-acid single-letter code (or
"-") to plot, by default cysteine.figsize (tuple[float, float] | None, optional) – Figure size; by default sized to the tallest column stack.
highlight_targets (bool, optional) – If True, draw the curated conserved-cysteine callout boxes for the kinases in
LIST_RESIDUE_DOT_KINASES– a labeled box of kinases + residue numbers with an arrow to each shared-residue column found by searching the alignment (_annotation_callouts()) – by default False.
- Return type:
tuple[matplotlib.figure.Figure, matplotlib.axes.Axes]
- build_split_figures(split_index: int | None = None) list[tuple[str, Figure]][source]
Build the three supplemental figures: horizontal summary + top / bottom detail panels, split at
split_index(default:INT_TREE_SPLIT_INDEX, the CMGC/CAMK boundary; falls back to_split_index()when the resolved index is None or out of range for the current panel).- Returns:
(output_basename, figure)for the summary, top, and bottom panels.- Return type:
list[tuple[str, matplotlib.figure.Figure]]
- conservation_threshold: float
Minimum consensus-residue frequency for a column to count as conserved.
- distance_matrix: np.ndarray | None
Square
N x Npairwise distance matrix; computed post-init unless supplied (e.g. injected byfrom_conservation_data()from a persisted artifact).
- exclude_pseudokinases: bool
If True, drop predicted pseudokinases (
KinaseInfo.is_pseudokinase()) from the panel before clustering, so the tree and conservation reflect catalytically active kinases only (default: False).
- font_size: float
Base font size; raising it widens the (measured) name boxes and narrows the table.
- gap_chars: str
Characters treated as gap/unknown and excluded from scoring and conservation.
- groups: list[str]
Manning group per kinase, used for the external concordance check.
- linkage_matrix: np.ndarray | None
SciPy linkage matrix; computed post-init unless supplied.
- linkage_method: str
"average"(UPGMA, default) or"complete".- Type:
SciPy linkage method
- metric: str
"blosum"(default) or"identity".- Type:
Pairwise distance metric
- min_child_members: int
Minimum child-clade size considered in survives-up pruning; children smaller than this (e.g. singleton outliers peeled off at the root) are ignored. Set to 1 to require every immediate child to agree (the strict, topology-sensitive definition).
- min_cluster_size: int
Gathered subtrees with fewer members collapse to a single leaf bar.
- names: list[str]
List of HGNC kinase names (one per pocket).
- plot(output_path: str, formats: tuple[str, ...] = ('svg', 'png', 'pdf')) None[source]
Render and save the single full-page figure to
output_path.Writes
{STR_FILE_CONSERVATION_TREE}.{ext}intooutput_pathfor each requested format. No tight bbox, so the page stays exactlyTUP_TREE_PAGE.- Parameters:
output_path (str) – Directory to write the figure into.
formats (tuple[str, …], optional) – File extensions to write, by default
("svg", "png", "pdf").
- plot_residue_dot(output_path: str, aa: str = 'C', formats: tuple[str, ...] = ('pdf',), highlight_targets: bool = False) None[source]
Render and save the static per-amino-acid dot-plot figure to
output_path.- Parameters:
output_path (str) – Directory to write the figure into.
aa (str) – Amino-acid single-letter code (or
"-") to plot, by default cysteine.formats (tuple[str, …], optional) – File extensions to write, by default
("pdf",).highlight_targets (bool, optional) – If True, draw target arrows beneath the conserved inhibitor-targetable columns, by default False.
- plot_split(output_path: str, formats: tuple[str, ...] = ('pdf',), split_index: int | None = None) None[source]
Render and save the three split supplemental figures to
output_path.Writes
{basename}.{ext}intooutput_pathfor each format (PDF by default, as these are supplemental materials).- Parameters:
output_path (str) – Directory to write the figures into.
formats (tuple[str, …], optional) – File extensions to write, by default
("pdf",).split_index (int | None, optional) – Leaf-order split index; default auto (
_split_index()).
- pockets: list[str]
List of 85-character KLIFS pocket strings, column-aligned by construction.
- position_labels: list[str]
KLIFS region labels (e.g.
"g.l:4") for the 85 pocket columns.
- split_index: int | None
Leaf-order index splitting the top/bottom detail panels. Defaults to the curated CMGC/CAMK boundary of the human-kinome KLIFS tree (
INT_TREE_SPLIT_INDEX). Set to None (or an out-of-range value) to auto-pick the group boundary nearest the midpoint (_split_index()).
- tree: ClusterNode | None
Root
ClusterNodeof the hierarchical tree, computed post-init.
- weighting: str
"none"(default) or"henikoff".- Type:
Per-node consensus weighting