From 37245cbbc2d8d76294e42974534903c1a33e0a59 Mon Sep 17 00:00:00 2001 From: zeptodoctor <44736852+zeptodoctor@users.noreply.github.com> Date: Thu, 14 Nov 2024 08:27:01 +0000 Subject: [PATCH] build based on 6048e91 --- dev/advanced_usage/index.html | 2 +- dev/api/index.html | 10 +- dev/comparison/index.html | 2 +- dev/examples/index.html | 656 +++++++++++++++------------------- dev/index.html | 2 +- dev/overloading/index.html | 2 +- dev/parabola.html | 4 +- dev/performance/index.html | 4 +- dev/search/index.html | 2 +- dev/sign.html | 4 +- dev/sin.html | 4 +- dev/sin_wide.html | 4 +- 12 files changed, 313 insertions(+), 383 deletions(-) diff --git a/dev/advanced_usage/index.html b/dev/advanced_usage/index.html index 278dca3..aed3594 100644 --- a/dev/advanced_usage/index.html +++ b/dev/advanced_usage/index.html @@ -1,2 +1,2 @@ -Advanced usage · MonteCarloMeasurements Documentation

Advanced usage

Several non-exported functions that may facilitate working with structures that contain uncertain parameters (struct-of-arrays, SoA) exist. These are not to be considered part of the API and are subject to breakage at any time, but may nevertheless be of use in special situations.

MonteCarloMeasurements.mean_objectFunction
mean_object(x)

Returns an object similar to x, but where all internal instances of Particles are replaced with their mean. The generalization of this function is replace_particles.

source
MonteCarloMeasurements.replace_particlesFunction
replace_particles(x; condition=P->P isa AbstractParticles,replacer = P->vecindex(P, 1))

This function recursively scans through the structure x, every time a field that matches condition is found, replacer is called on that field and the result is used instead of P. See function mean_object, which uses this function to replace all instances of Particles with their mean.

source
MonteCarloMeasurements.has_particlesFunction
has_particles(P)

Determine whether or no the object P has some kind of particles inside it. This function examins fields of P recursively and looks inside arrays etc.

source
MonteCarloMeasurements.array_of_structsFunction
array_of_structs(f, arg)

Exectues f on each instance of arg represented by internal particles of arg. This is useful as a last resort if all other methods to propagate particles through f fails. The function returns an array (length = num. particles) of structs rather than particles, each struct is the result of f(replace_particles(arg, p->p[i])).

source
+Advanced usage · MonteCarloMeasurements Documentation

Advanced usage

Several non-exported functions that may facilitate working with structures that contain uncertain parameters (struct-of-arrays, SoA) exist. These are not to be considered part of the API and are subject to breakage at any time, but may nevertheless be of use in special situations.

MonteCarloMeasurements.mean_objectFunction
mean_object(x)

Returns an object similar to x, but where all internal instances of Particles are replaced with their mean. The generalization of this function is replace_particles.

source
MonteCarloMeasurements.replace_particlesFunction
replace_particles(x; condition=P->P isa AbstractParticles,replacer = P->vecindex(P, 1))

This function recursively scans through the structure x, every time a field that matches condition is found, replacer is called on that field and the result is used instead of P. See function mean_object, which uses this function to replace all instances of Particles with their mean.

source
MonteCarloMeasurements.has_particlesFunction
has_particles(P)

Determine whether or no the object P has some kind of particles inside it. This function examins fields of P recursively and looks inside arrays etc.

source
MonteCarloMeasurements.array_of_structsFunction
array_of_structs(f, arg)

Exectues f on each instance of arg represented by internal particles of arg. This is useful as a last resort if all other methods to propagate particles through f fails. The function returns an array (length = num. particles) of structs rather than particles, each struct is the result of f(replace_particles(arg, p->p[i])).

source
diff --git a/dev/api/index.html b/dev/api/index.html index 819e230..c1ff238 100644 --- a/dev/api/index.html +++ b/dev/api/index.html @@ -1,5 +1,5 @@ -API · MonteCarloMeasurements Documentation

Exported functions and types

Index

MonteCarloMeasurements.MonteCarloMeasurementsModule

This package facilitates working with probability distributions by means of Monte-Carlo methods, in a way that allows for propagation of probability distributions through functions. This is useful for, e.g., nonlinear uncertainty propagation. A variable or parameter might be associated with uncertainty if it is measured or otherwise estimated from data. We provide two core types to represent probability distributions: Particles and StaticParticles, both <: Real. (The name "Particles" comes from the particle-filtering literature.) These types all form a Monte-Carlo approximation of the distribution of a floating point number, i.e., the distribution is represented by samples/particles. Correlated quantities are handled as well, see multivariate particles below.

A number of type Particles behaves just as any other Number while partaking in calculations. Particles also behave like a distribution, so after a calculation, an approximation to the complete distribution of the output is captured and represented by the output particles. mean, std etc. can be extracted from the particles using the corresponding functions pmean and pstd. Particles also interact with Distributions.jl, so that you can call, e.g., Normal(p) and get back a Normal type from distributions or fit(Gamma, p) to get a Gammadistribution. Particles can also be asked for maximum/minimum, quantile etc. using functions with a prefix p, i.e., pmaximum. If particles are plotted with plot(p), a histogram is displayed. This requires Plots.jl. A kernel-density estimate can be obtained by density(p) is StatsPlots.jl is loaded.

Quick start

julia> using MonteCarloMeasurements, Plots
+API · MonteCarloMeasurements Documentation

Exported functions and types

Index

