Created
August 22, 2017 08:15
-
-
Save doomhz/1c3036089ba73eff0d8efa534e5335dc to your computer and use it in GitHub Desktop.
crowding js
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const {min, max} = require('underscore') | |
const first = (arr) => arr[0] | |
const last = (arr) => arr[arr.length - 1] | |
const almostZero = (a) => (a > -0.000001 && a < 0.000001) | |
const almostEqual = (a, b) => almostZero(Math.abs(a) - Math.abs(b)) | |
const population = [ | |
{ objectives: [0.1, 0.2, 0.3] }, | |
{ objectives: [0.2, 0.4, 0.6] }, | |
{ objectives: [0.1, 0.05, 0.3] } | |
] | |
function calculateCrowdingDistance(pop) { | |
pop.forEach(p => p['dist'] = 0.0) | |
const objectivesNumber = pop[0].objectives.length | |
for(let i = 1; i < objectivesNumber - 1; i++) { | |
const comparable = (p, index) => { | |
const next = pop[index + 1] | |
if (!next) return 0; | |
if (p.objectives[i] < next.objectives[i]) return 1 | |
if (p.objectives[i] > next.objectives[i]) return -1 | |
if (almostEqual(p.objectives[i], next.objectives[i])) return 0 | |
} | |
let minVal = min(pop, comparable) | |
let maxVal = max(pop, comparable) | |
let rge = maxVal.objectives[i] - minVal.objectives[i] | |
first(pop).dist = Number.POSITIVE_INFINITY | |
last(pop).dist = Number.NEGATIVE_INFINITY | |
if (almostZero(rge)) return; | |
for(let j = 1; j < pop.length - 1; j++) { | |
pop[j].dist += (pop[j + 1].objectives[i] - pop[j - 1].objectives[i])/rge | |
} | |
} | |
} | |
calculateCrowdingDistance(population) | |
console.log('=========== RESULT ===========') | |
console.log(population) | |
console.log('===============================') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment