Skip to content

Spectral utils

Utility functions for spectral analysis. Defaults are chosen to replicate MATLAB's default behavior.

csd

csd(x, y, fs, num_windows=8, window_type='hamming', window_len=None, nfft=None, detrend=False, onesided=True)

Cross spectral density via Welch's method.

Parameters:

Name Type Description Default
x ndarray

Two input signals of identical shape; the longest axis is time.

required
y ndarray

Two input signals of identical shape; the longest axis is time.

required
fs float

Sampling frequency (Hz).

required
num_windows int

Number of (50%-overlapping) Welch windows when window_len is not given.

8
window_type str

Window passed to scipy.signal.csd.

'hamming'
window_len int

Window length in samples. If None, derived from num_windows and N.

None
nfft int

FFT length. Defaults to window_len.

None
detrend bool

If True, detrend each segment before transforming.

False
onesided bool

If True, return the one-sided spectrum.

True

Returns:

Name Type Description
f ndarray

Frequency vector (Hz).

Pxy ndarray

Complex cross spectral density (units of x*y / Hz).

Source code in src/pytoast/utils/spectral_utils.py
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
def csd(
    x: np.ndarray,
    y: np.ndarray,
    fs: float,
    num_windows: int = 8,
    window_type: str = "hamming",
    window_len: int | None = None,
    nfft: int | None = None,
    detrend: bool = False,
    onesided: bool = True,
) -> tuple[np.ndarray, np.ndarray]:
    """
    Cross spectral density via Welch's method.

    Parameters
    ----------
    x, y : np.ndarray
        Two input signals of identical shape; the longest axis is time.
    fs : float
        Sampling frequency (Hz).
    num_windows : int, optional
        Number of (50%-overlapping) Welch windows when ``window_len`` is not given.
    window_type : str, optional
        Window passed to ``scipy.signal.csd``.
    window_len : int, optional
        Window length in samples. If None, derived from ``num_windows`` and ``N``.
    nfft : int, optional
        FFT length. Defaults to ``window_len``.
    detrend : bool, optional
        If True, detrend each segment before transforming.
    onesided : bool, optional
        If True, return the one-sided spectrum.

    Returns
    -------
    f : np.ndarray
        Frequency vector (Hz).
    Pxy : np.ndarray
        Complex cross spectral density (units of x*y / Hz).
    """
    N = max(x.shape)
    if window_len is None:
        window_len = get_window_len(N, num_windows)
    if nfft is None:
        nfft = window_len

    f, Pxy = sig.csd(
        x=x,
        y=y,
        fs=fs,
        window=window_type,
        nperseg=window_len,
        nfft=nfft,
        detrend=detrend,
        return_onesided=onesided,
    )

    return f, Pxy

get_frequency_range

get_frequency_range(f, f_low=None, f_high=None)

Index range into f covering [f_low, f_high].

Parameters:

Name Type Description Default
f ndarray

Monotonically increasing frequency vector (Hz).

required
f_low float

Lower frequency bound (Hz). If None, start at index 0.

None
f_high float

Upper frequency bound (Hz). If None, end at len(f).

None

Returns:

Type Description
tuple of int

(start_index, end_index) into f.

Source code in src/pytoast/utils/spectral_utils.py
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
def get_frequency_range(f: np.ndarray, f_low: float | None = None, f_high: float | None = None) -> tuple[int, int]:
    """
    Index range into ``f`` covering [f_low, f_high].

    Parameters
    ----------
    f : np.ndarray
        Monotonically increasing frequency vector (Hz).
    f_low : float, optional
        Lower frequency bound (Hz). If None, start at index 0.
    f_high : float, optional
        Upper frequency bound (Hz). If None, end at ``len(f)``.

    Returns
    -------
    tuple of int
        ``(start_index, end_index)`` into ``f``.
    """
    if f_low is not None:
        start_index = int(np.argmin(np.abs(f - f_low)))
    else:
        start_index = 0

    if f_high is not None:
        end_index = int(np.argmin(np.abs(f - f_high)))
    else:
        end_index = len(f)

    return start_index, end_index

get_window_len

get_window_len(N, num_windows)

Welch-method window length.

Parameters:

Name Type Description Default
N int

Number of samples in the time series.

required
num_windows int

Number of (50%-overlapping) windows desired.

required

Returns:

Type Description
int

Window length in samples.

Source code in src/pytoast/utils/spectral_utils.py
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
def get_window_len(N: int, num_windows: int) -> int:
    """
    Welch-method window length.

    Parameters
    ----------
    N : int
        Number of samples in the time series.
    num_windows : int
        Number of (50%-overlapping) windows desired.

    Returns
    -------
    int
        Window length in samples.
    """
    return int(2 * N / (num_windows + 1))

plot_spectral_fit

plot_spectral_fit(x, y, x_fit, y_fit, eps, xlabel='Wavenumber $k$ (rad/m)', ylabel='Spectral density', title=None, out_file=None)

Save a log-log plot of a spectral curve fit to a PNG file.

Draws the observed spectrum as scattered points together with the fitted -5/3 curve. The caller supplies the data points and the pre-computed fit line, so this function is agnostic to the specific model or independent variable (wavenumber or angular frequency).

Parameters:

Name Type Description Default
x ndarray

Independent variable of the observed data points over the fit range (e.g. wavenumber in rad/m or angular frequency in rad/s).

required
y ndarray

Observed spectral density at x.

required
x_fit ndarray

Independent variable of the fitted curve (e.g. a linspace over the fit range).

