otaf.sampling package

Module contents

Tools for generating experimental designs, low-discrepancy sequences, and surface sampling.

class otaf.sampling.LagrangeConstraintSolver(dim, g, bounds, starting_points)[source]

Bases: object

Solve for the subspace where the constraint function equals zero.

Parameters:
  • dim (int) – Dimensionality of the space (number of variables).

  • g (callable) – Constraint function g(X) such that g(X) = 0.

  • bounds (list of tuple) – List of (min, max) bounds for each variable.

  • starting_points (ndarray) – Initial points for the optimization algorithm.

dim

Dimensionality of the space (number of variables).

Type:

int

g

Constraint function g(X) such that g(X) = 0.

Type:

callable

bounds

List of (min, max) bounds for each variable.

Type:

list of tuple

starting_points

Initial points for the optimization algorithm.

Type:

ndarray

objective_function(X)[source]

Calculate the objective value for the constraint minimization.

Parameters:

X (ndarray) – Current vector of variables.

Returns:

Absolute value of the constraint function evaluated at X.

Return type:

float

solve()[source]

Solve the optimization problem using the SLSQP method.

Finds the subspace satisfying g(X) = 0 subject to defined variable bounds.

Returns:

The result object of the optimization process.

Return type:

OptimizeResult

class otaf.sampling.UniformSurfaceSampler(dim, g, bounds, starting_points, step_size=0.1)[source]

Bases: object

Generate a uniform distribution of points on a surface where g(X) = 0.

Parameters:
  • dim (int) – Dimensionality of the space.

  • g (callable) – Constraint function g(X) such that g(X) = 0.

  • bounds (list of tuple) – List of (min, max) bounds for each variable.

  • starting_points (ndarray) – Initial points already satisfying the constraint.

  • step_size (float, optional) – Step size for generating new points on the surface. Default is 0.1.

dim

Dimensionality of the space.

Type:

int

g

Constraint function g(X) such that g(X) = 0.

Type:

callable

bounds

List of (min, max) bounds for each variable.

Type:

list of tuple

starting_points

Initial points already satisfying the constraint.

Type:

ndarray

step_size

Magnitude of the random step taken during sampling.

Type:

float

objective_function(X)[source]

Calculate the absolute value of the constraint function g(X).

Parameters:

X (ndarray) – Current vector of variables.

Returns:

The absolute constraint violation.

Return type:

float

sample_surface(num_samples)[source]

Generate a uniform distribution of points on the surface.

Parameters:

num_samples (int) – The number of points to generate.

Returns:

Array of points satisfying g(X) = 0.

Return type:

ndarray

solve(x0)[source]

Project an arbitrary point onto the surface g(X) = 0.

Uses the SLSQP method to find the nearest point satisfying the constraint.

Parameters:

x0 (ndarray) – Initial guess point for optimization.

Returns:

The projected point on the surface, or None if optimization failed.

Return type:

ndarray or None

otaf.sampling.calculate_sample_in_deviation_domain(pos_u, theta, lambda_pos, lambda_theta)[source]

Scale and stack position and theta arrays into a 2D coordinate array.

Applies independent scaling factors to both the positional and angular input vectors, then reshapes them into a paired (N, 2) array.

Parameters:
  • pos_u (array_like) – An array or sequence of raw positional coordinates.

  • theta (array_like) – An array or sequence of raw angular coordinates.

  • lambda_pos (float) – The scalar multiplier applied to scale the position data.

  • lambda_theta (float) – The scalar multiplier applied to scale the theta data.

Returns:

An (N, 2) NumPy array where each row represents a paired (scaled_pos, scaled_theta) coordinate.

Return type:

array_like

otaf.sampling.compose_defects_with_lambdas(lds, rdv)[source]

Calculate scaled defect samples by multiplying with lambda values.

For each point in the lambda sample, compute a new defect sample by performing an element-wise multiplication with the input defect sample.

Parameters:
  • lds (ot.Sample) – Lambda sample of size Nl.

  • rdv (ot.Sample) – Random defects sample of size Nd.

Returns:

A list of size Nl, where each element contains the scaled defect sample of size Nd.

Return type:

list[ot.Sample]

Raises:

AssertionError – If the dimensions of the lambda sample and defect sample do not match.

otaf.sampling.condition_lambda_sample(sample, squared_sum=False)[source]

Condition lambda parameters to sum to 1 for each feature group.

This function extracts feature indices from the descriptions of the sample, normalizes the array representation using those indices, and returns a new sample. Note that if squared_sum is True, an element-wise square root transformation is applied.

