test_SpecDisperse.py 25.5 KB
Newer Older
Zhang Xin's avatar
Zhang Xin committed
1
#
2
#need add environment parameter  UNIT_TEST_DATA_ROOT, link to "testData/"
Zhang Xin's avatar
Zhang Xin committed
3
#linx and mac can run as follow, need modify the name of file directory
4
#export UNIT_TEST_DATA_ROOT=/Users/zhangxin/Work/SlitlessSim/CSST_SIM/CSST_develop/csst-simulation/tests/testData
Zhang Xin's avatar
Zhang Xin committed
5
#
6
7
8
import unittest
from ObservationSim.MockObject.SpecDisperser import rotate90, SpecDisperser

9
from ObservationSim.Config import ChipOutput
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
from ObservationSim.Instrument import Telescope, Chip, FilterParam, Filter, FocalPlane
from ObservationSim.MockObject import MockObject, Star
from ObservationSim.PSF import PSFGauss

import numpy as np
import galsim
from astropy.table import Table
from scipy import interpolate

import matplotlib.pyplot as plt

from lmfit.models import LinearModel, GaussianModel

from ObservationSim.Config.Header import generateExtensionHeader
import math
import yaml
26
import os
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


def getAngle132(x1=0, y1=0, z1=0, x2=0, y2=0, z2=0, x3=0, y3=0, z3=0):
    cosValue = 0;
    angle = 0;

    x11 = x1 - x3;
    y11 = y1 - y3;
    z11 = z1 - z3;

    x22 = x2 - x3;
    y22 = y2 - y3;
    z22 = z2 - z3;

    tt = np.sqrt((x11 * x11 + y11 * y11 + z11 * z11) * (x22 * x22 + y22 * y22 + z22 * z22));
    if (tt == 0):
        return 0;

    cosValue = (x11 * x22 + y11 * y22 + z11 * z22) / tt;

    if (cosValue > 1):
        cosValue = 1;
    if (cosValue < -1):
        cosValue = -1;
    angle = math.acos(cosValue);
    return angle * 360 / (2 * math.pi);


def fit_SingleGauss(xX, yX, contmX, iHa0):
    background = LinearModel(prefix='line_')
    pars = background.make_params(intercept=yX.max(), slope=0)
    pars = background.guess(yX, x=xX)

    gauss = GaussianModel(prefix='g_')
    pars.update(gauss.make_params())
    pars['g_center'].set(iHa0, min=iHa0 - 3, max=iHa0 + 3)
    pars['g_amplitude'].set(50, min=0)
    pars['g_sigma'].set(12, min=0.0001)

    mod = gauss + background
    init = mod.eval(pars, x=xX)
    outX = mod.fit(yX, pars, x=xX)
    compsX = outX.eval_components(x=xX)
    # print(outX.fit_report(min_correl=0.25))
    # print outX.params['g_center']
    outX.fit_report(min_correl=0.25)
    # print(outX.fit_report(min_correl=0.25))
    line_slopeX = float(outX.fit_report(min_correl=0.25).split('line_slope:')[1].split('+/-')[0]) * contmX
    err_line_slopeX = float(
        outX.fit_report(min_correl=0.25).split('line_slope:')[1].split('+/-')[1].split('(')[0]) * contmX

    line_interceptX = float(outX.fit_report(min_correl=0.25).split('line_intercept:')[1].split('+/-')[0]) * contmX
    err_line_interceptX = float(
        outX.fit_report(min_correl=0.25).split('line_intercept:')[1].split('+/-')[1].split('(')[0]) * contmX

    sigmaX = float(outX.fit_report(min_correl=0.25).split('g_sigma:')[1].split('+/-')[0])
    err_sigmaX = float(outX.fit_report(min_correl=0.25).split('g_sigma:')[1].split('+/-')[1].split('(')[0])

    fwhmX = float(outX.fit_report(min_correl=0.25).split('g_fwhm:')[1].split('+/-')[0])
    err_fwhmX = float(outX.fit_report(min_correl=0.25).split('g_fwhm:')[1].split('+/-')[1].split('(')[0])

    centerX = float(outX.fit_report(min_correl=0.25).split('g_center:')[1].split('+/-')[0])
    err_centerX = float(outX.fit_report(min_correl=0.25).split('g_center:')[1].split('+/-')[1].split('(')[0])

    return sigmaX, err_sigmaX, fwhmX, err_fwhmX, centerX, err_centerX

