Skip to content

Vectorize Coordinate Conversion Functions - #748

Merged
philipc2 merged 19 commits into
mainfrom
philipc2/vec
May 15, 2024
Merged

philipc2 merged 19 commits into
mainfrom
philipc2/vec

Conversation

@philipc2

@philipc2 philipc2 commented Apr 3, 2024 •

Copy link
Copy Markdown
Member

Closes #346

Overview

  • Vectorized implementations of _lonlat_rad_to_xyz, _xyz_to_lonlat_rad, and _xyz_to_lonlat_deg
  • Updates to existing coordinate population functions to use the vectorized versions.

Usage Example

import uxarray as ux 
import numpy as np
from uxarray.grid.coordinates import _lonlat_rad_to_xyz, _xyz_to_lonlat_rad

# assume an initialized grid
uxgrid = ux.Grid()

lon_rad = np.deg2rad(uxgrid.node_lon)
lat_rad = np.deg2rad(uxgrid.node_lat)

# conversion is vectorized across the entire arrays of coordinates
x, y, z = _lonlat_rad_to_xyz(lon_rad, lat_rad)

@philipc2 philipc2 self-assigned this Apr 3, 2024
@erogluorhan erogluorhan linked an issue Apr 23, 2024 that may be closed by this pull request
@philipc2

philipc2 commented May 9, 2024 •

Copy link
Copy Markdown
Member Author

Hi @hongyuchen1030

I'm almost done with vectorizing all the functions. The only issue I'm running into is one of the point inside polygon tests is now failing (test_pole_point_inside_polygon_from_vertice_cross)

I stepped through the function, and was able to determine that the issue somewhere in this portion of the _pole_point_inside_polygon method.

        return (
            _check_intersection(ref_edge_north, north_edges)
            + _check_intersection(ref_edge_south, south_edges)
        ) % 2 != 0

With the changes I've made here, the sum of the intersections is 2, however prior to the change the number of intersections is 1.

Do you know what might be causing this? Could it be a precision issue? Every other test is passing except for this one.

@hongyuchen1030

hongyuchen1030 commented May 9, 2024 •

Copy link
Copy Markdown
Contributor

Hi @hongyuchen1030

I'm almost done with vectorizing all the functions. The only issue I'm running into is one of the point inside polygon tests is now failing (test_pole_point_inside_polygon_from_vertice_cross)

I stepped through the function, and was able to determine that the issue somewhere in this portion of the _pole_point_inside_polygon method.

        return (
            _check_intersection(ref_edge_north, north_edges)
            + _check_intersection(ref_edge_south, south_edges)
        ) % 2 != 0

With the changes I've made here, the sum of the intersections is 2, however prior to the change the number of intersections is 1.

Do you know what might be causing this? Could it be a precision issue? Every other test is passing except for this one.

Thank you very much for your work! I feel like the problem might be a combination of precision and the coordinate conversion style for this test case. I tried to change our error tolerance to 10-3 but it's still failing, so I don't think that's the case (at least not the only factor)

So the test case face tests a very extreme case: The face goes across the equator while still encompassing the North Pole. The face may be referred to as the "bigger face" on the sphere, while it should refer to the "smaller face". I can look into this tomorrow and see what I can find out!

But if you feel this test case is unrealistically complicate for our users, you can feel free to remove it!

@philipc2

philipc2 commented May 9, 2024

Copy link
Copy Markdown
Member Author

Hi @hongyuchen1030
I'm almost done with vectorizing all the functions. The only issue I'm running into is one of the point inside polygon tests is now failing (test_pole_point_inside_polygon_from_vertice_cross)
I stepped through the function, and was able to determine that the issue somewhere in this portion of the _pole_point_inside_polygon method.

        return (
            _check_intersection(ref_edge_north, north_edges)
            + _check_intersection(ref_edge_south, south_edges)
        ) % 2 != 0

With the changes I've made here, the sum of the intersections is 2, however prior to the change the number of intersections is 1.
Do you know what might be causing this? Could it be a precision issue? Every other test is passing except for this one.

Thank you very much for your work! I feel like the problem might be a combination of precision and the coordinate conversion style for this test case. I tried to change our error tolerance to 10-3 but it's still failing, so I don't think that's the case (at least not the only factor)

So the test case face tests a very extreme case: The face goes across the equator while still encompassing the North Pole. The face may be referred to as the "bigger face" on the sphere, while it should refer to the "smaller face". I can look into this tomorrow and see what I can find out!

But if you feel this test case is unrealistically complicate for our users, you can feel free to remove it!

Thanks for the response! If you'd like to look into it, that would be greatly appreciated. I'll be requesting reviews soon, so if we don't get to fixing this test, we can comment it out and put together an issue for this edge case.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

lat = np.where(np.abs(z) > 1.0 - ERROR_TOLERANCE, np.sign(z) * np.pi / 2, lat)

Something I found here:
the line lat = np.where(np.abs(z) > 1.0 - ERROR_TOLERANCE, np.sign(z) * np.pi / 2, lat) will turn lat from a scalar to an size1 np.ndarray