Parameters:
  • sample (ot.Sample) – Lambda parameters with each feature description ending in an integer sequence.

  • squared_sum (bool, optional) – Whether to apply a square root transform to the normalized values. Default is False.

Returns:

The conditioned lambda parameters sample sharing the original descriptions.

Return type:

ot.Sample

Notes

This function can only be used if all the features are planar. If they are cylindrical, the constraints are absolutely different. To support both types, a more complex function is required to inspect the structural type of each feature and apply the corresponding mathematical constraint.

otaf.sampling.condition_sample_array(sample_array, feature_indices, squared_sum)[source]

Condition a sample array by normalizing specified feature slices.

This function normalizes columns of an array grouped by identical feature identifiers, dividing each slice by the sum of all matching features. If requested, a square root transform is applied to the final result.

Parameters:
  • sample_array (ndarray) – The input data array containing features along its last axis.

  • feature_indices (list of int) – An ordered list of IDs mapping each column to its parent feature.

  • squared_sum (bool) – If True, applies an element-wise square root transformation to the normalized array.

Returns:

The normalized (and optionally square-rooted) conditioned sample array.

Return type:

ndarray

Raises:

Exception – If the dimension alignment fails or division by zero occurs during normalization.

otaf.sampling.find_best_worst_quantile(parameters, results, quantile)[source]

Find best and worst observations based on a given quantile.

This function calculates the best and worst performing observations from a given set of parameters and corresponding results, based on the specified quantile.

Parameters:
  • parameters (ndarray) – Array containing parameter values.

  • results (ndarray) – Array containing corresponding result values.

  • quantile (float) – Desired quantile value, must be in the range [0, 1].

Returns:

best, worst – A tuple containing two subsets: - best: Tuple of (best_params, best_res) up to the quantile. - worst: Tuple of (worst_params, worst_res) down to the quantile.

Return type:

tuple of tuple

otaf.sampling.generate_and_transform_sequence(dim, samplesize, target_distribution, sequence_type='halton')[source]

Generate a low-discrepancy sequence and transform it to target.

Map a low-discrepancy sequence from the unit hypercube to the target distribution space using iso-probabilistic transformations.

Parameters:
  • dim (int) – Number of dimensions.

  • samplesize (int) – Number of samples to generate.

  • target_distribution (ot.Distribution) – The target OpenTURNS distribution to transform the sequence into.

  • sequence_type (str, optional) – Type of low-discrepancy sequence. Choices are "sobol", "halton", "reverse_halton", "faure", or "haselgrove". Default is “halton”.

Returns:

Transformed sample points in the target distribution space.

Return type:

ndarray

Raises:

ValueError – If an unsupported sequence_type is provided.

otaf.sampling.generate_imprecise_probabilistic_samples(subgroup_sizes, num_samples=None, seed=None, discretization=4)[source]

Generate permutations for imprecise probabilistic models.

Each subgroup in subgroup_sizes represents a set of variables contributing to a probabilistic model, where the sum of elements within each subgroup is constrained to 1. This function samples random permutations from this constrained space.

Parameters:
  • subgroup_sizes (list of int) – List where each entry corresponds to the size of a subgroup (number of variables).

  • num_samples (int, optional) – Number of random samples to generate. If -1, all valid permutations are computed. The default is -1.

  • seed (int, optional) – Seed for the random number generator to ensure reproducibility.

  • discretization (int, optional) – Number of steps to discretize the space between [0, 1]. Finer granularity is provided by higher values. The default is 4.

Yields:

np.ndarray – A valid sample of probabilistic contributions. Each sample is a 1D array where the sum of elements in each subgroup is 1.

Return type:

Generator[ndarray, None, None]

Notes

The generator produces samples lazily to reduce memory consumption. If num_samples is -1, the function generates all possible permutations lazily. The discretization parameter controls the precision of the [0, 1] interval; higher values increase precision but may significantly increase computation time.

Examples

>>> subgroup_sizes = [3, 4]
>>> samples = generate_imprecise_probabilistic_samples(
...     subgroup_sizes, num_samples=5, seed=42
... )
>>> for sample in samples:
...     print(sample)
otaf.sampling.generate_lhs_experiment(composed_distribution, N, SEED=999, T0=10.0, c=0.95, iMax=2000)[source]

Generate an optimal Latin Hypercube Sample (LHS) design.

Construct a space-filling design using the Simulated Annealing algorithm to minimize the C2 criterion, ensuring a high-quality distribution of samples within the input space.

