From d5870c4e4ba660edc87abaae6f0ff0a6bb6ee1d7 Mon Sep 17 00:00:00 2001 From: Ray Speth Date: Fri, 20 Jun 2014 18:45:22 +0000 Subject: [PATCH] [Python] Allow Func1 to accept nearly-scalar types This includes lists, tuples, and numpy arrays with a single element --- interfaces/cython/cantera/func1.pyx | 17 ++++++++++++----- interfaces/cython/cantera/test/test_func1.py | 18 ++++++++++++++++++ 2 files changed, 30 insertions(+), 5 deletions(-) diff --git a/interfaces/cython/cantera/func1.pyx b/interfaces/cython/cantera/func1.pyx index 832a4d2ce..945bbe3cc 100644 --- a/interfaces/cython/cantera/func1.pyx +++ b/interfaces/cython/cantera/func1.pyx @@ -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, self) diff --git a/interfaces/cython/cantera/test/test_func1.py b/interfaces/cython/cantera/test/test_func1.py index b16632d9d..d1d53d762 100644 --- a/interfaces/cython/cantera/test/test_func1.py +++ b/interfaces/cython/cantera/test/test_func1.py @@ -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')