mlmc.sim

Contains a parent simulation class and a specific synthetic simulation

Submodules

mlmc.sim.simulation module

class mlmc.sim.simulation.Simulation[source]

Bases: ABC

Abstract base class for multi-level Monte Carlo (MLMC) simulations.

Defines the interface that all concrete simulation classes must implement. Provides methods for creating level simulations, specifying result formats, and running calculations.

abstract level_instance(fine_level_params, coarse_level_params)[source]

Create a LevelSimulation object for a given level.

The LevelSimulation instance is used for sample generation and result extraction at both the fine and coarse levels in MLMC.

Parameters:
  • fine_level_params (List[float]) – List of floats defining parameters for the fine simulation level.

  • coarse_level_params (List[float]) – List of floats defining parameters for the coarse simulation level.

Return type:

LevelSimulation

Returns:

LevelSimulation instance configured for the given level parameters.

abstract result_format()[source]

Define the format of the simulation results.

This method should return a list of QuantitySpec objects, which describe the type, shape, and units of each quantity produced by the simulation.

Return type:

List[QuantitySpec]

Returns:

List of QuantitySpec objects defining the simulation output format.

abstract static calculate(config_dict, seed)[source]

Execute a single simulation calculation.

This method runs the simulation for both fine and coarse levels, computes the results, and returns them in a flattened form suitable for MLMC analysis.

Parameters:
  • config_dict – Dictionary containing simulation configuration parameters (usually LevelSimulation.config_dict from level_instance).

  • seed (int) – Random seed (int) to ensure reproducibility of the stochastic simulation.

Returns:

List containing two elements: [fine_result, coarse_result], both as flattened arrays.

mlmc.sim.synth_simulation module

class mlmc.sim.synth_simulation.SynthSimulation(config=None)[source]

Bases: Simulation

Artificial (synthetic) simulation used for testing and examples.

The simulation generates random samples from a specified distribution and optionally injects numerical error / NaN failures according to configuration. It implements the Simulation interface: provides level_instance, calculate, and result_format methods and a simple cost estimator n_ops_estimate.

n_nans = 0
nan_fraction = 0
len_results = 0
result_dict = {}
static sample_fn(x, h)[source]

Compute a (noisy) synthetic sample value for given distribution samples.

Parameters:
  • x – Distribution sample(s) (scalar or array-like).

  • h – Simulation step (resolution parameter). Typically small positive float.

Returns:

Computed sample(s). Introduces small h-dependent perturbation: x + h * sqrt(1e-4 + |x|). This can produce outliers for certain x.

static sample_fn_no_error(x, h)[source]

Compute a synthetic sample without introducing numerical error.

Parameters:
  • x – Distribution sample(s) (scalar or array-like).

  • h – Simulation step (ignored for this function).

Returns:

The input sample(s) unchanged (identity mapping).

level_instance(fine_level_params, coarse_level_params)[source]

Create a LevelSimulation configured for a pair of fine/coarse level parameters.

Parameters:
  • fine_level_params (List[float]) – List-like where the first element is the fine step size.

  • coarse_level_params (List[float]) – List-like where the first element is the coarse step size.

Return type:

LevelSimulation

Returns:

LevelSimulation instance initialized with: - config_dict containing ‘fine.step’, ‘coarse.step’, ‘distr’, and ‘res_format’ - task_size estimated by n_ops_estimate(…)

static generate_random_samples(distr, seed, size)[source]

Draw random samples from the provided scipy distribution reproducibly.

Parameters:
  • distr – scipy.stats distribution object (must support .rvs()).

  • seed – Integer seed used to construct a RandomState for reproducibility.

  • size – Number of samples to draw.

Returns:

Tuple (fine_samples, coarse_samples). For this synthetic sim both are identical. May return [np.nan] to simulate a failed sample according to nan_fraction.

static calculate(config, seed)[source]

Calculate fine and coarse samples and convert them to the expected result format.

Parameters:
  • config – Dictionary containing simulation configuration (must include ‘res_format’, ‘fine.step’ and ‘coarse.step’ keys).

  • seed – Integer RNG seed for reproducibility.

