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