Exemplo n.º 1
0
    def __init__(self, img, **kwa):
        flexbase.__init__(self, **kwa)
        arr = kwa.get('arr', None)
        if arr is None: arr = img  #kwa['arr'] = arr = img
        amin, amax = self._intensity_limits(arr, **kwa)

        aspratio = float(img.shape[0]) / float(img.shape[1])  # heigh/width

        kwa.setdefault('w_in', 9)
        kwa.setdefault('h_in', 8)
        _fig = gr_figure(**kwa)

        kwfica = {}
        fymin, fymax = 0.04, 0.93
        self.fig, self.axim, self.axcb = gr.fig_img_cbar_axes(\
            fig=_fig,\
            win_axim = kwa.get('win_axim', (0.05,  fymin, 0.86, fymax)),\
            win_axcb = kwa.get('win_axcb', (0.915, fymin, 0.01, fymax)), **kwfica)

        kwa.setdefault('amin', amin)
        kwa.setdefault('amax', amax)
        self.imsh, self.cbar = gr_imshow_cbar(self.fig, self.axim, self.axcb,
                                              img, **kwa)

        gr.draw_fig(self.fig)
Exemplo n.º 2
0
def test01(tname):

    PF = V3 if tname == '3' else V4
    SHOW_PEAKS = tname != '0'

    ds = data_hdf5_v0(FNAME)
    #ds.print_images()

    alg = peak_finder_algos(pbits=0)
    if PF == V3:
        alg.set_peak_selection_parameters(npix_min=0,
                                          npix_max=1e6,
                                          amax_thr=0,
                                          atot_thr=0,
                                          son_min=6)
    if PF == V4:
        alg.set_peak_selection_parameters(npix_min=0,
                                          npix_max=1e6,
                                          amax_thr=0,
                                          atot_thr=0,
                                          son_min=6)

    img = ds.next_image()
    shape = img.shape
    mask = np.ones(shape, dtype=np.uint16)
    INDS = np.indices((shape[0], shape[1]), dtype=np.int64)
    imRow, imCol = INDS[0, :], INDS[1, :]

    fig1, axim1, axcb1 = gr.fig_img_cbar_axes(gr.figure(figsize=(8, 7)))

    for nev in range(min(EVTMAX, ds.nevmax)):

        img = ds.next_image()

        #ave, rms = img.mean(), img.std()
        #amin, amax = ave-1*rms, ave+8*rms
        #amin, amax = img.min(), img.max()
        amin, amax = 0, img.max()
        axim1.clear()
        axcb1.clear()

        #imsh1,cbar1=\
        gr.imshow_cbar(fig1, axim1, axcb1, img, amin=amin, amax=amax, extent=None,\
                       interpolation='nearest', aspect='auto', origin='upper',\
                       orientation='vertical', cmap='inferno')
        fig1.canvas.set_window_title('Event: %04d random data' % nev)
        gr.move_fig(fig1, x0=400, y0=30)

        if SHOW_PEAKS:
            peaks = alg.peak_finder_v3r3_d2(img, mask, rank=5, r0=7, dr=2, nsigm=9)               if PF == V3 else\
                alg.peak_finder_v4r3_d2(img, mask, thr_low=100, thr_high=200, rank=5, r0=7, dr=2) if PF == V4 else\
                None
            plot_peaks_on_img(peaks, axim1, imRow, imCol, color='w', lw=1)

        gr.show(mode='do not hold')

    gr.show()
Exemplo n.º 3
0
def plot_image(data):
    fig, axim, axcb = gr.fig_img_cbar_axes(gr.figure(figsize=(10, 5), dpi=80))
    ave, rms = np.mean(data), np.std(data)
    _, _ = gr.imshow_cbar(fig,
                          axim,
                          axcb,
                          data,
                          amin=ave - 1 * rms,
                          amax=ave + 5 * rms,
                          extent=None,
                          cmap='inferno')
    return axim
