def photonStatistics(stack):
    """ """

    number_of_images = stack.shape[0]
    photons = numpy.sum(stack, axis=(1, 2))
    avg_photons = numpy.mean(photons)
    rms_photons = numpy.std(photons)

    print("*************************")
    print("avg = %6.5e" % (avg_photons))
    print("std = %6.5e" % (rms_photons))
    print("*************************")

    # Plot histogram.
    plt.figure()
    max_photon_number = int(numpy.max(photons))
    min_photon_number = int(numpy.min(photons))
    if max_photon_number == min_photon_number:
        max_photon_number += 1

    binwidth = max_photon_number - min_photon_number
    number_of_bins = min(20, number_of_images)
    binwidth = int(binwidth / number_of_bins)

    plt.hist(photons,
             bins=range(min_photon_number, max_photon_number, binwidth),
             facecolor='red',
             alpha=0.75)
    plt.xlim([min_photon_number, max_photon_number])
    plt.xlabel("Photons")
    plt.ylabel("Histogram")
    plt.title("Photon number histogram")
def plotImage(pattern, logscale=False, offset=1e-1):
    """ Workhorse function to plot an image

    :param logscale: Whether to show the data on logarithmic scale (z axis) (default False).
    :type logscale: bool

    :param offset: Offset to apply if logarithmic scaling is on.
    :type offset: float

    """
    plt.figure()
    # Get limits.
    mn, mx = pattern.min(), pattern.max()

    x_range, y_range = pattern.shape

    if logscale:
        if mn <= 0.0:
            mn += pattern.min() + offset
            pattern = pattern.astype(float) + mn
        plt.imshow(pattern,
                   norm=mpl.colors.LogNorm(vmin=mn, vmax=mx),
                   cmap="viridis")
    else:
        plt.imshow(pattern, norm=Normalize(vmin=mn, vmax=mx), cmap='viridis')

    plt.xlabel(r'$x$ (pixel)')
    plt.ylabel(r'$y$ (pixel)')
    plt.xlim([0, x_range - 1])
    plt.ylim([0, y_range - 1])
    plt.tight_layout()
    plt.colorbar()
Beispiel #3
0
def plotImage(pattern,
              logscale=False,
              offset=1e-1,
              symlog=False,
              *argv,
              **kwargs):
    """ Workhorse function to plot an image

    :param logscale: Whether to show the data on logarithmic scale (z axis) (default False).
    :type logscale: bool

    :param offset: Offset to apply if logarithmic scaling is on.
    :type offset: float

    :param symlog: If logscale is True, to show the data on symlogarithmic scale (z axis) (default False).
    :type symlog: bool

    :return: the handles of figure and axis
    :rtype: figure,axis

    """
    fig, ax = plt.subplots()
    # Get limits.
    mn, mx = pattern.min(), pattern.max()

    x_range, y_range = pattern.shape

    if logscale:
        if mn <= 0.0:
            mn = pattern.min() + offset
            mx = pattern.max() + offset
            pattern = pattern.astype(float) + offset

        # default plot setup
        kwargs['cmap'] = kwargs.pop('cmap', "viridis")
        if symlog:
            kwargs['norm'] = kwargs.pop(
                'norm', mpl.colors.SymLogNorm(0.015, vmin=mn, vmax=mx))
        else:
            kwargs['norm'] = kwargs.pop('norm',
                                        mpl.colors.LogNorm(vmin=mn, vmax=mx))
        axes = kwargs.pop('axes', None)
        plt.imshow(pattern, *argv, **kwargs)
    else:
        kwargs['norm'] = kwargs.pop('norm', Normalize(vmin=mn, vmax=mx))
        kwargs['cmap'] = kwargs.pop('cmap', "viridis")
        plt.imshow(pattern, *argv, **kwargs)

    plt.xlabel(r'$x$ (pixel)')
    plt.ylabel(r'$y$ (pixel)')
    plt.xlim([0, x_range - 1])
    plt.ylim([0, y_range - 1])
    plt.tight_layout()
    plt.colorbar()
    return fig, ax
