Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Move axisartist towards untransposed transforms (operating on (N, 2) arrays instead of (2, N) arrays). #27551

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Dec 19, 2024
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
4 changes: 4 additions & 0 deletions doc/api/next_api_changes/deprecations/27551-AL.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
``GridFinder.transform_xy`` and ``GridFinder.inv_transform_xy``
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
... are deprecated. Directly use the standard transform returned by
`.GridFinder.get_transform` instead.
21 changes: 11 additions & 10 deletions lib/mpl_toolkits/axisartist/angle_helper.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import numpy as np
import math

from matplotlib.transforms import Bbox
from mpl_toolkits.axisartist.grid_finder import ExtremeFinderSimple


Expand Down Expand Up @@ -347,11 +348,12 @@ def __init__(self, nx, ny,
self.lon_minmax = lon_minmax
self.lat_minmax = lat_minmax

def __call__(self, transform_xy, x1, y1, x2, y2):
def _find_transformed_bbox(self, trans, bbox):
# docstring inherited
x, y = np.meshgrid(
np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny))
lon, lat = transform_xy(np.ravel(x), np.ravel(y))
grid = np.reshape(np.meshgrid(np.linspace(bbox.x0, bbox.x1, self.nx),
np.linspace(bbox.y0, bbox.y1, self.ny)),
(2, -1)).T
lon, lat = trans.transform(grid).T

# iron out jumps, but algorithm should be improved.
# This is just naive way of doing and my fail for some cases.
Expand All @@ -367,11 +369,10 @@ def __call__(self, transform_xy, x1, y1, x2, y2):
lat0 = np.nanmin(lat)
lat -= 360. * ((lat - lat0) > 180.)

lon_min, lon_max = np.nanmin(lon), np.nanmax(lon)
lat_min, lat_max = np.nanmin(lat), np.nanmax(lat)

lon_min, lon_max, lat_min, lat_max = \
self._add_pad(lon_min, lon_max, lat_min, lat_max)
tbbox = Bbox.null()
tbbox.update_from_data_xy(np.column_stack([lon, lat]))
tbbox = tbbox.expanded(1 + 2 / self.nx, 1 + 2 / self.ny)
lon_min, lat_min, lon_max, lat_max = tbbox.extents

# check cycle
if self.lon_cycle:
Expand All @@ -391,4 +392,4 @@ def __call__(self, transform_xy, x1, y1, x2, y2):
max0 = self.lat_minmax[1]
lat_max = min(max0, lat_max)

return lon_min, lon_max, lat_min, lat_max
return Bbox.from_extents(lon_min, lat_min, lon_max, lat_max)
6 changes: 4 additions & 2 deletions lib/mpl_toolkits/axisartist/axislines.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,8 @@
from matplotlib import _api
import matplotlib.axes as maxes
from matplotlib.path import Path
from matplotlib.transforms import Bbox

from mpl_toolkits.axes_grid1 import mpl_axes
from .axisline_style import AxislineStyle # noqa
from .axis_artist import AxisArtist, GridlinesCollection
Expand Down Expand Up @@ -285,10 +287,10 @@ def update_lim(self, axes):
x1, x2 = axes.get_xlim()
y1, y2 = axes.get_ylim()
if self._old_limits != (x1, x2, y1, y2):
self._update_grid(x1, y1, x2, y2)
self._update_grid(Bbox.from_extents(x1, y1, x2, y2))
self._old_limits = (x1, x2, y1, y2)

def _update_grid(self, x1, y1, x2, y2):
def _update_grid(self, bbox):
"""Cache relevant computations when the axes limits have changed."""

def get_gridlines(self, which, axis):
Expand Down
39 changes: 17 additions & 22 deletions lib/mpl_toolkits/axisartist/floating_axes.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,8 @@
from matplotlib import _api, cbook
import matplotlib.patches as mpatches
from matplotlib.path import Path

from matplotlib.transforms import Bbox
from mpl_toolkits.axes_grid1.parasite_axes import host_axes_class_factory

from . import axislines, grid_helper_curvelinear
from .axis_artist import AxisArtist
from .grid_finder import ExtremeFinderSimple
Expand Down Expand Up @@ -109,8 +108,7 @@ def get_line(self, axes):
right=("lon_lines0", 1),
bottom=("lat_lines0", 0),
top=("lat_lines0", 1))[self._side]
xx, yy = self._grid_info[k][v]
return Path(np.column_stack([xx, yy]))
return Path(self._grid_info[k][v])


