Commit 29ac5666 authored by Fang Yuedong's avatar Fang Yuedong
Browse files

Baseline

parents
Loading
Loading
Loading
Loading
+93 −0
Original line number Diff line number Diff line
import os

class ChipOutput(object):
    def __init__(self, config, focal_plane, chip, filt, imgKey0="", imgKey1="", imgKey2="", exptime=150., mjdTime="", ra_cen=None, dec_cen=None, pointing_ID='0', subdir="./", prefix=""):
        self.focal_plane = focal_plane
        self.chip = chip
        self.filt = filt
        self.imgKey0 = imgKey0
        self.imgKey1 = imgKey1
        self.imgKey2 = imgKey2
        self.exptime = exptime
        self.mjdTime = mjdTime
        if (ra_cen is not None) and (dec_cen is not None):
            self.ra_cen = ra_cen
            self.dec_cen = dec_cen
        else:
            self.ra_cen = config["ra_center"]
            self.dec_cen = config["dec_center"]
        exp_name = imgKey0 + "_%s_%s.fits"
        self.chipLabel = focal_plane.getChipLabel(chip.chipID)
        self.img_name =  prefix + exp_name%(self.chipLabel, filt.filter_type)
        # self.cat_name = self.img_name[:-5] + ".cat"
        self.cat_name = 'MSC_' +  config["date_obs"] + config["time_obs"] + "_" + str(pointing_ID).rjust(7, '0') + "_" + self.chipLabel.rjust(2,'0') + ".cat"
        self.subdir = subdir

        # hdr1  = "#ID ID_chip filter xImage yImage ra dec z mag flag SNR "
        hdr1  = "#ID ID_chip filter xImage yImage ra dec z mag flag "
        hdr2  = "thetaR bfrac hlr_disk hlr_bulge e1_disk e2_disk e1_bulge e2_bulge e1_total e2_total"
        hdr3  = "e1PSF e2PSF e1 e2 g1 g2 e1OBS e2OBS"
        hdr4  = "sed_type av redden "
        hdr5  = "star_model teff logg feh\n"
        # fmt1  = "%10d %4d %5s %10.3f %10.3f %15.6f %15.6f %7.4f %8.4f %2d %9.2f "
        fmt1  = "%10d %4d %5s %10.3f %10.3f %15.6f %15.6f %7.4f %8.4f %2d "
        fmt2  = "%8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f"
        fmt3  = "%8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f %8.4f"
        fmt4 = "%2d %8.4f %8.4f "
        fmt5 = "%10s %8.4f %8.4f %8.4f\n"
        self.hdr = hdr1 + hdr2 + hdr3 + hdr4 + hdr5
        self.fmt = fmt1 + fmt2 + fmt3 + fmt4 + fmt5
        self.cat = open(os.path.join(self.subdir, self.cat_name), "w")
        self.cat.write(self.hdr)

    def updateHDR(self, hdr):
        hdrNew = [{"name":"RDNOISE", "value":self.chip.read_noise,        "comment":"read noise in e-/pixel"},
                {"name":"DARK",    "value":self.chip.dark_noise,        "comment":"Dark noise (e-/pixel/s)"},
                {"name":"EXPTIME", "value":self.exptime,          "comment":"exposure time in second"},
                {"name":"GAIN",    "value":self.chip.gain,             "comment":"CCD gain in e-/ADU"},
                {"name":"SATURATE","value":65535.0,          "comment":"saturation level"},
                {"name":"CCDCHIP",  "value":int(self.chipLabel), "comment":"chip ID in the CCD mosaic"},
                {"name":"FILTER",  "value":self.filt.filter_type,          "comment":"filter name"},
                {"name":"MJD-OBS", "value":self.mjdTime,          "comment":"Modified Julian Date (MJD) of observation"},
                {"name":"DATE-OBS","value":self.imgKey1,          "comment":"Date of observation"},
                {"name":"EQUINOX", "value":2000.0},
                {"name":"RADECSYS","value":"ICRS"},
                {"name":"RA",      "value":self.ra_cen,           "comment":"telescope pointing center"},
                {"name":"DEC",     "value":self.dec_cen,          "comment":"telescope pointing center"},
                {"name":"OBJECT",  "value":"CSS-OS"},
                {"name":"WCSDIM",  "value":2.0,              "comment":"WCS Dimensionality"},
                {"name":"EXTNAME", "value":"IM1",            "comment":"Extension name"},
                {"name":"BSCALE",  "value":1.0},
                {"name":"BZERO",   "value":0.0},
                {"name":"OBSID",   "value":self.imgKey0,          "comment":"Observation ID"},
                {"name":"CCDNAME", "value":"ccd"+self.chipLabel,"comment":"CCD name"},
                {"name":"RSPEED",  "value":10.0,             "comment":"Read speed"},
                {"name":"CHIPTEMP","value":-100.0,           "comment":"Chip temperature"},
                {"name":"DATASEC", "value":"1:%d,1:%d"%(self.chip.npix_x,self.chip.npix_y), "comment":"Data section"},
                {"name":"CCDSUM",  "value":self.chip.npix_x*self.chip.npix_y,      "comment":"CCD pixel summing"},
                {"name":"NSUM",    "value":self.chip.npix_x*self.chip.npix_y,      "comment":"CCD pixel summing"},
                {"name":"AUTHOR",  "value":"CSST-Sim Group"},
                {"name":"GROUP",   "value":"Weak Lensing Working Group for CSST"}]
        for item in hdrNew:
            hdr.add_record(item)
        return hdr

    # def cat_add_obj(self, obj, pos_img, snr, pos_shear, g1, g2):
        def cat_add_obj(self, obj, pos_img, pos_shear, g1, g2):
        ximg = pos_img.x - self.chip.bound.xmin + 1.0
        yimg = pos_img.y - self.chip.bound.ymin + 1.0
        e1, e2, g1, g2, e1OBS, e2OBS = obj.getObservedEll(g1, g2)
        if obj.type == 'galaxy':
            line = self.fmt%(obj.id, int(self.chipLabel), self.filt.filter_type, ximg, yimg, obj.ra, obj.dec, obj.z, obj.getMagFilter(self.filt), obj.param["star"], obj.thetaR, obj.bfrac, obj.hlr_disk, obj.hlr_bulge,
                obj.e1_disk, obj.e2_disk, obj.e1_bulge, obj.e2_bulge, obj.e1_total, obj.e2_total,
                pos_shear.g1, pos_shear.g2, e1, e2, g1, g2, e1OBS, e2OBS, obj.sed_type, obj.param['av'], obj.param['redden'], 'n', 0, 0, 0)
        elif obj.type == "quasar":
            line = self.fmt % (obj.id, int(self.chipLabel), self.filt.filter_type, ximg, yimg, obj.ra, obj.dec, obj.z,
                               obj.getMagFilter(self.filt), obj.param["star"], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                               0.0, 0.0,
                               pos_shear.g1, pos_shear.g2, e1, e2, g1, g2, e1OBS, e2OBS, obj.sed_type, obj.param['av'], obj.param['redden'], 'n', 0.0, 0.0, 0.0)
        else:
            line = self.fmt%(obj.id, int(self.chipLabel), self.filt.filter_type, ximg, yimg, obj.ra, obj.dec, obj.z, obj.getMagFilter(self.filt), obj.param["star"], 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, 0.0,
                pos_shear.g1, pos_shear.g2, e1, e2, g1, g2, e1OBS, e2OBS, 0, 0.0, 0.0, obj.param['model_tag'], obj.param['teff'], obj.param['logg'],obj.param['feh'])
        # line = self.fmt%(obj.id, int(self.chipLabel), self.filt.filter_type, ximg, yimg, obj.ra, obj.dec, obj.z, obj.getMagFilter(self.filt), obj.param["star"], pos_shear.g1, pos_shear.g2, e1, e2, g1, g2, e1OBS, e2OBS)
        self.cat.write(line)
 No newline at end of file
