File: SpecFileDataInfo.py

package info (click to toggle)
pymca 5.4.3%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 44,320 kB
  • sloc: python: 140,671; ansic: 20,050; sh: 175; makefile: 133; xml: 55
file content (307 lines) | stat: -rw-r--r-- 11,581 bytes parent folder | download
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
140
141
142
143
144
145
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
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
#/*##########################################################################
# Copyright (C) 2004-2017 V.A. Sole, European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF by the Software group.
#
# 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.
#
#############################################################################*/
__author__ = "V.A. Sole - ESRF Data Analysis"
__contact__ = "sole@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
import sys
from PyMca5.PyMcaGui import PyMcaQt as qt

try:
    from silx.gui.widgets.TableWidget import TableWidget
except ImportError:
    from PyMca5.PyMcaGui.misc.TableWidget import TableWidget

QTVERSION = qt.qVersion()

class QTable(TableWidget):
    def setText(self, row, col, text):
        if qt.qVersion() < "4.0.0":
            QTable.setText(self, row, col, text)
        else:
            item = self.item(row, col)
            if item is None:
                item = qt.QTableWidgetItem(text,
                                           qt.QTableWidgetItem.Type)
                self.setItem(row, col, item)
            else:
                item.setText(text)

class SpecFileDataInfoCustomEvent(qt.QEvent):
    def __init__(self, ddict):
        if ddict is None:
            ddict = {}
        self.dict = ddict
        qt.QEvent.__init__(self, qt.QEvent.User)


