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"
Exemplo n.º 2
0
def main():
    args = parse_cli()
    max_updates = args.num_updates
    period = 1 / args.rate
    status_rate = 100
    image_n = args.images
    col_n = args.columns
    windows = args.windows
    pixels_n = 1024
    width = 50
    pos = 25
    topic = 'image'
    title = 'Image Test'
    multi_topic = 'multi-image'
    multi_title = 'Mulit Image Test'

    #optional port, buffer-depth arguments.
    publish.local = args.local
    publish.client_opts.daemon = True
    if args.mpl:
        publish.client_opts.renderer = 'mpl'
    elif args.pyqt:
        publish.client_opts.renderer = 'pyqt'
    publish.plot_opts.zrange = (-250., 250.)

    counter = 0
    while counter < max_updates or max_updates < 1:
        multi_image = MultiPlot(counter,
                                multi_title,
                                ncols=min(col_n, image_n),
                                use_windows=windows)
        for num in range(image_n):
            image_data = Image(
                counter, '%s %d' % (title, num),
                np.random.normal((-1)**num * pos * num, width,
                                 (pixels_n, pixels_n)))
            multi_image.add(image_data)
        publish.send(multi_topic, multi_image)
        image_data = Image(counter, title,
                           np.random.normal(0, width, (pixels_n, pixels_n)))
        publish.send(topic, image_data)

        counter += 1

        if counter % status_rate == 0:
            print("Processed %d updates so far" % counter)

        time.sleep(period)
Exemplo n.º 3
0
 def __init__(self,
              topic,
              num_data,
              title=None,
              pubrate=None,
              publisher=None):
     super(MultiHelper, self).__init__(topic, title, pubrate, publisher)
     self.data = MultiPlot(None, self.title, [None] * num_data)
Exemplo n.º 4
0
 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)
Exemplo n.º 5
0
def plot(hd):

    for j in range(0,len(ftop)-1):
	ftop[j]=ftop[j+1]
	fmid[j]=fmid[j+1]
        fids[j]=fids[j+1]

    ftop[len(ftop)-1]=hd.myorig
    fmid[len(fmid)-1]=hd.myfit

    comp=hd.myobj['comp']
  
    fids[len(fids)-1]=comp['et'].fiducial()
    
    multop = MultiPlot(1, 'Original Image')
    mulmid = MultiPlot(1, 'Fitted   Image')

    for j in range(0,len(ftop)):
        if ftop[j] is not None :
      	    plottop = Image(fids[j],"Original",ftop[j])
      	    plotmid = Image(fids[j],"Fitted",fmid[j])
            multop.add(plottop)
            mulmid.add(plotmid)

    publish.send('ORIG', multop)
    publish.send('FIT', mulmid)
Exemplo n.º 6
0
def plot(hd, args):




    for j in range(0,len(ftop)-1):
	ftop[j]=ftop[j+1]
	fmid[j]=fmid[j+1]
	fbot[j]=fbot[j+1]
        fids[j]=fids[j+1]

    ftop[len(ftop)-1]=hd.myorig
    fmid[len(fmid)-1]=np.log10(100+abs(np.amin(hd.myfit))+hd.myfit)

    comp=hd.myobj['comp']

    ttPos = comp['epics']['TTSPEC:FLTPOS']
    delay = (ttA*ttPos**2 + ttB*ttPos + ttC)*1000 - 300

    #fids[len(fids)-1]=comp['tofsum']
    fids[len(fids)-1]=comp['imgsum']
    fbot[len(ftop)-1]=comp['tof']
    
    multop = MultiPlot(1, 'Original Image')
    mulmid = MultiPlot(1, 'Fitted   Image')
    mulbot = MultiPlot(1, 'TOF plot')# + args.exprun+'_' + args.label)

    for j in range(0,len(ftop)):
        if ftop[j] is not None :
      	    plottop = Image(fids[j],"Original",ftop[j])
      	    plotmid = Image(fids[j],"Fitted",fmid[j])
            plotbot = XYPlot(fids[j], "TOF", comp['tofAxis'], fbot[j])
            multop.add(plottop)
            mulmid.add(plotmid)
            mulbot.add(plotbot)

    publish.send('ORIG', multop)
    publish.send('FIT', mulmid)
    publish.send('TOFXY', mulbot)
Exemplo n.º 7
0
    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)
Exemplo n.º 8
0
        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
        publish.send('SHESOnline', multi)

        time.sleep(arc_wait_time)

        continue  # don't accumulate data for the arced shot

    #%%
    cent_pe = l3Proc.CentPE(evt)
