Esempio n. 1
0
def visualize():
    from skfem.visuals.matplotlib import plot
    return plot(ibasis2, u2, Nrefs=4, colorbar=True, shading='gouraud')
Esempio n. 2
0
                w=[basis['psi'].interpolate(velocity[i::2]) for i in range(2)])
psi = solve(*condense(A, vorticity, D=basis['psi'].find_dofs()['floor'].all()))

if __name__ == '__main__':

    from functools import partial
    from os.path import splitext
    from sys import argv

    from matplotlib.tri import Triangulation

    from skfem.visuals.matplotlib import plot, savefig

    name = splitext(argv[0])[0]

    plot(mesh, pressure)
    savefig(f'{name}-pressure.png', bbox_inches='tight', pad_inches=0)

    mesh.save(f'{name}-velocity.vtk',
              {'velocity': velocity[basis['u'].nodal_dofs].T})

    fig, ax = subplots()
    ax.plot(
        *mesh.p[:,
                mesh.facets[:,
                            np.concatenate(list(mesh.boundaries.values()))]],
        color='k')

    n_streamlines = 11
    plot = partial(ax.tricontour,
                   Triangulation(*mesh.p, mesh.t.T),
Esempio n. 3
0
    from matplotlib.tri import Triangulation

    from skfem.visuals.matplotlib import plot, draw, savefig

    name = splitext(argv[0])[0]

    mesh.save(f'{name}_velocity.vtk',
              {'velocity': velocity[basis['u'].nodal_dofs].T})

    print(basis['psi'].interpolator(psi)(np.zeros((2, 1)))[0],
          '(cf. exact 1/64)')

    print(
        basis['p'].interpolator(pressure)(np.array([[-0.5, 0.5], [0.5, 0.5]])),
        '(cf. exact -/+ 1/8)')

    ax = draw(mesh)
    plot(basis['p'], pressure, ax=ax)
    savefig(f'{name}_pressure.png')

    ax = draw(mesh)
    velocity1 = velocity[basis['u'].nodal_dofs]
    ax.quiver(*mesh.p, *velocity1, mesh.p[0, :])  # colour by buoyancy
    savefig(f'{name}_velocity.png')

    ax = draw(mesh)
    ax.tricontour(Triangulation(*mesh.p, mesh.t.T),
                  psi[basis['psi'].nodal_dofs.flatten()])
    savefig(f'{name}_stream-function.png')
Esempio n. 4
0
@BilinearForm
def hdg(u, ut, v, vt, w):
    from skfem.helpers import grad, dot
    # outwards normal
    n = w.n * (-1.)**w.idx[0]
    return dot(n, grad(u)) * (vt - v) + dot(n, grad(v)) * (ut - u)\
        + 1e1 / w.h * (ut - u) * (vt - v)


@LinearForm
def load(v, vt, w):
    return 1. * v


A = asm(laplace, ibasis) + asm(hdg, tbasis)
f = asm(load, ibasis)

y = solve(*condense(A, f, D=ibasis.get_dofs()))

(u1, ibasis1), (u2, ibasis2) = ibasis.split(y)

if __name__ == '__main__':
    from os.path import splitext
    from sys import argv
    from skfem.visuals.matplotlib import plot, savefig
    plot(ibasis1, u1, Nrefs=3, colorbar=True, shading='gouraud')
    savefig(splitext(argv[0])[0] + '_p1dg.png')
    plot(ibasis2, u2, Nrefs=4, colorbar=True, shading='gouraud')
    savefig(splitext(argv[0])[0] + '_skeleton.png')
Esempio n. 5
0
    n = w.n
    x = w.x
    return -dot(grad(v), n) * (x[0] == 1.0)


A = asm(laplace, ib)
B = asm(facetbilinf, fb)

b = asm(facetlinf, fb)

D = ib.find_dofs({'plate': m.facets_satisfying(lambda x: (x[1] == 0.0))})
I = ib.complement_dofs(D)

import scipy.sparse
b = scipy.sparse.csr_matrix(b)
K = scipy.sparse.bmat([[A + B, b.T], [b, None]], 'csr')

import numpy as np
f = np.concatenate((ib.zeros(), -1.0 * np.ones(1)))

I = np.append(I, K.shape[0] - 1)

x = solve(*condense(K, f, I=I))

if __name__ == "__main__":
    from os.path import splitext
    from sys import argv
    from skfem.visuals.matplotlib import plot, savefig
    plot(m, x[:-1], colorbar=True)
    savefig(splitext(argv[0])[0] + '_solution.png')
Esempio n. 6
0
def visualize():
    from skfem.visuals.matplotlib import plot
    return plot(m, x, shading='gouraud', colorbar=True)
Esempio n. 7
0
@BilinearForm
def advection(u, v, w):
    from skfem.helpers import grad
    _, y = w.x
    velocity_0 = 6 * y * (height - y)  # parabolic plane Poiseuille
    return v * velocity_0 * grad(u)[0]


dofs = basis.find_dofs({
    'inlet': mesh.facets_satisfying(lambda x: x[0] == 0.),
    'floor': mesh.facets_satisfying(lambda x: x[1] == 0.)
})
interior = basis.complement_dofs(dofs)

A = asm(laplace, basis) + peclet * asm(advection, basis)
t = np.zeros(basis.N)
t[dofs['floor'].all()] = 1.
t = solve(*condense(A, np.zeros_like(t), t, I=interior))

basis0 = basis.with_element(ElementQuad0())
t0 = solve(asm(mass, basis0), asm(mass, basis, basis0) @ t)

if __name__ == '__main__':
    from pathlib import Path
    from skfem.visuals.matplotlib import plot, savefig

    plot(mesh, t0)
    savefig(Path(__file__).with_suffix('.png'),
            bbox_inches='tight',
            pad_inches=0)
Esempio n. 8
0
print(f'v={v} c')

if __name__ == '__main__':
    from os.path import splitext
    from sys import argv
    from skfem.visuals.matplotlib import plot, savefig
    import matplotlib.pyplot as plt
    from skfem.utils import derivative

    B_x = derivative(A, global_basis, global_basis, 1)
    B_y = -derivative(A, global_basis, global_basis, 0)

    E_x = -derivative(U, global_basis, global_basis, 0)
    E_y = -derivative(U, global_basis, global_basis, 1)

    fig = plt.figure(figsize=(11.52, 5.12))

    ax1 = plt.subplot(1, 2, 1)
    plot(global_basis, np.sqrt(B_x**2 + B_y**2), ax=ax1, colorbar=True)
    ax1.set_title('Magnetic flux density (Tesla)')
    ax1.set_aspect('equal')
    ax1.set_yticks([])

    ax2 = plt.subplot(1, 2, 2)
    plot(global_basis, np.sqrt(E_x**2 + E_y**2), ax=ax2, colorbar=True)
    ax2.set_title('Electric field strength (V/m)')
    ax2.set_aspect('equal')
    ax2.set_yticks([])

    savefig(splitext(argv[0])[0] + '_solution.png')
Esempio n. 9
0
psi = solve(*condense(A, vorticity, D=basis['psi'].get_dofs('floor')))


if __name__ == '__main__':

    from functools import partial
    from os.path import splitext
    from sys import argv

    from matplotlib.tri import Triangulation

    from skfem.visuals.matplotlib import plot, savefig

    name = splitext(argv[0])[0]

    plot(mesh, pressure)
    savefig(f'{name}-pressure.png', bbox_inches='tight', pad_inches=0)

    mesh.save(f'{name}-velocity.vtk',
              {'velocity': velocity[basis['u'].nodal_dofs].T})

    fig, ax = subplots()
    ax.plot(*mesh.p[:, mesh.facets[:, np.concatenate(
        list(mesh.boundaries.values()))]],
            color='k')

    n_streamlines = 11
    contour = partial(ax.tricontour,
                      Triangulation(*mesh.p, mesh.t.T),
                      psi[basis['psi'].nodal_dofs.flatten()],
                      linewidths=1.)
Esempio n. 10
0
def visualize():
    from skfem.visuals.matplotlib import draw, plot
    ax = draw(m)
    return plot(ib, x, ax=ax, shading='gouraud', colorbar=True, nrefs=2)
Esempio n. 11
0
 def runTest(self):
     m = self.mesh_type()
     plot(m, m.p[0])
Esempio n. 12
0
def visualize():
    from skfem.visuals.matplotlib import plot, show
    return plot(basis, u, shading='gouraud', colorbar=True)
Esempio n. 13
0
facet_basis = FacetBasis(mesh, element, facets=mesh.boundaries['perimeter'])
H = heat_transfer_coefficient * asm(convection, facet_basis)

core_basis = InteriorBasis(mesh, basis.elem, elements=mesh.subdomains['core'])
f = joule_heating * asm(unit_load, core_basis)

temperature = solve(L + H, f)

if __name__ == '__main__':

    from os.path import splitext
    from sys import argv
    from skfem.visuals.matplotlib import draw, plot, savefig

    T0 = {
        'skfem':
        basis.interpolator(temperature)(np.zeros((2, 1)))[0],
        'exact':
        (joule_heating * radii[0]**2 / 4 / thermal_conductivity['core'] *
         (2 * thermal_conductivity['core'] / radii[1] /
          heat_transfer_coefficient +
          (2 * thermal_conductivity['core'] / thermal_conductivity['annulus'] *
           np.log(radii[1] / radii[0])) + 1))
    }
    print('Central temperature:', T0)

    ax = draw(mesh)
    plot(basis, temperature, ax=ax, colorbar=True)
    savefig(splitext(argv[0])[0] + '_solution.png')
Esempio n. 14
0
ib = InteriorBasis(m, e, intorder=5)

if __name__ == "__main__":
    import matplotlib.pyplot as plt
    from skfem.visuals.matplotlib import plot, draw
    f, axes = plt.subplots(3, 3)

    ixs = [(0, 0), (0, 1), (0, 2), (1, 0), (1, 2), (2, 0)]
    i = 0

    for itr in ib.nodal_dofs[:, 4]:
        axi = axes[ixs[i]]
        axi.set_axis_off()
        X = np.zeros(ib.N)
        X[itr] = 1.0
        plot(ib, X, Nrefs=5, shading='gouraud', ax=axi)
        i += 1

    axi = axes[(1, 1)]
    axi.set_axis_off()
    draw(m, ax=axi)

    axi = axes[(2, 1)]
    axi.set_axis_off()
    X = np.zeros(ib.N)
    X[np.array([56, 59, 64, 66])] = 1.0
    plot(ib, X, Nrefs=5, shading='gouraud', ax=axi)

    axi = axes[(2, 2)]
    axi.set_axis_off()
    X = np.zeros(ib.N)
Esempio n. 15
0

b = asm(load, V)


@BilinearForm
def diffusion_form(u, v, w):
    return sum(v.grad * (q(w["w"]) * u.grad))


def diffusion_matrix(u):
    return asm(diffusion_form, V, w=V.interpolate(u))


dirichlet = apply(u_exact, mesh.p)  # P1 nodal interpolation
plot(V, dirichlet).get_figure().savefig(str(output_dir.joinpath("exact.png")))


def residual(u):
    r = b - diffusion_matrix(u) @ u
    r[boundary] = 0.0
    return r


u = np.zeros(V.N)
u[boundary] = dirichlet[boundary]
result = root(residual, u, method="krylov")

if result.success:
    u = result.x
    print("Success.  Residual =", np.linalg.norm(residual(u), np.inf))
Esempio n. 16
0
"""One-dimensional Poisson."""

import numpy as np
from skfem import *
from skfem.models.poisson import laplace, unit_load

m = MeshLine(np.linspace(0, 1, 10))

e = ElementLineP1()
basis = InteriorBasis(m, e)

A = asm(laplace, basis)
b = asm(unit_load, basis)

x = solve(*condense(A, b, D=basis.find_dofs()))

if __name__ == "__main__":
    from skfem.visuals.matplotlib import plot, show
    plot(m, x)
    show()
Esempio n. 17
0
    from matplotlib.animation import FuncAnimation
    import matplotlib.pyplot as plt

    from skfem.visuals.matplotlib import plot

    parser = ArgumentParser(description='heat equation in a rectangle')
    parser.add_argument(
        '-g',
        '--gif',
        action='store_true',
        help='write animated GIF',
    )
    args = parser.parse_args()

    ax = plot(mesh, u_init[basis.nodal_dofs.flatten()], shading='gouraud')
    title = ax.set_title('t = 0.00')
    field = ax.get_children()[0]  # vertex-based temperature-colour
    fig = ax.get_figure()
    fig.colorbar(field)

    def update(event):
        t, u = event

        u0 = {'skfem': (probe @ u)[0], 'exact': (probe @ exact(t))[0]}
        print('{:4.2f}, {:5.3f}, {:+7.4f}'.format(t, u0['skfem'],
                                                  u0['skfem'] - u0['exact']))

        title.set_text(f'$t$ = {t:.2f}')
        field.set_array(u[basis.nodal_dofs.flatten()])
Esempio n. 18
0
                 solver=solver_iter_krylov(minres),
                 M=build_pc_diag(asm(mass, basis['p'])))

velocity = flow(pressure)

basis['psi'] = basis['u'].with_element(ElementQuad2())
psi = np.zeros(A.shape[0])
vorticity = asm(rot, basis['psi'], w=basis['u'].interpolate(velocity))
psi = solve(*condense(asm(laplace, basis['psi']), vorticity, D=basis['psi'].find_dofs()))
psi0 = basis['psi'].interpolator(psi)(np.zeros((2, 1)))[0]


if __name__ == '__main__':

    from os.path import splitext
    from sys import argv

    from matplotlib.tri import Triangulation
    from skfem.visuals.matplotlib import plot, draw

    print(psi0)

    name = splitext(argv[0])[0]
    plot(mesh, pressure, colorbar=True).get_figure().savefig(
        f'{name}_pressure.png')

    ax = draw(mesh)
    ax.tricontour(Triangulation(*mesh.p, mesh.to_meshtri().t.T),
                  psi[basis['psi'].nodal_dofs.flatten()])
    ax.get_figure().savefig(f'{name}_stream-lines.png')
Esempio n. 19
0
from skfem import *
from skfem.models.poisson import laplace, unit_load

m = MeshTri().refined(4)

e = ElementTriP1()
basis = InteriorBasis(m, e)

A = asm(laplace, basis)
b = asm(unit_load, basis)

x = solve(*condense(A, b, I=m.interior_nodes()))

if __name__ == "__main__":
    from os.path import splitext
    from sys import argv
    from skfem.visuals.matplotlib import plot, savefig

    plot(m, x, shading='gouraud', colorbar=True)
    savefig(splitext(argv[0])[0] + '_solution.png')
Esempio n. 20
0
M = asm(mass, basis)
u_exact = 2 * np.arctan2(*basis.doflocs[::-1]) / np.pi
u_error = u - u_exact
error_L2 = np.sqrt(u_error @ M @ u_error)
conductance = {'skfem': u @ A @ u,
               'exact': 2 * np.log(2) / np.pi}


@Functional
def port_flux(w):
    from skfem.helpers import dot, grad
    return dot(w.n, grad(w['u']))


current = {}
for port, boundary in mesh.boundaries.items():
    fbasis = FacetBasis(mesh, elements, facets=boundary)
    current[port] = asm(port_flux, fbasis, u=fbasis.interpolate(u))

if __name__ == '__main__':

    from skfem.visuals.matplotlib import plot, show

    print('L2 error:', error_L2)
    print('conductance:', conductance)
    print('Current in through ports:', current)

    plot(basis, u)
    show()
Esempio n. 21
0
import numpy as np

from .ex17 import mesh, basis, radii, joule_heating, thermal_conductivity


annulus = np.unique(basis.element_dofs[:, mesh.subdomains['annulus']])
temperature = basis.zeros()
core = basis.complement_dofs(annulus)
core_basis = Basis(mesh, basis.elem, elements=mesh.subdomains['core'])
L = asm(laplace, core_basis)
f = asm(unit_load, core_basis)
temperature = solve(*condense(thermal_conductivity['core'] * L,
                              joule_heating * f,
                              D=annulus))

T0 = {
    "skfem": (basis.probes(np.zeros((2, 1))) @ temperature)[0],
    "exact": joule_heating * radii[0] ** 2 / 4 / thermal_conductivity["core"],
}


if __name__ == '__main__':
    from os.path import splitext
    from sys import argv
    from skfem.visuals.matplotlib import draw, plot

    ax = draw(mesh)
    plot(mesh, temperature[basis.nodal_dofs.flatten()],
         ax=ax, colorbar=True)
    ax.get_figure().savefig(splitext(argv[0])[0] + '_solution.png')
Esempio n. 22
0
    eta_E = edge_jump.elemental(fbasis[0], **w)

    tmp = np.zeros(m.facets.shape[1])
    np.add.at(tmp, fbasis[0].find, eta_E)
    eta_E = np.sum(0.5 * tmp[m.t2f], axis=0)

    return eta_K + eta_E


if __name__ == "__main__":
    from skfem.visuals.matplotlib import draw, plot, show
    draw(m)

for itr in range(9):  # 9 adaptive refinements
    if itr > 0:
        m = m.refined(adaptive_theta(eval_estimator(m, u)))

    basis = InteriorBasis(m, e)

    K = asm(laplace, basis)
    f = asm(load, basis)

    I = m.interior_nodes()
    u = solve(*condense(K, f, I=I))

if __name__ == "__main__":
    draw(m)
    plot(m, u, shading='gouraud')
    show()
Esempio n. 23
0
    from matplotlib.animation import FuncAnimation
    import matplotlib.pyplot as plt

    from skfem.visuals.matplotlib import plot

    parser = ArgumentParser(description='heat equation in a rectangle')
    parser.add_argument(
        '-g',
        '--gif',
        action='store_true',
        help='write animated GIF',
    )
    args = parser.parse_args()

    ax = plot(mesh, u_init, shading='gouraud')
    title = ax.set_title('t = 0.00')
    field = ax.get_children()[0]  # vertex-based temperature-colour
    fig = ax.get_figure()
    fig.colorbar(field)

    def update(event):
        t, u = event

        u0 = {
            'skfem': basis.interpolator(u)(np.zeros((2, 1)))[0],
            'exact':
            np.exp(-diffusivity * np.pi**2 * t / 4 * sum(halfwidth**-2))
        }
        print('{:4.2f}, {:5.3f}, {:+7.4f}'.format(t, u0['skfem'],
                                                  u0['skfem'] - u0['exact']))