For example, before this line, lat = 0.64052231, after the line lat = array(0.64052231), is this something we're expecting?

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

@hongyuchen1030 hongyuchen1030 May 9, 2024 •

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

The reason I discovered it because the return is [lon, array(lat)], for example when I call the _node_xyz_to_lonlat_rad on an array of vertices, I will sometimes get [[3.14, array(-1.57)],[0, array(1.57)],[1, array(0.29)]] as the return. The dimensions don't look uniform for the longitude and latitude.

Although it's treated the same by numpy, it's still a good idea to make the dimension consistent and following the API description

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

image

If we convert that 2D matrix into a numpy array, it correctly represents the scalar values.

Even when we don't convert to numpy, this still shouldn't cause any issues since a 0-dim numpy array is treated as a scalar.

For example, using the math library:

image

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

thank you for your explanation. I understood it will be treated the same by numpy. My concern is

  1. Most of my functions would use pythong.list for the coordinates conversion according to the previous implementation. And I noticed some of them are still using the same pythong.list right now. I just worry they might cause some potential problems.

  2. When we do the array conversion between python.list and numpy.array() or between other data types for some nested array, I am worrying that this inconsistent will cause problems. Especially in this function call, sometimes it will actually return [lon, lat] with lat as a scalar.

I just encountered so many minor issues between the conversion of python.list and numpy.array when I was calling the cartesian coordinates conversion function and being very cautious about it now.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

I've actually mostly left the original implementations the same, so there isn't any issues with using the lists.

For example, some of the functions would have a gca_pt (or something similar) that would be a list of cartesiain coordinates: [x, y, z]. We can still use these new functions with minimal changes.

gca_pt = [0, 1, 0]

# unpack a list for parameters
lon, lat = _xyz_to_lonlat_rad(*gca_pt)

# equivalent to 
lon, lat = _xyz_to_lonlat_rad(gca_pt[0], gca_pt[1], gca_pt[2])

Even if one of these returns a np.array(0) or something similar, it hasn't broken anything and is still being treated as a scalar.

@hongyuchen1030

Copy link
Copy Markdown
Contributor

Hi @philipc2 , I think I have figured out why it will break, it's related to the coordinates conversion style

in my current node_xyz_to_lonlat_rad it has the following lines, you can tell it will make the pole point presentation uniform in a way such that northpole=[0.0, 0.5 * np.pi], southpole=[0.0, -0.5 * np.pi]. However, there's no such uniform function in you branch. All my functions is built on top of the uniform presentation of the north pole and south pole.

So when in your branch, one of the south pole was presented as [3.14,-0.5 * np.pi ], and it cannot be handled by my function.

    if np.absolute(dz) < (1.0 - ERROR_TOLERANCE):
        d_lon_rad = math.atan2(dy, dx)
        d_lat_rad = np.arcsin(dz)

        if d_lon_rad < 0.0:
            d_lon_rad += 2.0 * np.pi
    elif dz > 0.0:
        d_lon_rad = 0.0
        d_lat_rad = 0.5 * np.pi
    else:
        d_lon_rad = 0.0
        d_lat_rad = -0.5 * np.pi

After I add an extra lon = 0.0 here below in your _xyz_to_lonlat_rad, it passes. I

    if scalar:
        if np.abs(z) > 1.0 - ERROR_TOLERANCE:
            lat = np.sign(z) * np.pi / 2
            lon = 0.0

I feel like this will be a good test case for the new coordinates conversion function.

@philipc2

philipc2 commented May 9, 2024

Copy link
Copy Markdown
Member Author

Hi @philipc2 , I think I have figured out why it will break, it's related to the coordinates conversion style

in my current node_xyz_to_lonlat_rad it has the following lines, you can tell it will make the pole point presentation uniform in a way such that northpole=[0.0, 0.5 * np.pi], southpole=[0.0, -0.5 * np.pi]. However, there's no such uniform function in you branch. All my functions is built on top of the uniform presentation of the north pole and south pole.

So when in your branch, one of the south pole was presented as [3.14,-0.5 * np.pi ], and it cannot be handled by my function.

    if np.absolute(dz) < (1.0 - ERROR_TOLERANCE):
        d_lon_rad = math.atan2(dy, dx)
        d_lat_rad = np.arcsin(dz)

        if d_lon_rad < 0.0:
            d_lon_rad += 2.0 * np.pi
    elif dz > 0.0:
        d_lon_rad = 0.0
        d_lat_rad = 0.5 * np.pi
    else:
        d_lon_rad = 0.0
        d_lat_rad = -0.5 * np.pi

After I add an extra lon = 0.0 here below in your _xyz_to_lonlat_rad, it passes. I

    if scalar:
        if np.abs(z) > 1.0 - ERROR_TOLERANCE:
            lat = np.sign(z) * np.pi / 2
            lon = 0.0

I feel like this will be a good test case for the new coordinates conversion function.

