#!/usr/bin/env python

import numpy as np
import h5py
import matplotlib.pyplot as plt
from matplotlib.colors import LogNorm

def show_frame(data, event, apa, tag) :
  key = '/%d/frame_%s%d'%(event,tag,apa)
  f = data.get(key)
  if f is None:
    print('f is None')
    return
  frame = np.array(f)
  frame_ma = np.ma.array(frame)
  fontsize = 24
  plt.imshow(np.ma.masked_where(frame_ma<=100,frame_ma), cmap="bwr_r", interpolation="none"
  #plt.imshow(frame, cmap="rainbow", interpolation="none"
  # , extent = [0 , 2560, 0 , 600]
  # , extent = [0 , 2300, 0 , 4800]
  #, norm=LogNorm()
  , origin='lower'
  , aspect=0.8/4.7 # 1 tick ~ 0.8 mm; 1 pitch ~ 4.7 mm 
  # , aspect='auto'
  # , aspect=0.1
  )
  plt.colorbar()
  # plt.xlim([0,800]) # U
  # plt.xlim([800,1600]) # V
  plt.xlim([0,1600]) # V
  plt.ylim([0, 6000])
  plt.clim([0,1])
  plt.xticks(fontsize=fontsize)
  plt.yticks(fontsize=fontsize)
  ax = plt.gca()
  ax.xaxis.set_major_locator(plt.MaxNLocator(5))
  plt.xlabel('Wire [4.7mm spacing]', fontsize=fontsize)
  plt.ylabel('Time [0.5$\mu$s]', fontsize=fontsize)
  plt.grid()
  plt.show()


if __name__ == '__main__':
  apa = 0
  tag = 'ductor'

  # data = h5py.File('cosmic-500-event-IonAndScint/g4-tru-%d.h5'%apa, 'r')
  # data = h5py.File('/home/yuhw/wc/wct-analysis/ml-sp/backup/eval-dune-collab-2020-01/nf-on/eval-87-85/g4-tru-0.h5')
  # data = h5py.File('beam-cosmic-500-event/g4-tru-%d.h5'%apa, 'r')
  # data = h5py.File('pr79/ref.h5', 'r')
  # data = h5py.File('nf-on/ref-87-75/g4-tru-0.h5', 'r')
  data = h5py.File('g4-tru-0.h5', 'r')


  plt.figure()

  start = 100
  for event in range(start, start+len(list(data.keys()))) :
    print("processing event: ", event)
    show_frame(data, event, apa, tag)
