diff --git a/.github/workflows/bench.yml b/.github/workflows/bench.yml index 9116a72..ebc5684 100644 --- a/.github/workflows/bench.yml +++ b/.github/workflows/bench.yml @@ -9,10 +9,17 @@ on: - cron: "17 3 * * 1" # Mondays 03:17 UTC workflow_dispatch: +# The macOS leg has no MKL: it measures the SuperLU / AMG path (results must still match; +# its times are only recorded) and never fails the run while macOS runners are scarce. jobs: bench: - runs-on: ubuntu-22.04 - timeout-minutes: 60 + strategy: + fail-fast: false + matrix: + os: [ubuntu-22.04, macos-14] + runs-on: ${{ matrix.os }} + continue-on-error: ${{ matrix.os == 'macos-14' }} + timeout-minutes: 90 steps: - uses: actions/checkout@v4 @@ -25,7 +32,9 @@ jobs: - name: Benchmark run: | - if [ -f packaging/bench_baseline_ci.json ]; then + if [ "$RUNNER_OS" = "macOS" ]; then + uv run python packaging/bench.py --json bench.json --check packaging/bench_baseline.json --results-only + elif [ -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 @@ -34,5 +43,5 @@ jobs: - uses: actions/upload-artifact@v4 if: always() with: - name: bench + name: bench-${{ matrix.os }} path: bench.json diff --git a/.github/workflows/build.yml b/.github/workflows/build.yml index 36e054f..c4774a0 100644 --- a/.github/workflows/build.yml +++ b/.github/workflows/build.yml @@ -27,7 +27,14 @@ jobs: fail-fast: false matrix: os: [windows-latest, macos-14, ubuntu-22.04] + include: + # macOS (arm64, no MKL: SuperLU / AMG path) is built when a runner is assigned, + # but its failure or cancellation never holds back the Windows/Linux release + - os: macos-14 + optional: true runs-on: ${{ matrix.os }} + continue-on-error: ${{ matrix.optional == true }} + timeout-minutes: 120 steps: - uses: actions/checkout@v4 diff --git a/CLAUDE.md b/CLAUDE.md index 9926bc5..b9d25bd 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -34,10 +34,11 @@ CI(`.github/workflows/build.yml`)가 Windows/macOS/Linux에서 테스트 → PyI - **열 해석**(`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회(상한 `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직선, 잔류 신장, 붕괴 하중, 엘라스티카 외팔보). +- **비선형 정적 해석**(`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-멀티그리드(접촉·볼트가 있으면 분해). **볼트**는 선형과 같은 스프링이고 예압은 첫 하중 단계(`_Path`로 0 → 당김력)로 건 뒤, 그 상태의 접선으로 당김력을 보정해(`LOCK_ITERATIONS`, 보정 단계는 한 증분부터) 볼트마다 정확히 P가 되게 하고, 나머지 하중은 체결한 상태에서 건다(영구 변형 = 하중 제거 뒤 − 체결 직후). **접촉**(마찰 없음)은 `_Contacts`: 닫힌 쌍 = 간극 g = g0 + c·u의 페널티 스프링(선형 접촉과 같은 α, 작은 미끄럼·초기 법선), 뉴턴 반복마다 닫힘(g ≤ 0 유지, 열린 쌍은 관통하면 닫힘)을 다시 고르고, 바뀌면 수렴으로 치지 않으며(반복 상한 +`CONTACT_EXTRA_ITERATIONS`) 쌍마다 증분당 `MAX_FLIPS`회까지만 바뀐다; 증분 실패 시 닫힘 상태를 되돌린다. 접촉으로만 붙은 부품용 1e-9 안정화 스프링. 마찰이 있으면 `unsupported` → 6단계 체크리스트 ✘. 이론해 테스트 `tests/test_fem_nonlinear_contact.py`(접촉으로 쌓은 두 블록 = 한 봉의 신장·붕괴, 항복 전 선형 접촉 해석과 일치, 예압 정확, 분리 뒤 볼트가 당김 전부). 응력 표시는 코시 응력, 항복한 요소는 적분점 평균(외삽이 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는 부정치; 행렬은 CSR — CSC 곱이 느렸다). 압축이 거의 없으면 반복 상한에서 끊고 "좌굴 없음"으로 처리. 고유쌍은 모드+3개를 먼저 요청하고 양수(하중 반전 아닌 것)가 모자랄 때만 2·모드+4개로 다시(같은 분해) — 요청 1쌍이 역대입 ~10회다. +- **진동 응답**(`fem/harmonic.py`, `AnalysisKind.HARMONIC`): 활성 케이스의 하중을 진폭 F·cos ωt로 보고 모드 중첩 qⱼ = φⱼᵀf/(ωⱼ² − ω² + 2iζωⱼω) + **잔류 정적 보정**(K⁻¹f − Σφⱼpⱼ/ωⱼ²; 0 Hz가 정적해와 정확히 같다). 모드·행렬은 `modal.modal_system`/`eigenmodes`를 공유하고, 모드는 스윕 상한의 `MODE_MARGIN`(1.5)배까지(최소 `MIN_MODES` 12, 최대 80). 범위는 `Project.harmonic_range`(상한 0 = n번째 고유진동수 × 1.2 자동), 감쇠 `damping_ratio`(기본 2 %), 스윕은 등간격 240점 + 공진마다 반전력 대역 단위 점(`sweep`). 한 주기 최댓값은 이차형식의 닫힌 해(`_worst_over_period`). `state(f)`가 `StaticResult`(+`harmonic`, `harmonic_frequency`)를 만들어 강도 UI·요약·보고서를 그대로 쓴다: 변위는 **한 순간**(가장 많이 움직이는 절점이 최대인 위상 — 절점마다 위상을 고르면 공진의 90° 위상에서 이웃 부호가 뒤집혔다), 응력은 절점마다 최대 폰 미세스 위상 + 큰 주응력이 인장이 되게 부호, 반력은 축별 진폭. 판정 진동수는 사용률(폰 미세스/강도) 최대(`governing`), 피로는 항상 양방향(`summarize`). 열 조건·볼트 예압·강제 변위는 빠지고(요약 메모) 접촉은 접합. 결과 패널은 진동수 상자(가장 불리·n차 공진·운전 진동수·곡선에서 고른 값 → `MainWindow.select_frequency`)와 `ui/response_curve.py`(QPainter, 로그 축, 보고서용 `to_png`). 이론해 테스트 `tests/test_fem_harmonic.py`(축 진동 봉의 파동해·감쇠 모드 급수·반력 F/cos kL). - **표시 단위**(`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 리더는 자체 구현. @@ -46,13 +47,16 @@ 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, 한/영, 가장 좁게 끈 상태에서 검사). -- **결과 도구**(v0.6): 최대·최소 위치 라벨(`ResultField.extreme`: 안전율·수명은 최소, 부호 있는 값은 양쪽, 그 밖은 최대; 단면 보기는 화면에 보이는 잘린 면에서, 아니면 **절점값**에서 찾는다 — 세분 표면은 2차 보간이 절점값을 넘어선다; 라벨 글꼴은 `_label_font`로 번들 한글 글꼴), 변형 '배율 직접'(`scale_factor`), 색 범위 직접(결과 종류를 바꾸면 해제), 색각 친화 색표(`COLORBLIND_MAPS`, `prefs.colorblind`). 자주 안 쓰는 표시 설정은 '표시 설정 더 보기'로 접혀 있고 단면·색 범위를 켜면 펼쳐진다. **재료 바꿔 보기**(`kstruct/whatif.py`): 한 재료·선형·푸아송비 같음·열응력/밀도 의존 체적력/강제 변위/탄성 지지/볼트 없음이면 응력 그대로·변위 × E_old/E_new로 다시 풀지 않고 재판정(`tests/test_whatif.py`가 재해석과 일치 확인), 아니면 이유를 말하고 재해석을 묻는다; '이 재료로 확정'은 결과를 유지한 채 재료만 바꾼다. **포락**(`static.envelope`): 절점마다 안전율이 가장 낮은 케이스의 응력(모두 상한이면 응력이 가장 큰 케이스)과 가장 큰 변위, 반력·볼트는 비움 — 케이스 상자의 마지막 항목. **메시 확인**(`kstruct/meshcheck.py`, `MainWindow.check_mesh`): 같은 케이스를 다음 프리셋으로 다시 풀어 판정 안전율·최대 변형의 변화율(5 % 초과면 '메시에 민감'), 특이점 최대 응력은 비교하지 않고 따로 알린다. **둘러보기**(`ui/tour.py`): 카드는 항상 왼쪽 아래(3D 뷰 위에 두면 네이티브 OpenGL 창에 가려질 수 있음), 대상은 `tourHighlight` 테두리; 단계를 열었는데 입력이 없으면 상태 표시줄에 `NEXT_HINTS`. +- **3D 뷰 도구**(`ui/viewer.py` 위쪽 `viewStrip`): '보기' 메뉴(표준 보기 `set_view`, 단축키 0·1·3·7, Ctrl = 반대쪽), 반투명, **측정**(M, `set_measure_mode`/`measure_at`: 클릭한 면의 면적·구멍 지름·축·법선, 두 점 거리와 ΔXYZ — 문구는 `geometry/measure.py`, 표시 단위; 측정 중 클릭은 선택하지 않고 영역 선택과 배타), 그리고 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, 한/영, 가장 좁게 끈 상태에서 검사). +- **조건 묶음·대칭면**(UX-7, `kstruct/templates.py`): 고정·하중을 면 번호가 아니라 면 종류(원통 = 반지름, 평면 = 바깥 법선 + 면적, 허용 `SIMILAR_TOLERANCE`·1°)로 저장해(`paths.templates_path()`의 templates.json, 내장 `BUILT_IN`의 '자중') 다른 모델의 맞는 면 **모두**에 넣고, 맞는 면이 없는 항목은 빼고 센다(`MainWindow.apply_template`, 실행 취소 1번). 3단계 '선택한 평면을 대칭면으로'는 `Fixture(ROLLER, symmetry=True)`(저장됨)를 만들고 요약 메모·조건 문구가 반력은 계산한 부분만의 값이라고 알린다. +- **숫자 입력칸**: 단계 패널·대화상자의 숫자 칸은 `ui/unit_spin.UnitSpinBox`(`QDoubleSpinBox` 대신 — 새 칸도 이것을 쓸 것): "10 kN", "2 in", "=1500*9.81"을 받는다(`kstruct/unitparse.py`; 수식은 ast로만 계산하고 eval 금지, 단위는 칸의 접미사 = 표시 단위와 같은 종류일 때만 변환, 못 읽으면 이전 값 유지). `tests/test_unitparse.py`. +- **결과 도구**(v0.6): 최대·최소 위치 라벨(`ResultField.extreme`: 안전율·수명은 최소, 부호 있는 값은 양쪽, 그 밖은 최대; 단면 보기는 화면에 보이는 잘린 면에서, 아니면 **절점값**에서 찾는다 — 세분 표면은 2차 보간이 절점값을 넘어선다; 라벨 글꼴은 `_label_font`로 번들 한글 글꼴), 변형 '배율 직접'(`scale_factor`), 색 범위 직접(결과 종류를 바꾸면 해제), 색각 친화 색표(`COLORBLIND_MAPS`, `prefs.colorblind`). 자주 안 쓰는 표시 설정은 '표시 설정 더 보기'로 접혀 있고 단면·색 범위를 켜면 펼쳐진다. **재료 바꿔 보기**(`kstruct/whatif.py`): 한 재료·선형·푸아송비 같음·열응력/밀도 의존 체적력/강제 변위/탄성 지지/볼트 없음이면 응력 그대로·변위 × E_old/E_new로 다시 풀지 않고 재판정(`tests/test_whatif.py`가 재해석과 일치 확인), 아니면 이유를 말하고 재해석을 묻는다; '이 재료로 확정'은 결과를 유지한 채 재료만 바꾼다. **포락**(`static.envelope`): 절점마다 안전율이 가장 낮은 케이스의 응력(모두 상한이면 응력이 가장 큰 케이스)과 가장 큰 변위, 반력·볼트는 비움 — 케이스 상자의 마지막 항목. **메시 확인**(`kstruct/meshcheck.py`, `MainWindow.check_mesh`): 같은 케이스를 다음 프리셋으로 다시 풀어 판정 안전율·최대 변형의 변화율(5 % 초과면 '메시에 민감'), 특이점 최대 응력은 비교하지 않고 따로 알린다. **결과 비교**(UX-8): '이 결과를 비교 기준으로'(`pin_reference`)가 강도 결과를 `MainWindow.reference`(라벨, 메시, 결과, 요약)로 두고, 이후 결과와 판정 안전율·최대 응력·최대 변형을 나란히 표로 보여 준다(`_compare_html`). 메시가 똑같으면(`same_mesh_as_reference`: 절점·요소 배열 동일) `compare_view = "diff"`로 지금 − 기준 색 지도(표시 단위로 바꾼 뒤 뺌), `"ref"`면 기준 결과·메시·변형을 그대로 띄운다(`_with_reference`가 mesh/result/summary를 잠시 바꿔 끼움). 기준은 다른 모델을 열 때 지운다. **둘러보기**(`ui/tour.py`): 카드는 항상 왼쪽 아래(3D 뷰 위에 두면 네이티브 OpenGL 창에 가려질 수 있음), 대상은 `tourHighlight` 테두리; 단계를 열었는데 입력이 없으면 상태 표시줄에 `NEXT_HINTS`. - **단면·내보내기**: 뷰어는 평소 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 뷰 수명**: `ModelViewer`는 `QtInteractor(off_screen=False)`로 만든다 — CI의 headless 액션이 `PYVISTA_OFF_SCREEN=true`를 걸면 기본값으로는 `plotter.iren`이 None이라 선택이 깨진다. 창을 닫을 때 `viewer.shutdown()`으로 렌더 창을 해제한다(안 하면 테스트가 창 수십 개를 열 때 소프트웨어 OpenGL(Xvfb/Mesa)이 `render()`에서 segfault). `tests/conftest.py`가 테스트마다 남은 `MainWindow`를 닫고 지연 삭제·GC까지 돌려 GL 컨텍스트가 쌓이지 않게 한다(CI Linux의 간헐 세그폴트 완화). 로컬 Linux에서 UI 테스트는 `PYVISTA_OFF_SCREEN=true xvfb-run -a uv run pytest`로 CI와 같게 돌린다. - **3D 텍스트 한글**: VTK 기본 글꼴에 한글이 없어 색 막대에 번들 Noto Sans KR(OFL)을 지정한다(`viewer._use_korean_font`). - **결과 표시 주의**: 2차 요소 보간이 범위를 벗어나 거짓 색을 만들 수 있어 안전율 같은 잘린 값은 표시 전에 clim으로 자른다. - **응력 특이점**(`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`). +- **설계 조언**(`report/advice.py`, `Summary.advice`, 결과 패널·보고서의 '개선 방법'): 판정 절점(`PartSummary.governing_node`, 특이점 제외 판정이면 `hotspot_node`)에 닿은 B-rep 면으로 위치를 분류한다 — 특이점 종류 '오목 모서리' → 필렛, 오목 원통(면 방향 REVERSED)의 각도 > 0.6π → 구멍(분할된 반원통 포함), 그보다 작으면 필렛, `face_thickness` < 부품 최대 치수 × 0.15 → 얇은 벽. **수치는 선형에서 정확한 비례만** 쓴다: 하중 배수 fos/target, 두께는 굽힘 √r ~ 당김 r(r = target/fos, 둘 다 표기), 재료는 whatif 정확 조건을 만족하는 후보와 필요한 강도. 여유가 크면(모든 부품 안전율 ≥ 권장 × 3) 보수적인 굽힘 기준으로만 얇게 하라고 한다. 접촉·예압·열·강제 변위가 있으면(`linear_in_loads` 거짓) 수치 없이 '바꾼 뒤 다시 해석', 진동 응답은 하중 진폭 배수만(두께·재료는 고유진동수를 바꿈), 비선형은 조언 없음. 필렛 반지름별 응력 감소처럼 근거 없는 수치는 쓰지 않는다(`tests/test_advice.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. 워커 프로세스(spawn Pool)는 **유지·재사용**한다(`_get_pool`, 앱 시작 때 `prewarm()`이 2개를 띄움; 생성+import 1.4 s가 메시마다 들던 것을 없앰). 시간 초과·취소·오류 때만 `drop_pool()`로 죽인다(Netgen 안에서 멈췄을 수 있음). Netgen 스레드(`TaskManager`)는 이득이 작고(1.2 → 1.0 s) 멈춤 위험이 있어 쓰지 않는다. diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index b2f7639..f29c266 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -380,6 +380,15 @@ OS별 설치 절차(서명 전이면 SmartScreen/Gatekeeper 우회 안내도 필 | | UI-4 결과 패널 정리 | ✅ 표시 설정 접기(판정·근거 먼저) | | | UX-5 첫 사용 안내 | ✅ 둘러보기(5장, 시작 화면·정보 메뉴), 단계별 '다음에 할 일' | +| v0.7 적용 범위 | FT-4 진동 응답(주파수 응답) | ✅ `fem/harmonic.py` — 모드 중첩 + 잔류 정적 보정, 감쇠비·진동수 범위, 응답 곡선(클릭으로 진동수 선택), 가장 불리한 진동수에서 강도·양방향 피로 판정, 보고서 표·곡선. 축 진동 봉의 파동해와 변위 오차 < 0.2 %, 감쇠 공진 < 0.5 % | +| | FT-6 설계 조언 | ✅ `report/advice.py` — 판정 위치(오목 모서리·구멍·필렛·얇은 벽)별 조언 + 선형 비례 수치(하중 배수·두께 범위·필요 강도와 재료 후보). 하중 배수로 다시 풀면 권장 안전율과 1e-6 안에서 같음 | +| | FT-5 비선형 + 접촉(마찰 없음)·볼트 | ✅ `fem/nonlinear.py` — 뉴턴 반복 안의 능동 집합 접촉, 볼트 예압 = 첫 하중 단계(정확히 P로 잠금). 항복 전엔 선형 접촉 해석과 변위 차 3e-12, 접촉으로 쌓은 블록 = 한 봉(신장·붕괴). 마찰은 아직 ✘ | +| | UX-9 단위 붙여 입력·수식 | ✅ `kstruct/unitparse.py`, `ui/unit_spin.UnitSpinBox` | +| | UX-3 측정 도구 | ✅ 3D 뷰 '측정'(M): 면적·구멍 지름·축·법선, 두 점 거리 | +| | UI-5 macOS 빌드 | ⚠ CI에서 선택 사항으로 분리(실패·취소가 릴리스를 막지 않음), 주간 벤치마크에 macOS(SuperLU 경로) 추가. dmg 산출은 러너가 배정돼야 확인 가능 | +| | UX-8 결과 비교 | ✅ 기준 결과 고정 → 나란히 숫자 비교, 같은 메시면 차이 색 지도(같은 실행 두 번 = 차이 0 표시), 기준 결과 번갈아 보기 | +| | UX-7 조건 묶음·대칭면 | ✅ `kstruct/templates.py` — 면 종류(구멍 반지름·평면 방향과 면적)로 매칭해 다른 모델에 적용, '자중' 내장. 대칭면 = 미끄럼 지지 + 결과 안내 | + 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 진행 순서 제안 diff --git a/packaging/windows/kstruct.iss b/packaging/windows/kstruct.iss index 55fbf5e..ec37c68 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.6.0 packaging\windows\kstruct.iss +; Build: iscc /DAppVersion=0.7.0 packaging\windows\kstruct.iss #ifndef AppVersion - #define AppVersion "0.6.0" + #define AppVersion "0.7.0" #endif [Setup] diff --git a/pyproject.toml b/pyproject.toml index b5263d2..9bb901c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kstruct" -version = "0.6.0" +version = "0.7.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 1c2c873..e5eedb3 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.6.0" # keep in sync with pyproject.toml (tests check) +RELEASE_VERSION = "0.7.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/fem/estimate.py b/src/kstruct/fem/estimate.py index 568c231..927423c 100644 --- a/src/kstruct/fem/estimate.py +++ b/src/kstruct/fem/estimate.py @@ -26,7 +26,11 @@ def solve_estimate(project: Project, mesh: FEMesh) -> tuple[str, bool]: nonlinear = project.analysis == AnalysisKind.STATIC and ( project.plasticity or project.large_deformation ) - heavy = contact or nonlinear or project.analysis in (AnalysisKind.MODAL, AnalysisKind.BUCKLING) + heavy = ( + contact + or nonlinear + or project.analysis in (AnalysisKind.MODAL, AnalysisKind.BUCKLING, AnalysisKind.HARMONIC) + ) if project.analysis == AnalysisKind.THERMAL: dof //= 3 # one unknown per node limits = _FACTORIZED if heavy else _PLAIN_STATIC diff --git a/src/kstruct/fem/harmonic.py b/src/kstruct/fem/harmonic.py new file mode 100644 index 0000000..06a1aa6 --- /dev/null +++ b/src/kstruct/fem/harmonic.py @@ -0,0 +1,275 @@ +"""Harmonic (frequency) response: the loads of the active case vary as F·cos(ωt) and the +part answers with u(ω) = Σ φⱼ qⱼ, by mode superposition with modal damping ζ: + + qⱼ = φⱼᵀf / (ωⱼ² − ω² + 2iζωⱼω) + +plus the static share of the modes left out (residual vector r = K⁻¹f − Σ φⱼ φⱼᵀf / ωⱼ²), +so that 0 Hz gives the static answer exactly and the truncation error well below the +highest mode used is small. The modes are taken up to well above the sweep's upper end. + +For a complex response the worst instant differs from node to node. For a quadratic +measure Q (|u|², von Mises²) of x(t) = A cos ωt + B sin ωt the largest value over a +period is (a+b)/2 + √(((a−b)/2)² + c²) with a = Q(A), b = Q(B), c = Q(A, B), reached at +θ = ½·atan2(2c, a − b) — so the worst stress state of every node is found exactly, and the +verdict uses those states (a conservative envelope over the period). + +Thermal loads, bolt preload and imposed displacements are not vibrating loads and are +left out (a displacement support holds still); contacts act bonded, as in the modal +analysis. +""" + +from __future__ import annotations + +from collections.abc import Callable +from dataclasses import dataclass, field + +import numpy as np + +from kstruct.fem.assembly import SolverError, make_solver, rigid_body_modes +from kstruct.fem.mesh import FEMesh +from kstruct.fem.modal import RIGID_HZ, eigenmodes, modal_system +from kstruct.fem.static import StaticResult, _load_vector, recover_stress +from kstruct.i18n import tr +from kstruct.model import Material, Project + +Progress = Callable[[float, str], None] + +SWEEP_POINTS = 240 # evenly spaced frequencies, plus points packed around each resonance +MIN_MODES = 12 # modes taken at least for the superposition +MAX_MODES = 80 +MODE_MARGIN = 1.5 # modes are taken up to this times the sweep's upper end +AUTO_MARGIN = 1.2 # without an upper end: sweep to this times the n-th natural frequency +CHUNK = 32 # frequencies evaluated at once (memory: 3N x CHUNK doubles, twice) +# offsets around each natural frequency, in half-power bandwidths (ζ·fⱼ) +PEAK_OFFSETS = np.array([-6, -3, -2, -1.5, -1, -0.5, -0.25, 0, 0.25, 0.5, 1, 1.5, 2, 3, 6]) + + +def _worst_over_period(a: np.ndarray, b: np.ndarray, c: np.ndarray): + """Largest value of a·cos²θ + 2c·sinθcosθ + b·sin²θ and the θ where it occurs.""" + half = (a - b) / 2 + peak = (a + b) / 2 + np.sqrt(half**2 + c**2) + return peak, 0.5 * np.arctan2(2 * c, a - b) + + +def _vm_form(s: np.ndarray, t: np.ndarray) -> np.ndarray: + """Bilinear form of von Mises² for two stress states (…, 6), so vm² = form(s, s).""" + d = lambda x, i, j: x[..., i] - x[..., j] # noqa: E731 + return 0.5 * ( + d(s, 0, 1) * d(t, 0, 1) + d(s, 1, 2) * d(t, 1, 2) + d(s, 2, 0) * d(t, 2, 0) + ) + 3 * (s[..., 3] * t[..., 3] + s[..., 4] * t[..., 4] + s[..., 5] * t[..., 5]) + + +@dataclass +class HarmonicResult: + mesh: FEMesh + materials: dict[int, Material] + damping: float # modal damping ratio ζ + natural: np.ndarray # (m,) Hz, the modes used + frequencies: np.ndarray # (F,) Hz, the sweep + displacement: np.ndarray # (F,) largest displacement amplitude in the model, mm + stress: np.ndarray # (F,) largest von Mises amplitude, MPa + utilisation: np.ndarray # (F,) largest von Mises / strength (picks the worst frequency) + governing: float # Hz, the frequency the verdict is taken at + static_displacement: float # largest displacement under the loads held still, mm + # superposition data: basis vectors (modes, then the residual) and their stresses + _omega2: np.ndarray = field(repr=False, default=None) + _p: np.ndarray = field(repr=False, default=None) + _basis: np.ndarray = field(repr=False, default=None) # (3N, m+1) + _stress: np.ndarray = field(repr=False, default=None) # (6N, m+1) + _system: object = field(repr=False, default=None) + _force: np.ndarray = field(repr=False, default=None) + + @property + def range(self) -> tuple[float, float]: + return float(self.frequencies[0]), float(self.frequencies[-1]) + + def coefficients(self, freq) -> np.ndarray: + """(m+1,) or (m+1, F) complex weights of the basis vectors at freq (Hz).""" + w = 2 * np.pi * np.atleast_1d(np.asarray(freq, dtype=float)) + wj = np.sqrt(self._omega2)[:, None] + q = self._p[:, None] / (self._omega2[:, None] - w**2 + 2j * self.damping * wj * w) + q = np.vstack([q, np.ones((1, len(w)))]) + return q[:, 0] if np.ndim(freq) == 0 else q + + def amplification(self, freq: float) -> float: + """Largest displacement amplitude at freq over the static one (dynamic factor).""" + if self.static_displacement <= 0: + return 0.0 + return float(np.interp(freq, self.frequencies, self.displacement)) / ( + self.static_displacement + ) + + def peaks(self) -> list[float]: + """Natural frequencies inside the sweep (where the response peaks).""" + lo, hi = self.range + return [float(f) for f in self.natural if lo <= f <= hi] + + def state(self, freq: float) -> StaticResult: + """The response at freq as a static result. Displacement: one instant, the one + at which the node that moves most is furthest out (a consistent deformed shape; + near resonance the motion is a quarter period behind the load, and taking every + node at its own worst instant flipped neighbours' signs). Stress: every node at + its own worst instant (largest von Mises over the period), the sign chosen so the + larger principal stress is tensile (a reversed load reaches both). Reactions are + the amplitudes of the support forces per axis.""" + q = self.coefficients(float(freq)) + n = self.mesh.n_nodes + u = (self._basis @ q).reshape(n, 3) + ur, ui = u.real, -u.imag # x(t) = Re(u e^{iωt}) = ur cos ωt + ui sin ωt + amp, theta = _worst_over_period( + np.einsum("ij,ij->i", ur, ur), + np.einsum("ij,ij->i", ui, ui), + np.einsum("ij,ij->i", ur, ui), + ) + t = theta[int(np.argmax(amp))] + disp = ur * np.cos(t) + ui * np.sin(t) + s = (self._stress @ q).reshape(n, 6) + sr, si = s.real, -s.imag + _, theta = _worst_over_period(_vm_form(sr, sr), _vm_form(si, si), _vm_form(sr, si)) + stress = sr * np.cos(theta)[:, None] + si * np.sin(theta)[:, None] + T = stress[:, [0, 3, 5, 3, 1, 4, 5, 4, 2]].reshape(n, 3, 3) + principal = np.linalg.eigvalsh(T) + stress[principal[:, 0] + principal[:, 2] < 0] *= -1 + result = StaticResult( + mesh=self.mesh, + materials=self.materials, + displacement=disp, + stress=stress, + reactions=self._reactions(u.ravel(), float(freq)), + applied_load=np.abs(self._force.reshape(-1, 3).sum(axis=0)), + ) + result.harmonic = self + result.harmonic_frequency = float(freq) + return result + + def _reactions(self, u: np.ndarray, freq: float) -> list[np.ndarray]: + """Amplitude of each support's force per axis: what the constrained DOFs need + to stay in balance with the elastic and inertia forces, (K − ω²M)u − f.""" + sysm = self._system + c = sysm.constraints + w2 = (2 * np.pi * freq) ** 2 + residual = sysm.K @ u - w2 * (sysm.M @ u) - self._force + out = [] + for dofs, equations in zip(c.fixture_dofs, c.fixture_equations, strict=True): + r = np.zeros(3, dtype=complex) + np.add.at(r, dofs % 3, residual[dofs]) + if len(equations): + r += c.penalty_forces(u.real, equations, sysm.scale) + r += 1j * c.penalty_forces(u.imag, equations, sysm.scale) + out.append(np.abs(r)) + for i, Ks in c.springs: + out[i] = np.abs((Ks @ u).reshape(-1, 3).sum(axis=0)) + return out + + +def sweep(f_lo: float, f_hi: float, natural: np.ndarray, damping: float, extra=()) -> np.ndarray: + """Evenly spaced frequencies plus points packed around each resonance inside.""" + points = [np.linspace(f_lo, f_hi, SWEEP_POINTS)] + width = max(damping, 1e-3) + for f in natural: + points.append(f * (1 + width * PEAK_OFFSETS)) + points.append(np.asarray(extra, dtype=float)) + f = np.unique(np.concatenate(points)) + return f[(f >= f_lo) & (f <= f_hi)] + + +def solve_harmonic( + project: Project, + mesh: FEMesh, + materials: dict[int, Material], + progress: Progress | None = None, +) -> StaticResult: + """The worst state over the sweep; the whole response is in `result.harmonic`.""" + report = progress or (lambda frac, msg: None) + if not project.fixtures: + raise SolverError("unstable") + zeta = float(project.damping_ratio) + f_lo, f_hi = (float(v) for v in project.harmonic_range) + + report(0.05, tr("강성·질량 행렬 조립 중")) + system = modal_system(project, mesh, materials) + free = system.free + f = _load_vector(project, mesh, materials) + if not np.any(f): + raise SolverError(tr("진동시킬 하중이 없습니다. 5단계에서 하중을 넣어 주세요.")) + + report(0.15, tr("정적 변형 계산 중")) + solve = make_solver(system.Kf.tocsr(), rigid_body_modes(mesh.nodes)[free]) + u_static = np.zeros(len(f)) + u_static[free] = solve(f[free]) + size = np.ptp(mesh.nodes, axis=0).max() + if np.abs(u_static).max() > 1e3 * size: + raise SolverError("unstable") + + report(0.3, tr("고유진동수 계산 중")) + k = max(MIN_MODES, project.n_modes) + while True: + omega2, phi = eigenmodes(system, mesh, k) + natural = np.sqrt(np.clip(omega2, 0, None)) / (2 * np.pi) + if np.any(natural <= RIGID_HZ): + raise SolverError("unstable") + top = f_hi if f_hi > 0 else AUTO_MARGIN * natural[min(project.n_modes, len(natural)) - 1] + if natural[-1] >= MODE_MARGIN * top or k >= MAX_MODES or len(natural) < k: + break + k = min(2 * k, MAX_MODES) + if f_hi <= 0: + f_hi = top + if f_hi <= f_lo: + raise SolverError(tr("진동수 범위가 잘못되었습니다. 최대가 최소보다 커야 합니다.")) + + report(0.55, tr("응답 합성 중")) + n_dof = len(f) + m = len(omega2) + basis = np.zeros((n_dof, m + 1)) + basis[free, :m] = phi + p = phi.T @ f[free] + basis[:, m] = u_static - basis[:, :m] @ (p / omega2) # static share of the other modes + stress = np.empty((mesh.n_nodes * 6, m + 1)) + for j in range(m + 1): + stress[:, j] = recover_stress(mesh, materials, basis[:, j]).ravel() + report(0.55 + 0.25 * (j + 1) / (m + 1), tr("응답 합성 중")) + + extra = [project.operating_frequency] if project.operating_frequency > 0 else [] + freqs = sweep(f_lo, f_hi, natural, zeta, extra) + result = HarmonicResult( + mesh=mesh, + materials=materials, + damping=zeta, + natural=natural, + frequencies=freqs, + displacement=np.zeros(len(freqs)), + stress=np.zeros(len(freqs)), + utilisation=np.zeros(len(freqs)), + governing=0.0, + static_displacement=float(np.linalg.norm(u_static.reshape(-1, 3), axis=1).max()), + _omega2=omega2, + _p=p, + _basis=basis, + _stress=stress, + _system=system, + _force=f, + ) + + report(0.85, tr("진동수별 응답 계산 중")) + capacity = np.ones(mesh.n_nodes) + for pid, mat in materials.items(): + capacity[mesh.part_nodes(pid)] = mat.yield_strength if mat.ductile else mat.tensile_strength + n = mesh.n_nodes + for start in range(0, len(freqs), CHUNK): + q = result.coefficients(freqs[start : start + CHUNK]) + u = basis @ q # (3N, F) + ur, ui = u.real.reshape(n, 3, -1), u.imag.reshape(n, 3, -1) + amp, _ = _worst_over_period((ur * ur).sum(1), (ui * ui).sum(1), (ur * ui).sum(1)) + s = stress @ q + sr = np.moveaxis(s.real.reshape(n, 6, -1), 1, -1) + si = np.moveaxis(s.imag.reshape(n, 6, -1), 1, -1) + vm2, _ = _worst_over_period(_vm_form(sr, sr), _vm_form(si, si), _vm_form(sr, si)) + vm = np.sqrt(np.maximum(vm2, 0)) + sl = slice(start, start + q.shape[1]) + result.displacement[sl] = np.sqrt(amp.max(axis=0)) + result.stress[sl] = vm.max(axis=0) + result.utilisation[sl] = (vm / capacity[:, None]).max(axis=0) + result.governing = float(freqs[int(np.argmax(result.utilisation))]) + + report(1.0, tr("완료")) + return result.state(result.governing) diff --git a/src/kstruct/fem/modal.py b/src/kstruct/fem/modal.py index 8b867b9..3b53186 100644 --- a/src/kstruct/fem/modal.py +++ b/src/kstruct/fem/modal.py @@ -40,16 +40,22 @@ def near(self, frequency: float, band: float = 0.2) -> list[int]: return [i for i, f in enumerate(self.frequencies) if abs(f - frequency) <= band * frequency] -def solve_modal( - project: Project, - mesh: FEMesh, - materials: dict[int, Material], - n_modes: int = 6, - progress: Progress | None = None, -) -> ModalResult: - report = progress or (lambda frac, msg: None) +@dataclass +class ModalSystem: + """Stiffness and mass restricted to the free DOFs, shared by the modal and the + harmonic (frequency response) analyses.""" + + K: object # full (3N, 3N) stiffness, constraints' penalty and springs included + M: object + free: np.ndarray + Kf: object # csc, free DOFs + Mf: object + constraints: object # fem.constraints.Constraints + scale: float # penalty stiffness scale (for the penalty equations' forces) + + +def modal_system(project: Project, mesh: FEMesh, materials: dict[int, Material]) -> ModalSystem: n_dof = mesh.n_nodes * 3 - report(0.05, tr("경계조건 준비 중")) if project.fixtures: c = build_constraints(project, mesh) else: # free-free modal is legitimate: rigid modes come out at ~0 Hz and are skipped @@ -58,28 +64,48 @@ def solve_modal( c = Constraints(fixed=np.zeros(n_dof, dtype=bool)) for conn in project.connections: add_bonded(c, mesh, conn) - - report(0.15, tr("강성·질량 행렬 조립 중")) K = stiffness_matrix(mesh, materials) - K = K + c.penalty_matrix(n_dof, K.diagonal().max()) + c.spring_matrix() + scale = K.diagonal().max() + K = K + c.penalty_matrix(n_dof, scale) + c.spring_matrix() K = K + bolt_stiffness_and_preload(build_bolts(project, mesh), n_dof)[0] M = mass_matrix(mesh, materials) free = np.flatnonzero(~c.fixed) - Kf, Mf = K[free][:, free].tocsc(), M[free][:, free].tocsc() + return ModalSystem(K, M, free, K[free][:, free].tocsc(), M[free][:, free].tocsc(), c, scale) - report(0.4, tr("고유진동수 계산 중")) - extra = 0 if project.fixtures else 6 - k = min(n_modes + extra, len(free) - 2) + +def eigenmodes(system: ModalSystem, mesh: FEMesh, k: int) -> tuple[np.ndarray, np.ndarray]: + """The k lowest eigenpairs (ω², φ over the free DOFs), ascending.""" + k = min(k, len(system.free) - 2) # shift slightly below zero so rigid-body (zero) modes don't make K - σM singular sigma = -1.0 * (2 * np.pi) ** 2 + Kf, Mf = system.Kf, system.Mf try: # K - σM = K + |σ|M is positive definite even for a free-floating part - OPinv = inverse_operator(Kf - sigma * Mf, rigid_body_modes(mesh.nodes)[free]) + OPinv = inverse_operator(Kf - sigma * Mf, rigid_body_modes(mesh.nodes)[system.free]) omega2, phi = spla.eigsh(Kf, k=k, M=Mf, sigma=sigma, which="LM", OPinv=OPinv) except (RuntimeError, spla.ArpackNoConvergence) as e: raise SolverError("not converged") from e order = np.argsort(omega2) - omega2, phi = omega2[order], phi[:, order] + return omega2[order], phi[:, order] + + +def solve_modal( + project: Project, + mesh: FEMesh, + materials: dict[int, Material], + n_modes: int = 6, + progress: Progress | None = None, +) -> ModalResult: + report = progress or (lambda frac, msg: None) + n_dof = mesh.n_nodes * 3 + report(0.05, tr("경계조건 준비 중")) + report(0.15, tr("강성·질량 행렬 조립 중")) + system = modal_system(project, mesh, materials) + M, free = system.M, system.free + + report(0.4, tr("고유진동수 계산 중")) + extra = 0 if project.fixtures else 6 + omega2, phi = eigenmodes(system, mesh, n_modes + extra) freq = np.sqrt(np.clip(omega2, 0, None)) / (2 * np.pi) keep = freq > RIGID_HZ rigid = int((~keep).sum()) diff --git a/src/kstruct/fem/nonlinear.py b/src/kstruct/fem/nonlinear.py index 15afebe..041efb6 100644 --- a/src/kstruct/fem/nonlinear.py +++ b/src/kstruct/fem/nonlinear.py @@ -17,8 +17,10 @@ factor it reached: the part collapses at about that share of the load. Constraints are eliminated exactly where possible (u = T û, as for the multigrid path of -the linear solver), else enforced by penalty springs. Contact, bolts and the per-case -reuse of factorizations of the linear solver are not supported here. +the linear solver), else enforced by penalty springs. Bolts are the linear solver's +springs, tightened as a first loading stage; frictionless contact opens and closes +inside the Newton iterations (small sliding). Friction and the per-case reuse of +factorizations of the linear solver are not supported here. """ from __future__ import annotations @@ -55,6 +57,11 @@ TOLERANCE = 1e-5 # residual norm relative to the load (or to the first residual) RUNAWAY_PLASTIC_STRAIN = 0.5 # beyond this the part has collapsed for any practical use ITERATIVE_MIN_DOF = 30_000 # p-multigrid CG for the Newton systems from this size +CONTACT_EXTRA_ITERATIONS = 20 # contact pairs opening and closing need more iterations +MAX_FLIPS = 3 # open/closed changes of one contact pair within an increment +LOCK_ITERATIONS = 4 # corrections of the bolt pulls towards the exact preload +LOCK_TOLERANCE = 1e-4 # relative to the largest preload +STAB_SHARE = 0.1 # load share on the contact stabilising springs: a part is not held _THERMAL = np.array([1.0, 1.0, 1.0, 0.0, 0.0, 0.0]) _SHEAR_PAIRS = ((0, 1), (1, 2), (2, 0)) # Voigt 3, 4, 5 @@ -261,8 +268,20 @@ class _Space: """The unknowns of the Newton systems: û with u = T û + λ u_set when the constraints can be eliminated exactly, else the free DOFs with penalty springs P.""" - def __init__(self, c: Constraints, mesh: FEMesh, scale: float): + def __init__( + self, + c: Constraints, + mesh: FEMesh, + scale: float, + bolts: sp.csr_matrix | None = None, + contacts: _Contacts | None = None, + ): self.c, self.mesh, self.scale = c, mesh, scale + self.bolts, self.contacts = bolts, contacts + # parts held only by contact (or by bolts through contact) are free to slide + # along it: a tiny spring everywhere keeps the tangent regular (like the linear + # contact solver); it carries a negligible share of the load + self.stab = 1e-9 * scale if contacts is not None else 0.0 self.n_dof = mesh.n_nodes * 3 self.u_set = c.prescribed() eliminated = c.elimination() @@ -285,26 +304,55 @@ def __init__(self, c: Constraints, mesh: FEMesh, scale: float): def exact(self) -> bool: return self.P is None - def internal(self, f_int: np.ndarray, u: np.ndarray) -> np.ndarray: - """Add the linear parts (supports, penalty springs) to the internal forces.""" + def internal(self, f_int: np.ndarray, u: np.ndarray, penalty: bool = True) -> np.ndarray: + """Add the other parts (supports, bolts, contact, penalty springs) to the internal + forces of the elements.""" if self.springs is not None: f_int = f_int + self.springs @ u - if self.P is not None: + if self.bolts is not None: + f_int = f_int + self.bolts @ u + if self.contacts is not None: + f_int = f_int + self.contacts.force(u) + self.stab * u + if self.P is not None and penalty: f_int = f_int + self.P @ u return f_int + def full(self, K: sp.csr_matrix) -> sp.csr_matrix: + """Tangent over all DOFs: elements plus the linear parts and the closed contacts.""" + for extra in (self.springs, self.bolts, self.P): + if extra is not None: + K = K + extra + if self.contacts is not None: + K = K + self.contacts.matrix() + sp.identity(K.shape[0], format="csr") * self.stab + return K + def tangent(self, K: sp.csr_matrix) -> sp.csr_matrix: - if self.springs is not None: - K = K + self.springs - if self.P is not None: - K = K + self.P - return (self.TT @ K @ self.T).tocsr() + return (self.TT @ self.full(K) @ self.T).tocsr() def solver(self, A: sp.csr_matrix): """Solve A x = b for the reduced tangent: p-multigrid CG for large exact systems, a factorization otherwise. A singular / indefinite tangent means the structure - can no longer carry an increase of the load.""" - if self.exact and A.shape[0] >= ITERATIVE_MIN_DOF: + can no longer carry an increase of the load. The tangent repeats exactly while + nothing yields and no contact changes (small strain): then the last + factorization is used again.""" + last = getattr(self, "_last", None) + if ( + last is not None + and last[0].shape == A.shape + and last[0].nnz == A.nnz + and np.array_equal(last[0].indptr, A.indptr) + and np.array_equal(last[0].indices, A.indices) + and np.array_equal(last[0].data, A.data) + ): + return last[1] + solve = self._new_solver(A) + self._last = (A.copy(), solve) + return solve + + def _new_solver(self, A: sp.csr_matrix): + # penalty contact or bolt springs: multigrid does not converge with them + direct = self.contacts is not None or self.bolts is not None + if self.exact and not direct and A.shape[0] >= ITERATIVE_MIN_DOF: from kstruct.fem.static import _coarse_dofs coarse_free = np.flatnonzero(~self.c.fixed[_coarse_dofs(self.mesh)]) @@ -327,15 +375,100 @@ def run(b): raise NotCarried("singular tangent") from e +class _Contacts: + """Frictionless node-to-surface contact inside the Newton iterations. A closed pair is + a penalty spring on its gap g = g0 + c·u (small sliding: the pairing and normals of + the undeformed mesh, as in the linear contact solver). After every Newton iteration + the pairs are chosen again: a closed pair stays closed while it is compressed (g ≤ 0) + and an open one closes once it penetrates. A pair may change at most MAX_FLIPS times + per increment (no chatter).""" + + def __init__(self, sets, alpha: float, n_dof: int): + self.sets, self.alpha, self.n_dof = sets, alpha, n_dof + self.flips = [np.zeros(len(cs.active), dtype=int) for cs in sets] + self._matrix = None # (state, K_c) of the last assembly + + def snapshot(self) -> list[np.ndarray]: + return [cs.active.copy() for cs in self.sets] + + def restore(self, saved: list[np.ndarray]) -> None: + for cs, active, flips in zip(self.sets, saved, self.flips, strict=True): + cs.active[:] = active + flips[:] = 0 + + def matrix(self) -> sp.csr_matrix: + key = tuple(cs.active.tobytes() for cs in self.sets) + if self._matrix is None or self._matrix[0] != key: + K = sp.csr_matrix((self.n_dof, self.n_dof)) + for cs in self.sets: + K = K + cs.penalty(self.n_dof, self.alpha)[0] + self._matrix = (key, K.tocsr()) + return self._matrix[1] + + def force(self, u: np.ndarray) -> np.ndarray: + """Spring forces of the closed pairs: α g c (pushes apart while penetrating).""" + f = np.zeros(self.n_dof) + for cs in self.sets: + act = cs.active + g = cs.gap(u)[act] + np.add.at(f, cs.dofs[act].ravel(), (self.alpha * cs.coefs[act] * g[:, None]).ravel()) + return f + + def update(self, u: np.ndarray) -> bool: + """Choose the closed pairs for u; True when any changed.""" + changed = False + for cs, flips in zip(self.sets, self.flips, strict=True): + g = cs.gap(u) + new = np.where(cs.active, g <= 0.0, g < -cs.tol) + new = np.where(flips >= MAX_FLIPS, cs.active, new) + diff = new != cs.active + if diff.any(): + flips += diff + cs.active[:] = new + changed = True + return changed + + def new_increment(self) -> None: + for flips in self.flips: + flips[:] = 0 + + def stats(self) -> list[tuple[int, int, int]]: + return [(int(cs.active.sum()), len(cs.active), 0) for cs in self.sets] + + +@dataclass +class _Path: + """One loading stage: λ runs 0 → 1 between the external forces f0 and f1, the imposed + displacements between the factors set0 and set1 of their full value and the thermal + strain between th0 and th1 of its full value.""" + + f0: np.ndarray + f1: np.ndarray + set0: float = 0.0 + set1: float = 0.0 + th0: float = 0.0 + th1: float = 0.0 + + def force(self, lam: float) -> np.ndarray: + return self.f0 + lam * (self.f1 - self.f0) + + def moved(self, lam: float) -> float: + return self.set0 + lam * (self.set1 - self.set0) + + def heat(self, lam: float) -> float: + return self.th0 + lam * (self.th1 - self.th0) + + # --- driver --------------------------------------------------------------------------- def unsupported(project: Project) -> str | None: """Why this project cannot be solved nonlinearly (None: it can).""" - if any(c.kind == ConnectionKind.CONTACT for c in project.connections): - return tr("접촉 연결이 있는 모델은 비선형(항복·큰 변형) 해석을 아직 지원하지 않습니다.") - if project.bolts: - return tr("볼트가 있는 모델은 비선형(항복·큰 변형) 해석을 아직 지원하지 않습니다.") + if any(c.kind == ConnectionKind.CONTACT and c.friction > 0 for c in project.connections): + return tr( + "마찰이 있는 접촉은 비선형(항복·큰 변형) 해석에서 아직 지원하지 않습니다. " + "마찰 계수를 0으로 하면 계산할 수 있습니다." + ) return None @@ -346,7 +479,19 @@ def solve_nonlinear( progress: Progress | None = None, ): """Static analysis with yielding and/or large deformation (project.plasticity, - project.large_deformation). Returns a StaticResult with `nonlinear` filled in.""" + project.large_deformation). Returns a StaticResult with `nonlinear` filled in. + + Bolts are springs as in the linear analysis; their tightening is the first loading + stage (the pulls are then corrected so every bolt carries exactly its preload), and + the other loads follow with the bolts held tight. Contacts (frictionless) open and + close inside the Newton iterations.""" + from kstruct.fem.bolts import ( + axial_vectors, + bolt_stiffness_and_preload, + build_bolts, + evaluate, + ) + from kstruct.fem.contact import CONTACT_PENALTY_FACTOR, build_contact from kstruct.fem.static import ( StaticResult, _load_vector, @@ -381,10 +526,31 @@ def solve_nonlinear( from kstruct.fem.assembly import stiffness_matrix K0 = stiffness_matrix(mesh, materials) - space = _Space(c, mesh, K0.diagonal().max()) - if not np.any(f_mech) and not np.any(space.u_set) and dT is None: + scale = K0.diagonal().max() + connectors = build_bolts(project, mesh) + K_bolts = bolt_stiffness_and_preload(connectors, n_dof)[0] if connectors else None + contact_links = [x for x in project.connections if x.kind == ConnectionKind.CONTACT] + contacts = ( + _Contacts( + [build_contact(mesh, x) for x in contact_links], CONTACT_PENALTY_FACTOR * scale, n_dof + ) + if contact_links + else None + ) + space = _Space(c, mesh, scale, K_bolts, contacts) + preload = np.array([bc.bolt.preload for bc in connectors]) if connectors else np.zeros(0) + if preload.any(): + joined = { + frozenset((x.faces_a[0].part_id, x.faces_b[0].part_id)) for x in project.connections + } + for bc in connectors: + pair = frozenset((bc.bolt.hole_a.part_id, bc.bolt.hole_b.part_id)) + if bc.bolt.preload and pair not in joined: + raise SolverError("bolt without contact") + if not np.any(f_mech) and not np.any(space.u_set) and dT is None and not preload.any(): raise SolverError(tr("하중이 없습니다. 힘, 압력, 중력 또는 온도 하중을 추가하세요.")) size = float(np.ptp(mesh.nodes, axis=0).max()) + max_newton = MAX_NEWTON + (CONTACT_EXTRA_ITERATIONS if contacts is not None else 0) # thermal strain also ramps with λ: it is part of the load def thermal_scale(lam): @@ -394,44 +560,37 @@ def thermal_scale(lam): base_thermal = [t.copy() if t is not None else None for t in el.thermal] - state = zero_state - u = np.zeros(n_dof) - lam, step = 0.0, FIRST_STEP - increments = iterations = 0 - limit_reason = "" - stress_points = np.zeros((el.n, 4, 6)) + counts = {"increments": 0, "iterations": 0} - def increment(target: float, u_start: np.ndarray, committed, lam_start: float): - """Newton iterations to equilibrium at load factor `target`, starting with a + def increment(target: float, u_start: np.ndarray, committed, lam_start: float, path: _Path): + """Newton iterations to equilibrium at `target` on the path, starting with a tangent predictor: the whole increment (load and imposed movement) is first applied through the last converged tangent. Moving only the imposed DOFs and iterating from there yields a thin layer of spurious plastic strain next to them that Newton's method then chases for many iterations.""" - nonlocal iterations moved = space.u_set != 0 - f_ext = target * f_mech - thermal_scale(lam_start) + f_ext = path.force(target) + thermal_scale(path.heat(lam_start)) f_int, K, _, _ = _evaluate(el, mesh, u_start, committed, large) du_set = np.zeros(n_dof) - du_set[moved] = (target - lam_start) * space.u_set[moved] - thermal_scale(target) + du_set[moved] = (path.moved(target) - path.moved(lam_start)) * space.u_set[moved] + thermal_scale(path.heat(target)) A = space.tangent(K) # linearised residual at the end of the increment (thermal strain enters through # the internal forces of the next evaluation, not the predictor) - Kfull = K if space.P is None else K + space.P - if space.springs is not None: - Kfull = Kfull + space.springs + Kfull = space.full(K) r_pred = space.TT @ (space.internal(f_int, u_start) + Kfull @ du_set - f_ext) u = u_start + du_set + space.T @ space.solver(A)(-r_pred) reference = max(np.linalg.norm(space.TT @ f_ext), np.linalg.norm(r_pred), 1e-30) previous = np.inf - for _ in range(MAX_NEWTON): + for _ in range(max_newton): f_int, K, trial, S = _evaluate(el, mesh, u, committed, large) + changed = contacts.update(u) if contacts is not None else False r = space.TT @ (space.internal(f_int, u) - f_ext) norm = np.linalg.norm(r) - if norm <= TOLERANCE * reference: + if norm <= TOLERANCE * reference and not changed: return u, trial, S - if norm > 10 * previous: + if norm > 10 * previous and not changed: raise NotCarried("diverging") previous = norm du = space.solver(space.tangent(K))(-r) @@ -447,33 +606,116 @@ def increment(target: float, u_start: np.ndarray, committed, lam_start: float): break step_du = 0.5 * step_du u = trial_u - iterations += 1 + counts["iterations"] += 1 if np.abs(u).max() > 0.5 * size: raise NotCarried("runaway displacement") raise NotCarried("no convergence") - report(0.1, tr("비선형 해석 시작")) - while lam < 1.0 - 1e-12: - target = min(1.0, lam + step) - try: - u_new, trial, S = increment(target, u, state, lam) - if trial[1].max() > RUNAWAY_PLASTIC_STRAIN: - raise NotCarried("runaway plastic strain") - except NotCarried as e: - step /= 2 - if step < MIN_STEP: - limit_reason = str(e) - log.info("nonlinear: load not carried beyond %.3f (%s)", lam, e) - break - continue - u, state, stress_points, lam = u_new, trial, S, target - increments += 1 - report( - 0.1 + 0.75 * lam, - tr("하중 {pct:.0f}% 계산 완료 (증분 {n})", pct=lam * 100, n=increments), + def ramp(path: _Path, u, state, stress_points, lo: float, hi: float, first=FIRST_STEP): + """Follow the path from λ = 0 to 1 in adaptive increments. Returns the last + converged state and the λ reached (< 1: the load was not carried in full).""" + lam, step, why = 0.0, first, "" + while lam < 1.0 - 1e-12: + target = min(1.0, lam + step) + saved = contacts.snapshot() if contacts is not None else None + if contacts is not None: + contacts.new_increment() + try: + u_new, trial, S = increment(target, u, state, lam, path) + if trial[1].max() > RUNAWAY_PLASTIC_STRAIN: + raise NotCarried("runaway plastic strain") + except NotCarried as e: + if contacts is not None: + contacts.restore(saved) + step /= 2 + if step < MIN_STEP: + why = str(e) + log.info("nonlinear: load not carried beyond %.3f (%s)", lam, e) + break + continue + if space.stab: + # the stabilising springs balance a real share of the load: a part is + # held by contact alone and came loose (as the linear contact solver + # says). Their resultant, not their sum: a collapsing part moves a lot + # too, but the springs then carry only ~1 % of the load. + free = ~space.c.fixed + held = np.zeros(n_dof) + held[free] = space.stab * u_new[free] + resultant = np.linalg.norm(held.reshape(-1, 3).sum(axis=0)) + total = np.abs(path.force(target)).reshape(-1, 3).sum() + if resultant > STAB_SHARE * max(total, 1e-30): + raise SolverError("contact unstable") + u, state, stress_points, lam = u_new, trial, S, target + counts["increments"] += 1 + report( + lo + (hi - lo) * lam, + tr("하중 {pct:.0f}% 계산 완료 (증분 {n})", pct=lam * 100, n=counts["increments"]), + ) + step = min(step * 1.5, 0.25) # easy increments: larger steps + return u, state, stress_points, lam, why + + state = zero_state + u = np.zeros(n_dof) + stress_points = np.zeros((el.n, 4, 6)) + zero = np.zeros(n_dof) + + pulls = preload.astype(float) + f_base = zero + u_tight = None + if preload.any(): + # stage 1: tighten the bolts, then correct the pulls until every bolt carries + # exactly its preload (the parts give a little as the bolts pull them together) + report(0.1, tr("볼트 체결 상태 계산 중")) + axial = axial_vectors(connectors, n_dof) + k = np.array([bc.k_axial for bc in connectors]) + + def f_pull(t): + return bolt_stiffness_and_preload(connectors, n_dof, t)[1] + + u, state, stress_points, lam, why = ramp( + _Path(zero, f_pull(pulls)), u, state, stress_points, 0.1, 0.25 ) - step = min(step * 1.5, 0.25) # easy increments: larger steps - if increments == 0: + if lam < 1.0 - 1e-9: + raise SolverError( + tr("볼트 체결력만으로도 부품이 버티지 못합니다. 체결력이나 볼트 자리를 확인하세요.") + ) + for _ in range(LOCK_ITERATIONS): + carried = pulls + k * (axial @ u) + if np.abs(preload - carried).max() <= LOCK_TOLERANCE * preload.max(): + break + _, K, _, _ = _evaluate(el, mesh, u, state, large) + solve = space.solver(space.tangent(K)) + U = np.column_stack( + [space.T @ solve(space.TT @ -axial[j]) for j in range(len(connectors))] + ) + change = np.linalg.solve(np.eye(len(k)) + k[:, None] * (axial @ U), preload - carried) + u, state, stress_points, lam, why = ramp( + _Path(f_pull(pulls), f_pull(pulls + change)), + u, + state, + stress_points, + 0.25, + 0.3, + first=1.0, # a small correction: one increment unless it fails + ) + if lam < 1.0 - 1e-9: + raise SolverError( + tr( + "볼트 체결력만으로도 부품이 버티지 못합니다. " + "체결력이나 볼트 자리를 확인하세요." + ) + ) + pulls = pulls + change + f_base = f_pull(pulls) + u_tight = u.copy() + + report(0.3 if preload.any() else 0.1, tr("비선형 해석 시작")) + loading = _Path(f_base, f_base + f_mech, 0.0, 1.0, 0.0, 1.0) + before = counts["increments"] + u, state, stress_points, lam, limit_reason = ramp( + loading, u, state, stress_points, 0.3 if preload.any() else 0.1, 0.85 + ) + if counts["increments"] == before: raise SolverError( tr("처음 하중 단계부터 풀리지 않습니다. 부품이 충분히 고정되었는지 확인하세요.") if limit_reason @@ -482,6 +724,8 @@ def increment(target: float, u_start: np.ndarray, committed, lam_start: float): report(0.88, tr("응력 계산 중")) loaded_u = u.copy() + contact_state = contacts.stats() if contacts is not None else [] + bolt_results = evaluate(connectors, loaded_u, pulls) if connectors else [] points = _cauchy(stress_points, el, mesh, u) if large else stress_points.copy() # in elements that yielded the stress is capped by the flow stress: a linear # extrapolation to the corners overshoots it (676 MPa shown for a 360 MPa material), @@ -493,9 +737,7 @@ def increment(target: float, u_start: np.ndarray, committed, lam_start: float): f_int, _, _, _ = _evaluate(el, mesh, u, state, large, False) # equilibrium residual without the penalty springs: at the fixed DOFs it is the support # force; on the free DOFs it is what the constraint equations carry - residual = f_int - lam * f_mech - if space.springs is not None: - residual = residual + space.springs @ u + residual = space.internal(f_int, u, penalty=False) - loading.force(lam) reactions = _reactions(c, space, residual, u) permanent = None @@ -503,8 +745,9 @@ def increment(target: float, u_start: np.ndarray, committed, lam_start: float): report(0.94, tr("하중을 뺀 뒤 남는 변형 계산 중")) try: for start, target in ((1.0, 0.5), (0.5, 0.0)): - u, state, _ = increment(target, u, state, start) - permanent = u.reshape(-1, 3) + u, state, _ = increment(target, u, state, start, loading) + # with bolts: what remains of the working load, the bolts still tight + permanent = (u - (u_tight if u_tight is not None else 0.0)).reshape(-1, 3) except NotCarried: log.info("nonlinear: unloading did not converge; no permanent deformation") thermal_scale(lam) # leave the element data as loaded @@ -515,8 +758,8 @@ def increment(target: float, u_start: np.ndarray, committed, lam_start: float): load_factor=lam, plastic_strain=peeq, permanent=permanent, - increments=increments, - iterations=iterations, + increments=counts["increments"], + iterations=counts["iterations"], limit_reason=limit_reason, ) report(1.0, tr("완료")) @@ -528,9 +771,13 @@ def increment(target: float, u_start: np.ndarray, committed, lam_start: float): reactions=reactions, applied_load=lam * f_mech.reshape(-1, 3).sum(axis=0), thermal=thermal, - contact=[], - bolts=[], - bolt_nodes=np.zeros(0, dtype=int), + contact=contact_state, + bolts=bolt_results, + bolt_nodes=np.unique( + np.concatenate([np.r_[b.weights_a[0], b.weights_b[0]] for b in connectors]) + ) + if connectors + else np.zeros(0, dtype=int), nonlinear=info, ) diff --git a/src/kstruct/fem/static.py b/src/kstruct/fem/static.py index 9169669..cba65f6 100644 --- a/src/kstruct/fem/static.py +++ b/src/kstruct/fem/static.py @@ -66,6 +66,8 @@ class StaticResult: bolts: list | None = None # fem.bolts.BoltResult per bolt bolt_nodes: np.ndarray | None = None # nodes under bolt heads / nuts nonlinear: object | None = None # fem.nonlinear.NonlinearInfo for yield / large runs + harmonic: object | None = None # fem.harmonic.HarmonicResult: a vibration response + harmonic_frequency: float | None = None # Hz this state belongs to @property def von_mises(self) -> np.ndarray: diff --git a/src/kstruct/geometry/measure.py b/src/kstruct/geometry/measure.py new file mode 100644 index 0000000..2269ffe --- /dev/null +++ b/src/kstruct/geometry/measure.py @@ -0,0 +1,73 @@ +"""Measuring on the model (3D view 'Measure' tool): the face under the cursor (area, +hole diameter and axis, plane normal) and the distance between two picked points, in +the project's display units.""" + +from __future__ import annotations + +import numpy as np +from OCP.BRepAdaptor import BRepAdaptor_Surface +from OCP.GeomAbs import GeomAbs_Cone, GeomAbs_Cylinder +from OCP.TopoDS import TopoDS_Face + +from kstruct.geometry.face_info import face_info, outward_normal +from kstruct.i18n import tr +from kstruct.units import fmt, quantity + + +def axis_of(face: TopoDS_Face) -> tuple[np.ndarray, np.ndarray] | None: + """(point on the axis, unit direction) of a cylinder or cone, else None.""" + surface = BRepAdaptor_Surface(face) + kind = surface.GetType() + if kind == GeomAbs_Cylinder: + ax = surface.Cylinder().Axis() + elif kind == GeomAbs_Cone: + ax = surface.Cone().Axis() + else: + return None + return np.array(ax.Location().Coord()), np.array(ax.Direction().Coord()) + + +def _vector(system: str, v) -> str: + return "(" + ", ".join(fmt(system, "length", float(x), ",.2f") for x in v) + ")" + + +def face_text(face: TopoDS_Face, system: str, at=None) -> str: + """Area, and for a hole/shaft its diameter and axis, for a plane its normal.""" + info = face_info(face) + area = quantity(system, "length") + area_unit = f"{area.unit}²" + text = tr( + "{kind}, 면적 {area:,.2f} {unit}", + kind=info.kind, + area=info.area * area.to_display**2, + unit=area_unit, + ) + axis = axis_of(face) + if info.radius is not None: + text += tr(", 지름 {d}", d=fmt(system, "length", 2 * info.radius, ",.3f")) + if axis is not None: + point, direction = axis + if at is not None: # the axis point nearest to where the face was picked + point = point + direction * float(np.dot(np.asarray(at) - point, direction)) + text += tr( + ", 축 방향 ({x:.3f}, {y:.3f}, {z:.3f}) · 축 위 점 {p}", + x=direction[0], + y=direction[1], + z=direction[2], + p=_vector(system, point), + ) + normal = outward_normal(face) + if normal is not None: + text += tr(", 바깥 법선 ({x:.3f}, {y:.3f}, {z:.3f})", x=normal[0], y=normal[1], z=normal[2]) + return text + + +def distance_text(p, q, system: str) -> str: + d = np.asarray(q, float) - np.asarray(p, float) + return tr( + "거리 {d} (ΔX {dx}, ΔY {dy}, ΔZ {dz})", + d=fmt(system, "length", float(np.linalg.norm(d)), ",.3f"), + dx=fmt(system, "length", float(d[0]), "+,.3f"), + dy=fmt(system, "length", float(d[1]), "+,.3f"), + dz=fmt(system, "length", float(d[2]), "+,.3f"), + ) diff --git a/src/kstruct/model/project.py b/src/kstruct/model/project.py index acf7312..1d43a5a 100644 --- a/src/kstruct/model/project.py +++ b/src/kstruct/model/project.py @@ -71,6 +71,7 @@ class Fixture: displacement: tuple[float | None, float | None, float | None] = (None, None, None) # ELASTIC: total spring stiffness of the faces in the normal direction (N/mm) stiffness: float = 0.0 + symmetry: bool = False # ROLLER on a plane of symmetry (results are for part of it) class LoadKind(Enum): @@ -169,6 +170,7 @@ class AnalysisKind(Enum): MODAL = "modal" # natural frequencies THERMAL = "thermal" # steady-state temperature only BUCKLING = "buckling" # load factor at which slender parts collapse sideways + HARMONIC = "harmonic" # response to loads that vibrate (frequency sweep) @dataclass @@ -193,6 +195,8 @@ class Project: large_deformation: bool = False # geometry changes under load (large rotations) operating_frequency: float = 0.0 # Hz, excitation to compare natural frequencies with n_modes: int = 6 + damping_ratio: float = 0.02 # modal damping ζ for the harmonic response + harmonic_range: tuple[float, float] = (0.0, 0.0) # Hz; upper 0 = automatic load_cycle: str = "none" # fem.fatigue.LoadCycle value fatigue_surface: str = "machined" # fem.fatigue.SURFACE_FACTORS key fatigue_reliability: str = "90" # fem.fatigue.RELIABILITY_FACTORS key (%) diff --git a/src/kstruct/paths.py b/src/kstruct/paths.py index e4207fc..ba4c79e 100644 --- a/src/kstruct/paths.py +++ b/src/kstruct/paths.py @@ -43,6 +43,11 @@ def user_materials_path() -> Path: return data_dir() / "materials.json" +def templates_path() -> Path: + """Saved condition templates (kstruct/templates.py).""" + return data_dir() / "templates.json" + + def setup_logging() -> Path: """Rotating log file in the data folder (plus stderr when there is a console). Returns the log path. Safe to call more than once.""" diff --git a/src/kstruct/project_io.py b/src/kstruct/project_io.py index 9fb4fc4..529caa3 100644 --- a/src/kstruct/project_io.py +++ b/src/kstruct/project_io.py @@ -99,6 +99,8 @@ def to_document(project: Project) -> dict: "large_deformation": project.large_deformation, "operating_frequency": project.operating_frequency, "n_modes": project.n_modes, + "damping_ratio": project.damping_ratio, + "harmonic_range": list(project.harmonic_range), "load_cycle": project.load_cycle, "fatigue_surface": project.fatigue_surface, "fatigue_reliability": project.fatigue_reliability, @@ -115,6 +117,7 @@ def to_document(project: Project) -> dict: "faces": _refs(f.faces), "displacement": list(f.displacement), "stiffness": f.stiffness, + "symmetry": f.symmetry, } for f in project.fixtures ], @@ -268,6 +271,8 @@ def from_document(doc: dict, shapes: dict) -> Project: large_deformation=bool(doc.get("large_deformation", False)), operating_frequency=doc.get("operating_frequency", 0.0), n_modes=doc.get("n_modes", 6), + damping_ratio=doc.get("damping_ratio", 0.02), + harmonic_range=tuple(doc.get("harmonic_range", (0.0, 0.0))), load_cycle=doc.get("load_cycle", "none"), fatigue_surface=doc.get("fatigue_surface", "machined"), fatigue_reliability=str(doc.get("fatigue_reliability", "90")), @@ -293,6 +298,7 @@ def from_document(doc: dict, shapes: dict) -> Project: _unrefs(f["faces"]), tuple(None if d is None else float(d) for d in f.get("displacement", [None] * 3)), float(f.get("stiffness", 0.0)), + bool(f.get("symmetry", False)), ) for f in doc["fixtures"] ] diff --git a/src/kstruct/report/advice.py b/src/kstruct/report/advice.py new file mode 100644 index 0000000..84bb241 --- /dev/null +++ b/src/kstruct/report/advice.py @@ -0,0 +1,271 @@ +"""What to change after a strength verdict, from where the governing stress sits. + +The location is classified from the B-rep faces through the governing node: a sharp +concave corner (a stress singularity), a hole, a fillet, a thin wall. The numbers come +only from scaling laws that hold exactly for a linear analysis: + +- load: stress is proportional to load, so the load the target allows is fos / target + times the present one; +- material: with one material and the same Poisson's ratio the stresses do not change + (kstruct/whatif.py), so the strength needed is target / fos times the present one; +- wall thickness: a wall that bends carries σ ∝ 1/t², one pulled or pushed σ ∝ 1/t, so + the thickness needed lies between √r and r times the present one, r = target / fos. + Which of the two applies is not known here and both are stated. + +Nothing else gets a number (no "a fillet of R lowers the stress by x %"). +""" + +from __future__ import annotations + +import math + +import numpy as np + +from kstruct import standards +from kstruct.fem.singularity import CONCAVE_EDGE, KIND_NAMES +from kstruct.i18n import tr, tr_data +from kstruct.model import THERMAL_LOADS, ConnectionKind, FixtureKind, LoadKind, Project +from kstruct.standards import Verdict +from kstruct.units import fmt, system_of + +THIN = 0.15 # a wall thinner than this times the part's largest extent counts as thin +HOLE_SPAN = 0.6 * math.pi # a concave cylinder spanning more than this is (part of) a hole +GENEROUS = 3.0 # safety factor above this times the target: room to save material + + +def linear_in_loads(project: Project, result) -> bool: + """True when every stress scales with the loads (and with nothing else).""" + if result.nonlinear is not None or result.thermal is not None: + return False + if any(c.kind == ConnectionKind.CONTACT for c in project.connections): + return False + if any(b.preload for b in project.bolts): + return False + if any(ld.kind in THERMAL_LOADS or ld.kind == LoadKind.TEMPERATURE for ld in project.loads): + return False + return not any( + fx.kind == FixtureKind.DISPLACEMENT and any(fx.displacement or ()) + for fx in project.fixtures + ) + + +def _faces_at(mesh, node: int) -> list[int]: + """B-rep faces (of the node's part) whose surface triangles hold the node; for an + interior node those at the closest surface node.""" + hit = np.flatnonzero((mesh.tris == node).any(axis=1)) + if len(hit) == 0: + surface = np.unique(mesh.tris) + nearest = surface[np.argmin(np.linalg.norm(mesh.nodes[surface] - mesh.nodes[node], axis=1))] + hit = np.flatnonzero((mesh.tris == nearest).any(axis=1)) + return sorted({int(f) for f in mesh.tri_face[hit]}) + + +def _cylinder(face): + """(radius, concave, angular span) of a cylindrical face, else None.""" + from OCP.BRepAdaptor import BRepAdaptor_Surface + from OCP.BRepTools import BRepTools + from OCP.GeomAbs import GeomAbs_Cylinder + from OCP.TopAbs import TopAbs_REVERSED + + surface = BRepAdaptor_Surface(face) + if surface.GetType() != GeomAbs_Cylinder: + return None + u0, u1, _v0, _v1 = BRepTools.UVBounds_s(face) + # the surface normal points away from the axis; a reversed face has the material + # outside the cylinder: a hole or a fillet in a concave corner + concave = face.Orientation() == TopAbs_REVERSED + return surface.Cylinder().Radius(), concave, u1 - u0 + + +def _location(project: Project, mesh, part_summary) -> dict: + """What the governing node sits on: hole / fillet radius, wall thickness.""" + from kstruct.geometry.tessellate import faces_of + from kstruct.geometry.thickness import face_thickness + + part = project.part(part_summary.part_id) + faces = faces_of(part.shape) + node = part_summary.governing_node + out = {"hole": None, "fillet": None, "thickness": None} + indices = _faces_at(mesh, node) + for i in indices: + cyl = _cylinder(faces[i]) + if cyl is None or not cyl[1]: + continue + radius, _, span = cyl + if span > HOLE_SPAN: + out["hole"] = radius + else: + out["fillet"] = radius + nodes = mesh.part_nodes(part_summary.part_id) + extent = float(np.ptp(mesh.nodes[nodes], axis=0).max()) + walls = face_thickness(part.shape) + thick = [walls[i] for i in indices if i in walls] + if thick and min(thick) < THIN * extent: + out["thickness"] = min(thick) + return out + + +def design_advice(project: Project, result, summary) -> list[str]: + """Plain-language suggestions for the weakest part (empty when there is nothing + useful to say).""" + if not summary.parts or result.nonlinear is not None: + return [] + us = system_of(project) + worst = max(summary.parts, key=lambda s: (_rank(s.verdict), -s.governing_fos)) + fos, target = worst.governing_fos, worst.target + fatigue = ( + worst.fatigue_fos is not None + and worst.fatigue_fos < fos + and worst.fatigue_verdict != Verdict.OK + ) + if fatigue: + fos = worst.fatigue_fos + harmonic = getattr(result, "harmonic", None) is not None + generous = not fatigue and all( + s.governing_fos >= GENEROUS * s.target and s.verdict == Verdict.OK for s in summary.parts + ) + if worst.verdict == Verdict.OK and not generous and not fatigue: + return [] + if worst.governing_node < 0: + return [] + where = _location(project, result.mesh, worst) + name = tr_data(worst.name) + lines = [] + + # where the stress gathers and what to do about it there + if worst.singular_kind == KIND_NAMES[CONCAVE_EDGE]: + lines.append( + tr( + "{name}: 응력이 가장 큰 곳은 필렛 없는 오목 모서리입니다. 모서리에 필렛(둥글림)을 " + "주는 것이 가장 효과적입니다. 반지름이 클수록 응력이 낮아지며, 필렛을 넣은 뒤 다시 " + "해석하면 그 자리의 실제 응력을 볼 수 있습니다.", + name=name, + ) + ) + if where["hole"] is not None: + lines.append( + tr( + "{name}: 판정 위치가 구멍(지름 {d}) 가장자리입니다. 구멍 둘레에는 응력이 몰립니다" + "(넓은 판을 당길 때 이론적으로 평균의 3배). 구멍을 응력이 낮은 곳으로 옮기거나, " + "가장자리까지의 거리를 늘리거나, 구멍 둘레를 두껍게(보스) 하세요.", + name=name, + d=fmt(us, "length", 2 * where["hole"], ".3g"), + ) + ) + elif where["fillet"] is not None: + lines.append( + tr( + "{name}: 판정 위치가 필렛(반지름 {r})입니다. 반지름을 키우면 응력이 낮아집니다.", + name=name, + r=fmt(us, "length", where["fillet"], ".3g"), + ) + ) + if generous: + if where["thickness"] is not None and not harmonic and linear_in_loads(project, result): + r = target / fos + lines.append( + tr( + "여유가 큽니다(안전율 {fos:.1f}, 권장 {target:.1f}). 하중이 확실하다면 가장 약한 " + "곳의 벽(두께 {t})을 약 {b}까지 줄여도 권장값을 만족합니다(굽힘을 받는 벽 기준의 " + "선형 비례 추정이며, 당김·누름을 받는 벽이면 더 얇아도 됩니다). 줄인 뒤 다시 " + "해석해 확인하세요.", + fos=fos, + target=target, + t=fmt(us, "length", where["thickness"], ".3g"), + b=fmt(us, "length", where["thickness"] * math.sqrt(r), ".3g"), + ) + ) + return lines + + if not linear_in_loads(project, result): + lines.append( + tr( + "접촉·예압·열응력·강제 변위가 있어 응력이 하중에 정비례하지 않으므로, 두께·하중을 " + "몇 배 바꿀지는 바꾼 뒤 다시 해석해 확인하세요." + ) + ) + return lines + r = target / fos + kind = tr("피로 안전율") if fatigue else tr("안전율") + lines.append( + tr( + "하중을 지금의 {k:.2f}배 이하로 줄이면 권장 {kind}({target:.1f})을 만족합니다" + "(선형 해석이라 응력은 하중에 정비례).", + k=1 / r, + kind=kind, + target=target, + ) + if not harmonic + else tr( + "흔들리는 하중의 크기를 지금의 {k:.2f}배 이하로 줄이면 권장 {kind}({target:.1f})을 " + "만족합니다(응답은 하중 크기에 정비례).", + k=1 / r, + kind=kind, + target=target, + ) + ) + if harmonic: + return lines # thickness or material also move the natural frequencies + if where["thickness"] is not None: + t = where["thickness"] + lines.append( + tr( + "판정 위치의 벽 두께는 {t}입니다. 그 벽이 굽힘을 받는다면 약 {b}(×{fb:.2f}), " + "당김·누름을 받는다면 약 {m}(×{fm:.2f})로 두껍게 하면 권장값을 만족합니다(선형 비례 " + "추정, 두께 외 형상은 그대로일 때). 리브를 더하는 것도 방법입니다.", + t=fmt(us, "length", t, ".3g"), + b=fmt(us, "length", t * math.sqrt(r), ".3g"), + fb=math.sqrt(r), + m=fmt(us, "length", t * r, ".3g"), + fm=r, + ) + ) + if not fatigue: + lines += _materials(project, result, worst, r) + return lines + + +def _materials(project: Project, result, worst, r: float) -> list[str]: + """Materials strong enough for the same stresses (exact swaps only).""" + from kstruct.whatif import why_not_exact + + pack = standards.effective_pack(project) + us = system_of(project) + current = result.materials.get(worst.part_id) + if current is None: + return [] + needed = worst.capacity * r + fits = [] + for m in standards.project_materials(project).values(): + if m.ductile != current.ductile or m.id == current.id: + continue + capacity = m.yield_strength if m.ductile else m.tensile_strength + if capacity < needed or why_not_exact(project, result, m) is not None: + continue + fits.append((capacity, tr_data(pack.material_name(m)))) + strength = tr("항복강도") if current.ductile else tr("인장강도") + if not fits: + return [ + tr( + "재료만 바꾼다면 {strength} {need} 이상이 필요합니다(지금 {now}). 목록에 그런 " + "재료가 없어 형상 변경을 권합니다.", + strength=strength, + need=fmt(us, "stress", needed, ",.0f"), + now=fmt(us, "stress", worst.capacity, ",.0f"), + ) + ] + fits.sort() + return [ + tr( + "재료만 바꾼다면 {strength} {need} 이상이 필요합니다(지금 {now}). 같은 응력 분포로 " + "바로 쓸 수 있는 후보: {names}. 결과 화면의 '재료 바꿔 보기'로 바로 확인할 수 있습니다.", + strength=strength, + need=fmt(us, "stress", needed, ",.0f"), + now=fmt(us, "stress", worst.capacity, ",.0f"), + names=", ".join(n for _, n in fits[:3]), + ) + ] + + +def _rank(v: Verdict) -> int: + return {Verdict.OK: 0, Verdict.WARN: 1, Verdict.FAIL: 2}[v] diff --git a/src/kstruct/report/describe.py b/src/kstruct/report/describe.py index c496e07..2cc64ec 100644 --- a/src/kstruct/report/describe.py +++ b/src/kstruct/report/describe.py @@ -66,6 +66,8 @@ def describe_fixture(project: Project, fx: Fixture, faces: FaceNamer | None = No detail = f" ({', '.join(parts)})" if parts else "" elif fx.kind == FixtureKind.ELASTIC: detail = f" ({fmt(system, 'stiffness', fx.stiffness)})" + if fx.symmetry: + return tr("대칭면 (미끄럼 지지): {faces}", faces=faces(fx.faces)) return f"{tr(FIXTURE_NAMES[fx.kind])}{detail}: {faces(fx.faces)}" diff --git a/src/kstruct/report/pdf.py b/src/kstruct/report/pdf.py index c83e2d0..d175d53 100644 --- a/src/kstruct/report/pdf.py +++ b/src/kstruct/report/pdf.py @@ -258,9 +258,18 @@ def _static_html( iterations=nl.iterations, reached=nl.load_factor * 100, ) + harmonic, kind = ( + "", + (N_("비선형 정적 유한요소해석") if nl is not None else N_("선형 정적 유한요소해석")), + ) + if result.harmonic is not None: + method, harmonic, kind = _harmonic_html(result, us) + advice = _list(summary.advice) body = f""" +{f"

