diff --git a/CLAUDE.md b/CLAUDE.md index e4330a3..9926bc5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -47,6 +47,7 @@ CI(`.github/workflows/build.yml`)가 Windows/macOS/Linux에서 테스트 → PyI - **화면 디자인**(`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`. - **단면·내보내기**: 뷰어는 평소 TRI6 겉면만 그리지만 단면 보기는 `viewer.linear_volume_grid`(TET10을 선형 사면체 8개로 분할; VTK clip은 비선형 셀을 못 다룸)를 잘라 보여준다. VTU 내보내기는 `volume_grid`(VTK 2차 사면체, 중간 절점 순서 `_TET10_TO_VTK`로 재배열 — Netgen과 VTK의 중간 절점 순서가 다르다). 결과 열 정의는 `report/export.py.result_columns` 한 곳. - **3D 뷰 수명**: `ModelViewer`는 `QtInteractor(off_screen=False)`로 만든다 — CI의 headless 액션이 `PYVISTA_OFF_SCREEN=true`를 걸면 기본값으로는 `plotter.iren`이 None이라 선택이 깨진다. 창을 닫을 때 `viewer.shutdown()`으로 렌더 창을 해제한다(안 하면 테스트가 창 수십 개를 열 때 소프트웨어 OpenGL(Xvfb/Mesa)이 `render()`에서 segfault). 로컬 Linux에서 UI 테스트는 `PYVISTA_OFF_SCREEN=true xvfb-run -a uv run pytest`로 CI와 같게 돌린다. - **3D 텍스트 한글**: VTK 기본 글꼴에 한글이 없어 색 막대에 번들 Noto Sans KR(OFL)을 지정한다(`viewer._use_korean_font`). diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 831d8eb..b2f7639 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -373,6 +373,13 @@ OS별 설치 절차(서명 전이면 SmartScreen/Gatekeeper 우회 안내도 필 | | PF-7 설치 파일 | ⚠ Linux tar.gz 609 → 560 MB (안 쓰는 VTK-m·테스트·웹 모듈 제외, VTK 라이브러리 strip). 350 MB 목표는 OCP 284 MB·MKL ~500 MB(CPU별 커널)가 남아 미달 | | | (덤) 배포본 GUI selftest | ✅ 3분 → 10초: 종료 때 '저장할까요?' 창이 떠서 안전 타이머까지 기다리던 문제 | +| v0.6 결과 | UI-1 최대·최소 위치, 변형 배율 직접, 색 범위, 색각 친화 색 | ✅ `ResultField.extreme`, `COLORBLIND_MAPS` | +| | FT-2 재료 바꿔 보기 | ✅ `kstruct/whatif.py` — 재해석과 1e-6 안에서 같음, 정확하지 않으면 이유 + 재해석 제안 | +| | FT-3 하중 케이스 포락 | ✅ `static.envelope`, 케이스 상자 마지막 항목 | +| | FT-1 메시 수렴 확인 | ✅ `kstruct/meshcheck.py` — 인장봉 변화 < 1 %, 예제 브래킷 거침→보통은 안전율 −6 %로 '민감' 표시 | +| | UI-4 결과 패널 정리 | ✅ 표시 설정 접기(판정·근거 먼저) | +| | UX-5 첫 사용 안내 | ✅ 둘러보기(5장, 시작 화면·정보 메뉴), 단계별 '다음에 할 일' | + 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 f7b18ac..55fbf5e 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.5.0 packaging\windows\kstruct.iss +; Build: iscc /DAppVersion=0.6.0 packaging\windows\kstruct.iss #ifndef AppVersion - #define AppVersion "0.5.0" + #define AppVersion "0.6.0" #endif [Setup] diff --git a/pyproject.toml b/pyproject.toml index b25db2c..b5263d2 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -1,6 +1,6 @@ [project] name = "kstruct" -version = "0.5.0" +version = "0.6.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 3bce6a5..1c2c873 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.5.0" # keep in sync with pyproject.toml (tests check) +RELEASE_VERSION = "0.6.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/static.py b/src/kstruct/fem/static.py index 7011592..9169669 100644 --- a/src/kstruct/fem/static.py +++ b/src/kstruct/fem/static.py @@ -494,3 +494,31 @@ def sub(frac, msg, i=i, prefix=prefix): results.append(solve_static(with_case(project, i), mesh, materials, sub, shared=shared)) return results + + +def envelope(results: list[StaticResult]) -> StaticResult: + """The worst of several load cases at every node: the stress state of the case with + the lowest safety factor there (the highest von Mises stress for ductile parts) and + the largest displacement. Reactions, bolt forces and contact states belong to single + cases and are left out.""" + first = results[0] + fos = np.stack([r.safety_factor for r in results]) # (cases, N) + weakest = np.argmin(fos, axis=0) + # where every case is capped (FOS_CAP, next to no stress) the factors tie: take the + # most stressed case there, not simply the first + capped = fos.min(axis=0) >= FOS_CAP + if capped.any(): + vm = np.stack([r.von_mises for r in results]) + weakest[capped] = np.argmax(vm[:, capped], axis=0) + nodes = np.arange(first.mesh.n_nodes) + stress = np.stack([r.stress for r in results])[weakest, nodes] + disp = np.stack([r.displacement for r in results]) + largest = np.argmax(np.linalg.norm(disp, axis=2), axis=0) + return StaticResult( + mesh=first.mesh, + materials=first.materials, + displacement=disp[largest, nodes], + stress=stress, + reactions=[np.zeros(3) for _ in first.reactions], + applied_load=np.zeros(3), + ) diff --git a/src/kstruct/meshcheck.py b/src/kstruct/meshcheck.py new file mode 100644 index 0000000..1a4821f --- /dev/null +++ b/src/kstruct/meshcheck.py @@ -0,0 +1,59 @@ +"""Mesh convergence check: solve the same load case again on the next finer mesh and say +how much the numbers the verdict rests on moved. A change of a few percent means the +mesh is fine enough; more means the answer still depends on the mesh. + +The governing safety factor is compared (for ductile parts it excludes the stress +singularities, whose peak keeps growing with every refinement and means nothing), and +the largest displacement. +""" + +from __future__ import annotations + +from dataclasses import dataclass + +from kstruct.fem.mesh import MESH_PRESETS + +SENSITIVE = 0.05 # relative change above which the result is called mesh-dependent +ORDER = list(MESH_PRESETS) + + +def finer(quality: str) -> str | None: + """The next finer mesh preset, None for the finest.""" + i = ORDER.index(quality) + return ORDER[i + 1] if i + 1 < len(ORDER) else None + + +@dataclass +class MeshCheck: + quality: str # the mesh the result was solved on + finer: str # the mesh it was checked against + elements: tuple[int, int] + fos: tuple[float, float] # governing safety factor, current / finer + disp: tuple[float, float] # largest displacement (mm) + singular_peak: tuple[float, float] | None # raw peak stress where it is singular + + @staticmethod + def change(pair: tuple[float, float]) -> float: + a, b = pair + return (b - a) / a if a else 0.0 + + @property + def sensitive(self) -> bool: + return max(abs(self.change(self.fos)), abs(self.change(self.disp))) > SENSITIVE + + +def compare(quality, finer_quality, mesh, finer_mesh, summary, finer_summary) -> MeshCheck: + peak = None + if any(p.hotspot_stress is not None for p in summary.parts): + peak = ( + max(p.max_stress for p in summary.parts), + max(p.max_stress for p in finer_summary.parts), + ) + return MeshCheck( + quality, + finer_quality, + (len(mesh.tets), len(finer_mesh.tets)), + (summary.governing_fos, finer_summary.governing_fos), + (summary.max_disp, finer_summary.max_disp), + peak, + ) diff --git a/src/kstruct/resources/help/en.json b/src/kstruct/resources/help/en.json index 12f788b..0f87c72 100644 --- a/src/kstruct/resources/help/en.json +++ b/src/kstruct/resources/help/en.json @@ -204,7 +204,7 @@ "result.scale": { "title": "Deformation display", "short": "Sets how much the deformed shape is exaggerated.", - "detail": "The actual deformation is usually too small to see, so 'Auto scale' enlarges it tens to thousands of times so the shape is easy to see (the scale factor is shown in the color bar title). 'True scale' shows it without enlargement. The gray lines show the shape before deformation." + "detail": "The actual deformation is usually too small to see, so 'Auto scale' enlarges it tens to thousands of times so the shape is easy to see (the scale factor is shown in the color bar title). 'True scale' shows it without enlargement. The gray lines show the shape before deformation.

'Custom scale' lets you type the magnification yourself (it starts at the automatic one)." }, "result.report": { "title": "Save report", @@ -604,5 +604,43 @@ "title": "Clear selection", "short": "Deselects all faces (shortcut Esc).", "detail": "Also turns box select off. Clicking an empty spot in the 3D view clears the selection too." + }, + "result.markers": { + "title": "Mark the largest and smallest", + "short": "Labels the spot where the shown value is largest (smallest for safety factors) with its value.", + "detail": "Stress, deformation and temperature get the maximum, safety factor and fatigue life the weakest minimum, and signed values (deformation X, Y, Z, max principal stress) both ends. With a section view it searches the cut face and the kept half's outer surface.

When the peak stress sits on a sharp corner (a singularity), that value keeps growing with the mesh: judge by the 'excluding singularities' value on the verdict card.", + "related": [ + "result.hotspot", + "result.field" + ] + }, + "result.range": { + "title": "Set the color range", + "short": "Sets the minimum and maximum of the color bar yourself, e.g. to compare two results on the same scale.", + "detail": "When you turn it on, the boxes hold the current automatic range; change them as you like. Values outside the range get the end colors. Choosing another result type returns to the automatic range." + }, + "result.colorblind": { + "title": "Color-blind friendly colors", + "short": "Uses color maps that stay readable without telling red from green (cividis, red-yellow-blue).", + "detail": "The rainbow map becomes the blue-yellow cividis, and the red-yellow-green of safety factors becomes red-yellow-blue. The choice is saved on this computer." + }, + "result.display": { + "title": "Display settings", + "short": "Opens animation, max/min markers, color range, color-blind friendly colors and the section view.", + "detail": "The less used display settings are folded away so the verdict and its reasons come first. Turning on the section view or the color range unfolds them." + }, + "result.mesh_check": { + "title": "Mesh check", + "short": "Solves the same load case once more on the next finer mesh and shows how much the governing safety factor and the largest deformation change.", + "detail": "Finite element results depend a little on the mesh (element size). If one step finer changes them by less than 5%, the current mesh is fine enough; more means the result still depends on the mesh, so choose a finer mesh in step 5 or refine just the faces with high stress.

The peak stress at a sharp corner (a singularity) grows without end as the mesh gets finer, so it is reported separately and not compared. The verdict uses the 'excluding singularities' value.

The current result and mesh stay as they are; this only compares. It takes a little longer than one analysis.", + "related": [ + "mesh.quality", + "result.hotspot" + ] + }, + "result.material_trial": { + "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." } } diff --git a/src/kstruct/resources/help/ko.json b/src/kstruct/resources/help/ko.json index 5493d4a..661fb26 100644 --- a/src/kstruct/resources/help/ko.json +++ b/src/kstruct/resources/help/ko.json @@ -204,7 +204,7 @@ "result.scale": { "title": "변형 표시", "short": "변형된 모양을 얼마나 과장해서 보여줄지 정합니다.", - "detail": "실제 변형은 보통 너무 작아 눈에 안 보이므로, '자동 확대'는 모양이 잘 보이도록 수십~수천 배 키워서 보여줍니다(배율은 색 막대 제목에 표시). '실제 크기'는 확대하지 않습니다. 회색 선은 변형 전 모양입니다." + "detail": "실제 변형은 보통 너무 작아 눈에 안 보이므로, '자동 확대'는 모양이 잘 보이도록 수십~수천 배 키워서 보여줍니다(배율은 색 막대 제목에 표시). '실제 크기'는 확대하지 않습니다. 회색 선은 변형 전 모양입니다.

'배율 직접'을 고르면 몇 배로 보여줄지 직접 적습니다(처음 값은 자동 확대 배율)." }, "result.report": { "title": "보고서 저장", @@ -604,5 +604,43 @@ "title": "선택 해제", "short": "고른 면을 모두 해제합니다 (단축키 Esc).", "detail": "영역 선택이 켜져 있으면 함께 끕니다. 3D 화면의 빈 곳을 클릭해도 선택이 풀립니다." + }, + "result.markers": { + "title": "최대·최소 위치 표시", + "short": "지금 보는 값이 가장 큰 곳(안전율은 가장 작은 곳)에 값과 함께 표시를 붙입니다.", + "detail": "응력·변형·온도는 최대, 안전율·피로 수명은 가장 약한 최소, 방향이 있는 값(변형량 X·Y·Z, 최대 주응력)은 양쪽 끝을 모두 표시합니다. 단면 보기에서는 화면에 보이는 단면과 남은 쪽 겉면에서 찾습니다.

응력의 최대가 날카로운 모서리(특이점)에 있으면 그 값은 메시에 따라 계속 커지므로, 판정은 결과 카드의 '특이점 제외' 값을 보세요.", + "related": [ + "result.hotspot", + "result.field" + ] + }, + "result.range": { + "title": "색 범위 직접 정하기", + "short": "색 막대의 최소·최대를 직접 정합니다. 두 결과를 같은 색 기준으로 비교할 때 씁니다.", + "detail": "켜면 지금 자동 범위가 입력 칸에 들어가니 원하는 값으로 고치세요. 범위를 벗어난 값은 양 끝 색으로 칠해집니다. 다른 결과 종류(보기)를 고르면 자동 범위로 돌아갑니다." + }, + "result.colorblind": { + "title": "색각 이상에도 잘 보이는 색", + "short": "빨강·초록을 구분하기 어려워도 읽히는 색 지도(cividis, 빨강-노랑-파랑)를 씁니다.", + "detail": "켜면 무지개 색 지도는 파랑-노랑의 cividis로, 안전율의 빨강-노랑-초록은 빨강-노랑-파랑으로 바뀝니다. 선택은 이 컴퓨터에 저장됩니다." + }, + "result.display": { + "title": "표시 설정", + "short": "움직임(애니메이션), 최대·최소 표시, 색 범위, 색각 친화 색, 단면 보기를 엽니다.", + "detail": "자주 쓰지 않는 표시 설정을 접어 두어 판정과 근거가 먼저 보이게 했습니다. 단면 보기나 색 범위를 켜면 저절로 펼쳐집니다." + }, + "result.mesh_check": { + "title": "메시 확인", + "short": "같은 하중 케이스를 한 단계 더 세밀한 메시로 다시 풀어, 판정 안전율과 최대 변형이 얼마나 바뀌는지 보여 줍니다.", + "detail": "유한요소 결과는 메시(요소 크기)에 따라 조금씩 달라집니다. 한 단계 세밀하게 풀었을 때 변화가 5% 이내면 지금 메시로 충분하고, 넘으면 결과가 아직 메시에 따라 달라진다는 뜻이니 5단계에서 더 세밀한 메시를 고르거나 응력이 큰 면만 세밀하게 하세요.

날카로운 모서리(특이점)의 최대 응력은 메시를 세밀하게 할수록 끝없이 커지는 값이라 비교하지 않고 따로 알려 줍니다. 판정은 '특이점 제외' 값으로 합니다.

지금 결과와 메시는 그대로 두고 비교만 합니다. 시간은 해석 한 번보다 조금 더 걸립니다.", + "related": [ + "mesh.quality", + "result.hotspot" + ] + }, + "result.material_trial": { + "title": "재료 바꿔 보기", + "short": "다른 재료였다면 판정이 어떻게 되는지 봅니다. 가능하면 다시 해석하지 않고 바로 보여 줍니다.", + "detail": "모든 부품이 한 재료이고 선형 해석이면, 재료를 바꿔도 응력 분포는 그대로이고 변형만 탄성계수 비율만큼 달라지므로 다시 풀지 않고 판정(안전율·피로)만 새로 합니다. 같은 계열(예: 강철끼리, 알루미늄끼리)처럼 푸아송비가 같아야 합니다.

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

'이 재료로 확정'을 누르면 프로젝트의 재료도 바뀌고 결과는 그대로 유효합니다." } } diff --git a/src/kstruct/resources/i18n/en/core.json b/src/kstruct/resources/i18n/en/core.json index d0ad942..cc9fdbe 100644 --- a/src/kstruct/resources/i18n/en/core.json +++ b/src/kstruct/resources/i18n/en/core.json @@ -108,5 +108,13 @@ "하중을 뺀 뒤 남는 변형 계산 중": "Computing the deformation left after unloading", "하중을 줄 면이 메시에 없습니다. 메시를 다시 만들어 주세요.": "A loaded face is not in the mesh. Please create the mesh again.", "하중의 축 방향이 정해지지 않았습니다. 하중을 다시 추가해 주세요.": "The load has no axis direction. Please add the load again.", - "하중이 없습니다. 힘, 압력, 중력 또는 온도 하중을 추가하세요.": "There are no loads. Add a force, pressure, gravity or temperature load." + "하중이 없습니다. 힘, 압력, 중력 또는 온도 하중을 추가하세요.": "There are no loads. Add a force, pressure, gravity or temperature load.", + "항복·대변형 해석은 재료에 따라 응력 분포가 달라집니다.": "With yielding or large deformation the stresses depend on the material.", + "부품마다 재료가 달라 강성 비율이 바뀝니다.": "The parts have different materials, so their stiffness ratio changes.", + "푸아송비가 달라({old:.2f} → {new:.2f}) 응력 분포가 조금 바뀝니다.": "Poisson's ratio differs ({old:.2f} → {new:.2f}), which changes the stresses a little.", + "열응력은 탄성계수와 열팽창계수에 따라 달라집니다.": "Thermal stress depends on the stiffness and the thermal expansion.", + "자중·원심력은 밀도에 비례합니다.": "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." } diff --git a/src/kstruct/resources/i18n/en/main.json b/src/kstruct/resources/i18n/en/main.json index a12d74d..6d010db 100644 --- a/src/kstruct/resources/i18n/en/main.json +++ b/src/kstruct/resources/i18n/en/main.json @@ -214,5 +214,51 @@ "이 부품만 보기": "Show only this part", "이 부품 숨기기 (화면에서만)": "Hide this part (view only)", "반투명 (클릭이 통과)": "See-through (clicks pass through)", - "모든 부품 다시 보이기": "Show all parts again" + "모든 부품 다시 보이기": "Show all parts again", + "다음에 할 일: 부품마다 재료를 고르세요.": "Next: choose a material for each part.", + "다음에 할 일: 3D 화면에서 붙잡힌 면(볼트 구멍·바닥 등)을 클릭하고 '선택한 면을 고정'을 누르세요.": "Next: click the faces that are held (bolt holes, base, ...) in the 3D view and press 'Fix selected faces'.", + "다음에 할 일: 힘을 받는 면을 클릭하고 종류·크기·방향을 정한 뒤 '하중 추가'를 누르세요.": "Next: click the faces the load acts on, set its type, size and direction, then press 'Add load'.", + "다음에 할 일: '메시 만들기'를 누르세요. 바로 6단계로 가도 메시는 자동으로 만들어집니다.": "Next: press 'Create mesh'. You can also go straight to step 6: the mesh is made automatically.", + "다음에 할 일: 확인 목록이 모두 ✔이면 '해석 시작'(F5)을 누르세요.": "Next: when every checklist item shows ✔, press 'Start analysis' (F5).", + "포락 (케이스별 최악값)": "Envelope (worst of all cases)", + "이미 가장 세밀한 메시입니다. 5단계에서 응력이 큰 면만 더 세밀하게 할 수 있습니다.": "This is already the finest mesh. In step 5 you can refine just the faces with high stress.", + "더 세밀한 메시 만드는 중": "Creating a finer mesh", + "다시 계산 중": "Solving again", + "메시 확인 중: {message}": "Checking the mesh: {message}", + "메시 확인을 취소했습니다.": "Mesh check cancelled.", + "메시 확인 ({q0} → {q1}, 요소 {n0:,} → {n1:,}개): 안전율 {f0:.2f} → {f1:.2f} ({df:+.1f}%), 최대 변형 {d0} → {d1} ({dd:+.1f}%).": "Mesh check ({q0} → {q1}, {n0:,} → {n1:,} elements): safety factor {f0:.2f} → {f1:.2f} ({df:+.1f}%), largest deformation {d0} → {d1} ({dd:+.1f}%).", + "5% 넘게 달라졌습니다: 메시에 따라 달라지는 결과입니다. 5단계에서 더 세밀한 메시를 고르거나 응력이 큰 면을 세밀하게 해서 다시 풀어 보세요.": "It changed by more than 5%: the result still depends on the mesh. Choose a finer mesh in step 5, or refine the faces with high stress, and solve again.", + "변화가 5% 이내라 지금 메시로 충분합니다.": "It changed by less than 5%: the current mesh is fine enough.", + "특이점의 최대 응력({p0} → {p1})은 메시를 바꿀 때마다 계속 커지는 값이라 판정에 쓰지 않습니다.": "The peak stress at the singularity ({p0} → {p1}) keeps growing with every refinement, so it is not used for the verdict.", + "이 모델은 재료만 바꿔 다시 판정할 수 없습니다: {reason}\n\n'{material}'(으)로 바꿔 다시 해석할까요?": "This model cannot be re-judged by swapping the material alone: {reason}\n\nChange to '{material}' and run the analysis again?", + "재료를 '{material}'(으)로 바꿔 본 결과입니다. 응력 분포는 그대로이고 변형은 탄성계수 비율만큼 달라집니다(다시 해석하지 않음). 프로젝트에 반영하려면 '이 재료로 확정'을 누르세요.": "This is the result with the material changed to '{material}'. The stresses are the same and the deformation scales with the stiffness ratio (no new analysis). Press 'Use this material' to keep it in the project.", + "'{material}' 기준으로 다시 판정했습니다.": "Judged again for '{material}'.", + "포락: 케이스 {n}개 중 절점마다 가장 불리한 응력과 가장 큰 변형을 모아 보여 줍니다. 반력·볼트 축력은 케이스별로 보세요.": "Envelope: at every point, the worst stress and the largest deformation of the {n} load cases. See the single cases for reactions and bolt forces.", + "재료를 바꿨습니다. 결과는 그대로 유효합니다.": "Material changed. The result stays valid.", + "포락": "Envelope", + "처음이라면: 1분 둘러보기": "New here? Take the 1-minute tour", + "둘러보기 (화면 안내)": "Tour of the window", + "1~7단계": "Steps 1-7", + "위쪽의 단계를 차례로 따라가면 됩니다. 입력이 끝난 단계에는 체크가 붙고, 단계 이름을 눌러 언제든 돌아갈 수 있습니다 (Alt+1~7).": "Follow the steps at the top in order. A finished step gets a tick, and you can go back to any step by clicking it (Alt+1-7).", + "입력 패널": "Input panel", + "지금 단계의 입력을 여기서 합니다. 항목 옆의 ? 를 누르면 쉬운 설명이 나오고, 아래 상태 표시줄이 다음에 할 일을 알려 줍니다.": "This is where you enter the current step. The ? beside an item explains it in plain words, and the status bar at the bottom says what to do next.", + "3D 화면": "3D view", + "왼쪽 끌기로 돌리고, 휠로 확대하고, 면을 클릭해 고릅니다. 위쪽 막대에 보는 방향(0·1·3·7 키), 반투명, 여러 면을 한 번에 고르는 도구가 있습니다. 부품을 오른쪽 클릭하면 그 부품만 볼 수 있습니다.": "Drag with the left button to rotate, use the wheel to zoom and click a face to select it. The bar above has view directions (keys 0, 1, 3, 7), see-through and tools that select many faces at once. Right-click a part to show only that part.", + "입력이 끝나면 '다음 단계'를 누르세요. 6단계에서 해석을 시작하면 7단계에 판정과 색 지도가 나옵니다.": "When a step is done, press 'Next step'. Start the analysis in step 6 and step 7 shows the verdict and the color map.", + "도움말과 저장": "Help and saving", + "막히면 F1(사용 안내), Ctrl+/(단축키 목록), 이 정보 메뉴의 '질문·아이디어'를 쓰세요. 저장은 Ctrl+S, 되돌리기는 Ctrl+Z입니다. 이제 예제 브래킷으로 2단계(재료)부터 해 보세요.": "If you get stuck: F1 (user guide), Ctrl+/ (keyboard shortcuts) and 'Questions and ideas' in this info menu. Save with Ctrl+S, undo with Ctrl+Z. Now try the sample bracket, starting with step 2 (material).", + "배율 직접": "Custom scale", + "최대·최소 위치 표시": "Mark the largest and smallest", + "색 범위 직접 정하기": "Set the color range", + "최대": "Max", + "최소": "Min", + "색각 이상에도 잘 보이는 색": "Color-blind friendly colors", + "표시 설정 더 보기": "More display settings", + "메시 확인 (한 단계 세밀하게 다시 풀어 비교)": "Check the mesh (solve once more, finer)", + "재료 바꿔 보기": "Try another material", + "이 재료로 판정해 보기": "Judge with this material", + "이 재료로 확정": "Use this material", + "다음": "Next", + "그만 보기": "Close", + "시작하기": "Get started" } diff --git a/src/kstruct/ui/main_window.py b/src/kstruct/ui/main_window.py index 3761cb5..6d1dc69 100644 --- a/src/kstruct/ui/main_window.py +++ b/src/kstruct/ui/main_window.py @@ -34,13 +34,13 @@ QWidget, ) -from kstruct import diagnose, i18n, standards +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.mesh import FEMesh from kstruct.fem.modal import ModalResult, solve_modal from kstruct.fem.nonlinear import unsupported as nonlinear_unsupported -from kstruct.fem.static import StaticResult, solve_cases +from kstruct.fem.static import StaticResult, envelope, solve_cases, solve_static from kstruct.fem.thermal import ThermalResult, solve_thermal from kstruct.geometry import GeometryImportError, load_cad from kstruct.geometry.contacts import find_touching_faces @@ -129,6 +129,19 @@ N_("7. 결과"), ] THERMAL_FIELDS = [("temp", N_("온도")), ("flux", N_("열 흐름 (열유속)"))] +# shown in the status bar when a step is opened and its input is still missing +NEXT_HINTS = { + 1: N_("다음에 할 일: 부품마다 재료를 고르세요."), + 2: N_( + "다음에 할 일: 3D 화면에서 붙잡힌 면(볼트 구멍·바닥 등)을 클릭하고 " + "'선택한 면을 고정'을 누르세요." + ), + 3: N_("다음에 할 일: 힘을 받는 면을 클릭하고 종류·크기·방향을 정한 뒤 '하중 추가'를 누르세요."), + 4: N_( + "다음에 할 일: '메시 만들기'를 누르세요. 바로 6단계로 가도 메시는 자동으로 만들어집니다." + ), + 5: N_("다음에 할 일: 확인 목록이 모두 ✔이면 '해석 시작'(F5)을 누르세요."), +} STEP_KEYS = [ "step.open", "step.material", @@ -188,6 +201,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 + 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 + self.showing_envelope = False self._solved_quality: str | None = None # mesh preset the current result used self._dirty = False # unsaved changes (drives autosave and the close prompt) self.ask_before_close = True # tests switch the "save changes?" prompt off @@ -209,6 +226,7 @@ def __init__(self) -> None: app.setWindowIcon(self.windowIcon()) self.viewer = ModelViewer() self.viewer.apply_theme(self.theme) + self.viewer.colorblind = prefs.colorblind() self.viewer.selection_changed.connect(self._selection_changed) self.viewer.probed.connect(lambda text: self.panels[STEP_RESULT].probe.setText(text)) self.viewer.notice.connect(lambda text: self.statusBar().showMessage(text, 8000)) @@ -349,6 +367,12 @@ def _build_welcome(self) -> QWidget: formats.setProperty("role", "hint") box.addWidget(formats) + tour = QPushButton(tr("처음이라면: 1분 둘러보기")) + tour.setFlat(True) + tour.setCursor(Qt.CursorShape.PointingHandCursor) + tour.clicked.connect(self.start_tour) + box.addWidget(tour) + box.addSpacing(10) section = QLabel(tr("예제로 시작하기")) section.setProperty("role", "section") @@ -511,6 +535,7 @@ def action(text, slot, key=None, shortcut=None, icon=None, icon_only=False): info_menu.addAction(tr("KStruct 정보"), lambda: AboutDialog(self).exec()) info_menu.addAction(tr("사용 안내"), lambda: HelpDialog("help.mode", self).exec()) info_menu.addAction(tr("단축키 목록"), self.show_shortcuts) + info_menu.addAction(tr("둘러보기 (화면 안내)"), self.start_tour) info_menu.addAction(tr("업데이트 확인…"), self.show_update) info_menu.addSeparator() info_menu.addAction(tr("오류 신고 (GitHub 이슈)"), lambda: open_contact(self)) @@ -526,6 +551,64 @@ def action(text, slot, key=None, shortcut=None, icon=None, icon_only=False): self.info_button.setMenu(info_menu) bar.addWidget(self.info_button) + def start_tour(self) -> None: + """A one-minute guided tour of the window (opens the sample bracket first when + nothing is open, so there is something to point at).""" + from kstruct.ui.tour import Tour + + if self.project is None: + self.open_sample("bracket") + if self.project is None: + return + self._go(STEP_OPEN) + steps_ = [ + ( + lambda: self.nav, + tr("1~7단계"), + tr( + "위쪽의 단계를 차례로 따라가면 됩니다. 입력이 끝난 단계에는 체크가 붙고, " + "단계 이름을 눌러 언제든 돌아갈 수 있습니다 (Alt+1~7)." + ), + ), + ( + lambda: self.stack, + tr("입력 패널"), + tr( + "지금 단계의 입력을 여기서 합니다. 항목 옆의 ? 를 누르면 쉬운 설명이 " + "나오고, 아래 상태 표시줄이 다음에 할 일을 알려 줍니다." + ), + ), + ( + lambda: self.viewer.strip, + tr("3D 화면"), + tr( + "왼쪽 끌기로 돌리고, 휠로 확대하고, 면을 클릭해 고릅니다. 위쪽 막대에 " + "보는 방향(0·1·3·7 키), 반투명, 여러 면을 한 번에 고르는 도구가 있습니다. " + "부품을 오른쪽 클릭하면 그 부품만 볼 수 있습니다." + ), + ), + ( + lambda: self.next_btn, + tr("다음 단계"), + tr( + "입력이 끝나면 '다음 단계'를 누르세요. 6단계에서 해석을 시작하면 " + "7단계에 판정과 색 지도가 나옵니다." + ), + ), + ( + lambda: self.info_button, + tr("도움말과 저장"), + tr( + "막히면 F1(사용 안내), Ctrl+/(단축키 목록), 이 정보 메뉴의 '질문·아이디어'를 " + "쓰세요. 저장은 Ctrl+S, 되돌리기는 Ctrl+Z입니다. 이제 예제 브래킷으로 " + "2단계(재료)부터 해 보세요." + ), + ), + ] + self._tour = Tour(self, steps_) + self._tour.finished.connect(lambda: setattr(self, "_tour", None)) + self._tour.start() + def _build_shortcuts(self) -> None: """Keyboard shortcuts without a button of their own (the toolbar's and the 3D view's actions carry theirs).""" @@ -690,6 +773,12 @@ def _update_available(self, release) -> None: def show_update(self) -> None: UpdateDialog(self, self._pending_release).exec() + def set_colorblind(self, on: bool) -> None: + """Result colour maps readable with red-green colour blindness (remembered).""" + prefs.set_colorblind(on) + self.viewer.colorblind = bool(on) + self.show_result() + def toggle_theme(self) -> None: """Switch between the light and the dark look and remember the choice.""" name = "dark" if self.theme.name == "light" else "light" @@ -912,6 +1001,8 @@ def _nav_changed(self, step: int) -> None: self.show_result() self._update_nav() self._fit_side() + if self.project is not None and step in NEXT_HINTS and not self._step_done(step): + self.statusBar().showMessage(tr(NEXT_HINTS[step]), 12000) # --- project lifecycle ----------------------------------------------------------- @@ -1068,6 +1159,10 @@ def invalidate_mesh(self) -> None: self._record() def _invalidate_result(self) -> None: + self._trial_material = None + self._mesh_check_line = None + self._envelope = None + self.showing_envelope = False if self.summary is not None: # remember what the run being discarded came to self.previous = self._key_numbers() or self.previous self.result = self.summary = None @@ -1367,6 +1462,10 @@ def job(progress): def done(value): self._busy = False self._job = None + self._trial_material = None + self._mesh_check_line = None + self._envelope = None + self.showing_envelope = False self.previous = self._key_numbers() or self.previous # solved again unchanged self._solved_quality = project.mesh_quality self.mesh, self.result = value @@ -1456,17 +1555,217 @@ def _configure_result_panel(self) -> None: + (tr(" ◀ 가장 불리") if self.overview and i == self.overview.worst else "") for i, (name, _, s) in enumerate(self.case_results) ] - panel.set_cases(labels, self.project.active_case) + labels.append(tr("포락 (케이스별 최악값)")) + current = len(self.case_results) if self.showing_envelope else self.project.active_case + panel.set_cases(labels, current) else: panel.set_cases(None) has_shape = not isinstance(r, ThermalResult) panel.scale.setEnabled(has_shape) panel.animate.setEnabled(has_shape) + self._fill_material_trial(panel) + linear = isinstance(r, StaticResult) and r.nonlinear 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 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).""" + r = self.result + if self._busy or not isinstance(r, StaticResult) or r.nonlinear is not None: + return + panel: steps.ResultStep = self.panels[STEP_RESULT] + quality = self._solved_quality or self.project.mesh_quality + target = meshcheck.finer(quality) + if target is None: + panel.mesh_check_text.setText( + tr( + "이미 가장 세밀한 메시입니다. 5단계에서 응력이 큰 면만 더 세밀하게 할 수 있습니다." + ) + ) + return + project = active_project(self.project) + case = with_case(project, project.active_case) + materials, mesh, summary = r.materials, self.mesh, self.summary + pack = standards.effective_pack(project) + self._busy = True + panel.mesh_check.setEnabled(False) + + def job(progress): + progress(0.05, tr("더 세밀한 메시 만드는 중")) + finer_mesh = generate_mesh(project, target, check=progress.check) + progress(0.5, tr("다시 계산 중")) + finer = solve_static(case, finer_mesh, materials) + return finer_mesh, summarize(case, finer, pack) + + def show_progress(fraction: float, message: str) -> None: + panel.mesh_check_text.setText(tr("메시 확인 중: {message}", message=message)) + + def done(value): + self._busy = False + self._job = None + finer_mesh, finer_summary = value + check = meshcheck.compare(quality, target, mesh, finer_mesh, summary, finer_summary) + self._mesh_check_line = self._mesh_check_text(check) + panel.mesh_check.setEnabled(True) + panel.mesh_check_text.setText(self._mesh_check_line) + + def failed(e): + self._busy = False + self._job = None + panel.mesh_check.setEnabled(True) + if isinstance(e, Cancelled): + panel.mesh_check_text.setText(tr("메시 확인을 취소했습니다.")) + return + panel.mesh_check_text.setText("") + self.warn(friendly_error(e)) + + self._job = run_job(job, done, failed, show_progress) + + def _mesh_check_text(self, c: meshcheck.MeshCheck) -> str: + us = system_of(self.project) + text = tr( + "메시 확인 ({q0} → {q1}, 요소 {n0:,} → {n1:,}개): 안전율 {f0:.2f} → " + "{f1:.2f} ({df:+.1f}%), 최대 변형 {d0} → {d1} ({dd:+.1f}%).", + q0=tr(steps.QUALITY_NAMES[c.quality]), + q1=tr(steps.QUALITY_NAMES[c.finer]), + n0=c.elements[0], + n1=c.elements[1], + f0=c.fos[0], + f1=c.fos[1], + df=c.change(c.fos) * 100, + d0=fmt(us, "length", c.disp[0]), + d1=fmt(us, "length", c.disp[1]), + dd=c.change(c.disp) * 100, + ) + if c.sensitive: + text += " " + tr( + "5% 넘게 달라졌습니다: 메시에 따라 달라지는 결과입니다. 5단계에서 더 " + "세밀한 메시를 고르거나 응력이 큰 면을 세밀하게 해서 다시 풀어 보세요." + ) + else: + text += " " + tr("변화가 5% 이내라 지금 메시로 충분합니다.") + if c.singular_peak is not None: + text += " " + tr( + "특이점의 최대 응력({p0} → {p1})은 메시를 바꿀 때마다 계속 커지는 값이라 " + "판정에 쓰지 않습니다.", + p0=fmt(us, "stress", c.singular_peak[0], ",.0f"), + p1=fmt(us, "stress", c.singular_peak[1], ",.0f"), + ) + return text + + def _fill_material_trial(self, panel: steps.ResultStep) -> None: + """'재료 바꿔 보기': strength results of a model made of one material.""" + r = self.result + ok = isinstance(r, StaticResult) and len({m.id for m in r.materials.values()}) == 1 + panel.trial_box.setVisible(ok) + if not ok: + return + current = next(iter(r.materials.values())).id + panel.trial_material.blockSignals(True) + panel.trial_material.clear() + for mid, m in standards.project_materials(self.project).items(): + panel.trial_material.addItem(tr_data(m.name), mid) + panel.trial_material.setCurrentIndex(max(0, panel.trial_material.findData(current))) + panel.trial_material.blockSignals(False) + panel.trial_keep.setEnabled(self._trial_material is not None) + + def try_material(self, material_id: str | None) -> None: + """Show the strength result as if every part were made of another material. + Exact without a new analysis for a linear one-material model (whatif.py); + otherwise say why and leave the result alone.""" + if material_id is None or not self.case_results: + return + project = active_project(self.project) + new = standards.project_materials(self.project)[material_id] + pack = standards.effective_pack(project) + back_to_own = {p.material_id for p in project.parts} == {material_id} + swapped = [] + for i, (name, r, _) in enumerate(self.case_results): + tried, reason = whatif.swap_material(with_case(project, i), r, new) + if tried is None: + if self._confirm( + tr( + "이 모델은 재료만 바꿔 다시 판정할 수 없습니다: {reason}\n\n" + "'{material}'(으)로 바꿔 다시 해석할까요?", + reason=reason, + material=tr_data(new.name), + ) + ): + for part in self.project.visible_parts(): + part.material_id = material_id + self._project_changed() + self._go(STEP_SOLVE) + self.solve() + return + summary = summarize(with_case(project, i), tried, pack) + if back_to_own: + swapped.append((name, tried, summary)) + continue + summary.notes.insert( + 0, + tr( + "재료를 '{material}'(으)로 바꿔 본 결과입니다. 응력 분포는 그대로이고 " + "변형은 탄성계수 비율만큼 달라집니다(다시 해석하지 않음). 프로젝트에 " + "반영하려면 '이 재료로 확정'을 누르세요.", + material=tr_data(new.name), + ), + ) + swapped.append((name, tried, summary)) + self._trial_material = None if back_to_own else material_id + self.case_results = swapped + self._envelope = None + self.showing_envelope = False + names = [name for name, _, _ in swapped] + summaries = [s for _, _, s in swapped] + self.overview = compare_cases(names, summaries) if len(names) > 1 else None + index = min(self.project.active_case, len(swapped) - 1) + _, self.result, self.summary = swapped[index] + self.materials = self.result.materials + self._configure_result_panel() + self.show_result() + self.statusBar().showMessage( + tr("'{material}' 기준으로 다시 판정했습니다.", material=tr_data(new.name)), 8000 + ) + + def envelope_result(self) -> tuple[StaticResult, Summary]: + """(result, summary) of the worst value of every load case at every node.""" + if self._envelope is None: + project = active_project(self.project) + result = envelope([r for _, r, _ in self.case_results]) + summary = summarize(project, result, standards.effective_pack(project)) + summary.notes.insert( + 0, + tr( + "포락: 케이스 {n}개 중 절점마다 가장 불리한 응력과 가장 큰 변형을 모아 " + "보여 줍니다. 반력·볼트 축력은 케이스별로 보세요.", + n=len(self.case_results), + ), + ) + self._envelope = (result, summary) + return self._envelope + + def keep_trial_material(self) -> None: + """Make the tried material the parts' material; the result already shows it.""" + if self._trial_material is None or self.project is None: + return + for part in self.project.visible_parts(): + part.material_id = self._trial_material + self._trial_material = None + for _, _, summary in self.case_results or []: + if summary.notes: + summary.notes.pop(0) # no longer a trial + self._dirty = True + self._record() + self._configure_result_panel() + self.show_result() + self.statusBar().showMessage(tr("재료를 바꿨습니다. 결과는 그대로 유효합니다."), 8000) def _key_numbers(self) -> dict | None: """What the last strength run came to, kept for the comparison line.""" s, p, r = self.summary, self.project, self.result - if s is None or not isinstance(s, Summary) or r is None: + if s is None or not isinstance(s, Summary) or r is None or self.showing_envelope: return None quality = self._solved_quality or p.mesh_quality return { @@ -1511,9 +1810,17 @@ def delta(a, b): return text def select_case(self, index: int) -> None: - """Result panel: show another load case of the last strength run.""" - if not self.case_results or not 0 <= index < len(self.case_results): + """Result panel: show another load case of the last strength run (the last entry + is the envelope of all cases).""" + if not self.case_results or not 0 <= index <= len(self.case_results): return + if index == len(self.case_results): + self.result, self.summary = self.envelope_result() + self.showing_envelope = True + self._configure_result_panel() + self.show_result() + return + self.showing_envelope = False _, self.result, self.summary = self.case_results[index] self.project.active_case = index self._configure_result_panel() @@ -1529,6 +1836,15 @@ def _displacement(self) -> np.ndarray: def result_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 + field.extreme = ( + "min" + if key in ("fos", "ffos", "life") + else "both" + if key in ("ux", "uy", "uz", "p1") + else "max" + ) kind = { "vm": "stress", "p1": "stress", @@ -1627,6 +1943,8 @@ def deformation_scale(self, key: str) -> float: shape_only = isinstance(self.result, (ModalResult, BucklingResult)) if key == "true" and not shape_only: return 1.0 # mode shapes have no physical size + if key == "custom": + return float(self.panels[STEP_RESULT].scale_factor.value()) size = float(np.ptp(self.mesh.nodes, axis=0).max()) peak = float(np.linalg.norm(self._displacement(), axis=1).max()) fraction = 0.1 if shape_only else 0.05 @@ -1637,6 +1955,12 @@ def show_result(self) -> None: return panel: steps.ResultStep = self.panels[STEP_RESULT] field = self.result_field(panel.field_key()) + manual = panel.manual_range() + if manual is not None: + field.clim = manual + else: + lo, hi = field.clim or (float(field.values.min()), float(field.values.max())) + panel.show_range(lo, hi) scale = self.deformation_scale(panel.scale_key()) if isinstance(self.result, (ModalResult, BucklingResult)) or scale == 0.0: panel.scale_note.setText("") @@ -1666,6 +1990,7 @@ def show_result(self) -> None: scale, symmetric=isinstance(self.result, (ModalResult, BucklingResult)), clip=clip, + markers=panel.markers.isChecked(), ) self._fill_summary(panel) @@ -1737,7 +2062,7 @@ def _fill_summary(self, panel: steps.ResultStep) -> None: "{headline} ({worst}). 지금 보는 케이스: {case}", headline=o.headline, worst=o.summaries[o.worst].headline, - case=self.project.case.name, + case=tr("포락") if self.showing_envelope else self.project.case.name, ) ) comparison = self._comparison_line() diff --git a/src/kstruct/ui/prefs.py b/src/kstruct/ui/prefs.py index f2f9da8..e0f5187 100644 --- a/src/kstruct/ui/prefs.py +++ b/src/kstruct/ui/prefs.py @@ -84,6 +84,17 @@ def set_theme(name: str) -> None: save_prefs(prefs) +def colorblind() -> bool: + """Colour maps that stay readable with red-green colour blindness (result view).""" + return bool(load_prefs().get("colorblind", False)) + + +def set_colorblind(on: bool) -> None: + prefs = load_prefs() + prefs["colorblind"] = bool(on) + save_prefs(prefs) + + def language() -> str: """'ko' or 'en' (applied at start-up; changing it needs a restart).""" from kstruct.i18n import DEFAULT, LANGUAGES diff --git a/src/kstruct/ui/steps.py b/src/kstruct/ui/steps.py index 84f384c..3036b35 100644 --- a/src/kstruct/ui/steps.py +++ b/src/kstruct/ui/steps.py @@ -27,6 +27,7 @@ QSizePolicy, QSlider, QSpinBox, + QToolButton, QVBoxLayout, QWidget, ) @@ -1781,7 +1782,12 @@ def set_progress(self, frac: float | None, msg: str = "") -> None: ("uz", N_("변형량 Z")), ("p1", N_("최대 주응력 (인장)")), ] -SCALE_LABELS = [("auto", N_("자동 확대")), ("true", N_("실제 크기")), ("none", N_("변형 안 보기"))] +SCALE_LABELS = [ + ("auto", N_("자동 확대")), + ("true", N_("실제 크기")), + ("custom", N_("배율 직접")), + ("none", N_("변형 안 보기")), +] class ResultStep(StepPanel): @@ -1812,13 +1818,22 @@ def __init__(self, app: MainWindow) -> None: self.field = QComboBox() for key, label in FIELD_LABELS: self.field.addItem(tr(label), key) - self.field.currentIndexChanged.connect(app.show_result) + self.field.currentIndexChanged.connect(self._field_changed) form.addRow(tr("보기"), with_help(self.field, "result.field")) self.scale = QComboBox() for key, label in SCALE_LABELS: self.scale.addItem(tr(label), key) - self.scale.currentIndexChanged.connect(app.show_result) + self.scale.currentIndexChanged.connect(self._scale_changed) form.addRow(tr("변형"), with_help(self.scale, "result.scale")) + self.scale_factor = QDoubleSpinBox() + self.scale_factor.setRange(0.1, 1e7) + self.scale_factor.setDecimals(1) + self.scale_factor.setPrefix("× ") + self.scale_factor.setValue(100.0) + self.scale_factor.valueChanged.connect(lambda _v: app.show_result()) + self.scale_factor_row = with_help(self.scale_factor, "result.scale") + form.addRow("", self.scale_factor_row) + self.scale_factor_row.setVisible(False) self.mode = QComboBox() self.mode.currentIndexChanged.connect(app.show_result) self.mode_label = QLabel(tr("진동 모드")) @@ -1826,9 +1841,33 @@ def __init__(self, app: MainWindow) -> None: form.addRow(self.mode_label, self.mode_box) self.scale_note = _hint("") form.addRow("", self.scale_note) + # the finer display settings fold away: the verdict and its reasons come first + more = QFormLayout() self.animate = QCheckBox(tr("움직임 보기 (애니메이션)")) self.animate.toggled.connect(app.viewer.set_animated) - form.addRow("", self.animate) + more.addRow("", self.animate) + self.markers = QCheckBox(tr("최대·최소 위치 표시")) + self.markers.setChecked(True) + self.markers.toggled.connect(lambda _on: app.show_result()) + more.addRow("", with_help(self.markers, "result.markers")) + 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() + for spin in (self.range_min, self.range_max): + spin.setRange(-1e12, 1e12) + spin.setDecimals(3) + spin.setKeyboardTracking(False) + spin.valueChanged.connect(lambda _v: app.show_result()) + self.range_row = _row( + QLabel(tr("최소")), self.range_min, QLabel(tr("최대")), self.range_max + ) + more.addRow("", self.range_row) + self.range_row.setVisible(False) + self.colorblind = QCheckBox(tr("색각 이상에도 잘 보이는 색")) + self.colorblind.setChecked(app.viewer.colorblind) + self.colorblind.toggled.connect(app.set_colorblind) + more.addRow("", with_help(self.colorblind, "result.colorblind")) self.clip = QCheckBox(tr("단면 보기 (안쪽 값)")) self.clip.toggled.connect(self._clip_changed) self.clip_axis = QComboBox() @@ -1839,13 +1878,24 @@ def __init__(self, app: MainWindow) -> None: self.clip_pos.setRange(1, 99) self.clip_pos.setValue(50) self.clip_pos.valueChanged.connect(lambda _v: app.show_result()) - form.addRow("", with_help(self.clip, "result.clip")) + more.addRow("", with_help(self.clip, "result.clip")) self.clip_row = _row(self.clip_axis, self.clip_pos) - form.addRow("", self.clip_row) + more.addRow("", self.clip_row) self.clip_row.setVisible(False) box = QWidget() box.setLayout(form) self.add(box) + self.more_toggle = QToolButton() + self.more_toggle.setText(tr("표시 설정 더 보기")) + self.more_toggle.setCheckable(True) + self.more_toggle.setArrowType(Qt.ArrowType.RightArrow) + self.more_toggle.setToolButtonStyle(Qt.ToolButtonStyle.ToolButtonTextBesideIcon) + self.more_toggle.toggled.connect(self._more_toggled) + self.add(with_help(self.more_toggle, "result.display")) + self.more = QWidget() + self.more.setLayout(more) + self.more.setVisible(False) + self.add(self.more) self.summary = QLabel() self.summary.setWordWrap(True) @@ -1854,6 +1904,27 @@ def __init__(self, app: MainWindow) -> None: self.probe = _hint(tr("결과 위를 클릭하면 그 위치의 값을 보여줍니다.")) self.add(self.probe) + # is the mesh fine enough? (solve once more on the next finer one and compare) + self.mesh_check = QPushButton(tr("메시 확인 (한 단계 세밀하게 다시 풀어 비교)")) + self.mesh_check.clicked.connect(app.check_mesh) + self.mesh_check_box = with_help(self.mesh_check, "result.mesh_check") + self.add(self.mesh_check_box) + self.mesh_check_text = _hint("") + self.mesh_check_text.setTextFormat(Qt.TextFormat.RichText) + self.add(self.mesh_check_text) + + # what if the part were made of another material (no new analysis when exact) + self.trial_box = QGroupBox(tr("재료 바꿔 보기")) + trial = QVBoxLayout(self.trial_box) + self.trial_material = QComboBox() + trial.addWidget(with_help(self.trial_material, "result.material_trial")) + self.trial_run = QPushButton(tr("이 재료로 판정해 보기")) + self.trial_run.clicked.connect(lambda: app.try_material(self.trial_material.currentData())) + self.trial_keep = QPushButton(tr("이 재료로 확정")) + self.trial_keep.clicked.connect(app.keep_trial_material) + trial.addWidget(_row(self.trial_run, self.trial_keep)) + self.add(self.trial_box) + buttons = QHBoxLayout() report = _primary(QPushButton(tr("보고서 저장 (PDF)"))) report.clicked.connect(app.save_report) @@ -1915,7 +1986,54 @@ def set_modes(self, frequencies, labels: list[str] | None = None, title=None) -> self.mode.setCurrentIndex(min(current, len(frequencies) - 1)) self.mode.blockSignals(False) + def _more_toggled(self, on: bool) -> None: + self.more.setVisible(on) + self.more_toggle.setArrowType(Qt.ArrowType.DownArrow if on else Qt.ArrowType.RightArrow) + + def _field_changed(self) -> None: + # a typed colour range belongs to the field it was typed for + if self.range_manual.isChecked(): + self.range_manual.blockSignals(True) + self.range_manual.setChecked(False) + self.range_manual.blockSignals(False) + self.range_row.setVisible(False) + self.app.show_result() + + def _scale_changed(self) -> None: + custom = self.scale.currentData() == "custom" + if custom and not self.scale_factor_row.isVisible(): + # start from what the automatic scale showed + auto = self.app.deformation_scale("auto") + if auto > 0: + self.scale_factor.blockSignals(True) + self.scale_factor.setValue(float(f"{auto:.2g}")) + self.scale_factor.blockSignals(False) + self.scale_factor_row.setVisible(custom) + self.app.show_result() + + def _range_toggled(self, on: bool) -> None: + if on: + self.more_toggle.setChecked(True) + self.range_row.setVisible(on) + self.app.show_result() + + def manual_range(self) -> tuple[float, float] | None: + """(min, max) of the colour scale typed by the user, in display units.""" + if not self.range_manual.isChecked(): + return None + lo, hi = self.range_min.value(), self.range_max.value() + return (lo, hi) if hi > lo else None + + def show_range(self, lo: float, hi: float) -> None: + """Put the automatic colour range into the boxes (as the starting point).""" + for spin, v in ((self.range_min, lo), (self.range_max, hi)): + spin.blockSignals(True) + spin.setValue(v) + spin.blockSignals(False) + def _clip_changed(self, on: bool) -> None: + if on: + self.more_toggle.setChecked(True) # the section controls are in there self.clip_row.setVisible(on) self.animate.setEnabled(not on) if on: diff --git a/src/kstruct/ui/theme.py b/src/kstruct/ui/theme.py index a30d30c..89ccaaa 100644 --- a/src/kstruct/ui/theme.py +++ b/src/kstruct/ui/theme.py @@ -160,6 +160,13 @@ def _stylesheet(t: Theme) -> str: QToolBar QToolButton:pressed {{ background: {t.border}; }} QToolBar QToolButton::menu-indicator {{ image: none; }} QToolBar QToolButton:checked {{ background: {t.raised}; color: {t.accent}; font-weight: 700; }} +/* guided tour (ui/tour.py) */ +QFrame#tourCard {{ + background: {t.surface}; border: 1px solid {t.accent}; border-radius: 10px; +}} +QFrame#tourHighlight {{ + background: transparent; border: 3px solid {t.accent}; border-radius: 8px; +}} /* the slim bar above the 3D view */ QToolBar#viewStrip {{ padding: 1px 8px; }} QToolBar#viewStrip QToolButton {{ padding: 3px 8px; }} diff --git a/src/kstruct/ui/tour.py b/src/kstruct/ui/tour.py new file mode 100644 index 0000000..43101c7 --- /dev/null +++ b/src/kstruct/ui/tour.py @@ -0,0 +1,125 @@ +"""A short guided tour: one card at a time that points at a part of the window (the step +navigator, the side panel, the 3D view's tools, the next-step button, help).""" + +from __future__ import annotations + +from collections.abc import Callable + +from PySide6.QtCore import QEvent, QPoint, QRect, Qt, Signal +from PySide6.QtWidgets import QFrame, QHBoxLayout, QLabel, QPushButton, QVBoxLayout, QWidget + +from kstruct.i18n import tr + +MARGIN = 6 # px between the highlight frame and its target + + +class Tour(QFrame): + """Cards shown one after another over `window`; each step is (target getter, title, + text). The highlight is a frame around the target (never over the 3D view itself: + a native OpenGL child can hide widgets above it).""" + + finished = Signal() + + def __init__(self, window: QWidget, steps: list[tuple[Callable[[], QWidget], str, str]]): + super().__init__(window) + self.window_, self.steps = window, steps + self.setObjectName("tourCard") + self.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self.setFixedWidth(316) + layout = QVBoxLayout(self) + layout.setContentsMargins(16, 14, 16, 12) + self.title = QLabel() + self.title.setProperty("role", "section") + self.text = QLabel() + self.text.setWordWrap(True) + self.counter = QLabel() + self.counter.setProperty("role", "hint") + layout.addWidget(self.title) + layout.addWidget(self.text) + buttons = QHBoxLayout() + buttons.addWidget(self.counter, 1) + self.back = QPushButton(tr("이전")) + self.back.setProperty("compact", "true") + self.back.clicked.connect(lambda: self.go(self.index - 1)) + self.next = QPushButton(tr("다음")) + self.next.setProperty("primary", "true") + self.next.setProperty("compact", "true") + self.next.clicked.connect(self._next) + close = QPushButton(tr("그만 보기")) + close.setProperty("compact", "true") + close.clicked.connect(self.finish) + for b in (self.back, self.next, close): + buttons.addWidget(b) + layout.addLayout(buttons) + + self.highlight = QFrame(window) + self.highlight.setObjectName("tourHighlight") + self.highlight.setAttribute(Qt.WidgetAttribute.WA_TransparentForMouseEvents, True) + self.highlight.setAttribute(Qt.WidgetAttribute.WA_StyledBackground, True) + self.index = 0 + window.installEventFilter(self) + + def start(self) -> None: + self.show() + self.go(0) + + def go(self, index: int) -> None: + if not 0 <= index < len(self.steps): + return + self.index = index + getter, title, text = self.steps[index] + self.title.setText(title) + self.text.setText(text) + self.counter.setText(f"{index + 1} / {len(self.steps)}") + self.back.setEnabled(index > 0) + last = index == len(self.steps) - 1 + self.next.setText(tr("시작하기") if last else tr("다음")) + self._place(getter()) + + def _next(self) -> None: + if self.index == len(self.steps) - 1: + self.finish() + else: + self.go(self.index + 1) + + def target_rect(self, target: QWidget | None) -> QRect | None: + if target is None or not target.isVisible(): + return None + top_left = target.mapTo(self.window_, QPoint(0, 0)) + return QRect(top_left, target.size()).adjusted(-MARGIN, -MARGIN, MARGIN, MARGIN) + + def _place(self, target: QWidget | None) -> None: + """Highlight the target; the card itself stays at the bottom left, over the side + panel (a plain Qt area: over the 3D view a native OpenGL window could hide it).""" + win = self.window_.rect() + # wrapped text: the height follows from the fixed width + self.layout().invalidate() + self.resize(self.width(), self.layout().totalHeightForWidth(self.width())) + rect = self.target_rect(target) + if rect is None: + self.highlight.hide() + else: + self.highlight.setGeometry(rect.intersected(win)) + self.highlight.show() + self.highlight.raise_() + self.move(12, max(8, win.height() - self.height() - 72)) + self.raise_() + + def eventFilter(self, obj, event) -> bool: # noqa: N802 (Qt override) + if obj is self.window_ and event.type() == QEvent.Type.Resize and self.isVisible(): + self.go(self.index) + return False + + def keyPressEvent(self, event) -> None: # noqa: N802 (Qt override) + if event.key() == Qt.Key.Key_Escape: + self.finish() + else: + super().keyPressEvent(event) + + def finish(self) -> None: + self.window_.removeEventFilter(self) + self.highlight.hide() + self.highlight.deleteLater() + self.hide() + self.deleteLater() + self.finished.emit() diff --git a/src/kstruct/ui/viewer.py b/src/kstruct/ui/viewer.py index 1e3cf97..09601ad 100644 --- a/src/kstruct/ui/viewer.py +++ b/src/kstruct/ui/viewer.py @@ -69,6 +69,16 @@ ] +# colour maps readable with red-green colour blindness (prefs.colorblind) +COLORBLIND_MAPS = { + "turbo": "cividis", + "inferno": "cividis", + "magma": "cividis", + "YlOrRd": "cividis", + "RdYlGn": "RdYlBu", +} + + @dataclass class ResultField: values: np.ndarray # (N,) per node @@ -76,6 +86,7 @@ class ResultField: cmap: str = "turbo" clim: tuple[float, float] | None = None unit: str = "" + extreme: str = "max" # which end to mark: "max", "min", "both" or "none" class ModelViewer(QWidget): @@ -123,6 +134,8 @@ def __init__(self, parent: QWidget | None = None) -> None: self._result_tree: cKDTree | None = None self._result_field: ResultField | None = None self._probe_actor = None + self.colorblind = False # use COLORBLIND_MAPS for results + self.markers: list = [] # (label, position, value) shown on the current result self._selection_enabled = True self._press_pos: tuple[int, int] | None = None self._right_pos: tuple[int, int] | None = None @@ -558,9 +571,11 @@ def show_result( scale: float, symmetric: bool = False, clip: tuple | None = None, + markers: bool = True, ): """clip: (normal, origin) keeps the half of the model on the normal's side and - shows the interior values on the cut face (no deformation animation).""" + shows the interior values on the cut face (no deformation animation). + markers: label where the field is largest / smallest (field.extreme).""" self.clear_result(render=False) points = mesh.nodes + scale * displacement if clip is not None: @@ -580,10 +595,11 @@ def show_result( self._anim_delta = np.array(surf.points) - self._anim_base self._anim_symmetric = symmetric self._anim_phase = 0.0 + cmap = COLORBLIND_MAPS.get(field.cmap, field.cmap) if self.colorblind else field.cmap self._result_actor = self.plotter.add_mesh( surf, scalars="value", - cmap=field.cmap, + cmap=cmap, clim=field.clim, smooth_shading=True, scalar_bar_args={ @@ -610,6 +626,12 @@ def show_result( self._result_points = boundary self._result_tree = cKDTree(points[boundary]) self._result_field = field + if markers and field.extreme != "none": + if clip is not None: # what is on screen: the kept half and its cut face + where, values = np.asarray(surf.points), np.asarray(surf.point_data["value"]) + else: # nodal values (the subdivided surface can overshoot them) + where, values = points[boundary], field.values[boundary] + self._add_extremes(where, values, field) self._apply_visibility() for actor in self._overlay: actor.SetVisibility(False) @@ -617,6 +639,37 @@ def show_result( self._anim_timer.start() self.plotter.render() + def extremes(self, where: np.ndarray, values: np.ndarray, field: ResultField) -> list: + """[(label, position, value)] of the marked ends of the field.""" + out = [] + if len(values) == 0: + return out + if field.extreme in ("max", "both"): + i = int(np.argmax(values)) + out.append((tr("최대"), where[i], float(values[i]))) + if field.extreme in ("min", "both"): + i = int(np.argmin(values)) + out.append((tr("최소"), where[i], float(values[i]))) + return out + + def _add_extremes(self, where: np.ndarray, values: np.ndarray, field: ResultField) -> None: + marks = self.extremes(where, values, field) + self.markers = marks + if not marks: + return + actor = self.plotter.add_point_labels( + [m[1] for m in marks], + [f"{label} {value:.4g} {field.unit}".rstrip() for label, _, value in marks], + point_size=14, + point_color=self._theme.viewer_text, + font_size=13, + shape_opacity=0.8, + always_visible=True, + pickable=False, + ) + _label_font(actor) + self._result_extras.append(actor) + def shutdown(self) -> None: """Release the OpenGL render window (the main window is closing). @@ -662,6 +715,7 @@ def clear_result(self, render: bool = True) -> None: self.plotter.remove_actor(self._probe_actor) self._probe_actor = None self._result_field = None + self.markers = [] self._apply_visibility() for actor in self._overlay: actor.SetVisibility(True) @@ -899,6 +953,18 @@ def section_surface( return clipped.extract_surface(algorithm="dataset_surface") +def _label_font(actor) -> None: + """Point labels (add_point_labels) in the bundled font: VTK's own has no Hangul.""" + font = str(resources.files("kstruct.resources").joinpath("fonts/NotoSansKR.ttf")) + try: + hierarchy = actor.GetMapper().GetInputAlgorithm() + prop = hierarchy.GetTextProperty() + prop.SetFontFamily(VTK_FONT_FILE) + prop.SetFontFile(font) + except AttributeError: # another pyvista layout: keep its font + pass + + def _use_korean_font(scalar_bar) -> None: """VTK's built-in fonts have no Hangul; render scalar bar text with the bundled font.""" font = str(resources.files("kstruct.resources").joinpath("fonts/NotoSansKR.ttf")) diff --git a/src/kstruct/whatif.py b/src/kstruct/whatif.py new file mode 100644 index 0000000..d7dd2a7 --- /dev/null +++ b/src/kstruct/whatif.py @@ -0,0 +1,67 @@ +"""'What if it were made of …': a strength result for another material without solving +again, where that is exact. + +For a linear static model whose every part has the same material, scaling Young's +modulus E scales the stiffness matrix as a whole: the stresses stay exactly the same and +the displacements scale by E_old / E_new. Only the verdict (yield / tensile strength, +fatigue limit) changes. That stops being exact as soon as something in the model does not +scale with E, so those cases are refused with the reason and the user re-runs the +analysis instead. +""" + +from __future__ import annotations + +from dataclasses import replace + +from kstruct.fem.static import StaticResult +from kstruct.i18n import tr +from kstruct.model import FixtureKind, LoadKind, Material, Project + +NU_TOLERANCE = 1e-3 # Poisson's ratios closer than this give the same stress field + + +def why_not_exact(project: Project, result: StaticResult, new: Material) -> str | None: + """The reason the swap needs a new analysis, or None when it is exact.""" + if result.nonlinear is not None: + return tr("항복·대변형 해석은 재료에 따라 응력 분포가 달라집니다.") + if len({m.id for m in result.materials.values()}) != 1: + return tr("부품마다 재료가 달라 강성 비율이 바뀝니다.") + current = next(iter(result.materials.values())) + if abs(current.poisson_ratio - new.poisson_ratio) > NU_TOLERANCE: + return tr( + "푸아송비가 달라({old:.2f} → {new:.2f}) 응력 분포가 조금 바뀝니다.", + old=current.poisson_ratio, + new=new.poisson_ratio, + ) + if result.thermal is not None: + return tr("열응력은 탄성계수와 열팽창계수에 따라 달라집니다.") + body = {LoadKind.GRAVITY, LoadKind.CENTRIFUGAL} + if any(ld.kind in body for ld in project.loads) and current.density != new.density: + return tr("자중·원심력은 밀도에 비례합니다.") + for fx in project.fixtures: + if fx.kind == FixtureKind.ELASTIC: + return tr("탄성 지지는 부품 강성과의 비율로 힘을 나눕니다.") + if fx.kind == FixtureKind.DISPLACEMENT and any(v for v in fx.displacement or () if v): + return tr("강제 변위로 생기는 응력은 탄성계수에 비례합니다.") + if project.bolts: + return tr("볼트와 부품의 강성 비율이 바뀝니다.") + return None + + +def swap_material( + project: Project, result: StaticResult, new: Material +) -> tuple[StaticResult | None, str | None]: + """(result with every part made of `new`, None) or (None, reason it is not exact).""" + reason = why_not_exact(project, result, new) + if reason is not None: + return None, reason + current = next(iter(result.materials.values())) + ratio = current.youngs_modulus / new.youngs_modulus + return ( + replace( + result, + materials={pid: new for pid in result.materials}, + displacement=result.displacement * ratio, + ), + None, + ) diff --git a/tests/test_load_cases.py b/tests/test_load_cases.py index 5d0d4f1..5b969a6 100644 --- a/tests/test_load_cases.py +++ b/tests/test_load_cases.py @@ -172,3 +172,42 @@ def test_report_has_a_case_table(): # a single case keeps the old layout html1 = build_html(project, results[0], summaries[0], [], {0: STEEL}, None) assert "하중 케이스 비교" not in html1 + + +def test_envelope_takes_the_worst_case_at_every_node(): + """Two load cases bending a cantilever up and sideways: the envelope has, node by + node, the larger von Mises stress, the lower safety factor and the larger + displacement of the two.""" + from kstruct.fem import generate_mesh + from kstruct.fem.static import envelope, solve_cases + from kstruct.geometry.face_info import face_at + from kstruct.geometry.samples import _box + from kstruct.model import ( + FaceRef, + Fixture, + FixtureKind, + Load, + LoadCase, + LoadKind, + Material, + Part, + Project, + ) + + steel = Material("s", "s", "steel", 210_000.0, 0.3, 7.85e-9, 235.0, 360.0) + shape = _box(0, 0, 0, 60, 10, 10) + tip = [FaceRef(0, face_at(shape, (60, 5, 5)))] + project = Project(parts=[Part(0, "bar", shape, "s")]) + project.fixtures = [Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(shape, (0, 5, 5)))])] + project.cases = [ + LoadCase("up", [Load(LoadKind.FORCE, tip, vector=(0, 0, 300.0))]), + LoadCase("side", [Load(LoadKind.FORCE, tip, vector=(0, 500.0, 0))]), + ] + mesh = generate_mesh(project, "coarse") + a, b = solve_cases(project, mesh, {0: steel}) + env = envelope([a, b]) + assert np.allclose(env.von_mises, np.maximum(a.von_mises, b.von_mises)) + assert np.allclose(env.safety_factor, np.minimum(a.safety_factor, b.safety_factor)) + assert np.allclose( + env.displacement_magnitude, np.maximum(a.displacement_magnitude, b.displacement_magnitude) + ) diff --git a/tests/test_meshcheck.py b/tests/test_meshcheck.py new file mode 100644 index 0000000..28e8728 --- /dev/null +++ b/tests/test_meshcheck.py @@ -0,0 +1,46 @@ +"""Mesh check: a bar in uniform tension (stress P/A everywhere, no singularity that +counts) gives the same safety factor and stretch on the next finer mesh; the check says +so, and the presets run coarse -> very fine.""" + +import pytest + +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 +from kstruct.meshcheck import ORDER, compare, finer +from kstruct.model import FaceRef, Fixture, FixtureKind, Load, LoadKind, Material, Part, Project +from kstruct.report.summary import summarize + +STEEL = Material("s235", "s", "steel", 210_000.0, 0.3, 7.85e-9, 235.0, 360.0) + + +def test_finer_steps_through_the_presets(): + assert ORDER[0] == "coarse" and finer("coarse") == "normal" + assert finer(ORDER[-1]) is None + + +def test_bar_in_tension_is_not_mesh_sensitive(): + shape = _box(0, 0, 0, 80, 10, 10) + project = Project(parts=[Part(0, "bar", shape, "s235")]) + project.fixtures = [ + Fixture(FixtureKind.ROLLER, [FaceRef(0, face_at(shape, (0, 5, 5)))]), + Fixture(FixtureKind.ROLLER, [FaceRef(0, face_at(shape, (40, 0, 5)))]), + Fixture(FixtureKind.ROLLER, [FaceRef(0, face_at(shape, (40, 5, 0)))]), + ] + project.loads = [ + Load(LoadKind.PRESSURE, [FaceRef(0, face_at(shape, (80, 5, 5)))], magnitude=-100.0) + ] + pack = standards.effective_pack(project) + runs = [] + for quality in ("coarse", "normal"): + mesh = generate_mesh(project, quality) + result = solve_static(project, mesh, {0: STEEL}) + runs.append((mesh, summarize(project, result, pack))) + (m0, s0), (m1, s1) = runs + check = compare("coarse", "normal", m0, m1, s0, s1) + assert check.elements[1] > check.elements[0] + assert check.fos[0] == pytest.approx(2.35, rel=0.02) # 235 / 100 MPa + assert abs(check.change(check.fos)) < 0.01 + assert abs(check.change(check.disp)) < 0.01 + assert not check.sensitive diff --git a/tests/test_ui.py b/tests/test_ui.py index 068eac4..cb705dd 100644 --- a/tests/test_ui.py +++ b/tests/test_ui.py @@ -510,7 +510,7 @@ def test_multi_case_strength_run(qtbot): assert len(window.case_results) == 2 and window.overview is not None assert window.overview.worst == 1 and window.project.active_case == 1 # heavy governs panel = window.panels[mw.STEP_RESULT] - assert panel.case.count() == 2 and panel.case.currentIndex() == 1 + assert panel.case.count() == 3 and panel.case.currentIndex() == 1 # + the envelope assert "가장 불리" in panel.case.itemText(1) assert "2개 케이스 중 가장 불리한 것: 무거움" in panel.summary.text() heavy = window.summary.governing_fos diff --git a/tests/test_ui_results.py b/tests/test_ui_results.py new file mode 100644 index 0000000..9c78caa --- /dev/null +++ b/tests/test_ui_results.py @@ -0,0 +1,126 @@ +"""v0.6 result tools in the window: max/min markers, custom deformation scale and colour +range, trying another material, the load-case envelope, the mesh check, the guided tour +and the next-step hints.""" + +import numpy as np +import pytest + +from kstruct.geometry.face_info import face_at +from kstruct.model import FaceRef, Fixture, FixtureKind, Load, LoadCase, LoadKind + + +def _solved(qtbot, cases=False): + from kstruct.ui.main_window import MainWindow + + window = MainWindow() + window.ask_before_close = False + window.warn = lambda text, *a, **k: pytest.fail(text) + qtbot.addWidget(window) + window.resize(1280, 720) + window.show() + window.open_sample("bracket") + project = window.project + shape = project.parts[0].shape + project.parts[0].material_id = "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, -2000.0))] + if cases: + project.cases.append(LoadCase("side", [Load(LoadKind.FORCE, top, vector=(0, 2000.0, 0))])) + project.mesh_quality = "coarse" + window._project_changed() + window.solve() + qtbot.waitUntil(lambda: window.result is not None, timeout=120_000) + return window + + +def test_markers_scale_and_colour_range(qtbot): + from kstruct.ui import main_window as mw + + window = _solved(qtbot) + panel = window.panels[mw.STEP_RESULT] + viewer = window.viewer + ((label, _, value),) = viewer.markers # von Mises: the maximum + assert label == "최대" and value == pytest.approx(window.result.von_mises.max(), rel=1e-9) + + panel.field.setCurrentIndex(panel.field.findData("fos")) + ((label, _, value),) = viewer.markers + assert label == "최소" and value == pytest.approx(window.result.safety_factor.min(), rel=1e-6) + panel.field.setCurrentIndex(panel.field.findData("uz")) + assert [m[0] for m in viewer.markers] == ["최대", "최소"] + panel.markers.setChecked(False) + assert viewer.markers == [] + + panel.scale.setCurrentIndex(panel.scale.findData("custom")) + assert panel.scale_factor.isVisibleTo(panel) + panel.scale_factor.setValue(250.0) + assert window.deformation_scale("custom") == 250.0 + assert "250" in panel.scale_note.text() + + panel.range_manual.setChecked(True) + assert panel.more.isVisibleTo(panel) # the folded settings opened + panel.range_min.setValue(-0.2) + panel.range_max.setValue(0.05) + assert tuple(viewer._result_actor.mapper.scalar_range) == pytest.approx((-0.2, 0.05)) + panel.field.setCurrentIndex(panel.field.findData("vm")) + assert not panel.range_manual.isChecked() # a typed range belongs to its field + + +def test_trying_a_material_and_the_envelope(qtbot): + from kstruct.ui import main_window as mw + + window = _solved(qtbot, cases=True) + panel = window.panels[mw.STEP_RESULT] + assert panel.trial_box.isVisibleTo(panel) + fos = [s.governing_fos for _, _, s in window.case_results] + disp = window.summary.max_disp + + window.try_material("s355") # same Poisson's ratio: exact without solving + assert [s.governing_fos for _, _, s in window.case_results] == pytest.approx( + [f * 355 / 235 for f in fos], rel=1e-6 + ) + assert window.summary.max_disp == pytest.approx(disp, rel=1e-9) # same modulus + assert window.summary.notes[0].startswith("재료를 ") # says it is a trial + window.keep_trial_material() + assert window.project.parts[0].material_id == "s355" and window.result is not None + + asked = [] + window._confirm = lambda text: asked.append(text) or False + window.try_material("al6061t6") # Poisson's ratio 0.33: needs a new analysis + assert asked and "푸아송비" in asked[0] + assert window.project.parts[0].material_id == "s355" # declined: nothing changed + + labels = [panel.case.itemText(i) for i in range(panel.case.count())] + assert labels[-1].startswith("포락") + panel.case.setCurrentIndex(len(labels) - 1) + assert window.showing_envelope and window.summary.notes[0].startswith("포락") + worst = np.maximum(*[r.von_mises for _, r, _ in window.case_results]) + assert window.result.von_mises == pytest.approx(worst) + assert not panel.mesh_check_box.isVisibleTo(panel) # not for the envelope + panel.case.setCurrentIndex(0) + assert not window.showing_envelope + + +def test_mesh_check_tour_and_next_step_hints(qtbot): + from kstruct.ui import main_window as mw + + window = _solved(qtbot) + panel = window.panels[mw.STEP_RESULT] + window.check_mesh() + qtbot.waitUntil(lambda: "메시 확인" in panel.mesh_check_text.text(), timeout=120_000) + assert "거침 → 보통" in panel.mesh_check_text.text() + + window.start_tour() + tour = window._tour + assert tour.isVisible() + for i in range(len(tour.steps)): + tour.go(i) + assert tour.highlight.isVisible(), tour.title.text() + assert window.rect().contains(tour.geometry()) + tour.finish() + assert window._tour is None + + window.project.fixtures = [] + window._project_changed() + window._go(mw.STEP_FIXTURE) + assert window.statusBar().currentMessage().startswith("다음에 할 일") diff --git a/tests/test_whatif.py b/tests/test_whatif.py new file mode 100644 index 0000000..299329c --- /dev/null +++ b/tests/test_whatif.py @@ -0,0 +1,65 @@ +"""'재료 바꿔 보기': a one-material linear model gets the same answer as a new analysis +(stresses unchanged, displacements scaled by the modulus ratio), and the cases where that +is not exact are refused with a reason.""" + +from dataclasses import replace + +import numpy as np +import pytest + +from kstruct.fem import generate_mesh, solve_static +from kstruct.geometry.face_info import face_at +from kstruct.geometry.samples import _box +from kstruct.model import FaceRef, Fixture, FixtureKind, Load, LoadKind, Material, Part, Project +from kstruct.whatif import swap_material, why_not_exact + +STEEL = Material("s", "s", "steel", 210_000.0, 0.3, 7.85e-9, 235.0, 360.0) +STRONG = replace(STEEL, id="h", name="h", youngs_modulus=190_000.0, yield_strength=600.0) + + +def _bar() -> Project: + shape = _box(0, 0, 0, 60, 10, 10) + project = Project(parts=[Part(0, "bar", shape, "s")]) + project.fixtures = [Fixture(FixtureKind.FIXED, [FaceRef(0, face_at(shape, (0, 5, 5)))])] + project.loads = [ + Load(LoadKind.FORCE, [FaceRef(0, face_at(shape, (60, 5, 5)))], vector=(0, 0, -300.0)) + ] + return project + + +def test_swap_equals_a_new_analysis(): + project = _bar() + mesh = generate_mesh(project, "coarse") + steel = solve_static(project, mesh, {0: STEEL}) + tried, reason = swap_material(project, steel, STRONG) + assert reason is None + fresh = solve_static(project, mesh, {0: STRONG}) + peak = np.abs(fresh.stress).max() + assert np.abs(tried.stress - fresh.stress).max() < 1e-6 * peak + scale = np.abs(fresh.displacement).max() + assert np.abs(tried.displacement - fresh.displacement).max() < 1e-6 * scale + assert tried.displacement_magnitude.max() == pytest.approx( + steel.displacement_magnitude.max() * 210 / 190, rel=1e-9 + ) + assert tried.safety_factor.min() == pytest.approx(fresh.safety_factor.min(), rel=1e-6) + assert tried.safety_factor.min() == pytest.approx( + steel.safety_factor.min() * 600 / 235, rel=1e-9 + ) + + +def test_cases_that_need_a_new_analysis_are_refused(): + project = _bar() + mesh = generate_mesh(project, "coarse") + result = solve_static(project, mesh, {0: STEEL}) + aluminium = replace(STRONG, poisson_ratio=0.33) + assert "푸아송비" in why_not_exact(project, result, aluminium) + project.loads.append(Load(LoadKind.GRAVITY, vector=(0, 0, -9810.0))) + assert "밀도" in why_not_exact(project, result, replace(STRONG, density=2.7e-9)) + assert why_not_exact(project, result, STRONG) is None # same density: still exact + project.loads.pop() + project.fixtures.append( + Fixture(FixtureKind.DISPLACEMENT, project.fixtures[0].faces, displacement=(0.1, 0, 0)) + ) + assert "강제 변위" in why_not_exact(project, result, STRONG) + two = replace(result, materials={0: STEEL, 1: STRONG}) + assert "재료가 달라" in why_not_exact(_bar(), two, STRONG) diff --git a/uv.lock b/uv.lock index bdfb75b..b016586 100644 --- a/uv.lock +++ b/uv.lock @@ -245,7 +245,7 @@ wheels = [ [[package]] name = "kstruct" -version = "0.5.0" +version = "0.6.0" source = { editable = "." } dependencies = [ { name = "cadquery-ocp" },