MonteCarloMeasurements.MonteCarloMeasurementsModule

This package facilitates working with probability distributions by means of Monte-Carlo methods, in a way that allows for propagation of probability distributions through functions. This is useful for, e.g., nonlinear uncertainty propagation. A variable or parameter might be associated with uncertainty if it is measured or otherwise estimated from data. We provide two core types to represent probability distributions: Particles and StaticParticles, both <: Real. (The name "Particles" comes from the particle-filtering literature.) These types all form a Monte-Carlo approximation of the distribution of a floating point number, i.e., the distribution is represented by samples/particles. Correlated quantities are handled as well, see multivariate particles below.

A number of type Particles behaves just as any other Number while partaking in calculations. Particles also behave like a distribution, so after a calculation, an approximation to the complete distribution of the output is captured and represented by the output particles. mean, std etc. can be extracted from the particles using the corresponding functions pmean and pstd. Particles also interact with Distributions.jl, so that you can call, e.g., Normal(p) and get back a Normal type from distributions or fit(Gamma, p) to get a Gammadistribution. Particles can also be asked for maximum/minimum, quantile etc. using functions with a prefix p, i.e., pmaximum. If particles are plotted with plot(p), a histogram is displayed. This requires Plots.jl. A kernel-density estimate can be obtained by density(p) is StatsPlots.jl is loaded.

Quick start

julia> using MonteCarloMeasurements, Plots
 
 julia> a = π ± 0.1 # Construct Gaussian uncertain parameters using ± (\pm)
 Particles{Float64,2000}
@@ -26,7 +26,7 @@
 
 julia> c = Particles(500, Poisson(3.)) # Create uncertain numbers distributed according to a given distribution
 Particles{Int64,500}
- 2.882 ± 1.7

For further help, see the documentation, the examples folder or the arXiv paper.

source
MonteCarloMeasurements.ParticlesType
struct Particles{T, N} <: AbstractParticles{T, N}

This type represents uncertainty using a cloud of particles.

Constructors:

  • Particles()
  • Particles(N::Integer)
  • Particles([rng::AbstractRNG,] d::Distribution)
  • Particles([rng::AbstractRNG,] N::Integer, d::Distribution; permute=true, systematic=true)
  • Particles(v::Vector{T} where T)
  • Particles(m::Matrix{T} where T): Creates multivariate particles (Vector{Particles})
source
MonteCarloMeasurements.StaticParticlesType
struct StaticParticles{T, N} <: AbstractParticles{T, N}

See ?Particles for help. The difference between StaticParticles and Particles is that the StaticParticles store particles in a static vecetor. This makes runtimes much shorter, but compile times longer. See the documentation for some benchmarks. Only recommended for sample sizes of ≲ 300-400

source
MonteCarloMeasurements.WorkspaceType
struct Workspace{T1, T2, T3, T4, T5, T6}

Arguments:

  • simple_input: Input object f will be called with, does not contain any particles
  • simple_result: Simple output from f without particles
  • result: Complete output of f including particles
  • buffersetter: Helper function to shift data between objects
  • resultsetter: Helper function to shift data between objects
  • f: Function to call
  • N: Number of particles
source
MonteCarloMeasurements.WorkspaceMethod
Workspace(f, input)

Create a Workspace object for inputs of type typeof(input). Useful if input is a structure with fields of type <: AbstractParticles (can be deeply nested). See also with_workspace.

source
MonteCarloMeasurements.:±Function
μ ± σ

Creates 2000 Particles with mean μ and std σ. It can also be used as a unary operator, a mean of 0 is then used with std σ. If μ is a vector, the constructor MvNormal is used, and σ is thus treated as std if it's a scalar, and variances if it's a matrix or vector. See also , ..

source
MonteCarloMeasurements.:∓Function
μ ∓ σ

Creates 100 StaticParticles with mean μ and std σ. It can also be used as a unary operator, a mean of 0 is then used with std σ. If μ is a vector, the constructor MvNormal is used, and σ is thus treated as std if it's a scalar, and variances if it's a matrix or vector. See also ±,

source
MonteCarloMeasurements.:⊞Method
a ⊞ Distribution()

Adds 2000 Particles sampled from a specified ::Distribution to a. Shorthand for a + Particles(Distribution()), e.g., 1 ⊞ Binomial(3).

source
MonteCarloMeasurements.:⊠Method
a ⊠ Distribution()

Multiplies a by 2000 Particles sampled from a specified ::Distribution. Shorthand for a * Particles(Distribution()), e.g., a ⊠ Gamma(1).

source
MonteCarloMeasurements.bootstrapFunction
bootstrap([rng::AbstractRNG,] p::Particles, n = nparticles(p))

Return Particles resampled with replacement. n specifies the number of samples to draw. Also works for arrays of Particles, in which case a single set of indices are drawn and used to extract samples from all elements in the array.

source
MonteCarloMeasurements.bootstrapFunction
bootstrap([rng::AbstractRNG,] p::Particles, n = nparticles(p))

Return Particles resampled with replacement. n specifies the number of samples to draw. Also works for arrays of Particles, in which case a single set of indices are drawn and used to extract samples from all elements in the array.

source
MonteCarloMeasurements.errorbarplotFunction
errorbarplot(x,y,[q=0.025])

Plots a vector of particles with error bars at quantile q. If q::Tuple, then you can specify both lower and upper quantile, e.g., (0.01, 0.99).

source
MonteCarloMeasurements.essMethod
ess(p::AbstractParticles{T,N})

Calculates the effective sample size. This is useful if particles come from MCMC sampling and are correlated in time. The ESS is a number between [0,N].