def produceObj(x,y,chip, ra, dec, pa):
94
    pos_img = galsim.PositionD(x, y)
95
96
97
98
99
100
101
102
103
104
105

    param = {}
    param["star"] = 1
    param["id"] = 1
    param["z"] = 0
    param["sed_type"] = 1
    param["model_tag"] = 1
    param["mag_use_normal"] = 10

    obj = Star(param)

106
    header_wcs = generateExtensionHeader(chip,
107
108
109
110
111
112
113
114
115
116
117
        xlen=chip.npix_x,
        ylen=chip.npix_y,
        ra=ra,
        dec=dec,
        pa=pa,
        gain=chip.gain,
        readout=chip.read_noise,
        dark=chip.dark_noise,
        saturation=90000,
        row_num=chip.rowID,
        col_num=chip.colID,
118
119
120
121
122
123
124
125
126
127
128
129
130
        pixel_scale=chip.pix_scale,
        pixel_size=chip.pix_size,
        xcen=chip.x_cen,
        ycen=chip.y_cen,
        extName='SCI')

    chip_wcs = galsim.FitsWCS(header=header_wcs)
    param["ra"] = chip_wcs.posToWorld(pos_img).ra.deg
    param["dec"] = chip_wcs.posToWorld(pos_img).dec.deg
    # pos_img, offset, local_wcs, _, _ = obj.getPosImg_Offset_WCS(img=chip.img, chip=chip, img_header=header_wcs)
    pos_img, offset, local_wcs, real_wcs, fd_shear = obj.getPosImg_Offset_WCS(img=chip.img,
                                                                              chip=chip, verbose=False,
                                                                              chip_wcs=chip_wcs, img_header=header_wcs)
131
132
133
134
135
136
137
138
139
140
141
142
143
144
    wave = np.arange(2500, 11000.5, 0.5)
    # sedLen = wave.shape[0]
    flux = pow(wave, -2) * 1e8
    flux[200] = flux[200] * 10
    flux[800] = flux[800] * 30
    flux[2000] = flux[2000] * 5

    obj.sed = Table(np.array([wave, flux]).T,
                    names=('WAVELENGTH', 'FLUX'))
    return obj, pos_img


class TestSpecDisperse(unittest.TestCase):

145
    def __init__(self, methodName='runTest'):
146
        super(TestSpecDisperse,self).__init__(methodName)
147

Zhang Xin's avatar
Zhang Xin committed
148
149
        self.filePath('csst_fz_gc0')
        
150
151
        # self.conff = conff
        # self.throughputf = throughputf
152

