# -*- coding: utf-8 -*- """Постобработка: чтение .frd/.dat CalculiX, интерполяция напряжений в точках, эквивалентные напряжения по Треска (ГОСТ 34233.1-2017 п. 4.3, 8.10), линеаризация по линиям классификации, поиск зоны максимума.""" import re import numpy as np from scipy.spatial import cKDTree from fea.mesher import tet10_N # =========================================================================== .frd / .dat def read_frd(path, n_nodes): """Результаты по шагам: список dict(name -> (n_nodes, ncomp)). Блоки DISP (3) и STRESS (6).""" steps = [] cur = None with open(path) as f: it = iter(f) for line in it: if line.startswith(" -4 "): name = line[5:13].strip() ncomp = int(line[13:18]) comps = [] for line in it: if line.startswith(" -5"): comps.append(line[5:13].strip()) continue break nval = len([c for c in comps if c != "ALL"]) arr = np.zeros((n_nodes, nval)) while not line.startswith(" -3"): if line.startswith(" -1"): k = int(line[3:13]) if k <= n_nodes: arr[k - 1] = [float(line[13 + 12 * j:25 + 12 * j]) for j in range(nval)] line = next(it) if cur is None or name in cur: # новый шаг/форма начинается с повторного имени блока cur = {} steps.append(cur) cur[name] = arr return steps def read_dat_reactions(path): """Суммарные реакции по наборам узлов: список (set, time, [fx,fy,fz]).""" out = [] with open(path) as f: lines = f.readlines() for i, l in enumerate(lines): m = re.search(r"total force \(fx,fy,fz\) for set (\S+) and time\s+(\S+)", l) if m: for j in range(i + 1, min(i + 4, len(lines))): v = lines[j].split() if len(v) >= 3: try: out.append((m.group(1), float(m.group(2)), [float(x) for x in v[-3:]])) break except ValueError: continue return out def read_dat_modal(path): with open(path) as f: txt = f.read().splitlines() res = dict(freq=[], omega=[], eig=[], part={}, mass={}, total_mass=None) i = 0 while i < len(txt): l = txt[i] if "E I G E N V A L U E O U T P U T" in l: i += 1 while i < len(txt) and not re.match(r"^\s+\d+\s+[-\d.E+]+", txt[i]): i += 1 while i < len(txt) and re.match(r"^\s+\d+\s+[-\d.E+]+", txt[i]): v = txt[i].split() res["eig"].append(float(v[1])) res["omega"].append(float(v[2])) res["freq"].append(float(v[3])) i += 1 continue for key, tag in (("part", "P A R T I C I P A T I O N F A C T O R S"), ("mass", "E F F E C T I V E M O D A L M A S S")): if tag in l: i += 1 rows = [] while i < len(txt) and not re.match(r"^\s+\d+\s+[-\d.E+]+", txt[i]): i += 1 while i < len(txt) and re.match(r"^\s+\d+\s+[-\d.E+]+", txt[i]): rows.append([float(x) for x in txt[i].split()[1:]]) i += 1 res[key] = rows if key == "mass": for j in range(i, min(i + 8, len(txt))): if "TOTAL" in txt[j].upper(): nums = re.findall(r"[-+]?\d\.\d+E[-+]\d+", txt[j]) if not nums and j + 1 < len(txt): nums = re.findall(r"[-+]?\d\.\d+E[-+]\d+", txt[j + 1]) if nums: res["total_mass"] = [float(x) for x in nums] break break i += 1 return res # =========================================================================== тензоры def tensor(S): """S (...,6) в порядке ccx: xx, yy, zz, xy, yz, zx -> (...,3,3).""" S = np.asarray(S) T = np.empty(S.shape[:-1] + (3, 3)) T[..., 0, 0], T[..., 1, 1], T[..., 2, 2] = S[..., 0], S[..., 1], S[..., 2] T[..., 0, 1] = T[..., 1, 0] = S[..., 3] T[..., 1, 2] = T[..., 2, 1] = S[..., 4] T[..., 0, 2] = T[..., 2, 0] = S[..., 5] return T def principal(S): return np.linalg.eigvalsh(tensor(S)) def tresca(S): w = principal(S) return w[..., -1] - w[..., 0] def mises(S): S = np.asarray(S) return np.sqrt(0.5 * ((S[..., 0] - S[..., 1]) ** 2 + (S[..., 1] - S[..., 2]) ** 2 + (S[..., 2] - S[..., 0]) ** 2) + 3 * (S[..., 3] ** 2 + S[..., 4] ** 2 + S[..., 5] ** 2)) # =========================================================================== интерполяция class Locator: def __init__(self, X, T): self.X, self.T = X, T self.C = X[T[:, :4]].mean(axis=1) self.tree = cKDTree(self.C) P0 = X[T[:, 0]] M = np.stack([X[T[:, 1]] - P0, X[T[:, 2]] - P0, X[T[:, 3]] - P0], axis=2) # (ne,3,3) self.P0 = P0 self.Minv = np.linalg.inv(M) def locate(self, p, k=40): d, idx = self.tree.query(p, k=k) lam = np.einsum("eij,ej->ei", self.Minv[idx], p - self.P0[idx]) # (k,3): r, s, t u = 1 - lam.sum(axis=1) mn = np.minimum(lam.min(axis=1), u) j = int(np.argmax(mn)) r, s, t = lam[j] if mn[j] < -0.02: # вне сетки (точка на кривой границе) — проекция в ближайший r, s, t = np.clip([r, s, t], 0, 1) sm = r + s + t if sm > 1: r, s, t = r / sm, s / sm, t / sm return int(idx[j]), (r, s, t), float(mn[j]) def interp(self, field, p): e, (r, s, t), q = self.locate(np.asarray(p, float)) N = tet10_N(r, s, t) return N @ field[self.T[e]], q # =========================================================================== линеаризация def linearize(loc, S, A, B, n=41): """Линеаризация тензора напряжений по отрезку AB (все 6 компонент; ср. ГОСТ 34233.1 п. 8.10 — «линеаризованные по сечению значения приведённых напряжений»; методика — как ASME VIII-2, прил. 5-A).""" A, B = np.asarray(A, float), np.asarray(B, float) t = float(np.linalg.norm(B - A)) xs = np.linspace(0.0, t, n) d = (B - A) / t # точки на концах сдвигаются внутрь на 1e-3·t (исключение попадания на границу) pts = [A + d * np.clip(x, 1e-3 * t, t - 1e-3 * t) for x in xs] vals, qmin = [], 1.0 for p in pts: v, q = loc.interp(S, p) vals.append(v) qmin = min(qmin, q) sig = np.array(vals) # (n,6) w = np.ones(n) w[1:-1:2], w[2:-1:2] = 4, 2 # Симпсон w *= (xs[1] - xs[0]) / 3.0 sm = (w[:, None] * sig).sum(axis=0) / t sb = 6.0 / t ** 2 * (w[:, None] * sig * (t / 2 - xs)[:, None]).sum(axis=0) tr_tot = tresca(sig) res = dict(t=t, sm=sm.tolist(), sb=sb.tolist(), Pm=float(tresca(sm)), PmPb_A=float(tresca(sm + sb)), PmPb_B=float(tresca(sm - sb)), peak=float(tr_tot.max()), peak_at=float(xs[int(np.argmax(tr_tot))]), tresca_profile=tr_tot.tolist(), x=xs.tolist(), locate_qmin=qmin) res["PmPb"] = max(res["PmPb_A"], res["PmPb_B"]) res["Pb"] = float(tresca(sb)) return res # =========================================================================== зона максимума def node_normals(fe): N = np.zeros_like(fe["X"]) for j in range(6): np.add.at(N, fe["bf"][:, j], fe["bn"] * fe["barea"][:, None]) nn = np.linalg.norm(N, axis=1) m = nn > 0 N[m] /= nn[m][:, None] return N, m def hot_spot(fe, tr, exclude_nodes, excl_radius=8.0): """Узел поверхности с максимальным σэкв вне окрестности закреплений; направление ЛКН — внутрь.""" N, onb = node_normals(fe) X = fe["X"] cand = np.where(onb)[0] if len(exclude_nodes): tree = cKDTree(X[exclude_nodes]) dd, _ = tree.query(X[cand]) cand = cand[dd > excl_radius] k = cand[int(np.argmax(tr[cand]))] return int(k), X[k].copy(), -N[k].copy()