from pathlib import Path
import json, numpy as np
from collections import Counter
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
from PIL import Image
root=Path(__file__).resolve().parent.parent
m=json.loads((root/'参考库/参考子库清单.json').read_text());r=json.loads((root/'附件/小范围匹配结果.json').read_text());c=json.loads((root/'附件/方法控制验证.json').read_text())
lib=np.load(root/'参考库/参考子库_仪器波长对齐.npz');obs=np.load(root/'附件/18窗口中位光谱.npz')
accepted=[p for p in r['points'] if p['status']=='candidate']
deltas=np.array([p['matching']['cosine']-p['shift_40nm_control_cosine'] for p in accepted])
summary={'data_windows':18,'raw_pixels_in_windows':18*48*24,'cell_size':[4,4],'tested_cells':len(r['points']),
    'candidate_cells':len(accepted),'unresolved_cells':len(r['points'])-len(accepted),
    'candidates_by_box':{str(box):dict(Counter(p['matching']['best_group'] for p in accepted if p['box']==box)) for box in [4,5]},
    'best_refs_among_roi_medians':dict(Counter(m['refs'][p['matching']['best_ref']]['filename'] for p in r['patches'])),
    'accepted_cell_shift_40nm_control':{'n':len(deltas),'mean_original_minus_shifted_cosine':float(deltas.mean()),
        'median_original_minus_shifted_cosine':float(np.median(deltas)),
        'original_score_higher_count':int((deltas>0).sum()),'lower_or_equal_count':int((deltas<=0).sum())},
    'unique_specimen_families':len(set(x['specimen_family'] for x in m['refs'])),
    'matched_species_count':len(set(x['mineral'] for x in m['refs'])),
    'purity_counts':dict(Counter(x['purity_code'] for x in m['refs'])),
    'unresolved_reasons':r['unresolved_reasons'],
    'independent_customer_validation':'NOT AVAILABLE; all results remain hypotheses'}
(root/'附件/验证摘要.json').write_text(json.dumps(summary,ensure_ascii=False,indent=2))
# Plot the one ROI-median candidate with actual source crop, common-axis spectra, feature and residual.
p=next(p for p in r['patches'] if p['status']=='candidate');index=[x['id'] for x in r['patches']].index(p['id']);mch=p['matching'];reference=m['refs'][mch['best_ref']]
x0,x1=p['x_bounds'];y0,y1=p['y_bounds'];source=root.parent/'调整后目标';folder=next(source.glob(f'SWIR_b_{p["box"]}_*'));im=np.asarray(Image.open(folder/f'{folder.name}.png'))
w=lib['wavelength_nm'];mw=lib['match_wavelength_nm'];wi=np.array(m['match_band_indices_zero_based']);ob=obs['spectra'][index];rf=lib['spectra_fwhm12'][mch['best_ref']]
# Independent plot-side upper envelope, kept local so the figure can be regenerated without running matching.
def dep(w,y):
 hull=[]
 for k in range(len(w)):
  while len(hull)>=2:
   a,b=hull[-2:]
   if (y[b]-y[a])/(w[b]-w[a]) <= (y[k]-y[b])/(w[k]-w[b]):hull.pop()
   else:break
  hull.append(k)
 return np.maximum(1-y/np.interp(w,w[hull],y[hull]),0)
q=dep(mw,ob[wi]);f=lib['absorption_fwhm12'][mch['best_ref']]*mch['depth_scale'];alt=mch['alternative_ref'];aq=lib['absorption_fwhm12'][alt];af=aq*(q@aq/max(aq@aq,1e-12))
fig,axs=plt.subplots(2,2,figsize=(12,8))
axs[0,0].imshow(im[y0:y1,x0:x1],extent=(x0,x1,y1,y0));axs[0,0].set(title=f'{p["id"]} | source preview crop',xlabel='Image x',ylabel='Image y; NOT depth')
valid=(w>=1050)&(w<=2450)
axs[0,1].plot(w[valid],ob[valid]/np.mean(ob[valid]),color='black',label='Core white-relative median, mean-normalized')
axs[0,1].plot(w[valid],rf[valid]/np.nanmean(rf[valid]),label='USGS best reference, mean-normalized')
axs[0,1].axvspan(2050,2450,color='#0072B2',alpha=.08);axs[0,1].set(title='Whole SWIR shape; shaded region used for matching',xlabel='Wavelength (nm)',ylabel='Relative shape');axs[0,1].legend(fontsize=7)
axs[1,0].plot(mw,q,color='black',label='Core continuum-removed depth');axs[1,0].plot(mw,f,color='#0072B2',label='Scaled '+reference['mineral']+' reference');axs[1,0].plot(mw,af,'--',color='#D55E00',label='Competing '+m['refs'][alt]['mineral'])
axs[1,0].set(title=f'Feature cosine {mch["cosine"]:.4f}; group margin {mch["group_margin"]:.4f}',xlabel='Wavelength (nm)',ylabel='Feature depth');axs[1,0].legend(fontsize=7)
axs[1,1].plot(mw,q-f,color='#7B2CBF');axs[1,1].axhline(0,color='gray',lw=.7);axs[1,1].set(title=f'Feature residual fraction {mch["residual_fraction"]:.3f}; not abundance error',xlabel='Wavelength (nm)',ylabel='Observed - fitted feature')
fig.suptitle('Priority review ROI: amphibole-like candidate, NOT confirmed actinolite\nReference: '+reference['filename'],fontsize=11)
fig.tight_layout(rect=[0,0,1,.93]);fig.savefig(root/'图表/06_优先复核窗口_匹配与残差.png',dpi=160);plt.close(fig)
print(json.dumps(summary,ensure_ascii=False,indent=2))
