Skip to content
Snippets Groups Projects
refl_gui.py 58.6 KiB
Newer Older
                transmission_ws = CreateTransmissionWorkspaceAuto(FirstTransmissionRun=trans1, OutputWorkspace=out_ws_name, SecondTransmissionRun=trans2, Params=0.02, StartOverlap=10.0, EndOverlap=12.0)
            else:
                raise RuntimeError("Up to 2 transmission runs can be specified. No more than that.")
        # Load the runs required ConvertToWavelength will deal with the transmission runs, while .to_workspace will deal with the run itself
        ws = ConvertToWavelength.to_workspace(loadedRun, ws_prefix="")
            # If we're dealing with a workspace group, we'll manually map execution over each group member
            # We do this so we can get ThetaOut correctly (see ticket #10597 for why we can't at the moment)
            if isinstance(ws, WorkspaceGroup):
                wqGroup = []
                wlamGroup = []
                thetaGroup = []

                group_trans_ws = transmission_ws
                for i in range(0, ws.size()):
                    #If the transmission workspace is a group, we'll use it pair-wise with the tof workspace group
                    if isinstance(transmission_ws, WorkspaceGroup):
                        group_trans_ws = transmission_ws[i]
                    wq, wlam, th = ReflectometryReductionOneAuto(InputWorkspace=ws[i], FirstTransmissionRun=group_trans_ws, thetaIn=angle, OutputWorkspace=runno+'_IvsQ_'+str(i+1), OutputWorkspaceWavelength=runno+'_IvsLam_'+str(i+1),)
                    wqGroup.append(wq)
                    wlamGroup.append(wlam)
                    thetaGroup.append(th)

                wq = GroupWorkspaces(InputWorkspaces=wqGroup, OutputWorkspace=runno+'_IvsQ')
                wlam = GroupWorkspaces(InputWorkspaces=wlamGroup, OutputWorkspace=runno+'_IvsLam')
                th = thetaGroup[0]
            else:
                wq, wlam, th = ReflectometryReductionOneAuto(InputWorkspace=ws, FirstTransmissionRun=transmission_ws, thetaIn=angle, OutputWorkspace=runno+'_IvsQ', OutputWorkspaceWavelength=runno+'_IvsLam',)
            wlam, wq, th = quick(loadedRun, trans=transmission_ws, theta=angle, tof_prefix="")
        if self.__group_tof_workspaces and not isinstance(ws, WorkspaceGroup):
            if "TOF" in mtd:
                tof_group = mtd["TOF"]
                if not tof_group.contains(loadedRun):
                    tof_group.add(loadedRun)
            else:
                tof_group = GroupWorkspaces(InputWorkspaces=loadedRun, OutputWorkspace="TOF")
        if ':' in runno:
            runno = runno.split(':')[0]
        if ',' in runno:
            runno = runno.split(',')[0]
        if isinstance(wq, WorkspaceGroup):
            inst = wq[0].getInstrument()
        else:
            inst = wq.getInstrument()
        #NOTE: In the new Refl UI, these adjustments to lmin/lmax are NOT made. This has been
        #noted in the parameter files for INTER/CRIST/POLREF/SURF.
        lmin = inst.getNumberParameter('LambdaMin')[0] + 1
        lmax = inst.getNumberParameter('LambdaMax')[0] - 2
        qmin = 4 * math.pi / lmax * math.sin(th * math.pi / 180)
        qmax = 4 * math.pi / lmin * math.sin(th * math.pi / 180)
        return th, qmin, qmax, wlam, wq
    def _save_table_contents(self, filename):
        """
        Save the contents of the table
        """
            writer = csv.writer(open(filename, "wb"))
            for row in range(self.tableMain.rowCount()):
                rowtext = []
                for column in range(self.tableMain.columnCount() - 2):
                    rowtext.append(self.tableMain.item(row, column).text())
                    writer.writerow(rowtext)
            self.current_table = filename
            logger.notice("Saved file to " + filename)
            self.mod_flag = False
        self.mod_flag = False
    def _save(self, failsave=False):
        """
        Save the table, showing no interface if not necessary. This also provides the failing save functionality.
        """
        filename = ''
        if failsave:
            #this is an emergency autosave as the program is failing
            logger.error("The ISIS Reflectonomy GUI has encountered an error, it will now attempt to save a copy of your work.")
            msgBox = QtGui.QMessageBox()
            msgBox.setText("The ISIS Reflectonomy GUI has encountered an error, it will now attempt to save a copy of your work.\nPlease check the log for details.")
            msgBox.setStandardButtons(QtGui.QMessageBox.Ok)
            msgBox.setIcon(QtGui.QMessageBox.Critical)
            msgBox.setDefaultButton(QtGui.QMessageBox.Ok)
            msgBox.setEscapeButton(QtGui.QMessageBox.Ok)
            msgBox.exec_()
            import datetime
            failtime = datetime.datetime.today().strftime('%Y-%m-%d_%H-%M-%S')
            if self.current_table:
                filename = self.current_table.rsplit('.', 1)[0] + "_recovered_" + failtime + ".tbl"
            else:
                mantidDefault = config['defaultsave.directory']
                if os.path.exists(mantidDefault):
                    filename = os.path.join(mantidDefault, "mantid_reflectometry_recovered_" + failtime + ".tbl")
                else:
                    import tempfile
                    tempDir = tempfile.gettempdir()
                    filename = os.path.join(tempDir, "mantid_reflectometry_recovered_" + failtime + ".tbl")
            # this is a save-on-quit or file->save
            if self.current_table:
                filename = self.current_table
                saveDialog = QtGui.QFileDialog(self.widgetMainRow.parent(), "Save Table")
                saveDialog.setFileMode(QtGui.QFileDialog.AnyFile)
                saveDialog.setNameFilter("Table Files (*.tbl);;All files (*.*)")
                saveDialog.setDefaultSuffix("tbl")
                saveDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
                if saveDialog.exec_():
                    filename = saveDialog.selectedFiles()[0]
                else:
                    return False
        return self._save_table_contents(filename)

    def _save_as(self):
        """
        show the save as dialog and save to a .tbl file with that name
        """
        saveDialog = QtGui.QFileDialog(self.widgetMainRow.parent(), "Save Table")
        saveDialog.setFileMode(QtGui.QFileDialog.AnyFile)
        saveDialog.setNameFilter("Table Files (*.tbl);;All files (*.*)")
        saveDialog.setDefaultSuffix("tbl")
        saveDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        if saveDialog.exec_():
            filename = saveDialog.selectedFiles()[0]
            self._save_table_contents(filename)

    def _load_table(self):
        """
        Load a .tbl file from disk
        """
        self.loading = True
        loadDialog = QtGui.QFileDialog(self.widgetMainRow.parent(), "Open Table")
        loadDialog.setFileMode(QtGui.QFileDialog.ExistingFile)
        loadDialog.setNameFilter("Table Files (*.tbl);;All files (*.*)")
        if loadDialog.exec_():
                #before loading make sure you give them a chance to save
                    ret, _saved = self._save_check()
                    if ret == QtGui.QMessageBox.RejectRole:
                        #if they hit cancel abort the load
                        self.loading = False
                        return
                self._reset_table()
                filename = loadDialog.selectedFiles()[0]
                self.current_table = filename
                reader = csv.reader(open(filename, "rb"))
                row = 0
                for line in reader:
                        for column in range(self.tableMain.columnCount() - 2):
                            item = QtGui.QTableWidgetItem()
                            item.setText(line[column])
                            self.tableMain.setItem(row, column, item)
                        row = row + 1
            except:
                logger.error('Could not load file: ' + str(filename) + '. File not found or unable to read from file.')
        self.loading = False
        self.mod_flag = False

    def _reload_table(self):
        """
        Reload the last loaded file from disk, replacing anything in the table already
        """
        self.loading = True
        filename = self.current_table
                msgBox = QtGui.QMessageBox()
                msgBox.setText("The table has been modified. Are you sure you want to reload the table and lose your changes?")
                msgBox.setStandardButtons(QtGui.QMessageBox.Yes | QtGui.QMessageBox.No)
                msgBox.setIcon(QtGui.QMessageBox.Question)
                msgBox.setDefaultButton(QtGui.QMessageBox.Yes)
                msgBox.setEscapeButton(QtGui.QMessageBox.No)
                ret = msgBox.exec_()
                if ret == QtGui.QMessageBox.No:
                    #if they hit No abort the reload
                    self.loading = False
                    return
                self._reset_table()
                reader = csv.reader(open(filename, "rb"))
                row = 0
                for line in reader:
                        for column in range(self.tableMain.columnCount() - 2):
                            item = QtGui.QTableWidgetItem()
                            item.setText(line[column])
                            self.tableMain.setItem(row, column, item)
                        row = row + 1
                self.mod_flag = False
                logger.error('Could not load file: ' + str(filename) + '. File not found or unable to read from file.')
            logger.notice('No file in table to reload.')
        self.loading = False

    def _save_workspaces(self):
        """
        Shows the export dialog for saving workspaces to non mantid formats
        """
        try:
            Dialog = QtGui.QDialog()
            u = refl_save.Ui_SaveWindow()
            u.setupUi(Dialog)
            Dialog.exec_()
        except Exception as ex:
            logger.notice("Could not open save workspace dialog")
            logger.notice(str(ex))
    def _options_dialog(self):
        """
        Shows the dialog for setting options regarding live data
        """
        try:

            dialog_controller = refl_options.ReflOptions(def_method = self.live_method, def_freq = self.live_freq,
                                                         def_alg_use = self.__alg_use, def_icat_download=self.__icat_download,
                                                         def_group_tof_workspaces = self.__group_tof_workspaces,
                                                         def_stitch_right=self.__scale_right)
            if dialog_controller.exec_():
                # Fetch the settings back off the controller
                self.live_freq = dialog_controller.frequency()
                self.live_method = dialog_controller.method()
                self.__alg_use = dialog_controller.useAlg()
                self.__icat_download = dialog_controller.icatDownload()
                self.__group_tof_workspaces = dialog_controller.groupTOFWorkspaces()
                self.__scale_right = dialog_controller.stitchRight()
                # Persist the settings
                settings = QtCore.QSettings()
                settings.beginGroup(self.__live_data_settings)
                settings.setValue(self.__live_data_frequency_key, self.live_freq)
                settings.setValue(self.__live_data_method_key, self.live_method)
                settings.beginGroup(self.__generic_settings)
                settings.setValue(self.__ads_use_key, self.__alg_use)
                settings.setValue(self.__icat_download_key, self.__icat_download)
                settings.setValue(self.__group_tof_workspaces_key, self.__group_tof_workspaces)
                settings.setValue(self.__stitch_right_key, self.__scale_right)
                settings.endGroup()
            logger.notice("Problem opening options dialog or problem retrieving values from dialog")
            logger.notice(str(ex))

    def _choose_columns(self):
        """
        shows the choose columns dialog for hiding and revealing of columns
        """
            dialog = refl_choose_col.ReflChoose(self.shown_cols, self.tableMain)
            if dialog.exec_():
                settings = QtCore.QSettings()
                settings.beginGroup(self.__column_settings)
                for key, value in dialog.visiblestates.iteritems():
                    self.shown_cols[key] = value
                    settings.setValue(str(key), value)
                    if value:
                        self.tableMain.showColumn(key)
                    else:
                        self.tableMain.hideColumn(key)
                settings.endGroup()
                del settings
        except Exception as ex:
            logger.notice("Could not open choose columns dialog")
            logger.notice(str(ex))
    def _show_help(self):
        """
        Launches the wiki page for this interface
        """
        import webbrowser
        webbrowser.open('http://www.mantidproject.org/ISIS_Reflectometry_GUI')

def getLogValue(wksp, field=''):
    returns the last value from a sample log
    ws = getWorkspace(wksp)
    log = ws.getRun().getLogData(field).value

    if type(log) is int or type(log) is str:
        return log
    else:
        return log[-1]
def getWorkspace(wksp, report_error=True):
    """
    Gets the first workspace associated with the given string. Does not load.
    """
    if isinstance(wksp, Workspace):
        return wksp
    elif isinstance(wksp, str):
        exists = mtd.doesExist(wksp)
        if not exists:
            if report_error:
                logger.error("Unable to get workspace: " + str(wksp))
                return exists  # Doesn't exist
                return exists  # Doesn't exist
        elif isinstance(mtd[wksp], WorkspaceGroup):
            wout = mtd[wksp][0]
        else:
            wout = mtd[wksp]
        return wout