Beispiel #1
0
def test_main():
    """
    test main
    :return:
    """
    rs_core = pyrscore.PyRsCore()

    # pre-requisite is that the data file exists
    test_data = 'tests/data/Hidra_16-1_cor_log.h5'
    assert os.path.exists(test_data), 'File {} does not exist'.format(
        test_data)

    # load data
    test_hd_ws = rs_core.load_hidra_project(test_data, 'test core', False,
                                            True)
    assert test_hd_ws is not None

    # Get sub runs
    sub_runs = rs_core.reduction_service.get_sub_runs('test core')
    assert sub_runs is not None

    # Get sample logs
    log_names = rs_core.reduction_service.get_sample_logs_names(
        'test core', None)
    assert isinstance(log_names, list)

    return
Beispiel #2
0
def test_retrieve_fit_metadata(source_project_file, output_project_file,
                               peak_type, peak_info):
    """A full set of test including loading project,  fitting peaks, write fitting result and exporting fitting
    result and calculated peaks

    Parameters
    ----------
    source_project_file
    output_project_file
    peak_type
    peak_info

    Returns
    -------

    """
    if os.path.exists(source_project_file) is False:
        pytest.skip('{} does not exist on Travis'.format(source_project_file))

    # Create calibration control
    controller = pyrscore.PyRsCore()

    # Load project file to HidraWorkspace
    project_name = 'Jean Peaks'
    hd_ws = controller.load_hidra_project(source_project_file,
                                          project_name=project_name,
                                          load_detector_counts=False,
                                          load_diffraction=True)

    # set wave length
    # TODO : @Jean please find out the correct value
    hd_ws.set_wavelength(1.071, False)

    # Set peak fitting engine
    # create a controller from factory
    fit_engine = PeakFitEngineFactory.getInstance(
        hd_ws, peak_function_name=peak_type, background_function_name='Linear')

    # Fit peak
    fit_result = fit_engine.fit_peaks(peak_tag=peak_info.tag,
                                      x_min=peak_info.left_bound,
                                      x_max=peak_info.right_bound)

    # Retrieve all effective peak parameters
    peakcollection = fit_result.peakcollections[0]
    eff_param_value_array, eff_param_error_array = peakcollection.get_effective_params(
    )

    # result file
    ref_h5 = h5py.File(output_project_file, 'w')
    peak_entry = ref_h5.create_group(peak_info.tag)
    peak_entry.create_dataset('Center', data=eff_param_value_array['Center'])
    peak_entry.create_dataset('Height', data=eff_param_value_array['Height'])
    peak_entry.create_dataset('FWHM', data=eff_param_value_array['FWHM'])
    peak_entry.create_dataset('Mixing', data=eff_param_value_array['Mixing'])
    peak_entry.create_dataset('Intensity',
                              data=eff_param_value_array['Intensity'])
    ref_h5.close()
def main(argv):
    """
    Main
    :param argv:
    :return:
    """
    #
    # Required: HIDRA
    # Optional: Instrument file
    # Optional: mask files
    # Optional: bins

    # long-name, short-name, target name, type, default value, is mandatory, documen
    args_def_dict = [('input', 'i', 'inputfile', str, None, True,
                      'Input HIDRA project file'),
                     ('instrument', None, 'instrument', str, None, False,
                      'Path to instrument file'),
                     ('output', 'o', 'outputfile', str, None, True,
                      'Output calibration in JSON format'),
                     ('binsize', 'b', 'binsize', float, 0.01, False,
                      '2theta step')]

    try:
        param_dict = script_helper.process_arguments(argv, args_def_dict)
    except RuntimeError as run_err:
        print('Failed to parse inputs due to {}'.format(run_err))
        return

    # In case of help
    if param_dict is None:
        return

    # Create calibration control
    calib_controller = pyrscore.PyRsCore()

    # Load data
    project_name = 'calibration'
    calib_controller.load_hidra_project(param_dict['inputfile'],
                                        project_name=project_name)

    # Reduce data
    calib_controller.reduce_diffraction_data(project_name,
                                             num_bins=args_def_dict['binsize'],
                                             pyrs_engine=True)

    # Export reduction data
    calib_controller.export_diffraction_data(project_name,
                                             param_dict['inputfile'])

    # Calibration init: import ROI/Mask files
    mask_file_list = parse_mask_files(param_dict['masks'])
    if len(mask_file_list) < 2:
        print('For X-ray case, user must specify at least 2 masks')
        sys.exit(-1)

    # TODO - to be continued

    return
Beispiel #4
0
    def do_launch_fit_peak_window(self):
        """
        launch peak fit window
        :return:
        """
        # core
        fit_peak_core = pyrscore.PyRsCore()

        # set up interface object
        # if self.peak_fit_window is None:
        self.peak_fit_window = fitpeakswindow.FitPeaksWindow(self, fit_peak_core=fit_peak_core)
        self.peak_fit_window.show()
Beispiel #5
0
def test_improve_quality():
    """This is a test to improve the quality of peak fitting.

    Data are from the real HB2B data previously reported problematic

    Returns
    -------

    """
    # Define HiDRA project file name and skip test if it does not exist (on Travis)
    project_file_name = '/HFIR/HB2B/IPTS-22731/shared/autoreduce/HB2B_1060.h5'
    if not os.path.exists(project_file_name):
        pytest.skip('{} does not exist on Travis'.format(project_file_name))

    # Create calibration control
    controller = pyrscore.PyRsCore()

    # Load project file to HidraWorkspace
    project_name = 'Jean Peaks'
    hd_ws = controller.load_hidra_project(project_file_name,
                                          project_name=project_name,
                                          load_detector_counts=False,
                                          load_diffraction=True)

    # set wave length
    # TODO : @Jean please find out the correct value
    wavelength = 1.071
    hd_ws.set_wavelength(wavelength, False)

    peak_type = 'Gaussian'

    # Set peak fitting engine
    # create a controller from factory
    fit_engine = PeakFitEngineFactory.getInstance(
        hd_ws,
        peak_function_name=peak_type,
        background_function_name='Linear',
        wavelength=wavelength)

    # Fit peak @ left
    peak_info_left = PeakInfo(91.7, 87., 93., 'Left Peak')

    fit_result = fit_engine.fit_peaks(peak_tag=peak_info_left.tag,
                                      x_min=peak_info_left.left_bound,
                                      x_max=peak_info_left.right_bound)
    assert fit_result

    # Fit the right peak
    peak_info_left = PeakInfo(95.8, 93.5, 98.5, 'Right Peak')

    fit_engine.fit_peaks(peak_tag=peak_info_left.tag,
                         x_min=peak_info_left.left_bound,
                         x_max=peak_info_left.right_bound)
Beispiel #6
0
    def do_launch_strain_stress_window(self):
        """
        launch the strain/stress calculation and visualization window
        :return:
        """
        # core
        ss_core = pyrscore.PyRsCore()

        if self.strain_stress_window is None:
            self.strain_stress_window = strainstresscalwindow.StrainStressCalculationWindow(self, ss_core)

        # launch
        self.strain_stress_window.show()
Beispiel #7
0
    def do_launch_calibration(self):
        """

        :return:
        """
        from pyrs.interface.calibration import calibrationwindow
        # core
        pyrs_core = pyrscore.PyRsCore()

        # set up interface object
        if self.calibration_window is None:
            self.calibration_window = calibrationwindow.InstrumentCalibrationWindow(self, pyrs_core)
        self.calibration_window.show()
Beispiel #8
0
def modify_test_copy_from_unconstrained_to_plane():
    """
    testing the use case such that the user copy a strain/stress calculator to another one
    :return:
    """
    # initialize core
    rs_core = pyrscore.PyRsCore()

    # create testing files, aka, testing peak fitting module (core)
    target_data_set = {
        'e11': 'tests/temp/LD_Data_Log.hdf5',
        'e22': 'tests/temp/BD_Data_Log.hdf5',
        'e33': 'tests/temp/ND_Data_Log.hdf5'
    }

    # start a session
    rs_core.new_strain_stress_session('test strain/stress module',
                                      is_plane_strain=False,
                                      is_plane_stress=False)

    # set parameters
    rs_core.strain_stress_calculator.set_d0(d0=1.2345)
    rs_core.strain_stress_calculator.set_youngs_modulus(young_e=500.)
    rs_core.strain_stress_calculator.set_poisson_ratio(poisson_ratio=0.23)

    # load data
    rs_core.strain_stress_calculator.load_reduced_file(
        file_name=target_data_set['e11'], direction='e11')
    rs_core.strain_stress_calculator.load_reduced_file(
        file_name=target_data_set['e22'], direction='e22')
    rs_core.strain_stress_calculator.load_reduced_file(
        file_name=target_data_set['e33'], direction='e33')

    # check and align measurement points around
    try:
        rs_core.strain_stress_calculator.check_grids_alignment()
    except RuntimeError as run_err:
        print('Measuring points are not aligned: {}'.format(run_err))

    # create a plane strain/stress calculator
    ss_calculator = rs_core.strain_stress_calculator

    new_ss_calculator = ss_calculator.migrate(plane_strain=True,
                                              plane_stress=False)

    # re check
    new_ss_calculator.check_grids_alignment()
    new_ss_calculator.located_matched_grids(resolution=0.001)
    new_ss_calculator.execute()

    return
