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