def test_pythagoras(self): from math import sqrt X = Symbol('X') Y = Symbol('Y') expr = sym_call(sqrt, X ** 2 + Y ** 2) func = to_callable(expr) self.assertEqual(func(X=3, Y=4), 5)
def argument_symbolic_reference(self, arg): if hasattr(arg, '_eval'): arg = symbolic.to_callable(arg)(self.df) if isinstance(arg, pd.Series): return arg.name elif isinstance(arg, pd.DataFrame): return symbolic.sym_call(lambda *x: x, arg.columns.tolist()) elif isinstance(arg, (list, tuple)): arglist = [self.argument_symbolic_reference(subarg) for subarg in arg] return symbolic.sym_call(lambda *x: x, *arglist) return arg
def _label_or_arg(self, df, arg): """Recursively extracts pandas series arguments or retains original argument.""" arg = symbolic.to_callable(arg)(df) if isinstance(arg, pd.Series): return arg.name elif isinstance(arg, pd.DataFrame): return arg.columns.tolist() elif isinstance(arg, (list, tuple)): return [self._label_or_arg(df, subarg) for subarg in arg] else: return arg
def test_to_callable_from_nonsymbolic_callable(self): func = mock.Mock(return_value='return value') del func._eval # So it doesn't pretend to be symbolic test_callable = to_callable(func) # Ensure running to_callable does not call the function self.assertFalse(func.called) result = test_callable('arg1', 'arg2', kwarg_name='kwarg value') func.assert_called_once_with('arg1', 'arg2', kwarg_name='kwarg value') self.assertEqual(result, 'return value')
def test_to_callable_from_symbolic(self): mock_expr = mock.Mock() mock_expr._eval.return_value = 'eval return value' test_callable = to_callable(mock_expr) # Ensure running to_callable does not evaluate the expression self.assertFalse(mock_expr._eval.called) result = test_callable('arg1', 'arg2', kwarg_name='kwarg value') mock_expr._eval.assert_called_once_with( {0: 'arg1', 1: 'arg2', 'kwarg_name': 'kwarg value'}) self.assertEqual(result, 'eval return value')
def _kwargs_eval(self, df, kwargs): return {k:symbolic.to_callable(v)(df) for k,v in kwargs.items()}
def _args_eval(self, df, args): return [df]+[symbolic.to_callable(arg)(df) for arg in args]
def call_action(self, args, kwargs): self.df = args[0] symbolic_function = symbolic.Call(self.function, args=[self.df]+self.recurse_args(args[1:]), kwargs=self.recurse_kwargs(kwargs)) return symbolic.to_callable(symbolic_function)(self.df)
def call_action(self, args, kwargs): symbolic_function = symbolic.Call(self.function, args=self.recurse_args(args), kwargs=self.recurse_kwargs(kwargs)) return symbolic.to_callable(symbolic_function)(args[0])
def test_to_callable_from_nonsymbolic_noncallable(self): test_callable = to_callable('nonsymbolic') self.assertEqual( test_callable('arg1', 'arg2', kwarg_name='kwarg value'), 'nonsymbolic')