"""Deterministic synthetic intensity display; not a physical depth reconstruction."""
from pathlib import Path
import csv, hashlib, json
import numpy as np
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt

OUT = Path(__file__).resolve().parent
N = 65
u = np.linspace(-1, 1, N)
X, Y = np.meshgrid(u, u)
# Chosen normalized reflectance on a perfectly flat, uniformly lit surface.
# Ideal linear detector, no noise, shadows, perspective or optical blur.
I = 0.15 + 0.65 * np.exp(-((X / 0.42) ** 2 + (Y / 0.60) ** 2))
Z = np.zeros_like(I)
H = I.copy()  # Display convention only; there is no physical height calibration.
assert np.all(Z == 0) and np.allclose(H, I)
assert 0 <= I.min() <= I.max() <= 1
with (OUT / 'intensity-height.csv').open('w', newline='', encoding='utf-8') as f:
    w = csv.writer(f)
    w.writerow(['x_normalized', 'y_normalized', 'intensity_normalized', 'true_height_normalized', 'display_height_normalized'])
    w.writerows(zip(X.ravel(), Y.ravel(), I.ravel(), Z.ravel(), H.ravel()))

plt.rcParams.update({'font.size': 11, 'svg.fonttype': 'none', 'font.family': 'DejaVu Sans'})
fig = plt.figure(figsize=(12, 5.4), facecolor='white')
ax = fig.add_subplot(121)
im = ax.imshow(I, extent=[-1, 1, -1, 1], origin='lower', cmap='gray', vmin=0, vmax=1)
ax.set(title='A  Brightness on a flat surface', xlabel='x (normalized position)', ylabel='y (normalized position)')
fig.colorbar(im, ax=ax, shrink=.72, pad=.035, label='Intensity (normalized, 0–1)')
ax.text(.03, .97, 'True height = 0 everywhere', transform=ax.transAxes, va='top', color='#75ddff', fontsize=10)
bx = fig.add_subplot(122, projection='3d')
bx.plot_surface(X, Y, H, cmap='magma', vmin=0, vmax=1, rcount=N, ccount=N, linewidth=0, alpha=.94)
bx.plot([-1,1,1,-1,-1],[-1,-1,1,1,-1],[0]*5, color='#007d91', linewidth=2)
bx.set(title='B  The same intensity displayed as height', xlabel='x (normalized)', ylabel='y (normalized)', zlabel='Display height (normalized)', zlim=(0,1))
bx.set_xticks([-1,0,1]); bx.set_yticks([-1,0,1]); bx.set_zticks([0,.5,1])
bx.view_init(elev=27, azim=-55)
bx.text2D(.06,.96,'Blue outline: true flat surface at height 0', transform=bx.transAxes, color='#006978', fontsize=10)
fig.suptitle('A raised display is not a measured raised object', fontsize=16, y=.99)
fig.text(.5,.025,'SYNTHETIC MODEL  •  Uniform lighting + varying reflectance  •  Display rule: height = intensity',ha='center',fontsize=11)
fig.subplots_adjust(left=.065,right=.95,bottom=.14,top=.86,wspace=.20)
for ext in ['svg','png','pdf']:
    fig.savefig(OUT / f'intensity-height.{ext}', dpi=180, facecolor='white', metadata={'Creator':'Scientific Systems Lab synthetic teaching model'})
plt.close(fig)
metadata={'synthetic':True,'measured_data':False,'grid_shape':[N,N],'rows':N*N,'formula':'I(x,y) = 0.15 + 0.65 exp(-((x/0.42)^2 + (y/0.60)^2))', 'true_height':'0 everywhere', 'display_rule':'h_display = I', 'units':'All coordinates, intensity and display height are normalized dimensionless quantities; no physical length calibration.', 'intensity_min':float(I.min()),'intensity_max':float(I.max()),'numpy':np.__version__,'matplotlib':matplotlib.__version__,'csv_sha256':hashlib.sha256((OUT/'intensity-height.csv').read_bytes()).hexdigest()}
(OUT/'study.json').write_text(json.dumps(metadata,indent=2)+'\n',encoding='utf-8')
print(json.dumps(metadata,indent=2))