Initial source: https://github.com/tpapp/MCMCDiagnostics.jl

source
MonteCarloMeasurements.has_particlesMethod
has_particles(P)

Determine whether or no the object P has some kind of particles inside it. This function examins fields of P recursively and looks inside arrays etc.

source
MonteCarloMeasurements.mcplotFunction
mcplot(x,y,[N=0])

Plots all trajectories represented by a vector of particles. N > 1 controls the number of trajectories to plot.

source
MonteCarloMeasurements.mean_objectMethod
mean_object(x)

Returns an object similar to x, but where all internal instances of Particles are replaced with their mean. The generalization of this function is replace_particles.

source
MonteCarloMeasurements.outer_productFunction
p = outer_product([rng::AbstractRNG,] dists::Vector{<:Distribution}, N=100_000)

Creates a multivariate systematic sample where each dimension is sampled according to the corresponding univariate distribution in dists. Returns p::Vector{Particles} where each Particles has a length approximately equal to N. The particles form the outer product between d systematically sampled vectors with length given by the d:th root of N, where d is the length of dists, All particles will be independent and have marginal distributions given by dists.

See also MonteCarloMeasurements.⊗

source
MonteCarloMeasurements.register_primitiveFunction
register_primitive(f, eval=eval)

Register both single and multi-argument function so that it works with particles. If you want to register functions from within a module, you must pass the modules eval function.

source
MonteCarloMeasurements.register_primitive_multiFunction
register_primitive_multi(ff, eval=eval)

Register a multi-argument function so that it works with particles. If you want to register functions from within a module, you must pass the modules eval function.

source
MonteCarloMeasurements.register_primitive_singleFunction
register_primitive_single(ff, eval=eval)

Register a single-argument function so that it works with particles. If you want to register functions from within a module, you must pass the modules eval function.

source
MonteCarloMeasurements.ribbonplotFunction
ribbonplot(x,y,[q=0.025]; N=true)

Plots a vector of particles with a ribbon covering quantiles q, 1-q. If q::Tuple, then you can specify both lower and upper quantile, e.g., (0.01, 0.99).

If a positive number N is provided, N sample trajectories will be plotted on top of the ribbon.

source
MonteCarloMeasurements.set_comparison_functionMethod
set_comparison_function(f)

Change the Function used to reduce particles to a number for comparison operators Toggle the use of a comparison Function without warning using the Function unsafe_comparisons.

source
MonteCarloMeasurements.ParticlesType
struct Particles{T, N} <: AbstractParticles{T, N}

This type represents uncertainty using a cloud of particles.

Constructors:

  • Particles()
  • Particles(N::Integer)
  • Particles([rng::AbstractRNG,] d::Distribution)
  • Particles([rng::AbstractRNG,] N::Integer, d::Distribution; permute=true, systematic=true)
  • Particles(v::Vector{T} where T)
  • Particles(m::Matrix{T} where T): Creates multivariate particles (Vector{Particles})
source
MonteCarloMeasurements.StaticParticlesType
struct StaticParticles{T, N} <: AbstractParticles{T, N}

See ?Particles for help. The difference between StaticParticles and Particles is that the StaticParticles store particles in a static vecetor. This makes runtimes much shorter, but compile times longer. See the documentation for some benchmarks. Only recommended for sample sizes of ≲ 300-400

source
MonteCarloMeasurements.WorkspaceType
struct Workspace{T1, T2, T3, T4, T5, T6}

Arguments:

  • simple_input: Input object f will be called with, does not contain any particles
  • simple_result: Simple output from f without particles
  • result: Complete output of f including particles
  • buffersetter: Helper function to shift data between objects
  • resultsetter: Helper function to shift data between objects
  • f: Function to call
  • N: Number of particles
source
MonteCarloMeasurements.WorkspaceMethod
Workspace(f, input)

Create a Workspace object for inputs of type typeof(input). Useful if input is a structure with fields of type <: AbstractParticles (can be deeply nested). See also with_workspace.

source
MonteCarloMeasurements.:±Function
μ ± σ

Creates 2000 Particles with mean μ and std σ. It can also be used as a unary operator, a mean of 0 is then used with std σ. If μ is a vector, the constructor MvNormal is used, and σ is thus treated as std if it's a scalar, and variances if it's a matrix or vector. See also , ..

source
MonteCarloMeasurements.:∓Function
μ ∓ σ

Creates 100 StaticParticles with mean μ and std σ. It can also be used as a unary operator, a mean of 0 is then used with std σ. If μ is a vector, the constructor MvNormal is used, and σ is thus treated as std if it's a scalar, and variances if it's a matrix or vector. See also ±,

source
MonteCarloMeasurements.:⊞Method
a ⊞ Distribution()

Adds 2000 Particles sampled from a specified ::Distribution to a. Shorthand for a + Particles(Distribution()), e.g., 1 ⊞ Binomial(3).

source
MonteCarloMeasurements.:⊠Method
a ⊠ Distribution()

Multiplies a by 2000 Particles sampled from a specified ::Distribution. Shorthand for a * Particles(Distribution()), e.g., a ⊠ Gamma(1).

source
MonteCarloMeasurements.bootstrapFunction
bootstrap([rng::AbstractRNG,] p::Particles, n = nparticles(p))

Return Particles resampled with replacement. n specifies the number of samples to draw. Also works for arrays of Particles, in which case a single set of indices are drawn and used to extract samples from all elements in the array.

source
MonteCarloMeasurements.bootstrapFunction
bootstrap([rng::AbstractRNG,] p::Particles, n = nparticles(p))