Thank you for the explanation! It's working for me locally now too.

@philipc2
philipc2 requested a review from rajeeja May 9, 2024 19:38
@philipc2
philipc2 marked this pull request as ready for review May 9, 2024 19:48
@philipc2 philipc2 changed the title DRAFT: Vectorize Coordinate Conversion Functions Vectorize Coordinate Conversion Functions May 9, 2024
@philipc2

philipc2 commented May 9, 2024

Copy link
Copy Markdown
Member Author

For combability, the coordinate conversion functions here are all written in pure Numpy, no longer depending on Numba in certain cases.

The main reason for this is that many Numpy functions (such as linalg.norm) when used with Numba don't support optional parameters.

Once Rachel joins us this summer, we can do some further Numba exploration as was described in #202

@philipc2
philipc2 requested a review from erogluorhan May 9, 2024 19:56
@philipc2

Copy link
Copy Markdown
Member Author

Some preliminary performance analysis of running the code vectorized compared to iteratively.

image

image

About a 150x improvement for Cartesian to Spherical and 50x for Spherical to Cartesian.

@philipc2
philipc2 requested a review from hongyuchen1030 May 13, 2024 17:36
@philipc2 philipc2 mentioned this pull request May 14, 2024
1 task done
@erogluorhan

Copy link
Copy Markdown
Member

Performance improvements sound great; I am excited to review it as soon as I can (aiming at today)

@erogluorhan erogluorhan left a comment

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.

This is looking great; just one comment below

Comment thread test/test_geometry.py Resolved
Comment thread uxarray/grid/coordinates.py Resolved
Comment thread uxarray/grid/arcs.py Resolved
@rajeeja

rajeeja commented May 15, 2024

Copy link
Copy Markdown
Contributor

For combability, the coordinate conversion functions here are all written in pure Numpy, no longer depending on Numba in certain cases.

The main reason for this is that many Numpy functions (such as linalg.norm) when used with Numba don't support optional parameters.

Once Rachel joins us this summer, we can do some further Numba exploration as was described in #202

Good work.

After some profiling and understanding the number of calls to certain functions - I believe in introducing some numba decorator again, that were removed from this PR - specifically the one's in area calculation; it might speedup things.

Getting things compatible and decorating all function->function->function with Numba can be a pain. It is known that Numba struggles with functions that use dynamic data structures.

@rajeeja

rajeeja commented May 15, 2024

Copy link
Copy Markdown
Contributor

Some preliminary performance analysis of running the code vectorized compared to iteratively.

image

image

About a 150x improvement for Cartesian to Spherical and 50x for Spherical to Cartesian.

Is my understanding correct: Removing numba and using numpy vectorization caused this?

@rajeeja

rajeeja commented May 15, 2024

Copy link
Copy Markdown
Contributor

There is some numba in grid/ geometry, neighbors and connectivity - all mostly non-nested functions. A note for #202

@philipc2

Copy link
Copy Markdown
Member Author

There is some numba in grid/ geometry, neighbors and connectivity - all mostly non-nested functions. A note for #202

Thanks for that! Can you reference that in the issue directly too?

@philipc2

Copy link
Copy Markdown
Member Author

Some preliminary performance analysis of running the code vectorized compared to iteratively.
image
image
About a 150x improvement for Cartesian to Spherical and 50x for Spherical to Cartesian.

Is my understanding correct: Removing numba and using numpy vectorization caused this?

Correct, the vectorization timings can be achieved when running this function on the entire arrays, as opposed to on each value itteratievely.

x, y, z = _lonlat_rad_to_xyz(lon_rad, lat_rad)

@philipc2

Copy link
Copy Markdown
Member Author

For combability, the coordinate conversion functions here are all written in pure Numpy, no longer depending on Numba in certain cases.
The main reason for this is that many Numpy functions (such as linalg.norm) when used with Numba don't support optional parameters.
Once Rachel joins us this summer, we can do some further Numba exploration as was described in #202

Good work.

After some profiling and understanding the number of calls to certain functions - I believe in introducing some numba decorator again, that were removed from this PR - specifically the one's in area calculation; it might speedup things.

Getting things compatible and decorating all function->function->function with Numba can be a pain. It is known that Numba struggles with functions that use dynamic data structures.

Yeah, I'm hoping we can explore this more this summer, since there is still room for improvement with the performance.

Comment thread test/test_geometry.py Resolved
@erogluorhan
erogluorhan self-requested a review May 15, 2024 22:42

@erogluorhan erogluorhan left a comment

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.

Great work!

@philipc2
philipc2 merged commit ed1e2ae into main May 15, 2024
@hongyuchen1030 hongyuchen1030 mentioned this pull request Aug 7, 2024
13 of 14 tasks
@erogluorhan
erogluorhan deleted the philipc2/vec branch December 2, 2024 16:23
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.

Support Numpy.ndArray for Node 2D/3D Coordinate Conversion Functions NumbaPendingDeprecationWarning

4 participants