variate

package module
v0.4.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 21, 2026 License: AGPL-3.0 Imports: 21 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Variate

A Monte Carlo engine for event-driven risk and cost models, in Go, with exact answers wherever the model allows them.

A model is a directed acyclic graph. Sources emit events at a rate per period; each event walks the graph from the node it enters, booking values at the nodes it passes, choosing an outcome at each, and holding for a while where the model says so. The engine simulates periods and reports the period total, its breakdown by category and source, the events and values at each node, quantiles, the exceedance curve and who the tail belongs to. Beside the simulation it computes the exact mean, variance and probability of an empty period from the graph, and for most models the exact distribution of the period total by FFT, bracketed between rigorous bounds, with no sampling at all.

What a model can say

  • Rates: a constant or an uncertain rate drawn once per period (Poisson or mixed-Poisson counts); a source that fires on every n-th arrival of its stream; a source silent for a repair after each firing; a reliability block diagram of components with mean times between failures and repairs, simulated exactly as a Markov chain of the units; and shared factors that scale several rates at once, the common shock that makes a bad year bad for every risk together; and schedules, cycles of multipliers that give a rate its season or shift pattern.
  • Nodes: values booked on entry or per unit of time held, in any of twenty-two distribution families with truncation and caps; a selection of outcomes with fixed or uncertain probabilities, as shares or tried in order; holding times, including the outage of the reliability block that fired the event; values and probabilities drawn once per period and shared by every event in it.
  • Structure: several graphs in one model, templates instanced with overrides, categories added across the model; totals the model names over chosen categories, each reported as the total is, a net one subtracting some of them with the chance it is at or below zero, and categories kept outside the total, such as hours or revenue beside cost.
  • Queues: a node that serves its rounds first come, first served with a number of servers of one speed, each round bringing its own work, carrying its line from period to period or emptying it at each period's end; the report gives the wait and stay with their quantiles, the line and the servers' utilisation.
  • Where it starts: the steady state, or a started run, a horizon of periods repeated from an empty start or from a given state, the rounds waiting or in service at each queue with their ages and the rounds part-way through a holding time, reported period by period with each period's exact mean where the paths allow, beside the horizon's total.

docs/format.md is the reference for the YAML model file, and examples/ holds twenty-eight complete models with a README saying what each shows, from a one-line compound loss to a register of a hundred risks, a plant as a block diagram, and a shift with its own period.

Running

go run ./cmd/variate run -f examples/compound.yaml          # simulate to the plan's criteria
go run ./cmd/variate run -f examples/compound.yaml --analytic   # with the exact distribution
go run ./cmd/variate plan -f examples/compound.yaml         # the convergence plan and work
go run ./cmd/variate stream -f examples/sequential.yaml --leaf undetected --rounds csv
go run ./cmd/variate sweep -f examples/pump_station.yaml --figure p99 --top 5
go run ./cmd/variate compare -f examples/pump_station.yaml --option other.yaml --figure p99

run reports a table, JSON or CSV, and with --at total=150 (or --at category:labour=40, repeated as needed) also the chance a period reaches each value and of staying under it, counted in the run with its standard error rather than read off the histogram. With --when total>=1/100 (a value, or 1/N for the level reached once in N periods, or a band such as --when "total in [1/10,1/100)") it also says what those periods are made of: each category's, source's and node's mean in them and share of their total, each with its standard error, and a return period's level with its error; plan says how many periods each convergence criterion needs and what the run will cost; stream writes the rounds, the path each event takes with the values it books, filtered to a node or a leaf; sweep moves each input the model gives a range, how far its frequency, value, probability, holding time, factor, schedule or block component's MTBF or MTTR could plausibly be off, to the two ends of that range and ranks the inputs by how far they move a figure: the mean, a quantile, a return period's loss, P(T = 0), or a layer's, category's or source's mean (--screen 0.1 moves every input by a tenth instead, to see which deserve a range). Its rows are exact where the analytic means give the figure, brackets where the exact distribution applies, and otherwise simulated at one seed, the moved models drawing alike wherever the move does not reach, so that each difference's standard error is measured on paired blocks: every draw is keyed by what it is, its period, source, round and the node, function or holding by name, not by its place in the model. compare sets options against the model, each a model file of its own run with the model's settings: each option's figure, its difference from the model's and, for a simulated row, that difference's standard error on the same paired blocks, a small fraction of what two independent runs would give where an option changes little. A run without a period count continues until every criterion is met: enough hits on every outcome, a small enough error on every mean, enough periods in the tail. The same model, seed and block size repeat a run exactly.

The browser demo

make demo builds the engine to WebAssembly with TinyGo and serves a page at http://127.0.0.1:8000/ with every example as a model with knobs, or any model pasted as YAML. A run draws the histogram and exceedance curve of the total or of any category, source, node or trigger's sum, with return periods and the exact bounds when asked for; the sources' contributions and who the tail belongs to beyond a return period; a source's events per period against a Poisson reference; the totals over the run; what the uncertain inputs could do to the mean, as a tornado chart; and the compiled graph as a flow diagram. A run can be pinned as a baseline and the next drawn beside it, for cheaper-and-slower against faster-and-dearer. The page lives under web/; cmd/variate-wasm is the engine's browser entry point. A host that builds the engine into its own WebAssembly applies the same limits with browser.Apply: one worker, and the transform's work and memory budgets that keep it within a browser's time and wasm32's memory.

From Python

The variate-python repository, MIT-licensed, builds a model in Python and runs it through the variate command, the model crossing as a YAML file and the report returning as JSON. The engine runs as a separate program, so a notebook, a library or a product built on the package takes on none of the engine's obligations; embedding the engine itself is what this repository's licence and its commercial licences cover. variate plan --format json, variate sweep --format json and the series in the JSON report exist for it.

Building and testing

make ci runs what runs on every push: formatting, vet, the linters and the project's own analyzers, the escape and allocation checks on the hot path, the race detector, the suite again with a 32-bit int (the width of TinyGo's wasm target), a TinyGo build of the browser engine, the fuzzers and the vulnerability scan. make stat is the long statistical suite, make bench the benchmarks against a baseline, make wasm-test the engine's tests as wasm under the wazero runtime, and make race the race detector run. The engine's test suites live in internal/suite, against the public API only; the root keeps the tests that reach inside. internal/lint is a separate module holding the project's checkers. The engine allocates nothing while a run is going, has no recursion and bounds every loop, and the build checks each of these with a tool wherever a tool can.

Licence

Copyright © 2026 Eitanity Systems VCC.

Variate is free software under the GNU Affero General Public License, version 3 (see LICENSE). Any work that links it, calls it over a network or ships it must be offered under the same terms, source included. Commercial licences are available for those terms do not suit.

Documentation

Overview

Package variate is the engine: the graph model, compilation to flat index arrays, the period-block simulation, the workspace with its fixed heap, the round stream, analytic expectations and the FFT transform.

Index

Examples

Constants

View Source
const (
	InputFactor      = "factor"
	InputSchedule    = "schedule"
	InputFrequency   = "frequency"
	InputRepair      = "repair"
	InputFunction    = "function"
	InputProbability = "probability"
	InputHolding     = "holding"
	InputMTBF        = "mtbf"
	InputMTTR        = "mttr"
)

The kinds of input a sweep can scale.

View Source
const (
	MethodExact      = "exact"      // the analytic expectations
	MethodTransform  = "transform"  // the transform's bracket
	MethodSimulation = "simulation" // paired fixed runs at one seed
)

The ways a sweep row is computed, cheapest first.

Variables

View Source
var ErrStop = errors.New("stop")

ErrStop is returned by an Observer to end the run cleanly.

Functions

func ChainFigures

func ChainFigures(chains []Chain) (rate, unavailability float64)

ChainFigures returns the stationary failure frequency per period of a source's chains in series and the share of time it is down.

func LayerBoundsAt

func LayerBoundsAt(b Bounds, y Layer, x float64) (lo, hi float64)

LayerBoundsAt reads a bracket on the layer's payout at x from the total's bracket: the payout reaches x when the total reaches the attachment plus x over the share, and never exceeds the share times the limit.

func QuantileLevels added in v0.3.0

func QuantileLevels() [5]float64

QuantileLevels returns the levels of P50, P90, P95, P99 and P999.

func QueueColumns added in v0.3.0

func QueueColumns() []string

Queues are the queue column names, in the order of Queue's col.

func WhenName added in v0.3.0

func WhenName(c When) string

WhenName is how a condition names its quantity and bounds, as the command line writes it: total>=1/100, category:damage in [5e5,1e6).

Types

type Accum

type Accum struct {
	Sum   stats.Neumaier // compensated sum over periods
	W     stats.Welford  // count, mean and M2 over periods
	Block stats.Welford  // over the means of full blocks
	Min   float64
	Max   float64
	Zero  int64          // periods with exactly 0
	Hist  *stats.LogHist // nil when the quantity has no histogram

	// With delays, coarse histograms of the full blocks in batchGroups
	// groups, block b in group b mod batchGroups, and the periods each
	// holds; nil without delays or a histogram. Where the groups are
	// independent timelines, GroupSum is each one's sum over its full
	// blocks, and GroupN is kept for every quantity.
	Groups   []*stats.LogHist
	GroupN   []int64
	GroupSum []stats.Neumaier
}

