# ---
# jupyter:
#   jupytext:
#     text_representation:
#       extension: .py
#       format_name: light
#       format_version: '1.5'
#       jupytext_version: 1.14.4
#   kernelspec:
#     display_name: Python 3
#     language: python
#     name: python3
# ---

# +
import mne
import os
import scipy.io
import listen_italian_functions
import numpy as np
from matplotlib import pyplot as plt
import pandas as pd
import pickle
import warnings
warnings.filterwarnings('ignore')
from IPython.display import clear_output
from itertools import combinations,permutations
from IPython.display import clear_output

data_path = os.path.dirname(os.path.dirname(os.getcwd()))

subject_name = ['Alice','Andrea','Daniel','Elena','Elenora','Elisa','Federica','Francesca','Gianluca1','Giada','Giorgia',
                'Jonluca','Laura','Leonardo','Linda','Lucrezia','Manu','Marco','Martina','Pagani','Pasquale','Sara',
                'Silvia','Silvia2','Tommaso']

remove_first = 0.5 #seconds

# -

# # Read the epoches

# +
Tmin = 0
Tmax = 3.51
trial_len = 2

GA_epoches = []
for s in subject_name:
    save_path = data_path + '/python/data/coherence_epochs/'+s+'-coh-epo-'+str(Tmin)+'-' \
    +str(Tmax)+'-trialLen-'+str(trial_len)+'.fif'
    epochs = mne.read_epochs(save_path)
    GA_epoches.append(epochs)
    print('----------------------------------------------------------------------------------------------------------------'+s)

# -

# # partial coherence

# coherence
# <img src="http://nipy.org/nitime/_images/math/8b2ad8f5230194bf1f946cdde75e57e513e8fb18.png">
#
# partial coherence
# <img src="http://nipy.org/nitime/_images/math/6f19a896ad7872e2077078e1d5dc1bac04b2049c.png">

# + code_folding=[0, 22, 30]
def coherence_preprocess_delay(epochs,remove_first,d,trial_len,extra_channels,eeg_channles,condition):	

    if condition != 'All':
        E = epochs[condition].copy()
    else:
        E = epochs.copy()
        
    eeg = E.copy().pick_channels(eeg_channles)
    speech = E.copy().pick_channels(extra_channels)

    E = eeg.copy().crop(d+remove_first,d+remove_first+trial_len)
    S = speech.copy().crop(0.5+remove_first,0.5+remove_first+trial_len)
    
    #E = eeg.copy().crop(0.5+remove_first,0.5+remove_first+trial_len)
    #S = speech.copy().crop(d+remove_first,d+remove_first+trial_len)
    
    
    c = np.concatenate((E.get_data(),S.get_data()),axis=1)
    
    return c


def get_coherence(epochs,sfreq,fmin,fmax,indices):
    con, freqs, times, n_epochs, n_tapers = mne.connectivity.spectral_connectivity(epochs, method='coh',mode='multitaper', 
                                                                                   sfreq=sfreq, 
                                                              fmin=fmin, fmax=fmax,indices=indices,faverage=True, 
                                                              tmin=0, mt_adaptive=False, block_size=1000,verbose='ERROR')

    return con

def get_partialCoherence(conXY,conXR,conRY,fr):
    partial_coh_XY_R=[]
    for i in range(59):
        a = (abs(conXY[i,fr]-conXR[i,fr]*conRY[fr])**2) / ((1-abs(conXR[i,fr])**2)*(1-abs(conRY[fr])**2))
        partial_coh_XY_R.append(a)

    partial_coh_XY_R = np.asarray(partial_coh_XY_R)
    
    return partial_coh_XY_R


# + code_folding=[28, 43, 53]
features = ['envelop','jawaopening','lipaparature','lipProtrusion','TTCD','TMCD','TBCD']
eeg_chan = GA_epoches[0].ch_names[0:59]
sfreq = GA_epoches[0].info['sfreq']

delay = np.arange(-5,6) / 10

condition = ['hyper','normal','hypo','All']
condition = ['All']

features = ['envelop','lipaparature']

feat_comb = (['envelop','lipaparature'],['lipaparature','envelop'])

#############################
iter_freqs = [
    ('fr', 0.25, 1),
    ('fr', 0.5, 2),
    ('fr', 1, 3),
    ('fr', 1, 4),
    ('fr', 2, 6),
    ('fr', 4, 8),
    ('fr', 8, 12),
    ('fr', 12, 18),
    ('fr', 18, 24),
    ('fr', 24, 40)
]
fmin = []
fmax = []
for fr in range(0,len(iter_freqs)):
    fmin.append(iter_freqs[fr][1])
    fmax.append(iter_freqs[fr][2])
    
