examples.shooting package

Submodules

examples.shooting.Shooting1DPBS module

examples.shooting.shooting_1D module

class examples.shooting.shooting_1D.ProcessShooting1D[source]

Bases: object

Example driver for a 1D shooting problem using the MLMC framework.

This tutorial class demonstrates how to:
  • create a Sampler with storage and sampling pool,

  • schedule and collect MLMC samples,

  • estimate moments and build an approximate probability density function of the quantity of interest.

The constructor runs a full example MLMC workflow when the module is executed.

create_sampler(level_parameters)[source]

Create the Sampler with storage and sampling pool and return it.

Components created:
  • sampling_pool: OneProcessPool (runs all samples in the same process)

  • simulation_factory: instance of ShootingSimulation1D

  • sample_storage: Memory() (in-memory storage)

  • sampler: mlmc.sampler.Sampler

Parameters:

level_parameters – List of level parameter lists (simulation-dependent).

Returns:

mlmc.sampler.Sampler instance configured for this example.

generate_samples(sampler, n_samples=None, target_var=None)[source]

Schedule and generate MLMC samples, optionally targetting a global variance.

Parameters:
  • sampler – mlmc.sampler.Sampler instance controlling sampling.

  • n_samples – None or list of exact sample counts per level.

  • target_var – Target variance for MLMC estimator (if not None).

Returns:

None (results are stored in sampler.sample_storage).

set_moments(quantity, sample_storage, n_moments=25)[source]

Create a Legendre-moments function object for the given quantity.

Parameters:
  • quantity – mlmc.quantity.quantity.Quantity instance (root quantity).

  • sample_storage – sample storage instance to estimate domain from samples.

  • n_moments – Number of moments (basis size) to construct.

Returns:

Legendre(n_moments, domain) instance to be used for moment estimation.

all_collect(sampler)[source]

Wait until all scheduled samples finish by repeatedly collecting finished samples.

Parameters:

sampler – mlmc.sampler.Sampler instance.

Returns:

None

process_results(sampler, n_levels)[source]

Postprocess completed samples: estimate moments and approximate distribution.

Steps:
  • Load result format and build Quantity objects

  • Choose a target item inside the quantity and check its mean

  • Compute estimated domain, construct moment functions (Legendre)

  • Estimate moments and their variances, compute distribution approximation

Parameters:
  • sampler – mlmc.sampler.Sampler instance containing sample_storage.

  • n_levels – int, number of MLMC levels used in the run.

Returns:

None

approx_distribution(estimator, n_levels, tol=1.95)[source]

Construct and display an approximate probability density function for the quantity.

Parameters:
  • estimator – mlmc.estimator.Estimate instance which contains the quantity and methods for constructing the density approximation.

  • n_levels – int, number of MLMC levels (used for optional plotting of raw samples).

  • tol – Tolerance parameter for the density fitting problem (default 1.95).

Returns:

None

static determine_level_parameters(n_levels, step_range)[source]

Determine level parameters for MLMC from the coarsest and finest step sizes.

The default strategy interpolates in log-space between step_range[0] and step_range[1] across n_levels and returns a list of single-entry lists containing the step for each level.

Parameters:
  • n_levels – int number of MLMC levels.

  • step_range – Sequence [coarse_step, fine_step] where coarse_step > fine_step.

Returns:

list of lists where each inner list contains the parameter(s) for that level.

examples.shooting.shooting_2D module

class examples.shooting.shooting_2D.ProcessShooting2D[source]

Bases: object

Example driver for a 2D shooting simulation using the MLMC framework.

Demonstrates:
  • building sampler, sampling pool and sample storage,

  • scheduling and collecting MLMC samples,

  • estimating moments and approximating probability densities for quantities of interest.

create_estimator(quantity, sample_storage)[source]

Create an Estimate object for a given quantity and storage using Legendre moments.

Parameters:
  • quantity – Quantity object (mlmc.quantity.quantity.Quantity item) to estimate.

  • sample_storage – sample storage instance used to estimate domain.

Returns:

mlmc.estimator.Estimate instance configured for the quantity.

process_results(sampler, n_levels)[source]

Postprocess completed MLMC samples: form quantities, create estimators and approximate distributions.

Steps performed:
  • load result format and create root Quantity,

  • extract x and y components of the target item,

  • build per-component estimators,

  • compute root-level moments and means,

  • approximate and display distributions for x and y.

Parameters:
  • sampler – mlmc.sampler.Sampler instance containing completed samples.

  • n_levels – int, number of MLMC levels used.

Returns:

None

approx_distribution(estimator, n_levels, tol=1.95)[source]

Approximate and display the probability density function for the estimator’s quantity.

Parameters:
  • estimator – mlmc.estimator.Estimate instance providing construct_density().

  • n_levels – int, number of MLMC levels (used to optionally overlay raw samples).

  • tol – float, tolerance for density-fitting routine (affects regularization with moment variances).

Returns:

None

create_sampler(level_parameters)[source]

Create sampler, sampling pool and simulation factory for the 2D shooting example.

Parameters:

level_parameters – list of per-level parameter lists.

Returns:

mlmc.sampler.Sampler instance configured with Memory storage and OneProcessPool.

generate_samples(sampler, n_samples=None, target_var=None)[source]

Schedule and generate MLMC samples. If target_var is provided, iteratively determine additional samples required to reach the variance target.

Parameters:
  • sampler – mlmc.sampler.Sampler instance controlling the run.

  • n_samples – Optional list of exact sample counts per level.

  • target_var – Optional float target variance for MLMC estimator.

Returns:

None

all_collect(sampler)[source]

Repeatedly poll the sampling pool and collect finished samples until none remain running.

Parameters:

sampler – mlmc.sampler.Sampler instance.

Returns:

None

set_moments(quantity, sample_storage, n_moments=25)[source]

Build Legendre moments object for a given quantity using the domain estimated from samples.

Parameters:
  • quantity – quantity object (used to estimate domain).

  • sample_storage – storage used to compute the domain estimate.

  • n_moments – number of Legendre polynomials to use.

Returns:

Legendre instance configured for the estimated domain.

static determine_level_parameters(n_levels, step_range)[source]

Determine level parameters for MLMC.

For this example a single per-level ‘step’ is returned in a list, interpolating (geometrically) between step_range[0] and step_range[1].

Parameters:
  • n_levels – int number of MLMC levels.

  • step_range – [coarse_step, fine_step] with coarse_step > fine_step.

Returns:

List[List[float]]: per-level parameters (each inner list contains the step value).

examples.shooting.simulation_shooting_1D module

examples.shooting.simulation_shooting_1D.create_corr_field(model='gauss', corr_length=0.1, dim=1, log=True, sigma=1, mode_no=1000)[source]

Create a correlated random field wrapper used by the simulations.

Parameters:
  • model – str, covariance model name. Supported values: ‘gauss’ (default), ‘exp’, ‘TPLgauss’, ‘TPLexp’, ‘TPLStable’.

  • corr_length – float, correlation length (len_scale) for the covariance model.

  • dim – int, spatial dimension of the covariance model.

  • log – bool, whether the generated random field is treated as log-field.

  • sigma – float, standard deviation (sigma) for the random field.

  • mode_no – int, number of Fourier modes (used by GSTools SRF).

Returns:

cf.Field instance that wraps a GSToolsSpatialCorrelatedField configured with the selected covariance model.

class examples.shooting.simulation_shooting_1D.ShootingSimulation1D(config)[source]

Bases: Simulation

Simple 1D “shooting” simulation used as example for MLMC workflow.

The class implements:
  • level_instance(…) to create LevelSimulation configurations,

  • calculate(…) static method to produce paired (fine, coarse) samples,

  • result_format() describing the output QuantitySpec.

level_instance(fine_level_params, coarse_level_params)[source]

Create a LevelSimulation object for given fine and coarse level parameters.

This constructs the simulation configuration for one MLMC level (fine/coarse pair) and returns a LevelSimulation that knows which calculate() function to call.

Parameters:
  • fine_level_params (List[float]) – List[float], typically a single-element list containing the fine step size.

  • coarse_level_params (List[float]) – List[float], typically a single-element list containing the coarse step size.

Return type:

LevelSimulation

Returns:

LevelSimulation configured with the derived config dictionary and task size.

static calculate(config, seed)[source]

Build random field and produce a paired (fine, coarse) simulation result.

This is the static worker function used by LevelSimulation to generate one sample pair. It creates the correlated random field, samples it on the fine+coarse point set and runs the deterministic integrator for fine and coarse input arrays.

Parameters:
  • config – dict, level-specific configuration produced by level_instance(). It must include ‘fields_params’, and ‘fine’/’coarse’ with ‘n_elements’ and ‘step’ keys, plus other simulation settings.

  • seed – int, RNG seed passed by sampler (currently unused inside; RNG is handled by field implementation).

Returns:

tuple (fine_result, coarse_result), each is a scalar float (y coordinate at final time or NaN).

static create_points(config)[source]

Create concatenated evaluation points for the random field for fine and coarse parts.

Points are returned as an (n_fine + n_coarse, 1) array where each row is a coordinate at which the GSTools SRF will be evaluated. The first n_fine rows correspond to the fine mesh, the remaining rows (if any) to the coarse mesh.

Parameters:

config – dict, level configuration that contains ‘fine’ and ‘coarse’ sub-dicts with ‘n_elements’ integer entries and other simulation parameters.

Returns:

tuple (points, n_fine_elements) - points: np.ndarray shape (n_fine + n_coarse, 1) - n_fine_elements: int number of fine elements (split index)

static generate_random_sample(field, coarse_step, n_fine_elements)[source]

Sample a realization from the provided correlated field and split it into fine and coarse parts.

Parameters:
  • field – cf.Field instance created by create_corr_field(…) and already set_points() called.

  • coarse_step – float, coarse level step (if 0 then no coarse part is returned).

  • n_fine_elements – int, number of entries that belong to the fine-level part (split index).

Returns:

tuple (fine_input_sample, coarse_input_sample) - fine_input_sample: np.ndarray shape (n_fine_elements,) - coarse_input_sample: np.ndarray shape (n_coarse_elements,) or [] if coarse_step == 0

n_ops_estimate(step)[source]

Estimate computational cost (# of operations) for a sample at a given step size.

Parameters:

step – float, simulation step size for the fine level

Returns:

float, heuristic estimate of cost used by MLMC to balance work across levels

result_format()[source]

Describe the output format of the simulation for MLMC.

Return type:

List[QuantitySpec]

Returns:

List[QuantitySpec] describing the result vector(s). Here we return a single scalar quantity ‘target’ representing y-position at final time.

examples.shooting.simulation_shooting_2D module

examples.shooting.simulation_shooting_2D.create_corr_field(model='gauss', corr_length=0.1, dim=1, log=True, sigma=1, mode_no=1000)[source]

Create a correlated random field wrapper (GSTools model -> mlmc.random.correlated_field.Field).

Parameters:
  • model – str, covariance model name. Supported strings: ‘gauss’ (default), ‘exp’, ‘TPLgauss’, ‘TPLexp’, ‘TPLStable’.

  • corr_length – float, correlation length (len_scale) supplied to the GSTools model.

  • dim – int, spatial dimension of the covariance model.

  • log – bool, if True the field will be considered in log-space when sampling.

  • sigma – float, multiplicative sigma parameter for the SRF generator.

  • mode_no – int, number of Fourier modes used by GSTools SRF.

Returns:

cf.Field — an mlmc.random.correlated_field.Field wrapping a GSTools SRF.

class examples.shooting.simulation_shooting_2D.ShootingSimulation2D(config)[source]

Bases: Simulation

Example 2D shooting simulation used with MLMC sampler.

Implements:
  • level_instance(…) to create per-level LevelSimulation config,

  • calculate(…) static method used to produce a (fine, coarse) sample pair,

  • result_format() describing output QuantitySpec.

level_instance(fine_level_params, coarse_level_params)[source]

Construct LevelSimulation for given fine/coarse parameters.

This method mutates a copy of self.config into a level-specific config and returns a LevelSimulation that will call ShootingSimulation2D.calculate to generate samples for this level.

Parameters:
  • fine_level_params (List[float]) – list-like, typically [fine_step]

  • coarse_level_params (List[float]) – list-like, typically [coarse_step]

Return type:

LevelSimulation

Returns:

LevelSimulation configured for this level

static calculate(config, seed)[source]

Build correlated fields and produce paired fine/coarse simulation results.

This static function is intended to be executed by the LevelSimulation worker. It:

  • creates two independent correlated fields (x and y components),

  • sets evaluation points,

  • samples the fields and splits the realization into fine and coarse parts,

  • simulates the projectile dynamics for fine/coarse inputs.

Parameters:
  • config – dict, level-specific configuration produced by level_instance().

  • seed – int, RNG seed (currently not used directly; GSTools RNG is internal).

Returns:

tuple (fine_result, coarse_result) - fine_result: np.ndarray or scalar describing the fine-level output - coarse_result: np.ndarray or scalar describing the coarse-level output

static create_points(config)[source]

Build concatenated evaluation points for the correlated fields (fine first, then coarse).

The points are 1D coordinates used for the GSTools SRF evaluation; the first n_fine rows correspond to the fine mesh, the remainder to the coarse mesh.

Parameters:

config – dict with ‘fine’ and ‘coarse’ sub-dicts containing ‘n_elements’.

Returns:

tuple (points, n_fine_elements) - points: np.ndarray shape (n_fine + n_coarse, 1) - n_fine_elements: int number of fine-level points

static generate_random_sample(field_x, field_y, coarse_step, n_fine_elements)[source]

Sample two correlated fields (x and y components) and split the realization into fine and coarse parts.

Parameters:
  • field_x – cf.Field for x-component (already had set_points called).

  • field_y – cf.Field for y-component (already had set_points called).

  • coarse_step – float, coarse-level step size (if 0 there is no coarse part).

  • n_fine_elements – int, how many samples belong to the fine-level portion.

Returns:

tuple (fine_input_sample, coarse_input_sample) - fine_input_sample: np.ndarray shape (n_fine_elements, 2) with x and y forcing - coarse_input_sample: np.ndarray shape (n_coarse_elements, 2) or empty array if coarse_step==0

n_ops_estimate(step)[source]

Heuristic estimate of computational expense for a single fine-level sample.

Parameters:

step – float, fine-level step size.

Returns:

float, cost estimate used by MLMC scheduler.

result_format()[source]

Describe the result format (QuantitySpec) produced by calculate().

Return type:

List[QuantitySpec]

Returns:

list of QuantitySpec objects describing outputs. Here a single 2D target vector.

Module contents