def _initialise_ephemeris(self, earth_ephem, sun_ephem, time_corr): """ Initialise the solar system ephemeris. """ if earth_ephem is not None: earthfile = earth_ephem else: earthfile = self.__earthstr.format(self.ephem) if sun_ephem is not None: sunfile = sun_ephem else: sunfile = self.__sunstr.format(self.ephem) if time_corr is not None: timefile = time_corr else: timefile = self.__timecorrstr.format(self.__units_map[self.units]) try: edat = lalpulsar.InitBarycenter(earthfile, sunfile) except RuntimeError: try: # try downloading the ephemeris files from astropy.utils.data import download_file efile = download_file(DOWNLOAD_URL.format(earthfile), cache=True) sfile = download_file(DOWNLOAD_URL.format(sunfile), cache=True) edat = lalpulsar.InitBarycenter(efile, sfile) except Exception as e: raise IOError( "Could not read in ephemeris files: {}".format(e)) try: tdat = lalpulsar.InitTimeCorrections(timefile) except RuntimeError: try: # try downloading the ephemeris files from astropy.utils.data import download_file tfile = download_file(DOWNLOAD_URL.format(timefile), cache=True) tdat = lalpulsar.InitTimeCorrections(tfile) except Exception as e: raise IOError( "Could not read in time correction file: {}".format(e)) return edat, tdat
def _initialise_ephemeris(self, earth_ephem, sun_ephem, time_corr): """ Initialise the solar system ephemeris. """ if earth_ephem is not None: earthfile = earth_ephem else: earthfile = self.__earthstr.format(self.ephem) if sun_ephem is not None: sunfile = sun_ephem else: sunfile = self.__sunstr.format(self.ephem) if time_corr is not None: timefile = time_corr else: timefile = self.__timecorrstr.format(self.__units_map[self.units]) try: edat = lalpulsar.InitBarycenter(earthfile, sunfile) except Exception as e: raise IOError("Could not read in ephemeris files: {}".format(e)) try: tdat = lalpulsar.InitTimeCorrections(timefile) except Exception as e: raise IOError( "Could not read in time correction file: {}".format(e)) return edat, tdat
def get_frequency(self, t): DeltaFDrift = self.F1 * (t - self.tref) phir = 2 * np.pi * t / self.Pmod + self.Pmod_phi if self.Alpha is not None and self.Delta is not None: spin_posvel = lalpulsar.PosVel3D_t() orbit_posvel = lalpulsar.PosVel3D_t() det = lal.CachedDetectors[4] ephems = lalpulsar.InitBarycenter(self.earth_ephem, self.sun_ephem) lalpulsar.DetectorPosVel( spin_posvel, orbit_posvel, lal.LIGOTimeGPS(t), det, ephems, lalpulsar.DETMOTION_ORBIT, ) # Pos and vel returned in units of c DeltaFOrbital = np.dot(self.n, orbit_posvel.vel) * self.Fmax if self.IFO == "H1": Lambda = lal.LHO_4K_DETECTOR_LATITUDE_RAD elif self.IFO == "L1": Lambda = lal.LLO_4K_DETECTOR_LATITUDE_RAD DeltaFSpin = ( self.Pmod_amp * lal.REARTH_SI / lal.C_SI * 2 * np.pi / self.Pmod * (np.cos(self.Delta) * np.cos(Lambda) * np.sin(self.Alpha - phir)) * self.Fmax ) else: DeltaFOrbital = 0 DeltaFSpin = 2 * np.pi * self.Pmod_amp / self.Pmod * np.cos(phir) f = self.F0 + DeltaFDrift + DeltaFOrbital + DeltaFSpin return f
[1000068400.0, -1.737338292421e-26, -1.215410941899e-26], [1000072000.0, -7.948860127300e-27, -9.699169393802e-27], [1000075600.0, 3.255444398910e-27, -4.686765876987e-27], [1000079200.0, 1.369234859571e-26, 1.647785967195e-27], [1000082800.0, 2.100706686852e-26, 7.709825036865e-27]]) # set ephemeris files earthephem = os.path.join(os.environ['LAL_TEST_PKGDATADIR'], 'earth00-19-DE405.dat.gz') sunephem = os.path.join(os.environ['LAL_TEST_PKGDATADIR'], 'sun00-40-DE405.dat.gz') timefile = os.path.join(os.environ['LAL_TEST_PKGDATADIR'], 'te405_2000-2040.dat.gz') # get ephemeris files edat = lalpulsar.InitBarycenter(earthephem, sunephem) tdat = lalpulsar.InitTimeCorrections(timefile) def test_one(): par = PulsarParametersPy() par['F'] = [123.456789, -9.87654321e-12] # set frequency par['DELTAF'] = [0.0, 0.0] # frequency difference par['RAJ'] = lal.TranslateHMStoRAD('01:23:34.5') # set right ascension par['DECJ'] = lal.TranslateDMStoRAD('-45:01:23.4') # set declination pepoch = lal.TranslateStringMJDTTtoGPS('58000') par['PEPOCH'] = pepoch.gpsSeconds + 1e-9 * pepoch.gpsNanoSeconds par['H0'] = 5.6e-26 par['COSIOTA'] = -0.2 par['PSI'] = 0.4 par['PHI0'] = 2.3
def __init__(self, gps_t0, T, wf, gps_tref_wf, dt_wf, phi_0, psi, alpha, delta, det_name, earth_ephem_file="earth00-19-DE405.dat.gz", sun_ephem_file="sun00-19-DE405.dat.gz"): """ Initialise a continuous-wave signal simulator. @param gps_t0: start time of signal, in GPS seconds @param T: total duration of signal, in seconds @param wf: function which computes signal phase and amplitudes as functions of time: @b dphi, @b aplus, @b across = @b wf(dt), where: @b dt = time since reference time @b gps_tref_wf; @b dphi = phase of signal at time @b dt relative to reference time @b gps_tref_wf, in radians; @b aplus = strain amplitude of plus polarisation at time @b dt; @b across = strain amplitude of cross polarisation at time @b dt @param gps_tref_wf: reference time for signal phase, in GPS seconds @param dt_wf: sampling time of the function @c wf; this need only be small enough to ensure that @c dphi, @c aplus, and @c across are smoothly interpolated, and does not need to make the desired sampling frequency of the output strain time series @param phi_0: initial phase of the gravitational-wave signal at @b gps_t0, in radians @param psi: polarisation angle of the gravitational-wave source, in radians @param alpha: right ascension of the gravitational-wave source, in radians @param delta: declination of the gravitational-wave source, in radians @param det_name: name of the gravitational-wave detector to simulate a response for; e.g. @c "H1" for LIGO Hanford, @c "L1" for LIGO Livingston, @c "V1" for Virgo @param earth_ephem_file: name of file to load Earth ephemeris from @param sun_ephem_file: name of file to load Sun ephemeris from """ # store arguments self.__gps_t0 = gps_t0 self.__T = T # parse detector name try: _, self.__det_index = lalpulsar.GetCWDetectorPrefix(det_name) assert (self.__det_index >= 0) except: raise ValueError("Invalid detector name det_name='%s'" % det_name) # load Earth and Sun ephemerides self.__ephemerides = lalpulsar.InitBarycenter(earth_ephem_file, sun_ephem_file) # start signal time series 'T_pad_wf' before/after output strain time series # to add sufficient padding for maximum Doppler modulation time shifts, otherwise # lalpulsar.PulsarSimulateCoherentGW() will output zeros without complaint (unless # you run with LAL_DEBUG_LEVEL=warning) T_pad_wf = 2.0 * lal.AU_SI / lal.C_SI gps_t0_wf = gps_t0 - T_pad_wf N_wf = int(math.ceil(float(T + 2 * T_pad_wf) / float(dt_wf))) # create REAL8TimeSeries to store signal phase self.__phi = lal.CreateREAL8TimeSeries("phi", gps_t0_wf, 0, dt_wf, lal.DimensionlessUnit, N_wf) # create REAL4TimeVectorSeries to store signal amplitudes # - LAL provides no creator function for this type, so must be done manually self.__a = lal.REAL4TimeVectorSeries() self.__a.name = "a+,ax" self.__a.epoch = gps_t0_wf self.__a.deltaT = dt_wf self.__a.f0 = 0 self.__a.sampleUnits = lal.StrainUnit self.__a.data = lal.CreateREAL4VectorSequence(N_wf, 2) # call wf() to fill time series of signal phase and amplitudes dt = float(gps_t0_wf - gps_tref_wf) for i in xrange(0, N_wf): dphi, aplus, across = wf(dt) self.__phi.data.data[i] = phi_0 + dphi self.__a.data.data[i][0] = aplus self.__a.data.data[i][1] = across dt += dt_wf # create and initialise PulsarCoherentGW struct self.__waveform = lalpulsar.PulsarCoherentGW() self.__waveform.position.system = lal.COORDINATESYSTEM_EQUATORIAL self.__waveform.position.longitude = alpha self.__waveform.position.latitude = delta self.__waveform.psi = psi self.__waveform.phi = self.__phi self.__waveform.a = self.__a # create and initialise PulsarDetectorResponse struct self.__detector = lalpulsar.PulsarDetectorResponse() self.__detector.site = lal.CachedDetectors[self.__det_index] self.__detector.ephemerides = self.__ephemerides
def get_Nstar_estimate(nsegs, tref, minStartTime, maxStartTime, prior, detector_names): """Returns N* estimated from the super-sky metric Parameters ---------- nsegs : int Number of semi-coherent segments tref : int Reference time in GPS seconds minStartTime, maxStartTime : int Minimum and maximum SFT timestamps prior : dict The prior dictionary detector_names : array Array of detectors to average over Returns ------- Nstar: int The estimated approximate number of templates to cover the prior parameter space at a mismatch of unity, assuming the normalised thickness is unity. """ earth_ephem, sun_ephem = helper_functions.get_ephemeris_files() in_phys, spindowns, sky, fiducial_freq = _extract_data_from_prior(prior) out_rssky = np.zeros(in_phys.shape) in_phys = helper_functions.convert_array_to_gsl_matrix(in_phys) out_rssky = helper_functions.convert_array_to_gsl_matrix(out_rssky) tboundaries = np.linspace(minStartTime, maxStartTime, nsegs + 1) ref_time = lal.LIGOTimeGPS(tref) segments = lal.SegListCreate() for j in range(len(tboundaries) - 1): seg = lal.SegCreate( lal.LIGOTimeGPS(tboundaries[j]), lal.LIGOTimeGPS(tboundaries[j + 1]), j ) lal.SegListAppend(segments, seg) detNames = lal.CreateStringVector(*detector_names) detectors = lalpulsar.MultiLALDetector() lalpulsar.ParseMultiLALDetector(detectors, detNames) detector_weights = None detector_motion = lalpulsar.DETMOTION_SPIN + lalpulsar.DETMOTION_ORBIT ephemeris = lalpulsar.InitBarycenter(earth_ephem, sun_ephem) try: SSkyMetric = lalpulsar.ComputeSuperskyMetrics( lalpulsar.SUPERSKY_METRIC_TYPE, spindowns, ref_time, segments, fiducial_freq, detectors, detector_weights, detector_motion, ephemeris, ) except RuntimeError as e: logging.warning("Encountered run-time error {}".format(e)) raise RuntimeError("Calculation of the SSkyMetric failed") if sky: i = 0 else: i = 2 lalpulsar.ConvertPhysicalToSuperskyPoints( out_rssky, in_phys, SSkyMetric.semi_rssky_transf ) d = out_rssky.data g = SSkyMetric.semi_rssky_metric.data g = g[i:, i:] # Remove sky if required parallelepiped = (d[i:, 1:].T - d[i:, 0]).T Nstars = [] for j in range(1, len(g) + 1): dV = np.abs(np.linalg.det(parallelepiped[:j, :j])) sqrtdetG = np.sqrt(np.abs(np.linalg.det(g[:j, :j]))) Nstars.append(sqrtdetG * dV) logging.debug( "Nstar for each dimension = {}".format( ", ".join(["{:1.1e}".format(n) for n in Nstars]) ) ) return np.max(Nstars)
import sys import numpy as np from numpy.testing import assert_allclose import pytest import lal import lalpulsar from lalpulsar import simulateCW as simCW # load Earth and Sun ephemerides earth_ephem_file = os.path.join(os.environ['LAL_TEST_PKGDATADIR'], 'earth00-19-DE405.dat.gz') sun_ephem_file = os.path.join(os.environ['LAL_TEST_PKGDATADIR'], 'sun00-19-DE405.dat.gz') ephemerides = lalpulsar.InitBarycenter(earth_ephem_file, sun_ephem_file) # amplitude parameters h0 = 1e-24 assume_sqrtSh = 1e-23 cosi = 0.123 psi = 2.345 phi0 = 3.210 # phase parameters freq = 10.0 fcmin = 5.0 fcmax = 15.0 f1dot = -1.35e-8 alpha = 6.12 delta = 1.02
def initialise_ephemeris( ephem="DE405", units="TCB", earthfile=None, sunfile=None, timefile=None, ssonly=False, timeonly=False, filenames=False, ): """ Download/read and return solar system ephemeris and time coordinate data. If files are provided these will be used and read. If not provided then, using supplied ``ephem`` and ``units`` values, it will first attempt to find files locally (either in your current path or in a path supplied by a ``LAL_DATA_PATH`` environment variable), and if not present will then attempt to download the files from a repository. To do ----- Add the ability to create ephemeris files using astropy. Parameters ---------- earthfile: str A file containing the Earth's position/velocity ephemeris sunfile: str A file containing the Sun's position/velocity ephemeris timefile: str A file containing time corrections for the TCB or TDB time coordinates. ephem: str The JPL ephemeris name, e.g., DE405 units: str The time coordinate system, which can be either "TDB" or "TCB" (TCB is the default). ssonly: bool If True only return the initialised solar system ephemeris data. Default is False. timeonly: bool If True only return the initialised time correction ephemeris data. Default is False. filenames: bool If True return the paths to the ephemeris files. Default is False. Returns ------- edat, sdat, filenames: The LAL EphemerisData object and TimeCorrectionData object. """ earth = "earth00-40-{}.dat.gz".format( ephem) if earthfile is None else earthfile sun = "sun00-40-{}.dat.gz".format(ephem) if sunfile is None else sunfile filepaths = [] if not timeonly: try: with MuteStream(): # get full file path earthf = lalpulsar.PulsarFileResolvePath(earth) sunf = lalpulsar.PulsarFileResolvePath(sun) edat = lalpulsar.InitBarycenter(earthf, sunf) filepaths = [edat.filenameE, edat.filenameS] except RuntimeError: # try downloading the ephemeris files try: efile = download_ephemeris_file( LAL_EPHEMERIS_URL.format(earth)) sfile = download_ephemeris_file(LAL_EPHEMERIS_URL.format(sun)) edat = lalpulsar.InitBarycenter(efile, sfile) filepaths = [efile, sfile] except Exception as e: raise IOError( "Could not read in ephemeris files: {}".format(e)) if ssonly: return (edat, filepaths) if filenames else edat unit = None if timefile is None: if units.upper() in ["TCB", "TDB"]: unit = dict(TCB="te405", TDB="tdb")[units.upper()] else: raise ValueError("units must be TCB or TDB") time = "{}_2000-2040.dat.gz".format(unit) if timefile is None else timefile try: with MuteStream(): # get full file path timef = lalpulsar.PulsarFileResolvePath(time) tdat = lalpulsar.InitTimeCorrections(timef) filepaths.append(timef) except RuntimeError: try: # try downloading the time coordinate file tfile = download_ephemeris_file(LAL_EPHEMERIS_URL.format(time)) tdat = lalpulsar.InitTimeCorrections(tfile) filepaths.append(tfile) except Exception as e: raise IOError( "Could not read in time correction file: {}".format(e)) if timeonly: return (tdat, filepaths) if filenames else tdat else: return (edat, tdat, filepaths) if filenames else (edat, tdat)
def initialise_ephemeris(ephem="DE405", units="TCB", earthfile=None, sunfile=None, timefile=None): """ Download/read and return solar system ephemeris and time coordinate data. If files are provided these will be used and read. If not provided then, using supplied ``ephem`` and ``units`` values, it will first attempt to find files locally (either in your current path or in a path supplied by a ``LAL_DATA_PATH`` environment variable), and if not present will then attempt to download the files from a repository. To do ----- Add the ability to create ephemeris files using astropy. Parameters ---------- earthfile: str A file containing the Earth's position/velocity ephemeris sunfile: str A file containing the Sun's position/velocity ephemeris timefile: str A file containing time corrections for the TCB or TDB time coordinates. ephem: str The JPL ephemeris name, e.g., DE405 units: str The time coordinate system, which can be either "TDB" or "TCB" (TCB is the default). """ DOWNLOAD_URL = "https://git.ligo.org/lscsoft/lalsuite/raw/master/lalpulsar/lib/{}" unit = None if timefile is None: if units.upper() in ["TCB", "TDB"]: unit = dict(TCB="te405", TDB="tdb")[units.upper()] else: raise ValueError("units must be TCB or TDB") earth = "earth00-40-{}.dat.gz".format( ephem) if earthfile is None else earthfile sun = "sun00-40-{}.dat.gz".format(ephem) if sunfile is None else sunfile time = "{}_2000-2040.dat.gz".format(unit) if timefile is None else timefile try: edat = lalpulsar.InitBarycenter(earth, sun) except RuntimeError: # try downloading the ephemeris files try: from astropy.utils.data import download_file efile = download_file(DOWNLOAD_URL.format(earth), cache=True) sfile = download_file(DOWNLOAD_URL.format(sun), cache=True) edat = lalpulsar.InitBarycenter(efile, sfile) except Exception as e: raise IOError("Could not read in ephemeris files: {}".format(e)) try: tdat = lalpulsar.InitTimeCorrections(time) except RuntimeError: try: # try downloading the time coordinate file from astropy.utils.data import download_file tfile = download_file(DOWNLOAD_URL.format(time), cache=True) tdat = lalpulsar.InitTimeCorrections(tfile) except Exception as e: raise IOError( "Could not read in time correction file: {}".format(e)) return edat, tdat
def __init__(self, tref, tstart, Tdata, waveform, dt_wf, phi0, psi, alpha, delta, det_name, earth_ephem_file="earth00-40-DE405.dat.gz", sun_ephem_file="sun00-40-DE405.dat.gz", tref_at_det=False, extra_comment=None): """ Initialise a continuous-wave signal simulator. @param tref: reference time of signal phase at Solar System barycentre, in GPS seconds (but see @b tref_at_det) @param tstart: start time of signal, in GPS seconds @param Tdata: total duration of signal, in seconds @param waveform: function which computes signal phase and amplitudes as functions of time: @b dphi, @b aplus, @b across = @b waveform(dt), where: @b dt = time since reference time @b tref; @b dphi = phase of signal at time @b dt relative to reference time @b tref, in radians; @b aplus = strain amplitude of plus polarisation at time @b dt; @b across = strain amplitude of cross polarisation at time @b dt @param dt_wf: sampling time of the function @c waveform; this need only be small enough to ensure that @c dphi, @c aplus, and @c across are smoothly interpolated, and does not need to make the desired sampling frequency of the output strain time series @param phi0: initial phase of the gravitational-wave signal at @b tstart, in radians @param psi: polarisation angle of the gravitational-wave source, in radians @param alpha: right ascension of the gravitational-wave source, in radians @param delta: declination of the gravitational-wave source, in radians @param det_name: name of the gravitational-wave detector to simulate a response for; e.g. @c "H1" for LIGO Hanford, @c "L1" for LIGO Livingston, @c "V1" for Virgo @param earth_ephem_file: name of file to load Earth ephemeris from @param sun_ephem_file: name of file to load Sun ephemeris from @param tref_at_det: default False; if True, shift reference time @b tref so that @b dt = 0 is @b tref in @e detector frame instead of Solar System barycentre frame, useful if e.g. one wants to turn on signal only for @b dt > 0, one can use @b tref as the turn-on time @param extra_comment: additional text to add to comment string in frame/SFT headers (not filenames), e.g. for wrapper script commandlines """ self.__origin_str = "Generated by %s, %s-%s (%s)" % (__file__, git_version.id, git_version.status, git_version.date) if extra_comment: self.__origin_str += ", "+extra_comment # store arguments self.__tstart = tstart self.__Tdata = Tdata # parse detector name try: _, self.__site_index = lalpulsar.FindCWDetector(det_name, True) assert(self.__site_index >= 0) except: raise ValueError("Invalid detector name det_name='%s'" % det_name) self.__site = lal.CachedDetectors[self.__site_index] # load Earth and Sun ephemerides self.__ephemerides = lalpulsar.InitBarycenter(earth_ephem_file, sun_ephem_file) if tref_at_det: # calculate barycentric delay at reference time bary_state = lalpulsar.EarthState() bary_input = lalpulsar.BarycenterInput() bary_emit = lalpulsar.EmissionTime() bary_input.tgps = tref bary_input.site = self.__site for i in range(0, 3): bary_input.site.location[i] /= lal.C_SI bary_input.alpha = alpha bary_input.delta = delta bary_input.dInv = 0.0 lalpulsar.BarycenterEarth(bary_state, bary_input.tgps, self.__ephemerides) lalpulsar.Barycenter(bary_emit, bary_input, bary_state) # adjust reference time so that dt = 0 is tref in detector frame tref += bary_emit.deltaT # start signal time series 'Tpad_wf' before/after output strain time series # add sufficient padding to signal for maximum Doppler modulation time shifts, otherwise # lalpulsar.PulsarSimulateCoherentGW() will output zeros without complaint (unless # you run with LAL_DEBUG_LEVEL=warning) Tpad_wf = 2.0 * lal.AU_SI / lal.C_SI tstart_wf = tstart - Tpad_wf Nwf = int(math.ceil(float(Tdata + 2*Tpad_wf) / float(dt_wf))) # create REAL8TimeSeries to store signal phase self.__phi = lal.CreateREAL8TimeSeries("phi", tstart_wf, 0, dt_wf, lal.DimensionlessUnit, Nwf) # create REAL4TimeVectorSeries to store signal amplitudes # - LAL provides no creator function for this type, so must be done manually self.__a = lal.REAL4TimeVectorSeries() self.__a.name = "a+,ax" self.__a.epoch = tstart_wf self.__a.deltaT = dt_wf self.__a.f0 = 0 self.__a.sampleUnits = lal.StrainUnit self.__a.data = lal.CreateREAL4VectorSequence(Nwf, 2) # call waveform() to fill time series of signal phase and amplitudes dt = float(tstart_wf - tref) for i in range(0, Nwf): dphi, aplus, across = waveform(dt) self.__phi.data.data[i] = phi0 + dphi self.__a.data.data[i][0] = aplus self.__a.data.data[i][1] = across dt += dt_wf # create and initialise PulsarCoherentGW struct self.__wf = lalpulsar.PulsarCoherentGW() self.__wf.position.system = lal.COORDINATESYSTEM_EQUATORIAL self.__wf.position.longitude = alpha self.__wf.position.latitude = delta self.__wf.psi = psi self.__wf.phi = self.__phi self.__wf.a = self.__a # create and initialise PulsarDetectorResponse struct self.__detector = lalpulsar.PulsarDetectorResponse() self.__detector.site = self.__site self.__detector.ephemerides = self.__ephemerides
def __init__(self): self.ephems = lalpulsar.InitBarycenter(*get_ephemeris_files())