開発版ドキュメント · 0.2.3 30c2f8ba · 入門例の検証対象 0.2.3 · 版情報 · 既知の制限

Interoperability (gwexpy.interop)#

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

Convert TimeSeries to pandas.Series.

パラメータ:
  • ts (TimeSeries) -- Input time series to convert.

  • index (str, default "datetime") -- "datetime" (UTC aware), "seconds" (unix), or "gps".

  • name (str, optional) -- Override name for the resulting series.

  • copy (bool) -- Whether to copy data.

戻り値の型:

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, channel: str | None = None, name: str | None = None) T

Create a TimeSeries from pandas.Series.

t0/dt are inferred from the index when possible; if inference fails they fall back to 0/1 with a UserWarning rather than silently. channel/name (which a plain Series cannot carry) may be supplied explicitly.

gwexpy.interop.to_pandas_dataframe(tsd: TimeSeriesDict, index: Literal['datetime', 'seconds', 'gps'] = 'datetime', copy: bool = False) pd.DataFrame

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

Convert DataFrame to TimeSeriesDict.

gwexpy.interop.to_xarray(ts: TimeSeries, time_coord: Literal['datetime', 'seconds', 'gps'] = 'datetime') xr.DataArray

Convert TimeSeries to xarray.DataArray.

gwexpy.interop.from_xarray(cls: type[T], da: xr.DataArray, *, unit: str | None = None, channel: str | None = None, name: str | None = None) T

Convert xarray.DataArray to TimeSeries.

t0/dt are recomputed from the time coordinate. Metadata absent from the source (unit/channel/name) can be supplied explicitly; an explicit argument takes priority over the stored attribute.

gwexpy.interop.to_xarray_field(field: Any, *, dim_names: tuple[str, str, str, str] | None = None) Any

Convert a ScalarField or VectorField to an xarray DataArray / Dataset.

パラメータ:
  • field (ScalarField or VectorField) -- Source field.

  • dim_names (tuple of 4 str, optional) -- Dimension names (axis0, axis1, axis2, axis3). Defaults to field.axis_names when available, then to ("t", "x", "y", "z").

戻り値:

  • 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

Convert an xarray.DataArray or Dataset to a ScalarField / VectorField.

Dimension auto-detection priority:

  1. CF Convention axis attribute (T / X / Y / Z)

  2. MetPy _metpy_axis attribute

  3. Heuristic name matching

パラメータ:
  • cls (type) -- ScalarField or VectorField.

  • da (xarray.DataArray or xarray.Dataset) -- Input array. A Dataset is 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 when None. 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.

戻り値:

  • 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

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, *, unit: str | None = None, channel: str | None = None, name: str | None = None, t0: float | None = None, dt: float | None = None) T

Read TimeSeries from HDF5 group.

The channel attribute written by to_hdf5() is restored (closing a write-but-not-read round-trip gap). Metadata absent from the dataset can be supplied explicitly; an explicit argument takes priority over the stored attribute. Missing t0/dt fall back to 0/1 with a UserWarning rather than silently.

gwexpy.interop.to_obspy_trace(ts, stats_extra=None, dtype=None)

Legacy alias for internal use, prefers using new generic to_obspy.

gwexpy.interop.from_obspy_trace(cls, tr, unit=None, name_policy='id')

Legacy alias.

gwexpy.interop.to_obspy(data, **kwargs)

Convert gwexpy object to Obspy object.

FrequencySeries -> Trace (Spectrum mode) Spectrogram -> Stream (Filter Bank mode) TimeSeries -> Trace

gwexpy.interop.from_obspy(cls, data, **kwargs)

Convert an Obspy object to a GWexpy object of type cls.

gwexpy.interop.to_specutils(data, **kwargs)

Convert a gwexpy object to a specutils object.

パラメータ:
  • data (FrequencySeries) -- Input data.

  • **kwargs -- Additional arguments for Spectrum1D constructor.

戻り値の型:

specutils.Spectrum1D

gwexpy.interop.from_specutils(cls, spectrum, **kwargs)

Convert a specutils object to a gwexpy object.

パラメータ:
  • cls (class) -- Target class (FrequencySeries).

  • spectrum (specutils.Spectrum1D) -- Input spectrum.

  • **kwargs -- Additional keyword arguments passed to the target constructor.

戻り値の型:

FrequencySeries

gwexpy.interop.to_pyspeckit(data, **kwargs)

Convert a gwexpy object to a pyspeckit Spectrum.

パラメータ:
  • data (FrequencySeries) -- Input data.

  • **kwargs -- Additional arguments for pyspeckit.Spectrum.

戻り値の型:

pyspeckit.Spectrum

gwexpy.interop.from_pyspeckit(cls, spectrum, **kwargs)

Convert a pyspeckit Spectrum to a gwexpy object.

パラメータ:
  • cls (class) -- Target class (FrequencySeries).

  • spectrum (pyspeckit.Spectrum) -- Input spectrum.

  • **kwargs -- Additional keyword arguments passed to the target constructor.

戻り値の型:

FrequencySeries

gwexpy.interop.to_polars_series(ts, name=None)

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')

Convert TimeSeries to polars.DataFrame with a time column.

gwexpy.interop.from_polars_series(cls, series, unit=None, t0=None, dt=None, channel=None, name=None)

Create TimeSeries or FrequencySeries from polars.Series.

A plain polars Series carries no timing or channel metadata. Missing t0/dt fall back to 0/1 with a UserWarning (instead of silently), and channel/name may be supplied explicitly.

