This file is indexed.

/usr/lib/python2.7/dist-packages/PyMca/XiaCorrect.py is in pymca 4.7.1+dfsg-2.

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
#/*##########################################################################
# 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 Software 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.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
#
# PyMca follows the dual licensing model of 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.
#############################################################################*/
__author__ = "E. Papillon - ESRF Software group"
from PyMca import XiaEdf
import sys
import os
import time

__version__="$Revision: 1.11 $"

def defaultErrorCB(message):
    print(message)

def defaultLogCB(message, verbose_level=None, verbose_ask=None):
    if verbose_level is None:
        print(message)
    elif verbose_level <= verbose_ask:
        print(message)

def defaultDoneCB(nbdone, total):
    pass

def checkCB(log_cb=None, done_cb=None, error_cb=None):
    if log_cb is None:
        log_cb= defaultLogCB
    if done_cb is None:
        done_cb= defaultDoneCB
    if error_cb is None:
        error_cb= defaultErrorCB

    return (log_cb, done_cb, error_cb)
    

def parseFiles(filelist, verbose=0, keep_sum=0, log_cb=None, done_cb=None, error_cb=None):
    (log_cb, done_cb, error_cb)= checkCB(log_cb, done_cb, error_cb)

    log_cb("Checking xia files ...")
    xiafiles= []

    for file in filelist:
        xf= XiaEdf.XiaFilename(file)
        if xf.isValid():
            log_cb(" - Parsing %s (OK - %s)"%(file, xf.getType()), 1, verbose)
            if not keep_sum:
                if not xf.isSum():
                    xiafiles.append(xf)
            else:
                xiafiles.append(xf)
        else:
            log_cb(" - Parsing %s (Not Xia)"%file, 1, verbose)

    if len(xiafiles):
        log_cb("Sorting xia files ...")
        xiafiles.sort()

        groupfiles= []
        group= None

        for xf in xiafiles:
            if group is None:
                group= [ xf ]
            else:
                if xf.isGroupedWith(group[0]):
                    group.append(xf)
                else:
                    groupfiles.append(group)
                    group= [ xf ]
        if group is not None:
            groupfiles.append(group)

        grouperrors= []
        for group in groupfiles:
            if group[0].isScan():
                if not group[-1].isStat():
                    stat= group[0].findStatFile()
                    if stat is not None:
                        log_cb(" - Find stat file for group <%s>"%stat.get(), 1, verbose)
                        group.append(stat)
                    else:
                        error_cb("XiaCorrect ERROR: no stat file in current group <%s>"%group[0].get())
                        grouperrors.append(group)

        for group in grouperrors:
            groupfiles.remove(group)

        if not len(groupfiles):
            error_cb("XiaCorrect ERROR: No valid XIA group files")
            return None

        return groupfiles

    else:
        error_cb("XiaCorrect ERROR: No XIA files found.")
        return None

    
