ProjectChooser.py 8.37 KB
Newer Older
DN's avatar
DN committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139
# coding: utf-8
# /*##########################################################################
#
# Copyright (c) 2015-2016 European Synchrotron Radiation Facility
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
#
# ###########################################################################*/

from __future__ import absolute_import

__authors__ = ["D. Naudet"]
__license__ = "MIT"
__date__ = "15/09/2016"

import os

from silx.gui import qt as Qt

from ...io.XsocsH5 import XsocsH5
from .FileChooser import FileChooser
from ..widgets.Containers import GroupBox
from ..project.XsocsProject import XsocsProject


class ProjectChooserDialog(Qt.QDialog):
    projectFile = property(lambda self: self.__projectFile)

    def __init__(self, parent=None):
        super(ProjectChooserDialog, self).__init__(parent)

        self.__projectFile = None

        layout = Qt.QVBoxLayout(self)

        prjChooser = ProjectChooser()
        layout.addWidget(prjChooser)
        prjChooser.sigProjectPicked.connect(self.__prjPicked)

        self.__bnBox = bnBox = Qt.QDialogButtonBox(Qt.QDialogButtonBox.Open |
                                                   Qt.QDialogButtonBox.Cancel)

        bnBox.rejected.connect(self.reject)
        bnBox.accepted.connect(self.accept)

        bnBox.button(Qt.QDialogButtonBox.Open).setEnabled(False)

        layout.addWidget(bnBox)

    def __prjPicked(self, filename):
        if filename:
            self.__projectFile = filename
            enabled = True
        else:
            self.__projectFile = None
            enabled = False
        self.__bnBox.button(Qt.QDialogButtonBox.Open).setEnabled(enabled)


class ProjectChooser(Qt.QWidget):
    sigProjectPicked = Qt.Signal(object)

    projectSummary = property(lambda self:
                              self.findChild(ProjectSummaryWidget))

    def __init__(self, parent=None):
        super(ProjectChooser, self).__init__(parent)

        layout = Qt.QVBoxLayout(self)

        self.__isValid = False
        self.__selectedPath = None

        group = GroupBox('Please select the project file to open.')
        layout.addWidget(group)

        grpLayout = Qt.QHBoxLayout(group)
        filePicker = FileChooser(fileMode=Qt.QFileDialog.ExistingFile)
        filePicker.setObjectName('PROJ_FILEPICKER')
        grpLayout.addWidget(filePicker)

        filePicker.sigSelectionChanged.connect(self.__filePicked)

        fileDialog = filePicker.fileDialog
        fileDialog.setNameFilters(['Xsocs project files (*.prj)',
                                   'Any files (*)'])

        group = GroupBox('Project Summary')
        layout.addWidget(group)
        grpLayout = Qt.QVBoxLayout(group)
        view = ProjectSummaryWidget()
        grpLayout.addWidget(view)

    def __filePicked(self, selectedPath):
        self.__selectedPath = selectedPath

        view = self.projectSummary
        view.setProjectFile(selectedPath)

        valid = view.isValidProject()

        self.__isValid = valid

        if valid:
            self.sigProjectPicked.emit(selectedPath)
        else:
            self.sigProjectPicked.emit('')

    def isValid(self):
        return self.__isValid


class ProjectSummaryWidget(Qt.QWidget):
    def __init__(self, projectFile=None, parent=None):
        super(ProjectSummaryWidget, self).__init__(parent)

        self.__valid = False

        layout = Qt.QVBoxLayout(self)
        layout.setContentsMargins(0, 0, 0, 0)
        view = Qt.QTreeWidget()
        view.setColumnCount(2)
        view.setHeaderLabels(['Name', 'Value'])
Damien Naudet's avatar
Damien Naudet committed
140 141 142 143 144 145

        if int(Qt.qVersion().split('.')[0]) <= 4:
            view.header().setResizeMode(Qt.QHeaderView.ResizeToContents)
        else:
            view.header().setSectionResizeMode(Qt.QHeaderView.ResizeToContents)

