Generic kernel classes¶
All kernels in lsqfitgp are subclasses of CrossKernel. The user should
almost exclusively deal with its subclass Kernel, as CrossKernel objects
are produced behind the scenes by GP.
The generic classes can be used standalone. To ease subclassing, use the decorators.
Index¶
CrossKernel, Kernel, CrossStationaryKernel, StationaryKernel,
CrossIsotropicKernel, IsotropicKernel
Classes¶
- class lsqfitgp.CrossKernel(core, *, scale=None, loc=None, derivable=None, maxdim=None, dim=None, forcekron=False, batchbytes=None, dynkw={}, **initkw)[source]¶
Base class to represent kernels, i.e., covariance functions.
A kernel is a two-argument function that computes the covariance between two functions at some points according to some probability distribution:
\[\mathrm{kernel}(x, y) = \mathrm{Cov}[f(x), g(y)].\]CrossKernelobjects are callable, the signature isobj(x, y), and they can be summed and multiplied between them and with scalars. They are immutable; all operations return new objects.- Parameters:
- corecallable
A function with signature
core(x, y), wherexandyare two broadcastable numpy arrays, which computes the value of the kernel.- scale, loc, derivable, maxdim, dim
If specified, these arguments are passed as arguments to the correspondingly named operators, in the order listed here. See
linop. Briefly: the kernel selects only fieldsdimin the input, checks the dimensionality againstmaxdim, checks there are not too many derivatives taken on the arguments, then transforms as(x - loc) / scale. If any argument is callable, it is passed**kwand must return the actual argument. If an argument is a tuple, it is interpreted as a pair of arguments.- forcekronbool, default False
If True, apply
.transf('forcekron')to the kernel, before the operations above. Available only forKernel.- batchbytesnumber, optional
If specified, apply
.batch(batchbytes)to the kernel.- dynkwdict, optional
Additional keyword arguments passed to
corethat can be modified by transformations. Deleted by transformations by default.- **initkw
Additional keyword arguments passed to
corethat can be read but not changed by transformations.
- Attributes:
- initkwdict
The
initkwargument.- dynkwdict
The
dynkwargument, or a modification of it if the object has been transformed.- corecallable
The
coreargument partially evaluated oninitkw, or another function wrapping it if the object has been transformed.
Methods
batch(maxnbytes)Return a batched version of the kernel.
linop(transfname, *args, **kw)Transform kernels to represent the application of a linear operator.
algop(transfname, *operands, **kw)Return a nonnegative algebraic transformation of the input kernels.
transf(transfname, *args, **kw)Return a transformed kernel.
register_transf(func[, transfname, doc, kind])Register a transformation for use with
transf.register_linop(op[, transfname, doc, argparser])Register a transformation for use with
linop.register_corelinop(corefunc[, transfname, ...])Register a linear operator with a function that acts only on the core.
register_xtransf(xfunc[, transfname, doc])Register a linear operator that acts only on the input.
register_algop(op[, transfname, doc])Register a transformation for use with
algop.register_ufuncalgop(ufunc[, transfname, doc])Register an algebraic operation with a function that acts only on the kernel value.
transf_help(transfname)Return the documentation of a transformation.
has_transf(transfname)Check if a transformation is registered.
list_transf([superclasses])List all the available transformations.
super_transf(transfname, self, *args, **kw)Transform the kernel using a superclass transformation.
make_linop_family(transfname, bothker, leftker)Form a family of kernels classes related by linear operators.
See also
Notes
The predefined class hierarchy and the class logic of the transformations assume that each kernel class corresponds to a subalgebra, i.e., addition and multiplication preserve the class.
- algop(transfname, *operands, **kw)[source]¶
Return a nonnegative algebraic transformation of the input kernels.
\[\begin{split}\mathrm{newkernel}(x, y) &= f(\mathrm{kernel}_1(x, y), \mathrm{kernel}_2(x, y), \ldots), \\ f(z_1, z_2, \ldots) &= \sum_{k_1,k_2,\ldots=0}^\infty a_{k_1 k_2 \ldots} z_1^{k_1} z_2^{k_2} \ldots, \quad a_* \ge 0.\end{split}\]- Parameters:
- transfnamehashable
A name identifying the transformation.
- *operandsCrossKernel, scalar
Arguments to the transformation in addition to self.
- **kw
Additional arguments to the transformation, not considered as operands.
- Returns:
- newkernelCrossKernel or NotImplemented
The transformed kernel, or NotImplemented if the operation is not supported.
See also
Notes
The class of
newkernelis the least common superclass of: the “natural” output of the operation, the class defining the transformation, and the classes of the operands.For class determination, scalars in the input count as
Constantif nonnegative or traced by jax, elseCrossConstant.
- batch(maxnbytes)[source]¶
Return a batched version of the kernel.
The batched kernel processes its inputs in chunks to try to limit memory usage.
- Parameters:
- maxnbytesnumber
The maximum number of input bytes per chunk, counted after broadcasting the input shapes. Actual broadcasting may not occur if not induced by the operations in the kernel.
- Returns:
- batched_kernelCrossKernel
The same kernel but with batched computations.
- classmethod has_transf(transfname)[source]¶
Check if a transformation is registered.
- Parameters:
- transfnamehashable
The transformation name.
- Returns:
- has_transfbool
Whether the transformation is registered.
See also
- classmethod inherit_all_algops(intermediates=False)[source]¶
Inherit all algebraic operations from superclasses.
This makes sense if the class represents a subalgebra, i.e., it should be preserved by addition and multiplication.
- Parameters:
- intermediatesbool, default False
If True, make all superclasses up to the one definining the transformation inherit it too.
- Raises:
- KeyError
An algebraic operation is already registered for one of the target classes.
See also
- classmethod inherit_transf(transfname, *, intermediates=False)[source]¶
Inherit a transformation from a superclass.
- Parameters:
- transfnamehashable
The name of the transformation.
- intermediatesbool, default False
If True, make all superclasses up to the one definining the transformation inherit it too.
- Raises:
- KeyError
The transformation was not found in any superclass, or the transformation is already registered on any of the target classes.
See also
- linop(transfname, *args, **kw)[source]¶
Transform kernels to represent the application of a linear operator.
\[\begin{split}\text{kernel}_1(x, y) &= \mathrm{Cov}[f_1(x), g_1(y)], \\ \text{kernel}_2(x, y) &= \mathrm{Cov}[f_2(x), g_2(y)], \\ &\ldots \\ \text{newkernel}(x, y) &= \mathrm{Cov}[T_f(f_1, f_2, \ldots)(x), T_g(g_1, g_2, \ldots)(y)]\end{split}\]- Parameters:
- transfnamehashable
The name of the transformation.
- *args
A sequence of
CrossKernelinstances, representing the operands, followed by one or two non-kernel arguments, indicating how to act on each side of the kernels. If both arguments represent the identity, this is a no-op. If there is only one argument, it is intended that the two arguments are equal.Nonealways represents the identity.
- Returns:
- newkernelCrossKernel
The transformed kernel.
- Raises:
- ValueError
The transformation exists but was not defined by
register_linop.
See also
Notes
The linear operator is defined on the function the kernel represents the distribution of, not in full generality on the kernel itself. When multiple kernels are involved, their distributions may be considered independent or not, depending on the specific operation.
If the result is a subclass of the class defining the transformation, the result is casted to the latter. Then, if the result and all the operands are instances of
Kernel, but the two operator arguments differ, the result is casted to its first non-Kernelsuperclass.
- classmethod list_transf(superclasses=True)[source]¶
List all the available transformations.
- Parameters:
- superclassesbool, default True
Include transformations defined in superclasses.
- Returns:
- transfs: dict of Transf
The dictionary keys are the transformation names, the values are named tuples
(tcls, kind, impl, doc)wheretclsis the class defining the transformation,kindis the kind of transformation,implis the implementation with signatureimpl(tcls, self, *args, **kw),docis the docstring.
- classmethod make_linop_family(transfname, bothker, leftker, rightker=None, *, doc=None, argparser=None, argnames=None, translkw=None)[source]¶
Form a family of kernels classes related by linear operators.
The class this method is called on is the seed class. A new trasformation is registered to obtain other classes from the seed class by applying a newly defined linop transformation.
- Parameters:
- transfnamestr
The name of the new transformation.
- bothker, leftker, rightkerCrossKernel
The kernel classes to be obtained by applying the operator to a seed class object respectively on both sides, only left, or only right. All classes are assumed to require no positional arguments at construction, and recognize the same set of keyword arguments. If
rightkeris not specified, it is defined by subclassingleftkerand transposing the kernel on object construction.- doc, argparsercallable, optional
See
register_linop.- argnamespair of str, optional
If specified,
leftkeris passed an additional keyword argument with nameargnames[0]that specifies the argument of the operator,rightkeris passedargnames[1], andbothkersimilarly is passed both.If
leftkeris used to implementrightker, it must accept both arguments, and may use them to determine if it is being invoked asleftkerorrightker.- translkwcallable, optional
A function with signature
translkw(dynkw, <argnames>, **initkw) -> dictthat determines the constructor arguments for a new object starting from the ones of the object to be transformed. By default,initkwis passed over, and an error is raised ifdynkwis not empty.
See also
Examples
>>> @lgp.kernel ... def A(x, y, *, gatto): ... ''' The reknown A kernel of order gatto ''' ... return ... ... >>> @lgp.kernel ... def T(n, m, *, gatto, op): ... ''' The kernel of the Topo series of an A process of order ... gatto ''' ... op1, op2 = op ... return ... ... >>> @lgp.crosskernel ... def CrossTA(n, x, *, gatto, op): ... ''' The cross covariance between the Topo series of an A ... process of order gatto and the process itself ''' ... return ... ... >>> A.make_linop_family('topo', T, CrossTA) >>> a = A(gatto=7) >>> ta = A.linop('topo', True, None) >>> at = A.linop('topo', None, True) >>> t = A.linop('topo', True)
- classmethod register_algop(op, transfname=None, doc=None)[source]¶
Register a transformation for use with
algop.- Parameters:
- opcallable
A function
op(tcls, *kernels, **kw) -> CrossKernel | NotImplementedthat returns the new kernel.kernelsmay be scalars but for the first argument.- transfname, doc
See
register_transf.
- Returns:
- opcallable
The
opargument as is.
See also
- classmethod register_corelinop(corefunc, transfname=None, doc=None, argparser=None)[source]¶
Register a linear operator with a function that acts only on the core.
- Parameters:
- corefunccallable
A function
corefunc(core, arg1, arg2, *cores) -> newcore, wherecoreis the function that implements the kernel passed at initialization, andcoresfor other operands.- transfname, doc, argparser
See
register_linop.
- Returns:
- corefunccallable
The
corefuncargument as is.
See also
- classmethod register_linop(op, transfname=None, doc=None, argparser=None)[source]¶
Register a transformation for use with
linop.- Parameters:
- opcallable
A function
op(tcls, self, arg1, arg2, *operands) -> CrossKernelthat returns the new kernel, wherearg1andarg2represent the operators acting on each side of the kernels, andoperandsare the other kernels beyondself.- transfname, docoptional
See
register_transf.- argparsercallable, optional
A function applied to
arg1andarg2. Not called if the argument isNone. It should map the identity toNone.
- Returns:
- opcallable
The
opargument as is.
See also
Notes
The function
opis called only ifarg1orarg2is notNoneafter potential conversion withargparser.
- classmethod register_transf(func, transfname=None, doc=None, kind=None)[source]¶
Register a transformation for use with
transf.The transformation will be accessible to subclasses.
- Parameters:
- funccallable
A function
func(tcls, self, *args, **kw) -> objectimplementing the transformation, wheretclsis the class that defines the transformation.- transfnamehashable, optional.
The
transfnameparameter totransfthis transformation will be accessible under. If not specified, use the name offunc.- docstr, optional
The documentation of the transformation for
transf_help. If not specified, use the docstring offunc.- kindobject, optional
An arbitrary marker.
- Returns:
- funccallable
The
funcargument as is.
- Raises:
- KeyError
The name is already in use for another transformation in the same class.
See also
- classmethod register_ufuncalgop(ufunc, transfname=None, doc=None)[source]¶
Register an algebraic operation with a function that acts only on the kernel value.
- Parameters:
- corefunccallable
A function
ufunc(*values, **kw) -> value, wherevaluesare the values yielded by the operands.- transfname, doc
See
register_transf.
- Returns:
- ufunccallable
The
ufuncargument as is.
See also
- classmethod register_xtransf(xfunc, transfname=None, doc=None)[source]¶
Register a linear operator that acts only on the input.
- Parameters:
- xfunccallable
A function
xfunc(arg) -> (lambda x: newx)that takes in alinopargument and produces a function to transform the input. Not called ifargisNone. To indicate the identity, returnNone.- transfname, doc
See
register_linop.argparseris not provided because its functionality can be included inxfunc.
- Returns:
- xfunccallable
The
xfuncargument as is.
See also
- classmethod super_transf(transfname, self, *args, **kw)[source]¶
Transform the kernel using a superclass transformation.
This is equivalent to
transfbut is invoked on a class and the object is passed explicitly. The definition of the transformation is searched starting from the next class in the MRO ofself.- Parameters:
- transfname, *args, **kw
See
transf.- selfCrossKernel
The object to transform.
- Returns:
- newkernelobject
The output of the transformation.
- transf(transfname, *args, **kw)[source]¶
Return a transformed kernel.
- Parameters:
- transfnamehashable
A name identifying the transformation.
- *args, **kw
Arguments to the transformation.
- Returns:
- newkernelobject
The output of the transformation.
- Raises:
- KeyError
The transformation is not defined in this class or any superclass.
- class lsqfitgp.Kernel(core, *, scale=None, loc=None, derivable=None, maxdim=None, dim=None, forcekron=False, batchbytes=None, dynkw={}, **initkw)[source]¶
Subclass of
CrossKernelto represent the kernel of a single function:\[\mathrm{kernel}(x, y) = \mathrm{Cov}[f(x), f(y)].\]
- class lsqfitgp.CrossStationaryKernel(core, *, input='signed', **kw)[source]¶
Subclass of
CrossKernelfor stationary kernels.A stationary kernel depends only on the difference, dimension by dimension, between its two arguments.
- Parameters:
- corecallable
A function taking one positional argument
delta = x - yand optional keyword arguments.- input{‘signed’, ‘posabs’, ‘abs’}, default ‘signed’
If
'signed',kernelis passed the bare difference. If'posabs',kernelis passed the absolute value of the difference, and the difference of equal points is a small number instead of zero. If'abs', the absolute value.- **kw
Additional keyword arguments are passed to the
CrossKernelconstructor.
- class lsqfitgp.CrossIsotropicKernel(core, *, input='squared', **kw)[source]¶
Subclass of
CrossStationaryKernelfor isotropic kernels.An isotropic kernel depends only on the Euclidean distance between its two arguments.
- Parameters:
- corecallable
A function taking one argument
r2which is the squared distance between x and y, plus optionally keyword arguments.- input{‘squared’, ‘abs’, ‘posabs’, ‘raw’}, default ‘squared’
If
'squared',coreis passed the squared distance. If'abs', it is passed the distance (not squared). If'posabs', it is passed the distance, and the distance of equal points is a small number instead of zero. If'raw',coreis passed both points separately like non-stationary kernels.- **kw
Additional keyword arguments are passed to the
CrossKernelconstructor.
Notes
The
input='posabs'option will cause problems with second derivatives in more than one dimension.