计划执行与检查节点
executing-plans
按既定实施计划完成工作,保持过程检查和反馈。
simulate-stochastic-process【效率与协作】Simulate stochastic processes (Markov chains, random walks, SDEs, MCMC) w/ convergence diagnostics, variance reduction, viz. Use → sample paths for est/predict/viz, analytical intractable, Monte Carlo needing convergence guarantees, validate analytical vs empirical, sample complex posteriors via MCMC.
独立 GitHub 快照 · 自动分类 · 以原作者文档为准
Sample paths from stochastic processes — discrete Markov, continuous-time, SDEs, MCMC samplers — w/ convergence diagnostics, variance reduction, trajectory viz.
| Input | Type | Description |
|---|---|---|
process_type | string | "dtmc", "ctmc", "random_walk", "brownian_motion", "sde", "mcmc" |
parameters | dict | Process-specific (transition matrix, drift/diffusion, target density) |
n_paths | integer | Independent paths to sim |
n_steps | integer | Time steps per path (or total MCMC iters) |
| Input | Type | Default | Description |
|---|---|---|---|
initial_state | scalar/vector | process-specific | Start state |
dt | float | 0.01 | Time step → continuous discretization |
seed | integer | random | Reproducibility |
burn_in | integer | n_steps / 10 | Initial discard (MCMC) |
thinning | integer | 1 | Keep every k-th → reduce autocorr |
variance_reduction | string | "none" | "none", "antithetic", "stratified", "control_variate" |
target_function | callable | none | Eval along paths → MC est |
1.1. ID process type + gather params:
P + state space. Validate row-stochastic.Q. Rows sum 0, off-diag non-neg.{-1, +1} equal prob), boundaries.mu, vol sigma, dim d.a(x,t), diffusion b(x,t).1.2. Validate consistency:
1.3. Set seed → reproducibility.
Got: Fully spec'd model w/ validated params + reproducible RNG state.
If err: Inconsistent params (e.g. non-stochastic matrix) → correct first. Pathological SDE coefs → diff discretization scheme.
2.1. Choose algo per type:
| Process | Method | Key Property |
|---|---|---|
| DTMC | Direct sampling from transition row | Exact |
| CTMC | Gillespie algorithm (SSA) | Exact, event-driven |
| CTMC (approx.) | Tau-leaping | Approximate, faster for high rates |
| Random walk | Direct sampling of increments | Exact |
| Brownian motion | Cumulative sum of Gaussian increments | Exact for fixed dt |
| SDE (general) | Euler-Maruyama | Order 0.5 strong, order 1.0 weak |
| SDE (higher order) | Milstein | Order 1.0 strong (scalar noise) |
| SDE (stiff) | Implicit Euler-Maruyama | Stable for stiff drift |
| MCMC (general) | Metropolis-Hastings | Asymptotically exact |
| MCMC (gradient) | Hamiltonian Monte Carlo (HMC) | Better mixing for high dimensions |
| MCMC (conditional) | Gibbs sampler | Exact conditionals when available |
2.2. SDE → dt small enough for stability. Heuristic: start dt = 0.01, halve until results stabilize.
2.3. MCMC → tune proposal scale → acceptance ~:
2.4. Variance reduction config:
Z → also sim w/ -ZGot: Algo matched to type w/ tuning params.
If err: Unstable (Euler-Maruyama diverging) → implicit method | reduce dt.
3.1. Allocate storage n_paths × n_steps (or dynamic for event-driven Gillespie).
3.2. Per path i = 1, ..., n_paths:
DTMC / Random Walk:
x[0] = initial_statet = 1..n_steps: sample x[t] from transition given x[t-1]CTMC (Gillespie):
x[0] = initial_state, time = 0time < T_max:
lambda = -Q[x, x]tau ~ Exp(lambda)Q[x, j] / lambda for j != xtime += tau, recordSDE (Euler-Maruyama):
x[0] = initial_statet = 1..n_steps:
dW = sqrt(dt) * N(0, I) (Wiener)x[t] = x[t-1] + a(x[t-1], t*dt) * dt + b(x[t-1], t*dt) * dWMCMC (Metropolis-Hastings):
x[0] = initial_statet = 1..n_steps:
x' ~ q(x' | x[t-1])alpha = min(1, p(x') * q(x[t-1]|x') / (p(x[t-1]) * q(x'|x[t-1])))alpha: x[t] = x' if accepted, else x[t-1]3.3. target_function provided → eval at each state, store.
3.4. Apply thinning: keep every thinning-th.
3.5. Discard burn_in from start (MCMC).
Got: n_paths complete trajectories in mem, optional fn evals. MCMC acceptance in target range.
If err: NaN/Inf → reduce dt (SDE) | check params. MCMC accept ~0% | ~100% → adjust proposal scale.
4.1. Trace plots: per-component over time, subset paths. Visual check stationarity (no trends, stable var).
4.2. Gelman-Rubin (R-hat) for multi-chain MCMC:
W, between-chain BR_hat = sqrt((n-1)/n + B/(n*W))R_hat < 1.01 (strict) | < 1.1 (lenient) → convergence4.3. Effective sample size (ESS):
ESS = n_samples / (1 + 2 * sum(autocorr))ESS > 400 for reliable posterior summaries4.4. Geweke: cmp mean first 10% vs last 50%. Z-score in [-2, 2] → convergence.
4.5. Non-MCMC: time-avg stats (mean, var) stabilize as path length ↑. Plot running averages.
4.6. Summary table:
| Diagnostic | Value | Threshold | Status |
|---|---|---|---|
| R-hat (max) | ... | < 1.01 | ... |
| ESS (min) | ... | > 400 | ... |
| Geweke z (max abs) | ... | < 2.0 | ... |
| Acceptance rate | ... | 0.15-0.50 | ... |
Got: All diagnostics pass thresholds. Trace shows stable, well-mixing chains.
If err: R-hat > 1.1 → run longer | improve proposal. ESS very low → ↑ thinning | better sampler (HMC). Geweke fails → extend burn-in.
5.1. Per quantity (state occupancy, fn E, hitting times):
SE = SD / sqrt(ESS)5.2. Build CIs:
est +/- z_{alpha/2} * SE5.3. Variance reduction → VRF:
VRF = Var(naive) / Var(reduced)5.4. MC integration: report est, SE, 95% CI, ESS, # fn evals.
5.5. Distribution est:
5.6. Tabulate all w/ uncertainties.
Got: Point ests + SEs + CIs. Variance reduction (if applied) → VRF > 1.
If err: CIs too wide → ↑ n_paths | n_steps. Var reduction worsens (VRF < 1) → disable; control variate | antithetic mismatched.
6.1. Trajectory plots: 5-20 paths over time. Use transparency for overlap.
6.2. Ensemble stats: overlay mean + pointwise 95% CI bands across paths.
6.3. Marginal distributions: at selected times, hist | density estimates of state across paths.
6.4. Stationary cmp: analytical avail → overlay on empirical hist (final time slice).
6.5. Autocorr plots (MCMC): ACF per component, reasonable lag.
6.6. Diagnostic dashboard: trace + ACF + running mean + marginal density → multi-panel.
6.7. Save figures vector (PDF/SVG) + raster (PNG) → docs.
Got: Pub-quality figures showing trajectory, distributional convergence, diagnostics. Analytical (where avail) matches empirical.
If err: Viz reveals non-stationarity | unexpected multimodality → revisit Steps 1-2 (param/method err). Cluttered plots → reduce paths shown | bigger figure.
dt doesn't qualitatively change → convergence order1/sqrt(n_paths) (CLT)