예제 #1
0
    def __init__(self,
                 working_dir,
                 view=None,
                 img_data=None,
                 calibration_data=None):
        self.working_dir = working_dir
        if view == None:
            self.view = CalibrationView()
        else:
            self.view = view

        if img_data == None:
            self.data = ImgData()
        else:
            self.data = img_data

        if calibration_data == None:
            self.calibration_data = CalibrationData(self.data)
        else:
            self.calibration_data = calibration_data

        self.data.subscribe(self.plot_image)
        self.view.set_start_values(self.calibration_data.start_values)
        self._first_plot = True
        self.create_signals()
        self.load_calibrants_list()
        self.raise_window()
예제 #2
0
 def setUp(self):
     self.img_data = ImgData()
     self.img_data.load('Data/LaB6_p49_40keV_006.tif')
     self.calibration_data = CalibrationData(self.img_data)
     self.calibration_data.calibrant.load_file('Data/Calibrants/LaB6.D')
     self.calibration_data.calibrant.set_wavelength(0.31 * 1e-10)
     self.calibration_data.load('Data/LaB6_p49_40keV_006.poni')
예제 #3
0
class CombinedDataTest(unittest.TestCase):
    def setUp(self):
        self.img_data = ImgData()
        self.img_data.load('Data/LaB6_p49_40keV_006.tif')
        self.calibration_data = CalibrationData(self.img_data)
        self.calibration_data.calibrant.load_file('Data/Calibrants/LaB6.D')
        self.calibration_data.calibrant.set_wavelength(0.31 * 1e-10)
        self.calibration_data.load('Data/LaB6_p49_40keV_006.poni')

    def test_recalibration(self):
        self.calibration_data.recalibrate()
        plt.imshow(self.img_data.img_data)
        plt.plot(self.calibration_data.geometry.data[:, 0],
                 self.calibration_data.geometry.data[:, 1], 'g.')
        plt.savefig('Results/recalib_massif.jpg')

        self.calibration_data.recalibrate('blob')
        plt.figure(2)
        plt.imshow(self.img_data.img_data)
        plt.plot(self.calibration_data.geometry.data[:, 0],
                 self.calibration_data.geometry.data[:, 1], 'g.')
        plt.savefig('Results/recalib_blob.jpg')

        self.calibration_data.recalibrate('blob')
        plt.figure(3)
        plt.imshow(self.img_data.img_data)
        plt.plot(self.calibration_data.geometry.data[:, 0],
                 self.calibration_data.geometry.data[:, 1], 'g.')
        plt.savefig('Results/recalib_blob2.jpg')
예제 #4
0
    def __init__(self):
        self.view = MainView()

        #create data
        self.img_data = ImgData()
        self.calibration_data = CalibrationData(self.img_data)
        self.mask_data = MaskData()
        self.spectrum_data = SpectrumData()
        self.phase_data = PhaseData()

        self.load_directories()
        #create controller
        self.calibration_controller = CalibrationController(
            self.working_dir, self.view.calibration_widget, self.img_data,
            self.calibration_data)
        self.mask_controller = MaskController(self.working_dir,
                                              self.view.mask_widget,
                                              self.img_data, self.mask_data)
        self.integration_controller = IntegrationController(
            self.working_dir, self.view.integration_widget, self.img_data,
            self.mask_data, self.calibration_data, self.spectrum_data,
            self.phase_data)

        self.create_signals()
        self.raise_window()
예제 #5
0
class CombinedDataTest(unittest.TestCase):
    def setUp(self):
        self.img_data = ImgData()
        self.img_data.load('Data/LaB6_p49_40keV_006.tif')
        self.calibration_data = CalibrationData(self.img_data)
        self.calibration_data.calibrant.load_file('Data/Calibrants/LaB6.D')
        self.calibration_data.calibrant.set_wavelength(0.31 * 1e-10)
        self.calibration_data.load('Data/LaB6_p49_40keV_006.poni')

    def test_recalibration(self):
        self.calibration_data.recalibrate()
        plt.imshow(self.img_data.img_data)
        plt.plot(self.calibration_data.geometry.data[:, 0], self.calibration_data.geometry.data[:, 1], 'g.')
        plt.savefig('Results/recalib_massif.jpg')

        self.calibration_data.recalibrate('blob')
        plt.figure(2)
        plt.imshow(self.img_data.img_data)
        plt.plot(self.calibration_data.geometry.data[:, 0], self.calibration_data.geometry.data[:, 1], 'g.')
        plt.savefig('Results/recalib_blob.jpg')

        self.calibration_data.recalibrate('blob')
        plt.figure(3)
        plt.imshow(self.img_data.img_data)
        plt.plot(self.calibration_data.geometry.data[:, 0], self.calibration_data.geometry.data[:, 1], 'g.')
        plt.savefig('Results/recalib_blob2.jpg')
예제 #6
0
    def __init__(self, working_dir, view=None, imgData=None, maskData=None):
        self.working_dir = working_dir
        if view == None:
            self.view = MaskView()
        else:
            self.view = view

        if imgData == None:
            self.img_data = ImgData()
        else:
            self.img_data = imgData

        if maskData == None:
            self.mask_data = MaskData()
        else:
            self.mask_data = maskData

        self.view.img_view.mouse_left_clicked.connect(self.process_click)

        self.state = None
        self.clicks = 0
        self.create_signals()

        self.rect = None
        self.circle = None
        self.polygon = None
        self.point = None

        self.raise_window()
예제 #7
0
    def __init__(self, app):
        self.splash_img = QtGui.QPixmap("UiFiles/splash.png")
        self.splash_screen = QtGui.QSplashScreen(
            self.splash_img, QtCore.Qt.WindowStaysOnTopHint)
        self.splash_screen.show()
        app.processEvents()
        time.sleep(1)
        app.processEvents()

        self.view = MainView()
        #create data
        self.img_data = ImgData()
        self.calibration_data = CalibrationData(self.img_data)
        self.mask_data = MaskData()
        self.spectrum_data = SpectrumData()
        self.phase_data = PhaseData()

        self.load_directories()
        #create controller
        self.calibration_controller = CalibrationController(
            self.working_dir, self.view.calibration_widget, self.img_data,
            self.mask_data, self.calibration_data)
        self.mask_controller = MaskController(self.working_dir,
                                              self.view.mask_widget,
                                              self.img_data, self.mask_data)
        self.integration_controller = IntegrationController(
            self.working_dir, self.view.integration_widget, self.img_data,
            self.mask_data, self.calibration_data, self.spectrum_data,
            self.phase_data)
        self.create_signals()
        self.set_title()
        self.raise_window()
        self.splash_screen.finish(self.view)
예제 #8
0
 def setUp(self):
     self.img_data = ImgData()
     self.img_data.load('Data/Mg2SiO4_ambient_001.tif')
     self.calibration_data = CalibrationData(self.img_data)
     self.calibration_data.load('Data/calibration.poni')
     self.mask_data = MaskData()
     self.mask_data.load_mask('Data/test.mask')
     self.spectrum_data = SpectrumData()
예제 #9
0
    def __init__(self):
        self.view = MainView()
        #create data
        self.img_data = ImgData()
        self.calibration_data = CalibrationData(self.img_data)
        self.mask_data = MaskData()
        self.spectrum_data = SpectrumData()
        self.phase_data = PhaseData()

        self.settings_directory = os.path.join(os.path.expanduser("~"), '.Dioptas')
        self.working_directories = {'calibration': '', 'mask': '', 'image': '', 'spectrum': '', 'overlay': '',
                                'phase': ''}
        self.load_settings()
        #create controller
        self.calibration_controller = CalibrationController(self.working_directories,
                                                            self.view.calibration_widget,
                                                            self.img_data,
                                                            self.mask_data,
                                                            self.calibration_data)
        self.mask_controller = MaskController(self.working_directories,
                                              self.view.mask_widget,
                                              self.img_data,
                                              self.mask_data)
        self.integration_controller = IntegrationController(self.working_directories,
                                                            self.view.integration_widget,
                                                            self.img_data,
                                                            self.mask_data,
                                                            self.calibration_data,
                                                            self.spectrum_data,
                                                            self.phase_data)
        self.create_signals()
        self.set_title()
        self.raise_window(self.view)
예제 #10
0
 def setUp(self):
     self.img_data = ImgData()
     self.img_data.load('Data/LaB6_p49_40keV_006.tif')
     self.calibration_data = CalibrationData(self.img_data)
     self.calibration_data.calibrant.load_file('Data/Calibrants/LaB6.D')
     self.calibration_data.calibrant.set_wavelength(0.31 * 1e-10)
     self.calibration_data.load('Data/LaB6_p49_40keV_006.poni')
예제 #11
0
    def __init__(self):
        self.view = MainView()

        #create data
        self.img_data = ImgData()
        self.calibration_data = CalibrationData(self.img_data)
        self.mask_data = MaskData()
        self.spectrum_data = SpectrumData()
        self.phase_data = PhaseData()

        self.load_directories()
        #create controller
        self.calibration_controller = CalibrationController(self.working_dir,
                                                            self.view.calibration_widget,
                                                            self.img_data,
                                                            self.calibration_data)
        self.mask_controller = MaskController(self.working_dir,
                                              self.view.mask_widget,
                                              self.img_data,
                                              self.mask_data)
        self.integration_controller = IntegrationController(self.working_dir,
                                                            self.view.integration_widget,
                                                            self.img_data,
                                                            self.mask_data,
                                                            self.calibration_data,
                                                            self.spectrum_data,
                                                            self.phase_data)

        self.create_signals()
        self.raise_window()
예제 #12
0
    def __init__(self, working_dir, view=None, imgData=None, maskData=None):
        self.working_dir = working_dir
        if view == None:
            self.view = MaskView()
        else:
            self.view = view

        if imgData == None:
            self.img_data = ImgData()
        else:
            self.img_data = imgData

        if maskData == None:
            self.mask_data = MaskData()
        else:
            self.mask_data = maskData

        self.view.img_view.add_left_click_observer(self.process_click)

        self.state = None
        self.clicks = 0
        self.create_signals()

        self.rect = None
        self.circle = None
        self.polygon = None
        self.point = None

        self.raise_window()
예제 #13
0
    def setUp(self):
        self.app = QtGui.QApplication(sys.argv)
        self.image_data = ImgData()
        self.calibration_data = CalibrationData(self.image_data)
        self.calibration_data._calibrants_working_dir = 'Data/Calibrants'

        self.calibration_controller = CalibrationController(img_data=self.image_data, \
                                                            calibration_data=self.calibration_data)
예제 #14
0
 def setUp(self):
     self.img_data = ImgData()
     self.img_data.load('Data/Mg2SiO4_ambient_001.tif')
     self.calibration_data = CalibrationData(self.img_data)
     self.calibration_data.load('Data/calibration.poni')
     self.mask_data = MaskData()
     self.mask_data.mask_ellipse(500, 500, 100, 100)
     self.spectrum_data = SpectrumData()
예제 #15
0
class CombinedDataTest(unittest.TestCase):
    def setUp(self):
        self.img_data = ImgData()
        self.img_data.load('Data/Mg2SiO4_ambient_001.tif')
        self.calibration_data = CalibrationData(self.img_data)
        self.calibration_data.load('Data/calibration.poni')
        self.mask_data = MaskData()
        self.mask_data.mask_ellipse(500, 500, 100, 100)
        self.spectrum_data = SpectrumData()

    def test_dependencies(self):
        tth1, int1 = self.calibration_data.integrate_1d()
        self.img_data.load_next_file()

        self.assertEqual(os.path.abspath(self.img_data.filename),
                         os.path.abspath('Data/Mg2SiO4_ambient_002.tif'))
        tth2, int2 = self.calibration_data.integrate_1d()
        self.assertFalse(np.array_equal(int1, int2))

        plt.figure(1)
        plt.plot(tth1, int1)
        plt.plot(tth2, int2)
        plt.savefig('Results/dependencies1.png')

        tth3, int3 = self.calibration_data.integrate_1d(mask=self.mask_data.get_mask())
        self.assertFalse(np.array_equal(int2, int3))
        plt.figure(2)
        plt.plot(tth2, int2)
        plt.plot(tth3, int3)
        plt.savefig('Results/dependencies2.png')

        tth4, int4 = self.calibration_data.integrate_1d(polarization_factor=0.90, mask=None)
        plt.figure(3)
        plt.plot(tth2, int2)
        plt.plot(tth4, int4)
        plt.savefig('Results/dependencies3.png')

        tth5, int5 = self.calibration_data.integrate_1d(polarization_factor=.5, mask=None)
        plt.figure(4)
        plt.plot(tth4, int4)
        plt.plot(tth5, int5)
        plt.savefig('Results/dependencies4.png')

    def test_automatism(self):
        def integrate_and_set_spectrum():
            tth, I = self.calibration_data.integrate_1d()
            self.spectrum_data.set_spectrum(tth, I, self.img_data.filename)

        self.img_data.subscribe(integrate_and_set_spectrum)

        y1 = self.spectrum_data.spectrum.data[1]
        self.img_data.load_next_file()
        y2 = self.spectrum_data.spectrum.data[1]
        self.assertFalse(np.array_equal(y1, y2))