def test_xtcav_data_access():
    tname = sys.argv[1] if len(sys.argv) > 1 else '0'

    #fig, axim = fig_axis()
    fig, axim, axcb = gr.fig_img_cbar_axes(fig=None,\
             win_axim=(0.05,  0.05, 0.87, 0.93),\
             win_axcb=(0.923, 0.05, 0.02, 0.93)) #, **kwargs)

    ds = DataSource(files=data_file(tname))
    orun = next(ds.runs())
    det = orun.Detector('xtcav')

    print('test_xtcav_data    expt: %s runnum: %d\n' %
          (orun.expt, orun.runnum))

    for nev, evt in enumerate(orun.events()):
        if nev > 10: break
        print('Event %03d' % nev, end='')

        nda = det.raw(evt)
        print_ndarr(nda, '  det.raw(evt):')

        mean, std = nda.mean(), nda.std()
        aran = (mean - 3 * std, mean + 5 * std)

        axim.clear()
        axcb.clear()

        imsh = gr.imshow(axim, nda, amp_range=aran, extent=None, interpolation='nearest',\
                         aspect='auto', origin='upper', orientation='horizontal', cmap='inferno')
        cbar = gr.colorbar(fig,
                           imsh,
                           axcb,
                           orientation='vertical',
                           amp_range=aran)

        gr.set_win_title(fig, 'Event: %d' % nev)
        gr.draw_fig(fig)
        gr.show(mode='non-hold')

    gr.save_fig(
        fig,
        prefix='./img-%s-r%04d-e%06d-' % (orun.expt, orun.runnum, nev),
        suffix='.png',
    )
    gr.show()
Exemplo n.º 5
0
    def __init__(self, img, **kwa):
        """
        """
        flexbase.__init__(self, **kwa)
        arr = kwa.setdefault('arr', img)
        amin, amax = self._intensity_limits(arr, kwa)
        w_in = kwa.pop('w_in', 9)
        h_in = kwa.pop('h_in', 8)

        aspratio = float(img.shape[0]) / float(img.shape[1])  # heigh/width

        kwfig = {}
        _fig=gr.plt.figure(\
                num   = kwa.get('num',None),\
                figsize   = kwa.get('figsize',(w_in, h_in)),\
                dpi       = kwa.get('dpi',80),\
                facecolor = kwa.get('facecolor','w'),\
                edgecolor = kwa.get('edgecolor','w'),\
                frameon   = kwa.get('frameon',True),\
                clear     = kwa.get('clear',False),\
                **kwfig)

        kwfica = {}
        self.fig, self.axim, self.axcb = gr.fig_img_cbar_axes(\
            fig=_fig,\
            win_axim = kwa.get('win_axim', (0.05,0.03,0.87,0.94)),\
            win_axcb = kwa.get('win_axcb', (0.915,0.03,0.01,0.94)), **kwfica)

        kwic = {
            'amin': amin,
            'amax': amax,
            'extent': kwa.get('extent', None),
            'interpolation': kwa.get('interpolation', 'nearest'),
            'aspect': kwa.get('aspect', 'equal'),
            'origin': kwa.get('origin', 'upper'),
            'orientation': kwa.get('orientation', 'vertical'),
            'cmap': kwa.get('cmap', 'inferno'),
        }
        self.imsh, self.cbar = gr.imshow_cbar(self.fig, self.axim, self.axcb,
                                              img, **kwic)

        gr.draw_fig(self.fig)