{tr('개선 방법')}

" if summary.advice else ""} {f"

{tr('참고')}

" if notes else ""} {_cases_html(project, overview, us)} +{harmonic}

{tr("1. 부품별 결과")}

@@ -296,10 +305,44 @@ def _static_html( summary.verdict, body, result.mesh, - N_("비선형 정적 유한요소해석") - if result.nonlinear is not None - else N_("선형 정적 유한요소해석"), + kind, + ) + + +def _harmonic_html(result: StaticResult, us) -> tuple[str, str, str]: + """(method line, response table, disclaimer kind) of a vibration response result.""" + h, shown = result.harmonic, result.harmonic_frequency + lo, hi = h.range + method = tr( + "진동 응답(주파수 응답) 해석: 고유 모드 {m}개 중첩 + 나머지 모드의 정적 보정, " + "감쇠비 {z:.1f}%, {lo:,.1f}~{hi:,.1f} Hz를 {n}개 진동수로 계산. 응력·변형은 " + "{f:,.1f} Hz에서 한 주기 동안의 최댓값이며 피로는 양방향 반복으로 판정", + m=len(h.natural), + z=h.damping * 100, + lo=lo, + hi=hi, + n=len(h.frequencies), + f=shown, + ) + picks = [(tr("판정 진동수"), shown)] + if abs(h.governing - shown) > 1e-9: + picks.append((tr("가장 불리"), h.governing)) + picks += [(tr("{i}차 공진", i=i + 1), f) for i, f in enumerate(h.natural) if lo <= f <= hi] + rows = "".join( + f"" + f"" + f"" + f"" + for label, f in picks + ) + table = ( + f"

{tr('진동수별 응답')}

" + "
{tr("부품")}{tr("재료")}{tr("최대 응력")}{tr("재료 강도")}
{label}{f:,.1f} Hz{fmt(us, 'length', float(np.interp(f, h.frequencies, h.displacement)))}{fmt(us, 'stress', float(np.interp(f, h.frequencies, h.stress)), ',.1f')}×{h.amplification(f):,.1f}
" + f"" + f"" + f"{rows}
{tr('진동수')}{tr('최대 변형 진폭')}{tr('최대 응력 진폭')}{tr('정지 하중 대비')}
" ) + return method, table, N_("진동 응답 유한요소해석(모드 중첩)") # --- modal / thermal / buckling ------------------------------------------------------- diff --git a/src/kstruct/report/summary.py b/src/kstruct/report/summary.py index fbbf7cc..6ff5467 100644 --- a/src/kstruct/report/summary.py +++ b/src/kstruct/report/summary.py @@ -16,7 +16,7 @@ from kstruct.fem.singularity import CONCAVE_EDGE, KIND_NAMES, NONE, find_singularities from kstruct.fem.static import StaticResult from kstruct.i18n import N_, tr, tr_data -from kstruct.model import ConnectionKind, FixtureKind, Project +from kstruct.model import THERMAL_LOADS, ConnectionKind, FixtureKind, LoadKind, Project from kstruct.standards import StandardPack, Verdict, verdict from kstruct.units import fmt, system_of @@ -68,6 +68,15 @@ class PartSummary: fatigue_verdict: Verdict | None = None fatigue_excludes_singularity: bool = False # fatigue values taken outside the zone plastic_strain: float | None = None # nonlinear run with yielding: governing peeq + weakest_node: int = -1 # node of min_fos + hotspot_node: int | None = None # node of hotspot_fos + + @property + def governing_node(self) -> int: + """Node the governing safety factor belongs to.""" + if self.hotspot_fos is not None and self.ductile: + return self.hotspot_node + return self.weakest_node @property def governing_fos(self) -> float: @@ -93,6 +102,7 @@ class Summary: fatigue: object | None = None # fem.fatigue.FatigueResult bolts: list = field(default_factory=list) # fem.bolts.BoltResult governing_fos: float = 0.0 # the number in the headline + advice: list[str] = field(default_factory=list) # what to change (report/advice.py) def summarize(project: Project, result: StaticResult, pack: StandardPack) -> Summary: @@ -137,6 +147,7 @@ def summarize(project: Project, result: StaticResult, pack: StandardPack) -> Sum verdict=verdict(float(fos[weakest]), target), max_disp=float(disp[nodes].max()), at_fixture=bool(np.isin(peak, fixture_nodes)), + weakest_node=int(weakest), ) zone = singular.zone(mesh, pid) outside = nodes[~zone[nodes]] @@ -145,6 +156,7 @@ def summarize(project: Project, result: StaticResult, pack: StandardPack) -> Sum if kind != NONE: hot = float(demand[outside].max()) hot_fos = float(fos[outside].min()) + part.hotspot_node = int(outside[int(np.argmin(fos[outside]))]) part.singular_kind = KIND_NAMES[kind] part.hotspot_stress = hot part.hotspot_fos = hot_fos @@ -155,6 +167,9 @@ def summarize(project: Project, result: StaticResult, pack: StandardPack) -> Sum fatigue = None cycle = LoadCycle(project.load_cycle) nonlinear = getattr(result, "nonlinear", None) + harmonic = getattr(result, "harmonic", None) + if harmonic is not None: + cycle = LoadCycle.REVERSED # a vibration swings both ways about zero if cycle != LoadCycle.NONE and nonlinear is not None: cycle = LoadCycle.NONE # stresses beyond yield: the fatigue model does not apply skipped_fatigue = True @@ -409,6 +424,17 @@ def summarize(project: Project, result: StaticResult, pack: StandardPack) -> Sum ) ) + if any(fx.symmetry for fx in project.fixtures): + notes.append( + tr( + "대칭면을 지정해 부품의 일부만 계산했습니다. 응력·변형·안전율은 전체 부품과 " + "같지만, 반력과 하중 합은 계산한 부분만의 값입니다(반 모델이면 전체의 1/2, " + "1/4 모델이면 1/4). 하중과 형상이 대칭일 때만 맞는 방법입니다." + ) + ) + if harmonic is not None: + notes[:0] = _harmonic_notes(project, result) + title = VERDICT_STYLE[worst_verdict][0] label = tr("최소 안전율") if fatigue is not None and worst_fos == min(s.fatigue_fos for s in parts): @@ -432,9 +458,59 @@ def summarize(project: Project, result: StaticResult, pack: StandardPack) -> Sum ) if nonlinear is not None: _judge_nonlinear(summary, project, result, singular, us) + else: + from kstruct.report.advice import design_advice + + summary.advice = design_advice(project, result, summary) return summary +def _harmonic_notes(project: Project, result) -> list[str]: + """What a vibration response result means: where in the sweep it was taken, how much + the vibration amplifies the loads there, and what was left out.""" + h, freq = result.harmonic, result.harmonic_frequency + lo, hi = h.range + notes = [ + tr( + "진동 응답: 하중이 {lo:,.1f}~{hi:,.1f} Hz로 흔들릴 때 {f:,.1f} Hz의 상태입니다. " + "변형은 같은 하중을 가만히 걸 때의 약 {a:,.1f}배이고, 응력·변형은 한 주기 동안의 " + "가장 큰 값입니다(양방향 반복으로 피로도 판정).", + lo=lo, + hi=hi, + f=freq, + a=h.amplification(freq), + ) + ] + near = [i for i, fn in enumerate(h.natural) if abs(freq - fn) <= 3 * h.damping * fn] + if near: + i = near[0] + notes.append( + tr( + "{i}차 고유진동수 {fn:,.1f} Hz의 공진입니다. 공진 응답은 감쇠비(가정 {z:.1f}%)에 " + "반비례해 실제 감쇠가 작으면 더 커집니다. 가진 진동수가 이 값의 ±20 % 밖에 " + "있게 하거나 두께·리브로 고유진동수를 옮기면 응답이 크게 줄어듭니다.", + i=i + 1, + fn=float(h.natural[i]), + z=h.damping * 100, + ) + ) + left_out = [] + if any(ld.kind in THERMAL_LOADS or ld.kind == LoadKind.TEMPERATURE for ld in project.loads): + left_out.append(tr("열 조건")) + if any(fx.kind == FixtureKind.DISPLACEMENT for fx in project.fixtures): + left_out.append(tr("강제 변위(움직이지 않는 지지로 봄)")) + if any(b.preload for b in project.bolts): + left_out.append(tr("볼트 예압")) + if left_out: + notes.append( + tr( + "진동 응답 계산에서 빠진 조건: {items}. 흔들리는 하중만 계산합니다.", + items=", ".join(left_out), + ) + ) + return notes + + # beyond this equivalent plastic strain a part is permanently bent for practical purposes; # up to it the yielding is local and the permanent set small (the 0.2 % of a proof stress) LOCAL_YIELD_STRAIN = 0.002 diff --git a/src/kstruct/resources/help/en.json b/src/kstruct/resources/help/en.json index 0f87c72..698890c 100644 --- a/src/kstruct/resources/help/en.json +++ b/src/kstruct/resources/help/en.json @@ -642,5 +642,55 @@ "title": "Try another material", "short": "Shows what the verdict would be with another material, straight away when no new analysis is needed.", "detail": "When every part has the same material and the analysis is linear, another material leaves the stresses unchanged and scales the deformation by the stiffness ratio, so only the verdict (safety factor, fatigue) is worked out again without solving. The Poisson's ratios must match, as within one family (steels, aluminium alloys).

With a different Poisson's ratio, thermal stress, self-weight (different density), imposed displacements, elastic supports or bolts the result really changes: you are told why and asked whether to run the analysis again.

'Use this material' also changes the material in the project; the result stays valid." + }, + "analysis.harmonic": { + "title": "Vibration response", + "short": "How much the part shakes and how high the stresses get when the loads vibrate at a steady frequency.", + "detail": "When the same load keeps swinging, as from a motor, a pump or a rotor, the deflection and stress grow to several or even tens of times their static values the closer the frequency comes to a natural frequency of the part (resonance).

The loads from step 5 are taken as the amplitude of the vibrating load. The whole frequency range set in step 6 is swept, and strength and fatigue (fully reversed) are checked at the worst frequency. The curve in the results shows the largest stress per frequency; click it to see another frequency.

The natural modes are superposed (mode superposition) and the share of the higher modes left out is added as a static correction. Thermal conditions, bolt preload and imposed displacements do not vibrate and are left out; contacts act bonded.", + "related": [ + "harmonic.damping", + "harmonic.range", + "analysis.modal" + ] + }, + "harmonic.damping": { + "title": "Damping ratio", + "short": "How quickly vibration dies away by itself. If unsure, use 2 % (a common value for bolted or welded steel structures).", + "detail": "The response at resonance is nearly inversely proportional to the damping ratio: with 2 % it is about 25 times the static response, with 1 % about 50 times.

Rough values: a part machined in one piece 0.5-1 %, bolted or welded assemblies 2-5 %, rubber mounts or structures with much friction 5-10 %. When in doubt the smaller value is on the safe side." + }, + "harmonic.range": { + "title": "Vibrating frequencies", + "short": "The range of frequencies the loads can vibrate at. With the upper end on 'Auto' it covers all natural frequencies found.", + "detail": "For example, a motor whose speed varies from 600 to 3000 rpm gives 10-50 Hz (rpm / 60). The check is taken at the worst frequency in the range, so a range that contains a natural frequency is judged at resonance.

A range wider than the machine really runs can fail a design needlessly." + }, + "result.frequency": { + "title": "Frequency", + "short": "Choose the frequency to view the vibration response at. The verdict is taken at the 'worst' one.", + "detail": "'Worst' is the frequency in the range where the stress comes closest to the strength; 'resonance n' is the state at a natural frequency. You can also click the curve below to choose another frequency.

Stresses and deflections are the largest each point reaches during one cycle." + }, + "result.response": { + "title": "Response curve", + "short": "The largest stress in the model at each frequency. Dashed lines are natural frequencies, the red dashed line the strength. Click to view that frequency.", + "detail": "The peaks are resonances; their height is inversely proportional to the damping ratio. An operating frequency away from the peaks gives a much smaller response.

The vertical axis is logarithmic: one grid step is a factor of 10." + }, + "view.measure": { + "title": "Measure", + "short": "Measures face area, hole diameter and axis, and the distance between two points (shortcut M).", + "detail": "While it is on, clicking a face shows its area (needed to convert pressure to force and back) and, for a hole or shaft, its diameter and axis direction in the status bar. Clicking a second point shows the distance between the two points and their X, Y, Z differences and draws a line. A third click starts a new measurement.

While measuring, clicks do not select faces. Press it again to turn it off." + }, + "result.compare": { + "title": "Compare results", + "short": "Keep this result as the reference and compare it side by side with the result after a design change.", + "detail": "After 'Use this result as the reference', change thickness, material, loads etc. and analyse again: the governing safety factor, the largest stress and the largest deflection are shown for the reference and now, side by side.

On an identical mesh (shape and mesh grade unchanged) the difference can be shown in colour: now − reference. 'Show the reference result' brings the reference back on screen to switch between the two. The reference stays until another model is opened." + }, + "fixture.symmetry": { + "title": "Plane of symmetry", + "short": "When the part is cut at a plane of symmetry to compute half (or a quarter) of it, select the cut plane and press this.", + "detail": "When shape and loads are both symmetric, modelling half gives the same stresses and deflections much faster. The cut face may slide within its plane but not move through it, so it becomes a roller support.

Reactions and load sums in the results are for the computed part only (half of the whole for a half model). Vibration and buckling can miss shapes that are not symmetric." + }, + "fixture.template": { + "title": "Condition templates", + "short": "Save the present fixtures and loads as a template and put them on faces of the same kind in another model.", + "detail": "Faces are remembered by kind, not by number: holes and shafts by radius, planes by direction and area. Applying a template puts each condition on every such face (a 'bolt hole fixed' template saved from one hole lands on all holes of that size). Conditions that find no matching face are left out and reported.

Conditions without faces, such as self-weight, are added as they are. Saved templates stay in this computer's user data folder." } } diff --git a/src/kstruct/resources/help/ko.json b/src/kstruct/resources/help/ko.json index 661fb26..60808ff 100644 --- a/src/kstruct/resources/help/ko.json +++ b/src/kstruct/resources/help/ko.json @@ -642,5 +642,55 @@ "title": "재료 바꿔 보기", "short": "다른 재료였다면 판정이 어떻게 되는지 봅니다. 가능하면 다시 해석하지 않고 바로 보여 줍니다.", "detail": "모든 부품이 한 재료이고 선형 해석이면, 재료를 바꿔도 응력 분포는 그대로이고 변형만 탄성계수 비율만큼 달라지므로 다시 풀지 않고 판정(안전율·피로)만 새로 합니다. 같은 계열(예: 강철끼리, 알루미늄끼리)처럼 푸아송비가 같아야 합니다.

푸아송비가 다르거나, 열응력·자중(밀도가 다를 때)·강제 변위·탄성 지지·볼트가 있으면 결과가 실제로 달라지므로 그 이유를 알려 주고 다시 해석할지 묻습니다.

'이 재료로 확정'을 누르면 프로젝트의 재료도 바뀌고 결과는 그대로 유효합니다." + }, + "analysis.harmonic": { + "title": "진동 응답 해석", + "short": "하중이 일정한 진동수로 흔들릴 때 부품이 얼마나 떨리고 응력이 얼마나 커지는지 구합니다.", + "detail": "모터·펌프·회전체처럼 같은 하중이 계속 흔들리며 걸리면, 그 진동수가 부품의 고유진동수에 가까울수록 변형과 응력이 정지 하중일 때보다 몇 배에서 수십 배까지 커집니다(공진).

5단계에서 넣은 하중을 흔들리는 하중의 크기(진폭)로 보고, 6단계에서 정한 진동수 범위 전체를 훑어 가장 불리한 진동수에서 강도와 피로(양방향 반복)를 판정합니다. 결과 화면의 곡선에서 진동수별 최대 응력을 보고, 다른 진동수를 눌러 그때의 모습을 볼 수 있습니다.

고유진동수를 구한 뒤 모드를 겹쳐 계산하며(모드 중첩), 빠진 높은 모드의 몫은 정적 보정으로 넣습니다. 열 조건·볼트 예압·강제 변위는 흔들리지 않는 조건이라 빠지고, 접촉은 붙어 있는 것으로 봅니다.", + "related": [ + "harmonic.damping", + "harmonic.range", + "analysis.modal" + ] + }, + "harmonic.damping": { + "title": "감쇠비", + "short": "진동이 스스로 잦아드는 정도입니다. 모르면 2 %(용접·볼트 조립 강구조의 흔한 값)를 쓰세요.", + "detail": "공진에서의 응답은 감쇠비에 거의 반비례합니다. 감쇠비 2 %면 공진 응답이 정지 하중의 약 25배, 1 %면 약 50배입니다.

대략적인 값: 한 덩어리로 깎은 금속 부품 0.5~1 %, 볼트·용접 조립 구조 2~5 %, 고무 마운트·마찰이 큰 구조 5~10 %. 확실하지 않으면 작은 값을 쓰는 쪽이 안전합니다." + }, + "harmonic.range": { + "title": "흔들리는 진동수", + "short": "하중이 흔들릴 수 있는 진동수 범위입니다. 최대를 '자동'으로 두면 구한 고유진동수들을 모두 덮습니다.", + "detail": "예: 회전수가 600~3000 rpm으로 바뀌는 모터라면 10~50 Hz(rpm ÷ 60)입니다. 이 범위 안의 가장 불리한 진동수에서 판정하므로, 범위가 고유진동수를 포함하면 공진 상태로 판정됩니다.

실제로 운전하지 않는 진동수까지 넓게 잡으면 불필요하게 불합격이 날 수 있습니다." + }, + "result.frequency": { + "title": "진동수", + "short": "진동 응답 결과를 어느 진동수에서 볼지 고릅니다. 판정은 '가장 불리'한 진동수 기준입니다.", + "detail": "'가장 불리'는 범위 안에서 응력이 강도에 가장 가까워지는 진동수, '○차 공진'은 고유진동수에서의 상태입니다. 아래 곡선을 눌러 다른 진동수를 고를 수도 있습니다.

응력·변형은 한 주기 동안 각 위치에서 가장 큰 값입니다." + }, + "result.response": { + "title": "응답 곡선", + "short": "진동수마다 모델 안의 가장 큰 응력입니다. 점선은 고유진동수, 빨간 점선은 강도입니다. 누르면 그 진동수를 봅니다.", + "detail": "봉우리는 공진입니다. 봉우리의 높이는 감쇠비에 반비례합니다. 운전 진동수가 봉우리에서 떨어져 있으면 응답이 크게 줄어듭니다.

세로축은 로그 눈금이라 한 칸이 10배입니다." + }, + "view.measure": { + "title": "측정", + "short": "면의 면적·구멍 지름·축과 두 점 사이 거리를 잽니다 (단축키 M).", + "detail": "켜 두고 면을 클릭하면 면적(압력 ↔ 힘 환산에 필요)과, 구멍·축이면 지름과 축 방향을 상태 표시줄에 보여 줍니다. 두 번째 점을 클릭하면 두 점 사이 거리와 X·Y·Z 차이를 보여 주고 선을 긋습니다. 세 번째 클릭은 새로 잽니다.

측정 중에는 클릭이 면을 선택하지 않습니다. 다시 누르면 꺼집니다." + }, + "result.compare": { + "title": "결과 비교", + "short": "지금 결과를 기준으로 정해 두고, 설계를 바꾼 뒤의 결과와 나란히 비교합니다.", + "detail": "'이 결과를 비교 기준으로'를 누른 뒤 두께·재료·하중 등을 바꿔 다시 해석하면, 판정 안전율·최대 응력·최대 변형을 기준과 지금 값으로 나란히 보여 줍니다.

메시가 똑같으면(형상·메시 등급을 바꾸지 않았을 때) 차이를 색으로 볼 수 있습니다: 지금 − 기준. '기준 결과를 화면에 보기'로 기준 결과를 다시 띄워 번갈아 볼 수 있습니다. 기준은 다른 모델을 열 때까지 남습니다." + }, + "fixture.symmetry": { + "title": "대칭면", + "short": "부품을 대칭면에서 잘라 절반(또는 1/4)만 계산할 때, 잘린 평면을 고르고 누르세요.", + "detail": "형상과 하중이 모두 대칭이면 절반만 모델링해도 응력·변형은 같고 계산은 훨씬 빠릅니다. 잘린 면은 그 면 안에서는 미끄러질 수 있지만 면을 뚫고 움직이지는 않으므로 미끄럼 지지로 만듭니다.

결과의 반력과 하중 합은 계산한 부분만의 값입니다(반 모델이면 전체의 1/2). 진동·좌굴은 대칭이 아닌 모양을 놓칠 수 있습니다." + }, + "fixture.template": { + "title": "조건 묶음", + "short": "지금의 고정·하중을 묶음으로 저장해 두었다가 다른 모델에 같은 종류의 면에 넣습니다.", + "detail": "면은 번호가 아니라 종류로 기억합니다: 구멍·축은 반지름, 평면은 방향과 면적. 불러오면 그와 같은 면 모두에 넣습니다(구멍 하나로 저장한 '볼트 구멍 고정'은 같은 크기 구멍 전부에). 맞는 면이 없는 항목은 빼고 알려 줍니다.

'자중'처럼 면이 없는 조건은 그대로 들어갑니다. 저장한 묶음은 이 컴퓨터의 사용자 데이터 폴더에 남습니다." } } diff --git a/src/kstruct/resources/i18n/en/core.json b/src/kstruct/resources/i18n/en/core.json index cc9fdbe..79c2bbc 100644 --- a/src/kstruct/resources/i18n/en/core.json +++ b/src/kstruct/resources/i18n/en/core.json @@ -45,7 +45,6 @@ "볼트 {n}개": "{n} bolt(s)", "볼트 구멍 면이 메시에 없습니다. 메시를 다시 만들어 주세요.": "The bolt hole face is not in the mesh. Please create the mesh again.", "볼트 체결 상태 계산 중": "Computing the bolted joint state", - "볼트가 있는 모델은 비선형(항복·큰 변형) 해석을 아직 지원하지 않습니다.": "Nonlinear analysis (yielding, large deformation) does not support bolts yet.", "볼트는 구멍(원통면)끼리만 연결할 수 있습니다.": "A bolt can only connect holes (cylindrical faces).", "부품 형상을 읽을 수 없습니다: {name}": "Cannot read the part geometry: {name}", "부품 형상을 저장할 수 없습니다: {name}": "Cannot save the part geometry: {name}", @@ -79,7 +78,6 @@ "이 버전의 KStruct에서 열 수 없는 프로젝트 파일입니다.": "This project file cannot be opened by this version of KStruct.", "이 하중으로는 좌굴이 생기지 않습니다(누르는 힘이 없음). 좌굴은 압축을 받는 가늘거나 얇은 부품에서 확인하세요.": "These loads cannot cause buckling (nothing is compressed). Check buckling on slender or thin parts under compression.", "접촉 상태 계산 중 (반복)": "Computing contact state (iterating)", - "접촉 연결이 있는 모델은 비선형(항복·큰 변형) 해석을 아직 지원하지 않습니다.": "Nonlinear analysis (yielding, large deformation) does not support contact connections yet.", "접촉·비선형·진동·좌굴 해석은 큰 모델에서 오래 걸립니다. ": "Contact, nonlinear, vibration and buckling analyses take long on large models. ", "접촉면이 서로 너무 멀리 떨어져 있습니다.": "The contact faces are too far apart.", "접촉할 면이 메시에 없습니다.": "The contact faces are not in the mesh.", @@ -116,5 +114,32 @@ "자중·원심력은 밀도에 비례합니다.": "Self-weight and centrifugal loads are proportional to the density.", "탄성 지지는 부품 강성과의 비율로 힘을 나눕니다.": "Elastic supports share the load in proportion to the part's stiffness.", "강제 변위로 생기는 응력은 탄성계수에 비례합니다.": "Stress from imposed displacements is proportional to the stiffness.", - "볼트와 부품의 강성 비율이 바뀝니다.": "The stiffness ratio of bolts and parts changes." + "볼트와 부품의 강성 비율이 바뀝니다.": "The stiffness ratio of bolts and parts changes.", + "진동시킬 하중이 없습니다. 5단계에서 하중을 넣어 주세요.": "There is no load to vibrate. Add loads in step 5.", + "정적 변형 계산 중": "Computing the static deflection", + "진동수 범위가 잘못되었습니다. 최대가 최소보다 커야 합니다.": "The frequency range is invalid: the upper end must be above the lower end.", + "응답 합성 중": "Combining the response", + "진동수별 응답 계산 중": "Computing the response per frequency", + "진동 응답(주파수 응답) 해석: 고유 모드 {m}개 중첩 + 나머지 모드의 정적 보정, 감쇠비 {z:.1f}%, {lo:,.1f}~{hi:,.1f} Hz를 {n}개 진동수로 계산. 응력·변형은 {f:,.1f} Hz에서 한 주기 동안의 최댓값이며 피로는 양방향 반복으로 판정": "Vibration (frequency) response: {m} natural modes superposed plus a static correction for the other modes, damping ratio {z:.1f}%, {lo:,.1f}-{hi:,.1f} Hz computed at {n} frequencies. Stresses and deflections are the largest over one cycle at {f:,.1f} Hz; fatigue is checked as fully reversed", + "판정 진동수": "Frequency judged", + "가장 불리": "Worst", + "{i}차 공진": "Resonance {i}", + "진동수별 응답": "Response per frequency", + "최대 변형 진폭": "Largest deflection amplitude", + "최대 응력 진폭": "Largest stress amplitude", + "정지 하중 대비": "Versus the load held still", + "진동 응답 유한요소해석(모드 중첩)": "vibration response finite element analysis (mode superposition)", + "진동 응답: 하중이 {lo:,.1f}~{hi:,.1f} Hz로 흔들릴 때 {f:,.1f} Hz의 상태입니다. 변형은 같은 하중을 가만히 걸 때의 약 {a:,.1f}배이고, 응력·변형은 한 주기 동안의 가장 큰 값입니다(양방향 반복으로 피로도 판정).": "Vibration response: the state at {f:,.1f} Hz while the loads vibrate at {lo:,.1f}-{hi:,.1f} Hz. The deflection is about {a:,.1f} times that under the same load held still; stresses and deflections are the largest over one cycle (fatigue checked as fully reversed).", + "{i}차 고유진동수 {fn:,.1f} Hz의 공진입니다. 공진 응답은 감쇠비(가정 {z:.1f}%)에 반비례해 실제 감쇠가 작으면 더 커집니다. 가진 진동수가 이 값의 ±20 % 밖에 있게 하거나 두께·리브로 고유진동수를 옮기면 응답이 크게 줄어듭니다.": "This is resonance at natural frequency {i}, {fn:,.1f} Hz. The resonant response is inversely proportional to the damping ratio (assumed {z:.1f}%) and is larger if the real damping is lower. Keeping the excitation more than ±20 % away from this value, or moving the natural frequency with thickness or ribs, reduces the response greatly.", + "강제 변위(움직이지 않는 지지로 봄)": "imposed displacements (taken as supports that hold still)", + "볼트 예압": "bolt preload", + "진동 응답 계산에서 빠진 조건: {items}. 흔들리는 하중만 계산합니다.": "Left out of the vibration response: {items}. Only the vibrating loads are computed.", + "진동 응답은 탄성계수와 밀도로 정해지는 고유진동수에 따라 달라집니다.": "A vibration response depends on the natural frequencies, which follow from the elastic modulus and the density.", + "마찰이 있는 접촉은 비선형(항복·큰 변형) 해석에서 아직 지원하지 않습니다. 마찰 계수를 0으로 하면 계산할 수 있습니다.": "Nonlinear analysis (yielding, large deformation) does not support contact with friction yet. With a friction coefficient of 0 it can be computed.", + "볼트 체결력만으로도 부품이 버티지 못합니다. 체결력이나 볼트 자리를 확인하세요.": "The parts cannot carry even the bolt tightening alone. Check the preload or the bolt seats.", + "{kind}, 면적 {area:,.2f} {unit}": "{kind}, area {area:,.2f} {unit}", + ", 지름 {d}": ", diameter {d}", + ", 축 방향 ({x:.3f}, {y:.3f}, {z:.3f}) · 축 위 점 {p}": ", axis direction ({x:.3f}, {y:.3f}, {z:.3f}) · point on the axis {p}", + ", 바깥 법선 ({x:.3f}, {y:.3f}, {z:.3f})": ", outward normal ({x:.3f}, {y:.3f}, {z:.3f})", + "거리 {d} (ΔX {dx}, ΔY {dy}, ΔZ {dz})": "Distance {d} (ΔX {dx}, ΔY {dy}, ΔZ {dz})" } diff --git a/src/kstruct/resources/i18n/en/main.json b/src/kstruct/resources/i18n/en/main.json index 6d010db..932668f 100644 --- a/src/kstruct/resources/i18n/en/main.json +++ b/src/kstruct/resources/i18n/en/main.json @@ -260,5 +260,53 @@ "이 재료로 확정": "Use this material", "다음": "Next", "그만 보기": "Close", - "시작하기": "Get started" + "시작하기": "Get started", + "흔들릴 하중이 없습니다 (열 조건은 진동시키지 않습니다)": "No loads to vibrate (thermal conditions do not vibrate)", + "가장 불리: {f:,.1f} Hz": "Worst: {f:,.1f} Hz", + "{i}차 공진: {f:,.1f} Hz": "Resonance {i}: {f:,.1f} Hz", + "운전 진동수: {f:,.1f} Hz": "Operating frequency: {f:,.1f} Hz", + "고른 진동수: {f:,.1f} Hz": "Chosen frequency: {f:,.1f} Hz", + "응답 곡선 (진동수별 최대 응력)": "Response curve (largest stress per frequency)", + "진동수 (Hz) · 세로: 최대 응력 ({unit}, 로그)": "Frequency (Hz) · vertical: largest stress ({unit}, log)", + "진동 응답 — 흔들리는 하중에 얼마나 떨리고 버틸까?": "Vibration response — how much will it shake under vibrating loads, and hold?", + "진동 응답 설정": "Vibration response settings", + "감쇠비": "Damping ratio", + "자동": "Auto", + "흔들리는 진동수": "Vibrating frequencies", + "단위나 수식도 입력할 수 있습니다 (예: 10 kN, 2 in, =1500*9.81)": "Units and arithmetic are accepted too (e.g. 10 kN, 2 in, =1500*9.81)", + "측정": "Measure", + "측정: 면을 클릭하면 면적·지름을, 두 점을 차례로 클릭하면 거리를 알려 줍니다.": "Measure: click a face for its area and diameter, two points in turn for their distance.", + "점 {n}: {face}": "Point {n}: {face}", + "결과 비교": "Compare results", + "이 결과를 비교 기준으로": "Use this result as the reference", + "기준과의 차이를 색으로 보기": "Show the difference from the reference in colour", + "기준 결과를 화면에 보기": "Show the reference result", + "이 결과를 비교 기준으로 정했습니다.": "This result is now the reference for comparison.", + "판정 안전율": "Governing safety factor", + "같은 메시라 차이를 색으로 볼 수 있습니다.": "Same mesh: the difference can be shown in colour.", + "메시가 달라(형상·메시 변경) 숫자만 비교합니다.": "The mesh differs (shape or mesh changed): only the numbers are compared.", + "기준: {label}": "Reference: {label}", + "기준": "Reference", + "지금": "Now", + "변화": "Change", + "기준: {title}": "Reference: {title}", + "차이 (지금 − 기준): {title}": "Difference (now − reference): {title}", + "색으로 본 차이: 최대 {d:.4g} {unit}": "Difference shown in colour: largest {d:.4g} {unit}", + "차이 없음: 두 결과가 같습니다(최대 차이 0).": "No difference: the two results are the same (largest difference 0).", + "대칭면 (미끄럼 지지): {faces}": "Plane of symmetry (roller): {faces}", + "대칭면을 지정해 부품의 일부만 계산했습니다. 응력·변형·안전율은 전체 부품과 같지만, 반력과 하중 합은 계산한 부분만의 값입니다(반 모델이면 전체의 1/2, 1/4 모델이면 1/4). 하중과 형상이 대칭일 때만 맞는 방법입니다.": "Planes of symmetry are set, so only part of the component was computed. Stresses, deflections and safety factors are those of the whole part, but reactions and load sums are for the computed part only (1/2 of the whole for a half model, 1/4 for a quarter model). This holds only when loads and shape are symmetric.", + "선택한 평면을 대칭면으로": "Make the selected planes planes of symmetry", + "3D 화면에서 대칭면(잘린 평면)을 먼저 고르세요.": "First select the plane(s) of symmetry (the cut faces) in the 3D view.", + "대칭면은 평면이어야 합니다.": "A plane of symmetry must be a flat face.", + "조건 묶음 저장…": "Save template…", + "조건 묶음 불러오기…": "Apply template…", + "저장할 고정이나 하중이 없습니다.": "There are no fixtures or loads to save.", + "조건 묶음 저장": "Save template", + "묶음 이름 (예: 볼트 구멍 고정)": "Template name (e.g. bolt holes fixed)", + "조건 묶음 '{name}'을 저장했습니다.": "Saved template '{name}'.", + "조건 묶음 불러오기": "Apply template", + "이 모델에 넣을 묶음": "Template to put on this model", + "'{name}': 고정 {f}개, 하중 {n}개를 넣었습니다.": "'{name}': added {f} fixture(s) and {n} load(s).", + " 맞는 면을 찾지 못한 {m}개는 뺐습니다.": " {m} item(s) found no matching face and were left out.", + "자중 (중력 −Z)": "Self-weight (gravity −Z)" } diff --git a/src/kstruct/resources/i18n/en/steps.json b/src/kstruct/resources/i18n/en/steps.json index 8a48ea4..8cbee2b 100644 --- a/src/kstruct/resources/i18n/en/steps.json +++ b/src/kstruct/resources/i18n/en/steps.json @@ -209,5 +209,6 @@ "회전 속도": "Speed", "회전축": "Axis", "회전축을 정할 수 없습니다. 축이나 구멍의 원통면을 고르거나 '회전축'에서 X·Y·Z 축을 지정하세요.": "Cannot determine the rotation axis. Select the cylindrical face of a shaft or hole, or choose an X, Y or Z axis under 'Axis'.", - "힘": "Force" + "힘": "Force", + "피로 검토 설정": "Fatigue check settings" } diff --git a/src/kstruct/resources/i18n/en/summary.json b/src/kstruct/resources/i18n/en/summary.json index 38fa5e5..500b5c3 100644 --- a/src/kstruct/resources/i18n/en/summary.json +++ b/src/kstruct/resources/i18n/en/summary.json @@ -111,5 +111,17 @@ "한 번의 하중은 견디지만, 반복되면 피로로 균열이 생길 수 있습니다(예상 수명 {life}).": "It holds a single load, but repeated loading may cause fatigue cracks (expected life {life}).", "한 번의 하중은 충분히 견디지만 반복 하중에 대한 여유가 부족합니다.": "It easily holds a single load, but the margin for repeated loading is too small.", "항복": "yielding", - "힘 {mag:,.1f} {unit} ({fx:+.0f}, {fy:+.0f}, {fz:+.0f}): {faces}": "Force {mag:,.1f} {unit} ({fx:+.0f}, {fy:+.0f}, {fz:+.0f}): {faces}" + "힘 {mag:,.1f} {unit} ({fx:+.0f}, {fy:+.0f}, {fz:+.0f}): {faces}": "Force {mag:,.1f} {unit} ({fx:+.0f}, {fy:+.0f}, {fz:+.0f}): {faces}", + "{name}: 응력이 가장 큰 곳은 필렛 없는 오목 모서리입니다. 모서리에 필렛(둥글림)을 주는 것이 가장 효과적입니다. 반지름이 클수록 응력이 낮아지며, 필렛을 넣은 뒤 다시 해석하면 그 자리의 실제 응력을 볼 수 있습니다.": "{name}: the highest stress is at a sharp concave corner without a fillet. Rounding that corner (a fillet) is the most effective change. The larger the radius, the lower the stress; analyse again with the fillet to see the real stress there.", + "{name}: 판정 위치가 구멍(지름 {d}) 가장자리입니다. 구멍 둘레에는 응력이 몰립니다(넓은 판을 당길 때 이론적으로 평균의 3배). 구멍을 응력이 낮은 곳으로 옮기거나, 가장자리까지의 거리를 늘리거나, 구멍 둘레를 두껍게(보스) 하세요.": "{name}: the verdict is taken at the edge of a hole (diameter {d}). Stress gathers around holes (in a wide plate under tension, theoretically 3 times the average). Move the hole to where the stress is lower, increase its distance from the edge, or thicken the material around it (a boss).", + "{name}: 판정 위치가 필렛(반지름 {r})입니다. 반지름을 키우면 응력이 낮아집니다.": "{name}: the verdict is taken at a fillet (radius {r}). A larger radius lowers the stress.", + "여유가 큽니다(안전율 {fos:.1f}, 권장 {target:.1f}). 하중이 확실하다면 가장 약한 곳의 벽(두께 {t})을 약 {b}까지 줄여도 권장값을 만족합니다(굽힘을 받는 벽 기준의 선형 비례 추정이며, 당김·누름을 받는 벽이면 더 얇아도 됩니다). 줄인 뒤 다시 해석해 확인하세요.": "There is plenty of margin (safety factor {fos:.1f}, recommended {target:.1f}). If the loads are certain, the wall at the weakest spot (thickness {t}) can be thinned to about {b} and still meet the recommended value (a linear scaling estimate for a wall in bending; a wall pulled or pushed can be thinner still). Analyse again after thinning to confirm.", + "접촉·예압·열응력·강제 변위가 있어 응력이 하중에 정비례하지 않으므로, 두께·하중을 몇 배 바꿀지는 바꾼 뒤 다시 해석해 확인하세요.": "With contact, preload, thermal stress or imposed displacements the stress is not proportional to the load, so check any change of thickness or load by analysing again.", + "하중을 지금의 {k:.2f}배 이하로 줄이면 권장 {kind}({target:.1f})을 만족합니다(선형 해석이라 응력은 하중에 정비례).": "Reducing the load to {k:.2f} times the present one or less meets the recommendation ({kind} ≥ {target:.1f}); in a linear analysis the stress is proportional to the load.", + "흔들리는 하중의 크기를 지금의 {k:.2f}배 이하로 줄이면 권장 {kind}({target:.1f})을 만족합니다(응답은 하중 크기에 정비례).": "Reducing the vibrating load to {k:.2f} times the present amplitude or less meets the recommendation ({kind} ≥ {target:.1f}); the response is proportional to the load amplitude.", + "판정 위치의 벽 두께는 {t}입니다. 그 벽이 굽힘을 받는다면 약 {b}(×{fb:.2f}), 당김·누름을 받는다면 약 {m}(×{fm:.2f})로 두껍게 하면 권장값을 만족합니다(선형 비례 추정, 두께 외 형상은 그대로일 때). 리브를 더하는 것도 방법입니다.": "The wall at the verdict location is {t} thick. Thickening it to about {b} (×{fb:.2f}) if it bends, or to about {m} (×{fm:.2f}) if it is pulled or pushed, meets the recommended value (a linear scaling estimate, with the rest of the shape unchanged). Adding ribs is another way.", + "재료만 바꾼다면 {strength} {need} 이상이 필요합니다(지금 {now}). 목록에 그런 재료가 없어 형상 변경을 권합니다.": "Changing only the material would need {strength} ≥ {need} (now {now}). No material in the list has that, so a change of shape is recommended.", + "재료만 바꾼다면 {strength} {need} 이상이 필요합니다(지금 {now}). 같은 응력 분포로 바로 쓸 수 있는 후보: {names}. 결과 화면의 '재료 바꿔 보기'로 바로 확인할 수 있습니다.": "Changing only the material would need {strength} ≥ {need} (now {now}). Candidates that keep the same stress distribution: {names}. Check them at once with 'Try another material' in the results.", + "개선 방법": "How to improve", + "개선 방법": "How to improve" } diff --git a/src/kstruct/templates.py b/src/kstruct/templates.py new file mode 100644 index 0000000..ac9533c --- /dev/null +++ b/src/kstruct/templates.py @@ -0,0 +1,150 @@ +"""Condition templates: fixtures and loads saved without the model, and put back on +another model's faces of the same kind. + +A face is remembered by what it is, not by its index: a cylinder (hole or shaft) by its +radius, a plane by its outward normal and area. Applying a template attaches each +condition to every visible face that matches (a hole fixture saved from one bolt hole +lands on all holes of that size). Conditions without faces (gravity, a uniform +temperature) are copied as they are. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import numpy as np + +from kstruct.geometry.face_info import SIMILAR_TOLERANCE, face_info, outward_normal +from kstruct.geometry.tessellate import faces_of +from kstruct.i18n import N_ +from kstruct.model import FaceRef, Fixture, FixtureKind, Load, LoadKind, Project + +NORMAL_TOLERANCE = 0.02 # rad (≈1°) between plane normals still called the same +VERSION = 1 + +# offered on every model (names are translated when shown) +BUILT_IN = { + N_("자중 (중력 −Z)"): { + "version": VERSION, + "fixtures": [], + "loads": [{"kind": "gravity", "faces": [], "vector": [0.0, 0.0, -9810.0]}], + }, +} + + +def signature(project: Project, ref: FaceRef) -> dict: + face = faces_of(project.part(ref.part_id).shape)[ref.face_index] + info = face_info(face) + if info.radius is not None: + return {"kind": "cylinder", "radius": info.radius} + normal = outward_normal(face) + if normal is not None: + return {"kind": "plane", "normal": list(normal), "area": info.area} + return {"kind": "other", "area": info.area} + + +def _matches(project: Project, ref: FaceRef, sig: dict) -> bool: + mine = signature(project, ref) + if mine["kind"] != sig["kind"]: + return False + if sig["kind"] == "cylinder": + return abs(mine["radius"] - sig["radius"]) <= SIMILAR_TOLERANCE * sig["radius"] + if abs(mine["area"] - sig["area"]) > SIMILAR_TOLERANCE * sig["area"]: + return False + if sig["kind"] == "plane": + cos = float(np.dot(mine["normal"], sig["normal"])) + return cos >= np.cos(NORMAL_TOLERANCE) + return True + + +def matching_faces(project: Project, sigs: list[dict]) -> list[FaceRef]: + """Every visible face matching any of the signatures (each once).""" + out = [] + for part in project.parts: + if not part.visible: + continue + for i in range(len(faces_of(part.shape))): + ref = FaceRef(part.id, i) + if any(_matches(project, ref, s) for s in sigs): + out.append(ref) + return out + + +def make_template(project: Project, fixtures: list[Fixture], loads: list[Load]) -> dict: + return { + "version": VERSION, + "fixtures": [ + { + "kind": f.kind.value, + "faces": [signature(project, r) for r in f.faces], + "displacement": list(f.displacement), + "stiffness": f.stiffness, + "symmetry": f.symmetry, + } + for f in fixtures + ], + "loads": [ + { + "kind": ld.kind.value, + "faces": [signature(project, r) for r in ld.faces], + "vector": list(ld.vector), + "magnitude": ld.magnitude, + "ambient": ld.ambient, + "point": list(ld.point) if ld.point is not None else None, + } + for ld in loads + ], + } + + +def apply_template(project: Project, template: dict) -> tuple[list[Fixture], list[Load], int]: + """The template's conditions on this model's matching faces, and how many found no + face (left out).""" + fixtures, loads, missed = [], [], 0 + for f in template.get("fixtures", []): + faces = matching_faces(project, f["faces"]) + if not faces: + missed += 1 + continue + fixtures.append( + Fixture( + FixtureKind(f["kind"]), + faces, + tuple(None if d is None else float(d) for d in f.get("displacement", [None] * 3)), + float(f.get("stiffness", 0.0)), + bool(f.get("symmetry", False)), + ) + ) + for ld in template.get("loads", []): + faces = matching_faces(project, ld["faces"]) if ld["faces"] else [] + if ld["faces"] and not faces: + missed += 1 + continue + loads.append( + Load( + LoadKind(ld["kind"]), + faces, + tuple(ld.get("vector", (0.0, 0.0, 0.0))), + float(ld.get("magnitude", 0.0)), + float(ld.get("ambient", 20.0)), + tuple(ld["point"]) if ld.get("point") is not None else None, + ) + ) + return fixtures, loads, missed + + +def load_library(path: Path) -> dict[str, dict]: + try: + data = json.loads(Path(path).read_text("utf-8")) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +def save_library(path: Path, library: dict[str, dict]) -> None: + path = Path(path) + path.parent.mkdir(parents=True, exist_ok=True) + tmp = path.with_suffix(".part") + tmp.write_text(json.dumps(library, ensure_ascii=False, indent=1), "utf-8") + tmp.replace(path) diff --git a/src/kstruct/ui/dialogs.py b/src/kstruct/ui/dialogs.py index 39581f3..e69913e 100644 --- a/src/kstruct/ui/dialogs.py +++ b/src/kstruct/ui/dialogs.py @@ -14,7 +14,6 @@ QComboBox, QDialog, QDialogButtonBox, - QDoubleSpinBox, QFileDialog, QFormLayout, QLabel, @@ -31,6 +30,7 @@ from kstruct.model import Material from kstruct.paths import environment_summary, log_path, notices_text, user_materials_path from kstruct.ui.help import with_help +from kstruct.ui.unit_spin import UnitSpinBox from kstruct.units import quantity log = logging.getLogger(__name__) @@ -67,7 +67,7 @@ def __init__(self, base: Material | None, system: str, parent: QWidget | None = form.addRow(tr("종류"), self.category) def spin(value, lo, hi, decimals, suffix): - box = QDoubleSpinBox() + box = UnitSpinBox() box.setRange(lo, hi) box.setDecimals(decimals) box.setSuffix(f" {suffix}") diff --git a/src/kstruct/ui/main_window.py b/src/kstruct/ui/main_window.py index 6d1dc69..4dfb777 100644 --- a/src/kstruct/ui/main_window.py +++ b/src/kstruct/ui/main_window.py @@ -2,6 +2,7 @@ from __future__ import annotations +import html import json import logging import sys @@ -19,6 +20,7 @@ QFileDialog, QFrame, QHBoxLayout, + QInputDialog, QLabel, QListWidgetItem, QMainWindow, @@ -37,6 +39,7 @@ from kstruct import diagnose, i18n, meshcheck, standards, whatif from kstruct.fem import ConstraintError, MeshingError, SolverError, generate_mesh from kstruct.fem.buckling import BucklingResult, solve_buckling +from kstruct.fem.harmonic import solve_harmonic from kstruct.fem.mesh import FEMesh from kstruct.fem.modal import ModalResult, solve_modal from kstruct.fem.nonlinear import unsupported as nonlinear_unsupported @@ -201,6 +204,10 @@ def __init__(self) -> None: self.overview: CaseOverview | None = None # key numbers of the previous strength run, for the "compared with last time" line self.previous: dict | None = None + # result kept for comparison: (label, mesh, result, summary) and what is shown + self.reference: tuple | None = None + self.compare_view: str | None = None # None, "diff" (now − reference) or "ref" + self.compare_difference = (0.0, "") # largest |now − reference| shown, unit self._trial_material: str | None = None # material the result now shows, if tried self._envelope: tuple | None = None # (result, summary) of the worst-of-all-cases view self._mesh_check_line: str | None = None # outcome of the last mesh check @@ -1012,6 +1019,7 @@ def _set_project(self, project: Project, path: Path | None = None) -> None: self.mesh = self.result = self.summary = None self.case_results = self.overview = None self.previous = None + self.reference, self.compare_view = None, None self.viewer.load_project(project) for part in project.parts: if not part.visible: @@ -1291,7 +1299,7 @@ def readiness(self) -> list[tuple[bool, str]]: ), ] thermal_bcs = [ld for ld in p.loads if ld.kind in THERMAL_LOADS] - if p.analysis in (AnalysisKind.STATIC, AnalysisKind.BUCKLING): + if p.analysis in (AnalysisKind.STATIC, AnalysisKind.BUCKLING, AnalysisKind.HARMONIC): checks.append( ( bool(p.fixtures), @@ -1317,7 +1325,12 @@ def readiness(self) -> list[tuple[bool, str]]: text = tr("하중: {n}개", n=len(p.loads)) if p.loads else tr("하중이 없습니다") if len(p.cases) > 1: text += tr(" ('{case}' 케이스만 사용)", case=p.case.name) - checks.append((bool(mech or thermal_bcs), text)) + if p.analysis == AnalysisKind.HARMONIC: + if not mech: + text = tr("흔들릴 하중이 없습니다 (열 조건은 진동시키지 않습니다)") + checks.append((bool(mech), text)) + else: + checks.append((bool(mech or thermal_bcs), text)) elif p.analysis == AnalysisKind.MODAL: checks.append( ( @@ -1457,6 +1470,8 @@ def job(progress): return m, solve_thermal(project, m, materials, progress) if kind == AnalysisKind.BUCKLING: return m, solve_buckling(project, m, materials, project.n_modes, progress) + if kind == AnalysisKind.HARMONIC: + return m, solve_harmonic(project, m, materials, progress) return m, solve_cases(project, m, materials, progress) def done(value): @@ -1489,6 +1504,9 @@ def done(value): elif isinstance(self.result, BucklingResult): pack = standards.effective_pack(project) self.summary = summarize_buckling(project, self.result, pack) + else: # vibration response: the worst state over the sweep + self.case_results = self.overview = None + self.summary = summarize(project, self.result, standards.effective_pack(project)) panel.set_progress(None, "") self._configure_result_panel() self._update_nav() @@ -1549,6 +1567,8 @@ def _configure_result_panel(self) -> None: panel.set_fields(_translated(fields)) panel.set_modes(None) panel.animate.setChecked(False) + self._configure_frequencies(panel) + self._configure_compare(panel) if self.case_results and len(self.case_results) > 1: labels = [ f"{name} — {VERDICT_STYLE[s.verdict][0]} {s.governing_fos:.2f}" @@ -1564,11 +1584,240 @@ def _configure_result_panel(self) -> None: panel.scale.setEnabled(has_shape) panel.animate.setEnabled(has_shape) self._fill_material_trial(panel) - linear = isinstance(r, StaticResult) and r.nonlinear is None + linear = isinstance(r, StaticResult) and r.nonlinear is None and r.harmonic is None panel.mesh_check_box.setVisible(linear and not self.showing_envelope) panel.mesh_check.setEnabled(not self._busy) panel.mesh_check_text.setText(self._mesh_check_line or "") + def _configure_frequencies(self, panel) -> None: + """Vibration response: the frequency selector and the response curve.""" + r = self.result + h = r.harmonic if isinstance(r, StaticResult) else None + if h is None: + panel.set_frequencies(None) + return + lo, hi = h.range + options = [(tr("가장 불리: {f:,.1f} Hz", f=h.governing), h.governing)] + for i, fn in enumerate(h.natural): + if lo <= fn <= hi: + options.append((tr("{i}차 공진: {f:,.1f} Hz", i=i + 1, f=fn), float(fn))) + op = self.project.operating_frequency + if op > 0 and lo <= op <= hi: + options.append((tr("운전 진동수: {f:,.1f} Hz", f=op), op)) + shown = r.harmonic_frequency + current = next((i for i, (_, f) in enumerate(options) if abs(f - shown) < 1e-9), None) + if current is None: + options.append((tr("고른 진동수: {f:,.1f} Hz", f=shown), shown)) + current = len(options) - 1 + panel.set_frequencies(options, current) + stress = quantity(system_of(self.project), "stress") + capacity = min( + m.yield_strength if m.ductile else m.tensile_strength for m in r.materials.values() + ) + panel.curve.set_data( + h.frequencies, + stress.show(h.stress), + h.peaks(), + stress.unit, + stress.show(capacity), + ) + panel.curve.set_selected(shown) + + def select_frequency(self, freq: float) -> None: + """Result panel: show the vibration response at another frequency.""" + r = self.result + h = r.harmonic if isinstance(r, StaticResult) else None + if h is None or self._busy: + return + lo, hi = h.range + freq = min(max(float(freq), lo), hi) + if abs(freq - r.harmonic_frequency) < 1e-9: + return + project = active_project(self.project) + self.result = h.state(freq) + self.summary = summarize(project, self.result, standards.effective_pack(project)) + self._configure_result_panel() + self.show_result() + + # --- condition templates ------------------------------------------------------------- + + def save_template(self, name: str | None = None) -> None: + """Keep the fixtures and the active case's loads as a named template.""" + from kstruct import paths, templates + + p = self.project + if p is None or not (p.fixtures or p.loads): + self.warn(tr("저장할 고정이나 하중이 없습니다.")) + return + if name is None: + name, ok = QInputDialog.getText( + self, tr("조건 묶음 저장"), tr("묶음 이름 (예: 볼트 구멍 고정)") + ) + if not ok or not name.strip(): + return + library = templates.load_library(paths.templates_path()) + library[name.strip()] = templates.make_template(p, p.fixtures, p.loads) + templates.save_library(paths.templates_path(), library) + self.statusBar().showMessage( + tr("조건 묶음 '{name}'을 저장했습니다.", name=name.strip()), 5000 + ) + + def template_names(self) -> dict[str, dict]: + """Shown name -> template: the built-in ones first, then the saved ones.""" + from kstruct import paths, templates + + out = {tr(k): v for k, v in templates.BUILT_IN.items()} + out.update(templates.load_library(paths.templates_path())) + return out + + def choose_template(self) -> None: + if self.project is None: + return + names = list(self.template_names()) + name, ok = QInputDialog.getItem( + self, tr("조건 묶음 불러오기"), tr("이 모델에 넣을 묶음"), names, 0, False + ) + if ok and name: + self.apply_template(name) + + def apply_template(self, name: str) -> tuple[int, int, int]: + """Add a template's fixtures and loads on this model's matching faces.""" + from kstruct import templates + + template = self.template_names().get(name) + if template is None or self.project is None: + return 0, 0, 0 + fixtures, loads, missed = templates.apply_template(self.project, template) + self.project.fixtures.extend(fixtures) + self.project.loads.extend(loads) + self._project_changed() + for step in (STEP_FIXTURE, STEP_LOAD): + self.panels[step].refresh() + text = tr( + "'{name}': 고정 {f}개, 하중 {n}개를 넣었습니다.", + name=name, + f=len(fixtures), + n=len(loads), + ) + if missed: + text += tr(" 맞는 면을 찾지 못한 {m}개는 뺐습니다.", m=missed) + self.statusBar().showMessage(text, 8000) + return len(fixtures), len(loads), missed + + # --- comparing with a reference result ---------------------------------------------- + + def pin_reference(self) -> None: + """Keep the shown strength result as the reference the next ones are compared + with (side by side numbers; colours of the difference on the same mesh).""" + r = self.result + if not isinstance(r, StaticResult) or not isinstance(self.summary, Summary): + return + label = (self._key_numbers() or {}).get("label", "") + self.reference = (label, self.mesh, r, self.summary) + self.compare_view = None + self._configure_compare(self.panels[STEP_RESULT]) + self.show_result() + self.statusBar().showMessage(tr("이 결과를 비교 기준으로 정했습니다."), 5000) + + def same_mesh_as_reference(self) -> bool: + if self.reference is None or self.mesh is None: + return False + ref = self.reference[1] + return ( + ref is self.mesh + or ref.nodes.shape == self.mesh.nodes.shape + and ref.tets.shape == self.mesh.tets.shape + and np.array_equal(ref.nodes, self.mesh.nodes) + and np.array_equal(ref.tets, self.mesh.tets) + ) + + def set_compare_view(self, view: str | None) -> None: + if view == "diff" and not self.same_mesh_as_reference(): + view = None + if view == "ref" and self.reference is None: + view = None + self.compare_view = view + self._configure_compare(self.panels[STEP_RESULT]) + self.show_result() + + def _configure_compare(self, panel) -> None: + r = self.result + strength = isinstance(r, StaticResult) and isinstance(self.summary, Summary) + panel.compare_box.setVisible(strength) + has_ref = self.reference is not None and strength + same = has_ref and self.same_mesh_as_reference() + if not same and self.compare_view == "diff" or not has_ref: + self.compare_view = None + for box, view, enabled in ( + (panel.compare_diff, "diff", same), + (panel.compare_ref, "ref", has_ref), + ): + box.blockSignals(True) + box.setChecked(self.compare_view == view) + box.setEnabled(enabled) + box.setVisible(has_ref) + box.blockSignals(False) + panel.compare_text.setText(self._compare_html(same) if has_ref else "") + + def _compare_html(self, same_mesh: bool) -> str: + """Reference and current key numbers side by side.""" + label, _, _, ref = self.reference + now = self.summary + us = system_of(self.project) + + def change(a, b): + return f"{(b - a) / a * 100:+.1f}%" if a else "" + + rows = [ + ( + tr("판정 안전율"), + f"{ref.governing_fos:.2f}", + f"{now.governing_fos:.2f}", + change(ref.governing_fos, now.governing_fos), + ), + ( + tr("최대 응력"), + fmt(us, "stress", max(p.max_stress for p in ref.parts), ",.1f"), + fmt(us, "stress", max(p.max_stress for p in now.parts), ",.1f"), + change(max(p.max_stress for p in ref.parts), max(p.max_stress for p in now.parts)), + ), + ( + tr("최대 변형"), + fmt(us, "length", ref.max_disp), + fmt(us, "length", now.max_disp), + change(ref.max_disp, now.max_disp), + ), + ] + cells = "".join( + f"{name}{a}{b}" + f"{d}" + for name, a, b, d in rows + ) + note = ( + tr("같은 메시라 차이를 색으로 볼 수 있습니다.") + if same_mesh + else tr("메시가 달라(형상·메시 변경) 숫자만 비교합니다.") + ) + return ( + tr("기준: {label}", label=html.escape(label)) + + "" + + f"" + + f"" + + cells + + "
{tr('기준')}{tr('지금')}{tr('변화')}
" + + note + ) + + def _with_reference(self, fn): + """Run fn with the reference result standing in for the current one.""" + _, mesh, result, summary = self.reference + saved = self.mesh, self.result, self.summary + self.mesh, self.result, self.summary = mesh, result, summary + try: + return fn() + finally: + self.mesh, self.result, self.summary = saved + def check_mesh(self) -> None: """Solve the shown load case once more on the next finer mesh and report how much the governing safety factor and the largest displacement moved (meshcheck.py).""" @@ -1835,6 +2084,30 @@ def _displacement(self) -> np.ndarray: return r.displacement def result_field(self, key: str) -> ResultField: + """The field to show, in display units; with a reference result pinned, the + reference's field or the difference (now − reference) on the same mesh.""" + if self.compare_view == "diff" and self.same_mesh_as_reference(): + now = self._display_field(key) + ref = self._with_reference(lambda: self._display_field(key)) + diff = now.values - ref.values # in display units: a °F offset cancels + lim = float(np.abs(diff).max()) + field = ResultField( + diff, + tr("차이 (지금 − 기준): {title}", title=now.title), + "coolwarm", + (-lim, lim) if lim > 0 else (-1.0, 1.0), + now.unit, + ) + field.extreme = "both" if lim > 0 else "none" + self.compare_difference = (lim, now.unit) + return field + if self.compare_view == "ref" and self.reference is not None: + field = self._with_reference(lambda: self._display_field(key)) + field.title = tr("기준: {title}", title=field.title) + return field + return self._display_field(key) + + def _display_field(self, key: str) -> ResultField: field = self._result_field_internal(key) # the end worth pointing at: the weakest spot for safety factors and life, both # ends for signed values, else the largest @@ -1983,9 +2256,29 @@ def show_result(self) -> None: normal = np.zeros(3) normal[axis] = -1.0 # keep the lower side, look at the cut face clip = (normal, origin) + if self.compare_view == "diff": + lim, unit = self.compare_difference + panel.compare_text.setText( + self._compare_html(True) + + "
" + + ( + tr("색으로 본 차이: 최대 {d:.4g} {unit}", d=lim, unit=unit) + if lim > 0 + else tr("차이 없음: 두 결과가 같습니다(최대 차이 0).") + ) + ) + mesh, displacement = self.mesh, self._displacement() + if self.compare_view == "ref" and self.reference is not None: + mesh, displacement, scale = self._with_reference( + lambda: ( + self.mesh, + self._displacement(), + self.deformation_scale(panel.scale_key()), + ) + ) self.viewer.show_result( - self.mesh, - self._displacement(), + mesh, + displacement, field, scale, symmetric=isinstance(self.result, (ModalResult, BucklingResult)), @@ -2127,6 +2420,11 @@ def _fill_summary(self, panel: steps.ResultStep) -> None: tref=self.project.reference_temperature, ) ) + advice = getattr(s, "advice", None) + if advice: + lines.append( + tr("개선 방법") + "".join(f"
 • {html.escape(a)}" for a in advice) + ) for note in s.notes: lines.append(f"※ {note}") panel.summary.setText("

".join(lines)) @@ -2225,6 +2523,8 @@ def capture_result_images(self) -> list[tuple[str, bytes]]: panel.mode.blockSignals(False) self.show_result() self.viewer.set_animated(animated) + if isinstance(r, StaticResult) and r.harmonic is not None: + images.insert(0, (tr("응답 곡선 (진동수별 최대 응력)"), panel.curve.to_png())) return images # --- dialogs --------------------------------------------------------------------- diff --git a/src/kstruct/ui/response_curve.py b/src/kstruct/ui/response_curve.py new file mode 100644 index 0000000..93c744a --- /dev/null +++ b/src/kstruct/ui/response_curve.py @@ -0,0 +1,175 @@ +"""Frequency response curve of a vibration (harmonic) result: the largest stress in the +model against the excitation frequency, natural frequencies as dashed lines and the +frequency shown in the 3D view as a solid one. Clicking picks a frequency.""" + +from __future__ import annotations + +import numpy as np +from PySide6.QtCore import QPointF, QRectF, Qt, Signal +from PySide6.QtGui import QColor, QPainter, QPainterPath, QPen +from PySide6.QtWidgets import QSizePolicy, QWidget + +from kstruct.i18n import tr +from kstruct.ui import theme + +PAD_LEFT, PAD_RIGHT, PAD_TOP, PAD_BOTTOM = 46, 10, 10, 30 + + +class ResponseCurve(QWidget): + picked = Signal(float) # Hz + + def __init__(self, parent=None) -> None: + super().__init__(parent) + self.setMinimumHeight(170) + self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Fixed) + self.setCursor(Qt.CursorShape.CrossCursor) + self.freqs = np.zeros(0) + self.values = np.zeros(0) + self.natural: list[float] = [] + self.selected: float | None = None + self.unit = "" + self.limit: float | None = None # strength line (same unit as values) + self.colours: theme.Theme | None = None # None: the current theme + + def set_data(self, freqs, values, natural, unit: str, limit: float | None = None) -> None: + self.freqs, self.values = np.asarray(freqs, float), np.asarray(values, float) + self.natural, self.unit, self.limit = list(natural), unit, limit + self.update() + + def set_selected(self, freq: float | None) -> None: + self.selected = freq + self.update() + + def sizeHint(self): # noqa: N802 (Qt override) + size = super().sizeHint() + size.setHeight(170) + return size + + # --- geometry ------------------------------------------------------------------- + + def _plot_rect(self) -> QRectF: + return QRectF( + PAD_LEFT, + PAD_TOP, + max(10, self.width() - PAD_LEFT - PAD_RIGHT), + max(10, self.height() - PAD_TOP - PAD_BOTTOM), + ) + + def _y_range(self) -> tuple[float, float]: + """Log axis bounds (decades) around the data and the strength line.""" + values = self.values[self.values > 0] + if len(values) == 0: + return 0.0, 1.0 + lo, hi = np.log10(values.min()), np.log10(values.max()) + if self.limit: + hi = max(hi, np.log10(self.limit)) + lo, hi = np.floor(lo), np.ceil(hi) + return lo, max(hi, lo + 1) + + def _x(self, f: float, rect: QRectF) -> float: + f0, f1 = self.freqs[0], self.freqs[-1] + return rect.left() + (f - f0) / (f1 - f0 or 1.0) * rect.width() + + def _y(self, v: float, rect: QRectF, lo: float, hi: float) -> float: + t = (np.log10(max(v, 10**lo)) - lo) / (hi - lo) + return rect.bottom() - t * rect.height() + + # --- painting ------------------------------------------------------------------- + + def paintEvent(self, _event) -> None: # noqa: N802 (Qt override) + t = self.colours or theme.current() + p = QPainter(self) + p.setRenderHint(QPainter.RenderHint.Antialiasing) + p.fillRect(self.rect(), QColor(t.surface)) + rect = self._plot_rect() + p.setPen(QPen(QColor(t.border), 1)) + p.drawRect(rect) + if len(self.freqs) < 2: + p.end() + return + lo, hi = self._y_range() + font = theme.weighted(p.font(), False) + font.setPointSizeF(max(7.0, font.pointSizeF() * 0.85)) + p.setFont(font) + muted = QColor(t.muted) + + # decades on the stress axis + for d in range(int(lo), int(hi) + 1): + y = self._y(10.0**d, rect, lo, hi) + p.setPen(QPen(QColor(t.border), 1, Qt.PenStyle.DotLine)) + p.drawLine(QPointF(rect.left(), y), QPointF(rect.right(), y)) + p.setPen(muted) + p.drawText( + QRectF(0, y - 8, PAD_LEFT - 4, 16), + Qt.AlignmentFlag.AlignRight | Qt.AlignmentFlag.AlignVCenter, + f"{10.0**d:g}", + ) + # frequency ticks at the ends and the middle + # the end labels grow inwards so they are never cut off + ticks = ( + (self.freqs[0], 0, Qt.AlignmentFlag.AlignLeft), + ((self.freqs[0] + self.freqs[-1]) / 2, -40, Qt.AlignmentFlag.AlignHCenter), + (self.freqs[-1], -80, Qt.AlignmentFlag.AlignRight), + ) + for f, shift, align in ticks: + x = self._x(f, rect) + p.drawText(QRectF(x + shift, rect.bottom() + 2, 80, 14), align, f"{f:,.0f}") + p.drawText( + QRectF(rect.left(), rect.bottom() + 14, rect.width(), 14), + Qt.AlignmentFlag.AlignHCenter, + tr("진동수 (Hz) · 세로: 최대 응력 ({unit}, 로그)", unit=self.unit), + ) + # natural frequencies + p.setPen(QPen(muted, 1, Qt.PenStyle.DashLine)) + for f in self.natural: + if self.freqs[0] <= f <= self.freqs[-1]: + x = self._x(f, rect) + p.drawLine(QPointF(x, rect.top()), QPointF(x, rect.bottom())) + # strength + if self.limit: + y = self._y(self.limit, rect, lo, hi) + p.setPen(QPen(QColor(t.fail), 1, Qt.PenStyle.DashLine)) + p.drawLine(QPointF(rect.left(), y), QPointF(rect.right(), y)) + # the curve + path = QPainterPath() + for i, (f, v) in enumerate(zip(self.freqs, self.values, strict=True)): + point = QPointF(self._x(f, rect), self._y(v, rect, lo, hi)) + path.moveTo(point) if i == 0 else path.lineTo(point) + p.setPen(QPen(QColor(t.accent), 2)) + p.drawPath(path) + # the frequency shown + if self.selected is not None: + x = self._x(self.selected, rect) + v = float(np.interp(self.selected, self.freqs, self.values)) + p.setPen(QPen(QColor(t.text), 1)) + p.drawLine(QPointF(x, rect.top()), QPointF(x, rect.bottom())) + p.setBrush(QColor(t.accent)) + p.drawEllipse(QPointF(x, self._y(v, rect, lo, hi)), 4, 4) + p.end() + + def to_png(self, width: int = 640, height: int = 260) -> bytes: + """The curve drawn on its own in light colours, for the report.""" + from PySide6.QtCore import QBuffer, QIODevice + + copy = ResponseCurve() + copy.colours = theme.LIGHT + copy.set_data(self.freqs, self.values, self.natural, self.unit, self.limit) + copy.set_selected(self.selected) + copy.setFixedSize(width, height) + buffer = QBuffer() + buffer.open(QIODevice.OpenModeFlag.WriteOnly) + copy.grab().save(buffer, "PNG") + copy.deleteLater() + return bytes(buffer.data()) + + def mousePressEvent(self, event) -> None: # noqa: N802 (Qt override) + if len(self.freqs) < 2: + return + rect = self._plot_rect() + x = min(max(event.position().x(), rect.left()), rect.right()) + f = self.freqs[0] + (x - rect.left()) / rect.width() * (self.freqs[-1] - self.freqs[0]) + # snap to a natural frequency close by (a resonance is what one aims at) + for fn in self.natural: + if abs(self._x(fn, rect) - x) <= 4: + f = fn + self.picked.emit(float(f)) diff --git a/src/kstruct/ui/steps.py b/src/kstruct/ui/steps.py index 3036b35..ae2f86b 100644 --- a/src/kstruct/ui/steps.py +++ b/src/kstruct/ui/steps.py @@ -59,6 +59,8 @@ from kstruct.ui import theme from kstruct.ui.dialogs import MaterialDialog, load_user_library, save_user_library from kstruct.ui.help import HelpButton, HelpDialog, topic, with_help +from kstruct.ui.response_curve import ResponseCurve +from kstruct.ui.unit_spin import UnitSpinBox from kstruct.units import quantity, system_of if TYPE_CHECKING: @@ -296,7 +298,7 @@ def __init__(self, app: MainWindow) -> None: self.conn_kind.activated.connect(self._kind_chosen) self.connections.currentRowChanged.connect(self._connection_selected) conn.addWidget(with_help(self.conn_kind, "connection.contact")) - self.friction = QDoubleSpinBox() + self.friction = UnitSpinBox() self.friction.setRange(0.0, 2.0) self.friction.setSingleStep(0.05) self.friction.setDecimals(2) @@ -669,6 +671,15 @@ def delete_selected(self) -> None: self._remove() +def _template_row(app: MainWindow) -> QWidget: + """Save the fixtures and loads as a template / put a template on this model.""" + save = QPushButton(tr("조건 묶음 저장…")) + save.clicked.connect(app.save_template) + use = QPushButton(tr("조건 묶음 불러오기…")) + use.clicked.connect(app.choose_template) + return with_help(_row(save, use), "fixture.template") + + class FixtureStep(_FaceListStep): def __init__(self, app: MainWindow) -> None: super().__init__(app, tr("3. 고정"), "step.fixture") @@ -684,10 +695,33 @@ def __init__(self, app: MainWindow) -> None: self.add_btn = _primary(QPushButton(tr("선택한 면을 고정"))) self.add_btn.clicked.connect(self._add) self.add(self.add_btn) + self.symmetry_btn = QPushButton(tr("선택한 평면을 대칭면으로")) + self.symmetry_btn.clicked.connect(self._add_symmetry) + self.add(with_help(self.symmetry_btn, "fixture.symmetry")) + self.add(_template_row(app)) self.finish_layout() self._build_bolt_box() self._kind_changed() + def _add_symmetry(self) -> None: + """A plane of symmetry: the faces may slide in their plane but not move through + it (a roller), flagged so the summary explains what the results then mean.""" + refs = self.app.viewer.selection + if not refs: + self.app.warn(tr("3D 화면에서 대칭면(잘린 평면)을 먼저 고르세요.")) + return + project = self.app.project + if any( + outward_normal(faces_of(project.part(r.part_id).shape)[r.face_index]) is None + for r in refs + ): + self.app.warn(tr("대칭면은 평면이어야 합니다.")) + return + project.fixtures.append(Fixture(FixtureKind.ROLLER, list(refs), symmetry=True)) + self.app.viewer.clear_selection() + self.changed.emit() + self.refresh() + def _build_value_box(self) -> None: """Inputs of the two fixtures that carry a value: the movement of a prescribed displacement (per axis, unticked = free) and the stiffness of an elastic support.""" @@ -696,7 +730,7 @@ def _build_value_box(self) -> None: self.move_axes: list[tuple[QCheckBox, QDoubleSpinBox]] = [] for axis in "XYZ": check = QCheckBox(tr("{axis} 방향", axis=axis)) - spin = QDoubleSpinBox() + spin = UnitSpinBox() spin.setRange(-1e4, 1e4) spin.setDecimals(4) spin.setSingleStep(0.01) @@ -712,7 +746,7 @@ def _build_value_box(self) -> None: ) ) form.addRow(self.move_hint) - self.stiffness = QDoubleSpinBox() + self.stiffness = UnitSpinBox() self.stiffness.setRange(1e-6, 1e12) self.stiffness.setDecimals(1) self.stiffness.setValue(10_000.0) @@ -764,7 +798,7 @@ def _build_bolt_box(self) -> None: for name in bolt_grades(): self.bolt_grade.addItem(name, name) self.bolt_grade.setCurrentIndex(self.bolt_grade.findData("8.8")) - self.bolt_preload = QDoubleSpinBox() + self.bolt_preload = UnitSpinBox() self.bolt_preload.setRange(0, 1e7) self.bolt_preload.setDecimals(0) self.bolt_preload.setSuffix(" N") @@ -950,7 +984,7 @@ def __init__(self, app: MainWindow) -> None: self.add(_row(self.kind, self.kind_help)) form = QFormLayout() - self.value = QDoubleSpinBox() + self.value = UnitSpinBox() self.value.setRange(-1e9, 1e9) self.value.setDecimals(2) self.value.setValue(1000) @@ -967,12 +1001,12 @@ def __init__(self, app: MainWindow) -> None: self.axis.addItem(tr(label)) self.axis_label = QLabel(tr("회전축")) form.addRow(self.axis_label, with_help(self.axis, "load.axis")) - self.ambient = QDoubleSpinBox() + self.ambient = UnitSpinBox() self.ambient.setRange(-100, 2000) self.ambient.setValue(20) self.ambient_label = QLabel(tr("주변 공기 온도 (°C)")) form.addRow(self.ambient_label, self.ambient) - self.offset = [QDoubleSpinBox() for _ in range(3)] + self.offset = [UnitSpinBox() for _ in range(3)] for spin in self.offset: spin.setRange(-1e6, 1e6) spin.setDecimals(2) @@ -996,6 +1030,7 @@ def __init__(self, app: MainWindow) -> None: self.add_btn = _primary(QPushButton(tr("하중 추가"))) self.add_btn.clicked.connect(self._add) self.add(self.add_btn) + self.add(_template_row(app)) self.finish_layout() self._shown_system = None self._kind_changed() @@ -1357,7 +1392,7 @@ def __init__(self, app: MainWindow) -> None: self.selection_label = _hint("") layout.addWidget(self.selection_label) form = QFormLayout() - self.refine_size = QDoubleSpinBox() + self.refine_size = UnitSpinBox() self.refine_size.setRange(0.01, 1e4) self.refine_size.setDecimals(2) self.refine_size.setSuffix(" mm") @@ -1465,6 +1500,11 @@ def set_busy(self, busy: bool) -> None: (AnalysisKind.MODAL, N_("진동 — 어떤 진동수에서 흔들릴까? (공진)"), "analysis.modal"), (AnalysisKind.THERMAL, N_("열 — 온도가 몇 도까지 오를까?"), "analysis.thermal"), (AnalysisKind.BUCKLING, N_("좌굴 — 눌리면 옆으로 휘며 무너지지 않을까?"), "analysis.buckling"), + ( + AnalysisKind.HARMONIC, + N_("진동 응답 — 흔들리는 하중에 얼마나 떨리고 버틸까?"), + "analysis.harmonic", + ), ] @@ -1486,7 +1526,7 @@ def __init__(self, app: MainWindow) -> None: self.n_modes.setRange(1, 30) self.n_modes.valueChanged.connect(self._modal_changed) form.addRow(tr("구할 진동수 개수"), with_help(self.n_modes, "modal.count")) - self.speed = QDoubleSpinBox() + self.speed = UnitSpinBox() self.speed.setRange(0, 1e6) self.speed.setDecimals(1) self.speed_unit = QComboBox() @@ -1498,12 +1538,34 @@ def __init__(self, app: MainWindow) -> None: form.addRow(self.speed_label, self.speed_row) self.add(self.modal_box) + self.harmonic_box = QGroupBox(tr("진동 응답 설정")) + vform = QFormLayout(self.harmonic_box) + self.damping = UnitSpinBox() + self.damping.setRange(0.1, 20.0) + self.damping.setDecimals(1) + self.damping.setSingleStep(0.5) + self.damping.setSuffix(" %") + self.damping.valueChanged.connect(self._harmonic_changed) + vform.addRow(tr("감쇠비"), with_help(self.damping, "harmonic.damping")) + self.f_min, self.f_max = UnitSpinBox(), UnitSpinBox() + for spin in (self.f_min, self.f_max): + spin.setRange(0, 1e6) + spin.setDecimals(1) + spin.setSuffix(" Hz") + spin.valueChanged.connect(self._harmonic_changed) + self.f_max.setSpecialValueText(tr("자동")) + vform.addRow( + tr("흔들리는 진동수"), + with_help(_row(self.f_min, QLabel("~"), self.f_max), "harmonic.range"), + ) + self.add(self.harmonic_box) + self.thermal_box = QGroupBox(tr("열 해석 설정")) hform = QFormLayout(self.thermal_box) self.transient = QCheckBox(tr("시간에 따른 변화 보기 (데워지고 식는 과정)")) self.transient.toggled.connect(self._thermal_changed) hform.addRow(with_help(self.transient, "analysis.transient")) - self.duration = QDoubleSpinBox() + self.duration = UnitSpinBox() self.duration.setRange(1, 1e7) self.duration.setDecimals(0) self.duration_unit = QComboBox() @@ -1515,7 +1577,7 @@ def __init__(self, app: MainWindow) -> None: self.duration_label = QLabel(tr("계산할 시간")) self.duration_row = _row(self.duration, self.duration_unit) hform.addRow(self.duration_label, self.duration_row) - self.initial = QDoubleSpinBox() + self.initial = UnitSpinBox() self.initial.setRange(-200, 3000) self.initial.setDecimals(1) self.initial.valueChanged.connect(self._thermal_changed) @@ -1529,7 +1591,8 @@ def __init__(self, app: MainWindow) -> None: for key, label in CYCLE_LABELS: self.cycle.addItem(tr(label), key) self.cycle.currentIndexChanged.connect(self._cycle_changed) - sform.addRow(tr("하중이 반복되나요?"), with_help(self.cycle, "fatigue.cycle")) + self.cycle_box = with_help(self.cycle, "fatigue.cycle") + sform.addRow(tr("하중이 반복되나요?"), self.cycle_box) self.surface = QComboBox() for key, (label, _a, _b) in SURFACE_FACTORS.items(): self.surface.addItem(tr_data(label), key) @@ -1546,10 +1609,12 @@ def __init__(self, app: MainWindow) -> None: sform.addRow(self.reliability_label, self.reliability_box) self.plasticity = QCheckBox(tr("항복한 뒤까지 계산 (영구 변형·붕괴 하중)")) self.plasticity.toggled.connect(self._nonlinear_changed) - sform.addRow(with_help(self.plasticity, "analysis.plasticity")) + self.plasticity_box = with_help(self.plasticity, "analysis.plasticity") + sform.addRow(self.plasticity_box) self.large = QCheckBox(tr("큰 변형 고려 (얇고 많이 휘는 부품)")) self.large.toggled.connect(self._nonlinear_changed) - sform.addRow(with_help(self.large, "analysis.large_deformation")) + self.large_box = with_help(self.large, "analysis.large_deformation") + sform.addRow(self.large_box) self.add(self.static_box) self.target_box = QGroupBox(tr("권장 안전율")) @@ -1564,7 +1629,7 @@ def __init__(self, app: MainWindow) -> None: ("brittle", tr("취성재 (주철 등)")), ("buckling", tr("좌굴 하중 배수")), ): - spin = QDoubleSpinBox() + spin = UnitSpinBox() spin.setRange(1.0, 20.0) spin.setSingleStep(0.1) spin.setDecimals(2) @@ -1602,7 +1667,13 @@ def refresh(self) -> None: for b in self.kinds.buttons(): b.setChecked(b.property("kind") == project.analysis) self.modal_box.setVisible(project.analysis == AnalysisKind.MODAL) - self.static_box.setVisible(project.analysis == AnalysisKind.STATIC) + # a vibration response is always a reversed load: only the fatigue corrections + harmonic = project.analysis == AnalysisKind.HARMONIC + self.static_box.setVisible(project.analysis == AnalysisKind.STATIC or harmonic) + self.static_box.setTitle(tr("피로 검토 설정") if harmonic else tr("강도 해석 설정")) + for w in (self.cycle_box, self.plasticity_box, self.large_box): + w.setVisible(not harmonic) + self.static_box.layout().labelForField(self.cycle_box).setVisible(not harmonic) self._show_thermal(project) self.modal_box.setTitle( tr("좌굴 해석 설정") @@ -1622,7 +1693,7 @@ def refresh(self) -> None: box.blockSignals(True) box.setChecked(value) box.blockSignals(False) - repeated = project.load_cycle != "none" + repeated = project.load_cycle != "none" or harmonic for w in ( self.surface_label, self.surface_box, @@ -1644,7 +1715,17 @@ def refresh(self) -> None: self.speed.setValue(hz * 60 if self.speed_unit.currentText() == "rpm" else hz) for w in (self.n_modes, self.speed, self.speed_unit): w.blockSignals(False) - self.target_box.setVisible(project.analysis in (AnalysisKind.STATIC, AnalysisKind.BUCKLING)) + self.harmonic_box.setVisible(project.analysis == AnalysisKind.HARMONIC) + for w in (self.damping, self.f_min, self.f_max): + w.blockSignals(True) + self.damping.setValue(project.damping_ratio * 100) + self.f_min.setValue(project.harmonic_range[0]) + self.f_max.setValue(project.harmonic_range[1]) + for w in (self.damping, self.f_min, self.f_max): + w.blockSignals(False) + self.target_box.setVisible( + project.analysis in (AnalysisKind.STATIC, AnalysisKind.BUCKLING, AnalysisKind.HARMONIC) + ) pack = standards.effective_pack(project) values = { "ductile": pack.target_ductile, @@ -1753,6 +1834,12 @@ def _thermal_changed(self) -> None: self.changed.emit() self.refresh() + def _harmonic_changed(self) -> None: + project = self.app.project + project.damping_ratio = self.damping.value() / 100 + project.harmonic_range = (self.f_min.value(), self.f_max.value()) + self.changed.emit() + def _modal_changed(self) -> None: project = self.app.project project.n_modes = self.n_modes.value() @@ -1825,7 +1912,7 @@ def __init__(self, app: MainWindow) -> None: self.scale.addItem(tr(label), key) self.scale.currentIndexChanged.connect(self._scale_changed) form.addRow(tr("변형"), with_help(self.scale, "result.scale")) - self.scale_factor = QDoubleSpinBox() + self.scale_factor = UnitSpinBox() self.scale_factor.setRange(0.1, 1e7) self.scale_factor.setDecimals(1) self.scale_factor.setPrefix("× ") @@ -1839,6 +1926,11 @@ def __init__(self, app: MainWindow) -> None: self.mode_label = QLabel(tr("진동 모드")) self.mode_box = with_help(self.mode, "result.mode") form.addRow(self.mode_label, self.mode_box) + self.freq = QComboBox() + self.freq.currentIndexChanged.connect(self._frequency_chosen) + self.freq_label = QLabel(tr("진동수")) + self.freq_box = with_help(self.freq, "result.frequency") + form.addRow(self.freq_label, self.freq_box) self.scale_note = _hint("") form.addRow("", self.scale_note) # the finer display settings fold away: the verdict and its reasons come first @@ -1853,7 +1945,7 @@ def __init__(self, app: MainWindow) -> None: self.range_manual = QCheckBox(tr("색 범위 직접 정하기")) self.range_manual.toggled.connect(self._range_toggled) more.addRow("", with_help(self.range_manual, "result.range")) - self.range_min, self.range_max = QDoubleSpinBox(), QDoubleSpinBox() + self.range_min, self.range_max = UnitSpinBox(), UnitSpinBox() for spin in (self.range_min, self.range_max): spin.setRange(-1e12, 1e12) spin.setDecimals(3) @@ -1885,6 +1977,11 @@ def __init__(self, app: MainWindow) -> None: box = QWidget() box.setLayout(form) self.add(box) + self.curve = ResponseCurve() + self.curve.picked.connect(app.select_frequency) + self.curve_box = with_help(self.curve, "result.response") + self.add(self.curve_box) + self.set_frequencies(None) self.more_toggle = QToolButton() self.more_toggle.setText(tr("표시 설정 더 보기")) self.more_toggle.setCheckable(True) @@ -1913,6 +2010,24 @@ def __init__(self, app: MainWindow) -> None: self.mesh_check_text.setTextFormat(Qt.TextFormat.RichText) self.add(self.mesh_check_text) + # compare with a result kept as the reference (before / after a design change) + self.compare_box = QGroupBox(tr("결과 비교")) + compare = QVBoxLayout(self.compare_box) + self.pin = QPushButton(tr("이 결과를 비교 기준으로")) + self.pin.clicked.connect(app.pin_reference) + compare.addWidget(with_help(self.pin, "result.compare")) + self.compare_text = QLabel() + self.compare_text.setWordWrap(True) + self.compare_text.setTextFormat(Qt.TextFormat.RichText) + compare.addWidget(self.compare_text) + self.compare_diff = QCheckBox(tr("기준과의 차이를 색으로 보기")) + self.compare_diff.toggled.connect(lambda on: app.set_compare_view("diff" if on else None)) + compare.addWidget(self.compare_diff) + self.compare_ref = QCheckBox(tr("기준 결과를 화면에 보기")) + self.compare_ref.toggled.connect(lambda on: app.set_compare_view("ref" if on else None)) + compare.addWidget(self.compare_ref) + self.add(self.compare_box) + # what if the part were made of another material (no new analysis when exact) self.trial_box = QGroupBox(tr("재료 바꿔 보기")) trial = QVBoxLayout(self.trial_box) @@ -1964,6 +2079,24 @@ def set_cases(self, labels: list[str] | None, current: int = 0) -> None: self.case.setCurrentIndex(min(current, len(labels) - 1)) self.case.blockSignals(False) + def set_frequencies(self, options: list[tuple[str, float]] | None, current: int = 0) -> None: + """Vibration response: the frequencies to look at (label, Hz) and the response + curve; None hides both.""" + visible = bool(options) + for w in (self.freq_box, self.freq_label, self.curve_box): + w.setVisible(visible) + self.freq.blockSignals(True) + self.freq.clear() + for label, hz in options or []: + self.freq.addItem(label, hz) + if options: + self.freq.setCurrentIndex(min(current, len(options) - 1)) + self.freq.blockSignals(False) + + def _frequency_chosen(self, index: int) -> None: + if index >= 0: + self.app.select_frequency(self.freq.itemData(index)) + def set_modes(self, frequencies, labels: list[str] | None = None, title=None) -> None: """Fill the mode selector (vibration / buckling modes, or the moments of a transient heat run); None hides it.""" diff --git a/src/kstruct/ui/unit_spin.py b/src/kstruct/ui/unit_spin.py new file mode 100644 index 0000000..3c34cc2 --- /dev/null +++ b/src/kstruct/ui/unit_spin.py @@ -0,0 +1,49 @@ +"""Number box that also takes arithmetic and units: "10 kN" into a box in N, "2 in" into +one in mm, "=1500*9.81" anywhere (kstruct/unitparse.py). Anything it cannot read, or a +unit of another kind, leaves the previous value.""" + +from __future__ import annotations + +from PySide6.QtGui import QValidator +from PySide6.QtWidgets import QDoubleSpinBox + +from kstruct.i18n import tr +from kstruct.unitparse import parse + + +class UnitSpinBox(QDoubleSpinBox): + def __init__(self, parent=None) -> None: + super().__init__(parent) + self.setToolTip(tr("단위나 수식도 입력할 수 있습니다 (예: 10 kN, 2 in, =1500*9.81)")) + + def unit(self) -> str: + return self.suffix().strip() + + def _body(self, text: str) -> str: + prefix, suffix = self.prefix(), self.suffix() + if prefix and text.startswith(prefix): + text = text[len(prefix) :] + if suffix and text.endswith(suffix): + text = text[: -len(suffix)] + return text.strip() + + def _read(self, text: str) -> float: + special = self.specialValueText() + if special and text.strip() == special: + return self.minimum() + return parse(self._body(text), self.unit()) + + def validate(self, text: str, pos: int): # noqa: D102 (Qt override) + try: + value = self._read(text) + except ValueError: + return (QValidator.State.Intermediate, text, pos) + if self.minimum() <= value <= self.maximum(): + return (QValidator.State.Acceptable, text, pos) + return (QValidator.State.Intermediate, text, pos) + + def valueFromText(self, text: str) -> float: # noqa: N802 (Qt override) + try: + return self._read(text) + except ValueError: + return self.value() diff --git a/src/kstruct/ui/viewer.py b/src/kstruct/ui/viewer.py index 09601ad..25819a3 100644 --- a/src/kstruct/ui/viewer.py +++ b/src/kstruct/ui/viewer.py @@ -126,6 +126,10 @@ def __init__(self, parent: QWidget | None = None) -> None: self._problem_parts: set[int] = set() self._problem_faces: list[FaceRef] = [] self._box_mode = False + self._measure_mode = False + self._measure_points: list[np.ndarray] = [] + self._measure_actors: list = [] + self.measure_message = "" # what the last measuring click found self._overlay: list = [] # arrows etc. self._mesh_actor = None self._result_actor = None @@ -203,6 +207,10 @@ def act(text, slot, key, shortcut=None, checkable=False) -> QAction: tr("반투명"), self.set_see_through, "view.see_through", checkable=True ) strip.addAction(self.see_through_action) + self.measure_action = act( + tr("측정"), self.set_measure_mode, "view.measure", "M", checkable=True + ) + strip.addAction(self.measure_action) self._select_separator = strip.addSeparator() self.box_action = act( tr("영역 선택"), self.set_box_mode, "view.box_select", "B", checkable=True @@ -318,6 +326,8 @@ def set_project(self, project: Project) -> None: def load_project(self, project: Project) -> None: self.plotter.clear_actors() + self._measure_actors = [] # cleared with the scene + self._measure_points = [] self._project = project self._meshes.clear() self._actors.clear() @@ -764,6 +774,9 @@ def _on_release(self, *_args) -> None: if self._result_actor is not None: self._probe(*pos) return + if self._measure_mode: + self._measure_click(*pos) + return if not self.selection_enabled: return ref = self._pick(*pos) @@ -826,12 +839,87 @@ def _context_menu(self, ref: FaceRef | None) -> None: menu.addAction(label, callback) menu.exec(QCursor.pos()) + # --- measuring ------------------------------------------------------------------- + + def set_measure_mode(self, on: bool) -> None: + """Clicks measure instead of selecting: the face under the cursor (area, hole + diameter and axis) and, from the second click, the distance between the last two + points.""" + on = bool(on) + self.measure_action.setChecked(on) + if on == self._measure_mode: + return + self._measure_mode = on + if on and self._box_mode: + self.set_box_mode(False) + self._clear_measure() + if on: + self.notice.emit( + tr("측정: 면을 클릭하면 면적·지름을, 두 점을 차례로 클릭하면 거리를 알려 줍니다.") + ) + self.plotter.render() + + def _clear_measure(self) -> None: + for actor in self._measure_actors: + self.plotter.remove_actor(actor) + self._measure_actors = [] + self._measure_points = [] + self.measure_message = "" + + def measure_at(self, ref: FaceRef, point) -> str: + """One measuring click at `point` on face `ref`: describe the face, and the + distance from the previous point (a third click starts over).""" + from kstruct.geometry.measure import distance_text, face_text + from kstruct.geometry.tessellate import faces_of + from kstruct.units import system_of + + system = system_of(self._project) + point = np.asarray(point, dtype=float) + if len(self._measure_points) >= 2: + self._clear_measure() + self._measure_points.append(point) + face = faces_of(self._project.part(ref.part_id).shape)[ref.face_index] + n = len(self._measure_points) + text = tr("점 {n}: {face}", n=n, face=face_text(face, system, point)) + self._measure_actors.append( + self.plotter.add_point_labels( + [point], + [str(n)], + point_size=10, + point_color="#e8743b", + font_size=13, + shape_opacity=0.85, + always_visible=True, + pickable=False, + ) + ) + if n == 2: + first = self._measure_points[0] + self._measure_actors.append( + self.plotter.add_mesh( + pv.Line(first, point), color="#e8743b", line_width=3, pickable=False + ) + ) + text = distance_text(first, point, system) + " · " + text + self.measure_message = text + self.notice.emit(text) + self.plotter.render() + return text + + def _measure_click(self, x: int, y: int) -> None: + ref = self._pick(x, y) + if ref is None: + return + self.measure_at(ref, self._picker.GetPickPosition()) + # --- 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 and self._measure_mode: + self.set_measure_mode(False) if on == self._box_mode: self.box_action.setChecked(on) return diff --git a/src/kstruct/unitparse.py b/src/kstruct/unitparse.py new file mode 100644 index 0000000..9ce24ef --- /dev/null +++ b/src/kstruct/unitparse.py @@ -0,0 +1,133 @@ +"""Typed input with units and arithmetic: "10 kN", "2 in", "=1500*9.81", "(30+12)/2 mm". + +`parse(text, unit)` returns the value in `unit` (the unit the input box shows). A unit +typed after the number is converted when it measures the same thing (length, force, …); +a unit of another kind, an unknown unit or anything that is not plain arithmetic is +rejected with ValueError. The arithmetic is evaluated from the syntax tree (numbers, ++ − × ÷, powers, parentheses), never with eval. +""" + +from __future__ import annotations + +import ast +import operator +import re + +# unit -> (kind, factor to the kind's base unit, offset): base = value * factor + offset +_UNITS: dict[str, tuple[str, float, float]] = {} + + +def _add(kind: str, factor: float, *names: str, offset: float = 0.0) -> None: + for name in names: + _UNITS[name] = (kind, factor, offset) + + +_IN, _LBF = 25.4, 4.4482216152605 +_add("length", 1.0, "mm") +_add("length", 10.0, "cm") +_add("length", 1000.0, "m") +_add("length", 1e-3, "µm", "um") +_add("length", _IN, "in", "inch", '"') +_add("length", 12 * _IN, "ft") +_add("force", 1.0, "N") +_add("force", 1e3, "kN") +_add("force", 1e6, "MN") +_add("force", _LBF, "lbf") +_add("force", 1000 * _LBF, "kip") +_add("force", 9.80665, "kgf") +_add("stress", 1.0, "MPa", "N/mm²", "N/mm2") +_add("stress", 1e-6, "Pa") +_add("stress", 1e-3, "kPa") +_add("stress", 1e3, "GPa") +_add("stress", 0.1, "bar") +_add("stress", 1 / 145.03773773, "psi") +_add("stress", 1000 / 145.03773773, "ksi") +_add("temperature", 1.0, "°C", "C", "degC") +_add("temperature", 5 / 9, "°F", "F", "degF", offset=-32 * 5 / 9) +_add("temperature", 1.0, "K", offset=-273.15) +_add("torque", 1.0, "N·mm", "Nmm", "N*mm") +_add("torque", 1e3, "N·m", "Nm", "N*m") +_add("torque", _LBF * _IN, "lbf·in", "lbf*in", "lbfin") +_add("torque", _LBF * 12 * _IN, "lbf·ft", "lbf*ft", "lbfft") +_add("stiffness", 1.0, "N/mm") +_add("stiffness", 1e-3, "N/m") +_add("stiffness", 1e3, "kN/mm") +_add("stiffness", _LBF / _IN, "lbf/in") +_add("frequency", 1.0, "Hz") +_add("frequency", 1e3, "kHz") +_add("frequency", 1 / 60, "rpm") +_add("time", 1.0, "s", "sec") +_add("time", 60.0, "min") +_add("time", 3600.0, "h") +_add("power", 1.0, "W") +_add("power", 1e3, "kW") + +_OPS = { + ast.Add: operator.add, + ast.Sub: operator.sub, + ast.Mult: operator.mul, + ast.Div: operator.truediv, + ast.Pow: operator.pow, +} +# the number part, then optionally a unit made of letters, symbols and a trailing digit +_SPLIT = re.compile(r"^(?P.*?)\s*(?P[A-Za-zµ°\"][A-Za-zµ°·*/²2]*)?\s*$") + + +def _evaluate(node: ast.AST) -> float: + if isinstance(node, ast.Expression): + return _evaluate(node.body) + if isinstance(node, ast.Constant) and isinstance(node.value, (int, float)): + return float(node.value) + if isinstance(node, ast.UnaryOp) and isinstance(node.op, (ast.UAdd, ast.USub)): + value = _evaluate(node.operand) + return -value if isinstance(node.op, ast.USub) else value + if isinstance(node, ast.BinOp) and type(node.op) in _OPS: + left, right = _evaluate(node.left), _evaluate(node.right) + if isinstance(node.op, ast.Pow) and abs(right) > 100: + raise ValueError("exponent too large") + return _OPS[type(node.op)](left, right) + raise ValueError("not arithmetic") + + +def arithmetic(text: str) -> float: + """Value of a plain arithmetic expression (× and ÷ accepted, commas as thousands).""" + text = text.replace("×", "*").replace("÷", "/").replace(",", "").replace("^", "**") + if not text.strip(): + raise ValueError("empty") + try: + tree = ast.parse(text.strip(), mode="eval") + return _evaluate(tree) + except (SyntaxError, ZeroDivisionError, OverflowError, TypeError) as e: + raise ValueError(str(e)) from e + + +def convert(value: float, source: str, target: str) -> float: + """value in unit `source` expressed in unit `target` (same kind of quantity).""" + if source == target: + return value + if source not in _UNITS or target not in _UNITS: + raise ValueError(f"unknown unit {source!r} or {target!r}") + kind_s, f_s, o_s = _UNITS[source] + kind_t, f_t, o_t = _UNITS[target] + if kind_s != kind_t: + raise ValueError(f"{source} is not a {kind_t}") + return (value * f_s + o_s - o_t) / f_t + + +def parse(text: str, unit: str = "") -> float: + """Number typed into a box that shows `unit` ("" for a plain number).""" + text = text.strip() + if text.startswith("="): + text = text[1:] + try: + return arithmetic(text) # no unit ("1e2" is a number, not 1 of unit "e2") + except ValueError: + pass + match = _SPLIT.match(text) + expr, typed = match["expr"], match["unit"] + value = arithmetic(expr) + if not typed or typed == unit: + return value + if not unit or unit not in _UNITS: + raise ValueError(f"this box takes no unit {typed!r}") + return convert(value, typed, unit) diff --git a/src/kstruct/whatif.py b/src/kstruct/whatif.py index d7dd2a7..bda48e2 100644 --- a/src/kstruct/whatif.py +++ b/src/kstruct/whatif.py @@ -24,6 +24,8 @@ def why_not_exact(project: Project, result: StaticResult, new: Material) -> str """The reason the swap needs a new analysis, or None when it is exact.""" if result.nonlinear is not None: return tr("항복·대변형 해석은 재료에 따라 응력 분포가 달라집니다.") + if result.harmonic is not None: + return tr("진동 응답은 탄성계수와 밀도로 정해지는 고유진동수에 따라 달라집니다.") if len({m.id for m in result.materials.values()}) != 1: return tr("부품마다 재료가 달라 강성 비율이 바뀝니다.") current = next(iter(result.materials.values())) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..1185d4c --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,37 @@ +"""Shared test set-up. + +The UI tests open dozens of main windows, each with an OpenGL render window. Under +software OpenGL (Xvfb/Mesa, as in CI) the process crashed now and then deep into the run +with a segmentation fault in the Qt event loop. Closed windows are only destroyed when +their deferred-delete events are processed and the Python wrappers collected, so their +GL contexts piled up. After every test, release what the test left behind. +""" + +import gc + +import pytest + + +@pytest.fixture(autouse=True) +def _release_windows(): + # autouse fixtures are set up first and torn down last: this runs after pytest-qt + # has closed the widgets the test registered with qtbot + yield + try: + from PySide6.QtCore import QCoreApplication, QEvent + from PySide6.QtWidgets import QApplication + except ImportError: + return + app = QApplication.instance() + if app is None: + return + from kstruct.ui.main_window import MainWindow + + for widget in app.topLevelWidgets(): + if isinstance(widget, MainWindow): + widget.ask_before_close = False + widget.close() # closeEvent releases the render window (viewer.shutdown) + widget.deleteLater() + QCoreApplication.sendPostedEvents(None, QEvent.Type.DeferredDelete) + app.processEvents() + gc.collect() diff --git a/tests/test_advice.py b/tests/test_advice.py new file mode 100644 index 0000000..c25357f --- /dev/null +++ b/tests/test_advice.py @@ -0,0 +1,97 @@ +"""Design advice after a strength verdict (report/advice.py): what it says depends on +where the governing stress sits, and its numbers are the exact linear scalings.""" + +import math + +import pytest +from OCP.BRepAlgoAPI import BRepAlgoAPI_Cut +from OCP.gp import gp_Dir + +from kstruct import standards +from kstruct.fem import generate_mesh, solve_static +from kstruct.geometry.face_info import face_at +from kstruct.geometry.samples import _box, _hole, l_bracket +from kstruct.model import FaceRef, Fixture, FixtureKind, Load, LoadKind, Part, Project +from kstruct.report.advice import linear_in_loads +from kstruct.report.summary import summarize + + +def _run(project, quality="normal"): + mats = standards.project_materials(project) + materials = {p.id: mats[p.material_id] for p in project.parts} + mesh = generate_mesh(project, quality) + result = solve_static(project, mesh, materials) + return result, summarize(project, result, standards.effective_pack(project)) + + +def _bracket(force): + shape = l_bracket() + project = Project(parts=[Part(0, "브래킷", shape, "s235")]) + project.fixtures = [Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(shape, (0, 30, 40)))])] + top = [FaceRef(0, face_at(shape, (90, 30, 8)))] + project.loads = [Load(LoadKind.FORCE, top, vector=(0, 0, -force))] + return project + + +def test_nothing_to_say_when_the_margin_is_right(): + _, summary = _run(_bracket(2000.0)) + assert summary.parts[0].verdict.name == "OK" and summary.advice == [] + + +def test_generous_bracket_gets_fillet_and_thinner_wall(): + _, summary = _run(_bracket(200.0)) + fillet, thinner = summary.advice + assert "필렛 없는 오목 모서리" in fillet + p = summary.parts[0] + t = 8.0 * math.sqrt(p.target / p.governing_fos) # bending: σ ∝ 1/t² + assert "두께 8 mm" in thinner and f"{t:.3g} mm" in thinner + + +def test_plate_with_a_hole_in_tension(): + plate = BRepAlgoAPI_Cut( + _box(0, 0, 0, 200, 60, 5), _hole(100, 30, -1, gp_Dir(0, 0, 1), 10, 7) + ).Shape() + project = Project(parts=[Part(0, "판", plate, "s235")]) + project.fixtures = [Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(plate, (0, 30, 2.5)))])] + end = [FaceRef(0, face_at(plate, (200, 30, 2.5)))] + project.loads = [Load(LoadKind.FORCE, end, vector=(40_000.0, 0, 0))] + result, summary = _run(project) + hole, load, material = summary.advice + assert "구멍(지름 20 mm)" in hole and "3배" in hole + k = summary.parts[0].governing_fos / summary.parts[0].target + assert f"{k:.2f}배" in load + assert "항복강도" in material + + # the load factor is exact: scaling the load by it lands on the target + project.loads = [Load(LoadKind.FORCE, end, vector=(40_000.0 * k, 0, 0))] + _, scaled = _run(project) + assert scaled.parts[0].governing_fos == pytest.approx(summary.parts[0].target, rel=1e-6) + + +def test_thin_cantilever_gets_a_thickness_range_and_materials(): + plate = _box(0, 0, 0, 200, 40, 4) + project = Project(parts=[Part(0, "판", plate, "s235")]) + project.fixtures = [Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(plate, (0, 20, 2)))])] + end = [FaceRef(0, face_at(plate, (200, 20, 2)))] + project.loads = [Load(LoadKind.FORCE, end, vector=(0, 0, -100.0))] + _, summary = _run(project) + p = summary.parts[0] + r = p.target / p.governing_fos + assert r > 1 + load, thickness, material = summary.advice + assert "두께는 4 mm" in thickness + assert f"×{math.sqrt(r):.2f}" in thickness and f"×{r:.2f}" in thickness + # stronger steels with the same Poisson's ratio: an exact swap, named + assert "후보:" in material + + +def test_scalings_are_only_claimed_for_linear_loads(): + project = _bracket(2000.0) + project.loads.append(Load(LoadKind.TEMPERATURE, [], magnitude=50.0)) + + class R: + nonlinear = thermal = None + + assert not linear_in_loads(project, R()) + project.loads.pop() + assert linear_in_loads(project, R()) diff --git a/tests/test_fem_harmonic.py b/tests/test_fem_harmonic.py new file mode 100644 index 0000000..d2bb17b --- /dev/null +++ b/tests/test_fem_harmonic.py @@ -0,0 +1,157 @@ +"""Harmonic (frequency) response against the exact solution of a bar vibrating along its +axis: fixed at x = 0, a force F cos ωt at x = L, ν = 0 so the bar is truly one-dimensional. + +Undamped: u(L) = F tan(kL) / (EA k), k = ω/c, c = √(E/ρ); natural frequencies +(2n−1)c/4L. With modal damping ζ the exact response is the modal series +u(L) = Σₙ F/(ρAL/2) / (ωₙ² − ω² + 2iζωₙω), the modes being sin((2n−1)πx/2L). +""" + +import numpy as np +import pytest + +from kstruct import standards +from kstruct.fem import generate_mesh, solve_static +from kstruct.fem.harmonic import _vm_form, _worst_over_period, solve_harmonic, sweep +from kstruct.geometry.face_info import face_at +from kstruct.geometry.samples import _box +from kstruct.model import ( + AnalysisKind, + FaceRef, + Fixture, + FixtureKind, + Load, + LoadKind, + Material, + Part, + Project, +) +from kstruct.report.summary import summarize + +E, RHO, L, A = 210_000.0, 7.85e-9, 200.0, 100.0 +C = np.sqrt(E / RHO) +F1 = C / (4 * L) # first axial natural frequency, ~6.47 kHz +PRESSURE = 10.0 # MPa on the 10 x 10 end: F = 1000 N +FORCE = PRESSURE * A +BAR = Material("bar", "bar", "steel", E, 0.0, RHO, 235.0, 360.0) + + +def _project(damping: float, upper: float) -> Project: + shape = _box(0, 0, 0, L, 10, 10) + project = Project(parts=[Part(0, "bar", shape, "bar")]) + project.analysis = AnalysisKind.HARMONIC + # rollers on three faces: x held at the root, no bending, free lateral contraction + project.fixtures = [ + Fixture(FixtureKind.ROLLER, [FaceRef(0, face_at(shape, (0, 5, 5)))]), + Fixture(FixtureKind.ROLLER, [FaceRef(0, face_at(shape, (L / 2, 0, 5)))]), + Fixture(FixtureKind.ROLLER, [FaceRef(0, face_at(shape, (L / 2, 5, 0)))]), + ] + project.loads = [ + Load(LoadKind.PRESSURE, [FaceRef(0, face_at(shape, (L, 5, 5)))], magnitude=-PRESSURE) + ] + project.damping_ratio = damping + project.harmonic_range = (0.0, upper) + return project + + +@pytest.fixture(scope="module") +def bar(): + project = _project(1e-6, 3 * F1) + mesh = generate_mesh(project, "normal") + return project, mesh, solve_harmonic(project, mesh, {0: BAR}) + + +def _tip(mesh, state) -> float: + tip = np.flatnonzero(np.isclose(mesh.nodes[:, 0], L)) + return float(np.abs(state.displacement[tip, 0]).mean()) + + +def test_natural_frequencies_of_the_bar(bar): + _, _, result = bar + axial = [(2 * n - 1) * F1 for n in (1, 2, 3)] + found = [f for f in result.harmonic.natural if min(abs(f / a - 1) for a in axial) < 1e-3] + assert len(found) == 3 + + +@pytest.mark.parametrize("ratio", [0.3, 0.5, 0.8, 1.5, 2.5]) +def test_undamped_tip_amplitude_matches_the_wave_solution(bar, ratio): + _, mesh, result = bar + k = 2 * np.pi * ratio * F1 / C + exact = abs(FORCE * np.tan(k * L) / (E * A * k)) + assert _tip(mesh, result.harmonic.state(ratio * F1)) == pytest.approx(exact, rel=2e-3) + + +def test_support_force_is_amplified_like_the_wave_solution(bar): + _, _, result = bar + k = 2 * np.pi * 0.5 * F1 / C + reaction = result.harmonic.state(0.5 * F1).reactions[0] + assert reaction[0] == pytest.approx(FORCE / np.cos(k * L), rel=1e-3) + + +def test_zero_frequency_is_the_static_solution(bar): + project, mesh, result = bar + static = solve_static(project, mesh, {0: BAR}) + still = result.harmonic.state(0.0) + assert np.abs(still.displacement).max() == pytest.approx( + np.abs(static.displacement).max(), rel=1e-9 + ) + assert still.von_mises.max() == pytest.approx(static.von_mises.max(), rel=1e-6) + assert result.harmonic.amplification(0.0) == pytest.approx(1.0, rel=1e-9) + + +@pytest.mark.parametrize("ratio", [0.8, 1.0, 1.2]) +def test_damped_response_matches_the_modal_series(ratio): + zeta = 0.02 + project = _project(zeta, 1.5 * F1) + mesh = generate_mesh(project, "coarse") + h = solve_harmonic(project, mesh, {0: BAR}).harmonic + w = 2 * np.pi * ratio * F1 + n = np.arange(1, 200_001) + wn = (2 * n - 1) * np.pi * C / (2 * L) + exact = abs(np.sum(FORCE / (RHO * A * L / 2) / (wn**2 - w**2 + 2j * zeta * wn * w))) + assert _tip(mesh, h.state(ratio * F1)) == pytest.approx(exact, rel=5e-3) + if ratio == 1.0: # resonance: about 1/(2ζ) times the first mode's static share + assert h.amplification(F1) == pytest.approx(8 / np.pi**2 / (2 * zeta), rel=0.02) + + +def test_the_verdict_is_taken_at_resonance_with_reversed_fatigue(bar): + project, mesh, _ = bar + project = _project(0.02, 1.5 * F1) + result = solve_harmonic(project, mesh, {0: BAR}) + h = result.harmonic + assert result.harmonic_frequency == h.governing + assert abs(h.governing / F1 - 1) < 0.02 # the resonance peak + summary = summarize(project, result, standards.effective_pack(project)) + assert summary.fatigue is not None # vibration is a fully reversed load + assert summary.notes[0].startswith("진동 응답") + assert "1차 고유진동수" in summary.notes[1] + # 25 x the static 10 MPa is beyond the 235 MPa yield + assert summary.governing_fos < 1.0 + + +def test_sweep_packs_points_around_resonances(): + f = sweep(0.0, 100.0, np.array([40.0, 250.0]), 0.02, extra=[33.0]) + assert f[0] == 0.0 and f[-1] == 100.0 and 40.0 in f and 33.0 in f + assert np.all(np.diff(f) > 0) + assert np.count_nonzero(np.abs(f - 40) < 40 * 0.02) >= 7 # inside the half-power band + + +def test_worst_instant_over_a_period(): + rng = np.random.default_rng(1) + A_, B_ = rng.normal(size=(50, 6)), rng.normal(size=(50, 6)) + peak, theta = _worst_over_period(_vm_form(A_, A_), _vm_form(B_, B_), _vm_form(A_, B_)) + t = np.linspace(0, 2 * np.pi, 20_001) + states = A_[:, None, :] * np.cos(t)[None, :, None] + B_[:, None, :] * np.sin(t)[None, :, None] + brute = _vm_form(states, states).max(axis=1) + assert peak == pytest.approx(brute, rel=1e-6) + at = A_ * np.cos(theta)[:, None] + B_ * np.sin(theta)[:, None] + assert _vm_form(at, at) == pytest.approx(peak, rel=1e-9) + + +def test_without_vibrating_loads_it_says_so(): + from kstruct.fem.assembly import SolverError + + project = _project(0.02, 100.0) + project.loads = [] + mesh = generate_mesh(project, "coarse") + with pytest.raises(SolverError, match="하중"): + solve_harmonic(project, mesh, {0: BAR}) diff --git a/tests/test_fem_nonlinear_contact.py b/tests/test_fem_nonlinear_contact.py new file mode 100644 index 0000000..a71d0a1 --- /dev/null +++ b/tests/test_fem_nonlinear_contact.py @@ -0,0 +1,149 @@ +"""Yielding with contact and bolts (fem/nonlinear.py): frictionless contact opens and +closes inside the Newton iterations, bolts are tightened as the first loading stage. + +Checks: two blocks stacked through a contact behave like one bar (elastic stretch +F·L/(EA), collapse at σy + H·0.5 as for the single bar); below yield a preloaded contact +joint matches the linear contact solver; every bolt carries exactly its preload; once +the plates separate the bolts carry the whole pull (equilibrium), yielding or not. +""" + +import sys +from dataclasses import replace +from pathlib import Path + +import numpy as np +import pytest + +from kstruct.fem import generate_mesh, solve_static +from kstruct.fem.nonlinear import solve_nonlinear, unsupported +from kstruct.geometry.face_info import face_at +from kstruct.geometry.samples import _box +from kstruct.model import ( + Connection, + ConnectionKind, + FaceRef, + Fixture, + FixtureKind, + Load, + LoadKind, + Part, + Project, +) + +sys.path.insert(0, str(Path(__file__).parent)) +from test_fem_bolts import STEEL as BOLT_STEEL # noqa: E402 +from test_fem_bolts import _joint # noqa: E402 +from test_fem_nonlinear import AREA, STEEL, SY, E # noqa: E402 + +H = 50.0 # height of each block + + +def _stack(force: float) -> Project: + """Two 10x10x50 blocks on top of each other, touching through a frictionless contact, + on rollers at the coordinate planes; force along z on the top face.""" + lower, upper = _box(0, 0, 0, 10, 10, H), _box(0, 0, H, 10, 10, H) + project = Project(parts=[Part(0, "lower", lower, "s"), Part(1, "upper", upper, "s")]) + project.fixtures = [ + Fixture(FixtureKind.ROLLER, [FaceRef(0, face_at(lower, (5, 5, 0)))]), + Fixture( + FixtureKind.ROLLER, + [ + FaceRef(0, face_at(lower, (0, 5, H / 2))), + FaceRef(1, face_at(upper, (0, 5, 1.5 * H))), + ], + ), + Fixture( + FixtureKind.ROLLER, + [ + FaceRef(0, face_at(lower, (5, 0, H / 2))), + FaceRef(1, face_at(upper, (5, 0, 1.5 * H))), + ], + ), + ] + project.connections = [ + Connection( + ConnectionKind.CONTACT, + [FaceRef(0, face_at(lower, (5, 5, H)))], + [FaceRef(1, face_at(upper, (5, 5, H)))], + ) + ] + top = [FaceRef(1, face_at(upper, (5, 5, 2 * H)))] + project.loads = [Load(LoadKind.FORCE, top, vector=(0, 0, force))] + project.plasticity = True + return project + + +def test_stacked_blocks_in_compression_shorten_like_one_bar(): + force = -0.5 * SY * AREA + project = _stack(force) + mesh = generate_mesh(project, "coarse") + r = solve_nonlinear(project, mesh, {0: STEEL, 1: STEEL}) + assert r.nonlinear.completed and not r.nonlinear.yielded + top = np.isclose(mesh.nodes[:, 2], 2 * H) + assert r.displacement[top, 2].mean() == pytest.approx(force * 2 * H / (E * AREA), rel=2e-3) + closed, total, _ = r.contact[0] + assert closed == total # pressed all over + + +def test_stacked_blocks_collapse_like_one_bar(): + """Nearly no hardening: as for the single bar, the stack carries σy + H·0.5.""" + project = _stack(-1.1 * SY * AREA) + mesh = generate_mesh(project, "coarse") + soft = replace(STEEL, tangent_modulus=1e-4 * E) + r = solve_nonlinear(project, mesh, {0: soft, 1: soft}) + assert not r.nonlinear.completed + hardening = E * soft.tangent_modulus / (E - soft.tangent_modulus) + assert r.nonlinear.load_factor == pytest.approx((SY + 0.5 * hardening) / (1.1 * SY), rel=0.01) + + +def test_pulled_apart_blocks_cannot_be_held_by_contact(): + project = _stack(+0.1 * SY * AREA) # the upper block is only held by the contact + mesh = generate_mesh(project, "coarse") + from kstruct.fem import SolverError + + with pytest.raises(SolverError): + solve_nonlinear(project, mesh, {0: STEEL, 1: STEEL}) + + +@pytest.fixture(scope="module") +def joint_mesh(): + project = _joint(force=(0, 0, 3000.0), preload=10_000.0, interface=ConnectionKind.CONTACT) + return generate_mesh(project, "coarse") + + +def test_preloaded_contact_joint_below_yield_matches_the_linear_solver(joint_mesh): + project = _joint(force=(0, 0, 3000.0), preload=10_000.0, interface=ConnectionKind.CONTACT) + materials = {0: BOLT_STEEL, 1: BOLT_STEEL} + linear = solve_static(project, joint_mesh, materials) + project.plasticity = True + r = solve_nonlinear(project, joint_mesh, materials) + assert r.nonlinear.completed + assert [b.axial for b in r.bolts] == pytest.approx([b.axial for b in linear.bolts], rel=1e-3) + assert r.contact[0][0] == linear.contact[0][0] # the same pairs pressed + scale = np.abs(linear.displacement).max() + assert np.abs(r.displacement - linear.displacement).max() < 2e-3 * scale + + +def test_every_bolt_carries_its_preload(joint_mesh): + project = _joint(preload=10_000.0, interface=ConnectionKind.CONTACT) + project.plasticity = True + r = solve_nonlinear(project, joint_mesh, {0: BOLT_STEEL, 1: BOLT_STEEL}) + assert [b.axial for b in r.bolts] == pytest.approx([10_000.0] * 3, rel=1e-3) + + +def test_separated_joint_puts_the_whole_pull_on_the_bolts_even_while_yielding(joint_mesh): + pull = 36_000.0 # beyond the clamping force of 3 x 10 kN, short of collapse (~40 kN) + project = _joint(force=(0, 0, pull), preload=10_000.0, interface=ConnectionKind.CONTACT) + project.plasticity = True + r = solve_nonlinear(project, joint_mesh, {0: BOLT_STEEL, 1: BOLT_STEEL}) + assert r.nonlinear.completed and r.nonlinear.yielded # the plates yield under the heads + closed, total, _ = r.contact[0] + assert closed < 0.2 * total + assert sum(b.axial for b in r.bolts) >= 0.99 * pull + + +def test_friction_is_not_yet_supported(): + project = _joint(preload=10_000.0, interface=ConnectionKind.CONTACT) + assert unsupported(project) is None + project.connections[0].friction = 0.2 + assert "마찰" in unsupported(project) diff --git a/tests/test_measure.py b/tests/test_measure.py new file mode 100644 index 0000000..4a8bbf2 --- /dev/null +++ b/tests/test_measure.py @@ -0,0 +1,54 @@ +"""Measuring on the model: face area / hole diameter and axis, two-point distance, in +the display units; and the 3D view's measure tool driven by picks.""" + +from kstruct.geometry.face_info import face_at +from kstruct.geometry.measure import axis_of, distance_text, face_text +from kstruct.geometry.samples import l_bracket +from kstruct.geometry.tessellate import faces_of + + +def test_face_text_of_a_plane_and_a_hole(): + shape = l_bracket() + faces = faces_of(shape) + top = faces[face_at(shape, (90, 30, 8))] + text = face_text(top, "SI") + assert text.startswith("평면, 면적") and "바깥 법선 (0.000, 0.000, 1.000)" in text + holes = [f for f in faces if axis_of(f) is not None] + assert holes + text = face_text(holes[0], "SI") + assert "지름" in text and "축 방향" in text + inch = face_text(top, "US") + assert "in²" in inch + + +def test_distance_text(): + assert distance_text((0, 0, 0), (3, 4, 0), "SI").startswith("거리 5.000 mm") + assert "ΔX +3.000 mm" in distance_text((0, 0, 0), (3, 4, 0), "SI") + assert distance_text((0, 0, 0), (25.4, 0, 0), "US").startswith("거리 1.000 in") + + +def test_measure_tool_in_the_window(qtbot): + from kstruct.model import FaceRef + from kstruct.ui.main_window import MainWindow + + window = MainWindow() + window.ask_before_close = False + qtbot.addWidget(window) + window.show() + window.open_sample("bracket") + viewer = window.viewer + shape = window.project.parts[0].shape + viewer.measure_action.trigger() + assert viewer.measure_action.isChecked() and viewer._measure_mode + top = FaceRef(0, face_at(shape, (90, 30, 8))) + first = viewer.measure_at(top, (90, 30, 8)) + assert first.startswith("점 1: 평면, 면적") + second = viewer.measure_at(top, (60, 10, 8)) + assert second.startswith("거리 36.056 mm (ΔX -30.000 mm, ΔY -20.000 mm, ΔZ +0.000 mm)") + assert len(viewer._measure_actors) == 3 # two points and the line + assert window.statusBar().currentMessage() == second + viewer.measure_at(top, (50, 10, 8)) # a third click starts over + assert len(viewer._measure_points) == 1 + viewer.measure_action.trigger() + assert not viewer._measure_mode and viewer._measure_actors == [] + assert viewer.selection == [] # measuring never selected anything diff --git a/tests/test_templates.py b/tests/test_templates.py new file mode 100644 index 0000000..0a3b442 --- /dev/null +++ b/tests/test_templates.py @@ -0,0 +1,105 @@ +"""Condition templates and the plane-of-symmetry helper (UX-7).""" + +import pytest + +from kstruct import standards, templates +from kstruct.fem import generate_mesh, solve_static +from kstruct.geometry.face_info import face_at +from kstruct.geometry.samples import _box, bolted_plates, l_bracket +from kstruct.model import FaceRef, Fixture, FixtureKind, Load, LoadKind, Part, Project +from kstruct.report.summary import summarize + + +def _project(shape) -> Project: + return Project(parts=[Part(0, "p", shape, "s235")]) + + +def test_hole_fixture_lands_on_every_hole_of_that_size(tmp_path): + source = _project(l_bracket()) + holes = [ + FaceRef(0, i) + for i in range(12) + if templates.signature(source, FaceRef(0, i))["kind"] == "cylinder" + ] + fixture = Fixture(FixtureKind.FIXED, holes[:1]) # saved from one hole + gravity = Load(LoadKind.GRAVITY, [], vector=(0, 0, -9810.0)) + template = templates.make_template(source, [fixture], [gravity]) + path = tmp_path / "templates.json" + templates.save_library(path, {"holes": template}) + loaded = templates.load_library(path)["holes"] + + target = _project(l_bracket()) + fixtures, loads, missed = templates.apply_template(target, loaded) + assert missed == 0 and len(fixtures) == 1 and loads[0].kind == LoadKind.GRAVITY + radius = templates.signature(source, holes[0])["radius"] + same = [r for r in holes if abs(templates.signature(source, r)["radius"] - radius) < 1e-9] + assert sorted(fixtures[0].faces, key=lambda r: r.face_index) == same + + # a model without such holes: the fixture is left out and counted + plain = _project(_box(0, 0, 0, 50, 50, 10)) + fixtures, loads, missed = templates.apply_template(plain, loaded) + assert fixtures == [] and missed == 1 and len(loads) == 1 + + +def test_plane_matches_by_direction_and_area(): + a = _project(_box(0, 0, 0, 40, 20, 10)) + top = FaceRef(0, face_at(a.parts[0].shape, (20, 10, 10))) + load = Load(LoadKind.PRESSURE, [top], magnitude=1.0) + template = templates.make_template(a, [], [load]) + moved = _project(_box(100, 0, 0, 40, 20, 10)) # same box elsewhere: still matches + _, loads, missed = templates.apply_template(moved, template) + assert missed == 0 and len(loads[0].faces) == 1 + other = _project(_box(0, 0, 0, 40, 30, 10)) # bigger top face: no match + _, loads, missed = templates.apply_template(other, template) + assert loads == [] and missed == 1 + + +def test_bolted_plates_template_keeps_its_holes(): + project = Project( + parts=[Part(i, f"p{i}", s, "s235") for i, s in enumerate(_solids(bolted_plates()))] + ) + hole = next( + FaceRef(0, i) + for i in range(30) + if templates.signature(project, FaceRef(0, i))["kind"] == "cylinder" + ) + template = templates.make_template(project, [Fixture(FixtureKind.FIXED, [hole])], []) + fixtures, _, _ = templates.apply_template(project, template) + assert len(fixtures[0].faces) >= 6 # three holes in each plate + + +def _solids(shape): + from OCP.TopAbs import TopAbs_SOLID + from OCP.TopExp import TopExp_Explorer + + out = [] + explorer = TopExp_Explorer(shape, TopAbs_SOLID) + while explorer.More(): + out.append(explorer.Current()) + explorer.Next() + return out + + +def test_half_model_with_a_plane_of_symmetry_gives_the_full_stress(): + """A bar pulled at both ends equals half of it pulled at one end with the cut plane + on a symmetry roller; the summary explains what the reactions then mean.""" + half = _box(0, 0, 0, 50, 10, 10) + project = _project(half) + cut = FaceRef(0, face_at(half, (0, 5, 5))) + project.fixtures = [ + Fixture(FixtureKind.ROLLER, [cut], symmetry=True), + Fixture(FixtureKind.ROLLER, [FaceRef(0, face_at(half, (25, 0, 5)))]), + Fixture(FixtureKind.ROLLER, [FaceRef(0, face_at(half, (25, 5, 0)))]), + ] + end = FaceRef(0, face_at(half, (50, 5, 5))) + project.loads = [Load(LoadKind.FORCE, [end], vector=(10_000.0, 0, 0))] + mats = standards.project_materials(project) + mesh = generate_mesh(project, "coarse") + result = solve_static(project, mesh, {0: mats["s235"]}) + assert result.von_mises.max() == pytest.approx(100.0, rel=1e-3) # 10 kN / 100 mm² + summary = summarize(project, result, standards.effective_pack(project)) + assert any(n.startswith("대칭면을 지정해") for n in summary.notes) + + from kstruct.report.describe import describe_fixture + + assert describe_fixture(project, project.fixtures[0]).startswith("대칭면") diff --git a/tests/test_ui.py b/tests/test_ui.py index cb705dd..d305568 100644 --- a/tests/test_ui.py +++ b/tests/test_ui.py @@ -11,7 +11,7 @@ from kstruct.ui import help as kshelp UI_SRC = Path(__file__).parents[1] / "src" / "kstruct" / "ui" # help keys live in UI code -PREFIXES = "step|view|file|help|project|connection|material|fixture|load|mesh|result|analysis|modal|fatigue|bolt" +PREFIXES = "step|view|file|help|project|connection|material|fixture|load|mesh|result|analysis|modal|harmonic|fatigue|bolt" HELP_KEY = rf'"((?:{PREFIXES})\.[a-z_]+)"' @@ -941,10 +941,13 @@ def test_nonlinear_run_from_the_panel(qtbot): panel.plasticity.setChecked(True) assert window.project.plasticity and not window.project.large_deformation assert all(ok for ok, _ in window.readiness()), window.readiness() - # contact is not supported yet: the checklist says so instead of failing mid-run + # frictionless contact is solved; friction is not yet: the checklist says so + # instead of failing mid-run window.project.connections.append(Connection(ConnectionKind.CONTACT, [top], [top])) + assert all(ok for ok, _ in window.readiness()) + window.project.connections[-1].friction = 0.2 blocked = [text for ok, text in window.readiness() if not ok] - assert blocked and "접촉" in blocked[0] + assert blocked and "마찰" in blocked[0] window.project.connections.pop() panel.large.setChecked(True) # both switches together assert window.project.large_deformation diff --git a/tests/test_ui_results.py b/tests/test_ui_results.py index 9c78caa..312b00a 100644 --- a/tests/test_ui_results.py +++ b/tests/test_ui_results.py @@ -124,3 +124,104 @@ def test_mesh_check_tour_and_next_step_hints(qtbot): window._project_changed() window._go(mw.STEP_FIXTURE) assert window.statusBar().currentMessage().startswith("다음에 할 일") + + +def test_vibration_response_in_the_window(qtbot, tmp_path): + from PySide6.QtCore import QPointF, Qt + + from kstruct.model import AnalysisKind + from kstruct.ui import main_window as mw + + window = _solved(qtbot) + project = window.project + project.analysis = AnalysisKind.HARMONIC + project.damping_ratio = 0.02 + window._project_changed() + solve = window.panels[mw.STEP_SOLVE] + solve.refresh() + assert solve.harmonic_box.isVisibleTo(solve) and solve.run.isEnabled() + window.solve() + qtbot.waitUntil(lambda: getattr(window.result, "harmonic", None) is not None, timeout=120_000) + h = window.result.harmonic + panel = window.panels[mw.STEP_RESULT] + assert panel.freq_box.isVisibleTo(panel) and panel.curve_box.isVisibleTo(panel) + assert panel.freq.itemText(0).startswith("가장 불리") + assert window.result.harmonic_frequency == h.governing + assert window.summary.notes[0].startswith("진동 응답") + assert len(panel.curve.freqs) == len(h.frequencies) and panel.curve.selected == h.governing + + panel.freq.setCurrentIndex(1) # the first resonance + assert window.result.harmonic_frequency == pytest.approx(h.natural[0]) + # clicking the curve at its left end: close to 0 Hz, the static response + rect = panel.curve._plot_rect() + qtbot.mouseClick( + panel.curve, + Qt.MouseButton.LeftButton, + pos=QPointF(rect.left(), rect.center().y()).toPoint(), + ) + assert window.result.harmonic_frequency == pytest.approx(h.frequencies[0]) + assert panel.freq.currentText().startswith("고른 진동수") + assert not panel.mesh_check_box.isVisibleTo(panel) + + from kstruct.report.pdf import build_html, write_pdf + + images = window.capture_result_images() + assert images[0][0].startswith("응답 곡선") and images[0][1][:4] == b"\x89PNG" + page = build_html(window.project, window.result, window.summary, images, window.materials) + assert "진동수별 응답" in page and "1차 공진" in page and "모드 중첩" in page + assert write_pdf(page, tmp_path / "vibration.pdf").stat().st_size > 10_000 + + project.analysis = AnalysisKind.STATIC # back to strength: the frequency tools go away + window._project_changed() + window.solve() + qtbot.waitUntil( + lambda: window.result is not None and window.result.harmonic is None, timeout=120_000 + ) + assert not panel.freq_box.isVisibleTo(panel) + + +def test_compare_with_a_reference_result(qtbot): + from kstruct.ui import main_window as mw + + window = _solved(qtbot) + panel = window.panels[mw.STEP_RESULT] + assert panel.compare_box.isVisibleTo(panel) and not panel.compare_diff.isVisibleTo(panel) + window.pin_reference() + assert window.reference is not None and panel.compare_diff.isEnabled() + fos = window.summary.governing_fos + + window.solve() # the same model again: the same mesh, the same answer + qtbot.waitUntil(lambda: window.result is not window.reference[2], timeout=120_000) + panel.compare_diff.setChecked(True) + assert window.compare_view == "diff" + assert window.compare_difference[0] == 0.0 + assert "차이 없음" in panel.compare_text.text() + + # twice the load: the difference map shows the change, the table the numbers + window.project.loads[0].vector = (0, 0, -4000.0) + window._project_changed() + before = window.result + window.solve() + qtbot.waitUntil( + lambda: window.result is not None and window.result is not before, timeout=120_000 + ) + assert window.same_mesh_as_reference() + panel.compare_diff.setChecked(True) + field = window.result_field("vm") + ref = window._with_reference(lambda: window.result.von_mises) + assert field.values == pytest.approx(window.result.von_mises - ref, abs=1e-9) + assert f"{fos:.2f}" in panel.compare_text.text() + assert f"{window.summary.governing_fos:.2f}" in panel.compare_text.text() + panel.compare_ref.setChecked(True) + assert window.compare_view == "ref" and not panel.compare_diff.isChecked() + assert window.result_field("vm").title.startswith("기준") + + window.project.mesh_quality = "normal" # another mesh: numbers only + window.invalidate_mesh() + before = window.result + window.solve() + qtbot.waitUntil( + lambda: window.result is not None and window.result is not before, timeout=120_000 + ) + assert not window.same_mesh_as_reference() and not panel.compare_diff.isEnabled() + assert "숫자만" in panel.compare_text.text() diff --git a/tests/test_ui_tools.py b/tests/test_ui_tools.py index cb0bff2..3a536da 100644 --- a/tests/test_ui_tools.py +++ b/tests/test_ui_tools.py @@ -344,3 +344,35 @@ def test_unheld_part_is_painted_and_the_fix_step_offered(qtbot): assert window.viewer._problem_parts == {1} window._project_changed() # the next edit clears the marking assert window.viewer._problem_parts == set() + + +def test_symmetry_button_and_templates_in_the_window(qtbot, monkeypatch, tmp_path): + from kstruct import paths + from kstruct.geometry.face_info import face_at + from kstruct.model import FaceRef, Fixture, FixtureKind + from kstruct.ui import main_window as mw + + monkeypatch.setattr(paths, "templates_path", lambda: tmp_path / "templates.json") + window = _window(qtbot) + window.warn = lambda text, *a, **k: pytest.fail(text) + window.open_sample("bracket") + window._go(mw.STEP_FIXTURE) + panel = window.panels[mw.STEP_FIXTURE] + shape = window.project.parts[0].shape + back = FaceRef(0, face_at(shape, (0, 30, 40))) + window.viewer.set_selection([back]) + panel.symmetry_btn.click() + (fx,) = window.project.fixtures + assert fx.kind == FixtureKind.ROLLER and fx.symmetry and fx.faces == [back] + assert panel.items.item(0).text().startswith("대칭면") + + window.project.fixtures = [Fixture(FixtureKind.FIXED, [back])] + window.save_template("뒷면 고정") + assert "뒷면 고정" in window.template_names() + window.project.fixtures = [] + assert window.apply_template("뒷면 고정") == (1, 0, 0) + assert window.project.fixtures[0].faces == [back] + assert window.apply_template("자중 (중력 −Z)") == (0, 1, 0) + assert window.project.loads[-1].vector == (0, 0, -9810.0) + window.undo() # a template is one undoable edit + assert not window.project.loads diff --git a/tests/test_unitparse.py b/tests/test_unitparse.py new file mode 100644 index 0000000..389d341 --- /dev/null +++ b/tests/test_unitparse.py @@ -0,0 +1,87 @@ +"""Typed input with units and arithmetic (kstruct/unitparse.py).""" + +import pytest + +from kstruct.unitparse import arithmetic, convert, parse + + +@pytest.mark.parametrize( + ("text", "unit", "value"), + [ + ("12.5", "mm", 12.5), + ("10 kN", "N", 10_000.0), + ("10kN", "N", 10_000.0), + ("2 in", "mm", 50.8), + ("1 ft", "in", 12.0), + ("=1500*9.81", "N", 14_715.0), + ("1500*9.81", "", 14_715.0), + ("(30+12)/2 mm", "mm", 21.0), + ("1,500", "N", 1500.0), + ("2^3", "", 8.0), + ("-4", "°C", -4.0), + ("212 °F", "°C", 100.0), + ("0 °C", "°F", 32.0), + ("300 K", "°C", 26.85), + ("1 ksi", "MPa", 6.894757), + ("100 MPa", "psi", 14_503.77), + ("10 N·m", "N·m", 10.0), + ("5 Nm", "lbf·in", 44.2537), + ("1 kN/mm", "N/mm", 1000.0), + ("3000 rpm", "Hz", 50.0), + ("2 min", "s", 120.0), + ("1e3", "N", 1000.0), + ("1e2 kN", "N", 100_000.0), + ], +) +def test_parse(text, unit, value): + assert parse(text, unit) == pytest.approx(value, rel=1e-6) + + +@pytest.mark.parametrize( + ("text", "unit"), + [ + ("10 kN", "mm"), # another kind of quantity + ("10 parsec", "mm"), # unknown unit + ("10 mm", ""), # the box takes no unit + ("10 mm", "%"), + ("__import__('os')", ""), # not arithmetic + ("abs(-3)", ""), + ("1/0", ""), + ("", "mm"), + ("2**1000", ""), + ("10 k", "N"), # still typing + ], +) +def test_rejected(text, unit): + with pytest.raises(ValueError): + parse(text, unit) + + +def test_round_trip_conversions(): + for a, b in (("mm", "in"), ("N", "lbf"), ("MPa", "psi"), ("°C", "°F"), ("N·m", "lbf·in")): + assert convert(convert(123.4, a, b), b, a) == pytest.approx(123.4, rel=1e-12) + assert arithmetic("2 × 3 ÷ 4") == 1.5 + + +def test_number_box_takes_units_and_arithmetic(qtbot): + from kstruct.ui.unit_spin import UnitSpinBox + + box = UnitSpinBox() + qtbot.addWidget(box) + box.setRange(0, 1e6) + box.setDecimals(2) + box.setSuffix(" N") + for text, value in (("10 kN", 10_000.0), ("=1500*9.81", 14_715.0), ("2 lbf", 8.9)): + box.lineEdit().setText(text) + box.interpretText() + assert box.value() == pytest.approx(value, abs=0.01) + box.lineEdit().setText("3 mm") # another kind of quantity: the value stays + box.interpretText() + assert box.value() == pytest.approx(8.9, abs=0.01) + box.setSuffix(" mm") + box.lineEdit().setText("2 in") + box.interpretText() + assert box.value() == pytest.approx(50.8) + box.setSpecialValueText("자동") + box.setValue(0) + assert box.valueFromText("자동") == 0 diff --git a/uv.lock b/uv.lock index b016586..7521e3a 100644 --- a/uv.lock +++ b/uv.lock @@ -245,7 +245,7 @@ wheels = [ [[package]] name = "kstruct" -version = "0.6.0" +version = "0.7.0" source = { editable = "." } dependencies = [ { name = "cadquery-ocp" },