Series#

class gwpy.types.Series(
value: QuantityLike,
unit: UnitBase | str | None = None,
x0: QuantityLike | None = None,
dx: QuantityLike | None = None,
xindex: QuantityLike | None = None,
xunit: UnitBase | str | None = None,
**kwargs,
)[source]#

Bases: Array

A one-dimensional data series.

A Series is defined as an array of data indexed upon an axis, meaning each sample maps to a position upon the axis. By convention the X axis is used to define the index, with the x0, dx, and xindex attributes allowing the positions of the data to be well defined.

Parameters:
valuearray_like

Input data array.

unitUnit, optional

Physical unit of these data.

x0float, Quantity, optional, default: 0

The starting value for the x-axis of this array.

dxfloat, Quantity, optional, default: `1

The step size for the x-axis of this array.

xindexarray-like

The complete array of x-axis values for this array. This argument takes precedence over x0 and dx so should be given in place of these if relevant, not alongside.

xunitUnit, optional

The unit of the x-axis index. If not given explicitly, it will be taken from any of dx, x0, or xindex, or set to a boring default.

epochLIGOTimeGPS, float, str, optional

GPS epoch associated with these data, any input parsable by to_gps is fine.

namestr, optional

Descriptive title for this array.

channelChannel, str, optional

Source data stream for these data.

dtypedtype, optional

Input data type.

copybool, optional, default: False

Choose to copy the input data to new memory.

subokbool, optional, default: True

Allow passing of sub-classes by the array generator.

Returns:
seriesSeries

a new Series

Examples

To define a Series of displacements at a given input laser power, for example:

>>> data = Series([1, 2, 3, 2, 4, 3], unit='nm', x0=0, dx=2, xunit='W')
>>> print(data)
Series([ 1., 2., 3., 2., 4., 3.]
       unit: Unit("nm"),
       name: None,
       epoch: None,
       channel: None,
       x0: 0.0 W,
       dx: 2.0 W,
       xindex: [  0.   2.   4.   6.   8.  10.] W)

Attributes Summary

dx

X-axis sample separation.

read

Read data into a Series.

write

Write this Series to a file.

x0

X-axis coordinate of the first data point.

xindex

Positions of the data on the x-axis.

xspan

X-axis [low, high) segment encompassed by these data.

xunit

Unit of x-axis index.

Methods Summary

append(other, *[, inplace, gap, pad, resize])

Connect another series onto this one.

check_compatible(other[, casting, ...])

Check whether this Series and other are compatible.

copy([order])

Return a copy of the array.

crop([start, end, copy])

Crop this series to the given x-axis extent.

diff([n, axis])

Calculate the n-th order discrete difference along given axis.

inject(other, *[, inplace])

Add two compatible Series along their shared x-axis values.

is_compatible(other)

Check whether this series and other have compatible metadata.

is_contiguous(other[, tol])

Check whether other is contiguous with self.

pad(pad_width, **kwargs)

Pad this series to a new size.

plot([method])

Plot the data for this series.

prepend(other, *[, inplace, gap, pad, resize])

Connect another series onto the start of the current one.

shift(delta)

Shift this Series forward on the X-axis by delta.

step(**kwargs)

Create a step plot of this series.

update(other, *[, inplace, gap, pad])

Update this series by appending new data like a buffer.

value_at(x)

Return the value of this Series at the given xindex value.

zip()

Zip the xindex and value arrays of this Series.

Attributes Documentation

dx[source]#

X-axis sample separation.

read#

Read data into a Series.

Arguments and keywords depend on the output format, see the online documentation for full details for each format, the parameters below are common to most formats.

Parameters:
sourcestr, pathlib.Path, file, list

Source of data, any of the following:

  • open (readable) file object

  • path to a file

  • list of files (open or paths)

formatstr,

Source format identifier. If not given, the format will be detected if possible. See below for list of acceptable formats.

kwargs

Other keywords arguments depend on the format, see the online documentation for details.

Returns:
dataSeries
Raises:
IndexError

if source is an empty list

write#

Write this Series to a file.

Arguments and keywords depend on the output format, see the online documentation for full details for each format, the parameters below are common to most formats.

Parameters:
targetstr, Path, file

Output file path or file opened in write mode.

formatstr, optional

Output format identifier. Default format will be detected if possible. See below for list of acceptable formats.

x0[source]#

X-axis coordinate of the first data point.

xindex[source]#

Positions of the data on the x-axis.

xspan[source]#

X-axis [low, high) segment encompassed by these data.

xunit[source]#

Unit of x-axis index.

Methods Documentation

append(
other: numpy.ndarray | Series,
*,
inplace: bool = True,
gap: Literal['raise', 'ignore', 'pad'] | None = None,
pad: float | None = None,
resize: bool = True,
) Self[source]#

Connect another series onto this one.

Parameters:
othernumpy.ndarray, Series

Another Series, or a simple data array to connect to this one.

inplacebool, optional

If True (default) perform the operation in-place, modifying current series. If False copy the data to new memory before modifying.

Warning

inplace append bypasses the reference check in numpy.ndarray.resize, so be carefully to only use this for arrays that haven’t been sharing their memory!

gapstr, optional

Action to perform if there’s a gap between the other series and this one. One of

  • 'raise' - raise a ValueError

  • 'ignore' - remove gap and join data

  • 'pad' - pad gap with zeros

If pad is given and is not None, the default is gap='pad', otherwise gap='raise'.

If gap='pad' is given, the default for pad is 0.

padfloat, optional

Value with which to pad discontiguous series, by default gaps will result in a ValueError.

resizebool, optional

If True (default) resize this array to accommodate new data. If False roll the current data like a buffer to the left and insert new data at the other end.

Returns:
seriesSeries

A new series containing joined data sets.

check_compatible(
other: list | numpy.ndarray,
casting: Literal['no', 'equiv', 'safe', 'same_kind', 'unsafe'] | None = 'safe',
*,
irregular_equal: bool = True,
) None[source]#

Check whether this Series and other are compatible.

Parameters:
othernumpy.ndarray, Series

The array to compare to.

castingstr, optional

The type of casting to support when comparing dtypes.

irregular_equalbool, optional

Require irregular indices to be equal (default). If irregular_equal=False and either (or both) of the series are irregular, this method just returns without doing anything.

Raises:
ValueError

If any metadata elements aren’t compatible.

TypeError

If the dtype can’t be safely cast between the arrays.

copy(order='C')[source]#

Return a copy of the array.

Parameters:
order{‘C’, ‘F’, ‘A’, ‘K’}, optional

Controls the memory layout of the copy. ‘C’ means C-order, ‘F’ means F-order, ‘A’ means ‘F’ if a is Fortran contiguous, ‘C’ otherwise. ‘K’ means match the layout of a as closely as possible. (Note that this function and numpy.copy() are very similar but have different default values for their order= arguments, and this function always passes sub-classes through.)

See also

numpy.copy

Similar function with different default behavior

numpy.copyto

Notes

This function is the preferred method for creating an array copy. The function numpy.copy() is similar, but it defaults to using order ‘K’, and will not pass sub-classes through by default.

Examples

>>> import numpy as np
>>> x = np.array([[1,2,3],[4,5,6]], order='F')
>>> y = x.copy()
>>> x.fill(0)
>>> x
array([[0, 0, 0],
       [0, 0, 0]])
>>> y
array([[1, 2, 3],
       [4, 5, 6]])
>>> y.flags['C_CONTIGUOUS']
True

For arrays containing Python objects (e.g. dtype=object), the copy is a shallow one. The new array will contain the same object which may lead to surprises if that object can be modified (is mutable):

>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> b = a.copy()
>>> b[2][0] = 10
>>> a
array([1, 'm', list([10, 3, 4])], dtype=object)

To ensure all elements within an object array are copied, use copy.deepcopy:

>>> import copy
>>> a = np.array([1, 'm', [2, 3, 4]], dtype=object)
>>> c = copy.deepcopy(a)
>>> c[2][0] = 10
>>> c
array([1, 'm', list([10, 3, 4])], dtype=object)
>>> a
array([1, 'm', list([2, 3, 4])], dtype=object)
crop(
start: Quantity | float | None = None,
end: Quantity | float | None = None,
*,
copy: bool = False,
) Self[source]#

Crop this series to the given x-axis extent.

Parameters:
startfloat, optional

Lower limit of x-axis to crop to, defaults to x0.

endfloat, optional

Upper limit of x-axis to crop to, defaults to series end.

copybool, optional

Copy the input data to fresh memory, otherwise return a view (default).

Returns:
seriesSeries

A new series with a sub-set of the input data.

Notes

If either start or end are outside of the original Series span, warnings will be printed and the limits will be restricted to the xspan.

diff(n: int = 1, axis: int = -1) Self[source]#

Calculate the n-th order discrete difference along given axis.

The first order difference is given by out[n] = a[n+1] - a[n] along the given axis, higher order differences are calculated by using diff recursively.

Parameters:
nint, optional

The number of times values are differenced.

axisint, optional

The axis along which the difference is taken, default is the last axis.

Returns:
diffSeries

The n order differences. The shape of the output is the same as the input, except along axis where the dimension is smaller by n.

See also

numpy.diff

For documentation on the underlying method.

inject(other: Series, *, inplace: bool = False) Self[source]#

Add two compatible Series along their shared x-axis values.

Parameters:
otherSeries

A Series whose xindex intersects with self.xindex.

inplacebool, optional

If True (default) perform the operation in-place, modifying the current series. If False copy the data to new memory before modifying.

Returns:
outSeries

The sum of self and other along their shared x-axis values.

Raises:
ValueError

If self and other have incompatible units or xindex intervals.

Notes

The offset between self and other will be rounded to the nearest sample if they are not exactly aligned.

If self.xindex is an array of timestamps, and if other.xspan is not a subset of self.xspan, then other will be cropped before being adding to self.

Users may wish to taper or window their Series before passing it to this method. See TimeSeries.taper() and planck() for more information.

is_compatible(other: list | ndarray) bool[source]#

Check whether this series and other have compatible metadata.

This method tests that the sample size, and the unit match.

is_contiguous(
other: Series | ndarray | list,
tol: float = 3.814697265625e-06,
) int[source]#

Check whether other is contiguous with self.

Parameters:
otherSeries, numpy.ndarray

Another series of the same type to test for contiguity.

tolfloat, optional

The numerical tolerance of the test.

Returns:
1

If other is contiguous with this series, i.e. would attach seamlessly onto the end.

-1

If other is anti-contiguous with this seires, i.e. would attach seamlessly onto the start.

0

If other is completely dis-contiguous with this series.

Notes

If other is an array that doesn’t have index information (e.g. a numpy.ndarray), this method always returns 1.

If self *or* other` have an irregular Index array (e.g. aren’t linearly sampled), this method will always return 1 if other starts after self finishes, or -1` if the inverse. If the two arrays overlap, that is bad and will raise an error.

pad(pad_width: int | tuple[int, int], **kwargs) Self[source]#

Pad this series to a new size.

This just wraps numpy.pad and handles shifting the Index to accommodate padding on the left.

Parameters:
pad_widthint, tuple[int, int]

Number of samples by which to pad each end of the array; given a single int to pad both ends by the same amount, or a (before, after) tuple for assymetric padding.

kwargs

Other keyword arguments are passed to numpy.pad.

Returns:
seriesSeries

The padded version of the input.

See also

numpy.pad

For details on the pad function and valid keyword arguments.

plot(method: str = 'plot', **kwargs) Plot[source]#

Plot the data for this series.

Parameters:
methodstr, optional

The method on the Axes to call to render this object. Default is "plot" (plot).

kwargs

Other keyword arguments are passed to the relevant Axes plotting method.

Returns:
figureFigure

The newly created figure, with populated Axes.

See also

matplotlib.pyplot.figure

For documentation of keyword arguments used to create the figure.

matplotlib.figure.Figure.add_subplot

For documentation of keyword arguments used to create the axes.

matplotlib.axes.Axes.plot

For documentation of keyword arguments used in rendering the data.

prepend(
other: QuantityLike,
*,
inplace: bool = True,
gap: Literal['raise', 'ignore', 'pad'] | None = None,
pad: float | None = None,
resize: bool = True,
) Series[source]#

Connect another series onto the start of the current one.

Parameters:
othernumpy.ndarray, Series

The data to prepend to this series.

inplacebool, optional

If True (default) perform the operation in-place, modifying current series. If False copy the data to new memory before modifying.

Warning

inplace append bypasses the reference check in numpy.ndarray.resize, so be carefully to only use this for arrays that haven’t been sharing their memory!

gapstr, optional

Action to perform if there’s a gap between the other series and this one. One of

  • 'raise' - raise a ValueError

  • 'ignore' - remove gap and join data

  • 'pad' - pad gap with zeros

If pad is given and is not None, the default is gap='pad', otherwise gap='raise'.

If gap='pad' is given, the default for pad is 0.

padfloat, optional

Value with which to pad discontiguous series, by default gaps will result in a ValueError.

resizebool, optional

If True (default) resize this array to accommodate new data. If False roll the current data like a buffer to the left or right (depending on prepend) and insert new data at the other end.

Returns:
seriesSeries

The modified series.

shift(delta: QuantityLike) None[source]#

Shift this Series forward on the X-axis by delta.

This modifies the series in-place.

Parameters:
deltafloat, Quantity, str

The amount by which to shift (in x-axis units if float), give a negative value to shift backwards in time

Examples

>>> from gwpy.types import Series
>>> a = Series([1, 2, 3, 4, 5], x0=0, dx=1, xunit='m')
>>> print(a.x0)
0.0 m
>>> a.shift(5)
>>> print(a.x0)
5.0 m
>>> a.shift('-1 km')
-995.0 m
step(**kwargs) Plot[source]#

Create a step plot of this series.

kwargs

All keyword arguments are passed to the plot() method. of this series.

See also

plot

For details of the plotting.

update(
other: QuantityLike,
*,
inplace: bool = True,
gap: Literal['raise', 'ignore', 'pad'] | None = None,
pad: float | None = None,
) Self[source]#

Update this series by appending new data like a buffer.

Old data (at the start) are dropped to maintain a fixed size.

This is a convenience method that just calls append with resize=False.

Parameters:
otherSeries, numpy.ndarray

The data to add to the end of this Series.

inplacebool

If True (default) modify the data in place. If False copy the data to new memory.

gapstr, optional

Action to perform if there’s a gap between the other series and this one. One of

  • 'raise' - raise a ValueError

  • 'ignore' - remove gap and join data

  • 'pad' - pad gap with zeros

If pad is given and is not None, the default is gap='pad', otherwise gap='raise'.

If gap='pad' is given, the default for pad is 0.

padfloat, optional

Value with which to pad discontiguous series, by default gaps will result in a ValueError.

Returns:
seriesSeries

Either the same series (if inplace=True) or a new series (if inplace=False) with other data added to the end of this ‘buffer’.

See also

append

For details of the data manipulation.

value_at(x: QuantityLike) Quantity[source]#

Return the value of this Series at the given xindex value.

Parameters:
xfloat, Quantity

The xindex value at which to search.

Returns:
yQuantity

The value of this Series at the given xindex value.

Raises:
IndexError

If x doesn’t match an X-index value.

zip() ndarray[source]#

Zip the xindex and value arrays of this Series.

Returns:
stacked2-d numpy.ndarray

The array formed by stacking the the xindex and value of this series

Examples

>>> a = Series([0, 2, 4, 6, 8], xindex=[-5, -4, -3, -2, -1])
>>> a.zip()
array([[-5.,  0.],
       [-4.,  2.],
       [-3.,  4.],
       [-2.,  6.],
       [-1.,  8.]])