class ExtremeFinderFixed(ExtremeFinderSimple):
Expand All @@ -125,11 +123,12 @@ def __init__(self, extremes):
extremes : (float, float, float, float)
The bounding box that this helper always returns.
"""
self._extremes = extremes
x0, x1, y0, y1 = extremes
self._tbbox = Bbox.from_extents(x0, y0, x1, y1)

def __call__(self, transform_xy, x1, y1, x2, y2):
def _find_transformed_bbox(self, trans, bbox):
# docstring inherited
return self._extremes
return self._tbbox


class GridHelperCurveLinear(grid_helper_curvelinear.GridHelperCurveLinear):
Expand Down Expand Up @@ -177,25 +176,22 @@ def new_fixed_axis(
# axis.get_helper().set_extremes(*self._extremes[2:])
# return axis

def _update_grid(self, x1, y1, x2, y2):
def _update_grid(self, bbox):
if self._grid_info is None:
self._grid_info = dict()

grid_info = self._grid_info

grid_finder = self.grid_finder
extremes = grid_finder.extreme_finder(grid_finder.inv_transform_xy,
x1, y1, x2, y2)
tbbox = grid_finder.extreme_finder._find_transformed_bbox(
grid_finder.get_transform().inverted(), bbox)

lon_min, lon_max = sorted(extremes[:2])
lat_min, lat_max = sorted(extremes[2:])
grid_info["extremes"] = lon_min, lon_max, lat_min, lat_max # extremes
lon_min, lat_min, lon_max, lat_max = tbbox.extents
grid_info["extremes"] = tbbox

lon_levs, lon_n, lon_factor = \
grid_finder.grid_locator1(lon_min, lon_max)
lon_levs, lon_n, lon_factor = grid_finder.grid_locator1(lon_min, lon_max)
lon_levs = np.asarray(lon_levs)
lat_levs, lat_n, lat_factor = \
grid_finder.grid_locator2(lat_min, lat_max)
lat_levs, lat_n, lat_factor = grid_finder.grid_locator2(lat_min, lat_max)
lat_levs = np.asarray(lat_levs)

grid_info["lon_info"] = lon_levs, lon_n, lon_factor
Expand All @@ -212,24 +208,23 @@ def _update_grid(self, x1, y1, x2, y2):
lon_lines, lat_lines = grid_finder._get_raw_grid_lines(
lon_values[(lon_min < lon_values) & (lon_values < lon_max)],
lat_values[(lat_min < lat_values) & (lat_values < lat_max)],
lon_min, lon_max, lat_min, lat_max)
tbbox)

grid_info["lon_lines"] = lon_lines
grid_info["lat_lines"] = lat_lines

lon_lines, lat_lines = grid_finder._get_raw_grid_lines(
# lon_min, lon_max, lat_min, lat_max)
extremes[:2], extremes[2:], *extremes)
tbbox.intervalx, tbbox.intervaly, tbbox)

grid_info["lon_lines0"] = lon_lines
grid_info["lat_lines0"] = lat_lines

def get_gridlines(self, which="major", axis="both"):
grid_lines = []
if axis in ["both", "x"]:
grid_lines.extend(self._grid_info["lon_lines"])
grid_lines.extend(map(np.transpose, self._grid_info["lon_lines"]))
if axis in ["both", "y"]:
grid_lines.extend(self._grid_info["lat_lines"])
grid_lines.extend(map(np.transpose, self._grid_info["lat_lines"]))
return grid_lines


Expand Down
84 changes: 40 additions & 44 deletions lib/mpl_toolkits/axisartist/grid_finder.py
Original file line number Diff line number Diff line change
Expand Up @@ -77,20 +77,29 @@ def __call__(self, transform_xy, x1, y1, x2, y2):
extremal coordinates; then adding some padding to take into account the
finite sampling.

As each sampling step covers a relative range of *1/nx* or *1/ny*,
As each sampling step covers a relative range of ``1/nx`` or ``1/ny``,
the padding is computed by expanding the span covered by the extremal
coordinates by these fractions.
"""
x, y = np.meshgrid(
np.linspace(x1, x2, self.nx), np.linspace(y1, y2, self.ny))
xt, yt = transform_xy(np.ravel(x), np.ravel(y))
return self._add_pad(xt.min(), xt.max(), yt.min(), yt.max())
tbbox = self._find_transformed_bbox(
_User2DTransform(transform_xy, None), Bbox.from_extents(x1, y1, x2, y2))
return tbbox.x0, tbbox.x1, tbbox.y0, tbbox.y1

def _add_pad(self, x_min, x_max, y_min, y_max):
"""Perform the padding mentioned in `__call__`."""
dx = (x_max - x_min) / self.nx
dy = (y_max - y_min) / self.ny
return x_min - dx, x_max + dx, y_min - dy, y_max + dy
def _find_transformed_bbox(self, trans, bbox):
"""
Compute an approximation of the bounding box obtained by applying
*trans* to *bbox*.

See ``__call__`` for details; this method performs similar
calculations, but using a different representation of the arguments and
return value.
"""
grid = np.reshape(np.meshgrid(np.linspace(bbox.x0, bbox.x1, self.nx),
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Even though this is private, it should have a docstring.

In particular it should explain the padding (expanded()) and it should mention that it's semantically equivalent to __call__ but with a better API.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Sure.

np.linspace(bbox.y0, bbox.y1, self.ny)),
(2, -1)).T
tbbox = Bbox.null()
tbbox.update_from_data_xy(trans.transform(grid))
return tbbox.expanded(1 + 2 / self.nx, 1 + 2 / self.ny)