Beispiel #9
0
    def __init__(self, input_file_name):
        """ Initialization
        :param input_file_name: name of testing HIDRA project file
        """
        # Create calibration control
        self._reduction_controller = pyrscore.PyRsCore()

        # Load data
        self._project_name = 'NFRS2 Peaks'
        hd_ws = self._reduction_controller.load_hidra_project(input_file_name, project_name=self._project_name,
                                                              load_detector_counts=False,
                                                              load_diffraction=True)

        # set wave length
        hd_ws.set_wavelength(1.071, False)
def broken_test_pole_figure_calculation():
    """
    main testing body to test the workflow to calculate pole figure
    :return:
    """
    # initialize core
    rs_core = pyrscore.PyRsCore()
    assert rs_core

    # import data file: detector ID and file name
    test_data_set = [
        (1, 'tests/testdata/HB2B_exp129_Long_Al_222[1]_single.hdf5'),
        (2, 'tests/testdata/HB2B_exp129_Long_Al_222[2]_single.hdf5'),
        (3, 'tests/testdata/HB2B_exp129_Long_Al_222[3]_single.hdf5'),
        (4, 'tests/testdata/HB2B_exp129_Long_Al_222[4]_single.hdf5'),
        (5, 'tests/testdata/HB2B_exp129_Long_Al_222[5]_single.hdf5'),
        (6, 'tests/testdata/HB2B_exp129_Long_Al_222[6]_single.hdf5'),
        (7, 'tests/testdata/HB2B_exp129_Long_Al_222[7]_single.hdf5')
    ]
    assert test_data_set
Beispiel #11
0
    def do_launch_texture_window(self):
        """
        launch texture analysis home
        :return:
        """
        # core
        texture_core = pyrscore.PyRsCore()

        if self.texture_analysis_window is None:
            self.texture_analysis_window = textureanalysiswindow.TextureAnalysisWindow(self)
            self.texture_analysis_window.setup_window(texture_core)

        # show
        self.texture_analysis_window.show()

        # optionally close the main window
        # if self.ui.checkBox_keepWindowOpen.isChecked() is False:
        #     self.close()

        return
