Ejemplo n.º 1
0
def plotmask(maskwoutput=None, maxr=None, xray_image=None,
             position_matrix=None):
    """
    Plots the mask metrics allowing for evaluation of mask quality
    """

    # highper,lowper,totalper, mask, imask,StatsA=maskwoutput
    highper, lowper, totalper, mask, imask = maskwoutput
    # May need matplotlib help from Tom on this
    plt.ioff()
    plt.clf()
    # plot the graph of how the mask depends on radial distance
    # TODO: use Q instead of r in the final product?
    plt.plot(np.arange(0, maxr + 1, 1), highper[:], '-',
             np.arange(0, maxr + 1, 1), lowper[:], 'o',
             np.arange(0, maxr + 1, 1), totalper[:], '^')
    plt.show()
    # Plot the mask itself
    # plot the overlay of the mask and the image
    mask = plt.imshow(mask)
    plt.show()
    imagemask = plt.imshow(xray_image * imask)
    plt.show()
    t = np.arange(0, maxr, 1)
    plt.plot(t, Calculate.mean1d(xray_image,
                                 position_matrix=position_matrix * imask,
                                 step=1), 'b',
             # t, Median1D(xray_image, max=maxr, step=1, position_matrix=position_matrix*imask), 'r',\
             # t,Median1D(xray_image, max=maxr, step=1, position_matrix=position_matrix*imask)-Mean1D(xray_image, max=maxr, step=1, position_matrix=position_matrix*imask)
    )
    plt.show()

    oldstd = np.sqrt(
        Calculate.variance1d(xray_image, position_matrix=position_matrix,
                             max=maxr, step=1))
    newstd = np.sqrt(Calculate.variance1d(xray_image,
                                          position_matrix=position_matrix * imask,
                                          max=maxr, step=1))
    plt.plot(t, oldstd, 'b', t, newstd, 'r', t, oldstd - newstd, 'g')
    plt.show()
