|
|
# -*- coding: utf-8 -*-
|
|
|
"""Визуализация результатов МКЭ (запускается из run_fea.py интерпретатором tools/venv/bin/python, vtk-osmesa,
|
|
|
offscreen). Вход — out/fea/vtk/render_spec.json. Выход — out/fea/img/*.png."""
|
|
|
import json
|
|
|
import math
|
|
|
import os
|
|
|
import sys
|
|
|
|
|
|
import numpy as np
|
|
|
import vtk
|
|
|
from vtk.util.numpy_support import numpy_to_vtk
|
|
|
|
|
|
W, H = 1400, 1000
|
|
|
try:
|
|
|
import matplotlib
|
|
|
_MPL = os.path.join(matplotlib.get_data_path(), "fonts", "ttf") # шрифт с кириллицей из комплекта matplotlib (venv)
|
|
|
except ImportError:
|
|
|
_MPL = "/usr/share/fonts/truetype/dejavu"
|
|
|
FONT = os.path.join(_MPL, "DejaVuSans.ttf")
|
|
|
FONT_B = os.path.join(_MPL, "DejaVuSans-Bold.ttf")
|
|
|
|
|
|
|
|
|
def _font(tp, bold=False):
|
|
|
f = FONT_B if bold else FONT
|
|
|
if os.path.exists(f):
|
|
|
tp.SetFontFamily(vtk.VTK_FONT_FILE)
|
|
|
tp.SetFontFile(f)
|
|
|
else:
|
|
|
tp.SetFontFamilyToArial()
|
|
|
|
|
|
|
|
|
def reader(path):
|
|
|
r = vtk.vtkUnstructuredGridReader()
|
|
|
r.SetFileName(path)
|
|
|
r.ReadAllScalarsOn()
|
|
|
r.ReadAllVectorsOn()
|
|
|
r.Update()
|
|
|
return r.GetOutput()
|
|
|
|
|
|
|
|
|
def surface(ds, level=1):
|
|
|
f = vtk.vtkDataSetSurfaceFilter()
|
|
|
f.SetInputData(ds)
|
|
|
f.SetNonlinearSubdivisionLevel(level)
|
|
|
f.Update()
|
|
|
return f.GetOutput()
|
|
|
|
|
|
|
|
|
def clip_half(ds, normal=(0, 1, 0), origin=(0, 0, 0)):
|
|
|
"""Оставить половину тела y ≤ 0 (вид в разрезе плоскостью XZ)."""
|
|
|
pl = vtk.vtkPlane()
|
|
|
pl.SetOrigin(*origin)
|
|
|
pl.SetNormal(*normal)
|
|
|
c = vtk.vtkTableBasedClipDataSet()
|
|
|
c.SetInputData(ds)
|
|
|
c.SetClipFunction(pl)
|
|
|
c.InsideOutOn()
|
|
|
c.Update()
|
|
|
return c.GetOutput()
|
|
|
|
|
|
|
|
|
def lut_rainbow(vmin, vmax, n=12):
|
|
|
lut = vtk.vtkLookupTable()
|
|
|
lut.SetNumberOfTableValues(n)
|
|
|
lut.SetHueRange(0.667, 0.0)
|
|
|
lut.SetRange(vmin, vmax)
|
|
|
lut.Build()
|
|
|
return lut
|
|
|
|
|
|
|
|
|
def scalar_bar(lut, title):
|
|
|
sb = vtk.vtkScalarBarActor()
|
|
|
sb.SetLookupTable(lut)
|
|
|
sb.SetTitle(title)
|
|
|
sb.SetNumberOfLabels(7)
|
|
|
sb.SetLabelFormat("%.0f")
|
|
|
sb.SetWidth(0.09)
|
|
|
sb.SetHeight(0.7)
|
|
|
sb.SetPosition(0.86, 0.15)
|
|
|
for tp in (sb.GetTitleTextProperty(), sb.GetLabelTextProperty()):
|
|
|
tp.SetColor(0.1, 0.1, 0.1)
|
|
|
_font(tp)
|
|
|
tp.ItalicOff()
|
|
|
tp.BoldOff()
|
|
|
tp.ShadowOff()
|
|
|
sb.GetTitleTextProperty().SetFontSize(16)
|
|
|
sb.GetLabelTextProperty().SetFontSize(14)
|
|
|
sb.SetUnconstrainedFontSize(True)
|
|
|
return sb
|
|
|
|
|
|
|
|
|
def text(s, pos=(0.02, 0.95), size=20):
|
|
|
t = vtk.vtkTextActor()
|
|
|
t.SetInput(s)
|
|
|
t.GetTextProperty().SetFontSize(size)
|
|
|
t.GetTextProperty().SetColor(0.05, 0.05, 0.05)
|
|
|
_font(t.GetTextProperty())
|
|
|
t.GetPositionCoordinate().SetCoordinateSystemToNormalizedViewport()
|
|
|
t.SetPosition(*pos)
|
|
|
return t
|
|
|
|
|
|
|
|
|
def mapper(poly, scalars=None, lut=None):
|
|
|
m = vtk.vtkPolyDataMapper()
|
|
|
m.SetInputData(poly)
|
|
|
if scalars:
|
|
|
poly.GetPointData().SetActiveScalars(scalars)
|
|
|
m.SetScalarModeToUsePointData()
|
|
|
m.SelectColorArray(scalars)
|
|
|
m.SetLookupTable(lut)
|
|
|
m.SetScalarRange(lut.GetRange())
|
|
|
m.ScalarVisibilityOn()
|
|
|
m.InterpolateScalarsBeforeMappingOn()
|
|
|
else:
|
|
|
m.ScalarVisibilityOff()
|
|
|
return m
|
|
|
|
|
|
|
|
|
def render(actors, fname, cam, overlays=(), depth_peel=False):
|
|
|
r = vtk.vtkRenderer()
|
|
|
r.SetBackground(1, 1, 1)
|
|
|
if depth_peel:
|
|
|
r.SetUseDepthPeeling(1)
|
|
|
r.SetMaximumNumberOfPeels(8)
|
|
|
for a in actors:
|
|
|
r.AddActor(a)
|
|
|
for o in overlays:
|
|
|
r.AddActor2D(o) if isinstance(o, (vtk.vtkActor2D,)) else r.AddViewProp(o)
|
|
|
w = vtk.vtkRenderWindow()
|
|
|
w.SetOffScreenRendering(1)
|
|
|
if depth_peel:
|
|
|
w.SetAlphaBitPlanes(1)
|
|
|
w.SetMultiSamples(0)
|
|
|
w.SetSize(W, H)
|
|
|
w.AddRenderer(r)
|
|
|
c = r.GetActiveCamera()
|
|
|
c.SetFocalPoint(*cam["focal"])
|
|
|
c.SetPosition(*cam["pos"])
|
|
|
c.SetViewUp(*cam.get("up", (0, 0, 1)))
|
|
|
r.ResetCamera()
|
|
|
c.Zoom(cam.get("zoom", 1.0))
|
|
|
r.ResetCameraClippingRange()
|
|
|
w.Render()
|
|
|
f = vtk.vtkWindowToImageFilter()
|
|
|
f.SetInput(w)
|
|
|
f.Update()
|
|
|
wr = vtk.vtkPNGWriter()
|
|
|
wr.SetFileName(fname)
|
|
|
wr.SetInputConnection(f.GetOutputPort())
|
|
|
wr.Write()
|
|
|
|
|
|
|
|
|
def cam_iso(c, d=900, az=-50, el=25, zoom=1.0):
|
|
|
a, e = math.radians(az), math.radians(el)
|
|
|
return dict(focal=c, pos=(c[0] + d * math.cos(e) * math.cos(a), c[1] + d * math.cos(e) * math.sin(a), c[2] + d * math.sin(e)),
|
|
|
zoom=zoom)
|
|
|
|
|
|
|
|
|
def edges_actor(poly, color=(0.2, 0.2, 0.2), op=0.25):
|
|
|
fe = vtk.vtkFeatureEdges()
|
|
|
fe.SetInputData(poly)
|
|
|
fe.BoundaryEdgesOn()
|
|
|
fe.FeatureEdgesOn()
|
|
|
fe.SetFeatureAngle(35)
|
|
|
fe.ManifoldEdgesOff()
|
|
|
fe.NonManifoldEdgesOff()
|
|
|
fe.ColoringOff()
|
|
|
fe.Update()
|
|
|
m = vtk.vtkPolyDataMapper()
|
|
|
m.SetInputData(fe.GetOutput())
|
|
|
a = vtk.vtkActor()
|
|
|
a.SetMapper(m)
|
|
|
a.GetProperty().SetColor(*color)
|
|
|
a.GetProperty().SetOpacity(op)
|
|
|
a.GetProperty().SetLineWidth(1.0)
|
|
|
return a
|
|
|
|
|
|
|
|
|
def tube(A, B, color, r=1.2):
|
|
|
ls = vtk.vtkLineSource()
|
|
|
ls.SetPoint1(*A)
|
|
|
ls.SetPoint2(*B)
|
|
|
t = vtk.vtkTubeFilter()
|
|
|
t.SetInputConnection(ls.GetOutputPort())
|
|
|
t.SetRadius(r)
|
|
|
t.SetNumberOfSides(16)
|
|
|
m = vtk.vtkPolyDataMapper()
|
|
|
m.SetInputConnection(t.GetOutputPort())
|
|
|
a = vtk.vtkActor()
|
|
|
a.SetMapper(m)
|
|
|
a.GetProperty().SetColor(*color)
|
|
|
return a
|
|
|
|
|
|
|
|
|
def label3d(s, p, color=(0.6, 0.0, 0.0), size=22):
|
|
|
t = vtk.vtkBillboardTextActor3D()
|
|
|
t.SetInput(s)
|
|
|
t.SetPosition(*p)
|
|
|
t.GetTextProperty().SetFontSize(size)
|
|
|
t.GetTextProperty().SetColor(*color)
|
|
|
_font(t.GetTextProperty(), bold=True)
|
|
|
return t
|
|
|
|
|
|
|
|
|
def sphere(p, r, color):
|
|
|
s = vtk.vtkSphereSource()
|
|
|
s.SetCenter(*p)
|
|
|
s.SetRadius(r)
|
|
|
s.SetThetaResolution(16)
|
|
|
s.SetPhiResolution(16)
|
|
|
m = vtk.vtkPolyDataMapper()
|
|
|
m.SetInputConnection(s.GetOutputPort())
|
|
|
a = vtk.vtkActor()
|
|
|
a.SetMapper(m)
|
|
|
a.GetProperty().SetColor(*color)
|
|
|
return a
|
|
|
|
|
|
|
|
|
def main(spec_path):
|
|
|
with open(spec_path, encoding="utf-8") as f:
|
|
|
spec = json.load(f)
|
|
|
img = spec["img"]
|
|
|
os.makedirs(img, exist_ok=True)
|
|
|
ds = reader(spec["static"])
|
|
|
b = ds.GetBounds()
|
|
|
cen = ((b[0] + b[1]) / 2, (b[2] + b[3]) / 2, (b[4] + b[5]) / 2)
|
|
|
surf = surface(ds)
|
|
|
half = surface(clip_half(ds))
|
|
|
# --- сетка
|
|
|
m = mapper(surf)
|
|
|
a = vtk.vtkActor()
|
|
|
a.SetMapper(m)
|
|
|
a.GetProperty().SetColor(0.80, 0.82, 0.86)
|
|
|
a.GetProperty().EdgeVisibilityOn()
|
|
|
a.GetProperty().SetEdgeColor(0.25, 0.25, 0.3)
|
|
|
a.GetProperty().SetLineWidth(0.5)
|
|
|
sur_lin = surface(ds, 0)
|
|
|
m2 = mapper(sur_lin)
|
|
|
a2 = vtk.vtkActor()
|
|
|
a2.SetMapper(m2)
|
|
|
a2.GetProperty().SetColor(0.82, 0.84, 0.88)
|
|
|
a2.GetProperty().EdgeVisibilityOn()
|
|
|
a2.GetProperty().SetEdgeColor(0.2, 0.2, 0.25)
|
|
|
ov = [text("КЭ-сетка корпуса (C3D10): %d узлов, %d элементов" % (ds.GetNumberOfPoints(), ds.GetNumberOfCells()))]
|
|
|
acts = [a2]
|
|
|
for p in spec["bcs"]["tap"]:
|
|
|
acts.append(sphere(p, 0.9, (0.1, 0.5, 0.1)))
|
|
|
for p in spec["bcs"]["rf"]:
|
|
|
acts.append(sphere(p, 0.9, (0.1, 0.3, 0.8)))
|
|
|
render(acts, os.path.join(img, "mesh_iso.png"), cam_iso(cen, az=-60, el=-20, zoom=1.25), ov)
|
|
|
hm = surface(clip_half(ds), 0)
|
|
|
a3 = vtk.vtkActor()
|
|
|
a3.SetMapper(mapper(hm))
|
|
|
a3.GetProperty().SetColor(0.82, 0.84, 0.88)
|
|
|
a3.GetProperty().EdgeVisibilityOn()
|
|
|
a3.GetProperty().SetEdgeColor(0.2, 0.2, 0.25)
|
|
|
render([a3], os.path.join(img, "mesh_cut.png"), dict(focal=cen, pos=(cen[0], cen[1] + 900, cen[2]), zoom=1.35),
|
|
|
[text("КЭ-сетка: разрез плоскостью XZ (сгущение у переходов, канавок, резьбы, вдоль ЛКН)")])
|
|
|
# --- поля напряжений
|
|
|
for c in spec["cases"]:
|
|
|
nm = "tresca_" + c["id"]
|
|
|
sig = c["sigma"]
|
|
|
vmax = max(1.5 * sig, min(c["tmax"], 3.0 * sig))
|
|
|
lut = lut_rainbow(0.0, vmax, 15)
|
|
|
for tag, poly, cam in (("iso", surf, cam_iso(cen, az=-55, el=25, zoom=1.25)),
|
|
|
("back", surf, cam_iso(cen, az=130, el=20, zoom=1.25)),
|
|
|
("cut", half, dict(focal=cen, pos=(cen[0], cen[1] + 900, cen[2]), zoom=1.35))):
|
|
|
ma = vtk.vtkActor()
|
|
|
ma.SetMapper(mapper(poly, nm, lut))
|
|
|
ov = [scalar_bar(lut, "σэкв (Треска), МПа"),
|
|
|
text("%s — %s" % (c["id"], c["name"]), size=19),
|
|
|
text("max %.0f МПа (узл.); [σ] = %.1f МПа; шкала до %.0f" % (c["tmax"], sig, vmax), pos=(0.02, 0.91), size=17)]
|
|
|
render([ma, edges_actor(poly)], os.path.join(img, "stress_%s_%s.png" % (c["id"], tag)), cam, ov)
|
|
|
# --- линии классификации (тело полупрозрачное)
|
|
|
full = vtk.vtkActor()
|
|
|
full.SetMapper(mapper(surf))
|
|
|
full.GetProperty().SetColor(0.78, 0.80, 0.86)
|
|
|
full.GetProperty().SetOpacity(0.18)
|
|
|
acts = [full, edges_actor(surf, op=0.6)]
|
|
|
labels = []
|
|
|
for s_ in spec["scl"]:
|
|
|
col = (0.85, 0.1, 0.1) if not s_.get("hot") else (0.1, 0.35, 0.9)
|
|
|
acts.append(tube(s_["A"], s_["B"], col, 1.3))
|
|
|
Bp, Ap = np.array(s_["B"]), np.array(s_["A"])
|
|
|
mid = Bp + 6.0 * (Bp - Ap) / max(np.linalg.norm(Bp - Ap), 1e-9)
|
|
|
labels.append(label3d(s_["id"], mid.tolist(), col, 20 if not s_.get("hot") else 15))
|
|
|
for tag, cam in (("front", dict(focal=cen, pos=(cen[0] + 150, cen[1] + 900, cen[2] + 200), zoom=1.3)),
|
|
|
("iso", cam_iso(cen, az=40, el=30, zoom=1.3))):
|
|
|
render(acts + labels, os.path.join(img, "scl_%s.png" % tag), cam,
|
|
|
[text("Линии классификации напряжений: красные — заданные, синие — через зоны максимума σэкв", size=18)],
|
|
|
depth_peel=True)
|
|
|
# --- формы колебаний
|
|
|
dm = reader(spec["modal"])
|
|
|
up = spec["upper"]
|
|
|
for md in spec["modes"]:
|
|
|
nm = "U_mode%d" % md["n"]
|
|
|
dm.GetPointData().SetActiveVectors(nm)
|
|
|
U = np.array([dm.GetPointData().GetArray(nm).GetTuple3(i) for i in range(dm.GetNumberOfPoints())])
|
|
|
umax = np.linalg.norm(U, axis=1).max()
|
|
|
# перемещение верхнего жёсткого узла (оболочка-контур крышки с колпаком)
|
|
|
uc = np.array(md["u_c"])
|
|
|
th = np.array(md["theta"])
|
|
|
C = np.array(up["com"])
|
|
|
top = np.array([0, 0, up["z1"]]) - C
|
|
|
u_top = uc + np.cross(th, top)
|
|
|
umax_all = max(umax, np.linalg.norm(u_top), 1e-12)
|
|
|
sc = 40.0 / umax_all
|
|
|
wv = vtk.vtkWarpVector()
|
|
|
wv.SetInputData(dm)
|
|
|
wv.SetScaleFactor(sc)
|
|
|
wv.Update()
|
|
|
mag = vtk.vtkArrayCalculator()
|
|
|
mag.SetInputConnection(wv.GetOutputPort())
|
|
|
mag.AddVectorArrayName(nm)
|
|
|
mag.SetFunction("mag(%s)" % nm)
|
|
|
mag.SetResultArrayName("umag")
|
|
|
mag.Update()
|
|
|
sp = surface(mag.GetOutput(), 0)
|
|
|
lut = lut_rainbow(0, umax, 12)
|
|
|
ma = vtk.vtkActor()
|
|
|
ma.SetMapper(mapper(sp, "umag", lut))
|
|
|
ma.GetProperty().SetOpacity(1.0)
|
|
|
und = vtk.vtkActor()
|
|
|
und.SetMapper(mapper(surface(dm, 0)))
|
|
|
und.GetProperty().SetRepresentationToWireframe()
|
|
|
und.GetProperty().SetColor(0.6, 0.6, 0.6)
|
|
|
und.GetProperty().SetOpacity(0.08)
|
|
|
# контур верхнего узла: цилиндр, движущийся как жёсткое тело
|
|
|
cyl = vtk.vtkCylinderSource()
|
|
|
cyl.SetRadius(up["r"])
|
|
|
cyl.SetHeight(up["z1"] - up["z0"])
|
|
|
cyl.SetResolution(48)
|
|
|
cyl.Update()
|
|
|
tr = vtk.vtkTransform()
|
|
|
tr.PostMultiply()
|
|
|
tr.RotateX(90)
|
|
|
tr.Translate(0, 0, 0.5 * (up["z0"] + up["z1"]))
|
|
|
tf = vtk.vtkTransformPolyDataFilter()
|
|
|
tf.SetInputConnection(cyl.GetOutputPort())
|
|
|
tf.SetTransform(tr)
|
|
|
tf.Update()
|
|
|
pts = tf.GetOutput().GetPoints()
|
|
|
for i in range(pts.GetNumberOfPoints()):
|
|
|
p = np.array(pts.GetPoint(i))
|
|
|
u = uc + np.cross(th, p - C)
|
|
|
pts.SetPoint(i, *(p + sc * u))
|
|
|
ca = vtk.vtkActor()
|
|
|
cm = vtk.vtkPolyDataMapper()
|
|
|
cm.SetInputData(tf.GetOutput())
|
|
|
ca.SetMapper(cm)
|
|
|
ca.GetProperty().SetColor(0.95, 0.55, 0.2)
|
|
|
ca.GetProperty().SetOpacity(0.35)
|
|
|
ov = [text("Форма %d: f = %.1f Гц — %s" % (md["n"], md["f"], md["kind"]), size=20),
|
|
|
text("масштаб перемещений ×%.0f (норм.); верхний узел — жёсткое тело (оранжевый контур)" % sc, pos=(0.02, 0.91), size=16),
|
|
|
scalar_bar(lut, "U, норм.")]
|
|
|
cc = (cen[0], cen[1], 0.5 * (b[4] + up["z1"]))
|
|
|
render([und, ma, ca], os.path.join(img, "mode%d.png" % md["n"]), cam_iso(cc, d=1400, az=-60, el=15, zoom=1.0), ov)
|
|
|
|
|
|
|
|
|
if __name__ == "__main__":
|
|
|
main(sys.argv[1])
|