Beispiel #12
0
def modify_test_strain_calculation():
    """
    main testing body to test the workflow to calculate strain
    :return:
    """
    # initialize core
    rs_core = pyrscore.PyRsCore()

    # create testing files, aka, testing peak fitting module (core)
    target_data_set = {
        'e11': 'tests/temp/LD_Data_Log.hdf5',
        'e22': 'tests/temp/BD_Data_Log.hdf5',
        'e33': 'tests/temp/ND_Data_Log.hdf5'
    }

    # start a session
    rs_core.new_strain_stress_session('test strain/stress module',
                                      is_plane_strain=False,
                                      is_plane_stress=False)

    # TODO - 20180810 - d0 might not be a single value but changes along grids.
    # TODO   continue   So make it possible to accept d0 in a n x 3 matrix as (x, y, z)
    rs_core.strain_stress_calculator.set_d0(d0=1.2345)
    rs_core.strain_stress_calculator.set_youngs_modulus(young_e=500.)
    rs_core.strain_stress_calculator.set_poisson_ratio(poisson_ratio=0.23)

    # load data
    rs_core.strain_stress_calculator.load_reduced_file(
        file_name=target_data_set['e11'], direction='e11')
    rs_core.strain_stress_calculator.load_reduced_file(
        file_name=target_data_set['e22'], direction='e22')
    rs_core.strain_stress_calculator.load_reduced_file(
        file_name=target_data_set['e33'], direction='e33')

    # convert peak positions to d-spacing
    rs_core.strain_stress_calculator.convert_peaks_positions()

    # check and align measurement points around
    # TODO FIXME - 20181001 - Make an individual method for ....  ---> New workflow!
    if True:
        # TODO FIXME - 20181001 - This is a new suite of methods to analyze the sample grids
        # ... ...
        # set the name of the sample log for grid positions
        pos_x_sample_names = {'e11': 'vx', 'e22': 'vx', 'e33': 'vx'}
        pos_y_sample_names = {'e11': 'vy', 'e22': 'vy', 'e33': 'vy'}
        pos_z_sample_names = {'e11': 'vz', 'e22': 'vz', 'e33': 'vz'}
        rs_core.strain_stress_calculator.set_grid_log_names(
            pos_x_sample_names, pos_y_sample_names, pos_z_sample_names)

        rs_core.strain_stress_calculator.check_grids_alignment(
        )  # rename method
        rs_core.strain_stress_calculator.located_matched_grids(
            resolution=0.001)
    # END-Align-Grid

    # calculate unconstrained strain and stress
    strain_vec, stress_vec = rs_core.strain_stress_calculator.execute()

    # save
    rs_core.strain_stress_calculator.save_strain_stress('tests/temp/ss1.dat')

    # generate strain/stress grids
    grid_dict = {
        'Min': {
            'X': -130,
            'Y': None,
            'Z': 9.
        },
        'Max': {
            'X': 130.,
            'Y': None,
            'Z': None
        },
        'NotUsed': {}
    }
    grids, maps = rs_core.strain_stress_calculator.generate_grids(
        'e22', user_defined=False, grids_dimension_dict=grid_dict)

    # convert to image of slice view...
    rs_core.strain_stress_calculator.export_strain_2d(grids)

    # export
    #  rs_core.export_to_paraview(data_key, 'strain', '/tmp/stain_para.dat')

    return
Beispiel #13
0
def modify_test_plane_stress():
    """
    Same as test_strain_calculation but using plane stress
    :return:
    """
    # TODO - 20180817 - Continue to implement
    # initialize core
    rs_core = pyrscore.PyRsCore()

    # create testing files, aka, testing peak fitting module (core)
    target_data_set = {
        'e11': 'tests/temp/LD_Data_Log.hdf5',
        'e22': 'tests/temp/BD_Data_Log.hdf5',
        'e33': 'tests/temp/ND_Data_Log.hdf5'
    }

    # start a session
    rs_core.new_strain_stress_session('test strain/stress module',
                                      is_plane_strain=False,
                                      is_plane_stress=True)

    # set up d0, E and nu
    rs_core.strain_stress_calculator.set_d0(d0=1.2345)
    rs_core.strain_stress_calculator.set_youngs_modulus(young_e=500.)
    rs_core.strain_stress_calculator.set_poisson_ratio(poisson_ratio=0.23)

    # load data
    rs_core.strain_stress_calculator.load_reduced_file(
        file_name=target_data_set['e11'], direction='e11')
    rs_core.strain_stress_calculator.load_reduced_file(
        file_name=target_data_set['e22'], direction='e22')

    # check and align measurement points around
    try:
        rs_core.strain_stress_calculator.check_grids_alignment()
    except RuntimeError as run_err:
        print('Measuring points are not aligned: {}'.format(run_err))
    rs_core.strain_stress_calculator.located_matched_grids(resolution=0.001)

    # convert peak positions to d-spacing
    rs_core.strain_stress_calculator.convert_peaks_positions()

    # generate strain/stress grids
    grid_dict = {
        'Min': {
            'X': -130,
            'Y': 0.,
            'Z': 9.
        },
        'Max': {
            'X': 130.,
            'Y': 0.,
            'Z': 19
        },
        'Resolution': {
            'X': 5.0,
            'Y': None,
            'Z': 1.0
        }
    }
    grids, maps = rs_core.strain_stress_calculator.generate_grids(
        None, user_defined=True, grids_dimension_dict=grid_dict)
    center_d_vec = rs_core.strain_stress_calculator.align_peak_parameter_on_grids(
        grids, 'center_d', maps)

    # calculate unconstrained strain and stress
    strain_vec, stress_vec = rs_core.strain_stress_calculator.execute(
        ss_grid_vec=grids, peak_pos_d_vec=center_d_vec)

    assert strain_vec
    assert stress_vec

    return
