test_SpecDisperse.py 25.5 KB
Newer Older
Zhang Xin's avatar
Zhang Xin committed
1
2
3
4
5
#
#need add environment parameter  TEST_HOME, link to "testData/"
#linx and mac can run as follow, need modify the name of file directory
#export TEST_HOME=/Users/zhangxin/Work/SlitlessSim/CSST_SIM/CSST_develop/csst-simulation/tests/testData
#
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
import unittest
from ObservationSim.MockObject.SpecDisperser import rotate90, SpecDisperser

from ObservationSim.Config import ChipOutput, Config
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
148
149
150
151
152
153

        self.conff= os.path.join(os.getenv('TEST_HOME'), 'CSST_GI2.conf')
        self.throughputf= os.path.join(os.getenv('TEST_HOME'), 'GI.Throughput.1st.fits')
        self.testDir = os.getenv('TEST_HOME')

        # self.conff = conff
        # self.throughputf = throughputf
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

    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):
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
        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)
298
299
        # print(fwhmx/deltLamda_pix*pix_scale - psf_fwhm)
        self.assertTrue(fwhmx/deltLamda_pix*pix_scale - psf_fwhm  < np.abs(0.02))
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
        # 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):
410
        # work_dir = "/public/home/fangyuedong/CSST_unittest/CSST/test/"
411
        # data_dir = "/Volumes/Extreme SSD/SimData/"
412
        # data_dir = "/data/simudata/CSSOSDataProductsSims/data/"
413
414
        configFn = os.path.join(self.testDir, 'config_C6.yaml')
        normFilterFn =  os.path.join(self.testDir, 'SLOAN_SDSS.g.fits')
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
        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)
        # config = Config.read_config(configFn)
        # path_dict = Config.config_dir(config,work_dir=work_dir, data_dir=data_dir)


        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"]))
444
        # print(pos_img,chip.pix_scale)
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
        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
493
        configFn = os.path.join(self.testDir,'config_C6.yaml')
494
495
496
497
498
499
500
501
502
503
504
505
506
507

        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"])

508
509
        chip.rotate_angle = 0
        header_wcs1 = generateExtensionHeader(chip,
510
511
512
513
514
515
516
517
518
            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,
519
            pixel_scale=chip.pix_scale,
520
521
            row_num=chip.rowID,
            col_num=chip.colID,
522
            extName='raw')
523
524
525
526
527

        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)
528
        chip = Chip(1, config=config)
529
        rot_angle = 1
530
531
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
532
533
534
535
536
537
538
539
540
            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,
541
            pixel_scale=chip.pix_scale,
542
543
            row_num=chip.rowID,
            col_num=chip.colID,
544
            extName='raw')
545
546
547
548

        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)
549
550
551

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

        rot_angle = 10
554
555
        chip.rotate_angle =  rot_angle
        header_wcs2 = generateExtensionHeader(chip,
556
557
558
559
560
561
562
563
564
            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,
565
            pixel_scale=chip.pix_scale,
566
567
            row_num=chip.rowID,
            col_num=chip.colID,
568
            extName='raw')
569
570
571
572

        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)
573
        # print("rotation angle:", rot_angle, chip.rotate_angle, angle)
574
575
576
        self.assertTrue(rot_angle - angle < np.abs(0.001))

        rot_angle = 50
577
578
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
579
580
581
582
583
584
585
586
587
            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,
588
            pixel_scale=chip.pix_scale,
589
590
            row_num=chip.rowID,
            col_num=chip.colID,
591
            extName='raw')
592
593
594
595

        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)
596
        # print(rot_angle - angle)
597
598
599
600
601
602
603
604
        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"])
605
606
        chip.rotate_angle = 0
        header_wcs1 = generateExtensionHeader(chip,
607
608
609
610
611
612
613
614
615
            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,
616
            pixel_scale=chip.pix_scale,
617
618
            row_num=chip.rowID,
            col_num=chip.colID,
619
            extName='raw')
620
621
622
623
624
625
626

        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
627
628
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
629
630
631
632
633
634
635
636
637
            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,
638
            pixel_scale=chip.pix_scale,
639
640
            row_num=chip.rowID,
            col_num=chip.colID,
641
            extName='raw')
642
643
644
645

        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)
646
        # print(rot_angle - angle)
647
648
649
        self.assertTrue(rot_angle - angle < np.abs(0.001))

        rot_angle = 10
650
651
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
652
653
654
655
656
657
658
659
660
            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,
661
            pixel_scale=chip.pix_scale,
662
663
            row_num=chip.rowID,
            col_num=chip.colID,
664
            extName='raw')
665
666
667
668

        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)
669
        # print(rot_angle - angle)
670
671
672
        self.assertTrue(rot_angle - angle < np.abs(0.001))

        rot_angle = 50
673
674
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
675
676
677
678
679
680
681
682
683
            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,
684
            pixel_scale=chip.pix_scale,
685
686
            row_num=chip.rowID,
            col_num=chip.colID,
687
            extName='raw')
688
689
690
691

        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)
692
        # print(rot_angle - angle)
693
694
695
696
697
698
699
        self.assertTrue(rot_angle - angle < np.abs(0.001))




if __name__ == '__main__':

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

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