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.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(str(BACKGROUND_INPUT)) |
---|
224 | self.model.setItem(WIDGETS.W_BACKGROUND_INPUT, item) |
---|
225 | item = QtGui.QStandardItem("") |
---|
226 | self.model.setItem(WIDGETS.W_QMIN, item) |
---|
227 | item = QtGui.QStandardItem("") |
---|
228 | self.model.setItem(WIDGETS.W_QMAX, item) |
---|
229 | item = QtGui.QStandardItem("") |
---|
230 | self.model.setItem(WIDGETS.W_SLIT_WIDTH, item) |
---|
231 | item = QtGui.QStandardItem("") |
---|
232 | self.model.setItem(WIDGETS.W_SLIT_HEIGHT, item) |
---|
233 | item = QtGui.QStandardItem(str(NUMBER_OF_TERMS)) |
---|
234 | self.model.setItem(WIDGETS.W_NO_TERMS, item) |
---|
235 | item = QtGui.QStandardItem(str(REGULARIZATION)) |
---|
236 | self.model.setItem(WIDGETS.W_REGULARIZATION, item) |
---|
237 | item = QtGui.QStandardItem(str(MAX_DIST)) |
---|
238 | self.model.setItem(WIDGETS.W_MAX_DIST, item) |
---|
239 | item = QtGui.QStandardItem("") |
---|
240 | self.model.setItem(WIDGETS.W_RG, item) |
---|
241 | item = QtGui.QStandardItem("") |
---|
242 | self.model.setItem(WIDGETS.W_I_ZERO, item) |
---|
243 | item = QtGui.QStandardItem("") |
---|
244 | self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, item) |
---|
245 | item = QtGui.QStandardItem("") |
---|
246 | self.model.setItem(WIDGETS.W_COMP_TIME, item) |
---|
247 | item = QtGui.QStandardItem("") |
---|
248 | self.model.setItem(WIDGETS.W_CHI_SQUARED, item) |
---|
249 | item = QtGui.QStandardItem("") |
---|
250 | self.model.setItem(WIDGETS.W_OSCILLATION, item) |
---|
251 | item = QtGui.QStandardItem("") |
---|
252 | self.model.setItem(WIDGETS.W_POS_FRACTION, item) |
---|
253 | item = QtGui.QStandardItem("") |
---|
254 | self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION, item) |
---|
255 | |
---|
256 | def setupWindow(self): |
---|
257 | """Initialize base window state on init""" |
---|
258 | self.enableButtons() |
---|
259 | self.estimateBgd.setChecked(True) |
---|
260 | |
---|
261 | def setupValidators(self): |
---|
262 | """Apply validators to editable line edits""" |
---|
263 | self.noOfTermsInput.setValidator(QtGui.QIntValidator()) |
---|
264 | self.regularizationConstantInput.setValidator(GuiUtils.DoubleValidator()) |
---|
265 | self.maxDistanceInput.setValidator(GuiUtils.DoubleValidator()) |
---|
266 | self.minQInput.setValidator(GuiUtils.DoubleValidator()) |
---|
267 | self.maxQInput.setValidator(GuiUtils.DoubleValidator()) |
---|
268 | self.slitHeightInput.setValidator(GuiUtils.DoubleValidator()) |
---|
269 | self.slitWidthInput.setValidator(GuiUtils.DoubleValidator()) |
---|
270 | |
---|
271 | ###################################################################### |
---|
272 | # Methods for updating GUI |
---|
273 | |
---|
274 | def enableButtons(self): |
---|
275 | """ |
---|
276 | Enable buttons when data is present, else disable them |
---|
277 | """ |
---|
278 | self.calculateAllButton.setEnabled(self.logic.data_is_loaded) |
---|
279 | self.calculateThisButton.setEnabled(self.logic.data_is_loaded) |
---|
280 | self.removeButton.setEnabled(self.logic.data_is_loaded) |
---|
281 | self.explorerButton.setEnabled(self.logic.data_is_loaded) |
---|
282 | self.regConstantSuggestionButton.setEnabled( |
---|
283 | self._calculator.suggested_alpha != self._calculator.alpha) |
---|
284 | self.noOfTermsSuggestionButton.setEnabled( |
---|
285 | self._calculator.nfunc != self.nTermsSuggested) |
---|
286 | |
---|
287 | def populateDataComboBox(self, filename, data_ref): |
---|
288 | """ |
---|
289 | Append a new file name to the data combobox |
---|
290 | :param filename: data filename |
---|
291 | :param data_ref: QStandardItem reference for data set to be added |
---|
292 | """ |
---|
293 | self.dataList.addItem(filename, data_ref) |
---|
294 | |
---|
295 | def acceptNoTerms(self): |
---|
296 | """Send estimated no of terms to input""" |
---|
297 | self.model.setItem(WIDGETS.W_NO_TERMS, QtGui.QStandardItem( |
---|
298 | self.noOfTermsSuggestionButton.text())) |
---|
299 | |
---|
300 | def acceptAlpha(self): |
---|
301 | """Send estimated alpha to input""" |
---|
302 | self.model.setItem(WIDGETS.W_REGULARIZATION, QtGui.QStandardItem( |
---|
303 | self.regConstantSuggestionButton.text())) |
---|
304 | |
---|
305 | def displayChange(self): |
---|
306 | """Switch to another item in the data list""" |
---|
307 | ref_item = self.dataList.itemData(self.dataList.currentIndex()) |
---|
308 | self.updateDataList(ref_item) |
---|
309 | self.setCurrentData(ref_item) |
---|
310 | |
---|
311 | ###################################################################### |
---|
312 | # GUI Interaction Events |
---|
313 | |
---|
314 | def update_calculator(self): |
---|
315 | """Update all p(r) params""" |
---|
316 | self._calculator.set_x(self._data_set.x) |
---|
317 | self._calculator.set_y(self._data_set.y) |
---|
318 | self._calculator.set_err(self._data_set.dy) |
---|
319 | self.set_background(self.backgroundInput.text()) |
---|
320 | |
---|
321 | def set_background(self, value): |
---|
322 | self._calculator.background = is_float(value) |
---|
323 | |
---|
324 | def model_changed(self): |
---|
325 | """Update the values when user makes changes""" |
---|
326 | if not self.mapper: |
---|
327 | msg = "Unable to update P{r}. The connection between the main GUI " |
---|
328 | msg += "and P(r) was severed. Attempting to restart P(r)." |
---|
329 | logging.warning(msg) |
---|
330 | self.setClosable(True) |
---|
331 | self.close() |
---|
332 | InversionWindow.__init__(self.parent(), list(self._data_list.keys())) |
---|
333 | exit(0) |
---|
334 | if self.pr_plot is not None: |
---|
335 | title = self.pr_plot.name |
---|
336 | GuiUtils.updateModelItemWithPlot(self._data, self.pr_plot, title) |
---|
337 | if self.data_plot is not None: |
---|
338 | title = self.data_plot.name |
---|
339 | GuiUtils.updateModelItemWithPlot(self._data, self.data_plot, title) |
---|
340 | if self.dmaxWindow is not None: |
---|
341 | self.dmaxWindow.pr_state = self._calculator |
---|
342 | self.dmaxWindow.nfunc = self.getNFunc() |
---|
343 | self.dmaxWindow.modelChanged() |
---|
344 | self.mapper.toFirst() |
---|
345 | |
---|
346 | def help(self): |
---|
347 | """ |
---|
348 | Open the P(r) Inversion help browser |
---|
349 | """ |
---|
350 | tree_location = "/user/sasgui/perspectives/pr/pr_help.html" |
---|
351 | |
---|
352 | # Actual file anchor will depend on the combo box index |
---|
353 | # Note that we can be clusmy here, since bad current_fitter_id |
---|
354 | # will just make the page displayed from the top |
---|
355 | self._manager.showHelp(tree_location) |
---|
356 | |
---|
357 | def toggleBgd(self): |
---|
358 | """ |
---|
359 | Toggle the background between manual and estimated |
---|
360 | """ |
---|
361 | sender = self.sender() |
---|
362 | if sender is self.estimateBgd: |
---|
363 | self.backgroundInput.setEnabled(False) |
---|
364 | self._calculator.set_est_bck = True |
---|
365 | elif sender is self.manualBgd: |
---|
366 | self.backgroundInput.setEnabled(True) |
---|
367 | self._calculator.set_est_bck = False |
---|
368 | else: |
---|
369 | pass |
---|
370 | |
---|
371 | def openExplorerWindow(self): |
---|
372 | """ |
---|
373 | Open the Explorer window to see correlations between params and results |
---|
374 | """ |
---|
375 | from .DMaxExplorerWidget import DmaxWindow |
---|
376 | self.dmaxWindow = DmaxWindow(self._calculator, self.getNFunc(), self) |
---|
377 | self.dmaxWindow.show() |
---|
378 | |
---|
379 | ###################################################################### |
---|
380 | # Response Actions |
---|
381 | |
---|
382 | def setData(self, data_item=None, is_batch=False): |
---|
383 | """ |
---|
384 | Assign new data set(s) to the P(r) perspective |
---|
385 | Obtain a QStandardItem object and parse it to get Data1D/2D |
---|
386 | Pass it over to the calculator |
---|
387 | """ |
---|
388 | assert data_item is not None |
---|
389 | |
---|
390 | if not isinstance(data_item, list): |
---|
391 | msg = "Incorrect type passed to the P(r) Perspective" |
---|
392 | raise AttributeError(msg) |
---|
393 | |
---|
394 | for data in data_item: |
---|
395 | if data in self._data_list.keys(): |
---|
396 | # Don't add data if it's already in |
---|
397 | return |
---|
398 | # Create initial internal mappings |
---|
399 | self._data_set = GuiUtils.dataFromItem(data) |
---|
400 | self.logic = InversionLogic(self._data_set) |
---|
401 | self.populateDataComboBox(self._data_set.filename, data) |
---|
402 | # Estimate q range |
---|
403 | qmin, qmax = self.logic.computeDataRange() |
---|
404 | self._calculator.set_qmin(qmin) |
---|
405 | self._calculator.set_qmax(qmax) |
---|
406 | self.updateDataList(data) |
---|
407 | self.setCurrentData(data) |
---|
408 | # Estimate initial values from data |
---|
409 | self.performEstimate() |
---|
410 | self.updateGuiValues() |
---|
411 | |
---|
412 | def updateDataList(self, dataRef): |
---|
413 | """Save the current data state of the window into self._data_list""" |
---|
414 | if dataRef is None: |
---|
415 | return |
---|
416 | self._data_list[dataRef] = { |
---|
417 | DICT_KEYS[0]: self._calculator, |
---|
418 | DICT_KEYS[1]: self.pr_plot, |
---|
419 | DICT_KEYS[2]: self.data_plot, |
---|
420 | DICT_KEYS[3]: self.dmaxWindow, |
---|
421 | DICT_KEYS[4]: self.nTermsSuggested |
---|
422 | } |
---|
423 | |
---|
424 | def getNFunc(self): |
---|
425 | """Get the n_func value from the GUI object""" |
---|
426 | try: |
---|
427 | nfunc = int(self.noOfTermsInput.text()) |
---|
428 | except ValueError: |
---|
429 | logging.error("Incorrect number of terms specified: %s" %self.noOfTermsInput.text()) |
---|
430 | self.noOfTermsInput.setText(str(NUMBER_OF_TERMS)) |
---|
431 | nfunc = NUMBER_OF_TERMS |
---|
432 | return nfunc |
---|
433 | |
---|
434 | def setCurrentData(self, data_ref): |
---|
435 | """Get the data by reference and display as necessary""" |
---|
436 | if data_ref is None: |
---|
437 | return |
---|
438 | if not isinstance(data_ref, QtGui.QStandardItem): |
---|
439 | msg = "Incorrect type passed to the P(r) Perspective" |
---|
440 | raise AttributeError(msg) |
---|
441 | # Data references |
---|
442 | self._data = data_ref |
---|
443 | self._data_set = GuiUtils.dataFromItem(data_ref) |
---|
444 | self._calculator = self._data_list[data_ref].get(DICT_KEYS[0]) |
---|
445 | self.pr_plot = self._data_list[data_ref].get(DICT_KEYS[1]) |
---|
446 | self.data_plot = self._data_list[data_ref].get(DICT_KEYS[2]) |
---|
447 | self.dmaxWindow = self._data_list[data_ref].get(DICT_KEYS[3]) |
---|
448 | self.nTermsSuggested = self._data_list[data_ref].get(DICT_KEYS[4]) |
---|
449 | self.logic.set_data = self._data_set |
---|
450 | self.updateGuiValues() |
---|
451 | |
---|
452 | def updateGuiValues(self): |
---|
453 | pr = self._calculator |
---|
454 | out = self._calculator.out |
---|
455 | cov = self._calculator.cov |
---|
456 | elapsed = self._calculator.elapsed |
---|
457 | alpha = self._calculator.suggested_alpha |
---|
458 | nterms = self._calculator.nfunc |
---|
459 | self.model.setItem(WIDGETS.W_QMIN, |
---|
460 | QtGui.QStandardItem("{:.4g}".format(pr.get_qmin()))) |
---|
461 | self.model.setItem(WIDGETS.W_QMAX, |
---|
462 | QtGui.QStandardItem("{:.4g}".format(pr.get_qmax()))) |
---|
463 | self.model.setItem(WIDGETS.W_BACKGROUND_INPUT, |
---|
464 | QtGui.QStandardItem("{:.3f}".format(pr.background))) |
---|
465 | self.model.setItem(WIDGETS.W_BACKGROUND_OUTPUT, |
---|
466 | QtGui.QStandardItem("{:.3g}".format(pr.background))) |
---|
467 | self.model.setItem(WIDGETS.W_COMP_TIME, |
---|
468 | QtGui.QStandardItem("{:.4g}".format(elapsed))) |
---|
469 | self.regConstantSuggestionButton.setText("{:-3.2g}".format(alpha)) |
---|
470 | self.noOfTermsSuggestionButton.setText( |
---|
471 | "{:n}".format(self.nTermsSuggested)) |
---|
472 | self.model.setItem(WIDGETS.W_COMP_TIME, |
---|
473 | QtGui.QStandardItem("{:.2g}".format(elapsed))) |
---|
474 | |
---|
475 | if isinstance(pr.chi2, np.ndarray): |
---|
476 | self.model.setItem(WIDGETS.W_CHI_SQUARED, |
---|
477 | QtGui.QStandardItem("{:.3g}".format(pr.chi2[0]))) |
---|
478 | if out is not None: |
---|
479 | self.model.setItem(WIDGETS.W_RG, |
---|
480 | QtGui.QStandardItem("{:.3g}".format(pr.rg(out)))) |
---|
481 | self.model.setItem(WIDGETS.W_I_ZERO, |
---|
482 | QtGui.QStandardItem( |
---|
483 | "{:.3g}".format(pr.iq0(out)))) |
---|
484 | self.model.setItem(WIDGETS.W_OSCILLATION, QtGui.QStandardItem( |
---|
485 | "{:.3g}".format(pr.oscillations(out)))) |
---|
486 | self.model.setItem(WIDGETS.W_POS_FRACTION, QtGui.QStandardItem( |
---|
487 | "{:.3g}".format(pr.get_positive(out)))) |
---|
488 | if cov is not None: |
---|
489 | self.model.setItem(WIDGETS.W_SIGMA_POS_FRACTION, |
---|
490 | QtGui.QStandardItem( |
---|
491 | "{:.3g}".format( |
---|
492 | pr.get_pos_err(out, cov)))) |
---|
493 | self.enableButtons() |
---|
494 | |
---|
495 | def removeData(self): |
---|
496 | """Remove the existing data reference from the P(r) Persepective""" |
---|
497 | if self.dmaxWindow is not None: |
---|
498 | self.dmaxWindow.done() |
---|
499 | self.dmaxWindow = None |
---|
500 | self.dataList.removeItem(self.dataList.currentIndex()) |
---|
501 | self._data_list.pop(self._data) |
---|
502 | # Last file removed |
---|
503 | if len(self._data_list) == 0: |
---|
504 | self._data = None |
---|
505 | self._data_set = None |
---|
506 | self.pr_plot = None |
---|
507 | self.data_plot = None |
---|
508 | self._calculator = Invertor() |
---|
509 | self.logic.data = self._data_set |
---|
510 | self.nTermsSuggested = NUMBER_OF_TERMS |
---|
511 | self.noOfTermsSuggestionButton.setText("{:n}".format( |
---|
512 | self.nTermsSuggested)) |
---|
513 | self.regConstantSuggestionButton.setText("{:-3.2g}".format( |
---|
514 | REGULARIZATION)) |
---|
515 | self.enableButtons() |
---|
516 | self.setupModel() |
---|
517 | else: |
---|
518 | self.dataList.setCurrentIndex(0) |
---|
519 | self.updateGuiValues() |
---|
520 | |
---|
521 | ###################################################################### |
---|
522 | # Thread Creators |
---|
523 | def startThreadAll(self): |
---|
524 | for data_ref in self._data_list.keys(): |
---|
525 | self.setCurrentData(data_ref) |
---|
526 | self.startThread() |
---|
527 | |
---|
528 | def startThread(self): |
---|
529 | """ |
---|
530 | Start a calculation thread |
---|
531 | """ |
---|
532 | from .Thread import CalcPr |
---|
533 | |
---|
534 | # Set data before running the calculations |
---|
535 | self.update_calculator() |
---|
536 | |
---|
537 | # If a thread is already started, stop it |
---|
538 | if self.calc_thread is not None and self.calc_thread.isrunning(): |
---|
539 | self.calc_thread.stop() |
---|
540 | pr = self._calculator.clone() |
---|
541 | nfunc = self.getNFunc() |
---|
542 | self.calc_thread = CalcPr(pr, nfunc, |
---|
543 | error_func=self._threadError, |
---|
544 | completefn=self._calculateCompleted, |
---|
545 | updatefn=None) |
---|
546 | self.calc_thread.queue() |
---|
547 | self.calc_thread.ready(2.5) |
---|
548 | |
---|
549 | def performEstimateNT(self): |
---|
550 | """ |
---|
551 | Perform parameter estimation |
---|
552 | """ |
---|
553 | from .Thread import EstimateNT |
---|
554 | |
---|
555 | # If a thread is already started, stop it |
---|
556 | if (self.estimation_thread is not None and |
---|
557 | self.estimation_thread.isrunning()): |
---|
558 | self.estimation_thread.stop() |
---|
559 | pr = self._calculator.clone() |
---|
560 | # Skip the slit settings for the estimation |
---|
561 | # It slows down the application and it doesn't change the estimates |
---|
562 | pr.slit_height = 0.0 |
---|
563 | pr.slit_width = 0.0 |
---|
564 | nfunc = self.getNFunc() |
---|
565 | |
---|
566 | self.estimation_thread = EstimateNT(pr, nfunc, |
---|
567 | error_func=self._threadError, |
---|
568 | completefn=self._estimateNTCompleted, |
---|
569 | updatefn=None) |
---|
570 | self.estimation_thread.queue() |
---|
571 | self.estimation_thread.ready(2.5) |
---|
572 | |
---|
573 | def performEstimate(self): |
---|
574 | """ |
---|
575 | Perform parameter estimation |
---|
576 | """ |
---|
577 | from .Thread import EstimatePr |
---|
578 | |
---|
579 | self.startThread() |
---|
580 | |
---|
581 | # If a thread is already started, stop it |
---|
582 | if (self.estimation_thread is not None and |
---|
583 | self.estimation_thread.isrunning()): |
---|
584 | self.estimation_thread.stop() |
---|
585 | pr = self._calculator.clone() |
---|
586 | nfunc = self.getNFunc() |
---|
587 | self.estimation_thread = EstimatePr(pr, nfunc, |
---|
588 | error_func=self._threadError, |
---|
589 | completefn=self._estimateCompleted, |
---|
590 | updatefn=None) |
---|
591 | self.estimation_thread.queue() |
---|
592 | self.estimation_thread.ready(2.5) |
---|
593 | |
---|
594 | ###################################################################### |
---|
595 | # Thread Complete |
---|
596 | |
---|
597 | def _estimateCompleted(self, alpha, message, elapsed): |
---|
598 | ''' Send a signal to the main thread for model update''' |
---|
599 | self.estimateSignal.emit((alpha, message, elapsed)) |
---|
600 | |
---|
601 | def _estimateUpdate(self, output_tuple): |
---|
602 | """ |
---|
603 | Parameter estimation completed, |
---|
604 | display the results to the user |
---|
605 | |
---|
606 | :param alpha: estimated best alpha |
---|
607 | :param elapsed: computation time |
---|
608 | """ |
---|
609 | alpha, message, elapsed = output_tuple |
---|
610 | if message: |
---|
611 | logging.info(message) |
---|
612 | self.performEstimateNT() |
---|
613 | |
---|
614 | def _estimateNTCompleted(self, nterms, alpha, message, elapsed): |
---|
615 | ''' Send a signal to the main thread for model update''' |
---|
616 | self.estimateNTSignal.emit((nterms, alpha, message, elapsed)) |
---|
617 | |
---|
618 | def _estimateNTUpdate(self, output_tuple): |
---|
619 | """ |
---|
620 | Parameter estimation completed, |
---|
621 | display the results to the user |
---|
622 | |
---|
623 | :param alpha: estimated best alpha |
---|
624 | :param nterms: estimated number of terms |
---|
625 | :param elapsed: computation time |
---|
626 | """ |
---|
627 | nterms, alpha, message, elapsed = output_tuple |
---|
628 | self._calculator.elapsed = elapsed |
---|
629 | self._calculator.suggested_alpha = alpha |
---|
630 | self.nTermsSuggested = nterms |
---|
631 | # Save useful info |
---|
632 | self.updateGuiValues() |
---|
633 | if message: |
---|
634 | logging.info(message) |
---|
635 | |
---|
636 | def _calculateCompleted(self, out, cov, pr, elapsed): |
---|
637 | ''' Send a signal to the main thread for model update''' |
---|
638 | self.calculateSignal.emit((out, cov, pr, elapsed)) |
---|
639 | |
---|
640 | def _calculateUpdate(self, output_tuple): |
---|
641 | """ |
---|
642 | Method called with the results when the inversion is done |
---|
643 | |
---|
644 | :param out: output coefficient for the base functions |
---|
645 | :param cov: covariance matrix |
---|
646 | :param pr: Invertor instance |
---|
647 | :param elapsed: time spent computing |
---|
648 | """ |
---|
649 | out, cov, pr, elapsed = output_tuple |
---|
650 | # Save useful info |
---|
651 | cov = np.ascontiguousarray(cov) |
---|
652 | pr.cov = cov |
---|
653 | pr.out = out |
---|
654 | pr.elapsed = elapsed |
---|
655 | |
---|
656 | # Save Pr invertor |
---|
657 | self._calculator = pr |
---|
658 | |
---|
659 | # Create new P(r) and fit plots |
---|
660 | if self.pr_plot is None: |
---|
661 | self.pr_plot = self.logic.newPRPlot(out, self._calculator, cov) |
---|
662 | if self.data_plot is None: |
---|
663 | self.data_plot = self.logic.new1DPlot(out, self._calculator) |
---|
664 | self.updateDataList(self._data) |
---|
665 | self.updateGuiValues() |
---|
666 | |
---|
667 | def _threadError(self, error): |
---|
668 | """ |
---|
669 | Call-back method for calculation errors |
---|
670 | """ |
---|
671 | logging.warning(error) |
---|