Ejemplo n.º 1
0
    def UpdatePlot(self, CFL, schemaSolver, nbrIter, traceLongueur,
                   traceEspacement):
        self.ax.cla()
        tailleDomaine = 1000
        if traceLongueur == 1:
            iterationTrace = [nbrIter]
        else:
            iterationTrace = [
                int(nbrIter * (traceEspacement / 100) + nbrIter *
                    ((100 - traceEspacement) / 100) * (i /
                                                       (traceLongueur - 1)))
                for i in range(traceLongueur)
            ]
        listSol, pos, duree = Solvers.Get_Multiple_Solution(
            schemaSolver(CFL, tailleDomaine), iterationTrace)

        for i in range(len(listSol) - 1):
            a = i / len(listSol)
            self.ax.plot(pos, listSol[i], 'k-', linewidth=1.0, alpha=a / 2.0)
        self.ax.plot(pos,
                     listSol[len(listSol) - 1],
                     'k-',
                     linewidth=2,
                     alpha=1.0)

        self.ax.set_title(
            r"$ \frac{\partial \Phi}{\partial t} + a \ \frac{\partial \Phi}{\partial x}$  %s  $a = 2 m.s^{-1}$  %s $ x \in [0,1] $  %s %s s"
            % ("\t", "\t", "\t", str(duree)),
            fontsize=20)
        self.draw()
Ejemplo n.º 2
0
    def solve(self):
        '''
        Method that solves the linear equations system.
        
        Param:
            -
        Return:
            -
        '''
        G = self.__matrix.getMatrix()
        f = self.__matrix.getfv()

        if self.__algorithm == 'linalg':
            self.__lam = np.linalg.solve(G, f)
        elif self.__algorithm == 'jacobi':
            self.__lam, self.__err, self.__k, self.__errv = sol.jacobi(
                G, f, self.__tol, self.__max_iter, self.__test)
        elif self.__algorithm == 'gs':
            self.__lam, self.__err, self.__k, self.__errv = sol.gauss_seidel(
                G, f, self.__tol, self.__max_iter, self.__test)
        elif self.__algorithm == 'sor':
            self.__lam, self.__err, self.__k, self.__errv = sol.sor(
                G, f, self.__tol, self.__max_iter, 1.5, self.__test)
        elif self.__algorithm == 'cgm':
            b = np.matrix(f.copy())
            self.__lam, self.__err, self.__k, self.__errv = sol.cgm(
                G, b.T, b.T, self.__tol, self.__max_iter, self.__test)
        elif self.__algorithm == 'bicgstab':
            b = np.matrix(f.copy())
            self.__lam, self.__err, self.__k, self.__errv = sol.bicgstab(
                G, b.T, b.T, self.__tol, self.__max_iter, self.__test)
        elif self.__algorithm == 'gmres':
            b = np.matrix(f.copy())
            self.__lam, self.__err, self.__k, self.__errv = sol.gmres(
                G, b.T, b.T, self.__tol, self.__max_iter, 15, self.__test)
Ejemplo n.º 3
0
axis_x = discret_X((marg, k), ((Bz, k), (Bp, k)), True, Q)
axis_y = discret_Y(((marg, k), (Hy, k), (Hp, k), (dz, k), (0.05, k)))

data = body_grid(axis_x, axis_y, Body.bodies)

from PhysicsMF import MagneticField
a = MagneticField(data, omega=314)

r, mmf_bc_right, mmf_bc_left, mmf_bc_up, mmf_bc_down = a.set_matrix_complex_2()
mmf = a.mmf(mmf_bc_right, mmf_bc_left, mmf_bc_up, mmf_bc_down)
#r = a.test_fun()
"""The part of the program is to run simulation"""

import Solvers as sol

solution = sol.solve_it_ling(r, mmf)

solution_2 = sol.solve_it(r, mmf)
"""The part of the program is to present the results"""

from PostProcessing import PostProcessing

pp_class = PostProcessing(solution, a)
pp_class_2 = PostProcessing(solution_2, a)
reshape_sol = pp_class.reshape_data(solution)
reshape_sol_2 = pp_class.reshape_data(solution_2)
reshape_mmf = pp_class.reshape_data(mmf)

magnetic_flux_x = pp_class.calculate_magnetic_flux_x(reshape_sol)
magnetic_flux_y = pp_class.calculate_magnetic_flux_y(reshape_sol)
magnetic_flux_x_2 = pp_class.calculate_magnetic_flux_x(reshape_sol_2)
Ejemplo n.º 4
0
QP_homo_P = dict()

