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
26 changes: 24 additions & 2 deletions autoarray/plot/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
This replaces the ``MatPlot2D.plot_grid`` / ``MatWrap`` system.
"""

import logging
from typing import Iterable, List, Optional, Tuple

import numpy as np
Expand All @@ -18,6 +19,8 @@
numpy_lines,
)

_logger = logging.getLogger(__name__)


def plot_grid(
grid,
Expand Down Expand Up @@ -62,6 +65,10 @@ def plot_grid(
color_array
1D array of scalar values for colouring each point; triggers a
colorbar.
indexes
Groups of grid indexes to highlight, one colour per group. Indexes
outside the grid are dropped (logged), e.g. when indexes chosen for
a full-size grid meet one capped by ``PYAUTO_SMALL_DATASETS``.
title
Figure title.
xlabel, ylabel
Expand Down Expand Up @@ -170,14 +177,29 @@ def plot_grid(

if indexes is not None:
colors = ["r", "g", "b", "m", "c", "y"]
total_points = grid.shape[0]
dropped = 0
for i, idx_list in enumerate(indexes):
idx_array = np.asarray(idx_list).ravel()
if idx_array.dtype == bool:
idx_array = np.flatnonzero(idx_array)
in_range = (idx_array >= -total_points) & (idx_array < total_points)
dropped += int(np.count_nonzero(~in_range))
idx_array = idx_array[in_range]
if idx_array.size == 0:
continue
ax.scatter(
grid[idx_list, 1],
grid[idx_list, 0],
grid[idx_array, 1],
grid[idx_array, 0],
s=10,
c=colors[i % len(colors)],
zorder=5,
)
if dropped:
_logger.info(
f"plot_grid: dropped {dropped} highlighted index(es) outside the "
f"{total_points}-point grid."
)

if force_symmetric_extent and extent is not None:
x_abs = max(abs(extent[0]), abs(extent[1]))
Expand Down
84 changes: 84 additions & 0 deletions test_autoarray/plot/test_grid.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,84 @@
"""
``plot_grid(indexes=...)`` highlights groups of grid points. Indexes outside the
grid are dropped rather than raising ``IndexError`` (PyAutoArray#705): tutorials
pick indexes for a full-size grid, which ``PYAUTO_SMALL_DATASETS`` can cap.
"""

import logging

import matplotlib

matplotlib.use("Agg")

import matplotlib.pyplot as plt
import numpy as np

import autoarray as aa
import autoarray.plot as aplt


def _grid():
return aa.Grid2D.uniform(shape_native=(4, 4), pixel_scales=1.0)


def _highlight_offsets(ax):
# The first collection is the base scatter of every grid point; the rest are
# one scatter per highlighted index group.
return [np.asarray(c.get_offsets()) for c in ax.collections[1:]]


def test__plot_grid__indexes_in_range__each_group_highlighted():
grid = _grid()
fig, ax = plt.subplots()

aplt.plot_grid(grid=grid, indexes=[[0, 1], [5]], ax=ax)

offsets = _highlight_offsets(ax)
assert len(offsets) == 2
values = np.asarray(grid.array)
assert np.allclose(offsets[0], values[[0, 1]][:, ::-1])
assert np.allclose(offsets[1], values[[5]][:, ::-1])
plt.close(fig)


def test__plot_grid__indexes_partly_out_of_range__out_of_range_dropped(caplog):
grid = _grid()
fig, ax = plt.subplots()

with caplog.at_level(logging.INFO, logger="autoarray.plot.grid"):
aplt.plot_grid(grid=grid, indexes=[[2, 5118], [7099]], ax=ax)

offsets = _highlight_offsets(ax)
assert len(offsets) == 1
assert np.allclose(offsets[0], np.asarray(grid.array)[[2]][:, ::-1])
assert "dropped 2 highlighted index(es) outside the 16-point grid" in caplog.text
plt.close(fig)


def test__plot_grid__indexes_all_out_of_range__no_highlight_and_no_error():
grid = _grid()
fig, ax = plt.subplots()

aplt.plot_grid(
grid=grid,
indexes=[[5118, 5119], [3078]],
ax=ax,
extent=(-5.5, 5.5, -5.5, 5.5),
)

assert _highlight_offsets(ax) == []
plt.close(fig)


def test__plot_grid__boolean_mask_group__highlights_masked_points():
grid = _grid()
fig, ax = plt.subplots()
mask = np.zeros(16, dtype=bool)
mask[[7, 9]] = True

aplt.plot_grid(grid=grid, indexes=[mask], ax=ax)

offsets = _highlight_offsets(ax)
assert len(offsets) == 1
assert np.allclose(offsets[0], np.asarray(grid.array)[[7, 9]][:, ::-1])
plt.close(fig)
Loading