Beispiel #1
0
 def __init__(self,
              initial_array,
              delta_f=None,
              epoch="",
              dtype=None,
              copy=True):
     if len(initial_array) < 1:
         raise ValueError('initial_array must contain at least one sample.')
     if delta_f is None:
         try:
             delta_f = initial_array.delta_f
         except AttributeError:
             raise TypeError(
                 'must provide either an initial_array with a delta_f attribute, or a value for delta_f'
             )
     if not delta_f > 0:
         raise ValueError('delta_f must be a positive number')
     # We gave a nonsensical default value to epoch so we can test if it's been set.
     # If the user passes in an initial_array that has an 'epoch' attribute and doesn't
     # pass in a value of epoch, then our new object's epoch comes from initial_array.
     # But if the user passed in a value---even 'None'---that will take precedence over
     # anything set in initial_array.  Finally, if the user passes in something without
     # an epoch attribute *and* doesn't pass in a value of epoch, it becomes 'None'
     if not isinstance(epoch, _lal.LIGOTimeGPS):
         if epoch == "":
             if isinstance(initial_array, FrequencySeries):
                 epoch = initial_array._epoch
             else:
                 epoch = _lal.LIGOTimeGPS(0)
         elif epoch is not None:
             try:
                 epoch = _lal.LIGOTimeGPS(epoch)
             except:
                 raise TypeError(
                     'epoch must be either None or a lal.LIGOTimeGPS')
     Array.__init__(self, initial_array, dtype=dtype, copy=copy)
     self._delta_f = delta_f
     self._epoch = epoch
Beispiel #2
0
def utc_midnight(gps):
	"""
	Truncate a LIGOTimeGPS to UTC midnight.
	"""
	# convert to UTC (as list so we can edit it)
	tm = list(lal.GPSToUTC(int(gps)))

	# truncate to midnight
	tm[3] = 0       # hours
	tm[4] = 0       # minutes
	tm[5] = 0       # seconds

	# convert back to LIGOTimeGPS
	return lal.LIGOTimeGPS(lal.UTCToGPS(tuple(tm)))
Beispiel #3
0
 def __init__(self,
              initial_array,
              delta_t,
              epoch=None,
              dtype=None,
              copy=True):
     """initial_array: array containing sampled data.
     delta_t: time between consecutive samples in seconds.
     epoch: time series start time in seconds. Must be a lal.LIGOTimeGPS object.
     """
     if len(initial_array) < 1:
         raise ValueError('initial_array must contain at least one sample.')
     if not delta_t > 0:
         raise ValueError('delta_t must be a positive number')
     if epoch is not None and not isinstance(epoch, _lal.LIGOTimeGPS):
         raise TypeError('epoch must be either None or a lal.LIGOTimeGPS')
     if epoch is None:
         epoch = _lal.LIGOTimeGPS(0, 0)
     else:
         epoch = _lal.LIGOTimeGPS(epoch)
     Array.__init__(self, initial_array, dtype=dtype, copy=copy)
     self._delta_t = delta_t
     self._epoch = epoch
Beispiel #4
0
    def to_lal_frequencyseries(self):
        """
        Output the frequency series strain data as a LAL FrequencySeries object.
        """

        laldata = lal.CreateCOMPLEX16FrequencySeries("",
                                                     lal.LIGOTimeGPS(self.start_time),
                                                     self.frequency_array[0],
                                                     (self.frequency_array[1] - self.frequency_array[0]),
                                                     lal.SecondUnit,
                                                     len(self.frequency_domain_strain))
        laldata.data.data[:] = self.frequency_domain_strain

        return laldata
Beispiel #5
0
    def to_pycbc_timeseries(self):
        """
        Output the time series strain data as a :class:`pycbc.types.timeseries.TimeSeries`.
        """

        try:
            import pycbc
        except ImportError:
            raise ImportError("Cannot output strain data as PyCBC TimeSeries")

        return pycbc.types.timeseries.TimeSeries(
            self.time_domain_strain,
            delta_t=(1. / self.sampling_frequency),
            epoch=lal.LIGOTimeGPS(self.start_time))
