# قياس مشهد MODIS MOD11A1 h20v05 2026-11-30. إعادة: python3 modis_measure.py
import numpy as np,hashlib,json
from pyhdf.SD import SD,SDC
P='/downloads/anan2090/units/MOD11A1_h20v05.hdf'
sha=hashlib.sha256(open(P,'rb').read()).hexdigest()
f=SD(P,SDC.READ);print('datasets:',[k for k in f.datasets()][:20])
out={'file':'MOD11A1.A2026334.h20v05.061.2026336211750','sha256':sha,'sha256_expected':'38f566a21f74c36c9483506a0e897780ff2a450a1934fe7e7c066777f926b2ae','sha_match':sha=='38f566a21f74c36c9483506a0e897780ff2a450a1934fe7e7c066777f926b2ae'}
for name,qc in (('LST_Day_1km','QC_Day'),('LST_Night_1km','QC_Night')):
    s=f.select(name);a=s[:].astype(np.int64);at=s.attributes();scale=at.get('scale_factor',0.02);fill=at.get('_FillValue',0)
    q=f.select(qc)[:].astype(np.int64)
    n=a.size;valid=a!=0
    qcl=q&3   # bits0-1: 0 = LST produced good quality, 1 = produced other quality, 2 = not produced cloud, 3 = not produced other
    good=valid&(qcl==0)
    k=(a[valid]*float(scale));c=k-273.15
    g=(a[good]*float(scale))-273.15
    out[name]={'scale_factor':float(scale),'fill_value':float(fill),'total_pixels':int(n),'valid_pixels':int(valid.sum()),'rejected_fill_or_cloud':int(n-valid.sum()),
     'qc_good_pixels':int(good.sum()),'qc_not_produced_cloud':int((qcl==2).sum()),'qc_not_produced_other':int((qcl==3).sum()),
     'min_C':round(float(c.min()),2) if c.size else None,'max_C':round(float(c.max()),2) if c.size else None,'median_C':round(float(np.median(c)),2) if c.size else None,'mean_C':round(float(c.mean()),2) if c.size else None,
     'good_only_median_C':round(float(np.median(g)),2) if g.size else None,'good_only_range_C':[round(float(g.min()),2),round(float(g.max()),2)] if g.size else None}
json.dump(out,open('/downloads/anan2090/units/modis_result.json','w'),indent=1,ensure_ascii=False)
print(json.dumps(out,indent=1,ensure_ascii=False))