예제 #16
0
class CombinedDataTest(unittest.TestCase):
    def setUp(self):
        self.img_data = ImgData()
        self.img_data.load('Data/Mg2SiO4_ambient_001.tif')
        self.calibration_data = CalibrationData(self.img_data)
        self.calibration_data.load('Data/calibration.poni')
        self.mask_data = MaskData()
        self.mask_data.load_mask('Data/test.mask')
        self.spectrum_data = SpectrumData()

    def test_dependencies(self):
        tth1, int1 = self.calibration_data.integrate_1d()
        self.img_data.load_next()
        tth2, int2 = self.calibration_data.integrate_1d()
        self.assertFalse(np.array_equal(int1, int2))

        plt.figure(1)
        plt.plot(tth1, int1)
        plt.plot(tth2, int2)
        plt.savefig('Results/dependencies1.jpg')

        tth3, int3 = self.calibration_data.integrate_1d(mask=self.mask_data.get_mask())
        self.assertFalse(np.array_equal(int2, int3))
        plt.figure(2)
        plt.plot(tth2, int2)
        plt.plot(tth3, int3)
        plt.savefig('Results/dependencies2.jpg')

        tth4, int4 = self.calibration_data.integrate_1d(polarization_factor=0.90, mask=None)
        plt.figure(3)
        plt.plot(tth2, int2)
        plt.plot(tth4, int4)
        plt.savefig('Results/dependencies3.jpg')

        tth5, int5 = self.calibration_data.integrate_1d(polarization_factor=.5, mask=None)
        plt.figure(4)
        plt.plot(tth4, int4)
        plt.plot(tth5, int5)
        plt.savefig('Results/dependencies4.jpg')

    def test_automatism(self):
        def integrate_and_set_spectrum():
            tth, I = self.calibration_data.integrate_1d()
            self.spectrum_data.set_spectrum(tth, I, self.img_data.filename)

        self.img_data.subscribe(integrate_and_set_spectrum)

        y1 = self.spectrum_data.spectrum.data[1]
        self.img_data.load_next()
        y2 = self.spectrum_data.spectrum.data[1]
        self.assertFalse(np.array_equal(y1, y2))
예제 #17
0
    def setUp(self):
        self.app = QtGui.QApplication(sys.argv)
        self.image_data = ImgData()
        self.controller = MainController(self.app)
        self.controller.calibration_controller.load_calibration(
            'Data/LaB6_p49_40keV_006.poni')
        self.controller.view.tabWidget.setCurrentIndex(2)
        self.controller.calibration_controller.load_img(
            'Data/Mg2SiO4_ambient_001.tif')

        self.overlay_controller = self.controller.integration_controller.overlay_controller
        self.spectrum_data = self.controller.spectrum_data
        self.spectrum_view = self.controller.view.integration_widget
        self.overlay_tw = self.spectrum_view.overlay_tw
예제 #18
0
    def setUp(self):
        self.app = QtGui.QApplication(sys.argv)
        self.img_data = ImgData()
        self.mask_data = MaskData()
        self.calibration_data = CalibrationData(self.img_data)
        self.calibration_data._calibrants_working_dir = 'Data/Calibrants'
        self.calibration_view = CalibrationView()

        self.working_dir = {}

        self.calibration_controller = CalibrationController(working_dir=self.working_dir,
                                                            img_data=self.img_data,
                                                            mask_data=self.mask_data,
                                                            view=self.calibration_view,
                                                            calibration_data=self.calibration_data)
예제 #19
0
    def __init__(self,
                 working_dir,
                 view=None,
                 img_data=None,
                 mask_data=None,
                 calibration_data=None,
                 spectrum_data=None,
                 phase_data=None):
        self.working_dir = working_dir
        if view == None:
            self.view = IntegrationView()
        else:
            self.view = view

        if img_data == None:
            self.img_data = ImgData()
        else:
            self.img_data = img_data

        if mask_data == None:
            self.mask_data = MaskData()
        else:
            self.mask_data = mask_data

        if calibration_data == None:
            self.calibration_data = CalibrationData(self.img_data)
        else:
            self.calibration_data = calibration_data

        if spectrum_data == None:
            self.spectrum_data = SpectrumData()
        else:
            self.spectrum_data = spectrum_data

        if phase_data == None:
            self.phase_data = PhaseData()
        else:
            self.phase_data = phase_data

        self.create_sub_controller()

        self.view.setWindowState(self.view.windowState()
                                 & ~QtCore.Qt.WindowMinimized
                                 | QtCore.Qt.WindowActive)
        self.view.activateWindow()
        self.view.raise_()
예제 #20
0
    def __init__(self, app):
        self.splash_img = QtGui.QPixmap("UiFiles/splash.png")
        self.splash_screen = QtGui.QSplashScreen(self.splash_img, QtCore.Qt.WindowStaysOnTopHint)
        self.splash_screen.show()
        app.processEvents()
        time.sleep(1)
        app.processEvents()

        self.view = MainView()
        #create data
        self.img_data = ImgData()
        self.calibration_data = CalibrationData(self.img_data)
        self.mask_data = MaskData()
        self.spectrum_data = SpectrumData()
        self.phase_data = PhaseData()

        self.load_directories()
        #create controller
        self.calibration_controller = CalibrationController(self.working_dir,
                                                            self.view.calibration_widget,
                                                            self.img_data,
                                                            self.mask_data,
                                                            self.calibration_data)
        self.mask_controller = MaskController(self.working_dir,
                                              self.view.mask_widget,
                                              self.img_data,
                                              self.mask_data)
        self.integration_controller = IntegrationController(self.working_dir,
                                                            self.view.integration_widget,
                                                            self.img_data,
                                                            self.mask_data,
                                                            self.calibration_data,
                                                            self.spectrum_data,
                                                            self.phase_data)
        self.create_signals()
        self.set_title()
        self.raise_window()
        self.splash_screen.finish(self.view)
예제 #21
0
    def __init__(self, working_dir, view=None, img_data=None, calibration_data=None):
        self.working_dir = working_dir
        if view == None:
            self.view = CalibrationView()
        else:
            self.view = view

        if img_data == None:
            self.data = ImgData()
        else:
            self.data = img_data

        if calibration_data == None:
            self.calibration_data = CalibrationData(self.data)
        else:
            self.calibration_data = calibration_data

        self.data.subscribe(self.plot_image)
        self.view.set_start_values(self.calibration_data.start_values)
        self._first_plot = True
        self.create_signals()
        self.load_calibrants_list()
        self.raise_window()
예제 #22
0
class MainController(object):
    def __init__(self, app):
        self.splash_img = QtGui.QPixmap("UiFiles/splash.png")
        self.splash_screen = QtGui.QSplashScreen(self.splash_img, QtCore.Qt.WindowStaysOnTopHint)
        self.splash_screen.show()
        app.processEvents()
        time.sleep(1)
        app.processEvents()

        self.view = MainView()
        #create data
        self.img_data = ImgData()
        self.calibration_data = CalibrationData(self.img_data)
        self.mask_data = MaskData()
        self.spectrum_data = SpectrumData()
        self.phase_data = PhaseData()

        self.load_directories()
        #create controller
        self.calibration_controller = CalibrationController(self.working_dir,
                                                            self.view.calibration_widget,
                                                            self.img_data,
                                                            self.mask_data,
                                                            self.calibration_data)
        self.mask_controller = MaskController(self.working_dir,
                                              self.view.mask_widget,
                                              self.img_data,
                                              self.mask_data)
        self.integration_controller = IntegrationController(self.working_dir,
                                                            self.view.integration_widget,
                                                            self.img_data,
                                                            self.mask_data,
                                                            self.calibration_data,
                                                            self.spectrum_data,
                                                            self.phase_data)
        self.create_signals()
        self.set_title()
        self.raise_window()
        self.splash_screen.finish(self.view)

    def raise_window(self):
        self.view.show()
        self.view.setWindowState(self.view.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)
        self.view.activateWindow()
        self.view.raise_()

    def create_signals(self):
        self.view.tabWidget.currentChanged.connect(self.tab_changed)
        self.view.closeEvent = self.close_event
        self.img_data.subscribe(self.set_title)
        self.spectrum_data.subscribe(self.set_title)

    def tab_changed(self, ind):
        if ind == 2:
            self.integration_controller.image_controller.plot_mask()
            self.integration_controller.view.calibration_lbl.setText(self.calibration_data.calibration_name)
            auto_scale_previous = self.integration_controller.image_controller._auto_scale
            self.integration_controller.image_controller._auto_scale = False
            self.integration_controller.spectrum_controller.image_changed()
            self.integration_controller.image_controller._auto_scale = auto_scale_previous
        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()
            except TypeError:
                pass

    def set_title(self):
        img_filename = os.path.basename(self.img_data.filename)
        spec_filename = os.path.basename(self.spectrum_data.spectrum_filename)
        calibration_name = self.calibration_data.calibration_name
        str = 'Dioptas v' + __VERSION__
        if img_filename is '' and spec_filename is '':
            self.view.setWindowTitle(str)
            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 += ']'
        self.view.setWindowTitle(str)

    def load_directories(self):
        if os.path.exists('working_directories.csv'):
            reader = csv.reader(open('working_directories.csv', 'rb'))
            self.working_dir = dict(x for x in reader)
        else:
            self.working_dir = {'calibration': '', 'mask': '', 'image': '', 'spectrum': '', 'overlay': '',
                                'phase': ''}

    def save_directories(self):
        writer = csv.writer(open('working_directories.csv', 'wb'))
        for key, value in self.working_dir.items():
            writer.writerow([key, value])


    def close_event(self, _):
        self.save_directories()
예제 #23
0
__author__ = 'Clemens Prescher'

from pyFAI.blob_detection import BlobDetection
from Data.ImgData import ImgData
import numpy as np
import pylab

img_data = ImgData()
# img_data.load('/Users/Doomgoroth/Programming/Large Projects/Dioptas/Testing/pyFAITest/17_LaB6_dc300-00000.tif')
img_data.load('/Users/Doomgoroth/Programming/Large Projects/Dioptas/Testing/pyFAITest/LaB6_WOS_30keV_005.tif')
bd = BlobDetection(np.log1p(img_data.get_img_data()))

bd.process()

x = []
y = []
int = []
sigma = []

print bd.keypoints.__len__()
for j in range(bd.keypoints.__len__()):
    k = bd.keypoints[j]
    int.append(k[2])
    sigma.append(k[3])
    if sigma[-1] > 0.25:
        x.append(k[0])
        y.append(k[1])

pylab.hist(int)
pylab.figure(2)
pylab.hist(sigma)
예제 #24
0
class MaskController(object):
    def __init__(self, working_dir, view=None, imgData=None, maskData=None):
        self.working_dir = working_dir
        if view == None:
            self.view = MaskView()
        else:
            self.view = view

        if imgData == None:
            self.img_data = ImgData()
        else:
            self.img_data = imgData

        if maskData == None:
            self.mask_data = MaskData()
        else:
            self.mask_data = maskData

        self.view.img_view.mouse_left_clicked.connect(self.process_click)

        self.state = None
        self.clicks = 0
        self.create_signals()

        self.rect = None
        self.circle = None
        self.polygon = None
        self.point = None

        self.raise_window()

    def raise_window(self):
        self.view.show()
        self.view.setWindowState(self.view.windowState()
                                 & ~QtCore.Qt.WindowMinimized
                                 | QtCore.Qt.WindowActive)
        self.view.activateWindow()
        self.view.raise_()

    def connect_click_function(self, emitter, function):
        self.view.connect(emitter, QtCore.SIGNAL('clicked()'), function)

    def create_signals(self):
        self.connect_click_function(self.view.circle_btn,
                                    self.activate_circle_btn)
        self.connect_click_function(self.view.rectangle_btn,
                                    self.activate_rectangle_btn)
        self.connect_click_function(self.view.polygon_btn,
                                    self.activate_polygon_btn)
        self.connect_click_function(self.view.point_btn,
                                    self.activate_point_btn)
        self.connect_click_function(self.view.undo_btn, self.undo_btn_click)
        self.connect_click_function(self.view.redo_btn, self.redo_btn_click)
        self.connect_click_function(self.view.below_thresh_btn,
                                    self.below_thresh_btn_click)
        self.connect_click_function(self.view.above_thresh_btn,
                                    self.above_thresh_btn_click)
        self.connect_click_function(self.view.cosmic_btn,
                                    self.cosmic_btn_click)
        self.connect_click_function(self.view.invert_mask_btn,
                                    self.invert_mask_btn_click)
        self.connect_click_function(self.view.clear_mask_btn,
                                    self.clear_mask_btn_click)
        self.connect_click_function(self.view.save_mask_btn,
                                    self.save_mask_btn_click)
        self.connect_click_function(self.view.load_mask_btn,
                                    self.load_mask_btn_click)
        self.connect_click_function(self.view.add_mask_btn,
                                    self.add_mask_btn_click)
        self.connect_click_function(self.view.mask_rb, self.mask_rb_click)
        self.connect_click_function(self.view.unmask_rb, self.unmask_rb_click)
        self.connect_click_function(self.view.fill_rb, self.fill_rb_click)
        self.connect_click_function(self.view.transparent_rb,
                                    self.transparent_rb_click)
        self.view.connect(self.view.point_size_sb,
                          QtCore.SIGNAL('valueChanged(int)'),
                          self.set_point_size)

        self.view.img_view.mouse_moved.connect(self.show_img_mouse_position)

        self.view.keyPressEvent = self.key_press_event

    def uncheck_all_btn(self, except_btn=None):
        btns = [self.view.circle_btn, self.view.rectangle_btn, self.view.polygon_btn, \
                self.view.point_btn]
        for btn in btns:
            if btn is not except_btn:
                if btn.isChecked():
                    btn.toggle()
        # if not except_btn.isChecked() and except_btn is not None:
        #     except_btn.toggle()

        shapes = [self.rect, self.circle, self.polygon]
        for shape in shapes:
            if shape is not None:
                self.view.img_view.img_view_box.removeItem(shape)
                self.view.img_view.mouse_moved.disconnect(shape.set_size)

        try:
            self.view.img_view.mouse_moved.disconnect(self.point.set_position)
            self.view.img_view.img_view_box.removeItem(self.point)
            self.point = None
        except AttributeError:
            pass

    def activate_circle_btn(self):
        if self.view.circle_btn.isChecked():
            self.state = 'circle'
            self.clicks = 0
            self.uncheck_all_btn(except_btn=self.view.circle_btn)
        else:
            print 'hmm'
            self.state = None
            self.clicks = 0
            self.uncheck_all_btn()

    def activate_rectangle_btn(self):
        if self.view.rectangle_btn.isChecked():
            self.state = 'rectangle'
            self.clicks = 0
            self.uncheck_all_btn(except_btn=self.view.rectangle_btn)
        else:
            self.state = None
            self.uncheck_all_btn()

    def activate_polygon_btn(self):
        if self.view.polygon_btn.isChecked():
            self.state = 'polygon'
            self.clicks = 0
            self.uncheck_all_btn(except_btn=self.view.polygon_btn)
        else:
            self.state = None
            self.uncheck_all_btn()

    def activate_point_btn(self):
        if self.view.point_btn.isChecked():
            self.state = 'point'
            self.clicks = 0
            self.uncheck_all_btn(except_btn=self.view.point_btn)
            self.point = self.view.img_view.draw_point(
                self.view.point_size_sb.value())
            self.view.img_view.mouse_moved.connect(self.point.set_position)
        else:
            self.state = 'None'
            self.uncheck_all_btn()

    def undo_btn_click(self):
        self.mask_data.undo()
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def redo_btn_click(self):
        self.mask_data.redo()
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def plot_image(self):
        self.view.img_view.plot_image(self.img_data.get_img_data(), False)
        self.view.img_view.auto_range()

    def process_click(self, x, y):
        if self.state == 'circle':
            self.draw_circle(x, y)
        elif self.state == 'rectangle':
            self.draw_rectangle(x, y)
        elif self.state == 'point':
            self.draw_point(x, y)
        elif self.state == 'polygon':
            self.draw_polygon(x, y)

    def draw_circle(self, x, y):
        if self.clicks == 0:
            self.clicks += 1
            self.circle = self.view.img_view.draw_circle(x, y)
            self.view.img_view.mouse_moved.connect(self.circle.set_size)
        elif self.clicks == 1:
            self.clicks = 0
            self.mask_data.mask_QGraphicsEllipseItem(self.circle)
            self.view.img_view.img_view_box.removeItem(self.circle)
            self.view.img_view.plot_mask(self.mask_data.get_img())
            self.view.img_view.mouse_moved.disconnect(self.circle.set_size)
            self.circle = None

    def draw_rectangle(self, x, y):
        if self.clicks == 0:
            self.clicks += 1
            self.rect = self.view.img_view.draw_rectangle(x, y)
            self.view.img_view.mouse_moved.connect(self.rect.set_size)
        elif self.clicks == 1:
            self.clicks = 0
            self.mask_data.mask_QGraphicsRectItem(self.rect)
            self.view.img_view.img_view_box.removeItem(self.rect)
            self.view.img_view.plot_mask(self.mask_data.get_img())
            self.view.img_view.mouse_moved.disconnect(self.rect.set_size)
            self.rect = None

    def draw_point(self, x, y):
        radius = self.view.point_size_sb.value()
        self.mask_data.mask_ellipse(y, x, radius, radius)
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def set_point_size(self, radius):
        try:
            self.point.set_radius(radius)
        except AttributeError:
            pass

    def draw_polygon(self, x, y):
        if self.clicks == 0:
            self.clicks += 1
            self.polygon = self.view.img_view.draw_polygon(x, y)
            self.view.img_view.mouse_moved.connect(self.polygon.set_size)
            self.view.img_view.mouse_left_double_clicked.connect(
                self.finish_polygon)
        elif self.clicks == 1:
            self.polygon.set_size(x, y)
            self.polygon.add_point(x, y)

    def finish_polygon(self, x, y):
        self.view.img_view.mouse_moved.disconnect(self.polygon.set_size)
        self.view.img_view.mouse_left_double_clicked.disconnect(
            self.finish_polygon)
        self.polygon.add_point(y, x)
        self.clicks = 0
        self.mask_data.mask_QGraphicsPolygonItem(self.polygon)
        self.view.img_view.plot_mask(self.mask_data.get_img())
        self.view.img_view.img_view_box.removeItem(self.polygon)
        self.polygon = None

    def below_thresh_btn_click(self):
        thresh = np.float64(self.view.below_thresh_txt.text())
        self.mask_data.mask_below_threshold(self.img_data.get_img_data(),
                                            thresh)
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def above_thresh_btn_click(self):
        thresh = np.float64(self.view.above_thresh_txt.text())
        self.mask_data.mask_above_threshold(self.img_data.get_img_data(),
                                            thresh)
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def invert_mask_btn_click(self):
        self.mask_data.invert_mask()
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def clear_mask_btn_click(self):
        self.mask_data.clear_mask()
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def cosmic_btn_click(self):
        self.mask_data.remove_cosmic(self.img_data.get_img_data())
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def save_mask_btn_click(self, filename=None):
        if filename is None:
            filename = str(
                QtGui.QFileDialog.getSaveFileName(
                    self.view,
                    caption="Save mask data",
                    directory=self.working_dir['mask'],
                    filter='*.mask'))

        if filename is not '':
            self.working_dir['mask'] = os.path.dirname(filename)
            np.savetxt(filename, self.mask_data.get_mask(), fmt="%d")

    def load_mask_btn_click(self, filename=None):
        if filename is None:
            filename = str(
                QtGui.QFileDialog.getOpenFileName(
                    self.view,
                    caption="Load mask data",
                    directory=self.working_dir['mask'],
                    filter='*.mask'))

        if filename is not '':
            self.working_dir['mask'] = os.path.dirname(filename)
            mask_data = np.loadtxt(filename)
            if self.img_data.get_img_data().shape == mask_data.shape:
                self.mask_data.set_mask(np.loadtxt(filename))
                self.plot_mask()
            else:
                QtGui.QMessageBox.critical(
                    self.view, 'Error',
                    'Image data and mask data in selected file do not have '
                    'the same shape. Mask could not be loaded.')

    def add_mask_btn_click(self, filename=None):
        if filename is None:
            filename = str(
                QtGui.QFileDialog.getOpenFileName(
                    self.view,
                    caption="Add mask data",
                    directory=self.working_dir['mask'],
                    filter='*.mask'))

        if filename is not '':
            self.working_dir['mask'] = os.path.dirname(filename)
            mask_data = np.loadtxt(filename)
            if self.mask_data.get_mask().shape == mask_data.shape:
                self.mask_data.add_mask(np.loadtxt(filename))
                self.plot_mask()
            else:
                QtGui.QMessageBox.critical(
                    self.view, 'Error',
                    'Image data and mask data in selected file do not have '
                    'the same shape. Mask could not be added.')

    def plot_mask(self):
        self.view.img_view.plot_mask(self.mask_data.get_mask())

    def key_press_event(self, ev):
        if self.state == "point":
            if ev.text() == 'q':
                self.view.point_size_sb.setValue(
                    self.view.point_size_sb.value() + 1)
            if ev.text() == 'w':
                self.view.point_size_sb.setValue(
                    self.view.point_size_sb.value() - 1)

        if ev.modifiers() == QtCore.Qt.ControlModifier:
            if ev.key() == 90:  #for pressing z
                self.undo_btn_click()
            elif ev.key() == 89:  #for pressing y
                self.redo_btn_click()
            elif ev.key() == 83:  #for pressing s
                self.save_mask_btn_click()
            elif ev.key == 79:  #for pressing o
                self.load_mask_btn_click()
            elif ev.key == 65:
                self.add_mask_btn_click()

    def mask_rb_click(self):
        self.mask_data.set_mode(True)

    def unmask_rb_click(self):
        self.mask_data.set_mode(False)

    def fill_rb_click(self):
        self.view.img_view.set_color([255, 0, 0, 255])
        self.plot_mask()

    #
    def transparent_rb_click(self):
        self.view.img_view.set_color([255, 0, 0, 100])
        self.plot_mask()

    def show_img_mouse_position(self, x, y):
        try:
            if x > 0 and y > 0:
                str = "x: %8.1f   y: %8.1f   I: %6.f" % (
                    x, y, self.view.img_view.img_data.T[np.floor(x),
                                                        np.floor(y)])
            else:
                str = "x: %.1f y: %.1f" % (x, y)
        except (IndexError, AttributeError):
            str = "x: %.1f y: %.1f" % (x, y)
        self.view.pos_lbl.setText(str)
