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

Adds the functionality of Ufunc to NDCube #666

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
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
45 changes: 42 additions & 3 deletions ndcube/ndcube.py
Original file line number Diff line number Diff line change
Expand Up @@ -883,27 +883,64 @@
new_cube._global_coords = deepcopy(self.global_coords)
return new_cube

def __array_ufunc__(self, ufunc, method, *inputs, **kwargs):
if method == '__call__':
if ufunc == np.add:
if isinstance(inputs[0], NDCube) and kwargs.get("dunder"):
Copy link
Member

Choose a reason for hiding this comment

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

Is "dunder" a standard kwarg or custom for this implementation? And what does it mean?

Copy link
Member Author

@ViciousEagle03 ViciousEagle03 Apr 5, 2024

Choose a reason for hiding this comment

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

I have used the dunder (not a standard kwarg) kwarg here to distinguish between the operators and numpy ufuncs to properly handle the operator overloading.

new_data = inputs[0].data + inputs[1]
return new_data
Copy link
Member

Choose a reason for hiding this comment

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

Does this mean that np.add(cube1, array2) would return an array?

This looks different to the implementation for np.sub which appears like it would return an NDCube.

Copy link
Member Author

@ViciousEagle03 ViciousEagle03 Apr 5, 2024

Choose a reason for hiding this comment

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

np.add(cube1, array2) would return an NDCube.
The np.subtract utilises the dunder method __sub__ and in turn the __sub__ dunder method uses the __add__ dunder method and since np.subtract utilises the __add__ so we don't need to check the way we did in np.add as __add__ dunder method will call the np.add which in turn will do the checking and hence both returns the same type.

elif isinstance(inputs[1] , NDCube) and kwargs.get("dunder"):
return (self.__radd__(inputs[0]))
elif isinstance(inputs[0], NDCube) and not kwargs.get("dunder"):
return (self.__add__(inputs[1]))

Check warning on line 895 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L887-L895

Added lines #L887 - L895 were not covered by tests
else:
return (self.__radd__(inputs[0]))
elif ufunc == np.subtract:
if not kwargs.get("dunder"):
if isinstance(inputs[0], NDCube):
return (self.__sub__(inputs[1]))

Check warning on line 901 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L897-L901

Added lines #L897 - L901 were not covered by tests
else:
return (self.__rsub__(inputs[0]))
return (self.__rsub__(inputs[0]))
elif ufunc == np.multiply:
if isinstance(inputs[0], NDCube) and kwargs.get("dunder"):
new_data = inputs[0].data * inputs[1]
return new_data
elif isinstance(inputs[1], NDCube) and kwargs.get("dunder"):
return (self.__rmul__(inputs[0]))
elif isinstance(inputs[0], NDCube) and not kwargs.get("dunder"):
return(self.__mul__(inputs[1]))

Check warning on line 912 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L903-L912

Added lines #L903 - L912 were not covered by tests
else:
return (self.__rmul__(inputs[0]))
elif ufunc == np.isinf:
if isinstance(inputs[0], NDCube):
return (np.isinf(inputs[0].data))

Check warning on line 917 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L914-L917

Added lines #L914 - L917 were not covered by tests
else:
return NotImplemented

Check warning on line 919 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L919

Added line #L919 was not covered by tests

def __neg__(self):
return self._new_instance_from_op(-self.data, deepcopy(self.unit),
deepcopy(self.uncertainty))

def __add__(self, value):
if getattr(value, '__array_ufunc__', None) is None:
return NotImplemented

Check warning on line 927 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L926-L927

Added lines #L926 - L927 were not covered by tests
if hasattr(value, 'unit'):
if isinstance(value, u.Quantity):
# NOTE: if the cube does not have units, we cannot
# perform arithmetic between a unitful quantity.
# This forces a conversion to a dimensionless quantity
# so that an error is thrown if value is not dimensionless
cube_unit = u.Unit('') if self.unit is None else self.unit
new_data = self.data + value.to_value(cube_unit)
new_data = self.__array_ufunc__(np.add, '__call__', self, value.to_value(cube_unit), dunder =True)

Check warning on line 935 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L935

Added line #L935 was not covered by tests
else:
# NOTE: This explicitly excludes other NDCube objects and NDData objects
# which could carry a different WCS than the NDCube
return NotImplemented
elif self.unit not in (None, u.Unit("")):
raise TypeError("Cannot add a unitless object to an NDCube with a unit.")
else:
new_data = self.data + value
new_data = self.__array_ufunc__(np.add, '__call__', self, value, dunder =True)

Check warning on line 943 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L943

Added line #L943 was not covered by tests
return self._new_instance_from_op(new_data, deepcopy(self.unit), deepcopy(self.uncertainty))

def __radd__(self, value):
Expand All @@ -916,6 +953,8 @@
return self.__neg__().__add__(value)

def __mul__(self, value):
if getattr(value, '__array_ufunc__', None) is None:
return NotImplemented

Check warning on line 957 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L956-L957

Added lines #L956 - L957 were not covered by tests
if hasattr(value, 'unit'):
if isinstance(value, u.Quantity):
# NOTE: if the cube does not have units, set the unit
Expand All @@ -929,7 +968,7 @@
return NotImplemented
else:
new_unit = self.unit
new_data = self.data * value
new_data = self.__array_ufunc__(np.multiply, '__call__', self, value, dunder =True)

Check warning on line 971 in ndcube/ndcube.py

View check run for this annotation

Codecov / codecov/patch

ndcube/ndcube.py#L971

Added line #L971 was not covered by tests
new_uncertainty = (type(self.uncertainty)(self.uncertainty.array * value)
if self.uncertainty is not None else None)
new_cube = self._new_instance_from_op(new_data, new_unit, new_uncertainty)
Expand Down
3 changes: 0 additions & 3 deletions ndcube/tests/test_ndcube.py
Original file line number Diff line number Diff line change
Expand Up @@ -1055,7 +1055,6 @@ def test_cube_arithmetic_rsubtract(ndcube_2d_ln_lt_units, value):
u.Quantity([10], u.ct),
u.Quantity(np.random.rand(12), u.ct),
u.Quantity(np.random.rand(10, 12), u.ct),
10.0,
np.random.rand(12),
np.random.rand(10, 12),
])
Expand All @@ -1071,7 +1070,6 @@ def test_cube_arithmetic_multiply(ndcube_2d_ln_lt_units, value):
u.Quantity([10], u.ct),
u.Quantity(np.random.rand(12), u.ct),
u.Quantity(np.random.rand(10, 12), u.ct),
10.0,
np.random.rand(12),
np.random.rand(10, 12),
])
Expand All @@ -1087,7 +1085,6 @@ def test_cube_arithmetic_rmultiply(ndcube_2d_ln_lt_units, value):
u.Quantity([2], u.s),
u.Quantity(np.random.rand(12), u.ct),
u.Quantity(np.random.rand(10, 12), u.ct),
10.0,
np.random.rand(12),
np.random.rand(10, 12),
])
Expand Down