Beispiel #1
0
def testadjoint():
    d = 2
    gc = grid.Grid(d * [3], bounds=d * [[-1, 1]])
    gf = grid.Grid(d * [5], bounds=d * [[-1, 1]])
    uf = np.random.random(gf.nall())
    uc = np.random.random(gc.nall())
    uc2 = interpolate(gf, gc, uf, transpose=True)
    uf2 = interpolate(gf, gc, uc)
    print(f"uc2*uc = {uc2.dot(uc)} uf2*uf = {uf2.dot(uf)}")
Beispiel #2
0
 def __init__(self, gridf, A=None, **kwargs):
     from strucfem import matrix, grid
     if 'verbose' in kwargs: self.verbose = kwargs.pop('verbose')
     else: self.verbose = False
     n = gridf.n
     maxlevelgrids = self._getmaxlevelgrids(n)
     if 'maxlevel' in kwargs:
         maxlevel = kwargs.pop('maxlevel')
         if maxlevel >= 0: self.maxlevel = min(maxlevel, maxlevelgrids - 1)
         else:
             self.maxlevel = min(
                 self._getmaxlevelmg(-maxlevel, gridf.nall(), gridf.dim),
                 maxlevelgrids - 1)
     else:
         self.maxlevel = maxlevelgrids - 1
     if self.verbose:
         print(
             f"maxlevelgrids = {maxlevelgrids} maxlevel = {self.maxlevel} nfine = {gridf.nall()}"
         )
     self.grids, self.matrices = [], []
     self.grids.append(gridf)
     for l in range(self.maxlevel):
         n = (n - 1) // 2 + 1
         self.grids.append(grid.Grid(n=n, bounds=gridf.bounds))
     if self.verbose: t0 = time.time()
     for i, grid in enumerate(self.grids):
         if i == 0 and A is not None: self.matrices.append(A)
         else: self.matrices.append(matrix.createMatrixDiff(grid))
     if self.verbose: print(f"matrix {time.time()-t0:8.2f}")
     if 'smoothers' in kwargs: self.smoothers = kwargs.pop('smoothers')
     else: raise KeyError(f"please give list of smoother")
     self.rhomat = np.abs(splinalg.eigs(self.matrices[-1], k=1)[0][0])
     if self.verbose: print(f"self.rhomat = {self.rhomat}")
     self.intsimp = transfer.InterpolateSimple(self.grids)
Beispiel #3
0
def test(d=1):
    n = np.random.randint(low=3, high=10, size=d)
    n = 3 * np.ones(d, dtype=int)
    bounds = d * [np.array([-1, 1])]
    if d > 1: bounds[-1] *= 100
    expr = ''
    for i in range(d):
        expr += f"cos(pi*x{i})+"
    expr = expr[:-1]
    uex = anasol.AnalyticalSolution(expr, dim=d)
    solvers = ["direct", "pyamg", "mg"]
    solvers = ["pyamg", "mg"]
    N, errs, its, ts = [], {}, {}, {}
    for solver in solvers:
        errs[solver], its[solver], ts[solver] = [], [], []
    gold = None
    while (1):
        n = 2 * n - 1
        g = grid.Grid(n=n, bounds=bounds)
        if g.nall() > 2 * 1e6 or np.max(g.dx) < 1e-3: break
        N.append(g.nall())
        A = matrix.createMatrixDiff(g)
        b = matrix.createRhsVectorDiff(g, uex)
        if gold == None: u0 = np.zeros_like(b)
        else: u0 = transfer.interpolate(gridf=g, gridc=gold, uold=uold)
        for solver in solvers:
            u, t, it = solve.solve(solver, A, b, x0=u0, grid=g)
            err = errors.errorl2(g, u, uex)
            errs[solver].append(err)
            its[solver].append(it)
            ts[solver].append(t)
        uold, gold = u, g
    print(f"its={its}")
    fig = plt.figure()
    ax = fig.add_subplot(311)
    ax.set_xlabel(r'$\log_{10}(N)$')
    ax.set_ylabel(r'$\log_{10}(e)$')
    ax.set_title(f"{expr}")
    for solver in solvers:
        ax.plot(np.log10(N), np.log10(errs[solver]), '-x', label=f"{solver}")
    ax.legend()
    ax = fig.add_subplot(312)
    ax.set_xlabel(r'$\log_{10}(N)$')
    ax.set_ylabel(r'it')
    ax.set_title(f"iter")
    for solver in solvers:
        ax.plot(np.log10(N), its[solver], '-x', label=f"{solver}")
    ax.legend()
    ax = fig.add_subplot(313)
    ax.set_xlabel(r'$\log_{10}(N)$')
    ax.set_ylabel(r't')
    ax.set_title(f"time")
    for solver in solvers:
        ax.plot(np.log10(N), np.log10(ts[solver]), '-x', label=f"{solver}")
    ax.legend()
    plt.show()