+121 −0
Original line number Diff line number Diff line
import galsim
import os
from astropy.time import Time as asTime

def ConfigDir(cat_dir=None, work_dir=None, data_dir=None, config_file_path=None):
    path_dict = {}
    # Working directory
    if work_dir == None:
        dirname, _ = os.path.split(os.path.abspath(__file__))
        path_dict["work_dir"] = "/".join(dirname.split("/")[:-1]) + "/"
    else:
        path_dict["work_dir"] = work_dir
    
    # Configuration file
    if config_file_path is not None:
        path_dict["config_file"] = config_file_path
    else:
        path_dict["config_file"] = os.path.join(path_dict["work_dir"], "ObservationSim.cfg")
    
    # Output directories
    # path_dict["output_fig_dir"] = os.path.join(path_dict["work_dir"], "figure/")
    # if not os.path.exists(path_dict["output_fig_dir"]):
    #     os.system("mkdir %s"%path_dict["output_fig_dir"])
    # path_dict["output_cat_dir"] = os.path.join(path_dict["work_dir"], "scat/")
    # if not os.path.exists(path_dict["output_cat_dir"]):
    #     os.system("mkdir %s"%path_dict["output_cat_dir"])
    path_dict["output_img_dir"] = os.path.join(path_dict["work_dir"], "simg/")
    if not os.path.exists(path_dict["output_img_dir"]):
        os.system("mkdir %s"%path_dict["output_img_dir"])
    
    # Data directory
    if data_dir == None:
        path_dict["data_dir"] =os.path.join(path_dict["work_dir"], "data/")
    else:
        path_dict["data_dir"] = data_dir
    # Data sub-catalogs
    # Object catalog direcotry
    # path_dict["cat_dir"] = os.path.join(path_dict["data_dir"], "catalog_points_7degree2/", cat_dir)
    path_dict["cat_dir"] = os.path.join(path_dict["data_dir"], "Catalog_20210126")
    # PSF data directory
    path_dict["psf_dir"] = os.path.join(path_dict["data_dir"], "csstPSFdata/CSSOS_psf_20210108/CSST_psf_ciomp_2p5um_cycle3_ccr90_proc")
    # SED catalog directory
    path_dict["SED_dir"] = os.path.join(path_dict["data_dir"], "imageSims/Catalog/SEDObject")
    path_dict["template_dir"] = path_dict["data_dir"] + "Templates/"
    # Directories/files for instrument parameters, e.g. efficiency curves.
    path_dict["filter_dir"] = os.path.join(path_dict["data_dir"], "Filters")
    path_dict["ccd_dir"] = os.path.join(path_dict["data_dir"], "Filter_CCD_Mirror/ccd")
    path_dict["mirror_file"] = os.path.join(path_dict["data_dir"], "Filter_CCD_Mirror/mirror_ccdnote.txt")

    # Cosmic-ray data directory:
    path_dict["CRdata_dir"] = os.path.join(path_dict["data_dir"], "CRdata")

    # Slitless spectroscopy realted
    path_dict["sls_dir"] = os.path.join(path_dict["data_dir"], "CONF/")
    path_dict["normalize_dir"] = os.path.join(path_dict["data_dir"], "normalize_filter/")

    return path_dict