Return Particles resampled with replacement. n specifies the number of samples to draw. Also works for arrays of Particles, in which case a single set of indices are drawn and used to extract samples from all elements in the array.

source
MonteCarloMeasurements.errorbarplotFunction
errorbarplot(x,y,[q=0.025])

Plots a vector of particles with error bars at quantile q. If q::Tuple, then you can specify both lower and upper quantile, e.g., (0.01, 0.99).

source
MonteCarloMeasurements.essMethod
ess(p::AbstractParticles{T,N})

Calculates the effective sample size. This is useful if particles come from MCMC sampling and are correlated in time. The ESS is a number between [0,N].

Initial source: https://github.com/tpapp/MCMCDiagnostics.jl

source
MonteCarloMeasurements.has_particlesMethod
has_particles(P)

Determine whether or no the object P has some kind of particles inside it. This function examins fields of P recursively and looks inside arrays etc.

source
MonteCarloMeasurements.mcplotFunction
mcplot(x,y,[N=0])

Plots all trajectories represented by a vector of particles. N > 1 controls the number of trajectories to plot.

source
MonteCarloMeasurements.mean_objectMethod
mean_object(x)

Returns an object similar to x, but where all internal instances of Particles are replaced with their mean. The generalization of this function is replace_particles.

source
MonteCarloMeasurements.outer_productFunction
p = outer_product([rng::AbstractRNG,] dists::Vector{<:Distribution}, N=100_000)

Creates a multivariate systematic sample where each dimension is sampled according to the corresponding univariate distribution in dists. Returns p::Vector{Particles} where each Particles has a length approximately equal to N. The particles form the outer product between d systematically sampled vectors with length given by the d:th root of N, where d is the length of dists, All particles will be independent and have marginal distributions given by dists.

See also MonteCarloMeasurements.⊗

source
MonteCarloMeasurements.register_primitiveFunction
register_primitive(f, eval=eval)

Register both single and multi-argument function so that it works with particles. If you want to register functions from within a module, you must pass the modules eval function.

source
MonteCarloMeasurements.register_primitive_multiFunction
register_primitive_multi(ff, eval=eval)

Register a multi-argument function so that it works with particles. If you want to register functions from within a module, you must pass the modules eval function.

source
MonteCarloMeasurements.register_primitive_singleFunction
register_primitive_single(ff, eval=eval)

Register a single-argument function so that it works with particles. If you want to register functions from within a module, you must pass the modules eval function.

source
MonteCarloMeasurements.ribbonplotFunction
ribbonplot(x,y,[q=0.025]; N=true)

Plots a vector of particles with a ribbon covering quantiles q, 1-q. If q::Tuple, then you can specify both lower and upper quantile, e.g., (0.01, 0.99).

If a positive number N is provided, N sample trajectories will be plotted on top of the ribbon.

source
MonteCarloMeasurements.set_comparison_functionMethod
set_comparison_function(f)

Change the Function used to reduce particles to a number for comparison operators Toggle the use of a comparison Function without warning using the Function unsafe_comparisons.

source
MonteCarloMeasurements.sigmapointsMethod
sigmapoints(m, Σ)
 sigmapoints(d::Normal)
 sigmapoints(d::MvNormal)

The unscented transform uses a small number of points to propagate the first and second moments of a probability density, called sigma points. We provide a function sigmapoints(μ, Σ) that creates a Matrix of 2n+1 sigma points, where n is the dimension. This can be used to initialize any kind of AbstractParticles, e.g.:

julia> m = [1,2]
 
@@ -45,12 +45,12 @@
 ζ = StaticParticles(sigmapoints(0.3, 0.1^2))             # Wrong!
 ω = StaticParticles(sigmapoints(1, 0.1^2))               # Wrong!
 
-p,ζ,ω = StaticParticles(sigmapoints([1, 0.3, 1], 0.1^2)) # Correct
source
MonteCarloMeasurements.systematic_sampleFunction
systematic_sample([rng::AbstractRNG,] N, d=Normal(0,1); permute=true)

returns a Vector of length N sampled systematically from the distribution d. If permute=false, this vector will be sorted.

source
MonteCarloMeasurements.transform_momentsMethod
Y = transform_moments(X::Matrix, m, Σ; preserve_latin=false)

Transforms X such that it get the specified mean and covariance.

m, Σ   = [1,2], [2 1; 1 4] # Desired mean and covariance
+p,ζ,ω = StaticParticles(sigmapoints([1, 0.3, 1], 0.1^2)) # Correct
source
MonteCarloMeasurements.systematic_sampleFunction
systematic_sample([rng::AbstractRNG,] N, d=Normal(0,1); permute=true)

returns a Vector of length N sampled systematically from the distribution d. If permute=false, this vector will be sorted.

source
MonteCarloMeasurements.transform_momentsMethod
Y = transform_moments(X::Matrix, m, Σ; preserve_latin=false)

Transforms X such that it get the specified mean and covariance.

m, Σ   = [1,2], [2 1; 1 4] # Desired mean and covariance
 particles = transform_moments(X, m, Σ)
 julia> cov(particles) ≈ Σ
-true

Note, if X is a latin hypercube and Σ is non-diagonal, then the latin property is destroyed for all dimensions but the first. We provide a method preserve_latin=true) which absolutely preserves the latin property in all dimensions, but if you use this, the covariance of the sample will be slightly wrong

source
MonteCarloMeasurements.unsafe_comparisonsFunction
unsafe_comparisons(onoff=true; verbose=true)

