Example #1
0
def plot_accuracy(ref=1, save=False):
    name = 'accuracy'
    params = ((0, 0), (0, 50), (50, 0), (50, 50))
    regimes = ['Statique', 'Stationnaire', 'Harmonique', 'Dynamique']
    solvers = ['LU', 'QR', 'Numpy']
    plots_id = []
    plt.Figure(figsize=(20, 20))
    plt.title('Précision')
    plt.xlabel('Régime')
    # plt.yscale('log')
    plt.ylabel('Précision')
    plt.ylim(bottom=10e-16, top=2.8 * 10e-15)
    for s in range(len(solvers)):
        acc = []
        for param in params:
            setVariables(ref=ref, vel=param[0], freq=param[1])
            setSolver(solvers[s])
            ndt.main(show=False, test=False, solver=True)
            b = ndt.b
            A = np.array(ndt.A)
            num = np.linalg.norm(A @ ndt.x - b)
            den = np.linalg.norm(b)
            acc.append((num / den))
            print("\n\nWOUHOU : %s : %.15f\n\n" % (solvers[s],
                                                   (num / den) * 10e13))
        p = plt.scatter(regimes, acc, color=COLORS[s])
        plots_id.append(p)
    plt.legend(plots_id, solvers)
    if save: plt.savefig('res/plots/%s.png' % (name))
    plt.show()
    return
Example #2
0
def plot_ilu(ref=1, save=False):
    name = 'conditionnementILU'
    params = ((0, 0), (0, 50), (50, 0), (50, 50))
    regimes = ['Statique', 'Stationnaire', 'Harmonique', 'Dynamique']
    func = [ILU, getA]
    plots_names = ['M$^{{{}}}$A'.format(-1), 'A']
    plots_id = []
    plt.Figure(figsize=(20, 20))
    plt.xlabel('Régime')
    plt.yscale('log')
    plt.ylabel('Nombre de conditionnement')
    for s in range(len(func)):
        k = []
        for param in params:
            setVariables(ref=ref, vel=param[0], freq=param[1])
            ndt.main(show=False, test=False, solver=False)
            A = func[s](ndt.A)
            [min, max] = my.get_min_max_singular_values(A)
            k.append(max / min)
        p = plt.scatter(regimes, k, color=COLORS[s])
        plots_id.append(p)
    plt.legend(plots_id, plots_names)
    if save: plt.savefig('res/plots/%s.png' % (name))
    plt.show()
    return
Example #3
0
def spectrum(save=False, name='spectrum'):
    ndt.vel = 0
    ndt.freq = 0
    ndt.ref = 1
    ndt.main(solver=False, show=False, test=False)
    ndt.A = np.array(ndt.A)
    ndt.b = np.array(ndt.b)
    marksize = 4

    fig = plt.Figure()
    plt.subplot(211)
    plt.title(
        'Spectre de la matrice initiale et de la matrice préconditionnée')
    plt.xlabel('$\Re(z)$')
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.ylabel('$\Im(z)$')
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))

    eigen, _ = lin.eig(ndt.A)
    plt.plot(np.real(eigen),
             np.imag(eigen),
             'o',
             markersize=marksize,
             color=orange,
             label='Spectre de la matrice initiale ($A$)')

    sM, iM, jM = csrILU0(*CSRformat(ndt.A))
    ILU = invCSRformat(sM, iM, jM)
    L = np.tril(ILU, -1) + np.eye(len(ILU))
    U = np.triu(ILU)
    M_1 = lin.inv(np.dot(L, U)) @ ndt.A
    eigen, _ = lin.eig(M_1)
    plt.plot(np.real(eigen),
             np.imag(eigen),
             'o',
             markersize=marksize + 2,
             color=purple,
             label='Spectre de la matrice préconditionnée (M$^{-1}A$)')
    plt.legend()
    plt.subplot(212)
    plt.title('Spectre de la matrice préconditionnée')
    plt.xlabel('$\Re(z)$')
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.ylabel('$\Im(z)$')
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))

    plt.plot(np.real(eigen),
             np.imag(eigen),
             'o',
             markersize=marksize + 2,
             color=purple,
             label='Spectre de la matrice préconditionnée (M$^{-1}A$)')
    plt.legend()
    if save: plt.savefig('res/plots/%s.png' % (name))
    else: plt.show()
    return
Example #4
0
def complexitylog(precision, save=False, name='complexitylog'):
    ndt.vel = 1
    ndt.freq = 50
    selfColors = [orange, purple, purple]
    selfChar = ['o', 'o', 'x']
    plus = [0.5, 0.25, 0]
    names = ['LUsolve', 'LUcsrsolve', 'LUcsrsolve avec RCMK']
    selfSolver = [LUsolve, LUcsrsolve, LUcsrsolve]
    selfRMCK = [False, False, True]
    plt.Figure()
    plt.tick_params(
        labelleft=False,  # ticks along the top edge are off
        labelbottom=False)
    plt.title('Logarithme des complexités temporelles des différents solvers')
    plt.xlabel('Nombre de noeuds [log$_{10}$]')
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.ylabel('Temps d\'exécution [log$_{10}$ sec]')
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    plotID = []
    for i in range(len(selfSolver)):
        times = []
        sizes = []
        for ndt.ref in precision:
            ndt.main()
            A = np.array(ndt.A)
            b = np.array(ndt.b)
            if (selfRMCK[i]):
                r = RCMK(*CSRformat(A)[1:3])
                A = (A[:, r])[r, :]
                b = b[r]
            sizes.append(len(A))
            tic = timer()
            selfSolver[i](A, b)
            tac = timer()
            times.append(tac - tic)
        logx = np.log10(sizes)
        logy = np.log10(times) + plus[i]
        ranger = np.linspace(logx[0], logx[-1], 100)
        fit = np.polyfit(logx, logy, 1)
        plt.plot(logx, logy, selfChar[i], color=selfColors[i])
        plt.plot(ranger, np.poly1d(fit)(ranger), '--', color=selfColors[i])
        plotID.append(fit)
    plt.legend([
        names[0],
        'Polyfit LUsolve : %.2fx+...' % plotID[0][0], names[1],
        'Polyfit LUcsrsolve sans RCMK: %.2fx+...' % plotID[1][0], names[2],
        'Polyfit LUcsrsolve avec RCMK: %.2fx+...' % plotID[2][0]
    ])
    if save: plt.savefig('res/plots/%s.png' % (name))
    else: plt.show()
    return
Example #5
0
def denseA(precision, save=False, name='DensityA'):
    Standard_densities = []
    sizes = []
    for ref in precision:
        ndt.ref = ref
        ndt.main()
        A = np.array(ndt.A)

        Standard_densities.append(density(A))
        sizes.append(len(A))

    plt.Figure()
    plt.title('Densité de la matrice initiale')
    plt.xlabel('Nombre de noeuds')
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.ylabel('Densité')
    plt.scatter(sizes, Standard_densities, color=purple)
    if save: plt.savefig('res/plots/%s.png' % (name))
    else: plt.show()
    return
Example #6
0
def band(precision, save=False, name='bandRCMK'):
    Standard_width = []
    RCMK_width = []
    sizes = []
    for ndt.ref in precision:
        ndt.main()
        A = np.array(ndt.A)
        size = len(A)
        sizes.append(size)

        sA, iA, jA = CSRformat(A)
        r = RCMK(iA, jA)
        ARCMK = (A[:, r])[r, :]
        sARCMK, iARCMK, jARCMK = CSRformat(ARCMK)

        Standard_width.append(bandwidth(iA, jA)[2])
        RCMK_width.append(bandwidth(iARCMK, jARCMK)[2])

    plt.Figure()
    plt.title('Largeur de bande des matrices selon RCMK')
    plt.xlabel('Nombre de noeuds')
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.ylabel('Largeur de la bande')
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    ps = plt.plot(sizes, Standard_width, 'o', color=purple)
    pr = plt.plot(sizes, RCMK_width, 'o', color=orange)
    ranger = np.linspace(sizes[0], sizes[-1], 100)
    spoly = np.polyfit(sizes, Standard_width, 1)
    rpoly = np.polyfit(sizes, RCMK_width, 1)
    pps = plt.plot(ranger, np.poly1d(spoly)(ranger), '--', color=purple)
    ppr = plt.plot(ranger, np.poly1d(rpoly)(ranger), '--', color=orange)
    plt.legend([
        'Sans RCMK', 'Avec RCMK',
        'Polyfit sans RCMK : %.2fx+...' % (spoly[0]),
        'Polyfit avec RCMK : %.2fx+...' % (rpoly[0])
    ])
    if save: plt.savefig('res/plots/%s.png' % (name))
    else: plt.show()
    return
Example #7
0
def regimes(refs, iterations=1000, save=False, name='regimes'):
    vels = [0, 50]
    freqs = [0, 50]
    linestyle = [[10, 0], [10, 10]]
    lwidth = [1.5, 3.0]
    names = ['statique', 'harmonique', 'stationnaire', 'dynamique']
    xranger = np.arange(iterations)
    fig = plt.Figure()
    ax = fig.add_subplot(111)
    plt.title(
        'Convergence de la norme du résidu en fonction du nombre d\'itérations et des différents régimes'
    )
    plt.xlabel('Nombre d\'itérations')
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.ylabel('Norme du résidu (||b-Ax$_n$||$_2$)')
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    for (i, ndt.ref) in zip(range(len(refs)), refs):
        for (j, ndt.freq) in zip(range(len(freqs)), freqs):
            for (k, ndt.vel) in zip(range(len(vels)), vels):
                ndt.main()
                A = np.array(ndt.A)
                b = np.array(ndt.b)
                _, res = csrGMRES(*CSRformat(A),
                                  b,
                                  rtol=1e-30,
                                  prec=False,
                                  max_iterations=iterations,
                                  res_history=[])
                plt.loglog(xranger,
                           res,
                           dashes=linestyle[j],
                           color=COLORS[len(freqs) * j + k],
                           label='Régime %s (%d noeuds)' %
                           (names[len(freqs) * j + k], ndt.Nodes),
                           linewidth=lwidth[i])
    plt.legend()
    if save: plt.savefig('res/plots/%s.png' % (name))
    else: plt.show()
    return
Example #8
0
def complexity(precision, save=False, name='complexity'):
    ndt.vel = 0
    ndt.freq = 50
    selfColors = [orange, purple, purple]
    selfChar = ['--o', '--o', '--x']
    names = ['LUsolve', 'LUcsrsolve', 'LUcsrsolve avec RCMK']
    selfSolver = [LUsolve, LUcsrsolve, LUcsrsolve]
    selfRMCK = [False, False, True]
    plt.Figure()
    plt.title('Complexité temporelle selon matrice creuse et RCMK')
    plt.xlabel('Nombre de noeuds')
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.ylabel('Temps d\'exécution [sec]')
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    plotID = []
    for i in range(len(selfSolver)):
        times = []
        sizes = []
        for ndt.ref in precision:
            ndt.main()
            A = np.array(ndt.A)
            b = np.array(ndt.b)
            if (selfRMCK[i]):
                r = RCMK(*CSRformat(A)[1:3])
                A = (A[:, r])[r, :]
                b = b[r]
            sizes.append(len(A))
            tic = timer()
            selfSolver[i](A, b)
            tac = timer()
            times.append(tac - tic)
        id = plt.scatter(sizes, times, marker=selfChar[i], color=selfColors[i])
        plotID.append(id)

    plt.legend(plotID, names)
    if save: plt.savefig('res/plots/%s.png' % (name))
    else: plt.show()
    return
Example #9
0
def CSR(precision, save=False, name='CSR'):
    times = []
    sizes = []
    for ndt.ref in precision:
        ndt.main()
        A = np.array(ndt.A)
        size = len(A)
        sizes.append(size)
        mean = []
        for m in range(4):
            tic = timer()
            sA, iA, jA = CSRformat(A)
            tac = timer()
            mean.append(tac - tic)
        times.append(sum(mean) / len(mean))

    plt.Figure()
    plt.title('Complexité temporelle de CSRformat')
    plt.xlabel('Nombre de noeuds [log$_{10}$]')
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.ylabel('Temps d\'exécution [log$_{10}$ sec]')
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    logx = np.log10(sizes)
    logy = np.log10(times)

    ps = plt.scatter(logx, logy, color=purple)
    fitab = np.polyfit(logx, logy, 1)
    fit = np.poly1d(fitab)
    ranger = np.linspace(logx[0], logx[-1], 100)
    pfit = plt.plot(ranger, fit(ranger), '--', color=orange)
    plt.legend([
        'Polyfit : (%.2fx-%.2f)' % (fitab[0], abs(fitab[1])),
        'Complexités temporelles'
    ])
    if save: plt.savefig('res/plots/%s.png' % (name))
    else: plt.show()
    return
Example #10
0
def precond(refs, iterations=1000, save=False, name='precond'):
    ndt.vel = 0
    ndt.freq = 0
    linestyle = ['--', '-']
    precs = [True, False]
    names = ['Avec préconditionnement', 'Sans préconditionnement']
    xranger = np.arange(iterations)
    fig = plt.Figure(figsize=(15, 22))
    ax = fig.add_subplot(111)
    plt.title(
        'Convergence de la norme du résidu en fonction du nombre d\'itéartions et du préconditionnement'
    )
    plt.xlabel('Nombre d\'itérations')
    plt.ticklabel_format(style='sci', axis='x', scilimits=(0, 0))
    plt.ylabel('Norme du résidu')
    plt.ticklabel_format(style='sci', axis='y', scilimits=(0, 0))
    for (i, ndt.ref) in zip(range(len(refs)), refs):
        for j in range(len(precs)):
            ndt.main()
            A = np.array(ndt.A)
            b = np.array(ndt.b)
            _, res = csrGMRES(*CSRformat(A),
                              b,
                              rtol=1e-30,
                              prec=precs[j],
                              max_iterations=iterations,
                              res_history=[])
            print('res 0 : ', res[0])
            plt.loglog(xranger,
                       res,
                       linestyle[i],
                       color=COLORS[i + j],
                       label='%s (%d noeuds)' % (names[i + j], ndt.Nodes))
    plt.legend()
    if save: plt.savefig('res/plots/%s.png' % (name))
    else: plt.show()
    return
Example #11
0
def all_RCMK():
    ndt.main()
    A = ndt.A
    L = LU.LU(A)[0]
    sA, iA, jA = CSRformat(A)
    r = RCMK(iA, jA)
    a_rcmk = (A[:, r])[r, :]
    sA, iA, jA = CSRformat(A)
    sA, iA, jA = CSRformat(a_rcmk)
    LRMCK = LU.LU(a_rcmk)[0]
    sA, iA, jA = CSRformat(LRMCK)
    plt.subplot(221)
    plt.title('Initial A')
    plt.spy(A)
    plt.subplot(222)
    plt.title('LU with initial A')
    plt.spy(L)
    plt.subplot(223)
    plt.title('A reordered')
    plt.spy((a_rcmk))
    plt.subplot(224)
    plt.title('LU with A reordered')
    plt.spy(LRMCK)
    plt.show()
Example #12
0
        firstIndex = iA[i]
        length = iA[i + 1] - firstIndex
        for j in range(length):
            curIndex = firstIndex + j
            A[i, jA[curIndex]] = sA[curIndex]
    return A


def csr_arnoldi(sA, iA, jA, v0, k: int, *M):
    n = len(v0)
    H = np.zeros((k + 1, k))
    Q = np.zeros((n, k + 1))
    q = v0 / np.linalg.norm(v0)
    Q[:, 0] = q
    for j in range(k):
        v = csr_dot(sA, iA, jA, Q[:, j])
        for i in range(j + 1):
            H[i, j] = np.dot(Q[:, i], v)
            v -= H[i, j] * Q[:, i]
        H[j + 1, j] = np.linalg.norm(v)
        if H[j + 1, j] != 0 and j != n - 1:
            q = v / H[j + 1, j]
            Q[:, j + 1] = q
        else:
            return Q, H
    return Q, H


if __name__ == '__main__':
    ndt.main(show=True, solver=True)
Example #13
0
def timer(SOLVER, **kwargs):
    start = time.time()
    setSolver(SOLVER)
    ndt.main(**kwargs)
    return time.time() - start
Example #14
0
#!/usr/bin/env python
# coding=utf-8
# Stan 2012-04-14

from pyramid.paster import setup_logging, get_appsettings
from wsgiref.simple_server import make_server

from ndt import main


if __name__ == '__main__':
    config_uri = '../development.ini'
    settings = get_appsettings(config_uri)

    app = main(global_config=None, **settings)
    server = make_server('0.0.0.0', 8080, app)
    server.serve_forever()