[Python] Allow Func1 to accept nearly-scalar types
This includes lists, tuples, and numpy arrays with a single element
This commit is contained in:
parent
8bee138553
commit
d5870c4e4b
2 changed files with 30 additions and 5 deletions
|
|
@ -56,13 +56,20 @@ cdef class Func1:
|
|||
"""
|
||||
def __cinit__(self, c):
|
||||
self.exception = None
|
||||
if isinstance(c, (float, int)):
|
||||
self.callable = lambda t: c
|
||||
elif hasattr(c, '__call__'):
|
||||
if hasattr(c, '__call__'):
|
||||
self.callable = c
|
||||
else:
|
||||
raise TypeError('Func1 must be constructed from a number or a '
|
||||
'callable object')
|
||||
try:
|
||||
# calling float() converts numpy arrays of size 1 to scalars
|
||||
k = float(c)
|
||||
except TypeError:
|
||||
if hasattr(c, '__len__') and len(c) == 1:
|
||||
# Handle lists or tuples with a single element
|
||||
k = float(c[0])
|
||||
else:
|
||||
raise TypeError('Func1 must be constructed from a number or'
|
||||
' a callable object')
|
||||
self.callable = lambda t: k
|
||||
|
||||
self.func = new CxxFunc1(func_callback, <void*>self)
|
||||
|
||||
|
|
|
|||
|
|
@ -33,6 +33,24 @@ class TestFunc1(utilities.CanteraTest):
|
|||
for t in [0.1, 0.7, 4.5]:
|
||||
self.assertNear(f(t), 5)
|
||||
|
||||
def test_sequence(self):
|
||||
f = ct.Func1([5])
|
||||
for t in [0.1, 0.7, 4.5]:
|
||||
self.assertNear(f(t), 5)
|
||||
|
||||
with self.assertRaises(TypeError):
|
||||
ct.Func1([3,4])
|
||||
|
||||
def test_numpy(self):
|
||||
f = ct.Func1(np.array(5))
|
||||
g = ct.Func1(np.array([[5]]))
|
||||
for t in [0.1, 0.7, 4.5]:
|
||||
self.assertNear(f(t), 5)
|
||||
self.assertNear(g(t), 5)
|
||||
|
||||
with self.assertRaises(TypeError):
|
||||
ct.Func1(np.array([3,4]))
|
||||
|
||||
def test_failure(self):
|
||||
def fails(t):
|
||||
raise ValueError('bad')
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue