3.7.1. sdepy.kfunc¶
-
sdepy.
kfunc
(f=None, *, nvar=None)[source]¶ Decorator to wrap classes or functions as objects with managed keyword arguments.
This decorator, intended as an aid to interactive and notebook sessions, wraps a callable, class or function, as a “kfunc” object that handles separately its parameters (keyword-only), whose values are stored in the object, and its variables (positional or keyword), always provided upon evaluation.
Syntax:
@kfunc class my_class: def __init___(self, **kwparams): ... def __call__(self, *var, **kwvar): ... @kfunc(nvar=k) def my_function(*var, **kwargs): ...
After decoration,
my_class
is a kfunc withkwparams
as parameters, and withvar
andkwvar
as variables, andmy_function
is a kfunc with the firstk
ofvar, kwargs
as variables, and the remainingkwargs
as parameters. For usage, see examples below.Examples
Wrap
wiener_source
into a kfunc, nameddw
:>>> import numpy >>> from sdepy import wiener_source, kfunc >>> dw = kfunc(wiener_source)
Instantiate
dw
and evaluate it (this is business as usual):>>> my_instance = dw(paths=100, dtype=numpy.float32) >>> x = my_instance(t=0, dt=1) >>> x.shape, x.dtype ((100,), dtype('float32'))
Inspect kfunc parameters stored in
my_instance
:>>> my_instance.params # doctest: +SKIP {'paths': 100, 'vshape': (), 'dtype': <class 'numpy.float32'>, 'corr': None, 'rho': None}
Evaluate
my_instance
changing some parameters (call the instance with one or more):>>> x = my_instance(t=0, dt=1, paths=999) >>> x.shape, x.dtype ((999,), dtype('float32'))
Parameters stored in
my_instance
are not affected:>>> my_instance.paths == my_instance.params['paths'] == 100 True
Create a new instance, changing some parameters and keeping those already set (call the instance without passing any variables):
>>> new_instance = my_instance(vshape=2, rho=0.5) >>> new_instance.params # doctest: +SKIP {'paths': 100, 'vshape': 2, 'dtype': <class 'numpy.float32'>, 'corr': None, 'rho': 0.5}
Instantiate and evaluate at once (pass one or more variables to the class constructor):
>>> x = dw(0, 1, paths=100, dtype=numpy.float32) >>> x.shape, x.dtype ((100,), dtype('float32'))
As long as variables are passed by name, order doesn’t matter (omitted variables take default values, if any):
>>> x = dw(paths=100, dtype=numpy.float32, dt=1, t=0) >>> x.shape, x.dtype ((100,), dtype('float32'))
Attributes: - params : dictionary
Parameter values stored in the instance (read-only). For wrapped
SDE
subclasses, also includes default values of all SDE-specific parameters, as stored in theargs
attribute.