Exemple #1
0
    def filter_psd(self, segment_duration, delta_f, flow):
        """ Calculate the power spectral density of this time series.

        Use the `pycbc.psd.welch` method to estimate the psd of this time segment.
        The psd is then truncated in the time domain to the segment duration
        and interpolated to the requested sample frequency.

        Parameters
        ----------
        segment_duration: float
            Duration in seconds to use for each sample of the spectrum.
        delta_f : float
            Frequency spacing to return psd at.
        flow : float
            The low frequency cutoff to apply when truncating the inverse
            spectrum.

        Returns
        -------
        psd : FrequencySeries
            Frequency series containing the estimated PSD.
        """
        from pycbc.psd import interpolate, inverse_spectrum_truncation
        p = self.psd(segment_duration)
        samples = int(round(p.sample_rate * segment_duration))
        p = interpolate(p, delta_f)
        return inverse_spectrum_truncation(p,
                                           samples,
                                           low_frequency_cutoff=flow,
                                           trunc_method='hann')
Exemple #2
0
    def setUp(self):
        ###### Get data for references analysis of 170817
        m = Merger("GW170817")
        ifos = ['H1', 'V1', 'L1']
        self.psds = {}
        self.data = {}

        for ifo in ifos:
            print("Processing {} data".format(ifo))

            # Download the gravitational wave data for GW170817
            url = "https://dcc.ligo.org/public/0146/P1700349/001/"
            url += "{}-{}1_LOSC_CLN_4_V1-1187007040-2048.gwf"
            fname = download_file(url.format(ifo[0], ifo[0]), cache=True)
            ts = read_frame(fname,
                            "{}:LOSC-STRAIN".format(ifo),
                            start_time=int(m.time - 260),
                            end_time=int(m.time + 40))
            ts = highpass(ts, 15.0)
            ts = resample_to_delta_t(ts, 1.0 / 2048)
            ts = ts.time_slice(m.time - 112, m.time + 16)
            self.data[ifo] = ts.to_frequencyseries()

            psd = interpolate(ts.psd(4), ts.delta_f)
            psd = inverse_spectrum_truncation(psd,
                                              int(4 * psd.sample_rate),
                                              trunc_method='hann',
                                              low_frequency_cutoff=20.0)
            self.psds[ifo] = psd

        self.static = {
            'mass1': 1.3757,
            'mass2': 1.3757,
            'f_lower': 20.0,
            'approximant': "TaylorF2",
            'polarization': 0,
            'ra': 3.44615914,
            'dec': -0.40808407,
            'tc': 1187008882.42840,
        }
        self.variable = (
            'distance',
            'inclination',
        )
        self.flow = {'H1': 25, 'L1': 25, 'V1': 25}
        inclination_prior = SinAngle(inclination=None)
        distance_prior = Uniform(distance=(10, 100))
        tc_prior = Uniform(tc=(m.time - 0.1, m.time + 0.1))
        self.prior = JointDistribution(self.variable, inclination_prior,
                                       distance_prior)

        ###### Expected answers
        # Answer taken from marginalized gaussian model
        self.q1 = {'distance': 42.0, 'inclination': 2.5}
        self.a1 = 541.8235746138382

        # answer taken from brute marginize pol + phase
        self.a2 = 542.581
        self.pol_samples = 200
Exemple #3
0
    def whiten(self, segment_duration, max_filter_duration, trunc_method='hann',
                     remove_corrupted=True, low_frequency_cutoff=None,
                     return_psd=False, **kwds):
        """ Return a whitened time series

        Parameters
        ----------
        segment_duration: float
            Duration in seconds to use for each sample of the spectrum.
        max_filter_duration : int
            Maximum length of the time-domain filter in seconds.
        trunc_method : {None, 'hann'}
            Function used for truncating the time-domain filter.
            None produces a hard truncation at `max_filter_len`.
        remove_corrupted : {True, boolean}
            If True, the region of the time series corrupted by the whitening
            is excised before returning. If false, the corrupted regions
            are not excised and the full time series is returned.
        low_frequency_cutoff : {None, float}
            Low frequency cutoff to pass to the inverse spectrum truncation.
            This should be matched to a known low frequency cutoff of the
            data if there is one.
        return_psd : {False, Boolean}
            Return the estimated and conditioned PSD that was used to whiten
            the data.
        kwds : keywords
            Additional keyword arguments are passed on to the `pycbc.psd.welch` method.

        Returns
        -------
        whitened_data : TimeSeries
            The whitened time series
        """
        from pycbc.psd import inverse_spectrum_truncation, interpolate
        # Estimate the noise spectrum
        psd = self.psd(segment_duration, **kwds)
        psd = interpolate(psd, self.delta_f)
        max_filter_len = int(max_filter_duration * self.sample_rate)

        # Interpolate and smooth to the desired corruption length
        psd = inverse_spectrum_truncation(psd,
                   max_filter_len=max_filter_len,
                   low_frequency_cutoff=low_frequency_cutoff,
                   trunc_method=trunc_method)

        # Whiten the data by the asd
        white = (self.to_frequencyseries() / psd**0.5).to_timeseries()

        if remove_corrupted:
            white = white[int(max_filter_len/2):int(len(self)-max_filter_len/2)]

        if return_psd:
            return white, psd

        return white
Exemple #4
0
def make(conditioned, template, fc, mc, hc, grafica):

    #	We use 4 second samles of our time series in Welch method.
    psd = conditioned.psd(4)

    #	Now that we have the psd we need to interpolate it to match our data
    #	and then limit the filter length of 1 / PSD. After this, we can
    #	directly use this PSD to filter the data in a controlled manner

    psd = interpolate(psd, conditioned.delta_f)

    psd = inverse_spectrum_truncation(psd,
                                      4 * conditioned.sample_rate,
                                      low_frequency_cutoff=fc)

    psd_o = psd

    snr = matched_filter(template,
                         conditioned,
                         psd=psd,
                         low_frequency_cutoff=fc)
    sigmasq = sigma(template, psd, low_frequency_cutoff=fc)

    #print 'Rho_0'
    #print sigmasq

    #	Remove time corrupted by the template filter and the psd filter
    #	We remove 4 seonds at the beginning and end for the PSD filtering
    #	And we remove 4 additional seconds at the beginning to account for
    #	the template length (this is somewhat generous for
    #	so short a template). A longer signal such as from a BNS, would
    #	require much more padding at the beginning of the vector.
    snr = snr.crop(4, 4)

    if grafica == 1:

        pylab.figure('Matched_filter_output')
        pylab.title('Matched filter output')
        pylab.grid()
        pylab.plot(snr.sample_times, abs(snr))

        pylab.ylabel('Signal-to-noise ratio')
        pylab.xlabel('Time (s)')
        pylab.show()

    peak = abs(snr).numpy().argmax()
    snrp = snr[peak]
    time = snr.sample_times[peak]

    #print 'Tiempo de SNR máximo'
    #print time
    #print 'SNR recuperado'
    #print abs(snrp)

    return snr, psd, peak, time, snrp, psd_o, sigmasq
