macros
import "github.com/umbralcalc/stochadex/pkg/macros"Package macros builds multi-partition simulation topologies from a single declarative spec. Each entry point takes an Applied* struct describing what you want — a rolling likelihood comparison, a posterior estimation loop, a grouped aggregation — plus a *simulator.StateTimeStorage holding the data it reads, and returns the *simulator.PartitionConfig values that realise it.
This is the tier the YAML `macros:` key expands into. Every constructor here is reachable from a config through pkg/api, which decodes the spec structs from YAML and calls into this package; the one exception is NewMCTSSelfPlayPartitions, whose agents.Environment is arbitrary Go game rules and so has no data spelling. The package is named for the shape of what it produces — spec in, partitions out — not for the YAML key alone.
Layering
macros sits above pkg/analysis and depends on it one way only. pkg/analysis owns the data vocabulary: DataRef and IndexRange for addressing series inside storage, the NewStateTimeStorageFrom* loaders, GroupedStateTimeStorage, and the plotting and dataframe renderers. This package consumes that vocabulary and never the reverse, so the stack is
pkg/api → pkg/macros → pkg/analysis → pkg/simulatorWhat each file builds
- aggregation.go — grouped and rolling vector mean/variance/covariance partitions over an analysis.GroupedStateTimeStorage.
- likelihood.go — the windowed-simulation substrate (WindowedPartitions, ParameterisedModel) plus rolling likelihood comparison and mean-function fitting. inference.go and optimisation.go build on its types.
- inference.go — posterior mean/covariance/sampler partitions driving a windowed likelihood, i.e. inference run as forward simulation.
- optimisation.go — evolution-strategy optimisation over a windowed reward.
- smc.go — sequential Monte Carlo inference, including the live RunSMCInference driver.
- regression.go — ScalarRegressionStatsIteration, the one true Iteration in this package, streaming OLS sufficient statistics alongside a run.
- mcts.go — MCTS self-play topology over a pkg/agents Environment.
Invariants
Constructors panic rather than return errors: they run at config-assembly time, before any simulation starts, so a bad spec is a programming error and failing loudly beats a silently misshapen topology. Window depths are checked against the history depths the storage will actually carry — ValidateWindowDataHistoryDepth is the public form of that check, and callers wiring windows through analysis.AddPartitionsToStateTimeStorage should call it with the same map to fail fast instead of underflowing at step time.
Index
- Constants
- func NewEvolutionStrategyOptimisationPartitions(applied AppliedEvolutionStrategyOptimisation, storage *simulator.StateTimeStorage) []*simulator.PartitionConfig
- func NewGroupedAggregationPartition(aggregation func(defaultValues []float64, outputIndexByGroup map[string]int, groupings map[string][]float64, weightings map[string][]float64) []float64, applied AppliedAggregation, storage *analysis.GroupedStateTimeStorage) *simulator.PartitionConfig
- func NewLikelihoodComparisonPartition(applied AppliedLikelihoodComparison, storage *simulator.StateTimeStorage) *simulator.PartitionConfig
- func NewLikelihoodMeanFunctionFitPartition(applied AppliedLikelihoodMeanFunctionFit, storage *simulator.StateTimeStorage) *simulator.PartitionConfig
- func NewMCTSSelfPlayPartitions[S any, A any](spec MCTSSelfPlaySpec[S, A]) []*simulator.PartitionConfig
- func NewPosteriorEstimationPartitions(applied AppliedPosteriorEstimation, storage *simulator.StateTimeStorage) []*simulator.PartitionConfig
- func NewSMCInferencePartitions(applied AppliedSMCInference) []*simulator.PartitionConfig
- func NewScalarRegressionStatsPartition(applied AppliedScalarRegressionStats, storage *simulator.StateTimeStorage) *simulator.PartitionConfig
- func NewVectorCovariancePartition(mean analysis.DataRef, applied AppliedAggregation, storage *simulator.StateTimeStorage) *simulator.PartitionConfig
- func NewVectorMeanPartition(applied AppliedAggregation, storage *simulator.StateTimeStorage) *simulator.PartitionConfig
- func NewVectorVariancePartition(mean analysis.DataRef, applied AppliedAggregation, storage *simulator.StateTimeStorage) *simulator.PartitionConfig
- func RunSMCInference(applied AppliedSMCInference) *inference.SMCResult
- func ScalarRegressionStateWidth(intercept bool, mode RegressionStatsMode, windowLength int) int
- func ValidateWindowDataHistoryDepth(windowDepth int, windowSizeByPartition map[string]int, dataRefs []analysis.DataRef)
- type AppliedAggregation
- type AppliedEvolutionStrategyOptimisation
- type AppliedLikelihoodComparison
- type AppliedLikelihoodMeanFunctionFit
- type AppliedPosteriorEstimation
- type AppliedSMCInference
- type AppliedScalarRegressionStats
- type EvolutionStrategyCovariance
- type EvolutionStrategyMean
- type EvolutionStrategyReward
- type EvolutionStrategySampler
- type EvolutionStrategySorting
- type LikelihoodMeanGradient
- type MCTSSelfPlaySpec
- type ParameterisedModel
- type ParameterisedModelWithGradient
- type PosteriorCovariance
- type PosteriorLogNorm
- type PosteriorMean
- type PosteriorSampler
- type RegressionStatsMode
- type SMCInnerSimConfig
- type SMCParticleModel
- type
ScalarRegressionStatsIteration
- func (s *ScalarRegressionStatsIteration) Configure(partitionIndex int, settings *simulator.Settings)
- func (s *ScalarRegressionStatsIteration) Iterate(params *simulator.Params, partitionIndex int, stateHistories []*simulator.StateHistory, timestepsHistory *simulator.CumulativeTimestepsHistory) []float64
- type WindowedPartition
- type WindowedPartitions
Constants
Param keys for ParamsFromUpstream wiring into ScalarRegressionStatsIteration. Each upstream slice should have length 1 (or use Indices on NamedUpstreamConfig).
const (
ScalarRegressionParamY = "y"
ScalarRegressionParamX = "x"
)func NewEvolutionStrategyOptimisationPartitions
func NewEvolutionStrategyOptimisationPartitions(applied AppliedEvolutionStrategyOptimisation, storage *simulator.StateTimeStorage) []*simulator.PartitionConfigNewEvolutionStrategyOptimisationPartitions creates a set of PartitionConfigs for an online evolution strategies optimisation process. It builds:
- A sampler drawing from N(mean, covariance)
- An embedded simulation running user partitions with discounted reward
- A sorted collection ranking samples by return
- A weighted mean update from the top-ranked samples
- A weighted covariance update around the mean
func NewGroupedAggregationPartition
func NewGroupedAggregationPartition(aggregation func(defaultValues []float64, outputIndexByGroup map[string]int, groupings map[string][]float64, weightings map[string][]float64) []float64, applied AppliedAggregation, storage *analysis.GroupedStateTimeStorage) *simulator.PartitionConfigNewGroupedAggregationPartition creates a partition that performs grouped aggregations over historical state values with customizable binning.
This function creates a partition that aggregates data by grouping values into bins and applying custom aggregation functions within each group. It’s particularly useful for computing statistics over value ranges or categorical data.
Mathematical Concept: Grouped aggregations compute statistics within value bins:
G_i(t) = aggregate({X(s) : X(s) ∈ bin_i, s ≤ t})where bin_i represents a value range or category, and aggregate is the user-provided function (e.g., mean, sum, count).
Parameters:
- aggregation: Function that computes aggregated values from grouped data. Input parameters:
- defaultValues: Fill values for each group when no data is available
- outputIndexByGroup: Maps group names to output vector indices
- groupings: Maps group names to their historical values
- weightings: Maps group names to their time-based weights Output: []float64 aggregated results ordered by accepted value groups
- applied: AppliedAggregation configuration specifying source data and kernel
- storage: analysis.GroupedStateTimeStorage containing group definitions and binning rules
Returns:
- *PartitionConfig: Configured partition ready for simulation
Example:
// Aggregate price data by volatility bins
config := NewGroupedAggregationPartition(
func(defaults, indices, groups, weights map[string][]float64) []float64 {
results := make([]float64, len(indices))
for group, idx := range indices {
values := groups[group]
w := weights[group]
// Compute weighted mean
sum := 0.0
totalWeight := 0.0
for i, v := range values {
sum += v * w[i]
totalWeight += w[i]
}
if totalWeight > 0 {
results[idx] = sum / totalWeight
} else {
results[idx] = defaults[idx]
}
}
return results
},
AppliedAggregation{
Name: "volatility_aggregates",
Data: analysis.DataRef{PartitionName: "prices"},
Kernel: &kernels.ExponentialIntegrationKernel{},
DefaultValue: 0.0,
},
volatilityStorage,
)Performance Notes:
- O(n * m) time complexity where n is history depth, m is number of groups
- Memory usage scales with group count and history depth
- Efficient for moderate numbers of groups (< 1000)
func NewLikelihoodComparisonPartition
func NewLikelihoodComparisonPartition(applied AppliedLikelihoodComparison, storage *simulator.StateTimeStorage) *simulator.PartitionConfigNewLikelihoodComparisonPartition builds a PartitionConfig embedding an inner windowed simulation to evaluate the likelihood over a rolling window, producing a per-step comparison score.
func NewLikelihoodMeanFunctionFitPartition
func NewLikelihoodMeanFunctionFitPartition(applied AppliedLikelihoodMeanFunctionFit, storage *simulator.StateTimeStorage) *simulator.PartitionConfigNewLikelihoodMeanFunctionFitPartition builds a PartitionConfig embedding an inner simulation that runs gradient descent to fit the likelihood mean to the referenced data window.
func NewMCTSSelfPlayPartitions
func NewMCTSSelfPlayPartitions[S any, A any](spec MCTSSelfPlaySpec[S, A]) []*simulator.PartitionConfigNewMCTSSelfPlayPartitions returns the outer partitions for an MCTS self-play simulation built around the spec. The returned slice contains two entries: the apply partition (outer state, one ply per outer step) and the search partition (an embedded sub-simulation that runs the tree + rollout pipeline for SimsPerPly inner steps per outer step).
Add both partitions to your ConfigGenerator. The tree + rollout inner partitions are encapsulated inside the search partition’s EmbeddedSimulationRunIteration and do not appear in the outer config.
Naming: the apply partition is exposed as “<Name>_apply” (handy for reading the encoded game state via params_from_upstream from any other outer partition you might add — telemetry, logging, custom analyses). The search partition is exposed as “<Name>_search”.
func NewPosteriorEstimationPartitions
func NewPosteriorEstimationPartitions(applied AppliedPosteriorEstimation, storage *simulator.StateTimeStorage) []*simulator.PartitionConfigNewPosteriorEstimationPartitions creates a set of PartitionConfigs for an online posterior estimation process using rolling statistics.
func NewSMCInferencePartitions
func NewSMCInferencePartitions(applied AppliedSMCInference) []*simulator.PartitionConfigNewSMCInferencePartitions creates three PartitionConfigs for SMC inference: a proposal partition, an embedded simulation partition, and a posterior partition.
func NewScalarRegressionStatsPartition
func NewScalarRegressionStatsPartition(applied AppliedScalarRegressionStats, storage *simulator.StateTimeStorage) *simulator.PartitionConfigNewScalarRegressionStatsPartition builds a PartitionConfig for ScalarRegressionStatsIteration. storage is used to resolve analysis.DataRef indices; it must already contain the series partitions referenced by Y and X.
func NewVectorCovariancePartition
func NewVectorCovariancePartition(mean analysis.DataRef, applied AppliedAggregation, storage *simulator.StateTimeStorage) *simulator.PartitionConfigNewVectorCovariancePartition constructs a PartitionConfig that computes the rolling windowed weighted covariance matrix of the referenced data values. Provide the corresponding rolling mean via the mean analysis.DataRef.
func NewVectorMeanPartition
func NewVectorMeanPartition(applied AppliedAggregation, storage *simulator.StateTimeStorage) *simulator.PartitionConfigNewVectorMeanPartition creates a partition that computes rolling weighted means for each dimension of the referenced data.
This function creates a partition that maintains running weighted averages over historical data using the specified integration kernel for time weighting. Each dimension of the source data is aggregated independently.
Mathematical Concept: Vector mean aggregation computes:
μ_i(t) = Σ w(t-s) * X_i(s) / Σ w(t-s)where μ_i(t) is the mean for dimension i at time t, w(t-s) is the kernel weight, and X_i(s) is the value of dimension i at historical time s.
Parameters:
- applied: AppliedAggregation specifying source data, kernel, and output name
- storage: StateTimeStorage containing the source data
Returns:
- *PartitionConfig: Partition that outputs rolling weighted means
Example:
// Compute exponentially weighted moving averages of price data
meanPartition := NewVectorMeanPartition(
AppliedAggregation{
Name: "price_ema",
Data: analysis.DataRef{
PartitionName: "prices",
ValueIndices: []int{0, 1, 2}, // Use first 3 price dimensions
},
Kernel: &kernels.ExponentialIntegrationKernel{},
DefaultValue: 100.0, // Initial price assumption
},
priceStorage,
)Performance:
- O(d * h) time complexity where d is data dimensions, h is history depth
- Memory usage: O(d) for output state
- Efficient for moderate dimensions (< 100)
func NewVectorVariancePartition
func NewVectorVariancePartition(mean analysis.DataRef, applied AppliedAggregation, storage *simulator.StateTimeStorage) *simulator.PartitionConfigNewVectorVariancePartition constructs a PartitionConfig that computes the rolling windowed weighted variance per-index of the referenced data values. Provide the corresponding rolling mean via the mean analysis.DataRef.
func RunSMCInference
func RunSMCInference(applied AppliedSMCInference) *inference.SMCResultRunSMCInference builds and runs SMC inference, returning the posterior result from the final round.
func ScalarRegressionStateWidth
func ScalarRegressionStateWidth(intercept bool, mode RegressionStatsMode, windowLength int) intScalarRegressionStateWidth returns the required InitStateValues length for the given options (same layout ScalarRegressionStatsIteration uses).
func ValidateWindowDataHistoryDepth
func ValidateWindowDataHistoryDepth(windowDepth int, windowSizeByPartition map[string]int, dataRefs []analysis.DataRef)ValidateWindowDataHistoryDepth checks that each window data source partition will have at least depth rows of history when wired through analysis.AddPartitionsToStateTimeStorage (missing names default to depth 1). Call with the same windowSizeByPartition map passed to analysis.AddPartitionsToStateTimeStorage.
type AppliedAggregation
AppliedAggregation describes how to aggregate a referenced dataset over time using customizable weighting kernels.
This struct configures the aggregation process by specifying the source data, output partition name, weighting scheme, and handling of insufficient history. It serves as a blueprint for creating aggregation partitions in simulations.
Mathematical Concept: Aggregations compute weighted averages over historical data:
A(t) = Σ w(t-s) * f(X(s)) / Σ w(t-s)where w(t-s) is the kernel weight, f(X(s)) is the source data, and the sum is over all historical samples s ≤ t.
Fields:
- Name: Output partition name for the aggregated results
- Data: Reference to the source data partition and value indices
- Kernel: Integration kernel for time-based weighting (nil = instantaneous)
- DefaultValue: Fill value when insufficient history is available
Related Types:
- See kernels.IntegrationKernel for available weighting schemes
- See analysis.DataRef for source data configuration
- See NewGroupedAggregationPartition for grouped aggregations
Example:
aggregation := AppliedAggregation{
Name: "rolling_mean",
Data: analysis.DataRef{
PartitionName: "prices",
ValueIndices: []int{0, 1}, // Use first two price columns
},
Kernel: &kernels.ExponentialIntegrationKernel{},
DefaultValue: 0.0,
}type AppliedAggregation struct {
Name string
Data analysis.DataRef
Kernel kernels.IntegrationKernel
DefaultValue float64
}func (*AppliedAggregation) GetKernel
func (a *AppliedAggregation) GetKernel() kernels.IntegrationKernelGetKernel returns the configured integration kernel with automatic fallback.
This method ensures that callers never need to handle nil kernels by providing a sensible default. The instantaneous kernel applies no time weighting, effectively using only the most recent value for aggregation.
Returns:
- kernels.IntegrationKernel: The configured kernel, or InstantaneousIntegrationKernel if nil
Usage:
kernel := aggregation.GetKernel()
// Safe to use kernel without nil checksPerformance:
- O(1) time complexity
- No memory allocation for cached kernels
type AppliedEvolutionStrategyOptimisation
AppliedEvolutionStrategyOptimisation is the base configuration for an online evolution strategies optimisation of discounted future returns calculated by an embedded simulation.
type AppliedEvolutionStrategyOptimisation struct {
Sampler EvolutionStrategySampler
Sorting EvolutionStrategySorting
Mean EvolutionStrategyMean
Covariance EvolutionStrategyCovariance
Reward EvolutionStrategyReward
Window WindowedPartitions
Seed uint64
}type AppliedLikelihoodComparison
AppliedLikelihoodComparison configures a rolling likelihood comparison between referenced data and a model over a sliding window.
type AppliedLikelihoodComparison struct {
Name string
Model ParameterisedModel
Data analysis.DataRef
Window WindowedPartitions
// EmbeddedBurnInSteps, if non-nil, sets outer burn-in steps before the
// embedded window runs (see general.EmbeddedSimulationRunIteration). If
// nil, defaults to Window.Depth so the inner replay starts with a full window.
EmbeddedBurnInSteps *int
// WindowDataHistoryDepth, if non-nil, must map every Window.Data
// PartitionName to that partition’s StateHistoryDepth in the outer
// simulation; each value must be >= Window.Depth.
WindowDataHistoryDepth map[string]int
}type AppliedLikelihoodMeanFunctionFit
AppliedLikelihoodMeanFunctionFit configures online fitting of the model’s likelihood mean to data using a gradient function and learning rate over a finite descent schedule.
type AppliedLikelihoodMeanFunctionFit struct {
Name string
Model ParameterisedModelWithGradient
Gradient LikelihoodMeanGradient
Data analysis.DataRef
Window WindowedPartitions
// EmbeddedBurnInSteps mirrors AppliedLikelihoodComparison.EmbeddedBurnInSteps.
EmbeddedBurnInSteps *int
// WindowDataHistoryDepth mirrors AppliedLikelihoodComparison.WindowDataHistoryDepth.
WindowDataHistoryDepth map[string]int
LearningRate float64
DescentIterations int
// WarmStart, if true, seeds each outer step's inner gradient descent from
// the previous outer step's output rather than from a fixed param. Enables
// convergence to a global MLE over the full data window as outer steps
// accumulate (standard online SGD behaviour).
WarmStart bool
}type AppliedPosteriorEstimation
AppliedPosteriorEstimation is the base configuration for an online inference of a simulation (specified by partition configs) from a referenced dataset.
Windowed likelihood comparison: the embedded partition uses burn_in_steps equal to Window.Depth by default so the inner FromHistory replay has a full window before the first meaningful likelihood (earlier outer steps repeat the same inner log-likelihood, often 0, which can dominate PosteriorLogNormalisationIteration until history rolls). Override with Comparison.EmbeddedBurnInSteps. Optional Comparison.WindowDataHistoryDepth opts into a setup-time check that each Window.Data source partition’s StateHistoryDepth is at least Window.Depth.
type AppliedPosteriorEstimation struct {
LogNorm PosteriorLogNorm
Mean PosteriorMean
Covariance PosteriorCovariance
Sampler PosteriorSampler
Comparison AppliedLikelihoodComparison
PastDiscount float64
// MemoryDepth sets the likelihood partition's StateHistoryDepth — the number
// of past rows the posterior log-normalisation rolling window aggregates. Keep
// it consistent with how much history you intend to accumulate; must be >= 1.
MemoryDepth int
Seed uint64
}type AppliedSMCInference
AppliedSMCInference configures batch SMC (Sequential Monte Carlo) inference using iterated importance sampling.
type AppliedSMCInference struct {
ProposalName string
SimName string
PosteriorName string
NumParticles int
NumRounds int
Priors []inference.Prior
ParamNames []string
Model SMCParticleModel
Seed uint64
Verbose bool
}type AppliedScalarRegressionStats
AppliedScalarRegressionStats configures a partition that streams scalar OLS sufficient statistics and closed-form estimates. Wire Y and X from upstream partitions via ParamsFromUpstream (keys ScalarRegressionParamY and ScalarRegressionParamX); each side must be a single scalar state element per step.
type AppliedScalarRegressionStats struct {
Name string
Y analysis.DataRef
X analysis.DataRef
Intercept bool
Mode RegressionStatsMode
WindowLength int
MinDenominator float64
StateHistoryDepth int
}type EvolutionStrategyCovariance
EvolutionStrategyCovariance defines the configuration needed to specify the covariance update in the AppliedEvolutionStrategyOptimisation.
type EvolutionStrategyCovariance struct {
Name string
Default []float64
LearningRate float64
}type EvolutionStrategyMean
EvolutionStrategyMean defines the configuration needed to specify the mean update in the AppliedEvolutionStrategyOptimisation.
type EvolutionStrategyMean struct {
Name string
Default []float64
Weights []float64
LearningRate float64
}type EvolutionStrategyReward
EvolutionStrategyReward defines the per-step reward iteration to be wrapped with discounted cumulative accumulation inside the embedded simulation.
type EvolutionStrategyReward struct {
Partition WindowedPartition
DiscountFactor float64
}type EvolutionStrategySampler
EvolutionStrategySampler defines the configuration needed to specify the sampling distribution in the AppliedEvolutionStrategyOptimisation.
type EvolutionStrategySampler struct {
Name string
Default []float64
}type EvolutionStrategySorting
EvolutionStrategySorting defines the configuration needed to specify the sorted collection in the AppliedEvolutionStrategyOptimisation.
type EvolutionStrategySorting struct {
Name string
CollectionSize int
EmptyValue float64
}type LikelihoodMeanGradient
LikelihoodMeanGradient specifies a function mapping params and the gradient of the likelihood mean to a parameter update direction.
type LikelihoodMeanGradient struct {
Function func(
params *simulator.Params,
likeMeanGrad []float64,
) []float64
Width int
}type MCTSSelfPlaySpec
MCTSSelfPlaySpec captures the inputs needed to wire a fully-decomposed MCTS self-play stack into a stochadex simulation. The result is three outer partitions plus an embedded sub-simulation hosting the (MCTSTreeIteration + MCTSRolloutIteration) pipeline:
outer:
<Name>_apply : ApplyIteration — encoded game state; advances by
one ply per outer step using the
best-action signal from the
embedded search.
<Name>_search : EmbeddedSimulationRunIteration — runs SimsPerPly
inner steps per outer step, with
the inner sim's tree root
re-seeded each outer step from
the apply partition's row.
inner sim (inside <Name>_search):
<Name>_tree : MCTSTreeIteration — selection + backup; tree on
struct; row exposes leaf state
and root edge stats.
<Name>_rollout : MCTSRolloutIteration — one rollout per inner step,
consuming the leaf from
<Name>_tree.The (selection + expansion + backup) bundle stays together because both selection and backup mutate the same shared graph state, but rollouts split out as a first-class partition — making per-rollout scores and selection paths into stochadex-native rows that other partitions can consume via params_from_upstream.
type MCTSSelfPlaySpec[S any, A any] struct {
// Name prefix used to build per-partition names (apply, search,
// tree, rollout). Each partition's actual name will be
// "<Name>_apply" / "<Name>_search" / "<Name>_tree" / "<Name>_rollout".
Name string
// Env is the typed Environment[S, A] for both the search tree and
// the rollout playouts.
Env agents.Environment[S, A]
// Cfg supplies UCT hyperparameters and the rollout function. The
// rollout function is consumed by the rollout partition; tree
// hyperparameters (Simulations / MaxTreeDepth / Exploration /
// RolloutMaxSteps) are forwarded to the tree partition's selection
// loop.
Cfg agents.MCTSConfig[S, A]
// InitState is the encoded-via-Encoder initial game state used as
// both the apply partition's row and the inner tree partition's
// initial root.
InitState S
// Decoder / Encoder define the codec for game state. Decoder must
// round-trip Encoder.
Decoder func([]float64) (S, error)
Encoder func(S) []float64
// SimsPerPly is the inner-sim termination step count — i.e. the
// number of MCTS iterations to run between each outer ply. After a
// 2-step pipeline fill in the inner sim, this is approximately the
// number of distinct UCT iterations completed per ply.
SimsPerPly int
// MaxLegalActions is the K bound used for the tree partition's row
// layout (per-action visit / win slots, padded with zeros for
// inactive slots). Set to the maximum legal-action count any state
// can produce. Tic-tac-toe = 9; card games typically 50+.
MaxLegalActions int
// StateWidth is the encoded-state vector length (= len(Encoder(s))
// for any s).
StateWidth int
// Players is the player count (= per-player score vector length).
Players int
// Seed is the base RNG seed for both inner partitions.
Seed uint64
}type ParameterisedModel
ParameterisedModel bundles a likelihood distribution with its parameter configuration and any cross-partition parameter wiring required at runtime.
type ParameterisedModel struct {
Likelihood inference.LikelihoodDistribution
Params simulator.Params
ParamsAsPartitions map[string][]string
ParamsFromUpstream map[string]simulator.NamedUpstreamConfig
}func (*ParameterisedModel) Init
func (p *ParameterisedModel) Init()Init ensures internal parameter wiring maps are initialised.
type ParameterisedModelWithGradient
ParameterisedModelWithGradient augments ParameterisedModel with gradient support for optimisation routines.
type ParameterisedModelWithGradient struct {
Likelihood inference.LikelihoodDistributionWithGradient
Params simulator.Params
ParamsAsPartitions map[string][]string
ParamsFromUpstream map[string]simulator.NamedUpstreamConfig
}func (*ParameterisedModelWithGradient) Init
func (p *ParameterisedModelWithGradient) Init()Init ensures internal parameter wiring maps are initialised.
type PosteriorCovariance
PosteriorCovariance defines the configuration needed to specify the posterior covariance in the AppliedPosteriorEstimation.
When JustVariance is true, Default has length N (per-dimension variance) and NewPosteriorEstimationPartitions wires the sampler to use variance_partition for the posterior output (not a dense covariance).
type PosteriorCovariance struct {
Name string
Default []float64
JustVariance bool
}type PosteriorLogNorm
PosteriorLogNorm defines the configuration needed to specify the posterior log-normalisation in the AppliedPosteriorEstimation.
type PosteriorLogNorm struct {
Name string
Default float64
}type PosteriorMean
PosteriorMean defines the configuration needed to specify the posterior mean in the AppliedPosteriorEstimation.
type PosteriorMean struct {
Name string
Default []float64
}type PosteriorSampler
PosteriorSampler defines the configuration needed to specify the posterior sampler in the AppliedPosteriorEstimation.
type PosteriorSampler struct {
Name string
Default []float64
Distribution ParameterisedModel
}type RegressionStatsMode
RegressionStatsMode selects cumulative vs sliding-window sufficient statistics.
type RegressionStatsMode intconst (
// RegressionStatsCumulative accumulates (x, y) sums over all prior steps.
RegressionStatsCumulative RegressionStatsMode = iota
// RegressionStatsWindow keeps the last WindowLength pairs and recomputes sums.
RegressionStatsWindow
)type SMCInnerSimConfig
SMCInnerSimConfig describes the inner simulation that evaluates N particles through data.
type SMCInnerSimConfig struct {
// Partitions for the inner simulation (data, model, loglike, etc.).
// They are registered in the order given.
Partitions []*simulator.PartitionConfig
// Simulation config for the inner simulation.
Simulation *simulator.SimulationConfig
// LoglikePartitions lists, for each particle p (length N), the name
// of the inner partition whose state[0] is the cumulative
// log-likelihood for that particle.
LoglikePartitions []string
// ParamForwarding maps "innerPartitionName/paramName" to indices
// into the N*d flat proposal state. These are forwarded from the
// proposal partition to inner partitions via the embedded sim.
// Partition and param names must be alphanumeric+underscore only.
ParamForwarding map[string][]int
}type SMCParticleModel
SMCParticleModel describes a user-defined model for particle evaluation inside the SMC inner simulation.
type SMCParticleModel struct {
// Build creates the inner simulation configuration for N particles
// with nParams parameters each.
Build func(N int, nParams int) *SMCInnerSimConfig
}type ScalarRegressionStatsIteration
ScalarRegressionStatsIteration maintains OLS-relevant sufficient statistics for scalar y on scalar x, optionally with intercept, and writes closed-form estimates each step. Row 0 of state history is the latest values, matching LaggedValues / FromHistory conventions elsewhere.
Through-origin state (cumulative): [Sxx, Sxy, Syy, n, beta, sigma2] (width 6). With intercept (cumulative): [n, Sx, Sy, Sxx, Sxy, Syy, alpha, beta, sigma2] (width 9). Window modes prefix a packed ring of the last W (x, y) pairs plus a count slot, then the same trailing statistic/estimate block.
type ScalarRegressionStatsIteration struct {
// contains filtered or unexported fields
}func (*ScalarRegressionStatsIteration) Configure
func (s *ScalarRegressionStatsIteration) Configure(partitionIndex int, settings *simulator.Settings)Configure reads scalar_regression_* params from the partition settings.
func (*ScalarRegressionStatsIteration) Iterate
func (s *ScalarRegressionStatsIteration) Iterate(params *simulator.Params, partitionIndex int, stateHistories []*simulator.StateHistory, timestepsHistory *simulator.CumulativeTimestepsHistory) []float64Iterate updates sufficient statistics and returns the next state vector.
type WindowedPartition
WindowedPartition configures a partition that participates in a finite windowed simulation.
Usage hints:
- Partition defines the inner partition and its params.
- OutsideUpstreams map allows wiring upstreams from outside the window.
type WindowedPartition struct {
Partition *simulator.PartitionConfig
OutsideUpstreams map[string]simulator.NamedUpstreamConfig
}type WindowedPartitions
WindowedPartitions defines the sliding-window context used by analysis.
Usage hints:
- Partitions are simulated inside the window.
- Data references supply historical values to seed and drive the window.
- Depth is the number of steps in the window.
type WindowedPartitions struct {
Partitions []WindowedPartition
Data []analysis.DataRef
Depth int
}Generated by gomarkdoc