Zhang Xin's avatar
Zhang Xin committed
153
154
155
156
157
158
    def filePath(self, file_name):
        fn = os.path.join(os.getenv('UNIT_TEST_DATA_ROOT'), file_name)
        self.conff= os.path.join(fn, 'CSST_GI2.conf')
        self.throughputf= os.path.join(fn, 'GI.Throughput.1st.fits')
        self.testDir = fn

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
    def test_rotate901(self):
        m = np.array([[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]])
        m1 = np.array([[21,16,11,6,1],[22,17,12,7,2],[23,18,13,8,3],[24,19,14,9,4],[25,20,15,10,5]])
        m2 = np.array([[5,10,15,20,25],[4,9,14,19,24],[3,8,13,18,23],[2,7,12,17,22],[1,6,11,16,21]])
        xc = 2
        yc = 2
        isClockwise = 0
        m1, xc1, yc1 = rotate90(array_orig=m, xc=xc, yc=yc, isClockwise=isClockwise)
        self.assertTrue(xc1-xc == 0)
        self.assertTrue(yc1-yc == 0)
        self.assertTrue(np.sum(m-m1) == 0)

    def test_rotate902(self):
        m = np.array([[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]])
        m1 = np.array([[21,16,11,6,1],[22,17,12,7,2],[23,18,13,8,3],[24,19,14,9,4],[25,20,15,10,5]])
        m2 = np.array([[5,10,15,20,25],[4,9,14,19,24],[3,8,13,18,23],[2,7,12,17,22],[1,6,11,16,21]])
        xc = 2
        yc = 2
        isClockwise =1
        m1, xc1, yc1 = rotate90(array_orig=m, xc=xc, yc=yc, isClockwise=isClockwise)
        self.assertTrue(xc1-xc == 0)
        self.assertTrue(yc1-yc == 0)
        self.assertTrue(np.sum(m-m2) == 0)


    def test_Specdistperse1(self):
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
        star = galsim.Gaussian(fwhm=0.39)
        g_img = galsim.Image(100, 100, scale=0.074)
        starImg = star.drawImage(image=g_img)

        wave = np.arange(6200, 10000.5, 0.5)
        # sedLen = wave.shape[0]
        flux = pow(wave, -2) * 1e8
        # flux[200] = flux[200] * 10
        # flux[800] = flux[800] * 30
        # flux[2000] = flux[2000] * 5

        sed = Table(np.array([wave, flux]).T,
                    names=('WAVELENGTH', 'FLUX'))
        conff = self.conff
        throughput_f = self.throughputf
        thp = Table.read(throughput_f)
        thp_i = interpolate.interp1d(thp['WAVELENGTH'], thp['SENSITIVITY'])
        sdp = SpecDisperser(orig_img=starImg, xcenter=0, ycenter=0, origin=[100, 100], tar_spec=sed, band_start=6200,
                            band_end=10000, isAlongY=0, conf=conff, gid=0)
        spec = sdp.compute_spec_orders()
        Aimg = spec['A'][0]
        wave_pix = spec['A'][5]
        wave_pos = spec['A'][3]
        sens = spec['A'][6]
        sh = Aimg.shape
        spec_pix = np.zeros(sh[1])
        for i in range(sh[1]):
            spec_pix[i] = sum(Aimg[:, i])
        # figure()
        # imshow(Aimg)

        wave_flux = np.zeros(wave_pix.shape[0])
        for i in np.arange(1, wave_pix.shape[0] - 1):
            w = wave_pix[i]
            thp_w = thp_i(w)
            deltW = (w - wave_pix[i - 1]) / 2 + (wave_pix[i + 1] - w) / 2
            f = spec_pix[wave_pos[0] - 1 + i]

            if 6200 <= w <= 10000:
                f = f / thp_w
            else:
                f = 0
            wave_flux[i] = f / deltW
        sed_i = interpolate.interp1d(sed['WAVELENGTH'], sed['FLUX'])
        ids = wave_pix < 9700
        ids1 = wave_pix[ids] > 6500
        print('Spec disperse flux test')
        self.assertTrue(np.mean((wave_flux[ids][ids1] - sed_i(wave_pix[ids][ids1]))/sed_i(wave_pix[ids][ids1]))<0.004)
        plt.figure()
        plt.plot(wave_pix, wave_flux)
        plt.plot(sed['WAVELENGTH'], sed['FLUX'])
        plt.xlim(6200, 10000)
        plt.ylim(1, 3)
        plt.yscale('log')
        plt.xlabel('$\lambda$')
        plt.ylabel('$F\lambda$')
        plt.legend(['extracted', 'input'])
        plt.show()

    def test_Specdistperse2(self):

        psf_fwhm = 0.39
        pix_scale = 0.074
        star = galsim.Gaussian(fwhm=psf_fwhm)
        g_img = galsim.Image(100, 100, scale=pix_scale)
        starImg = star.drawImage(image=g_img)

        wave = np.arange(6200, 10000.5, 0.5)
        # sedLen = wave.shape[0]
        flux = pow(wave, -2) * 1e8
        flux[200] = flux[200] * 10
        flux[800] = flux[800] * 30
        flux[2000] = flux[2000] * 5

        sed = Table(np.array([wave, flux]).T,
                    names=('WAVELENGTH', 'FLUX'))
        conff = self.conff
        throughput_f = self.throughputf
        thp = Table.read(throughput_f)
        thp_i = interpolate.interp1d(thp['WAVELENGTH'], thp['SENSITIVITY'])
        sdp = SpecDisperser(orig_img=starImg, xcenter=0, ycenter=0, origin=[100, 100], tar_spec=sed, band_start=6200,
                            band_end=10000, isAlongY=0, conf=conff, gid=0)
        spec = sdp.compute_spec_orders()
        Aimg = spec['A'][0]
        wave_pix = spec['A'][5]
        wave_pos = spec['A'][3]
        sens = spec['A'][6]
        sh = Aimg.shape
        spec_pix = np.zeros(sh[1])
        for i in range(sh[1]):
            spec_pix[i] = sum(Aimg[:, i])
        # figure()
        # imshow(Aimg)

        wave_flux = np.zeros(wave_pix.shape[0])
        for i in np.arange(1, wave_pix.shape[0] - 1):
            w = wave_pix[i]
            thp_w = thp_i(w)
            deltW = (w - wave_pix[i - 1]) / 2 + (wave_pix[i + 1] - w) / 2
            f = spec_pix[wave_pos[0] - 1 + i]

            if 6200 <= w <= 10000:
                f = f / thp_w
            else:
                f = 0
            wave_flux[i] = f / deltW
        sed_i = interpolate.interp1d(sed['WAVELENGTH'], sed['FLUX'])
        input_em_lam = 6600
        ids = wave_pix < input_em_lam+200
        ids1 = wave_pix[ids] > input_em_lam-200
        deltLamda_pix = (max(wave_pix[ids][ids1]) - min(wave_pix[ids][ids1])) / (wave_pix[ids][ids1].shape[0] - 1)
        _, _, fwhmx, fwhmx_err, center, center_err = fit_SingleGauss(wave_pix[ids][ids1], wave_flux[ids][ids1], 1.0, 6600)

        print('Emission line position and shape test')

        self.assertTrue(input_em_lam-center < deltLamda_pix)
