コード例 #1
0
def create_instrument(test_data_file, calibrated, pixel_number):
    """
    Create instruments: PyRS and Mantid
    :param calibrated:
    :param pixel_number:
    :return:
    """
    # instrument
    instrument = calibration_file_io.import_instrument_setup(
        xray_2k_instrument_file)

    # 2theta
    two_theta = 35.
    arm_length_shift = 0.
    center_shift_x = 0.
    center_shift_y = 0.
    rot_x_flip = 0.
    rot_y_flip = 0.
    rot_z_spin = 0.

    if False:
        center_shift_x = 1.0 * (random.random() - 0.5) * 2.0
        center_shift_y = 1.0 * (random.random() - 0.5) * 2.0
        arm_length_shift = (random.random() -
                            0.5) * 2.0  # 0.416 + (random.random() - 0.5) * 2.0
        # calibration
        rot_x_flip = 2.0 * (random.random() - 0.5) * 2.0
        rot_y_flip = 2.0 * (random.random() - 0.5) * 2.0
        rot_z_spin = 2.0 * (random.random() - 0.5) * 2.0
    # END-IF: arbitrary calibration

    test_calibration = AnglerCameraDetectorShift()
    test_calibration.center_shift_x = center_shift_x
    test_calibration.center_shift_y = center_shift_y
    test_calibration.center_shift_z = arm_length_shift
    test_calibration.rotation_x = rot_x_flip
    test_calibration.rotation_y = rot_y_flip
    test_calibration.rotation_z = rot_z_spin

    # reduction engine
    engine = reduction_manager.HB2BReductionManager()
    test_data_id, two_the_tmp = engine.load_data(data_file_name=test_data_file,
                                                 target_dimension=pixel_number,
                                                 load_to_workspace=True)

    # load instrument
    pyrs_reducer = reduce_hb2b_pyrs.PyHB2BReduction(instrument)
    pyrs_reducer.build_instrument(two_theta, arm_length_shift, center_shift_x,
                                  center_shift_y, rot_x_flip, rot_y_flip,
                                  rot_z_spin)

    mantid_reducer = None
    # mantid_reducer = reduce_hb2b_mtd.MantidHB2BReduction()
    # data_ws_name = engine.get_raw_data(test_data_id, is_workspace=True)
    # mantid_reducer.set_workspace(data_ws_name)
    # mantid_reducer.load_instrument(two_theta, xray_idf_name, test_calibration)

    return engine, pyrs_reducer, mantid_reducer
