OT function decorator

Hi,

Here is an easier way to pass python functions to openturns

First define once this decorator for python functions (could be proposed in a future version):

def FunctionDecorator(n, p):
  class otfunc(OpenTURNSPythonFunction):
      
    def __init__(self, func):
      OpenTURNSPythonFunction.__init__(self, n, p) 
      self.__class__.__name__ = func.__name__
      self._exec = func 
        
  return otfunc

Then apply it to your function by adding this one line:

@FunctionDecorator(2, 1)
def SIMPLEFUNC(X):
    Y = [ X[0] + X[1] ]    
    return Y

Then use it through OpenTURNS as usual:

myFunc = NumericalMathFunction( SIMPLEFUNC )

This is open for discussion ...

J.

  • Posted: 2012-05-04 09:00 (Updated: 2012-05-15 17:52)
  • Author: schueller
  • Categories: python

Comments

1. souchaud@… -- 2012-05-15 18:20

Hi,

except for python specialist, this code is quite weird, isn't it?

Why we could not propose directly something like this :

def SIMPLEFUNC(X):
    Y = [ X[0] + X[1] ]
    return Y
myFunc = UserPythonFunction( SIMPLEFUNC, 2, 1 )

Mathieu

2. souchaud@… -- 2012-10-20 23:36

Something like this around OpenTURNSPythonFunction will do the trick:

class PythonFunction(OpenTURNSPythonFunction) :
    def __init__(self, n_input, n_output, func, func_sample=None) :
        OpenTURNSPythonFunction.__init__(self, n_input, n_output)
        self._exec = func
        if func_sample != None:
            self._exec_sample = func_sample

use it:

def SIMPLEFUNC(X):
    Y = [ X[0] + X[1] ]
    return Y
myFunc = NumericalMathFunction( PythonFunction( 2, 1, SIMPLEFUNC ) )