#!/usr/bin/env python
# coding: utf-8

"""
Sensor-level RSA using a searchlight
====================================

This example demonstrates how to perform representational similarity analysis
(RSA) on EEG data, using a searchlight approach.

In the searchlight approach, representational similarity is computed between
the model and searchlight "patches". A patch is defined by a seed point (e.g.
sensor Pz) and everything within the given radius (e.g. all sensors within 4
cm. of Pz). Patches are created for all possible seed points (e.g. all
sensors), so you can think of it as a "searchlight" that moves from seed
point to seed point and everything that is in the spotlight is used in the
computation.

The radius of a searchlight can be defined in space, in time, or both. In
this example, our searchlight will have a spatial radius of 4.5 cm. and a
temporal radius of 50 ms.

The dataset will be the kiloword dataset [1]_: approximately 1,000 words were
presented to 75 participants in a go/no-go lexical decision task while
event-related potentials (ERPs) were recorded.

.. [1] Dufau, S., Grainger, J., Midgley, KJ., Holcomb, PJ (2015). A thousand
       words are worth a picture: Snapshots of printed-word processing in an
       event-related potential megastudy. Psychological science.
"""
# sphinx_gallery_thumbnail_number=2

# Import required packages
import mne
import mne_rsa

###############################################################################
# MNE-Python contains a build-in data loader for the kiloword dataset. We use
# it here to read it as 960 epochs. Each epoch represents the brain response to
# a single word, averaged across all the participants. For this example, we
# speed up the computation, at a cost of temporal precision, by downsampling
# the data from the original 250 Hz. to 100 Hz.

data_path = mne.datasets.kiloword.data_path(verbose=True)
epochs = mne.read_epochs(data_path / 'kword_metadata-epo.fif')
epochs = epochs.resample(100)

# Drop some
epochs.drop([0, 10, 20, 100], reason='BAD')

dsms = mne_rsa.dsm_epochs(
    epochs,
    spatial_radius=None,
    temporal_radius=0.05,
    dropped_as_nan=True,
)

dsm = next(dsms)


###############################################################################
# The kiloword datas was erroneously stored with sensor locations given in
# centimeters instead of meters. We will fix it now. For your own data, the
# sensor locations are likely properly stored in meters, so you can skip this
# step.
for ch in epochs.info['chs']:
    ch['loc'] /= 100
