diff --git a/packages/squiggle-lang/src/rescript/Distributions/SymbolicDist/SymbolicDist.res b/packages/squiggle-lang/src/rescript/Distributions/SymbolicDist/SymbolicDist.res index 997506d9..a4704a34 100644 --- a/packages/squiggle-lang/src/rescript/Distributions/SymbolicDist/SymbolicDist.res +++ b/packages/squiggle-lang/src/rescript/Distributions/SymbolicDist/SymbolicDist.res @@ -219,12 +219,18 @@ module Uniform = { module Float = { type t = float let make = t => #Float(t) + let makeSafe = t => + if E.Float.isFinite(t) { + Ok(#Float(t)) + } else { + Error("Float must be finite") + } let pdf = (x, t: t) => x == t ? 1.0 : 0.0 let cdf = (x, t: t) => x >= t ? 1.0 : 0.0 let inv = (p, t: t) => p < t ? 0.0 : 1.0 let mean = (t: t) => Ok(t) let sample = (t: t) => t - let toString = Js.Float.toString + let toString = (t: t) => j`Delta($t)` } module From90thPercentile = { diff --git a/packages/squiggle-lang/src/rescript/ReducerInterface/ReducerInterface_GenericDistribution.res b/packages/squiggle-lang/src/rescript/ReducerInterface/ReducerInterface_GenericDistribution.res index 4615fa44..542a54a2 100644 --- a/packages/squiggle-lang/src/rescript/ReducerInterface/ReducerInterface_GenericDistribution.res +++ b/packages/squiggle-lang/src/rescript/ReducerInterface/ReducerInterface_GenericDistribution.res @@ -178,10 +178,12 @@ let dispatchToGenericOutput = (call: ExpressionValue.functionCall, _environment) > => { let (fnName, args) = call switch (fnName, args) { - | ("exponential" as fnName, [EvNumber(f1)]) => + | ("exponential" as fnName, [EvNumber(f)]) => SymbolicConstructors.oneFloat(fnName) - ->E.R.bind(r => r(f1)) + ->E.R.bind(r => r(f)) ->SymbolicConstructors.symbolicResultToOutput + | ("delta", [EvNumber(f)]) => + SymbolicDist.Float.makeSafe(f)->SymbolicConstructors.symbolicResultToOutput | ( ("normal" | "uniform" | "beta" | "lognormal" | "cauchy" | "to") as fnName, [EvNumber(f1), EvNumber(f2)], diff --git a/packages/squiggle-lang/src/rescript/Utility/E.res b/packages/squiggle-lang/src/rescript/Utility/E.res index 472c32f7..1445a80c 100644 --- a/packages/squiggle-lang/src/rescript/Utility/E.res +++ b/packages/squiggle-lang/src/rescript/Utility/E.res @@ -198,6 +198,7 @@ module Float = { let with3DigitsPrecision = Js.Float.toPrecisionWithPrecision(_, ~digits=3) let toFixed = Js.Float.toFixed let toString = Js.Float.toString + let isFinite = Js.Float.isFinite } module I = { diff --git a/packages/website/docs/Discussions/Three-Formats-Of-Distributions.md b/packages/website/docs/Discussions/Three-Formats-Of-Distributions.md index 8ec5b88d..405bc97c 100644 --- a/packages/website/docs/Discussions/Three-Formats-Of-Distributions.md +++ b/packages/website/docs/Discussions/Three-Formats-Of-Distributions.md @@ -11,7 +11,7 @@ _Symbolic_ formats are just the math equations. `normal(5,3)` is the symbolic re When you sample distributions (usually starting with symbolic formats), you get lists of samples. Monte Carlo techniques return lists of samples. Let’s call this the “_Sample Set_” format. -Lastly is what I’ll refer to as the _Graph_ format. It describes the coordinates, or the shape, of the distribution. You can save these formats in JSON, for instance, like, `{xs: [1, 2, 3, 4…], ys: [.0001, .0003, .002, …]}`. +Lastly is what I’ll refer to as the _Graph_ format. It describes the coordinates, or the shape, of the distribution. You can save these formats in JSON, for instance, like, `{xs: [1, 2, 3, 4, …], ys: [.0001, .0003, .002, …]}`. Symbolic, Sample Set, and Graph formats all have very different advantages and disadvantages. @@ -19,7 +19,7 @@ Note that the name "Symbolic" is fairly standard, but I haven't found common nam ## Symbolic Formats -**TLDR** +**TL;DR** Mathematical representations. Require analytic solutions. These are often ideal where they can be applied, but apply to very few actual functions. Typically used sparsely, except for the starting distributions (before any computation is performed). **Examples** @@ -29,9 +29,6 @@ Mathematical representations. Require analytic solutions. These are often ideal **How to Do Computation** To perform calculations of symbolic systems, you need to find analytical solutions. For example, there are equations to find the pdf or cdf of most distribution shapes at any point. There are also lots of simplifications that could be done in particular situations. For example, there’s an analytical solution for combining normal distributions. -**Special: The Metalog Distribution** -The Metalog distribution seems like it can represent almost any reasonable distribution. It’s symbolic. This is great for storage, but it’s not clear if it helps with calculation. My impression is that we don’t have symbolic ways of doing most functions (addition, multiplication, etc) on metalog distributions. Also, note that it can take a fair bit of computation to fit a shape to the Metalog distribution. - **Advantages** - Maximally compressed; i.e. very easy to store. @@ -54,10 +51,14 @@ The Metalog distribution seems like it can represent almost any reasonable distr **How to Visualize** Convert to graph, then display that. (Optionally, you can also convert to samples, then display those using a histogram, but this is often worse you have both options.) +**Bonus: The Metalog Distribution** + +The Metalog distribution seems like it can represent almost any reasonable distribution. It’s symbolic. This is great for storage, but it’s not clear if it helps with calculation. My impression is that we don’t have symbolic ways of doing most functions (addition, multiplication, etc) on metalog distributions. Also, note that it can take a fair bit of computation to fit a shape to the Metalog distribution. + ## Graph Formats -**TLDR** -Lists of the x-y coordinates of the shape of a distribution. (Usually the pdf, which is more compressed than the cdf). Some key functions (like pdf, cdf) and manipulations can work on almost any graphally-described distribution. +**TL;DR** +Lists of the x-y coordinates of the shape of a distribution. (Usually the pdf, which is more compressed than the cdf). Some key functions (like pdf, cdf) and manipulations can work on almost any graphically-described distribution. **Alternative Names:** Grid, Mesh, Graph, Vector, Pdf, PdfCoords/PdfPoints, Discretised, Bezier, Curve @@ -77,7 +78,7 @@ Use graph techniques. These can be fairly computationally-intensive (particularl **Disadvantages** -- Most calculations are infeasible/impossible to perform graphally. In these cases, you need to use sampling. +- Most calculations are infeasible/impossible to perform graphically. In these cases, you need to use sampling. - Not as accurate or fast as symbolic methods, where the symbolic methods are applicable. - The tails get cut off, which is subideal. It’s assumed that the value of the pdf outside of the bounded range is exactly 0, which is not correct. (Note: If you have ideas on how to store graph formats that don’t cut off tails, let me know) @@ -108,7 +109,7 @@ Use graph techniques. These can be fairly computationally-intensive (particularl ## Sample Set Formats -**TLDR** +**TL;DR** Random samples. Use Monte Carlo simulation to perform calculations. This is the predominant technique using Monte Carlo methods; in these cases, most nodes are essentially represented as sample sets. [Guesstimate](https://www.getguesstimate.com/) works this way. **How to Do Computation** diff --git a/packages/website/docs/Features/Distributions.mdx b/packages/website/docs/Features/Distributions.mdx new file mode 100644 index 00000000..28e1db01 --- /dev/null +++ b/packages/website/docs/Features/Distributions.mdx @@ -0,0 +1,360 @@ +--- +title: "Distribution Creation" +sidebar_position: 8 +--- + +import TOCInline from "@theme/TOCInline"; +import { SquiggleEditor } from "../../src/components/SquiggleEditor"; +import Admonition from "@theme/Admonition"; +import Tabs from "@theme/Tabs"; +import TabItem from "@theme/TabItem"; + + + +## To + +`(5thPercentile: number) to (95thPercentile: number)` +`to(5thPercentile: number, 95thPercentile: number)` + +The `to` function is an easy way to generate simple distributions using predicted _5th_ and _95th_ percentiles. + +If both values are above zero, a `lognormal` distribution is used. If not, a `normal` distribution is used. + + + + When 5 to 10 is entered, both numbers are positive, so it + generates a lognormal distribution with 5th and 95th percentiles at 5 and + 10. + + + + 5 to 10 does the same thing as to(5,10). + + + + When -5 to 5 is entered, there's negative values, so it + generates a normal distribution. This has 5th and 95th percentiles at 5 and + 10. + + + + It's very easy to generate distributions with very long tails. If this + happens, you can click the "log x scale" box to view this using a log scale. + + + + +### Arguments + +- `5thPercentile`: number +- `95thPercentile`: number, greater than `5thPercentile` + + +

+ "To" is a great way to generate probability distributions very + quickly from your intuitions. It's easy to write and easy to read. It's + often a good place to begin an estimate. +

+
+ + +

+ If you haven't tried{" "} + + calibration training + + , you're likely to be overconfident. We recommend doing calibration training + to get a feel for what a 90 percent confident interval feels like. +

+
+ +## Mixture + +`mixture(...distributions: Distribution[], weights?: number[])` +`mx(...distributions: Distribution[], weights?: number[])` + +The `mixture` mixes combines multiple distributions to create a mixture. You can optionally pass in a list of proportional weights. + + + + + + + + + + + + + +### Arguments + +- `distributions`: A set of distributions or numbers, each passed as a paramater. Numbers will be converted into Delta distributions. +- `weights`: An optional array of numbers, each representing the weight of its corresponding distribution. The weights will be re-scaled to add to `1.0`. If a weights array is provided, it must be the same length as the distribution paramaters. + +### Aliases + +- `mx` + +### Special Use Cases of Mixtures + +
+ 🕐 Zero or Continuous +

+ One common reason to have mixtures of continous and discrete distributions is to handle the special case of 0. + Say I want to model the time I will spend on some upcoming project. I think I have an 80% chance of doing it. +

+ +

+ In this case, I have a 20% chance of spending 0 time with it. I might estimate my hours with, +

+ +
+ +
+ 🔒 Model Uncertainty Safeguarding +

+ One technique several Foretold.io users used is to combine their main guess, with a + "just-in-case distribution". This latter distribution would have very low weight, but would be + very wide, just in case they were dramatically off for some weird reason. +

+ + +
+ +## Normal + +`normal(mean:number, standardDeviation:number)` + +Creates a [normal distribution](https://en.wikipedia.org/wiki/Normal_distribution) with the given mean and standard deviation. + + + + + + + + + + +### Arguments + +- `mean`: Number +- `standard deviation`: Number greater than zero + +[Wikipedia](https://en.wikipedia.org/wiki/Normal_distribution) + +## Log-normal + +`lognormal(mu: number, sigma: number)` + +Creates a [log-normal distribution](https://en.wikipedia.org/wiki/Log-normal_distribution) with the given mu and sigma. + +`Mu` and `sigma` represent the mean and standard deviation of the normal which results when +you take the log of our lognormal distribution. They can be difficult to directly reason about. +Because of this complexity, we recommend typically using the to syntax instead of estimating `mu` and `sigma` directly. + + + +### Arguments + +- `mu`: Number +- `sigma`: Number greater than zero + +[Wikipedia](https://en.wikipedia.org/wiki/Log-normal_distribution) + +
+ + ❓ Understanding mu and sigma + +

+ The log of lognormal(mu, sigma) is a normal distribution with + mean mu + and standard deviation sigma. For example, these two distributions + are identical: +

+ +
+ +## Uniform + +`uniform(low:number, high:number)` + +Creates a [uniform distribution]() with the given low and high values. + + + +### Arguments + +- `low`: Number +- `high`: Number greater than `low` + + +

+ While uniform distributions are very simple to understand, we find it rare + to find uncertainties that actually look like this. Before using a uniform + distribution, think hard about if you are really 100% confident that the + paramater will not wind up being just outside the stated boundaries. +

+ +

+ One good example of a uniform distribution uncertainty would be clear + physical limitations. You might have complete complete uncertainty on what + time of day an event will occur, but can say with 100% confidence it will + happen between the hours of 0:00 and 24:00. +

+
+ +## Delta + +`delta(value:number)` + +Creates a discrete distribution with all of its probability mass at point `value`. + +Few Squiggle users call the function `delta()` directly. Numbers are converted into delta distributions automatically, when it is appropriate. + +For example, in the function `mixture(1,2,normal(5,2))`, the first two arguments will get converted into delta distributions +with values at 1 and 2. Therefore, this is the same as `mixture(delta(1),delta(2),normal(5,2))`. + +`Delta()` distributions are currently the only discrete distributions accessible in Squiggle. + + + + + + + + + + + + + + + + + + + +### Arguments + +- `value`: Number + +## Beta + +`beta(alpha:number, beta:number)` + +Creates a [beta distribution](https://en.wikipedia.org/wiki/Beta_distribution) with the given `alpha` and `beta` values. For a good summary of the beta distribution, see [this explanation](https://stats.stackexchange.com/a/47782) on Stack Overflow. + + + + + + + + + + + + + + + + + + + +### Arguments + +- `alpha`: Number greater than zero +- `beta`: Number greater than zero + + +

+ Squiggle struggles to show beta distributions when either alpha or beta are + below 1.0. This is because the tails at ~0.0 and ~1.0 are very high. Using a + log scale for the y-axis helps here. +

+
+ Examples + + + + + + + + + + + + + + +
+
+ +## Exponential + +`exponential(rate:number)` + +Creates an [exponential distribution](https://en.wikipedia.org/wiki/Exponential_distribution) with the given rate. + + + +### Arguments + +- `rate`: Number greater than zero + +## Triangular distribution + +`triangular(low:number, mode:number, high:number)` + +Creates a [triangular distribution](https://en.wikipedia.org/wiki/Triangular_distribution) with the given low, mode, and high values. + +### Arguments + +- `low`: Number +- `mode`: Number greater than `low` +- `high`: Number greater than `mode` + + + +## FromSamples + +`fromSamples(samples:number[])` + +Creates a sample set distribution using an array of samples. + + + +### Arguments + +- `samples`: An array of at least 5 numbers. + + +

+ Samples are converted into{" "} + PDF{" "} + shapes automatically using{" "} + + kernel density estimation + {" "} + and an approximated bandwidth. Eventually Squiggle will allow for more + specificity. +

+
diff --git a/packages/website/docs/Features/Functions.mdx b/packages/website/docs/Features/Functions.mdx index 1de7514b..46bc4e39 100644 --- a/packages/website/docs/Features/Functions.mdx +++ b/packages/website/docs/Features/Functions.mdx @@ -5,144 +5,15 @@ sidebar_position: 7 import { SquiggleEditor } from "../../src/components/SquiggleEditor"; -_The source of truth for this document is [this file of code](https://github.com/quantified-uncertainty/squiggle/blob/develop/packages/squiggle-lang/src/rescript/ReducerInterface/ReducerInterface_GenericDistribution.res)_ - -## Inventory distributions - -We provide starter distributions, computed symbolically. - -### Normal distribution - -The `normal(mean, sd)` function creates a normal distribution with the given mean -and standard deviation. - - - -#### Validity - -- `sd > 0` - -### Uniform distribution - -The `uniform(low, high)` function creates a uniform distribution between the -two given numbers. - - - -#### Validity - -- `low < high` - -### Lognormal distribution - -The `lognormal(mu, sigma)` returns the log of a normal distribution with parameters -`mu` and `sigma`. The log of `lognormal(mu, sigma)` is a normal distribution with mean `mu` and standard deviation `sigma`. - - - -An alternative format is also available. The `to` notation creates a lognormal -distribution with a 90% confidence interval between the two numbers. We add -this convenience as lognormal distributions are commonly used in practice. - - - -#### Future feature: - -Furthermore, it's also possible to create a lognormal from it's actual mean -and standard deviation, using `lognormalFromMeanAndStdDev`. - -TODO: interpreter/parser doesn't provide this in current `develop` branch - - - -#### Validity - -- `sigma > 0` -- In `x to y` notation, `x < y` - -### Beta distribution - -The `beta(a, b)` function creates a beta distribution with parameters `a` and `b`: - - - -#### Validity - -- `a > 0` -- `b > 0` -- Empirically, we have noticed that numerical instability arises when `a < 1` or `b < 1` - -### Exponential distribution - -The `exponential(rate)` function creates an exponential distribution with the given -rate. - - - -#### Validity - -- `rate > 0` - -### Triangular distribution - -The `triangular(a,b,c)` function creates a triangular distribution with lower -bound `a`, mode `b` and upper bound `c`. - -#### Validity - -- `a < b < c` - - - -### Scalar (constant dist) - -Squiggle, when the context is right, automatically casts a float to a constant distribution. - -## `fromSamples` - -The last distribution constructor takes an array of samples and constructs a sample set distribution. - - - -#### Validity - -For `fromSamples(xs)`, - -- `xs.length > 5` -- Strictly every element of `xs` must be a number. - ## Operating on distributions Here are the ways we combine distributions. -### Mixture of distributions - -The `mixture` function combines 2 or more other distributions to create a weighted -combination of the two. The first positional arguments represent the distributions -to be combined, and the last argument is how much to weigh every distribution in the -combination. - - - -It's possible to create discrete distributions using this method. - - - -As well as mixed distributions: - - - -An alias of `mixture` is `mx` - -#### Validity - -Using javascript's variable arguments notation, consider `mx(...dists, weights)`: - -- `dists.length == weights.length` - ### Addition -A horizontal right shift +A horizontal right shift. The addition operation represents the distribution of the sum of +the value of one random sample chosen from the first distribution and the value one random sample +chosen from the second distribution. @@ -199,6 +80,8 @@ exp(dist)`} ### Taking logarithms +A projection over a stretched x-axis. + @@ -297,7 +182,8 @@ or all values lower than x. It is the inverse of `inv`. ### Inverse CDF The `inv(dist, prob)` gives the value x or which the probability for all values -lower than x is equal to prob. It is the inverse of `cdf`. +lower than x is equal to prob. It is the inverse of `cdf`. In the literature, it +is also known as the quantiles function. @@ -332,7 +218,7 @@ Or `PointSet` format Above, we saw the unary `toSampleSet`, which uses an internal hardcoded number of samples. If you'd like to provide the number of samples, it has a binary signature as well (floored) - + #### Validity @@ -372,7 +258,7 @@ You can cut off from the left You can cut off from the right - + You can cut off from both sides diff --git a/packages/website/docs/Features/Language.mdx b/packages/website/docs/Features/Language.mdx index 5b66d2e2..74c703ae 100644 --- a/packages/website/docs/Features/Language.mdx +++ b/packages/website/docs/Features/Language.mdx @@ -7,21 +7,21 @@ import { SquiggleEditor } from "../../src/components/SquiggleEditor"; ## Expressions -A distribution +### Distributions -A number +### Numbers - + -Arrays +### Arrays -Records +### Records = We can define functions ## See more diff --git a/packages/website/docs/Features/Node-Packages.md b/packages/website/docs/Features/Node-Packages.md index ab590c32..381cef1f 100644 --- a/packages/website/docs/Features/Node-Packages.md +++ b/packages/website/docs/Features/Node-Packages.md @@ -30,7 +30,7 @@ this library to help navigate the return type. The `@quri/squiggle-components` package offers several components and utilities for people who want to embed Squiggle components into websites. This documentation -relies on `@quri/squiggle-components` frequently. +uses `@quri/squiggle-components` frequently. We host [a storybook](https://squiggle-components.netlify.app/) with details and usage of each of the components made available.