Debian Codegraph @

commissioning/extrap/extrap.py

raw symbols SCIP
1 """This script will operate on throughput files to bound them
2 with zeros. There are three kinds of files to be considered:
3 - simple files with wavelength and throughput only
4 - simple files with wavelength, throughput, and error
5 - parameterized files with multiple throughput columns
6
7 The procedure will be:
8 - determine what kind of file it is
9 - determine whether it needs to be zero-bounded
10 - apply the zero-bounding to all necessary columns
11 - update the history or comment records accordingly
12 """
13
14 from __future__ import print_function
15 import re, time, os, sys
16 from astropy.io import fits as pyfits
17 import numpy as N
18
19 __version__='1.1d'
20
21
22 def classify_file(f):
23 """Examine the column names to determine which type of file
24 this is. Return a tuple:
25 retvalue[0] = "file is non-parameterized"
26 retvalue[1] = "file contains error column"
27 """
28 cols=f[1].columns
29 if len(cols) == 2:
30 #Then we must have a simple file
31 return (True,False)
32 elif len(cols) == 3 and ('ERROR' in cols.names):
33 return (True,True)
34 elif len(cols) > 2 and ('ERROR' not in cols.names):
35 return (True,False)
36 else:
37 return (False,True)
38
39 def run(fname,outdir=None):
40
41 if outdir is not None and not os.path.isdir(outdir):
42 os.mkdir(outdir)
43
44 dwave=0.001
45 f=pyfits.open(fname)
46 nonparam,error=classify_file(f)
47 #Check whether a fix is needed
48 if nonparam: #just check column 1 = throughput
49 t=f[1].data.field(1)
50 ok = (t[0]==0.0) and (t[-1]==0.0)
51 else:
52 ok=False
53 cols=f[1].columns
54 for k in range(1,len(cols)):
55 if 'err' not in cols[k].name.lower():
56 t=f[1].data.field(k)
57 ok = ok and ( (t[0]==0.0) and (t[-1]==0.0) )
58
59 if ok:
60 f.close()
61 return "%s: no change necessary"%fname
62
63
64 #If not ok, we fall through to here.
65 #We're going to have to make a new hdu
66 clist=[]
67 #And we need column info from the existing hdu
68 cols=f[1].columns
69 #Always make a new wavelength array
70 w=f[1].data.field(0)
71 nrows=len(w)
72 wave=N.zeros((nrows+2,),dtype=w.dtype)
73 wave[1:-1]=w
74 wave[0]=w[0]-dwave
75 wave[-1]=w[-1]+dwave
76 wc=pyfits.Column(name=cols[0].name,
77 format=cols[0].format,
78 array=wave)
79 clist.append(wc)
80 #Stick zeros on the ends of all other columns, unless
81 #there's an "ERR" in their name
82
83 padval={True:100,False:0}
84 for k in range(1,len(cols)):
85 t=f[1].data.field(k)
86 thru=N.zeros((nrows+2,),dtype=t.dtype)
87 thru[1:-1]=t
88 pv=padval[("err" in cols.names[k].lower())]
89 thru[0]=thru[-1]=pv
90 tc=pyfits.Column(name=cols[k].name,
91 format=cols[k].format,
92 array=thru)
93 clist.append(tc)
94
95 #Now we have all the columns; put them in an HDU
96 tbhdu=pyfits.BinTableHDU.from_columns(clist)
97 #and copy in the header information we need
98 h=f[1].header.copy()
99 h.update('NAXIS1',tbhdu.header['NAXIS1'])
100 h.update('NAXIS2',tbhdu.header['NAXIS2'])
101 tbhdu.header=h
102
103
104 #Replace the HDU
105 f[1]=tbhdu
106
107 #Update the primary header
108 f[0].header.add_history(time.asctime())
109 f[0].header.add_history("..Added a point with throughput=0 at each end of the")
110 f[0].header.add_history("..throughput curves (dLambda=.001A) using the script")
111 f[0].header.add_history("..extrap.py v%s. V. Laidler"%__version__)
112
113 #And write out the new file
114 if outdir is not None:
115 newname=os.path.join(outdir,fincre(fname))
116 else:
117 newname=fincre(fname)
118 f.writeto(newname)
119
120 return("%s -> %s"%(fname, newname))
121
122
123
124 def blue(fname,outdir=None):
125 """Cut&pasted from run, but to operate only on blue end."""
126 if outdir is not None and not os.path.isdir(outdir):
127 os.mkdir(outdir)
128
129 dwave=0.001
130 f=pyfits.open(fname)
131 nonparam,error=classify_file(f)
132 #Check whether a fix is needed
133 if nonparam: #just check column 1 = throughput
134 t=f[1].data.field(1)
135 ok = (t[0]==0.0) and (t[-1]==0.0)
136 else:
137 ok=False
138 cols=f[1].columns
139 for k in range(1,len(cols)):
140 if 'err' not in cols[k].name.lower():
141 t=f[1].data.field(k)
142 ok = ok and ( (t[0]==0.0) and (t[-1]==0.0) )
143
144 if ok:
145 f.close()
146 return "%s: no change necessary"%fname
147
148
149 #If not ok, we fall through to here.
150 #We're going to have to make a new hdu
151 clist=[]
152 #And we need column info from the existing hdu
153 cols=f[1].columns
154 #Always make a new wavelength array
155 w=f[1].data.field(0)
156 nrows=len(w)
157 wave=N.zeros((nrows+1,),dtype=w.dtype)
158 wave[1:]=w
159 wave[0]=w[0]-dwave
160
161 wc=pyfits.Column(name=cols[0].name,
162 format=cols[0].format,
163 array=wave)
164 clist.append(wc)
165 #Stick zeros on the ends of all other columns, unless
166 #there's an "ERR" in their name
167
168 padval={True:100,False:0}
169 for k in range(1,len(cols)):
170 t=f[1].data.field(k)
171 thru=N.zeros((nrows+1,),dtype=t.dtype)
172 thru[1:]=t
173 pv=padval[("err" in cols.names[k].lower())]
174 thru[0]=pv
175 tc=pyfits.Column(name=cols[k].name,
176 format=cols[k].format,
177 array=thru)
178 clist.append(tc)
179
180 #Now we have all the columns; put them in an HDU
181 tbhdu=pyfits.BinTableHDU.from_columns(clist)
182 #and copy in the header information we need
183 h=f[1].header.copy()
184 h.update('NAXIS1',tbhdu.header['NAXIS1'])
185 h.update('NAXIS2',tbhdu.header['NAXIS2'])
186 tbhdu.header=h
187
188
189 #Replace the HDU
190 f[1]=tbhdu
191
192 #Update the primary header
193 f[0].header.add_history(time.asctime())
194 f[0].header.add_history("..Added a point with throughput=0 at blue end of the")
195 f[0].header.add_history("..throughput curves (dLambda=.001A) using the script")
196 f[0].header.add_history("..extrap.py v%s. V. Laidler"%__version__)
197
198 #And write out the new file
199 if outdir is not None:
200 newname=os.path.join(outdir,fincre(fname))
201 else:
202 newname=fincre(fname)
203 f.writeto(newname)
204
205 return("%s -> %s"%(fname, newname))
206
207 def fincre(oldname):
208 """Increment the synphot version number from a filename"""
209 x=re.search('_(?P<version>[0-9][0-9][0-9])_syn',oldname)
210 version=x.group('version')
211 newversion="%03d"%(int(version)+1)
212 ans=oldname.replace(version,newversion)
213 return ans
214
215
216 if __name__ == '__main__':
217 for fname in sys.argv[1:]:
218 retval=run(fname)
219 print(retval)
220
221 def buildtmc(tmcname):
222 from pyraf import iraf
223 from iraf import stsdas,hst_calib,synphot
224 out=open('buildtmc.log','w')
225 f=pyfits.open(tmcname)
226 flist=f[1].data.field('filename')
227 iraf.set(crrefer='./') #work locally
228
229 for k in range(len(flist)):
230 oldname=iraf.osfn(flist[k]).split('[')[0]
231 newname=fincre(oldname)
232 if os.path.exists(newname):
233 flist[k]=fincre(flist[k])
234 else:
235 out.write("%s: no change necessary\n"%oldname)
236 f.writeto(tmcname.replace(".fits","_new.fits"))
237 out.close()