diff --git a/.github/workflows/bench.yml b/.github/workflows/bench.yml new file mode 100644 index 0000000..9116a72 --- /dev/null +++ b/.github/workflows/bench.yml @@ -0,0 +1,38 @@ +name: bench + +# Weekly performance and result check of every analysis (packaging/bench.py). +# The result numbers must match packaging/bench_baseline.json on any machine; the times +# are compared with packaging/bench_baseline_ci.json once that file exists (CI runners +# are slower than a desktop: record it from this job's artifact first). +on: + schedule: + - cron: "17 3 * * 1" # Mondays 03:17 UTC + workflow_dispatch: + +jobs: + bench: + runs-on: ubuntu-22.04 + timeout-minutes: 60 + steps: + - uses: actions/checkout@v4 + + - uses: astral-sh/setup-uv@v5 + with: + python-version: "3.12" + + - name: Install + run: uv sync --locked + + - name: Benchmark + run: | + if [ -f packaging/bench_baseline_ci.json ]; then + uv run python packaging/bench.py --json bench.json --check packaging/bench_baseline_ci.json + else + uv run python packaging/bench.py --json bench.json --check packaging/bench_baseline.json --results-only + fi + + - uses: actions/upload-artifact@v4 + if: always() + with: + name: bench + path: bench.json diff --git a/CLAUDE.md b/CLAUDE.md index dca8d10..e4330a3 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -16,6 +16,7 @@ uv run kstruct --selftest-gui out.png # 창 열고 예제 해석 후 스크 uv run pytest # 전체 테스트 (~1분, Qt 창이 뜸) uv run pytest tests/test_fem_static.py::test_cantilever_tip_deflection # 단일 테스트 uv run ruff check --fix src tests && uv run ruff format src tests +uv run python packaging/bench.py [case…] [--profile] [--check packaging/bench_baseline.json] # 성능·결과 지문(사례마다 별도 프로세스, 기준의 1.5배 넘거나 결과가 1e-6 넘게 바뀌면 실패) uv run python packaging/build.py # 버전 스탬프(빌드 번호 +1) → PyInstaller → selftest → 설치 파일 uv run pyinstaller packaging/kstruct.spec --noconfirm # 프리즈만 (dist/KStruct/), 버전 스탬프 없음 ``` @@ -29,14 +30,14 @@ 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`가 조립·선형해. **직접 분해는 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`(한쪽 끝 가열 막대의 푸리에 급수, 긴 시간 → 정상 상태, 에너지 보존). +- **솔버는 자체 구현**(원래 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 제외; VTK는 쓰지 않는 VTK-m(viskores)·테스트·웹 모듈을 `VTK_DROP`으로 빼고 Linux에서 VTK 라이브러리만 strip — 다른 휠의 라이브러리는 auditwheel/patchelf로 고쳐져 있어 strip하면 깨질 수 있음), 배포본 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만 넘어도 발산했다. 과도 해석에서 복사·k(T)로 단계마다 바뀌는 행렬은 마지막 분해를 전처리로 쓰는 CG(`_pcg`, 상대 잔차 `TRANSIENT_CG_TOL` 1e-12, `TRANSIENT_CG_MAX` 8회 넘으면 새로 분해)로 푼다(60회 분해 → 1회). 온도 기준(`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`가 되고 요약 첫 메모로 경고한다. -- **비선형 정적 해석**(`fem/nonlinear.py`, `fem/plasticity.py`): `Project.plasticity`(재료 항복)·`large_deformation`(기하 비선형, 전체 라그랑주: 그린-라그랑주 변형률, 2차 PK 응력, 기하 강성)이 켜지면 `solve_cases`가 케이스마다 `solve_nonlinear`를 부른다. 재료는 J2 소성 + 3직선 경화(E → 항복 후 E_t(`Material.tangent_modulus`, JSON `Et`; 없으면 R_m을 변형률 10 %에서 만나도록 추정) → R_m 뒤 거의 평평 H = E·1e-4; R_m 넘어 계속 경화하면 붕괴 하중을 1/3 과대평가했다), radial return + consistent tangent. 취성재는 항복 없이 탄성(선형 판정 유지). 하중은 적응 증분(첫 0.1, 수렴하면 ×1.5, 실패하면 반으로, 최소 1e-3)으로 걸고 뉴턴 반복은 **접선 예측자**(강제 변위 증분까지 K로 미리 반영)+ 역추적 선탐색 — 예측자 없이 강제 변위 DOF만 움직이면 경계에 가짜 소성이 생겨 증분이 100개를 넘었다. 미수렴·특이 접선·변위 폭주(> 0.5·크기)·소성 변형률 50 %면 "버티지 못함"(`NonlinearInfo.load_factor` < 1). 끝까지 가면 하중을 빼서 영구 변형(`permanent`)을 구한다. 구속은 소거(T) 가능하면 소거, 아니면 페널티; 3만 DOF 이상 소거 모드는 p-멀티그리드. 접촉·볼트는 미지원(`unsupported` → 6단계 체크리스트 ✘). 응력 표시는 코시 응력, 항복한 요소는 적분점 평균(외삽이 R_m을 넘는 거짓 값을 만듦). 판정(`summary._judge_nonlinear`): 무너짐 → ❌(안전율 칸 = 도달 하중 비율), 소성 변형률 ≤ 0.2 % → ⚠ 국부 항복, 그 이상 → ❌ 영구 변형; 연성재는 특이점 구역 밖에서 잼. 피로는 비선형 실행에서 건너뛴다. 이론해 테스트 `tests/test_plasticity.py`, `tests/test_fem_nonlinear.py`(1축 2직선, 잔류 신장, 붕괴 하중, 엘라스티카 외팔보). +- **접촉**(`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회(상한 `MAX_FRICTION_SWEEPS`)이고, 마찰은 저항만 한다. 스윕 가속: 기준점 고정점에 Anderson 가속(`_accelerate`, 깊이 `ANDERSON_DEPTH` 5, 닫힌 쌍 집합이 바뀌면 이력 초기화 — 초기화하지 않거나 깊이 10이면 발산하는 증분이 있었다), 같은 스프링 상태의 행렬은 캐시(`_penalty_matrix`, 값·순서가 같아 비트 단위 동일), 같은 행렬에서 이어지는 Woodbury 풀이는 직전 해에서 `x + K⁻¹(rhs − K x)` 역대입 1회(풀이 겸 반복 개선; 예전엔 풀이+개선 2회), 잔차 `K u − f`는 슬레이브 행만(`_K_slave`). 마찰 스윕 도중 함께 생긴 열림·닫힘은 능동 집합 반복(`MAX_ITERATIONS` 40)이 아니라 스윕으로 센다 (예압 뒤 기준점이 풀리며 가장자리 쌍이 하나씩 열려 40회를 다 쓰고 '수렴 안 됨'이 났다; 쌍마다 `MAX_FLIPS`가 종료를 보장). 예압의 두 번째 풀이(잠금 당김력)는 첫 풀이의 기준점에서 출발(`solve(warm=True)`, 문제는 base = 0 그대로)하고, 첫 풀이(공칭 당김력, 잠금 계산용 접촉 상태)는 `friction_tol` 1e-2. 측정(`packaging/bench.py friction`, 볼트 3개 8.2만 DOF): 121 s → 56 s. 하지 말 것: 모든 쌍 자리를 넣은 고정 희소 패턴(순서 캐시는 맞지만 채움이 12 % 늘어 역대입이 더 느려짐), PARDISO 병렬 역대입 `iparm[24]`(메모리 대역폭이 한계라 효과 없음). 닫힌 쌍의 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`가 되고 요약 첫 메모로 경고한다. +- **비선형 정적 해석**(`fem/nonlinear.py`, `fem/plasticity.py`): `Project.plasticity`(재료 항복)·`large_deformation`(기하 비선형, 전체 라그랑주: 그린-라그랑주 변형률, 2차 PK 응력, 기하 강성)이 켜지면 `solve_cases`가 케이스마다 `solve_nonlinear`를 부른다. 재료는 J2 소성 + 3직선 경화(E → 항복 후 E_t(`Material.tangent_modulus`, JSON `Et`; 없으면 R_m을 변형률 10 %에서 만나도록 추정) → R_m 뒤 거의 평평 H = E·1e-4; R_m 넘어 계속 경화하면 붕괴 하중을 1/3 과대평가했다), radial return + consistent tangent(작은 변형은 탄성 접선을 한 번 조립하고 항복 중인 적분점만 `Bᵀ(D_t − D_e)B`로 보정 — `_elastic_values`). 취성재는 항복 없이 탄성(선형 판정 유지). 하중은 적응 증분(첫 0.1, 수렴하면 ×1.5, 실패하면 반으로, 최소 1e-3)으로 걸고 뉴턴 반복은 **접선 예측자**(강제 변위 증분까지 K로 미리 반영)+ 역추적 선탐색 — 예측자 없이 강제 변위 DOF만 움직이면 경계에 가짜 소성이 생겨 증분이 100개를 넘었다. 미수렴·특이 접선·변위 폭주(> 0.5·크기)·소성 변형률 50 %면 "버티지 못함"(`NonlinearInfo.load_factor` < 1). 끝까지 가면 하중을 빼서 영구 변형(`permanent`)을 구한다. 구속은 소거(T) 가능하면 소거, 아니면 페널티; 3만 DOF 이상 소거 모드는 p-멀티그리드. 접촉·볼트는 미지원(`unsupported` → 6단계 체크리스트 ✘). 응력 표시는 코시 응력, 항복한 요소는 적분점 평균(외삽이 R_m을 넘는 거짓 값을 만듦). 판정(`summary._judge_nonlinear`): 무너짐 → ❌(안전율 칸 = 도달 하중 비율), 소성 변형률 ≤ 0.2 % → ⚠ 국부 항복, 그 이상 → ❌ 영구 변형; 연성재는 특이점 구역 밖에서 잼. 피로는 비선형 실행에서 건너뛴다. 이론해 테스트 `tests/test_plasticity.py`, `tests/test_fem_nonlinear.py`(1축 2직선, 잔류 신장, 붕괴 하중, 엘라스티카 외팔보). - **강제 변위·탄성 지지·원격 하중·모멘트**: `FixtureKind.DISPLACEMENT`(`Fixture.displacement` 축별 mm, None = 자유)는 고정 DOF + `Constraints.values`; 정적 해석은 u = u_set + solve(f − Kp u_set)로 풀고(접촉은 `ContactSolver.solve(offset=…)`가 틈·접선 기준점에 반영, 마찰 증분에서 비례 증가), 소거(반복 솔버)는 강제 변위 DOF를 지나는 방정식이 있으면 포기한다. `FixtureKind.ELASTIC`(`Fixture.stiffness` 면 전체 N/mm, 법선 방향만)은 구속이 아니라 강성 `constraints.elastic_support`(k/A·∫NᵢNⱼdA·nnᵀ, TRI6 면 질량 `_tri6_mass`)로 K에 더하고(정적·모달·좌굴), 반력은 −K_s u. `LoadKind.REMOTE`(`vector` = F, `point` = 작용점)·`MOMENT`(`vector` = M, N·mm)는 `loads.rigid_face_forces`: 절점 면적 가중치 wᵢ로 F를 나누고 모멘트는 wᵢ(a × rᵢ), a = J⁻¹M — 합력·합모멘트가 정확하고 보 이론의 선형 분포. 이론해 테스트 `tests/test_fem_supports.py`. - **볼트**(`fem/bolts.py`): 머리·너트 아래 고리 면(없으면 구멍 벽)의 평균 변위를 잇는 축/전단 스프링. 예압은 "잠금" 방식: 예압만 걸린 상태에서 각 볼트가 정확히 P가 되도록 당김력 T를 `locked_pulls`로 풀고, 축력은 항상 모델 안의 실제 힘 T + k·신장량으로 보고한다(평형 보장). 예압이 있으면 두 부품 사이에 접촉/접합 연결이 필수. -- **좌굴**(`fem/buckling.py`): ARPACK `mode="buckling"`(K는 SPD, K_G는 부정치). 압축이 거의 없으면 반복 상한에서 끊고 "좌굴 없음"으로 처리. +- **좌굴**(`fem/buckling.py`): ARPACK `mode="buckling"`(K는 SPD, K_G는 부정치; 행렬은 CSR — CSC 곱이 느렸다). 압축이 거의 없으면 반복 상한에서 끊고 "좌굴 없음"으로 처리. 고유쌍은 모드+3개를 먼저 요청하고 양수(하중 반전 아닌 것)가 모자랄 때만 2·모드+4개로 다시(같은 분해) — 요청 1쌍이 역대입 ~10회다. - **표시 단위**(`units.py`): 계산은 항상 SI 내부 단위. 입력·목록·결과 필드·보고서만 `system_of(project)`(프로젝트 설정, 없으면 기준 팩의 `units`)로 변환한다. - **여러 부품**: 처음부터 `Project.parts` 리스트 + `connections`. STEP의 솔리드마다 Part 하나(이름은 XCAF `read_named_solids`로 읽고 어셈블리는 배치를 적용해 평탄화; STEP의 UTF-8 이름은 바이트당 한 코드포인트로 돌아오므로 `_decode_name`으로 복원), 맞닿은 면은 `geometry/contacts.py`가 자동 접합(바깥 법선이 마주보고 실제 겹침 면적이 있어야 함). - **메시 포맷**(`geometry/mesh_import.py`, `geometry/fbx.py`): 삼각형을 공유 위상 B-rep 솔리드로 만들고 같은 평면 삼각형을 병합. 열린 메시는 자동 보정하지 않고 거부한다(보정이 형상을 몰래 바꾸므로). FBX 리더는 자체 구현. @@ -45,6 +46,7 @@ CI(`.github/workflows/build.yml`)가 Windows/macOS/Linux에서 테스트 → PyI - **도움말**: 모든 UI 요소는 `resources/help/ko.json`의 키를 참조(`HelpButton`, `with_help`, `topic(key).short`; 영어 모드는 `help/en.json`, 없는 항목은 한국어). `tests/test_ui.py`가 UI 코드에 쓰인 키가 JSON에 다 있는지 검사하므로 새 접두어를 쓰면 그 테스트의 `PREFIXES`도 갱신. - **화면 디자인**(`ui/theme.py`): 색은 전부 `Theme` 토큰(LIGHT/DARK)에서 온다 — 위젯에 색을 직접 쓰지 말고 `theme.current()`를 읽거나 스타일시트가 고르는 속성을 붙인다(`primary="true"` 주 버튼은 패널당 하나, `role="hint"|"section"|"disclaimer"|"help"`, `compact`). `theme.apply()`가 Fusion 스타일 + 팔레트 + QSS + 글꼴을 앱 전체에 건다(`MainWindow.__init__`에서 호출, 선택은 `prefs.theme()`에 저장, `toggle_theme`). 글꼴은 번들 Noto Sans KR **가변 폰트라 기본 굵기가 Thin(100)** 이다: `theme.weighted()`로 `wght` 축을 지정해야 하고(본문 420, 굵게 700), 직접 그리는 글자(`StepDelegate`)도 이걸 쓴다. 콤보·스핀박스는 QSS로 테두리를 건드리지 않는다(화살표 그림이 사라짐). 툴바 아이콘은 `theme.icon()`이 코드로 그린다(이미지 파일 없음). 단계 표시는 가로형 `StepNav`(QListWidget 그대로라 `nav.currentRow()`로 구동, 완료 표시는 `STEP_DONE` 데이터 = `MainWindow._step_done`). 프로젝트가 없으면 오른쪽은 시작 화면(`pane` 0번), 있으면 3D 뷰(1번). 3D 배경·모서리·색 막대 글자는 `viewer.apply_theme`. - **UI**: `ui/main_window.py`가 Project·mesh·result를 소유하고, `ui/steps.py`의 7개 패널이 이를 편집해 `changed`를 보낸다. 메싱·해석은 `ui/worker.run_job`으로 백그라운드 실행. `run_job`이 돌려주는 `JobHandle.cancel()`(취소 버튼 → `MainWindow.cancel_job`)은 협조적 취소라 다음 진행 보고(`progress`)에서 `Cancelled`가 나고, 메싱 대기 중에는 `generate_mesh(check=progress.check)`가 0.25초마다 확인해 Netgen 워커 프로세스를 죽인다. 분해(factorization) 도중에는 멈추지 않는다. 결과 종류(Static/Modal/Thermal)에 따라 결과 패널 필드가 바뀐다. +- **3D 뷰 도구**(`ui/viewer.py` 위쪽 `viewStrip`): '보기' 메뉴(표준 보기 `set_view`, 단축키 0·1·3·7, Ctrl = 반대쪽), 반투명, 그리고 3~5단계에서만 보이는 선택 도구(`selection_enabled` 세터가 켜고 끔): 영역 선택(B, `enable_rubber_band_2d_style` + `vtkHardwareSelector`로 **가려지지 않은** 셀만; 선택 동안 SSAA를 꺼야 하고 depth peeling은 쓰지 말 것 — 둘 다 선택 버퍼를 망가뜨려 뒤쪽 면이 잡힌다), 같은 크기 모두(S, `face_info.similar_faces`: 원통은 반지름, 평면은 면적+방향), 이어진 면(T, `tangent_faces`: `BRepLib.ContinuityOfFaces`로 G1 이음 추적 — `EncodeRegularity`는 형상에 기록해 메시 캐시 키(brep 바이트)를 바꾸므로 쓰지 말 것), 선택 해제(Esc). 단축키는 뷰어 위젯에 `WindowShortcut`으로 붙인 QAction이라 메뉴가 닫혀 있어도 동작하고, 입력 칸의 숫자 입력이 우선한다. 오른쪽 클릭 메뉴(`context_menu_actions`)와 1단계 부품 목록 메뉴의 단독 보기·숨기기·반투명은 **화면 전용**(`_view_hidden`, `_translucent`, 저장 안 함) — 해석 제외는 체크 상자(`Part.visible`)뿐. 목록 항목의 면은 `steps.FaceHighlighter`가 하늘색으로 칠한다(`set_highlight`). 해석 실패 시 `diagnose.problem_parts`(고정이 닿지 않는 부품, 접촉으로만 붙은 부품, 볼트 예압 쌍, 열 해석은 `SolverError.parts`)를 빨갛게 칠하고(`mark_problem`, 다음 편집에서 지움) 경고 상자에 '○ 단계로 가기'를 단다(`MainWindow.warn(message, fix_step)`). 창 단축키(Alt+1~7, Ctrl+M, F5, Del, Ctrl+/)는 `_build_shortcuts`, 단축키 목록은 실제 QAction에서 만든다(`shortcut_entries`). 파일 끌어다 놓기(`dropEvent` → `open_path`), 저장 안 한 변경이 있으면 열기 전에 묻는다(`may_discard`, 테스트는 `ask_before_close = False`로 끔). 왼쪽 패널은 가로 스크롤이 없으므로 `_fit_side`가 현재 단계 패널의 최소 폭만큼 최소 폭을 넓힌다(`tests/test_layout.py`가 1280×720, 한/영, 가장 좁게 끈 상태에서 검사). - **단면·내보내기**: 뷰어는 평소 TRI6 겉면만 그리지만 단면 보기는 `viewer.linear_volume_grid`(TET10을 선형 사면체 8개로 분할; VTK clip은 비선형 셀을 못 다룸)를 잘라 보여준다. VTU 내보내기는 `volume_grid`(VTK 2차 사면체, 중간 절점 순서 `_TET10_TO_VTK`로 재배열 — Netgen과 VTK의 중간 절점 순서가 다르다). 결과 열 정의는 `report/export.py.result_columns` 한 곳. - **3D 뷰 수명**: `ModelViewer`는 `QtInteractor(off_screen=False)`로 만든다 — CI의 headless 액션이 `PYVISTA_OFF_SCREEN=true`를 걸면 기본값으로는 `plotter.iren`이 None이라 선택이 깨진다. 창을 닫을 때 `viewer.shutdown()`으로 렌더 창을 해제한다(안 하면 테스트가 창 수십 개를 열 때 소프트웨어 OpenGL(Xvfb/Mesa)이 `render()`에서 segfault). 로컬 Linux에서 UI 테스트는 `PYVISTA_OFF_SCREEN=true xvfb-run -a uv run pytest`로 CI와 같게 돌린다. - **3D 텍스트 한글**: VTK 기본 글꼴에 한글이 없어 색 막대에 번들 Noto Sans KR(OFL)을 지정한다(`viewer._use_korean_font`). @@ -52,7 +54,7 @@ CI(`.github/workflows/build.yml`)가 Windows/macOS/Linux에서 테스트 → PyI - **응력 특이점**(`fem/singularity.py`): 필렛 없는 오목 모서리(경계 삼각형 쌍의 이면각으로 판정. 법선은 반드시 **공유 모서리에서의 TRI6 곡면 법선**(`_tri6_normal`)으로: 평평한 삼각형 법선을 쓰면 둘로 나뉜 원통면의 이음선·필렛 접선이 '날카로운 모서리'로 잡혀 구멍의 진짜 응력집중을 특이점으로 면제했다)와 완전 고정면 가장자리 절점을 표시하고, 그 주변(요소 1.5개 또는 부품 대각선 3% 중 큰 값)을 제외한 "특이점 제외(핫스팟)" 응력·안전율을 `report.summary`가 함께 보고한다. 연성재 판정은 핫스팟 값(`PartSummary.governing_fos`), 취성재는 최대값 기준. 피로도 연성재는 특이점 구역 밖에서 판정한다(`fatigue_excludes_singularity`, 메모로 고지). 취성재 안전율은 인장(Rm/σ1)과 압축(`Material.compressive_strength`(JSON `ucs`), 없으면 Rm / |σ3|) 중 작은 값. 예제 브래킷의 판정이 메시 등급과 무관하게 같아야 한다(`tests/test_improvements.py`). - **숨긴 부품**: 해석·메시·자동 접합은 항상 `model.active_project(project)`(보이는 부품 + 그 부품만 참조하는 고정·하중·연결·볼트)를 쓴다. 숨긴 부품에 걸린 조건은 6단계 체크리스트에 "제외" 표시. - **권장 안전율·사용자 재료**: 판정 기준은 `standards.effective_pack(project)`(`Project.target_overrides` 반영), 재료 조회는 `standards.project_materials(project)`(내장 + `Project.custom_materials`). `standards.pack()`/`materials()`를 UI·요약·보고서에서 직접 쓰지 말 것. 사용자 재료는 .kst에 저장되고 `paths.user_materials_path()` 라이브러리에도 복사된다. -- **메시 크기**: `MESH_PRESETS`는 `MeshPreset(분할수, grading, 두께 방향 요소 수)`. `fem.mesh.face_sizes`가 `geometry/thickness.py`(테셀레이션에 자체 Möller–Trumbore 레이 캐스팅, 면별 중앙값 두께)로 얇은 면의 크기를 두께/요소수로 줄이고 `Project.mesh_refinements`를 합친 뒤 Netgen에 면별 `maxh`로 넘긴다. Netgen은 `geo.shape.faces[i].maxh`를 설정한 뒤 **`OCCGeometry(shape)`로 다시 감싸야** 반영된다(원래 geo에 바로 설정하면 무시됨). netgen은 OCP와 다른 OCCT 사본이라 주 프로세스에서 import하면 `faces_of`가 빈 목록을 돌려주므로 반드시 워커 프로세스 안에서만 import. +- **메시 크기**: `MESH_PRESETS`는 `MeshPreset(분할수, grading, 두께 방향 요소 수)`. `fem.mesh.face_sizes`가 `geometry/thickness.py`(테셀레이션에 자체 Möller–Trumbore 레이 캐스팅, 면별 중앙값 두께)로 얇은 면의 크기를 두께/요소수로 줄이고 `Project.mesh_refinements`를 합친 뒤 Netgen에 면별 `maxh`로 넘긴다. Netgen은 `geo.shape.faces[i].maxh`를 설정한 뒤 **`OCCGeometry(shape)`로 다시 감싸야** 반영된다(원래 geo에 바로 설정하면 무시됨). netgen은 OCP와 다른 OCCT 사본이라 주 프로세스에서 import하면 `faces_of`가 빈 목록을 돌려주므로 반드시 워커 프로세스 안에서만 import. 워커 프로세스(spawn Pool)는 **유지·재사용**한다(`_get_pool`, 앱 시작 때 `prewarm()`이 2개를 띄움; 생성+import 1.4 s가 메시마다 들던 것을 없앰). 시간 초과·취소·오류 때만 `drop_pool()`로 죽인다(Netgen 안에서 멈췄을 수 있음). Netgen 스레드(`TaskManager`)는 이득이 작고(1.2 → 1.0 s) 멈춤 위험이 있어 쓰지 않는다. - **하중 케이스**: `Project.cases`(`LoadCase`) + `active_case`. `project.loads`는 활성 케이스의 리스트(프로퍼티)라 기존 코드가 그대로 동작하고, 강도 해석은 `solve_cases`가 `with_case(project, i)`(얕은 뷰, 복사 없음)로 모든 케이스를 푼다. UI는 `case_results`에 케이스별 (이름, 결과, 요약)을 들고 `select_case`로 바꿔 보여주며, 열·좌굴은 활성 케이스만 쓴다. 프로젝트 파일 v2는 `cases`를 저장하고 v1의 평면 `loads`도 읽는다. - **회전 하중**(`fem/loads.py`): 토크는 선택 면에 반지름에 비례하는 접선 트랙션(합 모멘트 = T 정확), 베어링 하중은 구멍 원통면의 하중 방향 절반에 코사인 분포(합력 = F가 되도록 잔차를 보정), 원심력은 ρω²r 체적력. 축은 `Load.point` + `vector`(토크·원심력, 없으면 선택 원통면의 축), 베어링은 항상 원통면 축. 내부 단위 N·mm, rad/s이며 표시는 `units`의 `torque`(N·m / lbf·in)·`speed`(rpm). - **조건 문구**: 고정·하중·연결 설명은 `report/describe.py` 한 곳에서 만들어 패널과 PDF가 같은 문장을 쓴다. 보고서 수치는 모두 `units.fmt`를 거친다. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index d38fcff..831d8eb 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1,6 +1,7 @@ # KStruct 기능 완성도 검토와 문서화·상용화 계획 > 2026-10-25 기준 코드(`4e967ee`)를 읽고, 테스트·셀프테스트·벤치마크를 실제로 돌려 확인한 결과입니다. +> **최신 계획은 §8(2026-11-29)을 보세요.** > 이 문서는 (1) 지금 무엇이 되고 무엇이 안 되는지, (2) 상용 배포 전에 고칠 것, (3) 제품과 함께 **써내야 할 문서**와 각 문서에 들어갈 내용을 정리합니다. ## 0. 진행 상황 (2026-10-25) @@ -49,7 +50,7 @@ P0 중 코드로 해결되는 항목은 구현했습니다. 아래 표의 "상 > **목표 조정 (2026-11-18)**: KStruct는 상용 소프트웨어 *수준의 품질*을 목표로 하며 판매·외부 배포용 제품이 아니다. 그래서 P0-6(코드 서명·공증)·P0-7(EULA·라이선스)과 §6의 영업·법무 문서는 할 일 목록에서 뺀다. 이미 넣은 서명 단계는 인증서가 없으면 아무 일도 하지 않으므로 그대로 둔다. -남은 것(품질 기준): CI 러너 문제(Windows/macOS 검증), 모달·좌굴·접촉 큰 모델의 성능(희소 분해가 지배), 영어 UI(P1-7, 필요할 때만). +남은 것(2026-11-29 갱신): 영어 UI(v0.3.0)와 PARDISO 직접 분해(v0.3.1)는 끝났고 Windows/Linux CI·릴리스는 자동화됐다. macOS 러너, 마찰·좌굴·과도 열 성능, 조작성은 **§8 다음 개선 계획**에 정리했다. ## 1. 결론 요약 @@ -274,3 +275,111 @@ OS별 설치 절차(서명 전이면 SmartScreen/Gatekeeper 우회 안내도 필 3. **P0-8~P0-11(재료·안전율·고지·입력 보존)**: 1~2주. 4. 문서 §6.1~§6.6 작성 — P0와 병행 가능. 매뉴얼은 `help/ko.json`에서 생성, 검증 보고서는 테스트에서 생성하도록 스크립트화하면 버전마다 자동 갱신됨. 5. 이후 P1-1(토크·베어링·원심력), P1-2(하중 케이스), P1-3(국부 메시) 순으로 적용 범위를 넓힘. + +## 8. 다음 개선 계획 (2026-11-29, v0.3.2 기준) + +§5의 P0·P1은 서명·EULA(목표에서 제외)를 빼고 모두 끝났다. 영어 UI(P1-7)와 PARDISO 직접 분해(P1-8)도 v0.3.x에 들어갔다. 이 절은 그다음 계획이다. 원칙은 이렇다. + +- **측정 먼저**: 성능 항목은 아래 기준값(같은 4코어 PC, `bench.py`)을 다시 재서 완료를 판정한다. +- **결과가 달라지면 안 된다**: 성능 작업은 기존 결과와 1e-9 이내로 같아야 한다. 마찰 해석은 비트 단위로 같아야 한다. +- **새 해석 기능은 이론해 테스트와 함께** 넣는다(`tests/test_fem_*.py`). +- **비전문가 기준**: 기능을 늘리기보다 지금 기능을 "실수 없이, 덜 클릭해서" 쓰게 하는 것을 앞에 둔다. + +규모: S = 1~3일, M = 1~2주, L = 3주 이상(1인 기준). + +### 8.1 성능 기준값 (v0.3.2, PARDISO 적용 후) + +| 사례 | 시간 | 지배 요인 | +|------|------|-----------| +| 정적(브래킷 세밀) | 3.3 s | 메싱 포함 | +| 모달 | 6.6 s | 이동-역변환 고유치 | +| 좌굴 | 28 s | ARPACK 역대입 ≈140회(ncv 조정 효과 없음) | +| 열(정상) | 2.7 s | — | +| 과도 열 | 28 s | 60단계마다 재분해 | +| 비선형 3.8만 DOF | 17 s | 요소 루프 `_evaluate`(파이썬), 멀티그리드 CG | +| 볼트+예압 | 15 s | — | +| 볼트+마찰 8.2만 DOF | 115 s | 역대입 1,207회 + `csr_plus_csr`·`_penalty` 파이썬 오버헤드 | +| 메싱 | 3.3 s | 워커 생성 ≈1 s + Netgen 2.06 s(단일 스레드; 4스레드면 1.38 s) | + +### 8.2 성능 (PF) + +| ID | 항목 | 방안 | 규모 | 완료 기준 | +|----|------|------|------|-----------| +| PF-1 | **마찰 접촉 가속** | (a) 페널티 행렬의 희소 패턴을 고정하고 값만 갱신한다(`csr_plus_csr`·`_penalty` 재조립 제거). (b) 증분 사이에 기준점·능동 집합을 이어서 시작한다(warm start). (c) 그래도 반복이 수백 회면 미끄럼 쌍에 일관 접선을 쓰는 semi-smooth Newton을 검토한다. | M | 115 s → 40 s 이하. 접촉 상태·반력은 기존과 같고 실행마다 비트 단위로 같음 | +| PF-2 | **좌굴 고유치 블록화** | 역대입 140회를 벡터 하나씩 하지 않고, PARDISO 다중 우변으로 블록 부분공간 반복(LOBPCG 또는 블록 Lanczos)을 한다. 같은 분해를 모달 해석에도 쓴다. | M | 28 s → 10 s 이하. 좌굴 하중 배수가 1e-6 이내로 같음 | +| PF-3 | **과도 열 재분해 줄이기** | 선형이면 분해를 1회만 한다(지금 경로가 재분해하는 원인을 확인). 복사·k(T)이면 PARDISO 수치 분해만(phase 22, 기호 분석 재사용) 하거나 직전 단계 해로 시작하는 CG를 쓴다. | S~M | 28 s → 10 s 이하. 푸리에 급수 테스트 유지 | +| PF-4 | **메싱 멀티스레드·워커 예열** | 워커 안에서 `pyngcore.SetNumThreads` + `TaskManager`를 쓴다. 앱이 시작될 때 Netgen 워커 1개를 미리 띄운다(spawn 1 s 숨기기). | S | 메싱 3.3 s → 2 s 이하. 면 번호 순서 테스트 유지 | +| PF-5 | **비선형 요소 계산 벡터화** | `_evaluate`의 요소·적분점 루프를 numpy 일괄 연산(einsum)으로 바꾼다. 부족하면 Numba(BSD, 라이선스 문제 없음)를 쓴다. | M | 17 s → 6 s 이하. 소성·엘라스티카 테스트 유지 | +| PF-6 | **시작 시간** | 배포본의 냉시작을 잰다. pyvista·scipy·netgen 지연 import, 시작 화면부터 먼저 그리기. | S | 측정값 기록 + 창 표시까지 3 s 이하(Windows 배포본) | +| PF-7 | **설치 파일 크기** | Linux 609 MB / Windows 270 MB. 번들 내용을 분석하고 안 쓰는 Qt·VTK 모듈과 중복 공유 라이브러리를 뺀다. | S | Linux 350 MB 이하, selftest 통과 | +| PF-8 | **성능 회귀 감시** | `bench.py`를 저장소(`packaging/bench.py`)로 옮긴다. CI 주간 작업이 시간을 기록하고 기준의 1.5배를 넘으면 실패시킨다. | S | 위 기준값 표가 CI 산출물로 자동 갱신 | + +### 8.3 기능 (FT) + +| ID | 항목 | 근거 | 방안 | 규모 | 완료 기준 | +|----|------|------|------|------|-----------| +| FT-1 | **메시 수렴 확인** | P0-1(b)는 핫스팟 표시로 대신했고 자동 확인은 없다 | 결과 패널에 '메시 확인' 버튼을 둔다. 핫스팟 주변을 국부 세분화(또는 한 등급 세밀)해 다시 풀고 최대·핫스팟 응력 변화율을 보여 준다. 5 % 넘게 변하면 "메시에 민감" 배지를 단다. | M | 인장봉: 변화 < 1 %. 예제 브래킷: 핫스팟 변화 < 5 %, 특이점 최대값은 '민감'으로 표시 | +| FT-2 | **재료 바꿔 보기(즉시)** | 비전문가의 첫 질문은 "다른 재료면?" | 선형 정적 + 단일 재료(ν가 같음)면 응력장이 그대로이므로 다시 풀지 않고 안전율만 다시 계산한다. ν가 다르거나 여러 재료면 "다시 해석 필요"라고 안내한다. | S | 같은 모델을 재해석한 결과와 안전율이 일치 | +| FT-3 | **하중 케이스 포락(최악값) 보기** | P1-2는 케이스 비교표만 있다 | 절점별로 모든 케이스의 최대 응력·최소 안전율을 내는 '포락' 가상 케이스, 보고서 표 | S~M | 두 케이스 포락 = 각 절점 max 테스트 | +| FT-4 | **조화 응답(주파수 응답)** | 진동 해석이 고유진동수 확인에서 멈춘다 | 모드 중첩, 감쇠비 입력, 주파수 범위 스윕, 선택 점의 진폭·응력 곡선, 공진 시 최대 응력 판정 | M~L | 1자유도·외팔보 이론해(동적 증폭 계수) 테스트 | +| FT-5 | **비선형 + 접촉·볼트** | 지금은 `unsupported`(체크리스트 ✘) | 뉴턴 반복 안에 능동 집합 접촉을 넣는다(마찰 없음부터). 볼트 예압은 첫 하중 단계로 건다. | L | 헤르츠 접촉 근사·볼트 이음 소성 테스트 | +| FT-6 | **설계 조언 구체화** | 판정 뒤 "무엇을 바꾸나"가 막연 | 최대 응력 위치의 면 종류(오목 모서리·구멍·얇은 벽)에 따라 조언한다(필렛 R, 두께, 재료). 두께·하중 배율은 선형 스케일 추정치로 "약 몇 배"를 보여 준다. 근거 없는 수치는 쓰지 않는다. | M | 예제 3종에서 조언 문구 스냅샷 테스트 | +| FT-7 | 셸·빔 요소, 과도 동역학(충격) | 얇은 판·프레임 비용, 낙하 | P2 유지. FT-4 이후 다시 검토 | L | — | + +### 8.4 UI (UI) + +| ID | 항목 | 방안 | 규모 | 완료 기준 | +|----|------|------|------|-----------| +| UI-1 | **결과 읽기 쉽게** | 최대·최소 위치 마커와 값 라벨(클릭 프로브는 있음). 변형 배율 직접 설정(지금은 자동만). 색 막대 범위·단계 수 지정. 색각 이상 친화 색표(cividis) 선택 | M | 결과 화면에서 최대값 위치를 한 번에 찾음(사용성 점검 5명 중 5명) | +| UI-2 | **표준 보기·뷰 큐브** | 정면/윗면/옆면/등각 버튼과 단축키(지금은 '화면 맞춤'만), 작은 방향 큐브, 투명·모서리만 표시 | S | 키보드만으로 6방향 보기 | +| UI-3 | **화면 크기·배율 검사 자동화** | 지난번 수동으로 한 `widths.py` 점검을 테스트로 만든다. 1280×720·150 % 배율에서 한/영 두 언어로 잘린 라벨·넘치는 툴바를 검사한다. | S | CI에서 잘림 0건 | +| UI-4 | **결과 패널 정보 구조** | 판정 카드 → 근거(어느 부품·어디·왜) → 상세 수치 순으로 접고 펼친다. 메모가 많을 때 중요도 순으로 정렬한다. | S~M | 메모 10개 이상 모델에서 첫 화면에 판정·근거가 보임 | +| UI-5 | **macOS 빌드** | CI 러너가 배정되지 않아 매번 취소된다. 러너 라벨을 바꾸거나(macos-14 arm64) 별도 작업으로 분리해, 실패해도 Windows/Linux 릴리스를 막지 않게 한다. MKL이 없으니 SuperLU 경로 성능도 따로 잰다. | S~M | dmg 산출, selftest 통과 | +| UI-6 | 글자 크기·고대비 | 설정에서 글자 크기 3단계, 고대비 테마 토큰 | S | 테마 토큰만으로 구현(위젯 직접 색 없음) | + +### 8.5 조작성 (UX) + +| ID | 항목 | 방안 | 규모 | 완료 기준 | +|----|------|------|------|-----------| +| UX-1 | **면 선택 도우미** | 지금은 클릭 한 번에 면 하나다. 추가할 것: 사각형(드래그) 선택, '같은 구멍 모두'(같은 반지름 원통면), '이어진 면'(접한 면 연쇄), 선택 반전·해제(Esc), 목록 항목에 마우스를 올리면 3D 강조 | M | 볼트 구멍 8개 고정을 클릭 2번 안에 끝냄 | +| UX-2 | **부품 단독 보기·투명** | 부품 우클릭 → 단독 보기 / 숨기기 / 반투명. 안쪽 면 선택용 | S | 조립품 안쪽 접촉면을 선택할 수 있음 | +| UX-3 | **측정 도구** | 두 점 거리, 면 면적, 구멍 지름·축 | S~M | 하중 입력 전에 면적을 확인해 압력↔힘 환산 가능 | +| UX-4 | **단축키 체계** | 1~7 단계 이동, F5 해석, Ctrl+M 메싱, Del 조건 삭제, 보기 단축키, 단축키 목록(도움말 메뉴). 지금은 열기·저장·실행 취소·F만 있다. | S | 단축키 목록이 실제 동작과 일치(테스트) | +| UX-5 | **첫 사용 안내** | 시작 화면에서 예제 3종 + 5분 둘러보기(단계마다 강조 오버레이와 한 줄 설명, 건너뛰기). 각 단계가 비어 있을 때 "다음에 할 일" 안내 | M | 처음 쓰는 사람이 도움 없이 첫 결과까지 10분 이내(사용성 점검) | +| UX-6 | **오류를 3D로 보여 주기** | `SolverError`(안 붙잡힌 부품, 접촉 불안정, 온도 기준 없음)일 때 해당 부품·면을 빨갛게 강조하고, "고치는 방법" 버튼으로 해당 단계를 열어 준다. | S~M | 오류 3종 각각 강조·이동 UI 테스트 | +| UX-7 | **조건 묶음(템플릿)·대칭 도우미** | 자주 쓰는 고정·하중 묶음 저장/불러오기(볼트 구멍 고정, 자중, 압력). '대칭면' 버튼은 미끄럼 지지로 만들어 주고 결과 해석 안내를 붙인다. | S~M | 템플릿을 다른 모델에 적용하면 같은 종류 면에 매칭 | +| UX-8 | **결과 비교 화면** | 지금은 직전 결과와 비교하는 문구 한 줄이다. 두 결과(설계 변경 전후, 케이스) 나란히 보기와 차이 색 지도를 넣는다(같은 메시일 때). | M | 같은 메시 두 실행의 차이 = 0 표시 | +| UX-9 | **단위 붙여 입력·수식** | 입력칸에 "10 kN", "2 in", "=1500*9.81"을 받아 표시 단위로 바꾼다. | S | 단위 파서 테스트(SI·US, 잘못된 입력 거부) | +| UX-10 | **파일 끌어다 놓기** | 창에 STEP/메시/.kst를 끌어다 놓으면 연다. 지금은 없다. | S | UI 테스트 | + +### 8.6 진행 상황 + +| 묶음 | 항목 | 상태 | +|------|------|------| +| v0.4 조작성 | UX-1 면 선택 도우미(영역 선택·같은 크기 모두·이어진 면·Esc·목록 항목 강조) | ✅ `ui/viewer.py`, `geometry/face_info.py`, `steps.FaceHighlighter` | +| | UX-2 부품 단독 보기·숨기기·반투명(화면 전용, 3D·부품 목록 오른쪽 클릭) | ✅ | +| | UX-4 단축키 체계 + 단축키 목록(Ctrl+/) | ✅ `MainWindow._build_shortcuts`, `shortcut_entries` | +| | UI-2 표준 보기(보기 메뉴·숫자 키) | ✅ `ModelViewer.set_view` | +| | UX-10 파일 끌어다 놓기(+ 저장 안 한 변경 확인) | ✅ `dropEvent`, `may_discard` | +| | UX-6 오류 부품 빨간 표시 + '단계로 가기' | ✅ `kstruct/diagnose.py`, `MainWindow.report_failure` | +| | UI-3 잘림 검사 자동화 | ✅ `tests/test_layout.py` — 기존 결함 발견·수정: 왼쪽 패널을 최소 폭(340 px)으로 줄이면 고정·해석 단계 등 6개 패널의 오른쪽이 잘렸음 → `_fit_side` | + +| v0.5 성능 | PF-8 성능 회귀 감시 | ✅ `packaging/bench.py`(결과 지문 + 시간, `--check`), 주간 CI `bench.yml` | +| | PF-1 마찰 접촉 | ✅ 121 s → 55 s. 결함도 수정: 볼트+마찰 예제(보통 메시)의 예압 풀이가 '수렴 안 됨'으로 끝나던 문제 | +| | PF-3 과도 열 | ✅ 10.1 s → 5.4 s (이전 분해로 전처리한 CG) | +| | PF-4 메싱 | ✅ 작업 프로세스 예열·재사용: 앱 안에서 3.0 s → 1.6 s. Netgen 스레드는 1.2 → 1.0 s뿐이고 멈춤 위험이 있어 보류 | +| | PF-2 좌굴 | ⚠ 20.4 s → 14.3 s (목표 10 s 미달: 남은 시간은 역대입 100회 + 정적 해석) | +| | PF-5 비선형 | ⚠ 14.8 s → 8.7 s (목표 6 s 미달: 멀티그리드 CG가 남음) | +| | PF-7 설치 파일 | ⚠ Linux tar.gz 609 → 560 MB (안 쓰는 VTK-m·테스트·웹 모듈 제외, VTK 라이브러리 strip). 350 MB 목표는 OCP 284 MB·MKL ~500 MB(CPU별 커널)가 남아 미달 | +| | (덤) 배포본 GUI selftest | ✅ 3분 → 10초: 종료 때 '저장할까요?' 창이 떠서 안전 타이머까지 기다리던 문제 | + +v0.5 측정(같은 4코어 PC, `packaging/bench.py`, 해석 시간): 정적 3.5 → 2.7 s, 모달 6.2 → 5.7 s, 좌굴 20.4 → 14.3 s, 과도 열 10.1 → 5.4 s, 비선형 14.8 → 8.7 s, 볼트 12.9 → 11.8 s, 마찰 120.8 → 55.4 s. 결과 지문은 마찰(수렴 수정으로 변위 +0.5 %)을 빼고 모두 1e-6 안에서 같음. + +### 8.7 진행 순서 제안 + +1. **v0.4 — 조작성 묶음(3~4주)**: UX-1(면 선택), UX-4(단축키), UI-2(표준 보기), UX-10(끌어다 놓기), UX-2(단독 보기), UX-6(오류 강조), UI-3(잘림 검사). 매일 쓰는 불편을 먼저 없앤다. 대부분 S라 효과 대비 비용이 가장 낮다. +2. **v0.5 — 성능 묶음(3~4주)**: PF-8(회귀 감시)을 먼저 깔고 PF-1(마찰), PF-3(과도 열), PF-4(메싱), PF-2(좌굴), PF-5(비선형) 순. PF-7(크기)도 같이 한다. +3. **v0.6 — 결과 신뢰·이해(3~4주)**: FT-1(메시 수렴 확인), UI-1(결과 마커·배율), FT-2(재료 바꿔 보기), FT-3(포락), UI-4(결과 패널), UX-5(첫 사용 안내). +4. **v0.7 이후 — 적용 범위**: FT-4(조화 응답) → FT-6(설계 조언) → FT-5(비선형+접촉) → UX-3/7/8/9, UI-5(macOS)는 러너가 해결되는 대로. + +각 버전은 지금처럼 브랜치 → PR → 병합 → `workflow_dispatch` 릴리스로 내고, 버전마다 이 표의 "완료 기준"을 PR 설명에 체크리스트로 옮긴다. diff --git a/packaging/bench.py b/packaging/bench.py new file mode 100644 index 0000000..7097eb9 --- /dev/null +++ b/packaging/bench.py @@ -0,0 +1,280 @@ +"""Performance benchmark of every analysis on the built-in sample models. + + uv run python packaging/bench.py # all cases, table on screen + uv run python packaging/bench.py friction transient # some cases + uv run python packaging/bench.py --json out.json # also write the numbers + uv run python packaging/bench.py --check packaging/bench_baseline.json # fail if slower + uv run python packaging/bench.py friction --profile # where the time goes + +Each case runs in its own process (no caches shared between cases). Besides the times it +records a few result numbers ("fingerprint"): a speed-up must leave them unchanged, and +--check fails when one moves by more than its tolerance. +""" + +from __future__ import annotations + +import argparse +import json +import os +import subprocess +import sys +import tempfile +import time +from pathlib import Path + +# case -> mesh grade (the bracket cases use fine meshes, the assemblies normal ones) +CASES = { + "static": "fine", + "modal": "fine", + "buckling": "fine", + "thermal": "fine", + "transient": "fine", + "nonlinear": "normal", + "bolted": "normal", + "friction": "normal", +} +RESULT_TOLERANCE = 1e-6 # relative change of a fingerprint number still called "the same" +# friction iterates to a tolerance (contact.FRICTION_TOL): another machine's BLAS can stop +# it at a slightly different point +CASE_TOLERANCE = {"friction": 1e-3} + + +def _bracket(case: str): + from kstruct.geometry.face_info import face_at + from kstruct.geometry.samples import l_bracket, write_step + from kstruct.geometry.step_import import load_cad + from kstruct.model import AnalysisKind, FaceRef, Fixture, FixtureKind, Load, LoadKind + + project = load_cad(write_step(l_bracket(), Path(tempfile.mkdtemp()) / "bracket.step")) + s = project.parts[0].shape + back, top = FaceRef(0, face_at(s, (0, 30, 40))), FaceRef(0, face_at(s, (90, 30, 8))) + project.parts[0].material_id = "s355" + project.fixtures = [Fixture(FixtureKind.FIXED, [back])] + project.loads = [Load(LoadKind.FORCE, [top], vector=(0, 0, -3000.0))] + if case == "modal": + project.analysis = AnalysisKind.MODAL + elif case == "buckling": + project.analysis = AnalysisKind.BUCKLING + project.loads = [Load(LoadKind.FORCE, [top], vector=(-30000.0, 0, 0))] + elif case in ("thermal", "transient"): + project.analysis = AnalysisKind.THERMAL + project.fixtures = [] + project.loads = [ + Load(LoadKind.HEAT_FLOW, [top], magnitude=15.0), + Load(LoadKind.CONVECTION, [back], magnitude=50.0), + Load( + LoadKind.RADIATION, + [FaceRef(0, face_at(s, (50, 30, 16)))], + magnitude=0.9, + ambient=20.0, + ), + ] + if case == "transient": + project.thermal_duration = 600.0 + project.initial_temperature = 20.0 + elif case == "nonlinear": + project.plasticity = True + project.loads = [Load(LoadKind.FORCE, [top], vector=(0, 0, -9000.0))] + return project + + +def _bolted(case: str): + from kstruct.fem.bolts import hole_axis, recommended_preload, suggest_size + from kstruct.geometry.contacts import find_touching_faces + from kstruct.geometry.face_info import face_at + from kstruct.geometry.samples import bolted_plates, write_step + from kstruct.geometry.step_import import load_cad + from kstruct.model import ( + Bolt, + ConnectionKind, + FaceRef, + Fixture, + FixtureKind, + Load, + LoadKind, + ) + + project = load_cad(write_step(bolted_plates(), Path(tempfile.mkdtemp()) / "bolted.step")) + lower, upper = (p.shape for p in project.parts) + for p in project.parts: + p.material_id = "s355" + project.connections = find_touching_faces(project) + project.connections[0].kind = ConnectionKind.CONTACT + if case == "friction": + project.connections[0].friction = 0.2 + for n, (x, y) in enumerate(((10, 10), (70, 10), (40, 50)), start=1): + a = FaceRef(0, face_at(lower, (x + 5.5, y, 2.5))) + b = FaceRef(1, face_at(upper, (x + 5.5, y, 7.5))) + size = suggest_size(min(hole_axis(project, r)[2] for r in (a, b))) + project.bolts.append(Bolt(a, b, size, "8.8", recommended_preload(size, "8.8"), f"bolt {n}")) + project.fixtures = [Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(lower, (40, 30, 0)))])] + load = (1500.0, 0, 0) if case == "friction" else (0, 0, 3000.0) + project.loads = [Load(LoadKind.FORCE, [FaceRef(1, face_at(upper, (40, 30, 10)))], vector=load)] + return project + + +def _fingerprint(case: str, result) -> dict[str, float]: + """A few numbers that a speed-up must not change.""" + import numpy as np + + if case == "modal": + return {f"f{i + 1}_Hz": float(f) for i, f in enumerate(result.frequencies[:3])} + if case == "buckling": + return {"factor1": float(result.factors[0])} + if case in ("thermal", "transient"): + out = {"T_max": float(result.temperature.max()), "heat_out_W": float(result.heat_out)} + if result.history is not None: + out["T_peak"] = float(np.max(result.history)) + return out + r = result[0] + out = { + "u_max": float(np.linalg.norm(r.displacement, axis=1).max()), + "reaction_sum": float(np.linalg.norm(np.sum(r.reactions, axis=0))), + } + if r.bolts: + out.update({f"bolt{i + 1}_N": float(b.axial) for i, b in enumerate(r.bolts)}) + if r.nonlinear is not None: + out["load_factor"] = float(r.nonlinear.load_factor) + out["plastic_max"] = float(r.nonlinear.plastic_strain.max()) + return out + + +def run_case(case: str, grade: str, profile: bool = False) -> dict: + os.environ.setdefault("KSTRUCT_DATA_DIR", tempfile.mkdtemp()) + from kstruct import standards + from kstruct.fem import generate_mesh + from kstruct.fem.buckling import solve_buckling + from kstruct.fem.modal import solve_modal + from kstruct.fem.static import solve_cases + from kstruct.fem.thermal import solve_thermal + from kstruct.model import active_project + + project = active_project(_bolted(case) if case in ("bolted", "friction") else _bracket(case)) + project.mesh_quality = grade + mats = standards.project_materials(project) + materials = {p.id: mats[p.material_id] for p in project.parts} + + t0 = time.perf_counter() + mesh = generate_mesh(project, grade) + t_mesh = time.perf_counter() - t0 + + def solve(): + if case == "modal": + return solve_modal(project, mesh, materials, 6) + if case == "buckling": + return solve_buckling(project, mesh, materials, 4) + if case in ("thermal", "transient"): + return solve_thermal(project, mesh, materials) + return solve_cases(project, mesh, materials) + + prof = None + if profile: + import cProfile + + prof = cProfile.Profile() + prof.enable() + t0 = time.perf_counter() + result = solve() + t_solve = time.perf_counter() - t0 + out = { + "case": case, + "grade": grade, + "dof": int(mesh.n_nodes * 3), + "mesh_s": round(t_mesh, 2), + "solve_s": round(t_solve, 2), + "result": _fingerprint(case, result), + } + if prof is not None: + import pstats + + prof.disable() + stats = pstats.Stats(prof) + rows = sorted( + ( + (tt, ct, nc, f"{fn.split('site-packages/')[-1].split('src/')[-1]}:{ln}:{func}") + for (fn, ln, func), (_, nc, tt, ct, _) in stats.stats.items() + ), + reverse=True, + ) + out["top_own"] = [(round(t, 2), round(c, 2), n, f) for t, c, n, f in rows[:15]] + return out + + +def _child(case: str, grade: str, profile: bool) -> dict: + cmd = [sys.executable, __file__, "--one", case, "--grade", grade] + if profile: + cmd.append("--profile") + done = subprocess.run(cmd, capture_output=True, text=True, check=False) + lines = [ln for ln in done.stdout.splitlines() if ln.startswith("{")] + if done.returncode != 0 or not lines: + raise RuntimeError(f"{case} failed:\n{done.stderr[-3000:]}") + return json.loads(lines[-1]) + + +def check(rows: list[dict], baseline: dict, tolerance: float, times: bool = True) -> list[str]: + """Slower than tolerance × baseline, or a fingerprint number that moved.""" + problems = [] + for row in rows: + base = baseline.get(row["case"]) + if base is None: + continue + if times and row["solve_s"] > tolerance * base["solve_s"] + 0.5: + problems.append( + f"{row['case']}: solve {row['solve_s']} s > {tolerance} × {base['solve_s']} s" + ) + for key, value in base.get("result", {}).items(): + new = row["result"].get(key) + tol = CASE_TOLERANCE.get(row["case"], RESULT_TOLERANCE) + if new is None or abs(new - value) > tol * max(abs(value), 1e-12): + problems.append(f"{row['case']}: {key} {value!r} -> {new!r}") + return problems + + +def main() -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("cases", nargs="*", help=f"some of: {' '.join(CASES)} (default: all)") + parser.add_argument("--grade", help="mesh grade for every case (default: per case)") + parser.add_argument("--profile", action="store_true", help="top functions by own time") + parser.add_argument("--json", type=Path, help="write the rows to this file") + parser.add_argument("--check", type=Path, help="baseline JSON to compare with") + parser.add_argument("--tolerance", type=float, default=1.5, help="allowed slow-down") + parser.add_argument( + "--results-only", action="store_true", help="--check the results, not the times" + ) + parser.add_argument("--one", help=argparse.SUPPRESS) # child process + args = parser.parse_args() + + if args.one: + print(json.dumps(run_case(args.one, args.grade or CASES[args.one], args.profile))) + return 0 + + unknown = set(args.cases) - set(CASES) + if unknown: + parser.error(f"unknown case(s): {', '.join(sorted(unknown))}") + rows = [] + print(f"{'case':10} {'grade':7} {'DOF':>8} {'mesh s':>7} {'solve s':>8} result") + for case in args.cases or list(CASES): + row = _child(case, args.grade or CASES[case], args.profile) + rows.append(row) + numbers = ", ".join(f"{k}={v:.6g}" for k, v in row["result"].items()) + print( + f"{case:10} {row['grade']:7} {row['dof']:8d} {row['mesh_s']:7.2f} " + f"{row['solve_s']:8.2f} {numbers}", + flush=True, + ) + for t, c, n, f in row.get("top_own", []): + print(f" own {t:7.2f} cum {c:7.2f} x{n:<6} {f}") + if args.json: + args.json.write_text(json.dumps({r["case"]: r for r in rows}, indent=1) + "\n") + if args.check: + problems = check( + rows, json.loads(args.check.read_text()), args.tolerance, not args.results_only + ) + for p in problems: + print("FAIL", p) + return 1 if problems else 0 + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packaging/bench_baseline.json b/packaging/bench_baseline.json new file mode 100644 index 0000000..f6ea79f --- /dev/null +++ b/packaging/bench_baseline.json @@ -0,0 +1,99 @@ +{ + "static": { + "case": "static", + "grade": "fine", + "dof": 93882, + "mesh_s": 2.85, + "solve_s": 2.67, + "result": { + "u_max": 0.6148712826394954, + "reaction_sum": 2999.99999999448 + } + }, + "modal": { + "case": "modal", + "grade": "fine", + "dof": 93882, + "mesh_s": 2.8, + "solve_s": 5.65, + "result": { + "f1_Hz": 752.98136747408, + "f2_Hz": 2487.1129989711612, + "f3_Hz": 4201.504471717308 + } + }, + "buckling": { + "case": "buckling", + "grade": "fine", + "dof": 93882, + "mesh_s": 2.88, + "solve_s": 14.26, + "result": { + "factor1": 15.253099112245751 + } + }, + "thermal": { + "case": "thermal", + "grade": "fine", + "dof": 93882, + "mesh_s": 2.92, + "solve_s": 1.54, + "result": { + "T_max": 105.26156752990501, + "heat_out_W": 14.99999999999801 + } + }, + "transient": { + "case": "transient", + "grade": "fine", + "dof": 93882, + "mesh_s": 2.83, + "solve_s": 5.39, + "result": { + "T_max": 59.0155837696419, + "heat_out_W": 5.055528889887896, + "T_peak": 59.0155837696419 + } + }, + "nonlinear": { + "case": "nonlinear", + "grade": "normal", + "dof": 37569, + "mesh_s": 2.08, + "solve_s": 8.7, + "result": { + "u_max": 1.9767629589439513, + "reaction_sum": 9000.000000256245, + "load_factor": 1.0, + "plastic_max": 0.0025735638439601575 + } + }, + "bolted": { + "case": "bolted", + "grade": "normal", + "dof": 82368, + "mesh_s": 2.35, + "solve_s": 11.82, + "result": { + "u_max": 0.05427366716141983, + "reaction_sum": 2999.632703908165, + "bolt1_N": 25876.949086013527, + "bolt2_N": 25884.790666334455, + "bolt3_N": 25770.680618475184 + } + }, + "friction": { + "case": "friction", + "grade": "normal", + "dof": 82368, + "mesh_s": 2.51, + "solve_s": 55.44, + "result": { + "u_max": 0.016303937990780722, + "reaction_sum": 1499.9898226722962, + "bolt1_N": 25659.242601167105, + "bolt2_N": 25696.648146715535, + "bolt3_N": 25626.222778883686 + } + } +} diff --git a/packaging/kstruct.spec b/packaging/kstruct.spec index e83572a..6175893 100644 --- a/packaging/kstruct.spec +++ b/packaging/kstruct.spec @@ -60,6 +60,13 @@ for dist in ("mkl", "intel-openmp", "tbb"): if MKL_KEEP.match(f.name) and "_db" not in f.name: binaries.append((str(f.locate().resolve()), ".")) +# VTK parts KStruct never loads (checked by listing the libraries mapped into a full run: +# result view, section, box selection, screenshots, VTU export): the VTK-m accelerators +# with their viskores libraries, testing and web modules. ~115 MB. +VTK_DROP = re.compile(r"viskores|AcceleratorsVTKm|vtk\w*Testing|vtkWeb", re.IGNORECASE) +hiddenimports = [h for h in hiddenimports if not VTK_DROP.search(h)] +binaries = [b for b in binaries if not VTK_DROP.search(Path(b[0]).name)] + a = Analysis( [str(ROOT / "src" / "kstruct" / "app.py")], pathex=[str(ROOT / "src")], @@ -80,6 +87,7 @@ a = Analysis( # netgen looks up its OCC libraries through the netgen-occt wheel metadata, whose paths are # wrong inside the bundle; without the metadata it falls back to the libraries shipped above a.datas = [d for d in a.datas if "netgen_occt-" not in d[0]] +a.binaries = [b for b in a.binaries if not VTK_DROP.search(Path(b[0]).name)] pyz = PYZ(a.pure) exe = EXE( pyz, @@ -93,6 +101,18 @@ exe = EXE( ) coll = COLLECT(exe, a.binaries, a.datas, name="KStruct") +# The VTK wheel's Linux libraries carry their full symbol tables (libvtkCommonCore 150 MB, +# 92 MB without): strip them, ~160 MB. Only VTK's: the auditwheel-repaired libraries of +# the other wheels were rewritten by patchelf, which strip can corrupt. +if sys.platform.startswith("linux"): + import shutil + import subprocess + + vtk_dir = Path(DISTPATH) / "KStruct" / "_internal" / "vtkmodules" + if shutil.which("strip") and vtk_dir.is_dir(): + for lib in vtk_dir.glob("*.so*"): + subprocess.run(["strip", "--strip-unneeded", str(lib)], check=False) + if sys.platform == "darwin": app = BUNDLE( coll, diff --git a/packaging/windows/kstruct.iss b/packaging/windows/kstruct.iss index f91caaa..f7b18ac 100644 --- a/packaging/windows/kstruct.iss +++ b/packaging/windows/kstruct.iss @@ -1,8 +1,8 @@ ; Inno Setup script: builds KStruct-Setup-.exe from dist\KStruct -; Build: iscc /DAppVersion=0.3.2 packaging\windows\kstruct.iss +; Build: iscc /DAppVersion=0.5.0 packaging\windows\kstruct.iss #ifndef AppVersion - #define AppVersion "0.3.2" + #define AppVersion "0.5.0" #endif [Setup] diff --git a/pyproject.toml b/pyproject.toml index c50a740..b25db2c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kstruct" -version = "0.3.2" +version = "0.5.0" description = "Mechanical part FEA for non-experts" readme = "README.md" authors = [ diff --git a/src/kstruct/__init__.py b/src/kstruct/__init__.py index 5c72b59..3bce6a5 100644 --- a/src/kstruct/__init__.py +++ b/src/kstruct/__init__.py @@ -1,6 +1,6 @@ """KStruct: mechanical part FEA for non-experts.""" -RELEASE_VERSION = "0.3.2" # keep in sync with pyproject.toml (tests check) +RELEASE_VERSION = "0.5.0" # keep in sync with pyproject.toml (tests check) # The build number is stamped into kstruct/_build.py by packaging/build.py (and by the CI # workflow) right before freezing, so every build gets a higher version: diff --git a/src/kstruct/app.py b/src/kstruct/app.py index 2901e1b..8032887 100644 --- a/src/kstruct/app.py +++ b/src/kstruct/app.py @@ -53,6 +53,9 @@ def selftest_gui(screenshot: Path) -> int: app = QApplication(sys.argv) window = MainWindow() + # app.quit() closes the window, and the unsaved sample would ask "save changes?": + # the test then sat in that dialog until the 3-minute safety quit + window.ask_before_close = False window.resize(1400, 860) window.show() window.open_sample("bracket") @@ -123,6 +126,9 @@ def main() -> None: window = MainWindow() window.install_crash_dialog() window.show() + from kstruct.fem.mesh import prewarm + + prewarm() # the first mesh then does not wait for a worker process and Netgen window.check_updates_quietly() args = [a for a in sys.argv[1:] if not a.startswith("-")] if args: diff --git a/src/kstruct/diagnose.py b/src/kstruct/diagnose.py new file mode 100644 index 0000000..833c7b7 --- /dev/null +++ b/src/kstruct/diagnose.py @@ -0,0 +1,73 @@ +"""Which parts an analysis error is about, so the UI can paint them red and open the step +that fixes it. Plain data in, plain data out (no Qt).""" + +from __future__ import annotations + +from kstruct.fem.assembly import SolverError +from kstruct.model import ConnectionKind, Project + +# the wizard step to open for each kind of problem (main_window.STEP_*) +FIX_FIXTURE, FIX_CONNECTION, FIX_LOAD = "fixture", "connection", "load" + + +def _groups(part_ids: list[int], joins: list[tuple[int, int]]) -> list[set[int]]: + group = {pid: {pid} for pid in part_ids} + for a, b in joins: + if a in group and b in group and group[a] is not group[b]: + merged = group[a] | group[b] + for pid in merged: + group[pid] = merged + seen, out = set(), [] + for g in group.values(): + if id(g) not in seen: + seen.add(id(g)) + out.append(g) + return out + + +def _joins(project: Project, bonded_only: bool) -> list[tuple[int, int]]: + pairs = [ + (c.faces_a[0].part_id, c.faces_b[0].part_id) + for c in project.connections + if c.faces_a and c.faces_b and (not bonded_only or c.kind == ConnectionKind.BONDED) + ] + return pairs + [(b.hole_a.part_id, b.hole_b.part_id) for b in project.bolts] + + +def unheld_parts(project: Project, bonded_only: bool = False) -> list[int]: + """Parts that no fixture reaches through the connections (bonded_only: through bonded + connections and bolts only, i.e. the parts that only contact keeps in place).""" + held = {ref.part_id for fx in project.fixtures for ref in fx.faces} + ids = [p.id for p in project.parts] + out: set[int] = set() + for group in _groups(ids, _joins(project, bonded_only)): + if not group & held: + out |= group + return sorted(out) + + +def problem_parts(project: Project, error: Exception) -> tuple[list[int], str | None]: + """(parts to show, the step that fixes it) for an analysis error; ([], None) when the + error is not about particular parts. `project` is the analysed (active) project.""" + if not isinstance(error, SolverError): + return [], None + if error.parts: + return sorted(error.parts), FIX_LOAD # thermal: no temperature reference + reason = str(error) + if reason == "unstable": + return unheld_parts(project), FIX_FIXTURE + if reason == "contact unstable": + return unheld_parts(project, bonded_only=True), FIX_FIXTURE + if reason == "bolt without contact": + joined = { + frozenset((c.faces_a[0].part_id, c.faces_b[0].part_id)) + for c in project.connections + if c.faces_a and c.faces_b + } + parts: set[int] = set() + for b in project.bolts: + pair = frozenset((b.hole_a.part_id, b.hole_b.part_id)) + if b.preload and pair not in joined: + parts |= pair + return sorted(parts), FIX_CONNECTION + return [], None diff --git a/src/kstruct/fem/assembly.py b/src/kstruct/fem/assembly.py index 303a92d..227e989 100644 --- a/src/kstruct/fem/assembly.py +++ b/src/kstruct/fem/assembly.py @@ -43,7 +43,12 @@ class SolverError(Exception): - pass + """An analysis that cannot be done as set up. `parts`: the parts it is about, when the + solver knows (the UI paints them).""" + + def __init__(self, *args, parts=()) -> None: + super().__init__(*args) + self.parts = tuple(parts) def element_dofs(tets: np.ndarray) -> np.ndarray: diff --git a/src/kstruct/fem/buckling.py b/src/kstruct/fem/buckling.py index 0968576..859288b 100644 --- a/src/kstruct/fem/buckling.py +++ b/src/kstruct/fem/buckling.py @@ -105,27 +105,35 @@ def solve_buckling( K = K + c.penalty_matrix(n_dof, K.diagonal().max()) + c.spring_matrix() K = K + bolt_stiffness_and_preload(build_bolts(project, mesh), n_dof)[0] free = np.flatnonzero(~c.fixed) - Kf, Kgf = K[free][:, free].tocsc(), Kg[free][:, free].tocsc() + # CSR: ARPACK's buckling mode multiplies by K a few hundred times (CSC was slower) + Kf, Kgf = K[free][:, free].tocsr(), Kg[free][:, free].tocsr() report(0.6, tr("좌굴 하중 계산 중")) # K φ = λ (-Kg) φ with K positive definite and Kg indefinite: ARPACK "buckling" mode. - # Eigenvalues closest to the shift come first; negative ones (load reversal) are dropped, - # so ask for extra. - k = min(2 * n_modes + 4, len(free) - 2) + # Eigenvalues closest to the shift come first; negative ones (load reversal) are + # dropped. Ask for a few extra first and for many more only if the negative ones took + # too many places: every requested pair costs ~10 back-substitutions (2n+4 always + # was 150 of them, 14 s on a 94k-DOF bracket). sigma = 1e-3 - try: - # buckling mode inverts K - σ(-Kg); with σ this small it stays positive definite - OPinv = inverse_operator(Kf + sigma * Kgf, rigid_body_modes(mesh.nodes)[free]) - lam, phi = spla.eigsh( - Kf, k=k, M=-Kgf, sigma=sigma, mode="buckling", which="LM", maxiter=300, OPinv=OPinv - ) - except spla.ArpackNoConvergence as e: - # no buckling mode anywhere near practical load levels (only tiny local compression) - lam, phi = e.eigenvalues, e.eigenvectors - if len(lam) == 0: - raise SolverError(tr(NO_COMPRESSION)) from e - except RuntimeError as e: - raise SolverError("not converged") from e + # buckling mode inverts K - σ(-Kg); with σ this small it stays positive definite + OPinv = inverse_operator(Kf + sigma * Kgf, rigid_body_modes(mesh.nodes)[free]) + lam = phi = None + for k in dict.fromkeys((min(n_modes + 3, len(free) - 2), min(2 * n_modes + 4, len(free) - 2))): + try: + lam, phi = spla.eigsh( + Kf, k=k, M=-Kgf, sigma=sigma, mode="buckling", which="LM", maxiter=300, + OPinv=OPinv, + ) # fmt: skip + except spla.ArpackNoConvergence as e: + # no buckling mode anywhere near practical load levels (only tiny local + # compression) + lam, phi = e.eigenvalues, e.eigenvectors + if len(lam) == 0: + raise SolverError(tr(NO_COMPRESSION)) from e + except RuntimeError as e: + raise SolverError("not converged") from e + if np.count_nonzero(lam > 1e-9) >= n_modes: + break positive = lam > 1e-9 if not positive.any(): raise SolverError(tr(NO_COMPRESSION)) diff --git a/src/kstruct/fem/contact.py b/src/kstruct/fem/contact.py index 34f86e3..29233c4 100644 --- a/src/kstruct/fem/contact.py +++ b/src/kstruct/fem/contact.py @@ -56,6 +56,7 @@ GROSS_SLIP_SHARE = 0.9 GROSS_GRIP_SHARE = 0.98 MAX_FRICTION_SWEEPS = 400 # back-substitutions allowed for the anchor iteration of a solve +ANDERSON_DEPTH = 5 # past sweeps the anchor extrapolation uses # Contact uses a softer penalty than ties (constraints.PENALTY_FACTOR = 1e6): penetration # stays ~1e-3 of the contact displacement, and releasing a pair can then be done as a # low-rank update of the factorization (with 1e6 the subtraction cancels catastrophically) @@ -78,7 +79,7 @@ class ContactSet: gross: bool = False # the interface slides as a whole: no springs, mu N along `slide` slide: np.ndarray | None = None # (2,) unit direction of the friction force when gross slip_force: np.ndarray | None = None # (P, 2) friction force on the slave when gross - aitken: tuple | None = None # (last anchor step, its relaxation, closed pairs) of a solve + aitken: tuple | None = None # anchor history of the solve (ContactSolver._accelerate) normal: np.ndarray | None = None # (P,) compressive normal force of the last iteration (N) def __post_init__(self) -> None: @@ -136,12 +137,15 @@ def commit_friction(self, u: np.ndarray, alpha_t: float) -> None: self.stick[:] = True self.base = self.anchor.copy() - def reset_friction(self) -> None: + def reset_friction(self, keep_anchor: bool = False) -> None: """Every pair sticks again with relaxed springs (a new load is a new solution, not - an increment of the last one).""" + an increment of the last one). keep_anchor: the anchors of the last solve stay as + the first guess of the iteration (the problem itself, measured from base = 0, is + the same; it only starts closer to its answer).""" self.stick[:] = True self.slip_force[:] = 0.0 - self.anchor[:] = 0.0 + if not keep_anchor or self.gross: + self.anchor[:] = 0.0 self.base[:] = 0.0 self.gross = False @@ -267,6 +271,14 @@ def __init__( self._fact_solve = None self._fact_state: list[tuple[np.ndarray, np.ndarray]] | None = None self._update = None # (signature, C, Y, S) of the last Woodbury update + # penalty matrix of the last spring state: friction sweeps only move anchors and + # forces, so the matrix (and K_ff + it) repeats for hundreds of iterations + self._matrix_cache: tuple | None = None # (signature, K_c) + self._last: tuple | None = None # (signature, x) of the last Woodbury solve + # K u - f is only needed on the slave nodes (their contact forces) + rows = np.unique(np.concatenate([cs.dofs[:, :3].ravel() for cs in contacts])) + self._slave_rows = rows + self._K_slave = K[rows].tocsr() # how many update columns (back-substitutions) one refactorization is worth; set # from the factorization's size, never from wall-clock time (that made the result # of a contact solve change from run to run) @@ -277,6 +289,7 @@ def __init__( # the result then belongs to an arbitrary intermediate contact/friction state self.converged = True self._offset = np.zeros(self.n_dof) # imposed displacement of the current solve + self._friction_tol = FRICTION_TOL # --- assembly -------------------------------------------------------------------- @@ -301,14 +314,35 @@ def _springs(self, cs: ContactSet, active, sprung) -> list: return out def _penalty(self) -> tuple[sp.csr_matrix, np.ndarray]: + return self._penalty_matrix() - self.K_ff, self._penalty_force() + + def _penalty_matrix(self) -> sp.csr_matrix: + """K_ff plus the springs of the current state, reused while the state repeats: + friction sweeps only move anchors and forces, so the same matrix (same values, + same order: the result does not change by a bit) serves hundreds of them.""" + signature = self._signature() + if self._matrix_cache is not None and self._matrix_cache[0] == signature: + return self._matrix_cache[1] rows, cols, vals = [], [], [] - f_c = np.zeros(len(self.free)) for cs in self.contacts: for mask, coefs, stiffness in self._springs(cs, cs.active, cs.sprung): dofs, c = self._rows(cs, mask, coefs) rows.append(np.repeat(dofs, 21, axis=1).ravel()) cols.append(np.tile(dofs, (1, 21)).ravel()) vals.append(stiffness * np.einsum("pi,pj->pij", c, c).ravel()) + K_pen = sp.csr_matrix( + (np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), + shape=self.K_ff.shape, + ) + K_c = self.K_ff + K_pen + self._matrix_cache = (signature, K_c) + return K_c + + def _penalty_force(self) -> np.ndarray: + """Right-hand side of the springs: gaps closed at the imposed displacement, the + anchors of the tangential springs, and the Coulomb forces of a gross slide.""" + f_c = np.zeros(len(self.free)) + for cs in self.contacts: dofs, c = self._rows(cs, cs.active) # a moved fixed node shifts the gap; its coefficient is not in the matrix gap0 = cs.gap(self._offset)[cs.active] @@ -325,11 +359,7 @@ def _penalty(self) -> tuple[sp.csr_matrix, np.ndarray]: dofs, c = self._rows(cs, gross, cs.tcoefs[:, k]) force = cs.slip_force[gross, k] np.add.at(f_c, dofs.ravel(), (c * force[:, None]).ravel()) - K_pen = sp.csr_matrix( - (np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), - shape=self.K_ff.shape, - ) - return K_pen, f_c + return f_c def _state(self) -> list[tuple[np.ndarray, np.ndarray]]: return [(cs.active.copy(), cs.sprung) for cs in self.contacts] @@ -339,7 +369,7 @@ def _signature(self) -> tuple: def matrix(self) -> sp.csr_matrix: """Reduced matrix of the current active set.""" - return self.K_ff + self._penalty()[0] + return self._penalty_matrix() # --- linear solves --------------------------------------------------------------- @@ -383,6 +413,7 @@ def reduced_solve(self, K_c: sp.csr_matrix, rhs: np.ndarray) -> np.ndarray: change = self._change() k = change[0].shape[0] if change is not None else MAX_UPDATE_RANK + 1 if k == 0: + self._last = None return self._fact_solve(rhs) # the update costs about k back-substitutions; refactorize when that is more than # a fresh factorization is worth (small systems factorize fast) @@ -395,6 +426,7 @@ def reduced_solve(self, K_c: sp.csr_matrix, rhs: np.ndarray) -> np.ndarray: self._breakeven = float(getattr(self._fact_solve, "breakeven", 0.0)) self._fact_state = self._state() self._update = None + self._last = None self.factorizations += 1 return self._fact_solve(rhs) @@ -426,18 +458,30 @@ def apply(b: np.ndarray) -> np.ndarray: y = self._fact_solve(b) return y - Y @ (S_inv @ (C @ y)) - x = apply(rhs) - if not np.all(np.isfinite(x)): - return None - # The update alone is only as accurate as cond(S)·eps allows: on a lap joint - # cond(S) ~ 1e6 left 8e-7 of the peak displacement (a fresh factorization agrees - # with another ordering to 6e-10), and on Windows CI it crossed 1e-6. One step of - # iterative refinement with the same operator brings it to 1.5e-9. The residual - # itself is no accuracy measure (the penalty rows amplify round-off), so the step - # is kept only when it is a small correction; otherwise the plain update stands. - dx = apply(rhs - K_c @ x) - if np.all(np.isfinite(dx)) and np.abs(dx).max() <= 1e-3 * np.abs(x).max(): - x = x + dx + last = self._last + if last is not None and last[0] == signature: + # Same matrix as the previous solve (a friction sweep moved only anchors and + # forces): continue from that solution, x + K_c⁻¹(rhs − K_c x). This one + # back-substitution is the new solve and a refinement step at once, so the + # accuracy below holds with half the back-substitutions. + x = last[1] + apply(rhs - K_c @ last[1]) + if not np.all(np.isfinite(x)): + return None + else: + x = apply(rhs) + if not np.all(np.isfinite(x)): + return None + # The update alone is only as accurate as cond(S)·eps allows: on a lap joint + # cond(S) ~ 1e6 left 8e-7 of the peak displacement (a fresh factorization + # agrees with another ordering to 6e-10), and on Windows CI it crossed 1e-6. + # One step of iterative refinement with the same operator brings it to + # 1.5e-9. The residual itself is no accuracy measure (the penalty rows amplify + # round-off), so the step is kept only when it is a small correction; + # otherwise the plain update stands. + dx = apply(rhs - K_c @ x) + if np.all(np.isfinite(dx)) and np.abs(dx).max() <= 1e-3 * np.abs(x).max(): + x = x + dx + self._last = (signature, x) self.updates += 1 return x @@ -458,7 +502,9 @@ def solve_path( return self.solve(f, offset=offset) u = np.zeros(self.n_dof) if np.any(f_start): - u = self.solve(f_start)[0] + # the bolt preload was settled once already (under the nominal pulls): start + # the anchors from there + u = self.solve(f_start, warm=True)[0] else: for cs in self.contacts: cs.reset_friction() @@ -474,14 +520,22 @@ def solve_path( return u, K_c # the last increment's stick/slip state is the reported one def solve( - self, f: np.ndarray, keep_friction: bool = False, offset: np.ndarray | None = None + self, + f: np.ndarray, + keep_friction: bool = False, + offset: np.ndarray | None = None, + warm: bool = False, + friction_tol: float = FRICTION_TOL, ) -> tuple[np.ndarray, sp.csr_matrix]: """Settle the active set (and the stick/slip state) under the full-size load f. Returns the displacement and the reduced matrix of the final contact state. keep_friction starts from the committed friction state (an increment of solve_path) instead of relaxing every tangential spring at zero sliding. - offset: displacement imposed on the fixed DOFs (prescribed movements).""" + offset: displacement imposed on the fixed DOFs (prescribed movements). + warm: a fresh solve (not an increment) that starts its anchor iteration from the + last solve's anchors, for a load close to the last one.""" self._offset = np.zeros(self.n_dof) if offset is None else offset + self._friction_tol = friction_tol f_f = (f - self.K @ self._offset)[self.free] load_scale = max(np.abs(f).max(), np.abs(f_f).max(), 1e-30) u = self._offset.copy() @@ -490,15 +544,15 @@ def solve( for cs in self.contacts: # the open/closed state carries over, friction starts afresh cs.aitken = None if not keep_friction: - cs.reset_friction() + cs.reset_friction(keep_anchor=warm) seen = {self._signature()} flips = [np.zeros(len(cs.active), dtype=int) for cs in self.contacts] exhausted = True changes = 0 # iterations that changed the springs (each needs a new solve matrix) sweeps = 0 # iterations that only moved anchors / friction forces (same matrix) while True: - K_pen, f_c = self._penalty() - K_c = self.K_ff + K_pen + K_c = self._penalty_matrix() + f_c = self._penalty_force() u = self._offset.copy() u[self.free] = self.reduced_solve(K_c, f_f + f_c) # Decide by the spring force, not the gap: a stiff penalty keeps even a @@ -509,7 +563,8 @@ def solve( # penetrates noticeably on the scale of the displacements. Pairs carrying # next to nothing would otherwise chatter between the two states for many # iterations, so each pair may change state only a few times per solve. - residual = self.K @ u - f + residual = np.zeros(self.n_dof) + residual[self._slave_rows] = self._K_slave @ u - f[self._slave_rows] geom_tol = 1e-6 * max(np.abs(u).max(), 1e-30) changed = False # the springs changed (pairs opened / closed, gross slide) forces_changed = False # only anchors or Coulomb forces moved (same matrix) @@ -543,7 +598,8 @@ def solve( if not changed and not forces_changed: exhausted = False break - if changed: + if changed and not forces_changed: + # a pure open/closed change: the active-set loop proper changes += 1 signature = self._signature() if signature in seen: # chattering between two states: keep the current one @@ -554,6 +610,13 @@ def solve( if changes >= MAX_ITERATIONS: break else: + # The friction forces are still moving. Pairs that open or close meanwhile + # follow the friction relaxation (under a bolt preload the rim of the + # clamped area opens pair by pair as the anchors settle): they count as + # sweeps, not as active-set iterations, or the loop gave up after 40 of + # them with the anchors half settled. MAX_FLIPS still bounds every pair. + if changed: + seen.add(self._signature()) sweeps += 1 if sweeps >= MAX_FRICTION_SWEEPS: break @@ -625,22 +688,12 @@ def _coulomb(self, cs, new_active, u, normal, force_tol): change = np.abs(new_force - cs.slip_force).sum() cs.slip_force = new_force cs.stick[:] = False - return False, bool(change > FRICTION_TOL * max(np.abs(new_force).sum(), force_tol)) + return False, bool( + change > self._friction_tol * max(np.abs(new_force).sum(), force_tol) + ) anchor = np.where(new_active[:, None], sliding + force / self.alpha_t, cs.anchor) movement = self.alpha_t * np.abs(anchor - cs.anchor)[new_active].sum() - # Aitken (Irons-Tuck) acceleration of the anchor fixed point: each plain sweep only - # removes a small share of the error when the springs are stiff against the parts - step = (anchor - cs.anchor)[new_active].ravel() - prev = cs.aitken - omega = 1.0 - if prev is not None and prev[0].shape == step.shape and np.array_equal(prev[2], new_active): - d = step - prev[0] - dd = float(d @ d) - if dd > 0: - omega = float(np.clip(-prev[1] * (prev[0] @ d) / dd, 0.1, 20.0)) - cs.aitken = (step, omega, new_active.copy()) - if omega != 1.0: - anchor[new_active] = cs.anchor[new_active] + omega * (anchor - cs.anchor)[new_active] + anchor = self._accelerate(cs, anchor, new_active) total = np.abs(force[new_active]).sum() log.debug( "friction: closed %d, slipping %d, anchor movement %.3g N of %.3g N", @@ -651,7 +704,35 @@ def _coulomb(self, cs, new_active, u, normal, force_tol): ) cs.anchor = anchor cs.stick = ~over - return False, bool(movement > FRICTION_TOL * max(total, force_tol)) + return False, bool(movement > self._friction_tol * max(total, force_tol)) + + def _accelerate(self, cs: ContactSet, plain: np.ndarray, active: np.ndarray) -> np.ndarray: + """Anderson acceleration of the anchor fixed point a -> G(a) (G = one sweep: + solve, then return mapping). Each plain sweep only removes a small share of the + error when the springs are stiff against the parts; the last few sweeps tell + how the error shrinks and the next anchors are extrapolated from them. The + history restarts when the set of closed pairs changes (the map changes).""" + x = cs.anchor.ravel() + g = plain.ravel() + hist = cs.aitken + if hist is None or not np.array_equal(hist[2], active): + cs.aitken = ([x.copy()], [g.copy()], active.copy()) + return plain + xs, gs, _ = hist + xs.append(x.copy()) + gs.append(g.copy()) + del xs[: -(ANDERSON_DEPTH + 1)], gs[: -(ANDERSON_DEPTH + 1)] + F = np.array(gs) - np.array(xs) # residuals G(x) - x, oldest first + dF = np.diff(F, axis=0) # (m, n) + dG = np.diff(np.array(gs), axis=0) + try: + gamma, *_ = np.linalg.lstsq(dF.T, F[-1], rcond=1e-10) + except np.linalg.LinAlgError: + return plain + accelerated = g - gamma @ dG + if not np.all(np.isfinite(accelerated)): + return plain + return np.where(active[:, None], accelerated.reshape(plain.shape), plain) def current_solver(self): """Exact solver for the current active set on full-size right-hand sides (used for diff --git a/src/kstruct/fem/mesh.py b/src/kstruct/fem/mesh.py index 7e63cef..8b41960 100644 --- a/src/kstruct/fem/mesh.py +++ b/src/kstruct/fem/mesh.py @@ -14,6 +14,7 @@ import multiprocessing import os import tempfile +import threading import time from collections.abc import Callable from dataclasses import dataclass, field @@ -27,6 +28,8 @@ from kstruct.model import FaceRef, Project MESH_TIMEOUT = 600 # seconds per part before the meshing process is killed +MAX_WORKERS = 4 # meshing processes (parts are meshed in parallel) +WORKER_TASKS = 20 # meshes per worker process before it is replaced (Netgen memory) @dataclass(frozen=True) @@ -102,6 +105,53 @@ def _mesh_shape( return nodes, tets, tris, faces +def _warm_up() -> None: + """Worker initializer: import Netgen now, not when the first mesh is wanted.""" + import netgen.occ # noqa: F401 + + +_pool = None # spawned worker processes, kept between meshings +_pool_size = 0 +_pool_lock = threading.Lock() + + +def _get_pool(workers: int): + """The kept worker pool, made (or made bigger) on demand. Starting a process and + importing Netgen took 1.4 s of a 3 s mesh; a pool kept alive pays that once.""" + global _pool, _pool_size + with _pool_lock: + if _pool is None or _pool_size < workers: + _drop_pool_locked() + _pool = multiprocessing.get_context("spawn").Pool( + workers, initializer=_warm_up, maxtasksperchild=WORKER_TASKS + ) + _pool_size = workers + return _pool + + +def _drop_pool_locked() -> None: + global _pool, _pool_size + if _pool is not None: + _pool.terminate() + _pool.join() + _pool, _pool_size = None, 0 + + +def drop_pool() -> None: + """Kill the worker processes (after a timeout, a cancel or an error: a worker may be + stuck in Netgen).""" + with _pool_lock: + _drop_pool_locked() + + +def prewarm() -> None: + """Start a meshing worker in the background so that the first mesh does not wait for + a process and the Netgen import (called once the main window is up).""" + if os.environ.get("KSTRUCT_INPROCESS_MESH") != "1": + workers = max(1, min(os.cpu_count() or 1, 2)) # two: assemblies are common + threading.Thread(target=_get_pool, args=(workers,), daemon=True).start() + + def _mesh_all( steps: list[Path], maxh: float, @@ -124,9 +174,10 @@ def _mesh_all( _mesh_or_raise(step, maxh, name, fh, grading) for step, name, fh in zip(steps, names, face_maxh, strict=True) ] - workers = max(1, min(len(steps), os.cpu_count() or 1, 4)) + workers = max(1, min(len(steps), os.cpu_count() or 1, MAX_WORKERS)) for attempt in (1, 2): - pool = multiprocessing.get_context("spawn").Pool(workers) + pool = _get_pool(workers) + ok = False try: jobs = [ pool.apply_async(_mesh_shape, (str(step), maxh, fh, grading)) @@ -154,12 +205,13 @@ def _mesh_all( raise MeshingError( tr("'{name}' 부품의 메시 생성에 실패했습니다: {e}", name=name, e=e) ) from e + ok = True return results except _Retry: continue finally: - pool.terminate() - pool.join() + if not ok: # a worker may still be busy in (or stuck inside) Netgen + drop_pool() raise AssertionError("unreachable") diff --git a/src/kstruct/fem/nonlinear.py b/src/kstruct/fem/nonlinear.py index a186da1..15afebe 100644 --- a/src/kstruct/fem/nonlinear.py +++ b/src/kstruct/fem/nonlinear.py @@ -42,7 +42,7 @@ ) from kstruct.fem.constraints import Constraints, build_constraints from kstruct.fem.mesh import FEMesh -from kstruct.fem.plasticity import point_material, return_map +from kstruct.fem.plasticity import elasticity, point_material, return_map from kstruct.i18n import tr from kstruct.model import ConnectionKind, Material, Project @@ -108,6 +108,7 @@ def __init__(self, mesh: FEMesh, materials: dict[int, Material], dT_nodes): self.thermal.append(alpha * (dT_nodes[mesh.tets] @ tet10.shape_functions(p))) self.n = len(mesh.tets) self._pattern = None + self._elastic = None # tangent values of the unyielded body (small strain) def pattern(self, mesh: FEMesh): """(indptr, indices, slot of every element entry) of the tangent's CSR pattern, @@ -127,6 +128,27 @@ def pattern(self, mesh: FEMesh): return self._pattern +def _elastic_values(el: _Elements, mesh: FEMesh) -> np.ndarray: + """Values (in the pattern of el.pattern) of the small-strain elastic stiffness: the + tangent of every point that is not yielding right now, assembled once.""" + if el._elastic is None: + _, indices, slot = el.pattern(mesh) + values = np.zeros(len(indices)) + for start in range(0, el.n, CHUNK): + sl = slice(start, min(start + CHUNK, el.n)) + mat = el.mat.subset(sl) + D = elasticity(mat.E, mat.nu) + Ke = np.zeros((sl.stop - sl.start, 30, 30)) + for g in range(4): + B = tet10.strain_matrix(el.dN[g][sl]) + Ke += (B.transpose(0, 2, 1) @ (D @ B)) * el.dv[g][sl][:, None, None] + values += np.bincount( + slot[sl.start * 900 : sl.stop * 900], weights=Ke.ravel(), minlength=len(values) + ) + el._elastic = values + return el._elastic + + def _deformation_gradient(ue: np.ndarray, dN: np.ndarray) -> np.ndarray: """F = I + Σ_a u_a ⊗ ∇N_a, (E, 3, 3).""" return np.eye(3) + np.einsum("eai,eaj->eij", ue, dN) @@ -168,9 +190,13 @@ def _evaluate( eps_p, alpha = state new_eps_p, new_alpha = eps_p.copy(), alpha.copy() f_int = np.zeros(n_dof) + # Small strain: B is fixed and a point that is not yielding has the elastic tangent, + # so the tangent is the elastic matrix (assembled once) plus Bᵀ(D_t − D_e)B on the + # yielding points only. The full B ᵀ D B of every point was most of a Newton step. + elastic_base = want_matrix and not large if want_matrix: indptr, indices, slot = el.pattern(mesh) - values = np.zeros(len(indices)) + values = _elastic_values(el, mesh).copy() if elastic_base else 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)) @@ -180,6 +206,8 @@ def _evaluate( fe = np.zeros((len(tets), 30)) Ke = np.zeros((len(tets), 30, 30)) if want_matrix else None mat = el.mat.subset(sl) + D_e = elasticity(mat.E, mat.nu) if elastic_base else None + corrected = np.zeros(len(tets), dtype=bool) for g in range(4): dN, dv = el.dN[g][sl], el.dv[g][sl] strain, B, _ = _strain_and_B(ue, dN, large) @@ -189,7 +217,15 @@ def _evaluate( new_eps_p[sl, g], new_alpha[sl, g] = ep, a S_points[sl, g] = S fe += np.einsum("eji,ej->ei", B, S) * dv[:, None] - if want_matrix: + if elastic_base: + yielding = a > alpha[sl, g] + if np.any(yielding): + i = np.flatnonzero(yielding) + Bi = B[i] + dD = D[i] - D_e[i] + Ke[i] += (Bi.transpose(0, 2, 1) @ (dD @ Bi)) * dv[i][:, None, None] + corrected[i] = True + elif want_matrix: Ke += (B.transpose(0, 2, 1) @ (D @ B)) * dv[:, None, None] if large: # initial stress stiffness: ∇N_a · S · ∇N_b on each axis St = _tensor(S) @@ -197,7 +233,12 @@ def _evaluate( for k in range(3): Ke[:, k::3, k::3] += Gab f_int += np.bincount(dofs.ravel(), weights=fe.ravel(), minlength=n_dof) - if want_matrix: + if elastic_base: + if np.any(corrected): + i = np.flatnonzero(corrected) + entries = slot[sl.start * 900 : sl.stop * 900].reshape(-1, 900)[i] + values += np.bincount(entries.ravel(), weights=Ke[i].ravel(), minlength=len(values)) + elif want_matrix: 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 diff --git a/src/kstruct/fem/static.py b/src/kstruct/fem/static.py index 37f525f..7011592 100644 --- a/src/kstruct/fem/static.py +++ b/src/kstruct/fem/static.py @@ -389,7 +389,7 @@ def guarded(rhs): report(0.35, tr("볼트 체결 상태 계산 중")) _, f_nominal = bolt_stiffness_and_preload(connectors, n_dof) if contact_solver is not None: - contact_solver.solve(f_nominal) + contact_solver.solve(f_nominal, friction_tol=1e-2) unit_solver = contact_solver.current_solver() else: unit_solver = linear_solver() diff --git a/src/kstruct/fem/thermal.py b/src/kstruct/fem/thermal.py index 9ce94f3..4ca1a61 100644 --- a/src/kstruct/fem/thermal.py +++ b/src/kstruct/fem/thermal.py @@ -238,7 +238,8 @@ def solve_thermal( "{names} 부품에 온도의 기준이 없습니다. 이 부품에 '고정 온도'·'대류 냉각'·" "'복사 냉각' 중 하나를 지정하거나, 기준이 있는 부품과 접합(맞닿은 면 연결)하세요.", names=names, - ) + ), + parts=sorted(group), ) faces = {} for i, ld in enumerate(loads): @@ -370,6 +371,7 @@ def _march(assemble, C, project: Project, duration: float, nonlinear: bool, repo every = max(TRANSIENT_STEPS // TRANSIENT_FRAMES, 1) times, history = [0.0], [T.copy()] solver = None + factored = None # (free DOFs, solver) of the last factorization fixed, films = np.zeros(n, dtype=bool), [] for step in range(1, TRANSIENT_STEPS + 1): report( @@ -380,10 +382,21 @@ def _march(assemble, C, project: Project, duration: float, nonlinear: bool, repo Kp, f, fixed, T_fix, films = assemble(T if nonlinear else None) A = (Kp + C / dt).tocsr() free = np.flatnonzero(~fixed) - solver = make_solver(A[free][:, free].tocsr(), np.ones((len(free), 1))) + A_ff = A[free][:, free].tocsr() + solver = "direct" T_next = T_fix.copy() rhs = f + C @ T / dt - A @ T_fix - T_next[free] = solver(rhs[free]) + b = rhs[free] + x = None + if nonlinear and factored is not None and np.array_equal(factored[0], free): + # Radiation / k(T) change the matrix a little from step to step: the last + # factorization preconditions CG on the new one (a few back-substitutions) + # instead of a factorization per step (60 of them were 9 of 10 s). + x = _pcg(A_ff, b, factored[1], T[free]) + if x is None: + factored = (free, make_solver(A_ff, np.ones((len(free), 1)))) + x = factored[1](b) + T_next[free] = x T = T_next if step % every == 0 or step == TRANSIENT_STEPS: times.append(step * dt) @@ -391,6 +404,35 @@ def _march(assemble, C, project: Project, duration: float, nonlinear: bool, repo return T, fixed, films, np.array(times), np.array(history) +TRANSIENT_CG_TOL = 1e-12 # relative residual of a step solved with an older factorization +TRANSIENT_CG_MAX = 8 # CG iterations before the step matrix is factorized afresh + + +def _pcg(A: sp.csr_matrix, b: np.ndarray, precondition, x0: np.ndarray) -> np.ndarray | None: + """Preconditioned conjugate gradients to TRANSIENT_CG_TOL; None if that takes more + than TRANSIENT_CG_MAX iterations (the preconditioner is too stale).""" + x = x0.copy() + r = b - A @ x + target = TRANSIENT_CG_TOL * max(np.linalg.norm(b), 1e-300) + if np.linalg.norm(r) <= target: + return x + z = precondition(r) + p = z.copy() + rz = r @ z + for _ in range(TRANSIENT_CG_MAX): + Ap = A @ p + a = rz / (p @ Ap) + x += a * p + r -= a * Ap + if np.linalg.norm(r) <= target: + return x + z = precondition(r) + rz_new = r @ z + p = z + (rz_new / rz) * p + rz = rz_new + return None + + def _nodal_flux(mesh: FEMesh, k: np.ndarray, T: np.ndarray) -> np.ndarray: X = mesh.nodes[mesh.tets] Te = T[mesh.tets] diff --git a/src/kstruct/geometry/face_info.py b/src/kstruct/geometry/face_info.py index 13378e8..7960787 100644 --- a/src/kstruct/geometry/face_info.py +++ b/src/kstruct/geometry/face_info.py @@ -105,3 +105,96 @@ def faces_centroid(faces: list[TopoDS_Face]): acc += area * np.array(props.CentreOfMass().Coord()) total += area return acc / total if total > 0 else acc + + +SIMILAR_TOLERANCE = 5e-3 # relative difference in radius / area still called "the same" +TANGENT_ANGLE = 0.02 # rad (≈1°): faces meeting smoother than this continue each other + + +def similar_faces(shape, index: int) -> list[int]: + """Faces of the same kind and size as face `index` (faces_of order, itself included): + for a cylinder every cylinder of the same radius (all the bolt holes, both halves of + a split hole), otherwise faces of the same surface type and area (repeated bosses).""" + from kstruct.geometry.tessellate import faces_of + + faces = faces_of(shape) + + def key(face): + surface = BRepAdaptor_Surface(face) + kind = surface.GetType() + if kind == GeomAbs_Cylinder: + return kind, surface.Cylinder().Radius(), None + props = GProp_GProps() + BRepGProp.SurfaceProperties_s(face, props) + # planes also face the same way: the tops of repeated bosses, not a plate's top + # and bottom + normal = outward_normal(face) if kind == GeomAbs_Plane else None + return kind, props.Mass(), normal + + kind, size, normal = key(faces[index]) + found = [] + for i, face in enumerate(faces): + k, s, n = key(face) + if k != kind or abs(s - size) > SIMILAR_TOLERANCE * max(abs(size), 1e-9): + continue + if normal is not None and ( + n is None or sum(a * b for a, b in zip(n, normal, strict=True)) < 0.999 + ): + continue + found.append(i) + return found + + +def tangent_faces(shape, index: int) -> list[int]: + """Face `index` and every face joined to it through smooth (tangent) edges: a fillet + with the faces it rounds, a hole split into halves, a slot's walls and ends.""" + from OCP.BRepLib import BRepLib + from OCP.GeomAbs import GeomAbs_C0 + from OCP.TopAbs import TopAbs_EDGE + from OCP.TopExp import TopExp_Explorer + from OCP.TopoDS import TopoDS + + from kstruct.geometry.tessellate import faces_of + + faces = faces_of(shape) + edges = IndexedEdges() + edge_faces: dict[int, set[int]] = {} + for i, face in enumerate(faces): + explorer = TopExp_Explorer(face, TopAbs_EDGE) + while explorer.More(): + edge_faces.setdefault(edges.add(explorer.Current()), set()).add(i) + explorer.Next() + neighbours: dict[int, set[int]] = {} + for k, owners in edge_faces.items(): + if len(owners) != 2: + continue # a seam (one face) or a non-manifold edge + a, b = sorted(owners) + edge = TopoDS.Edge(edges.key(k)) + # ContinuityOfFaces does not store anything in the shape (EncodeRegularity + # would, and change the brep bytes the saved mesh is keyed on) + if BRepLib.ContinuityOfFaces_s(edge, faces[a], faces[b], TANGENT_ANGLE) != GeomAbs_C0: + neighbours.setdefault(a, set()).add(b) + neighbours.setdefault(b, set()).add(a) + seen = {index} + todo = [index] + while todo: + for j in neighbours.get(todo.pop(), ()): + if j not in seen: + seen.add(j) + todo.append(j) + return sorted(seen) + + +class IndexedEdges: + """Edges numbered by identity (an edge shared by two faces gets one number).""" + + def __init__(self) -> None: + from OCP.collections import IndexedMap_TopoDS_Shape_TopTools_ShapeMapHasher + + self._map = IndexedMap_TopoDS_Shape_TopTools_ShapeMapHasher() + + def add(self, edge) -> int: + return self._map.Add(edge) + + def key(self, k: int): + return self._map.FindKey(k) diff --git a/src/kstruct/resources/help/en.json b/src/kstruct/resources/help/en.json index 1bbf6cc..12f788b 100644 --- a/src/kstruct/resources/help/en.json +++ b/src/kstruct/resources/help/en.json @@ -46,7 +46,13 @@ "view.face_pick": { "title": "Face selection", "short": "Click a face of a part to select it. Ctrl+click to select several faces.", - "detail": "Click a face with the left mouse button and it is highlighted in yellow. Hold Ctrl while clicking to select several faces together; click an empty area to clear the selection." + "detail": "Click a face with the left mouse button and it is highlighted in yellow. Hold Ctrl while clicking to select several faces together; click an empty area to clear the selection.", + "related": [ + "view.box_select", + "view.similar", + "view.tangent", + "view.isolate" + ] }, "view.fit": { "title": "Fit to view", @@ -559,5 +565,44 @@ "title": "GitHub token (optional)", "short": "Usually leave this empty. Enter one only if update checks are blocked by the 'rate limit'.", "detail": "The KStruct repository is public, so updates can be checked and downloaded without a token. However, GitHub limits requests without sign-in to 60 per hour from the same internet address, so if your whole company goes out through one address, you may get a 'rate limit' error. In that case, create a token with no permissions (read-only access to public repositories) under GitHub → Settings → Developer settings → Personal access tokens and paste it here. The token is saved in the user data folder on this computer (prefs.json). You can also set it with the environment variable KSTRUCT_GITHUB_TOKEN, which then takes precedence." + }, + "view.views": { + "title": "View direction", + "short": "Look from the front, back, sides, top, bottom or at an angle (shortcuts 1, 3, 7; with Ctrl the opposite side; 0 isometric).", + "detail": "Choose from the 'View' menu or press a number key, following the numeric-keypad habit of CAD programs: 1 front, 3 right, 7 top, Ctrl+1/3/7 the opposite side (back, left, bottom), 0 isometric.

