Skip to content

Commit

Permalink
Merge pull request #389 from jcapriot/abstract_mat_truthiness
Browse files Browse the repository at this point in the history
Implement truthiness for Zero and Identity
  • Loading branch information
jcapriot authored Dec 18, 2024
2 parents 9102097 + 9d9dae5 commit bc3e78d
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 0 deletions.
8 changes: 8 additions & 0 deletions discretize/utils/matrix_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -1493,6 +1493,10 @@ def __repr__(self):
"""Represent zeros a string."""
return "Zero"

def __bool__(self):
"""Return False for zero matrix."""
return False

def __add__(self, v):
"""Add a value to zero."""
return v
Expand Down Expand Up @@ -1655,6 +1659,10 @@ def __repr__(self):
else:
return "-I"

def __bool__(self):
"""Return True for identity matrix."""
return True

def __pos__(self):
"""Return positive 1 (or -1 if not positive)."""
return self
Expand Down
5 changes: 5 additions & 0 deletions tests/base/test_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,7 @@ def test_as_array_n_by_dim(self):
class TestZero(unittest.TestCase):
def test_zero(self):
z = Zero()
assert not z
assert z == 0
assert not (z < 0)
assert z <= 0
Expand Down Expand Up @@ -319,6 +320,7 @@ def test_numpy_multiply(self):

def test_one(self):
o = Identity()
assert o
assert o == 1
assert not (o < 1)
assert o <= 1
Expand Down Expand Up @@ -411,6 +413,9 @@ def test_numpy_one(self):
def test_both(self):
z = Zero()
o = Identity()
assert z or o
assert not (z and o)
assert o and not z
assert o * z == 0
assert o * z + o == 1
assert o - z == 1
Expand Down

0 comments on commit bc3e78d

Please sign in to comment.