def sendPlots(x_proj_sum, image_sum, counts_buff, counts_buff_regint, opal_image, hist_L3PhotEnergy, \ hist_FeeGasEnergy, nevt, numshotsforacc): # Define plots plotxproj = XYPlot(nevt,'Accumulated electron spectrum over past '+\ str(numshotsforacc)+' good shots', \ np.arange(x_proj_sum.shape[0]), x_proj_sum) plotcumimage = Image( nevt, 'Accumulated sum (' + str(numshotsforacc) + ' good shots)', image_sum) plotcounts = XYPlot(nevt,'Estimated number of identified electron counts over past '+ \ str(len(counts_buff))+' good shots', np.arange(len(counts_buff)), \ np.array(counts_buff)) plotcountsregint = XYPlot(nevt,'Estimated number of identified electron counts over past '+ \ str(len(counts_buff_regint))+' good shots in region '+str(np.round(region_int_lower_act,2))+\ ' eV - '+str(np.round(region_int_upper_act,2))+' eV (inclusive)', \ np.arange(len(counts_buff_regint)), np.array(counts_buff_regint)) plotshot = Image(nevt, 'Single shot', opal_image) plotL3PhotEnergy = Hist(nevt,'Histogram of L3 \'central\' photon energies (plotting for '+str(np.round(min_cent_pe, 2))+\ '- '+str(np.round(min_cent_pe, 2))+')', hist_L3PhotEnergy.edges[0], \ np.array(hist_L3PhotEnergy.values)) plotFeeGasEnergy = Hist(nevt,'Histogram of FEE gas energy (plotting for above '+str(np.round(fee_gas_threshold, 2))+\ ' only)', hist_FeeGasEnergy.edges[0], np.array(hist_FeeGasEnergy.values)) # Publish plots publish.send('AccElectronSpec', plotxproj) publish.send('OPALCameraAcc', plotcumimage) publish.send('ElectronCounts', plotcounts) publish.send('ElectronCountsRegInt', plotcountsregint) publish.send('OPALCameraSingShot', plotshot) publish.send('L3Histogram', plotL3PhotEnergy) publish.send('FEEGasHistogram', plotFeeGasEnergy)
def CurvatureMain(): # We will probably do this in ipython notebook # Otherwise here we can run it # Read input file filename = "./UXSAlign/0.out.accimage" print "Reading {}".format(filename) image = readImage(filename) uxspre = UXSDataPreProcessing(image.copy()) uxspre.CalculateProjection() uncorrspectrum = uxspre.wf # Produce curvaturecorrection zippdxy = CurvatureFinder(image) xshifts = CreateXshifts(zippdxy) # Monkey path the correction uxspre.xshifts = xshifts uxspre.CorrectImageGeometry() uxspre.CalculateProjection() # Plot difference with and without calibration multi = MultiPlot(0, "UXSCalibration {}".format(filename), ncols=2) image = AddCurvLine(image, xshifts) uncorrimage = Image(0, "Uncorrected", image) multi.add(uncorrimage) corrimage = Image(0, "Corrected", uxspre.image) multi.add(corrimage) uncorrspec = XYPlot(0, "Uncorrected", range(len(uncorrspectrum)), uncorrspectrum) multi.add(uncorrspec) corrspec = XYPlot(0, "Corrected", range(len(uxspre.wf)), uxspre.wf) multi.add(corrspec) for i in range(10): publish.send("UXSCalibration", multi) saveXshifts(filename, xshifts) print "fin"
def publish_corr_plots(self): """Publish correlation plots between x and y """ # Make MultiPlot to hold correlation plots plots_title = ''.join( [self.x_name, ' Vs ', self.y_name, ' Correlation Plots']) corr_plots = MultiPlot(plots_title, plots_title, ncols=3) # Make scatter plot scat_plot_title = ''.join( [self.y_name, ' Vs ', self.x_name, ' Scatter Plot']) scat_plot_text = ''.join([ 'Pearson: ', str(format(self.pearson, '.3f')), ' Update Pearson: ', str(format(self.upd_pearson, '.3f')), '\n SNR: ', str(format(self.snr, '.3f')), ' Update SNR: ', str(format(self.upd_snr, '.3f')) ]) scat_plot = XYPlot(scat_plot_text, scat_plot_title, np.copy(self.upd_x_data), np.copy(self.upd_y_data), xlabel=self.x_name, ylabel=self.y_name, formats='b.') # Make linearity plot lin_data = self._linearity_data(self.upd_x_data, self.upd_y_data) lin_plot_title = ''.join( [self.y_name, ' Vs ', self.x_name, ' Linearity Plot']) lin_plot_text = 'Red is Binned Data, Green is Linear Fit' lin_plot = XYPlot(lin_plot_text, lin_plot_title, [lin_data['x_avgs'], lin_data['x_avgs']], [lin_data['lin_y_vals'], lin_data['y_avgs']], xlabel=self.x_name, ylabel=self.y_name, formats=['g-', 'r-']) # Make histogram plot using filtered data filt_idx = self._filt_idx(self.upd_x_data, self.perc_too_high, self.perc_too_low) x_filt = self.upd_x_data[filt_idx] y_filt = self.upd_y_data[filt_idx] norm_data = y_filt / x_filt norm_data = norm_data / np.average(norm_data, weights=x_filt) hist_data, hbin_edges = np.histogram(norm_data, bins=20, weights=x_filt) hbin_centers = (hbin_edges[1:] + hbin_edges[:-1]) / 2 hist_plot_title = ''.join( [self.y_name, ' Normalized by ', self.x_name, ' Histogram']) hist_plot = Hist('', hist_plot_title, hbin_edges, hist_data) # Add created plots to plot list corr_plots.add(scat_plot) corr_plots.add(lin_plot) corr_plots.add(hist_plot) publish.send(self.plots_name, corr_plots)
def my_smalldata(data_dict): # one core gathers all data from mpi workers global numevents, lastimg, numendrun, mydeque if 'endrun' in data_dict: numendrun += 1 if numendrun == numworkers: print('Received endrun from all workers. Resetting data.') numendrun = 0 numevents = 0 mydeque = deque(maxlen=25) return numevents += 1 if 'opal' in data_dict: lastimg = data_dict['opal'] mydeque.append(data_dict['opalsum']) if numevents % 100 == 0: # update plots around 1Hz print('event:', numevents) myxyplot = XYPlot(numevents, "Last 25 Sums", np.arange(len(mydeque)), np.array(mydeque), formats='o') publish.send("OPALSUMS", myxyplot) if lastimg is not None: # opal image is not sent all the time myimgplot = Image(numevents, "Opal Image", lastimg) publish.send("OPALIMG", myimgplot)
def plot_acqiris(detectorObject, thisEvent): selfName = detectorObject['self_name'] y = detectorObject[selfName](thisEvent)[0][1] if (None != y): to_plot = XYPlot(time.time(), "x vs y", arange(len(y)), y) publish.send('my_plot', to_plot)
def plot_acqiris_mpi(detectorObject, thisEvent): nevent = detectorObject['event_number'] comm = detectorObject['myComm'] rank = detectorObject['rank'] selfName = detectorObject['self_name'] y = detectorObject[selfName](thisEvent)[0][1] all_traces = {} all_traces[rank] = y if (sum(y) > -430): gatheredSummary = comm.gather(y, root=0) else: gatheredSummary = comm.gather(zeros([15000]), root=0) if rank == 0: for i in gatheredSummary: try: to_plot = XYPlot(time.time(), "x vs y", arange(len(i)), i) publish.send('my_plot', to_plot) print(sum(i)) except: pass print(len(gatheredSummary))
def publish_traces(self): # Calculate accumulated absorptions: abs_lon_mp = -np.log( self.lon_hists['signal_mp'] / self.lon_hists['norm_mp']) abs_lon_mm = -np.log( self.lon_hists['signal_mm'] / self.lon_hists['norm_mm']) abs_loff_mp = -np.log( self.loff_hists['signal_mp'] / self.loff_hists['norm_mp']) abs_loff_mm = -np.log( self.loff_hists['signal_mm'] / self.loff_hists['norm_mm']) # Make MultiPlot to hold plots: plots_title = 'XMCD Scan' xmcd_plots = MultiPlot(plots_title, plots_title, ncols=3) # Make traces plot: trace_plot_title = 'XAS Traces' trace_plot = XYPlot(trace_plot_title, trace_plot_title, [self.bin_edges[1:], self.bin_edges[1:]], [(abs_lon_mp + abs_lon_mm) / 2, (abs_loff_mm + abs_loff_mp) / 2], xlabel=self.scan_key) # Make laser on/laser off difference plots: diff_plot_title = 'XMCD Traces' diff_plot = XYPlot(diff_plot_title, diff_plot_title, [self.bin_edges[1:], self.bin_edges[1:]], [(abs_lon_mp - abs_lon_mm), (abs_loff_mp - abs_loff_mm)], xlabel=self.scan_key) # Make histogram plot of amounts of data collected norm_title = 'Normalization signal sums' norm_plot = XYPlot( norm_title, norm_title, [ self.bin_edges[1:], self.bin_edges[1:], self.bin_edges[1:], self.bin_edges[1:] ], [ self.lon_hists['norm_mp'], self.lon_hists['norm_mm'], self.loff_hists['signal_mp'], self.loff_hists['signal_mm'] ], xlabel=self.scan_key) # Update plots: xmcd_plots.add(trace_plot) xmcd_plots.add(diff_plot) xmcd_plots.add(norm_plot) publish.send('xmcd_plots', xmcd_plots)
def DebugPlot(x, y, title): """ Publishes a debugspectrum """ from psmon.plots import Image,XYPlot, MultiPlot from psmon import publish #publish.local = True plot = XYPlot(0, title, x, y) publish.send("UXSDebug", plot)
def update(self,md): self.nupdate+=1 if self.spectrumsum is None: self.spectrumsum = md.spectrumsum self.roisum = md.roisum self.nevents = md.small.nevents self.nevents_on_off = md.nevents_on_off else: self.spectrumsum += md.spectrumsum self.roisum += md.roisum self.nevents += md.small.nevents self.nevents_on_off += md.nevents_on_off self.avgroisum = self.roisum/self.nevents self.deque.append(md.spectrumsum[0,:]+md.spectrumsum[1,:]) # lasing on and off if self.nupdate%updaterate==0: print('Client updates',self.nupdate,'Master received events:',self.nevents) if self.lasttime is not None: print('Rate:',(self.nevents-self.lastnevents)/(time.time()-self.lasttime)) self.lasttime = time.time() self.lastnevents = self.nevents spectrum_recent = None for entry in self.deque: if spectrum_recent is None: spectrum_recent=entry else: spectrum_recent+=entry spectrum_on_plot = XYPlot(self.nupdate,"Spectrum On",np.arange(md.spectrumsum.shape[1]),self.spectrumsum[0,:]) publish.send('SPECTRUM_ON',spectrum_on_plot) spectrum_off_plot = XYPlot(self.nupdate,"Spectrum Off",np.arange(md.spectrumsum.shape[1]),self.spectrumsum[1,:]) publish.send('SPECTRUM_OFF',spectrum_off_plot) spectrum_diff_plot = XYPlot(self.nupdate,"Spectrum Diff",np.arange(md.spectrumsum.shape[1]),self.spectrumsum[0,:]*self.nevents_on_off[1]-self.spectrumsum[1,:]*self.nevents_on_off[0]) publish.send('SPECTRUM_DIFF',spectrum_diff_plot) spectrum_recent_plot = XYPlot(self.nupdate,"Recent Spectrum",np.arange(md.spectrumsum.shape[1]),spectrum_recent) publish.send('RECENT_SPECTRUM',spectrum_recent_plot) roi_plot = Image(self.nupdate,"Epix ROI",self.avgroisum) publish.send('EPIX_ROI',roi_plot)
def CallBack(evt_dict): global dat,t0,t500,num img = Image(0,'atm',evt_dict['atm']) xy = XYPlot(0,'atm_proj',range(len(evt_dict['atm_proj'])),evt_dict['atm_proj']) publish.local = True publish.send('ATM',img) publish.send('ATMP',xy) num += 1 if num==500: t500 = time.time() elif num>500: print('t500:',t500-t0,'num:',num,'rank:',evt_dict['rank'],'tstamp:',evt_dict['tstamp'],'index:',evt_dict['index']) #dat.append(evt_dict['evr']) else: print('num:',num,'rank:',evt_dict['rank'],'tstamp:',evt_dict['tstamp'],'index:',evt_dict['index'])
def __init__(self, topic, title=None, xlabel=None, ylabel=None, format='-', pubrate=None, publisher=None): super(XYPlotHelper, self).__init__(topic, title, pubrate, publisher) self.index = 0 self.xdata = np.zeros(XYPlotHelper.DEFAULT_ARR_SIZE) self.ydata = np.zeros(XYPlotHelper.DEFAULT_ARR_SIZE) self.data = XYPlot(None, self.title, None, None, xlabel=xlabel, ylabel=ylabel, formats=format)
def __init__(self, topic, npoints, title=None, xlabel=None, ylabel=None, format='-', pubrate=None, publisher=None): super(StripHelper, self).__init__(topic, title, pubrate, publisher) self.index = 0 self.npoints = npoints self.xdata = np.arange(npoints) self.ydata = np.zeros(npoints) self.data = XYPlot(None, self.title, None, None, xlabel=xlabel, ylabel=ylabel, formats=format)
outline="white") # AAi dr.rectangle(((600, 100), (800, 200)), fill=DV_color, outline="white") # DV dr.text((20, 50), BTEMP, font=font) dr.text((220, 50), ATEMP, font=font) dr.text((420, 50), HU, font=font) dr.text((620, 50), AAi, font=font) dr.text((20, 150), ADi, font=font) dr.text((220, 150), DET, font=font) dr.text((420, 150), AV, font=font) dr.text((620, 150), DV, font=font) npimg = np.array(im) npimg = npimg[:, :, 1] # print(npimg.shape) img0 = ii(0, "epix10ka_env", npimg) publish.send('IMAGE0', img0) detplotxy = XYPlot(0, "dr", range(NUMEVT), envs_u[2, :]) publish.send('dr', detplotxy) huplotxy = XYPlot(0, "hu", range(NUMEVT), envs_s[2, :]) publish.send('hu', huplotxy) sbplotxy = XYPlot(0, "sb", range(NUMEVT), envs_s[0, :]) publish.send('sb', sbplotxy) # raw_input('Hit <CR> for next event') # raw_input('Hit <CR> for next event') # if nevent >= 2: # break
numbins_L3EnergyWeighted=100 minhistlim_L3EnergyWeighted=3300 maxhistlim_L3EnergyWeighted=3400 hist_L3_elec1mom = Histogram((numbins_L3_elec1mom_L3,minhistlim_L3_elec1mom_L3,\ mmaxhistlim_L3_elec1mom_L3),(numbins_L3_elec1mom_elec1mom,\ minhistlim_L3_elec1mom_elec1mom,maxhistlim_L3_elec1mom_elec1mom)) hist_L3Energy=Histogram((numbins_L3Energy,minhistlim_L3Energy,maxhistlim_L3Energy)) hist_L3EnergyWeighted=Histogram((numbins_L3EnergyWeighted,minhistlim_L3EnergyWeighted,maxhistlim_L3EnergyWeighted)) for nevt, evt in enumerate(ds.events()): print nevt energyL3=procL3Energy.L3Energy(evt) moments, numhits=procSHES.CalibProcess(evt, inPix=True) mom1=moments[0] hist_L3Energy.fill(energyL3) hist_L3EnergyWeighted.fill([energyL3], weights=[numhits]) if nevt>100: break avShotsPerL3Energy=hist_L3EnergyWeighted/np.float(hist_L3Energy.values) L3_weighted_plot = XYPlot(nevt, 'L3_weighted', hist_L3EnergyWeighted.centers[0], hist_L3EnergyWeighted.values) publish.send('L3 weighted', L3_weighted_plot)
print 'No SHES image, continuing to next event' continue if arced: print '***WARNING - ARC DETECTED!!!***' cv2.putText(opal_image, 'ARCING DETECTED!!!', (50, int(i_len / 2)), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 10) cv2.putText(image_sum, 'ARCING DETECTED!!!', (50, int(i_len / 2)), cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 0, 0), 10) #%% Now send plots (only counts updated from last time) and wait 2 seconds # Define plots plotxproj = XYPlot(0,'Accumulated electron spectrum over past '+\ str((len(x_proj_sum_buff)-1)*plot_every)+ \ ' shots', np.arange(x_proj_sum.shape[0]), x_proj_sum) plotcumimage = Image(0, 'Accumulated sum', image_sum) plotcounts = XYPlot(0,'Estimated number of identified electron counts over past '+ \ str(len(counts_buff))+' shots', np.arange(len(counts_buff)), \ np.array(counts_buff)) plotshot = Image(0, 'Single shot', opal_image) multi = MultiPlot(0, 'Multi', ncols=2) multi.add(plotcounts) multi.add(plotshot) multi.add(plotxproj) multi.add(plotcumimage) # Publish plots
""" # Send single plots #plotimglive = Image(0, "UXS Monitor Live image {} {}Hz {}".format(frameidx, speed, metadata[frameidx]), uxspre.image) #plotimgacc = Image(0, "UXS Monitor Accumulated image {} {}Hz {}".format(frameidx, speed, metadata[frameidx]), summedimage) #plotxylive = XYPlot(0, "UXS Monitor Live Spectrum {}".format(metadata[frameidx]), range(1024), uxspre.wf) #plotxyacc = XYPlot(0, "UXS Monitor Accumulated Spectrum {}".format(metadata[frameidx]), range(1024), summedspectrum) #publish.send("UXSMonitorLive", plotimglive) #publish.send("UXSMonitorAcc", plotimgacc) #publish.send("UXSMonitorLiveSpectrum", plotxylive) #publish.send("UXSMonitorAccSpectrum", plotxy) # Send a multiplot plotimglive = Image(0, "Live", uxspre.image) plotimgacc = Image(0, "Acc", accimage) plotxylive = XYPlot(0, "Live", energyscale, spectrum) plotxyacc = XYPlot(0, "Acc", energyscale, accspectrum) ###plotxyfit = XYPlot(0, "Fit", energyscale, fity) multi = MultiPlot(0, "UXSMonitor {} Hz {}".format(speed, metadata[frameidx]), ncols=2) multi.add(plotimglive) multi.add(plotimgacc) multi.add(plotxylive) multi.add(plotxyacc) ###multi.add(plotxyfit) publish.send("UXSMonitor", multi) # Count rate evolution over the frames. #counts = np.sum(images, axis=(0,1)) #counts = np.roll(counts, -frameidx) #counts = scipy.ndimage.gaussian_filter1d(counts,1)
if not accepted: continue print cspad_tbx.evt_timestamp( cspad_tbx.evt_time(evt)), "Publishing data for event", i #header = "Event %d, m/f: %7.7f, f: %d"%(i, peak_max/flux, flux) header = "Event %d" % (i) if rank == 0: fee = Image(header, "FEE", data) # make a 2D plot publish.send("FEE", fee) # send to the display spectrumplot = XYPlot(header, 'summed 1D trace', range(data.shape[1]), spectrum) # make a 1D plot publish.send("SPECTRUM", spectrumplot) # send to the display fee = Image(header, "DC_OFFSET", dc_offset) # make a 2D plot publish.send("DC_OFFSET", fee) # send to the display fee = Image(header, "ALL_FEE", all_data) # make a 2D plot publish.send("ALL_FEE", fee) # send to the display fee = Image(header, "ALL_FEE_RAW", all_data_raw) # make a 2D plot publish.send("ALL_FEE_RAW", fee) # send to the display if __name__ == "__main__": run(sys.argv[1:])
if rank == 0: # initilisation for the root core only publish.init() # for plotting ref_time = time.time() # for estimating rate of data acquisition print 'Monitoring counts in region between ' +str(np.round(roi_lower_act,2))+\ ' eV - '+str(np.round(roi_upper_act,2))+' eV' if rem_a != 0: print 'For efficient monitoring of accumulated electron spectra require history_len divisible by \ refresh_rate*size, set history_len to ' + str(history_len) #%% Define plotting function def definePlots(x_proj_sum, image_sum, counts_buff, counts_buff_roi, opal_image, (hist_L3PhotEnergy, \ hist_L3PhotEnergy_edges), (hist_FeeGasEnergy, hist_FeeGasEnergy_edges), (hist_FeeGasEnergy_CountsROI, hist_FeeGasEnergy_CountsROI_edges), nevt, numshotsforacc,\ good_shot_count_pcage): # Define plots plotxproj = XYPlot(nevt,'Accumulated electron spectrum from good shots ('+str(np.round(good_shot_count_pcage, 2))+\ '%) over past '+str(numshotsforacc)+' shots', calib_array, x_proj_sum) plotcumimage = Image(nevt, 'Accumulated sum of good shots ('+str(np.round(good_shot_count_pcage, 2))+\ '%) over past '+str(numshotsforacc)+' shots', image_sum) plotcounts = XYPlot(nevt,'Estimated number of identified electron counts over past '+ \ str(len(counts_buff))+' shots', np.arange(len(counts_buff)), np.array(counts_buff)) plotcountsregint = XYPlot(nevt,'Estimated number of identified electron counts in region '+\ str(np.round(roi_lower_act,2))+' eV - '+\ str(np.round(roi_upper_act,2))+' eV (inclusive) over past '+ \ str(len(counts_buff_roi))+' shots', \ np.arange(len(counts_buff_roi)), np.array(counts_buff_roi)) opal_image[:, roi_idx_lower - 3:roi_idx_lower - 1] = 900 opal_image[:, roi_idx_upper + 1:roi_idx_upper + 3] = 900 plotshot = Image(nevt, 'Single shot, ROI marked from '+str(np.round(roi_lower_act,2))+' eV - '+\ str(np.round(roi_upper_act,2))+' eV', opal_image) plotL3PhotEnergy = Hist(nevt,'Histogram of L3 \'central\' photon energies (getting electron data for '+str(np.round(min_cent_pe, 2))+\
def runmaster(nClients, pars, args): # get data source parameters expName = pars['expName'] runNum = args.run runString = 'exp=' + expName + ':run=' + runNum # get number of events between updates updateEvents = pars['updateEvents'] # expected delay nomDelay = args.delay # plotting things plotFormat = 'ro' xdata = np.zeros(updateEvents) ydata = np.zeros(updateEvents) # initialize plots # plot for pulse 1 vs pulse 2 amplitude Amplitudes = XYPlot(0, "Amplitudes", xdata, ydata, formats=plotFormat, xlabel='Pulse 1 amplitude', ylabel='Pulse 2 amplitude') publish.send("AMPLITUDES", Amplitudes) # plot for MCP trace and fit x1 = np.linspace(0, 2500, 20000) y1 = np.zeros(20000) x1 = [x1[12500:13500], x1[12500:13500]] y1 = [y1[12500:13500], y1[12500:13500] + 1] plotFormat = ['b-', 'r-'] legend = ['Raw', 'Fit'] Trace = XYPlot(0, "Trace", x1, y1, formats=plotFormat, leg_label=legend, xlabel='Time (ns)', ylabel='MCP Signal') publish.send("TRACE", Trace) # histogram of delays based on fit (to make sure fit is working) DelayHist = Hist(0, "Delay", np.linspace(nomDelay - 1.0, nomDelay + 1.0, 101), np.zeros(100), xlabel='Delay (ns)', ylabel='Number of Events') publish.send("DELAYHIST", DelayHist) # initialize arrays for plotting wf = np.zeros(20000) fit1 = np.zeros(20000) a1 = np.empty(0) a2 = np.empty(0) delay = np.empty(0) # keep plotting until all clients stop while nClients > 0: # Remove client if the run ended # # set up data receiving md = mpidata() # check which client we're receiving from rank1 = md.recv() # check if this client is finished if md.small.endrun: nClients -= 1 else: # add new data to arrays a1 = np.append(a1, md.a1) a2 = np.append(a2, md.a2) delay = np.append(delay, md.delay) wf = md.wf fit1 = md.fit # plot if we're receiving from the last client if rank1 == size - 1: # make histogram of delays hist1, bins = np.histogram(delay, bins=np.linspace( nomDelay - 5, nomDelay + 5, 101)) # update plots plot(Trace, x1, [wf[12500:13500], fit1[12500:13500]], md.small.event, "TRACE") plot(Amplitudes, a1, a2, md.small.event, "AMPLITUDES") histPlot(DelayHist, bins, hist1, md.small.event, "DELAYHIST") # re-initialize arrays a1 = np.empty(0) a2 = np.empty(0) delay = np.empty(0)
def publish(self, image=None, saxs=None, c2=None, ind=None, n_a=None, n_saxs=None, n_c2=None, n_i=None, n_q=None, n_bin=None): """Publish Intermediate results: @image Average image @saxs Averaged saxs data @c2 Averaged c2 data @ind Indexed data @n_a Nr of averaged images @n_saxs Nr of averaged saxs curves @n_c2 Nr of averaged c2 data @n_i Nr of indexed images @n_q Nr of q-rings to plot @n_bin Nr of bins for size histogram KEYWORDS FOR PLOTS AVE : Average image C2_IMAGE : Heat plot of C2 C2 : Individual C2 plots SAXS : Saxs curve IND : Index data ex: psplot -s psanaXXXX AVE C2 SAXS IND C2_IMAGE """ if n_q is None: n_q = min(15, len(self.q)) if n_q > len(self.q): # Ascert that there is enough q's n_q = len(self.q) if n_bin is None: n_bin = n_i / 10 if image is not None: # Average Image title = 'AVERAGE Run ' + str(self.run_nr) AVEimg = Image(n_a, title, image) publish.send('AVE', AVEimg) if saxs is not None: # SAXS plot title = 'SAXS Run ' + str(self.run_nr) SAXSimg = XYPlot(n_saxs, title, self.q, saxs, xlabel='q (1/A)', formats='b') publish.send('SAXS', SAXSimg) if c2 is not None: # C2 plots title = 'C2 Run ' + str(self.run_nr) # C2 heatmap plot C2img = Image(n_c2, title, c2) publish.send('C2_IMAGE', C2img) # Multiplot, plot C2 for 10 q-points multi = MultiPlot(n_c2, title, ncols=5) step = round(len(self.q) / (n_q + 1)) for p in range(n_q): R = XYPlot(n_c2, 'q = ' + str(np.around(self.q[(p + 1) * step], decimals=3)), self.phi, c2[(p + 1) * step], xlabel='dPhi') multi.add(R) publish.send('C2', multi) if ind is not None: if n_bin is None: n_bin = n_i / 10 # Last non-zero intensity nz = np.nonzero(ind[:, 0]) last = nz[0][-1] ind = ind[0:last, :] # Check if we manged to estimate sizes sind = ind[:, 2] > 0.98 if sind.any(): title = 'INDEX Run ' + str(self.run_nr) # INDEX plot multi2 = MultiPlot(n_i, title, ncols=1) # Intensity plot title = 'Intensity Run ' + str(self.run_nr) I = XYPlot(n_i, title, np.arange(last), ind[:, 0], xlabel='N', formats='rs') multi2.add(I) # Size plot title = 'Size Run ' + str(self.run_nr) diam = ind[sind, 1] * (2 / 10) # Diameter in nm hist, bins = np.histogram(diam, n_bin) S = Hist(n_i, title, bins, hist, xlabel='Size [nm]') multi2.add(S) publish.send('IND', multi2) else: title = 'Intensity Run ' + str(self.run_nr) I = XYPlot(n_i, title, np.arange(last), ind[:, 0], xlabel='N', formats='rs') publish.send('IND', I)
#print FEE_shot_energy if FEE_shot_energy is None or FEE_shot_energy < threshold: continue hist_L3Energy.fill(EBEAM_beam_energy) hist_L3EnergyWeighted.fill( [EBEAM_beam_energy], weights=[np.abs(wf[1][:10000].sum()) / FEE_shot_energy]) hist_L3EnergyWeighted_unnorm.fill([EBEAM_beam_energy], weights=[np.abs(wf[1][:10000].sum())]) if nevt % 500 == 0: print nevt multi = MultiPlot(nevt, 'MULTI') vShotsPerL3Energy = np.nan_to_num(hist_L3EnergyWeighted.values / hist_L3Energy.values) L3_weighted_plot = XYPlot(nevt, 'L3', hist_L3EnergyWeighted.centers[0], vShotsPerL3Energy) #publish.send('L3', L3_weighted_plot) multi.add(L3_weighted_plot) vShotsPerL3Energy_un = np.nan_to_num( hist_L3EnergyWeighted_unnorm.values / hist_L3Energy.values) L3_weighted_plot_un = XYPlot(nevt, 'L3UN', hist_L3EnergyWeighted.centers[0], vShotsPerL3Energy_un) #publish.send('L3UN', L3_weighted_plot_un) multi.add(L3_weighted_plot_un) publish.send('MULTI', multi) filename = "../npz/ana_itof_run_%d" % run np.savez(filename, vShotsPerL3Energy=vShotsPerL3Energy, vShotsPerL3Energy_un=vShotsPerL3Energy_un, hist_L3Energy_centers=hist_L3EnergyWeighted.centers[0])
#tssPublishedProfile = XYPlot(0,"TSS_OPAL_Profile",arange(len(tssCorrelation)),tssCorrelation) #publish.send('TSS_OPAL_Profile',tssPublishedProfile) #tssPublishedProfile = XYPlot(0,"TSS_OPAL_Profile",arange(len(byKickTssOpalProfile)),byKickTssOpalProfile) #publish.send('TSS_OPAL_Profile',tssPublishedProfile) try: tempCov = cov(tssProfile, byKickTssOpalProfile) temp = tssProfile - tempCov[0, 1] / tempCov[1, 1] * ( byKickTssOpalProfile - mean(byKickTssOpalProfile)) temp -= mean(temp) temp2 = (arange(len(temp)) - len(temp) / 2.0)**2 temp -= dot(temp, temp2) / dot(temp2, temp2) * temp2 if (nEvent % 5 == 1): tssPublishedProfile2 = XYPlot(0, "TSS_OPAL_Profile", arange(len(tssProfile)), temp) publish.send('TSS_OPAL_Profile', tssPublishedProfile2) except: print("skipping") #opal1PublishedProfile = XYPlot(0,"OPAL1_Profile",arange(len(opal1Correlation)),opal1Correlation) #publish.send('OPAL1_Profile',opal1PublishedProfile) try: temp = mean((opal1Image - byKickOpal1Image)[:73, :], axis=0) temp -= mean(temp) temp2 = mean(opal1Image[73:, :], axis=0) temp2 -= mean(temp2) #temp = temp - dot(temp,temp2)/dot(temp2,temp2)*temp2 #temp =
def run(args): user_phil = [] for arg in args: if os.path.isfile(arg): try: user_phil.append(parse(file_name=arg)) except Exception as e: print(str(e)) raise Sorry("Couldn't parse phil file %s" % arg) else: try: user_phil.append(parse(arg)) except Exception as e: print(str(e)) raise Sorry("Couldn't parse argument %s" % arg) params = phil_scope.fetch(sources=user_phil).extract() # cxid9114, source fee: FeeHxSpectrometer.0:Opal1000.1, downstream: CxiDg3.0:Opal1000.0 # cxig3614, source fee: FeeHxSpectrometer.0:OrcaFl40.0 src = psana.Source(params.spectra_filter.detector_address) dataset_name = "exp=%s:run=%s:idx" % (params.experiment, params.runs) print("Dataset string:", dataset_name) ds = psana.DataSource(dataset_name) spf = spectra_filter(params) if params.selected_filter == None: filter_name = params.spectra_filter.filter[0].name else: filter_name = params.selected_filter rank = 0 size = 1 max_events = sys.maxsize for run in ds.runs(): print("starting run", run.run()) # list of all events times = run.times() if params.skip_events is not None: times = times[params.skip_events:] nevents = min(len(times), max_events) # chop the list into pieces, depending on rank. This assigns each process # events such that the get every Nth event where N is the number of processes mytimes = [times[i] for i in range(nevents) if (i + rank) % size == 0] for i, t in enumerate(mytimes): evt = run.event(t) accepted, data, spectrum, dc_offset, all_data, all_data_raw = spf.filter_event( evt, filter_name) if not accepted: continue print(cspad_tbx.evt_timestamp(cspad_tbx.evt_time(evt)), "Publishing data for event", i) #header = "Event %d, m/f: %7.7f, f: %d"%(i, peak_max/flux, flux) header = "Event %d" % (i) if rank == 0: fee = Image(header, "FEE", data) # make a 2D plot publish.send("FEE", fee) # send to the display spectrumplot = XYPlot(header, 'summed 1D trace', list(range(data.shape[1])), spectrum) # make a 1D plot publish.send("SPECTRUM", spectrumplot) # send to the display fee = Image(header, "DC_OFFSET", dc_offset) # make a 2D plot publish.send("DC_OFFSET", fee) # send to the display fee = Image(header, "ALL_FEE", all_data) # make a 2D plot publish.send("ALL_FEE", fee) # send to the display fee = Image(header, "ALL_FEE_RAW", all_data_raw) # make a 2D plot publish.send("ALL_FEE_RAW", fee) # send to the display
# Double Gaussian fitresults = UXSDataPreProcessing.DoubleGaussian([int1, pos1, sigma1, int2, pos2, sigma2], cutenergyscale) elif not np.isnan(sigma1): # Simple gaussian fitresults = UXSDataPreProcessing.Gaussian([int1, pos1, sigma1], cutenergyscale) else: fitresults = np.zeros(1024) livetitle = """<table><tr><td>Live</td><td>-----------</td><td>----------</td><td>-----------</td></tr> <tr><td>Pos1:</td><td>{:.2f}</td><td>Sigma1:</td><td>{:.2f}</td></tr> <tr><td>Pos2:</td><td>{:.2f}</td><td>Sigma2:</td><td>{:.2f}</td></tr> <tr><td>"Int2/Int1":</td><td>{:.2f}</td><td></td><td></td></tr> </table>""".format(pos1,sigma1,pos2,sigma2,(int2*sigma2)/(int1*sigma1)) # Send a multiplot plotimglive = Image(0, "Live", uxspre.image) plotimgacc = Image(0, "Acc", accimage) plotxylive = XYPlot(0, livetitle, [energyscale, cutenergyscale, cutenergyscale], [spectrum, fitresults, darkremovespec])#filtspec]) plotxyacc = XYPlot(0, "Acc", energyscale, accspectrum) multi = MultiPlot(0, "UXSMonitor {} Hz {}".format(speed, metadata[frameidx]), ncols=2) multi.add(plotimglive) multi.add(plotimgacc) multi.add(plotxylive) multi.add(plotxyacc) publish.send("UXSMonitor", multi) # 2nd UXSMonitor multi = MultiPlot(0, "UXSMonitor2 {} Hz {}".format(speed, metadata[frameidx]), ncols=3) plotsigma = XYPlot(0, "Sigma1: {:.2f}<br>Sigma2: {:.2f}".format(sigma1,sigma2), 2*[range(numhistory)], [np.roll(s, -histidx-1) for s in sigmamonitor], formats='.') plotheight = XYPlot(0, "Height1: {:.2f}<br>Height2: {:.2f}".format(int1,int2), 2*[range(numhistory)], [np.roll(h, -histidx-1) for h in heightmonitor], formats='.') plotpos = XYPlot(0, "Pos1: {:.2f}<br>Pos2:{:.2f}".format(pos1,pos2), 2*[range(numhistory)], [np.roll(p, -histidx-1) for p in posmonitor], formats='.') plotintensity = XYPlot(0, "Intensity", range(numhistory), np.roll(intensitymonitor, -histidx-1), formats='.') plotfiltintensity = XYPlot(0, "Filtered Intensity", range(numhistory), np.roll(filtintensitymonitor, -histidx-1), formats='.')
from psana import * ds = DataSource('exp=xpptut15:run=54:smd') det = Detector('cspad') for nevent,evt in enumerate(ds.events()): img = det.image(evt) y = img.sum(axis=0) break from psmon.plots import Image,XYPlot from psmon import publish publish.local = True plotimg = Image(0,"CsPad",img) publish.send('IMAGE',plotimg) plotxy = XYPlot(0,"Y vs. X",range(len(y)),y) publish.send('XY',plotxy)
def runmaster(nClients, pars, args): # initialize arrays dataDict = {} dataDict['nevents'] = np.ones(10000) * -1 dataDict['h_peak'] = np.zeros(10000) dataDict['v_peak'] = np.zeros(10000) dataDict['h_width'] = np.zeros(10000) dataDict['v_width'] = np.zeros(10000) dataDict['x_prime'] = np.zeros(10000) dataDict['x_res'] = np.zeros(10000) dataDict['y_prime'] = np.zeros(10000) dataDict['y_res'] = np.zeros(10000) dataDict['x_grad'] = np.zeros(10000) dataDict['y_grad'] = np.zeros(10000) dataDict['intensity'] = np.zeros(10000) roi = pars['roi'] xmin = roi[0] xmax = roi[1] ymin = roi[2] ymax = roi[3] padSize = pars['pad'] xSize = (xmax - xmin) * padSize ySize = (ymax - ymin) * padSize # initialize plots img_measured = Image(0, "RAW", np.zeros((ySize, xSize))) img_fft = Image(0, "FFT", np.zeros((ySize, xSize))) img_focus = Image(0, "FOCUS", np.zeros((ySize, xSize))) img_amp = Image(0, "AMP", np.zeros((ySize, xSize))) # peak_plot = XYPlot(0, "peak", [dataDict['nevents'],dataDict['nevents'],dataDict['nevents']],[dataDict['h_peak'],dataDict['v_peak'],dataDict['h_peak']], formats=['bo','ro','bo'],leg_label=['Horizontal','Vertical','smooth']) focus_dist_plot = XYPlot(0, "focus_dist", [ dataDict['nevents'], dataDict['nevents'], dataDict['nevents'], dataDict['nevents'] ], [ dataDict['h_peak'], dataDict['v_peak'], dataDict['h_peak'], dataDict['v_peak'] ], formats=['bo', 'ro', 'c.', 'm.'], leg_label=[ 'Horizontal', 'Vertical', 'Horizontal Smooth', 'Vertical Smooth' ]) focus_dist_plot.xlabel = 'Event number' focus_dist_plot.ylabel = 'Focus position (mm)' x_grad_plot = XYPlot(0, "x_grad", dataDict['x_prime'], dataDict['x_grad']) x_grad_plot.xlabel = 'x (microns)' x_grad_plot.ylabel = 'Phase gradient' y_grad_plot = XYPlot(0, "y_grad", dataDict['y_prime'], dataDict['y_grad']) y_grad_plot.xlabel = 'y (microns)' y_grad_plot.ylabel = 'Phase gradient' x_res_plot = XYPlot(0, "x_res", dataDict['x_prime'], dataDict['x_res']) x_res_plot.xlabel = 'x (microns)' x_res_plot.ylabel = 'Residual phase (rad)' y_res_plot = XYPlot(0, "y_res", dataDict['y_prime'], dataDict['y_res']) y_res_plot.xlabel = 'y (microns)' y_res_plot.ylabel = 'Residual phase (rad)' rms_plot = XYPlot(0, "rms", [dataDict['nevents'], dataDict['nevents'], 0, 0], [dataDict['h_width'], dataDict['v_width'], 0, 0], formats=['bo', 'ro', 'c.', 'm.'], leg_label=[ 'Horizontal', 'Vertical', 'Horizontal Smooth', 'Vertical Smooth' ]) rms_plot.xlabel = 'Event number' rms_plot.ylabel = 'RMS Residual Phase (rad)' intensity_plot = XYPlot(0, "intensity", dataDict['nevents'], dataDict['intensity'], formats='bo') intensity_plot.xlabel = 'Event number' intensity_plot.ylabel = 'Peak intensity (a.u.)' publish.send("peak", focus_dist_plot) publish.send("rms", rms_plot) publish.send("FFT", img_fft) publish.send("RAW", img_measured) publish.send("x_res", x_res_plot) publish.send("y_res", y_res_plot) #publish.send("x_grad",x_grad_plot) #publish.send("y_grad",y_grad_plot) publish.send("FOCUS", img_focus) publish.send("intensity", intensity_plot) #publish.send("v_grad",img_v_grad) publish.send("AMP", img_amp) nevent = -1 while nClients > 0: # Remove client if the run ended md = mpidata() rank1 = md.recv() print(rank1) if md.small.endrun: nClients -= 1 else: #nevents = np.append(nevents,md.nevents) dataDict['nevents'] = update(md.nevents, dataDict['nevents']) dataDict['h_peak'] = update(md.h_peak, dataDict['h_peak']) dataDict['v_peak'] = update(md.v_peak, dataDict['v_peak']) dataDict['h_width'] = update(md.h_width, dataDict['h_width']) dataDict['v_width'] = update(md.v_width, dataDict['v_width']) dataDict['intensity'] = update(md.intensity, dataDict['intensity']) if md.nevents > nevent: nevent = md.nevents F0 = md.F0 focus = md.focus img0 = md.img0 x_res = md.x_res y_res = md.y_res focus_distance = md.focus_distance amp = md.amp #if len(nevents)>1000: # nevents = nevents[len(nevents)-1000:] #counterSum += md.counter if rank1 == size - 1: #if True: #plot(md,img_measured,img_fft,peak_plot,width_plot,dataDict) mask = dataDict['nevents'] > 0 eventMask = dataDict['nevents'][mask] order = np.argsort(eventMask) eventMask = eventMask[order] h_peak = dataDict['h_peak'][mask][order] v_peak = dataDict['v_peak'][mask][order] h_width = dataDict['h_width'][mask][order] v_width = dataDict['v_width'][mask][order] intensity = dataDict['intensity'][mask][order] h_smooth = pandas.rolling_mean(h_peak, 10) v_smooth = pandas.rolling_mean(v_peak, 10) hw_smooth = pandas.rolling_mean(h_width, 10) vw_smooth = pandas.rolling_mean(v_width, 10) plot(focus_dist_plot, "focus_dist", [eventMask, eventMask, eventMask[10:], eventMask[10:]], [h_peak, v_peak, h_smooth[10:], v_smooth[10:]]) plot(rms_plot, "rms", [eventMask, eventMask, eventMask[10:], eventMask[10:]], [h_width, v_width, hw_smooth[10:], vw_smooth[10:]]) plot(intensity_plot, "intensity", eventMask, intensity) imshow(img_measured, "RAW", img0, nevent) imshow(img_fft, "FFT", F0, nevent) imshow(img_focus, "FOCUS", focus, focus_distance) #imshow(img_v_grad,"v_grad",md.v_grad,md.small.event) imshow(img_amp, "AMP", amp, nevent) plot(x_res_plot, "x_res", md.x_prime, md.x_res) plot(y_res_plot, "y_res", md.y_prime, md.y_res) #plot(x_grad_plot,"x_grad",md.x_prime,md.x_grad) #plot(y_grad_plot,"y_grad",md.y_prime,md.y_grad) fileName = '/reg/d/psdm/' + pars['hutch'] + '/' + pars['hutch'] + pars[ 'exp_name'] + '/results/wfs/' + args.run + '_2d_data.h5' mask = dataDict['nevents'] >= 0 for key in dataDict.keys(): dataDict[key] = dataDict[key][mask] i1 = np.argsort(dataDict['nevents']) for key in dataDict.keys(): dataDict[key] = dataDict[key][i1] with h5py.File(fileName, 'w') as f: for key in dataDict.keys(): f.create_dataset(key, data=dataDict[key])
#moments_avg_buff.append(moments_sum_all[0]/(len(moments_buff)*size)) ### moments history moments_buff.append(s) #moments_sum = np.array([sum(moments_buff)])#/len(moments_buff) opal_pers_xproj = np.sum(opal_perspective, axis=0) hitrate_roi_buff.append( np.sum(hitxprojhist_sum_all[40:60]) / (len(hitxprojhist_buff) * size)) ##################################################################################################### ###################################### EXQUISIT PLOTTING ############################################ ax = range(0, len(opal_thresh_xproj)) xproj_plot = XYPlot(evtGood, "X Projection", ax, opal_thresh_xproj, formats=".-") # make a 1D plot publish.send("XPROJ", xproj_plot) # send to the display # # opal_hit_avg_arr = np.array(list(opal_hit_avg_buff)) # print opal_hit_avg_buff ax2 = range(0, len(opal_hit_avg_arr)) hitrate_avg_plot = XYPlot(evtGood, "Hitrate history", ax2, opal_hit_avg_arr, formats=".-") # make a 1D plot # print 'publish',opal_hit_avg_arr publish.send("HITRATE", hitrate_avg_plot) # send to the display
def make_acq_svd_basis(detectorObject, thisEvent, previousProcessing): selfName = detectorObject['self_name'] config_parameters = { "thresh_hold": 0.05, "waveform_mask": arange(1200, 1230), "eigen_basis_size": 25, "offset_mask": arange(300) } eigen_system = {} ############################## #### initializing arrays ##### ############################## if None is detectorObject[selfName](thisEvent): return None if (len(detectorObject[selfName](thisEvent)) == 4): the_wave_forms = detectorObject[selfName](thisEvent) else: the_wave_forms = detectorObject[selfName](thisEvent)[0] for i in arange(len(the_wave_forms)): try: eigen_system["ch" + str(i)] = previousProcessing["ch" + str(i)] except (KeyError, TypeError) as e: try: y = 1.0 * the_wave_forms[i] y -= mean(y[config_parameters['offset_mask']]) eigen_system["ch" + str(i)] = { 'eigen_wave_forms': y, 'eigen_weightings': [1], 'norm_eigen_wave_forms': [1] } except (KeyError, TypeError) as e: eigen_system["ch" + str(i)] = { 'eigen_wave_forms': None, 'eigen_weightings': None, 'norm_eigen_wave_forms': None } ############################## ###main part of calculation### ############################## new_eigen_system = {} for i in arange(len(the_wave_forms)): y = 1.0 * the_wave_forms[i] y -= mean(y[config_parameters['offset_mask']]) start_time = time.time() new_eigen_system["ch" + str(i)] = svd_update( eigen_system["ch" + str(i)], y, config_parameters) #print(time.time() - start_time) #for j in eigen_system["ch"+str(i)]: # print(str(j)+", "+str(eigen_system["ch"+str(i)][j].shape)) ######################################################## ########plotting for real time SVD debugging############ ######################################################## publish.local = True try: wave_to_plot = new_eigen_system["ch2"]['norm_eigen_wave_forms'] to_plot = XYPlot( time.time(), "eigen_system", [arange(len(wave_to_plot[0])), arange(len(wave_to_plot[0]))], [wave_to_plot[0], wave_to_plot[1]]) publish.send('eigen_system_' + selfName, to_plot) #psplot -s hostname -p 12303 eigen_system except: pass ######################################################## ########end of SVD debugging########################### ######################################################## return new_eigen_system
def main(): my_list = [] #pv_list = [gdet, gmd, ebeam] gdet, gmd, e_beam = get_time_stamped_data() e_beam_mean = np.mean(e_beam) e_beam_std = np.std(e_beam) e_range = 20 + 0 * 6 * e_beam_std n_bins = 100 my_bins = arange(e_beam_mean - e_range, e_beam_mean + e_range, 2 * e_range / n_bins) e_beam_histogram = np.histogram(e_beam, my_bins)[0] e_beam_histogram /= sum(e_beam_histogram) plot_ebeam_hist = XYPlot(0, "counts vs. e_beam", my_bins[1:], e_beam_histogram) gmd_histogram = np.histogram(e_beam * gmd, my_bins)[0] / e_beam_histogram plot_gmd_hist = XYPlot(0, "counts vs. e_beam", my_bins[1:], gmd_histogram) #publish.local = True hist_size = 2400 gdet_list, gmd_list, e_beam_list = (array([]), array([]), array([])) while (True): try: gdet, gmd, e_beam = get_time_stamped_data() e_beam_mean = np.mean(e_beam) e_beam_std = np.std(e_beam) e_range = 10 + 0 * 6 * e_beam_std n_bins = 100 my_bins = arange(e_beam_mean - e_range, e_beam_mean + e_range, 2 * e_range / n_bins) e_beam_list = append(e_beam_list[-hist_size:], e_beam) gmd_list = append(gmd_list[-hist_size:], gmd) gdet_list = append(gdet_list[-hist_size:], gdet) e_beam_histogram = np.histogram(e_beam_list, my_bins)[0] gmd_histogram = np.histogram( e_beam_list, my_bins, weights=gmd_list)[0] * 1.0 / (e_beam_histogram + 1e-12) gdet_histogram = np.histogram( e_beam_list, my_bins, weights=gdet_list)[0] * 1.0 / (e_beam_histogram + 1e-12) plot_ebeam_hist = XYPlot(0, "counts vs. e_beam", my_bins[1:], e_beam_histogram) publish.send('counts_ebeam', plot_ebeam_hist) plot_gmd_hist = XYPlot(0, "gmd vs. e_beam", my_bins[1:], gmd_histogram) publish.send('gmd_ebeam', plot_gmd_hist) normalized_e_beam_histogram = e_beam_histogram * 1.0 / sum( nan_to_num(e_beam_histogram) + 1e-12) normalized_gmd_histogram = gmd_histogram * 1.0 / sum( nan_to_num(gmd_histogram)) normalized_gdet_histogram = gdet_histogram * 1.0 / sum( nan_to_num(gdet_histogram)) plot_overlay = XYPlot( 0, "gmd and ebeam", [my_bins[1:], my_bins[1:]], [normalized_e_beam_histogram, normalized_gmd_histogram]) #plot_overlay = XYPlot(0,"gmd and ebeam",[my_bins[1:],my_bins[1:],my_bins[1:]],[normalized_e_beam_histogram,normalized_gmd_histogram,normalized_gdet_histogram]) x_temp = arange(-10, 10, 1) publish.send('both_gmd_ebeam', plot_overlay) except KeyboardInterrupt: break except ValueError: print("GMD likely down") time.sleep(2)
if rank==0: ###### calculating moments of the hithist.data m,s = moments(hitxprojjitter_sum_all) #changed from hitxprojhist_sum_all ###### History on master print eventCounter*size, 'total events processed.' opal_hit_avg_buff.append(opal_hit_sum_all[0]/(len(opal_hit_buff)*size)) #xproj_int_avg_buff.append(xproj_int_sum_all[0]/(len(xproj_int_buff)*size)) #moments_avg_buff.append(moments_sum_all[0]/(len(moments_buff)*size)) ### moments history moments_buff.append(s) #moments_sum = np.array([sum(moments_buff)])#/len(moments_buff) # Exquisit plotting ax = range(0,len(opal_thresh_xproj)) xproj_plot = XYPlot(evtGood, "X Projection", ax, opal_thresh_xproj,formats=".-") # make a 1D plot publish.send("XPROJ", xproj_plot) # send to the display # # opal_hit_avg_arr = np.array(list(opal_hit_avg_buff)) # print opal_hit_avg_buff ax2 = range(0,len(opal_hit_avg_arr)) hitrate_avg_plot = XYPlot(evtGood, "Hitrate history", ax2, opal_hit_avg_arr,formats=".-") # make a 1D plot # print 'publish',opal_hit_avg_arr publish.send("HITRATE", hitrate_avg_plot) # send to the display # # #xproj_int_avg_arr = np.array(list(xproj_int_avg_buff)) #ax3 = range(0,len(xproj_int_avg_arr)) #xproj_int_plot = XYPlot(evtGood, "XProjection running avg history", ax3, xproj_int_avg_arr) # make a 1D plot #publish.send("XPROJRUNAVG", xproj_int_plot) # send to the display # #