gwexpy.interop.from_polars_dataframe(cls, df, index_column='time', unit=None, *, channel=None, name=None)

Create TimeSeries from polars.DataFrame.

t0/dt are inferred from the time column (handling GPS, unix and datetime values). If the column is empty or holds a single sample, the missing timing falls back to 0/1 with a UserWarning instead of silently. channel (which a DataFrame cannot carry) and name may be supplied explicitly; name defaults to the data column label.

gwexpy.interop.to_polars_frequencyseries(fs, index_column='frequency', index_unit='Hz')

Convert FrequencySeries to polars.DataFrame.

gwexpy.interop.to_polars_dict(tsd, index_column='time', time_unit='datetime')

Convert TimeSeriesDict to polars.DataFrame.

gwexpy.interop.from_polars_dict(cls, df, index_column='time', unit_map=None)

Convert polars.DataFrame to TimeSeriesDict.

gwexpy.interop.to_tgraph(series: Any, error: Any | None = None) ROOT.TGraph

Convert a 1D series to a ROOT TGraph or TGraphErrors.

gwexpy.interop.to_th1d(series: Any, error: Any | None = None) ROOT.TH1D

Convert a 1D series to a ROOT TH1D.

gwexpy.interop.to_th2d(spec: Spectrogram, error: Any | None = None) ROOT.TH2D

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]

Create a GWexpy series object from a ROOT TGraph or TH1.

gwexpy.interop.to_tmultigraph(collection, name: str | None = None) Any

Convert a collection of series to a ROOT TMultiGraph.

gwexpy.interop.write_root_file(collection, filename: str, **kwargs: Any) None

Write a collection of series to a ROOT TFile.

gwexpy.interop.to_sqlite(ts, conn, series_id=None, overwrite=False)

Write a time series into a SQLite connection and return its id.

gwexpy.interop.from_sqlite(cls, conn, series_id)

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

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

Create a FrequencySeries from a pandas Series.

gwexpy.interop.to_xarray_frequencyseries(fs: FrequencySeries, freq_coord: Literal['Hz'] = 'Hz') xr.DataArray

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

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

Write a FrequencySeries to an HDF5 group.

gwexpy.interop.from_hdf5_frequencyseries(cls: type[T], group: h5py.Group, path: str) T

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

Convert a series to a PyTorch tensor.

パラメータ:
  • 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.

戻り値:

The converted tensor.

戻り値の型:

torch.Tensor

gwexpy.interop.from_torch(cls: type[T], tensor: torch.Tensor, t0: Any, dt: Any, unit: str | None = None) T

Create a TimeSeries from a PyTorch tensor.

パラメータ:
  • cls (type) -- TimeSeries class to instantiate.

  • tensor (torch.Tensor) -- Input tensor.

  • t0 (Quantity or float) -- Start time.

  • dt (Quantity or float) -- Sample interval.

  • unit (str or Unit, optional) -- Data unit.

戻り値:

The created time series.

戻り値の型:

TimeSeries

gwexpy.interop.to_tf(ts, dtype=None)

Convert a time series to a TensorFlow tensor.

gwexpy.interop.from_tf(cls, tensor, t0, dt, unit=None)

Create a time series from a TensorFlow tensor.

gwexpy.interop.to_dask(ts, chunks='auto')

Convert a TimeSeries to a dask.array.Array.

gwexpy.interop.from_dask(cls, array, t0, dt, unit=None, compute=True)

Create TimeSeries from dask array.

パラメータ:
  • 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

Write to a Zarr array.

gwexpy.interop.from_zarr(cls: type[T], store: Any, path: str) T

Read from a Zarr array.

gwexpy.interop.to_netcdf4(ts, ds, var_name, dim_time='time', time_units=None, overwrite=False)

Write to netCDF4 Dataset.

ds: netCDF4.Dataset (writable)

gwexpy.interop.from_netcdf4(cls, ds, var_name, *, unit=None, channel=None, name=None, t0=None, dt=None)

Read from a netCDF4 dataset.

Metadata absent from the variable can be supplied explicitly; an explicit argument takes priority over the stored attribute. Missing t0/dt fall back to 0/1 with a UserWarning rather than silently.

gwexpy.interop.to_control_frd(fs: FrequencySeries, frequency_unit: Literal['rad/s', 'Hz'] = 'rad/s') control.FRD

Convert FrequencySeries to control.FRD.

パラメータ:
  • 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 for control.FRD).

戻り値:

Frequency response data object compatible with python-control.

戻り値の型:

control.FRD

サンプル

>>> 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

Create FrequencySeries from control.FRD.

パラメータ:
  • cls (type) -- The FrequencySeries class to instantiate.

  • frd (control.FRD) -- Frequency response data from python-control.

  • frequency_unit (str, optional) -- Unit of the input FRD's omega attribute. Either 'Hz' or 'rad/s'. Default is 'Hz' (output will be in Hz).

戻り値:

The converted frequency response. Returns FrequencySeriesMatrix for MIMO systems.

戻り値の型:

FrequencySeries or FrequencySeriesMatrix

サンプル

>>> 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

Create TimeSeries or TimeSeriesDict from control.TimeResponseData.

パラメータ:
  • cls (type) -- The TimeSeries (or TimeSeriesDict) class.

  • response (control.TimeResponseData) -- The simulation result from python-control (e.g., from forced_response).

  • **kwargs (dict) -- Additional arguments passed to the TimeSeries constructor (e.g., unit).

戻り値:

The converted time-domain data.

戻り値の型:

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

