Ejemplo n.º 1
0
    def pbEstimate_Callback(self):
        import config
        from swcm import Imatrix, Lcurve
        import numpy as np
        MethodVal = config.MethodVal
        K = config.K
        s = config.s
        nC, nSamples, nTrials = s.shape
        nV = K.shape[1]

        #        logalpha = Lcurve.MN(s[:,0,0], K)
        #        poweralpha = logalpha[0]
        #        alpha = pow(10, poweralpha)
        #        print("from Lcurve alpha=%3.2e" %alpha)

        alpha = 0.001
        if MethodVal == 0:
            Imat = Imatrix.MN(alpha, K)
        elif MethodVal == 1:
            Imat = Imatrix.sMN(alpha, K)
        else:
            print("Inverse Method is not selected. ")

        if nTrials > 1:
            sden = np.zeros((nV, nSamples, nTrials))
            for i in range(nTrials):
                sden[:, :, i] = np.dot(Imat, s[:, :, i])
        else:
            sden = np.dot(Imat, s)

        print("Source is estimated")
        config.sden = sden

        return sden
Ejemplo n.º 2
0
    def pbEstimate_Callback(self):
        import config
        from swcm import Imatrix, Lcurve
        import numpy as np
        #        import pdb
        #        pdb.pm()
        MethodVal = config.MethodVal
        K = config.K
        s = config.s
        nC, nSamples, nTrials = s.shape
        nV = K.shape[1]

        if self.rbTikhonov.isChecked():
            poweralpha = self.leTikhonov.text()
            poweralpha = int(poweralpha)
            alpha = pow(10, poweralpha)
            print("alpha = %3.2e " % alpha)
        else:
            logalpha = Lcurve.MN(s[:, 0, 0], K)
            poweralpha = logalpha[0]
            alpha = pow(10, poweralpha)
            print("from Lcurve alpha=%3.2e" % alpha)

        if MethodVal == 0:
            Imat = Imatrix.MN(alpha, K)
        elif MethodVal == 1:
            Imat = Imatrix.sMN(alpha, K)
        else:
            print("Inverse Method is not selected. ")

        sden = np.zeros((nV, nSamples, nTrials))
        for i in range(nTrials):
            sden[:, :, i] = np.dot(Imat, s[:, :, i])

        print("Source is estimated")
        config.sden = sden

        return sden
Ejemplo n.º 3
0
    def pbEstimate_Callback(self):
        import config 
        from swcm import Imatrix, Lcurve
        import numpy as np      
#        import pdb
#        pdb.pm() 
        MethodVal = config.MethodVal 
        K = config.K
        s = config.s
        nC, nSamples, nTrials = s.shape 
        nV = K.shape[1]
                
        if self.rbTikhonov.isChecked():
            poweralpha = self.leTikhonov.text()
            poweralpha = int(poweralpha)
            alpha = pow(10, poweralpha)  
            print("alpha = %3.2e "  %alpha)
        else :         
            logalpha = Lcurve.MN(s[:,0,0], K)
            poweralpha = logalpha[0]
            alpha = pow(10, poweralpha)                      
            print("from Lcurve alpha=%3.2e" %alpha)

        if MethodVal == 0:
            Imat = Imatrix.MN(alpha, K) 
        elif MethodVal == 1:
            Imat = Imatrix.sMN(alpha, K) 
        else:
            print("Inverse Method is not selected. ")
            
        sden = np.zeros((nV, nSamples, nTrials)) 
        for i in range(nTrials):             
            sden[:,:,i] = np.dot(Imat, s[:,:,i]) 
        
        print("Source is estimated")                    
        config.sden = sden 
        
        return  sden 
Ejemplo n.º 4
0
fig = plt.figure()
plt.plot(K[:, :3])
plt.show()

#K = data.reshape((nD, nE))
#K = K.T

#fig = plt.figure()
#plt.imshow(K, cmap='seismic', aspect="auto")
#plt.show()

#VoxCoord = np.loadtxt('/Users/jesong1126/Documents/MATLAB/SWCM/data/TalCoord2447.txt', delimiter='\t', dtype=np.dtype('i4') )
from3To1 = np.kron(np.eye(nV), np.ones((1, 3)))

