def setUp(self): # creating Data objects self.img_data = ImgModel() self.img_data.load("Data/CbnCorrectionOptimization/Mg2SiO4_091.tif") self.calibration_data = CalibrationModel(self.img_data) self.calibration_data.load("Data/CbnCorrectionOptimization/LaB6_40keV side.poni") self.mask_data = MaskModel() self.mask_data.load_mask("Data/CbnCorrectionOptimization/Mg2SiO4_91_combined.mask") # creating the ObliqueAngleDetectorAbsorptionCorrection _, fit2d_parameter = self.calibration_data.get_calibration_parameter() detector_tilt = fit2d_parameter['tilt'] detector_tilt_rotation = fit2d_parameter['tiltPlanRotation'] self.tth_array = self.calibration_data.spectrum_geometry.twoThetaArray((2048, 2048)) self.azi_array = self.calibration_data.spectrum_geometry.chiArray((2048, 2048)) self.oiadac_correction = ObliqueAngleDetectorAbsorptionCorrection( self.tth_array, self.azi_array, detector_thickness=40, absorption_length=465.5, tilt=detector_tilt, rotation=detector_tilt_rotation, ) self.img_data.add_img_correction(self.oiadac_correction, "oiadac")
def setUp(self): self.working_dir = {} self.img_model = ImgModel() self.mask_model = MaskModel() self.mask_widget = MaskWidget() self.mask_controller = MaskController(self.working_dir, self.mask_widget, self.img_model, self.mask_model)
class MaskControllerTest(unittest.TestCase): def setUp(self): self.app = QtGui.QApplication(sys.argv) self.working_dir = {} self.img_model = ImgModel() self.mask_model = MaskModel() self.mask_widget = MaskWidget() self.mask_controller = MaskController(self.working_dir, self.mask_widget, self.img_model, self.mask_model) def tearDown(self): del self.img_model del self.mask_model self.mask_widget.close() del self.mask_widget del self.mask_controller del self.app gc.collect() def get_file_size(self, filename): stat_info = os.stat(filename) return stat_info.st_size def test_loading_and_saving_mask_files(self): self.mask_controller.load_mask_btn_click(os.path.join(data_path, 'test.mask')) self.mask_model.mask_below_threshold(self.img_model, 1) filename = os.path.join(data_path, 'dummy.mask') self.mask_controller.save_mask_btn_click(filename) self.assertTrue(os.path.exists(filename)) os.remove(filename) def test_loading_and_saving_with_super_sampling(self): self.mask_model.set_supersampling(2) self.mask_controller.load_mask_btn_click(os.path.join(data_path, 'test.mask')) self.assertEqual(self.mask_model.get_mask().shape[0], 4096) self.assertEqual(self.mask_model.get_mask().shape[1], 4096) self.assertEqual(self.mask_model.get_img().shape[0], 2048) self.assertEqual(self.mask_model.get_img().shape[1], 2048) self.mask_model.mask_below_threshold(self.img_model, 1) filename = os.path.join(data_path, 'dummy.mask') self.mask_controller.save_mask_btn_click(filename) self.assertEqual(self.get_file_size(filename), self.get_file_size(os.path.join(data_path, 'test.mask'))) def test_grow_and_shrinking(self): self.mask_model.mask_ellipse(100,100,20,20) previous_mask = np.copy(self.mask_model._mask_data) QTest.mouseClick(self.mask_widget.grow_btn, QtCore.Qt.LeftButton) self.assertFalse(np.array_equal(previous_mask, self.mask_model._mask_data)) QTest.mouseClick(self.mask_widget.shrink_btn, QtCore.Qt.LeftButton) self.assertTrue(np.array_equal(previous_mask, self.mask_model._mask_data))
def setUp(self): self.app = QtGui.QApplication(sys.argv) self.working_dir = {} self.img_model = ImgModel() self.mask_model = MaskModel() self.mask_widget = MaskWidget() self.mask_controller = MaskController(self.working_dir, self.mask_widget, self.img_model, self.mask_model)
def __init__(self, use_settings=True): self.use_settings = use_settings self.widget = MainWidget() # create data self.img_model = ImgModel() self.calibration_model = CalibrationModel(self.img_model) self.mask_model = MaskModel() self.spectrum_model = PatternModel() self.phase_model = PhaseModel() self.settings_directory = os.path.join(os.path.expanduser("~"), '.Dioptas') self.working_directories = { 'calibration': '', 'mask': '', 'image': '', 'spectrum': '', 'overlay': '', 'phase': '' } if use_settings: self.load_settings() self.calibration_controller = CalibrationController( self.working_directories, self.widget.calibration_widget, self.img_model, self.mask_model, self.calibration_model) self.mask_controller = MaskController(self.working_directories, self.widget.mask_widget, self.img_model, self.mask_model) self.integration_controller = IntegrationController( self.working_directories, self.widget.integration_widget, self.img_model, self.mask_model, self.calibration_model, self.spectrum_model, self.phase_model) self.create_signals() self.update_title() self.current_tab_index = 0
def setUp(self): self.app = QtGui.QApplication(sys.argv) self.img_model = ImgModel() self.mask_model = MaskModel() self.calibration_model = CalibrationModel(self.img_model) self.calibration_model._calibrants_working_dir = os.path.join(data_path, 'calibrants') self.calibration_widget = CalibrationWidget() self.working_dir = {} self.calibration_controller = CalibrationController(working_dir=self.working_dir, img_model=self.img_model, mask_model=self.mask_model, widget=self.calibration_widget, calibration_model=self.calibration_model)
def setUp(self): self.working_dir = {'image': ''} self.widget = IntegrationWidget() self.image_model = ImgModel() self.mask_model = MaskModel() self.spectrum_model = PatternModel() self.calibration_model = CalibrationModel(self.image_model) self.controller = ImageController( working_dir=self.working_dir, widget=self.widget, img_model=self.image_model, mask_model=self.mask_model, spectrum_model=self.spectrum_model, calibration_model=self.calibration_model)
def setUp(self): self.img_model = ImgModel() self.mask_model = MaskModel() self.calibration_model = CalibrationModel(self.img_model) self.calibration_model._calibrants_working_dir = os.path.join( data_path, 'calibrants') self.calibration_model.integrate_1d = MagicMock() self.calibration_model.integrate_2d = MagicMock() self.calibration_widget = CalibrationWidget() self.working_dir = {} self.calibration_controller = CalibrationController( working_dir=self.working_dir, img_model=self.img_model, mask_model=self.mask_model, widget=self.calibration_widget, calibration_model=self.calibration_model)
def __init__(self, use_settings=True): self.use_settings = use_settings self.widget = MainWidget() # create data self.img_model = ImgModel() self.calibration_model = CalibrationModel(self.img_model) self.mask_model = MaskModel() self.spectrum_model = PatternModel() self.phase_model = PhaseModel() self.settings_directory = os.path.join(os.path.expanduser("~"), '.Dioptas') self.working_directories = {'calibration': '', 'mask': '', 'image': '', 'spectrum': '', 'overlay': '', 'phase': ''} if use_settings: self.load_settings() self.calibration_controller = CalibrationController(self.working_directories, self.widget.calibration_widget, self.img_model, self.mask_model, self.calibration_model) self.mask_controller = MaskController(self.working_directories, self.widget.mask_widget, self.img_model, self.mask_model) self.integration_controller = IntegrationController(self.working_directories, self.widget.integration_widget, self.img_model, self.mask_model, self.calibration_model, self.spectrum_model, self.phase_model) self.create_signals() self.update_title() self.current_tab_index = 0
def setUp(self): self.mask_model = MaskModel() self.img = np.zeros((10, 10)) self.mask_model.set_dimension(self.img.shape)
class MaskModelTest(unittest.TestCase): def setUp(self): self.mask_model = MaskModel() self.img = np.zeros((10, 10)) self.mask_model.set_dimension(self.img.shape) def tearDown(self): del self.mask_model del self.img gc.collect() def test_growing_masks(self): self.mask_model._mask_data[4, 4] = 1 self.mask_model._mask_data[0, 0] = 1 self.mask_model._mask_data[0, 9] = 1 self.mask_model._mask_data[9, 9] = 1 self.mask_model._mask_data[9, 0] = 1 self.mask_model.grow() # test corners self.assertEqual(self.mask_model._mask_data[0, 1], 1) self.assertEqual(self.mask_model._mask_data[1, 1], 1) self.assertEqual(self.mask_model._mask_data[1, 0], 1) self.assertEqual(self.mask_model._mask_data[0, 8], 1) self.assertEqual(self.mask_model._mask_data[1, 8], 1) self.assertEqual(self.mask_model._mask_data[1, 9], 1) self.assertEqual(self.mask_model._mask_data[8, 0], 1) self.assertEqual(self.mask_model._mask_data[8, 1], 1) self.assertEqual(self.mask_model._mask_data[9, 1], 1) self.assertEqual(self.mask_model._mask_data[8, 8], 1) self.assertEqual(self.mask_model._mask_data[8, 9], 1) self.assertEqual(self.mask_model._mask_data[9, 8], 1) # test center self.assertEqual(self.mask_model._mask_data[3, 3], 1) self.assertEqual(self.mask_model._mask_data[4, 3], 1) self.assertEqual(self.mask_model._mask_data[5, 3], 1) self.assertEqual(self.mask_model._mask_data[3, 5], 1) self.assertEqual(self.mask_model._mask_data[4, 5], 1) self.assertEqual(self.mask_model._mask_data[5, 5], 1) self.assertEqual(self.mask_model._mask_data[3, 4], 1) self.assertEqual(self.mask_model._mask_data[5, 4], 1) def test_shrink_mask(self): self.mask_model._mask_data[4, 4] = 1 self.mask_model._mask_data[0, 0] = 1 self.mask_model._mask_data[0, 9] = 1 self.mask_model._mask_data[9, 9] = 1 self.mask_model._mask_data[9, 0] = 1 self.before_mask = np.copy(self.mask_model._mask_data) self.mask_model.grow() self.mask_model.shrink() self.assertTrue(np.array_equal(self.before_mask, self.mask_model._mask_data)) self.mask_model.clear_mask() self.mask_model._mask_data[4, 4] = 1 self.mask_model._mask_data[5, 4] = 1 self.mask_model._mask_data[5, 5] = 1 self.mask_model._mask_data[4, 5] = 1 self.mask_model.shrink() self.assertEqual(np.sum(self.mask_model._mask_data), 0) def test_saving_and_loading(self): self.mask_model.mask_ellipse(1024, 1024, 100, 100) self.mask_model.set_dimension((2048, 2048)) mask_array = np.copy(self.mask_model.get_img()) filename = os.path.join(data_path, "dummy.mask") self.mask_model.save_mask(filename) self.mask_model.load_mask(filename) self.assertTrue(np.array_equal(mask_array, self.mask_model.get_img())) os.remove(filename)
class MainController(object): """ Creates a the main controller for Dioptas. Creates all the data objects and connects them with the other controllers """ def __init__(self, use_settings=True): self.use_settings = use_settings self.widget = MainWidget() # create data self.img_model = ImgModel() self.calibration_model = CalibrationModel(self.img_model) self.mask_model = MaskModel() self.spectrum_model = PatternModel() self.phase_model = PhaseModel() self.settings_directory = os.path.join(os.path.expanduser("~"), '.Dioptas') self.working_directories = {'calibration': '', 'mask': '', 'image': '', 'spectrum': '', 'overlay': '', 'phase': ''} if use_settings: self.load_settings() self.calibration_controller = CalibrationController(self.working_directories, self.widget.calibration_widget, self.img_model, self.mask_model, self.calibration_model) self.mask_controller = MaskController(self.working_directories, self.widget.mask_widget, self.img_model, self.mask_model) self.integration_controller = IntegrationController(self.working_directories, self.widget.integration_widget, self.img_model, self.mask_model, self.calibration_model, self.spectrum_model, self.phase_model) self.create_signals() self.update_title() self.current_tab_index = 0 def show_window(self): """ Displays the main window on the screen and makes it active. """ self.widget.show() if _platform == "darwin": self.widget.setWindowState(self.widget.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive) self.widget.activateWindow() self.widget.raise_() def create_signals(self): """ Creates subscriptions for changing tabs and also newly loaded files which will update the title of the main window. """ self.widget.tabWidget.currentChanged.connect(self.tab_changed) self.widget.closeEvent = self.close_event self.img_model.img_changed.connect(self.update_title) self.spectrum_model.pattern_changed.connect(self.update_title) def tab_changed(self, ind): """ Function which is called when a tab has been selected (calibration, mask, or integration). Performs needed initialization tasks. :param ind: index for the tab selected (2 - integration, 1 = mask, 0 - calibration) :return: """ old_index = self.current_tab_index self.current_tab_index = ind # get the old view range old_view_range = None old_hist_levels = None if old_index == 0: # calibration tab old_view_range = self.widget.calibration_widget.img_widget.img_view_box.targetRange() old_hist_levels = self.widget.calibration_widget.img_widget.img_histogram_LUT.getExpLevels() elif old_index == 1: # mask tab old_view_range = self.widget.mask_widget.img_widget.img_view_box.targetRange() old_hist_levels = self.widget.mask_widget.img_widget.img_histogram_LUT.getExpLevels() elif old_index == 2: old_view_range = self.widget.integration_widget.img_widget.img_view_box.targetRange() old_hist_levels = self.widget.integration_widget.img_widget.img_histogram_LUT.getExpLevels() # update the GUI if ind == 2: # integration tab self.mask_model.set_supersampling() self.integration_controller.image_controller.plot_mask() self.integration_controller.widget.calibration_lbl.setText(self.calibration_model.calibration_name) self.integration_controller.image_controller._auto_scale = False self.integration_controller.spectrum_controller.image_changed() self.integration_controller.image_controller.update_img() self.widget.integration_widget.img_widget.set_range(x_range=old_view_range[0], y_range=old_view_range[1]) self.widget.integration_widget.img_widget.img_histogram_LUT.setLevels(*old_hist_levels) elif ind == 1: # mask tab self.mask_controller.plot_mask() self.mask_controller.plot_image() self.widget.mask_widget.img_widget.set_range(x_range=old_view_range[0], y_range=old_view_range[1]) self.widget.mask_widget.img_widget.img_histogram_LUT.setLevels(*old_hist_levels) elif ind == 0: # calibration tab self.calibration_controller.plot_mask() try: self.calibration_controller.update_calibration_parameter_in_view() except (TypeError, AttributeError): pass self.widget.calibration_widget.img_widget.set_range(x_range=old_view_range[0], y_range=old_view_range[1]) self.widget.calibration_widget.img_widget.img_histogram_LUT.setLevels(*old_hist_levels) def update_title(self): """ Updates the title bar of the main window. The title bar will always show the current version of Dioptas, the image or spectrum filenames loaded and the current calibration name. """ img_filename = os.path.basename(self.img_model.filename) spec_filename = os.path.basename(self.spectrum_model.pattern_filename) calibration_name = self.calibration_model.calibration_name str = 'Dioptas ' + __version__ if img_filename is '' and spec_filename is '': self.widget.setWindowTitle(str + u' - © 2015 C. Prescher') self.widget.integration_widget.img_frame.setWindowTitle(str + u' - © 2015 C. Prescher') return if img_filename is not '' or spec_filename is not '': str += ' - [' if img_filename is not '': str += img_filename elif img_filename is '' and spec_filename is not '': str += spec_filename if not img_filename == spec_filename: str += ', ' + spec_filename if calibration_name is not None: str += ', calibration: ' + calibration_name str += ']' str += u' - © 2015 C. Prescher' self.widget.setWindowTitle(str) self.widget.integration_widget.img_frame.setWindowTitle(str) def load_settings(self): """ Loads previously saved Dioptas settings. """ if os.path.exists(self.settings_directory): self.load_directories() self.load_xml_settings() def load_directories(self): """ Loads previously used Dioptas directory paths. """ working_directories_path = os.path.join(self.settings_directory, 'working_directories.csv') if os.path.exists(working_directories_path): reader = csv.reader(open(working_directories_path, 'r')) self.working_directories = dict(x for x in reader) def load_xml_settings(self): """ Loads previously used Dioptas settings. Currently this is only the calibration. :return: """ xml_settings_path = os.path.join(self.settings_directory, "settings.xml") if os.path.exists(xml_settings_path): tree = ET.parse(xml_settings_path) root = tree.getroot() filenames = root.find("filenames") calibration_path = filenames.find("calibration").text if os.path.exists(str(calibration_path)): self.calibration_model.load(calibration_path) def save_settings(self): """ Saves current settings of Dioptas in the users directory. """ if not os.path.exists(self.settings_directory): os.mkdir(self.settings_directory) self.save_directories() self.save_xml_settings() def save_directories(self): """ Currently used working directories for images, spectra, etc. are saved as csv file in the users directory for reuse when Dioptas is started again """ working_directories_path = os.path.join(self.settings_directory, 'working_directories.csv') writer = csv.writer(open(working_directories_path, 'w')) for key, value in list(self.working_directories.items()): writer.writerow([key, value]) writer.writerow([key, value]) def save_xml_settings(self): """ Currently used settings of Dioptas are saved in to an xml file in the users directory for reuse when Dioptas is started again. Right now this is only saving the calibration filename. """ root = ET.Element("DioptasSettings") filenames = ET.SubElement(root, "filenames") calibration_filename = ET.SubElement(filenames, "calibration") calibration_filename.text = self.calibration_model.filename tree = ET.ElementTree(root) tree.write(os.path.join(self.settings_directory, "settings.xml")) def close_event(self, _): """ Intervention of the Dioptas close event to save settings before closing the Program. """ if self.use_settings: self.save_settings() QtGui.QApplication.closeAllWindows() QtGui.QApplication.quit()
class MaskControllerTest(unittest.TestCase): @classmethod def setUpClass(cls): cls.app = QtGui.QApplication([]) @classmethod def tearDownClass(cls): cls.app.quit() cls.app.deleteLater() def setUp(self): self.working_dir = {} self.img_model = ImgModel() self.mask_model = MaskModel() self.mask_widget = MaskWidget() self.mask_controller = MaskController(self.working_dir, self.mask_widget, self.img_model, self.mask_model) def tearDown(self): del self.img_model del self.mask_model self.mask_widget.close() del self.mask_widget del self.mask_controller gc.collect() def get_file_size(self, filename): stat_info = os.stat(filename) return stat_info.st_size def test_loading_and_saving_mask_files(self): self.mask_controller.load_mask_btn_click( os.path.join(data_path, 'test.mask')) self.mask_model.mask_below_threshold(self.img_model, 1) filename = os.path.join(data_path, 'dummy.mask') self.mask_controller.save_mask_btn_click(filename) self.assertTrue(os.path.exists(filename)) os.remove(filename) def test_loading_and_saving_with_super_sampling(self): self.mask_model.set_supersampling(2) self.mask_controller.load_mask_btn_click( os.path.join(data_path, 'test.mask')) self.assertEqual(self.mask_model.get_mask().shape[0], 4096) self.assertEqual(self.mask_model.get_mask().shape[1], 4096) self.assertEqual(self.mask_model.get_img().shape[0], 2048) self.assertEqual(self.mask_model.get_img().shape[1], 2048) self.mask_model.mask_below_threshold(self.img_model, 1) filename = os.path.join(data_path, 'dummy.mask') self.mask_controller.save_mask_btn_click(filename) self.assertAlmostEqual(self.get_file_size(filename), self.get_file_size( os.path.join(data_path, 'test.mask')), delta=20) def test_grow_and_shrinking(self): self.mask_model.mask_ellipse(100, 100, 20, 20) previous_mask = np.copy(self.mask_model._mask_data) QTest.mouseClick(self.mask_widget.grow_btn, QtCore.Qt.LeftButton) self.assertFalse( np.array_equal(previous_mask, self.mask_model._mask_data)) QTest.mouseClick(self.mask_widget.shrink_btn, QtCore.Qt.LeftButton) self.assertTrue( np.array_equal(previous_mask, self.mask_model._mask_data))
class MaskModelTest(unittest.TestCase): def setUp(self): self.mask_model = MaskModel() self.img = np.zeros((10, 10)) self.mask_model.set_dimension(self.img.shape) def tearDown(self): del self.mask_model del self.img gc.collect() def test_growing_masks(self): self.mask_model._mask_data[4, 4] = 1 self.mask_model._mask_data[0, 0] = 1 self.mask_model._mask_data[0, 9] = 1 self.mask_model._mask_data[9, 9] = 1 self.mask_model._mask_data[9, 0] = 1 self.mask_model.grow() # tests corners self.assertEqual(self.mask_model._mask_data[0, 1], 1) self.assertEqual(self.mask_model._mask_data[1, 1], 1) self.assertEqual(self.mask_model._mask_data[1, 0], 1) self.assertEqual(self.mask_model._mask_data[0, 8], 1) self.assertEqual(self.mask_model._mask_data[1, 8], 1) self.assertEqual(self.mask_model._mask_data[1, 9], 1) self.assertEqual(self.mask_model._mask_data[8, 0], 1) self.assertEqual(self.mask_model._mask_data[8, 1], 1) self.assertEqual(self.mask_model._mask_data[9, 1], 1) self.assertEqual(self.mask_model._mask_data[8, 8], 1) self.assertEqual(self.mask_model._mask_data[8, 9], 1) self.assertEqual(self.mask_model._mask_data[9, 8], 1) # tests center self.assertEqual(self.mask_model._mask_data[3, 3], 1) self.assertEqual(self.mask_model._mask_data[4, 3], 1) self.assertEqual(self.mask_model._mask_data[5, 3], 1) self.assertEqual(self.mask_model._mask_data[3, 5], 1) self.assertEqual(self.mask_model._mask_data[4, 5], 1) self.assertEqual(self.mask_model._mask_data[5, 5], 1) self.assertEqual(self.mask_model._mask_data[3, 4], 1) self.assertEqual(self.mask_model._mask_data[5, 4], 1) def test_shrink_mask(self): self.mask_model._mask_data[4, 4] = 1 self.mask_model._mask_data[0, 0] = 1 self.mask_model._mask_data[0, 9] = 1 self.mask_model._mask_data[9, 9] = 1 self.mask_model._mask_data[9, 0] = 1 self.before_mask = np.copy(self.mask_model._mask_data) self.mask_model.grow() self.mask_model.shrink() self.assertTrue(np.array_equal(self.before_mask, self.mask_model._mask_data)) self.mask_model.clear_mask() self.mask_model._mask_data[4, 4] = 1 self.mask_model._mask_data[5, 4] = 1 self.mask_model._mask_data[5, 5] = 1 self.mask_model._mask_data[4, 5] = 1 self.mask_model.shrink() self.assertEqual(np.sum(self.mask_model._mask_data), 0) def test_saving_and_loading(self): self.mask_model.mask_ellipse(1024, 1024, 100, 100) self.mask_model.set_dimension((2048, 2048)) mask_array = np.copy(self.mask_model.get_img()) filename = os.path.join(data_path, 'dummy.mask') self.mask_model.save_mask(filename) self.mask_model.load_mask(filename) self.assertTrue(np.array_equal(mask_array, self.mask_model.get_img())) os.remove(filename)
class CbnAbsorptionCorrectionOptimizationTest(unittest.TestCase): def setUp(self): # creating Data objects self.img_data = ImgModel() self.img_data.load("Data/CbnCorrectionOptimization/Mg2SiO4_091.tif") self.calibration_data = CalibrationModel(self.img_data) self.calibration_data.load("Data/CbnCorrectionOptimization/LaB6_40keV side.poni") self.mask_data = MaskModel() self.mask_data.load_mask("Data/CbnCorrectionOptimization/Mg2SiO4_91_combined.mask") # creating the ObliqueAngleDetectorAbsorptionCorrection _, fit2d_parameter = self.calibration_data.get_calibration_parameter() detector_tilt = fit2d_parameter['tilt'] detector_tilt_rotation = fit2d_parameter['tiltPlanRotation'] self.tth_array = self.calibration_data.spectrum_geometry.twoThetaArray((2048, 2048)) self.azi_array = self.calibration_data.spectrum_geometry.chiArray((2048, 2048)) self.oiadac_correction = ObliqueAngleDetectorAbsorptionCorrection( self.tth_array, self.azi_array, detector_thickness=40, absorption_length=465.5, tilt=detector_tilt, rotation=detector_tilt_rotation, ) self.img_data.add_img_correction(self.oiadac_correction, "oiadac") def tearDown(self): del self.calibration_data.cake_geometry del self.calibration_data.spectrum_geometry def test_the_world(self): params = Parameters() params.add("diamond_thickness", value=2, min=1.9, max=2.3) params.add("seat_thickness", value=5.3, min=4.0, max=6.6, vary=False) params.add("small_cbn_seat_radius", value=0.2, min=0.10, max=0.5, vary=True) params.add("large_cbn_seat_radius", value=1.95, min=1.85, max=2.05, vary=False) params.add("tilt", value=3.3, min=0, max=8) params.add("tilt_rotation", value=0, min=-15, max=+15) params.add("cbn_abs_length", value=14.05, min=12, max=16) region = [8, 26] self.tth_array = 180.0 / np.pi * self.tth_array self.azi_array = 180.0 / np.pi * self.azi_array def fcn2min(params): cbn_correction = CbnCorrection( tth_array=self.tth_array, azi_array=self.azi_array, diamond_thickness=params['diamond_thickness'].value, seat_thickness=params['seat_thickness'].value, small_cbn_seat_radius=params['small_cbn_seat_radius'].value, large_cbn_seat_radius=params['large_cbn_seat_radius'].value, tilt=params['tilt'].value, tilt_rotation=params['tilt_rotation'].value, cbn_abs_length=params["cbn_abs_length"].value ) self.img_data.add_img_correction(cbn_correction, "cbn") tth, int = self.calibration_data.integrate_1d(mask=self.mask_data.get_mask()) self.img_data.delete_img_correction("cbn") ind = np.where((tth > region[0]) & (tth < region[1])) int = gaussian_filter1d(int, 20) return (np.diff(int[ind])) ** 2 def output_values(param1, iteration, residual): report_fit(param1) result = minimize(fcn2min, params, iter_cb=output_values) report_fit(params) # plotting result: cbn_correction = CbnCorrection( tth_array=self.tth_array, azi_array=self.azi_array, diamond_thickness=params['diamond_thickness'].value, seat_thickness=params['seat_thickness'].value, small_cbn_seat_radius=params['small_cbn_seat_radius'].value, large_cbn_seat_radius=params['large_cbn_seat_radius'].value, tilt=params['tilt'].value, tilt_rotation=params['tilt_rotation'].value, cbn_abs_length=params['cbn_abs_length'].value ) self.img_data.add_img_correction(cbn_correction, "cbn") tth, int = self.calibration_data.integrate_1d(mask=self.mask_data.get_mask()) ind = np.where((tth > region[0]) & (tth < region[1])) tth = tth[ind] int = int[ind] int_smooth = gaussian_filter1d(int, 10) int_diff1 = np.diff(int) int_diff1_smooth = np.diff(int_smooth) int_diff2 = np.diff(int_diff1) int_diff2_smooth = np.diff(int_diff1_smooth) plt.figure() plt.subplot(3, 1, 1) plt.plot(tth, int) plt.plot(tth, int_smooth) plt.subplot(3, 1, 2) plt.plot(int_diff1) plt.plot(int_diff1_smooth) plt.subplot(3, 1, 3) plt.plot(int_diff2) plt.plot(int_diff2_smooth) plt.savefig("Results/optimize_cbn_absorption.png", dpi=300) os.system("open " + "Results/optimize_cbn_absorption.png")
class MainController(object): """ Creates a the main controller for Dioptas. Creates all the data objects and connects them with the other controllers """ def __init__(self, use_settings=True): self.use_settings = use_settings self.widget = MainWidget() # create data self.img_model = ImgModel() self.calibration_model = CalibrationModel(self.img_model) self.mask_model = MaskModel() self.spectrum_model = PatternModel() self.phase_model = PhaseModel() self.settings_directory = os.path.join(os.path.expanduser("~"), '.Dioptas') self.working_directories = { 'calibration': '', 'mask': '', 'image': '', 'spectrum': '', 'overlay': '', 'phase': '' } if use_settings: self.load_settings() self.calibration_controller = CalibrationController( self.working_directories, self.widget.calibration_widget, self.img_model, self.mask_model, self.calibration_model) self.mask_controller = MaskController(self.working_directories, self.widget.mask_widget, self.img_model, self.mask_model) self.integration_controller = IntegrationController( self.working_directories, self.widget.integration_widget, self.img_model, self.mask_model, self.calibration_model, self.spectrum_model, self.phase_model) self.create_signals() self.update_title() self.current_tab_index = 0 def show_window(self): """ Displays the main window on the screen and makes it active. """ self.widget.show() if _platform == "darwin": self.widget.setWindowState(self.widget.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive) self.widget.activateWindow() self.widget.raise_() def create_signals(self): """ Creates subscriptions for changing tabs and also newly loaded files which will update the title of the main window. """ self.widget.tabWidget.currentChanged.connect(self.tab_changed) self.widget.closeEvent = self.close_event self.img_model.img_changed.connect(self.update_title) self.spectrum_model.pattern_changed.connect(self.update_title) def tab_changed(self, ind): """ Function which is called when a tab has been selected (calibration, mask, or integration). Performs needed initialization tasks. :param ind: index for the tab selected (2 - integration, 1 = mask, 0 - calibration) :return: """ old_index = self.current_tab_index self.current_tab_index = ind # get the old view range old_view_range = None old_hist_levels = None if old_index == 0: # calibration tab old_view_range = self.widget.calibration_widget.img_widget.img_view_box.targetRange( ) old_hist_levels = self.widget.calibration_widget.img_widget.img_histogram_LUT.getExpLevels( ) elif old_index == 1: # mask tab old_view_range = self.widget.mask_widget.img_widget.img_view_box.targetRange( ) old_hist_levels = self.widget.mask_widget.img_widget.img_histogram_LUT.getExpLevels( ) elif old_index == 2: old_view_range = self.widget.integration_widget.img_widget.img_view_box.targetRange( ) old_hist_levels = self.widget.integration_widget.img_widget.img_histogram_LUT.getExpLevels( ) # update the GUI if ind == 2: # integration tab self.mask_model.set_supersampling() self.integration_controller.image_controller.plot_mask() self.integration_controller.widget.calibration_lbl.setText( self.calibration_model.calibration_name) self.integration_controller.image_controller._auto_scale = False self.integration_controller.spectrum_controller.image_changed() self.integration_controller.image_controller.update_img() self.widget.integration_widget.img_widget.set_range( x_range=old_view_range[0], y_range=old_view_range[1]) self.widget.integration_widget.img_widget.img_histogram_LUT.setLevels( *old_hist_levels) elif ind == 1: # mask tab self.mask_controller.plot_mask() self.mask_controller.plot_image() self.widget.mask_widget.img_widget.set_range( x_range=old_view_range[0], y_range=old_view_range[1]) self.widget.mask_widget.img_widget.img_histogram_LUT.setLevels( *old_hist_levels) elif ind == 0: # calibration tab self.calibration_controller.plot_mask() try: self.calibration_controller.update_calibration_parameter_in_view( ) except (TypeError, AttributeError): pass self.widget.calibration_widget.img_widget.set_range( x_range=old_view_range[0], y_range=old_view_range[1]) self.widget.calibration_widget.img_widget.img_histogram_LUT.setLevels( *old_hist_levels) def update_title(self): """ Updates the title bar of the main window. The title bar will always show the current version of Dioptas, the image or spectrum filenames loaded and the current calibration name. """ img_filename = os.path.basename(self.img_model.filename) spec_filename = os.path.basename(self.spectrum_model.pattern_filename) calibration_name = self.calibration_model.calibration_name str = 'Dioptas ' + __version__ if img_filename is '' and spec_filename is '': self.widget.setWindowTitle(str + u' - © 2015 C. Prescher') self.widget.integration_widget.img_frame.setWindowTitle( str + u' - © 2015 C. Prescher') return if img_filename is not '' or spec_filename is not '': str += ' - [' if img_filename is not '': str += img_filename elif img_filename is '' and spec_filename is not '': str += spec_filename if not img_filename == spec_filename: str += ', ' + spec_filename if calibration_name is not None: str += ', calibration: ' + calibration_name str += ']' str += u' - © 2015 C. Prescher' self.widget.setWindowTitle(str) self.widget.integration_widget.img_frame.setWindowTitle(str) def load_settings(self): """ Loads previously saved Dioptas settings. """ if os.path.exists(self.settings_directory): self.load_directories() self.load_xml_settings() def load_directories(self): """ Loads previously used Dioptas directory paths. """ working_directories_path = os.path.join(self.settings_directory, 'working_directories.csv') if os.path.exists(working_directories_path): reader = csv.reader(open(working_directories_path, 'r')) self.working_directories = dict(x for x in reader) def load_xml_settings(self): """ Loads previously used Dioptas settings. Currently this is only the calibration. :return: """ xml_settings_path = os.path.join(self.settings_directory, "settings.xml") if os.path.exists(xml_settings_path): tree = ET.parse(xml_settings_path) root = tree.getroot() filenames = root.find("filenames") calibration_path = filenames.find("calibration").text if os.path.exists(str(calibration_path)): self.calibration_model.load(calibration_path) def save_settings(self): """ Saves current settings of Dioptas in the users directory. """ if not os.path.exists(self.settings_directory): os.mkdir(self.settings_directory) self.save_directories() self.save_xml_settings() def save_directories(self): """ Currently used working directories for images, spectra, etc. are saved as csv file in the users directory for reuse when Dioptas is started again """ working_directories_path = os.path.join(self.settings_directory, 'working_directories.csv') writer = csv.writer(open(working_directories_path, 'w')) for key, value in list(self.working_directories.items()): writer.writerow([key, value]) writer.writerow([key, value]) def save_xml_settings(self): """ Currently used settings of Dioptas are saved in to an xml file in the users directory for reuse when Dioptas is started again. Right now this is only saving the calibration filename. """ root = ET.Element("DioptasSettings") filenames = ET.SubElement(root, "filenames") calibration_filename = ET.SubElement(filenames, "calibration") calibration_filename.text = self.calibration_model.filename tree = ET.ElementTree(root) tree.write(os.path.join(self.settings_directory, "settings.xml")) def close_event(self, _): """ Intervention of the Dioptas close event to save settings before closing the Program. """ if self.use_settings: self.save_settings() QtGui.QApplication.closeAllWindows() QtGui.QApplication.quit()
class MainController(object): """ Creates a the main controller for Dioptas. Loads all the data objects and connects them with the other controllers """ def __init__(self, use_settings=True): self.use_settings = use_settings self.widget = MainWidget() #create data self.img_model = ImgModel() self.calibration_model = CalibrationModel(self.img_model) self.mask_model = MaskModel() self.spectrum_model = SpectrumModel() self.phase_model = PhaseModel() self.settings_directory = os.path.join(os.path.expanduser("~"), '.Dioptas') self.working_directories = {'calibration': '', 'mask': '', 'image': '', 'spectrum': '', 'overlay': '', 'phase': ''} if use_settings: self.load_settings() #create controller self.calibration_controller = CalibrationController(self.working_directories, self.widget.calibration_widget, self.img_model, self.mask_model, self.calibration_model) self.mask_controller = MaskController(self.working_directories, self.widget.mask_widget, self.img_model, self.mask_model) self.integration_controller = IntegrationController(self.working_directories, self.widget.integration_widget, self.img_model, self.mask_model, self.calibration_model, self.spectrum_model, self.phase_model) self.create_signals() self.set_title() def show_window(self): self.widget.show() self.widget.setWindowState(self.widget.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive) self.widget.activateWindow() self.widget.raise_() def create_signals(self): self.widget.tabWidget.currentChanged.connect(self.tab_changed) self.widget.closeEvent = self.close_event self.img_model.subscribe(self.set_title) self.spectrum_model.spectrum_changed.connect(self.set_title) def tab_changed(self, ind): if ind == 2: self.mask_model.set_supersampling() self.integration_controller.image_controller.plot_mask() self.integration_controller.widget.calibration_lbl.setText(self.calibration_model.calibration_name) self.integration_controller.image_controller._auto_scale = False self.integration_controller.spectrum_controller.image_changed() self.integration_controller.image_controller.update_img() elif ind == 1: self.mask_controller.plot_mask() self.mask_controller.plot_image() elif ind == 0: self.calibration_controller.plot_mask() try: self.calibration_controller.update_calibration_parameter_in_view() except (TypeError, AttributeError): pass def set_title(self): img_filename = os.path.basename(self.img_model.filename) spec_filename = os.path.basename(self.spectrum_model.spectrum_filename) calibration_name = self.calibration_model.calibration_name str = 'Dioptas ' + __version__ if img_filename is '' and spec_filename is '': self.widget.setWindowTitle(str + u' - © 2015 C. Prescher') self.widget.integration_widget.img_frame.setWindowTitle(str + u' - © 2015 C. Prescher') return if img_filename is not '' or spec_filename is not '': str += ' - [' if img_filename is not '': str += img_filename elif img_filename is '' and spec_filename is not '': str += spec_filename if not img_filename == spec_filename: str += ', ' + spec_filename if calibration_name is not None: str += ', calibration: ' + calibration_name str += ']' str += u' - © 2015 C. Prescher' self.widget.setWindowTitle(str) self.widget.integration_widget.img_frame.setWindowTitle(str) def load_settings(self): if os.path.exists(self.settings_directory): self.load_directories() self.load_xml_settings() def load_directories(self): working_directories_path = os.path.join(self.settings_directory, 'working_directories.csv') if os.path.exists(working_directories_path): reader = csv.reader(open(working_directories_path, 'r')) self.working_directories = dict(x for x in reader) def load_xml_settings(self): xml_settings_path = os.path.join(self.settings_directory, "settings.xml") if os.path.exists(xml_settings_path): tree = ET.parse(xml_settings_path) root = tree.getroot() filenames = root.find("filenames") calibration_path=filenames.find("calibration").text if os.path.exists(str(calibration_path)): self.calibration_model.load(calibration_path) def save_settings(self): if not os.path.exists(self.settings_directory): os.mkdir(self.settings_directory) self.save_directories() self.save_xml_settings() def save_directories(self): working_directories_path = os.path.join(self.settings_directory, 'working_directories.csv') writer = csv.writer(open(working_directories_path, 'w')) for key, value in list(self.working_directories.items()): writer.writerow([key, value]) writer.writerow([key, value]) def save_xml_settings(self): root = ET.Element("DioptasSettings") filenames = ET.SubElement(root, "filenames") calibration_filename = ET.SubElement(filenames, "calibration") calibration_filename.text = self.calibration_model.filename tree = ET.ElementTree(root) tree.write(os.path.join(self.settings_directory, "settings.xml")) def close_event(self, _): if self.use_settings: self.save_settings() QtGui.QApplication.closeAllWindows() QtGui.QApplication.quit()
class CalibrationControllerTest(unittest.TestCase): def setUp(self): self.app = QtGui.QApplication(sys.argv) self.img_model = ImgModel() self.mask_model = MaskModel() self.calibration_model = CalibrationModel(self.img_model) self.calibration_model._calibrants_working_dir = os.path.join(data_path, 'calibrants') self.calibration_widget = CalibrationWidget() self.working_dir = {} self.calibration_controller = CalibrationController(working_dir=self.working_dir, img_model=self.img_model, mask_model=self.mask_model, widget=self.calibration_widget, calibration_model=self.calibration_model) def tearDown(self): del self.img_model del self.calibration_model.cake_geometry del self.calibration_model.spectrum_geometry del self.calibration_model del self.app gc.collect() def load_pilatus_1M_and_pick_peaks(self): self.calibration_controller.load_img(os.path.join(data_path,'CeO2_Pilatus1M.tif')) QTest.mouseClick(self.calibration_widget.automatic_peak_num_inc_cb, QtCore.Qt.LeftButton) self.assertFalse(self.calibration_widget.automatic_peak_num_inc_cb.isChecked()) self.calibration_controller.search_peaks(517.664434674, 647.529865592) self.calibration_controller.search_peaks(667.380513299, 525.252854758) self.calibration_controller.search_peaks(671.110095329, 473.571503774) self.calibration_controller.search_peaks(592.788872703, 350.495296791) self.calibration_controller.search_peaks(387.395462348, 390.987901686) self.calibration_controller.search_peaks(367.94835605, 554.290314848) self.calibration_widget.sv_wavelength_txt.setText('0.406626') self.calibration_widget.sv_distance_txt.setText('200') self.calibration_widget.sv_pixel_width_txt.setText('172') self.calibration_widget.sv_pixel_height_txt.setText('172') calibrant_index = self.calibration_widget.calibrant_cb.findText('CeO2') self.calibration_widget.calibrant_cb.setCurrentIndex(calibrant_index) self.mask_model.set_dimension(self.img_model.img_data.shape) def test_automatic_calibration1(self): self.calibration_controller.load_img(os.path.join(data_path,'LaB6_40keV_MarCCD.tif')) self.calibration_controller.search_peaks(1179.6, 1129.4) self.calibration_controller.search_peaks(1268.5, 1119.8) self.calibration_controller.widget.sv_wavelength_txt.setText('0.31') self.calibration_controller.widget.sv_distance_txt.setText('200') self.calibration_controller.widget.sv_pixel_width_txt.setText('79') self.calibration_controller.widget.sv_pixel_height_txt.setText('79') calibrant_index = self.calibration_widget.calibrant_cb.findText('LaB6') self.calibration_controller.widget.calibrant_cb.setCurrentIndex(calibrant_index) self.calibration_controller.calibrate() self.calibration_controller.widget.cake_view.set_vertical_line_pos(1419.8, 653.4) def test_automatic_calibration2(self): self.calibration_controller.load_img(os.path.join(data_path,'LaB6_OffCenter_PE.tif')) self.calibration_controller.search_peaks(1245.2, 1919.3) self.calibration_controller.search_peaks(1334.0, 1823.7) self.calibration_controller.widget.sv_wavelength_txt.setText('0.3344') self.calibration_controller.widget.sv_distance_txt.setText('500') self.calibration_controller.widget.sv_pixel_width_txt.setText('200') self.calibration_controller.widget.sv_pixel_height_txt.setText('200') calibrant_index = self.calibration_widget.calibrant_cb.findText('LaB6') self.calibration_controller.widget.calibrant_cb.setCurrentIndex(calibrant_index) self.calibration_controller.calibrate() self.calibration_controller.widget.cake_view.set_vertical_line_pos(206.5, 171.6) def test_automatic_calibration3(self): self.load_pilatus_1M_and_pick_peaks() start_values = self.calibration_widget.get_start_values() self.assertAlmostEqual(start_values['wavelength'], 0.406626e-10) self.assertAlmostEqual(start_values['pixel_height'], 172e-6) self.assertAlmostEqual(start_values['pixel_width'], 172e-6) self.calibration_controller.load_calibrant() self.assertAlmostEqual(self.calibration_model.calibrant.wavelength, 0.406626e-10) QTest.mouseClick(self.calibration_widget.integrate_btn, QtCore.Qt.LeftButton) calibration_parameter = self.calibration_model.get_calibration_parameter()[0] self.assertAlmostEqual(calibration_parameter['dist'], .2086, places=4) def test_automatic_calibration_with_supersampling(self): self.load_pilatus_1M_and_pick_peaks() self.img_model.set_supersampling(2) self.calibration_model.set_supersampling(2) self.calibration_controller.calibrate() def test_automatic_calibration_with_supersampling_and_mask(self): self.load_pilatus_1M_and_pick_peaks() self.img_model.set_supersampling(2) self.mask_model.mask_below_threshold(self.img_model._img_data, 1) self.mask_model.set_supersampling(2) self.calibration_model.set_supersampling(2) self.calibration_controller.widget.use_mask_cb.setChecked(True) self.calibration_controller.calibrate() def test_calibrating_one_image_size_and_loading_different_image_size(self): self.load_pilatus_1M_and_pick_peaks() self.calibration_controller.calibrate() self.calibration_model.integrate_1d() self.calibration_model.integrate_2d() self.calibration_controller.load_img(os.path.join(data_path, 'CeO2_Pilatus1M.tif')) self.calibration_model.integrate_1d() self.calibration_model.integrate_2d() def test_loading_and_saving_of_calibration_files(self): self.calibration_controller.load_calibration(os.path.join(data_path, 'LaB6_40keV_MarCCD.poni')) self.calibration_controller.save_calibration(os.path.join(data_path, 'calibration.poni')) self.assertTrue(os.path.exists(os.path.join(data_path, 'calibration.poni'))) os.remove(os.path.join(data_path, 'calibration.poni'))