source: sasview/src/sas/qtgui/Perspectives/Fitting/FittingPerspective.py @ 2eeda93

ESS_GUIESS_GUI_batch_fittingESS_GUI_bumps_abstractionESS_GUI_iss1116ESS_GUI_openclESS_GUI_orderingESS_GUI_sync_sascalc
Last change on this file since 2eeda93 was 2eeda93, checked in by Piotr Rozyczko <piotr.rozyczko@…>, 6 years ago

Working version of Save/Load? Analysis. SASVIEW-983.
Changed the default behaviour of Category/Model? combos:
Selecting a category does not pre-select the first model now.

  • Property mode set to 100644
File size: 12.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.onCopyToClipboard("")
105
106    def onParamPaste(self):
107        self.currentTab.onParameterPaste()
108
109    def onExcelCopy(self):
110        self.currentTab.onCopyToClipboard("Excel")
111
112    def onLatexCopy(self):
113        self.currentTab.onCopyToClipboard("Latex")
114
115    def getSerializedFitpage(self):
116        # serialize current(active) fitpage
117        fitpage_state = self.currentTab.getFitPage()
118        fitpage_state += self.currentTab.getFitModel()
119        # put the text into dictionary
120        line_dict = {}
121        for line in fitpage_state:
122            #content = line.split(',')
123            if len(line) > 1:
124                line_dict[line[0]] = line[1:]
125        return line_dict
126
127    def currentTabDataId(self):
128        """
129        Returns the data ID of the current tab
130        """
131        tab_id = None
132        if self.currentTab.data:
133            tab_id = self.currentTab.data.id
134        return tab_id
135
136    def updateFromParameters(self, parameters):
137        """
138        Pass the update parameters to the current fit page
139        """
140        self.currentTab.createPageForParameters(parameters)
141
142    def closeEvent(self, event):
143        """
144        Overwrite QDialog close method to allow for custom widget close
145        """
146        # Invoke fit page events
147        if self._allow_close:
148            # reset the closability flag
149            self.setClosable(value=False)
150            # Tell the MdiArea to close the container
151            self.parentWidget().close()
152            event.accept()
153        else:
154            # Maybe we should just minimize
155            self.setWindowState(QtCore.Qt.WindowMinimized)
156            event.ignore()
157
158    def addFit(self, data, is_batch=False):
159        """
160        Add a new tab for passed data
161        """
162        tab     = FittingWidget(parent=self.parent, data=data, tab_id=self.maxIndex)
163        tab.is_batch_fitting = is_batch
164
165        # Add this tab to the object library so it can be retrieved by scripting/jupyter
166        tab_name = self.getTabName(is_batch=is_batch)
167        ObjectLibrary.addObject(tab_name, tab)
168        self.tabs.append(tab)
169        if data:
170            self.updateFitDict(data, tab_name)
171        self.maxIndex += 1
172        icon = QtGui.QIcon()
173        if is_batch:
174            icon.addPixmap(QtGui.QPixmap("src/sas/qtgui/images/icons/layers.svg"))
175        self.addTab(tab, icon, tab_name)
176        # Show the new tab
177        self.setCurrentWidget(tab);
178        # Notify listeners
179        self.tabsModifiedSignal.emit()
180
181    def addConstraintTab(self):
182        """
183        Add a new C&S fitting tab
184        """
185        tabs = [isinstance(tab, ConstraintWidget) for tab in self.tabs]
186        if any(tabs):
187            # We already have a C&S tab: show it
188            self.setCurrentIndex(tabs.index(True))
189            return
190        tab     = ConstraintWidget(parent=self)
191        # Add this tab to the object library so it can be retrieved by scripting/jupyter
192        tab_name = self.getCSTabName() # TODO update the tab name scheme
193        ObjectLibrary.addObject(tab_name, tab)
194        self.tabs.append(tab)
195        icon = QtGui.QIcon()
196        icon.addPixmap(QtGui.QPixmap("src/sas/qtgui/images/icons/link.svg"))
197        self.addTab(tab, icon, tab_name)
198
199        # This will be the last tab, so set the index accordingly
200        self.setCurrentIndex(self.count()-1)
201
202    def updateFitDict(self, item_key, tab_name):
203        """
204        Create a list if none exists and append if there's already a list
205        """
206        item_key_str = str(item_key)
207        if item_key_str in list(self.dataToFitTab.keys()):
208            self.dataToFitTab[item_key_str].append(tab_name)
209        else:
210            self.dataToFitTab[item_key_str] = [tab_name]
211
212    def getTabName(self, is_batch=False):
213        """
214        Get the new tab name, based on the number of fitting tabs so far
215        """
216        page_name = "BatchPage" if is_batch else "FitPage"
217        page_name = page_name + str(self.maxIndex)
218        return page_name
219
220    def getCSTabName(self):
221        """
222        Get the new tab name, based on the number of fitting tabs so far
223        """
224        page_name = "Const. & Simul. Fit"
225        return page_name
226
227    def resetTab(self, index):
228        """
229        Adds a new tab and removes the last tab
230        as a way of resetting the fit tabs
231        """
232        # If data on tab empty - do nothing
233        if index in self.tabs and not self.tabs[index].data:
234            return
235        # Add a new, empy tab
236        self.addFit(None)
237        # Remove the previous last tab
238        self.tabCloses(index)
239
240    def tabCloses(self, index):
241        """
242        Update local bookkeeping on tab close
243        """
244        #assert len(self.tabs) >= index
245        # don't remove the last tab
246        if len(self.tabs) <= 1:
247            self.resetTab(index)
248            return
249        try:
250            ObjectLibrary.deleteObjectByRef(self.tabs[index])
251            self.removeTab(index)
252            del self.tabs[index]
253            self.tabsModifiedSignal.emit()
254        except IndexError:
255            # The tab might have already been deleted previously
256            pass
257
258    def closeTabByName(self, tab_name):
259        """
260        Given name of the fitting tab - close it
261        """
262        for tab_index in range(len(self.tabs)):
263            if self.tabText(tab_index) == tab_name:
264                self.tabCloses(tab_index)
265        pass # debug hook
266
267    def dataDeleted(self, index_list):
268        """
269        Delete fit tabs referencing given data
270        """
271        if not index_list or not self.dataToFitTab:
272            return
273        for index_to_delete in index_list:
274            index_to_delete_str = str(index_to_delete)
275            if index_to_delete_str in list(self.dataToFitTab.keys()):
276                for tab_name in self.dataToFitTab[index_to_delete_str]:
277                    # delete tab #index after corresponding data got removed
278                    self.closeTabByName(tab_name)
279                self.dataToFitTab.pop(index_to_delete_str)
280
281    def allowBatch(self):
282        """
283        Tell the caller that we accept multiple data instances
284        """
285        return True
286
287    def isSerializable(self):
288        """
289        Tell the caller that this perspective writes its state
290        """
291        return True
292
293    def setData(self, data_item=None, is_batch=False):
294        """
295        Assign new dataset to the fitting instance
296        Obtain a QStandardItem object and dissect it to get Data1D/2D
297        Pass it over to the calculator
298        """
299        assert data_item is not None
300
301        if not isinstance(data_item, list):
302            msg = "Incorrect type passed to the Fitting Perspective"
303            raise AttributeError(msg)
304
305        if not isinstance(data_item[0], QtGui.QStandardItem):
306            msg = "Incorrect type passed to the Fitting Perspective"
307            raise AttributeError(msg)
308
309        if is_batch:
310            # Just create a new fit tab. No empty batchFit tabs
311            self.addFit(data_item, is_batch=is_batch)
312            return
313
314        items = [data_item] if is_batch else data_item
315        for data in items:
316            # Find the first unassigned tab.
317            # If none, open a new tab.
318            available_tabs = [tab.acceptsData() for tab in self.tabs]
319
320            if numpy.any(available_tabs):
321                first_good_tab = available_tabs.index(True)
322                self.tabs[first_good_tab].data = data
323                tab_name = str(self.tabText(first_good_tab))
324                self.updateFitDict(data, tab_name)
325            else:
326                self.addFit(data, is_batch=is_batch)
327
328    def onFittingOptionsChange(self, fit_engine):
329        """
330        React to the fitting algorithm change by modifying window title
331        """
332        fitter = [f.id for f in options.FITTERS if f.name == str(fit_engine)][0]
333        # set the optimizer
334        self.fit_options.selected_id = str(fitter)
335        # Update the title
336        self.updateWindowTitle()
337
338    def onFittingStarted(self, tabs_for_fitting=None):
339        """
340        Notify tabs listed in tabs_for_fitting
341        that the fitting thread started
342        """
343        assert(isinstance(tabs_for_fitting, list))
344        assert(len(tabs_for_fitting)>0)
345
346        for tab_object in self.tabs:
347            if not isinstance(tab_object, FittingWidget):
348                continue
349            page_name = "Page%s"%tab_object.tab_id
350            if any([page_name in tab for tab in tabs_for_fitting]):
351                tab_object.disableInteractiveElements()
352
353        pass
354
355    def onFittingStopped(self, tabs_for_fitting=None):
356        """
357        Notify tabs listed in tabs_for_fitting
358        that the fitting thread stopped
359        """
360        assert(isinstance(tabs_for_fitting, list))
361        assert(len(tabs_for_fitting)>0)
362
363        for tab_object in self.tabs:
364            if not isinstance(tab_object, FittingWidget):
365                continue
366            page_name = "Page%s"%tab_object.tab_id
367            if any([page_name in tab for tab in tabs_for_fitting]):
368                tab_object.enableInteractiveElements()
369
370        pass
371
372    def getCurrentStateAsXml(self):
373        """
374        Returns an XML version of the current state
375        """
376        state = {}
377        for tab in self.tabs:
378            pass
379        return state
380
381    @property
382    def currentTab(self):
383        """
384        Returns the tab widget currently shown
385        """
386        return self.currentWidget()
387
Note: See TracBrowser for help on using the repository browser.