예제 #1
0
def background_subtract(sample, background_file=None, background_level=None,
                        bg_refine_qmin_index=None, bg_refine_qmax_index=None):
    """
    Wrap the background subtraction optimization with file IO

    Parameters
    ----------
    :param bg_refine_qmin_index:
    sample: ndarray
        Sample I(Q) array
    background_file: str, optional
        The file name of the background file, if not specified give an IO
        gui to select the file, f '' no file is loaded
    background_level: float, optional
        The background level if none given, calculate via minimization

    Returns
    -------
    float:
        The background level
    array:
        The background array
    array:
        The background q array
    str:
        The name of the background file

    """
    #File IO
    background_data, background_file = IO.load_chi_file(
        background_file)
    #Unpack file IO
    if background_data is not None:
        background = background_data[:, 1]
        background_q = background_data[:, 0]
        percentile_peak_pick = np.where(
            background >= np.percentile(background,  98))[0]
        print len(percentile_peak_pick)
        print percentile_peak_pick[0]
        print percentile_peak_pick[-1]
        if len(percentile_peak_pick) >= 2:
            bg_refine_qmin_index = percentile_peak_pick[0]
            bg_refine_qmax_index = percentile_peak_pick[-1]
        else:

            if bg_refine_qmax_index is None:
                plt.plot(background)
                plt.plot(sample)
                plt.show()
                bg_refine_qmax_index = int(raw_input('High end of the '
                                                     'background to fit: '))
            if bg_refine_qmin_index is None:
                plt.plot(background)
                plt.plot(sample)
                plt.show()
                bg_refine_qmin_index = int(raw_input('Low end of the '
                                                     'background to fit: '))
        # Fit the background
        if background_level is None:
            background_level = Calculate.optimize_background_level(background,
                                                                   sample,
                                                                   bg_refine_qmin_index,
                                                                   bg_refine_qmax_index)
            print 'background level= ', background_level
    else:
        background = None
        background_q = None
    return background_level, background_q, background, background_file, \
           bg_refine_qmin_index, bg_refine_qmax_index