blindSourceSeparationWidget.py 6.75 KB
Newer Older
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
1
2
3
# coding: utf-8
# /*##########################################################################
#
4
# Copyright (c) 2017-2019 European Synchrotron Radiation Facility
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/


__authors__ = ["J. Garriga"]
__license__ = "MIT"
29
__date__ = "07/02/2020"
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
30
31
32
33
34
35

import numpy

from silx.gui import qt

from darfix.core.blindSourceSeparation import Method, BSS
36
from .operationThread import OperationThread
37
from .displayComponentsWidget import DisplayComponentsWidget
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
38
39
40
41


class BSSWidget(qt.QMainWindow):
    """
42
    Widget to apply blind source separation.
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
43
44
45
    """
    signalComputed = qt.Signal()

46
    def __init__(self, parent=None):
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
47
48
        qt.QMainWindow.__init__(self, parent)

49
        # Widget with the type of bss and the number of components to compute
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
50
51
52
53
        top_widget = qt.QWidget(self)

        methodLabel = qt.QLabel("Method: ")
        self.methodCB = qt.QComboBox()
54
        for method in Method.values():
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
55
56
57
58
59
            self.methodCB.addItem(method)
        nComponentsLabel = qt.QLabel("Num comp:")
        self.nComponentsLE = qt.QLineEdit("1")
        self.nComponentsLE.setValidator(qt.QIntValidator())
        self.computeButton = qt.QPushButton("Compute")
60
61
        maxNComponentsLabel = qt.QLabel("Max number of components:")
        self.maxNumComp = qt.QLineEdit("")
62
63
64
65
66
        self.maxNumComp.setToolTip("For a specific number of components enter an "
                                   "integer, for a\npercentage enter a float between "
                                   "0 (included) and 1 (not included).\n"
                                   "Float 0.5 will take as max number the 50% of "
                                   "the images.\nEmpty text computes all components.")
67
        self.maxNumComp.setValidator(qt.QDoubleValidator())
68
        self.detectButton = qt.QPushButton("Detect number of components")
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
69
        self.computeButton.setEnabled(False)
70
        self.detectButton.setEnabled(False)
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
71
72
73
74
75
76
77
        layout = qt.QGridLayout()

        layout.addWidget(methodLabel, 0, 0, 1, 1)
        layout.addWidget(self.methodCB, 0, 1, 1, 1)
        layout.addWidget(nComponentsLabel, 0, 2, 1, 1)
        layout.addWidget(self.nComponentsLE, 0, 3, 1, 1)
        layout.addWidget(self.computeButton, 0, 4, 1, 1)
78
79
        layout.addWidget(maxNComponentsLabel, 1, 2, 1, 1)
        layout.addWidget(self.maxNumComp, 1, 3, 1, 1)
80
        layout.addWidget(self.detectButton, 1, 4, 1, 1)
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
81
82

        top_widget.setLayout(layout)
83

Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
84
85
86
        self.splitter = qt.QSplitter(qt.Qt.Vertical)
        self.splitter.addWidget(top_widget)
        self.setCentralWidget(self.splitter)
87
88
89
90

        self._displayComponentsWidget = DisplayComponentsWidget()
        self.splitter.addWidget(self._displayComponentsWidget)
        self._displayComponentsWidget.hide()
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
91

92
        self.computeButton.clicked.connect(self._computeBSS)
93
        self.detectButton.clicked.connect(self._detectComp)
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108

    def hideButton(self):
        self._computeB.hide()

    def showButton(self):
        self._computeB.show()

    def setDataset(self, dataset):
        """
        Dataset setter. Saves the dataset and updates the stack with the dataset
        data

        :param Dataset dataset: dataset
        """
        self.dataset = dataset
109
        self.BSS = BSS(self.dataset.hi_data)
Julia Garriga Ferrer's avatar
Julia Garriga Ferrer committed
110
        self.computeButton.setEnabled(True)
111
        self.detectButton.setEnabled(True)
112

113
    def _computeBSS(self):
114
115
116
        """
        Computes blind source separation with the chosen method.
        """
117
        self.computeButton.setEnabled(False)
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
        self.nComponentsLE.setEnabled(False)
        method = Method(self.methodCB.currentText())
        n_comp = int(self.nComponentsLE.text())
        if method == Method.PCA:
            self._thread = OperationThread(self.BSS.PCA)
        elif method == Method.NNICA:
            self._thread = OperationThread(self.BSS.non_negative_ICA)
        elif method == Method.NMF:
            self._thread = OperationThread(self.BSS.NMF)
        elif method == Method.NNICA_NMF:
            self._thread = OperationThread(self.BSS.NNICA_NMF)
        else:
            raise ValueError('BSS method not managed')

        self._thread.setArgs(n_comp)
133
        self._thread.finished.connect(self._displayComponents)
134
135
        self._thread.start()

136
137
    def _displayComponents(self):
        self._thread.finished.disconnect(self._displayComponents)
138
139
140
141
142
143
144
145
146
147
        comp, self.W = self._thread.data
        n_comp = int(self.nComponentsLE.text())
        if comp.shape[0] < n_comp:
            n_comp = comp.shape[0]
            msg = qt.QMessageBox()
            msg.setIcon(qt.QMessageBox.Information)
            msg.setText("Found only {0} components".format(n_comp))
            msg.setStandardButtons(qt.QMessageBox.Ok)
            msg.exec_()
        self.comp = comp.reshape(n_comp, self.dataset.data.shape[1], self.dataset.data.shape[2])
148
        self._displayComponentsWidget.show()
149
150
        self.computeButton.setEnabled(True)
        self.nComponentsLE.setEnabled(True)
151
        self._displayComponentsWidget.setComponents(self.comp, self.W, self.dataset.get_dimensions_values())
152
153

    def _detectComp(self):
154
155
156
157
158
        txt = self.maxNumComp.text()
        if txt != "":
            maxNumComp = float(self.maxNumComp.text())
        else:
            maxNumComp = None
159
160
161
162
163
164
165
166
167
        self.detectButton.setEnabled(False)
        self._thread = OperationThread(self.BSS.PCA)
        self._thread.setArgs(None, maxNumComp)
        self._thread.finished.connect(self._setNumComp)
        self._thread.start()

    def _setNumComp(self):
        self._thread.finished.disconnect(self._setNumComp)
        mean, vecs, vals = self._thread.data
168
169
        vals /= numpy.sum(vals)
        components = len(vals[vals > 0.01])
170
        self.detectButton.setEnabled(True)
171
        self.nComponentsLE.setText(str(components))