def correctFiles(xiafiles, deadtime=1, livetime=0, sums=None, avgflag=0, outdir=None, outname="corr", force=0, \
		    verbose=0, log_cb=None, done_cb=None, error_cb=None):
    (log_cb, done_cb, error_cb)= checkCB(log_cb, done_cb, error_cb)

    processed= 0
    saved= 0
    total= 0
    errors= 0
    tps= time.time()

    done_cb(0, total)
    total= len(xiafiles)

    log_cb("Correcting xia files ...")

    for group in xiafiles:
        if not group[0].isScan():
            file= group[0]
            name= file.get()
            log_cb("Working on %s"%name, 1, verbose)

            try:
                xia= XiaEdf.XiaEdfCountFile(name)
                file.setDirectory(outdir)
                file.appendPrefix(outname)
                name= file.get()

                if sums is not None:
                    err= xia.sum(sums, deadtime, livetime, avgflag)
                    file.setType("sum", -1)
                else:
                    err= xia.correct(deadtime, livetime)
                if len(err):
                    error_cb(" - WARNING: in %s"%name)
                    for msg in err:
                        error_cb("     * " + msg)

                log_cb(" - Saving %s"%name)
                xia.save(name, force)
                saved += 1

            except XiaEdf.XiaEdfError:
                errors += 1
                log_cb(sys.exc_info()[1])
                
        else:
            groupfiles= [ file.get() for file in group ]
            name= groupfiles[-1]
            log_cb("Reading %s"%name, 1, verbose)

            try:
                xia= XiaEdf.XiaEdfScanFile(name, groupfiles[:-1])
            except XiaEdf.XiaEdfError:
                xia= None
                errors += 1
                error_cb(sys.exc_info()[1])

            if xia is not None:
                for file in group:
                    file.setDirectory(outdir)
                    file.appendPrefix(outname)

                if sums is None:
                    for file in group[:-1]:
                        det= file.getDetector()
                    
                        if det is not None:
                            log_cb("Working on detector #%02d"%det, 1, verbose)
                            try:
                                err= xia.correct(det, deadtime, livetime)
                                name= file.get()

                                if len(err):
                                    error_cb(" - WARNING: in %s"%name)
                                    for msg in err:
                                        error_cb("     * " + msg)

                                log_cb(" - Saving %s"%name)
                                xia.save(name, force)

                                saved += 1

                            except XiaEdf.XiaEdfError:
                                errors += 1
                                error_cb(sys.exc_info()[1])
                else:
                    log_cb("Working on group %s"%name, 1, verbose)
                    file= group[-1]
                    for isum in range(len(sums)):
                        try:
                            err= xia.sum(sums[isum], deadtime, livetime, avgflag)
                        
                            file.setType("sum", isum+1)
                            name= file.get()

                            if len(err):
                                error_cb(" - WARNING: in %s"%name)
                                for msg in err:
                                    error_cb("     * " + msg)

                            log_cb(" - Saving %s"%name)
                            xia.save(name, force)

                            saved += 1
                        except XiaEdf.XiaEdfError:
                            errors += 1
                            error_cb(sys.exc_info()[1])

        processed += 1
        done_cb(processed, total)
                    
    done_cb(total, total)
    log_cb("\n* %d groups processed and %d files saved in %.2f sec"%(processed, saved, time.time()-tps))
    if not errors:
        log_cb("* No errors found")
    else:
        log_cb("* %d errors found"%errors)
    log_cb("\n")


def parseArguments():
    import getopt, os.path

    prog= os.path.basename(sys.argv[0])

    long = ["help", "input=", "output=", "force", "verbose", "deadtime", "livetime", "sum=", "avg", "name=", "parsing"]
    short= ["h",    "i:",     "o:",      "f",     "v",       "d",        "l",        "s:",   "a",   "n:",    "p"]

    try:
        opts, args= getopt.getopt(sys.argv[1:], " ".join(short), long)
    except getopt.error:
        print("XiaCorrect ERROR: Cannot parse command line arguments")
        print("\t%s" % sys.exc_info()[1])
        sys.exit(0)

    parsing= 0
    options= {"input": [], "files": [], "output": None, "force": 0, "name": "corr",
		"verbose": 0, "deadtime": 0, "livetime": 0, "sums": None, "avgflag": 0, "parsing": 0}

    for opt, arg in opts:
        if opt in ("-h", "--help"):
            printHelp()
            sys.exit(0)
        if opt in ("-i", "--input"):
            options["input"].append(os.path.normpath(arg))
        if opt in ("-o", "--output"):
            options["output"]= os.path.normpath(arg)
        if opt in ("-f", "--force"):
            options["force"]= 1
        if opt in ("-v", "--verbose"):
            options["verbose"]= 1
        if opt in ("-d", "--deadtime"):
            options["deadtime"]= 1
        if opt in ("-l", "--livetime"):
            options["livetime"]= 1
        if opt in ("-n", "--name"):
            options["name"]= str(arg)
        if opt in ("-s", "--sum"):
            if options["sums"] is None:
                options["sums"]= []
            try:
                ssum= [ int(det) for det in arg.split(",") ]
                if ssum[0]==-1:
                    ssum= []
                options["sums"].append(ssum)
            except:
                print("XiaCorrect ERROR: Cannot parse sum detectors")
                print("\t%s"%arg)
                sys.exit(0)
        if opt in ("-a", "--avg"):
            options["avgflag"]= 1
        if opt in ("-p", "--parsing"):
            options["parsing"]= 1
                
    
    for iinput in options["input"]:
        if not os.path.isdir(iinput):
            print("XiaCorrect WARNING: Input directory <%s> is not valid"%\
                  iinput)

        files= [ os.path.join(iinput, file) for file in os.listdir(iinput) ]
        if not len(files):
            print("XiaCorrect WARNING: Input directory <%s> is empty"%\
                  (iinput, prog))
        else:
            options["files"]+= files

    if len(args):
        options["files"]+= args

    if not len(options["files"]):
        print("XiaCorrect ERROR: No input datafiles")
        sys.exit(0)

    if not options["parsing"]:
        if not options["deadtime"] and not options["livetime"] and options["sums"] is None:
            print("XiaCorrect ERROR: Must have at least deadtime, livetime or sum options")
            sys.exit(0)

        if options["output"] is not None:
            if not os.path.isdir(options["output"]):
                print("XiaCorrect ERROR: output directory is not valid")
                sys.exit(0)

    return options 