Create a frequency-series object from a Finesse 3 response solution.

パラメータ:
  • 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.

戻り値:

  • 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).

サンプル

>>> 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

Create a frequency-series object from a Finesse 3 noise solution.

パラメータ:
  • 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)").

戻り値:

  • FrequencySeries -- When a single output and noise source are both specified.

  • FrequencySeriesDict -- When multiple outputs or noise sources are present.

サンプル

>>> 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

Create TimeSeries or TimeSeriesDict from a PySpice TransientAnalysis.

パラメータ:
  • 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").

戻り値:

  • TimeSeries -- When a single node or branch is specified.

  • TimeSeriesDict -- When neither node nor branch is given; keyed by signal name.

サンプル

>>> 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

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.

パラメータ:
  • 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").

戻り値:

  • FrequencySeries -- When a single signal is selected; data is complex.

  • FrequencySeriesDict -- When no specific signal is selected; keyed by signal name.

サンプル

>>> 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

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.

パラメータ:
  • 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").

戻り値:

  • FrequencySeries -- When a single signal is selected; data is real.

  • FrequencySeriesDict -- When no signal is selected; keyed by signal name.

サンプル

>>> 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

Create FrequencySeries or FrequencySeriesDict from a PySpice DistortionAnalysis.

Distortion analysis waveforms contain harmonic/intermodulation distortion components as a function of frequency.

パラメータ:
  • 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.

戻り値:

  • FrequencySeries -- When a single signal is selected.

  • FrequencySeriesDict -- When no signal is selected; keyed by signal name.

サンプル

>>> 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

Create GWexpy frequency objects from a scikit-rf network.

パラメータ:
  • 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 FrequencySeries directly.

    • Multi-port networks return a FrequencySeriesMatrix when cls is FrequencySeries, or a FrequencySeriesDict when cls is FrequencySeriesDict.

  • 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".

戻り値:

  • 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.

サンプル

>>> 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

Create a scikit-rf Network from a FrequencySeries or FrequencySeriesMatrix.

パラメータ:
  • fs (FrequencySeries or FrequencySeriesMatrix) -- Source data. A FrequencySeries is treated as a 1-port network (scalar parameter). A FrequencySeriesMatrix of 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.

戻り値:

The constructed Network object.

戻り値の型:

skrf.Network

サンプル

>>> 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

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.

パラメータ:
  • 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.

戻り値:

  • TimeSeries -- For a single port pair or a 1-port network.

  • TimeSeriesDict -- For a multi-port network when no port_pair is specified.

サンプル

>>> 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

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.

パラメータ:
  • 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.

戻り値:

  • TimeSeries -- For a single port pair or a 1-port network.

  • TimeSeriesDict -- For a multi-port network when no port_pair is specified.

サンプル

>>> 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

Create TimeSeries or TimeSeriesDict from pyroomacoustics room impulse responses.

パラメータ:
  • cls (type) -- The TimeSeries (or TimeSeriesDict) class to instantiate.

  • room (pyroomacoustics.Room) -- The room object after compute_rir() or simulate() has been called. room.rir must follow the pyroomacoustics convention rir[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.

戻り値:

  • TimeSeries -- When a single source-mic pair is selected.

  • TimeSeriesDict -- When multiple pairs are returned.

例外:

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

Create TimeSeries or TimeSeriesDict from pyroomacoustics microphone signals.

パラメータ:
  • 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.

戻り値:

  • TimeSeries -- When a single microphone is selected.

  • TimeSeriesDict -- When multiple microphones are returned.

例外:

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

Create TimeSeries from a pyroomacoustics sound source signal.

パラメータ:
  • 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.

戻り値の型:

TimeSeries

gwexpy.interop.from_pyroomacoustics_stft(cls: type, stft_obj: Any, *, channel: int | None = None, fs: float | None = None, unit: Any | None = None) Any

Create Spectrogram or SpectrogramDict from a pyroomacoustics STFT object.

パラメータ:
  • cls (type) -- The Spectrogram (or SpectrogramDict) class to instantiate.

  • stft_obj (pyroomacoustics.stft.STFT or similar) -- Object with .X (complex STFT data), .hop, and .N attributes.

  • 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_obj does not have an fs attribute.

  • unit (str or astropy.units.Unit, optional) -- Unit to assign to the result.

戻り値:

  • 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

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).

パラメータ:
  • 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 satisfy prod(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.

戻り値:

4D field with shape (nt, nx, ny, nz).

戻り値の型:

ScalarField

例外:

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]

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)
パラメータ:

ts (TimeSeries) -- The time series to export.

戻り値:

  • 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

Export Spectrogram as a pyroomacoustics STFT object.

パラメータ:
  • 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.

戻り値:

STFT object with .X set to the spectrogram data.

戻り値の型:

pyroomacoustics.stft.STFT

gwexpy.interop.to_jax(ts, dtype=None)

Convert a series-like object to a JAX array.

gwexpy.interop.from_jax(cls, array, t0, dt, unit=None)

Create a GWexpy object from a JAX array.

gwexpy.interop.to_cupy(obj, dtype=None)

Convert an object to a CuPy array.

gwexpy.interop.from_cupy(cls, array, t0, dt, unit=None)

Create a GWexpy object from a CuPy array.

gwexpy.interop.is_cupy_available()

Check whether CuPy is installed and the CUDA environment is usable.

gwexpy.interop.to_librosa(ts, y_dtype=<class 'numpy.float32'>)

Export to librosa-compatible numpy array and sampling rate.

