Пример #1
0
    def test_ward_spatial_scikit_with_mask(self):
        from pyhrf.parcellation import parcellation_dist, parcellation_ward_spatial
        from pyhrf.graph import graph_from_lattice, kerMask2D_4n
        from pyhrf.ndarray import expand_array_in_mask

        if debug:
            print 'data:'
            print self.p1
            print ''

        mask = self.p1 != 0
        graph = graph_from_lattice(mask, kerMask2D_4n)

        X = self.p1[np.where(mask)].reshape(-1,1)

        labels = parcellation_ward_spatial(X, n_clusters=4, graph=graph)

        labels = expand_array_in_mask(labels, mask)



        # print 'labels:'
        # print labels

        #+1 because parcellation_dist sees 0 as background:
        dist = parcellation_dist(self.p1+1, labels+1)[0]
        self.assertEqual(dist, 0)
Пример #2
0
def create_3Dlabels_Potts(condition_defs, beta, dims, mask):
    labels = []
    graph = graph_from_lattice(mask, kerMask=kerMask3D_6n, toroidal=True)
    for c in condition_defs:
        tmp = genPotts(graph, beta, 2)
        tmp = np.reshape(tmp, dims)
        labels.append(tmp)
    return np.array(labels)
Пример #3
0
def create_3Dlabels_Potts(condition_defs, beta, dims, mask):
    labels = []
    graph = graph_from_lattice(mask, kerMask=kerMask3D_6n, toroidal=True)
    for c in condition_defs:
        tmp = genPotts(graph, beta, 2)
        tmp = np.reshape(tmp, dims)
        labels.append(tmp)
    return np.array(labels)
Пример #4
0
    def test_split_parcel(self):
        shape = (5, 5, 5)
        mask = np.zeros(shape, dtype=int)
        mask[1:-1, 1:-1, 1:-1] = 1
        mask_labels = mask[np.where(mask)]
        g = graph_from_lattice(mask, kerMask3D_6n)

        nparcels = 2
        pm.split_parcel(mask_labels, {1: g}, 1, nparcels, inplace=True,
                        verbosity=0)
Пример #5
0
def create_labels_Potts(condition_defs, beta, nb_voxels):
    labels = []
    nb_voxels = nb_voxels**.5  # assume square shape
    shape = (nb_voxels, nb_voxels)
    mask = np.ones(shape, dtype=int)
    graph = graph_from_lattice(mask, kerMask=kerMask2D_4n, toroidal=True)
    shape = (1, nb_voxels, nb_voxels)
    for c in condition_defs:
        tmp = genPotts(graph, beta, 2)
        tmp = np.reshape(tmp, shape)
        labels.append(tmp)
    return np.array(labels)
Пример #6
0
def create_labels_Potts(condition_defs, beta, nb_voxels):
    labels = []
    nb_voxels = nb_voxels ** 0.5  # assume square shape
    shape = (nb_voxels, nb_voxels)
    mask = np.ones(shape, dtype=int)
    graph = graph_from_lattice(mask, kerMask=kerMask2D_4n, toroidal=True)
    shape = (1, nb_voxels, nb_voxels)
    for c in condition_defs:
        tmp = genPotts(graph, beta, 2)
        tmp = np.reshape(tmp, shape)
        labels.append(tmp)
    return np.array(labels)
Пример #7
0
    def test_ward_spatial_scikit(self):
        from pyhrf.parcellation import parcellation_dist, \
            parcellation_ward_spatial
        from pyhrf.graph import graph_from_lattice, kerMask2D_4n

        X = np.reshape(self.p1, (-1, 1))
        graph = graph_from_lattice(np.ones(self.p1.shape), kerMask2D_4n)

        labels = parcellation_ward_spatial(X, n_clusters=5, graph=graph)

        labels = np.reshape(labels, self.p1.shape)
        # +1 because parcellation_dist sees 0 as background
        dist = parcellation_dist(self.p1 + 1, labels + 1)[0]
        self.assertEqual(dist, 0)