Toggle the use of a comparison function without warning. By default mean is used to reduce particles to a floating point number for comparisons. This function can be changed, example: set_comparison_function(median)

unsafe_comparisons(mode=:reduction; verbose=true)

One can also specify a comparison mode, mode can take the values :safe, :montecarlo, :reduction. :safe is the same as calling unsafe_comparisons(false) and :reduction corresponds to true.

See Documentation: Comparison mode for more details.

source
MonteCarloMeasurements.wassersteinMethod
wasserstein(p1::AbstractParticles,p2::AbstractParticles,p)

Returns the Wasserstein distance (Earth-movers distance) of order p, to the pth power, between p1 and p2. I.e., for p=2, this returns W₂²

source
MonteCarloMeasurements.with_nominalMethod
pn = with_nominal(p, val)

Endow particles p with a nominal value val. The particle closest to val will be replaced with val, and moved to index 1. This operation introduces a slight bias in the statistics of pn, but the operation is asymptotically unbiased for large sample sizes. To obtain the nominal value of pn, call nominal(pn).

source
MonteCarloMeasurements.with_workspaceMethod
with_workspace(f,P)

In some cases, defining a primitive function which particles are to be propagate through is not possible but allowing unsafe comparisons are not acceptable. One such case is functions that internally calculate eigenvalues of uncertain matrices. The eigenvalue calculation makes use of comparison operators. If the uncertainty is large, eigenvalues might change place in the sorted list of returned eigenvalues, completely ruining downstream computations. For this we recommend, in order of preference

  1. Use @bymap detailed in the documentation. Applicable if all uncertain values appears as arguments to your entry function.
  2. Create a Workspace object and call it using your entry function. Applicable if uncertain parameters appear nested in an object that is an argument to your entry function:
# desired computation: y = f(obj), obj contains uncertain parameters inside
+true

Note, if X is a latin hypercube and Σ is non-diagonal, then the latin property is destroyed for all dimensions but the first. We provide a method preserve_latin=true) which absolutely preserves the latin property in all dimensions, but if you use this, the covariance of the sample will be slightly wrong

source
MonteCarloMeasurements.unsafe_comparisonsFunction
unsafe_comparisons(onoff=true; verbose=true)

Toggle the use of a comparison function without warning. By default mean is used to reduce particles to a floating point number for comparisons. This function can be changed, example: set_comparison_function(median)

unsafe_comparisons(mode=:reduction; verbose=true)

One can also specify a comparison mode, mode can take the values :safe, :montecarlo, :reduction. :safe is the same as calling unsafe_comparisons(false) and :reduction corresponds to true.

See Documentation: Comparison mode for more details.

source
MonteCarloMeasurements.wassersteinMethod
wasserstein(p1::AbstractParticles,p2::AbstractParticles,p)

Returns the Wasserstein distance (Earth-movers distance) of order p, to the pth power, between p1 and p2. I.e., for p=2, this returns W₂²

source
MonteCarloMeasurements.with_nominalMethod
pn = with_nominal(p, val)

Endow particles p with a nominal value val. The particle closest to val will be replaced with val, and moved to index 1. This operation introduces a slight bias in the statistics of pn, but the operation is asymptotically unbiased for large sample sizes. To obtain the nominal value of pn, call nominal(pn).

source
MonteCarloMeasurements.with_workspaceMethod
with_workspace(f,P)

In some cases, defining a primitive function which particles are to be propagate through is not possible but allowing unsafe comparisons are not acceptable. One such case is functions that internally calculate eigenvalues of uncertain matrices. The eigenvalue calculation makes use of comparison operators. If the uncertainty is large, eigenvalues might change place in the sorted list of returned eigenvalues, completely ruining downstream computations. For this we recommend, in order of preference

  1. Use @bymap detailed in the documentation. Applicable if all uncertain values appears as arguments to your entry function.
  2. Create a Workspace object and call it using your entry function. Applicable if uncertain parameters appear nested in an object that is an argument to your entry function:
# desired computation: y = f(obj), obj contains uncertain parameters inside
 y = with_workspace(f, obj)
 # or equivalently
 w = Workspace(f, obj)
 use_invokelatest = true # Set this to false to gain 0.1-1 ms, at the expense of world-age problems if w is created and used in the same function.
-w(obj, use_invokelatest)
source
MonteCarloMeasurements.ℂ2ℂ_functionMethod
ℂ2ℂ_function(f::Function, z::Complex{<:AbstractParticles})

Helper function for uncertainty propagation through complex-valued functions of complex arguments. applies f : ℂ → ℂ to z::Complex{<:AbstractParticles}.

source
MonteCarloMeasurements.ℝⁿ2ℂⁿ_functionMethod
ℝⁿ2ℂⁿ_function(f::Function, p::AbstractArray{T})

Helper function for performing uncertainty propagation through complex-valued functions with vector inputs. Applies f : ℝⁿ → Cⁿ to an array of particles. E.g., LinearAlgebra.eigvals(p::Matrix{<:AbstractParticles}) = ℝⁿ2ℂⁿ_function(eigvals,p)

source
MonteCarloMeasurements.ℝⁿ2ℂⁿ_functionMethod
ℝⁿ2ℂⁿ_function(f::Function, p::AbstractArray{T})

Helper function for performing uncertainty propagation through complex-valued functions with vector inputs. Applies f : ℝⁿ → Cⁿ to an array of particles. E.g., LinearAlgebra.eigvals(p::Matrix{<:AbstractParticles}) = ℝⁿ2ℂⁿ_function(eigvals,p)