Beispiel #4
0
def test(d=1):
    n = np.random.randint(low=3,high=4, size=d)
    bounds = d*[[-1,1]]
    g = grid.Grid(n=n, bounds=bounds)
    expr = ''
    for i in range(d): expr += f"{np.random.randint(low=1,high=9)}*x{i}+"
    uex = anasol.AnalyticalSolution(expr[:-1], dim=g.dim)
    u = uex(g.coord())
    err = errorl2(g, u, uex)
    print(f"u={uex} grid={g}\nerr = {err:10.4e}")
Beispiel #5
0
def testerror(ns, bounds, expr):
    from scipy import stats
    solvers = ['mg', 'pyamg']
    # solvers = ['scsp']
    errs, times, niters = {}, {}, {}
    times = {}
    for solver in solvers:
        times[solver], errs[solver], niters[solver] = [], [], []
    uold, gold = None, None
    N = []
    for i, n in enumerate(ns):
        if i: uold, gold = u, g
        g = grid.Grid(n=n, bounds=bounds)
        N.append(g.nall())
        for solver in solvers:
            err, u, t, niter = test(g,
                                    expr=expr,
                                    solver=solver,
                                    uold=uold,
                                    gold=gold)
            # if solver == 'pyamg': uold, gold = u, g
            errs[solver].append(err)
            niters[solver].append(niter)
            times[solver].append(t)
    slope, ic, r, p, stderr = stats.linregress(np.log(N),
                                               np.log(errs[solvers[0]]))
    # print(f"y = {slope:4.2f} * x  {ic:+4.2f}")
    fig = plt.figure()
    ax = fig.add_subplot(311)
    ax.set_xlabel(r'log10(N)')
    ax.set_ylabel(r'log(e)')
    ax.set_title(f"y = {slope:4.2f} * x  {ic:+4.2f}")
    for solver in solvers:
        ax.plot(np.log10(N), np.log10(errs[solver]), '-x', label=f"{solver}")
    ax.legend()
    ax = fig.add_subplot(312)
    ax.set_xlabel(r'log10(N)')
    ax.set_ylabel(r'niter')
    ax.set_title(f"nall = {N[-1]}")
    # le premier est trop grand !!
    print(f"niters {niters}")
    for solver in solvers:
        if np.any(np.array(niters[solver]) != -1):
            ax.plot(np.log10(N), niters[solver], '-x', label=f"{solver}")
    ax.legend()
    ax = fig.add_subplot(313)
    ax.set_xlabel(r'log10(N)')
    ax.set_ylabel(r't')
    ax.set_title(f"dim = {g.dim}")
    # le premier est trop grand !!
    for solver in solvers:
        ax.plot(np.log10(N[1:]), times[solver][1:], '-x', label=f"{solver}")
    ax.legend()
    plt.show()
Beispiel #6
0
def test(solvers, d=1):
    n = np.random.randint(low=10,high=20, size=d)
    bounds = d*[[-1,1]]
    g = grid.Grid(n=n, bounds=bounds)
    expr = ''
    for i in range(d): expr += f"{np.random.randint(low=1,high=9)}*x{i}+"
    uex = anasol.AnalyticalSolution(expr[:-1], dim=g.dim)
    A = matrix.createMatrixDiff(g)
    b = matrix.createRhsVectorDiff(g, uex)
    for solver in solvers:
        u, t, iter = solve(solver, A, b, grid=g)
        err = errors.errorl2(g, u, uex)
        print(f"grid={g}\nsolver = {solver}\terr = {err:10.4e}\t time = {t}\t iter = {iter}")
Beispiel #7
0
def test(d=1):
    n = np.random.randint(low=4, high=8, size=d)
    bounds = d * [[-1, 1]]
    g = grid.Grid(n=n, bounds=bounds)
    expr = ''
    for i in range(d):
        expr += f"{np.random.randint(low=1,high=9)}*x{i}+"
    uex = anasol.AnalyticalSolution(expr[:-1], dim=g.dim)
    A = matrix.createMatrixDiff(g)
    b = matrix.createRhsVectorDiff(g, uex)
    u = splinalg.spsolve(A, b)
    err = errors.errorl2(g, u, uex)
    print(f"u={uex} grid={g}\nerr = {err:10.4e}")
