OHBA-analysis / osl-dynamics

Methods for studying dynamic functional brain activity in neuroimaging data.
https://osl-dynamics.readthedocs.io/
Other
61 stars 18 forks source link

Spectrogram calculation error when a state doesn't activate (`analysis/spectral.py`) #216

Closed scho97 closed 9 months ago

scho97 commented 9 months ago

When calculating a multitaper spectrogram, the following error can arise:

RuntimeWarning: invalid value encountered in divide  psd_ /= fo_

which occurred in spectral.py (L1727-L1728). This affects subsequent analysis and plotting.

Here, the resulting psd_ value is an array of np.nan, and this turns out to be because fo_ = 0 and psd_ is an array of zeroes. This was a very specific case, occurring for a single subject within a model single run (so far). In such case, it seems like one state did not activate over entire time points.

=> print(psd_ / fo_)
[[nan nan nan ... nan nan nan]
 [nan nan nan ... nan nan nan]
 [nan nan nan ... nan nan nan]
 ...
 [nan nan nan ... nan nan nan]
 [nan nan nan ... nan nan nan]
 [nan nan nan ... nan nan nan]]
=> print(fo_)
0.0
=> print(psd_)
[[0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 ...
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]
 [0. 0. 0. ... 0. 0. 0.]]

For this, I wasn't sure if we should consider this as a poor model fit (and therefore train the model again) or we should fix it with something like

psd_ = np.nan_to_num(psd_)

as we did for the coherence in spectral.py (L855-L856).

cgohil8 commented 9 months ago

I left this in because having no state activation probably indicates the HMM fit didn't go so well. Getting an error makes this ver obvious, otherwise the user might think everything's fine.

I guess would eventually realise the HMM fit's off based on the spectra being full of zeros.

Maybe we should add nan_to_num for the PSDs. @RukuangHuang what do you think?

RukuangHuang commented 9 months ago

nan_to_num will be good. But I think we should add a warning that warns the user of potential poor HMM fit. And maybe suggest solutions like training multiple times and get the lowert FE run.

scho97 commented 9 months ago

Okay, I can make a pull request with nan_to_num and a detailed warning message, and perhaps both of you can review it?