source
MonteCarloMeasurements.ℝⁿ2ℝⁿ_functionMethod
ℝⁿ2ℝⁿ_function(f::Function, p::AbstractArray{T})

Helper function for performing uncertainty propagation through vector-valued functions with vector inputs. Applies f : ℝⁿ → ℝⁿ to an array of particles. E.g., Base.log(p::Matrix{<:AbstractParticles}) = ℝⁿ2ℝⁿ_function(log,p)

source
MonteCarloMeasurements.ℝⁿ2ℝⁿ_functionMethod
ℝⁿ2ℝⁿ_function(f::Function, p::AbstractArray{T})

Helper function for performing uncertainty propagation through vector-valued functions with vector inputs. Applies f : ℝⁿ → ℝⁿ to an array of particles. E.g., Base.log(p::Matrix{<:AbstractParticles}) = ℝⁿ2ℝⁿ_function(log,p)

source
MonteCarloMeasurements.@probMacro
@prob a < b

Calculate the probability that an event on any of the forms a < b, a > b, a <= b, a >= b occurs, where a and/or b are of type AbstractParticles.

source
MonteCarloMeasurements.@unsafeMacro
@unsafe expression

Activates unsafe comparisons for the provided expression only. The expression is surrounded by a try/catch block to robustly restore unsafe comparisons in case of exception.

source
Base.:≈Method
p1 ≈ p2

Determine if two particles are not significantly different

source
Base.:≉Method
p1 ≉ p2

Determine if two particles are significantly different

source
+w(obj, use_invokelatest)
source
MonteCarloMeasurements.ℂ2ℂ_functionMethod
ℂ2ℂ_function(f::Function, z::Complex{<:AbstractParticles})

Helper function for uncertainty propagation through complex-valued functions of complex arguments. applies f : ℂ → ℂ to z::Complex{<:AbstractParticles}.

source
MonteCarloMeasurements.ℝⁿ2ℂⁿ_functionMethod
ℝⁿ2ℂⁿ_function(f::Function, p::AbstractArray{T})

Helper function for performing uncertainty propagation through complex-valued functions with vector inputs. Applies f : ℝⁿ → Cⁿ to an array of particles. E.g., LinearAlgebra.eigvals(p::Matrix{<:AbstractParticles}) = ℝⁿ2ℂⁿ_function(eigvals,p)

source
MonteCarloMeasurements.ℝⁿ2ℂⁿ_functionMethod
ℝⁿ2ℂⁿ_function(f::Function, p::AbstractArray{T})

Helper function for performing uncertainty propagation through complex-valued functions with vector inputs. Applies f : ℝⁿ → Cⁿ to an array of particles. E.g., LinearAlgebra.eigvals(p::Matrix{<:AbstractParticles}) = ℝⁿ2ℂⁿ_function(eigvals,p)

source
MonteCarloMeasurements.ℝⁿ2ℝⁿ_functionMethod
ℝⁿ2ℝⁿ_function(f::Function, p::AbstractArray{T})

Helper function for performing uncertainty propagation through vector-valued functions with vector inputs. Applies f : ℝⁿ → ℝⁿ to an array of particles. E.g., Base.log(p::Matrix{<:AbstractParticles}) = ℝⁿ2ℝⁿ_function(log,p)

source
MonteCarloMeasurements.ℝⁿ2ℝⁿ_functionMethod
ℝⁿ2ℝⁿ_function(f::Function, p::AbstractArray{T})

Helper function for performing uncertainty propagation through vector-valued functions with vector inputs. Applies f : ℝⁿ → ℝⁿ to an array of particles. E.g., Base.log(p::Matrix{<:AbstractParticles}) = ℝⁿ2ℝⁿ_function(log,p)

source
MonteCarloMeasurements.@probMacro
@prob a < b

Calculate the probability that an event on any of the forms a < b, a > b, a <= b, a >= b occurs, where a and/or b are of type AbstractParticles.

source
MonteCarloMeasurements.@unsafeMacro
@unsafe expression

Activates unsafe comparisons for the provided expression only. The expression is surrounded by a try/catch block to robustly restore unsafe comparisons in case of exception.

source
Base.:≈Method
p1 ≈ p2

Determine if two particles are not significantly different

source
Base.:≉Method
p1 ≉ p2

Determine if two particles are significantly different

source
diff --git a/dev/comparison/index.html b/dev/comparison/index.html index cbf6a47..18d44de 100644 --- a/dev/comparison/index.html +++ b/dev/comparison/index.html @@ -31,4 +31,4 @@ plot!(0 .+ ym, yxr, lab="Linear Gaussian propagation") end fig -end
plot_dens (generic function with 2 methods)

The first example we'll look at is the quadratic parabola. This function will be poorly approximated by a linear function around $x=0$.

plot_dens(x->x^2+3, Normal(0,1), -3, 3, legend=:top)

as we can see, the linear method outputs a Dirac distribution (no uncertainty) at $x=0$, while there should clearly be a lot of uncertainty in the output. The histogram displays the output density as approximated by the particles. The histogram does not go below zero, and tapers off as values increase. The problem here is that the uncertainty is large in relation to the curvature of the function. As the uncertainty decreases, the true output density becomes closer and closer to a DIrac distribution.

The next function has a discontinuity (≈ infinite curvature)

plot_dens(x->sign(x)+1, Normal(0.5,1), -3, 3, legend=:bottomright)