Accum is the streamed statistics of one per-period quantity.

func (*Accum) Inflation added in v0.3.0

func (a *Accum) Inflation(x float64) float64

Inflation is the ratio of the batch-means standard error of the share of periods at or above x to its binomial standard error: 1 for independent periods, and with delays measured from the group histograms at the coarse bin holding x. NaN below minBlocks full blocks. Where every or no full-block period reaches x, the groups cannot measure it, and it is 1.

func (*Accum) Mean

func (a *Accum) Mean() float64

Mean is the mean per period.

func (*Accum) N

func (a *Accum) N() int64

N is the number of periods accumulated.

func (*Accum) StdDev

func (a *Accum) StdDev() float64

StdDev is the sample standard deviation over periods.

func (*Accum) StdErr

func (a *Accum) StdErr(delays bool) float64

StdErr is the standard error of the mean: from the periods without delays; with delays, from the means of the independent timelines where the run has them, else from the block means; NaN below 16 full blocks.

type Basis

type Basis uint8

Basis says how a function books its value: once per trigger, or as a rate multiplied by the holding time of the outcome taken.

const (
	OnEntry Basis = iota
	PerTime
)

type Bound added in v0.3.0

type Bound struct {
	X, OneIn float64
}

Bound is a level of a quantity: a value X, or, with OneIn ≥ 1, the level reached once in OneIn periods, which the run estimates as the (1 − 1/OneIn) quantile of what it saw.

type Bounds

type Bounds struct {
	H            float64
	Lower, Upper []float64
	DiscGap      []float64
	Alias        float64
	Roundoff     []float64
}

Bounds brackets P(T ≥ x) at x = 0, h, 2h, …, with the parts of the bracket reported separately.

func (Bounds) LayerMean

func (b Bounds) LayerMean(y Layer) (lo, hi float64)

LayerMean brackets E[payout] of a layer from a bracket on P(T ≥ x): the payout is the share times the integral of P(T ≥ t) over the band, and on each lattice cell the lower curve at the cell's end and the upper curve at its start bound the integrand.

func (Bounds) Quantile

func (b Bounds) Quantile(p float64) (lo, hi float64)

Quantile brackets the p-quantile of T: the smallest lattice points at which the upper and lower curves fall to 1 − p.

type Chain

type Chain struct {
	K, N         int
	Fail, Repair float64
	MTBFRange    *InputRange // how uncertain a unit's mean up time 1/Fail is, in periods, for a sweep; nil = not swept
	MTTRRange    *InputRange // how uncertain a unit's mean repair time 1/Repair is, in periods; nil = not swept
}

Chain is one block of a reliability diagram the engine simulates exactly: N identical units of which K must be working, each failing at rate Fail while up and repaired at rate Repair while down, both per period. A Repair of 0 means a unit is replaced at once. A source's chains are in series: the source is up when every chain has at least K working units, and it fires when that stops being so.

type CompareConfig added in v0.4.0

type CompareConfig struct {
	// Figure is the quantity compared, as a sweep's: "mean" (the
	// default), "p<percent>", "rp:<periods>", "pzero", "layer:<id>",
	// "category:<name>" or "source:<id>".
	Figure string
	// Run compiles every model and runs the simulated rows: its Seed is
	// the one seed of every run, its Periods their length (0 = the length
	// the base run's plan settles on).
	Run Config
}

CompareConfig is what a comparison reports and how its runs go.

type CompareRow added in v0.4.0

type CompareRow struct {
	Method string
	// Base is the base model's figure by the row's method, Value the
	// option's.
	Base, Value Range
	// Diff is Value − Base: one point when exact or simulated, the
	// widest difference of the two brackets otherwise.
	Diff Range
	// SE is the standard error of Diff: 0 when exact, NaN for a bracket
	// or too few blocks, and for a simulated row measured on the two
	// runs' paired blocks.
	SE float64
}

CompareRow is one option against the base: both figures by one method, and the option's difference from the base with its standard error.

type Comparison added in v0.4.0

type Comparison struct {
	Figure  string
	Seed    uint64
	Periods int64 // of the simulated rows; 0 when there are none
	Rows    []CompareRow
}

Comparison is each option against the base, in the options' order.

type Compiled

type Compiled struct {
	// contains filtered or unexported fields
}

Compiled is a validated, flattened model.

func (*Compiled) Analytic

func (m *Compiled) Analytic() (*Expectation, error)

Analytic computes the exact expectations of the model; with Config.NoBreakdown or Config.NoBreakdownVariance the per-source, per-category and per-node variances are NaN, left uncomputed.

func (*Compiled) Binding

func (m *Compiled) Binding() (criterion, driver string)

Binding returns the criterion and driver with the largest need.

func (*Compiled) BurnIn added in v0.3.0

func (m *Compiled) BurnIn() int64

BurnIn returns the burn-in in periods.

func (*Compiled) Categories

func (m *Compiled) Categories() []string

Categories returns the category names in index order.

func (*Compiled) DiscountFactors added in v0.4.0

func (m *Compiled) DiscountFactors() []float64

DiscountFactors is each period's factor, nil without a discount.

func (*Compiled) Discounted added in v0.4.0

func (m *Compiled) Discounted() bool

Discounted reports whether the run discounts any category.

func (*Compiled) DiscountedCategories added in v0.4.0

func (m *Compiled) DiscountedCategories() []string

DiscountedCategories names the categories discounted.

func (*Compiled) Firings added in v0.2.0

func (m *Compiled) Firings() []Firing

Firings returns each trigger's P(fire).

func (*Compiled) GivenState added in v0.3.0

func (m *Compiled) GivenState() bool

GivenState reports whether a started run starts from a given state.

func (*Compiled) HasDelays

func (m *Compiled) HasDelays() bool

HasDelays reports whether any outcome has a holding time.

func (*Compiled) HasQueues added in v0.3.0

func (m *Compiled) HasQueues() bool

HasQueues reports whether any node is a queue.

func (*Compiled) HasRepair

func (m *Compiled) HasRepair() bool

HasRepair reports whether a source is silent for a repair after each firing, which leaves the variance and P(T = 0) without a closed form.

func (*Compiled) HasTriggers added in v0.2.0

func (m *Compiled) HasTriggers() bool

HasTriggers reports whether the model has a trigger, whose firing moves with the rest of the total and leaves the variance without a closed form.

func (*Compiled) Horizon added in v0.3.0

func (m *Compiled) Horizon() int

Horizon is a started run's periods per repeat; 0 in steady state.

func (*Compiled) InTotal added in v0.4.0

func (m *Compiled) InTotal(c int) bool

InTotal reports whether category c is booked into the total.

func (*Compiled) LatticeUnit

func (m *Compiled) LatticeUnit() float64

LatticeUnit is the value every period total is a multiple of when each function is a constant booked on entry, or 0 when the total can take values between multiples.

func (*Compiled) Layers

func (m *Compiled) Layers() []Layer

Layers are the model's layers, with their defaults filled in.

func (*Compiled) Levels added in v0.3.0

func (m *Compiled) Levels() []Level

Levels returns Config.At as compiled.

func (*Compiled) LongestPath

func (m *Compiled) LongestPath() int

LongestPath is the number of nodes on the longest source-to-leaf path: the step capacity a round needs.

func (*Compiled) NewWorkspace

func (m *Compiled) NewWorkspace(cfg Config) (*Workspace, error)

NewWorkspace allocates everything a run needs, sized from the model and the configuration, and starts the worker pool.

Example

A fixed run of a compiled model: the workspace holds every buffer, Run fills its Result, Summarize turns the result into named statistics.

package main

import (
	"context"
	"fmt"

	"code.eitanity.com/variate"
	"code.eitanity.com/variate/dist"
)

// compoundModel is the smallest graph: a source with an uncertain rate
// feeding one node that books a value per event.
func compoundModel() variate.Graph {
	rate, _ := dist.NewPERT(2, 5, 12, dist.DefaultPERTShape)
	severity, _ := dist.NewLognormalFromMedianP90(1000, 5000)
	return variate.Graph{
		ID:      "compound",
		Sources: []variate.Source{{ID: "incident", Frequency: rate, To: "loss"}},
		Nodes: []variate.Node{{
			ID:        "loss",
			Functions: []variate.Function{{Name: "cost", Category: "money", Model: severity}},
		}},
	}
}

