test_SpecDisperse.py 30.3 KB
Newer Older
Zhang Xin's avatar
Zhang Xin committed
1
#
Fang Yuedong's avatar
Fang Yuedong committed
2
3
4
# need add environment parameter  UNIT_TEST_DATA_ROOT, link to "testData/"
# linx and mac can run as follow, need modify the name of file directory
# 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
import unittest
Fang Yuedong's avatar
Fang Yuedong committed
7
from observation_sim.mock_objects.SpecDisperser import rotate90, SpecDisperser
8

Fang Yuedong's avatar
Fang Yuedong committed
9
10
11
from observation_sim.config import ChipOutput
from observation_sim.instruments import Telescope, Chip, FilterParam, Filter, FocalPlane
from observation_sim.mock_objects import MockObject, Star
Fang Yuedong's avatar
Fang Yuedong committed
12
from observation_sim.psf import PSFGauss
13
14
15
16
17
18
19
20
21
22

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

Fang Yuedong's avatar
Fang Yuedong committed
23
from observation_sim.config.header import generateExtensionHeader
24
25
import math
import yaml
26
import os
27
28
29


def getAngle132(x1=0, y1=0, z1=0, x2=0, y2=0, z2=0, x3=0, y3=0, z3=0):
Fang Yuedong's avatar
Fang Yuedong committed
30
31
    cosValue = 0
    angle = 0
32

Fang Yuedong's avatar
Fang Yuedong committed
33
34
35
    x11 = x1 - x3
    y11 = y1 - y3
    z11 = z1 - z3
36

Fang Yuedong's avatar
Fang Yuedong committed
37
38
39
    x22 = x2 - x3
    y22 = y2 - y3
    z22 = z2 - z3
40

Fang Yuedong's avatar
Fang Yuedong committed
41
42
    tt = np.sqrt((x11 * x11 + y11 * y11 + z11 * z11)
                 * (x22 * x22 + y22 * y22 + z22 * z22))
43
    if (tt == 0):
Fang Yuedong's avatar
Fang Yuedong committed
44
        return 0
45

Fang Yuedong's avatar
Fang Yuedong committed
46
    cosValue = (x11 * x22 + y11 * y22 + z11 * z22) / tt
47
48

    if (cosValue > 1):
Fang Yuedong's avatar
Fang Yuedong committed
49
        cosValue = 1
50
    if (cosValue < -1):
Fang Yuedong's avatar
Fang Yuedong committed
51
52
53
        cosValue = -1
    angle = math.acos(cosValue)
    return angle * 360 / (2 * math.pi)
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74


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))
Fang Yuedong's avatar
Fang Yuedong committed
75
76
    line_slopeX = float(outX.fit_report(min_correl=0.25).split(
        'line_slope:')[1].split('+/-')[0]) * contmX
77
78
79
    err_line_slopeX = float(
        outX.fit_report(min_correl=0.25).split('line_slope:')[1].split('+/-')[1].split('(')[0]) * contmX

Fang Yuedong's avatar
Fang Yuedong committed
80
81
    line_interceptX = float(outX.fit_report(min_correl=0.25).split(
        'line_intercept:')[1].split('+/-')[0]) * contmX
82
83
84
    err_line_interceptX = float(
        outX.fit_report(min_correl=0.25).split('line_intercept:')[1].split('+/-')[1].split('(')[0]) * contmX

Fang Yuedong's avatar
Fang Yuedong committed
85
86
87
88
    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])
89

Fang Yuedong's avatar
Fang Yuedong committed
90
91
92
93
    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])
94

Fang Yuedong's avatar
Fang Yuedong committed
95
96
97
98
    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])
99
100
101

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

Fang Yuedong's avatar
Fang Yuedong committed
102
103

def produceObj(x, y, chip, ra, dec, pa):
104
    pos_img = galsim.PositionD(x, y)
105
106
107
108
109
110
111
112
113
114
115

    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)

