fitting
- gwexpy.fitting.fit_bootstrap_spectrum(data_or_spectrogram: TimeSeries | Spectrogram, model_fn: Callable, freq_range: tuple[float, float] | None = None, method: str = 'median', rebin_width: float | None = None, block_size: float | str | None = None, ci: float = 0.68, window: str = 'hann', fftlength=None, overlap=None, nfft: int | None = None, noverlap: int | None = None, n_boot: int = 1000, initial_params: dict[str, float] | None = None, bounds: dict[str, tuple[float, float]] | None = None, fixed: list | None = None, run_mcmc: bool = False, mcmc_walkers: int = 32, mcmc_steps: int = 5000, mcmc_burn_in: int = 500, plot: bool = True, progress: bool = True, **kwargs) FitResult[source]
Integrated spectral analysis pipeline with bootstrap, GLS fitting, and MCMC.
This function provides a unified workflow for: 1. Converting TimeSeries to Spectrogram (if needed) 2. Bootstrap resampling to estimate PSD and covariance 3. GLS fitting with proper frequency correlation 4. Optional MCMC for Bayesian parameter inference 5. Visualization of results
- Parameters:
data_or_spectrogram (TimeSeries or Spectrogram) – Input data. If TimeSeries, a spectrogram will be computed automatically.
model_fn (callable) – Model function with signature model(f, *params) -> y. First argument must be frequency array. Example: lambda f, A, alpha: A * f**alpha
freq_range (tuple of (fmin, fmax), optional) – Frequency range for fitting. If None, use all frequencies.
method (str, optional) – Bootstrap averaging method: ‘median’ (default) or ‘mean’.
rebin_width (float, optional) – Frequency rebinning width in Hz. If None, no rebinning.
block_size (float, Quantity, or 'auto', optional) – Duration of blocks for block bootstrap in seconds. Can be specified as float (seconds), Quantity with time units, or ‘auto’. If None, standard bootstrap.
ci (float, optional) – Confidence interval for bootstrap errors. Default is 0.68 (1-sigma).
window (str, optional) – Window function for spectrogram and correlation correction. Default is ‘hann’.
fftlength (float or Quantity, optional) – FFT segment length in seconds (e.g.
1.0or1.0 * u.s). Used to generate the spectrogram from a TimeSeries and for VIF overlap-correlation correction. If None and a TimeSeries is given, GWpy chooses a default covering the full duration.overlap (float or Quantity, optional) – Overlap between FFT segments in seconds. If None, defaults to the recommended overlap for window (50 % for Hann). Cannot be used with noverlap.
nfft (int, optional) – FFT segment length in samples. Alternative to fftlength. Cannot be used with fftlength.
noverlap (int, optional) – Overlap length in samples. Must be used with nfft. Cannot be used with overlap.
n_boot (int, optional) – Number of bootstrap resamples. Default is 1000.
initial_params (dict, optional) – Initial parameter values for fitting, e.g., {“A”: 10, “alpha”: -1.5}.
bounds (dict, optional) – Parameter bounds, e.g., {“A”: (0, 100), “alpha”: (-5, 0)}.
fixed (list, optional) – List of parameter names to fix during fitting.
run_mcmc (bool, optional) – Whether to run MCMC after fitting. Default is False.
mcmc_walkers (int, optional) – Number of MCMC walkers. Default is 32.
mcmc_steps (int, optional) – Number of MCMC steps. Default is 5000.
mcmc_burn_in (int, optional) – MCMC burn-in steps to discard. Default is 500.
plot (bool, optional) – Whether to display plots. Default is True.
progress (bool, optional) – Whether to show progress bars for MCMC. Default is True.
- Returns:
Fit result object containing: - Best-fit parameters and errors - Chi-square and reduced chi-square - Covariance matrix (in cov_inv and accessible cov attribute) - MCMC samples and intervals (if run_mcmc=True) - Plotting methods
- Return type:
FitResult
Examples
>>> from gwexpy.fitting.highlevel import fit_bootstrap_spectrum >>> >>> # Define model >>> def power_law(f, A, alpha): ... return A * f**alpha >>> >>> # Run pipeline >>> result = fit_bootstrap_spectrum( ... data, ... model_fn=power_law, ... freq_range=(5, 50), ... fftlength=1.0, ... overlap=0.5, ... rebin_width=0.25, ... block_size=2.0, # 2 seconds ... initial_params={"A": 10, "alpha": -1.5}, ... run_mcmc=True, ... ) >>> >>> # Access results >>> print(result.params) >>> print(result.parameter_intervals) # If MCMC was run
Notes
The covariance matrix from bootstrap is stored and used for GLS fitting, properly accounting for frequency correlations in the spectral estimate.
See also
gwexpy.spectral.bootstrap_spectrogramBootstrap resampling function
gwexpy.fitting.fit_seriesLower-level fitting function
gwexpy.fitting.GeneralizedLeastSquaresGLS cost function
- gwexpy.fitting.enable_series_fit() None[source]
Opt-in monkeypatch for gwpy.types.Series.fit.
Note: standard gwexpy classes (TimeSeries, FrequencySeries) already have the .fit() method via inheritance. This function is generally not needed unless you are using base gwpy objects directly.
- gwexpy.fitting.enable_fitting_monkeypatch() None
Opt-in monkeypatch for gwpy.types.Series.fit.
Note: standard gwexpy classes (TimeSeries, FrequencySeries) already have the .fit() method via inheritance. This function is generally not needed unless you are using base gwpy objects directly.
interop
- 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.
- Parameters:
index (str, default "datetime") – “datetime” (UTC aware), “seconds” (unix), or “gps”.
copy (bool) – Whether to copy data.
- Return type:
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 TimeSeries from pandas.Series.
- gwexpy.interop.to_pandas_dataframe(tsd: TimeSeriesDict, index: Literal['datetime', 'seconds', 'gps'] = 'datetime', copy: bool = False) pd.DataFrame[source]
TimeSeriesDict -> 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]
DataFrame -> TimeSeriesDict
- gwexpy.interop.to_xarray(ts: TimeSeries, time_coord: Literal['datetime', 'seconds', 'gps'] = 'datetime') xr.DataArray[source]
TimeSeries -> xarray.DataArray
- gwexpy.interop.from_xarray(cls: Type[T], da: xr.DataArray, unit: str | None = None) T[source]
DataArray -> 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 Obspy object to 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.
- 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.
- 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]
TimeSeriesDict -> polars.DataFrame
- gwexpy.interop.from_polars_dict(cls, df, index_column='time', unit_map=None)[source]
polars.DataFrame -> TimeSeriesDict
- gwexpy.interop.to_tgraph(series: Any, error: Any | None = None) ROOT.TGraph[source]
Convert 1D Series to ROOT TGraph or TGraphErrors.
- gwexpy.interop.to_th1d(series: Any, error: Any | None = None) ROOT.TH1D[source]
Convert 1D Series to ROOT TH1D.
- gwexpy.interop.to_th2d(spec: Spectrogram, error: Any | None = None) ROOT.TH2D[source]
Convert Spectrogram to 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 Series (TimeSeries or FrequencySeries) from ROOT TGraph or TH1.
- 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]
- gwexpy.interop.from_sqlite(cls, conn, series_id)[source]
- gwexpy.interop.require_optional(name: str) Any[source]
Import an optional dependency or raise an informative ImportError.
- Parameters:
name (str) – Key name of the dependency (e.g., ‘pandas’).
- Returns:
The imported module.
- Return type:
module
- Raises:
ImportError – If the package is not installed.
- gwexpy.interop.to_pandas_frequencyseries(fs: FrequencySeries, index: Literal['frequency'] = 'frequency', name: str | None = None, copy: bool = False) pd.Series[source]
- 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]
- gwexpy.interop.to_xarray_frequencyseries(fs: FrequencySeries, freq_coord: Literal['Hz'] = 'Hz') xr.DataArray[source]
- 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]
- 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]
- gwexpy.interop.from_hdf5_frequencyseries(cls: Type[T], group: h5py.Group, path: str) T[source]
- 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.
- Parameters:
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.
- Returns:
The created time series.
- Return type:
TimeSeries
- gwexpy.interop.to_tf(ts, dtype=None)[source]
Convert TimeSeries to tensorflow.Tensor.
- gwexpy.interop.from_tf(cls, tensor, t0, dt, unit=None)[source]
Create TimeSeries from tensorflow.Tensor.
- gwexpy.interop.to_dask(ts, chunks='auto')[source]
Convert TimeSeries to dask.array.Array.
- gwexpy.interop.from_dask(cls, array, t0, dt, unit=None, compute=True)[source]
Create TimeSeries from dask array.
- Parameters:
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 Zarr array.
- gwexpy.interop.from_zarr(cls: Type[T], store: Any, path: str) T[source]
Read from 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 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:
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).
- 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:
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).
- 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 FrequencySeries or FrequencySeriesMatrix from a Finesse 3
FrequencyResponseSolution.- 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 FrequencySeries or FrequencySeriesDict from a Finesse 3
NoiseProjectionSolution.- 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 FrequencySeries, FrequencySeriesDict, or FrequencySeriesMatrix 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]
- gwexpy.interop.from_jax(cls, array, t0, dt, unit=None)[source]
- gwexpy.interop.to_cupy(obj, dtype=None)[source]
- gwexpy.interop.from_cupy(cls, array, t0, dt, unit=None)[source]
- gwexpy.interop.is_cupy_available()[source]
Check if cupy is installed and functionally usable (CUDA environment is working).
- 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 pydub.AudioSegment.
- gwexpy.interop.from_pydub(cls, seg, unit=None)[source]
Create TimeSeries from AudioSegment.
- gwexpy.interop.to_astropy_timeseries(ts, column='value', time_format='gps')[source]
ts: TimeSeries
- gwexpy.interop.from_astropy_timeseries(cls, ap_ts, column='value', unit=None)[source]
ap_ts: 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]
raw: 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’.
- 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.
- Return type:
Object of type cls.
- gwexpy.interop.to_neo(obj, units=None)[source]
Convert TimeSeries or TimeSeriesMatrix to neo.AnalogSignal.
- gwexpy.interop.from_neo(cls, sig)[source]
Create 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 TimeSeries from a JSON string.
- gwexpy.interop.to_dict(ts)[source]
Convert TimeSeries to a dictionary.
- gwexpy.interop.from_dict(cls, data_dict)[source]
Create 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:
cls (type) –
ScalarFieldclass.da (xarray.DataArray) – Output of
wrf.getvar().vertical_dim (str, optional) – Override the vertical dimension name. Auto-detected from
bottom_top/bottom_top_stagwhenNone.axis0_domain ({"time", "frequency"}, default "time") – Physical domain of axis0.
- 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:
cls (type) – The
TimeSeriesclass 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.
- 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:
cls (type) – The
FrequencySeriesclass to instantiate.lalfs (lal.REAL8FrequencySeries or lal.COMPLEX16FrequencySeries) – LAL frequency series struct.
copy (bool, default True) – Whether to copy the underlying data array.
- 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:
cls (type) – The
TimeSeriesclass to instantiate.pycbc_ts (pycbc.types.TimeSeries) – PyCBC time series object.
copy (bool, default True) – Whether to copy the underlying data array.
- 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:
cls (type) – The
FrequencySeriesclass to instantiate.pycbc_fs (pycbc.types.FrequencySeries) – PyCBC frequency series object.
copy (bool, default True) – Whether to copy the underlying data array.
- 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]
Convenience wrapper to build a TimeSeriesWindowDataset.
- gwexpy.interop.to_torch_dataloader(dataset, *, batch_size: int = 1, shuffle: bool = False, num_workers: int = 0, **kwargs)[source]
Create a torch DataLoader from 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.- Parameters:
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").
- Return type:
FrequencySeriesMatrix
- gwexpy.interop.from_sdynpy_timehistory(cls: type, tha: Any, *, response_type: str | None = None) Any[source]
Convert an SDynPy
TimeHistoryArrayto aTimeSeriesMatrix.- Parameters:
cls (type) –
TimeSeriesMatrixorTimeSeriesDict.tha (sdynpy.core.sdynpy_data.TimeHistoryArray) – SDynPy time-history array.
response_type (str, optional) – Response type for unit inference.
- Return type:
TimeSeriesMatrix or TimeSeriesDict
- 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).
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).
- 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.