302
303
        # print(fwhmx/deltLamda_pix*pix_scale - psf_fwhm)
        self.assertTrue(fwhmx/deltLamda_pix*pix_scale - psf_fwhm  < np.abs(0.02))
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
        # print('error is ',np.mean((wave_flux[ids][ids1] - sed_i(wave_pix[ids][ids1]))/sed_i(wave_pix[ids][ids1])))
        # self.assertTrue(np.mean((wave_flux[ids][ids1] - sed_i(wave_pix[ids][ids1]))/sed_i(wave_pix[ids][ids1]))<0.004)
        plt.figure()
        plt.plot(wave_pix, wave_flux)
        plt.plot(sed['WAVELENGTH'], sed['FLUX'])
        plt.xlim(6200, 10000)
        plt.ylim(1, 75)
        plt.yscale('log')
        plt.xlabel('$\lambda$')
        plt.ylabel('$F\lambda$')
        plt.legend(['extracted', 'input'])
        plt.show()

    def test_Specdistperse3(self):

        psf_fwhm = 0.39
        pix_scale = 0.074
        star = galsim.Gaussian(fwhm=psf_fwhm)
        g_img = galsim.Image(100, 100, scale=pix_scale)
        starImg = star.drawImage(image=g_img)

        wave = np.arange(6200, 10000.5, 0.5)
        # sedLen = wave.shape[0]
        flux = pow(wave, -2) * 1e8
        flux[200] = flux[200] * 10
        flux[800] = flux[800] * 30
        flux[2000] = flux[2000] * 5

        sed = Table(np.array([wave, flux]).T,
                    names=('WAVELENGTH', 'FLUX'))
        conff = self.conff
        throughput_f = self.throughputf
        thp = Table.read(throughput_f)
        thp_i = interpolate.interp1d(thp['WAVELENGTH'], thp['SENSITIVITY'])
        sdp = SpecDisperser(orig_img=starImg, xcenter=0, ycenter=0, origin=[100, 100], tar_spec=sed, band_start=6200,
                            band_end=8000, isAlongY=0, conf=conff, gid=0)
        sdp1 = SpecDisperser(orig_img=starImg, xcenter=0, ycenter=0, origin=[100, 100], tar_spec=sed, band_start=8000,
                             band_end=10000, isAlongY=0, conf=conff, gid=0)
        spec = sdp.compute_spec_orders()
        spec1 = sdp1.compute_spec_orders()
        Aimg = spec['A'][0] + spec1['A'][0]
        wave_pix = spec['A'][5]
        wave_pos = spec['A'][3]
        sens = spec['A'][6]
        sh = Aimg.shape
        spec_pix = np.zeros(sh[1])
        for i in range(sh[1]):
            spec_pix[i] = sum(Aimg[:, i])


        wave_flux = np.zeros(wave_pix.shape[0])
        for i in np.arange(1, wave_pix.shape[0] - 1):
            w = wave_pix[i]
            thp_w = thp_i(w)
            deltW = (w - wave_pix[i - 1]) / 2 + (wave_pix[i + 1] - w) / 2
            f = spec_pix[wave_pos[0] - 1 + i]

            if 6200 <= w <= 10000:
                f = f / thp_w
            else:
                f = 0
            wave_flux[i] = f / deltW

        sdp2 = SpecDisperser(orig_img=starImg, xcenter=0, ycenter=0, origin=[100, 100], tar_spec=sed, band_start=6200,
                             band_end=10000, isAlongY=0, conf=conff, gid=0)

        spec2 = sdp2.compute_spec_orders()
        Aimg2 = spec2['A'][0]

        spec_pix2 = np.zeros(sh[1])
        for i in range(sh[1]):
            spec_pix2[i] = sum(Aimg2[:, i])

        wave_flux2 = np.zeros(wave_pix.shape[0])
        for i in np.arange(1, wave_pix.shape[0] - 1):
            w = wave_pix[i]
            thp_w = thp_i(w)
            deltW = (w - wave_pix[i - 1]) / 2 + (wave_pix[i + 1] - w) / 2
            f = spec_pix2[wave_pos[0] - 1 + i]

            if 6200 <= w <= 10000:
                f = f / thp_w
            else:
                f = 0
            wave_flux2[i] = f / deltW

        r1_i = interpolate.interp1d(wave_pix, wave_flux2)
        r2_i = interpolate.interp1d(wave_pix, wave_flux)

        print('Spec Splicing test')
        self.assertTrue(r1_i(8000)-r2_i(8000) < np.abs(0.0001))

        # self.assertTrue(fwhmx/deltLamda_pix*pix_scale - psf_fwhm  < np.abs(0.01))
        # print('error is ',np.mean((wave_flux[ids][ids1] - sed_i(wave_pix[ids][ids1]))/sed_i(wave_pix[ids][ids1])))
        # self.assertTrue(np.mean((wave_flux[ids][ids1] - sed_i(wave_pix[ids][ids1]))/sed_i(wave_pix[ids][ids1]))<0.004)
        plt.figure()
        plt.plot(wave_pix, wave_flux2)
        plt.plot(wave_pix, wave_flux)
        # plt.plot(sed['WAVELENGTH'], sed['FLUX'])
        plt.xlim(6200, 10000)
        plt.ylim(1, 4)
        plt.yscale('log')
        plt.xlabel('$\lambda$')
        plt.ylabel('$F\lambda$')
        plt.legend(['one spec', 'split in 8000 A'])
        plt.show()



    def test_double_disperse(self):
