# Original Bopbun code and figure composition: CC0-1.0. See LICENSE.txt.
# Run: python object-method.py (data.csv must be beside this script).
from pathlib import Path
import csv
import hashlib
import json
import platform
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from matplotlib import font_manager

out = Path(__file__).resolve().parent
input_path = out / 'data.csv'
input_hash = hashlib.sha256(input_path.read_bytes()).hexdigest()
with input_path.open(newline='', encoding='utf-8') as stream:
    rows = list(csv.DictReader(stream))
z = np.full((3, 4), np.nan)
for row in rows:
    z[int(row['row']), int(row['column'])] = float(row['value'])
assert len(rows) == 12 and np.isfinite(z).all()
saved = z.copy()

original = matplotlib.colormaps['viridis']
reversed_object = original.reversed()
named_reverse = matplotlib.colormaps['viridis_r']
# Independently reverse the original 256-entry color list, then compare each bin.
reference = np.asarray(original.colors)[::-1]
centers = (np.arange(256) + 0.5) / 256
assert np.array_equal(reversed_object(centers)[:, :3], reference)
assert np.array_equal(named_reverse(centers), reversed_object(centers))

plt.rcParams.update({'font.family': 'DejaVu Sans', 'font.size': 12,
                     'pdf.fonttype': 42, 'savefig.dpi': 160})
checks = {}
for filename, cmap, title in [
    ('original-method', original, 'Original viridis'),
    ('named-method', 'viridis_r', 'Reversed viridis'),
    ('object-method', reversed_object, 'Reversed viridis')
]:
    fig, ax = plt.subplots(figsize=(7.2, 4.5), layout='constrained')
    im = ax.imshow(z, cmap=cmap, vmin=0, vmax=8, interpolation='nearest')
    for i, j in np.ndindex(z.shape):
        r, g, b, _ = im.cmap(im.norm(z[i, j]))
        luminance = 0.2126*r + 0.7152*g + 0.0722*b
        ax.text(j, i, f'{z[i, j]:.0f}', ha='center', va='center',
                color='black' if luminance > 0.45 else 'white', fontsize=15)
    ax.set(xticks=range(4), yticks=range(3), xlabel='Column', ylabel='Row', title=title)
    colorbar = fig.colorbar(im, ax=ax, ticks=range(9), label='Response (a.u.)')
    fig.canvas.draw()
    renderer = fig.canvas.get_renderer()
    outside = []
    for area in fig.axes:
        for text in [area.title, area.xaxis.label, area.yaxis.label,
                     *area.get_xticklabels(), *area.get_yticklabels(), *area.texts]:
            if text.get_visible() and text.get_text():
                box = text.get_window_extent(renderer)
                if box.x0 < -1 or box.y0 < -1 or box.x1 > fig.bbox.width+1 or box.y1 > fig.bbox.height+1:
                    outside.append(text.get_text())
    assert not outside, outside
    assert np.array_equal(im.get_array(), saved)
    assert im.get_clim() == (0.0, 8.0)
    assert colorbar.ax.get_ylim() == (0.0, 8.0)
    fig.savefig(out / f'{filename}.png')
    if filename == 'object-method':
        fig.savefig(out / 'object-method.pdf', metadata={'CreationDate': None, 'ModDate': None})
    checks[filename] = {'shape': list(z.shape), 'sum': float(z.sum()),
                        'clim': list(im.get_clim()), 'colorbar_limits': list(colorbar.ax.get_ylim()),
                        'data_axes_limits': [list(ax.get_xlim()), list(ax.get_ylim())],
                        'text_outside_canvas': outside}
    plt.close(fig)

assert hashlib.sha256(input_path.read_bytes()).hexdigest() == input_hash
from PIL import Image
with Image.open(out/'named-method.png') as a, Image.open(out/'object-method.png') as b:
    assert np.array_equal(np.asarray(a), np.asarray(b))
    png_size = list(b.size)
result = {'python': platform.python_version(), 'numpy': np.__version__,
          'matplotlib': matplotlib.__version__, 'input_sha256': input_hash,
          'color_entries_checked': 256, 'cell_values_checked': 12,
          'named_and_object_pixels_equal': True, 'png_pixels': png_size,
          'pdf_inches': [7.2, 4.5], 'font_file': Path(font_manager.findfont('DejaVu Sans')).name,
          'checks': checks}
(out/'run.json').write_text(json.dumps(result, indent=2), encoding='utf-8')
print(json.dumps(result))