Parameters:
  • composed_distribution (JointDistribution) – The probability distribution from which to draw samples.

  • N (int) – The number of samples to generate in the design.

  • SEED (int, optional) – Seed for the random number generator. Default is 999.

  • T0 (float, optional) – Initial temperature for the simulated annealing process. Default is 10.0.

  • c (float, optional) – Geometric cooling factor for the simulated annealing process. Default is 0.95.

  • iMax (int, optional) – Maximum number of iterations for the optimization. Default is 2000.

Returns:

The optimized Latin Hypercube Sample design.

Return type:

ot.Sample

otaf.sampling.generate_random_permutations_with_sampling(subgroup_sizes, num_samples=None, seed=None)[source]

Generate a random subset of signed permutations for configurations.

Create a random subset of valid permutations for concatenated one-hot encoded subgroups, where each non-zero element is randomly assigned a +1 or -1 sign to mitigate the curse of dimensionality.

Parameters:
  • subgroup_sizes (list of int) – List where each entry is the size of a subgroup (number of one-hot vectors).

  • num_samples (int, optional) – Number of permutations to generate. If None or exceeding the total number of possible permutations, all possible permutations are generated.

  • seed (int, optional) – Seed for the random number generator to ensure reproducibility.

Returns:

A 2D array where each row is a generated permutation, including randomized sign flips.

Return type:

ndarray

Notes

This function addresses the curse of dimensionality by limiting permutations to num_samples.

If num_samples exceeds total possible permutations, all unique combinations are returned.

Each subgroup is constrained to exactly one non-zero element per sample.

otaf.sampling.generate_scaled_permutations(subgroup_sizes, scaling_factors, num_samples=None, seed=None)[source]

Generate scaled random permutations with sign flips.

Create a set of random permutations for concatenated one-hot encoded subgroups, applying random sign flips (+1 or -1) and scaling each element by the provided factors.

Parameters:
  • subgroup_sizes (list of int) – Size of each subgroup, representing the number of possible one-hot vectors.

  • scaling_factors (array_like) – Scaling factors for each element in the permutation vector. Must match the total sum of subgroup_sizes.

  • num_samples (int, optional) – Number of permutations to generate. If None or exceeding the total possible combinations, all combinations are generated.

  • seed (int, optional) – Random seed for reproducibility.

Returns:

A 2D array where each row is a generated permutation, scaled and sign-flipped according to the logic defined in the underlying sampling.

Return type:

ndarray

Raises:

ValueError – If the length of scaling_factors does not match the sum of subgroup_sizes.

otaf.sampling.project_samples_to_hyperplane(a, b, samples, bounds=None)[source]

Project (N-1)-dimensional samples onto an N-dimensional hyperplane.

Parameters:
  • a (array_like) – Coefficients of the hyperplane linear equation.

  • b (float) – Constant term in the hyperplane linear equation.

  • samples (ndarray) – Samples in (N-1)-dimensional space with shape (M, N-1).

  • bounds (list of tuple, optional) – Bounds for each dimension in the format [(min, max), …]. Only samples whose projections fall within these bounds are returned.

Returns:

Projected samples in N-dimensional space that satisfy the hyperplane equation.

Return type:

ndarray

Notes

The function solves the hyperplane equation to calculate the dependent coordinate x0 before reconstructing the full vector:

\[a_0 x_0 + a_1 x_1 + \dots + a_{N-1} x_{N-1} = b\]
otaf.sampling.scale_sample_with_params(sample, parameters)[source]

Scale a sample using mean and variance parameters.

Transform each column of the input sample, assuming it originates from a standard normal unit distribution, by applying the provided mean and standard deviation values.

Parameters:
  • sample (np.ndarray) – A 2D array of shape (N, M), where each column represents a random vector component from a standard normal distribution.

  • parameters (array_like) – A 1D array or sequence of size 2 * M, where elements alternate between mean and standard deviation (mu_0, sigma_0, mu_1, sigma_1, ...).

Returns:

A 2D array of shape (N, M), with each column scaled using the parameters.

Return type:

np.ndarray

Raises:

ValueError – If sample is not a 2D array, if the size of parameters does not equal 2 * M, or if any standard deviation is negative.

otaf.sampling.validate_and_extract_indices(description)[source]

Validate the feature descriptions and extract feature indices.

Parameters:

description (list of str) – List of feature descriptions where each element represents a symbol or feature name.

Returns:

Extracted feature indices parsed from the trailing characters of the descriptions.

Return type:

list of int

Raises:

ValueError – If the description is empty or if any individual feature name fails to end with an integer suffix.