model-markov-chain
정보
이 스킬은 메모리리스 시스템 모델링을 위해 이산 또는 연속 마르코프 체인을 구축하고 분석합니다. 전이 행렬을 구성하고, 상태를 분류하며, 정상 분포를 계산하고, 평균 최초 도달 시간을 결정합니다. 정상 상태 확률 계산, 예상 도달 시간 계산, 또는 HMM과 MDP의 기반으로 활용할 수 있습니다.
빠른 설치
Claude Code
추천npx skills add pjt222/agent-almanac -a claude-code/plugin add https://github.com/pjt222/agent-almanacgit clone https://github.com/pjt222/agent-almanac.git ~/.claude/skills/model-markov-chainClaude Code에서 이 명령을 복사하여 붙여넣어 스킬을 설치하세요
문서
Model Markov Chain
Construct + classify + analyze DTMC/CTMC from raw transition data or domain specs → stationary distributions + mean first passage times + simulation validation. Both DTMC + CTMC workflows end-to-end.
Use When
- Memoryless system: future depends only on current state
- Observed transition counts/rates between finite state set
- Long-run steady-state probabilities
- Expected hitting times or absorption probabilities
- Classify states transient/recurrent/absorbing for structural analysis
- Compare alternative Markov models for same system
- Foundation for advanced (HMM, RL MDPs)
In
Required
| Input | Type | Description |
|---|---|---|
state_space | list/vector | Exhaustive enumeration of all states in the chain |
transition_data | matrix, data frame, or edge list | Raw transition counts, a probability matrix, or a rate matrix (for CTMC) |
chain_type | string | Either "discrete" (DTMC) or "continuous" (CTMC) |
Optional
| Input | Type | Default | Description |
|---|---|---|---|
initial_distribution | vector | uniform | Starting state probabilities |
time_horizon | integer/float | 100 | Number of steps (DTMC) or time units (CTMC) for simulation |
tolerance | float | 1e-10 | Convergence tolerance for iterative computations |
absorbing_states | list | auto-detect | States explicitly marked as absorbing |
labels | list | state indices | Human-readable names for each state |
method | string | "eigen" | Solver method: "eigen", "power", or "linear_system" |
Do
Step 1: Define State Space + Transitions
1.1. Enumerate all distinct states. Confirm exhaustive + mutually exclusive.
1.2. Raw obs → tabulate counts into n x n count matrix C where C[i,j] = transitions from i to j.
1.3. CTMC → collect holding times each state alongside transition destinations.
1.4. Verify no state missing → every observed origin + destination in state space.
1.5. Doc data source, observation period, filtering. Provenance essential for reproducing + explaining anomalies.
→ Well-defined state space size n + count matrix or (origin, destination, rate/count) tuples covering all observed transitions. Small enough for matrix ops (typically n < 10000 dense).
If err: states missing → re-examine source, expand enumeration. Too large → lump rare into "other" or simulation-based. Extremely sparse → verify observation period long enough.
Step 2: Construct Transition Matrix or Generator
2.1. DTMC: Normalize each row of count matrix → probability matrix P:
P[i,j] = C[i,j] / sum(C[i,])- Verify row sums = 1 within tolerance
2.2. CTMC: Construct rate (generator) matrix Q:
- Off-diag:
Q[i,j] = rate i to j - Diag:
Q[i,i] = -sum(Q[i,j] for j != i) - Verify row sums = 0 within tolerance
2.3. Zero-count rows (states never observed as origins) → smoothing: Laplace, absorbing, or flag for review.
2.4. Store format suitable for downstream (dense small, sparse large).
→ Valid stochastic P (rows sum 1) or generator Q (rows sum 0), no neg off-diag in P, no pos diag in Q.
If err: row sums deviate → check data corruption or float issues. Re-normalize or re-examine.
Step 3: Classify States
3.1. Communication classes via strongly connected components of directed graph (positive prob edges only).
3.2. Per class:
- Recurrent if no outgoing edges to other classes
- Transient if has outgoing edges
- Absorbing if single state w/
P[i,i] = 1
3.3. Periodicity per recurrent class via GCD of cycle lengths. Period 1 = aperiodic.
3.4. Irreducible (single class) or reducible (multiple)?
3.5. Summarize: each class, type, period, absorbing states.
→ Complete classification: every state assigned class + labels (transient/positive recurrent/null recurrent/absorbing) + periodicity.
If err: graph analysis inconsistent → verify no neg entries + rows sum correctly. Very large → iterative graph algorithms not full matrix powers.
Step 4: Stationary Distribution
4.1. Irreducible aperiodic: Solve pi * P = pi s.t. sum(pi) = 1.
- Reformulate
pi * (P - I) = 0w/ normalization - Eigendecomp:
pi= left eigenvector ofPfor eigenvalue 1, normalized
4.2. Irreducible periodic: Stationary still exists but doesn't converge from arbitrary init. Same as 4.1.
4.3. Reducible: Stationary per recurrent class independently. Overall = convex combo depending on absorption probabilities from transient.
4.4. CTMC: Solve pi * Q = 0 w/ sum(pi) = 1.
4.5. Verify: pi * P (or Q) = pi within tolerance.
4.6. Reducible → absorption probabilities from each transient to each recurrent class. Combined w/ per-class stationary → long-run conditional on start.
4.7. Spectral gap (largest vs. 2nd-largest eigenvalue magnitudes). Governs convergence rate, useful for sim length Step 6.
→ Probability vector pi length n, all non-neg, sum 1, satisfies balance equations within tolerance. Spectral gap > 0 for aperiodic irreducible.
If err: eigensolver no converge → iterative power method (pi_k+1 = pi_k * P until converge). Multiple eigenvalues = 1 → reducible, handle 4.3. Very small spectral gap → mixes slowly, needs very long sims.
Step 5: Mean First Passage Times
5.1. Define m[i,j] = expected steps to reach j from i.
5.2. Irreducible → solve linear system:
m[i,j] = 1 + sum(P[i,k] * m[k,j] for k != j)for alli != jm[j,j] = 1 / pi[j](mean recurrence)
5.3. Absorbing → absorption probs + expected times:
- Partition
Pinto transient (Q_t) + absorbing - Fundamental:
N = (I - Q_t)^{-1} - Expected steps to absorption:
N * 1 - Absorption probs:
N * RwhereR= transient-to-absorbing block
5.4. CTMC → step counts → expected holding times via generator matrix.
5.5. Present matrix/table of pairwise FPT for key state pairs.
→ FPT matrix: diag = mean recurrence (1/pi[j]), off-diag = finite for communicating pairs.
If err: linear system singular → transient states can't reach target. Report unreachable as infinite. Verify chain structure Step 3.
Step 6: Validate w/ Simulation
6.1. Sim K independent paths for T steps, starting from initial dist.
6.2. Estimate stationary empirically: state occupancy frequencies across paths after burn-in.
6.3. Compare sim freq vs. analytical stationary. Total variation distance or chi-squared.
6.4. Estimate FPT empirically: first hitting time per target state across reps.
6.5. Report agreement:
- Max abs deviation analytical vs. sim stationary probs
- 95% CI for sim FPT vs. analytical
6.6. Discrepancies > tolerance → re-examine matrix construction + classification.
→ Sim stationary within 0.01 TV distance of analytical (sufficient runs). Sim FPT within 10% of analytical.
If err: increase T or K. Persists → analytical may have numerical errors, recompute higher precision.
Check
- Transition matrix
P: all non-neg, rows sum 1 (orQrows sum 0 CTMC) - Stationary
pivalid probability vector,pi * P = pi - Mean recurrence =
1/pi[j]for each recurrent statej - Sim state freqs converge to analytical stationary
- State classification consistent: no recurrent state edges leaving its class
- All eigenvalues of
P≤ 1 magnitude, exactly one = 1 per recurrent class - Absorbing chains: absorption probs from each transient sum to 1 across absorbing classes
- Fundamental
N = (I - Q_t)^{-1}all positive (expected visit counts positive) - Detailed balance iff reversible:
pi[i] * P[i,j] = pi[j] * P[j,i]for alli,j
Traps
- Non-exhaustive state space: Missing states → sub-stochastic (rows < 1). Always verify row sums first
- Confuse DTMC vs. CTMC: Rate matrix has non-pos diag + rows sum 0. DTMC formulas on rate matrix → nonsense
- Ignore periodicity: Periodic chain has valid stationary but doesn't converge usual sense. Mixing time analysis must account for period
- Numerical instability large chains: Eigendecomp large dense matrices expensive + loses precision. Use sparse solvers or iterative for >few hundred states
- Zero-prob transitions: Structural zeros → reducible. Verify irreducibility before single stationary
- Insufficient sim length: Short sims w/ poor mixing → biased. Always compute effective sample size + check trace plots
- Assume reversibility w/o checking: Many shortcuts (detailed balance) only reversible chains. Verify
pi[i] * P[i,j] = pi[j] * P[j,i]before - Float accumulation in power method: Iterating
pi * Pmany times accumulates rounding. Periodically re-normalize during power iteration
→
- Fit Hidden Markov Model — extends Markov chains to latent-state models w/ observed emissions
- Simulate Stochastic Process — general sim framework for Markov chain sample paths + Monte Carlo validation
GitHub 저장소
연관 스킬
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을 선택하십시오.
