add_objects.py 11.5 KB
Newer Older
1
2
3
import os
import gc
import psutil
Fang Yuedong's avatar
Fang Yuedong committed
4
import traceback
5
6
7
8
9
import numpy as np
import galsim
from ObservationSim._util import get_shear_field
from ObservationSim.PSF import PSFGauss, FieldDistortion, PSFInterp, PSFInterpSLS

10
11
12
from astropy.time import Time
from datetime import datetime, timezone

Fang Yuedong's avatar
Fang Yuedong committed
13

14
15
def add_objects(self, chip, filt, tel, pointing, catalog, obs_param):

16
17
18
19
20
21
    # Get exposure time
    if (obs_param) and ("exptime" in obs_param) and (obs_param["exptime"] is not None):
        exptime = obs_param["exptime"]
    else:
        exptime = pointing.exp_time

22
23
    # Load catalogues
    if catalog is None:
Fang Yuedong's avatar
Fang Yuedong committed
24
25
26
27
28
29
        self.chip_output.Log_error(
            "Catalog interface class must be specified for SCIE-OBS")
        raise ValueError(
            "Catalog interface class must be specified for SCIE-OBS")
    cat = catalog(config=self.overall_config, chip=chip,
                  pointing=pointing, chip_output=self.chip_output, filt=filt)
30

31
32
33
34
35
    # Prepare output file(s) for this chip
    # [NOTE] Headers of output .cat file may be updated by Catalog instance
    # this should be called after the creation of Catalog instance
    self.chip_output.create_output_file()

36
37
    # Prepare the PSF model
    if self.overall_config["psf_setting"]["psf_model"] == "Gauss":
Fang Yuedong's avatar
Fang Yuedong committed
38
39
        psf_model = PSFGauss(
            chip=chip, psfRa=self.overall_config["psf_setting"]["psf_rcont"])
40
41
    elif self.overall_config["psf_setting"]["psf_model"] == "Interp":
        if chip.survey_type == "spectroscopic":
Fang Yuedong's avatar
Fang Yuedong committed
42
43
            psf_model = PSFInterpSLS(
                chip, filt, PSF_data_prefix=self.overall_config["psf_setting"]["psf_sls_dir"])
44
        else:
Fang Yuedong's avatar
Fang Yuedong committed
45
46
            psf_model = PSFInterp(chip=chip, npsf=chip.n_psf_samples,
                                  PSF_data_file=self.overall_config["psf_setting"]["psf_pho_dir"])
47
48
    else:
        self.chip_output.Log_error("unrecognized PSF model type!!", flush=True)
Fang Yuedong's avatar
Fang Yuedong committed
49

50
51
52
53
54
55
56
57
58
59
    # Apply field distortion model
    if obs_param["field_dist"] == True:
        fd_model = FieldDistortion(chip=chip, img_rot=pointing.img_pa.deg)
    else:
        fd_model = None

    # Update limiting magnitudes for all filters based on the exposure time
    # Get the filter which will be used for magnitude cut
    for ifilt in range(len(self.all_filters)):
        temp_filter = self.all_filters[ifilt]
Fang Yuedong's avatar
Fang Yuedong committed
60
61
        temp_filter.update_limit_saturation_mags(
            exptime=pointing.get_full_depth_exptime(temp_filter.filter_type), chip=chip)
62
63
64
65
66
67
        if temp_filter.filter_type.lower() == self.overall_config["obs_setting"]["cut_in_band"].lower():
            cut_filter = temp_filter

    # Read in shear values from configuration file if the constant shear type is used
    if self.overall_config["shear_setting"]["shear_type"] == "constant":
        g1_field, g2_field, _ = get_shear_field(config=self.overall_config)
Fang Yuedong's avatar
Fang Yuedong committed
68
69
        self.chip_output.Log_info(
            "Use constant shear: g1=%.5f, g2=%.5f" % (g1_field, g2_field))