def test(d=1):
    n = np.random.randint(low=3, high=4, size=d)
    bounds = d * [[-1, 1]]
    expr = ''
    for i in range(d):
        expr += f"cos(pi*x{i})+"
    expr = expr[:-1]
    uex = anasol.AnalyticalSolution(expr, dim=d)
    N, errs, its, ts = [], [], [], []
    gold = None
    for k in range(2 * (6 - d)):
        n = 2 * n - 1
        g = grid.Grid(n=n, bounds=bounds)
        A = matrix.createMatrixDiff(g)
        b = matrix.createRhsVectorDiff(g, uex)
        if gold == None: u0 = np.zeros_like(b)
        else: u0 = transfer.interpolate(gridf=g, gridc=gold, uold=uold)
        u, t, it = solve.solve("pyamg", A, b, x0=u0)
        err = errors.errorl2(g, u, uex)
        uold, gold = u, g
        N.append(g.nall())
        errs.append(err)
        its.append(it)
        ts.append(t)
        # print(f"u={uex} grid={g}\nerr = {err:10.4e}")
    slope, ic, r, p, stderr = stats.linregress(np.log10(N), np.log10(errs))
    # print(f"y = {slope:4.2f} * x  {ic:+4.2f}")
    fig = plt.figure()
    ax = fig.add_subplot(211)
    ax.set_xlabel(r'$\log_{10}(N)$')
    ax.set_ylabel(r'$\log_{10}(e)$')
    ax.set_title(f"{expr}")
    ax.plot(np.log10(N), np.log10(errs), '-x', label=f"err")
    ax.plot(np.log10(N),
            ic + slope * np.log10(N),
            '-k',
            label=f"y = {slope:4.2f} * x  {ic:+4.2f}")
    ax.legend()
    ax = fig.add_subplot(212)
    ax.set_xlabel(r'$\log_{10}(N)$')
    ax.set_ylabel(r'it', color='b')
    p0, = ax.plot(np.log10(N), its, '-xb', label=f"it")
    ax.set_title(f"iter/time")
    axt = ax.twinx()
    p1, = axt.plot(np.log10(N), np.log10(ts), '-xr', label=f"t")
    axt.set_ylabel(r'$\log_{10}(t)$', color='r')
    ax.tick_params(axis='y', labelcolor='b')
    axt.tick_params(axis='y', labelcolor='r')
    plt.legend(handles=[p0, p1])
    plt.show()
Beispiel #9
0
def testtocell(d=1):
    g = grid.Grid(d * [3], bounds=d * [[-1, 1]])
    expr = ''
    for i in range(d):
        expr += f"{np.random.randint(low=1,high=9)}*x{i}+"
    uex = anasol.AnalyticalSolution(expr[:-1], dim=d)
    u = uex(g.coord())
    # print(f"grid = {g}\nuex={uex}\nu={u}")
    uc = tocell(g, u)
    fig = plt.figure()
    ax = fig.add_subplot(2, 1, 1)
    plotgrid.plot(g, ax=ax, u=u, title=f"d={d}")
    ax = fig.add_subplot(2, 1, 2)
    plotgrid.plot(g, ax=ax, u=uc, title=f"d={d}", celldata=True)
    plt.show()
Beispiel #10
0
#=================================================================#
class MgDriver(mg.FdDriver):
    def __init__(self, grid, A, **kwargs):
        maxlevel=-10000
        if grid.dim == 1: maxlevel = -100
        super().__init__(grid, A=A, smoothers=['lgs'], maxlevel=maxlevel)

#=================================================================#
def solve(A, b, grid, x0=None, verbose=True):
    mgD = MgDriver(grid, A)
    mgS = mg.MultiGrid(mgD)
    return mgS.solve(b, x0=x0, verbose=verbose)

#=================================================================#
if __name__ == '__main__':
    import matplotlib.pyplot as plt
    d, l = 3, 6
    expr = ''
    for i in range(d): expr += f"log(1+x{i}**2)*"
    expr = expr[:-1]
    uex = anasol.AnalyticalSolution(expr, dim=d)
    bounds=d*[[-1,1]]
    grid = grid.Grid(n=np.array(d*[2**l+1]), bounds=bounds)
    print(f"uex = {uex} N={grid.nall()}")
    b = matrix.createRhsVectorDiff(grid, uex)
    A = matrix.createMatrixDiff(grid)
    u, res = solve(A, b, grid)
    plotgrid.plot(grid, u=u)
    plt.show()