Beispiel #14
0
def test_pseudovoigt_HB2B_1060(target_values):
    """This is a test of Pseudovoigt peak fitting for HB2B 1060.

     Data are from the real HB2B data previously reported problematic


     """
    # Define HiDRA project file name and skip test if it does not exist (on Travis)

    project_file_name = 'tests/data/HB2B_1060_first3_subruns.h5'

    if not os.path.exists(project_file_name):
        pytest.skip('{} does not exist on Travis'.format(project_file_name))

    # Create calibration control
    controller = pyrscore.PyRsCore()

    # Load project file to HidraWorkspace
    project_name = 'HB2B_1060 Peaks'
    hd_ws = controller.load_hidra_project(project_file_name,
                                          project_name=project_name,
                                          load_detector_counts=False,
                                          load_diffraction=True)

    peak_type = 'PseudoVoigt'
    # Set peak fitting engine
    # create a controller from factory
    fit_engine = PeakFitEngineFactory.getInstance(
        hd_ws,
        peak_function_name=peak_type,
        background_function_name='Linear',
        wavelength=np.nan)

    # Fit peak @ left and right
    peak_info_left = PeakInfo(91.7, 87., 93., 'Left Peak')
    peak_info_right = PeakInfo(95.8, 93.5, 98.5, 'Right Peak')

    fit_result = fit_engine.fit_multiple_peaks(
        peak_tags=[peak_info_left.tag, peak_info_right.tag],
        x_mins=[peak_info_left.left_bound, peak_info_right.left_bound],
        x_maxs=[peak_info_left.right_bound, peak_info_right.right_bound])

    assert len(fit_result.peakcollections) == 2, 'two PeakCollection'
    assert fit_result.fitted
    assert fit_result.difference

    # peak 'Left'
    param_values_lp, _ = fit_result.peakcollections[0].get_native_params()

    # peak 'Right'
    param_values_rp, _ = fit_result.peakcollections[1].get_native_params()

    assert param_values_lp.size == 3, '3 subruns'
    assert len(param_values_lp.dtype.names) == 6, '6 native parameters'

    assert param_values_rp.size == 3, '3 subruns'
    assert len(param_values_rp.dtype.names) == 6, '6 native parameters'

    np.testing.assert_allclose(param_values_lp['Intensity'],
                               target_values['Intensity'][0],
                               atol=0.9)
    np.testing.assert_allclose(param_values_lp['PeakCentre'],
                               target_values['peak_center'][0],
                               atol=0.8)
    np.testing.assert_allclose(param_values_lp['FWHM'],
                               target_values['FWHM'][0],
                               atol=1.)
    np.testing.assert_allclose(param_values_lp['A0'],
                               target_values['background_A0'][0],
                               atol=1.)
    np.testing.assert_allclose(param_values_lp['A1'],
                               target_values['background_A1'][0],
                               atol=1.)

    np.testing.assert_allclose(param_values_rp['Intensity'],
                               target_values['Intensity'][1],
                               atol=0.01)
    np.testing.assert_allclose(param_values_rp['PeakCentre'],
                               target_values['peak_center'][1],
                               atol=1)
    np.testing.assert_allclose(param_values_rp['FWHM'],
                               target_values['FWHM'][1],
                               atol=1.2)
    np.testing.assert_allclose(param_values_rp['A0'],
                               target_values['background_A0'][1],
                               atol=1.)
    np.testing.assert_allclose(param_values_rp['A1'],
                               target_values['background_A1'][1],
                               atol=1.)
