#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Sat Jan 14 17:17:22 2017
    Bad channels and trials contaminated by artifacts including eye blinks, muscle activities and SQUID jumps were labeled with Fieldtrip.
   
@author: daisy
"""
#%% trial want to remove due to SQUID jump or muscle

#%% 

#set para
import os.path as op
import matplotlib.pyplot as plt
import numpy as np
import mne
from mne.preprocessing import ICA, create_eog_epochs,create_ecg_epochs
from mne import io
print(__doc__)

data_path = '/Users/daisy/Desktop/MEG_data/s38/run2_mooney_normal'
subject='lanmengying'
subjects_dir = '/Applications/freesurfer/subjects' 
data_name='/S19_heshengibp_20180125_02.ds'
con1='mooney'
con2='normal'
 
#Load raw data and save
raw_fname=data_path + data_name
raw = io.read_raw_ctf(raw_fname, preload=True)  
events = mne.find_events(raw, stim_channel='UPPT001',shortest_event=1)
events[:,0]=events[:,0]-raw.info['srfeq']*0.05 
event_id={con1:1,con2:2}
fname_raw=data_path+'/'+ subject + '-raw.fif'
raw.save(fname_raw,overwrite=True)

#filter
raw.filter(2, 80, method='iir')
raw.plot_psd(fmin=0.5,fmax=50)

#epoch
tmin, tmax = -0.25, 0.55
picks = mne.pick_types(raw.info, meg=True, exclude='bads',ref_meg=True)  
baseline = None  
reject = dict(mag=5e-12)
epochs = mne.Epochs(raw, events, event_id, tmin, tmax,  picks=picks,
                    baseline=baseline, preload=True, reject=reject)

# check epochs and remove Bad channels and trials identified by Fieldtrip
%matplotlib qt4
epochs.plot(n_channels=30)


#% calculate ICA and identified trials contaminated by blink
picks=mne.pick_types(raw.info, meg=True, exclude='bads',ref_meg=False)  
ica = ICA(n_components=0.95, random_state=0).fit(raw, decim=1)
ica.plot_components()
ica.plot_sources(epochs)

#reject bad trials with blinks by clicking
epochs.plot(n_epochs=30)

#save epochs
epochs_fname=data_path + '/'+ subject+ '-epo.fif'
epochs.save(epochs_fname)
