func main() {
	m, _, _ := compoundModel().Compile(variate.Config{})
	cfg := variate.Config{Periods: 20000}
	w, err := m.NewWorkspace(cfg)
	if err != nil {
		fmt.Println(err)
		return
	}
	defer w.Close()
	r, err := w.Run(context.Background(), 42)
	if err != nil {
		fmt.Println(err)
		return
	}
	var s variate.Summary
	w.Summarize(&s)
	e, _ := m.Analytic()
	z := (s.Total.Mean - e.Mean) / s.Total.StdErr
	fmt.Printf("periods %d  mean within 3 standard errors of exact: %v\n", r.Periods, z > -3 && z < 3)
	fmt.Printf("p50 and p99 ordered: %v\n", s.Total.P50 < s.Total.P99)
	bands := w.Bands([]float64{0, 5000, 20000, 1e9}, make([]float64, 3))
	fmt.Printf("bands sum to one: %v\n", bands[0]+bands[1]+bands[2] > 0.999)
}
Output:
periods 20000  mean within 3 standard errors of exact: true
p50 and p99 ordered: true
bands sum to one: true

func (*Compiled) NodeIDs

func (m *Compiled) NodeIDs() []string

NodeIDs returns the node names in index order.

func (*Compiled) NodeOrder

func (m *Compiled) NodeOrder() []string

NodeOrder is the node identifiers in topological order, every node after the nodes that lead to it.

func (*Compiled) OutcomeNames

func (m *Compiled) OutcomeNames() []string

OutcomeNames returns the outcome names in index order.

func (*Compiled) Phase added in v0.1.4

func (m *Compiled) Phase() Phase

Phase is the phase the model was fixed at; Index 0 for the whole cycle.

func (*Compiled) Plan

func (m *Compiled) Plan() []PlanRow

Plan returns the sizing table: one row per criterion, with the periods it needs; Observed and Met are unset.

func (*Compiled) PlanPeriods

func (m *Compiled) PlanPeriods(batchPeriods int64) int64

PlanPeriods is the plan's run length: the largest need, rounded up to whole batches of blocks.

func (*Compiled) Pools

func (m *Compiled) Pools() []dist.Distribution

Pools returns the distributions by pool index.

func (*Compiled) QueueIDs added in v0.3.0

func (m *Compiled) QueueIDs() []string

QueueIDs returns the queue nodes' names in queue order.

func (*Compiled) QueueLongRun added in v0.3.0

func (m *Compiled) QueueLongRun(c int) QueueLongRun

QueueLongRun returns queue c's long-run figures.

func (*Compiled) QueueServers added in v0.3.0

func (m *Compiled) QueueServers(i int) int

QueueServers returns queue i's servers.

func (*Compiled) QueueStdErrUnreliable added in v0.3.0

func (m *Compiled) QueueStdErrUnreliable(c int) bool

QueueStdErrUnreliable reports whether queue c's wait and stay have infinite variance, so that their standard errors mean nothing.

func (*Compiled) Simulate

func (m *Compiled) Simulate(ctx context.Context, cfg Config) (*Result, error)

Simulate is the one-shot form: a workspace for cfg, one run with cfg.Seed, or a random seed when that is 0, and the workspace closed. The Result stays valid and records the seed.

Example

An adaptive run stops when every convergence criterion is met.

package main

import (
	"context"
	"fmt"

	"code.eitanity.com/variate"
	"code.eitanity.com/variate/dist"
)

// compoundModel is the smallest graph: a source with an uncertain rate
// feeding one node that books a value per event.
func compoundModel() variate.Graph {
	rate, _ := dist.NewPERT(2, 5, 12, dist.DefaultPERTShape)
	severity, _ := dist.NewLognormalFromMedianP90(1000, 5000)
	return variate.Graph{
		ID:      "compound",
		Sources: []variate.Source{{ID: "incident", Frequency: rate, To: "loss"}},
		Nodes: []variate.Node{{
			ID:        "loss",
			Functions: []variate.Function{{Name: "cost", Category: "money", Model: severity}},
		}},
	}
}

func main() {
	m, _, _ := compoundModel().Compile(variate.Config{MinHits: 100, TargetRSE: 0.05, ContribRSE: 0.05, TailP: 0.99, TailHits: 20})
	r, err := m.Simulate(context.Background(), variate.Config{MinHits: 100, TargetRSE: 0.05, ContribRSE: 0.05, TailP: 0.99, TailHits: 20, Seed: 1})
	if err != nil {
		fmt.Println(err)
		return
	}
	fmt.Printf("converged %v  periods > 0: %v\n", r.Converged, r.Periods > 0)
}
Output:
converged true  periods > 0: true

func (*Compiled) SourceIDs

func (m *Compiled) SourceIDs() []string

SourceIDs returns the source names in index order.

func (*Compiled) StartState added in v0.3.0

func (m *Compiled) StartState() []string

StartState describes a started run's given state, an entry a line: the mean rounds and where they are, and whether what is left of a service or a holding follows the time so far or, not given, the long-run residual.

func (*Compiled) Started added in v0.3.0

func (m *Compiled) Started() bool

Started reports whether the model is a started run.

func (*Compiled) StdErrUnreliable added in v0.3.0

func (m *Compiled) StdErrUnreliable(col int) bool

StdErrUnreliable reports whether the quantity in column col, in the order of the series' columns, has infinite variance, so that its standard error means nothing.

func (*Compiled) Structure

func (m *Compiled) Structure() Structure

Structure returns the graph's drawing description.

func (*Compiled) TotalIDs added in v0.4.0

func (m *Compiled) TotalIDs() []string

TotalIDs returns the named totals' ids in the model's order.

func (*Compiled) Transform

func (m *Compiled) Transform(cfg TransformConfig) (*Transformed, error)

Transform computes the distribution of the period total by FFT with a bracket, for models without delays.

Example

The exact distribution of the period total, where the transform applies: a bracket on P(T >= x) and on every quantile.

package main

import (
	"fmt"

	"code.eitanity.com/variate"
	"code.eitanity.com/variate/dist"
)

// compoundModel is the smallest graph: a source with an uncertain rate
// feeding one node that books a value per event.
func compoundModel() variate.Graph {
	rate, _ := dist.NewPERT(2, 5, 12, dist.DefaultPERTShape)
	severity, _ := dist.NewLognormalFromMedianP90(1000, 5000)
	return variate.Graph{
		ID:      "compound",
		Sources: []variate.Source{{ID: "incident", Frequency: rate, To: "loss"}},
		Nodes: []variate.Node{{
			ID:        "loss",
			Functions: []variate.Function{{Name: "cost", Category: "money", Model: severity}},
		}},
	}
}

func main() {
	m, _, _ := compoundModel().Compile(variate.Config{})
	tr, err := m.Transform(variate.TransformConfig{Tol: 1e-2})
	if err != nil {
		fmt.Println(err)
		return
	}
	lo, hi := tr.Total.Quantile(0.99)
	fmt.Printf("applicable %v  grid %d  P99 within [%.0f, %.0f]\n", tr.Applicable, tr.M, lo, hi)
}
Output:
applicable true  grid 65536  P99 within [56382, 56437]

func (*Compiled) TransformEntries

func (m *Compiled) TransformEntries(cfg TransformConfig) (*Counts, error)

TransformEntries computes the distribution of every node's entries per period: Poisson given the period draws, mixed over them.

func (*Compiled) Transformed

func (m *Compiled) Transformed() *Transformed

Transformed returns the transform computed at compile, or nil.

func (*Compiled) Whens added in v0.3.0

func (m *Compiled) Whens() []When

Whens returns Config.When as compiled.

type Config

type Config struct {
	Periods          int64
	Repeats          int64   // a started run's repeats of its horizon; 0 = the plan decides
	AllowUnconverged bool    // run to the caps when the plan exceeds them
	Transform        bool    // compute the transform at compile; the tail criterion then counts periods beyond its quantile
	TransformGrid    int     // largest grid of that transform; 0 = the transform's default
	TransformTol     float64 // its tolerance; 0 = the default
	TransformWork    int64   // its work budget; 0 = the default
	TransformBytes   int64   // what a transform pass may allocate; 0 = the default
	MinHits          uint64
	ContribRSE       float64
	TargetRSE        float64
	TailP            float64
	TailHits         uint64
	MaxPeriods       int64
	MaxSteps         uint64
	Batch            int
	HistRes          float64

	Seed         uint64
	Workers      int
	BlockPeriods int
	Series       bool
	NoBreakdown  bool
	NodeHist     bool
	BurnIn       int
	MaxMemory    int64
	Observer     Observer
	Watch        Watch
	Pace         time.Duration
	RoundScratch int
	RecordBuffer int

	// At names values whose chance of being reached the run counts:
	// for each, the share of periods (of repeats, in a started run) in
	// which the quantity is at least the value, with its error.
	At []Level

	// When names conditions on a quantity whose periods the run
	// describes: for each, the chance of meeting it, and over the periods
	// (repeats, in a started run) that meet it, every quantity's mean and
	// share of their total, each with its error.
	When []When

	// NoBreakdownVariance leaves the per-category, per-source and
	// per-node variances uncomputed, as on a large model they are most of
	// what Compile costs: the breakdowns are still kept, and their
	// criteria are checked on what the run observes alone.
	NoBreakdownVariance bool
	// contains filtered or unexported fields
}