Returns (y, sr).

gwexpy.interop.to_pydub(ts, sample_width=2, channels=1)

Export to a pydub AudioSegment.

gwexpy.interop.from_pydub(cls, seg, unit=None)

Create a time series from a pydub AudioSegment.

gwexpy.interop.to_astropy_timeseries(ts, column='value', time_format='gps')

Convert a gwexpy time series to astropy.timeseries.TimeSeries.

gwexpy.interop.from_astropy_timeseries(cls, ap_ts, column='value', unit=None)

Build a gwexpy series from an astropy.timeseries.TimeSeries.

gwexpy.interop.to_mne_rawarray(tsd, info=None, picks=None)

Convert a TimeSeries-like object to an mne.io.RawArray.

パラメータ:
  • tsd -- TimeSeriesDict-like mapping (multi-channel) or a single TimeSeries.

  • info -- Optional MNE Info. If omitted, a minimal Info is created.

  • picks -- Optional channel selection (names or indices). Only supported for mapping inputs.

戻り値:

The converted MNE Raw object.

戻り値の型:

mne.io.RawArray

例外:
  • TypeError -- If picks is given for a single-channel input.

  • ValueError -- If info's channel count does not match the input; if mapping channels have mismatched sampling frequency, length, or (for same-length channels) epoch; or if t0 conflicts with an existing info["meas_date"].

  • LeapSecondConversionError -- If t0 falls on a leap second.

メモ

The input epoch (t0) is reconciled with info["meas_date"]: if info has no meas_date yet, it is set from t0 (unless t0 == 0, which leaves it unset); if info already has a meas_date, t0 -- including 0 -- is always compared against it, and a mismatch beyond ~1us raises ValueError instead of silently overwriting or ignoring it. A t0 that falls on a leap second raises LeapSecondConversionError.

For a mapping input, all channels must share the same sampling frequency; a mismatch always raises ValueError (previously stacked silently), even when channel lengths differ. Same-length channels are then stacked without resampling/alignment and must also share an exactly matching epoch; a mismatch raises ValueError (previously stacked silently). Only channels of differing length (with matching sampling frequency) are automatically aligned, via to_matrix() on a TimeSeriesDict input -- sampling-frequency or epoch mismatches are never auto-aligned and must be resolved by the caller beforehand.

A mixed exact/legacy mapping uses MNE's one shared official time axis for the legacy channels, while GWexpy retains exact epochs as private per-channel in-memory metadata. Exact channels must still agree exactly on epoch and sample interval; exact/exact conflicts are rejected.

gwexpy.interop.from_mne_raw(cls, raw, unit_map=None)

Create a TimeSeriesDict from mne.io.Raw.

パラメータ:
  • cls -- The TimeSeriesDict-like class to construct and populate.

  • raw (mne.io.Raw) -- The MNE Raw object to convert.

  • unit_map (dict, optional) -- Optional mapping from channel name to unit, applied to the resulting TimeSeries entries. Channels absent from the mapping (or when unit_map is omitted) get unit=None.

戻り値:

A cls instance populated with one TimeSeries per channel.

戻り値の型:

TimeSeriesDict

メモ

The GPS epoch is reconstructed as datetime_utc_to_gps(raw.info["meas_date"]) + raw.first_samp / sfreq (or just the first_samp offset if meas_date is unset), so cropped or resumed Raw objects (first_samp > 0) get the correct absolute epoch instead of always starting at meas_date (or 0).

gwexpy.interop.to_mne(data, info=None, **kwargs)

Convert a gwexpy object to an MNE object.

パラメータ:
  • 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.

戻り値:

The converted MNE object (e.g. RawArray, SpectrumArray, EpochsTFRArray).

戻り値の型:

mne_object

gwexpy.interop.from_mne(cls, data, **kwargs)

Convert an MNE object to a gwexpy object.

パラメータ:
  • 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.

戻り値の型:

gwexpy object

gwexpy.interop.to_simpeg(data, location=None, rx_type='PointElectricField', orientation='x', **kwargs)

Convert gwexpy object to simpeg.data.Data.

パラメータ:
  • 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.

戻り値:

SimPEG Data object containing the survey and observed data.

戻り値の型:

simpeg.data.Data

gwexpy.interop.from_simpeg(cls, data_obj, **kwargs)

Convert SimPEG Data object to gwexpy object.

パラメータ:
  • cls (class) -- Target class (TimeSeries or FrequencySeries).

  • data_obj (simpeg.data.Data) -- SimPEG Data object.

  • **kwargs -- Reserved for future converter-specific options.

戻り値の型:

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

Write a TimeSeries to an MTH5 file.

パラメータ:
  • 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'.

例外:

ImportError -- If mth5 package is not installed.

サンプル

>>> 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)

Read a channel from MTH5 to TimeSeries.

パラメータ:
  • mth5_obj (str or mth5.mth5.MTH5) -- Open MTH5 object or path to HDF5 file.

  • station (str) -- Station name.

  • run (str) -- Run name.

  • channel (str) -- Channel name to read.

  • survey (str, optional) -- Survey name for MTH5 v0.2.0 files. If omitted, available surveys are searched.

戻り値:

The loaded time series data.

戻り値の型:

TimeSeries

例外:
  • ImportError -- If mth5 package is not installed.

  • KeyError -- If station, run, or channel is not found.

サンプル

>>> from gwexpy.interop.mt_ import from_mth5
>>> ts = from_mth5("data.h5", "Site01", "Run01", "Ex")
gwexpy.interop.to_neo(obj, units=None)