Ejemplo n.º 2
0
def tif_to_iq(
        # Calibration info
        poni_file=None, dspace_file=None, detector=None,
        calibration_imagefile=None, wavelength=None,
        # image info
        image_path=None, out_ending='',
        # Correction info
        solid=False, pol=True, polarization=0.95,
        # old_files info
        generate_mask=False, mask_file=None, initial_m=None,
        # integration info
        space='Q', resolution=None, average_method='median',
        plot_verbose=False):
    """
    Takes TIFF images to CHI files, including masking, integrating, and CHI
    writing

    Parameters
    ----------
    poni_file: str
        Location of poni file, a detector geometry file produced by pyFAI.
        If none is given a GUI prompt will ask for the file.
    dspace_file : str
        Location of the calibrant d-spacing file.  This is used to generate
        the poni file if no poni file is loaded.
    detector: str
        Name of the detector. This is used to generate
        the poni file if no poni file is loaded.
    calibration_imagefile : str
        Location of the calibration image.  This is used to generate
        the poni file if no poni file is loaded
    wavelength: float
        The wavelength of light in angstrom. This is used to generate
        the poni file if no poni file is loaded.
    image_path: str or list of str or tuple of str
        The image(s) to be masked and integrated.  If more than one image is
        passed via a list or tuple, sum the images together before proceeding.
    out_ending: str
        The ending to append to the output file name before the extension
    solid: bool
        If true, apply solid angle correction as calculated by pyFAI, else do not
    pol: bool
        If true, apply polarization angle correction
    polarization: float
        The polarization of the beam used in the polarization correction
    generate_mask: bool
        If true, generate mask via mask writing algorithum
    mask_file: str
        Location of mask file
    initial_m: float
        Initial guess at ring threshold mask scale factor
    space: {'Q'}
        Eventually will support TTH as well
    resolution:
        The resolution in Q or TTH of the detector
    average_method: str or function
        The function to use in binned statistics to calculate the average
    plot_verbose: bool
        If true, generate a bunch of plots related to statistics of the rings

    Returns
    -------
    str:
        The name of the chi file
    str:
        The name of the mask, if generated
    """

    # load the calibration file/calibrate
    resolution = resolution if resolution is not None else .02
    a = IO.calibrate(poni_file, calibration_imagefile, dspace_file, wavelength,
                     detector)

    # load image
    xray_image, bulk_image_path_no_ext, image_path = IO.loadimage(image_path)

    # mask image, expect out an array of 1s and 0s which is the mask, if the
    # mask is 0 then mask that pixel
    mask_array = None
    if generate_mask is True:

        """This should handle all mask writing functions including binning,
        applying criteria, plotting, and writing the mask out as a numpy
        array where masked pixels are zero.  This should also give the
        option to combine the calculated mask with a previous user
        generated mask."""

        mask_array = Calculate.write_mask(xray_image, a, mask_file, initial_m,
                                          resolution)
        # write mask to FIT2D file for later use
        mask_file_name = IO.fit2d_save(mask_array, bulk_image_path_no_ext)
    elif mask_file is not None:
        # LOAD THE MASK
        mask_array = IO.loadmask(mask_file)
        # mask_array = np.abs(mask_array-1)
    if mask_array is None:
        mask_array = np.ones(np.shape(xray_image))

    if plot_verbose:
        plt.imshow(mask_array, cmap='cubehelix'), plt.colorbar()
        plt.savefig('/home/christopher/mask.png', bbox_inches='tight',
                    transparent=True)
        plt.show()

        plt.imshow(mask_array*xray_image, cmap='cubehelix'), plt.colorbar()
        plt.show()

    # correct for corrections
    corrected_image = Calculate.corrections(xray_image, geometry_object=a,
                                            solid=solid, pol=pol,
                                            polarization_factor=polarization)

    position_matrix = None
    # TODO: Add options for tth
    if space == 'Q':
        position_matrix = a.qArray(np.shape(xray_image)) / 10

    max_position = np.max(position_matrix)
    masked_position = position_matrix * mask_array

    # Integrate using the global average
    independant_out_array = np.arange(0, max_position + resolution, resolution)

    integrated = Calculate.statistics1d(corrected_image,
                                        position_matrix=masked_position,
                                        max=max_position, step=resolution,
                                        statistic=average_method)
    integrated[np.isnan(integrated)] = 0

    uncertainty_array = np.sqrt(
        Calculate.variance1d(corrected_image, position_matrix=masked_position,
                             max=max_position, step=resolution))

    uncertainty_array[np.isnan(uncertainty_array)] = 0

    if plot_verbose is True:
        no_mask_integrated = Calculate.statistics1d(corrected_image,
                                                    position_matrix=position_matrix,
                                                    max=max_position,
                                                    step=resolution,
                                                    statistic=average_method)
        integrated_mean = Calculate.statistics1d(corrected_image,
                                                 position_matrix=masked_position,
                                                 max=max_position,
                                                 step=resolution,
                                                 statistic='mean')
        fig, ax = plt.subplots()
        ax.plot(independant_out_array, integrated, 'g', label='Median I[Q]')
        ax.plot(independant_out_array, integrated_mean, 'b', label='Mean I[Q]')
        ax.plot(independant_out_array, ((integrated - integrated_mean)/((
                                                                            integrated+integrated_mean)/2))*10e6,
                                        'k', label='((Median-Mean)/('
                                                   'Median+Mean)/2)x10^6')
        ax.legend(loc='upper right')
        plt.xlabel('Q (1/A)')
        plt.ylabel('Raw Counts')
        plt.savefig('/home/christopher/integrator.png', bbox_inches='tight',
                    transparent=True)
        plt.show()

        no_mask_uncertainty_percent_array = np.sqrt(
            Calculate.variance1d(corrected_image,
                                 position_matrix=position_matrix,
                                 max=max_position, step=resolution)) / no_mask_integrated
        fig, ax = plt.subplots()
        ax.plot(independant_out_array, integrated, 'g', label='I[Q]')
        ax.plot(independant_out_array, no_mask_integrated, 'k', label='No '
                                                                      'old_files I[Q]')
        ax.plot(independant_out_array, integrated - no_mask_integrated, 'r',
                label='Difference')
        legend = ax.legend(loc='upper right')
        plt.show()

        old_settings = np.seterr(divide='ignore')
        uncertainty_percent_array = uncertainty_array / integrated
        uncertainty_percent_array[np.isnan(uncertainty_percent_array)] = 0
        np.seterr(**old_settings)

        fig, ax = plt.subplots()
        ax.plot(independant_out_array, uncertainty_percent_array * 100, 'g',
                label='Sigma I[Q]')
        plt.xlabel('Q (1/A)')
        plt.ylabel('% uncertainty')
        legend = ax.legend(loc='upper right')
        plt.show()

        ring_std = Calculate.statistics1d(corrected_image,
                                          position_matrix=masked_position,
                                          max=max_position, step=resolution,
                                          statistic=np.std) / integrated

        ring_std_no_mask = Calculate.statistics1d(corrected_image,
                                                  position_matrix=position_matrix,
                                                  max=max_position,
                                                  step=resolution,
                                                  statistic=np.std) / no_mask_integrated
        ring_s = Calculate.statistics1d(corrected_image,
                                        position_matrix=masked_position,
                                        max=max_position, step=resolution,
                                        statistic=stats.skew)

        ring_s_no_mask = Calculate.statistics1d(corrected_image,
                                                position_matrix=position_matrix,
                                                max=max_position,
                                                step=resolution,
                                                statistic=stats.skew)
        fig, ax = plt.subplots()
        ax.plot(independant_out_array, ring_std, 'g',
                label='Ring Standard Deviation')
        ax.plot(independant_out_array, ring_std_no_mask, 'b',
                label='Ring Standard Deviation No old_files')
        legend = ax.legend(loc='upper right')
        plt.show()

        fig, ax = plt.subplots()
        ax.plot(independant_out_array, ring_s, 'g',
                label='Ring Skew')
        ax.plot(independant_out_array, ring_s_no_mask, 'b',
                label='Ring Skew No old_files')
        legend = ax.legend(loc='upper right')
        plt.show()

        # plt.plot(independant_out_array, test_uncertainty / integrated * 100)
        # plt.show()

        plt.plot(
            independant_out_array, integrated, 'g',
            independant_out_array, integrated - uncertainty_array, 'b',
            independant_out_array, integrated + uncertainty_array, 'r'
        )
        plt.show()

        # plt.plot(
        # independant_out_array, integrated, 'g',
        #     independant_out_array, integrated - test_uncertainty, 'b',
        #     independant_out_array, integrated + test_uncertainty, 'r'
        # )
        # plt.show()
    # Save file as chi file with uncertainties
    out_array = np.c_[independant_out_array, integrated, uncertainty_array]
    # print out_array.shape
    chi_filename = os.path.splitext(bulk_image_path_no_ext)[0] + out_ending
    out_file_name = IO.save_chi(out_array, a, chi_filename, mask_file, image_path)
    if generate_mask is True:
        return out_file_name, mask_file_name
    return out_file_name