Config holds every run setting; each field's zero value selects the default.

func (*Config) PickSeed added in v0.1.4

func (c *Config) PickSeed()

PickSeed replaces a seed of 0 with a random one from 1 to 2^53 - 1, so that a model left at 0 runs independently each time and the Result records the seed it ran at; any other seed is kept.

type Counter

type Counter struct {
	ByLeaf []uint64
	Total  uint64
}

Counter counts delivered rounds by leaf.

func NewCounter

func NewCounter(m *Compiled) *Counter

NewCounter sizes the counter for a model.

func (*Counter) Observe

func (c *Counter) Observe(r *Round) error

Observe counts the round.

type Counts

type Counts struct {
	Applicable bool
	Reason     string
	M          int
	Theta      float64
	Passes     int
	QuadNodes  int
	Entries    []Bounds // [node]; H = 1 and no discretisation gap
}

Counts is the distribution of each node's entries per period on the integer lattice, inside a bracket, or the reason the method does not apply.

type Dependence added in v0.4.0

type Dependence struct {
	Members []string
	Rank    float64 // Spearman's rank correlation of every pair, in [0, 1]; 1 moves them in lockstep, 0 is none
}

Dependence makes the values one round draws move together: every pair of its members has the rank correlation Rank, each keeping its own law. A member is "node.function", an on-entry value or a per-time rate, or "node->to", the holding time from node to to.

type Discount added in v0.4.0

type Discount struct {
	Rate       float64   // per period; > -1
	Factors    []float64 // one per period of the horizon, each >= 0; nil = from Rate
	Categories []string  // the categories discounted; nil = no discount
}

Discount weighs what a started run books in chosen categories by the period it lands in, so their figures are present values. Period p of the horizon, p from 1, has the factor (1+Rate)^-p, the end of the period, or Factors[p-1] in place of Rate for any other curve.

type ECPoint

type ECPoint struct{ X, P, StdErr float64 }

ECPoint is one point of the exceedance curve: P(T ≥ X) with its standard error, binomial for independent periods and from batch means with delays.

type Estimate added in v0.3.0

type Estimate struct{ X, StdErr float64 }

Estimate is a level with its standard error: 0 for a value given, and for a return period's level from the order statistics about it.

type Expectation

type Expectation struct {
	Reach               [][]float64 // [source][node]
	EntriesPer          []float64   // [node]
	OutcomeRate         []float64   // [outcome]
	Terminal            [][]float64 // [source][node], 0 for non-leaves
	Mean                float64
	Var                 float64 // +Inf if infinite; NaN with delays or above the pair budget
	DrawsMean, DrawsVar float64
	MeanByCategory      []float64
	MeanBySource        []float64
	MeanByTotal         []float64 // [named total]
	Contrib             []float64 // [node]
	VarByCategory       []float64 // NaN with delays or above the pair budget
	VarBySource         []float64
	VarByTotal          []float64 // [named total]
	ContribVar          []float64 // [node]
	StepsPerPeriod      float64
	ArrivalsPerPeriod   float64  // arrivals the renewal and chain sources draw beyond their rounds: the stream's events, the units' failures and repairs
	RoundsPerPeriod     float64  // Σ_k E[λ_k]
	Firing              []Firing // per trigger, P(fire)
	// ByPeriod is a started run's exact mean per period of its horizon,
	// [period][quantity] in the order of Series columns, NaN where no
	// closed form applies; nil in steady state. The fields above are
	// then over the whole horizon.
	ByPeriod [][]float64
	// contains filtered or unexported fields
}

Expectation holds the exact values of the model, indexed like Result.

func (*Expectation) PZero

func (e *Expectation) PZero() float64

PZero is the exact probability of a zero period total; NaN with a repair source, with a trigger that counts entries booking nothing, or when its mixture is above the work cap even with the probabilities at their means.

type Factor

type Factor struct {
	ID    string
	Model dist.Distribution // support in [0, ∞)
	Range *InputRange       // how uncertain Model is, for a sweep; nil = not swept
}

Factor is a multiplier on rates, drawn once per period and shared by every source naming it: a common shock, which makes the sources' counts dependent and the aggregate tail heavier than independence says.

type Firing added in v0.2.0

type Firing struct {
	Source  int // the trigger's index among the sources
	Lo, Hi  float64
	Reason  string
	SumMean float64 // E[the sum the trigger tests]; NaN when unknown, as for a gate on other triggers
}

Firing is P(fire) of a trigger: within [Lo, Hi] from the transform of its sum, or NaN with the reason the transform does not apply.

func (Firing) Exact added in v0.2.0

func (f Firing) Exact() bool

Exact reports whether the bracket is known.

type Function

type Function struct {
	Name, Category string
	Model          dist.Distribution // value; for PerTime, a rate per period
	Basis          Basis
	Scope          Scope
	Range          *InputRange // how uncertain Model is, for a sweep; nil = not swept
	Factor         string      // a shared factor multiplying the value, a rate for PerTime; "" = none
	Expr           string      // the value as an expression of the node's other on-entry functions, Model nil; "" = drawn from Model
}

Function is a pdf a node applies on every trigger, booked to a category.

type Given added in v0.3.0

type Given struct {
	Node, To string
	Source   string            // whose rounds they are; "" for the model's one source
	Count    dist.Distribution // rounds, drawn once a repeat and rounded to a whole number
	Age      dist.Distribution // at a queue: how long each round has been there, in periods
	// InService is, at a queue, how long a round in service has been
	// served; nil draws its remaining work from the work's equilibrium
	// residual, as in a queue that has long been running.
	InService dist.Distribution
	// Elapsed is, in a holding, how long a round has been held; nil
	// draws what is left from the holding's equilibrium residual.
	Elapsed dist.Distribution
}

Given is one part of what is under way at the start of a started run: Count rounds of Source at node Node. Without To, Node is a queue and the rounds are in it, each there for Age: the oldest in service, the rest waiting, oldest first. With To, the rounds are part-way through the holding time of Node's outcome to To, each held for Elapsed so far. Nothing they booked before period 0 is booked again: no on-entry value at Node, and the per-time values over what is left of the stay or the holding.

type Graph

type Graph struct {
	ID, Description string
	Sources         []Source
	Nodes           []Node
	Factors         []Factor
	Schedules       []Schedule
	Layers          []Layer // functions of the period total reported beside it
	Totals          []Total // sums of chosen categories reported beside the total
	OutsideTotal    []string
	Phased          Phase    // set by Phase: the place in the cycle every schedule is fixed at
	Start           Start    // where a run begins: steady state, or a started run's horizon
	Discount        Discount // a started run's discount on chosen categories; zero = none
	Dependence      []Dependence
}

Graph is a model: sources feeding a DAG of nodes.

func (Graph) Compare added in v0.4.0

func (g Graph) Compare(ctx context.Context, options []Graph, cfg CompareConfig) (*Comparison, error)

Compare reports cfg.Figure for each option against the graph as it is. A row is exact where the analytic expectations give the figure for both, a bracket where the transform applies to both, and simulated otherwise: fixed runs at the one seed and the base run's length and blocks, so that the option draws alike wherever it does not differ, with the standard error of the difference measured on the runs' paired blocks.

func (Graph) Compile

func (g Graph) Compile(cfg Config) (*Compiled, []Warning, error)

Compile validates the graph and flattens it; the warnings are the non-fatal findings.

Example

Compile validates a graph; Analytic gives the exact mean and variance of the period total without simulating.

package main

import (
	"fmt"

	"code.eitanity.com/variate"
	"code.eitanity.com/variate/dist"
)

// compoundModel is the smallest graph: a source with an uncertain rate
// feeding one node that books a value per event.
func compoundModel() variate.Graph {
	rate, _ := dist.NewPERT(2, 5, 12, dist.DefaultPERTShape)
	severity, _ := dist.NewLognormalFromMedianP90(1000, 5000)
	return variate.Graph{
		ID:      "compound",
		Sources: []variate.Source{{ID: "incident", Frequency: rate, To: "loss"}},
		Nodes: []variate.Node{{
			ID:        "loss",
			Functions: []variate.Function{{Name: "cost", Category: "money", Model: severity}},
		}},
	}
}

func main() {
	m, warnings, err := compoundModel().Compile(variate.Config{})
	if err != nil {
		fmt.Println(err)
		return
	}
	for _, w := range warnings {
		fmt.Println("warning:", w.Code)
	}
	e, _ := m.Analytic()
	fmt.Printf("mean %.0f  sd %.0f  P(T = 0) %.4f\n", e.Mean, sqrt(e.Var), e.PZero())
}

func sqrt(x float64) float64 {
	z := x
	for i := 0; i < 60; i++ {
		z = (z + x/z) / 2
	}
	return z
}
Output:
warning: expected-work
mean 12468  sd 12201  P(T = 0) 0.0118

func (Graph) Cycle added in v0.1.4

func (g Graph) Cycle() (int, error)

Cycle is the length of the model's combined cycle, the least common multiple of its schedules' lengths; 0 for a model without schedules.

