Пример #1
0
 def show():
     log( "rmin", rmin)
     log( "rmax", rmax)
     import pyimgalgos.GlobalGraphics as gg
     gg.plotImageLarge(imarr, amp_range=(rmin, rmax), title = title, origin = 'lower')
     if show_plot:
         gg.show()
Пример #2
0
 def show():
     log("rmin", rmin)
     log("rmax", rmax)
     import pyimgalgos.GlobalGraphics as gg
     gg.plotImageLarge(imarr,
                       amp_range=(rmin, rmax),
                       title=title,
                       origin='lower')
     if show_plot:
         gg.show()
def draw_times(ax, wf, wt):
    #wf -= wf[0:1000].mean()
    edges = find_edges(wf, BASE, THR, CFR, DEADTIME, LEADINGEDGE)
    # pairs of (amplitude,sampleNumber)
    print 'MCP edges'
    print edges

    for (amp, ind) in edges:
        x0 = wt[int(ind)]
        xarr = (x0, x0)
        yarr = (amp, -amp)
        gg.drawLine(ax, xarr, yarr, s=10, linewidth=1, color='k')
Пример #4
0
def plot_lut_as_omega_vs_qh(list_oq) :
    """Plots content of the lookup table as an image of intensities for omega(deg) vs. hq(1/A)
    """
    img = lut_as_image(list_oq)
    print_ndarr(img, 'img')

    img_range = (bpq.vmin(), bpq.vmax(), bpomega.vmax(), bpomega.vmin()) 
    axim = gg.plotImageLarge(img, img_range=img_range, amp_range=None, figsize=(15,13),\
                      title='Plot reconstructed from look-up table', origin='upper',\
                             window=(0.06,  0.06, 0.94, 0.92), cmap='gray_r')
    axim.set_xlabel('$q_{H}$ ($1/\AA$)', fontsize=18)
    axim.set_ylabel('$\omega$ (degree)', fontsize=18)
    gg.save('img-lut-prob-omega-vs-qh.png', pbits=1)
    gg.show('do not block')
Пример #5
0
def plot_lut_as_omega_vs_qh(list_oq):
    """Plots content of the lookup table as an image of intensities for omega(deg) vs. hq(1/A)
    """
    img = lut_as_image(list_oq)
    print_ndarr(img, 'img')

    img_range = (bpq.vmin(), bpq.vmax(), bpomega.vmax(), bpomega.vmin())
    axim = gg.plotImageLarge(img, img_range=img_range, amp_range=None, figsize=(15,13),\
                      title='Plot reconstructed from look-up table', origin='upper',\
                             window=(0.06,  0.06, 0.94, 0.92), cmap='gray_r')
    axim.set_xlabel('$q_{H}$ ($1/\AA$)', fontsize=18)
    axim.set_ylabel('$\omega$ (degree)', fontsize=18)
    gg.save('img-lut-prob-omega-vs-qh.png', pbits=1)
    gg.show('do not block')
Пример #6
0
def draw_times(ax, wf, wt):

    #extrema = 0.1* wf_extremas(ax, wf, wt, rank=10)
    #gg.drawLine(ax, wt, extrema, s=10, linewidth=1, color='k')
    #return

    #wf -= wf[0:1000].mean()
    #edges = find_edges(wf, BASE, THR, CFR, DEADTIME, LEADINGEDGE)

    edges = wf_extremas(ax, wf, wt, rank=10)
    # pairs of (amplitude,sampleNumber)
    print ' nhits:', edges.shape[0],
    print ' edges:', edges

    for (amp, ind) in edges:
        x0 = wt[int(ind)]
        xarr = (x0, x0)
        yarr = (amp, -amp)
        gg.drawLine(ax, xarr, yarr, s=10, linewidth=1, color='k')
Пример #7
0
def plot_xy_lattice(list_oq) :
    """Plots image of the crystal lattice, using list of [(omega,<1-d-array-of-intensities-for-omega>)]
    """

    img = xy_lattice_image(list_oq)
    print_ndarr(img, 'img')

    #--- Convolution of image 
    from scipy.signal import convolve2d
    g2d = arr_2d_gauss(2, 1.5)
    img = convolve2d(img, g2d, mode='same', boundary='fill', fillvalue=0)
    #---

    img_range = (bpq.vmin(), bpq.vmax(), bpq.vmin(), bpq.vmax()) 
    axim = gg.plotImageLarge(img, img_range=img_range, amp_range=None, figsize=(15,13),\
                      title='Lattice', origin='upper',\
                             window=(0.08,  0.06, 0.94, 0.92)) # , cmap='gray_r')
    axim.set_xlabel('Reciprocal x ($1/\AA$)', fontsize=18)
    axim.set_ylabel('Reciprocal y ($1/\AA$)', fontsize=18)
    gg.save('img-lut-lattice-xy.png', pbits=1)
    gg.show()
Пример #8
0
def plot_xy_lattice(list_oq):
    """Plots image of the crystal lattice, using list of [(omega,<1-d-array-of-intensities-for-omega>)]
    """

    img = xy_lattice_image(list_oq)
    print_ndarr(img, 'img')

    #--- Convolution of image
    from scipy.signal import convolve2d
    g2d = arr_2d_gauss(2, 1.5)
    img = convolve2d(img, g2d, mode='same', boundary='fill', fillvalue=0)
    #---

    img_range = (bpq.vmin(), bpq.vmax(), bpq.vmin(), bpq.vmax())
    axim = gg.plotImageLarge(img, img_range=img_range, amp_range=None, figsize=(15,13),\
                      title='Lattice', origin='upper',\
                             window=(0.08,  0.06, 0.94, 0.92)) # , cmap='gray_r')
    axim.set_xlabel('Reciprocal x ($1/\AA$)', fontsize=18)
    axim.set_ylabel('Reciprocal y ($1/\AA$)', fontsize=18)
    gg.save('img-lut-lattice-xy.png', pbits=1)
    gg.show()
Пример #9
0
def test03(ntest, prefix='fig-v01'):
    """Test for 2-d binning of the restricted rad-phi range of entire image
    """
    from time import time
    import pyimgalgos.GlobalGraphics as gg
    from PSCalib.GeometryAccess import img_from_pixel_arrays

    arr, geo = data_geo(ntest)

    iX, iY = geo.get_pixel_coord_indexes()
    X, Y, Z = geo.get_pixel_coords()
    mask = geo.get_pixel_mask(mbits=0377).flatten()

    t0_sec = time()

    rb = RadialBkgd(X, Y, mask, nradbins=200, nphibins=32, phiedges=(-20, 240), radedges=(10000,80000)) if ntest in (51,52)\
    else RadialBkgd(X, Y, mask, nradbins=  5, nphibins= 8, phiedges=(-20, 240), radedges=(10000,80000))
    #rb = RadialBkgd(X, Y, mask, nradbins=3, nphibins=8, phiedges=(240, -20), radedges=(80000,10000)) # v3

    print 'RadialBkgd initialization time %.3f sec' % (time() - t0_sec)

    #print 'npixels_per_bin:',   rb.npixels_per_bin()
    #print 'intensity_per_bin:', rb.intensity_per_bin(arr)
    #print 'average_per_bin:',   rb.average_per_bin(arr)

    t0_sec = time()
    nda, title = arr, None
    if ntest == 41: nda, title = arr, 'averaged data'
    elif ntest == 42: nda, title = rb.pixel_rad(), 'pixel radius value'
    elif ntest == 43: nda, title = rb.pixel_phi(), 'pixel phi value'
    elif ntest == 44:
        nda, title = rb.pixel_irad() + 2, 'pixel radial bin index'
    elif ntest == 45:
        nda, title = rb.pixel_iphi() + 2, 'pixel phi bin index'
    elif ntest == 46:
        nda, title = rb.pixel_iseq(
        ) + 2, 'pixel sequential (rad and phi) bin index'
    elif ntest == 47:
        nda, title = mask, 'mask'
    elif ntest == 48:
        nda, title = rb.pixel_avrg(nda), 'averaged radial background'
    elif ntest == 49:
        nda, title = rb.subtract_bkgd(nda) * mask, 'background-subtracted data'
    elif ntest == 50:
        nda, title = rb.bin_avrg_rad_phi(nda), 'r-phi'
    elif ntest == 51:
        nda, title = rb.pixel_avrg_interpol(
            nda), 'averaged radial interpolated background'
    elif ntest == 52:
        nda, title = rb.subtract_bkgd_interpol(
            nda) * mask, 'interpol-background-subtracted data'
    else:
        print 'Test %d is not implemented' % ntest
        return

    print 'Get %s n-d array time %.3f sec' % (title, time() - t0_sec)

    img = img_from_pixel_arrays(
        iX, iY, nda) if not ntest in (50, ) else nda  # [100:300,:]

    colmap = 'jet'  # 'cubehelix' 'cool' 'summer' 'jet' 'winter' 'gray'

    da = (nda.min() - 1, nda.max() + 1)
    ds = da

    if ntest in (41, 48, 49, 50, 51):
        ave, rms = nda.mean(), nda.std()
        da = ds = (ave - 2 * rms, ave + 3 * rms)

    elif ntest in (52, ):
        colmap = 'gray'
        ds = da = (-20, 20)

    gg.plotImageLarge(img,
                      amp_range=da,
                      figsize=(14, 12),
                      title=title,
                      cmap=colmap)
    gg.save('%s-%02d-img.png' % (prefix, ntest))

    gg.hist1d(nda, bins=None, amp_range=ds, weights=None, color=None, show_stat=True, log=False, \
           figsize=(6,5), axwin=(0.18, 0.12, 0.78, 0.80), \
           title=None, xlabel='Pixel value', ylabel='Number of pixels', titwin=title)
    gg.save('%s-%02d-his.png' % (prefix, ntest))

    gg.show()

    print 'End of test for %s' % title