Beispiel #6
0
    def __init__(self, mass1, mass2, S, f_low, approximant, amplitude_order,
                 phase_order):
        """Create a TaylorF2 signal model with the given masses, PSD function
        S(f), PN amplitude order, and low-frequency cutoff."""

        if approximant == lalsimulation.TaylorF2:
            # Frequency-domain post-Newtonian inspiral waveform.
            h, _ = lalsimulation.SimInspiralChooseFDWaveform(
                0, 1, mass1 * lal.LAL_MSUN_SI, mass2 * lal.LAL_MSUN_SI, 0, 0,
                0, 0, 0, 0, f_low, 0, 1e6 * lal.LAL_PC_SI, 0, 0, 0, None, None,
                amplitude_order, 0, approximant)

            # Find indices of first and last nonzero samples.
            nonzero = np.nonzero(h.data.data)[0]
            first_nonzero = nonzero[0]
            last_nonzero = nonzero[-1]
        elif approximant == lalsimulation.TaylorT4:
            # Time-domain post-Newtonian inspiral waveform.
            hplus, hcross = lalsimulation.SimInspiralChooseTDWaveform(
                0, 1 / 4096, mass1 * lal.LAL_MSUN_SI, mass2 * lal.LAL_MSUN_SI,
                0, 0, 0, 0, 0, 0, f_low, f_low, 1e6 * lal.LAL_PC_SI, 0, 0, 0,
                None, None, amplitude_order, phase_order, approximant)

            hplus.data.data += hcross.data.data
            hplus.data.data /= np.sqrt(2)

            h = lal.CreateCOMPLEX16FrequencySeries(
                None, lal.LIGOTimeGPS(0), 0, 0, lal.lalDimensionlessUnit,
                len(hplus.data.data) // 2 + 1)
            plan = CreateForwardREAL8FFTPlan(len(hplus.data.data), 0)
            lal.REAL8TimeFreqFFT(h, hplus, plan)

            f = h.f0 + len(h.data.data) * h.deltaF
            first_nonzero = long(np.floor((f_low - h.f0) / h.deltaF))
            last_nonzero = long(np.ceil((2048 - h.f0) / h.deltaF))
            last_nonzero = min(last_nonzero, len(h.data.data) - 1)
        else:
            raise ValueError("unrecognized approximant")

        # Frequency sample points
        self.dw = 2 * np.pi * h.deltaF
        f = h.f0 + h.deltaF * np.arange(first_nonzero, last_nonzero + 1)
        self.w = 2 * np.pi * f

        # Throw away leading and trailing zeros.
        h = h.data.data[first_nonzero:last_nonzero + 1]

        self.denom_integrand = 4 / (2 * np.pi) * (np.square(h.real) +
                                                  np.square(h.imag)) / S(f)
        self.den = np.trapz(self.denom_integrand, dx=self.dw)
Beispiel #7
0
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

    freqfactor = 2.  # set frequency factor

    for det in t1output.keys():
        # convert into GPS times
        gpstimes = lalpulsar.CreateTimestampVector(len(t1output[det]))
        for i, time in enumerate(t1output[det][:, 0]):
            gpstimes.data[i] = lal.LIGOTimeGPS(time)

        detector = lalpulsar.GetSiteInfo(det)

        # set the response function look-up table
        dt = t1output[det][1, 0] - t1output[det][0, 0]  # time step
        resp = lalpulsar.DetResponseLookupTable(t1output[det][0, 0], detector,
                                                par['RAJ'], par['DECJ'], 2880,
                                                dt)

        # get the heterodyned file SSB delay
        hetSSBdelay = lalpulsar.HeterodynedPulsarGetSSBDelay(
            par.PulsarParameters(), gpstimes, detector, edat, tdat,
            lalpulsar.TIMECORRECTION_TCB)

        fullsignal = lalpulsar.HeterodynedPulsarGetModel(
            par.PulsarParameters(), freqfactor, 1, 0, 0, gpstimes, hetSSBdelay,
            0, None, 0, resp, edat, tdat, lalpulsar.TIMECORRECTION_TCB)

        # check output matches that from lalapps_pulsar_parameter_estimation_nested
        if np.any(
                np.abs(fullsignal.data.data.real -
                       t1output[det][:, 1]) > 1e-34):
            return False
        elif np.any(
                np.abs(fullsignal.data.data.imag -
                       t1output[det][:, 2]) > 1e-34):
            return False

    return True
Beispiel #8
0
    def parseTimeDelayDegeneracy(self, ifos, gpstime=lal.GPSTimeNow(),\
                                 dt=0.0005):

        # get detectors
        detectors = [cached_detector.get(prefix_to_name[ifo])\
                         for ifo in ifos]

        timeDelays = []
        degenerate = []

        new = table.new_from_template(self)
        for n, row in enumerate(self):
            # get all time delays for this point
            timeDelays.append([])
            for i in xrange(len(ifos)):
                for j in xrange(i + 1, len(ifos)):
                    timeDelays[n].append(lal.ArrivalTimeDiff(\
                                             detectors[i].location,\
                                             detectors[j].location,\
                                             row.longitude,\
                                             row.latitude,\
                                             lal.LIGOTimeGPS(gpstime)))
            # skip the first point
            if n == 0:
                degenerate.append(False)
                new.append(row)
                continue
            else:
                degenerate.append(True)
            # test this point against all others
            for i in xrange(0, n):
                # if check point is degenerate, skip
                if degenerate[i]:
                    continue
                # check each time delay individually
                for j in xrange(0, len(timeDelays[n])):
                    # if this time delay is non-degenerate the point is valid
                    if np.fabs(timeDelays[i][j] - timeDelays[n][j]) >= dt:
                        degenerate[n] = False
                        break
                    else:
                        degenerate[n] = True
                if degenerate[n]:
                    break

            if not degenerate[n]:
                new.append(row)

        return new
Beispiel #9
0
 def __init__(self, *args):
     self.context = context
     self.dtype = dtype
     self.odtype = odtype
     if _options['scheme'] == 'cpu':
         self.scheme = type(None)
     elif _options['scheme'] == 'cuda':
         self.scheme = pycbc.scheme.CUDAScheme
     else:
         self.scheme = pycbc.scheme.OpenCLScheme
     if epoch is None:
         self.epoch = lal.LIGOTimeGPS(0, 0)
     else:
         self.epoch = epoch
     unittest.TestCase.__init__(self, *args)
Beispiel #10
0
 def __init__(self,
              initial_array,
              delta_f,
              epoch=None,
              dtype=None,
              copy=True):
     """initial_array: array containing sampled data.
     delta_f: frequency between consecutive samples in Hertz.
     epoch: start time of the associated time domain data, in seconds.
            Must be a lal.LIGOTimeGPS object.
     """
     if len(initial_array) < 1:
         raise ValueError('initial_array must contain at least one sample.')
     if not delta_f > 0:
         raise ValueError('delta_f must be a positive number')
     if epoch is not None and not isinstance(epoch, _lal.LIGOTimeGPS):
         raise TypeError('epoch must be either None or a lal.LIGOTimeGPS')
     if epoch is None:
         epoch = _lal.LIGOTimeGPS(0, 0)
     else:
         epoch = _lal.LIGOTimeGPS(epoch)
     Array.__init__(self, initial_array, dtype=dtype, copy=copy)
     self._delta_f = delta_f
     self._epoch = epoch
Beispiel #11
0
    def test_coordframe_project_strain(self):
        """ Check consistency of project_strain() with skypoints in different cooordinate frames
        """

        coords = numpy.array([uniform(0,360), uniform(-90,90)])
        
        pt_eq = pb.skymaps.Skypoint(*numpy.radians(coords), COORD_SYS_EQUATORIAL)
        pt_geo = pt_eq.transformed_to(COORD_SYS_GEOGRAPHIC)
        
        d = pb.detectors.Detector(random.choice(DETECTORS))
    
        hplus = TimeSeries(SIN_1_SEC, sample_rate=SAMPLING_RATE).to_lal()
        hcross = TimeSeries(ZEROS_1_SEC, sample_rate=SAMPLING_RATE).to_lal()
        hplus.epoch = lal.LIGOTimeGPS(TIME)
        hcross.epoch = lal.LIGOTimeGPS(TIME)

        # Project wave onto detector
        response_eq = d.project_strain(hplus, hcross, pt_eq, 0)
        response_geo = d.project_strain(hplus, hcross, pt_geo, 0)

        err = numpy.abs(response_eq-response_geo)

        # self.assertEqual(response_eq, response_geo)
        self.assertTrue(numpy.allclose(numpy.abs(err), 0))
Beispiel #12
0
    def test_fplus_project_strain(self):
        """ Check consistency of project_strain() against antenna_pattern()
        """

        coords = numpy.array([uniform(0,360), uniform(-90,90)])
        psi = math.radians(uniform(0,180))
        
        pt_eq = pb.skymaps.Skypoint(*numpy.radians(coords), COORD_SYS_EQUATORIAL)
        d = pb.detectors.Detector(random.choice(DETECTORS))
        antenna_pat = d.antenna_pattern(pt_eq, time=TIME, psi=psi)
        
        hplus = TimeSeries(SIN_1_SEC, sample_rate=SAMPLING_RATE).to_lal()
        hcross = TimeSeries(ZEROS_1_SEC, sample_rate=SAMPLING_RATE).to_lal()
        hplus.epoch = lal.LIGOTimeGPS(TIME)
        hcross.epoch = lal.LIGOTimeGPS(TIME)
            
        # Project wave onto detector
        response = d.project_strain(hplus, hcross, pt_eq, psi)
                
        # Generate support timeseries
        data = TimeSeries(ZEROS_5_SEC, \
                          sample_rate=SAMPLING_RATE, \
                          t0=TIME-2, unit=response._unit)

        # Inject signal into timeseries
        h = data.inject(response)

        if antenna_pat[0] > 0:
            estimated_pat = h.max().to_value()
        else:
            estimated_pat = h.min().to_value()

        print("Exact antenna pattern = {} ; Estimated amplitude = {}".format(antenna_pat[0], estimated_pat))
            
        # Estimate delay from timeseries
        self.assertAlmostEqual(antenna_pat[0], estimated_pat, places=2)    
Beispiel #13
0
    def __init__(self,
                 initial_array,
                 delta_t=None,
                 epoch=None,
                 dtype=None,
                 copy=True):
        if len(initial_array) < 1:
            raise ValueError('initial_array must contain at least one sample.')
        if delta_t is None:
            try:
                delta_t = initial_array.delta_t
            except AttributeError:
                raise TypeError(
                    'must provide either an initial_array with a delta_t attribute, or a value for delta_t'
                )
        if not delta_t > 0:
            raise ValueError('delta_t must be a positive number')

        # Get epoch from initial_array if epoch not given (or is None)
        # If initialy array has no epoch, set epoch to 0.
        # If epoch is provided, use that.
        if not isinstance(epoch, _lal.LIGOTimeGPS):
            if epoch is None:
                if isinstance(initial_array, TimeSeries):
                    epoch = initial_array._epoch
                else:
                    epoch = _lal.LIGOTimeGPS(0)
            elif epoch is not None:
                try:
                    epoch = _lal.LIGOTimeGPS(epoch)
                except:
                    raise TypeError(
                        'epoch must be either None or a lal.LIGOTimeGPS')
        Array.__init__(self, initial_array, dtype=dtype, copy=copy)
        self._delta_t = delta_t
        self._epoch = epoch
Beispiel #14
0
 def test_injection_presence(self):
     """Verify presence of signals at expected times"""
     injections = InjectionSet(self.inj_file.name)
     for det in self.detectors:
         for inj in self.injections:
             ts = TimeSeries(numpy.zeros(int(10 * self.sample_rate)),
                             delta_t=1 / self.sample_rate,
                             epoch=lal.LIGOTimeGPS(inj.end_time - 5),
                             dtype=numpy.float64)
             injections.apply(ts, det.name)
             max_amp, max_loc = ts.abs_max_loc()
             # FIXME could test amplitude and time more precisely
             self.assertTrue(max_amp > 0 and max_amp < 1e-10)
             time_error = ts.sample_times.numpy()[max_loc] - inj.end_time
             self.assertTrue(abs(time_error) < 2 * self.earth_time)
Beispiel #15
0
    def to_pycbc_frequencyseries(self):
        """
        Output the frequency series strain data as a :class:`pycbc.types.frequencyseries.FrequencySeries`.
        """

        try:
            import pycbc
        except ImportError:
            raise ImportError(
                "Cannot output strain data as PyCBC FrequencySeries")

        return pycbc.types.frequencyseries.FrequencySeries(
            self.frequency_domain_strain,
            delta_f=(self.frequency_array[1] - self.frequency_array[0]),
            epoch=lal.LIGOTimeGPS(self.start_time))
Beispiel #16
0
def generate_PSD(psd_name="aLIGOZeroDetHighPower", length=None, delta_f=None):
    psd_list = get_lalsim_psd_list()

    if psd_name in psd_list:
        # print (psd_name)
        # Function for PSD
        func = lalsim.__dict__["SimNoisePSD" + psd_name + "Ptr"]
        # Generate a lal frequency series
        PSDseries = lal.CreateREAL8FrequencySeries("", lal.LIGOTimeGPS(0), 0,
                                                   delta_f,
                                                   lal.DimensionlessUnit,
                                                   length)
        # func(PSDseries)
        lalsim.SimNoisePSD(PSDseries, 0, func)
    return PSDseries
Beispiel #17
0
def to_lal_ligotimegps(gps):
    """Convert the given GPS time to a `lal.LIGOTimeGPS` object

    Parameters
    ----------
    gps : `~gwpy.time.LIGOTimeGPS`, `float`, `str`
        input GPS time, can be anything parsable by :meth:`~gwpy.time.to_gps`

    Returns
    -------
    ligotimegps : `lal.LIGOTimeGPS`
        a SWIG-LAL `~lal.LIGOTimeGPS` representation of the given GPS time
    """
    gps = to_gps(gps)
    return lal.LIGOTimeGPS(gps.gpsSeconds, gps.gpsNanoSeconds)
Beispiel #18
0
def gen_psd(fs, T_obs, op='AdvDesign', det='H1'):
    """ generates noise for a variety of different detectors

    Parameters
    ----------
    fs:
        sampling frequency
    T_obs:
        observation time window
    op:
        type of noise curve
    det:
        detector

    Returns
    -------
    psd:
        noise power spectral density
    """
    N = T_obs * fs  # the total number of time samples
    dt = 1 / fs  # the sampling time (sec)
    df = 1 / T_obs  # the frequency resolution
    psd = lal.CreateREAL8FrequencySeries(None, lal.LIGOTimeGPS(0), 0.0, df,
                                         lal.HertzUnit, N // 2 + 1)

    if det == 'H1' or det == 'L1':
        if op == 'AdvDesign':
            lalsimulation.SimNoisePSDAdVDesignSensitivityP1200087(psd, 10.0)
        elif op == 'AdvEarlyLow':
            lalsimulation.SimNoisePSDAdVEarlyLowSensitivityP1200087(psd, 10.0)
        elif op == 'AdvEarlyHigh':
            lalsimulation.SimNoisePSDAdVEarlyHighSensitivityP1200087(psd, 10.0)
        elif op == 'AdvMidLow':
            lalsimulation.SimNoisePSDAdVMidLowSensitivityP1200087(psd, 10.0)
        elif op == 'AdvMidHigh':
            lalsimulation.SimNoisePSDAdVMidHighSensitivityP1200087(psd, 10.0)
        elif op == 'AdvLateLow':
            lalsimulation.SimNoisePSDAdVLateLowSensitivityP1200087(psd, 10.0)
        elif op == 'AdvLateHigh':
            lalsimulation.SimNoisePSDAdVLateHighSensitivityP1200087(psd, 10.0)
        else:
            print 'unknown noise option'
            exit(1)
    else:
        print 'unknown detector - will add Virgo soon'
        exit(1)

    return psd
Beispiel #19
0
 def test_injection_absence(self):
     """Verify absence of signals outside known injection times"""
     clear_times = [
         self.injections[0].end_time - 86400,
         self.injections[-1].end_time + 86400
     ]
     injections = InjectionSet(self.inj_file.name)
     for det in self.detectors:
         for epoch in clear_times:
             ts = TimeSeries(numpy.zeros(int(10 * self.sample_rate)),
                             delta_t=1 / self.sample_rate,
                             epoch=lal.LIGOTimeGPS(epoch),
                             dtype=numpy.float64)
             injections.apply(ts, det.name)
             max_amp, max_loc = ts.abs_max_loc()
             self.assertEqual(max_amp, 0)
Beispiel #20
0
def get_PSD_from_xml(PSD_filename, df, f_min=15., f_max=1024.):
    "Gets the PSD from lal from an ASD file"
    PSD = lal.CreateREAL8FrequencySeries('PSD', lal.LIGOTimeGPS(0), 0.0, df,
                                         lal.SecondUnit,
                                         int(round(f_max / df)) + 1)

    #FIXME: how shall I read the PSD??
    lalsimulation.SimNoisePSDFromFile(PSD, f_min, filename)
    #see documentation here:
    #https://lscsoft.docs.ligo.org/lalsuite/lalsimulation/group___l_a_l_sim_noise_p_s_d__c.html#ga67d250556e4e8647c50d379364eb7911

    # SimNoisePSDFromFile expects ASD in the file, but this one
    # contains the PSD, so take the square root
    PSD.data.data = PSD.data.data**0.5

    return PSD
Beispiel #21
0
 def to_lal(self):
     """Convert this `TimeSeries` into a LAL TimeSeries.
     """
     import lal
     from ..utils.lal import (LAL_TYPE_STR_FROM_NUMPY, to_lal_unit)
     typestr = LAL_TYPE_STR_FROM_NUMPY[self.dtype.type]
     try:
         unit = to_lal_unit(self.unit)
     except ValueError as e:
         warnings.warn("%s, defaulting to lal.DimensionlessUnit" % str(e))
         unit = lal.DimensionlessUnit
     create = getattr(lal, 'Create%sTimeSeries' % typestr.upper())
     lalts = create(self.name, lal.LIGOTimeGPS(self.epoch.gps), 0,
                    self.dt.value, unit, self.size)
     lalts.data.data = self.value
     return lalts
Beispiel #22
0
 def fill_sim_inspiral_row(self, row):
     # using dummy values for many fields, should work for our purposes
     row.waveform = 'TaylorT4threePointFivePN'
     row.distance = self.distance
     total_mass = self.mass1 + self.mass2
     row.mass1 = self.mass1
     row.mass2 = self.mass2
     row.eta = self.mass1 * self.mass2 / total_mass**2
     row.mchirp = total_mass * row.eta**(3. / 5.)
     row.latitude = self.latitude
     row.longitude = self.longitude
     row.inclination = self.inclination
     row.polarization = self.polarization
     row.phi0 = 0
     row.f_lower = 20
     row.f_final = lal.C_SI ** 3 / \
             (6. ** (3. / 2.) * lal.PI * lal.G_SI * total_mass)
     row.spin1x = row.spin1y = row.spin1z = 0
     row.spin2x = row.spin2y = row.spin2z = 0
     row.alpha1 = 0
     row.alpha2 = 0
     row.alpha3 = 0
     row.alpha4 = 0
     row.alpha5 = 0
     row.alpha6 = 0
     row.alpha = 0
     row.beta = 0
     row.theta0 = 0
     row.psi0 = 0
     row.psi3 = 0
     row.geocent_end_time = int(self.end_time)
     row.geocent_end_time_ns = int(1e9 *
                                   (self.end_time - row.geocent_end_time))
     row.end_time_gmst = lal.GreenwichMeanSiderealTime(
         lal.LIGOTimeGPS(self.end_time))
     for d in 'lhvgt':
         row.__setattr__('eff_dist_' + d, row.distance)
         row.__setattr__(d + '_end_time', row.geocent_end_time)
         row.__setattr__(d + '_end_time_ns', row.geocent_end_time_ns)
     row.amp_order = 0
     row.coa_phase = 0
     row.bandpass = 0
     row.taper = self.taper
     row.numrel_mode_min = 0
     row.numrel_mode_max = 0
     row.numrel_data = None
     row.source = 'ANTANI'
Beispiel #23
0
    def times(self, times):
        """
        Set an array of times, and also a ``LIGOTimeGPSVector()`` containing
        the times.

        Parameters
        ----------
        times: array_like
            An array of GPS times. This can be a :class:`astropy.time.Time`
            object, for which inputs will be converted to GPS is not already
            held as GPS times.
        """

        from astropy.time import Time

        if times is None:
            self.__times = None
            self.__gpstimes = None
            return
        elif isinstance(times, lal.LIGOTimeGPS):
            self.__times = np.array(
                [times.gpsSeconds + 1e-9 * times.gpsNanoSeconds], dtype=np.float128
            )
            self.__gpstimes = lalpulsar.CreateTimestampVector(1)
            self.__gpstimes.data[0] = times
            return
        elif isinstance(times, lalpulsar.LIGOTimeGPSVector):
            self.__gpstimes = times
            self.__times = np.zeros(len(times.data), dtype=np.float128)
            for i in range(len(times.data)):
                self.__times[i] = (
                    times.data[i].gpsSeconds + 1e-9 * times.data[i].gpsNanoSeconds
                )
            return
        elif isinstance(times, (int, float, np.float128, list, tuple, np.ndarray)):
            self.__times = np.atleast_1d(np.array(times, dtype=np.float128))
        elif isinstance(times, Time):
            self.__times = np.atleast_1d(times.gps).astype(np.float128)
        else:
            raise TypeError("Unknown data type for times")

        self.__gpstimes = lalpulsar.CreateTimestampVector(len(self.__times))
        for i, time in enumerate(self.__times):
            seconds = int(np.floor(time))
            nanoseconds = int((time - seconds) * 1e9)
            self.__gpstimes.data[i] = lal.LIGOTimeGPS(seconds, nanoseconds)
Beispiel #24
0
def getPSD(deltaF, npts, psd="SimNoisePSDaLIGOZeroDetHighPowerPtr"):
    """
    deltaF :: The frequency interval between data points.
    npts   :: Total number of date points
    psd    :: The noise model in lalsimulation. To get info use
              lalsim.__dict__ in interpretor and search string SimNoisePSD
    """
    lalseries = lal.CreateREAL8FrequencySeries('', lal.LIGOTimeGPS(0), 0,
                                               deltaF, lal.DimensionlessUnit,
                                               npts)
    func = lalsim.__dict__[psd]
    lalsim.SimNoisePSD(lalseries, 0, func)
    f_end = lalseries.f0 + len(lalseries.data.data) * lalseries.deltaF
    freq = np.linspace(lalseries.f0, f_end, len((lalseries.data.data)))
    output = np.vstack((freq, lalseries.data.data)).T

    return output
Beispiel #25
0
  def get_coincs_from_coire(self,files,stat='snr'):
    """
    uses CoincInspiralUtils to get data from old-style (coire'd) coincs
    """
    coincTrigs = CoincInspiralUtils.coincInspiralTable()
    inspTrigs = SnglInspiralUtils.ReadSnglInspiralFromFiles(files, \
                                  mangle_event_id = True,verbose=None)
    statistic = CoincInspiralUtils.coincStatistic(stat,None,None)
    coincTrigs = CoincInspiralUtils.coincInspiralTable(inspTrigs,statistic)

    try:
      inspInj = SimInspiralUtils.ReadSimInspiralFromFiles(files)
      coincTrigs.add_sim_inspirals(inspInj)
    #FIXME: name the exception!
    except:
      pass

    #now extract the relevant information into CoincData objects
    for ctrig in coincTrigs:
      coinc = CoincData()
      coinc.set_ifos(ctrig.get_ifos()[1])
      coinc.set_gps(dict((trig.ifo,lal.LIGOTimeGPS(trig.get_end())) for trig in ctrig))
      coinc.set_snr(dict((trig.ifo,getattr(ctrig,trig.ifo).snr) for trig in ctrig))
      coinc.set_effDs(dict((trig.ifo,getattr(ctrig,trig.ifo).eff_distance) for trig in ctrig))
      coinc.set_masses(dict((trig.ifo,getattr(ctrig,trig.ifo).mass1) for trig in ctrig), \
                       dict((trig.ifo,getattr(ctrig,trig.ifo).mass2) for trig in ctrig))
      
      try:
        effDs_inj = {}
        for ifo in coinc.ifo_list:
          if ifo == 'H1':
            effDs_inj[ifo] = getattr(ctrig,'sim').eff_dist_h
          elif ifo == 'L1':
            effDs_inj[ifo] = getattr(ctrig,'sim').eff_dist_l
          elif ifo == 'V1':
            effDs_inj[ifo] = getattr(ctrig,'sim').eff_dist_v
        dist_inj = getattr(ctrig,'sim').distance
        coinc.set_inj_params(getattr(ctrig,'sim').latitude,getattr(ctrig,'sim').longitude, \
                             getattr(ctrig,'sim').mass1,getattr(ctrig,'sim').mass2,dist_inj,effDs_inj)
        coinc.is_injection = True
        #FIXME: name the exception!
      except:
        pass
      
      self.append(coinc)
Beispiel #26
0
def MaxTimeDelayLine3(ifo1, ifo2, ra, dec, gpstime=None, n=3):
    """
        Alternative implementation of MaxTimeDelayLine.
    """

    if gpstime:
        gpstime = lal.LIGOTimeGPS(gpstime)

    p = SkyPosition()
    p.longitude = ra
    p.latitude = dec
    p.system = 'equatorial'
    p.probability = None
    p.solid_angle = None
    if gpstime:
        p = EquatorialToGeographic(p, gpstime)
    cart = SphericalToCartesian(p)

    # get baseline
    detectors = [cached_detector.get(prefix_to_name[ifo])\
                 for ifo in [ifo1,ifo2]]
    baseline = detectors[0].location - detectors[1].location
    baseline = baseline / np.linalg.norm(baseline)

    # get angular spacing
    dtheta = lal.TWOPI / n

    # get axis and angle of rotation
    north = np.array([0, 0, 1])
    axis = np.cross(cart, baseline)
    axis = axis / np.linalg.norm(axis)
    R = _rotation(axis, dtheta)

    # set up list
    l = SkyPositionTable()
    # append central point
    l.append(p)

    for i in xrange(1, n):
        l.append(l[i - 1].rotate(R))

    if gpstime:
        for i, p in enumerate(l):
            l[i] = GeographicToEquatorial(p, gpstime)
    return l
Beispiel #27
0
        def __init__(self, name, ref_time=None):
            """
            name -- name of the coordinate system
            ref_time: reference time for sky-fixed coordinate systems
            ref_time is None for the Earth-fixed (geocentric) coordinate system.
            """

            self.name = name
            assert self.is_valid(), "Unsupported coordinate system"
            
            if name=='geographic':
                assert ref_time is None, \
                    'ref_time must be None for Earth-fixed coordinate system'
            else:
                assert ref_time is not None, \
                    'ref_time must be provided for sky-fixed coordinate systems'
            
            self.ref_time = lal.LIGOTimeGPS(ref_time) if ref_time is not None else None
Beispiel #28
0
def apply_taper(TimeSeries, newlen=16384):
    """
    Smoothly taper the start of the data in TimeSeries using LAL tapering
    routines

    Also zero pads
    """

    # Create and populate lal time series
    tmp = lal.CreateREAL8TimeSeries('tmp', lal.LIGOTimeGPS(), 0.0,
                                    TimeSeries.delta_t, lal.StrainUnit, newlen)
    #TimeSeries.delta_t, lal.StrainUnit, len(TimeSeries))
    tmp.data.data = np.zeros(newlen)
    tmp.data.data[0:len(TimeSeries)] = TimeSeries.data

    # Taper
    lalsim.SimInspiralREAL8WaveTaper(tmp.data, lalsim.SIM_INSPIRAL_TAPER_START)

    return pycbc.types.TimeSeries(tmp.data.data, delta_t=TimeSeries.delta_t)
Beispiel #29
0
    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
Beispiel #30
0
    def __getitem__(self, coinc_id):
        template_id = self.template_ids[coinc_id]
        timeslide_id = self.timeslide_ids[coinc_id]
        template = [col[template_id] for col in self.bank]

        trigger_ids = [
            trigger_ids[coinc_id] for trigger_ids in self.trigger_ids
        ]

        return [
            self.SnglInspiral(
                trigger_id, ifo, triggers[0][trigger_id],
                triggers[1][trigger_id],
                lal.LIGOTimeGPS(triggers[2][trigger_id] +
                                (timeslide_id *
                                 self.timeslide_interval if i == 0 else 0)),
                *template)
            for i, (trigger_id, ifo, triggers
                    ) in enumerate(zip(trigger_ids, self.ifos, self.triggers))
        ]