70
71
72
73

    # Get chip WCS
    if not hasattr(self, 'h_ext'):
        _, _ = self.prepare_headers(chip=chip, pointing=pointing)
Fang Yuedong's avatar
Fang Yuedong committed
74
75
76

    chip_wcs = galsim.FitsWCS(header=self.h_ext)

77
    # Loop over objects
78
    nobj = len(cat.objs)
79
80
81
82
83
84
85
    missed_obj = 0
    bright_obj = 0
    dim_obj = 0
    for j in range(nobj):
        # # [DEBUG] [TODO]
        # if j >= 10:
        #     break
86
        obj = cat.objs[j]
87
88
89

        # load and convert SED; also caculate object's magnitude in all CSST bands
        try:
90
91
            sed_data = cat.load_sed(obj)
            norm_filt = cat.load_norm_filt(obj)
Fang Yuedong's avatar
Fang Yuedong committed
92
            obj.sed, obj.param["mag_%s" % filt.filter_type.lower()], obj.param["flux_%s" % filt.filter_type.lower()] = cat.convert_sed(
93
94
                mag=obj.param["mag_use_normal"],
                sed=sed_data,
Fang Yuedong's avatar
Fang Yuedong committed
95
                target_filt=filt,
96
                norm_filt=norm_filt,
Fang Yuedong's avatar
Fang Yuedong committed
97
                mu=obj.mu
98
            )
Fang Yuedong's avatar
Fang Yuedong committed
99
            _, obj.param["mag_%s" % cut_filter.filter_type.lower()], obj.param["flux_%s" % cut_filter.filter_type.lower()] = cat.convert_sed(
100
101
                mag=obj.param["mag_use_normal"],
                sed=sed_data,
Fang Yuedong's avatar
Fang Yuedong committed
102
                target_filt=cut_filter,
103
                norm_filt=norm_filt,
Fang Yuedong's avatar
Fang Yuedong committed
104
                mu=obj.mu
105
106
107
108
109
110
111
112
113
114
115
            )
        except Exception as e:
            traceback.print_exc()
            self.chip_output.Log_error(e)
            continue

        # [TODO] Testing
        # self.chip_output.Log_info("mag_%s = %.3f"%(filt.filter_type.lower(), obj.param["mag_%s"%filt.filter_type.lower()]))

        # Exclude very bright/dim objects (for now)
        if cut_filter.is_too_bright(
Fang Yuedong's avatar
Fang Yuedong committed
116
117
118
119
120
                mag=obj.param["mag_%s" %
                              self.overall_config["obs_setting"]["cut_in_band"].lower()],
                margin=self.overall_config["obs_setting"]["mag_sat_margin"]):
            self.chip_output.Log_info("obj %s too birght!! mag_%s = %.3f" % (
                obj.id, cut_filter.filter_type, obj.param["mag_%s" % self.overall_config["obs_setting"]["cut_in_band"].lower()]))
121
122
123
124
            bright_obj += 1
            obj.unload_SED()
            continue
        if filt.is_too_dim(
Fang Yuedong's avatar
Fang Yuedong committed
125
126
127
128
                mag=obj.getMagFilter(filt),
                margin=self.overall_config["obs_setting"]["mag_lim_margin"]):
            self.chip_output.Log_info("obj %s too dim!! mag_%s = %.3f" % (
                obj.id, filt.filter_type, obj.getMagFilter(filt)))
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
            dim_obj += 1
            obj.unload_SED()
            continue

        # Get corresponding shear values
        if self.overall_config["shear_setting"]["shear_type"] == "constant":
            if obj.type == 'star':
                obj.g1, obj.g2 = 0., 0.
            else:
                # Figure out shear fields from overall configuration shear setting
                obj.g1, obj.g2 = g1_field, g2_field
        elif self.overall_config["shear_setting"]["shear_type"] == "catalog":
            pass
        else:
            self.chip_output.Log_error("Unknown shear input")
            raise ValueError("Unknown shear input")

        # Get position of object on the focal plane
