Skip to content

Main content

Bayesian Network Simulator Source Code

Browse the implementation files for Bayesian Network Simulator.
tool.ts typescript
// Tool: Bayesian Network Simulator

interface NodeDefinition {
	name: string;
	parents: string[];
	pTrue: number | Record<string, number>;
}

const MAX_NODES = 30;
const MAX_SAMPLES = 10_000;

const parsePositiveInteger = (
	input: unknown
): number | null => {
	const value =
		typeof input === 'string' || typeof input === 'number'
			? Number(input)
			: NaN;

	return Number.isSafeInteger(value) &&
		value >= 1 &&
		value <= MAX_SAMPLES
		? value
		: null;
};

const validProbability = (value: unknown): value is number =>
	typeof value === 'number' &&
	Number.isFinite(value) &&
	value >= 0 &&
	value <= 1;

const parseNetwork = (
	input: unknown
): NodeDefinition[] | null => {
	if (typeof input !== 'string' || input.trim() === '')
		return null;

	try {
		const nodes: unknown = JSON.parse(input);

		if (
			!Array.isArray(nodes) ||
			nodes.length === 0 ||
			nodes.length > MAX_NODES
		) {
			return null;
		}

		const names = new Set<string>();

		for (const node of nodes) {
			const candidate = node as Record<string, unknown>;
			if (
				typeof node !== 'object' ||
				node === null ||
				typeof candidate.name !== 'string' ||
				candidate.name.trim() === '' ||
				names.has(candidate.name) ||
				!Array.isArray(candidate.parents) ||
				!candidate.parents.every(
					(parent: unknown) =>
						typeof parent === 'string' && names.has(parent)
				)
			) {
				return null;
			}

			if (candidate.parents.length === 0) {
				if (!validProbability(candidate.pTrue)) return null;
			} else {
				if (
					typeof candidate.pTrue !== 'object' ||
					candidate.pTrue === null
				) {
					return null;
				}

				for (
					let state = 0;
					state < 2 ** candidate.parents.length;
					state += 1
				) {
					const key = state
						.toString(2)
						.padStart(candidate.parents.length, '0');
					if (
						!validProbability(
							(candidate.pTrue as Record<string, unknown>)[key]
						)
					)
						return null;
				}
			}

			names.add(candidate.name);
		}

		return nodes as NodeDefinition[];
	} catch {
		return null;
	}
};

const createRandom = (seed: string): (() => number) => {
	let state = 2166136261;
	for (const character of seed) {
		state ^= character.charCodeAt(0);
		state = Math.imul(state, 16777619);
	}
	return () => {
		state += 0x6d2b79f5;
		let value = state;
		value = Math.imul(value ^ (value >>> 15), value | 1);
		value ^=
			value + Math.imul(value ^ (value >>> 7), value | 61);
		return ((value ^ (value >>> 14)) >>> 0) / 4294967296;
	};
};

const round = (value: number): number =>
	Number(value.toPrecision(12));

export const simulateBayesianNetwork = (
	networkInput: unknown,
	sampleCountInput: unknown,
	seedInput: unknown
): string => {
	const network = parseNetwork(networkInput);
	const sampleCount = parsePositiveInteger(sampleCountInput);

	if (
		network === null ||
		sampleCount === null ||
		typeof seedInput !== 'string' ||
		seedInput.trim() === ''
	) {
		return '';
	}

	const random = createRandom(seedInput);
	const trueCounts = Object.fromEntries(
		network.map(({ name }) => [name, 0])
	) as Record<string, number>;
	const jointCounts = new Map<string, number>();
	const preview: Record<string, boolean>[] = [];

	for (
		let sampleIndex = 0;
		sampleIndex < sampleCount;
		sampleIndex += 1
	) {
		const sample: Record<string, boolean> = {};

		for (const node of network) {
			const probability =
				typeof node.pTrue === 'number'
					? node.pTrue
					: node.pTrue[
							node.parents
								.map((parent) => (sample[parent] ? '1' : '0'))
								.join('')
						];
			sample[node.name] = random() < probability;
			if (sample[node.name]) trueCounts[node.name] += 1;
		}

		const state = network
			.map(({ name }) => (sample[name] ? '1' : '0'))
			.join('');
		jointCounts.set(state, (jointCounts.get(state) ?? 0) + 1);
		if (preview.length < 20) preview.push(sample);
	}

	return JSON.stringify(
		{
			jointCounts: Object.fromEntries(
				[...jointCounts].sort(([first], [second]) =>
					first.localeCompare(second)
				)
			),
			marginals: Object.fromEntries(
				network.map(({ name }) => [
					name,
					round(trueCounts[name] / sampleCount)
				])
			),
			preview,
			sampleCount,
			seed: seedInput,
			stateOrder: network.map(({ name }) => name)
		},
		null,
		2
	);
};

const DEFAULT_NETWORK =
	'[{"name":"Rain","parents":[],"pTrue":0.2},{"name":"Sprinkler","parents":["Rain"],"pTrue":{"0":0.4,"1":0.01}},{"name":"WetGrass","parents":["Rain","Sprinkler"],"pTrue":{"00":0,"01":0.9,"10":0.8,"11":0.99}}]';

export const Tool: TypeTool = {
	name: 'Bayesian Network Simulator',
	slug: 'probability/bayesian-network-simulator',
	intro:
		'Draw reproducible ancestral samples from a Boolean Bayesian network and estimate its marginals.',
	tool: simulateBayesianNetwork,
	i: [
		{
			example: DEFAULT_NETWORK,
			help: 'Parents must appear before their child. Conditional keys use parent states in listed order.',
			label: 'Network',
			placeholder:
				'JSON array of Boolean Bayesian-network nodes',
			render: 'textarea',
			type: 'text',
			value: DEFAULT_NETWORK
		},
		{
			example: '1000',
			label: 'Samples',
			placeholder: 'Number of samples from 1 to 10000',
			type: 'number',
			value: 1000
		},
		{
			example: 'tool.io',
			label: 'Seed',
			placeholder: 'Seed for reproducible samples',
			type: 'text',
			value: 'tool.io'
		}
	],
	o: [
		{
			example: '{ "marginals": {}, "preview": [] }',
			label: 'Simulation',
			placeholder: 'Simulation result will appear here...',
			render: 'textarea',
			type: 'text'
		}
	],
	cite: [
		{
			title:
				'Bayesian Networks: A Model of Self-Activated Memory for Evidential Reasoning',
			url: 'https://escholarship.org/uc/item/0vr7830n'
		},
		{
			title: 'Bayesian network — Wikipedia',
			url: 'https://en.wikipedia.org/wiki/Bayesian_network'
		}
	]
};

export default Tool;

Description

Browse the implementation files for Bayesian Network Simulator.

References

  1. Tool.io on GitHub
  2. Tool.io TypeScript tools library

Similar or alternative tools