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)
- func QuantileLevels() [5]float64
- func QueueColumns() []string
- func WhenName(c When) string
- type Accum
- type Basis
- type Bound
- type Bounds
- type Chain
- type CompareConfig
- type CompareRow
- type Comparison
- type Compiled
- func (m *Compiled) Analytic() (*Expectation, error)
- func (m *Compiled) Binding() (criterion, driver string)
- func (m *Compiled) BurnIn() int64
- func (m *Compiled) Categories() []string
- func (m *Compiled) DiscountFactors() []float64
- func (m *Compiled) Discounted() bool
- func (m *Compiled) DiscountedCategories() []string
- func (m *Compiled) Firings() []Firing
- func (m *Compiled) GivenState() bool
- func (m *Compiled) HasDelays() bool
- func (m *Compiled) HasQueues() bool
- func (m *Compiled) HasRepair() bool
- func (m *Compiled) HasTriggers() bool
- func (m *Compiled) Horizon() int
- func (m *Compiled) InTotal(c int) bool
- func (m *Compiled) LatticeUnit() float64
- func (m *Compiled) Layers() []Layer
- func (m *Compiled) Levels() []Level
- 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) QueueIDs() []string
- func (m *Compiled) QueueLongRun(c int) QueueLongRun
- func (m *Compiled) QueueServers(i int) int
- func (m *Compiled) QueueStdErrUnreliable(c int) bool
- func (m *Compiled) Simulate(ctx context.Context, cfg Config) (*Result, error)
- func (m *Compiled) SourceIDs() []string
- func (m *Compiled) StartState() []string
- func (m *Compiled) Started() bool
- func (m *Compiled) StdErrUnreliable(col int) bool
- func (m *Compiled) Structure() Structure
- func (m *Compiled) TotalIDs() []string
- func (m *Compiled) Transform(cfg TransformConfig) (*Transformed, error)
- func (m *Compiled) TransformEntries(cfg TransformConfig) (*Counts, error)
- func (m *Compiled) Transformed() *Transformed
- func (m *Compiled) Whens() []When
- type Config
- type Counter
- type Counts
- type Dependence
- type Discount
- type ECPoint
- type Estimate
- type Expectation
- type Factor
- type Firing
- type Function
- type Given
- type Graph
- func (g Graph) Compare(ctx context.Context, options []Graph, cfg CompareConfig) (*Comparison, error)
- 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 ItemStat
- type Layer
- type Level
- type LevelStat
- type Mode
- type Node
- type Observer
- type Outcome
- type PeriodStat
- type PeriodStats
- func (s *PeriodStats) Category(c, k int) PeriodStat
- func (s *PeriodStats) Contrib(v, k int) PeriodStat
- func (s *PeriodStats) Entries(v, k int) PeriodStat
- func (s *PeriodStats) Named(i, k int) PeriodStat
- func (s *PeriodStats) Periods() int
- func (s *PeriodStats) Queue(c, col, k int) PeriodStat
- func (s *PeriodStats) Source(k, p int) PeriodStat
- func (s *PeriodStats) Stay(c, k int) QueueRatio
- func (s *PeriodStats) Total(k int) PeriodStat
- func (s *PeriodStats) Trigger(i, k int) PeriodStat
- func (s *PeriodStats) Wait(c, k int) QueueRatio
- type Phase
- type PlanRow
- type Prop
- type Queue
- type QueueLongRun
- type QueueRatio
- type QueueResult
- type QueueSummary
- 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) Horizon() int64
- func (s *Series) LayerColumn(j int, dst []float64) []float64
- func (s *Series) NamedColumn(i 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
- func (s *Series) TriggerColumn(i int, dst []float64) []float64
- type Source
- type Start
- type Stat
- type Step
- type Structure
- type StructureEdge
- type StructureFunction
- type StructureNode
- type StructureSource
- type Summary
- type Sweep
- type SweepConfig
- type SweepRow
- type Threshold
- type Total
- type TransformConfig
- type Transformed
- type Trigger
- type TriggerInput
- type Warning
- type Watch
- type When
- type WhenPart
- type WhenStat
- type Workspace
- func (w *Workspace) Bands(edges, dst []float64) []float64
- func (w *Workspace) BandsOf(row int, edges, dst []float64) []float64
- func (w *Workspace) BlockPeriods() int64
- 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)
- func (w *Workspace) Timelines() int
- func (w *Workspace) Workers() int
Examples ¶
Constants ¶
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.
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.
func LayerBoundsAt ¶
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.
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
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.
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 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.
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) Categories ¶
Categories returns the category names in index order.
func (*Compiled) DiscountFactors ¶ added in v0.4.0
DiscountFactors is each period's factor, nil without a discount.
func (*Compiled) Discounted ¶ added in v0.4.0
Discounted reports whether the run discounts any category.
func (*Compiled) DiscountedCategories ¶ added in v0.4.0
DiscountedCategories names the categories discounted.
func (*Compiled) GivenState ¶ added in v0.3.0
GivenState reports whether a started run starts from a given state.
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) Horizon ¶ added in v0.3.0
Horizon is a started run's periods per repeat; 0 in steady state.
func (*Compiled) InTotal ¶ added in v0.4.0
InTotal reports whether category c is booked into the total.
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) 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
QueueServers returns queue i's servers.
func (*Compiled) QueueStdErrUnreliable ¶ added in v0.3.0
QueueStdErrUnreliable reports whether queue c's wait and stay have infinite variance, so that their standard errors mean nothing.
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) StartState ¶ added in v0.3.0
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) StdErrUnreliable ¶ added in v0.3.0
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) TotalIDs ¶ added in v0.4.0
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.
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.
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.
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 ¶
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 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
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", "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
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 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
}
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
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
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 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 ¶
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
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.
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 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) CategoryColumn ¶
CategoryColumn copies category c's values into dst.
func (*Series) EntriesColumn ¶
EntriesColumn copies node v's entries into dst.
func (*Series) Horizon ¶ added in v0.3.0
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 ¶
LayerColumn copies a layer's payouts into dst.
func (*Series) NamedColumn ¶ added in v0.4.0
NamedColumn copies named total i's values into dst.
func (*Series) Periods ¶
Periods is the number of periods recorded: in a started run, the repeats times the horizon.
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 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
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 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 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 Watch ¶
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
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
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 ¶
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) BlockPeriods ¶ added in v0.3.0
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 ¶
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", "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 ¶
QuantityStat is the statistics of the quantity at row, with its share of the total for a category or source.
func (*Workspace) Run ¶
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 ¶
Summarize fills a caller-owned Summary from the workspace's result, reusing its slices and maps.
Source Files
¶
- analytic.go
- builder.go
- burnin.go
- clock.go
- compare.go
- compile.go
- criteria.go
- cycle.go
- delaylag.go
- delaymemo.go
- delayvar.go
- dependence.go
- depsplit.go
- discount.go
- doc.go
- errors.go
- expr.go
- finalise.go
- flatten.go
- given.go
- given_sim.go
- infvar.go
- keys.go
- layer.go
- layout.go
- level.go
- model.go
- observers.go
- outage.go
- pairs.go
- pending.go
- periodmix.go
- phase.go
- plan.go
- quantity.go
- queue.go
- queue_exact.go
- queue_sim.go
- queue_start.go
- record.go
- reliability.go
- renewal.go
- residual.go
- result.go
- scaled.go
- seed.go
- simulate.go
- slot.go
- slot_build.go
- started.go
- stream.go
- summary.go
- sweep.go
- tbounds.go
- tcount.go
- tfactor.go
- theta.go
- totals.go
- tpass.go
- tquad.go
- transform.go
- trigger.go
- valuefactor.go
- when.go
- whole.go
- worker.go
- workspace.go
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. |