Skip to content

Main content

Particle Swarm Optimization Solver Source Code

Browse the implementation files for Particle Swarm Optimization Solver.
tool.ts typescript
import { parseFiniteNumber } from '../../parse/number/tool';
import { parseInteger } from '../../parse/integer/tool';
import { createSeededRandom } from '../../random/seeded-number/tool';

const objectives = {
	sphere: (position: number[]) =>
		position.reduce((sum, value) => sum + value * value, 0),
	rastrigin: (position: number[]) =>
		10 * position.length +
		position.reduce(
			(sum, value) =>
				sum +
				value * value -
				10 * Math.cos(2 * Math.PI * value),
			0
		)
};

export const solveWithParticleSwarm = (
	objectiveInput: unknown,
	dimensionsInput: unknown,
	particleCountInput: unknown,
	iterationsInput: unknown,
	minimumInput: unknown,
	maximumInput: unknown,
	seedInput: unknown
): string => {
	const objective =
		typeof objectiveInput === 'string'
			? objectives[objectiveInput as keyof typeof objectives]
			: undefined;
	const dimensions = parseInteger(dimensionsInput);
	const particleCount = parseInteger(particleCountInput);
	const iterations = parseInteger(iterationsInput);
	const minimum = parseFiniteNumber(minimumInput);
	const maximum = parseFiniteNumber(maximumInput);
	if (
		!objective ||
		dimensions === null ||
		dimensions < 1 ||
		dimensions > 100 ||
		particleCount === null ||
		particleCount < 2 ||
		particleCount > 10_000 ||
		iterations === null ||
		iterations < 1 ||
		iterations > 100_000 ||
		dimensions * particleCount * iterations > 20_000_000 ||
		minimum === null ||
		maximum === null ||
		minimum >= maximum ||
		typeof seedInput !== 'string' ||
		!seedInput.trim()
	)
		return '';
	const random = createSeededRandom(seedInput);
	const span = maximum - minimum;
	if (!Number.isFinite(span)) return '';
	const positions = Array.from({ length: particleCount }, () =>
		Array.from(
			{ length: dimensions },
			() => minimum + random() * span
		)
	);
	const velocities = Array.from({ length: particleCount }, () =>
		Array.from(
			{ length: dimensions },
			() => (random() - 0.5) * span * 0.2
		)
	);
	const personalBest = positions.map((position) => [
		...position
	]);
	const personalValues = personalBest.map(objective);
	let bestIndex = personalValues.indexOf(
		personalValues.reduce(
			(best, value) => Math.min(best, value),
			Infinity
		)
	);
	let globalBest = [...personalBest[bestIndex]];
	let globalValue = personalValues[bestIndex];
	for (
		let iteration = 0;
		iteration < iterations;
		iteration += 1
	)
		for (
			let particle = 0;
			particle < particleCount;
			particle += 1
		) {
			for (
				let dimension = 0;
				dimension < dimensions;
				dimension += 1
			) {
				velocities[particle][dimension] =
					0.729 * velocities[particle][dimension] +
					1.49445 *
						random() *
						(personalBest[particle][dimension] -
							positions[particle][dimension]) +
					1.49445 *
						random() *
						(globalBest[dimension] -
							positions[particle][dimension]);
				positions[particle][dimension] = Math.max(
					minimum,
					Math.min(
						maximum,
						positions[particle][dimension] +
							velocities[particle][dimension]
					)
				);
			}
			const value = objective(positions[particle]);
			if (!Number.isFinite(value)) return '';
			if (value < personalValues[particle]) {
				personalValues[particle] = value;
				personalBest[particle] = [...positions[particle]];
				if (value < globalValue) {
					globalValue = value;
					globalBest = [...positions[particle]];
				}
			}
		}
	return JSON.stringify(
		{
			minimum: Number(globalValue.toPrecision(12)),
			objective: objectiveInput,
			position: globalBest.map((value) =>
				Number(value.toPrecision(12))
			),
			seed: seedInput
		},
		null,
		2
	);
};

export const Tool: TypeTool = {
	name: 'Particle Swarm Optimization Solver',
	slug: 'optimization/particle-swarm',
	intro:
		'Minimize a selected benchmark function with a reproducible bounded particle swarm.',
	tool: solveWithParticleSwarm,
	i: [
		{
			example: 'sphere',
			label: 'Objective',
			options: [
				{ text: 'Sphere', value: 'sphere' },
				{ text: 'Rastrigin', value: 'rastrigin' }
			],
			placeholder: 'Benchmark function',
			type: 'select'
		},
		{
			example: '2',
			label: 'Dimensions',
			placeholder: 'Vector dimensions',
			type: 'number'
		},
		{
			example: '30',
			label: 'Particles',
			placeholder: 'Swarm size',
			type: 'number'
		},
		{
			example: '100',
			label: 'Iterations',
			placeholder: 'Update iterations',
			type: 'number'
		},
		{
			example: '-5',
			label: 'Minimum Bound',
			placeholder: 'Lower bound',
			type: 'number'
		},
		{
			example: '5',
			label: 'Maximum Bound',
			placeholder: 'Upper bound',
			type: 'number'
		},
		{
			example: 'tool.io',
			label: 'Seed',
			placeholder: 'Reproducible seed',
			type: 'text'
		}
	],
	o: [
		{
			example: '{ "minimum": 0, "position": [0,0] }',
			label: 'Best Solution',
			placeholder: 'Solution will appear here...',
			render: 'textarea',
			type: 'text'
		}
	],
	rerunnable: true,
	cite: [
		{
			title: 'Particle swarm optimization - Wikipedia',
			url: 'https://en.wikipedia.org/wiki/Particle_swarm_optimization'
		}
	]
};
export default Tool;

Description

Browse the implementation files for Particle Swarm Optimization Solver.

References

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

Similar or alternative tools