from json import detect_encoding from tkinter.ttk import Sizegrip from collections import deque import numpy as np import time import pickle import os import epics from slic.gui.widgets import LabeledMathEntry from slic.gui.widgets import make_filled_hbox, make_filled_vbox, EXPANDING from slic.gui.widgets.plotting import PlotPanel from itertools import groupby from bstrd import BS, bsstream from epics import caget, caput, cainfo from scipy.signal import savgol_filter import wx def create_text_entry(parent,text = "", maxlength = 12, hint = None, setvalue = None): text = wx.StaticText(parent, -1, text) textctrl = wx.TextCtrl(parent) textctrl.SetMaxLength(maxlength) if hint is not None: textctrl.SetHint('%s'%str(hint)) if setvalue is not None: textctrl.SetValue('%s'%str(setvalue)) return text, textctrl class DataManager: # init method or constructor def __init__(self, queue_length,number_shots, sizer = None, parent = None, scannable_channel = None): self.detectors = [] self.queue_length = queue_length self.number_shots = number_shots self.figsizer = sizer self.wxparent = parent self.scannable_channel = scannable_channel self.scannable_pv = epics.PV(scannable_channel[:-4]) self.connect_scannable_BS() self.histogram = None # Sample Method def add_detector(self, detector): if detector.detector_shape == 1: data_shape = np.empty((self.number_shots, detector.ROI[1] - detector.ROI[0])) roi = [detector.ROI[0],detector.ROI[1]] else: data_shape = np.empty(self.number_shots) roi = None if detector.plot: plot, histogram, plot_items= self.create_plots(detector_shape = detector.detector_shape, roi_value= roi) detector_dict = { "Det":detector, "Plot": plot, "Hist": histogram, "ROI_Thresh_Panel": plot_items, "Data": data_shape } self.detectors.append(detector_dict) def create_plots(self, detector_shape = 1, roi_value = [0,100], figsize = (4,2), border = 10): if detector_shape == 0: histogram = PlotPanel(self.wxparent, figsize=figsize) #Threshold based on histogram intensity #FOR I0 text_thresh_min, textctrl_thresh_min = create_text_entry(self.wxparent, text = 'Signal Intensity min', setvalue = 0) text_thresh_max, textctrl_thresh_max = create_text_entry(self.wxparent, text = 'Signal Intensity max', setvalue = 0) btn_threshold_update = wx.Button(self.wxparent, label="Set Threshold") btn_threshold_update.Bind(wx.EVT_BUTTON, self.Threshold_update) thresh_min_box = make_filled_vbox((text_thresh_min, textctrl_thresh_min)) thresh_max_box = make_filled_vbox((text_thresh_max, textctrl_thresh_max)) thresh_box = make_filled_hbox((thresh_min_box, thresh_max_box, btn_threshold_update)) box_items = { 'Thresh_min': textctrl_thresh_min, 'Thresh_max': textctrl_thresh_max, 'Threshold_Set_Btn': btn_threshold_update } full_plot_panel = make_filled_vbox((histogram, thresh_box)) plot = None if detector_shape == 1: #Create plots plot = PlotPanel(self.wxparent, figsize=figsize) histogram = PlotPanel(self.wxparent, figsize=figsize) #Roi buttons for data text_min, textctrl_min = create_text_entry(self.wxparent, text = 'ROI min', setvalue = roi_value[0]) text_max, textctrl_max = create_text_entry(self.wxparent, text = 'ROI max', setvalue = roi_value[1]) btn_ROI_update = wx.Button(self.wxparent, label="Update ROI") btn_ROI_update.Bind(wx.EVT_BUTTON, self.update_ROIs_btns) minbox = make_filled_vbox((text_min, textctrl_min)) maxbox = make_filled_vbox((text_max, textctrl_max)) roibox = make_filled_hbox((minbox, maxbox, btn_ROI_update)) #Threshold based on histogram intensity #FOR I0 text_thresh_min, textctrl_thresh_min = create_text_entry(self.wxparent, text = 'Signal Intensity min', setvalue = 0) text_thresh_max, textctrl_thresh_max = create_text_entry(self.wxparent, text = 'Signal Intensity max', setvalue = 0) btn_threshold_update = wx.Button(self.wxparent, label="Set Threshold") btn_threshold_update.Bind(wx.EVT_BUTTON, self.Threshold_update) thresh_min_box = make_filled_vbox((text_thresh_min, textctrl_thresh_min)) thresh_max_box = make_filled_vbox((text_thresh_max, textctrl_thresh_max)) thresh_box = make_filled_hbox((thresh_min_box, thresh_max_box, btn_threshold_update)) box_items = { 'ROI_min': textctrl_min, 'ROI_max': textctrl_max, 'ROI_Set_Btn': btn_ROI_update, 'Thresh_min': textctrl_thresh_min, 'Thresh_max': textctrl_thresh_max, 'Threshold_Set_Btn': btn_threshold_update } full_plot_panel = make_filled_vbox((plot,roibox, histogram, thresh_box)) self.figsizer.Add(full_plot_panel, 0, wx.ALL, border ) self.figsizer.Layout() return plot, histogram, box_items def update_ROIs_btns(self, _event): self.update_ROIS() def Threshold_update(self, _event): self.update_thresholds() def update_thresholds(self): for i,det in enumerate(self.detectors): if det['Det'].detector_shape == 1: #Set detecotor ROI det['Det'].intensity_threshold = [np.double(det['ROI_Thresh_Panel']['Thresh_min'].GetValue()), np.double(det['ROI_Thresh_Panel']['Thresh_max'].GetValue())] def update_ROIS(self): for i,det in enumerate(self.detectors): if det['Det'].detector_shape == 1: #Set detecotor ROI det['Det'].ROI = [np.int16(det['ROI_Thresh_Panel']['ROI_min'].GetValue()), np.int16(det['ROI_Thresh_Panel']['ROI_max'].GetValue())] #Update detecotor data shape det['Data'] = np.empty((self.number_shots, det['Det'].ROI[1] - det['Det'].ROI[0])) def destroy_plots(self): self.figsizer.ShowItems(False) for i in range(0,len(self.figsizer.GetChildren())): a = self.figsizer.Remove(0) self.figsizer.Layout() self.figsizer.Layout() dd = self.detectors[0] def update_plots(self): self.get_batch() for i,detector in enumerate(self.detectors): if detector['Plot'] is not None: detector['Plot'].clear() detector['Plot'].set_title(detector['Det'].detector_name +" - " +detector['Det'].channel_name, fontsize = 10) for i in range(0,np.min((self.number_shots, 5))): detector['Plot'].plot(np.arange(detector['Det'].ROI[0], detector['Det'].ROI[1]), detector['Data'][i]) detector['Plot'].plot(np.arange(detector['Det'].ROI[0], detector['Det'].ROI[1]), detector['Data'].mean(0)) detector['Plot'].draw() if detector['Hist'] is not None: detector['Hist'].clear() if detector['Det'].detector_shape == 1: hist_y, bins = np.histogram(detector['Data'].sum(1), bins = 100) else: hist_y, bins = np.histogram(detector['Data'], bins = 100) detector['Hist'].set_title(detector['Det'].detector_name +" - " +detector['Det'].channel_name, fontsize = 10) detector['Hist'].plot(bins[:-1], hist_y) if detector['Det'].intensity_threshold is not None: detector['Hist'].vlines(detector['Det'].intensity_threshold[0], hist_y.min(), hist_y.max(),'r') detector['Hist'].vlines(detector['Det'].intensity_threshold[1], hist_y.min(), hist_y.max(),'r') detector['Hist'].set_xlim([bins[:-1][0], bins[:-1][-1]]) detector['Hist'].draw() def get_batch(self): # bsstream.flush() ## Step many times in case missing shots for i in range(0,10): self.BSstep() self.scannable_static = True self.scannable_values = [] for i in range(0, self.number_shots): for detector in self.detectors: detector['Data'][i] = detector['Det'].get_processed_channel() print(self.get_scannable_value()) self.scannable_values.append(self.get_scannable_value()) self.BSstep() #Check if pv have changed within acquisition: g = groupby(self.scannable_values) self.scannable_static = next(g, True) and not next(g, False) # print(self.scannable_values, self.scannable_static) def BSstep(self): next(bsstream) def BSstop(self): bsstream.stop() # bsstream.flush() def connect_scannable_BS(self): self.scannable_val = BS(self.scannable_channel) def get_scannable_value(self): return self.scannable_val.get() class Detector: def __init__(self, detector_name, channel_name, ROI = None, projection = None, intensity_threshold = None, detector_shape = 1, plot = False, plot_wx = None): self.detector_name = detector_name self.channel_name = channel_name #Shape of data : 0 for singe value, 1 for array, and 2 for images. self.detector_shape = detector_shape # ROI: None for data shape 0, [a,b] for array data, and [a,b,c,d] for 2d self.ROI = ROI self.intensity_threshold = intensity_threshold # describe projection self.projection = projection self.connect_to_stream() self.plot = plot self.data def connect_to_stream(self): self.channel = BS(self.channel_name) #get first datapoint to establish shape spec = self.get_processed_channel() if spec.shape == (): self.detector_shape = 0 else: self.detector_shape = 1 #currently no 2d detectors available. self.ROI = [0, len(spec)] def get_processed_channel(self): self.data = self.channel.get() if self.ROI: self.data = self.data[self.ROI[0]:self.ROI[1]] # if self.projection: self.data = self.data.sum() return self.data def get_raw_channel(self): self.data = self.channel.get() return self.data # Standard analyzer: rolling over time with time stamps on the figure # Stepping analyzer: accumelates until new step, with step position of the PV on the plot # Histograming analyzer: histogram over specific steps excluding while moving. # Time tool analyzer: apply corrections/exclusion # XAS with correction. # each analyzer contains: # analyzer name # data manager: signal, i01, i02, TT and scannable # data manager: number of shots processed and queue length # parent and sizer #fucntions: # update plot # destroy plots # counter # Create queue # get thresholds # populate data # Create plots def destroy_plots_function(sizer): sizer.ShowItems(False) for i in range(0,len(sizer.GetChildren())): a = sizer.Remove(0) sizer.Layout() sizer.Layout() class Analyzer: def __init__(self, analyzer_name, datamanager, sizer): self.analyzer_name = analyzer_name #inherit datamanager conditions and detectors self.datamanager = datamanager self.signal = self.datamanager.detectors[0] self.I01 = self.datamanager.detectors[1] self.I02 = self.datamanager.detectors[2] self.scannable_pv = self.datamanager.scannable_pv self.figsizer = sizer self.wxparent = self.datamanager.wxparent self.queue_length = self.datamanager.queue_length self.number_shots = self.datamanager.number_shots self.max_entries = 3 #Create deque to start filling data self.create_deque() self.counter = 0 self.plot, self.box_items = self.create_plots() def create_deque(self): self.map = deque(maxlen=self.queue_length) self.stat = deque(maxlen=self.queue_length) self.stat_thresh = deque(maxlen=self.queue_length) self.pv_positions = deque(maxlen=self.queue_length) self.temp_spec = deque(maxlen=self.max_entries) self.temp_I01 = deque(maxlen=self.max_entries) self.temp_I02 = deque(maxlen=self.max_entries) self.temp_scannable = deque(maxlen=self.max_entries) def get_thresholds(self): self.signal_thresholds = self.signal['Det'].intensity_threshold if self.signal_thresholds is None or self.signal_thresholds == [0,0]: self.signal_thresholds = [-np.inf, np.inf] self.I01_thresholds = self.I01['Det'].intensity_threshold if self.I01_thresholds is None or self.I01_thresholds == [0,0]: self.I01_thresholds = [-np.inf, np.inf] self.I02_thresholds = self.I02['Det'].intensity_threshold if self.I02_thresholds is None or self.I02_thresholds == [0,0]: self.I02_thresholds = [-np.inf, np.inf] self.signal_thresholds.sort() self.I01_thresholds.sort() self.I02_thresholds.sort() def populate_data(self): # print(self.current_scan_val, self.last_scan_val) if self.counter > self.max_entries: #clean data: temp_signal = np.vstack(np.squeeze(self.temp_spec)) temp_I01 = np.vstack(np.squeeze(self.temp_I01)) temp_I02 = np.vstack(np.squeeze(self.temp_I02)) temp_scannable = np.vstack(np.squeeze(self.temp_scannable)) #Clear lists: self.temp_spec.clear() self.temp_I01.clear() self.temp_I02.clear() self.temp_scannable.clear() #get thresholds: self.get_thresholds() signal_int = temp_signal.sum(1) if len(temp_I01.shape) > 1: I01_int = temp_I01.sum(1) else: I01_int = temp_I01 if len(temp_I02.shape) > 1: I02_int = temp_I02.sum(1) else: I02_int = temp_I02 mask_signal = (signal_int > self.signal_thresholds[0]) & (signal_int < self.signal_thresholds[1]) mask_I01 = (I01_int > self.I01_thresholds[0]) & (I01_int < self.I01_thresholds[1]) mask_I02 = (I02_int > self.I02_thresholds[0]) & (I02_int < self.I02_thresholds[1]) mask_full = mask_signal & mask_I01 & mask_I02 # print(mask_full.sum()) if mask_full.sum()>0: self.map.append(temp_signal[mask_full].sum(0)/mask_full.sum()) self.stat.append(mask_full.sum()) self.pv_positions.append(temp_scannable[mask_full].mean()) self.counter = 0 else: #Get parameters: self.counter += self.number_shots # print(self.signal['Data'].shape) self.temp_spec.append(self.signal['Data']) self.temp_I01.append(self.I01['Data']) self.temp_I02.append(self.I02['Data']) self.temp_scannable.append(self.datamanager.scannable_values) def destroy_plots(self): destroy_plots_function(self.figsizer) def create_plots(self, detector_shape = 1, roi_value = [0,100], figsize = (4,4), border = 10): if detector_shape == 1: #Create plots plot = PlotPanel(self.wxparent, figsize=figsize) #Roi buttons for data text_min, textctrl_min = create_text_entry(self.wxparent, text = 'ROI min', setvalue = roi_value[0]) text_max, textctrl_max = create_text_entry(self.wxparent, text = 'ROI max', setvalue = roi_value[1]) btn_ROI_update = wx.Button(self.wxparent, label="Update ROI") # btn_ROI_update.Bind(wx.EVT_BUTTON, self.update_ROIs_btns) minbox = make_filled_vbox((text_min, textctrl_min)) maxbox = make_filled_vbox((text_max, textctrl_max)) roibox = make_filled_hbox((minbox, maxbox, btn_ROI_update)) box_items = { 'ROI_min': textctrl_min, 'ROI_max': textctrl_max, 'ROI_Set_Btn': btn_ROI_update, } hb_plot1 = make_filled_vbox((plot,roibox)) self.figsizer.Add(hb_plot1, 0, wx.ALL, border ) self.figsizer.Layout() return plot, box_items def update_plot(self): npmap = np.squeeze(self.map) if len(npmap.shape) > 1: self.plot.clear() self.plot.set_title( self.signal['Det'].detector_name +" vs " +self.scannable_pv.pvname, fontsize = 10) self.plot.imshow(npmap, aspect = 'auto') y_labels = [str('%0.3f'%i) for i in np.squeeze(self.pv_positions)] labels = y_labels[::10] self.plot.set_yticks(list(np.arange(0,len(y_labels)))[::10]) self.plot.set_yticklabels(labels) self.plot.set_ylabel(self.scannable_pv.pvname + " [%s]"%self.scannable_pv.units, fontsize = 10) self.plot.draw() class Analyzer_Histogram: def __init__(self, analyzer_name, datamanager, sizer): self.analyzer_name = analyzer_name #inherit datamanager conditions and detectors self.datamanager = datamanager self.signal = self.datamanager.detectors[0] self.I01 = self.datamanager.detectors[1] self.I02 = self.datamanager.detectors[2] self.scannable_pv = self.datamanager.scannable_pv self.hist_vals = self.datamanager.histogram # print(self.hist_vals) self.figsizer = sizer self.wxparent = self.datamanager.wxparent self.queue_length = self.datamanager.queue_length self.number_shots = self.datamanager.number_shots #Create deque to start filling data self.create_map() self.counter = 0 self.plot, self.box_items = self.create_plots() def create_map(self): self.hist_steps = np.arange(self.hist_vals['start'], self.hist_vals['end'], self.hist_vals['step']) self.map = np.zeros((self.hist_steps.shape[0], self.signal['Data'][0].shape[0] )) self.bin_counts = np.zeros_like(self.hist_steps) self.bkg = np.zeros_like(self.signal['Data'][0]) self.bkg_count = 0 self.bkg_flag = self.hist_vals['subtract_bkg'] self.bkg_bounds = [self.hist_vals['bkg_start'], self.hist_vals['bkg_end']] self.bkg_bounds.sort() def get_thresholds(self): self.signal_thresholds = self.signal['Det'].intensity_threshold if self.signal_thresholds is None or self.signal_thresholds == [0,0]: self.signal_thresholds = [-np.inf, np.inf] self.I01_thresholds = self.I01['Det'].intensity_threshold if self.I01_thresholds is None or self.I01_thresholds == [0,0]: self.I01_thresholds = [-np.inf, np.inf] self.I02_thresholds = self.I02['Det'].intensity_threshold if self.I02_thresholds is None or self.I02_thresholds == [0,0]: self.I02_thresholds = [-np.inf, np.inf] self.signal_thresholds.sort() self.I01_thresholds.sort() self.I02_thresholds.sort() def populate_data(self): #Get data from datamanager: temp_spec = self.signal['Data'] temp_I01 = self.I01['Data'] temp_I02 = self.I02['Data'] temp_scannable = self.datamanager.scannable_values temp_scannable_static_flag = self.datamanager.scannable_values self.get_thresholds() #if scannable did not move in the last acquisition, use the data, else skip! if temp_scannable_static_flag: signal_int = temp_spec.sum(1) if len(temp_I01.shape) > 1: I01_int = temp_I01.sum(1) else: I01_int = temp_I01 if len(temp_I02.shape) > 1: I02_int = temp_I02.sum(1) else: I02_int = temp_I02 mask_signal = (signal_int > self.signal_thresholds[0]) & (signal_int < self.signal_thresholds[1]) mask_I01 = (I01_int > self.I01_thresholds[0]) & (I01_int < self.I01_thresholds[1]) mask_I02 = (I02_int > self.I02_thresholds[0]) & (I02_int < self.I02_thresholds[1]) mask_full = mask_signal & mask_I01 & mask_I02 scannable_mean = np.mean(temp_scannable) # find index in histogram, we find closest point in histgram steps: idx = np.argmin(np.abs(scannable_mean - self.hist_steps)) self.map[idx,:] += temp_spec[mask_full].sum(0) self.bin_counts[idx] += mask_full.sum() if self.bkg_flag and scannable_mean > self.bkg_bounds[0] and scannable_mean < self.bkg_bounds[1]: self.bkg_count += mask_full.sum() self.bkg += temp_spec[mask_full].sum(0) else: print("PV changing") # hist_variables = { # 'start': np.double(self.scan_start_hist.GetValue()).item(), # 'end': np.double(self.scan_end_hist.GetValue()).item(), # 'step': np.double(self.time_step_hist.GetValue()).item(), # 'bkg_start': np.double(self.scan_bkg_start.GetValue()).item(), # 'bkg_end': np.double(self.scan_bkg_end.GetValue()).item(), # 'subtract_bkg': self.histogram_background_checkbox_text.GetValue(), # } def destroy_plots(self): destroy_plots_function(self.figsizer) def create_plots(self, detector_shape = 1, roi_value = [0,100], figsize = (4,4), border = 10): if detector_shape == 1: #Create plots plot = PlotPanel(self.wxparent, figsize=figsize) #Roi buttons for data text_min, textctrl_min = create_text_entry(self.wxparent, text = 'ROI min', setvalue = roi_value[0]) text_max, textctrl_max = create_text_entry(self.wxparent, text = 'ROI max', setvalue = roi_value[1]) btn_ROI_update = wx.Button(self.wxparent, label="Update ROI") # btn_ROI_update.Bind(wx.EVT_BUTTON, self.update_ROIs_btns) minbox = make_filled_vbox((text_min, textctrl_min)) maxbox = make_filled_vbox((text_max, textctrl_max)) roibox = make_filled_hbox((minbox, maxbox, btn_ROI_update)) box_items = { 'ROI_min': textctrl_min, 'ROI_max': textctrl_max, 'ROI_Set_Btn': btn_ROI_update, } hb_plot1 = make_filled_vbox((plot,roibox)) self.figsizer.Add(hb_plot1, 0, wx.ALL, border ) self.figsizer.Layout() return plot, box_items def update_plot(self): #process map before plotting: temp_map = np.zeros_like(self.map) for i,val in enumerate(self.bin_counts): if val >1: temp_map[i,:] = self.map[i,:]/val if self.bkg_flag and self.bkg_count > 10: temp_map[i,:] = temp_map[i,:] - self.bkg/self.bkg_count self.plot.clear() self.plot.set_title( self.signal['Det'].detector_name +" vs " +self.scannable_pv.pvname, fontsize = 10) extent = (0, len(temp_map[0,:]), self.hist_steps[-1], self.hist_steps[0]) self.plot.imshow(temp_map, aspect = 'auto', extent = extent) self.plot.set_ylabel(self.scannable_pv.pvname + " [%s]"%self.scannable_pv.units, fontsize = 10) self.plot.draw()