alpha = 0.0001
Imn = Imatrix.MN(alpha, K)
sdeneegMean = np.dot(Imn, eegMean)
sdeneegT = np.dot(Imn, eegT)

fig, ax = plt.subplots(2, 2)
im = ax[0, 0].imshow(sdeneegMean, cmap='seismic', aspect="auto")
#ax[0,0].colorbar(im)
ax[0, 1].plot(msSamples, sdeneegMean.T)
im = ax[0, 0].imshow(sdeneegT, cmap='seismic', aspect="auto")
#ax[0,0].colorbar(im)
ax[0, 1].plot(msSamples, sdeneegT.T)
plt.show()

#Imn = Imatrix.LORETA(alpha, K)
temp = np.kron(np.eye(nV), np.ones((1, 3)))
Ejemplo n.º 5
0
def CSL(phi, K, bkdir):
    ## alphaS
    Logalpha = np.arange(-6, 7, 1)
    nLcurve = len(Logalpha)
    LcurveS = []  # Lcurve Residual L2
    for i in Logalpha:
        alphai = 10**i
        Imat = Imatrix.MN(alphai, K)
        beta = np.dot(Imat, phi)
        phihat = np.dot(K, beta)
        phidiff = phi - phihat
        Resid2 = np.sqrt(sum(phidiff * phidiff))
        L2 = np.sqrt(sum(beta * beta))
        LcurveS = np.concatenate((LcurveS, [i, Resid2, L2]), axis=0)

    LcurveS = LcurveS.reshape(nLcurve, 3)
    LcurveS0 = np.array([
        LcurveS[:, 0], LcurveS[:, 1] / max(LcurveS[:, 1]),
        LcurveS[:, 2] / max(LcurveS[:, 2])
    ])
    LcurveS = LcurveS0.T

    Resid2D1 = np.diff(LcurveS[:, 1])
    Resid2D2 = np.diff(Resid2D1)
    L2D1 = np.diff(LcurveS[:, 2])
    L2D2 = np.diff(L2D1)

    pho = np.array([
        LcurveS[:, 1],
        np.concatenate((Resid2D1, [0])),
        np.concatenate((Resid2D2, [0, 0]))
    ])
    pho = pho.T
    eta = np.array([
        LcurveS[:, 2],
        np.concatenate((L2D1, [0])),
        np.concatenate((L2D2, [0, 0]))
    ])
    eta = eta.T

    nume = (np.multiply(pho[:, 1], eta[:, 2]) -
            np.multiply(pho[:, 2], eta[:, 1]))
    denume = np.power((np.multiply(pho[:, 1], pho[:, 1]) -
                       np.multiply(eta[:, 1], eta[:, 1])), 3 / 2)
    kappa = np.array(np.divide(nume, denume))
    maxKappa = np.where(abs(kappa) == np.nanmax(abs(kappa)))[0]
    logalphaS = LcurveS[maxKappa[0], 0]

    figLC, axLC = plt.subplots(2, 2)
    axLC[0, 0].plot(LcurveS[:, 0], LcurveS[:, 1])
    axLC[0, 0].set_xlim((Logalpha[0], Logalpha[-1]))
    axLC[0, 0].set_xlabel('alpha')
    axLC[0, 0].set_ylabel('Residual')
    axLC[0, 1].plot(LcurveS[:, 0], LcurveS[:, 2])
    axLC[0, 1].set_xlim((Logalpha[0], Logalpha[-1]))
    axLC[0, 1].set_xlabel('alpha')
    axLC[0, 1].set_ylabel('|J|')
    axLC[1, 0].scatter(LcurveS[:, 1], LcurveS[:, 2])
    axLC[1, 0].set_xlabel('Residual')
    axLC[1, 0].set_ylabel('|J|')
    axLC[1, 1].scatter(LcurveS[:, 0], kappa)
    axLC[1, 1].set_xlabel('alpha')
    axLC[1, 1].set_ylabel('kappa')

    fig, ax = plt.subplots()
    ax.scatter(LcurveS[:, 1], LcurveS[:, 2])
    plt.xlabel('Residual')
    plt.ylabel('|J|')
    for i, txt in enumerate(Logalpha):
        ax.annotate(txt, (LcurveS[i, 1], LcurveS[i, 2]),
                    xytext=(5, 1),
                    textcoords='offset points')

    ## alphaL
    Ne, Nd = K.shape
    for dsafilename1 in glob.iglob(bkdir + "/*.Adjacents_1_*"):
        A_local1 = read_bk.dsa(dsafilename1)
    for dsafilename2 in glob.iglob(bkdir + "/*.Adjacents_2_*"):
        A_local2 = read_bk.dsa(dsafilename2)

    nD1 = A_local1.shape[0] - 1
    nD2 = A_local2.shape[0] - 1
    Nei1 = A_local1[:-1, :-1]
    Nei2 = A_local2[:-1, :-1]

    r0 = np.concatenate((Nei1, np.zeros((nD1, nD2))), axis=1)
    r1 = np.concatenate((np.zeros((nD2, nD1)), Nei2), axis=1)
    Neighbor = np.concatenate((r0, r1), axis=0)

    B = np.identity(Nd)
    for i in range(Nd):
        Ni = np.sum(Neighbor[i, :]) - 1
        if Ni > 0:
            B[i, :] = -Neighbor[i, :] / Ni
            B[i, i] = 1
        else:
            B[i, :] = -1 / (Nd - 1)
            B[i, i] = 1

    alphaS = 10**logalphaS
    Logalpha = np.arange(-6, 7, 1)
    nLcurve = len(Logalpha)
    LcurveL = []  # np.zeros((nLcurve, 4))
    for i in Logalpha:
        alphaLi = 10**i
        Imat = Imatrix.CSL(alphaS, alphaLi, K, bkdir)
        beta = np.dot(Imat, phi)
        phihat = np.dot(K, beta)
        phidiff = phi - phihat
        Resid2 = np.sqrt(sum(phidiff * phidiff))
        L2 = np.sqrt(sum(beta * beta))
        Bbeta = np.dot(B, beta)
        BL2 = np.sqrt(sum(Bbeta * Bbeta))
        LcurveL = np.concatenate((LcurveL, [i, Resid2, L2, BL2]), axis=0)

    LcurveL = LcurveL.reshape(nLcurve, 4)
    LcurveL0 = np.array([
        LcurveL[:, 0], LcurveL[:, 1] / max(LcurveL[:, 1]),
        LcurveL[:, 2] / max(LcurveL[:, 2]), LcurveL[:, 3] / max(LcurveL[:, 3])
    ])
    LcurveL = LcurveL0.T

    Resid2D1 = np.diff(LcurveL[:, 1])
    Resid2D2 = np.diff(Resid2D1)
    L2D1 = np.diff(LcurveL[:, 3])
    L2D2 = np.diff(L2D1)

    pho = np.array([
        LcurveL[:, 1],
        np.concatenate((Resid2D1, [0])),
        np.concatenate((Resid2D2, [0, 0]))
    ])
    pho = pho.T
    eta = np.array([
        LcurveL[:, 3],
        np.concatenate((L2D1, [0])),
        np.concatenate((L2D2, [0, 0]))
    ])
    eta = eta.T

    nume = (np.multiply(pho[:, 1], eta[:, 2]) -
            np.multiply(pho[:, 2], eta[:, 1]))
    denume = np.power((np.multiply(pho[:, 1], pho[:, 1]) -
                       np.multiply(eta[:, 1], eta[:, 1])), 3 / 2)
    kappa = np.array(np.divide(nume, denume))
    maxKappa = np.where(abs(kappa) == np.nanmax(abs(kappa)))[0]
    logalphaL = LcurveL[maxKappa[0], 0]

    figLCL, axLCL = plt.subplots(2, 2)
    axLCL[0, 0].plot(LcurveL[:, 0], LcurveL[:, 1])
    axLCL[0, 0].set_xlim((Logalpha[0], Logalpha[-1]))
    axLCL[0, 0].set_xlabel('alpha')
    axLCL[0, 0].set_ylabel('Residual')
    axLCL[0, 1].plot(LcurveL[:, 0], LcurveL[:, 3])
    axLCL[0, 1].set_xlim((Logalpha[0], Logalpha[-1]))
    axLCL[0, 1].set_xlabel('alpha')
    axLCL[0, 1].set_ylabel('|BJ|')
    axLCL[1, 0].scatter(LcurveL[:, 1], LcurveL[:, 3])
    axLCL[1, 0].set_xlabel('Residual')
    axLCL[1, 0].set_ylabel('|BJ|')
    axLCL[1, 1].scatter(LcurveL[:, 0], kappa)
    axLCL[1, 1].set_xlabel('alpha')
    axLCL[1, 1].set_ylabel('kappa')

    fig, ax = plt.subplots()
    ax.scatter(LcurveL[:, 1], LcurveL[:, 3])
    plt.xlabel('Residual')
    plt.ylabel('|BJ|')
    for i, txt in enumerate(Logalpha):
        ax.annotate(txt, (LcurveL[i, 1], LcurveL[i, 3]),
                    xytext=(5, 1),
                    textcoords='offset points')

    logalpha = logalphaS, LcurveS, logalphaL, LcurveL

    return logalpha
