File: nuclides.py

package info (click to toggle)
xraylib 4.0.0%2Bdfsg1-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 46,936 kB
  • sloc: ansic: 16,103; f90: 8,746; java: 6,766; python: 1,497; cpp: 1,305; pascal: 1,139; makefile: 809; ruby: 622; php: 594; perl: 573; cs: 193; sh: 125
file content (298 lines) | stat: -rwxr-xr-x 13,239 bytes parent folder | download | duplicates (2)
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
#!/usr/bin/env python3


import urllib.request
from io import StringIO
import lxml.etree as ET
import re
import xraylib as xrl

xrl.SetErrorMessages(0)

lbl_url = "http://nucleardata.nuclear.lu.se/toi/nuclide.asp?iZA="

nuclide_codes = sorted(("260055", "940238", "960244", "480109", "530125", "950241", "640153", "270057", "560133", "550137"))

with open("../../src/xraylib-radionuclides-internal.h", "w") as output_int, open("../../include/xraylib-radionuclides.h", "w") as output_header:


    header_begin = '''/*
Copyright (c) 2014-2018, Tom Schoonjans
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Tom Schoonjans ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Tom Schoonjans BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*
 * This file was automatically generated by nuclides.pl
 * Modify at your own risk...
 */


#ifndef XRAYLIB_RADIO_NUCLIDES_H
#define XRAYLIB_RADIO_NUCLIDES_H

#include "xraylib-error.h"

/* 
 * name: a string containing the mass number (A), followed by the chemical element (e.g. 55Fe)
 * Z: atomic number of the radionuclide
 * A: mass number of the radionuclide
 * N: number of neutrons of the radionuclide
 * Z_xray: atomic number of the nuclide after decay, and which should be used in calculating the energy of the emitted X-ray lines
 * nXrays: number of emitted characteristic X-rays
 * XrayLines: array of *_LINE macros, identifying the emitted X-rays
 * XrayIntensities: array of photons per disintegration, one value per emitted X-ray
 * nGammas: number of emitted gamma-rays
 * GammaEnergies: array of emitted gamma-ray energies
 * GammaIntensities: array of emitted gamma-ray photons per disintegration
 */

struct radioNuclideData{
	char *name;
	int Z;
	int A;
	int N;
	int Z_xray;
	int nXrays;
	int *XrayLines;
	double *XrayIntensities;
	int nGammas;
	double *GammaEnergies;
	double *GammaIntensities;
};


/*
 *
 * Returns a pointer to a newly allocated struct containing
 * the requested radionuclide on success, or NULL when the radionuclide 
 * was not found in the list. The radionuclide is requested by providing
 * its name as argument to the function. For a list of available names,
 * use GetRadioNuclideList.
 *
 * The returned struct should be freed after usage with FreeRadioNuclideData.
 *
 */
XRL_EXTERN
struct radioNuclideData *GetRadioNuclideDataByName(const char radioNuclideString[], xrl_error **error);

/*
 *
 * Returns a pointer to a newly allocated struct containing
 * the requested radionuclide on success, or NULL when the radionuclide
 * was not found in the list. The radionuclide is requested by providing
 * its index in the internal table to the function. Typically this would
 * be done using the RADIO_NUCLIDE_* macros in this file.
 *
 * The returned struct should be freed after usage with FreeRadioNuclideData.
 *
 */
XRL_EXTERN
struct radioNuclideData *GetRadioNuclideDataByIndex(int radioNuclideIndex, xrl_error **error);

/*
 *
 * Returns a NULL-terminated array of strings of all the radionuclides in the
 * internal table. If nRadioNuclides is not NULL, it shall receive the number 
 * of radionuclides.
 *
 * The returned array should be freed firstly by using xrlFree to deallocate
 * all individual strings, and subsequently by using xrlFree to deallocate the array
 *
 */
XRL_EXTERN
char **GetRadioNuclideDataList(int *nRadioNuclides, xrl_error **error);

/*
 *
 * Deallocates a pointer to a radioNuclideData struct completely.
 * It is recommended to set the pointer to NULL after calling this function.
 *
 */
XRL_EXTERN
void FreeRadioNuclideData(struct radioNuclideData *radioNuclideData);

'''

    output_header.write(header_begin)

    header_begin2 = '''/*
Copyright (c) 2014-2018, Tom Schoonjans
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
    * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
    * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
    * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY Tom Schoonjans ''AS IS'' AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL Tom Schoonjans BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

/*
 * This file was automatically generated by nuclides.pl
 * Modify at your own risk...
 */

#include "xraylib.h"
#include "xraylib-error-private.h"

'''
    output_int.write(header_begin2)


    nuclideData = []

    for nuclideIndex, nuclide_code in enumerate(nuclide_codes):
        print(nuclide_code)
        url = lbl_url + nuclide_code
        print("url: {}".format(url))

        try:
            response = urllib.request.urlopen(url)
            html = response.read().decode("utf-8")

            # fix html file
            html = re.sub(r"(<\/FONT>\r\n)<\/FONT>", r"\1", html)
            html = re.sub(r"(Tables:<\/A>)<\/FONT>", r"\1", html)
            html = re.sub(r"(ENSDF data:<\/A>)<\/FONT>", r"\1", html)
            html = re.sub(r"(Java applets:<\/A>)<\/FONT>", r"\1", html)
            html = re.sub(r"(TORI Data \(1999\))(<\/font>)(<\/I>)", r"\1\3\2", html)
            html = re.sub(r"(<\/B>)(<\/FONT>)(<P>)", r"\2\1\3", html)
            html = re.sub(r"&nbsp;<I>.+<\/I>&nbsp;", "", html)
            html = re.sub(r"&nbsp;<i>.+<\/i>&nbsp;", "", html)
            html = re.sub(r"/&nbsp;", "", html)
            html = re.sub(r"(<TD>)<\d.+(<\/TD>)", r"\1\2", html)

            parser = ET.HTMLParser()
            tree = ET.parse(StringIO(html), parser)

            xpath_Z = "/html/body/center/table/tr[3]/td[2]/center/table[1]/caption/table/tr[2]/th[1]/font/text()";
            xpath_A = "/html/body/center/table/tr[3]/td[2]/center/table[1]/caption/table/tr[1]/th[1]/font/text()";
            xpath_N = "/html/body/center/table/tr[3]/td[2]/center/table[1]/caption/table/tr[2]/th[2]/font/text()";

            nuclideDataSingle = dict()

            Z = tree.xpath(xpath_Z)[0]
            A = tree.xpath(xpath_A)[0]
            N = tree.xpath(xpath_N)[0]
            print("Z: {}".format(Z))
            print("A: {}".format(A))
            print("N: {}".format(N))

            nuclideDataSingle['Z'] = Z
            nuclideDataSingle['A'] = A
            nuclideDataSingle['N'] = N
            nuclideDataSingle['name'] = "{}{}".format(A, xrl.AtomicNumberToSymbol(int(Z)))

            ##gamma stuff
            xpath_gamma = "/html/body/center/table/tr[3]/td[2]/center/table[3]/tr[position() >= 4 and position() < count(/html/body/center/table/tr[3]/td[2]/center/table[3]/tr)]"
            gamma_nodes = tree.xpath(xpath_gamma)

            print("gamma nodes number: {}".format(len(gamma_nodes)))

            gamma_energies = []
            gamma_intensities = []

            for node in gamma_nodes:
                try:
                    gamma_intensity = node.xpath("td[2]/text()")[0]
                    gamma_intensity = float(gamma_intensity)
                    gamma_energies.append(node.xpath("td[1]/text()")[0].strip())
                    gamma_intensities.append("{:g}".format(gamma_intensity / 100.0))
                except Exception:
                    pass

            nuclideDataSingle['nGammas'] = len(gamma_energies)
            nuclideDataSingle['gammaEnergies'] = gamma_energies
            nuclideDataSingle['gammaIntensities'] = gamma_intensities
            print("nGammas: {}".format(nuclideDataSingle['nGammas']))


            ##X-rays
            xpath_xray= "/html/body/center/table/tr[3]/td[2]/center/table[4]/tr[position() >= 4 and position() <= count(/html/body/center/table/tr[3]/td[2]/center/table[4]/tr)]"
            xray_nodes = tree.xpath(xpath_xray)

            print("xray nodes number: {}".format(len(xray_nodes)))

            xray_lines = []
            xray_intensities = []

            # extract X-ray element
            Z_xray = xray_nodes[0].xpath("td[3]/text()")[0][0:2]
            if not Z_xray[1].isalpha() or not Z_xray[1].islower():
                Z_xray = Z_xray[0]
            print("Z_xray: {}".format(Z_xray))
            nuclideDataSingle['Z_xray'] = xrl.SymbolToAtomicNumber(Z_xray)

            for node in xray_nodes:
                xray_intensity = node.xpath("td[2]/text()")[0]
                line = node.xpath("td[3]/text()")[0]
                line = line.replace(Z_xray, "")
                line_major = line.upper()
                line_minor = node.xpath("td[3]/sub/*/text()")[0].upper()
                try:
                    line_micro = node.xpath("td[3]/sub/text()")[0].upper()
                except IndexError:
                    line_micro = ""
                line = line_major + line_minor + line_micro + "_LINE"
                line = line.strip()
                print("line: {}".format(line))
                try:
                    xray_intensity = float(xray_intensity)
                    xray_energy = xrl.LineEnergy(nuclideDataSingle['Z_xray'], getattr(xrl, line))
                    if xray_energy == 0.0:
                        raise Exception("LineEnergy not found for {} {}", nuclideDataSingle['Z_xray'], line)
                    print("Energies: {}  {}".format(node.xpath("td[1]/text()")[0], xray_energy))
                    xray_intensities.append("{:g}".format(xray_intensity/100.0))
                    xray_lines.append(line)
                except Exception as e:
                    print("Exception: " + str(e))

            nuclideDataSingle['nXrays'] = len(xray_intensities)
            print("nXrays: {}".format(nuclideDataSingle['nXrays']))
            nuclideDataSingle['xrayIntensities'] = xray_intensities
            nuclideDataSingle['xrayLines'] = xray_lines

            output_header.write("#define RADIO_NUCLIDE_{} {}\n".format(nuclideDataSingle['name'].upper(), nuclideIndex))
            nuclideData.append(nuclideDataSingle)
        except Exception as e:
            print(e)
            raise


    output_int.write("static const int nNuclideDataList = {};\n".format(len(nuclideData)))

    for i, nd in enumerate(nuclideData):
        output_int.write("static int __NuclideDataList_XrayLines_{}[] = {{{}}};\n".format(i, ", ".join(nd['xrayLines'])))
        output_int.write("static double __NuclideDataList_XrayIntensities_{}[] = {{{}}};\n".format(i, ", ".join(nd['xrayIntensities'])))
        output_int.write("static double __NuclideDataList_GammaEnergies_{}[] = {{{}}};\n".format(i, ", ".join(nd['gammaEnergies'])))
        output_int.write("static double __NuclideDataList_GammaIntensities_{}[] = {{{}}};\n".format(i, ", ".join(nd['gammaIntensities'])))

    output_int.write("static const struct radioNuclideData nuclideDataList[] = {\n")
    ls = ["{{\"{}\" ,{}, {}, {}, {}, {}, __NuclideDataList_XrayLines_{}, __NuclideDataList_XrayIntensities_{}, {}, __NuclideDataList_GammaEnergies_{}, __NuclideDataList_GammaIntensities_{}}}".format( \
        nd['name'], \
	nd['Z'], \
        nd['A'], \
        nd['N'], \
        nd['Z_xray'], \
        nd['nXrays'], \
        i, \
        i, \
        nd['nGammas'], \
        i, \
        i) for i, nd in enumerate(nuclideData)]
    output_int.write(",\n".join(ls) + "\n")

    output_int.write("};\n")

    output_header.write("\n#endif\n")