Exemple #5
0
    def whiten(self, segment_duration, max_filter_duration, trunc_method='hann',
                     remove_corrupted=True, low_frequency_cutoff=None,
                     return_psd=False, **kwds):
        """ Return a whitened time series

        Parameters
        ----------
        segment_duration: float
            Duration in seconds to use for each sample of the spectrum.
        max_filter_duration : int
            Maximum length of the time-domain filter in seconds.
        trunc_method : {None, 'hann'}
            Function used for truncating the time-domain filter.
            None produces a hard truncation at `max_filter_len`.
        remove_corrupted : {True, boolean}
            If True, the region of the time series corrupted by the whitening
            is excised before returning. If false, the corrupted regions
            are not excised and the full time series is returned.
        low_frequency_cutoff : {None, float}
            Low frequency cutoff to pass to the inverse spectrum truncation.
            This should be matched to a known low frequency cutoff of the
            data if there is one.
        return_psd : {False, Boolean}
            Return the estimated and conditioned PSD that was used to whiten
            the data.
        kwds : keywords
            Additional keyword arguments are passed on to the `pycbc.psd.welch` method.

        Returns
        -------
        whitened_data : TimeSeries
            The whitened time series
        """
        from pycbc.psd import inverse_spectrum_truncation, interpolate
        # Estimate the noise spectrum
        psd = self.psd(segment_duration, **kwds)
        psd = interpolate(psd, self.delta_f)
        max_filter_len = int(max_filter_duration * self.sample_rate)

        # Interpolate and smooth to the desired corruption length
        psd = inverse_spectrum_truncation(psd,
                   max_filter_len=max_filter_len,
                   low_frequency_cutoff=low_frequency_cutoff,
                   trunc_method=trunc_method)

        # Whiten the data by the asd
        white = (self.to_frequencyseries() / psd**0.5).to_timeseries()

        if remove_corrupted:
            white = white[int(max_filter_len/2):int(len(self)-max_filter_len/2)]

        if return_psd:
            return white, psd

        return white
Exemple #6
0
    def setUp(self, *args):
        self.context = _context
        self.scheme = _scheme
        self.tolerance = 1e-6
        xr = numpy.random.uniform(low=-1, high=1.0, size=2**20)
        xi = numpy.random.uniform(low=-1, high=1.0, size=2**20)
        self.x = Array(xr + xi * 1.0j, dtype=complex64)
        self.z = zeros(2**20, dtype=float32)
        for i in range(0, 4):
            trusted_accum(self.z, self.x)

        m = Merger("GW170814")

        ifos = ['H1', 'L1', 'V1']
        data = {}
        psd = {}
        for ifo in ifos:
            # Read in and condition the data and measure PSD
            ts = m.strain(ifo).highpass_fir(15, 512)
            data[ifo] = resample_to_delta_t(ts, 1.0 / 2048).crop(2, 2)
            p = data[ifo].psd(2)
            p = interpolate(p, data[ifo].delta_f)
            p = inverse_spectrum_truncation(p,
                                            int(2 * data[ifo].sample_rate),
                                            low_frequency_cutoff=15.0)
            psd[ifo] = p
        hp, _ = get_fd_waveform(approximant="IMRPhenomD",
                                mass1=31.36,
                                mass2=31.36,
                                f_lower=20.0,
                                delta_f=data[ifo].delta_f)
        hp.resize(len(psd[ifo]))

        # For each ifo use this template to calculate the SNR time series
        snr = {}
        snr_unnorm = {}
        norm = {}
        corr = {}
        for ifo in ifos:
            snr_unnorm[ifo], corr[ifo], norm[ifo] = \
                matched_filter_core(hp, data[ifo], psd=psd[ifo],
                                    low_frequency_cutoff=20)
            snr[ifo] = snr_unnorm[ifo] * norm[ifo]

        self.snr = snr
        self.snr_unnorm = snr_unnorm
        self.norm = norm
        self.corr = corr
        self.hp = hp
        self.data = data
        self.psd = psd
        self.ifos = ifos
Exemple #7
0
    def scale(template, noise, SNR):

        template_size = len(template)
        template.resize(time_duration * f_sample)
        psd = noise.psd(1)
        psd = interpolate(psd, template.delta_f)
        sigma = matchedfilter.sigma(template,
                                    psd=psd,
                                    low_frequency_cutoff=f_min)
        amplitude = SNR / (sigma)
        template *= amplitude
        template.resize(template_size)

        return template, amplitude
Exemple #8
0
    def setUp(self,*args):
        self.context = _context
        self.scheme = _scheme
        self.tolerance = 1e-6
        xr = numpy.random.uniform(low=-1, high=1.0, size=2**20)
        xi = numpy.random.uniform(low=-1, high=1.0, size=2**20)
        self.x = Array(xr + xi * 1.0j, dtype=complex64)
        self.z = zeros(2**20, dtype=float32)
        for i in range(0, 4):
            trusted_accum(self.z, self.x)

        m = Merger("GW170814")

        ifos = ['H1', 'L1', 'V1']
        data = {}
        psd = {}
        for ifo in ifos:
            # Read in and condition the data and measure PSD
            ts = m.strain(ifo).highpass_fir(15, 512)
            data[ifo] = resample_to_delta_t(ts, 1.0/2048).crop(2, 2)
            p = data[ifo].psd(2)
            p = interpolate(p, data[ifo].delta_f)
            p = inverse_spectrum_truncation(p, 2 * data[ifo].sample_rate,
                                            low_frequency_cutoff=15.0)
            psd[ifo] = p
        hp, _ = get_fd_waveform(approximant="IMRPhenomD",
                                 mass1=31.36, mass2=31.36,
                                 f_lower=20.0, delta_f=data[ifo].delta_f)
        hp.resize(len(psd[ifo]))

        # For each ifo use this template to calculate the SNR time series
        snr = {}
        snr_unnorm = {}
        norm = {}
        corr = {}
        for ifo in ifos:
            snr_unnorm[ifo], corr[ifo], norm[ifo] = \
                matched_filter_core(hp, data[ifo], psd=psd[ifo],
                                    low_frequency_cutoff=20)
            snr[ifo] = snr_unnorm[ifo] * norm[ifo]

        self.snr = snr
        self.snr_unnorm = snr_unnorm
        self.norm = norm
        self.corr = corr
        self.hp = hp
        self.data = data
        self.psd = psd
        self.ifos = ifos
Exemple #9
0
def signal_whiten(psd, signal, segment_duration, max_filter_duration, 
                  trunc_method='hann', low_frequency_cutoff=None):
    # Estimate the noise spectrum, no need for segment_duration, because we already get in line 193.
    psd = interpolate(psd, signal.delta_f)
    max_filter_len = int(max_filter_duration * signal.sample_rate)

    # Interpolate and smooth to the desired corruption length
    psd = inverse_spectrum_truncation(psd,
               max_filter_len=max_filter_len,
               low_frequency_cutoff=low_frequency_cutoff,
               trunc_method=trunc_method)

    # Whiten the data by the asd
    white = (signal.to_frequencyseries() / psd**0.5).to_timeseries()
    return white
def whiten_data(strain_list, psd, low_freq_cutoff=20.0):
    org_type = type(strain_list)
    if not org_type == list:
        strain_list = [strain_list]

    #set to strain[0].delta_f
    DF = 1.0 / strain_list[0].delta_t / (
        4 * strain_list[0].sample_rate
    )  #This is the definition of delta_f from the TimeSeries.whiten in the welchs method.
    #set to len(strain_list[0]) / 2 + 1
    F_LEN = int(4 * strain_list[0].sample_rate / 2 + 1)
    get_hyper_waveform_defaults
    low_freq_diff = 20
    if low_freq_cutoff > low_freq_diff:
        tmp_psd = aLIGOZeroDetHighPower(length=F_LEN,
                                        delta_f=DF,
                                        low_freq_cutoff=low_freq_cutoff -
                                        low_freq_diff)
    else:
        tmp_psd = aLIGOZeroDetHighPower(length=F_LEN,
                                        delta_f=DF,
                                        low_freq_cutoff=0)

    for i in range(len(strain_list)):
        max_filter_len = int(
            4 * strain_list[i].sample_rate)  #To replicate TimeSeries.whiten
        tmp_psd_2 = interpolate(
            tmp_psd, strain_list[i].delta_f)  #To replicate TimeSeries.whiten
        tmp_psd_2 = inverse_spectrum_truncation(
            tmp_psd_2,
            max_filter_len=max_filter_len,
            low_frequency_cutoff=low_freq_cutoff,
            trunc_method='hann')
        strain_list[i] = (strain_list[i].to_frequencyseries() /
                          tmp_psd_2**0.5).to_timeseries()
        strain_list[i] = strain_list[i][int(float(max_filter_len) / 2):int(
            len(strain_list[i]) -
            float(max_filter_len) / 2)]  #To replicate TimeSeries.whiten

    if not org_type == list:
        return (strain_list[0])
    else:
        return (strain_list)
def whiten_data_new(strain_list,
                    low_freq_cutoff=20.,
                    max_filter_duration=4.,
                    psd=None):
    org_type = type(strain_list)
    if not org_type == list:
        strain_list = [strain_list]

    ret = []
    for strain in strain_list:
        df = strain.delta_f
        f_len = int(len(strain) / 2) + 1
        if psd is None:
            psd = aLIGOZeroDetHighPower(length=f_len,
                                        delta_f=df,
                                        low_freq_cutoff=low_freq_cutoff - 2.)
        else:
            if not len(psd) == f_len:
                msg = 'Length of PSD does not match data.'
                raise ValueError(msg)
            elif not psd.delta_f == df:
                psd = interpolate(psd, df)
        max_filter_len = int(
            max_filter_duration *
            strain.sample_rate)  #Cut out the beginning and end
        psd = inverse_spectrum_truncation(psd,
                                          max_filter_len=max_filter_len,
                                          low_frequency_cutoff=low_freq_cutoff,
                                          trunc_method='hann')
        f_strain = strain.to_frequencyseries()
        kmin = int(low_freq_cutoff / df)
        f_strain.data[:kmin] = 0
        f_strain.data[-1] = 0
        f_strain.data[kmin:] /= psd[kmin:]**0.5
        strain = f_strain.to_timeseries()
        ret.append(strain[max_filter_len:len(strain) - max_filter_len])

    if not org_type == list:
        return (ret[0])
    else:
        return (ret)
frange = [1230, 1240]  # frequency range (Hz)
taurange = [0.06, 0.07]  # Quality factor ranges
mm = 0.03  # maximum mismatch
tb = ringdown.RingdownTemplateBank(frange, taurange=taurange, mm=mm)
flow = lowcutoff

# get the initial chunk of data to matched filter - let's get four seconds
# after ignoring the first two seconds due to the filter response
respbuffer = 2
chunkdur = 4
inidata = pycbcdata.crop(respbuffer, duration - (respbuffer + chunkdur))
initilde = inidata.to_frequencyseries()

# get the psd using the whole data segment (using 128 / 16 length segments)
psd = pycbcdata.filter_psd(128 / 16, (8 / samplerate), flow)
psd = interpolate(psd, initilde.delta_f)

# perform matched filtering
for i, waveform in enumerate(
        tb.generate_waveforms(domain="frequency", deltaf=initilde.delta_f)):
    hp, hc = waveform

    hp.resize(len(initilde))
    snr = pycbc.filter.matched_filter(hp,
                                      initilde,
                                      psd=psd,
                                      low_frequency_cutoff=flow)

    # remove regions corrupted by filter wraparound (see https://pycbc.org/pycbc/latest/html/gw150914.html#calculate-the-signal-to-noise)
    snr = snr[len(snr) // 4:len(snr) * 3 // 4]
injected_ts_highpass = highpass(signal_and_noise, 0.01)

#crop to avoid filter wraparound
conditioned = injected_ts_highpass.crop(2,2)

#display to check for excessive wraparound -> increase crop length
# plt.figure()
# plt.plot(conditioned.sample_times, conditioned, label='conditioned data for matched filter')
# plt.xlabel('times (s)')
# plt.ylabel('Noise + hidden signal strain amplitude')
# plt.legend()ju
# plt.show()

#make sure noise psd is of same delta_f as the noise data timeseries
signal_and_noise_psd = welch_function.pycbc_welch(conditioned, 15)
grace_psd = psd.interpolate(welch_function.pycbc_welch(merged_noise_ts.copy(), 15), conditioned.delta_f)
#grace_psd = psd.interpolate(welch_function.pycbc_welch(signal_and_noise.copy(), 15), conditioned.delta_f)
#sig_n_c = signal_and_noise_psd.copy()
#grace_psd = psd.interpolate(sig_n_c, conditioned.delta_f)

plt.figure()
plt.loglog(grace_psd.sample_frequencies, np.sqrt(grace_psd), label='noise model asd with no signal')
plt.loglog(signal_and_noise_psd.sample_frequencies, np.sqrt(signal_and_noise_psd), label='signal and noise asd')
plt.loglog(grace_freqs, grace_asd, label='gracefo asd')

plt.legend()
plt.xlabel('frequency (Hz)')
plt.ylabel('strain amplitude spectral density (1/sqrt(Hz))')
plt.grid()
#plt.show()
Exemple #14
0
def snr_distance_plotter_wf_self_generating(mass1, mass2, f_lower_bound, dt,
                                            theta, distance_array, noise_psd):

    snr_values_pycbc_welch = []
    snr_values_fft = []
    snr_values_scipy_welch = []

    for r in distance_array:
        times, plus_strain, cross_strain = q_c_py2.obs_time_inspiral_strain(
            mass1, mass2, f_lower_bound, dt, r, theta)

        h_ts = types.timeseries.TimeSeries(plus_strain, dt)

        #find psd via welch-------------------------------------------------------------------------------------------
        h_fs_pycbc = welch_function.pycbc_welch(
            h_ts.copy(), 15)  #15 is number of segments used

        #interpolate the larger df of the two to match
        h_fs_pycbc = psd.interpolate(h_fs_pycbc, noise_psd.delta_f)

        #calculate snr
        psd_ratio_pycbc_welch = (4.0 * h_fs_pycbc) / (noise_psd)
        snr_squared_pycbc_welch = psd_ratio_pycbc_welch.sum()
        snr_estimate_pycbc_welch = np.sqrt(snr_squared_pycbc_welch)

        #add to snr list
        snr_values_pycbc_welch.append(snr_estimate_pycbc_welch)

        #find psd via fft--------------------------------------------------------------------------------------------

        #take fft and calculate psd
        freqs = np.fft.fftfreq(np.size(h_ts))
        mask = freqs > 0
        raw_fft_h_ts = np.fft.fft(h_ts.copy())
        psd_of_h_ts = 2.0 * (np.abs(raw_fft_h_ts / float(np.size(h_ts))))**2.0

        #turn psd to frequencyseries with df of fftfreqs
        fft_psd = types.frequencyseries.FrequencySeries(
            psd_of_h_ts[mask], delta_f=(1.0 / float(h_ts.duration)))

        fft_psd = psd.interpolate(fft_psd, noise_psd.delta_f)

        psd_ratio_fft = (4.0 * fft_psd) / (noise_psd[:-2])
        snr_squared_fft = psd_ratio_fft.sum()
        snr_estimate_fft = np.sqrt(snr_squared_fft)
        snr_values_fft.append(snr_estimate_fft)

        #find psd via scipy welch------------------------------------------------------------------------------------
        f_s = 10  #sampling frequency
        frequency_array, sp_welch_psd = welch_function.scipy_welch(
            h_ts.copy(), f_s, 15)  #15 to match the pycbc welch segment #

        sp_welch_psd = types.frequencyseries.FrequencySeries(
            sp_welch_psd, delta_f=(frequency_array[1] - frequency_array[0]))

        sp_welch_psd = psd.interpolate(sp_welch_psd, noise_psd.delta_f)

        psd_ratio_sp_welch = (4.0 * sp_welch_psd) / (noise_psd)
        snr_squared_sp_welch = psd_ratio_sp_welch.sum()
        snr_estimate_sp_welch = np.sqrt(snr_squared_sp_welch)
        snr_values_scipy_welch.append(snr_estimate_sp_welch)

    plt.loglog(distance_array, snr_values_fft, label='fft')
    plt.loglog(distance_array, snr_values_pycbc_welch, label='pycbc welch')
    plt.loglog(distance_array, snr_values_scipy_welch, label='scipy welch')
    plt.grid()
    plt.xlabel('distance in pc')
    plt.ylabel('snr')
    plt.legend(loc="upper right")
    plt.show()

    return snr_values_pycbc_welch, snr_values_fft, snr_values_scipy_welch


#Note to self, build function that takes in the waveform as an input parameter instead of generating it
Exemple #15
0
from pycbc.filter import highpass_fir, lowpass_fir
from pycbc.psd import welch, interpolate
from pycbc.types import TimeSeries
try:
    from urllib.request import urlretrieve
except ImportError:  # python < 3
    from urllib import urlretrieve

# Read data and remove low frequency content
fname = 'H-H1_LOSC_4_V2-1126259446-32.gwf'
url = "https://www.gw-openscience.org/GW150914data/" + fname
urlretrieve(url, filename=fname)
h1 = highpass_fir(read_frame(fname, 'H1:LOSC-STRAIN'), 15.0, 8)

# Calculate the noise spectrum and whiten
psd = interpolate(welch(h1), 1.0 / 32)
white_strain = (h1.to_frequencyseries() / psd ** 0.5 * psd.delta_f).to_timeseries()

# remove some of the high and low frequencies
smooth = highpass_fir(white_strain, 25, 8)
smooth = lowpass_fir(white_strain, 250, 8)

#strech out and shift the frequency upwards to aid human hearing
fdata = smooth.to_frequencyseries()
fdata.roll(int(1200 / fdata.delta_f))
smooth = TimeSeries(fdata.to_timeseries(), delta_t=1.0/1024)

#Take slice around signal
smooth = smooth[len(smooth)/2 - 1500:len(smooth)/2 + 3000]
smooth.save_to_wav('gw150914_h1_chirp.wav')
Exemple #16
0
def generate_sample(static_arguments,
                    event_tuple,
                    waveform_params=None):
    """
    Generate a single sample (or example) by taking a piece of LIGO
    background noise (real or synthetic, depending on `event_tuple`),
    optionally injecting a simulated waveform (depending on
    `waveform_params`) and post-processing the result (whitening,
    band-passing).
    
    Args:
        static_arguments (dict): A dictionary containing global
            technical parameters for the sample generation, for example
            the target_sampling_rate of the output.
        event_tuple (tuple): A tuple `(event_time, file_path)`, which
            specifies the GPS time at which to make an injection and
            the path of the HDF file which contains said GPS time.
            If `file_path` is `None`, synthetic noise will be used
            instead and the `event_time` only serves as a seed for
            the corresponding (random) noise generator.
        waveform_params (dict): A dictionary containing the randomly
            sampled parameters that are passed as inputs to the
            waveform model (e.g., the masses, spins, position, ...).

    Returns:
        A tuple `(sample, injection_parameters)`, which contains the
        generated `sample` itself (a dict with keys `{'event_time',
        'h1_strain', 'l1_strain'}`), and the `injection_parameters`,
        which are either `None` (in case no injection was made), or a
        dict containing the `waveform_params` and some additional
        parameters (e.g., single detector SNRs).
    """

    # -------------------------------------------------------------------------
    # Define shortcuts for some elements of self.static_arguments
    # -------------------------------------------------------------------------

    # Read out frequency-related arguments
    original_sampling_rate = static_arguments['original_sampling_rate']
    target_sampling_rate = static_arguments['target_sampling_rate']
    f_lower = static_arguments['f_lower']
    delta_f = static_arguments['delta_f']
    fd_length = static_arguments['fd_length']

    # Get the width of the noise sample that we either select from the raw
    # HDF files, or generate synthetically
    noise_interval_width = static_arguments['noise_interval_width']

    # Get how many seconds before and after the event time to use
    seconds_before_event = static_arguments['seconds_before_event']
    seconds_after_event = static_arguments['seconds_after_event']

    # Get the event time and the dict containing the HDF file path
    event_time, hdf_file_paths = event_tuple

    # -------------------------------------------------------------------------
    # Get the background noise (either from data or synthetically)
    # -------------------------------------------------------------------------

    # If the event_time is None, we generate synthetic noise
    if hdf_file_paths is None:

        # Create an artificial PSD for the noise
        # TODO: Is this the best choice for this task?
        psd = aLIGOZeroDetHighPower(length=fd_length,
                                    delta_f=delta_f,
                                    low_freq_cutoff=f_lower)

        # Actually generate the noise using the PSD and LALSimulation
        noise = dict()
        for i, det in enumerate(('H1', 'L1')):

            # Compute the length of the noise sample in time steps
            noise_length = noise_interval_width * target_sampling_rate

            # Generate the noise for this detector
            noise[det] = noise_from_psd(length=noise_length,
                                        delta_t=(1.0 / target_sampling_rate),
                                        psd=psd,
                                        seed=(2 * event_time + i))

            # Manually fix the noise start time to match the fake event time.
            # However, for some reason, the correct setter method seems broken?
            start_time = event_time - noise_interval_width / 2
            # noinspection PyProtectedMember
            noise[det]._epoch = LIGOTimeGPS(start_time)

    # Otherwise we select the noise from the corresponding HDF file
    else:

        kwargs = dict(hdf_file_paths=hdf_file_paths,
                      gps_time=event_time,
                      interval_width=noise_interval_width,
                      original_sampling_rate=original_sampling_rate,
                      target_sampling_rate=target_sampling_rate,
                      as_pycbc_timeseries=True)
        noise = get_strain_from_hdf_file(**kwargs)

    # -------------------------------------------------------------------------
    # If applicable, make an injection
    # -------------------------------------------------------------------------

    # If no waveform parameters are given, we are not making an injection.
    # In this case, there are no detector signals and no injection
    # parameters, and the strain is simply equal to the noise
    if waveform_params is None:
        detector_signals = None
        output_signals = None
        injection_parameters = None
        output_signals = None
        strain = noise

    # Otherwise, we need to simulate a waveform for the given waveform_params
    # and add it into the noise to create the strain
    else:

        # ---------------------------------------------------------------------
        # Simulate the waveform with the given injection parameters
        # ---------------------------------------------------------------------

        # Actually simulate the waveform with these parameters
        waveform = get_waveform(static_arguments=static_arguments,
                                waveform_params=waveform_params)

        # Get the detector signals by projecting on the antenna patterns
        detector_signals = \
            get_detector_signals(static_arguments=static_arguments,
                                 waveform_params=waveform_params,
                                 event_time=event_time,
                                 waveform=waveform)
        # Store the output_signal
        output_signals = {}
        output_signals = detector_signals.copy()

        # ---------------------------------------------------------------------
        # Add the waveform into the noise as is to calculate the NOMF-SNR
        # ---------------------------------------------------------------------

        # Store the dummy strain, the PSDs and the SNRs for the two detectors
        strain_ = {}
        psds = {}
        snrs = {}

        # Calculate these quantities for both detectors
        for det in ('H1', 'L1'):

            # Add the simulated waveform into the noise to get the dummy strain
            strain_[det] = noise[det].add_into(detector_signals[det])

            # Estimate the Power Spectral Density from the dummy strain, this 1 is the psd segment duration of the strain
            psds[det] = strain_[det].psd(1)
            psds[det] = interpolate(psds[det], delta_f=delta_f)

            # Use the PSD estimate to calculate the optimal matched
            # filtering SNR for this injection and this detector
            snrs[det] = sigma(htilde=detector_signals[det],
                              psd=psds[det],
                              low_frequency_cutoff=f_lower)

        # Calculate the network optimal matched filtering SNR for this
        # injection (which we need for scaling to the chosen injection SNR)
        nomf_snr = np.sqrt(snrs['H1']**2 + snrs['L1']**2)

        # ---------------------------------------------------------------------
        # Add the waveform into the noise with the chosen injection SNR
        # ---------------------------------------------------------------------

        # Compute the rescaling factor
        #injection_snr = waveform_params['injection_snr']
        injection_snr = static_arguments['injection_snr']
        scale_factor = 1.0 * injection_snr / nomf_snr

        strain = {}
        for det in ('H1', 'L1'):

            # Add the simulated waveform into the noise, using a scaling
            # factor to ensure that the resulting NOMF-SNR equals the chosen
            # injection SNR
            strain[det] = noise[det].add_into(scale_factor *
                                              detector_signals[det])
            output_signals[det] = scale_factor * output_signals[det]

        # ---------------------------------------------------------------------
        # Store some information about the injection we just made
        # ---------------------------------------------------------------------

        # Store the information we have computed ourselves
        injection_parameters = {'scale_factor': scale_factor,
                                'h1_snr': snrs['H1'],
                                'l1_snr': snrs['L1']}

        # Also add the waveform parameters we have sampled
        for key, value in waveform_params.iteritems():
            injection_parameters[key] = value

    # -------------------------------------------------------------------------
    # Whiten and bandpass the strain (also for noise-only samples)
    # -------------------------------------------------------------------------

    for det in ('H1', 'L1'):

        # Get the whitening parameters
        segment_duration = static_arguments['whitening_segment_duration']
        max_filter_duration = static_arguments['whitening_max_filter_duration']

        # Whiten the strain (using the built-in whitening of PyCBC)
        # We don't need to remove the corrupted samples here, because we
        # crop the strain later on
        strain[det] = \
            strain[det].whiten(segment_duration=segment_duration,
                               max_filter_duration=max_filter_duration,
                               remove_corrupted=False)
        
        if waveform_params is not None:
            output_signals[det] = \
                signal_whiten(psd = psds[det], 
                              signal = output_signals[det], 
                              segment_duration = segment_duration, 
                              max_filter_duration = max_filter_duration)
    
        # Get the limits for the bandpass
        bandpass_lower = static_arguments['bandpass_lower']
        bandpass_upper = static_arguments['bandpass_upper']

        # Apply a high-pass to remove everything below `bandpass_lower`;
        # If bandpass_lower = 0, do not apply any high-pass filter.
        if bandpass_lower != 0:
            strain[det] = strain[det].highpass_fir(frequency=bandpass_lower,
                                                   remove_corrupted=False,
                                                   order=512)
            if waveform_params is not None:
                output_signals[det] = output_signals[det].highpass_fir(frequency=bandpass_lower,
                                                       remove_corrupted=False,
                                                       order=512)

        # Apply a low-pass filter to remove everything above `bandpass_upper`.
        # If bandpass_upper = sampling rate, do not apply any low-pass filter.
        if bandpass_upper != target_sampling_rate:
            strain[det] = strain[det].lowpass_fir(frequency=bandpass_upper,
                                                  remove_corrupted=False,
                                                  order=512)
            if waveform_params is not None:
                output_signals[det] = output_signals[det].lowpass_fir(frequency=bandpass_upper,
                                                      remove_corrupted=False,
                                                      order=512)

    # -------------------------------------------------------------------------
    # Cut strain (and signal) time series to the pre-specified length
    # -------------------------------------------------------------------------

    for det in ('H1', 'L1'):

        # Define some shortcuts for slicing
        a = event_time - seconds_before_event
        b = event_time + seconds_after_event

        # Cut the strain to the desired length
        strain[det] = strain[det].time_slice(a, b)

        # If we've made an injection, also cut the simulated signal
        if waveform_params is not None:

            # Cut the detector signals to the specified length
            detector_signals[det] = detector_signals[det].time_slice(a, b)
            output_signals[det] = output_signals[det].time_slice(a, b)

            # Also add the detector signals to the injection parameters
            injection_parameters['h1_signal'] = \
                np.array(detector_signals['H1'])
            injection_parameters['l1_signal'] = \
                np.array(detector_signals['L1'])
            
            injection_parameters['h1_output_signal'] = \
                np.array(output_signals['H1'])
            injection_parameters['l1_output_signal'] = \
                np.array(output_signals['L1'])

    # -------------------------------------------------------------------------
    # Collect all available information about this sample and return results
    # -------------------------------------------------------------------------

    # The whitened strain is numerically on the order of O(1), so we can save
    # it as a 32-bit float (unlike the original signal, which is down to
    # O(10^-{30}) and thus requires 64-bit floats).
    sample = {'event_time': event_time,
              'h1_strain': np.array(strain['H1']).astype(np.float32),
              'l1_strain': np.array(strain['L1']).astype(np.float32)}

    return sample, injection_parameters
from pycbc.filter import highpass_fir, lowpass_fir, matched_filter
from pycbc.waveform import get_fd_waveform
from pycbc.psd import welch, interpolate
import urllib
import pylab

for ifo in ['H1', 'L1']:
    # Read data and remove low frequency content
    fname = '%s-%s_LOSC_4_V2-1126259446-32.gwf' % (ifo[0], ifo)
    url = "https://losc.ligo.org/s/events/GW150914/" + fname
    urllib.urlretrieve(url, filename=fname)
    h1 = read_frame(fname, '%s:LOSC-STRAIN' % ifo)
    h1 = highpass_fir(h1, 15, 8)

    # Calculate the noise spectrum
    psd = interpolate(welch(h1), 1.0 / h1.duration)

    # whiten
    white_strain = (h1.to_frequencyseries() / psd ** 0.5 * psd.delta_f).to_timeseries()

    # remove some of the high and low
    smooth = highpass_fir(white_strain, 35, 8)
    smooth = lowpass_fir(white_strain, 300, 8)

    # time shift and flip L1
    if ifo == 'L1':
        smooth *= -1
        smooth.roll(int(.007 / smooth.delta_t))

    pylab.plot(smooth.sample_times, smooth, label=ifo)
Exemple #18
0
from pycbc.frame import read_frame
from pycbc.filter import highpass_fir, matched_filter
from pycbc.waveform import get_fd_waveform
from pycbc.psd import welch, interpolate
import urllib

# Read data and remove low frequency content
fname = 'H-H1_LOSC_4_V2-1126259446-32.gwf'
url = "https://www.gw-openscience.org/GW150914data/" + fname
urllib.urlretrieve(url, filename=fname)
h1 = read_frame('H-H1_LOSC_4_V2-1126259446-32.gwf', 'H1:LOSC-STRAIN')
h1 = highpass_fir(h1, 15, 8)

# Calculate the noise spectrum
psd = interpolate(welch(h1), 1.0 / h1.duration)

# Generate a template to filter with
hp, hc = get_fd_waveform(approximant="IMRPhenomD",
                         mass1=40,
                         mass2=32,
                         f_lower=20,
                         delta_f=1.0 / h1.duration)
hp.resize(len(h1) / 2 + 1)

# Calculate the complex (two-phase SNR)
snr = matched_filter(hp, h1, psd=psd, low_frequency_cutoff=20.0)

# Remove regions corrupted by filter wraparound
snr = snr[len(snr) / 4:len(snr) * 3 / 4]

import pylab
Exemple #19
0
def whiten_data(strain_list,
                low_freq_cutoff=20.,
                max_filter_duration=4.,
                psd=None):
    """Returns the data whitened by the PSD.
    
    Arguments
    ---------
    strain_list : list of pycbc.TimeSeries or pycbc.TimeSeries
        The data that should be whitened.
    low_freq_cutoff : {float, 20.}
        The lowest frequency that is considered during calculations. It
        must be >= than the lowest frequency where the PSD is not zero.
        Unit: hertz
    max_filter_duration : {float, 4.}
        The duration to which the PSD is truncated to in the
        time-domain. The amount of time is removed from both the
        beginning and end of the input data to avoid wrap-around errors.
        Unit: seconds
    psd : {None or pycbc.FrequencySeries, None}
        The PSD that should be used to whiten the data. If set to None
        the pycbc.psd.aLIGOZeroDetHighPower PSD will be used. If a PSD
        is provided which does not fit the delta_f of the data, it will
        be interpolated to fit.
    
    Returns
    -------
    list of pycbc.TimeSeries or TimeSeries
        Depending on the input type it will return a list of TimeSeries
        or a single TimeSeries. The data contained in this time series
        is the whitened input data, where the inital and final seconds
        as specified by max_filter_duration are removed.
    """
    org_type = type(strain_list)
    if not org_type == list:
        strain_list = [strain_list]

    ret = []
    for strain in strain_list:
        df = strain.delta_f
        f_len = int(len(strain) / 2) + 1
        if psd is None:
            psd = aLIGOZeroDetHighPower(length=f_len,
                                        delta_f=df,
                                        low_freq_cutoff=low_freq_cutoff - 2.)
        else:
            if not len(psd) == f_len:
                msg = 'Length of PSD does not match data.'
                raise ValueError(msg)
            elif not psd.delta_f == df:
                psd = interpolate(psd, df)
        max_filter_len = int(
            max_filter_duration *
            strain.sample_rate)  #Cut out the beginning and end
        psd = inverse_spectrum_truncation(psd,
                                          max_filter_len=max_filter_len,
                                          low_frequency_cutoff=low_freq_cutoff,
                                          trunc_method='hann')
        f_strain = strain.to_frequencyseries()
        kmin = int(low_freq_cutoff / df)
        f_strain.data[:kmin] = 0
        f_strain.data[-1] = 0
        f_strain.data[kmin:] /= psd[kmin:]**0.5
        strain = f_strain.to_timeseries()
        ret.append(strain[max_filter_len:len(strain) - max_filter_len])

    if not org_type == list:
        return (ret[0])
    else:
        return (ret)
hp, hc = get_td_waveform(approximant='SEOBNRv4_opt',
                         mass1=mass,
                         mass2=mass,
                         delta_t=delta_t,
                         f_lower=25,
                         distance=100)
noise = generate_noise(time_duration, delta_f, delta_t, f_min)

merger_time = (1 / 4096) * hp.numpy().argmax()
snr = 20

hp_size = len(hp)
hp.resize(time_duration * f_sample)
psd = noise.psd(4)
psd = interpolate(psd, hp.delta_f)
sigma = matchedfilter.sigma(hp, psd=psd, low_frequency_cutoff=f_min)
Amplitude = snr / (sigma)

hp *= Amplitude

hp.resize(hp_size)
merger_time = 69
merger_index = int(69 / delta_t) + 1
start_index = merger_index + len(hp)
waveform = TimeSeries(numpy.zeros(len(noise)), delta_t=delta_t, \
        dtype=real_same_precision_as(noise))

waveform[merger_index:start_index] = hp

signal = noise + waveform
Exemple #21
0
  # Read the detector data and remove low frequencycontent
  strain[ifo] = highpass(ts,15)
  # Remove time corrupted by the high pass filter
  strain[ifo] = strain[ifo].crop(4,4)
  # Also create a frequency domain version of the data
  stilde[ifo] = strain[ifo].to_frequencyseries()
  #print (strain.delta_t)
  pylab.plot(strain['H1'].sample_times, strain['H1'])
  pylab.xlabel('Time (s)')
  pylab.show()

from pycbc.psd import interpolate, inverse_spectrum_truncation
psds = {}
for ifo in ['L1','H1']:
# Calculate a psd from the data. We'll use 2s segments in a median -welch style estimate# We then interpolate the PSD to the desired frequencystep.
  psds[ifo] = interpolate(strain[ifo].psd(2), stilde[ifo].delta_f)
# We explicitly control how much data will be corruptedbyoverwhitening the data later on# In this case we choose 2 seconds.
  psds[ifo] = inverse_spectrum_truncation(psds[ifo],int(2*strain[ifo].sample_rate),low_frequency_cutoff=15.0,trunc_method='hann')
  pylab.loglog(psds[ifo].sample_frequencies, psds[ifo],label=ifo)
  pylab.xlim(20,1024)
  pylab.ylim(1e-47,1e-42)
pylab.legend()

from pycbc.waveform import get_fd_waveform
from pycbc.filter import matched_filter
from pycbc.conversions import mass1_from_mchirp_q
import numpy
# We will try different component masses and see whichgives us thelargest
masses = numpy.arange(1.3,1.5,.01)
# Variables to store when we've found the max
hmax, smax, tmax, mmax, nsnr = None, {}, {},0,0
Exemple #22
0
def fake_noisyGW(tab_waveform, seed, run, fs):
    nbr_sec = 15
    nbr_sec_begin = 7
    nbr_sec_end = 8
    NFFT = 1 * fs
    fmin = 15
    fmax = 200000
    print("########################")
    print("creation of noisy signal")
    tab_whiten = []
    tab_snr = []
    random.seed(seed)
    for i in tqdm(range(0, len(tab_waveform))):
        #creation of the fake noise
        seed_local = random.randint(1, 1000)
        fake_noise = fake_gaussian_noise(nbr_sec, seed_local, fs, fmin)
        # injection of GW into the noise
        noisyGW = np.empty([len(fake_noise)])
        # creation of the template (for SNR)
        template = np.zeros([len(fake_noise)
                             ])  # idem pure_GW but with GW in the end(for SNR)
        # creation of pureGW (no use exept plot)
        pureGW = np.zeros([len(fake_noise)])  #pure GW in nbr_sec of 0
        # injection of GW into noise
        k = 0
        for j in range(0, len(fake_noise)):
            if j >= fs * nbr_sec_begin and j < fs * nbr_sec_end:
                noisyGW[j] = fake_noise[j] + tab_waveform[i][0][k]
                pureGW[j] = tab_waveform[i][0][k]
                k = k + 1
            else:
                noisyGW[j] = fake_noise[j]
                pureGW[j] = 0
        # creation of the template
        k = 0
        for j in range(0, len(fake_noise)):
            if j < len(fake_noise) - len(tab_waveform[i][0]):
                template[j] = 0
            else:
                template[j] = tab_waveform[i][0][k]
                k += 1

        ########## the calcule of the SNR ##############
        # First we have to calculate the SNR (the following step is neccessary)
        # we calculate the SNR of noisy GW
        noisyGW_timeseries = TimeSeries(noisyGW, delta_t=tab_waveform[i][17])
        # we need to calculate again the psd
        # we use just 4 sec of data to calulate psd (weltch method)
        psd = noisyGW_timeseries.psd(4)
        # we need to interpolate our psd on all data
        psd = interpolate(psd, noisyGW_timeseries.delta_f)
        # we need to inform that the noise was creat with a lowfrequency cutoff
        psd = inverse_spectrum_truncation(psd,
                                          4 * noisyGW_timeseries.sample_rate,
                                          low_frequency_cutoff=fmin)

        #Second we calcule the SNR
        # we calculate the SNR
        template_timeseries = TimeSeries(template, delta_t=tab_waveform[i][17])
        noisyGW_timeseries = TimeSeries(noisyGW, delta_t=tab_waveform[i][17])
        if template.max(0) == 0:
            snrp = 0
            tab_snr = tab_snr + [snrp]
        else:
            snr = matched_filter(template_timeseries,
                                 noisyGW_timeseries,
                                 psd=psd,
                                 low_frequency_cutoff=fmin)
            #  4+1 sec remove at the begining of SNR and 4 seconde remove at the end
            # +1 is because the length of the template is one sec
            snr = snr.crop(4 + 1, 4)
            peak = abs(snr).numpy().argmax()
            snrp = snr[peak]
            tab_snr = tab_snr + [abs(snrp)]

        # on fait le withening
        # I) methode pycbc
        # data and then flattening the frequency response.
        # (1) The first option sets the duration in seconds of each
        #     sample of the data used as part of the PSD estimate.
        # (2) The second option sets the duration of the filter to apply
        #whitened = noisyGW_timeseries.whiten(15, 4)
        # on fait aussi un bandpass
        #whitened_bp = whitened.highpass_fir(30, 512).lowpass_fir(250, 512)
        # le whitening pycbc donne meme chose mais modifie la longueur
        # par facilite je reprends l autre whitening

        # II) method numpy
        Pxx, freqs = mlab.psd(noisyGW,
                              Fs=freq,
                              NFFT=NFFT,
                              noverlap=NFFT / 2,
                              window=np.blackman(NFFT))
        # We will use interpolations of the ASDs computed above for whitening:
        psd_numpy = interp1d(freqs, Pxx)
        whitened = whitening(noisyGW, psd_numpy, tab_waveform[i][17])
        # We need to suppress the high frequencies with some bandpassing:
        high_freq = 600.
        low_freq = fmin
        bb, ab = butter(4, [low_freq * 2. / fs, high_freq * 2. / fs],
                        btype='band')
        whitened_bp = filtfilt(bb, ab, whitened)

        # Select the secon containing the GW
        withen_bp_onesec = np.empty([fs])
        for j in range(0, len(withen_bp_onesec)):
            withen_bp_onesec[j] = whitened_bp[nbr_sec_begin * fs + j]
        tab_whiten = tab_whiten + [withen_bp_onesec]
        '''
		######################################################################
		### PLOT this is no necessary is just to be sure everithing is OK ###
		# just some  plot to see if everything looks fine
		temps = np.empty([len(fake_noise)])
		for tps in range(0, len(fake_noise)):
			temps[tps] = tps

		temps_onesec = np.empty([len(tab_waveform[i][0])])
		for tps in range(0, len(tab_waveform[i][0])):
			temps_onesec[tps] = tps
		
		# noisy GW
		plt.figure("noisyGW")
		plt.plot(temps, noisyGW, 'b')
		plt.plot(temps, pureGW, 'r')
		plt.show()
		# template 
		plt.figure("template")
		plt.plot(temps, template, 'r')
		plt.show()
		# the GW
		plt.figure("template")
		plt.plot(temps_onesec, tab_waveform[i][0], 'r')
		plt.show()	
		# psd 
		plt.figure("psd")
		plt.loglog(psd.sample_frequencies, psd)
		pylab.xlim(10, 2048)
		pylab.show()
		# SNR
		plt.figure("SNR")
		pylab.plot(snr.sample_times, abs(snr))
		pylab.grid()
		pylab.show()
		# Whitening
		whitened_bp = TimeSeries(whitened_bp, delta_t=tab_waveform[i][17])
		plt.figure("whitening")
		pylab.plot(whitened_bp.sample_times, whitened_bp)
		#pylab.xlim(7,8)
		pylab.grid()
		pylab.show()
		#whitening onesec
		whiten_bp_onesec_timeseries = TimeSeries(withen_bp_onesec, delta_t=tab_waveform[i][17])
		plt.figure("whitening_one_sec")
		pylab.plot(whiten_bp_onesec_timeseries.sample_times, whiten_bp_onesec_timeseries)
		pylab.xlim(0.6, 1.0)
		pylab.grid()
		pylab.show()
		###################################################################
		'''
    tab_snr = np.asarray(tab_snr)
    tab_whiten = np.asarray(tab_whiten)
    # we create the big array (with all the parameters,...)
    tab_waveformnoisy = copy.deepcopy(tab_waveform)
    for i in range(0, len(tab_waveformnoisy)):
        tab_waveformnoisy[i][0] = tab_whiten[i]

    return tab_waveformnoisy, tab_snr
Exemple #23
0
def get_chirp_time_region(trigger_params,
                          psd,
                          miss_match,
                          f_lower=30.,
                          f_max=2048.,
                          f_ref=30.):
    central_param = copy.deepcopy(trigger_params)
    # if central_param['approximant'] == 'SPAtmplt':
    central_param['approximant'] == 'TaylorF2RedSpin'
    # if not ('tau0' and 'tau3' in central_param):
    #     t0, t3 = pnu.mass1_mass2_to_tau0_tau3(central_param['mass1'], central_param['mass2'], f_ref)
    # else:
    #     t0 = central_param['tau0']
    #     t3 = central_param['tau3']
    # for tau0 boundary
    newt0, newt3 = temp_tau0_tau3_with_valid_dtau0(central_param['tau0'],
                                                   central_param['tau3'],
                                                   f_ref)
    temp_param0 = temp_param_from_central_param(central_param, newt0, newt3,
                                                f_ref)
    # for tau3 boundary
    newt0, newt3 = temp_tau0_tau3_with_valid_dtau3(central_param['tau0'],
                                                   central_param['tau3'],
                                                   f_ref)
    temp_param3 = temp_param_from_central_param(central_param, newt0, newt3,
                                                f_ref)

    tlen = pnu.nearest_larger_binary_number(
        max([central_param['tau0'], temp_param0['tau0'], temp_param3['tau0']]))
    df = 1.0 / tlen
    flen = int(f_max / df) + 1

    # hp = pt.zeros(flen, dtype=pt.complex64)
    # hp0 = pt.zeros(flen, dtype=pt.complex64)
    # hp3 = pt.zeros(flen, dtype=pt.complex64)

    # print central_param['approximant']

    # if central_param['approximant'] == 'SPAtmplt':
    #     central_param['approximant'] == 'TaylorF2RedSpin'
    # hp = pw.get_waveform_filter(hp, central_param, delta_f=df, f_lower=f_lower, f_ref=f_ref, f_final=f_max)
    # hp0 = pw.get_waveform_filter(hp0, temp_param0, delta_f=df, f_lower=f_lower, f_ref=f_ref, f_final=f_max)
    # hp3 = pw.get_waveform_filter(hp3, temp_param3, delta_f=df, f_lower=f_lower, f_ref=f_ref, f_final=f_max)
    # else:
    hp, hc = pw.get_fd_waveform(central_param,
                                delta_f=df,
                                f_lower=f_lower,
                                f_ref=f_ref,
                                f_final=f_max)
    hp0, hc0 = pw.get_fd_waveform(temp_param0,
                                  delta_f=df,
                                  f_lower=f_lower,
                                  f_ref=f_ref,
                                  f_final=f_max)
    hp3, hc3 = pw.get_fd_waveform(temp_param3,
                                  delta_f=df,
                                  f_lower=f_lower,
                                  f_ref=f_ref,
                                  f_final=f_max)

    # FIXME: currently will using aLIGOZeroDetHighPower
    # FIXME: add how to make sure, psd numerical problems of psd
    if psd is not None:
        ipsd = pp.interpolate(psd, df)
    else:
        ipsd = None
        # ipsd = pp.aLIGOZeroDetHighPower(flen, df, f_lower)
        # ipsd = pp.interpolate(ipsd, df)
        # ipsd.data[-1] = 2.0*ipsd.data[-2]
        # ipsd = ipsd.astype(hp.dtype)

    mat0, _ = pf.match(hp, hp0, ipsd, f_lower, f_max)
    mat3, _ = pf.match(hp, hp3, ipsd, f_lower, f_max)
    # print mat0, mat3, miss_match
    #     print central_param['tau0'], central_param['tau3']
    #     print temp_param0['tau0'], temp_param0['tau3']
    #     print temp_param3['tau0'], temp_param3['tau3']
    #     print float(temp_param0['tau0'])-float(central_param['tau0'])
    #     print temp_param3['tau3']-central_param['tau3']
    dtau0_range = miss_match * (temp_param0['tau0'] -
                                central_param['tau0']) / (1.0 - mat0)
    dtau3_range = miss_match * (temp_param3['tau3'] -
                                central_param['tau3']) / (1.0 - mat3)
    #     print dtau0_range, dtau3_range
    return dtau0_range, dtau3_range
Exemple #24
0
# template = np.roll(template, (np.size(template) - np.size(hp_ts) ))
# template = types.timeseries.TimeSeries(template, delta_t=dt)
    
plt.figure()
plt.plot(template.sample_times, template, label='template rotated for filter')
plt.grid()
plt.legend()
plt.show()


noise_psd = welch_function.pyc_welch(merged_noise_ts.copy(), seg_size)



#grace_psd = psd.inverse_spectrum_truncation(noise_psd, int((dt*seg_size) * conditioned.sample_rate), low_frequency_cutoff=0.01)
grace_psd = psd.interpolate(noise_psd, conditioned.delta_f)

plt.figure()
plt.loglog(noise_psd.sample_frequencies, np.sqrt(noise_psd), label='noise model asd')
plt.loglog(grace_psd.sample_frequencies, np.sqrt(grace_psd), label='interpolated noise curve')

plt.grid()
plt.legend()
plt.show()


#matched_filter
snr1 = matched_filter(template, conditioned,  psd=grace_psd, low_frequency_cutoff=0.01) 
    
snr1 = snr1.crop(10, 10)
    
Exemple #25
0
from pycbc.frame import read_frame
from pycbc.filter import highpass_fir, lowpass_fir
from pycbc.psd import welch, interpolate
from pycbc.types import TimeSeries
import urllib

# Read data and remove low frequency content
fname = 'H-H1_LOSC_4_V2-1126259446-32.gwf'
url = "https://losc.ligo.org/s/events/GW150914/" + fname
urllib.urlretrieve(url, filename=fname)
h1 = highpass_fir(read_frame(fname, 'H1:LOSC-STRAIN'), 15.0, 8)

# Calculate the noise spectrum and whiten
psd = interpolate(welch(h1), 1.0 / 32)
white_strain = (h1.to_frequencyseries() / psd ** 0.5 * psd.delta_f).to_timeseries()

# remove some of the high and low frequencies
smooth = highpass_fir(white_strain, 25, 8)
smooth = lowpass_fir(white_strain, 250, 8)

#strech out and shift the frequency upwards to aid human hearing
fdata = smooth.to_frequencyseries()
fdata.roll(int(1200 / fdata.delta_f))
smooth = TimeSeries(fdata.to_timeseries(), delta_t=1.0/1024)

#Take slice around signal
smooth = smooth[len(smooth)/2 - 1500:len(smooth)/2 + 3000]
smooth.save_to_wav('gw150914_h1_chirp.wav')

Exemple #26
0
    # =========================
    # = Precondition the data =
    # =========================

    # Remove low frequency noise
    hoft = highpass(hoft, 15.0)

    hoft = resample_to_delta_t(hoft, 1./2048.)

    # Remove 2 seconds from the start and the end to protect against edge effects
    conditioned = hoft.crop(2, 2)

    # Calculate PSD of data
    psd = conditioned.psd(4)
    psd = interpolate(psd, conditioned.delta_f)
    psd = inverse_spectrum_truncation(psd, 4 * conditioned.sample_rate, low_frequency_cutoff=15)

    psdlist[i] = psd



    # Generate a zeros frequency series the same length as the psd
    filter = FrequencySeries(numpy.zeros(len(psd)), 1, dtype=numpy.complex128)

    # Generate the waveform filter with given params
    filter = get_waveform_filter(filter,
                                 approximant=params.apx,
                                 mass1=m1,
                                 mass2=m2,
                                 sp1z=params.sp1z,