Esempio n. 1
0
def noise_from_psd(length, sample_rate, psd, seed=0, name=None, unit=u.m):
    """ Create noise with a given psd.

    Return noise with a given psd. Note that if unique noise is desired
    a unique seed should be provided.
    Parameters
    ----------
    length : int
        The length of noise to generate in seconds.
    sample_rate : float
       the sample rate of the data
    stride : int
        Length of noise segments in seconds
    psd : FrequencySeries
        The noise weighting to color the noise.
    seed : {0, int}
        The seed to generate the noise.

    Returns
    --------
    noise : TimeSeries
        A TimeSeries containing gaussian noise colored by the given psd.
    """
    if name is None:
        name = 'noise'
    length *= sample_rate

    noise_ts = TimeSeries(np.zeros(length),
                          sample_rate=sample_rate,
                          name=name,
                          unit=unit)

    randomness = lal.gsl_rng("ranlux", seed)

    N = int(sample_rate / psd.df.value)
    n = N / 2 + 1
    stride = N / 2

    if n > len(psd):
        raise ValueError("PSD not compatible with requested delta_t")
    psd = (psd[0:n]).to_lal()
    psd.data.data[n - 1] = 0
    segment = TimeSeries(np.zeros(N), sample_rate=sample_rate).to_lal()
    length_generated = 0

    SimNoise(segment, 0, psd, randomness)
    while (length_generated < length):
        if (length_generated + stride) < length:
            noise_ts.data[length_generated:length_generated +
                          stride] = segment.data.data[0:stride]
        else:
            noise_ts.data[length_generated:length] = segment.data.data[
                0:length - length_generated]

        length_generated += stride
        SimNoise(segment, stride, psd, randomness)
    return noise_ts
Esempio n. 2
0
def noise_from_psd(length, delta_t, psd, seed=None):
    """ Create noise with a given psd.

    Return noise with a given psd. Note that if unique noise is desired
    a unique seed should be provided.

    Parameters
    ----------
    length : int
        The length of noise to generate in samples.
    delta_t : float
        The time step of the noise.
    psd : FrequencySeries
        The noise weighting to color the noise.
    seed : {0, int}
        The seed to generate the noise.

    Returns
    --------
    noise : TimeSeries
        A TimeSeries containing gaussian noise colored by the given psd.
    """
    noise_ts = TimeSeries(zeros(length), delta_t=delta_t)

    if seed is None:
        seed = numpy.random.randint(2**32)

    randomness = lal.gsl_rng("ranlux", seed)

    N = int(1.0 / delta_t / psd.delta_f)
    n = N // 2 + 1
    stride = N // 2

    if n > len(psd):
        raise ValueError("PSD not compatible with requested delta_t")

    psd = (psd[0:n]).lal()
    psd.data.data[n - 1] = 0
    psd.data.data[0] = 0

    segment = TimeSeries(zeros(N), delta_t=delta_t).lal()
    length_generated = 0

    lalsimulation.SimNoise(segment, 0, psd, randomness)
    while (length_generated < length):
        if (length_generated + stride) < length:
            noise_ts.data[length_generated:length_generated +
                          stride] = segment.data.data[0:stride]
        else:
            noise_ts.data[length_generated:length] = segment.data.data[
                0:length - length_generated]

        length_generated += stride
        lalsimulation.SimNoise(segment, stride, psd, randomness)

    return noise_ts
Esempio n. 3
0
 def __init__(self, psd, length, epoch, rate = 16384.0):
     """
     Create a noisy timeseries.
     
     Parameters
     ----------
     psd : `minke.noise.PSD`
        The power spectral density of the noise.
     """
     self.psd = psd
     randomness = lal.gsl_rng("ranlux", seed)
     seg = lal.CreateREAL8TimeSeries("STRAIN", epoch, 0.0, 1.0/rate, lal.StrainUnit, length)
Esempio n. 4
0
def noise_from_psd(length, delta_t, psd, seed=None):
    """ Create noise with a given psd.

    Return noise with a given psd. Note that if unique noise is desired
    a unique seed should be provided.

    Parameters
    ----------
    length : int
        The length of noise to generate in samples.
    delta_t : float
        The time step of the noise.
    psd : FrequencySeries
        The noise weighting to color the noise.
    seed : {0, int}
        The seed to generate the noise.

    Returns
    --------
    noise : TimeSeries
        A TimeSeries containing gaussian noise colored by the given psd.
    """
    noise_ts = TimeSeries(zeros(length), delta_t=delta_t)

    if seed is None:
        seed = numpy.random.randint(2**32)

    randomness = lal.gsl_rng("ranlux", seed)

    N = int (1.0 / delta_t / psd.delta_f)
    n = N/2+1
    stride = N/2

    if n > len(psd):
        raise ValueError("PSD not compatible with requested delta_t")

    psd = (psd[0:n]).lal()
    psd.data.data[n-1] = 0

    segment = TimeSeries(zeros(N), delta_t=delta_t).lal()
    length_generated = 0

    SimNoise(segment, 0, psd, randomness)
    while (length_generated < length):
        if (length_generated + stride) < length:
            noise_ts.data[length_generated:length_generated+stride] = segment.data.data[0:stride]
        else:
            noise_ts.data[length_generated:length] = segment.data.data[0:length-length_generated]

        length_generated += stride
        SimNoise(segment, stride, psd, randomness)

    return noise_ts
Esempio n. 5
0
def noise_from_psd(length, sample_rate, psd, seed=0, name=None, unit=u.m):
    """ Create noise with a given psd.

    Return noise with a given psd. Note that if unique noise is desired
    a unique seed should be provided.
    Parameters
    ----------
    length : int
        The length of noise to generate in seconds.
    sample_rate : float
       the sample rate of the data
    stride : int
        Length of noise segments in seconds
    psd : FrequencySeries
        The noise weighting to color the noise.
    seed : {0, int}
        The seed to generate the noise.

    Returns
    --------
    noise : TimeSeries
        A TimeSeries containing gaussian noise colored by the given psd.
    """
    if name is None:
        name='noise'
    length *=sample_rate

    noise_ts = TimeSeries(np.zeros(length),
            sample_rate=sample_rate, name=name, unit=unit)

    randomness = lal.gsl_rng("ranlux", seed)

    N = int (sample_rate / psd.df.value)
    n = N/2+1
    stride = N/2

    if n > len(psd):
        raise ValueError("PSD not compatible with requested delta_t")
    psd = (psd[0:n]).to_lal()
    psd.data.data[n-1] = 0
    segment = TimeSeries(np.zeros(N), sample_rate=sample_rate).to_lal()
    length_generated = 0

    SimNoise(segment, 0, psd, randomness)
    while (length_generated < length):
        if (length_generated + stride) < length:
            noise_ts.data[length_generated:length_generated+stride] = segment.data.data[0:stride]
        else:
            noise_ts.data[length_generated:length] = segment.data.data[0:length-length_generated]

        length_generated += stride
        SimNoise(segment,stride, psd, randomness)
    return noise_ts
Esempio n. 6
0
def create_cbc_prior_function(
    trigtime,
    component_min=1.,
    component_max=5.,
    massratio_min=0.2,
    massratio_max=0.25,
    distance_min=1.,
    distance_max=100.,
    trigtime_window=1.,
):
    """
    Generates two closures; one will calculate the log(prior) for a given
    set of parameters (uses LALInferenceInspiralPriorNormalised) and the other
    will do a random draw from the same prior.
    """

    # Create a LALInferenceVariables representing the prior function parameters
    # i.e. the min/max values corresponding to the prior bounds for each
    # parameter.

    prior_args = li.Variables()

    time_width = trigtime_window  # in seconds

    # TODO: fix so this uses full inspiral prior with cuts on mass ratio/total mass

    # These are the prior function parameters specifying various bounds
    # on the parameters.
    prior_args_list = [
        #('component',component_min,component_max,li.LALINFERENCE_REAL8_t),
        #('massratio',massratio_min,massratio_max,li.LALINFERENCE_REAL8_t),
        ('mass1', component_min, component_max, li.LALINFERENCE_REAL8_t),
        ('mass2', component_min, component_max, li.LALINFERENCE_REAL8_t),
        ('distance', distance_min, distance_max, li.LALINFERENCE_REAL8_t),
        ('inclination', 0, np.pi, li.LALINFERENCE_REAL8_t),
        ('phase', 0., 2. * np.pi, li.LALINFERENCE_REAL8_t),
        ('time', trigtime - time_width / 2., trigtime + time_width / 2.,
         li.LALINFERENCE_REAL8_t),
        ('polarisation', 0., np.pi, li.LALINFERENCE_REAL8_t),
        ('rightascension', 0., 2. * np.pi, li.LALINFERENCE_REAL8_t),
        ('declination', -np.pi / 2., np.pi / 2., li.LALINFERENCE_REAL8_t),
    ]

    # Initialise the prior function parameters
    for param_name, param_min, param_max, param_type in prior_args_list:
        LALInferenceAddMinMaxPrior(prior_args, param_name, param_min,
                                   param_max, param_type)

    #li.AddREAL8Variable(prior_args,'MTotMax',2.*component_max-component_min,li.LALINFERENCE_PARAM_FIXED)

    # These are the actual run parameters
    in_params_args = [
        ('mass1', ),
        ('mass2', ),
        ('distance', ),
        ('inclination', ),
        ('phase', ),
        ('time', ),
        ('polarisation', ),
        ('rightascension', ),
        ('declination', ),
    ]

    # Pre-allocate a list to transfer the run parameters in/out of
    # LALInference functions.
    in_params = li.Variables()
    for (param_name, ) in in_params_args:
        li.AddREAL8Variable(in_params, param_name, 0.,
                            li.LALINFERENCE_PARAM_LINEAR)

    # Create a dummy LALInferenceRunState to hold the prior args to pass
    # to the prior functions.
    dummy_rs = li.RunState()
    dummy_rs.priorArgs = prior_args

    # Initialise a GSL random number generator
    li_gsl_rng = lal.gsl_rng("mt19937", int(time.time()))

    def logp(params_in):

        for (param_name, ), param_val in zip(in_params_args, params_in):
            li.SetREAL8Variable(in_params, param_name, param_val)

        # Call the prior functions and return the normalised prior value
        return li.InspiralPrior(dummy_rs, in_params)

    def draw_from_prior():

        li.DrawFromPrior(in_params, prior_args, li_gsl_rng)
        params_out = []
        for (param_name, ) in in_params_args:
            params_out.append(li.GetREAL8Variable(in_params, param_name))

        return cbc_params_sub(*params_out)

    return logp, draw_from_prior
Esempio n. 7
0
def create_cbc_prior_function(
    trigtime,
    component_min=1.,
    component_max=5.,
    massratio_min=0.2,
    massratio_max=0.25,
    distance_min=1.,
    distance_max=100.,
    trigtime_window=1.,
):
    """
    Generates two closures; one will calculate the log(prior) for a given
    set of parameters (uses LALInferenceInspiralPriorNormalised) and the other
    will do a random draw from the same prior.
    """

    # Create a LALInferenceVariables representing the prior function parameters
    # i.e. the min/max values corresponding to the prior bounds for each
    # parameter.
    
    prior_args=li.Variables()

    time_width=trigtime_window # in seconds

    # TODO: fix so this uses full inspiral prior with cuts on mass ratio/total mass

    # These are the prior function parameters specifying various bounds
    # on the parameters.
    prior_args_list=[
        #('component',component_min,component_max,li.LALINFERENCE_REAL8_t),
        #('massratio',massratio_min,massratio_max,li.LALINFERENCE_REAL8_t),
        ('mass1',component_min,component_max,li.LALINFERENCE_REAL8_t),
        ('mass2',component_min,component_max,li.LALINFERENCE_REAL8_t),
        ('distance',distance_min,distance_max,li.LALINFERENCE_REAL8_t),
        ('inclination',0,np.pi,li.LALINFERENCE_REAL8_t),
        ('phase',0.,2.*np.pi,li.LALINFERENCE_REAL8_t),
        ('time',trigtime-time_width/2.,trigtime+time_width/2.,li.LALINFERENCE_REAL8_t),
        ('polarisation',0.,np.pi,li.LALINFERENCE_REAL8_t),
        ('rightascension',0.,2.*np.pi,li.LALINFERENCE_REAL8_t),
        ('declination',-np.pi/2.,np.pi/2.,li.LALINFERENCE_REAL8_t),
    ]

    # Initialise the prior function parameters
    for param_name,param_min,param_max,param_type in prior_args_list:
        LALInferenceAddMinMaxPrior(prior_args,param_name,param_min,param_max,param_type)

    #li.AddREAL8Variable(prior_args,'MTotMax',2.*component_max-component_min,li.LALINFERENCE_PARAM_FIXED)

    # These are the actual run parameters
    in_params_args=[
        ('mass1',),
        ('mass2',),
        ('distance',),
        ('inclination',),
        ('phase',),
        ('time',),
        ('polarisation',),
        ('rightascension',),
        ('declination',),
    ]

    # Pre-allocate a list to transfer the run parameters in/out of
    # LALInference functions.
    in_params=li.Variables()
    for (param_name,) in in_params_args:
        li.AddREAL8Variable(in_params,param_name,0.,li.LALINFERENCE_PARAM_LINEAR)

    # Create a dummy LALInferenceRunState to hold the prior args to pass
    # to the prior functions.
    dummy_rs=li.RunState()
    dummy_rs.priorArgs=prior_args

    # Initialise a GSL random number generator
    li_gsl_rng=lal.gsl_rng("mt19937",int(time.time()))

    def logp(params_in):

        for (param_name,),param_val in zip(in_params_args,params_in):
            li.SetREAL8Variable(in_params,param_name,param_val)

        # Call the prior functions and return the normalised prior value
        return li.InspiralPrior(dummy_rs,in_params)

    def draw_from_prior():

        li.DrawFromPrior(in_params,prior_args,li_gsl_rng)
        params_out=[]
        for (param_name,) in in_params_args:
            params_out.append(li.GetREAL8Variable(in_params,param_name))

        return cbc_params_sub(*params_out)

    return logp,draw_from_prior
Esempio n. 8
0
    def generate_gaussian_timeseries(self,
                                     length,
                                     sample_rate,
                                     seed=None,
                                     name=None,
                                     unit=None):
        """ Create noise with a given PSD.

        Return noise with a given psd. Note that if unique noise is desired
        a unique seed should be provided.
        Parameters
        ----------
        length : int
            The length of noise to generate in seconds.
        sample_rate : float
           the sample rate of the data
        stride : int
            Length of noise segments in seconds
        psd : FrequencySeries
            The noise weighting to color the noise.
        seed : {0, int}
            The seed to generate the noise.

        Returns
        --------
        noise : TimeSeries
            A TimeSeries containing gaussian noise colored by the given psd.
        """
        if name is None:
            name = 'noise'
        length *= sample_rate
        length = int(length)

        if seed is None:
            seed = np.random.randint(2**32)

        randomness = lal.gsl_rng("ranlux", seed)

        N = int(sample_rate / self.df.value)
        n = N / 2 + 1
        stride = N / 2
        notches = [(58, 62), (19, 21), (118, 122), (75, 77), (0, 10)]
        freqs_to_notch = np.asarray([])
        df = np.nanmin(
            np.abs(self.frequencies.value[1:] - self.frequencies.value[:-1]))
        for notch in notches:
            freqs_to_notch = np.append(freqs_to_notch,
                                       np.arange(notch[0], notch[1], df))
        idxs = np.in1d(np.round(np.abs(self.frequencies.value), 7),
                       np.round(freqs_to_notch, 7))
        psd_vals = self.value.copy()
        psd_vals[idxs] = 0
        psd = MagSpectrum(psd_vals, x0=self.x0, dx=self.dx)

        if n > len(psd):
            raise ValueError("PSD not compatible with requested delta_t")
        psd = (psd[0:n]).to_lal()
        psd.data.data[n - 1] = 0
        segment = MagTimeSeries(np.zeros(N), sample_rate=sample_rate).to_lal()
        length_generated = 0
        newdat = []

        SimNoise(segment, 0, psd, randomness)
        while (length_generated < length):
            if (length_generated + stride) < length:
                newdat.extend(segment.data.data[:stride])
            else:
                newdat.extend(segment.data.data[0:length - length_generated])

            length_generated += stride
            SimNoise(segment, stride, psd, randomness)
        return MagTimeSeries(newdat,
                             sample_rate=sample_rate,
                             name=name,
                             unit=unit,
                             channel=name)