The Software: EEG REM Detection Implementation (Code)

A project log for OpenLD: Lucid Dreaming Research Platform

An open source platform to help induce and explore the realm of Lucid Dreaming for Research and Personal Well-being

Jae ChoiJae Choi 09/25/2016 at 14:210 Comments

In the previous Project Log, I talked about the EEG REM Detection algorithm (Imtiaz et al.). In this log, I will talk about the implementation of the algorithm in C++. Note, for the OpenLD software, I will be using Qt C++, due to its extensive cross-platform support and ease of use.

Implementation of REM Detection

I will list the C++ code along with its corresponding formula, which are explained in depth in the previous Project Log.

SEFd (Spectral Edge Frequency difference)

SEF(x) where x in the Percentage of Edge Frequency:

#define FREQ_TO_BIN(x, N_FFT, Fs) int(x * N_FFT/Fs)
#define BIN_TO_FREQ(x, N_FFT, Fs) int(x * Fs/N_FFT)

double remDetect::SEFx(double *spectrum, int x, int f_Start, double sum_SEF)
    double sum_fft = 0;
    for (int i = FREQ_TO_BIN(f_Start, m_size_fft, m_Fs); sum_fft < ((double)x) / 100.0 * sum_SEF; i++) {
        sum_fft += spectrum[i] * spectrum[i] * ((double)m_Fs) / ((double)m_size_fft);
    return (((double)i) * ((double)m_Fs) / ((double)m_size_fft));

SEFd: the difference between SEF95 and SEF50

SEFd[epoch_Counter] = SEFx(spectrum, 95, f_Start, m_SEF_sum) - SEFx(spectrum, 50, f_Start, m_SEF_sum);

AP (Absolute Power) and RP (Relative Power)

Absolute Power

double remDetect::absPower(double *spectrum, int f_Start, int f_End)
    double sum_fft = 0;
    for (int i = FREQ_TO_BIN(f_Start, m_size_fft, m_Fs); i <= FREQ_TO_BIN(f_End, m_size_fft, m_Fs); i++) {
        sum_fft += spectrum[i] * ((double)m_Fs) / ((double)m_size_fft);
    return ((double) 20.0 * log10(sum_fft));

Relative Power

double remDetect::relPower(double *spectrum, int f_Start, int f_End)
    double ratio_spectrum = 0;
    ratio_spectrum = absPower(spectrum, f_Start, f_End) - absPower(spectrum, 1, f_Max);
    return ratio_spectrum;

Decision Tree for REM Detection

int remDetect::evaluate_REM_Epoch()
    // If the SEFd value is bigger than the specified minimum
    if (avg_SEFd > m_min_SEFd) {
        // If the averaged Absolute power is smaller than specified maximum
        if (avg_AP < m_max_AP) {
            // If the averaged Relative power is between the specified interval
            if (avg_RP > m_min_RP && avg_RP < m_max_RP) {
                // REM DETECTED :D
                return 1;
            } else return 0;
        } else return 0;
    } else return 0;


Imtiaz, Syed Anas, and Esther Rodriguez-Villegas. "A low computational cost algorithm for rem sleep detection using single channel EEG." Annals of biomedical engineering 42.11 (2014): 2344-2359.