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
54 changes: 27 additions & 27 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -7,54 +7,54 @@ 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:
python-version: ["3.9", "3.10", "3.11", "3.12", "3.13"]

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
33 changes: 33 additions & 0 deletions .github/workflows/compat.yml
Original file line number Diff line number Diff line change
@@ -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
18 changes: 0 additions & 18 deletions TODO.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
<!-- examples/__init__.py checks `name in ["linezolid", "quinoxoline", "methyl"]`
(misspelled) before building the shared LSU sample, so `quinaxoline` inherits
from `None` unless `linezolid` or `methyl` was loaded earlier. Fix the spelling
in that list. -->
- [ ] `plot_arcs_compare(region=...)` draws the whole alignment and clips the arcs
<!-- Seen on 1f0e81c and later with rnasep_1/rnasep_2, region=[1, 120]: the x-axis
still runs to 265 and long arcs are cut off at the top and bottom. Likely
cause: plot_sequence_alignment (plots/functions/functions.py) sets nucleotide
ticks over the full alignment, and set_xticks widens the x-limits to include
them, while AP sizes the y-limits for the region only. -->

- [ ] `data_loading.get_sequence(sequence)` raises without a sample
<!-- Its docstring says `sample` is optional, but it calls `sample.get_data(...)`
before anything else and catches only ValueError, so sample=None raises
AttributeError even for a literal sequence string or a Sequence object.
Found while implementing projected sequence tracks. -->

---

## Infrastructure & Packaging
Expand Down
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
4 changes: 2 additions & 2 deletions rnavigate/data/interactions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand Down Expand Up @@ -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]


Expand Down
3 changes: 2 additions & 1 deletion rnavigate/data/secondary_structure.py
Original file line number Diff line number Diff line change
Expand Up @@ -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):
Expand Down
9 changes: 5 additions & 4 deletions rnavigate/data_loading.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
2 changes: 1 addition & 1 deletion rnavigate/examples/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down
7 changes: 6 additions & 1 deletion rnavigate/plots/functions/functions.py
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand All @@ -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
Expand All @@ -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"]:
Expand All @@ -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:
Expand Down
45 changes: 33 additions & 12 deletions tests/plots/test_track_geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,6 @@

matplotlib.use("Agg")

import matplotlib.pyplot as plt # noqa: E402
import numpy as np # noqa: E402
import pytest # noqa: E402

Expand All @@ -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():
Expand Down Expand Up @@ -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]
Expand All @@ -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}"
46 changes: 46 additions & 0 deletions tests/test_data_loading.py
Original file line number Diff line number Diff line change
@@ -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)
2 changes: 1 addition & 1 deletion uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading