Distributions

HypertoroidalWNDistribution = HypertoroidalWrappedNormalDistribution module-attribute

WNDistribution = WrappedNormalDistribution module-attribute

HypertoroidalWDDistribution = HypertoroidalDiracDistribution module-attribute

ToroidalWDDistribution = ToroidalDiracDistribution module-attribute

VMDistribution = VonMisesDistribution module-attribute

WDDistribution = CircularDiracDistribution module-attribute

VMFDistribution = VonMisesFisherDistribution module-attribute

WEDistribution = WrappedExponentialDistribution module-attribute

aliases = ['HypertoroidalWNDistribution', 'WNDistribution', 'HypertoroidalWDDistribution', 'ToroidalWDDistribution', 'VMDistribution', 'WDDistribution', 'VMFDistribution', 'WEDistribution'] module-attribute

__all__ = aliases + ['GvMDistribution', 'ConversionError', 'ConversionResult', 'can_convert', 'convert_distribution', 'register_conversion', 'register_conversion_alias', 'registered_conversion_aliases', 'registered_conversions', 'GeneralizedKSineSkewedVonMisesDistribution', 'AbstractBoundedDomainDistribution', 'AbstractBoundedNonPeriodicDistribution', 'AbstractCustomDistribution', 'AbstractCustomNonPeriodicDistribution', 'AbstractDiracDistribution', 'AbstractDiskDistribution', 'AbstractDistributionType', 'AbstractEllipsoidalBallDistribution', 'AbstractGridDistribution', 'AbstractManifoldSpecificDistribution', 'AbstractMixture', 'AbstractNonperiodicDistribution', 'AbstractOrthogonalBasisDistribution', 'AbstractPeriodicDistribution', 'AbstractPeriodicGridDistribution', 'AbstractSE2Distribution', 'AbstractSE3Distribution', 'AbstractUniformDistribution', 'AbstractCartProdDistribution', 'AbstractCustomLinBoundedCartProdDistribution', 'AbstractHypercylindricalDistribution', 'AbstractLinBoundedCartProdDistribution', 'AbstractLinHemisphereCartProdDistribution', 'AbstractLinHyperhemisphereCartProdDistribution', 'AbstractLinHypersphereCartProdDistribution', 'AbstractLinHypersphereSubsetCartProdDistribution', 'AbstractLinPeriodicCartProdDistribution', 'CartProdDiracDistribution', 'HyperhemisphericalDiracDistribution', 'HypersphericalDiracDistribution', 'CartProdStackedDistribution', 'CustomHypercylindricalDistribution', 'HypercylindricalDiracDistribution', 'HyperhemisphereCartProdDiracDistribution', 'LinBoundedCartProdDiracDistribution', 'LinHypersphereCartProdDiracDistribution', 'LinHypersphereSubsetCartProdDiracDistribution', 'LinPeriodicCartProdDiracDistribution', 'PartiallyWrappedNormalDistribution', 'SE2PWNDistribution', 'MardiaSuttonDistribution', 'StateSpaceSubdivisionDistribution', 'StateSpaceSubdivisionGaussianDistribution', 'AbstractCircularDistribution', 'CircularDiracDistribution', 'CircularFourierDistribution', 'CircularMixture', 'CircularUniformDistribution', 'CustomCircularDistribution', 'AbstractSineSkewedDistribution', 'GeneralizedKSineSkewedVonMisesDistribution', 'GeneralizedKSineSkewedWrappedCauchyDistribution', 'GSSVMDistribution', 'SineSkewedVonMisesDistribution', 'SineSkewedWrappedCauchyDistribution', 'SineSkewedWrappedNormalDistribution', 'PiecewiseConstantDistribution', 'VonMisesDistribution', 'WrappedCauchyDistribution', 'WrappedExponentialDistribution', 'WrappedLaplaceDistribution', 'WrappedNormalDistribution', 'AbstractConditionalDistribution', 'S2CondS2GridDistribution', 'SdCondSdGridDistribution', 'SdHalfCondSdHalfGridDistribution', 'TdCondTdGridDistribution', 'CustomHyperrectangularDistribution', 'DiskUniformDistribution', 'EllipsoidalBallUniformDistribution', 'AbstractHemisphericalDistribution', 'AbstractHyperhemisphericalDistribution', 'AbstractHypersphereSubsetDiracDistribution', 'AbstractHypersphereSubsetDistribution', 'AbstractHypersphereSubsetGridDistribution', 'AbstractHypersphereSubsetUniformDistribution', 'AbstractHypersphericalDistribution', 'AbstractSphereSubsetDistribution', 'AbstractSphericalDistribution', 'AbstractSphericalHarmonicsDistribution', 'BinghamDistribution', 'ComplexWatsonDistribution', 'AbstractComplexHypersphericalDistribution', 'ComplexBinghamDistribution', 'ComplexAngularCentralGaussianDistribution', 'CustomHemisphericalDistribution', 'CustomHyperhemisphericalDistribution', 'CustomHypersphericalDistribution', 'HemisphericalUniformDistribution', 'HyperhemisphericalBinghamDistribution', 'HyperhemisphericalDiracDistribution', 'HyperhemisphericalGridDistribution', 'HyperhemisphericalUniformDistribution', 'HyperhemisphericalWatsonDistribution', 'HypersphericalDiracDistribution', 'HypersphericalGridDistribution', 'HypersphericalMixture', 'HypersphericalUniformDistribution', 'SphericalGridDistribution', 'SphericalHarmonicsDistributionComplex', 'SphericalHarmonicsDistributionReal', 'VonMisesFisherDistribution', 'WatsonDistribution', 'AbstractHypertoroidalDistribution', 'AbstractToroidalBivarVMDistribution', 'AbstractToroidalDistribution', 'CustomHypertoroidalDistribution', 'CustomToroidalDistribution', 'HypertoroidalDiracDistribution', 'HypertoroidalFourierDistribution', 'HypertoroidalGridDistribution', 'HypertoroidalMixture', 'HypertoroidalUniformDistribution', 'HypertoroidalWrappedNormalDistribution', 'ToroidalDiracDistribution', 'ToroidalFourierDistribution', 'ToroidalMixture', 'ToroidalUniformDistribution', 'ToroidalVonMisesCosineDistribution', 'ToroidalVonMisesSineDistribution', 'ToroidalVMMatrixDistribution', 'ToroidalVMRivestDistribution', 'ToroidalWrappedNormalDistribution', 'AbstractHyperrectangularDistribution', 'AbstractLinearDistribution', 'CustomLinearDistribution', 'GaussianDistribution', 'GaussianMixture', 'LinearBoxParticleDistribution', 'HyperrectangularUniformDistribution', 'LinearDiracDistribution', 'LinearMixture', 'SE2DiracDistribution', 'SE3CartProdStackedDistribution', 'SE3DiracDistribution', 'SO3ProductDiracDistribution', 'SO3BinghamDistribution', 'SO3TangentGaussianDistribution', 'SO3UniformDistribution', 'SO3DiracDistribution', 'SO3ProductTangentGaussianDistribution', 'SE2BinghamDistribution'] module-attribute

AbstractBoundedDomainDistribution

Bases: AbstractManifoldSpecificDistribution

Abstract class for distributions with bounded domains.

This class extends the AbstractManifoldSpecificDistribution class, and serves as the base class for all distributions that are defined over bounded domains. This class does not define any methods or properties and is intended to be subclassed by specific distributions.

AbstractBoundedNonPeriodicDistribution

Bases: AbstractBoundedDomainDistribution

Abstract class for distributions with on non-periodic bounded domains.

This class extends the AbstractBoundedDomainDistribution class, and serves as the base class for all distributions that are defined over non-periodic bounded domains.

mean()

AbstractCustomDistribution

Bases: AbstractDistributionType

Abstract class for creating distributions based on callable functions.

This class accepts a function f that calculates the probability density function and a scaling factor scale_by to adjust the PDF.

Methods: - pdf(xs : Union[float, ]) -> Union[float, ]: Compute the probability density function at given points. - integrate(integration_boundaries: Optional[Union[float, Tuple[float, float]]] = None) -> float: Calculate the integral of the probability density function. - normalize(verify : Optional[bool] = None) -> AbstractCustomDistribution: Normalize the PDF such that its integral is 1. Returns a copy of the original distribution.

f = f instance-attribute

scale_by = scale_by instance-attribute

__init__(f, scale_by=1)

Initialize AbstractCustomDistribution.

Parameters:

Name Type Description Default
f

The function that calculates the probability density function.

required
scale_by

Scaling factor to adjust the PDF, default is 1.

1

pdf(xs)

Compute the probability density function at given points.

Parameters:

Name Type Description Default
xs

Points at which to compute the PDF.

required

Returns:

Type Description

PDF values at given points.

integrate(integration_boundaries=None) abstractmethod

Calculate the integral of the probability density function.

Parameters:

Name Type Description Default
integration_boundaries

The boundaries of integration, default is None.

None

Returns:

Type Description

The integral of the PDF.

normalize(verify=None)

Normalize the PDF such that its integral is 1.

Parameters:

Name Type Description Default
verify bool | None

Whether to verify if the density is properly normalized, default is None.

None

Returns:

Type Description
AbstractCustomDistribution

A copy of the original distribution, with the PDF normalized.

AbstractCustomNonPeriodicDistribution

Bases: AbstractCustomDistribution, AbstractNonperiodicDistribution

This class serves as a base for all custom non-periodic distributions.

Custom non-periodic distributions are distributions that are defined by a given probability density function and are not periodic.

AbstractDiracDistribution

Bases: AbstractDistributionType

This class represents an abstract base for Dirac distributions.

d = copy.copy(d) instance-attribute

w = ones(d.shape[0]) / d.shape[0] instance-attribute

__init__(d, w=None)

Initialize a Dirac distribution with given Dirac locations and weights.

Parameters:

Name Type Description Default
d

Dirac locations as a numpy array.

required
w

Weights of Dirac locations as a numpy array. If not provided, defaults to uniform weights.

None

normalize_in_place()

Normalize the weights in-place to ensure they sum to 1.

normalize()

apply_function(f, function_is_vectorized=True)

Apply a function to the Dirac locations and return a new distribution.

Parameters:

Name Type Description Default
f Callable

Function to apply.

required

Returns:

Type Description

A new distribution with the function applied to the locations.

reweigh(f)

sample(n)

entropy()

integrate(left=None, right=None)

log_likelihood(*args)

pdf(_)

integrate_numerically(*args)

trigonometric_moment_numerical(*args)

sample_metropolis_hastings(*args)

squared_distance_numerical(*args)

kld_numerical(*args)

mode(rel_tol=0.001)

mode_numerical(_=None)

entropy_numerical()

is_valid_for_conversion(distribution) classmethod

from_distribution(distribution, n_particles) classmethod

AbstractDiskDistribution

Bases: AbstractEllipsoidalBallDistribution

This class represents an abstract base for distributions on the unit disk.

__init__()

mean()

AbstractDistributionType

Bases: ABC

This class represents an abstract base for specific types of distributions, regardless of their domain (uniform, mixture, custom, etc.)

convert_to(target_type, /, *, return_info=False, **kwargs)

Convert or approximate this distribution as target_type.

This is a convenience wrapper around :func:pyrecest.distributions.convert_distribution. target_type may be either a concrete distribution class or a registered conversion alias.

Parameters

target_type Concrete target representation class or conversion alias. return_info If true, return a ConversionResult containing metadata. **kwargs Conversion parameters required by the target representation.

approximate_as(target_type, /, *, return_info=False, **kwargs)

Alias for :meth:convert_to emphasizing approximate conversions.

AbstractEllipsoidalBallDistribution

Bases: AbstractBoundedNonPeriodicDistribution

This class represents distributions on ellipsoidal balls.

center = center instance-attribute

shape_matrix = shape_matrix instance-attribute

__init__(center, shape_matrix)

Initialize the class with a center and shape matrix.

Parameters:

Name Type Description Default
center

The center of the ellipsoidal ball.

required
shape_matrix

The shape matrix of the ellipsoidal ball.

required

get_manifold_size()

Calculate the size of the manifold.

Returns:

Type Description

The size of the manifold.

AbstractGridDistribution

Bases: AbstractDistributionType

grid_values = grid_values instance-attribute

grid_type = grid_type instance-attribute

grid = grid instance-attribute

enforce_pdf_nonnegative = enforce_pdf_nonnegative instance-attribute

grid_density_description = {'n_grid_values': grid_values.shape[0], 'grid_type': grid_type} instance-attribute

n_grid_points property

__init__(grid_values, grid_type='custom', grid=None, dim=None, enforce_pdf_nonnegative=True)

pdf(xs)

get_closest_point(xs) abstractmethod

get_manifold_size() abstractmethod

integrate(integration_boundaries=None)

normalize_in_place(tol=0.0001, warn_unnorm=True)

normalize(tol=0.0001, warn_unnorm=True)

get_grid()

get_grid_point(indices)

multiply(other)

AbstractManifoldSpecificDistribution

Bases: ABC

Abstract base class for distributions catering to specific manifolds. Should be inerhited by (abstract) classes limited to specific manifolds.

dim property writable

Get dimension of the manifold.

input_dim abstractmethod property

__init__(dim)

get_manifold_size() abstractmethod

get_ln_manifold_size()

convert_to(target_type, /, *, return_info=False, **kwargs)

Convert or approximate this distribution as target_type.

This is a convenience wrapper around :func:pyrecest.distributions.convert_distribution. target_type may be either a concrete distribution class or a registered conversion alias such as "particles" or "gaussian".

Parameters

target_type Concrete target representation class or conversion alias. return_info If true, return a ConversionResult containing metadata. **kwargs Conversion parameters required by the target representation.

approximate_as(target_type, /, *, return_info=False, **kwargs)

Alias for :meth:convert_to emphasizing approximate conversions.

pdf(xs) abstractmethod

ln_pdf(xs)

mean() abstractmethod

Convenient access to a reasonable "mean" for different manifolds.

Returns:

Type Description

The mean of the distribution.

set_mode(_)

Set the mode of the distribution

sample(n)

Obtain n samples from the distribution.

sample_metropolis_hastings(n, burn_in=10, skipping=5, proposal=None, start_point=None)

Metropolis Hastings sampling algorithm.

AbstractMixture

Bases: AbstractDistributionType

Abstract base class for mixture distributions.

dists = dists instance-attribute

w = weights / sum(weights) instance-attribute

input_dim property

__init__(dists, weights=None)

sample(n)

pdf(xs)

AbstractNonperiodicDistribution

Bases: AbstractManifoldSpecificDistribution

Abstract base class for all distributions on non-periodic manifolds.

AbstractOrthogonalBasisDistribution

Bases: AbstractDistributionType

Abstract base class for distributions based on orthogonal basis functions.

transformation = transformation instance-attribute

coeff_mat = coeff_mat instance-attribute

__init__(coeff_mat, transformation)

Initialize the distribution.

Parameters:

Name Type Description Default
coeff_mat

Coefficient matrix.

required
transformation

Transformation function. Possible values are "sqrt", "identity", "log".

required

normalize_in_place() abstractmethod

Abstract method to normalize the distribution. Implementation required in subclasses.

value(xs) abstractmethod

Abstract method to get value of the distribution for given input. Implementation required in subclasses.

Parameters:

Name Type Description Default
xs

Input data for value calculation.

required

normalize()

Normalizes the distribution.

Returns:

Type Description

Normalized distribution.

pdf(xs)

Calculates probability density function for the given input.

Parameters:

Name Type Description Default
xs

Input data for PDF calculation.

required

Returns:

Type Description

PDF value.

AbstractPeriodicDistribution

Bases: AbstractBoundedDomainDistribution

Abstract class for a distributions on periodic manifolds.

__init__(dim)

mean()

Convenient access to mean_direction to have a consistent interface throughout manifolds.

Returns:

Type Description

The mean of the distribution.

mean_direction() abstractmethod

Abstract method to compute the mean direction of the distribution.

Returns

mean_direction: The mean direction of the distribution.

AbstractPeriodicGridDistribution

Bases: AbstractGridDistribution, AbstractPeriodicDistribution

Abstract base class for grid distributions on periodic domains.

AbstractSE2Distribution

Bases: AbstractHypercylindricalDistribution

__init__()

plot_state(scaling_factor=1, circle_color=None, angle_color=None)

angle_pos_to_dual_quaternion(x) staticmethod

dual_quaternion_to_angle_pos(dq) staticmethod

plot_trajectory(periodic_states, lin_states, animate=False, delay=0.05, arrow_scaling=1, pos_color=None, angle_color=None, fade=False) staticmethod

AbstractSE3Distribution

Bases: AbstractLinBoundedCartProdDistribution

input_dim property

__init__()

mode() abstractmethod

plot_mode()

plot_state(orientationSamples=10, showMarginalized=True)

plot_point(se3point) staticmethod

Visualize just a point in the SE(3) domain (no uncertainties are considered)

plot_trajectory(periodicStates, linStates, animate=False, delay=0.05) staticmethod

get_manifold_size()

AbstractUniformDistribution

Bases: AbstractDistributionType

Abstract class for a uniform distribution on a manifold.

pdf(xs)

Compute the probability density function at each point in xs.

Parameters:

Name Type Description Default
xs

Points at which to compute the pdf.

required

Returns:

Type Description

The pdf evaluated at each point in xs.

get_manifold_size() abstractmethod

Compute the size of the distribution's manifold.

Returns:

Type Description

Size of the manifold.

mode()

Mode is not defined for a uniform distribution.

AbstractCartProdDistribution

Bases: AbstractManifoldSpecificDistribution

For arbitrary Cartesian products, such as ones of linear and bounded or hypertori and hypersphere, etc.

AbstractCustomLinBoundedCartProdDistribution

Bases: AbstractCustomDistribution, AbstractLinPeriodicCartProdDistribution

Is abstract because .input_dim (among others) cannot be properly defined without specifying the specific periodic dimension

__init__(f_, bound_dim, lin_dim)

Parameters: f_ (callable) pdf of the distribution bound_dim (int) dimension of the bounded part of the manifold lin_dim (int) dimension of the linear part of the manifold

AbstractHypercylindricalDistribution

Bases: AbstractLinPeriodicCartProdDistribution

input_dim property

__init__(bound_dim, lin_dim)

pdf(xs) abstractmethod

integrate(integration_boundaries=None)

integrate_numerically(integration_boundaries=None)

get_reasonable_integration_boundaries(scalingFactor=10)

Returns reasonable integration boundaries for the specific distribution based on the mode and covariance.

mode()

Find the mode of the distribution by calling mode_numerical.

linear_covariance(approximate_mean=None)

Calculates the linear covariance, or calls linear_covariance_numerical if a non-numerical solution doesn't exist.

Parameters: - approximate_mean : ndarray, optional The approximate mean to be used. If None, uses NaNs to flag for calculation.

Returns: - C : ndarray The linear covariance.

linear_covariance_numerical(approximate_mean=None)

Numerically calculates the linear covariance.

Parameters: - approximate_mean : ndarray, optional The approximate mean to be used. If None, calculates the mean.

Returns: - C : ndarray The linear covariance.

condition_on_linear(input_lin, normalize=True)

Condition on linear.

Parameters: lin_input : ndarray Input array. normalize : bool, optional If True (default), normalizes the distribution.

Returns: dist : CustomHypertoroidalDistribution The distribution after conditioning.

condition_on_periodic(input_periodic, normalize=True)

Conditions the distribution on periodic variables

Arguments: input_periodic: ndarray Input data, assumed to have shape (self.bound_dim,) normalize: bool If True, normalizes the distribution

Returns: dist: CustomLinearDistribution CustomLinearDistribution instance

linear_mean_numerical()

mode_numerical(starting_point=None)

Find the mode of the distribution numerically.

Parameters: starting_point : ndarray, optional The starting point for the optimization. If None, uses [pi * ones(self.bound_dim); zeros(self.lin_dim)]

Returns: m : ndarray The mode of the distribution.

plot(*args, **kwargs)

plot_cylinder(limits_linear=None)

AbstractLinBoundedCartProdDistribution

Bases: AbstractCartProdDistribution

For Cartesian products of linear and bounded (periodic or parts of Euclidean spaces) domains. Assumption is that the input dimensions are ordered as follows: bounded dimensions first, then linear dimensions.

bound_dim = bound_dim instance-attribute

lin_dim = lin_dim instance-attribute

__init__(bound_dim, lin_dim)

Parameters: bound_dim (int) number of bounded (e.g., periodic or hyperrectangular) dimensions lin_dim (int) number of linear dimensions

mean()

Convenient access to hybrid_mean() to have a consistent interface throughout manifolds.

Returns:

Type Description

The mean of the distribution.

hybrid_mean()

marginalize_linear() abstractmethod

marginalize_periodic() abstractmethod

AbstractLinHemisphereCartProdDistribution

AbstractLinHyperhemisphereCartProdDistribution

AbstractLinHypersphereSubsetCartProdDistribution

AbstractLinPeriodicCartProdDistribution

Bases: AbstractLinBoundedCartProdDistribution

For Cartesian products of linear and periodic domains. Assumption is that it is bounded x R^n (in this order)

__init__(bound_dim, lin_dim)

get_manifold_size()

CartProdDiracDistribution

CartProdStackedDistribution

Bases: AbstractCartProdDistribution

dists = dists instance-attribute

__init__(dists)

sample(n)

pdf(xs)

shift(shift_by)

set_mode(new_mode)

hybrid_mean()

mean()

Convenient access to hybrid_mean() to have a consistent interface throughout manifolds.

Returns:

Type Description

The mean of the distribution.

mode()

CustomHypercylindricalDistribution

Bases: AbstractCustomLinBoundedCartProdDistribution, AbstractHypercylindricalDistribution

__init__(f, bound_dim, lin_dim)

Constructor, it is the user's responsibility to ensure that f is a valid hypertoroidal density and takes arguments of the same form as .pdf, i.e., it needs to be vectorized.

Parameters: f (function handle) pdf of the distribution bound_dim (scalar) dimension of the hypertorus lin_dim (scalar) linear dimension

from_distribution(distribution) staticmethod

Create a CustomHypercylindricalDistribution from another AbstractHypercylindricalDistribution.

Parameters: dist (AbstractHypercylindricalDistribution) The distribution to convert into a CustomHypercylindricalDistribution

Returns: chhd (CustomHypercylindricalDistribution) The created CustomHypercylindricalDistribution

integrate(integration_boundaries=None)

condition_on_periodic(input_periodic, normalize=True)

condition_on_linear(input_lin, normalize=True)

marginalize_linear()

marginalize_periodic()

HypercylindricalDiracDistribution

Bases: LinBoundedCartProdDiracDistribution, AbstractHypercylindricalDistribution

__init__(bound_dim, d, w=None)

pdf(xs)

marginalize_periodic()

marginalize_linear()

hybrid_moment()

plot(*args, **kwargs)

HyperhemisphereCartProdDiracDistribution

Bases: AbstractDiracDistribution, AbstractCartProdDistribution

dim_hemisphere = dim_hemisphere instance-attribute

n_hemispheres = n_hemispheres instance-attribute

dim = dim_hemisphere * n_hemispheres instance-attribute

component_dim property

input_dim property

__init__(d, w=None, dim_hemisphere=None, n_hemispheres=None, *, store_flat=True)

Initialize a Dirac distribution with given Dirac locations and weights.

Parameters:

Name Type Description Default
d

Dirac locations as a numpy array.

required
w

Weights of Dirac locations as a numpy array. If not provided, defaults to uniform weights.

None

as_component_array()

Return locations with shape (n, n_hemispheres, dim_hemisphere + 1).

as_flat_array()

Return locations with shape (n, (dim_hemisphere + 1) * n_hemispheres).

component_particles(component_index)

Return Dirac locations for one hyperhemisphere component.

get_manifold_size()

moment(component_index=None)

Return weighted second moments for the product components.

mean_axis(component_index=None)

Return weighted principal axes for the product components.

mean()

apply_function_component_wise(f, f_supports_multiple=True)

Apply a function to the Dirac locations and return a new distribution.

Parameters:

Name Type Description Default
f Callable

Function to apply.

required

Returns:

Type Description

A new distribution with the function applied to the locations.

LinBoundedCartProdDiracDistribution

Bases: AbstractDiracDistribution, AbstractLinBoundedCartProdDistribution

marginalize_periodic()

linear_mean()

linear_covariance(approximate_mean=False)

marginalize_linear() abstractmethod

hybrid_mean()

from_distribution(distribution, n_particles) classmethod

Needs to be overwritten to allow the specification of bound_dim for Cartesian products of bounded and Euclidean manifolds

LinHypersphereCartProdDiracDistribution

Bases: LinBoundedCartProdDiracDistribution, AbstractSE3Distribution

input_dim property

__init__(bound_dim, d, w=None)

LinHypersphereSubsetCartProdDiracDistribution

LinPeriodicCartProdDiracDistribution

MardiaSuttonDistribution

Bases: AbstractHypercylindricalDistribution

Gauss-von Mises distribution for cylindrical data (1 circular + 1 linear dimension).

Mardia, K. V. & Sutton, T. W. A Model for Cylindrical Variables with Applications Journal of the Royal Statistical Society. Series B (Methodological), Wiley for the Royal Statistical Society, 1978, 40, pp. 229-233

mu = mu instance-attribute

mu0 = mod(mu0, 2.0 * pi) instance-attribute

kappa = kappa instance-attribute

rho1 = rho1 instance-attribute

rho2 = rho2 instance-attribute

sigma = sigma instance-attribute

__init__(mu, mu0, kappa, rho1, rho2, sigma)

Parameters: mu (scalar): linear mean mu0 (scalar): circular mean (wrapped to [0, 2π)) kappa (positive scalar): circular concentration rho1 (scalar): first correlation parameter rho2 (scalar): second correlation parameter sigma (positive scalar): linear standard deviation

get_mu_sigma(xa_circular)

Compute the conditional mean and std of the linear variable given circular values.

Parameters: xa_circular: circular variable values

Returns: muc: conditional mean of the linear variable (same shape as xa_circular) sigmac: conditional std of the linear variable (positive scalar)

pdf(xs)

Evaluate the pdf at each row of xs.

Parameters: xs (..., 2): locations where to evaluate the pdf; first column is circular (θ), second is linear (x)

Returns: p (...,): value of the pdf at each location

mode()

Return the mode of the distribution.

Returns: m (2,): mode [mu0, mu] (circular first, then linear)

sample(n)

Obtain n samples from the distribution.

Parameters: n (int): number of samples

Returns: s (n, 2): n samples on [0, 2π) × R (circular first, then linear)

linear_covariance(approximate_mean=None)

Return the intrinsic linear variance as a (1, 1) matrix.

Returns: C (1, 1): [[sigma^2]]

marginalize_linear()

Return the marginal circular distribution.

The marginal over the linear variable is a Von Mises distribution since the conditional Gaussian integrates to one.

Returns: vm: VonMisesDistribution(mu0, kappa)

marginalize_periodic()

Return the marginal linear distribution by integrating out the circular variable.

Returns: dist: CustomLinearDistribution representing the marginal over the linear variable

get_reasonable_integration_boundaries(scalingFactor=10)

integrate_numerically(integration_boundaries=None)

PartiallyWrappedNormalDistribution

Bases: AbstractHypercylindricalDistribution

Partially wrapped normal distribution on periodic-linear domains.

References

Kurz, G., Gilitschenski, I., & Hanebeck, U. D. (2014). The Partially Wrapped Normal Distribution for SE(2) Estimation. Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration.

mu = where(arange(mu.shape[0]) < bound_dim, mod(mu, 2.0 * pi), mu) instance-attribute

C = C instance-attribute

__init__(mu, C, bound_dim)

pdf(xs, m=3)

mode()

Determines the mode of the distribution, i.e., the point where the pdf is largest. Returns: m (lin_dim + bound_dim,) vector: the mode

set_mean(new_mean)

Return a copy of this distribution with the location parameter shifted to new_mean.

For bounded dimensions, the mean is wrapped into [0, 2*pi) to stay on the manifold.

set_mode(new_mode)

hybrid_moment()

Calculates mean of [x1, x2, .., x_lin_dim, cos(x_(linD+1), sin(x_(linD+1)), ..., cos(x_(linD+boundD), sin(x_(lin_dim+bound_dim))] Returns: mu (linD+2): expectation value of [x1, x2, .., x_lin_dim, cos(x_(lin_dim+1), sin(x_(lin_dim+1)), ..., cos(x_(lin_dim+bound_dim), sin(x_(lin_dim+bound_dim))]

hybrid_mean()

linear_mean()

periodic_mean()

sample(n)

Sample n points from the distribution Parameters: n (int): number of points to sample

to_gaussian()

linear_covariance(approximate_mean=None)

marginalize_periodic()

marginalize_linear()

SE2BinghamDistribution

Bases: AbstractSE2Distribution

Distribution on SE(2) = S^1 x R^2.

The density is f(x) = (1/NC) * exp(x^T * C * x) where x is the dual quaternion representation (first two components on S^1, last two components in R^2).

C is a 4x4 symmetric matrix partitioned as::

C = [ C1   C2^T ]
    [ C2   C3   ]

where: - C1 (2x2): symmetric, controls the Bingham (rotational) part - C2 (2x2): coupling between rotation and translation - C3 (2x2): symmetric, negative-definite, controls the Gaussian (translational) part

Reference: Igor Gilitschenski, Gerhard Kurz, Simon J. Julier, Uwe D. Hanebeck, "A New Probability Distribution for Simultaneous Representation of Uncertain Position and Orientation", Proceedings of the 17th International Conference on Information Fusion (Fusion 2014), Salamanca, Spain, July 2014.

C = C instance-attribute

C1 = C[:2, :2] instance-attribute

C2 = C[2:, :2] instance-attribute

C3 = C[2:, 2:] instance-attribute

nc property

Normalization constant (lazily computed).

__init__(C, C2=None, C3=None)

Create an SE2BinghamDistribution.

Parameters

C : array_like, shape (4, 4) or (2, 2) If C2 and C3 are not provided, this is the full 4x4 parameter matrix. Otherwise it is the 2x2 Bingham (rotational) part C1. C2 : array_like, shape (2, 2), optional Coupling matrix between rotation and translation. C3 : array_like, shape (2, 2), optional Symmetric negative-definite matrix for the translational part.

pdf(xs)

Evaluate the probability density at the given points.

Parameters

xs : array_like, shape (N, 4) or (N, 3) Evaluation points in dual quaternion (N x 4) or angle-pos (N x 3) representation.

Returns

p : array, shape (N,) Density values.

mode()

Compute one mode of the distribution.

Because of antipodal symmetry, -mode is equally valid.

Returns

m : array, shape (4,) Mode in dual quaternion representation.

sample(n)

Draw n samples from the distribution.

Sampling uses a two-step procedure: 1. Sample the rotational part from the Bingham marginal. 2. Sample the translational part from the Gaussian conditional.

Parameters

n : int Number of samples.

Returns

s : array, shape (n, 4) Samples in dual quaternion representation.

marginalize_linear()

Return the marginal distribution over the periodic (rotational) part.

The marginal is the Bingham distribution corresponding to the Schur complement BM = C1 - C2^T * C3^{-1} * C2.

Returns

b : BinghamDistribution Marginal Bingham distribution on S^1.

marginalize_periodic()

Return the marginal distribution over the linear (translational) part.

The marginal is computed by numerically integrating out the rotational component.

Returns

dist : CustomLinearDistribution Marginal distribution over R^2.

fit(samples, weights=None) staticmethod

Estimate SE2BinghamDistribution parameters from samples.

Parameters

samples : array_like, shape (N, 4) or (N, 3) Samples in dual quaternion (N x 4) or angle-pos (N x 3) form. weights : array_like, shape (N,), optional Non-negative weights (need not sum to 1). Defaults to uniform.

Returns

dist : SE2BinghamDistribution Fitted distribution.

SE2PWNDistribution

Bases: PartiallyWrappedNormalDistribution, AbstractSE2Distribution

Partially wrapped normal distribution for SE(2).

The first component is the rotation angle (periodic), the second and third components are the 2-D translation (linear).

References

Kurz, G., Gilitschenski, I., & Hanebeck, U. D. (2014). The Partially Wrapped Normal Distribution for SE(2) Estimation. Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration.

__init__(mu, C)

mean4D()

Return the 4-D moment E[cos(x1), sin(x1), x2, x3].

Returns

array of shape (4,)

covariance4D()

Return the analytical 4-D covariance of [cos(x1), sin(x1), x2, x3].

Returns

array of shape (4, 4)

covariance4D_numerical(n_samples=10000)

Estimate the 4-D covariance of [cos(x1), sin(x1), x2, x3] from samples.

Parameters

n_samples : int Number of samples to draw for the estimate.

Returns

array of shape (4, 4)

from_samples(samples) staticmethod

Fit an SE2PWNDistribution from samples via moment matching.

Parameters

samples : array of shape (n, 3) Samples on [0, 2*pi) x R^2.

Returns

SE2PWNDistribution

StateSpaceSubdivisionDistribution

Represents a joint distribution over a Cartesian product of a grid-based (periodic/bounded) space and a linear space, where the linear part is represented as a collection of distributions conditioned on each grid point of the periodic/bounded part.

The periodic part is stored as an AbstractGridDistribution, which holds grid_values (unnormalized weights) at each grid point. The linear part is stored as a list of distributions, one per grid point.

gd = copy.deepcopy(gd) instance-attribute

linear_distributions = list(copy.deepcopy(linear_distributions)) instance-attribute

bound_dim property writable

Dimension of the periodic/bounded space (ambient dimension of grid points).

lin_dim property writable

Dimension of the linear space.

__init__(gd, linear_distributions)

Parameters

gd : AbstractGridDistribution Grid-based distribution for the periodic/bounded part. Its grid_values represent (unnormalized) marginal weights over the grid points. linear_distributions : list One distribution per grid point representing the conditional distribution of the linear state given that grid point.

hybrid_mean()

Returns the hybrid mean, i.e. the concatenation of the mean direction of the periodic part and the mean of the linear marginal.

marginalize_linear() abstractmethod

Marginalise out the linear dimensions, returning a distribution over the periodic/bounded part only.

marginalize_periodic() abstractmethod

Marginalise out the periodic/bounded dimensions, returning a distribution over the linear part only.

StateSpaceSubdivisionGaussianDistribution

Bases: StateSpaceSubdivisionDistribution

Joint distribution over a Cartesian product of a grid-based (periodic/bounded) space and a linear space where every conditional linear distribution is a Gaussian.

The periodic part is a grid distribution (e.g. HypertoroidalGridDistribution or HyperhemisphericalGridDistribution). The linear part is a list of GaussianDistribution objects, one per grid point.

__init__(gd, gaussians)

Parameters

gd : AbstractGridDistribution Grid-based distribution for the periodic/bounded part. gaussians : list of GaussianDistribution One Gaussian per grid point of gd.

marginalize_linear()

Return the grid distribution (marginalised over the linear part).

marginalize_periodic()

Marginalise over the periodic/bounded dimensions.

Returns a GaussianMixture whose components are the conditional Gaussians and whose weights are the (normalised) grid values.

linear_mean()

Compute the mean of the marginal linear distribution by treating the state as a Gaussian mixture.

Returns

mu : array, shape (lin_dim,)

linear_covariance()

Compute the covariance of the marginal linear distribution by treating the state as a Gaussian mixture.

Returns

C : array, shape (lin_dim, lin_dim)

multiply(other)

Multiply two StateSpaceSubdivisionGaussianDistributions.

Both operands must be defined on the same grid. For each grid point the conditional Gaussians are multiplied (Bayesian update). The grid weights are updated by the likelihood factors that arise from the overlap of the two conditional Gaussians.

Parameters

other : StateSpaceSubdivisionGaussianDistribution

Returns

StateSpaceSubdivisionGaussianDistribution

mode()

Compute the (approximate) joint mode.

The mode is found by maximising the product of the conditional Gaussian peak value and the grid weight at each grid point. Only the discrete grid is searched (no interpolation).

Returns

m : array, shape (bound_dim + lin_dim,) Concatenation of the periodic mode (grid point) and the linear mode (mean of the conditional Gaussian at that grid point).

Warns

UserWarning If the density appears multimodal (i.e. another grid point has a joint value within a factor of 1.001 of the maximum).

convolve(_other)

AbstractCircularDistribution

Bases: AbstractHypertoroidalDistribution

__init__()

cdf_numerical(xs, starting_point=0.0)

Calculates the cumulative distribution function.

Args: xs (): The 1D array to calculate the CDF on. starting_point (float, optional): Defaults to 0.

Returns: : The computed CDF as a numpy array.

kld_numerical(other)

Calculates the Kullback-Leibler divergence numerically.

Args: other (AbstractCircularDistribution): Distribution to compare against.

Returns: : The Kullback-Leibler divergence D_KL(self || other).

to_vm()

Convert to von Mises by trigonometric moment matching.

Returns: vm (VMDistribution): Distribution with the same first trigonometric moment.

to_wn()

Convert to wrapped normal by trigonometric moment matching.

Returns: wn (WrappedNormalDistribution): Distribution with the same first trigonometric moment.

plot_circle(*args, **kwargs) staticmethod

CircularDiracDistribution

Bases: HypertoroidalDiracDistribution, AbstractCircularDistribution

__init__(d, w=None)

Initializes a CircularDiracDistribution instance.

Args: d (): The Dirac locations. w (Optional[]): The weights for each Dirac location.

plot_interpolated(_)

Raises an exception since interpolation is not available for WDDistribution.

CircularFourierDistribution

Bases: AbstractCircularDistribution

Circular distribution represented by a Fourier series.

References

Pfaff, F., Kurz, G., & Hanebeck, U. D. (2015). Multimodal Circular Filtering Using Fourier Series. Proceedings of the 18th International Conference on Information Fusion.

Pfaff, F., Kurz, G., & Hanebeck, U. D. (2016). Nonlinear Prediction for Circular Filtering Using Fourier Series. Proceedings of the 19th International Conference on Information Fusion.

c = c instance-attribute

a = None instance-attribute

b = None instance-attribute

n = 2 * c.shape[0] - 1 instance-attribute

multiplied_by_n = multiplied_by_n instance-attribute

transformation = transformation instance-attribute

__init__(transformation='sqrt', c=None, a=None, b=None, n=None, multiplied_by_n=True)

__sub__(other)

pdf(xs)

normalize()

integrate(integration_boundaries=None)

plot_grid()

plot(resolution=128, **kwargs)

get_a_b()

get_c()

to_real_fd()

get_full_c()

from_distribution(distribution, n, transformation='sqrt', store_values_multiplied_by_n=True) staticmethod

from_function_values(fvals, transformation='sqrt', store_values_multiplied_by_n=True) staticmethod

CircularMixture

Bases: AbstractCircularDistribution, HypertoroidalMixture

dists = dists instance-attribute

w = w / sum(w) instance-attribute

__init__(dists, w)

Creates a new circular mixture.

Args: dists: The list of distributions. w: The weights of the distributions. They must have the same shape as 'dists' and the sum of all weights must be 1.

CircularUniformDistribution

Bases: HypertoroidalUniformDistribution, AbstractCircularDistribution

Circular uniform distribution

__init__()

get_manifold_size()

shift(_)

cdf(xa, starting_point=0)

Evaluate cumulative distribution function

Parameters

xa : (1, n) points where the cdf should be evaluated starting_point : scalar point where the cdf is zero (starting point can be [0, 2pi) on the circle, default 0

Returns

val : (1, n) cdf evaluated at columns of xa

CustomCircularDistribution

Bases: AbstractCustomDistribution, AbstractCircularDistribution

shift_by = shift_by instance-attribute

__init__(f_, scale_by=1, shift_by=0)

Initializes a new instance of the CustomCircularDistribution class.

Args: f_ (callable): The function to be used for the distribution. scale_by (float, optional): The scale factor for the distribution. Defaults to 1. shift_by (float, optional): The shift for the distribution. Defaults to 0.

Note: It is the user's responsibility to ensure that f_ is a valid circular density, i.e., 2pi-periodic, nonnegative and normalized.

pdf(xs)

Computes the probability density function at xs.

Args: xs (): The values at which to evaluate the pdf.

Returns: : The value of the pdf at xs.

integrate(integration_boundaries=None)

Computes the integral of the pdf over the given boundaries.

Args: integration_boundaries (, optional): The boundaries of the integral. Defaults to [0, 2 * pi].

Returns: float: The value of the integral.

GvMDistribution

Bases: AbstractCircularDistribution

Generalized von Mises distribution of arbitrary order.

See Riccardo Gatto, Sreenivasa Rao Jammalamadaka, "The Generalized von Mises Distribution", Statistical Methodology, 2007.

Parameters

mu : array_like, shape (k,) Location parameters. kappa : array_like, shape (k,) Concentration parameters, all must be positive.

mu = mu instance-attribute

kappa = kappa instance-attribute

norm_const property

__init__(mu, kappa)

pdf_unnormalized(xs)

Evaluate the unnormalized pdf at each point in xs.

Parameters

xs : array_like, shape (n,) Points where the pdf is evaluated.

Returns

p : array, shape (n,) Unnormalized pdf values.

pdf(xs)

Evaluate the pdf at each point in xs.

Parameters

xs : array_like, shape (n,) Points where the pdf is evaluated.

Returns

p : array, shape (n,) Pdf values.

PiecewiseConstantDistribution

Bases: AbstractCircularDistribution

Piecewise constant (i.e. discrete) circular distribution, similar to a histogram.

The circle [0, 2*pi) is divided into n equal intervals, each with a constant probability density weight.

Gerhard Kurz, Florian Pfaff, Uwe D. Hanebeck, Discrete Recursive Bayesian Filtering on Intervals and the Unit Circle Proceedings of the 2016 IEEE International Conference on Multisensor Fusion and Integration for Intelligent Systems (MFI 2016), Baden-Baden, Germany, September 2016.

w = w / (mean(w) * 2.0 * pi) instance-attribute

__init__(w)

Initialize with a weight vector that is automatically normalized.

Parameters

w : array_like, shape (n,) Weight for each interval (will be normalized to form a valid pdf).

pdf(xs)

Evaluate the pdf at each point in xs.

Parameters

xs : array_like, shape (n,) Points at which to evaluate the pdf.

Returns

p : ndarray, shape (n,) Pdf values at each point.

trigonometric_moment(n)

Calculate the n-th trigonometric moment analytically.

Parameters

n : int Moment order.

Returns

m : complex n-th trigonometric moment.

entropy()

Calculate the entropy analytically.

Returns

e : float Entropy of the distribution.

sample(n)

Draw n random samples from the distribution.

Parameters

n : int Number of samples to draw.

Returns

samples : ndarray, shape (n,) Samples in [0, 2*pi).

left_border(m, n) staticmethod

Left border of the m-th interval (1-indexed) for n total intervals.

Parameters

m : int Interval index (1-indexed). n : int Total number of intervals.

Returns

float Left border of the m-th interval.

right_border(m, n) staticmethod

Right border of the m-th interval (1-indexed) for n total intervals.

Parameters

m : int Interval index (1-indexed). n : int Total number of intervals.

Returns

float Right border of the m-th interval.

interval_center(m, n) staticmethod

Center of the m-th interval (1-indexed) for n total intervals.

Parameters

m : int Interval index (1-indexed). n : int Total number of intervals.

Returns

float Center of the m-th interval.

calculate_parameters_numerically(pdf_func, n) staticmethod

Calculate weights by numerically integrating a given pdf over each interval.

Parameters

pdf_func : callable Pdf of a circular density; accepts a 1-D array and returns a 1-D array. n : int Number of discretization intervals.

Returns

w : ndarray, shape (n,) Weights of the corresponding PiecewiseConstantDistribution.

AbstractSineSkewedDistribution

Bases: AbstractCircularDistribution

Abstract superclass for sine-skewed distributions.

mu = mu instance-attribute

lambda_ = lambda_ instance-attribute

__init__(mu, lambda_)

Initialize the sine-skewed distribution with a central location parameter mu and a skewness parameter lambda_.

base_pdf(xs) abstractmethod

Compute the base probability density function (PDF) for the wrapped distribution without skewness. This method must be implemented by subclasses.

pdf(xs)

Compute the skewed probability density function (PDF) for the distribution.

GeneralizedKSineSkewedVonMisesDistribution

Bases: AbstractCircularDistribution

See Bekker, A., Nakhaei Rad, N., Arashi, M., Ley, C. (2020). Generalized Skew-Symmetric Circular and Toroidal Distributions, Florence Nightingale Directional Statistics volume, Springer. Parameters: - mu (float): Mean direction of the distribution. - kappa (float): Concentration parameter (non-negative). - lambda_ (float): Skewness parameter, must be between -1 and 1 inclusive. - k (int): Sine multiplier, currently supports only k=1. - m (int): Power of the sine term, must be a positive integer.

mu = mod(mu, 2 * pi) instance-attribute

kappa = kappa instance-attribute

lambda_ = lambda_ instance-attribute

k = k instance-attribute

m = m instance-attribute

__init__(mu, kappa, lambda_, k, m)

validate_parameters()

pdf(xs)

shift(shift_by)

GeneralizedKSineSkewedWrappedCauchyDistribution

Bases: AbstractCircularDistribution

Generalized K Sine-Skewed Wrapped Cauchy (GSSC) distribution. See Bekker, A., Nakhaei Rad, N., Arashi, M., Ley, C. (2020). Generalized Skew-Symmetric Circular and Toroidal Distributions, Florence Nightingale Directional Statistics volume, Springer. Parameters: - mu (float): Mean direction of the distribution. - gamma (float): Concentration parameter of the wrapped Cauchy distribution (positive). - lambda_ (float): Skewness parameter, must be between -1 and 1 inclusive. - k (int): Sine multiplier, currently supports only k=1. - m (int): Power of the sine term, must be a positive integer.

mu = mod(mu, 2 * pi) instance-attribute

gamma = gamma instance-attribute

lambda_ = lambda_ instance-attribute

k = k instance-attribute

m = m instance-attribute

__init__(mu, gamma, lambda_, k, m)

validate_parameters()

pdf(xs)

shift(shift_by)

GSSVMDistribution

Bases: GeneralizedKSineSkewedVonMisesDistribution

Generalized Skew-Symmetric Von Mises (GSSVM) distribution.

Special case of GeneralizedKSineSkewedVonMisesDistribution with k=1 fixed. Corresponds to GSSVMDistribution in libDirectional.

Parameters: - mu (float): Mean direction of the distribution. - kappa (float): Concentration parameter (non-negative). - lambda_ (float): Skewness parameter, must be between -1 and 1 inclusive. - n (int): Order/power of the sine skewing term, must be a positive integer.

n property

__init__(mu, kappa, lambda_, n)

shift(shift_by)

SineSkewedVonMisesDistribution

Bases: GeneralizedKSineSkewedVonMisesDistribution

__init__(mu, kappa, lambda_)

SineSkewedWrappedCauchyDistribution

Bases: AbstractSineSkewedDistribution

wrapped_cauchy = WrappedCauchyDistribution(mu, gamma) instance-attribute

gamma property

__init__(mu, gamma, lambda_)

base_pdf(xs)

SineSkewedWrappedNormalDistribution

Bases: AbstractSineSkewedDistribution

wrapped_normal = WrappedNormalDistribution(mu, sigma) instance-attribute

sigma property

__init__(mu, sigma, lambda_)

base_pdf(xs)

VonMisesDistribution

Bases: AbstractCircularDistribution

Von Mises distribution on the circle.

References

Jammalamadaka, S. R., & SenGupta, A. (2001). Topics in Circular Statistics. World Scientific.

mu = mu instance-attribute

kappa = kappa instance-attribute

norm_const property

__init__(mu, kappa, norm_const=None)

get_params()

pdf(xs)

sample(n)

Draw samples from the von Mises distribution.

set_mean(mu)

Set the mean direction of the distribution.

Parameters: mu : scalar New mean direction to set.

besselratio(nu, kappa) staticmethod

cdf(xs, starting_point=0)

Evaluate cumulative distribution function

Parameters: xs : (n) points where the cdf should be evaluated starting_point : scalar, optional, default: 0 point where the cdf is zero (starting point can be [0, 2pi) on the circle, default is 0)

Returns: val : (n) cdf evaluated at columns of xs

besselratio_inverse(v, x) staticmethod

multiply(vm2)

convolve(vm2)

entropy()

trigonometric_moment(n)

trigonometric_moment_analytic(n)

from_moment(m) staticmethod

Obtain a VM distribution from a given first trigonometric moment.

Parameters: m (scalar): First trigonometric moment (complex number).

Returns: vm (VMDistribution): VM distribution obtained by moment matching.

__str__()

WrappedCauchyDistribution

Bases: AbstractCircularDistribution

Wrapped Cauchy distribution on the circle.

References

Jammalamadaka, S. R., & SenGupta, A. (2001). Topics in Circular Statistics. World Scientific.

mu = mod(mu, 2 * pi) instance-attribute

gamma = gamma instance-attribute

__init__(mu, gamma)

pdf(xs)

cdf(xs)

trigonometric_moment(n)

WrappedExponentialDistribution

Bases: AbstractCircularDistribution

Wrapped exponential distribution on the circle.

See Sreenivasa Rao Jammalamadaka and Tomasz J. Kozubowski, "New Families of Wrapped Distributions for Modeling Skew Circular Data", Communications in Statistics - Theory and Methods, Vol. 33, No. 9, pp. 2059-2074, 2004.

lambda_ = lambda_ instance-attribute

__init__(lambda_)

pdf(xs)

trigonometric_moment(n)

sample(n)

entropy()

WrappedLaplaceDistribution

Bases: AbstractCircularDistribution

Wrapped Laplace distribution on the circle.

References

Jammalamadaka, S. R., & Kozubowski, T. J. (2004). New families of wrapped distributions for modeling skew circular data. Communications in Statistics - Theory and Methods, 33(9), 2059-2074.

lambda_ = lambda_ instance-attribute

kappa = kappa_ instance-attribute

__init__(lambda_, kappa_)

trigonometric_moment(n)

pdf(xs)

WrappedNormalDistribution

Bases: AbstractCircularDistribution, HypertoroidalWrappedNormalDistribution

Wrapped normal distribution on the circle.

References

Jammalamadaka, S. R., & SenGupta, A. (2001). Topics in Circular Statistics. World Scientific.

MAX_SIGMA_BEFORE_UNIFORM = 10 class-attribute instance-attribute

sigma property

__init__(mu, sigma)

Initialize a wrapped normal distribution with mean mu and standard deviation sigma.

pdf(xs, m=3)

cdf(xs, starting_point=0.0, n_wraps=10)

trigonometric_moment(n)

multiply(other)

multiply_vm(other)

sample(n)

shift(shift_by)

to_vm()

from_moment(m) staticmethod

sigma_to_kappa(sigma) staticmethod

AbstractConditionalDistribution

Bases: ABC

Abstract base class for conditional grid distributions on manifolds.

Subclasses represent distributions of the form f(a | b) where both a and b live on the same manifold. The joint state is stored as a square matrix grid_values where grid_values[i, j] = f(grid[i] | grid[j]).

grid = grid instance-attribute

grid_values = grid_values instance-attribute

enforce_pdf_nonnegative = enforce_pdf_nonnegative instance-attribute

dim = 2 * d instance-attribute

__init__(grid, grid_values, enforce_pdf_nonnegative=True)

Common initialisation for conditional grid distributions.

Parameters

grid : array of shape (n_points, d) Grid points on the individual manifold. grid_values : array of shape (n_points, n_points) Conditional pdf values; grid_values[i, j] = f(grid[i] | grid[j]). enforce_pdf_nonnegative : bool Whether to require non-negative grid_values.

normalize()

No-op – returns self for compatibility.

multiply(other)

Element-wise multiply two conditional grid distributions.

The resulting distribution is not normalized.

Parameters

other : AbstractConditionalDistribution Must be defined on the same grid.

Returns

AbstractConditionalDistribution Same concrete type as self.

S2CondS2GridDistribution

Bases: SdCondSdGridDistribution

Conditional distribution on S2 x S2 represented by a grid of values.

This is a specialisation of :class:SdCondSdGridDistribution for the two-sphere (S²). The grid is restricted to embedding dimension 3 (grid.shape[1] == 3), and factory / slicing methods return :class:~pyrecest.distributions.hypersphere_subset.spherical_grid_distribution.SphericalGridDistribution instances instead of the generic :class:~pyrecest.distributions.hypersphere_subset.hyperspherical_grid_distribution.HypersphericalGridDistribution.

__init__(grid, grid_values, enforce_pdf_nonnegative=True)

Parameters

grid : array of shape (n_points, 3) Grid points on S². grid_values : array of shape (n_points, n_points) Conditional pdf values: grid_values[i, j] = f(grid[i] | grid[j]). enforce_pdf_nonnegative : bool Whether non-negativity of grid_values is required.

marginalize_out(first_or_second)

Marginalize out one of the two spheres.

Returns a :class:SphericalGridDistribution (S²-specific).

Parameters

first_or_second : int (1 or 2)

fix_dim(first_or_second, point)

Return the conditional slice for a fixed grid point.

Returns a :class:SphericalGridDistribution (S²-specific).

Parameters

first_or_second : int (1 or 2) point : array of shape (3,)

from_function(fun, no_of_grid_points, fun_does_cartesian_product=False, grid_type='leopardi', dim=6) staticmethod

Construct an :class:S2CondS2GridDistribution from a callable.

Parameters

fun : callable Conditional pdf f(a, b) – see :meth:SdCondSdGridDistribution.from_function for the fun_does_cartesian_product convention. no_of_grid_points : int Number of grid points for each sphere. fun_does_cartesian_product : bool If True, fun is called with the full grids of shape (n_points, 3) and must return (n_points, n_points). If False (default), fun receives paired rows and must return a 1-D array. grid_type : str Grid type passed to the sampler. Defaults to 'leopardi'.

Returns

S2CondS2GridDistribution

SdCondSdGridDistribution

Bases: AbstractConditionalDistribution

Conditional distribution on Sd x Sd represented by a grid of values.

For a conditional distribution f(a|b), grid_values[i, j] stores the value f(grid[i] | grid[j]).

Convention

  • grid has shape (n_points, d) where d is the embedding dimension of the individual sphere (e.g. d=3 for S2).
  • grid_values has shape (n_points, n_points).
  • dim = 2 * d is the embedding dimension of the Cartesian product space (convention inherited from libDirectional).

__init__(grid, grid_values, enforce_pdf_nonnegative=True)

Parameters

grid : array of shape (n_points, d) Grid points on the sphere. All coordinate values must lie in [-1, 1] (unit sphere). grid_values : array of shape (n_points, n_points) Conditional pdf values: grid_values[i, j] = f(grid[i] | grid[j]). Must be non-negative. enforce_pdf_nonnegative : bool Whether non-negativity of grid_values is required.

marginalize_out(first_or_second)

Marginalize out one of the two spheres.

Parameters

first_or_second : int (1 or 2) 1 marginalizes out the first dimension (sums over rows); 2 marginalizes out the second dimension (sums over columns).

Returns

HypersphericalGridDistribution

fix_dim(first_or_second, point)

Return the conditional slice for a fixed grid point.

The supplied point must be an existing grid point.

Parameters

first_or_second : int (1 or 2) 1 fixes the first argument at point and returns values over the second sphere; 2 fixes the second argument and returns values over the first sphere. point : array of shape (d,) Grid point at which to evaluate.

Returns

HypersphericalGridDistribution

from_function(fun, no_of_grid_points, fun_does_cartesian_product=False, grid_type='leopardi', dim=6) staticmethod

Construct a :class:SdCondSdGridDistribution from a callable.

Parameters

fun : callable Conditional pdf function f(a, b).

*   When ``fun_does_cartesian_product=False`` (default): ``fun``
    is called once with two arrays of shape ``(n_pairs, d)``
    containing all ``n_points²`` pairs, and must return a 1-D
    array of length ``n_points²``.
*   When ``fun_does_cartesian_product=True``: ``fun`` is called
    with both full grids of shape ``(n_points, d)`` and must
    return an array of shape ``(n_points, n_points)``.

no_of_grid_points : int Number of grid points for each sphere. fun_does_cartesian_product : bool See fun description above. grid_type : str Grid type passed to :func:~pyrecest.sampling.hyperspherical_sampler.get_grid_hypersphere. Defaults to 'leopardi'. dim : int Embedding dimension of the Cartesian product space (2 * embedding_dim_of_individual_sphere). Defaults to 6 (S2 × S2).

Returns

SdCondSdGridDistribution

SdHalfCondSdHalfGridDistribution

Bases: AbstractConditionalDistribution

Conditional grid distribution on hemisphere × hemisphere.

Stores a conditional distribution f(a | b) where both a and b live on the upper hemisphere (last coordinate >= 0).

Convention

  • grid has shape (n_points, d) where d is the embedding dimension of the individual hemisphere (e.g. d=3 for S2-half).
  • grid_values has shape (n_points, n_points).
  • grid_values[i, j] = f(grid[i] | grid[j]).
  • dim = 2 * d follows the product-space embedding-dimension convention from libDirectional.

__init__(grid, grid_values, enforce_pdf_nonnegative=True)

Parameters

grid : array of shape (n_points, d) Grid points on the upper hemisphere. All coordinate values must lie in [-1, 1] and the last coordinate must be >= 0. grid_values : array of shape (n_points, n_points) Conditional pdf values. enforce_pdf_nonnegative : bool Whether non-negativity of grid_values is required.

get_grid()

Return the grid array.

marginalize_out(first_or_second)

Marginalize out one of the two hemispheres.

Parameters

first_or_second : int (1 or 2)

Returns

HyperhemisphericalGridDistribution

fix_dim(first_or_second, point)

Return the conditional slice for a fixed grid point.

Returns

HyperhemisphericalGridDistribution

from_function(fun, no_of_grid_points, fun_does_cartesian_product=False, grid_type='leopardi_symm', dim=4) staticmethod

Construct a :class:SdHalfCondSdHalfGridDistribution from a callable.

Parameters

fun : callable Conditional pdf function f(a, b). When fun_does_cartesian_product=False: called with pairs of shape (n_pairs, d) and must return array of length n_pairs. When fun_does_cartesian_product=True: called with both grids of shape (n_points, d) and must return (n_points, n_points). no_of_grid_points : int Number of grid points for each hemisphere. fun_does_cartesian_product : bool See fun description above. grid_type : str Grid type for hemisphere. Defaults to 'leopardi_symm'. dim : int Embedding dimension of the Cartesian product space (2 * embedding_dim_of_individual_hemisphere). Default 4 for circles; use 6 for S2-half.

Returns

SdHalfCondSdHalfGridDistribution

TdCondTdGridDistribution

Bases: AbstractConditionalDistribution

Conditional distribution on Td x Td represented by a grid of values.

For a conditional distribution f(a|b), grid_values[i, j] stores the value f(grid[i] | grid[j]).

Convention

  • grid has shape (n_points, d) where d is the number of dimensions of the individual torus (e.g. d=1 for T1).
  • grid_values has shape (n_points, n_points).
  • dim = 2 * d is the dimension of the Cartesian product space (convention inherited from libDirectional).

__init__(grid, grid_values, enforce_pdf_nonnegative=True)

Parameters

grid : array of shape (n_points, d) Grid points on the torus. grid_values : array of shape (n_points, n_points) Conditional pdf values: grid_values[i, j] = f(grid[i] | grid[j]). Must be non-negative when enforce_pdf_nonnegative=True. enforce_pdf_nonnegative : bool Whether non-negativity of grid_values is required.

marginalize_out(first_or_second)

Marginalize out one of the two tori.

Parameters

first_or_second : int (1 or 2) 1 marginalizes out the first dimension (sums over rows); 2 marginalizes out the second dimension (sums over columns).

Returns

HypertoroidalGridDistribution

fix_dim(first_or_second, point)

Return the conditional slice for a fixed grid point.

The supplied point must be an existing grid point.

Parameters

first_or_second : int (1 or 2) 1 fixes the first argument at point and returns values over the second torus; 2 fixes the second argument and returns values over the first torus. point : array of shape (d,) Grid point at which to evaluate.

Returns

HypertoroidalGridDistribution

from_function(fun, no_of_grid_points, fun_does_cartesian_product=False, grid_type='CartesianProd', dim=2) staticmethod

Construct a :class:TdCondTdGridDistribution from a callable.

Parameters

fun : callable Conditional pdf function f(a, b).

*   When ``fun_does_cartesian_product=False`` (default): ``fun``
    is called once with two arrays of shape ``(n_pairs, d)``
    containing all ``n_points²`` pairs, and must return a 1-D
    array of length ``n_points²``.
*   When ``fun_does_cartesian_product=True``: ``fun`` is called
    with both full grids of shape ``(n_points, d)`` and must
    return an array of shape ``(n_points, n_points)``.

no_of_grid_points : int Number of grid points for each torus. fun_does_cartesian_product : bool See fun description above. grid_type : str Grid type passed to :meth:~pyrecest.distributions.hypertorus.hypertoroidal_grid_distribution.HypertoroidalGridDistribution.generate_cartesian_product_grid. Defaults to 'CartesianProd'. dim : int Dimension of the Cartesian product space (2 * dim_of_individual_torus). Defaults to 2 (T1 × T1).

Returns

TdCondTdGridDistribution

ConversionError

Bases: ValueError

Raised when a distribution representation conversion is unavailable.

ConversionResult dataclass

Distribution conversion result and metadata.

Attributes

distribution Converted distribution instance. source_type Concrete source distribution type. target_type Requested target distribution type. method Human-readable conversion method used by the gateway. exact Whether the conversion is mathematically exact as a distribution representation. Moment matching, sampling, and grid approximation should be reported as approximate. parameters Conversion parameters that were passed to the conversion routine.

distribution instance-attribute

source_type instance-attribute

target_type instance-attribute

method instance-attribute

exact instance-attribute

parameters = field(default_factory=dict) class-attribute instance-attribute

__init__(distribution, source_type, target_type, method, exact, parameters=dict())

CustomHyperrectangularDistribution

DiskUniformDistribution

Bases: EllipsoidalBallUniformDistribution, AbstractDiskDistribution

A class used to represent uniform distribution on a disk. Inherits from EllipsoidalBallUniformDistribution and AbstractDiskDistribution.

__init__()

Initialize DiskUniformDistribution.

The center of the disk is at [0, 0] and the shape matrix of the ellipsoid is an identity covariance matrix.

EllipsoidalBallUniformDistribution

Bases: AbstractEllipsoidalBallDistribution, AbstractUniformDistribution

A class representing a uniform distribution on an ellipsoidal ball.

input_dim property

Returns the size of the input vector for evaluation of the pdf.

__init__(center, shape_matrix)

Initialize EllipsoidalBallUniformDistribution.

Parameters:

Name Type Description Default
center

Center of the ellipsoidal ball.

required
shape_matrix

Shape matrix defining the ellipsoidal ball.

required

mean()

pdf(xs)

Compute the probability density function at given points.

Parameters:

Name Type Description Default
xs

Points at which to compute the PDF.

required

Returns:

Type Description

PDF values at given points.

sample(n)

Generate samples from the distribution.

Parameters:

Name Type Description Default
n Union[int, int32, int64]

Number of samples to generate.

required

Returns:

Type Description

Generated samples.

AbstractComplexHypersphericalDistribution

Bases: AbstractManifoldSpecificDistribution

Abstract base class for distributions on the complex unit hypersphere in C^d.

The complex unit hypersphere in C^d is the set {z in C^d : ||z|| = 1} which is isomorphic to the real sphere S^{2d-1} in R^{2d}.

The complex dimension d is stored as complex_dim. The underlying manifold dimension (as a real manifold) is 2*d - 1.

complex_dim property

Complex dimension d of the ambient space C^d.

input_dim property

Number of complex coordinates of a point on the sphere (= complex_dim).

__init__(complex_dim)

Parameters

complex_dim : int Complex dimension d of the ambient space C^d (d >= 1).

get_manifold_size()

Surface area of the real sphere S^{2d-1} = 2*pi^d / (d-1)!

pdf(xs) abstractmethod

Probability density at the given point(s) on the complex unit sphere.

mean()

AbstractHemisphericalDistribution

Bases: AbstractSphereSubsetDistribution, AbstractHyperhemisphericalDistribution

This abstract class represents a distribution over the hemisphere. It inherits from both AbstractSphereSubsetDistribution and AbstractHyperhemisphericalDistribution. The class is meant to be subclassed and should not be instantiated directly.

__init__()

Initializes a new instance of the AbstractHemisphericalDistribution class.

AbstractHyperhemisphericalDistribution

Bases: AbstractHypersphereSubsetDistribution

mean()

Convenient access to axis to have a consistent interface throughout manifolds.

Returns:

Type Description

The mean of the distribution.

mean_axis()

sample_metropolis_hastings(n, burn_in=10, skipping=5, proposal=None, start_point=None)

mean_direction_numerical(integration_boundaries=None)

get_full_integration_boundaries(dim) staticmethod

integrate(integration_boundaries=None)

integrate_numerically(integration_boundaries=None)

integrate_fun_over_domain(f_hypersph_coords, dim) staticmethod

mode_numerical()

plot_hemisphere(resolution=150) staticmethod

get_manifold_size()

AbstractHypersphereSubsetDiracDistribution

Bases: AbstractDiracDistribution, AbstractHypersphereSubsetDistribution

__init__(d, w=None)

from_distribution(distribution, n_particles=None) classmethod

Approximate a hypersphere-subset distribution as weighted Diracs.

Grid distributions are converted deterministically by reusing their grid points as Dirac locations and their grid values as weights. Non-grid distributions fall back to the generic sampling-based Dirac conversion and therefore require n_particles.

moment()

entropy()

integrate(left=None, right=None)

mean_axis()

Returns the principal axis of the Dirac mixture on the hypersphere. Because ±v represent the same axis, the sign of the returned vector is arbitrary.

AbstractHypersphereSubsetDistribution

Bases: AbstractBoundedDomainDistribution

input_dim property

mean_direction()

get_full_integration_boundaries(dim) abstractmethod staticmethod

mean_direction_numerical(integration_boundaries=None)

gen_pdf_hyperspherical_coords()

Generate the PDF in hyperspherical coordinates.

Returns:

Type Description

A function that computes the PDF value at given angles.

gen_fun_hyperspherical_coords(f, dim) staticmethod

moment()

moment_numerical()

mean_axis()

mean_axis_numerical()

integrate(integration_boundaries)

integrate_fun_over_domain(f_hypersph_coords, dim) abstractmethod staticmethod

integrate_fun_over_domain_part(f_hypersph_coords, integration_boundaries) staticmethod

integrate_numerically(integration_boundaries=None)

integration_boundaries have to be given in (hyper)spherical coordinates

mode()

mode_numerical()

entropy_numerical()

hellinger_distance_numerical(other, integration_boundaries=None)

total_variation_distance_numerical(other, integration_boundaries=None)

hypersph_to_cart(hypersph_coords, mode='colatitude') staticmethod

cart_to_hypersph(cart_coords, mode='colatitude') staticmethod

compute_unit_hypersphere_surface(dim) staticmethod

AbstractHypersphereSubsetGridDistribution

Bases: AbstractGridDistribution, AbstractHypersphereSubsetDistribution

__init__(grid, grid_values, enforce_pdf_nonnegative=True)

mean_direction()

moment()

multiply(other)

from_distribution(distribution, no_of_grid_points, grid_type=None, enforce_pdf_nonnegative=True) classmethod

AbstractHypersphereSubsetUniformDistribution

Bases: AbstractHypersphereSubsetDistribution, AbstractUniformDistribution

This is an abstract class for a uniform distribution over a subset of a hypersphere.

pdf(xs)

Calculates the probability density function over the subset of the hypersphere.

Args: xs (): Input data points.

Returns: : Probability density at the given data points.

AbstractHypersphericalDistribution

Bases: AbstractHypersphereSubsetDistribution

This is an abstract class for a distribution over a hypersphere.

mean()

Convenient access to mean_direction to have a consistent interface throughout manifolds.

Returns:

Type Description

The mean of the distribution.

sample_metropolis_hastings(n, burn_in=10, skipping=5, proposal=None, start_point=None)

Sample from the distribution using Metropolis-Hastings algorithm.

Args: n (int): Number of samples. burn_in (int, optional): Number of samples to discard at the start. Defaults to 10. skipping (int, optional): Number of samples to skip between each kept sample. Defaults to 5. proposal (function, optional): Proposal distribution for the Metropolis-Hastings algorithm. Defaults to None. start_point (, optional): Starting point for the Metropolis-Hastings algorithm. Defaults to None.

Returns: : Sampled points.

plot(faces=100, grid_faces=20)

moment()

get_full_integration_boundaries(dim) staticmethod

integrate(integration_boundaries=None)

integrate_numerically(integration_boundaries=None)

entropy()

mode_numerical()

hellinger_distance(other)

total_variation_distance(other)

create_sphere(faces) staticmethod

integrate_fun_over_domain(f_hypersph_coords, dim) staticmethod

get_manifold_size()

get_ln_manifold_size()

AbstractSphereSubsetDistribution

Bases: AbstractHypersphereSubsetDistribution

This is an abstract class for a distribution over a sphere.

__init__()

Initialize the AbstractSphereSubsetDistribution instance.

sph_to_cart(angles1, angles2, mode='inclination') staticmethod

Convert spherical coordinates to Cartesian coordinates. For different convetions, see https://en.wikipedia.org/wiki/Spherical_coordinate_system Supported convetions: inclination and azimuth (θ_inc, φ_az,right) azimuth, and colatitude Refer to the respective functions for more information.

cart_to_sph(x, y, z, mode='inclination') staticmethod

Convert Cartesian coordinates to spherical coordinates.

Args: x (): X coordinates. y (): Y coordinates. z (): Z coordinates.

Returns: tuple: Spherical coordinates.

AbstractSphericalDistribution

Bases: AbstractSphereSubsetDistribution, AbstractHypersphericalDistribution

__init__()

plot_unit_sphere() staticmethod

AbstractSphericalHarmonicsDistribution

Bases: AbstractSphericalDistribution, AbstractOrthogonalBasisDistribution

__init__(coeff_mat, transformation='identity')

pdf(xs)

normalize_in_place(warn_unnorm=True)

integrate(integration_boundaries=None)

truncate(degree)

BinghamDistribution

Bases: AbstractHypersphericalDistribution

Bingham distribution on the hypersphere.

References

Bingham, C. (1974). An antipodally symmetric distribution on the sphere. The Annals of Statistics, 2(6), 1201-1225.

Z = Z instance-attribute

M = M instance-attribute

F property writable

dF property

__init__(Z, M)

calculate_F(Z) staticmethod

Uses analytical method. Supports 2-D and 4-D distributions.

pdf(xs)

mean_direction()

mean_axis()

Returns the principal axis of the Bingham distribution as a unit vector in R^{dim+1}. Because of antipodal symmetry, v and -v represent the same axis; this method returns one of them.

multiply(B2)

sample(n)

calculate_dF()

sample_kent(n)

moment()

Returns: S (numpy.ndarray): scatter/covariance matrix in R^d

mode()

Returns the mode of the Bingham distribution.

The mode is the eigenvector corresponding to Z=0 (the maximum), i.e., the last column of M.

Returns: mode (numpy.ndarray): mode as a unit vector in R^{dim+1}

sample_deterministic(_spread=0.5)

Returns deterministic sigma-point samples and weights.

Generates 2*(dim+1) sigma points as ±columns of M with weights derived from the normalized moments, so that the weighted scatter matrix equals the distribution's moment matrix.

Parameters: _spread (float): spread parameter reserved for future use (e.g., tuning the sigma-point placement); currently the samples are always ±M columns

Returns: samples (numpy.ndarray): shape (dim+1, 2(dim+1)), columns are samples weights (numpy.ndarray): shape (2(dim+1),), non-negative weights summing to 1

compose(B2)

Compose two Bingham distributions via complex or quaternion multiplication.

Computes the Bingham distribution approximating the scatter matrix of the product x*y, where x ~ self and y ~ B2 are independent.

Parameters: B2 (BinghamDistribution): second distribution

Returns: BinghamDistribution: composed distribution

fit_to_moment(S) staticmethod

Fit a Bingham distribution to a given scatter/moment matrix.

Finds Z and M such that the moment of B(Z, M) matches S.

Parameters: S (numpy.ndarray): symmetric positive semi-definite matrix with trace 1 (or will be normalized)

Returns: BinghamDistribution: fitted distribution

ComplexAngularCentralGaussianDistribution

Complex Angular Central Gaussian distribution on the complex unit hypersphere.

This distribution is defined on the complex unit sphere in C^d (equivalently S^{2d-1} in R^{2d}). It is parameterized by a Hermitian positive definite matrix C of shape (d, d).

Reference: Ported from ComplexAngularCentralGaussian.m in libDirectional: https://github.com/libDirectional/libDirectional/blob/master/lib/distributions/complexHypersphere/ComplexAngularCentralGaussian.m

C = C instance-attribute

dim = C.shape[0] instance-attribute

__init__(C)

Initialize the distribution.

Parameters

C : array-like of shape (d, d) Hermitian positive definite parameter matrix.

pdf(za)

Evaluate the pdf at each row of za.

Parameters

za : array-like of shape (n, d) or (d,) Points on the complex unit sphere. Each row is a complex unit vector.

Returns

p : array-like of shape (n,) or scalar PDF values at each row of za.

sample(n)

Sample n points from the distribution.

Parameters

n : int Number of samples.

Returns

Z : array-like of shape (n, d) Complex unit vectors sampled from the distribution.

fit(Z, n_iterations=100) staticmethod

Fit distribution to data Z using fixed-point iterations.

Parameters

Z : array-like of shape (n, d) Complex unit vectors (each row is a sample). n_iterations : int, optional Number of fixed-point iterations (default 100).

Returns

dist : ComplexAngularCentralGaussianDistribution

estimate_parameter_matrix(Z, n_iterations=100) staticmethod

Estimate the parameter matrix from data using fixed-point iterations.

Parameters

Z : array-like of shape (n, d) Complex unit vectors (each row is a sample). n_iterations : int, optional Number of iterations (default 100).

Returns

C : array-like of shape (d, d) Estimated Hermitian parameter matrix.

ComplexBinghamDistribution

Bases: AbstractComplexHypersphericalDistribution

Complex Bingham distribution on the complex unit hypersphere.

The distribution is defined on the complex unit sphere S^{2d-1} = {z in C^d : ||z|| = 1} with pdf

p(z) proportional to exp(z^H B z),

where B is a d x d Hermitian parameter matrix.

Attributes

B : array, shape (d, d), dtype complex128 Hermitian parameter matrix. log_norm_const : float Negative log normalization constant (i.e. -log C(B) where C(B) is the normalising constant), stored so that pdf(z) = exp(log_norm_const + Re(z^H B z)).

B = B instance-attribute

log_norm_const = ComplexBinghamDistribution.log_norm(B) instance-attribute

__init__(B)

Construct a ComplexBinghamDistribution.

Parameters

B : array_like, shape (d, d) Hermitian parameter matrix (B == B^H must hold).

pdf(xs)

Evaluate the pdf at one or more points on the complex unit sphere.

Parameters

xs : array_like, shape (d,) or (d, n) Each column (or the single vector) is a point on the complex unit sphere.

Returns

array, shape (n,) or float Pdf value(s).

sample(n)

Draw samples from the complex Bingham distribution.

Uses the rejection-sampling algorithm of Kent, Constable & Er (2004) "Simulation for the complex Bingham distribution", Statistics and Computing, 14, 53-57.

Parameters

n : int Number of samples.

Returns

array, shape (d, n), dtype complex128 Sampled unit vectors (each column has unit norm).

log_norm(B) staticmethod

Compute the negative log normalization constant -log C(B).

The formula used is (Kent 1994, eq. 2.3) after eigenvalue shift:

C(lambda) = 2*pi^d * sum_j exp(lambda_j) / prod_{k!=j}(lambda_j - lambda_k)

For nearly-equal eigenvalues a small perturbation is applied so that the Vandermonde denominators remain well-conditioned, matching the approach in the original MATLAB implementation.

Parameters

B : array_like, shape (d, d) Hermitian parameter matrix.

Returns

float Negative log normalization constant.

fit(Z) classmethod

Maximum-likelihood fit of a complex Bingham distribution to data.

Parameters

Z : array_like, shape (d, n) Complex unit vectors (columns); it is assumed that ||z_i|| = 1.

Returns

ComplexBinghamDistribution

cauchy_schwarz_divergence(cB1, cB2) staticmethod

Cauchy-Schwarz divergence between two complex Bingham distributions.

D_CS(p, q) = half * [log C(2B1) + log C(2B2)] - log C(B1+B2) >= 0

Using the stored negative log normalization (log_norm = -log C):

D_CS = log_norm(B1+B2) - half * [log_norm(2*B1) + log_norm(2*B2)]

This matches the MATLAB libDirectional CauchySchwarzDivergence convention.

Parameters

cB1, cB2 : ComplexBinghamDistribution or array_like Distributions or Hermitian parameter matrices.

Returns

float Non-negative divergence value.

ComplexWatsonDistribution

Complex Watson distribution on the complex unit sphere C^D.

References: Mardia, K. V. & Dryden, I. L. The Complex Watson Distribution and Shape Analysis Journal of the Royal Statistical Society: Series B (Statistical Methodology), Blackwell Publishers Ltd., 1999, 61, 913-926

EPSILON = 1e-06 class-attribute instance-attribute

mu = mu instance-attribute

kappa = float(kappa) instance-attribute

dim = mu.shape[0] instance-attribute

log_norm_const property

Log normalization constant log(C_D(kappa)).

__init__(mu, kappa)

Parameters: mu: 1-D complex array of shape (D,), must be a unit vector kappa: scalar concentration parameter

mean()

Return the mean direction (mode) of the distribution.

pdf(za)

Evaluate the pdf at each row of za.

Parameters: za: complex array of shape (N, D) or (D,) for a single point

Returns: Real-valued array of shape (N,) or a scalar

sample(n)

Sample from the complex Watson distribution.

Uses the complex Bingham distribution sampling algorithm described in Mardia, K. V. & Jupp, P. E., Directional Statistics, Wiley, 2009, p. 336.

Parameters: n: number of samples

Returns: complex array of shape (n, D)

fit(Z, weights=None) classmethod

Fit a complex Watson distribution to data using MLE.

Parameters: Z: complex array of shape (N, D) weights: optional 1-D real array of shape (N,)

Returns: ComplexWatsonDistribution

estimate_parameters(Z, weights=None) staticmethod

Estimate parameters of the complex Watson distribution via MLE.

Following Mardia & Dryden (1999).

Parameters: Z: complex array of shape (N, D) weights: optional 1-D real array of shape (N,)

Returns: tuple (mu_hat, kappa_hat)

log_norm(D, kappa) staticmethod

Compute the log normalization constant log(C_D(kappa)).

Uses three numerical regimes for stability (Mardia & Dryden 1999).

Parameters: D: feature-space dimension (integer >= 1) kappa: concentration parameter – scalar or array-like

Returns: log(C_D(kappa)); same shape as kappa (scalar if scalar input)

CustomHemisphericalDistribution

Bases: CustomHyperhemisphericalDistribution, AbstractHemisphericalDistribution

__init__(f)

from_distribution(distribution) staticmethod

CustomHyperhemisphericalDistribution

Bases: AbstractCustomDistribution, AbstractHyperhemisphericalDistribution

__init__(f, dim, scale_by=1)

Initialize a CustomHyperhemisphericalDistribution.

Parameters:

Name Type Description Default
f Callable

function to be used for custom distribution.

required
dim Union[int, int32, int64]

dimension of the distribution.

required
scale_by float

scaling factor for the distribution, default is 1.

1

pdf(xs)

Calculate the probability density function at given points.

Parameters:

Name Type Description Default
xs

points where the pdf will be calculated.

required

Returns:

Type Description

numpy.ndarray: pdf values at given points.

integrate(integration_boundaries=None)

Integrate the pdf over given boundaries.

Parameters:

Name Type Description Default
integration_boundaries

boundaries of the integration, if None, the integration will be performed over the whole domain.

None

Returns:

Type Description

float: result of the integration.

from_distribution(distribution) staticmethod

Create a CustomHyperhemisphericalDistribution from another distribution.

Parameters:

Name Type Description Default
distribution AbstractHypersphericalDistribution

the distribution from which the CustomHyperhemisphericalDistribution will be created.

required

Returns:

Type Description

CustomHyperhemisphericalDistribution: the resulting distribution.

Raises:

Type Description
ValueError

if the type of dist is not supported.

CustomHypersphericalDistribution

Bases: AbstractCustomDistribution, AbstractHypersphericalDistribution

__init__(f, dim, scale_by=1)

from_distribution(distribution) staticmethod

integrate(integration_boundaries=None)

HyperhemisphericalBinghamDistribution

Bases: AbstractHyperhemisphericalDistribution

distFullSphere = BinghamDistribution(Z_, M_) instance-attribute

dim = self.distFullSphere.dim instance-attribute

F property

__init__(Z_, M_)

pdf(xs)

Z()

M()

dF()

sample(n)

multiply(B2)

compose(B2)

mode()

mean_axis()

HyperhemisphericalDiracDistribution

HyperhemisphericalGridDistribution

Bases: AbstractHypersphereSubsetGridDistribution, AbstractHyperhemisphericalDistribution

__init__(grid, grid_values, enforce_pdf_nonnegative=True)

mean_direction()

For hyperhemispheres this method returns the mode (grid point with maximum weight) rather than the true mean direction.

Using the spherical mean would bias the result toward [0; ...; 0; 1], since the lower half of the sphere is not represented.

to_full_sphere(method='antipodal')

Convert hemisphere to full sphere.

The grid is mirrored, and the values are halved to keep the resulting hyperspherical distribution normalized.

plot()

plot_interpolated()

get_closest_point(xs)

Return the closest grid point(s) on the hemisphere, taking the symmetry x ~ -x into account.

Parameters

xs : array_like Either a single point of shape (dim,), or an array of shape (n_points, dim).

Returns

points : ndarray Closest grid point(s), shape (dim,). indices : ndarray or int Indices of the closest grid points.

get_manifold_size()

multiply(other)

Multiply two hyperhemispherical grid distributions that share the same grid.

  1. Convert both to full-sphere grid distributions.
  2. Multiply them as HypersphericalGridDistribution objects.
  3. Restrict back to the hemisphere and rescale.
Parameters

other : HyperhemisphericalGridDistribution

Returns

HyperhemisphericalGridDistribution

Raises

ValueError If the grids are not identical (up to numerical tolerance).

from_function(fun, no_of_grid_points, dim=2, grid_type='leopardi_symm', enforce_pdf_nonnegative=True) staticmethod

Construct a hyperhemispherical grid distribution from a callable.

Parameters

fun : callable A function mapping an array of shape (batch_dim, space_dim) to a 1-D array of pdf values. In particular this matches your Python convention pdf(x) with x.shape == (batch, dim). no_of_grid_points : int Number of grid points on the hemisphere. dim : int, optional Ambient dimension (space_dim). Default is 2 for S². grid_type : {'leopardi_symm', 'healpix'}

Notes

For 'leopardi*' types, the grid is deterministic and only depends on (dim, no_of_grid_points, grid_type). For 'healpix', only dim == 3 is supported and healpy must be installed.

HyperhemisphericalUniformDistribution

Bases: AbstractHyperhemisphericalDistribution, AbstractHypersphereSubsetUniformDistribution

sample(n)

Sample n points from the hyperhemispherical distribution.

Args: n: number of points to sample.

Returns: numpy.ndarray: n sampled points.

get_manifold_size()

Compute the size of the manifold.

Returns: float: size of the manifold.

HyperhemisphericalWatsonDistribution

Bases: AbstractHyperhemisphericalDistribution

dist_full_sphere = WatsonDistribution(mu, kappa) instance-attribute

mu property writable

kappa property writable

__init__(mu, kappa)

pdf(xs)

set_mode(mu)

sample(n)

mode()

shift(shift_by)

HypersphericalDiracDistribution

Bases: AbstractHypersphereSubsetDiracDistribution, AbstractHypersphericalDistribution

plot(*args, **kwargs)

to_circular_dirac_distribution()

mean_direction()

mean_resultant_vector()

HypersphericalGridDistribution

Bases: AbstractHypersphereSubsetGridDistribution, AbstractHypersphericalDistribution

Convention: - self.grid is shape (n_points, input_dim) - self.grid_values is shape (n_points,) - pdf(x) expects x of shape (batch_dim, input_dim)

grid_type = grid_type instance-attribute

__init__(grid, grid_values_, enforce_pdf_nonnegative=True, grid_type='unknown')

get_manifold_size()

mean_direction()

Mean direction on the hypersphere.

pdf(xs)

Piecewise-constant interpolated pdf.

xs can be: - shape (dim,) - shape (batch, dim)

Returns: - scalar if input is 1D - (batch,) if input is 2D

symmetrize()

Make the grid distribution antipodally symmetric.

Requires a symmetric grid: the second half of the grid is the negation of the first half.

New grid_values are the average of each pair, copied to both points.

to_hemisphere(tol=1e-10)

Convert a symmetric full-sphere grid distribution to a HyperhemisphericalGridDistribution on the upper hemisphere.

If the density appears asymmetric (pairwise grid values differ by more than tol), the hemisphere values are formed by summing symmetric pairs instead of 2 * first_half.

get_closest_point(xs)

Return closest grid point(s) in Euclidean distance.

xs can be: - shape (dim,) - shape (batch, dim)

Returns

points : ndarray Shape (dim,) for single query or (batch, dim) for multiple. indices : int or ndarray Index/indices of closest grid points.

multiply(other)

Multiply two hyperspherical grid distributions defined on the same grid.

This method simply checks grid compatibility and then delegates to the superclass multiply implementation.

from_function(fun, no_of_grid_points, dim, grid_type='leopardi', enforce_pdf_nonnegative=True) staticmethod

Construct a HypersphericalGridDistribution from a callable.

Parameters

fun : callable Function taking an array of shape (batch_dim, space_dim) and returning a 1D array of pdf values. no_of_grid_points : int Grid parameter (interpreted as number of points for 'leopardi' and total number of points for symmetric schemes). dim : int Ambient space dimension (>= 2). grid_type : str Type of grid to use. See get_grid_hypersphere for options. enforce_pdf_nonnegative : bool Whether to enforce non-negativity of grid values in base class.

HypersphericalMixture

Bases: AbstractMixture, AbstractHypersphericalDistribution

A class used to represent a mixture of hyperspherical distributions.

__init__(dists, w)

Initializes the HypersphericalMixture with a list of distributions and weights.

Args: dists (List[AbstractHypersphericalDistribution]): The list of hyperspherical distributions. w (List[float]): The list of weights for each distribution.

HypersphericalUniformDistribution

Bases: AbstractHypersphericalDistribution, AbstractHypersphereSubsetUniformDistribution

__init__(dim)

pdf(xs)

ln_pdf(xs)

sample(n)

get_manifold_size()

SphericalGridDistribution

Bases: HypersphericalGridDistribution, AbstractSphericalDistribution

Grid-based approximation of a spherical (S²) distribution.

Conventions: - grid: shape (n_points, 3) - grid_values: shape (n_points,) - pdf(x): x has shape (batch_dim, space_dim) = (N, 3)

__init__(grid, grid_values, enforce_pdf_nonnegative=True, grid_type='unknown')

normalize(tol=0.01, warn_unnorm=True)

Normalize the grid-based pdf.

If grid_type == 'sh_grid', we still normalize but warn because the grid may not be into equally-sized areas.

plot_interpolated(use_harmonics=True)

Plot interpolated pdf.

use_harmonics = False -> piecewise constant interpolation via self.pdf(..., False). use_harmonics = True -> spherical harmonics interpolation (currently unsupported).

pdf(xs, use_harmonics=False)

Pdf on S².

Parameters

xa : array_like (batch_dim, 3). use_harmonics : bool If True: interpolate via spherical harmonics (preferred). If False: piecewise constant interpolation on the grid.

from_distribution(distribution, no_of_grid_points, grid_type='leopardi', enforce_pdf_nonnegative=True) staticmethod

Construct a SphericalGridDistribution from an AbstractHypersphericalDistribution.

from_function(fun, no_of_grid_points, dim=2, grid_type='leopardi', enforce_pdf_nonnegative=True) staticmethod

Construct from a function fun(x) where x has shape (batch_dim, 3).

grid_type: - 'leopardi' : Leopardi equal point set on S² - 'sh_grid' : spherical harmonics grid (lat/lon mesh).

SphericalHarmonicsDistributionComplex

Bases: AbstractSphericalHarmonicsDistribution

assert_real = assert_real instance-attribute

__init__(coeff_mat, transformation='identity', assert_real=True)

value(xs)

value_sph(phi, theta)

to_spherical_harmonics_distribution_real()

mean_direction()

from_distribution_via_integral(dist, degree, transformation='identity') staticmethod

from_function_via_integral_cart(fun_cart, degree, transformation='identity') staticmethod

from_function_via_integral_sph(fun, degree, transformation='identity') staticmethod

from_distribution_numerical_fast(dist, degree, transformation='identity') staticmethod

Approximate dist by a degree-degree SHD using a DH grid.

This is faster than :meth:from_distribution_via_integral because it uses the discrete spherical-harmonic transform instead of numerical quadrature.

convolve(other)

Spherical convolution with a zonal distribution other.

For the 'identity' transformation the standard frequency-domain formula is used (exact for bandlimited functions). For the 'sqrt' transformation a grid-based approach with a 2× finer intermediate grid is used so that squaring the sqrt functions introduces no aliasing.

multiply(other)

Pointwise multiplication in physical space (Bayesian update step).

Works for both 'identity' and 'sqrt' transformations. For 'sqrt': sqrt(p) * sqrt(q) = sqrt(p*q) which is the correct sqrt-transformed product density.

rotate(alpha, beta, gamma)

Rotate the distribution by ZYZ Euler angles (in radians).

Parameters

alpha : float First rotation angle around Z (radians). beta : float Second rotation angle around Y (radians). gamma : float Third rotation angle around Z (radians).

SphericalHarmonicsDistributionReal

Bases: AbstractSphericalHarmonicsDistribution

__init__(coeff_mat, transformation='identity')

real_spherical_harmonic_basis_function(n, m, theta, phi) staticmethod

value(xs)

to_spherical_harmonics_distribution_complex()

VonMisesFisherDistribution

Bases: AbstractHypersphericalDistribution

von Mises-Fisher distribution on the unit hypersphere.

The distribution is defined on unit vectors in R^d. In PyRecEst, input_dim is d and dim is the manifold dimension d - 1. Von Mises-Fisher distribution on the hypersphere.

References

Fisher, R. (1953). Dispersion on a sphere. Proceedings of the Royal Society of London. Series A, Mathematical and Physical Sciences, 217(1130), 295-305.

mu = mu instance-attribute

kappa = kappa instance-attribute

C = kappa / (4 * pi * sinh(kappa)) instance-attribute

__init__(mu, kappa)

Create a von Mises-Fisher distribution.

Parameters

mu : array-like, shape (d,) Unit mean direction in the embedding space. kappa : float Positive concentration parameter. Larger values concentrate more mass around mu.

pdf(xs)

Evaluate the density at unit vectors.

Parameters

xs : array-like, shape (d,) or (..., d) Unit-vector evaluation point or batch of points in the embedding space.

mean_direction()

Return the unit mean direction with shape (d,).

sample(n)

Generate random unit vectors from the distribution.

Parameters

n : int Number of samples to generate.

Returns

array-like, shape (n, d) Random samples on the unit hypersphere.

Notes

Sampling currently requires the NumPy backend and SciPy's vonmises_fisher implementation.

sample_deterministic()

Return deterministic sigma points matched to the mean direction.

get_rotation_matrix()

Return an orthogonal matrix whose first column is mu.

mean_resultant_vector()

Return the mean resultant vector with shape (d,).

from_distribution(d) staticmethod

Fit a von Mises-Fisher distribution to mean-resultant information.

from_mean_resultant_vector(m) staticmethod

Create a distribution from a mean resultant vector.

Parameters

m : array-like, shape (d,) Mean resultant vector. Its direction becomes mu and its norm is inverted to estimate kappa.

mode()

Return the modal direction, equal to mu.

set_mean(new_mean)

Replace the mean direction and return the distribution.

set_mode(new_mode)

Replace the modal direction and return the distribution.

multiply(other)

Multiply two vMF densities and return the normalized product.

convolve(other)

Convolve with a zonal vMF distribution.

other must be zonal around the final coordinate axis.

a_d(d, kappa) staticmethod

Return the ratio of modified Bessel functions used by vMF moments.

a_d_inverse(d, x) staticmethod

Numerically invert :meth:a_d for dimension d and value x.

WatsonDistribution

Bases: AbstractHypersphericalDistribution

EPSILON = 1e-06 class-attribute instance-attribute

mu = mu instance-attribute

kappa = kappa instance-attribute

norm_const property

ln_norm_const property

__init__(mu, kappa, norm_const=None)

Initializes a new instance of the WatsonDistribution class.

Args: mu (): The mean direction of the distribution. kappa (float): The concentration parameter of the distribution.

pdf(xs)

Computes the probability density function at xs.

Args: xs: The values at which to evaluate the pdf.

Returns: np.generic: The value of the pdf at xs.

ln_pdf(xs)

to_bingham()

sample(n)

mode()

set_mode(new_mode)

shift(shift_by)

AbstractHypertoroidalDistribution

Bases: AbstractPeriodicDistribution

An abstract class representing a Hypertoroidal Distribution

input_dim property

integrate_fun_over_domain(f, dim) staticmethod

shift(shift_by)

Shift the distribution by a given vector.

Parameters:

Name Type Description Default
shift_by

The shift vector. Must be of the same dimension as the distribution.

required

Returns:

Type Description
CustomHypertoroidalDistribution

The shifted distribution.

Raises:

Type Description
AssertionError

If the shift vector is not of the same dimension as the distribution.

integrate_fun_over_domain_part(f, integration_boundaries) staticmethod

integrate_numerically(integration_boundaries=None)

trigonometric_moment_numerical(n)

Calculates the complex trignometric moments. Since nquad does not support complex functions, the calculation is split up (as used in the alternative representation of trigonometric polonymials involving the two real numbers alpha and beta

entropy_numerical()

get_manifold_size()

angular_error(alpha, beta) staticmethod

Calculates the angular error between alpha and beta.

Parameters: alpha (float or numpy array): The first angle(s) in radians. beta (float or numpy array): The second angle(s) in radians.

Returns: float or numpy array: The angular error(s) in radians.

hellinger_distance_numerical(other)

total_variation_distance_numerical(other)

plot(resolution=128, **kwargs)

mean()

Convenient access to mean_direction to have a consistent interface throughout manifolds.

Returns:

Type Description

The mean of the distribution.

mean_direction()

mode()

mode_numerical()

trigonometric_moment(n)

integrate(integration_boundaries=None)

mean_2dimD()

sample_metropolis_hastings(n, burn_in=10, skipping=5, proposal=None, start_point=None)

setup_axis_circular(axis_name='x', ax=plt.gca()) staticmethod

AbstractToroidalBivarVMDistribution

Bases: AbstractToroidalDistribution

Abstract base for bivariate von Mises distributions on the torus.

Subclasses share the same pdf structure:

C * exp(kappa1*cos(x1 - mu1) + kappa2*cos(x2 - mu2) + coupling_term)

and must implement :meth:_coupling_term.

mu = mod(mu, 2.0 * pi) instance-attribute

kappa = kappa instance-attribute

__init__(mu, kappa)

pdf(xs)

AbstractToroidalDistribution

Bases: AbstractHypertoroidalDistribution

__init__()

covariance_4D_numerical()

circular_correlation_jammalamadaka()

circular_correlation_jammalamadaka_numerical()

mean_4D()

Calculates the 4D mean of [cos(x1), sin(x1), cos(x2), sin(x2)]

Returns: mu (4 x 1) expectation value of [cos(x1), sin(x1), cos(x2), sin(x2)]

CustomHypertoroidalDistribution

Bases: AbstractHypertoroidalDistribution, AbstractCustomDistribution

shift_by = zeros(dim) instance-attribute

__init__(f, dim, shift_by=None)

pdf(xs)

to_custom_circular()

to_custom_toroidal()

CustomToroidalDistribution

HypertoroidalDiracDistribution

Bases: AbstractDiracDistribution, AbstractHypertoroidalDistribution

__init__(d, w=None, dim=None)

Can set dim manually to tell apart number of samples vs dimension for 1-D arrays.

from_distribution(distribution, n_particles=None) staticmethod

Create a hypertoroidal Dirac approximation from a distribution.

Grid distributions are converted deterministically by using every grid point as a Dirac location and normalized grid values as weights. Other hypertoroidal distributions are approximated by sampling and need n_particles.

plot(resolution=128, **kwargs)

set_mean(mean)

mean_direction()

Calculate the mean direction of the HypertoroidalDiracDistribution.

Parameters:

Name Type Description Default
self

HypertoroidalDiracDistribution instance

required

Returns:

Type Description

Mean direction

trigonometric_moment(n)

Calculate the trigonometric moment of the HypertoroidalDiracDistribution.

Parameters:

Name Type Description Default
self

HypertoroidalDiracDistribution instance

required
n Union[int, int32, int64]

Integer moment order

required

Returns:

Type Description

Trigonometric moment

apply_function(f, function_is_vectorized=True)

to_toroidal_wd()

marginalize_to_1D(dimension)

marginalize_out(dimensions)

shift(shift_by)

entropy()

to_wd()

HypertoroidalFourierDistribution

Bases: AbstractOrthogonalBasisDistribution, AbstractHypertoroidalDistribution

Hypertoroidal distribution represented by a Fourier series.

coeff_mat (self.coeff_mat) contains the complex Fourier coefficients on an index grid k ∈ {-k_max_d, ..., 0, ..., +k_max_d}^dim.

The 'transformation' argument controls how the coefficients relate to the actual pdf:

- 'identity':  pdf(x) = sum_k C_k exp(i k⋅x)
- 'sqrt':      pdf(x) = | sum_k C_k exp(i k⋅x) |^2
- 'log':       pdf(x) ∝ exp(sum_k C_k exp(i k⋅x))  (no auto-normalization)

References

Pfaff, F., Kurz, G., & Hanebeck, U. D. (2016). Multivariate Angular Filtering Using Fourier Series. Journal of Advances in Information Fusion, 11(2), 206-226.

__init__(coeff_mat, transformation='sqrt')

value(xs)

Evaluate the underlying (pre-transformation) Fourier series at xs.

Parameters

xs : array_like, shape (n_eval, dim) or (dim,) Points on the hypertorus in radians.

Returns

val : array, shape (n_eval,) Complex-valued series evaluation (real up to numerical error).

normalize_in_place(tol=0.0001, warn_unnorm=True)

Normalize the coefficients so that the implied pdf integrates to 1.

truncate(n_coefficients, force_normalization=False)

Truncate or pad the coefficient tensor to a desired size, centered.

n_coefficients : int or sequence of ints Desired number of complex coefficients along each dimension. Must be odd and >1 except possibly in the 1-D case.

force_normalization : bool If True, ensures the resulting distribution is normalized even if the transformation is 'identity'.

transform_via_coefficients(desired_transformation, n_coefficients=None)

Transform the representation (e.g., square the underlying function) directly in coefficient space, where supported.

Currently supports only desired_transformation == 'square'.

multiply(f2, n_coefficients=None)

Multiply two hypertoroidal Fourier distributions (same transformation).

trigonometric_moment(n)

Compute the n-th trigonometric moment for each angular component.

Returns a vector m of length self.dim where

m[d] = E[exp(i * n * x_d)],  for d = 0..dim-1

from_function(fun, n_coefficients, desired_transformation='sqrt') staticmethod

Construct a Fourier distribution by sampling a function on a grid.

Parameters

fun : callable Takes 'dim' arrays as input (each axis of the grid) and returns an array of the same shape representing the (possibly unnormalized) pdf on the grid. n_coefficients : tuple[int] Desired number of Fourier coefficients along each dimension. desired_transformation : str Transformation to apply to the function values before computing Fourier coefficients. One of 'sqrt', 'log', 'identity'.

from_function_values(fvals, n_coefficients=None, desired_transformation='sqrt', already_transformed=False) classmethod

Creates Fourier distribution from function values on a regular grid.

fvals : n-D array Values of the (possibly unnormalized) density on a regular grid.

n_coefficients : tuple[int, ...], optional Desired number of Fourier coefficients along each dimension. If None, defaults to size(fvals) plus 1 in even-dimension sizes.

from_distribution(distribution, n_coefficients, desired_transformation='sqrt') classmethod

Approximate a given hypertoroidal distribution with a Fourier series.

n_coefficients can be a single integer (broadcast to all dimensions) or a sequence with length equal to distribution.dim.

integrate(integration_boundaries=None)

transform_via_fft(desired_transformation, n_coefficients=None)

Transform the distribution by: 1) Going to state space via IFFT (using current 'identity' coeffs), 2) Applying the desired transformation (sqrt / log / identity / custom), 3) Recomputing Fourier coeffs via FFT and truncating.

convolve(f2, n_coefficients=None)

Convolution of two hypertoroidal Fourier distributions.

shift(shift_by)

Shift distribution by shift_by (on the hypertorus).

Parameters

shift_by : array_like, shape (dim,) Shift in radians for each angular dimension.

HypertoroidalGridDistribution

Bases: AbstractGridDistribution, AbstractHypertoroidalDistribution

Grid-based distribution on a hypertorus.

Python convention: * grid: array of shape (n_grid_points, dim) * grid_values: array of shape (n_grid_points,) * pdf(x): x has shape (n_eval, dim)

__init__(grid_values, grid_type='custom', grid=None, enforce_pdf_nonnegative=True, dim=None)

get_closest_point(xs)

Return the closest grid point (toroidal distance) to x.

Parameters

x : array_like, shape (dim,) or (1, dim)

get_manifold_size()

generate_cartesian_product_grid(n_grid_points) staticmethod

Generate a Cartesian product grid on [0, 2π)^dim.

Parameters

n_grid_points : int or sequence of int Number of grid points along each dimension.

multiply(other)

pdf(xs)

Evaluate the pdf at given query points.

Parameters

xs : array_like (backend compatible), shape (n_points_eval, dim) or (dim,)

get_grid()

pdf_unnormalized(xs)

value_of_closest(xa)

Return pdf values of the closest grid point for each query.

Parameters

xa : array_like, shape (n_eval, dim) or (dim,)

from_distribution(distribution, n_grid_points, grid_type='cartesian_prod', enforce_pdf_nonnegative=True) staticmethod

Create a grid distribution from an existing hypertoroidal distribution.

from_function(fun, n_grid_points, grid_type='cartesian_prod', enforce_pdf_nonnegative=True) staticmethod

Construct a grid distribution by sampling a function on a grid. You need to provide the number of grid points along each dimension. Dimensionality of the torus is determined by the length of n_grid_points.

Parameters

fun : callable Function handle representing a (possibly unnormalized) pdf. Must accept an array of shape (n_eval, dim) and return shape (n_eval,). n_grid_points : int or sequence of int Number of grid points along each dimension.

to_dirac_distribution()

Return a weighted Dirac distribution on the grid points.

plot(*args, **kwargs)

trigonometric_moment(n)

HypertoroidalMixture

Bases: AbstractMixture, AbstractHypertoroidalDistribution

dists = self.dists instance-attribute

input_dim property

__init__(dists, w=None)

Constructor

Parameters:

Name Type Description Default
dists Sequence[AbstractHypertoroidalDistribution]

list of hypertoroidal distributions

required
w

list of weights

None

trigonometric_moment(n)

Calculate n-th trigonometric moment

Parameters:

Name Type Description Default
n Union[int, int32, int64]

number of moment

required

Returns:

Type Description

n-th trigonometric moment (complex number)

shift(shift_by)

Shifts the distribution by shift_by.

Parameters:

Name Type Description Default
shift_by

angles to shift by

required

Returns:

Type Description

shifted distribution

to_circular_mixture()

Convert to a circular mixture (only in 1D case)

Returns:

Type Description

CircularMixture with same parameters

to_toroidal_mixture()

Convert to a toroidal mixture (only in 2D case)

Returns:

Type Description

ToroidalMixture with same parameters

HypertoroidalUniformDistribution

Bases: AbstractUniformDistribution, AbstractHypertoroidalDistribution

pdf(xs)

Returns the Probability Density Function evaluated at xs

Parameters:

Name Type Description Default
xs

Values at which to evaluate the PDF

required

Returns:

Type Description

PDF evaluated at xs

trigonometric_moment(n)

Returns the n-th trigonometric moment

Parameters:

Name Type Description Default
n Union[int, int32, int64]

Moment order

required

Returns:

Type Description

n-th trigonometric moment

entropy()

Returns the entropy of the distribution

Returns:

Type Description
float

Entropy

mean_direction()

Returns the mean of the circular uniform distribution. Since it doesn't have a unique mean, this function always raises a ValueError.

Raises:

Type Description
ValueError

Circular uniform distribution does not have a unique mean

sample(n)

Returns a sample of size n from the distribution

Parameters:

Name Type Description Default
n Union[int, int32, int64]

Sample size

required

Returns:

Type Description

Sample of size n

get_manifold_size()

shift(shift_by)

Shifts the distribution by shift_by. Since this is a uniform distribution, the shift does not change the distribution.

Parameters:

Name Type Description Default
shift_by

Angles to shift by

required

Returns:

Type Description
HypertoroidalUniformDistribution

Shifted distribution

integrate(integration_boundaries=None)

Returns the integral of the distribution over the specified boundaries

Parameters:

Name Type Description Default
integration_boundaries

Optional boundaries for integration. If None, uses the entire distribution support.

None

Returns:

Type Description
float

Integral over the specified boundaries

HypertoroidalWrappedNormalDistribution

Bases: AbstractHypertoroidalDistribution

mu = mod(mu, 2.0 * pi) instance-attribute

C = C instance-attribute

__init__(mu, C)

Initialize HypertoroidalWrappedNormalDistribution.

Parameters:

Name Type Description Default
mu

Mean vector.

required
C

Covariance matrix.

required

Raises:

Type Description
AssertionError

If C_ is not square, not symmetric, not positive definite, or its dimension does not match with mu_.

set_mean(mu)

Set the mean of the distribution.

Parameters: mu (numpy array): The new mean.

Returns: HypertoroidalWNDistribution: A new instance of the distribution with the updated mean.

pdf(xs, m=3)

Compute the PDF at given points.

Parameters:

Name Type Description Default
xs

Points to evaluate the PDF at.

required
m Union[int, int32, int64]

Controls the number of terms in the Fourier series approximation.

3

Returns:

Type Description

PDF values at xs.

shift(shift_by)

Shift distribution by the given angles

Parameters:

Name Type Description Default
shift_by

Angles to shift by.

required

Returns:

Type Description
HypertoroidalWrappedNormalDistribution

Shifted distribution.

Raises:

Type Description
AssertionError

If shape of shift_by does not match the dimension of the distribution.

sample(n)

convolve(other)

set_mode(m)

Set the mode of the distribution.

Parameters: m (numpy array): The new mode.

Returns: HypertoroidalWNDistribution: A new instance of the distribution with the updated mode.

trigonometric_moment(n)

Calculate the trigonometric moment of the HypertoroidalWNDistribution.

Parameters:

Name Type Description Default
self

HypertoroidalWNDistribution instance

required
n

Integer moment order

required

Returns:

Type Description

Trigonometric moment

mode()

ToroidalDiracDistribution

Bases: HypertoroidalDiracDistribution, AbstractToroidalDistribution

__init__(d, w)

Initialize ToroidalDiracDistribution.

Parameters:

Name Type Description Default
d

Array of positions.

required
w

Array of weights.

required

circular_correlation_jammalamadaka()

Calculate the circular correlation according to Jammalamadaka's definition

Returns:

Type Description
float

Correlation coefficient.

covariance_4D()

Compute the 4D covariance matrix.

Returns:

Type Description

4D covariance matrix.

ToroidalFourierDistribution

Bases: HypertoroidalFourierDistribution, AbstractToroidalDistribution

Distribution on the torus [0, 2π)^2 represented by a 2-D Fourier series.

Inherits all Fourier-based methods from HypertoroidalFourierDistribution and all toroidal-specific methods (e.g. mean_4D, covariance_4D_numerical, circular_correlation_jammalamadaka_numerical) from AbstractToroidalDistribution.

This port follows: Florian Pfaff, Gerhard Kurz, Uwe D. Hanebeck, "Multivariate Angular Filtering Using Fourier Series", Journal of Advances in Information Fusion, 11(2):206-226, Dec 2016.

__init__(coeff_mat, transformation='sqrt')

integrate(integration_boundaries=None)

Compute the integral of the pdf over the given rectangular region.

Parameters

integration_boundaries : array-like, shape (2, 2), optional [[l1, r1], [l2, r2]]. Defaults to [[0, 2π], [0, 2π]].

Returns

float Value of the integral.

covariance_4d()

Compute the 4×4 covariance of [cos x1, sin x1, cos x2, sin x2].

Delegates to the numerical implementation from AbstractToroidalDistribution.

circular_correlation_jammalamadaka()

Jammalamadaka–SenGupta circular correlation, computed analytically from the Fourier coefficients.

to_twn()

Approximate this distribution with a Toroidal Wrapped Normal.

Uses the moment-matching formula via Fourier coefficients.

Returns

ToroidalWrappedNormalDistribution The best-fitting TWN.

from_function(fun, n_coefficients, desired_transformation='sqrt') classmethod

Construct a ToroidalFourierDistribution from a function on the torus.

Parameters

fun : callable Function of two arrays (x1_grid, x2_grid) returning pdf values. n_coefficients : int or tuple[int, int] Number of Fourier coefficients per dimension (must be odd ≥ 3). desired_transformation : str 'sqrt', 'identity', or 'log'.

from_function_values(fvals, n_coefficients=None, desired_transformation='sqrt', already_transformed=False) classmethod

Construct a ToroidalFourierDistribution from function values on a grid.

Parameters

fvals : 2-D array Function values on a regular grid over [0, 2π)^2. n_coefficients : tuple[int, int] or None If None, inferred from fvals shape. desired_transformation : str already_transformed : bool

from_distribution(distribution, n_coefficients, desired_transformation='sqrt') classmethod

Approximate a given toroidal distribution with a ToroidalFourierDistribution.

Parameters

distribution : AbstractHypertoroidalDistribution Distribution to approximate (must have dim == 2). n_coefficients : int or tuple[int, int] Number of Fourier coefficients per dimension. desired_transformation : str

ToroidalMixture

Bases: HypertoroidalMixture, AbstractToroidalDistribution

__init__(hds, w)

Constructor

Parameters:

Name Type Description Default
hds list[AbstractToroidalDistribution]

list of toroidal distributions

required
w

list of weights

required

ToroidalUniformDistribution

Bases: HypertoroidalUniformDistribution, AbstractToroidalDistribution

get_manifold_size()

shift(_)

ToroidalVMMatrixDistribution

Bases: AbstractToroidalDistribution

Bivariate von Mises distribution, matrix version.

References

Mardia, K. V. (1975). Statistics of Directional Data. Journal of the Royal Statistical Society: Series B, 37, 349-393.

Mardia, K. V., & Jupp, P. E. (1999). Directional Statistics. Wiley.

Kurz, G., & Hanebeck, U. D. (2015). Toroidal Information Fusion Based on the Bivariate von Mises Distribution. Proceedings of the 2015 IEEE International Conference on Multisensor Fusion and Information Integration.

mu = mod(mu, _2pi) instance-attribute

kappa = kappa instance-attribute

A = A instance-attribute

C = 1.0 instance-attribute

__init__(mu, kappa, A)

pdf(xs)

multiply(other)

Multiply two ToroidalVMMatrixDistributions (exact product).

marginalize_to_1d(dimension)

Get marginal distribution in the given dimension (0 or 1, 0-indexed).

Integrates out the other dimension analytically using the Bessel function identity for the von-Mises-type integral.

shift(shift_by)

Return a copy of this distribution shifted by shift_by.

ToroidalVMRivestDistribution

Bases: AbstractToroidalDistribution

Bivariate von Mises distribution (Rivest version) with two correlation parameters alpha and beta, corresponding to A = diag([alpha, beta]).

Rivest, L.-P. A Distribution for Dependent Unit Vectors Communications in Statistics - Theory and Methods, 1988, 17, 461-483

mu = mod(mu, 2.0 * pi) instance-attribute

kappa = kappa instance-attribute

alpha = alpha instance-attribute

beta = beta instance-attribute

C = 1.0 / self.norm_const instance-attribute

norm_const property

__init__(mu, kappa, alpha, beta)

pdf(xs)

trigonometric_moment(n)

circular_correlation_jammalamadaka()

shift(shift_by)

ToroidalVonMisesCosineDistribution

Bases: AbstractToroidalBivarVMDistribution

Bivariate von Mises distribution, cosine model.

Corresponds to A = [-kappa3, 0; 0, -kappa3].

References: Mardia, K. V.; Taylor, C. C. & Subramaniam, G. K. Protein Bioinformatics and Mixtures of Bivariate von Mises Distributions for Angular Data Biometrics, 2007, 63, 505-512

Mardia, K. V. & Frellsen, J. in Hamelryck, T.; Mardia, K. &
Ferkinghoff-Borg, J. (Eds.)
Statistics of Bivariate von Mises Distributions
Bayesian Methods in Structural Bioinformatics,
Springer Berlin Heidelberg, 2012, 159-178

kappa3 = kappa3 instance-attribute

C = 1.0 / self.norm_const instance-attribute

norm_const property

__init__(mu, kappa, kappa3)

trigonometric_moment(n)

shift(shift_by)

ToroidalVonMisesSineDistribution

Bases: AbstractToroidalBivarVMDistribution

Bivariate von Mises sine model on the torus.

References

Singh, H., Hnizdo, V., & Demchuk, E. (2002). Probabilistic model for two dependent circular variables. Biometrika, 89(3), 719-723.

lambda_ = lambda_ instance-attribute

C = 1.0 / self.norm_const instance-attribute

norm_const property

__init__(mu, kappa, lambda_)

ToroidalWrappedNormalDistribution

Bases: HypertoroidalWrappedNormalDistribution, AbstractToroidalDistribution

Bivariate wrapped normal distribution on the torus.

References

Kurz, G., Gilitschenski, I., Dolgov, M., & Hanebeck, U. D. (2014). Bivariate Angular Estimation Under Consideration of Dependencies Using Directional Statistics. Proceedings of the 53rd IEEE Conference on Decision and Control.

mean_4D()

Compute the 4D mean of the distribution.

Returns: array: The 4D mean.

covariance_4D()

Compute the 4D covariance of the distribution.

Returns: array: The 4D covariance.

AbstractHyperrectangularDistribution

Bases: AbstractBoundedNonPeriodicDistribution

bounds = bounds instance-attribute

input_dim property

__init__(bounds)

get_manifold_size()

integrate(integration_boundaries=None)

Integrate the probability density function over given boundaries. If no boundaries are provided, default to self.bounds.

Args: integration_boundaries (tuple): A tuple of two elements, each of which can be either a scalar or an array. If a scalar, it represents a single boundary value. If an array, it represents multiple boundary values.

Returns: float: The result of the integration.

AbstractLinearDistribution

Bases: AbstractManifoldSpecificDistribution

input_dim property

__init__(dim)

mean()

covariance()

get_manifold_size()

mode(starting_point=None)

mode_numerical(starting_point=None)

sample_metropolis_hastings(n, burn_in=10, skipping=5, proposal=None, start_point=None)

mean_numerical()

covariance_numerical()

integrate(left=None, right=None)

integrate_numerically(left=None, right=None)

integrate_fun_over_domain(f, dim, left, right) staticmethod

get_suggested_integration_limits(scaling_factor=10)

Returns suggested limits for integration over the whole density.

The linear part should be integrated from -Inf to Inf but Python's numerical integration does not handle that well. When we can obtain the covariance of the linear part easily, we integrate from mu-10sigma to mu+scaling_factorsigma, which contains almost the entire probability mass. The circular part is integrated form 0 to 2pi.

Returns: l (numpy.ndarray): lower integration bound (shape: (linD+boundD,)) r (numpy.ndarray): upper integration bound (shape: (linD+boundD,))

plot(*args, plot_range=None, **kwargs)

plot_state(scaling_factor=1, color=(0, 0.447, 0.741))

CustomLinearDistribution

Bases: AbstractLinearDistribution, AbstractCustomNonPeriodicDistribution

Linear distribution with custom pdf.

shift_by = shift_by instance-attribute

__init__(f, dim, scale_by=1, shift_by=None)

Constructor, it is the user's responsibility to ensure that f is a valid linear density.

Parameters: f_ (function handle) pdf of the distribution dim_ (scalar) dimension of the Euclidean space

shift(shift_by)

set_mean(new_mean)

pdf(xs)

from_distribution(distribution) staticmethod

Creates a CustomLinearDistribution from some other distribution

Parameters: dist (AbstractLinearDistribution) distribution to convert

Returns: chd (CustomLinearDistribution) CustomLinearDistribution with identical pdf

integrate(left=None, right=None)

GaussianDistribution

Bases: AbstractLinearDistribution

Multivariate Gaussian distribution on a Euclidean space.

Parameters

mu : array-like, shape (n,) or scalar Mean vector. Scalar input is treated as a one-dimensional Gaussian. C : array-like, shape (n, n) or scalar Positive-definite covariance matrix. Scalar input is treated as the covariance of a one-dimensional Gaussian. check_validity : bool, optional If true, validate that C is positive definite.

Attributes

mu : array-like, shape (n,) Mean vector. C : array-like, shape (n, n) Covariance matrix.

mu = mu instance-attribute

C = C instance-attribute

__init__(mu, C, check_validity=True)

set_mean(new_mean)

Return a copy with a replaced mean vector.

Parameters

new_mean : array-like, shape (n,) New mean vector.

pdf(xs)

Evaluate the probability density.

Parameters

xs : array-like, shape (n,) or (..., n) Evaluation point or batch of evaluation points. For a one-dimensional Gaussian, one-dimensional arrays are interpreted as a batch of scalar evaluation points.

Returns

array-like Density values with one value per evaluation point.

shift(shift_by)

Return a copy with its mean shifted by shift_by.

Parameters

shift_by : array-like, shape (n,) or scalar Additive shift for the mean vector.

mean()

Return the mean vector with shape (n,).

mode(starting_point=None)

Return the mode of the Gaussian, equal to the mean vector.

set_mode(new_mode)

Return a copy with a replaced mode.

For a Gaussian distribution, the mode and mean are identical.

covariance()

Return the covariance matrix with shape (n, n).

multiply(other)

Multiply two Gaussian densities and return the normalized product.

Parameters

other : GaussianDistribution Gaussian distribution with the same dimension as self.

Returns

GaussianDistribution Gaussian proportional to the pointwise product of both densities.

convolve(other)

Convolve two independent Gaussian distributions.

Parameters

other : GaussianDistribution Gaussian distribution with the same dimension as self.

Returns

GaussianDistribution Gaussian whose mean and covariance are the sums of both operands.

marginalize_out(dimensions)

Return the marginal distribution after dropping dimensions.

Parameters

dimensions : int or iterable of int Zero-based state dimensions to remove from the distribution.

sample(n)

Draw n random samples with shape (n, dim).

from_distribution(distribution, check_validity=False) staticmethod

Approximate or convert another distribution as a Gaussian.

Gaussian mixtures are converted with to_gaussian. Other distributions must expose mean and covariance information compatible with :class:GaussianDistribution.

GaussianMixture

Bases: LinearMixture, AbstractLinearDistribution

__init__(dists, w)

mean()

set_mean(new_mean)

to_gaussian(check_validity=True)

covariance()

mixture_parameters_to_gaussian_parameters(means, covariance_matrices, weights=None) staticmethod

HyperrectangularUniformDistribution

Bases: AbstractUniformDistribution, AbstractHyperrectangularDistribution

__init__(bounds)

get_manifold_size()

LinearBoxParticleDistribution

Bases: AbstractLinearDistribution

Mixture of uniform densities supported on axis-aligned boxes.

The represented density is

.. math:: p(x) = \sum_i w_i \mathcal{U}(x; [\ell_i, u_i]),

where each box particle is encoded by a lower and an upper corner. The d property returns the box centers so that the class can interoperate with APIs that expect particle locations, while the full box support is kept in lower and upper.

lower = copy.copy(lower) instance-attribute

upper = copy.copy(upper) instance-attribute

w = ones(n_boxes) / n_boxes instance-attribute

d property writable

Return the box centers for compatibility with particle APIs.

__init__(lower, upper=None, w=None)

normalize_in_place()

Normalize weights in-place.

normalize()

centers()

Return all box centers with shape (n_boxes, dim).

widths()

Return side lengths of all boxes.

half_widths()

Return side half-lengths of all boxes.

volumes()

Return the hypervolume of every box particle.

mean()

Return the mixture mean.

covariance()

Return the covariance of the uniform box mixture.

This includes both the covariance of the box centers and the within-box covariance of each uniform hyperrectangle, diag(width**2 / 12).

set_mean(new_mean)

Shift all boxes so the mixture has the supplied mean.

sample(n)

Draw point samples from the represented box mixture.

pdf(xs)

Evaluate the mixture density at xs.

For one-dimensional distributions, a vector of shape (n,) is treated as n scalar evaluation points. For higher dimensions, a vector of shape (dim,) is treated as a single point.

reweigh(f)

Return a copy with weights multiplied by f evaluated at centers.

integrate(left=None, right=None)

Integrate the mixture over an axis-aligned query box.

mode(starting_point=None)

Return the center of the box with highest mixture density.

from_distribution(distribution, n_particles=None, n_samples=None, n=None, box_half_width=0.5) staticmethod

Create equally sized boxes around samples from another distribution.

LinearDiracDistribution

Bases: AbstractDiracDistribution, AbstractLinearDistribution

__init__(d, w=None)

mean()

set_mean(new_mean)

covariance()

plot(*args, **kwargs)

from_distribution(distribution, n_particles=None, n_samples=None, n=None) staticmethod

weighted_samples_to_mean_and_cov(samples, weights=None) staticmethod

LinearMixture

Bases: AbstractMixture, AbstractLinearDistribution

input_dim property

__init__(dists, w)

SE2DiracDistribution

Bases: HypercylindricalDiracDistribution, AbstractSE2Distribution

Partially wrapped Dirac distribution on SE(2).

Represents a distribution on SE(2) = S^1 x R^2 using weighted Dirac components. Each component d[i] = (angle, x, y) encodes a pose.

References: Gerhard Kurz, Igor Gilitschenski, Uwe D. Hanebeck, The Partially Wrapped Normal Distribution for SE(2) Estimation, Proceedings of the 2014 IEEE International Conference on Multisensor Fusion and Information Integration (MFI 2014), Beijing, China, September 2014.

__init__(d, w=None)

Initialize SE2DiracDistribution.

Parameters

d : array of shape (n, 3) Dirac locations with columns [angle, x, y], where angle is in [0, 2*pi). w : array of shape (n,), optional Weights for each Dirac component. Defaults to uniform weights.

mean_4d()

Compute the 4D mean [E[cos(angle)], E[sin(angle)], E[x], E[y]].

Returns

array of shape (4,)

covariance_4d()

Compute the 4D second moment matrix for [cos(angle), sin(angle), x, y].

This is the weighted sum of outer products sum_i w_i * s_i * s_i^T where s_i = [cos(angle_i), sin(angle_i), x_i, y_i].

Returns

array of shape (4, 4)

mean()

Return the hybrid mean for a consistent interface.

Returns

array of shape (4,)

from_distribution(distribution, n_particles) staticmethod

Create an SE2DiracDistribution by sampling from a given distribution.

Parameters

distribution : AbstractHypercylindricalDistribution Source distribution on SE(2) (bound_dim=1, lin_dim=2) to sample from. n_particles : int Number of particles (Dirac components).

Returns

SE2DiracDistribution

SE3CartProdStackedDistribution

Bases: CartProdStackedDistribution, AbstractSE3Distribution

__init__(dists)

marginalize_linear()

marginalize_periodic()

get_manifold_size()

pdf(xs)

SE3DiracDistribution

Bases: LinHypersphereCartProdDiracDistribution, AbstractSE3Distribution

__init__(d, w=None)

marginalize_linear()

mean()

Convenient access to hybrid_mean() to have a consistent interface throughout manifolds.

Returns:

Type Description

The mean of the distribution.

from_distribution(distribution, n_particles) staticmethod

SO3BinghamDistribution

Bases: HyperhemisphericalBinghamDistribution

Bingham distribution over rotations represented by unit quaternions.

The distribution uses scalar-last quaternion coordinates (x, y, z, w). Because q and -q encode the same rotation, this class models SO(3) through the upper quaternion hemisphere and evaluates twice the full antipodally symmetric S^3 Bingham density.

geodesic_distance = staticmethod(geodesic_distance) class-attribute instance-attribute

__init__(Z, M)

calculate_normalization_constant(Z) staticmethod

Return the 4-D Bingham normalizing constant.

from_mode_and_concentration(mode, concentration) classmethod

Create an isotropic Bingham distribution around mode.

from_concentration_matrix(concentration_matrix) classmethod

Create from a symmetric 4-by-4 exponent matrix.

from_bingham_distribution(distribution) classmethod

Create from a 4-D hyperspherical Bingham distribution.

pdf(xs)

Evaluate the SO(3) density at scalar-last quaternions.

ln_pdf(xs)

Evaluate the natural logarithm of the SO(3) density.

mode()

Return the modal rotation as a canonical scalar-last quaternion.

mean()

Return the principal quaternion axis as the SO(3) mean proxy.

mean_axis()

Return the principal axis as a canonical scalar-last quaternion.

concentration_matrix()

Return the symmetric 4-by-4 exponent matrix.

moment_weights()

Return normalized Bingham moment weights without backend mutation.

moment()

Return the quaternion scatter matrix.

multiply(B2)

Multiply two SO(3) Bingham densities.

compose(B2)

Approximate the distribution of the composed rotation self * other.

sample(n)

Draw n canonical scalar-last unit quaternion samples.

as_rotation_matrices(quaternions) staticmethod

Convert scalar-last quaternions to rotation matrices.

mean_rotation_matrix()

Return the modal/principal rotation matrix.

is_valid(tolerance=1e-06)

Return whether the parameters define a valid SO(3) Bingham model.

SO3DiracDistribution

Bases: HyperhemisphericalDiracDistribution

Weighted Dirac distribution on SO(3).

The distribution stores rotations as unit quaternions with scalar-last coordinates (x, y, z, w). Since q and -q represent the same rotation, quaternions are canonicalized to a nonnegative scalar component during construction.

geodesic_distance = staticmethod(geodesic_distance) class-attribute instance-attribute

__init__(d, w=None)

from_rotation_matrices(rotation_matrices, w=None) classmethod

Create an SO(3) Dirac distribution from rotation matrices.

as_quaternions()

Return canonical scalar-last unit quaternions shaped (n, 4).

as_rotation_matrices()

Return Dirac locations as rotation matrices shaped (n, 3, 3).

mean_rotation_matrix()

Return the mean rotation as a 3-by-3 rotation matrix.

chordal_distance(rotation_a, rotation_b) staticmethod

Return the SO(3) Frobenius chordal distance between quaternions.

distance_to(rotation)

Return geodesic distances from all Dirac locations to rotation.

chordal_distance_to(rotation)

Return chordal distances from all Dirac locations to rotation.

from_distribution(distribution, n_particles=None) classmethod

Create an SO(3) Dirac distribution by sampling another distribution.

angular_error_mean(rotation)

Return the weighted mean angular error to rotation in radians.

chordal_error_mean(rotation)

Return the weighted mean chordal error to rotation.

is_valid(tolerance=1e-06)

Return whether all stored quaternions are normalized and canonical.

SO3ProductDiracDistribution

Bases: HyperhemisphereCartProdDiracDistribution

Weighted Dirac distribution on SO(3)^K.

Rotations are represented as scalar-last unit quaternions (x, y, z, w). The constructor also accepts flattened particles of shape (n, 4 * K). Internally, particles are stored as (n, K, 4) and canonicalized to the upper quaternion hemisphere.

num_rotations = inferred_num_rotations instance-attribute

__init__(d, w=None, num_rotations=None)

get_manifold_size()

from_rotation_matrices(rotation_matrices, w=None) classmethod

Create an SO(3)^K Dirac distribution from rotation matrices.

as_quaternions()

Return Dirac locations with shape (n, K, 4).

as_flat_quaternions()

Return Dirac locations with shape (n, 4 * K).

sample(n)

marginalize_rotation(rotation_index)

Return the single SO(3) marginal at rotation_index.

marginalize_rotations(rotation_indices)

Return the SO(3)^L marginal selected by rotation_indices.

moment(rotation_index=None)

Return weighted quaternion second moments.

With rotation_index=None, the result has shape (K, 4, 4). Otherwise it returns the (4, 4) moment of one SO(3) component.

mean_quaternion(rotation_index=None)

Return the weighted chordal quaternion mean.

mean()

Return the weighted chordal quaternion mean for each component.

geodesic_distance(rotation_a, rotation_b) staticmethod

Return SO(3) geodesic distances between scalar-last quaternions.

distance_to(rotations, reduce=True)

Return component-wise or summed geodesic distances to rotations.

angular_error_mean(rotations)

Return the weighted mean summed geodesic distance to rotations.

as_rotation_matrices(quaternions) staticmethod

Convert scalar-last unit quaternions to rotation matrices.

mean_rotation_matrices()

Return rotation matrices of the component-wise quaternion means.

is_valid(tolerance=1e-06)

SO3ProductTangentGaussianDistribution

Bases: AbstractBoundedDomainDistribution

Gaussian distribution in a tangent chart of SO(3)^K.

Rotations are represented as scalar-last unit quaternions (x, y, z, w). The mean is stored as a product point with shape (K, 4) and covariance is a full matrix on the flattened tangent vector in R^(3K).

num_rotations = inferred_num_rotations instance-attribute

mu = mean instance-attribute

C = C instance-attribute

input_dim property

__init__(mu, C, num_rotations=None, check_validity=True)

get_manifold_size()

exp_map(tangent_vectors, base=None, num_rotations=None) staticmethod

Map flattened tangent vectors to SO(3)^K product quaternions.

log_map(rotations, base=None, num_rotations=None) staticmethod

Map SO(3)^K product quaternions to flattened tangent vectors.

geodesic_distance(rotation_a, rotation_b, reduce=True, num_rotations=None) staticmethod

Return component-wise or summed SO(3)^K geodesic distances.

as_rotation_matrices(quaternions) staticmethod

Convert scalar-last quaternions to rotation matrices.

pdf(xs)

Evaluate the tangent Gaussian density at SO(3)^K rotations.

ln_pdf(xs)

Evaluate the natural logarithm of the tangent Gaussian density.

tangent_vectors(rotations)

Return flattened log-map coordinates around the distribution mean.

tangent_vectors_product(rotations)

Return log-map coordinates with shape (n, K, 3).

sample_tangent(n)

Draw tangent-space Gaussian samples with shape (n, 3 * K).

sample(n)

Draw n SO(3)^K samples as scalar-last unit quaternions.

mean()

Return the mean product rotation with shape (K, 4).

mode()

Return the modal product rotation with shape (K, 4).

mean_rotation_matrices()

Return rotation matrices of the mean product rotation.

covariance()

Return the full (3K, 3K) tangent covariance matrix.

set_mean(new_mean)

Return a copy with a replaced mean product rotation.

set_mode(new_mode)

Return a copy with a replaced modal product rotation.

marginalize_rotation(rotation_index)

Return the one-component SO(3) tangent Gaussian marginal.

marginalize_rotations(rotation_indices)

Return the marginal over selected SO(3) components.

distance_to(rotations, reduce=True)

Return geodesic distances from the mean to rotations.

is_valid(tolerance=1e-06)

Return whether the mean and covariance have valid SO(3)^K dimensions.

from_covariance_diagonal(mu, covariance_diagonal) staticmethod

Create a product tangent Gaussian from a diagonal covariance vector.

SO3TangentGaussianDistribution

Bases: AbstractBoundedDomainDistribution

Gaussian distribution in a local tangent chart of SO(3).

Rotations are represented as scalar-last unit quaternions (x, y, z, w). The density is evaluated by mapping rotations into the tangent space at the mean via log(mean^{-1} * rotation) and applying a 3-D Gaussian there. This is a local tangent approximation, not a globally wrapped density.

mu = self._normalize_quaternions(mu)[0] instance-attribute

C = C instance-attribute

input_dim property

geodesic_distance = staticmethod(geodesic_distance) class-attribute instance-attribute

__init__(mu, C, check_validity=True)

exp_map(tangent_vectors, base=None) staticmethod

Map tangent vectors to SO(3) quaternions.

If base is given, the returned rotations are base * Exp(v).

log_map(rotations, base=None) staticmethod

Map SO(3) quaternions to tangent vectors.

If base is given, this returns Log(base^{-1} * rotations).

as_rotation_matrices(quaternions) staticmethod

Convert scalar-last quaternions to rotation matrices.

pdf(xs)

Evaluate the tangent Gaussian density at SO(3) quaternions.

ln_pdf(xs)

Evaluate the natural logarithm of the tangent Gaussian density.

tangent_vectors(rotations)

Return log-map coordinates of rotations around the distribution mean.

sample_tangent(n)

Draw tangent-space Gaussian samples with shape (n, 3).

sample(n)

Draw n SO(3) samples as scalar-last unit quaternions.

mean()

Return the mean rotation as a scalar-last unit quaternion.

mode()

Return the modal rotation as a scalar-last unit quaternion.

mean_rotation_matrix()

Return the mean rotation matrix.

covariance()

Return the 3-by-3 tangent covariance matrix.

set_mean(new_mean)

Return a copy with a replaced mean rotation.

set_mode(new_mode)

Return a copy with a replaced modal rotation.

get_manifold_size()

Return the embedding half-sphere volume used for unit quaternions.

is_valid(tolerance=1e-06)

Return whether the mean and covariance have valid SO(3) dimensions.

from_covariance_diagonal(mu, covariance_diagonal) staticmethod

Create a tangent Gaussian from a diagonal covariance vector.

SO3UniformDistribution

Bases: HyperhemisphericalUniformDistribution

Uniform distribution on SO(3) using scalar-last unit quaternions.

The distribution represents rotations by canonical unit quaternions (x, y, z, w) with nonnegative scalar component. This identifies each SO(3) rotation with one point on the upper hemisphere of S^3, except for the measure-zero equator where q and -q both have zero scalar part.

geodesic_distance = staticmethod(geodesic_distance) class-attribute instance-attribute

as_rotation_matrices = staticmethod(quaternions_to_rotation_matrices) class-attribute instance-attribute

__init__()

pdf(xs)

Evaluate the constant SO(3) density.

ln_pdf(xs)

Evaluate the natural logarithm of the constant SO(3) density.

sample(n)

Draw n canonical scalar-last unit quaternions.

mode()

Mode is undefined for a uniform SO(3) distribution.

mean()

Mean rotation is undefined for a uniform SO(3) distribution.

mean_axis()

Mean axis is undefined for a uniform SO(3) distribution.

is_valid(tolerance=1e-12)

Return whether this instance has the expected SO(3) dimensions.

can_convert(distribution, target_type)

Return whether a conversion route exists.

This only checks for a route. It does not verify that all conversion arguments required by the route have been supplied.

convert_distribution(distribution, target_type, /, *, return_info=False, copy_if_same=False, **kwargs)

Convert or approximate distribution as target_type.

The gateway supports three cases, in order:

  1. identity conversion when distribution already is an instance of target_type;
  2. explicitly registered conversions;
  3. target classes exposing from_distribution(distribution, ...).

Parameters

distribution Source distribution instance. target_type Concrete target representation class, such as LinearDiracDistribution, CircularGridDistribution, or GaussianDistribution; or a conversion alias such as "particles", "gaussian", "grid", or "fourier". return_info If false, return the converted distribution directly. If true, return a :class:ConversionResult. copy_if_same If true, identity conversion returns a deep copy instead of the same object. **kwargs Parameters required by the target conversion.

Returns

object or ConversionResult Converted distribution, or metadata wrapper if return_info=True.

register_conversion(source_type, target_type, converter=None, *, exact=False, method=None)

Register a custom conversion between two representation classes.

Parameters

source_type Source type accepted by the converter. Subclasses are accepted. target_type Target type produced by the converter. Subclasses of this target may also use the registered conversion. converter Callable with signature converter(source, **kwargs). When omitted, this function acts as a decorator. exact Whether the conversion is exact. method Optional human-readable method name used in :class:ConversionResult.

Returns

Callable The original converter, enabling decorator use.

register_conversion_alias(alias, target_type_or_resolver, *, default_kwargs=None, description=None)

Register a string alias for a target representation.

Parameters

alias Alias accepted by :func:convert_distribution, for example "particles" or "gaussian". Aliases are case-insensitive; hyphens and spaces are normalized to underscores. target_type_or_resolver Concrete target class or callable resolver(source_distribution) returning a concrete target class. Resolvers make aliases domain-aware. default_kwargs Optional conversion arguments supplied by default. User-provided keyword arguments override these defaults. description Optional human-readable description used by :func:registered_conversion_aliases.

registered_conversion_aliases()

Return registered custom conversion aliases.

registered_conversions()

Return a compact snapshot of explicitly registered conversions.