Fang Yuedong's avatar
Fang Yuedong committed
147
148
        pos_img, _, _, _, fd_shear = obj.getPosImg_Offset_WCS(
            img=chip.img, fdmodel=fd_model, chip=chip, verbose=False, chip_wcs=chip_wcs, img_header=self.h_ext)
149
150
151
152
153

        # [TODO] For now, only consider objects which their centers (after field distortion) are projected within the focal plane
        # Otherwise they will be considered missed objects
        # if pos_img.x == -1 or pos_img.y == -1 or (not chip.isContainObj(x_image=pos_img.x, y_image=pos_img.y, margin=0.)):
        if pos_img.x == -1 or pos_img.y == -1:
Fang Yuedong's avatar
Fang Yuedong committed
154
155
156
            self.chip_output.Log_info('obj_ra = %.6f, obj_dec = %.6f, obj_ra_orig = %.6f, obj_dec_orig = %.6f' % (
                obj.ra, obj.dec, obj.ra_orig, obj.dec_orig))
            self.chip_output.Log_error("Objected missed: %s" % (obj.id))
157
158
159
160
161
162
163
164
            missed_obj += 1
            obj.unload_SED()
            continue

        # Draw object & update output catalog
        try:
            if self.overall_config["run_option"]["out_cat_only"]:
                isUpdated = True
Fang Yuedong's avatar
Fang Yuedong committed
165
166
                obj.real_pos = obj.getRealPos(
                    chip.img, global_x=obj.posImg.x, global_y=obj.posImg.y, img_real_wcs=obj.chip_wcs)
167
168
169
170
                pos_shear = 0.
            elif chip.survey_type == "photometric" and not self.overall_config["run_option"]["out_cat_only"]:
                isUpdated, pos_shear = obj.drawObj_multiband(
                    tel=tel,
Fang Yuedong's avatar
Fang Yuedong committed
171
172
173
174
175
176
177
                    pos_img=pos_img,
                    psf_model=psf_model,
                    bandpass_list=filt.bandpass_sub_list,
                    filt=filt,
                    chip=chip,
                    g1=obj.g1,
                    g2=obj.g2,
178
                    exptime=exptime,
179
180
181
182
                    fd_shear=fd_shear)

            elif chip.survey_type == "spectroscopic" and not self.overall_config["run_option"]["out_cat_only"]:
                isUpdated, pos_shear = obj.drawObj_slitless(
Fang Yuedong's avatar
Fang Yuedong committed
183
184
185
186
187
188
189
190
                    tel=tel,
                    pos_img=pos_img,
                    psf_model=psf_model,
                    bandpass_list=filt.bandpass_sub_list,
                    filt=filt,
                    chip=chip,
                    g1=obj.g1,
                    g2=obj.g2,
191
                    exptime=exptime,
192
193
194
195
196
197
198
199
200
                    normFilter=norm_filt,
                    fd_shear=fd_shear)

            if isUpdated == 1:
                # TODO: add up stats
                self.chip_output.cat_add_obj(obj, pos_img, pos_shear)
                pass
            elif isUpdated == 0:
                missed_obj += 1
Fang Yuedong's avatar
Fang Yuedong committed
201
                self.chip_output.Log_error("Objected missed: %s" % (obj.id))
202
            else:
Fang Yuedong's avatar
Fang Yuedong committed
203
204
                self.chip_output.Log_error(
                    "Draw error, object omitted: %s" % (obj.id))
205
206
207
208
                continue
        except Exception as e:
            traceback.print_exc()
            self.chip_output.Log_error(e)