コード例 #2
0
def peaks_alignment_score(x, engine, hb2b_setup, two_theta, roi_vec_set, plot=False):
    """ Cost function for peaks alignment
    :param x:
    :param engine:
    :param hb2b_setup:
    :param two_theta:
    :param roi_vec_set: list/array of ROI/mask vector
    :param plot:
    :return:
    """
    peak_centers = '17.5,24.5,30.25,35.2,39.4,43.2,53.5'
    fit_windows = '16,19,23,26,29,32,33,37,38,41,42,44.5,51.5,55'

    # check
    assert isinstance(roi_vec_set, list), 'must be list'
    if len(roi_vec_set) < 2:
        raise RuntimeError('User must specify more than 1 ROI/MASK vector')
    else:
        num_reduced_set = len(roi_vec_set)

    # convert the input X array (to be refined) to geometry calibration values
    geom_calibration = AnglerCameraDetectorShift()
    geom_calibration.center_shift_x = x[0]
    geom_calibration.center_shift_y = x[1]
    geom_calibration.center_shift_z = x[2]
    geom_calibration.rotation_x = x[3]
    geom_calibration.rotation_y = x[4]
    geom_calibration.rotation_z = x[5]

    # reduce data
    reduced_data_set = [None] * num_reduced_set
    for i_roi in range(num_reduced_set):
        ws_name_i = 'reduced_data_{:02}'.format(i_roi)
        out_peak_pos_ws = 'peaks_positions_{:02}'.format(i_roi)
        fitted_ws = 'fitted_peaks_{:02}'.format(i_roi)

        # reduce
        reduced_i = convert_to_2theta(engine, two_theta, hb2b_setup, roi_vec_set[i_roi], geom_calibration,
                                      ws_name_i)
        # fit peaks
        FitPeaks(InputWorkspace=ws_name_i, OutputWorkspace=out_peak_pos_ws,
                 StartWorkspaceIndex=0, StopWorkspaceIndex=0,
                 PeakCenters=peak_centers,
                 FitWindowBoundaryList=fit_windows,
                 FittedPeaksWorkspace=fitted_ws,
                 OutputPeakParametersWorkspace='hb2b_rotate_p30deg_reduced_FITS',  # FIXME - need to give a good name too
                 OutputParameterFitErrorsWorkspace='hb2b_rotate_p30deg_reduced_Errors')

        reduced_data_set[i_roi] = reduced_i, ws_name_i, out_peak_pos_ws, fitted_ws
    # END-FOR

    # calculate the quality of peak alignment for each pair of ROI
    residual = None
    for roi_i, roi_j in list(itertools.combinations(range(num_reduced_set), 2)):
        # get data
        r_t_i = reduced_data_set[roi_i]
        r_t_j = reduced_data_set[roi_j]

        # calculate residual/cost
        num_peaks = len(mtd[r_t_i[2]].readY(0))
        residual_sq = np.zeros(shape=(num_peaks,), dtype='float')
        for p_index in range(num_peaks):
            pos_pos_i = mtd[r_t_i[2]].readY(0)[p_index]
            neg_pos_i = mtd[r_t_j[2]].readY(0)[p_index]
            if pos_pos_i < 0. and neg_pos_i < 0.:
                # both failed to fit
                residual_sq[p_index] = 20 ** 2
            elif pos_pos_i * neg_pos_i < 0.:
                # 1 failed to fit
                residual_sq[p_index] = 10 ** 2
            else:
                residual_sq[p_index] = (pos_pos_i - neg_pos_i) ** 2
        # END-FOR
        residual_ij = np.sqrt(residual_sq)
        if residual is None:
            residual = residual_ij
        else:
            residual = np.concatenate([residual, residual_ij])
    # END-IF-ELSE
    c_n_2 = math.factorial(num_reduced_set) / (math.factorial(2) * math.factorial(num_reduced_set - 2))
    norm_cost = residual.sum() / c_n_2

    # plot
    num_rows = 1 + num_reduced_set / 2 + num_reduced_set % 2

    ax1 = plt.subplot(num_rows, 1, num_rows)
    ax1.margins(0.05)  # Default margin is 0.05, value 0 means fit
    colors = ['black', 'red', 'blue', 'green', 'yellow']
    for roi_i in range(num_reduced_set):
        r_t_i = reduced_data_set[roi_i]
        ax1.plot(r_t_i[0][0], r_t_i[0][1], color=colors[roi_i % 5])
    ax1.set_title('Normalized Cost = {}'.format(norm_cost))

    for roi_i in range(num_reduced_set):
        index_i = roi_i + 1
        print('subplot: {}, {}, {}'.format(num_rows, 2, index_i))
        ax2 = plt.subplot(num_rows, 2, index_i)
        ax2.plot(reduced_data_set[roi_i][0][0], reduced_data_set[roi_i][0][1], color='black')
        ax2.plot(mtd[reduced_data_set[roi_i][3]].readX(0), mtd[reduced_data_set[roi_i][3]].readY(0), color='red')
        ax2.set_title('{}'.format(roi_i))

    if plot:
        plt.show()
    else:
        plt.savefig('Round{:010}.png'.format(GlobalParameter.global_curr_sequence))
        GlobalParameter.global_curr_sequence += 1

    # print ('Parameters:     {}'.format(x))
    # print ('Fitted Peaks +: {}'.format(mtd[P30_Fit].readY(0)))
    # print ('Fitted Peaks -: {}'.format(mtd[N30_Fit].readY(0)))
    print('Residual      = {}'.format(norm_cost))

    return residual
コード例 #3
0
def create_instrument_load_data(instrument, calibrated, pixel_number):
    """ Create instruments: PyRS and Mantid and load data
    :param instrument: name of instrument
    :param calibrated:
    :param pixel_number:
    :return:
    """
    # instrument
    if instrument == 'XRay-XRayMock':
        hydra_idf = xray_2k_instrument_file
        mantid_idf = xray_idf_name
        two_theta = xray_2theta
        test_data_file = test_xray_data
    elif instrument == 'HBZ':
        hydra_idf = hbz_instrument_file
        mantid_idf = hbz_idf
        two_theta = hbz_2theta
        test_data_file = test_hbz_data
        print('Loaded {} and {} to compare @ 2theta = {} degree'
              ''.format(hydra_idf, mantid_idf, two_theta))
    else:
        raise RuntimeError('Instrument {} does not have test data and IDF'.format(instrument))

    print('----------- IDF in Test: {} vs {} ---------------'.format(hydra_idf, mantid_idf))

    instrument = calibration_file_io.import_instrument_setup(hydra_idf)

    # instrument geometry calibration
    if calibrated:
        # Note: README/TODO-ING: ONLY shift Y
        center_shift_x = int(1000. * (random.random() - 0.5) * 2.0) / 1000.
        center_shift_y = int(1000. * (random.random() - 0.5) * 2.0) / 1000.
        arm_length_shift = int(1000. * (random.random() - 0.5) * 2.0) / 1000.  # 0.416 + (random.random() - 0.5) * 2.0
        # calibration  FIXME - Disable rotation calibration to find out the source of difference:  10-17 vs 10-7
        rot_x_flip = int(1000. * 2.0 * (random.random() - 0.5) * 5.0) / 1000.
        rot_y_flip = int(1000. * 2.0 * (random.random() - 0.5) * 5.0) / 1000.
        rot_z_spin = int(1000. * 2.0 * (random.random() - 0.5) * 5.0) / 1000.
        print('[(Random) Calibration Setup]\n    Shift Linear (X, Y, Z) = {}, {}, {}\n    Shift Rotation '
              '(X, Y, Z) = {}, {}, {}'
              ''.format(center_shift_x, center_shift_y, arm_length_shift, rot_x_flip, rot_y_flip,
                        rot_z_spin))
    else:
        arm_length_shift = center_shift_x = center_shift_y = 0.
        rot_x_flip = rot_y_flip = rot_z_spin = 0.
    # END-IF: arbitrary calibration

    test_calibration = AnglerCameraDetectorShift()
    test_calibration.center_shift_x = center_shift_x
    test_calibration.center_shift_y = center_shift_y
    test_calibration.center_shift_z = arm_length_shift
    test_calibration.rotation_x = rot_x_flip
    test_calibration.rotation_y = rot_y_flip
    test_calibration.rotation_z = rot_z_spin

    # reduction engine
    engine = reduction_manager.HB2BReductionManager()
    test_data_id, two_theta_tmp = engine.load_data(data_file_name=test_data_file, target_dimension=pixel_number,
                                                   load_to_workspace=True)

    # load instrument
    pyrs_reducer = reduce_hb2b_pyrs.PyHB2BReduction(instrument)
    pyrs_reducer.build_instrument(two_theta, arm_length_shift, center_shift_x, center_shift_y,
                                  rot_x_flip, rot_y_flip, rot_z_spin)

    mantid_reducer = reduce_hb2b_mtd.MantidHB2BReduction()
    data_ws_name = engine.get_raw_data(test_data_id, is_workspace=True)
    mantid_reducer.set_workspace(data_ws_name)
    mantid_reducer.build_instrument(two_theta, mantid_idf, test_calibration)

    return engine, pyrs_reducer, mantid_reducer
