/usr/share/pyshared/PyMca/StackSelector.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 | #!/usr/bin/env python
#/*##########################################################################
# Copyright (C) 2004-2012 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 sys
import os
import copy
from PyMca import PyMcaQt as qt
from PyMca import PyMcaDirs
from PyMca import DataObject
from PyMca import OmnicMap
from PyMca import OpusDPTMap
from PyMca import LuciaMap
from PyMca import SupaVisioMap
from PyMca import AifiraMap
from PyMca import TextImageStack
from PyMca import TiffStack
from PyMca.QEDFStackWidget import QStack, QSpecFileStack
try:
from PyMca import QHDF5Stack1D
import h5py
HDF5 = True
except ImportError:
HDF5 = False
pass
QTVERSION = qt.qVersion()
DEBUG = 0
class StackSelector(object):
def __init__(self, parent=None):
self.parent = parent
def getStack(self, filelist=None, imagestack=False):
if filelist in [None, []]:
filelist, filefilter = self._getStackOfFiles(getfilter=True)
else:
filefilter = ""
if not len(filelist):
return None
if filefilter == "":
if HDF5:
if h5py.is_hdf5(filelist[0]):
filefilter = "HDF5"
fileindex = 0
begin = None
end = None
aifirafile = False
if len(filelist):
PyMcaDirs.inputDir = os.path.dirname(filelist[0])
#if we are dealing with HDF5, no more tests needed
if not filefilter.upper().startswith('HDF5'):
f = open(filelist[0], 'rb')
#read 10 characters
if sys.version < '3.0':
line = f.read(10)
else:
line = str(f.read(10).decode())
f.close()
omnicfile = False
if filefilter.upper().startswith('HDF5'):
stack = QHDF5Stack1D.QHDF5Stack1D(filelist)
omnicfile = True
elif filefilter.upper().startswith('OPUS-DPT'):
stack = OpusDPTMap.OpusDPTMap(filelist[0])
omnicfile = True
elif filefilter.upper().startswith("AIFIRA"):
stack = AifiraMap.AifiraMap(filelist[0])
omnicfile = True
aifirafile = True
elif filefilter.upper().startswith("SUPAVISIO"):
stack = SupaVisioMap.SupaVisioMap(filelist[0])
omnicfile = True
elif filefilter.upper().startswith("TEXTIMAGE"):
imagestack = True
fileindex = 0
stack = TextImageStack.TextImageStack(imagestack=True)
elif filefilter.upper().startswith("IMAGE") and\
(filelist[0].upper().endswith("TIF") or\
filelist[0].upper().endswith("TIFF")):
stack = TiffStack.TiffStack(imagestack=True)
elif filefilter == "" and\
(filelist[0].upper().endswith("TIF") or\
filelist[0].upper().endswith("TIFF")):
stack = TiffStack.TiffStack(imagestack=True)
elif filefilter.upper().startswith("IMAGE"):
imagestack = True
fileindex = 0
stack = QStack(imagestack=True)
elif line[0] == "{":
stack = QStack(imagestack=imagestack)
elif line[0:2] in ["II", "MM"]:
stack = QStack(imagestack=True)
elif line.startswith('Spectral'):
stack = OmnicMap.OmnicMap(filelist[0])
omnicfile = True
elif line.startswith('#\tDate'):
stack = LuciaMap.LuciaMap(filelist[0])
omnicfile = True
elif filelist[0][-4:].upper() in ["PIGE", "PIGE"]:
stack = SupaVisioMap.SupaVisioMap(filelist[0])
omnicfile = True
elif filelist[0][-3:].upper() in ["RBS"]:
stack = SupaVisioMap.SupaVisioMap(filelist[0])
omnicfile = True
elif filelist[0][-3:].upper() in ["SPE"] and\
(line[0] not in ['$']):
#Roper Scientific format
#handle it as MarCCD stack
stack = QStack(imagestack=True)
else:
stack = QSpecFileStack()
if len(filelist) == 1:
if not omnicfile:
try:
stack.loadIndexedStack(filelist[0], begin, end,
fileindex=fileindex)
except:
msg = qt.QMessageBox()
msg.setIcon(qt.QMessageBox.Critical)
msg.setText("%s" % sys.exc_info()[1])
if QTVERSION < '4.0.0':
msg.exec_loop()
else:
msg.exec_()
if DEBUG:
raise
elif len(filelist):
if not omnicfile:
try:
stack.loadFileList(filelist, fileindex=fileindex)
except:
msg = qt.QMessageBox()
msg.setIcon(qt.QMessageBox.Critical)
msg.setText("%s" % sys.exc_info()[1])
if QTVERSION < '4.0.0':
msg.exec_loop()
else:
msg.exec_()
if DEBUG:
raise
if aifirafile:
masterStack = DataObject.DataObject()
masterStack.info = copy.deepcopy(stack.info)
masterStack.data = stack.data[:,:,0:1024]
masterStack.info['Dim_2'] = int(masterStack.info['Dim_2'] / 2)
slaveStack = DataObject.DataObject()
slaveStack.info = copy.deepcopy(stack.info)
slaveStack.data = stack.data[:,:, 1024:]
slaveStack.info['Dim_2'] = int(slaveStack.info['Dim_2'] / 2)
return [masterStack, slaveStack]
else:
return stack
def getStackFromPattern(self, filepattern, begin, end, increment=None,
imagestack=None, fileindex=0):
#get the first filename
filename = filepattern % tuple(begin)
if not os.path.exists(filename):
raise IOError("Filename %s does not exist." % filename)
#get the file list
args = self.getFileListFromPattern(filepattern, begin, end, increment=increment)
#get the file type
f = open(args[0], 'rb')
#read 10 characters
line = f.read(10)
f.close()
specfile = False
omnicfile = False
marCCD = False
if line.startswith("II") or line.startswith("MM"):
marCCD= True
if line[0] == "\n":
line = line[1:]
if (line[0] == "{") or marCCD:
if imagestack is None:
if marCCD:
imagestack = True
if imagestack:
#prevent any modification
fileindex = 0
if filepattern is not None:
#this dows not seem to put any trouble
#(because of no redimensioning attempt)
if False and (len(begin) != 1):
raise IOError("EDF stack redimensioning not supported yet")
stack = QStack(imagestack=imagestack)
elif line.startswith('Spectral'):
stack = OmnicMap.OmnicMap(args[0])
omnicfile = True
elif line.startswith('#\tDate:'):
stack = LuciaMap.LuciaMap(args[0])
omnicfile = True
elif args[0][-4:].upper() in ["PIGE", "PIXE"]:
stack = SupaVisioMap.SupaVisioMap(args[0])
omnicfile = True
elif args[0][-3:].upper() in ["RBS"]:
stack = SupaVisioMap.SupaVisioMap(args[0])
omnicfile = True
elif args[0][-3:].lower() in [".h5", "nxs", "hdf"]:
if not HDF5:
raise IOError(\
"No HDF5 support while trying to read an HDF5 file")
stack = QHDF5Stack1D.QHDF5Stack1D(args)
omnicfile = True
else:
if HDF5:
if h5py.is_hdf5(args[0]):
stack = QHDF5Stack1D.QHDF5Stack1D(args)
omnicfile = True
else:
stack = QSpecFileStack()
specfile = True
else:
stack = QSpecFileStack()
specfile = True
if specfile and (len(begin) == 2):
if increment is None:
increment = [1] * len(begin)
shape = (len(range(begin[0], end[0]+1, increment[0])),
len(range(begin[1], end[1]+1, increment[1])))
stack.loadFileList(args, fileindex=fileindex, shape=shape)
else:
stack.loadFileList(args, fileindex=fileindex)
return stack
def _getFileList(self, fileTypeList, message=None, getfilter=None):
if message is None:
message = "Please select a file"
if getfilter is None:
getfilter = False
wdir = PyMcaDirs.inputDir
filterused = None
if QTVERSION < '4.0.0':
if sys.platform != 'darwin':
filetypes = ""
for filetype in fileTypeList:
filetypes += filetype+"\n"
filelist = qt.QFileDialog.getOpenFileNames(filetypes,
wdir,
self.parent,
message,
message)
if not len(filelist):
if getfilter:
return [], filterused
else:
return []
else:
#if (QTVERSION < '4.3.0') and (sys.platform != 'darwin'):
if (PyMcaDirs.nativeFileDialogs) and (not getfilter):
filetypes = ""
for filetype in fileTypeList:
filetypes += filetype+"\n"
filelist = qt.QFileDialog.getOpenFileNames(self.parent,
message,
wdir,
filetypes)
if not len(filelist):
if getfilter:
return [], filterused
else:
return []
else:
sample = str(filelist[0])
for filetype in fileTypeList:
ftype = filetype.replace("(", "")
ftype = ftype.replace(")", "")
extensions = ftype.split()[2:]
for extension in extensions:
if sample.endswith(extension[-3:]):
filterused = filetype
break
else:
fdialog = qt.QFileDialog(self.parent)
fdialog.setModal(True)
fdialog.setWindowTitle(message)
if hasattr(qt, "QStringList"):
strlist = qt.QStringList()
else:
strlist = []
for filetype in fileTypeList:
strlist.append(filetype)
fdialog.setFilters(strlist)
fdialog.setFileMode(fdialog.ExistingFiles)
fdialog.setDirectory(wdir)
if QTVERSION > '4.3.0':
history = fdialog.history()
if len(history) > 6:
fdialog.setHistory(history[-6:])
ret = fdialog.exec_()
if ret == qt.QDialog.Accepted:
filelist = fdialog.selectedFiles()
if getfilter:
filterused = str(fdialog.selectedFilter())
fdialog.close()
del fdialog
else:
fdialog.close()
del fdialog
if getfilter:
return [], filterused
else:
return []
if sys.version < '3.0':
try:
filelist = [str(x) for x in filelist]
except UnicodeEncodeError:
filelist = [unicode(x) for x in filelist]
if not(len(filelist)): return []
PyMcaDirs.inputDir = os.path.dirname(filelist[0])
if PyMcaDirs.outputDir is None:
PyMcaDirs.outputDir = os.path.dirname(filelist[0])
#This should not be there in order to allow the user other choices
#filelist.sort()
if getfilter:
return filelist, filterused
else:
return filelist
def _getStackOfFiles(self, getfilter=None):
if getfilter is None:
getfilter = False
fileTypeList = ["EDF Files (*edf)",
"EDF Files (*ccd)",
"Specfile Files (*mca)",
"Specfile Files (*dat)",
"OMNIC Files (*map)",
"OPUS-DPT Files (*.DPT *.dpt)",
"HDF5 Files (*.nxs *.hdf *.h5)",
"AIFIRA Files (*DAT)",
"SupaVisio Files (*pige *pixe *rbs)",
"Image Files (*edf *ccd)",
"Image Files (*tif *tiff *TIF *TIFF)",
"TextImage Files (*txt)",
"All Files (*)"]
if not HDF5:
idx = fileTypeList.index("HDF5 Files (*.nxs *.hdf *.h5)")
del fileTypeList[idx]
message = "Open ONE indexed stack or SEVERAL files"
return self._getFileList(fileTypeList, message=message, getfilter=getfilter)
def getFileListFromPattern(self, pattern, begin, end, increment=None):
if type(begin) == type(1):
begin = [begin]
if type(end) == type(1):
end = [end]
if len(begin) != len(end):
raise ValueError(\
"Begin list and end list do not have same length")
if increment is None:
increment = [1] * len(begin)
elif type(increment) == type(1):
increment = [increment]
if len(increment) != len(begin):
raise ValueError(\
"Increment list and begin list do not have same length")
fileList = []
if len(begin) == 1:
for j in range(begin[0], end[0]+increment[0], increment[0]):
fileList.append(pattern % (j))
elif len(begin) == 2:
for j in range(begin[0], end[0]+increment[0], increment[0]):
for k in range(begin[1], end[1]+increment[1], increment[1]):
fileList.append(pattern % (j, k))
elif len(begin) == 3:
raise ValueError("Cannot handle three indices yet.")
for j in range(begin[0], end[0]+increment[0], increment[0]):
for k in range(begin[1], end[1]+increment[1], increment[1]):
for l in range(begin[2], end[2]+increment[2], increment[2]):
fileList.append(pattern % (j, k, l))
else:
raise ValueError("Cannot handle more than three indices.")
return fileList
if __name__ == "__main__":
from PyMca import QStackWidget
import getopt
options = ''
longoptions = ["fileindex=",
"filepattern=", "begin=", "end=", "increment=",
"nativefiledialogs=", "imagestack="]
try:
opts, args = getopt.getopt(
sys.argv[1:],
options,
longoptions)
except:
print(sys.exc_info()[1])
sys.exit(1)
fileindex = 0
filepattern=None
begin = None
end = None
imagestack=False
increment=None
for opt, arg in opts:
if opt in '--begin':
if "," in arg:
begin = [int (x) for x in arg.split(",")]
else:
begin = [int(arg)]
elif opt in '--end':
if "," in arg:
end = [int(x) for x in arg.split(",")]
else:
end = int(arg)
elif opt in '--increment':
if "," in arg:
increment = [int(x) for x in arg.split(",")]
else:
increment = int(arg)
elif opt in '--filepattern':
filepattern = arg.replace('"','')
filepattern = filepattern.replace("'","")
elif opt in '--fileindex':
fileindex = int(arg)
elif opt in '--imagestack':
imagestack = int(arg)
elif opt in '--nativefiledialogs':
if int(arg):
PyMcaDirs.nativeFileDialogs=True
else:
PyMcaDirs.nativeFileDialogs=False
if filepattern is not None:
if (begin is None) or (end is None):
raise ValueError(\
"A file pattern needs at least a set of begin and end indices")
app = qt.QApplication([])
widget = QStackWidget.QStackWidget()
w = StackSelector(widget)
if filepattern is not None:
#ignore the args even if present
stack = w.getStackFromPattern(filepattern, begin, end, increment=increment,
imagestack=imagestack)
else:
stack = w.getStack(args, imagestack=imagestack)
if type(stack) == type([]):
#aifira like, two stacks
widget.setStack(stack[0])
slave = QStackWidget.QStackWidget(master=False,
rgbwidget=widget.rgbWidget)
slave.setStack(stack[1])
widget.setSlave(slave)
stack = None
else:
widget.setStack(stack)
widget.show()
app.exec_()
|