func (Graph) Inputs added in v0.1.3

func (g Graph) Inputs() []Input

Inputs lists the graph's inputs in a fixed order: factors, schedules, sources, then per node its functions and outcomes. A source standing on chains has no frequency input but each chain's up time, and its repair time when it has one; a remainder outcome has no probability, and a node's only outcome in absolute mode no probability either.

func (Graph) Phase added in v0.1.4

func (g Graph) Phase(i int) (Graph, error)

Phase returns the graph at phase i of its cycle, counted from 1: each schedule fixed at its value for the periods at that place, period p being at phase p mod the cycle + 1. Every period of a run is then that phase, and the exact figures describe one such period rather than a period taken at random from the cycle.

func (Graph) Scaled added in v0.1.3

func (g Graph) Scaled(input string, f float64) (scaled Graph, clamped bool, err error)

Scaled returns a copy of the graph with one input multiplied by f > 0; the receiver is not changed. A probability stays a probability: one that would pass 1 is held at 1, the fixed probabilities of an absolute node with a remainder are held to a sum of 1, and those of a node without one are rescaled together so that they still sum to 1. clamped reports that a hold changed the scaled value.

func (Graph) Sweep added in v0.1.3

func (g Graph) Sweep(ctx context.Context, cfg SweepConfig) (*Sweep, error)

Sweep moves each input of the graph that has a range to the low and the high end of it, or, with cfg.Screen, every input by that relative amount, and reports the change in cfg.Figure. A row is exact where the analytic expectations give the figure, a bracket where the transform applies to the base and both moved models, and simulated otherwise: fixed runs at the one seed, so that the moved models draw from the base model's streams, with the standard error of each difference measured on the runs' paired blocks.

type Input added in v0.1.3

type Input struct {
	Name  string
	Kind  string
	Range *InputRange // nil when the model gives the input none
}

Input is one distribution of a graph that a sweep can scale, named as the report names things: "source <id> frequency", "source <id> repair", "source <id> block <n> mtbf", "source <id> block <n> mttr", "node <id> function <name>", "node <id> outcome <target> p", "node <id> outcome <target> holding", "node <id> next holding", "factor <id>", "schedule <id>". A block's n counts its chains from 1 in the order they were written. A repeated target carries its #n as in the outcome names. Constants are inputs too.

func SelectInputs added in v0.1.3

func SelectInputs(all []Input, filters []string) []Input

SelectInputs keeps the inputs a filter names, by name, by kind, or by a name's leading words; no filters keep them all.

type InputRange added in v0.1.3

type InputRange struct {
	Low, High float64
	Factors   bool
}

InputRange is how uncertain an input is: its mean at the low and the high end of what is plausible, in the input's own units, a probability as a probability; or, with Factors, the factors on the input at the two ends. A sweep moves the input to each end.

type ItemStat added in v0.3.0

type ItemStat struct {
	N                        int64
	Mean, StdErr             float64
	P50, P90, P95, P99, P999 float64
	Clipped                  bool
	QLo, QHi, QSE            [5]float64
	StdErrUnreliable         bool // the variance is infinite, so the mean's standard error means nothing
}

ItemStat summarises a per-round quantity of a queue over the rounds served: the count, the mean with its standard error over the batch groups, and the quantiles with their 95% intervals and errors, which the groups widen as they do a period's.

type Layer

type Layer struct {
	ID         string
	Attachment float64 // the total below which the layer pays nothing
	Limit      float64 // the most the layer pays before the share; 0 = no limit
	Share      float64 // the share of the band the layer pays; 0 = all of it
}

Layer is a function of the period total reported beside it: the part of the total between an attachment and the attachment plus a limit, times a share, as an aggregate deductible, an aggregate limit or a reinsurance layer takes it. A layer is computed from each closed period's total, so it has the statistics, histogram, series and quantity access of any other row; when the transform applies, its mean has exact bounds from the total's bracket.

type Level added in v0.3.0

type Level struct {
	Kind, Name string
	X          float64
}

Level is a value X of a quantity, named as Workspace.QuantityRow names one: Kind "total", "category", "source", "entries", "contrib", "layer" or "trigger", and Name within it ("" for the total).

type LevelStat added in v0.3.0

type LevelStat struct {
	Level
	N         int64
	P, StdErr float64
}

LevelStat is the chance a quantity reaches one of Config.At's values: P is the share of the N periods (repeats, in a started run) in which it is at least X, and P(Q < X) is 1 − P; the standard error is binomial, widened as a mean's is where periods are correlated.

type Mode

type Mode uint8

Mode is a node's selection mode.

const (
	Absolute Mode = iota
	Sequential
)

type Node

type Node struct {
	ID, Description string
	Functions       []Function
	Mode            Mode
	Outcomes        []Outcome
	Next            string          // continuation without a selection; "" with no Outcomes = leaf
	NextOutage      bool            // the continuation holds for the block's outage (as OutageHolding)
	NextHolding     dist.Continuous // holding time on Next; nil = 0
	NextScope       Scope
	NextRange       *InputRange // how uncertain NextHolding is; nil = not swept
	Threshold       *Threshold  // a branch on one function's value, in place of Outcomes and Next; nil = none
	Trigger         *Trigger    // the node is entered once at a period's end when the period's sum of its inputs is above a level; nil = none
	Queue           *Queue      // the node serves the rounds reaching it in order with limited capacity; nil = none
}

Node is a state an event passes through.

type Observer

type Observer interface {
	Observe(r *Round) error
}

Observer receives delivered rounds, one at a time, from one goroutine. Returning ErrStop ends the run; any other error fails it.

Example

A Watch narrows the rounds an Observer receives; here to those whose value is at least 10000. The Watch is read at Compile, the Observer at NewWorkspace.

package main

import (
	"context"
	"fmt"

	"code.eitanity.com/variate"
	"code.eitanity.com/variate/dist"
)

// compoundModel is the smallest graph: a source with an uncertain rate
// feeding one node that books a value per event.
func compoundModel() variate.Graph {
	rate, _ := dist.NewPERT(2, 5, 12, dist.DefaultPERTShape)
	severity, _ := dist.NewLognormalFromMedianP90(1000, 5000)
	return variate.Graph{
		ID:      "compound",
		Sources: []variate.Source{{ID: "incident", Frequency: rate, To: "loss"}},
		Nodes: []variate.Node{{
			ID:        "loss",
			Functions: []variate.Function{{Name: "cost", Category: "money", Model: severity}},
		}},
	}
}

// leafCounter is an Observer: it receives every delivered round.
type leafCounter struct{ rounds, steps int }

func (c *leafCounter) Observe(r *variate.Round) error {
	c.rounds++
	c.steps += len(r.Steps)
	return nil
}

func main() {
	cfg := variate.Config{Periods: 200, Watch: variate.Watch{MinValue: 10000}}
	m, _, _ := compoundModel().Compile(cfg)
	obs := &leafCounter{}
	cfg.Observer = obs
	w, _ := m.NewWorkspace(cfg)
	defer w.Close()
	r, _ := w.Run(context.Background(), 3)
	fmt.Printf("events %d, delivered %d, one step each: %v\n", r.Events[0], obs.rounds, obs.steps == obs.rounds)
}
Output:
events 1119, delivered 37, one step each: true

type Outcome

type Outcome struct {
	To            string
	P             dist.Distribution // nil = remainder; Constant for fixed; otherwise drawn per period
	Holding       dist.Continuous   // nil = no delay
	HoldingScope  Scope
	OutageHolding bool        // hold for the time the reliability block that fired the round stays down
	PRange        *InputRange // how uncertain P is, for a sweep, as probabilities; nil = not swept
	HoldingRange  *InputRange // how uncertain Holding is; nil = not swept
}

Outcome is one branch of a node's selection.

type PeriodStat added in v0.3.0

type PeriodStat struct {
	N                    int64
	Mean, StdErr, StdDev float64
}

PeriodStat is one quantity in one period of the horizon, across the repeats: their number, the mean, its standard error and the standard deviation.

type PeriodStats added in v0.3.0

type PeriodStats struct {
	// contains filtered or unexported fields
}

PeriodStats holds, per period of a started run's horizon and per quantity, the mean and spread across the repeats.

func (*PeriodStats) Category added in v0.3.0

func (s *PeriodStats) Category(c, k int) PeriodStat

Category is category c's value in period k.

func (*PeriodStats) Contrib added in v0.3.0

func (s *PeriodStats) Contrib(v, k int) PeriodStat

Contrib is node v's booked value in period k.

func (*PeriodStats) Entries added in v0.3.0

func (s *PeriodStats) Entries(v, k int) PeriodStat

Entries is node v's entries in period k.

func (*PeriodStats) Named added in v0.4.0

func (s *PeriodStats) Named(i, k int) PeriodStat

Named is named total i in period k of the horizon.

func (*PeriodStats) Periods added in v0.3.0

func (s *PeriodStats) Periods() int

Periods is the horizon.

