Table
Overview
|
Segment-keyed analysis table. |
|
A single lazy-loadable payload cell. |
SegmentTable Class
- class gwexpy.table.segment_table.SegmentTable(meta: DataFrame)[source]
Bases:
objectSegment-keyed analysis table.
Each row holds exactly one
span(gwpy.segments.Segment) plus arbitrary meta columns and optional heavy payload columns.- Parameters:
meta –
pandas.DataFramewith at least aspancolumn whose elements aregwpy.segments.Segmentobjects.- Raises:
ValueError – If
metadoes not contain aspancolumn.TypeError – If any element of the
spancolumn is not agwpy.segments.Segment.
Examples
>>> from gwpy.segments import Segment >>> import pandas as pd >>> segs = [Segment(0, 4), Segment(4, 8)] >>> st = SegmentTable(pd.DataFrame({"span": segs})) >>> len(st) 2
Factory Methods
from_segmentsCreate a
SegmentTablefrom a sequence of segments.from_tableCreate a
SegmentTablefrom an existing table.Column Management
add_columnAdd a lightweight meta column.
add_series_columnAdd a payload column (lazy-loadable).
Row-wise Processing
applyApply func to each row and collect the results as new columns.
mapApply func to each value in column.
cropCrop each row's payload to its
Segment.asdApply ASD to each row's
TimeSeriesorTimeSeriesDict.Selection & Conversion
selectSelect rows by boolean mask or column conditions.
fetchEagerly load all payload cells in columns (default: all).
materializeMaterialize lazy payload cells (equivalent to
fetch()in v0.1).to_pandasReturn a
pandas.DataFramerepresentation.copyReturn a copy of this table.
Drawing (Representative APIs)
segmentsDraw each row's span as a horizontal bar.
overlay_spectraOverlay frequency spectra with colour-graded lines.
plotGeneral-purpose plot entry.
scatterScatter plot of two scalar columns.
histHistogram of a scalar column.
overlayOverlay payload from multiple rows.
- classmethod from_segments(segments: Sequence[Any], **meta_columns: Sequence[Any]) SegmentTable[source]
Create a
SegmentTablefrom a sequence of segments.- Parameters:
segments – Sequence of
gwpy.segments.Segmentobjects.**meta_columns – Extra meta columns supplied as keyword arguments. Each value must have the same length as segments.
- Return type:
SegmentTable
- Raises:
ValueError – If any column length does not match
len(segments).
Examples
>>> from gwpy.segments import Segment >>> segs = [Segment(0, 4), Segment(4, 8)] >>> st = SegmentTable.from_segments(segs, label=["a", "b"])
- classmethod from_table(table: Any, span: str = 'span') SegmentTable[source]
Create a
SegmentTablefrom an existing table.- Parameters:
table – A
pandas.DataFrame(or compatible object).span – Column name to use as the
spancolumn. If different from"span", the column is renamed.
- Return type:
SegmentTable
- Raises:
ValueError – If span column is not found in table.
- classmethod read_csv(filepath: str, span_cols: tuple[str, str] = ('start', 'end'), **kwargs: Any) SegmentTable[source]
Read a
SegmentTablefrom a CSV file.- Parameters:
filepath – Path to the CSV file.
span_cols – The two column names to use as the
spanstart and end values. Ignored if a column named"span"already exists (containing Segment objects or compatible).**kwargs – Forwarded to
pandas.read_csv().
- Return type:
SegmentTable
- classmethod read(filepath: str, span_cols: tuple[str, str] = ('start', 'end'), **kwargs: Any) SegmentTable
Read a
SegmentTablefrom a CSV file.- Parameters:
filepath – Path to the CSV file.
span_cols – The two column names to use as the
spanstart and end values. Ignored if a column named"span"already exists (containing Segment objects or compatible).**kwargs – Forwarded to
pandas.read_csv().
- Return type:
SegmentTable
- add_column(name: str, data: Sequence[Any], kind: str = 'meta') None[source]
Add a lightweight meta column.
- Parameters:
name – Column name. Must not already exist.
data – Sequence of values; length must equal
len(self).kind – Column kind —
"meta"or"object".
- Raises:
ValueError – If name already exists, length mismatch, or kind is not
"meta"or"object".
- add_series_column(name: str, data: Sequence[Any] | None = None, loader: Sequence[Callable[[], Any]] | Callable[[int], Callable[[], Any]] | None = None, kind: str = 'timeseries') None[source]
Add a payload column (lazy-loadable).
- Parameters:
name – Column name. Must not already exist.
data – Sequence of concrete payload objects, one per row. Exclusive with loader (but one of the two must be provided).
loader – Either a sequence of zero-argument callables (one per row), or a single callable that accepts the row index and returns a zero-argument callable.
kind – Payload kind. Must be one of:
"timeseries","timeseriesdict","frequencyseries","frequencyseriesdict","object".
- Raises:
ValueError – If both data and loader are
None, or if length mismatches.ValueError – If kind is not a valid payload kind.
- property columns: list[str]
Ordered list of all column names (meta then payload).
- property schema: dict[str, str]
Mapping of column name → kind.
- row(i: int) RowProxy[source]
Return a dict-like proxy for row i.
- Parameters:
i – 0-based row index.
- Raises:
IndexError – If i is out of range.
- apply(func: Callable[[RowProxy], dict[str, Any]], in_cols: list[str] | None = None, out_cols: list[str] | None = None, parallel: bool = False, inplace: bool = False) SegmentTable[source]
Apply func to each row and collect the results as new columns.
- Parameters:
func – Callable that receives a
RowProxyand returns adict[str, object].in_cols – Hint for which columns are read (ignored in v0.1).
out_cols – Expected keys of
func’s return dict. If given, the actual keys must match exactly.parallel – If
True, falls back to sequential execution in v0.1.inplace – If
True, add columns to self; otherwise return a newSegmentTable.
- Returns:
Either self (
inplace=True) or a new table.- Return type:
SegmentTable
- Raises:
TypeError – If func does not return a
dict.ValueError – If
out_colsis given and the actual keys do not match.
- map(column: str, func: Callable[[Any], Any], out_col: str | None = None, inplace: bool = False) SegmentTable[source]
Apply func to each value in column.
- Parameters:
column – Source column name.
func – Callable that receives the cell value and returns a new value.
out_col – Output column name. Defaults to
column + "_mapped".inplace – Whether to modify self in place.
- Return type:
SegmentTable
- crop(column: str, out_col: str | None = None, span_col: str = 'span', inplace: bool = False) SegmentTable[source]
Crop each row’s payload to its
Segment.- Parameters:
column – Payload column containing
TimeSeriesorTimeSeriesDict.out_col – Output column name; defaults to
column + "_cropped".span_col – Column name for the span (default
"span").inplace – Whether to modify self in place.
- Raises:
TypeError – If the payload is not
TimeSeriesorTimeSeriesDict.
- asd(column: str, out_col: str | None = None, **kwargs: Any) SegmentTable[source]
Apply ASD to each row’s
TimeSeriesorTimeSeriesDict.- Parameters:
column – Payload column.
out_col – Output column name; defaults to
column + "_asd".**kwargs – Forwarded to
asd().
- Return type:
SegmentTable
- select(mask: Sequence[bool] | None = None, **conditions: Any) SegmentTable[source]
Select rows by boolean mask or column conditions.
- Parameters:
mask – Boolean sequence of length
len(self).**conditions – Simple equality conditions, e.g.
label="glitch".
- Returns:
A new
SegmentTablewith only the selected rows.- Return type:
SegmentTable
- Raises:
ValueError – If mask length is not equal to
len(self).KeyError – If a condition column does not exist.
- fetch(columns: list[str] | None = None) None[source]
Eagerly load all payload cells in columns (default: all).
- Parameters:
columns – List of payload column names to load.
Noneloads all.
- materialize(columns: list[str] | None = None, inplace: bool = True) SegmentTable | None[source]
Materialize lazy payload cells (equivalent to
fetch()in v0.1).- Parameters:
columns – Payload columns to materialize.
Nonemeans all.inplace – If
True(default), mutate self. IfFalse, return a copy with the payload loaded.
- Returns:
None if
inplace=True; new table ifinplace=False.- Return type:
SegmentTable or None
- to_pandas(meta_only: bool = True) DataFrame[source]
Return a
pandas.DataFramerepresentation.- Parameters:
meta_only – If
True(default), return only the meta columns. IfFalse, payload columns are appended as object columns containing the resolved cell values.- Return type:
pandas.DataFrame
- copy(deep: bool = False) SegmentTable[source]
Return a copy of this table.
- Parameters:
deep – If
False(default), meta is copied and payload cells are referenced (shallow). IfTrue, payload values are also deep-copied where possible.- Return type:
SegmentTable
- clear_cache() None[source]
Discard all cached payload values, forcing re-load on next access.
- plot(column: str | None = None, *, row: int | None = None, mode: str | None = None, **kwargs: Any) Any[source]
General-purpose plot entry. Requires both column and row.
- scatter(x: str, y: str, color: str | None = None, *, selection: Any | None = None, **kwargs: Any) Any[source]
Scatter plot of two scalar columns.
- hist(column: str, *, bins: int = 10, **kwargs: Any) Any[source]
Histogram of a scalar column.
- segments(*, y: str | None = None, color: str | None = None, **kwargs: Any) Any[source]
Draw each row’s span as a horizontal bar.
This is one of the two representative APIs of
SegmentTable(alongsideoverlay_spectra()).
- overlay(column: str, rows: list[int], *, separate: bool = False, sharex: bool = True, **kwargs: Any) Any[source]
Overlay payload from multiple rows.
- overlay_spectra(column: str, *, channel: str | None = None, rows: list[int] | None = None, color_by: str | None = None, sort_by: str | None = None, cmap: str = 'viridis', alpha: float = 0.7, linewidth: float = 0.8, colorbar: bool = True, colorbar_label: str | None = None, xscale: str = 'log', yscale: str = 'log', xlim: Any | None = None, ylim: Any | None = None, ax: Any | None = None) Any[source]
Overlay frequency spectra with colour-graded lines.
Representative API of
SegmentTablefor frequency-domain visualisation (alongsidesegments()for time-domain).
- display(max_rows: int = 20, max_cols: int = 8, meta_only: bool = False) DataFrame[source]
Return a summary
pandas.DataFramefor interactive display.- Parameters:
max_rows – Maximum rows to include.
max_cols – Maximum columns to include.
meta_only – If
True, omit payload columns.
- Return type:
pandas.DataFrame
SegmentCell Class
- class gwexpy.table.segment_cell.SegmentCell(value: Any | None = None, loader: Callable[[], Any] | None = None, cacheable: bool = True)[source]
Bases:
objectA single lazy-loadable payload cell.
- Parameters:
value (Any | None) – The concrete payload object. May be None when a loader is set.
loader (collections.abc.Callable[[], Any] | None) – A zero-argument callable that returns the payload. Ignored when value is already set.
cacheable (bool) – When True (default) the result of loader is stored in value after the first call, so subsequent calls return directly.
Examples
>>> cell = SegmentCell(loader=lambda: 42, cacheable=True) >>> cell.get() 42 >>> cell.is_loaded() True
- value: Any | None = None
- loader: Callable[[], Any] | None = None
- cacheable: bool = True
- get() Any[source]
Return the payload, loading it if necessary.
- Returns:
The resolved payload.
- Return type:
object
- Raises:
ValueError – If both value and loader are
None.
- is_loaded() bool[source]
Return
Trueif the value has been loaded (or was set directly).
- clear() None[source]
Discard the cached value so the next
get()call re-invokes the loader.
Module Contents
SegmentTable — segment-keyed analysis container.
Each row represents one analysis unit defined by a Segment
(a half-open time interval [start, end)). Columns may be lightweight meta
values or heavy payload objects such as TimeSeries.
Payload columns are stored as SegmentCell
instances that support lazy loading and optional caching.