diff --git a/CLAUDE.md b/CLAUDE.md index 1d3a930..caaa97e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -29,7 +29,7 @@ CI(`.github/workflows/build.yml`)가 Windows/macOS/Linux에서 테스트 → PyI - **단위계**: 내부는 mm·N·MPa·tonne·s 고정. 밀도 t/mm³(재료 JSON은 kg/m³로 저장하고 로드 시 변환), 열량 1 W = 1000 N·mm/s, 대류 h[W/m²K]×1e-3. 변환은 `standards/__init__.py`와 `fem/thermal.py`에만 있다. - **면 식별(FaceRef)**: `geometry.faces_of(shape)`의 리스트 인덱스가 `FaceRef.face_index`. Netgen의 면 번호도 같은 순서임이 테스트로 보장된다. 뷰어 삼각형의 `cell_data["face_id"]`, 메시 경계 삼각형의 `FEMesh.tri_face`가 모두 이 인덱스라서 클릭 → 고정/하중 → 메시 절점이 연결된다. 면 순서를 바꾸는 형상 처리를 하면 기존 FaceRef가 깨진다. - **Netgen**은 자체 OCCT 사본을 쓰므로 부품을 STEP 임시 파일로 넘긴다(`fem/mesh.py`). `mesh.Coordinates()`는 Netgen 메모리 뷰라 반드시 복사할 것(안 하면 다음 부품 메싱 때 좌표가 깨짐). -- **솔버는 자체 구현**(원래 GPL 회피 목적이었으나 2026-11-18 사내용으로 정해져 GPL 의존성도 허용했으나, 2026-11-19 저장소를 공개(MinaryHub로 이전)하기로 해서 **새 GPL 의존성은 추가 전에 라이선스 재검토**): `fem/tet10.py`가 요소 수식, `fem/assembly.py`가 조립·선형해(작으면 SuperLU, 크면 pyamg CG). SuperLU는 반드시 `MMD_AT_PLUS_A` + `SymmetricMode` + `DiagPivotThresh=0`(SPD라 대각 피벗 안전). 기본 부분 피벗은 페널티 tie가 있으면 채움이 30배로 폭증한다. 여러 우변은 `make_solver`로 한 번 분해 후 재사용. **큰 정적 해석**(자유 DOF ≥ `static.ITERATIVE_MIN_DOF` 3만, 접촉 없음)은 `fem/multigrid.py`의 p-멀티그리드 CG를 쓴다: TET10의 꼭짓점 절점(TET4) 문제를 직접 풀어 보정 + Gauss-Seidel 1회씩. 반복 수가 메시와 무관(22~26회)해서 85k DOF 15 s → 2.6 s, 245k DOF 8 s. 페널티 행이 있으면 수렴하지 않으므로 `Constraints.elimination()`으로 구속을 소거한 K̂ = TᵀKT를 풀고(tie는 슬레이브 DOF, 핀·경사 미끄럼은 절점별 작은 블록), 이때 구속 반력은 `multiplier_forces`(라그랑주 승수)로 구한다(`_Stiffness.exact`). 소거 불가(tie 사슬)·특이(안 붙잡힌 부품)·미수렴이면 기존 분해 경로로 넘어가 그쪽이 진단한다. 접촉·모달·좌굴은 계속 분해를 쓴다(행렬이 바뀌거나 우변이 수십 개). 경계조건(`fem/constraints.py`)은 축 정렬 구속은 DOF 제거, 경사 미끄럼/핀/부품 간 접합(tie)은 페널티 방정식. 반력은 각 고정이 실제로 구속한 DOF/방정식만 합산한다(모서리 공유 DOF 이중 집계 방지). +- **솔버는 자체 구현**(원래 GPL 회피 목적이었으나 2026-11-18 사내용으로 정해져 GPL 의존성도 허용했으나, 2026-11-19 저장소를 공개(MinaryHub로 이전)하기로 해서 **새 GPL 의존성은 추가 전에 라이선스 재검토**): `fem/tet10.py`가 요소 수식, `fem/assembly.py`가 조립·선형해. **직접 분해는 PARDISO 우선**(`fem/pardiso.py`, MKL을 ctypes로; Windows/Linux x86-64, `mkl` 의존성): 2천~30만 DOF에서 `make_solver`가 먼저 쓰고, MKL이 없거나(macOS) 분해 실패(부정치) 또는 상대 피벗 < 1e-12(특이: 안 붙잡힌 부품)면 None → 기존 SuperLU/AMG가 이전과 똑같이 진단한다. 같은 행렬에서 85k DOF 분해 16.2 s → 0.9 s, 볼트 접촉 73k 52 s → 1.2 s(차이 1e-11). SPD(mtype 2)만, METIS 병렬 순서(`iparm[1]=3`), 같은 희소 패턴의 순서는 캐시(`_ORDERINGS`, 순서가 분해의 ~75 %), `MKL_CBWR_Set(COMPATIBLE)`로 **실행마다 비트 단위 동일**(마찰이 반올림 경로에 민감). 대체 경로는 `KSTRUCT_NO_PARDISO=1`로 강제할 수 있고 `tests/test_fem_pardiso.py`가 두 경로 일치를 확인한다. 설치 파일에는 PARDISO가 실제로 여는 MKL 라이브러리만 넣는다(`kstruct.spec`의 `MKL_KEEP`; GPU·MPI·ScaLAPACK 제외), 배포본 selftest는 Windows/Linux에서 PARDISO가 없으면 실패. 그 밖(작은 행렬·macOS)은 SuperLU, 큰 것은 pyamg CG. SuperLU는 반드시 `MMD_AT_PLUS_A` + `SymmetricMode` + `DiagPivotThresh=0`(SPD라 대각 피벗 안전). 기본 부분 피벗은 페널티 tie가 있으면 채움이 30배로 폭증한다. 여러 우변은 `make_solver`로 한 번 분해 후 재사용. **큰 정적 해석**(자유 DOF ≥ `static.ITERATIVE_MIN_DOF` 3만, 접촉 없음)은 `fem/multigrid.py`의 p-멀티그리드 CG를 쓴다: TET10의 꼭짓점 절점(TET4) 문제를 직접 풀어 보정 + Gauss-Seidel 1회씩. 반복 수가 메시와 무관(22~26회)해서 85k DOF 15 s → 2.6 s, 245k DOF 8 s. 페널티 행이 있으면 수렴하지 않으므로 `Constraints.elimination()`으로 구속을 소거한 K̂ = TᵀKT를 풀고(tie는 슬레이브 DOF, 핀·경사 미끄럼은 절점별 작은 블록), 이때 구속 반력은 `multiplier_forces`(라그랑주 승수)로 구한다(`_Stiffness.exact`). 소거 불가(tie 사슬)·특이(안 붙잡힌 부품)·미수렴이면 기존 분해 경로로 넘어가 그쪽이 진단한다. 접촉·모달·좌굴은 계속 분해를 쓴다(행렬이 바뀌거나 우변이 수십 개). 경계조건(`fem/constraints.py`)은 축 정렬 구속은 DOF 제거, 경사 미끄럼/핀/부품 간 접합(tie)은 페널티 방정식. 반력은 각 고정이 실제로 구속한 DOF/방정식만 합산한다(모서리 공유 DOF 이중 집계 방지). - **열 해석**(`fem/thermal.py`): 정상 상태 전도. 복사(`LoadKind.RADIATION`, magnitude = 방사율, `ambient` = 주변 온도)는 등가 대류 계수 εσ(T²+T∞²)(T+T∞)로, 온도 의존 열전도율(`Material.conductivity_table`, 재료 JSON `k_table`)은 요소 평균 온도 보간으로 넣고 둘 중 하나라도 있으면 `MAX_ITERATIONS`까지 고정점 반복(변화 < 범위의 1e-4). 복사는 Newton 접선 선형화(`radiation_tangent`: h = 4εσT³, 기준 온도 T − q/h)를 쓴다 — 할선 계수(`radiation_coefficient`)의 고정점 반복은 몇 W만 넘어도 발산했다. 온도 기준(`TEMPERATURE_REFERENCES`: 고정 온도·대류·복사)은 **연결된 부품 묶음마다** 있어야 하고 없으면 부품 이름을 넣은 `SolverError`(예전엔 그 부품이 말없이 0 °C). `heat_in`/`heat_out`은 들어온 열과 나간 열을 따로 합한다(상쇄하지 않음). **과도 해석**: `Project.thermal_duration` > 0이면 `_march`가 처음 온도(`initial_temperature`)에서 후진 오일러 `TRANSIENT_STEPS`(60)단계로 (K + C/Δt)Tₙ₊₁ = f + C/Δt·Tₙ을 푼다(C = ρc∫NNᵀ 일관 행렬 `capacity_matrix`, 선형이면 분해 1회, 복사·k(T)는 직전 단계 온도로 선형화). 온도 기준 없이도 풀리고(열 입력만으로 데워짐), 비열·밀도가 없으면 `SolverError`. `ThermalResult.times/history`(`TRANSIENT_FRAMES` 20 + 시작)를 결과 패널의 '시각'(모드 선택 상자 재사용)으로 고르고 색 범위는 전 시간 공통. 판정은 전 시간 최고 온도(`peak`), 강도 해석의 열응력은 마지막 시점 온도. 이론해 테스트 `tests/test_fem_transient.py`(한쪽 끝 가열 막대의 푸리에 급수, 긴 시간 → 정상 상태, 에너지 보존). - **열응력**: 정적해석에 열 조건(`THERMAL_LOADS`)이 있으면 먼저 `solve_thermal`로 온도장을 구하고 `reference_temperature` 대비 ΔT로 열하중을 만든다. 피로(`fem/fatigue.py`)는 정적 결과를 반복 하중의 최대값으로 보고 `report.summary.summarize`에서 계산된다. 피로 한도 보정은 `FatigueSettings`(표면 `SURFACE_FACTORS`, 신뢰도 `RELIABILITY_FACTORS`, 크기 0.85)로 하고 `Project.fatigue_surface/fatigue_reliability`에 저장; settings 없이 부르면 옛 상수 `MARIN_FACTOR`(0.7). - **접촉**(`fem/contact.py`, `ContactSolver`): 마찰 없는 node-to-surface 페널티(`CONTACT_PENALTY_FACTOR` 1e3, 접합 tie의 1e6보다 무름) + 능동 집합 반복. 해제 판정은 틈이 아니라 **평형 잔차 K u − f의 슬레이브 절점 성분**(= 스프링 힘; α·틈은 반올림을 α배 증폭하므로 쓰지 말 것)으로 하고, 임계값은 최대 접촉 압력의 0.1 %. 결합은 요소 크기·변위 크기 기준 관통. 쌍마다 상태 변경을 `MAX_FLIPS`회로 제한하고 상태가 순환하면 멈춘다(채터링 방지). 분해는 한 번 하고 능동 집합이 같으면 재사용, 바뀐 쌍이 적으면 Woodbury 저랭크 갱신(재분해와의 선택은 `make_solver`가 붙이는 `solve.breakeven` = 0.25·nnz(LU)/n 기준. **벽시계 시간으로 고르지 말 것**: 반올림 경로가 실행마다 달라져 마찰 결과가 195~1500 N으로 흔들렸다). K_c의 잔차는 페널티 행이 반올림을 증폭해 정확도 지표로 쓸 수 없다. Woodbury 갱신만으로는 cond(S)·eps(겹침 이음에서 8e-7, Windows CI에서 1e-6 초과)라서 같은 연산자로 반복 개선 1회를 하고(1.5e-9), 보정이 해의 1e-3을 넘으면 버린다. 접촉으로만 붙은 부품을 위해 1e-9 크기 안정화 스프링을 쓰고, 그 부품이 미끄러지면 `SolverError("contact unstable")`. 진동·좌굴·열 해석에서는 접촉을 접합으로 취급. **마찰**(`Connection.friction`, 쿨롱): 닫힌 쌍은 항상 접선 스프링 2개(α_t = `TANGENT_PENALTY_FACTOR` 1e-3 × 법선 α)를 갖고, 마찰은 스프링 기준점(anchor)을 옮기는 **return mapping**으로 푼다: 증분 시작 때 확정된 기준점(`base`)에서 잰 시험력 −α_t(s − base)를 마찰원 |F| ≤ μN으로 잘라 그 힘을 내도록 기준점을 다시 잡는다. 행렬이 안 바뀌어 반복 1회 = 역대입 1회(Aitken 가속, 상한 `MAX_FRICTION_SWEEPS`)이고, 마찰은 저항만 한다. 닫힌 쌍의 90 % 이상이 마찰원 위이고 마찰력 합력이 μΣN의 98 %에 이르면 **면 전체 미끄럼**(`gross`): 그 면의 접선 스프링을 빼고 합력 방향으로 μN을 외력으로 건다(받쳐 주는 것이 없으면 "contact unstable"). 하중은 `solve_path`가 예압 → 나머지 하중 `FRICTION_INCREMENTS`(4) 증분으로 건다(마찰은 경로 의존; 면 전체 미끄럼은 다음 증분으로 이어짐). 하지 말 것: 미끄럼 쌍의 스프링을 빼고 방향을 고정한 μN 외력(예압 판이 볼트 축으로 돌거나 마찰이 판을 되밀어 수렴 안 함), α_t를 법선 α와 같게(고착 범위 μN/α가 반올림보다 작아 판정이 흔들림), 시험력 크기의 합으로 면 전체 미끄럼 판정(예압 뒤엔 모든 쌍이 반지름 방향 마찰원 위라 거짓 발동). `StaticResult.contact`는 (닫힘, 전체, 미끄럼)이고 미끄럼 = 닫힘 × 미끄럼 쌍이 받는 법선력 비율(`ContactSet.slip_share`; TRI6 꼭짓점 절점은 균일 압력에서 법선력이 0이라 개수로 세면 아무 데서나 "미끄럼"). 반복 상한을 다 쓰면 `contact_converged=False`가 되고 요약 첫 메모로 경고한다. diff --git a/README.md b/README.md index 2afa058..1ded889 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +

KStruct

+ # KStruct — 부품 강도 해석 CAD 모델을 불러와 재료·고정·하중을 지정하면, 부품이 안전한지 색과 쉬운 말로 알려주는 diff --git a/docs/logo.png b/docs/logo.png new file mode 100644 index 0000000..66a9bbb Binary files /dev/null and b/docs/logo.png differ diff --git a/docs/screenshots/1920x1080/01_welcome.png b/docs/screenshots/1920x1080/01_welcome.png index 10d49b6..85e5181 100644 Binary files a/docs/screenshots/1920x1080/01_welcome.png and b/docs/screenshots/1920x1080/01_welcome.png differ diff --git a/docs/screenshots/1920x1080/02_setup.png b/docs/screenshots/1920x1080/02_setup.png index 2897dda..40a3071 100644 Binary files a/docs/screenshots/1920x1080/02_setup.png and b/docs/screenshots/1920x1080/02_setup.png differ diff --git a/docs/screenshots/1920x1080/03_stress.png b/docs/screenshots/1920x1080/03_stress.png index af363fb..d4f7965 100644 Binary files a/docs/screenshots/1920x1080/03_stress.png and b/docs/screenshots/1920x1080/03_stress.png differ diff --git a/docs/screenshots/1920x1080/04_safety.png b/docs/screenshots/1920x1080/04_safety.png index 34863f8..728dc4e 100644 Binary files a/docs/screenshots/1920x1080/04_safety.png and b/docs/screenshots/1920x1080/04_safety.png differ diff --git a/docs/screenshots/1920x1080/05_bolts.png b/docs/screenshots/1920x1080/05_bolts.png index 74ad112..2ce1742 100644 Binary files a/docs/screenshots/1920x1080/05_bolts.png and b/docs/screenshots/1920x1080/05_bolts.png differ diff --git a/docs/screenshots/1920x1080/06_modal.png b/docs/screenshots/1920x1080/06_modal.png index 1a46581..5032537 100644 Binary files a/docs/screenshots/1920x1080/06_modal.png and b/docs/screenshots/1920x1080/06_modal.png differ diff --git a/docs/screenshots/1920x1080/07_thermal.png b/docs/screenshots/1920x1080/07_thermal.png index 31ecd39..4b9b251 100644 Binary files a/docs/screenshots/1920x1080/07_thermal.png and b/docs/screenshots/1920x1080/07_thermal.png differ diff --git a/docs/screenshots/1920x1080/08_nonlinear.png b/docs/screenshots/1920x1080/08_nonlinear.png index 4e21a38..d242f11 100644 Binary files a/docs/screenshots/1920x1080/08_nonlinear.png and b/docs/screenshots/1920x1080/08_nonlinear.png differ diff --git a/docs/screenshots/1920x1080/09_dark_theme.png b/docs/screenshots/1920x1080/09_dark_theme.png index f02385a..00d5c91 100644 Binary files a/docs/screenshots/1920x1080/09_dark_theme.png and b/docs/screenshots/1920x1080/09_dark_theme.png differ diff --git a/docs/screenshots/2880x1800/01_welcome.png b/docs/screenshots/2880x1800/01_welcome.png index 76dfe00..e2a3d00 100644 Binary files a/docs/screenshots/2880x1800/01_welcome.png and b/docs/screenshots/2880x1800/01_welcome.png differ diff --git a/docs/screenshots/2880x1800/02_setup.png b/docs/screenshots/2880x1800/02_setup.png index 9beb0a3..f31c26c 100644 Binary files a/docs/screenshots/2880x1800/02_setup.png and b/docs/screenshots/2880x1800/02_setup.png differ diff --git a/docs/screenshots/2880x1800/03_stress.png b/docs/screenshots/2880x1800/03_stress.png index 83ba44f..56220e7 100644 Binary files a/docs/screenshots/2880x1800/03_stress.png and b/docs/screenshots/2880x1800/03_stress.png differ diff --git a/docs/screenshots/2880x1800/04_safety.png b/docs/screenshots/2880x1800/04_safety.png index b684b19..6af928f 100644 Binary files a/docs/screenshots/2880x1800/04_safety.png and b/docs/screenshots/2880x1800/04_safety.png differ diff --git a/docs/screenshots/2880x1800/05_bolts.png b/docs/screenshots/2880x1800/05_bolts.png index 9751988..c0ba2bd 100644 Binary files a/docs/screenshots/2880x1800/05_bolts.png and b/docs/screenshots/2880x1800/05_bolts.png differ diff --git a/docs/screenshots/2880x1800/06_modal.png b/docs/screenshots/2880x1800/06_modal.png index cfa78f9..48aa459 100644 Binary files a/docs/screenshots/2880x1800/06_modal.png and b/docs/screenshots/2880x1800/06_modal.png differ diff --git a/docs/screenshots/2880x1800/07_thermal.png b/docs/screenshots/2880x1800/07_thermal.png index 285a37a..9ea3fe4 100644 Binary files a/docs/screenshots/2880x1800/07_thermal.png and b/docs/screenshots/2880x1800/07_thermal.png differ diff --git a/docs/screenshots/2880x1800/08_nonlinear.png b/docs/screenshots/2880x1800/08_nonlinear.png index 303c117..cf9cb9a 100644 Binary files a/docs/screenshots/2880x1800/08_nonlinear.png and b/docs/screenshots/2880x1800/08_nonlinear.png differ diff --git a/docs/screenshots/2880x1800/09_dark_theme.png b/docs/screenshots/2880x1800/09_dark_theme.png index 8b0735c..b981933 100644 Binary files a/docs/screenshots/2880x1800/09_dark_theme.png and b/docs/screenshots/2880x1800/09_dark_theme.png differ diff --git a/packaging/kstruct.spec b/packaging/kstruct.spec index c291a59..e83572a 100644 --- a/packaging/kstruct.spec +++ b/packaging/kstruct.spec @@ -40,6 +40,26 @@ for f in occt.files or []: if f.suffix.lower() in (".dll", ".so", ".dylib") or ".so." in f.name: binaries.append((str(f.locate().resolve()), ".")) +# MKL for the PARDISO solver (Windows/Linux x86-64; fem/pardiso.py loads it with ctypes, +# so PyInstaller cannot see it). Only what PARDISO loads: the runtime, core, LP64 +# interface and OpenMP threading layers, every CPU-specific kernel (MKL picks one at run +# time), OpenMP and tbbmalloc. The wheels hold ~1 GB more (MPI, ScaLAPACK, GPU offload). +import re + +MKL_KEEP = re.compile( + r"^(lib)?(mkl_(rt|core|intel_lp64|intel_thread|sequential|def|mc3|avx\d*|vml_\w+)" + r"|iomp5(md)?|tbbmalloc)[.\d]*\.(dll|so[.\d]*|dylib)$", + re.IGNORECASE, +) +for dist in ("mkl", "intel-openmp", "tbb"): + try: + files = distribution(dist).files or [] + except Exception: # not installed on this platform (macOS) + continue + for f in files: + if MKL_KEEP.match(f.name) and "_db" not in f.name: + binaries.append((str(f.locate().resolve()), ".")) + a = Analysis( [str(ROOT / "src" / "kstruct" / "app.py")], pathex=[str(ROOT / "src")], @@ -69,8 +89,14 @@ exe = EXE( name="KStruct", console=False, disable_windowed_traceback=False, + icon=str(ROOT / "packaging" / "windows" / "kstruct.ico") if sys.platform == "win32" else None, ) coll = COLLECT(exe, a.binaries, a.datas, name="KStruct") if sys.platform == "darwin": - app = BUNDLE(coll, name="KStruct.app", bundle_identifier="kr.smic.kstruct") + app = BUNDLE( + coll, + name="KStruct.app", + icon=str(ROOT / "packaging" / "macos" / "kstruct.icns"), + bundle_identifier="kr.smic.kstruct", + ) diff --git a/packaging/macos/kstruct.icns b/packaging/macos/kstruct.icns new file mode 100644 index 0000000..788e44d Binary files /dev/null and b/packaging/macos/kstruct.icns differ diff --git a/packaging/make_icons.py b/packaging/make_icons.py new file mode 100644 index 0000000..0eac9d7 --- /dev/null +++ b/packaging/make_icons.py @@ -0,0 +1,59 @@ +"""Render the logo (src/kstruct/resources/icons/kstruct.svg) to every icon file: + + uv run python packaging/make_icons.py + +- src/kstruct/resources/icons/kstruct_.png window / taskbar icon, header logo +- packaging/windows/kstruct.ico KStruct.exe and the installer +- packaging/macos/kstruct.icns KStruct.app +- docs/logo.png README + +Rendered with Qt's SVG renderer (SVG Tiny: no clipPath, filters or CSS), so the SVG +must stay within that subset; the PNGs are committed so builds need no SVG support. +""" + +import io +import sys +from pathlib import Path + +ROOT = Path(__file__).resolve().parents[1] +SVG = ROOT / "src" / "kstruct" / "resources" / "icons" / "kstruct.svg" +SIZES = (16, 24, 32, 48, 64, 128, 256, 512) + + +def main() -> None: + from PIL import Image + from PySide6.QtCore import QBuffer, QIODevice, QRectF + from PySide6.QtGui import QGuiApplication, QImage, QPainter + from PySide6.QtSvg import QSvgRenderer + + app = QGuiApplication(sys.argv) # noqa: F841 + renderer = QSvgRenderer(str(SVG)) + if not renderer.isValid(): + raise SystemExit(f"cannot read {SVG}") + + images = {} + for size in (*SIZES, 1024): + img = QImage(size, size, QImage.Format_ARGB32) + img.fill(0) + p = QPainter(img) + p.setRenderHint(QPainter.Antialiasing) + p.setRenderHint(QPainter.SmoothPixmapTransform) + renderer.render(p, QRectF(0, 0, size, size)) + p.end() + buf = QBuffer() + buf.open(QIODevice.WriteOnly) + img.save(buf, "PNG") + images[size] = Image.open(io.BytesIO(bytes(buf.data()))).convert("RGBA") + + out = SVG.parent + for size in SIZES: + images[size].save(out / f"kstruct_{size}.png", optimize=True) + ico_sizes = [(s, s) for s in (16, 24, 32, 48, 64, 128, 256)] + images[256].save(ROOT / "packaging" / "windows" / "kstruct.ico", sizes=ico_sizes) + images[1024].save(ROOT / "packaging" / "macos" / "kstruct.icns") + images[512].save(ROOT / "docs" / "logo.png", optimize=True) + print("icons written") + + +if __name__ == "__main__": + main() diff --git a/packaging/windows/kstruct.ico b/packaging/windows/kstruct.ico new file mode 100644 index 0000000..861660e Binary files /dev/null and b/packaging/windows/kstruct.ico differ diff --git a/packaging/windows/kstruct.iss b/packaging/windows/kstruct.iss index 5347c9c..55d3089 100644 --- a/packaging/windows/kstruct.iss +++ b/packaging/windows/kstruct.iss @@ -19,6 +19,8 @@ SolidCompression=yes ArchitecturesAllowed=x64compatible ArchitecturesInstallIn64BitMode=x64compatible WizardStyle=modern +SetupIconFile=kstruct.ico +UninstallDisplayIcon={app}\KStruct.exe LicenseFile=..\..\THIRD_PARTY_NOTICES.md [Languages] diff --git a/pyproject.toml b/pyproject.toml index c7b04eb..4521870 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -10,6 +10,8 @@ requires-python = ">=3.12,<3.13" dependencies = [ "cadquery-ocp>=8.0.1.1.0", "lxml>=6.1.3", + # PARDISO sparse solver (fem/pardiso.py); not built for macOS, which keeps SuperLU + "mkl>=2024.2; (sys_platform == 'win32' or sys_platform == 'linux') and (platform_machine == 'x86_64' or platform_machine == 'AMD64')", "netgen-mesher>=6.2.2608", "networkx>=3.7", "numpy>=2.5.3", diff --git a/src/kstruct/app.py b/src/kstruct/app.py index b363cb2..2901e1b 100644 --- a/src/kstruct/app.py +++ b/src/kstruct/app.py @@ -1,5 +1,6 @@ from __future__ import annotations +import platform import sys from pathlib import Path @@ -23,7 +24,21 @@ def selftest() -> int: result = solve_static(project, mesh, {0: standards.materials()["s235"]}) peak = float(result.von_mises.max()) ok = 80 < peak < 200 and abs(result.reactions[0][2] - 2000) < 1e-3 - print(f"selftest: elements={len(mesh.tets)} peak_vm={peak:.1f} MPa -> {'OK' if ok else 'FAIL'}") + # a frozen build for Windows/Linux x86-64 must carry MKL; without it every analysis + # silently runs on the 18-55x slower SuperLU + from kstruct.fem import pardiso + + wants_mkl = sys.platform in ("win32", "linux") and platform.machine().lower() in ( + "x86_64", + "amd64", + ) + solver = "PARDISO" if pardiso.available() else "SuperLU" + if getattr(sys, "frozen", False) and wants_mkl and not pardiso.available(): + ok = False + print( + f"selftest: elements={len(mesh.tets)} peak_vm={peak:.1f} MPa solver={solver} " + f"-> {'OK' if ok else 'FAIL'}" + ) return 0 if ok else 1 @@ -80,6 +95,13 @@ def main() -> None: setup_logging() install_excepthook() + if sys.platform == "win32": # own taskbar entry and icon, not python.exe's + import ctypes + + try: + ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID("MinaryHub.KStruct") + except (AttributeError, OSError): + pass if "--version" in sys.argv: from kstruct import build_info diff --git a/src/kstruct/fem/assembly.py b/src/kstruct/fem/assembly.py index 046dcec..303a92d 100644 --- a/src/kstruct/fem/assembly.py +++ b/src/kstruct/fem/assembly.py @@ -2,13 +2,14 @@ from __future__ import annotations +import logging from collections.abc import Callable import numpy as np import scipy.sparse as sp import scipy.sparse.linalg as spla -from kstruct.fem import tet10 +from kstruct.fem import pardiso, tet10 from kstruct.fem.mesh import FEMesh from kstruct.model import Material @@ -22,6 +23,22 @@ REFACTOR_COLUMNS_PER_FILL = 0.25 AMG_BREAKEVEN = 2.0 # AMG setup is worth about this many preconditioned CG solves +# PARDISO (MKL, Windows/Linux x86-64): measured 18-55x faster factorization than SuperLU +# (85k-DOF bracket 16.2 s -> 0.9 s, 73k-DOF bolted joint 52 s -> 1.2 s, same answers), +# so with it the direct path is kept for much larger models (73k DOF peaked at 320 MB; +# fill grows about as n^(4/3), so 300k DOF stays near 2.3 GB) +PARDISO_MIN_DOF = 2_000 # below this SuperLU is as fast and starts no threads +PARDISO_MAX_DOF = 300_000 +# a factor pivot below this fraction of its diagonal entry means K is singular (a part +# not held): an exact singularity came out at 1.7e-14, a 1e-9 stabilising spring at 5e-10 +PARDISO_PIVOT_TOL = 1e-12 +# refactorization vs low-rank update break-even for PARDISO: a factorization costs about +# this many (batched) back-substitutions per nonzero-per-column of the factor (73k DOF: +# 1.2 s factorization, 0.02 s per batched column, 460 nonzeros per column) +PARDISO_REFACTOR_COLUMNS_PER_FILL = 0.12 + +log = logging.getLogger(__name__) + Progress = Callable[[float, str], None] @@ -100,6 +117,10 @@ def make_solver(K: sp.csr_matrix, near_null: np.ndarray): import warnings n = K.shape[0] + if PARDISO_MIN_DOF <= n <= PARDISO_MAX_DOF and pardiso.available(): + solve = _pardiso_solver(K) + if solve is not None: + return solve if n <= DIRECT_SOLVER_MAX_DOF: with warnings.catch_warnings(): warnings.simplefilter("error", spla.MatrixRankWarning) @@ -143,6 +164,34 @@ def solve(f: np.ndarray) -> np.ndarray: return solve +def _pardiso_solver(K: sp.csr_matrix): + """PARDISO factorization of the SPD K, or None to fall back to SuperLU / AMG: a K + that is not positive definite (singular, or an indefinite buckling shift) is left + to them so that they diagnose it exactly as before.""" + try: + factor = pardiso.factorize(K) + df, da = factor.pivots() + except pardiso.PardisoError as e: + log.info("PARDISO declined (%s): using SuperLU", e) + return None + with np.errstate(divide="ignore", invalid="ignore"): + smallest = float(np.min(df / np.abs(da))) if len(df) else 1.0 + if not smallest > PARDISO_PIVOT_TOL: + factor.free() + log.info("PARDISO: relative pivot %.1e, treating K as singular", smallest) + return None + + def solve(f: np.ndarray) -> np.ndarray: + x = factor.solve(f) + if not np.all(np.isfinite(x)): + raise SolverError("unstable") + return x + + solve.breakeven = PARDISO_REFACTOR_COLUMNS_PER_FILL * factor.nnz_factor / K.shape[0] + solve.factor = factor # keeps the factorization alive as long as the solver + return solve + + def inverse_operator(A: sp.spmatrix, near_null: np.ndarray) -> spla.LinearOperator: """A⁻¹ as a LinearOperator for eigsh's OPinv (shift-invert). diff --git a/src/kstruct/fem/nonlinear.py b/src/kstruct/fem/nonlinear.py index 7015043..a186da1 100644 --- a/src/kstruct/fem/nonlinear.py +++ b/src/kstruct/fem/nonlinear.py @@ -107,6 +107,24 @@ def __init__(self, mesh: FEMesh, materials: dict[int, Material], dT_nodes): else: self.thermal.append(alpha * (dT_nodes[mesh.tets] @ tet10.shape_functions(p))) self.n = len(mesh.tets) + self._pattern = None + + def pattern(self, mesh: FEMesh): + """(indptr, indices, slot of every element entry) of the tangent's CSR pattern, + built once: the pattern never changes, so each Newton iteration only sums the + element values into place instead of building and adding sparse matrices + (that sorting and conversion took a third of a 38k-DOF run).""" + if self._pattern is None: + n_dof = mesh.n_nodes * 3 + dofs = element_dofs(mesh.tets).astype(np.int64) + rows = np.repeat(dofs, 30, axis=1).ravel() + cols = np.tile(dofs, (1, 30)).ravel() + keys, slot = np.unique(rows * n_dof + cols, return_inverse=True) + indptr = np.zeros(n_dof + 1, dtype=np.int64) + np.cumsum(np.bincount(keys // n_dof, minlength=n_dof), out=indptr[1:]) + dtype = np.int32 if len(keys) < 2**31 else np.int64 + self._pattern = (indptr, (keys % n_dof).astype(dtype), slot.astype(dtype)) + return self._pattern def _deformation_gradient(ue: np.ndarray, dN: np.ndarray) -> np.ndarray: @@ -150,7 +168,9 @@ def _evaluate( eps_p, alpha = state new_eps_p, new_alpha = eps_p.copy(), alpha.copy() f_int = np.zeros(n_dof) - K = sp.csr_matrix((n_dof, n_dof)) if want_matrix else None + if want_matrix: + indptr, indices, slot = el.pattern(mesh) + values = np.zeros(len(indices)) S_points = np.zeros((el.n, 4, 6)) for start in range(0, el.n, CHUNK): sl = slice(start, min(start + CHUNK, el.n)) @@ -176,11 +196,11 @@ def _evaluate( Gab = np.einsum("eai,eij,ebj->eab", dN, St, dN) * dv[:, None, None] for k in range(3): Ke[:, k::3, k::3] += Gab - np.add.at(f_int, dofs.ravel(), fe.ravel()) + f_int += np.bincount(dofs.ravel(), weights=fe.ravel(), minlength=n_dof) if want_matrix: - rows = np.repeat(dofs, 30, axis=1).ravel() - cols = np.tile(dofs, (1, 30)).ravel() - K = K + sp.csr_matrix((Ke.ravel(), (rows, cols)), shape=(n_dof, n_dof)) + entries = slot[sl.start * 900 : sl.stop * 900] + values += np.bincount(entries, weights=Ke.ravel(), minlength=len(values)) + K = sp.csr_matrix((values, indices, indptr), shape=(n_dof, n_dof)) if want_matrix else None return f_int, K, (new_eps_p, new_alpha), S_points diff --git a/src/kstruct/fem/pardiso.py b/src/kstruct/fem/pardiso.py new file mode 100644 index 0000000..2a1725e --- /dev/null +++ b/src/kstruct/fem/pardiso.py @@ -0,0 +1,242 @@ +"""Intel oneMKL PARDISO for symmetric positive definite systems, through ctypes. + +SciPy's SuperLU factorizes on one core with a minimum-degree ordering that fills badly +on 3D meshes: a 85k-DOF bracket took 16 s and a 73k-DOF bolted joint 52 s to factorize. +PARDISO (METIS nested dissection, supernodal, multithreaded) does both in under a second +with the same answers (1e-11). MKL ships as the `mkl` wheel on Windows and Linux x86-64; +elsewhere, or if the library cannot be loaded, `available()` is False and callers keep +using SuperLU. + +Only the SPD path (mtype 2) is used. A matrix that is not positive definite (a part not +held, an indefinite shift in buckling) makes the factorization fail with error -4, and +the caller falls back to SuperLU, which then diagnoses it as before. + +Results must not depend on thread timing (friction is path dependent and once swung by +an order of magnitude with round-off): conditional numerical reproducibility is switched +on before the first call. +""" + +from __future__ import annotations + +import ctypes +import glob +import hashlib +import logging +import os +import sys +import weakref +from collections import OrderedDict +from functools import cache + +import numpy as np +import scipy.sparse as sp + +log = logging.getLogger(__name__) + +SPD = 2 +_PHASE_ANALYZE_FACTOR = 12 +_PHASE_SOLVE = 33 +_PHASE_RELEASE = -1 +MKL_CBWR_COMPATIBLE = 2 # bit-reproducible across runs and thread counts + + +class PardisoError(RuntimeError): + def __init__(self, code: int): + super().__init__(f"PARDISO error {code}") + self.code = code + + +def _candidates() -> list[str]: + env = os.environ.get("KSTRUCT_MKL_RT") + if env: + return [env] + if sys.platform == "win32": + names = ["mkl_rt.3.dll", "mkl_rt.2.dll", "mkl_rt.dll"] + else: + names = ["libmkl_rt.so.3", "libmkl_rt.so.2", "libmkl_rt.so"] + roots = [sys.prefix, getattr(sys, "_MEIPASS", ""), os.path.dirname(sys.executable)] + found: list[str] = [] + for root in filter(None, roots): + for sub in ("", "Library/bin", "lib", "_internal", "_internal/Library/bin"): + for name in names: + found += glob.glob(os.path.join(root, sub, name)) + return found + names # bare names: let the loader search its own path + + +@cache +def _library(): + if sys.platform == "darwin" or os.environ.get("KSTRUCT_NO_PARDISO"): + return None + for path in _candidates(): + try: + lib = ctypes.CDLL(path) + lib.pardiso.restype = None + except (OSError, AttributeError): + continue + try: + lib.MKL_CBWR_Set.restype = ctypes.c_int + lib.MKL_CBWR_Set(MKL_CBWR_COMPATIBLE) + except AttributeError: + log.warning("MKL without CBWR control: results may vary in the last digits") + log.info("PARDISO from %s", path) + return lib + return None + + +def available() -> bool: + return _library() is not None + + +# METIS ordering is ~75 % of a factorization (85k DOF: 0.8 s of 1.05 s) and depends only +# on the sparsity pattern, which repeats: every transient heat step, contact iterations +# whose active set comes back, load cases. Remember the last few orderings by pattern. +_ORDERINGS: OrderedDict[bytes, np.ndarray] = OrderedDict() +_ORDERINGS_KEPT = 4 + + +def _pattern_key(upper: sp.csr_matrix) -> bytes: + h = hashlib.blake2b(digest_size=16) + h.update(np.int64(upper.shape[0]).tobytes()) + h.update(upper.indptr.tobytes()) + h.update(upper.indices.tobytes()) + return h.digest() + + +class _Factor: + """One factorization; free() releases MKL's memory (also on garbage collection).""" + + def __init__(self, K: sp.spmatrix): + lib = _library() + if lib is None: + raise PardisoError(-999) + upper = sp.triu(K, format="csr") + upper.sort_indices() + n = upper.shape[0] + # PARDISO needs every diagonal entry present, even when zero + if np.any(upper.indices[upper.indptr[:-1]] != np.arange(n)): + upper = (upper + sp.eye(n, format="csr") * 0.0).tocsr() + upper.sort_indices() + self.n = n + self.a = np.ascontiguousarray(upper.data, dtype=np.float64) + self.ia = np.ascontiguousarray(upper.indptr, dtype=np.int32) + self.ja = np.ascontiguousarray(upper.indices, dtype=np.int32) + self.pt = np.zeros(64, dtype=np.int64) + self.iparm = np.zeros(64, dtype=np.int32) + ip = self.iparm + ip[0] = 1 # supply all values below + ip[1] = 3 # METIS nested dissection, parallel (0.76 -> 0.45 s at 85k, same order) + key = _pattern_key(upper) + known = _ORDERINGS.get(key) + if known is not None: + _ORDERINGS.move_to_end(key) + self.perm = known.copy() + ip[4] = 1 # use this ordering + else: + self.perm = np.zeros(n, dtype=np.int32) + ip[4] = 2 # return the computed ordering in perm + ip[7] = 0 # refine only if pivots were perturbed (never for SPD): 1e-12 as is + ip[9] = 13 # pivot perturbation 1e-13 (not used for SPD) + ip[17] = -1 # report nonzeros in the factor + ip[20] = 1 # Bunch-Kaufman (not used for SPD) + ip[26] = 0 # no matrix checker (indices are sorted above) + ip[34] = 1 # zero-based indices + ip[55] = 1 # keep the factor's diagonal (pivots) for the singularity check + self._lib = lib + self._finalizer = weakref.finalize(self, _release, lib, self.pt, n) + self._call(_PHASE_ANALYZE_FACTOR, None) + self.nnz_factor = int(ip[17]) + if known is None: + _ORDERINGS[key] = self.perm.copy() + while len(_ORDERINGS) > _ORDERINGS_KEPT: + _ORDERINGS.popitem(last=False) + + def pivots(self) -> tuple[np.ndarray, np.ndarray]: + """(diagonal of the factor, diagonal of the matrix), as pardiso_getdiag gives them.""" + df = np.zeros(self.n) + da = np.zeros(self.n) + error = ctypes.c_int32(0) + self._lib.pardiso_getdiag( + self.pt.ctypes.data_as(ctypes.POINTER(ctypes.c_int64)), + df.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), + da.ctypes.data_as(ctypes.POINTER(ctypes.c_double)), + ctypes.byref(ctypes.c_int32(1)), + ctypes.byref(error), + ) + if error.value != 0: + raise PardisoError(error.value) + return df, da + + def _call(self, phase: int, b: np.ndarray | None) -> np.ndarray | None: + nrhs = 1 if b is None or b.ndim == 1 else b.shape[1] + if b is None: + bb = np.zeros(1) + x = np.zeros(1) + else: + bb = np.asfortranarray(b, dtype=np.float64) + x = np.zeros_like(bb) + error = ctypes.c_int32(0) + i32 = ctypes.POINTER(ctypes.c_int32) + f64 = ctypes.POINTER(ctypes.c_double) + self._lib.pardiso( + self.pt.ctypes.data_as(ctypes.POINTER(ctypes.c_int64)), + ctypes.byref(ctypes.c_int32(1)), # maxfct + ctypes.byref(ctypes.c_int32(1)), # mnum + ctypes.byref(ctypes.c_int32(SPD)), + ctypes.byref(ctypes.c_int32(phase)), + ctypes.byref(ctypes.c_int32(self.n)), + self.a.ctypes.data_as(f64), + self.ia.ctypes.data_as(i32), + self.ja.ctypes.data_as(i32), + self.perm.ctypes.data_as(i32), + ctypes.byref(ctypes.c_int32(nrhs)), + self.iparm.ctypes.data_as(i32), + ctypes.byref(ctypes.c_int32(0)), # msglvl + bb.ctypes.data_as(f64), + x.ctypes.data_as(f64), + ctypes.byref(error), + ) + if error.value != 0: + self.free() + raise PardisoError(error.value) + return None if b is None else np.ascontiguousarray(x) + + def solve(self, b: np.ndarray) -> np.ndarray: + return self._call(_PHASE_SOLVE, np.asarray(b, dtype=np.float64)) + + def free(self) -> None: + self._finalizer() + + +def _release(lib, pt: np.ndarray, n: int) -> None: + if not pt.any(): + return + error = ctypes.c_int32(0) + dummy = np.zeros(1) + idx = np.zeros(1, dtype=np.int32) + iparm = np.zeros(64, dtype=np.int32) + i32 = ctypes.POINTER(ctypes.c_int32) + f64 = ctypes.POINTER(ctypes.c_double) + lib.pardiso( + pt.ctypes.data_as(ctypes.POINTER(ctypes.c_int64)), + ctypes.byref(ctypes.c_int32(1)), + ctypes.byref(ctypes.c_int32(1)), + ctypes.byref(ctypes.c_int32(SPD)), + ctypes.byref(ctypes.c_int32(_PHASE_RELEASE)), + ctypes.byref(ctypes.c_int32(n)), + dummy.ctypes.data_as(f64), + idx.ctypes.data_as(i32), + idx.ctypes.data_as(i32), + None, + ctypes.byref(ctypes.c_int32(1)), + iparm.ctypes.data_as(i32), + ctypes.byref(ctypes.c_int32(0)), + dummy.ctypes.data_as(f64), + dummy.ctypes.data_as(f64), + ctypes.byref(error), + ) + pt[:] = 0 + + +def factorize(K: sp.spmatrix) -> _Factor: + """Cholesky-type factorization of the SPD matrix K (full or upper storage).""" + return _Factor(K) diff --git a/src/kstruct/fem/thermal.py b/src/kstruct/fem/thermal.py index 39bb23d..9ce94f3 100644 --- a/src/kstruct/fem/thermal.py +++ b/src/kstruct/fem/thermal.py @@ -161,16 +161,29 @@ def capacity_matrix(mesh: FEMesh, materials: dict[int, Material]) -> sp.csr_matr return sp.csr_matrix((Ce.ravel(), (rows, cols)), shape=(n, n)) +class _Conduction: + """Element conduction matrices for k = 1, computed once per mesh. k is constant over + an element (the element mean temperature picks it), so K(k) only rescales them: + rebuilding the gradients every transient step cost 19 of 168 s on a 94k-DOF part.""" + + def __init__(self, mesh: FEMesh): + X = mesh.nodes[mesh.tets] + Ke = np.zeros((len(mesh.tets), 10, 10)) + for p, w in zip(tet10.GAUSS_POINTS, tet10.GAUSS_WEIGHTS, strict=True): + dNdx, det = tet10.gradients(X, p) + Ke += np.einsum("eni,emi,e->enm", dNdx, dNdx, det * w) + self.unit = Ke + self.rows = np.repeat(mesh.tets, 10, axis=1).ravel() + self.cols = np.tile(mesh.tets, (1, 10)).ravel() + self.n = mesh.n_nodes + + def matrix(self, k: np.ndarray) -> sp.csr_matrix: + data = (self.unit * np.asarray(k, dtype=float)[:, None, None]).ravel() + return sp.csr_matrix((data, (self.rows, self.cols)), shape=(self.n, self.n)) + + def _conductivity_matrix(mesh: FEMesh, k: np.ndarray) -> sp.csr_matrix: - X = mesh.nodes[mesh.tets] - Ke = np.zeros((len(mesh.tets), 10, 10)) - for p, w in zip(tet10.GAUSS_POINTS, tet10.GAUSS_WEIGHTS, strict=True): - dNdx, det = tet10.gradients(X, p) - Ke += np.einsum("eni,emi,e->enm", dNdx, dNdx, k * det * w) - rows = np.repeat(mesh.tets, 10, axis=1).ravel() - cols = np.tile(mesh.tets, (1, 10)).ravel() - n = mesh.n_nodes - return sp.csr_matrix((Ke.ravel(), (rows, cols)), shape=(n, n)) + return _Conduction(mesh).matrix(k) def _surface_matrices(mesh: FEMesh, tris: np.ndarray, h): @@ -246,14 +259,18 @@ def solve_thermal( for dofs, coefs in zip(ties.penalty_rows, ties.penalty_coefs, strict=True): if np.all(dofs % 3 == 0): scalar.add_equation(dofs // 3, coefs) - K0 = _conductivity_matrix(mesh, element_conductivity(mesh, materials)) + conduction = _Conduction(mesh) + K0 = conduction.matrix(element_conductivity(mesh, materials)) + k_depends_on_t = any(m.conductivity_table for m in materials.values()) tie_matrix = scalar.penalty_matrix(n, K0.diagonal().max()) def assemble(T_prev: np.ndarray | None): """Linear problem at the previous temperatures: (K, f, fixed mask, prescribed T, film terms (tris, h, ambient, ∫N dA) for the heat balance).""" - k = element_conductivity(mesh, materials, T_prev) - K = (K0 if T_prev is None else _conductivity_matrix(mesh, k)).tolil() + if T_prev is None or not k_depends_on_t: + K = K0 + else: + K = conduction.matrix(element_conductivity(mesh, materials, T_prev)) f = np.zeros(n) fixed = np.zeros(n, dtype=bool) T = np.zeros(n) @@ -283,11 +300,11 @@ def assemble(T_prev: np.ndarray | None): H, integral_n = _surface_matrices(mesh, tris, h) rows = np.repeat(tris, 6, axis=1).ravel() cols = np.tile(tris, (1, 6)).ravel() - K = K + sp.csr_matrix((H.ravel(), (rows, cols)), shape=(n, n)).tolil() + K = K + sp.csr_matrix((H.ravel(), (rows, cols)), shape=(n, n)) source = np.broadcast_to(np.asarray(h * ambient, dtype=float), (len(tris),)) np.add.at(f, tris.ravel(), (integral_n * source[:, None]).ravel()) films.append((tris, h, ambient, integral_n)) - return K.tocsr() + tie_matrix, f, fixed, T, films + return K + tie_matrix, f, fixed, T, films def solve_once(T_prev): Kp, f, fixed, T, films = assemble(T_prev) diff --git a/src/kstruct/resources/icons/kstruct.svg b/src/kstruct/resources/icons/kstruct.svg new file mode 100644 index 0000000..2990549 --- /dev/null +++ b/src/kstruct/resources/icons/kstruct.svg @@ -0,0 +1,18 @@ + + + + + + + + + + + + + + + + + + diff --git a/src/kstruct/resources/icons/kstruct_128.png b/src/kstruct/resources/icons/kstruct_128.png new file mode 100644 index 0000000..34ff5c3 Binary files /dev/null and b/src/kstruct/resources/icons/kstruct_128.png differ diff --git a/src/kstruct/resources/icons/kstruct_16.png b/src/kstruct/resources/icons/kstruct_16.png new file mode 100644 index 0000000..f0ff600 Binary files /dev/null and b/src/kstruct/resources/icons/kstruct_16.png differ diff --git a/src/kstruct/resources/icons/kstruct_24.png b/src/kstruct/resources/icons/kstruct_24.png new file mode 100644 index 0000000..08b7b27 Binary files /dev/null and b/src/kstruct/resources/icons/kstruct_24.png differ diff --git a/src/kstruct/resources/icons/kstruct_256.png b/src/kstruct/resources/icons/kstruct_256.png new file mode 100644 index 0000000..fe8ff47 Binary files /dev/null and b/src/kstruct/resources/icons/kstruct_256.png differ diff --git a/src/kstruct/resources/icons/kstruct_32.png b/src/kstruct/resources/icons/kstruct_32.png new file mode 100644 index 0000000..b453902 Binary files /dev/null and b/src/kstruct/resources/icons/kstruct_32.png differ diff --git a/src/kstruct/resources/icons/kstruct_48.png b/src/kstruct/resources/icons/kstruct_48.png new file mode 100644 index 0000000..f610951 Binary files /dev/null and b/src/kstruct/resources/icons/kstruct_48.png differ diff --git a/src/kstruct/resources/icons/kstruct_512.png b/src/kstruct/resources/icons/kstruct_512.png new file mode 100644 index 0000000..66a9bbb Binary files /dev/null and b/src/kstruct/resources/icons/kstruct_512.png differ diff --git a/src/kstruct/resources/icons/kstruct_64.png b/src/kstruct/resources/icons/kstruct_64.png new file mode 100644 index 0000000..4590218 Binary files /dev/null and b/src/kstruct/resources/icons/kstruct_64.png differ diff --git a/src/kstruct/ui/main_window.py b/src/kstruct/ui/main_window.py index 37cfe21..84dd4c5 100644 --- a/src/kstruct/ui/main_window.py +++ b/src/kstruct/ui/main_window.py @@ -185,6 +185,9 @@ def __init__(self) -> None: app = QApplication.instance() self.theme = theme.apply(app, prefs.theme()) if app is not None else theme.current() + self.setWindowIcon(theme.app_icon()) + if app is not None: + app.setWindowIcon(self.windowIcon()) self.viewer = ModelViewer() self.viewer.apply_theme(self.theme) self.viewer.selection_changed.connect(self._selection_changed) @@ -376,6 +379,10 @@ def _build_toolbar(self) -> None: bar.setContextMenuPolicy(Qt.ContextMenuPolicy.PreventContextMenu) bar.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) bar.setIconSize(QSize(18, 18)) + logo = QLabel() + logo.setPixmap(self.windowIcon().pixmap(QSize(26, 26))) + logo.setContentsMargins(4, 0, 6, 0) + bar.addWidget(logo) name = QLabel("KStruct") name.setObjectName("appName") bar.addWidget(name) diff --git a/src/kstruct/ui/theme.py b/src/kstruct/ui/theme.py index 540b480..4a070c9 100644 --- a/src/kstruct/ui/theme.py +++ b/src/kstruct/ui/theme.py @@ -488,6 +488,22 @@ def _paths() -> dict[str, list]: } +LOGO_SIZES = (16, 24, 32, 48, 64, 128, 256, 512) + + +def app_icon() -> QIcon: + """The KStruct logo (window, taskbar, dialogs) from the committed PNG sizes + (packaging/make_icons.py renders them from resources/icons/kstruct.svg).""" + icons = resources.files("kstruct.resources").joinpath("icons") + result = QIcon() + for size in LOGO_SIZES: + data = icons.joinpath(f"kstruct_{size}.png").read_bytes() + pixmap = QPixmap() + pixmap.loadFromData(data, "PNG") + result.addPixmap(pixmap) + return result + + def icon(name: str, colour: str | None = None, size: int = 20) -> QIcon: """A toolbar icon in the theme's text colour (2x pixmap for sharp HiDPI rendering).""" scale = 2 diff --git a/tests/test_fem_pardiso.py b/tests/test_fem_pardiso.py new file mode 100644 index 0000000..e55c2c6 --- /dev/null +++ b/tests/test_fem_pardiso.py @@ -0,0 +1,125 @@ +"""PARDISO (MKL) direct solver: same answers as SuperLU, singular systems still reported, +bit-reproducible, and everything works the same when MKL is not available.""" + +import numpy as np +import pytest +import scipy.sparse as sp +import scipy.sparse.linalg as spla + +from kstruct.fem import SolverError, assembly, generate_mesh, pardiso, solve_static +from kstruct.geometry.face_info import face_at +from kstruct.geometry.samples import _box, l_bracket +from kstruct.model import ( + Connection, + ConnectionKind, + FaceRef, + Fixture, + FixtureKind, + Load, + LoadKind, + Material, + Part, + Project, +) + +needs_mkl = pytest.mark.skipif(not pardiso.available(), reason="MKL/PARDISO not available") + +STEEL = Material( + id="steel", + name="steel", + category="steel", + youngs_modulus=210000.0, + poisson_ratio=0.3, + density=7.85e-9, + yield_strength=235.0, + tensile_strength=360.0, +) + + +def _laplacian(n: int, shift: float) -> sp.csr_matrix: + A = sp.diags([-np.ones(n - 1), 2 * np.ones(n), -np.ones(n - 1)], [-1, 0, 1]).tolil() + A[0, 0] = A[-1, -1] = 1.0 + shift # free ends: singular without the shift + return A.tocsr() + + +@needs_mkl +def test_pardiso_matches_superlu_and_is_reproducible(): + rng = np.random.default_rng(1) + n = 3000 + B = sp.random(n, n, density=4 / n, random_state=2) + K = (B @ B.T + sp.eye(n) * 0.1 + _laplacian(n, 1.0)).tocsr() + b = rng.standard_normal((n, 3)) + reference = spla.splu(K.tocsc()).solve(b) + factor = pardiso.factorize(K) + x1, x2 = factor.solve(b), factor.solve(b) + again = pardiso.factorize(K).solve(b) + assert np.abs(x1 - reference).max() < 1e-9 * np.abs(reference).max() + assert np.array_equal(x1, x2) and np.array_equal(x1, again) + assert factor.nnz_factor > 0 + + +@needs_mkl +def test_singular_and_indefinite_matrices_are_left_to_superlu(monkeypatch): + monkeypatch.setattr(assembly, "PARDISO_MIN_DOF", 10) + singular = _laplacian(3000, 0.0) # constant vector in the null space: a free body + assert assembly._pardiso_solver(singular) is None + indefinite = sp.diags(np.r_[np.ones(2999), -1.0]).tocsr() + assert assembly._pardiso_solver(indefinite) is None + held = _laplacian(3000, 1e-9) # like the contact stabilising springs: still accepted + assert assembly._pardiso_solver(held) is not None + + +def _bracket(load=-2000.0) -> Project: + shape = l_bracket() + project = Project(parts=[Part(0, "bracket", shape, "steel")]) + project.fixtures = [Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(shape, (0, 30, 40)))])] + project.loads = [ + Load(LoadKind.FORCE, [FaceRef(0, face_at(shape, (90, 30, 8)))], vector=(0, 0, load)) + ] + return project + + +def _stack(kind) -> Project: + lower, upper = _box(0, 0, 0, 40, 20, 10), _box(0, 0, 10, 40, 20, 20) + project = Project(parts=[Part(0, "a", lower, "steel"), Part(1, "b", upper, "steel")]) + project.connections = [ + Connection( + kind, + [FaceRef(0, face_at(lower, (20, 10, 10)))], + [FaceRef(1, face_at(upper, (20, 10, 10)))], + ) + ] + project.fixtures = [Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(lower, (20, 10, 0)))])] + project.loads = [ + Load(LoadKind.FORCE, [FaceRef(1, face_at(upper, (20, 10, 20)))], vector=(0, 0, -800.0)) + ] + return project + + +@needs_mkl +@pytest.mark.parametrize("make", [_bracket, lambda: _stack(ConnectionKind.CONTACT)]) +def test_analyses_agree_with_and_without_pardiso(monkeypatch, make): + project = make() + mesh = generate_mesh(project, "coarse") + materials = {p.id: STEEL for p in project.parts} + monkeypatch.setattr(assembly, "PARDISO_MIN_DOF", 0) + fast = solve_static(project, mesh, materials) + monkeypatch.setattr(pardiso, "available", lambda: False) + slow = solve_static(project, mesh, materials) + scale = np.abs(slow.displacement).max() + assert np.abs(fast.displacement - slow.displacement).max() < 1e-6 * scale + assert np.abs(fast.von_mises - slow.von_mises).max() < 1e-5 * slow.von_mises.max() + for a, b in zip(fast.reactions, slow.reactions, strict=True): + assert a == pytest.approx(b, rel=1e-6, abs=1e-6) + + +@needs_mkl +def test_unheld_part_is_still_reported(monkeypatch): + """Lower block fixed, upper block resting on it with no connection: nothing holds the + upper block, PARDISO declines the singular matrix and the SuperLU path reports it.""" + project = _stack(ConnectionKind.BONDED) + project.connections = [] + mesh = generate_mesh(project, "coarse") + monkeypatch.setattr(assembly, "PARDISO_MIN_DOF", 0) + with pytest.raises(SolverError, match="unstable"): + solve_static(project, mesh, {0: STEEL, 1: STEEL}) diff --git a/uv.lock b/uv.lock index c315fce..410bd9e 100644 --- a/uv.lock +++ b/uv.lock @@ -193,6 +193,30 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/56/43/4ca9e49d27a1fcf6bece6f6aec0ea46bb9112489b93d4b688fb415457bdb/iniconfig-2.3.1-py3-none-any.whl", hash = "sha256:9121e2c1fdb355232495be3194c8dfe87ccc2d5dee45947b78e68f499790d7a7", size = 7552, upload-time = "2026-10-06T22:48:36.959Z" }, ] +[[package]] +name = "intel-cmplr-lib-ur" +version = "2026.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "umf" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/f3/5b/10acaa79feeae68db3ee7e1e712cb007c665b05000c71a7e7afdab1750e6/intel_cmplr_lib_ur-2026.2.0-py2.py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:0d0a5099aa2e1e38375b509c2a8182e719ed74aa656b2a800ddf6cfbd3384b80", size = 33070367, upload-time = "2026-10-16T12:35:00.896Z" }, + { url = "https://files.pythonhosted.org/packages/5e/25/546c8f9d6e4d9501e848d352ecac99dc79e4bf41badc8ef1a2db6402637b/intel_cmplr_lib_ur-2026.2.0-py2.py3-none-win_amd64.whl", hash = "sha256:5bbf5f18ed13c801895d6f5fc40f0ef356344345b84c3bf29cc7b57bd3df9362", size = 672060, upload-time = "2026-10-16T12:32:00.153Z" }, +] + +[[package]] +name = "intel-openmp" +version = "2026.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "intel-cmplr-lib-ur" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/79/fd/8c80ef4b540e62761bb62b6bde10c17339218f6a25e27aedac816ac5c4c1/intel_openmp-2026.2.0-py2.py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:2308a1a3e74718a9cd8cccf218c34d8cd80b43d3b89dfbb01b38dee205c50980", size = 50322489, upload-time = "2026-10-16T12:35:17.817Z" }, + { url = "https://files.pythonhosted.org/packages/cd/81/3014f8c74e15bbea3de37e12ef43ea8df8fac498378162d1a89f28236398/intel_openmp-2026.2.0-py2.py3-none-win_amd64.whl", hash = "sha256:0fcd60701d6dcf8f17cd40c9733d7046ff3b82921a0a039bea2e6a68fb12c152", size = 23199644, upload-time = "2026-10-16T12:32:13.886Z" }, +] + [[package]] name = "kiwisolver" version = "1.5.1" @@ -226,6 +250,7 @@ source = { editable = "." } dependencies = [ { name = "cadquery-ocp" }, { name = "lxml" }, + { name = "mkl", marker = "(platform_machine == 'AMD64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32') or (platform_machine == 'x86_64' and sys_platform == 'win32')" }, { name = "netgen-mesher" }, { name = "networkx" }, { name = "numpy" }, @@ -249,6 +274,7 @@ dev = [ requires-dist = [ { name = "cadquery-ocp", specifier = ">=8.0.1.1.0" }, { name = "lxml", specifier = ">=6.1.3" }, + { name = "mkl", marker = "(platform_machine == 'AMD64' and sys_platform == 'linux') or (platform_machine == 'x86_64' and sys_platform == 'linux') or (platform_machine == 'AMD64' and sys_platform == 'win32') or (platform_machine == 'x86_64' and sys_platform == 'win32')", specifier = ">=2024.2" }, { name = "netgen-mesher", specifier = ">=6.2.2608" }, { name = "networkx", specifier = ">=3.7" }, { name = "numpy", specifier = ">=2.5.3" }, @@ -353,6 +379,19 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b3/38/89ba8ad64ae25be8de66a6d463314cf1eb366222074cfda9ee839c56a4b4/mdurl-0.1.2-py3-none-any.whl", hash = "sha256:84008a41e51615a49fc9966191ff91509e3c40b939176e643fd50a5c2196b8f8", size = 9979, upload-time = "2022-08-14T12:40:09.779Z" }, ] +[[package]] +name = "mkl" +version = "2026.2.1" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "intel-openmp" }, + { name = "tbb" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/31/53bb8fd1098caaf2c634cae75a1abbc1d3c67089a085afa38eeea79f7ea7/mkl-2026.2.1-py2.py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:76322a3abf512594ab7b4e82cb72df91e4e5d195498769aa8b292373c1ddd6d1", size = 229090670, upload-time = "2026-11-12T15:02:49.435Z" }, + { url = "https://files.pythonhosted.org/packages/47/db/8cad265c49b425e51dda3ba2fe7397f51ad0604cae0f5a129dfbc7f2ee92/mkl-2026.2.1-py2.py3-none-win_amd64.whl", hash = "sha256:96f9ee6a5f101801c56225bd6b7a4a82c95d3da1268d7bf952fa07d09992a619", size = 185223117, upload-time = "2026-11-12T15:03:42.019Z" }, +] + [[package]] name = "netgen-mesher" version = "6.2.2608" @@ -891,6 +930,27 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/b7/ce/149a00dd41f10bc29e5921b496af8b574d8413afcd5e30dfa0ed46c2cc5e/six-1.17.0-py2.py3-none-any.whl", hash = "sha256:4721f391ed90541fddacab5acf947aa0d3dc7d27b2e1e8eda2be8970586c3274", size = 11050, upload-time = "2024-12-04T17:35:26.475Z" }, ] +[[package]] +name = "tbb" +version = "2023.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tcmlib" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/59/fd/8ca476c7b2513b1e64e08d3f5404c8ed19b34d0213000b5e23b3a91676c2/tbb-2023.2.0-py2.py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:7d80615b6e970f11671fa05b6eaa9483ac864fbfe525ac280271a78b37870b7c", size = 6864088, upload-time = "2026-10-16T12:38:06.333Z" }, + { url = "https://files.pythonhosted.org/packages/d0/41/2aeac799ab57e81898c8cc24f503fe301e12f19758bb1fe34d522764d3bb/tbb-2023.2.0-py3-none-win_amd64.whl", hash = "sha256:b39121cbdaff350fc61a448766cbb26807c523491d66e364838c9feeb3c6a0eb", size = 430857, upload-time = "2026-10-16T12:34:41.635Z" }, +] + +[[package]] +name = "tcmlib" +version = "1.6.0" +source = { registry = "https://pypi.org/simple" } +wheels = [ + { url = "https://files.pythonhosted.org/packages/a4/95/d2616129c971d989c1f5ec2ea697a6885165570c69d9fa50bfbde8195d26/tcmlib-1.6.0-py2.py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:46c2491988bfd18c4733eeb08aca6a386706a497b92cc51d155f37ddea003c14", size = 2802717, upload-time = "2026-10-16T12:38:19.821Z" }, + { url = "https://files.pythonhosted.org/packages/d7/a5/996458475dcc65f20ec20c0e3d4bbc175c87750ff9bb703908c373b2497a/tcmlib-1.6.0-py2.py3-none-win_amd64.whl", hash = "sha256:7f65c0a6d56f2b1383b3022e873175f5025db00a5c7d0aaeb019300c25f5d482", size = 371933, upload-time = "2026-10-16T12:34:53.372Z" }, +] + [[package]] name = "trimesh" version = "5.1.1" @@ -912,6 +972,18 @@ wheels = [ { url = "https://files.pythonhosted.org/packages/49/d3/b8441a820a491ddfc024b0b0cf0393375b75ea13866d9c66727e54c2fc80/typing_extensions-4.16.0-py3-none-any.whl", hash = "sha256:481caa481374e813c1b176ada14e97f1f67a4539ce9cfeb3f350d78d6370c2e8", size = 45571, upload-time = "2026-07-02T08:40:04.659Z" }, ] +[[package]] +name = "umf" +version = "1.2.0" +source = { registry = "https://pypi.org/simple" } +dependencies = [ + { name = "tcmlib" }, +] +wheels = [ + { url = "https://files.pythonhosted.org/packages/e9/98/4df9fdfac2af58f63652936c6f90c4dbf7c237f6aed2c4310c9583e177b0/umf-1.2.0-py2.py3-none-manylinux_2_28_x86_64.whl", hash = "sha256:238d186fdd9e9c0fe1489da95b19b0b79045fe26c4aa98bd0a022a2a3603c195", size = 429931, upload-time = "2026-10-16T12:37:02.109Z" }, + { url = "https://files.pythonhosted.org/packages/8c/7c/f35fe9eaae40a31cb7eafdc5689c90f3ba267391b79d010b4bac9f832a4b/umf-1.2.0-py2.py3-none-win_amd64.whl", hash = "sha256:8aab76eb1404812e753fe916de45299ed3c460b227558a41df768c31a663c11e", size = 296227, upload-time = "2026-10-16T12:33:40.537Z" }, +] + [[package]] name = "urllib3" version = "2.8.0"