Convert a TimeSeries or TimeSeriesMatrix to neo.AnalogSignal.

gwexpy.interop.from_neo(cls, sig)

Create a TimeSeriesMatrix from a neo object.

Accepts a single neo.AnalogSignal, or a neo.Block/neo.Segment containing exactly one AnalogSignal (the form returned by most neo.io readers).

gwexpy.interop.to_quantity(series, units=None)

Convert a series (TimeSeries, FrequencySeries, etc) to a quantities.Quantity.

パラメータ:
  • 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.

戻り値:

The data wrapped as a Quantity.

戻り値の型:

quantities.Quantity

gwexpy.interop.from_quantity(cls, q, **kwargs)

Create a GWpy/GWexpy Series from a quantities.Quantity.

パラメータ:
  • 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).

戻り値の型:

instance of cls

gwexpy.interop.to_json(ts)

Convert TimeSeries to a JSON string.

Includes data and basic metadata.

gwexpy.interop.from_json(cls, json_str, **kwargs)

Create a TimeSeries from a JSON string.

Extra keyword arguments are forwarded to from_dict() so callers can override metadata (unit/channel/name/t0/dt) absent from the JSON payload.

gwexpy.interop.to_dict(ts)

Convert a TimeSeries to a dictionary.

gwexpy.interop.from_dict(cls, data_dict, *, unit=None, channel=None, name=None, t0=None, dt=None)

Create a TimeSeries from a dictionary.

Metadata not present in data_dict can be supplied explicitly via the keyword arguments; an explicit argument always takes priority over a value stored in the dictionary (user > source). Missing t0/dt fall back to 0/1 with a UserWarning rather than silently.

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

Create FrequencySeries or FrequencySeriesDict from a gwinc Budget.

パラメータ:
  • cls (type) -- FrequencySeries or FrequencySeriesDict class to instantiate.

  • budget_or_model (gwinc.Budget or str) -- Pre-loaded Budget object, or a model name string (e.g., "aLIGO", "Aplus") which is passed to gwinc.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:

    • FrequencySeries cls → total noise only.

    • FrequencySeriesDict cls → 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.

戻り値:

  • FrequencySeries -- When trace_name is given, or cls is FrequencySeries.

  • FrequencySeriesDict -- When trace_name is None and cls is FrequencySeriesDict. Keys: "Total", plus sub-trace names.

例外:
  • ValueError -- If trace_name does not exist in the budget trace hierarchy, or if quantity is not "asd" or "psd".

  • ImportError -- If pygwinc is not installed.

サンプル

Load a GWinc budget and convert its total noise PSD to an amplitude spectral density. GWinc's load_budget accepts a frequency array, and the module-level converter accepts the GWexpy target class explicitly:

>>> import gwinc
>>> import numpy as np
>>> from gwexpy.frequencyseries import FrequencySeries
>>> from gwexpy.interop import from_gwinc_budget
>>> frequencies = np.array([10.0, 100.0, 1000.0])
>>> budget = gwinc.load_budget("aLIGO", freq=frequencies)
>>> total_asd = from_gwinc_budget(
...     FrequencySeries, budget, frequencies=frequencies, quantity="asd"
... )

total_asd is the total aLIGO detector-noise ASD in 1 / sqrt(Hz) at the requested frequencies.

Passing FrequencySeriesDict instead returns the total together with every sub-trace, keyed by "Total" and the gwinc trace names:

>>> from gwexpy.frequencyseries import FrequencySeriesDict
>>> noise_budget = from_gwinc_budget(
...     FrequencySeriesDict, budget, frequencies=frequencies
... )

Use trace_name to pull a single sub-trace out as one ~gwexpy.frequencyseries.FrequencySeries:

>>> quantum = from_gwinc_budget(
...     FrequencySeries, budget, frequencies=frequencies, 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

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.

パラメータ:
  • cls (type) -- ScalarField or VectorField class 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:

    • ScalarField cls → first dataset found.

    • VectorField cls → all recognised vector components.

  • component (str, optional) -- Specific component to extract (e.g., "ex"). When given, a single ScalarField is always returned, regardless of cls.

  • resolution (float, optional) -- Meep resolution (grid points per unit length). Used to build spatial coordinate axes. Defaults to 1.0 when 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.

戻り値:

  • ScalarField -- When component is given, or only one component is found, or cls is ScalarField.

  • VectorField -- When multiple vector components are found and cls is VectorField.

例外:
  • ValueError -- If no matching datasets are found in the file, or if real/imaginary dataset shapes do not match.

  • ImportError -- If h5py is not installed.

サンプル

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

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/z and 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.

パラメータ:
  • cls (type) -- ScalarField or VectorField class.

  • filepath (str or Path) -- Path to the HDF5 dump file.

  • dump_type (int, default 0) --

    openEMS DumpType value 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. None loads all steps along axis 0.

  • frequency_index (int, optional) -- For frequency-domain dumps: which frequency index to extract. None loads all frequencies along axis 0.

  • component ({"x", "y", "z"}, optional) -- Return a single vector component as ScalarField. None returns all three components as VectorField.

  • unit (str or astropy.units.Unit, optional) -- Override the physical unit. Defaults to the unit implied by dump_type (see DUMP_TYPE_MAP).

戻り値:

  • ScalarField -- When component is given, dump type is SAR, or cls is ScalarField.

  • VectorField -- When component is None and cls is VectorField.

例外:
  • ValueError -- If the required field group is absent, or if a requested time step / frequency index does not exist.

  • ImportError -- If h5py is not installed.

サンプル

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

Convert an emg3d.fields.Field to a GWexpy VectorField.

The emg3d Field stores each Cartesian component (fx, fy, fz) on a staggered (Yee) grid where component shapes may differ. When interpolate_to_cell_center is True (default), each component is averaged to the common cell-centre grid so that all three ScalarField objects share the same spatial shape.

パラメータ:
  • cls (type) -- VectorField (default) or ScalarField class.

  • field (emg3d.fields.Field) -- emg3d field object. Must have attributes fx, fy, fz, grid, and electric (bool).

  • component ({"x", "y", "z"}, optional) -- Extract a single Cartesian component and return a ScalarField. None returns all three components as a VectorField.

  • interpolate_to_cell_center (bool, default True) -- Interpolate staggered-grid components to cell centres. Setting this to False raises ValueError if the shapes differ.

戻り値:

  • ScalarField -- When component is specified or cls is ScalarField.

  • VectorField -- When component is None and cls is VectorField.

例外:

ValueError -- If interpolate_to_cell_center=False and component shapes differ.

サンプル

>>> 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

Load an emg3d field saved via emg3d.save() and convert it.

パラメータ:
  • cls (type) -- VectorField or ScalarField.

  • 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().

戻り値の型:

ScalarField or VectorField

gwexpy.interop.to_emg3d_field(vf: VectorField | ScalarField, *, frequency: float | None = None, electric: bool = True) Any

Convert a GWexpy VectorField back to an emg3d.fields.Field.

パラメータ:
  • vf (VectorField or ScalarField) -- Source field. For VectorField, components "x", "y", "z" are expected. For ScalarField the 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).