#######################################
indices = []
b = (np.repeat(59,59),np.arange(0,59))
indices.append(b)
b = (np.repeat(60,59),np.arange(0,59))
indices.append(b)
b = (np.repeat(59,1),np.repeat(60,1))
indices.append(b)

INDEX = []
b=0
for idx in range(0,len(indices)):
    a = np.arange(b,b+len(indices[idx][0]))
    INDEX.append(a)
    b = b+len(a)

indices = np.concatenate((indices),axis=1)
indices = (indices[0],indices[1])
#######################################    
    
frame = [] 
for s in range(0,len(subject_name)):
    for d in delay:
        for con in condition:
            c = coherence_preprocess_delay(GA_epoches[s],remove_first,d + 0.5,trial_len,features,eeg_chan,con)         
            coh = get_coherence(c,sfreq,fmin,fmax,indices)    

            for iii in range(2):
                if iii ==0:
                    conXY = coh[INDEX[0],:]
                    conXR = coh[INDEX[1],:]
                else:
                    conXY = coh[INDEX[1],:]
                    conXR = coh[INDEX[0],:]

                conRY = coh[INDEX[2],:][0]

                for fr in range(0,len(iter_freqs)):
                    a = str(iter_freqs[fr][0])+ ' '+str(iter_freqs[fr][1])+' - '+str(iter_freqs[fr][2])+'Hz'

                    cc = get_partialCoherence(conXY,conXR,conRY,fr)            

                    df = pd.DataFrame({'Feature':feat_comb[iii][0],'FeatureDelay':d,'RemoveFeature':feat_comb[iii][1],
                                       'RemoveFeatureDelay':d,'Freq':a,'Condition':con,
                                       'Subject': subject_name[s], 'Data':[cc.flatten()]})
                    frame.append(df)


            print(str(d)+'-'+subject_name[s])

data=pd.concat((frame),axis=0)
save_path = data_path + '/python/data/partialCoh/PartialCoh-removedFirst-'+str(remove_first)+'.pkl'
data.to_pickle(save_path)   


# -

# # surrogate distribution partial coherence

# + code_folding=[0, 101]
def PartialCoherence_preprocess_delay_surrogate(epochs,remove_first,d,trial_len,eeg_channles,keep_feat,condition,iter_freqs):	

    
    ##############
    if condition != 'All':
        E = epochs[condition].copy()
    else:
        E = epochs.copy()
    
    eeg = E.copy().pick_channels(eeg_channles)
    speech = E.copy().pick_channels(keep_feat)

    E = eeg.copy().crop(d+remove_first,d+remove_first+trial_len)
    S = speech.copy().crop(0.5+remove_first,0.5+remove_first+trial_len)
    
    #E = eeg.copy().crop(0.5+remove_first,0.5+remove_first+trial_len)
    #S = speech.copy().crop(d+remove_first,d+remove_first+trial_len)
    
    
    sfreq = E.info['sfreq']
    
    E = E.get_data()
    S = S.get_data()

    label = np.concatenate((eeg.ch_names,speech.ch_names))
    
    ##################### all possible combination
    trial_length=S.shape[0]
    a = list(permutations(np.arange(0,trial_length), 2))
    a = np.asarray(a)
    X = np.arange(0,trial_length)

    no_surrogates = 500 #dummy value
    B=[]
    for j in range(no_surrogates):
        X = np.roll(X,1)
        while True:
            A,a = get_combinations(X,a)        
            if A.shape[0] == trial_length:
                B.append(A)
                break
            elif len(a)==0:
                break
            else:
                X = np.roll(X,1)
                print('.',end=' ')
    
    B = np.asarray(B)
    no_surrogates = len(B)
    
    #######################################à
    fmin = []
    fmax = []
    for fr in range(0,len(iter_freqs)):
        fmin.append(iter_freqs[fr][1])
        fmax.append(iter_freqs[fr][2])  
    
    #######################################
    indices = []
    b = (np.repeat(59,59),np.arange(0,59))
    indices.append(b)
    b = (np.repeat(60,59),np.arange(0,59))
    indices.append(b)
    b = (np.repeat(59,1),np.repeat(60,1))
    indices.append(b)

    INDEX = []
    b=0
    for idx in range(0,len(indices)):
        a = np.arange(b,b+len(indices[idx][0]))
        INDEX.append(a)
        b = b+len(a)

    indices = np.concatenate((indices),axis=1)
    indices = (indices[0],indices[1])
    #######################################  

    frames = np.zeros((2,59,len(iter_freqs),no_surrogates))
    for i in range(no_surrogates):
        print('--------------------'+str(i))
        EE = E.copy()
        SS = S.copy()
        c = np.concatenate((EE[B[i][:,0]],SS[B[i][:,1]]),axis=1)
        
        coh = get_coherence(c,sfreq,fmin,fmax,indices)
        for iii in range(0,1):
            if iii ==0:
                conXY = coh[INDEX[0],:]
                conXR = coh[INDEX[1],:]
            else:
                conXY = coh[INDEX[1],:]
                conXR = coh[INDEX[0],:]
            
            conRY = coh[INDEX[2],:][0]

            for f in range(0,len(iter_freqs)):
                frames[iii,:,f,i] = get_partialCoherence(conXY,conXR,conRY,f)
        clear_output()  
        
    return frames

