Poisson–Gamma Mixture Sampler Source Code
Browse the implementation files for Poisson–Gamma Mixture Sampler.tool.ts typescript
import { parseFiniteNumber } from '../../parse/number/tool';
import { parseInteger } from '../../parse/integer/tool';
import { createSeededRandom } from '../../random/seeded-number/tool';
import { randomGamma } from '../gamma-sampler/tool';
import { randomPoisson } from '../poisson-sampler/tool';
export const samplePoissonGammaMixture = (
shapeInput: unknown,
scaleInput: unknown,
countInput: unknown,
seedInput: unknown
): string => {
const shape = parseFiniteNumber(shapeInput);
const scale = parseFiniteNumber(scaleInput);
const count = parseInteger(countInput);
if (
shape === null ||
shape <= 0 ||
scale === null ||
scale <= 0 ||
shape * scale > 1_000_000 ||
count === null ||
count < 1 ||
count > 100_000 ||
typeof seedInput !== 'string' ||
!seedInput.trim()
)
return '';
const random = createSeededRandom(seedInput);
const samples: number[] = [];
for (let index = 0; index < count; index += 1) {
const gamma = randomGamma(shape, random);
if (gamma === null) return '';
const rate = gamma * scale;
if (!Number.isFinite(rate) || rate > 1_000_000) return '';
const poisson = randomPoisson(rate, random);
if (poisson === null) return '';
samples.push(poisson);
}
return JSON.stringify(
{
count,
distribution: 'poisson-gamma-mixture',
samples,
scale,
seed: seedInput,
shape
},
null,
2
);
};
export const Tool: TypeTool = {
name: 'Poisson–Gamma Mixture Sampler',
slug: 'probability/poisson-gamma-mixture-sampler',
intro:
'Generate reproducible overdispersed counts by mixing a Poisson rate with a gamma distribution.',
tool: samplePoissonGammaMixture,
i: [
{
example: '3',
label: 'Gamma Shape',
placeholder: 'Positive shape',
type: 'number'
},
{
example: '2',
label: 'Gamma Scale',
placeholder: 'Positive scale',
type: 'number'
},
{
example: '20',
label: 'Sample Count',
placeholder: 'Number of samples',
type: 'number'
},
{
example: 'tool.io',
label: 'Seed',
placeholder: 'Reproducible seed',
type: 'text'
}
],
o: [
{
example: '{ "samples": [3, 9] }',
label: 'Mixture Samples',
placeholder: 'Samples will appear here...',
render: 'textarea',
type: 'text'
}
],
rerunnable: true,
cite: [
{
title: 'Negative binomial distribution - Wikipedia',
url: 'https://en.wikipedia.org/wiki/Negative_binomial_distribution#Gamma%E2%80%93Poisson_mixture'
}
]
};
export default Tool;
Description
Browse the implementation files for Poisson–Gamma Mixture Sampler.