Skip to content
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

🩹 Fix find_axes inside use_plot_config causing TypeError with DataArray #303

Merged
merged 4 commits into from
Sep 28, 2024

Conversation

s-weigand
Copy link
Member

This PR fixes that find_axes raises a TypeError when a config enabled function (has a use_plot_config decorator) has a xr.DataArray argument or return value.

Thanks @jsnel for discovering this error.

We didn't catch this error earlier since all our examples use xr.Dataset and when iterating over xr.Dataset you get the keys of the data_vars.
For xr.DataArray however find_axes recursively looks up sub xr.DataArray until it gets to a point where the value is a single item xr.DataArray and raises the TypeError due to the dimensionality check in its __iter__.

In addition to fixing the above described bug, this PR also fixes that Mappings of Axes as arguments or return values wouldn't have been handled correctly.

Minimal reproducible example:

import xarray as xr
from pyglotaran_extras import plot_data_overview

plot_data_overview(xr.DataArray([[0, 1]], coords={"time": [0], "spectral": [500, 510]}))

Error before fix:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
Cell In[10], line 4
      1 import xarray as xr
      2 from pyglotaran_extras import plot_data_overview
----> 4 plot_data_overview(xr.DataArray([[0, 1]], coords={"time": [0], "spectral": [500, 510]}))

File ~/git/GTA/pyglotaran-extras/pyglotaran_extras/config/plot_config.py:525, in use_plot_config.<locals>.outer_wrapper.<locals>.wrapper(*args, **kwargs)
    523 arg_axes = find_axes(getcallargs(func, *args, **updated_kwargs).values())
    524 return_values = func(*args, **updated_kwargs)
--> 525 function_config.update_axes_labels(arg_axes)
    527 if isinstance(return_values, Iterable):
    528     return_axes = find_axes(return_values)

File ~/git/GTA/pyglotaran-extras/pyglotaran_extras/config/plot_config.py:268, in PerFunctionPlotConfig.update_axes_labels(self, axes)
    266     self.update_axes_labels((axes,))
    267     return
--> 268 for ax in axes:
    269     if isinstance(ax, Axes):
    270         orig_x_label = ax.get_xlabel()

File ~/git/GTA/pyglotaran-extras/pyglotaran_extras/config/plot_config.py:489, in find_axes(values)
    487     yield from find_axes(value.flatten())
    488 elif isinstance(value, Iterable):
--> 489     yield from find_axes(value)

File ~/git/GTA/pyglotaran-extras/pyglotaran_extras/config/plot_config.py:489, in find_axes(values)
    487     yield from find_axes(value.flatten())
    488 elif isinstance(value, Iterable):
--> 489     yield from find_axes(value)

File ~/git/GTA/pyglotaran-extras/pyglotaran_extras/config/plot_config.py:489, in find_axes(values)
    487     yield from find_axes(value.flatten())
    488 elif isinstance(value, Iterable):
--> 489     yield from find_axes(value)

File ~/git/GTA/pyglotaran-extras/pyglotaran_extras/config/plot_config.py:481, in find_axes(values)
    467 def find_axes(
    468     values: Iterable[Any],
    469 ) -> Generator[Axes, None, None]:
    470     """Iterate over values and yield the values that are ``Axes``.
    471 
    472     Parameters
   (...)
    479     Axes
    480     """
--> 481     for value in values:
    482         if isinstance(value, str):
    483             continue

File ~/git/GTA/pyglotaran-extras/.venv/lib/python3.10/site-packages/xarray/core/common.py:213, in AbstractArray.__iter__(self)
    211 def __iter__(self: Any) -> Iterator[Any]:
    212     if self.ndim == 0:
--> 213         raise TypeError("iteration over a 0-d array")
    214     return self._iter()

TypeError: iteration over a 0-d array

Change summary

Checklist

  • ✔️ Passing the tests (mandatory for all PR's)
  • 🧪 Adds new tests for the feature (mandatory for ✨ feature and 🩹 bug fix PR's)

@s-weigand s-weigand requested a review from a team as a code owner September 27, 2024 23:41
Copy link
Contributor

sourcery-ai bot commented Sep 27, 2024

🧙 Sourcery has finished reviewing your pull request!


Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it.

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link
Contributor

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

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

We've reviewed this pull request using the Sourcery rules engine. If you would also like our AI-powered code review then let us know.

Copy link

codecov bot commented Sep 27, 2024

Codecov Report

All modified and coverable lines are covered by tests ✅

Project coverage is 58.33%. Comparing base (4d38e46) to head (3806437).
Report is 2 commits behind head on main.

Additional details and impacted files
@@            Coverage Diff             @@
##             main     #303      +/-   ##
==========================================
+ Coverage   58.26%   58.33%   +0.07%     
==========================================
  Files          31       31              
  Lines        1598     1601       +3     
  Branches      290      291       +1     
==========================================
+ Hits          931      934       +3     
  Misses        651      651              
  Partials       16       16              

☔ View full report in Codecov by Sentry.
📢 Have feedback on the report? Share it here.

Copy link
Member

@jsnel jsnel left a comment

Choose a reason for hiding this comment

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

Thanks for fixing this so quickly! And good thinking expanding the unit tests to include this scenario!

@jsnel jsnel merged commit 29b37dc into glotaran:main Sep 28, 2024
31 checks passed
@s-weigand s-weigand deleted the fix-find_axes-crash branch January 3, 2025 19:34
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

2 participants