MCP HubMCP Hub
스킬 목록으로 돌아가기

simulate-stochastic-process

pjt222
업데이트됨 2 days ago
8 조회
17
2
17
GitHub에서 보기
메타aidesign

정보

이 스킬은 분석적 해법을 사용할 수 없을 때, 추정, 예측 및 시각화를 위해 마르코프 체인, 랜덤 워크, 확률미분방정식(SDE)과 같은 확률적 과정을 시뮬레이션합니다. 수렴 진단, 분산 감소 기법, 샘플 경로 시각화를 포함한 핵심 기능을 제공합니다. 개발자는 보장된 조건의 몬테카를로 추정, 분석적 결과 검증, 또는 MCMC를 통한 복잡한 사후분포 샘플링에 이를 사용해야 합니다.

빠른 설치

Claude Code

추천
기본
npx skills add pjt222/agent-almanac -a claude-code
플러그인 명령대체
/plugin add https://github.com/pjt222/agent-almanac
Git 클론대체
git clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/simulate-stochastic-process

Claude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요

문서

Simulate Stochastic Process

Simulate sample paths from stochastic processes -- discrete Markov chains, continuous-time processes, stochastic differential equations, MCMC samplers -- with convergence diagnostics, variance reduction, trajectory visualization.

When Use

  • Need generate sample paths from stochastic process for estimation, prediction, or visualization
  • Analytical solutions intractable; simulation only feasible approach
  • Running Monte Carlo estimation, need convergence guarantees and uncertainty quantification
  • Want validate analytical results (stationary distributions, hitting times) against empirical simulation
  • Need sample from complex posterior distribution using MCMC
  • Prototyping stochastic model before committing to full analytical treatment

Inputs

Required

InputTypeDescription
process_typestringType of process: "dtmc", "ctmc", "random_walk", "brownian_motion", "sde", "mcmc"
parametersdictProcess-specific parameters (transition matrix, drift/diffusion coefficients, target density, etc.)
n_pathsintegerNumber of independent sample paths to simulate
n_stepsintegerNumber of time steps per path (or total MCMC iterations)

Optional

InputTypeDefaultDescription
initial_statescalar/vectorprocess-specificStarting state or distribution for each path
dtfloat0.01Time step size for continuous-time discretization
seedintegerrandomRandom seed for reproducibility
burn_inintegern_steps / 10Number of initial steps to discard (MCMC)
thinninginteger1Keep every k-th sample to reduce autocorrelation
variance_reductionstring"none"Method: "none", "antithetic", "stratified", "control_variate"
target_functioncallablenoneFunction to evaluate along paths for Monte Carlo estimation

Steps

Step 1: Define Process Model and Parameters

1.1. Identify process type, gather all required parameters:

  • DTMC: Transition matrix P and state space. Validate P is row-stochastic.
  • CTMC: Rate matrix Q. Validate rows sum to 0 and off-diagonal entries are non-negative.
  • Random walk: Step distribution (e.g., {-1, +1} with equal probability), boundaries if any.
  • Brownian motion: Drift mu, volatility sigma, dimension d.
  • SDE (Ito): Drift function a(x,t), diffusion function b(x,t).
  • MCMC: Target log-density, proposal mechanism (random walk Metropolis, Hamiltonian, Gibbs components).

1.2. Validate parameter consistency:

  • Matrix dimensions match state space size.
  • SDE coefficients satisfy growth and Lipschitz conditions (at least informally) for the chosen solver.
  • MCMC proposal is well-defined for the support of the target distribution.

1.3. Set the random seed for reproducibility.

Got: Fully specified stochastic model with validated parameters and reproducible random state.

If fail: Parameters inconsistent (e.g., non-stochastic matrix)? Correct before proceeding. SDE coefficients pathological? Consider different discretization scheme.

Step 2: Select Simulation Method

2.1. Choose appropriate algorithm based on process type:

ProcessMethodKey Property
DTMCDirect sampling from transition rowExact
CTMCGillespie algorithm (SSA)Exact, event-driven
CTMC (approx.)Tau-leapingApproximate, faster for high rates
Random walkDirect sampling of incrementsExact
Brownian motionCumulative sum of Gaussian incrementsExact for fixed dt
SDE (general)Euler-MaruyamaOrder 0.5 strong, order 1.0 weak
SDE (higher order)MilsteinOrder 1.0 strong (scalar noise)
SDE (stiff)Implicit Euler-MaruyamaStable for stiff drift
MCMC (general)Metropolis-HastingsAsymptotically exact
MCMC (gradient)Hamiltonian Monte Carlo (HMC)Better mixing for high dimensions
MCMC (conditional)Gibbs samplerExact conditionals when available

2.2. For SDE methods, choose dt small enough for numerical stability. A useful heuristic: start with dt = 0.01 and halve it until results stabilize.

2.3. For MCMC, tune the proposal scale to achieve an acceptance rate of approximately:

  • 23.4% for high-dimensional random walk Metropolis
  • 57.4% for one-dimensional targets
  • 65-90% for HMC (depends on trajectory length)

2.4. If variance reduction is requested, configure it:

  • Antithetic variates: For each path with random increments Z, also simulate with -Z.
  • Stratified sampling: Partition the probability space and sample within each stratum.
  • Control variates: Identify a correlated quantity with known expectation to reduce variance.

Got: Selected simulation algorithm matched to process type with appropriate tuning parameters.

If fail: Chosen method unstable (e.g., Euler-Maruyama diverging)? Switch to implicit method or reduce dt.

Step 3: Implement and Run Simulation

3.1. Allocate storage for n_paths trajectories, each length n_steps (or dynamic for event-driven methods like Gillespie).

3.2. For each path i = 1, ..., n_paths:

DTMC / Random Walk:

  • Set x[0] = initial_state
  • For t = 1, ..., n_steps: sample x[t] from the transition distribution given x[t-1]

CTMC (Gillespie):

  • Set x[0] = initial_state, time = 0
  • While time < T_max:
    • Compute total rate lambda = -Q[x, x]
    • Sample holding time tau ~ Exp(lambda)
    • Sample next state from transition probabilities Q[x, j] / lambda for j != x
    • Update time += tau, record transition

SDE (Euler-Maruyama):

  • Set x[0] = initial_state
  • For t = 1, ..., n_steps:
    • dW = sqrt(dt) * N(0, I) (Wiener increment)
    • x[t] = x[t-1] + a(x[t-1], t*dt) * dt + b(x[t-1], t*dt) * dW