Exemplo n.º 6
0
    def __init__(self, args):
        """
        """
        #self.args = args

        fname = getattr(
            args, 'fname',
            '/reg/g/psdm/detector/data2_test/xtc/data-amox23616-r0131-e000200-xtcav-v2.xtc2'
        )
        experiment = getattr(args, 'experiment', 'amox23616')
        run_number = getattr(args, 'run_number', 131)
        max_shots = getattr(args, 'max_shots',
                            401)  #Maximum number of shots to process
        validity_range = getattr(args, 'validity_range', None)
        save_to_file = getattr(args, 'save_to_file', True)
        calibration_path = getattr(args, 'calibration_path', '')
        start_image = getattr(args, 'start_image', 0)
        dark_reference_path = getattr(args, 'dark_reference_path',
                                      None)  #Dark reference information
        num_bunches = getattr(args, 'num_bunches', 1)  #Number of bunches
        num_groups = getattr(args, 'num_groups',
                             None)  #Number of profiles to average together
        snr_filter = getattr(args, 'snr_filter',
                             10)  #Number of sigmas for the noise threshold
        roi_expand = getattr(args, 'roi_expand',
                             1)  #Parameter for the roi location
        roi_fraction = getattr(args, 'roi_fraction', cons.ROI_PIXEL_FRACTION)
        island_split_method = getattr(
            args, 'island_split_method',
            cons.DEFAULT_SPLIT_METHOD)  #Method for island splitting
        island_split_par1 = getattr(
            args, 'island_split_par1', 3.0
        )  #Ratio between number of pixels between largest and second largest groups when calling scipy.label
        island_split_par2 = getattr(
            args, 'island_split_par2', 5.
        )  #Ratio between number of pixels between second/third largest groups when calling scipy.label
        PLOT_IMAGE = getattr(args, 'plot_image', False)

        if PLOT_IMAGE:
            self.fig, self.axim, self.axcb = gr.fig_img_cbar_axes(fig=None,\
            win_axim=(0.05,  0.05, 0.87, 0.93),\
            win_axcb=(0.923, 0.05, 0.02, 0.93)) #, **kwargs)

        #if type(run_number) == int:
        #    run_number = str(run_number)

        self.parameters = LasingOffParameters(
            experiment=experiment,
            max_shots=max_shots,
            run_number=run_number,
            start_image=start_image,
            validity_range=validity_range,
            dark_reference_path=dark_reference_path,
            num_bunches=num_bunches,
            num_groups=num_groups,
            snr_filter=snr_filter,
            roi_expand=roi_expand,
            roi_fraction=roi_fraction,
            island_split_method=island_split_method,
            island_split_par2=island_split_par2,
            island_split_par1=island_split_par1,
            calibration_path=calibration_path,
            fname=fname,
            version=1)

        if rank == 0:
            print('Lasing off reference')
            print('\t File name: %s' % self.parameters.fname)
            print('\t Experiment: %s' % self.parameters.experiment)
            print('\t Runs: %s' % self.parameters.run_number)
            print('\t Number of bunches: %d' % self.parameters.num_bunches)
            print('\t Valid shots to process: %d' % self.parameters.max_shots)
            print('\t Dark reference run: %s' %
                  self.parameters.dark_reference_path)

        #Loading the data, this way of working should be compatible with both xtc and hdf5 files

        #ds = psana.DataSource("exp=%s:run=%s:idx" % (self.parameters.experiment, self.parameters.run_number))

        ds = DataSource(files=fname)
        run = next(ds.runs())  # run = ds.runs().next()
        #env = SimulatorEnvironment() # ds.env()

        #Camera for the xtcav images, Ebeam type, eventid, gas detectors
        camera = run.Detector(cons.DETNAME)  # psana.Detector(cons.DETNAME)
        ebeam = run.Detector(
            cons.EBEAM)  #SimulatorEBeam() # psana.Detector(cons.EBEAM)
        eventid = run.Detector(
            cons.EVENTID)  #SimulatorEventId() # evt.get(psana.EventId)
        gasdetector = run.Detector(
            cons.GAS_DETECTOR
        )  #SimulatorGasDetector() # psana.Detector(cons.GAS_DETECTOR)
        xtcavpars = run.Detector(cons.XTCAVPARS)

        # Empty list for the statistics obtained from each image, the shot to shot properties,
        # and the ROI of each image (although this ROI is initially the same for each shot,
        # it becomes different when the image is cropped around the trace)
        list_image_profiles = []

        #dark_background = self._getDarkBackground(env)

        dark_data, dark_meta = xtup.get_calibconst(camera, 'xtcav_pedestals',
                                                   cons.DETNAME, experiment,
                                                   run_number)

        logger.debug('==== dark_meta:\n%s' % str(dark_meta))

        dark_background = xtu.xtcav_calib_object_from_dict(dark_data)
        logger.debug('==== dir(dark_background):\n%s' %
                     str(dir(dark_background)))
        logger.debug('==== dark_background.ROI:\n%s' %
                     str(dark_background.ROI))
        logger.debug(
            info_ndarr(dark_background.image, '==== dark_background.image:'))

        print('\n', 100 * '_', '\n')

        camraw = xtup.get_attribute(camera, 'raw')
        valsxtp = xtup.get_attribute(xtcavpars, 'valsxtp')
        valsebm = xtup.get_attribute(ebeam, 'valsebm')
        valseid = xtup.get_attribute(eventid, 'valseid')
        valsgd = xtup.get_attribute(gasdetector, 'valsgd')

        if None in (camraw, valsxtp, valsebm, eventid, valsgd):
            sys.error(
                'FATAL ERROR IN THE DETECTOR INTERFACE: MISSING ATTRIBUTE MUST BE IMPLEMENTED'
            )

        #times = run.times()
        #image_numbers = xtup.divideImageTasks(first_event, len(times), rank, size)

        roi_xtcav, global_calibration, saturation_value = None, None, None
        num_processed = 0  #Counter for the total number of xtcav images processed within the run

        for nev, evt in enumerate(run.events()):
            #logger.info('Event %03d'%nev)
            img = camraw(evt)
            if img is None: continue

            if roi_xtcav is None:
                # get calibration values needed to process images.
                resp = self._getCalibrationValues(nev, evt, camraw, valsxtp)
                if resp is None: continue
                roi_xtcav, global_calibration, saturation_value = resp

            #Obtain the shot to shot parameters necessary for the retrieval of the x and y axis in time and energy units
            shot_to_shot = xtup.getShotToShotParameters(
                evt, valsebm, valsgd, valseid)
            #logger.debug('shot_to_shot: %s' % str(shot_to_shot))

            if not shot_to_shot.valid: continue

            image_profile, _ = xtu.processImage(img, self.parameters,
                                                dark_background,
                                                global_calibration,
                                                saturation_value, roi_xtcav,
                                                shot_to_shot)

            #logger.debug(info_ndarr(image_profile, 'LasingOffReference image_profile'))

            if not image_profile:
                continue

            #Append only image profile, omit processed image
            list_image_profiles.append(image_profile)
            num_processed += 1

            self._printProgressStatements(num_processed)

            if num_processed >= np.ceil(
                    self.parameters.max_shots / float(size)):
                break

            if PLOT_IMAGE:

                nda = img

                mean, std = nda.mean(), nda.std()
                aran = (mean - 3 * std, mean + 5 * std)

                self.axim.clear()
                self.axcb.clear()
                imsh = gr.imshow(self.axim, nda, amp_range=aran, extent=None, interpolation='nearest',\
                                 aspect='auto', origin='upper', orientation='horizontal', cmap='inferno')
                cbar = gr.colorbar(self.fig,
                                   imsh,
                                   self.axcb,
                                   orientation='vertical',
                                   amp_range=aran)

                gr.set_win_title(self.fig, 'Event: %d' % nev)
                gr.draw_fig(self.fig)
                gr.show(mode='non-hold')

        # here gather all shots in one core, add all lists
        #image_profiles = comm.gather(list_image_profiles, root=0)
        image_profiles = list_image_profiles

        if rank != 0: return

        sys.stdout.write('\n')
        # Flatten gathered arrays
        #image_profiles = [item for sublist in image_profiles for item in sublist]

        #for i,ipf in enumerate(image_profiles) :
        #  print('XXX image_profiles %d:\n  %s'%(i,str(ipf)))

        #Since there are 12 cores it is possible that there are more references than needed. In that case we discard some
        if len(image_profiles) > self.parameters.max_shots:
            image_profiles = image_profiles[0:self.parameters.max_shots]

        #At the end, all the reference profiles are converted to Physical units, grouped and averaged together
        averaged_profiles = xtu.averageXTCAVProfilesGroups(
            image_profiles, self.parameters.num_groups)

        self.averaged_profiles, num_groups = averaged_profiles
        self.n = num_processed
        self.parameters = self.parameters._replace(num_groups=num_groups)

        logger.debug('self.parameters.validity_range: %s  type: %s' %
                     (self.parameters.validity_range,
                      type(self.parameters.validity_range)))
        logger.debug(
            'self.parameters.run_number: %d  type: %s' %
            (self.parameters.run_number, type(self.parameters.run_number)))

        # Set validity range, replace 'end' -> 9999 othervise save does not work...
        if not self.parameters.validity_range or not type(
                self.parameters.validity_range) == tuple:
            self.parameters = self.parameters._replace(
                validity_range=(self.parameters.run_number,
                                9999))  # IT WAS 'end'))
        elif len(self.parameters.validity_range) == 1:
            self.parameters = self.parameters._replace(
                validity_range=(self.parameters.validity_range[0],
                                9999))  # 'end'))

        #=====================
        #sys.exit('TEST EXIT')
        #=====================

        if save_to_file:
            #cp = CalibrationPaths(env, self.parameters.calibration_path)
            #file = cp.newCalFileName(cons.LOR_FILE_NAME, self.parameters.validity_range[0], self.parameters.validity_range[1])
            fname = 'cons-%s-%04d-xtcav-lasingoff.data' % (run.expt, run.runnum
                                                           )  # , cons.DETNAME)
            self.save(fname)
