File: testXRF.py

package info (click to toggle)
python-fisx 1.3.2-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 21,888 kB
  • sloc: cpp: 9,333; python: 1,339; sh: 144; makefile: 41
file content (250 lines) | stat: -rw-r--r-- 11,557 bytes parent folder | download | duplicates (3)
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
#/*##########################################################################
#
# The fisx library for X-Ray Fluorescence
#
# Copyright (c) 2014-2020 European Synchrotron Radiation Facility
#
# This file is part of the fisx X-ray developed by V.A. Sole
#
# 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"
import unittest
import sys
import os

ElementList= ['H', 'He',
            'Li', 'Be', 'B', 'C', 'N', 'O', 'F', 'Ne',
            'Na', 'Mg', 'Al', 'Si', 'P', 'S', 'Cl', 'Ar',
            'K', 'Ca', 'Sc', 'Ti', 'V', 'Cr', 'Mn', 'Fe',
            'Co', 'Ni', 'Cu', 'Zn', 'Ga', 'Ge', 'As', 'Se',
            'Br', 'Kr', 'Rb', 'Sr', 'Y', 'Zr', 'Nb', 'Mo',
            'Tc', 'Ru', 'Rh', 'Pd', 'Ag', 'Cd', 'In', 'Sn',
            'Sb', 'Te', 'I', 'Xe', 'Cs', 'Ba', 'La', 'Ce',
            'Pr', 'Nd', 'Pm', 'Sm', 'Eu', 'Gd', 'Tb', 'Dy',
            'Ho', 'Er', 'Tm', 'Yb', 'Lu', 'Hf', 'Ta', 'W',
            'Re', 'Os', 'Ir', 'Pt', 'Au', 'Hg', 'Tl', 'Pb',
            'Bi', 'Po', 'At', 'Rn', 'Fr', 'Ra', 'Ac', 'Th',
            'Pa', 'U', 'Np', 'Pu', 'Am', 'Cm', 'Bk', 'Cf',
            'Es', 'Fm', 'Md', 'No', 'Lr', 'Rf', 'Db', 'Sg',
            'Bh', 'Hs', 'Mt']

def getSymbol(z):
    return ElementList[z-1]

def getZ(ele):
    return ElementList.index(ele) + 1