once again, linear uncertainty propagation outputs a distribution with zero uncertainty. The true output distribution has two modes since the input distribution places mass on both sides of the discontinuity. This is captured in the particle distribution, where most particles end up at the right side of the discontinuity, while a smaller proportion of the particles end up to the left. If the input density would have its mean at 0, half of the particles would end up in each of the output locations. Any function containing an if-statement where the chosen branch depends on an uncertain value falls into this category.

Next, we consider a periodic function

plot_dens(x->sin(x)+2, Normal(0.5,1), -3, 3, legend=:topright)

Once again, the uncertainty is large in relation to the curvature of the function and linear uncertainty propagation places significant mass outside the interval $[-1, 1]$ which is the range of the $\sin$ function. The particle histogram respects this range. If we increase the uncertainty in the input further, the linear approximation to the function becomes increasingly worse

plot_dens(x->sin(x)+2, Normal(0.5,5), -15, 15, legend=:topright)

Pendulum simulation

The example Differential Equations shows how linear/Monte-Carlo uncertainty propagation through a nonlinear ODE works.

+end
plot_dens (generic function with 2 methods)

The first example we'll look at is the quadratic parabola. This function will be poorly approximated by a linear function around $x=0$.

plot_dens(x->x^2+3, Normal(0,1), -3, 3, legend=:top)

as we can see, the linear method outputs a Dirac distribution (no uncertainty) at $x=0$, while there should clearly be a lot of uncertainty in the output. The histogram displays the output density as approximated by the particles. The histogram does not go below zero, and tapers off as values increase. The problem here is that the uncertainty is large in relation to the curvature of the function. As the uncertainty decreases, the true output density becomes closer and closer to a DIrac distribution.

The next function has a discontinuity (≈ infinite curvature)

plot_dens(x->sign(x)+1, Normal(0.5,1), -3, 3, legend=:bottomright)

once again, linear uncertainty propagation outputs a distribution with zero uncertainty. The true output distribution has two modes since the input distribution places mass on both sides of the discontinuity. This is captured in the particle distribution, where most particles end up at the right side of the discontinuity, while a smaller proportion of the particles end up to the left. If the input density would have its mean at 0, half of the particles would end up in each of the output locations. Any function containing an if-statement where the chosen branch depends on an uncertain value falls into this category.

Next, we consider a periodic function

plot_dens(x->sin(x)+2, Normal(0.5,1), -3, 3, legend=:topright)

Once again, the uncertainty is large in relation to the curvature of the function and linear uncertainty propagation places significant mass outside the interval $[-1, 1]$ which is the range of the $\sin$ function. The particle histogram respects this range. If we increase the uncertainty in the input further, the linear approximation to the function becomes increasingly worse

plot_dens(x->sin(x)+2, Normal(0.5,5), -15, 15, legend=:topright)

Pendulum simulation

The example Differential Equations shows how linear/Monte-Carlo uncertainty propagation through a nonlinear ODE works.

diff --git a/dev/examples/index.html b/dev/examples/index.html index 0fd13c0..54f6cd3 100644 --- a/dev/examples/index.html +++ b/dev/examples/index.html @@ -2,10 +2,10 @@ Examples · MonteCarloMeasurements Documentation

Examples

Control systems

This example shows how to simulate control systems (using ControlSystems.jl) with uncertain parameters. We calculate and display Bode diagrams, Nyquist diagrams and time-domain responses. We also illustrate how the package ControlSystemIdentification.jl interacts with MonteCarloMeasurements to facilitate the creation and analysis of uncertain systems.

We also perform some limited benchmarks.

The package RobustAndOptimalControl.jl contains lots of additional tools to work with linear systems with uncertainty represented as Particles. See the documentation on Uncertainty modeling for several examples.

Latin Hypercube Sampling

We show how to initialize particles with LHS and how to make sure the sample gets the desired moments. We also visualize the statistics of the sample.

How MC uncertainty propagation works

We produce the first figure in this readme and explain in visual detail how different forms of uncertainty propagation propagates a probability distribution through a nonlinear function. Also see Comparison between linear uncertainty propagation and Monte-Carlo sampling for more visual examples.

Robust probabilistic optimization

Here, we use MonteCarloMeasurements to perform robust optimization. With robust and probabilistic, we mean that we place some kind of bound on a quantile of an uncertain value, or otherwise make use of the probability distribution of some value that depend on the optimized parameters.

The application we consider is optimization of a PID controller. Normally, we are interested in controller performance and robustness against uncertainty. The robustness is often introduced by placing an upper bound on the, so called, sensitivity function. When the system to be controlled is parameterized by Particles, we can penalize both variance in the performance measure as well as the 90:th quantile of the maximum of the sensitivity function. This example illustrates how easy it is to incorporate probabilistic constrains or cost functions in an optimization problem using Particles.

Autodiff and Robust optimization

Another example using MonteCarloMeasurements to perform robust optimization, this time with automatic differentiation. We use Optim.jl to solve a linear program with probabilistic constraints using 4 different methods, two gradient free, one first-order and one second-order method. We demonstrate calculation of gradients of uncertain functions with uncertain inputs using both Zygote.jl and ForwardDiff.jl.

Unitful interaction

Particles with units can be created using the package Unitful.jl for uncertainty propagation with automatic unit checks. The interaction is only supported through the construct Particles{Quantity}, whereas the reverse construct Quantity{Particles} is likely to result in problems. Unitful particles are thus created like this

julia> using MonteCarloMeasurements, Unitful
 
 julia> (1 ± 0.1)u"V"
