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 ¶
- Constants
- Variables
- func ChainFigures(chains []Chain) (rate, unavailability float64)
- func LayerBoundsAt(b Bounds, y Layer, x float64) (lo, hi float64)
- type Accum
- type Basis
- type Bounds
- type Chain
- type Compiled
- func (m *Compiled) Analytic() (*Expectation, error)
- func (m *Compiled) Binding() (criterion, driver string)
- func (m *Compiled) Categories() []string
- func (m *Compiled) Firings() []Firing
- func (m *Compiled) HasDelays() bool
- func (m *Compiled) HasRepair() bool
- func (m *Compiled) HasTriggers() bool
- func (m *Compiled) LatticeUnit() float64
- func (m *Compiled) Layers() []Layer
- func (m *Compiled) LongestPath() int
- func (m *Compiled) NewWorkspace(cfg Config) (*Workspace, error)
- func (m *Compiled) NodeIDs() []string
- func (m *Compiled) NodeOrder() []string
- func (m *Compiled) OutcomeNames() []string
- func (m *Compiled) Phase() Phase
- func (m *Compiled) Plan() []PlanRow
- func (m *Compiled) PlanPeriods(batchPeriods int64) int64
- func (m *Compiled) Pools() []dist.Distribution
- func (m *Compiled) Simulate(ctx context.Context, cfg Config) (*Result, error)
- func (m *Compiled) SourceIDs() []string
- func (m *Compiled) Spill() int
- func (m *Compiled) Structure() Structure
- func (m *Compiled) TailThresholds() []float64
- func (m *Compiled) Transform(cfg TransformConfig) (*Transformed, error)
- func (m *Compiled) TransformEntries(cfg TransformConfig) (*Counts, error)
- func (m *Compiled) Transformed() *Transformed
- type Config
- type Counter
- type Counts
- type ECPoint
- type Expectation
- type Factor
- type Firing
- type Function
- type Graph
- func (g Graph) Compile(cfg Config) (*Compiled, []Warning, error)
- func (g Graph) Cycle() (int, error)
- func (g Graph) Inputs() []Input
- func (g Graph) Phase(i int) (Graph, error)
- func (g Graph) Scaled(input string, f float64) (scaled Graph, clamped bool, err error)
- func (g Graph) Sweep(ctx context.Context, cfg SweepConfig) (*Sweep, error)
- type Input
- type InputRange
- type Layer
- type Mode
- type Node
- type Observer
- type Outcome
- type Phase
- type PlanRow
- type Prop
- type Range
- type RecordWriter
- type Result
- type Round
- type Schedule
- type Scope
- type Series
- func (s *Series) Category(c int, p int64) float64
- func (s *Series) CategoryColumn(c int, dst []float64) []float64
- func (s *Series) Contrib(v int, p int64) float64
- func (s *Series) Entries(v int, p int64) float64
- func (s *Series) EntriesColumn(v int, dst []float64) []float64
- func (s *Series) LayerColumn(j int, dst []float64) []float64
- func (s *Series) Periods() int64
- func (s *Series) Source(k int, p int64) float64
- func (s *Series) SourceColumn(k int, dst []float64) []float64
- func (s *Series) Total(p int64) float64
- func (s *Series) TotalColumn(dst []float64) []float64
- type Source
- type Stat
- type Step
- type Structure
- type StructureEdge
- type StructureFunction
- type StructureNode
- type StructureSource
- type Summary
- type Sweep
- type SweepConfig
- type SweepRow
- type TailShare
- type Threshold
- type TransformConfig
- type Transformed
- type Trigger
- type TriggerInput
- type Warning
- type Watch
- type Workspace
- func (w *Workspace) Bands(edges, dst []float64) []float64
- func (w *Workspace) BandsOf(row int, edges, dst []float64) []float64
- func (w *Workspace) Close()
- func (w *Workspace) ExceedanceOf(row int, dst []ECPoint) []ECPoint
- func (w *Workspace) Footprint() int64
- func (w *Workspace) HasHistogram(row int) bool
- func (w *Workspace) Means() []float64
- func (w *Workspace) QuantityRow(kind, name string) (row int, ok bool)
- func (w *Workspace) QuantityStat(row int) Stat
- func (w *Workspace) Run(ctx context.Context, seed uint64) (*Result, error)
- func (w *Workspace) Summarize(dst *Summary)
Examples ¶
Constants ¶
const ( InputFactor = "factor" InputSchedule = "schedule" InputFrequency = "frequency" InputRepair = "repair" InputFunction = "function" InputProbability = "probability" InputHolding = "holding" )
The kinds of input a sweep can scale.
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 ¶
var ErrStop = errors.New("stop")
ErrStop is returned by an Observer to end the run cleanly.
Functions ¶
func ChainFigures ¶
ChainFigures returns the stationary failure frequency per period of a source's chains in series and the share of time it is down.
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
}
Accum is the streamed statistics of one per-period quantity.
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.
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.
type Chain ¶
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 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 the per-source, per-category and per-node variances are NaN, left uncomputed.
func (*Compiled) Categories ¶
Categories returns the category names in index order.
func (*Compiled) HasRepair ¶
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
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) LatticeUnit ¶
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) LongestPath ¶
LongestPath is the number of nodes on the longest source-to-leaf path: the step capacity a round needs.
func (*Compiled) NewWorkspace ¶
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) NodeOrder ¶
NodeOrder is the node identifiers in topological order, every node after the nodes that lead to it.
func (*Compiled) OutcomeNames ¶
OutcomeNames returns the outcome names in index order.
func (*Compiled) Phase ¶ added in v0.1.4
Phase is the phase the model was fixed at; Index 0 for the whole cycle.
func (*Compiled) Plan ¶
Plan returns the sizing table: one row per criterion, with the periods it needs; Observed and Met are unset.
func (*Compiled) PlanPeriods ¶
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) Simulate ¶
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) TailThresholds ¶
TailThresholds are the totals the tail shares are counted against.
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.
type Config ¶
type Config struct {
Periods int64
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 // the grids a transform pass may hold; 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
PoolSize int
Series bool
NoBreakdown bool
NodeHist bool
Spill int
MaxMemory int64
Observer Observer
Watch Watch
Pace time.Duration
RoundScratch int
RecordBuffer int
}
Config holds every run setting; each field's zero value selects the default.
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 ECPoint ¶
type ECPoint struct{ X, P, StdErr float64 }
ECPoint is one point of the exceedance curve: P(T ≥ X) with its binomial standard error.
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
Contrib []float64 // [node]
VarByCategory []float64 // NaN with delays or above the pair budget
VarBySource []float64
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)
// 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
}
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.
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
}
Function is a pdf a node applies on every trigger, booked to a category.
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
Phased Phase // set by Phase: the place in the cycle every schedule is fixed at
}
Graph is a model: sources feeding a DAG of nodes.
func (Graph) Compile ¶
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
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
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, a remainder outcome no probability, and a node's only outcome in absolute mode no probability either.
func (Graph) Phase ¶ added in v0.1.4
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
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
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", "node <id> function <name>", "node <id> outcome <target> p", "node <id> outcome <target> holding", "node <id> next holding", "factor <id>", "schedule <id>". A repeated target carries its #n as in the outcome names. Constants are inputs too.
func SelectInputs ¶ added in v0.1.3
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
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 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
}
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 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
}
Node is a state an event passes through.
type Observer ¶
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 1095, delivered 36, 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 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
}
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 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.
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
Steps uint64
BeyondHorizon float64
TailPeriods int64
// Per tail threshold (Compiled.TailThresholds), the periods whose
// total reached it and their total, categories and sources summed,
// in the row order, for the tail shares.
TailCounts []int64
TailSums [][]float64
Series *Series // raw per-period rows; fixed runs with Config.Series only
}
Result is the outcome of a run.
type Round ¶
type Round struct {
Seq uint64
Period int64
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 Series ¶
type Series struct {
// contains filtered or unexported fields
}
Series holds every closed period's row of quantities: total, categories, sources, entries per node and contribution per node.
func (*Series) CategoryColumn ¶
CategoryColumn copies category c's values into dst.
func (*Series) EntriesColumn ¶
EntriesColumn copies node v's entries into dst.
func (*Series) LayerColumn ¶
LayerColumn copies a layer's payouts into dst.
func (*Series) SourceColumn ¶ added in v0.1.3
SourceColumn copies source k's values into dst.
func (*Series) TotalColumn ¶
TotalColumn copies the period totals 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 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
}
Stat summarises one per-period quantity.
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 ¶
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 ¶
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 ¶
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, ContribPer and TailShares, 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
Plan []PlanRow
}
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 TailShare ¶
type TailShare struct {
}
TailShare is the share of the total each source and category booked over the periods whose total reached X: who the tail belongs to.
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 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
Total Bounds
ByCategory []Bounds
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 Watch ¶
Watch selects which rounds an Observer receives: a round matches every non-empty field, and any entry within a list.
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 ¶
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 ¶
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) Close ¶
func (w *Workspace) Close()
Close stops the worker pool. The workspace cannot be used afterwards.
func (*Workspace) ExceedanceOf ¶
ExceedanceOf returns log-spaced points of P(Q ≥ x) for the quantity at row, as Summary.Exceedance does for the total.
func (*Workspace) Footprint ¶
Footprint is the planned size of the workspace's buffers in bytes, the figure checked against MaxMemory.
func (*Workspace) HasHistogram ¶
HasHistogram reports whether a quantity's row keeps a histogram.
func (*Workspace) Means ¶
Means returns the analytic means the histogram ranges were sized from, by row quantity; for diagnostics.
func (*Workspace) QuantityRow ¶
QuantityRow finds the row of a quantity by kind ("total", "category", "source", "entries", "contrib", "layer") and name; ok is false for a kind or name the model does not have, and for a breakdown with Config.NoBreakdown.
func (*Workspace) QuantityStat ¶
QuantityStat is the statistics of the quantity at row, with its share of the total for a category or source.
Source Files
¶
- analytic.go
- builder.go
- clock.go
- compile.go
- criteria.go
- cycle.go
- doc.go
- errors.go
- finalise.go
- flatten.go
- layer.go
- layout.go
- model.go
- observers.go
- outage.go
- pairs.go
- phase.go
- plan.go
- quantity.go
- record.go
- reliability.go
- renewal.go
- result.go
- scaled.go
- seed.go
- simulate.go
- slot.go
- slot_build.go
- stream.go
- summary.go
- sweep.go
- tbounds.go
- tcount.go
- theta.go
- tpass.go
- tquad.go
- transform.go
- trigger.go
- whole.go
- worker.go
- workspace.go
Directories
¶
| Path | Synopsis |
|---|---|
|
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.
|
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. |
|
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. |
|
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. |