class testXRF(unittest.TestCase):
    def setUp(self):
        """
        import the module
        """
        try:
            from fisx import XRF
            self._module = XRF
        except:
            self._module = None

    def tearDown(self):
        self._module = None

    def testXRFImport(self):
        self.assertTrue(self._module is not None,
                        'Unsuccessful fisx.XRF import')

    def testXRFInstantiation(self):
        try:
            instance = self._module()
        except:
            instance = None
            print("Instantiation error: ",
                    sys.exc_info()[0], sys.exc_info()[1], sys.exc_info()[2])
        self.assertTrue(instance is not None,
                        'Unsuccesful XRF() instantiation')

    def testXRFResults(self):
        from fisx import Elements
        from fisx import Material
        from fisx import Detector
        from fisx import XRF

        elementsInstance = Elements()
        elementsInstance.initializeAsPyMca()
        # After the slow initialization (to be made once), the rest is fairly fast.
        xrf = XRF()
        xrf.setBeam(16.0) # set incident beam as a single photon energy of 16 keV
        xrf.setBeamFilters([["Al1", 2.72, 0.11, 1.0]]) # Incident beam filters
        # Steel composition of Schoonjans et al, 2012 used to generate table I
        steel = {"C":  0.0445,
                 "N":  0.04,
                 "Si": 0.5093,
                 "P":  0.02,
                 "S":  0.0175,
                 "V":  0.05,
                 "Cr":18.37,
                 "Mn": 1.619,
                 "Fe":64.314, # calculated by subtracting the sum of all other elements
                 "Co": 0.109,
                 "Ni":12.35,
                 "Cu": 0.175,
                 "As": 0.010670,
                 "Mo": 2.26,
                 "W":  0.11,
                 "Pb": 0.001}
        SRM_1155 = Material("SRM_1155", 1.0, 1.0)
        SRM_1155.setComposition(steel)
        elementsInstance.addMaterial(SRM_1155)
        xrf.setSample([["SRM_1155", 1.0, 1.0]]) # Sample, density and thickness
        xrf.setGeometry(45., 45.)               # Incident and fluorescent beam angles
        detector = Detector("Si1", 2.33, 0.035) # Detector Material, density, thickness
        detector.setActiveArea(0.50)            # Area and distance in consistent units
        detector.setDistance(2.1)               # expected cm2 and cm.
        xrf.setDetector(detector)
        Air = Material("Air", 0.0012048, 1.0)
        Air.setCompositionFromLists(["C1", "N1", "O1", "Ar1", "Kr1"],
                                    [0.0012048, 0.75527, 0.23178, 0.012827, 3.2e-06])
        elementsInstance.addMaterial(Air)
        xrf.setAttenuators([["Air", 0.0012048, 5.0, 1.0],
                            ["Be1", 1.848, 0.002, 1.0]]) # Attenuators
        fluo = xrf.getMultilayerFluorescence(["Cr K", "Fe K", "Ni K"],
                                             elementsInstance,
                                             secondary=2,
                                             useMassFractions=1)
        print("\nElement   Peak          Energy       Rate      Secondary  Tertiary")
        for key in fluo:
            for layer in fluo[key]:
                peakList = list(fluo[key][layer].keys())
                peakList.sort()
                for peak in peakList:
                    # energy of the peak
                    energy = fluo[key][layer][peak]["energy"]
                    # expected measured rate
                    rate = fluo[key][layer][peak]["rate"]
                    # primary photons (no attenuation and no detector considered)
                    primary = fluo[key][layer][peak]["primary"]
                    # secondary photons (no attenuation and no detector considered)
                    secondary = fluo[key][layer][peak]["secondary"]
                    # tertiary photons (no attenuation and no detector considered)
                    tertiary = fluo[key][layer][peak].get("tertiary", 0.0)
                    # correction due to secondary excitation
                    enhancement2 = (primary + secondary) / primary
                    enhancement3 = (primary + secondary + tertiary) / primary
                    print("%s   %s    %.4f     %.3g     %.5g    %.5g" % \
                                       (key, peak + (13 - len(peak)) * " ", energy,
                                       rate, enhancement2, enhancement3))
                    # compare against expected values from Schoonjans et al.
                    testXMI = True
                    if (key == "Cr K") and peak.startswith("KL3"):
                        second = 1.626
                        third = 1.671
                    elif (key == "Cr K") and peak.startswith("KM3"):
                        second = 1.646
                        third = 1.694
                    elif (key == "Fe K") and peak.startswith("KL3"):
                        second = 1.063
                        third = 1.064
                    elif (key == "Fe K") and peak.startswith("KL3"):
                        second = 1.065
                        third = 1.066
                    else:
                        testXMI = False
                    if testXMI:
                        discrepancy = 100 * (abs(second-enhancement2)/second)
                        self.assertTrue(discrepancy < 1.5,
                            "%s %s secondary discrepancy = %.1f %%" % \
                            (key, peak, discrepancy))
                        discrepancy = 100 * (abs(third-enhancement3)/third)
                        self.assertTrue(discrepancy < 1.5,
                            "%s %s tertiary discrepancy = %.1f %%" % \
                            (key, peak, discrepancy))

        # check user beamfilters
        xrf.setUserBeamFilters([[[0.0, 100.], [0.5, 0.5], "half", "half intensity expected"]])
        fluo2 = xrf.getMultilayerFluorescence(["Cr K", "Fe K", "Ni K"],
                                             elementsInstance,
                                             secondary=2,
                                             useMassFractions=1)
        for key in ["rate", "primary", "secondary"]:
            before = fluo["Cr K"][0]["KL3"][key]
            after = fluo2["Cr K"][0]["KL3"][key]
            self.assertTrue(abs( before - 2.0 * after) < 1.0e-8,
                            "Expected to measure half %s and not %f" % \
                                (key, after / before))

        # check removal of user beam filters
        xrf.setUserBeamFilters([])
        fluo2 = xrf.getMultilayerFluorescence(["Cr K", "Fe K", "Ni K"],
                                             elementsInstance,
                                             secondary=2,
                                             useMassFractions=1)
        for key in ["rate", "primary", "secondary"]:
            before = fluo["Cr K"][0]["KL3"][key]
            after = fluo2["Cr K"][0]["KL3"][key]
            self.assertTrue(abs( before - after) < 1.0e-8,
                            "Expected to measure a 1 ratio and not %f" % \
                                (after / before))

        # check user attenuators
        xrf.setUserAttenuators([[{0.0:0.25, 100.:0.25},
                                 "quarter",
                                 "quarter intensity expected"]])
        fluo2 = xrf.getMultilayerFluorescence(["Cr K", "Fe K", "Ni K"],
                                             elementsInstance,
                                             secondary=2,
                                             useMassFractions=1)
        for key in ["rate"]:
            before = fluo["Cr K"][0]["KL3"][key]
            after = fluo2["Cr K"][0]["KL3"][key]
            self.assertTrue(abs( before - 4.0 * after) < 1.0e-8,
                        "Expected to measure 1/4 intensity and not %f" % \
                            (after / before))

        # check removal of user attenuators
        xrf.setUserAttenuators([])
        fluo2 = xrf.getMultilayerFluorescence(["Cr K", "Fe K", "Ni K"],
                                             elementsInstance,
                                             secondary=2,
                                             useMassFractions=1)
        
        for key in ["rate"]:
            before = fluo["Cr K"][0]["KL3"][key]
            after = fluo2["Cr K"][0]["KL3"][key]
            self.assertTrue(abs( before - after) < 1.0e-8,
                        "Expected to measure a 1 ratio and not %f" % \
                            (after / before))

def getSuite(auto=True):
    testSuite = unittest.TestSuite()
    if auto:
        testSuite.addTest(\
            unittest.TestLoader().loadTestsFromTestCase(testXRF))
    else:
        # use a predefined order
        testSuite.addTest(testXRF("testXRFImport"))
        testSuite.addTest(testXRF("testXRFInstantiation"))
        testSuite.addTest(testXRF("testXRFResults"))
    return testSuite

def test(auto=False):
    unittest.TextTestRunner(verbosity=2).run(getSuite(auto=auto))

if __name__ == '__main__':
    test()