Exemplo n.º 7
0
def test01(tname='1', NUMBER_OF_EVENTS=5, DO_PRINT=True):

    print('local extrema : %s' % ('minimums' if tname in ('1','2')\
                             else 'maximums' if tname in ('3','4')\
                             else 'maximums runk=1 cross' if tname in ('5','6')\
                             else 'two-threshold maximums' if tname == '7'\
                             else 'unknown test'))

    from time import time  #, sleep
    from psana.pyalgos.generic.NDArrUtils import print_ndarr
    import psana.pyalgos.generic.Graphics as gr

    sh, fs = (50, 50), (7, 6)
    fig1, axim1, axcb1 = gr.fig_img_cbar_axes(gr.figure(figsize=fs))
    fig2, axim2, axcb2 = gr.fig_img_cbar_axes(gr.figure(figsize=fs))
    imsh1 = None
    imsh2 = None

    print('Image shape: %s' % str(sh))

    mu, sigma = 200, 25

    for evnum in range(NUMBER_OF_EVENTS):

        data = 10.*np.ones(sh, dtype=np.float64) if tname in ('2','4','6') else\
               np.array(mu + sigma*np.random.standard_normal(sh), dtype=np.float64)
        mask = np.ones(sh, dtype=np.uint16)
        extrema = np.zeros(sh, dtype=np.uint16)
        rank = 5

        thr_low = mu + 3 * sigma
        thr_high = mu + 4 * sigma

        nmax = 0

        if DO_PRINT: print_ndarr(data, '        input data')
        t0_sec = time()
        #----------
        if tname in ('1', '2'):
            nmax = algos.local_minimums(data, mask, rank, extrema)
        elif tname in ('3', '4'):
            nmax = algos.local_maximums(data, mask, rank, extrema)
        elif tname in ('5', '6'):
            nmax = algos.local_maximums_rank1_cross(data, mask, extrema)
        elif tname == '7':
            nmax = algos.threshold_maximums(data, mask, rank, thr_low,
                                            thr_high, extrema)
        elif tname == '8':
            nmax = algos.local_maximums_rank1_cross(data, mask, extrema)
        else:
            contunue
        #----------
        print('Event: %2d,  consumed time = %10.6f(sec),  nmax = %d' %
              (evnum, time() - t0_sec, nmax))

        if DO_PRINT: print_ndarr(extrema, '        output extrema')

        img1 = data
        img2 = extrema

        axim1.clear()
        axcb1.clear()
        if imsh1 is not None: del imsh1
        imsh1 = None

        axim2.clear()
        axcb2.clear()
        if imsh2 is not None: del imsh2
        imsh2 = None

        #ave, rms = img1.mean(), img1.std()
        #amin, amax = ave-1*rms, ave+5*rms
        amin, amax = img1.min(), img1.max()
        #imsh1,cbar1=\
        gr.imshow_cbar(fig1, axim1, axcb1, img1, amin=amin, amax=amax, extent=None,\
                       interpolation='nearest', aspect='auto', origin='upper',\
                       orientation='vertical', cmap='inferno')
        fig1.canvas.set_window_title('Event: %d Random data' % evnum)
        gr.move_fig(fig1, x0=560, y0=30)

        #imsh2,cbar2=\
        gr.imshow_cbar(fig2, axim2, axcb2, img2, amin=0, amax=img2.max(), extent=None,\
                       interpolation='nearest', aspect='auto', origin='upper',\
                       orientation='vertical', cmap='inferno')
        fig2.canvas.set_window_title('Event: %d Local extrema' % evnum)
        gr.move_fig(fig2, x0=0, y0=30)

        gr.show(mode='DO_NOT_HOLD')

    gr.show()