戻り値:

Reconstructed field object.

戻り値の型:

emg3d.fields.Field

例外:
  • ImportError -- If emg3d is 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

Convert a meshio.Mesh to a GWexpy ScalarField or VectorField.

The unstructured mesh data is interpolated onto a regular grid using scipy.interpolate.griddata.

パラメータ:
  • cls (type) -- ScalarField or VectorField.

  • mesh (meshio.Mesh) -- Input mesh object.

  • field_name (str, optional) -- Key in point_data or cell_data to 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.

戻り値の型:

ScalarField or VectorField

メモ

Only point_data is supported for interpolation. If the mesh contains only cell_data and no point_data, a ValueError is raised. To use cell data, first convert it to point data (e.g. meshio's cell_data_to_point_data utility).

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

Read a dolfinx XDMF file via meshio and convert to ScalarField.

パラメータ:
  • cls (type) -- ScalarField or VectorField.

  • filepath (str or Path) -- Path to the .xdmf file.

  • 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.

戻り値の型:

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

Read a VTK/VTU file via meshio and convert to ScalarField.

パラメータ:
  • cls (type) -- ScalarField or VectorField.

  • filepath (str or Path) -- Path to a .vtk or .vtu file.

  • 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.

戻り値の型:

ScalarField or VectorField

gwexpy.interop.from_metpy_dataarray(cls: type, da: Any, *, dequantify: bool = True, axis0_domain: Literal['time', 'frequency'] = 'time') ScalarField

Convert a MetPy-enhanced xarray.DataArray to a ScalarField.

MetPy attaches Pint units to data arrays via .metpy.quantify(). This function strips the Pint layer (dequantify) and converts the unit to astropy.units before creating a ScalarField.

パラメータ:
  • cls (type) -- ScalarField class.

  • da (xarray.DataArray) -- MetPy-enhanced DataArray. May have Pint-backed data or plain float64 data with a "units" attribute.

  • dequantify (bool, default True) -- Call .metpy.dequantify() to strip Pint units and move them to attrs["units"]. Set to False if the array is already plain.

  • axis0_domain ({"time", "frequency"}, default "time") -- Physical domain of axis0.

戻り値の型:

ScalarField

メモ

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

Convert a wrf.getvar() xarray.DataArray to a ScalarField.

WRF dimension names are mapped to GWexpy axes:

  • Time / time → axis0

  • west_east → axis1 (x)

  • south_north → axis2 (y)

  • bottom_top → axis3 (z)

2-D XLAT / XLONG coordinates are collapsed to 1-D when the grid is regular.

パラメータ:
  • cls (type) -- ScalarField class.

  • da (xarray.DataArray) -- Output of wrf.getvar().

  • vertical_dim (str, optional) -- Override the vertical dimension name. Auto-detected from bottom_top / bottom_top_stag when None.

  • axis0_domain ({"time", "frequency"}, default "time") -- Physical domain of axis0.

戻り値の型:

ScalarField

gwexpy.interop.from_harmonica_grid(cls: type, ds: Any, *, data_name: str | None = None) ScalarField | VectorField

Convert a Harmonica xarray grid to a ScalarField or VectorField.

Harmonica grids typically have dimensions easting/northing (for projected coordinates) or longitude/latitude (for geographic coordinates), with an optional upward dimension for height.

パラメータ:
  • cls (type) -- ScalarField or VectorField.

  • ds (xarray.DataArray or xarray.Dataset) -- Harmonica grid data. A Dataset is treated as a VectorField unless 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 a Dataset, all variables become VectorField components.

戻り値:

  • 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

Create a GWexpy TimeSeries from a LAL TimeSeries struct.

パラメータ:
  • cls (type) -- The TimeSeries class to instantiate.

  • lalts (lal.REAL4TimeSeries or lal.REAL8TimeSeries or lal.COMPLEX8TimeSeries or lal.COMPLEX16TimeSeries) -- LAL time series struct.

  • copy (bool, default True) -- Whether to copy the underlying data array.

戻り値:

GWexpy TimeSeries with epoch, sample rate and unit from the LAL struct.

戻り値の型:

TimeSeries

サンプル

>>> 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

Convert a GWexpy TimeSeries to a LAL TimeSeries struct.

パラメータ:
  • ts (TimeSeries) -- GWexpy TimeSeries to convert.

  • dtype (str, optional) -- LAL type string (e.g., "REAL8", "COMPLEX16"). If None, inferred from the array dtype.

戻り値:

LAL time series struct.

戻り値の型:

lal.REAL8TimeSeries or similar

サンプル

>>> 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

Create a GWexpy FrequencySeries from a LAL FrequencySeries struct.

パラメータ:
  • cls (type) -- The FrequencySeries class to instantiate.

  • lalfs (lal.REAL8FrequencySeries or lal.COMPLEX16FrequencySeries) -- LAL frequency series struct.

  • copy (bool, default True) -- Whether to copy the underlying data array.

戻り値:

GWexpy FrequencySeries with f0, df, epoch and unit from the LAL struct.

戻り値の型:

FrequencySeries

gwexpy.interop.to_lal_frequencyseries(fs: FrequencySeries) Any

Convert a GWexpy FrequencySeries to a LAL FrequencySeries struct.

パラメータ:

fs (FrequencySeries) -- GWexpy FrequencySeries to convert.

戻り値:

LAL frequency series struct.

戻り値の型:

lal.REAL8FrequencySeries or similar

gwexpy.interop.from_pycbc_timeseries(cls: type, pycbc_ts: Any, *, copy: bool = True) Any

Create a GWexpy TimeSeries from a PyCBC TimeSeries.

パラメータ:
  • cls (type) -- The TimeSeries class to instantiate.

  • pycbc_ts (pycbc.types.TimeSeries) -- PyCBC time series object.

  • copy (bool, default True) -- Whether to copy the underlying data array.

戻り値:

GWexpy TimeSeries with epoch, sample rate and unit from PyCBC.

戻り値の型:

TimeSeries

サンプル

>>> 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

Convert a GWexpy TimeSeries to a PyCBC TimeSeries.

パラメータ:

ts (TimeSeries) -- GWexpy TimeSeries to convert.

戻り値:

PyCBC time series.

戻り値の型:

pycbc.types.TimeSeries

サンプル

>>> 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

Create a GWexpy FrequencySeries from a PyCBC FrequencySeries.

パラメータ:
  • cls (type) -- The FrequencySeries class to instantiate.

  • pycbc_fs (pycbc.types.FrequencySeries) -- PyCBC frequency series object.

  • copy (bool, default True) -- Whether to copy the underlying data array.

戻り値:

GWexpy FrequencySeries with df, epoch and unit from PyCBC.

戻り値の型:

FrequencySeries

サンプル

>>> 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

Convert a GWexpy FrequencySeries to a PyCBC FrequencySeries.

パラメータ:

fs (FrequencySeries) -- GWexpy FrequencySeries to convert.

戻り値:

PyCBC frequency series.

戻り値の型:

pycbc.types.FrequencySeries

サンプル

>>> 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)