414
        # work_dir = "/public/home/fangyuedong/CSST_unittest/CSST/test/"
415
        # data_dir = "/Volumes/Extreme SSD/SimData/"
416
        # data_dir = "/data/simudata/CSSOSDataProductsSims/data/"
417
418
        configFn = os.path.join(self.testDir, 'config_C6.yaml')
        normFilterFn =  os.path.join(self.testDir, 'SLOAN_SDSS.g.fits')
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
        norm_star = Table.read(normFilterFn)
        with open(configFn, "r") as stream:
            try:
                config = yaml.safe_load(stream)
                for key, value in config.items():
                    print(key + " : " + str(value))
            except yaml.YAMLError as exc:
                print(exc)


        filter_param = FilterParam()
        focal_plane = FocalPlane(survey_type=config["obs_setting"]["survey_type"])
        chip = Chip(1, config=config)
        filter_id, filter_type = chip.getChipFilter()
        filt = Filter(filter_id=filter_id, filter_type=filter_type, filter_param=filter_param,
                      ccd_bandpass=chip.effCurve)
        tel = Telescope()

        psf_model = PSFGauss(chip=chip)


        wcs_fp = focal_plane.getTanWCS(float(config["obs_setting"]["ra_center"]), float(config["obs_setting"]["dec_center"]), float(config["obs_setting"]["image_rot"]) * galsim.degrees, chip.pix_scale)
        chip.img = galsim.ImageF(chip.npix_x, chip.npix_y)
        chip.img.setOrigin(chip.bound.xmin, chip.bound.ymin)
        chip.img.wcs = wcs_fp

        obj, pos_img = produceObj(2000,4500, chip,float(config["obs_setting"]["ra_center"]), float(config["obs_setting"]["dec_center"]), float(config["obs_setting"]["image_rot"]))
