###############################################################################
# Rapid eye movement function
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~

###############################################################################
# This function does NOT perform a real REM detection. It illustrates how to
# replace the default detection behavior by a basic thresholding function.
# Note that the function returns a boolean array indicating samples that are
# above a specific threshold.

def fcn_rem(data, sf, time, hypno):  # noqa
    """New REM detection function."""
    mean_data = np.mean(data)
    std_data = np.std(data)
    # Threshold is mean + 3 * STD
    return data > mean_data + 3. * std_data

###############################################################################
# Replace existing methods
###############################################################################
# Now we use the :class:`visbrain.Sleep.replace_detections` method to overwrite
# existing spindles and REM detections.

# Replace the spindle detection function :
sp.replace_detections('spindle', fcn_spindle)
# Replace the REM detection function :
sp.replace_detections('rem', fcn_rem)

# Finally, open the graphical user interface :
sp.show()
# Define a DetectSlowWave instance :
opts_sw = DetectSlowWave('Massimini2004')
# Define the function to replace :
def fcn_slowwave(data, sf, time, hypno):  # noqa
    """New slowwave detection function.

    See : https://wonambi-python.github.io/api/wonambi.detect.slowwave.html
    for an exhaustive list of implemented detections inside wonambi.
    """
    out = detect_Massimini2004(data, sf, time, opts_sw)
    indices = np.zeros((len(out), 2))
    for i, k in enumerate(out):
        indices[i, 0] = k['start']
        indices[i, 1] = k['end']
    indices *= sf
    return indices.astype(int)

###############################################################################
# Replace existing methods
###############################################################################
# Now we use the :class:`visbrain.Sleep.replace_detections` method to overwrite
# existing spindles and slow-waves detections.

# Replace the spindle detection function :
sp.replace_detections('spindle', fcn_spindle)
# Replace the slow-wave detection function :
sp.replace_detections('sw', fcn_slowwave)

# Finally, open the graphical user interface :
sp.show()