예제 #25
0
class MainController(object):
    def __init__(self):
        self.view = MainView()

        #create data
        self.img_data = ImgData()
        self.calibration_data = CalibrationData(self.img_data)
        self.mask_data = MaskData()
        self.spectrum_data = SpectrumData()
        self.phase_data = PhaseData()

        self.load_directories()
        #create controller
        self.calibration_controller = CalibrationController(self.working_dir,
                                                            self.view.calibration_widget,
                                                            self.img_data,
                                                            self.calibration_data)
        self.mask_controller = MaskController(self.working_dir,
                                              self.view.mask_widget,
                                              self.img_data,
                                              self.mask_data)
        self.integration_controller = IntegrationController(self.working_dir,
                                                            self.view.integration_widget,
                                                            self.img_data,
                                                            self.mask_data,
                                                            self.calibration_data,
                                                            self.spectrum_data,
                                                            self.phase_data)

        self.create_signals()
        self.raise_window()

    def raise_window(self):
        self.view.show()
        self.view.setWindowState(self.view.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)
        self.view.activateWindow()
        self.view.raise_()

    def create_signals(self):
        self.view.tabWidget.currentChanged.connect(self.tab_changed)
        self.view.closeEvent = self.close_event

    def tab_changed(self, ind):
        if ind == 2:
            self.integration_controller.image_controller.plot_mask()
            self.integration_controller.view.calibration_lbl.setText(self.calibration_data.calibration_name)
            self.img_data.notify()
        elif ind == 1:
            self.mask_controller.plot_mask()
            self.mask_controller.plot_image()
        elif ind == 0:
            try:
                self.calibration_controller.update_calibration_parameter()
            except TypeError:
                pass

    def load_directories(self):
        if os.path.exists('working_directories.csv'):
            reader = csv.reader(open('working_directories.csv', 'rb'))
            self.working_dir = dict(x for x in reader)
        else:
            self.working_dir = {'calibration': '', 'mask': '', 'image': '', 'spectrum': '', 'overlay': '',
                                'phase': ''}

    def save_directories(self):
        writer = csv.writer(open('working_directories.csv', 'wb'))
        for key, value in self.working_dir.items():
            writer.writerow([key, value])

    def close_event(self, _):
        self.save_directories()
예제 #26
0
class MaskController(object):
    def __init__(self, working_dir, view=None, imgData=None, maskData=None):
        self.working_dir = working_dir
        if view == None:
            self.view = MaskView()
        else:
            self.view = view

        if imgData == None:
            self.img_data = ImgData()
        else:
            self.img_data = imgData

        if maskData == None:
            self.mask_data = MaskData()
        else:
            self.mask_data = maskData

        self.view.img_view.add_left_click_observer(self.process_click)

        self.state = None
        self.clicks = 0
        self.create_signals()

        self.rect = None
        self.circle = None
        self.polygon = None
        self.point = None

        self.raise_window()

    def raise_window(self):
        self.view.show()
        self.view.setWindowState(self.view.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)
        self.view.activateWindow()
        self.view.raise_()

    def connect_click_function(self, emitter, function):
        self.view.connect(emitter, QtCore.SIGNAL('clicked()'), function)

    def create_signals(self):
        self.connect_click_function(self.view.circle_btn, self.activate_circle_btn)
        self.connect_click_function(self.view.rectangle_btn, self.activate_rectangle_btn)
        self.connect_click_function(self.view.polygon_btn, self.activate_polygon_btn)
        self.connect_click_function(self.view.point_btn, self.activate_point_btn)
        self.connect_click_function(self.view.undo_btn, self.undo_btn_click)
        self.connect_click_function(self.view.redo_btn, self.redo_btn_click)
        self.connect_click_function(self.view.below_thresh_btn, self.below_thresh_btn_click)
        self.connect_click_function(self.view.above_thresh_btn, self.above_thresh_btn_click)
        self.connect_click_function(self.view.cosmic_btn, self.cosmic_btn_click)
        self.connect_click_function(self.view.invert_mask_btn, self.invert_mask_btn_click)
        self.connect_click_function(self.view.clear_mask_btn, self.clear_mask_btn_click)
        self.connect_click_function(self.view.save_mask_btn, self.save_mask_btn_click)
        self.connect_click_function(self.view.load_mask_btn, self.load_mask_btn_click)
        self.connect_click_function(self.view.add_mask_btn, self.add_mask_btn_click)
        self.connect_click_function(self.view.mask_rb, self.mask_rb_click)
        self.connect_click_function(self.view.unmask_rb, self.unmask_rb_click)
        self.connect_click_function(self.view.fill_rb, self.fill_rb_click)
        self.connect_click_function(self.view.transparent_rb, self.transparent_rb_click)
        self.view.connect(self.view.point_size_sb, QtCore.SIGNAL('valueChanged(int)'), self.set_point_size)

        self.view.keyPressEvent = self.key_press_event


    def uncheck_all_btn(self, except_btn=None):
        btns = [self.view.circle_btn, self.view.rectangle_btn, self.view.polygon_btn, \
                self.view.point_btn]
        for btn in btns:
            if btn is not except_btn:
                if btn.isChecked():
                    btn.toggle()
        # if not except_btn.isChecked() and except_btn is not None:
        #     except_btn.toggle()

        shapes = [self.rect, self.circle, self.polygon]
        for shape in shapes:
            if shape is not None:
                self.view.img_view.img_view_box.removeItem(shape)
                self.view.img_view.del_mouse_move_observer(shape.set_size)

        try:
            self.view.img_view.del_mouse_move_observer(self.point.set_position)
            self.view.img_view.img_view_box.removeItem(self.point)
            self.point = None
        except AttributeError:
            pass


    def activate_circle_btn(self):
        if self.view.circle_btn.isChecked():
            self.state = 'circle'
            self.clicks = 0
            self.uncheck_all_btn(except_btn=self.view.circle_btn)
        else:
            print 'hmm'
            self.state = None
            self.clicks = 0
            self.uncheck_all_btn()

    def activate_rectangle_btn(self):
        if self.view.rectangle_btn.isChecked():
            self.state = 'rectangle'
            self.clicks = 0
            self.uncheck_all_btn(except_btn=self.view.rectangle_btn)
        else:
            self.state = None
            self.uncheck_all_btn()

    def activate_polygon_btn(self):
        if self.view.polygon_btn.isChecked():
            self.state = 'polygon'
            self.clicks = 0
            self.uncheck_all_btn(except_btn=self.view.polygon_btn)
        else:
            self.state = None
            self.uncheck_all_btn()

    def activate_point_btn(self):
        if self.view.point_btn.isChecked():
            self.state = 'point'
            self.clicks = 0
            self.uncheck_all_btn(except_btn=self.view.point_btn)
            self.point = self.view.img_view.draw_point(self.view.point_size_sb.value())
            self.view.img_view.add_mouse_move_observer(self.point.set_position)
        else:
            self.state = 'None'
            self.uncheck_all_btn()

    def undo_btn_click(self):
        self.mask_data.undo()
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def redo_btn_click(self):
        self.mask_data.redo()
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def plot_image(self):
        self.view.img_view.plot_image(self.img_data.get_img_data(), False)
        self.view.img_view.auto_range()

    def process_click(self, x, y):
        if self.state == 'circle':
            self.draw_circle(x, y)
        elif self.state == 'rectangle':
            self.draw_rectangle(x, y)
        elif self.state == 'point':
            self.draw_point(x, y)
        elif self.state == 'polygon':
            self.draw_polygon(x, y)

    def draw_circle(self, x, y):
        if self.clicks == 0:
            self.clicks += 1
            self.circle = self.view.img_view.draw_circle(x, y)
            self.view.img_view.add_mouse_move_observer(self.circle.set_size)
        elif self.clicks == 1:
            self.clicks = 0
            self.mask_data.mask_QGraphicsEllipseItem(self.circle)
            self.view.img_view.img_view_box.removeItem(self.circle)
            self.view.img_view.plot_mask(self.mask_data.get_img())
            self.view.img_view.del_mouse_move_observer(self.circle.set_size)
            self.circle = None

    def draw_rectangle(self, x, y):
        if self.clicks == 0:
            self.clicks += 1
            self.rect = self.view.img_view.draw_rectangle(x, y)
            self.view.img_view.add_mouse_move_observer(self.rect.set_size)
        elif self.clicks == 1:
            self.clicks = 0
            self.mask_data.mask_QGraphicsRectItem(self.rect)
            self.view.img_view.img_view_box.removeItem(self.rect)
            self.view.img_view.plot_mask(self.mask_data.get_img())
            self.view.img_view.del_mouse_move_observer(self.rect.set_size)
            self.rect = None

    def draw_point(self, x, y):
        radius = self.view.point_size_sb.value()
        self.mask_data.mask_ellipse(y, x, radius, radius)
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def set_point_size(self, radius):
        try:
            self.point.set_radius(radius)
        except AttributeError:
            pass

    def draw_polygon(self, x, y):
        if self.clicks == 0:
            self.clicks += 1
            self.polygon = self.view.img_view.draw_polygon(x, y)
            self.view.img_view.add_mouse_move_observer(self.polygon.set_size)
            self.view.img_view.add_left_double_click_observer(self.finish_polygon)
        elif self.clicks == 1:
            self.polygon.set_size(x, y)
            self.polygon.add_point(x, y)

    def finish_polygon(self, x, y):
        self.view.img_view.del_mouse_move_observer(self.polygon.set_size)
        self.view.img_view.del_left_double_click_observer(self.finish_polygon)
        self.polygon.add_point(y, x)
        self.clicks = 0
        self.mask_data.mask_QGraphicsPolygonItem(self.polygon)
        self.view.img_view.plot_mask(self.mask_data.get_img())
        self.view.img_view.img_view_box.removeItem(self.polygon)
        self.polygon = None


    def below_thresh_btn_click(self):
        thresh = np.float64(self.view.below_thresh_txt.text())
        self.mask_data.mask_below_threshold(self.img_data.get_img_data(), thresh)
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def above_thresh_btn_click(self):
        thresh = np.float64(self.view.above_thresh_txt.text())
        self.mask_data.mask_above_threshold(self.img_data.get_img_data(), thresh)
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def invert_mask_btn_click(self):
        self.mask_data.invert_mask()
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def clear_mask_btn_click(self):
        self.mask_data.clear_mask()
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def cosmic_btn_click(self):
        self.mask_data.remove_cosmic(self.img_data.get_img_data())
        self.view.img_view.plot_mask(self.mask_data.get_img())

    def save_mask_btn_click(self, filename=None):
        if filename is None:
            filename = str(QtGui.QFileDialog.getSaveFileName(self.view, caption="Save mask data",
                                                             directory=self.working_dir['mask'], filter='*.mask'))

        if filename is not '':
            self.working_dir['mask'] = os.path.dirname(filename)
            np.savetxt(filename, self.mask_data.get_mask(), fmt="%d")

    def load_mask_btn_click(self, filename=None):
        if filename is None:
            filename = str(QtGui.QFileDialog.getOpenFileName(self.view, caption="Load mask data",
                                                             directory=self.working_dir['mask'], filter='*.mask'))

        if filename is not '':
            self.working_dir['mask'] = os.path.dirname(filename)
            mask_data = np.loadtxt(filename)
            if self.img_data.get_img_data().shape == mask_data.shape:
                self.mask_data.set_mask(np.loadtxt(filename))
                self.plot_mask()
            else:
                QtGui.QMessageBox.critical(self.view, 'Error', 'Image data and mask data in selected file do not have '
                                                               'the same shape. Mask could not be loaded.')

    def add_mask_btn_click(self, filename=None):
        if filename is None:
            filename = str(QtGui.QFileDialog.getOpenFileName(self.view, caption="Add mask data",
                                                             directory=self.working_dir['mask'], filter='*.mask'))

        if filename is not '':
            self.working_dir['mask'] = os.path.dirname(filename)
            mask_data = np.loadtxt(filename)
            if self.mask_data.get_mask().shape == mask_data.shape:
                self.mask_data.add_mask(np.loadtxt(filename))
                self.plot_mask()
            else:
                QtGui.QMessageBox.critical(self.view, 'Error', 'Image data and mask data in selected file do not have '
                                                               'the same shape. Mask could not be added.')

    def plot_mask(self):
        self.view.img_view.plot_mask(self.mask_data.get_mask())

    def key_press_event(self, ev):
        if self.state == "point":
            if ev.text() == 'q':
                self.view.point_size_sb.setValue(self.view.point_size_sb.value() + 1)
            if ev.text() == 'w':
                self.view.point_size_sb.setValue(self.view.point_size_sb.value() - 1)

        if ev.modifiers() == QtCore.Qt.ControlModifier:
            if ev.key() == 90:  #for pressing z
                self.undo_btn_click()
            elif ev.key() == 89:  #for pressing y
                self.redo_btn_click()
            elif ev.key() == 83:  #for pressing s
                self.save_mask_btn_click()
            elif ev.key == 79:  #for pressing o
                self.load_mask_btn_click()
            elif ev.key == 65:
                self.add_mask_btn_click()


    def mask_rb_click(self):
        self.mask_data.set_mode(True)

    def unmask_rb_click(self):
        self.mask_data.set_mode(False)

    def fill_rb_click(self):
        self.view.img_view.set_color([255, 0, 0, 255])
        self.plot_mask()

    #
    def transparent_rb_click(self):
        self.view.img_view.set_color([255, 0, 0, 100])
        self.plot_mask()
예제 #27
0
 def setUp(self):
     self.img_data = ImgData()
     self.img_data.load('Data/Mg2SiO4_ambient_001.tif')
예제 #28
0
class CalibrationController(object):
    def __init__(self,
                 working_dir,
                 view=None,
                 img_data=None,
                 calibration_data=None):
        self.working_dir = working_dir
        if view == None:
            self.view = CalibrationView()
        else:
            self.view = view

        if img_data == None:
            self.data = ImgData()
        else:
            self.data = img_data

        if calibration_data == None:
            self.calibration_data = CalibrationData(self.data)
        else:
            self.calibration_data = calibration_data

        self.data.subscribe(self.plot_image)
        self.view.set_start_values(self.calibration_data.start_values)
        self._first_plot = True
        self.create_signals()
        self.load_calibrants_list()
        self.raise_window()

    def raise_window(self):
        self.view.show()
        self.view.setWindowState(self.view.windowState()
                                 & ~QtCore.Qt.WindowMinimized
                                 | QtCore.Qt.WindowActive)
        self.view.activateWindow()
        self.view.raise_()

    def create_signals(self):
        self.create_transformation_signals()
        self.create_txt_box_signals()

        self.view.calibrant_cb.currentIndexChanged.connect(self.load_calibrant)

        self.connect_click_function(self.view.load_file_btn, self.load_file)
        self.connect_click_function(self.view.save_calibration_btn,
                                    self.save_calibration)
        self.connect_click_function(self.view.load_calibration_btn,
                                    self.load_calibration)

        self.connect_click_function(self.view.integrate_btn, self.calibrate)
        self.connect_click_function(self.view.refine_btn, self.refine)

        self.view.img_view.add_left_click_observer(self.search_peaks)
        self.connect_click_function(self.view.clear_peaks_btn,
                                    self.clear_peaks_btn_click)

    def create_transformation_signals(self):
        self.connect_click_function(self.view.rotate_m90_btn,
                                    self.data.rotate_img_m90)
        self.connect_click_function(self.view.rotate_m90_btn,
                                    self.clear_peaks_btn_click)
        self.connect_click_function(self.view.rotate_p90_btn,
                                    self.data.rotate_img_p90)
        self.connect_click_function(self.view.rotate_p90_btn,
                                    self.clear_peaks_btn_click)
        self.connect_click_function(self.view.invert_horizontal_btn,
                                    self.data.flip_img_horizontally)
        self.connect_click_function(self.view.invert_horizontal_btn,
                                    self.clear_peaks_btn_click)
        self.connect_click_function(self.view.invert_vertical_btn,
                                    self.data.flip_img_vertically)
        self.connect_click_function(self.view.invert_vertical_btn,
                                    self.clear_peaks_btn_click)
        self.connect_click_function(self.view.reset_transformations_btn,
                                    self.data.reset_img_transformations)
        self.connect_click_function(self.view.reset_transformations_btn,
                                    self.clear_peaks_btn_click)
        self.view.connect(self.view.f2_wavelength_cb,
                          QtCore.SIGNAL('clicked()'),
                          self.wavelength_cb_changed)
        self.view.connect(self.view.pf_wavelength_cb,
                          QtCore.SIGNAL('clicked()'),
                          self.wavelength_cb_changed)

    def create_txt_box_signals(self):
        self.connect_click_function(self.view.f2_update_btn,
                                    self.update_f2_btn_click)
        self.connect_click_function(self.view.pf_update_btn,
                                    self.update_pyFAI_btn_click)

    def update_f2_btn_click(self):
        fit2d_parameter = self.view.get_fit2d_parameter()
        self.calibration_data.geometry.setFit2D(
            directDist=fit2d_parameter['directDist'],
            centerX=fit2d_parameter['centerX'],
            centerY=fit2d_parameter['centerY'],
            tilt=fit2d_parameter['tilt'],
            tiltPlanRotation=fit2d_parameter['tiltPlanRotation'],
            pixelX=fit2d_parameter['pixelX'],
            pixelY=fit2d_parameter['pixelY'])
        self.calibration_data.geometry.wavelength = fit2d_parameter[
            'wavelength']
        self.calibration_data.polarization_factor = fit2d_parameter[
            'polarization_factor']
        self.calibration_data.is_calibrated = True
        self.update_all()

    def update_pyFAI_btn_click(self):
        pyFAI_parameter = self.view.get_pyFAI_parameter()
        self.calibration_data.geometry.setPyFAI(
            dist=pyFAI_parameter['dist'],
            poni1=pyFAI_parameter['poni1'],
            poni2=pyFAI_parameter['poni2'],
            rot1=pyFAI_parameter['rot1'],
            rot2=pyFAI_parameter['rot2'],
            rot3=pyFAI_parameter['rot3'],
            pixel1=pyFAI_parameter['pixel1'],
            pixel2=pyFAI_parameter['pixel2'])
        self.calibration_data.geometry.wavelength = pyFAI_parameter[
            'wavelength']
        self.calibration_data.polarization_factor = pyFAI_parameter[
            'polarization_factor']
        self.calibration_data.is_calibrated = True
        self.update_all()

    def load_file(self, filename=None):
        if filename is None:
            filename = str(
                QtGui.QFileDialog.getOpenFileName(
                    self.view,
                    caption="Load Calibration Image",
                    directory=self.working_dir['image']))

        if filename is not '':
            self.working_dir['image'] = os.path.dirname(filename)
            self.data.load(filename)

    def load_calibrants_list(self):
        self._calibrants_file_list = []
        self._calibrants_file_names_list = []
        for file in os.listdir(self.calibration_data._calibrants_working_dir):
            if file.endswith('.D'):
                self._calibrants_file_list.append(file)
                self._calibrants_file_names_list.append(
                    file.split('.')[:-1][0])
        self.view.calibrant_cb.blockSignals(True)
        self.view.calibrant_cb.clear()
        self.view.calibrant_cb.addItems(self._calibrants_file_names_list)
        self.view.calibrant_cb.blockSignals(False)
        self.view.calibrant_cb.setCurrentIndex(7)  # to LaB6
        self.load_calibrant()

    def load_calibrant(self, wavelength_from='start_values'):
        current_index = self.view.calibrant_cb.currentIndex()
        filename = os.path.join(self.calibration_data._calibrants_working_dir,
                                self._calibrants_file_list[current_index])
        self.calibration_data.set_calibrant(filename)

        wavelength = 0
        if wavelength_from == 'start_values':
            start_values = self.view.get_start_values()
            wavelength = start_values['wavelength']
        elif wavelength_from == 'pyFAI':
            pyFAI_parameter, _ = self.calibration_data.get_calibration_parameter(
            )
            if pyFAI_parameter['wavelength'] is not 0:
                wavelength = pyFAI_parameter['wavelength']
            else:
                start_values = self.view.get_start_values()
                wavelength = start_values['wavelength']
        else:
            start_values = self.view.get_start_values()
            wavelength = start_values['wavelength']

        self.calibration_data.calibrant.setWavelength_change2th(wavelength)
        self.view.spectrum_view.plot_vertical_lines(
            np.array(self.calibration_data.calibrant.get_2th()) / np.pi * 180,
            name=self._calibrants_file_names_list[current_index])

    def set_calibrant(self, index):
        self.view.calibrant_cb.setCurrentIndex(index)
        self.load_calibrant()

    def plot_image(self):
        if self._first_plot:
            self.view.img_view.plot_image(self.data.get_img_data(), True)
            self.view.img_view.auto_range()
            self._first_plot = False
        else:
            self.view.img_view.plot_image(self.data.get_img_data(), False)
        self.view.set_img_filename(self.data.filename)

    def connect_click_function(self, emitter, function):
        self.view.connect(emitter, QtCore.SIGNAL('clicked()'), function)

    def search_peaks(self, x, y):
        peak_ind = self.view.peak_num_sb.value()
        if self.view.automatic_peak_search_rb.isChecked():
            points = self.calibration_data.find_peaks_automatic(
                x, y, peak_ind - 1)
        else:
            search_size = np.int(self.view.search_size_sb.value())
            points = self.calibration_data.find_peak(x, y, search_size,
                                                     peak_ind - 1)
        if len(points):
            self.plot_points(points)
            if self.view.automatic_peak_num_inc_cb.checkState():
                self.view.peak_num_sb.setValue(peak_ind + 1)

    def plot_points(self, points=None):
        if points == None:
            try:
                points = self.calibration_data.get_point_array()
            except IndexError:
                points = []
        if len(points):
            self.view.img_view.add_scatter_data(points[:, 0] + 0.5,
                                                points[:, 1] + 0.5)

    def clear_peaks_btn_click(self):
        self.calibration_data.clear_peaks()
        self.view.img_view.clear_scatter_plot()
        self.view.peak_num_sb.setValue(1)

    def wavelength_cb_changed(self):
        self.calibration_data.fit_wavelength = self.view.f2_wavelength_cb.isChecked(
        )

    def calibrate(self):
        self.load_calibrant()  #load the right calibration file...
        self.calibration_data.set_start_values(self.view.get_start_values())
        self.calibration_data.calibrate()
        self.update_calibration_parameter()

        if self.view.options_automatic_refinement_cb.isChecked():
            self.refine()
        self.update_all()

    def refine(self):
        self.clear_peaks_btn_click()
        self.load_calibrant(
            wavelength_from='pyFAI')  #load right calibration file

        # get options
        algorithm = str(
            self.view.options_peaksearch_algorithm_cb.currentText())
        delta_tth = np.float(self.view.options_delta_tth_txt.text())
        intensity_min_factor = np.float(
            self.view.options_intensity_mean_factor_sb.value())
        intensity_max = np.float(self.view.options_intensity_limit_txt.text())
        num_rings = self.view.options_num_rings_sb.value()

        self.calibration_data.search_peaks_on_ring(0, delta_tth, algorithm,
                                                   intensity_min_factor,
                                                   intensity_max)
        self.calibration_data.search_peaks_on_ring(1, delta_tth, algorithm,
                                                   intensity_min_factor,
                                                   intensity_max)
        try:
            self.calibration_data.refine()
        except IndexError:
            print 'Did not find any Points with the specified parameters for the first two rings!'
        self.plot_points()

        for i in xrange(num_rings - 2):
            points = self.calibration_data.search_peaks_on_ring(
                i + 2, delta_tth, algorithm, intensity_min_factor,
                intensity_max)
            self.plot_points(points)
            QtGui.QApplication.processEvents()
            QtGui.QApplication.processEvents()
            try:
                self.calibration_data.refine()
            except IndexError:
                print 'Did not find enough points with the specified parameters!'
        self.calibration_data.integrate()
        self.update_all()

    def load_calibration(self, filename=None):
        if filename is None:
            filename = str(
                QtGui.QFileDialog.getOpenFileName(
                    self.view,
                    caption="Load calibration...",
                    directory=self.working_dir['calibration'],
                    filter='*.poni'))
        if filename is not '':
            self.working_dir['calibration'] = os.path.dirname(filename)
            self.calibration_data.load(filename)
            self.update_all()

    def update_all(self):
        if not self._first_plot:
            self.calibration_data.integrate_1d()
            self.calibration_data.integrate_2d()
            self.view.cake_view.plot_image(self.calibration_data.cake_img,
                                           True)

            self.view.spectrum_view.plot_data(self.calibration_data.tth,
                                              self.calibration_data.int)
            self.view.spectrum_view.plot_vertical_lines(
                np.array(self.calibration_data.calibrant.get_2th()) / np.pi *
                180)
            self.view.spectrum_view.view_box.autoRange()
            if self.view.tab_widget.currentIndex() == 0:
                self.view.tab_widget.setCurrentIndex(1)

        if self.view.ToolBox.currentIndex() is not 2 or \
                        self.view.ToolBox.currentIndex() is not 3:
            self.view.ToolBox.setCurrentIndex(2)
        self.update_calibration_parameter()

    def update_calibration_parameter(self):
        pyFAI_parameter, fit2d_parameter = self.calibration_data.get_calibration_parameter(
        )
        self.view.set_calibration_parameters(pyFAI_parameter, fit2d_parameter)

    def save_calibration(self, filename=None):
        if filename is None:
            filename = str(
                QtGui.QFileDialog.getSaveFileName(
                    self.view, "Save calibration...",
                    self.working_dir['calibration'], '*.poni'))
        if filename is not '':
            self.working_dir['calibration'] = os.path.dirname(filename)
            self.calibration_data.geometry.save(filename)
예제 #29
0
class MainController(object):
    def __init__(self, app):
        self.splash_img = QtGui.QPixmap("UiFiles/splash.png")
        self.splash_screen = QtGui.QSplashScreen(
            self.splash_img, QtCore.Qt.WindowStaysOnTopHint)
        self.splash_screen.show()
        app.processEvents()
        time.sleep(1)
        app.processEvents()

        self.view = MainView()
        #create data
        self.img_data = ImgData()
        self.calibration_data = CalibrationData(self.img_data)
        self.mask_data = MaskData()
        self.spectrum_data = SpectrumData()
        self.phase_data = PhaseData()

        self.load_directories()
        #create controller
        self.calibration_controller = CalibrationController(
            self.working_dir, self.view.calibration_widget, self.img_data,
            self.mask_data, self.calibration_data)
        self.mask_controller = MaskController(self.working_dir,
                                              self.view.mask_widget,
                                              self.img_data, self.mask_data)
        self.integration_controller = IntegrationController(
            self.working_dir, self.view.integration_widget, self.img_data,
            self.mask_data, self.calibration_data, self.spectrum_data,
            self.phase_data)
        self.create_signals()
        self.set_title()
        self.raise_window()
        self.splash_screen.finish(self.view)

    def raise_window(self):
        self.view.show()
        self.view.setWindowState(self.view.windowState()
                                 & ~QtCore.Qt.WindowMinimized
                                 | QtCore.Qt.WindowActive)
        self.view.activateWindow()
        self.view.raise_()

    def create_signals(self):
        self.view.tabWidget.currentChanged.connect(self.tab_changed)
        self.view.closeEvent = self.close_event
        self.img_data.subscribe(self.set_title)
        self.spectrum_data.subscribe(self.set_title)

    def tab_changed(self, ind):
        if ind == 2:
            self.integration_controller.image_controller.plot_mask()
            self.integration_controller.view.calibration_lbl.setText(
                self.calibration_data.calibration_name)
            auto_scale_previous = self.integration_controller.image_controller._auto_scale
            self.integration_controller.image_controller._auto_scale = False
            self.integration_controller.spectrum_controller.image_changed()
            self.integration_controller.image_controller._auto_scale = auto_scale_previous
        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()
            except TypeError:
                pass

    def set_title(self):
        img_filename = os.path.basename(self.img_data.filename)
        spec_filename = os.path.basename(self.spectrum_data.spectrum_filename)
        calibration_name = self.calibration_data.calibration_name
        str = 'Dioptas v' + __VERSION__
        if img_filename is '' and spec_filename is '':
            self.view.setWindowTitle(str)
            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 += ']'
        self.view.setWindowTitle(str)

    def load_directories(self):
        if os.path.exists('working_directories.csv'):
            reader = csv.reader(open('working_directories.csv', 'rb'))
            self.working_dir = dict(x for x in reader)
        else:
            self.working_dir = {
                'calibration': '',
                'mask': '',
                'image': '',
                'spectrum': '',
                'overlay': '',
                'phase': ''
            }

    def save_directories(self):
        writer = csv.writer(open('working_directories.csv', 'wb'))
        for key, value in self.working_dir.items():
            writer.writerow([key, value])

    def close_event(self, _):
        self.save_directories()
예제 #30
0
class CalibrationControllerTest(unittest.TestCase):
    def setUp(self):
        self.app = QtGui.QApplication(sys.argv)
        self.img_data = ImgData()
        self.mask_data = MaskData()
        self.calibration_data = CalibrationData(self.img_data)
        self.calibration_data._calibrants_working_dir = 'Data/Calibrants'
        self.calibration_view = CalibrationView()

        self.working_dir = {}

        self.calibration_controller = CalibrationController(working_dir=self.working_dir,
                                                            img_data=self.img_data,
                                                            mask_data=self.mask_data,
                                                            view=self.calibration_view,
                                                            calibration_data=self.calibration_data)

    def tearDown(self):
        del self.app

    def test_automatic_calibration1(self):
        self.calibration_controller.load_img('Data/LaB6_p49_40keV_006.tif')
        self.calibration_controller.search_peaks(1179.6, 1129.4)
        self.calibration_controller.search_peaks(1268.5, 1119.8)
        self.calibration_controller.view.sv_wavelength_txt.setText('0.31')
        self.calibration_controller.view.sv_distance_txt.setText('200')
        self.calibration_controller.view.sv_pixel_width_txt.setText('79')
        self.calibration_controller.view.sv_pixel_height_txt.setText('79')
        self.calibration_controller.view.calibrant_cb.setCurrentIndex(7)
        self.calibration_controller.calibrate()
        self.calibration_controller.view.cake_view.set_vertical_line_pos(1419.8, 653.4)

    def test_automatic_calibration2(self):
        self.calibration_controller.load_img('Data/LaB6_WOS_30keV_005.tif')
        self.calibration_controller.search_peaks(1245.2, 1919.3)
        self.calibration_controller.search_peaks(1334.0, 1823.7)
        self.calibration_controller.view.sv_wavelength_txt.setText('0.3344')
        self.calibration_controller.view.sv_distance_txt.setText('500')
        self.calibration_controller.view.sv_pixel_width_txt.setText('200')
        self.calibration_controller.view.sv_pixel_height_txt.setText('200')
        self.calibration_controller.view.calibrant_cb.setCurrentIndex(7)
        self.calibration_controller.calibrate()
        self.calibration_controller.view.cake_view.set_vertical_line_pos(206.5, 171.6)

    def test_automatic_calibration3(self):
        self.calibration_controller.load_img('Data/CeO2_Oct24_2014_001_0000.tif')
        QTest.mouseClick(self.calibration_view.automatic_peak_num_inc_cb, QtCore.Qt.LeftButton)

        self.assertFalse(self.calibration_view.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_controller.view.sv_wavelength_txt.setText('0.406626')
        self.calibration_controller.view.sv_distance_txt.setText('200')
        self.calibration_controller.view.sv_pixel_width_txt.setText('172')
        self.calibration_controller.view.sv_pixel_height_txt.setText('172')
        self.calibration_controller.view.calibrant_cb.setCurrentIndex(4)

        start_values = self.calibration_view.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_data.calibrant.wavelength, 0.406626e-10)

        QTest.mouseClick(self.calibration_view.integrate_btn, QtCore.Qt.LeftButton)
        calibration_parameter = self.calibration_data.get_calibration_parameter()[0]

        self.assertAlmostEqual(calibration_parameter['dist'], .2086, places=4)

    def test_automatic_calibration_with_supersampling(self):
        self.calibration_controller.load_img('Data/LaB6_p49_40keV_006.tif')
        self.calibration_controller.search_peaks(1179.6, 1129.4)
        self.calibration_controller.search_peaks(1268.5, 1119.8)
        self.calibration_controller.view.sv_wavelength_txt.setText('0.31')
        self.calibration_controller.view.sv_distance_txt.setText('200')
        self.calibration_controller.view.sv_pixel_width_txt.setText('79')
        self.calibration_controller.view.sv_pixel_height_txt.setText('79')
        self.calibration_controller.view.calibrant_cb.setCurrentIndex(7)
        self.img_data.set_supersampling(2)
        self.calibration_data.set_supersampling(2)
        self.calibration_controller.calibrate()

    def test_automatic_calibration_with_supersampling_and_mask(self):
        self.calibration_controller.load_img('Data/LaB6_p49_40keV_006.tif')
        self.calibration_controller.search_peaks(1179.6, 1129.4)
        self.calibration_controller.search_peaks(1268.5, 1119.8)
        self.calibration_controller.view.sv_wavelength_txt.setText('0.31')
        self.calibration_controller.view.sv_distance_txt.setText('200')
        self.calibration_controller.view.sv_pixel_width_txt.setText('79')
        self.calibration_controller.view.sv_pixel_height_txt.setText('79')
        self.calibration_controller.view.calibrant_cb.setCurrentIndex(7)
        self.img_data.set_supersampling(2)
        self.mask_data.mask_below_threshold(self.img_data._img_data, 1)
        self.mask_data.set_supersampling(2)
        self.calibration_data.set_supersampling(2)
        self.calibration_controller.view.use_mask_cb.setChecked(True)
        self.calibration_controller.calibrate()

    def test_calibrating_one_image_size_and_loading_different_image_size(self):
        self.calibration_controller.load_img('Data/LaB6_p49_40keV_006.tif')
        self.calibration_controller.search_peaks(1179.6, 1129.4)
        self.calibration_controller.search_peaks(1268.5, 1119.8)
        self.calibration_controller.view.sv_wavelength_txt.setText('0.31')
        self.calibration_controller.view.sv_distance_txt.setText('200')
        self.calibration_controller.view.sv_pixel_width_txt.setText('79')
        self.calibration_controller.view.sv_pixel_height_txt.setText('79')
        self.calibration_controller.view.calibrant_cb.setCurrentIndex(7)
        self.calibration_controller.view.options_automatic_refinement_cb.setChecked(False)
        self.calibration_controller.view.use_mask_cb.setChecked(True)
        self.calibration_controller.calibrate()
        self.calibration_data.integrate_1d()
        self.calibration_data.integrate_2d()
        self.calibration_controller.load_img('Data/CeO2_Pilatus1M.tif')
        self.calibration_data.integrate_1d()
        self.calibration_data.integrate_2d()

    def test_loading_and_saving_of_calibration_files(self):
        self.calibration_controller.load_calibration('Data/calibration.poni')
        self.calibration_controller.save_calibration('Data/calibration.poni')
예제 #31
0
class CalibrationController(object):
    def __init__(self, working_dir, view=None, img_data=None, calibration_data=None):
        self.working_dir = working_dir
        if view == None:
            self.view = CalibrationView()
        else:
            self.view = view

        if img_data == None:
            self.data = ImgData()
        else:
            self.data = img_data

        if calibration_data == None:
            self.calibration_data = CalibrationData(self.data)
        else:
            self.calibration_data = calibration_data

        self.data.subscribe(self.plot_image)
        self.view.set_start_values(self.calibration_data.start_values)
        self._first_plot = True
        self.create_signals()
        self.load_calibrants_list()
        self.raise_window()

    def raise_window(self):
        self.view.show()
        self.view.setWindowState(self.view.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)
        self.view.activateWindow()
        self.view.raise_()

    def create_signals(self):
        self.create_transformation_signals()
        self.create_txt_box_signals()

        self.view.calibrant_cb.currentIndexChanged.connect(self.load_calibrant)

        self.connect_click_function(self.view.load_file_btn, self.load_file)
        self.connect_click_function(self.view.save_calibration_btn, self.save_calibration)
        self.connect_click_function(self.view.load_calibration_btn, self.load_calibration)

        self.connect_click_function(self.view.integrate_btn, self.calibrate)
        self.connect_click_function(self.view.refine_btn, self.refine)

        self.view.img_view.add_left_click_observer(self.search_peaks)
        self.connect_click_function(self.view.clear_peaks_btn, self.clear_peaks_btn_click)


    def create_transformation_signals(self):
        self.connect_click_function(self.view.rotate_m90_btn, self.data.rotate_img_m90)
        self.connect_click_function(self.view.rotate_m90_btn, self.clear_peaks_btn_click)
        self.connect_click_function(self.view.rotate_p90_btn, self.data.rotate_img_p90)
        self.connect_click_function(self.view.rotate_p90_btn, self.clear_peaks_btn_click)
        self.connect_click_function(self.view.invert_horizontal_btn, self.data.flip_img_horizontally)
        self.connect_click_function(self.view.invert_horizontal_btn, self.clear_peaks_btn_click)
        self.connect_click_function(self.view.invert_vertical_btn, self.data.flip_img_vertically)
        self.connect_click_function(self.view.invert_vertical_btn, self.clear_peaks_btn_click)
        self.connect_click_function(self.view.reset_transformations_btn, self.data.reset_img_transformations)
        self.connect_click_function(self.view.reset_transformations_btn, self.clear_peaks_btn_click)
        self.view.connect(self.view.f2_wavelength_cb, QtCore.SIGNAL('clicked()'), self.wavelength_cb_changed)
        self.view.connect(self.view.pf_wavelength_cb, QtCore.SIGNAL('clicked()'), self.wavelength_cb_changed)


    def create_txt_box_signals(self):
        self.connect_click_function(self.view.f2_update_btn, self.update_f2_btn_click)
        self.connect_click_function(self.view.pf_update_btn, self.update_pyFAI_btn_click)

    def update_f2_btn_click(self):
        fit2d_parameter = self.view.get_fit2d_parameter()
        self.calibration_data.geometry.setFit2D(directDist=fit2d_parameter['directDist'],
                                                centerX=fit2d_parameter['centerX'],
                                                centerY=fit2d_parameter['centerY'],
                                                tilt=fit2d_parameter['tilt'],
                                                tiltPlanRotation=fit2d_parameter['tiltPlanRotation'],
                                                pixelX=fit2d_parameter['pixelX'],
                                                pixelY=fit2d_parameter['pixelY'])
        self.calibration_data.geometry.wavelength = fit2d_parameter['wavelength']
        self.calibration_data.polarization_factor = fit2d_parameter['polarization_factor']
        self.calibration_data.is_calibrated = True
        self.update_all()

    def update_pyFAI_btn_click(self):
        pyFAI_parameter = self.view.get_pyFAI_parameter()
        self.calibration_data.geometry.setPyFAI(dist=pyFAI_parameter['dist'],
                                                poni1=pyFAI_parameter['poni1'],
                                                poni2=pyFAI_parameter['poni2'],
                                                rot1=pyFAI_parameter['rot1'],
                                                rot2=pyFAI_parameter['rot2'],
                                                rot3=pyFAI_parameter['rot3'],
                                                pixel1=pyFAI_parameter['pixel1'],
                                                pixel2=pyFAI_parameter['pixel2'])
        self.calibration_data.geometry.wavelength = pyFAI_parameter['wavelength']
        self.calibration_data.polarization_factor = pyFAI_parameter['polarization_factor']
        self.calibration_data.is_calibrated = True
        self.update_all()


    def load_file(self, filename=None):
        if filename is None:
            filename = str(QtGui.QFileDialog.getOpenFileName(self.view, caption="Load Calibration Image",
                                                             directory=self.working_dir['image']))

        if filename is not '':
            self.working_dir['image'] = os.path.dirname(filename)
            self.data.load(filename)

    def load_calibrants_list(self):
        self._calibrants_file_list = []
        self._calibrants_file_names_list = []
        for file in os.listdir(self.calibration_data._calibrants_working_dir):
            if file.endswith('.D'):
                self._calibrants_file_list.append(file)
                self._calibrants_file_names_list.append(file.split('.')[:-1][0])
        self.view.calibrant_cb.blockSignals(True)
        self.view.calibrant_cb.clear()
        self.view.calibrant_cb.addItems(self._calibrants_file_names_list)
        self.view.calibrant_cb.blockSignals(False)
        self.view.calibrant_cb.setCurrentIndex(7)  # to LaB6
        self.load_calibrant()

    def load_calibrant(self, wavelength_from='start_values'):
        current_index = self.view.calibrant_cb.currentIndex()
        filename = os.path.join(self.calibration_data._calibrants_working_dir,
                                self._calibrants_file_list[current_index])
        self.calibration_data.set_calibrant(filename)

        wavelength = 0
        if wavelength_from == 'start_values':
            start_values = self.view.get_start_values()
            wavelength = start_values['wavelength']
        elif wavelength_from == 'pyFAI':
            pyFAI_parameter, _ = self.calibration_data.get_calibration_parameter()
            if pyFAI_parameter['wavelength'] is not 0:
                wavelength = pyFAI_parameter['wavelength']
            else:
                start_values = self.view.get_start_values()
                wavelength = start_values['wavelength']
        else:
            start_values = self.view.get_start_values()
            wavelength = start_values['wavelength']

        self.calibration_data.calibrant.setWavelength_change2th(wavelength)
        self.view.spectrum_view.plot_vertical_lines(np.array(self.calibration_data.calibrant.get_2th()) / np.pi * 180,
                                                    name=self._calibrants_file_names_list[current_index])

    def set_calibrant(self, index):
        self.view.calibrant_cb.setCurrentIndex(index)
        self.load_calibrant()


    def plot_image(self):
        if self._first_plot:
            self.view.img_view.plot_image(self.data.get_img_data(), True)
            self.view.img_view.auto_range()
            self._first_plot = False
        else:
            self.view.img_view.plot_image(self.data.get_img_data(), False)
        self.view.set_img_filename(self.data.filename)


    def connect_click_function(self, emitter, function):
        self.view.connect(emitter, QtCore.SIGNAL('clicked()'), function)

    def search_peaks(self, x, y):
        peak_ind = self.view.peak_num_sb.value()
        if self.view.automatic_peak_search_rb.isChecked():
            points = self.calibration_data.find_peaks_automatic(x, y, peak_ind - 1)
        else:
            search_size = np.int(self.view.search_size_sb.value())
            points = self.calibration_data.find_peak(x, y, search_size, peak_ind - 1)
        if len(points):
            self.plot_points(points)
            if self.view.automatic_peak_num_inc_cb.checkState():
                self.view.peak_num_sb.setValue(peak_ind + 1)

    def plot_points(self, points=None):
        if points == None:
            try:
                points = self.calibration_data.get_point_array()
            except IndexError:
                points = []
        if len(points):
            self.view.img_view.add_scatter_data(points[:, 0] + 0.5, points[:, 1] + 0.5)

    def clear_peaks_btn_click(self):
        self.calibration_data.clear_peaks()
        self.view.img_view.clear_scatter_plot()
        self.view.peak_num_sb.setValue(1)

    def wavelength_cb_changed(self):
        self.calibration_data.fit_wavelength = self.view.f2_wavelength_cb.isChecked()

    def calibrate(self):
        self.load_calibrant()  #load the right calibration file...
        self.calibration_data.set_start_values(self.view.get_start_values())
        self.calibration_data.calibrate()
        self.update_calibration_parameter()

        if self.view.options_automatic_refinement_cb.isChecked():
            self.refine()
        self.update_all()

    def refine(self):
        self.clear_peaks_btn_click()
        self.load_calibrant(wavelength_from='pyFAI')  #load right calibration file

        # get options
        algorithm = str(self.view.options_peaksearch_algorithm_cb.currentText())
        delta_tth = np.float(self.view.options_delta_tth_txt.text())
        intensity_min_factor = np.float(self.view.options_intensity_mean_factor_sb.value())
        intensity_max = np.float(self.view.options_intensity_limit_txt.text())
        num_rings = self.view.options_num_rings_sb.value()

        self.calibration_data.search_peaks_on_ring(0, delta_tth, algorithm, intensity_min_factor, intensity_max)
        self.calibration_data.search_peaks_on_ring(1, delta_tth, algorithm, intensity_min_factor, intensity_max)
        try:
            self.calibration_data.refine()
        except IndexError:
            print 'Did not find any Points with the specified parameters for the first two rings!'
        self.plot_points()

        for i in xrange(num_rings - 2):
            points = self.calibration_data.search_peaks_on_ring(i + 2, delta_tth, algorithm, intensity_min_factor,
                                                                intensity_max)
            self.plot_points(points)
            QtGui.QApplication.processEvents()
            QtGui.QApplication.processEvents()
            try:
                self.calibration_data.refine()
            except IndexError:
                print 'Did not find enough points with the specified parameters!'
        self.calibration_data.integrate()
        self.update_all()

    def load_calibration(self, filename=None):
        if filename is None:
            filename = str(QtGui.QFileDialog.getOpenFileName(self.view, caption="Load calibration...",
                                                             directory=self.working_dir['calibration'],
                                                             filter='*.poni'))
        if filename is not '':
            self.working_dir['calibration'] = os.path.dirname(filename)
            self.calibration_data.load(filename)
            self.update_all()


    def update_all(self):
        if not self._first_plot:
            self.calibration_data.integrate_1d()
            self.calibration_data.integrate_2d()
            self.view.cake_view.plot_image(self.calibration_data.cake_img, True)

            self.view.spectrum_view.plot_data(self.calibration_data.tth, self.calibration_data.int)
            self.view.spectrum_view.plot_vertical_lines(np.array(self.calibration_data.calibrant.get_2th()) /
                                                        np.pi * 180)
            self.view.spectrum_view.view_box.autoRange()
            if self.view.tab_widget.currentIndex() == 0:
                self.view.tab_widget.setCurrentIndex(1)

        if self.view.ToolBox.currentIndex() is not 2 or \
                        self.view.ToolBox.currentIndex() is not 3:
            self.view.ToolBox.setCurrentIndex(2)
        self.update_calibration_parameter()

    def update_calibration_parameter(self):
        pyFAI_parameter, fit2d_parameter = self.calibration_data.get_calibration_parameter()
        self.view.set_calibration_parameters(pyFAI_parameter, fit2d_parameter)

    def save_calibration(self, filename=None):
        if filename is None:
            filename = str(QtGui.QFileDialog.getSaveFileName(self.view, "Save calibration...",
                                                             self.working_dir['calibration'], '*.poni'))
        if filename is not '':
            self.working_dir['calibration'] = os.path.dirname(filename)
            self.calibration_data.geometry.save(filename)
예제 #32
0
__author__ = 'Clemens Prescher'

from pyFAI.blob_detection import BlobDetection
from Data.ImgData import ImgData
import numpy as np
import pylab

img_data = ImgData()
# img_data.load('/Users/Doomgoroth/Programming/Large Projects/Dioptas/Testing/pyFAITest/17_LaB6_dc300-00000.tif')
img_data.load(
    '/Users/Doomgoroth/Programming/Large Projects/Dioptas/Testing/pyFAITest/LaB6_WOS_30keV_005.tif'
)
bd = BlobDetection(np.log1p(img_data.get_img_data()))

bd.process()

x = []
y = []
int = []
sigma = []

print bd.keypoints.__len__()
for j in range(bd.keypoints.__len__()):
    k = bd.keypoints[j]
    int.append(k[2])
    sigma.append(k[3])
    if sigma[-1] > 0.25:
        x.append(k[0])
        y.append(k[1])

pylab.hist(int)
예제 #33
0
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):
        self.view = MainView()
        #create data
        self.img_data = ImgData()
        self.calibration_data = CalibrationData(self.img_data)
        self.mask_data = MaskData()
        self.spectrum_data = SpectrumData()
        self.phase_data = PhaseData()

        self.settings_directory = os.path.join(os.path.expanduser("~"), '.Dioptas')
        self.working_directories = {'calibration': '', 'mask': '', 'image': '', 'spectrum': '', 'overlay': '',
                                'phase': ''}
        self.load_settings()
        #create controller
        self.calibration_controller = CalibrationController(self.working_directories,
                                                            self.view.calibration_widget,
                                                            self.img_data,
                                                            self.mask_data,
                                                            self.calibration_data)
        self.mask_controller = MaskController(self.working_directories,
                                              self.view.mask_widget,
                                              self.img_data,
                                              self.mask_data)
        self.integration_controller = IntegrationController(self.working_directories,
                                                            self.view.integration_widget,
                                                            self.img_data,
                                                            self.mask_data,
                                                            self.calibration_data,
                                                            self.spectrum_data,
                                                            self.phase_data)
        self.create_signals()
        self.set_title()
        self.raise_window(self.view)

    @staticmethod
    def raise_window(widget):
        widget.show()
        widget.setWindowState(widget.windowState() & ~QtCore.Qt.WindowMinimized | QtCore.Qt.WindowActive)
        widget.activateWindow()
        widget.raise_()

    def create_signals(self):
        self.view.tabWidget.currentChanged.connect(self.tab_changed)
        self.view.closeEvent = self.close_event
        self.img_data.subscribe(self.set_title)
        self.spectrum_data.subscribe(self.set_title)

    def tab_changed(self, ind):
        if ind == 2:
            self.mask_data.set_supersampling()
            self.integration_controller.image_controller.plot_mask()
            self.integration_controller.view.calibration_lbl.setText(self.calibration_data.calibration_name)
            auto_scale_previous = self.integration_controller.image_controller._auto_scale
            self.integration_controller.image_controller._auto_scale = False
            self.integration_controller.spectrum_controller.image_changed()
            self.integration_controller.image_controller.update_img()
            self.integration_controller.image_controller._auto_scale = auto_scale_previous
        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_data.filename)
        spec_filename = os.path.basename(self.spectrum_data.spectrum_filename)
        calibration_name = self.calibration_data.calibration_name
        str = 'Dioptas ' + __VERSION__
        if img_filename is '' and spec_filename is '':
            self.view.setWindowTitle(str + u' - © 2014 C. Prescher')
            self.view.integration_widget.img_frame.setWindowTitle(str + u' - © 2014 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' - © 2014 C. Prescher'
        self.view.setWindowTitle(str)
        self.view.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_data.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_data.filename
        tree = ET.ElementTree(root)
        tree.write(os.path.join(self.settings_directory, "settings.xml"))

    def close_event(self, _):
        self.save_settings()
        QtGui.QApplication.closeAllWindows()
        QtGui.QApplication.quit()
예제 #34
0
class ImgDataUnitTest(unittest.TestCase):
    def setUp(self):
        self.img_data = ImgData()
        self.img_data.load('Data/Mg2SiO4_ambient_001.tif')

    def perform_transformations_tests(self):
        self.assertEqual(np.sum(np.absolute(self.img_data.get_img_data())), 0)
        self.img_data.rotate_img_m90()
        self.assertEqual(np.sum(np.absolute(self.img_data.get_img_data())), 0)
        self.img_data.flip_img_horizontally()
        self.assertEqual(np.sum(np.absolute(self.img_data.get_img_data())), 0)
        self.img_data.rotate_img_p90()
        self.assertEqual(np.sum(np.absolute(self.img_data.get_img_data())), 0)
        self.img_data.flip_img_vertically()
        self.assertEqual(np.sum(np.absolute(self.img_data.get_img_data())), 0)
        self.img_data.reset_img_transformations()
        self.assertEqual(np.sum(np.absolute(self.img_data.get_img_data())), 0)

    def test_flipping_images(self):
        original_image = np.copy(self.img_data._img_data)
        self.img_data.flip_img_vertically()
        self.assertTrue(np.array_equal(self.img_data._img_data, np.flipud(original_image)))

    def test_simple_background_subtraction(self):
        self.first_image = np.copy(self.img_data.get_img_data())
        self.img_data.load_next_file()
        self.second_image = np.copy(self.img_data.get_img_data())

        self.img_data.load('Data/Mg2SiO4_ambient_001.tif')
        self.img_data.load_background('Data/Mg2SiO4_ambient_002.tif')

        self.assertFalse(np.array_equal(self.first_image, self.img_data.get_img_data()))

        self.img_data.load_next_file()
        self.assertEqual(np.sum(self.img_data.get_img_data()), 0)

    def test_background_subtraction_with_supersampling(self):
        self.img_data.load_background('Data/Mg2SiO4_ambient_002.tif')

        self.img_data.set_supersampling(2)
        self.img_data.get_img_data()
        self.img_data.set_supersampling(3)
        self.img_data.get_img_data()

        self.img_data.load_next_file()
        self.img_data.get_img_data()

    def test_background_subtraction_with_transformation(self):

        self.img_data.load_background('Data/Mg2SiO4_ambient_002.tif')
        original_img = np.copy(self.img_data._img_data)
        original_background = np.copy(self.img_data._background_data)

        self.assertNotEqual(self.img_data._background_data, None)
        self.assertFalse(np.array_equal(self.img_data.img_data,  self.img_data._img_data))

        original_img_background_subtracted = np.copy(self.img_data.get_img_data())
        self.assertTrue(np.array_equal(original_img_background_subtracted, original_img-original_background))

        ### now comes the main process - flipping the image
        self.img_data.flip_img_vertically()
        flipped_img = np.copy(self.img_data._img_data)
        self.assertTrue(np.array_equal(np.flipud(original_img), flipped_img))

        flipped_background = np.copy(self.img_data._background_data)
        self.assertTrue(np.array_equal(np.flipud(original_background), flipped_background))

        flipped_img_background_subtracted = np.copy(self.img_data.get_img_data())
        self.assertTrue(np.array_equal(flipped_img_background_subtracted, flipped_img-flipped_background))

        self.assertTrue(np.array_equal(np.flipud(original_img_background_subtracted),
                                       flipped_img_background_subtracted))
        self.assertEqual(np.sum(np.flipud(original_img_background_subtracted)-flipped_img_background_subtracted), 0)

        self.img_data.load('Data/Mg2SiO4_ambient_002.tif')
        self.perform_transformations_tests()


    def test_background_subtraction_with_supersampling_and_image_transformation(self):
        self.img_data.load_background('Data/Mg2SiO4_ambient_002.tif')
        self.img_data.load('Data/Mg2SiO4_ambient_002.tif')

        self.img_data.set_supersampling(2)
        self.assertEqual(self.img_data.get_img_data().shape, (4096, 4096))

        self.perform_transformations_tests()

        self.img_data.set_supersampling(3)
        self.assertEqual(self.img_data.get_img_data().shape, (6144, 6144))

        self.perform_transformations_tests()

        self.img_data.load('Data/Mg2SiO4_ambient_002.tif')
        self.assertEqual(self.img_data.get_img_data().shape, (6144, 6144))

        self.perform_transformations_tests()

    def test_background_scaling_and_offset(self):
        self.img_data.load_background('Data/Mg2SiO4_ambient_002.tif')

        #assure that everything is correct before
        self.assertTrue(np.array_equal(self.img_data.get_img_data(),
                                       self.img_data._img_data-self.img_data._background_data))

        #set scaling and see difference
        self.img_data.set_background_scaling(2.4)
        self.assertTrue(np.array_equal(self.img_data.get_img_data(),
                                       self.img_data._img_data-2.4*self.img_data._background_data))

        #set offset and see the difference
        self.img_data.set_background_scaling(1.0)
        self.img_data.set_background_offset(100.0)
        self.assertTrue(np.array_equal(self.img_data.img_data,
                                       self.img_data._img_data-(self.img_data._background_data+100.0)))

        #use offset and scaling combined
        self.img_data.set_background_scaling(2.3)
        self.img_data.set_background_offset(100.0)
        self.assertTrue(np.array_equal(self.img_data.img_data,
                                       self.img_data._img_data-(2.3*self.img_data._background_data+100)))

    def test_background_with_different_shape(self):
        self.img_data.load_background('Data/CeO2_Pilatus1M.tif')
        self.assertEqual(self.img_data._background_data, None)

        self.img_data.load_background('Data/Mg2SiO4_ambient_002.tif')
        self.assertTrue(self.img_data._background_data is not None)

        self.img_data.load('Data/CeO2_Pilatus1M.tif')
        self.assertEqual(self.img_data._background_data, None)

    def test_absorption_correction_with_supersampling(self):
        original_image = np.copy(self.img_data.get_img_data())
        dummy_correction = DummyCorrection(self.img_data.get_img_data().shape, 0.6)

        self.img_data.add_img_correction(dummy_correction, "Dummy 1")
        self.assertAlmostEqual(np.sum(original_image)/0.6, np.sum(self.img_data.get_img_data()), places=4)

        self.img_data.set_supersampling(2)
        self.img_data.get_img_data()

    def test_absorption_correction_with_different_image_sizes(self):
        dummy_correction = DummyCorrection(self.img_data.get_img_data().shape, 0.4)
        # self.img_data.set_absorption_correction(np.ones(self.img_data._img_data.shape)*0.4)
        self.img_data.add_img_correction(dummy_correction, "Dummy 1")
        self.assertTrue(self.img_data._img_corrections.has_items())


        self.img_data.load('Data/CeO2_Pilatus1M.tif')
        self.assertFalse(self.img_data.has_corrections())

    def test_adding_several_absorption_corrections(self):
        original_image = np.copy(self.img_data.get_img_data())
        img_shape = original_image.shape
        self.img_data.add_img_correction(DummyCorrection(img_shape, 0.4))
        self.img_data.add_img_correction(DummyCorrection(img_shape, 3))
        self.img_data.add_img_correction(DummyCorrection(img_shape, 5))

        self.assertTrue(np.sum(original_image)/(0.5*3*5), np.sum(self.img_data.get_img_data()))

        self.img_data.delete_img_correction(1)
        self.assertTrue(np.sum(original_image)/(0.5*5), np.sum(self.img_data.get_img_data()))


    def test_saving_data(self):
        self.img_data.load('Data/Mg2SiO4_ambient_001.tif')
        self.img_data.save('Data/TestSaving.tif')
        first_img_array = np.copy(self.img_data._img_data)
        self.img_data.load('Data/TestSaving.tif')
        self.assertTrue(np.array_equal(first_img_array, self.img_data._img_data))
예제 #35
0
class MainController(object):
    def __init__(self):
        self.view = MainView()

        #create data
        self.img_data = ImgData()
        self.calibration_data = CalibrationData(self.img_data)
        self.mask_data = MaskData()
        self.spectrum_data = SpectrumData()
        self.phase_data = PhaseData()

        self.load_directories()
        #create controller
        self.calibration_controller = CalibrationController(
            self.working_dir, self.view.calibration_widget, self.img_data,
            self.calibration_data)
        self.mask_controller = MaskController(self.working_dir,
                                              self.view.mask_widget,
                                              self.img_data, self.mask_data)
        self.integration_controller = IntegrationController(
            self.working_dir, self.view.integration_widget, self.img_data,
            self.mask_data, self.calibration_data, self.spectrum_data,
            self.phase_data)

        self.create_signals()
        self.raise_window()

    def raise_window(self):
        self.view.show()
        self.view.setWindowState(self.view.windowState()
                                 & ~QtCore.Qt.WindowMinimized
                                 | QtCore.Qt.WindowActive)
        self.view.activateWindow()
        self.view.raise_()

    def create_signals(self):
        self.view.tabWidget.currentChanged.connect(self.tab_changed)
        self.view.closeEvent = self.close_event

    def tab_changed(self, ind):
        if ind == 2:
            self.integration_controller.image_controller.plot_mask()
            self.integration_controller.view.calibration_lbl.setText(
                self.calibration_data.calibration_name)
            self.img_data.notify()
        elif ind == 1:
            self.mask_controller.plot_mask()
            self.mask_controller.plot_image()
        elif ind == 0:
            try:
                self.calibration_controller.update_calibration_parameter()
            except TypeError:
                pass

    def load_directories(self):
        if os.path.exists('working_directories.csv'):
            reader = csv.reader(open('working_directories.csv', 'rb'))
            self.working_dir = dict(x for x in reader)
        else:
            self.working_dir = {
                'calibration': '',
                'mask': '',
                'image': '',
                'spectrum': '',
                'overlay': '',
                'phase': ''
            }

    def save_directories(self):
        writer = csv.writer(open('working_directories.csv', 'wb'))
        for key, value in self.working_dir.items():
            writer.writerow([key, value])

    def close_event(self, _):
        self.save_directories()