def plotResolutionRings(parameters):
    """
    Show resolution rings on current plot.

    :param parameters: Parameters needed to construct the resolution rings.
    :type parameters: dict

    """

    # Extract parameters.
    beam = parameters['beam']
    geom = parameters['geom']

    # Photon energy and wavelength
    E0 = beam['photonEnergy']
    lmd = 1239.8 / E0

    # Pixel dimension
    apix = geom['pixelWidth']
    # Sample-detector distance
    Ddet = geom['detectorDist']
    # Number of pixels in each dimension
    Npix = geom['mask'].shape[0]

    # Find center.
    center = 0.5 * (Npix - 1)

    # Max. scattering angle.
    theta_max = math.atan(center * apix / Ddet)
    # Min resolution.
    d_min = 0.5 * lmd / math.sin(theta_max)

    # Next integer resolution.
    d0 = 0.1 * math.ceil(d_min * 10.0)  # 10 powers to get Angstrom

    # Array of resolution rings to plot.
    ds = numpy.array([1.0, 0.5, .3])

    # Pixel numbers corresponding to resolution rings.
    Ns = Ddet / apix * numpy.arctan(numpy.arcsin(lmd / 2. / ds))

    # Plot each ring and attach a label.
    for i, N in enumerate(Ns):
        x0 = center
        X = numpy.linspace(x0 - N, x0 + N, 512)
        Y_up = x0 + numpy.sqrt(N**2 - (X - x0)**2)
        Y_dn = x0 - numpy.sqrt(N**2 - (X - x0)**2)
        plt.plot(X, Y_up, color='k')
        plt.plot(X, Y_dn, color='k')
        plt.text(x0 + 0.75 * N, x0 + 0.75 * N, "%2.1f" % (ds[i] * 10.))

    plt.xlim(0, Npix - 1)
    plt.ylim(0, Npix - 1)
Beispiel #5
0
def plotImage(pattern,
              logscale=False,
              offset=None,
              symlog=False,
              *argv,
              **kwargs):
    """ Workhorse function to plot an image

    :param logscale: Whether to show the data on logarithmic scale (z axis) (default False).
    :type logscale: bool

    :param offset: Offset to apply to the pattern.
    :type offset: float

    :param symlog: To show the data on symlogarithmic scale (z axis) (default False).
    :type symlog: bool
    """
    fig, ax = plt.subplots()
    # Get limits.
    mn, mx = pattern.min(), pattern.max()

    x_range, y_range = pattern.shape

    if offset:
        mn = pattern.min() + offset
        mx = pattern.max() + offset
        pattern = pattern.astype(float) + offset

    if (logscale and symlog):
        print('logscale and symlog are both true.\noverrided by logscale')

    # default plot setup
    if (logscale or symlog):
        kwargs['cmap'] = kwargs.pop('cmap', "viridis")
        if logscale:
            kwargs['norm'] = kwargs.pop('norm', mpl.colors.LogNorm())
        elif symlog:
            kwargs['norm'] = kwargs.pop('norm', mpl.colors.SymLogNorm(0.015))
        axes = kwargs.pop('axes', None)
        plt.imshow(pattern, *argv, **kwargs)
    else:
        kwargs['norm'] = kwargs.pop('norm', Normalize(vmin=mn, vmax=mx))
        kwargs['cmap'] = kwargs.pop('cmap', "viridis")
        plt.imshow(pattern, *argv, **kwargs)

    plt.xlabel(r'$x$ (pixel)')
    plt.ylabel(r'$y$ (pixel)')
    plt.xlim([0, x_range - 1])
    plt.ylim([0, y_range - 1])
    plt.tight_layout()
    plt.colorbar()
