Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,29 @@
# 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 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-is-a-prefix rule. Column
naming itself is unchanged.

## 5.113.6

Fixes #622.
Expand Down
2 changes: 1 addition & 1 deletion docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -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). |
Expand Down
3 changes: 2 additions & 1 deletion docs/cli.md
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down
7 changes: 7 additions & 0 deletions docs/expression.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,6 +67,13 @@ 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`. 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

Expand Down
12 changes: 11 additions & 1 deletion docs/ranking.md
Original file line number Diff line number Diff line change
Expand Up @@ -453,7 +453,17 @@ 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`,
`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

Expand Down
15 changes: 15 additions & 0 deletions tests/test_cli_coverage.py
Original file line number Diff line number Diff line change
Expand Up @@ -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__}"
101 changes: 101 additions & 0 deletions tests/test_cli_ranking.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,19 @@
"""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
from topiary.ranking import (
Affinity,
BinOp,
BoolOp,
Column,
Comparison,
DSLNode,
Field,
LOWER_IS_BETTER_COLUMNS,
apply_filter,
apply_sort,
)
Expand Down Expand Up @@ -305,6 +308,104 @@ 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,
),
])


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".
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(
_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 = []
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_exclude_kind_dependent_columns():
import topiary

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


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)
Expand Down
7 changes: 4 additions & 3 deletions tests/test_consumer_workflows.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
64 changes: 64 additions & 0 deletions tests/test_expression_integration.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
4 changes: 3 additions & 1 deletion topiary/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -97,6 +97,7 @@
UnaryOp,
apply_filter,
apply_sort,
LOWER_IS_BETTER_COLUMNS,
class_i,
class_ii,
evaluate_scores,
Expand Down Expand Up @@ -246,7 +247,7 @@
encode_amino_acids,
)

__version__ = "5.113.6"
__version__ = "5.114.0"

__all__ = [
"best_protein_transcript",
Expand Down Expand Up @@ -389,6 +390,7 @@
"UnaryOp",
"apply_filter",
"apply_sort",
"LOWER_IS_BETTER_COLUMNS",
"class_i",
"class_ii",
"evaluate_scores",
Expand Down
7 changes: 7 additions & 0 deletions topiary/cli/args.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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:
Expand Down
5 changes: 4 additions & 1 deletion topiary/cli/filtering.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,10 @@ 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 "
"(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"],
Expand Down
8 changes: 7 additions & 1 deletion topiary/cli/rna.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +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: 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."
),
Expand All @@ -30,7 +35,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 "
"(either one adds the column 'gene_tpm')"
),
)
expr_group.add_argument(
Expand Down
4 changes: 3 additions & 1 deletion topiary/predictor.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Loading