Skip to content

Commit

Permalink
Merge pull request openmc-dev#1493 from drewejohnson/numpy-mul-fy
Browse files Browse the repository at this point in the history
Disallow numpy ufuncs being applied directly to FissionYields
  • Loading branch information
paulromano authored Feb 25, 2020
2 parents 66dabca + 2854b3a commit 630be27
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 1 deletion.
8 changes: 8 additions & 0 deletions openmc/deplete/nuclide.py
Original file line number Diff line number Diff line change
Expand Up @@ -533,6 +533,7 @@ def items(self):
return zip(self.products, self.yields)

def __add__(self, other):
"""Add one set of fission yields to this set, return new yields"""
if not isinstance(other, FissionYield):
return NotImplemented
new = FissionYield(self.products, self.yields.copy())
Expand All @@ -550,12 +551,14 @@ def __radd__(self, other):
return self + other

def __imul__(self, scalar):
"""Scale these fission yields by a real scalar"""
if not isinstance(scalar, Real):
return NotImplemented
self.yields *= scalar
return self

def __mul__(self, scalar):
"""Return a new set of yields scaled by a real scalar"""
if not isinstance(scalar, Real):
return NotImplemented
new = FissionYield(self.products, self.yields.copy())
Expand All @@ -568,3 +571,8 @@ def __rmul__(self, scalar):
def __repr__(self):
return "<{} containing {} products and yields>".format(
self.__class__.__name__, len(self))

# Avoid greedy numpy operations like np.float64 * fission_yield
# converting this to an array on the fly. Force __rmul__ and
# __radd__. See issue #1492
__array_ufunc__ = None
8 changes: 7 additions & 1 deletion tests/unit_tests/test_deplete_nuclide.py
Original file line number Diff line number Diff line change
Expand Up @@ -149,12 +149,18 @@ def test_fission_yield_distribution():
# __getitem__ return yields as a view into yield matrix
assert orig_yields.yields.base is yield_dist.yield_matrix

# Fission yield feature uses scaled and incremented
# Scale and increment fission yields
mod_yields = orig_yields * 2
assert numpy.array_equal(orig_yields.yields * 2, mod_yields.yields)
mod_yields += orig_yields
assert numpy.array_equal(orig_yields.yields * 3, mod_yields.yields)

mod_yields = 2.0 * orig_yields
assert numpy.array_equal(orig_yields.yields * 2, mod_yields.yields)

mod_yields = numpy.float64(2.0) * orig_yields
assert numpy.array_equal(orig_yields.yields * 2, mod_yields.yields)

# Failure modes for adding, multiplying yields
similar = numpy.empty_like(orig_yields.yields)
with pytest.raises(TypeError):
Expand Down

0 comments on commit 630be27

Please sign in to comment.