diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0238726..ec769eb 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -7,17 +7,33 @@ on: branches: [master, main] workflow_call: +# Runners are pinned (not ubuntu-latest) so a runner image update cannot break the build. +# Dependencies come from uv.lock, so a failure here is a change in this repository, not +# a new upstream release. Compatibility with other dependency versions is checked by +# compat.yml. jobs: lockfile: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - uses: astral-sh/setup-uv@v4 - name: Check lockfile is up to date run: uv lock --check + lint: + runs-on: ubuntu-24.04 + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v4 + - name: Install dev dependencies + run: uv sync --locked --extra dev --python 3.12 + - name: Lint with ruff + run: uv run --no-sync ruff check . + - name: Check formatting with ruff + run: uv run --no-sync ruff format --check . + test: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 strategy: fail-fast: false matrix: @@ -25,36 +41,20 @@ jobs: steps: - uses: actions/checkout@v4 - - - name: Set up Python ${{ matrix.python-version }} - uses: actions/setup-python@v5 - with: - python-version: ${{ matrix.python-version }} - cache: "pip" - - - name: Install package and dev dependencies - run: pip install -e ".[dev]" - - - name: Lint with ruff - run: ruff check . - - - name: Check formatting with ruff - run: ruff format --check . - + - uses: astral-sh/setup-uv@v4 + - name: Install package and dev dependencies from the lockfile + run: uv sync --locked --extra dev --python ${{ matrix.python-version }} - name: Run tests - run: pytest --tb=short + run: uv run --no-sync pytest --tb=short docs: - runs-on: ubuntu-latest + runs-on: ubuntu-24.04 steps: - uses: actions/checkout@v4 - name: Install pandoc run: sudo apt-get install -y pandoc - - uses: actions/setup-python@v5 - with: - python-version: "3.12" - cache: "pip" - - name: Install docs dependencies - run: pip install -e ".[docs]" + - uses: astral-sh/setup-uv@v4 + - name: Install docs dependencies from the lockfile + run: uv sync --locked --extra docs --python 3.12 - name: Build docs - run: sphinx-build docs/source docs/build/html -D nbsphinx_execute=never + run: uv run --no-sync sphinx-build docs/source docs/build/html -D nbsphinx_execute=never diff --git a/.github/workflows/compat.yml b/.github/workflows/compat.yml new file mode 100644 index 0000000..e1a1a27 --- /dev/null +++ b/.github/workflows/compat.yml @@ -0,0 +1,33 @@ +name: Dependency compatibility + +# Not a gate for pushes or releases. Checks that RNAvigate works with the oldest +# dependency versions it declares and with the newest releases, so an upstream change +# (or a minimum that is too low) is found within a month instead of by a user. +on: + schedule: + - cron: "0 9 1 * *" # 09:00 UTC on the first of every month + workflow_dispatch: + +jobs: + compat: + runs-on: ubuntu-24.04 + strategy: + fail-fast: false + matrix: + include: + # oldest direct dependencies on the oldest Python, then the newest on the + # oldest and newest Pythons (the newest releases can need a newer Python) + - {resolution: lowest-direct, python-version: "3.9"} + - {resolution: highest, python-version: "3.9"} + - {resolution: highest, python-version: "3.13"} + + steps: + - uses: actions/checkout@v4 + - uses: astral-sh/setup-uv@v4 + - name: Install with ${{ matrix.resolution }} dependencies (ignoring uv.lock) + run: | + uv venv --python ${{ matrix.python-version }} + uv pip install -e ".[dev]" --resolution ${{ matrix.resolution }} + uv pip list + - name: Run tests + run: uv run --no-sync pytest --tb=short diff --git a/TODO.md b/TODO.md index 42f44a2..8641d24 100644 --- a/TODO.md +++ b/TODO.md @@ -14,24 +14,6 @@ histogram format. The ShapeMapper 2.2 log format appears to have changed, causing PlotQC to fail. Needs a real v2.2 log file to inspect and update the parser. Works correctly with earlier ShapeMapper versions. --> -- [ ] `rnavigate.examples.quinaxoline` fails when loaded first - -- [ ] `plot_arcs_compare(region=...)` draws the whole alignment and clips the arcs - - -- [ ] `data_loading.get_sequence(sequence)` raises without a sample - - --- ## Infrastructure & Packaging diff --git a/pyproject.toml b/pyproject.toml index c72ec2f..51908bb 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -25,7 +25,7 @@ classifiers = [ ] requires-python = ">=3.9" dependencies = [ - "biopython>=1.78", + "biopython>=1.80", "matplotlib>=3.8", "numpy>=1.20.1", "pandas>=1.4.4", diff --git a/rnavigate/data/interactions.py b/rnavigate/data/interactions.py index 6404b56..37301f3 100644 --- a/rnavigate/data/interactions.py +++ b/rnavigate/data/interactions.py @@ -654,7 +654,7 @@ def get_sorted_data(self): ascending = self.metric not in ["Distance"] # high distance is bad dataframe = self.data[["i", "j", self.metric]].copy() dataframe = dataframe.sort_values( - by=self.metric, ascending=ascending, na_position="first" + by=self.metric, ascending=ascending, na_position="first", kind="stable" ) return dataframe @@ -1192,7 +1192,7 @@ def get_sorted_data(self): columns = ["i", "j", self.metric] dataframe = self.data[columns + ["Sign"]].copy() dataframe[self.metric] = dataframe.eval(f"{self.metric} * Sign") - dataframe = dataframe.sort_values(by=self.metric, ascending=True) + dataframe = dataframe.sort_values(by=self.metric, ascending=True, kind="stable") return dataframe[columns] diff --git a/rnavigate/data/secondary_structure.py b/rnavigate/data/secondary_structure.py index 0eb89f5..e71f9fc 100644 --- a/rnavigate/data/secondary_structure.py +++ b/rnavigate/data/secondary_structure.py @@ -161,7 +161,8 @@ def nts(self): @property def pair_nts(self): - return self.data["Pair"].to_numpy() + # nullable Int32 becomes an object array in older pandas; a missing pair is 0 + return self.data["Pair"].to_numpy(dtype=np.int64, na_value=0) @property def ycoordinates(self): diff --git a/rnavigate/data_loading.py b/rnavigate/data_loading.py index 85adb5e..807e53c 100644 --- a/rnavigate/data_loading.py +++ b/rnavigate/data_loading.py @@ -203,10 +203,11 @@ def get_sequence(sequence, sample=None, default=None): raise ValueError("A sequence must be provided.") elif sequence is None: sequence = default - try: - sequence = sample.get_data(sequence) - except ValueError: - pass + if sample is not None: + try: + sequence = sample.get_data(sequence) + except ValueError: + pass if isinstance(sequence, data.Sequence): return sequence # a long sequence string is not a file name; checking it as one raises OSError diff --git a/rnavigate/examples/__init__.py b/rnavigate/examples/__init__.py index 85b42d5..0e3d6a9 100644 --- a/rnavigate/examples/__init__.py +++ b/rnavigate/examples/__init__.py @@ -144,7 +144,7 @@ def __getattr__(name): # pylint: disable=invalid-name pairmap=str(rnasep_dir / "example4-rnasep-pairmap.txt"), ringmap=str(rnasep_dir / "example4-rnasep.corrs"), ) - if name in ["linezolid", "quinoxoline", "methyl"]: + if name in ["linezolid", "quinaxoline", "methyl"]: global _rrna_fragmap_common if _rrna_fragmap_common is None: _rrna_fragmap_common = rnav.Sample( diff --git a/rnavigate/plots/functions/functions.py b/rnavigate/plots/functions/functions.py index f51af73..8ee6bba 100644 --- a/rnavigate/plots/functions/functions.py +++ b/rnavigate/plots/functions/functions.py @@ -186,6 +186,8 @@ def plot_sequence_alignment( al1 = alignment.alignment1 al2 = alignment.alignment2 sequence_height = height / 3 + # ticks outside the current limits would widen them; keep the plotted region + xlim = ax.get_xlim() top = offset + height plots.plot_sequence_track(ax, al1, transform, offset, sequence_height) plots.plot_sequence_track( @@ -197,6 +199,7 @@ def to_data(y): return ax.transData.inverted().transform(display_y)[1] set_nt_ticks(ax=ax, sequence=al1, region=(1, len(al1)), major=20, minor=5) + ax.set_xlim(xlim) ax.set_xlabel(labels[0], loc="left") ax.spines["bottom"].set(position=("data", to_data(offset)), visible=False) # an inset over the top row, placed through `transform` so its top edge stays on @@ -205,11 +208,12 @@ def to_data(y): [0, top - sequence_height, 1, sequence_height], transform=mp_transforms.blended_transform_factory(ax.transAxes, transform), ) - ax2.set(xlim=ax.get_xlim(), yticks=[]) + ax2.set(xlim=xlim, yticks=[]) ax2.patch.set_visible(False) ax2.xaxis.tick_top() ax2.xaxis.set_label_position("top") set_nt_ticks(ax=ax2, sequence=al2, region=(1, len(al2)), major=20, minor=5) + ax2.set_xlim(xlim) ax2.set_xlabel(labels[1], loc="left") for spine in ["top", "bottom", "left", "right"]: @@ -227,6 +231,7 @@ def to_data(y): ec="none", transform=transform, ) + ax.set_xlim(xlim) def get_arc_height(span: float, max_arc_height: float | None = None) -> float: diff --git a/tests/plots/test_track_geometry.py b/tests/plots/test_track_geometry.py index 3179421..d976d06 100644 --- a/tests/plots/test_track_geometry.py +++ b/tests/plots/test_track_geometry.py @@ -33,7 +33,6 @@ matplotlib.use("Agg") -import matplotlib.pyplot as plt # noqa: E402 import numpy as np # noqa: E402 import pytest # noqa: E402 @@ -42,6 +41,16 @@ SNAPSHOT = Path(__file__).with_name("track_geometry_snapshot.json.gz") DECIMALS = 2 +# Matplotlib releases shift the whole layout by a pixel or two (3.11 moves every artist +# 2 px relative to 3.10). Coordinates match to within PIXEL_TOLERANCE; everything else +# (text, font sizes, tick labels, artist counts) must match exactly. A track unit is +# 1/16 in, several pixels at any dpi used here, so moved tracks still fail. +PIXEL_TOLERANCE = 3.0 +COORDINATE_KEYS = ["xy", "paths"] +# Matplotlib changed which class some calls return: axvspan/axhspan return a Polygon +# before 3.9 and a Rectangle after, and fill_between returns a PolyCollection before +# 3.10 and a FillBetweenPolyCollection after. The snapshot has the newer names. +KIND_ALIASES = {"Polygon": "Rectangle", "PolyCollection": "FillBetweenPolyCollection"} def _annotated_tpp(): @@ -215,6 +224,12 @@ def _load_snapshot(): return json.load(snapshot_file) +def _extent(points): + """Lower-left and upper-right corners of a list of points.""" + points = np.asarray(points) + return [points.min(axis=0).tolist(), points.max(axis=0).tolist()] + + @pytest.mark.parametrize("case", CASES) def test_track_geometry_matches_snapshot(case): expected = _load_snapshot()[case] @@ -231,14 +246,20 @@ def test_track_geometry_matches_snapshot(case): for index, (got, want) in enumerate( zip(actual_ax["artists"], expected_ax["artists"]) ): - assert got == want, f"axes {ax_index}, artist {index}" - - -def record_snapshot(): - """Draw every case and write its geometry to the snapshot file.""" - geometry = {} - for name, make_plot in CASES.items(): - geometry[name] = track_geometry(make_plot()) - plt.close("all") - with gzip.open(SNAPSHOT, "wt") as snapshot_file: - json.dump(geometry, snapshot_file) + where = f"axes {ax_index}, artist {index}" + assert got.keys() == want.keys(), where + assert KIND_ALIASES.get(got["kind"], got["kind"]) == want["kind"], where + for key in got: + if key == "kind": + continue + if key in COORDINATE_KEYS: + got_xy, want_xy = got[key], want[key] + if want["kind"] == "Rectangle": + # Polygon and Rectangle list the corners in a different order + got_xy, want_xy = _extent(got_xy), _extent(want_xy) + assert np.shape(got_xy) == np.shape(want_xy), f"{where}: {key}" + np.testing.assert_allclose( + got_xy, want_xy, rtol=0, atol=PIXEL_TOLERANCE, err_msg=where + ) + else: + assert got[key] == want[key], f"{where}: {key}" diff --git a/tests/test_data_loading.py b/tests/test_data_loading.py new file mode 100644 index 0000000..ba4f49b --- /dev/null +++ b/tests/test_data_loading.py @@ -0,0 +1,46 @@ +"""Tests for data_loading.get_sequence and the bundled examples.""" + +from __future__ import annotations + +import subprocess +import sys + +import rnavigate as rnav +from rnavigate import data_loading + + +def test_get_sequence_without_sample_string(): + seq = data_loading.get_sequence("GAUC") + assert isinstance(seq, rnav.data.Sequence) + assert seq.sequence == "GAUC" + + +def test_get_sequence_without_sample_object(): + seq = rnav.data.Sequence("GAUC") + assert data_loading.get_sequence(seq) is seq + + +def test_get_sequence_default_without_sample(): + assert data_loading.get_sequence(None, default="GAUC").sequence == "GAUC" + + +def test_quinaxoline_loads_first(): + code = ( + "import rnavigate.examples as ex; " + "s = ex.quinaxoline; " + "assert s.get_data('pdb') is not None" + ) + result = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True + ) + assert result.returncode == 0, result.stderr + + +def test_arcs_compare_region_limits(rnasep_1, rnasep_2): + import matplotlib + + matplotlib.use("Agg") + plot = rnav.plot_arcs_compare( + [rnasep_1, rnasep_2], sequence="ss_ct", structure="ss_ct", region=[1, 120] + ) + assert plot.axes[0, 0].get_xlim() == (0.5, 120.5) diff --git a/uv.lock b/uv.lock index aeb436f..ce54778 100644 --- a/uv.lock +++ b/uv.lock @@ -3965,7 +3965,7 @@ docs = [ [package.metadata] requires-dist = [ - { name = "biopython", specifier = ">=1.78" }, + { name = "biopython", specifier = ">=1.80" }, { name = "ipykernel", marker = "extra == 'docs'" }, { name = "matplotlib", specifier = ">=3.8" }, { name = "myst-parser", marker = "extra == 'docs'" },