class SpecFileDataInfo(qt.QTabWidget):
    InfoTableItems= [
        ("SourceType", "Type"),
        ("SourceName", "Filename"),
        ("Date", "Date"),
        ("Command", "Command"),
        ("Key", "Scan Number"),
        ("Lines", "Nb Lines"),
        ("NbMca", "Nb Mca Spectrum"),
        ("NbMcaDet", "Nb Mca Detectors"),
        ("McaCalib", "Mca Calibration"),
        ("McaPresetTime", "Mca Preset Time"),
        ("McaLiveTime", "Mca Live Time"),
        ("McaRealTime", "Mca Real Time"),
        #EDF Related
        ("HeaderID", "HeaderID"),
        ("Image", "Image"),
        ("DataType", "Data Type"),
        ("ByteOrder", "Byte Order"),
        ("Dim_1", "1st Dimension"),
        ("Dim_2", "2nd Dimension"),
        ("Dim_3", "3rd Dimension"),
        ("Size", "File Data Size"),
    ]

    def __init__(self, info, parent=None, name="DataSpecFileInfo", fl=0):
        if QTVERSION < '4.0.0':
            qt.QTabWidget.__init__(self, parent, name, fl)
            self.setContentsMargins(5, 5, 5, 5)
        else:
            qt.QTabWidget.__init__(self, parent)
            if name is not None:self.setWindowTitle(name)
            self._notifyCloseEventToWidget = []
        self.info= info
        self.__createInfoTable()
        self.__createMotorTable()
        self.__createCounterTable()
        self.__createHeaderText()
        self.__createEDFHeaderText()
        self.__createFileHeaderText()

    if QTVERSION > '4.0.0':
        def sizeHint(self):
            return qt.QSize(2 * qt.QTabWidget.sizeHint(self).width(),
                            3 * qt.QTabWidget.sizeHint(self).height())

        def notifyCloseEventToWidget(self, widget):
            if widget not in self._notifyCloseEventToWidget:
                self._notifyCloseEventToWidget.append(widget)

    def __createInfoTable(self):
        pars= [ par for par in self.InfoTableItems if par[0] in self.info.keys() ]
        num= len(pars)
        if num:
            table= self.__createTable(num, "Parameter", "Value")
            for idx in range(num):
                table.setText(idx, 0, str(pars[idx][1]))
                table.setText(idx, 1, str(self.info.get(pars[idx][0], "-")))
            self.__adjustTable(table)
            self.addTab(table, "Info")

    def __createTable(self, rows, head_par, head_val):
        if qt.qVersion() < '4.0.0':
            table= QTable(self)
        else:
            table= QTable()
        table.setColumnCount(2)
        table.setRowCount(rows)
        if qt.qVersion() < '4.0.0':
            table.setReadOnly(1)
            table.setSelectionMode(QTable.SingleRow)
        else:
            table.setSelectionMode(qt.QTableWidget.NoSelection)
        table.verticalHeader().hide()
        if qt.qVersion() < '4.0.0':
            table.setLeftMargin(0)
            table.horizontalHeader().setLabel(0, head_par)
            table.horizontalHeader().setLabel(1, head_val)
        else:
            labels = [head_par, head_val]
            for i in range(len(labels)):
                item = table.horizontalHeaderItem(i)
                if item is None:
                    item = qt.QTableWidgetItem(labels[i],
                                               qt.QTableWidgetItem.Type)
                item.setText(labels[i])
                table.setHorizontalHeaderItem(i,item)
        return table

    def __adjustTable(self, table):
        for col in range(table.columnCount()):
            table.resizeColumnToContents(col)
        if qt.qVersion() > '4.0.0':
            rheight = table.horizontalHeader().sizeHint().height()
            for row in range(table.rowCount()):
                table.setRowHeight(row, rheight)

    def __createMotorTable(self):
        nameKeys = ["MotorNames", "motor_mne"]
        for key in nameKeys:
            names= self.info.get(key, None)
            if names is not None:
                if key != nameKeys[0]:
                    #EDF like ...
                    tmpString = names.replace('"','')
                    #ID01 specific
                    tmpKey = key + '~1'
                    if tmpKey in self.info:
                        tmpString += self.info[tmpKey].replace('"','')
                    names = tmpString.split()
                break
        valKeys = ["MotorValues", "motor_pos"]
        for key in valKeys:
            pos= self.info.get(key, None)
            if pos is not None:
                if key != valKeys[0]:
                    #EDF like ...
                    tmpString = pos.replace('"', '')
                    #ID01 specific
                    tmpKey = key + '~1'
                    if tmpKey in self.info:
                        tmpString += self.info[tmpKey].replace('"','')
                    pos = tmpString.split()
                break
        if names is not None and pos is not None:
            num= len(names)
            if num != len(pos):
                print("Incorrent number of labels or values")
                return
            if num:
                table= self.__createTable(num, "Motor", "Position")
                for idx in range(num):
                    table.setText(idx, 0, str(names[idx]))
                    table.setText(idx, 1, str(pos[idx]))
                self.__adjustTable(table)
                self.addTab(table, "Motors")

    def __createCounterTable(self):
        nameKeys = ["LabelNames", "counter_mne"]
        for key in nameKeys:
            cnts= self.info.get(key, None)
            if cnts is not None:
                if key != nameKeys[0]:
                    #EDF like ...
                    cnts = cnts.split()
                break
        valKeys = ["LabelValues", "counter_pos"]
        for key in valKeys:
            vals= self.info.get(key, None)
            if vals is not None:
                if key != valKeys[0]:
                    #EDF like ...
                    vals = vals.split()
                break
        if cnts is not None and vals is not None:
            num= len(cnts)
            if num != len(vals):
                print("Incorrent number of labels or values")
                return
            if num:
                table= self.__createTable(num, "Counter", "Value")
                for idx in range(num):
                    table.setText(idx, 0, str(cnts[idx]))
                    table.setText(idx, 1, str(vals[idx]))
                self.__adjustTable(table)
                self.addTab(table, "Counters")

    def __createHeaderText(self):
        text = self.info.get("SourceType","")
        if text.upper() in ['EDFFILE', 'EDFFILESTACK']:
            return
        text= self.info.get("Header", None)
        if text is not None:
            if qt.qVersion() < '4.0.0':
                wid = qt.QTextEdit(self)
                wid.setText("\n".join(text))
            else:
                wid = qt.QTextEdit()
                wid.insertHtml("<BR>".join(text))
            wid.setReadOnly(1)
            self.addTab(wid, "Scan Header")

    def __createEDFHeaderText(self):
        text = self.info.get("SourceType","")
        if text.upper() not in ['EDFFILE', 'EDFFILESTACK']:
            return
        keys = self.info.keys()
        nameKeys = []
        vals = []
        for key in keys:
            if key in ['SourceName', 'SourceType']:
                continue
            nameKeys.append(key)
            vals.append(self.info.get(key," --- "))
        num = len(nameKeys)
        if num:
            table= self.__createTable(num, "Keyword", "Value")
            for idx in range(num):
                table.setText(idx, 0, str(nameKeys[idx]))
                table.setText(idx, 1, str(vals[idx]))
            self.__adjustTable(table)
            self.addTab(table, "Header")

    def __createFileHeaderText(self):
        text= self.info.get("FileHeader", None)
        if text not in [None, []]:
            if qt.qVersion() < '4.0.0':
                wid = qt.QTextEdit(self)
                wid.setText("\n".join(text))
            else:
                wid = qt.QTextEdit()
                wid.insertHtml("<BR>".join(text))
            wid.setReadOnly(1)
            self.addTab(wid, "File Header")

    def closeEvent(self, event):
        ddict = {}
        ddict['event'] = "SpecFileDataInfoClosed"
        ddict['id'] = id(self)
        #self.sigSpecFileDataInfoSignal.emit(ddict)
        if len(self._notifyCloseEventToWidget):
            for widget in self._notifyCloseEventToWidget:
                newEvent = SpecFileDataInfoCustomEvent(ddict)
                qt.QApplication.postEvent(widget,
                                      newEvent)
            self._notifyCloseEventToWidget = []
        return qt.QTabWidget.closeEvent(self, event)

def test():
    from PyMca5.PyMcaCore import SpecFileLayer

    if len(sys.argv) < 3:
        print("USAGE: %s <filename> <key>" % sys.argv[0])
        sys.exit(0)

    d = SpecFileLayer.SpecFileLayer()

    d.SetSource(sys.argv[1])
    info,data = d.LoadSource(sys.argv[2])

    app= qt.QApplication([])
    wid= SpecFileDataInfo(info)
    wid.show()
    app.exec_()

if __name__ == "__main__":
    test()