コード例 #4
0
def MinDifference(x, engine, hb2b_setup, positive_roi_vec, negative_roi_vec):
    """ Cost function to align the peaks!
    :param x:
    :return:
    """
    def convert_to_2theta(two_theta, instrument_setup, roi_vec, geometry_shift,
                          ws_name):
        # load instrument: as it changes
        pyrs_reducer = reduce_hb2b_pyrs.PyHB2BReduction(
            instrument_setup, 1.239)
        pyrs_reducer.build_instrument(two_theta, geometry_shift.center_shift_z,
                                      geometry_shift.center_shift_x,
                                      geometry_shift.center_shift_y,
                                      geometry_shift.rotation_x,
                                      geometry_shift.rotation_y,
                                      geometry_shift.rotation_z)

        # reduce data
        min_2theta = 8.
        max_2theta = 64.
        num_bins = 1800

        # reduce PyRS (pure python)
        curr_id = engine.current_data_id
        vec_2theta, vec_hist = pyrs_reducer.reduce_to_2theta_histogram(
            counts_array=engine.get_counts(curr_id),
            mask=roi_vec,
            x_range=(min_2theta, max_2theta),
            num_bins=num_bins,
            is_point_data=True,
            use_mantid_histogram=False)

        CreateWorkspace(DataX=vec_2theta,
                        DataY=vec_hist,
                        DataE=np.sqrt(vec_hist),
                        NSpec=1,
                        OutputWorkspace=ws_name)

        return vec_2theta, vec_hist

    if False:
        WS_p30deg_Rot = test_rotate_2theta(idf_name,
                                           WS_p30deg,
                                           'hb2b_rotate_p30deg_Rot',
                                           DetDistance=0.0,
                                           DetTTH=35.0,
                                           DetTTH_Shift=0.0,
                                           Beam_Center_X=-0.002,
                                           Beam_Center_Y=-0.007,
                                           DetFlit=x[0],
                                           DetSpin=0.0)
        WS_n30deg_Rot = test_rotate_2theta(idf_name,
                                           WS_n30deg,
                                           'hb2b_rotate_n30deg_Rot',
                                           DetDistance=0.0,
                                           DetTTH=35.0,
                                           DetTTH_Shift=0.0,
                                           Beam_Center_X=-0.002,
                                           Beam_Center_Y=-0.007,
                                           DetFlit=x[0],
                                           DetSpin=0.0)

        convert_to_2theta(WS_p30deg_Rot, vanadium_P30)
        convert_to_2theta(WS_n30deg_Rot, vanadium_N30)
    else:
        # TODO - TONIGHT 0 - From here!

        geom_calibration = AnglerCameraDetectorShift()
        geom_calibration.center_shift_x = x[0]
        geom_calibration.center_shift_y = x[1]
        geom_calibration.center_shift_z = x[2]
        geom_calibration.rotation_x = x[3]
        geom_calibration.rotation_y = x[4]
        geom_calibration.rotation_z = x[5]

        positive_roi = convert_to_2theta(two_theta, hb2b_setup,
                                         positive_roi_vec, geom_calibration,
                                         'positive_roi_ws')
        negative_roi = convert_to_2theta(two_theta, hb2b_setup,
                                         negative_roi_vec, geom_calibration,
                                         'negative_roi_ws')

        # plt.plot(positive_roi[0], positive_roi[1], color='red')
        # plt.plot(negative_roi[0], negative_roi[1], color='green')
        # plt.show()

    N30_Fit = 'Fit_N30'
    P30_Fit = 'Fit_P30'

    FitPeaks(
        InputWorkspace='positive_roi_ws',
        OutputWorkspace=N30_Fit,
        StartWorkspaceIndex=0,
        StopWorkspaceIndex=0,
        PeakCenters='17.5,24.5,30.25,35.2,39.4,43.2,53.5',
        FitWindowBoundaryList='16,19,23,26,29,32,33,37,38,41,42,44.5,51.5,55',
        FittedPeaksWorkspace='hb2b_rotate_n30deg_reduced_Output',
        OutputPeakParametersWorkspace='hb2b_rotate_n30deg_reduced_FITS',
        OutputParameterFitErrorsWorkspace='hb2b_rotate_n30deg_reduced_Errors')

    FitPeaks(
        InputWorkspace='negative_roi_ws',
        OutputWorkspace=P30_Fit,
        StartWorkspaceIndex=0,
        StopWorkspaceIndex=0,
        PeakCenters='17.5,24.5,30.25,35.2,39.4,43.2,53.5',
        FitWindowBoundaryList='16,19,23,26,29,32,33,37,38,41,42,44.5,51.5,55',
        FittedPeaksWorkspace='hb2b_rotate_p30deg_reduced_Output',
        OutputPeakParametersWorkspace='hb2b_rotate_p30deg_reduced_FITS',
        OutputParameterFitErrorsWorkspace='hb2b_rotate_p23deg_reduced_Errors')

    Error3 = (mtd[N30_Fit].extractY()[0] - mtd[P30_Fit].extractY()[0])

    print('Parameters:     {}'.format(x))
    print('Fitted Peaks +: {}'.format(mtd[P30_Fit].readY(0)))
    print('Fitted Peaks -: {}'.format(mtd[N30_Fit].readY(0)))
    print('Diff**2       = {}'.format(Error3 * Error3))
    return (Error3 * Error3) * 1e8
コード例 #5
0
def peaks_alignment_score(x,
                          engine,
                          hb2b_setup,
                          two_theta,
                          roi_vec_set,
                          plot=False,
                          ScalarReturn=False):
    """ Cost function for peaks alignment
    :param x:
    :param engine:
    :param hb2b_setup:
    :param two_theta:
    :param roi_vec_set: list/array of ROI/mask vector
    :param plot:
    :return:
    """
    peak_centers = '17.5,24.5,30.25,35.2,39.4,43.2,53.5'
    fit_windows = '16,19,23,26,29,32,33,37,38,41,42,44.5,51.5,55'

    peak_pos = [17.5, 24.5, 30.25, 35.2, 39.4, 43.2, 53.5]

    peak_pos = [25.5, 30.25, 35.2, 39.4, 43.2, 50.7, 54., 57., 59]

    # check
    #assert isinstance(roi_vec_set, list), 'must be list'
    if len(roi_vec_set) < 2:
        raise RuntimeError('User must specify more than 1 ROI/MASK vector')
    else:
        num_reduced_set = len(roi_vec_set)
        num_peaks = len(peak_pos)

    # convert the input X array (to be refined) to geometry calibration values
    geom_calibration = AnglerCameraDetectorShift()
    geom_calibration.center_shift_x = x[0]
    geom_calibration.center_shift_y = x[1]
    geom_calibration.center_shift_z = x[2]
    geom_calibration.rotation_x = x[3]
    geom_calibration.rotation_y = x[4]
    geom_calibration.rotation_z = x[5]

    # load instrument: as it changes
    pyrs_reducer = reduce_hb2b_pyrs.PyHB2BReduction(hb2b_setup, 1.239)
    pyrs_reducer.build_instrument(two_theta, geom_calibration.center_shift_z,
                                  geom_calibration.center_shift_x,
                                  geom_calibration.center_shift_y,
                                  geom_calibration.rotation_x,
                                  geom_calibration.rotation_y,
                                  geom_calibration.rotation_z)

    Eta_val = pyrs_reducer.get_eta_value()

    # reduce data
    reduced_data_set = [None] * num_reduced_set

    if plot:
        fig, ax = plt.subplots(1, 1, figsize=(10, 10))

        for i_roi in range(num_reduced_set):
            # Define Mask
            Mask = np.zeros_like(Eta_val)
            if abs(roi_vec_set[i_roi]) == roi_vec_set[i_roi]:
                index = np.where((Eta_val < (roi_vec_set[i_roi] + 5)) == (
                    Eta_val > (roi_vec_set[i_roi] - 5)))[0]
            else:
                index = np.where((Eta_val > (roi_vec_set[i_roi] - 5)) == (
                    Eta_val < (roi_vec_set[i_roi] + 5)))[0]

            Mask[index] = 1.

            #x_vec, y_vec = convert_to_2theta(engine, pyrs_reducer, Mask, 18, 63, 1800 )
            vec_x, vec_y = convert_to_2theta(engine, pyrs_reducer, Mask, 18,
                                             63, 1800)
            ax.plot(vec_x.T, vec_y.T, label=roi_vec_set[i_roi])

        ax.set_ylabel('Int (cts.)')
        ax.set_ylabel('2theta (deg.)')
        handles, labels = ax.get_legend_handles_labels()
        fig.legend(handles, labels, loc='upper center')
        plt.show()
        return

    for i_roi in range(num_reduced_set):
        Peaks = [None] * num_peaks

        # Define Mask
        Mask = np.zeros_like(Eta_val)
        if abs(roi_vec_set[i_roi]) == roi_vec_set[i_roi]:
            index = np.where((Eta_val < (roi_vec_set[i_roi] + 5)) == (
                Eta_val > (roi_vec_set[i_roi] - 5)))[0]
        else:
            index = np.where((Eta_val > (roi_vec_set[i_roi] - 5)) == (
                Eta_val < (roi_vec_set[i_roi] + 5)))[0]

        Mask[index] = 1.
        for i_peak in range(num_peaks):
            # reduce
            Peaks[i_peak] = convert_to_2theta(engine, pyrs_reducer, Mask,
                                              peak_pos[i_peak] - 1,
                                              peak_pos[i_peak] + 1, 60)[1]

        reduced_data_set[i_roi] = Peaks

    # END-FOR

    # calculate the quality of peak alignment for each pair of ROI
    residual = None

    for i_roi in range(num_reduced_set):
        for peak_i, peak_j in list(itertools.combinations(range(num_peaks),
                                                          2)):
            # get data

            #residual_sq = 1. / np.min( np.corrcoef( reduced_data_set[i_roi][peak_i], reduced_data_set[i_roi][peak_j] ) )

            temp_p1 = reduced_data_set[i_roi][peak_i]
            temp_p2 = reduced_data_set[i_roi][peak_j]
            residual_sq = (
                1. / np.correlate(temp_p1 / np.linalg.norm(temp_p1),
                                  temp_p2 / np.linalg.norm(temp_p2))) - 1.
            #            residual_sq = np.correlate( reduced_data_set[i_roi][peak_i], reduced_data_set[i_roi][peak_j] )
            if not np.isfinite(residual_sq):
                residual_sq = np.array([1000.])
            if residual is None:
                residual = residual_sq
            else:
                residual = np.concatenate([residual, residual_sq])

    # END-IF-ELSE
    c_n_2 = math.factorial(num_reduced_set) / (
        math.factorial(2) * math.factorial(num_reduced_set - 2))
    norm_cost = residual.sum() / c_n_2

    print('Residual      = {}'.format(norm_cost))

    if ScalarReturn:
        return np.sum(residual)
    else:
        return residual
