Skip to content

Commit

Permalink
Merge pull request #560 from kinnala/add-svg-mesh2d
Browse files Browse the repository at this point in the history
Add support for visualizing 2D meshes as svg
  • Loading branch information
kinnala authored Feb 13, 2021
2 parents 30a0c00 + 1757b5d commit c986540
Show file tree
Hide file tree
Showing 3 changed files with 84 additions and 9 deletions.
8 changes: 7 additions & 1 deletion skfem/mesh/mesh2d/mesh2d.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
import warnings
from typing import Optional

import numpy as np
from numpy import ndarray

from skfem.mesh import Mesh


Expand Down Expand Up @@ -55,6 +55,12 @@ def param(self) -> float:
return np.max(np.linalg.norm(np.diff(self.p[:, self.facets], axis=1),
axis=0))

def _repr_svg_(self) -> Optional[str]:
from skfem.visuals.svg import draw
if self.t.shape[1] > 5000:
return None
return draw(self)

@staticmethod
def strip_extra_coordinates(p: ndarray) -> ndarray:
return p[:, :2]
18 changes: 10 additions & 8 deletions skfem/visuals/matplotlib.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,15 @@

from functools import singledispatch

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.axes import Axes
from mpl_toolkits.mplot3d import Axes3D
from numpy import ndarray

import matplotlib.pyplot as plt
from matplotlib.axes import Axes

from ..assembly import InteriorBasis
from ..mesh import Mesh2D, MeshLine, MeshTri,\
MeshTet, MeshQuad
from ..mesh import Mesh2D, MeshLine, MeshQuad, MeshTet, MeshTri


@singledispatch
Expand Down Expand Up @@ -50,14 +50,16 @@ def draw_mesh2d(m: Mesh2D, **kwargs) -> Axes:
ax (optional)
A preinitialised Matplotlib axes for plotting.
node_numbering (optional)
If true, draw node numbering.
If ``True``, draw node numbering.
facet_numbering (optional)
If true, draw facet numbering.
If ``True``, draw facet numbering.
element_numbering (optional)
If true, draw element numbering.
If ``True``, draw element numbering.
aspect (optional)
Ratio of vertical to horizontal length-scales; ignored if ax
Ratio of vertical to horizontal length-scales; ignored if ``ax`` is
specified
boundaries_only (optional)
If ``True``, draw only boundary edges.
Returns
-------
Expand Down
67 changes: 67 additions & 0 deletions skfem/visuals/svg.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
"""Drawing meshes using svg."""

from functools import singledispatch

import numpy as np

from ..mesh import Mesh2D
from ..assembly import InteriorBasis


@singledispatch
def draw(m, **kwargs) -> str:
"""Visualise meshes by drawing the edges.
Parameters
----------
m
A mesh object.
Returns
-------
string
The svg xml source as a string.
"""
raise NotImplementedError("Type {} not supported.".format(type(m)))


@draw.register(Mesh2D)
def draw_mesh2d(m: Mesh2D, **kwargs) -> str:
"""Support for two-dimensional meshes."""
if "boundaries_only" in kwargs:
facets = m.facets[:, m.boundary_facets()]
else:
facets = m.facets
p = m.p
maxx = np.max(p[0])
minx = np.min(p[0])
maxy = np.max(p[1])
miny = np.min(p[1])
width = kwargs["width"] if "width" in kwargs else 300
if "height" in kwargs:
height = kwargs["height"]
else:
height = width * (maxy - miny) / (maxx - miny)
stroke = kwargs["stroke"] if "stroke" in kwargs else 1
sx = (width - 2 * stroke) / (maxx - minx)
sy = (height - 2 * stroke) / (maxy - miny)
p[0] = sx * (p[0] - miny) + stroke
p[1] = sy * (maxy - p[1]) + stroke
template = ("""<line x1="{}" y1="{}" x2="{}" y2="{}" """
"""style="stroke:black;stroke-width:{}"/>""")
lines = ""
for s, t, u, v in zip(p[0, facets[0]],
p[1, facets[0]],
p[0, facets[1]],
p[1, facets[1]]):
lines += template.format(s, t, u, v, stroke)
return ("""<svg xmlns="http://www.w3.org/2000/svg" version="1.1" """
"""width="{}" height="{}">{}</svg>""").format(width, height, lines)


@draw.register(InteriorBasis)
def draw_basis(ib: InteriorBasis, **kwargs) -> str:
Nrefs = kwargs["Nrefs"] if "Nrefs" in kwargs else 2
m, _ = ib.refinterp(ib.mesh.p[0], Nrefs=Nrefs)
return draw(m, boundaries_only=True, **kwargs)

0 comments on commit c986540

Please sign in to comment.