-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnodeGenetic.js
172 lines (155 loc) · 4.6 KB
/
nodeGenetic.js
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
const Task = require('genetic').Task
const FITNESS_MAX = 160000 * 256;
console.log( "FitMax ", FITNESS_MAX )
/* Parameters */
var popSize = 20;
var mutateRate = 0.1;
var crossRate = 0.7;
var solutionSize = 150;
var generations = 100000;
var maxElemSize = 20;
/* Parameters END */
var winner;
function getUserHome() {
return process.env[(process.platform == 'win32') ? 'USERPROFILE' : 'HOME'];
}
function getSetting( id ) {
return document.getElementById( id ).value;
}
function crossover( mother, father, cb ) {
let n = random( mother.length - 1 )
cb( _.first(mother, n).concat(_.rest(father, n)) )
}
function mutate( solution, cb ) {
let rnd = random(solutionSize - 1)
let sox = solution[rnd].x
let soy = solution[rnd].y
let col = imageCtx.getImageData(sox, soy,1,1).data
if( col.length > 0 && col.reduce(function(p, c) { return p + c; }) === 0 ) {
col = [255, 255, 255, 255];
}
solution[ rnd ] = {
'x': sox,
'y': soy,
's': random(maxElemSize),
'c': "rgb("+
col[0]+","+
col[1]+","+
col[2]+")"
}
cb( solution )
}
function getRandomSolution( cb ) {
let solution = [];
for( let i = 0; i < solutionSize; i++ ) {
solution.push({
'x': random(CANVAS_W),
'y': random(CANVAS_H),
's': random(maxElemSize),
'c': "rgb("+
Math.floor(Math.random()*256)+","+
Math.floor(Math.random()*256)+","+
Math.floor(Math.random()*256)+")"
})
}
cb( solution )
}
function stopCriteria() {
return (this.generation == generations)
}
function fitness( solution, cb ) {
hiddenCanvasCtx.clearRect(0, 0, CANVAS_W, CANVAS_H)
for( let i = 0; i < solution.length; i++ ) {
hiddenCanvasCtx.beginPath();
hiddenCanvasCtx.arc( solution[i].x, solution[i].y, solution[i].s, 0, 2*Math.PI)
hiddenCanvasCtx.fillStyle = solution[i].c;
hiddenCanvasCtx.fill();
}
let canvasData = _.flatten( hiddenCanvasCtx.getImageData(0, 0, CANVAS_W, CANVAS_H).data )
let sum = 0;
for( let i = 0; i < canvasData.length; i++ ) {
sum += ( Math.abs(canvasData[i] - imageData[i]) )
}
cb( FITNESS_MAX - sum )
}
document.getElementById('imageBtn').onclick = function() {
var imgPath = dialog.showOpenDialog({
'properties': ['openFile'],
'filters': [
{name: 'Images', extensions: ['jpg', 'png']}
]
});
console.log( imgPath[0] );
fs.readFile( imgPath[0], (err, data) => {
if( err ) {
console.error( err );
}
fs.writeFileSync(getUserHome()+'/tmp', data);
var img = document.getElementById( 'img' );
img.src = getUserHome()+'/tmp';
//imageCtx.drawImage(img, 0, 0, CANVAS_W, CANVAS_H);
})
}
document.getElementById('startBtn').onclick = function() {
initImage();
try {
fs.accessSync(getUserHome()+'/tmp')
fs.unlinkSync(getUserHome()+'/tmp')
} catch(e) {}
popSize = getSetting('popSize')
mutateRate = getSetting('mutateRate');
crossRate = getSetting('crossRate');
solutionSize = getSetting('solutionSize');
generations = getSetting('generations');
maxElemSize = getSetting('maxElemSize');
let t = new Task( {
'getRandomSolution': getRandomSolution,
'popSize': popSize,
'stopCriteria': stopCriteria,
'fitness': fitness,
'minimize': false,
'mutateProbability': mutateRate,
'mutate': mutate,
'crossoverProbability': crossRate,
'crossover': crossover
} )
t.on('statistics', function(s) {
document.getElementById( 'minScore' ).innerHTML = s.minScore
document.getElementById( 'maxScore' ).innerHTML = s.maxScore
document.getElementById( 'avgScore' ).innerHTML = Math.floor( s.avg )
canvasCtx.clearRect(0, 0, CANVAS_W, CANVAS_H)
for( let i = 0; i < s.max.length; i++ ) {
canvasCtx.beginPath();
canvasCtx.arc( s.max[i].x, s.max[i].y, s.max[i].s, 0, 2*Math.PI)
canvasCtx.fillStyle = s.max[i].c;
canvasCtx.fill();
}
})
t.on('iteration start', function(g) {
document.getElementById( 'actGener' ).innerHTML = g
})
t.on('error', function(err) {
console.error( err )
})
t.run(function(stats) {
winner = stats.max;
console.log( "Done: ", stats )
})
}
document.getElementById('saveRBtn').onclick = function() {
var ctx = new C2S(200, 200);
for( let i = 0; i < winner.length; i++ ) {
ctx.beginPath();
ctx.arc( winner[i].x, winner[i].y, winner[i].s, 0, 2*Math.PI)
ctx.fillStyle = winner[i].c;
ctx.fill();
}
var myRectangle = ctx.getSerializedSvg(true);
fs.writeFileSync(getUserHome()+'/evo-art.svg', myRectangle);
dialog.showMessageBox({
'type': 'info',
'buttons': ['OK'],
'title': 'Output saved!',
'message': `Output file saved to ${getUserHome() + '/evo-art.svg'}`
})
}