This notebook presents the merge of the various pristine catalogues to produce the HELP master catalogue on HDF-N.
from herschelhelp_internal import git_version
print("This notebook was run with herschelhelp_internal version: \n{}".format(git_version()))
%matplotlib inline
#%config InlineBackend.figure_format = 'svg'
import matplotlib.pyplot as plt
plt.rc('figure', figsize=(10, 6))
import os
import time
from astropy import units as u
from astropy.coordinates import SkyCoord
from astropy.table import Column, Table
import numpy as np
from pymoc import MOC
from herschelhelp_internal.masterlist import merge_catalogues, nb_merge_dist_plot, specz_merge
from herschelhelp_internal.utils import coords_to_hpidx, ebv, gen_help_id, inMoc
TMP_DIR = os.environ.get('TMP_DIR', "./data_tmp")
OUT_DIR = os.environ.get('OUT_DIR', "./data")
SUFFIX = os.environ.get('SUFFIX', time.strftime("_%Y%m%d"))
try:
os.makedirs(OUT_DIR)
except FileExistsError:
pass
#threed = Table.read("{}/CANDELS-3D-HST.fits".format(TMP_DIR)) # 1.1
#acs = Table.read("{}/ACS.fits".format(TMP_DIR)) # 1.2 GOODS-ACS
hawaii = Table.read("{}/Hawaii.fits".format(TMP_DIR)) # 1.3 Hawaii-HDFN
ultra = Table.read("{}/Ultradeep.fits".format(TMP_DIR)) # 1.4 Ultradeep_Ks_GOODS-N
ps1 = Table.read("{}/PS1.fits".format(TMP_DIR)) # 1.5 PanSTARRS
candels_gn = Table.read("{}/CANDELS-GOODS-N.fits".format(TMP_DIR)) # 1.6 CANDELS-GOODS-N
We first merge the optical catalogues and then add the infrared ones. We start with PanSTARRS because it coevrs the whole field.
At every step, we look at the distribution of the distances separating the sources from one catalogue to the other (within a maximum radius) to determine the best cross-matching radius.
master_catalogue = ps1
master_catalogue['ps1_ra'].name = 'ra'
master_catalogue['ps1_dec'].name = 'dec'
nb_merge_dist_plot(
SkyCoord(master_catalogue['ra'], master_catalogue['dec']),
SkyCoord(candels_gn['candels-gn_ra'], candels_gn['candels-gn_dec'])
)
# Given the graph above, we use 0.8 arc-second radius
master_catalogue = merge_catalogues(master_catalogue, candels_gn, "candels-gn_ra", "candels-gn_dec", radius=0.8*u.arcsec)
nb_merge_dist_plot(
SkyCoord(master_catalogue['ra'], master_catalogue['dec']),
SkyCoord(ultra['ultradeep_ra'], ultra['ultradeep_dec'])
)
# Given the graph above, we use 0.8 arc-second radius
master_catalogue = merge_catalogues(master_catalogue, ultra, "ultradeep_ra", "ultradeep_dec", radius=0.8*u.arcsec)
nb_merge_dist_plot(
SkyCoord(master_catalogue['ra'], master_catalogue['dec']),
SkyCoord(hawaii['hawaii_ra'], hawaii['hawaii_dec'])
)
# Given the graph above, we use 0.8 arc-second radius
master_catalogue = merge_catalogues(master_catalogue, hawaii, "hawaii_ra", "hawaii_dec", radius=0.8*u.arcsec)
When we merge the catalogues, astropy masks the non-existent values (e.g. when a row comes only from a catalogue and has no counterparts in the other, the columns from the latest are masked for that row). We indicate to use NaN for masked values for floats columns, False for flag columns and -1 for ID columns.
for col in master_catalogue.colnames:
if "m_" in col or "merr_" in col or "f_" in col or "ferr_" in col or "stellarity" in col:
master_catalogue[col] = master_catalogue[col].astype(float)
master_catalogue[col].fill_value = np.nan
elif "flag" in col:
master_catalogue[col].fill_value = 0
elif "id" in col:
master_catalogue[col].fill_value = -1
master_catalogue = master_catalogue.filled()
master_catalogue[:10].show_in_notebook()
Each pristine catalogue contains a flag indicating if the source was associated to a another nearby source that was removed during the cleaning process. We merge these flags in a single one.
flag_cleaned_columns = [column for column in master_catalogue.colnames
if 'flag_cleaned' in column]
flag_column = np.zeros(len(master_catalogue), dtype=bool)
for column in flag_cleaned_columns:
flag_column |= master_catalogue[column]
master_catalogue.add_column(Column(data=flag_column, name="flag_cleaned"))
master_catalogue.remove_columns(flag_cleaned_columns)
combining the flag_merged column which contains information regarding multiple associations
master_catalogue['flag_merged'].name = 'flag_merged_tmp'
flag_merged_columns = [column for column in master_catalogue.colnames
if 'flag_merged' in column]
flag_merged_column = np.zeros(len(master_catalogue), dtype=bool)
for column in flag_merged_columns:
flag_merged_column |= master_catalogue[column]
master_catalogue.add_column(Column(data=flag_merged_column, name="flag_merged"))
master_catalogue.remove_columns(flag_merged_columns)
Each pristine catalogue contains a flag indicating the probability of a source being a Gaia object (0: not a Gaia object, 1: possibly, 2: probably, 3: definitely). We merge these flags taking the highest value.
flag_gaia_columns = [column for column in master_catalogue.colnames
if 'flag_gaia' in column]
master_catalogue.add_column(Column(
data=np.max([master_catalogue[column] for column in flag_gaia_columns], axis=0),
name="flag_gaia"
))
master_catalogue.remove_columns(flag_gaia_columns)
Each prisitine catalogue may contain one or several stellarity columns indicating the probability (0 to 1) of each source being a star. We merge these columns taking the highest value. We keep trace of the origin of the stellarity.
stellarity_columns = [column for column in master_catalogue.colnames
if 'stellarity' in column]
print(", ".join(stellarity_columns))
# We create an masked array with all the stellarities and get the maximum value, as well as its
# origin. Some sources may not have an associated stellarity.
stellarity_array = np.array([master_catalogue[column] for column in stellarity_columns])
stellarity_array = np.ma.masked_array(stellarity_array, np.isnan(stellarity_array))
max_stellarity = np.max(stellarity_array, axis=0)
max_stellarity.fill_value = np.nan
no_stellarity_mask = max_stellarity.mask
master_catalogue.add_column(Column(data=max_stellarity.filled(), name="stellarity"))
stellarity_origin = np.full(len(master_catalogue), "NO_INFORMATION", dtype="S20")
stellarity_origin[~no_stellarity_mask] = np.array(stellarity_columns)[np.argmax(stellarity_array, axis=0)[~no_stellarity_mask]]
master_catalogue.add_column(Column(data=stellarity_origin, name="stellarity_origin"))
master_catalogue.remove_columns(stellarity_columns)
master_catalogue.add_column(
ebv(master_catalogue['ra'], master_catalogue['dec'])
)
master_catalogue.add_column(Column(gen_help_id(master_catalogue['ra'], master_catalogue['dec']),
name="help_id"))
master_catalogue.add_column(Column(np.full(len(master_catalogue), "HDF-N", dtype='<U18'),
name="field"))
# Check that the HELP Ids are unique
if len(master_catalogue) != len(np.unique(master_catalogue['help_id'])):
print("The HELP IDs are not unique!!!")
else:
print("OK!")
#specz = Table.read("../../dmu23/dmu23_HDF-N/data/HDF-N-specz-v2.8.fits")
#specz['objid'].name = 'specz_id'
#nb_merge_dist_plot(
# SkyCoord(master_catalogue['ra'], master_catalogue['dec']),
# SkyCoord(specz['ra'] * u.deg, specz['dec'] * u.deg)
#)
#master_catalogue = specz_merge(master_catalogue, specz, radius=1. * u.arcsec)
We have to choose between the various HST catalogues which may contains different objects depending on the prior catalogue. The CANDELS-GOODS-N catalogue is taken as a base and any missing wircam or IRAC fluxes are taken from the Ultradeep Ks selected catalogues
bands = [
['candels-wircam_k', 'ultradeep-wircam_k', 'wircam_k'],
['candels-irac_i1', 'ultradeep-irac_i1', 'irac_i1'],
['candels-irac_i2', 'ultradeep-irac_i2', 'irac_i2'],
['candels-irac_i3', 'ultradeep-irac_i3', 'irac_i3'],
['candels-irac_i4', 'ultradeep-irac_i4', 'irac_i4'],
]
ir_origin = Table()
ir_origin.add_column(master_catalogue['help_id'])
ir_stats = Table()
ir_stats.add_column(Column(data=np.array(bands)[:,2], name="Band"))
for col in ["CANDELS-GOODS-N", "Ultradeep"]:
ir_stats.add_column(Column(data=np.full(5, 0), name="{}".format(col), dtype=str))
ir_stats.add_column(Column(data=np.full(5, 0), name="use {}".format(col), dtype=str))
ir_stats.show_in_notebook()
for band in bands:
# total flux
has_candels = ~np.isnan(master_catalogue['f_' + band[0]])
has_ultradeep = ~np.isnan(master_catalogue['f_' + band[1]])
use_candels = has_candels
use_ultradeep = has_ultradeep & ~has_candels
f_ir = np.full(len(master_catalogue), np.nan)
f_ir[use_candels] = master_catalogue['f_' + band[0]][use_candels]
f_ir[use_ultradeep] = master_catalogue['f_' + band[1]][use_ultradeep]
ferr_ir = np.full(len(master_catalogue), np.nan)
ferr_ir[use_candels] = master_catalogue['ferr_' + band[0]][use_candels]
ferr_ir[use_ultradeep] = master_catalogue['ferr_' + band[1]][use_ultradeep]
m_ir = np.full(len(master_catalogue), np.nan)
m_ir[use_candels] = master_catalogue['m_' + band[0]][use_candels]
m_ir[use_ultradeep] = master_catalogue['m_' + band[1]][use_ultradeep]
merr_ir = np.full(len(master_catalogue), np.nan)
merr_ir[use_candels] = master_catalogue['merr_' + band[0]][use_candels]
merr_ir[use_ultradeep] = master_catalogue['merr_' + band[1]][use_ultradeep]
flag_ir = np.full(len(master_catalogue), np.nan)
flag_ir[use_candels] = master_catalogue['flag_' + band[0]][use_candels]
flag_ir[use_ultradeep] = master_catalogue['flag_' + band[1]][use_ultradeep]
master_catalogue.add_column(Column(data=f_ir, name="f_" + band[2]))
master_catalogue.add_column(Column(data=ferr_ir, name="ferr_" + band[2]))
master_catalogue.add_column(Column(data=m_ir, name="m_" + band[2]))
master_catalogue.add_column(Column(data=merr_ir, name="merr_" + band[2]))
master_catalogue.add_column(Column(data=flag_ir, name="flag_" + band[2]))
master_catalogue.remove_columns(['f_' + band[0], 'f_' + band[1],
'ferr_' + band[0], 'ferr_' + band[1],
'm_' + band[0], 'm_' + band[1],
'merr_' + band[0], 'merr_' + band[1],
'flag_' + band[0], 'flag_' + band[1],])
origin = np.full(len(master_catalogue), ' ', dtype='<U5')
origin[use_candels] = "CANDELS-GOODS-N"
origin[use_ultradeep] = "Ultradeep"
ir_origin.add_column(Column(data=origin, name= 'f_' + band[2] ))
#Aperture fluxes
#has_ap_candels = ~np.isnan(master_catalogue['f_ap_' + band[0]])
#has_ap_ultradeep = ~np.isnan(master_catalogue['f_ap_' + band[1]])
#use_ap_candels = has_ap_candels
#use_ap_ultradeep = has_ap_ultradeep & ~has_ap_candels
#f_ap_ir = np.full(len(master_catalogue), np.nan)
#f_ap_ir[use_ap_candels] = master_catalogue['f_ap_' + band[0]][use_ap_candels]
#f_ap_ir[use_ap_ultradeep] = master_catalogue['f_ap_' + band[1]][use_ap_ultradeep]
#ferr_ap_ir = np.full(len(master_catalogue), np.nan)
#ferr_ap_ir[use_ap_candels] = master_catalogue['ferr_ap_' + band[0]][use_ap_candels]
#ferr_ap_ir[use_ap_ultradeep] = master_catalogue['ferr_ap_' + band[1]][use_ap_ultradeep]
#m_ap_ir = np.full(len(master_catalogue), np.nan)
#m_ap_ir[use_ap_candels] = master_catalogue['m_ap_' + band[0]][use_ap_candels]
#m_ap_ir[use_ap_ultradeep] = master_catalogue['m_ap_' + band[1]][use_ap_ultradeep]
#merr_ap_ir = np.full(len(master_catalogue), np.nan)
#merr_ap_ir[use_ap_candels] = master_catalogue['merr_ap_' + band[0]][use_ap_candels]
#merr_ap_ir[use_ap_ultradeep] = master_catalogue['merr_ap_' + band[1]][use_ap_ultradeep]
#master_catalogue.add_column(Column(data=f_ap_ir, name="f_ap_" + band[2]))
#master_catalogue.add_column(Column(data=ferr_ap_ir, name="ferr_ap_" + band[2]))
#master_catalogue.add_column(Column(data=m_ap_ir, name="m_ap_" + band[2]))
#master_catalogue.add_column(Column(data=merr_ap_ir, name="merr_ap_" + band[2]))
#master_catalogue.remove_columns(['f_ap_' + band[0], 'f_ap_' + band[1],
# 'ferr_ap_' + band[0], 'ferr_ap_' + band[1],
# 'm_ap_' + band[0], 'm_ap_' + band[1],
# 'merr_ap_' + band[0], 'merr_ap_' + band[1],
# 'flag_ap_' + band[0], 'flag_ap_' + band[1],])
#origin_ap = np.full(len(master_catalogue), ' ', dtype='<U5')
#origin_ap[use_ap_candels] = "CANDELS-GOODS-N"
#origin_ap[use_ap_ultradeep] = "Ultradeep"
#ir_origin.add_column(Column(data=origin_ap, name= 'f_ap_' + band[2] ))
ir_stats['CANDELS-GOODS-N'][ir_stats['Band'] == band[0]] = np.sum(has_candels)
ir_stats['Ultradeep'][ir_stats['Band'] == band[0]] = np.sum(has_ultradeep)
ir_stats['use CANDELS-GOODS-N'][ir_stats['Band'] == band[0]] = np.sum(use_candels)
ir_stats['use Ultradeep'][ir_stats['Band'] == band[0]] = np.sum(use_ultradeep)
ir_stats.show_in_notebook()
ir_origin.write("{}/hdf-n_wircam_irac_fluxes_origins{}.fits".format(OUT_DIR, SUFFIX))
We add a binary flag_optnir_obs
indicating that a source was observed in a given wavelength domain:
It's an integer binary flag, so a source observed both in optical and near-infrared by not in mid-infrared would have this flag at 1 + 2 = 3.
Note 1: The observation flag is based on the creation of multi-order coverage maps from the catalogues, this may not be accurate, especially on the edges of the coverage.
Note 2: Being on the observation coverage does not mean having fluxes in that wavelength domain. For sources observed in one domain but having no flux in it, one must take into consideration the different depths in the catalogue we are using.
candels_gn_moc = MOC(filename="../../dmu0/dmu0_CANDELS-3D-HST/data/CANDELS-3D-HST_XMM-LSS_MOC.fits")
ultra_moc = MOC(filename="../../dmu0/dmu0_Ultradeep-Ks-GOODS-N/data/Ultradeep_Ks_GOODS-N_HELP-coverage_MOC.fits")
ps1_moc = MOC(filename="../../dmu0/dmu0_PanSTARRS1-3SS/data/PanSTARRS1-3SS_XMM-LSS_MOC.fits")
hawaii_moc = MOC(filename="../../dmu0/dmu0_Hawaii-HDFN/data/R_MOC.fits")
was_observed_optical = inMoc(
master_catalogue['ra'], master_catalogue['dec'],
ps1_moc + hawaii_moc)
was_observed_nir = inMoc(
master_catalogue['ra'], master_catalogue['dec'],
candels_gn_moc + ultra_moc
)
was_observed_mir = inMoc(
master_catalogue['ra'], master_catalogue['dec'],
candels_gn_moc + ultra_moc
)
master_catalogue.add_column(
Column(
1 * was_observed_optical + 2 * was_observed_nir + 4 * was_observed_mir,
name="flag_optnir_obs")
)
We add a binary flag_optnir_det
indicating that a source was detected in a given wavelength domain:
It's an integer binary flag, so a source detected both in optical and near-infrared by not in mid-infrared would have this flag at 1 + 2 = 3.
Note 1: We use the total flux columns to know if the source has flux, in some catalogues, we may have aperture flux and no total flux.
To get rid of artefacts (chip edges, star flares, etc.) we consider that a source is detected in one wavelength domain when it has a flux value in at least two bands. That means that good sources will be excluded from this flag when they are on the coverage of only one band.
# SpARCS is a catalogue of sources detected in r (with fluxes measured at
# this prior position in the other bands). Thus, we are only using the r
# CFHT band.
# Check to use catalogue flags from HSC and PanSTARRS.
nb_optical_flux = (
# PanSTARRS
1 * ~np.isnan(master_catalogue['f_gpc1_g']) +
1 * ~np.isnan(master_catalogue['f_gpc1_r']) +
1 * ~np.isnan(master_catalogue['f_gpc1_i']) +
1 * ~np.isnan(master_catalogue['f_gpc1_z']) +
1 * ~np.isnan(master_catalogue['f_gpc1_y']) +
1 * ~np.isnan(master_catalogue['f_suprime_r'])
)
nb_nir_flux = (
1 * ~np.isnan(master_catalogue['f_wircam_k'])
)
nb_mir_flux = (
1 * ~np.isnan(master_catalogue['f_irac_i1']) +
1 * ~np.isnan(master_catalogue['f_irac_i2']) +
1 * ~np.isnan(master_catalogue['f_irac_i3']) +
1 * ~np.isnan(master_catalogue['f_irac_i4'])
)
has_optical_flux = nb_optical_flux >= 2
has_nir_flux = nb_nir_flux >= 2
has_mir_flux = nb_mir_flux >= 2
master_catalogue.add_column(
Column(
1 * has_optical_flux + 2 * has_nir_flux + 4 * has_mir_flux,
name="flag_optnir_det")
)
We are producing a table associating to each HELP identifier, the identifiers of the sources in the pristine catalogues. This can be used to easily get additional information from them.
For convenience, we also cross-match the master list with the SDSS catalogue and add the objID associated with each source, if any. TODO: should we correct the astrometry with respect to Gaia positions?
#
# Addind SDSS ids
#
sdss = Table.read("../../dmu0/dmu0_SDSS-DR13/data/SDSS-DR13_HDF-N.fits")['objID', 'ra', 'dec']
sdss_coords = SkyCoord(sdss['ra'] * u.deg, sdss['dec'] * u.deg)
idx_ml, d2d, _ = sdss_coords.match_to_catalog_sky(SkyCoord(master_catalogue['ra'], master_catalogue['dec']))
idx_sdss = np.arange(len(sdss))
# Limit the cross-match to 1 arcsec
mask = d2d <= 1. * u.arcsec
idx_ml = idx_ml[mask]
idx_sdss = idx_sdss[mask]
d2d = d2d[mask]
nb_orig_matches = len(idx_ml)
# In case of multiple associations of one master list object to an SDSS object, we keep only the
# association to the nearest one.
sort_idx = np.argsort(d2d)
idx_ml = idx_ml[sort_idx]
idx_sdss = idx_sdss[sort_idx]
_, unique_idx = np.unique(idx_ml, return_index=True)
idx_ml = idx_ml[unique_idx]
idx_sdss = idx_sdss[unique_idx]
print("{} master list rows had multiple associations.".format(nb_orig_matches - len(idx_ml)))
# Adding the ObjID to the master list
master_catalogue.add_column(Column(data=np.full(len(master_catalogue), -1, dtype='>i8'), name="sdss_id"))
master_catalogue['sdss_id'][idx_ml] = sdss['objID'][idx_sdss]
id_names = []
for col in master_catalogue.colnames:
if '_id' in col:
id_names += [col]
if '_intid' in col:
id_names += [col]
print(id_names)
master_catalogue[id_names].write(
"{}/master_list_cross_ident_hdf-n{}.fits".format(OUT_DIR, SUFFIX), overwrite=True)
id_names.remove('help_id')
master_catalogue.remove_columns(id_names)
We are adding a column with a HEALPix index at order 13 associated with each source.
master_catalogue.add_column(Column(
data=coords_to_hpidx(master_catalogue['ra'], master_catalogue['dec'], order=13),
name="hp_idx"
))
columns = ["help_id", "field", "ra", "dec", "hp_idx"]
bands = [column[5:] for column in master_catalogue.colnames if 'f_ap' in column]
bands_no_ap = (set([column[5:] for column in master_catalogue.colnames if 'flag' in column])
- set(bands)
- set(['cleaned', 'gaia', 'merged', 'optnir_det', 'optnir_obs'])
)
for band in bands:
columns += ["f_ap_{}".format(band), "ferr_ap_{}".format(band),
"m_ap_{}".format(band), "merr_ap_{}".format(band),
"f_{}".format(band), "ferr_{}".format(band),
"m_{}".format(band), "merr_{}".format(band),
#"flag_{}".format(band)
]
for band in bands_no_ap:
columns += ["f_{}".format(band), "ferr_{}".format(band),
"m_{}".format(band), "merr_{}".format(band),
#"flag_{}".format(band)
]
columns += ["stellarity", "stellarity_origin", "flag_cleaned", "flag_merged", "flag_gaia",
"flag_optnir_obs", "flag_optnir_det", "ebv"] # "zspec", "zspec_qual", "zspec_association_flag",
# We check for columns in the master catalogue that we will not save to disk.
print("Missing columns: {}".format(set(master_catalogue.colnames) - set(columns)))
#master_catalogue[columns].write("{}/master_catalogue_hdf-n{}.fits".format(OUT_DIR, SUFFIX), overwrite=True)
master_catalogue.write("{}/master_catalogue_hdf-n{}.fits".format(OUT_DIR, SUFFIX), overwrite=True)