Observatório
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
demo-kit/ é o que simula o dispositivo para a demo na página inicial. O próprio dispositivo não precisa dele.
// The pretend observatory for the demo of the observatory example (../../demo-kit/README.md): the same
// answers the program on the Raspberry Pi gives in simulator mode (../pi/observatory.py). The sky is drawn
// by the same formulas, every frame gets fresh noise, and the stack is a real average of those frames. It
// differs in speed only: the pretend mount turns faster, the telescope moves on to the next target after
// 45 frames, and a pretend program at home pulls every frame.
(function () {
var ctx = czDemo.context;
var WIDTH = 160;
var HEIGHT = 160;
var PIXELS = WIDTH * HEIGHT;
var EXPOSURES = [1, 2, 4, 8]; // seconds
var GAIN_MAX = 300; // in units of 0.1 dB
var SLEW_RATE = 20; // degrees a second
var TOUR_FRAMES = 45;
// Right ascension in hours, declination in degrees (J2000). The object drawn at each is synthetic.
var TARGETS = [
{ id: 'm51', name: 'M51', title: 'Whirlpool Galaxy', kind: 'spiral', ra: 13.498, dec: 47.195 },
{ id: 'm42', name: 'M42', title: 'Orion Nebula', kind: 'nebula', ra: 5.588, dec: -5.391 },
{ id: 'm13', name: 'M13', title: 'Hercules Cluster', kind: 'cluster', ra: 16.695, dec: 36.46 },
{ id: 'm57', name: 'M57', title: 'Ring Nebula', kind: 'ring', ra: 18.893, dec: 33.029 },
];
var SEEDS = { m51: 51, m42: 42, m13: 13, m57: 57 };
var SKY = 0.06; // the sky background, in the unit of the scene (1 is the core of the galaxy)
var ELECTRONS_PER_SECOND = 20; // what a scene value of 1 gives the sensor
var COUNTS_PER_ELECTRON = 16; // at gain 0
var OFFSET = 400; // the count of a pixel that saw nothing
var STAR_SIGMA = 1.15; // the width of a star, in pixels
function clamp(value, min, max) {
return Math.max(min, Math.min(max, value));
}
function smooth(low, high, value) {
var t = clamp((value - low) / (high - low), 0, 1);
return t * t * (3 - 2 * t);
}
// --- The sky without noise (the same formulas as render_scene in observatory.py). ---
function lcg(seed) {
var state = Math.imul(seed, 2654435761) >>> 0;
return function () {
state = (Math.imul(state, 1664525) + 1013904223) >>> 0;
return state / 4294967296;
};
}
function starColour(c) {
return [1 - 0.25 * c, 0.82 + 0.03 * c, 0.7 + 0.3 * c]; // from a warm star (0) to a blue one (1)
}
function addStar(image, x, y, brightness, colour) {
var cx = ((x + 1) / 2) * WIDTH - 0.5;
var cy = ((y + 1) / 2) * HEIGHT - 0.5;
var x0 = Math.max(0, Math.trunc(cx) - 5), x1 = Math.min(WIDTH, Math.trunc(cx) + 7);
var y0 = Math.max(0, Math.trunc(cy) - 5), y1 = Math.min(HEIGHT, Math.trunc(cy) + 7);
for (var py = y0; py < y1; py++) {
for (var px = x0; px < x1; px++) {
var spot = brightness * Math.exp(-((px - cx) * (px - cx) + (py - cy) * (py - cy)) / (2 * STAR_SIGMA * STAR_SIGMA));
var at = (py * WIDTH + px) * 3;
image[at] += spot * colour[0];
image[at + 1] += spot * colour[1];
image[at + 2] += spot * colour[2];
}
}
}
function renderScene(kind, seed) {
var image = new Float32Array(PIXELS * 3);
var rng = lcg(seed);
var fieldStars = 36;
var at = 0;
function add(value, colour) {
image[at] += value * colour[0];
image[at + 1] += value * colour[1];
image[at + 2] += value * colour[2];
}
for (var j = 0; j < HEIGHT; j++) {
var y = ((j + 0.5) / HEIGHT) * 2 - 1;
for (var i = 0; i < WIDTH; i++, at += 3) {
var x = ((i + 0.5) / WIDTH) * 2 - 1;
var u, v, r, theta;
if (kind === 'spiral') {
// An inclined disc with a bright core, two arms, knots along them and a companion.
u = (x * Math.cos(0.6) + y * Math.sin(0.6)) / 1.3;
v = (-x * Math.sin(0.6) + y * Math.cos(0.6)) / (1.3 * 0.72);
r = Math.hypot(u, v);
theta = Math.atan2(v, u);
var psi = 2 * theta - 5.2 * Math.log(r + 0.02);
var arm = Math.pow(0.5 + 0.5 * Math.cos(psi), 3) * Math.exp(-r / 0.36) * smooth(0.06, 0.16, r) * (1 - smooth(0.62, 0.85, r));
add(1.1 * Math.exp(-r / 0.055) + 0.3 * Math.exp(-Math.pow(r / 0.16, 2)), [1, 0.86, 0.62]);
add(0.1 * Math.exp(-r / 0.3), [0.9, 0.85, 0.8]);
add(0.42 * arm, [0.5, 0.66, 1]);
add(0.3 * arm * arm * Math.pow(0.5 + 0.5 * Math.sin(9 * theta + 23 * r), 4), [1, 0.35, 0.55]);
add(0.5 * Math.exp(-(Math.pow(x - 0.62, 2) + Math.pow(y + 0.6, 2)) / (2 * 0.07 * 0.07)), [1, 0.85, 0.65]);
} else if (kind === 'nebula') {
// Glowing gas: warped waves under a wide envelope, a bright core, a blue wing and a dark bay.
var a = x + 0.25 * Math.sin(3.1 * y + 1.3);
var b = y + 0.25 * Math.sin(2.7 * x - 0.8);
var n1 = 0.5 + 0.5 * Math.sin(4.2 * a + 1.7 * Math.sin(3.3 * b));
var n2 = 0.5 + 0.5 * Math.sin(5.1 * b - 2.2 * Math.sin(2.9 * a) + 1);
var n3 = 0.5 + 0.5 * Math.sin(9 * a + 7 * b + 2 * Math.sin(6 * b));
var cloud = 0.55 * n1 * n2 + 0.25 * n3 * n1 + 0.2;
var envelope = Math.exp(-(Math.pow(x + 0.05, 2) / 0.5 + Math.pow(y - 0.05, 2) / 0.38));
var bay = 1 - 0.8 * Math.exp(-(Math.pow(x - 0.12, 2) / 0.012 + Math.pow(y - 0.24, 2) / 0.05));
var core = Math.exp(-(Math.pow(x + 0.08, 2) + Math.pow(y - 0.02, 2)) / (2 * 0.13 * 0.13));
add(0.85 * cloud * envelope * bay, [1, 0.32, 0.42]);
add(0.9 * core * (0.6 + 0.4 * n3) * bay, [0.75, 0.95, 1]);
add(0.18 * Math.exp(-(Math.pow(x - 0.35, 2) + Math.pow(y + 0.45, 2)) / 0.08), [0.45, 0.6, 1]);
} else if (kind === 'cluster') {
// A globular cluster: a glow, and some hundred stars added below.
r = Math.hypot(x, y);
add(0.35 / Math.pow(1 + Math.pow(r / 0.12, 2), 1.3), [1, 0.93, 0.8]);
} else if (kind === 'ring') {
// A planetary nebula: a red rim, a green ring inside it, a blue filling and the star in the middle.
u = x * Math.cos(0.5) + y * Math.sin(0.5);
v = (-x * Math.sin(0.5) + y * Math.cos(0.5)) / 0.78;
r = Math.hypot(u, v);
theta = Math.atan2(v, u);
add(0.55 * Math.exp(-Math.pow((r - 0.33) / 0.07, 2)) * (1 + 0.25 * Math.cos(2 * theta)), [1, 0.35, 0.3]);
add(0.5 * Math.exp(-Math.pow((r - 0.27) / 0.06, 2)), [0.55, 1, 0.6]);
add(0.22 * Math.exp(-Math.pow(r / 0.22, 2)), [0.3, 0.7, 1]);
add(0.05 * Math.exp(-Math.pow(r / 0.5, 2)), [1, 0.4, 0.4]);
}
// Any other kind is an empty field: stars only.
}
}
if (kind === 'cluster') {
for (var n = 0; n < 520; n++) {
var radius = Math.min(1.3, 0.09 * Math.tan(rng() * 1.35));
var angle = rng() * 2 * Math.PI;
var brightness = 0.08 + 0.9 * Math.pow(rng(), 5);
addStar(image, radius * Math.cos(angle), radius * Math.sin(angle), brightness, starColour(Math.pow(rng(), 2)));
}
fieldStars = 18;
}
if (kind === 'ring') addStar(image, 0, 0, 0.6, [0.8, 0.9, 1]);
for (var s = 0; s < fieldStars; s++) {
var sx = rng() * 2 - 1;
var sy = rng() * 2 - 1;
addStar(image, sx, sy, 0.2 + 2.2 * Math.pow(rng(), 8), starColour(rng()));
}
for (var k = 0; k < image.length; k++) image[k] += SKY;
return image;
}
// --- The camera: the scene, as many electrons as the exposure collects, with noise, times the gain. ---
function gaussian() {
return Math.sqrt(-2 * Math.log(1 - ctx.rand())) * Math.cos(2 * Math.PI * ctx.rand());
}
function gainFactor(gain) {
return COUNTS_PER_ELECTRON * Math.pow(10, gain / 200);
}
function expose(scene, seconds, gain) {
var frame = new Uint16Array(scene.length);
var readNoise = 7 - gain / 75;
var factor = gainFactor(gain);
for (var k = 0; k < scene.length; k++) {
var electrons = scene[k] * seconds * ELECTRONS_PER_SECOND;
electrons += gaussian() * Math.sqrt(electrons + readNoise * readNoise);
frame[k] = clamp(Math.round(electrons * factor + OFFSET), 0, 65535);
}
return frame;
}
function whiteLevel(seconds, gain) {
return 1.4 * seconds * ELECTRONS_PER_SECOND * gainFactor(gain);
}
// A picture as the device sends it: 16 bytes ('CZFR'; width and height as uint16; channels and bits per
// sample as uint8; the serial of the stack as uint16; a number as uint32; little endian), then the samples.
function encodeImage(samples, serial, number) {
var bits = samples.BYTES_PER_ELEMENT * 8;
var buffer = new ArrayBuffer(16 + samples.byteLength);
var view = new DataView(buffer);
[67, 90, 70, 82].forEach(function (code, index) {
view.setUint8(index, code);
});
view.setUint16(4, WIDTH, true);
view.setUint16(6, HEIGHT, true);
view.setUint8(8, 3);
view.setUint8(9, bits);
view.setUint16(10, serial & 0xffff, true);
view.setUint32(12, number, true);
if (bits === 16) for (var k = 0; k < samples.length; k++) view.setUint16(16 + 2 * k, samples[k], true);
else new Uint8Array(buffer, 16).set(samples);
return buffer;
}
function median(values) {
var sorted = Float32Array.from(values).sort();
var half = sorted.length >> 1;
return sorted.length % 2 ? sorted[half] : (sorted[half - 1] + sorted[half]) / 2;
}
// --- The observatory: pointing, exposures and the live stack. ---
var sim = {
target: TARGETS[0],
ra: TARGETS[0].ra,
dec: TARGETS[0].dec,
goal: null, // { ra, dec } while slewing
running: true,
exposure: 2,
gain: 120,
elapsed: 0, // seconds of the exposure that is running
serial: 0, // counts the stacks
sequence: 0, // counts the frames since the demo started
frames: 0, // frames in the stack
sum: new Float64Array(PIXELS * 3),
noise: 0,
snr: 0,
latest: null,
preview: null,
scene: null,
served: 0,
servedSequence: 0,
servedAt: 0,
pullAt: null, // when the pretend program at home pulls the newest frame
clock: 0, // the simulation's own seconds: it stands still while the demo is paused
lastReal: Date.now(),
};
var sockets = [];
function broadcast(message) {
sockets.forEach(function (socket) {
socket.send(message);
});
}
function seedOf(target) {
return SEEDS[target.id] !== undefined ? SEEDS[target.id] : Math.trunc(target.ra * 1000) * 7919 + Math.trunc((target.dec + 90) * 100);
}
function newStack() {
sim.serial += 1;
sim.frames = 0;
sim.sum.fill(0);
sim.noise = sim.snr = 0;
sim.elapsed = 0;
sim.latest = null;
sim.preview = null;
sim.pullAt = null;
}
function stack() {
return {
serial: sim.serial,
frames: sim.frames,
integrationSeconds: sim.frames * sim.exposure,
noise: Math.round(sim.noise * 100) / 100,
snr: Math.round(sim.snr * 100) / 100,
};
}
function state() {
var slewing = sim.goal !== null;
return {
t: Math.round(Date.now() / 1000),
simulated: true,
mount: { state: slewing ? 'slewing' : 'tracking', ra: Math.round(sim.ra * 10000) / 10000, dec: Math.round(sim.dec * 1000) / 1000, target: sim.target },
camera: { exposureSeconds: sim.exposure, gain: sim.gain, width: WIDTH, height: HEIGHT },
capture: {
running: sim.running,
exposureProgress: slewing || !sim.running ? 0 : Math.round(Math.min(1, sim.elapsed / sim.exposure) * 1000) / 1000,
sequence: sim.sequence,
},
stack: stack(),
downlink: {
framesServed: sim.served,
lastSequence: sim.servedSequence,
lastSecondsAgo: sim.served ? Math.round((sim.clock - sim.servedAt) * 10) / 10 : null,
},
};
}
function changed() {
broadcast({ type: 'state', state: state() });
}
function addFrame(quiet) {
var frame = expose(sim.scene, sim.exposure, sim.gain);
sim.sequence += 1;
sim.frames += 1;
var k;
for (k = 0; k < frame.length; k++) sim.sum[k] += frame[k];
sim.latest = encodeImage(frame, sim.serial, sim.sequence);
// The noise and the signal to noise of the stack, estimated as in observatory.py.
var brightness = new Float32Array(PIXELS);
var channels = [new Float32Array(PIXELS), new Float32Array(PIXELS), new Float32Array(PIXELS)];
for (k = 0; k < PIXELS; k++) {
var red = sim.sum[3 * k] / sim.frames, green = sim.sum[3 * k + 1] / sim.frames, blue = sim.sum[3 * k + 2] / sim.frames;
channels[0][k] = red;
channels[1][k] = green;
channels[2][k] = blue;
brightness[k] = (red + green + blue) / 3;
}
var steps = new Float32Array((WIDTH - 1) * HEIGHT);
var at = 0;
for (var row = 0; row < HEIGHT; row++) {
for (var column = 1; column < WIDTH; column++) steps[at++] = brightness[row * WIDTH + column] - brightness[row * WIDTH + column - 1];
}
var middleStep = median(steps);
for (k = 0; k < steps.length; k++) steps[k] = Math.abs(steps[k] - middleStep);
sim.noise = (1.4826 * median(steps)) / Math.SQRT2;
var total = 0, count = 0;
for (row = HEIGHT / 4; row < HEIGHT - HEIGHT / 4; row++) {
for (column = WIDTH / 4; column < WIDTH - WIDTH / 4; column++, count++) total += brightness[row * WIDTH + column];
}
sim.snr = sim.noise > 0 ? Math.max(0, total / count - median(brightness)) / sim.noise : 0;
// The live stack for the screen: the sky taken off each colour, then a fixed asinh stretch to 8 bits.
var white = whiteLevel(sim.exposure, sim.gain);
var full = Math.asinh(1.015 / 0.05);
var shown = new Uint8Array(PIXELS * 3);
for (var channel = 0; channel < 3; channel++) {
var sky = median(channels[channel]);
for (k = 0; k < PIXELS; k++) {
var level = (channels[channel][k] - sky) / white;
shown[3 * k + channel] = Math.round(clamp(Math.asinh((level + 0.015) / 0.05) / full, 0, 1) * 255);
}
}
sim.preview = encodeImage(shown, sim.serial, sim.frames);
sim.pullAt = sim.clock + 0.4 + ctx.rand() * 0.5;
if (!quiet) broadcast({ type: 'frame', sequence: sim.sequence, stack: stack() });
}
function slew(target) {
if (sim.goal === null && Math.abs(sim.ra - target.ra) < 1e-6 && Math.abs(sim.dec - target.dec) < 1e-6) return; // already there
sim.target = target;
sim.goal = { ra: ((target.ra % 24) + 24) % 24, dec: clamp(target.dec, -90, 90) };
newStack(); // what was stacked belongs to the place the telescope leaves
changed();
}
function tick() {
var now = Date.now();
// Not more than a second and a half at once: when the demo was paused off screen, nothing jumps.
var seconds = clamp((now - sim.lastReal) / 1000, 0, 1.5);
sim.lastReal = now;
sim.clock += seconds;
if (sim.pullAt !== null && sim.clock >= sim.pullAt) {
sim.pullAt = null;
sim.served += 1;
sim.servedSequence = sim.sequence;
sim.servedAt = sim.clock;
}
if (sim.goal !== null) {
var step = SLEW_RATE * seconds; // degrees
var raLeft = ((((sim.goal.ra - sim.ra + 12) % 24) + 24) % 24 - 12) * 15; // degrees, the short way
var decLeft = sim.goal.dec - sim.dec;
sim.ra = (((sim.ra + clamp(raLeft, -step, step) / 15) % 24) + 24) % 24;
sim.dec += clamp(decLeft, -step, step);
if (Math.abs(raLeft) <= step && Math.abs(decLeft) <= step) {
sim.ra = sim.goal.ra;
sim.dec = sim.goal.dec;
sim.goal = null;
sim.scene = renderScene(sim.target.kind, seedOf(sim.target));
newStack();
changed();
}
}
if (sim.goal !== null || !sim.running) return;
sim.elapsed += seconds;
if (sim.elapsed >= sim.exposure) {
sim.elapsed = 0;
addFrame(false);
if (sim.frames >= TOUR_FRAMES) {
var index = TARGETS.findIndex(function (target) { return target.id === sim.target.id; });
slew(TARGETS[(index + 1) % TARGETS.length]);
}
}
}
// The demo opens on a stack of two frames, so that there is a picture from the first moment.
sim.scene = renderScene(sim.target.kind, seedOf(sim.target));
newStack();
addFrame(true);
addFrame(true);
function isNumber(value) {
return typeof value === 'number' && isFinite(value);
}
var BINARY = { 'Content-Type': 'application/octet-stream' };
czDemo.define({
device: { name: 'observatory', title: 'Observatory' },
routes: {
'GET /state': function () {
tick();
return state();
},
'GET /targets': function () {
return TARGETS;
},
'GET /frame/latest': function (request) {
tick();
if (sim.latest === null) return ctx.respond(404, { error: 'No frame yet.' });
if (request.query.has('after') && Number(request.query.get('after')) === sim.sequence) return ctx.respond(204, null);
sim.served += 1;
sim.servedSequence = sim.sequence;
sim.servedAt = sim.clock;
return ctx.respond(200, sim.latest, BINARY);
},
'GET /stack': function () {
tick();
if (sim.preview === null) return ctx.respond(404, { error: 'No frame yet.' });
return ctx.respond(200, sim.preview, BINARY);
},
'POST /slew': function (request) {
tick();
var wanted = request.json();
if (!wanted || typeof wanted !== 'object') return ctx.respond(400, { error: 'The body is a JSON object.' });
var target;
if ('target' in wanted) {
target = TARGETS.find(function (candidate) { return candidate.id === wanted.target; });
if (!target) return ctx.respond(400, { error: 'There is no such target; GET /targets lists them.' });
} else {
if (!isNumber(wanted.ra) || !isNumber(wanted.dec) || wanted.ra < 0 || wanted.ra >= 24 || wanted.dec < -90 || wanted.dec > 90) {
return ctx.respond(400, { error: 'Give target, or ra (0 up to 24 hours) and dec (-90 to 90 degrees).' });
}
target = { id: 'custom', name: 'Field', title: 'Custom position', kind: 'field', ra: Math.round(wanted.ra * 10000) / 10000, dec: Math.round(wanted.dec * 1000) / 1000 };
}
slew(target);
return state();
},
'POST /capture': function (request) {
tick();
var wanted = request.json();
if (!wanted || typeof wanted !== 'object') return ctx.respond(400, { error: 'The body is a JSON object.' });
var running = wanted.running, exposure = wanted.exposureSeconds, gain = wanted.gain;
if (running !== undefined && running !== null && typeof running !== 'boolean') return ctx.respond(400, { error: 'running is true or false.' });
if (exposure !== undefined && exposure !== null && EXPOSURES.indexOf(exposure) < 0) {
return ctx.respond(400, { error: 'exposureSeconds is one of ' + EXPOSURES.join(', ') + '.' });
}
if (gain !== undefined && gain !== null && (!Number.isInteger(gain) || gain < 0 || gain > GAIN_MAX)) {
return ctx.respond(400, { error: 'gain is a whole number from 0 to ' + GAIN_MAX + '.' });
}
if ((typeof exposure === 'number' && exposure !== sim.exposure) || (typeof gain === 'number' && gain !== sim.gain)) {
if (typeof exposure === 'number') sim.exposure = exposure;
if (typeof gain === 'number') sim.gain = gain;
newStack(); // frames of different settings are not averaged together
}
if (typeof running === 'boolean' && running !== sim.running) {
sim.running = running;
sim.elapsed = 0;
}
changed();
return state();
},
},
sockets: {
'/events': function (socket) {
sockets.push(socket);
tick();
socket.send({ type: 'state', state: state() });
var told = sim.clock;
// Four times a second: the clock of the observatory. The state goes out once a second, and four
// times a second while the mount slews.
var timer = setInterval(function () {
tick();
if (sim.clock - told >= 1 || sim.goal !== null) {
told = sim.clock;
socket.send({ type: 'state', state: state() });
}
}, 250);
socket.onclose = function () {
clearInterval(timer);
sockets.splice(sockets.indexOf(socket), 1);
};
},
},
});
})();