File: TransmissionTableEditor.py

package info (click to toggle)
pymca 5.8.0%2Bdfsg-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 44,392 kB
  • sloc: python: 155,456; ansic: 15,843; makefile: 116; sh: 73; xml: 55
file content (383 lines) | stat: -rw-r--r-- 14,386 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
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
#/*##########################################################################
#
# The PyMca X-Ray Fluorescence Toolkit
#
# Copyright (c) 2020-2022 European Synchrotron Radiation Facility
#
# This file is part of the PyMca X-ray Fluorescence Toolkit developed at
# the ESRF.
#
# 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. Armando Sole"
__contact__ = "sole@esrf.fr"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
import sys
import os
import copy
import logging
import numpy
import traceback
from PyMca5.PyMcaGui import PyMcaQt as qt
from PyMca5.PyMcaCore import PyMcaDirs
from PyMca5.PyMcaGui.io import PyMcaFileDialogs
from PyMca5.PyMcaIO import specfilewrapper as specfile
from PyMca5.PyMcaIO import ArraySave

_logger = logging.getLogger(__name__)

class TransmissionTableEditor(qt.QWidget):
    def __init__(self, parent=None):
        qt.QWidget.__init__(self, parent)
        layout = qt.QGridLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(2)

        # the flag to use it
        useBox = qt.QWidget(self)
        label = qt.QLabel(useBox)
        label.setText("Use")
        self.useCheckBox = qt.QCheckBox(useBox)
        self.useCheckBox.setChecked(False)
        self.useCheckBox.clicked.connect(self._useSlot)
        useBoxLayout = qt.QHBoxLayout(useBox)
        useBoxLayout.addWidget(label)
        useBoxLayout.addWidget(self.useCheckBox)
        layout.addWidget(useBox, 0, 0, 2, 1)

        self.lineEditDict = {}
        r = 0
        c = 1
        labels = ["Name", "Comment"]
        for idx in range(len(labels)):
            l = labels[idx]
            label = qt.QLabel(self)
            label.setText(l)
            line = qt.QLineEdit(self)
            line.editingFinished.connect(self._lineSlot)
            line.setText("")
            layout.addWidget(label, r, c)
            layout.addWidget(line, r, c + 1)
            self.lineEditDict[l.lower()] = line
            r += 1

        buttonsBox = qt.QWidget(self)
        buttonsBoxLayout = qt.QHBoxLayout(buttonsBox)
        self.buttonsDict = {}
        actions = ["Load", "Save", "Show"]
        slots = [self._loadSlot, self._saveSlot, self._showSlot]
        buttonsBoxLayout.addWidget(qt.HorizontalSpacer(buttonsBox))
        for i in range(len(slots)):
            l = actions[i]
            s = slots[i]
            b = qt.QPushButton(buttonsBox)
            b.setText(l)
            b.setAutoDefault(False)
            b.clicked.connect(s)
            buttonsBoxLayout.addWidget(b)
            self.buttonsDict[l.lower()] = b
        buttonsBoxLayout.addWidget(qt.HorizontalSpacer(buttonsBox))
        layout.addWidget(buttonsBox, 2, 0, 1, 3)
        self.inputDir = None
        self.outputDir = None
        self.outputFilter = None
        self.plotDialog = None
        ddict = {}
        ddict["use"] = 0
        ddict["name"] = ""
        ddict["comment"] = ""
        ddict["energy"] = [0.0, 0.001]
        ddict["transmission"] = [0.0, 1.0]
        self._transmissionTable = ddict
        self.update()
        self.setTransmissionTable(ddict)

    def _useSlot(self):
        if self.useCheckBox.isChecked():
            self._transmissionTable["use"] = 1
        else:
            self._transmissionTable["use"] = 0

    def _lineSlot(self):
        ddict = {}
        for key in ["name", "comment"]:
            txt = qt.safe_str(self.lineEditDict[key].text())
            ddict[key] = txt.strip()
        self.setTransmissionTable(ddict, updating=True)

    def _loadSlot(self):
        if self.inputDir is None:
            if self.inputDir is not None:
                self.inputDir = self.outputDir
            else:
                self.inputDir = PyMcaDirs.inputDir
        wdir = self.inputDir
        if not os.path.exists(wdir):
            wdir = os.getcwd()
        filename = PyMcaFileDialogs.getFileList(self,
                            filetypelist=["Transmission table files (*.csv)",
                                          "Transmission table files (*)"],
                            mode="OPEN",
                            message="Choose 2-column transmission table file",
                            currentdir=wdir,
                            single=True)
        if len(filename):
            filename = qt.safe_str(filename[0])
            if len(filename):
                try:
                    self.loadTransmissionTable(filename)
                    self.inputDir = os.path.dirname(filename)
                    PyMcaDirs.inputDir = self.inputDir
                except:
                    msg = qt.QMessageBox(self)
                    msg.setIcon(qt.QMessageBox.Critical)
                    msg.setText("Error transmission table: %s" % (sys.exc_info()[1]))
                    msg.exec()
                    return

    def loadTransmissionTable(self, filename):
        # read with our wrapper
        sf = specfile.Specfile(filename)
        scan = sf[0]
        data = scan.data()
        labels = scan.alllabels()
        scan = None
        sf = None

        nLabels = len(labels)
        if nLabels not in [2, 3]:
            txt = "Expected a two column file got %d columns" % nLabels
            raise IOError(txt)
        if nLabels == 3 and labels[0].lower().startswith("point"):
            energyIdx = 1
            transmissionIdx = 2
        else:
            energyIdx = 0
            transmissionIdx = 1

        # sort energies in ascending order
        energy = data[energyIdx, :]
        transmission = data[transmissionIdx, :]
        idx = numpy.argsort(energy)
        energy = numpy.take(energy, idx)
        transmission = numpy.take(transmission, idx)

        ddict = {}
        ddict["use"] = 1
        ddict["energy"] = energy
        ddict["transmission"] = transmission 
        ddict["name"] = os.path.basename(filename)
        ddict["comment"] = ""

        self.setTransmissionTable(ddict, updating=True)

    def _saveSlot(self):
        if self.outputDir is None:
            if self.inputDir is not None:
                self.outputDir = self.inputDir
            else:
                self.outputDir = PyMcaDirs.outputDir
        wdir = self.outputDir
        format_list = ['";"-separated CSV *.csv',
                       '","-separated CSV *.csv',
                       '"tab"-separated CSV *.csv']
        if self.outputFilter is None:
            self.outputFilter = format_list[0]
        outfile, filterused = PyMcaFileDialogs.getFileList(self,
                                        filetypelist=format_list,
                                        mode="SAVE",
                                        message="Output File Selection",
                                        currentdir=wdir,
                                        currentfilter=self.outputFilter,
                                        getfilter=True,
                                        single=True)
        if len(outfile):
            outputFile = qt.safe_str(outfile[0])
        else:
            return
        self.outputFilter = qt.safe_str(filterused)
        filterused = self.outputFilter.split()
        try:
            self.outputDir  = os.path.dirname(outputFile)
            PyMcaDirs.outputDir = os.path.dirname(outputFile)
        except:
            self.outputDir  = "."
        if not outputFile.endswith('.csv'):
            outputFile += '.csv'
        #always overwrite
        if "," in filterused[0]:
            csv = ","
        elif ";" in filterused[0]:
            csv = ";"
        else:
            csv = "\t"

        ddict = self.getTransmissionTable()
        x = ddict["energy"]
        y = ddict["transmission"]

        try:
            ArraySave.saveXY(x, y, outputFile,
                             xlabel="Energy", ylabel="Transmission",
                             csv=True, csvseparator=csv)
        except IOError:
            msg = qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setText("Input Output Error: %s" % (sys.exc_info()[1]))
            msg.exec()
            return

    def _showSlot(self):
        self.showPlot()

    def setTransmissionTable(self, tableDict, updating=False):
        # make things case insensitive
        tableKeys = list(tableDict.keys())
        tableKeysLower = [x.lower() for x in tableKeys]
        if updating:
            # we are not expected to supply a complete dictionary
            ddict = self.getTransmissionTable()
        else:
            # a complete dictionary expected
            ddict = {}
            ddict["use"] = 0
            ddict["name"] = ""
            ddict["comment"] = ""
            ddict["energy"] = [0.0, 0.001]
            ddict["transmission"] = [0.0, 1.0]

        for key in ["name", "comment"]:
            if key in tableKeysLower:
                idx = tableKeysLower.index(key)
                txt = tableDict[tableKeys[idx]]
                if not len(txt):
                    txt = ""
                ddict[key] = txt.strip()

        for key in ["use"]:
            if key in tableKeysLower:
                idx = tableKeysLower.index(key)
                txt = tableDict[tableKeys[idx]]
                if txt in ["", "0", 0, "false", "False"]:
                    ddict[key] = 0
                else:
                    ddict[key] = 1

        for key in ["energy", "transmission"]:
            if key in tableKeysLower:
                idx = tableKeysLower.index(key)
                values = tableDict[tableKeys[idx]]
                ddict[key] = values

        for key in ["energy", "transmission"]:
            # make sure we have floats
            values = numpy.array(ddict[key], numpy.float64).reshape(-1)
            # convert to list to prevent issues when saving
            ddict[key] = values.tolist()

        try:
            self._validateDict(ddict)
            self._transmissionTable = ddict
        except:
            msg=qt.QMessageBox(self)
            msg.setIcon(qt.QMessageBox.Critical)
            msg.setInformativeText(str(sys.exc_info()[1]))
            msg.setDetailedText(traceback.format_exc())
            msg.exec()
        self.update()

    def _validateDict(self, ddict):
        for key in ["name", "comment"]:
            txt = ddict.get(key, "")
            for c in ["%"]:
                if c in txt:
                    raise ValueError("Invalid name '%s'\n" % txt + \
                            "It contains a <%s> character.\n" % c)
        txt = ddict.get("name", "")
        if txt.startswith(" ") or txt.endswith(" "):
            raise ValueError("Invalid name '%s'\n" % txt + \
                        "It starts or ends with a space.\n")

        if len(ddict["energy"]) != len(ddict["transmission"]):
            txt = "Energy and transmission vectors must have same length"
            raise ValueError(txt)
        return True

    def update(self):
        for key in ["name", "comment"]:
            self.lineEditDict[key].setText(self._transmissionTable[key])
        if self._transmissionTable["use"]:
            self.useCheckBox.setChecked(True)
        else:
            self.useCheckBox.setChecked(False)
        if self.plotDialog is not None:
            self.plot()

    def plot(self):
        if self.plotDialog is None:
            from PyMca5.PyMcaGui.plotting.PlotWindow import PlotWindow
            dialog = qt.QDialog(self)
            dialog.mainLayout = qt.QVBoxLayout(dialog)
            dialog.mainLayout.setContentsMargins(0, 0, 0, 0)
            dialog.mainLayout.setSpacing(0)
            dialog.plotWidget = PlotWindow(dialog,
                                           newplot=False,
                                           fit=False,
                                           plugins=False,
                                           control=True,
                                           position=True)
            dialog.plotWidget.setDefaultPlotLines(True)
            dialog.plotWidget.setDefaultPlotPoints(True)
            dialog.plotWidget.setDataMargins(0.05, 0.05, 0.05, 0.05)
            dialog.mainLayout.addWidget(dialog.plotWidget)
            self.plotDialog = dialog

        legend = self._transmissionTable["name"]
        if legend == "":
            legend = None
        x = self._transmissionTable["energy"]
        y = self._transmissionTable["transmission"]
        comment = self._transmissionTable["comment"]
        self.plotDialog.plotWidget.addCurve(x,
                                 y,
                                 legend=legend,
                                 xlabel="Energy (keV)",
                                 ylabel="Transmission",
                                 replot=True,
                                 replace=True)
        self.plotDialog.plotWidget.setGraphTitle(comment)

    def showPlot(self):
        self.plot()
        self.plotDialog.exec()

    def getTransmissionTable(self):
        return copy.deepcopy(self._transmissionTable)

if __name__ == "__main__":
    app = qt.QApplication([])
    app.lastWindowClosed.connect(app.quit)
    demo = TransmissionTableEditor()
    if len(sys.argv) > 1:
        demo.loadTransmissionTable(sys.argv[1])
    demo.show()
    ret  = app.exec()
    app = None