required
y_fit ndarray

Fitted spectral density evaluated at x_fit.

required
eps float

Dissipation rate estimate (m^2/s^3), shown in the legend label.

required
xlabel str

Label for the x-axis. Defaults to a wavenumber label.

'Wavenumber $k$ (rad/m)'
ylabel str

Label for the y-axis. Defaults to a generic spectral density label.

'Spectral density'
title str

Axis title. If None, no title is drawn.

None
out_file str

Destination PNG path. If None, a temporary file (suffix ".png") is created.

None

Returns:

Type Description
str

Path to the saved PNG file.

Source code in src/pytoast/utils/spectral_utils.py
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
def plot_spectral_fit(
    x: np.ndarray,
    y: np.ndarray,
    x_fit: np.ndarray,
    y_fit: np.ndarray,
    eps: float,
    xlabel: str = r"Wavenumber $k$ (rad/m)",
    ylabel: str = r"Spectral density",
    title: str | None = None,
    out_file: str | None = None,
) -> str:
    """
    Save a log-log plot of a spectral curve fit to a PNG file.

    Draws the observed spectrum as scattered points together with the fitted -5/3 curve.
    The caller supplies the data points and the pre-computed fit line, so this function is
    agnostic to the specific model or independent variable (wavenumber or angular frequency).

    Parameters
    ----------
    x : np.ndarray
        Independent variable of the observed data points over the fit range (e.g. wavenumber
        in rad/m or angular frequency in rad/s).
    y : np.ndarray
        Observed spectral density at ``x``.
    x_fit : np.ndarray
        Independent variable of the fitted curve (e.g. a linspace over the fit range).
    y_fit : np.ndarray
        Fitted spectral density evaluated at ``x_fit``.
    eps : float
        Dissipation rate estimate (m^2/s^3), shown in the legend label.
    xlabel : str, optional
        Label for the x-axis. Defaults to a wavenumber label.
    ylabel : str, optional
        Label for the y-axis. Defaults to a generic spectral density label.
    title : str, optional
        Axis title. If None, no title is drawn.
    out_file : str, optional
        Destination PNG path. If None, a temporary file (suffix ".png") is created.

    Returns
    -------
    str
        Path to the saved PNG file.
    """
    if out_file is None:
        out_file = tempfile.NamedTemporaryFile(suffix=".png", delete=False).name

    fig, ax = plt.subplots(figsize=(5, 4))
    ax.plot(x, y, "o", label="Data", alpha=0.5)
    ax.plot(x_fit, y_fit, linewidth=2, label=f"Fit (eps={eps:.3e})")
    ax.set_xlabel(xlabel)
    ax.set_ylabel(ylabel)
    ax.set_yscale("log")
    if title is not None:
        ax.set_title(title)
    ax.legend()
    ax.xaxis.set_major_formatter("{x:.1f}")
    ax.xaxis.set_minor_formatter("{x:.1f}")
    fig.tight_layout(pad=0.5)
    fig.savefig(out_file, dpi=300)
    plt.close(fig)

    return out_file

psd

psd(x, fs, num_windows=8, window_type='hamming', window_len=None, nfft=None, detrend=False, onesided=True)

Power spectral density via Welch's method.

Parameters:

Name Type Description Default
x ndarray

Input signal. The longest axis is treated as time.

required
fs float

Sampling frequency (Hz).

required
num_windows int

Number of (50%-overlapping) Welch windows when window_len is not given.

8
window_type str

Window passed to scipy.signal.welch (default 'hamming').

'hamming'
window_len int

Window length in samples. If None, derived from num_windows and N.

None
nfft int

FFT length. Defaults to window_len.

None
detrend bool

If True, detrend each segment before transforming.

False
onesided bool

If True, return the one-sided spectrum.

True

Returns:

Name Type Description
f ndarray

Frequency vector (Hz).

Pxx ndarray

Power spectral density (units of x^2 / Hz).

Source code in src/pytoast/utils/spectral_utils.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
def psd(
    x: np.ndarray,
    fs: float,
    num_windows: int = 8,
    window_type: str = "hamming",
    window_len: int | None = None,
    nfft: int | None = None,
    detrend: bool = False,
    onesided: bool = True,
) -> tuple[np.ndarray, np.ndarray]:
    """
    Power spectral density via Welch's method.

    Parameters
    ----------
    x : np.ndarray
        Input signal. The longest axis is treated as time.
    fs : float
        Sampling frequency (Hz).
    num_windows : int, optional
        Number of (50%-overlapping) Welch windows when ``window_len`` is not given.
    window_type : str, optional
        Window passed to ``scipy.signal.welch`` (default ``'hamming'``).
    window_len : int, optional
        Window length in samples. If None, derived from ``num_windows`` and ``N``.
    nfft : int, optional
        FFT length. Defaults to ``window_len``.
    detrend : bool, optional
        If True, detrend each segment before transforming.
    onesided : bool, optional
        If True, return the one-sided spectrum.

    Returns
    -------
    f : np.ndarray
        Frequency vector (Hz).
    Pxx : np.ndarray
        Power spectral density (units of ``x``^2 / Hz).
    """
    N = max(x.shape)
    if window_len is None:
        window_len = get_window_len(N, num_windows)
    if nfft is None:
        nfft = window_len

    f, Pxx = sig.welch(
        x=x,
        fs=fs,
        window=window_type,
        nperseg=window_len,
        nfft=nfft,
        detrend=detrend,
        return_onesided=onesided,
    )

    return f, Pxx