DN's avatar
DN committed
146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199
        layout.addWidget(view)

        self.setProjectFile(projectFile)

    def isValidProject(self):
        return self.__valid

    def setProjectFile(self, projectFile):
        view = self.findChild(Qt.QTreeWidget)

        view.clear()

        self.__valid = False

        if projectFile is None:
            return

        errMsg = ''

        try:
            # reading project file
            errMsg = 'Failed to open X-Socs project file.'
            projectH5 = XsocsProject(projectFile, mode='r')

            # reading XSOCS data file
            errMsg = 'Failed to open X-Socs data file.'
            xsocsFile = projectH5.xsocsFile
            xsocsH5 = XsocsH5(xsocsFile, mode='r')

            # getting entries
            errMsg = 'Failed to read entries from data file.'
            entries = xsocsH5.entries()

            # getting entries
            errMsg = 'Failed to read scan parameters.'
            params = xsocsH5.scan_params(entries[0])

            inputItem = Qt.QTreeWidgetItem(
                ['Data file', os.path.basename(xsocsFile)])
            inputItem.setToolTip(0, xsocsFile)
            inputItem.setToolTip(1, xsocsFile)
            inputItem.addChild(Qt.QTreeWidgetItem(['Full path', xsocsFile]))
            view.addTopLevelItem(inputItem)

            # getting acquisition params
            errMsg = 'Failed to read Acquisition parameters.'
            title = ' '.join(str(value) for value in params.values())
            commandItem = Qt.QTreeWidgetItem(['Scan', title])
            commandItem.setToolTip(0, title)
            commandItem.setToolTip(1, title)
            for key, value in params.items():
                commandItem.addChild(Qt.QTreeWidgetItem([key, str(value)]))
            view.addTopLevelItem(commandItem)

200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221
            # getting scan angles and energies
            errMsg = 'Failed to read scan angles and energies.'
            text = '{nb_scan} (eta:[{eta1:g}°;{eta2:g}°] ' \
                   'phi:[{phi1:g}°;{phi2:g}°] ' \
                   'energy:[{energy1:g}eV;{energy2:g}eV])'.format(
                nb_scan=len(entries),
                eta1=xsocsH5.positioner(entries[0], 'eta'),
                eta2=xsocsH5.positioner(entries[-1], 'eta'),
                phi1=xsocsH5.positioner(entries[0], 'phi'),
                phi2=xsocsH5.positioner(entries[-1], 'phi'),
                energy1=xsocsH5.beam_energy(entries[0]),
                energy2=xsocsH5.beam_energy(entries[-1]))
            entriesItem = Qt.QTreeWidgetItem(['Scans', text])
            for entry in entries:
                text = 'eta:{eta:g}°\tphi:{phi:g}°\tenergy:{nrj:g}eV'.format(
                    eta=xsocsH5.positioner(entry, 'eta'),
                    phi=xsocsH5.positioner(entry, 'phi'),
                    nrj=xsocsH5.beam_energy(entry))
                entryItem = Qt.QTreeWidgetItem([entry, text])
                entriesItem.addChild(entryItem)
            view.addTopLevelItem(entriesItem)

DN's avatar
DN committed
222
            for key, value in xsocsH5.acquisition_params(entries[0]).items():
223 224
                if key == 'beam_energy':
                    continue  # Skip beam_energy
DN's avatar
DN committed
225 226 227 228 229 230 231 232 233 234 235 236 237 238
                view.addTopLevelItem(Qt.QTreeWidgetItem([key, str(value)]))

        except Exception as ex:
            style = Qt.QApplication.style()
            errorItem = Qt.QTreeWidgetItem(['', errMsg])
            icon = style.standardIcon(Qt.QStyle.SP_MessageBoxCritical)
            errorItem.setIcon(0, icon)
            errorItem.setBackground(1, Qt.QBrush(Qt.Qt.red))
            exItem = Qt.QTreeWidgetItem([ex.__class__.__name__, str(ex)])
            errorItem.addChild(exItem)
            view.addTopLevelItem(errorItem)
            errorItem.setExpanded(True)
            return

DN's avatar
DN committed
239
        self.__valid = True