forked from mike-a-yen/bpz-1.99.3
-
Notifications
You must be signed in to change notification settings - Fork 0
/
coeio.py
2254 lines (2048 loc) · 80.5 KB
/
coeio.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
## Automatically adapted for numpy Jun 08, 2006
## By hand: 'float' -> float, Float -> float, Int -> int
# coeio.py
# INPUT / OUTPUT OF FILES
from coetools import *
import string
#import fitsio
try:
import pyfits#, numarray
pyfitsloaded = True
except:
pyfitsloaded = False
#pass # print "pyfits not installed, so not importing it"
try:
import Image
from coeim import *
except:
pass # print "Image not installed, so not importing it"
from os.path import exists, join
from numpy.random import *
from compress2 import compress2 as compress
def strspl(s):
if type(s) == str:
if string.find(s, ' ') > -1:
s = string.split(s)
return s
def pint(A, n=0):
"""Makes it easier to view float arrays:
prints A.astype(int)"""
if type(A) in [list, tuple]:
A = array(A)
if n <> 0:
A = A * 10**n
print A.astype(int)
def pintup(A, n=0):
"""Makes it easier to view float arrays:
prints A.astype(int)"""
pint(flipud(A), n)
if pyfitsloaded:
# UNLESS $NUMERIX IS SET TO numpy, pyfits(v1.1b) USES NumArray
pyfitsusesnumpy = (string.atof(pyfits.__version__[:3]) >= 1.1) and (numerix == 'numpy')
if not pyfitsusesnumpy:
print 'You probably should have done this first: setenv NUMERIX numpy'
import numarray
def recapfile(name, ext):
"""CHANGE FILENAME EXTENSION"""
if ext[0] <> '.':
ext = '.' + ext
i = string.rfind(name, ".")
if i == -1:
outname = name + ext
else:
outname = name[:i] + ext
return outname
def capfile(name, ext):
"""ADD EXTENSION TO FILENAME IF NECESSARY"""
if ext[0] <> '.':
ext = '.' + ext
n = len(ext)
if name[-n:] <> ext:
name += ext
return name
def decapfile(name, ext=''):
"""REMOVE EXTENSION FROM FILENAME IF PRESENT
IF ext LEFT BLANK, THEN ANY EXTENSION WILL BE REMOVED"""
if ext:
if ext[0] <> '.':
ext = '.' + ext
n = len(ext)
if name[-n:] == ext:
name = name[:-n]
else:
i = string.rfind(name, '.')
if i > -1:
name = name[:i]
return name
uncapfile = decapfile
def params_cl():
"""RETURNS PARAMETERS FROM COMMAND LINE ('cl') AS DICTIONARY:
KEYS ARE OPTIONS BEGINNING WITH '-'
VALUES ARE WHATEVER FOLLOWS KEYS: EITHER NOTHING (''), A VALUE, OR A LIST OF VALUES
ALL VALUES ARE CONVERTED TO INT / FLOAT WHEN APPROPRIATE"""
list = sys.argv[:]
i = 0
dict = {}
oldkey = ""
key = ""
list.append('') # EXTRA ELEMENT SO WE COME BACK AND ASSIGN THE LAST VALUE
while i < len(list):
if striskey(list[i]) or not list[i]: # (or LAST VALUE)
if key: # ASSIGN VALUES TO OLD KEY
if value:
if len(value) == 1: # LIST OF 1 ELEMENT
value = value[0] # JUST ELEMENT
dict[key] = value
if list[i]:
key = list[i][1:] # REMOVE LEADING '-'
value = None
dict[key] = value # IN CASE THERE IS NO VALUE!
else: # VALUE (OR HAVEN'T GOTTEN TO KEYS)
if key: # (HAVE GOTTEN TO KEYS)
if value:
value.append(str2num(list[i]))
else:
value = [str2num(list[i])]
i += 1
return dict
def delfile(file, silent=0):
if os.path.exists(file) or os.path.islink(file): # COULD BE BROKEN LINK!
if not silent:
print 'REMOVING ', file, '...'
os.remove(file)
else:
if not silent:
print "CAN'T REMOVE", file, "DOES NOT EXIST."
rmfile = delfile
def dirfile(filename, dir=""):
"""RETURN CLEAN FILENAME COMPLETE WITH PATH
JOINS filename & dir, CHANGES ~/ TO home"""
if filename[0:2] == '~/':
filename = os.path.join(home, filename[2:])
else:
if dir[0:2] == '~/':
dir = os.path.join(home, dir[2:])
filename = os.path.join(dir, filename)
return filename
def loadfile(filename, dir="", silent=0, keepnewlines=0):
infile = dirfile(filename, dir)
if not silent:
print "Loading ", infile, "...\n"
fin = open(infile, 'r')
sin = fin.readlines()
fin.close()
if not keepnewlines:
for i in range(len(sin)):
sin[i] = sin[i][:-1]
return sin
def loadheader(filename, dir="", silent=0, keepnewlines=0):
infile = dirfile(filename, dir)
if not silent:
print "Loading ", infile, "...\n"
fin = open(infile, 'r')
line = '#'
sin = []
while line:
line = fin.readline()
if line[0] <> '#':
break
else:
sin.append(line)
fin.close()
if not keepnewlines:
for i in range(len(sin)):
sin[i] = sin[i][:-1]
return sin
def fileempty(filename, dir="", silent=0, delifempty=0):
"""CHECK IF A FILE ACTUALLY HAS ANYTHING IN IT
OR IF IT'S JUST CONTAINS BLANK / COMMENTED LINES"""
filename = dirfile(filename, dir)
gotdata = 0
if os.path.exists(filename):
fin = open(filename, 'r')
line = 'x'
while line and not gotdata:
line = fin.readline()
if line:
if line[0] <> '#':
gotdata = 1
if delifempty:
if not gotdata:
os.remove(filename)
fin.close()
return (gotdata == 0)
def delfileifempty(filename, dir="", silent=0):
fileempty(filename, dir, silent, 1)
def assigndict(keys, values):
n = len(keys)
if n <> len(values):
print "keys & values DON'T HAVE SAME LENGTH IN coeio.assigndict!"
else:
d = {}
for i in range(n):
d[keys[i]] = values[i]
return d
def loaddict1(filename, dir="", silent=0):
lines = loadfile(filename, dir, silent)
dict = {}
for line in lines:
if line[0] <> '#':
words = string.split(line)
key = str2num(words[0])
val = '' # if nothing there
if len(words) == 2:
val = str2num(words[1])
elif len(words) > 2:
val = []
for word in words[1:]:
val.append(str2num(word))
dict[key] = val
return dict
def loaddict(filename, dir="", silent=0):
lines = loadfile(filename, dir, silent)
dict = {}
for line in lines:
if line[0] <> '#':
words = string.split(line)
key = str2num(words[0])
val = '' # if nothing there
valstr = string.join(words[1:], ' ')
valtuple = False
if valstr[0] in '[(' and valstr[-1] in '])': # LIST / TUPLE!
valtuple = valstr[0] == '('
valstr = valstr[1:-1].replace(',', '')
words[1:] = string.split(valstr)
if len(words) == 2:
val = str2num(words[1])
elif len(words) > 2:
val = []
for word in words[1:]:
val.append(str2num(word))
if valtuple:
val = tuple(val)
dict[key] = val
return dict
# THE LONG AWAITED MIXED FORMAT LOADER!
def loadcols(infile, format='', pl=0):
"""LOADS A DATA FILE CONTAINING COLUMNS OF DIFFERENT TYPES (STRING, FLOAT, & INT
RETURNS A LIST OF LISTS
format (OPTIONAL) INPUT AS A STRING, ONE LETTER (s, d, or f) FOR EACH COLUMN
ARRAY OUTPUT FOR NUMBERS: ADD AN 'A' TO THE BEGINNING OF format
USAGE: labels, x, y = loadcols('~/A1689/arcsnew_lab.txt', format='sdd')"""
txt = loadfile(infile)
## line = txt[0]
## words = string.split(line)
while txt[0][0] == '#':
txt = txt[1:]
line = txt[0]
words = string.split(line)
ncols = len(words)
data = [[]]
for icol in range(ncols-1):
data.append([])
arrayout = 0
if format:
if format[0] == 'A':
format = format[1:]
arrayout = 1
if not format: # FIGURE IT OUT BASED ON FIRST LINE ONLY
for word in words:
try:
datum = string.atoi(word)
format += 'd'
except:
try:
datum = string.atof(word)
format += 'f'
except:
format += 's'
#print format
roundcols = []
for line in txt:
if line:
if line[0] <> '#':
words = string.split(line)
if pl:
print line
for iword in range(len(words)):
if iword > len(format)-1:
print 'EXTRA CONTENT IN LINE: ',
print string.join(words[iword:])
break
#print iword
word = words[iword]
formatum = format[iword]
if formatum == 'f':
datum = string.atof(word)
elif formatum == 'd':
try:
datum = string.atoi(word)
except:
#datum = int(round(string.atof(word)))
datum = string.atof(word)
try:
datum = roundint(datum)
if not (iword+1) in roundcols:
roundcols.append(iword+1)
except:
pass
else:
datum = word
data[iword].append(datum)
if roundcols:
if len(roundcols) > 1:
print 'WARNING, THE FOLLOWING COLUMNS WERE ROUNDED FROM FLOAT TO INT: ', roundcols
else:
print 'WARNING, THE FOLLOWING COLUMN WAS ROUNDED FROM FLOAT TO INT: ', roundcols
if arrayout:
for icol in range(ncols):
if format[icol] in 'df':
data[icol] = array(data[icol])
return data
# CRUDE
def savecols(data, filename, format=''):
ncols = len(data)
nrows = len(data[0])
if not format:
for icol in range(ncols):
datum = data[icol][0]
if type(datum) == int:
format += 'd'
elif type(datum) == float:
format += 'f'
else:
format += 's'
# CHANGE format from 'sdd' TO ' %s %d %d\n'
ff = ' '
for f in format:
if f == 'f':
ff += '%.3f '
else:
ff += '%' + f + ' '
format = ff[:-1]
format += '\n'
fout = open(filename, 'w')
for irow in range(nrows):
dataline = []
for icol in range(ncols):
dataline.append(data[icol][irow])
fout.write(format % tuple(dataline))
fout.close()
def savedata(data, filename, dir="", header="", separator=" ", format='', labels='', descriptions='', units='', notes=[], pf=0, maxy=300, machine=0, silent=0):
"""Saves an array as an ascii data file into an array."""
# AUTO FORMATTING (IF YOU WANT, ALSO OUTPUTS FORMAT SO YOU CAN USE IT NEXT TIME w/o HAVING TO CALCULATE IT)
# maxy: ONLY CHECK THIS MANY ROWS FOR FORMATTING
# LABELS MAY BE PLACED ABOVE EACH COLUMN
# IMPROVED SPACING
dow = filename[-1] == '-' # DON'T OVERWRITE
if dow:
filename = filename[:-1]
tr = filename[-1] == '+'
if tr:
data = transpose(data)
filename = filename[:-1]
if machine:
filename = 'datafile%d.txt' % machine # doubles as table number
outfile = dirfile(filename, dir)
if dow and os.path.exists(outfile):
print outfile, " ALREADY EXISTS"
else:
skycat = strend(filename, '.scat')
if skycat:
separator = '\t'
if len(data.shape) == 1:
data = reshape(data, (len(data), 1))
#data = data[:,NewAxis]
[ny,nx] = data.shape
colneg = [0] * nx # WHETHER THE COLUMN HAS ANY NEGATIVE NUMBERS: 1=YES, 0=NO
collens = []
if format:
if type(format) == dict: # CONVERT DICTIONARY FORM TO LIST
dd = ' '
for label in labels:
if label in format.keys():
dd += format[label]
else:
print "WARNING: YOU DIDN'T SUPPLY A FORMAT FOR", label + ". USING %.3f AS DEFAULT"
dd += '%.3f'
dd += ' '
dd = dd[:-2] + '\n' # REMOVE LAST WHITESPACE, ADD NEWLINE
format = dd
#print format
else:
if not silent:
print "Formatting... "
coldec = [0] * nx # OF DECIMAL PLACES
colint = [0] * nx # LENGTH BEFORE DECIMAL PLACE (INCLUDING AN EXTRA ONE IF IT'S NEGATIVE)
#colneg = [0] * nx # WHETHER THE COLUMN HAS ANY NEGATIVE NUMBERS: 1=YES, 0=NO
colexp = [0] * nx # WHETHER THE COLUMN HAS ANY REALLY BIG NUMBERS THAT NEED exp FORMAT : 1=YES, 0=NO
if machine:
maxy = 0
if (ny <= maxy) or not maxy:
yyy = range(ny)
else:
yyy = arange(maxy) * ((ny - 1.) / (maxy - 1.))
yyy = yyy.astype(int)
for iy in yyy:
for ix in range(nx):
datum = data[iy,ix]
if isNaN(datum):
ni, nd = 1, 1
else:
if (abs(datum) > 1.e9) or (0 < abs(datum) < 1.e-5): # IF TOO BIG OR TOO SMALL, NEED exp FORMAT
ni, nd = 1, 3
colexp[ix] = 1
else:
ni = len("% d" % datum) - 1
if ni <= 3:
nd = ndec(datum, max=4)
else:
nd = ndec(datum, max=7-ni)
# Float32: ABOUT 7 DIGITS ARE ACCURATE (?)
if ni > colint[ix]: # IF BIGGEST, YOU GET TO DECIDE NEG SPACE OR NO
colneg[ix] = (datum < 0)
#print '>', ix, colneg[ix], nd, coldec[ix]
elif ni == colint[ix]: # IF MATCH BIGGEST, YOU CAN SET NEG SPACE ON (NOT OFF)
colneg[ix] = (datum < 0) or colneg[ix]
#print '=', ix, colneg[ix], nd, coldec[ix]
coldec[ix] = max([ nd, coldec[ix] ])
colint[ix] = max([ ni, colint[ix] ])
#print colneg
#print colint
#print coldec
collens = []
for ix in range(nx):
if colexp[ix]:
collen = 9 + colneg[ix]
else:
collen = colint[ix] + coldec[ix] + (coldec[ix] > 0) + (colneg[ix] > 0) # EXTRA ONES FOR DECIMAL POINT / - SIGN
if labels and not machine:
collen = max((collen, len(labels[ix]))) # MAKE COLUMN BIG ENOUGH TO ACCOMODATE LABEL
collens.append(collen)
format = ' '
for ix in range(nx):
collen = collens[ix]
format += '%'
if colneg[ix]: # NEGATIVE
format += ' '
if colexp[ix]: # REALLY BIG (EXP FORMAT)
format += '.3e'
else:
if coldec[ix]: # FLOAT
format += "%d.%df" % (collen, coldec[ix])
else: # DECIMAL
format += "%dd" % collen
if ix < nx - 1:
format += separator
else:
format += "\n"
if pf:
print "format='%s\\n'" % format[:-1]
# NEED TO BE ABLE TO ALTER INPUT FORMAT
if machine: # machine readable
collens = [] # REDO collens (IN CASE format WAS INPUT)
mformat = ''
separator = ' '
colformats = string.split(format, '%')[1:]
format = '' # redoing format, too
for ix in range(nx):
#print ix, colformats
cf = colformats[ix]
format += '%'
if cf[0] == ' ':
format += ' '
cf = string.strip(cf)
format += cf
mformat += {'d':'I', 'f':'F', 'e':'E'}[cf[-1]]
mformat += cf[:-1]
if ix < nx - 1:
format += separator
mformat += separator
else:
format += "\n"
mformat += "\n"
# REDO collens (IN CASE format WAS INPUT)
colneg[ix] = string.find(cf, ' ') == -1
if string.find(cf, 'e') > -1:
collen = 9 + colneg[ix]
else:
cf = string.split(cf, '.')[0] # FLOAT: Number before '.'
cf = string.split(cf, 'd')[0] # INT: Number before 'd'
collen = string.atoi(cf)
collens.append(collen)
else:
if not collens:
collens = [] # REDO collens (IN CASE format WAS INPUT)
colformats = string.split(format, '%')[1:]
for ix in range(nx):
cf = colformats[ix]
colneg[ix] = string.find(cf, ' ') == -1
if string.find(cf, 'e') > -1:
collen = 9 + colneg[ix]
else:
cf = string.split(cf, '.')[0] # FLOAT: Number before '.'
cf = string.split(cf, 'd')[0] # INT: Number before 'd'
collen = string.atoi(cf)
if labels:
collen = max((collen, len(labels[ix]))) # MAKE COLUMN BIG ENOUGH TO ACCOMODATE LABEL
collens.append(collen)
## if machine: # machine readable
## mformat = ''
## for ix in range(nx):
## collen = collens[ix]
## if colexp[ix]: # EXP
## mformat += 'E5.3'
## elif coldec[ix]: # FLOAT
## mformat += 'F%d.%d' % (collen, coldec[ix])
## else: # DECIMAL
## mformat += 'I%d' % collen
## if ix < nx - 1:
## mformat += separator
## else:
## mformat += "\n"
if descriptions:
if type(descriptions) == dict: # CONVERT DICTIONARY FORM TO LIST
dd = []
for label in labels:
dd.append(descriptions.get(label, ''))
descriptions = dd
if units:
if type(units) == dict: # CONVERT DICTIONARY FORM TO LIST
dd = []
for label in labels:
dd.append(units.get(label, ''))
units = dd
if not machine:
## if not descriptions:
## descriptions = labels
if labels:
headline = ''
maxcollen = 1
for label in labels:
maxcollen = max([maxcollen, len(label)])
for ix in range(nx):
label = string.ljust(labels[ix], maxcollen)
headline += '# %2d %s' % (ix+1, label)
if descriptions:
if descriptions[ix]:
headline += ' %s' % descriptions[ix]
headline += '\n'
##headline += '# %2d %s %s\n' % (ix+1, label, descriptions[ix])
#ff = '# %%2d %%%ds %%s\n' % maxcollen # '# %2d %10s %s\n'
#headline += ff % (ix+1, labels[ix], descriptions[ix])
#headline += '# %2d %s\n' % (ix+1, descriptions[ix])
headline += '#\n'
headline += '#'
colformats = string.split(format, '%')[1:]
if not silent:
print
for ix in range(nx):
cf = colformats[ix]
collen = collens[ix]
#label = labels[ix][:collen] # TRUNCATE LABEL TO FIT COLUMN DATA
label = labels[ix]
label = string.center(label, collen)
headline += label + separator
headline += '\n'
if not header:
header = [headline]
else:
if header[-1] <> '.': # SPECIAL CODE TO REFRAIN FROM ADDING TO HEADER
header.append(headline)
if skycat:
headline1 = ''
headline2 = ''
for label in labels:
headline1 += label + '\t'
headline2 += '-' * len(label) + '\t'
headline1 = headline1[:-1] + '\n'
headline2 = headline2[:-1] + '\n'
header.append(headline1)
header.append(headline2)
elif machine: # Machine readable Table!
maxlabellen = 0
for ix in range(nx):
flaglabel = 0
if len(labels[ix]) >= 2:
flaglabel = (labels[ix][1] == '_')
if not flaglabel:
labels[ix] = ' ' + labels[ix]
if len(labels[ix]) > maxlabellen:
maxlabellen = len(labels[ix])
# labelformat = '%%%ds' % maxlabellen
if not header:
header = []
header.append('Title:\n')
header.append('Authors:\n')
header.append('Table:\n')
header.append('='*80+'\n')
header.append('Byte-by-byte Description of file: %s\n' % filename)
header.append('-'*80+'\n')
#header.append(' Bytes Format Units Label Explanations\n')
headline = ' Bytes Format Units '
headline += string.ljust('Label', maxlabellen-2)
headline += ' Explanations\n'
header.append(headline)
header.append('-'*80+'\n')
colformats = string.split(mformat)
byte = 1
for ix in range(nx):
collen = collens[ix]
headline = ' %3d-%3d' % (byte, byte + collen - 1) # bytes
headline += ' '
# format:
cf = colformats[ix]
headline += cf
headline += ' ' * (7 - len(cf))
# units:
cu = ''
if units:
cu = units[ix]
if not cu:
cu = '---'
headline += cu
headline += ' '
# label:
label = labels[ix]
headline += string.ljust(labels[ix], maxlabellen)
# descriptions:
if descriptions:
headline += ' '
headline += descriptions[ix]
headline += '\n'
header.append(headline)
byte += collen + 1
header.append('-'*80+'\n')
if notes:
for inote in range(len(notes)):
headline = 'Note (%d): ' % (inote+1)
note = string.split(notes[inote], '\n')
headline += note[0]
if headline[-1] <> '\n':
headline += '\n'
header.append(headline)
if len(note) > 1:
for iline in range(1, len(note)):
if note[iline]: # make sure it's not blank (e.g., after \n)
headline = ' ' * 10
headline += note[iline]
if headline[-1] <> '\n':
headline += '\n'
header.append(headline)
header.append('-'*80+'\n')
if not silent:
print "Saving ", outfile, "...\n"
fout = open(outfile, 'w')
# SPECIAL CODE TO REFRAIN FROM ADDING TO HEADER:
# LAST ELEMENT IS A PERIOD
if header:
if header[-1] == '.':
header = header[:-1]
for headline in header:
fout.write(headline)
if not (headline[-1] == '\n'):
fout.write('\n')
for iy in range(ny):
fout.write(format % tuple(data[iy].tolist()))
fout.close()
def loaddata(filename, dir="", silent=0, headlines=0):
"""Loads an ascii data file (OR TEXT BLOCK) into an array.
Skips header (lines that begin with #), but saves it in the variable 'header', which can be accessed by:
from coeio import header"""
global header
tr = 0
if filename[-1] == '+': # TRANSPOSE OUTPUT
tr = 1
filename = filename[:-1]
if len(filename[0]) > 1:
sin = filename
else:
sin = loadfile(filename, dir, silent)
header = sin[0:headlines]
sin = sin[headlines:]
headlines = 0
while (headlines < len(sin)) and (sin[headlines][0] == '#'):
headlines = headlines + 1
header[len(header):] = sin[0:headlines]
ny = len(sin) - headlines
if ny == 0:
if headlines:
ss = string.split(sin[headlines-1])[1:]
else:
ss = []
else:
ss = string.split(sin[headlines])
nx = len(ss)
#size = [nx,ny]
data = FltArr(ny,nx)
sin = sin[headlines:ny+headlines]
for iy in range(ny):
ss = string.split(sin[iy])
for ix in range(nx):
try:
data[iy,ix] = string.atof(ss[ix])
except:
print ss
print ss[ix]
data[iy,ix] = string.atof(ss[ix])
if tr:
data = transpose(data)
if data.shape[0] == 1: # ONE ROW
return ravel(data)
else:
return data
def loadlist(filename, dir="./"):
"""Loads an ascii data file into a list.
The file has one number on each line.
Skips header (lines that begin with #), but saves it in the variable 'header'."""
global header
# os.chdir("/home/coe/imcat/ksb/A1689txitxo/R/02/")
infile = dirfile(filename, dir)
print "Loading ", infile, "...\n"
fin = open(infile, 'r')
sin = fin.readlines()
fin.close
headlines = 0
while sin[headlines][0] == '#':
headlines = headlines + 1
header = sin[0:headlines-1]
n = len(sin) - headlines
sin = sin[headlines:n+headlines]
list = []
for i in range(n):
list.append(string.atof(sin[i]))
return list
def machinereadable(filename, dir=''):
if filename[-1] == '+':
filename = filename[:-1]
filename = dirfile(filename, dir)
fin = open(filename, 'r')
line = fin.readline()
return line[0] == 'T' # BEGINS WITH Title:
def loadmachine(filename, dir="", silent=0):
"""Loads machine-readable ascii data file into a VarsClass()
FORMAT...
Title:
Authors:
Table:
================================================================================
Byte-by-byte Description of file: datafile1.txt
--------------------------------------------------------------------------------
Bytes Format Units Label Explanations
--------------------------------------------------------------------------------
(columns & descriptions)
--------------------------------------------------------------------------------
(notes)
--------------------------------------------------------------------------------
(data)
"""
cat = VarsClass('')
filename = dirfile(filename, dir)
fin = open(filename, 'r')
# SKIP HEADER
line = ' '
while string.find(line, 'Bytes') == -1:
line = fin.readline()
fin.readline()
# COLUMNS & DESCRIPTIONS
cols = []
cat.labels = []
line = fin.readline()
while line[0] <> '-':
xx = []
xx.append(string.atoi(line[1:4]))
xx.append(string.atoi(line[5:8]))
cols.append(xx)
cat.labels.append(string.split(line[9:])[2])
line = fin.readline()
nx = len(cat.labels)
# NOW SKIP NOTES:
line = fin.readline()
while line[0] <> '-':
line = fin.readline()
# INITIALIZE DATA
for ix in range(nx):
exec('cat.%s = []' % cat.labels[ix])
# LOAD DATA
while line:
line = fin.readline()
if line:
for ix in range(nx):
s = line[cols[ix][0]-1:cols[ix][1]]
#print cols[ix][0], cols[ix][1], s
val = string.atof(s)
exec('cat.%s.append(val)' % cat.labels[ix])
# FINALIZE DATA
for ix in range(nx):
exec('cat.%s = array(cat.%s)' % (cat.labels[ix], cat.labels[ix]))
return cat
def loadpymc(filename, dir="", silent=0):
filename = dirfile(filename, dir)
ind = loaddict(filename+'.ind')
i, data = loaddata(filename+'.out+')
cat = VarsClass()
for label in ind.keys():
ilo, ihi = ind[label]
chunk = data[ilo-1:ihi]
cat.add(label, chunk)
return cat
class Cat2D_xyflip:
def __init__(self, filename='', dir="", silent=0, labels=string.split('x y z')):
if len(labels) == 2:
labels.append('z')
self.labels = labels
if filename:
if filename[-1] <> '+':
filename += '+'
self.data = loaddata(filename, dir)
self.assigndata()
def assigndata(self):
exec('self.%s = self.x = self.data[1:,0]' % self.labels[0])
exec('self.%s = self.y = self.data[0,1:]' % self.labels[1])
exec('self.%s = self.z = self.data[1:,1:]' % self.labels[2])
def get(self, x, y, dointerp=0):
ix = interp(x, self.x, arange(len(self.x)))
iy = interp(y, self.y, arange(len(self.y)))
if not dointerp: # JUST GET NEAREST
#ix = searchsorted(self.x, x)
#iy = searchsorted(self.y, y)
ix = roundint(ix)
iy = roundint(iy)
z = self.z[ix,iy]
else:
z = bilin2(iy, ix, self.z)
return z
class Cat2D:
def __init__(self, filename='', dir="", silent=0, labels=string.split('x y z')):
if len(labels) == 2:
labels.append('z')
self.labels = labels
if filename:
if filename[-1] == '+':
filename = filename[:-1]
self.data = loaddata(filename, dir)
self.assigndata()
def assigndata(self):
exec('self.%s = self.x = self.data[0,1:]' % self.labels[0])
exec('self.%s = self.y = self.data[1:,0]' % self.labels[1])
exec('self.%s = self.z = self.data[1:,1:]' % self.labels[2])
def get(self, x, y, dointerp=0):
ix = interp(x, self.x, arange(len(self.x)))
iy = interp(y, self.y, arange(len(self.y)))
if not dointerp: # JUST GET NEAREST
#ix = searchsorted(self.x, x)
#iy = searchsorted(self.y, y)
ix = roundint(ix)
iy = roundint(iy)
z = self.z[iy,ix]
else:
z = bilin2(ix, iy, self.z)
return z
def loadcat2d(filename, dir="", silent=0, labels='x y z'):
"""INPUT: ARRAY w/ SORTED NUMERIC HEADERS (1ST COLUMN & 1ST ROW)
OUTPUT: A CLASS WITH RECORDS"""
if type(labels) == str:
labels = string.split(labels)
outclass = Cat2D(filename, dir, silent, labels)
#outclass.z = transpose(outclass.z) # NOW FLIPPING since 12/5/09
return outclass
def savecat2d(data, x, y, filename, dir="", silent=0):
"""OUTPUT: FILE WITH data IN BODY AND x & y ALONG LEFT AND TOP"""
x = x.reshape(1, len(x))
data = concatenate([x, data])
y = concatenate([[0], y])
y = y.reshape(len(y), 1)
data = concatenate([y, data], 1)
if filename[-1] == '+':
filename = filename[:-1]
savedata(data, filename, dir, header='.')
def savecat2d_xyflip(data, x, y, filename, dir="", silent=0):
"""OUTPUT: FILE WITH data IN BODY AND x & y ALONG LEFT AND TOP"""
#y = y[NewAxis, :]
y = reshape(y, (1, len(y)))
data = concatenate([y, data])
x = concatenate([[0], x])
#x = x[:, NewAxis]
x = reshape(x, (len(x), 1))
data = concatenate([x, data], 1)
if filename[-1] <> '+':
filename += '+'
#savedata(data, filename)
savedata1(data, filename, dir)
def savedata1d(data, filename, dir="./", format='%6.5e ', header=""):
fout = open(filename, 'w')
for datum in data:
fout.write('%d\n' % datum)
fout.close()
def loadvars(filename, dir="", silent=0):
"""INPUT: CATALOG w/ LABELED COLUMNS
OUTPUT: A STRING WHICH WHEN EXECUTED WILL LOAD DATA INTO VARIABLES WITH NAMES THE SAME AS COLUMNS
>>> exec(loadvars('file.cat'))
NOTE: DATA IS ALSO SAVED IN ARRAY data"""
global data, labels, labelstr