/usr/share/pyshared/PyMca/SpecFileStack.py is in pymca 4.5.0-4.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
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 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 | #/*##########################################################################
# Copyright (C) 2004-2011 European Synchrotron Radiation Facility
#
# This file is part of the PyMCA X-ray Fluorescence Toolkit developed at
# the ESRF by the Beamline Instrumentation Software Support (BLISS) group.
#
# This toolkit is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by the Free
# Software Foundation; either version 2 of the License, or (at your option)
# any later version.
#
# PyMCA is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
# details.
#
# You should have received a copy of the GNU General Public License along with
# PyMCA; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
# Suite 330, Boston, MA 02111-1307, USA.
#
# PyMCA follows the dual licensing model of Trolltech's Qt and Riverbank's PyQt
# and cannot be used as a free plugin for a non-free program.
#
# Please contact the ESRF industrial unit (industry@esrf.fr) if this license
# is a problem for you.
#############################################################################*/
import DataObject
import specfilewrapper as specfile
import SpecFileDataSource
import numpy.oldnumeric as Numeric
import numpy
import sys
import os
HDF5 = False
try:
import h5py
HDF5 = True
except:
pass
SOURCE_TYPE = "SpecFileStack"
DEBUG = 0
X_AXIS=0
Y_AXIS=1
Z_AXIS=2
class SpecFileStack(DataObject.DataObject):
def __init__(self, filelist = None):
DataObject.DataObject.__init__(self)
self.incrProgressBar=0
self.__keyList = []
if filelist is not None:
if type(filelist) != type([]):
filelist = [filelist]
if len(filelist) == 1:
self.loadIndexedStack(filelist)
else:
self.loadFileList(filelist)
def loadFileList(self, filelist, fileindex=0, shape=None):
if type(filelist) == type(''):
filelist = [filelist]
self.__keyList = []
self.sourceName = filelist
self.__indexedStack = True
self.sourceType = SOURCE_TYPE
self.info = {}
self.nbFiles=len(filelist)
#read first file
#get information
tempInstance=SpecFileDataSource.SpecFileDataSource(filelist[0])
keylist = tempInstance.getSourceInfo()['KeyList']
nscans = len(keylist) #that is the number of scans
nmca = 0
numberofdetectors = 0
for key in keylist:
info = tempInstance.getKeyInfo(key)
numberofmca = info['NbMca']
if numberofmca > 0:
numberofdetectors = info['NbMcaDet']
scantype = info["ScanType"]
if numberofmca:
nmca += numberofmca
if numberofdetectors == 0:
raise ValueError("No MCA found in file %s" % filelist[0])
if (nscans > 1) and ((nmca/numberofdetectors) == nscans):
SLOW_METHOD = True
else:
SLOW_METHOD = False
#get last mca of first point
key = "%s.1.%s" % (keylist[-1], numberofmca)
dataObject = tempInstance._getMcaData(key)
self.info.update(dataObject.info)
arrRet = dataObject.data
self.onBegin(self.nbFiles*nmca/numberofdetectors)
self.incrProgressBar= 0
if info['NbMcaDet'] > 1:
#Should I generate a map for each mca and not just for the last one as I am doing?
iterlist = range(info['NbMcaDet'],info['NbMca']+1,info['NbMcaDet'])
else:
iterlist = [1]
if SLOW_METHOD and shape is None:
self.data = Numeric.zeros((self.nbFiles,
nmca/numberofdetectors,
arrRet.shape[0]),
arrRet.dtype.char)
filecounter = 0
for tempFileName in filelist:
tempInstance=SpecFileDataSource.SpecFileDataSource(tempFileName)
mca_number = -1
for keyindex in keylist:
info = tempInstance.getKeyInfo(keyindex)
numberofmca = info['NbMca']
if numberofmca <= 0:
continue
key = "%s.1.%s" % (keyindex, numberofmca)
dataObject = tempInstance._getMcaData(key)
arrRet = dataObject.data
mca_number += 1
for i in iterlist:
#mcadata = scan_obj.mca(i)
self.data[filecounter,
mca_number,
:] = arrRet[:]
self.incrProgressBar += 1
self.onProgress(self.incrProgressBar)
filecounter += 1
elif shape is None and (self.nbFiles == 1) and (iterlist == [1]):
#it can only be here if there is one file
#it can only be here if there is only one scan
#it can only be here if there is only one detector
self.data = Numeric.zeros((1,
numberofmca,
arrRet.shape[0]),
arrRet.dtype.char)
for tempFileName in filelist:
tempInstance=specfile.Specfile(tempFileName)
#it can only be here if there is one scan per file
#prevent problems if the scan number is different
#scan = tempInstance.select(keylist[-1])
scan = tempInstance[0]
iterationList = range(scan.nbmca())
for i in iterationList:
#mcadata = scan_obj.mca(i)
self.data[0,
i,
:] = scan.mca(i+1)[:]
self.incrProgressBar += 1
self.onProgress(self.incrProgressBar)
filecounter = 1
elif shape is None:
#it can only be here if there is one scan per file
try:
self.data = Numeric.zeros((self.nbFiles,
numberofmca/numberofdetectors,
arrRet.shape[0]),
arrRet.dtype.char)
filecounter = 0
for tempFileName in filelist:
tempInstance=specfile.Specfile(tempFileName)
#it can only be here if there is one scan per file
#prevent problems if the scan number is different
#scan = tempInstance.select(keylist[-1])
scan = tempInstance[0]
for i in iterlist:
#mcadata = scan_obj.mca(i)
self.data[filecounter,
0,
:] = scan.mca(i)[:]
self.incrProgressBar += 1
self.onProgress(self.incrProgressBar)
filecounter += 1
except MemoryError:
qtflag = False
if ('PyQt4.QtCore' in sys.modules) or\
('PyMcaQt' in sys.modules) or\
('PyMca.PyMcaQt' in sys.modules):
qtflag = True
hdf5done = False
if HDF5 and qtflag:
import PyMcaQt as qt
import ArraySave
msg=qt.QMessageBox.information( None,
"Memory error\n",
"Do you want to convert your data to HDF5?\n",
qt.QMessageBox.Yes,qt.QMessageBox.No)
if msg != qt.QMessageBox.No:
hdf5file = qt.QFileDialog.getSaveFileName(None,
"Please select output file name",
os.path.dirname(filelist[0]),
"HDF5 files *.h5")
if not len(hdf5file):
raise IOError("Invalid output file")
hdf5file = str(hdf5file)
if not hdf5file.endswith(".h5"):
hdf5file += ".h5"
#get the final shape
from PyMca.RGBCorrelatorWidget import ImageShapeDialog
stackImageShape = self.nbFiles,\
int(numberofmca/numberofdetectors)
dialog = ImageShapeDialog(None, shape =stackImageShape)
dialog.setModal(True)
ret = dialog.exec_()
if ret:
stackImageShape= dialog.getImageShape()
dialog.close()
del dialog
hdf, self.data = ArraySave.getHDF5FileInstanceAndBuffer(hdf5file,
(stackImageShape[0],
stackImageShape[1],
arrRet.shape[0]),
compression=None,
interpretation="spectrum")
nRow = 0
nCol = 0
for tempFileName in filelist:
tempInstance=specfile.Specfile(tempFileName)
#it can only be here if there is one scan per file
#prevent problems if the scan number is different
#scan = tempInstance.select(keylist[-1])
scan = tempInstance[0]
nRow = int(self.incrProgressBar/stackImageShape[1])
nCol = self.incrProgressBar%stackImageShape[1]
for i in iterlist:
#mcadata = scan_obj.mca(i)
self.data[nRow,
nCol,
:] = scan.mca(i)[:]
self.incrProgressBar += 1
self.onProgress(self.incrProgressBar)
hdf5done = True
hdf.flush()
self.onEnd()
self.info["SourceType"] = "HDF5Stack1D"
self.info["McaIndex"] = 2
self.info["FileIndex"] = 0
self.info["SourceName"] = [hdf5file]
self.info["NumberOfFiles"] = 1
self.info["Size"] = 1
return
else:
raise
else:
sampling_order = 1
s0 = shape[0]
s1 = shape[1]
MEMORY_ERROR = False
try:
self.data = Numeric.zeros((shape[0],
shape[1],
arrRet.shape[0]),
arrRet.dtype.char)
except MemoryError:
try:
self.data = numpy.zeros((shape[0],
shape[1],
arrRet.shape[0]),
numpy.float32)
except MemoryError:
MEMORY_ERROR = True
while MEMORY_ERROR:
try:
for i in range(5):
print("\7")
sampling_order += 1
print("**************************************************")
print(" Memory error!, attempting %dx%d sub-sampling " %\
(sampling_order, sampling_order))
print("**************************************************")
s0 = int(shape[0]/sampling_order)
s1 = int(shape[1]/sampling_order)
#if shape[0] % sampling_order:
# s0 = s0 + 1
#if shape[1] % sampling_order:
# s1 = s1 + 1
self.data = numpy.zeros((s0, s1,
arrRet.shape[0]),
numpy.float32)
MEMORY_ERROR = False
except MemoryError:
pass
filecounter = 0
for j in range(s0):
filecounter = (j * sampling_order) * shape[1]
for k in range(s1):
tempFileName = filelist[filecounter]
tempInstance=specfile.Specfile(tempFileName)
if tempInstance is None:
if not os.path.exists(tempFileName):
print("File %s does not exists" % tempFileName)
raise IOError(\
"File %s does not exists" % tempFileName)
scan = tempInstance.select(keylist[-1])
for i in iterlist:
#sum the present mcas
self.data[j,
k,
:] += scan.mca(i)[:]
self.incrProgressBar += 1
self.onProgress(self.incrProgressBar)
filecounter += sampling_order
self.nbFiles = s0 * s1
self.onEnd()
"""
# Scan types
# ----------
#SF_EMPTY = 0 # empty scan
#SF_SCAN = 1 # non-empty scan
#SF_MESH = 2 # mesh scan
#SF_MCA = 4 # single mca
#SF_NMCA = 8 # multi mca (more than 1 mca per acq)
case = None
if scantype == (SpecFileDataSource.SF_MESH + \
SpecFileDataSource.SF_MCA):
# SINGLE MESH + SINGLE MCA
# nfiles = 1
# nscans = 1
# nmca = 1
# there is a danger if it can be considered an indexed file ...
pass
elif scantype == (SpecFileDataSource.SF_MESH + \
SpecFileDataSource.SF_NMCA):
# SINGLE MESH + MULTIPLE MCA
# nfiles = 1
# nscans = 1
# nmca > 1
# there is a danger if it can be considered an indexed file ...
#for the time being I take last mca
pass
elif scantype == (SpecFileDataSource.SF_SCAN+ \
SpecFileDataSource.SF_MCA):
#Assumed scans containing always 1 detector
pass
elif scantype == (SpecFileDataSource.SF_MCA):
#Assumed scans containing always 1 detector
pass
elif scantype == (SpecFileDataSource.SF_SCAN+ \
SpecFileDataSource.SF_NMCA):
#Assumed scans containing the same number of detectors
#for the time being I take last mca
pass
elif scantype == (SpecFileDataSource.SF_NMCA):
#Assumed scans containing the same number of detectors
#for the time being I take last mca
pass
else:
raise ValueError, "Unhandled scan type = %s" % scantype
"""
self.__nFiles = self.nbFiles
self.__nImagesPerFile = 1
shape = self.data.shape
for i in range(len(shape)):
key = 'Dim_%d' % (i+1,)
self.info[key] = shape[i]
self.info["SourceType"] = SOURCE_TYPE
self.info["SourceName"] = self.sourceName
self.info["Size"] = self.__nFiles * self.__nImagesPerFile
self.info["NumberOfFiles"] = self.__nFiles * 1
self.info["FileIndex"] = fileindex
def onBegin(self, n):
pass
def onProgress(self, n):
pass
def onEnd(self):
pass
def loadIndexedStack(self,filename,begin=None,end=None, skip = None, fileindex=0):
#if begin is None: begin = 0
if type(filename) == type([]):
filename = filename[0]
if not os.path.exists(filename):
raise IOError("File %s does not exists" % filename)
name = os.path.basename(filename)
n = len(name)
i = 1
numbers = ['0', '1', '2', '3', '4', '5',
'6', '7', '8','9']
while (i <= n):
c = name[n-i:n-i+1]
if c in ['0', '1', '2',
'3', '4', '5',
'6', '7', '8',
'9']:
break
i += 1
suffix = name[n-i+1:]
if len(name) == len(suffix):
#just one file, one should use standard widget
#and not this one.
self.loadFileList(filename, fileindex=fileindex)
else:
nchain = []
while (i<=n):
c = name[n-i:n-i+1]
if c not in ['0', '1', '2',
'3', '4', '5',
'6', '7', '8',
'9']:
break
else:
nchain.append(c)
i += 1
number = ""
nchain.reverse()
for c in nchain:
number += c
fformat = "%" + "0%dd" % len(number)
if (len(number) + len(suffix)) == len(name):
prefix = ""
else:
prefix = name[0:n-i+1]
prefix = os.path.join(os.path.dirname(filename),prefix)
if not os.path.exists(prefix + number + suffix):
print("Internal error in EDFStack")
print("file should exist: %s" % (prefix + number + suffix))
return
i = 0
if begin is None:
begin = 0
testname = prefix+ fformat % begin+suffix
while not os.path.exists(prefix + fformat % begin+suffix):
begin += 1
testname = prefix + fformat % begin+suffix
if len(testname) > len(filename):break
i = begin
else:
i = begin
if not os.path.exists(prefix+ fformat % i+suffix):
raise ValueError("Invalid start index file = %s" % \
(prefix+ fformat % i+suffix))
f = prefix + fformat % i+suffix
filelist = []
while os.path.exists(f):
filelist.append(f)
i += 1
if end is not None:
if i > end:
break
f = prefix + fformat % i+suffix
self.loadFileList(filelist, fileindex=fileindex)
def getSourceInfo(self):
sourceInfo = {}
sourceInfo["SourceType"]=SOURCE_TYPE
if self.__keyList == []:
for i in range(1, self.__nFiles + 1):
for j in range(1, self.__nImages + 1):
self.__keyList.append("%d.%d" % (i,j))
sourceInfo["KeyList"]= self.__keyList
def getKeyInfo(self, key):
print("Not implemented")
return {}
def isIndexedStack(self):
return self.__indexedStack
def getZSelectionArray(self,z=0):
return (self.data[:,:,z]).astype(Numeric.Float)
def getXYSelectionArray(self,coord=(0,0)):
x,y=coord
return (self.data[y,x,:]).astype(Numeric.Float)
if __name__ == "__main__":
import time
import sys
t0= time.time()
stack = SpecFileStack()
#stack.loadIndexedStack("Z:\COTTE\ch09\ch09__mca_0005_0000_0070.edf")
if len(sys.argv) > 1:
stack.loadIndexedStack(sys.argv[1])
else:
stack.loadIndexedStack("..\..\mca3\c449b01_001.mca")
shape = stack.data.shape
print("elapsed = %f" % (time.time() - t0))
#guess the MCA
imax = 0
for i in range(len(shape)):
if shape[i] > shape[imax]:
imax = i
print("selections ")
print("getZSelectionArray shape = ", stack.getZSelectionArray().shape)
print("getXYSelectionArray shape = ", stack.getXYSelectionArray().shape)
import PyMcaQt as qt
app = qt.QApplication([])
qt.QObject.connect(app, qt.SIGNAL("lastWindowClosed()"),
app, qt.SLOT("quit()"))
if 1:
import RGBCorrelatorGraph
w = RGBCorrelatorGraph.RGBCorrelatorGraph()
graph = w.graph
else:
import QtBlissGraph
w = QtBlissGraph.QtBlissGraph()
graph = w
print("shape sum 0 = ",Numeric.sum(stack.data, 0).shape)
print("shape sum 1 = ",Numeric.sum(stack.data, 1).shape)
print("shape sum 2 = ",Numeric.sum(stack.data, 2).shape)
a = Numeric.sum(stack.data, imax)
print(a.shape)
graph.setX1AxisLimits(0, a.shape[0])
if 0:
w.setY1AxisLimits(0, a.shape[1])
w.setY1AxisInverted(True)
else:
graph.setY1AxisInverted(True)
graph.setY1AxisLimits(0, a.shape[1])
graph.imagePlot(a, ymirror=0)
if imax == 0:
graph.x1Label('Column Number')
else:
graph.x1Label('Row Number')
graph.ylabel('File Number')
w.show()
if imax == 0:
mcaData0 = Numeric.sum(Numeric.sum(stack.data, 2),1)
else:
mcaData0 = Numeric.sum(Numeric.sum(stack.data, 2),0)
import McaWindow
mca = McaWindow.McaWidget()
sel = {}
sel['SourceName'] = "Specfile Stack"
sel['Key'] = "SUM"
sel['legend'] = "EDF Stack SUM"
mcaData = DataObject.DataObject()
mcaData.info = {'McaCalib': [0 , 2.0 ,0],
"selectiontype":"1D",
"SourceName":"Specfile Stack",
"Key":"SUM"}
mcaData.x = [Numeric.arange(len(mcaData0)).astype(Numeric.Float)]
mcaData.y = [mcaData0]
sel['dataobject'] = mcaData
mca.show()
mca._addSelection([sel])
graph.enableSelection(True)
def graphSlot(ddict):
if ddict['event'] == "MouseSelection":
ix1 = int(ddict['xmin'])
ix2 = int(ddict['xmax'])+1
iy1 = int(ddict['xmin'])
iy2 = int(ddict['xmax'])+1
if imax == 0:
selectedData = Numeric.sum(Numeric.sum(stack.data[:,ix1:ix2, iy1:iy2], 2),1)
else:
selectedData = Numeric.sum(Numeric.sum(stack.data[ix1:ix2,:, iy1:iy2], 2),0)
sel = {}
sel['SourceName'] = "Specfile Stack"
sel['Key'] = "Selection"
sel["selectiontype"] = "1D"
sel['legend'] = "EDF Stack Selection"
selDataObject = DataObject.DataObject()
selDataObject.info={'McaCalib': [100 , 2.0 ,0],
"selectiontype":"1D",
"SourceName":"EDF Stack Selection",
"Key":"Selection"}
selDataObject.x = [Numeric.arange(len(mcaData0)).astype(Numeric.Float)]
selDataObject.y = [selectedData]
sel['dataobject'] = selDataObject
mca._addSelection([sel])
qt.QObject.connect(graph, qt.SIGNAL('QtBlissGraphSignal'),
graphSlot)
#w.replot()
if qt.qVersion() < '4.0.0':
app.exec_loop()
else:
app.exec_()
|