APB2 converter architecture
APB2 compiles one effective rule per quantification level. A bound parser reads a vendor table and returns one ParsedLevel with keyed observation and feature axes and long measurement layers. A ParserCollection assembles those levels into ParsedLevels, the value shared by the H5AD, H5MU, Parquet and DuckDB adapters.
Design decisions
| Decision | Reason |
|---|---|
| Compile rules into executable operations before reading quantities | Resolve vendor, layout, optional columns and dtypes once, where the evidence is available. Keep the authored rule and plan snapshots for provenance |
| Keep semantic identity in explicit axis key columns | Coercion and sequence normalization can collapse distinct source keys. The axes retain enough evidence to detect and report that collision |
| Store layer cells as long rows with integer axis coordinates | Share the same coordinate columns across layers, reduce repeated cells before widening, and allocate dense values one block at a time |
| Use concrete Polars dataframes and expressions | The workload benchmark favored Polars for reading and grouping. The parser uses its stable joins, ordered groups and projected reads directly |
| Parse once, then write the resulting value | The V5 conversion sketch called parsing a second time during writing. The storage boundary lets the CLI choose an adapter after parsing and lets reformat reuse the same adapters |
| Persist both structural and semantic layer roles | Structural roles define which layers take part in occupancy checks. Semantic roles such as abundance let consumers find quantities by meaning. The rule's primary layer determines X |
| Keep storage projection in the adapters | AnnData needs string storage indexes, compatible dtypes and matrices in observation-by-feature order. Those choices belong to HDF5 I/O. The Parquet directory and DuckDB preserve ordered tables and their schemas |
On 24 October 2026, the parser switched from widening raw text layers before alignment to keeping cells in long rows with axis coordinates. Writers and the sidecar adopted blockwise widening on 26 October. Readers adopted per-level parking on 27 October. Layer blocks · Layer parking
Performance measurements
The engine benchmark measured a nine-column TSV read followed by axis and layer operations. The scatter row belongs to that benchmark's dense workload. The current parser returns long cells.
| Step | Polars 1.43 | pandas 3.0 + PyArrow | pandas 3.0 conventional |
|---|---|---|---|
| Read TSV, 9 columns | 0.107 s | 1.980 s | 1.945 s |
| Build axis keys | 0.005 s | 0.038 s | 0.086 s |
| Factorize | 0.027 s | 0.056 s | 0.054 s |
| Scatter to three dense layers | 0.008 s | 0.013 s | 0.004 s |
| Deduplicate axis frames | 0.008 s | 0.039 s | 0.032 s |
| Total | 0.155 s | 2.130 s | 2.120 s |
On this workload pandas with PyArrow took about 13.7 times as long as Polars. The TSV read accounted for most of the difference.
The wide-text ion parser peaked at 41.3 GB for 7.4 GB of final layers on a 150-run subset of a 1,236-run DIA-NN report. Dense text used 16 bytes per cell even though 89% of cells were empty at full size. An alignment join copied the wide layer, and a protein with 2,671 source rows in one run occupied space for those repeats before they collapsed. Keeping cells long moved duplicate resolution ahead of widening. The first long implementation reduced the write peak from 21.8 GB to the size of one layer and its array on the 150-run subset.
| Change and workload | Earlier footprint | Later footprint |
|---|---|---|
| Read repeated axis strings as categoricals, 150-run DIA-NN ion report with 9 million rows | 7.2 GB | 3.7 GB |
| Convert 17 numeric layers inside the streaming scan, read stage of the 150-run ion report | 3.4 GB | 2.0 GB |
| Replace the mapping join in numeric text processing with elementwise expressions, 150-run TPCPA ion layers | 7.7 GB | 2.7 GB |
| Assign row numbers before fragment expansion, 50 runs of DIA-NN 1.8 with 3.4 million precursor rows and 20.3 million fragment rows | 11.1 GB | 8.7 GB |
| Explode numeric values, use an integer fragment-axis key and check duplicates in ranges, 150 runs with 9 million precursors and 54 million scalars | 18.0 GB | 9.3 GB |
| Repeat that combined change on the 50-run fragment case | 6.6 GB | 4.7 GB |
These pairs measure different stages and implementation revisions. A full wide fragment layer for 2.8 million features and 1,236 runs is 27.6 GB. Writers now target about 1 GiB of wide values per block. Readback of the 1,236-run TPCPA result held 2.3 billion cells in 36 GB of process memory before readers parked each level. Parking sorts layer cells by feature and observation position, writes uncompressed Arrow IPC, memory-maps it and unlinks the backing file. Future timing comparisons should record the fixture size, machine, warm-up, Polars version, wall time by stage and peak memory.
Rule compilation and source binding
Schema 0.11 defines table groups with input, base, levels and optional prepare. A level belongs to one group. Composition expands table defaults, source prefixes and wide sample placeholders, then validates the effective rule. The authored final keys belong to axis. Ordered sourced or computed outputs belong to columns. The primary layer, repeated-cell policy and layer declarations belong to measurements. The primary layer's source is required. Version-tagged entries select the available source from the header and check that the parsed software version, when supplied, admits that entry. Rule authoring
ParseRuleCompiler.detect() selects a vendor parameter parser using an explicit software choice or header evidence, reads typed parameters and binds compatible levels. Tools that require two files, including MetaMorpheus and quantms, take a tuple of paths or repeated --params options. Quantms reads a versions YAML and a Nextflow params JSON in either order. Rule conditions receive only the evidence fields acquisition_method and combine_charge_states. The full parameter record remains available to the caller and enters root parse provenance alongside one input record per parameter file. Parameter-free selection uses header signatures, and an explicit rule bypasses packaged rule recognition. A level's forbidden_columns can rule it out independently of other levels.
ParseRuleFacade projects one effective rule to WorkingParseConfiguration, including configured computed-column operations. SourcePlanResolver binds it using the observed header, notation and dtypes. The resolver derives the column projection, builds the two axis phases, and chooses decomposition, duplicate handling, value parsing and validation. Format selection belongs to result I/O, and the strictness setting applies during binding. Detection retains the bound parsers that pass these checks. compile() assembles them into a collection. The saved rule_json and plan_json capture the effective rule and binding decisions. Execution uses the configured operations. Compiler · Source resolution
Direct levels read separate projections. A prepared group reads and reshapes its inputs once, then each level projects the shared table. A hook can join separate files, join named workbook sheets, or bring a different source shape to the declared hierarchy level. For mzTab, the reader binds from the first section header and stacks namespaced long rows for the represented section and sample axes. Explicit file names identify direct tables in a vendor folder. Header compatibility can identify renamed files. Competing interpretations that satisfy the same rule raise a binding error. Optional columns and blocked computations are resolved at binding. Operations such as coalesce keep available inputs when the rule permits it. Preparation
The delimited read plan sets explicit dtypes. Raw-key inputs such as 01 and 1, sequence evidence, factors and structured tokens retain their lexical values. Repeated axis strings can use categorical codes internally. Plain numeric sources that do not need lexical preservation can be converted in the streaming scan. A column containing unreadable text or the literal NaN is reread as text so the layer parser can preserve its diagnostics and NaN behavior. Numeric aggregation sources receive numeric dtypes when the source supports them. Parquet retains its native source schema. The numeric notation resolved during binding is shared by axis coercion, layer presence checks and value parsing. A projected or lazy aggregation over the source touches only its own columns. An eager group-by on the 150-run TPCPA ion table would rechunk the layer columns as well, which accounted for 2.3 GB in that run.
Decomposition and identity
The raw axes use the physical dependency closure of the authored final keys. This includes every input that can change a normalized sequence, already-resolved wide captures and any synthesized fragment label. Each distinct raw tuple owns one row in first-appearance order. A missing raw component stays available to operations such as coalesce. Final validity is checked after computation.
For an AlphaDIA v1.10 ion, the raw var key uses sequence, mods, mod_sites and charge. The final key is ProForma_ion, computed from ProForma_peptidoform and charge. The same dependency walk derives a direct DIA-NN protein key from Protein.Group and adds a synthesized fragment label when the final key uses one.
- In long input, one ordered join per axis assigns
var_rowandobs_rowusing the raw key columns, with null keys comparing equal. Each layer shares those position columns and retains its own value column. - In wide input, the primary layer defines the observation order from matching headers. Other layers use that sample axis. Columns that claim the same sample repeat cells in header order and then file order. A required layer with no physical match makes the level incompatible. A required layer whose columns match only non-primary samples gives no rows on the primary grid.
- Packed fragments first validate aligned token counts, then assign row numbers on precursor rows and expand the values. Interior empty tokens keep their positions. Positional labels are
frag_0,frag_1and so on. Column labels use the token before the first/. A rule with an optional label column can fall back to positional labels. The resulting layers use the ordinary long representation. Null or blank packed cells yield zero tokens, and trailing delimiter terminators are removed before splitting.
Observation payload keeps its first physical row. Feature payload follows per_feature. The first mode keeps the first nonblank value and reports disagreements. The min and max modes select the source value at the numerical extreme. The best_row mode uses the required numeric column in rank_rows, with ties in file order. The winning feature's ranked values identify the rows to keep across runs, so the feature table and layers use the same selection.
Axis preparation runs the key phase on the small raw axes. It computes canonical keys and records diagnostic-producing sequence operations here, including diagnostics from rows that later drop out. A preserve policy for unknown modifications keeps the token in the sequence and records it once in first-observed order. An incomplete final key removes its row and any layer cells pointing to it. Distinct raw tuples that produce one valid final key raise CanonicalKeyCollisionError with raw-key evidence. The output phase then adds the remaining metadata in order. FinalPositions maps retained raw rows to their final axis offsets. Decomposition · Axis preparation and placement
Repeated cells and layer values
Each placed layer row carries var_pos, obs_pos and the source value. present() masks absent values before duplicate handling. The presence check uses the layer's missing tokens, numeric sentinels and thresholds where configured. A nonblank token that cannot be parsed may still claim its position, so the duplicate policy cannot silently skip it. Duplicate resolution processes only the rows whose coordinate pair repeats. Value parsing then interprets the retained scalars using the declared numeric, regex or factor semantics and records unreadable tokens.
repeated_cells mode |
Behavior |
|---|---|
error |
Reject a second row for a cell, including a row with an absent value |
same |
Keep the shared non-null value. Reject differing present values |
sum |
Sum numeric contributions. Keep all-missing cells null |
keep_best |
Rank once by the named layer. Prefer a present rank, with ties in file order. Copy the winning row across layers, including its absent values. Layers listed in sum add all contributions |
Every claimed ranking value must be numeric, including one in a cell with only one row. Layers copied from the winner must have the same repeated positions in the same order as the ranking layer. Source compilation checks that summed layers can provide numeric inputs. The aggregate guards the dtype again at execution. Feature-payload selection and repeated-cell reduction happen at separate stages. The former chooses axis values, and the latter works on one measurement cell at a time. Duplicate policies
Parse-time validation checks the required names and compares occupancy among measurement layers. A layer below the configured empty ratio is effectively empty when another measurement layer reaches the populated ratio. Standard checks raise for the primary and record other effectively empty layers. Strict checks raise for any effectively empty measurement layer. Pruning removes eligible empty and effectively empty fields and fields with the same value in at least two cells when every cell is filled. A constant value mixed with missing cells passes the constant-field check. Keys, role columns, computed columns, flag inputs and the primary and sample layers are retained by the pruner. Pruning rules
Result model and serialization
FinalLayerTable stores cells at final positions with the feature count, observation labels, roles and value semantics. A missing coordinate reads as null for numeric layers or as the configured missing code for factors. Positional labels such as obs_0 are unique and avoid var-key column names. They locate columns in a wide view. The corresponding rows and key columns in obs identify observations. wide() builds the full view on request. Writers use blocks of feature rows, and the JSON sidecar uses blocks of observation columns.
ParsedLevel also carries aligned obsm and varm frames and sparse obsp and varp coordinates. Aligned frames follow the associated axis order. Pairwise frames use unique zero-based row and column coordinates. ParsedLevels adds the hierarchy, common provenance, annotation tables and feature relations. A conversion lists featureless levels under levels_without_features and records each input file once. ParsedLevels.observation_groups() aligns observation axes when it finds an explicit complete bijection, and the CLI writes each incompatible group separately. Result model · Output naming
| Format | Result contract |
|---|---|
| Parquet | A directory with an explicit manifest for ordered tables, dtypes, keys, roles and mapped physical names. Each layer is written in feature-row blocks |
| DuckDB | One database with a versioned manifest and generated physical names. Reads and writes preserve ordered tables and dtypes, including null versus NaN |
| H5AD | Exactly one level. The file root holds the root metadata and the level's named part holds level metadata |
| H5MU | One or more modalities. Each modality has its own feature axis and level metadata. Storage var names receive modality prefixes by default |
HDF5 writes observations as rows and features as columns, with the primary layer stored exclusively in X. A single string key can serve as the storage index. Other keys use a JSON array of type and value pairs, leaving the authored keys as ordinary axis columns. The physical matrix can merge numeric nulls with NaN. Stored layer semantics restore integer and category values on readback. Parquet and DuckDB round trips preserve the canonical result. HDF5 round trips preserve its matrix projection.
Writers validate keys, cell coordinates, dtypes, aligned slots and metadata before staging. They publish the result atomically in its target format. write_parsed_levels() selects the writer by suffix and publishes the JSON sidecar after the result write succeeds. Readers keep stored cells from slabs of HDF5 feature columns or batches of Parquet and DuckDB feature rows. A single-level read also returns annotation tables and the feature relations whose ends are present. The reformat command reads a ParsedLevels and writes it through the target adapter. Format contracts · Metadata specification
The same entry points serve the CLI and library callers.
from pathlib import Path
from apb2.api import ParseRuleCompiler, write_parsed_levels
parser = ParseRuleCompiler.detect(
report_path,
parameter_source,
requested_levels=("peptidoform_ion",),
checks="standard",
).compile()
parsed = parser.parse()
write_parsed_levels(parsed, Path("peptidoform_ion.h5ad"))
Package boundaries and verification
Parent modules compose vendor_parse_rules, vendor_params, joins and parse_quant, which all sit above search_parameters. Rule validation lives in the rule package. Vendor grammar dispatch lives in the parameter registry. The parent facade and resolver construct the computation, and the candidate source binds its reader. The parser consumes its own capability contracts in parse_quant/contracts.py. The only sibling edge inside parse_quant runs from io to data. parameters stays independent. Child packages import downward, and each child can directly depend on at most one sibling. Parent modules own work that composes multiple children. Computation consumes Polars values and bound operations, while result adapters own their backend dependencies. CLI and sibling packages use apb2.api. Import contracts
Parity cases should exercise both the common pipeline and the format boundaries. The schema and source tests cover prepared inputs, header ambiguities and effective rules. Parser tests cover stable axis order, colliding canonical keys, packed lengths, all repeated-cell modes and missing values. Result tests cover ordered keys, dtypes, layers and provenance, including format crossings and preservation of the target on validation failure. For the Rust port, run the same fixtures through both implementations against APB2's current HEAD. Compare axis order, value and missingness, and diagnostics before serialization. For files, compare both columns and metadata after readback, accounting for the HDF5 projection. Physical-input tests · Result-format tests