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
|
#/*##########################################################################
#
# The PyMca X-Ray Fluorescence Toolkit
#
# Copyright (c) 2019 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__ = "Wout De Nolf"
__contact__ = "wout.de_nolf@esrf.eu"
__license__ = "MIT"
__copyright__ = "European Synchrotron Radiation Facility, Grenoble, France"
import numpy
import time
import os
import sys
import numbers
def generateXRFConfig(modfunc=None):
"""
:param callable modfunc: modify configuration on loading
:returns: ConfigDict
"""
from PyMca5.PyMcaDataDir import PYMCA_DATA_DIR as dataDir
from PyMca5.PyMcaIO import ConfigDict
configuration = ConfigDict.ConfigDict()
cfg = os.path.join(dataDir, "Steel.cfg")
configuration.read(cfg)
if modfunc is not None:
modfunc(configuration)
return configuration
def generateXRFData(nRows=5, nColumns=10, nDet=1, nTimes=3, presetTime=1, same=True):
"""
:param int nRows:
:param int nColumns:
:param int nDet:
:param int nTimes: number of different live times
:param int presetTime: exposure time for each spectrum
:param bool same: same spectrum in all pixels (add pixel index as constant background otherwise)
:returns: data(nRows, nColumns, nChannels), liveTime(nRows*nColumns)
"""
from PyMca5.PyMcaDataDir import PYMCA_DATA_DIR as dataDir
from PyMca5.PyMcaIO import specfilewrapper as specfile
spe = os.path.join(dataDir, "Steel.spe")
sf = specfile.Specfile(spe)
counts = sf[0].mca(1).astype(numpy.int32)
#counts = numpy.arange(counts.size, dtype=int) # for testing
data = numpy.zeros((nDet, nRows, nColumns, counts.size), dtype=counts.dtype)
liveTime = numpy.zeros((nDet, nRows, nColumns), dtype=numpy.float)
nTimes *= nDet
initialTime = presetTime
mcaIndex = 0
for i in range(nRows):
for j in range(nColumns):
for k in range(nDet):
if same:
data[k, i, j] = counts
else:
data[k, i, j] = counts + mcaIndex*nDet + k
liveTime[k, i, j] = initialTime * (1 + mcaIndex % nTimes)/float(nTimes)
mcaIndex += 1
return data, liveTime
def generate(modfunc=None, **kwargs):
"""
:param callable modfunc: modify configuration on loading
:param **kwargs: see `generateXRFData`
:returns dict: {configuration: ConfigDict,
data: ndarray(nDet, nRows, nColumns, nChannels),
liveTime: ndarray(nDet, nRows, nColumns),
presetTime: number}
"""
configuration = generateXRFConfig(modfunc=modfunc)
presetTime = configuration["concentrations"]["time"]
data, liveTime = generateXRFData(presetTime=presetTime, **kwargs)
return {'configuration': configuration,
'data': data,
'liveTime': liveTime,
'presetTime': presetTime}
def generateSpecMesh(filename, nmaps=1, **kwargs):
"""
:param str filename: save data under this name
:param num nmaps: number of mesh scans
:param **kwargs: see `generate`
:returns dict: {filelist: list(str),
configuration: ConfigDict,
data: ndarray(nDet, nRows, nColumns, nChannels),
liveTime: ndarray(nDet, nRows, nColumns),
presetTime: number}
"""
info = generate(**kwargs)
nDet, nRows, nColumns, nChannels = info['data'].shape
expoTime = info['presetTime']
zero = info['configuration']["detector"]["zero"]
gain = info['configuration']["detector"]["gain"]
command = 'mesh samy 0 %d %d samz 0 %d %d %g' % \
(nRows, nRows-1, nColumns, nColumns-1, expoTime)
if sys.version < "3.0":
mode = 'wb'
oparams = {}
else:
mode = 'w'
oparams = {'newline': ''}
with open(filename, mode, **oparams) as ffile:
ffile.write("#F %s\n" % filename)
ffile.write("#D %s\n" % (time.ctime(time.time())))
ffile.write("\n")
for scan in range(nmaps):
ffile.write("#S %d %s\n" % (scan+1, command))
ffile.write("#D %s\n" % (time.ctime(time.time())))
ffile.write("#@MCA %16C\n")
ffile.write("#@CHANN %d %d %d 1\n" % (nChannels, 0, nChannels-1))
ffile.write("#@CALIB %.7g %.7g %.7g\n" % (zero, gain, 0.0))
# Live time changes for each spectrum, so this doesn't work:
#ffile.write("#@CTIME %.7g %.7g %.7g\n" % (preset, live, real))
ffile.write("#L col row\n")
for i in range(nRows):
for j in range(nColumns):
ffile.write('%d %d\n' % (j, i))
for k in range(nDet):
ffile.write(mcaToSpecString(info['data'][k, i, j, :]))
ffile.write("\n")
basename = os.path.splitext(os.path.basename(filename))[0]
path = os.path.dirname(filename)
cfgname = os.path.join(path, basename+'.cfg')
info['configuration'].write(cfgname)
info['filelist'] = [filename]
return info
def generateEdfMap(filename, fastpulsefraction=0.01, **kwargs):
"""
Result of a digital pulse processor with fast and slow channel
for pile-up rejection and paralyzable deadtime.
:param str filename: save data under this name
:param num fastpulsefraction: ratio of fast pulse width (in time) over slow pulse width
:param **kwargs: see `generate`
:returns dict: {filelist: list(str),
configuration: ConfigDict,
data: ndarray(nDet, nRows, nColumns, nChannels),
liveTime: ndarray(nDet, nRows, nColumns),
presetTime: number}
"""
from PyMca5.PyMcaIO.EdfFile import EdfFile
info = generate(**kwargs)
nDet, nRows, nColumns, nChannels = info['data'].shape
Treal = float(info['configuration']["concentrations"]["time"])
nstats = 6
stats = numpy.empty((nRows, nColumns, nDet*nstats),
dtype=info['data'].dtype)
for k in range(nDet):
# Slow channel events
Nslow = info['data'][k, ...].sum(axis=-1)
LTslow = info['liveTime'][k, ...]
Rslow = Nslow/Treal
DTslow = 1-LTslow/Treal
Rreal = Rslow/LTslow*Treal
tauslow = -numpy.log(1-DTslow)/Rreal
# Fast channel events
taufast = tauslow*fastpulsefraction
factor = numpy.exp(-Rreal*taufast)
LTfast = Treal*factor
#Rfast = Rreal*factor
#DTfast = 1-Rfast/Rreal
stats[..., k*nstats+0] = k # detector index
stats[..., k*nstats+1] = Nslow # slow channel events
stats[..., k*nstats+2] = Rreal # real count rate (Hz)
stats[..., k*nstats+3] = Rslow # slow channel count rate (Hz)
stats[..., k*nstats+4] = LTfast*1000 # fast channel live time (msec)
stats[..., k*nstats+5] = DTslow*100 # dead time %
basename = os.path.splitext(os.path.basename(filename))[0]
path = os.path.dirname(filename)
cfgname = os.path.join(path, basename+'.cfg')
filelist = []
for i in range(nRows):
for k in range(nDet):
filename = os.path.join(path, '{}_xia{:02d}_0001_0000_{:04d}.edf'
.format(basename, k, i))
edf = EdfFile(filename, 'wb+')
edf.WriteImage({'time': Treal}, info['data'][k, i, ...])
edf = None
filelist.append(filename)
filename = os.path.join(path, '{}_xiast_0001_0000_{:04d}.edf'.format(basename, i))
edf = EdfFile(filename, 'wb+')
edf.WriteImage({'time': Treal}, stats[i, ...])
edf = None
info['configuration'].write(cfgname)
info['filelist'] = sorted(filelist)
return info
def generateHdf5Map(filename, **kwargs):
"""
:param str filename: save data under this name
:param **kwargs: see `generate`
:returns dict: {filelist: list(str),
configuration: ConfigDict,
data: ndarray(nDet, nRows, nColumns, nChannels),
liveTime: ndarray(nDet, nRows, nColumns),
presetTime: number}
"""
from PyMca5.PyMcaIO import NexusUtils
info = generate(**kwargs)
preset_time = info['configuration']["concentrations"]["time"]
basename = os.path.splitext(os.path.basename(filename))[0]
path = os.path.dirname(filename)
cfgname = os.path.join(path, basename+'.cfg')
with NexusUtils.nxRoot(filename, mode='w') as f:
entry = NexusUtils.nxEntry(f, basename)
instrument = NexusUtils.nxInstrument(entry)
xrf = NexusUtils.nxSubEntry(entry, 'xrf')
for iDet, (detData, detLT) in enumerate(zip(info['data'], info['liveTime'])):
name = 'mca{:02}'.format(iDet)
detector = NexusUtils.nxDetector(instrument, name)
detector['data'] = detData
detector['data'].attrs['interpretation'] = 'spectrum'
xdetector = NexusUtils.nxCollection(xrf, name)
xdetector['data'] = NexusUtils.h5py.SoftLink(detector['data'].name)
xdetector['preset_time'] = preset_time
xdetector['live_time'] = detLT
xdetector['live_time'].attrs['interpretation'] = 'image'
xdetector['live_time'].attrs['units'] = 's'
#nxprocess = NexusUtils.nxProcess(entry, 'fit')
#NexusUtils.nxProcessConfigurationInit(nxprocess, configdict=info['configuration'])
info['configuration'].write(cfgname)
info['filelist'] = [filename]
return info
def mcaToSpecString(mca):
"""
:param mca: vector(list or ndarray)
:returns str: formatted for spec file
"""
tmpstr = "@A"
length = len(mca)
nChanPerLine = 16
if isinstance(mca[0], numbers.Integral):
fmt = " %d"
else:
fmt = " %.4f"
for idx in range(0, length, nChanPerLine):
if idx+nChanPerLine-1 < length:
for i in range(0, nChanPerLine):
tmpstr += fmt % mca[idx+i]
if idx+nChanPerLine != length:
tmpstr += "\\"
else:
for i in range(idx, length):
tmpstr += fmt % mca[i]
tmpstr += "\n"
return tmpstr
|