question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Correction for reduced energy when windowing

See original GitHub issue

Applying window weighting (e.g. Hann) to a signal reduces its energy. I think it’s common to want to correct for this. For example, it appears that such a correction is applied by default in scipy.signal.welch:

import xrft
import numpy as np
import scipy.signal
import xarray as xr
import matplotlib.pyplot as plt 

x = xr.DataArray(np.random.normal(0, 1, size=10000), 
                 dims=['t'], 
                 coords=[range(0,10000)])
n_segment = 100

f_scipy, p_scipy = scipy.signal.welch(x.values,
                                      window='hann',
                                      nperseg=n_segment,
                                      noverlap=0,
                                      return_onesided=False)
                
p_xrft = xrft.xrft.power_spectrum(x.chunk({'t': n_segment}), 
                                  dim=['t'],
                                  detrend='constant',
                                  window=True,
                                  chunks_to_segments=True).mean('t_segment')

# Correction tends to 8/3 for infinitely long Hann window
p_xrft_corrected = (1 / np.mean(np.hanning(n_segment)**2))*p_xrft 

plt.plot(f_scipy, p_scipy, 
         label='scipy psd')
plt.plot(p_xrft.freq_t, p_xrft, 
         color='C2', label='xrft psd')
plt.plot(p_xrft.freq_t, p_xrft_corrected, 
         linestyle='--', color='C1', label='corrected xrft psd')
plt.ylim(0,1.6)
plt.xlabel('freq')
plt.ylabel('psd')
plt.legend()

delete-2

Is there an appetite (beyond my own) to have an option to apply such a correction when using window=True in xrft?

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:15 (15 by maintainers)

github_iconTop GitHub Comments

1reaction
roxyboycommented, Feb 7, 2021

If you pass window='windows[0]' to sps.welch() rather than window='hann', then you’ll get exactly the same values as our corrected results. Perhaps it would be a good idea for xrft to also use scipy.windows? This would make extending to other windows very easy.

I agree with this but we’ll keep it for another PR.

1reaction
roxyboycommented, Feb 6, 2021

Sorry, I forgot to mention that I changed the _apply_window function to also return the windows as below:

def _apply_window(da, dims, window_type="hanning"):
    """Creating windows in dimensions dims."""

    if window_type not in ["hanning"]:
        raise NotImplementedError("Only hanning window is supported for now.")

    numpy_win_func = getattr(np, window_type)

    if da.chunks:

        def dask_win_func(n):
            return dsar.from_delayed(delayed(numpy_win_func, pure=True)(n), (n,), float)

        win_func = dask_win_func
    else:
        win_func = numpy_win_func

    windows = [
        xr.DataArray(win_func(len(da[d])), dims=da[d].dims, coords=da[d].coords)
        for d in dims
    ]

    return windows, da * reduce(operator.mul, windows[::-1])
Read more comments on GitHub >

github_iconTop Results From Across the Web

Window Correction Factors - Siemens Communities
To correct for amplitude or energy distortion, each spectral line of a windowed frequency spectrum are multiplied by a fixed factor. This factor ......
Read more >
Crosstalk Reduction Using a Dual Energy Window ... - PubMed
In conventional single-photon emission computed tomography, a dual energy window (DEW) subtraction method is used to reduce crosstalk. This ...
Read more >
Crosstalk Reduction Using a Dual Energy Window Scatter ...
In conventional single-photon emission computed tomography, a dual energy window (DEW) subtraction method is used to reduce crosstalk.
Read more >
Window settings in Triple Energy Window scatter correction ...
Window settings in Triple Energy Window scatter correction. The main window is centered on the peak in the photon energy spectrum of the...
Read more >
The influence of triple energy window scatter ... - IOPscience
This technique uses upper and lower scatter energy windows, immediately adjacent to the photopeak window, to estimate the number of ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found