Пример #10
0
def test01(ntest, prefix='fig-v01'):
    """Test for radial 1-d binning of entire image.
    """
    from time import time
    import pyimgalgos.GlobalGraphics as gg
    from PSCalib.GeometryAccess import img_from_pixel_arrays

    arr, geo = data_geo(ntest)

    t0_sec = time()
    iX, iY = geo.get_pixel_coord_indexes()
    X, Y, Z = geo.get_pixel_coords()
    mask = geo.get_pixel_mask(mbits=0377).flatten()
    print 'Time to retrieve geometry %.3f sec' % (time() - t0_sec)

    t0_sec = time()
    rb = RadialBkgd(X, Y, mask, nradbins=500, nphibins=1)  # v1
    print 'RadialBkgd initialization time %.3f sec' % (time() - t0_sec)

    t0_sec = time()
    nda, title = arr, None
    if ntest == 1: nda, title = arr, 'averaged data'
    elif ntest == 2: nda, title = rb.pixel_rad(), 'pixel radius value'
    elif ntest == 3: nda, title = rb.pixel_phi(), 'pixel phi value'
    elif ntest == 4: nda, title = rb.pixel_irad() + 2, 'pixel radial bin index'
    elif ntest == 5: nda, title = rb.pixel_iphi() + 2, 'pixel phi bin index'
    elif ntest == 6:
        nda, title = rb.pixel_iseq(
        ) + 2, 'pixel sequential (rad and phi) bin index'
    elif ntest == 7:
        nda, title = mask, 'mask'
    elif ntest == 8:
        nda, title = rb.pixel_avrg(nda), 'averaged radial background'
    elif ntest == 9:
        nda, title = rb.subtract_bkgd(nda) * mask, 'background-subtracted data'

    else:
        t1_sec = time()
        pf = polarization_factor(rb.pixel_rad(), rb.pixel_phi(),
                                 94e3)  # Z=94mm
        print 'Time to evaluate polarization correction factor %.3f sec' % (
            time() - t1_sec)

        if ntest == 10: nda, title = pf, 'polarization factor'
        elif ntest == 11:
            nda, title = arr * pf, 'polarization-corrected averaged data'
        elif ntest == 12:
            nda, title = rb.subtract_bkgd(
                arr *
                pf) * mask, 'polarization-corrected background subtracted data'
        elif ntest == 13:
            nda, title = rb.pixel_avrg(
                arr * pf), 'polarization-corrected averaged radial background'
        elif ntest == 14:
            nda, title = rb.pixel_avrg_interpol(
                arr * pf
            ) * mask, 'polarization-corrected interpolated radial background'
        elif ntest == 15:
            nda, title = rb.subtract_bkgd_interpol(
                arr * pf
            ) * mask, 'polarization-corrected interpolated radial background-subtracted data'

        else:
            print 'Test %d is not implemented' % ntest
            return

    print 'Get %s n-d array time %.3f sec' % (title, time() - t0_sec)

    img = img_from_pixel_arrays(
        iX, iY, nda) if not ntest in (21, ) else nda[100:300, :]

    da, ds = None, None
    colmap = 'jet'  # 'cubehelix' 'cool' 'summer' 'jet' 'winter'
    if ntest in (2, 3, 4, 5, 6, 7):
        da = ds = (nda.min() - 1., nda.max() + 1.)

    if ntest in (12, 15):
        ds = da = (-20, 20)
        colmap = 'gray'

    else:
        ave, rms = nda.mean(), nda.std()
        da = ds = (ave - 2 * rms, ave + 3 * rms)

    gg.plotImageLarge(img,
                      amp_range=da,
                      figsize=(14, 12),
                      title=title,
                      cmap=colmap)
    gg.save('%s-%02d-img.png' % (prefix, ntest))

    gg.hist1d(nda, bins=None, amp_range=ds, weights=None, color=None, show_stat=True, log=False, \
           figsize=(6,5), axwin=(0.18, 0.12, 0.78, 0.80), \
           title=None, xlabel='Pixel value', ylabel='Number of pixels', titwin=title)
    gg.save('%s-%02d-his.png' % (prefix, ntest))

    gg.show()

    print 'End of test for %s' % title
Пример #11
0
def make_index_table(prefix='./v01-') :

    from pyimgalgos.GlobalUtils import str_tstamp
    fname = '%s**t-cxif5315-r0169-%s.txt' % (prefix, str_tstamp())
    fout = open(fname,'w')
    fout.write('# file name: %s\n' % fname)

    #------------------------------
    # Photon energy
    Egamma_eV  = 6003.1936                               # eV SIOC:SYS0:ML00:AO541
    wavelen_nm = wavelength_nm_from_energy_ev(Egamma_eV) # nm
    evald_rad  = wave_vector_value(Egamma_eV)            # 1/A
    #-------
    sigma_ql   = 0.002 * evald_rad
    sigma_qt   = 0.002 * evald_rad
    #-------
    rec  = '\n# photon energy = %.4f eV' % (Egamma_eV)\
         + '\n# wavelength = %.4f A' % (wavelen_nm*10)\
         + '\n# wave number/Evald radius k = 1/lambda = %.6f 1/A' % (evald_rad)\
         + '\n# sigma_ql = %.6f 1/A (approximately = k * <pixel size>/' % (sigma_ql)\
         + '\n# sigma_qt = %.6f 1/A (approximately = k * <pixel size>/' % (sigma_qt)\
         + '<sample-to-detector distance> = k*100um/100mm)'\
         + '\n# 3*sigma_ql = %.6f 1/A\n' % (3*sigma_ql)\
         + '\n# 3*sigma_qt = %.6f 1/A\n' % (3*sigma_qt)
    print rec
    fout.write(rec)

    #------------------------------
    # Lattice parameters
    # from previous analysis note:
    #a, b, c = 18.36, 26.65, 4.81        # Angstrom
    #alpha, beta, gamma = 90, 90, 77.17  # 180 - 102.83 degree
    a= 18.55 # Angstrom
    b, c = 1.466*a, 0.262*a              # Angstrom
    alpha, beta, gamma = 90, 90, 78.47   # 180 - 101.53 degree
    hmax, kmax, lmax = 4, 6, 0           # size of lattice to consider
    #hmin, kmin, lmin =-4,-6, 0          # size of lattice to consider
    hmin, kmin, lmin = None, None, None  # default [-hmax,hmax], [-kmax,kmax],

    a1, a2, a3 = triclinic_primitive_vectors(a, b, c, alpha, beta, gamma)
    b1, b2, b3 = reciprocal_from_bravias(a1, a2, a3)

    msg1 = '\n# Triclinic crystal cell parameters:'\
         + '\n#   a = %.2f A\n#   b = %.2f A\n#   c = %.2f A' % (a, b, c)\
         + '\n#   alpha = %.2f deg\n#   beta  = %.2f deg\n#   gamma = %.2f deg' % (alpha, beta, gamma)

    msg2 = '\n# 3-d space primitive vectors:\n#   a1 = %s\n#   a2 = %s\n#   a3 = %s' %\
           (str(a1), str(a2), str(a3))

    msg3 = '\n# reciprocal space primitive vectors:\n#   b1 = %s\n#   b2 = %s\n#   b3 = %s' %\
           (str(b1), str(b2), str(b3))

    rec = '%s\n%s\n%s\n' % (msg1, msg2, msg3)
    print rec
    fout.write(rec)

    fout.write('\n# %s\n\n' % (89*'_'))

    #for line in triclinic_primitive_vectors.__doc__.split('\n') : fout.write('\n# %s' % line)

    test_lattice       (b1, b2, b3, hmax, kmax, lmax, np.float32, hmin, kmin, lmin)
    lattice_node_radius(b1, b2, b3, hmax, kmax, lmax, np.float32, '%10.6f', hmin, kmin, lmin)
    lattice_node_radius(b1, b2, b3, hmax, kmax, 1,    np.float32, '%10.6f', hmin, kmin, lmin)

    #------------------------------
    #return

    #------------------------------
    # binning for look-up table and plots

    # bin parameters for q in units of k = Evald's sphere radius [1/A]
    bpq = BinPars((-0.25, 0.25), 1000, vtype=np.float32, endpoint=False)

    # bin parameters for omega [degree] - fiber rotation angle around axis
    bpomega = BinPars((0.,  180.), 360, vtype=np.float32, endpoint=False)
    
    # bin parameters for beta [degree] - fiber axis tilt angle
    #bpbeta = BinPars((15.,  195.),  2, vtype=np.float32, endpoint=True)
    #bpbeta = BinPars((15.,   15.),  1, vtype=np.float32, endpoint=False)
    #bpbeta = BinPars((5.,    25.),  2, vtype=np.float32, endpoint=True)
    bpbeta  = BinPars((0.,    50.), 11, vtype=np.float32, endpoint=True)
    bpbeta2 = BinPars((180., 230.), 11, vtype=np.float32, endpoint=True)
    str_beta = 'for-beta:%s' % (bpbeta.strrange)
     
    print '\n%s\nIndexing lookup table\n' % (91*'_')
    lut  = make_lookup_table_v2(b1, b2, b3, hmax, kmax, lmax, np.float32, evald_rad, sigma_ql, sigma_qt, fout, bpq, bpomega, bpbeta, hmin, kmin, lmin)
    lut2 = make_lookup_table_v2(b1, b2, b3, hmax, kmax, lmax, np.float32, evald_rad, sigma_ql, sigma_qt, fout, bpq, bpomega, bpbeta2, hmin, kmin, lmin)

    fout.close()
    print '\nIndexing lookup table is saved in the file: %s' % fname

    #------------------------------
    # produce and save plots
    import pyimgalgos.GlobalGraphics as gg

    img = lut # or lut2
    img = lut + lut2

    img_range = (bpq.vmin, bpq.vmax, bpomega.vmax, bpomega.vmin) 
    axim = gg.plotImageLarge(lut, img_range=img_range, amp_range=None, figsize=(15,13),\
                      title='Non-symmetrized for beta', origin='upper', window=(0.05,  0.06, 0.94, 0.94))
    axim.set_xlabel('$q_{H}$ ($1/\AA$)', fontsize=18)
    axim.set_ylabel('$\omega$ (degree)', fontsize=18)
    gg.save('%splot-img-prob-omega-vs-qh-%s.png' % (prefix, str_beta), pbits=1)

    axim = gg.plotImageLarge(img, img_range=img_range, amp_range=None, figsize=(15,13),\
                      title='Symmetrized for beta (beta, beta+pi)', origin='upper', window=(0.05,  0.06, 0.94, 0.94))
    axim.set_xlabel('$q_{H}$ ($1/\AA$)', fontsize=18)
    axim.set_ylabel('$\omega$ (degree)', fontsize=18)
    gg.save('%splot-img-prob-omega-vs-qh-sym-%s.png' % (prefix, str_beta), pbits=1)

    arrhi = np.sum(img,0)    
    fighi, axhi, hi = gg.hist1d(bpq.binedges, bins=bpq.nbins-1, amp_range=(bpq.vmin, bpq.vmax), weights=arrhi,\
                                color='b', show_stat=True, log=False,\
                                figsize=(15,5), axwin=(0.05, 0.12, 0.85, 0.80),\
                                title=None, xlabel='$q_{H}$ ($1/\AA$)', ylabel='Intensity', titwin=None)
    gg.show()

    gg.save_fig(fighi, '%splot-his-prob-vs-qh-%s.png' % (prefix, str_beta), pbits=1)

    qh_weight = zip(bpq.bincenters, arrhi)
    fname = '%sarr-qh-weight-%s.npy' % (prefix, str_beta)
    print 'Save qh:weigt array in file %s' % fname
    np.save(fname, qh_weight)