Beispiel #15
0
def test_peak_fitting(qtbot, tmpdir):
    fit_peak_core = pyrscore.PyRsCore()
    window = fitpeakswindow.FitPeaksWindow(None, fit_peak_core=fit_peak_core)
    qtbot.addWidget(window)
    window.show()
    qtbot.wait(wait)

    assert window.isVisible()

    # This is the handle modal dialogs
    def handle_dialog(filename):
        # get a reference to the dialog and handle it here
        dialog = window.findChild(QtWidgets.QFileDialog)
        # get a File Name field
        lineEdit = dialog.findChild(QtWidgets.QLineEdit)
        # Type in file to load and press enter
        qtbot.keyClicks(lineEdit, filename)
        qtbot.wait(wait)
        qtbot.keyClick(lineEdit, QtCore.Qt.Key_Enter)

    # Browser Exp. Data File ...
    # wait until dialog is loaded then handle it, this is required
    # because the dialog is modal
    QtCore.QTimer.singleShot(500, functools.partial(handle_dialog, "tests/data/HB2B_1423.h5"))
    qtbot.mouseClick(window.ui.pushButton_browseHDF, QtCore.Qt.LeftButton)
    qtbot.wait(wait)

    # Select peak range, drag select

    # First get canvas
    canvas = window.ui.frame_PeakView.children()[1]._myCanvas
    # The get start and end mouse points to drag select
    start_x, start_y = canvas.figure.axes[0].transData.transform((78, 500))
    end_x, end_y = canvas.figure.axes[0].transData.transform((85, 500))
    # Drag select with mouse control
    qtbot.mousePress(canvas, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier, QtCore.QPoint(start_x, start_y))
    qtbot.wait(wait)
    qtbot.mouseRelease(canvas, QtCore.Qt.LeftButton, QtCore.Qt.NoModifier, QtCore.QPoint(end_x, end_y))
    qtbot.wait(wait)

    # Peak Ranges Save ...
    peak_range_filename = tmpdir.join("peak_range.json")
    # wait until dialog is loaded then handle it, this is required
    # because the dialog is modal
    QtCore.QTimer.singleShot(500, functools.partial(handle_dialog, str(peak_range_filename)))
    qtbot.mouseClick(window.ui.pushButton_save_peak_range, QtCore.Qt.LeftButton)
    qtbot.wait(wait)

    # check peak range data in json file
    with open(peak_range_filename, 'r') as json_file:
        data = json.load(json_file)
    assert len(data) == 1
    assert '0' in data
    p0 = data['0']
    assert p0['peak_label'] == 'Peak0'
    assert len(p0['d0']) == 0
    start, end = p0['peak_range']
    assert start == pytest.approx(78, abs=0.1)
    assert end == pytest.approx(85, abs=0.1)

    # Fit Peak(s)
    qtbot.mouseClick(window.ui.pushButton_FitPeaks, QtCore.Qt.LeftButton)
    qtbot.wait(wait)

    # Export CSV ...
    # wait until dialog is loaded then handle it, this is required
    # because the dialog is modal
    QtCore.QTimer.singleShot(500, functools.partial(handle_dialog, str(tmpdir)))
    qtbot.mouseClick(window.ui.pushButton_exportCSV, QtCore.Qt.LeftButton)
    qtbot.wait(wait)

    # check output CSV
    assert os.path.isfile(tmpdir.join("HB2B_1423.csv"))
    file_contents = open(tmpdir.join("HB2B_1423.csv")).readlines()
    # check number of lines
    assert len(file_contents) == 127
    # check number of values in line
    assert len(np.fromstring(file_contents[-1], dtype=float, sep=',')) == 33

    # look at 1D results plot
    line = window.ui.graphicsView_fitResult.canvas().get_axis(0, 0, True).lines[0]
    assert line.get_xdata().min() == 1
    assert line.get_xdata().max() == 87
    assert line.get_ydata().min() == pytest.approx(-42.000572)
    assert line.get_ydata().max() == pytest.approx(37.999313)

    # change plot to sx vs d-spacing and check data
    # Scroll ComboBox down to d-spacing
    for _ in range(15):
        qtbot.keyClick(window.ui.comboBox_yaxisNames, QtCore.Qt.Key_Down)
        qtbot.wait(wait)
    # Scroll to sx
    qtbot.keyClick(window.ui.comboBox_xaxisNames, QtCore.Qt.Key_Down)
    qtbot.wait(wait)

    line = window.ui.graphicsView_fitResult.canvas().get_axis(0, 0, True).lines[0]
    assert line.get_xdata().min() == pytest.approx(-42.000572)
    assert line.get_xdata().max() == pytest.approx(37.999313)
    assert line.get_ydata().min() == pytest.approx(1.169515, rel=1e-5)
    assert line.get_ydata().max() == pytest.approx(1.170074, rel=1e-5)

    # Change to Peak Type to Gaussian
    qtbot.keyClick(window.ui.comboBox_peakType, QtCore.Qt.Key_Down)
    qtbot.wait(wait)
    # Fit Peak(s)
    qtbot.mouseClick(window.ui.pushButton_FitPeaks, QtCore.Qt.LeftButton)
    qtbot.wait(wait)

    # Export CSV ...
    # wait until dialog is loaded then handle it, this is required
    # because the dialog is modal
    QtCore.QTimer.singleShot(500, functools.partial(handle_dialog, str(tmpdir)))
    qtbot.mouseClick(window.ui.pushButton_exportCSV, QtCore.Qt.LeftButton)
    qtbot.wait(wait)

    # check output CSV
    assert os.path.isfile(tmpdir.join("HB2B_1423.csv"))
    file_contents = open(tmpdir.join("HB2B_1423.csv")).readlines()
    # check number of lines
    assert len(file_contents) == 127
    # check number of values in line
    assert len(np.fromstring(file_contents[-1], dtype=float, sep=',')) == 33

    # look at 1D results plot
    line = window.ui.graphicsView_fitResult.canvas().get_axis(0, 0, True).lines[0]
    assert line.get_xdata().min() == 1
    assert line.get_xdata().max() == 87
    assert line.get_ydata().min() == pytest.approx(-42.000572)
    assert line.get_ydata().max() == pytest.approx(37.999313)

    # change plot to sx vs d-spacing and check data
    # Scroll ComboBox down to d-spacing
    for _ in range(15):
        qtbot.keyClick(window.ui.comboBox_yaxisNames, QtCore.Qt.Key_Down)
        qtbot.wait(wait)
    # Scroll to sx
    qtbot.keyClick(window.ui.comboBox_xaxisNames, QtCore.Qt.Key_Down)
    qtbot.wait(wait)

    line = window.ui.graphicsView_fitResult.canvas().get_axis(0, 0, True).lines[0]
    assert line.get_xdata().min() == pytest.approx(-42.000572)
    assert line.get_xdata().max() == pytest.approx(37.999313)
    assert line.get_ydata().min() == pytest.approx(1.169389, rel=1e-5)
    assert line.get_ydata().max() == pytest.approx(1.170393, rel=1e-5)