class _User2DTransform(Transform):
Expand Down Expand Up @@ -170,42 +179,31 @@ def get_grid_info(self, x1, y1, x2, y2):
rough number of grids in each direction.
"""

extremes = self.extreme_finder(self.inv_transform_xy, x1, y1, x2, y2)

# min & max rage of lat (or lon) for each grid line will be drawn.
# i.e., gridline of lon=0 will be drawn from lat_min to lat_max.
bbox = Bbox.from_extents(x1, y1, x2, y2)
tbbox = self.extreme_finder._find_transformed_bbox(
self.get_transform().inverted(), bbox)

lon_min, lon_max, lat_min, lat_max = extremes
lon_levs, lon_n, lon_factor = self.grid_locator1(lon_min, lon_max)
lon_levs = np.asarray(lon_levs)
lat_levs, lat_n, lat_factor = self.grid_locator2(lat_min, lat_max)
lat_levs = np.asarray(lat_levs)
lon_levs, lon_n, lon_factor = self.grid_locator1(*tbbox.intervalx)
lat_levs, lat_n, lat_factor = self.grid_locator2(*tbbox.intervaly)

lon_values = lon_levs[:lon_n] / lon_factor
lat_values = lat_levs[:lat_n] / lat_factor
lon_values = np.asarray(lon_levs[:lon_n]) / lon_factor
lat_values = np.asarray(lat_levs[:lat_n]) / lat_factor

lon_lines, lat_lines = self._get_raw_grid_lines(lon_values,
lat_values,
lon_min, lon_max,
lat_min, lat_max)
lon_lines, lat_lines = self._get_raw_grid_lines(lon_values, lat_values, tbbox)

bb = Bbox.from_extents(x1, y1, x2, y2).expanded(1 + 2e-10, 1 + 2e-10)

grid_info = {
"extremes": extremes,
# "lon", "lat", filled below.
}
bbox_expanded = bbox.expanded(1 + 2e-10, 1 + 2e-10)
grid_info = {"extremes": tbbox} # "lon", "lat" keys filled below.

for idx, lon_or_lat, levs, factor, values, lines in [
(1, "lon", lon_levs, lon_factor, lon_values, lon_lines),
(2, "lat", lat_levs, lat_factor, lat_values, lat_lines),
]:
grid_info[lon_or_lat] = gi = {
"lines": [[l] for l in lines],
"lines": lines,
"ticks": {"left": [], "right": [], "bottom": [], "top": []},
}
for (lx, ly), v, level in zip(lines, values, levs):
all_crossings = _find_line_box_crossings(np.column_stack([lx, ly]), bb)
for xys, v, level in zip(lines, values, levs):
all_crossings = _find_line_box_crossings(xys, bbox_expanded)
for side, crossings in zip(
["left", "right", "bottom", "top"], all_crossings):
for crossing in crossings:
Expand All @@ -218,18 +216,14 @@ def get_grid_info(self, x1, y1, x2, y2):

return grid_info

def _get_raw_grid_lines(self,
lon_values, lat_values,
lon_min, lon_max, lat_min, lat_max):

lons_i = np.linspace(lon_min, lon_max, 100) # for interpolation
lats_i = np.linspace(lat_min, lat_max, 100)

lon_lines = [self.transform_xy(np.full_like(lats_i, lon), lats_i)
def _get_raw_grid_lines(self, lon_values, lat_values, bbox):
trans = self.get_transform()
lons = np.linspace(bbox.x0, bbox.x1, 100) # for interpolation
lats = np.linspace(bbox.y0, bbox.y1, 100)
lon_lines = [trans.transform(np.column_stack([np.full_like(lats, lon), lats]))
for lon in lon_values]
lat_lines = [self.transform_xy(lons_i, np.full_like(lons_i, lat))
lat_lines = [trans.transform(np.column_stack([lons, np.full_like(lons, lat)]))
for lat in lat_values]

return lon_lines, lat_lines

def set_transform(self, aux_trans):
Expand All @@ -246,9 +240,11 @@ def get_transform(self):

update_transform = set_transform # backcompat alias.

@_api.deprecated("3.11", alternative="grid_finder.get_transform()")
def transform_xy(self, x, y):
return self._aux_transform.transform(np.column_stack([x, y])).T

@_api.deprecated("3.11", alternative="grid_finder.get_transform().inverted()")
def inv_transform_xy(self, x, y):
return self._aux_transform.inverted().transform(
np.column_stack([x, y])).T
Expand Down
Loading
Loading