-
Notifications
You must be signed in to change notification settings - Fork 8
/
nes.js
209 lines (181 loc) · 5.67 KB
/
nes.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
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
if (window.require) {
const math = require('mathjs');
}
const math2 = math.create({
matrix: 'Array'
});
const W = 500;
const H = 500;
const sampleSize = 50;
const samplesArea = 30;
const learningRate = 0.1;
const canvas = document.getElementById('data');
canvas.width = W;
canvas.height = H;
const context = canvas.getContext('2d');
context.width = W;
context.height = H;
const canvas2 = document.getElementById('main');
canvas2.width = W;
canvas2.height = H;
const context2 = canvas2.getContext('2d');
context2.width = W;
context2.height = H;
const initRandomMatrix = (h, w) =>
math.map(math.zeros(h, w), () => math.random());
const setPixelInImageData = (imageData, x, y, r, g, b, a) => {
const i = y * imageData.width * 4 + x * 4;
imageData.data[i] = r;
imageData.data[i + 1] = g;
imageData.data[i + 2] = b;
imageData.data[i + 3] = a;
}
const pickNRandomPoints = (n, min, max) =>
math2.range(0, n).map(
() => [
math.randomInt(W + 1),
math.randomInt(H + 1),
math.random() * (max - min) + min])
const illustratePoints = (points) =>
points.forEach(([x, y, value], i) => {
context.beginPath();
if (value > 0) {
context.fillStyle = 'rgba(0, 255, 0, 0.1)';
} else {
context.fillStyle = 'rgba(0, 0, 255, 0.1)';
}
context.arc(x, y, Math.abs(value) * 10, 0, Math.PI * 2, false);
context.fill();
});
const renderMatrix = (matrix) => {
const imageData = context2.createImageData(W, H);
const totalMax = Math.max(math.max(matrix), Math.abs(math.min(matrix)));
math.forEach(matrix, (el, [y, x]) => {
const r = 0;
let g = b = 0;
if (el > 0) {
g = 255;
} else {
b = 255;
}
setPixelInImageData(imageData, x, y, r, g, b, Math.abs(el) / totalMax * 255);
});
context2.putImageData(imageData, 0, 0);
}
const linspace = (start, end, size) => {
const interval = (end - start) / (size - 1);
return math2.range(0, size).map((el) => start + el * interval);
}
const _linSpace = linspace(-1, 1, W);
const _X = math.multiply(math.ones(W, 1), [_linSpace]);
const _Y = math.multiply(math.reshape(_linSpace, [W, 1]), math.ones(1, W))
const gpu = new GPU();
if (canvas.getContext('webgl') || canvas.getContext('experimental-webgl')) {
mode = 'gpu';
console.log('Using GPU');
} else {
mode = 'cpu';
console.log('Using CPU');
}
const myFunc = gpu.createKernel(function (A, k, mux, muy) {
const m = Math.pow(A[this.thread.x] - mux, 2) + Math.pow(A[this.thread.y] - muy, 2);
return Math.exp(m * k);
}, { mode }).setOutput([W, H]);
const makeG = (mux, muy, sigma) => {
const k = -1 / 2 * Math.pow(sigma, 2);
const data = myFunc(_linSpace, k, mux, muy);
return math.matrix(Array.prototype.map.call(data, (row) => Array.prototype.slice.call(row)));
}
const drawPoints = (points, fillStyle = "rgba(0,0,0,0.5)", size = 3) => points.forEach(([x, y]) => {
context.beginPath();
context.fillStyle = fillStyle;
context.arc(x, y, size, 0, 2 * Math.PI, false);
context.fill();
});
const drawArrow = (pFrom, pTo) => {
context.beginPath();
context.strokeStyle = 'rgb(255, 100, 0)';
context.lineWidth = 3;
context.moveTo(pFrom[0], pFrom[1]);
context.lineTo(pTo[0], pTo[1]);
context.stroke();
}
const clearContext = () => {
context.clearRect(0, 0, W, H);
}
const randomG = () => {
const x = math.random() * 2 - 1;
const y = math.random() * 2 - 1;
const sigma = math.randomInt(3) + 1;
return makeG(x, y, sigma);
}
const clipValue = (val, min, max) => {
if (val > max) {
return max;
} else if (val < min) {
return min;
} else {
return val;
}
}
const main = () => {
let G = null;
for (let i = 0; i < 3; i++) {
if (G === null) {
G = randomG();
} else {
G = math.add(G, randomG());
}
}
for (let i = 0; i < 3; i++) {
G = math.subtract(G, randomG());
}
const alpha = learningRate;
const sigma = samplesArea;
let w = [math.randomInt(W - sigma * 4) + sigma * 2, math.randomInt(H - sigma * 4) + sigma * 2];
const points = [];
const samplePoints = [];
let minimumFound = false;
while (!minimumFound) {
const noise = math.add(math.multiply(initRandomMatrix(sampleSize, 2), 4), -2);
const wp = math.add(math.dotMultiply(sigma, noise), math.multiply(math.ones(sampleSize, 1), [w]));
samplePoints.push(wp.toArray());
let R = wp.toArray().map(([x, y]) =>
G.get(
[
Math.round(clipValue(y, 0, H - 1)),
Math.round(clipValue(x, 0, W - 1))
])
);
R = math.subtract(R, math.mean(R));
R = math.dotDivide(R, math.std(R));
g = math.multiply([R], noise)
const u = math.dotMultiply(g, alpha).toArray()[0];
points.push(w);
w = math.add(w, u);
if (points.length > 5 && math.distance(points[points.length - 1], points[points.length - 6]) < 2) {
minimumFound = true;
}
}
let frameIndex = 0;
renderMatrix(G);
const frame = () => {
clearContext();
drawPoints(samplePoints[frameIndex]);
drawPoints([points[frameIndex]], fillStyle = "red", size = 3)
for (let i = 1; i <= frameIndex; i++) {
drawArrow(points[i - 1], points[i]);
}
frameIndex += 1;
if (frameIndex === points.length) {
frameIndex = 0;
}
setTimeout(frame, 50);
// requestAnimationFrame(frame);
};
frame();
}
// const G = randomG();
// console.log(G);
// renderMatrix(G);
main();