Skip to content

Commit

Permalink
Rewritten callbacks to async/await
Browse files Browse the repository at this point in the history
  • Loading branch information
Jozo132 committed Feb 23, 2023
1 parent d43ea67 commit 332887f
Show file tree
Hide file tree
Showing 8 changed files with 390 additions and 405 deletions.
5 changes: 4 additions & 1 deletion .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -103,4 +103,7 @@ dist
# TernJS port file
.tern-port

package-lock.json
package-lock.json


*test*
97 changes: 49 additions & 48 deletions benchmark.js

Large diffs are not rendered by default.

62 changes: 29 additions & 33 deletions example_1.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,36 +6,35 @@ const trainer = new GA()

console.log(`Example 1: Simple function optimization`)

const MY_FUNCTION = (x, y, z) => Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2) + Math.pow(z, 2))
const MY_FUNCTION = (x, y, z) => Math.sqrt(x ** 2 + y ** 2 + z ** 2)
const desired_output = Math.PI // Desired function output

// (1) Direct return fitness function
// const myFitnessFunction = (sample) => {
// const { x, y, z } = sample
// let desired_output = Math.PI // Desired function output
// let actual_output = MY_FUNCTION(x, y, z) // My function
// let loss = Math.abs(desired_output - actual_output)
// const desired_output = Math.PI // Desired function output
// const actual_output = MY_FUNCTION(x, y, z) // My function
// const loss = Math.abs(desired_output - actual_output)
// return loss
// }

// (2) Callback return fitness function
// const myFitnessFunction = (sample, callback) => {
// const { x, y, z } = sample
// let desired_output = Math.PI // Desired function output
// let actual_output = MY_FUNCTION(x, y, z) // My function
// let loss = Math.abs(desired_output - actual_output)
// callback(loss)
// }
// (2) Promise return fitness function
// const myFitnessFunction = (sample) => new Promise((resolve, reject) => {
// try {
// const { x, y, z } = sample
// const actual_output = MY_FUNCTION(x, y, z) // My function
// const loss = Math.abs(desired_output - actual_output)
// resolve(loss)
// } catch (e) { reject(e) }
// })

// (3) Promise return fitness function
const myFitnessFunction = (sample) => new Promise((resolve, reject) => {
try {
const { x, y, z } = sample
let desired_output = Math.PI // Desired function output
let actual_output = MY_FUNCTION(x, y, z) // My function
let loss = Math.abs(desired_output - actual_output)
resolve(loss)
} catch (e) { reject(e) }
})
// (3) Promise return fitness function with async/await
const myFitnessFunction = async (sample) => {
const { x, y, z } = sample
const actual_output = MY_FUNCTION(x, y, z) // My function
const loss = Math.abs(desired_output - actual_output)
return loss
}

const parameters = [
{ variable: 'x', type: 'number', range: { min: -20, max: 20 } },
Expand All @@ -44,9 +43,6 @@ const parameters = [
// { variable: 'p', type: 'option', options: [1.0, 1.2, 1.4, 1.6, 1.8, 2.0] }
]




const logProgress = progress => {
console.log(progress.message)
}
Expand All @@ -57,11 +53,6 @@ const logResult = result => {
console.log(`Test ${MY_FUNCTION.toString()} ---> ${MY_FUNCTION(x, y, z)}`)
}

const catchError = e => {
if (e === 'timeout') console.log('Training timeout!')
else throw e
}

const config = {
debug: false,
maxPopulation: 1000,
Expand All @@ -79,6 +70,11 @@ const config = {
fitnessTimeout: 10000
}

trainer.configure(config).evolve(100, logProgress)
.then(logResult)
.catch(catchError)
const main = async () => {
trainer.configure(config)
const result = await trainer.evolve(100, logProgress)
logResult(result)
}


main().catch(console.error)
4 changes: 1 addition & 3 deletions example_2_training_another_trainer.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,11 +20,9 @@ const mvfBohachevsky2 = {
params: { variable: ['x0', 'x1'], type: 'number', range: { min: -50, max: 50 } },
default: {},
targetFitness: 0,
fn: (sample, callback) => {
callback = callback || (() => { })
fn: (sample) => {
const { x0, x1 } = sample
const output = sq(x0) + 2 * sq(x1) - 0.3 * cos(3 * pi * x0) * cos(4 * pi * x1) + 0.3
callback(output)
return output
}
}
Expand Down
3 changes: 1 addition & 2 deletions example_3.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,10 +17,9 @@ const test = (x, y) => {
return output
}

const fitnessFunction = (sample, /* callback */) => { // optional async callback
const fitnessFunction = (sample) => {
const { x, y } = sample
const output = test(x, y)
//callback(output)
return output - desiredOutput
}

Expand Down
3 changes: 1 addition & 2 deletions example_4.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,14 @@ const desiredOutput = 'To be or not to be, that is the question.'
const parameters = { variable: 'myMessage', size: desiredOutput.length, type: 'string', options: 'abcdefghijklmonpqrstuvxyzABCDEFGHIJKLMNOPQRSTUVWXYZ ,.!?-_' }


const fitnessFunction = (sample, /* callback */) => { // optional async callback
const fitnessFunction = (sample) => {
const { myMessage } = sample
let correctCharacters = 0
desiredOutput.split('').forEach((c, i) => {
if (c === myMessage.split('')[i])
correctCharacters++;
})
const score = correctCharacters / desiredOutput.length
//callback(score)
return score
}

Expand Down
25 changes: 22 additions & 3 deletions example_5.js
Original file line number Diff line number Diff line change
Expand Up @@ -93,8 +93,8 @@ const fitnessFunction = (sample, /* callback */) => { // optional async callba
const conf = {
//debug: true,
maxPopulation: 10000,
survivorsPERCENT: 0.10,
crossoverChance: 0.05,
survivorsPERCENT: 0.005,
crossoverChance: 0.15,
mutationChance: 0.05,
mutationPower: 1,
bestSurvive: true,
Expand Down Expand Up @@ -135,6 +135,25 @@ const catchError = e => {
setTimeout(() => {
console.log(`Starting training...`)
trainer.configure(conf).evolve(100, logProgress)
.then(logResult)
.then(result => {
logResult(result)
/*
Plot data:
1. Points:
0,0
10,10
5,5
2. Path:
1 2 3
*/
console.log(`Plot data:`)
console.log(`1. Points:`)
dataSet.cities.forEach(city => {
console.log(`\t${city.x},${city.y}`)
})
console.log(`2. Path:`)
const { path } = result.parameters
console.log(`\t${path.map(x => x + 1).join(' ')}`)
})
.catch(catchError)
}, 1000)
Loading

0 comments on commit 332887f

Please sign in to comment.