def get_combinations(X,a):
    aa = a
    A=[]
    EEG = []
    Speech = []
    for i in range(0,len(X)):
        b = np.where(a[:,0]==X[i])
        if not len(b[0]) == 0:
            for k in range(len(b[0])):
                if not a[b[0][k],1] in Speech:
                    A.append(a[b[0][k],:])
                    EEG.append(a[b[0][k],0])
                    Speech.append(a[b[0][k],1])
                    a = np.delete(a, b[0][k], 0)
                    break
    if len(A) == len(X):                    
        return np.asarray(A),a
    else:
        return np.asarray(A),aa	



# + code_folding=[]
features = ['envelop','jawaopening','lipaparature','lipProtrusion','TTCD','TMCD','TBCD']
eeg_chan = GA_epoches[0].ch_names[0:59]
sfreq = GA_epoches[0].info['sfreq']

delay = np.arange(-5,6) / 10

condition = ['hyper','normal','hypo','All']
condition = ['All']

features = ['envelop','lipaparature']

#############################
iter_freqs = [
    ('fr', 0.25, 1),
    ('fr', 0.5, 2),
    ('fr', 1, 3),
    ('fr', 1, 4),
    ('fr', 2, 6),
    ('fr', 4, 8),
    ('fr', 8, 12),
    ('fr', 12, 18),
    ('fr', 18, 24),
    ('fr', 24, 40)
]

#######################################    
    
    
for s in range(0,len(subject_name)):
    frame = [] 
    for d in delay:       
        for con in condition:
            surrogate_coh = PartialCoherence_preprocess_delay_surrogate(GA_epoches[s],remove_first,
                                                                        d + 0.5,trial_len,eeg_chan,features,
                                                                        con,iter_freqs)

            # mean or median of the surrogate distribution
            coh=surrogate_coh

            for fr in range(0,len(iter_freqs)):
                a = str(iter_freqs[fr][0])+ ' '+str(iter_freqs[fr][1])+' - '+str(iter_freqs[fr][2])+'Hz'

                cc = coh[0,:,fr,:]            
                df = pd.DataFrame({'Feature':features[0],'FeatureDelay':d,'RemoveFeature':features[1],
                               'RemoveFeatureDelay':d,'Freq':a,'Condition':con,
                               'Subject': subject_name[s], 'Data':[cc]})
                frame.append(df)
                cc = coh[1,:,fr,:]            
                df = pd.DataFrame({'Feature':features[1],'FeatureDelay':d,'RemoveFeature':features[0],
                               'RemoveFeatureDelay':d,'Freq':a,'Condition':con,
                               'Subject': subject_name[s], 'Data':[cc]})
                frame.append(df)    

        
    data=pd.concat((frame),axis=0)
    a = ('-').join(features)
    save_path = data_path + '/python/data/partialCoh/Surrogate_PartialCoh-removedFirst-' \
    +str(remove_first)+'-'+a+'-'+subject_name[s]+'.pkl'
    data.to_pickle(save_path)  
    
# putit into one file    
A=[]
a = ('-').join(features)
for s in subject_name:
    save_path = data_path + '/python/data/partialCoh/SurrogateCoherence-removedFirst-' \
    +str(remove_first)+'-'+a+'-'+s+'.pkl'
    A.append(pd.read_pickle(save_path))

data = pd.concat((A),axis=0)
save_path = data_path + '/python/data/partialCoh/SurrogateCoherence-removedFirst-' \
    +str(remove_first)+'-'+a+'.pkl'  
data.to_pickle(save_path)  
# -





# # remove contribution of lipaperature from the envelop delayed version (partial coherence implemented here) 

def partialCoherence_preprocess_delay(epochs,remove_first,d,trial_len,feat,condition,typee):	

    if condition != 'All':
        E = epochs[condition].copy()
    else:
        E = epochs.copy()
    
    S = E.copy().pick_channels(feat)
    
    if typee != 'eeg':
        E = S.copy().crop(d+remove_first,d+remove_first+trial_len)
    else:
        E = S.copy().crop(0.5+remove_first,0.5+remove_first+trial_len)

    c = E.get_data()

    return c


# + code_folding=[]
features = ['envelop','jawaopening','lipaparature','lipProtrusion','TTCD','TMCD','TBCD']
eeg_chan = GA_epoches[0].ch_names[0:59]
sfreq = GA_epoches[0].info['sfreq']

delay = np.arange(-5,6) / 10

condition = ['hyper','normal','hypo','All']
condition = ['All']

features = ['envelop','lipaparature']

feat_comb = (['envelop','lipaparature'],['lipaparature','envelop'])
FD = np.arange(-5,6) / 10 # keep feature delay
RD = np.arange(-5,6) / 10 # remove feature delay

#############################
iter_freqs = [
    ('fr', 1, 3),
    ('fr', 4, 6)
]
fmin = []
fmax = []
for fr in range(0,len(iter_freqs)):
    fmin.append(iter_freqs[fr][1])
    fmax.append(iter_freqs[fr][2])
    
#######################################
indices = []
b = (np.repeat(59,59),np.arange(0,59))
indices.append(b)
b = (np.repeat(60,59),np.arange(0,59))
indices.append(b)
b = (np.repeat(59,1),np.repeat(60,1))
indices.append(b)

INDEX = []
b=0
for idx in range(0,len(indices)):
    a = np.arange(b,b+len(indices[idx][0]))
    INDEX.append(a)
    b = b+len(a)

indices = np.concatenate((indices),axis=1)
indices = (indices[0],indices[1])
#######################################  
    
frame = [] 
for s in range(0,len(subject_name)):   
    clear_output() 
    for fd in FD:
        for rd in RD:
            for con in condition:
                eeg = partialCoherence_preprocess_delay(GA_epoches[s],remove_first,fd + 0.5,trial_len,eeg_chan,con,'eeg')
                speech = partialCoherence_preprocess_delay(GA_epoches[s],remove_first,fd + 0.5,trial_len,[features[0]],con,'speech')
                lipaparature = partialCoherence_preprocess_delay(GA_epoches[s],remove_first,rd + 0.5,trial_len,[features[1]],con,'speech')

                c = np.concatenate((eeg,speech,lipaparature),axis=1)
                coh = get_coherence(c,sfreq,fmin,fmax,indices)

                for iii in range(2):
                    if iii ==0:
                        conXY = coh[INDEX[0],:]
                        conXR = coh[INDEX[1],:]
                    else:
                        conXY = coh[INDEX[1],:]
                        conXR = coh[INDEX[0],:]

                    conRY = coh[INDEX[2],:][0]

                    for fr in range(0,len(iter_freqs)):
                        a = str(iter_freqs[fr][0])+ ' '+str(iter_freqs[fr][1])+' - '+str(iter_freqs[fr][2])+'Hz'

                        cc = get_partialCoherence(conXY,conXR,conRY,fr)            
                        df = pd.DataFrame({'Feature':feat_comb[iii][0],'FeatureDelay':fd,'RemoveFeature':feat_comb[iii][1],
                                       'RemoveFeatureDelay':rd,'Freq':a,'Condition':con,
                                       'Subject': subject_name[s], 'Data':[cc.flatten()]})
                        frame.append(df)    
                print(str(fd)+'-'+str(rd)+'-'+subject_name[s])

data=pd.concat((frame),axis=0)
save_path = data_path + '/python/data/partialCoh/Delayed_partialCohopp-removedFirst-'+str(remove_first)+'.pkl'
data.to_pickle(save_path)
# -





# +
s=0
d=0.2
iter_freqs = [
    ('fr', 1, 3),
    ('fr', 4, 6)
]
condition = 'All'
keep_feat = ['envelop']
remove_feat = ['lipaparature']
features = ['envelop','jawaopening','lipaparature','lipProtrusion','TTCD','TMCD','TBCD']
remove_first = 0.5 #seconds
channel_names = GA_epoches[0].ch_names
eeg_chan = GA_epoches[0].ch_names[0:59]
#######################################
indices = []
b = (np.repeat(59,59),np.arange(0,59))
indices.append(b)
b = (np.repeat(60,59),np.arange(0,59))
indices.append(b)
b = (np.repeat(59,1),np.repeat(60,1))
#indices.append(b)

INDEX = []
b=0
for idx in range(0,len(indices)):
    a = np.arange(b,b+len(indices[idx][0]))
    INDEX.append(a)
    b = b+len(a)

indices = np.concatenate((indices),axis=1)
indices = (indices[0],indices[1])
#######################################  

eeg = partialCoherence_preprocess_delay(GA_epoches[s],remove_first,d + 0.5,trial_len,eeg_chan,condition)
envelop = partialCoherence_preprocess_delay(GA_epoches[s],remove_first,d + 0.5,trial_len,keep_feat,condition)
lipaparature = partialCoherence_preprocess_delay(GA_epoches[s],remove_first,d + 0.5,trial_len,remove_feat,condition) 

c = np.concatenate((eeg,envelop,lipaparature),axis=1)
print(c.shape)
print(fmin)
print(fmax)
coh = get_coherence(c,400,fmin,fmax,indices)
# -

conXY = coh[INDEX[0],:]
a = plt.plot(conXY[:,0]) # plotting by columns

# +
condition = ['All']
indices = (np.repeat([np.arange(59,len(features)+59)],59),np.tile(np.arange(0,59),len(features)))   

extra_channels = ['envelop','jawaopening','lipaparature','lipProtrusion','TTCD','TMCD','TBCD']
eeg_channles = GA_epoches[0].ch_names[0:59]
event_id = {'Hyper': 1,'Normal': 2,'Hypo': 3}
ch_types = np.repeat('eeg', len(features)+59)
ch_names = np.hstack((eeg_channles,features))        
info = mne.create_info(ch_names = ch_names.tolist(),ch_types = ch_types,sfreq = GA_epoches[0].info['sfreq'])
ch_names = np.setdiff1d(extra_channels,features)
c = coherence_preprocess_delay(GA_epoches[s],remove_first,d+0.5,trial_len,extra_channels,eeg_channles,condition)
coh2 = get_coherence(c,400,fmin,fmax,indices)
# -

cc = np.split(coh2[:,0], len(features))
a = plt.plot(cc[0]) # plotting by columns



c = np.concatenate((eeg,envelop,lipaparature),axis=1)
coh = get_coherence(c,400,fmin,fmax,indices)
conXY = coh[INDEX[0],:]
conXR = coh[INDEX[1],:]
conRY = coh[INDEX[2],:][0]
a = plt.plot(conXY[:,0]) # plotting by columns
a = plt.plot(conXR[:,0]) # plotting by columns
print(conRY[0])

# +
s=0
epochs = GA_epoches[s].copy()
eeg = epochs.copy().pick_channels(eeg_channles)
speech = epochs.copy().pick_channels(extra_channels)

E = eeg.copy().crop(d+remove_first,d+remove_first+trial_len)
S = speech.copy().crop(0.5+remove_first,0.5+remove_first+trial_len)

events = E.events
sfreq = E.info['sfreq']    
C = np.concatenate((E.get_data(),S.get_data()),axis=1)
epochs = mne.EpochsArray(C, info, E.events, 0,event_id)
c = epochs.get_data()

ch_names = np.hstack((E.ch_names,S.ch_names))


# +
#A = C.mean(axis=0)
#a = plt.plot(A[2,:]) # plotting by columns
A = c.mean(axis=0)
a = plt.plot(A[59,:]) # plotting by columns

#a = epochs.copy().pick_channels(['AF7']).get_data()
#A = a.mean(axis=0)
#a = plt.plot(A[0,:]) # plotting by columns
# -

print(GA_epoches[s].ch_names)





c = np.concatenate((eeg,envelop,lipaparature),axis=1)
coh = get_coherence(c,400,fmin,fmax,indices)
conXY = coh[INDEX[1],:]
conXR = coh[INDEX[0],:]
conRY = coh[INDEX[2],:][0]


a = plt.plot(conXY[:,0]) # plotting by columns
a = plt.plot(conXR[:,0]) # plotting by columns
print(conRY[0])

a = plt.plot(conXY[0:59,0]) # plotting by columns
a = plt.plot(conXY[59:118,0]) # plotting by columns
print(conXY[118,0])