Пример #8
0
def parcellate_balanced_vol(mask, nb_parcels):
    """
    Performs a balanced partitioning on the input mask using a balloon patroling
     algorithm [Eurol 2009]. Values with 0 are discarded position in the mask.

    Args:
        - mask (numpy.ndarray): binary 3D array of valid position to parcellate
        - nb_parcels (int): the required number of parcels

    Return:
        - the parcellation (numpy.ndarray): a 3D array of integers
    """

    parcellation = np.zeros(mask.shape, dtype=int)
    nvox = (mask != 0).sum()

    # Iterate over connected components in the input mask
    for cc_mask in mg.split_mask_into_cc_iter(mask != 0):
        logger.info('Treating a connected component (CC) of %d positions',
                    cc_mask.sum())
        g = mg.graph_from_lattice(cc_mask)
        size_cc = cc_mask.sum()
        # compute the required number of parcels within the current CC:
        cc_np = max(int(np.round(nb_parcels * size_cc / (nvox * 1.))), 1)

        logger.info('Split (CC) into %d parcels', cc_np)

        cc_labels = np.ones(cc_mask.sum(), dtype=int)
        if cc_np > 1:
            split_parcel(cc_labels, {1: g},
                         1,
                         cc_np,
                         inplace=True,
                         verbosity=2,
                         balance_tolerance='draft')
        else:  # only one parcel expected, CC must be too small to be splited
            cc_labels[:] = 1
        logger.info('Split done!')

        # accumulate parcellation result
        maxp = parcellation.max()
        parcellation += expand_array_in_mask(cc_labels + maxp, cc_mask > 0)

    return parcellation
Пример #9
0
    def test_ward_spatial_scikit_with_mask(self):
        from pyhrf.parcellation import parcellation_dist, parcellation_ward_spatial
        from pyhrf.graph import graph_from_lattice, kerMask2D_4n
        from pyhrf.ndarray import expand_array_in_mask

        if debug:
            print 'data:'
            print self.p1
            print ''

        mask = self.p1 != 0
        graph = graph_from_lattice(mask, kerMask2D_4n)

        X = self.p1[np.where(mask)].reshape(-1, 1)

        labels = parcellation_ward_spatial(X, n_clusters=4, graph=graph)

        labels = expand_array_in_mask(labels, mask)
        #+1 because parcellation_dist sees 0 as background:
        dist = parcellation_dist(self.p1 + 1, labels + 1)[0]
        self.assertEqual(dist, 0)
Пример #10
0
def parcellate_balanced_vol(mask, nb_parcels):
    """
    Performs a balanced partitioning on the input mask using a balloon patroling
     algorithm [Eurol 2009]. Values with 0 are discarded position in the mask.

    Args:
        - mask (numpy.ndarray): binary 3D array of valid position to parcellate
        - nb_parcels (int): the required number of parcels

    Return:
        - the parcellation (numpy.ndarray): a 3D array of integers
    """

    parcellation = np.zeros(mask.shape, dtype=int)
    nvox = (mask != 0).sum()

    # Iterate over connected components in the input mask
    for cc_mask in mg.split_mask_into_cc_iter(mask != 0):
        pyhrf.verbose(2, 'Treating a connected component (CC) of %d positions' \
                          %cc_mask.sum())
        g = mg.graph_from_lattice(cc_mask)
        size_cc = cc_mask.sum()
        # compute the required number of parcels within the current CC:
        cc_np = max(int(np.round(nb_parcels * size_cc / (nvox*1.))), 1)

        pyhrf.verbose(2, 'Split (CC) into %d parcels' %cc_np)

        cc_labels = np.ones(cc_mask.sum(), dtype=int)
        if cc_np > 1:
            split_parcel(cc_labels, {1:g}, 1, cc_np, inplace=True,
                         verbosity=2, balance_tolerance='draft')
        else: #only one parcel expected, CC must be too small to be splited
            cc_labels[:] = 1
        pyhrf.verbose(2, 'Split done!')

        # accumulate parcellation result
        maxp = parcellation.max()
        parcellation += expand_array_in_mask(cc_labels + maxp, cc_mask>0)

    return parcellation
 def trait(self):    
     areas = ['ra']
     labelFields = {}
     cNames = ['inactiv', 'activ']
     height = self.data.getheight()
     width = self.data.getwidth()
     spConf = RegularLatticeMapping((height, width, 1))
     graph = graph_from_lattice(ones((height, width, 1), dtype=int))
     Y = self.data.post_lecture()
     J = Y.shape[0]
     l = int(sqrt(J))
     FlagZ = 1
     q_Z0 = zeros((self.scen.M, self.scen.K, J), dtype=float64)
     if not FlagZ:
         q_Z0 = q_Z
     FlagH = 1
     TT, m_h = getCanoHRF(self.scen.Thrf - self.scen.dt, self.scen.dt)
     hrf0 = hrf0 = array(m_h).astype(float64)
     Sigma_H0 = eye(hrf0.shape[0])
     if not FlagH:
         hrf0 = h_H
         Sigma_H0 = Sigma_H
     return Y, graph, hrf0, Sigma_H0, q_Z0, width, height, FlagZ, FlagH
