test_SpecDisperse.py 25.3 KB
Newer Older
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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
21
import os
22
23
24
25
26
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


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):
89
    pos_img = galsim.PositionD(x, y)
90
91
92
93
94
95
96
97
98
99
100

    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)

101
    header_wcs = generateExtensionHeader(chip,
102
103
104
105
106
107
108
109
110
111
112
        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,
113
114
115
116
117
118
119
120
121
122
123
124
125
        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)
126
127
128
129
130
131
132
133
134
135
136
137
138
139
    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):

140
    def __init__(self, methodName='runTest'):
141
        super(TestSpecDisperse,self).__init__(methodName)
142
143
144
145
146
147
148

        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
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175

    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):
176

177
178
179
180
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
        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)
293
294
        # print(fwhmx/deltLamda_pix*pix_scale - psf_fwhm)
        self.assertTrue(fwhmx/deltLamda_pix*pix_scale - psf_fwhm  < np.abs(0.02))
295
296
297
298
299
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
        # 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):
405
        # work_dir = "/public/home/fangyuedong/CSST_unittest/CSST/test/"
406
        # data_dir = "/Volumes/Extreme SSD/SimData/"
407
        # data_dir = "/data/simudata/CSSOSDataProductsSims/data/"
408
409
        configFn = os.path.join(self.testDir, 'config_C6.yaml')
        normFilterFn =  os.path.join(self.testDir, 'SLOAN_SDSS.g.fits')
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
        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"]))
439
        # print(pos_img,chip.pix_scale)
440
441
442
443
444
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
        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
488
        configFn = os.path.join(self.testDir,'config_C6.yaml')
489
490
491
492
493
494
495
496
497
498
499
500
501
502

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

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

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

        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)
544
545
546

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

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

        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)
568
        # print("rotation angle:", rot_angle, chip.rotate_angle, angle)
569
570
571
        self.assertTrue(rot_angle - angle < np.abs(0.001))

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

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

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

        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)
641
        # print(rot_angle - angle)
642
643
644
        self.assertTrue(rot_angle - angle < np.abs(0.001))

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

        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)
664
        # print(rot_angle - angle)
665
666
667
        self.assertTrue(rot_angle - angle < np.abs(0.001))

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

        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)
687
        # print(rot_angle - angle)
688
689
690
691
692
693
694
        self.assertTrue(rot_angle - angle < np.abs(0.001))




if __name__ == '__main__':

695
696
697
698
    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')
699
    suit = unittest.TestSuite()
700
    case1 = TestSpecDisperse('test_Specdistperse1')
701
    suit.addTest(case1)
702
    case2 = TestSpecDisperse('test_Specdistperse2')
703
    suit.addTest(case2)
704
    case3 = TestSpecDisperse('test_Specdistperse3')
705
    suit.addTest(case3)
706
    case4 = TestSpecDisperse('test_double_disperse')
707
708
709
710
711
712
713
    suit.addTest(case4)
    case5 = TestSpecDisperse('test_SLSImage_rotation')
    suit.addTest(case5)

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