コード例 #6
0
def CostFunction(x,
                 engine,
                 hb2b_setup,
                 two_theta,
                 positive_roi_vec,
                 negative_roi_vec,
                 plot=False):
    """ Cost function to align the peaks!
    :param x:
    :return:
    """
    # Reduce
    geom_calibration = AnglerCameraDetectorShift()
    geom_calibration.center_shift_x = x[0]
    geom_calibration.center_shift_y = x[1]
    geom_calibration.center_shift_z = x[2]
    geom_calibration.rotation_x = x[3]
    geom_calibration.rotation_y = x[4]
    geom_calibration.rotation_z = x[5]

    positive_roi = convert_to_2theta(engine, two_theta, hb2b_setup,
                                     positive_roi_vec, geom_calibration,
                                     'positive_roi_ws')
    negative_roi = convert_to_2theta(engine, two_theta, hb2b_setup,
                                     negative_roi_vec, geom_calibration,
                                     'negative_roi_ws')

    # Fit peaks
    N30_Fit = 'Fit_N30'
    P30_Fit = 'Fit_P30'
    p30_fitted = 'hb2b_rotate_p30deg_reduced_Output'
    n30_fitted = 'hb2b_rotate_n30deg_reduced_Output'

    FitPeaks(
        InputWorkspace='positive_roi_ws',
        OutputWorkspace=P30_Fit,
        StartWorkspaceIndex=0,
        StopWorkspaceIndex=0,
        PeakCenters='17.5,24.5,30.25,35.2,39.4,43.2,53.5',
        FitWindowBoundaryList='16,19,23,26,29,32,33,37,38,41,42,44.5,51.5,55',
        FittedPeaksWorkspace=p30_fitted,
        OutputPeakParametersWorkspace='hb2b_rotate_p30deg_reduced_FITS',
        OutputParameterFitErrorsWorkspace='hb2b_rotate_p30deg_reduced_Errors')

    FitPeaks(
        InputWorkspace='negative_roi_ws',
        OutputWorkspace=N30_Fit,
        StartWorkspaceIndex=0,
        StopWorkspaceIndex=0,
        PeakCenters='17.5,24.5,30.25,35.2,39.4,43.2,53.5',
        FitWindowBoundaryList='16,19,23,26,29,32,33,37,38,41,42,44.5,51.5,55',
        FittedPeaksWorkspace=n30_fitted,
        OutputPeakParametersWorkspace='hb2b_rotate_n30deg_reduced_FITS',
        OutputParameterFitErrorsWorkspace='hb2b_rotate_n30deg_reduced_Errors')

    assert len(mtd[P30_Fit].readY(0)) == len(
        mtd[N30_Fit].readY(0)), 'Number of peaks fitted must be equal'

    # calculate residual/cost
    num_peaks = len(mtd[N30_Fit].readY(0))
    residual_sq = np.zeros(shape=(num_peaks, ), dtype='float')
    for p_index in range(len(mtd[P30_Fit].readY(0))):
        pos_pos_i = mtd[P30_Fit].readY(0)[p_index]
        neg_pos_i = mtd[N30_Fit].readY(0)[p_index]
        if pos_pos_i < 0. and neg_pos_i < 0.:
            # both failed to fit
            residual_sq[p_index] = 20**2
        elif pos_pos_i * neg_pos_i < 0.:
            # 1 failed to fit
            residual_sq[p_index] = 10**2
        else:
            residual_sq[p_index] = (pos_pos_i - neg_pos_i)**2
    # END-FOR
    residual = np.sqrt(residual_sq)

    # plot
    ax1 = plt.subplot(212)
    ax1.margins(0.05)  # Default margin is 0.05, value 0 means fit
    ax1.plot(r[0], positive_roi[1], color='red')
    ax1.plot(negative_roi[0], negative_roi[1], color='green')
    ax1.set_title('Cost = {}'.format(residual))

    ax2 = plt.subplot(221)
    # ax2.margins(2, 2)  # Values >0.0 zoom out
    ax2.plot(positive_roi[0], positive_roi[1], color='black')
    ax2.plot(mtd[p30_fitted].readX(0), mtd[p30_fitted].readY(0), color='red')
    ax2.set_title('Positive')

    ax3 = plt.subplot(222)
    # ax3.margins(x=0, y=-0.25)  # Values in (-0.5, 0.0) zooms in to center
    ax3.plot(negative_roi[0], negative_roi[1], color='black')
    ax3.plot(mtd[n30_fitted].readX(0), mtd[n30_fitted].readY(0), color='red')
    ax3.set_title('Negative')

    if plot:
        plt.show()
    else:
        plt.savefig('Round{:010}.png'.format(
            GlobalParameter.global_curr_sequence))
        GlobalParameter.global_curr_sequence += 1

    print('Parameters:     {}'.format(x))
    print('Fitted Peaks +: {}'.format(mtd[P30_Fit].readY(0)))
    print('Fitted Peaks -: {}'.format(mtd[N30_Fit].readY(0)))
    print('Residual      = {}'.format(residual.sum()))

    return residual
