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