<reponame>PyMarc2/FLIM-SS2021<gh_stars>0
from PyQt5.QtWidgets import QWidget, QMessageBox, QCheckBox, QFileDialog
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QThread
from flim_analysis import QFLIMAnalyser
import re
import os
import csv
from PyQt5 import uic
import numpy as np
from gui.tools.roiMaker import MultiRoi
import logging


log = logging.getLogger(__name__)

filterViewUiPath = os.path.dirname(os.path.realpath(__file__)) + "{0}flimViewMWEUi.ui".format(os.sep)
Ui_filterView, QtBaseClass = uic.loadUiType(filterViewUiPath)


class FilterView(QWidget, Ui_filterView):
    s_data_changed = pyqtSignal(dict)
    s_data_acquisition_done = pyqtSignal()
    s_send_message = pyqtSignal(str)

    # Initializing Functions

    def __init__(self, model=None):
        super(FilterView, self).__init__()
        self.model = model
        self.setupUi(self)
        self.FA = QFLIMAnalyser()
        self.calculationThread = QThread()
        self.segmImages = None
        self.segmImage = None
        self.segmIndex = 0

        self.roiMaker = MultiRoi(fig=self.mpl_segmentation.canvas.fig, ax=self.mpl_segmentation.canvas.ax[0])
        self.showROI = False
        self.photonLimits = [0, 65535]
        self.layersLimits = [0, 255]
        self.boxLimits = [0, 255]

        self.connect_buttons()
        self.connect_signals()
        self.create_threads()
        self.update_segmentation_display()

    def connect_buttons(self):
        # LOAD MENU
        self.cmb_loadFiles.currentIndexChanged.connect(self.update_all)
        self.pb_loadFiles.clicked.connect(self.select_data_files)
        self.pb_loadIRF.clicked.connect(self.select_irf_file)
        self.pb_sumFiles.clicked.connect(self.make_select_sum_files)

        # ROI CONTROLS
        self.pb_addROI.clicked.connect(self.roiMaker.add)

        # SAVE DATA CONTROLS
        self.pb_roiAnalysis.clicked.connect(self.save_roi_decay_data)

        # SLIDERS
        self.hs_layerSelect.valueChanged.connect(self.save_layers_limits)
        self.hs_photonAmount.valueChanged.connect(self.save_photon_limits)
        self.hs_boxFilter.valueChanged.connect(self.save_box_limits)

        self.hs_layerSelect.valueMoving.connect(lambda: self.s_send_message.emit(f"Layer Selected :: min="
                                                                             f"{self.hs_layerSelect._left_thumb.value}"
                                                                             f",\t max={self.hs_layerSelect._right_thumb.value}"))
        self.hs_photonAmount.valueMoving.connect(lambda: self.s_send_message.emit(f"Photon Amount Filter :: min="
                                                                             f"{self.hs_photonAmount._left_thumb.value}"
                                                                             f",\t max={self.hs_photonAmount._right_thumb.value}"))
        self.hs_boxFilter.valueMoving.connect(lambda: self.s_send_message.emit(f"Box Filter :: min="
                                                                             f"{self.hs_boxFilter._left_thumb.value}"
                                                                             f",\t max={self.hs_boxFilter._right_thumb.value}"))

        self.hs_layerSelect.sliderReleased.connect(lambda: self.s_send_message.emit(f""))
        self.hs_photonAmount.sliderReleased.connect(lambda: self.s_send_message.emit(f""))
        self.hs_boxFilter.sliderReleased.connect(lambda: self.s_send_message.emit(f""))

    def connect_signals(self):
        self.FA.imageChanged.connect(self.set_segmentation_image)

    def create_threads(self, *args):
        pass

    # Data Capture Methods

    def set_rois(self):
        self.FA.make_rois(fig=self.mpl_segmentation.canvas.fig, ax=self.mpl_segmentation.canvas.ax[0], canvas=self.mpl_segmentation.canvas)
        if self.FA.rois:
            self.showROI = True
        else:
            self.showROI = False

    def make_sum_files(self):
        self.FA.sum_images()
        self.cmb_loadFiles.addItem("Sum Of Images")

    def make_select_sum_files(self):
        self.make_sum_files()
        self.pb_sumFiles.setEnabled(False)

    def save_photon_limits(self, limits):
        self.photonLimits = limits
        self.update_index_and_display()

    def save_layers_limits(self, limits):
        self.layersLimits = limits
        self.update_index_and_display()

    def save_box_limits(self, limits):
        self.boxLimits = limits
        self.update_index_and_display()

    def set_segmentation_image(self, image):
        self.segmImage = image

    def update_all(self):
        self.update_image_index()
        self.FA.sum_layers_image(self.layersLimits, self.photonLimits)
        self.update_sliders()
        self.update_segmentation_display()
        print(self.hs_photonAmount._right_value)

    def update_image_index(self):
        self.segmIndex = self.cmb_loadFiles.currentIndex()
        self.FA.set_image_index(self.segmIndex)
        print(self.segmIndex)

    def update_index_and_display(self):
        self.update_image_index()
        self.FA.sum_layers_image(self.layersLimits, self.photonLimits)
        self.update_segmentation_display()

    def update_segmentation_display(self, image=None):
        if self.segmImage is None:
            self.mpl_segmentation.canvas.ax[0].imshow([[0]])
        elif not self.showROI:
            self.mpl_segmentation.canvas.ax[0].imshow(self.segmImage)
        else:
            self.mpl_segmentation.canvas.ax[0].imshow(self.segmImage)
            self.FA.display_rois()

        self.mpl_segmentation.canvas.ax[0].set_axis_off()
        self.mpl_segmentation.canvas.fig.tight_layout()
        self.mpl_segmentation.canvas.fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
        self.mpl_segmentation.canvas.draw()

    def update_sliders(self):
        self.hs_photonAmount.setMaximum(np.max(self.segmImage))
        self.hs_imageSelect.setMaximum(0)

    def select_data_files(self):
        self.cmb_loadFiles.clear()
        self.FA.load_data()
        parsedFileNames = [(re.findall("[^\/]*$", t))[0] for t in self.FA.paths]
        self.cmb_loadFiles.addItems(parsedFileNames)

        self.update_segmentation_display()
        if len(parsedFileNames) > 1:
            self.pb_sumFiles.setEnabled(True)
        else:
            self.pb_sumFiles.setEnabled(False)

    def select_irf_file(self):
        self.FA.load_irf()
        self.le_loadIRF.setText(str(self.FA.irfPath))

    def save_capture_csv(self):
        pass

    def clear_all(self):
        pass

    # OUTPUT FUNCTIONS
    def save_roi_decay_data(self):
        self.FA.set_rois(self.roiMaker.rois)
        self.FA.mask_image()
        data = self.FA.get_roi_decay_data()
        saveFilePath = QFileDialog.getSaveFileName()
        self.write_to_file(data, saveFilePath[0])

    def write_to_file(self, data, filepath):
        columnData = zip(*data)
        with open(filepath, "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(columnData)

from PyQt5.QtWidgets import QWidget, QMessageBox, QCheckBox, QFileDialog
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QThread
from flim_analysis import QFLIMAnalyser
import re
import os
import csv
from PyQt5 import uic
import numpy as np
from gui.tools.roiMaker import MultiRoi
import logging


log = logging.getLogger(__name__)

filterViewUiPath = os.path.dirname(os.path.realpath(__file__)) + "{0}flimViewMWEUi.ui".format(os.sep)
Ui_filterView, QtBaseClass = uic.loadUiType(filterViewUiPath)


class FilterView(QWidget, Ui_filterView):
    s_data_changed = pyqtSignal(dict)
    s_data_acquisition_done = pyqtSignal()
    s_send_message = pyqtSignal(str)

    # Initializing Functions

    def __init__(self, model=None):
        super(FilterView, self).__init__()
        self.model = model
        self.setupUi(self)
        self.FA = QFLIMAnalyser()
        self.calculationThread = QThread()
        self.segmImages = None
        self.segmImage = None
        self.segmIndex = 0

        self.roiMaker = MultiRoi(fig=self.mpl_segmentation.canvas.fig, ax=self.mpl_segmentation.canvas.ax[0])
        self.showROI = False
        self.photonLimits = [0, 65535]
        self.layersLimits = [0, 255]
        self.boxLimits = [0, 255]

        self.connect_buttons()
        self.connect_signals()
        self.create_threads()
        self.update_segmentation_display()

    def connect_buttons(self):
        # LOAD MENU
        self.cmb_loadFiles.currentIndexChanged.connect(self.update_all)
        self.pb_loadFiles.clicked.connect(self.select_data_files)
        self.pb_loadIRF.clicked.connect(self.select_irf_file)
        self.pb_sumFiles.clicked.connect(self.make_select_sum_files)

        # ROI CONTROLS
        self.pb_addROI.clicked.connect(self.roiMaker.add)

        # SAVE DATA CONTROLS
        self.pb_roiAnalysis.clicked.connect(self.save_roi_decay_data)

        # SLIDERS
        self.hs_layerSelect.valueChanged.connect(self.save_layers_limits)
        self.hs_photonAmount.valueChanged.connect(self.save_photon_limits)
        self.hs_boxFilter.valueChanged.connect(self.save_box_limits)

        self.hs_layerSelect.valueMoving.connect(lambda: self.s_send_message.emit(f"Layer Selected :: min="
                                                                             f"{self.hs_layerSelect._left_thumb.value}"
                                                                             f",\t max={self.hs_layerSelect._right_thumb.value}"))
        self.hs_photonAmount.valueMoving.connect(lambda: self.s_send_message.emit(f"Photon Amount Filter :: min="
                                                                             f"{self.hs_photonAmount._left_thumb.value}"
                                                                             f",\t max={self.hs_photonAmount._right_thumb.value}"))
        self.hs_boxFilter.valueMoving.connect(lambda: self.s_send_message.emit(f"Box Filter :: min="
                                                                             f"{self.hs_boxFilter._left_thumb.value}"
                                                                             f",\t max={self.hs_boxFilter._right_thumb.value}"))

        self.hs_layerSelect.sliderReleased.connect(lambda: self.s_send_message.emit(f""))
        self.hs_photonAmount.sliderReleased.connect(lambda: self.s_send_message.emit(f""))
        self.hs_boxFilter.sliderReleased.connect(lambda: self.s_send_message.emit(f""))

    def connect_signals(self):
        self.FA.imageChanged.connect(self.set_segmentation_image)

    def create_threads(self, *args):
        pass

    # Data Capture Methods

    def set_rois(self):
        self.FA.make_rois(fig=self.mpl_segmentation.canvas.fig, ax=self.mpl_segmentation.canvas.ax[0], canvas=self.mpl_segmentation.canvas)
        if self.FA.rois:
            self.showROI = True
        else:
            self.showROI = False

    def make_sum_files(self):
        self.FA.sum_images()
        self.cmb_loadFiles.addItem("Sum Of Images")

    def make_select_sum_files(self):
        self.make_sum_files()
        self.pb_sumFiles.setEnabled(False)

    def save_photon_limits(self, limits):
        self.photonLimits = limits
        self.update_index_and_display()

    def save_layers_limits(self, limits):
        self.layersLimits = limits
        self.update_index_and_display()

    def save_box_limits(self, limits):
        self.boxLimits = limits
        self.update_index_and_display()

    def set_segmentation_image(self, image):
        self.segmImage = image

    def update_all(self):
        self.update_image_index()
        self.FA.sum_layers_image(self.layersLimits, self.photonLimits)
        self.update_sliders()
        self.update_segmentation_display()
        print(self.hs_photonAmount._right_value)

    def update_image_index(self):
        self.segmIndex = self.cmb_loadFiles.currentIndex()
        self.FA.set_image_index(self.segmIndex)
        print(self.segmIndex)

    def update_index_and_display(self):
        self.update_image_index()
        self.FA.sum_layers_image(self.layersLimits, self.photonLimits)
        self.update_segmentation_display()

    def update_segmentation_display(self, image=None):
        if self.segmImage is None:
            self.mpl_segmentation.canvas.ax[0].imshow([[0]])
        elif not self.showROI:
            self.mpl_segmentation.canvas.ax[0].imshow(self.segmImage)
        else:
            self.mpl_segmentation.canvas.ax[0].imshow(self.segmImage)
            self.FA.display_rois()

        self.mpl_segmentation.canvas.ax[0].set_axis_off()
        self.mpl_segmentation.canvas.fig.tight_layout()
        self.mpl_segmentation.canvas.fig.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=0, hspace=0)
        self.mpl_segmentation.canvas.draw()

    def update_sliders(self):
        self.hs_photonAmount.setMaximum(np.max(self.segmImage))
        self.hs_imageSelect.setMaximum(0)

    def select_data_files(self):
        self.cmb_loadFiles.clear()
        self.FA.load_data()
        parsedFileNames = [(re.findall("[^\/]*$", t))[0] for t in self.FA.paths]
        self.cmb_loadFiles.addItems(parsedFileNames)

        self.update_segmentation_display()
        if len(parsedFileNames) > 1:
            self.pb_sumFiles.setEnabled(True)
        else:
            self.pb_sumFiles.setEnabled(False)

    def select_irf_file(self):
        self.FA.load_irf()
        self.le_loadIRF.setText(str(self.FA.irfPath))

    def save_capture_csv(self):
        pass

    def clear_all(self):
        pass

    # OUTPUT FUNCTIONS
    def save_roi_decay_data(self):
        self.FA.set_rois(self.roiMaker.rois)
        self.FA.mask_image()
        data = self.FA.get_roi_decay_data()
        saveFilePath = QFileDialog.getSaveFileName()
        self.write_to_file(data, saveFilePath[0])

    def write_to_file(self, data, filepath):
        columnData = zip(*data)
        with open(filepath, "w", newline="") as f:
            writer = csv.writer(f)
            writer.writerows(columnData)
# Initializing Functions # LOAD MENU # ROI CONTROLS # SAVE DATA CONTROLS # SLIDERS # Data Capture Methods # OUTPUT FUNCTIONS