# +
keep_feat1= np.append(eeg_chan,keep_feat)

envelop = partialCoherence_preprocess_delay(GA_epoches[s],remove_first,d + 0.5,trial_len,channel_names,
                                           keep_feat1,condition)

remove_feat1= np.append(eeg_chan,remove_feat)
lipaparature = partialCoherence_preprocess_delay(GA_epoches[s],remove_first,d + 0.5,trial_len,channel_names,
                                                 remove_feat1,condition)                

conXY = get_coherence(envelop,400,fmin,fmax,indicesXY)
conXR = get_coherence(lipaparature,400,fmin,fmax,indicesXR)

c = np.dstack((envelop[:,59,:],lipaparature[:,59,:]))
c = np.swapaxes(c,1,2)
conRY = get_coherence(c,400,fmin,fmax,indicesRY)[0]
# -

a = plt.plot(conXY[:,0]) # plotting by columns
a = plt.plot(conXR[:,0]) # plotting by columns
print(conRY[0])

# +
eeg = partialCoherence_preprocess_delay(GA_epoches[s],remove_first,d + 0.5,trial_len,channel_names,
                                            eeg_chan,condition)
keep_feat = ['envelop']

envelop = partialCoherence_preprocess_delay(GA_epoches[s],remove_first,d + 0.5,trial_len,channel_names,
                                           keep_feat,condition)
remove_feat = ['lipaparature']

lipaparature = partialCoherence_preprocess_delay(GA_epoches[s],remove_first,d + 0.5,trial_len,channel_names,
                                                 remove_feat,condition)                

c = np.concatenate((eeg,envelop),axis=1)
conXY = get_coherence(c,400,fmin,fmax,indicesXY)
c = np.concatenate((eeg,lipaparature),axis=1)
conXR = get_coherence(c,400,fmin,fmax,indicesXR)

c = np.concatenate((envelop,lipaparature),axis=1)
conRY = get_coherence(c,400,fmin,fmax,indicesRY)[0]
# -

a = plt.plot(conXY[:,0]) # plotting by columns
a = plt.plot(conXR[:,0]) # plotting by columns
print(conRY[0])













# # bandpass filter epoches and save as fieldtrip format for partial coherence

# +
iter_freqs = [
    ('fr', 1, 3),
    #('fr', 2, 4),
    #('fr', 3, 5),
    ('fr', 4, 6)
    #('fr', 5, 7),
    #('fr', 6, 8),
    #('fr', 7, 9),
    #('fr', 8, 10),
    #('fr', 9, 11),
    #('fr', 10, 12)
]

save_path = data_path +'/python/data/partialCoh/partialCoh-trailLen-' +str(trial_len)+'-removedFirst-'+ str(remove_first)

features = ['envelop','jawaopening','lipaparature','lipProtrusion','TTCD','TMCD','TBCD']
condition = ['Hyper','Normal','Hypo','All']
delay = np.arange(0,1.1,0.1)


extra_channels = ['envelop','jawaopening','lipaparature','lipProtrusion','TTCD','TMCD','TBCD']
eeg_channles = np.setdiff1d(GA_epoches[0].ch_names, extra_channels)
event_id = {'Hyper': 1,'Normal': 2,'Hypo': 3}
ch_types = np.repeat('eeg', len(features)+59)
ch_names = np.hstack((eeg_channles,features))        
info = mne.create_info(ch_names = ch_names.tolist(),ch_types = ch_types,sfreq = GA_epoches[0].info['sfreq'])
ch_names = np.setdiff1d(extra_channels,features)
        
for s in range(0,len(subject_name)):
    for d in delay:   
        for c in condition:
            for fr in range(0,len(iter_freqs)):
                b = str(iter_freqs[fr][0])+ '-'+str(iter_freqs[fr][1])+'-'+str(iter_freqs[fr][2])+'Hz'

                fmin = iter_freqs[fr][1]
                fmax = iter_freqs[fr][2]
                a = listen_italian_functions.partialCoherence_preprocess_delay(GA_epoches[s],remove_first,d,
                                                                               trial_len,extra_channels,eeg_channles,
                                                                               info,ch_names,event_id,fmin,fmax,c)   
    
                d = d.round(decimals=1)
                scipy.io.savemat(save_path+'s-'+'condition-'+c+'-delay-'+str(d)+'-'+b+'-' +subject_name[s],a)
        
        

StarcoderdataJupyterScriptsDedupFiltered