From f575e2c22fee8671968f6e6436342f1e7a69c85a Mon Sep 17 00:00:00 2001 From: JunyanHuo Date: Mon, 23 Dec 2024 14:10:11 +0800 Subject: [PATCH] Further modifies the _add_ method. --- ndcube/ndcube.py | 35 +++++++++++++++++------------------ 1 file changed, 17 insertions(+), 18 deletions(-) diff --git a/ndcube/ndcube.py b/ndcube/ndcube.py index 3cb5ec941..c39ede2b4 100644 --- a/ndcube/ndcube.py +++ b/ndcube/ndcube.py @@ -1044,10 +1044,21 @@ def __add__(self, value): else: raise TypeError("Cannot add unitless NDData to a unitful NDCube.") + # combine mask + self_ma = np.ma.MaskedArray(self.data, mask=self.mask) + value_ma = np.ma.MaskedArray(value_data, mask=value.mask) + + # addition + result_ma = self_ma + value_ma + + # extract new mask and new data + kwargs["mask"] = result_ma.mask + kwargs["data"] = result_ma.data + # combine the uncertainty if self.uncertainty is not None and value.uncertainty is not None: new_uncertainty = self.uncertainty.propagate( - np.add, value.uncertainty, result_data = value.data, correlation=0 + np.add, value.uncertainty, result_data = kwargs["data"], correlation=0 ) kwargs["uncertainty"] = new_uncertainty elif self.uncertainty is not None: @@ -1058,20 +1069,6 @@ def __add__(self, value): else: new_uncertainty = None - # combine mask - self_ma = np.ma.MaskedArray(self.data, mask=self.mask) - value_ma = np.ma.MaskedArray(value_data, mask=value.mask) - - # addition - result_ma = self_ma + value_ma - - # extract new mask and new data - kwargs["mask"] = result_ma.mask - kwargs["data"] = result_ma.data - - # return the new NDCube instance - return self._new_instance(**kwargs) - if hasattr(value, 'unit'): if isinstance(value, u.Quantity): # NOTE: if the cube does not have units, we cannot @@ -1079,7 +1076,7 @@ def __add__(self, value): # 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) + kwargs["data"] = self.data + value.to_value(cube_unit) else: # NOTE: This explicitly excludes other NDCube objects and NDData objects # which could carry a different WCS than the NDCube @@ -1087,8 +1084,10 @@ def __add__(self, value): 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 - return self._new_instance(data=new_data) + kwargs["data"] = self.data + value + + # return the new NDCube instance + return self._new_instance(**kwargs) def __radd__(self, value): return self.__add__(value)