116
    header_wcs = generateExtensionHeader(chip,
Fang Yuedong's avatar
Fang Yuedong committed
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
                                         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,
                                         pixel_scale=chip.pix_scale,
                                         pixel_size=chip.pix_size,
                                         xcen=chip.x_cen,
                                         ycen=chip.y_cen,
                                         extName='SCI')
133
134
135
136
137
138
139
140

    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)
141
142
143
144
145
146
147
148
149
150
151
152
153
154
    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):

155
    def __init__(self, methodName='runTest'):
Fang Yuedong's avatar
Fang Yuedong committed
156
        super(TestSpecDisperse, self).__init__(methodName)
157

Zhang Xin's avatar
Zhang Xin committed
158
        self.filePath('csst_msc_sim/test_sls_and_straylight')
Fang Yuedong's avatar
Fang Yuedong committed
159

160
161
        # self.conff = conff
        # self.throughputf = throughputf
162

Zhang Xin's avatar
Zhang Xin committed
163
164
    def filePath(self, file_name):
        fn = os.path.join(os.getenv('UNIT_TEST_DATA_ROOT'), file_name)
Fang Yuedong's avatar
Fang Yuedong committed
165
166
        self.conff = os.path.join(fn, 'CSST_GI2.conf')
        self.throughputf = os.path.join(fn, 'GI.Throughput.1st.fits')
Zhang Xin's avatar
Zhang Xin committed
167
        self.testDir = fn
Fang Yuedong's avatar
Fang Yuedong committed
168
        self.outDataFn = os.path.join(fn, 'output')
Zhang Xin's avatar
Zhang Xin committed
169
170
171
172
        if os.path.isdir(self.outDataFn):
            pass
        else:
            os.mkdir(self.outDataFn)
Zhang Xin's avatar
Zhang Xin committed
173

174
    def test_rotate901(self):
Fang Yuedong's avatar
Fang Yuedong committed
175
176
177
178
179
180
        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]])
181
182
183
        xc = 2
        yc = 2
        isClockwise = 0
Fang Yuedong's avatar
Fang Yuedong committed
184
185
        m1, xc1, yc1 = rotate90(array_orig=m, xc=xc,
                                yc=yc, isClockwise=isClockwise)
186
187
188
189
190
        self.assertTrue(xc1-xc == 0)
        self.assertTrue(yc1-yc == 0)
        self.assertTrue(np.sum(m-m1) == 0)

    def test_rotate902(self):
Fang Yuedong's avatar
Fang Yuedong committed
191
192
193
194
195
196
        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]])
197
198
        xc = 2
        yc = 2
Fang Yuedong's avatar
Fang Yuedong committed
199
200
201
        isClockwise = 1
        m1, xc1, yc1 = rotate90(array_orig=m, xc=xc,
                                yc=yc, isClockwise=isClockwise)
202
203
204
205
206
        self.assertTrue(xc1-xc == 0)
        self.assertTrue(yc1-yc == 0)
        self.assertTrue(np.sum(m-m2) == 0)

    def test_Specdistperse1(self):
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
        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')
Fang Yuedong's avatar
Fang Yuedong committed
255
256
        self.assertTrue(np.mean(
            (wave_flux[ids][ids1] - sed_i(wave_pix[ids][ids1]))/sed_i(wave_pix[ids][ids1])) < 0.004)
Zhang Xin's avatar
Zhang Xin committed
257
258
259
260
261
262
263
264
265
266
        # 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()
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
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318

    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
Fang Yuedong's avatar
Fang Yuedong committed
319
320
321
322
        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)
323
324
325
326

        print('Emission line position and shape test')

        self.assertTrue(input_em_lam-center < deltLamda_pix)
327
        # print(fwhmx/deltLamda_pix*pix_scale - psf_fwhm)
Fang Yuedong's avatar
Fang Yuedong committed
328
329
        self.assertTrue(fwhmx/deltLamda_pix*pix_scale -
                        psf_fwhm < np.abs(0.02))
330
331
        # 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)
Zhang Xin's avatar
Zhang Xin committed
332
333
334
335
336
337
338
339
340
341
        # 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()
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
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436

    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):
437
        # work_dir = "/public/home/fangyuedong/CSST_unittest/CSST/test/"
