Skip to content

Fix negative axis indices raising error, fixes #117 - #119

Closed
nils-werner wants to merge 5 commits into
pydata:masterfrom
nils-werner:normalize_axis
Closed

nils-werner wants to merge 5 commits into
pydata:masterfrom
nils-werner:normalize_axis

Conversation

@nils-werner

@nils-werner nils-werner commented Mar 2, 2018 •

Copy link
Copy Markdown
Contributor

Giving negative axis indices for reductions raises errors, see #117. This PR fixes that.

Fixes #117

@hameerabbasi

Copy link
Copy Markdown
Collaborator

XD I got a kind of a problem with bugs... I squash them too fast. #117 was fixed by #118.

@nils-werner

Copy link
Copy Markdown
Contributor Author

Actually, digging through the code I've found a couple more axis issues. Trying to fix them too now.

@hameerabbasi

Copy link
Copy Markdown
Collaborator

Any fixes are welcome, as well as a normalize_axes of some sort.

@hameerabbasi

Copy link
Copy Markdown
Collaborator

Needs a rebase. Also, are you done here?

Comment thread sparse/coo.py
axes = _normalize_axis(axes, self.ndim)

if np.any(axes >= self.ndim) or np.any(axes < 0):
if any(a >= self.ndim for a in axes) or any(a < 0 for a in axes):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can we put this into _normalize_axis?

@hameerabbasi

Copy link
Copy Markdown
Collaborator

Needs tests for exceptions... with pytest.raises(ExceptionType): code

@mrocklin

mrocklin commented Apr 3, 2018

Copy link
Copy Markdown
Contributor

Checking in on this. It looks like this has fallen behind a bit from master. @nils-werner are you still interested in this? If so then do you know how to proceed or are you blocked on anything?

@nils-werner

Copy link
Copy Markdown
Contributor Author

Sorry for being silent for a month, I was quite busy with other work. I've rebased the branch to sit ontop of master again.

A few pointers as to what is still missing from this PR would be appreciated. Alternatively, if anybody wants to pick up the work and finish it, I'd be happy to hand it over.

Comment thread sparse/coo/core.py
axes = _normalize_axis(axes, self.ndim)

if np.any(axes >= self.ndim) or np.any(axes < 0):
if any(a >= self.ndim for a in axes) or any(a < 0 for a in axes):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

This is better placed in _normalize_axis.

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Actually, it seems the function already has this check, so this can be safely removed.

@codecov-io

codecov-io commented Apr 5, 2018 •

Copy link
Copy Markdown

Codecov Report

Merging #119 into master will increase coverage by 0.02%.
The diff coverage is 95%.

Impacted file tree graph

@@            Coverage Diff            @@
##           master    #119      +/-   ##
=========================================
+ Coverage   95.57%   95.6%   +0.02%     
=========================================
  Files          10      10              
  Lines        1220    1228       +8     
=========================================
+ Hits         1166    1174       +8     
  Misses         54      54
Impacted Files Coverage Δ
sparse/coo/common.py 96.24% <100%> (-0.02%) ⬇️
sparse/coo/core.py 93.21% <100%> (+0.23%) ⬆️
sparse/coo/indexing.py 98.97% <91.66%> (-1.03%) ⬇️

Continue to review full report at Codecov.

Legend - Click here to learn more
Δ = absolute <relative> (impact), ø = not affected, ? = missing data
Powered by Codecov. Last update 1a1df9d...4b56457. Read the comment docs.

Comment thread sparse/coo/indexing.py
return starts, stops


def _normalize_axis(axis, ndim):

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Best to move this function into utils. indexing is COO specific and I'm pretty sure this will be needed elsewhere down the road.

@hameerabbasi

Copy link
Copy Markdown
Collaborator

Some minor comments. You can see in the CodeCov page what's missing coverage-wise, it'd be nice to have a test or remove dead code. Overall, this looks pretty good and complete. Thanks!

Comment thread sparse/coo/indexing.py
)
return axis
elif isinstance(axis, int):
return _normalize_axis([axis], ndim)[0]

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Can we flip the logic here? Make int the default and call that for Iterable?

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

Also, please use numbers.Integral. Otherwise Numpy int64 etc. won't work.

@hameerabbasi

Copy link
Copy Markdown
Collaborator

Superseded by #136, which is now merged.

hameerabbasi pushed a commit that referenced this pull request Oct 7, 2026
`_arg_minmax_common` never normalized the axis, and its bounds check only
covered one side (`axis >= x.ndim`), so a negative axis reached the
transpose and reshape logic untouched. The initial `list.pop(axis)`
happens to work for `-1`, but the final un-transpose does
`new_transpose.insert(axis, new_transpose.pop(0))`, which for `-1`
inserts before the last element instead of at the end. The reduced axis
ends up in front.

Measured against numpy on a (2, 3) array:

    axis=1   numpy [[1], [0]] (2, 1)   sparse [[1], [0]] (2, 1)
    axis=-1  numpy [[1], [0]] (2, 1)   sparse [[1, 0]]   (1, 2)

A 1-D array with `axis=-1` raised `ValueError: shape must be an
non-negative integer...` where numpy returns a value, and `axis=-5` on a
2-D array leaked `IndexError: pop index out of range` instead of a
message naming the bounds.

`normalize_axis` is already imported in this module and every other
axis-taking function in it uses it: `concatenate`, `stack`, `roll`,
`diagonal`, `expand_dims` and `flip`. This was the only one left out,
which also matches the history: the reductions got this treatment in
#118/#119 and `diagonal` in #955, while `argmax`/`argmin` arrived later
in #614 and were never covered. The existing tests parametrize `axis`
over `[None, 0, 1, 2]`, so no negative axis was ever exercised.

The wording of the out-of-bounds `ValueError` is kept so that
`test_argmax_argmin_constraint` still passes, including the 0-D case.
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.

Reduce operations raise error for negative axis values

4 participants