-
Notifications
You must be signed in to change notification settings - Fork 0
/
per_list.py
executable file
·1571 lines (1179 loc) · 42.3 KB
/
per_list.py
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
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#! /usr/bin/env python
'''
Space Telescope Science Institute
Usage (as a standalone program:
per_list.py
or
per_list.py [various options] fileroot
where fileroot the root name of the outputfiles
aperture is 'all' or 'full' with the latter indicating one creates a list containing only the full IR frames, no subarrays
Options:
-h Print this help
-all Create a new .ls file and a new summary file
-new_sum Create a new summary file
-daily Create a new .ls but just update the old summary file
-file_type Instead of the defult flt files, create a file continaing
a different file type, e.g. -file_type raw to get the
raw data files
without any arguments the call is effectively
per_list.py -all -file_type flt observations
per_list.py
Synopsis:
If this is run as a standalone program, the routine creates two files. The first
is set of ascii records that describe all the WFC3/IR files of a certain type
that are in this directory and any subdirectories. The second is an observations.sum
file that really is only pertinent to the persistence processing software
More generally this module contains routines both to make an ordered list of the records
and then to read them back, as well as a number of utilities to handle matters
related to where the Persist directories are located.
Description:
The routine uses 'find' to locate all of the files of a certain type,
aand then orders the list in time. If there are duplicate files then
it uses the creation date as the one to put in the list. The dupliccates
are in the list also, but are commented out.
Primary routines:
steer Parses the command line and runs the program
mske_ordered_list Creates .ls file
make_sum_file Creates/updates the summary file
Notes:
This should probably be rewritten to remove the iraf dependencies
History:
091026 ksl Coding begun
091215 ksl Updated to prevent reading UVIS data and put in an option to only
look at full arrays
1006 ksl Split out from other routines so this routine could be used as
a library of routines for dealing with ascii lists
100608 ksl Added the ability to create lists from the command line by running
per_list.py
100906 ksl Added what amounts to a standalone utility find_latest to locate
the last version of a file in any subdirectory if there is no
such file in the current directory. This is here in this file
becasue per_list.py contains all the file locating routines
not because it is really part of the rest of per_list
110103 ksl Modified various portions of the way with which summary files are
handled and introduced a steering routine as the input options
became more complicated.
120330 ksl Modified the help so that it reflects how the routine actually
works
130909 ksl Standardized error printouts
150317 ksl Remove iraf/pyraf from per_list
151022 ksl Restored iraf/pyraf for performance reasons
160104 ksl Changes to lock and unlock files so that parallel processing
will not corrupt the obervations.sum file
'''
import sys
import os
import numpy
import time
import string
import math
import scipy
import subprocess
import pylab
import shutil
import per_fits
from astropy.io import fits
import pyraf
from multiprocessing import Pool
# Utilities
def backup(filename,tformat='%y%m%d',force='no'):
'''
Backup a file with a standard way of naming the file.
The original file is copied to the backup unless the
backup file already exists or force is 'yes'.
The format can be any valid time.strftime format, but
probably should have no spaces.
The routine returns the name of the backup file, or
'None' if there was no backup made
Notes: The idea of this is that one wants to keep
a history of a file over time, but not at infinite
time resolution.
110105 ksl Coded as part of effort to be able
to use per_list as aprt of a crontab
'''
curtime=time.strftime(tformat,time.localtime())
if os.path.exists(filename)==False:
print 'Warning: No file %s to backup' % filename
return 'None'
backup_file='%s.%s.old' % (filename,curtime)
if os.path.exists(backup_file)==False or force=='yes':
shutil.copy(filename,backup_file)
return backup_file
else:
return 'None'
def open_file(filename,permiss=0770):
'''
Open a file for writing and set its permissions
This was written in an attempt to get all of the
files to have a common set of permissions
no mattter who writes them
'''
if os.path.isfile(filename):
os.remove(filename)
g=open(filename,'w')
try:
os.chmod(filename,permiss)
except OSError:
print 'Error: open_file: OSerror trying to set permissions'
return g
def set_path(name,mkdirs='yes',local='no'):
'''
Check that the directory Persist where the outputs are to go exists, and if not
create it, and also create an underlying directory .../Persist/Figs.
The input is the complete filename, including the path. The routine
requires that there be a '/' in the complete name. If not, it will
create Persist below the current working directory
The routine returns the path include the directory name Persist
Note:
Normally this routine is given either the complete name to a file in the
visit directory, e. g.
./D/VisitAJ/ib0lajdyq_flt.fits[1] or
a name to a file in the Persist directory, e. g.
./D/VisitAJ/Persist/filename
This accounts for the somewhat convoluted attempt to locate where the Persist
directory should be
mkdirs must be 'yes' for directores to be made. If it is for example, 'no',
then the path will be return but there will be not attempt to make the
directory
if local is anything but 'no', then the path will be set to ./Persist
101014 ksl Added
101214 ksl Moved into per_list since this is mostly used in conjunction
with other routines that are there. It is not obvious that
this is the correct place for this.
101215 ksl Added creation of the Figs directory
110105 ksl Made creation of the directories an option
110121 ksl Made change to control permissions of the directories
110203 ksl Made change to allow the directories to be written beneath
the current working directory, a change that is primarily
for testing
110811 ksl The directory permissions are set so that the group name
should be inherited.
110811 ksl Added commands to set the group name, but only if we are
in the Quicklook2 directory structure. These commands
would need to change if the group names change or directory
names change. They should have no effect outsdide the standard
structure
'''
# 110120 - I am not sure why but I had to reimport string
import string
if len(name)==0:
print 'Error: set_path: name had length 0, nothing to parse'
return ''
# Determine where we want Persist to be located.
if local=='no':
try:
i=string.rindex(name,'Persist')
path=name[0:i]
except ValueError:
# Find the last / in the name
try:
i=string.rindex(name,'/')
path=name[0:i]
except ValueError:
print 'Warning: set_path: Assuming the intent was to work in the current directory'
path='./'
else:
path='./'
# Check whether the parent directory for Persits exists
if os.path.exists(path)==False:
string='set path: The directory %s contained in %s does not exist' % (path,name)
print 'Error: %s' % (string)
return 'NOK %s ' % string
path=path+'/Persist/'
if mkdirs!='yes':
return path
# If one has reached this point then you want to make any necessary directories
# set the chmod of the diretory so those within the group can delete the directory
# when necessary
# Note that the group name assignments below only are valid with the current
# Quicklook2 directory structure and group names
if os.path.exists(path)==False:
try:
os.mkdir(path)
os.chmod(path,02770)
if path.count('QL_GO'):
os.chown(path,-1,6047)
elif path.count('Quicklook'):
os.chown(path,-1,340)
except OSError:
print 'Error: set_path: Could not create %s for %s' % (path,name)
return 'NOK Could not create %s' % path
# Add a figs directory if it does not exist as well
figs=path+'/Figs'
if os.path.exists(figs)==False:
os.mkdir(figs)
os.chmod(figs,02770)
if figs.count('QL_GO'):
os.chown(figs,-1,6047)
elif figs.count('Quicklook'):
os.chown(figs,-1,340)
# print 'set_path',figs,os.path.exists(figs)
return path
def parse_dataset_name(name):
'''
Check if we have been given the name of the fits file instead of the
dataset name, and if so try to determine and return the dataset name
100103 ksl Coded because it is natural in some cases to give the filename
'''
xname=name
if string.count(xname,'.') > 0 or string.count(xname,'/') > 0:
# This must be a filename
i=string.rindex(xname,'/')
xname=xname[i+1:i+10]
return xname
def parse_creation_time(xtime='2010-07-10T19:11:52'):
'''
Parse the time string for the date at which a fits file
was created and return a time that can be used to choose
which of two fits files was created last
The time returned approximates the number of days since
1990 but does not account for the fact that there are
different numbers of days in a month.
The routine returns 0.0 and raises an IndexErro exception
if the time cannot be parsed
Note the use of int instead of eval because leading zeros
caused eval to interprete the numbers as octal
100817 Added error checking which arose because the values
being passed to routine were actually not the
creation date
'''
xtime=xtime.replace('-',' ')
xtime=xtime.replace('T',' ')
xtime=xtime.replace(':',' ')
xtime=xtime.split()
try:
day_sec=int(xtime[3])*3600.+int(xtime[4])*60+int(xtime[5])
day_frac=day_sec/86400
# Next section for day is really not accurate, but we don't care
year_frac=(int(xtime[1])+int(xtime[2])/31.)/12.
day=365.*((int(xtime[0])-1990.)+year_frac)
except IndexError:
raise IndexError
return 0.0
pseudo_time=day+day_frac
return pseudo_time
def check4duplicates(records):
'''
Check the list 4 duplicate records, and choose the one that was
created last if that is possible
The routine returns a list that contains 'ok' for files that
are the ones to use and 'nok' for those that are duplicates
100817 Added checks to trap problems parsing times.
110120 This is a new attempt to find the duplicates and select the last one
160127 Modified again to speed this up (when there are large numbers of files
to examine. If there are no duplicates this is quite quick. Even
when there are duplicates this is about 3x faster than the old method.
'''
xstart=time.time()
ok=[]
names=[]
for record in records:
ok.append('ok')
names.append(record[1])
unique=set(names)
if len(unique)==len(names):
print 'check4duplicates: There are no duplicates in the directory structure'
return ok
else:
duplicate_names=[]
print 'check4duplicates: Warning: There are %d duplicate datasets in the directory structure' % (len(names)-len(unique))
for one in unique:
icount=names.count(one)
if icount>1:
duplicate_names.append(one)
hold=[]
j=0
while j<len(records):
if names[j]==one:
hold.append(j)
if len(hold)==icount:
break # We have them all
j=j+1
times=[]
for one in hold:
times.append(records[one][17])
times=numpy.array(times)
order=numpy.argsort(times) # Give me the order of the times
last=order[len(order)-1]
k=0
while k<len(hold):
if k==last:
ok[hold[k]]='ok'
else:
ok[hold[k]]='nok'
k=k+1
print 'Check for duplicates in direcory structure took:',time.time()-xstart
return ok
def find_latest(filename='foo'):
'''
This is a simple routine to locate a specific version of a file. If
the file is in the current directory that is the file name that
will be returned. If it is in one of the subdirectories of the
current directory then the one that was modified most recently
will be returned.
Notes:
This routine uses the unix utility find. It is therefore
likely to be slow in large directory structures
This uses subprocess which handles stdin and stdout, unlike
os.system
History:
100906 ksl Coding begun. There is a standalone version of this
called find.py (in my normal py_progs/scripts directory
'''
proc=subprocess.Popen('find . -follow -name %s -print ' % filename,shell=True,stdout=subprocess.PIPE)
# Before
lines=proc.stdout.readlines()
if len(lines)==0:
'Warning: find_best: No versions of %s found' % filename
return ''
tbest=0
for line in lines:
fname=line.strip()
if fname.count('/') <= 1:
fbest=fname
break
else:
time=os.path.getmtime(fname)
if time>tbest:
fbest=fname
tbest=time
return fbest
def check4scan(filename='./Visit43/ic9t43j1q_flt.fits[1]'):
'''
Determine whether or not a raw, ima, or flt file is associated with an observation involving
a spatial scan.
Return:
scan if a spatial scan
stare if the spt file exists, but it is not a spatial san
unknown if the spt file does not exist
Notes:
The routine looks for the spt file corresponding to the dataset and
parses the header to find out if it is a scanned observation.
130225 Coded and Debugged
130307 Replaced routine using astropy.fits with iraf because astropy.fits
was very slow
'''
xscan='unknown'
# First strip of the extension if any
xname=per_fits.parse_fitsname(filename,0,'yes')
xfile=xname[0]
xfile=xfile.replace('flt','spt')
xfile=xfile.replace('raw','spt')
xfile=xfile.replace('ima','spt')
# Now we should have the name of the spt file
if os.path.exists(xfile)==True:
# Revert to iraf/pyraf for performance reasons
# xx=per_fits.get_keyword(xfile,0,'SCAN_TYP')
xx=pyraf.iraf.hselect(xfile+'[0]','SCAN_TYP','yes',Stdout=1)
xx=xx[0].split('\t')
else:
return 'no_spt'
if xx[0]=='N':
xscan='stare'
else:
xscan='scan'
return xscan
# End utilities
# Routines for making and updating the summary file
def update_summary(dataset,status_word='Unknown',results='Whatever you want',fileroot='observations',append='yes'):
'''
Update a record in the summary file, where the inputs have the following meaning
dataset rootname of the file, usually the flt file, being processed
status_word one word, e.g. Complete or Error, to define the current status of the processing
results A string which can be appended to the current set of results or which can replace it
fileroot The rootname of the summarry file, almost always obsevations
append if 'yes', then append the new results to the old, else replace the old results with the
new
Notes:
Aside from the dataset name everything is free format in terms of results
It is not really obvious that appending to a line is the best approach. If I werre writing this
today, I might opt for a fixed format from the beginning, but this is part of a larger question
of whether one should use astropy. tables, or some kind of database system - ksl - 151006
Before 1601 this routine modified the observation.sum file directly, but now it just records the
information needed to update the summary file in a directory tmp_sum. This change was to prevent
multiple processing writing to the summary file at the same file. A new routine fixup_summary_file
below now inserts the results into the data.
101221 ksl Coded as part of effort to get a way to check what files
had been processed with the persistence software
110103 ksl Added a better way to keep enough summary files that one
might be able to roll back
110117 ksl Dealt with the situation where there were not old_results
110721 ksl Improved the description of the routine
151006 ksl Fixed Error #553, which arose because the routine assumes one
often wants to append to a summary line. Because we use index
to find where in the line we want to start replacing data, one
needs to be careful that there is no possibility that one is
indexing to the wrong position.
160105 ksl Modified for multiprocessing
'''
if os.path.isdir('tmp_sum')==False:
os.mkdir('tmp_sum')
summary_file=fileroot+'.sum'
gmt=time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
try:
f=open(summary_file,'r')
lines=f.readlines()
f.close()
except IOError:
print 'Error: update_summary: File %s does not exist' % summary_file
return
# this opens the files for writing and sets the permissions
xfile='tmp_sum/%s.txt' % dataset
if os.path.isfile(xfile)==True:
gg=open(xfile,'r')
old_results=gg.readline()
gg.close()
else:
i=0
while i <len(lines):
line=lines[i].split()
if line[0]==dataset:
old_results=lines[i]
break
i=i+1
# OK at this point I have the old results
results=results.strip()
old_results=old_results.strip()
line=old_results.split()
if len(line)>6:
k=old_results.index(line[5])+len(line[5])
old_results=old_results[k:len(old_results)] # This should be the bits that were append previously
old_results=old_results.strip()
if append=='yes' and len(old_results)>0:
results='%s %s' % (old_results,results)
string='%-10s %5s %20s %20s %-20s %s' % (line[0],line[1],line[2],gmt,status_word,results)
gg=open_file('tmp_sum/%s.txt' % dataset)
gg.write('%s\n' % string)
gg.close()
return
def fixup_summary_file(datasets,fileroot='observations'):
'''
Update the observations.sum file from the information stored in the 'tmp_sum' directory
where
datasets is a list of the datasets which have been processed
fileroot is the root name of the .sum file to be updated
Notes:
The directory where the data is stored is hardwired
The routine simple finds the line in the observations.sum file associated with
the dataset and replaces that line with the line that is in the .txt file
History:
160105 ksl Coded as part of the effort to add multiprocessing
'''
# Get the data
good=[]
data=[]
for dataset in datasets:
try:
xname='tmp_sum/%s.txt' % dataset
f=open(xname,'r')
line=f.readline()
data.append(line)
good.append(dataset)
except IOError:
print 'Error: fixup_summary_file: %s does not appear to exist' % xname
# OK at this point we have found all of the good files
summary_file=fileroot+'.sum'
try:
f=open(summary_file,'r')
lines=f.readlines()
f.close()
except IOError:
print 'Error: update_summary: File %s does not exist' % summary_file
return
i=0
while i<len(lines):
line=lines[i].split()
j=0
while j<len(good):
if line[0]==good[j]:
lines[i]=data[j]
print lines[i].strip()
break
j=j+1
i=i+1
g=open_file('tmp.sum')
for one in lines:
g.write(one)
backup(summary_file)
proc=subprocess.Popen('mv %s %s' % ('tmp.sum',summary_file),shell=True,stdout=subprocess.PIPE)
return
def make_sum_file(fileroot='observations',new='no'):
'''
Make the file that will record the results of persistence processing. If
it already exists, give the user the option of merging new records into
the old file or creating a new file
Note that each new output line should have the following values
dataset prog_id MJD ProcessDate Unprocessed
101221 ksl Coded as part of effort to put a recording mechanism
in place
110103 ksl Modified the outputs when new records are inserted
110103 ksl Changed so the routine itself reads the observation.ls
file
110119 ksl Rewrote to assure that there is exactly one summary
file line for each observation file line
'''
# Read the entire observations.ls file
print '# (Re)Making summary file'
records=read_ordered_list0(fileroot)
print '# The number of records in the old per_list file is %d' % (len(records))
gmt=time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime())
summary_file=fileroot+'.sum'
if os.path.exists(summary_file)==False or new=='yes':
print '# Making a pristine summary file'
g=open_file(summary_file)
for record in records:
string='%-10s %5s %20s %20s %-20s' % (record[1],record[2],record[6],gmt,'Unprocessed')
g.write('%s\n' % string)
g.close()
else:
print '# Merging new records into old list'
try:
f=open(summary_file,'r')
summary=f.readlines()
except IOError:
print 'Error: make_sum_file: Could not read summary file %s ' % summary_file
# Get the dataset names in the summary file
datasets=[]
for one in summary:
word=one.split()
datasets.append(word[0])
g=open_file('tmp.sum')
# The next portion is not very smart since it always goes through the summary information
# from the beginning. But is should be "sure".
for record in records:
i=0
while i<len(datasets):
if datasets[i]==record[1]:
break
i=i+1
if i==len(datasets):
string='%-10s %5s %20s %20s %-20s' % (record[1],record[2],record[6],gmt,'Unprocessed')
g.write('%s\n' % string)
else:
g.write(summary[i])
g.close()
ndup=check_sum_file('tmp.sum',summary_file)
if ndup>0:
print 'Error: make_sum_file: Since there were duplicates in th tmp file, not moving to %s' % (summary_file)
return 'NOK - Since there were duplicates in th tmp file, not moving to %s' % (summary_file)
# Now move the files around. Note that the next 3 lines need to be the same as in update_summary above
# gmt=time.strftime("%y%m%d.%H%M", time.gmtime()) # Create a string to use to name the updated file. As written a new file a minute
# proc=subprocess.Popen('mv %s %s.%s.old' % (summary_file,summary_file,gmt),shell=True,stdout=subprocess.PIPE)
backup(summary_file)
proc=subprocess.Popen('mv %s %s' % ('tmp.sum',summary_file),shell=True,stdout=subprocess.PIPE)
return
def check_sum_file(new='tmp.sum',old='none'):
'''
Check a summary file for unique dataset names
Description
The routine checks the new summary file to assure
that there is only one line with a given dataset name.
It returns the number of duplicate records
If a file name is given in old, then the routine checks
whether there are any records that were in the old file, that
are not in the new file. This can happen and not be an error,
but the results are recorded in a file with the extension problem
Notes:
There should be one and only one record for each
record in observaitions.ls
110119 - Expanded the questions that were asked
150127 ksl Rewrote so that it was much faster by using sets
'''
# Read the new summary file
summary_file=new
if os.path.exists(summary_file)==False:
print 'Error: check_sum: There is no summary file names %s.sum to check' % fileroot
return
f=open(summary_file,'r')
lines=f.readlines()
f.close()
# Open a diagnostic file to record any problems
g=open_file(summary_file+'.problem')
string='# Checking new (%s) against (%s) old summary file' % (new,old)
print string
g.write('%s\n' % string)
# Check for duplicate datasets in new summary file
xstart=time.time()
names=[]
for line in lines:
x=line.strip()
word=x.split()
names.append(word[0])
unique=set(names)
if len(unique)==len(names):
dups=0
else: # There is a problem and so the duplicate check must be carried out
print 'Error: There are duplicate datasets in the the newly created summary file %s' % new
print 'A detailed check is now underway'
dup_names=[]
dups=0
for one in unique:
jj=names.count(one)
if jj>1:
g.write('Duplicate: %5d %s\n' % (jj,one))
dup_names.append(one)
dups=dups+1
string='# Check of %s revealed %d duplicates' % (new,dups)
print string
g.write('%s\n' % string)
delta_t=time.time()-xstart
print 'check_sum: time to search for duplicate records in the new .sum file: ',delta_t
# Check for datasets that were in the .sum file before but are missing now
if old!='none':
print 'Checking for datasets that were in the last .sum file but are now missing'
xstart=time.time()
old_names=[]
try:
f=open(old,'r')
old_lines=f.readlines()
f.close()
for one in old_lines:
x=one.strip()
word=x.split()
old_names.append(word[0])
except IOError:
old_lines=[]
nlost=0
for one in old_names:
if names.count(one)==0:
g.write('Missing: %s\n' % (one))
nlost=nlost+1
string='# Check of %s revealed %d datasets no longer in the .sum file' % (old,nlost)
if nlost>0:
print 'Warning: Lost datasets may not be a problem, but are noted as a warning of something possibly worth invesigation'
print string
g.write('%s\n' % string)
print '# check_sum_file: The check for missing records took %s s' % delta_t
# xstart=time.time()
# names=[]
# dups=0
# for line in lines:
# x=line.strip()
# word=x.split()
# j=0
# while j<len(names):
# name=names[j]
# if word[0]==name:
# g.write('%5d %s' % (j,line))
# dups=dups+1
# break
# j=j+1
# if j==len(names):
# names.append(word[0])
#
# string='# Check of %s revealed %d duplicates' % (new,dups)
# print string
# g.write('%s\n' % string)
# delta_t=time.time()-xstart
# print '# check_sum_file: The check for duplicates took %s s' % delta_t
# if old!='none':
# xstart=time.time()
#
# try:
# f=open(old,'r')
# old_lines=f.readlines()
# f.close()
# except IOError:
# old_lines=[]
#
# nlost=0
# for one in old_lines:
# x=one.strip()
# word=x.split()
# j=0
# while j<len(names):
# name=names[j]
# if word[0]==name:
# break # Then we have a match
# j=j+1
# if j==len(names): # There was no match
# print 'Lost record:',x
# g.write('%5d %s' % (j,one))
# nlost=nlost+1
#
# string='# Check of %s revealed %d lost records' % (old,nlost)
# print string
# g.write('%s\n' % string)
# print '# check_sum_file: The check for missing records took %s s' % delta_t
g.close()
return dups
def get_info(lines,apertures,filetype):
'''
Get all of the keyword information for a set of files and return this
Notes:
This section of the old make_ordered list was put into a separate function
so that it could be run in parallel
History
160118 ksl Added
'''
records=[]
times=[]
if len(lines)==0:
print 'There were no %s files in the directory structure' % filetype
return []
else:
print 'There are %d datasets to process' % len(lines)
i=0
for line in lines:
line=line.strip()
line=line.split()
# 100807 Added date of file creation so could handle non-unique data sets
# This is the old version using pyraf, which has been put back for perfomance reasons
xfile='%s[1]' % line[0]
if pyraf.iraf.imaccess(xfile):
x=pyraf.iraf.hselect(xfile,'$I,rootname,proposid,linenum, instrume,detector,expstart,date-obs,time-obs,aperture,filter,exptime,crval1,crval2,targname,asn_id,pr_inv_L,date','yes',Stdout=1)
x=x[0].split('\t')
# Kluge for raw data files which have two ROOTNAME keywords for unknown reasons
if x[1]==x[2]:
x.pop(2)
x[16].replace(' ','-') # Get rid of spaces in PI names
# Another kludge for raw files. The is no 'date' field in the first extension as there is for flt and ima files, but DATE does exist in extension 0
if filetype=='raw':
xname=per_fits.parse_fitsname(xfile,0,'yes')
xx=pyraf.iraf.hselect(xname[2],'$I,DATE','yes',Stdout=1)
xx=xx[0].split('\t')
x.append(xx[1])
x[0]=line[0]
# # Replaced upcoming lines with iraf/pyraf for performance reasons
# xfile=line[0]
# if os.path.isfile(xfile) == True:
# x=per_fits.get_keyword(xfile,1,'rootname,proposid,linenum, instrume,detector,expstart,date-obs,time-obs,aperture,filter,exptime,crval1,crval2,targname,asn_id,pr_inv_L')