Source code for spm1d.util._eq
'''
Equality utilities.
'''
# Copyright (C) 2026 Todd Pataky
import math
import numpy as np
def _equal(x0, x1, approx=False):
'''
Compare one attribute: arrays elementwise and floats approximately.
'''
if (x0 is None) or (x1 is None):
return (x0 is None) and (x1 is None)
if isinstance(x0, np.ndarray) or isinstance(x1, np.ndarray):
a0, a1 = np.ma.getdata(x0), np.ma.getdata(x1)
if (a0.shape != a1.shape) or not np.array_equal( np.ma.getmaskarray(x0), np.ma.getmaskarray(x1) ):
return False
return bool( np.allclose(a0, a1, rtol=1e-6, atol=1e-12, equal_nan=True) if approx else np.array_equal(a0, a1) )
if approx:
if isinstance(x0, (int, float, np.number)) and isinstance(x1, (int, float, np.number)):
return math.isclose( x0, x1, rel_tol=1e-6, abs_tol=1e-12 )
try:
return bool( np.allclose( np.asarray(x0, dtype=float), np.asarray(x1, dtype=float), rtol=1e-6, atol=1e-12 ) )
except (TypeError, ValueError):
pass
return bool( x0 == x1 )
[docs]
def isequal(self, other, attrs, attrs_approx=None, verbose=False):
'''
Equality of two objects on named attributes.
:Parameters:
- *self* --- object
- *other* --- other object
- *attrs* --- list of attribute names compared exactly
- *attrs_approx* --- list of attribute names compared approximately
(relative tolerance 1e-6 and absolute tolerance 1e-12). Default None
- *verbose* --- if True, print the first unequal attribute name (default
False)
:Returns:
- True if the objects are equal, otherwise False
:Example:
>>> import spm1d
>>> import jikudata as jd
>>> y = jd.SimulatedPataky2015b().y # (10,101) array
>>> t0 = spm1d.stats.ttest( y, 0 )
>>> t1 = spm1d.stats.ttest( y, 0 )
>>> print( spm1d.util.isequal( t0, t1, ['STAT', 'df'], ['z'] ) )
True
The example datasets require the jiku-data package:
``pip install "spm1d[data]"``.
'''
attrs_approx = [] if (attrs_approx is None) else attrs_approx
if type(self) != type(other):
return False
for s in (attrs + attrs_approx):
if not _equal( getattr(self, s), getattr(other, s), approx=(s in attrs_approx) ):
if verbose:
print(f'unequal {s} values')
return False
return True