Пример #12
0
def plot_lattice(b1 = (1.,0.,0.), b2 = (0.,1.,0.), b3 = (0.,0.,1.),\
                 hmax=3, kmax=2, lmax=1, cdtype=np.float32,\
                 evald_rad=0.5, qtol=0.01, prefix='', do_movie=False, delay=400,\
                 hmin=None, kmin=None, lmin=None, title_add='') :
    """Plots 2-d reciprocal space lattice, evald sphere,
       generates series of plots for rotated lattice and movie from these plots.

       - do_movie = True/False - on/off production of movie
       - delay - is a time in msec between movie frames.
    """

    import matplotlib.pyplot as plt
    import pyimgalgos.GlobalGraphics as gg
    
    print '\nIn %s' % sys._getframe().f_code.co_name
    print '%s\nTest lattice with default parameters' % (80*'_')

    x, y, z, r, h, k, l = lattice(b1, b2, b3, hmax, kmax, lmax, cdtype, hmin, kmin, lmin)

    x.shape = (x.size,)
    y.shape = (y.size,)
    z.shape = (z.size,)

    xlimits = ylimits = (-0.3, 0.3) # plot limits in (1/A)
    #ylimits = (-0.4, 0.4) # plot limits in (1/A)
    #xlimits = (-0.5, 0.3) # plot limits in (1/A)

    fig, ax = gg.plotGraph(x,y, figsize=(8,7.5), window=(0.17, 0.10, 0.78, 0.84), pfmt='bo')

    ax.set_xlim(xlimits)
    ax.set_ylim(ylimits)
    ax.set_xlabel('Reciprocal x ($1/\AA$)', fontsize=18)
    ax.set_ylabel('Reciprocal y ($1/\AA$)', fontsize=18)
    gg.save_fig(fig, '%sreciprocal-space-lattice.png' % prefix, pbits=1)

    lst_omega = range(0,180,2) if do_movie else range(0,11,10)
    #lst_omega = range(0,180,5) if do_movie else range(0,13,11)
    #lst_omega = range(0,180,45) if do_movie else range(0,13,11)

    beta_deg = 0
    for omega_deg in lst_omega :

        xrot1, yrot1 = rotation(x, y, omega_deg)
        xrot2, zrot2 = rotation(xrot1, z, beta_deg)        
        dr, qv, qh, qt, ql = q_components(xrot2, yrot1, zrot2, evald_rad)

        xhit = [xr for dq,xr in zip(dr.flatten(), xrot2.flatten()) if math.fabs(dq)<qtol]
        yhit = [yr for dq,yr in zip(dr.flatten(), yrot1.flatten()) if math.fabs(dq)<qtol]

        #fig, ax = gg.plotGraph(xrot2, yrot1, figsize=(8,7.5), window=(0.15, 0.10, 0.78, 0.84), pfmt='bo')
        ax.cla()
        ax.set_xlim(xlimits)
        ax.set_ylim(ylimits)
        ax.plot(xrot1, yrot1, 'yo')
        if len(xhit)>0 and len(yhit)>0 : ax.plot(xhit, yhit, 'bo')

        tit = 'beta=%.0f omega=%.0f' % (beta_deg, omega_deg)
        if title_add : tit += ' %s' % (title_add)
        ax.set_title(tit, color='k', fontsize=12)
        ax.set_xlabel('Reciprocal x ($1/\AA$)', fontsize=18)
        ax.set_ylabel('Reciprocal y ($1/\AA$)', fontsize=18)
        gg.drawCenter(ax, (-evald_rad,0), s=0.04, linewidth=2, color='k')
        gg.drawCircle(ax, (-evald_rad,0), evald_rad, linewidth=1, color='k', fill=False)
        fig.canvas.draw()
        gg.show('Do not hold!')
        gg.save_fig(fig, '%slattice-rotated-beta%03d-omega%03d.png'%\
                    (prefix, int(beta_deg), int(omega_deg)), pbits=1)

    if do_movie :
        import os
        #dir_movie = 'movie'
        #os.system('mkdir %s'% dir_movie)
        cmd = 'convert -delay %f %slattice-rotated-beta*.png movie.gif' % (delay, prefix)
        print 'Wait for completion of the command: %s' % cmd
        os.system(cmd)
        print 'DONE!'
    
    gg.show()
