Skip to content

FIX: bug in 'reflect' and 'wrap' coordinate mapping - #1583

Merged
ahojnnes merged 19 commits into
scikit-image:masterfrom
grlee77:fix_interp_modes
Aug 20, 2015
Merged

ahojnnes merged 19 commits into
scikit-image:masterfrom
grlee77:fix_interp_modes

Conversation

@grlee77

@grlee77 grlee77 commented Jul 7, 2015

Copy link
Copy Markdown
Contributor

This pull request fixes subtle indexing errors in coord_map from _shared.interpolation.pyx
for modes 'reflect' and 'mirror'.

I added a small python wrapper to coord_map so I could create a test. The image example shown below was added to the documentation.

The following lists output for a set of 1D coordinates before and after the PR:

wrap = [coord_map(4, n, 'W') for n in range(-6, 6)]
# before PR, wrap = [3, 1, 2, 3, 1, 2, 0, 1, 2, 3, 1, 2]
# after PR, wrap  = [2, 3, 0, 1, 2, 3, 0, 1, 2, 3, 0, 1]

Note that coordinate 0 was not wrapped!

reflect = [coord_map(4, n, 'R') for n in range(-6, 6)]
# before PR, reflect = [0, 1, 2, 3, 2, 1, 0, 1, 2, 3, 2, 1]
# after PR, reflect  = [2, 3, 3, 2, 1, 0, 0, 1, 2, 3, 3, 2]

note that the edge coordinates 0 and 3 were not being duplicated in the mirrors

The difference is perhaps easier to see in images than the 1D example above. The original image extent is indicated by the region inside the yellow lines.

Prior to the PR:
buggy_edge_modesv2

After this PR:
fixed_edge_modesv2

@grlee77

grlee77 commented Jul 7, 2015

Copy link
Copy Markdown
Contributor Author

As an aside, is there any easy way during development to force cython to regenerate all .c files from the .pyx files? Several .pyx files in the codebase include interpolation.pxd which contains inline functions. Because the .pyx files themselves have not been changed, cython does not think it needs to regenerate the corresponding .c files.

For now, I just manually deleted the .c files and used cythonize from the command line to regenerate them. Is there a simpler way?

@JDWarner

JDWarner commented Jul 7, 2015

Copy link
Copy Markdown
Contributor

Thanks for the PR and the very informative figure, @grlee77! That really makes it clear (and I like it as an example, too).

Regarding cleaning compiled files, on platforms with makefile support make clean will scour the package clean of compiled files.

@grlee77

grlee77 commented Jul 7, 2015

Copy link
Copy Markdown
Contributor Author

@JDWarner:
make cleanremoves the .so files, but this isn't enough in this case. I needed to also remove the .c files generated by cython so they can be regenerated using the updated version of interpolation.pxd. Normally if you change a .pyx file cython will detect that and regenerate the .c file, but it does not appear to check whether any included .pxd files have changed as well.

@JDWarner

JDWarner commented Jul 8, 2015

Copy link
Copy Markdown
Contributor

I was just looking at the Makefile and you're right. I'll update that file to be more comprehensive.

In the meantime you can run the command behind make clean directly, with "*.c" and ".pyd" added.:

[Edit: Removed because this command was dangerous to run. See #1584]

@grlee77

grlee77 commented Jul 8, 2015

Copy link
Copy Markdown
Contributor Author

@JDWarner:
Okay, but it is still a bit more complicated than the above. We need to not remove any .c files that were not generated by cython. I know there are at least a couple of these:
restoration/unwrap_2d_ljmu.c
restoration/unwrap_3d_ljmu.c

@grlee77

grlee77 commented Jul 8, 2015

Copy link
Copy Markdown
Contributor Author

Now that I think about it more, it could be argued that the original 'reflect' behaviour is correct if you consider the point of reflection to be the center of the edge pixels as opposed to their edges.

The original 'wrap' behaviour does not seem correct to me, though.

@jni

jni commented Jul 8, 2015

Copy link
Copy Markdown
Member

@grlee77 I would indeed consider reflect's behaviour correct, because it matches NumPy's:

In [139]: np.pad([0, 1, 2, 3], 2, mode='reflect')
Out[139]: array([2, 1, 0, 1, 2, 3, 2, 1])

@grlee77

grlee77 commented Jul 8, 2015

Copy link
Copy Markdown
Contributor Author

Thanks @jni:
It does seem the np.pad wrap behaviour matches what I have proposed here, though

In[43]:    np.pad([0, 1, 2, 3], 4, mode='wrap')
Out[43]: array([0, 1, 2, 3, 0, 1, 2, 3, 0, 1, 2, 3])

What I implemented as reflect in this PR is equivalent to np.pad's "symmetric":

In[44]:    np.pad([0, 1, 2, 3], 4, mode='symmetric')
Out[44]: array([3, 2, 1, 0, 0, 1, 2, 3, 3, 2, 1, 0])

As a further comparison, I looked at the behaviour implemented in the function map_coordinate from scipy/ndimage/src/ni_interpolation.c. That function also accepts non-integer coordinates, but from what I can tell, when integer inputs are used, mode 'reflect' matches what I have implemented in this pull request. However, the map_coordinate function from ndimage also has a mode called 'mirror' which gives a result matching the behaviour of 'reflect' prior to my pull request!

Oddly, the 'wrap' behavior in map_coordinate seems to match the pre-PR wrap behaviour above! Am I missing something here or is this a bug?

I don't have a strong opinion on which reflect mode should be used (perhaps offer both as options?). This all came up because I was looking into the potential impact of changing the default mode for transform.resize and transform.rescale to 'reflect' as discussed in #1514.

@grlee77

grlee77 commented Jul 8, 2015

Copy link
Copy Markdown
Contributor Author

see #1585 for the case that lead me to start looking into this. (The images shown there look identical whether using current master or the code from this PR because the problem seems to be in the 'reflect' mode of ndi.map_coordinates itself)

@grlee77 grlee77 changed the title FIX: bug in 'reflect' and 'mirror' coordinate mapping FIX: bug in 'reflect' and 'wrap' coordinate mapping Jul 8, 2015
@ahojnnes

ahojnnes commented Jul 8, 2015

Copy link
Copy Markdown
Member

Thanks very much for this bug fix! This is extremely important.

I hope to have some time later today to look over this.

@grlee77

grlee77 commented Jul 8, 2015

Copy link
Copy Markdown
Contributor Author

As implemented in the most recent commits, I propose to rename the old pre-PR 'reflect' to 'mirror' for consistency with ndimage. The behaviour for 'reflect' will become what is proposed in this PR and would be consistent with ndimage (but consistent with mode 'symmetric' of np.pad & skimage.util.pad).

Several other functions in skimage already accept both 'mirror' and 'reflect' modes (via calls to ndimage functions) . For example:
https://github.com/scikit-image/scikit-image/blob/master/skimage/feature/corner.py#L60
https://github.com/scikit-image/scikit-image/blob/master/skimage/transform/pyramids.py#L48
https://github.com/scikit-image/scikit-image/blob/master/skimage/filters/_gaussian.py#L28

The proposed 'reflect' behavior is also what is implemented in dask's array ghosting (used by skimage.util.apply_parallel):
https://github.com/ContinuumIO/dask/blob/master/dask/array/ghost.py#L301-L333

However, this still leaves the question of which is the desired behaviour for mode 'wrap'. The proposed behavior matches np.pad and dask and is more intuitive to me, but the previous behaviour matches ndimage.

Here is a summary of the current behavior in this PR:
all_modes_v2

@grlee77

grlee77 commented Jul 8, 2015

Copy link
Copy Markdown
Contributor Author

For completeness, the following code demonstrates the behaviour in ndi.map_coordinates. Comparing to my previous comment above, only mode 'wrap' is different.

import scipy.ndimage as ndi
from matplotlib import pyplot as plt

img = np.zeros((9, 9))
img[:8, :8] += 1
img[:4, :4] += 1
img[:2, :2] += 1
img[:1, :1] += 2
img[8, 8] = 4

rows, cols = img.shape[0], img.shape[1]
map_rows, map_cols = np.mgrid[-rows:2*rows, -cols:2*cols]
coord_map = np.array([map_rows, map_cols])
order=1, cval=0
fig, axes = plt.subplots(1, 5, figsize=(15, 5))
for n, mode in enumerate(['constant', 'nearest', 'wrap', 'reflect', 'mirror']):
    out = ndi.map_coordinates(img, coord_map, order=order,
                              mode=mode, cval=cval)
    axes[n].imshow(out, cmap=plt.cm.gray, interpolation='nearest')
    axes[n].plot([8.5, 8.5], [8.5, 17.5], 'y--', linewidth=0.5)
    axes[n].plot([17.5, 17.5], [8.5, 17.5], 'y--', linewidth=0.5)
    axes[n].plot([8.5, 17.5], [8.5, 8.5], 'y--', linewidth=0.5)
    axes[n].plot([8.5, 17.5], [17.5, 17.5], 'y--', linewidth=0.5)
    axes[n].set_axis_off()
    axes[n].set_aspect('equal')
    axes[n].set_title(mode)
plt.tight_layout()

ndimage.map_coordinates result:
all_modes_ndimage_v2

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Add newline

@ahojnnes

ahojnnes commented Jul 9, 2015

Copy link
Copy Markdown
Member

Just a few comments, but all looks good! Thanks for the fix.

Regarding the mismatch in terminology between skimage, np.pad and scipy.ndimage: Can we make the behavior consistent with np.pad and internally make it consistent with scipy.ndimage whenever we use it for 3D (replace the modes)?

@grlee77

grlee77 commented Jul 9, 2015

Copy link
Copy Markdown
Contributor Author

@ahojnnes

See if you are satisfied with the naming/organization of _shared/interpolation.pyx now.

It certainly would be possibile to do the following transformation of np.pad mode names to the corresponding ndimage behaviour.
'reflect' -> 'mirror'
'symmetric' -> 'reflect'
However, there would still be the other places in the codebase that wrap ndimage functionality, using those naming conventions and not the ones from np.pad. Would these all then need to be modified accordingly? I am not sure if this would help or make things more confusing for users.

Does anyone else have an opinion on the best approach to take here?

@grlee77

grlee77 commented Jul 9, 2015

Copy link
Copy Markdown
Contributor Author

I have also (re)raised the issue of the unexpected wrap behaviour in scipy.ndimage here:
scipy/scipy#2640 (comment)

@ahojnnes

ahojnnes commented Jul 9, 2015

Copy link
Copy Markdown
Member

Thanks for your amazing work. Let's wait for an opinion from at least one other core developer on this before you spend any additional time.

@jni

jni commented Jul 9, 2015

Copy link
Copy Markdown
Member

@grlee77 I don't think anyone in their right mind would think ndimage's wrap is correct. That's definitely a bug in my book.

I don't have a strong opinion about reflect/mirror vs symmetric/reflect, because both are in use by pretty major functions in this ecosystem. It's a shame that they diverged. Some thoughts to consider:

  • map_coordinates is a closer function to interpolate, so it makes sense to mirror their API. (heh. =P)
  • np.pad is a more "primal" function in the scipy universe, so it makes sense to use that convention.

I'm leaning towards the second consideration, because I think there might be more of a chance to get ndimage to match numpy than vice-versa, especially since they are on 0.15 (not 1.x yet), while numpy is on 1.9, ie, mature. So we could bring about a unification, rather than continuing the schism.

Whatever we end up deciding, thank you @grlee77 for this!

@jni

jni commented Jul 9, 2015

Copy link
Copy Markdown
Member

I'm particularly impressed by your demo figures, they are super-clear, and make reviewing so much easier. It might be worth putting them in our docs!

@JDWarner

JDWarner commented Jul 9, 2015

Copy link
Copy Markdown
Contributor

My guess is these were independently developed. I can't take credit (or blame) for the np.pad API - I just made it fast ;) - but to cloud the picture even more:

  • np.pad is in arguably the most core package of the ecosystem, but wasn't introduced until 1.7
  • ndi.map_coordinates has existed for much longer.

I prefer np.pad's conventions but that's likely just familiarity talking, so I should recuse my vote here.

@grlee77

grlee77 commented Aug 4, 2015

Copy link
Copy Markdown
Contributor Author

We need a decision on the names for the border modes to move this forward. In summary, what was being called 'reflect' in the current codebase, matches the behavior of mode 'mirror' of ndimage (but does match 'reflect' of np.pad). No equivalent of ndimage 'reflect' (or np.pad 'symmetric') was previously provided.

In the current PR, I have made 'mirror' and 'reflect' match the ndimage behaviour. I think this approach is the simplest since a number of other routines in skimage already take ndimage mode arguments. However, it was suggested to perhaps use the border mode names from np.pad (and skimage.util.pad) instead. There is no clear consensus on this from the core devs who responded. Do any of the other core devs want to chime in? @stefanv maybe?

If we go with the np.pad names there would be 3 names that would require a name conversions whenever routines from ndimage are called :

  • 'edge' -> 'nearest'
  • 'reflect' -> 'mirror'
  • 'symmetric' -> 'reflect'

np.pad modes below:
numpy_pad_modes

ndimage modes (with bug in wrap mode):
ndimage_modes

OpenCV has slightly different names as well:
opencv_border_modes

@ahojnnes

Copy link
Copy Markdown
Member

@grlee77 Thanks again for putting this together. I earlier mentioned that we should replicate the np.pad behavior. @stefanv @JDWarner @jni Would you please give some feedback here? Thanks.

@JDWarner

Copy link
Copy Markdown
Contributor

I also favor the np.pad conventions.

@ahojnnes

ahojnnes commented Aug 13, 2015 via email

Copy link
Copy Markdown
Member

@grlee77

grlee77 commented Aug 14, 2015

Copy link
Copy Markdown
Contributor Author

@ahojnnes: sure, I will update it soon

…istent with numpy.pad naming conventions. Specifically 'nearest' was changed to 'edge' and 'mirror' was changed to 'reflect'. All functions with a mode argument that rely on these functions had their inputs changed accordingly. For now there is a deprecation warning if the user supplies mode 'nearest'. Mode 'mirror' never appeared in an official release of skimage and so has no corresponding deprecation warning.
@grlee77

grlee77 commented Aug 14, 2015

Copy link
Copy Markdown
Contributor Author

okay just rebased off of current master and I think that may have fixed it.

@stefanv

stefanv commented Aug 14, 2015

Copy link
Copy Markdown
Member

I apologize for taking so long into this PR. First, thanks so much for the effort you put into such clear explanations, Gregory. Now, this issue comes a long way. In fact, I should probably take the blame, because I re-enabled the "mirror" mode in ndimage which the original author, Peter Verveer, labeled with a warning comment. Here Be Dragons? Meh.

So, the problem, partially, is that SciPy has what I think is a problematic representations of pixels as "tiny little blocks". Thinking about this off and on over a few years, I've come to expect values to represent data points in space. I.e., the first element of a numpy image array represents a value at the coordinate (0, 0).

This issue is important enough that I mentioned it in the SciPy roadmap. Solving it will close no less than four (!) SciPy bugs.

I think the scikit-image pixel model is more sane than ndimage's, and that we should aim at fixing SciPy if we can (and the broken modes in scikit-image, highlighted above, of course) since we fall back to it quite often.

Finally, I am delighted to see that my inattention to the issue really made no difference, since you all figure this and more out yourselves--kudos!

@grlee77

grlee77 commented Aug 14, 2015

Copy link
Copy Markdown
Contributor Author

@ahojnnes: see if the additions to TODO.txt seems adequate (I think maybe I should have put it under 0.14 instead), then hopefully we are ready to merge!

@ahojnnes

Copy link
Copy Markdown
Member

LGTM. Approval from my side. Waiting for a second voice from another core dev @JDWarner @stefanv @jni etc.

@JDWarner

Copy link
Copy Markdown
Contributor

LGTM as well, @ahojnnes. Thanks for sticking with this, @grlee77!

@ahojnnes

Copy link
Copy Markdown
Member

Thanks very much @grlee77 - this fix is very important!

Since you seem to be familiar with the interpolation code now, how about a new challenge: #1279 :-)

Anyway, thanks very much.

ahojnnes added a commit that referenced this pull request Aug 20, 2015
FIX:  bug in 'reflect' and 'wrap' coordinate mapping
@ahojnnes
ahojnnes merged commit 236aa20 into scikit-image:master Aug 20, 2015
@stefanv

stefanv commented Sep 30, 2015

Copy link
Copy Markdown
Member

@grlee77 @ahojnnes Can you please have a look at scipy/scipy#5223 and confirm whether scikit-image is doing the right thing? The question is whether:

tf.rescale(np.array([1,2,3,4.]), (1, 3), order=0)

is supposed to return

array([[ 1.,  1.,  1.,  2.,  2.,  2.,  3.,  3.,  3.,  4.,  4.,  4.]])

as it currently does?

@ahojnnes

Copy link
Copy Markdown
Member

That's what it is supposed to do. skimage uses the convention that the pixel centers are at 0.5. Is that enough?

@stefanv

stefanv commented Oct 1, 2015

Copy link
Copy Markdown
Member

@ahojnnes I thought we agreed to use the data point system? The centers of pixels system seems a bit odd, and causes a lot of problems in, e.g., scipy.ndimage.

@ahojnnes

ahojnnes commented Oct 1, 2015 via email

Copy link
Copy Markdown
Member

@ahojnnes

ahojnnes commented Oct 1, 2015 via email

Copy link
Copy Markdown
Member

@stefanv

stefanv commented Oct 1, 2015 via email

Copy link
Copy Markdown
Member

@ahojnnes

ahojnnes commented Oct 1, 2015 via email

Copy link
Copy Markdown
Member

@stefanv

stefanv commented Oct 1, 2015 via email

Copy link
Copy Markdown
Member

@ahojnnes

ahojnnes commented Oct 1, 2015 via email

Copy link
Copy Markdown
Member

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.

5 participants