Debian Codegraph @

commissioning/basecase.py

raw symbols SCIP
1 from pytools import testutil
2 import pysynphot as S
3 import numpy as N
4 from astropy.io import fits as pyfits
5 from pysynphot import etc
6 from pyraf import iraf
7 from iraf import stsdas,hst_calib,synphot
8 import os,time,re
9 from pysynphot.wavetable import wavetable as Wavecat
10 from pysynphot.observationmode import ObservationMode
11
12
13 class calcspecCase(testutil.LogTestCase):
14 def setUp(self):
15 self.obsmode=None
16 self.spectrum=None
17 self.runpy()
18 self.skip=True
19
20 def hasSkyLines(self):
21 lnames="el1215a|el1302a|el1356a|el2471a"
22 ans=re.findall(lnames,self.spectrum)
23 if len(ans) > 0:
24 return True
25 else:
26 return False
27
28 def setglobal(self,fname=None):
29 if fname is None:
30 fname=__file__
31 self.propername=self.id()
32 base,ext=os.path.splitext(os.path.basename(fname))
33 main,case,test=self.propername.split('.')
34 self.name=os.path.join(base,test,case)
35 self.wavename=self.name+'_wave.fits'
36 #Make sure the directories exist
37 dirname=os.path.dirname(self.name)
38 if not os.path.isdir(dirname):
39 os.makedirs(dirname)
40
41 self.file=self.name
42 self.thresh=0.01
43 self.superthresh=0.20
44 self.sigthresh=0.01
45 self.discrep=-99
46 self.tda={'Obsmode':self.obsmode,
47 'Spectrum':self.spectrum,
48 'ETCid':None, #placeholder
49 'Thresh':self.thresh,
50 'Superthresh':self.superthresh,
51 'SigThresh':self.sigthresh,
52 'crrefer':iraf.osfn('crrefer$'),
53 'pysyn_cdbs':os.environ['PYSYN_CDBS'],
54 'SkyLines':self.hasSkyLines()}
55 try:
56 self.tda['Subset']=self.subset
57 except AttributeError:
58 pass
59 try:
60 self.tda['ETCid']=self.etcid
61 except AttributeError:
62 pass
63 try:
64 self.tda['form']=self.form
65 except AttributeError:
66 pass
67
68 self.tra={}
69
70 def run_crbox(self,spstring,form,output="",wavecat="INDEF",
71 lowave=0,hiwave=30000):
72 """Calcspec has a bug. We will use countrate instead, and force it
73 to use a box function of uniform transmission as the obsmode."""
74
75 range=hiwave-lowave
76 midwave=range/2.0
77 iraf.countrate(spectrum=spstring, magnitude="",
78 instrument="box(%f,%f)"%(midwave,range),
79 form=form,
80 wavecat=wavecat,
81 output=output)
82
83
84 def run_countrate(self,form,output=None):
85 if output is None:
86 output=""
87 count=0
88 while count < 10:
89 try:
90 iraf.countrate(spectrum=self.spectrum,magnitude="",
91 instrument=self.obsmode,
92 output=output,form=form)
93 break
94 except iraf.IrafError as e:
95 count+=1
96 pass
97
98 if count == 10:
99 raise(e)
100
101 def runpy(self):
102 self.sptest=etc.parse_spec(self.spectrum)
103 self.csname=self.name+'.fits'
104 self.specname=self.name+'_spec.fits'
105 for name in (self.csname, self.specname, self.wavename):
106 try:
107 os.remove(name)
108 except OSError:
109 pass
110
111 def arraydiff(self,test,ref):
112 idx=N.nonzero(ref)
113 ans=(test[idx]-ref[idx])/ref[idx]
114 return ans
115
116 def arraysigtest(self,test,ref):
117 #Raise an error if the arrays are not the same size
118 if test.shape != ref.shape:
119 raise ValueError("Array size mismatch")
120 tt=test[2:-2]
121 rr=ref[2:-2]
122 #Identify the significant elements
123 tidx=N.where(tt>(self.sigthresh*tt.max()))[0]
124 ridx=N.where(rr>(self.sigthresh*rr.max()))[0]
125 #Set a flag if they're not the same set
126 if not (N.alltrue(tidx == ridx)):
127 self.tra['SigElemDiscrep']=True
128 tidx=ridx
129
130 #Now compare only the significant elements.
131 #We no longer need to exclude points with zero value, because
132 #those points were already excluded as insignificant.
133 self.arraytest(tt[ridx],rr[ridx])
134
135
136 def count_outliers(self,Nsigma=3):
137 mean=self.adiscrep.mean()
138 std=self.adiscrep.std()
139 outliers=N.where(abs(self.adiscrep) > mean + Nsigma*std)
140 return len(outliers[0])
141
142 def arraytest(self,test,ref):
143 #Exclude the endpoints where the gradient is very steep
144 self.adiscrep=self.arraydiff(test,ref)#[2:-2]
145 count=N.where(abs(self.adiscrep)>self.thresh)[0].size
146 try:
147 self.tra['Discrepfrac']=float(count)/self.adiscrep.size
148 self.tra['Discrepmin']=self.adiscrep.min()
149 self.tra['Discrepmax']=self.adiscrep.max()
150 self.tra['Discrepmean']=self.adiscrep.mean()
151 self.tra['Discrepstd']=self.adiscrep.std()
152 self.tra['Outliers']=self.count_outliers(5)
153 if (self.tra['Discrepfrac'] > self.superthresh):
154 self.tra['Extreme']=True
155 self.failUnless(N.alltrue(abs(self.adiscrep)<self.thresh),
156 msg="Worst case %f"%abs(self.adiscrep).max())
157 except ZeroDivisionError:
158 self.tra['Discrepfrac']=0.0
159 self.tra['Discrepmin']=0.0
160 self.tra['Discrepmax']=0.0
161
162
163 def savepysyn(self,wave,flux,fname,units=None):
164 """ Cannot ever use the .writefits() method, because the array is
165 frequently just sampled at the synphot waveset; plus, writefits
166 is smart and does things like tapering."""
167 if units is None:
168 ytype='throughput'
169 units=' '
170 else:
171 ytype='flux'
172 col1=pyfits.Column(name='wavelength',format='D',array=wave)
173 col2=pyfits.Column(name=ytype,format='D',array=flux)
174 tbhdu=pyfits.BinTableHDU.from_columns(pyfits.ColDefs([col1,col2]))
175 tbhdu.header.update('tunit1','angstrom')
176 tbhdu.header.update('tunit2',units)
177 tbhdu.writeto(fname.replace('.fits','_pysyn.fits'))
178
179 def testcrspec(self):
180 #Use countrate with a box; use the native waveset as the waveset
181 wname='/tmp/%s_box.cat'%os.path.basename(self.name)
182 self.sptest.convert('photlam')
183 self.sptest.writefits(self.csname.replace('.fits','_pysyn.fits'),
184 precision='single')
185
186 out=open(wname,'w')
187 out.write('box %s\n'%self.csname.replace('.fits','_pysyn.fits'))
188 out.close()
189
190 #Put this in a loop to compensate for an apparent race condition
191 #that sometimes prevents the IRAF task from opening the file.
192 count=0
193 while count<10:
194 try:
195 self.run_crbox(self.spectrum,'photlam',
196 output=self.csname,
197 wavecat=wname,
198 hiwave=self.sptest.wave.max())
199 break
200 except iraf.IrafError as e:
201 count+=1
202 pass
203
204 if count == 10:
205 raise e
206
207 os.unlink(wname)
208
209 #Now do the comparison
210 spref=S.FileSpectrum(self.csname)
211 ridx=N.where(spref.wave >= 900.0)
212 rflux=spref.flux[ridx]
213 tflux=self.sptest(spref.wave[ridx])
214 self.arraysigtest(tflux,rflux)
215
216 class calcphotCase(calcspecCase):
217 Extrap=None
218 def runpy(self):
219 self.sptest=etc.parse_spec(self.spectrum)
220 self.bp=S.ObsBandpass(self.obsmode)
221 self.cbname=self.name+'.fits'
222 self.csname=self.name+'_cs.fits'
223
224 for fname in (self.cbname, self.csname):
225 try:
226 os.remove(fname)
227 os.remove(fname.replace('.fits','_pysyn.fits'))
228 except OSError:
229 pass
230 self.discrep=-99
231
232
233
234
235 def testthru(self):
236 iraf.calcband(obsmode=self.obsmode,output=self.cbname)
237 ref=S.FileBandpass(self.cbname)
238 rthru=ref.throughput
239 rwave=ref.wave
240 tthru=self.bp(rwave)
241 self.savepysyn(rwave,tthru,self.cbname)
242 self.arraysigtest(tthru,rthru)
243
244
245 def testefflam(self):
246 iraf.calcphot(obsmode=self.obsmode,spectrum=self.spectrum,
247 form='photlam', func='efflerg')
248 rlam=iraf.calcphot.getParam('calcphot.result',native=1)
249 obs=S.Observation(self.sptest,self.bp,force=self.Extrap)
250 tlam=obs.efflam()
251 if rlam != 0:
252 self.discrep=(tlam-rlam)/rlam
253 else:
254 self.discrep=tlam-rlam
255 self.tra['Discrep']=self.discrep
256 if abs(self.discrep)>self.superthresh:
257 self.tra['Extreme']=True
258 self.tra['Syn']=rlam
259 self.tra['Pysyn']=tlam
260
261 self.failUnless(abs(self.discrep) < self.thresh,msg="Discrep=%f"%self.discrep)
262
263 class calcphotOverlapCase(calcphotCase):
264 Extrap='taper'
265
266 class effstimCase(calcphotCase):
267 def testeffstim(self):
268 iraf.calcphot(obsmode=self.obsmode,spectrum=self.spectrum,
269 form=self.form,func='effstim')
270 rcounts=iraf.calcphot.getParam('calcphot.result',native=1)
271 obs=S.Observation(self.sptest,self.bp)
272 tcounts=obs.effstim(self.form)
273 self.tra['Syn']=rcounts
274 self.tra['Pysyn']=tcounts
275
276 if rcounts != 0:
277 self.discrep=(tcounts-rcounts)/rcounts
278 else:
279 self.discrep=tcounts-rcounts
280 self.tra['Discrep']=self.discrep
281 if abs(self.discrep)>self.superthresh:
282 self.tra['Extreme']=True
283
284 self.failUnless(abs(self.discrep) < self.thresh,msg="Discrep=%f"%self.discrep)
285 def testthru(self):
286 __test__ = False
287 def testefflam(self):
288 __test__ = False
289
290
291 class thermbackCase(calcspecCase):
292
293 def runpy(self):
294
295 #self.sptest=etc.parse_spec(self.spectrum)
296 self.bp=S.ObsBandpass(self.obsmode)
297 self.cbname=self.name+'.fits'
298 self.csname=self.name+'_cs.fits'
299
300 for fname in (self.cbname, self.csname):
301 try:
302 os.remove(fname)
303 os.remove(fname.replace('.fits','_pysyn.fits'))
304 except OSError:
305 pass
306 self.discrep=-99
307
308 #Both tests need this
309 omode=ObservationMode(self.obsmode)
310 self.sptest=omode.ThermalSpectrum()
311 self.ttherm=self.sptest.integrate()*omode.pixscale**2*omode.area
312 self.sptest.convert('counts')
313
314
315 def testcrspec(self):
316 iraf.thermback(obsmode=self.obsmode,form='counts',
317 output=self.csname)
318
319 spref=S.FileSpectrum(self.csname)
320 self.savepysyn(spref.wave,self.sptest.sample(spref.wave),
321 self.csname,units='counts')
322
323 ridx=N.where(spref.wave >= 900.0)
324 rflux=spref.flux[ridx]
325 tflux=self.sptest.sample(spref.wave[ridx])
326 self.arraysigtest(tflux,rflux)
327
328
329 ##-----------------------------------------------------------------------
330 ## The wave arrays are never equal; comment out this test.
331 ##........................................................................
332 ## def testthermspec(self):
333 ## ref=S.FileSpectrum(self.csname)
334 ## if N.any(self.sp.wave != ref.wave):
335 ## raise ValueError('wave arrays not equal')
336 ## self.arraysigtest(self.sp.flux,ref.flux)
337
338 def testthermback(self):
339 iraf.thermback(obsmode=self.obsmode,form='counts')
340 rtherm=iraf.thermback.getParam('thermback.thermflux',native=1)
341 ttherm=self.ttherm
342 if rtherm != 0:
343 self.discrep=(ttherm-rtherm)/rtherm
344 else:
345 self.discrep=ttherm-rtherm
346 self.tra['Discrep']=self.discrep
347 if abs(self.discrep)>self.superthresh:
348 self.tra['Extreme']=True
349 self.tra['Syn']=rtherm
350 self.tra['Pysyn']=ttherm
351
352 self.failUnless(abs(self.discrep) < self.thresh,msg="Discrep=%f"%self.discrep)
353
354
355
356 class countrateCase(calcphotCase):
357 Extrap=None
358 def runpy(self):
359 self.sptest=etc.parse_spec(self.spectrum)
360 self.bp=S.ObsBandpass(self.obsmode)
361 self.csname=self.name+'_cs.fits'
362 self.crname=self.name+'_cr.fits'
363 self.cbname=self.name+'.fits'
364 for fname in (self.cbname, self.csname, self.crname):
365 try:
366 os.remove(fname)
367 os.remove(fname.replace('.fits','_pysyn.fits'))
368 except OSError:
369 pass
370 def testcrphotlam(self):
371 self.run_countrate('photlam',self.crname)
372 spref=S.FileSpectrum(self.crname)
373 obs=S.Observation(self.sptest,self.bp,binset=spref.wave,force=self.Extrap)
374 obs.convert('photlam')
375 ridx=N.where(spref.wave >= 900.0)
376 rflux=spref.flux[ridx]
377 tidx=N.where(obs.binwave >= 900.0)
378 tflux=obs.binflux[tidx]
379 self.savepysyn(obs.binwave,obs.binflux,
380 self.crname,units='photlam')
381
382 self.arraysigtest(tflux,rflux)
383
384 def testcrcounts(self):
385 self.run_countrate('counts',self.crname.replace('.fits','_counts.fits'))
386 spref=S.FileSpectrum(self.crname.replace('.fits','_counts.fits'))
387 obs=S.Observation(self.sptest,self.bp,binset=spref.wave,force=self.Extrap)
388 obs.convert('counts')
389 ridx=N.where(spref.wave >= 900.0)
390 rflux=spref.flux[ridx]
391 tidx=N.where(obs.binwave >= 900.0)
392 tflux=obs.binflux[tidx]
393 self.savepysyn(obs.binwave,obs.binflux,
394 self.crname.replace('.fits','_counts.fits'),
395 units='counts')
396 if N.any(obs.binwave != spref.wave):
397 raise ValueError('wave arrays not equal')
398
399 self.arraysigtest(tflux,rflux)
400
401 def testcountrate(self):
402 obs=S.Observation(self.sptest,self.bp,force=self.Extrap)
403 self.run_countrate('counts')
404 rval=iraf.countrate.getParam('flux_tot',native=1)
405 tval=obs.countrate()
406 if rval != 0:
407 self.discrep=(tval-rval)/rval
408 else:
409 self.discrep=tval-rval
410 self.tra['Discrep']=self.discrep
411 self.tra['Syn']=rval
412 self.tra['Pysyn']=tval
413 if abs(self.discrep)>self.superthresh:
414 self.tra['Extreme']=True
415 self.failUnless(abs(self.discrep) < self.thresh,msg="Discrep=%f"%self.discrep)
416
417 class countrateOverlapCase(countrateCase):
418 Extrap='taper'
419
420 class SpecSourcerateSpecCase(countrateCase):
421 Extrap=None
422 def placeholder(self):
423 pass
424
425 class SpecSourcerateSpecOverlapCase(countrateCase):
426 Extrap='taper'