1 | import logging |
---|
2 | import numpy as np |
---|
3 | |
---|
4 | from PyQt5 import QtGui, QtCore, QtWidgets |
---|
5 | |
---|
6 | # sas-global |
---|
7 | import sas.qtgui.Utilities.GuiUtils as GuiUtils |
---|
8 | |
---|
9 | # pr inversion GUI elements |
---|
10 | from .InversionUtils import WIDGETS |
---|
11 | from .UI.TabbedInversionUI import Ui_PrInversion |
---|
12 | from .InversionLogic import InversionLogic |
---|
13 | |
---|
14 | # pr inversion calculation elements |
---|
15 | from sas.sascalc.pr.invertor import Invertor |
---|
16 | from sas.qtgui.Plotting.PlotterData import Data1D |
---|
17 | # Batch calculation display |
---|
18 | from sas.qtgui.Utilities.GridPanel import BatchInversionOutputPanel |
---|
19 | |
---|
20 | |
---|
21 | def is_float(value): |
---|
22 | """Converts text input values to floats. Empty strings throw ValueError""" |
---|
23 | try: |
---|
24 | return float(value) |
---|
25 | except ValueError: |
---|
26 | return 0.0 |
---|
27 | |
---|
28 | |
---|
29 | NUMBER_OF_TERMS = 10 |
---|
30 | REGULARIZATION = 0.0001 |
---|
31 | BACKGROUND_INPUT = 0.0 |
---|
32 | MAX_DIST = 140.0 |
---|
33 | DICT_KEYS = ["Calculator", "PrPlot", "DataPlot"] |
---|
34 | |
---|
35 | logger = logging.getLogger(__name__) |
---|
36 | |
---|
37 | |
---|
38 | class InversionWindow(QtWidgets.QDialog, Ui_PrInversion): |
---|
39 | """ |
---|
40 | The main window for the P(r) Inversion perspective. |
---|
41 | """ |
---|
42 | |
---|
43 | name = "Inversion" |
---|
44 | estimateSignal = QtCore.pyqtSignal(tuple) |
---|
45 | estimateNTSignal = QtCore.pyqtSignal(tuple) |
---|
46 | estimateDynamicNTSignal = QtCore.pyqtSignal(tuple) |
---|
47 | estimateDynamicSignal = QtCore.pyqtSignal(tuple) |
---|
48 | calculateSignal = QtCore.pyqtSignal(tuple) |
---|
49 | |
---|
50 | def __init__(self, parent=None, data=None): |
---|
51 | super(InversionWindow, self).__init__() |
---|
52 | self.setupUi(self) |
---|
53 | |
---|
54 | self.setWindowTitle("P(r) Inversion Perspective") |
---|
55 | |
---|
56 | self._manager = parent |
---|
57 | #Needed for Batch fitting |
---|
58 | self._parent = parent |
---|
59 | self.communicate = parent.communicator() |
---|
60 | self.communicate.dataDeletedSignal.connect(self.removeData) |
---|
61 | |
---|
62 | self.logic = InversionLogic() |
---|
63 | |
---|
64 | # The window should not close |
---|
65 | self._allowClose = False |
---|
66 | |
---|
67 | # Visible data items |
---|
68 | # current QStandardItem showing on the panel |
---|
69 | self._data = None |
---|
70 | # Reference to Dmax window for self._data |
---|
71 | self.dmaxWindow = None |
---|
72 | # p(r) calculator for self._data |
---|
73 | self._calculator = Invertor() |
---|
74 | # Default to background estimate |
---|
75 | self._calculator.est_bck = True |
---|
76 | # plots of self._data |
---|
77 | self.prPlot = None |
---|
78 | self.dataPlot = None |
---|
79 | # suggested nTerms |
---|
80 | self.nTermsSuggested = NUMBER_OF_TERMS |
---|
81 | |
---|
82 | # Calculation threads used by all data items |
---|
83 | self.calcThread = None |
---|
84 | self.estimationThread = None |
---|
85 | self.estimationThreadNT = None |
---|
86 | self.isCalculating = False |
---|
87 | |
---|
88 | # Mapping for all data items |
---|
89 | # Dictionary mapping data to all parameters |
---|
90 | self._dataList = {} |
---|
91 | if not isinstance(data, list): |
---|
92 | data_list = [data] |
---|
93 | if data is not None: |
---|
94 | for datum in data_list: |
---|
95 | self.updateDataList(datum) |
---|
96 | |
---|
97 | self.dataDeleted = False |
---|
98 | |
---|
99 | self.model = QtGui.QStandardItemModel(self) |
---|
100 | self.mapper = QtWidgets.QDataWidgetMapper(self) |
---|
101 | |
---|
102 | # Batch fitting parameters |
---|
103 | self.isBatch = False |
---|
104 | self.batchResultsWindow = None |
---|
105 | self.batchResults = {} |
---|
106 | self.batchComplete = [] |
---|
107 | |
---|
108 | # Add validators |
---|
109 | self.setupValidators() |
---|
110 | # Link user interactions with methods |
---|
111 | self.setupLinks() |
---|
112 | # Set values |
---|
113 | self.setupModel() |
---|
114 | # Set up the Widget Map |
---|
115 | self.setupMapper() |
---|
116 | |
---|
117 | #Hidding calculate all buton |
---|
118 | self.calculateAllButton.setVisible(False) |
---|
119 | # Set base window state |
---|
120 | self.setupWindow() |
---|
121 | |
---|
122 | ###################################################################### |
---|
123 | # Base Perspective Class Definitions |
---|
124 | |
---|
125 | def communicator(self): |
---|
126 | return self.communicate |
---|
127 | |
---|
128 | def allowBatch(self): |
---|
129 | return False |
---|
130 | |
---|
131 | def setClosable(self, value=True): |
---|
132 | """ |
---|
133 | Allow outsiders close this widget |
---|
134 | """ |
---|
135 | assert isinstance(value, bool) |
---|
136 | self._allowClose = value |
---|
137 | |
---|
138 | def isClosable(self): |
---|
139 | """ |
---|
140 | Allow outsiders close this widget |
---|
141 | """ |
---|
142 | return self._allowClose |
---|
143 | |
---|
144 | def closeEvent(self, event): |
---|
145 | """ |
---|
146 | Overwrite QDialog close method to allow for custom widget close |
---|
147 | """ |
---|
148 | # Close report widgets before closing/minimizing main widget |
---|
149 | self.closeDMax() |
---|
150 | self.closeBatchResults() |
---|
151 | if self._allowClose: |
---|
152 | # reset the closability flag |
---|
153 | self.setClosable(value=False) |
---|
154 | # Tell the MdiArea to close the container |
---|
155 | self.parentWidget().close() |
---|
156 | event.accept() |
---|
157 | else: |
---|
158 | event.ignore() |
---|
159 | # Maybe we should just minimize |
---|
160 | self.setWindowState(QtCore.Qt.WindowMinimized) |
---|
161 | |
---|
162 | def closeDMax(self): |
---|
163 | if self.dmaxWindow is not None: |
---|
164 | self.dmaxWindow.close() |
---|
165 | |
---|
166 | def closeBatchResults(self): |
---|
167 | if self.batchResultsWindow is not None: |
---|
168 | self.batchResultsWindow.close() |
---|
169 | |
---|
170 | ###################################################################### |
---|
171 | # Initialization routines |
---|
172 | |
---|
173 | def setupLinks(self): |
---|
174 | """Connect the use controls to their appropriate methods""" |
---|
175 | self.dataList.currentIndexChanged.connect(self.displayChange) |
---|
176 | self.calculateAllButton.clicked.connect(self.startThreadAll) |
---|
177 | self.calculateThisButton.clicked.connect(self.startThread) |
---|
178 | self.stopButton.clicked.connect(self.stopCalculation) |
---|
179 | self.removeButton.clicked.connect(self.removeData) |
---|
180 | self.helpButton.clicked.connect(self.help) |
---|
181 | self.estimateBgd.toggled.connect(self.toggleBgd) |
---|
182 | self.manualBgd.toggled.connect(self.toggleBgd) |
---|
183 | self.regConstantSuggestionButton.clicked.connect(self.acceptAlpha) |
---|
184 | self.noOfTermsSuggestionButton.clicked.connect(self.acceptNoTerms) |
---|
185 | self.explorerButton.clicked.connect(self.openExplorerWindow) |
---|
186 | |
---|
187 | self.backgroundInput.textChanged.connect( |
---|
188 | lambda: self.set_background(self.backgroundInput.text())) |
---|
189 | self.minQInput.textChanged.connect( |
---|
190 | lambda: self._calculator.set_qmin(is_float(self.minQInput.text()))) |
---|
191 | self.regularizationConstantInput.textChanged.connect( |
---|
192 | lambda: self._calculator.set_alpha(is_float(self.regularizationConstantInput.text()))) |
---|
193 | self.maxDistanceInput.textChanged.connect( |
---|
194 | lambda: self._calculator.set_dmax(is_float(self.maxDistanceInput.text()))) |
---|
195 | self.maxQInput.textChanged.connect( |
---|
196 | lambda: self._calculator.set_qmax(is_float(self.maxQInput.text()))) |
---|
197 | self.slitHeightInput.textChanged.connect( |
---|
198 | lambda: self._calculator.set_slit_height(is_float(self.slitHeightInput.text()))) |
---|
199 | self.slitWidthInput.textChanged.connect( |
---|
200 | lambda: self._calculator.set_slit_width(is_float(self.slitWidthInput.text()))) |
---|
201 | |
---|
202 | self.model.itemChanged.connect(self.model_changed) |
---|
203 | self.estimateNTSignal.connect(self._estimateNTUpdate) |
---|
204 | self.estimateDynamicNTSignal.connect(self._estimateDynamicNTUpdate) |
---|
205 | self.estimateDynamicSignal.connect(self._estimateDynamicUpdate) |
---|
206 | self.estimateSignal.connect(self._estimateUpdate) |
---|
207 | self.calculateSignal.connect(self._calculateUpdate) |
---|
208 | |
---|
209 | self.maxDistanceInput.textEdited.connect(self.performEstimateDynamic) |
---|
210 | |
---|
211 | def setupMapper(self): |
---|
212 | # Set up the mapper. |
---|
213 | self.mapper.setOrientation(QtCore.Qt.Vertical) |
---|
214 | self.mapper.setModel(self.model) |
---|
215 | |
---|
216 | # Filename |
---|
217 | self.mapper.addMapping(self.dataList, WIDGETS.W_FILENAME) |
---|
218 | # Background |
---|
219 | self.mapper.addMapping(self.backgroundInput, WIDGETS.W_BACKGROUND_INPUT) |
---|
220 | self.mapper.addMapping(self.estimateBgd, WIDGETS.W_ESTIMATE) |
---|
221 | self.mapper.addMapping(self.manualBgd, WIDGETS.W_MANUAL_INPUT) |
---|
222 | |
---|
223 | # Qmin/Qmax |
---|
224 | self.mapper.addMapping(self.minQInput, WIDGETS.W_QMIN) |
---|
225 | self.mapper.addMapping(self.maxQInput, WIDGETS.W_QMAX) |
---|
226 | |
---|
227 | # Slit Parameter items |
---|
228 | self.mapper.addMapping(self.slitWidthInput, WIDGETS.W_SLIT_WIDTH) |
---|
229 | self.mapper.addMapping(self.slitHeightInput, WIDGETS.W_SLIT_HEIGHT) |
---|
230 | |
---|
231 | # Parameter Items |
---|
232 | self.mapper.addMapping(self.regularizationConstantInput, WIDGETS.W_REGULARIZATION) |
---|
233 | self.mapper.addMapping(self.regConstantSuggestionButton, WIDGETS.W_REGULARIZATION_SUGGEST) |
---|
234 | self.mapper.addMapping(self.explorerButton, WIDGETS.W_EXPLORE) |
---|
235 | self.mapper.addMapping(self.maxDistanceInput, WIDGETS.W_MAX_DIST) |
---|
236 | self.mapper.addMapping(self.noOfTermsInput, WIDGETS.W_NO_TERMS) |
---|
237 | self.mapper.addMapping(self.noOfTermsSuggestionButton, WIDGETS.W_NO_TERMS_SUGGEST) |
---|
238 | |
---|
239 | # Output |
---|
240 | self.mapper.addMapping(self.rgValue, WIDGETS.W_RG) |
---|
241 | self.mapper.addMapping(self.iQ0Value, WIDGETS.W_I_ZERO) |
---|
242 | self.mapper.addMapping(self.backgroundValue, WIDGETS.W_BACKGROUND_OUTPUT) |
---|
243 | self.mapper.addMapping(self.computationTimeValue, WIDGETS.W_COMP_TIME) |
---|
244 | self.mapper.addMapping(self.chiDofValue, WIDGETS.W_CHI_SQUARED) |
---|
245 | self.mapper.addMapping(self.oscillationValue, WIDGETS.W_OSCILLATION) |
---|
246 | self.mapper.addMapping(self.posFractionValue, WIDGETS.W_POS_FRACTION) |
---|
247 | self.mapper.addMapping(self.sigmaPosFractionValue, WIDGETS.W_SIGMA_POS_FRACTION) |
---|
248 | |
---|
249 | # Main Buttons |
---|
250 | self.mapper.addMapping(self.removeButton, WIDGETS.W_REMOVE) |
---|
251 | self.mapper.addMapping(self.calculateAllButton, WIDGETS.W_CALCULATE_ALL) |
---|
252 | self.mapper.addMapping(self.calculateThisButton, WIDGETS.W_CALCULATE_VISIBLE) |
---|
253 | self.mapper.addMapping(self.helpButton, WIDGETS.W_HELP) |
---|
254 | |
---|
255 | self.mapper.toFirst() |
---|
256 | |
---|
257 | def setupModel(self): |
---|
258 | """ |
---|
259 | Update boxes with initial values |
---|
260 | """ |
---|
261 | bgd_item = QtGui.QStandardItem(str(BACKGROUND_INPUT)) |
---|
262 | self.model.setItem(WIDGETS.W_BACKGROUND_INPUT, bgd_item) |
---|
263 | blank_item = QtGui.QStandardItem("") |
---|
264 | self.model.setItem(WIDGETS.W_QMIN, blank_item) |
---|
265 | blank_item = QtGui.QStandardItem("") |
---|
266 | self.model.setItem(WIDGETS.W_QMAX, blank_item) |
---|
267 | blank_item = QtGui.QStandardItem("") |
---|
268 | self.model.setItem(WIDGETS.W_SLIT_WIDTH, blank_item) |
---|
269 | blank_item = QtGui.QStandardItem("") |
---|
270 | self.model.setItem(WIDGETS.W_SLIT_HEIGHT, blank_item) |
---|
271 | no_terms_item = QtGui.QStandardItem(str(NUMBER_OF_TERMS)) |
---|
272 | self.model.setItem(WIDGETS.W_NO_TERMS, no_terms_item) |
---|
273 | reg_item = QtGui.QStandardItem(str(REGULARIZATION)) |
---|
274 | self.model.setItem(WIDGETS.W_REGULARIZATION, reg_item) |
---|
275 | max_dist_item = QtGui.QStandardItem(str(MAX_DIST)) |
---|
276 | self.model.setItem(WIDGETS.W_MAX_DIST, max_dist_item) |
---|
277 | blank_item = QtGui.QStandardItem("") |
---|
278 | self.model.setItem(WIDGETS.W_RG, blank_item) |
---|
279 | blank_item = QtGui.QStandardItem("") |
---|
280 | self.model.setItem(WIDGETS.W_I_ZERO, blank_item) |
---|
281 | bgd_item = QtGui.QStandardItem(str(BACKGROUND_INPUT)) |
---|
282 | self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, bgd_item) |
---|
283 | blank_item = QtGui.QStandardItem("") |
---|
284 | self.model.setItem(WIDGETS.W_COMP_TIME, blank_item) |
---|
285 | blank_item = QtGui.QStandardItem("") |
---|
286 | self.model.setItem(WIDGETS.W_CHI_SQUARED, blank_item) |
---|
287 | blank_item = QtGui.QStandardItem("") |
---|
288 | self.model.setItem(WIDGETS.W_OSCILLATION, blank_item) |
---|
289 | blank_item = QtGui.QStandardItem("") |
---|
290 | self.model.setItem(WIDGETS.W_POS_FRACTION, blank_item) |
---|
291 | blank_item = QtGui.QStandardItem("") |
---|
292 | self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION, blank_item) |
---|
293 | |
---|
294 | def setupWindow(self): |
---|
295 | """Initialize base window state on init""" |
---|
296 | self.enableButtons() |
---|
297 | self.estimateBgd.setChecked(True) |
---|
298 | |
---|
299 | def setupValidators(self): |
---|
300 | """Apply validators to editable line edits""" |
---|
301 | self.noOfTermsInput.setValidator(QtGui.QIntValidator()) |
---|
302 | self.regularizationConstantInput.setValidator(GuiUtils.DoubleValidator()) |
---|
303 | self.maxDistanceInput.setValidator(GuiUtils.DoubleValidator()) |
---|
304 | self.minQInput.setValidator(GuiUtils.DoubleValidator()) |
---|
305 | self.maxQInput.setValidator(GuiUtils.DoubleValidator()) |
---|
306 | self.slitHeightInput.setValidator(GuiUtils.DoubleValidator()) |
---|
307 | self.slitWidthInput.setValidator(GuiUtils.DoubleValidator()) |
---|
308 | |
---|
309 | ###################################################################### |
---|
310 | # Methods for updating GUI |
---|
311 | |
---|
312 | def enableButtons(self): |
---|
313 | """ |
---|
314 | Enable buttons when data is present, else disable them |
---|
315 | """ |
---|
316 | self.calculateAllButton.setEnabled(len(self._dataList) > 1 |
---|
317 | and not self.isBatch |
---|
318 | and not self.isCalculating) |
---|
319 | self.calculateThisButton.setEnabled(self.logic.data_is_loaded |
---|
320 | and not self.isBatch |
---|
321 | and not self.isCalculating) |
---|
322 | self.removeButton.setEnabled(self.logic.data_is_loaded) |
---|
323 | self.explorerButton.setEnabled(self.logic.data_is_loaded) |
---|
324 | self.stopButton.setVisible(self.isCalculating) |
---|
325 | self.regConstantSuggestionButton.setEnabled( |
---|
326 | self.logic.data_is_loaded and |
---|
327 | self._calculator.suggested_alpha != self._calculator.alpha) |
---|
328 | self.noOfTermsSuggestionButton.setEnabled( |
---|
329 | self.logic.data_is_loaded and |
---|
330 | self._calculator.nfunc != self.nTermsSuggested) |
---|
331 | |
---|
332 | def populateDataComboBox(self, filename, data_ref): |
---|
333 | """ |
---|
334 | Append a new file name to the data combobox |
---|
335 | :param filename: data filename |
---|
336 | :param data_ref: QStandardItem reference for data set to be added |
---|
337 | """ |
---|
338 | self.dataList.addItem(filename, data_ref) |
---|
339 | |
---|
340 | def acceptNoTerms(self): |
---|
341 | """Send estimated no of terms to input""" |
---|
342 | self.model.setItem(WIDGETS.W_NO_TERMS, QtGui.QStandardItem( |
---|
343 | self.noOfTermsSuggestionButton.text())) |
---|
344 | |
---|
345 | def acceptAlpha(self): |
---|
346 | """Send estimated alpha to input""" |
---|
347 | self.model.setItem(WIDGETS.W_REGULARIZATION, QtGui.QStandardItem( |
---|
348 | self.regConstantSuggestionButton.text())) |
---|
349 | |
---|
350 | def displayChange(self, data_index=0): |
---|
351 | """Switch to another item in the data list""" |
---|
352 | if self.dataDeleted: |
---|
353 | return |
---|
354 | self.updateDataList(self._data) |
---|
355 | self.setCurrentData(self.dataList.itemData(data_index)) |
---|
356 | |
---|
357 | ###################################################################### |
---|
358 | # GUI Interaction Events |
---|
359 | |
---|
360 | def updateCalculator(self): |
---|
361 | """Update all p(r) params""" |
---|
362 | self._calculator.set_x(self.logic.data.x) |
---|
363 | self._calculator.set_y(self.logic.data.y) |
---|
364 | self._calculator.set_err(self.logic.data.dy) |
---|
365 | self.set_background(self.backgroundInput.text()) |
---|
366 | |
---|
367 | def set_background(self, value): |
---|
368 | self._calculator.background = is_float(value) |
---|
369 | |
---|
370 | def model_changed(self): |
---|
371 | """Update the values when user makes changes""" |
---|
372 | if not self.mapper: |
---|
373 | msg = "Unable to update P{r}. The connection between the main GUI " |
---|
374 | msg += "and P(r) was severed. Attempting to restart P(r)." |
---|
375 | logger.warning(msg) |
---|
376 | self.setClosable(True) |
---|
377 | self.close() |
---|
378 | InversionWindow.__init__(self.parent(), list(self._dataList.keys())) |
---|
379 | exit(0) |
---|
380 | if self.dmaxWindow is not None: |
---|
381 | self.dmaxWindow.nfunc = self.getNFunc() |
---|
382 | self.dmaxWindow.pr_state = self._calculator |
---|
383 | self.mapper.toLast() |
---|
384 | |
---|
385 | def help(self): |
---|
386 | """ |
---|
387 | Open the P(r) Inversion help browser |
---|
388 | """ |
---|
389 | tree_location = "/user/qtgui/Perspectives/Inversion/pr_help.html" |
---|
390 | |
---|
391 | # Actual file anchor will depend on the combo box index |
---|
392 | # Note that we can be clusmy here, since bad current_fitter_id |
---|
393 | # will just make the page displayed from the top |
---|
394 | self._manager.showHelp(tree_location) |
---|
395 | |
---|
396 | def toggleBgd(self): |
---|
397 | """ |
---|
398 | Toggle the background between manual and estimated |
---|
399 | """ |
---|
400 | if self.estimateBgd.isChecked(): |
---|
401 | self.manualBgd.setChecked(False) |
---|
402 | self.backgroundInput.setEnabled(False) |
---|
403 | self._calculator.set_est_bck = True |
---|
404 | elif self.manualBgd.isChecked(): |
---|
405 | self.estimateBgd.setChecked(False) |
---|
406 | self.backgroundInput.setEnabled(True) |
---|
407 | self._calculator.set_est_bck = False |
---|
408 | else: |
---|
409 | pass |
---|
410 | |
---|
411 | def openExplorerWindow(self): |
---|
412 | """ |
---|
413 | Open the Explorer window to see correlations between params and results |
---|
414 | """ |
---|
415 | from .DMaxExplorerWidget import DmaxWindow |
---|
416 | self.dmaxWindow = DmaxWindow(pr_state=self._calculator, |
---|
417 | nfunc=self.getNFunc(), |
---|
418 | parent=self) |
---|
419 | self.dmaxWindow.show() |
---|
420 | |
---|
421 | def showBatchOutput(self): |
---|
422 | """ |
---|
423 | Display the batch output in tabular form |
---|
424 | :param output_data: Dictionary mapping filename -> P(r) instance |
---|
425 | """ |
---|
426 | if self.batchResultsWindow is None: |
---|
427 | self.batchResultsWindow = BatchInversionOutputPanel( |
---|
428 | parent=self, output_data=self.batchResults) |
---|
429 | else: |
---|
430 | self.batchResultsWindow.setupTable(self.batchResults) |
---|
431 | self.batchResultsWindow.show() |
---|
432 | |
---|
433 | def stopCalculation(self): |
---|
434 | """ Stop all threads, return to the base state and update GUI """ |
---|
435 | self.stopCalcThread() |
---|
436 | self.stopEstimationThread() |
---|
437 | self.stopEstimateNTThread() |
---|
438 | # Show any batch calculations that successfully completed |
---|
439 | if self.isBatch and self.batchResultsWindow is not None: |
---|
440 | self.showBatchOutput() |
---|
441 | self.isBatch = False |
---|
442 | self.isCalculating = False |
---|
443 | self.updateGuiValues() |
---|
444 | |
---|
445 | ###################################################################### |
---|
446 | # Response Actions |
---|
447 | |
---|
448 | def setData(self, data_item=None, is_batch=False): |
---|
449 | """ |
---|
450 | Assign new data set(s) to the P(r) perspective |
---|
451 | Obtain a QStandardItem object and parse it to get Data1D/2D |
---|
452 | Pass it over to the calculator |
---|
453 | """ |
---|
454 | assert data_item is not None |
---|
455 | |
---|
456 | if not isinstance(data_item, list): |
---|
457 | msg = "Incorrect type passed to the P(r) Perspective" |
---|
458 | raise AttributeError(msg) |
---|
459 | |
---|
460 | for data in data_item: |
---|
461 | if data in self._dataList.keys(): |
---|
462 | # Don't add data if it's already in |
---|
463 | continue |
---|
464 | # Create initial internal mappings |
---|
465 | self.logic.data = GuiUtils.dataFromItem(data) |
---|
466 | if not isinstance(self.logic.data, Data1D): |
---|
467 | msg = "P(r) perspective cannot be computed with 2D data." |
---|
468 | logger.error(msg) |
---|
469 | raise ValueError(msg) |
---|
470 | # Estimate q range |
---|
471 | qmin, qmax = self.logic.computeDataRange() |
---|
472 | self._calculator.set_qmin(qmin) |
---|
473 | self._calculator.set_qmax(qmax) |
---|
474 | if np.size(self.logic.data.dy) == 0 or np.all(self.logic.data.dy) == 0: |
---|
475 | self.logic.data.dy = self._calculator.add_errors(self.logic.data.y) |
---|
476 | self.updateDataList(data) |
---|
477 | self.populateDataComboBox(self.logic.data.filename, data) |
---|
478 | self.dataList.setCurrentIndex(len(self.dataList) - 1) |
---|
479 | #Checking for 1D again to mitigate the case when 2D data is last on the data list |
---|
480 | if isinstance(self.logic.data, Data1D): |
---|
481 | self.setCurrentData(data) |
---|
482 | |
---|
483 | def updateDataList(self, dataRef): |
---|
484 | """Save the current data state of the window into self._data_list""" |
---|
485 | if dataRef is None: |
---|
486 | return |
---|
487 | self._dataList[dataRef] = { |
---|
488 | DICT_KEYS[0]: self._calculator, |
---|
489 | DICT_KEYS[1]: self.prPlot, |
---|
490 | DICT_KEYS[2]: self.dataPlot |
---|
491 | } |
---|
492 | # Update batch results window when finished |
---|
493 | self.batchResults[self.logic.data.filename] = self._calculator |
---|
494 | if self.batchResultsWindow is not None: |
---|
495 | self.showBatchOutput() |
---|
496 | |
---|
497 | def getNFunc(self): |
---|
498 | """Get the n_func value from the GUI object""" |
---|
499 | try: |
---|
500 | nfunc = int(self.noOfTermsInput.text()) |
---|
501 | except ValueError: |
---|
502 | logger.error("Incorrect number of terms specified: %s" |
---|
503 | %self.noOfTermsInput.text()) |
---|
504 | self.noOfTermsInput.setText(str(NUMBER_OF_TERMS)) |
---|
505 | nfunc = NUMBER_OF_TERMS |
---|
506 | return nfunc |
---|
507 | |
---|
508 | def setCurrentData(self, data_ref): |
---|
509 | """Get the data by reference and display as necessary""" |
---|
510 | if data_ref is None: |
---|
511 | return |
---|
512 | if not isinstance(data_ref, QtGui.QStandardItem): |
---|
513 | msg = "Incorrect type passed to the P(r) Perspective" |
---|
514 | raise AttributeError(msg) |
---|
515 | # Data references |
---|
516 | self._data = data_ref |
---|
517 | self.logic.data = GuiUtils.dataFromItem(data_ref) |
---|
518 | self._calculator = self._dataList[data_ref].get(DICT_KEYS[0]) |
---|
519 | self.prPlot = self._dataList[data_ref].get(DICT_KEYS[1]) |
---|
520 | self.dataPlot = self._dataList[data_ref].get(DICT_KEYS[2]) |
---|
521 | self.performEstimate() |
---|
522 | |
---|
523 | def updateDynamicGuiValues(self): |
---|
524 | pr = self._calculator |
---|
525 | alpha = self._calculator.suggested_alpha |
---|
526 | self.model.setItem(WIDGETS.W_MAX_DIST, |
---|
527 | QtGui.QStandardItem("{:.4g}".format(pr.get_dmax()))) |
---|
528 | self.regConstantSuggestionButton.setText("{:-3.2g}".format(alpha)) |
---|
529 | self.noOfTermsSuggestionButton.setText( |
---|
530 | "{:n}".format(self.nTermsSuggested)) |
---|
531 | |
---|
532 | self.enableButtons() |
---|
533 | |
---|
534 | def updateGuiValues(self): |
---|
535 | pr = self._calculator |
---|
536 | out = self._calculator.out |
---|
537 | cov = self._calculator.cov |
---|
538 | elapsed = self._calculator.elapsed |
---|
539 | alpha = self._calculator.suggested_alpha |
---|
540 | self.model.setItem(WIDGETS.W_QMIN, |
---|
541 | QtGui.QStandardItem("{:.4g}".format(pr.get_qmin()))) |
---|
542 | self.model.setItem(WIDGETS.W_QMAX, |
---|
543 | QtGui.QStandardItem("{:.4g}".format(pr.get_qmax()))) |
---|
544 | self.model.setItem(WIDGETS.W_BACKGROUND_INPUT, |
---|
545 | QtGui.QStandardItem("{:.3g}".format(pr.background))) |
---|
546 | self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, |
---|
547 | QtGui.QStandardItem("{:.3g}".format(pr.background))) |
---|
548 | self.model.setItem(WIDGETS.W_COMP_TIME, |
---|
549 | QtGui.QStandardItem("{:.4g}".format(elapsed))) |
---|
550 | self.model.setItem(WIDGETS.W_MAX_DIST, |
---|
551 | QtGui.QStandardItem("{:.4g}".format(pr.get_dmax()))) |
---|
552 | |
---|
553 | if isinstance(pr.chi2, np.ndarray): |
---|
554 | self.model.setItem(WIDGETS.W_CHI_SQUARED, |
---|
555 | QtGui.QStandardItem("{:.3g}".format(pr.chi2[0]))) |
---|
556 | if out is not None: |
---|
557 | self.model.setItem(WIDGETS.W_RG, |
---|
558 | QtGui.QStandardItem("{:.3g}".format(pr.rg(out)))) |
---|
559 | self.model.setItem(WIDGETS.W_I_ZERO, |
---|
560 | QtGui.QStandardItem( |
---|
561 | "{:.3g}".format(pr.iq0(out)))) |
---|
562 | self.model.setItem(WIDGETS.W_OSCILLATION, QtGui.QStandardItem( |
---|
563 | "{:.3g}".format(pr.oscillations(out)))) |
---|
564 | self.model.setItem(WIDGETS.W_POS_FRACTION, QtGui.QStandardItem( |
---|
565 | "{:.3g}".format(pr.get_positive(out)))) |
---|
566 | if cov is not None: |
---|
567 | self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION, |
---|
568 | QtGui.QStandardItem( |
---|
569 | "{:.3g}".format( |
---|
570 | pr.get_pos_err(out, cov)))) |
---|
571 | if self.prPlot is not None: |
---|
572 | title = self.prPlot.name |
---|
573 | self.prPlot.plot_role = Data1D.ROLE_RESIDUAL |
---|
574 | GuiUtils.updateModelItemWithPlot(self._data, self.prPlot, title) |
---|
575 | self.communicate.plotRequestedSignal.emit([self._data,self.prPlot], None) |
---|
576 | if self.dataPlot is not None: |
---|
577 | title = self.dataPlot.name |
---|
578 | self.dataPlot.plot_role = Data1D.ROLE_DEFAULT |
---|
579 | self.dataPlot.symbol = "Line" |
---|
580 | self.dataPlot.show_errors = False |
---|
581 | GuiUtils.updateModelItemWithPlot(self._data, self.dataPlot, title) |
---|
582 | self.communicate.plotRequestedSignal.emit([self._data,self.dataPlot], None) |
---|
583 | self.enableButtons() |
---|
584 | |
---|
585 | def removeData(self, data_list=None): |
---|
586 | """Remove the existing data reference from the P(r) Persepective""" |
---|
587 | self.dataDeleted = True |
---|
588 | self.batchResults = {} |
---|
589 | if not data_list: |
---|
590 | data_list = [self._data] |
---|
591 | self.closeDMax() |
---|
592 | for data in data_list: |
---|
593 | self._dataList.pop(data) |
---|
594 | self._data = None |
---|
595 | length = len(self.dataList) |
---|
596 | for index in reversed(range(length)): |
---|
597 | if self.dataList.itemData(index) in data_list: |
---|
598 | self.dataList.removeItem(index) |
---|
599 | # Last file removed |
---|
600 | self.dataDeleted = False |
---|
601 | if len(self._dataList) == 0: |
---|
602 | self.prPlot = None |
---|
603 | self.dataPlot = None |
---|
604 | self.logic.data = None |
---|
605 | self._calculator = Invertor() |
---|
606 | self.closeBatchResults() |
---|
607 | self.nTermsSuggested = NUMBER_OF_TERMS |
---|
608 | self.noOfTermsSuggestionButton.setText("{:n}".format( |
---|
609 | self.nTermsSuggested)) |
---|
610 | self.regConstantSuggestionButton.setText("{:-3.2g}".format( |
---|
611 | REGULARIZATION)) |
---|
612 | self.updateGuiValues() |
---|
613 | self.setupModel() |
---|
614 | else: |
---|
615 | self.dataList.setCurrentIndex(0) |
---|
616 | self.updateGuiValues() |
---|
617 | |
---|
618 | ###################################################################### |
---|
619 | # Thread Creators |
---|
620 | |
---|
621 | def startThreadAll(self): |
---|
622 | self.isCalculating = True |
---|
623 | self.isBatch = True |
---|
624 | self.batchComplete = [] |
---|
625 | self.calculateAllButton.setText("Calculating...") |
---|
626 | self.enableButtons() |
---|
627 | self.batchResultsWindow = BatchInversionOutputPanel( |
---|
628 | parent=self, output_data=self.batchResults) |
---|
629 | self.performEstimate() |
---|
630 | |
---|
631 | def startNextBatchItem(self): |
---|
632 | self.isBatch = False |
---|
633 | for index in range(len(self._dataList)): |
---|
634 | if index not in self.batchComplete: |
---|
635 | self.dataList.setCurrentIndex(index) |
---|
636 | self.isBatch = True |
---|
637 | # Add the index before calculating in case calculation fails |
---|
638 | self.batchComplete.append(index) |
---|
639 | break |
---|
640 | if self.isBatch: |
---|
641 | self.performEstimate() |
---|
642 | else: |
---|
643 | # If no data sets left, end batch calculation |
---|
644 | self.isCalculating = False |
---|
645 | self.batchComplete = [] |
---|
646 | self.calculateAllButton.setText("Calculate All") |
---|
647 | self.showBatchOutput() |
---|
648 | self.enableButtons() |
---|
649 | |
---|
650 | def startThread(self): |
---|
651 | """ |
---|
652 | Start a calculation thread |
---|
653 | """ |
---|
654 | from .Thread import CalcPr |
---|
655 | |
---|
656 | # Set data before running the calculations |
---|
657 | self.isCalculating = True |
---|
658 | self.enableButtons() |
---|
659 | self.updateCalculator() |
---|
660 | # Disable calculation buttons to prevent thread interference |
---|
661 | |
---|
662 | # If the thread is already started, stop it |
---|
663 | self.stopCalcThread() |
---|
664 | |
---|
665 | pr = self._calculator.clone() |
---|
666 | #Making sure that nfunc and alpha parameters are correctly initialized |
---|
667 | pr.suggested_alpha = self._calculator.alpha |
---|
668 | self.calcThread = CalcPr(pr, self.nTermsSuggested, |
---|
669 | error_func=self._threadError, |
---|
670 | completefn=self._calculateCompleted, |
---|
671 | updatefn=None) |
---|
672 | self.calcThread.queue() |
---|
673 | self.calcThread.ready(2.5) |
---|
674 | |
---|
675 | def stopCalcThread(self): |
---|
676 | """ Stops a thread if it exists and is running """ |
---|
677 | if self.calcThread is not None and self.calcThread.isrunning(): |
---|
678 | self.calcThread.stop() |
---|
679 | |
---|
680 | def performEstimateNT(self): |
---|
681 | """ |
---|
682 | Perform parameter estimation |
---|
683 | """ |
---|
684 | from .Thread import EstimateNT |
---|
685 | |
---|
686 | self.updateCalculator() |
---|
687 | |
---|
688 | # If a thread is already started, stop it |
---|
689 | self.stopEstimateNTThread() |
---|
690 | |
---|
691 | pr = self._calculator.clone() |
---|
692 | # Skip the slit settings for the estimation |
---|
693 | # It slows down the application and it doesn't change the estimates |
---|
694 | pr.slit_height = 0.0 |
---|
695 | pr.slit_width = 0.0 |
---|
696 | nfunc = self.getNFunc() |
---|
697 | |
---|
698 | self.estimationThreadNT = EstimateNT(pr, nfunc, |
---|
699 | error_func=self._threadError, |
---|
700 | completefn=self._estimateNTCompleted, |
---|
701 | updatefn=None) |
---|
702 | self.estimationThreadNT.queue() |
---|
703 | self.estimationThreadNT.ready(2.5) |
---|
704 | |
---|
705 | def performEstimateDynamicNT(self): |
---|
706 | """ |
---|
707 | Perform parameter estimation |
---|
708 | """ |
---|
709 | from .Thread import EstimateNT |
---|
710 | |
---|
711 | self.updateCalculator() |
---|
712 | |
---|
713 | # If a thread is already started, stop it |
---|
714 | self.stopEstimateNTThread() |
---|
715 | |
---|
716 | pr = self._calculator.clone() |
---|
717 | # Skip the slit settings for the estimation |
---|
718 | # It slows down the application and it doesn't change the estimates |
---|
719 | pr.slit_height = 0.0 |
---|
720 | pr.slit_width = 0.0 |
---|
721 | nfunc = self.getNFunc() |
---|
722 | |
---|
723 | self.estimationThreadNT = EstimateNT(pr, nfunc, |
---|
724 | error_func=self._threadError, |
---|
725 | completefn=self._estimateDynamicNTCompleted, |
---|
726 | updatefn=None) |
---|
727 | self.estimationThreadNT.queue() |
---|
728 | self.estimationThreadNT.ready(2.5) |
---|
729 | |
---|
730 | def stopEstimateNTThread(self): |
---|
731 | if (self.estimationThreadNT is not None and |
---|
732 | self.estimationThreadNT.isrunning()): |
---|
733 | self.estimationThreadNT.stop() |
---|
734 | |
---|
735 | def performEstimate(self): |
---|
736 | """ |
---|
737 | Perform parameter estimation |
---|
738 | """ |
---|
739 | from .Thread import EstimatePr |
---|
740 | |
---|
741 | # If a thread is already started, stop it |
---|
742 | self.stopEstimationThread() |
---|
743 | |
---|
744 | self.estimationThread = EstimatePr(self._calculator.clone(), |
---|
745 | self.getNFunc(), |
---|
746 | error_func=self._threadError, |
---|
747 | completefn=self._estimateCompleted, |
---|
748 | updatefn=None) |
---|
749 | self.estimationThread.queue() |
---|
750 | self.estimationThread.ready(2.5) |
---|
751 | |
---|
752 | def performEstimateDynamic(self): |
---|
753 | """ |
---|
754 | Perform parameter estimation |
---|
755 | """ |
---|
756 | from .Thread import EstimatePr |
---|
757 | |
---|
758 | # If a thread is already started, stop it |
---|
759 | self.stopEstimationThread() |
---|
760 | |
---|
761 | self.estimationThread = EstimatePr(self._calculator.clone(), |
---|
762 | self.getNFunc(), |
---|
763 | error_func=self._threadError, |
---|
764 | completefn=self._estimateDynamicCompleted, |
---|
765 | updatefn=None) |
---|
766 | self.estimationThread.queue() |
---|
767 | self.estimationThread.ready(2.5) |
---|
768 | |
---|
769 | def stopEstimationThread(self): |
---|
770 | """ Stop the estimation thread if it exists and is running """ |
---|
771 | if (self.estimationThread is not None and |
---|
772 | self.estimationThread.isrunning()): |
---|
773 | self.estimationThread.stop() |
---|
774 | |
---|
775 | ###################################################################### |
---|
776 | # Thread Complete |
---|
777 | |
---|
778 | def _estimateCompleted(self, alpha, message, elapsed): |
---|
779 | ''' Send a signal to the main thread for model update''' |
---|
780 | self.estimateSignal.emit((alpha, message, elapsed)) |
---|
781 | |
---|
782 | def _estimateDynamicCompleted(self, alpha, message, elapsed): |
---|
783 | ''' Send a signal to the main thread for model update''' |
---|
784 | self.estimateDynamicSignal.emit((alpha, message, elapsed)) |
---|
785 | |
---|
786 | def _estimateUpdate(self, output_tuple): |
---|
787 | """ |
---|
788 | Parameter estimation completed, |
---|
789 | display the results to the user |
---|
790 | |
---|
791 | :param alpha: estimated best alpha |
---|
792 | :param elapsed: computation time |
---|
793 | """ |
---|
794 | alpha, message, elapsed = output_tuple |
---|
795 | self._calculator.alpha = alpha |
---|
796 | self._calculator.elapsed += self._calculator.elapsed |
---|
797 | if message: |
---|
798 | logger.info(message) |
---|
799 | self.performEstimateNT() |
---|
800 | self.performEstimateDynamicNT() |
---|
801 | |
---|
802 | def _estimateDynamicUpdate(self, output_tuple): |
---|
803 | """ |
---|
804 | Parameter estimation completed, |
---|
805 | display the results to the user |
---|
806 | |
---|
807 | :param alpha: estimated best alpha |
---|
808 | :param elapsed: computation time |
---|
809 | """ |
---|
810 | alpha, message, elapsed = output_tuple |
---|
811 | self._calculator.alpha = alpha |
---|
812 | self._calculator.elapsed += self._calculator.elapsed |
---|
813 | if message: |
---|
814 | logger.info(message) |
---|
815 | self.performEstimateDynamicNT() |
---|
816 | |
---|
817 | def _estimateNTCompleted(self, nterms, alpha, message, elapsed): |
---|
818 | ''' Send a signal to the main thread for model update''' |
---|
819 | self.estimateNTSignal.emit((nterms, alpha, message, elapsed)) |
---|
820 | |
---|
821 | def _estimateDynamicNTCompleted(self, nterms, alpha, message, elapsed): |
---|
822 | ''' Send a signal to the main thread for model update''' |
---|
823 | self.estimateDynamicNTSignal.emit((nterms, alpha, message, elapsed)) |
---|
824 | |
---|
825 | def _estimateNTUpdate(self, output_tuple): |
---|
826 | """ |
---|
827 | Parameter estimation completed, |
---|
828 | display the results to the user |
---|
829 | |
---|
830 | :param alpha: estimated best alpha |
---|
831 | :param nterms: estimated number of terms |
---|
832 | :param elapsed: computation time |
---|
833 | """ |
---|
834 | nterms, alpha, message, elapsed = output_tuple |
---|
835 | self._calculator.elapsed += elapsed |
---|
836 | self._calculator.suggested_alpha = alpha |
---|
837 | self.nTermsSuggested = nterms |
---|
838 | # Save useful info |
---|
839 | self.updateGuiValues() |
---|
840 | if message: |
---|
841 | logger.info(message) |
---|
842 | if self.isBatch: |
---|
843 | self.acceptAlpha() |
---|
844 | self.acceptNoTerms() |
---|
845 | self.startThread() |
---|
846 | |
---|
847 | def _estimateDynamicNTUpdate(self, output_tuple): |
---|
848 | """ |
---|
849 | Parameter estimation completed, |
---|
850 | display the results to the user |
---|
851 | |
---|
852 | :param alpha: estimated best alpha |
---|
853 | :param nterms: estimated number of terms |
---|
854 | :param elapsed: computation time |
---|
855 | """ |
---|
856 | nterms, alpha, message, elapsed = output_tuple |
---|
857 | self._calculator.elapsed += elapsed |
---|
858 | self._calculator.suggested_alpha = alpha |
---|
859 | self.nTermsSuggested = nterms |
---|
860 | # Save useful info |
---|
861 | self.updateDynamicGuiValues() |
---|
862 | if message: |
---|
863 | logger.info(message) |
---|
864 | if self.isBatch: |
---|
865 | self.acceptAlpha() |
---|
866 | self.acceptNoTerms() |
---|
867 | self.startThread() |
---|
868 | |
---|
869 | def _calculateCompleted(self, out, cov, pr, elapsed): |
---|
870 | ''' Send a signal to the main thread for model update''' |
---|
871 | self.calculateSignal.emit((out, cov, pr, elapsed)) |
---|
872 | |
---|
873 | def _calculateUpdate(self, output_tuple): |
---|
874 | """ |
---|
875 | Method called with the results when the inversion is done |
---|
876 | |
---|
877 | :param out: output coefficient for the base functions |
---|
878 | :param cov: covariance matrix |
---|
879 | :param pr: Invertor instance |
---|
880 | :param elapsed: time spent computing |
---|
881 | """ |
---|
882 | out, cov, pr, elapsed = output_tuple |
---|
883 | # Save useful info |
---|
884 | cov = np.ascontiguousarray(cov) |
---|
885 | pr.cov = cov |
---|
886 | pr.out = out |
---|
887 | pr.elapsed = elapsed |
---|
888 | |
---|
889 | # Save Pr invertor |
---|
890 | self._calculator = pr |
---|
891 | |
---|
892 | # Update P(r) and fit plots |
---|
893 | self.prPlot = self.logic.newPRPlot(out, self._calculator, cov) |
---|
894 | self.prPlot.filename = self.logic.data.filename |
---|
895 | self.dataPlot = self.logic.new1DPlot(out, self._calculator) |
---|
896 | self.dataPlot.filename = self.logic.data.filename |
---|
897 | |
---|
898 | # Udpate internals and GUI |
---|
899 | self.updateDataList(self._data) |
---|
900 | if self.isBatch: |
---|
901 | self.batchComplete.append(self.dataList.currentIndex()) |
---|
902 | self.startNextBatchItem() |
---|
903 | else: |
---|
904 | self.isCalculating = False |
---|
905 | self.updateGuiValues() |
---|
906 | |
---|
907 | def _threadError(self, error): |
---|
908 | """ |
---|
909 | Call-back method for calculation errors |
---|
910 | """ |
---|
911 | logger.error(error) |
---|
912 | if self.isBatch: |
---|
913 | self.startNextBatchItem() |
---|
914 | else: |
---|
915 | self.stopCalculation() |
---|