def plot(sumDict, event_ts_str):
    #print sumDict['n_off'], sumDict['n_early'], sumDict['n_late']

    #publish.local=True
    publish.plot_opts.palette = 'spectrum'
    multi_plot_data = MultiPlot(event_ts_str, 'normImg')
    multi_plot_dataDiff = MultiPlot(event_ts_str, 'normImgDiff')

    if 'img_off' in sumDict.keys():
        sumDict['img_off'] = sumDict['img_off'].astype(float)
    if 'img_early' in sumDict.keys():
        sumDict['img_early'] = sumDict['img_early'].astype(float)
    if 'img_late' in sumDict.keys():
        sumDict['img_late'] = sumDict['img_late'].astype(float)

    if sumDict['n_off'] > 0:
        #plotImgOffNorm = Image(0,'off_norm',sumDict['img_off']/sumDict['i0_off'])
        plotImgOffNorm = Image(0, 'off_norm',
                               sumDict['img_off'] / sumDict['n_off'])
        multi_plot_data.add(plotImgOffNorm)
    if sumDict['n_early'] > 0:
        #plotImgEarlyNorm = Image(0,'early_norm',sumDict['img_early']/sumDict['i0_early'])
        plotImgEarlyNorm = Image(0, 'early_norm',
                                 sumDict['img_early'] / sumDict['n_early'])
        multi_plot_data.add(plotImgEarlyNorm)
    if sumDict['n_late'] > 0:
        #plotImgLateNorm = Image(0,'late_norm',sumDict['img_late']/sumDict['i0_late'])
        plotImgLateNorm = Image(0, 'late_norm',
                                sumDict['img_late'] / sumDict['n_late'])
        multi_plot_data.add(plotImgLateNorm)
    #uncomment to see plots.
    if sumDict['n_early'] > 0 and sumDict['n_late'] > 0:
        publish.send('normImg', multi_plot_data)
        plotImgDiffT0 = Image(
            0, 'late_early', sumDict['img_late'] / sumDict['i0_late'] -
            sumDict['img_early'] / sumDict['i0_early'])
        multi_plot_dataDiff.add(plotImgDiffT0)

    if sumDict['n_off'] > 0 and sumDict['n_late'] > 0:
        plotImgDiffOff = Image(
            0, 'late_off', sumDict['img_late'] / sumDict['i0_late'] -
            sumDict['img_off'] / sumDict['i0_off'])
        multi_plot_dataDiff.add(plotImgDiffOff)

    if sumDict['n_early'] > 0 and sumDict['n_late'] > 0 and sumDict[
            'n_off'] > 0:
        publish.send('normImgDiff', multi_plot_dataDiff)
Exemplo n.º 10
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 xrange(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)
Exemplo n.º 11
0
        continue
    EBEAM_beam_energy = EBEAM.ebeamL3Energy()  # beam energy in MeV
    FEE_shot_energy = procFEE.ShotEnergy(evt)
    #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
Exemplo n.º 12
0
        #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)
        #plotxy = XYPlot(0, "UXS Counts {}".format(str(evt.get(EventId))), range(numframes), counts)
        #publish.send("UXSMonitorCounts", plotxy)
 
    # Iterate framenumber
Exemplo n.º 13
0
        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='.')
        pulsehistogram, pulsehistogramedges = np.histogram(pulsemonitor,3)
        plotpulsemonitor = Hist(0, "Pulse count histogram", pulsehistogramedges, pulsehistogram)
Exemplo n.º 14
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)
        publish.send('FEEGasHistogram', plotFeeGasEnergy)
        publish.send('FEEGasROICountsHistogram', plotFeeGasEnergy_CountsROI)

    def sendMultiPlot(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, speed):
        plotxproj, plotcumimage, plotcounts, plotcountsregint, plotshot, plotL3PhotEnergy, plotFeeGasEnergy, \
        plotFeeGasEnergy_CountsROI=\
        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 multiplot
        multi = MultiPlot(nevt,
                          'SHES Online Monitoring, running at ~' +
                          str(np.round(speed, 1)) + ' Hz',
                          ncols=3)
        # Publish plots
        multi.add(plotshot)
        multi.add(plotcounts)
        multi.add(plotL3PhotEnergy)
        multi.add(plotcumimage)
        multi.add(plotcountsregint)
        multi.add(plotFeeGasEnergy)
        multi.add(plotxproj)
        multi.add(plotFeeGasEnergy_CountsROI)

        publish.send('SHES Online Monitoring', multi)


rolling_count = 0