Merge pull request #686 from quantified-uncertainty/documentation-refactor-June12-2022

Documentation refactor june12 2022
This commit is contained in:
Ozzie Gooen 2022-06-14 16:57:09 -07:00 committed by GitHub
commit 76281ee16d
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
22 changed files with 465 additions and 321 deletions

View File

@ -142,7 +142,7 @@ module DistributionOperation = {
| ToDist(Scale(#LogarithmWithThreshold(eps), r)) =>
`scaleLogWithThreshold(${E.Float.toFixed(r)}, epsilon=${E.Float.toFixed(eps)})`
| ToString(ToString) => `toString`
| ToString(ToSparkline(n)) => `toSparkline(${E.I.toString(n)})`
| ToString(ToSparkline(n)) => `sparkline(${E.I.toString(n)})`
| ToBool(IsNormalized) => `isNormalized`
| ToDistCombination(Algebraic(_), _, _) => `algebraic`
| ToDistCombination(Pointwise, _, _) => `pointwise`

View File

@ -295,7 +295,7 @@ module Float = {
let inv = (p, t: t) => p < t ? 0.0 : 1.0
let mean = (t: t) => Ok(t)
let sample = (t: t) => t
let toString = (t: t) => j`Delta($t)`
let toString = (t: t) => j`PointMass($t)`
let toPointSetDist = (t: t): PointSetTypes.pointSetDist => Discrete(
Discrete.make(~integralSumCache=Some(1.0), {xs: [t], ys: [1.0]}),
)

View File

@ -221,9 +221,9 @@ let dispatchToGenericOutput = (
}
| ("integralSum", [EvDistribution(dist)]) => Helpers.toFloatFn(#IntegralSum, dist, ~env)
| ("toString", [EvDistribution(dist)]) => Helpers.toStringFn(ToString, dist, ~env)
| ("toSparkline", [EvDistribution(dist)]) =>
| ("sparkline", [EvDistribution(dist)]) =>
Helpers.toStringFn(ToSparkline(MagicNumbers.Environment.sparklineLength), dist, ~env)
| ("toSparkline", [EvDistribution(dist), EvNumber(n)]) =>
| ("sparkline", [EvDistribution(dist), EvNumber(n)]) =>
Helpers.toStringFn(ToSparkline(Belt.Float.toInt(n)), dist, ~env)
| ("exp", [EvDistribution(a)]) =>
// https://mathjs.org/docs/reference/functions/exp.html
@ -273,6 +273,8 @@ let dispatchToGenericOutput = (
| ("cdf", [EvDistribution(dist), EvNumber(float)]) => Helpers.toFloatFn(#Cdf(float), dist, ~env)
| ("pdf", [EvDistribution(dist), EvNumber(float)]) => Helpers.toFloatFn(#Pdf(float), dist, ~env)
| ("inv", [EvDistribution(dist), EvNumber(float)]) => Helpers.toFloatFn(#Inv(float), dist, ~env)
| ("quantile", [EvDistribution(dist), EvNumber(float)]) =>
Helpers.toFloatFn(#Inv(float), dist, ~env)
| ("toSampleSet", [EvDistribution(dist), EvNumber(float)]) =>
Helpers.toDistFn(ToSampleSet(Belt.Int.fromFloat(float)), dist, ~env)
| ("toSampleSet", [EvDistribution(dist)]) =>

View File

@ -1,8 +1,23 @@
module Bindings = Reducer_Category_Bindings
module Module = Reducer_Category_Module
let m =
Module.emptyModule->Module.defineNumber("pi", Js.Math._PI)->Module.defineNumber("e", Js.Math._E)
let availableNumbers: array<(string, float)> = [
("pi", Js.Math._PI),
("e", Js.Math._E),
("ln2", Js.Math._LN2),
("ln10", Js.Math._LN10),
("log2e", Js.Math._LOG2E),
("log10e", Js.Math._LOG10E),
("sqrt2", Js.Math._SQRT2),
("sqrt1_2", Js.Math._SQRT1_2),
("phi", 1.618033988749895),
("tau", 6.283185307179586),
]
let mathBindings: Bindings.ExpressionT.bindings =
availableNumbers
->E.A2.fmap(((name, v)) => (name, ReducerInterface_ExpressionValue.EvNumber(v)))
->Belt.Map.String.fromArray
let makeBindings = (previousBindings: Bindings.t): Bindings.t =>
previousBindings->Bindings.defineModule("Math", m)
previousBindings->Bindings.defineModule("Math", mathBindings)

View File

@ -1,2 +1,3 @@
.docusaurus
build
docs/Api/.*

View File

@ -3,8 +3,12 @@ sidebar_position: 1
title: Date
---
Squiggle date types are a very simple implementation on [Javascript's Date type](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date). It's mainly here for early experimentation. There are more relevant functions for the [Duration](/docs/Api/Duration) type.
### makeFromYear
(Now `makeDateFromYear`)
```
Date.makeFromYear: (number) => date
```
@ -19,6 +23,16 @@ makeFromYear(2022.32);
toString: (date) => string
```
### add
```
add: (date, duration) => date
```
```js
makeFromYear(2022.32) + years(5);
```
### subtract
```
@ -30,13 +44,3 @@ subtract: (date, duration) => date
makeFromYear(2040) - makeFromYear(2020); // 20 years
makeFromYear(2040) - years(20); // 2020
```
### add
```
add: (date, duration) => date
```
```js
makeFromYear(2022.32) + years(5);
```

View File

@ -3,6 +3,34 @@ sidebar_position: 2
title: Dictionary
---
Squiggle dictionaries work similar to Python dictionaries. The syntax is similar to objects in Javascript.
Dictionaries are unordered and duplicates are not allowed. They are meant to be immutable, like most types in Squiggle.
**Example**
```javascript
valueFromOfficeItems = {
keyboard: 1,
chair: 0.01 to 0.5,
headphones: "ToDo"
}
valueFromHomeItems = {
monitor: 1,
bed: 0.2 to 0.6,
lights: 0.02 to 0.2,
coffee: 5 to 20
}
homeToItemsConversion = 0.1 to 0.4
conversionFn(i) = [i[0], i[1] * homeToItemsConversion]
updatedValueFromHomeItems = valueFromHomeItems |> Dict.toList |> map(conversionFn) |> Dict.fromList
allItems = merge(valueFromOfficeItems, updatedValueFromHomeItems)
```
### toList
```

View File

@ -3,50 +3,47 @@ sidebar_position: 3
title: Distribution
---
import Admonition from "@theme/Admonition";
import TOCInline from "@theme/TOCInline";
Distributions are the flagship data type in Squiggle. The distribution type is a generic data type that contains one of three different formats of distributions.
These subtypes are [point set](/docs/Api/DistPointSet), [sample set](/docs/Api/DistSampleSet), and symbolic. The first two of these have a few custom functions that only work on them. You can read more about the differences between these formats [here](/docs/Discussions/Three-Formats-Of-Distributions).
Several functions below only can work on particular distribution formats.
For example, scoring and pointwise math requires the point set format. When this happens, the types are automatically converted to the correct format. These conversions are lossy.
<TOCInline toc={toc} />
## Distribution Creation
### Normal Distribution
These are functions for creating primative distributions. Many of these could optionally take in distributions as inputs. In these cases, Monte Carlo Sampling will be used to generate the greater distribution. This can be used for simple hierarchical models.
**Definitions**
See a longer tutorial on creating distributions [here](/docs/Guides/DistributionCreation).
### normal
```javascript
normal: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
```
```javascript
normal: (dict<{p5: frValueDistOrNumber, p95: frValueDistOrNumber}>) => distribution
```
```javascript
normal: (dict<{mean: frValueDistOrNumber, stdev: frValueDistOrNumber}>) => distribution
normal: (distribution|number, distribution|number) => distribution
normal: (dict<{p5: distribution|number, p95: distribution|number}>) => distribution
normal: (dict<{mean: distribution|number, stdev: distribution|number}>) => distribution
```
**Examples**
```js
normal(5, 1);
normal({ p5: 4, p95: 10 });
normal({ mean: 5, stdev: 2 });
normal(5, 1)
normal({ p5: 4, p95: 10 })
normal({ mean: 5, stdev: 2 })
normal(5 to 10, normal(3, 2))
normal({ mean: uniform(5, 9), stdev: 3 })
```
### Lognormal Distribution
### lognormal
**Definitions**
```javascript
lognormal: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
```
```javascript
lognormal: (dict<{p5: frValueDistOrNumber, p95: frValueDistOrNumber}>) => distribution
```
```javascript
lognormal: (dict<{mean: frValueDistOrNumber, stdev: frValueDistOrNumber}>) => distribution
lognormal: (distribution|number, distribution|number) => distribution
lognormal: (dict<{p5: distribution|number, p95: distribution|number}>) => distribution
lognormal: (dict<{mean: distribution|number, stdev: distribution|number}>) => distribution
```
**Examples**
@ -57,12 +54,10 @@ lognormal({ p5: 4, p95: 10 });
lognormal({ mean: 5, stdev: 2 });
```
### Uniform Distribution
### uniform
**Definitions**
```javascript
uniform: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
```
uniform: (distribution|number, distribution|number) => distribution
```
**Examples**
@ -71,12 +66,10 @@ uniform: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
uniform(10, 12);
```
### Beta Distribution
### beta
**Definitions**
```javascript
beta: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
```
beta: (distribution|number, distribution|number) => distribution
```
**Examples**
@ -85,12 +78,10 @@ beta: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
beta(20, 25);
```
### Cauchy Distribution
### cauchy
**Definitions**
```javascript
cauchy: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
```
cauchy: (distribution|number, distribution|number) => distribution
```
**Examples**
@ -99,12 +90,22 @@ cauchy: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
cauchy(5, 1);
```
### Gamma Distribution
**Definitions**
### gamma
```javascript
gamma: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
gamma: (distribution|number, distribution|number) => distribution
```
**Examples**
```js
gamma(5, 1);
```
### logistic
```
logistic: (distribution|number, distribution|number) => distribution
```
**Examples**
@ -113,30 +114,53 @@ gamma: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
gamma(5, 1);
```
### Logistic Distribution
### exponential
**Definitions**
```javascript
logistic: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
```
exponential: (distribution|number) => distribution
```
**Examples**
```javascript
gamma(5, 1);
exponential(2);
```
### To (Distribution)
### bernoulli
**Definitions**
```javascript
to: (frValueDistOrNumber, frValueDistOrNumber) => distribution;
```
bernoulli: (distribution|number) => distribution
```
**Examples**
```javascript
credibleIntervalToDistribution(frValueDistOrNumber, frValueDistOrNumber) => distribution;
bernoulli(0.5);
```
### triangular
```javascript
triangular: (number, number, number) => distribution;
```
**Examples**
```javascript
triangular(5, 10, 20);
```
### to / credibleIntervalToDistribution
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.
`To` is an alias for `credibleIntervalToDistribution`. However, because of its frequent use, it is recommended to use the shorter name.
```
to: (distribution|number, distribution|number) => distribution
credibleIntervalToDistribution(distribution|number, distribution|number) => distribution
```
**Examples**
@ -147,97 +171,29 @@ to(5,10)
-5 to 5
```
### Exponential
### mixture
**Definitions**
```javascript
exponential: (frValueDistOrNumber) => distribution;
```
mixture: (...distributionLike, weights?:list<float>) => distribution
mixture: (list<distributionLike>, weights?:list<float>) => distribution
```
**Examples**
```javascript
exponential(2);
```
### Bernoulli
**Definitions**
```javascript
bernoulli: (frValueDistOrNumber) => distribution;
```
**Examples**
```javascript
bernoulli(0.5);
```
### toContinuousPointSet
Converts a set of points to a continuous distribution
**Definitions**
```javascript
toContinuousPointSet: (array<dict<{x: numeric, y: numeric}>>) => distribution
```
**Examples**
```javascript
toContinuousPointSet([
{ x: 0, y: 0.1 },
{ x: 1, y: 0.2 },
{ x: 2, y: 0.15 },
{ x: 3, y: 0.1 },
]);
```
### toDiscretePointSet
Converts a set of points to a discrete distribution
**Definitions**
```javascript
toDiscretePointSet: (array<dict<{x: numeric, y: numeric}>>) => distribution
```
**Examples**
```javascript
toDiscretePointSet([
{ x: 0, y: 0.1 },
{ x: 1, y: 0.2 },
{ x: 2, y: 0.15 },
{ x: 3, y: 0.1 },
]);
mixture(normal(5, 1), normal(10, 1), 8);
mx(normal(5, 1), normal(10, 1), [0.3, 0.7]);
mx([normal(5, 1), normal(10, 1)], [0.3, 0.7]);
```
## Functions
### mixture
```javascript
mixture: (...distributionLike, weights:list<float>) => distribution
```
**Examples**
```javascript
mixture(normal(5, 1), normal(10, 1));
mx(normal(5, 1), normal(10, 1), [0.3, 0.7]);
```
### sample
Get one random sample from the distribution
One random sample from the distribution
```javascript
sample(distribution) => number
```
sample: (distribution) => number
```
**Examples**
@ -248,66 +204,70 @@ sample(normal(5, 2));
### sampleN
Get n random samples from the distribution
N random samples from the distribution
```javascript
```
sampleN: (distribution, number) => list<number>
```
**Examples**
```javascript
sample: normal(5, 2), 100;
sampleN(normal(5, 2), 100);
```
### mean
Get the distribution mean
The distribution mean
```javascript
mean: (distribution) => number;
```
mean: (distribution) => number
```
**Examples**
```javascript
mean: normal(5, 2);
mean(normal(5, 2));
```
### stdev
```javascript
stdev: (distribution) => number;
Standard deviation. Only works now on sample set distributions (so converts other distributions into sample set in order to calculate.)
```
stdev: (distribution) => number
```
### variance
```javascript
variance: (distribution) => number;
Variance. Similar to stdev, only works now on sample set distributions.
```
variance: (distribution) => number
```
### mode
```javascript
mode: (distribution) => number;
```
mode: (distribution) => number
```
### cdf
```javascript
cdf: (distribution, number) => number;
```
cdf: (distribution, number) => number
```
**Examples**
```javascript
cdf: normal(5, 2), 3;
cdf(normal(5, 2), 3);
```
### pdf
```javascript
pdf: (distribution, number) => number;
```
pdf: (distribution, number) => number
```
**Examples**
@ -316,24 +276,26 @@ pdf: (distribution, number) => number;
pdf(normal(5, 2), 3);
```
### inv
### quantile
```javascript
inv: (distribution, number) => number;
```
quantile: (distribution, number) => number
```
**Examples**
```javascript
inv(normal(5, 2), 0.5);
quantile(normal(5, 2), 0.5);
```
### toPointSet
Converts a distribution to the pointSet format
**TODO: Will soon be called "PointSet.make"**
```javascript
toPointSet: (distribution) => pointSetDistribution;
Converts a distribution to the pointSet format.
```
toPointSet: (distribution) => pointSetDistribution
```
**Examples**
@ -344,10 +306,12 @@ toPointSet(normal(5, 2));
### toSampleSet
Converts a distribution to the sampleSet format, with n samples
**TODO: Will soon be called "SampleSet.make"**
```javascript
toSampleSet: (distribution, number) => sampleSetDistribution;
Converts a distribution to the sampleSet format, with n samples.
```
toSampleSet: (distribution, number) => sampleSetDistribution
```
**Examples**
@ -360,7 +324,7 @@ toSampleSet(normal(5, 2), 1000);
Truncates the left side of a distribution. Returns either a pointSet distribution or a symbolic distribution.
```javascript
```
truncateLeft: (distribution, l => number) => distribution
```
@ -374,7 +338,7 @@ truncateLeft(normal(5, 2), 3);
Truncates the right side of a distribution. Returns either a pointSet distribution or a symbolic distribution.
```javascript
```
truncateRight: (distribution, r => number) => distribution
```
@ -384,14 +348,12 @@ truncateRight: (distribution, r => number) => distribution
truncateLeft(normal(5, 2), 6);
```
## Scoring
### klDivergence
KullbackLeibler divergence between two distributions
[KullbackLeibler divergence](https://en.wikipedia.org/wiki/Kullback%E2%80%93Leibler_divergence) between two distributions.
```javascript
klDivergence: (distribution, distribution) => number;
```
klDivergence: (distribution, distribution) => number
```
**Examples**
@ -404,8 +366,8 @@ klDivergence(normal(5, 2), normal(5, 4)); // returns 0.57
### toString
```javascript
toString: (distribution) => string;
```
toString: (distribution) => string
```
**Examples**
@ -414,42 +376,46 @@ toString: (distribution) => string;
toString(normal(5, 2));
```
### toSparkline
### sparkline
Produce a sparkline of length n
Produce a sparkline of length n. For example, `▁▁▁▁▁▂▄▆▇██▇▆▄▂▁▁▁▁▁`. These can be useful for testing or quick text visualizations.
```javascript
toSparkline: (distribution, n = 20) => string;
```
sparkline: (distribution, n = 20) => string
```
**Examples**
```javascript
toSparkline(normal(5, 2), 10);
toSparkline(truncateLeft(normal(5, 2), 3), 20); // produces ▁▇█████▇▅▄▃▂▂▁▁▁▁▁▁▁
```
### inspect
Prints the value of the distribution to the Javascript console, then returns the distribution.
Prints the value of the distribution to the Javascript console, then returns the distribution. Useful for debugging.
```javascript
inspect: (distribution) => distribution;
```
inspect: (distribution) => distribution
```
**Examples**
```javascript
inspect(normal(5, 2));
inspect(normal(5, 2)); // logs "normal(5, 2)" to the javascript console and returns the distribution.
```
## Normalization
There are some situations where computation will return unnormalized distributions. This means that their cumulative sums are not equal to 1.0. Unnormalized distributions are not valid for many relevant functions; for example, klDivergence and scoring.
The only functions that do not return normalized distributions are the pointwise arithmetic operations and the scalewise arithmetic operations. If you use these functions, it is recommended that you consider normalizing the resulting distributions.
### normalize
Normalize a distribution. This means scaling it appropriately so that it's cumulative sum is equal to 1.
```javascript
normalize: (distribution) => distribution;
```
normalize: (distribution) => distribution
```
**Examples**
@ -462,8 +428,8 @@ normalize(normal(5, 2));
Check of a distribution is normalized. Most distributions are typically normalized, but there are some commands that could produce non-normalized distributions.
```javascript
isNormalized: (distribution) => bool;
```
isNormalized: (distribution) => bool
```
**Examples**
@ -474,10 +440,12 @@ isNormalized(normal(5, 2)); // returns true
### integralSum
Get the sum of the integral of a distribution. If the distribution is normalized, this will be 1.
**Note: If you have suggestions for better names for this, please let us know.**
```javascript
integralSum: (distribution) => number;
Get the sum of the integral of a distribution. If the distribution is normalized, this will be 1.0. This is useful for understanding unnormalized distributions.
```
integralSum: (distribution) => number
```
**Examples**
@ -486,151 +454,208 @@ integralSum: (distribution) => number;
integralSum(normal(5, 2));
```
## Algebraic Operations
## Regular Arithmetic Operations
Regular arithmetic operations cover the basic mathematical operations on distributions. They work much like their equivalent operations on numbers.
The infixes `+`,`-`, `*`, `/`, `^` are supported for addition, subtraction, multiplication, division, power, and unaryMinus.
```javascript
pointMass(5 + 10) == pointMass(5) + pointMass(10);
```
### add
```
add: (distributionLike, distributionLike) => distribution
```
**Examples**
```javascript
add: (distributionLike, distributionLike) => distribution;
normal(0, 1) + normal(1, 3); // returns normal(1, 3.16...)
add(normal(0, 1), normal(1, 3)); // returns normal(1, 3.16...)
```
### sum
```javascript
**Todo: Not yet implemented**
```
sum: (list<distributionLike>) => distribution
```
**Examples**
```javascript
sum([normal(0, 1), normal(1, 3), uniform(10, 1)]);
```
### multiply
```javascript
multiply: (distributionLike, distributionLike) => distribution;
```
multiply: (distributionLike, distributionLike) => distribution
```
### product
```javascript
```
product: (list<distributionLike>) => distribution
```
### subtract
```javascript
subtract: (distributionLike, distributionLike) => distribution;
```
subtract: (distributionLike, distributionLike) => distribution
```
### divide
```javascript
divide: (distributionLike, distributionLike) => distribution;
```
divide: (distributionLike, distributionLike) => distribution
```
### pow
```javascript
pow: (distributionLike, distributionLike) => distribution;
```
pow: (distributionLike, distributionLike) => distribution
```
### exp
```javascript
exp: (distributionLike, distributionLike) => distribution;
```
exp: (distributionLike, distributionLike) => distribution
```
### log
```javascript
log: (distributionLike, distributionLike) => distribution;
```
log: (distributionLike, distributionLike) => distribution
```
### log10
```javascript
log10: (distributionLike, distributionLike) => distribution;
```
log10: (distributionLike, distributionLike) => distribution
```
### unaryMinus
```javascript
unaryMinus: (distribution) => distribution;
```
unaryMinus: (distribution) => distribution
```
## Pointwise Operations
**Examples**
```javascript
-normal(5, 2); // same as normal(-5, 2)
unaryMinus(normal(5, 2)); // same as normal(-5, 2)
```
## Pointwise Arithmetic Operations
<Admonition type="caution" title="Unnormalized Results">
<p>
Pointwise arithmetic operations typically return unnormalized or completely
invalid distributions. For example, the operation{" "}
<code>normal(5,2) .- uniform(10,12)</code> results in a distribution-like
object with negative probability mass.
</p>
</Admonition>
Pointwise arithmetic operations cover the standard arithmetic operations, but work in a different way than the regular operations. These operate on the y-values of the distributions instead of the x-values. A pointwise addition would add the y-values of two distributions.
The infixes `.+`,`.-`, `.*`, `./`, `.^` are supported for their respective operations.
The `mixture` methods works with pointwise addition.
### dotAdd
```javascript
dotAdd: (distributionLike, distributionLike) => distribution;
```
dotAdd: (distributionLike, distributionLike) => distribution
```
### dotMultiply
```javascript
dotMultiply: (distributionLike, distributionLike) => distribution;
```
dotMultiply: (distributionLike, distributionLike) => distribution
```
### dotSubtract
```javascript
dotSubtract: (distributionLike, distributionLike) => distribution;
```
dotSubtract: (distributionLike, distributionLike) => distribution
```
### dotDivide
```javascript
dotDivide: (distributionLike, distributionLike) => distribution;
```
dotDivide: (distributionLike, distributionLike) => distribution
```
### dotPow
```javascript
dotPow: (distributionLike, distributionLike) => distribution;
```
dotPow: (distributionLike, distributionLike) => distribution
```
### dotExp
```javascript
dotExp: (distributionLike, distributionLike) => distribution;
```
dotExp: (distributionLike, distributionLike) => distribution
```
## Scale Operations
## Scale Arithmetic Operations
### scaleMultiply
<Admonition type="caution" title="Likely to change">
<p>
We're planning on removing scale operations in favor of more general
functions soon.
</p>
</Admonition>
```javascript
scaleMultiply: (distributionLike, number) => distribution;
Scale operations are similar to pointwise operations, but operate on a constant y-value instead of y-values coming from a distribution. You can think about this as scaling a distribution vertically by a constant.
The following items would be equivalent.
```js
scalePow(normal(5,2), 2)
mapY(normal(5,2), {|y| y ^ 2}) // Not yet available
```
### scalePow
```javascript
scalePow: (distributionLike, number) => distribution;
```
scalePow: (distributionLike, number) => distribution
```
### scaleExp
```javascript
scaleExp: (distributionLike, number) => distribution;
```
scaleExp: (distributionLike, number) => distribution
```
### scaleLog
```javascript
scaleLog: (distributionLike, number) => distribution;
```
scaleLog: (distributionLike, number) => distribution
```
### scaleLog10
```javascript
scaleLog10: (distributionLike, number) => distribution;
```
scaleLog10: (distributionLike, number) => distribution
```
## Special
### Declaration (Continuous Function)
### Declaration (Continuous Functions)
Adds metadata to a function of the input ranges. Works now for numeric and date inputs. This is useful when making predictions. It allows you to limit the domain that your prediction will be used and scored within.
Adds metadata to a function of the input ranges. Works now for numeric and date inputs. This is useful when making formal predictions. It allows you to limit the domain that your prediction will be used and scored within.
```javascript
Declarations are currently experimental and will likely be removed or changed in the future.
```
declareFn: (dict<{fn: lambda, inputs: array<dict<{min: number, max: number}>>}>) => declaration
```

View File

@ -3,20 +3,56 @@ sidebar_position: 4
title: Point Set Distribution
---
:::danger
These functions aren't yet implemented with these specific names. This should be changed soon
:::
Point set distributions are one of the three distribution formats. They are stored as a list of x-y coordinates representing both discrete and continuous distributions.
One complication is that it's possible to represent invalid probability distributions in the point set format. For example, you can represent shapes with negative values, or shapes that are not normalized.
### make
Converts the distribution in question into a point set distribution. If the distribution is symbolic, then it does this by taking the quantiles. If the distribution is a sample set, then it uses a version of kernel density estimation to approximate the point set format. One complication of this latter process is that if there is a high proportion of overlapping samples (samples that are exactly the same as each other), it will convert these samples into discrete point masses. Eventually we'd like to add further methods to help adjust this process.
```
PointSet.make: (distribution) => pointSetDist
```
### makeContinuous
**TODO: Now called "toContinuousPointSet"**
Converts a set of x-y coordinates directly into a continuous distribution.
```
PointSet.makeContinuous: (list<{x: number, y: number}>) => pointSetDist
```
```javascript
PointSet.makeContinuous([
{ x: 0, y: 0.1 },
{ x: 1, y: 0.2 },
{ x: 2, y: 0.15 },
{ x: 3, y: 0.1 },
]);
```
### makeDiscrete
**TODO: Now called "toDiscretePointSet"**
Converts a set of x-y coordinates directly into a discrete distribution.
```
PointSet.makeDiscrete: (list<{x: number, y: number}>) => pointSetDist
```
```javascript
PointSet.makeDiscrete([
{ x: 0, y: 0.1 },
{ x: 1, y: 0.2 },
{ x: 2, y: 0.15 },
{ x: 3, y: 0.1 },
]);
```

View File

@ -3,12 +3,22 @@ sidebar_position: 5
title: Sample Set Distribution
---
:::danger
These functions aren't yet implemented with these specific names. This should be added soon.
:::
Sample set distributions are one of the three distribution formats. Internally, they are stored as a list of numbers. It's useful to distinguish point set distributions from arbitrary lists of numbers to make it clear which functions are applicable.
Monte Carlo calculations typically result in sample set distributions.
All regular distribution function work on sample set distributions. In addition, there are several functions that only work on sample set distributions.
### make
```
SampleSet.make: (distribution) => sampleSet
SampleSet.make: (() => number) => sampleSet
SampleSet.make: (list<number>) => sampleSet
SampleSet.make: (() => number) => sampleSet // not yet implemented
```
### map
@ -35,7 +45,7 @@ SampleSet.map3: (sampleSet, sampleSet, sampleSet, ((number, number, number) => n
SampleSet.toList: (sampleSet) => list<number>
```
Gets the internal samples of a sampleSet distribution. This is separate from the sampleN() function, which would shuffle the samples. toList() maintains order and length. Gets the internal samples of a sampleSet distribution. This is separate from the sampleN() function, which would shuffle the samples. toList() maintains order and length.
Gets the internal samples of a sampleSet distribution. This is separate from the sampleN() function, which would shuffle the samples. toList() maintains order and length.
**Examples**

View File

@ -3,6 +3,10 @@ sidebar_position: 6
title: Duration
---
Duration works with the [Date](/docs/Api/Date) type. Similar to the Date implementation, the Duration functions are early and experimental. There is no support yet for date or duration probability distributions.
Durations are stored in Unix milliseconds.
import TOCInline from "@theme/TOCInline";
<TOCInline toc={toc} />

View File

@ -3,13 +3,21 @@ sidebar_position: 7
title: List
---
Squiggle lists are a lot like Python lists or Ruby arrays. They accept all types.
```javascript
myList = [3, normal(5, 2), "random"];
```
### make
**Note: currently just called `makeList`, without the preix**
```
List.make: (number, 'a) => list<'a>
```
Returns an array of size `n` filled with value `e`.
Returns an array of size `n` filled with the value.
```js
List.make(4, 1); // creates the list [1, 1, 1, 1]
@ -31,6 +39,8 @@ length: (list<'a>) => number
### up to
**Note: currently just called `upTo`, without the preix**
```
List.upTo: (low:number, high:number) => list<number>
```

View File

@ -6,7 +6,7 @@ title: Math
### E
```
Math.E:
Math.e:
```
Euler's number; ≈ 2.718281828459045
@ -14,7 +14,7 @@ Euler's number; ≈ 2.718281828459045
### LN2
```
Math.LN2:
Math.ln2:
```
Natural logarithm of 2; ≈ 0.6931471805599453
@ -22,7 +22,7 @@ Natural logarithm of 2; ≈ 0.6931471805599453
### LN10
```
Math.LN10:
Math.ln10:
```
Natural logarithm of 10; ≈ 2.302585092994046
@ -30,7 +30,7 @@ Natural logarithm of 10; ≈ 2.302585092994046
### LOG2E
```
Math.LOG2E:
Math.log2e:
```
Base 2 logarithm of E; ≈ 1.4426950408889634Base 2 logarithm of E; ≈ 1.4426950408889634
@ -38,7 +38,7 @@ Base 2 logarithm of E; ≈ 1.4426950408889634Base 2 logarithm of E; ≈ 1.442695
### LOG10E
```
Math.LOG10E:
Math.log10e:
```
Base 10 logarithm of E; ≈ 0.4342944819032518
@ -46,7 +46,7 @@ Base 10 logarithm of E; ≈ 0.4342944819032518
### PI
```
Math.PI:
Math.pi:
```
Pi - ratio of the circumference to the diameter of a circle; ≈ 3.141592653589793
@ -54,7 +54,7 @@ Pi - ratio of the circumference to the diameter of a circle; ≈ 3.1415926535897
### SQRT1_2
```
Math.SQRT1_2:
Math.sqrt1_2:
```
Square root of 1/2; ≈ 0.7071067811865476
@ -62,7 +62,7 @@ Square root of 1/2; ≈ 0.7071067811865476
### SQRT2
```
Math.SQRT2:
Math.sqrt2:
```
Square root of 2; ≈ 1.4142135623730951
@ -70,7 +70,7 @@ Square root of 2; ≈ 1.4142135623730951
### PHI
```
Math.PHI:
Math.phi:
```
Phi is the golden ratio. 1.618033988749895
@ -78,7 +78,7 @@ Phi is the golden ratio. 1.618033988749895
### TAU
```
Math.TAU:
Math.tau:
```
Tau is the ratio constant of a circle's circumference to radius, equal to 2 \* pi. 6.283185307179586

View File

@ -3,63 +3,67 @@ sidebar_position: 9
title: Number
---
Squiggle `numbers` are Javascript floats.
Many of the functions below work on lists or pairs of numbers.
import TOCInline from "@theme/TOCInline";
<TOCInline toc={toc} />
### ceil
```javascript
ceil: (number) => number;
```
ceil: (number) => number
```
### floor
```javascript
floor: (number) => number;
```
floor: (number) => number
```
### abs
```javascript
abs: (number) => number;
```
abs: (number) => number
```
### round
```javascript
round: (number) => number;
```
round: (number) => number
```
## Statistics
### max
```javascript
```
max: (list<number>) => number
```
### min
```javascript
```
min: (list<number>) => number
```
### mean
```javascript
```
mean: (list<number>) => number
```
### stdev
```javascript
```
stdev: (list<number>) => number
```
### variance
```javascript
```
variance: (list<number>) => number
```
@ -67,25 +71,25 @@ variance: (list<number>) => number
### unaryMinus
```javascript
unaryMinus: (number) => number;
```
unaryMinus: (number) => number
```
### equal
```javascript
equal: (number, number) => boolean;
```
equal: (number, number) => boolean
```
### add
```javascript
add: (number, number) => number;
```
add: (number, number) => number
```
### sum
```javascript
```
sum: (list<number>) => number
```
@ -97,13 +101,13 @@ cumsum: (list<number>) => list<number>
### multiply
```javascript
multiply: (number, number) => number;
```
multiply: (number, number) => number
```
### product
```javascript
```
product: (list<number>) => number
```
@ -115,30 +119,30 @@ cumprod: (list<number>) => list<number>
### subtract
```javascript
subtract: (number, number) => number;
```
subtract: (number, number) => number
```
### divide
```javascript
divide: (number, number) => number;
```
divide: (number, number) => number
```
### pow
```javascript
pow: (number, number) => number;
```
pow: (number, number) => number
```
### exp
```javascript
exp: (number) => number;
```
exp: (number) => number
```
### log
```javascript
log: (number) => number;
```
log: (number) => number
```

View File

@ -1,6 +1,6 @@
---
title: "Distribution Creation"
sidebar_position: 20
sidebar_position: 2
---
import { SquiggleEditor } from "../../src/components/SquiggleEditor";
@ -91,7 +91,7 @@ The `mixture` mixes combines multiple distributions to create a mixture. You can
### Arguments
- `distributions`: A set of distributions or numbers, each passed as a paramater. Numbers will be converted into Delta distributions.
- `distributions`: A set of distributions or numbers, each passed as a paramater. Numbers will be converted into point mass 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
@ -221,22 +221,22 @@ Creates a [uniform distribution](<https://en.wikipedia.org/wiki/Uniform_distribu
</p>
</Admonition>
## Delta
## Point Mass
`delta(value:number)`
`pointMass(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.
Few Squiggle users call the function `pointMass()` directly. Numbers are converted into point mass 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))`.
For example, in the function `mixture(1,2,normal(5,2))`, the first two arguments will get converted into point mass distributions
with values at 1 and 2. Therefore, this is the same as `mixture(pointMass(1),pointMass(2),pointMass(5,2))`.
`Delta()` distributions are currently the only discrete distributions accessible in Squiggle.
`pointMass()` distributions are currently the only discrete distributions accessible in Squiggle.
<Tabs>
<TabItem value="ex1" label="delta(3)" default>
<SquiggleEditor initialSquiggleString="delta(3)" />
<TabItem value="ex1" label="pointMass(3)" default>
<SquiggleEditor initialSquiggleString="pointMass(3)" />
</TabItem>
<TabItem value="ex3" label="mixture(1,3,5)">
<SquiggleEditor initialSquiggleString="mixture(1,3,5)" />

View File

@ -1,5 +1,5 @@
---
title: "Functions Reference"
title: "Distribution Functions"
sidebar_position: 3
---
@ -170,7 +170,7 @@ given point x.
### Cumulative density function
The `cdf(dist, x)` gives the cumulative probability of the distribution
or all values lower than x. It is the inverse of `inv`.
or all values lower than x. It is the inverse of `quantile`.
<SquiggleEditor initialSquiggleString="cdf(normal(0,1),0)" />
@ -179,13 +179,13 @@ or all values lower than x. It is the inverse of `inv`.
- `x` must be a scalar
- `dist` must be a distribution
### Inverse CDF
### Quantile
The `inv(dist, prob)` gives the value x or which the probability for all values
The `quantile(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`. In the literature, it
is also known as the quantiles function.
<SquiggleEditor initialSquiggleString="inv(normal(0,1),0.5)" />
<SquiggleEditor initialSquiggleString="quantile(normal(0,1),0.5)" />
#### Validity

View File

@ -49,6 +49,6 @@ ozzie_estimate(1) * nuno_estimate(1, 1)`}
## See more
- [Distribution creation](./Distributions)
- [Distribution creation](./DistributionCreation)
- [Functions reference](./Functions)
- [Gallery](../Discussions/Gallery)

View File

@ -122,14 +122,14 @@ TODO
TODO
## `pdf`, `cdf`, and `inv`
## `pdf`, `cdf`, and `quantile`
With $\forall dist, pdf := x \mapsto \texttt{pdf}(dist, x) \land cdf := x \mapsto \texttt{cdf}(dist, x) \land inv := p \mapsto \texttt{inv}(dist, p)$,
With $\forall dist, pdf := x \mapsto \texttt{pdf}(dist, x) \land cdf := x \mapsto \texttt{cdf}(dist, x) \land quantile := p \mapsto \texttt{quantile}(dist, p)$,
### `cdf` and `inv` are inverses
### `cdf` and `quantile` are inverses
$$
\forall x \in (0,1), cdf(inv(x)) = x \land \forall x \in \texttt{dom}(cdf), x = inv(cdf(x))
\forall x \in (0,1), cdf(quantile(x)) = x \land \forall x \in \texttt{dom}(cdf), x = quantile(cdf(x))
$$
### The codomain of `cdf` equals the open interval `(0,1)` equals the codomain of `pdf`

View File

@ -25,7 +25,7 @@ $$
a \cdot Normal(\mu, \sigma) = Normal(a \cdot \mu, |a| \cdot \sigma)
$$
We can now look at the inverse cdf of a $Normal(0,1)$. We find that the 95% point is reached at $1.6448536269514722$. ([source](https://stackoverflow.com/questions/20626994/how-to-calculate-the-inverse-of-the-normal-cumulative-distribution-function-in-p)) This means that the 90% confidence interval is $[-1.6448536269514722, 1.6448536269514722]$, which has a width of $2 \cdot 1.6448536269514722$.
We can now look at the quantile of a $Normal(0,1)$. We find that the 95% point is reached at $1.6448536269514722$. ([source](https://stackoverflow.com/questions/20626994/how-to-calculate-the-inverse-of-the-normal-cumulative-distribution-function-in-p)) This means that the 90% confidence interval is $[-1.6448536269514722, 1.6448536269514722]$, which has a width of $2 \cdot 1.6448536269514722$.
So then, if we take a $Normal(0,1)$ and we multiply it by $\frac{(high -. low)}{(2. *. 1.6448536269514722)}$, it's 90% confidence interval will be multiplied by the same amount. Then we just have to shift it by the mean to get our target normal.

View File

@ -66,7 +66,7 @@ const config = {
},
{
type: "doc",
docId: "Api/Dictionary",
docId: "Api/DistGeneric",
position: "left",
label: "API",
},

View File

@ -26,6 +26,11 @@ const sidebars = {
id: "Introduction",
label: "Introduction",
},
{
type: "doc",
id: "Node-Packages",
label: "Node Packages",
},
{
type: "category",
label: "Guides",