source: sasview/src/sas/qtgui/Perspectives/Fitting/FittingPerspective.py @ 345b3b3

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 345b3b3 was 345b3b3, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 5 years ago

Save status of data explorer

  • Property mode set to 100644
File size: 11.5 KB
Line 
1import numpy
2
3from PyQt5 import QtCore
4from PyQt5 import QtGui
5from PyQt5 import QtWidgets
6
7from bumps import options
8from bumps import fitters
9
10import sas.qtgui.Utilities.LocalConfig as LocalConfig
11import sas.qtgui.Utilities.ObjectLibrary as ObjectLibrary
12
13from sas.qtgui.Perspectives.Fitting.FittingWidget import FittingWidget
14from sas.qtgui.Perspectives.Fitting.ConstraintWidget import ConstraintWidget
15from sas.qtgui.Perspectives.Fitting.FittingOptions import FittingOptions
16from sas.qtgui.Perspectives.Fitting.GPUOptions import GPUOptions
17
18class FittingWindow(QtWidgets.QTabWidget):
19    """
20    """
21    tabsModifiedSignal = QtCore.pyqtSignal()
22    fittingStartedSignal = QtCore.pyqtSignal(list)
23    fittingStoppedSignal = QtCore.pyqtSignal(list)
24
25    name = "Fitting" # For displaying in the combo box in DataExplorer
26    def __init__(self, parent=None, data=None):
27
28        super(FittingWindow, self).__init__()
29
30        self.parent = parent
31        self._data = data
32
33        # List of active fits
34        self.tabs = []
35
36        # Max index for adding new, non-clashing tab names
37        self.maxIndex = 1
38
39        ## Index of the current tab
40        #self.currentTab = 0
41
42        # The default optimizer
43        self.optimizer = 'Levenberg-Marquardt'
44
45        # Dataset index -> Fitting tab mapping
46        self.dataToFitTab = {}
47
48        # The tabs need to be closeable
49        self.setTabsClosable(True)
50
51        # The tabs need to be movabe
52        self.setMovable(True)
53
54        self.communicate = self.parent.communicator()
55
56        # Initialize the first tab
57        self.addFit(None)
58
59        # Deal with signals
60        self.tabCloseRequested.connect(self.tabCloses)
61        self.communicate.dataDeletedSignal.connect(self.dataDeleted)
62        self.fittingStartedSignal.connect(self.onFittingStarted)
63        self.fittingStoppedSignal.connect(self.onFittingStopped)
64
65        self.communicate.copyFitParamsSignal.connect(self.onParamCopy)
66        self.communicate.pasteFitParamsSignal.connect(self.onParamPaste)
67        self.communicate.copyExcelFitParamsSignal.connect(self.onExcelCopy)
68        self.communicate.copyLatexFitParamsSignal.connect(self.onLatexCopy)
69
70
71        # Perspective window not allowed to close by default
72        self._allow_close = False
73
74        # Fit options - uniform for all tabs
75        self.fit_options = options.FIT_CONFIG
76        self.fit_options_widget = FittingOptions(self, config=self.fit_options)
77        self.fit_options.selected_id = fitters.LevenbergMarquardtFit.id
78
79        # Listen to GUI Manager signal updating fit options
80        self.fit_options_widget.fit_option_changed.connect(self.onFittingOptionsChange)
81
82        # GPU Options
83        self.gpu_options_widget = GPUOptions(self)
84
85        self.updateWindowTitle()
86
87    def updateWindowTitle(self):
88        """
89        Update the window title with the current optimizer name
90        """
91        self.optimizer = self.fit_options.selected_name
92        self.setWindowTitle('Fit panel - Active Fitting Optimizer: %s' % self.optimizer)
93
94
95    def setClosable(self, value=True):
96        """
97        Allow outsiders to close this widget
98        """
99        assert isinstance(value, bool)
100
101        self._allow_close = value
102
103    def onParamCopy(self):
104        self.currentTab.onParameterCopy("")
105
106    def onParamPaste(self):
107        self.currentTab.onParameterPaste()
108
109    def onExcelCopy(self):
110        self.currentTab.onParameterCopy("Excel")
111
112    def onLatexCopy(self):
113        self.currentTab.onParameterCopy("Latex")
114
115    def closeEvent(self, event):
116        """
117        Overwrite QDialog close method to allow for custom widget close
118        """
119        # Invoke fit page events
120        if self._allow_close:
121            # reset the closability flag
122            self.setClosable(value=False)
123            # Tell the MdiArea to close the container
124            self.parentWidget().close()
125            event.accept()
126        else:
127            # Maybe we should just minimize
128            self.setWindowState(QtCore.Qt.WindowMinimized)
129            event.ignore()
130
131    def addFit(self, data, is_batch=False):
132        """
133        Add a new tab for passed data
134        """
135        tab     = FittingWidget(parent=self.parent, data=data, tab_id=self.maxIndex)
136        tab.is_batch_fitting = is_batch
137
138        # Add this tab to the object library so it can be retrieved by scripting/jupyter
139        tab_name = self.getTabName(is_batch=is_batch)
140        ObjectLibrary.addObject(tab_name, tab)
141        self.tabs.append(tab)
142        if data:
143            self.updateFitDict(data, tab_name)
144        self.maxIndex += 1
145        icon = QtGui.QIcon()
146        if is_batch:
147            icon.addPixmap(QtGui.QPixmap("src/sas/qtgui/images/icons/layers.svg"))
148        self.addTab(tab, icon, tab_name)
149        # Show the new tab
150        self.setCurrentWidget(tab);
151        # Notify listeners
152        self.tabsModifiedSignal.emit()
153
154    def addConstraintTab(self):
155        """
156        Add a new C&S fitting tab
157        """
158        tabs = [isinstance(tab, ConstraintWidget) for tab in self.tabs]
159        if any(tabs):
160            # We already have a C&S tab: show it
161            self.setCurrentIndex(tabs.index(True))
162            return
163        tab     = ConstraintWidget(parent=self)
164        # Add this tab to the object library so it can be retrieved by scripting/jupyter
165        tab_name = self.getCSTabName() # TODO update the tab name scheme
166        ObjectLibrary.addObject(tab_name, tab)
167        self.tabs.append(tab)
168        icon = QtGui.QIcon()
169        icon.addPixmap(QtGui.QPixmap("src/sas/qtgui/images/icons/link.svg"))
170        self.addTab(tab, icon, tab_name)
171
172        # This will be the last tab, so set the index accordingly
173        self.setCurrentIndex(self.count()-1)
174
175    def updateFitDict(self, item_key, tab_name):
176        """
177        Create a list if none exists and append if there's already a list
178        """
179        item_key_str = str(item_key)
180        if item_key_str in list(self.dataToFitTab.keys()):
181            self.dataToFitTab[item_key_str].append(tab_name)
182        else:
183            self.dataToFitTab[item_key_str] = [tab_name]
184
185    def getTabName(self, is_batch=False):
186        """
187        Get the new tab name, based on the number of fitting tabs so far
188        """
189        page_name = "BatchPage" if is_batch else "FitPage"
190        page_name = page_name + str(self.maxIndex)
191        return page_name
192
193    def getCSTabName(self):
194        """
195        Get the new tab name, based on the number of fitting tabs so far
196        """
197        page_name = "Const. & Simul. Fit"
198        return page_name
199
200    def resetTab(self, index):
201        """
202        Adds a new tab and removes the last tab
203        as a way of resetting the fit tabs
204        """
205        # If data on tab empty - do nothing
206        if index in self.tabs and not self.tabs[index].data:
207            return
208        # Add a new, empy tab
209        self.addFit(None)
210        # Remove the previous last tab
211        self.tabCloses(index)
212
213    def tabCloses(self, index):
214        """
215        Update local bookkeeping on tab close
216        """
217        #assert len(self.tabs) >= index
218        # don't remove the last tab
219        if len(self.tabs) <= 1:
220            self.resetTab(index)
221            return
222        try:
223            ObjectLibrary.deleteObjectByRef(self.tabs[index])
224            self.removeTab(index)
225            del self.tabs[index]
226            self.tabsModifiedSignal.emit()
227        except IndexError:
228            # The tab might have already been deleted previously
229            pass
230
231    def closeTabByName(self, tab_name):
232        """
233        Given name of the fitting tab - close it
234        """
235        for tab_index in range(len(self.tabs)):
236            if self.tabText(tab_index) == tab_name:
237                self.tabCloses(tab_index)
238        pass # debug hook
239
240    def dataDeleted(self, index_list):
241        """
242        Delete fit tabs referencing given data
243        """
244        if not index_list or not self.dataToFitTab:
245            return
246        for index_to_delete in index_list:
247            index_to_delete_str = str(index_to_delete)
248            if index_to_delete_str in list(self.dataToFitTab.keys()):
249                for tab_name in self.dataToFitTab[index_to_delete_str]:
250                    # delete tab #index after corresponding data got removed
251                    self.closeTabByName(tab_name)
252                self.dataToFitTab.pop(index_to_delete_str)
253
254    def allowBatch(self):
255        """
256        Tell the caller that we accept multiple data instances
257        """
258        return True
259
260    def setData(self, data_item=None, is_batch=False):
261        """
262        Assign new dataset to the fitting instance
263        Obtain a QStandardItem object and dissect it to get Data1D/2D
264        Pass it over to the calculator
265        """
266        assert data_item is not None
267
268        if not isinstance(data_item, list):
269            msg = "Incorrect type passed to the Fitting Perspective"
270            raise AttributeError(msg)
271
272        if not isinstance(data_item[0], QtGui.QStandardItem):
273            msg = "Incorrect type passed to the Fitting Perspective"
274            raise AttributeError(msg)
275
276        if is_batch:
277            # Just create a new fit tab. No empty batchFit tabs
278            self.addFit(data_item, is_batch=is_batch)
279            return
280
281        items = [data_item] if is_batch else data_item
282        for data in items:
283            # Find the first unassigned tab.
284            # If none, open a new tab.
285            available_tabs = [tab.acceptsData() for tab in self.tabs]
286
287            if numpy.any(available_tabs):
288                first_good_tab = available_tabs.index(True)
289                self.tabs[first_good_tab].data = data
290                tab_name = str(self.tabText(first_good_tab))
291                self.updateFitDict(data, tab_name)
292            else:
293                self.addFit(data, is_batch=is_batch)
294
295    def onFittingOptionsChange(self, fit_engine):
296        """
297        React to the fitting algorithm change by modifying window title
298        """
299        fitter = [f.id for f in options.FITTERS if f.name == str(fit_engine)][0]
300        # set the optimizer
301        self.fit_options.selected_id = str(fitter)
302        # Update the title
303        self.updateWindowTitle()
304
305    def onFittingStarted(self, tabs_for_fitting=None):
306        """
307        Notify tabs listed in tabs_for_fitting
308        that the fitting thread started
309        """
310        assert(isinstance(tabs_for_fitting, list))
311        assert(len(tabs_for_fitting)>0)
312
313        for tab_object in self.tabs:
314            if not isinstance(tab_object, FittingWidget):
315                continue
316            page_name = "Page%s"%tab_object.tab_id
317            if any([page_name in tab for tab in tabs_for_fitting]):
318                tab_object.disableInteractiveElements()
319
320        pass
321
322    def onFittingStopped(self, tabs_for_fitting=None):
323        """
324        Notify tabs listed in tabs_for_fitting
325        that the fitting thread stopped
326        """
327        assert(isinstance(tabs_for_fitting, list))
328        assert(len(tabs_for_fitting)>0)
329
330        for tab_object in self.tabs:
331            if not isinstance(tab_object, FittingWidget):
332                continue
333            page_name = "Page%s"%tab_object.tab_id
334            if any([page_name in tab for tab in tabs_for_fitting]):
335                tab_object.enableInteractiveElements()
336
337        pass
338
339    def getCurrentStateAsXml(self):
340        """
341        Returns an XML version of the current state
342        """
343        state = {}
344        for tab in self.tabs:
345            pass
346        return state
347
348    @property
349    def currentTab(self):
350        """
351        Returns the tab widget currently shown
352        """
353        return self.currentWidget()
354
Note: See TracBrowser for help on using the repository browser.