While you are typing in an input box the number goes into the box instead. The full list is under 'Keyboard shortcuts' in the info menu (Ctrl+/)." + }, + "view.see_through": { + "title": "See-through", + "short": "Draws every part see-through so faces inside or behind become visible.", + "detail": "Clicks still hit the front-most face. To pick an inner face, right-click the part in front in the 3D view and choose 'See-through (clicks pass through)' or 'Hide this part'." + }, + "view.isolate": { + "title": "Show and hide parts (view only)", + "short": "Right-click a part in the 3D view or in the part list to show only that part or hide it.", + "detail": "Show only this part, Hide this part and See-through (clicks pass through) only change the view; the analysis still uses every part. Use them to pick contact faces or holes inside an assembly. 'Show all parts again' in the 'View' menu undoes them.

To leave a part out of the analysis, untick it in the part list of step 1.", + "related": [ + "view.parts", + "view.face_pick" + ] + }, + "view.box_select": { + "title": "Box select", + "short": "Drag a rectangle to select every visible face inside it (shortcut B).", + "detail": "While it is on, a left drag draws a rectangle instead of rotating (middle drag pans, the wheel zooms). Faces hidden behind others are not selected. Hold Ctrl while dragging to add to the selection. Press it again or Esc to turn it off." + }, + "view.similar": { + "title": "All same size", + "short": "Adds every face of the same kind and size as the selected one (shortcut S): all the bolt holes at once.", + "detail": "For a cylinder it finds the cylinders of the same radius (every hole of that diameter, both halves of a split hole); for a plane, the planes with the same area facing the same way; for other faces, faces of the same kind and area. Only within the same part." + }, + "view.tangent": { + "title": "Connected faces", + "short": "Adds every face joined smoothly to the selection (shortcut T): fillets, rounded slots, split holes.", + "detail": "Follows the faces that continue across an edge without a corner. Selecting a fillet, for example, also selects the faces on both sides of it; selecting one wall of a slot also selects the wall and its round ends." + }, + "view.clear_selection": { + "title": "Clear selection", + "short": "Deselects all faces (shortcut Esc).", + "detail": "Also turns box select off. Clicking an empty spot in the 3D view clears the selection too." } } diff --git a/src/kstruct/resources/help/ko.json b/src/kstruct/resources/help/ko.json index 3bb4bb8..5493d4a 100644 --- a/src/kstruct/resources/help/ko.json +++ b/src/kstruct/resources/help/ko.json @@ -46,7 +46,13 @@ "view.face_pick": { "title": "면 선택", "short": "부품의 면을 클릭하면 선택됩니다. Ctrl+클릭으로 여러 면을 고릅니다.", - "detail": "마우스 왼쪽 버튼으로 면을 클릭하면 노란색으로 표시됩니다. Ctrl을 누른 채 클릭하면 여러 면을 함께 고를 수 있고, 빈 곳을 클릭하면 선택이 풀립니다." + "detail": "마우스 왼쪽 버튼으로 면을 클릭하면 노란색으로 표시됩니다. Ctrl을 누른 채 클릭하면 여러 면을 함께 고를 수 있고, 빈 곳을 클릭하면 선택이 풀립니다.", + "related": [ + "view.box_select", + "view.similar", + "view.tangent", + "view.isolate" + ] }, "view.fit": { "title": "화면 맞춤", @@ -559,5 +565,44 @@ "title": "GitHub 토큰 (선택)", "short": "보통은 비워 두면 됩니다. 업데이트 확인이 '요청 한도'로 막힐 때만 넣으세요.", "detail": "KStruct 저장소는 공개라서 토큰 없이도 업데이트를 확인하고 받을 수 있습니다. 다만 GitHub은 로그인하지 않은 요청을 같은 인터넷 주소에서 시간당 60회로 제한하므로, 회사 전체가 한 주소로 나가는 경우 '요청 한도' 오류가 날 수 있습니다. 그때 GitHub → Settings → Developer settings → Personal access tokens에서 권한 없는(공개 저장소 읽기만) 토큰을 만들어 붙여 넣으세요. 토큰은 이 컴퓨터의 사용자 데이터 폴더(prefs.json)에 저장됩니다. 환경 변수 KSTRUCT_GITHUB_TOKEN으로 지정할 수도 있고, 이때는 환경 변수가 우선합니다." + }, + "view.views": { + "title": "보기 방향", + "short": "앞·뒤·옆·위·아래·등각에서 본 모습으로 바꿉니다 (단축키 1·3·7, Ctrl과 함께 반대쪽, 0 등각).", + "detail": "'보기' 메뉴에서 고르거나 숫자 키를 누르세요. CAD 프로그램의 숫자 키패드 습관을 따릅니다: 1 앞, 3 오른쪽, 7 위, Ctrl+1/3/7 반대쪽(뒤·왼쪽·아래), 0 등각.