209
210
211
212
213
214
            self.chip_output.Log_error(
                "pointing: #%d, chipID: %d" % (pointing.id, chip.chipID))
            if obj.type == "galaxy":
                self.chip_output.Log_error("obj id: %s" % (obj.param['id']))
                self.chip_output.Log_error("    e1: %.5f\n    e2: %.5f\n    size: %f\n    bfrac: %f\n    detA: %f\n    g1: %.5f\n    g2: %.5f\n" % (
                    obj.param['e1'], obj.param['e2'], obj.param['size'], obj.param['bfrac'], obj.param['detA'], obj.param['g1'], obj.param['g2']))
215
216
217
218
219
220
221
222

        # Unload SED:
        obj.unload_SED()
        del obj
        gc.collect()
    del psf_model
    gc.collect()

Fang Yuedong's avatar
Fang Yuedong committed
223
224
    self.chip_output.Log_info("Running checkpoint #1 (Object rendering finished): pointing-%d chip-%d pid-%d memory-%6.2fGB" %
                              (pointing.id, chip.chipID, os.getpid(), (psutil.Process(os.getpid()).memory_info().rss / 1024 / 1024 / 1024)))
225

Fang Yuedong's avatar
Fang Yuedong committed
226
227
228
229
230
231
    self.chip_output.Log_info(
        "# objects that are too bright %d out of %d" % (bright_obj, nobj))
    self.chip_output.Log_info(
        "# objects that are too dim %d out of %d" % (dim_obj, nobj))
    self.chip_output.Log_info(
        "# objects that are missed %d out of %d" % (missed_obj, nobj))
232
233
234
235

    # Apply flat fielding (with shutter effects)
    flat_normal = np.ones_like(chip.img.array)
    if obs_param["flat_fielding"] == True:
Fang Yuedong's avatar
Fang Yuedong committed
236
237
        flat_normal = flat_normal * chip.flat_img.array / \
            np.mean(chip.flat_img.array)
238
239
240
    if obs_param["shutter_effect"] == True:
        flat_normal = flat_normal * chip.shutter_img
        flat_normal = np.array(flat_normal, dtype='float32')
Fang Yuedong's avatar
Fang Yuedong committed
241
242
        self.updateHeaderInfo(header_flag='ext', keys=[
                              'SHTSTAT'], values=[True])
243
    else:
Fang Yuedong's avatar
Fang Yuedong committed
244
245
        self.updateHeaderInfo(header_flag='ext', keys=['SHTSTAT', 'SHTOPEN1', 'SHTCLOS0'], values=[
                              True, self.h_ext['SHTCLOS1'], self.h_ext['SHTOPEN0']])
246
247
248
    chip.img *= flat_normal
    del flat_normal

249
250
251
252
    # renew header info
    datetime_obs = datetime.utcfromtimestamp(pointing.timestamp)
    datetime_obs = datetime_obs.replace(tzinfo=timezone.utc)
    t_obs = Time(datetime_obs)
Fang Yuedong's avatar
Fang Yuedong committed
253
254

    # ccd刷新2s,等待0.s,开始曝光
255
    t_obs_renew = Time(t_obs.mjd - (2.+0.) / 86400., format="mjd")
256

Fang Yuedong's avatar
Fang Yuedong committed
257
258
259
260
    t_obs_utc = datetime.utcfromtimestamp(np.round(datetime.utcfromtimestamp(
        t_obs_renew.unix).replace(tzinfo=timezone.utc).timestamp(), 1))
    self.updateHeaderInfo(header_flag='prim', keys=[
                          'DATE-OBS'], values=[t_obs_utc.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-5]])
261

Fang Yuedong's avatar
Fang Yuedong committed
262
263
264
    # dark time : 曝光时间+刷新后等带时间0.s+关快门后读出前等待0.s
    self.updateHeaderInfo(header_flag='ext', keys=[
                          'DARKTIME'], values=[0.+0.+pointing.exp_time])
265

Fang Yuedong's avatar
Fang Yuedong committed
266
    return chip, filt, tel, pointing