Commit 36189a3e authored by JX's avatar JX 😵
Browse files

Merge remote-tracking branch 'origin/develop'

parents dd26d370 27646bc4
Pipeline #4509 passed with stage
in 0 seconds
import numpy as np
from ObservationSim.MockObject import FlatLED
from observation_sim.mock_objects import FlatLED
import galsim
from astropy.time import Time
......@@ -7,29 +7,34 @@ from datetime import datetime, timezone
import gc
def add_LED_Flat(self, chip, filt, tel, pointing, catalog, obs_param):
if not hasattr(self, 'h_ext'):
_, _ = self.prepare_headers(chip=chip, pointing=pointing)
chip_wcs = galsim.FitsWCS(header = self.h_ext)
chip_wcs = galsim.FitsWCS(header=self.h_ext)
pf_map = np.zeros_like(chip.img.array)
if obs_param["LED_TYPE"] is not None:
if len(obs_param["LED_TYPE"]) != 0:
print("LED OPEN--------")
led_obj = FlatLED(chip, filt)
led_flat, ledstat, letts = led_obj.drawObj_LEDFlat(led_type_list=obs_param["LED_TYPE"], exp_t_list=obs_param["LED_TIME"])
led_flat, ledstat, letts = led_obj.drawObj_LEDFlat(
led_type_list=obs_param["LED_TYPE"], exp_t_list=obs_param["LED_TIME"])
pf_map = led_flat
self.updateHeaderInfo(header_flag='ext', keys = ['LEDSTAT'], values = [ledstat])
self.updateHeaderInfo(header_flag='ext', keys = ['LEDT01','LEDT02','LEDT03','LEDT04','LEDT05','LEDT06','LEDT07','LEDT08','LEDT09','LEDT10','LEDT11','LEDT12','LEDT13','LEDT14'], values = letts)
self.updateHeaderInfo(header_flag='ext', keys=[
'LEDSTAT'], values=[ledstat])
self.updateHeaderInfo(header_flag='ext', keys=['LEDT01', 'LEDT02', 'LEDT03', 'LEDT04', 'LEDT05', 'LEDT06',
'LEDT07', 'LEDT08', 'LEDT09', 'LEDT10', 'LEDT11', 'LEDT12', 'LEDT13', 'LEDT14'], values=letts)
if obs_param["shutter_effect"] == True:
pf_map = pf_map * chip.shutter_img
pf_map = np.array(pf_map, dtype='float32')
self.updateHeaderInfo(header_flag='ext', keys = ['SHTSTAT'], values = [True])
self.updateHeaderInfo(header_flag='ext', keys=[
'SHTSTAT'], values=[True])
else:
self.updateHeaderInfo(header_flag='ext', keys = ['SHTSTAT','SHTOPEN1','SHTCLOS0'], values = [True,self.h_ext['SHTCLOS1'],self.h_ext['SHTOPEN0']])
self.updateHeaderInfo(header_flag='ext', keys=['SHTSTAT', 'SHTOPEN1', 'SHTCLOS0'], values=[
True, self.h_ext['SHTCLOS1'], self.h_ext['SHTOPEN0']])
chip.img = chip.img + pf_map
......@@ -37,15 +42,18 @@ def add_LED_Flat(self, chip, filt, tel, pointing, catalog, obs_param):
datetime_obs = datetime.utcfromtimestamp(pointing.timestamp)
datetime_obs = datetime_obs.replace(tzinfo=timezone.utc)
t_obs = Time(datetime_obs)
##ccd刷新2s,等待0.5s,开灯后等待0.5s,开始曝光
# ccd刷新2s,等待0.5s,开灯后等待0.5s,开始曝光
t_obs_renew = Time(t_obs.mjd - (2.) / 86400., format="mjd")
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]])
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]])
#dark time :
self.updateHeaderInfo(header_flag='ext', keys = ['DARKTIME'], values = [pointing.exp_time])
# dark time :
self.updateHeaderInfo(header_flag='ext', keys=[
'DARKTIME'], values=[pointing.exp_time])
gc.collect()
return chip, filt, tel, pointing
\ No newline at end of file
return chip, filt, tel, pointing
import numpy as np
import galsim
from ObservationSim.Instrument.Chip import ChipUtils as chip_utils
from ObservationSim.Instrument.Chip.libCTI.CTI_modeling import CTI_sim
from observation_sim.instruments.chip import chip_utils
from observation_sim.instruments.chip.libCTI.CTI_modeling import CTI_sim
def add_brighter_fatter(self, chip, filt, tel, pointing, catalog, obs_param):
chip.img = chip_utils.add_brighter_fatter(img=chip.img)
return chip, filt, tel, pointing
def apply_CTE(self, chip, filt, tel, pointing, catalog, obs_param):
self.chip_output.Log_info(" Apply CTE Effect")
### 2*8 -> 1*16 img-layout
# 2*8 -> 1*16 img-layout
img = chip_utils.formatOutput(GSImage=chip.img)
chip.nsecy = 1
chip.nsecx = 16
......@@ -20,23 +22,26 @@ def apply_CTE(self, chip, filt, tel, pointing, catalog, obs_param):
dy = int(ny/chip.nsecy)
newimg = galsim.Image(nx, int(ny+chip.overscan_y), init_value=0)
for ichannel in range(16):
print('\n***add CTI effects: pointing-{:} chip-{:} channel-{:}***'.format(pointing.id, chip.chipID, ichannel+1))
print('\n***add CTI effects: pointing-{:} chip-{:} channel-{:}***'.format(
pointing.id, chip.chipID, ichannel+1))
noverscan, nsp, nmax = chip.overscan_y, 3, 10
beta, w, c = 0.478, 84700, 0
t = np.array([0.74, 7.7, 37],dtype=np.float32)
rho_trap = np.array([0.6, 1.6, 1.4],dtype=np.float32)
trap_seeds = np.array([0, 1000, 10000],dtype=np.int32) + ichannel + chip.chipID*16
release_seed = 50 + ichannel + pointing.id*30 + chip.chipID*16
newimg.array[:, 0+ichannel*dx:dx+ichannel*dx] = CTI_sim(img_arr[:, 0+ichannel*dx:dx+ichannel*dx],dx,dy,noverscan,nsp,nmax,beta,w,c,t,rho_trap,trap_seeds,release_seed)
t = np.array([0.74, 7.7, 37], dtype=np.float32)
rho_trap = np.array([0.6, 1.6, 1.4], dtype=np.float32)
trap_seeds = np.array(
[0, 1000, 10000], dtype=np.int32) + ichannel + chip.chipID*16
release_seed = 50 + ichannel + pointing.id*30 + chip.chipID*16
newimg.array[:, 0+ichannel*dx:dx+ichannel*dx] = CTI_sim(
img_arr[:, 0+ichannel*dx:dx+ichannel*dx], dx, dy, noverscan, nsp, nmax, beta, w, c, t, rho_trap, trap_seeds, release_seed)
newimg.wcs = img.wcs
del img
img = newimg
### 1*16 -> 2*8 img-layout
# 1*16 -> 2*8 img-layout
chip.img = chip_utils.formatRevert(GSImage=img)
chip.nsecy = 2
chip.nsecx = 8
# [TODO] make overscan_y == 0
chip.overscan_y = 0
return chip, filt, tel, pointing
\ No newline at end of file
return chip, filt, tel, pointing
from ObservationSim.Instrument.Chip import ChipUtils as chip_utils
from observation_sim.instruments.chip import chip_utils
def add_cosmic_rays(self, chip, filt, tel, pointing, catalog, obs_param):
self.chip_output.Log_info(" Adding Cosmic-Ray")
# Get exposure time
if (obs_param) and ("exptime" in obs_param) and (obs_param["exptime"] is not None):
exptime = obs_param["exptime"]
......@@ -10,9 +11,9 @@ def add_cosmic_rays(self, chip, filt, tel, pointing, catalog, obs_param):
exptime = pointing.exp_time
chip.img, crmap_gsimg, cr_event_num = chip_utils.add_cosmic_rays(
img=chip.img,
chip=chip,
exptime=exptime,
img=chip.img,
chip=chip,
exptime=exptime,
seed=self.overall_config["random_seeds"]["seed_CR"]+pointing.id*30+chip.chipID)
# Save cosmic ray image
if (obs_param) and ("save_cosmic_img" in obs_param) and (obs_param["save_cosmic_img"] is not None):
......@@ -27,4 +28,4 @@ def add_cosmic_rays(self, chip, filt, tel, pointing, catalog, obs_param):
project_cycle=self.overall_config["project_cycle"],
run_counter=self.overall_config["run_counter"]
)
return chip, filt, tel, pointing
\ No newline at end of file
return chip, filt, tel, pointing
......@@ -4,8 +4,8 @@ import psutil
import traceback
import numpy as np
import galsim
from ObservationSim._util import get_shear_field
from ObservationSim.PSF import PSFGauss, FieldDistortion, PSFInterp, PSFInterpSLS
from observation_sim._util import get_shear_field
from observation_sim.PSF import PSFGauss, FieldDistortion, PSFInterp, PSFInterpSLS
from astropy.time import Time
from datetime import datetime, timezone
......
from numpy.random import Generator, PCG64
from ObservationSim.Instrument.Chip import ChipUtils as chip_utils
from ObservationSim.Instrument.Chip import Effects
from observation_sim.instruments.chip import chip_utils
from observation_sim.instruments.chip import effects
def apply_PRNU(self, chip, filt, tel, pointing, catalog, obs_param):
chip.img *= chip.prnu_img
if self.overall_config["output_setting"]["prnu_output"] == True:
chip.prnu_img.write("%s/FlatImg_PRNU_%s.fits" % (self.chip_output.subdir, str(chip.chipID).rjust(2, '0')))
chip.prnu_img.write("%s/FlatImg_PRNU_%s.fits" %
(self.chip_output.subdir, str(chip.chipID).rjust(2, '0')))
return chip, filt, tel, pointing
def add_poisson_and_dark(self, chip, filt, tel, pointing, catalog, obs_param):
# Add dark current & Poisson noise
# Get exposure time
......@@ -15,61 +18,68 @@ def add_poisson_and_dark(self, chip, filt, tel, pointing, catalog, obs_param):
exptime = obs_param["exptime"]
else:
exptime = pointing.exp_time
if obs_param["add_dark"] == True:
chip.img, _ = chip_utils.add_poisson(img=chip.img,
chip=chip,
exptime=pointing.exp_time,
poisson_noise=chip.poisson_noise,
InputDark=None)
chip=chip,
exptime=pointing.exp_time,
poisson_noise=chip.poisson_noise,
InputDark=None)
else:
chip.img, _ = chip_utils.add_poisson(img=chip.img,
chip=self,
exptime=exptime,
poisson_noise=chip.poisson_noise,
dark_noise=0.)
chip.img, _ = chip_utils.add_poisson(img=chip.img,
chip=self,
exptime=exptime,
poisson_noise=chip.poisson_noise,
dark_noise=0.)
return chip, filt, tel, pointing
def add_detector_defects(self, chip, filt, tel, pointing, catalog, obs_param):
# Add Hot Pixels or/and Dead Pixels
rgbadpix = Generator(PCG64(int(self.overall_config["random_seeds"]["seed_defective"]+chip.chipID)))
rgbadpix = Generator(
PCG64(int(self.overall_config["random_seeds"]["seed_defective"]+chip.chipID)))
badfraction = 5E-5*(rgbadpix.random()*0.5+0.7)
chip.img = Effects.DefectivePixels(
chip.img,
IfHotPix=obs_param["hot_pixels"],
chip.img = effects.DefectivePixels(
chip.img,
IfHotPix=obs_param["hot_pixels"],
IfDeadPix=obs_param["dead_pixels"],
fraction=badfraction,
fraction=badfraction,
seed=self.overall_config["random_seeds"]["seed_defective"]+chip.chipID, biaslevel=0)
# Apply Bad columns
# Apply Bad columns
if obs_param["bad_columns"] == True:
chip.img = Effects.BadColumns(chip.img,
seed=self.overall_config["random_seeds"]["seed_badcolumns"],
chipid=chip.chipID)
chip.img = effects.BadColumns(chip.img,
seed=self.overall_config["random_seeds"]["seed_badcolumns"],
chipid=chip.chipID)
return chip, filt, tel, pointing
def add_nonlinearity(self, chip, filt, tel, pointing, catalog, obs_param):
self.chip_output.Log_info(" Applying Non-Linearity on the chip image")
chip.img = Effects.NonLinearity(GSImage=chip.img,
beta1=5.e-7,
beta2=0)
chip.img = effects.NonLinearity(GSImage=chip.img,
beta1=5.e-7,
beta2=0)
return chip, filt, tel, pointing
def add_blooming(self, chip, filt, tel, pointing, catalog, obs_param):
self.chip_output.Log_info(" Applying CCD Saturation & Blooming")
chip.img = Effects.SaturBloom(GSImage=chip.img,
nsect_x=1,
nsect_y=1,
fullwell=int(chip.full_well))
chip.img = effects.SaturBloom(GSImage=chip.img,
nsect_x=1,
nsect_y=1,
fullwell=int(chip.full_well))
return chip, filt, tel, pointing
def add_bias(self, chip, filt, tel, pointing, catalog, obs_param):
self.chip_output.Log_info(" Adding Bias level and 16-channel non-uniformity")
self.chip_output.Log_info(
" Adding Bias level and 16-channel non-uniformity")
if obs_param["bias_16channel"] == True:
chip.img = Effects.AddBiasNonUniform16(chip.img,
bias_level=float(chip.bias_level),
nsecy = chip.nsecy,
nsecx=chip.nsecx,
seed=self.overall_config["random_seeds"]["seed_biasNonUniform"]+chip.chipID)
chip.img = effects.AddBiasNonUniform16(chip.img,
bias_level=float(
chip.bias_level),
nsecy=chip.nsecy,
nsecx=chip.nsecx,
seed=self.overall_config["random_seeds"]["seed_biasNonUniform"]+chip.chipID)
elif obs_param["bias_16channel"] == False:
chip.img += self.bias_level
return chip, filt, tel, pointing
import numpy as np
import galsim
from ObservationSim.Straylight import calculateSkyMap_split_g
from ObservationSim.Instrument import FilterParam
from observation_sim.sky_background import calculateSkyMap_split_g
from observation_sim.instruments import FilterParam
from astropy.time import Time
from datetime import datetime, timezone
def add_sky_background_sci(self, chip, filt, tel, pointing, catalog, obs_param):
# 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
flat_normal = np.ones_like(chip.img.array)
if obs_param["flat_fielding"] == True:
flat_normal = flat_normal * chip.flat_img.array / np.mean(chip.flat_img.array)
flat_normal = flat_normal * chip.flat_img.array / \
np.mean(chip.flat_img.array)
if obs_param["shutter_effect"] == True:
flat_normal = flat_normal * chip.shutter_img
flat_normal = np.array(flat_normal, dtype='float32')
self.updateHeaderInfo(header_flag='ext', keys = ['SHTSTAT'], values = [True])
self.updateHeaderInfo(header_flag='ext', keys=[
'SHTSTAT'], values=[True])
else:
self.updateHeaderInfo(header_flag='ext', keys = ['SHTSTAT','SHTOPEN1','SHTCLOS0'], values = [True,self.h_ext['SHTCLOS1'],self.h_ext['SHTOPEN0']])
self.updateHeaderInfo(header_flag='ext', keys=['SHTSTAT', 'SHTOPEN1', 'SHTCLOS0'], values=[
True, self.h_ext['SHTCLOS1'], self.h_ext['SHTOPEN0']])
if obs_param["enable_straylight_model"]:
# Filter.sky_background, Filter.zodical_spec will be updated
filt.setFilterStrayLightPixel(
jtime = pointing.jdt,
sat_pos = np.array([pointing.sat_x, pointing.sat_y, pointing.sat_z]),
pointing_radec = np.array([pointing.ra,pointing.dec]),
sun_pos = np.array([pointing.sun_x, pointing.sun_y, pointing.sun_z]))
self.chip_output.Log_info("================================================")
self.chip_output.Log_info("sky background + stray light pixel flux value: %.5f"%(filt.sky_background))
jtime=pointing.jdt,
sat_pos=np.array([pointing.sat_x, pointing.sat_y, pointing.sat_z]),
pointing_radec=np.array([pointing.ra, pointing.dec]),
sun_pos=np.array([pointing.sun_x, pointing.sun_y, pointing.sun_z]))
self.chip_output.Log_info(
"================================================")
self.chip_output.Log_info(
"sky background + stray light pixel flux value: %.5f" % (filt.sky_background))
if chip.survey_type == "photometric":
sky_map = filt.getSkyNoise(exptime = exptime)
sky_map = filt.getSkyNoise(exptime=exptime)
sky_map = sky_map * np.ones_like(chip.img.array) * flat_normal
sky_map = galsim.Image(array=sky_map)
else:
# chip.loadSLSFLATCUBE(flat_fn='flat_cube.fits')
sky_map = calculateSkyMap_split_g(
skyMap=flat_normal,
blueLimit=filt.blue_limit,
redLimit=filt.red_limit,
conf=chip.sls_conf,
pixelSize=chip.pix_scale,
isAlongY=0,
flat_cube=chip.flat_cube,
zoldial_spec = filt.zodical_spec)
skyMap=flat_normal,
blueLimit=filt.blue_limit,
redLimit=filt.red_limit,
conf=chip.sls_conf,
pixelSize=chip.pix_scale,
isAlongY=0,
flat_cube=chip.flat_cube,
zoldial_spec=filt.zodical_spec)
sky_map = (sky_map + filt.sky_background)*exptime
# sky_map = sky_map * tel.pupil_area * obs_param["exptime"]
chip.img += sky_map
return chip, filt, tel, pointing
def add_sky_flat_calibration(self, chip, filt, tel, pointing, catalog, obs_param):
if not hasattr(self, 'h_ext'):
_, _ = self.prepare_headers(chip=chip, pointing=pointing)
chip_wcs = galsim.FitsWCS(header = self.h_ext)
chip_wcs = galsim.FitsWCS(header=self.h_ext)
# 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
skyback_level = obs_param["flat_level"]
filter_param = FilterParam()
......@@ -75,27 +82,33 @@ def add_sky_flat_calibration(self, chip, filt, tel, pointing, catalog, obs_param
flat_normal = np.ones_like(chip.img.array)
if obs_param["flat_fielding"] == True:
flat_normal = flat_normal * chip.flat_img.array / np.mean(chip.flat_img.array)
flat_normal = flat_normal * chip.flat_img.array / \
np.mean(chip.flat_img.array)
if obs_param["shutter_effect"] == True:
flat_normal = flat_normal * chip.shutter_img
flat_normal = np.array(flat_normal, dtype='float32')
if self.overall_config["output_setting"]["shutter_output"] == True: # output 16-bit shutter effect image with pixel value <=65535
# output 16-bit shutter effect image with pixel value <=65535
if self.overall_config["output_setting"]["shutter_output"] == True:
shutt_gsimg = galsim.ImageUS(chip.shutter_img*6E4)
shutt_gsimg.write("%s/ShutterEffect_%s_1.fits" % (self.chip_output.subdir, str(chip.chipID).rjust(2, '0')))
self.updateHeaderInfo(header_flag='ext', keys = ['SHTSTAT'], values = [True])
shutt_gsimg.write("%s/ShutterEffect_%s_1.fits" %
(self.chip_output.subdir, str(chip.chipID).rjust(2, '0')))
self.updateHeaderInfo(header_flag='ext', keys=[
'SHTSTAT'], values=[True])
else:
self.updateHeaderInfo(header_flag='ext', keys = ['SHTSTAT','SHTOPEN1','SHTCLOS0'], values = [True,self.h_ext['SHTCLOS1'],self.h_ext['SHTOPEN0']])
self.updateHeaderInfo(header_flag='ext', keys=['SHTSTAT', 'SHTOPEN1', 'SHTCLOS0'], values=[
True, self.h_ext['SHTCLOS1'], self.h_ext['SHTOPEN0']])
if chip.survey_type == "photometric":
sky_map = flat_normal * np.ones_like(chip.img.array) * norm_scaler * filter_param.param[chip.filter_type][5] / tel.pupil_area * exptime
sky_map = flat_normal * np.ones_like(chip.img.array) * norm_scaler * \
filter_param.param[chip.filter_type][5] / tel.pupil_area * exptime
elif chip.survey_type == "spectroscopic":
# flat_normal = np.ones_like(chip.img.array)
if obs_param["flat_fielding"] == True:
flat_normal = flat_normal * chip.flat_img.array / np.mean(chip.flat_img.array)
flat_normal = flat_normal * chip.flat_img.array / \
np.mean(chip.flat_img.array)
if obs_param["shutter_effect"] == True:
flat_normal = flat_normal * chip.shutter_img
flat_normal = np.array(flat_normal, dtype='float32')
sky_map = calculateSkyMap_split_g(
......@@ -107,36 +120,42 @@ def add_sky_flat_calibration(self, chip, filt, tel, pointing, catalog, obs_param
isAlongY=0,
flat_cube=chip.flat_cube)
sky_map = sky_map * norm_scaler * exptime
chip.img += sky_map
return chip, filt, tel, pointing
def add_sky_background(self, chip, filt, tel, pointing, catalog, obs_param):
if not hasattr(self, 'h_ext'):
_, _ = self.prepare_headers(chip=chip, pointing=pointing)
chip_wcs = galsim.FitsWCS(header = self.h_ext)
chip_wcs = galsim.FitsWCS(header=self.h_ext)
if "flat_level" not in obs_param or "flat_level_filt" not in obs_param:
chip, filt, tel, pointing = self.add_sky_background_sci(chip, filt, tel, pointing, catalog, obs_param)
chip, filt, tel, pointing = self.add_sky_background_sci(
chip, filt, tel, pointing, catalog, obs_param)
else:
if obs_param.get('flat_level') is None or obs_param.get('flat_level_filt')is None:
chip, filt, tel, pointing = self.add_sky_background_sci(chip, filt, tel, pointing, catalog, obs_param)
if obs_param.get('flat_level') is None or obs_param.get('flat_level_filt') is None:
chip, filt, tel, pointing = self.add_sky_background_sci(
chip, filt, tel, pointing, catalog, obs_param)
else:
chip, filt, tel, pointing = self.add_sky_flat_calibration(chip, filt, tel, pointing, catalog, obs_param)
chip, filt, tel, pointing = self.add_sky_flat_calibration(
chip, filt, tel, pointing, catalog, obs_param)
# renew header info
datetime_obs = datetime.utcfromtimestamp(pointing.timestamp)
datetime_obs = datetime_obs.replace(tzinfo=timezone.utc)
t_obs = Time(datetime_obs)
##ccd刷新2s,等待0.5s,开始曝光
t_obs_renew = Time(t_obs.mjd - (2.+0.5) / 86400., format="mjd")
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]])
# ccd刷新2s,等待0.5s,开始曝光
t_obs_renew = Time(t_obs.mjd - (2.+0.5) / 86400., format="mjd")
#dark time : 曝光时间+刷新后等带时间0.5s+关闭快门时间1.5s+管快门后读出前等待0.5s
self.updateHeaderInfo(header_flag='ext', keys = ['DARKTIME'], values = [0.+0.0+0.0+pointing.exp_time])
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]])
# dark time : 曝光时间+刷新后等带时间0.5s+关闭快门时间1.5s+管快门后读出前等待0.5s
self.updateHeaderInfo(header_flag='ext', keys=['DARKTIME'], values=[
0.+0.0+0.0+pointing.exp_time])
return chip, filt, tel, pointing
\ No newline at end of file
return chip, filt, tel, pointing
from ObservationSim.Config.Header import generatePrimaryHeader, generateExtensionHeader
from observation_sim.config.header import generatePrimaryHeader, generateExtensionHeader
def prepare_headers(self, chip, pointing):
self.h_prim = generatePrimaryHeader(
xlen=chip.npix_x,
ylen=chip.npix_y,
pointing_id = pointing.obs_id,
pointing_type_code = pointing.pointing_type_code,
ra=pointing.ra,
dec=pointing.dec,
xlen=chip.npix_x,
ylen=chip.npix_y,
pointing_id=pointing.obs_id,
pointing_type_code=pointing.pointing_type_code,
ra=pointing.ra,
dec=pointing.dec,
pixel_scale=chip.pix_scale,
time_pt = pointing.timestamp,
time_pt=pointing.timestamp,
exptime=pointing.exp_time,
im_type=pointing.pointing_type,
sat_pos=[pointing.sat_x, pointing.sat_y, pointing.sat_z],
......@@ -19,32 +20,33 @@ def prepare_headers(self, chip, pointing):
chip_name=str(chip.chipID).rjust(2, '0'))
self.h_ext = generateExtensionHeader(
chip=chip,
xlen=chip.npix_x,
ylen=chip.npix_y,
ra=pointing.ra,
dec=pointing.dec,
pa=pointing.img_pa.deg,
gain=chip.gain,
readout=chip.read_noise,
dark=chip.dark_noise,
saturation=90000,
pixel_scale=chip.pix_scale,
xlen=chip.npix_x,
ylen=chip.npix_y,
ra=pointing.ra,
dec=pointing.dec,
pa=pointing.img_pa.deg,
gain=chip.gain,
readout=chip.read_noise,
dark=chip.dark_noise,
saturation=90000,
pixel_scale=chip.pix_scale,
pixel_size=chip.pix_size,
xcen=chip.x_cen,
ycen=chip.y_cen,
extName=pointing.pointing_type,
timestamp = pointing.timestamp,
exptime = pointing.exp_time,
readoutTime = chip.readout_time,
t_shutter_open = pointing.t_shutter_open,
t_shutter_close = pointing.t_shutter_close)
timestamp=pointing.timestamp,
exptime=pointing.exp_time,
readoutTime=chip.readout_time,
t_shutter_open=pointing.t_shutter_open,
t_shutter_close=pointing.t_shutter_close)
return self.h_prim, self.h_ext
def updateHeaderInfo(self,header_flag='prim', keys = ['key'], values = [0]):
def updateHeaderInfo(self, header_flag='prim', keys=['key'], values=[0]):
if header_flag == 'prim':
for key,value in zip(keys, values):
for key, value in zip(keys, values):
self.h_prim[key] = value
if header_flag == 'ext':
for key,value in zip(keys, values):
for key, value in zip(keys, values):
self.h_ext[key] = value
......@@ -2,66 +2,76 @@ import os
import galsim
import numpy as np
from astropy.io import fits
from ObservationSim.Instrument.Chip import ChipUtils as chip_utils
from ObservationSim.Instrument.Chip import Effects
from observation_sim.instruments.chip import chip_utils
from observation_sim.instruments.chip import effects
from astropy.time import Time
from datetime import datetime, timezone
def add_prescan_overscan(self, chip, filt, tel, pointing, catalog, obs_param):
self.chip_output.Log_info("Apply pre/over-scan")
chip.img = chip_utils.AddPreScan(GSImage=chip.img,
pre1=chip.prescan_x,
pre2=chip.prescan_y,
over1=chip.overscan_x,
over2=chip.overscan_y)
pre1=chip.prescan_x,
pre2=chip.prescan_y,
over1=chip.overscan_x,
over2=chip.overscan_y)
if obs_param["add_dark"] == True:
ny = int(chip.npix_y/2)
base_dark = (ny-1)*(chip.readout_time/ny)*chip.dark_noise
chip.img.array[(chip.prescan_y+ny):-(chip.prescan_y+ny),:] = base_dark
chip.img.array[(chip.prescan_y+ny):-(chip.prescan_y+ny), :] = base_dark
return chip, filt, tel, pointing
def add_readout_noise(self, chip, filt, tel, pointing, catalog, obs_param):
seed = int(self.overall_config["random_seeds"]["seed_readout"]) + pointing.id*30 + chip.chipID
seed = int(self.overall_config["random_seeds"]
["seed_readout"]) + pointing.id*30 + chip.chipID
rng_readout = galsim.BaseDeviate(seed)
readout_noise = galsim.GaussianNoise(rng=rng_readout, sigma=chip.read_noise)
readout_noise = galsim.GaussianNoise(
rng=rng_readout, sigma=chip.read_noise)
chip.img.addNoise(readout_noise)
return chip, filt, tel, pointing
def apply_gain(self, chip, filt, tel, pointing, catalog, obs_param):
self.chip_output.Log_info(" Applying Gain")
if obs_param["gain_16channel"] == True:
chip.img, chip.gain_channel = Effects.ApplyGainNonUniform16(chip.img,
gain=chip.gain,
nsecy = chip.nsecy,
nsecx=chip.nsecx,
seed=self.overall_config["random_seeds"]["seed_gainNonUniform"]+chip.chipID)
chip.img, chip.gain_channel = effects.ApplyGainNonUniform16(chip.img,
gain=chip.gain,
nsecy=chip.nsecy,
nsecx=chip.nsecx,
seed=self.overall_config["random_seeds"]["seed_gainNonUniform"]+chip.chipID)
elif obs_param["gain_16channel"] == False:
chip.img /= chip.gain
return chip, filt, tel, pointing
def quantization_and_output(self, chip, filt, tel, pointing, catalog, obs_param):
if not hasattr(self, 'h_ext'):
_, _ = self.prepare_headers(chip=chip, pointing=pointing)
self.updateHeaderInfo(header_flag='ext', keys = ['SHTSTAT','SHTOPEN1','SHTCLOS0','SHTCLOS1','EXPTIME'], values = [False,self.h_ext['SHTOPEN0'],self.h_ext['SHTOPEN0'],self.h_ext['SHTOPEN0'],0.0])
self.updateHeaderInfo(header_flag='ext', keys=['SHTSTAT', 'SHTOPEN1', 'SHTCLOS0', 'SHTCLOS1', 'EXPTIME'], values=[
False, self.h_ext['SHTOPEN0'], self.h_ext['SHTOPEN0'], self.h_ext['SHTOPEN0'], 0.0])
# renew header info
datetime_obs = datetime.utcfromtimestamp(pointing.timestamp)
datetime_obs = datetime_obs.replace(tzinfo=timezone.utc)
t_obs = Time(datetime_obs)
##ccd刷新2s,等待0.5s,开灯后等待0.5s,开始曝光
# ccd刷新2s,等待0.5s,开灯后等待0.5s,开始曝光
t_obs_renew = Time(t_obs.mjd - 2. / 86400., format="mjd")
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]])
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]])
gains1 = list(chip.gain_channel[0:8])
gains2 = list(chip.gain_channel[8:])
gains2.reverse()
gains = np.append(gains1,gains2)
self.updateHeaderInfo(header_flag='ext', keys = ['GAIN01','GAIN02','GAIN03','GAIN04','GAIN05','GAIN06','GAIN07','GAIN08','GAIN09','GAIN10','GAIN11','GAIN12','GAIN13','GAIN14','GAIN15','GAIN16'], values = gains)
gains = np.append(gains1, gains2)
self.updateHeaderInfo(header_flag='ext', keys=['GAIN01', 'GAIN02', 'GAIN03', 'GAIN04', 'GAIN05', 'GAIN06', 'GAIN07',
'GAIN08', 'GAIN09', 'GAIN10', 'GAIN11', 'GAIN12', 'GAIN13', 'GAIN14', 'GAIN15', 'GAIN16'], values=gains)
if obs_param["format_output"] == True:
self.chip_output.Log_info(" Apply 1*16 format")
......@@ -73,20 +83,21 @@ def quantization_and_output(self, chip, filt, tel, pointing, catalog, obs_param)
chip.img.replaceNegative(replace_value=0)
chip.img.quantize()
chip.img = galsim.Image(chip.img.array, dtype=np.uint16)
fname = os.path.join(self.chip_output.subdir, self.h_prim['FILENAME'] + '.fits')
fname = os.path.join(self.chip_output.subdir,
self.h_prim['FILENAME'] + '.fits')
f_name_size = 68
if(len(self.h_prim['FILENAME'])>f_name_size):
self.updateHeaderInfo(header_flag='prim', keys = ['FILENAME'], values = [self.h_prim['FILENAME'][0:f_name_size]])
if (len(self.h_prim['FILENAME']) > f_name_size):
self.updateHeaderInfo(header_flag='prim', keys=['FILENAME'], values=[
self.h_prim['FILENAME'][0:f_name_size]])
hdu1 = fits.PrimaryHDU(header=self.h_prim)
self.updateHeaderInfo(header_flag='ext', keys = ['DATASECT'], values = [str(chip.img.array.shape[1]) + 'x' + str(chip.img.array.shape[0])])
self.updateHeaderInfo(header_flag='ext', keys=['DATASECT'], values=[
str(chip.img.array.shape[1]) + 'x' + str(chip.img.array.shape[0])])
hdu2 = fits.ImageHDU(chip.img.array, header=self.h_ext)
hdu2.header.comments["XTENSION"] = "image extension"
hdu = fits.HDUList([hdu1, hdu2])
hdu[0].add_datasum(when='data unit checksum')
hdu[0].add_checksum(when='HDU checksum', override_datasum=True)
......
from ObservationSim.MockObject.SpecDisperser import SpecDisperser
from ObservationSim.MockObject.SpecDisperser import rotate90
from observation_sim.mock_objects.SpecDisperser import SpecDisperser
from observation_sim.mock_objects.SpecDisperser import rotate90
import galsim
import numpy as np
......@@ -20,10 +20,10 @@ except ImportError:
import importlib_resources as pkg_resources
###calculate sky map by sky SED
# calculate sky map by sky SED
def calculateSkyMap_split_g(skyMap=None, blueLimit=4200, redLimit=6500, skyfn='sky_emiss_hubble_50_50_A.dat', conf=[''], pixelSize=0.074, isAlongY=0,
split_pos=3685, flat_cube = None, zoldial_spec = None):
split_pos=3685, flat_cube=None, zoldial_spec=None):
# skyMap = np.ones([yLen, xLen], dtype='float32')
#
# if isAlongY == 1:
......@@ -45,19 +45,21 @@ def calculateSkyMap_split_g(skyMap=None, blueLimit=4200, redLimit=6500, skyfn='s
fImg = galsim.Image(fimg)
try:
with pkg_resources.files('ObservationSim.Straylight.data.sky').joinpath(skyfn) as data_path:
with pkg_resources.files('observation_sim.sky_background.data.sky').joinpath(skyfn) as data_path:
skySpec = np.loadtxt(data_path)
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.data.sky', skyfn) as data_path:
with pkg_resources.path('observation_sim.sky_background.data.sky', skyfn) as data_path:
skySpec = np.loadtxt(data_path)
# skySpec = np.loadtxt(skyfn)
spec = Table(np.array([skySpec[:, 0], skySpec[:, 1]]).T, names=('WAVELENGTH', 'FLUX'))
spec = Table(np.array([skySpec[:, 0], skySpec[:, 1]]
).T, names=('WAVELENGTH', 'FLUX'))
if zoldial_spec is not None:
deltL = 0.5
lamb = np.arange(2000, 11000, deltL)
speci = interpolate.interp1d(zoldial_spec['WAVELENGTH'], zoldial_spec['FLUX'])
speci = interpolate.interp1d(
zoldial_spec['WAVELENGTH'], zoldial_spec['FLUX'])
y = speci(lamb)
# erg/s/cm2/A --> photo/s/m2/A
......@@ -65,7 +67,7 @@ def calculateSkyMap_split_g(skyMap=None, blueLimit=4200, redLimit=6500, skyfn='s
spec = Table(np.array([lamb, s_flux]).T, names=('WAVELENGTH', 'FLUX'))
if isAlongY == 0:
directParm = 0
if isAlongY ==1:
if isAlongY == 1:
directParm = 1
if split_pos >= skyImg.array.shape[directParm]:
......@@ -90,25 +92,26 @@ def calculateSkyMap_split_g(skyMap=None, blueLimit=4200, redLimit=6500, skyfn='s
sub_x_end_arr = sub_x_start_arr + delt_x
sub_x_end_arr[-1] = min(sub_x_end_arr[-1], x_len)
for i,k1 in enumerate(sub_y_start_arr):
for i, k1 in enumerate(sub_y_start_arr):
sub_y_s = k1
sub_y_e = sub_y_end_arr[i]
sub_y_center = (sub_y_s+sub_y_e)/2.
for j,k2 in enumerate(sub_x_start_arr):
for j, k2 in enumerate(sub_x_start_arr):
sub_x_s = k2
sub_x_e = sub_x_end_arr[j]
skyImg_sub = galsim.Image(skyImg.array[sub_y_s:sub_y_e, sub_x_s:sub_x_e])
skyImg_sub = galsim.Image(
skyImg.array[sub_y_s:sub_y_e, sub_x_s:sub_x_e])
origin_sub = [sub_y_s, sub_x_s]
sub_x_center = (sub_x_s + sub_x_e) / 2.
sdp = SpecDisperser(orig_img=skyImg_sub, xcenter=sub_x_center, ycenter=sub_y_center, origin=origin_sub,
tar_spec=spec,
band_start=tbstart, band_end=tbend,
conf=conf2,
flat_cube=flat_cube, ignoreBeam=['D','E'])
tar_spec=spec,
band_start=tbstart, band_end=tbend,
conf=conf2,
flat_cube=flat_cube, ignoreBeam=['D', 'E'])
spec_orders = sdp.compute_spec_orders()
......@@ -141,9 +144,7 @@ def calculateSkyMap_split_g(skyMap=None, blueLimit=4200, redLimit=6500, skyfn='s
# if bounds.area() == 0:
# continue
# fImg[bounds] = fImg[bounds] + ssImg[bounds]
else:
# skyImg1 = galsim.Image(skyImg.array[:, 0:split_pos])
......@@ -165,32 +166,33 @@ def calculateSkyMap_split_g(skyMap=None, blueLimit=4200, redLimit=6500, skyfn='s
sub_y_start_arr = np.arange(0, y_len, delt_y)
sub_y_end_arr = sub_y_start_arr + delt_y
sub_y_end_arr[-1] = min(sub_y_end_arr[-1], y_len)
delt_x = split_pos-0
sub_x_start_arr = np.arange(0, split_pos, delt_x)
sub_x_end_arr = sub_x_start_arr + delt_x
sub_x_end_arr[-1] = min(sub_x_end_arr[-1], split_pos)
for i,k1 in enumerate(sub_y_start_arr):
for i, k1 in enumerate(sub_y_start_arr):
sub_y_s = k1
sub_y_e = sub_y_end_arr[i]
sub_y_center = (sub_y_s+sub_y_e)/2.
for j,k2 in enumerate(sub_x_start_arr):
for j, k2 in enumerate(sub_x_start_arr):
sub_x_s = k2
sub_x_e = sub_x_end_arr[j]
# print(i,j,sub_y_s, sub_y_e,sub_x_s,sub_x_e)
T1 = time.time()
skyImg_sub = galsim.Image(skyImg.array[sub_y_s:sub_y_e, sub_x_s:sub_x_e])
skyImg_sub = galsim.Image(
skyImg.array[sub_y_s:sub_y_e, sub_x_s:sub_x_e])
origin_sub = [sub_y_s, sub_x_s]
sub_x_center = (sub_x_s + sub_x_e) / 2.
sdp = SpecDisperser(orig_img=skyImg_sub, xcenter=sub_x_center, ycenter=sub_y_center, origin=origin_sub,
tar_spec=spec,
band_start=tbstart, band_end=tbend,
conf=conf1,
flat_cube=flat_cube)
tar_spec=spec,
band_start=tbstart, band_end=tbend,
conf=conf1,
flat_cube=flat_cube)
spec_orders = sdp.compute_spec_orders()
......@@ -204,10 +206,10 @@ def calculateSkyMap_split_g(skyMap=None, blueLimit=4200, redLimit=6500, skyfn='s
if bounds.area() == 0:
continue
fImg[bounds] = fImg[bounds] + ssImg[bounds]
T2 = time.time()
print('time: %s ms'% ((T2 - T1)*1000))
print('time: %s ms' % ((T2 - T1)*1000))
delt_x = x_len-split_pos
sub_x_start_arr = np.arange(split_pos, x_len, delt_x)
......@@ -224,18 +226,19 @@ def calculateSkyMap_split_g(skyMap=None, blueLimit=4200, redLimit=6500, skyfn='s
sub_x_s = k2
sub_x_e = sub_x_end_arr[j]
# print(i,j,sub_y_s, sub_y_e,sub_x_s,sub_x_e)
T1 = time.time()
skyImg_sub = galsim.Image(skyImg.array[sub_y_s:sub_y_e, sub_x_s:sub_x_e])
skyImg_sub = galsim.Image(
skyImg.array[sub_y_s:sub_y_e, sub_x_s:sub_x_e])
origin_sub = [sub_y_s, sub_x_s]
sub_x_center = (sub_x_s + sub_x_e) / 2.
sdp = SpecDisperser(orig_img=skyImg_sub, xcenter=sub_x_center, ycenter=sub_y_center, origin=origin_sub,
tar_spec=spec,
band_start=tbstart, band_end=tbend,
conf=conf2,
flat_cube=flat_cube)
tar_spec=spec,
band_start=tbstart, band_end=tbend,
conf=conf2,
flat_cube=flat_cube)
spec_orders = sdp.compute_spec_orders()
......@@ -251,17 +254,19 @@ def calculateSkyMap_split_g(skyMap=None, blueLimit=4200, redLimit=6500, skyfn='s
fImg[bounds] = fImg[bounds] + ssImg[bounds]
T2 = time.time()
print('time: %s ms'% ((T2 - T1)*1000))
print('time: %s ms' % ((T2 - T1)*1000))
if isAlongY == 1:
fimg, tmx, tmy = rotate90(array_orig=fImg.array, xc=0, yc=0, isClockwise=0)
fimg, tmx, tmy = rotate90(
array_orig=fImg.array, xc=0, yc=0, isClockwise=0)
else:
fimg = fImg.array
fimg = fimg * pixelSize * pixelSize
return fimg
def calculateSkyMap(xLen=9232, yLen=9126, blueLimit=4200, redLimit=6500,
skyfn='sky_emiss_hubble_50_50_A.dat', conf='', pixelSize=0.074, isAlongY=0):
skyMap = np.ones([yLen, xLen], dtype='float32')
......@@ -277,14 +282,15 @@ def calculateSkyMap(xLen=9232, yLen=9126, blueLimit=4200, redLimit=6500,
fimg = np.zeros_like(skyMap)
fImg = galsim.Image(fimg)
try:
with pkg_resources.files('ObservationSim.Straylight.data.sky').joinpath(skyfn) as data_path:
with pkg_resources.files('observation_sim.sky_background.data.sky').joinpath(skyfn) as data_path:
skySpec = np.loadtxt(data_path)
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.data.sky', skyfn) as data_path:
with pkg_resources.path('observation_sim.sky_background.data.sky', skyfn) as data_path:
skySpec = np.loadtxt(data_path)
# skySpec = np.loadtxt(skyfn)
spec = Table(np.array([skySpec[:, 0], skySpec[:, 1]]).T, names=('WAVELENGTH', 'FLUX'))
spec = Table(np.array([skySpec[:, 0], skySpec[:, 1]]
).T, names=('WAVELENGTH', 'FLUX'))
sdp = SpecDisperser(orig_img=skyImg, xcenter=skyImg.center.x, ycenter=skyImg.center.y, origin=[1, 1],
tar_spec=spec,
......@@ -303,10 +309,11 @@ def calculateSkyMap(xLen=9232, yLen=9126, blueLimit=4200, redLimit=6500,
fImg[bounds] = fImg[bounds] + ssImg[bounds]
if isAlongY == 1:
fimg, tmx, tmy = rotate90(array_orig=fImg.array, xc=0, yc=0, isClockwise=0)
fimg, tmx, tmy = rotate90(
array_orig=fImg.array, xc=0, yc=0, isClockwise=0)
else:
fimg = fImg.array
fimg = fimg * pixelSize * pixelSize
return fimg
......@@ -15,270 +15,291 @@ except ImportError:
# Try backported to PY<37 'importlib_resources'
import importlib_resources as pkg_resources
filterPivotWave = {'nuv':2875.5,'u':3629.6,'g':4808.4,'r':6178.2, 'i':7609.0, 'z':9012.9,'y':9627.9}
filterIndex = {'nuv':0,'u':1,'g':2,'r':3, 'i':4, 'z':5,'y':6}
filterCCD = {'nuv':'UV0','u':'UV0','g':'Astro_MB','r':'Astro_MB', 'i':'Basic_NIR', 'z':'Basic_NIR','y':'Basic_NIR'}
bandRange = {'nuv':[2504.0,3230.0],'u':[3190.0,4039.0],'g':[3989.0,5498.0],'r':[5438.0,6956.0], 'i':[6886.0,8469.0], 'z':[8379.0,10855.0],'y':[9217.0, 10900.0], 'GU':[2550, 4000],'GV':[4000, 6200],'GI':[6200,10000]}
filterPivotWave = {'nuv': 2875.5, 'u': 3629.6, 'g': 4808.4,
'r': 6178.2, 'i': 7609.0, 'z': 9012.9, 'y': 9627.9}
filterIndex = {'nuv': 0, 'u': 1, 'g': 2, 'r': 3, 'i': 4, 'z': 5, 'y': 6}
filterCCD = {'nuv': 'UV0', 'u': 'UV0', 'g': 'Astro_MB',
'r': 'Astro_MB', 'i': 'Basic_NIR', 'z': 'Basic_NIR', 'y': 'Basic_NIR'}
bandRange = {'nuv': [2504.0, 3230.0], 'u': [3190.0, 4039.0], 'g': [3989.0, 5498.0], 'r': [5438.0, 6956.0], 'i': [
6886.0, 8469.0], 'z': [8379.0, 10855.0], 'y': [9217.0, 10900.0], 'GU': [2550, 4000], 'GV': [4000, 6200], 'GI': [6200, 10000]}
# Instrument_dir = '/Users/zhangxin/Work/SlitlessSim/CSST_SIM/CSST_C6/straylight/straylight/Instrument/'
SpecOrder = ['-2','-1','0','1','2']
SpecOrder = ['-2', '-1', '0', '1', '2']
filterMirrorEff = {'nuv': 0.54, 'u': 0.68, 'g': 0.8,
'r': 0.8, 'i': 0.8, 'z': 0.8, 'y': 0.8}
filterMirrorEff = {'nuv':0.54,'u':0.68,'g':0.8,'r':0.8, 'i':0.8, 'z':0.8,'y':0.8}
def transRaDec2D(ra, dec):
x1 = np.cos(dec / 57.2957795) * np.cos(ra / 57.2957795);
y1 = np.cos(dec / 57.2957795) * np.sin(ra / 57.2957795);
z1 = np.sin(dec / 57.2957795);
x1 = np.cos(dec / 57.2957795) * np.cos(ra / 57.2957795)
y1 = np.cos(dec / 57.2957795) * np.sin(ra / 57.2957795)
z1 = np.sin(dec / 57.2957795)
return np.array([x1, y1, z1])
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 calculateAnglePwithEarth(sat = np.array([0,0,0]), pointing = np.array([0,0,0]), sun = np.array([0,0,0])):
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 calculateAnglePwithEarth(sat=np.array([0, 0, 0]), pointing=np.array([0, 0, 0]), sun=np.array([0, 0, 0])):
modSat = np.sqrt(sat[0]*sat[0] + sat[1]*sat[1]+sat[2]*sat[2])
modPoint = np.sqrt(pointing[0]*pointing[0] + pointing[1]*pointing[1] + pointing[2]*pointing[2])
withLocalZenithAngle = (pointing[0] * sat[0] + pointing[1] * sat[1] + pointing[2] * sat[2]) / (modPoint*modSat)
modPoint = np.sqrt(pointing[0]*pointing[0] +
pointing[1]*pointing[1] + pointing[2]*pointing[2])
withLocalZenithAngle = (
pointing[0] * sat[0] + pointing[1] * sat[1] + pointing[2] * sat[2]) / (modPoint*modSat)
innerM_sat_sun = sat[0] * sun[0] + sat[1] * sun[1] + sat[2] * sun[2]
cosAngle = innerM_sat_sun / (modSat * cons.au.value/1000)
isInSunSide = 1
if (cosAngle < -0.3385737): #cos109.79
isInSunSide = -1;
if (cosAngle < -0.3385737): # cos109.79
isInSunSide = -1
elif cosAngle >= -0.3385737 and cosAngle <= 0.3385737:
isInSunSide = 0;
isInSunSide = 0
return math.acos(withLocalZenithAngle)*180/math.pi,isInSunSide
return math.acos(withLocalZenithAngle)*180/math.pi, isInSunSide
# /**
# * *eCoor = ra, *eCoor+1 = dec
# */
def Cartesian2Equatorial(carCoor = np.array([0,0,0])):
def Cartesian2Equatorial(carCoor=np.array([0, 0, 0])):
eCoor = np.zeros(2)
if (carCoor[0] > 0 and carCoor[1] >= 0):
eCoor[0] = math.atan(carCoor[1] / carCoor[0]) * 360 / (2 * math.pi)
elif (carCoor[0] < 0):
eCoor[0] = (math.atan(carCoor[1] / carCoor[0]) + math.pi) * 360 / (2 * math.pi)
eCoor[0] = (math.atan(carCoor[1] / carCoor[0]) +
math.pi) * 360 / (2 * math.pi)
elif (carCoor[0] > 0 and carCoor[1] < 0):
eCoor[0] = (math.atan(carCoor[1] / carCoor[0]) + 2 * math.pi) * 360 / (2 * math.pi)
eCoor[0] = (math.atan(carCoor[1] / carCoor[0]) +
2 * math.pi) * 360 / (2 * math.pi)
elif (carCoor[0] == 0 and carCoor[1] < 0):
eCoor[0] = 270
elif (carCoor[0] == 0 and carCoor[1] > 0):
eCoor[0] = 90
eCoor[1] = math.atan(carCoor[2] / np.sqrt(carCoor[0] * carCoor[0] + carCoor[1] * carCoor[1])) * 360 / (2 * math.pi)
eCoor[1] = math.atan(carCoor[2] / np.sqrt(carCoor[0] *
carCoor[0] + carCoor[1] * carCoor[1])) * 360 / (2 * math.pi)
return eCoor
class Straylight(object):
def __init__(self, jtime = 2460843., sat_pos = np.array([0,0,0]), pointing_radec = np.array([0,0]), sun_pos = np.array([0,0,0])):
def __init__(self, jtime=2460843., sat_pos=np.array([0, 0, 0]), pointing_radec=np.array([0, 0]), sun_pos=np.array([0, 0, 0])):
self.jtime = jtime
self.sat = sat_pos
self.sun_pos = sun_pos
self.equator = coord.SkyCoord(pointing_radec[0]*u.degree, pointing_radec[1]*u.degree,frame='icrs')
self.equator = coord.SkyCoord(
pointing_radec[0]*u.degree, pointing_radec[1]*u.degree, frame='icrs')
self.ecliptic = self.equator.transform_to('barycentrictrueecliptic')
self.pointing = transRaDec2D(pointing_radec[0], pointing_radec[1])
platForm = sys.platform
if platForm == 'darwin':
try:
with pkg_resources.files('ObservationSim.Straylight.lib').joinpath('libstraylight.dylib') as dllFn:
with pkg_resources.files('observation_sim.sky_background.lib').joinpath('libstraylight.dylib') as dllFn:
self.slcdll = ctypes.CDLL(dllFn)
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.lib', 'libstraylight.dylib') as dllFn:
with pkg_resources.path('observation_sim.sky_background.lib', 'libstraylight.dylib') as dllFn:
self.slcdll = ctypes.CDLL(dllFn)
elif platForm == 'linux':
try:
with pkg_resources.files('ObservationSim.Straylight.lib').joinpath('libstraylight.so') as dllFn:
with pkg_resources.files('observation_sim.sky_background.lib').joinpath('libstraylight.so') as dllFn:
self.slcdll = ctypes.CDLL(dllFn)
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.lib', 'libstraylight.so') as dllFn:
with pkg_resources.path('observation_sim.sky_background.lib', 'libstraylight.so') as dllFn:
self.slcdll = ctypes.CDLL(dllFn)
# self.slcdll=ctypes.CDLL('./libstraylight.dylib')
self.slcdll.Calculate.argtypes = [ctypes.c_double, ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double), ctypes.POINTER(
ctypes.c_double),
ctypes.POINTER(ctypes.c_double), ctypes.c_char_p]
self.slcdll.PointSource.argtypes = [ctypes.c_double, ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double), ctypes.POINTER(
ctypes.c_double),
ctypes.POINTER(ctypes.c_double), ctypes.c_char_p]
self.slcdll.EarthShine.argtypes = [ctypes.c_double, ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double), ctypes.POINTER(
ctypes.c_double),
ctypes.POINTER(ctypes.c_double)]
self.slcdll.Zodiacal.argtypes = [ctypes.c_double, ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double)]
self.slcdll.ComposeY.argtypes = [ctypes.POINTER(ctypes.c_double), ctypes.POINTER(ctypes.c_double),
ctypes.POINTER(ctypes.c_double)]
self.slcdll.Init.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]
self.slcdll.Init.argtypes = [
ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]
try:
with pkg_resources.files('ObservationSim.Straylight.lib').joinpath('DE405') as tFn:
with pkg_resources.files('observation_sim.sky_background.lib').joinpath('DE405') as tFn:
self.deFn = tFn.as_uri()[7:]
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.lib', 'DE405') as tFn:
with pkg_resources.path('observation_sim.sky_background.lib', 'DE405') as tFn:
self.deFn = tFn.as_uri()[7:]
try:
with pkg_resources.files('ObservationSim.Straylight.lib').joinpath('PST') as tFn:
with pkg_resources.files('observation_sim.sky_background.lib').joinpath('PST') as tFn:
self.PSTFn = tFn.as_uri()[7:]
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.lib', 'PST') as tFn:
with pkg_resources.path('observation_sim.sky_background.lib', 'PST') as tFn:
self.PSTFn = tFn.as_uri()[7:]
try:
with pkg_resources.files('ObservationSim.Straylight.lib').joinpath('R') as tFn:
with pkg_resources.files('observation_sim.sky_background.lib').joinpath('R') as tFn:
self.RFn = tFn.as_uri()[7:]
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.lib', 'R') as tFn:
with pkg_resources.path('observation_sim.sky_background.lib', 'R') as tFn:
self.RFn = tFn.as_uri()[7:]
try:
with pkg_resources.files('ObservationSim.Straylight.lib').joinpath('Zodiacal') as tFn:
with pkg_resources.files('observation_sim.sky_background.lib').joinpath('Zodiacal') as tFn:
self.ZolFn = tFn.as_uri()[7:]
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.lib', 'Zodiacal') as tFn:
with pkg_resources.path('observation_sim.sky_background.lib', 'Zodiacal') as tFn:
self.ZolFn = tFn.as_uri()[7:]
try:
with pkg_resources.files('ObservationSim.Straylight.lib').joinpath('BrightGaia_with_csst_mag') as tFn:
with pkg_resources.files('observation_sim.sky_background.lib').joinpath('BrightGaia_with_csst_mag') as tFn:
self.brightStarTabFn = tFn.as_uri()[7:]
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.lib', 'BrightGaia_with_csst_mag') as tFn:
with pkg_resources.path('observation_sim.sky_background.lib', 'BrightGaia_with_csst_mag') as tFn:
self.brightStarTabFn = tFn.as_uri()[7:]
print(self.deFn)
self.slcdll.Init(str.encode(self.deFn), str.encode(self.PSTFn), str.encode(self.RFn), str.encode(self.ZolFn))
self.slcdll.Init(str.encode(self.deFn), str.encode(
self.PSTFn), str.encode(self.RFn), str.encode(self.ZolFn))
def getFilterAndCCD_Q(self, filter = 'i'):
def getFilterAndCCD_Q(self, filter='i'):
try:
with pkg_resources.files('ObservationSim.Instrument.data.ccd').joinpath(filterCCD[filter] + '.txt') as ccd_fn:
with pkg_resources.files('observation_sim.instruments.data.ccd').joinpath(filterCCD[filter] + '.txt') as ccd_fn:
q_ccd_f = np.loadtxt(ccd_fn)
except AttributeError:
with pkg_resources.path('ObservationSim.Instrument.data.ccd', filterCCD[filter] + '.txt') as ccd_fn:
with pkg_resources.path('observation_sim.instruments.data.ccd', filterCCD[filter] + '.txt') as ccd_fn:
q_ccd_f = np.loadtxt(ccd_fn)
try:
with pkg_resources.files('ObservationSim.Instrument.data.filters').joinpath(filter + '.txt') as filter_fn:
with pkg_resources.files('observation_sim.instruments.data.filters').joinpath(filter + '.txt') as filter_fn:
q_fil_f = np.loadtxt(filter_fn)
except AttributeError:
with pkg_resources.path('ObservationSim.Instrument.data.filters', filter + '.txt') as filter_fn:
with pkg_resources.path('observation_sim.instruments.data.filters', filter + '.txt') as filter_fn:
q_fil_f = np.loadtxt(filter_fn)
band_s = 2000
band_e = 11000
q_ccd_f[:,0] = q_ccd_f[:,0]*10
q_ccd = np.zeros([q_ccd_f.shape[0]+2,q_ccd_f.shape[1]])
q_ccd[1:-1,:] = q_ccd_f
q_ccd[0] = [band_s,0]
q_ccd[-1] = [band_e,0]
q_fil = np.zeros([q_fil_f.shape[0]+2,q_fil_f.shape[1]])
q_fil[1:-1,:] = q_fil_f
q_fil[0] = [band_s,0]
q_fil[-1] = [band_e,0]
q_fil_i = interpolate.interp1d(q_fil[:,0], q_fil[:,1])
q_ccd_i = interpolate.interp1d(q_ccd[:,0], q_ccd[:,1])
bands = np.arange(bandRange[filter][0], bandRange[filter][1],0.5)
q_ccd_f[:, 0] = q_ccd_f[:, 0]*10
q_ccd = np.zeros([q_ccd_f.shape[0]+2, q_ccd_f.shape[1]])
q_ccd[1:-1, :] = q_ccd_f
q_ccd[0] = [band_s, 0]
q_ccd[-1] = [band_e, 0]
q_fil = np.zeros([q_fil_f.shape[0]+2, q_fil_f.shape[1]])
q_fil[1:-1, :] = q_fil_f
q_fil[0] = [band_s, 0]
q_fil[-1] = [band_e, 0]
q_fil_i = interpolate.interp1d(q_fil[:, 0], q_fil[:, 1])
q_ccd_i = interpolate.interp1d(q_ccd[:, 0], q_ccd[:, 1])
bands = np.arange(bandRange[filter][0], bandRange[filter][1], 0.5)
q_ccd_fil = q_fil_i(bands)*q_ccd_i(bands)
return np.trapz(q_ccd_fil, bands)/(bandRange[filter][1]-bandRange[filter][0])
def calculateEarthShineFilter(self, filter = 'i', pixel_size_phy = 10 ):
def calculateEarthShineFilter(self, filter='i', pixel_size_phy=10):
sat = (ctypes.c_double*3)()
sat[:] = self.sat
ob = (ctypes.c_double*3)()
ob[:]=self.pointing
ob[:] = self.pointing
py1 = (ctypes.c_double*3)()
py2 = (ctypes.c_double*3)()
self.slcdll.ComposeY(ob,py1,py2)
self.slcdll.ComposeY(ob, py1, py2)
earth_e1 = (ctypes.c_double*7)()
self.slcdll.EarthShine(self.jtime,sat,ob,py1,earth_e1)
self.slcdll.EarthShine(self.jtime, sat, ob, py1, earth_e1)
earth_e2 = (ctypes.c_double*7)()
self.slcdll.EarthShine(self.jtime,sat,ob,py2,earth_e2)
self.slcdll.EarthShine(self.jtime, sat, ob, py2, earth_e2)
band_earth_e1 = earth_e1[:][filterIndex[filter]]
band_earth_e2 = earth_e2[:][filterIndex[filter]]
q=self.getFilterAndCCD_Q(filter=filter)
q = self.getFilterAndCCD_Q(filter=filter)
p_lambda = filterPivotWave[filter]
c = cons.c.value
h = cons.h.value
pix_earth_e1 = band_earth_e1/(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
pix_earth_e2 = band_earth_e2/(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
pix_earth_e1 = band_earth_e1 / \
(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
pix_earth_e2 = band_earth_e2 / \
(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
if pix_earth_e1< pix_earth_e2:
if pix_earth_e1 < pix_earth_e2:
return pix_earth_e1, py1[:]
else:
return pix_earth_e2, py2[:]
"""
calculate zodiacal call c++ program, seems to have some problem
"""
def calculateZodiacalFilter1(self, filter = 'i', pixel_size_phy = 10 ):
def calculateZodiacalFilter1(self, filter='i', pixel_size_phy=10):
sat = (ctypes.c_double*3)()
sat[:] = self.sat
ob = (ctypes.c_double*3)()
ob[:]=self.pointing
ob[:] = self.pointing
zodical_e = (ctypes.c_double*7)()
self.slcdll.Zodiacal(self.jtime,ob,zodical_e)
self.slcdll.Zodiacal(self.jtime, ob, zodical_e)
ob1 = (ctypes.c_double*2)()
ob1[:] = np.array([self.ecliptic.lon.value, self.ecliptic.lat.value])
zodical_e1 = (ctypes.c_double*7)()
self.slcdll.Zodiacal1(ob1,zodical_e1)
self.slcdll.Zodiacal1(ob1, zodical_e1)
band_zodical_e = zodical_e[:][filterIndex[filter]]
q=self.getFilterAndCCD_Q(filter=filter)
q = self.getFilterAndCCD_Q(filter=filter)
p_lambda = filterPivotWave[filter]
c = cons.c.value
h = cons.h.value
pix_zodical_e = band_zodical_e/(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
pix_zodical_e = band_zodical_e / \
(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
return pix_zodical_e, band_zodical_e
"""
calculate zodiacal use python
"""
def calculateZodiacalFilter2(self,filter = 'i', aper = 2, pixelsize = 0.074, sun_pos = np.array([0,0,0])):
spec, v_mag = self.calculateZodicalSpec(longitude = self.ecliptic.lon.value, latitude = self.ecliptic.lat.value, sun_pos = sun_pos)
def calculateZodiacalFilter2(self, filter='i', aper=2, pixelsize=0.074, sun_pos=np.array([0, 0, 0])):
spec, v_mag = self.calculateZodicalSpec(
longitude=self.ecliptic.lon.value, latitude=self.ecliptic.lat.value, sun_pos=sun_pos)
# spec = self.calculateZodicalSpec(longitude = lon, latitude = lat)
try:
with pkg_resources.files('ObservationSim.Instrument.data.throughputs').joinpath(filter + '_throughput.txt') as throughputFn:
with pkg_resources.files('observation_sim.instruments.data.throughputs').joinpath(filter + '_throughput.txt') as throughputFn:
throughput = np.loadtxt(throughputFn)
except AttributeError:
with pkg_resources.path('ObservationSim.Instrument.data.throughputs', filter + '_throughput.txt') as throughputFn:
with pkg_resources.path('observation_sim.instruments.data.throughputs', filter + '_throughput.txt') as throughputFn:
throughput = np.loadtxt(throughputFn)
deltL = 0.5
......@@ -294,61 +315,60 @@ class Straylight(object):
throughput_ = throughput_i(lamb)
sky_pix = np.trapz(flux*throughput_, lamb) * math.pi * aper*aper/4 * pixelsize * pixelsize
sky_pix = np.trapz(flux*throughput_, lamb) * \
math.pi * aper*aper/4 * pixelsize * pixelsize
# sky_pix_e = np.trapz(y, lamb) * math.pi * aper*aper/4 * pixelsize * pixelsize/(10*10*1e-6*1e-6)*1e-7*1e4
return sky_pix, v_mag#, sky_pix_e
def calculateStarLightFilter(self, filter = 'i', pointYaxis = np.array([1,1,1]), pixel_size_phy = 10 ):
return sky_pix, v_mag # , sky_pix_e
def calculateStarLightFilter(self, filter='i', pointYaxis=np.array([1, 1, 1]), pixel_size_phy=10):
sat = (ctypes.c_double*3)()
sat[:] = self.sat
ob = (ctypes.c_double*3)()
ob[:]=self.pointing
ob[:] = self.pointing
py = (ctypes.c_double*3)()
py[:] = pointYaxis
q=self.getFilterAndCCD_Q(filter=filter)
q = self.getFilterAndCCD_Q(filter=filter)
p_lambda = filterPivotWave[filter]
c = cons.c.value
h = cons.h.value
star_e1 = (ctypes.c_double*7)()
self.slcdll.PointSource(self.jtime,sat,ob,py,star_e1, str.encode(self.brightStarTabFn))
self.slcdll.PointSource(self.jtime, sat, ob, py,
star_e1, str.encode(self.brightStarTabFn))
band_star_e1 = star_e1[:][filterIndex[filter]]
pix_star_e1 = band_star_e1/(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
pix_star_e1 = band_star_e1 / \
(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
return pix_star_e1
def calculateEarthshineGrating(self, grating = 'GU', pixel_size_phy = 10, normFilter = 'g', aper = 2, pixelsize = 0.074):
def calculateEarthshineGrating(self, grating='GU', pixel_size_phy=10, normFilter='g', aper=2, pixelsize=0.074):
sat = (ctypes.c_double*3)()
sat[:] = self.sat
ob = (ctypes.c_double*3)()
ob[:]=self.pointing
ob[:] = self.pointing
py1 = (ctypes.c_double*3)()
py2 = (ctypes.c_double*3)()
self.slcdll.ComposeY(ob,py1,py2)
self.slcdll.ComposeY(ob, py1, py2)
earth_e1 = (ctypes.c_double*7)()
self.slcdll.EarthShine(self.jtime,sat,ob,py1,earth_e1)
self.slcdll.EarthShine(self.jtime, sat, ob, py1, earth_e1)
earth_e2 = (ctypes.c_double*7)()
self.slcdll.EarthShine(self.jtime,sat,ob,py2,earth_e2)
self.slcdll.EarthShine(self.jtime, sat, ob, py2, earth_e2)
# zodical_e = (ctypes.c_double*7)()
# self.slcdll.Zodiacal(self.jtime,ob,zodical_e)
band_earth_e1 = earth_e1[:][filterIndex[normFilter]]
band_earth_e2 = earth_e2[:][filterIndex[normFilter]]
band_earth_e = band_earth_e2
py = py2[:]
if band_earth_e1<band_earth_e2:
if band_earth_e1 < band_earth_e2:
band_earth_e = band_earth_e1
py = py1[:]
# band_earth_e = np.min([band_earth_e1, band_earth_e2])
......@@ -356,18 +376,20 @@ class Straylight(object):
# band_earth_e1 = 0
# band_earth_e2 = 0
# band_zodical_e = zodical_e[:][filterIndex[normFilter]]
q=self.getFilterAndCCD_Q(filter=normFilter)
q = self.getFilterAndCCD_Q(filter=normFilter)
p_lambda = filterPivotWave[normFilter]
c = cons.c.value
h = cons.h.value
pix_earth_e = band_earth_e/(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
pix_earth_e = band_earth_e / \
(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
# pix_earth_e2 = band_earth_e2/(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
# pix_zodical_e = band_zodical_e/(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
# pix_earth_e = np.min([pix_earth_e1, pix_earth_e2])
earthshine_v, earthshine_spec = self.calculatEarthshineByHSTSpec(filter = normFilter, aper = aper, pixelsize = pixelsize)
earthshine_v, earthshine_spec = self.calculatEarthshineByHSTSpec(
filter=normFilter, aper=aper, pixelsize=pixelsize)
lamb_earth = earthshine_spec['WAVELENGTH']
flux_earth = earthshine_spec['FLUX']*pix_earth_e/earthshine_v
......@@ -375,30 +397,31 @@ class Straylight(object):
earth_v_grating = 0
for s_order in SpecOrder:
try:
with pkg_resources.files('ObservationSim.Instrument.data.sls_conf').joinpath(
with pkg_resources.files('observation_sim.instruments.data.sls_conf').joinpath(
grating + '.Throughput.' + s_order + 'st.fits') as thpFn:
thp_ = Table.read(thpFn)
except AttributeError:
with pkg_resources.path('ObservationSim.Instrument.data.sls_conf',
with pkg_resources.path('observation_sim.instruments.data.sls_conf',
grating + '.Throughput.' + s_order + 'st.fits') as thpFn:
thp_ = Table.read(thpFn)
thpFn_i = interpolate.interp1d(thp_['WAVELENGTH'], thp_['SENSITIVITY'])
thpFn_i = interpolate.interp1d(
thp_['WAVELENGTH'], thp_['SENSITIVITY'])
thp = thpFn_i(lamb_earth)
beamsEarth = np.trapz(flux_earth*thp,lamb_earth)* math.pi*aper*aper/4 * pixelsize * pixelsize
beamsEarth = np.trapz(flux_earth*thp, lamb_earth) * \
math.pi*aper*aper/4 * pixelsize * pixelsize
earth_v_grating = earth_v_grating + beamsEarth
# print(beamsEarth)
# print(earthshine_v, pix_earth_e, earth_v_grating)
return earth_v_grating, py
def calculateStarLightGrating(self, grating = 'GU', pointYaxis = np.array([1,1,1]), pixel_size_phy = 10 ):
def calculateStarLightGrating(self, grating='GU', pointYaxis=np.array([1, 1, 1]), pixel_size_phy=10):
sat = (ctypes.c_double*3)()
sat[:] = self.sat
ob = (ctypes.c_double*3)()
ob[:]=self.pointing
ob[:] = self.pointing
py = (ctypes.c_double*3)()
py[:] = pointYaxis
......@@ -407,9 +430,9 @@ class Straylight(object):
c = cons.c.value
h = cons.h.value
star_e1 = (ctypes.c_double*7)()
self.slcdll.PointSource(self.jtime,sat,ob,py,star_e1, str.encode(self.brightStarTabFn))
self.slcdll.PointSource(self.jtime, sat, ob, py,
star_e1, str.encode(self.brightStarTabFn))
filterPivotWaveList = np.zeros(7)
bandRangeList = np.zeros(7)
......@@ -420,54 +443,54 @@ class Straylight(object):
filterMirrorEffList[i] = filterMirrorEff[filterNameList[i]]
brange = bandRange[filterNameList[i]]
bandRangeList[i] = brange[1] - brange[0]
filterFlux_lamb = star_e1[:]/bandRangeList/filterMirrorEffList/(h*c/(filterPivotWaveList*1e-10))
filterFlux_lambi = interpolate.interp1d(filterPivotWaveList,filterFlux_lamb,fill_value="extrapolate")
filterFlux_lamb = star_e1[:]/bandRangeList / \
filterMirrorEffList/(h*c/(filterPivotWaveList*1e-10))
filterFlux_lambi = interpolate.interp1d(
filterPivotWaveList, filterFlux_lamb, fill_value="extrapolate")
lamb_g = np.arange(bandRange[grating][0], bandRange[grating][1],1)
lamb_g = np.arange(bandRange[grating][0], bandRange[grating][1], 1)
flux_g = filterFlux_lambi(lamb_g)
# flux_total_g = np.trapz(flux_g,lamb_g)
starLight_grating = 0
for s_order in SpecOrder:
try:
with pkg_resources.files('ObservationSim.Instrument.data.sls_conf').joinpath(
with pkg_resources.files('observation_sim.instruments.data.sls_conf').joinpath(
grating + '.Throughput.' + s_order + 'st.fits') as thpFn:
thp_ = Table.read(thpFn)
except AttributeError:
with pkg_resources.path('ObservationSim.Instrument.data.sls_conf',
with pkg_resources.path('observation_sim.instruments.data.sls_conf',
grating + '.Throughput.' + s_order + 'st.fits') as thpFn:
thp_ = Table.read(thpFn)
thpFn_i = interpolate.interp1d(thp_['WAVELENGTH'], thp_['SENSITIVITY'])
thpFn_i = interpolate.interp1d(
thp_['WAVELENGTH'], thp_['SENSITIVITY'])
thp = thpFn_i(lamb_g)
beamsZol = np.trapz(flux_g*thp,lamb_g)*pixel_size_phy*1e-6*pixel_size_phy*1e-6
beamsZol = np.trapz(flux_g*thp, lamb_g) * \
pixel_size_phy*1e-6*pixel_size_phy*1e-6
starLight_grating = starLight_grating + beamsZol
# print(beamsZol)
# band_star_e1 = star_e1[:][filterIndex[filter]]
# pix_star_e1 = band_star_e1/(h*c/(p_lambda*1e-10))*pixel_size_phy*1e-6*pixel_size_phy*1e-6*q
return starLight_grating
return starLight_grating
def calculatEarthshineByHSTSpec(self, filter = 'g', aper = 2, pixelsize = 0.074, s = 2000, e = 11000):
def calculatEarthshineByHSTSpec(self, filter='g', aper=2, pixelsize=0.074, s=2000, e=11000):
try:
with pkg_resources.files('ObservationSim.Straylight.data.sky').joinpath('earthShine.dat') as specFn:
with pkg_resources.files('observation_sim.sky_background.data.sky').joinpath('earthShine.dat') as specFn:
spec = np.loadtxt(specFn)
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.data.sky',
with pkg_resources.path('observation_sim.sky_background.data.sky',
'earthShine.dat') as specFn:
spec = np.loadtxt(specFn)
try:
with pkg_resources.files('ObservationSim.Instrument.data.throughputs').joinpath(filter + '_throughput.txt') as throughputFn:
with pkg_resources.files('observation_sim.instruments.data.throughputs').joinpath(filter + '_throughput.txt') as throughputFn:
throughput = np.loadtxt(throughputFn)
except AttributeError:
with pkg_resources.path('ObservationSim.Instrument.data.throughputs', filter + '_throughput.txt') as throughputFn:
with pkg_resources.path('observation_sim.instruments.data.throughputs', filter + '_throughput.txt') as throughputFn:
throughput = np.loadtxt(throughputFn)
deltL = 0.5
......@@ -482,7 +505,8 @@ class Straylight(object):
throughput_ = throughput_i(lamb)
sky_pix = np.trapz(flux*throughput_, lamb) * math.pi * aper*aper/4 * pixelsize * pixelsize
sky_pix = np.trapz(flux*throughput_, lamb) * \
math.pi * aper*aper/4 * pixelsize * pixelsize
lamb = np.arange(s, e, deltL)
speci = interpolate.interp1d(spec[:, 0], spec[:, 1])
......@@ -490,30 +514,31 @@ class Straylight(object):
# erg/s/cm2/A --> photo/s/m2/A
flux = y * lamb / (cons.h.value * cons.c.value) * 1e-13
return sky_pix, Table(np.array([lamb, flux]).T,names=('WAVELENGTH', 'FLUX'))
return sky_pix, Table(np.array([lamb, flux]).T, names=('WAVELENGTH', 'FLUX'))
def calculateZodicalSpec(self,longitude = 50, latitude = 60, sun_pos = np.array([0,0,0])):
def calculateZodicalSpec(self, longitude=50, latitude=60, sun_pos=np.array([0, 0, 0])):
from scipy.interpolate import interp2d
from scipy.interpolate import griddata
try:
with pkg_resources.files('ObservationSim.Straylight.data').joinpath('Zodiacal_map1.dat') as z_map_fn:
ZL = np.loadtxt(z_map_fn)
with pkg_resources.files('observation_sim.sky_background.data').joinpath('Zodiacal_map1.dat') as z_map_fn:
ZL = np.loadtxt(z_map_fn)
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.data',
with pkg_resources.path('observation_sim.sky_background.data',
'Zodiacal_map1.dat') as z_map_fn:
ZL = np.loadtxt(z_map_fn)
# zl_sh = ZL.shape
# x = np.arange(0,zl_sh[1],1)
# y = np.arange(0,zl_sh[0],1)
x = ZL[0,1:]
y = ZL[1:,0]
X,Y = np.meshgrid(x,y)
x = ZL[0, 1:]
y = ZL[1:, 0]
X, Y = np.meshgrid(x, y)
# f_sur = interp2d(X,Y,ZL,kind='linear')
sun_radec = Cartesian2Equatorial(sun_pos)
sun_eclip = coord.SkyCoord(sun_radec[0]*u.degree, sun_radec[1]*u.degree,frame='icrs')
sun_eclip = coord.SkyCoord(
sun_radec[0]*u.degree, sun_radec[1]*u.degree, frame='icrs')
sun_equtor = sun_eclip.transform_to('barycentrictrueecliptic')
longitude = longitude - (sun_equtor.lon*u.degree).value
......@@ -526,15 +551,16 @@ class Straylight(object):
latitude = np.abs(latitude)
lo = longitude
la = latitude
zl = griddata((X.flatten(),Y.flatten()),ZL[1:,1:].flatten(),(la,lo), method='cubic').min()
zl = griddata((X.flatten(), Y.flatten()),
ZL[1:, 1:].flatten(), (la, lo), method='cubic').min()
zl = zl*(math.pi*math.pi)/(180*180)/(3600*3600)*1e-4*1e7*1e-8*1e-4
# print(zl , '\n')
try:
with pkg_resources.files('ObservationSim.Straylight.data.sky').joinpath('zodiacal.dat') as zodical_fn:
with pkg_resources.files('observation_sim.sky_background.data.sky').joinpath('zodiacal.dat') as zodical_fn:
spec = np.loadtxt(zodical_fn)
except AttributeError:
with pkg_resources.path('ObservationSim.Straylight.data.sky',
with pkg_resources.path('observation_sim.sky_background.data.sky',
'zodiacal.dat') as zodical_fn:
spec = np.loadtxt(zodical_fn)
......@@ -545,29 +571,37 @@ class Straylight(object):
v_mag = np.log10(f_ration)*(-2.5)+22.1
# print("factor:", v_mag, lo, la)
return Table(np.array([spec[:,0], spec[:,1]*f_ration]).T,names=('WAVELENGTH', 'FLUX')), v_mag
def calculateStrayLightFilter(self, filter = 'i', pixel_size_phy = 10, pixel_scale = 0.074):
e1,py = self.calculateEarthShineFilter(filter = filter, pixel_size_phy = pixel_size_phy)
e2, _ = self.calculateZodiacalFilter2(filter = filter, sun_pos=self.sun_pos, pixelsize = pixel_scale)
e3 = self.calculateStarLightFilter(filter = filter,pointYaxis = py, pixel_size_phy = pixel_size_phy)
return Table(np.array([spec[:, 0], spec[:, 1]*f_ration]).T, names=('WAVELENGTH', 'FLUX')), v_mag
def calculateStrayLightFilter(self, filter='i', pixel_size_phy=10, pixel_scale=0.074):
e1, py = self.calculateEarthShineFilter(
filter=filter, pixel_size_phy=pixel_size_phy)
e2, _ = self.calculateZodiacalFilter2(
filter=filter, sun_pos=self.sun_pos, pixelsize=pixel_scale)
e3 = self.calculateStarLightFilter(
filter=filter, pointYaxis=py, pixel_size_phy=pixel_size_phy)
return e1+e2+e3
def calculateStrayLightGrating(self, grating = 'GI', pixel_size_phy = 10, normFilter_es = 'g'):
e1,py = self.calculateEarthshineGrating(grating = grating, pixel_size_phy = pixel_size_phy, normFilter = normFilter_es)
e2 = self.calculateStarLightGrating(grating = grating, pointYaxis = py)
spec, _ = self.calculateZodicalSpec(longitude = self.ecliptic.lon.value, latitude = self.ecliptic.lat.value, sun_pos = self.sun_pos)
def calculateStrayLightGrating(self, grating='GI', pixel_size_phy=10, normFilter_es='g'):
e1, py = self.calculateEarthshineGrating(
grating=grating, pixel_size_phy=pixel_size_phy, normFilter=normFilter_es)
e2 = self.calculateStarLightGrating(grating=grating, pointYaxis=py)
spec, _ = self.calculateZodicalSpec(
longitude=self.ecliptic.lon.value, latitude=self.ecliptic.lat.value, sun_pos=self.sun_pos)
return e1+e2, spec
def testZodiacal(lon = 285.04312526255366, lat = 30.):
c_eclip = coord.SkyCoord(lon*u.degree, lat*u.degree,frame='barycentrictrueecliptic')
def testZodiacal(lon=285.04312526255366, lat=30.):
c_eclip = coord.SkyCoord(lon*u.degree, lat*u.degree,
frame='barycentrictrueecliptic')
c_equtor = c_eclip.transform_to('icrs')
sl = Straylight(jtime = 2459767.00354975, sat = np.array([]), radec = np.array([(c_equtor.ra*u.degree).value, (c_equtor.dec*u.degree).value]))
e_zol, v_mag = sl.calculateZodiacalFilter2(filter = 'i', sun_pos=np.array([-3.70939436e+07, 1.35334903e+08, 5.86673104e+07]))
sl = Straylight(jtime=2459767.00354975, sat=np.array([]), radec=np.array(
[(c_equtor.ra*u.degree).value, (c_equtor.dec*u.degree).value]))
e_zol, v_mag = sl.calculateZodiacalFilter2(filter='i', sun_pos=np.array(
[-3.70939436e+07, 1.35334903e+08, 5.86673104e+07]))
print(e_zol)
# ju=2.4608437604166665e+06
......@@ -639,4 +673,3 @@ def testZodiacal(lon = 285.04312526255366, lat = 30.):
# print(e1+e2,e1_+e3+e4,e5,e6)
#
# # print(e1,e2,e3,e4)
Supports Markdown
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment