1 | import sys |
---|
2 | import logging |
---|
3 | import pylab |
---|
4 | import numpy as np |
---|
5 | |
---|
6 | from PyQt5 import QtGui, QtCore, QtWidgets |
---|
7 | |
---|
8 | # sas-global |
---|
9 | import sas.qtgui.Utilities.GuiUtils as GuiUtils |
---|
10 | |
---|
11 | # pr inversion GUI elements |
---|
12 | from .InversionUtils import WIDGETS |
---|
13 | from .UI.TabbedInversionUI import Ui_PrInversion |
---|
14 | from .InversionLogic import InversionLogic |
---|
15 | |
---|
16 | # pr inversion calculation elements |
---|
17 | from sas.sascalc.pr.invertor import Invertor |
---|
18 | |
---|
19 | def is_float(value): |
---|
20 | """Converts text input values to floats. Empty strings throw ValueError""" |
---|
21 | try: |
---|
22 | return float(value) |
---|
23 | except ValueError: |
---|
24 | return 0.0 |
---|
25 | |
---|
26 | NUMBER_OF_TERMS = 10 |
---|
27 | REGULARIZATION = 0.0001 |
---|
28 | BACKGROUND_INPUT = 0.0 |
---|
29 | MAX_DIST = 140.0 |
---|
30 | DICT_KEYS = ["Calculator", "PrPlot", "DataPlot", "DMaxWindow", "NFuncEst"] |
---|
31 | |
---|
32 | |
---|
33 | # TODO: Explore window not working |
---|
34 | # TODO: Update help with batch capabilities |
---|
35 | # TODO: Method to export results in some meaningful way |
---|
36 | class InversionWindow(QtWidgets.QDialog, Ui_PrInversion): |
---|
37 | """ |
---|
38 | The main window for the P(r) Inversion perspective. |
---|
39 | """ |
---|
40 | |
---|
41 | name = "Inversion" |
---|
42 | estimateSignal = QtCore.pyqtSignal(tuple) |
---|
43 | estimateNTSignal = QtCore.pyqtSignal(tuple) |
---|
44 | calculateSignal = QtCore.pyqtSignal(tuple) |
---|
45 | |
---|
46 | def __init__(self, parent=None, data=None): |
---|
47 | super(InversionWindow, self).__init__() |
---|
48 | self.setupUi(self) |
---|
49 | |
---|
50 | self.setWindowTitle("P(r) Inversion Perspective") |
---|
51 | |
---|
52 | self._manager = parent |
---|
53 | self.communicate = GuiUtils.Communicate() |
---|
54 | |
---|
55 | self.logic = InversionLogic() |
---|
56 | |
---|
57 | # The window should not close |
---|
58 | self._allow_close = False |
---|
59 | |
---|
60 | # Visible data set items |
---|
61 | # current QStandardItem showing on the panel |
---|
62 | self._data = None |
---|
63 | # current Data1D as referenced by self._data |
---|
64 | self._data_set = None |
---|
65 | # Reference to Dmax window for self._data |
---|
66 | self.dmaxWindow = None |
---|
67 | # p(r) calculator for self._data |
---|
68 | self._calculator = Invertor() |
---|
69 | # Default to background estimate |
---|
70 | self._calculator.set_est_bck(True) |
---|
71 | # plots of self._data |
---|
72 | self.pr_plot = None |
---|
73 | self.data_plot = None |
---|
74 | # suggested nTerms |
---|
75 | self.nTermsSuggested = NUMBER_OF_TERMS |
---|
76 | |
---|
77 | # Calculation threads used by all data items |
---|
78 | self.calc_thread = None |
---|
79 | self.estimation_thread = None |
---|
80 | |
---|
81 | # Mapping for all data items |
---|
82 | # list mapping data to all parameters |
---|
83 | self._data_list = {} |
---|
84 | if not isinstance(data, list): |
---|
85 | data_list = [data] |
---|
86 | if data is not None: |
---|
87 | for datum in data_list: |
---|
88 | self.updateDataList(datum) |
---|
89 | |
---|
90 | self.enableButtons() |
---|
91 | |
---|
92 | self.model = QtGui.QStandardItemModel(self) |
---|
93 | self.mapper = QtWidgets.QDataWidgetMapper(self) |
---|
94 | |
---|
95 | # Add validators |
---|
96 | self.setupValidators() |
---|
97 | # Link user interactions with methods |
---|
98 | self.setupLinks() |
---|
99 | # Set values |
---|
100 | self.setupModel() |
---|
101 | # Set up the Widget Map |
---|
102 | self.setupMapper() |
---|
103 | # Set base window state |
---|
104 | self.setupWindow() |
---|
105 | |
---|
106 | ###################################################################### |
---|
107 | # Base Perspective Class Definitions |
---|
108 | |
---|
109 | def communicator(self): |
---|
110 | return self.communicate |
---|
111 | |
---|
112 | def allowBatch(self): |
---|
113 | return True |
---|
114 | |
---|
115 | def setClosable(self, value=True): |
---|
116 | """ |
---|
117 | Allow outsiders close this widget |
---|
118 | """ |
---|
119 | assert isinstance(value, bool) |
---|
120 | self._allow_close = value |
---|
121 | |
---|
122 | def closeEvent(self, event): |
---|
123 | """ |
---|
124 | Overwrite QDialog close method to allow for custom widget close |
---|
125 | """ |
---|
126 | if self._allow_close: |
---|
127 | # reset the closability flag |
---|
128 | self.setClosable(value=False) |
---|
129 | # Tell the MdiArea to close the container |
---|
130 | self.parentWidget().close() |
---|
131 | event.accept() |
---|
132 | else: |
---|
133 | event.ignore() |
---|
134 | # Maybe we should just minimize |
---|
135 | self.setWindowState(QtCore.Qt.WindowMinimized) |
---|
136 | |
---|
137 | ###################################################################### |
---|
138 | # Initialization routines |
---|
139 | |
---|
140 | def setupLinks(self): |
---|
141 | """Connect the use controls to their appropriate methods""" |
---|
142 | self.dataList.currentIndexChanged.connect(self.displayChange) |
---|
143 | self.calculateAllButton.clicked.connect(self.startThreadAll) |
---|
144 | self.calculateThisButton.clicked.connect(self.startThread) |
---|
145 | self.removeButton.clicked.connect(self.removeData) |
---|
146 | self.helpButton.clicked.connect(self.help) |
---|
147 | self.estimateBgd.toggled.connect(self.toggleBgd) |
---|
148 | self.manualBgd.toggled.connect(self.toggleBgd) |
---|
149 | self.regConstantSuggestionButton.clicked.connect(self.acceptAlpha) |
---|
150 | self.noOfTermsSuggestionButton.clicked.connect(self.acceptNoTerms) |
---|
151 | self.explorerButton.clicked.connect(self.openExplorerWindow) |
---|
152 | |
---|
153 | self.backgroundInput.editingFinished.connect( |
---|
154 | lambda: self._calculator.set_background(is_float(self.backgroundInput.text()))) |
---|
155 | self.minQInput.editingFinished.connect( |
---|
156 | lambda: self._calculator.set_qmin(is_float(self.minQInput.text()))) |
---|
157 | self.regularizationConstantInput.editingFinished.connect( |
---|
158 | lambda: self._calculator.set_alpha(is_float(self.regularizationConstantInput.text()))) |
---|
159 | self.maxDistanceInput.editingFinished.connect( |
---|
160 | lambda: self._calculator.set_dmax(is_float(self.maxDistanceInput.text()))) |
---|
161 | self.maxQInput.editingFinished.connect( |
---|
162 | lambda: self._calculator.set_qmax(is_float(self.maxQInput.text()))) |
---|
163 | self.slitHeightInput.editingFinished.connect( |
---|
164 | lambda: self._calculator.set_slit_height(is_float(self.slitHeightInput.text()))) |
---|
165 | self.slitWidthInput.editingFinished.connect( |
---|
166 | lambda: self._calculator.set_slit_width(is_float(self.slitHeightInput.text()))) |
---|
167 | |
---|
168 | self.model.itemChanged.connect(self.model_changed) |
---|
169 | self.estimateNTSignal.connect(self._estimateNTUpdate) |
---|
170 | self.estimateSignal.connect(self._estimateUpdate) |
---|
171 | self.calculateSignal.connect(self._calculateUpdate) |
---|
172 | |
---|
173 | def setupMapper(self): |
---|
174 | # Set up the mapper. |
---|
175 | self.mapper.setOrientation(QtCore.Qt.Vertical) |
---|
176 | self.mapper.setModel(self.model) |
---|
177 | |
---|
178 | # Filename |
---|
179 | self.mapper.addMapping(self.dataList, WIDGETS.W_FILENAME) |
---|
180 | # Background |
---|
181 | self.mapper.addMapping(self.backgroundInput, WIDGETS.W_BACKGROUND_INPUT) |
---|
182 | self.mapper.addMapping(self.estimateBgd, WIDGETS.W_ESTIMATE) |
---|
183 | self.mapper.addMapping(self.manualBgd, WIDGETS.W_MANUAL_INPUT) |
---|
184 | |
---|
185 | # Qmin/Qmax |
---|
186 | self.mapper.addMapping(self.minQInput, WIDGETS.W_QMIN) |
---|
187 | self.mapper.addMapping(self.maxQInput, WIDGETS.W_QMAX) |
---|
188 | |
---|
189 | # Slit Parameter items |
---|
190 | self.mapper.addMapping(self.slitWidthInput, WIDGETS.W_SLIT_WIDTH) |
---|
191 | self.mapper.addMapping(self.slitHeightInput, WIDGETS.W_SLIT_HEIGHT) |
---|
192 | |
---|
193 | # Parameter Items |
---|
194 | self.mapper.addMapping(self.regularizationConstantInput, WIDGETS.W_REGULARIZATION) |
---|
195 | self.mapper.addMapping(self.regConstantSuggestionButton, WIDGETS.W_REGULARIZATION_SUGGEST) |
---|
196 | self.mapper.addMapping(self.explorerButton, WIDGETS.W_EXPLORE) |
---|
197 | self.mapper.addMapping(self.maxDistanceInput, WIDGETS.W_MAX_DIST) |
---|
198 | self.mapper.addMapping(self.noOfTermsInput, WIDGETS.W_NO_TERMS) |
---|
199 | self.mapper.addMapping(self.noOfTermsSuggestionButton, WIDGETS.W_NO_TERMS_SUGGEST) |
---|
200 | |
---|
201 | # Output |
---|
202 | self.mapper.addMapping(self.rgValue, WIDGETS.W_RG) |
---|
203 | self.mapper.addMapping(self.iQ0Value, WIDGETS.W_I_ZERO) |
---|
204 | self.mapper.addMapping(self.backgroundValue, WIDGETS.W_BACKGROUND_OUTPUT) |
---|
205 | self.mapper.addMapping(self.computationTimeValue, WIDGETS.W_COMP_TIME) |
---|
206 | self.mapper.addMapping(self.chiDofValue, WIDGETS.W_CHI_SQUARED) |
---|
207 | self.mapper.addMapping(self.oscillationValue, WIDGETS.W_OSCILLATION) |
---|
208 | self.mapper.addMapping(self.posFractionValue, WIDGETS.W_POS_FRACTION) |
---|
209 | self.mapper.addMapping(self.sigmaPosFractionValue, WIDGETS.W_SIGMA_POS_FRACTION) |
---|
210 | |
---|
211 | # Main Buttons |
---|
212 | self.mapper.addMapping(self.removeButton, WIDGETS.W_REMOVE) |
---|
213 | self.mapper.addMapping(self.calculateAllButton, WIDGETS.W_CALCULATE_ALL) |
---|
214 | self.mapper.addMapping(self.calculateThisButton, WIDGETS.W_CALCULATE_VISIBLE) |
---|
215 | self.mapper.addMapping(self.helpButton, WIDGETS.W_HELP) |
---|
216 | |
---|
217 | self.mapper.toFirst() |
---|
218 | |
---|
219 | def setupModel(self): |
---|
220 | """ |
---|
221 | Update boxes with initial values |
---|
222 | """ |
---|
223 | item = QtGui.QStandardItem("") |
---|
224 | self.model.setItem(WIDGETS.W_FILENAME, item) |
---|
225 | item = QtGui.QStandardItem(str(BACKGROUND_INPUT)) |
---|
226 | self.model.setItem(WIDGETS.W_BACKGROUND_INPUT, item) |
---|
227 | item = QtGui.QStandardItem("") |
---|
228 | self.model.setItem(WIDGETS.W_QMIN, item) |
---|
229 | item = QtGui.QStandardItem("") |
---|
230 | self.model.setItem(WIDGETS.W_QMAX, item) |
---|
231 | item = QtGui.QStandardItem("") |
---|
232 | self.model.setItem(WIDGETS.W_SLIT_WIDTH, item) |
---|
233 | item = QtGui.QStandardItem("") |
---|
234 | self.model.setItem(WIDGETS.W_SLIT_HEIGHT, item) |
---|
235 | item = QtGui.QStandardItem(str(NUMBER_OF_TERMS)) |
---|
236 | self.model.setItem(WIDGETS.W_NO_TERMS, item) |
---|
237 | item = QtGui.QStandardItem(str(REGULARIZATION)) |
---|
238 | self.model.setItem(WIDGETS.W_REGULARIZATION, item) |
---|
239 | item = QtGui.QStandardItem(str(MAX_DIST)) |
---|
240 | self.model.setItem(WIDGETS.W_MAX_DIST, item) |
---|
241 | item = QtGui.QStandardItem("") |
---|
242 | self.model.setItem(WIDGETS.W_RG, item) |
---|
243 | item = QtGui.QStandardItem("") |
---|
244 | self.model.setItem(WIDGETS.W_I_ZERO, item) |
---|
245 | item = QtGui.QStandardItem("") |
---|
246 | self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, item) |
---|
247 | item = QtGui.QStandardItem("") |
---|
248 | self.model.setItem(WIDGETS.W_COMP_TIME, item) |
---|
249 | item = QtGui.QStandardItem("") |
---|
250 | self.model.setItem(WIDGETS.W_CHI_SQUARED, item) |
---|
251 | item = QtGui.QStandardItem("") |
---|
252 | self.model.setItem(WIDGETS.W_OSCILLATION, item) |
---|
253 | item = QtGui.QStandardItem("") |
---|
254 | self.model.setItem(WIDGETS.W_POS_FRACTION, item) |
---|
255 | item = QtGui.QStandardItem("") |
---|
256 | self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION, item) |
---|
257 | |
---|
258 | def setupWindow(self): |
---|
259 | """Initialize base window state on init""" |
---|
260 | self.enableButtons() |
---|
261 | self.estimateBgd.setChecked(True) |
---|
262 | |
---|
263 | def setupValidators(self): |
---|
264 | """Apply validators to editable line edits""" |
---|
265 | self.noOfTermsInput.setValidator(QtGui.QIntValidator()) |
---|
266 | self.regularizationConstantInput.setValidator(GuiUtils.DoubleValidator()) |
---|
267 | self.maxDistanceInput.setValidator(GuiUtils.DoubleValidator()) |
---|
268 | self.minQInput.setValidator(GuiUtils.DoubleValidator()) |
---|
269 | self.maxQInput.setValidator(GuiUtils.DoubleValidator()) |
---|
270 | self.slitHeightInput.setValidator(GuiUtils.DoubleValidator()) |
---|
271 | self.slitWidthInput.setValidator(GuiUtils.DoubleValidator()) |
---|
272 | |
---|
273 | ###################################################################### |
---|
274 | # Methods for updating GUI |
---|
275 | |
---|
276 | def enableButtons(self): |
---|
277 | """ |
---|
278 | Enable buttons when data is present, else disable them |
---|
279 | """ |
---|
280 | self.calculateAllButton.setEnabled(self.logic.data_is_loaded) |
---|
281 | self.calculateThisButton.setEnabled(self.logic.data_is_loaded) |
---|
282 | self.removeButton.setEnabled(self.logic.data_is_loaded) |
---|
283 | self.explorerButton.setEnabled(self.logic.data_is_loaded) |
---|
284 | |
---|
285 | def populateDataComboBox(self, filename, data_ref): |
---|
286 | """ |
---|
287 | Append a new file name to the data combobox |
---|
288 | :param filename: data filename |
---|
289 | :param data_ref: QStandardItem reference for data set to be added |
---|
290 | """ |
---|
291 | self.dataList.addItem(filename, data_ref) |
---|
292 | |
---|
293 | def acceptNoTerms(self): |
---|
294 | """Send estimated no of terms to input""" |
---|
295 | self.model.setItem(WIDGETS.W_NO_TERMS, QtGui.QStandardItem( |
---|
296 | self.noOfTermsSuggestionButton.text())) |
---|
297 | |
---|
298 | def acceptAlpha(self): |
---|
299 | """Send estimated alpha to input""" |
---|
300 | self.model.setItem(WIDGETS.W_REGULARIZATION, QtGui.QStandardItem( |
---|
301 | self.regConstantSuggestionButton.text())) |
---|
302 | |
---|
303 | def displayChange(self): |
---|
304 | """Switch to another item in the data list""" |
---|
305 | ref_item = self.dataList.itemData(self.dataList.currentIndex()) |
---|
306 | self.updateDataList(ref_item) |
---|
307 | self.setCurrentData(ref_item) |
---|
308 | |
---|
309 | ###################################################################### |
---|
310 | # GUI Interaction Events |
---|
311 | |
---|
312 | def update_calculator(self): |
---|
313 | """Update all p(r) params""" |
---|
314 | self._calculator.set_x(self._data_set.x) |
---|
315 | self._calculator.set_y(self._data_set.y) |
---|
316 | self._calculator.set_err(self._data_set.dy) |
---|
317 | |
---|
318 | def model_changed(self): |
---|
319 | """Update the values when user makes changes""" |
---|
320 | if not self.mapper: |
---|
321 | msg = "Unable to update P{r}. The connection between the main GUI " |
---|
322 | msg += "and P(r) was severed. Attempting to restart P(r)." |
---|
323 | logging.warning(msg) |
---|
324 | self.setClosable(True) |
---|
325 | self.close() |
---|
326 | InversionWindow.__init__(self.parent(), list(self._data_list.keys())) |
---|
327 | exit(0) |
---|
328 | if self.pr_plot is not None: |
---|
329 | title = self.pr_plot.name |
---|
330 | GuiUtils.updateModelItemWithPlot(self._data, self.pr_plot, title) |
---|
331 | if self.data_plot is not None: |
---|
332 | title = self.data_plot.name |
---|
333 | GuiUtils.updateModelItemWithPlot(self._data, self.data_plot, title) |
---|
334 | if self.dmaxWindow is not None: |
---|
335 | self.dmaxWindow.pr_state = self._calculator |
---|
336 | self.dmaxWindow.nfunc = self.getNFunc() |
---|
337 | self.dmaxWindow.modelChanged() |
---|
338 | self.mapper.toFirst() |
---|
339 | |
---|
340 | def help(self): |
---|
341 | """ |
---|
342 | Open the P(r) Inversion help browser |
---|
343 | """ |
---|
344 | tree_location = "/user/sasgui/perspectives/pr/pr_help.html" |
---|
345 | |
---|
346 | # Actual file anchor will depend on the combo box index |
---|
347 | # Note that we can be clusmy here, since bad current_fitter_id |
---|
348 | # will just make the page displayed from the top |
---|
349 | self._manager.showHelp(tree_location) |
---|
350 | |
---|
351 | def toggleBgd(self): |
---|
352 | """ |
---|
353 | Toggle the background between manual and estimated |
---|
354 | """ |
---|
355 | sender = self.sender() |
---|
356 | if sender is self.estimateBgd: |
---|
357 | self.backgroundInput.setEnabled(False) |
---|
358 | self._calculator.set_est_bck = True |
---|
359 | else: |
---|
360 | self.backgroundInput.setEnabled(True) |
---|
361 | self._calculator.set_est_bck = False |
---|
362 | |
---|
363 | def openExplorerWindow(self): |
---|
364 | """ |
---|
365 | Open the Explorer window to see correlations between params and results |
---|
366 | """ |
---|
367 | from .DMaxExplorerWidget import DmaxWindow |
---|
368 | self.dmaxWindow = DmaxWindow(self._calculator, self.getNFunc(), self) |
---|
369 | self.dmaxWindow.show() |
---|
370 | |
---|
371 | ###################################################################### |
---|
372 | # Response Actions |
---|
373 | |
---|
374 | def setData(self, data_item=None, is_batch=False): |
---|
375 | """ |
---|
376 | Assign new data set(s) to the P(r) perspective |
---|
377 | Obtain a QStandardItem object and parse it to get Data1D/2D |
---|
378 | Pass it over to the calculator |
---|
379 | """ |
---|
380 | assert data_item is not None |
---|
381 | |
---|
382 | if not isinstance(data_item, list): |
---|
383 | msg = "Incorrect type passed to the P(r) Perspective" |
---|
384 | raise AttributeError(msg) |
---|
385 | |
---|
386 | for data in data_item: |
---|
387 | if data in self._data_list.keys(): |
---|
388 | # Don't add data if it's already in |
---|
389 | return |
---|
390 | # Create initial internal mappings |
---|
391 | self._data_set = GuiUtils.dataFromItem(data) |
---|
392 | self.logic = InversionLogic(self._data_set) |
---|
393 | self.populateDataComboBox(self._data_set.filename, data) |
---|
394 | # Estimate q range |
---|
395 | qmin, qmax = self.logic.computeDataRange() |
---|
396 | self._calculator.set_qmin(qmin) |
---|
397 | self._calculator.set_qmax(qmax) |
---|
398 | self.updateDataList(data) |
---|
399 | self.setCurrentData(data) |
---|
400 | # Estimate initial values from data |
---|
401 | self.performEstimate() |
---|
402 | self.enableButtons() |
---|
403 | self.updateGuiValues() |
---|
404 | |
---|
405 | def updateDataList(self, dataRef): |
---|
406 | """Save the current data state of the window into self._data_list""" |
---|
407 | if dataRef is None: |
---|
408 | return |
---|
409 | self._data_list[dataRef] = { |
---|
410 | DICT_KEYS[0]: self._calculator, |
---|
411 | DICT_KEYS[1]: self.pr_plot, |
---|
412 | DICT_KEYS[2]: self.data_plot, |
---|
413 | DICT_KEYS[3]: self.dmaxWindow, |
---|
414 | DICT_KEYS[4]: self.nTermsSuggested |
---|
415 | } |
---|
416 | |
---|
417 | def getNFunc(self): |
---|
418 | """Get the n_func value from the GUI object""" |
---|
419 | try: |
---|
420 | nfunc = int(self.noOfTermsInput.text()) |
---|
421 | except ValueError: |
---|
422 | logging.error("Incorrect number of terms specified: %s" %self.noOfTermsInput.text()) |
---|
423 | self.noOfTermsInput.setText(str(NUMBER_OF_TERMS)) |
---|
424 | nfunc = NUMBER_OF_TERMS |
---|
425 | return nfunc |
---|
426 | |
---|
427 | def setCurrentData(self, data_ref): |
---|
428 | """Get the data by reference and display as necessary""" |
---|
429 | if data_ref is None: |
---|
430 | return |
---|
431 | if not isinstance(data_ref, QtGui.QStandardItem): |
---|
432 | msg = "Incorrect type passed to the P(r) Perspective" |
---|
433 | raise AttributeError(msg) |
---|
434 | # Data references |
---|
435 | self._data = data_ref |
---|
436 | self._data_set = GuiUtils.dataFromItem(data_ref) |
---|
437 | self._calculator = self._data_list[data_ref].get(DICT_KEYS[0]) |
---|
438 | self.pr_plot = self._data_list[data_ref].get(DICT_KEYS[1]) |
---|
439 | self.data_plot = self._data_list[data_ref].get(DICT_KEYS[2]) |
---|
440 | self.dmaxWindow = self._data_list[data_ref].get(DICT_KEYS[3]) |
---|
441 | self.nTermsSuggested = self._data_list[data_ref].get(DICT_KEYS[4]) |
---|
442 | self.logic.set_data = self._data_set |
---|
443 | self.updateGuiValues() |
---|
444 | |
---|
445 | def updateGuiValues(self): |
---|
446 | pr = self._calculator |
---|
447 | out = self._calculator.out |
---|
448 | cov = self._calculator.cov |
---|
449 | elapsed = self._calculator.elapsed |
---|
450 | alpha = self._calculator.suggested_alpha |
---|
451 | nterms = self._calculator.nfunc |
---|
452 | self.model.setItem(WIDGETS.W_QMIN, |
---|
453 | QtGui.QStandardItem("{:.4g}".format(pr.get_qmin()))) |
---|
454 | self.model.setItem(WIDGETS.W_QMAX, |
---|
455 | QtGui.QStandardItem("{:.4g}".format(pr.get_qmax()))) |
---|
456 | self.model.setItem(WIDGETS.W_BACKGROUND_INPUT, |
---|
457 | QtGui.QStandardItem("{:.3f}".format(pr.background))) |
---|
458 | self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, |
---|
459 | QtGui.QStandardItem("{:.3g}".format(pr.background))) |
---|
460 | self.model.setItem(WIDGETS.W_COMP_TIME, |
---|
461 | QtGui.QStandardItem("{:.4g}".format(elapsed))) |
---|
462 | if alpha != 0: |
---|
463 | self.regConstantSuggestionButton.setText("{:-3.2g}".format(alpha)) |
---|
464 | self.regConstantSuggestionButton.setEnabled(alpha != self._calculator.alpha) |
---|
465 | if nterms != self.nTermsSuggested: |
---|
466 | self.noOfTermsSuggestionButton.setText( |
---|
467 | "{:n}".format(self.nTermsSuggested)) |
---|
468 | self.noOfTermsSuggestionButton.setEnabled(nterms != self.nTermsSuggested) |
---|
469 | self.model.setItem(WIDGETS.W_COMP_TIME, |
---|
470 | QtGui.QStandardItem("{:.2g}".format(elapsed))) |
---|
471 | |
---|
472 | if isinstance(pr.chi2, np.ndarray): |
---|
473 | self.model.setItem(WIDGETS.W_CHI_SQUARED, |
---|
474 | QtGui.QStandardItem("{:.3g}".format(pr.chi2[0]))) |
---|
475 | if out is not None: |
---|
476 | self.model.setItem(WIDGETS.W_RG, |
---|
477 | QtGui.QStandardItem("{:.3g}".format(pr.rg(out)))) |
---|
478 | self.model.setItem(WIDGETS.W_I_ZERO, |
---|
479 | QtGui.QStandardItem( |
---|
480 | "{:.3g}".format(pr.iq0(out)))) |
---|
481 | self.model.setItem(WIDGETS.W_OSCILLATION, QtGui.QStandardItem( |
---|
482 | "{:.3g}".format(pr.oscillations(out)))) |
---|
483 | self.model.setItem(WIDGETS.W_POS_FRACTION, QtGui.QStandardItem( |
---|
484 | "{:.3g}".format(pr.get_positive(out)))) |
---|
485 | if cov is not None: |
---|
486 | self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION, |
---|
487 | QtGui.QStandardItem( |
---|
488 | "{:.3g}".format( |
---|
489 | pr.get_pos_err(out, cov)))) |
---|
490 | |
---|
491 | def removeData(self): |
---|
492 | """Remove the existing data reference from the P(r) Persepective""" |
---|
493 | if self.dmaxWindow is not None: |
---|
494 | self.dmaxWindow = None |
---|
495 | self.dataList.removeItem(self.dataList.currentIndex()) |
---|
496 | self._data_list.pop(self._data) |
---|
497 | # Last file removed |
---|
498 | if len(self._data_list) == 0: |
---|
499 | self._data = None |
---|
500 | self.pr_plot = None |
---|
501 | self._data_set = None |
---|
502 | self._calculator = Invertor() |
---|
503 | self.logic.data = None |
---|
504 | self.enableButtons() |
---|
505 | else: |
---|
506 | self.dataList.setCurrentIndex(0) |
---|
507 | self.updateGuiValues() |
---|
508 | |
---|
509 | ###################################################################### |
---|
510 | # Thread Creators |
---|
511 | def startThreadAll(self): |
---|
512 | for data_ref in self._data_list.keys(): |
---|
513 | self.setCurrentData(data_ref) |
---|
514 | self.startThread() |
---|
515 | |
---|
516 | def startThread(self): |
---|
517 | """ |
---|
518 | Start a calculation thread |
---|
519 | """ |
---|
520 | from .Thread import CalcPr |
---|
521 | |
---|
522 | # Set data before running the calculations |
---|
523 | self.update_calculator() |
---|
524 | |
---|
525 | # If a thread is already started, stop it |
---|
526 | if self.calc_thread is not None and self.calc_thread.isrunning(): |
---|
527 | self.calc_thread.stop() |
---|
528 | pr = self._calculator.clone() |
---|
529 | nfunc = self.getNFunc() |
---|
530 | self.calc_thread = CalcPr(pr, nfunc, |
---|
531 | error_func=self._threadError, |
---|
532 | completefn=self._calculateCompleted, |
---|
533 | updatefn=None) |
---|
534 | self.calc_thread.queue() |
---|
535 | self.calc_thread.ready(2.5) |
---|
536 | |
---|
537 | def performEstimateNT(self): |
---|
538 | """ |
---|
539 | Perform parameter estimation |
---|
540 | """ |
---|
541 | from .Thread import EstimateNT |
---|
542 | |
---|
543 | # If a thread is already started, stop it |
---|
544 | if (self.estimation_thread is not None and |
---|
545 | self.estimation_thread.isrunning()): |
---|
546 | self.estimation_thread.stop() |
---|
547 | pr = self._calculator.clone() |
---|
548 | # Skip the slit settings for the estimation |
---|
549 | # It slows down the application and it doesn't change the estimates |
---|
550 | pr.slit_height = 0.0 |
---|
551 | pr.slit_width = 0.0 |
---|
552 | nfunc = self.getNFunc() |
---|
553 | |
---|
554 | self.estimation_thread = EstimateNT(pr, nfunc, |
---|
555 | error_func=self._threadError, |
---|
556 | completefn=self._estimateNTCompleted, |
---|
557 | updatefn=None) |
---|
558 | self.estimation_thread.queue() |
---|
559 | self.estimation_thread.ready(2.5) |
---|
560 | |
---|
561 | def performEstimate(self): |
---|
562 | """ |
---|
563 | Perform parameter estimation |
---|
564 | """ |
---|
565 | from .Thread import EstimatePr |
---|
566 | |
---|
567 | self.startThread() |
---|
568 | |
---|
569 | # If a thread is already started, stop it |
---|
570 | if (self.estimation_thread is not None and |
---|
571 | self.estimation_thread.isrunning()): |
---|
572 | self.estimation_thread.stop() |
---|
573 | pr = self._calculator.clone() |
---|
574 | nfunc = self.getNFunc() |
---|
575 | self.estimation_thread = EstimatePr(pr, nfunc, |
---|
576 | error_func=self._threadError, |
---|
577 | completefn=self._estimateCompleted, |
---|
578 | updatefn=None) |
---|
579 | self.estimation_thread.queue() |
---|
580 | self.estimation_thread.ready(2.5) |
---|
581 | |
---|
582 | ###################################################################### |
---|
583 | # Thread Complete |
---|
584 | |
---|
585 | def _estimateCompleted(self, alpha, message, elapsed): |
---|
586 | ''' Send a signal to the main thread for model update''' |
---|
587 | self.estimateSignal.emit((alpha, message, elapsed)) |
---|
588 | |
---|
589 | def _estimateUpdate(self, output_tuple): |
---|
590 | """ |
---|
591 | Parameter estimation completed, |
---|
592 | display the results to the user |
---|
593 | |
---|
594 | :param alpha: estimated best alpha |
---|
595 | :param elapsed: computation time |
---|
596 | """ |
---|
597 | alpha, message, elapsed = output_tuple |
---|
598 | if message: |
---|
599 | logging.info(message) |
---|
600 | self.performEstimateNT() |
---|
601 | |
---|
602 | def _estimateNTCompleted(self, nterms, alpha, message, elapsed): |
---|
603 | ''' Send a signal to the main thread for model update''' |
---|
604 | self.estimateNTSignal.emit((nterms, alpha, message, elapsed)) |
---|
605 | |
---|
606 | def _estimateNTUpdate(self, output_tuple): |
---|
607 | """ |
---|
608 | Parameter estimation completed, |
---|
609 | display the results to the user |
---|
610 | |
---|
611 | :param alpha: estimated best alpha |
---|
612 | :param nterms: estimated number of terms |
---|
613 | :param elapsed: computation time |
---|
614 | """ |
---|
615 | nterms, alpha, message, elapsed = output_tuple |
---|
616 | self._calculator.elapsed = elapsed |
---|
617 | self._calculator.suggested_alpha = alpha |
---|
618 | self.nTermsSuggested = nterms |
---|
619 | # Save useful info |
---|
620 | self.updateGuiValues() |
---|
621 | if message: |
---|
622 | logging.info(message) |
---|
623 | |
---|
624 | def _calculateCompleted(self, out, cov, pr, elapsed): |
---|
625 | ''' Send a signal to the main thread for model update''' |
---|
626 | self.calculateSignal.emit((out, cov, pr, elapsed)) |
---|
627 | |
---|
628 | def _calculateUpdate(self, output_tuple): |
---|
629 | """ |
---|
630 | Method called with the results when the inversion is done |
---|
631 | |
---|
632 | :param out: output coefficient for the base functions |
---|
633 | :param cov: covariance matrix |
---|
634 | :param pr: Invertor instance |
---|
635 | :param elapsed: time spent computing |
---|
636 | """ |
---|
637 | out, cov, pr, elapsed = output_tuple |
---|
638 | # Save useful info |
---|
639 | cov = np.ascontiguousarray(cov) |
---|
640 | pr.cov = cov |
---|
641 | pr.out = out |
---|
642 | pr.elapsed = elapsed |
---|
643 | |
---|
644 | # Save Pr invertor |
---|
645 | self._calculator = pr |
---|
646 | |
---|
647 | # Create new P(r) and fit plots |
---|
648 | if self.pr_plot is None: |
---|
649 | self.pr_plot = self.logic.newPRPlot(out, self._calculator, cov) |
---|
650 | if self.data_plot is None: |
---|
651 | self.data_plot = self.logic.new1DPlot(out, self._calculator) |
---|
652 | self.updateDataList(self._data) |
---|
653 | self.updateGuiValues() |
---|
654 | |
---|
655 | def _threadError(self, error): |
---|
656 | """ |
---|
657 | Call-back method for calculation errors |
---|
658 | """ |
---|
659 | logging.warning(error) |
---|