입력 칸에 숫자를 쓰는 중에는 단축키 대신 숫자가 입력됩니다. 전체 목록은 정보 메뉴의 '단축키 목록'(Ctrl+/)에 있습니다." + }, + "view.see_through": { + "title": "반투명", + "short": "모든 부품을 반투명하게 그려 안쪽이나 뒤쪽 면을 보이게 합니다.", + "detail": "켜도 클릭은 맨 앞의 면에 닿습니다. 안쪽 면을 고르려면 3D 화면에서 앞을 가리는 부품을 오른쪽 클릭해 '반투명 (클릭이 통과)'나 '이 부품 숨기기'를 고르세요." + }, + "view.isolate": { + "title": "부품 보이기·숨기기 (화면에서만)", + "short": "3D 화면이나 부품 목록에서 부품을 오른쪽 클릭하면 그 부품만 보거나 숨길 수 있습니다.", + "detail": "이 부품만 보기, 이 부품 숨기기, 반투명 (클릭이 통과)는 화면에만 적용되고 해석에는 모든 부품이 그대로 들어갑니다. 조립품 안쪽의 맞닿은 면이나 구멍을 고를 때 쓰세요. '보기' 메뉴의 '모든 부품 다시 보이기'로 되돌립니다.

해석에서 부품을 빼려면 1단계 부품 목록의 체크를 해제하세요.", + "related": [ + "view.parts", + "view.face_pick" + ] + }, + "view.box_select": { + "title": "영역 선택", + "short": "끌어서 사각형을 그리면 그 안에 보이는 면을 모두 선택합니다 (단축키 B).", + "detail": "켜져 있는 동안 왼쪽 끌기는 회전 대신 사각형 그리기가 됩니다(가운데 끌기로 옮기고 휠로 확대). 다른 면에 가려진 면은 선택하지 않습니다. Ctrl을 누른 채 그리면 기존 선택에 더합니다. 다시 누르거나 Esc로 끕니다." + }, + "view.similar": { + "title": "같은 크기 모두", + "short": "선택한 면과 종류·크기가 같은 면을 모두 더합니다 (단축키 S). 볼트 구멍을 한 번에 고를 때 씁니다.", + "detail": "원통면이면 반지름이 같은 원통면(같은 지름의 구멍 전부, 반으로 나뉜 구멍의 두 쪽)을, 평면이면 면적과 방향이 같은 평면을, 그 밖의 면은 면적이 같은 같은 종류의 면을 찾습니다. 같은 부품 안에서만 찾습니다." + }, + "view.tangent": { + "title": "이어진 면", + "short": "선택한 면과 매끄럽게 이어진 면을 모두 더합니다 (단축키 T). 필렛·둥근 홈·나뉜 구멍에 씁니다.", + "detail": "모서리에서 꺾이지 않고 접선으로 이어지는 면을 따라가며 고릅니다. 예를 들어 필렛을 고르면 필렛과 그 양쪽 면이, 긴 구멍(슬롯)의 벽 하나를 고르면 벽과 둥근 끝이 함께 선택됩니다." + }, + "view.clear_selection": { + "title": "선택 해제", + "short": "고른 면을 모두 해제합니다 (단축키 Esc).", + "detail": "영역 선택이 켜져 있으면 함께 끕니다. 3D 화면의 빈 곳을 클릭해도 선택이 풀립니다." } } diff --git a/src/kstruct/resources/i18n/en/main.json b/src/kstruct/resources/i18n/en/main.json index a7bfed9..a12d74d 100644 --- a/src/kstruct/resources/i18n/en/main.json +++ b/src/kstruct/resources/i18n/en/main.json @@ -168,5 +168,51 @@ "확인": "Confirm", "확인이 필요합니다": "Please check", "후원하기": "Sponsor", - "후원하기 (GitHub Sponsors)": "Sponsor (GitHub Sponsors)" + "후원하기 (GitHub Sponsors)": "Sponsor (GitHub Sponsors)", + "왼쪽 끌기": "Left drag", + "돌려 보기": "Rotate the view", + "휠": "Wheel", + "확대·축소": "Zoom in / out", + "가운데 끌기 / Shift+왼쪽 끌기": "Middle drag / Shift+left drag", + "옮겨 보기": "Pan the view", + "클릭 / Ctrl+클릭": "Click / Ctrl+click", + "면 선택 / 여러 면 선택": "Select a face / several faces", + "오른쪽 클릭": "Right-click", + "부품 보기·선택 메뉴": "Part view and selection menu", + "파일 끌어다 놓기": "Drop a file on the window", + "모델·프로젝트 열기": "Open a model or project", + "해당 부품을 3D 화면에 빨갛게 표시했습니다: {names}": "The parts concerned are shown in red in the 3D view: {names}", + "{step} 단계로 가기": "Go to {step}", + "단축키 목록": "Keyboard shortcuts", + "{step} 단계로 이동": "Go to {step}", + "목록에서 고른 항목 삭제": "Delete the item chosen in the list", + "해석 전 확인 목록에서 ✘ 표시된 항목을 먼저 채우세요.": "Complete the items marked ✘ in the checklist first.", + "키보드": "Keyboard", + "마우스": "Mouse", + "저장하지 않은 변경이 있습니다. 저장하지 않고 다른 파일을 열까요?": "There are unsaved changes. Open another file without saving?", + "보기 ▾": "View ▾", + "반투명": "See-through", + "영역 선택": "Box select", + "같은 크기 모두": "All same size", + "이어진 면": "Connected faces", + "선택 해제": "Clear selection", + "면 {n}개를 더 선택했습니다.": "Added {n} more faces to the selection.", + "먼저 면을 하나 클릭한 다음 '같은 크기 모두'를 누르세요.": "Click a face first, then press 'All same size'.", + "먼저 면을 하나 클릭한 다음 '이어진 면'을 누르세요.": "Click a face first, then press 'Connected faces'.", + "등각 보기": "Isometric view", + "앞에서 보기": "Front view", + "뒤에서 보기": "Back view", + "오른쪽에서 보기": "Right view", + "왼쪽에서 보기": "Left view", + "위에서 보기": "Top view", + "아래에서 보기": "Bottom view", + "이 면 선택": "Select this face", + "같은 크기 면 모두 선택": "Select all faces of the same size", + "이어진 면 선택": "Select connected faces", + "영역 선택: 끌어서 사각형을 그리면 보이는 면이 선택됩니다. Ctrl을 누르면 추가.": "Box select: drag a rectangle to select the visible faces in it. Hold Ctrl to add.", + "면 {n}개를 선택했습니다.": "{n} faces selected.", + "이 부품만 보기": "Show only this part", + "이 부품 숨기기 (화면에서만)": "Hide this part (view only)", + "반투명 (클릭이 통과)": "See-through (clicks pass through)", + "모든 부품 다시 보이기": "Show all parts again" } diff --git a/src/kstruct/ui/main_window.py b/src/kstruct/ui/main_window.py index cd2b1ce..5094f72 100644 --- a/src/kstruct/ui/main_window.py +++ b/src/kstruct/ui/main_window.py @@ -34,7 +34,7 @@ QWidget, ) -from kstruct import i18n, standards +from kstruct import diagnose, i18n, standards from kstruct.fem import ConstraintError, MeshingError, SolverError, generate_mesh from kstruct.fem.buckling import BucklingResult, solve_buckling from kstruct.fem.mesh import FEMesh @@ -44,7 +44,9 @@ from kstruct.fem.thermal import ThermalResult, solve_thermal from kstruct.geometry import GeometryImportError, load_cad from kstruct.geometry.contacts import find_touching_faces +from kstruct.geometry.mesh_import import MESH_SUFFIXES from kstruct.geometry.samples import bolted_plates, l_bracket, two_plates, write_step +from kstruct.geometry.step_import import IGES_SUFFIXES, STEP_SUFFIXES from kstruct.i18n import N_, tr, tr_data from kstruct.model import ( TEMPERATURE_REFERENCES, @@ -96,7 +98,18 @@ "모든 파일 (*)" ) PROJECT_FILTER = N_("KStruct 프로젝트 (*{suffix})") # tr(PROJECT_FILTER, suffix=SUFFIX) +OPENABLE = STEP_SUFFIXES | IGES_SUFFIXES | MESH_SUFFIXES | {SUFFIX} # drag and drop +# mouse operations listed in the shortcut window next to the keyboard shortcuts +MOUSE_HELP = [ + (N_("왼쪽 끌기"), N_("돌려 보기")), + (N_("휠"), N_("확대·축소")), + (N_("가운데 끌기 / Shift+왼쪽 끌기"), N_("옮겨 보기")), + (N_("클릭 / Ctrl+클릭"), N_("면 선택 / 여러 면 선택")), + (N_("오른쪽 클릭"), N_("부품 보기·선택 메뉴")), + (N_("파일 끌어다 놓기"), N_("모델·프로젝트 열기")), +] MAX_UNDO = 50 # steps kept in the undo history +SIDE_MIN_WIDTH = 340 # px; widened when a step's panel needs more (see _fit_side) SAMPLES = {"bracket": l_bracket, "two_plates": two_plates, "bolted": bolted_plates} SAMPLE_PART_NAMES = { "bracket": [N_("브래킷")], @@ -198,6 +211,8 @@ def __init__(self) -> None: self.viewer.apply_theme(self.theme) self.viewer.selection_changed.connect(self._selection_changed) self.viewer.probed.connect(lambda text: self.panels[STEP_RESULT].probe.setText(text)) + self.viewer.notice.connect(lambda text: self.statusBar().showMessage(text, 8000)) + self.setAcceptDrops(True) self.panels: list[steps.StepPanel] = [ steps.OpenStep(self), @@ -219,10 +234,11 @@ def __init__(self) -> None: self.pane.addWidget(self.viewer) splitter.addWidget(self.pane) splitter.setStretchFactor(1, 1) - splitter.setSizes([400, 1040]) + splitter.setSizes([420, 1020]) splitter.setHandleWidth(1) self.setCentralWidget(splitter) self._build_toolbar() + self._build_shortcuts() self._restore_window_state(splitter) self._autosave_timer = QTimer(self) self._autosave_timer.setInterval(prefs.AUTOSAVE_MINUTES * 60 * 1000) @@ -237,7 +253,8 @@ def _build_side(self) -> QWidget: side = QWidget() side.setObjectName("sidePanel") side.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) - side.setMinimumWidth(340) + side.setMinimumWidth(SIDE_MIN_WIDTH) + self._side = side layout = QVBoxLayout(side) layout.setContentsMargins(0, 8, 0, 0) layout.setSpacing(0) @@ -373,6 +390,19 @@ def _fill_welcome_recent(self) -> None: link.clicked.connect(lambda _=False, p=path: self.load(p)) self._welcome_recent.addWidget(link) + def _fit_side(self) -> None: + """Keep the side bar at least as wide as the current step's panel needs: it does + not scroll sideways, so a bar dragged narrower would cut the panel's right edge + off (rows of buttons need up to ~400 px, more in English).""" + row = self.stack.currentIndex() + scroll = self.stack.widget(row) + need = ( + self.panels[row].minimumSizeHint().width() + + scroll.verticalScrollBar().sizeHint().width() + + 2 + ) + self._side.setMinimumWidth(max(SIDE_MIN_WIDTH, need)) + def _show_pane(self) -> None: """Welcome page without a project, the 3D view with one.""" if self.project is None: @@ -482,6 +512,7 @@ def action(text, slot, key=None, shortcut=None, icon=None, icon_only=False): info_menu = QMenu(self.info_button) info_menu.addAction(tr("KStruct 정보"), lambda: AboutDialog(self).exec()) info_menu.addAction(tr("사용 안내"), lambda: HelpDialog("help.mode", self).exec()) + info_menu.addAction(tr("단축키 목록"), self.show_shortcuts) info_menu.addAction(tr("업데이트 확인…"), self.show_update) info_menu.addSeparator() info_menu.addAction(tr("오류 신고 (GitHub 이슈)"), lambda: open_contact(self)) @@ -497,6 +528,135 @@ def action(text, slot, key=None, shortcut=None, icon=None, icon_only=False): self.info_button.setMenu(info_menu) bar.addWidget(self.info_button) + def _build_shortcuts(self) -> None: + """Keyboard shortcuts without a button of their own (the toolbar's and the 3D + view's actions carry theirs).""" + + def shortcut(text, keys, slot) -> QAction: + a = QAction(text, self) + a.setShortcut(QKeySequence(keys)) + a.setShortcutContext(Qt.ShortcutContext.WindowShortcut) + a.triggered.connect(slot) + self.addAction(a) + return a + + for i, name in enumerate(STEP_NAMES): + shortcut( + tr("{step} 단계로 이동", step=tr(name)), + f"Alt+{i + 1}", + lambda _=False, step=i: self._go(step), + ) + shortcut(tr("메시 만들기"), "Ctrl+M", self.mesh_shortcut) + shortcut(tr("해석 시작"), "F5", self.solve_shortcut) + shortcut( + tr("목록에서 고른 항목 삭제"), QKeySequence.StandardKey.Delete, self.delete_shortcut + ) + shortcut(tr("단축키 목록"), "Ctrl+/", self.show_shortcuts) + + def mesh_shortcut(self) -> None: + if self.project is None or self._busy: + return + self._go(STEP_MESH) + if self.panels[STEP_MESH].run.isEnabled(): + self.build_mesh() + + def solve_shortcut(self) -> None: + """F5: open step 6 and start if the checklist is complete (else the checklist shows + what is missing).""" + if self.project is None or self._busy: + return + self._go(STEP_SOLVE) + if self.panels[STEP_SOLVE].run.isEnabled(): + self.solve() + else: + self.statusBar().showMessage( + tr("해석 전 확인 목록에서 ✘ 표시된 항목을 먼저 채우세요."), 8000 + ) + + def delete_shortcut(self) -> None: + if self.project is None or self._busy: + return + panel = self.panels[self.nav.currentRow()] + if hasattr(panel, "delete_selected"): + panel.delete_selected() + + def shortcut_entries(self) -> list[tuple[str, str]]: + """(keys, what it does) for every action with a shortcut, as they really are.""" + entries: list[tuple[str, str]] = [] + seen: set[str] = set() + for a in self.findChildren(QAction): + keys = a.shortcut().toString(QKeySequence.SequenceFormat.NativeText) + if not keys or keys in seen: + continue + seen.add(keys) + entries.append((keys, a.text().replace("&", ""))) + return entries + + def show_shortcuts(self) -> None: + from PySide6.QtWidgets import QDialog, QDialogButtonBox, QTextBrowser + + def table(rows) -> str: + cells = "".join( + f"{k}{v}" + for k, v in rows + ) + return f"{cells}
" + + html = ( + f"

{tr('키보드')}

" + + table(self.shortcut_entries()) + + f"

{tr('마우스')}

" + + table([(tr(k), tr(v)) for k, v in MOUSE_HELP]) + ) + dialog = QDialog(self) + dialog.setWindowTitle(tr("단축키 목록")) + dialog.resize(560, 640) + layout = QVBoxLayout(dialog) + text = QTextBrowser() + text.setHtml(html) + layout.addWidget(text) + buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close) + buttons.rejected.connect(dialog.reject) + layout.addWidget(buttons) + dialog.exec() + + # --- drag and drop --------------------------------------------------------------- + + @staticmethod + def _dropped_file(event) -> Path | None: + urls = event.mimeData().urls() if event.mimeData().hasUrls() else [] + paths = [Path(u.toLocalFile()) for u in urls if u.isLocalFile()] + if len(paths) == 1 and paths[0].suffix.lower() in OPENABLE: + return paths[0] + return None + + def dragEnterEvent(self, event) -> None: # noqa: N802 (Qt override) + if self._dropped_file(event) is not None and not self._busy: + event.acceptProposedAction() + else: + event.ignore() + + def dropEvent(self, event) -> None: # noqa: N802 (Qt override) + path = self._dropped_file(event) + if path is None or self._busy: + event.ignore() + return + event.acceptProposedAction() + # after the drop has finished: a dialog inside the drop handler freezes the + # drag source on some platforms + QTimer.singleShot(0, lambda: self.open_path(path)) + + def open_path(self, path: Path) -> None: + """Open a model or project file the user handed over (drop, recent files).""" + if self.may_discard(): + self.load(path) + + def may_discard(self) -> bool: + """Before something replaces the current project: ask if it has unsaved changes.""" + if self.project is None or not self._dirty or not self.ask_before_close: + return True + return self._confirm(tr("저장하지 않은 변경이 있습니다. 저장하지 않고 다른 파일을 열까요?")) + def choose_language(self, lang: str) -> None: """Saved now, applied at the next start (widgets are built with their texts).""" if lang == prefs.language(): @@ -553,7 +713,9 @@ def _fill_recent_menu(self) -> None: if not files: self.recent_menu.addAction(tr("(최근에 연 파일이 없습니다)")).setEnabled(False) for path in files: - self.recent_menu.addAction(path.name, lambda p=path: self.load(p)).setToolTip(str(path)) + self.recent_menu.addAction(path.name, lambda p=path: self.open_path(p)).setToolTip( + str(path) + ) def _restore_window_state(self, splitter: QSplitter) -> None: geometry, sizes = prefs.window_state() @@ -744,12 +906,14 @@ def _nav_changed(self, step: int) -> None: self.viewer.selection_enabled = step in (STEP_FIXTURE, STEP_LOAD, STEP_MESH) if step != STEP_RESULT: self.viewer.clear_result() + self.viewer.set_highlight([]) if step in (STEP_FIXTURE, STEP_LOAD, STEP_MESH): self.viewer.set_selection([]) self.viewer.show_mesh(self.mesh if step == STEP_MESH else None) if step == STEP_RESULT and self.result is not None: self.show_result() self._update_nav() + self._fit_side() # --- project lifecycle ----------------------------------------------------------- @@ -797,6 +961,8 @@ def new_project(self) -> None: self.setWindowTitle(tr("KStruct — 부품 강도 해석")) def open_file(self) -> None: + if not self.may_discard(): + return path, _ = QFileDialog.getOpenFileName( self, tr("모델 열기"), prefs.last_dir(), tr(CAD_FILTER) ) @@ -837,6 +1003,8 @@ def load(self, path: Path) -> None: ) def open_project(self) -> None: + if not self.may_discard(): + return path, _ = QFileDialog.getOpenFileName( self, tr("프로젝트 열기"), prefs.last_dir(), tr(PROJECT_FILTER, suffix=SUFFIX) ) @@ -897,6 +1065,7 @@ def detect_connections(self, quiet: bool = False) -> None: def invalidate_mesh(self) -> None: self._dirty = True self.mesh = None + self.viewer.clear_problem() self._invalidate_result() self._record() @@ -909,6 +1078,8 @@ def _invalidate_result(self) -> None: def _project_changed(self) -> None: self._dirty = True + self.viewer.clear_problem() + self._fit_side() self._invalidate_result() self._annotate() self._record() @@ -983,6 +1154,7 @@ def mesh_inputs(p: Project): if mesh_inputs(old) != mesh_inputs(project): self.mesh = None self._dirty = True + self.viewer.clear_problem() self._invalidate_result() self._annotate() self.panels[STEP_OPEN].refresh() @@ -1238,7 +1410,7 @@ def failed(e): panel.status.setText(tr("해석을 취소했습니다.")) return log.warning("solve failed: %s: %s", type(e).__name__, e) - self.warn(friendly_error(e)) + self.report_failure(e, project) self._job = run_job(job, done, failed, show_progress) @@ -1734,8 +1906,42 @@ def capture_result_images(self) -> list[tuple[str, bytes]]: # --- dialogs --------------------------------------------------------------------- - def warn(self, message: str) -> None: - QMessageBox.warning(self, tr("확인이 필요합니다"), message) + def report_failure(self, e: Exception, project: Project) -> None: + """Error message for a failed run. Paints the parts it is about in the 3D view + (until the next edit) and offers to open the step that fixes it.""" + parts, fix = diagnose.problem_parts(project, e) + message = friendly_error(e) + if parts: + self.viewer.mark_problem(parts=parts) + names = ", ".join(f"'{tr_data(project.part(pid).name)}'" for pid in parts) + message += "\n\n" + tr( + "해당 부품을 3D 화면에 빨갛게 표시했습니다: {names}", names=names + ) + step = { + diagnose.FIX_FIXTURE: STEP_FIXTURE, + diagnose.FIX_CONNECTION: STEP_OPEN, + diagnose.FIX_LOAD: STEP_LOAD, + }.get(fix) + if step is None: + self.warn(message) + else: + self.warn(message, fix_step=step) + + def warn(self, message: str, fix_step: int | None = None) -> None: + """Warning box; with fix_step it also has a button that opens that step.""" + if fix_step is None: + QMessageBox.warning(self, tr("확인이 필요합니다"), message) + return + box = QMessageBox(QMessageBox.Icon.Warning, tr("확인이 필요합니다"), message, parent=self) + go = box.addButton( + tr("{step} 단계로 가기", step=tr(STEP_NAMES[fix_step])), + QMessageBox.ButtonRole.AcceptRole, + ) + box.addButton(tr("닫기"), QMessageBox.ButtonRole.RejectRole) + box.setDefaultButton(go) + box.exec() + if box.clickedButton() is go: + self._go(fix_step) def _confirm(self, message: str) -> bool: answer = QMessageBox.question(self, tr("확인"), message) diff --git a/src/kstruct/ui/steps.py b/src/kstruct/ui/steps.py index 57b90d9..84f384c 100644 --- a/src/kstruct/ui/steps.py +++ b/src/kstruct/ui/steps.py @@ -6,7 +6,7 @@ from typing import TYPE_CHECKING import numpy as np -from PySide6.QtCore import Qt, Signal +from PySide6.QtCore import QEvent, QObject, Qt, Signal from PySide6.QtWidgets import ( QButtonGroup, QCheckBox, @@ -20,6 +20,7 @@ QLabel, QListWidget, QListWidgetItem, + QMenu, QProgressBar, QPushButton, QRadioButton, @@ -176,6 +177,33 @@ def _row(*widgets: QWidget) -> QWidget: return box +class FaceHighlighter(QObject): + """Paints the faces of the list entry under the mouse (else the current one) in the + 3D view, so it is clear which faces an entry like "고정: 면#3, 면#7" is about.""" + + def __init__(self, app: MainWindow, widget: QListWidget, faces_for_row) -> None: + super().__init__(widget) + self.app, self.widget, self.faces_for_row = app, widget, faces_for_row + widget.setMouseTracking(True) + widget.itemEntered.connect(lambda item: self.show(widget.row(item))) + widget.currentRowChanged.connect(self.show) + widget.viewport().installEventFilter(self) + + def eventFilter(self, obj, event) -> bool: # noqa: N802 (Qt override) + if event.type() == QEvent.Type.Leave: + self.show(self.widget.currentRow()) + return False + + def show(self, row: int) -> None: + if self.app.project is None: + return + try: + faces = list(self.faces_for_row(row)) if row >= 0 else [] + except IndexError: + faces = [] + self.app.viewer.set_highlight(faces) + + class StepPanel(QWidget): changed = Signal() @@ -231,7 +259,7 @@ def __init__(self, app: MainWindow) -> None: (tr("예제: 볼트"), "bolted"), ): b = QPushButton(label) - b.clicked.connect(lambda _=False, n=name: app.open_sample(n)) + b.clicked.connect(lambda _=False, n=name: app.may_discard() and app.open_sample(n)) samples.addWidget(b) box = QWidget() box.setLayout(samples) @@ -240,6 +268,8 @@ def __init__(self, app: MainWindow) -> None: self.add(with_help(_section(tr("부품")), "view.parts")) self.parts = QListWidget() self.parts.itemChanged.connect(self._toggled) + self.parts.setContextMenuPolicy(Qt.ContextMenuPolicy.CustomContextMenu) + self.parts.customContextMenuRequested.connect(self._parts_menu) self.add(self.parts, 1) self.conn_box = QGroupBox(tr("부품 사이 연결")) @@ -250,6 +280,14 @@ def __init__(self, app: MainWindow) -> None: conn.addWidget(with_help(detect, "connection.bonded")) self.connections = QListWidget() self.connections.setMaximumHeight(110) + FaceHighlighter( + app, + self.connections, + lambda row: ( + self.app.project.connections[row].faces_a + + self.app.project.connections[row].faces_b + ), + ) conn.addWidget(self.connections) self.conn_kind = QComboBox() for kind, label in CONNECTION_LABELS.items(): @@ -342,6 +380,24 @@ def _remove_connection(self) -> None: self.app.invalidate_mesh() self.refresh() + def delete_selected(self) -> None: + self._remove_connection() + + def _parts_menu(self, pos) -> None: + """Right-click on the part list: the 3D view's show / hide commands (screen only; + the check box is what takes a part out of the analysis).""" + item = self.parts.itemAt(pos) + if item is None: + return + pid = item.data(Qt.ItemDataRole.UserRole) + viewer = self.app.viewer + menu = QMenu(self) + menu.addAction(tr("이 부품만 보기"), lambda: viewer.isolate_part(pid)) + menu.addAction(tr("이 부품 숨기기 (화면에서만)"), lambda: viewer.hide_part_view(pid)) + menu.addAction(tr("반투명 (클릭이 통과)"), lambda: viewer.set_part_translucent(pid, True)) + menu.addAction(tr("모든 부품 다시 보이기"), viewer.show_all_parts) + menu.exec(self.parts.viewport().mapToGlobal(pos)) + # --- 2. material -------------------------------------------------------------------- @@ -569,6 +625,7 @@ def __init__(self, app: MainWindow, title: str, key: str) -> None: self.selection_label = _hint("") self.items = QListWidget() self.items.setMinimumHeight(120) + FaceHighlighter(app, self.items, lambda row: self.entries()[row].faces) self.remove = QPushButton(tr("선택한 항목 삭제")) self.remove.clicked.connect(self._remove) @@ -607,6 +664,9 @@ def _remove(self) -> None: self.changed.emit() self.refresh() + def delete_selected(self) -> None: + self._remove() + class FixtureStep(_FaceListStep): def __init__(self, app: MainWindow) -> None: @@ -722,6 +782,11 @@ def _build_bolt_box(self) -> None: self.bolt_add.clicked.connect(self._add_bolt) layout.addWidget(self.bolt_add) self.bolt_list = QListWidget() + FaceHighlighter( + self.app, + self.bolt_list, + lambda row: [self.app.project.bolts[row].hole_a, self.app.project.bolts[row].hole_b], + ) self.bolt_list.setMaximumHeight(100) layout.addWidget(self.bolt_list) remove = QPushButton(tr("선택한 볼트 삭제")) @@ -779,6 +844,10 @@ def _remove_bolt(self) -> None: self.changed.emit() self.refresh() + def delete_selected(self) -> None: + # the bolt list when it has the keyboard focus, else the fixture list + (self._remove_bolt if self.bolt_list.hasFocus() else self._remove)() + def refresh(self) -> None: super().refresh() self._update_units() @@ -1297,6 +1366,9 @@ def __init__(self, app: MainWindow) -> None: self.refine_add.clicked.connect(self._add_refinement) layout.addWidget(self.refine_add) self.refinements = QListWidget() + FaceHighlighter( + app, self.refinements, lambda row: self.app.project.mesh_refinements[row].faces + ) self.refinements.setMaximumHeight(90) layout.addWidget(self.refinements) remove = QPushButton(tr("선택한 항목 삭제")) @@ -1339,6 +1411,9 @@ def _remove_refinement(self) -> None: self.app.invalidate_mesh() self.refresh() + def delete_selected(self) -> None: + self._remove_refinement() + def refresh(self) -> None: project = self.app.project self.quality.blockSignals(True) diff --git a/src/kstruct/ui/theme.py b/src/kstruct/ui/theme.py index 4a070c9..a30d30c 100644 --- a/src/kstruct/ui/theme.py +++ b/src/kstruct/ui/theme.py @@ -159,6 +159,10 @@ def _stylesheet(t: Theme) -> str: QToolBar QToolButton:hover {{ background: {t.raised}; }} QToolBar QToolButton:pressed {{ background: {t.border}; }} QToolBar QToolButton::menu-indicator {{ image: none; }} +QToolBar QToolButton:checked {{ background: {t.raised}; color: {t.accent}; font-weight: 700; }} +/* the slim bar above the 3D view */ +QToolBar#viewStrip {{ padding: 1px 8px; }} +QToolBar#viewStrip QToolButton {{ padding: 3px 8px; }} QLabel#appName {{ font-size: 15pt; font-weight: 700; color: {t.text}; padding: 0 12px 0 2px; }} QLabel#appName[accent="true"] {{ color: {t.accent}; }} diff --git a/src/kstruct/ui/viewer.py b/src/kstruct/ui/viewer.py index 369f3e2..cdab498 100644 --- a/src/kstruct/ui/viewer.py +++ b/src/kstruct/ui/viewer.py @@ -7,20 +7,27 @@ import numpy as np import pyvista as pv -from PySide6.QtCore import QTimer, Signal -from PySide6.QtWidgets import QVBoxLayout, QWidget +from PySide6.QtCore import Qt, QTimer, Signal +from PySide6.QtGui import QAction, QCursor, QKeySequence +from PySide6.QtWidgets import QMenu, QToolBar, QToolButton, QVBoxLayout, QWidget from pyvistaqt import QtInteractor from scipy.spatial import cKDTree from vtkmodules.vtkCommonCore import VTK_FONT_FILE -from vtkmodules.vtkRenderingCore import vtkCellPicker +from vtkmodules.vtkCommonDataModel import vtkDataObject, vtkSelectionNode +from vtkmodules.vtkRenderingCore import vtkCellPicker, vtkHardwareSelector from kstruct.fem.mesh import FEMesh from kstruct.geometry import tessellate +from kstruct.geometry.face_info import similar_faces, tangent_faces from kstruct.geometry.tessellate import bounding_diagonal +from kstruct.i18n import N_, tr from kstruct.model import FaceRef, Fixture, FixtureKind, Load, LoadKind, Project PART_COLORS = ["#9fb4c7", "#c7b29f", "#a8c79f", "#c79fbf", "#9fc7c3", "#c7c39f"] SELECT_COLOR = "#ffd23f" +HIGHLIGHT_COLOR = "#38c6f4" # faces of the list entry under the mouse +PROBLEM_COLOR = "#e5484d" # parts / faces an error message is about +TRANSLUCENT_OPACITY = 0.3 FIXTURE_COLORS = { FixtureKind.FIXED: "#2e9e5b", FixtureKind.ROLLER: "#2aa1b3", @@ -32,6 +39,18 @@ BOLT_COLOR = "#4a4f57" CLICK_TOLERANCE_PX = 4 # press/release further apart than this is a rotate, not a click +# standard views: (name, label, shortcut); the shortcuts follow the numeric keypad habit of +# CAD programs (1 front, 3 right, 7 top, Ctrl for the opposite side, 0 isometric) +VIEWS = [ + ("iso", N_("등각 보기"), "0"), + ("front", N_("앞에서 보기"), "1"), + ("back", N_("뒤에서 보기"), "Ctrl+1"), + ("right", N_("오른쪽에서 보기"), "3"), + ("left", N_("왼쪽에서 보기"), "Ctrl+3"), + ("top", N_("위에서 보기"), "7"), + ("bottom", N_("아래에서 보기"), "Ctrl+7"), +] + # Netgen TRI6 (mid nodes on edges 12, 02, 01) -> VTK quadratic triangle (01, 12, 20) _TRI6_TO_VTK = [0, 1, 2, 5, 3, 4] # Netgen TET10 mid nodes 4..9 on edges 01 02 03 12 13 23 -> VTK quadratic tetra 01 12 20 03 13 23 @@ -62,6 +81,7 @@ class ResultField: class ModelViewer(QWidget): selection_changed = Signal(list) # list[FaceRef] probed = Signal(str) # text describing the value under the cursor in result mode + notice = Signal(str) # one-line message for the status bar def __init__(self, parent: QWidget | None = None) -> None: super().__init__(parent) @@ -70,7 +90,9 @@ def __init__(self, parent: QWidget | None = None) -> None: self.plotter = QtInteractor(self, off_screen=False) layout = QVBoxLayout(self) layout.setContentsMargins(0, 0, 0, 0) - layout.addWidget(self.plotter) + layout.setSpacing(0) + layout.addWidget(self._build_strip()) + layout.addWidget(self.plotter, 1) from kstruct.ui import theme @@ -83,9 +105,16 @@ def __init__(self, parent: QWidget | None = None) -> None: self._meshes: dict[int, pv.PolyData] = {} self._actors: dict[int, list] = {} self._actor_part: dict[str, int] = {} # vtk actor address -> part id - self._hidden: set[int] = set() + self._hidden: set[int] = set() # parts left out of the analysis (step 1) + self._view_hidden: set[int] = set() # parts only hidden on screen (isolate / hide) + self._translucent: set[int] = set() # see-through parts, clicks pass through them + self._see_through = False # every part see-through (clicks still hit them) self._selection: list[FaceRef] = [] self._face_colors: dict[FaceRef, str] = {} + self._highlight: list[FaceRef] = [] + self._problem_parts: set[int] = set() + self._problem_faces: list[FaceRef] = [] + self._box_mode = False self._overlay: list = [] # arrows etc. self._mesh_actor = None self._result_actor = None @@ -94,8 +123,9 @@ def __init__(self, parent: QWidget | None = None) -> None: self._result_tree: cKDTree | None = None self._result_field: ResultField | None = None self._probe_actor = None - self.selection_enabled = True + self._selection_enabled = True self._press_pos: tuple[int, int] | None = None + self._right_pos: tuple[int, int] | None = None # deformation animation: surface points = base + factor(t) * delta self._anim_surface: pv.PolyData | None = None @@ -112,6 +142,144 @@ def __init__(self, parent: QWidget | None = None) -> None: self._picker.SetTolerance(0.0005) self.plotter.iren.add_observer("LeftButtonPressEvent", self._on_press) self.plotter.iren.add_observer("LeftButtonReleaseEvent", self._on_release) + self.plotter.iren.add_observer("RightButtonPressEvent", self._on_right_press) + self.plotter.iren.add_observer("RightButtonReleaseEvent", self._on_right_release) + + # --- view strip ---------------------------------------------------------------- + + def _build_strip(self) -> QToolBar: + """Thin bar above the 3D view: standard views, see-through, selection helpers.""" + from kstruct.ui.help import topic + + strip = QToolBar() + strip.setObjectName("viewStrip") + strip.setMovable(False) + strip.setContextMenuPolicy(Qt.ContextMenuPolicy.PreventContextMenu) + strip.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextOnly) + + def act(text, slot, key, shortcut=None, checkable=False) -> QAction: + a = QAction(text, self) + a.setToolTip(topic(key).short) + a.setCheckable(checkable) + if shortcut: + a.setShortcut(QKeySequence(shortcut)) + a.setShortcutContext(Qt.ShortcutContext.WindowShortcut) + self.addAction(a) # shortcuts work while the menu is closed + a.triggered.connect(slot) + return a + + self.view_actions: dict[str, QAction] = {} + views = QMenu(self) + for name, label, shortcut in VIEWS: + a = act(tr(label), lambda _=False, n=name: self.set_view(n), "view.views", shortcut) + views.addAction(a) + self.view_actions[name] = a + views.addSeparator() + self.show_all_action = act(tr("모든 부품 다시 보이기"), self.show_all_parts, "view.isolate") + views.addAction(self.show_all_action) + button = QToolButton() + button.setText(tr("보기 ▾")) + button.setToolTip(topic("view.views").short) + button.setMenu(views) + button.setPopupMode(QToolButton.ToolButtonPopupMode.InstantPopup) + strip.addWidget(button) + self.see_through_action = act( + tr("반투명"), self.set_see_through, "view.see_through", checkable=True + ) + strip.addAction(self.see_through_action) + self._select_separator = strip.addSeparator() + self.box_action = act( + tr("영역 선택"), self.set_box_mode, "view.box_select", "B", checkable=True + ) + self.similar_action = act(tr("같은 크기 모두"), self.select_similar, "view.similar", "S") + self.tangent_action = act(tr("이어진 면"), self.select_tangent, "view.tangent", "T") + self.clear_action = act( + tr("선택 해제"), self.clear_selection, "view.clear_selection", "Esc" + ) + self._select_actions = [ + self.box_action, + self.similar_action, + self.tangent_action, + self.clear_action, + ] + for a in self._select_actions: + strip.addAction(a) + self.strip = strip + return strip + + @property + def selection_enabled(self) -> bool: + return self._selection_enabled + + @selection_enabled.setter + def selection_enabled(self, on: bool) -> None: + """Face picking is on in the steps that attach things to faces (3, 4, 5).""" + self._selection_enabled = on + self._select_separator.setVisible(on) + for a in self._select_actions: + a.setVisible(on) + a.setEnabled(on) + if not on and self._box_mode: + self.set_box_mode(False) + + def set_view(self, name: str) -> None: + p = self.plotter + { + "iso": p.view_isometric, + "front": p.view_xz, + "back": lambda: p.view_xz(negative=True), + "right": p.view_yz, + "left": lambda: p.view_yz(negative=True), + "top": p.view_xy, + "bottom": lambda: p.view_xy(negative=True), + }[name]() + p.render() + + def set_see_through(self, on: bool) -> None: + self._see_through = bool(on) + self.see_through_action.setChecked(self._see_through) + self._apply_visibility() + self.plotter.render() + + def isolate_part(self, part_id: int) -> None: + """Show only this part (on screen only: the analysis still uses every part).""" + self._view_hidden = set(self._actors) - {part_id} + self._apply_visibility() + self.plotter.render() + + def hide_part_view(self, part_id: int) -> None: + self._view_hidden.add(part_id) + self._apply_visibility() + self.plotter.render() + + def set_part_translucent(self, part_id: int, on: bool) -> None: + (self._translucent.add if on else self._translucent.discard)(part_id) + self._apply_visibility() + self.plotter.render() + + def show_all_parts(self) -> None: + self._view_hidden.clear() + self._translucent.clear() + self._apply_visibility() + self.plotter.render() + + @property + def view_hidden(self) -> set[int]: + return set(self._view_hidden) + + def _apply_visibility(self) -> None: + # see-through parts use plain alpha blending: depth peeling looks slightly better + # but leaves the renderer in a state where box selection returns hidden faces + cad = self._result_actor is None + for part_id, actors in self._actors.items(): + visible = cad and part_id not in self._hidden and part_id not in self._view_hidden + for actor in actors: + actor.SetVisibility(visible) + body = actors[0] + translucent = self._see_through or part_id in self._translucent + body.prop.opacity = TRANSLUCENT_OPACITY if translucent else 1.0 + body.SetPickable(part_id not in self._translucent) + self.show_all_action.setEnabled(bool(self._view_hidden or self._translucent)) # --- CAD model ----------------------------------------------------------------- @@ -139,8 +307,13 @@ def load_project(self, project: Project) -> None: self._actors.clear() self._actor_part.clear() self._hidden.clear() + self._view_hidden.clear() + self._translucent.clear() self._selection.clear() self._face_colors.clear() + self._highlight.clear() + self._problem_parts.clear() + self._problem_faces.clear() self._overlay.clear() self._result_extras.clear() self._mesh_actor = self._result_actor = self._probe_actor = None @@ -167,15 +340,14 @@ def load_project(self, project: Project) -> None: self._meshes[part.id] = mesh self._actors[part.id] = [body, edges] self._actor_part[_address(body)] = part.id + self._apply_visibility() self._repaint() self.plotter.reset_camera() self.plotter.view_isometric() def set_part_visible(self, part_id: int, visible: bool) -> None: (self._hidden.discard if visible else self._hidden.add)(part_id) - if self._result_actor is None: - for actor in self._actors.get(part_id, []): - actor.SetVisibility(visible) + self._apply_visibility() self.plotter.render() def fit(self) -> None: @@ -191,6 +363,55 @@ def set_selection(self, refs: list[FaceRef]) -> None: self._repaint() self.selection_changed.emit(self.selection) + def clear_selection(self) -> None: + if self._box_mode: + self.set_box_mode(False) + if self._selection: + self.set_selection([]) + + def set_highlight(self, refs: list[FaceRef]) -> None: + """Show which faces a list entry is about (painted under the selection).""" + refs = list(refs) + if refs != self._highlight: + self._highlight = refs + self._repaint() + + def mark_problem(self, parts=(), faces=()) -> None: + """Paint the parts / faces an error message is about; cleared by clear_problem.""" + self._problem_parts = set(parts) + self._problem_faces = list(faces) + self._repaint() + + def clear_problem(self) -> None: + if self._problem_parts or self._problem_faces: + self._problem_parts.clear() + self._problem_faces.clear() + self._repaint() + + def _expand_selection(self, finder, empty_message: str) -> None: + if not self._selection: + self.notice.emit(empty_message) + return + found = list(self._selection) + for ref in self._selection: + shape = self._project.part(ref.part_id).shape + found += [FaceRef(ref.part_id, i) for i in finder(shape, ref.face_index)] + added = len(dict.fromkeys(found)) - len(self._selection) + self.set_selection(found) + self.notice.emit(tr("면 {n}개를 더 선택했습니다.", n=added)) + + def select_similar(self) -> None: + """Add every face of the same kind and size (all holes of one diameter).""" + self._expand_selection( + similar_faces, tr("먼저 면을 하나 클릭한 다음 '같은 크기 모두'를 누르세요.") + ) + + def select_tangent(self) -> None: + """Add the faces joined smoothly to the selection (fillets, split holes).""" + self._expand_selection( + tangent_faces, tr("먼저 면을 하나 클릭한 다음 '이어진 면'을 누르세요.") + ) + def annotate(self, fixtures: list[Fixture], loads: list[Load], bolts=()) -> None: """Color fixture/load/bolt faces and draw load arrows.""" self._face_colors.clear() @@ -289,14 +510,19 @@ def _repaint(self) -> None: selected = set(self._selection) for part_id, mesh in self._meshes.items(): rgb = mesh.cell_data["rgb"] - rgb[:] = pv.Color(PART_COLORS[part_id % len(PART_COLORS)]).int_rgb + base = PROBLEM_COLOR if part_id in self._problem_parts else None + rgb[:] = pv.Color(base or PART_COLORS[part_id % len(PART_COLORS)]).int_rgb face_id = mesh.cell_data["face_id"] - for ref, color in self._face_colors.items(): - if ref.part_id == part_id: - rgb[face_id == ref.face_index] = pv.Color(color).int_rgb - for ref in selected: - if ref.part_id == part_id: - rgb[face_id == ref.face_index] = pv.Color(SELECT_COLOR).int_rgb + layers = [ + (self._face_colors.items()), + ((ref, PROBLEM_COLOR) for ref in self._problem_faces), + ((ref, HIGHLIGHT_COLOR) for ref in self._highlight), + ((ref, SELECT_COLOR) for ref in selected), + ] + for layer in layers: + for ref, color in layer: + if ref.part_id == part_id: + rgb[face_id == ref.face_index] = pv.Color(color).int_rgb rgb.VTKObject.Modified() self.plotter.render() @@ -381,9 +607,7 @@ def show_result( self._result_points = boundary self._result_tree = cKDTree(points[boundary]) self._result_field = field - for actors in self._actors.values(): - for actor in actors: - actor.SetVisibility(False) + self._apply_visibility() for actor in self._overlay: actor.SetVisibility(False) if self._animated and self._anim_surface is not None: @@ -435,9 +659,7 @@ def clear_result(self, render: bool = True) -> None: self.plotter.remove_actor(self._probe_actor) self._probe_actor = None self._result_field = None - for part_id, actors in self._actors.items(): - for actor in actors: - actor.SetVisibility(part_id not in self._hidden) + self._apply_visibility() for actor in self._overlay: actor.SetVisibility(True) if render: @@ -498,6 +720,121 @@ def _on_release(self, *_args) -> None: else: self.set_selection([ref] if ref is not None else []) + def _on_right_press(self, *_args) -> None: + self._right_pos = self.plotter.iren.get_event_position() + + def _on_right_release(self, *_args) -> None: + pos = self.plotter.iren.get_event_position() + start, self._right_pos = self._right_pos, None + if start is None or np.hypot(pos[0] - start[0], pos[1] - start[1]) > CLICK_TOLERANCE_PX: + return # a right-drag zooms + if self._result_actor is not None or self._project is None: + return + ref = self._pick(*pos) + # after VTK has finished with the event: a modal menu inside its callback can + # leave the interactor style mid-gesture + QTimer.singleShot(0, lambda: self._context_menu(ref)) + + def context_menu_actions(self, ref: FaceRef | None) -> list[tuple[str, object]]: + """(label, callback) pairs of the right-click menu over a part (None: empty spot).""" + items: list[tuple[str, object]] = [] + if ref is not None: + pid = ref.part_id + items.append((tr("이 부품만 보기"), lambda: self.isolate_part(pid))) + items.append((tr("이 부품 숨기기 (화면에서만)"), lambda: self.hide_part_view(pid))) + items.append((tr("반투명 (클릭이 통과)"), lambda: self.set_part_translucent(pid, True))) + if self._selection_enabled: + if ref not in self._selection: + items.append((tr("이 면 선택"), lambda: self.set_selection([ref]))) + items.append((tr("같은 크기 면 모두 선택"), self._menu_select(ref, True))) + items.append((tr("이어진 면 선택"), self._menu_select(ref, False))) + if self._view_hidden or self._translucent: + items.append((tr("모든 부품 다시 보이기"), self.show_all_parts)) + return items + + def _menu_select(self, ref: FaceRef, similar: bool): + def run(): + if ref not in self._selection: + self.set_selection([ref]) + (self.select_similar if similar else self.select_tangent)() + + return run + + def _context_menu(self, ref: FaceRef | None) -> None: + items = self.context_menu_actions(ref) + if not items: + return + menu = QMenu(self) + for label, callback in items: + menu.addAction(label, callback) + menu.exec(QCursor.pos()) + + # --- box selection --------------------------------------------------------------- + + def set_box_mode(self, on: bool) -> None: + """Left-drag draws a rectangle and selects the visible faces inside it (Ctrl adds + to the selection); rotating is off meanwhile (middle button pans, wheel zooms).""" + on = bool(on) and self._selection_enabled + if on == self._box_mode: + self.box_action.setChecked(on) + return + self._box_mode = on + self.box_action.setChecked(on) + iren = self.plotter.iren + if on: + self.plotter.enable_rubber_band_2d_style() + style = iren.interactor.GetInteractorStyle() + style.AddObserver("SelectionChangedEvent", self._box_selected) + self.notice.emit( + tr("영역 선택: 끌어서 사각형을 그리면 보이는 면이 선택됩니다. Ctrl을 누르면 추가.") + ) + else: + self.plotter.enable_trackball_style() + + def _box_selected(self, style, _event) -> None: + (x0, y0), (x1, y1) = style.GetStartPosition(), style.GetEndPosition() + if abs(x1 - x0) <= CLICK_TOLERANCE_PX and abs(y1 - y0) <= CLICK_TOLERANCE_PX: + return # a click: handled by _on_release like any other + additive = bool(self.plotter.iren.interactor.GetControlKey()) + self.box_select(x0, y0, x1, y1, additive) + + def faces_in_box(self, x0: int, y0: int, x1: int, y1: int) -> list[FaceRef]: + """Faces with a visible (not hidden behind others) bit inside the rectangle in + display coordinates (origin bottom left).""" + selector = vtkHardwareSelector() + selector.SetRenderer(self.plotter.renderer) + selector.SetFieldAssociation(vtkDataObject.FIELD_ASSOCIATION_CELLS) + selector.SetArea(int(min(x0, x1)), int(min(y0, y1)), int(max(x0, x1)), int(max(y0, y1))) + # the SSAA render pass garbles the selection colour buffer ("too many props") + self.plotter.disable_anti_aliasing() + # render the current state first: an opacity changed since the last frame (parts + # made see-through and back) otherwise left stale depth, and faces behind showed up + self.plotter.render() + try: + result = selector.Select() + finally: + self.plotter.enable_anti_aliasing("ssaa") + found: list[FaceRef] = [] + if result is None: + return found + for i in range(result.GetNumberOfNodes()): + node = result.GetNode(i) + prop = node.GetProperties().Get(vtkSelectionNode.PROP()) + part_id = self._actor_part.get(_address(prop)) if prop is not None else None + ids = node.GetSelectionList() + if part_id is None or ids is None: + continue + cells = np.array([ids.GetValue(j) for j in range(ids.GetNumberOfTuples())], dtype=int) + face_id = self._meshes[part_id].cell_data["face_id"] + cells = cells[(cells >= 0) & (cells < len(face_id))] + found += [FaceRef(part_id, int(f)) for f in np.unique(face_id[cells])] + return list(dict.fromkeys(found)) + + def box_select(self, x0: int, y0: int, x1: int, y1: int, additive: bool = False) -> None: + found = self.faces_in_box(x0, y0, x1, y1) + self.set_selection((self._selection if additive else []) + found) + self.notice.emit(tr("면 {n}개를 선택했습니다.", n=len(self._selection))) + def _pick(self, x: int, y: int) -> FaceRef | None: if not self._picker.Pick(x, y, 0, self.plotter.renderer): return None diff --git a/tests/test_fem_contact.py b/tests/test_fem_contact.py index 570be9e..e0be1a4 100644 --- a/tests/test_fem_contact.py +++ b/tests/test_fem_contact.py @@ -293,3 +293,43 @@ def test_unsettled_contact_iteration_is_flagged(monkeypatch): assert not cut.contact_converged summary = summarize(project, cut, standards.effective_pack(project)) assert "수렴하지 않았습니다" in summary.notes[0] + + +def test_rim_pairs_opening_during_friction_sweeps_do_not_exhaust_the_loop(monkeypatch): + """Under a bolt preload with friction the clamped area shrinks while the anchors + settle: rim pairs open one or two at a time between friction sweeps. Those openings + follow the friction relaxation and must not use up the active-set iteration budget; + they did, and the three-bolt sample at the normal mesh came back "not converged" + (here the budget is cut to 5 so the coarse mesh shows it).""" + import kstruct.fem.contact as contact + from kstruct.fem.bolts import hole_axis, recommended_preload, suggest_size + from kstruct.geometry.contacts import find_touching_faces + from kstruct.geometry.samples import bolted_plates, write_step + from kstruct.geometry.step_import import load_cad + from kstruct.model import Bolt + + project = load_cad(write_step(bolted_plates(), _tmp_step())) + lower, upper = (p.shape for p in project.parts) + project.connections = find_touching_faces(project) + project.connections[0].kind = ConnectionKind.CONTACT + project.connections[0].friction = 0.2 + for x, y in ((10, 10), (70, 10), (40, 50)): + a = FaceRef(0, face_at(lower, (x + 5.5, y, 2.5))) + b = FaceRef(1, face_at(upper, (x + 5.5, y, 7.5))) + size = suggest_size(min(hole_axis(project, r)[2] for r in (a, b))) + project.bolts.append(Bolt(a, b, size, "8.8", recommended_preload(size, "8.8"))) + project.fixtures = [Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(lower, (40, 30, 0)))])] + project.loads = [ + Load(LoadKind.FORCE, [FaceRef(1, face_at(upper, (40, 30, 10)))], vector=(1500.0, 0, 0)) + ] + monkeypatch.setattr(contact, "MAX_ITERATIONS", 5) + _, result = _solve(project) + assert result.contact_converged + assert result.applied_load[0] == pytest.approx(1500.0) + + +def _tmp_step(): + import tempfile + from pathlib import Path + + return Path(tempfile.mkdtemp()) / "bolted.step" diff --git a/tests/test_fem_nonlinear.py b/tests/test_fem_nonlinear.py index cfd232f..bab6548 100644 --- a/tests/test_fem_nonlinear.py +++ b/tests/test_fem_nonlinear.py @@ -161,3 +161,43 @@ def face(pid, point): assert np.abs(r.displacement - linear.displacement).max() < 1e-3 * scale for a, b in zip(r.reactions, linear.reactions, strict=True): assert a == pytest.approx(b, rel=2e-3, abs=1e-2) + + +def test_small_strain_tangent_is_elastic_plus_yielding_points(): + """The small-strain tangent is assembled as the elastic matrix plus Bᵀ(D_t − D_e)B + on the yielding points only; it must equal the sum of Bᵀ D_t B over every point.""" + import scipy.sparse as sp + + from kstruct.fem import tet10 + from kstruct.fem.assembly import element_dofs + from kstruct.fem.nonlinear import _Elements, _evaluate + from kstruct.fem.plasticity import return_map + + project = Project(parts=[Part(0, "bar", _box(0, 0, 0, 30, 10, 10), "s")]) + mesh = generate_mesh(project, "coarse") + el = _Elements(mesh, {0: STEEL}, None) + # a stretch past the yield strain over half of the bar + x = mesh.nodes[:, 0] + u = np.zeros((mesh.n_nodes, 3)) + u[:, 0] = np.where(x < 15, 0.004 * x, 0.06 + 0.0005 * (x - 15)) + u = u.ravel() + state = (np.zeros((el.n, 4, 6)), np.zeros((el.n, 4))) + _, K, (_, alpha), _ = _evaluate(el, mesh, u, state, large=False) + assert 0 < np.count_nonzero(alpha) < alpha.size # some points yield, some do not + + n_dof = mesh.n_nodes * 3 + dofs = element_dofs(mesh.tets) + rows, cols, vals = [], [], [] + ue = u[dofs] + for g in range(4): + B = tet10.strain_matrix(el.dN[g]) + strain = np.einsum("eij,ej->ei", B, ue) + _, D, _, _ = return_map(strain, state[0][:, g], state[1][:, g], el.mat) + Ke = (B.transpose(0, 2, 1) @ (D @ B)) * el.dv[g][:, None, None] + rows.append(np.repeat(dofs, 30, axis=1).ravel()) + cols.append(np.tile(dofs, (1, 30)).ravel()) + vals.append(Ke.ravel()) + reference = sp.csr_matrix( + (np.concatenate(vals), (np.concatenate(rows), np.concatenate(cols))), shape=(n_dof, n_dof) + ) + assert abs(K - reference).max() < 1e-9 * abs(reference).max() diff --git a/tests/test_fem_transient.py b/tests/test_fem_transient.py index 25dbbe2..476d396 100644 --- a/tests/test_fem_transient.py +++ b/tests/test_fem_transient.py @@ -95,3 +95,41 @@ def test_transient_needs_heat_capacity_but_no_reference(): assert mean_rise == pytest.approx(expected_rise, rel=1e-6) # energy is conserved with pytest.raises(SolverError, match="비열"): solve_thermal(project, mesh, {0: replace(STEEL, specific_heat=0.0)}) + + +def test_radiating_transient_reuses_one_factorization(monkeypatch): + """With radiation the step matrix changes a little every step; the march solves it + by CG preconditioned with an older factorization. The temperatures must equal a + factorization per step to round-off, and the radiated heat must stay physical.""" + import kstruct.fem.thermal as thermal + from kstruct.fem import assembly + + project, shape = _bar() + project.thermal_duration = 3000.0 + project.initial_temperature = 20.0 + project.loads = [ + Load(LoadKind.HEAT_FLOW, [FaceRef(0, face_at(shape, (0, 5, 5)))], magnitude=20.0), + Load( + LoadKind.RADIATION, + [FaceRef(0, face_at(shape, (50, 5, 10)))], + magnitude=0.9, + ambient=20.0, + ), + ] + mesh = generate_mesh(project, "coarse") + factorizations = [] + real = assembly.make_solver + + def counting(*args, **kwargs): + factorizations.append(1) + return real(*args, **kwargs) + + monkeypatch.setattr(assembly, "make_solver", counting) + reused = solve_thermal(project, mesh, {0: STEEL}) + assert len(factorizations) < thermal.TRANSIENT_STEPS // 4 + monkeypatch.setattr(thermal, "TRANSIENT_CG_MAX", 0) # every step factorized afresh + factorizations.clear() + fresh = solve_thermal(project, mesh, {0: STEEL}) + assert len(factorizations) == thermal.TRANSIENT_STEPS + assert np.abs(reused.history - fresh.history).max() < 1e-8 * fresh.history.max() + assert reused.temperature.max() > 21.0 and 0 < reused.heat_out < 20.0 diff --git a/tests/test_layout.py b/tests/test_layout.py new file mode 100644 index 0000000..bc4a467 --- /dev/null +++ b/tests/test_layout.py @@ -0,0 +1,98 @@ +"""Nothing in the window is cut off at the smallest supported size (1280×720), in either +language: side-panel texts fit their widgets, the panels need no horizontal scrolling and +neither tool bar hides buttons behind its overflow arrow.""" + +import pytest +from PySide6.QtWidgets import ( + QAbstractButton, + QCheckBox, + QLabel, + QPushButton, + QRadioButton, + QScrollArea, + QToolBar, + QToolButton, +) + +from kstruct import i18n + +WIDTH, HEIGHT = 1280, 720 + + +@pytest.fixture(params=["ko", "en"]) +def language(request, monkeypatch, tmp_path): + monkeypatch.setenv("KSTRUCT_DATA_DIR", str(tmp_path)) # no saved splitter position + monkeypatch.setenv("KSTRUCT_LANG", request.param) + i18n.set_language(request.param) + yield request.param + monkeypatch.delenv("KSTRUCT_LANG") + i18n.set_language("ko") + + +def _solved_window(qtbot): + from kstruct.geometry.face_info import face_at + from kstruct.model import FaceRef, Fixture, FixtureKind, Load, LoadKind + from kstruct.ui.main_window import MainWindow + + window = MainWindow() + window.ask_before_close = False + window.warn = lambda text, *a, **k: pytest.fail(text) + qtbot.addWidget(window) + window.resize(WIDTH, HEIGHT) + window.show() + window.open_sample("two_plates") + lower, upper = (p.shape for p in window.project.parts) + for part in window.project.parts: + part.material_id = "s235" + window.project.fixtures = [ + Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(lower, (50, 20, 0)))]) + ] + window.project.loads = [ + Load(LoadKind.FORCE, [FaceRef(1, face_at(upper, (50, 20, 10)))], vector=(0, 0, -500.0)) + ] + window.project.mesh_quality = "coarse" + window._project_changed() + window.solve() + qtbot.waitUntil(lambda: window.result is not None, timeout=120_000) + return window + + +def _clipped(panel) -> list[str]: + problems = [] + for w in panel.findChildren(QAbstractButton) + panel.findChildren(QLabel): + if not w.isVisibleTo(panel) or w.width() == 0: + continue + if isinstance(w, QLabel) and (w.wordWrap() or not w.text() or w.pixmap() is not None): + continue + if isinstance(w, QToolButton) and w.property("role") == "help": + continue + if not isinstance(w, QLabel | QPushButton | QCheckBox | QRadioButton): + continue + need = w.sizeHint().width() + if w.width() + 1 < need: + problems.append(f"{type(w).__name__} {w.text()!r}: {w.width()} < {need}") + return problems + + +def test_nothing_is_cut_off_at_1280x720(qtbot, language): + window = _solved_window(qtbot) + problems = [] + for step, panel in enumerate(window.panels): + window._go(step) + # the narrowest the user can drag the side bar to + window.centralWidget().setSizes([1, WIDTH]) + qtbot.wait(50) + scroll = panel.parentWidget().parentWidget() + assert isinstance(scroll, QScrollArea) + if panel.minimumSizeHint().width() > scroll.viewport().width(): + problems.append( + f"step {step + 1} needs {panel.minimumSizeHint().width()} px, " + f"has {scroll.viewport().width()}" + ) + problems += [f"step {step + 1}: {p}" for p in _clipped(panel)] + for bar in window.findChildren(QToolBar): + overflow = bar.findChild(QToolButton, "qt_toolbar_ext_button") + if overflow is not None and overflow.isVisible(): + problems.append(f"tool bar {bar.objectName() or bar.windowTitle()!r} overflows") + window.viewer.shutdown() + assert not problems, "\n".join(problems) diff --git a/tests/test_mesh_control.py b/tests/test_mesh_control.py index 318e5c8..49f5f2e 100644 --- a/tests/test_mesh_control.py +++ b/tests/test_mesh_control.py @@ -65,3 +65,25 @@ def test_presets_are_ordered(): divisions = [MESH_PRESETS[k].divisions for k in order] layers = [MESH_PRESETS[k].layers for k in order] assert divisions == sorted(divisions) and layers == sorted(layers) + + +def test_meshing_workers_are_kept_and_replaced_after_a_failure(): + """The worker process (spawned, Netgen imported) is kept for the next mesh; a failed + or cancelled mesh replaces it, since a worker may be stuck inside Netgen.""" + import kstruct.fem.mesh as meshing + + project = Project(parts=[Part(0, "box", _box(0, 0, 0, 20, 10, 5), "s235")]) + first = generate_mesh(project, "coarse") + pool = meshing._pool + assert pool is not None + again = generate_mesh(project, "coarse") + assert meshing._pool is pool # reused + assert np.array_equal(first.nodes, again.nodes) # and the mesh is the same + + def cancel(): + raise RuntimeError("cancelled") + + with pytest.raises(RuntimeError, match="cancelled"): + generate_mesh(project, "coarse", check=cancel) + assert meshing._pool is None + assert len(generate_mesh(project, "coarse").tets) == len(first.tets) diff --git a/tests/test_ui_tools.py b/tests/test_ui_tools.py new file mode 100644 index 0000000..cb0bff2 --- /dev/null +++ b/tests/test_ui_tools.py @@ -0,0 +1,346 @@ +"""v0.4 usability tools: standard views, box / same-size / connected-face selection, +view-only hiding, list highlighting, keyboard shortcuts, drag and drop, and the red +marking of the parts an analysis error is about.""" + +import numpy as np +import pytest +from OCP.BRepFilletAPI import BRepFilletAPI_MakeFillet +from OCP.BRepPrimAPI import BRepPrimAPI_MakeBox +from OCP.TopAbs import TopAbs_EDGE +from OCP.TopExp import TopExp_Explorer +from OCP.TopoDS import TopoDS +from PySide6.QtCore import QMimeData, QPointF, Qt, QUrl +from PySide6.QtGui import QAction, QDropEvent +from PySide6.QtWidgets import QDoubleSpinBox + +from kstruct import diagnose +from kstruct.fem import SolverError +from kstruct.geometry import faces_of +from kstruct.geometry.face_info import face_at, similar_faces, tangent_faces +from kstruct.geometry.samples import _box, bolted_plates, l_bracket, write_step +from kstruct.model import ( + Bolt, + Connection, + ConnectionKind, + FaceRef, + Fixture, + FixtureKind, + Load, + LoadKind, + Part, + Project, +) + + +def _window(qtbot): + from kstruct.ui.main_window import MainWindow + + window = MainWindow() + window.ask_before_close = False + qtbot.addWidget(window) + window.resize(1280, 720) + window.show() + return window + + +# --- geometry helpers ------------------------------------------------------------------- + + +def _filleted_box(): + box = BRepPrimAPI_MakeBox(20, 20, 20).Shape() + fillet = BRepFilletAPI_MakeFillet(box) + fillet.Add(3.0, TopoDS.Edge(TopExp_Explorer(box, TopAbs_EDGE).Current())) + return fillet.Shape() + + +def test_tangent_faces_follow_a_fillet_but_stop_at_corners(): + shape = _filleted_box() + faces = faces_of(shape) + from kstruct.geometry.face_info import face_info + + fillet = next(i for i, f in enumerate(faces) if face_info(f).radius is not None) + chain = tangent_faces(shape, fillet) + assert len(chain) == 3 and fillet in chain # the fillet and the two faces it rounds + # a face on the far side meets its neighbours at sharp edges only + far = face_at(shape, (20, 10, 10)) if face_at(shape, (20, 10, 10)) not in chain else None + if far is not None: + assert tangent_faces(shape, far) == [far] + + +def test_similar_faces_find_every_hole_of_one_diameter(): + shape = l_bracket() + faces = faces_of(shape) + from kstruct.geometry.face_info import face_info + + holes = [i for i, f in enumerate(faces) if face_info(f).radius is not None] + assert similar_faces(shape, holes[0]) == holes + # a plate's top and bottom have the same area but face opposite ways + lower = _box(0, 0, 0, 40, 20, 10) + top = face_at(lower, (20, 10, 10)) + assert similar_faces(lower, top) == [top] + + +def test_tangent_lookup_does_not_change_the_shape(tmp_path): + """The saved mesh is keyed on the brep bytes: the face tools must not write edge + regularity into the shape.""" + from OCP.BRepTools import BRepTools + + def brep(shape, name): + path = tmp_path / name + BRepTools.Write_s(shape, str(path)) + return path.read_bytes() + + shape = _filleted_box() + before = brep(shape, "before.brep") + for i in range(len(faces_of(shape))): + tangent_faces(shape, i) + similar_faces(shape, i) + assert brep(shape, "after.brep") == before + + +# --- diagnosis ---------------------------------------------------------------------------- + + +def _stack(connected=True) -> Project: + lower, upper = _box(0, 0, 0, 40, 20, 10), _box(0, 0, 10, 40, 20, 10) + project = Project(parts=[Part(0, "a", lower, "s235"), Part(1, "b", upper, "s235")]) + if connected: + project.connections = [ + Connection( + ConnectionKind.CONTACT, + [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)))])] + return project + + +def test_unheld_parts_follow_the_connections(): + assert diagnose.unheld_parts(_stack(connected=False)) == [1] + contact = _stack() + assert diagnose.unheld_parts(contact) == [] # held through the contact + assert diagnose.unheld_parts(contact, bonded_only=True) == [1] # ...but only by it + assert diagnose.problem_parts(contact, SolverError("contact unstable")) == ( + [1], + diagnose.FIX_FIXTURE, + ) + assert diagnose.problem_parts(contact, SolverError("not converged")) == ([], None) + assert diagnose.problem_parts(contact, ValueError("x")) == ([], None) + + +def test_bolt_without_contact_names_the_bolted_parts(): + project = _stack(connected=False) + project.bolts = [Bolt(FaceRef(0, 0), FaceRef(1, 0), preload=5000.0)] + assert diagnose.problem_parts(project, SolverError("bolt without contact")) == ( + [0, 1], + diagnose.FIX_CONNECTION, + ) + + +def test_thermal_error_carries_the_part_without_a_reference(): + from kstruct.fem import generate_mesh + from kstruct.fem.thermal import solve_thermal + from kstruct.standards import project_materials + + project = _stack(connected=False) + project.loads = [ + Load( + LoadKind.FACE_TEMPERATURE, + [FaceRef(0, face_at(project.parts[0].shape, (20, 10, 0)))], + magnitude=50.0, + ) + ] + mesh = generate_mesh(project, "coarse") + materials = {p.id: project_materials(project)[p.material_id] for p in project.parts} + with pytest.raises(SolverError) as caught: + solve_thermal(project, mesh, materials) + assert caught.value.parts == (1,) + assert diagnose.problem_parts(project, caught.value) == ([1], diagnose.FIX_LOAD) + + +# --- viewer --------------------------------------------------------------------------------- + + +def test_standard_views_look_along_the_axes(qtbot): + window = _window(qtbot) + window.open_sample("bracket") + viewer = window.viewer + for name, axis in (("front", (0, -1, 0)), ("right", (1, 0, 0)), ("top", (0, 0, 1))): + viewer.set_view(name) + cam = viewer.plotter.camera + direction = np.subtract(cam.position, cam.focal_point) + direction /= np.linalg.norm(direction) + assert direction == pytest.approx(axis, abs=1e-6), name + viewer.view_actions["back"].trigger() + cam = viewer.plotter.camera + assert np.subtract(cam.position, cam.focal_point)[1] > 0 + + +def test_box_select_takes_only_visible_faces_and_isolate_is_view_only(qtbot): + from kstruct.ui import main_window as mw + + window = _window(qtbot) + window.open_sample("two_plates") + window._go(mw.STEP_FIXTURE) + viewer = window.viewer + viewer.set_view("top") + w, h = viewer.plotter.window_size + seen = viewer.faces_in_box(0, 0, w, h) + # from above: both plates' upward faces, nothing on the underside + assert {r.part_id for r in seen} == {0, 1} + bottom = FaceRef(0, face_at(window.project.parts[0].shape, (50, 20, 0))) + assert bottom not in seen + + viewer.isolate_part(0) + assert viewer.view_hidden == {1} + assert {r.part_id for r in viewer.faces_in_box(0, 0, w, h)} == {0} + assert all(p.visible for p in window.project.parts) # still analysed + + viewer.show_all_parts() + viewer.set_part_translucent(1, True) # clicks pass through the upper plate + ref = viewer._pick(w // 2, h // 2) + assert ref is not None and ref.part_id == 0 + viewer.show_all_parts() + + viewer.box_select(0, 0, w, h) + assert set(viewer.selection) == set(seen) + viewer.set_box_mode(True) + assert viewer.box_action.isChecked() + viewer.clear_selection() # Esc: clears and leaves box mode + assert viewer.selection == [] and not viewer.box_action.isChecked() + window._go(mw.STEP_SOLVE) + assert not viewer.box_action.isVisible() # selection tools only where faces are picked + + +def test_same_size_and_context_menu(qtbot): + from kstruct.ui import main_window as mw + + window = _window(qtbot) + window.open_sample("bracket") + window._go(mw.STEP_FIXTURE) + viewer = window.viewer + shape = window.project.parts[0].shape + hole = FaceRef(0, face_at(shape, (75, 15, 4))) + notices = [] + viewer.notice.connect(notices.append) + viewer.select_similar() # nothing selected yet: says what to do + assert notices and viewer.selection == [] + viewer.set_selection([hole]) + viewer.select_similar() + assert {r.face_index for r in viewer.selection} == set(similar_faces(shape, hole.face_index)) + labels = [label for label, _ in viewer.context_menu_actions(hole)] + assert labels[0] == "이 부품만 보기" and "이어진 면 선택" in labels + + +def test_list_entry_highlights_its_faces(qtbot): + from kstruct.ui import main_window as mw + + window = _window(qtbot) + window.open_sample("bracket") + shape = window.project.parts[0].shape + face = FaceRef(0, face_at(shape, (0, 30, 40))) + window.project.fixtures = [Fixture(FixtureKind.FIXED, [face])] + window._go(mw.STEP_FIXTURE) + panel = window.panels[mw.STEP_FIXTURE] + panel.refresh() + panel.items.setCurrentRow(0) + assert window.viewer._highlight == [face] + window._go(mw.STEP_LOAD) + assert window.viewer._highlight == [] + + +# --- shortcuts and files -------------------------------------------------------------------- + + +def test_keyboard_shortcuts(qtbot): + from kstruct.ui import main_window as mw + + window = _window(qtbot) + window.open_sample("bracket") + # key dispatch needs the active window, which other test windows may hold: trigger + # the action that owns the key sequence instead + by_key = { + a.shortcut().toString(): a + for a in window.findChildren(QAction) + if not a.shortcut().isEmpty() + } + by_key["Alt+3"].trigger() + assert window.nav.currentRow() == mw.STEP_FIXTURE + by_key["7"].trigger() + cam = window.viewer.plotter.camera + assert np.subtract(cam.position, cam.focal_point)[2] > 0 # looking down from the top + + shape = window.project.parts[0].shape + window.project.fixtures = [ + Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(shape, (0, 30, 40)))]) + ] + window.panels[mw.STEP_FIXTURE].refresh() + window.panels[mw.STEP_FIXTURE].items.setCurrentRow(0) + window.delete_shortcut() + assert window.project.fixtures == [] + + # digits typed into an input box stay there instead of turning the view + window._go(mw.STEP_LOAD) + spin = window.panels[mw.STEP_LOAD].findChildren(QDoubleSpinBox)[0] + spin.setFocus() + spin.selectAll() + before = window.viewer.plotter.camera.position + qtbot.keyClick(spin, Qt.Key.Key_1) + assert spin.text().startswith("1") and window.viewer.plotter.camera.position == before + + keys = dict(window.shortcut_entries()) + for key in ("F5", "Ctrl+M", "Alt+1", "Ctrl+/", "0", "Esc", "B", "S", "T"): + assert key in keys, key + + window.solve_shortcut() # no load yet: opens step 6 and leaves the run alone + assert window.nav.currentRow() == mw.STEP_SOLVE and window.result is None + + +def test_dropping_a_file_opens_it(qtbot, tmp_path): + window = _window(qtbot) + path = write_step(bolted_plates(), tmp_path / "dropped.step") + data = QMimeData() + data.setUrls([QUrl.fromLocalFile(str(path))]) + event = QDropEvent( + QPointF(200, 200), + Qt.DropAction.CopyAction, + data, + Qt.MouseButton.NoButton, + Qt.KeyboardModifier.NoModifier, + ) + window.dropEvent(event) + qtbot.waitUntil(lambda: window.project is not None, timeout=10_000) + assert len(window.project.parts) == 2 + + other = QMimeData() + other.setUrls([QUrl.fromLocalFile(str(tmp_path / "notes.txt"))]) + assert window._dropped_file(type("E", (), {"mimeData": lambda self: other})()) is None + + +def test_unheld_part_is_painted_and_the_fix_step_offered(qtbot): + from kstruct.ui import main_window as mw + + window = _window(qtbot) + window.open_sample("two_plates") + lower, upper = (p.shape for p in window.project.parts) + for part in window.project.parts: + part.material_id = "s235" + window.project.connections = [] # nothing holds the upper plate + window.project.fixtures = [ + Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(lower, (50, 20, 0)))]) + ] + window.project.loads = [ + Load(LoadKind.FORCE, [FaceRef(1, face_at(upper, (50, 20, 10)))], vector=(0, 0, -500.0)) + ] + window.project.mesh_quality = "coarse" + window._project_changed() + warnings = [] + window.warn = lambda text, fix_step=None: warnings.append((text, fix_step)) + window.solve() + qtbot.waitUntil(lambda: bool(warnings), timeout=120_000) + text, step = warnings[0] + assert step == mw.STEP_FIXTURE and "'위 판'" in text + assert window.viewer._problem_parts == {1} + window._project_changed() # the next edit clears the marking + assert window.viewer._problem_parts == set() diff --git a/uv.lock b/uv.lock index 3fa0719..bdfb75b 100644 --- a/uv.lock +++ b/uv.lock @@ -245,7 +245,7 @@ wheels = [ [[package]] name = "kstruct" -version = "0.3.2" +version = "0.5.0" source = { editable = "." } dependencies = [ { name = "cadquery-ocp" },