Пример #13
0
Rum.shape    = Phi.shape    = shape_cspad

#addhdr = '  Evnum  Reg  Seg  Row  Col  Npix      Amax      Atot   rcent   ccent '+\
#         'rsigma  csigma rmin rmax cmin cmax    bkgd     rms     son  imrow   imcol     x[um]     y[um]     r[um]  phi[deg]'
addhdr = '  Evnum  Reg  Seg  Row  Col  Npix      Amax      Atot   rcent   ccent '+\
         'rsigma  csigma    bkgd     rms     son  imrow   imcol     x[um]     y[um]     r[um]  phi[deg]'

fmt = '%7d  %3s  %3d %4d %4d  %4d  %8.1f  %8.1f  %6.1f  %6.1f %6.2f  %6.2f'+\
      '  %6.2f  %6.2f  %6.2f'+\
      ' %6d  %6d  %8.0f  %8.0f  %8.0f  %8.2f'

pstore = PeakStore(env, runnum, prefix='peaks', add_header=addhdr, pbits=1)
pstore.print_attrs()

##-----------------------------
fig, axim, axcb = gg.fig_axes() if DO_PLOT else (None, None, None)

fighi, axhi = None, None
if DO_SPEC :
    fighi = gr.figure(figsize=(6,5), title='Spectrum of pixel intensities', move=(800,0))
    axhi  = gr.add_axes(fighi, (0.17, 0.12, 0.78, 0.78))

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