Exemplo n.º 8
0
def test01(tname='1', NUMBER_OF_EVENTS=3, DO_PRINT=False):

    print('local extrema : %s' % ('minimums' if tname in ('1','2')\
                             else 'maximums' if tname in ('3','4')\
                             else 'maximums runk=1 cross' if tname in ('5','6')\
                             else 'two-threshold maximums' if tname == '7'\
                             else 'unknown test'))

    from time import time
    from psana.pyalgos.generic.NDArrUtils import print_ndarr
    import psana.pyalgos.generic.Graphics as gg

    #sh, fs = (185,388), (11,5)
    sh, fs = (50, 50), (7, 7)
    fig1, axim1, axcb1 = gg.fig_img_cbar_axes(gg.figure(figsize=fs),
                                              (0.05, 0.05, 0.87, 0.90),
                                              (0.923, 0.05, 0.02, 0.90))
    fig2, axim2, axcb2 = gg.fig_img_cbar_axes(gg.figure(figsize=fs),
                                              (0.05, 0.05, 0.87, 0.90),
                                              (0.923, 0.05, 0.02, 0.90))

    print('Image shape: %s' % str(sh))

    mu, sigma = 200, 25

    for evnum in range(NUMBER_OF_EVENTS):

        data = 10.*np.ones(sh, dtype=np.float64) if tname in ('2','4','6') else\
               np.array(mu + sigma*np.random.standard_normal(sh), dtype=np.float64)
        mask = np.ones(sh, dtype=np.uint16)
        extrema = np.zeros(sh, dtype=np.uint16)
        rank = 5

        thr_low = mu + 3 * sigma
        thr_high = mu + 4 * sigma

        nmax = 0

        if DO_PRINT: print_ndarr(data, 'input data')
        t0_sec = time()
        #----------
        if tname in ('1', '2'):
            nmax = algos.local_minimums(data, mask, rank, extrema)
        elif tname in ('3', '4'):
            nmax = algos.local_maximums(data, mask, rank, extrema)
        elif tname in ('5', '6'):
            nmax = algos.local_maximums_rank1_cross(data, mask, extrema)
        elif tname == '7':
            nmax = algos.threshold_maximums(data, mask, rank, thr_low,
                                            thr_high, extrema)
        else:
            contunue
        #----------
        print('Event: %4d,  consumed time = %10.6f(sec),  nmax = %d' %
              (evnum, time() - t0_sec, nmax))

        if DO_PRINT: print_ndarr(extrema, 'output extrema')

        img1 = data
        img2 = extrema

        axim1.clear()
        axim2.clear()

        ave, rms = img1.mean(), img1.std()
        amin, amax = ave - 1 * rms, ave + 5 * rms
        gg.imshow_cbar(fig1,
                       axim1,
                       axcb1,
                       img1,
                       amin=amin,
                       amax=amax,
                       cmap='inferno')
        axim1.set_title('Event: %d, Data' % evnum, color='k', fontsize=20)
        gg.move_fig(fig1, x0=550, y0=30)

        gg.imshow_cbar(fig2,
                       axim2,
                       axcb2,
                       img2,
                       amin=0,
                       amax=5,
                       cmap='inferno')
        axim2.set_title('Event: %d, Local extrema' % evnum,
                        color='k',
                        fontsize=20)
        gg.move_fig(fig2, x0=0, y0=30)

        gg.show(mode='DO_NOT_HOLD')
    gg.show()