MCMC (Metropolis-Hastings):

  • Set x[0] = initial_state
  • For t = 1, ..., n_steps:
    • Propose x' ~ q(x' | x[t-1])
    • Compute acceptance ratio alpha = min(1, p(x') * q(x[t-1]|x') / (p(x[t-1]) * q(x'|x[t-1])))
    • Accept with probability alpha: x[t] = x' if accepted, else x[t] = x[t-1]
    • Record acceptance decision

3.3. If target_function is provided, evaluate it at each state along each path and store the values.

3.4. Apply thinning: keep every thinning-th sample.

3.5. Discard burn_in samples from the beginning of each path (primarily for MCMC).

Got: n_paths complete trajectories stored in memory, optional function evaluations. MCMC acceptance rate within target range.

If fail: Simulation produces NaN or Inf values? Reduce dt for SDE methods or check parameter validity. MCMC acceptance rate near 0% or 100%? Adjust proposal scale.

Step 4: Apply Convergence Diagnostics

4.1. Trace plots: Plot the value of each component over time for a subset of paths. Visual inspection for stationarity (no trends, stable variance).

4.2. Gelman-Rubin diagnostic (R-hat): For MCMC with multiple chains:

  • Compute within-chain variance W and between-chain variance B.
  • R_hat = sqrt((n-1)/n + B/(n*W))
  • Convergence indicated by R_hat < 1.01 (strict) or R_hat < 1.1 (lenient).

4.3. Effective sample size (ESS):

  • Estimate autocorrelation at increasing lags.
  • ESS = n_samples / (1 + 2 * sum(autocorrelations))
  • Rule of thumb: ESS > 400 for reliable posterior summaries.

4.4. Geweke diagnostic: Compare the mean of the first 10% and last 50% of each chain. The z-score should be within [-2, 2] for convergence.

4.5. For non-MCMC processes: Verify that time-averaged statistics (mean, variance) stabilize as path length increases. Plot running averages.

4.6. Report a summary table:

DiagnosticValueThresholdStatus
R-hat (max)...< 1.01...
ESS (min)...> 400...
Geweke z (max abs)...< 2.0...
Acceptance rate...0.15-0.50...

Got: All convergence diagnostics pass thresholds. Trace plots show stable, well-mixing chains.

If fail: R-hat > 1.1? Run longer chains or improve proposal. ESS very low? Increase thinning or switch to better sampler (e.g., HMC). Geweke fails? Extend burn-in.

Step 5: Compute Summary Statistics with Confidence Intervals

5.1. For each quantity of interest (state occupancy, function expectation, hitting times):

  • Compute the point estimate as the sample mean across paths (after burn-in and thinning).
  • Compute the standard error using the effective sample size: SE = SD / sqrt(ESS).

5.2. Construct confidence intervals:

  • Normal approximation: estimate +/- z_{alpha/2} * SE
  • For skewed distributions, use percentile bootstrap or batch means.

5.3. If variance reduction was applied, compute the variance reduction factor:

  • VRF = Var(naive estimator) / Var(reduced estimator)
  • Report the effective speedup.

5.4. For Monte Carlo integration estimates:

  • Report the estimate, standard error, 95% CI, ESS, and number of function evaluations.

5.5. For distribution estimates:

  • Compute empirical quantiles (median, 2.5th, 97.5th percentiles).
  • Kernel density estimates for continuous quantities.

5.6. Tabulate all summary statistics with their uncertainties.

Got: Point estimates with associated standard errors and confidence intervals. Variance reduction (if applied) yields VRF > 1.

If fail: Confidence intervals too wide? Increase n_paths or n_steps. Variance reduction worsens estimates (VRF < 1)? Disable it -- control variate or antithetic scheme may not suit problem.

Step 6: Visualize Trajectories and Distributions

6.1. Trajectory plots: Plot a representative subset of sample paths (5-20 paths) over time. Use transparency for overlapping paths.

6.2. Ensemble statistics: Overlay the mean trajectory and pointwise 95% confidence bands across all paths.

6.3. Marginal distributions: At selected time points, plot histograms or density estimates of the state distribution across paths.

6.4. Stationary distribution comparison: If an analytical stationary distribution is available, overlay it on the empirical histogram from the final time slice.

6.5. Autocorrelation plots: For MCMC, plot the autocorrelation function (ACF) for each component up to a reasonable lag.

6.6. Diagnostic dashboard: Combine trace plots, ACF plots, running mean plots, and marginal densities into a single multi-panel figure for comprehensive assessment.

6.7. Save all figures in both vector (PDF/SVG) and raster (PNG) formats for documentation.

Got: Publication-quality figures show trajectory behavior, distributional convergence, diagnostic summaries. Analytical solutions (where available) match empirical results.

If fail: Visualizations reveal non-stationarity or multimodality not expected from model? Revisit Steps 1-2 for parameter or method errors. Plots cluttered? Reduce number of displayed paths or increase figure size.

Checks

  • All simulated trajectories remain in valid state space (no out-of-bounds values, no NaN/Inf)
  • DTMC/CTMC: empirical stationary distribution converges to analytical one (within expected Monte Carlo error)
  • SDE: halving dt does not qualitatively change results (convergence order check)
  • MCMC: R-hat < 1.01, ESS > 400, Geweke z-scores within [-2, 2]
  • Confidence interval widths decrease proportional to 1/sqrt(n_paths) (central limit theorem)
  • Variance reduction techniques yield VRF > 1 (estimates improve, not worsen)
  • Reproducibility: re-running with same seed produces identical results

Pitfalls

  • Insufficient burn-in for MCMC: Starting from poor initial state needs long burn-in before samples represent target distribution. Always inspect trace plots and use convergence diagnostics rather than guessing burn-in length.
  • Euler-Maruyama instability for stiff SDEs: Drift term has large gradients? Explicit Euler-Maruyama can diverge. Switch to implicit methods or use adaptive step sizing.
  • Confuse strong and weak convergence for SDEs: Strong convergence measures pathwise error (important for individual trajectories); weak convergence measures distributional error (sufficient for expectations). Euler-Maruyama has weak order 1.0 but strong order 0.5.
  • Pseudorandom number generator quality: Very long simulations? Low-quality RNGs can produce correlated samples. Use well-tested generator (Mersenne Twister, PCG, or Xoshiro), verify independence.
  • Ignore autocorrelation in MCMC: Treating autocorrelated MCMC samples as independent underestimates uncertainty. Always use effective sample size, not raw sample count, for standard errors.
  • Antithetic variates for non-monotone functions: Antithetic sampling reduces variance only when estimand is monotone function of underlying uniforms. Non-monotone functions? Can increase variance.
  • Memory for large simulations: Storing all time steps of many long paths can exhaust memory. Use online statistics (running mean, variance) when full trajectories not needed for visualization.

See Also

  • Model Markov Chain -- provides transition matrices and analytical solutions that simulation validates
  • Fit Hidden Markov Model -- simulation from fitted HMMs enables posterior predictive checking and synthetic data generation

GitHub 저장소

pjt222/agent-almanac
경로: i18n/caveman/skills/simulate-stochastic-process
0
agentsagentskillsai-assisted-developmentclaude-codeskillsteams

연관 스킬

content-collections

메타

이 스킬은 콘텐츠 콜렉션(Content Collections)을 위한 프로덕션 검증된 설정을 제공합니다. 콘텐츠 콜렉션은 Markdown/MDX 파일을 Zod 검증이 포함된 타입 안전한 데이터 콜렉션으로 변환해주는 TypeScript 최우선 도구입니다. 블로그, 문서 사이트 또는 콘텐츠 중심의 Vite + React 애플리케이션을 구축할 때 타입 안전성과 자동 콘텐츠 검증을 보장하기 위해 사용하세요. Vite 플러그인 구성과 MDX 컴파일부터 배포 최적화 및 스키마 검증에 이르기까지 모든 것을 다룹니다.

스킬 보기

polymarket

메타

이 스킬은 개발자들이 Polymarket 예측 시장 플랫폼을 활용한 애플리케이션을 구축할 수 있도록 지원하며, 거래 및 시장 데이터를 위한 API 통합 기능을 포함합니다. 또한 WebSocket을 통한 실시간 데이터 스트리밍을 제공하여 실시간 거래와 시장 활동을 모니터링할 수 있습니다. 이를 통해 거래 전략을 구현하거나 실시간 시장 업데이트를 처리하는 도구를 생성하는 데 활용할 수 있습니다.

스킬 보기

creating-opencode-plugins

메타

이 스킬은 개발자들이 명령어, 파일, LSP 작업 등 25개 이상의 이벤트 유형에 연결되는 OpenCode 플러그인을 만들 수 있도록 돕습니다. JavaScript/TypeScript 모듈을 위한 플러그인 구조, 이벤트 API 명세, 구현 패턴을 제공합니다. OpenCode AI 어시스턴트의 라이프사이클을 사용자 정의 이벤트 기반 로직으로 가로채거나, 모니터링하거나, 확장해야 할 때 사용하세요.

스킬 보기

sglang

메타

SGLang은 RadixAttention 프리픽스 캐싱을 활용하여 JSON, 정규식, 에이전트 워크플로우를 위한 고속 구조화 생성에 특화된 고성능 LLM 서빙 프레임워크입니다. 특히 반복되는 프리픽스가 있는 작업에서 상당히 빠른 추론 속도를 제공하여 복잡한 구조화 출력 및 다중 턴 대화에 이상적입니다. 제약 디코딩이 필요하거나 광범위한 프리픽스 공유가 있는 애플리케이션을 구축할 때는 vLLM과 같은 대안보다 SGLang을 선택하십시오.

스킬 보기