Returns:

Tuple (fine_flat, coarse_flat) where both are 1D numpy arrays produced by flattening the per-quantity/time/location arrays constructed below.

Raises:

Exception if any resulting sample contains NaN.

n_ops_estimate(step)[source]

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

Parameters:

step – Level step size (h).

Returns:

Estimated operation count (float). Uses configured complexity exponent.

result_format()[source]

Define the synthetic simulation’s result format.

Return type:

List[QuantitySpec]

Returns:

List[QuantitySpec] describing the shape, units, times and locations for each reported quantity. This informs how calculate arranges and flattens outputs.

class mlmc.sim.synth_simulation.SynthSimulationWorkspace(config)[source]

Bases: SynthSimulation

Synthetic simulation variant that requires a workspace (reads config from YAML).

This subclass behaves like SynthSimulation but:
  • Reads distribution and nan_fraction from a YAML configuration file.

  • Declares need_workspace = True so sample files are written to/read from disk.

  • Supplies common_files (the YAML) to LevelSimulation so workspaces get that file.

n_nans = 0
nan_fraction = 0
len_results = 0
result_dict = {}
CONFIG_FILE = 'synth_sim_config.yaml'
static sample_fn(x, h)[source]

Compute a (noisy) synthetic sample value for given distribution samples.

Parameters:
  • x – Distribution sample(s) (scalar or array-like).

  • h – Simulation step (resolution parameter).

Returns:

Computed sample(s): x + h * sqrt(1e-4 + |x|).

static sample_fn_no_error(x, h)[source]

Identity sampling function (no added numerical error).

Parameters:
  • x – Distribution sample(s).

  • h – Simulation step (ignored).

Returns:

x (unchanged).

level_instance(fine_level_params, coarse_level_params)[source]

Produce a LevelSimulation configured to use the YAML config as a common file.

Parameters:
  • fine_level_params (List[float]) – list-like where first element is fine step size.

  • coarse_level_params (List[float]) – list-like where first element is coarse step size.

Return type:

LevelSimulation

Returns:

LevelSimulation configured with: - config_dict: containing ‘fine.step’, ‘coarse.step’, ‘res_format’ - common_files: list containing the YAML path (so worker/workspace has it) - task_size: small constant (1/job_weight) to simulate job weighting - need_sample_workspace: True (this class requires workspace)

static generate_random_samples(distr, seed, size)[source]

Draw random samples based on YAML-specified distribution names.

This implementation currently supports only the string “norm” which maps to scipy.stats.norm(loc=1, scale=2). A NotImplementedError is raised for other distribution identifiers.

Parameters:
  • distr – Either a string identifier (e.g. “norm”) or a scipy distribution.

  • seed – Integer RNG seed used to create a RandomState for reproducibility.

  • size – Integer number of samples to draw.

Returns:

Tuple (fine_samples, coarse_samples) — identical arrays for this toy sim. May return [np.nan] to simulate a failed sample according to nan_fraction.

static calculate(config, seed)[source]

Calculate fine and coarse samples (using values from the YAML config file).

Workflow:
  1. Read YAML configuration (via _read_config) to get distribution and nan_fraction.

  2. Generate base random numbers (fine_random, coarse_random).

  3. Compute fine_result and coarse_result via sample functions.

  4. Assemble results into arrays shaped by res_format and flatten them.

Parameters:
  • config – LevelSimulation.config_dict (must include ‘res_format’, ‘fine.step’, ‘coarse.step’).

  • seed – Integer RNG seed.

Returns:

Tuple (fine_flat, coarse_flat) — 1D numpy arrays produced by flattening quantities × times × locations.

Raises:

Exception if any computed result contains NaN.

n_ops_estimate(step)[source]

Estimate a synthetic operation count for the workspace-enabled simulation. :type step: :param step: Level step size. :return: Estimated operation cost (float). Uses a fixed exponent of 2 here.

Module contents

Contains a parent simulation class and a specific synthetic simulation