Пример #12
0
    def gen_hrf(self,
                nItMin=30,
                nItMax=30,
                estimateSigmaH=0,
                estimateBeta=0,
                Onsets={'nuages': array([0])},
                scale=1,
                ):
        """
        allow to generate figures	

        :param nItMin: Minimum number of iteration
        :type nItMin: int
        :param nItMax: Maximum number of iteration
        :type nItMax: int 
        :param estimateSigmaH: estimation of sigmaH
        :type estimateSigmaH: int
        :param estimateBeta: estimation of Beta
        :type estimateBeta: int   
        :param scale: scale factor
        :type scale: int
        """
        # estimationSigmah = 0 sans estimation de sigmh , estimationSigmah=1 estimation de sigmah
        # estimateBeta = 0 sans estimation de beta , estimateBeta=1 estimation de beta
        # construction Onsets
        # Onsets = {'nuages' : array([1,6,7])}
        areas = ['ra']
        labelFields = {}
        cNames = ['inactiv', 'activ']
        spConf = RegularLatticeMapping((self.height, self.width, 1))
        graph = graph_from_lattice(
            ones((self.height, self.width, 1), dtype=int))
        J = self.Y.shape[0]
        l = int(sqrt(J))

        # NbIter, nrls_mean, hrf_mean, hrf_covar, labels_proba, noise_var, \
        # nrls_class_mean, nrls_class_var, beta, drift_coeffs, drift,CONTRAST, CONTRASTVAR, \
        # nrls_criteria, hrf_criteria,labels_criteria, nrls_hrf_criteria, compute_time,compute_time_mean, \
        # nrls_covar, stimulus_induced_signal, density_ratio,density_ratio_cano, density_ratio_diff, density_ratio_prod, \
        # ppm_a_nrl,ppm_g_nrl, ppm_a_contrasts, ppm_g_contrasts, variation_coeff = \
        # jde_vem_bold_fast_python(pl,graph, Y, Onsets, Thrf, K,TR, beta, dt, estimateSigmaH, sigmaH,nItMax,nItMin,estimateBeta)
        # FlagZ = 1
        # q_Z = zeros((M,K,J),dtype=float64)
        # NbIter,m_A, m_H, q_Z, sigma_epsilone, mu_k, sigma_k,Beta,L,PL,CONTRAST, CONTRASTVAR,cA,cH,cZ,cAH,cTime,cTimeMean,Sigma_A,XX = \
        # Main_vbjde_Extension_TD(height,width,q_Z,FlagZ,pl,graph,Y,Onsets,Thrf,K,TR,beta,dt,scale,estimateSigmaH,sigmaH,nItMax,nItMin,estimateBeta)

        # facteur = 1.0
        # Y,height,width,bande = lecture_data(dataDir,2660,2730,2600,2680,bande,start,facteur,end)
        # FlagZ = 0
        # NbIter_f,m_A_f, m_H_f, q_Z_f, sigma_epsilone_f, mu_k_f, sigma_k_f,Beta_f,L_f,PL,CONTRAST, CONTRASTVAR,cA,cH,cZ,cAH,cTime,cTimeMean,Sigma_A,XX = \
        # Main_vbjde_Extension_TD(height,width,q_Z,FlagZ,pl,graph,Y,Onsets,Thrf,K,TR,beta,dt,scale,estimateSigmaH,sigmaH,nItMax,nItMin,estimateBeta)

        # ytild=PL
        # matshow(reshape(m_A_f[:,0],(height,width)) - reshape(m_A[:,0],(height,width)),cmap=get_cmap('gray'))
        # colorbar()

        FlagZ = 1
        q_Z0 = zeros((self.M, self.K, J), dtype=float64)
        if not FlagZ:
            q_Z0 = q_Z
        FlagH = 1
        TT, m_h = getCanoHRF(self.Thrf - self.dt, self.dt)
        hrf0 = array(m_h).astype(float64)
        Sigma_H0 = eye(hrf0.shape[0])
        if not FlagH:
            hrf0 = h_H
            Sigma_H0 = Sigma_H

        self.m_A, self.m_H, self.q_Z, sigma_epsilone, mu_k, sigma_k, Beta, PL, Sigma_A, XX, Sigma_H = \
            Main_vbjde_Extension_TD(
                FlagH, hrf0, Sigma_H0, self.height, self.width, q_Z0, FlagZ,
                self.pl, graph, self.Y, Onsets, self.Thrf, self.K, self.TR,
                self.beta, self.dt, scale,
                estimateSigmaH, self.sigmaH, nItMin, estimateBeta)

        fgs = self.ConditionalNRLHist(self.m_A, self.q_Z)

        MMin = -1.0  # Y.min()
        MMax = 1.0  # Y.max()
        pas = (MMax - MMin) / 100
        xx = arange(MMin, MMax, pas)
        g0 = self.gaussian(xx, mu_k[0][0], sigma_k[0][0])
        g1 = self.gaussian(xx, mu_k[0][1], sigma_k[0][1])
        #
        # figure(77)
        # plot(xx,g0*pas, label='m=%.2f;v=%.2f' % (mu_k[0][0],sigma_k[0][0]))
        # hold(True)
        # plot(xx,g1*pas, label='m=%.2f;v=%.2f' % (mu_k[0][1],sigma_k[0][1]))
        # legend()

        # savgarde des PLs #
        # if ((pl != 0 )and (savepl !=0 )) :
        #   for i in range (0,ytild.shape[0]) :
        #       figure(nf)
        #       PL_img =reshape(ytild[i,:],(height,width))
        #       matshow(PL_img,cmap=get_cmap('gray'))
        #       colorbar()
        #       nf=nf+1
        #       savefig(outDir+'PL'+str(i)+'bande=' +str(bande)+'.png')

        # savefig(outDir+'PL'+str(i)+'bande=' +str(bande)+'beta='+str(beta)+'sigma='+str(sigmaH)+'pl='+str(pl)+'dt='+str(dt)+'thrf'+str(Thrf)+'.png')
        #
        # figure Hrf #######
        fgs.insert(0, figure((self.nf + 1) * 123))
        title("Fonction de reponse", fontsize='xx-large')
        figtext(0.2, 0.04,
                'bande = ' + str(self.bande) +
                ' beta =' + str(self.beta) +
                ' sigma = ' + str(self.sigmaH) +
                ' pl = ' + str(self.pl) +
                ' dt = ' + str(self.dt) +
                ' thrf = ' + str(self.Thrf),
                fontsize='x-large')
        plot(self.m_H)
        if self.shower == 1:
            show()
        return fgs
