-
Notifications
You must be signed in to change notification settings - Fork 0
/
parallel.ts
52 lines (45 loc) · 1.51 KB
/
parallel.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
/* eslint-disable @typescript-eslint/ban-ts-ignore */
/**
* This example shows that many GeneticAlgorithms can be run in parallel.
*/
import * as cluster from 'cluster';
import { cpus } from 'os';
// this is the worker code
import {
Duration, FitnessFunct,
GeneticAlgorithm as GA,
LogLvl,
NMutations,
PopSize,
} from '..';
const numCPUs = cpus().length;
// main thread dispatches
if (cluster.isMaster) {
for (let i = 0; i < numCPUs; i++) {
console.log(`worker #${i} started`);
cluster.fork();
}
// process.exit(0);
}
// @ts-ignore
const fitness: FitnessFunct = (xs): number => xs.reduce((x, y) => x + y, 0);
const dtype = 'u32';
const nGenes = 500;
// randomness will ensure different config for every worker
const opts = {
logLvl: LogLvl.NORMAL,
// you don't need to use NMutations or PopSize, you can just specify a number
nMutations: [NMutations.TINY + Math.floor(Math.random() * NMutations.MEDIUM), NMutations.TINY] as [number, number],
nElite: [0.01, 0.01 + Math.random() * 0.4] as [number, number],
popSize: PopSize.TINY + Math.floor(Math.random() * PopSize.HUGE),
timeOutMS: Duration.seconds(20),
};
const ga = new GA(fitness, nGenes, dtype, opts);
/*
* ga.search() will create a generator that iterates over the best population
* if you want the best candidate, just request the very first:
*/
const fittest = ga.search().next().value;
const bestPossible = 2 ** 32 * nGenes;
const bestActual = fitness(fittest);
console.log('score', bestActual / bestPossible, '/ 1.0');