"""
Remove the faint picture of the Earth's surface that a night-lights map shows under its lights,
leaving the lights on black, for use as an emissive texture.

Maps like NASA's Black Marble composite the city lights over a dim, bluish rendition of the
surface. As emission that would make the whole night side glow; only the lights should.

How it works, per color channel, in linear values (not the file's sRGB-encoded ones):

1. The surface layer is estimated as what is left after a grey-scale morphological opening:
   the image's minimum over a square of side 2*radius+1 pixels, then the maximum over the same
   square. Anything smaller than the square (a city, a road of lights) is removed, and anything
   larger (an ocean, a desert, an ice sheet) is kept, edges and all, so coastlines come out
   clean. The image is blurred slightly first, so JPEG noise does not drag the minimum down.
2. That estimate is subtracted, and then a small noise floor, so that what is left of the
   surface and of the JPEG's compression noise falls below zero and is clipped to black.
3. What is still left of the surface is small features brighter than their surroundings, like
   glaciers and fjords. The map draws its lights warm (in Black Marble, all but about 0.1% of
   clearly lit pixels are at least as red as they are blue) and the surface bluish, so any pixel
   left bluer than it is red is surface, and is set to black. --keep-blue skips this, for a map
   whose lights are not drawn warm.

Nothing is stretched back out afterwards: subtracting a surface layer of about 0.005 from
lights of up to about 1 changes their brightness by well under 1%, and the emissive factor sets
the lights' absolute radiance anyway.

The result is written sRGB-encoded, like the input, so it is read the same way
(read_image, then srgb_to_linear). PNG avoids adding new JPEG noise to the dark areas.

Usage:
    python remove_night_base.py 8k_earth_nightmap.jpg 8k_earth_nightlights.png
    python remove_night_base.py 8k_earth_nightmap.jpg out.png --radius 24 --floor 3 --preview previews

Needs numpy, scipy and Pillow.
"""

import argparse
from pathlib import Path

import numpy as np
from PIL import Image
from scipy import ndimage

Image.MAX_IMAGE_PIXELS = None  # the 8k maps are larger than Pillow's default limit


def srgb_to_linear(s):
    return np.where(s <= 0.04045, s / 12.92, ((s + 0.055) / 1.055) ** 2.4).astype(np.float32)


def linear_to_srgb(x):
    x = np.clip(x, 0.0, 1.0)
    return np.where(x <= 0.0031308, x * 12.92, 1.055 * x ** (1 / 2.4) - 0.055).astype(np.float32)


def surface_layer(channel, radius, blur):
    """The smooth surface under the lights: an opening of the slightly blurred channel."""
    smooth = ndimage.gaussian_filter(channel, blur) if blur > 0 else channel
    size = 2 * radius + 1
    # The map wraps in longitude, so filter across the left and right edges; it does not wrap
    # over the poles.
    return ndimage.grey_opening(smooth, size=(size, size), mode=("nearest", "wrap"))


def remove_surface(linear, radius, blur, floor, keep_blue):
    lights = np.empty_like(linear)
    for c in range(linear.shape[2]):
        lights[..., c] = linear[..., c] - surface_layer(linear[..., c], radius, blur) - floor
    lights = np.clip(lights, 0.0, None)
    if not keep_blue:
        lights[lights[..., 2] > lights[..., 0]] = 0.0
    return lights


def save_previews(srgb_in, srgb_out, directory, gain=4):
    """Crops of the input and the result side by side, brightened `gain` times."""
    directory.mkdir(parents=True, exist_ok=True)
    h, w, _ = srgb_in.shape
    regions = {  # (west, north, east, south), in degrees
        "europe_sahara": (-12, 60, 40, 15),
        "greenland": (-60, 80, -15, 58),
        "us_east": (-95, 48, -65, 25),
    }
    for name, (west, north, east, south) in regions.items():
        x0, x1 = int((west + 180) / 360 * w), int((east + 180) / 360 * w)
        y0, y1 = int((90 - north) / 180 * h), int((90 - south) / 180 * h)
        pair = np.concatenate([srgb_in[y0:y1, x0:x1], srgb_out[y0:y1, x0:x1]], axis=1)
        pair = np.clip(pair * 255 * gain, 0, 255).astype(np.uint8)
        image = Image.fromarray(pair)
        image = image.resize((image.width // 2, image.height // 2), Image.BOX)
        image.save(directory / f"{name}_before_after_x{gain}.png")


def main():
    parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0])
    parser.add_argument("input", type=Path, help="the night map, sRGB-encoded (JPEG or PNG)")
    parser.add_argument("output", type=Path, help="where to write the lights (PNG recommended)")
    parser.add_argument("--radius", type=int, default=16,
                        help="half-size, in pixels, of the largest patch of lights kept as lights; "
                             "larger patches count as surface (default 16, about 80 km at 8k)")
    parser.add_argument("--blur", type=float, default=1.5,
                        help="Gaussian blur, in pixels, before estimating the surface (default 1.5)")
    parser.add_argument("--floor", type=float, default=3.0,
                        help="noise floor subtracted after the surface, in 8-bit counts just above "
                             "black (default 3)")
    parser.add_argument("--keep-blue", action="store_true",
                        help="keep what is left that is bluer than it is red (see step 3)")
    parser.add_argument("--preview", type=Path, help="also write before/after crops here")
    args = parser.parse_args()

    srgb_in = np.asarray(Image.open(args.input).convert("RGB"), dtype=np.float32) / 255
    linear = srgb_to_linear(srgb_in)

    # A count just above black is 1/255 in sRGB, which is 1/(255 * 12.92) linear.
    floor = args.floor / (255 * 12.92)
    lights = remove_surface(linear, args.radius, args.blur, floor, args.keep_blue)
    srgb_out = linear_to_srgb(lights)

    Image.fromarray(np.round(srgb_out * 255).astype(np.uint8)).save(args.output)

    lum_in, lum_out = linear.mean(axis=2), lights.mean(axis=2)
    print(f"Wrote {args.output}")
    print(f"  pixels left black:          {np.mean(srgb_out.max(axis=2) < 0.5 / 255):.1%}")
    print(f"  median, linear:             {np.median(lum_in):.5f} -> {np.median(lum_out):.5f}")
    print(f"  99.9th percentile, linear:  {np.percentile(lum_in, 99.9):.4f} -> "
          f"{np.percentile(lum_out, 99.9):.4f}")
    print(f"  total light, linear sum:    {lum_in.sum():.4g} -> {lum_out.sum():.4g}")

    if args.preview:
        save_previews(srgb_in, srgb_out, args.preview)
        print(f"  previews in {args.preview}")


if __name__ == "__main__":
    main()
