def mk_coords(radecfile, outfile, cosmology): # Set the cosmology with h free if cosmology == "Planck": Planck13.__init__(100.0, Planck13.Om0) cosmo = Planck13 elif cosmology == "WMAP": WMAP5.__init__(100.0, WMAP5.Om0) cosmo = WMAP5 f_in = h5.File(radecfile) radecz = f_in["radecz"] f_out = h5.File(outfile) cart = f_out.create_dataset("cart_pts", shape=(radecz.shape[0], 3), dtype='float64') for i in range(radecz.shape[0]): ra = Angle(radecz[i, 0], u.deg) dec = Angle(radecz[i, 1], u.deg) losd = cosmo.comoving_distance(radecz[i, 2]) dis = Distance(losd) coord = ICRSCoordinates(ra, dec, distance=dis) cart[i, :] = np.array([coord.x, coord.y, coord.z]) f_in.close() f_out.close()
def mk_mock_coords(radeczfile, outfile, simul_cosmo): if simul_cosmo == "Planck": Planck13.__init__(100.0, Planck13.Om0) cosmo = Planck13 elif simul_cosmo == "WMAP": WMAP5.__init__(100.0, WMAP5.Om0) cosmo = WMAP5 rad = np.arange(1.0, 67.0, 5.0) radecz = h5_arr(radeczfile, "radecz") cart = np.zeros(radecz.shape) for i, rdz in enumerate(radecz): ra = Angle(rdz[0], u.deg) dec = Angle(rdz[1], u.deg) losd = cosmo.comoving_distance(rdz[2]) dis = Distance(losd) coord = ICRSCoordinates(ra, dec, distance=dis) cart[i, :] = np.array([coord.x.value, coord.y.value, coord.z.value]) np.savetxt(outfile, cart)
def predict(self, date, obs_code=568, abg_file=None): """ use the bk predict method to compute the location of the source on the given date. @param date: the julian date of interest or an astropy.core.time.Time object. @param obs_code: the Minor Planet Center observatory location code (Mauna Kea: 568 is the default) this methods sets the values of coordinate, dra (arcseconds), ddec (arcseconds), pa, (degrees) and date (str) """ if not isinstance(date, Time): if isinstance(date, float): try: date = Time(date, format='jd', scale='utc', precision=6) except: date = None # FIXME: this might blow up, not sure else: try: date = Time(date, format='jd', scale='utc', precision=6) except ValueError: try: date = Time(date, format='mpc', scale='utc', precision=6) except ValueError: date = Time(date, scale='utc', precision=6) # see if it can guess if hasattr(self, 'time'): dt = self.time - date if math.fabs(dt.sec) < 10: return jd = ctypes.c_double(date.jd) if abg_file is None: abg_file = tempfile.NamedTemporaryFile(suffix='.abg') abg_file.write(self.abg) abg_file.seek(0) # call predict with agbfile, jdate, obscode self.orbfit.predict.restype = ctypes.POINTER(ctypes.c_double * 5) self.orbfit.predict.argtypes = [ ctypes.c_char_p, ctypes.c_double, ctypes.c_int ] predict = self.orbfit.predict(ctypes.c_char_p(abg_file.name), jd, ctypes.c_int(obs_code)) self.coordinate = ICRSCoordinates(predict.contents[0], predict.contents[1], unit=(units.degree, units.degree), obstime=date) self.dra = predict.contents[2] self.ddec = predict.contents[3] self.pa = predict.contents[4] self.date = str(date) self.time = date
def append(self, coordinate): """ Append an target location to the ephemeris listing. """ fields = self.fields sra = coordinate.ra.format(units.hour, sep=':', precision=2, pad=True) sdec = coordinate.dec.format(units.degree, sep=':', precision=1, alwayssign=True) coord = ICRSCoordinates(sra+" "+sdec, unit=(units.hour, units.degree)) sra = coord.ra.format(units.hour, sep=":", precision=2, pad=True) sdec = coord.dec.format(units.degree, sep=":", precision=1, pad=True) sdate = str(coordinate.obstime.replicate(format('iso'))) self.cdata.appendData(self._entry(sdate, fields["DATE_UTC"]['attr']['width'], colsep=self.column_separator)) self.cdata.appendData(self._entry(sra, fields["RA_J2000"]['attr']['width'], colsep=self.column_separator)) self.cdata.appendData(self._entry(sdec, fields["DEC_J2000"]["attr"]["width"], colsep=self.column_separator)) self.cdata.appendData("\n")
def mock_vpf(mock_cart_coords, spheresfile, simul_cosmo, rad): gals = h5_arr(mock_cart_coords, "coords") print gals name = mock_cart_coords.split("/")[-1].split(".")[0] if simul_cosmo == "Planck": # First make h free Planck13.__init__(100.0, Planck13.Om0) cosmo = Planck13 elif simul_cosmo == "WMAP": WMAP5.__init__(100.0, WMAP5.Om0) cosmo = WMAP5 comv = cosmo.comoving_distance gal_baum = cKDTree(gals) spheres = h5_arr(spheresfile, "radecz_{0}".format(str(int(rad)))) print spheres for i, sphere in enumerate(spheres): rang = Angle(sphere[0], u.deg) decang = Angle(sphere[1], u.deg) dis = Distance(comv(sphere[2]), u.Mpc) coord = ICRSCoordinates(rang, decang, distance=dis) sph_cen = np.array([coord.x, coord.y, coord.z]) nn = gal_baum.query(sph_cen) print "rad: ", rad, ", sphere: ", i f = open( "{0}/vpf_out/ascii/{1}_{2}.dat".format( os.path.dirname(spheresfile), name, str(int(rad))), 'a') if not nn[0] < rad: f.write("1\n") else: f.write("0\n") f.close()
def mock_vpf(mock_cart_coords, spheresfile, simul_cosmo): gals = h5_arr(mock_cart_coords, "coords") name = mock_cart_coords.split("/")[-1].split(".")[0] if simul_cosmo == "Planck": # First make h free Planck13.__init__(100.0, Planck13.Om0) cosmo = Planck13 elif simul_cosmo == "WMAP": WMAP5.__init__(100.0, WMAP5.Om0) cosmo = WMAP5 comv = cosmo.comoving_distance gal_baum = cKDTree(gals) rad = np.arange(1.0, 67.0, 5.0) for r_i, r in enumerate(rad): spheres = h5_arr(spheresfile, "radecz_{0}".format(str(r_i * 5 + 1))) voids = np.zeros(spheres.shape[0]) for i, sphere in enumerate(spheres): rang = Angle(sphere[0], u.deg) decang = Angle(sphere[1], u.deg) dis = Distance(comv(sphere[2]), u.Mpc) coord = ICRSCoordinates(rang, decang, distance=dis) sph_cen = np.array([coord.x.value, coord.y.value, coord.z.value]) nn = gal_baum.query(sph_cen) print "rad: ", r, ", sphere: ", i if not nn[0] < r: voids[i] = 1 arr2h5(voids, "{0}/vpf_out/{1}.hdf5".format(os.path.dirname(spheresfile), name), "voids_{0}".format(str(r_i * 5 + 1)))
def residuals(self): ## compute the residuals (from the given observations) _residuals = "" for observation in self.observations: self.predict(observation.date) coord1 = ICRSCoordinates(self.coordinate.ra, self.coordinate.dec) coord2 = ICRSCoordinates(observation.coordinate.ra, self.coordinate.dec) observation.ra_residual = float(coord1.separation(coord2).arcsecs) observation.ra_residual = (coord1.ra.degrees - coord2.ra.degrees) * 3600.0 coord2 = ICRSCoordinates(self.coordinate.ra, observation.coordinate.dec) observation.dec_residual = float(coord1.separation(coord2).arcsecs) observation.dec_residual = (coord1.dec.degrees - coord2.dec.degrees) * 3600.0 _residuals += "{:1s}{:12s} {:+05.2f} {:+05.2f} # {}\n".format( observation.null_observation, observation.date, observation.ra_residual, observation.dec_residual, observation) return _residuals
def save_pointings(self): """Print the currently defined FOVs""" i = 0 if self.pointing_format.get() == 'CFHT ET': for pointing in self.pointings: name = pointing["label"]["text"] camera = pointing["camera"] ccds = camera.getGeometry() polygons = [] for ccd in ccds: polygon = Polygon.Polygon( ((ccd[0], ccd[1]), (ccd[0], ccd[3]), (ccd[2], ccd[3]), (ccd[2], ccd[1]), (ccd[0], ccd[1]))) polygons.append(polygon) et = EphemTarget(name) # determine the mean motion of target KBOs in this field. field_kbos = [] center_ra = 0 center_dec = 0 # Compute the mean position of KBOs in the field on current date. for kbo_name, kbo in self.kbos.items(): if kbo_name in Neptune or kbo_name in tracking_termination: # print 'skipping', kbo_name continue kbo.predict(mpc.Time(self.date.get(), scale='utc')) ra = kbo.coordinate.ra.radian dec = kbo.coordinate.dec.radian for polygon in polygons: if polygon.isInside(ra, dec): field_kbos.append(kbo) center_ra += ra center_dec += dec logging.info("KBOs in field {0}: {1}".format(name, field_kbos)) start_date = mpc.Time(self.date.get(), scale='utc').jd for days in range(-90, 90, 1): for hours in range(0, 23, 12): today = mpc.Time(start_date + days + hours / 24.0, scale='utc', format='jd') mean_motion = (0, 0) if len(field_kbos) > 0: current_ra = 0 current_dec = 0 for kbo in field_kbos: kbo.predict(today) current_ra += kbo.coordinate.ra.radian current_dec += kbo.coordinate.dec.radian mean_motion = ((current_ra - center_ra) / len(field_kbos), (current_dec - center_dec) / len(field_kbos)) ra = pointing[ 'camera'].coordinate.ra.radian + mean_motion[0] dec = pointing[ 'camera'].coordinate.dec.radian + mean_motion[1] cc = ICRSCoordinates(ra=ra, dec=dec, unit=(units.radian, units.radian), obstime=today) et.append(cc) et.save() return f = tkFileDialog.asksaveasfile() if self.pointing_format.get() == 'Subaru': for pointing in self.pointings: (sra, sdec) = str(pointing["camera"]).split() ra = sra.replace(":", "") dec = sdec.replace(":", "") name = pointing["label"]["text"] f.write( """{}=OBJECT="{}" RA={} DEC={} EQUINOX=2000.0 INSROT_PA=90\n""" .format(name, name, ra, dec)) return if self.pointing_format.get() == 'CFHT PH': f.write("""<?xml version = "1.0"?> <!DOCTYPE ASTRO SYSTEM "http://vizier.u-strasbg.fr/xml/astrores.dtd"> <ASTRO ID="v0.8" xmlns:ASTRO="http://vizier.u-strasbg.fr/doc/astrores.htx"> <TABLE ID="Table"> <NAME>Fixed Targets</NAME> <TITLE>Fixed Targets for CFHT QSO</TITLE> <!-- Definition of each field --> <FIELD name="NAME" datatype="A" width="20"> <DESCRIPTION>Name of target</DESCRIPTION> </FIELD> <FIELD name="RA" ref="" datatype="A" width="11" unit=""h:m:s""> <DESCRIPTION>Right ascension of target</DESCRIPTION> </FIELD> <FIELD name="DEC" ref="" datatype="A" width="11" unit=""d:m:s""> <DESCRIPTION>Declination of target</DESCRIPTION> </FIELD> <FIELD name="EPOCH" datatype="F" width="6"> <DESCRIPTION>Epoch of coordinates</DESCRIPTION> </FIELD> <FIELD name="POINT" datatype="A" width="5"> <DESCRIPTION>Pointing name</DESCRIPTION> </FIELD> <!-- Data table --> <DATA><CSV headlines="4" colsep="|"><![CDATA[ NAME |RA |DEC |EPOCH |POINT| |hh:mm:ss.ss|+dd:mm:ss.s| | | 12345678901234567890|12345678901|12345678901|123456|12345| --------------------|-----------|-----------|------|-----|\n""") if self.pointing_format.get() == 'Palomar': f.write("index\n") for pointing in self.pointings: i = i + 1 name = pointing["label"]["text"] (sra, sdec) = str(pointing["camera"]).split() ra = sra.split(":") dec = sdec.split(":") dec[0] = str(int(dec[0])) if int(dec[0]) >= 0: dec[0] = '+' + dec[0] if self.pointing_format.get() == 'Palomar': f.write( "%5d %16s %2s %2s %4s %3s %2s %4s 2000\n" % (i, name, ra[0].zfill(2), ra[1].zfill(2), ra[2].zfill(2), dec[0].zfill(3), dec[1].zfill(2), dec[2].zfill(2))) elif self.pointing_format.get() == 'CFHT PH': # f.write("%f %f\n" % (pointing["camera"].ra,pointing["camera"].dec)) f.write("%-20s|%11s|%11s|%6.1f|%-5d|\n" % (name, sra, sdec, 2000.0, 1)) elif self.pointing_format.get() == 'KPNO/CTIO': str1 = sra.replace(":", " ") str2 = sdec.replace(":", " ") f.write("%16s %16s %16s 2000\n" % (name, str1, str2)) elif self.pointing_format.get() == 'SSim': ra = [] dec = [] for ccd in pointing["camera"].getGeometry(): ra.append(ccd[0]) ra.append(ccd[2]) dec.append(ccd[1]) dec.append(ccd[3]) dra = math.degrees(math.fabs(max(ra) - min(ra))) ddec = math.degrees(math.fabs(max(dec) - min(dec))) f.write("%f %f %16s %16s DATE 1.00 1.00 500 FILE\n" % (dra, ddec, sra, sdec)) if self.pointing_format.get() == 'CFHT PH': f.write("""]]</CSV></DATA> </TABLE> </ASTRO> """) f.close()
def coordinate(self): return ICRSCoordinates( ra=math.degrees(self.ra), dec=math.degrees(self.dec), unit=(units.degree, units.degree))
rand_i = 0 for r_i, r in enumerate(rad): spheres = h5_arr(spheresfile, "radecz_{0}".format(str(r_i * 5 + 1))) badvols = np.zeros(spheres.shape[0]) for i, sphere in enumerate(spheres): rang = Angle(sphere[0], u.deg) decang = Angle(sphere[1], u.deg) dis = Distance(comv(sphere[2]), u.Mpc) coord = ICRSCoordinates(rang, decang, distance=dis) sph_cen = np.array([coord.x.value, coord.y.value, coord.z.value]) print "rad: ", r, ", sphere: ", i # Get radius of circular projection of sphere R = np.arcsin(r / np.sqrt(np.sum(sph_cen[:]**2))) # Get coordinates of circle centre on unit sphere crc_cen = radec2xyz(sphere[:2])[0] # Compute tree search radius from Cosine rule # (include points extending beyond sphere edge to account for # finite area around bad points) l_srch = np.sqrt(2. - 2. * np.cos(R))
from __future__ import division, print_function import numpy as np from novas.compat import sidereal_time from astropy.time import Time, TimeDelta import astropy.units as u from astropy.coordinates import ICRSCoordinates from astropy.table import Table from astropy.constants import c as SPEED_OF_LIGHT SOURCE = ICRSCoordinates('03h32m59.368s +54d34m43.57s') OUTFILE = 'outfile.mat' # first time stamp of all. Maybe should be rounded to minute? TIME_STAMP0 = '2013 06 29 03 53 00 0.660051' MAX_NO_IN_SEQ_FILE = 4331 N_BLOCK = MAX_NO_IN_SEQ_FILE - 1 DT_SAMPLE = TimeDelta(0., (3 / (200 * u.MHz)).to(u.s).value, format='sec') DT_BLOCK = 2.**24 * DT_SAMPLE TEL_LONGITUDE = 74 * u.deg + 02 * u.arcmin + 59.07 * u.arcsec TEL_LATITUDE = 19 * u.deg + 05 * u.arcmin + 47.46 * u.arcsec NPOD = 30 # Number of baselines (only used as sanity check) ANTENNA_FILE = '/home/mhvk/packages/scintellometry/scintellometry/phasing/' \ 'antsys.hdr' OUR_ANTENNA_ORDER = 'CWES' # and by number inside each group
import astropy.units as u from astropy.coordinates import ICRSCoordinates from streams.coordinates import SgrCoordinates, OrphanCoordinates icrs = ICRSCoordinates(15.34167, 1.53412, unit=(u.hour, u.degree)) sgr = icrs.transform_to(SgrCoordinates) print(sgr.Lambda, sgr.Beta) orp = sgr.transform_to(OrphanCoordinates) print(orp.Lambda, orp.Beta)
def vpf(dat_dir, Nsph, simul_cosmo, rad): # Grab the data coordinates gals = h5_arr( "./dat/out/{0}/{1}/gals_cart_coords.hdf5".format(dat_dir, simul_cosmo), "cart_pts") # Get details about the redshift interval being considered nbar_dict = json.load( open("./dat/out/{0}/{1}/nbar_zrange.json".format(dat_dir, simul_cosmo))) zlo = nbar_dict["zlo"] zhi = nbar_dict["zhi"] # Get the search points good_pts = h5_arr("./dat/out/{0}/srch_radec.hdf5".format(dat_dir), "good_pts") bad_pts = h5_arr("./dat/out/{0}/veto.hdf5".format(dat_dir), "bad_pts") # Set angular radius of effective area around bad points bad_r = np.arccos(1.0 - (np.pi * 9.8544099e-05) / (2 * 180**2)) bad_r_deg = np.rad2deg(bad_r) # Set the cosmology with h free # Here the cosmology is based on WMAP (for first MultiDark simulation) if simul_cosmo == "Planck": # First make h free Planck13.__init__(100.0, Planck13.Om0) cosmo = Planck13 elif simul_cosmo == "WMAP": WMAP5.__init__(100.0, WMAP5.Om0) cosmo = WMAP5 comv = cosmo.comoving_distance # Build the trees # galaxy tree gal_baum = cKDTree(gals) # tree of bad points (angular coordinates on unit sphere) bad_xyz = radec2xyz(bad_pts) veto_baum = cKDTree(bad_xyz) # Initialise final output arrays # rad = np.arange(1.0, 67.0, 5.0) doing it one radius at a time # P_0 = np.zeros(rad.shape) # No. of spheres and norm # Nsph_arr = Nsph * np.array(4 * [0.01] + 4 * [0.1] + 4 * [1.0]) # norm = 1. / Nsph_arr # norm = 1. / Nsph rand_i = 0 for r_i, r in enumerate(rad): # start the count of successful voids count = 0 # Custom zrange for sphere size dis_near = Distance(comv(zlo).value + r, u.Mpc) dis_far = Distance(comv(zhi).value - r, u.Mpc) z_a = dis_near.compute_z(cosmology=cosmo) z_b = dis_far.compute_z(cosmology=cosmo) for i in range(Nsph): # _arr[r_i]): # compensate for finite length of mask file rand_i = rand_i % 999999 radec = good_pts[rand_i, :] rang = Angle(radec[0], u.deg) decang = Angle(radec[1], u.deg) randz = (z_a ** 3 + \ (z_b ** 3 - z_a ** 3) * np.random.rand(1)[0]) ** (1. / 3.) dis = Distance(comv(randz), u.Mpc) coord = ICRSCoordinates(rang, decang, distance=dis) sph_cen = np.array([coord.x.value, coord.y.value, coord.z.value]) nn = gal_baum.query(sph_cen) print "rad: ", r, ", sphere: ", i if not nn[0] < r: # add instance to probability count count += 1 # record quality of sphere using spline values for intersection # with bad points # Get radius of circular projection of sphere R = np.arcsin(r / np.sqrt(np.sum(sph_cen[:]**2))) # Get coordinates of circle centre on unit sphere crc_cen = radec2xyz(radec)[0] # Compute tree search radius from Cosine rule # (include points extending beyond sphere edge to account for # finite area around bad points) l_srch = np.sqrt(2. - 2. * np.cos(R)) # Run search pierce_l = veto_baum.query_ball_point(crc_cen, l_srch) bad_vol = 0. R = np.degrees(R) # need in degrees for bad_vol computation for pt in pierce_l: pt_ang = bad_pts[pt] dis = np.degrees(central_angle(pt_ang, radec)) l = dis / R bad_vol += 1.5 * (bad_r_deg / R) ** 2 \ * np.sqrt(1.0 - l ** 2) f_r = open( "./dat/out/{0}/{1}/vpf_out/volfrac_{2}.dat".format( dat_dir, simul_cosmo, r), 'a') f_r.write("{0}\n".format(bad_vol)) f_r.close() rand_i += 1