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
9 changes: 7 additions & 2 deletions docs/api/for_agents.md
Original file line number Diff line number Diff line change
Expand Up @@ -96,16 +96,21 @@ vp.contours.signed_area(contour) -> float (> 0 counterclockwise in a y-up frame
vp.contours.resample_contour(contour, n_points=50) -> (2, n_points)
vp.contours.register_contour(contour) -> (2, n)
vp.contours.align_contour(contour, reference) -> (2, n)
vp.contours.lowpass_contour(contour, n_harmonics) -> (2, n) (Fourier low-pass; display only)

vp.shape_mode_distribution(labels, n_clusters=None) -> (n_clusters,) fractions
# labels in 1..n_clusters; entry i = fraction of mode i+1; default n_clusters = max(labels);
# label 0 or > n_clusters -> ValueError; n_clusters: int >= 1
vp.shannon_entropy(distribution, base=None) -> float # nats by default; base > 0, != 1
(aliases of vp.metrics.*)

vp.plotting.plot_summary(model, labels=None, figsize=None, height_ratios=(4, 1, 1)) -> (Figure, axes(3,))
vp.plotting.plot_summary(model, labels=None, figsize=None, height_ratios=(4, 1, 1),
n_harmonics=None) -> (Figure, axes(3,))
vp.plotting.plot_distribution(labels, n_clusters=None, ax=None, colors=None) -> Axes
vp.plotting.plot_shape_modes(model, ax=None, colors=None, ...) -> Axes
vp.plotting.plot_shape_modes(model, ax=None, colors=None, ..., smooth=True,
n_harmonics=None) -> Axes
# smooth: draw a periodic spline through the points; n_harmonics: Fourier
# low-pass before drawing (~8-12 removes pixel staircase). Drawing only.
vp.plotting.plot_dendrogram(model, ax=None, **dendrogram_kwargs) -> Axes
# default orientation="bottom" (root at bottom, leaves up toward the modes), no spines;
# also "top"/"left"/"right"; mode m at 10*m - 5 on the leaf axis
Expand Down
1 change: 1 addition & 0 deletions docs/api/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@ shape `(n_samples, 2, n)`, a Series of contours, or a DataFrame with a
resample_contour
register_contour
align_contour
lowpass_contour
```

## Metrics
Expand Down
15 changes: 15 additions & 0 deletions docs/conf.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
"""

import os
import tempfile
from datetime import date
from importlib.metadata import version as _version

Expand Down Expand Up @@ -98,6 +99,20 @@
nb_merge_streams = True
nb_execution_excludepatterns = []

# Render executed matplotlib figures at 300 dpi. "retina" makes IPython attach
# width/height metadata of half the pixel size, so figures are shown at
# 150 CSS px per inch with 2x pixel density (sharp on high-DPI screens).
# The notebook kernel reads this from a throwaway IPython profile directory.
_ipython_dir = tempfile.mkdtemp(prefix="vampire-docs-ipython-")
_profile_dir = os.path.join(_ipython_dir, "profile_default")
os.makedirs(_profile_dir)
with open(os.path.join(_profile_dir, "ipython_kernel_config.py"), "w") as _f:
_f.write(
'c.InlineBackend.figure_formats = {"retina"}\n'
'c.InlineBackend.print_figure_kwargs = {"bbox_inches": "tight", "dpi": 300}\n'
)
os.environ["IPYTHONDIR"] = _ipython_dir

# -- sphinx-copybutton ---------------------------------------------------------

copybutton_prompt_text = r">>> |\.\.\. |\$ "
Expand Down
16 changes: 16 additions & 0 deletions docs/examples/plotting.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,22 @@ vp.plotting.plot_shape_modes(model, ax=axes[0], colors="viridis")
vp.plotting.plot_shape_modes(model, ax=axes[1], colors="black", linewidth=1)
```

Mean contours of segmented cells keep some pixel-level wiggle. Pass
`n_harmonics` to low-pass filter the contours before drawing (keeping only
their first `n_harmonics` Fourier harmonics, see
{func}`vampire.contours.lowpass_contour`). Lower values are smoother; around 8
removes the staircase while keeping each mode's dents and waists. Only the
drawing changes, not the model. {func}`~vampire.plotting.plot_summary` and
{func}`~vampire.plotting.plot_representatives` accept the same option.

```{code-cell} ipython3
fig, axes = plt.subplots(3, 1, figsize=(6, 4.5), layout="constrained")
for ax, n_harmonics in zip(axes, [None, 12, 8]):
vp.plotting.plot_shape_modes(model, ax=ax, n_harmonics=n_harmonics)
ax.set_title(f"n_harmonics={n_harmonics}", fontsize=9)
ax.tick_params(labelbottom=ax is axes[-1]) # mode numbers on the last row
```

## Dendrogram

By default the root is at the bottom and the leaves point up, so the
Expand Down
8 changes: 7 additions & 1 deletion docs/releases/changelog.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,13 @@ files from earlier versions do not work with 1.0. See
`orientation="bottom"` (root at the bottom, leaves pointing up to the shape
modes) without axis spines; {func}`~vampire.plotting.plot_summary` shows the
mode numbers once, under the distribution bars, with the dendrogram under
the shape modes.
the shape modes. Contours are drawn as smooth periodic splines through
their points (`smooth=True` in {func}`~vampire.plotting.plot_shape_modes`
and {func}`~vampire.plotting.plot_representatives`). An optional
`n_harmonics` Fourier low-pass (also in
{func}`~vampire.plotting.plot_summary`) removes pixel-level wiggle before
drawing; the filter is available as {func}`vampire.contours.lowpass_contour`.
- Documentation figures are rendered at 300 dpi.
- {mod}`vampire.datasets`: bundled example images and a synthetic shape
generator.
- Method fixes: equidistant resampling without a duplicated endpoint, proper
Expand Down
59 changes: 59 additions & 0 deletions src/vampire/contours.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,10 @@
fix the starting point and direction;
3. :func:`align_contour` -- fine-tune starting point and rotation against a
reference (the mean registered contour of a data set).

:func:`lowpass_contour` is not part of that pipeline: it removes
high-frequency detail (pixel staircase, segmentation noise) for display, as
used by the ``n_harmonics`` option of :mod:`vampire.plotting`.
"""

import numpy as np
Expand Down Expand Up @@ -335,3 +339,58 @@ def align_contour(contour: NDArray, reference: NDArray) -> NDArray[np.float64]:
s = shifted[0] @ B[1] - shifted[1] @ B[0]
A_best = shifted[:, np.argmax(np.hypot(c, s))]
return kabsch_rotation(A_best, B) @ A_best


def lowpass_contour(contour: NDArray, n_harmonics: int) -> NDArray[np.float64]:
r"""Remove high-frequency detail from a closed contour (Fourier low-pass).

The contour is treated as a periodic complex signal
:math:`z_j = x_j + i\,y_j` and expanded in its discrete Fourier series
(elliptic Fourier descriptors). Harmonics above ``n_harmonics`` are set to
zero, and the contour is reconstructed at the same points. Harmonic 0 is
the centroid, harmonic 1 the best-fitting ellipse; each further harmonic
adds finer detail, so small values give smoother outlines.

Points should be roughly equidistant along the contour, as produced by
:func:`resample_contour` (and therefore by every fitted model attribute
such as ``Vampire.mean_cluster_contours_``).

Parameters
----------
contour : ndarray of shape (2, n_points)
Closed contour.
n_harmonics : int
Number of harmonics kept in each rotation direction (>= 1). Values of
``n_points // 2`` or more keep every harmonic and return the contour
unchanged.

Returns
-------
smoothed : ndarray of shape (2, n_points)
Low-pass filtered contour with the same number of points and the same
centroid.

Examples
--------
>>> import numpy as np
>>> t = np.linspace(0, 2 * np.pi, 64, endpoint=False)
>>> noisy = np.vstack([np.cos(t), np.sin(t)]) * (1 + 0.05 * np.cos(20 * t))
>>> smooth = lowpass_contour(noisy, n_harmonics=5)
>>> smooth.shape
(2, 64)
>>> bool(np.allclose(np.hypot(*smooth), 1.0)) # the ripple is gone
True
"""
contour = _check_contour(contour)
if (
isinstance(n_harmonics, bool)
or not isinstance(n_harmonics, int | np.integer)
or n_harmonics < 1
):
raise ValueError(f"n_harmonics must be an integer >= 1; got {n_harmonics!r}.")
n = contour.shape[1]
coefficients = np.fft.fft(contour[0] + 1j * contour[1])
frequencies = np.fft.fftfreq(n, d=1.0 / n) # integer harmonic numbers
coefficients[np.abs(frequencies) > n_harmonics] = 0
smoothed = np.fft.ifft(coefficients)
return np.vstack([smoothed.real, smoothed.imag])
87 changes: 77 additions & 10 deletions src/vampire/plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -35,9 +35,11 @@
from matplotlib.font_manager import FontProperties
from numpy.typing import ArrayLike, NDArray
from scipy.cluster.hierarchy import dendrogram
from scipy.interpolate import make_interp_spline
from sklearn.utils.validation import check_is_fitted

from ._validation import ContourSet, check_labels
from .contours import _drop_repeated_points, _segment_lengths, lowpass_contour
from .extraction import _to_label_image
from .metrics import shape_mode_distribution

Expand All @@ -53,6 +55,9 @@
#: Distance between adjacent SciPy dendrogram leaves in data units.
_LEAF_SPACING = 10.0

#: Number of points at which smoothed contours are drawn.
_SMOOTH_POINTS = 400

ColorSpec = str | Colormap | Sequence[Any] | None


Expand Down Expand Up @@ -111,6 +116,32 @@ def _as_labels(labels: ArrayLike) -> NDArray:
return np.asarray(labels)


def _closed_curve(
contour: NDArray, smooth: bool = True, n_harmonics: int | None = None
) -> NDArray[np.float64]:
"""Return a closed ``(2, m)`` curve for drawing a ``(2, n)`` contour.

With ``n_harmonics``, the contour is first low-pass filtered with
:func:`vampire.contours.lowpass_contour`. With ``smooth``, a periodic
cubic spline is fitted *through* the points (parameterized by chord
length) and sampled at ``_SMOOTH_POINTS`` points, so straight segments
between the few stored points are replaced by a smooth curve without
moving the points themselves. Otherwise the polygon is closed by repeating
its first point.
"""
points = np.asarray(contour, dtype=float)
if n_harmonics is not None:
points = lowpass_contour(points, n_harmonics)
if smooth:
points = _drop_repeated_points(points)
if not smooth or points.shape[1] < 4:
return np.hstack([points, points[:, :1]])
closed = np.hstack([points, points[:, :1]])
t = np.concatenate([[0.0], np.cumsum(_segment_lengths(closed))])
spline = make_interp_spline(t, closed, k=3, bc_type="periodic", axis=1)
return spline(np.linspace(0.0, t[-1], _SMOOTH_POINTS + 1))


def _invert_y(ax: Axes) -> None:
"""Make y grow downward (image convention), idempotently."""
if not ax.yaxis_inverted():
Expand Down Expand Up @@ -195,6 +226,8 @@ def plot_shape_modes(
scale: float | None = None,
linewidth: float = 2.0,
equal_aspect: bool = True,
smooth: bool = True,
n_harmonics: int | None = None,
) -> Axes:
"""Draw the mean contour of each shape mode side by side.

Expand All @@ -219,6 +252,17 @@ def plot_shape_modes(
equal_aspect : bool, default=True
Use equal data aspect (shapes undistorted). Set ``False`` when the axes
shares x with other axes; :func:`plot_summary` then adjusts y limits.
smooth : bool, default=True
Draw each contour as a periodic cubic spline passing through its
``n_points`` points instead of straight segments between them. The
points themselves (``model.mean_cluster_contours_``) are unchanged.
n_harmonics : int, optional
Low-pass filter each contour before drawing, keeping only its first
``n_harmonics`` Fourier harmonics (see
:func:`vampire.contours.lowpass_contour`). Removes high-frequency
wiggles such as the pixel staircase of segmented outlines; around 8-12
keeps the overall shape of typical cells. ``None`` (default) draws the
contours unfiltered. Only the drawing changes, not the model.

Returns
-------
Expand Down Expand Up @@ -253,9 +297,16 @@ def plot_shape_modes(
scale = 0.85 * spacing / width if width > 0 else 1.0
centers = spacing * (np.argsort(model.dendrogram_["leaves"]) + 0.5)
for i, contour in enumerate(contours):
x = np.append(contour[0], contour[0, 0]) * scale + centers[i]
y = np.append(contour[1], contour[1, 0]) * scale
ax.plot(x, y, color=palette[i], lw=linewidth, label=str(i + 1))
x, y = _closed_curve(contour, smooth, n_harmonics) * scale
x = x + centers[i]
ax.plot(
x,
y,
color=palette[i],
lw=linewidth,
label=str(i + 1),
solid_capstyle="round",
)
ax.set_xlim(0, spacing * k)
if equal_aspect:
ax.set_aspect("equal", adjustable="datalim")
Expand Down Expand Up @@ -331,6 +382,7 @@ def plot_summary(
labels: ArrayLike | None = None,
figsize: tuple[float, float] | None = None,
height_ratios: Sequence[float] = (4, 1, 1),
n_harmonics: int | None = None,
) -> tuple[Figure, NDArray[Any]]:
"""Plot shape-mode distribution, mean contours, and dendrogram stacked.

Expand All @@ -353,6 +405,9 @@ def plot_summary(
height_ratios : sequence of 3 floats, default=(4, 1, 1)
Relative heights of the distribution, shape-mode, and dendrogram axes.
Use smaller shape-mode heights for many modes.
n_harmonics : int, optional
Low-pass filter the shape-mode contours before drawing (see
:func:`plot_shape_modes`). ``None`` (default) draws them unfiltered.

Returns
-------
Expand Down Expand Up @@ -416,7 +471,9 @@ def plot_summary(
widest = np.ptp(contours[:, 0, :], axis=1).max()
tallest = np.abs(contours[:, 1, :]).max()
scale = min(0.85 * _LEAF_SPACING / widest, 0.9 * half_height / tallest)
plot_shape_modes(model, ax=ax_modes, scale=scale, equal_aspect=False)
plot_shape_modes(
model, ax=ax_modes, scale=scale, equal_aspect=False, n_harmonics=n_harmonics
)
plot_dendrogram(model, ax=ax_dend, orientation="bottom")
ax_dend.set_xlim(0, _LEAF_SPACING * k)
ax_dist.tick_params(axis="x", length=0, labelbottom=True)
Expand Down Expand Up @@ -452,6 +509,8 @@ def plot_representatives(
show_mean: bool = True,
alpha: float = 0.7,
figsize: tuple[float, float] | None = None,
smooth: bool = True,
n_harmonics: int | None = None,
) -> tuple[Figure, NDArray[Any]]:
"""Overlay the contours closest to each shape-mode center.

Expand Down Expand Up @@ -479,6 +538,16 @@ def plot_representatives(
Opacity of the representative contours.
figsize : (float, float), optional
Defaults to ``(1.6 * n_clusters, 1.8)``.
smooth : bool, default=True
Draw contours as periodic cubic splines through their points instead
of straight segments (see :func:`plot_shape_modes`).
n_harmonics : int, optional
Low-pass filter each contour before drawing, keeping only its first
``n_harmonics`` Fourier harmonics (see
:func:`vampire.contours.lowpass_contour`). Removes high-frequency
wiggles such as the pixel staircase of segmented outlines; around 8-12
keeps the overall shape of typical cells. ``None`` (default) draws the
contours unfiltered. Only the drawing changes, not the model.

Returns
-------
Expand Down Expand Up @@ -536,21 +605,19 @@ def plot_representatives(
members = np.flatnonzero(labels == i + 1)
closest = members[np.argsort(distances[members, i])[:n_per_mode]]
for idx in closest:
c = normalized[idx]
ax.plot(
np.append(c[0], c[0, 0]),
np.append(c[1], c[1, 0]),
*_closed_curve(normalized[idx], smooth, n_harmonics),
color=palette[i],
alpha=alpha,
lw=1.5,
solid_capstyle="round",
)
if show_mean:
m = model.mean_cluster_contours_[i]
ax.plot(
np.append(m[0], m[0, 0]),
np.append(m[1], m[1, 0]),
*_closed_curve(model.mean_cluster_contours_[i], smooth, n_harmonics),
color="black",
lw=2,
solid_capstyle="round",
ls="--",
)
ax.set_aspect("equal", adjustable="datalim")
Expand Down
Loading
Loading