438
        # data_dir = "/Volumes/Extreme SSD/SimData/"
439
        # data_dir = "/data/simudata/CSSOSDataProductsSims/data/"
440
        configFn = os.path.join(self.testDir, 'config_C6.yaml')
Fang Yuedong's avatar
Fang Yuedong committed
441
        normFilterFn = os.path.join(self.testDir, 'SLOAN_SDSS.g.fits')
442
443
444
445
446
447
448
449
450
451
        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()
Fang Yuedong's avatar
Fang Yuedong committed
452
453
        focal_plane = FocalPlane(
            survey_type=config["obs_setting"]["survey_type"])
454
455
456
457
458
459
460
461
        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)

Fang Yuedong's avatar
Fang Yuedong committed
462
463
        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)
464
465
466
467
        chip.img = galsim.ImageF(chip.npix_x, chip.npix_y)
        chip.img.setOrigin(chip.bound.xmin, chip.bound.ymin)
        chip.img.wcs = wcs_fp

Fang Yuedong's avatar
Fang Yuedong committed
468
469
        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"]))
470
        # print(pos_img,chip.pix_scale)
471
472
473
474
475
476
477
478
479
480
481
482
        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)

Fang Yuedong's avatar
Fang Yuedong committed
483
484
        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"]))
485
486
487
488
489
490
491
492
493
494
495
496
        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)

Fang Yuedong's avatar
Fang Yuedong committed
497
498
        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"]))
499
500
501
502
503
504
505
506
507
508
509
510
511
512
        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
Fang Yuedong's avatar
Fang Yuedong committed
513
514
        fits.writeto(os.path.join(
            self.outDataFn, 'test_sls_doubleDisp.fits'), chip.img.array, overwrite=True)
515
516
517
518
519
520
521

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

    def test_SLSImage_rotation(self):
        from astropy.wcs import WCS
Fang Yuedong's avatar
Fang Yuedong committed
522
        configFn = os.path.join(self.testDir, 'config_C6.yaml')
523
524
525
526
527
528
529
530
531
532

        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)

Fang Yuedong's avatar
Fang Yuedong committed
533
534
535
        ra = float(config["obs_setting"]["ra_center"])
        dec = float(config["obs_setting"]["dec_center"])
        pa = float(config["obs_setting"]["image_rot"])
536

537
538
        chip.rotate_angle = 0
        header_wcs1 = generateExtensionHeader(chip,
Fang Yuedong's avatar
Fang Yuedong committed
539
540
541
542
543
544
545
546
547
548
549
550
551
                                              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,
                                              pixel_scale=chip.pix_scale,
                                              row_num=chip.rowID,
                                              col_num=chip.colID,
                                              extName='raw')
552
553
554

        center = np.array([chip.npix_x / 2, chip.npix_y / 2])
        h_wcs1 = WCS(header_wcs1)
Fang Yuedong's avatar
Fang Yuedong committed
555
556
        x1, y1 = center + [100, 0]
        sky_1 = h_wcs1.pixel_to_world(x1, y1)
557
        chip = Chip(1, config=config)
558
        rot_angle = 1
559
560
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
Fang Yuedong's avatar
Fang Yuedong committed
561
562
563
564
565
566
567
568
569
570
571
572
573
                                              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,
                                              pixel_scale=chip.pix_scale,
                                              row_num=chip.rowID,
                                              col_num=chip.colID,
                                              extName='raw')
574
575
576

        h_wcs2 = WCS(header_wcs2)
        x2, y2 = h_wcs2.world_to_pixel(sky_1)
Fang Yuedong's avatar
Fang Yuedong committed
577
        angle = getAngle132(x1, y1, 0, x2, y2, 0, center[0], center[1], 0)
578
579
580

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

        rot_angle = 10
Fang Yuedong's avatar
Fang Yuedong committed
583
        chip.rotate_angle = rot_angle
584
        header_wcs2 = generateExtensionHeader(chip,
Fang Yuedong's avatar
Fang Yuedong committed
585
586
587
588
589
590
591
592
593
594
595
596
597
                                              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,
                                              pixel_scale=chip.pix_scale,
                                              row_num=chip.rowID,
                                              col_num=chip.colID,
                                              extName='raw')
