mkt.databases.conservation
Study-independent KLIFS hierarchical conservation of the human kinome.
Hierarchically clusters the human kinome on KLIFS pocket similarity (from the
DICT_KINASE KLIFS pocket sequences) and traces per-residue conservation up
the tree via the shared engine KLIFSHierarchicalConservation. Two
renderers sit on top of that engine: a static matplotlib supplemental figure
(KLIFSConservationTreeFigure) and an interactive standalone-HTML Bokeh
explorer (KLIFSTreeConservationApp), which therefore cannot diverge on
tree topology.
Moved out of mkt_impact into mkt.databases because it needs no
cohort/study data – it operates purely on the human-kinome KLIFS panel.
Module Attributes
Expected length of a valid KLIFS pocket alignment string. |
|
Minimum consensus-residue frequency for a column to count as conserved at a node. |
|
Minimum child-clade size considered in survives-up pruning; smaller (e.g. singleton outlier) children are ignored so they cannot veto an otherwise-robust residue. |
|
Default display threshold for |
|
Output basename for the static KLIFS conservation-tree figure. |
|
Figure size in inches (US letter, portrait). |
|
Base font size for the leaf name boxes, table cells, and KLIFS labels. |
|
Height of each leaf row / table cell in y (row) units. |
|
Inner horizontal padding per side of each name box (inches). |
|
Horizontal gap between adjacent name boxes (inches). |
|
Gap between the name boxes and the conservation table (inches). |
|
Right margin reserved past the table (inches). |
|
Dendrogram depth step (inches); keeps the tree a thin structural stub. |
|
Fraction of a clade that must share a family for the branch to take its color. |
|
Line width of the dendrogram branches. |
|
Border width for pseudokinase leaf boxes (active kinases use a thin white border). |
|
Line width of the leaf->table guide lines. |
|
Output basename for the horizontal summary dendrogram. |
|
Output basename for the top (first-half) detail panel. |
|
Output basename for the bottom (second-half) detail panel. |
|
Font size for the split detail panels (fewer rows -> a touch larger than the single full-page figure). |
|
Width (inches) of each split detail panel; height is flexible (row count). |
|
Inches of page height per leaf row in a split detail panel. |
|
Inches of page height reserved beneath a split detail panel for its kinase-group legend. |
|
Font size for the top/bottom detail-panel kinase-group legend (much larger than the table font so it is legible in the supplement). |
|
Figure size (inches) of the horizontal summary dendrogram. |
|
Font size for the summary dendrogram's kinase-group legend (matches the top/bottom detail panels' |
|
Default leaf-order index splitting the top/bottom detail panels of the human-kinome KLIFS conservation tree -- the boundary between the mostly-CMGC clade and the mostly-CAMK clade. |
|
Substitution matrix name (Bio.Align.substitution_matrices) for the default metric. |
|
Name of the substitution-score similarity metric (Metric A, default). |
|
Name of the percent-identity distance metric (Metric B, baseline). |
|
UPGMA linkage — standard for sequence trees (primary). |
|
Complete linkage — tighter, more compact clusters (contrast). |
|
Unweighted per-node consensus (every member counts equally, default). |
|
Henikoff (1994) position-based sequence weighting for the per-node consensus. |
|
Output filename for the interactive KLIFS conservation-tree explorer. |
|
Minimum consensus frequency for a residue to appear in the per-node logo. |
|
Minimum information content (bits) for a residue to appear in the IC logo modes. |
|
y-axis top (bits) for the information-content logo modes. |
|
Max items listed in a conservation-tree tooltip field before truncation. |
|
Output filename for the interactive per-amino-acid KLIFS dot-plot explorer. |
|
Output basename for the static per-amino-acid KLIFS dot-plot figure. |
|
Default amino acid for the static dot-plot figure (cysteine). |
|
Minimum same-clade dots stacked in a column for a clade enclosure to be drawn. |
|
The 20 amino-acid single-letter codes plus the gap symbol, for the dot-plot amino-acid selector. |
|
Clinically relevant kinases of interest whose covalent-targetable residues are called out on the static dot plot. |
|
Minimum kinases-of-interest carrying a residue at a column to draw a callout box (1 = annotate every cysteine of the kinases of interest, grouping any that share a column). |
Functions
|
Collect the gapless KLIFS pocket panel for hierarchical clustering. |
|
Temporary shim: fix CAMKK1's off-by-one KLIFS mapping in place. |
|
Build a conservation renderer from the shipped |
|
Reconstruct the SciPy hierarchical tree from a persisted artifact. |
Classes
|
Static letter-page figure of the KLIFS conservation tree + per-leaf table. |
|
A leaf row of the display tree: a collapsed clade or aggregated singletons. |
|
An internal (multifurcating) node of the display tree. |
|
Renderer-neutral display tree shared by the static figure and Bokeh app. |
|
Hierarchically cluster human kinases on KLIFS pocket similarity. |
|
Interactive standalone-HTML per-amino-acid KLIFS dot-plot explorer. |
|
Interactive standalone-HTML Bokeh explorer for the KLIFS conservation tree. |
|
Legend handler that renders a |
- mkt.databases.conservation.FLOAT_CONSERVATION_THRESHOLD = 0.8
Minimum consensus-residue frequency for a column to count as conserved at a node.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_BOX_GAP_IN = 0.03
Horizontal gap between adjacent name boxes (inches).
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_BOX_PAD_IN = 0.028
Inner horizontal padding per side of each name box (inches).
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_BRANCH_LW = 1.3
Line width of the dendrogram branches.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_DEPTH_STEP_IN = 0.014
Dendrogram depth step (inches); keeps the tree a thin structural stub.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_DETAIL_LEGEND_FS = 13.0
Font size for the top/bottom detail-panel kinase-group legend (much larger than the table font so it is legible in the supplement).
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_DETAIL_LEGEND_IN = 0.4
Inches of page height reserved beneath a split detail panel for its kinase-group legend.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_DETAIL_PAGE_W = 9.5
Width (inches) of each split detail panel; height is flexible (row count).
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_DETAIL_ROW_IN = 0.18
Inches of page height per leaf row in a split detail panel.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_DOMINANT_FRACTION = 0.8
Fraction of a clade that must share a family for the branch to take its color.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_FONT_SIZE = 4.0
Base font size for the leaf name boxes, table cells, and KLIFS labels.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_GUIDE_LW = 0.3
Line width of the leaf->table guide lines.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_LOGO_CUTOFF = 0.1
Minimum consensus frequency for a residue to appear in the per-node logo.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_LOGO_IC_FLOOR = 0.5
Minimum information content (bits) for a residue to appear in the IC logo modes.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_LOGO_IC_MAX = 4.6
y-axis top (bits) for the information-content logo modes.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_PSEUDO_BORDER_LW = 0.5
Border width for pseudokinase leaf boxes (active kinases use a thin white border).
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_RIGHT_PAD_IN = 0.05
Right margin reserved past the table (inches).
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_ROW_HEIGHT = 0.72
Height of each leaf row / table cell in y (row) units.
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_SPLIT_FONT_SIZE = 4.5
Font size for the split detail panels (fewer rows -> a touch larger than the single full-page figure).
- Type:
float
- mkt.databases.conservation.FLOAT_TREE_SUMMARY_LEGEND_FS = 13.0
Font size for the summary dendrogram’s kinase-group legend (matches the top/bottom detail panels’
FLOAT_TREE_DETAIL_LEGEND_FS).- Type:
float
- mkt.databases.conservation.FLOAT_TREE_TABLE_GAP_IN = 0.07
Gap between the name boxes and the conservation table (inches).
- Type:
float
- mkt.databases.conservation.INT_KLIFS_POCKET_LENGTH = 85
Expected length of a valid KLIFS pocket alignment string.
- Type:
int
- mkt.databases.conservation.INT_MIN_CHILD_MEMBERS = 2
Minimum child-clade size considered in survives-up pruning; smaller (e.g. singleton outlier) children are ignored so they cannot veto an otherwise-robust residue.
- Type:
int
- mkt.databases.conservation.INT_RESIDUE_DOT_MIN_ENCLOSE = 2
Minimum same-clade dots stacked in a column for a clade enclosure to be drawn.
- Type:
int
- mkt.databases.conservation.INT_RESIDUE_DOT_MIN_SHARED = 1
Minimum kinases-of-interest carrying a residue at a column to draw a callout box (1 = annotate every cysteine of the kinases of interest, grouping any that share a column).
- Type:
int
- mkt.databases.conservation.INT_TREE_MIN_CLUSTER_DISPLAY = 12
Default display threshold for
KLIFSHierarchicalConservation.build_display_tree()– gathered subtrees with fewer members collapse to a single leaf bar rather than expanding into their own split node. Shared by the static figure and the interactive Bokeh app.- Type:
int
- mkt.databases.conservation.INT_TREE_NAME_TRUNC = 14
Max items listed in a conservation-tree tooltip field before truncation.
- Type:
int
- mkt.databases.conservation.INT_TREE_SPLIT_INDEX = 47
Default leaf-order index splitting the top/bottom detail panels of the human-kinome KLIFS conservation tree – the boundary between the mostly-CMGC clade and the mostly-CAMK clade. A property of the fixed KLIFS panel (study-independent), so it is hardcoded;
KLIFSConservationTreeFigure._split_index()is retained as a fallback (used when this index is None or out of range for a non-standard panel).- Type:
int
- 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).- _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.
- 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]]
- font_size: float
Base font size; raising it widens the (measured) name boxes and narrows the table.
- min_cluster_size: int
Gathered subtrees with fewer members collapse to a single leaf bar.
- 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()).
- 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()).
- class mkt.databases.conservation.KLIFSDisplayLeaf(members: list[int], kind: str)[source]
Bases:
objectA leaf row of the display tree: a collapsed clade or aggregated singletons.
- Variables:
members (list[int]) – Leaf indices (into
KLIFSHierarchicalConservation.names) in this row.kind (str) –
"clade"(a collapsed subtree) or"singleton"(a single peeled leaf, present only when singleton aggregation is disabled).
- __init__(members: list[int], kind: str) None
- kind: str
- members: list[int]
- class mkt.databases.conservation.KLIFSDisplaySplit(id: int, node_id: int, depth: int, members: list[int], children: list[tuple[str, int]] = <factory>)[source]
Bases:
objectAn internal (multifurcating) node of the display tree.
- Variables:
id (int) – Index of this split within
KLIFSDisplayTree.splits(root is 0).node_id (int) – Underlying SciPy linkage node id.
depth (int) – Depth from the root (root is 0).
members (list[int]) – All leaf indices under this split.
children (list[tuple[str, int]]) – Ordered children as
("node", split_id)or("leaf", leaf_index).
- __init__(id: int, node_id: int, depth: int, members: list[int], children: list[tuple[str, int]] = <factory>) None
- children: list[tuple[str, int]]
- depth: int
- id: int
- members: list[int]
- node_id: int
- class mkt.databases.conservation.KLIFSDisplayTree(splits: list[KLIFSDisplaySplit], leaves: list[KLIFSDisplayLeaf], order: list[int])[source]
Bases:
objectRenderer-neutral display tree shared by the static figure and Bokeh app.
- Variables:
splits (list[KLIFSDisplaySplit]) – Internal multifurcating nodes;
splits[0]is the root.leaves (list[KLIFSDisplayLeaf]) – Leaf rows (collapsed clades / aggregated singletons).
order (list[int]) – Leaf indices (into
leaves) in in-order (top-to-bottom) display order.
- __init__(splits: list[KLIFSDisplaySplit], leaves: list[KLIFSDisplayLeaf], order: list[int]) None
- leaves: list[KLIFSDisplayLeaf]
- order: list[int]
- splits: list[KLIFSDisplaySplit]
- class mkt.databases.conservation.KLIFSHierarchicalConservation(*, 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)[source]
Bases:
BaseModelHierarchically cluster human kinases on KLIFS pocket similarity.
Builds a pairwise distance matrix over the gapless 85-column KLIFS pocket alignment (
_build_klifs_panel()), clusters it with SciPy linkage, then traces per-residue conservation up the tree. Per-node conservation reusesMSAConservationAnalyzer.column_conservation(), keeping the tree and the conservation read-out in the same coordinate system.Two metrics are provided behind a common interface: substitution-score similarity (Metric A,
"blosum", default) and percent identity (Metric B,"identity", baseline). Two views of conservation are emitted at each internal node: per-subtree (recompute on that node’s members) and survives-up (the residue must be conserved at the node and hold — same consensus residue — in both child clades).- _aggregate_singletons(splits: list[KLIFSDisplaySplit], leaves: list[KLIFSDisplayLeaf]) None[source]
Fold singleton leaves by tree adjacency so no leaf row holds one sequence.
Mutates
splits/leavesin place: >=2 sibling singletons fold into one aggregated clade row, a lone sibling singleton folds into its nearest sibling clade, otherwise it bubbles up to the parent split (with a final safety net into the largest clade). Dead leaves are dropped and child references are remapped.
- _annotation_callouts(aa: str) list[tuple[list[str], int]][source]
Find the shared-residue columns for the curated kinases of interest.
Searches every KLIFS column and, at each, collects the kinases from
LIST_RESIDUE_DOT_KINASESthat carryaathere; a column is called out when at leastINT_RESIDUE_DOT_MIN_SHAREDof them share it. There is no pre-grouping, so any kinases sharing a homologous residue at one column are boxed together, and the callouts are discovered from the current alignment (surviving a shift in the KLIFS mapping) rather than hardcoded.- Parameters:
aa (str) – The plotted residue (e.g.
"C").- Returns:
(shared_kinases, column_index)per discovered callout.- Return type:
list[tuple[list[str], int]]
- _annotation_lines(kinases: list[str], pos: int, label: str) list[str][source]
"{kinase} {residue}{uniprot_idx}"per kinase at KLIFS columnpos.Used for the curated conserved-residue callout boxes; the residue letter and UniProt index are read from each kinase’s pocket and
KLIFS2UniProtIdxinDICT_KINASE, so the numbers stay correct without hardcoding.
- _blosum_distance_matrix() ndarray[source]
Substitution-score similarity distance (Metric A).
Sums the substitution score over jointly non-gap columns, normalizes by each sequence’s self-score (cosine-like in score space), and converts to a distance
1 - sim.Returns:
- np.ndarray
Square
N x Ndistance matrix with a zero diagonal.
- _conserved_columns(conservation: list[tuple[str | None, float]]) dict[int, str][source]
Filter per-column conservation to the conserved consensus residues.
Parameters:
- conservationlist[tuple[str | None, float]]
Per-column
(consensus_aa, fraction)tuples.
Returns:
- dict[int, str]
Mapping of column index to consensus residue for columns whose consensus frequency meets
conservation_threshold.
- _drop_pseudokinases() None[source]
Filter the panel to catalytically active kinases (in place).
Drops any panel member for which
KinaseInfo.is_pseudokinase()is True, keepingnames,pocketsandgroupsin sync. Names absent fromDICT_KINASE(e.g. a custom panel) cannot be assessed and are kept.Returns:
None
- _encode_pockets() tuple[ndarray, ndarray, ndarray][source]
Integer-encode the pocket panel against the substitution-matrix alphabet.
Returns:
- tuple[np.ndarray, np.ndarray, np.ndarray]
(enc, valid, mat_arr)whereencis theN x 85integer code (gaps mapped to 0 but masked out),validis theN x 85boolean non-gap mask, andmat_arris the dense substitution-score matrix.
- _family_label(i: int) str[source]
Family used for the color: Lipid or Manning group (pseudo folds in).
- static _family_name(value) str[source]
Label for a family field, which may be a
Familyenum or a bare string.
- _henikoff_weights(sequences: list[str]) list[float][source]
Henikoff (1994) position-based sequence weights for a set of members.
Each non-gap residue contributes
1 / (r_c * s_c)to its sequence’s weight, wherer_cis the number of distinct residues in columncands_cis the number of sequences sharing that residue. This down-weights redundant subfamilies and up-weights divergent sequences. Weights are scaled to mean 1; the per-column conservation fraction is scale-invariant regardless.Parameters:
- sequenceslist[str]
Aligned member sequences.
Returns:
- list[float]
One weight per sequence.
- _hover_families(i: int) tuple[str, str][source]
(kinhub_family, klifs_family)labels for leafi’s dot hover.
- _identity_distance_matrix() ndarray[source]
Percent-identity distance (Metric B):
1 - matches / non_gap_columns.Returns:
- np.ndarray
Square
N x Ndistance matrix with a zero diagonal.
- _is_kept(node_id: int) bool[source]
True if both children of
node_idare clades (>=2 members each).A node fails this when one child is a singleton leaf peeling off, which is exactly the pattern
gather_children()contracts away.
- _kinome_background() ndarray[source]
Kinome amino-acid background (20-vector) over all KLIFS panel pockets.
The preferred KL background for the information-content measure (“surprising relative to kinases”): a residue conserved because it is the kinome norm scores low, while a subfamily-specific residue scores high (plan Addendum A.1).
- _member_style(i: int) tuple[str, str, float][source]
(fill, edge, linewidth)for leafi’s name box / dot.Lipid kinases get no border, pseudokinases a black border, active kinases a thin white border; the fill is the Manning-group (or Lipid) color. Shared by the static tree figure and the interactive dot-plot explorer.
- _pseudocount_model(background: str = 'swissprot') SubstitutionPseudocounts[source]
Cached pseudocount model for the requested KL background.
"swissprot"(default) scores conservation relative to a random protein – the continuous companion to the >=80% rule (pan-invariants score high)."kinome"scores conservation relative to the KLIFS panel itself, so subfamily-defining residues pop while pan-invariants score near zero (plan-preferred for the subfamily-delta view).
- _uniprot_index_at(i: int, pos: int) int | None[source]
1-based UniProt canonical index of leaf
iat KLIFS columnpos.Read from
KinaseInfo.KLIFS2UniProtIdxkeyed by the column’s region label; None when the kinase, mapping, or that position is unavailable.
- _walk_node(node: ClusterNode, depth: int, records: list[dict]) dict[int, str][source]
Recursively score a node and its children, appending one record per node.
For each node the per-subtree conserved columns are recomputed on its members. At an internal node the survives-up set keeps only columns conserved at the node whose consensus residue is also conserved (identical) in every child clade with at least
min_child_membersmembers. Children below that size (e.g. a singleton outlier peeled off at the root by UPGMA) are ignored so they cannot veto an otherwise-robust residue.Parameters:
- nodeClusterNode
Current node in the tree.
- depthint
Depth of the node (root is 0).
- recordslist[dict]
Accumulator the per-node record dicts are appended to.
Returns:
- dict[int, str]
The node’s per-subtree conserved columns (column index -> consensus aa), so the parent can intersect against it for the survives-up set.
- analyze_nodes() list[dict][source]
Walk the tree and compute per-node conservation, cached after first call.
Returns:
- list[dict]
One record per node with keys
node_id,depth,n_members,is_leaf,conserved(per-subtree column->aa) andsurvives_up(the pruned, robust column->aa).
- blosum_name: str
Substitution matrix name used by the
"blosum"metric.
- build_display_tree(min_cluster_size: int = 12, aggregate_singletons: bool = True) KLIFSDisplayTree[source]
Build the renderer-neutral display tree from the linkage.
Starting at the root,
gather_children()contracts singleton-peel chains; each gathered child then either expands into its own split (>=min_cluster_sizemembers), collapses to a clade leaf, or is a peeled singleton leaf. Whenaggregate_singletonsis True (default) singleton leaves are folded by tree adjacency so no leaf row holds a single sequence (which would read as artificially 100% conserved): >=2 sibling singletons fold into one row, a lone sibling singleton folds into its nearest sibling clade, and otherwise it bubbles up to the parent split.- Parameters:
min_cluster_size (int, optional) – Members below which a gathered subtree collapses to a single leaf bar, by default
INT_TREE_MIN_CLUSTER_DISPLAY.aggregate_singletons (bool, optional) – Fold singleton leaves so every leaf row has >=2 members, by default True.
- Returns:
Splits, leaves, and the in-order leaf display order.
- Return type:
- compute_distance_matrix() ndarray[source]
Dispatch to the configured pairwise distance metric.
Returns:
- np.ndarray
Square
N x Ndistance matrix.
- conservation_threshold: float
Minimum consensus-residue frequency for a column to count as conserved.
- cophenetic_correlation() float[source]
Cophenetic correlation between the tree and the input distances.
Returns:
- float
Pearson correlation of the cophenetic distances against the condensed input distance matrix (higher is a more faithful tree).
- critical_depth() DataFrame[source]
Most ancestral node at which each KLIFS column still survives-up.
A column’s critical depth is the shallowest (closest to root) depth at which it appears in a node’s survives-up set. Columns surviving at depth 0 are the pan-kinase invariants (expect the glycine-rich loop, the HRD arginine and the DFG aspartate).
Returns:
- pd.DataFrame
One row per KLIFS column with
column(0-based),position_label,critical_depth(NaN if never robust) andconsensus_aaat the shallowest surviving node, sorted by critical depth.
- distance_matrix: 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).
- classmethod from_conservation_data(data: KLIFSConservationData, **kwargs) KLIFSHierarchicalConservation[source]
Build a renderer from a persisted
KLIFSConservationDataartifact.Reuses the stored distances + linkage (so the rendered tree matches the persisted one and no clustering is recomputed), recovering the per-kinase pocket/group panel from
DICT_KINASEby name. Any renderer-specific keyword (e.g.min_cluster_size,font_size) is passed through.- Parameters:
data (KLIFSConservationData) – The persisted conservation-data artifact.
**kwargs – Extra fields forwarded to the (sub)class constructor.
- Returns:
An instance of
clswith injected distances, linkage, and tree.- Return type:
- gap_chars: str
Characters treated as gap/unknown and excluded from scoring and conservation.
- gather_children(node_id: int) list[int][source]
Singleton-contracted multifurcating children of
node_id.Descends through singleton-peel chains (nodes that are not
_is_kept()) so a kinase that peels off attaches directly to its clade, yielding a multifurcating child list of leaves and kept clades.- Parameters:
node_id (int) – Internal linkage node id.
- Returns:
Child node ids (leaves and kept internal nodes).
- Return type:
list[int]
- group_concordance(n_clusters: int | None = None) float[source]
Adjusted Rand index between flat clusters and Manning groups.
Parameters:
- n_clustersint | None
Number of flat clusters to cut the tree into. Defaults to the number of distinct Manning groups in the panel.
Returns:
- float
Adjusted Rand index (1.0 = perfect concordance, ~0 = chance).
- groups: list[str]
Manning group per kinase, used for the external concordance check.
- linkage_matrix: ndarray | None
SciPy linkage matrix; computed post-init unless supplied.
- linkage_method: str
"average"(UPGMA, default) or"complete".- Type:
SciPy linkage method
- members_consensus(member_idx: list[int]) list[str | None][source]
Per-column >=threshold consensus residue for a member set (else None).
Works for any set of leaves – a single leaf, a clade, or an aggregated row of unrelated singletons – so it backs both the per-node logo and the static per-leaf conservation table.
- Parameters:
member_idx (list[int]) – Leaf indices into
pockets.- Returns:
One entry per KLIFS column: the consensus residue if its frequency meets
conservation_threshold, elseNone.- Return type:
list[str | None]
- 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).
- names: list[str]
List of HGNC kinase names (one per pocket).
- node_conservation(member_idx: list[int]) list[tuple[str | None, float]][source]
Per-column conservation for a set of member leaves.
Reuses
MSAConservationAnalyzer.column_conservation()so the per-node read-out matches the panel-wide conservation analysis. Whenweightingis"henikoff"the consensus is computed with per-node Henikoff sequence weights (_henikoff_weights()).Parameters:
- member_idxlist[int]
Indices into
pocketsof the node’s member kinases.
Returns:
- list[tuple[str | None, float]]
One
(consensus_aa, fraction)tuple per KLIFS column.
- node_information(member_idx: list[int], background: str = 'swissprot') tuple[list[float | None], list[float]][source]
Per-column background-relative information content (bits) and effective count.
Continuous companion to
members_consensus()(plan Addendum A.2): for each KLIFS column, the KL divergence of the members’ substitution-smoothed residue distribution against the chosen background, plus the effective (weighted) count so the reader can see where the score is prior-influenced vs data-dominated. Sequence weighting followsweighting(uniform by default; Henikoff when set), the substitution-aware pseudocount is always applied.- Parameters:
member_idx (list[int]) – Leaf indices into
pockets.background (str, optional) – KL background:
"swissprot"(default) or"kinome"(see_pseudocount_model()).
- Returns:
(ic_per_column, n_eff_per_column);icisNonefor an all-gap column.- Return type:
tuple[list[float | None], list[float]]
- nodes_summary() DataFrame[source]
Tabular summary of per-node conservation counts (internal nodes only).
Returns:
- pd.DataFrame
One row per internal node with
node_id,depth,n_members,n_conserved(per-subtree),n_survives_up(pruned) andn_lost(conserved but not robust), sorted by depth.
- plot_critical_depth(figsize: tuple[float, float] = (15, 3), cmap: str = 'plasma') tuple[Figure, Axes][source]
Plot per-KLIFS-column critical depth as an opaque track with a region bar.
Each of the 85 KLIFS columns is colored by its critical depth — the shallowest (most ancestral) node at which it still survives-up (
critical_depth()). Lower depth means the residue holds across more of the kinome (depth 0 = a pan-kinase invariant); columns that never survive-up are drawn in grey. A KLIFS region color bar and position labels run beneath the track. Colors are flattened to opaque RGB (no alpha) for PowerPoint/PDF safety.Parameters:
- figsizetuple[float, float]
Figure size (default: (15, 3)).
- cmapstr
Matplotlib colormap name for the depth scale (default:
CMAP_CRITICAL_DEPTH).
Returns:
- tuple[plt.Figure, plt.Axes]
Figure and axis objects.
- 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.
- residue_dot_layout(min_cluster_size: int = 12) tuple[KLIFSDisplayTree, list[int], dict[int, int], dict[int, int], list[list[int]]][source]
Row/leaf assignment for the per-amino-acid dot plot.
Orders kinases by the display-tree leaf order (dendrogram order), assigning each kinase a y row and the 1-based number of the display leaf (clade) it belongs to. Shared by the interactive Bokeh explorer and the static companion figure so their ordering and clade grouping cannot diverge.
- Parameters:
min_cluster_size (int, optional) – Display-tree collapse threshold, by default
INT_TREE_MIN_CLUSTER_DISPLAY.- Returns:
(tree, ordered_members, row_of_member, leaf_of_member, leaf_members):ordered_membersare leaf indices (intonames) top-to-bottom,row_of_membermaps each to its y row,leaf_of_memberto its 1-based display-leaf number, andleaf_memberslists members per display leaf in display order.- Return type:
tuple
- to_conservation_data(min_cluster_size: int = 12, aggregate_singletons: bool = True) KLIFSConservationData[source]
Package the clustering output as a serializable
KLIFSConservationData.Stores the condensed upper-triangle distances, the SciPy linkage matrix, the leaf order, and the display-tree leaf composition (all as plain Python numbers), alongside the provenance metadata describing how they were assembled.
- Parameters:
min_cluster_size (int, optional) – Display-tree collapse threshold passed to
build_display_tree(), by defaultINT_TREE_MIN_CLUSTER_DISPLAY.aggregate_singletons (bool, optional) – Whether to fold singleton leaves in the display tree, by default True.
- Returns:
The serializable conservation-data artifact.
- Return type:
- tree: ClusterNode | None
Root
ClusterNodeof the hierarchical tree, computed post-init.
- tree_children(node_id: int) tuple[int, int][source]
The two linkage children of an internal node id.
- tree_members(node_id: int) list[int][source]
Leaf indices under
node_id(the node itself if it is a leaf).
- weighting: str
"none"(default) or"henikoff".- Type:
Per-node consensus weighting
- class mkt.databases.conservation.KLIFSResidueDotApp(*, 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, default_aa: str = 'C')[source]
Bases:
KLIFSHierarchicalConservationInteractive standalone-HTML per-amino-acid KLIFS dot-plot explorer.
A
Selectdropdown chooses one of the 20 amino acids (or the-gap); the plot then shows, for the 85 KLIFS pocket columns (x) against the human kinome in dendrogram leaf order (y), a dot wherever a kinase carries the selected residue at that column. Dots are colored by the dendrogram leaf coloring (Manning group / Lipid, with a black outline for pseudokinases). Dots of the same display-leaf clade that share the residue at a column (INT_RESIDUE_DOT_MIN_ENCLOSEor more) are enclosed, revealing columns “enriched” for that residue within a family (e.g. conserved cysteines). Hover reports the kinase, its display-leaf number, the UniProt residue (amino acid + canonical index, e.g.L858), the KLIFS label, and the KinHub / KLIFS family labels. All per-amino-acid data is precomputed and embedded, so the HTML needs no server.Panel-only view built on
KLIFSHierarchicalConservation;save_appwrites a self-contained HTML file to the structured output tree.- _column_stack(aa: str, pos: int, ordered_members: list[int], meta: dict) list[dict][source]
Kinases carrying
aaat KLIFS columnpos, in dendrogram leaf order.Each entry is the precomputed per-kinase
metadict; the list order is the bottom-to-top stacking order for the frequency dot plot (so same-clade dots are contiguous and can be enclosed).
- _dot_style(i: int) tuple[str, str][source]
(fill, line)colors for leafi’s dot (black outline if pseudokinase).
- _precompute_aa_data(ordered_members: list[int], leaf_of_member: dict[int, int]) tuple[dict, dict, dict][source]
Per-amino-acid stacked-dot and clade-enclosure payloads for the CustomJS switch.
For each amino acid this builds a frequency dot plot: within each KLIFS column the kinases carrying the residue are stacked (y = 0, 1, 2, …) in dendrogram leaf order, so a column’s dot count is its frequency and empty columns simply have no dots. Runs of >=
INT_RESIDUE_DOT_MIN_ENCLOSEconsecutive same-clade dots within a column are enclosed.- Returns:
(aa_data, enc_data, max_count)keyed by amino-acid symbol; the first two are dicts of parallel arrays ready to become aColumnDataSource, andmax_countis the tallest column stack (for the y-range).- Return type:
tuple[dict, dict, dict]
- build_layout()[source]
Assemble the Bokeh dot-plot layout with an amino-acid selector.
- Returns:
The column layout ready for
bokeh.embed.file_html().- Return type:
bokeh.models.LayoutDOM
- default_aa: str
cysteine).
- Type:
Amino acid shown on first load (default
- min_cluster_size: int
Display-tree collapse threshold (sets the display-leaf clades that are enclosed).
- save_app(output_path: str, filename: str | None = None) None[source]
Build the dot-plot explorer and write a self-contained HTML file.
- Parameters:
output_path (str) – Directory to write the HTML file into.
filename (str | None, optional) – Output filename; defaults to
STR_FILE_RESIDUE_DOT_APP.
- class mkt.databases.conservation.KLIFSTreeConservationApp(*, 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, logo_cutoff: float = 0.1, name_trunc: int = 14)[source]
Bases:
KLIFSHierarchicalConservationInteractive standalone-HTML Bokeh explorer for the KLIFS conservation tree.
Renders the agglomerative similarity dendrogram with singleton-peel chains contracted into multifurcating nodes (so a kinase that peels off attaches directly to its clade), above a per-node conservation logo that updates on tap. In the logo, letter height is the consensus frequency and color encodes novelty relative to the parent clade (region color = newly conserved/changed, black = inherited, grey = below threshold). Tree branches are colored by family while a clade is monophyletic (lipid > pseudokinase > Manning group) and grey once mixed; split nodes are filled by whether they carry a fixed-difference breakpoint. All per-node data is precomputed and embedded, so the HTML needs no server.
Panel-only view built on
KLIFSHierarchicalConservation(no cohort data);save_appwrites a self-contained HTML file to the structured output tree.- _family_types() tuple[list[str], dict[int, str | None], dict[str, str]][source]
Per-leaf family label and per-node subtree purity, with a color map.
Returns:
- tuple[list[str], dict[int, str | None], dict[str, str]]
(leaf_types, node_type, type_colors)whereleaf_types[i]is the leaf’s family (lipid > pseudokinase > Manning group),node_type[nid]is the subtree’s pure family orNoneif mixed, andtype_colorsmaps a family to its color.
- build_layout()[source]
Assemble the Bokeh layout (logo, legend, dendrogram) with tap interactivity.
Returns:
- bokeh.models.LayoutDOM
The column layout ready for
bokeh.embed.file_html().
- logo_cutoff: float
Minimum consensus frequency for a residue to appear in the per-node logo.
- min_cluster_size: int
Subtrees with fewer members collapse to a single tappable bar.
- name_trunc: int
Max items shown in a tooltip field before truncation.
- save_app(output_path: str, filename: str | None = None) None[source]
Build the explorer and write a self-contained HTML file to
output_path.- Parameters:
output_path (str) – Directory to write the HTML file into.
filename (str | None, optional) – Output filename; defaults to
STR_FILE_TREE_APP.
- mkt.databases.conservation.LIST_DOT_ALPHABET = ['A', 'R', 'N', 'D', 'C', 'E', 'Q', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'V', '-']
The 20 amino-acid single-letter codes plus the gap symbol, for the dot-plot amino-acid selector.
- Type:
list[str]
- mkt.databases.conservation.LIST_RESIDUE_DOT_KINASES = ['EGFR', 'BTK', 'FGFR1', 'FGFR2', 'FGFR3', 'FGFR4']
Clinically relevant kinases of interest whose covalent-targetable residues are called out on the static dot plot. Columns are not hardcoded: every KLIFS column where at least
INT_RESIDUE_DOT_MIN_SHAREDof these kinases carry the plotted residue is boxed (_annotation_callouts()), with kinases sharing a homologous column grouped in one box. For cysteine this captures all of these kinases’ pocket cysteines – FGFR1-4 at g.l:7 and VI:66, EGFR C797 / BTK C481 at linker:52, plus the singletons EGFR C775 (b.l:36), FGFR4 C552 (hinge:47), and BTK C527 (VII:76) – and tracks the current KLIFS mapping.- Type:
list[str]
- mkt.databases.conservation.STR_BLOSUM_MATRIX = 'BLOSUM62'
Substitution matrix name (Bio.Align.substitution_matrices) for the default metric.
- Type:
str
- mkt.databases.conservation.STR_FILE_CONSERVATION_TREE = 'klifs_conservation_tree'
Output basename for the static KLIFS conservation-tree figure.
- Type:
str
- mkt.databases.conservation.STR_FILE_CONSERVATION_TREE_BOTTOM = 'klifs_conservation_tree_bottom'
Output basename for the bottom (second-half) detail panel.
- Type:
str
- mkt.databases.conservation.STR_FILE_CONSERVATION_TREE_SUMMARY = 'klifs_conservation_tree_summary'
Output basename for the horizontal summary dendrogram.
- Type:
str
- mkt.databases.conservation.STR_FILE_CONSERVATION_TREE_TOP = 'klifs_conservation_tree_top'
Output basename for the top (first-half) detail panel.
- Type:
str
- mkt.databases.conservation.STR_FILE_RESIDUE_DOT = 'conservation_residue_dotplot'
Output basename for the static per-amino-acid KLIFS dot-plot figure.
- Type:
str
- mkt.databases.conservation.STR_FILE_RESIDUE_DOT_APP = 'conservation_residue_dotplot.html'
Output filename for the interactive per-amino-acid KLIFS dot-plot explorer.
- Type:
str
- mkt.databases.conservation.STR_FILE_TREE_APP = 'conservation_tree_explorer.html'
Output filename for the interactive KLIFS conservation-tree explorer.
- Type:
str
- mkt.databases.conservation.STR_LINKAGE_AVERAGE = 'average'
UPGMA linkage — standard for sequence trees (primary).
- Type:
str
- mkt.databases.conservation.STR_LINKAGE_COMPLETE = 'complete'
Complete linkage — tighter, more compact clusters (contrast).
- Type:
str
- mkt.databases.conservation.STR_METRIC_BLOSUM = 'blosum'
Name of the substitution-score similarity metric (Metric A, default).
- Type:
str
- mkt.databases.conservation.STR_METRIC_IDENTITY = 'identity'
Name of the percent-identity distance metric (Metric B, baseline).
- Type:
str
- mkt.databases.conservation.STR_RESIDUE_DOT_DEFAULT_AA = 'C'
Default amino acid for the static dot-plot figure (cysteine).
- Type:
str
- mkt.databases.conservation.STR_WEIGHTING_HENIKOFF = 'henikoff'
Henikoff (1994) position-based sequence weighting for the per-node consensus.
- Type:
str
- mkt.databases.conservation.STR_WEIGHTING_NONE = 'none'
Unweighted per-node consensus (every member counts equally, default).
- Type:
str
- mkt.databases.conservation.TUP_TREE_PAGE = (8.5, 11.0)
Figure size in inches (US letter, portrait).
- Type:
tuple[float, float]
- mkt.databases.conservation.TUP_TREE_SUMMARY_PAGE = (11.0, 5.0)
Figure size (inches) of the horizontal summary dendrogram.
- Type:
tuple[float, float]
- class mkt.databases.conservation._HandlerRoundedBox(patch_func=None, **kwargs)[source]
Bases:
HandlerPatchLegend handler that renders a
Patchhandle as a rounded box (matching the dot-plot clade enclosures) rather than a sharp rectangle.- create_artists(legend, orig_handle, xdescent, ydescent, width, height, fontsize, trans)[source]
Return the legend artists generated.
- Parameters:
legend (~matplotlib.legend.Legend) – The legend for which these legend artists are being created.
orig_handle (~matplotlib.artist.Artist or similar) – The object for which these legend artists are being created.
xdescent, ydescent, width, height (int) – The rectangle (xdescent, ydescent, width, height) that the legend artists being created should fit within.
fontsize (int) – The fontsize in pixels. The legend artists being created should be scaled according to the given fontsize.
trans (~matplotlib.transforms.Transform) – The transform that is applied to the legend artists being created. Typically from unit coordinates in the handler box to screen coordinates.
- mkt.databases.conservation._KLIFS_PANEL = ([], [], [])
cached (names, pockets, groups) KLIFS panel.
- Type:
tuple[list[str], list[str], list[str]]
- mkt.databases.conservation._build_klifs_panel(dict_kinase: dict = {}, int_length: int = 85) tuple[list[str], list[str], list[str]][source]
Collect the gapless KLIFS pocket panel for hierarchical clustering.
Iterates
DICT_KINASE, keeping kinases with a valid fixed-width pocket string and recording their Manning group for the concordance check. Kinases without a pocket, or whose pocket is the wrong length, are skipped with a log warning.Parameters:
- dict_kinasedict
Mapping of HGNC name to
KinaseInfo(default:DICT_KINASE).- int_lengthint
Required pocket length (default:
INT_KLIFS_POCKET_LENGTH).
Returns:
- tuple[list[str], list[str], list[str]]
Parallel lists of
(names, pockets, manning_groups).
- mkt.databases.conservation._repair_camkk1_pocket(dict_kinase: dict) None[source]
Temporary shim: fix CAMKK1’s off-by-one KLIFS mapping in place.
The cached
DICT_KINASEcarries a mis-curated CAMKK1 (UniProt Q8N5S9) KLIFS mapping. These indices are read 1-based (residue== canonical_seq[idx - 1]), and every CAMKK1 entry is one too low – so each position lands on the residue before the intended one (e.g. I:1 -> Q instead of S, and the catalytic columns onto non-catalytic residues). The off-by-one is uniform, so we:KLIFS2UniProtIdx: add 1 to every non-None entry. This realigns all positions, including the residues that flank the large alpha-C/beta-4 insert (II:13, IV:41, …) – a “shift each value to the preceding key” shortcut would mis-map exactly those, since the indices jump across the insert.pocket_seq: rebuild from the corrected indices (canonical_seq[idx - 1]), restoring the catalytic III:17=K / c.l:70=D / xDFG:81=D.KLIFS2UniProtSeq(keyed by full region, incl. inter-region inserts absent from the 85-position index): shift the gathered residue stream left by one and append the newly revealed trailing residue, skipping None regions.
Stopgap until the kinase dict is regenerated with the upstream root-cause fix; the
mkt.databaseschange_wrong_klifs_pocket_seqoverride currently patches onlypocket_sequpstream, so the regenerated indices will still need the root fix.- Parameters:
dict_kinase (dict) – The deserialized
DICT_KINASEmapping, modified in place.- Return type:
None
- mkt.databases.conservation.load_conservation_renderer(cls, **kwargs)[source]
Build a conservation renderer from the shipped
KLIFSConservationData.Deserializes the packaged artifact (via
mkt.schema.io_utils.load_conservation_data()) and injects its distances + linkage intoclsthroughKLIFSHierarchicalConservation.from_conservation_data(), so no clustering is recomputed. If the artifact is not found, falls back to buildingclsfrom the live KLIFS panel with a warning (rungenerate_conservation_datato persist it).- Parameters:
cls (type[KLIFSHierarchicalConservation]) – The renderer (sub)class to instantiate.
**kwargs – Renderer-specific keyword arguments forwarded to the constructor.
- Returns:
An instance of
cls.- Return type:
- mkt.databases.conservation.rebuild_tree_from_data(data: KLIFSConservationData) ClusterNode[source]
Reconstruct the SciPy hierarchical tree from a persisted artifact.
The scipy bridge for
KLIFSConservationData: consumers holding only the schema (which is scipy-free) call this inmkt.databasesto recover the fullClusterNodetree from the stored linkage matrix.- Parameters:
data (KLIFSConservationData) – The persisted conservation-data artifact.
- Returns:
Root node of the reconstructed hierarchical tree.
- Return type:
scipy.cluster.hierarchy.ClusterNode