Ejemplo n.º 6
0
def MN(phi, K):

    Logalpha = np.arange(-6, 7, 1)
    nLcurve = len(Logalpha)
    Lcurve = []  # Lcurve Residual L2
    for i in Logalpha:
        alphai = 10**i
        Imat = Imatrix.MN(alphai, K)
        beta = np.dot(Imat, phi)
        phihat = np.dot(K, beta)
        phidiff = phi - phihat
        Resid2 = np.sqrt(sum(phidiff * phidiff))
        L2 = np.sqrt(sum(beta * beta))
        Lcurve = np.concatenate((Lcurve, [i, Resid2, L2]), axis=0)

    Lcurve = Lcurve.reshape(nLcurve, 3)
    Lcurve0 = np.array([
        Lcurve[:, 0], Lcurve[:, 1] / max(Lcurve[:, 1]),
        Lcurve[:, 2] / max(Lcurve[:, 2])
    ])
    Lcurve = Lcurve0.T

    Resid2D1 = np.diff(Lcurve[:, 1])
    Resid2D2 = np.diff(Resid2D1)
    L2D1 = np.diff(Lcurve[:, 2])
    L2D2 = np.diff(L2D1)

    pho = np.array([
        Lcurve[:, 1],
        np.concatenate((Resid2D1, [0])),
        np.concatenate((Resid2D2, [0, 0]))
    ])
    pho = pho.T
    eta = np.array([
        Lcurve[:, 2],
        np.concatenate((L2D1, [0])),
        np.concatenate((L2D2, [0, 0]))
    ])
    eta = eta.T

    nume = (np.multiply(pho[:, 1], eta[:, 2]) -
            np.multiply(pho[:, 2], eta[:, 1]))
    denume = np.power((np.multiply(pho[:, 1], pho[:, 1]) -
                       np.multiply(eta[:, 1], eta[:, 1])), 3 / 2)
    kappa = np.divide(nume, denume)

    figLC, axLC = plt.subplots(2, 2)
    axLC[0, 0].plot(Lcurve[:, 0], Lcurve[:, 1])
    axLC[0, 0].set_xlim((Logalpha[0], Logalpha[-1]))
    axLC[0, 0].set_xlabel('alpha')
    axLC[0, 0].set_ylabel('Residual')
    axLC[0, 1].plot(Lcurve[:, 0], Lcurve[:, 2])
    axLC[0, 1].set_xlim((Logalpha[0], Logalpha[-1]))
    axLC[0, 1].set_xlabel('alpha')
    axLC[0, 1].set_ylabel('|J|')
    axLC[1, 0].scatter(Lcurve[:, 1], Lcurve[:, 2])
    axLC[1, 0].set_xlabel('Residual')
    axLC[1, 0].set_ylabel('|J|')
    axLC[1, 1].scatter(Lcurve[:, 0], kappa)
    axLC[1, 1].set_xlabel('alpha')
    axLC[1, 1].set_ylabel('kappa')

    fig, ax = plt.subplots()
    ax.scatter(Lcurve[:, 1], Lcurve[:, 2])
    plt.xlabel('Residual')
    plt.ylabel('|J|')
    for i, txt in enumerate(Logalpha):
        ax.annotate(txt, (Lcurve[i, 1], Lcurve[i, 2]),
                    xytext=(5, 1),
                    textcoords='offset points')

    maxKappa = np.where(abs(kappa) == np.nanmax(abs(kappa)))[0]
    logalphaS = Lcurve[maxKappa[0], 0]

    logalpha = logalphaS, Lcurve

    return logalpha