func (*PeriodStats) Queue added in v0.3.0

func (s *PeriodStats) Queue(c, col, k int) PeriodStat

Queue is queue c's column col (Joined … Unfinished) in period k.

func (*PeriodStats) Source added in v0.3.0

func (s *PeriodStats) Source(k, p int) PeriodStat

Source is source k's value in period p.

func (*PeriodStats) Stay added in v0.3.0

func (s *PeriodStats) Stay(c, k int) QueueRatio

Stay is queue c's mean stay of the rounds that reached it in period k.

func (*PeriodStats) Total added in v0.3.0

func (s *PeriodStats) Total(k int) PeriodStat

Total is the period total in period k of the horizon, from 0.

func (*PeriodStats) Trigger added in v0.3.0

func (s *PeriodStats) Trigger(i, k int) PeriodStat

Trigger is the sum trigger i tested in period k.

func (*PeriodStats) Wait added in v0.3.0

func (s *PeriodStats) Wait(c, k int) QueueRatio

Wait is queue c's mean wait in period k; Stay its mean stay.

type Phase added in v0.1.4

type Phase struct{ Index, Cycle int }

Phase is the place in the cycle a graph was fixed at by Graph.Phase: Index from 1 to Cycle, or 0 for a graph over its whole cycle.

type PlanRow

type PlanRow struct {
	Criterion        string
	Driver           string
	PlannedPerPeriod float64
	PeriodsNeeded    int64
	Observed         float64
	Met              bool
	NotApplicable    string // why the criterion does not apply, which then counts as met; "" where it does
}

PlanRow is one convergence criterion: planned against observed.

type Prop

type Prop struct{ P, StdErr float64 }

Prop is a proportion with its binomial standard error.

type Queue added in v0.3.0

type Queue struct {
	Servers    int
	Speed      float64           // work done per period by each server
	Work       dist.Distribution // each round's work, on [0, ∞) with a finite mean
	Reset      bool
	Unfinished string // with Reset, the node the unserved rounds go to
}

Queue makes a node a line served first come, first served by Servers servers of one Speed: a round reaching the node brings an amount of Work, drawn as it arrives, and is served for Work ÷ Speed periods once a server is free, from every source in order of arrival. The node's on-entry functions book on arrival, its per-time functions over the stay, waiting and service, and its outcomes are chosen once served. With Reset, at each period's end the rounds still waiting or in service leave for the Unfinished node; without it the line carries on, which only a started run allows.

type QueueLongRun added in v0.3.0

type QueueLongRun struct {
	Method         string
	Wait, Stay     float64 // means, +Inf when infinite
	WaitLo, WaitHi [5]float64
	Reason         string
}

QueueLongRun is a carried queue's long-run (stationary) wait and stay, where a closed form gives them: Erlang C for exponential work at any number of servers, Pollaczek–Khinchine for one server and any work. The wait's quantiles, at QuantileLevels(), lie in [WaitLo, WaitHi]: equal under Erlang C, and under Pollaczek–Khinchine from two discretisations of the law that bound it below and above. Reason says why there are none, Method is "" then.

type QueueRatio added in v0.3.0

type QueueRatio struct{ Mean, StdErr float64 }

QueueRatio is a queue's mean wait or stay of the rounds that reached it in a period and were served, with its standard error across the repeats by the delta method; NaN where none was served.

type QueueResult added in v0.3.0

type QueueResult struct {
	// contains filtered or unexported fields
}

QueueResult is a queue's statistics over the rounds it served: their waits and their stays, waiting and service.

func (*QueueResult) LookBack added in v0.4.0

func (q *QueueResult) LookBack() float64

LookBack is the mean periods a carried queue's exact start in a steady-state run looked back, over its timelines; NaN without one.

func (*QueueResult) Stay added in v0.3.0

func (q *QueueResult) Stay() ItemStat

Stay summarises the stays, wait and service, of the rounds served.

func (*QueueResult) Wait added in v0.3.0

func (q *QueueResult) Wait() ItemStat

Wait summarises the waits of the rounds served.

type QueueSummary added in v0.3.0

type QueueSummary struct {
	Servers                    int
	Wait, Stay                 ItemStat
	Joined, Served, Unfinished Stat
	Length                     Stat // summed over the horizon's period ends in a started run
	Busy                       Stat // busy server time
	Utilisation                float64
	Line                       float64 // the mean line at a period's end
	LongRun                    QueueLongRun
	LookBack                   float64 // a carried queue's mean periods its exact start looked back in a steady-state run; NaN otherwise
}

QueueSummary is a queue's figures: over the rounds it served, their wait and stay; and per period (in a started run, per repeat of the horizon) the rounds that joined, those served, the line's length at the period's end, the share of the servers' time busy, and the rounds sent to the unfinished node.

type Range added in v0.1.3

type Range struct{ Lo, Hi float64 }

Range is a figure known to lie in [Lo, Hi]: one point when it is exact or simulated, the transform's bracket otherwise.

func (Range) Mid added in v0.1.3

func (r Range) Mid() float64

Mid is the middle of the range.

type RecordWriter

type RecordWriter struct {
	// contains filtered or unexported fields
}

RecordWriter writes each delivered round as one fixed-layout little-endian binary record: the 56-byte header and 24 bytes per step.

func NewRecordWriter

func NewRecordWriter(w io.Writer, maxPath int) *RecordWriter

NewRecordWriter returns a writer for rounds of at most maxPath steps; the model's LongestPath gives that.

func (*RecordWriter) Observe

func (rw *RecordWriter) Observe(r *Round) error

Observe writes the round's record.

type Result

type Result struct {
	Seed      uint64
	Periods   int64
	Converged bool
	Stopped   bool
	Binding   string
	Unmet     []string

	Nodes, Outcomes, Categories, Sources []string

	Events       []uint64   // [source]
	Reach        [][]uint64 // [source][node]
	OutcomeCount [][]uint64 // [source][outcome]

	Total      Accum
	ByCategory []Accum
	BySource   []Accum
	EntriesPer []Accum // [node]
	Contrib    []Accum // [node]; zero for nodes without functions
	Layers     []Accum // [layer]: the layer's payout per period
	Totals     []Accum // [named total]: the sum of its categories per period
	Triggers   []Accum // [trigger]: the sum the trigger tests per period
	QueueCols  []Accum // [queue×queueCols]: each queue's joined, served, wait, stay, length, busy and unfinished per period
	Levels     []Accum // [Config.At]: 1 in a period reaching the value, else 0
	Queues     []QueueResult

	Steps         uint64
	BeyondHorizon float64
	TailPeriods   int64

	Series *Series // raw per-period rows; fixed runs with Config.Series only

	// ByPeriod is a started run's statistics per period of its horizon,
	// across the repeats; nil in steady state. The fields above then
	// describe the horizon: one row per repeat, its periods summed.
	ByPeriod *PeriodStats
}

Result is the outcome of a run.

type Round

type Round struct {
	Seq     uint64
	Repeat  int64 // a started run's repeat, from 0; 0 in steady state
	Period  int64 // in a started run, the period within the repeat
	Source  int32
	Arrival float64
	End     float64
	Leaf    int32
	Value   float64
	Steps   []Step
}

Round is one delivered event with its whole path.

type Schedule

type Schedule struct {
	ID     string
	Values []float64   // finite, not negative
	Range  *InputRange // how uncertain the values' mean is, for a sweep; nil = not swept
}

Schedule is a cycle of multipliers on rates: period p uses the value at p modulo the cycle's length, so a rate can follow a season or a shift pattern. Over whole cycles every value is seen equally often, and every schedule steps with the same period, so the analytics take the schedules jointly over their combined cycle: a period drawn uniformly from it.

type Scope

type Scope uint8

Scope says how widely one draw is shared: per event, or per period.

const (
	PerEvent Scope = iota
	PerPeriod
)

type Series

type Series struct {
	// contains filtered or unexported fields
}

Series holds every closed period's row of quantities: total, categories, sources, entries per node, contribution per node, layers and the sum each trigger tests.

func (*Series) Category

func (s *Series) Category(c int, p int64) float64

Category is category c's value in period p.

func (*Series) CategoryColumn

func (s *Series) CategoryColumn(c int, dst []float64) []float64

CategoryColumn copies category c's values into dst.

func (*Series) Contrib

func (s *Series) Contrib(v int, p int64) float64

Contrib is node v's booked value in period p.

func (*Series) Entries

func (s *Series) Entries(v int, p int64) float64

Entries is the number of entries at node v in period p.

func (*Series) EntriesColumn

func (s *Series) EntriesColumn(v int, dst []float64) []float64

EntriesColumn copies node v's entries into dst.

func (*Series) Horizon added in v0.3.0

func (s *Series) Horizon() int64

Horizon is a started run's periods per repeat, row p being period p mod Horizon of repeat p / Horizon; 0 in steady state.

func (*Series) LayerColumn

func (s *Series) LayerColumn(j int, dst []float64) []float64

LayerColumn copies a layer's payouts into dst.