-1.0000000000000002 V ± 0.0999923152893049 V Particles{Quantity{Float64, 𝐋^2 𝐌 𝐈^-1 𝐓^-3, Unitful.FreeUnits{(V,), 𝐋^2 𝐌 𝐈^-1 𝐓^-3, nothing}}, 2000}
+1.0000000000000002 V ± 0.09999231528930483 V Particles{Quantity{Float64, 𝐋^2 𝐌 𝐈^-1 𝐓^-3, Unitful.FreeUnits{(V,), 𝐋^2 𝐌 𝐈^-1 𝐓^-3, nothing}}, 2000}
 
 julia> (1..2)u"m"
-1.499999999999999 m ± 0.28874729435961827 m Particles{Quantity{Float64, 𝐋, Unitful.FreeUnits{(m,), 𝐋, nothing}}, 2000}

Example: Solar collector energy transfer

The following example estimates the amount of thermal power transferred from a solar collector embedded in a concrete floor, to a water reservoir. The power is computed by measuring the temperature difference, $\Delta T$, between the solar collectors circulating warm water going into the collector tank and the colder returning water. Using the mass-flow rate and the specific heat capacity of water, we can estimate the power transfer. No flow meter is installed, so the flow is estimated and subject to large uncertainty.

using MonteCarloMeasurements
+1.4999999999999991 m ± 0.28874729435961816 m Particles{Quantity{Float64, 𝐋, Unitful.FreeUnits{(m,), 𝐋, nothing}}, 2000}

Example: Solar collector energy transfer

The following example estimates the amount of thermal power transferred from a solar collector embedded in a concrete floor, to a water reservoir. The power is computed by measuring the temperature difference, $\Delta T$, between the solar collectors circulating warm water going into the collector tank and the colder returning water. Using the mass-flow rate and the specific heat capacity of water, we can estimate the power transfer. No flow meter is installed, so the flow is estimated and subject to large uncertainty.

using MonteCarloMeasurements
 using Unitful
 using Unitful: W, kW, m, mm, hr, K, g, J, l, s
 
@@ -14,19 +14,19 @@
 density_water = 1e6g/m^3
 flow = 8*(1..2.5)*l/(60s) # 8 solar collector circuits, each with an estimated flow rate of between 1 and 2.5 l/minute
 mass_flow = flow * density_water |> upreferred # Water flow in mass per second
-power = uconvert(W, mass_flow * specific_heat_water * ΔT) # Power in Watts
3418.5868975933918 W ± 1160.1579052110212 W Particles{Quantity{Float64, 𝐋^2 𝐌 𝐓^-3, Unitful.FreeUnits{(W,), 𝐋^2 𝐌 𝐓^-3, nothing}}, 2000}
+power = uconvert(W, mass_flow * specific_heat_water * ΔT) # Power in Watts
3430.962141719572 W ± 1196.2188968306957 W Particles{Quantity{Float64, 𝐋^2 𝐌 𝐓^-3, Unitful.FreeUnits{(W,), 𝐋^2 𝐌 𝐓^-3, nothing}}, 2000}
 

Some power is lost to the ground in which the heat-exchanger circuits are embedded, we estimate this to be between 10 and 50% of the total power.

ground_losses = (0.1..0.5) * power # Between 10-50% power loss to ground
-reservoir_volume = 7m*3m*1.5m
31.5 m^3

The energy transfered during 6hrs solar collection can be estimated as

energy_6_hrs = (power - ground_losses)*6hr
14379.564612040811 hr W ± 5570.13831605571 hr W Particles{Quantity{Float64, 𝐋^2 𝐌 𝐓^-2, Unitful.FreeUnits{(hr, W), 𝐋^2 𝐌 𝐓^-2, nothing}}, 2000}
-

and this energy transfer will increase the temperature in the reservoir by

ΔT_reservoir_6hr = energy_6_hrs/(reservoir_volume*density_water*specific_heat_water) |> upreferred
0.3922145137958631 K ± 0.1519301279524231 K Particles{Quantity{Float64, 𝚯, Unitful.FreeUnits{(K,), 𝚯, nothing}}, 2000}
+reservoir_volume = 7m*3m*1.5m
31.5 m^3

The energy transfered during 6hrs solar collection can be estimated as

energy_6_hrs = (power - ground_losses)*6hr
14393.444321472247 hr W ± 5545.519606284716 hr W Particles{Quantity{Float64, 𝐋^2 𝐌 𝐓^-2, Unitful.FreeUnits{(hr, W), 𝐋^2 𝐌 𝐓^-2, nothing}}, 2000}
+

and this energy transfer will increase the temperature in the reservoir by

ΔT_reservoir_6hr = energy_6_hrs/(reservoir_volume*density_water*specific_heat_water) |> upreferred
0.3925930943463272 K ± 0.1512586322887069 K Particles{Quantity{Float64, 𝚯, Unitful.FreeUnits{(K,), 𝚯, nothing}}, 2000}
 

Finally, we visualize the distributions associated with the estimated quantities:

using Plots
 figh = plot(ΔT_reservoir_6hr, xlabel="\$ΔT [K]\$", ylabel="\$P(ΔT)\$", title="Temperature increase 6hrs sun")
 qs   = 0:0.01:1
 Qs   = pquantile.(ΔT_reservoir_6hr, qs)
 figq = plot(qs, Qs, xlabel="∫\$P(ΔT)\$")
-plot(figh, figq)
+plot(figh, figq)
+

Loading search...

    +Search · MonteCarloMeasurements Documentation

    Loading search...

      diff --git a/dev/sign.html b/dev/sign.html index 60dc511..96a936e 100644 --- a/dev/sign.html +++ b/dev/sign.html @@ -1,7 +1,7 @@ -
      +
      +
      +