khipu: generalized tree structure to annotate untargeted metabolomics and stable isotope tracing data

Pre-annotation tool to annotate degenerate ions in relationships to the original compound and infer neutral mass. The initial version was described in Li and Zheng (2023). Analytical chemistry, 95(15), pp.6212-6217.
This applies to regular LC-MS data, but also enables easy analysis of isotope tracing and chemical labeling data. Different applications may require different parameters. A web server for isotope tracing data (described in [Mitchell et al (2024) Journal of the American Society for Mass Spectrometry. https://doi.org/10.1021/jasms.4c00175]) is now available at https://metabolomics.cloud/khipu/.
The detectable khipu model explained the metabolomics “dark matter” (Chi, et al (2026). Metabolomics, 22(3), p.79, https://link.springer.com/article/10.1007/s11306-026-02456-y). The paper included lists of in-source fragments, now available in this package.
Implementation overview
Khipu is developed as an open source Python 3 package, and available to install from the standard PyPi repository via the pip tool. It is freely available on GitHub (https://github.com/shuzhao-li/khipu) under a BSD 3-Clause License. The graph operations are supported by the networkx library, tree visualization aided by the treelib library. Khipu uses our package mass2chem for search functions. The data model of “empirical compound” is described in the metDataModel package. The package is designed in a modular way to encourage reuse.
The classes of Weavor and Khipu contain main algorithms, supported by numerous utility functions. All functions are documented in the source via docstrings. Examples of reuse are given in wrapper functions and in Jupyter notebooks. It can be run as a standalone command line tool. Users can use a feature table from any preprocessing tool as input and get annotated empirical compounds in JSON and tab delimited formats.
Installation and Use
Install as a package (some systems may require pip3):
pip install khipu-metabolomics
Optional extras, installed only when needed:
pip install "khipu-metabolomics[tracing]" # natural abundance correction (khipu.analysis, isocor)
pip install "khipu-metabolomics[plot]" # khipugram plots with matplotlib (khipu.plot)
pip install "khipu-metabolomics[viz]" # dashboard of khipugrams in a web browser (khipu --viz)
pip install "khipu-metabolomics[all]" # all of the above
The core package (pre-annotation, the CLI and the JSON/TSV outputs) needs none of them,
e.g. when khipu is deployed in a web app.
Run as a command line tool after installation:
khipu -i testdata/ecoli_pos.tsv -o this_test --workflow tracing
This will output pre-annotation to two files of JSON and tab delimited formats, this_test.json and this_test.tsv.
In the outputs, neutral_formula_mass has 6 decimals and feature representative_intensity is an integer.
Run from source code:
python3 -m khipu.main -i testdata/ecoli_pos.tsv -o this_test --workflow tracing
Run the demo script:
python3 -m khipu.test
(This downloads and uses test data from GitHub.)
Run the test suite (from the repository root, offline):
pip install -e ".[test,all]"
pytest
The regression tests compare results on testdata/ against snapshots in tests/snapshots/.
If a change is meant to alter results, regenerate the snapshots and review the change:
python tests/regression_cases.py --update
python tests/test_api_surface.py --update # only for intentional API changes
Best used as a library for software development or in a Jupyter Notebook for data analysis.
Dashboard of khipugrams
After a khipu run, browse the khipugrams of all khipus in a web browser:
pip install "khipu-metabolomics[viz]"
khipu --viz this_test.json
The input is the JSON output of khipu (also the empCpd JSON written by asari).
The dashboard steps through all khipus (play, step, or go to a number), and searches khipus
by neutral mass, by formula (annotated formula, or neutral mass within ppm of the formula's
mass) or by the m/z of a member feature. The khipugram is interactive: hover over a feature
for its ID, m/z, retention time and intensity; zoom and pan. --port sets the port.
Khipugrams show only the rows (isotopologues) and columns (adducts) that have features;
in the library, only_occupied=False draws the full search grid.
The JSON records the grid of each khipu (khipugram: isotope rows and adduct columns),
used to draw khipugrams; for JSON from khipu 2 the grid is inferred from the features.
Features found by the extended search (e.g. M+H+,H2O) are exported with their khipu
(khipu >= 3); one such feature can belong to several khipus. JSON from khipu 2 lacks them,
so empty extended-search columns are not shown.
Two workflows: regular and tracing
khipu treats two kinds of data differently, selected by --workflow (as in asari):
regular (default): data with naturally occurring isotopes only.
Isotopes are searched up to 13C/12C*3.
tracing: isotope tracing, with purposely introduced isotopes (e.g. 13C labeled samples).
Isotopes are searched up to 13C/12C*12. Natural abundance correction in khipu.analysis
needs pip install "khipu-metabolomics[tracing]".
Rules specific to the regular workflow:
- Isotopologue intensities must decrease within each adduct, M0 > M1 > M2 > M3 ...
(Mn with n 13C atoms). An isotopologue that is not lower than the one below it, or whose
lower isotopologue is missing, is dismissed from the khipu. Dismissed features are
released and can seed new khipus.
--ratio additionally enforces the abundance ratio ranges of the isotope search patterns
(the third element, e.g. (0, 0.8) for 13C/12C) when isotope pairs are searched.
Both use peak height if available, otherwise the mean intensity.
Filtering can increase the number of khipus, as it breaks some khipus and lets new ones form.
To set the ranges, pass custom isotope_search_patterns to the khipu functions, e.g.
from khipu.ion_patterns import IsotopePattern
params = KhipuParameters(mode='pos', workflow='regular', check_isotope_ratio=True,
isotope_search_patterns=[IsotopePattern(1.003355, '13C/12C', (0, 0.5)),
IsotopePattern(2.00671, '13C/12C*2', (0, 0.2)),
IsotopePattern(3.010065, '13C/12C*3', (0, 0.1))])
In the tracing workflow, labeled isotopologues can have very different ratios, so --ratio
is ignored (with a warning). Filtering by isotope ratios, e.g. comparing labeled and
unlabeled samples (khipu.analysis.detect_labelling), is done after khipus are
constructed, as additional steps of data analysis.
khipu --list_workflows prints them. The old -r/--regular flag means --workflow regular.
The test data ecoli_pos.tsv are 13C labeled, so the example above uses --workflow tracing.
In the library, KhipuParameters(workflow=...) selects the default isotope patterns;
peaklist_to_khipu_list(..., workflow=None) keeps khipu 2 behavior unless a workflow is given.
Use as a library
from khipu.utils import read_features_from_text
from khipu.parameters import KhipuParameters
from khipu.extended import peaklist_to_khipu_list, export_empCpd_khipu_list
peaklist = read_features_from_text(open('testdata/yeast_neg.tsv').read(), intensity_cols=(3, 6))
params = KhipuParameters(mode='neg', mz_tolerance_ppm=5, rt_tolerance=2, workflow='regular')
khipu_list, assigned = peaklist_to_khipu_list(peaklist, **params.to_kwargs())
empCpds = export_empCpd_khipu_list(khipu_list)
KhipuParameters picks the adduct patterns for the ionization mode, unless given.
Search patterns are lists of IsotopePattern(mz_diff, name, ratio_range) and
AdductPattern(mz_diff, name) (see khipu/ion_patterns.py); plain tuples of the same
shape work too.
Demo notebooks
We have provided multiple demo notebooks under
notebooks/
They include algorithm demostrations, data analysis examples, use of custom isotope and adduct patterns.
Development notebooks are under notebooks/dev/.
Algorithm overview
-
Start with an initial list of isotope patterns and adduct patterns (see khipu grid below). Search feature list to get all pairs that match any of the pattern. The initial adduct patterns are trimmed to reduce ambiguity.
-
Connect all pattern-matched feature pairs to an overall network, which is further partitioned into connected subnetworks.
-
Each subnetwork becomes a khipu instance. The subnetwork is inspected, redundant nodes removed, and converted to an optimal tree structure (see below). A khipu is essentially an 'empirical compound' that is used for downstream annotation and analysis.
-
This library supports tree and grid visualization in plain text. Once imported to a Jupyter Notebook, one can use enhanced visualization schemes.
-
The library can also be used by others for extended tools. Our data processing tool, asari, uses khipu for preannotation. Additional documentation, more for developers, is in docs/source/developer.md.
Assignment of ion species in a khipu to grid
- Separate isotope edges and adduct edges.
- The isotope edges form their own groups by shared nodes, each group belong to one adduct type. Each group of connected isotope edges is treated as one "branch".
- Establish a "trunk" of adducts with a root and a path for adducts, by optimizing the number of nodes explained.
- Assign each isotopic branch to the adduct trunk.
- Re-align isotopes in all branches to establish optimal match to the khipu grid.
- Based on available ions and the theoretical "khipu grid", the neutral mass can be obtained via linear regression.
Some ions may come into the initial network by mistakes or unresolved signals.
The are removed from the established khipu, and sent off to form a new khipu.
The khipu grid
Initial grid may look like this:
M+H[+] M+NH4[+] M+Na[+] M+HCl+H[+] M+K[+] M+ACN+H[+]
M0 1.007276 18.033826 22.989276 36.983976 38.963158 42.033825
13C/12C 2.010631 19.037181 23.992631 37.987331 39.966513 43.037180
13C/12C*2 3.013986 20.040536 24.995986 38.990686 40.969868 44.040535
13C/12C*3 4.017341 21.043891 25.999341 39.994041 41.973223 45.043890
13C/12C*4 5.020696 22.047246 27.002696 40.997396 42.976578 46.047245
13C/12C*5 6.024051 23.050601 28.006051 42.000751 43.979933 47.050600
13C/12C*6 7.027406 24.053956 29.009406 43.004106 44.983288 48.053955
This can be extended by searching for additional ions. But the core construction should be done first.
Applicable to isotope tracing
The search pattern for isotopes is often dependent on the biochemical experiment.
Users can overwrite the default by supplying their search patterns (see demo notebooks).
Search patterns are separate from search functions, lending flexibility to data analysis.
The next step is to apply Khipu to chemical derivatization experiments.
In chemical derivatization experiments, the origin compound and derivatized compound can be both measured in the LC-MS data.
We have separate khipu trees for each, then link them by the m/z shift from derivatization.
Because derivatization is a reaction that occurs before LC-MS, and
LC-MS measures whatever compounds that are present in samples.
Test data
Three datasets are included under testdata/. All three tables were generated by asari v1.9.2.
The automated khipu.test downloads ecoli_pos.tsv from GitHub remotely.
- The ecoli_pos.tsv was generated by Li lab using the credentialed E. coli sample from Cambridge Isotopes.
- The yeast datasets were from the NetID paper by Rabinowitz lab. The yeast_neg table is features that are filted by SNR > 100 to serve as a cleaner demo.
Input tables are tab delimited text files.
The first columns are feature ID, m/z, rtime, followed by intensities.
Users can specify the start column and end column of intensity data.
Detailed use of command and parameters
>>> khipu -h
usage: khipu [-h] [-v] [-m {pos,neg}] [--ppm PPM] [--rtol RTOL] [-i INPUT]
[-s START] [-e END] [-o OUTPUT] [--workflow WORKFLOW]
[--list_workflows] [-r] [--ratio [RATIO]] [--viz RESULTS_JSON]
[--port PORT] [--log LOG]
khipu, annotating metabolomics features to empCpds
options:
-h, --help show this help message and exit
-v, --version print version and exit
-m, --mode {pos,neg} mode of ionization, pos or neg
--ppm PPM mass precision in ppm (part per million), same as
mz_tolerance_ppm
--rtol RTOL tolerance of retention time match, arbitrary unit
dependent on preprocessing tool
-i, --input INPUT input file as feature table
-s, --start START start column for intensity in input table
-e, --end END end column for intensity in input table
-o, --output OUTPUT prefix of output files
--workflow WORKFLOW regular (natural isotopes only, default) or tracing
(isotope tracing, e.g. 13C labeled samples); see
--list_workflows
--list_workflows print available workflows and exit
-r, --regular same as --workflow regular (the default; kept for
compatibility)
--ratio [RATIO] regular workflow only: enforce the abundance ratio
ranges of the isotope search patterns; `--ratio` or
`--ratio true`. Ignored for tracing
--viz RESULTS_JSON open a dashboard of khipugrams for khipu results (the
.json output); needs pip install "khipu-
metabolomics[viz]"
--port PORT port for --viz (default: any free port)
--log LOG file for diagnostic messages (default khipu.log)
What's "khipu"?
Khipu is a recording device using knots, often 2-level of strings,
historically used by people in Andean South America, includign Inca (https://en.wikipedia.org/wiki/Quipu).
The format is similar to how we represent isotopes and adducts in our data.
We chose "khipu" over the spelling of "quipu", to pay respect to the indigenous people.
Khipu is part of The Asari Project.