598
599
600
601

        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)
602
        # print("rotation angle:", rot_angle, chip.rotate_angle, angle)
603
604
605
        self.assertTrue(rot_angle - angle < np.abs(0.001))

        rot_angle = 50
606
607
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
Fang Yuedong's avatar
Fang Yuedong committed
608
609
610
611
612
613
614
615
616
617
618
619
620
                                              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,
                                              pixel_scale=chip.pix_scale,
                                              row_num=chip.rowID,
                                              col_num=chip.colID,
                                              extName='raw')
621
622
623
624

        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)
625
        # print(rot_angle - angle)
626
627
628
629
630
631
632
        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"])
633
634
        chip.rotate_angle = 0
        header_wcs1 = generateExtensionHeader(chip,
Fang Yuedong's avatar
Fang Yuedong committed
635
636
637
638
639
640
641
642
643
644
645
646
647
                                              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,
                                              pixel_scale=chip.pix_scale,
                                              row_num=chip.rowID,
                                              col_num=chip.colID,
                                              extName='raw')
648
649
650
651
652
653
654

        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
655
656
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
Fang Yuedong's avatar
Fang Yuedong committed
657
658
659
660
661
662
663
664
665
666
667
668
669
                                              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,
                                              pixel_scale=chip.pix_scale,
                                              row_num=chip.rowID,
                                              col_num=chip.colID,
                                              extName='raw')
670
671
672
673

        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)
674
        # print(rot_angle - angle)
675
676
677
        self.assertTrue(rot_angle - angle < np.abs(0.001))

        rot_angle = 10
678
679
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
Fang Yuedong's avatar
Fang Yuedong committed
680
681
682
683
684
685
686
687
688
689
690
691
692
                                              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,
                                              pixel_scale=chip.pix_scale,
                                              row_num=chip.rowID,
                                              col_num=chip.colID,
                                              extName='raw')
693
694
695
696

        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)
697
        # print(rot_angle - angle)
698
699
700
        self.assertTrue(rot_angle - angle < np.abs(0.001))

        rot_angle = 50
701
702
        chip.rotate_angle = rot_angle
        header_wcs2 = generateExtensionHeader(chip,
Fang Yuedong's avatar
Fang Yuedong committed
703
704
705
706
707
708
709
710
711
712
713
714
715
                                              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,
                                              pixel_scale=chip.pix_scale,
                                              row_num=chip.rowID,
                                              col_num=chip.colID,
                                              extName='raw')
716
717
718
719

        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)
720
        # print(rot_angle - angle)
721
722
723
724
725
        self.assertTrue(rot_angle - angle < np.abs(0.001))


if __name__ == '__main__':

Fang Yuedong's avatar
Fang Yuedong committed
726
    os.environ['UNIT_TEST_DATA_ROOT'] = "/Users/zhangxin/Work/SlitlessSim/CSST_SIM/CSST_develop/csst-simulation/tests/testData"
727
    testDir = os.getenv('UNIT_TEST_DATA_ROOT')
728
729
    # conff= os.path.join(testDir, 'CSST_GI2.conf')
    # throughputf= os.path.join(testDir, 'GI.Throughput.1st.fits')
730
    suit = unittest.TestSuite()
731
    case1 = TestSpecDisperse('test_Specdistperse1')
732
    suit.addTest(case1)
733
    case2 = TestSpecDisperse('test_Specdistperse2')
734
    suit.addTest(case2)
735
    case3 = TestSpecDisperse('test_Specdistperse3')
736
    suit.addTest(case3)
737
    case4 = TestSpecDisperse('test_double_disperse')
738
739
740
741
742
743
    suit.addTest(case4)
    case5 = TestSpecDisperse('test_SLSImage_rotation')
    suit.addTest(case5)

    unittest.TextTestRunner(verbosity=2).run(suit)
    # runner = unittest.TextTestRunner()
Fang Yuedong's avatar
Fang Yuedong committed
744
    # runner.run(suit)