446
        # print(pos_img,chip.pix_scale)
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
        obj.drawObj_slitless(
            tel=tel,
            pos_img=pos_img,
            psf_model=psf_model,
            bandpass_list=filt.bandpass_sub_list,
            filt=filt,
            chip=chip,
            g1=0,
            g2=0,
            exptime=150,
            normFilter=norm_star)

        obj, pos_img = produceObj(3685, 6500, chip,float(config["obs_setting"]["ra_center"]), float(config["obs_setting"]["dec_center"]), float(config["obs_setting"]["image_rot"]))
        obj.drawObj_slitless(
            tel=tel,
            pos_img=pos_img,
            psf_model=psf_model,
            bandpass_list=filt.bandpass_sub_list,
            filt=filt,
            chip=chip,
            g1=0,
            g2=0,
            exptime=150,
            normFilter=norm_star)

        obj, pos_img = produceObj(5000, 2500, chip, float(config["obs_setting"]["ra_center"]), float(config["obs_setting"]["dec_center"]), float(config["obs_setting"]["image_rot"]))
        obj.drawObj_slitless(
            tel=tel,
            pos_img=pos_img,
            psf_model=psf_model,
            bandpass_list=filt.bandpass_sub_list,
            filt=filt,
            chip=chip,
            g1=0,
            g2=0,
            exptime=150,
            normFilter=norm_star)

        print('Spec double disperse test')
        from astropy.io import fits
        fits.writeto('test.fits',chip.img.array, overwrite = True)

        # plt.figure()
        # plt.imshow(chip.img.array)
        # plt.show()

    def test_SLSImage_rotation(self):
        from astropy.wcs import WCS
495
        configFn = os.path.join(self.testDir,'config_C6.yaml')
496
497
498
499
500
501
502
503
504
505
506
507
508
509

        with open(configFn, "r") as stream:
            try:
                config = yaml.safe_load(stream)
                for key, value in config.items():
                    print(key + " : " + str(value))
            except yaml.YAMLError as exc:
                print(exc)
        chip = Chip(1, config=config)

        ra=float(config["obs_setting"]["ra_center"])
        dec=float(config["obs_setting"]["dec_center"])
        pa=float(config["obs_setting"]["image_rot"])

510
511
        chip.rotate_angle = 0
        header_wcs1 = generateExtensionHeader(chip,
512
513
514
515
516
517
518
519
520
            xlen=chip.npix_x,
            ylen=chip.npix_y,
            ra=ra,
            dec=dec,
            pa=pa,
            gain=chip.gain,
            readout=chip.read_noise,
            dark=chip.dark_noise,
            saturation=90000,
521
            pixel_scale=chip.pix_scale,
522
523
            row_num=chip.rowID,
            col_num=chip.colID,
524
            extName='raw')