コード例 #7
0
    def do_reduce_data(self):
        """ reduce data
        :return:
        """
        try:
            cal_shift_x = gui_helper.parse_line_edit(self.ui.lineEdit_centerX,
                                                     float,
                                                     False,
                                                     'Center X',
                                                     default=0.)
            cal_shift_y = gui_helper.parse_line_edit(self.ui.lineEdit_centerY,
                                                     float,
                                                     False,
                                                     'Center Y',
                                                     default=0.)
            cal_shift_z = gui_helper.parse_line_edit(self.ui.lineEdit_centerZ,
                                                     float,
                                                     False,
                                                     'Center Z',
                                                     default=0.)
            cal_rot_x = gui_helper.parse_line_edit(self.ui.lineEdit_rotationX,
                                                   float,
                                                   False,
                                                   'Rotation X',
                                                   default=0.)
            cal_rot_y = gui_helper.parse_line_edit(self.ui.lineEdit_rotationY,
                                                   float,
                                                   False,
                                                   'Rotation Y',
                                                   default=0.)
            cal_rot_z = gui_helper.parse_line_edit(self.ui.lineEdit_rotationZ,
                                                   float,
                                                   False,
                                                   'Rotation Z',
                                                   default=0.)
            cal_wave_length = gui_helper.parse_line_edit(
                self.ui.lineEdit_wavelength,
                float,
                False,
                'Rotation Z',
                default=1.)
        except RuntimeError as run_err:
            gui_helper.pop_message(self, 'Unable to parse calibration value',
                                   str(run_err), 'error')
            return

        # get data file
        try:
            two_theta = gui_helper.parse_line_edit(self.ui.lineEdit_2theta,
                                                   float,
                                                   True,
                                                   'Two theta',
                                                   default=None)
        except RuntimeError as run_err:
            gui_helper.pop_message(self, '2-theta error', str(run_err),
                                   'error')
            return

        # load instrument
        # self._core.reduction_engine.set_instrument(instrument)
        #
        # self._core.reduction_engine.load_instrument(two_theta, cal_shift_x, cal_shift_y, cal_shift_z,
        #                                              cal_rot_x, cal_rot_y, cal_rot_z,
        #                                              cal_wave_length)

        # reduce masks
        geom_calibration = AnglerCameraDetectorShift()
        geom_calibration.center_shift_x = cal_shift_x
        geom_calibration.center_shift_y = cal_shift_y
        geom_calibration.center_shift_z = cal_shift_z
        geom_calibration.rotation_x = cal_rot_x
        geom_calibration.rotation_y = cal_rot_y
        geom_calibration.rotation_z = cal_rot_z

        self._core.reduction_service.set_geometry_calibration(geom_calibration)
        for mask_id in self._core.reduction_service.get_mask_ids():
            # mask_vec = self._core.reduction_engine.get_mask_vector(mask_id)
            self._core.reduction_service.reduce_to_2theta_histogram(
                data_id=self._curr_data_id,
                output_name=None,
                use_mantid_engine=False,
                mask=mask_id,
                two_theta=two_theta)
            """
             data_id, output_name, use_mantid_engine, mask, two_theta,
                         min_2theta=None, max_2theta=None, resolution_2theta=None
            """
            vec_x, vec_y = self._core.reduction_service.get_reduced_data()
            self.ui.graphicsView_calibration.plot_data(
                vec_x, vec_y, self._mask_subplot_dict[mask_id])

        if cal_wave_length:
            # TODO - Need to implement how to calibrate wave length
            raise NotImplementedError('Implement ASAP')

        return