Пример #13
0
    def gen_hrf(
        self,
        nItMin=30,
        nItMax=30,
        estimateSigmaH=0,
        estimateBeta=0,
        Onsets={'nuages': array([0])},
        scale=1,
    ):
        """
        allow to generate figures

        :param nItMin: Minimum number of iteration
        :type nItMin: int
        :param nItMax: Maximum number of iteration
        :type nItMax: int
        :param estimateSigmaH: estimation of sigmaH
        :type estimateSigmaH: int
        :param estimateBeta: estimation of Beta
        :type estimateBeta: int
        :param scale: scale factor
        :type scale: int
        """
        # estimationSigmah = 0 sans estimation de sigmh , estimationSigmah=1 estimation de sigmah
        # estimateBeta = 0 sans estimation de beta , estimateBeta=1 estimation de beta
        # construction Onsets
        # Onsets = {'nuages' : array([1,6,7])}
        areas = ['ra']
        labelFields = {}
        cNames = ['inactiv', 'activ']
        spConf = RegularLatticeMapping((self.height, self.width, 1))
        graph = graph_from_lattice(
            ones((self.height, self.width, 1), dtype=int))
        J = self.Y.shape[0]
        l = int(sqrt(J))

        # NbIter, nrls_mean, hrf_mean, hrf_covar, labels_proba, noise_var, \
        # nrls_class_mean, nrls_class_var, beta, drift_coeffs, drift,CONTRAST, CONTRASTVAR, \
        # nrls_criteria, hrf_criteria,labels_criteria, nrls_hrf_criteria, compute_time,compute_time_mean, \
        # nrls_covar, stimulus_induced_signal, density_ratio,density_ratio_cano, density_ratio_diff, density_ratio_prod, \
        # ppm_a_nrl,ppm_g_nrl, ppm_a_contrasts, ppm_g_contrasts, variation_coeff = \
        # jde_vem_bold_fast_python(pl,graph, Y, Onsets, Thrf, K,TR, beta, dt, estimateSigmaH, sigmaH,nItMax,nItMin,estimateBeta)
        # FlagZ = 1
        # q_Z = zeros((M,K,J),dtype=float64)
        # NbIter,m_A, m_H, q_Z, sigma_epsilone, mu_k, sigma_k,Beta,L,PL,CONTRAST, CONTRASTVAR,cA,cH,cZ,cAH,cTime,cTimeMean,Sigma_A,XX = \
        # Main_vbjde_Extension_TD(height,width,q_Z,FlagZ,pl,graph,Y,Onsets,Thrf,K,TR,beta,dt,scale,estimateSigmaH,sigmaH,nItMax,nItMin,estimateBeta)

        # facteur = 1.0
        # Y,height,width,bande = lecture_data(dataDir,2660,2730,2600,2680,bande,start,facteur,end)
        # FlagZ = 0
        # NbIter_f,m_A_f, m_H_f, q_Z_f, sigma_epsilone_f, mu_k_f, sigma_k_f,Beta_f,L_f,PL,CONTRAST, CONTRASTVAR,cA,cH,cZ,cAH,cTime,cTimeMean,Sigma_A,XX = \
        # Main_vbjde_Extension_TD(height,width,q_Z,FlagZ,pl,graph,Y,Onsets,Thrf,K,TR,beta,dt,scale,estimateSigmaH,sigmaH,nItMax,nItMin,estimateBeta)

        # ytild=PL
        # matshow(reshape(m_A_f[:,0],(height,width)) - reshape(m_A[:,0],(height,width)),cmap=get_cmap('gray'))
        # colorbar()

        FlagZ = 1
        q_Z0 = zeros((self.M, self.K, J), dtype=float64)
        if not FlagZ:
            q_Z0 = q_Z
        FlagH = 1
        TT, m_h = getCanoHRF(self.Thrf - self.dt, self.dt)
        self.hrf0 = hrf0 = array(m_h).astype(float64)
        Sigma_H0 = eye(hrf0.shape[0])
        if not FlagH:
            hrf0 = h_H
            Sigma_H0 = Sigma_H

        self.m_A, self.m_H, self.q_Z, sigma_epsilone, mu_k, sigma_k, Beta, PL, Sigma_A, XX, Sigma_H = \
            Main_vbjde_Extension_TD(
                FlagH, hrf0, Sigma_H0, self.height, self.width, q_Z0, FlagZ,
                self.pl, graph, self.Y, Onsets, self.Thrf, self.K, self.TR,
                self.beta, self.dt, scale,
                estimateSigmaH, self.sigmaH, nItMin, estimateBeta)

        fgs = self.ConditionalNRLHist(self.m_A, self.q_Z)

        MMin = -1.0  # Y.min()
        MMax = 1.0  # Y.max()
        pas = (MMax - MMin) / 100
        xx = arange(MMin, MMax, pas)
        g0 = self.gaussian(xx, mu_k[0][0], sigma_k[0][0])
        g1 = self.gaussian(xx, mu_k[0][1], sigma_k[0][1])
        #
        # figure(77)
        # plot(xx,g0*pas, label='m=%.2f;v=%.2f' % (mu_k[0][0],sigma_k[0][0]))
        # hold(True)
        # plot(xx,g1*pas, label='m=%.2f;v=%.2f' % (mu_k[0][1],sigma_k[0][1]))
        # legend()

        # savgarde des PLs #
        # if ((pl != 0 )and (savepl !=0 )) :
        #   for i in range (0,ytild.shape[0]) :
        #       figure(nf)
        #       PL_img =reshape(ytild[i,:],(height,width))
        #       matshow(PL_img,cmap=get_cmap('gray'))
        #       colorbar()
        #       nf=nf+1
        #       savefig(outDir+'PL'+str(i)+'bande=' +str(bande)+'.png')

        # savefig(outDir+'PL'+str(i)+'bande=' +str(bande)+'beta='+str(beta)+'sigma='+str(sigmaH)+'pl='+str(pl)+'dt='+str(dt)+'thrf'+str(Thrf)+'.png')
        #
        # figure Hrf #######
        fgs.insert(0, figure((self.nf + 1) * 123))
        title("Fonction de reponse", fontsize='xx-large')
        figtext(0.2,
                0.04,
                'bande = ' + str(self.bande) + ' beta =' + str(self.beta) +
                ' sigma = ' + str(self.sigmaH) + ' pl = ' + str(self.pl) +
                ' dt = ' + str(self.dt) + ' thrf = ' + str(self.Thrf),
                fontsize='x-large')
        plot(self.m_H)
        if self.shower == 1:
            show()
        return fgs