func (*Series) NamedColumn added in v0.4.0

func (s *Series) NamedColumn(i int, dst []float64) []float64

NamedColumn copies named total i's values into dst.

func (*Series) Periods

func (s *Series) Periods() int64

Periods is the number of periods recorded: in a started run, the repeats times the horizon.

func (*Series) Source

func (s *Series) Source(k int, p int64) float64

Source is source k's value in period p.

func (*Series) SourceColumn added in v0.1.3

func (s *Series) SourceColumn(k int, dst []float64) []float64

SourceColumn copies source k's values into dst.

func (*Series) Total

func (s *Series) Total(p int64) float64

Total is the period total of period p.

func (*Series) TotalColumn

func (s *Series) TotalColumn(dst []float64) []float64

TotalColumn copies the period totals into dst.

func (*Series) TriggerColumn added in v0.3.0

func (s *Series) TriggerColumn(i int, dst []float64) []float64

TriggerColumn copies the sums trigger i tested into dst.

type Source

type Source struct {
	ID, Description string
	Frequency       dist.Distribution // rate per period
	To              string
	Every           int               // fire on every Every-th arrival of the stream; 0 or 1 = every arrival
	Repair          dist.Distribution // holding after each firing, in periods, during which the source is silent; nil = none
	Chains          []Chain           // a reliability diagram the engine simulates in place of Frequency; nil = none
	Factor          string            // a Factor's ID scaling the rate, drawn once per period and shared; "" = none
	Schedule        string            // a Schedule's ID scaling the rate by the period's place in a cycle; "" = none
	FrequencyRange  *InputRange       // how uncertain Frequency is, for a sweep; nil = not swept
	RepairRange     *InputRange       // how uncertain Repair is; nil = not swept
}

Source is an initiating event flow.

type Start added in v0.3.0

type Start struct {
	Horizon int
	State   []Given // what is under way at period 0; nil = an empty start
}

Start is where a run begins. A zero Horizon is today's steady state; a positive one is a started run of that many periods, repeated, from an empty start or, with State, from a given one.

type Stat

type Stat struct {
	N                        int64
	Mean, StdErr, StdDev     float64
	Min, Max                 float64
	P50, P90, P95, P99, P999 float64
	Quantiles                bool // the percentiles exist: the quantity has a histogram
	Clipped                  bool
	Share                    float64
	StdErrUnreliable         bool // the variance is infinite, so the standard error means nothing

	// Per level of QuantileLevels(): the quantile's 95% interval, from the
	// order statistics, and its standard error, the interval's width over
	// 2·1.96. The interval is asymmetric in a skewed tail; quote it rather
	// than the quantile ± 1.96 standard errors. With delays, correlated
	// periods widen it by the batch-means inflation at the quantile, and
	// it is NaN below 16 full blocks.
	QLo, QHi, QSE [5]float64
}

Stat summarises one per-period quantity.

type Step

type Step struct {
	Node    int32
	Outcome int32 // −1 at the leaf
	T       float64
	Value   float64
}

Step is one node visit on a round's path.

type Structure

type Structure struct {
	Nodes    []StructureNode
	Outcomes []StructureEdge
	Sources  []StructureSource
}

Structure describes the compiled graph for drawing: the nodes with their functions, the outcomes as edges, and the sources with the node each enters.

type StructureEdge

type StructureEdge struct {
	Name, From, To string
	Holding        bool
}

StructureEdge is an outcome: from a node to its target, named as the report names it, holding when a holding time delays it.

type StructureFunction

type StructureFunction struct {
	Name, Category string
	PerTime        bool
}

StructureFunction is a function's name, category and basis.

type StructureNode

type StructureNode struct {
	ID        string
	Functions []StructureFunction
	Leaf      bool
}

StructureNode is a node and the functions it books.

type StructureSource

type StructureSource struct {
	ID, To  string
	Trigger bool
	Inputs  []string
	Over    float64
}

StructureSource is a source and the node it enters. A trigger is a source with the nodes whose bookings its sum adds up, and its level.

type Summary

type Summary struct {
	Total      Stat
	Exceedance []ECPoint
	ByCategory map[string]Stat // empty, as are BySource and ContribPer, with Config.NoBreakdown
	BySource   map[string]Stat

	ReachProb  map[string]map[string]Prop
	Terminal   map[string]map[string]Prop
	OutcomeP   map[string]Prop
	EntriesPer map[string]Stat
	ContribPer map[string]Stat // value booked per period at each node
	Layers     map[string]Stat // each layer's payout per period, its share that of the total's mean
	Totals     map[string]Stat // each named total per period; its share NaN when a category of it is outside the total
	Triggers   map[string]Stat // by the trigger's source name: the sum it tests per period
	Plan       []PlanRow
	Queues     map[string]QueueSummary // by the queue node's name
	At         []LevelStat             // Config.At in its order
	AtMostZero []LevelStat             // P(Q ≤ 0) of each named total that subtracts, in the model's order
	When       []WhenStat              // Config.When in its order
}

Summary is the report of a run, with names as keys.

type Sweep added in v0.1.3

type Sweep struct {
	Figure  string
	Screen  float64 // the screen's relative move; 0 when the inputs' ranges were swept
	Seed    uint64
	Periods int64 // of the simulated rows; 0 when there are none
	Phase   Phase // the phase the graph was fixed at; Index 0 for the whole cycle
	Rows    []SweepRow
}

Sweep is a sensitivity sweep: rows by swing, the largest first.

type SweepConfig added in v0.1.3

type SweepConfig struct {
	// Figure is the quantity reported: "mean" (the default), "p<percent>"
	// for a quantile (p99, p99.5), "rp:<periods>" for the total at a
	// return period, "pzero" for P(T = 0), "layer:<id>", "category:<name>"
	// or "source:<id>" for that mean.
	Figure string
	// Screen, when positive, moves every selected input to 1 − Screen
	// and 1 + Screen times itself, ranges or none: a screen of the inputs'
	// leverage, for which are worth a range. 0 = each input with a range
	// moves to the two ends of it, and the others stay.
	Screen float64
	// Inputs restricts the sweep to the inputs whose name or kind is one
	// of these, or whose name starts with one followed by a space ("node
	// pump" takes every input of node pump). nil = every input.
	Inputs []string
	// Top keeps the Top inputs with the largest swing of the exact mean,
	// which ranks them before any costlier row is computed. 0 = all.
	Top int
	// Run compiles every model and runs the simulated rows: its Seed is
	// the one seed of every run, its Periods their length (0 = the length
	// the base run's plan settles on).
	Run Config
}

SweepConfig is what a sweep moves and reports.

type SweepRow added in v0.1.3

type SweepRow struct {
	Input  Input
	Method string
	// Low and High are the factors that took the input to the ends.
	Low, High           float64
	AtLow, Base, AtHigh Range
	// Swing is |AtHigh − AtLow| between the middles.
	Swing float64
	// LowSE and HighSE are the standard errors of AtLow − Base and AtHigh
	// − Base: 0 when exact, NaN for a bracket or too few blocks, and for a
	// simulated row measured on the runs' paired blocks.
	LowSE, HighSE float64
	// Clamped reports that a probability was held at 1, or held to its
	// node's sum, at one of the ends.
	Clamped bool
}

SweepRow is one input's row: the figure with the input at the low end of its range, as it is, and at the high end.

type Threshold added in v0.2.0

type Threshold struct {
	Function     string  // the name of the node's OnEntry function whose value is tested
	Over         float64 // above is strictly greater than Over
	Above, Below string  // the next node on each side
}

Threshold sends a round one way when the value a node's function draws is above Over and the other way when it is at or below it. The value is drawn once and booked as usual; the round branches on it, so the branch and the value are as dependent as they are in the world.

type Total added in v0.4.0

type Total struct {
	ID         string
	Categories []string
	Less       []string // subtracted: such a total can be negative
}

Total is a sum of categories the model names, less those in Less, reported beside the period total as a quantity of its own.

type TransformConfig

type TransformConfig struct {
	MaxGrid  int     // default 1<<22 points
	Tol      float64 // default 1e-3: at each x up to x*, (Upper − Lower)/Upper, or the quantile bracket's (hi − lo)/hi
	TailP    float64 // default from the compile criteria
	MaxWork  int64   // default 1<<34 grid-point evaluations (a rate quadrature's nodes × points, a function's or closed-form rate's points) over the whole transform
	MaxBytes int64   // default 2<<30, 3<<29 with a 32-bit int: the grids a pass holds at once
}

TransformConfig controls the FFT transform.

type Transformed

type Transformed struct {
	Applicable bool
	Reason     string
	H          float64
	M          int
	Theta      float64
	PZero      float64
	QuadNodes  int
	Passes     int
	Work       int64 // grid-point evaluations spent
	Bytes      int64 // the most one pass allocated, the figure MaxBytes bounds
	Total      Bounds
	ByCategory []Bounds
	ByTotal    []Bounds // [named total]; empty Bounds for one that subtracts
	BySource   []Bounds // nil when the model has more than maxSourceBounds sources
}

