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