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