#!/usr/bin/env python3
"""Render the stacking demonstration to docs/planetary-imaging/img/fig-stacking.png.
Run scripts/stacking_demo.py first; it leaves the arrays in /tmp."""
import numpy as np
from PIL import Image, ImageDraw, ImageFont

S = 2                                  # supersample
PW, PH = 300, 200
COLS = [('_one_%d', 'one frame'), ('_stack_%d', 'best 5% stacked'), ('_dec_%d', 'stacked + deconvolved')]
ROWS = [(100, '100 mm', 1.384), (200, '200 mm (8 in)', 0.692), (356, '356 mm (14 in)', 0.389)]
INK, INK3, RULE = (24, 23, 21), (110, 103, 91), (228, 221, 203)
LAB, GAP, PAD, TOP = 150, 12, 22, 96

def font(sz, bold=False):
    for p in ('/usr/share/fonts/truetype/dejavu/DejaVuSans%s.ttf' % ('-Bold' if bold else ''),):
        try: return ImageFont.truetype(p, sz)
        except Exception: pass
    return ImageFont.load_default()

def panel(a, lo, hi):
    a = np.clip((a - lo) / (hi - lo), 0, 1)
    im = Image.fromarray((a * 255).astype(np.uint8), 'L').convert('RGB')
    return im.resize((PW * S, PH * S), Image.NEAREST)

truth = np.load('/tmp/_truth.npy')
lo, hi = float(truth.min()), float(truth.max())
Wpx = PAD * 2 + LAB + 3 * PW * S + 2 * GAP
Hpx = TOP + PH * S + 34 + 3 * (PH * S + 30) + 46
img = Image.new('RGB', (Wpx, Hpx), 'white')
d = ImageDraw.Draw(img)
d.text((PAD, 26), 'What stacking recovers, and where it stops', font=font(30, True), fill=INK)
d.text((PAD, 62), 'Same synthetic target throughout. The ladder on the right has line pairs at 1.6, 0.8, 0.4 and 0.2 arcsec, top to bottom.',
       font=font(17), fill=INK3)

y = TOP
img.paste(panel(truth, lo, hi), (PAD + LAB, y))
d.text((PAD, y + 8), 'ground truth', font=font(18, True), fill=INK)
d.text((PAD, y + 30), 'synthetic —', font=font(15), fill=INK3)
d.text((PAD, y + 48), 'no photograph', font=font(15), fill=INK3)
d.text((PAD, y + 66), 'was used', font=font(15), fill=INK3)
y += PH * S + 34

for i, (mm, name, dl) in enumerate(ROWS):
    for j, (pat, title) in enumerate(COLS):
        a = np.load('/tmp/' + (pat % mm) + '.npy')
        x = PAD + LAB + j * (PW * S + GAP)
        img.paste(panel(a, lo, hi), (x, y))
        if i == 0:
            d.text((x + 4, y - 26), title, font=font(18, True), fill=INK)
    d.text((PAD, y + 10), name, font=font(16, True), fill=INK)
    d.text((PAD, y + 34), 'resolution', font=font(15), fill=INK3)
    d.text((PAD, y + 52), 'limit %.2f"' % dl, font=font(15), fill=INK3)
    y += PH * S + 30

d.text((PAD, Hpx - 40), 'Contrast recovered at 1.6 arcsec runs 0.005 / 0.105 / 0.214 for the three apertures against a true 0.224 — it tracks the telescope.',
       font=font(17), fill=INK3)
d.text((PAD, Hpx - 20), 'Nothing finer than an aperture\'s own diffraction limit is ever recovered, by any number of frames or iterations.',
       font=font(17), fill=INK3)
img.save('docs/planetary-imaging/img/fig-stacking.png')
print('wrote docs/planetary-imaging/img/fig-stacking.png', img.size)
