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)].\]

CrossKernel objects are callable, the signature is obj(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), where x and y are 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 fields dim in the input, checks the dimensionality against maxdim, 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 **kw and 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 for Kernel.

batchbytesnumber, optional

If specified, apply .batch(batchbytes) to the kernel.

dynkwdict, optional

Additional keyword arguments passed to core that can be modified by transformations. Deleted by transformations by default.

**initkw

Additional keyword arguments passed to core that can be read but not changed by transformations.

See also

Kernel

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.

Attributes:
initkwdict

The initkw argument.

dynkwdict

The dynkw argument, or a modification of it if the object has been transformed.

corecallable

The core argument partially evaluated on initkw, 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.

class Transf(tcls, kind, func, doc)[source]

Create new instance of Transf(tcls, kind, func, doc)

doc

Alias for field number 3

func

Alias for field number 2

kind

Alias for field number 1

tcls

Alias for field number 0

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

transf

Notes

The class of newkernel is 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 Constant if nonnegative or traced by jax, else CrossConstant.

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

transf
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

transf
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

transf
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 CrossKernel instances, 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. None always represents the identity.

Returns:
newkernelCrossKernel

The transformed kernel.

Raises:
ValueError

The transformation exists but was not defined by register_linop.

See also

transf

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-Kernel superclass.

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) where tcls is the class defining the transformation, kind is the kind of transformation, impl is the implementation with signature impl(tcls, self, *args, **kw), doc is 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 rightker is not specified, it is defined by subclassing leftker and transposing the kernel on object construction.

doc, argparsercallable, optional

See register_linop.

argnamespair of str, optional

If specified, leftker is passed an additional keyword argument with name argnames[0] that specifies the argument of the operator, rightker is passed argnames[1], and bothker similarly is passed both.

If leftker is used to implement rightker, it must accept both arguments, and may use them to determine if it is being invoked as leftker or rightker.

translkwcallable, optional

A function with signature translkw(dynkw, <argnames>, **initkw) -> dict that determines the constructor arguments for a new object starting from the ones of the object to be transformed. By default, initkw is passed over, and an error is raised if dynkw is not empty.

See also

transf

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 | NotImplemented that returns the new kernel. kernels may be scalars but for the first argument.

transfname, doc

See register_transf.

Returns:
opcallable

The op argument as is.

See also

transf
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, where core is the function that implements the kernel passed at initialization, and cores for other operands.

transfname, doc, argparser

See register_linop.

Returns:
corefunccallable

The corefunc argument as is.

See also

transf
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) -> CrossKernel that returns the new kernel, where arg1 and arg2 represent the operators acting on each side of the kernels, and operands are the other kernels beyond self.

transfname, docoptional

See register_transf.

argparsercallable, optional

A function applied to arg1 and arg2. Not called if the argument is None. It should map the identity to None.

Returns:
opcallable

The op argument as is.

See also

transf

Notes

The function op is called only if arg1 or arg2 is not None after potential conversion with argparser.

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) -> object implementing the transformation, where tcls is the class that defines the transformation.

transfnamehashable, optional.

The transfname parameter to transf this transformation will be accessible under. If not specified, use the name of func.

docstr, optional

The documentation of the transformation for transf_help. If not specified, use the docstring of func.

kindobject, optional

An arbitrary marker.

Returns:
funccallable

The func argument as is.

Raises:
KeyError

The name is already in use for another transformation in the same class.

See also

transf
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, where values are the values yielded by the operands.

transfname, doc

See register_transf.

Returns:
ufunccallable

The ufunc argument as is.

See also

transf
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 a linop argument and produces a function to transform the input. Not called if arg is None. To indicate the identity, return None.

transfname, doc

See register_linop. argparser is not provided because its functionality can be included in xfunc.

Returns:
xfunccallable

The xfunc argument as is.

See also

transf
classmethod super_transf(transfname, self, *args, **kw)[source]

Transform the kernel using a superclass transformation.

This is equivalent to transf but 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 of self.

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.

classmethod transf_help(transfname)[source]

Return the documentation of a transformation.

Parameters:
transfnamehashable

The name of the transformation.

Returns:
docstr

The documentation of the transformation.

See also

transf

class lsqfitgp.Kernel(core, *, scale=None, loc=None, derivable=None, maxdim=None, dim=None, forcekron=False, batchbytes=None, dynkw={}, **initkw)[source]

Subclass of CrossKernel to 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 CrossKernel for 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 - y and optional keyword arguments.

input{‘signed’, ‘posabs’, ‘abs’}, default ‘signed’

If 'signed', kernel is passed the bare difference. If 'posabs', kernel is 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 CrossKernel constructor.


class lsqfitgp.StationaryKernel(core, *, input='signed', **kw)[source]

class lsqfitgp.CrossIsotropicKernel(core, *, input='squared', **kw)[source]

Subclass of CrossStationaryKernel for isotropic kernels.

An isotropic kernel depends only on the Euclidean distance between its two arguments.

Parameters:
corecallable

A function taking one argument r2 which is the squared distance between x and y, plus optionally keyword arguments.

input{‘squared’, ‘abs’, ‘posabs’, ‘raw’}, default ‘squared’

If 'squared', core is 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', core is passed both points separately like non-stationary kernels.

**kw

Additional keyword arguments are passed to the CrossKernel constructor.

Notes

The input='posabs' option will cause problems with second derivatives in more than one dimension.


class lsqfitgp.IsotropicKernel(core, *, input='squared', **kw)[source]