Ejemplo n.º 7
0
    axes[ii].set_title(('MicroState %d' % ii))
    axes[ii].set_xticks([])
    axes[ii].set_yticks([])
plt.savefig('VGT130MicroStateTMaps.png')

##-----------------------------------------------------------------------------
from braink import read_lfm
from swcm import Imatrix

nE = nC - 1
K = read_lfm.lfm('/Users/jesong1126/Python27/data_GeoPy/108_HM/Leadfield.lfm',
                 nE)
nV = K.shape[1]

alpha = 0.001
Imat = Imatrix.MN(alpha, K)

sdenTmaps = np.zeros((nV, Tmaps.shape[1]))
for i in range(Tmaps.shape[1]):
    sdenTmaps[:, i] = np.dot(Imat, Tmaps[:, i])

import os

os.system("open /Applications/EAV/EAV.app")

from RabbitMQ import Connection

c = Connection.Connection('localhost')
c.connect()

i = 0
Ejemplo n.º 8
0
    def pbRunMicro_Callback(self):
        import numpy as np
        import config
        #        import configMicrostates
        from microstates import Kmeans
        import matplotlib.pyplot as plt
        plt.ion()
        from matplotlib import gridspec

        from pandas import DataFrame
        import pandas as pd
        gsn257 = pd.read_table(
            '/Users/jesong1126/Python27/PermuStat/microstates/GSN257ToPy2.dat')
        frame = DataFrame(gsn257,
                          columns=['ChLabel', 'X3', 'Y3', 'Z3', 'X2', 'Y2'])
        x2 = frame.values[:, 4]
        y2 = frame.values[:, 5]

        msSamples = config.msSamples
        s = config.s

        #---------------------------------------------------------------------
        catName = categoryName[config.CatVal]
        print('%s is selected' % catName)

        NumK = self.editNumCluster.text()
        NumK = int(NumK)

        SamplesMS = self.editSamplesMS.text()
        SamplesMS = int(SamplesMS)
        nSamplesPre = np.where(msSamples == SamplesMS)[0]

        SamplesMSto = self.editSamplesMSto.text()
        SamplesMSto = int(SamplesMSto)
        nSamplesPost = np.where(msSamples == SamplesMSto)[0]

        Threshold = self.editThreshold.text()
        Threshold = float(Threshold)

        NumSim = self.editNumSim.text()
        NumSim = int(NumSim)

        if config.nTrials > 1:
            X = s[:, :, config.CatVal]
        else:
            X = s
        GFP = np.std(X, axis=0)

        ##-----------------------------------------------------------------------------
        Data = X[:, nSamplesPre:nSamplesPost]
        nT = Data.shape[1]
        KmeansOut = Kmeans.Kmeans(Data, NumK, NumSim, Threshold)

        KmeanId = np.array(KmeansOut['KmeanId'], 'i4')
        KmeanId1 = np.array(KmeansOut['KmeanId1'], 'i4')
        KmeanId2 = np.array(KmeansOut['KmeanId2'], 'i4')
        Tmaps3 = KmeansOut['Tmaps3']
        KmeanId3 = np.array(KmeansOut['KmeanId3'], 'i4')

        Mycolorkeys = ('w', 'b', 'g', 'r', 'c', 'm', 'y', 'k', 'gray',
                       'purple', 'firebrick', 'darkgoldenrod', '#afeeee',
                       '#8EBA42', '#7A68A6', '#56B4E9', '#D55E00', 'b', 'g',
                       'r', 'c', 'm', 'y', 'k')
        KmeanColorId = []
        for i in range(nT):
            KmeanColorId.append(Mycolorkeys[KmeanId[i]])

        KmeanIdColorId1 = []
        for i in range(nT):
            KmeanIdColorId1.append(Mycolorkeys[KmeanId1[i]])

        KmeanIdColorId2 = []
        for i in range(nT):
            KmeanIdColorId2.append(Mycolorkeys[KmeanId2[i]])

        KmeanIdColorId3 = []  # [None] * nT
        for i in range(nT):
            KmeanIdColorId3.append(Mycolorkeys[KmeanId3[i]])

        startTP2 = np.zeros(NumK)
        for i in range(NumK):
            startTP2[i] = np.where(KmeanId2 == (i + 1))[0][0]
        startTP2 = np.array(startTP2, dtype='i')

        startTP3 = np.zeros(
            NumK)  # np.array ([np.arange(k+1), np.zeros(k+1)]).reshape(2, k+1)
        for i in range(NumK):
            startTP3[i] = np.where(KmeanId3 == (i + 1))[0][0]
        startTP3 = np.array(startTP3, dtype='i')

        plt.figure(figsize=(11.5, 8))
        gs = gridspec.GridSpec(6,
                               NumK,
                               height_ratios=[2, 1, 1, 1, 1, 2],
                               width_ratios=np.ones(NumK))
        ax0 = plt.subplot(gs[0, :])
        ax0.plot(msSamples, X.T)
        ax0.set_title('%s' % catName)
        ax0.set_xlim([msSamples[0], msSamples[-1]])
        ax1 = plt.subplot(gs[1, :])
        ax1.plot(msSamples, GFP, 'k')
        ax1.set_xlim([msSamples[0], msSamples[-1]])
        ax1.set_ylabel('Kmean')
        ax1.vlines(msSamples[nSamplesPre:nSamplesPost], [0],
                   GFP[nSamplesPre:nSamplesPost],
                   color=KmeanColorId)
        ax2 = plt.subplot(gs[2, :])
        ax2.plot(msSamples, GFP, 'k')
        ax2.set_xlim([msSamples[0], msSamples[-1]])
        ax2.set_ylabel('%d ' % Threshold)
        ax2.vlines(msSamples[nSamplesPre:nSamplesPost], [0],
                   GFP[nSamplesPre:nSamplesPost],
                   color=KmeanIdColorId1)
        ax3 = plt.subplot(gs[3, :])
        ax3.plot(msSamples, GFP, 'k')
        ax3.set_xlim([msSamples[0], msSamples[-1]])
        ax3.set_ylabel('Continuous')
        ax3.vlines(msSamples[nSamplesPre:nSamplesPost], [0],
                   GFP[nSamplesPre:nSamplesPost],
                   color=KmeanIdColorId2)
        for i in range(NumK):
            ax3.text(msSamples[nSamplesPre + (startTP2[i])],
                     GFP[nSamplesPre + (startTP2[i])] + 0.1, ('%d' % (i + 1)),
                     fontsize=15)
        ax4 = plt.subplot(gs[4, :])
        ax4.plot(msSamples, GFP, 'k')
        ax4.set_xlim([msSamples[0], msSamples[-1]])
        ax4.set_ylabel('Rename')
        ax4.vlines(msSamples[nSamplesPre:nSamplesPost], [0],
                   GFP[nSamplesPre:nSamplesPost],
                   color=KmeanIdColorId3)  #, alpha= 0.2)
        for i in range(NumK):
            ax4.text(msSamples[nSamplesPre + (startTP3[i])],
                     GFP[nSamplesPre + (startTP3[i])] + 0.1, ('%d' % (i + 1)),
                     fontsize=15)
        for ii in range(NumK):
            axes = plt.subplot(gs[5, ii])
            axes.scatter(x2,
                         y2,
                         c=Tmaps3[:, ii],
                         s=30,
                         cmap=plt.get_cmap('seismic'),
                         alpha=.5)
            axes.set_alpha(0.75)
            axes.set_xlabel(('MicroState %d' % (ii + 1)))
            axes.set_xticks([])
            axes.set_yticks([])
        plt.show()

        from swcm import Imatrix  #, Lcurve
        import numpy as np
        MethodVal = config.MethodVal
        K = config.K
        nV = K.shape[1]

        #        logalpha = Lcurve.MN(Tmaps3[:,0], K)
        #        poweralpha = logalpha[0]
        #        alpha = pow(10, poweralpha)
        #        print("from Lcurve alpha=%3.2e" %alpha)

        alpha = 0.001

        if MethodVal == 0:
            Imat = Imatrix.MN(alpha, K)
        elif MethodVal == 1:
            Imat = Imatrix.sMN(alpha, K)
        else:
            print("Inverse Method is not selected. ")

        sdenTmaps = np.zeros((nV, NumK))
        for i in range(NumK):
            sdenTmaps[:, i] = np.dot(Imat, Tmaps3[:, i])

        config.Tmaps = Tmaps3
        config.sdenTmaps = sdenTmaps