Debian Codegraph @

commissioning/convert/conv_base.py

raw symbols SCIP
1 """Contains SpecCase used by commissioning_cases.CommCase*.
2 Defines all the common setup and testing.
3 """
4
5 import os
6
7 import numpy as N
8 import pysynphot as S
9 from pysynphot import etc
10 #For thermal classes only
11 from pysynphot.observationmode import ObservationMode
12
13 #BUG: find a better way
14 HERE = os.getcwd()
15 DATADIR = os.path.join(os.path.dirname(HERE),
16 'data')
17
18 #TODO: set a specified graph/comp/therm table set in a module setup
19
20 class SpecCase(object):
21 @classmethod
22 def setUpClass(cls):
23 """Always overridden by the child cases, but let's put some
24 real values in here to test with"""
25 self.obsmode=None
26 self.spectrum=None
27 self.bp=None
28 self.sp=None
29 self.obs=None
30 self.setup2()
31
32 @classmethod
33 def setup2(cls):
34 #Do the common setup here.
35 cls.sigthresh = 0.01
36 cls.thresh = 0.01
37 cls.tda=dict(obsmode=cls.obsmode,
38 spectrum=cls.spectrum,
39 thresh=cls.thresh,
40 sigthresh=cls.sigthresh)
41 cls.tra=dict()
42
43
44 if cls.obsmode != "None":
45 cls.bp=S.ObsBandpass(cls.obsmode)
46 cls.bp.writefits(cls.fname%'thru', clobber=True,
47 trimzero=False)
48 cls.tra['thru']=cls.bp.name
49 else:
50 cls.bp = None
51
52
53 if cls.spectrum != "None":
54 #All the data lives in a parallel directory, so go sit there
55 #in case we need a file
56 os.chdir(DATADIR)
57 cls.sp=etc.parse_spec(cls.spectrum)
58 os.chdir(HERE)
59 cls.sp.writefits(cls.fname%'spec', clobber=True,
60 trimzero=False)
61 cls.tra['sp']=cls.sp.name
62 else:
63 cls.sp = None
64
65
66 if "None" not in (cls.obsmode, cls.spectrum):
67 cls.obs = S.Observation(cls.sp, cls.bp)
68 cls.obs.convert('counts')
69 x = dict(PSCNTRAT = (cls.obs.countrate(),'countrate'),
70 PSEFFLAM = (cls.obs.efflam(),'efflam'))
71 cls.obs.writefits(cls.fname%'obs', hkeys=x, clobber=True,
72 trimzero=False)
73 cls.tra['obs']=cls.obs.name
74 else:
75 cls.obs = None
76
77 #Helper methods for arrays
78 def count_outliers(self,Nsigma=3):
79 mean=self.adiscrep.mean()
80 std=self.adiscrep.std()
81 outliers=N.where(abs(self.adiscrep) > mean + Nsigma*std)
82 return len(outliers[0])
83
84 def arraysigtest(self,ref,test):
85 #Raise an error if the arrays are not the same size
86 if test.shape != ref.shape:
87 raise ValueError("Array size mismatch")
88 tt=test[2:-2]
89 rr=ref[2:-2]
90 #Identify the significant elements
91 tidx=N.where(tt>(self.sigthresh*tt.max()))[0]
92 ridx=N.where(rr>(self.sigthresh*rr.max()))[0]
93 #Set a flag if they're not the same set
94 if not (N.alltrue(tidx == ridx)):
95 self.tra['SigElemDiscrep']=True
96 tidx=ridx
97
98 #Now compare only the significant elements.
99 #We no longer need to exclude points with zero value, because
100 #those points were already excluded as insignificant.
101 self.arraytest(tt[ridx],rr[ridx])
102
103 def arraydiff(self,test,ref):
104 idx=N.nonzero(ref)
105 ans=(test[idx]-ref[idx])/ref[idx]
106 return ans
107
108 def arraytest(self,ref,test):
109 self.adiscrep=self.arraydiff(test,ref)
110 count=N.where(abs(self.adiscrep)>self.thresh)[0].size
111 try:
112 self.tra['Discrepfrac']=float(count)/self.adiscrep.size
113 self.tra['Discrepmin']=self.adiscrep.min()
114 self.tra['Discrepmax']=self.adiscrep.max()
115 self.tra['Discrepmean']=self.adiscrep.mean()
116 self.tra['Discrepstd']=self.adiscrep.std()
117 self.tra['Outliers']=self.count_outliers(5)
118 self.failUnless(N.alltrue(abs(self.adiscrep)<self.thresh),
119 msg="Worst case %f"%abs(self.adiscrep).max())
120 except ZeroDivisionError:
121 self.tra['Discrepfrac']=0.0
122 self.tra['Discrepmin']=0.0
123 self.tra['Discrepmax']=0.0
124
125 #Helper method for scalar comparison
126 def tcompare(self,rval,tval):
127 if rval != 0:
128 self.discrep=(tval-rval)/rval
129 else:
130 self.discrep=tval-rval
131 self.tra['Discrep']=self.discrep
132 self.tra['ref']=rval
133 self.tra['tst']=tval
134 self.failUnless(abs(self.discrep) < self.thresh,
135 msg="Discrep=%f"%self.discrep)
136
137 def failUnless(self, expr, msg=None):
138 #Copied from unittest.TestCase
139 """Fail the test unless the expression is true."""
140 if not expr: raise self.failureException(msg)
141
142
143 #The actual tests start here.
144 #In the parent case, we do spectrum-only tests.
145
146 def testspec(self):
147 if self.sp:
148 self.spref = S.FileSpectrum((self.fname%'spec').replace('.fits','_ref.fits'))
149 self.arraytest(self.spref.flux, self.sp.flux)
150
151 class CommCase(SpecCase):
152 #In the default case, we also do throughput and observation tests
153 def testthru(self):
154 self.bpref = S.FileBandpass((self.fname%'thru').replace('.fits','_ref.fits'))
155 self.arraytest(self.bpref.throughput, self.bp.throughput)
156
157
158 def testobs(self):
159 self.obsref = S.FileSpectrum((self.fname%'obs').replace('.fits','_ref.fits'))
160 self.arraytest(self.obsref.flux, self.obs.binflux)
161
162 def testcntrate(self):
163 self.obsref = S.FileSpectrum((self.fname%'obs').replace('.fits','_ref.fits'))
164 self.tcompare(self.obsref.fheader['PSCNTRAT'],
165 self.obs.countrate())
166
167 def testefflam(self):
168 self.obsref = S.FileSpectrum((self.fname%'obs').replace('.fits','_ref.fits'))
169 self.tcompare(self.obsref.fheader['PSEFFLAM'],
170 self.obs.efflam())
171
172 class ThermCase(CommCase):
173 #In the thermal case, we also do thermal tests.
174
175 @classmethod
176 def setup2(cls):
177 #First call the parent
178 super(CommCase,cls).setup2()
179
180 #Then do the thermal stuff
181 cls.omode=ObservationMode(cls.obsmode)
182 cls.thspec=cls.omode.ThermalSpectrum()
183 cls.tra['thspec']=cls.thspec.name
184
185 cls.thspec.convert('counts')
186 cls.thermback=cls.thspec.integrate()*cls.omode.pixscale**2*cls.omode.area
187 x = dict(PSTHMBCK = (cls.thermback,'thermback'))
188 cls.thspec.writefits(cls.fname%'therm', clobber=True,
189 trimzero=False, hkeys=x)
190
191 def testthspec(self):
192 self.thref = S.FileSpectrum((self.fname%'therm').replace('.fits','_ref.fits'))
193 self.arraytest(self.thref.flux, self.thspec.flux)
194
195
196 def testhermback(self):
197 self.thref = S.FileSpectrum((self.fname%'therm').replace('.fits','_ref.fits'))
198 self.tcompare(self.thref.fheader['PSTHMBCK'],
199 self.thermback)
200
201 class Testing(CommCase):
202 @classmethod
203 def setUpClass(cls):
204 cls.obsmode="stis,e230h,i1913"
205 cls.spectrum="bb(30000)"
206 cls.fname="T1_%s.fits"
207 cls.setup2()