def printHelp():
    prog= os.path.basename(sys.argv[0])
    msg= """

%s [-h] [-v] [-f] [-d] [-l] [-a] [-s <detlist>] [-i <directory>] [-o <directory>] [<files ...>]

Options:
    [-h]/[--help]
            Print help message
    [-v]/[--verbose]
            Switch ON verbose mode
    [-f]/[--force]
            Force writing output files if they already exists
    [-d]/[--deadtime]
            Perform deadtime correction
    [-l]/[--livetime]
            Perform livetime normalization
    [-s]/[--sum] <detector_list_comma_separated>
            Sum given detectors. if detector list is set to (-1), 
            all detectors are used:
                %s -s 2,4,8  --> will sum detectors 2,4 and 8
                %s -s -1     --> will sum ALL detectors
	    Several sums can be added:
		-s 2,4,6,7 -s 8,9,10,11
    [-a]/[--avg]
	    Sum(s) are averaged.
	    Need <-s> to specify list of detectors:
		-s 2,3,4 -a  --> will average detectors 2,3 and 4
    [-i]/[--input] <directory>
            Specify input directory: all files in this directory 
            which appears to be xia edf files are processed.
            Several [-i] options can be added:
                %s -d -i /tmp -i /data/opidXX
    [-o]/[--output]
            Specify output directories. If not specified, output
            files are saved in the same place as input file.
    [-n]/[--name]
	    String to be appended to prefix for output filename.
	    Default is \"corr\".
    [<files ...>]
            Specify one or several input files. Wildcards can be used:
                %s -l file1.edf file2.edf /tmp/test*.edf

Minimum options to work:
    [-l] , [-d] or [-s]
    [-i input] or <files ...>

"""%(prog, prog, prog, prog, prog)
    print(msg)


def mainCommandLine():
    options= parseArguments()
    files= parseFiles(options["files"], options["verbose"])
    if files is not None:
        if options["parsing"]:
            for group in files:
                print("FileGroup:")
                for file in group:
                    print(" - ", file.get())
        else:
            correctFiles(files, options["deadtime"], options["livetime"], options["sums"], options["avgflag"], \
                 options["output"], options["name"], options["force"], options["verbose"])

def mainGUI(app=None):
    import PyMcaQt as qt
    import XiaCorrectWizard

    if app is None:
        app= qt.QApplication(sys.argv)

    wid= XiaCorrectWizard.XiaCorrectWizard()
    ret= wid.exec_()

    if ret==qt.QDialog.Accepted:
        options= wid.get()
        files= parseFiles(options["files"], options["verbose"])
        if files is not None:
            correctFiles(files, options["deadtime"], options["livetime"], options["sums"], options["avgflag"], \
                     options["output"], options["name"], options["force"], options["verbose"])
        



if __name__=="__main__": 
    import sys

    if len(sys.argv)==1:
        mainGUI()
    else:
        mainCommandLine()