Beispiel #16
0
def main(argv):
    """
    Main
    :param argv:
    :return:
    """
    #
    # Required: HIDRA
    # Optional: Instrument file
    # Optional: mask files
    # Optional: bins

    # long-name, short-name, target name, type, default value, is mandatory, documen
    args_def_list = [('input', 'i', 'inputfile', str, None, True, 'Input HIDRA project file'),
                     ('masks', 'm', 'masksfiles', str, None, False,
                      'Path to an ASCI file containing list of path to mask files, separated by ":", ", " or "\n"'),
                     ('instrument', None, 'instrument', str, None, False, 'Path to instrument file'),
                     ('output', 'o', 'outputfile', str, None, True, 'Output calibration in JSON format'),
                     ('binsize', 'b', 'binsize', float, 0.01, False, '2theta step')]

    try:
        param_dict = script_helper.process_arguments(argv, args_def_list)
    except RuntimeError as run_err:
        print('Failed to parse inputs due to {}'.format(run_err))
        return

    # In case of help
    if param_dict is None:
        return

    # Create calibration control
    calib_controller = pyrscore.PyRsCore()

    # Load data
    project_name = 'calibration xray'
    calib_controller.load_hidra_project(param_dict['inputfile'], project_name=project_name)

    # Reduce data
    calib_controller.reduce_diffraction_data(project_name, num_bins=param_dict['binsize'],
                                             pyrs_engine=True)

    # get handler on reduciton engine
    reduction_engine = calib_controller.reduction_service.get_last_reduction_engine()
    # Get pixels
    pixel_pos_array = reduction_engine.get_pixel_positions(is_matrix=False)  # (N, 3) array
    pixel_2theta_array = reduction_engine.instrument.get_pixels_2theta(dimension=1)  # (N, ) array

    #

    # # Calibration init: import ROI/Mask files
    # if 'masksfiles' in param_dict:
    #     mask_file_list = parse_mask_files(param_dict['masksfiles'])
    #     if len(mask_file_list) < 2:
    #         print ('For X-ray case, user must specify at least 2 masks')
    #         sys.exit(-1)
    # else:
    #     print ('[ERROR] X-ray-calibration algorithm requires Masks')
    #     sys.exit(-1)
    #
    # # Last test before calibration start: reduce by mask
    # for mask_file_name in mask_file_list:
    #     calib_controller.reduce_diffraction_data(project_name,  two_theta_step=param_dict['binsize'],
    #                                              pyrs_engine=True, mask_file_name=mask_file_name)
    # # END-FOR

    # Export reduction data
    calib_controller.save_diffraction_data(project_name, param_dict['inputfile'])

    return