"""Data preparation for the still battery (not product code): copy a SwissFEL converted JUNGFRAU file, replacing /data/data (float32 keV) by int16 photon counts, bitshuffle/LZ4, one chunk per frame. Everything else is copied unchanged. Non-finite values (NaN, inf) -> -32768, the int16 error marker. usage: float32_to_int16.py Needs h5py and hdf5plugin. The copies are the alvra*_int16 sets of still_manifest.json; read them with --gain 1. See docs/EXTERNAL_TEST_DATA_STILLS.md.""" import os, sys, time, h5py, hdf5plugin, numpy as np src, dst, e_kev = sys.argv[1], sys.argv[2], float(sys.argv[3]) t0 = time.time() with h5py.File(src, 'r') as fi, h5py.File(dst + '.part', 'w') as fo: for k, v in fi.attrs.items(): fo.attrs[k] = v def copy(name, obj): if name == 'data/data': return if isinstance(obj, h5py.Group): g = fo.require_group(name) for k, v in obj.attrs.items(): g.attrs[k] = v else: fo.copy(obj, name if '/' not in name else fo.require_group(name.rsplit('/', 1)[0]), name=name.rsplit('/', 1)[-1]) fi.visititems(copy) d = fi['data/data'] n, h, w = d.shape out = fo.create_dataset('data/data', shape=(n, h, w), dtype='int16', chunks=(1, h, w), **hdf5plugin.Bitshuffle(nelems=0, cname='lz4')) for k, v in d.attrs.items(): out.attrs[k] = v out.attrs['photon_energy_keV_used_for_conversion'] = e_kev out.attrs['conversion'] = 'int16 photons = round(float32 keV / photon_energy_keV), non-finite -> -32768 (no measurement), others clipped to [-32767, 32767]; original: ' + src nan = clipped = 0 hist = np.zeros(4, dtype=np.int64) # <0, 0, 1, >=2 photons for i in range(n): x = d[i] bad = ~np.isfinite(x) nan += int(bad.sum()) p = np.rint(np.where(bad, 0, x) / e_kev) clipped += int(((p > 32767) | (p < -32767)).sum()) p = np.clip(p, -32767, 32767).astype(np.int16) p[bad] = -32768 if i % 50 == 0: hist += [(p < 0).sum(), (p == 0).sum(), (p == 1).sum(), (p >= 2).sum()] out[i] = p os.rename(dst + '.part', dst) s_in, s_out = os.path.getsize(src), os.path.getsize(dst) print(f'{os.path.basename(src)} frames {n} in {s_in/1e9:.2f} GB out {s_out/1e9:.3f} GB ratio {s_in/s_out:.1f} ' f'MB/frame {s_in/n/1e6:.2f}->{s_out/n/1e6:.3f} time {time.time()-t0:.0f} s nan {nan} clipped {clipped} ' f'sampled photon hist <0/0/1/>=2 {hist.tolist()}', flush=True)