Transformed is the exact distribution of the period total inside a bracket, or the reason the method does not apply.

type Trigger added in v0.2.0

type Trigger struct {
	Over    float64        // fires when the sum is strictly greater
	Inputs  []TriggerInput // the values the sum adds up
	Entries []string       // or the nodes whose entries it counts, booking nothing
}

Trigger enters its node once, at the end of a period, when the sum of the values booked at its inputs by that period's events, or the count of that period's entries into its Entries nodes, is above Over. A booking counts toward the period its event arrived in, whatever period a holding time lands it in, and the walk the trigger starts books in that same period. No outcome leads into a trigger's node: it is entered only by firing. Its inputs may be reached by other triggers' walks, which then fire first in the period; a trigger whose sum its own firing feeds, directly or through others, is a cycle.

type TriggerInput added in v0.2.0

type TriggerInput struct {
	Node, Function string
}

TriggerInput is one term of a trigger's sum: one function of a node, or every function of it when Function is empty.

type Warning

type Warning struct {
	Code    string
	Subject string
	Message string
}

Warning is a non-fatal finding of Compile.

type Watch

type Watch struct {
	Nodes    []string
	Leaves   []string
	MinValue float64
}

Watch selects which rounds an Observer receives: a round matches every non-empty field, and any entry within a list.

type When added in v0.3.0

type When struct {
	Kind, Name string
	From       Bound
	To         *Bound
}

When is a condition on one quantity, named as a Level names it: the periods in which it is at least From and, with a To, below To.

type WhenPart added in v0.3.0

type WhenPart struct {
	Kind, Name         string
	Mean, MeanStdErr   float64
	Share, ShareStdErr float64
}

WhenPart is a quantity over the periods meeting a condition: its mean in them and its share of their total, each with its standard error; the share is NaN for the total, a node's entries, and a category or named total outside the total.

type WhenStat added in v0.3.0

type WhenStat struct {
	When
	N, Met    int64
	P, StdErr float64
	Lower     Estimate // the level of From
	Upper     Estimate // the level of To, with one
	Reason    string
	Parts     []WhenPart
}

WhenStat is one of Config.When's conditions: of the N periods (repeats, in a started run), the Met that meet it, their share P, and the level of each bound, a return period's estimated with its error; and over those periods each quantity's mean and share of their total. A return period's figures are at its estimated level, and their errors take in the level's own. Reason says why there are no figures, "" where there are.

type Workspace

type Workspace struct {
	// contains filtered or unexported fields
}

Workspace holds every buffer a run needs, allocated once, and the persistent worker pool.

func (*Workspace) Bands

func (w *Workspace) Bands(edges, dst []float64) []float64

Bands fills dst[i] with P(edges[i] ≤ T < edges[i+1]) for the period total; dst must have len(edges)−1 entries.

func (*Workspace) BandsOf

func (w *Workspace) BandsOf(row int, edges, dst []float64) []float64

BandsOf fills dst[i] with P(edges[i] ≤ Q < edges[i+1]) for the quantity at row; dst must have len(edges)−1 entries. A row without a histogram leaves dst zero.

func (*Workspace) BlockPeriods added in v0.3.0

func (w *Workspace) BlockPeriods() int64

BlockPeriods is the periods per task the workspace runs.

func (*Workspace) Close

func (w *Workspace) Close()

Close stops the worker pool. The workspace cannot be used afterwards.

func (*Workspace) ExceedanceOf

func (w *Workspace) ExceedanceOf(row int, dst []ECPoint) []ECPoint

ExceedanceOf returns log-spaced points of P(Q ≥ x) for the quantity at row, as Summary.Exceedance does for the total.

func (*Workspace) Footprint

func (w *Workspace) Footprint() int64

Footprint is the planned size of the workspace's buffers in bytes, the figure checked against MaxMemory.

func (*Workspace) HasHistogram

func (w *Workspace) HasHistogram(row int) bool

HasHistogram reports whether a quantity's row keeps a histogram.

func (*Workspace) Means

func (w *Workspace) Means() []float64

Means returns the analytic means the histogram ranges were sized from, by row quantity; for diagnostics.

func (*Workspace) QuantityRow

func (w *Workspace) QuantityRow(kind, name string) (row int, ok bool)

QuantityRow finds the row of a quantity by kind ("total", "category", "source", "entries", "contrib", "layer", "trigger") and name, "total" with a name for a named total; ok is false for a kind or name the model does not have, and for a breakdown with Config.NoBreakdown.

func (*Workspace) QuantityStat

func (w *Workspace) QuantityStat(row int) Stat

QuantityStat is the statistics of the quantity at row, with its share of the total for a category or source.

func (*Workspace) Run

func (w *Workspace) Run(ctx context.Context, seed uint64) (*Result, error)

Run simulates a fixed number of periods on the worker pool and returns the workspace's Result, which the next Run overwrites. One Run at a time: a second while one is in progress is refused, and a Close during a Run ends it with an error.

func (*Workspace) Summarize

func (w *Workspace) Summarize(dst *Summary)

Summarize fills a caller-owned Summary from the workspace's result, reusing its slices and maps.

func (*Workspace) Timelines added in v0.3.0

func (w *Workspace) Timelines() int

Timelines is the number of independent timelines the run's tasks are dealt into: up to 32 in a model with holding times, one with a series, an observer, or no holding times.

func (*Workspace) Workers added in v0.2.1

func (w *Workspace) Workers() int

Workers is the number of workers the workspace runs: Workers when set, else the most up to GOMAXPROCS that fit MaxMemory.

Directories

Path Synopsis
Package browser holds the settings a model runs with in a browser, built to WebAssembly: one worker, as the page has one thread, and the transform's budgets and tolerance, which keep it within a browser's time and wasm32's memory.
Package browser holds the settings a model runs with in a browser, built to WebAssembly: one worker, as the page has one thread, and the transform's budgets and tolerance, which keep it within a browser's time and wasm32's memory.
cmd
variate command
Command variate is the generic command-line interface: it loads a model file, sizes or runs it, and reports the results as a table, JSON or CSV, with the rounds streamed on request; or sweeps its inputs for the figure each moves most, or compares options against it.
Command variate is the generic command-line interface: it loads a model file, sizes or runs it, and reports the results as a table, JSON or CSV, with the rounds streamed on request; or sweeps its inputs for the figure each moves most, or compares options against it.
variate-demo command
Command variate-demo serves the browser demo: the page under web/, the engine compiled to WebAssembly, and the example models.
Command variate-demo serves the browser demo: the page under web/, the engine compiled to WebAssembly, and the example models.
variate-wasm command
Command variate-wasm is the engine for the browser: it exposes run, plan, sweep, version, histogram and release to JavaScript through syscall/js, taking a model as YAML text and settings as JSON text, and returning the report as JSON text.
Command variate-wasm is the engine for the browser: it exposes run, plan, sweep, version, histogram and release to JavaScript through syscall/js, taking a model as YAML text and settings as JSON text, and returning the report as JSON text.
Package config loads a model file into a variate.Graph and a variate.Config: YAML with one family key per distribution, time units converted to periods through the file's period declaration, several graphs merged under their names, and templates expanded into independent copies.
Package config loads a model file into a variate.Graph and a variate.Config: YAML with one family key per distribution, time units converted to periods through the file's period declaration, several graphs merged under their names, and templates expanded into independent copies.
Package dist holds the distribution families and their exact samplers.
Package dist holds the distribution families and their exact samplers.
examples
gograph command
Command gograph builds a model with the variate API instead of a file: the pattern a domain module follows to compile its own vocabulary into a graph.
Command gograph builds a model with the variate API instead of a file: the pattern a domain module follows to compile its own vocabulary into a graph.
internal
oracle
Package oracle is a deliberately simple reference walker, used only by tests to check the engine's counts and totals on random graphs.
Package oracle is a deliberately simple reference walker, used only by tests to check the engine's counts and totals on random graphs.
tinymem command
Command tinymem compiles a model and runs its transform with the browser's settings, built with TinyGo and run under a WASI runtime the way the page runs the engine, and fails when the heap reserved exceeds browser.MaxHeap: past it a doubling of the wasm memory can fail, and TinyGo then stops the engine instead of refusing.
Command tinymem compiles a model and runs its transform with the browser's settings, built with TinyGo and run under a WASI runtime the way the page runs the engine, and fails when the heap reserved exceeds browser.MaxHeap: past it a doubling of the wasm memory can fail, and TinyGo then stops the engine instead of refusing.
Package report writes a run's summary as a table, JSON or CSV from the typed values, by hand.
Package report writes a run's summary as a table, JSON or CSV from the typed values, by hand.
Package stats holds the numerical aggregation behind results: compensated sums, Welford moments with Chan's merge, and the log-bucketed histogram behind quantiles and the exceedance curve.
Package stats holds the numerical aggregation behind results: compensated sums, Welford moments with Chan's merge, and the log-bucketed histogram behind quantiles and the exceedance curve.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL