Exemplo n.º 1
0
    def test_get_timeseries(self):
        try:  # can't use decorator because this method gets called
            import nds2
        except ImportError as e:
            pytest.skip(str(e))
        product, parser = self.test_init_cli()
        args = parser.parse_args(self.TEST_ARGS + ['--out', TEMP_PLOT_FILE])
        product.post_arg(args)

        random.seed(0)
        xts = TimeSeries(random.rand(10240),
                         t0=1000000000,
                         sample_rate=1024,
                         name='X1:TEST-CHANNEL')
        yts = TimeSeries(random.rand(10240),
                         t0=1000000000,
                         sample_rate=1024,
                         name='Y1:TEST-CHANNEL')
        nds_connection = mocks.nds2_connection(buffers=[
            mocks.nds2_buffer_from_timeseries(xts),
            mocks.nds2_buffer_from_timeseries(yts),
        ])
        with mock.patch('nds2.connection') as mock_connection, \
                mock.patch('nds2.buffer'):
            mock_connection.return_value = nds_connection

            product.getTimeSeries(args)

        assert len(product.timeseries) == (len(product.chan_list) *
                                           len(product.start_list))

        return product, args
Exemplo n.º 2
0
    def test_delay_project_strain(self):
        """ Check consistency of project_strain() against time_delay_earth_center()
        """

        coords = numpy.array([uniform(0,360), uniform(-90,90)])
        
        pt_eq = pb.skymaps.Skypoint(*numpy.radians(coords), COORD_SYS_EQUATORIAL)
        d = pb.detectors.Detector(random.choice(DETECTORS))
        delay = d.time_delay_from_earth_center(pt_eq, TIME)
    
        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, 0)
                
        # 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)
        
        # Find end of the detector response
        ix, = numpy.where(numpy.abs(h) > numpy.max(h)/10)
        time_end = h.t0.value + ix[-1]/SAMPLING_RATE
        estimated_delay = float(time_end - (TIME+1))
        
        print("Exact delay = {} ; Estimated delay = {}".format(delay, estimated_delay))
        
        # Estimate delay from timeseries
        self.assertAlmostEqual(delay, estimated_delay, places=3)
Exemplo n.º 3
0
    def test_makePlot(self):
        product, parser = self.test_init_cli()
        args = parser.parse_args(self.TEST_ARGS + ['--out', TEMP_PLOT_FILE])
        product.post_arg(args)
        args.interactive = True

        random.seed(0)
        xts = TimeSeries(random.rand(10240),
                         t0=1000000000,
                         sample_rate=1024,
                         name='X1:TEST-CHANNEL')
        yts = TimeSeries(random.rand(10240),
                         t0=1000000000,
                         sample_rate=1024,
                         name='Y1:TEST-CHANNEL')
        nds_connection = mocks.nds2_connection(buffers=[
            mocks.nds2_buffer_from_timeseries(xts),
            mocks.nds2_buffer_from_timeseries(yts),
        ])

        with mock.patch('nds2.connection') as mock_connection, \
                mock.patch('nds2.buffer'):
            mock_connection.return_value = nds_connection

            try:
                product.makePlot(args, parser)
            finally:
                if os.path.isfile(args.out):
                    os.remove(args.out)

        assert product.is_interactive is True
Exemplo n.º 4
0
    def test_add_timeseries(self):
        a = TimeSeries([1, 2, 3, 4, 5],
                       name='test name',
                       epoch=0,
                       sample_rate=1)

        # test simple add using 'name'
        data.add_timeseries(a)
        assert 'test name' in globalv.DATA
        assert len(globalv.DATA['test name']) == 1
        assert globalv.DATA['test name'][0] is a

        # test add using key kwarg
        data.add_timeseries(a, key='test key')
        assert globalv.DATA['test key'][0] is a

        # test add to existing key with coalesce
        b = TimeSeries([6, 7, 8, 9, 10],
                       name='test name 2',
                       epoch=5,
                       sample_rate=1)
        data.add_timeseries(b, key='test key', coalesce=True)
        assert len(globalv.DATA['test key']) == 1
        nptest.assert_array_equal(globalv.DATA['test key'][0].value,
                                  arange(1, 11))
Exemplo n.º 5
0
    def test_fcross_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(ZEROS_1_SEC, sample_rate=SAMPLING_RATE).to_lal()
        hcross = TimeSeries(SIN_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[1] > 0:
            estimated_pat = h.max().to_value()
        else:
            estimated_pat = h.min().to_value()

        print("Exact antenna pattern = {} ; Estimated pattern from amplitude = {}".format(antenna_pat[1], estimated_pat))
            
        self.assertAlmostEqual(antenna_pat[1], estimated_pat, places=2)
Exemplo n.º 6
0
    def calculate_time_volume(segments, range):
        try:
            ts = TimeSeries(numpy.zeros(range.size),
                            xindex=range.times,
                            unit='s')
        except IndexError:
            ts = TimeSeries(numpy.zeros(range.size),
                            unit='s',
                            x0=range.x0,
                            dx=range.dx)
        dx = range.dx.value

        # override range units
        range.override_unit('Mpc')

        # use float, not LIGOTimeGPS for speed
        segments = type(segments)(
            [type(s)(float(s[0]), float(s[1])) for s in segments])

        def livetime_(t):
            return float(abs(SegmentList([Segment(t, t + dx)]) & segments))

        livetime = numpy.vectorize(livetime_, otypes=[float])
        ts[:] = livetime(ts.times.value) * ts.unit
        return (4 / 3. * pi * ts * range**3).to('Mpc^3 kyr')
Exemplo n.º 7
0
    def combined_time_volume(self, allsegments, allranges):
        try:
            combined_range = TimeSeries(numpy.zeros(allranges[0].size),
                                        xindex=allranges[0].times,
                                        unit='Mpc')
        except IndexError:
            combined_range = TimeSeries(numpy.zeros(allranges[0].size),
                                        unit='Mpc',
                                        x0=allranges[0].x0,
                                        dx=allranges[0].dx)

        # get coincident observing segments
        pairs = list(combinations(allsegments, 2))
        coincident = SegmentList()
        for pair in pairs:
            coincident.extend(pair[0] & pair[1])
        coincident = coincident.coalesce()

        # get effective network range
        values = [r.value for r in allranges]
        values = [min(nlargest(2, x)) for x in zip(*values)]
        size = min([r.size for r in allranges])
        combined_range[:size] = values * combined_range.unit

        # compute time-volume
        return self.calculate_time_volume(coincident, combined_range)
Exemplo n.º 8
0
def test_save_loudest_tile_features():
    # prepare input data
    channel = GW.channels[0]
    noise = TimeSeries(numpy.random.normal(loc=1, scale=.5, size=16384 * 68),
                       sample_rate=16384,
                       epoch=-34).zpk([], [0], 1)
    glitch = TimeSeries(signal.gausspulse(numpy.arange(-1, 1, 1. / 16384),
                                          bw=100),
                        sample_rate=16384,
                        epoch=-1) * 1e-4
    in_ = noise.inject(glitch)
    _, _, _, qgram, _, _, _ = core.scan(gps=0,
                                        channel=channel,
                                        xoft=in_,
                                        resample=4096,
                                        fftlength=8)

    # test loudest tiles
    channel.save_loudest_tile_features(qgram, correlate=glitch)
    assert channel.Q == numpy.around(qgram.plane.q, 1)
    assert channel.energy == numpy.around(qgram.peak['energy'], 1)
    assert channel.snr == numpy.around(qgram.peak['snr'], 1)
    assert channel.t == numpy.around(qgram.peak['time'], 3)
    assert channel.f == numpy.around(qgram.peak['frequency'], 1)
    assert channel.corr == numpy.around(glitch.max().value, 1)
    assert channel.delay == 0.0
    assert channel.stdev == glitch.std().value
Exemplo n.º 9
0
 def test_normalize_fft_params(self):
     """Test :func:`gwpy.signal.fft.ui.normalize_fft_params`
     """
     ftp = fft_ui.normalize_fft_params(
         TimeSeries(numpy.zeros(1024), sample_rate=256))
     assert ftp == {'nfft': 1024, 'noverlap': 0}
     ftp = fft_ui.normalize_fft_params(
         TimeSeries(numpy.zeros(1024), sample_rate=256), {'window': 'hann'})
     assert ftp == {'nfft': 1024, 'noverlap': 512, 'window': 'hann'}
Exemplo n.º 10
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
Exemplo n.º 11
0
 def rotate(self,theta):
     '''
     '''
     data = np.array([self.ew, self.ns, self.ud]).T
     data = np.dot(data,clockwise_Zaxis(theta))
     self.x = TimeSeries(data[:,0],unit=self.unit,dt=self.dt,
                         t0=self.t0,name=self.ew.name)#,channel=self.ew.channel)
     self.y = TimeSeries(data[:,1],unit=self.unit,dt=self.dt,
                         t0=self.t0,name=self.ns.name)#,channel=self.ns.channel)
     self.z = TimeSeries(data[:,2],unit=self.unit,dt=self.dt,
                         t0=self.t0,name=self.ud.name)#,channel=self.ud.channel)
Exemplo n.º 12
0
def makesine(freq, amp, makeplot=True, cropstart=1.0, cropend=1.05):
    fs = 4096

    time = np.arange(0, 3, 1.0 / fs)
    y1 = amp * np.sin(2 * np.pi * freq * time)
    if amp > 0:
        sig1 = TimeSeries(y1, dt=1.0 / fs).taper()
    else:
        sig1 = TimeSeries(y1, dt=1.0 / fs)
    if makeplot:
        plot_signal(sig1)
    return (sig1)
Exemplo n.º 13
0
def mock_nds2_connection():
    xts = TimeSeries(_random_data(10240),
                     t0=0,
                     sample_rate=1024,
                     name='X1:TEST-CHANNEL')
    yts = TimeSeries(_random_data(10240),
                     t0=0,
                     sample_rate=1024,
                     name='Y1:TEST-CHANNEL')
    data = [xts, yts]
    conn = mocks.nds2_connection(buffers=list(
        map(mocks.nds2_buffer_from_timeseries, data)), )
    return conn, data
Exemplo n.º 14
0
 def test_normalize_fft_params(self):
     """Test :func:`gwpy.signal.fft.ui.normalize_fft_params`
     """
     ftp = fft_ui.normalize_fft_params(
         TimeSeries(numpy.zeros(1024), sample_rate=256))
     assert ftp == {'nfft': 1024, 'noverlap': 0}
     ftp = fft_ui.normalize_fft_params(
         TimeSeries(numpy.zeros(1024), sample_rate=256), {'window': 'hann'})
     win = signal.get_window('hann', 1024)
     assert ftp.pop('nfft') == 1024
     assert ftp.pop('noverlap') == 512
     utils.assert_array_equal(ftp.pop('window'), win)
     assert not ftp
Exemplo n.º 15
0
def plot_tiles():
    bins = numpy.linspace(0, 40, 100)
    cnt = numpy.zeros(bins.shape[0] - 1)
    for i, tdf in enumerate(tdb[:nchans]):
        us_rate = int(1.0 / (2 * band * nc_sum * ts_data.dt.value))
        pyplot.figure(0, figsize=(10, 10))
        pyplot.subplot(nchans, 1, i + 1)
        white = tmp_ts_data.whiten(
            64, 32, asd=numpy.sqrt(cdata_psd_tmp),
            window='boxcar') * sample_rate / 4
        snr_1dof = numpy.convolve(tdf, white, "valid")
        # Undersample the data
        snr_1dof = snr_1dof[::us_rate]**2
        # Sum semi-adjacent samples to get 2 DOF tiles
        snr_2dof = numpy.convolve(snr_1dof, numpy.array([1, 0, 1, 0]))
        t = TimeSeries(snr_2dof,
                       epoch=white.epoch,
                       sample_rate=int(1.0 / (us_rate * tmp_ts_data.dt.value)))
        pyplot.plot(t.times + len(tdf) / 2 * tdf.dt, snr_2dof, 'k-')
        pyplot.axvline(random_time)
        tmp, _ = numpy.histogram(snr_2dof, bins=bins)
        cnt += tmp
    plot_spectrogram(dof_tiles.T,
                     fname='%s/tf_%ichans_%02idof.png' %
                     (segfolder, nc_sum + 1, 2 * j))
    plot.savefig("%s/bands.png" % (segfolder), dpi=300)
Exemplo n.º 16
0
    def low_pass_filter(self, filter_freq=None):
        """ Low pass filter the data """
        from gwpy.signal.filter_design import lowpass
        from gwpy.timeseries import TimeSeries

        if filter_freq is None:
            logger.debug(
                "Setting low pass filter_freq using given maximum frequency")
            filter_freq = self.maximum_frequency

        if 2 * filter_freq >= self.sampling_frequency:
            logger.info(
                "Low pass filter frequency of {}Hz requested, this is equal"
                " or greater than the Nyquist frequency so no filter applied".
                format(filter_freq))
            return

        logger.debug(
            "Applying low pass filter with filter frequency {}".format(
                filter_freq))
        bp = lowpass(filter_freq, self.sampling_frequency)
        strain = TimeSeries(self.time_domain_strain,
                            sample_rate=self.sampling_frequency)
        strain = strain.filter(bp, filtfilt=True)
        self._time_domain_strain = strain.value
Exemplo n.º 17
0
    def event_rate(self, stride, start=None, end=None, timecolumn='time'):
        """Calculate the rate `~gwpy.timeseries.TimeSeries` for this `Table`.

        Parameters
        ----------
        stride : `float`
            size (seconds) of each time bin
        start : `float`, :class:`~gwpy.time.LIGOTimeGPS`, optional
            GPS start epoch of rate :class:`~gwpy.timeseries.TimeSeries`
        end : `float`, :class:`~gwpy.time.LIGOTimeGPS`, optional
            GPS end time of rate :class:`~gwpy.timeseries.TimeSeries`.
            This value will be rounded up to the nearest sample if needed.
        timecolumn : `str`, optional, default: ``time``
            name of time-column to use when binning events

        Returns
        -------
        rate : :class:`~gwpy.timeseries.TimeSeries`
            a `TimeSeries` of events per second (Hz)
        """
        from gwpy.timeseries import TimeSeries
        times = self[timecolumn]
        if not start:
            start = times.min()
        if not end:
            end = times.max()
        nsamp = int(ceil((end - start) / stride))
        timebins = numpy.arange(nsamp + 1) * stride + start
        # histogram data and return
        out = TimeSeries(
            numpy.histogram(times, bins=timebins)[0] / float(stride),
            t0=start, dt=stride, unit='Hz', name='Event rate')
        return out
Exemplo n.º 18
0
def retrieve_data_timeseries(hfile, setname):
    dset = hfile[setname]
    sample_rate = dset.attrs["SamplingRate(Hz)"]
    gps_epoch = contruct_utc_from_metadata(dset.attrs["Date"], dset.attrs["t0"])
    data = retrieve_channel_data(hfile, setname)
    ts_data = TimeSeries(data, sample_rate=sample_rate, epoch=gps_epoch)
    return ts_data
Exemplo n.º 19
0
 def test_get_timeseries(self):
     product, parser = self.test_init_cli()
     args = parser.parse_args(self.TEST_ARGS + ['--out', TEMP_PLOT_FILE])
     try:
         try:
             product.getTimeSeries(args)
         except Exception as e:
             if 'No reader' in str(e):
                 raise RuntimeError(str(e))
             else:
                 raise
     except (RuntimeError, ImportError):
         product.timeseries = []
         product.time_groups = []
         product.start_list = []
         for s in map(int, args.start):
             product.start_list.append(s)
             product.time_groups.append([])
             for c in args.chan:
                 product.timeseries.append(
                     TimeSeries(random.random(1024 * 100),
                                sample_rate=1024,
                                channel=c,
                                epoch=s))
                 product.time_groups[-1].append(len(product.timeseries) - 1)
     return product, args
Exemplo n.º 20
0
def get_signals(r, rdot, phi, dt, mass):
    """Create a `~gwpy.timeseries.TimeSeriesDict` based on orbital trajectory
    """
    rconv = G * mass / c**2
    tconv = G * mass / c**3
    dt *= tconv
    r = TimeSeries(rconv * r,
                   dt=dt.value,
                   name="radial coordinate along geodesic")
    rdot = TimeSeries(c * rdot,
                      dt=dt.value,
                      name="radial component of 4-velocity")
    phi = TimeSeries(phi,
                     dt=dt.value,
                     name="azimuthal coordinate along geodesic")
    return TimeSeriesDict({'r': r, 'rdot': rdot, 'phi': phi})
Exemplo n.º 21
0
def BLWNB(f,df,dt,fs):
    #BLWNB - Generate a random signal of given duration with constant power
    #in a given band (and zero power out of band).

    #   x = blwnb(f,df,dt,fs)
    #
    #   f   Scalar. Minimum signal frequency [Hz].
    #   df  Scalar. Full signal bandwidth [Hz].
    #   dt  Scalar. Signal duration [s].
    #   fs  Scalar. Signal sample rate [Hz].

    # Power is restricted to the band (f,f+df). 
    # Note that fs must be greater than 2*(f+df).

    # original version: L. S. Finn, 2004.08.03

    # $Id: BLWNB.m 4992 2015-07-25 18:59:12Z [email protected] $

    #% ---- Check that fs > 2*(f+df), otherwise sampling rate is not high enough to
    #       cover requested frequency range of the signal.
    if (fs <= abs(2*(f+df))):
        raise ValueError('Sampling rate fs is too small, fs = '+str(fs)+' must be greater than 2*(f+df) = '+str(np.abs(2*(f+df))))


    if f < 0 or df <= 0 or fs <= 0 or dt <= 0 :
        raise ValueError('All arguments must be greater than zero')

    #% ---- Generate white noise with duration dt at sample rate df. This will be
    #%      white over the band [-df/2,df/2].

    nSamp = ceil(dt*df)
    x_old = TimeSeries(np.random.randn(nSamp),sample_rate=1/dt)
    


    #% ---- Resample to desired sample rate fs.
    x=x_old.resample(fs/df)
    #frac = Fraction(Decimal(fs/df))
    #p, q = frac.numerator , frac.denominator


    #% ---- Note that the rat() function returns p,q values that give the desired
    #%      ratio to a default accuracy of 1e-6. This is a big enough error that
    #%      x may be a few samples too short or too long. If too long, then truncate
    #%      to duration dt. If too short, zero-pad to duration dt.
    #print((np.zeros(nSamp-len(x)).shape))
    nSamp = round(dt*fs)
    if len(x) > nSamp:
        x = x[0:nSamp]
    elif len(x) < nSamp:
        x=np.hstack((np.array(x),np.zeros(nSamp-len(x))))

    #% ---- Heterodyne up by f+df/2 (moves zero frequency to center of desired band).
    fup = f+df/2.
    x = x*np.exp(-2*np.pi*1j*fup/fs*np.arange(1,len(x)+1))

    #% ---- Take real part and adjust amplitude.
    x = np.array(np.real(x)/np.sqrt(2))
    #% ---- Done.
    return(x)
Exemplo n.º 22
0
def plot_ts(ts, fname="ts.png"):
    plot = TimeSeriesPlot()
    ax = plot.gca()
    ax.plot(TimeSeries(ts, sample_rate=1.0 / ts.delta_t, epoch=ts.start_time))
    ax.set_xlim(ts.start_time, ts.end_time)
    pyplot.savefig(fname, dpi=300)
    pyplot.close()
Exemplo n.º 23
0
def convert_to_time_domain(fdb,sample_rate):
    """
    Convert filter bank from frequency to time domain
    
    Parameters
    ----------
    fdb : list
      List of filters from the filter bank in frequency domain
    sample_rate : float
      Sampling rate of magnetic field data
    
    Return
    ------
    tdb : list
      List of filters from the filter bank in time domain
    """
    print "|- Convert all the frequency domain to the time domain..."
    tdb = []
    for fdt in fdb:
        zero_padded = numpy.zeros(int((fdt.f0 / fdt.df).value) + len(fdt))
        st = int((fdt.f0 / fdt.df).value)
        zero_padded[st:st+len(fdt)] = numpy.real_if_close(fdt.value)
        n_freq = int(sample_rate / 2 / fdt.df.value) * 2
        tdt = numpy.fft.irfft(zero_padded, n_freq) * math.sqrt(sample_rate)
        tdt = numpy.roll(tdt, len(tdt)/2)
        tdt = TimeSeries(tdt, name="", epoch=fdt.epoch, sample_rate=sample_rate)
        tdb.append(tdt)
    return tdb
Exemplo n.º 24
0
def subtract(target, witness, tf):
    assert target.duration == witness.duration
    assert target.epoch == witness.epoch

    srate=int(target.sample_rate.value)
    tlen=len(target)
    flen=1+tlen/2

    tmp=irfft(tf)
    tmp_len=len(tmp)
    tmp=sig.hann(tmp_len)*np.roll(tmp, tmp_len/2)
    tmp.resize(len(witness)) # pad with zeros to length of witness
    tf_long=rfft(np.roll(tmp, -tmp_len/2))

    tmp=rfft(witness.astype(np.float64).value)*tf_long
    tmp.resize(flen)

    result=target.value-irfft((srate/float(witness.sample_rate.value))*tmp)

    pad=int(np.ceil(0.5/tf.df.value))
    print pad, srate
    return TimeSeries(result[int(pad*srate):-int(pad*srate)],
                        sample_rate=target.sample_rate,
                        name='%s minus %s' % (target.name,witness.name),
                        epoch=target.epoch.gps+pad)
Exemplo n.º 25
0
 def compute(self, raw: TimeSeries) -> TimeSeriesDict:
     out = TimeSeriesDict()
     times = unique([60 * (t.value // 60) for t in raw.times])
     raw.name = raw.name + '.mean'
     out[raw.name] = TimeSeries(
         [raw.crop(t - 60, t).mean().value for t in times[1:]], times=times)
     out[raw.name].__metadata_finalize__(raw)
     return out
Exemplo n.º 26
0
def getDataFromFile(fName, convert=False):
    '''
    Gets magnetometer data from file.
    
    fName: str
        Name of file
    convert: boolean (default: False)
        Whether to use conversion function from file.
        
    returns (data, sanity data) as astropy TimeSeries
    
    Note: must evaluate values in 'sanity' (e.g., using 'value' attribute) to get boolean
    '''
    h5pyFile = h5py.File(fName, 'r')
    saneList = h5pyFile['SanityChannel']
    dataList = h5pyFile['MagneticFields']

    # get mag field attributes
    attrs = dataList.attrs
    sampRate = float(attrs['SamplingRate(Hz)'])
    startT = time.mktime(
        time.strptime(attrs['Date'] + ' ' + attrs['t0'],
                      '%Y/%m/%d %H:%M:%S.%f'))
    # get sanity attributes
    saneAttrs = saneList.attrs
    saneRate = float(saneAttrs['SamplingRate(Hz)'])
    saneStart = time.mktime(
        time.strptime(saneAttrs['Date'] + ' ' + saneAttrs['t0'],
                      '%Y/%m/%d %H:%M:%S.%f'))

    # create data TimeSeries
    dataTS = TimeSeries(dataList, sample_rate=sampRate,
                        epoch=startT)  # put data in TimeSeries
    if (convert):
        convStr = attrs['MagFieldEq']  #string contatining conversion function
        unitLoc = convStr.find('[')  # unit info is at end in []
        if (unitLoc >= 0):  # unit given
            convStr = convStr[:unitLoc]  # get substring before units
        convStr = convStr.replace('MagneticFields',
                                  'dataTS')  # relabel with correct variable
        exec 'dataTS = ' + convStr  # dynamic execution to convert dataTS
    # create sanity TimeSeries
    saneTS = TimeSeries(saneList, sample_rate=saneRate, epoch=saneStart)

    h5pyFile.close()
    return dataTS, saneTS
Exemplo n.º 27
0
def bp_chunk(ts, new_srate, f_low, f_high):
    srate=int(ts.sample_rate.value)
    bp=sig.firwin(4*srate,[f_low, f_high],nyq=srate/2.,window='hann',pass_zero=False)
    bp.resize(len(ts))
    tmp=(2.*new_srate/float(srate))*abs(rfft(bp))*rfft(ts)
    padidx=4*int(new_srate) # Sample rate after irfft is twice desired
    return TimeSeries(irfft(tmp[:1+int(ts.duration.value*new_srate)])[padidx:-padidx:2],
                        sample_rate=new_srate,epoch=ts.epoch.gps+2)
Exemplo n.º 28
0
    def test_read_frame_file(self):
        start_time = 0
        end_time = 10
        channel = "H1:GDS-CALIB_STRAIN"
        N = 100
        times = np.linspace(start_time, end_time, N)
        data = np.random.normal(0, 1, N)
        ts = TimeSeries(data=data, times=times, t0=0)
        ts.channel = Channel(channel)
        ts.name = channel
        filename = os.path.join(self.outdir, "test.gwf")
        ts.write(filename, format="gwf")

        # Check reading without time limits
        strain = gwutils.read_frame_file(
            filename, start_time=None, end_time=None, channel=channel
        )
        self.assertEqual(strain.channel.name, channel)
        self.assertTrue(np.all(strain.value == data[:-1]))

        # Check reading with time limits
        start_cut = 2
        end_cut = 8
        strain = gwutils.read_frame_file(
            filename, start_time=start_cut, end_time=end_cut, channel=channel
        )
        idxs = (times > start_cut) & (times < end_cut)
        # Dropping the last element - for some reason gwpy drops the last element when reading in data
        self.assertTrue(np.all(strain.value == data[idxs][:-1]))

        # Check reading with unknown channels
        strain = gwutils.read_frame_file(filename, start_time=None, end_time=None)
        self.assertTrue(np.all(strain.value == data[:-1]))

        # Check reading with incorrect channel
        strain = gwutils.read_frame_file(
            filename, start_time=None, end_time=None, channel="WRONG"
        )
        self.assertTrue(np.all(strain.value == data[:-1]))

        ts = TimeSeries(data=data, times=times, t0=0)
        ts.name = "NOT-A-KNOWN-CHANNEL"
        ts.write(filename, format="gwf")
        strain = gwutils.read_frame_file(filename, start_time=None, end_time=None)
        self.assertEqual(strain, None)
Exemplo n.º 29
0
def plot_ts(ts, fname="ts.png"):
    '''
    Plot time series data
    '''
    plot = TimeSeriesPlot()
    ax = plot.gca()
    ax.plot(TimeSeries(ts, sample_rate=1.0 / ts.delta_t, epoch=ts.start_time))
    ax.set_xlim(ts.start_time, ts.end_time)
    plt.savefig(fname, transparent=True)
    plt.close()
Exemplo n.º 30
0
 def test_creation_with_metadata(self):
     self.ts = TimeSeries(self.data,
                          sample_rate=1,
                          name='TEST CASE',
                          epoch=0,
                          channel='TEST CASE')
     repr(self.ts)
     self.assertTrue(self.ts.epoch == GPS_EPOCH)
     self.assertTrue(self.ts.sample_rate == ONE_HZ)
     self.assertTrue(self.ts.dt == ONE_SECOND)