Beispiel #6
0
def photonStatistics(stack):
    """ """

    number_of_images = stack.shape[0]
    photons = numpy.sum(stack, axis=(1, 2))
    avg_photons = numpy.mean(photons)
    rms_photons = numpy.std(photons)

    meanPerPattern = numpy.mean(stack, axis=(1, 2))
    # average over the mean nphotons of each pattern in the stack
    avg_mean = numpy.mean(meanPerPattern)

    maxPerPattern = numpy.max(stack, axis=(1, 2))
    # average over the max nphotons of each pattern in the stack
    avg_max = numpy.mean(maxPerPattern)

    minPerPattern = numpy.min(stack, axis=(1, 2))
    # average over the min nphotons of each pattern in the stack
    avg_min = numpy.mean(minPerPattern)

    print("*************************")
    print("Photon number statistics per pattern")
    print("avg = %6.5e" % (avg_photons))
    print("std = %6.5e" % (rms_photons))
    print("Photon number statistics per pixel")
    print("avg_mean_pixel = %6.5e" % (avg_mean))
    print("avg_max_pixel = %6.5e" % (avg_max))
    print("avg_min_pixel = %6.5e" % (avg_min))
    print("*************************")

    # Plot histogram.
    plt.figure()
    max_photon_number = int(numpy.max(photons))
    min_photon_number = int(numpy.min(photons))
    if max_photon_number == min_photon_number:
        max_photon_number += 1

    binwidth = max_photon_number - min_photon_number
    number_of_bins = min(20, number_of_images)
    binwidth = int(binwidth / number_of_bins)

    plt.hist(photons,
             bins=range(min_photon_number, max_photon_number, binwidth),
             facecolor='red',
             alpha=0.75)
    plt.xlim([min_photon_number, max_photon_number])
    plt.xlabel("Photons")
    plt.ylabel("Histogram")
    plt.title("Photon number histogram")
Beispiel #7
0
def plotResolutionRings(parameters, rings=(10, 5.0, 3.5), half=True):
    """
    Show resolution rings on current plot.

    :param parameters: Parameters needed to construct the resolution rings.
    :type parameters: dict
    :param rings: the rings shown on the figure
    :type rings: list
    :param half: show half period resolution (True, default) or full period resolution (False)
    :type half: bool

    """

    # Extract parameters.
    beam = parameters['beam']
    geom = parameters['geom']

    # Photon energy and wavelength
    E0 = beam['photonEnergy']
    lmd = 1239.8 / E0

    # Pixel dimension
    apix = geom['pixelWidth']
    # Sample-detector distance
    Ddet = geom['detectorDist']
    # Number of pixels in each dimension
    Npix = geom['mask'].shape[0]

    # Find center.
    center = 0.5 * (Npix - 1)

    # Max. scattering angle.
    theta_max = math.atan(center * apix / Ddet)
    # Min resolution.
    if (half):
        d_min = 0.5 * lmd / math.sin(theta_max / 2.0) / 2.0
    else:
        d_min = 0.5 * lmd / math.sin(theta_max / 2.0)

    # Next integer resolution.
    d0 = 0.1 * math.ceil(d_min * 10.0)  # 10 powers to get Angstrom

    # Array of resolution rings to plot.
    ds = numpy.array(rings) / 10  # nm

    # Pixel numbers corresponding to resolution rings.
    if (half):
        Ns = Ddet / apix * numpy.tan(numpy.arcsin(lmd / 2. / ds / 2.) * 2)
    else:
        Ns = Ddet / apix * numpy.tan(numpy.arcsin(lmd / 2. / ds) * 2)

    # Plot each ring and attach a label.
    for i, N in enumerate(Ns):
        x0 = center
        X = numpy.linspace(x0 - N, x0 + N, 512)
        Y_up = x0 + numpy.sqrt(N**2 - (X - x0)**2)
        Y_dn = x0 - numpy.sqrt(N**2 - (X - x0)**2)
        plt.plot(X, Y_up, color='k')
        plt.plot(X, Y_dn, color='k')
        plt.text(x0 + 0.75 * N,
                 x0 + 0.75 * N,
                 "%2.1f" % (ds[i] * 10.),
                 color='red')

    plt.xlim(0, Npix - 1)
    plt.ylim(0, Npix - 1)