Exemplo n.º 9
0
def test_pf(tname):

    ##-----------------------------

    PF = V4  # default
    if tname == '1': PF = V1
    if tname == '2': PF = V2
    if tname == '3': PF = V3
    if tname == '4': PF = V4

    SKIP = 0
    EVTMAX = 10 + SKIP

    DO_PLOT_IMAGE = True
    DO_PLOT_PIXEL_STATUS = False  #True if PF in (V2,V4) else False
    DO_PLOT_CONNECED_PIXELS = False  #True if PF in (V2,V3,V4) else False
    DO_PLOT_LOCAL_MAXIMUMS = False  #True if PF == V3 else False
    DO_PLOT_LOCAL_MINIMUMS = False  #True if PF == V3 else False

    shape = (1000, 1000)

    mask = np.ones(shape, dtype=np.uint16)

    # Pixel image indexes
    #arr3d = np.array((1,shape[0],shape[1]))

    INDS = np.indices((1, shape[0], shape[1]), dtype=np.int64)
    imRow, imCol = INDS[1, :], INDS[2, :]
    #iX  = np.array(det.indexes_x(evt), dtype=np.int64) #- xoffset
    #iY  = np.array(det.indexes_y(evt), dtype=np.int64) #- yoffset

    ##-----------------------------
    fs = (8, 7)  # (11,10)
    fig1, axim1, axcb1 = gr.fig_img_cbar_axes(gr.figure(
        figsize=fs)) if DO_PLOT_IMAGE else (None, None, None)
    fig2, axim2, axcb2 = gr.fig_img_cbar_axes(gr.figure(
        figsize=fs)) if DO_PLOT_PIXEL_STATUS else (None, None, None)
    fig3, axim3, axcb3 = gr.fig_img_cbar_axes(gr.figure(
        figsize=fs)) if DO_PLOT_CONNECED_PIXELS else (None, None, None)
    fig4, axim4, axcb4 = gr.fig_img_cbar_axes(gr.figure(
        figsize=fs)) if DO_PLOT_LOCAL_MAXIMUMS else (None, None, None)
    fig5, axim5, axcb5 = gr.fig_img_cbar_axes(gr.figure(
        figsize=fs)) if DO_PLOT_LOCAL_MINIMUMS else (None, None, None)
    imsh1 = None
    imsh2 = None
    imsh3 = None
    imsh4 = None
    imsh5 = None
    ##-----------------------------

    alg = peak_finder_algos(pbits=0)

    if PF == V1:
        alg.set_peak_selection_parameters(npix_min=0,
                                          npix_max=1e6,
                                          amax_thr=0,
                                          atot_thr=0,
                                          son_min=6)

    elif PF == V2:
        alg.set_peak_selection_parameters(npix_min=0,
                                          npix_max=1e6,
                                          amax_thr=0,
                                          atot_thr=0,
                                          son_min=6)

    elif PF == V3:
        alg.set_peak_selection_parameters(npix_min=0,
                                          npix_max=1e6,
                                          amax_thr=0,
                                          atot_thr=0,
                                          son_min=8)

    elif PF == V4:
        alg.set_peak_selection_parameters(npix_min=0,
                                          npix_max=1e6,
                                          amax_thr=0,
                                          atot_thr=0,
                                          son_min=6)

    #alg.print_attributes()

    for ev in range(EVTMAX):
        ev1 = ev + 1

        if ev < SKIP: continue
        #if ev>=EVTMAX : break

        print(50 * '_', '\nEvent %04d' % ev1)

        img, peaks_sim = image_with_random_peaks(shape)

        # --- for debugging
        #np.save('xxx-image', img)
        #np.save('xxx-peaks', np.array(peaks_sim))

        #img = np.load('xxx-image-crash.npy')
        #peaks_sim = np.load('xxx-peaks-crash.npy')
        # ---

        peaks_gen = [(0, r, c, a, a * s, 9 * s * s)
                     for r, c, a, s in peaks_sim]

        t0_sec = time()

        peaks = alg.peak_finder_v3r3_d2(img, mask, rank=5, r0=7, dr=2, nsigm=3)                 if PF == V3 else\
                alg.peak_finder_v4r3_d2(img, mask, thr_low=20, thr_high=40, rank=6, r0=7, dr=2) if PF == V4 else\
                None
        #alg.peak_finder_v3r3_d2(img, rank=5, r0=7, dr=2, nsigm=3)        if PF == V3 else\
        #alg.peak_finder_v4r3_d2(img, thr_low=20, thr_high=40, rank=6, r0=7, dr=2) if PF == V3 else\

        print('  Time consumed by the peak_finder = %10.6f(sec)' %
              (time() - t0_sec))

        map2 = reshape_to_2d(alg.maps_of_pixel_status(
        )) if DO_PLOT_PIXEL_STATUS else None  # np.zeros((10,10))
        map3 = reshape_to_2d(alg.maps_of_connected_pixels(
        )) if DO_PLOT_CONNECED_PIXELS else None  # np.zeros((10,10))
        map4 = reshape_to_2d(alg.maps_of_local_maximums(
        )) if DO_PLOT_LOCAL_MAXIMUMS else None  # np.zeros((10,10))
        map5 = reshape_to_2d(alg.maps_of_local_minimums(
        )) if DO_PLOT_LOCAL_MINIMUMS else None  # np.zeros((10,10))

        print('arrays are extracted')

        #print_arr(map2, 'map_of_pixel_status')
        #print_arr(map3, 'map_of_connected_pixels')
        #maps.shape = shape

        print('Simulated peaks:')
        for i, (r0, c0, a0, sigma) in enumerate(peaks_sim):
            print('  %04d  row=%6.1f  col=%6.1f  amp=%6.1f  sigma=%6.3f' %
                  (i, r0, c0, a0, sigma))
        #plot_image(img)

        print('Found peaks:')
        print(hdr)
        reg = 'IMG'
        #for pk in peaks :
        #    seg,row,col,npix,amax,atot,rcent,ccent,rsigma,csigma,\
        #    rmin,rmax,cmin,cmax,bkgd,rms,son = pk[0:17]
        #    rec = fmt % (ev, reg, seg, row, col, npix, amax, atot, rcent, ccent, rsigma, csigma,\
        #          rmin, rmax, cmin, cmax, bkgd, rms, son) #,\
        #          #imrow, imcol, xum, yum, rum, phi)
        #    print(rec)

        for p in peaks:
            #print('  algos:', p.parameters())
            print('  row:%4d, col:%4d, npix:%4d, son:%4.1f amp_tot:%4.1f' %
                  (p.row, p.col, p.npix, p.son, p.amp_tot))

        if DO_PLOT_PIXEL_STATUS:
            gr.plot_imgcb(fig2,
                          axim2,
                          axcb2,
                          imsh2,
                          map2,
                          amin=0,
                          amax=30,
                          title='Pixel status, ev: %04d' % ev1)
            gr.move_fig(fig2, x0=0, y0=30)

        if DO_PLOT_CONNECED_PIXELS:
            cmin, cmax = (map3.min(),
                          map3.max()) if map3 is not None else (None, None)
            print('Connected pixel groups min/max:', cmin, cmax)
            gr.plot_imgcb(fig3,
                          axim3,
                          axcb3,
                          imsh3,
                          map3,
                          amin=cmin,
                          amax=cmax,
                          title='Connected pixel groups, ev: %04d' % ev1)
            gr.move_fig(fig3, x0=100, y0=30)

        if DO_PLOT_LOCAL_MAXIMUMS:
            gr.plot_imgcb(fig4,
                          axim4,
                          axcb4,
                          imsh4,
                          map4,
                          amin=0,
                          amax=10,
                          title='Local maximums, ev: %04d' % ev1)
            gr.move_fig(fig4, x0=200, y0=30)

        if DO_PLOT_LOCAL_MINIMUMS:
            gr.plot_imgcb(fig5,
                          axim5,
                          axcb5,
                          imsh5,
                          map5,
                          amin=0,
                          amax=10,
                          title='Local minimums, ev: %04d' % ev1)
            gr.move_fig(fig5, x0=300, y0=30)

        if DO_PLOT_IMAGE:
            #nda = maps_of_conpix_arc
            #nda = maps_of_conpix_equ
            #img = det.image(evt, nda)[xoffset:xoffset+xsize,yoffset:yoffset+ysize]
            #img = det.image(evt, mask_img*nda)[xoffset:xoffset+xsize,yoffset:yoffset+ysize]
            #img = det.image(evt, maps_of_conpix_equ)[xoffset:xoffset+xsize,yoffset:yoffset+ysize]

            ave, rms = img.mean(), img.std()
            amin, amax = ave - 1 * rms, ave + 8 * rms
            axim1.clear()
            if imsh1 is not None: del imsh1
            imsh1 = None
            gr.imshow_cbar(fig1, axim1, axcb1, img, amin=amin, amax=amax, extent=None,\
                           interpolation='nearest', aspect='auto', origin='upper',\
                           orientation='vertical', cmap='inferno')
            #gr.plot_imgcb(fig1, axim1, axcb1, imsh1, img, amin=amin, amax=amax, title='Image, ev: %04d' % ev1)
            fig1.canvas.set_window_title('Event: %04d random data' % ev1)
            gr.move_fig(fig1, x0=400, y0=30)

            #plot_peaks_on_img(peaks_gen, axim1, imRow, imCol, color='g', lw=5)
            plot_peaks_on_img(peaks, axim1, imRow, imCol, color='w', lw=1)

            fig1.canvas.draw()  # re-draw figure content

            #gr.plotHistogram(nda, amp_range=(-100,100), bins=200, title='Event %d' % i)
            gr.show(mode='do not hold')

    gr.show()
Exemplo n.º 10
0
def test01(tname='1', NUMBER_OF_EVENTS=10, DO_PRINT=False):

    print('local extrema : %s' % ('minimums' if tname in ('1','2')\
                             else 'maximums'))

    #sh, fs = (200,200), (11,10)
    sh, fs = (50, 50), (7, 6)
    #sh, fs = (185,388), (11,5)
    fig1, axim1, axcb1 = gr.fig_img_cbar_axes(gr.figure(figsize=fs))
    fig2, axim2, axcb2 = gr.fig_img_cbar_axes(gr.figure(figsize=fs))
    imsh1 = None
    imsh2 = None

    print('Image shape: %s' % str(sh))

    mu, sigma = 200, 25

    for evnum in range(NUMBER_OF_EVENTS):

        data = 10*np.ones(sh, dtype=np.float64) if tname in ('2','4') else\
               np.array(mu + sigma*np.random.standard_normal(sh), dtype=np.float64)
        mask = np.ones(sh, dtype=np.uint16).flatten()
        #mask = np.random.binomial(2, 0.80, data.size).astype(dtype=np.uint16)
        extrema = np.zeros(sh, dtype=np.uint16).flatten()

        rank = 5

        nmax = 0

        if DO_PRINT: print_ndarr(data, 'input data')
        t0_sec = time()

        #----------
        if tname in ('1', '2'):
            nmax = algos.local_minima_1d(data.flatten(), mask, rank, extrema)
        elif tname in ('3', '4'):
            nmax = algos.local_maxima_1d(data.flatten(), mask, rank, extrema)
        #----------
        print('Event: %4d,  consumed time = %10.6f(sec),  nmax = %d' %
              (evnum, time() - t0_sec, nmax))

        extrema.shape = sh

        if DO_PRINT: print_ndarr(extrema, 'output extrema')

        img1 = data
        img2 = extrema

        axim1.clear()
        axcb1.clear()
        if imsh1 is not None: del imsh1
        imsh1 = None

        axim2.clear()
        axcb2.clear()
        if imsh2 is not None: del imsh2
        imsh2 = None

        ave, rms = img1.mean(), img1.std()
        amin, amax = ave - 1 * rms, ave + 5 * rms
        #imsh1,cbar1=\
        gr.imshow_cbar(fig1, axim1, axcb1, img1, amin=amin, amax=amax, extent=None,\
                       interpolation='nearest', aspect='auto', origin='upper',\
                       orientation='vertical', cmap='inferno')
        fig1.canvas.set_window_title('Event: %d Random data' % evnum)
        gr.move_fig(fig1, x0=560, y0=30)

        #imsh2,cbar2=\
        gr.imshow_cbar(fig2, axim2, axcb2, img2, amin=0, amax=5, extent=None,\
                       interpolation='nearest', aspect='auto', origin='upper',\
                       orientation='vertical', cmap='inferno')
        fig2.canvas.set_window_title(
            'Event: %d Local extrema (1d-folded in image)' % evnum)
        gr.move_fig(fig2, x0=0, y0=30)

        gr.show(mode='DO_NOT_HOLD')
    gr.show()