U_true_set = dict()
for each in range(num_problem):
    Z_true = 1 + np.array([random.expovariate(1) for rand in range(M)])
    U_true = np.random.rand(K, N)
    X_clean = np.diag(Z_true).dot(S).dot(U_true)
    X = X_clean + (X_clean * sigma_n) * np.array(mtl.randn(M, N))

    U_true_set[str(each)] = U_true
    prot_sub = dict()
    prot_sub['S'] = S
    prot_sub['X'] = X
    hf.null_sp_dim(prot_sub)
    # SVD sovler
    SVD_solution = Solvers.SVD(prot_sub)
    SVD_protein, SVD_opt = SVD_solution
    SVD_homo_P[str(each)] = SVD_protein

    # QP solver
    QP_solution = Solvers.QP(prot_sub)
    QP_protein, QP_opt = QP_solution
    QP_homo_P[str(each)] = QP_protein

    # CD sovler
    CD_solution = Solvers.CD(prot_sub, 1000)
    CD_protein, CD_opt = CD_solution
    CD_homo_P[str(each)] = CD_protein

# I should test the correlation between U_true and U_hat
P_CD = np.array(
Ejemplo n.º 5
0
#----------------------------------------------------------------------------------------
if Nxy < 50:
#----------------------------------------------------------------------------------------
                               #Gram matrix solution Linalg
#----------------------------------------------------------------------------------------
    t1 = time.clock()
    ut = np.linalg.solve(As,bs)
    t2 = time.clock()
    te = t2 - t1
    fdm.plotSolution(ut,Nxy,Nxy,'linalg.solve({})'.format(0),'E. time : {:>3.5e}'.format(te),T1,T2,T3,T4)

#----------------------------------------------------------------------------------------
                               #Gram matrix solution Jacobi
#----------------------------------------------------------------------------------------
    t1 = time.clock()
    ut,error,it, eaJ = sol.jacobi(Aj,bj,tol,max_iter,True)
    t2 = time.clock()
    te = t2 - t1
    fdm.plotSolution(ut,Nxy,Nxy,'Jacobi ({:>8.5e} - {})'.format(error, it),'E. time : {:>3.5e}'.format(te),T1,T2,T3,T4)

#----------------------------------------------------------------------------------------
                               #Gram matrix solution Gauss-Seidel
#----------------------------------------------------------------------------------------
    t1 = time.clock()
    ut,error,it, eaGS = sol.gauss_seidel(Ags,bgs,tol,max_iter,True)
    t2 = time.clock()
    te = t2 - t1
    fdm.plotSolution(ut,Nxy,Nxy,'Gauss Seidel ({:>8.5e} - {})'.format(error, it),'E. time : {:>3.5e}'.format(te),T1,T2,T3,T4)

#----------------------------------------------------------------------------------------
                               #Gram matrix solution SOR
Ejemplo n.º 6
0
def P_inferred_expand_gen(prot_sub_noise_set, level_noise_Number, solver):
    # global each
    # each of following is list of array for each CC
    P = [prot_sub_noise_set[i]['P']
         for i in range(level_noise_Number)]  # same for all noise
    Z_true = [prot_sub_noise_set[i]['Z']
              for i in range(level_noise_Number)]  # same for all noise
    S = [prot_sub_noise_set[i]['S']
         for i in range(level_noise_Number)]  # same for all noise
    X = [prot_sub_noise_set[i]['X']
         for i in range(level_noise_Number)]  # different for each noise

    # U_hat = np.zeros(P[0].shape)
    P_all = dict()
    # R2_expand = dict()
    # P_all = np.array([])
    R2_expand = np.array([])
    overall_error_expand = np.array([])
    Median_ratio_expand = np.array([])
    Corr_expand = np.array([])
    Xi = np.array([])
    CV_mean = np.array([])
    CV_min = np.array([])
    CV_max = np.array([])
    X_corr_mean = np.array([])
    lst_sp_expand = np.array([])
    Neg_fract_expand = np.array([])

    for r in range(level_noise_Number):
        # print(' the {} noise level'.format(r))
        prot_sub = prot_sub_noise_set[r]
        if solver == 'QP':
            QP_solution = Solvers.QP(prot_sub)
            protein_inferred, opt = QP_solution

        elif solver == 'CD':
            CD_solution = Solvers.CD(prot_sub, 1000)
            protein_inferred, opt = CD_solution

        elif solver == 'SVD':
            SVD_solution = Solvers.SVD(prot_sub)
            protein_inferred, opt = SVD_solution

        alpha_SC = np.median(
            np.diag(Z_true[0]) / np.diag(opt['Z'])
        )  # rescale to match it closely (unidentifiable up-to-const)
        U_hat = protein_inferred
        U_hat = U_hat * (1 / alpha_SC)

        # -----Calculate Feature associated with each U_hat-----
        # 1) R^2
        rsq = opt['rsq']
        R2_expand = np.append(R2_expand, rsq)
        # R2_expand[str(r)] = rsq
        # R2_expand_t.append(rsq)

        # 2) Overall Error (♌ some of the element in U is zero which end up with divide by zeros element)
        rescale = np.median(np.concatenate(P[r]) / np.concatenate(U_hat))
        P_scaled = U_hat * rescale
        overall_error = np.median(np.abs(P_scaled - P[r]) / P[r])
        overall_error_expand = np.append(overall_error_expand, overall_error)
        # 3) Ratio Error
        #3.1 all possible combinations of rows of P
        combo = list(combinations(list(range(P[r].shape[0])), 2))
        ratio_set = np.array([])
        for pair in combo:
            row1, row2 = pair
            R_old = P[r][row1, :] / P[r][row2, :]
            R_new = U_hat[row1, :] / U_hat[row2, :]
            R_i = (R_new - R_old) / R_old
            ratio = np.median(np.abs(R_i))
            ratio_set = np.append(ratio_set, ratio)
        Median_ratio_i = np.median(ratio_set)
        Median_ratio_expand = np.append(Median_ratio_expand, Median_ratio_i)
        # print('The {} noise level has {} ratio set '.format(r, ratio_set))
        # 4) correlation (U_hat, P)
        Corr_P_P_true = np.corrcoef(np.concatenate(P[r]),
                                    np.concatenate(U_hat))[1][0]
        Corr_expand = np.append(Corr_expand, Corr_P_P_true)

        # 5) Xi
        P_relative_norm_temp = np.std(prot_sub['X'], axis=1) / np.mean(
            prot_sub['X'], axis=1)
        P_relative_norm = np.nanmean(P_relative_norm_temp)
        Xi = np.append(Xi, P_relative_norm)

        # 6) CV score for each simulated P
        cv_mean_i = cv_score(U_hat, 'mean')
        cv_max_i = cv_score(U_hat, 'max')
        cv_min_i = cv_score(U_hat, 'min')
        CV_mean = np.append(CV_mean, cv_mean_i)
        CV_max = np.append(CV_max, cv_max_i)
        CV_min = np.append(CV_min, cv_min_i)
        # 7) The mean correlation between the rows of X as a measure of linear independence between the the columns of X
        X_corr = np.corrcoef(prot_sub['X'].T)
        X_corr_modi = X_corr - np.eye(
            X_corr.shape[0]
        )  # the diagnal of X_corr shows 1, but when subtract by np.eye, the result shows a close to zeros Number
        X_corr_mean_i = mean_squareform(X_corr_modi)
        X_corr_mean = np.append(X_corr_mean, X_corr_mean_i)

        # 8) last eigen_spacing
        _, opt_eigen = Solvers.SVD(prot_sub)
        lst_sp_expand = np.append(lst_sp_expand, opt_eigen['eigen_spacing'])

        # 9) calculate the fraction of negative elements in the smallest singular vector of A, when v1 = median(sign(v1))v1
        vi = opt_eigen['V']
        vi = np.median(np.sign(vi)) * vi
        Neg_fract_i = np.sum(vi < 0) / len(vi)
        Neg_fract_expand = np.append(Neg_fract_expand, Neg_fract_i)

        # make P_inferred dictionary for the noise set.
        P_all[str(r)] = U_hat
        # P_all = np.append(P_all, U_hat)

    # Constructing the expanded feature Matrix
    feature_expand = np.array((R2_expand, Neg_fract_expand, Xi, CV_mean,
                               CV_max, CV_min, X_corr_mean, lst_sp_expand)).T
    return P_all, feature_expand, overall_error_expand, Median_ratio_expand, Corr_expand
Ejemplo n.º 7
0
 def ShowRangeCFL(self):
     self.UpdateParameters()
     Solvers.Show_MaxCFL(self.schemaSolver)