def geo_pars(s,r,c) :
    inds = (s,r,c)
    return imRow[inds], imCol[inds], Xum[inds], Yum[inds], Rum[inds], Phi[inds]

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

t0_sec_evloop = time()
Пример #14
0
def test_pf(tname):

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

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

    SKIP = 0
    EVTMAX = 5 + SKIP

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

    shape = (500, 500)

    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)
    ##-----------------------------
    fig5, axim5, axcb5, imsh5 = gg.fig_axim_axcb_imsh(
        figsize=fs) if DO_PLOT_LOCAL_MINIMUMS else (None, None, None, None)
    fig4, axim4, axcb4, imsh4 = gg.fig_axim_axcb_imsh(
        figsize=fs) if DO_PLOT_LOCAL_MAXIMUMS else (None, None, None, None)
    fig3, axim3, axcb3, imsh3 = gg.fig_axim_axcb_imsh(
        figsize=fs) if DO_PLOT_CONNECED_PIXELS else (None, None, None, None)
    fig1, axim1, axcb1, imsh1 = gg.fig_axim_axcb_imsh(
        figsize=fs) if DO_PLOT_IMAGE else (None, None, None, None)
    ##-----------------------------

    #alg = PyAlgos(windows=None, mask=None, pbits=10) # 0177777)
    alg = psalgos.peak_finder_algos(seg=0, 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=1,
                                          npix_max=1e6,
                                          amax_thr=0,
                                          atot_thr=0,
                                          son_min=8)

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

    alg.print_attributes()

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

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

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

        add_water_ring = False if PF == V4 else True
        img, peaks_sim = image_with_random_peaks(shape, add_water_ring)

        # --- 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=4, r0=6, dr=3, nsigm=3) if PF == V3 else\
                alg.peak_finder_v4r3_d2(img, mask, thr_low=20, thr_high=40, rank=4, r0=5, dr=3)

        #peaks = alg.list_of_peaks_selected()
        #peaks_tot = alg.list_of_peaks()

        #        peaks = alg.peak_finder_v1(img, thr_low=20, thr_high=40, radius=6, dr=2) if PF == V1 else\
        #                alg.peak_finder_v2r1(img, thr=30, r0=7, dr=2)                    if PF == V2 else\
        #                alg.peak_finder_v3r2(img, rank=5, r0=7, dr=2, nsigm=3)           if PF == V3 else\
        #                alg.peak_finder_v4r2(img, thr_low=20, thr_high=40, rank=6, r0=7, dr=2)
        #                #alg.peak_finder_v4r2(img, thr_low=20, thr_high=40, rank=6, r0=3.3, dr=0)

        print 'Time consumed by the peak_finder = %10.6f(sec) number of simulated/found peaks: %d/%d'%\
              (time()-t0_sec, len(peaks_sim), len(peaks))

        #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))

        map3 = reshape_to_2d(alg.connected_pixels(
        )) if DO_PLOT_CONNECED_PIXELS else None  # np.zeros((10,10))
        map4 = reshape_to_2d(alg.local_maxima(
        )) if DO_PLOT_LOCAL_MAXIMUMS else None  # np.zeros((10,10))
        map5 = reshape_to_2d(alg.local_minima(
        )) if DO_PLOT_LOCAL_MINIMUMS else None  # np.zeros((10,10))

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

        #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'

        peaks_rec = []

        if False:
            for pk in peaks:
                seg,row,col,npix,amax,atot,rcent,ccent,rsigma,csigma,\
                rmin,rmax,cmin,cmax,bkgd,rms,son = pk.parameters()
                #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)
                peaks_rec.append((seg, row, col, amax, atot, npix))
                print rec

        #peaks_gen = [(0, r, c, a, a*s, 9*s*s) for r,c,a,s in peaks_sim]
        #peaks_rec = [(p.seg, p.row, p.col, p.amp_max, p.amp_tot, p.npix) for p in peaks]
        #s, r, c, amax, atot, npix = rec[0:6]

        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
            gg.plot_imgcb(fig3,
                          axim3,
                          axcb3,
                          imsh3,
                          map3,
                          amin=cmin,
                          amax=cmax,
                          title='Connected pixel groups, ev: %04d' % ev1)
            gg.move_fig(fig3, x0=100, y0=30)

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

        if DO_PLOT_LOCAL_MINIMUMS:
            gg.plot_imgcb(fig5,
                          axim5,
                          axcb5,
                          imsh5,
                          map5,
                          amin=0,
                          amax=10,
                          title='Local minimums, ev: %04d' % ev1)
            gg.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
            gg.plot_imgcb(fig1,
                          axim1,
                          axcb1,
                          imsh1,
                          img,
                          amin=amin,
                          amax=amax,
                          title='Image, ev: %04d' % ev1)
            gg.move_fig(fig1, x0=400, y0=30)

            gg.plot_peaks_on_img(peaks_gen,
                                 axim1,
                                 imRow,
                                 imCol,
                                 color='g',
                                 lw=2)  #, pbits=3)
            gg.plot_peaks_on_img(peaks_rec, axim1, imRow, imCol,
                                 color='w')  #, pbits=3)

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

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

    gg.show()
Пример #15
0
def plot_image(img, img_range=None, amp_range=None, figsize=(12, 10)):
    #import pyimgalgos.GlobalGraphics as gg
    axim = gg.plotImageLarge(img, img_range, amp_range, figsize)
    gg.show()
Пример #16
0
imCol = np.select([iY < yoffset], [0], default=iY - yoffset)

# Pixel coordinates [um] (transformed as needed)
Xum = det.coords_y(runnum)
Yum = -det.coords_x(runnum)

# Derived pixel raduius in [um] and angle phi[degree]
Rum = np.sqrt(Xum * Xum + Yum * Yum)
Phi = np.arctan2(Yum, Xum) * 180 / np.pi

imRow.shape  = imCol.shape  = \
Xum.shape    = Yum.shape    = \
Rum.shape    = Phi.shape    = det.shape()

#------------------------------
fig1, axim1, axcb1, imsh1 = gg.fig_axim_axcb_imsh(figsize=(12, 11))
#------------------------------

t0_sec_evloop = time()
nda = None
peaks = None

# loop over events in data set
myrun = next(ds.runs())
for evnum, evt in enumerate(myrun.events()):

    if evnum % 100 == 0: print 'Event %d' % (evnum)

    if evnum < SKIP: continue
    if evnum >= EVTMAX: break