Interoperability (gwexpy.interop)ο
Stability: Stable
Public interop entry points.
This namespace exposes object-level bridges such as to_netcdf4() and
from_netcdf4(). Direct file I/O format names live in the .read() /
.write() registry and use canonical spellings such as "nc".
- gwexpy.interop.to_pandas_series(ts: TimeSeries, index: Literal['datetime', 'seconds', 'gps'] = 'datetime', name: str | None = None, copy: bool = False) pd.Series[source]
Convert TimeSeries to pandas.Series.
- gwexpy.interop.from_pandas_series(cls: type[T], series: pd.Series, *, unit: str | None = None, t0: float | None = None, dt: float | None = None) T[source]
Create a TimeSeries from pandas.Series.
- gwexpy.interop.to_pandas_dataframe(tsd: TimeSeriesDict, index: Literal['datetime', 'seconds', 'gps'] = 'datetime', copy: bool = False) pd.DataFrame[source]
Convert TimeSeriesDict to DataFrame.
- gwexpy.interop.from_pandas_dataframe(cls: type[TimeSeriesDict], df: pd.DataFrame, *, unit_map: dict[str, str] | None = None, t0: float | None = None, dt: float | None = None) TimeSeriesDict[source]
Convert DataFrame to TimeSeriesDict.
- gwexpy.interop.to_xarray(ts: TimeSeries, time_coord: Literal['datetime', 'seconds', 'gps'] = 'datetime') xr.DataArray[source]
Convert TimeSeries to xarray.DataArray.
- gwexpy.interop.from_xarray(cls: type[T], da: xr.DataArray, unit: str | None = None) T[source]
Convert xarray.DataArray to TimeSeries.
- gwexpy.interop.to_xarray_field(field: Any, *, dim_names: tuple[str, str, str, str] | None = None) Any[source]
Convert a ScalarField or VectorField to an xarray DataArray / Dataset.
- Parameters:
field (ScalarField or VectorField) β Source field.
dim_names (tuple of 4 str, optional) β Dimension names
(axis0, axis1, axis2, axis3). Defaults tofield.axis_nameswhen available, then to("t", "x", "y", "z").
- Returns:
xarray.DataArray β When field is a ScalarField.
xarray.Dataset β When field is a VectorField.
- gwexpy.interop.from_xarray_field(cls: type, da: Any, *, axis0_dim: str | None = None, spatial_dims: tuple[str, ...] | None = None, axis0_domain: Literal['time', 'frequency'] = 'time', space_domain: Literal['real', 'k'] = 'real') Any[source]
Convert an
xarray.DataArrayorDatasetto a ScalarField / VectorField.Dimension auto-detection priority:
CF Convention
axisattribute (T/X/Y/Z)MetPy
_metpy_axisattributeHeuristic name matching
- Parameters:
cls (type) β
ScalarFieldorVectorField.da (xarray.DataArray or xarray.Dataset) β Input array. A
Datasetis treated as a VectorField where each data variable becomes one component.axis0_dim (str, optional) β Dimension name to use as axis0. Auto-detected when
None.spatial_dims (tuple of str, optional) β Ordered tuple
(dim_x, dim_y, dim_z)for spatial axes. Auto-detected whenNone. Missing axes are filled with singleton dimensions.axis0_domain ({"time", "frequency"}, default "time") β Physical domain of axis0.
space_domain ({"real", "k"}, default "real") β Spatial domain label for the resulting ScalarField.
- Returns:
ScalarField β When da is a DataArray or cls is ScalarField.
VectorField β When da is a Dataset or cls is VectorField with a DataArray.
- gwexpy.interop.to_hdf5(ts: TimeSeries, group: h5py.Group, path: str, overwrite: bool = False, compression: str | None = None, compression_opts: Any = None) None[source]
Write TimeSeries to HDF5 group.
wrapper for ts.write(β¦, format=βhdf5β) usually, but here we implement direct low-level if strict control is needed, OR delegate.
- gwexpy.interop.from_hdf5(cls: type[T], group: h5py.Group, path: str) T[source]
Read TimeSeries from HDF5 group.
- gwexpy.interop.to_obspy_trace(ts, stats_extra=None, dtype=None)[source]
Legacy alias for internal use, prefers using new generic to_obspy.
- gwexpy.interop.from_obspy_trace(cls, tr, unit=None, name_policy='id')[source]
Legacy alias.
- gwexpy.interop.to_obspy(data, **kwargs)[source]
Convert gwexpy object to Obspy object.
FrequencySeries -> Trace (Spectrum mode) Spectrogram -> Stream (Filter Bank mode) TimeSeries -> Trace
- gwexpy.interop.from_obspy(cls, data, **kwargs)[source]
Convert an Obspy object to a GWexpy object of type cls.
- gwexpy.interop.to_specutils(data, **kwargs)[source]
Convert a gwexpy object to a specutils object.
- Parameters:
data (FrequencySeries) β Input data.
**kwargs β Additional arguments for Spectrum1D constructor.
- Return type:
specutils.Spectrum1D
- gwexpy.interop.from_specutils(cls, spectrum, **kwargs)[source]
Convert a specutils object to a gwexpy object.
- Parameters:
cls (class) β Target class (FrequencySeries).
spectrum (specutils.Spectrum1D) β Input spectrum.
**kwargs β Additional keyword arguments passed to the target constructor.
- Return type:
FrequencySeries
- gwexpy.interop.to_pyspeckit(data, **kwargs)[source]
Convert a gwexpy object to a pyspeckit Spectrum.
- Parameters:
data (FrequencySeries) β Input data.
**kwargs β Additional arguments for pyspeckit.Spectrum.
- Return type:
pyspeckit.Spectrum
- gwexpy.interop.from_pyspeckit(cls, spectrum, **kwargs)[source]
Convert a pyspeckit Spectrum to a gwexpy object.
- Parameters:
cls (class) β Target class (FrequencySeries).
spectrum (pyspeckit.Spectrum) β Input spectrum.
**kwargs β Additional keyword arguments passed to the target constructor.
- Return type:
FrequencySeries
- gwexpy.interop.to_polars_series(ts, name=None)[source]
Convert TimeSeries or FrequencySeries to polars.Series.
This only contains the data values, not the index.
- gwexpy.interop.to_polars_dataframe(ts, index_column='time', time_unit='datetime')[source]
Convert TimeSeries to polars.DataFrame with a time column.
- gwexpy.interop.from_polars_series(cls, series, unit=None, t0=0, dt=1)[source]
Create TimeSeries or FrequencySeries from polars.Series.
- gwexpy.interop.from_polars_dataframe(cls, df, index_column='time', unit=None)[source]
Create TimeSeries from polars.DataFrame.
Attempts to infer t0 and dt from the time_column.
- gwexpy.interop.to_polars_frequencyseries(fs, index_column='frequency', index_unit='Hz')[source]
Convert FrequencySeries to polars.DataFrame.
- gwexpy.interop.to_polars_dict(tsd, index_column='time', time_unit='datetime')[source]
Convert TimeSeriesDict to polars.DataFrame.
- gwexpy.interop.from_polars_dict(cls, df, index_column='time', unit_map=None)[source]
Convert polars.DataFrame to TimeSeriesDict.
- gwexpy.interop.to_tgraph(series: Any, error: Any | None = None) ROOT.TGraph[source]
Convert a 1D series to a ROOT
TGraphorTGraphErrors.
- gwexpy.interop.to_th1d(series: Any, error: Any | None = None) ROOT.TH1D[source]
Convert a 1D series to a ROOT
TH1D.
- gwexpy.interop.to_th2d(spec: Spectrogram, error: Any | None = None) ROOT.TH2D[source]
Convert a spectrogram to a ROOT
TH2D.
- gwexpy.interop.from_root(cls: type[T_s], obj: ROOT.TGraph | ROOT.TH1, return_error: bool = False) T_s | tuple[T_s, T_s][source]
Create a GWexpy series object from a ROOT
TGraphorTH1.
- gwexpy.interop.to_tmultigraph(collection, name: str | None = None) Any[source]
Convert a collection of series to a ROOT
TMultiGraph.
- gwexpy.interop.write_root_file(collection, filename: str, **kwargs: Any) None[source]
Write a collection of series to a ROOT
TFile.
- gwexpy.interop.to_sqlite(ts, conn, series_id=None, overwrite=False)[source]
Write a time series into a SQLite connection and return its id.
- gwexpy.interop.from_sqlite(cls, conn, series_id)[source]
Read a time series from a SQLite connection by series id.
- gwexpy.interop.to_pandas_frequencyseries(fs: FrequencySeries, index: Literal['frequency'] = 'frequency', name: str | None = None, copy: bool = False) pd.Series[source]
Convert a FrequencySeries to a pandas Series.
- gwexpy.interop.from_pandas_frequencyseries(cls: type[T], series: pd.Series, *, unit: str | None = None, frequencies: Any | None = None, df: float | None = None, f0: float | None = None, epoch: Any | None = None) T[source]
Create a FrequencySeries from a pandas Series.
- gwexpy.interop.to_xarray_frequencyseries(fs: FrequencySeries, freq_coord: Literal['Hz'] = 'Hz') xr.DataArray[source]
Convert a FrequencySeries to an xarray DataArray.
- gwexpy.interop.from_xarray_frequencyseries(cls: type[T], da: xr.DataArray, *, unit: str | None = None, freq_coord: str = 'frequency', epoch: Any | None = None) T[source]
Create a FrequencySeries from an xarray DataArray.
- gwexpy.interop.to_hdf5_frequencyseries(fs: FrequencySeries, group: h5py.Group, path: str, overwrite: bool = False, compression: str | None = None, compression_opts: Any = None) None[source]
Write a FrequencySeries to an HDF5 group.
- gwexpy.interop.from_hdf5_frequencyseries(cls: type[T], group: h5py.Group, path: str) T[source]
Read a FrequencySeries from an HDF5 group.
- gwexpy.interop.to_torch(series: TimeSeries | Any, device: str | torch.device | None = None, dtype: torch.dtype | None = None, requires_grad: bool = False, copy: bool = False) torch.Tensor[source]
Convert a series to a PyTorch tensor.
- Parameters:
series (TimeSeries or array-like) β Input data.
device (str or torch.device, optional) β Target device.
dtype (torch.dtype, optional) β Target dtype.
requires_grad (bool, optional) β Whether to track gradients.
copy (bool, optional) β If True, always copy data; otherwise share memory if possible.
- Returns:
The converted tensor.
- Return type:
torch.Tensor
- gwexpy.interop.from_torch(cls: type[T], tensor: torch.Tensor, t0: Any, dt: Any, unit: str | None = None) T[source]
Create a TimeSeries from a PyTorch tensor.
- gwexpy.interop.to_tf(ts, dtype=None)[source]
Convert a time series to a TensorFlow tensor.
- gwexpy.interop.from_tf(cls, tensor, t0, dt, unit=None)[source]
Create a time series from a TensorFlow tensor.
- gwexpy.interop.to_dask(ts, chunks='auto')[source]
Convert a TimeSeries to a dask.array.Array.
- gwexpy.interop.from_dask(cls, array, t0, dt, unit=None, compute=True)[source]
Create TimeSeries from dask array.
- Parameters:
cls (type) β Class to instantiate from the array data.
array (dask.array.Array) β Input dask array containing the sample values.
t0 (float or Quantity) β Start time for the output series.
dt (float or Quantity) β Sample spacing for the output series.
unit (str or Unit, optional) β Unit to assign to the output series.
compute (bool) β If True, compute the array to numpy immediately. If False, TimeSeries will hold the dask array (if underlying class supports it, gwpy TimeSeries usually expects numpy, so caution). Default True for safety.
- gwexpy.interop.to_zarr(ts: TimeSeries, store: Any, path: str, chunks: Any = None, compressor: Any = None, overwrite: bool = False) None[source]
Write to a Zarr array.
- gwexpy.interop.to_netcdf4(ts, ds, var_name, dim_time='time', time_units=None, overwrite=False)[source]
Write to netCDF4 Dataset.
ds: netCDF4.Dataset (writable)
- gwexpy.interop.from_netcdf4(cls, ds, var_name)[source]
Read from a netCDF4 dataset.
- gwexpy.interop.to_control_frd(fs: FrequencySeries, frequency_unit: Literal['rad/s', 'Hz'] = 'rad/s') control.FRD[source]
Convert FrequencySeries to control.FRD.
- Parameters:
fs (FrequencySeries) β Input frequency response data. Frequencies are assumed to be in Hz.
frequency_unit (str, optional) β Unit for the frequency axis in the output FRD object. Either
'rad/s'or'Hz'. Default is'rad/s'(standard forcontrol.FRD).
- Returns:
Frequency response data object compatible with python-control.
- Return type:
control.FRD
Examples
>>> from gwexpy.frequencyseries import FrequencySeries >>> from gwexpy.interop.control_ import to_control_frd >>> fs = FrequencySeries([1+0j, 0.5+0.5j], f0=1, df=1) >>> frd = to_control_frd(fs)
- gwexpy.interop.from_control_frd(cls: type[T_fs], frd: control.FRD, frequency_unit: Literal['Hz', 'rad/s'] = 'Hz') T_fs | FrequencySeriesMatrix[source]
Create FrequencySeries from control.FRD.
- Parameters:
- Returns:
The converted frequency response. Returns FrequencySeriesMatrix for MIMO systems.
- Return type:
FrequencySeries or FrequencySeriesMatrix
Examples
>>> from gwexpy.frequencyseries import FrequencySeries >>> from gwexpy.interop.control_ import from_control_frd >>> # frd = control.frd(data, omega) >>> # fs = from_control_frd(FrequencySeries, frd)
- gwexpy.interop.from_control_response(cls: type[TimeSeries | TimeSeriesDict], response: control.TimeResponseData, **kwargs: Any) TimeSeries | TimeSeriesDict[source]
Create TimeSeries or TimeSeriesDict from control.TimeResponseData.
- Parameters:
- Returns:
The converted time-domain data.
- Return type:
TimeSeries or TimeSeriesDict
- gwexpy.interop.from_finesse_frequency_response(cls: type[T_fs | FrequencySeriesDict], sol: Any, *, output: Any | None = None, input_dof: Any | None = None, unit: Any | None = None) T_fs | FrequencySeriesMatrix | FrequencySeriesDict[source]
Create a frequency-series object from a Finesse 3 response solution.
- Parameters:
cls (type) β The FrequencySeries (or FrequencySeriesDict) class to instantiate.
sol (finesse.analysis.actions.lti.FrequencyResponseSolution) β The frequency response solution from a Finesse 3 simulation.
output (str or object, optional) β Output DOF name to extract. If None and input_dof is also None, all output/input pairs are returned.
input_dof (str or object, optional) β Input DOF name to extract. Must be combined with output to select a single transfer function.
unit (str or astropy.units.Unit, optional) β Unit to assign to the resulting data. Finesse solutions do not carry astropy units, so this must be supplied by the caller if physical units are desired.
- Returns:
FrequencySeries β When a single (output, input_dof) pair is selected.
FrequencySeriesMatrix β When multiple output/input pairs exist and no specific pair is selected, or when only output is given (all inputs for that output).
FrequencySeriesDict β When called from
FrequencySeriesDict.from_finesse_frequency_response(cls is a dict type).
Examples
>>> from gwexpy.frequencyseries import FrequencySeries >>> # sol = model.run(...) # Finesse 3 simulation >>> fs = FrequencySeries.from_finesse_frequency_response( ... sol, output="DARM", input_dof="EX_drive" ... )
- gwexpy.interop.from_finesse_noise(cls: type[T_fs | FrequencySeriesDict], sol: Any, *, output: Any | None = None, noise: str | None = None, unit: Any | None = None) T_fs | FrequencySeriesDict[source]
Create a frequency-series object from a Finesse 3 noise solution.
- Parameters:
cls (type) β The FrequencySeries (or FrequencySeriesDict) class to instantiate.
sol (finesse.analysis.actions.noise.NoiseProjectionSolution) β The noise projection solution from a Finesse 3 simulation.
output (str or object, optional) β Output node name to extract. If None, all output nodes are included.
noise (str, optional) β Specific noise source name to extract. If None, all noise sources are included.
unit (str or astropy.units.Unit, optional) β Unit to assign to the resulting data (e.g.,
"m/sqrt(Hz)").
- Returns:
FrequencySeries β When a single output and noise source are both specified.
FrequencySeriesDict β When multiple outputs or noise sources are present.
Examples
>>> from gwexpy.frequencyseries import FrequencySeries >>> # sol = model.run(...) # Finesse 3 noise simulation >>> fs = FrequencySeries.from_finesse_noise( ... sol, output="nDARMout", noise="laser_freq" ... )
- gwexpy.interop.from_pyspice_transient(cls: type, analysis: Any, *, node: str | None = None, branch: str | None = None, unit: Any | None = None) Any[source]
Create TimeSeries or TimeSeriesDict from a PySpice TransientAnalysis.
- Parameters:
cls (type) β The TimeSeries (or TimeSeriesDict) class to instantiate.
analysis (PySpice.Spice.Simulation.TransientAnalysis) β The transient analysis result from a PySpice simulation.
node (str, optional) β Node name to extract (e.g.
"out"). If None and branch is also None, all nodes and branches are returned as a dict.branch (str, optional) β Branch name to extract (e.g.
"vcc"). Typically the name of a voltage source for current measurement. Cannot be combined with node.unit (str or astropy.units.Unit, optional) β Unit to assign to the result. PySpice waveforms carry unit information that is not astropy-compatible, so physical units must be supplied by the caller (e.g.
"V","A").
- Returns:
TimeSeries β When a single node or branch is specified.
TimeSeriesDict β When neither node nor branch is given; keyed by signal name.
Examples
>>> from gwexpy.timeseries import TimeSeries >>> # analysis = simulator.transient(...) >>> ts = TimeSeries.from_pyspice_transient(analysis, node="out")
- gwexpy.interop.from_pyspice_ac(cls: type, analysis: Any, *, node: str | None = None, branch: str | None = None, unit: Any | None = None) Any[source]
Create FrequencySeries or FrequencySeriesDict from a PySpice AcAnalysis.
AC analysis waveforms contain complex-valued frequency responses (transfer functions, impedances, etc.) with the frequency axis given by
analysis.frequency.- Parameters:
cls (type) β The FrequencySeries (or FrequencySeriesDict) class to instantiate.
analysis (PySpice.Spice.Simulation.AcAnalysis) β The AC analysis result from a PySpice simulation.
node (str, optional) β Node name to extract. If None and branch is also None, all nodes and branches are returned.
branch (str, optional) β Branch name to extract.
unit (str or astropy.units.Unit, optional) β Unit to assign to the result (e.g.
"V").
- Returns:
FrequencySeries β When a single signal is selected; data is complex.
FrequencySeriesDict β When no specific signal is selected; keyed by signal name.
Examples
>>> from gwexpy.frequencyseries import FrequencySeries >>> # analysis = simulator.ac(...) >>> fs = FrequencySeries.from_pyspice_ac(analysis, node="out")
- gwexpy.interop.from_pyspice_noise(cls: type, analysis: Any, *, node: str | None = None, unit: Any | None = None) Any[source]
Create FrequencySeries or FrequencySeriesDict from a PySpice NoiseAnalysis.
Noise analysis waveforms contain real-valued noise spectral densities (e.g. VΒ²/Hz or AΒ²/Hz) as a function of frequency.
- Parameters:
cls (type) β The FrequencySeries (or FrequencySeriesDict) class to instantiate.
analysis (PySpice.Spice.Simulation.NoiseAnalysis) β The noise analysis result from a PySpice simulation.
node (str, optional) β Node name to extract (e.g.
"onoise"for output-referred noise). If None, all signals are returned.unit (str or astropy.units.Unit, optional) β Unit to assign to the result (e.g.
"V**2/Hz").
- Returns:
FrequencySeries β When a single signal is selected; data is real.
FrequencySeriesDict β When no signal is selected; keyed by signal name.
Examples
>>> from gwexpy.frequencyseries import FrequencySeries >>> # analysis = simulator.noise(...) >>> fs = FrequencySeries.from_pyspice_noise(analysis, node="onoise")
- gwexpy.interop.from_pyspice_distortion(cls: type, analysis: Any, *, node: str | None = None, unit: Any | None = None) Any[source]
Create FrequencySeries or FrequencySeriesDict from a PySpice DistortionAnalysis.
Distortion analysis waveforms contain harmonic/intermodulation distortion components as a function of frequency.
- Parameters:
cls (type) β The FrequencySeries (or FrequencySeriesDict) class to instantiate.
analysis (PySpice.Spice.Simulation.DistortionAnalysis) β The distortion analysis result from a PySpice simulation.
node (str, optional) β Node name to extract. If None, all signals are returned.
unit (str or astropy.units.Unit, optional) β Unit to assign to the result.
- Returns:
FrequencySeries β When a single signal is selected.
FrequencySeriesDict β When no signal is selected; keyed by signal name.
Examples
>>> from gwexpy.frequencyseries import FrequencySeries >>> # analysis = simulator.distortion(...) >>> fs = FrequencySeries.from_pyspice_distortion(analysis, node="out")
- gwexpy.interop.from_skrf_network(cls: type, ntwk: Any, *, parameter: str = 's', port_pair: tuple[int, int] | None = None, unit: Any | None = None) Any[source]
Create GWexpy frequency objects from a scikit-rf network.
- Parameters:
cls (type) β The FrequencySeries (or FrequencySeriesDict) class to instantiate.
ntwk (skrf.Network) β The scikit-rf Network object to convert.
parameter (str, default
"s") β Which network parameter to extract. One of"s"(scattering),"z"(impedance),"y"(admittance),"a"(ABCD, 2-port only),"t"(transfer scattering, 2-port only), or"h"(hybrid, 2-port only).port_pair (tuple[int, int], optional) β
Zero-based
(row, col)port indices to extract a single element of the parameter matrix, e.g.(1, 0)for Sββ. If None:1-port networks return a
FrequencySeriesdirectly.Multi-port networks return a
FrequencySeriesMatrixwhen cls isFrequencySeries, or aFrequencySeriesDictwhen cls isFrequencySeriesDict.
unit (str or astropy.units.Unit, optional) β Unit to assign to the result. If None, a default unit is inferred from parameter:
None(dimensionless) for"s","t","a";"ohm"for"z";"S"for"y".
- Returns:
FrequencySeries β For a single port pair or a 1-port network.
FrequencySeriesMatrix β For a multi-port network when cls is
FrequencySeries.FrequencySeriesDict β When cls is
FrequencySeriesDict; keys are"P{row+1}{col+1}"or"S{row+1}{col+1}"etc.
Examples
>>> from gwexpy.frequencyseries import FrequencySeries >>> import skrf >>> ntwk = skrf.Network("myfilter.s2p") >>> fs_s21 = FrequencySeries.from_skrf_network(ntwk, port_pair=(1, 0)) >>> matrix = FrequencySeries.from_skrf_network(ntwk)
- gwexpy.interop.to_skrf_network(fs: Any, *, parameter: str = 's', z0: float = 50.0, port_names: list[str] | None = None, name: str | None = None) Any[source]
Create a scikit-rf Network from a FrequencySeries or FrequencySeriesMatrix.
- Parameters:
fs (FrequencySeries or FrequencySeriesMatrix) β Source data. A
FrequencySeriesis treated as a 1-port network (scalar parameter). AFrequencySeriesMatrixof shape(N, N, nfreq)is treated as an N-port network.parameter (str, default
"s") β Network parameter represented by the data. Currently only"s"is supported for direct construction; other parameters require manual conversion.z0 (float, default 50.0) β Reference impedance in Ohms applied to all ports at all frequencies.
port_names (list[str], optional) β Names for each port. Defaults to
["1", "2", ...].name (str, optional) β Name for the resulting Network. If None, uses
fs.name.
- Returns:
The constructed Network object.
- Return type:
skrf.Network
Examples
>>> from gwexpy.frequencyseries import FrequencySeries >>> import numpy as np >>> fs = FrequencySeries(np.array([0.1+0j, 0.2+0j]), frequencies=[1e9, 2e9]) >>> ntwk = fs.to_skrf_network()
- gwexpy.interop.from_skrf_impulse_response(cls: type, ntwk: Any, *, port_pair: tuple[int, int] | None = None, n: int | None = None, pad: int = 0, unit: Any | None = None) Any[source]
Create TimeSeries or TimeSeriesDict from a scikit-rf Network impulse response.
Computes the time-domain impulse response via IFFT on the S-parameters (or the selected port pair) and wraps the result in a
TimeSeries.- Parameters:
cls (type) β The TimeSeries (or TimeSeriesDict) class to instantiate.
ntwk (skrf.Network) β The scikit-rf Network object.
port_pair (tuple[int, int], optional) β
Zero-based
(row, col)port indices to compute the impulse response for. If None:1-port networks compute the single impulse response.
Multi-port networks compute all port pairs and return a
TimeSeriesDict.
n (int, optional) β Number of points for the IFFT. See
Network.impulse_response.pad (int, default 0) β Number of zero-padding points before IFFT.
unit (str or astropy.units.Unit, optional) β Unit to assign to the result.
- Returns:
TimeSeries β For a single port pair or a 1-port network.
TimeSeriesDict β For a multi-port network when no port_pair is specified.
Examples
>>> from gwexpy.timeseries import TimeSeries >>> import skrf >>> ntwk = skrf.Network("myfilter.s2p") >>> ts = TimeSeries.from_skrf_impulse_response(ntwk, port_pair=(1, 0))
- gwexpy.interop.from_skrf_step_response(cls: type, ntwk: Any, *, port_pair: tuple[int, int] | None = None, n: int | None = None, pad: int = 0, unit: Any | None = None) Any[source]
Create TimeSeries or TimeSeriesDict from a scikit-rf Network step response.
Computes the time-domain step response via IFFT on the S-parameters (or the selected port pair) and wraps the result in a
TimeSeries.- Parameters:
cls (type) β The TimeSeries (or TimeSeriesDict) class to instantiate.
ntwk (skrf.Network) β The scikit-rf Network object.
port_pair (tuple[int, int], optional) β
Zero-based
(row, col)port indices to compute the step response for. If None:1-port networks compute the single step response.
Multi-port networks compute all port pairs and return a
TimeSeriesDict.
n (int, optional) β Number of points for the IFFT. See
Network.step_response.pad (int, default 0) β Number of zero-padding points before IFFT.
unit (str or astropy.units.Unit, optional) β Unit to assign to the result.
- Returns:
TimeSeries β For a single port pair or a 1-port network.
TimeSeriesDict β For a multi-port network when no port_pair is specified.
Examples
>>> from gwexpy.timeseries import TimeSeries >>> import skrf >>> ntwk = skrf.Network("myfilter.s2p") >>> ts = TimeSeries.from_skrf_step_response(ntwk, port_pair=(1, 0))
- gwexpy.interop.from_pyroomacoustics_rir(cls: type, room: Any, *, source: int | None = None, mic: int | None = None, unit: Any | None = None) Any[source]
Create TimeSeries or TimeSeriesDict from pyroomacoustics room impulse responses.
- Parameters:
cls (type) β The TimeSeries (or TimeSeriesDict) class to instantiate.
room (pyroomacoustics.Room) β The room object after
compute_rir()orsimulate()has been called.room.rirmust follow the pyroomacoustics conventionrir[mic_index][source_index](outer index = microphone).source (int, optional) β Source index to extract. If None and mic is also None, all source-mic pairs are returned.
mic (int, optional) β Microphone index to extract. If None and source is also None, all source-mic pairs are returned.
unit (str or astropy.units.Unit, optional) β Unit to assign to the result.
- Returns:
TimeSeries β When a single source-mic pair is selected.
TimeSeriesDict β When multiple pairs are returned.
- Raises:
ValueError β If RIR has not been computed yet.
- gwexpy.interop.from_pyroomacoustics_mic_signals(cls: type, room: Any, *, mic: int | None = None, unit: Any | None = None) Any[source]
Create TimeSeries or TimeSeriesDict from pyroomacoustics microphone signals.
- Parameters:
cls (type) β The TimeSeries (or TimeSeriesDict) class to instantiate.
room (pyroomacoustics.Room) β The room object after
simulate()has been called.mic (int, optional) β Microphone index to extract. If None, all microphones are returned.
unit (str or astropy.units.Unit, optional) β Unit to assign to the result.
- Returns:
TimeSeries β When a single microphone is selected.
TimeSeriesDict β When multiple microphones are returned.
- Raises:
ValueError β If signals have not been computed yet.
- gwexpy.interop.from_pyroomacoustics_source(cls: type, room: Any, *, source: int = 0, unit: Any | None = None) Any[source]
Create TimeSeries from a pyroomacoustics sound source signal.
- Parameters:
cls (type) β The TimeSeries class to instantiate.
room (pyroomacoustics.Room) β The room object with at least one source added.
source (int, default 0) β Source index to extract.
unit (str or astropy.units.Unit, optional) β Unit to assign to the result.
- Return type:
TimeSeries
- gwexpy.interop.from_pyroomacoustics_stft(cls: type, stft_obj: Any, *, channel: int | None = None, fs: float | None = None, unit: Any | None = None) Any[source]
Create Spectrogram or SpectrogramDict from a pyroomacoustics STFT object.
- Parameters:
cls (type) β The Spectrogram (or SpectrogramDict) class to instantiate.
stft_obj (pyroomacoustics.stft.STFT or similar) β Object with
.X(complex STFT data),.hop, and.Nattributes.channel (int, optional) β Channel index to extract from multi-channel STFT. If None, all channels are returned.
fs (float, optional) β Sample rate in Hz. Required if
stft_objdoes not have anfsattribute.unit (str or astropy.units.Unit, optional) β Unit to assign to the result.
- Returns:
Spectrogram β When a single channel is selected or the STFT is single-channel.
SpectrogramDict β When multiple channels are present and no channel is selected.
- gwexpy.interop.from_pyroomacoustics_field(cls: type, room: Any, *, grid_shape: tuple[int, ...], source: int = 0, mode: str = 'rir', unit: Any | None = None) Any[source]
Create ScalarField from pyroomacoustics room with grid-placed microphones.
When microphones are placed on a regular spatial grid, this function converts the RIR or microphone signals into a 4D ScalarField with shape
(nt, nx, ny, nz).- Parameters:
cls (type) β The ScalarField class to instantiate.
room (pyroomacoustics.Room) β Room object with microphones placed on a regular grid.
grid_shape (tuple of int) β Spatial grid shape
(nx, ny, nz)for 3D rooms or(nx, ny)for 2D rooms. Must satisfyprod(grid_shape) == n_mics.source (int, default 0) β Source index (used only when
mode='rir').mode ({'rir', 'signals'}) β
Which data to extract:
'rir': Room impulse responses for the given source.'signals': Simulated microphone signals.
unit (str or astropy.units.Unit, optional) β Unit to assign to the data.
- Returns:
4D field with shape
(nt, nx, ny, nz).- Return type:
ScalarField
- Raises:
ValueError β If
prod(grid_shape)does not match the number of microphones, or if the requested data has not been computed.
- gwexpy.interop.to_pyroomacoustics_source(ts: Any) tuple[ndarray, int][source]
Export TimeSeries as a signal and sample rate tuple for pyroomacoustics.
The returned tuple can be used to add a source to a pyroomacoustics room:
signal, fs = ts.to_pyroomacoustics_source() room = pra.ShoeBox([5, 4, 3], fs=fs) room.add_source([1, 2, 1.5], signal=signal)
- Parameters:
ts (TimeSeries) β The time series to export.
- Returns:
signal (numpy.ndarray) β 1D float64 array of the signal samples.
fs (int) β Sample rate in Hz.
- gwexpy.interop.to_pyroomacoustics_stft(spec: Any, *, hop: int | None = None, analysis_window: ndarray | None = None) Any[source]
Export Spectrogram as a pyroomacoustics STFT object.
- Parameters:
spec (Spectrogram) β The spectrogram to export. Shape
(n_frames, n_freq_bins).hop (int, optional) β Hop size in samples. If None, estimated from the spectrogramβs time resolution and frequency resolution.
analysis_window (numpy.ndarray, optional) β Analysis window to set on the STFT object.
- Returns:
STFT object with
.Xset to the spectrogram data.- Return type:
pyroomacoustics.stft.STFT
- gwexpy.interop.to_jax(ts, dtype=None)[source]
Convert a series-like object to a JAX array.
- gwexpy.interop.from_jax(cls, array, t0, dt, unit=None)[source]
Create a GWexpy object from a JAX array.
- gwexpy.interop.to_cupy(obj, dtype=None)[source]
Convert an object to a CuPy array.
- gwexpy.interop.from_cupy(cls, array, t0, dt, unit=None)[source]
Create a GWexpy object from a CuPy array.
- gwexpy.interop.is_cupy_available()[source]
Check whether CuPy is installed and the CUDA environment is usable.
- gwexpy.interop.to_librosa(ts, y_dtype=<class 'numpy.float32'>)[source]
Export to librosa-compatible numpy array and sampling rate.
Returns (y, sr).
- gwexpy.interop.to_pydub(ts, sample_width=2, channels=1)[source]
Export to a pydub
AudioSegment.
- gwexpy.interop.from_pydub(cls, seg, unit=None)[source]
Create a time series from a pydub
AudioSegment.
- gwexpy.interop.to_astropy_timeseries(ts, column='value', time_format='gps')[source]
Convert a gwexpy time series to
astropy.timeseries.TimeSeries.
- gwexpy.interop.from_astropy_timeseries(cls, ap_ts, column='value', unit=None)[source]
Build a gwexpy series from an
astropy.timeseries.TimeSeries.
- gwexpy.interop.to_mne_rawarray(tsd, info=None, picks=None)[source]
Convert a TimeSeries-like object to an
mne.io.RawArray.- Parameters:
tsd β
TimeSeriesDict-like mapping (multi-channel) or a singleTimeSeries.info β Optional MNE
Info. If omitted, a minimalInfois created.picks β Optional channel selection (names or indices). Only supported for mapping inputs.
- gwexpy.interop.from_mne_raw(cls, raw, unit_map=None)[source]
Create a TimeSeriesDict from mne.io.Raw.
- gwexpy.interop.to_mne(data, info=None, **kwargs)[source]
Convert a gwexpy object to an MNE object.
- Parameters:
data (FrequencySeries, Spectrogram, or TimeSeries (or dicts)) β The data object to convert.
info (mne.Info, optional) β Measurement info to use. If None, one is created.
**kwargs β Additional arguments passed to MNE constructors.
- Returns:
The converted MNE object (e.g. RawArray, SpectrumArray, EpochsTFRArray).
- Return type:
mne_object
- gwexpy.interop.from_mne(cls, data, **kwargs)[source]
Convert an MNE object to a gwexpy object.
- Parameters:
cls (type) β The target class (e.g. FrequencySeries, Spectrogram, TimeSeries).
data (mne object) β The MNE object to convert.
**kwargs β Additional arguments passed to from_mne_* helpers.
- Return type:
gwexpy object
- gwexpy.interop.to_simpeg(data, location=None, rx_type='PointElectricField', orientation='x', **kwargs)[source]
Convert gwexpy object to simpeg.data.Data.
- Parameters:
data (TimeSeries or FrequencySeries) β Input data.
location (array_like, optional) β Rx location (x, y, z). Default is [0, 0, 0].
rx_type (str or class, optional) β Receiver class name or class object. Default βPointElectricFieldβ.
orientation (str, optional) β Receiver orientation (βxβ, βyβ, βzβ). Default βxβ.
**kwargs β Reserved for future converter-specific options.
- Returns:
SimPEG Data object containing the survey and observed data.
- Return type:
simpeg.data.Data
- gwexpy.interop.from_simpeg(cls, data_obj, **kwargs)[source]
Convert SimPEG Data object to gwexpy object.
- Parameters:
cls (class) β Target class (TimeSeries or FrequencySeries).
data_obj (simpeg.data.Data) β SimPEG Data object.
**kwargs β Reserved for future converter-specific options.
- Return type:
Object of type cls.
- gwexpy.interop.to_mth5(series, mth5_obj: str | Any, station: str | None = None, run: str | None = None, channel_type: str = 'electric') None[source]
Write a TimeSeries to an MTH5 file.
- Parameters:
series (TimeSeries) β Data to write.
mth5_obj (str or mth5.mth5.MTH5) β Open MTH5 object or path to HDF5 file.
station (str, optional) β Station name. Defaults to βStation01β.
run (str, optional) β Run name. Defaults to βRun01β.
channel_type ({'electric', 'magnetic', 'auxiliary'}, optional) β Channel type for metadata. Default is βelectricβ.
- Raises:
ImportError β If mth5 package is not installed.
Examples
>>> from gwexpy.timeseries import TimeSeries >>> from gwexpy.interop.mt_ import to_mth5 >>> ts = TimeSeries([1, 2, 3], dt=0.001, name="Ex") >>> to_mth5(ts, "data.h5", station="Site01", run="Run01")
- gwexpy.interop.from_mth5(mth5_obj: str | Any, station: str, run: str, channel: str, survey: str | None = None)[source]
Read a channel from MTH5 to TimeSeries.
- Parameters:
- Returns:
The loaded time series data.
- Return type:
TimeSeries
- Raises:
ImportError β If mth5 package is not installed.
KeyError β If station, run, or channel is not found.
Examples
>>> from gwexpy.interop.mt_ import from_mth5 >>> ts = from_mth5("data.h5", "Site01", "Run01", "Ex")
- gwexpy.interop.to_neo(obj, units=None)[source]
Convert a TimeSeries or TimeSeriesMatrix to neo.AnalogSignal.
- gwexpy.interop.from_neo(cls, sig)[source]
Create a TimeSeriesMatrix from neo.AnalogSignal.
- gwexpy.interop.to_quantity(series, units=None)[source]
Convert a series (TimeSeries, FrequencySeries, etc) to a quantities.Quantity.
- Parameters:
series (Series or array-like) β The input series with a .value and .unit attribute (or similar).
units (str or quantities.UnitQuantity, optional) β Target units for the output Quantity.
- Returns:
The data wrapped as a Quantity.
- Return type:
quantities.Quantity
- gwexpy.interop.from_quantity(cls, q, **kwargs)[source]
Create a GWpy/GWexpy Series from a quantities.Quantity.
- Parameters:
cls (type) β The target class (TimeSeries, FrequencySeries, etc).
q (quantities.Quantity) β Input quantity.
**kwargs β Additional arguments required by the class constructor (e.g. t0, dt, frequencies).
- Return type:
instance of cls
- gwexpy.interop.to_json(ts)[source]
Convert TimeSeries to a JSON string.
Includes data and basic metadata.
- gwexpy.interop.from_json(cls, json_str)[source]
Create a TimeSeries from a JSON string.
- gwexpy.interop.to_dict(ts)[source]
Convert a TimeSeries to a dictionary.
- gwexpy.interop.from_dict(cls, data_dict)[source]
Create a TimeSeries from a dictionary.
- gwexpy.interop.from_gwinc_budget(cls: type, budget_or_model: Any, *, frequencies: ndarray | None = None, quantity: Literal['asd', 'psd'] = 'asd', trace_name: str | None = None, fmin: float = 10.0, fmax: float = 4000.0, df: float = 1.0) Any[source]
Create FrequencySeries or FrequencySeriesDict from a gwinc Budget.
- Parameters:
cls (type) β
FrequencySeriesorFrequencySeriesDictclass to instantiate.budget_or_model (gwinc.Budget or str) β Pre-loaded
Budgetobject, or a model name string (e.g.,"aLIGO","Aplus") which is passed togwinc.load_budget.frequencies (array-like, optional) β Frequency array in Hz. If None, generated from
fmin/fmax/df.quantity ({"asd", "psd"}, default "asd") β Whether to return amplitude or power spectral density.
trace_name (str, optional) β
Name of a specific sub-trace to extract (e.g.,
"Quantum"). If None:FrequencySeriescls β total noise only.FrequencySeriesDictcls β total + all sub-traces.
fmin (float, default 10.0) β Minimum frequency [Hz] when frequencies is not provided.
fmax (float, default 4000.0) β Maximum frequency [Hz] when frequencies is not provided.
df (float, default 1.0) β Frequency step [Hz] when frequencies is not provided.
- Returns:
FrequencySeries β When
trace_nameis given, orclsisFrequencySeries.FrequencySeriesDict β When
trace_nameis None andclsisFrequencySeriesDict. Keys:"Total", plus sub-trace names.
- Raises:
ValueError β If
trace_namedoes not exist in the budget trace hierarchy, or ifquantityis not"asd"or"psd".ImportError β If pygwinc is not installed.
Examples
>>> from gwexpy.frequencyseries import FrequencySeries, FrequencySeriesDict >>> asd = FrequencySeries.from_gwinc_budget("aLIGO") >>> noise_budget = FrequencySeriesDict.from_gwinc_budget("aLIGO") >>> quantum = FrequencySeries.from_gwinc_budget("aLIGO", trace_name="Quantum")
- gwexpy.interop.from_meep_hdf5(cls: type, filepath: str | Path, *, field_name: str | None = None, component: str | None = None, resolution: float | None = None, origin: tuple[float, ...] | None = None, axis0_domain: Literal['time', 'frequency'] = 'frequency', unit: Any | None = None) Any[source]
Read a Meep HDF5 field output into a ScalarField or VectorField.
Meep writes electromagnetic field data as HDF5 files with dataset naming conventions:
Complex fields:
<name>.r(real part) and<name>.i(imaginary part).Real-only fields:
<name>(no suffix).
Common field names are
ex,ey,ez,hx,hy,hz.- Parameters:
cls (type) β
ScalarFieldorVectorFieldclass to instantiate.filepath (str or Path) β Path to the HDF5 file produced by Meep.
field_name (str, optional) β
Base name of the field dataset(s) to read. If None, all datasets are auto-detected:
ScalarFieldcls β first dataset found.VectorFieldcls β all recognised vector components.
component (str, optional) β Specific component to extract (e.g.,
"ex"). When given, a singleScalarFieldis always returned, regardless of cls.resolution (float, optional) β Meep resolution (grid points per unit length). Used to build spatial coordinate axes. Defaults to
1.0when not set.origin (tuple of float, optional) β Grid origin coordinates (x, y, z) in Meep length units. Defaults to
(0.0, 0.0, 0.0).axis0_domain ({"time", "frequency"}, default "frequency") β Physical domain of axis 0 in the resulting field. Meep frequency-domain outputs should use
"frequency"; time snapshots should use"time".unit (str or astropy.units.Unit, optional) β Physical unit to assign to the field data.
- Returns:
ScalarField β When
componentis given, or only one component is found, or cls isScalarField.VectorField β When multiple vector components are found and cls is
VectorField.
- Raises:
ValueError β If no matching datasets are found in the file, or if real/imaginary dataset shapes do not match.
ImportError β If
h5pyis not installed.
Examples
Read the Ez component from a frequency-domain output:
>>> from gwexpy.fields import ScalarField >>> sf = ScalarField.from_meep_hdf5("ez.h5")
Read all E-field components as a VectorField:
>>> from gwexpy.fields import VectorField >>> vf = VectorField.from_meep_hdf5("fields.h5")
- gwexpy.interop.from_openems_hdf5(cls: type, filepath: str | Path, *, dump_type: int = 0, timestep: int | None = None, frequency_index: int | None = None, component: Literal['x', 'y', 'z'] | None = None, unit: Any | None = None) ScalarField | VectorField[source]
Read an openEMS field dump HDF5 file into a ScalarField or VectorField.
openEMS dumps field data as HDF5 files containing mesh coordinates under
/Mesh/x,/Mesh/y,/Mesh/zand field values under/FieldData/TD(time domain) or/FieldData/FD(frequency domain). Each time step or frequency bin stores a 4-D array of shape(Nx, Ny, Nz, 3)where the last axis holds the x, y, z components.- Parameters:
cls (type) β
ScalarFieldorVectorFieldclass.filepath (str or Path) β Path to the HDF5 dump file.
dump_type (int, default 0) β
openEMS
DumpTypevalue used when the dump was configured. Determines the physical quantity and domain:0 β E-field, time domain
1 β H-field, time domain
10 β E-field, frequency domain
11 β H-field, frequency domain
20-22 β SAR (scalar, frequency domain)
timestep (int, optional) β For time-domain dumps: which step index to extract.
Noneloads all steps along axis 0.frequency_index (int, optional) β For frequency-domain dumps: which frequency index to extract.
Noneloads all frequencies along axis 0.component ({"x", "y", "z"}, optional) β Return a single vector component as
ScalarField.Nonereturns all three components asVectorField.unit (str or astropy.units.Unit, optional) β Override the physical unit. Defaults to the unit implied by dump_type (see
DUMP_TYPE_MAP).
- Returns:
ScalarField β When component is given, dump type is SAR, or cls is
ScalarField.VectorField β When component is
Noneand cls isVectorField.
- Raises:
ValueError β If the required field group is absent, or if a requested time step / frequency index does not exist.
ImportError β If
h5pyis not installed.
Examples
Read all components of a time-domain E-field dump:
>>> from gwexpy.fields import VectorField >>> vf = VectorField.from_openems_hdf5("e_dump.h5", dump_type=0)
Read only the z-component:
>>> from gwexpy.fields import ScalarField >>> sf = ScalarField.from_openems_hdf5("e_dump.h5", component="z")
- gwexpy.interop.from_emg3d_field(cls: type, field: Any, *, component: str | None = None, interpolate_to_cell_center: bool = True) ScalarField | VectorField[source]
Convert an
emg3d.fields.Fieldto a GWexpyVectorField.The emg3d
Fieldstores each Cartesian component (fx, fy, fz) on a staggered (Yee) grid where component shapes may differ. When interpolate_to_cell_center isTrue(default), each component is averaged to the common cell-centre grid so that all threeScalarFieldobjects share the same spatial shape.- Parameters:
cls (type) β
VectorField(default) orScalarFieldclass.field (emg3d.fields.Field) β emg3d field object. Must have attributes
fx,fy,fz,grid, andelectric(bool).component ({"x", "y", "z"}, optional) β Extract a single Cartesian component and return a
ScalarField.Nonereturns all three components as aVectorField.interpolate_to_cell_center (bool, default True) β Interpolate staggered-grid components to cell centres. Setting this to
FalseraisesValueErrorif the shapes differ.
- Returns:
ScalarField β When component is specified or cls is
ScalarField.VectorField β When component is
Noneand cls isVectorField.
- Raises:
ValueError β If
interpolate_to_cell_center=Falseand component shapes differ.
Examples
>>> from gwexpy.fields import VectorField >>> vf = VectorField.from_emg3d_field(field)
>>> from gwexpy.fields import ScalarField >>> sf = ScalarField.from_emg3d_field(field, component="z")
- gwexpy.interop.from_emg3d_h5(cls: type, filepath: str | Path, *, name: str = 'field', component: str | None = None, interpolate_to_cell_center: bool = True) ScalarField | VectorField[source]
Load an emg3d field saved via
emg3d.save()and convert it.- Parameters:
cls (type) β
VectorFieldorScalarField.filepath (str or Path) β Path to the HDF5 / npz / json file written by
emg3d.save().name (str, default "field") β Key under which the field was saved (kwarg name passed to
emg3d.save(**{name: field})).component ({"x", "y", "z"}, optional) β Extract a single component.
interpolate_to_cell_center (bool, default True) β See
from_emg3d_field().
- Return type:
ScalarField or VectorField
- gwexpy.interop.to_emg3d_field(vf: VectorField | ScalarField, *, frequency: float | None = None, electric: bool = True) Any[source]
Convert a GWexpy VectorField back to an
emg3d.fields.Field.- Parameters:
vf (VectorField or ScalarField) β Source field. For
VectorField, components"x","y","z"are expected. ForScalarFieldthe single component is broadcast as the x-component.frequency (float, optional) β Field frequency in Hz. Overrides
vfβs axis0 value when given.electric (bool, default True) β Whether the field is an E-field (
True) or H-field (False).
- Returns:
Reconstructed field object.
- Return type:
emg3d.fields.Field
- Raises:
ImportError β If
emg3dis not installed.ValueError β If the VectorField does not contain exactly 3 components.
- gwexpy.interop.from_meshio(cls: type, mesh: Any, *, field_name: str | None = None, grid_resolution: float, method: str = 'linear', axis0: ndarray | None = None, axis0_domain: Literal['time', 'frequency'] = 'time', unit: Any | None = None) ScalarField | VectorField[source]
Convert a
meshio.Meshto a GWexpyScalarFieldorVectorField.The unstructured mesh data is interpolated onto a regular grid using
scipy.interpolate.griddata.- Parameters:
cls (type) β
ScalarFieldorVectorField.mesh (meshio.Mesh) β Input mesh object.
field_name (str, optional) β Key in
point_dataorcell_datato use. Defaults to the first available field.grid_resolution (float) β Spacing of the output regular grid (mandatory).
method ({"linear", "nearest"}, default "linear") β Interpolation method.
axis0 (ndarray, optional) β Values for axis0 (e.g. time steps). Default: singleton
[0].axis0_domain ({"time", "frequency"}, default "time") β Physical domain of axis0.
unit (str or astropy unit, optional) β Unit of the field values.
- Return type:
ScalarField or VectorField
Notes
Only
point_datais supported for interpolation. If the mesh contains onlycell_dataand nopoint_data, aValueErroris raised. To use cell data, first convert it to point data (e.g. meshioβscell_data_to_point_datautility).
- gwexpy.interop.from_fenics_xdmf(cls: type, filepath: str | Path, *, field_name: str | None = None, grid_resolution: float, method: str = 'linear', unit: Any | None = None) ScalarField | VectorField[source]
Read a dolfinx XDMF file via meshio and convert to ScalarField.
- Parameters:
cls (type) β
ScalarFieldorVectorField.filepath (str or Path) β Path to the
.xdmffile.field_name (str, optional) β Field name in the XDMF data.
grid_resolution (float) β Regular grid spacing (mandatory).
method ({"linear", "nearest"}, default "linear") β Interpolation method.
unit (str or astropy unit, optional) β Physical unit of the field values.
- Return type:
ScalarField or VectorField
- gwexpy.interop.from_fenics_vtk(cls: type, filepath: str | Path, *, field_name: str | None = None, grid_resolution: float, method: str = 'linear', unit: Any | None = None) ScalarField | VectorField[source]
Read a VTK/VTU file via meshio and convert to ScalarField.
- Parameters:
cls (type) β
ScalarFieldorVectorField.filepath (str or Path) β Path to a
.vtkor.vtufile.field_name (str, optional) β Field name in the VTK point/cell data.
grid_resolution (float) β Regular grid spacing (mandatory).
method ({"linear", "nearest"}, default "linear") β Interpolation method.
unit (str or astropy unit, optional) β Physical unit of the field values.
- Return type:
ScalarField or VectorField
- gwexpy.interop.from_metpy_dataarray(cls: type, da: Any, *, dequantify: bool = True, axis0_domain: Literal['time', 'frequency'] = 'time') ScalarField[source]
Convert a MetPy-enhanced
xarray.DataArrayto aScalarField.MetPy attaches Pint units to data arrays via
.metpy.quantify(). This function strips the Pint layer (dequantify) and converts the unit toastropy.unitsbefore creating a ScalarField.- Parameters:
cls (type) β
ScalarFieldclass.da (xarray.DataArray) β MetPy-enhanced DataArray. May have Pint-backed data or plain
float64data with a"units"attribute.dequantify (bool, default True) β Call
.metpy.dequantify()to strip Pint units and move them toattrs["units"]. Set toFalseif the array is already plain.axis0_domain ({"time", "frequency"}, default "time") β Physical domain of axis0.
- Return type:
ScalarField
Notes
MetPy must be installed for full functionality, but the converter also works with plain xarray DataArrays that have
"units"and"_metpy_axis"attributes.
- gwexpy.interop.from_wrf_variable(cls: type, da: Any, *, vertical_dim: str | None = None, axis0_domain: Literal['time', 'frequency'] = 'time') ScalarField[source]
Convert a
wrf.getvar()xarray.DataArray to aScalarField.WRF dimension names are mapped to GWexpy axes:
Time/timeβ axis0west_eastβ axis1 (x)south_northβ axis2 (y)bottom_topβ axis3 (z)
2-D
XLAT/XLONGcoordinates are collapsed to 1-D when the grid is regular.- Parameters:
- Return type:
ScalarField
- gwexpy.interop.from_harmonica_grid(cls: type, ds: Any, *, data_name: str | None = None) ScalarField | VectorField[source]
Convert a Harmonica xarray grid to a
ScalarFieldorVectorField.Harmonica grids typically have dimensions
easting/northing(for projected coordinates) orlongitude/latitude(for geographic coordinates), with an optionalupwarddimension for height.- Parameters:
cls (type) β
ScalarFieldorVectorField.ds (xarray.DataArray or xarray.Dataset) β Harmonica grid data. A
Datasetis treated as aVectorFieldunless data_name is given, in which case a single variable is extracted.data_name (str, optional) β Variable name to extract from a
Dataset. If not given and ds is aDataset, all variables become VectorField components.
- Returns:
ScalarField β When ds is a DataArray or data_name is given.
VectorField β When ds is a Dataset and data_name is not given.
- gwexpy.interop.from_lal_timeseries(cls: type[T_ts], lalts: Any, *, copy: bool = True) T_ts[source]
Create a GWexpy TimeSeries from a LAL TimeSeries struct.
- Parameters:
- Returns:
GWexpy TimeSeries with epoch, sample rate and unit from the LAL struct.
- Return type:
TimeSeries
Examples
>>> import lal >>> from gwexpy.timeseries import TimeSeries >>> lalts = lal.CreateREAL8TimeSeries("test", lal.LIGOTimeGPS(0), 0, 1/1024, lal.DimensionlessUnit, 1024) >>> ts = TimeSeries.from_lal(lalts)
- gwexpy.interop.to_lal_timeseries(ts: TimeSeries, *, dtype: str | None = None) Any[source]
Convert a GWexpy TimeSeries to a LAL TimeSeries struct.
- Parameters:
ts (TimeSeries) β GWexpy TimeSeries to convert.
dtype (str, optional) β LAL type string (e.g.,
"REAL8","COMPLEX16"). If None, inferred from the array dtype.
- Returns:
LAL time series struct.
- Return type:
lal.REAL8TimeSeries or similar
Examples
>>> from gwexpy.timeseries import TimeSeries >>> import numpy as np >>> ts = TimeSeries(np.zeros(1024), t0=0, dt=1/1024, name="test") >>> lalts = ts.to_lal()
- gwexpy.interop.from_lal_frequencyseries(cls: type[T_fs], lalfs: Any, *, copy: bool = True) T_fs[source]
Create a GWexpy FrequencySeries from a LAL FrequencySeries struct.
- Parameters:
- Returns:
GWexpy FrequencySeries with f0, df, epoch and unit from the LAL struct.
- Return type:
FrequencySeries
- gwexpy.interop.to_lal_frequencyseries(fs: FrequencySeries) Any[source]
Convert a GWexpy FrequencySeries to a LAL FrequencySeries struct.
- Parameters:
fs (FrequencySeries) β GWexpy FrequencySeries to convert.
- Returns:
LAL frequency series struct.
- Return type:
lal.REAL8FrequencySeries or similar
- gwexpy.interop.from_pycbc_timeseries(cls: type, pycbc_ts: Any, *, copy: bool = True) Any[source]
Create a GWexpy TimeSeries from a PyCBC TimeSeries.
- Parameters:
- Returns:
GWexpy TimeSeries with epoch, sample rate and unit from PyCBC.
- Return type:
TimeSeries
Examples
>>> from pycbc.types import TimeSeries as PyCBCTimeSeries >>> import numpy as np >>> pycbc_ts = PyCBCTimeSeries(np.zeros(1024), delta_t=1/1024, epoch=0) >>> from gwexpy.timeseries import TimeSeries >>> ts = TimeSeries.from_pycbc(pycbc_ts)
- gwexpy.interop.to_pycbc_timeseries(ts: Any) Any[source]
Convert a GWexpy TimeSeries to a PyCBC TimeSeries.
- Parameters:
ts (TimeSeries) β GWexpy TimeSeries to convert.
- Returns:
PyCBC time series.
- Return type:
pycbc.types.TimeSeries
Examples
>>> from gwexpy.timeseries import TimeSeries >>> import numpy as np >>> ts = TimeSeries(np.zeros(1024), t0=0, dt=1/1024) >>> pycbc_ts = ts.to_pycbc()
- gwexpy.interop.from_pycbc_frequencyseries(cls: type, pycbc_fs: Any, *, copy: bool = True) Any[source]
Create a GWexpy FrequencySeries from a PyCBC FrequencySeries.
- Parameters:
- Returns:
GWexpy FrequencySeries with df, epoch and unit from PyCBC.
- Return type:
FrequencySeries
Examples
>>> from pycbc.types import FrequencySeries as PyCBCFrequencySeries >>> import numpy as np >>> pycbc_fs = PyCBCFrequencySeries(np.zeros(512, dtype=complex), delta_f=1.0, epoch=0) >>> from gwexpy.frequencyseries import FrequencySeries >>> fs = FrequencySeries.from_pycbc(pycbc_fs)
- gwexpy.interop.to_pycbc_frequencyseries(fs: Any) Any[source]
Convert a GWexpy FrequencySeries to a PyCBC FrequencySeries.
- Parameters:
fs (FrequencySeries) β GWexpy FrequencySeries to convert.
- Returns:
PyCBC frequency series.
- Return type:
pycbc.types.FrequencySeries
Examples
>>> from gwexpy.frequencyseries import FrequencySeries >>> import numpy as np >>> fs = FrequencySeries(np.zeros(512, dtype=complex), frequencies=np.arange(512)) >>> pycbc_fs = fs.to_pycbc()
- class gwexpy.interop.TimeSeriesWindowDataset(series, *, window: int, stride: int = 1, horizon: int = 0, labels: TimeSeries | TimeSeriesMatrix | np.ndarray | Callable | None = None, multivariate: bool = False, align: str = 'intersection', device=None, dtype=None)[source]
Bases:
objectSimple windowed dataset wrapper for torch training loops.
- gwexpy.interop.to_torch_dataset(obj, *, window: int, stride: int = 1, horizon: int = 0, labels: TimeSeries | TimeSeriesMatrix | np.ndarray | Callable | None = None, multivariate: bool = False, align: str = 'intersection', device=None, dtype=None)[source]
Build a
TimeSeriesWindowDatasetfrom the provided object.
- gwexpy.interop.to_torch_dataloader(dataset, *, batch_size: int = 1, shuffle: bool = False, num_workers: int = 0, **kwargs)[source]
Create a torch
DataLoaderfrom the provided dataset.
- gwexpy.interop.from_sdynpy_shape(shape_array: Any) Any[source]
Convert an SDynPy
ShapeArrayto apandas.DataFrame.- Parameters:
shape_array (sdynpy.core.sdynpy_shape.ShapeArray) β SDynPy shape array. Must expose
.frequency,.damping,.shape_matrix, and.coordinateattributes.- Returns:
Columns include DOF labels, optional node coordinates, and
mode_1 ... mode_Ncolumns.frequency_Hzanddamping_ratioare stored indf.attrs.- Return type:
pandas.DataFrame
- gwexpy.interop.from_sdynpy_frf(cls: type, tfa: Any, *, response_type: str | None = None) Any[source]
Convert an SDynPy
TransferFunctionArrayto aFrequencySeriesMatrix.
- gwexpy.interop.from_sdynpy_timehistory(cls: type, tha: Any, *, response_type: str | None = None) Any[source]
Convert an SDynPy
TimeHistoryArrayto aTimeSeriesMatrix.
- gwexpy.interop.from_uff_dataset58(cls: type, uff_data: dict, *, response_type: str | None = None) Any[source]
Convert a pyuff dataset-58 dict to
TimeSeriesorFrequencySeries.- Parameters:
cls (type) β
TimeSeriesorFrequencySeries. If None or ambiguous, the function type field in the UFF data is used to auto-select.uff_data (dict) β A single dataset-58 record as returned by
pyuff.UFF().read_sets(). Expected keys:"x","data","func_type","id1"(description),"rsp_dir","ref_dir", etc.response_type (str, optional) β Override for unit inference (e.g.
"accel").
- Return type:
TimeSeries or FrequencySeries
- gwexpy.interop.from_uff_dataset55(uff_data: dict) Any[source]
Convert a pyuff dataset-55 dict to a
pandas.DataFrame.Dataset type 55 contains modal model data: natural frequencies, modal damping, and mode shapes.
- Parameters:
uff_data (dict) β A single dataset-55 record from
pyuff.UFF().read_sets(). Expected keys:"modal_m"(mode number),"modal_freq","modal_damp","modal_viscous_damp","r1"β"r6"(DOF responses),"node_nums", etc.- Return type:
pandas.DataFrame
- gwexpy.interop.from_pyoma_results(cls: type, results: dict, *, fs: float | None = None) Any[source]
Convert pyOMA result dict to a GWexpy type.
- Parameters:
cls (type) β Target type. Use
pandas.DataFrame(or pass the string"DataFrame") for modal parameter summary, orFrequencySeriesMatrixfor mode-shape based FRF reconstruction.results (dict) β
pyOMA result dictionary. Expected keys:
"Fn": ndarray (n_modes,) β natural frequencies [Hz]"Zeta": ndarray (n_modes,) β damping ratios"Phi": ndarray (n_dof, n_modes) β mode-shape matrix (optional)"Xi": alias for"Zeta"in some pyOMA versions"Freq": alias for"Fn"in some versions
fs (float, optional) β Sampling frequency [Hz]. Stored in metadata.
- Return type:
pandas.DataFrame or FrequencySeriesMatrix
- gwexpy.interop.from_opensees_recorder(cls: type, filepath: str | Path, *, nodes: list[int], dofs: list[int], response_type: str = 'disp', dt: float | None = None, has_time_column: bool = True) Any[source]
Read an OpenSeesPy recorder text file into a
TimeSeriesMatrix.- Parameters:
cls (type) β
TimeSeriesMatrixorTimeSeriesDict.filepath (str or Path) β Path to the recorder output file (space-delimited text).
dofs (list[int]) β DOF numbers recorded per node (1-based, e.g.
[1, 2, 3]for X, Y, Z).response_type (str) β Response quantity for unit inference (
"disp","vel","accel","force").dt (float, optional) β Time step. Required if has_time_column is
False.has_time_column (bool) β Whether the first column is a time vector (default
True).
- Return type:
TimeSeriesMatrix or TimeSeriesDict
- gwexpy.interop.from_exudyn_sensor(cls: type, data: ndarray | str | Path, *, output_variable: str = 'Displacement', column_names: list[str] | None = None) Any[source]
Convert Exudyn sensor data to
TimeSeriesorTimeSeriesMatrix.- Parameters:
cls (type) β
TimeSeriesorTimeSeriesMatrix.data (ndarray or str or Path) β Either the array returned by
mbs.GetSensorStoredData()(column 0 = time), or a path to a space-delimited text file with the same layout.output_variable (str) β Exudyn output variable name (e.g.
"Displacement","Velocity","Force"). Used for unit inference.column_names (list[str], optional) β Names for non-time columns. If not given, default names like
"col_0","col_1"etc. are used.
- Return type:
TimeSeries or TimeSeriesMatrix
- gwexpy.interop.from_mtspec(cls: type, mt: Any, *, quantity: Literal['psd', 'asd'] = 'psd', include_ci: bool = True) Any[source]
Convert a Prieto
MTSpec/MTSineobject to a GWexpy type.- Parameters:
cls (type) β Target type. Pass
FrequencySeriesto always receive a plain spectrum (CI is discarded even when available). PassFrequencySeriesDictto receive a dict that includes CI series when CI is available.mt (multitaper.mtspec.MTSpec or multitaper.mtsine.MTSine) β
Computed multitaper object. Expected attributes:
freq: ndarray (nf,) β frequency axis [Hz]spec: ndarray (nf,) β adaptive-weighted PSDspec_ci: ndarray (nf, 2) β 95 % jackknife CI[lower, upper](optional; not present onMTSine)se: ndarray (nf,) β degrees of freedom per bin (optional)
quantity ({"psd", "asd"}, default "psd") β Whether to return power or amplitude spectral density.
"asd"appliesnp.sqrtto the PSD.include_ci (bool, default True) β If True and the object carries
spec_ci, return aFrequencySeriesDictwith keys"psd"/"asd","ci_lower", and"ci_upper". Ignored when the CI attribute is absent.
- Returns:
FrequencySeries β When CI is unavailable or
include_ci=False.FrequencySeriesDict β When CI is available and
include_ci=True.
- Raises:
ValueError β If
quantityis not"psd"or"asd", or if the frequency axis is empty.
- gwexpy.interop.from_mtspec_array(cls: type, spectrum: ndarray, freq: ndarray, *, quantity: Literal['psd', 'asd'] = 'psd', ci_lower: ndarray | None = None, ci_upper: ndarray | None = None, unit: Any | None = None) Any[source]
Convert Krischer
mtspecfunction output to a GWexpy type.- Parameters:
cls (type) β Target type. Pass
FrequencySeriesto always receive a plain spectrum (CI is discarded even when available). PassFrequencySeriesDictto receive a dict that includes CI series when CI is available.spectrum (array-like, shape (nf,)) β PSD (or ASD, depending on
quantity) array returned bymtspec.mtspec().freq (array-like, shape (nf,)) β Frequency axis [Hz] returned by
mtspec.mtspec().quantity ({"psd", "asd"}, default "psd") β Whether spectrum is a PSD or ASD. Set to
"asd"to interpret the input as amplitude spectral density.ci_lower (array-like, shape (nf,), optional) β Lower confidence-interval bound (same units as spectrum).
ci_upper (array-like, shape (nf,), optional) β Upper confidence-interval bound (same units as spectrum).
unit (str or astropy.units.Unit, optional) β Physical unit of the spectral density values.
- Returns:
FrequencySeries β When ci_lower and ci_upper are both None.
FrequencySeriesDict β When either CI array is provided. Keys:
"psd"/"asd","ci_lower","ci_upper".
- Raises:
ValueError β If
quantityis not"psd"or"asd", if freq is not equally spaced, or if shapes are inconsistent.
Standard Formatsο
|
|
|
|
|
|
|
SQLite interop helpers. |
|
|
|
Object-level NetCDF4 bridge helpers. |
Data Analysis Librariesο
|
|
|
Polars interop helpers. |
|
|
|
|
|
Array and Tensor Librariesο
|
Interoperability with PyTorch tensors. |
|
|
|
TensorFlow interop helpers. |
|
JAX interop helpers. |
|
CuPy interop helpers. |
Domain Specific Librariesο
|
Interoperate with the Finesse 3 interferometer simulation library. |
|
Provide interoperability with the |
|
SimPEG interop helpers. |
|
Interoperate with the MTH5 magnetotelluric HDF5 format. |
|
|
|
Neo interop helpers. |
|
quantities interop helpers. |
|
Interoperate with pyroomacoustics simulation results. |
|
Audio interop helpers for pydub and librosa-oriented exports. |
|
Interoperability with specutils. |
|
Interoperability with pyspeckit. |
|
Interoperate with PySpice circuit simulation results. |
|
Interoperability with scikit-rf for RF and microwave network analysis. |
|
Interoperate with pyOMA operational modal analysis results. |
|
Interoperate with multitaper spectral estimation packages. |
|
Interoperability with SDyPy and pyuff (Universal File Format). |
|
Interoperability with SDynPy (Structural Dynamics in Python). |
|
Interoperate with Meep FDTD simulation output files. |
|
Interoperate with openEMS field dump HDF5 files. |
|
Interoperate with emg3d electromagnetic modelling fields. |
|
Interoperate with meshio unstructured-mesh field data. |
|
Interoperate with MetPy xarray data arrays. |
|
Interoperability with |
|
Interoperate with Harmonica gravity and magnetic grids. |
|
Interoperate with Exudyn sensor output. |
|
Interoperate with OpenSeesPy recorder output. |
|
|
|
Interoperate with LALSuite time and frequency series. |
|
Interoperate with pygwinc noise budgets. |
|
Interoperate with PyCBC time and frequency series. |
|