525
526
527
528
529

        center = np.array([chip.npix_x / 2, chip.npix_y / 2])
        h_wcs1 = WCS(header_wcs1)
        x1, y1 = center + [100,0]
        sky_1 = h_wcs1.pixel_to_world(x1,y1)
530
        chip = Chip(1, config=config)
531
        rot_angle = 1
532
533
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
534
535
536
537
538
539
540
541
542
            xlen=chip.npix_x,
            ylen=chip.npix_y,
            ra=ra,
            dec=dec,
            pa=pa,
            gain=chip.gain,
            readout=chip.read_noise,
            dark=chip.dark_noise,
            saturation=90000,
543
            pixel_scale=chip.pix_scale,
544
545
            row_num=chip.rowID,
            col_num=chip.colID,
546
            extName='raw')
547
548
549
550

        h_wcs2 = WCS(header_wcs2)
        x2, y2 = h_wcs2.world_to_pixel(sky_1)
        angle = getAngle132(x1,y1,0,x2,y2,0,center[0],center[1],0)
551
552
553

        # print("rotation angle:" ,rot_angle ,chip.rotate_angle, angle)
        # self.assertTrue(rot_angle - angle < np.abs(0.001))
554
555

        rot_angle = 10
556
557
        chip.rotate_angle =  rot_angle
        header_wcs2 = generateExtensionHeader(chip,
558
559
560
561
562
563
564
565
566
            xlen=chip.npix_x,
            ylen=chip.npix_y,
            ra=ra,
            dec=dec,
            pa=pa,
            gain=chip.gain,
            readout=chip.read_noise,
            dark=chip.dark_noise,
            saturation=90000,
567
            pixel_scale=chip.pix_scale,
568
569
            row_num=chip.rowID,
            col_num=chip.colID,
570
            extName='raw')
571
572
573
574

        h_wcs2 = WCS(header_wcs2)
        x2, y2 = h_wcs2.world_to_pixel(sky_1)
        angle = getAngle132(x1, y1, 0, x2, y2, 0, center[0], center[1], 0)
575
        # print("rotation angle:", rot_angle, chip.rotate_angle, angle)
576
577
578
        self.assertTrue(rot_angle - angle < np.abs(0.001))

        rot_angle = 50
579
580
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
581
582
583
584
585
586
587
588
589
            xlen=chip.npix_x,
            ylen=chip.npix_y,
            ra=ra,
            dec=dec,
            pa=pa,
            gain=chip.gain,
            readout=chip.read_noise,
            dark=chip.dark_noise,
            saturation=90000,
590
            pixel_scale=chip.pix_scale,
591
592
            row_num=chip.rowID,
            col_num=chip.colID,
593
            extName='raw')
594
595
596
597

        h_wcs2 = WCS(header_wcs2)
        x2, y2 = h_wcs2.world_to_pixel(sky_1)
        angle = getAngle132(x1, y1, 0, x2, y2, 0, center[0], center[1], 0)
598
        # print(rot_angle - angle)
599
600
601
602
603
604
605
606
        self.assertTrue(rot_angle - angle < np.abs(0.001))


        chip = Chip(27, config=config)

        ra = float(config["obs_setting"]["ra_center"])
        dec = float(config["obs_setting"]["dec_center"])
        pa = float(config["obs_setting"]["image_rot"])
607
608
        chip.rotate_angle = 0
        header_wcs1 = generateExtensionHeader(chip,
609
610
611
612
613
614
615
616
617
            xlen=chip.npix_x,
            ylen=chip.npix_y,
            ra=ra,
            dec=dec,
            pa=pa,
            gain=chip.gain,
            readout=chip.read_noise,
            dark=chip.dark_noise,
            saturation=90000,
618
            pixel_scale=chip.pix_scale,
619
620
            row_num=chip.rowID,
            col_num=chip.colID,
621
            extName='raw')
622
623
624
625
626
627
628

        center = np.array([chip.npix_x / 2, chip.npix_y / 2])
        h_wcs1 = WCS(header_wcs1)
        x1, y1 = center + [100, 0]
        sky_1 = h_wcs1.pixel_to_world(x1, y1)

        rot_angle = 1
629
630
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
631
632
633
634
635
636
637
638
639
            xlen=chip.npix_x,
            ylen=chip.npix_y,
            ra=ra,
            dec=dec,
            pa=pa,
            gain=chip.gain,
            readout=chip.read_noise,
            dark=chip.dark_noise,
            saturation=90000,
640
            pixel_scale=chip.pix_scale,
641
642
            row_num=chip.rowID,
            col_num=chip.colID,
643
            extName='raw')
644
645
646
647

        h_wcs2 = WCS(header_wcs2)
        x2, y2 = h_wcs2.world_to_pixel(sky_1)
        angle = getAngle132(x1, y1, 0, x2, y2, 0, center[0], center[1], 0)
648
        # print(rot_angle - angle)
649
650
651
        self.assertTrue(rot_angle - angle < np.abs(0.001))

        rot_angle = 10
652
653
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
654
655
656
657
658
659
660
661
662
            xlen=chip.npix_x,
            ylen=chip.npix_y,
            ra=ra,
            dec=dec,
            pa=pa,
            gain=chip.gain,
            readout=chip.read_noise,
            dark=chip.dark_noise,
            saturation=90000,
663
            pixel_scale=chip.pix_scale,
664
665
            row_num=chip.rowID,
            col_num=chip.colID,
666
            extName='raw')
667
668
669
670

        h_wcs2 = WCS(header_wcs2)
        x2, y2 = h_wcs2.world_to_pixel(sky_1)
        angle = getAngle132(x1, y1, 0, x2, y2, 0, center[0], center[1], 0)
671
        # print(rot_angle - angle)
672
673
674
        self.assertTrue(rot_angle - angle < np.abs(0.001))

        rot_angle = 50
675
676
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
677
678
679
680
681
682
683
684
685
            xlen=chip.npix_x,
            ylen=chip.npix_y,
            ra=ra,
            dec=dec,
            pa=pa,
            gain=chip.gain,
            readout=chip.read_noise,
            dark=chip.dark_noise,
            saturation=90000,
686
            pixel_scale=chip.pix_scale,
687
688
            row_num=chip.rowID,
            col_num=chip.colID,
689
            extName='raw')
690
691
692
693

        h_wcs2 = WCS(header_wcs2)
        x2, y2 = h_wcs2.world_to_pixel(sky_1)
        angle = getAngle132(x1, y1, 0, x2, y2, 0, center[0], center[1], 0)
694
        # print(rot_angle - angle)
695
696
697
698
699
700
701
        self.assertTrue(rot_angle - angle < np.abs(0.001))




if __name__ == '__main__':

702
703
    os.environ['UNIT_TEST_DATA_ROOT']="/Users/zhangxin/Work/SlitlessSim/CSST_SIM/CSST_develop/csst-simulation/tests/testData"
    testDir = os.getenv('UNIT_TEST_DATA_ROOT')
704
705
    # conff= os.path.join(testDir, 'CSST_GI2.conf')
    # throughputf= os.path.join(testDir, 'GI.Throughput.1st.fits')
706
    suit = unittest.TestSuite()
707
    case1 = TestSpecDisperse('test_Specdistperse1')
708
    suit.addTest(case1)
709
    case2 = TestSpecDisperse('test_Specdistperse2')
710
    suit.addTest(case2)
711
    case3 = TestSpecDisperse('test_Specdistperse3')
712
    suit.addTest(case3)
713
    case4 = TestSpecDisperse('test_double_disperse')
714
715
716
717
718
719
720
    suit.addTest(case4)
    case5 = TestSpecDisperse('test_SLSImage_rotation')
    suit.addTest(case5)

    unittest.TextTestRunner(verbosity=2).run(suit)
    # runner = unittest.TextTestRunner()
    # runner.run(suit)