An open API service indexing awesome lists of open source software.

https://github.com/shravanngoswamii/mcmcvisualizer

Parse, analyze, and export MCMC sampling data in JavaScript or TypeScript. Zero dependencies, works in browser and Node.js.
https://github.com/shravanngoswamii/mcmcvisualizer

mcmc mcmc-analysis statistics

Last synced: about 2 months ago
JSON representation

Parse, analyze, and export MCMC sampling data in JavaScript or TypeScript. Zero dependencies, works in browser and Node.js.

Awesome Lists containing this project

README

          

# mcmc-visualizer

Parse, analyze, plot, and export MCMC sampling data in JavaScript/TypeScript. Zero runtime dependencies, works in browser and Node.js.

## Supported Formats

| Format | Read | Write |
|--------|------|-------|
| Turing.jl CSV (long) | yes | — |
| Turing.jl CSV (wide) | yes | — |
| Stan CSV | yes | — |
| MCMCChains.jl JSON | yes | — |
| ArviZ JSON | yes | — |
| Generic JSON | yes | yes |
| Raw arrays | yes | — |

## Install

```bash
npm install mcmc-visualizer
```

## Quick Start

```typescript
import { fromTuringCSV, fromStanCSV, fromAutoDetect } from 'mcmc-visualizer';

// Parse from a CSV string
const data = fromTuringCSV(csvText);

// Or auto-detect the format
const data2 = fromAutoDetect(csvText);

// Get variable names and chain names
console.log(data.variableNames); // ['alpha', 'beta', 'sigma']
console.log(data.chainNames); // ['chain#1', 'chain#2']

// Get draws for a specific variable and chain
const draws = data.getDraws('alpha', 'chain#1'); // Float64Array

// Get all draws across chains
const allDraws = data.getAllDraws('alpha'); // Float64Array

// Compute full summary table
const summary = data.summary();
// [{ variable, mean, stdev, mcse, ess, bulkEss, tailEss, rhat, splitRhat, geweke, quantiles, hdi90, ... }, ...]

// Per-chain stats
const seqStats = data.sequenceStats('alpha', 'chain#1');
// { mean, stdev, ess, essPerDraw, mcse, skewness, excessKurtosis, autocorrelation, count }
```

## Diagnostics

Built-in MCMC diagnostics with no dependencies:

- **ESS** (Effective Sample Size) via FFT-based autocorrelation
- **Bulk ESS / Tail ESS** for robust convergence checks
- **R-hat** (Gelman-Rubin convergence diagnostic)
- **Split R-hat** for split-chain convergence checks
- **MCSE** (Monte Carlo standard error)
- **Geweke z-score / p-value**
- **Autocorrelation** at all lags
- **HDI** (Highest Density Interval)
- **Skewness / Excess Kurtosis**
- **Quantiles** (5%, 25%, 50%, 75%, 95%)

```typescript
import { computeESS, computeRhat, computeHDI, computeMCSE } from 'mcmc-visualizer';

const { ess, autocorrelation } = computeESS(new Float64Array([...]));
const rhat = computeRhat([chain1, chain2], 'rank');
const [lo, hi] = computeHDI(new Float64Array([...]), 0.9);
const mcse = computeMCSE(new Float64Array([...]));
```

## Export

```typescript
import { toJSON } from 'mcmc-visualizer';

const json = toJSON(data);
// Output: { "chain#1": { "mu": [1.2, 1.3, ...], "sigma": [...] }, "chain#2": { ... } }
```

This format is readable by `fromChainArrays()` after `JSON.parse()`.

## Data Manipulation

```typescript
// Discard warmup (first 500 draws)
const postWarmup = data.slice(500);

// Keep only specific chains
const chain1Only = data.filterChains(['chain#1']);

// Keep only specific variables
const subset = data.filterVariables(['alpha', 'beta']);
```

## Construct from Arrays

```typescript
import { fromChainArrays } from 'mcmc-visualizer';

const data = fromChainArrays({
'chain#1': { alpha: [1.5, 2.3, 1.8], beta: [0.5, 0.7, 0.6] },
'chain#2': { alpha: [1.6, 2.4, 1.7], beta: [0.45, 0.65, 0.55] },
});
```

## Stan CSV (Multiple Files)

Stan outputs one CSV file per chain:

```typescript
import { fromStanCSVFiles } from 'mcmc-visualizer';

const data = fromStanCSVFiles([chain1Text, chain2Text, chain3Text]);
```

## Browser Usage

Works directly in the browser with any bundler or via CDN:

```html

import { fromAutoDetect } from 'mcmc-visualizer';

document.getElementById('upload').addEventListener('change', async (e) => {
const text = await e.target.files[0].text();
const data = fromAutoDetect(text);
console.table(data.summary());
});

```

## API

### Factory Functions

| Function | Description |
|----------|-------------|
| `fromTuringCSV(text)` | Parse Turing.jl CSV (long or wide format) |
| `fromStanCSV(text)` | Parse a single Stan CSV file |
| `fromStanCSVFiles(files)` | Parse multiple Stan CSV files as separate chains |
| `fromMCMCChainsJSON(text)` | Parse MCMCChains.jl JSON export |
| `fromArviZJSON(input)` | Parse ArviZ JSON (posterior group only) |
| `fromAutoDetect(text)` | Auto-detect format and parse |
| `fromChainArrays(data)` | Construct from `{ chain: { var: number[] } }` |

### InferenceData

| Method | Returns |
|--------|---------|
| `.getDraws(variable, chain?)` | `Float64Array` |
| `.getAllDraws(variable)` | `Float64Array` (concatenated across chains) |
| `.sequenceStats(variable, chain)` | `SequenceStats` |
| `.variableStats(variable)` | `VariableStats` |
| `.summary()` | `VariableSummary[]` |
| `.slice(start, end?)` | `InferenceData` |
| `.filterChains(names)` | `InferenceData` |
| `.filterVariables(names)` | `InferenceData` |

### Export

| Function | Description |
|----------|-------------|
| `toJSON(data)` | Serialize to `{ chain: { var: number[] } }` JSON string |
| `detectFormat(text)` | Detect file format: `'turing-csv' \| 'stan-csv' \| 'mcmcchains-json' \| 'unknown'` |

### Standalone Stats

| Function | Description |
|----------|-------------|
| `computeESS(chain)` | FFT-based effective sample size |
| `computeEssBulk(chains)` | Rank-normalized bulk ESS |
| `computeEssTail(chains)` | Tail ESS |
| `computeRhat(chains, kind?)` | Rank-normalized R-hat (`'rank' \| 'bulk' \| 'tail' \| 'basic'`) |
| `computeSplitRhat(chains)` | Split-chain R-hat |
| `computeMCSE(chain)` | Monte Carlo standard error |
| `computeMCSEMultiChain(chains)` | Multi-chain MCSE via bulk ESS |
| `computeGeweke(chain)` | Geweke z-score and p-value |
| `computeMean(arr)` | Arithmetic mean |
| `computeStdev(arr)` | Standard deviation |
| `computeSkewness(arr)` | Standardized third moment |
| `computeExcessKurtosis(arr)` | Standardized fourth moment minus 3 |
| `computeQuantiles(arr)` | 5/25/50/75/95th percentiles |
| `computeHDI(arr, mass?)` | Highest density interval |