ベースクラス: object

Simple 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)

Build a TimeSeriesWindowDataset from the provided object.

gwexpy.interop.to_torch_dataloader(dataset, *, batch_size: int = 1, shuffle: bool = False, num_workers: int = 0, **kwargs)

Create a torch DataLoader from the provided dataset.

gwexpy.interop.from_sdynpy_shape(shape_array: Any) Any

Convert an SDynPy ShapeArray to a pandas.DataFrame.

パラメータ:

shape_array (sdynpy.core.sdynpy_shape.ShapeArray) -- SDynPy shape array. Must expose .frequency, .damping, .shape_matrix, and .coordinate attributes.

戻り値:

Columns include DOF labels, optional node coordinates, and mode_1 ... mode_N columns. frequency_Hz and damping_ratio are stored in df.attrs.

戻り値の型:

pandas.DataFrame

gwexpy.interop.from_sdynpy_frf(cls: type, tfa: Any, *, response_type: str | None = None) Any

Convert an SDynPy TransferFunctionArray to a FrequencySeriesMatrix.

パラメータ:
  • cls (type) -- FrequencySeriesMatrix.

  • tfa (sdynpy.core.sdynpy_data.TransferFunctionArray) -- SDynPy transfer function array.

  • response_type (str, optional) -- Response type for unit inference (e.g. "accel").

戻り値の型:

FrequencySeriesMatrix

gwexpy.interop.from_sdynpy_timehistory(cls: type, tha: Any, *, response_type: str | None = None) Any

Convert an SDynPy TimeHistoryArray to a TimeSeriesMatrix.

パラメータ:
  • cls (type) -- TimeSeriesMatrix or TimeSeriesDict.

  • tha (sdynpy.core.sdynpy_data.TimeHistoryArray) -- SDynPy time-history array.

  • response_type (str, optional) -- Response type for unit inference.

戻り値の型:

TimeSeriesMatrix or TimeSeriesDict

gwexpy.interop.from_uff_dataset58(cls: type, uff_data: dict, *, response_type: str | None = None) Any

Convert a pyuff dataset-58 dict to TimeSeries or FrequencySeries.

パラメータ:
  • cls (type) -- TimeSeries or FrequencySeries. 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").

戻り値の型:

TimeSeries or FrequencySeries

gwexpy.interop.from_uff_dataset55(uff_data: dict) Any

Convert a pyuff dataset-55 dict to a pandas.DataFrame.

Dataset type 55 contains modal model data: natural frequencies, modal damping, and mode shapes.

パラメータ:

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.

戻り値の型:

pandas.DataFrame

gwexpy.interop.from_pyoma_results(cls: type, results: dict, *, fs: float | None = None) Any

Convert pyOMA result dict to a GWexpy type.

パラメータ:
  • cls (type) -- Target type. Use pandas.DataFrame (or pass the string "DataFrame") for modal parameter summary, or FrequencySeriesMatrix for 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.

戻り値の型:

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

Read an OpenSeesPy recorder text file into a TimeSeriesMatrix.

パラメータ:
  • cls (type) -- TimeSeriesMatrix or TimeSeriesDict.

  • filepath (str or Path) -- Path to the recorder output file (space-delimited text).

  • nodes (list[int]) -- Node numbers recorded (in order).

  • 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).

戻り値の型:

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

Convert Exudyn sensor data to TimeSeries or TimeSeriesMatrix.

パラメータ:
  • cls (type) -- TimeSeries or TimeSeriesMatrix.

  • 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.

戻り値の型:

TimeSeries or TimeSeriesMatrix

gwexpy.interop.from_mtspec(cls: type, mt: Any, *, quantity: Literal['psd', 'asd'] = 'psd', include_ci: bool = True) Any

Convert a Prieto MTSpec / MTSine object to a GWexpy type.

パラメータ:
  • cls (type) -- Target type. Pass FrequencySeries to always receive a plain spectrum (CI is discarded even when available). Pass FrequencySeriesDict to 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 PSD

    • spec_ci : ndarray (nf, 2) — 95 % jackknife CI [lower, upper] (optional; not present on MTSine)

    • se : ndarray (nf,) — degrees of freedom per bin (optional)

  • quantity ({"psd", "asd"}, default "psd") -- Whether to return power or amplitude spectral density. "asd" applies np.sqrt to the PSD.

  • include_ci (bool, default True) -- If True and the object carries spec_ci, return a FrequencySeriesDict with keys "psd"/"asd", "ci_lower", and "ci_upper". Ignored when the CI attribute is absent.

戻り値:

  • FrequencySeries -- When CI is unavailable or include_ci=False.

  • FrequencySeriesDict -- When CI is available and include_ci=True.

例外:

ValueError -- If quantity is 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

Convert Krischer mtspec function output to a GWexpy type.

パラメータ:
  • cls (type) -- Target type. Pass FrequencySeries to always receive a plain spectrum (CI is discarded even when available). Pass FrequencySeriesDict to receive a dict that includes CI series when CI is available.

  • spectrum (array-like, shape (nf,)) -- PSD (or ASD, depending on quantity) array returned by mtspec.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.

戻り値:

  • FrequencySeries -- When ci_lower and ci_upper are both None.

  • FrequencySeriesDict -- When either CI array is provided. Keys: "psd"/"asd", "ci_lower", "ci_upper".

例外:

ValueError -- If quantity is not "psd" or "asd", if freq is not equally spaced, or if shapes are inconsistent.

Standard Formats#

hdf5_

frequency

json_

sqlite_

SQLite interop helpers.

zarr_

netcdf4_

Object-level NetCDF4 bridge helpers.

Data Analysis Libraries#

pandas_

polars_

Polars interop helpers.

xarray_

astropy_

dask_

Array and Tensor Libraries#

torch_

Interoperability with PyTorch tensors.

torch_dataset

tensorflow_

TensorFlow interop helpers.

jax_

JAX interop helpers.

cupy_

CuPy interop helpers.

Domain Specific Libraries#

finesse_

Interoperate with the Finesse 3 interferometer simulation library.

control_

Provide interoperability with the python-control library.

simpeg_

SimPEG interop helpers.

mt_

Interoperate with the MTH5 magnetotelluric HDF5 format.

mne_

neo_

Neo interop helpers.

quantities_

quantities interop helpers.

pyroomacoustics_

Interoperate with pyroomacoustics simulation results.

pydub_

Audio interop helpers for pydub and librosa-oriented exports.

specutils_

Interoperability with specutils.

pyspeckit_

Interoperability with pyspeckit.

pyspice_

Interoperate with PySpice circuit simulation results.

skrf_

Interoperability with scikit-rf for RF and microwave network analysis.

pyoma_

Interoperate with pyOMA operational modal analysis results.

multitaper_

Interoperate with multitaper spectral estimation packages.

sdypy_

Interoperability with SDyPy and pyuff (Universal File Format).

sdynpy_

Interoperability with SDynPy (Structural Dynamics in Python).

meep_

Interoperate with Meep FDTD simulation output files.

openems_

Interoperate with openEMS field dump HDF5 files.

emg3d_

Interoperate with emg3d electromagnetic modelling fields.

meshio_

Interoperate with meshio unstructured-mesh field data.

metpy_

Interoperate with MetPy xarray data arrays.

wrf_

Interoperability with wrf.getvar() output from wrf-python.

harmonica_

Interoperate with Harmonica gravity and magnetic grids.

exudyn_

Interoperate with Exudyn sensor output.

opensees_

Interoperate with OpenSeesPy recorder output.

obspy_

lal_

Interoperate with LALSuite time and frequency series.

gwinc_

Interoperate with pygwinc noise budgets.

pycbc_

Interoperate with PyCBC time and frequency series.

root_