Beispiel #11
0
def testprolongation(ns, bounds, expr, fcts, transpose=False):
    import time
    d = len(bounds)
    uex = anasol.AnalyticalSolution(expr, dim=d)
    print(f"uex={uex}")
    grids = []
    for n in ns:
        grids.append(grid.Grid(n, bounds=bounds))
    intsimp = InterpolateSimple(grids)
    times = {}
    for fct in fcts:
        times[fct] = []
    N = []
    if transpose:
        args = "(gridf = gf, gridc = gc, uold=uc, level=l+1)"
        argsT = "(gridf = gf, gridc = gc, uold=uf, level=l+1, transpose=True)"
        for l in range(len(grids) - 1):
            gc = grids[l]
            gf = grids[l + 1]
            N.append(gf.nall())
            uf = np.random.random(gf.nall())
            uc = np.random.random(gc.nall())
            uc = np.linspace(0, 1, gc.nall())
            uf = np.ones(gf.nall())
            for fct in fcts:
                print(fct)
                t0 = time.time()
                # uf2 = eval(fct+args)
                # print(f"AVANT uf2 = {uf2} ({id(uf2)}) {adress(uf2)}")
                uc2 = eval(fct + argsT)
                # print(f"uc = {uc}\nuc2 = {uc2} ({id(uc2)})")
                # print(f"uc={uc.shape} uc2={uc2.shape}")
                uf2 = eval(fct + args)
                # print(f"APRES uf2 = {uf2} ({id(uf2)}) {adress(uf2)}")
                times[fct].append(time.time() - t0)
                # print(f"uc={uc.shape} uc2={uc2.shape}")
                suc, suf = uc2.dot(uc), uf2.dot(uf)
                if abs(suc - suf) > 1e-14 * uc.dot(uc):
                    print(f"uc2*uc = {suc} uf2*uf = {suf}")
                    raise ValueError(f"bug in restrict {abs(suc-suf)}")
    else:
        args = "(gridf = gf, gridc = gc, uold=uc, level=l+1)"
        uc = uex(*grids[0].coord())
        for l in range(len(grids) - 1):
            gc = grids[l]
            gf = grids[l + 1]
            N.append(gf.nall())
            for fct in fcts:
                print(fct)
                t0 = time.time()
                uf = eval(fct + args)
                times[fct].append(time.time() - t0)
                error(gf, uf, uex)
            uc = uf

    for fct in fcts:
        plt.plot(np.log10(N), np.log10(times[fct]), 'x-', label=fct)
    plt.title(f"d={d}")
    plt.legend()
    plt.xlabel("log10(n)")
    plt.ylabel("log10(t)")
    plt.show()
Beispiel #12
0
                                                        np.mean(u),
                                                        spacing=(0.1, 0.1,
                                                                 0.1))
            ax.plot_trisurf(verts[:, 0],
                            verts[:, 1],
                            faces,
                            verts[:, 2],
                            cmap='Spectral',
                            lw=1)
        # else:
        #     import pyvista as pv
        #     grid = pv.StructuredGrid(x[0], x[1], x[2])
        #     grid["U"] = u
        #     contours = grid.contour([np.mean(u)])
        #     pv.set_plot_theme('document')
        #     p = pv.Plotter()
        #     p.add_mesh(contours, scalars=contours.points[:, 2], show_scalar_bar=False)
        #     p.show()
    else:
        raise ValueError(f"Not written: plot in d={d}")

    if not 'ax' in kwargs: plt.show()


#=================================================================#
if __name__ == '__main__':
    from strucfem import grid

    grid1 = grid.Grid(n=[5], bounds=[[1, 3]])
    plot(grid1, title="1D")
Beispiel #13
0
    d, l = 2, 2
    expr = ''
    for i in range(d):
        expr += f"log(1+x{i}**2)*"
    expr = expr[:-1]
    # expr = '3+x1+x0'
    uex = anasol.AnalyticalSolution(expr, dim=d)
    n = np.array(d * [2**l + 1])
    # n = 2**(l-2)*np.array([2,16,2])+1
    bounds = np.tile(np.array([-1, 1]), d).reshape(d, 2)
    # print(f"bounds={bounds}")
    # bounds[2] *= 100
    # bounds[2] *= 100
    # print(f"bounds={bounds}")
    grid = grid.Grid(n=n, bounds=bounds)
    print(f"uex = {uex} n={grid.n} n={grid.nall()} dx={grid.dx}")
    b = matrix.createRhsVectorDiff(grid, uex)
    smootherss = []
    smootherss.append(['jac'])
    # smootherss.append(['gssp'])
    smootherss.append(['gs'])
    # smootherss.append(['ilu'])
    # smootherss.append(['ljac'])
    # smootherss.append(['lgs'])
    times, smooth, niters = {}, {}, {}
    for smoothers in smootherss:
        t0 = time.time()
        # fd = FdDriver(grid, verbose=True, smoothers=smoothers, maxlevel=-10000)
        fd = FdDriver(grid, verbose=True, smoothers=smoothers)
        mg = MultiGrid(fd, verbose=True)