def ReadConfig(config_filename):
    """Read in a configuration file and return the corresponding dict(s).

    Parameters:
        config_filename:    The name of the configuration file to read.
    Returns:
        (list) of config dicts
    """
    config = {}
    config_file = open(config_filename).readlines()
    nlines = len(config_file)
    for i in range(nlines):
        row = config_file[i].split()
        if len(row) <= 1: continue # blank row
        if not "#" in row:
            if len(row) == 2:
                key, val = row[0:2]
                config.update({key:val})
            else:
                print("!! Something is wrong with parameter '%s'."%row[0])
                return
        elif row.index("#") == 2:
            key, val = row[0:2]
            config.update({key:val})
        elif row.index("#") == 0:
            continue # annotation
        else:
            print("!! Something is wrong with parameter '%s'."%row[0])
            return
    config = ParseConfig(config)
    return config

def ParseConfig(config):
    """Parse the config values to the right type

    Parameters:
        config:     raw config dict 
    Returns:
        Parsed config dict
    """
    config["ra_center"]     = float(config["ra_center"])
    config["dec_center"]    = float(config["dec_center"])
    config["psf_rcont"]     = config["psf_rcont"].split(",")
    config["psfRa"]         = float(config["psf_rcont"][0])
    config["psfCont"]       = float(config["psf_rcont"][1])
    config["image_rot"]     = float(config["image_rot"])*galsim.degrees
    config["sigma_spin"]    = float(config["sigma_spin"])
    config["reduced_g1"]    = float(config["reduced_g1"])
    config["reduced_g2"]    = float(config["reduced_g2"])
    config["rotateEll"]     = float(config["rotateEll"])
    config["reEll"]         = int(config["rotateEll"]/45.0)
    if config["reEll"]==0: config["reIndex"] = "P"
    if config["reEll"]==1: config["reIndex"] = "X"
    if config["reEll"]==2: config["reIndex"] = "N"
    if config["reEll"]==3: config["reIndex"] = "Y"
    config["seed_flat"]     = int(config["seed_flat"])
    config["seed_prnu"]     = int(config["seed_prnu"])
    config["seed_star"]     = int(config["seed_star"])
    config["seed_gal"]      = int(config["seed_gal"])
    config["seed_Av"]       = int(config["seed_Av"])
    config["bias_level"]    = int(config["bias_level"])
    config["df_strength"]   = float(config["df_strength"])
    return config
 No newline at end of file
Loading