From da5dd6990a83df7e8d10f4bffa791740a165a252 Mon Sep 17 00:00:00 2001 From: Alex Rubinsteyn Date: Wed, 18 Nov 2026 21:01:50 -0500 Subject: [PATCH 1/5] Make the --gene-expression help example yield gene_tpm The leading name in an expression spec is a column prefix, so the documented gene_tpm:quant.sf:Name:TPM produced gene_tpm_tpm while the --filter-by hints use gene_tpm. Show gene:quant.sf:Name:TPM, state the {name}_{column} rule, and test that every help example composes with the documented filter. Closes #571. Claude-Session: https://claude.ai/code/session_01JHJhwjJyLksFkmysWFgmhP --- docs/expression.md | 5 +++ tests/test_expression_integration.py | 64 ++++++++++++++++++++++++++++ topiary/cli/rna.py | 6 ++- topiary/rna/expression_loader.py | 8 +++- 4 files changed, 80 insertions(+), 3 deletions(-) diff --git a/docs/expression.md b/docs/expression.md index 9abc90cd..92c8e10b 100644 --- a/docs/expression.md +++ b/docs/expression.md @@ -67,6 +67,11 @@ both lowercased: | `--transcript-expression abundance.tsv` | Kallisto | `tpm` | `transcript_tpm` | | `--variant-expression isovar.tsv` | generic | `num_alt_reads` | `variant_num_alt_reads` | | `--gene-expression mygene:quant.sf` | Salmon | `TPM` | `mygene_tpm` | +| `--gene-expression gene:quant.sf:Name:TPM` | Salmon | `TPM` | `gene_tpm` | +| `--gene-expression gene_tpm:quant.sf:Name:TPM` | Salmon | `TPM` | `gene_tpm_tpm` | + +The name is a prefix, not the finished column name: to filter on `gene_tpm`, +name the source `gene` (or leave the name out), not `gene_tpm`. ### Transcript selection diff --git a/tests/test_expression_integration.py b/tests/test_expression_integration.py index fe6e2189..bdd9c9e5 100644 --- a/tests/test_expression_integration.py +++ b/tests/test_expression_integration.py @@ -186,3 +186,67 @@ def test_expression_transform_repr_roundtrip(): df = _make_prediction_df() df["gene_tpm"] = [42.5, 42.5, 15.3] assert abs(expr.evaluate(df) - expr2.evaluate(df)) < 1e-9 + + +# --------------------------------------------------------------------------- +# The documented CLI examples produce the column the filter hints name (#571) +# --------------------------------------------------------------------------- + + +def _gene_expression_help_examples(): + """Every ``--gene-expression SPEC`` example in that option's help text.""" + import re + + from topiary.cli.args import create_arg_parser + + parser = create_arg_parser() + action = next( + action for action in parser._actions + if "--gene-expression" in action.option_strings + ) + return re.findall(r"--gene-expression (\S+)", action.help) + + +def test_gene_expression_help_examples_yield_the_gene_tpm_filter_column(): + import os + + from topiary.cli.args import create_arg_parser + from topiary.cli.rna import expression_data_from_args + from topiary.ranking import apply_filter + + salmon = os.path.join(os.path.dirname(__file__), "data", "salmon_quant.sf") + examples = _gene_expression_help_examples() + assert len(examples) == 2 + for example in examples: + parts = example.split(":") + file_index = next(i for i, part in enumerate(parts) if part.endswith(".sf")) + parts[file_index] = salmon + args = create_arg_parser().parse_args( + ["--gene-expression", ":".join(parts)] + ) + result = _attach_expression_data( + _make_prediction_df(), expression_data_from_args(args), + ) + assert "gene_tpm" in result.columns, example + assert "gene_tpm_tpm" not in result.columns, example + # The deprecated --rna-min-gene-expression help and the --filter-by + # examples both point at this exact expression. + kept = apply_filter(result, parse("gene_tpm >= 20")) + assert set(kept["gene_id"]) == {"ENSG00000157764"}, example + + +def test_gene_expression_name_is_a_prefix_not_a_column_name(): + import os + + from topiary.cli.args import create_arg_parser + from topiary.cli.rna import expression_data_from_args + + salmon = os.path.join(os.path.dirname(__file__), "data", "salmon_quant.sf") + args = create_arg_parser().parse_args( + ["--gene-expression", f"gene_tpm:{salmon}:Name:TPM"] + ) + result = _attach_expression_data( + _make_prediction_df(), expression_data_from_args(args), + ) + assert "gene_tpm_tpm" in result.columns + assert "gene_tpm" not in result.columns diff --git a/topiary/cli/rna.py b/topiary/cli/rna.py index 44eb2da1..54edf851 100644 --- a/topiary/cli/rna.py +++ b/topiary/cli/rna.py @@ -18,6 +18,9 @@ def add_expression_args(arg_parser): "Load expression quantification to annotate predictions. " "Values become columns accessible in --filter-by and --sort-by. " "Format: [name:]file[:id_col[:val_col]]. " + "The name is a column prefix, not a column name: each value " + "column becomes {name}_{column} in lower case, so the default " + "name 'gene' and a TPM column give 'gene_tpm'. " "Common formats (Salmon .sf, Kallisto abundance.tsv, RSEM, " "StringTie .gtf, Cufflinks .fpkm_tracking) are auto-detected." ), @@ -30,7 +33,8 @@ def add_expression_args(arg_parser): help=( "Gene-level expression file, joined on gene_id. " "Example: --gene-expression salmon_quant.sf " - "or --gene-expression gene_tpm:quant.sf:Name:TPM" + "or --gene-expression gene:quant.sf:Name:TPM " + "(both add the column 'gene_tpm')" ), ) expr_group.add_argument( diff --git a/topiary/rna/expression_loader.py b/topiary/rna/expression_loader.py index d11b8363..7ab42425 100644 --- a/topiary/rna/expression_loader.py +++ b/topiary/rna/expression_loader.py @@ -248,10 +248,14 @@ def parse_expression_spec(spec): Formats: "file.tsv" → (None, "file.tsv", None, None) - "gene_tpm:file.tsv" → ("gene_tpm", "file.tsv", None, None) - "gene_tpm:file.tsv:Name:TPM" → ("gene_tpm", "file.tsv", "Name", "TPM") + "gene:file.tsv" → ("gene", "file.tsv", None, None) + "gene:file.tsv:Name:TPM" → ("gene", "file.tsv", "Name", "TPM") "file.tsv:Name:TPM" → (None, "file.tsv", "Name", "TPM") + The name is a column *prefix*: joined values land in + ``{name}_{column}`` (lower case), so ``gene:file.tsv:Name:TPM`` adds + ``gene_tpm`` while ``gene_tpm:file.tsv:Name:TPM`` adds ``gene_tpm_tpm``. + Returns (name, filepath, id_col, val_cols). """ parts = spec.split(":") From d109c1aa8d0d99b8a68b5458174aadb7e178e389 Mon Sep 17 00:00:00 2001 From: Alex Rubinsteyn Date: Wed, 18 Nov 2026 21:02:16 -0500 Subject: [PATCH 2/5] Sort lower-is-better output columns ascending under --sort-direction auto --sort-by percentile_rank is a bare column reference, which auto sorted descending (worst binder first) although the help promises percentile ranks sort ascending. Columns in the public LOWER_IS_BETTER_COLUMNS set now sort ascending like the DSL keys reading the same numbers. Closes #572. Claude-Session: https://claude.ai/code/session_01JHJhwjJyLksFkmysWFgmhP --- docs/ranking.md | 7 +++- tests/test_cli_ranking.py | 72 +++++++++++++++++++++++++++++++++++++ topiary/cli/filtering.py | 4 ++- topiary/ranking/__init__.py | 9 ++++- topiary/ranking/apply.py | 28 +++++++++++++-- 5 files changed, 114 insertions(+), 6 deletions(-) diff --git a/docs/ranking.md b/docs/ranking.md index dbdfb95f..e39eaf28 100644 --- a/docs/ranking.md +++ b/docs/ranking.md @@ -453,7 +453,12 @@ Everything below works in Python and in string form (`--filter-by`, `--sort-direction` controls whether lower or higher values rank first. The default is `auto`: raw affinity values and percentile ranks sort ascending, -while all other sort expressions sort descending. +while all other sort expressions sort descending. That holds whether the +number is named by a DSL key (`affinity`, `affinity.rank`) or by its output +column (`affinity`, `percentile_rank`, `wt_affinity`, `wt_percentile_rank`, +`self_nearest_percentile_rank`). Any other bare column, including `value` +(an IC50 on affinity rows but a higher-is-better score on others), sorts +descending; pass `--sort-direction asc` to reverse it. ## peptide_view — one value per peptide diff --git a/tests/test_cli_ranking.py b/tests/test_cli_ranking.py index fa618a5f..c736ab65 100644 --- a/tests/test_cli_ranking.py +++ b/tests/test_cli_ranking.py @@ -1,6 +1,7 @@ """CLI integration tests for --sort-by / --filter-by parsing via _build_filter_and_sort.""" import pandas as pd +import pytest from topiary.cli import args as cli_args from topiary.cli.args import create_arg_parser, _build_filter_and_sort @@ -8,6 +9,7 @@ Affinity, BinOp, BoolOp, + Column, Comparison, DSLNode, Field, @@ -305,6 +307,76 @@ def test_sort_direction_auto_presentation_rank_sorts_ascending(): assert list(result["peptide"]) == ["BBB", "AAA"] +def _affinity_rows_worst_first(): + return pd.DataFrame([ + dict( + source_sequence_name="v1", peptide="AAA", peptide_offset=0, + allele="A", kind="pMHC_affinity", score=0.1, value=5000.0, + affinity=5000.0, percentile_rank=10.0, gene_tpm=1.0, + ), + dict( + source_sequence_name="v1", peptide="BBB", peptide_offset=1, + allele="A", kind="pMHC_affinity", score=0.9, value=50.0, + affinity=50.0, percentile_rank=0.1, gene_tpm=9.0, + ), + ]) + + +@pytest.mark.parametrize("column", ["percentile_rank", "affinity"]) +def test_sort_direction_auto_raw_lower_is_better_column_sorts_ascending(column): + # #572: the raw output column must rank like the DSL key that reads the + # same number, not fall through to "everything else sorts descending". + args = _make_args(f"column({column})") + _, sort_by, sort_direction = _build_filter_and_sort(args) + assert sort_direction == "auto" + assert isinstance(sort_by[0], Column) + result = apply_sort( + _affinity_rows_worst_first(), sort_by, sort_direction=sort_direction, + ) + assert list(result["peptide"]) == ["BBB", "AAA"] + + +def test_sort_by_bare_percentile_rank_matches_dsl_rank_key(): + frame = _affinity_rows_worst_first() + orders = [] + for expression in ["percentile_rank", "affinity.rank"]: + args = _make_args(expression) + _, sort_by, sort_direction = _build_filter_and_sort(args) + result = apply_sort(frame, sort_by, sort_direction=sort_direction) + orders.append(list(result["peptide"])) + assert orders == [["BBB", "AAA"], ["BBB", "AAA"]] + + +def test_sort_direction_auto_other_raw_column_still_sorts_descending(): + args = _make_args("gene_tpm") + _, sort_by, sort_direction = _build_filter_and_sort(args) + result = apply_sort( + _affinity_rows_worst_first(), sort_by, sort_direction=sort_direction, + ) + assert list(result["peptide"]) == ["BBB", "AAA"] + reversed_frame = _affinity_rows_worst_first().iloc[::-1].reset_index(drop=True) + result = apply_sort(reversed_frame, sort_by, sort_direction=sort_direction) + assert list(result["peptide"]) == ["BBB", "AAA"] + + +def test_sort_direction_explicit_desc_overrides_lower_is_better_column(): + args = _make_args("percentile_rank", extra_args=["--sort-direction", "desc"]) + _, sort_by, sort_direction = _build_filter_and_sort(args) + result = apply_sort( + _affinity_rows_worst_first().iloc[::-1].reset_index(drop=True), + sort_by, sort_direction=sort_direction, + ) + assert list(result["peptide"]) == ["AAA", "BBB"] + + +def test_lower_is_better_columns_are_public(): + from topiary.ranking import LOWER_IS_BETTER_COLUMNS + + assert {"percentile_rank", "affinity"} <= LOWER_IS_BETTER_COLUMNS + assert "value" not in LOWER_IS_BETTER_COLUMNS + assert "score" not in LOWER_IS_BETTER_COLUMNS + + def test_sort_by_comma_separated_keys_breaks_ties(): args = _make_args("presentation.score,gene_tpm.log()") _, sort_by, sort_direction = _build_filter_and_sort(args) diff --git a/topiary/cli/filtering.py b/topiary/cli/filtering.py index 99f8c3b2..bba7f493 100644 --- a/topiary/cli/filtering.py +++ b/topiary/cli/filtering.py @@ -93,7 +93,9 @@ def add_filter_args(arg_parser): "--sort-direction", help=( "Sort direction for --sort-by: 'asc', 'desc', or 'auto'. " - "'auto' sorts raw affinity values and percentile ranks ascending, " + "'auto' sorts raw affinity values and percentile ranks ascending " + "(as DSL keys such as 'affinity' and 'affinity.rank', or as the " + "output columns 'affinity' and 'percentile_rank'), " "and sorts everything else descending." ), choices=["auto", "asc", "desc"], diff --git a/topiary/ranking/__init__.py b/topiary/ranking/__init__.py index 95223688..63eed85b 100644 --- a/topiary/ranking/__init__.py +++ b/topiary/ranking/__init__.py @@ -92,7 +92,13 @@ shuffled, wt, ) -from .apply import apply_filter, apply_sort, evaluate_scores, evaluate_filter +from .apply import ( + LOWER_IS_BETTER_COLUMNS, + apply_filter, + apply_sort, + evaluate_scores, + evaluate_filter, +) from .parser import as_dsl_node, as_dsl_nodes, parse from .population import PopulationMaximum, DenseRank, FillMissing, OrdinalRank, ordinal_rank @@ -146,6 +152,7 @@ # Public entry points "apply_filter", "apply_sort", + "LOWER_IS_BETTER_COLUMNS", "evaluate_scores", "evaluate_filter", "parse", diff --git a/topiary/ranking/apply.py b/topiary/ranking/apply.py index 4d42f4a6..78048072 100644 --- a/topiary/ranking/apply.py +++ b/topiary/ranking/apply.py @@ -10,6 +10,7 @@ stated_values, ALLELE_SET_COLUMN, BestAlleleField, + Column, EvalContext, Field, _kind_value, @@ -84,7 +85,6 @@ def _collect_column_names(node): if isinstance(n, FillMissing) and hasattr(n.inner, 'col_name'): # fillna explicitly permits an absent numeric Column. Its eval # still checks contradictions when evidence is present. - from .nodes import Column if isinstance(n.inner, Column): continue col_name = getattr(n, "col_name", None) @@ -186,6 +186,23 @@ def _keep_allele_free_evidence(ctx, node, mask): return mask | (candidates & peptide_kept) +#: Output columns whose meaning is lower-is-better whichever prediction kind +#: the row holds: an IC50 in nM, or a percentile rank. ``--sort-direction +#: auto`` sorts a bare reference to one of them ascending, like the DSL keys +#: that read the same numbers (``affinity``, ``affinity.rank``), so +#: ``--sort-by percentile_rank`` puts the strongest binder first (#572). +#: ``value`` is deliberately absent: it is an IC50 on affinity rows and a +#: higher-is-better score on others, so its direction can't be read off the +#: column name. +LOWER_IS_BETTER_COLUMNS = frozenset({ + "affinity", + "percentile_rank", + "wt_affinity", + "wt_percentile_rank", + "self_nearest_percentile_rank", +}) + + def _infer_sort_direction(node): """Natural sort direction for a node (asc = smaller is better). @@ -193,8 +210,13 @@ def _infer_sort_direction(node): peptide — they change *which* row is read, never whether small or large is better, so ``peptide_view(Affinity.value)`` and ``Affinity.best_value`` sort ascending like the bare field. + + A bare column reference sorts ascending when it names one of + :data:`LOWER_IS_BETTER_COLUMNS`; any other column sorts descending. """ node = _unwrap_peptide_view(node) + if isinstance(node, Column) and node.col_name in LOWER_IS_BETTER_COLUMNS: + return "asc" if isinstance(node, (Field, BestAlleleField)): if node.field == "percentile_rank": return "asc" @@ -431,8 +453,8 @@ def apply_sort(df, sort_nodes, sort_direction="auto", *, group_keys=None, *sort_nodes* is one expression or a list of them, each anything :func:`as_dsl_node` accepts; ``None`` or an empty list is a no-op. The first is the primary key. Each node's direction is inferred - from its shape (percentile_rank → asc; affinity.value → asc; other → - desc) when *sort_direction* is ``"auto"``; otherwise the string + from its shape (percentile_rank → asc; affinity.value → asc; a bare + column in :data:`LOWER_IS_BETTER_COLUMNS` → asc; other → desc) when *sort_direction* is ``"auto"``; otherwise the string value is used for all nodes. A group with no value for a key is neutral on it: it takes the From 4ea127960d2b439e9c8ec65300e629f533b243f9 Mon Sep 17 00:00:00 2001 From: Alex Rubinsteyn Date: Wed, 18 Nov 2026 21:02:16 -0500 Subject: [PATCH 3/5] Add topiary --version and release 5.114.0 Part of #574. Claude-Session: https://claude.ai/code/session_01JHJhwjJyLksFkmysWFgmhP --- CHANGELOG.md | 23 +++++++++++++++++++++++ docs/cli.md | 3 ++- tests/test_cli_coverage.py | 15 +++++++++++++++ topiary/__init__.py | 2 +- topiary/cli/args.py | 7 +++++++ 5 files changed, 48 insertions(+), 2 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index d07eaa63..88177d6b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,28 @@ # Changelog +## 5.114.0 + +- `topiary --version` prints the installed version and exits (part of #574). + +- `--sort-by percentile_rank` now puts the strongest binder first under the + default `--sort-direction auto` (#572). `auto` already sorted the DSL keys + `affinity` and `affinity.rank` ascending, as its help says, but a bare + reference to the lower-is-better output columns (`percentile_rank`, + `affinity`, `wt_percentile_rank`, `wt_affinity`, + `self_nearest_percentile_rank`) fell through to "everything else" and + sorted worst-first. The set is public as + `topiary.ranking.LOWER_IS_BETTER_COLUMNS`. `apply_sort(..., + sort_direction="auto")` with `Column("percentile_rank")` changes the same + way; an explicit `asc` or `desc` is unaffected, and `value` still sorts + descending because its direction depends on the prediction kind. + +- The `--gene-expression` help example now yields the `gene_tpm` column that + the `--filter-by` examples use (#571). The leading name is a column prefix, + so the old example `gene_tpm:quant.sf:Name:TPM` produced `gene_tpm_tpm`; + the help, the expression guide and `parse_expression_spec` now show + `gene:quant.sf:Name:TPM` and state the `{name}_{column}` rule. Column + naming itself is unchanged. + ## 5.113.6 Fixes #622. diff --git a/docs/cli.md b/docs/cli.md index 59c02df5..5c8e7f51 100644 --- a/docs/cli.md +++ b/docs/cli.md @@ -400,7 +400,8 @@ Topiary also accepts options from - `--mhc-predictor-models-path PATH` selects the predictor model directory. - `--mixmhcpred-python PATH` selects the Python interpreter for MixMHCpred. -Run `topiary --help` for defaults and the complete list of accepted options. +Run `topiary --help` for defaults and the complete list of accepted options, +and `topiary --version` to print the installed version. ## Installation details diff --git a/tests/test_cli_coverage.py b/tests/test_cli_coverage.py index b69241c5..c7907ab9 100644 --- a/tests/test_cli_coverage.py +++ b/tests/test_cli_coverage.py @@ -243,3 +243,18 @@ def test_rna_transcript_expression_cufflinks_deprecation( assert caplog.messages == [ f"{named} is deprecated; use {replacement} instead." ] + + +# --------------------------------------------------------------------------- +# --version (#574) +# --------------------------------------------------------------------------- + + +def test_version_flag_prints_installed_version_and_exits(capsys): + import topiary + from topiary.cli.script import main + + with pytest.raises(SystemExit) as exit_info: + main(["--version"]) + assert exit_info.value.code == 0 + assert capsys.readouterr().out.strip() == f"topiary {topiary.__version__}" diff --git a/topiary/__init__.py b/topiary/__init__.py index dd1a6dcc..23413ff5 100644 --- a/topiary/__init__.py +++ b/topiary/__init__.py @@ -246,7 +246,7 @@ encode_amino_acids, ) -__version__ = "5.113.6" +__version__ = "5.114.0" __all__ = [ "best_protein_transcript", diff --git a/topiary/cli/args.py b/topiary/cli/args.py index 56c9fe0f..014cfe79 100644 --- a/topiary/cli/args.py +++ b/topiary/cli/args.py @@ -21,6 +21,7 @@ from mhctools.cli import add_mhc_args, predictors_from_args from varcode.cli import add_variant_args, variant_collection_from_args +from .. import __version__ from .cached_predictor import ( add_cached_predictor_args, cached_predictor_from_args, @@ -285,6 +286,12 @@ def create_arg_parser( ), formatter_class=RawDescriptionHelpFormatter, ) + arg_parser.add_argument( + "--version", + action="version", + version=f"topiary {__version__}", + help="Print the installed Topiary version and exit", + ) if expression: add_expression_args(arg_parser) if rna: From fefb7a89a2f3ee1335169ac9fb685551ebb7062d Mon Sep 17 00:00:00 2001 From: Alex Rubinsteyn Date: Wed, 18 Nov 2026 21:13:07 -0500 Subject: [PATCH 4/5] Cover every scope's percentile_rank column and tighten the wording Review of the first pass: the lower-is-better set listed two of six peptide scopes, so self_mimic_percentile_rank and friends still sorted descending while self_mimic.affinity.rank sorted ascending. Derive the rank columns from the scope keywords, test each member and the bare-column/scoped-field pairs together, export the set from the top level, and say plainly that bare affinity / wt_affinity are DSL keys and that the expression-name prefix rule has two exceptions. Claude-Session: https://claude.ai/code/session_01JHJhwjJyLksFkmysWFgmhP --- CHANGELOG.md | 19 ++++++++-------- docs/api.md | 2 +- docs/expression.md | 4 +++- docs/ranking.md | 15 ++++++++---- tests/test_cli_ranking.py | 39 ++++++++++++++++++++++++++++---- topiary/__init__.py | 2 ++ topiary/cli/filtering.py | 5 ++-- topiary/cli/rna.py | 10 ++++---- topiary/predictor.py | 4 +++- topiary/ranking/apply.py | 27 +++++++++++----------- topiary/rna/expression_loader.py | 1 + 11 files changed, 87 insertions(+), 41 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 88177d6b..b719cbcc 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -7,20 +7,21 @@ - `--sort-by percentile_rank` now puts the strongest binder first under the default `--sort-direction auto` (#572). `auto` already sorted the DSL keys `affinity` and `affinity.rank` ascending, as its help says, but a bare - reference to the lower-is-better output columns (`percentile_rank`, - `affinity`, `wt_percentile_rank`, `wt_affinity`, - `self_nearest_percentile_rank`) fell through to "everything else" and - sorted worst-first. The set is public as - `topiary.ranking.LOWER_IS_BETTER_COLUMNS`. `apply_sort(..., - sort_direction="auto")` with `Column("percentile_rank")` changes the same - way; an explicit `asc` or `desc` is unaffected, and `value` still sorts - descending because its direction depends on the prediction kind. + reference to a lower-is-better output column fell through to "everything + else" and sorted worst-first. That now covers `percentile_rank` in every + peptide scope (`wt_percentile_rank`, `self_nearest_percentile_rank`, + `self_mimic_percentile_rank`, ...) and the IC50 columns reached as + `column(affinity)` / `column(wt_affinity)`. The set is public as + `topiary.LOWER_IS_BETTER_COLUMNS`. `apply_sort(..., sort_direction="auto")` + and `TopiaryResult.sort_by` with `Column("percentile_rank")` change the + same way; an explicit `asc` or `desc` is unaffected, and `value` still + sorts descending because its direction depends on the prediction kind. - The `--gene-expression` help example now yields the `gene_tpm` column that the `--filter-by` examples use (#571). The leading name is a column prefix, so the old example `gene_tpm:quant.sf:Name:TPM` produced `gene_tpm_tpm`; the help, the expression guide and `parse_expression_spec` now show - `gene:quant.sf:Name:TPM` and state the `{name}_{column}` rule. Column + `gene:quant.sf:Name:TPM` and state the name-is-a-prefix rule. Column naming itself is unchanged. ## 5.113.6 diff --git a/docs/api.md b/docs/api.md index 01e1f08a..ff496964 100644 --- a/docs/api.md +++ b/docs/api.md @@ -97,7 +97,7 @@ policy composition and interpretation of missing results. | `alleles` | list of str | HLA alleles. Used to construct model classes. | | `filter_by` | DSLNode or str | Boolean filter expression (e.g. `Affinity <= 500` or `"affinity <= 500 \| el.rank <= 2"`). | | `sort_by` | DSLNode or list of DSLNode | Sort expression(s). Lexicographic tiebreakers; NaN falls through. | -| `sort_direction` | "auto", "asc", or "desc" | Direction for sort keys (auto infers per-key). | +| `sort_direction` | "auto", "asc", or "desc" | Direction for sort keys (auto infers per-key: percentile ranks and raw affinity ascending, everything else descending). | | `padding_around_mutation` | int | Residues around mutation for candidate epitopes. | | `only_novel_epitopes` | bool | Keep known mutation/target/junction overlaps; exclude unknown geometry. Does not establish tumor specificity. | | `min_gene_expression` | float | Minimum gene FPKM (variant inputs). | diff --git a/docs/expression.md b/docs/expression.md index 92c8e10b..868b3112 100644 --- a/docs/expression.md +++ b/docs/expression.md @@ -71,7 +71,9 @@ both lowercased: | `--gene-expression gene_tpm:quant.sf:Name:TPM` | Salmon | `TPM` | `gene_tpm_tpm` | The name is a prefix, not the finished column name: to filter on `gene_tpm`, -name the source `gene` (or leave the name out), not `gene_tpm`. +name the source `gene` (or leave the name out), not `gene_tpm`. A column that +already starts with the name is not prefixed again, and repeating an option +numbers the default names (`gene_1`, `gene_2`). ### Transcript selection diff --git a/docs/ranking.md b/docs/ranking.md index e39eaf28..1742bb2d 100644 --- a/docs/ranking.md +++ b/docs/ranking.md @@ -454,11 +454,16 @@ Everything below works in Python and in string form (`--filter-by`, `--sort-direction` controls whether lower or higher values rank first. The default is `auto`: raw affinity values and percentile ranks sort ascending, while all other sort expressions sort descending. That holds whether the -number is named by a DSL key (`affinity`, `affinity.rank`) or by its output -column (`affinity`, `percentile_rank`, `wt_affinity`, `wt_percentile_rank`, -`self_nearest_percentile_rank`). Any other bare column, including `value` -(an IC50 on affinity rows but a higher-is-better score on others), sorts -descending; pass `--sort-direction asc` to reverse it. +number is named by a DSL key (`affinity`, `affinity.rank`, +`wt.affinity.rank`) or by a bare output column: `percentile_rank` and its +scoped forms (`wt_percentile_rank`, `self_nearest_percentile_rank`, ...), and +`column(affinity)` / `column(wt_affinity)`. The parentheses matter for the +last two, because a bare `affinity` is the DSL key and `wt_affinity` means +affinity from a predictor named `wt`. Any other bare column, including +`value` (an IC50 on affinity rows but a higher-is-better score on others), +sorts descending; pass `--sort-direction asc` to reverse it. Only a bare +reference is recognised: arithmetic or a transform on the column +(`percentile_rank * 2`) is an ordinary expression and sorts descending. ## peptide_view — one value per peptide diff --git a/tests/test_cli_ranking.py b/tests/test_cli_ranking.py index c736ab65..d3da5d67 100644 --- a/tests/test_cli_ranking.py +++ b/tests/test_cli_ranking.py @@ -13,6 +13,7 @@ Comparison, DSLNode, Field, + LOWER_IS_BETTER_COLUMNS, apply_filter, apply_sort, ) @@ -322,7 +323,13 @@ def _affinity_rows_worst_first(): ]) -@pytest.mark.parametrize("column", ["percentile_rank", "affinity"]) +def _frame_with_column(column): + frame = _affinity_rows_worst_first() + frame[column] = [10.0, 0.1] + return frame + + +@pytest.mark.parametrize("column", sorted(LOWER_IS_BETTER_COLUMNS)) def test_sort_direction_auto_raw_lower_is_better_column_sorts_ascending(column): # #572: the raw output column must rank like the DSL key that reads the # same number, not fall through to "everything else sorts descending". @@ -331,11 +338,33 @@ def test_sort_direction_auto_raw_lower_is_better_column_sorts_ascending(column): assert sort_direction == "auto" assert isinstance(sort_by[0], Column) result = apply_sort( - _affinity_rows_worst_first(), sort_by, sort_direction=sort_direction, + _frame_with_column(column), sort_by, sort_direction=sort_direction, ) assert list(result["peptide"]) == ["BBB", "AAA"] +@pytest.mark.parametrize( + "bare, scoped", + [ + ("percentile_rank", "affinity.rank"), + ("wt_percentile_rank", "wt.affinity.rank"), + ("self_nearest_percentile_rank", "self_nearest.affinity.rank"), + ("self_mimic_percentile_rank", "self_mimic.affinity.rank"), + ], +) +def test_bare_rank_column_and_scoped_dsl_field_sort_the_same_way(bare, scoped): + # Two doors onto one column: the bare name parses to a Column, the + # dotted form to a scoped Field. Both must order the rows alike. + frame = _frame_with_column(bare) + orders = [] + for expression in [bare, scoped]: + args = _make_args(expression) + _, sort_by, sort_direction = _build_filter_and_sort(args) + result = apply_sort(frame, sort_by, sort_direction=sort_direction) + orders.append(list(result["peptide"])) + assert orders == [["BBB", "AAA"], ["BBB", "AAA"]] + + def test_sort_by_bare_percentile_rank_matches_dsl_rank_key(): frame = _affinity_rows_worst_first() orders = [] @@ -369,10 +398,10 @@ def test_sort_direction_explicit_desc_overrides_lower_is_better_column(): assert list(result["peptide"]) == ["AAA", "BBB"] -def test_lower_is_better_columns_are_public(): - from topiary.ranking import LOWER_IS_BETTER_COLUMNS +def test_lower_is_better_columns_exclude_kind_dependent_columns(): + import topiary - assert {"percentile_rank", "affinity"} <= LOWER_IS_BETTER_COLUMNS + assert topiary.LOWER_IS_BETTER_COLUMNS is LOWER_IS_BETTER_COLUMNS assert "value" not in LOWER_IS_BETTER_COLUMNS assert "score" not in LOWER_IS_BETTER_COLUMNS diff --git a/topiary/__init__.py b/topiary/__init__.py index 23413ff5..0a13dd2e 100644 --- a/topiary/__init__.py +++ b/topiary/__init__.py @@ -97,6 +97,7 @@ UnaryOp, apply_filter, apply_sort, + LOWER_IS_BETTER_COLUMNS, class_i, class_ii, evaluate_scores, @@ -389,6 +390,7 @@ "UnaryOp", "apply_filter", "apply_sort", + "LOWER_IS_BETTER_COLUMNS", "class_i", "class_ii", "evaluate_scores", diff --git a/topiary/cli/filtering.py b/topiary/cli/filtering.py index bba7f493..2b29fdf5 100644 --- a/topiary/cli/filtering.py +++ b/topiary/cli/filtering.py @@ -94,8 +94,9 @@ def add_filter_args(arg_parser): help=( "Sort direction for --sort-by: 'asc', 'desc', or 'auto'. " "'auto' sorts raw affinity values and percentile ranks ascending " - "(as DSL keys such as 'affinity' and 'affinity.rank', or as the " - "output columns 'affinity' and 'percentile_rank'), " + "(DSL keys such as 'affinity' and 'affinity.rank', and the " + "percentile_rank output column in any scope, e.g. " + "'percentile_rank' or 'wt_percentile_rank'), " "and sorts everything else descending." ), choices=["auto", "asc", "desc"], diff --git a/topiary/cli/rna.py b/topiary/cli/rna.py index 54edf851..62643b60 100644 --- a/topiary/cli/rna.py +++ b/topiary/cli/rna.py @@ -18,9 +18,11 @@ def add_expression_args(arg_parser): "Load expression quantification to annotate predictions. " "Values become columns accessible in --filter-by and --sort-by. " "Format: [name:]file[:id_col[:val_col]]. " - "The name is a column prefix, not a column name: each value " - "column becomes {name}_{column} in lower case, so the default " - "name 'gene' and a TPM column give 'gene_tpm'. " + "The name is a column prefix, not a column name: a value " + "column becomes {name}_{column} in lower case (unless it " + "already starts with the name), so a single --gene-expression " + "with the default name 'gene' and a TPM column gives 'gene_tpm'. " + "Repeating an option numbers the default names (gene_1, gene_2). " "Common formats (Salmon .sf, Kallisto abundance.tsv, RSEM, " "StringTie .gtf, Cufflinks .fpkm_tracking) are auto-detected." ), @@ -34,7 +36,7 @@ def add_expression_args(arg_parser): "Gene-level expression file, joined on gene_id. " "Example: --gene-expression salmon_quant.sf " "or --gene-expression gene:quant.sf:Name:TPM " - "(both add the column 'gene_tpm')" + "(either one adds the column 'gene_tpm')" ), ) expr_group.add_argument( diff --git a/topiary/predictor.py b/topiary/predictor.py index 7e2585f0..042a44e7 100644 --- a/topiary/predictor.py +++ b/topiary/predictor.py @@ -847,7 +847,9 @@ def __init__( sort_direction : "auto", "asc", or "desc" Direction for every sort key; "auto" infers per-key - (asc for percentile_rank and raw affinity, desc otherwise). + (asc for percentile_rank and raw affinity, whether named by + a DSL field or by a bare column in + :data:`topiary.LOWER_IS_BETTER_COLUMNS`; desc otherwise). default_methods : dict, optional Per-kind default ``prediction_method_name``, forwarded to diff --git a/topiary/ranking/apply.py b/topiary/ranking/apply.py index 78048072..c51093d0 100644 --- a/topiary/ranking/apply.py +++ b/topiary/ranking/apply.py @@ -9,6 +9,7 @@ from .nodes import ( stated_values, ALLELE_SET_COLUMN, + _CONTEXT_KEYWORDS, BestAlleleField, Column, EvalContext, @@ -187,20 +188,20 @@ def _keep_allele_free_evidence(ctx, node, mask): #: Output columns whose meaning is lower-is-better whichever prediction kind -#: the row holds: an IC50 in nM, or a percentile rank. ``--sort-direction -#: auto`` sorts a bare reference to one of them ascending, like the DSL keys -#: that read the same numbers (``affinity``, ``affinity.rank``), so +#: the row holds: a percentile rank in any peptide scope (``percentile_rank``, +#: ``wt_percentile_rank``, ``self_nearest_percentile_rank``, ...) or an IC50 +#: in nM (``affinity``, ``wt_affinity``). Under ``sort_direction="auto"`` a +#: bare column reference to one of them sorts ascending, like the DSL field +#: that reads the same column (``affinity.rank``, ``wt.affinity.rank``), so #: ``--sort-by percentile_rank`` puts the strongest binder first (#572). -#: ``value`` is deliberately absent: it is an IC50 on affinity rows and a -#: higher-is-better score on others, so its direction can't be read off the -#: column name. -LOWER_IS_BETTER_COLUMNS = frozenset({ - "affinity", - "percentile_rank", - "wt_affinity", - "wt_percentile_rank", - "self_nearest_percentile_rank", -}) +#: The rank columns are derived from the scope keywords so a new scope can't +#: be left out. ``value`` is deliberately absent: it is an IC50 on affinity +#: rows and a higher-is-better score on others, so its direction can't be +#: read off the column name. +LOWER_IS_BETTER_COLUMNS = frozenset( + {"percentile_rank", "affinity", "wt_affinity"} + | {f"{scope}_percentile_rank" for scope in _CONTEXT_KEYWORDS} +) def _infer_sort_direction(node): diff --git a/topiary/rna/expression_loader.py b/topiary/rna/expression_loader.py index 7ab42425..3587d12e 100644 --- a/topiary/rna/expression_loader.py +++ b/topiary/rna/expression_loader.py @@ -255,6 +255,7 @@ def parse_expression_spec(spec): The name is a column *prefix*: joined values land in ``{name}_{column}`` (lower case), so ``gene:file.tsv:Name:TPM`` adds ``gene_tpm`` while ``gene_tpm:file.tsv:Name:TPM`` adds ``gene_tpm_tpm``. + A column that already starts with the name is not prefixed again. Returns (name, filepath, id_col, val_cols). """ From 8ec38ad041647fed227a5cd5228a7c6c54809457 Mon Sep 17 00:00:00 2001 From: Alex Rubinsteyn Date: Wed, 18 Nov 2026 21:44:45 -0500 Subject: [PATCH 5/5] Update the consumer-workflow pin for the percentile_rank sort direction The result-sort door pinned the old descending order for a bare percentile_rank column, which is the behaviour #572 reports as a bug. Claude-Session: https://claude.ai/code/session_01JHJhwjJyLksFkmysWFgmhP --- tests/test_consumer_workflows.py | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) diff --git a/tests/test_consumer_workflows.py b/tests/test_consumer_workflows.py index 20a6dfe3..2af69929 100644 --- a/tests/test_consumer_workflows.py +++ b/tests/test_consumer_workflows.py @@ -620,9 +620,10 @@ def test_equal_and_missing_measurements_compose_without_order_dependence(door, r assert sorted(answer.peptide) == sorted(frame.peptide) if expected is not None: order = ["SIINFEKL", "SIINFEKL", "GILGFVFTL"] - # Result sorting infers direction: affinity values ascend, - # arbitrary numeric columns descend unless transformed. - if door == "result_sort" and column != "value": + # Result sorting infers direction: affinity values and + # the percentile_rank column ascend (#572); arbitrary + # numeric columns descend unless transformed. + if door == "result_sort" and column == "review_score": order = order[::-1] assert answer.peptide.tolist() == order pd.testing.assert_frame_equal(frame, original)