diff --git a/.gitignore b/.gitignore index adab5ce..4556c98 100644 --- a/.gitignore +++ b/.gitignore @@ -191,3 +191,6 @@ displacement.png # Figures and tables written by the example scripts and template examples/output/ templates/output/ + +# Claude Code agent worktrees (temporary checkouts of this repo) +.claude/worktrees/ diff --git a/CHANGELOG.md b/CHANGELOG.md index 1b59b08..50ec1fe 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,38 @@ releases may still change the API). ## [Unreleased] +### Added + +- New domains: `MachineElements` (bolt torque, preload and joint + stiffness, shaft diameter, spring rate and stress, bearing L10 life, + fillet welds), `Fatigue` (endurance limit, Marin factors, Goodman, + Soderberg, Gerber and ASME-elliptic safety factors, S-N curve) and + `Psychrometrics` (saturation pressure, humidity ratio, relative humidity, + dew point, enthalpy, specific volume, wet bulb). `Material` gains + Johnson buckling, slenderness ratios and an Euler/Johnson chooser. + Tests check published ASHRAE and Shigley table values. +- `fpc-mcp --domains fluids,thermo`: also serve each calculation in those + domains as its own MCP tool, with the registry's input schema, for + capable models that do better calling a tool directly. +- `fpc.uncertainty`: Monte Carlo on any calculation. Give inputs as + `Normal`, `Uniform` or `Triangular` distributions; get the mean, + standard deviation, percentiles, a 95 % interval and each input's share + of the spread. Also `fpc uncertainty` (`velocity=normal:2,0.1`). +- `fpc.report` and `fpc report`: a Markdown calc sheet for any calculation + (method, inputs with units, defaults, result, optional uncertainty, + review checklist), ready for a design file or `pandoc`. +- `apps/calculator.py`: a Streamlit web form for every calculation, + generated from the registry, with uncertainty and calc-sheet tabs. +- `scripts/try_local_model.py`: ask an Ollama model engineering questions + through `fpc-mcp` and check its answers against the library. + +### Changed + +- The MCP `calculate` tool's `arguments` is optional so that a model + which puts the inputs beside `key` gets a precise correction instead of + a validation error it cannot act on. +- mypy now requires every function in `fpc/` to be fully annotated. + ## [0.1.0] - first PyPI release ### Added diff --git a/CLAUDE.md b/CLAUDE.md index 5de8ab4..c12adb5 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -14,8 +14,10 @@ The original design lives in [SPEC.md](SPEC.md); the improvement backlog lives i ## Current state - `main.py` — displacement demo (closed form, `scipy` integration, library call) that prints results and saves a plot. -- `fpc/` — the installable package (import name `fpc`, distribution name `first-principles-code`). One class per engineering domain (Dynamics, Statics, Modal, Thermo, Fluids, Material, Gear, Electrical, Mechatronics, Controls, Utility, Design, Properties, plus the radiology set Radiation, Radiography, CT, MRI, Ultrasound, Dicom), the shared Pint registry in `fpc/units.py`, and the unit-aware `Beam` dataclass. +- `fpc/` — the installable package (import name `fpc`, distribution name `first-principles-code`). One class per engineering domain (Dynamics, Statics, Modal, Thermo, Fluids, Psychrometrics, Material, Gear, MachineElements, Fatigue, Electrical, Mechatronics, Controls, Utility, Design, Properties, plus the radiology set Radiation, Radiography, CT, MRI, Ultrasound, Dicom), the shared Pint registry in `fpc/units.py`, and the unit-aware `Beam` dataclass. - `fpc/registry.py` — introspects every domain method (type hints + `[unit]` docstring tags) into a catalogue with JSON Schemas; drives `fpc search/describe/run`, the MCP server (`fpc/mcp_server.py`, command `fpc-mcp`, optional `mcp` extra) and the generated `llms.txt`. See `docs/ai.md`. +- `fpc/uncertainty.py` (Monte Carlo on any calculation, `fpc uncertainty`) and `fpc/report.py` (Markdown calc sheets, `fpc report`) — both built on the registry. See `docs/trusting-results.md`. +- `apps/calculator.py` — Streamlit form for every calculation, generated from the registry (`uv run streamlit run apps/calculator.py`). - `gui.py` — tkinter MATLAB-style console; the `Session` class is GUI-free and tested. - `tests/` — pytest suite, run in CI (`.github/workflows/tests.yml`). - `examples/` — one self-contained worked problem per script; `templates/` — copy-and-adapt starting scripts; `notebooks/` — Jupyter notebooks; `fpc/data/` — cited reference tables (CSV); `docs/` — mkdocs site sources and guides. @@ -37,6 +39,7 @@ uv run pre-commit install # enable git hooks (ruff + pytest) uv run fpc llms-txt > llms.txt # regenerate after changing public methods (a test checks it) uv build # build sdist + wheel; releasing steps are in docs/releasing.md uv run scripts/python_support.py check # supported Python versions consistent everywhere +uv run --extra mcp scripts/try_local_model.py --model qwen3:14b --think off # MCP server vs a local Ollama model uv run -p 3.11 pytest # run the tests on a specific Python (CI runs every supported one) ``` diff --git a/README.md b/README.md index 6a5638b..824256a 100644 --- a/README.md +++ b/README.md @@ -17,8 +17,9 @@ You get: integration of constant acceleration, and numerical integration of a time-varying acceleration). - **`fpc/`** — an installable package with one well-documented class per - engineering domain (dynamics, statics, thermo, fluids, materials, gears, - electrical, mechatronics, modal/vibration, controls), a set of radiology / + engineering domain (dynamics, statics, thermo, fluids, psychrometrics, + materials, gears, machine elements, fatigue, electrical, mechatronics, + modal/vibration, controls), a set of radiology / medical-imaging classes, `Design` (root finding and optimization), `Properties` (cited reference tables with interpolation), and a `Utility` class for files, tables, and dialogs. @@ -334,6 +335,43 @@ Units: methods that take plain numbers expect **SI units** (the docstring says so for every parameter); use Pint at the boundaries where units are mixed. See [docs/units.md](https://github.com/kovirlabs/first-principles-code/blob/main/docs/units.md). +## Machine design, fatigue & HVAC + +The everyday sizing checks of a mechanical or HVAC engineer, following +Shigley's *Mechanical Engineering Design* and the *ASHRAE Handbook - +Fundamentals*: bolts, shafts, springs, bearings and welds +(`MachineElements`), stress-life fatigue (`Fatigue`), Euler/Johnson column +buckling (`Material`), and moist-air properties (`Psychrometrics`). + +```python +from fpc import Fatigue, MachineElements, Material, Psychrometrics + +me = MachineElements() +me.bolt_tightening_torque(preload=37.9e3, nominal_diameter=0.012) # 91 N*m (K = 0.2) +me.bearing_l10_life_hours(dynamic_load_rating=30e3, equivalent_load=3e3, speed_rpm=1500) # 11 111 h + +# Fatigue: endurance limit -> Marin factors -> mean-stress criterion. +f = Fatigue() +se = f.marin_endurance_limit( + specimen_endurance_limit=f.endurance_limit_steel(ultimate_strength=690e6), + surface_factor=f.surface_factor(ultimate_strength=690e6, finish="machined"), + size_factor=f.size_factor(diameter=0.03), +) # 237 MPa +f.goodman_safety_factor( + alternating_stress=120e6, mean_stress=80e6, endurance_limit=se, ultimate_strength=690e6 +) # 1.61 + +# Column buckling: picks Euler or Johnson from the slenderness ratio. +Material().critical_buckling_load( + modulus=200e9, moment_of_inertia=1.917e-8, area=4.909e-4, length=0.5, yield_strength=250e6 +) # {'critical_load': 97848.2, 'formula': 'johnson', 'slenderness_ratio': 80.0, ...} + +# Psychrometrics (temperatures in degC, RH as a fraction): solved with brentq. +psy = Psychrometrics() +psy.dew_point(temperature_c=25, relative_humidity=0.5) # 13.9 degC +psy.wet_bulb(temperature_c=25, relative_humidity=0.5) # 17.9 degC +``` + ## Radiology & medical imaging Six classes cover the physics and image handling a radiology student @@ -482,8 +520,18 @@ without writing any code: fpc search "pipe pressure drop" # find a calculation fpc describe Fluids.pipe_flow # its inputs, units and formula fpc run Fluids.reynolds_number density=998 velocity=2 length=0.05 viscosity=0.001 + +# How sure is the answer? Give inputs a spread and run 10 000 cases (Monte Carlo) +fpc uncertainty Fluids.reynolds_number density=998 velocity=normal:2,0.1 length=0.05 viscosity=0.001 + +# File it: a Markdown calc sheet with method, inputs and units, result, review checklist +fpc report Fluids.reynolds_number density=998 velocity=2 length=0.05 viscosity=0.001 --out re.md ``` +Or use every calculation from a web form, with uncertainty and calc-sheet +tabs: `uv run streamlit run apps/calculator.py`. See +[docs/trusting-results.md](https://github.com/kovirlabs/first-principles-code/blob/main/docs/trusting-results.md). + ## Use it with AI assistants (Ollama, LM Studio, Claude, ...) Small local models are unreliable at arithmetic. The `fpc-mcp` command is an @@ -540,17 +588,21 @@ first-principles-code/ │ ├── cli.py # the `fpc` terminal command │ ├── registry.py # catalogue of every calculation (types, units, schemas) │ ├── mcp_server.py # `fpc-mcp`: MCP server for AI apps +│ ├── uncertainty.py # Monte Carlo on any calculation +│ ├── report.py # Markdown calc sheets │ ├── hints.py # shared type-hint names (ArrayLike, FloatArray) │ ├── data/ # cited reference tables (CSV) + sources │ ├── dynamics.py, statics.py, modal.py, thermo.py, fluids.py, -│ ├── material.py, gear.py, electrical.py, mechatronics.py, controls.py +│ ├── material.py, gear.py, electrical.py, mechatronics.py, controls.py, +│ ├── machine_elements.py, fatigue.py, psychrometrics.py │ └── radiation.py, radiography.py, ct.py, mri.py, ultrasound.py, dicom.py ├── examples/ # worked problems, one script each (+ tools/ ladder) +├── apps/ # Streamlit calculator: a form for every calculation ├── templates/ # copy-and-adapt starting script ├── notebooks/ # Jupyter notebooks ├── docs/ # guides + API docs site sources (mkdocs.yml) ├── tests/ # pytest suite (uv run pytest) -├── scripts/ # maintenance scripts (python_support.py: Python version ratchet) +├── scripts/ # maintenance: python_support.py (version ratchet), try_local_model.py (MCP + Ollama) ├── pyproject.toml # metadata, dependencies, tool config ├── PACKAGES.md # Python packages by engineering field ├── SPEC.md # original project design spec diff --git a/ROADMAP.md b/ROADMAP.md index a21bb55..85bc6e0 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -12,8 +12,9 @@ whole: structure, tooling, docs, and discoverability. number next to it. Items marked **(decision needed)** wait on the maintainer's call before work starts. Keep items in priority order within each section. -_Last reviewed: 2026-11-07. Sections 0-8 were built in #6 (branch -`feat/roadmap-buildout`); see "Follow-ups" for what remains._ +_Last reviewed: 2026-11-07. Sections 0-8 were built in #6, most of 9-10 in #8, +and the rest of 9-11 on branch `feat/roadmap-next`; see "Follow-ups" for what +remains._ --- @@ -144,13 +145,13 @@ composing the code directly, so for them we document the API compactly. `list_domains`, `search_calculations`, `describe_calculation`, `calculate`, `list_reference_tables`. Never expose arbitrary code execution. Ships as the `mcp` extra: `pip install "first-principles-code[mcp]"`. -- [ ] **MCP: optional direct tools.** A `--domains fluids,thermo` flag that - also exposes those methods as individual tools with their own schemas - (better for capable models; the SDK builds schemas from signatures, so - this needs a registry-schema -> tool adapter). -- [ ] **Try the MCP server with real local models** (LM Studio + a Qwen / - Llama / Mistral tool-calling model, Open WebUI + Ollama) and tune the tool - descriptions and `INSTRUCTIONS` from what goes wrong. +- [x] **MCP: optional direct tools.** `fpc-mcp --domains fluids,thermo` + also serves each of those calculations as its own tool, with the + registry's schema. +- [x] **Try the MCP server with real local models.** Done with Ollama + (qwen3:14b, qwen2.5:7b, qwen2.5-coder:14b) through + `scripts/try_local_model.py`; results, and the fixes they led to, are in + `docs/ai.md`. The LM Studio and Open WebUI apps themselves: see Follow-ups. - [x] **`fpc search` / `fpc describe` / `fpc run` CLI subcommands**, driven by the registry, so every method is reachable from the terminal. - [x] **`llms.txt` + `AGENTS.md`** for coding agents: a generated, compact @@ -182,22 +183,23 @@ composing the code directly, so for them we document the API compactly. across all of them and a ratchet: `scripts/python_support.py` (`check` / `status` / `set`) plus a monthly workflow that opens an issue when a version is released or retired. See `docs/python-versions.md`. -- [ ] **Streamlit app generated from the registry**: one form per method, - for free, using the existing `apps` dependency group. +- [x] **Streamlit app generated from the registry**: `apps/calculator.py`, + one form per method, with uncertainty and calc-sheet tabs. ## 11. Trust and day-to-day usefulness -- [ ] **Calc reports.** Export a calculation to Markdown/PDF with the - equation, inputs with units, result, and source citation, the way a - checked hand calc is filed for review (compare `handcalcs`). -- [ ] **Worked-example tests with citations.** Tests that reproduce - published textbook examples (e.g. "Shigley Ex. 4-7") so users can trust - the numbers. Pairs with the data-verification follow-ups below. -- [ ] **Domain gaps engineers hit daily:** machine elements (bolts, shafts, - springs, bearings, welds), fatigue (Goodman/Soderberg), column buckling, - psychrometrics/HVAC. -- [ ] **Uncertainty on any calculation:** a Monte Carlo helper that wraps a - registry method and samples its inputs. +- [x] **Calc reports.** `fpc.report` / `fpc report`: Markdown calc sheet + with the method, inputs with units, result, library version and a review + checklist (PDF/Word via pandoc). +- [x] **Worked-example tests with citations** for the new machine-element, + fatigue, buckling and psychrometrics methods (ASHRAE Fundamentals tables, + Shigley Table 6-5). Older domains: see Follow-ups. +- [x] **Domain gaps engineers hit daily:** `MachineElements` (bolts, shafts, + springs, bearings, welds), `Fatigue` (Marin factors, Goodman, Soderberg, + Gerber, ASME-elliptic, S-N), Johnson/Euler column buckling on `Material`, + and `Psychrometrics`. +- [x] **Uncertainty on any calculation:** `fpc.uncertainty.monte_carlo` + and `fpc uncertainty`, with intervals and input sensitivity. --- @@ -211,13 +213,27 @@ Items found while building sections 0-8. values are typical published figures but were entered from reference knowledge, not copied from a fetched source. - [ ] **Verify `fpc/data/w_shapes.csv` against the AISC Shapes Database v16 - spreadsheet.** A test confirms every row is physically self-consistent + spreadsheet.** aisc.org refuses automated downloads, so this needs the + spreadsheet downloaded by hand. A test confirms every row is physically self-consistent (Sx = Ix/(d/2), weight = 3.4 x A), which catches typos but not a consistently wrong row. Extend the table while doing this. - [ ] **Plan the move off Material for MkDocs**, which reaches end of life on 2027-05-05. Its successor, Zensical, reads the existing `mkdocs.yml`. -- [ ] **Tighten mypy** module by module as type hints are added - (`disallow_untyped_defs` per module). +- [x] **Tighten mypy:** `disallow_untyped_defs` and + `disallow_incomplete_defs` for all of `fpc/`. +- [ ] **Spot-check the equation and table numbers** cited in + `fpc/machine_elements.py`, `fpc/fatigue.py` and `fpc/psychrometrics.py` + against Shigley 10th ed. and ASHRAE Fundamentals 2017. The values were + checked; some equation numbers were written from memory. +- [ ] **Psychrometrics enhancement factor.** Humidity ratios use the + ideal-gas equations and differ from ASHRAE Table 2 by about 0.4 %. +- [ ] **Cited worked-example tests for the older domains** (Fluids, Thermo, + Statics, ...), e.g. Moody-chart friction factors, textbook conduction. +- [ ] **Try `fpc-mcp` in the LM Studio and Open WebUI apps**, and add more + question types to `scripts/try_local_model.py` (Properties lookups, + multi-step problems). +- [ ] **An MCP tool for uncertainty** (`calculate_with_uncertainty`) if + model users ask for it; left out for now to keep the tool list at five. - [ ] Consider an InSpice row in place of PySpice in `PACKAGES.md` once InSpice has a longer release history. diff --git a/apps/calculator.py b/apps/calculator.py new file mode 100644 index 0000000..1704225 --- /dev/null +++ b/apps/calculator.py @@ -0,0 +1,199 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""calculator.py - a web form for every calculation in fpc, written once. + +``examples/tools/step4_web_app.py`` hand-builds a form for one calculation. +This app builds a form for *all* of them from :mod:`fpc.registry`: each input +already has a name, a type (number, whole number, list, choice) and a unit, so +the right widget can be chosen automatically. A method added to the library +tomorrow shows up here with no change to this file. + +Run it:: + + uv sync --group apps + uv run streamlit run apps/calculator.py + +Three tabs per calculation: + + * **Result** - the answer (a number, a table for several values, a chart + for a list); + * **Uncertainty** - give any input a +/- percentage and see the spread of + the answer (Monte Carlo, :mod:`fpc.uncertainty`); + * **Calc sheet** - download the calculation as a Markdown report for a + design file (:mod:`fpc.report`). + +Techniques shown: generating a UI from data instead of writing it by hand, +``st.session_state``-free Streamlit (every rerun recomputes from the widgets), +and caching a slow, unchanging result with ``st.cache_data``. +""" + +import json +from typing import Any + +import numpy as np +import pandas as pd +import streamlit as st + +from fpc import registry +from fpc.report import calc_report +from fpc.uncertainty import Normal, monte_carlo + +st.set_page_config(page_title="fpc calculator", layout="wide") + + +def widget(calc_key: str, p: registry.Parameter) -> Any: + """Draw the right input widget for one parameter and return its value. + + The JSON Schema from the registry decides the widget. A required input + starts empty (``None``) so the user must type a value: a made-up default + such as 0 could produce a plausible-looking wrong answer. + + Streamlit remembers a widget's value by its ``key``; including the + calculation in the key keeps ``length`` in one form from leaking into + another form that also has a ``length``. + """ + label = p.name + (f" [{p.unit}]" if p.unit else "") + schema = p.schema or {} + default = None if p.required else p.default + key = f"in:{calc_key}:{p.name}" + if "enum" in schema: + options = schema["enum"] + index = options.index(default) if default in options else 0 + return st.selectbox(label, options, index=index, help=p.description, key=key) + kind = schema.get("type") + if kind == "boolean": + return st.checkbox(label, value=bool(default), help=p.description, key=key) + if kind == "integer": + return st.number_input(label, value=default, step=1, help=p.description, key=key) + if kind == "number": + return st.number_input(label, value=default, format="%g", help=p.description, key=key) + if kind == "string": + return st.text_input(label, value=default or "", help=p.description, key=key) or None + # Arrays, "number or array", and objects: typed as JSON, e.g. [1, 2, 3]. + text = st.text_input( + label + " (JSON, e.g. [1, 2, 3])", + value="" if default is None else json.dumps(default), + help=p.description, + key=key, + ) + if not text or not text.strip(): + return None + try: + return json.loads(text) + except json.JSONDecodeError: + st.error(f"{p.name}: not valid JSON; write numbers like 2.5 or lists like [1, 2, 3]") + st.stop() + + +def show_result(result: Any, returns: str) -> None: + """Show a result in the most readable form for its shape.""" + st.caption(f"Returns: {returns}") + if isinstance(result, dict): + st.table(pd.DataFrame({"value": result})) + elif isinstance(result, list) and result and all(isinstance(v, int | float) for v in result): + st.line_chart(result) + with st.expander("Values"): + st.write(result) + elif isinstance(result, int | float): + st.metric("Result", f"{result:.6g}") + else: + st.write(result) + + +# --- Pick a calculation ------------------------------------------------------- + +with st.sidebar: + st.header("Calculation") + query = st.text_input("Search", placeholder="e.g. pipe pressure drop") + if query: + choices = [c.key for c in registry.search(query, limit=25)] + else: + domain = st.selectbox("Domain", sorted(registry.domains())) + choices = [c.key for c in registry.calculations() if c.domain == domain] + # Only offer calculations whose required inputs a form can collect. + choices = [k for k in choices if registry.get(k).json_callable] + if not choices: + st.warning("No calculation matches.") + st.stop() + key = st.selectbox("Calculation", choices, format_func=lambda k: k.split(".", 1)[1]) + +calc = registry.get(key) +st.title(calc.summary) +st.caption(f"`{calc.key}`") +with st.expander("Method and assumptions", expanded=False): + st.text(calc.description) + +# --- Inputs ----------------------------------------------------------------------- + +st.subheader("Inputs") +columns = st.columns(2) +values: dict[str, Any] = {} +for i, p in enumerate(p for p in calc.parameters if p.schema is not None): + with columns[i % 2]: + values[p.name] = widget(key, p) + +missing = [p.name for p in calc.parameters if p.required and values.get(p.name) is None] +# Leave out optional inputs the user cleared, so the method's default applies. +arguments = {name: v for name, v in values.items() if v is not None} + +if missing: + st.info("Enter " + ", ".join(f"**{name}**" for name in missing) + " to calculate.") + st.stop() + +try: + result = registry.calculate(key, arguments) +except (ValueError, TypeError, KeyError, ZeroDivisionError, ArithmeticError) as error: + st.error(f"{type(error).__name__}: {error}") + st.stop() + +# --- Outputs --------------------------------------------------------------------- + +tab_result, tab_uncertainty, tab_sheet = st.tabs(["Result", "Uncertainty", "Calc sheet"]) + +with tab_result: + show_result(result, calc.returns) + +with tab_uncertainty: + numeric = [ + n + for n, v in arguments.items() + if isinstance(v, int | float) and not isinstance(v, bool) and v != 0 + ] + if not numeric: + st.write("This calculation has no numeric inputs to vary.") + else: + st.write("Give inputs a spread (one standard deviation, as a percent of the value):") + spread = {} + for name in numeric: + spread[name] = st.slider(f"{name} +/- %", 0.0, 20.0, 0.0, 0.5, key=f"pct:{key}:{name}") + # Several results (a dict or tuple): pick which one to study. + output: str | int | None = None + if isinstance(result, dict): + output = st.selectbox("Result to study", list(result)) + elif isinstance(result, list): + output = st.number_input("Result index to study", 0, len(result) - 1, 0) + if any(spread.values()): + inputs = { + n: Normal(mean=v, std=abs(v) * spread[n] / 100) if spread.get(n) else v + for n, v in arguments.items() + } + mc = monte_carlo(key, inputs, samples=5_000, seed=0, output=output) + low, high = mc.interval(95) + a, b, c = st.columns(3) + a.metric("Mean", f"{mc.mean:.6g}") + b.metric("Std. deviation", f"{mc.std:.4g}") + c.metric("95 % interval", f"{low:.4g} to {high:.4g}") + counts, edges = np.histogram(mc.samples, bins=40) + st.bar_chart( + pd.DataFrame({"runs": counts}, index=np.round((edges[:-1] + edges[1:]) / 2, 6)) + ) + st.write("Share of the spread from each input:") + st.bar_chart(pd.Series(mc.sensitivity, name="share")) + +with tab_sheet: + title = st.text_input("Title", value=calc.summary) + checked_by = st.text_input("Checked by", value="") + sheet = calc_report(key, arguments, title=title, checked_by=checked_by) + st.download_button("Download calc sheet (.md)", sheet, file_name=f"{calc.key}.md") + st.markdown(sheet) diff --git a/docs/ai.md b/docs/ai.md index 456304a..625dce7 100644 --- a/docs/ai.md +++ b/docs/ai.md @@ -31,6 +31,20 @@ five tools, deliberately few so that small models choose well: It **cannot** run arbitrary code or read and write files: only the calculations catalogued by `fpc.registry` are callable. +### Direct tools for chosen domains + +`--domains` also turns every calculation in the named domains into its own +tool, with its own input schema: + +```bash +fpc-mcp --domains fluids,thermo # 5 tools + one per Fluids/Thermo calculation +``` + +The model can then call `fluids_reynolds_number(density=..., ...)` in one step +instead of search → describe → calculate. Name only the domains you need: +every tool's schema is sent to the model with each message, and a long tool +list costs context and, for small models, accuracy. + ## Install The server needs the optional `mcp` extra. @@ -103,6 +117,35 @@ Pick a model trained for tool calling (`ollama pull qwen3`, `llama3.1`, `mistral-small`, ...). Very small models (under ~7B parameters) often call tools poorly; that is a model limit, not a server one. +## Tested with local models + +`scripts/try_local_model.py` plays the part of a chat app: it hands the +server's tools to an Ollama model, runs six engineering questions with mixed +units (mm, kN, L/s, mPa·s, µF), and checks each answer against the library. + +```bash +uv run --extra mcp scripts/try_local_model.py --model qwen3:14b --think off +uv run --extra mcp scripts/try_local_model.py --model qwen3:14b --think off \ + --domains fluids,thermo,modal,electrical,radiation -v # -v: full transcripts +``` + +Results on 2026-11-07 (Ollama 0.40, temperature 0, Apple silicon): + +| Model | 5 general tools | `--domains` direct tools | Notes | +|---|---|---|---| +| `qwen3:14b`, thinking off | 6/6 | 6/6 | Recovered from a guessed key and from wrong argument names by reading the error message. | +| `qwen3:14b`, thinking on | 3/6 | 3/6 | Every tool call was right, but after a tool call Ollama put the final answer in the *thinking* field and left the reply empty. Turn thinking off (`--think off`, or `/no_think` in a chat app). | +| `qwen2.5:7b` | 5/6 | 4/6 | Sometimes replies with nothing at all; once forgot to convert the cm result to the mm asked for. | +| `qwen2.5-coder:14b` | 0/6 | 0/6 | Writes the tool call as JSON *text* instead of calling the tool; Ollama's template for this model does not produce native tool calls. Use `qwen3` or `qwen2.5` instead. | + +What the first run changed in the server: `qwen2.5:7b` put the inputs beside +`key` instead of inside `arguments` and retried the same mistake until it gave +up. The `calculate` description now shows the nesting in its example, and a +call without `arguments` gets back the exact shape to send. + +Every unit conversion in these runs (mm → m, kN → N, mPa·s → Pa·s, µF → F) +was done correctly by the model; the arithmetic was done by `fpc`. + ## Claude Desktop and Claude Code Claude Desktop: add the same `"fpc"` block to diff --git a/docs/api/fatigue.md b/docs/api/fatigue.md new file mode 100644 index 0000000..06a7dab --- /dev/null +++ b/docs/api/fatigue.md @@ -0,0 +1,4 @@ + + + +::: fpc.fatigue diff --git a/docs/api/machine_elements.md b/docs/api/machine_elements.md new file mode 100644 index 0000000..c98a541 --- /dev/null +++ b/docs/api/machine_elements.md @@ -0,0 +1,4 @@ + + + +::: fpc.machine_elements diff --git a/docs/api/psychrometrics.md b/docs/api/psychrometrics.md new file mode 100644 index 0000000..1cb8ad5 --- /dev/null +++ b/docs/api/psychrometrics.md @@ -0,0 +1,4 @@ + + + +::: fpc.psychrometrics diff --git a/docs/api/report.md b/docs/api/report.md new file mode 100644 index 0000000..79ea2ea --- /dev/null +++ b/docs/api/report.md @@ -0,0 +1,4 @@ + + + +::: fpc.report diff --git a/docs/api/uncertainty.md b/docs/api/uncertainty.md new file mode 100644 index 0000000..e6cb0f0 --- /dev/null +++ b/docs/api/uncertainty.md @@ -0,0 +1,4 @@ + + + +::: fpc.uncertainty diff --git a/docs/building-tools.md b/docs/building-tools.md index 2cede84..70fb70c 100644 --- a/docs/building-tools.md +++ b/docs/building-tools.md @@ -86,6 +86,20 @@ To share it, deploy to [Streamlit Community Cloud](https://streamlit.io/cloud) or an internal server. Check your organization's data policy before putting engineering data on a public host. +### A form for every calculation + +The app above is written by hand for one calculation. [`apps/calculator.py`](https://github.com/kovirlabs/first-principles-code/blob/main/apps/calculator.py) +builds a form for *every* calculation in the library from the +[calculation registry](api/registry.md): each input's type and unit decide +its widget, so a method added tomorrow appears with no change to the app. + +```bash +uv run streamlit run apps/calculator.py +``` + +Pick a domain and calculation (or search), fill in the inputs, and see the +result, its [uncertainty](trusting-results.md) and a downloadable calc sheet. + ## Rung 5: installed command (`[project.scripts]`) The final step turns the tool into a command that installs with the package. diff --git a/docs/trusting-results.md b/docs/trusting-results.md new file mode 100644 index 0000000..dae5cd4 --- /dev/null +++ b/docs/trusting-results.md @@ -0,0 +1,92 @@ + + + +# Trusting a result: uncertainty and calc sheets + +A number from a calculation is only as good as its inputs, and a result that +goes into a design file has to be checkable by someone else. `fpc` has two +helpers for this, and both work with **every** calculation in the library +because they are driven by the [calculation registry](api/registry.md). + +## How sure is the answer? Monte Carlo + +Real inputs are uncertain: a measured flow is "12 L/s, give or take 3 %", a +pipe's roughness is "somewhere between 0.02 and 0.09 mm". Monte Carlo +simulation runs the calculation thousands of times with inputs drawn at +random from those ranges and reports the spread of the answers. + +```python +from fpc.uncertainty import Normal, Uniform, monte_carlo + +result = monte_carlo( + "Fluids.pipe_flow", + { + "flow": Normal(mean=0.012, std=0.0004), # 12 L/s, 1 sigma = 0.4 L/s + "diameter": 0.1023, + "length": 120, + "roughness": Uniform(low=0.02e-3, high=0.09e-3), + "density": 998, + "viscosity": 1.0e-3, + }, + output="pressure_drop", # pipe_flow returns a dict; study this entry + seed=1, # same random numbers every run: repeatable +) +result.mean, result.std # about 24 300 and 1 900 Pa +result.interval(95) # (low, high) holding 95 % of the runs +result.sensitivity # {"flow": 0.64, "roughness": 0.36}: what to pin down first +``` + +| Distribution | Use it when you know | +|---|---| +| `Normal(mean, std)` | a measurement or manufacturing variation (one standard deviation) | +| `Uniform(low, high)` | only the bounds (a tolerance band) | +| `Triangular(low, mode, high)` | the bounds and a most likely value (an expert's estimate) | + +From the terminal, write an uncertain input as `name=normal:MEAN,STD`, +`name=uniform:LOW,HIGH` or `name=triangular:LOW,MODE,HIGH`: + +```bash +fpc uncertainty Fluids.reynolds_number density=998 velocity=normal:2,0.1 \ + length=0.05 viscosity=uniform:0.0009,0.0011 --seed 1 +``` + +Things to know: + +- A datasheet's "+/- x" is often two or three standard deviations, not one. +- `sensitivity` assumes the inputs are independent and each one pushes the + result in one direction; it is a first look, not a full variance analysis. +- 10 000 samples (the default) is plenty for engineering work; the error in + the mean shrinks like 1/sqrt(samples). + +## File it: calc sheets + +`fpc report` writes a calculation up the way a checked hand calc is filed: +the method and its assumptions (from the docstring), every input with its +unit (defaults included, so nothing is hidden), the result, the library +version, and a review checklist. + +```bash +fpc report Thermo.conduction_heat_rate conductivity=0.72 area=12 \ + delta_temperature=25 thickness=0.2 --title "North wall heat loss" --out wall.md +pandoc wall.md -o wall.pdf # optional: PDF or Word via pandoc +``` + +```python +from fpc.report import calc_report + +text = calc_report( + "Thermo.conduction_heat_rate", + {"conductivity": 0.72, "area": 12, "delta_temperature": 25, "thickness": 0.2}, + title="North wall heat loss", + uncertainty=result_of_monte_carlo, +) # optional extra section +``` + +The sheet is Markdown, so it can live in the project repository next to the +script that produced it and be reviewed in a pull request. + +## Both in a browser + +The [calculator app](building-tools.md#a-form-for-every-calculation) puts +every calculation in a web form, with an **Uncertainty** tab (sliders for ++/- % on each input) and a **Calc sheet** tab that downloads the report. diff --git a/fpc/__init__.py b/fpc/__init__.py index 67fd9c7..55e3cde 100644 --- a/fpc/__init__.py +++ b/fpc/__init__.py @@ -40,13 +40,16 @@ from fpc.dicom import Dicom from fpc.dynamics import Dynamics from fpc.electrical import Electrical +from fpc.fatigue import Fatigue from fpc.fluids import Fluids from fpc.gear import Gear +from fpc.machine_elements import MachineElements from fpc.material import Material from fpc.mechatronics import Mechatronics from fpc.modal import Modal from fpc.mri import MRI from fpc.properties import Properties +from fpc.psychrometrics import Psychrometrics # Medical imaging / radiology classes. from fpc.radiation import Radiation @@ -67,6 +70,9 @@ "Fluids", "Material", "Gear", + "MachineElements", + "Fatigue", + "Psychrometrics", "Electrical", "Mechatronics", "Controls", diff --git a/fpc/beam.py b/fpc/beam.py index 8b39d3d..6b6d330 100644 --- a/fpc/beam.py +++ b/fpc/beam.py @@ -31,6 +31,7 @@ import math from dataclasses import dataclass, field +from typing import Any from pint import Quantity @@ -62,7 +63,7 @@ class Beam: modulus: Quantity = field(default_factory=lambda: STEEL_MODULUS) density: Quantity = field(default_factory=lambda: STEEL_DENSITY) - def __post_init__(self): + def __post_init__(self) -> None: """Validate units and signs right after the object is created. Catching a bad input here (e.g. a time passed where a length belongs, @@ -76,7 +77,7 @@ def __post_init__(self): self._require(self.density, "[mass] / [length] ** 3", "density") @staticmethod - def _require(quantity, dimensionality, name): + def _require(quantity: Any, dimensionality: str, name: str) -> None: """Raise a helpful error unless ``quantity`` is positive with the right units.""" # ``.check()`` confirms the quantity has the expected dimensionality. if not hasattr(quantity, "check") or not quantity.check(dimensionality): @@ -86,12 +87,12 @@ def _require(quantity, dimensionality, name): # --- Geometry (computed on demand) ------------------------------------ @property - def area(self): + def area(self) -> Quantity: """Cross-sectional area A = width * height.""" return self.width * self.height @property - def moment_of_inertia(self): + def moment_of_inertia(self) -> Quantity: """Second moment of area about the bending (strong) axis: I = b*h^3/12. This is the property that resists bending; a taller section (bigger h) @@ -100,12 +101,12 @@ def moment_of_inertia(self): return self.width * self.height**3 / 12 @property - def mass(self): + def mass(self) -> Quantity: """Total mass = density * volume = density * area * length.""" return self.density * self.area * self.length # --- Structural behaviour --------------------------------------------- - def max_deflection_point_load(self, *, load): + def max_deflection_point_load(self, *, load: Quantity) -> Quantity: """Maximum deflection of a simply supported beam with a central load. delta = P * L^3 / (48 * E * I). The result carries length units, so @@ -119,7 +120,7 @@ def max_deflection_point_load(self, *, load): # Reduce to base units so the result reads cleanly as metres. return deflection.to_base_units() - def max_bending_stress_point_load(self, *, load): + def max_bending_stress_point_load(self, *, load: Quantity) -> Quantity: """Peak bending stress for a simply supported beam, central point load. The maximum bending moment is M = P*L/4 at midspan; the peak stress is @@ -134,7 +135,7 @@ def max_bending_stress_point_load(self, *, load): stress = max_moment * distance_to_fibre / self.moment_of_inertia return stress.to_base_units() - def euler_buckling_load(self, *, end_factor=1.0): + def euler_buckling_load(self, *, end_factor: float = 1.0) -> Quantity: """Critical axial buckling load (Euler), about the weakest axis. P_cr = pi^2 * E * I_min / (K*L)^2. A column buckles about whichever diff --git a/fpc/cli.py b/fpc/cli.py index 4760617..c8482f7 100644 --- a/fpc/cli.py +++ b/fpc/cli.py @@ -18,8 +18,11 @@ fpc search "pipe pressure drop" # find any calculation in the library fpc describe Fluids.reynolds_number # its inputs, units and formula fpc run Fluids.reynolds_number density=998 velocity=2 length=0.05 viscosity=0.001 + fpc uncertainty Fluids.reynolds_number density=998 velocity=normal:2,0.1 \ + length=0.05 viscosity=uniform:0.0009,0.0011 + fpc report Fluids.reynolds_number density=998 velocity=2 length=0.05 viscosity=0.001 -The last three are generic: they work for *every* method, because they are +The last five are generic: they work for *every* method, because they are driven by ``fpc.registry`` (a catalogue built from the code's own signatures and docstrings) instead of hand-written argument lists. @@ -29,13 +32,15 @@ import argparse import json +from collections.abc import Callable +from typing import Any from fpc import registry from fpc.fluids import Fluids from fpc.properties import Properties -def _pipe_flow(args): +def _pipe_flow(args: argparse.Namespace) -> None: """Handle ``fpc pipe-flow``.""" props = Properties() t = args.temperature_c @@ -44,8 +49,8 @@ def _pipe_flow(args): diameter=args.diameter_mm / 1000, length=args.length_m, roughness=args.roughness_mm / 1000, - density=props.water_liquid(temperature_c=t, property="density_kg_m3"), - viscosity=props.water_liquid(temperature_c=t, property="dynamic_viscosity_pa_s"), + density=float(props.water_liquid(temperature_c=t, property="density_kg_m3")), + viscosity=float(props.water_liquid(temperature_c=t, property="dynamic_viscosity_pa_s")), ) print(f"velocity {result['velocity']:.3f} m/s") print(f"Reynolds {result['reynolds']:.0f}") @@ -54,7 +59,7 @@ def _pipe_flow(args): print(f"pressure drop {result['pressure_drop'] / 1000:.2f} kPa") -def _water(args): +def _water(args: argparse.Namespace) -> None: """Handle ``fpc water``: print every liquid-water property at a temperature.""" props = Properties() columns = props.load_table(name="water_liquid_1atm").columns.drop("temperature_c") @@ -64,13 +69,13 @@ def _water(args): print(f" {column:<28} {value:.5g}") -def _search(args): +def _search(args: argparse.Namespace) -> None: """Handle ``fpc search``: list calculations matching some keywords.""" for calc in registry.search(args.query, limit=args.limit, domain=args.domain): print(f"{calc.key:<45} {calc.summary}") -def _describe(args): +def _describe(args: argparse.Namespace) -> None: """Handle ``fpc describe``: show one calculation's inputs and units.""" try: calc = registry.get(args.key) @@ -88,7 +93,7 @@ def _describe(args): print(f"Returns: {calc.returns}") -def _parse_value(text): +def _parse_value(text: str) -> Any: """Turn ``"998"`` into 998, ``"[1, 2]"`` into a list, and leave words as strings. JSON already knows how to read numbers, lists and true/false, so we try @@ -100,14 +105,20 @@ def _parse_value(text): return text -def _run(args): - """Handle ``fpc run``: call any calculation with ``name=value`` pairs.""" +def _pairs(pairs: list[str], parse: Callable[[str], Any] = _parse_value) -> dict[str, Any]: + """Turn ``["density=998", ...]`` into ``{"density": 998, ...}``.""" arguments = {} - for pair in args.arguments: + for pair in pairs: name, sep, value = pair.partition("=") if not sep: raise SystemExit(f"expected name=value, got {pair!r}") - arguments[name] = _parse_value(value) + arguments[name] = parse(value) + return arguments + + +def _run(args: argparse.Namespace) -> None: + """Handle ``fpc run``: call any calculation with ``name=value`` pairs.""" + arguments = _pairs(args.arguments) try: result = registry.calculate(args.key, arguments) except (KeyError, ValueError, TypeError) as error: @@ -115,12 +126,51 @@ def _run(args): print(json.dumps(result, indent=2)) -def _llms_txt(args): +def _uncertainty(args: argparse.Namespace) -> None: + """Handle ``fpc uncertainty``: Monte Carlo on any calculation.""" + from fpc.uncertainty import monte_carlo, parse_distribution + + def parse(text: str) -> Any: + # A distribution ("normal:2,0.1") or a number; anything else (a word + # such as property=density_kg_m3) passes through like ``fpc run``. + try: + return parse_distribution(text) + except ValueError: + return _parse_value(text) + + inputs = _pairs(args.arguments, parse) + output = int(args.output) if args.output and args.output.isdigit() else args.output + try: + result = monte_carlo(args.key, inputs, samples=args.samples, seed=args.seed, output=output) + except (KeyError, ValueError, TypeError) as error: + raise SystemExit(f"error: {error}") from error + print(json.dumps(result.summary(), indent=2)) + + +def _report(args: argparse.Namespace) -> None: + """Handle ``fpc report``: a Markdown calc sheet for one calculation.""" + from fpc.report import calc_report + + try: + text = calc_report( + args.key, _pairs(args.arguments), title=args.title, checked_by=args.checked_by + ) + except (KeyError, ValueError, TypeError) as error: + raise SystemExit(f"error: {error}") from error + if args.out: + with open(args.out, "w", encoding="utf-8") as file: + file.write(text) + print(f"wrote {args.out}") + else: + print(text, end="") + + +def _llms_txt(args: argparse.Namespace) -> None: """Handle ``fpc llms-txt``: print the AI-assistant index of the library.""" print(registry.llms_txt(), end="") -def build_parser(): +def build_parser() -> argparse.ArgumentParser: """Build the top-level parser with one subparser per tool.""" parser = argparse.ArgumentParser( prog="fpc", @@ -165,12 +215,37 @@ def build_parser(): run.add_argument("arguments", nargs="*", help="inputs as name=value (SI units unless stated)") run.set_defaults(handler=_run) + unc = tools.add_parser( + "uncertainty", + help="Monte Carlo: run a calculation with uncertain inputs", + description="Inputs are name=value; make one uncertain with name=normal:MEAN,STD, " + "name=uniform:LOW,HIGH or name=triangular:LOW,MODE,HIGH.", + ) + unc.add_argument("key", help="Domain.method, e.g. Fluids.pipe_flow") + unc.add_argument("arguments", nargs="*", help="inputs as name=value or name=normal:mean,std") + unc.add_argument("--samples", type=int, default=10_000, help="random runs (default 10000)") + unc.add_argument("--seed", type=int, help="fix the random numbers to repeat a run exactly") + unc.add_argument("--output", help="for several results: a dict key or tuple index to study") + unc.set_defaults(handler=_uncertainty) + + report = tools.add_parser("report", help="write a Markdown calc sheet for a calculation") + report.add_argument("key", help="Domain.method, e.g. Fluids.reynolds_number") + report.add_argument( + "arguments", nargs="*", help="inputs as name=value (SI units unless stated)" + ) + report.add_argument( + "--title", help="heading for the sheet (default: the calculation's summary)" + ) + report.add_argument("--checked-by", default="", help="name for the 'Checked by' line") + report.add_argument("--out", help="write to this file instead of printing") + report.set_defaults(handler=_report) + llms = tools.add_parser("llms-txt", help="print a compact index of the library for AI tools") llms.set_defaults(handler=_llms_txt) return parser -def main(argv=None): +def main(argv: list[str] | None = None) -> None: """Entry point for the ``fpc`` command. :param argv: list of arguments (defaults to the real command line); diff --git a/fpc/design.py b/fpc/design.py index 2ec4b97..3e2516b 100644 --- a/fpc/design.py +++ b/fpc/design.py @@ -27,6 +27,8 @@ import numpy as np from scipy.optimize import brentq, minimize +from fpc.hints import FloatArray + class Design: """Design-by-calculation helpers: size and optimize simple parts.""" @@ -152,25 +154,25 @@ def lightest_rectangular_beam( :raises RuntimeError: if the optimizer fails to find a feasible design """ - def mass(x): + def mass(x: FloatArray) -> float: width, height = x return density * width * height * length # Scale the objective to "about 1" by dividing by the starting mass. # Gradient-based optimizers converge far more reliably on well-scaled # numbers than on raw values that may be 1e-3 or 1e4. - start = [np.mean(width_bounds), np.mean(height_bounds)] + start = np.array([np.mean(width_bounds), np.mean(height_bounds)]) reference_mass = mass(start) - def scaled_mass(x): + def scaled_mass(x: FloatArray) -> float: return mass(x) / reference_mass - def stress_margin(x): + def stress_margin(x: FloatArray) -> float: width, height = x stress = self._bending_stress(load=load, length=length, width=width, height=height) return 1 - stress / allowable_stress - def deflection_margin(x): + def deflection_margin(x: FloatArray) -> float: width, height = x deflection = self._deflection( load=load, @@ -181,7 +183,7 @@ def deflection_margin(x): ) return 1 - deflection / max_deflection - def aspect_margin(x): + def aspect_margin(x: FloatArray) -> float: width, height = x return 1 - height / (max_aspect_ratio * width) diff --git a/fpc/fatigue.py b/fpc/fatigue.py new file mode 100644 index 0000000..c751cca --- /dev/null +++ b/fpc/fatigue.py @@ -0,0 +1,405 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""fatigue.py - high-cycle fatigue of metals (the stress-life method). + +Most mechanical failures are fatigue failures: a part that easily survives +its load once cracks after millions of repetitions at a fraction of that +load. The stress-life method estimates how long a part lasts, or how safe it +is, in four steps (Shigley's *Mechanical Engineering Design*, 10th ed., +Ch. 6): + +1. **Estimate the test-specimen endurance limit** Se' from the ultimate + strength (``endurance_limit_steel``). +2. **Correct it for the real part** with the Marin factors - surface finish, + size, load type, temperature, reliability - to get Se + (``surface_factor``, ``size_factor``, ``load_factor``, + ``reliability_factor``, ``marin_endurance_limit``). +3. **Account for mean stress** with a failure line on the + alternating-vs-mean stress diagram: Goodman, Soderberg, Gerber, or + ASME-elliptic (the ``*_safety_factor`` methods). +4. **For finite life**, use the Basquin S-N line between 10^3 and 10^6 + cycles (``sn_curve_coefficients``, ``cycles_to_failure``). + +Stresses and strengths are in pascals. The empirical curve fits from the +literature are in MPa; the methods convert internally, so you never have to. +These estimates are for steels; other metals have no true endurance limit. +""" + +import math +from typing import Literal + +from scipy.stats import norm + +# Surface factor ka = a * Sut^b with Sut in MPa (Shigley 10th ed., Table 6-2). +# Rougher finishes have more and deeper surface flaws where cracks start, so +# ka drops - and drops faster for stronger, more notch-sensitive steels. +_SURFACE_COEFFICIENTS: dict[str, tuple[float, float]] = { + "ground": (1.58, -0.085), + "machined": (4.51, -0.265), # machined or cold-drawn + "cold-drawn": (4.51, -0.265), + "hot-rolled": (57.7, -0.718), + "as-forged": (272.0, -0.995), +} + +# Load factor kc (Shigley Eq. 6-26): rotating-beam tests are in bending, and +# a part loaded axially or in torsion has a lower endurance limit. +_LOAD_FACTORS = {"bending": 1.0, "axial": 0.85, "torsion": 0.59} + +SurfaceFinish = Literal["ground", "machined", "cold-drawn", "hot-rolled", "as-forged"] +LoadType = Literal["bending", "axial", "torsion"] + + +class Fatigue: + """Stress-life fatigue: endurance limits, Marin factors, mean-stress criteria.""" + + # Pascals per megapascal, for the curve fits that are written in MPa. + _MPA = 1e6 + + # --- Step 1: the test-specimen endurance limit --------------------------- + + def endurance_limit_steel(self, *, ultimate_strength: float) -> float: + """Rotating-beam endurance limit estimate for steels, Shigley Eq. 6-8. + + Se' = 0.5 * Sut for Sut <= 1400 MPa + Se' = 700 MPa for Sut > 1400 MPa + + This is the endurance limit of a small, polished, rotating test + specimen - not of your part. Apply the Marin factors next. The + plateau reflects test data: very strong steels gain no further + fatigue resistance because tiny inclusions start the cracks. + + :param ultimate_strength: ultimate tensile strength Sut [Pa] + :returns: specimen endurance limit Se' [Pa] + :raises ValueError: if Sut is not positive + """ + if ultimate_strength <= 0: + raise ValueError("ultimate_strength must be positive") + return min(0.5 * ultimate_strength, 700 * self._MPA) + + # --- Step 2: Marin factors ---------------------------------------------- + + def surface_factor(self, *, ultimate_strength: float, finish: SurfaceFinish) -> float: + """Marin surface factor ka = a * Sut^b, Shigley Eq. 6-19 / Table 6-2. + + finish a b + ground 1.58 -0.085 + machined/cold-drawn 4.51 -0.265 + hot-rolled 57.7 -0.718 + as-forged 272 -0.995 + + (a for Sut in MPa.) The result is capped at 1: a fit is not allowed + to make a part *better* than the polished test specimen. + + :param ultimate_strength: ultimate tensile strength Sut [Pa] + :param finish: surface finish of the part + :returns: surface factor ka [-] + :raises ValueError: if Sut is not positive + """ + if ultimate_strength <= 0: + raise ValueError("ultimate_strength must be positive") + a, b = _SURFACE_COEFFICIENTS[finish] + return min(1.0, a * (ultimate_strength / self._MPA) ** b) + + def size_factor(self, *, diameter: float, loading: LoadType = "bending") -> float: + """Marin size factor kb for a round bar, Shigley Eq. 6-20. + + Bigger parts have more highly stressed material, so more chance of a + flaw where a crack can start. For rotating round bars in bending or + torsion, with d in mm: + + kb = 1.24 * d^-0.107 for 2.79 <= d <= 51 mm + kb = 1.51 * d^-0.157 for 51 < d <= 254 mm + + Axial loading has no stress gradient, so kb = 1. For a non-rotating + or non-round section, first convert to an equivalent diameter + (Shigley Sec. 6-9) and pass that. + + :param diameter: bar diameter d [m] + :param loading: ``"bending"``, ``"torsion"`` or ``"axial"`` + :returns: size factor kb [-] + :raises ValueError: for a diameter outside 2.79-254 mm + """ + if loading == "axial": + return 1.0 + d_mm = diameter * 1e3 + if not 2.79 <= d_mm <= 254: + raise ValueError( + f"size factor fit covers 2.79 to 254 mm; got {d_mm:g} mm (pass metres)" + ) + if d_mm <= 51: + return 1.24 * d_mm**-0.107 + return 1.51 * d_mm**-0.157 + + def load_factor(self, *, loading: LoadType) -> float: + """Marin load factor kc, Shigley Eq. 6-26: 1 bending, 0.85 axial, 0.59 torsion. + + The 0.59 for torsion is the distortion-energy ratio 1/sqrt(3) = 0.577, + rounded up to match test data. Do *not* use kc = 0.59 if you combine + torsion into a von Mises stress - that already accounts for it. + + :param loading: ``"bending"``, ``"axial"`` or ``"torsion"`` + :returns: load factor kc [-] + """ + return _LOAD_FACTORS[loading] + + def reliability_factor(self, *, reliability: float) -> float: + """Marin reliability factor ke = 1 - 0.08 * za, Shigley Table 6-5. + + Endurance-limit data scatter with a standard deviation of about 8 % + of the mean. Se' is a *mean* value (50 % reliability); to be sure that + a fraction R of parts survive, step down za standard deviations, where + za is the standard-normal variate with probability R below it. SciPy's + ``norm.ppf`` (the inverse normal CDF) gives za directly, so this + reproduces Table 6-5 without the table: R = 0.99 -> za = 2.326 -> + ke = 0.814. + + :param reliability: required probability of survival R, e.g. 0.99 [-] + :returns: reliability factor ke [-] + :raises ValueError: unless 0.5 <= R < 1 + """ + if not 0.5 <= reliability < 1: + raise ValueError("reliability must be in [0.5, 1), e.g. 0.99 for 99 %") + return 1 - 0.08 * float(norm.ppf(reliability)) + + def marin_endurance_limit( + self, + *, + specimen_endurance_limit: float, + surface_factor: float = 1.0, + size_factor: float = 1.0, + load_factor: float = 1.0, + temperature_factor: float = 1.0, + reliability_factor: float = 1.0, + miscellaneous_factor: float = 1.0, + ) -> float: + """Endurance limit of the real part: Se = ka*kb*kc*kd*ke*kf * Se', Shigley Eq. 6-18. + + Each Marin factor is a multiplier, usually below 1, that corrects the + laboratory value for one way the real part differs from the test + specimen. Compute them with the methods above (kd, the temperature + factor, is about 1 up to ~250 degC for steels). + + :param specimen_endurance_limit: test-specimen endurance limit Se' [Pa] + :param surface_factor: ka [-] + :param size_factor: kb [-] + :param load_factor: kc [-] + :param temperature_factor: kd [-] + :param reliability_factor: ke [-] + :param miscellaneous_factor: kf (corrosion, plating, ...) [-] + :returns: corrected endurance limit Se [Pa] + :raises ValueError: if Se' or any factor is not positive + """ + factors = ( + surface_factor, + size_factor, + load_factor, + temperature_factor, + reliability_factor, + miscellaneous_factor, + ) + if specimen_endurance_limit <= 0 or min(factors) <= 0: + raise ValueError("endurance limit and Marin factors must be positive") + return specimen_endurance_limit * math.prod(factors) + + # --- Step 3: mean-stress failure criteria --------------------------------- + # + # Each criterion is a line (or curve) on the alternating-vs-mean stress + # diagram from (0, Se) to the mean-stress axis. The safety factor n scales + # the load point (sigma_m, sigma_a) until it reaches that line. Goodman is + # the usual design choice; Soderberg is more conservative; Gerber and + # ASME-elliptic run through the middle of the test data. + + @staticmethod + def _check_stresses(alternating_stress: float, mean_stress: float) -> None: + if alternating_stress <= 0: + raise ValueError("alternating_stress must be positive") + if mean_stress < 0: + # A compressive mean stress does not shorten fatigue life; Shigley + # then uses n = Se / sigma_a (with a separate yield check). + raise ValueError("these criteria assume mean_stress >= 0 (tensile)") + + def goodman_safety_factor( + self, + *, + alternating_stress: float, + mean_stress: float, + endurance_limit: float, + ultimate_strength: float, + ) -> float: + """Fatigue safety factor, modified Goodman line: 1/n = sa/Se + sm/Sut. + + A straight line from Se on the alternating axis to Sut on the mean + axis. Simple, slightly conservative, and the most common choice. + + :param alternating_stress: alternating stress amplitude sigma_a [Pa] + :param mean_stress: mean stress sigma_m (>= 0) [Pa] + :param endurance_limit: corrected endurance limit Se [Pa] + :param ultimate_strength: ultimate tensile strength Sut [Pa] + :returns: fatigue safety factor n [-] + :raises ValueError: for non-positive sigma_a or negative sigma_m + """ + self._check_stresses(alternating_stress, mean_stress) + return 1 / (alternating_stress / endurance_limit + mean_stress / ultimate_strength) + + def soderberg_safety_factor( + self, + *, + alternating_stress: float, + mean_stress: float, + endurance_limit: float, + yield_strength: float, + ) -> float: + """Fatigue safety factor, Soderberg line: 1/n = sa/Se + sm/Sy. + + Like Goodman but ending at the yield strength, so it also guards + against yielding. The most conservative of the four criteria. + + :param alternating_stress: alternating stress amplitude sigma_a [Pa] + :param mean_stress: mean stress sigma_m (>= 0) [Pa] + :param endurance_limit: corrected endurance limit Se [Pa] + :param yield_strength: yield strength Sy [Pa] + :returns: fatigue safety factor n [-] + :raises ValueError: for non-positive sigma_a or negative sigma_m + """ + self._check_stresses(alternating_stress, mean_stress) + return 1 / (alternating_stress / endurance_limit + mean_stress / yield_strength) + + def gerber_safety_factor( + self, + *, + alternating_stress: float, + mean_stress: float, + endurance_limit: float, + ultimate_strength: float, + ) -> float: + """Fatigue safety factor, Gerber parabola: n*sa/Se + (n*sm/Sut)^2 = 1. + + A parabola through the middle of ductile-steel test data. Solving the + quadratic for its positive root (Shigley Table 6-7): + + n = 1/2 * (Sut/sm)^2 * (sa/Se) * [ -1 + sqrt(1 + (2*sm*Se/(Sut*sa))^2) ] + + With no mean stress the parabola meets the axis at Se, so n = Se/sa. + + :param alternating_stress: alternating stress amplitude sigma_a [Pa] + :param mean_stress: mean stress sigma_m (>= 0) [Pa] + :param endurance_limit: corrected endurance limit Se [Pa] + :param ultimate_strength: ultimate tensile strength Sut [Pa] + :returns: fatigue safety factor n [-] + :raises ValueError: for non-positive sigma_a or negative sigma_m + """ + self._check_stresses(alternating_stress, mean_stress) + if mean_stress == 0: + # The closed form divides by sigma_m; its limit as sigma_m -> 0 is Se/sa. + return endurance_limit / alternating_stress + sa, sm, se, sut = alternating_stress, mean_stress, endurance_limit, ultimate_strength + return ( + 0.5 + * (sut / sm) ** 2 + * (sa / se) + * (-1 + math.sqrt(1 + (2 * sm * se / (sut * sa)) ** 2)) + ) + + def asme_elliptic_safety_factor( + self, + *, + alternating_stress: float, + mean_stress: float, + endurance_limit: float, + yield_strength: float, + ) -> float: + """Fatigue safety factor, ASME-elliptic: (n*sa/Se)^2 + (n*sm/Sy)^2 = 1. + + A quarter ellipse from Se to Sy; it fits test data well and, ending + at Sy, includes a yield check. Solving directly: + + n = 1 / sqrt( (sa/Se)^2 + (sm/Sy)^2 ) + + :param alternating_stress: alternating stress amplitude sigma_a [Pa] + :param mean_stress: mean stress sigma_m (>= 0) [Pa] + :param endurance_limit: corrected endurance limit Se [Pa] + :param yield_strength: yield strength Sy [Pa] + :returns: fatigue safety factor n [-] + :raises ValueError: for non-positive sigma_a or negative sigma_m + """ + self._check_stresses(alternating_stress, mean_stress) + return 1 / math.sqrt( + (alternating_stress / endurance_limit) ** 2 + (mean_stress / yield_strength) ** 2 + ) + + # --- Step 4: finite life (S-N curve) ------------------------------------- + + def sn_curve_coefficients( + self, + *, + ultimate_strength: float, + endurance_limit: float, + fatigue_strength_fraction: float = 0.9, + ) -> dict[str, float]: + """Basquin S-N line Sf = a * N^b through (10^3, f*Sut) and (10^6, Se). + + On log-log axes the high-cycle S-N curve of steel is close to a + straight line between 10^3 cycles, where the strength is a fraction f + of Sut, and 10^6 cycles, where it reaches the endurance limit. Fitting + Sf = a * N^b through those two points gives (Shigley Eqs. 6-14, 6-15) + + a = (f*Sut)^2 / Se b = -1/3 * log10(f*Sut / Se) + + f is about 0.9 for Sut up to ~490 MPa, falling to ~0.77 at 1400 MPa + (Shigley Fig. 6-18). + + :param ultimate_strength: ultimate tensile strength Sut [Pa] + :param endurance_limit: corrected endurance limit Se [Pa] + :param fatigue_strength_fraction: f, the fraction of Sut at 10^3 cycles [-] + :returns: dict with ``a`` [Pa] and ``b`` [-] + :raises ValueError: for non-positive strengths or f*Sut <= Se + """ + if ultimate_strength <= 0 or endurance_limit <= 0: + raise ValueError("ultimate_strength and endurance_limit must be positive") + if not 0 < fatigue_strength_fraction <= 1: + raise ValueError("fatigue_strength_fraction must be in (0, 1]") + strength_1e3 = fatigue_strength_fraction * ultimate_strength + if strength_1e3 <= endurance_limit: + raise ValueError("f*Sut must exceed Se for the S-N line to slope downward") + return { + "a": strength_1e3**2 / endurance_limit, + "b": -math.log10(strength_1e3 / endurance_limit) / 3, + } + + def cycles_to_failure( + self, + *, + alternating_stress: float, + ultimate_strength: float, + endurance_limit: float, + fatigue_strength_fraction: float = 0.9, + ) -> float: + """Cycles to failure under fully reversed stress: N = (sigma_a / a)^(1/b). + + Inverts the Basquin line from ``sn_curve_coefficients``. Below the + endurance limit the steel is predicted to last indefinitely, so the + result is ``inf``. For mean stress, first convert to an equivalent + fully reversed stress, e.g. sigma_rev = sigma_a / (1 - sigma_m/Sut) + (Goodman). + + :param alternating_stress: fully reversed stress amplitude sigma_a [Pa] + :param ultimate_strength: ultimate tensile strength Sut [Pa] + :param endurance_limit: corrected endurance limit Se [Pa] + :param fatigue_strength_fraction: f, the fraction of Sut at 10^3 cycles [-] + :returns: cycles to failure N (``inf`` below the endurance limit) [cycles] + :raises ValueError: for sigma_a above f*Sut, the low-cycle region + (N < 10^3) where the Basquin line does not apply + """ + if alternating_stress <= 0: + raise ValueError("alternating_stress must be positive") + if alternating_stress <= endurance_limit: + return math.inf + if alternating_stress > fatigue_strength_fraction * ultimate_strength: + raise ValueError("stress above f*Sut: low-cycle fatigue (N < 1e3), out of range") + coefficients = self.sn_curve_coefficients( + ultimate_strength=ultimate_strength, + endurance_limit=endurance_limit, + fatigue_strength_fraction=fatigue_strength_fraction, + ) + return (alternating_stress / coefficients["a"]) ** (1 / coefficients["b"]) diff --git a/fpc/machine_elements.py b/fpc/machine_elements.py new file mode 100644 index 0000000..6a473e7 --- /dev/null +++ b/fpc/machine_elements.py @@ -0,0 +1,481 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""machine_elements.py - bolts, shafts, springs, bearings, and welds. + +Machine elements are the standard parts every mechanical design is built +from. This class collects the first-pass sizing equations a design engineer +reaches for daily, in the form given in Shigley's *Mechanical Engineering +Design* (Budynas & Nisbett, 10th ed.): + +* **Bolted joints** (Ch. 8): tightening torque, recommended preload, bolt and + member stiffness, the joint constant C, and how an external load is shared + between the bolt and the clamped members. +* **Shafts** (Ch. 7): the diameter needed for combined bending and torsion, + both statically (von Mises) and in fatigue (DE-Goodman). +* **Helical compression springs** (Ch. 10): spring rate and the curvature- + corrected wire shear stress. +* **Rolling bearings** (Ch. 11): L10 rating life and the catalogue rating + needed for a target life. +* **Fillet welds** (Ch. 9): the conventional throat shear stress. + +All inputs and outputs are SI floats (N, m, Pa, N*m) unless the parameter +name says otherwise (``speed_rpm``, ``life_hours``). These are *first-pass* +equations: they size a part quickly and transparently, but a final design +still needs the full code or catalogue check. +""" + +import math +from typing import Literal + + +class MachineElements: + """Sizing equations for bolts, shafts, springs, bearings, and welds.""" + + # --- Bolted joints ----------------------------------------------------- + + def bolt_tightening_torque( + self, *, preload: float, nominal_diameter: float, torque_coefficient: float = 0.2 + ) -> float: + """Wrench torque needed to reach a bolt preload: T = K * Fi * d. + + Shigley Eq. 8-27. The torque coefficient K lumps together thread and + under-head friction; almost all of the torque is lost to friction and + only ~10 % actually stretches the bolt, which is why K matters so + much. K = 0.2 is the usual value for unlubricated steel bolts of any + finish; lubricated or cadmium-plated bolts are nearer 0.15-0.16. + + :param preload: target bolt preload Fi [N] + :param nominal_diameter: bolt nominal (major) diameter d [m] + :param torque_coefficient: torque (nut) factor K, default 0.2 [-] + :returns: tightening torque T [N*m] + :raises ValueError: if any input is not positive + """ + if preload <= 0 or nominal_diameter <= 0 or torque_coefficient <= 0: + raise ValueError("preload, nominal_diameter and torque_coefficient must be positive") + return torque_coefficient * preload * nominal_diameter + + def bolt_preload( + self, + *, + proof_strength: float, + tensile_stress_area: float, + connection: Literal["reusable", "permanent"] = "reusable", + ) -> float: + """Recommended bolt preload as a fraction of the proof load. + + The proof load is Fp = At * Sp: the largest load the bolt carries with + no permanent set. Shigley (Sec. 8-9) recommends tightening to + + Fi = 0.75 * Fp for reusable (removable) connections, + Fi = 0.90 * Fp for permanent connections. + + A high preload keeps the joint clamped (so the bolt sees only a small + share of any fluctuating load - see ``bolted_joint_loads``), which is + the main reason preloaded bolts survive fatigue. + + :param proof_strength: bolt proof strength Sp (e.g. ISO 8.8: 600 MPa) [Pa] + :param tensile_stress_area: thread tensile-stress area At [m^2] + :param connection: ``"reusable"`` (0.75 Fp) or ``"permanent"`` (0.90 Fp) + :returns: recommended preload Fi [N] + :raises ValueError: if strength or area is not positive + """ + if proof_strength <= 0 or tensile_stress_area <= 0: + raise ValueError("proof_strength and tensile_stress_area must be positive") + fraction = {"reusable": 0.75, "permanent": 0.90}[connection] + return fraction * proof_strength * tensile_stress_area + + def bolt_stiffness( + self, + *, + modulus: float, + nominal_diameter: float, + tensile_stress_area: float, + unthreaded_length: float, + threaded_length: float, + ) -> float: + """Axial stiffness of a bolt within the grip: kb = Ad*At*E / (Ad*lt + At*ld). + + Shigley Eq. 8-17. Inside the clamped grip, a bolt is two springs in + series: the plain shank (area Ad = pi*d^2/4, length ld) and the + threaded part (tensile-stress area At, length lt). Springs in series + add their *flexibilities* (L / (A*E)), which gives this formula. + + :param modulus: bolt Young's modulus E (steel ~207e9) [Pa] + :param nominal_diameter: bolt nominal diameter d [m] + :param tensile_stress_area: thread tensile-stress area At [m^2] + :param unthreaded_length: length of plain shank in the grip ld [m] + :param threaded_length: length of thread in the grip lt [m] + :returns: bolt stiffness kb [N/m] + :raises ValueError: for non-positive sizes or a grip of zero length + """ + if modulus <= 0 or nominal_diameter <= 0 or tensile_stress_area <= 0: + raise ValueError("modulus, nominal_diameter and tensile_stress_area must be positive") + if unthreaded_length < 0 or threaded_length < 0: + raise ValueError("lengths in the grip cannot be negative") + if unthreaded_length + threaded_length == 0: + raise ValueError("the grip length (unthreaded + threaded) must be positive") + shank_area = math.pi * nominal_diameter**2 / 4 + return ( + shank_area + * tensile_stress_area + * modulus + / (shank_area * threaded_length + tensile_stress_area * unthreaded_length) + ) + + def member_stiffness( + self, *, modulus: float, nominal_diameter: float, grip_length: float + ) -> float: + """Stiffness of the clamped members, using 30-degree pressure cones. + + Shigley Eq. 8-23. The clamping pressure spreads out from under the + bolt head and nut as two cones of half-angle 30 deg. Integrating the + compliance of those frusta, for members of one material with washer + face diameter 1.5*d, gives + + km = 0.5774*pi*E*d / (2 * ln( 5*(0.5774*l + 0.5*d) / (0.5774*l + 2.5*d) )) + + (0.5774 = tan 30 deg). The members are usually much stiffer than the + bolt, which is why the bolt carries only a small share of the load. + + :param modulus: Young's modulus of the members E [Pa] + :param nominal_diameter: bolt nominal diameter d [m] + :param grip_length: total thickness of the clamped members l [m] + :returns: member stiffness km [N/m] + :raises ValueError: if any input is not positive + """ + if modulus <= 0 or nominal_diameter <= 0 or grip_length <= 0: + raise ValueError("modulus, nominal_diameter and grip_length must be positive") + tan30 = math.tan(math.radians(30.0)) + d, length = nominal_diameter, grip_length + log_term = math.log(5 * (tan30 * length + 0.5 * d) / (tan30 * length + 2.5 * d)) + return tan30 * math.pi * modulus * d / (2 * log_term) + + def joint_stiffness_constant(self, *, bolt_stiffness: float, member_stiffness: float) -> float: + """Joint constant C = kb / (kb + km): the bolt's share of an external load. + + Bolt and members are springs in *parallel* under an external load P + (both stretch by the same amount until the joint separates), so the + load divides in proportion to stiffness: the bolt takes C*P and the + members are unloaded by (1 - C)*P. Typical values are 0.15-0.35. + + :param bolt_stiffness: bolt stiffness kb [N/m] + :param member_stiffness: member stiffness km [N/m] + :returns: joint stiffness constant C [-] + :raises ValueError: if either stiffness is not positive + """ + if bolt_stiffness <= 0 or member_stiffness <= 0: + raise ValueError("stiffnesses must be positive") + return bolt_stiffness / (bolt_stiffness + member_stiffness) + + def bolted_joint_loads( + self, *, preload: float, external_load: float, stiffness_constant: float + ) -> dict[str, float]: + """Bolt and member forces in a preloaded joint under an external tensile load. + + From Shigley Sec. 8-7 (valid while the joint stays clamped): + + Fb = C*P + Fi (bolt tension) + Fm = (1 - C)*P - Fi (member force; negative = still compressed) + P0 = Fi / (1 - C) (external load that separates the joint) + + :param preload: bolt preload Fi [N] + :param external_load: external tensile load per bolt P [N] + :param stiffness_constant: joint constant C from ``joint_stiffness_constant`` [-] + :returns: dict with ``bolt_load`` [N], ``member_load`` [N], + ``separation_load`` [N], and ``separation_factor`` P0/P [-] + :raises ValueError: for C outside (0, 1), a negative load, or a joint + that has already separated (P >= P0) + """ + if not 0 < stiffness_constant < 1: + raise ValueError("stiffness_constant must be between 0 and 1") + if preload < 0 or external_load < 0: + raise ValueError("preload and external_load cannot be negative") + separation_load = preload / (1 - stiffness_constant) + if external_load >= separation_load: + # Past separation the members carry nothing and the bolt carries + # all of P; the linear spring model above no longer applies. + raise ValueError( + f"joint separates: external_load {external_load:g} N >= " + f"separation load {separation_load:g} N" + ) + return { + "bolt_load": stiffness_constant * external_load + preload, + "member_load": (1 - stiffness_constant) * external_load - preload, + "separation_load": separation_load, + "separation_factor": ( + separation_load / external_load if external_load > 0 else math.inf + ), + } + + # --- Shafts ------------------------------------------------------------ + + def shaft_diameter_static( + self, *, bending_moment: float, torque: float, yield_strength: float, safety_factor: float + ) -> float: + """Solid shaft diameter for steady bending + torsion (von Mises yield). + + A solid round shaft has bending stress sigma = 32*M/(pi*d^3) and + torsional shear tau = 16*T/(pi*d^3). Their von Mises equivalent is + + sigma' = sqrt(sigma^2 + 3*tau^2) = 16/(pi*d^3) * sqrt(4*M^2 + 3*T^2). + + Setting sigma' = Sy / n and solving for d: + + d = ( 16*n / (pi*Sy) * sqrt(4*M^2 + 3*T^2) )^(1/3) + + Use this for loads that do not fluctuate (or as a first-cycle yield + check). A rotating shaft under a steady moment sees *fully reversed* + bending, so it also needs the fatigue check in + ``shaft_diameter_de_goodman``. + + :param bending_moment: bending moment M [N*m] + :param torque: torque T [N*m] + :param yield_strength: shaft material yield strength Sy [Pa] + :param safety_factor: design factor n [-] + :returns: minimum shaft diameter d [m] + :raises ValueError: for non-positive strength/safety factor or no load + """ + if yield_strength <= 0 or safety_factor <= 0: + raise ValueError("yield_strength and safety_factor must be positive") + load_term = math.sqrt(4 * bending_moment**2 + 3 * torque**2) + if load_term == 0: + raise ValueError("bending_moment and torque cannot both be zero") + return (16 * safety_factor / (math.pi * yield_strength) * load_term) ** (1 / 3) + + def shaft_diameter_de_goodman( + self, + *, + alternating_moment: float, + mean_moment: float, + alternating_torque: float, + mean_torque: float, + endurance_limit: float, + ultimate_strength: float, + safety_factor: float, + fatigue_factor_bending: float = 1.0, + fatigue_factor_torsion: float = 1.0, + ) -> float: + """Solid shaft diameter for fatigue (DE-Goodman criterion), Shigley Eq. 7-8. + + Combines distortion-energy (von Mises) stresses with the modified + Goodman line. The alternating and mean von Mises stresses are each + built from bending (x 4) and torsion (x 3) exactly as in the static + case, then weighted by the endurance limit and ultimate strength: + + d = { 16*n/pi * [ sqrt(4*(Kf*Ma)^2 + 3*(Kfs*Ta)^2) / Se + + sqrt(4*(Kf*Mm)^2 + 3*(Kfs*Tm)^2) / Sut ] }^(1/3) + + A typical rotating shaft with steady torque has Mm = 0 and Ta = 0. + The endurance limit Se must already include the Marin factors (see + ``Fatigue.marin_endurance_limit``); the size factor depends on d, so + size iteratively: guess d, find Se, solve, repeat. Goodman does not + guard against first-cycle yield - check that separately. + + :param alternating_moment: alternating bending moment Ma [N*m] + :param mean_moment: mean bending moment Mm [N*m] + :param alternating_torque: alternating torque Ta [N*m] + :param mean_torque: mean torque Tm [N*m] + :param endurance_limit: fully corrected endurance limit Se [Pa] + :param ultimate_strength: ultimate tensile strength Sut [Pa] + :param safety_factor: design factor n [-] + :param fatigue_factor_bending: fatigue stress-concentration factor Kf [-] + :param fatigue_factor_torsion: fatigue stress-concentration factor Kfs [-] + :returns: minimum shaft diameter d [m] + :raises ValueError: for non-positive strengths, factors, or no load + """ + if endurance_limit <= 0 or ultimate_strength <= 0 or safety_factor <= 0: + raise ValueError("strengths and safety_factor must be positive") + if fatigue_factor_bending < 1 or fatigue_factor_torsion < 1: + raise ValueError("stress-concentration factors are >= 1 (use 1 for none)") + kf, kfs = fatigue_factor_bending, fatigue_factor_torsion + alternating = math.sqrt( + 4 * (kf * alternating_moment) ** 2 + 3 * (kfs * alternating_torque) ** 2 + ) + mean = math.sqrt(4 * (kf * mean_moment) ** 2 + 3 * (kfs * mean_torque) ** 2) + if alternating == 0 and mean == 0: + raise ValueError("at least one moment or torque must be non-zero") + bracket = alternating / endurance_limit + mean / ultimate_strength + return (16 * safety_factor / math.pi * bracket) ** (1 / 3) + + # --- Helical compression springs ---------------------------------------- + + def spring_rate( + self, + *, + wire_diameter: float, + mean_coil_diameter: float, + active_coils: float, + shear_modulus: float, + ) -> float: + """Rate of a helical compression spring: k = d^4 * G / (8 * D^3 * Na). + + Shigley Eq. 10-9. The wire is a long torsion bar wound into a helix, + so the rate comes from torsional strain energy. Note the powers: wire + diameter to the 4th, coil diameter to the 3rd - small changes in d or + D swing the rate a lot. + + :param wire_diameter: wire diameter d [m] + :param mean_coil_diameter: mean coil diameter D (outer minus d) [m] + :param active_coils: number of active coils Na (may be fractional) [-] + :param shear_modulus: wire shear modulus G (music wire ~81.7e9) [Pa] + :returns: spring rate k [N/m] + :raises ValueError: for non-positive inputs or D <= d + """ + if min(wire_diameter, mean_coil_diameter, active_coils, shear_modulus) <= 0: + raise ValueError("all spring inputs must be positive") + if mean_coil_diameter <= wire_diameter: + raise ValueError("mean_coil_diameter must exceed wire_diameter (check D vs d)") + return wire_diameter**4 * shear_modulus / (8 * mean_coil_diameter**3 * active_coils) + + def spring_shear_stress( + self, + *, + force: float, + wire_diameter: float, + mean_coil_diameter: float, + correction: Literal["wahl", "bergstrasser"] = "wahl", + ) -> float: + """Maximum wire shear stress in a helical spring: tau = K * 8*F*D / (pi*d^3). + + 8*F*D/(pi*d^3) is the plain torsion stress in the wire. The factor K + corrects for direct shear and for wire curvature, which concentrates + stress on the inside of the coil. With spring index C = D/d: + + Wahl: K_W = (4C - 1)/(4C - 4) + 0.615/C + Bergstrasser: K_B = (4C + 2)/(4C - 3) (Shigley Eq. 10-5) + + The two agree within about 1 %. Practical springs have 4 <= C <= 12. + + :param force: axial spring force F [N] + :param wire_diameter: wire diameter d [m] + :param mean_coil_diameter: mean coil diameter D [m] + :param correction: stress-correction factor, ``"wahl"`` or ``"bergstrasser"`` + :returns: maximum shear stress tau [Pa] + :raises ValueError: for non-positive sizes or a spring index C <= 1 + """ + if wire_diameter <= 0 or mean_coil_diameter <= 0: + raise ValueError("wire_diameter and mean_coil_diameter must be positive") + index = mean_coil_diameter / wire_diameter + if index <= 1: + raise ValueError("spring index D/d must be greater than 1 (check D vs d)") + if correction == "wahl": + factor = (4 * index - 1) / (4 * index - 4) + 0.615 / index + else: + factor = (4 * index + 2) / (4 * index - 3) + return factor * 8 * force * mean_coil_diameter / (math.pi * wire_diameter**3) + + # --- Rolling bearings ---------------------------------------------------- + + # Load-life exponent a in L10 = (C/P)^a: 3 for ball bearings (point + # contact), 10/3 for roller bearings (line contact). + _LIFE_EXPONENT = {"ball": 3.0, "roller": 10.0 / 3.0} + + def bearing_l10_life( + self, + *, + dynamic_load_rating: float, + equivalent_load: float, + bearing_type: Literal["ball", "roller"] = "ball", + ) -> float: + """Bearing rating life L10 = (C / P)^a, in millions of revolutions. + + L10 is the life that 90 % of a large group of identical bearings + reach or exceed. The catalogue dynamic load rating C is, by + definition, the load giving an L10 of one million revolutions, so the + load-life relation (Shigley Ch. 11) normalises to (C/P)^a with + a = 3 for ball bearings and a = 10/3 for roller bearings. Doubling + the load cuts a ball bearing's life by 2^3 = 8. + + :param dynamic_load_rating: catalogue basic dynamic load rating C [N] + :param equivalent_load: equivalent dynamic bearing load P [N] + :param bearing_type: ``"ball"`` (a = 3) or ``"roller"`` (a = 10/3) + :returns: L10 life [million rev] + :raises ValueError: if either load is not positive + """ + if dynamic_load_rating <= 0 or equivalent_load <= 0: + raise ValueError("dynamic_load_rating and equivalent_load must be positive") + exponent = self._LIFE_EXPONENT[bearing_type] + return (dynamic_load_rating / equivalent_load) ** exponent + + def bearing_l10_life_hours( + self, + *, + dynamic_load_rating: float, + equivalent_load: float, + speed_rpm: float, + bearing_type: Literal["ball", "roller"] = "ball", + ) -> float: + """Bearing rating life in operating hours: L10h = L10 * 1e6 / (60 * n). + + Converts the revolution life from ``bearing_l10_life`` to hours at a + constant shaft speed n (rev/min, so 60*n revolutions per hour). + + :param dynamic_load_rating: catalogue basic dynamic load rating C [N] + :param equivalent_load: equivalent dynamic bearing load P [N] + :param speed_rpm: shaft speed n [rev/min] + :param bearing_type: ``"ball"`` or ``"roller"`` + :returns: L10 life [h] + :raises ValueError: for non-positive loads or speed + """ + if speed_rpm <= 0: + raise ValueError("speed_rpm must be positive") + revolutions = self.bearing_l10_life( + dynamic_load_rating=dynamic_load_rating, + equivalent_load=equivalent_load, + bearing_type=bearing_type, + ) + return revolutions * 1e6 / (60 * speed_rpm) + + def bearing_required_load_rating( + self, + *, + equivalent_load: float, + life_hours: float, + speed_rpm: float, + bearing_type: Literal["ball", "roller"] = "ball", + ) -> float: + """Catalogue rating C needed to reach a target L10 life: C = P * L10^(1/a). + + The load-life relation turned around for selection: work out the + design life in millions of revolutions, L10 = 60 * n * Lh / 1e6, then + pick a bearing whose catalogue C is at least this value. + + :param equivalent_load: equivalent dynamic bearing load P [N] + :param life_hours: required L10 life Lh [h] + :param speed_rpm: shaft speed n [rev/min] + :param bearing_type: ``"ball"`` or ``"roller"`` + :returns: minimum basic dynamic load rating C [N] + :raises ValueError: for non-positive inputs + """ + if equivalent_load <= 0 or life_hours <= 0 or speed_rpm <= 0: + raise ValueError("equivalent_load, life_hours and speed_rpm must be positive") + life_million_rev = 60 * speed_rpm * life_hours / 1e6 + return equivalent_load * life_million_rev ** (1 / self._LIFE_EXPONENT[bearing_type]) + + # --- Welds --------------------------------------------------------------- + + def fillet_weld_shear_stress( + self, *, force: float, leg_size: float, weld_length: float + ) -> float: + """Average shear stress on a fillet weld throat: tau = F / (0.707 * h * L). + + The throat is the smallest section of a 45-degree fillet: t = h * + cos 45 = 0.707*h for leg size h. The conventional design rule + (Shigley Sec. 9-3, and the AWS/AISC codes) treats the load on the + throat area 0.707*h*L as pure shear for *both* parallel (load along + the weld) and transverse (load across the weld) fillets. That is + exact enough for parallel welds and conservative for transverse ones, + which are in fact about a third stronger. + + :param force: load carried by the weld group F [N] + :param leg_size: fillet leg size h [m] + :param weld_length: total effective length of weld L [m] + (add up every bead that shares the load) + :returns: throat shear stress tau [Pa] + :raises ValueError: if leg size or length is not positive + """ + if leg_size <= 0 or weld_length <= 0: + raise ValueError("leg_size and weld_length must be positive") + throat = leg_size * math.cos(math.radians(45.0)) + return force / (throat * weld_length) diff --git a/fpc/material.py b/fpc/material.py index 47a4551..109a341 100644 --- a/fpc/material.py +++ b/fpc/material.py @@ -5,8 +5,9 @@ This class covers how materials deform and fail under load: Hooke's law, the stress-strain relationship, beam bending, thermal expansion, and column -buckling. These are the calculations that decide whether a part is stiff -enough, strong enough, and stable enough. +buckling (Euler for long columns, the Johnson parabola for intermediate +ones, and a method that picks between them). These are the calculations that +decide whether a part is stiff enough, strong enough, and stable enough. """ import math @@ -89,6 +90,11 @@ def euler_buckling_load( P_cr = pi^2 * E * I / (K*L)^2. + Only valid while the column stays elastic, i.e. for slenderness + ratios KL/r above ``transition_slenderness_ratio``. For shorter + columns use ``johnson_buckling_load``, or let + ``critical_buckling_load`` choose. + :param modulus: Young's modulus E [Pa] :param moment_of_inertia: smallest second moment of area I [m^4] :param length: unsupported column length L [m] @@ -98,3 +104,167 @@ def euler_buckling_load( """ effective_length = end_factor * length return math.pi**2 * modulus * moment_of_inertia / effective_length**2 + + # --- Column buckling beyond Euler --------------------------------------- + # + # Euler's formula assumes the column stays elastic right up to buckling. + # For a short or medium column the Euler stress P/A would exceed the + # yield strength, so the column yields (or buckles inelastically) first. + # The J. B. Johnson parabola covers that "intermediate" range, and the + # slenderness ratio KL/r decides which formula applies (Shigley's + # Mechanical Engineering Design, 10th ed., Ch. 4, "Columns with Central + # Loading" and "Intermediate-Length Columns with Central Loading"). + # These live here, beside Euler, because they are one topic: the + # automatic chooser below calls both formulas. + + def radius_of_gyration(self, *, moment_of_inertia: float, area: float) -> float: + """Radius of gyration r = sqrt(I / A). + + The distance from the axis at which the whole area, concentrated in + a thin ring, would have the same second moment I. Use the *smallest* + I of the section: a column buckles about its weakest axis. + + :param moment_of_inertia: smallest second moment of area I [m^4] + :param area: cross-sectional area A [m^2] + :returns: radius of gyration r [m] + :raises ValueError: if I or A is not positive + """ + if moment_of_inertia <= 0 or area <= 0: + raise ValueError("moment_of_inertia and area must be positive") + return math.sqrt(moment_of_inertia / area) + + def slenderness_ratio( + self, *, length: float, radius_of_gyration: float, end_factor: float = 1.0 + ) -> float: + """Slenderness ratio of a column: KL / r. + + One number that captures how prone a column is to buckling: long, + thin columns (large KL/r) buckle elastically; stubby ones simply + crush or yield. + + :param length: unsupported column length L [m] + :param radius_of_gyration: least radius of gyration r [m] + :param end_factor: effective-length factor K (1.0 pinned-pinned, + 0.5 fixed-fixed, 2.0 fixed-free) [-] + :returns: slenderness ratio KL/r [-] + :raises ValueError: for non-positive inputs + """ + if length <= 0 or radius_of_gyration <= 0 or end_factor <= 0: + raise ValueError("length, radius_of_gyration and end_factor must be positive") + return end_factor * length / radius_of_gyration + + def transition_slenderness_ratio(self, *, modulus: float, yield_strength: float) -> float: + """Slenderness ratio where Euler hands over to Johnson: sqrt(2*pi^2*E / Sy). + + At this KL/r the Euler critical stress pi^2*E/(KL/r)^2 equals Sy/2, + and the Johnson parabola is built to meet Euler there with the same + value and slope. Columns more slender than this are "long" (Euler); + less slender ones are "intermediate" (Johnson). For structural steel + (E = 200 GPa, Sy = 250 MPa) it is about 126. + + :param modulus: Young's modulus E [Pa] + :param yield_strength: yield strength Sy [Pa] + :returns: transition slenderness ratio (KL/r)_1 [-] + :raises ValueError: if E or Sy is not positive + """ + if modulus <= 0 or yield_strength <= 0: + raise ValueError("modulus and yield_strength must be positive") + return math.sqrt(2 * math.pi**2 * modulus / yield_strength) + + def johnson_buckling_load( + self, + *, + modulus: float, + moment_of_inertia: float, + area: float, + length: float, + yield_strength: float, + end_factor: float = 1.0, + ) -> float: + """Critical load of an intermediate column (J. B. Johnson parabola). + + P_cr = A * [ Sy - (Sy * (KL/r) / (2*pi))^2 / E ] + + A parabola in KL/r that starts at the yield load A*Sy for a zero- + length column and meets the Euler curve tangentially at the + transition slenderness ratio. Only valid for KL/r up to that ratio; + ``critical_buckling_load`` picks the right formula for you. + + :param modulus: Young's modulus E [Pa] + :param moment_of_inertia: smallest second moment of area I [m^4] + :param area: cross-sectional area A [m^2] + :param length: unsupported column length L [m] + :param yield_strength: yield strength Sy [Pa] + :param end_factor: effective-length factor K, defaults to pinned-pinned [-] + :returns: critical axial load [N] + :raises ValueError: for non-positive inputs + """ + if modulus <= 0 or yield_strength <= 0: + raise ValueError("modulus and yield_strength must be positive") + r = self.radius_of_gyration(moment_of_inertia=moment_of_inertia, area=area) + slenderness = self.slenderness_ratio( + length=length, radius_of_gyration=r, end_factor=end_factor + ) + reduction = (yield_strength * slenderness / (2 * math.pi)) ** 2 / modulus + return area * (yield_strength - reduction) + + def critical_buckling_load( + self, + *, + modulus: float, + moment_of_inertia: float, + area: float, + length: float, + yield_strength: float, + end_factor: float = 1.0, + ) -> dict[str, float | str]: + """Critical column load, choosing Euler or Johnson from the slenderness ratio. + + Computes KL/r and the transition ratio sqrt(2*pi^2*E/Sy), then uses + Euler for long columns (KL/r >= transition) and Johnson for + intermediate ones. The two formulas give the same load at the + transition (A*Sy/2), so the answer is continuous. Divide the result + by your design factor to get an allowable load. + + :param modulus: Young's modulus E [Pa] + :param moment_of_inertia: smallest second moment of area I [m^4] + :param area: cross-sectional area A [m^2] + :param length: unsupported column length L [m] + :param yield_strength: yield strength Sy [Pa] + :param end_factor: effective-length factor K, defaults to pinned-pinned [-] + :returns: dict with ``critical_load`` [N], ``formula`` ("euler" or + "johnson"), ``slenderness_ratio`` [-] and + ``transition_slenderness_ratio`` [-] + :raises ValueError: for non-positive inputs + """ + r = self.radius_of_gyration(moment_of_inertia=moment_of_inertia, area=area) + slenderness = self.slenderness_ratio( + length=length, radius_of_gyration=r, end_factor=end_factor + ) + transition = self.transition_slenderness_ratio( + modulus=modulus, yield_strength=yield_strength + ) + if slenderness >= transition: + formula = "euler" + load = self.euler_buckling_load( + modulus=modulus, + moment_of_inertia=moment_of_inertia, + length=length, + end_factor=end_factor, + ) + else: + formula = "johnson" + load = self.johnson_buckling_load( + modulus=modulus, + moment_of_inertia=moment_of_inertia, + area=area, + length=length, + yield_strength=yield_strength, + end_factor=end_factor, + ) + return { + "critical_load": load, + "formula": formula, + "slenderness_ratio": slenderness, + "transition_slenderness_ratio": transition, + } diff --git a/fpc/mcp_server.py b/fpc/mcp_server.py index dbf08d9..871e5fc 100644 --- a/fpc/mcp_server.py +++ b/fpc/mcp_server.py @@ -29,15 +29,25 @@ fpc-mcp # stdio, what desktop AI apps expect fpc-mcp --transport streamable-http --port 8765 # HTTP, for web front ends + fpc-mcp --domains fluids,thermo # also one tool per Fluids/Thermo method + +``--domains`` suits capable models: each calculation becomes its own tool with +its own schema, so the model can call it in one step instead of +search -> describe -> calculate. Keep the list short; every tool's schema is +sent to the model with each request. Setup for LM Studio, Ollama front ends, and Claude is in ``docs/ai.md``. Requires the optional ``mcp`` extra: ``pip install "first-principles-code[mcp]"``. """ import argparse -from collections.abc import Iterator +import inspect +import json +from collections.abc import Callable, Iterator, Sequence from contextlib import contextmanager -from typing import Any +from typing import Annotated, Any + +from pydantic import Field, WithJsonSchema try: from mcp.server import MCPServer @@ -93,13 +103,73 @@ def _explain_errors() -> Iterator[None]: raise ToolError(f"{type(error).__name__}: {message}") from error -def build_server() -> MCPServer: +def tool_name(calc: registry.Calculation) -> str: + """MCP tool name for a calculation: ``Fluids.reynolds_number`` -> ``fluids_reynolds_number``. + + Many AI apps pass tools on to an OpenAI-style API that only accepts + letters, digits, ``_`` and ``-`` in a name, so the dot has to go. + """ + return f"{calc.domain.lower()}_{calc.name}" + + +def direct_tool(calc: registry.Calculation) -> Callable[..., dict[str, Any]]: + """Turn one registry calculation into a function the MCP library can serve. + + The MCP library builds a tool's input schema from the function's + *signature*, the way FastAPI does. The domain methods themselves can't be + handed over: their hints (``ArrayLike``, ``Literal``) say what *Python* + accepts, and some inputs (a DataFrame) can't travel as JSON at all. The + registry already knows the JSON Schema of every input, so we build a new + signature from it: + + * one keyword-only parameter per JSON-able input; + * annotated ``Annotated[Any, WithJsonSchema(schema), Field(description)]``, + which tells pydantic "accept anything, but *advertise* this schema". + The real checking happens in :func:`registry.calculate`, the same + doorway the CLI and the ``calculate`` tool use. + + Setting ``__signature__`` is how Python lets a function describe itself + differently from its ``def`` line; ``inspect.signature`` (and therefore + pydantic and the MCP library) reads it. + + :param calc: the calculation to expose + :returns: a function taking the calculation's inputs as keyword arguments + """ + + def run(**arguments: Any) -> dict[str, Any]: + with _explain_errors(): + return {"result": registry.calculate(calc.key, arguments), "returns": calc.returns} + + parameters = [] + for p in calc.parameters: + if p.schema is None: + continue # cannot be sent as JSON; keeps its default (json_callable checked) + # The description carries the unit, the most important thing for the model. + description = p.description + ( + f" [{p.unit}]" if p.unit and "[" not in p.description else "" + ) + annotation = Annotated[Any, WithJsonSchema(p.schema), Field(description=description)] + default = p.default if not p.required else inspect.Parameter.empty + parameters.append( + inspect.Parameter( + p.name, inspect.Parameter.KEYWORD_ONLY, default=default, annotation=annotation + ) + ) + run.__signature__ = inspect.Signature(parameters, return_annotation=dict[str, Any]) # type: ignore[attr-defined] + run.__name__ = tool_name(calc) + return run + + +def build_server(domains: Sequence[str] = ()) -> MCPServer: """Create the MCP server and register its tools. Kept separate from :func:`main` so tests can connect to the server in-process (``mcp.Client(build_server())``) without starting a subprocess. + :param domains: domain names (any case, e.g. ``["fluids", "thermo"]``) + whose calculations also become individual tools :returns: a configured ``MCPServer`` + :raises ValueError: if a domain name is unknown """ server = MCPServer("first-principles-code", instructions=INSTRUCTIONS) @@ -146,16 +216,25 @@ def describe_calculation(key: str) -> dict[str, Any]: return registry.get(key).to_dict() @server.tool() - def calculate(key: str, arguments: dict[str, Any]) -> dict[str, Any]: + def calculate(key: str, arguments: dict[str, Any] | None = None) -> dict[str, Any]: """Run a calculation and return its exact result. key: "Domain.method", e.g. "Fluids.reynolds_number". - arguments: keyword arguments, each in the unit given by - describe_calculation, e.g. {"density": 998, "velocity": 2, - "length": 0.05, "viscosity": 0.001}. + arguments: an object holding the inputs, each in the unit given by + describe_calculation. Nest them, e.g. {"key": "Fluids.reynolds_number", + "arguments": {"density": 998, "velocity": 2, "length": 0.05, "viscosity": 0.001}}. """ with _explain_errors(): calc = registry.get(key) + if arguments is None: + # Small models often put the inputs next to "key" instead of + # inside "arguments". The MCP library drops unknown keys before + # we see them, so all we can do is say exactly what to send. + example = {p.name: f"<{p.unit or 'value'}>" for p in calc.parameters if p.required} + raise ToolError( + 'the inputs must be nested inside "arguments", like this: ' + + json.dumps({"key": key, "arguments": example}) + ) result = registry.calculate(key, arguments) units = {p.name: p.unit for p in calc.parameters} return { @@ -177,6 +256,18 @@ def list_reference_tables() -> dict[str, list[str]]: props = Properties() return {name: list(props.load_table(name=name).columns) for name in props.list_tables()} + known = {name.lower(): name for name in registry.domains()} + unknown = sorted({d.lower() for d in domains} - set(known)) + if unknown: + raise ValueError(f"unknown domain(s) {unknown}; choose from {sorted(known.values())}") + wanted = {known[d.lower()] for d in domains} + for calc in registry.calculations(): + if calc.domain in wanted and calc.json_callable: + # The description is what the model reads to choose a tool, so + # lead with the summary and finish with what comes back. + description = f"{calc.description}\n\nReturns: {calc.returns}".strip() + server.add_tool(direct_tool(calc), name=tool_name(calc), description=description) + return server @@ -196,9 +287,18 @@ def main(argv: list[str] | None = None) -> None: ) parser.add_argument("--host", default="127.0.0.1", help="HTTP bind address (default 127.0.0.1)") parser.add_argument("--port", type=int, default=8765, help="HTTP port (default 8765)") + parser.add_argument( + "--domains", + default="", + help="comma-separated domains whose calculations also become individual tools, " + "e.g. fluids,thermo (for capable models; keep it short)", + ) args = parser.parse_args(argv) - server = build_server() + try: + server = build_server([d.strip() for d in args.domains.split(",") if d.strip()]) + except ValueError as error: + parser.error(str(error)) if args.transport == "stdio": server.run("stdio") else: diff --git a/fpc/modal.py b/fpc/modal.py index 62b77cb..ad1356d 100644 --- a/fpc/modal.py +++ b/fpc/modal.py @@ -166,7 +166,9 @@ def fit_damped_response( time = np.asarray(time, dtype=float) displacement = np.asarray(displacement, dtype=float) - def model(t, amplitude, zeta, omega_n, phase): + def model( + t: FloatArray, amplitude: float, zeta: float, omega_n: float, phase: float + ) -> FloatArray: omega_d = omega_n * np.sqrt(1 - zeta**2) return amplitude * np.exp(-zeta * omega_n * t) * np.cos(omega_d * t + phase) diff --git a/fpc/psychrometrics.py b/fpc/psychrometrics.py new file mode 100644 index 0000000..4b0fa23 --- /dev/null +++ b/fpc/psychrometrics.py @@ -0,0 +1,325 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""psychrometrics.py - properties of moist air for HVAC and drying. + +Psychrometrics is the thermodynamics of air-water vapour mixtures: how much +water the air holds, when it condenses, and how much energy it carries. It +sizes every air conditioner, cooling tower, dryer, and clean room. + +Everything here follows the ideal-gas formulation in the *ASHRAE +Handbook - Fundamentals* (2017, Ch. 1, "Psychrometrics"), which is accurate +to a fraction of a percent at ordinary pressures: + +* saturation vapour pressure from the Hyland-Wexler equations (Eqs. 5-6); +* humidity ratio W = 0.621945 * pw / (p - pw) (Eq. 20); +* moist-air enthalpy h = 1.006*t + W*(2501 + 1.86*t) (Eq. 32); +* specific volume from the ideal-gas law; +* wet-bulb temperature from the energy balance of an adiabatic saturator + (Eq. 33, and its ice form below 0 degC). + +**Units.** Pressures are in pascals and humidity ratio in kg of water per kg +of *dry* air - the "per kg dry air" basis is what makes the mass balances +work, because the dry air flow does not change as water is added or removed. +Following the HVAC convention (and ``docs/units.md``), temperatures are in +degC and named ``temperature_c``; enthalpy is in kJ/kg dry air. Relative +humidity is a fraction from 0 to 1, not a percentage. + +Dew point and wet bulb have no closed form, so - like +``Fluids.colebrook_friction_factor`` - they are solved with +``scipy.optimize.brentq``. +""" + +import math +from typing import Literal + +from scipy.optimize import brentq + +# Hyland-Wexler coefficients for ln(pws) with pws in Pa and T in K +# (ASHRAE Handbook - Fundamentals 2017, Ch. 1, Eqs. 5 and 6). +# Over ice, -100 to 0 degC: +_ICE = ( + -5.6745359e03, + 6.3925247e00, + -9.6778430e-03, + 6.2215701e-07, + 2.0747825e-09, + -9.4840240e-13, + 4.1635019e00, +) +# Over liquid water, 0 to 200 degC: +_WATER = ( + -5.8002206e03, + 1.3914993e00, + -4.8640239e-02, + 4.1764768e-05, + -1.4452093e-08, + 6.5459673e00, +) + +# Ratio of the molar masses of water and dry air, 18.015268 / 28.966. +_MOLAR_MASS_RATIO = 0.621945 +# Gas constant of dry air [J/(kg*K)], used for the specific volume. +_R_DRY_AIR = 287.042 + +Phase = Literal["auto", "water", "ice"] + + +class Psychrometrics: + """Moist-air properties (ASHRAE ideal-gas psychrometrics, SI).""" + + # Standard sea-level atmospheric pressure [Pa]. + STANDARD_PRESSURE = 101325.0 + + def standard_pressure(self, *, altitude: float) -> float: + """Standard-atmosphere pressure at an altitude, ASHRAE 2017 Ch. 1 Eq. 3. + + p = 101.325 * (1 - 2.25577e-5 * Z)^5.2559 kPa + + Psychrometric charts are drawn for sea level; in Denver (~1600 m) the + pressure is ~17 % lower, so the same air holds noticeably more water + per kg. Pass this result as ``pressure`` to the other methods. + + :param altitude: altitude above sea level Z [m] + :returns: atmospheric pressure [Pa] + :raises ValueError: for altitudes outside -5000 to 11000 m + """ + if not -5000 <= altitude <= 11000: + raise ValueError("altitude must be between -5000 and 11000 m (troposphere)") + return self.STANDARD_PRESSURE * (1 - 2.25577e-5 * altitude) ** 5.2559 + + def saturation_vapor_pressure(self, *, temperature_c: float, phase: Phase = "auto") -> float: + """Saturation pressure of water vapour (Hyland-Wexler), ASHRAE 2017 Ch. 1 Eqs. 5-6. + + Over ice (-100 to 0 degC): + ln pws = C1/T + C2 + C3*T + C4*T^2 + C5*T^3 + C6*T^4 + C7*ln T + Over liquid water (0 to 200 degC): + ln pws = C8/T + C9 + C10*T + C11*T^2 + C12*T^3 + C13*ln T + + with T in kelvin and pws in pascals. This is the most-used number in + psychrometrics: the most water vapour air can hold at a temperature. + It roughly doubles every 10 degC, which is why warm air holds so + much more moisture. ``"auto"`` uses ice below 0 degC, as ASHRAE's + tables do; ``"water"`` below 0 gives supercooled liquid. + + :param temperature_c: temperature t [degC], -100 to 200 + :param phase: ``"auto"``, ``"water"`` or ``"ice"`` + :returns: saturation vapour pressure pws [Pa] + :raises ValueError: for a temperature outside -100 to 200 degC, or + ice above 0 degC + """ + if not -100 <= temperature_c <= 200: + raise ValueError("temperature_c must be between -100 and 200 degC") + if phase == "auto": + phase = "ice" if temperature_c < 0 else "water" + if phase == "ice" and temperature_c > 0.01: + raise ValueError("ice does not exist above 0.01 degC (the triple point)") + t = temperature_c + 273.15 + if phase == "ice": + c1, c2, c3, c4, c5, c6, c7 = _ICE + ln_p = c1 / t + c2 + c3 * t + c4 * t**2 + c5 * t**3 + c6 * t**4 + c7 * math.log(t) + else: + c8, c9, c10, c11, c12, c13 = _WATER + ln_p = c8 / t + c9 + c10 * t + c11 * t**2 + c12 * t**3 + c13 * math.log(t) + return math.exp(ln_p) + + def humidity_ratio( + self, *, vapor_pressure: float, pressure: float = STANDARD_PRESSURE + ) -> float: + """Humidity ratio W = 0.621945 * pw / (p - pw), ASHRAE 2017 Ch. 1 Eq. 20. + + Dalton's law: the vapour and the dry air share the total pressure, + p = pw + pa. Each behaves as an ideal gas, so the mass ratio is the + ratio of partial pressures times the ratio of molar masses + (18.015 / 28.966 = 0.621945). + + :param vapor_pressure: partial pressure of water vapour pw [Pa] + :param pressure: total (barometric) pressure p, default sea level [Pa] + :returns: humidity ratio W [kg/kg dry air] + :raises ValueError: unless 0 <= pw < p + """ + if not 0 <= vapor_pressure < pressure: + raise ValueError("vapor_pressure must be >= 0 and below the total pressure") + return _MOLAR_MASS_RATIO * vapor_pressure / (pressure - vapor_pressure) + + def vapor_pressure( + self, *, humidity_ratio: float, pressure: float = STANDARD_PRESSURE + ) -> float: + """Vapour partial pressure from humidity ratio: pw = p * W / (0.621945 + W). + + The inverse of ``humidity_ratio``. + + :param humidity_ratio: humidity ratio W [kg/kg dry air] + :param pressure: total (barometric) pressure p, default sea level [Pa] + :returns: partial pressure of water vapour pw [Pa] + :raises ValueError: for a negative humidity ratio or pressure + """ + if humidity_ratio < 0 or pressure <= 0: + raise ValueError("humidity_ratio cannot be negative and pressure must be positive") + return pressure * humidity_ratio / (_MOLAR_MASS_RATIO + humidity_ratio) + + def relative_humidity(self, *, temperature_c: float, vapor_pressure: float) -> float: + """Relative humidity phi = pw / pws(t). + + How close the air is to saturation at its own temperature. Cooling + air raises phi without changing its water content, until phi = 1 at + the dew point. + + :param temperature_c: dry-bulb temperature t [degC] + :param vapor_pressure: partial pressure of water vapour pw [Pa] + :returns: relative humidity phi, 0 to 1 [-] + :raises ValueError: for a negative vapour pressure + """ + if vapor_pressure < 0: + raise ValueError("vapor_pressure cannot be negative") + return vapor_pressure / self.saturation_vapor_pressure(temperature_c=temperature_c) + + def humidity_ratio_from_relative_humidity( + self, + *, + temperature_c: float, + relative_humidity: float, + pressure: float = STANDARD_PRESSURE, + ) -> float: + """Humidity ratio from dry bulb and relative humidity: W(phi * pws(t), p). + + The everyday entry point: a thermostat or weather report gives you + temperature and RH, and nearly every HVAC calculation then needs W. + + :param temperature_c: dry-bulb temperature t [degC] + :param relative_humidity: relative humidity phi as a fraction, 0 to 1 [-] + :param pressure: total (barometric) pressure p, default sea level [Pa] + :returns: humidity ratio W [kg/kg dry air] + :raises ValueError: for RH outside 0-1 + """ + self._check_rh(relative_humidity) + pws = self.saturation_vapor_pressure(temperature_c=temperature_c) + return self.humidity_ratio(vapor_pressure=relative_humidity * pws, pressure=pressure) + + def dew_point(self, *, temperature_c: float, relative_humidity: float) -> float: + """Dew-point temperature: the t_d where pws(t_d) equals the actual pw. + + Cool the air at constant water content and condensation starts at + the dew point - the temperature of a cold-water pipe that will start + to "sweat". There is no closed-form inverse of the Hyland-Wexler + equation, so solve pws(t_d) - pw = 0 with ``scipy.optimize.brentq``. + The dew point cannot exceed the dry bulb and is above -100 degC, so + [-100, t] always brackets the root. Below 0 degC this is the frost + point (saturation over ice). + + :param temperature_c: dry-bulb temperature t [degC] + :param relative_humidity: relative humidity phi as a fraction, 0 to 1 [-] + :returns: dew-point temperature t_d [degC] + :raises ValueError: for RH not in (0, 1] + """ + self._check_rh(relative_humidity) + if relative_humidity == 0: + raise ValueError("bone-dry air (RH = 0) has no dew point") + if relative_humidity == 1: + return temperature_c # already saturated + vapor_pressure = relative_humidity * self.saturation_vapor_pressure( + temperature_c=temperature_c + ) + + def residual(t: float) -> float: + return self.saturation_vapor_pressure(temperature_c=t) - vapor_pressure + + return brentq(residual, -100.0, temperature_c, xtol=1e-9) + + def moist_air_enthalpy(self, *, temperature_c: float, humidity_ratio: float) -> float: + """Specific enthalpy of moist air, ASHRAE 2017 Ch. 1 Eq. 32. + + h = 1.006*t + W*(2501 + 1.86*t) kJ/kg dry air + + Dry-air sensible heat (cp = 1.006 kJ/(kg K)) plus the water vapour's + latent heat (2501 kJ/kg at 0 degC) and its sensible heat (cp = 1.86). + Zero is dry air at 0 degC. Multiply the change in h by the dry-air + mass flow to get a coil load in kW. + + :param temperature_c: dry-bulb temperature t [degC] + :param humidity_ratio: humidity ratio W [kg/kg dry air] + :returns: enthalpy h [kJ/kg dry air] + :raises ValueError: for a negative humidity ratio + """ + if humidity_ratio < 0: + raise ValueError("humidity_ratio cannot be negative") + return 1.006 * temperature_c + humidity_ratio * (2501 + 1.86 * temperature_c) + + def specific_volume( + self, *, temperature_c: float, humidity_ratio: float, pressure: float = STANDARD_PRESSURE + ) -> float: + """Moist-air specific volume, v = Ra * T * (1 + 1.607858*W) / p. + + The ideal-gas law for the mixture, per kg of dry air (ASHRAE 2017 + Ch. 1): 1.607858 is 1/0.621945, the ratio of the gas constants of + water vapour and dry air. Fans move volume, coils move mass - this + converts between them (dry-air mass flow = volume flow / v). + + :param temperature_c: dry-bulb temperature t [degC] + :param humidity_ratio: humidity ratio W [kg/kg dry air] + :param pressure: total (barometric) pressure p, default sea level [Pa] + :returns: specific volume v [m^3/kg dry air] + :raises ValueError: for a negative humidity ratio or non-positive pressure + """ + if humidity_ratio < 0 or pressure <= 0: + raise ValueError("humidity_ratio cannot be negative and pressure must be positive") + t_kelvin = temperature_c + 273.15 + return _R_DRY_AIR * t_kelvin * (1 + 1.607858 * humidity_ratio) / pressure + + def wet_bulb( + self, + *, + temperature_c: float, + relative_humidity: float, + pressure: float = STANDARD_PRESSURE, + ) -> float: + """Thermodynamic wet-bulb temperature from dry bulb and RH (iterative). + + The wet bulb t* is the temperature water evaporating into the air + cools to - the limit for an evaporative cooler or cooling tower. An + energy balance on an adiabatic saturator gives the humidity ratio + that produces a given t* (ASHRAE 2017 Ch. 1 Eq. 33, for t* >= 0): + + W = ((2501 - 2.326*t*) * Ws* - 1.006*(t - t*)) + / (2501 + 1.86*t - 4.186*t*) + + and, below freezing (ice surface, Eq. 35): + + W = ((2830 - 0.24*t*) * Ws* - 1.006*(t - t*)) + / (2830 + 1.86*t - 2.1*t*) + + where Ws* is the saturation humidity ratio at t*. We know W and want + t*, so ``brentq`` finds the t* in [-100, t] where the W predicted by + the balance equals the actual W. + + :param temperature_c: dry-bulb temperature t [degC] + :param relative_humidity: relative humidity phi as a fraction, 0 to 1 [-] + :param pressure: total (barometric) pressure p, default sea level [Pa] + :returns: thermodynamic wet-bulb temperature t* [degC] + :raises ValueError: for RH outside 0-1 + """ + actual_w = self.humidity_ratio_from_relative_humidity( + temperature_c=temperature_c, relative_humidity=relative_humidity, pressure=pressure + ) + t = temperature_c + + def residual(t_star: float) -> float: + pws_star = self.saturation_vapor_pressure(temperature_c=t_star) + ws_star = self.humidity_ratio(vapor_pressure=pws_star, pressure=pressure) + if t_star >= 0: + numerator = (2501 - 2.326 * t_star) * ws_star - 1.006 * (t - t_star) + predicted = numerator / (2501 + 1.86 * t - 4.186 * t_star) + else: + numerator = (2830 - 0.24 * t_star) * ws_star - 1.006 * (t - t_star) + predicted = numerator / (2830 + 1.86 * t - 2.1 * t_star) + return predicted - actual_w + + # Saturated air: wet bulb = dry bulb (the balance is already met at t). + if abs(residual(t)) < 1e-12: + return t + return brentq(residual, -100.0, t, xtol=1e-9) + + @staticmethod + def _check_rh(relative_humidity: float) -> None: + if not 0 <= relative_humidity <= 1: + raise ValueError("relative_humidity must be a fraction from 0 to 1 (pass 0.5, not 50)") diff --git a/fpc/report.py b/fpc/report.py new file mode 100644 index 0000000..b8d5955 --- /dev/null +++ b/fpc/report.py @@ -0,0 +1,157 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""report.py - file a calculation the way a checked hand calc is filed. + +An engineering calculation that goes into a design file needs more than its +answer: a reviewer must see *what* was calculated, *which* equation and +assumptions were used, every input *with its unit*, the result, and where the +method comes from. This module writes all of that as a Markdown "calc sheet" +from any calculation in the registry, because the registry already knows the +formula text, the inputs, and their units from the docstrings. + +Markdown is plain text, so the sheet can be committed next to the code, +diffed, and reviewed in a pull request. Turn it into a PDF or Word file with +`pandoc `_ when one is needed:: + + fpc report Fluids.reynolds_number density=998 velocity=2 length=0.05 \\ + viscosity=0.001 --out reynolds.md + pandoc reynolds.md -o reynolds.pdf + +From Python:: + + from fpc.report import calc_report + + text = calc_report("Thermo.conduction_heat_rate", + {"conductivity": 0.72, "area": 12, + "delta_temperature": 25, "thickness": 0.2}, + title="Heat loss through the north wall") + +Techniques shown: building text with f-strings and ``str.join``, Markdown +tables, ``datetime.date`` and ``importlib.metadata`` for the record of *when* +and *with which version* a result was produced. +""" + +import datetime +from collections.abc import Mapping +from typing import Any + +import fpc +from fpc import registry +from fpc.uncertainty import MonteCarloResult + + +def _number(value: Any) -> str: + """Six significant figures for numbers; anything else as written.""" + if isinstance(value, bool) or not isinstance(value, int | float): + return f"`{value}`" if isinstance(value, str) else str(value) + return f"{value:.6g}" + + +def _cell(text: str) -> str: + """Make text safe inside a Markdown table cell (no pipes, one line).""" + return " ".join(text.replace("|", "\\|").split()) + + +def _result_section(result: Any, returns: str) -> list[str]: + """Lines describing the result: one value, or a table for several.""" + lines = [f"Returns: {returns}", ""] + if isinstance(result, dict): + lines += ["| Quantity | Value |", "|---|---:|"] + lines += [f"| {name} | {_number(value)} |" for name, value in result.items()] + elif isinstance(result, list) and all(not isinstance(v, list | dict) for v in result): + lines += ["| # | Value |", "|---|---:|"] + lines += [f"| {i} | {_number(value)} |" for i, value in enumerate(result)] + else: + lines.append(f"**Result: {_number(result)}**") + return lines + + +def calc_report( + key: str, + arguments: Mapping[str, Any], + *, + title: str | None = None, + checked_by: str = "", + date: datetime.date | None = None, + uncertainty: MonteCarloResult | None = None, +) -> str: + """Run a calculation and write it up as a Markdown calc sheet. + + :param key: registry key, e.g. ``"Fluids.reynolds_number"`` + :param arguments: the inputs, each in the unit its docstring gives [input units] + :param title: heading for the sheet; defaults to the calculation's summary + :param checked_by: name for the "Checked by" line; blank leaves a line to sign + :param date: date printed on the sheet; defaults to today + :param uncertainty: optional result of :func:`fpc.uncertainty.monte_carlo` + for the same calculation, added as an "Uncertainty" section + :returns: the sheet as Markdown text + :raises KeyError: for an unknown key + :raises ValueError: for missing or unknown inputs + """ + calc = registry.get(key) + result = registry.calculate(key, arguments) # validates the inputs first + date = date or datetime.date.today() + by_name = {p.name: p for p in calc.parameters} + + lines = [ + f"# {title or calc.summary}", + "", + "| | |", + "|---|---|", + f"| Calculation | `{calc.key}` |", + f"| Method source | `{calc.cls.__module__}.{calc.domain}.{calc.name}` " + f"(first-principles-code {fpc.__version__}) |", + f"| Date | {date.isoformat()} |", + f"| Checked by | {checked_by or '_' * 24} |", + "", + "## Method", + "", + # The docstring's description holds the equation and its assumptions. + calc.description, + "", + "## Inputs", + "", + "| Input | Value | Unit | Description |", + "|---|---:|---|---|", + ] + for name, value in arguments.items(): + p = by_name[name] + lines.append(f"| `{name}` | {_number(value)} | {p.unit or ''} | {_cell(p.description)} |") + # Defaults the caller did not override are inputs too; a reviewer must see them. + for p in calc.parameters: + if p.name not in arguments and not p.required: + value = f"{_number(p.default)} (default)" + lines.append(f"| `{p.name}` | {value} | {p.unit or ''} | {_cell(p.description)} |") + + lines += ["", "## Result", ""] + _result_section(result, calc.returns) + + if uncertainty is not None: + low, high = uncertainty.interval(95) + lines += [ + "", + "## Uncertainty", + "", + f"Monte Carlo, {len(uncertainty.samples)} samples.", + "", + "| Statistic | Value |", + "|---|---:|", + f"| Mean | {_number(uncertainty.mean)} |", + f"| Standard deviation | {_number(uncertainty.std)} |", + f"| 95 % interval | {_number(low)} to {_number(high)} |", + "", + "Share of the variation from each uncertain input:", + "", + ] + lines += [f"- `{name}`: {share:.0%}" for name, share in uncertainty.sensitivity.items()] + + lines += [ + "", + "## Review", + "", + "- [ ] Inputs and units match the design basis", + "- [ ] Method and assumptions suit this case", + "- [ ] Result is plausible (order of magnitude, sign)", + "", + ] + return "\n".join(lines) diff --git a/fpc/uncertainty.py b/fpc/uncertainty.py new file mode 100644 index 0000000..1fb6a95 --- /dev/null +++ b/fpc/uncertainty.py @@ -0,0 +1,305 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""uncertainty.py - how sure is the answer? Monte Carlo on any calculation. + +Every input to a real calculation is uncertain: a pipe's roughness is "about +0.045 mm", a measured flow is "12 L/s +/- 3 %", a modulus varies from batch to +batch. A single answer hides that. **Monte Carlo** simulation shows it by brute +force: + + 1. describe each uncertain input by a probability distribution; + 2. draw thousands of random input sets; + 3. run the calculation on each one; + 4. look at the spread of the results (mean, standard deviation, + percentiles) instead of one number. + +It needs no calculus and works on any calculation, however non-linear, which +is why engineers reach for it before the textbook error-propagation formulas. + +Example:: + + from fpc.uncertainty import monte_carlo, Normal, Uniform + + result = monte_carlo( + "Fluids.pipe_flow", + { + "flow": Normal(mean=0.012, std=0.0004), # 12 L/s, +/- 3 % (1 sigma) + "diameter": 0.1023, + "length": 120, + "roughness": Uniform(low=0.02e-3, high=0.09e-3), + "density": 998, + "viscosity": 1.0e-3, + }, + output="pressure_drop", + seed=1, + ) + result.mean, result.std, result.interval(95) # Pa + result.sensitivity # which input matters most + +Techniques shown: NumPy's random ``Generator`` (``np.random.default_rng``) +and why a *seed* makes a random run repeatable; vectorized evaluation with a +fallback to a plain loop; ``np.percentile``; and a correlation-based +sensitivity measure. +""" + +from collections.abc import Callable, Mapping +from dataclasses import dataclass, field +from typing import Any, Protocol + +import numpy as np + +from fpc import registry +from fpc.hints import FloatArray + +# --- Input distributions -------------------------------------------------- +# Each one is a tiny frozen dataclass with a ``sample`` method. Anything with +# that method works as an input (that is what the ``Distribution`` Protocol +# below says), so you can add your own, e.g. a log-normal. + + +class Distribution(Protocol): + """Anything that can draw ``n`` random values with a NumPy ``Generator``.""" + + def sample(self, rng: np.random.Generator, n: int) -> FloatArray: ... + + +@dataclass(frozen=True) +class Normal: + """Bell curve: most values near ``mean``; about 95 % within 2 ``std``. + + Use it for measurements and manufacturing variation. A datasheet's + "+/- x" is often 2 or 3 standard deviations, so check before using it as ``std``. + + :param mean: centre value [input unit] + :param std: standard deviation, one sigma [input unit] + """ + + mean: float + std: float + + def __post_init__(self) -> None: + if self.std < 0: + raise ValueError(f"std must be >= 0, got {self.std}") + + def sample(self, rng: np.random.Generator, n: int) -> FloatArray: + return rng.normal(self.mean, self.std, n) + + +@dataclass(frozen=True) +class Uniform: + """Every value between ``low`` and ``high`` equally likely. + + Use it when you only know the bounds (a tolerance band, a "somewhere + between" estimate). + + :param low: smallest value [input unit] + :param high: largest value [input unit] + """ + + low: float + high: float + + def __post_init__(self) -> None: + if self.high < self.low: + raise ValueError(f"high ({self.high}) must be >= low ({self.low})") + + def sample(self, rng: np.random.Generator, n: int) -> FloatArray: + return rng.uniform(self.low, self.high, n) + + +@dataclass(frozen=True) +class Triangular: + """Bounds plus a most-likely value: a good fit for an expert's estimate. + + :param low: smallest value [input unit] + :param mode: most likely value [input unit] + :param high: largest value [input unit] + """ + + low: float + mode: float + high: float + + def __post_init__(self) -> None: + if not self.low <= self.mode <= self.high: + raise ValueError(f"need low <= mode <= high, got {self.low}, {self.mode}, {self.high}") + + def sample(self, rng: np.random.Generator, n: int) -> FloatArray: + return rng.triangular(self.low, self.mode, self.high, n) + + +def parse_distribution(text: str) -> float | Distribution: + """Read an input from text, as typed on the command line. + + ``"998"`` -> 998.0, ``"normal:2,0.1"`` -> ``Normal(2, 0.1)``, + ``"uniform:0.9,1.1"`` -> ``Uniform``, ``"triangular:1,2,4"`` -> ``Triangular``. + + :param text: a number, or ``kind:numbers`` + :returns: a float or a distribution + """ + kind, sep, numbers = text.partition(":") + if not sep: + return float(text) + values = [float(v) for v in numbers.split(",")] + kinds: dict[str, type] = {"normal": Normal, "uniform": Uniform, "triangular": Triangular} + if kind.lower() not in kinds: + raise ValueError(f"unknown distribution {kind!r}; use one of {sorted(kinds)}") + return kinds[kind.lower()](*values) + + +# --- Results ---------------------------------------------------------------- + + +@dataclass(frozen=True) +class MonteCarloResult: + """The spread of a calculation's result. + + :param samples: every simulated result [output unit] + :param inputs: the sampled value of each uncertain input, by name [input unit] + """ + + samples: FloatArray = field(repr=False) + inputs: dict[str, FloatArray] = field(repr=False) + + @property + def mean(self) -> float: + """Average result [output unit].""" + return float(np.mean(self.samples)) + + @property + def std(self) -> float: + """Standard deviation of the result [output unit].""" + return float(np.std(self.samples, ddof=1)) + + def percentile(self, q: float) -> float: + """Value below which ``q`` percent of the results fall [output unit]. + + :param q: percentage, 0 to 100 [-] + """ + return float(np.percentile(self.samples, q)) + + def interval(self, coverage: float = 95) -> tuple[float, float]: + """Range that holds the central ``coverage`` percent of the results. + + ``interval(95)`` is (2.5th percentile, 97.5th percentile). Unlike + ``mean +/- 2*std`` it stays right when the result is lopsided. + + :param coverage: percentage of results inside the range [-] + :returns: (low, high) [output unit] + """ + tail = (100 - coverage) / 2 + return self.percentile(tail), self.percentile(100 - tail) + + @property + def sensitivity(self) -> dict[str, float]: + """Share of the result's variation that comes from each uncertain input. + + Computed as the squared correlation between each input's samples and + the results, scaled to add up to 1. It is a first look, not a full + variance decomposition: it assumes the inputs are independent and the + effect is roughly monotonic (more input, more or less output), which + holds for most engineering formulas. Biggest first. + + :returns: ``{input name: share}`` [-] + """ + if not self.inputs or np.ptp(self.samples) == 0: + return {} + r2 = { + name: float(np.corrcoef(values, self.samples)[0, 1] ** 2) + for name, values in self.inputs.items() + } + total = sum(r2.values()) or 1.0 + return dict(sorted(((k, v / total) for k, v in r2.items()), key=lambda kv: -kv[1])) + + def summary(self) -> dict[str, Any]: + """Plain-number summary, ready for JSON, a table, or a report. + + :returns: mean, std, p5, p50, p95 [output unit], samples [-] and sensitivity [-] + """ + return { + "mean": self.mean, + "std": self.std, + "p5": self.percentile(5), + "p50": self.percentile(50), + "p95": self.percentile(95), + "samples": len(self.samples), + "sensitivity": self.sensitivity, + } + + +# --- The simulation ----------------------------------------------------------- + + +def monte_carlo( + calculation: str | Callable[..., Any], + inputs: Mapping[str, Any], + *, + samples: int = 10_000, + seed: int | None = None, + output: str | int | None = None, +) -> MonteCarloResult: + """Run a calculation many times with random inputs. + + :param calculation: a registry key such as ``"Fluids.pipe_flow"``, or any + function that takes keyword arguments + :param inputs: every argument the calculation needs; uncertain ones as a + distribution (:class:`Normal`, :class:`Uniform`, :class:`Triangular`), + fixed ones as plain values [input units] + :param samples: how many random runs; error in the mean shrinks like + 1/sqrt(samples), so 10 000 is plenty for engineering work [-] + :param seed: fix the random numbers so the run can be repeated exactly; + leave as ``None`` for fresh random numbers each time [-] + :param output: which part of the result to study when the calculation + returns several values: a dict key (``"pressure_drop"``) or a tuple + index (``1``) [-] + :returns: a :class:`MonteCarloResult` + :raises ValueError: if ``samples < 2`` or the result is not a number + """ + if samples < 2: + raise ValueError(f"samples must be at least 2, got {samples}") + if isinstance(calculation, str): + calc = registry.get(calculation) + function = getattr(calc.cls(), calc.name) + else: + function = calculation + + # A Generator with a seed gives the same "random" numbers every run, so + # a result in a report can be reproduced by whoever checks it. + rng = np.random.default_rng(seed) + drawn = { + name: value.sample(rng, samples) + for name, value in inputs.items() + if hasattr(value, "sample") + } + fixed = {name: value for name, value in inputs.items() if name not in drawn} + + def pick(result: Any) -> Any: + if output is None: + return result + return result[output] # works for dicts (key) and tuples (index) + + # Fast path: hand the whole arrays over in one call. Formulas written with + # plain operators (+, *, **) or NumPy functions work on arrays unchanged. + # Formulas using ``math.sqrt``, ``if x > ...`` or a root finder do not, and + # raise TypeError/ValueError, so we fall back to one call per sample. + values: FloatArray | None = None + try: + vectorized = np.asarray(pick(function(**fixed, **drawn)), dtype=float) + if vectorized.shape == (samples,): + values = vectorized + except (TypeError, ValueError, KeyError, IndexError): + values = None + if values is None: + values = np.empty(samples) + for i in range(samples): + one = {name: float(array[i]) for name, array in drawn.items()} + result = pick(function(**fixed, **one)) + if isinstance(result, dict | tuple | list): + options = list(result) if isinstance(result, dict) else list(range(len(result))) + raise ValueError( + f"the calculation returns several values; choose one with output=..., " + f"one of {options}" + ) + values[i] = float(result) + return MonteCarloResult(samples=values, inputs=drawn) diff --git a/gui.py b/gui.py index 71066f4..3b5d4d9 100644 --- a/gui.py +++ b/gui.py @@ -43,12 +43,15 @@ Dicom, Dynamics, Electrical, + Fatigue, Fluids, Gear, + MachineElements, Material, Mechatronics, Modal, Properties, + Psychrometrics, Radiation, Radiography, Statics, @@ -80,6 +83,9 @@ def __init__(self): "fluids": Fluids(), "material": Material(), "gear": Gear(), + "machine": MachineElements(), + "fatigue": Fatigue(), + "psychro": Psychrometrics(), "electrical": Electrical(), "mechatronics": Mechatronics(), "controls": Controls(), diff --git a/llms.txt b/llms.txt index 12143bc..b13c520 100644 --- a/llms.txt +++ b/llms.txt @@ -54,6 +54,21 @@ instance of the class named in the heading, e.g. `fpc.CT().apply_window(...)`. - `rc_time_constant(resistance [ohm], capacitance [F])`: Time constant of an RC circuit: tau = R * C. - `series_resistance(resistances [ohm])`: Total resistance of resistors in series (they simply add). +## Fatigue + +- `asme_elliptic_safety_factor(alternating_stress [Pa], mean_stress [Pa], endurance_limit [Pa], yield_strength [Pa])`: Fatigue safety factor, ASME-elliptic: (n*sa/Se)^2 + (n*sm/Sy)^2 = 1. +- `cycles_to_failure(alternating_stress [Pa], ultimate_strength [Pa], endurance_limit [Pa], fatigue_strength_fraction [-]=…)`: Cycles to failure under fully reversed stress: N = (sigma_a / a)^(1/b). +- `endurance_limit_steel(ultimate_strength [Pa])`: Rotating-beam endurance limit estimate for steels, Shigley Eq. 6-8. +- `gerber_safety_factor(alternating_stress [Pa], mean_stress [Pa], endurance_limit [Pa], ultimate_strength [Pa])`: Fatigue safety factor, Gerber parabola: n*sa/Se + (n*sm/Sut)^2 = 1. +- `goodman_safety_factor(alternating_stress [Pa], mean_stress [Pa], endurance_limit [Pa], ultimate_strength [Pa])`: Fatigue safety factor, modified Goodman line: 1/n = sa/Se + sm/Sut. +- `load_factor(loading)`: Marin load factor kc, Shigley Eq. 6-26: 1 bending, 0.85 axial, 0.59 torsion. +- `marin_endurance_limit(specimen_endurance_limit [Pa], surface_factor [-]=…, size_factor [-]=…, load_factor [-]=…, temperature_factor [-]=…, reliability_factor [-]=…, miscellaneous_factor [-]=…)`: Endurance limit of the real part: Se = ka*kb*kc*kd*ke*kf * Se', Shigley Eq. 6-18. +- `reliability_factor(reliability [-])`: Marin reliability factor ke = 1 - 0.08 * za, Shigley Table 6-5. +- `size_factor(diameter [m], loading=…)`: Marin size factor kb for a round bar, Shigley Eq. 6-20. +- `sn_curve_coefficients(ultimate_strength [Pa], endurance_limit [Pa], fatigue_strength_fraction [-]=…)`: Basquin S-N line Sf = a * N^b through (10^3, f*Sut) and (10^6, Se). +- `soderberg_safety_factor(alternating_stress [Pa], mean_stress [Pa], endurance_limit [Pa], yield_strength [Pa])`: Fatigue safety factor, Soderberg line: 1/n = sa/Se + sm/Sy. +- `surface_factor(ultimate_strength [Pa], finish)`: Marin surface factor ka = a * Sut^b, Shigley Eq. 6-19 / Table 6-2. + ## Fluids - `bernoulli_pressure(density [kg/m^3], velocity_1 [m/s], height_1 [m], pressure_1 [Pa], velocity_2 [m/s], height_2 [m], gravity [m/s^2]=…)`: Downstream static pressure from Bernoulli's equation. @@ -82,14 +97,36 @@ instance of the class named in the heading, e.g. `fpc.CT().apply_window(...)`. - `t1_recovery(time_ms [ms], t1_ms [ms], equilibrium_magnetization [-]=…)`: Longitudinal recovery after a 90 deg pulse: Mz = M0 * (1 - exp(-t/T1)). - `t2_decay(time_ms [ms], t2_ms [ms], initial_magnetization [-]=…)`: Transverse decay: Mxy = M0 * exp(-t/T2). +## MachineElements + +- `bearing_l10_life(dynamic_load_rating [N], equivalent_load [N], bearing_type=…)`: Bearing rating life L10 = (C / P)^a, in millions of revolutions. +- `bearing_l10_life_hours(dynamic_load_rating [N], equivalent_load [N], speed_rpm [rev/min], bearing_type=…)`: Bearing rating life in operating hours: L10h = L10 * 1e6 / (60 * n). +- `bearing_required_load_rating(equivalent_load [N], life_hours [h], speed_rpm [rev/min], bearing_type=…)`: Catalogue rating C needed to reach a target L10 life: C = P * L10^(1/a). +- `bolt_preload(proof_strength [Pa], tensile_stress_area [m^2], connection=…)`: Recommended bolt preload as a fraction of the proof load. +- `bolt_stiffness(modulus [Pa], nominal_diameter [m], tensile_stress_area [m^2], unthreaded_length [m], threaded_length [m])`: Axial stiffness of a bolt within the grip: kb = Ad*At*E / (Ad*lt + At*ld). +- `bolt_tightening_torque(preload [N], nominal_diameter [m], torque_coefficient [-]=…)`: Wrench torque needed to reach a bolt preload: T = K * Fi * d. +- `bolted_joint_loads(preload [N], external_load [N], stiffness_constant [-])`: Bolt and member forces in a preloaded joint under an external tensile load. +- `fillet_weld_shear_stress(force [N], leg_size [m], weld_length [m])`: Average shear stress on a fillet weld throat: tau = F / (0.707 * h * L). +- `joint_stiffness_constant(bolt_stiffness [N/m], member_stiffness [N/m])`: Joint constant C = kb / (kb + km): the bolt's share of an external load. +- `member_stiffness(modulus [Pa], nominal_diameter [m], grip_length [m])`: Stiffness of the clamped members, using 30-degree pressure cones. +- `shaft_diameter_de_goodman(alternating_moment [N*m], mean_moment [N*m], alternating_torque [N*m], mean_torque [N*m], endurance_limit [Pa], ultimate_strength [Pa], safety_factor [-], fatigue_factor_bending [-]=…, fatigue_factor_torsion [-]=…)`: Solid shaft diameter for fatigue (DE-Goodman criterion), Shigley Eq. 7-8. +- `shaft_diameter_static(bending_moment [N*m], torque [N*m], yield_strength [Pa], safety_factor [-])`: Solid shaft diameter for steady bending + torsion (von Mises yield). +- `spring_rate(wire_diameter [m], mean_coil_diameter [m], active_coils [-], shear_modulus [Pa])`: Rate of a helical compression spring: k = d^4 * G / (8 * D^3 * Na). +- `spring_shear_stress(force [N], wire_diameter [m], mean_coil_diameter [m], correction=…)`: Maximum wire shear stress in a helical spring: tau = K * 8*F*D / (pi*d^3). + ## Material - `axial_deformation(force [N], length [m], area [m^2], modulus [Pa])`: Axial stretch/compression of a bar: dL = F*L / (A*E). - `bending_stress(moment [N*m], distance [m], moment_of_inertia [m^4])`: Bending (flexural) stress in a beam: sigma = M*c / I. +- `critical_buckling_load(modulus [Pa], moment_of_inertia [m^4], area [m^2], length [m], yield_strength [Pa], end_factor [-]=…)`: Critical column load, choosing Euler or Johnson from the slenderness ratio. - `euler_buckling_load(modulus [Pa], moment_of_inertia [m^4], length [m], end_factor [-]=…)`: Critical buckling load of a slender column (Euler's formula). +- `johnson_buckling_load(modulus [Pa], moment_of_inertia [m^4], area [m^2], length [m], yield_strength [Pa], end_factor [-]=…)`: Critical load of an intermediate column (J. B. Johnson parabola). +- `radius_of_gyration(moment_of_inertia [m^4], area [m^2])`: Radius of gyration r = sqrt(I / A). +- `slenderness_ratio(length [m], radius_of_gyration [m], end_factor [-]=…)`: Slenderness ratio of a column: KL / r. - `strain(change_in_length [m], original_length [m])`: Engineering strain: epsilon = dL / L0 (dimensionless). - `stress(force [N], area [m^2])`: Engineering stress: sigma = F / A. - `thermal_expansion(coefficient [1/K], original_length [m], delta_temperature [K])`: Length change from temperature: dL = alpha * L0 * dT. +- `transition_slenderness_ratio(modulus [Pa], yield_strength [Pa])`: Slenderness ratio where Euler hands over to Johnson: sqrt(2*pi^2*E / Sy). - `youngs_modulus(stress [Pa], strain [-])`: Young's modulus (stiffness) from Hooke's law: E = sigma / strain. ## Mechatronics @@ -120,6 +157,19 @@ instance of the class named in the heading, e.g. `fpc.CT().apply_window(...)`. - `water_liquid(temperature_c [degC], property, method=…)`: Liquid water property at 1 atm and a given temperature. - `water_saturation(temperature_c [degC], property, method=…)`: Saturated-water property at a temperature (a steam-table lookup). +## Psychrometrics + +- `dew_point(temperature_c [degC], relative_humidity [-])`: Dew-point temperature: the t_d where pws(t_d) equals the actual pw. +- `humidity_ratio(vapor_pressure [Pa], pressure [Pa]=…)`: Humidity ratio W = 0.621945 * pw / (p - pw), ASHRAE 2017 Ch. 1 Eq. 20. +- `humidity_ratio_from_relative_humidity(temperature_c [degC], relative_humidity [-], pressure [Pa]=…)`: Humidity ratio from dry bulb and relative humidity: W(phi * pws(t), p). +- `moist_air_enthalpy(temperature_c [degC], humidity_ratio [kg/kg dry air])`: Specific enthalpy of moist air, ASHRAE 2017 Ch. 1 Eq. 32. +- `relative_humidity(temperature_c [degC], vapor_pressure [Pa])`: Relative humidity phi = pw / pws(t). +- `saturation_vapor_pressure(temperature_c [degC], phase=…)`: Saturation pressure of water vapour (Hyland-Wexler), ASHRAE 2017 Ch. 1 Eqs. 5-6. +- `specific_volume(temperature_c [degC], humidity_ratio [kg/kg dry air], pressure [Pa]=…)`: Moist-air specific volume, v = Ra * T * (1 + 1.607858*W) / p. +- `standard_pressure(altitude [m])`: Standard-atmosphere pressure at an altitude, ASHRAE 2017 Ch. 1 Eq. 3. +- `vapor_pressure(humidity_ratio [kg/kg dry air], pressure [Pa]=…)`: Vapour partial pressure from humidity ratio: pw = p * W / (0.621945 + W). +- `wet_bulb(temperature_c [degC], relative_humidity [-], pressure [Pa]=…)`: Thermodynamic wet-bulb temperature from dry bulb and RH (iterative). + ## Radiation - `decay_constant(half_life [any time unit])`: Decay constant lambda = ln(2) / T_half. diff --git a/mkdocs.yml b/mkdocs.yml index 9594f1a..32067a5 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -53,6 +53,7 @@ nav: - Guides: - Units - floats or Pint?: units.md - From calculation to tool: building-tools.md + - Trusting a result - uncertainty and calc sheets: trusting-results.md - Using fpc with AI assistants: ai.md - Releasing to PyPI: releasing.md - Supported Python versions: python-versions.md @@ -64,9 +65,12 @@ nav: - Material: api/material.md - Beam (Pint): api/beam.md - Gear: api/gear.md + - Machine elements: api/machine_elements.md + - Fatigue: api/fatigue.md - Thermal and fluids: - Thermo: api/thermo.md - Fluids: api/fluids.md + - Psychrometrics (moist air): api/psychrometrics.md - Electrical and controls: - Electrical: api/electrical.md - Mechatronics: api/mechatronics.md @@ -79,6 +83,8 @@ nav: - fpc command line: api/cli.md - Calculation registry: api/registry.md - MCP server: api/mcp_server.md + - Uncertainty (Monte Carlo): api/uncertainty.md + - Calc reports: api/report.md - Radiology: - Radiation: api/radiation.md - Radiography: api/radiography.md diff --git a/pyproject.toml b/pyproject.toml index 0c8b6ee..aa24d11 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -175,3 +175,7 @@ python_version = "3.11" # check against the oldest supported Python packages = ["fpc"] ignore_missing_imports = true warn_unused_ignores = true +# Every function in fpc/ must be fully annotated: the registry turns the +# hints into JSON Schema, and a missing hint is a missing check. +disallow_untyped_defs = true +disallow_incomplete_defs = true diff --git a/scripts/try_local_model.py b/scripts/try_local_model.py new file mode 100644 index 0000000..f574969 --- /dev/null +++ b/scripts/try_local_model.py @@ -0,0 +1,267 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""try_local_model.py - ask a local Ollama model engineering questions through fpc-mcp. + +The MCP server's tool descriptions and instructions are written *for a model*, +and the only way to know whether they work is to watch a real one use them. +This script plays the part of an AI chat app (LM Studio, Open WebUI, ...): + + 1. start the MCP server in-process and read its tool list, + 2. hand those tools to a model running in Ollama, + 3. loop: whenever the model asks for a tool, run it through MCP and send + back the result, until the model writes a final answer, + 4. check the answer against the number fpc itself computes. + +Usage (Ollama must be running; ``ollama pull qwen3:14b`` first):: + + uv run --extra mcp scripts/try_local_model.py --model qwen3:14b + uv run --extra mcp scripts/try_local_model.py --model qwen2.5:7b --domains fluids,thermo + uv run --extra mcp scripts/try_local_model.py --model qwen3:14b --only reynolds -v + +It prints one line per question (PASS/FAIL, tool calls made, seconds) and, +with ``-v``, the whole conversation. A FAIL is a lead, not a verdict: read the +transcript to see whether the model picked the wrong tool, converted a unit +wrongly, or never called a tool at all, then improve the tool descriptions or +``INSTRUCTIONS`` in ``fpc/mcp_server.py``. Findings so far are in docs/ai.md. + +Techniques shown: ``asyncio`` (the MCP client is async), ``urllib`` for a JSON +HTTP API with no extra dependency, and a tool-calling loop, the core of every +"AI agent". +""" + +import argparse +import asyncio +import json +import re +import sys +import time +import urllib.request +from dataclasses import dataclass +from typing import Any + +from mcp import Client + +from fpc import registry +from fpc.mcp_server import INSTRUCTIONS, build_server + +OLLAMA = "http://localhost:11434/api/chat" +MAX_TURNS = 10 # tool calls before we give up on a question + + +@dataclass(frozen=True) +class Question: + """One test question and how to get its true answer from fpc. + + :param name: short id for ``--only`` + :param text: what the user asks; units deliberately mixed (mm, kN, L/s, + mPa*s) because converting them is where models slip + :param key: the calculation that answers it + :param arguments: that calculation's inputs in SI + :param pick: turns the calculation's result into the expected number + :param scale: multiplies the expected number into the unit the question asks for + """ + + name: str + text: str + key: str + arguments: dict[str, Any] + pick: str = "" # dict key or tuple index ("1") into the result, if any + scale: float = 1.0 + + def expected(self) -> float: + result = registry.calculate(self.key, self.arguments) + if self.pick: + result = result[int(self.pick)] if isinstance(result, list) else result[self.pick] + return float(result) * self.scale + + +QUESTIONS = [ + Question( + "reynolds", + "Water (density 998 kg/m3, dynamic viscosity 1.0 mPa*s) flows at 2 m/s " + "in a pipe with a 50 mm inside diameter. What is the Reynolds number?", + "Fluids.reynolds_number", + {"density": 998, "velocity": 2, "length": 0.05, "viscosity": 1e-3}, + ), + Question( + "frequency", + "A 2.5 kg mass sits on a spring with a stiffness of 4 kN/m. " + "What is the undamped natural frequency in Hz?", + "Modal.natural_frequency", + {"stiffness": 4000, "mass": 2.5}, + pick="1", + ), + Question( + "wall", + "A brick wall is 200 mm thick and 12 m2 in area, with thermal " + "conductivity 0.72 W/(m K). It is 20 C inside and -5 C outside. " + "How many watts of heat flow through it?", + "Thermo.conduction_heat_rate", + {"conductivity": 0.72, "area": 12, "delta_temperature": 25, "thickness": 0.2}, + ), + Question( + "rc", + "What is the time constant, in seconds, of a 47 kilohm resistor " + "in series with a 10 uF capacitor?", + "Electrical.rc_time_constant", + {"resistance": 47e3, "capacitance": 10e-6}, + ), + Question( + "hvl", + "A material has a linear attenuation coefficient of 0.5 per cm. " + "What is its half-value layer in millimetres?", + "Radiation.half_value_layer", + {"attenuation_coefficient": 0.5}, + scale=10, # cm -> mm + ), + Question( + "pipe", + "12 L/s of water (density 998 kg/m3, viscosity 1.0 mPa*s) flows through " + "120 m of commercial steel pipe with a 100 mm inside diameter " + "(roughness 0.045 mm). What is the pressure drop in kPa?", + "Fluids.pipe_flow", + { + "flow": 0.012, + "diameter": 0.1, + "length": 120, + "roughness": 0.045e-3, + "density": 998, + "viscosity": 1e-3, + }, + pick="pressure_drop", + scale=1e-3, # Pa -> kPa + ), +] + + +def ollama_chat( + model: str, + messages: list[dict[str, Any]], + tools: list[dict[str, Any]], + think: bool | None = None, +) -> dict[str, Any]: + """One request to Ollama's chat API; returns the assistant message. + + ``think`` switches a reasoning model's thinking on or off; ``None`` leaves + the model's default (and works with models that cannot think at all). + """ + payload: dict[str, Any] = { + "model": model, + "messages": messages, + "tools": tools, + "stream": False, + "options": {"temperature": 0}, # repeatable runs + } + if think is not None: + payload["think"] = think + body = json.dumps(payload).encode() + request = urllib.request.Request(OLLAMA, body, {"Content-Type": "application/json"}) + with urllib.request.urlopen(request, timeout=600) as response: + return json.load(response)["message"] + + +def numbers_in(text: str) -> list[float]: + """Every number in a piece of text; "99,800" and "9.98e4" both count.""" + found = re.findall(r"-?\d[\d,]*\.?\d*(?:[eE][-+]?\d+)?", text) + return [float(n.replace(",", "")) for n in found if n.replace(",", "").strip("-.")] + + +async def ask( + client: Client, + model: str, + tools: list[dict[str, Any]], + question: Question, + verbose: bool, + think: bool | None = None, +) -> tuple[bool, list[str], str]: + """Run the tool-calling loop for one question. + + :returns: (passed, tool calls made, final answer text) + """ + messages: list[dict[str, Any]] = [ + {"role": "system", "content": INSTRUCTIONS}, + {"role": "user", "content": question.text}, + ] + calls: list[str] = [] + answer = "" + for _ in range(MAX_TURNS): + message = await asyncio.to_thread(ollama_chat, model, messages, tools, think) + messages.append(message) + if not message.get("tool_calls"): + answer = message.get("content", "") + if not answer.strip() and message.get("thinking"): + # Seen with qwen3 in Ollama: after a tool call the final answer + # lands in "thinking" and "content" is empty, so a chat app that + # hides thinking shows a blank reply. Count it as a failure (the + # user would see nothing) but say why. --think off avoids it. + answer = "" + if verbose: + print(" (answer was only in the thinking field; try --think off)") + break + for call in message["tool_calls"]: + name, arguments = call["function"]["name"], call["function"]["arguments"] + calls.append(name) + result = await client.call_tool(name, arguments) + text = result.content[0].text if result.content else "" + if verbose: + print(f" -> {name}({json.dumps(arguments)})\n <- {text[:300]}") + messages.append({"role": "tool", "tool_name": name, "content": text}) + expected = question.expected() + passed = any(abs(n - expected) <= 0.02 * abs(expected) for n in numbers_in(answer)) + if verbose: + print(f" answer: {answer.strip()[:600]}\n expected ~{expected:.4g}") + return passed, calls, answer + + +async def main_async(args: argparse.Namespace) -> int: + domains = [d for d in args.domains.split(",") if d] + think = {"on": True, "off": False}.get(args.think) + questions = [q for q in QUESTIONS if not args.only or q.name in args.only.split(",")] + async with Client(build_server(domains)) as client: + # Translate MCP tool definitions into the "function" format Ollama expects. + tools = [ + { + "type": "function", + "function": { + "name": t.name, + "description": t.description, + "parameters": t.input_schema, + }, + } + for t in (await client.list_tools()).tools + ] + print(f"{args.model}: {len(tools)} tools, {len(questions)} questions") + passed = 0 + for question in questions: + start = time.perf_counter() + if args.verbose: + print(f"\n[{question.name}] {question.text}") + ok, calls, _ = await ask(client, args.model, tools, question, args.verbose, think) + passed += ok + seconds = time.perf_counter() - start + verdict = "PASS" if ok else "FAIL" + trail = " > ".join(calls) or "(no tools)" + print(f" {verdict} {question.name:<10} {seconds:5.0f}s {trail}") + print(f"{passed}/{len(questions)} passed") + return 0 if passed == len(questions) else 1 + + +def main(argv: list[str] | None = None) -> int: + parser = argparse.ArgumentParser(description=__doc__.split("\n\n")[0]) + parser.add_argument("--model", default="qwen3:14b", help="an Ollama model with tool calling") + parser.add_argument("--domains", default="", help="passed to the server, e.g. fluids,thermo") + parser.add_argument("--only", default="", help="comma-separated question names") + parser.add_argument( + "--think", choices=["on", "off"], help="reasoning models: turn thinking on or off" + ) + parser.add_argument("-v", "--verbose", action="store_true", help="print each conversation") + args = parser.parse_args(argv) + try: + return asyncio.run(main_async(args)) + except OSError as error: # urllib's URLError is an OSError + sys.exit(f"Could not reach Ollama at {OLLAMA} ({error}). Is `ollama serve` running?") + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/tests/test_calculator_app.py b/tests/test_calculator_app.py new file mode 100644 index 0000000..4728280 --- /dev/null +++ b/tests/test_calculator_app.py @@ -0,0 +1,80 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""Tests for the registry-driven Streamlit app (apps/calculator.py). + +Streamlit's ``AppTest`` runs the script without a browser and lets a test set +widgets and read what was drawn. Streamlit is an optional dependency group. +""" + +from pathlib import Path + +import pytest + +pytest.importorskip("streamlit") + +from streamlit.testing.v1 import AppTest # noqa: E402 + +APP = str(Path(__file__).resolve().parent.parent / "apps" / "calculator.py") + + +def open_app(key: str) -> AppTest: + """Start the app and choose one calculation.""" + domain, name = key.split(".") + app = AppTest.from_file(APP, default_timeout=30).run() + app.sidebar.selectbox[0].set_value(domain).run() + app.sidebar.selectbox[1].set_value(key).run() + return app + + +def test_every_calculation_form_draws_without_error(): + app = AppTest.from_file(APP, default_timeout=30).run() + domains = app.sidebar.selectbox[0].options + assert "Fluids" in domains + for domain in domains: + app.sidebar.selectbox[0].set_value(domain).run() + for key in app.sidebar.selectbox[1].options: + app.sidebar.selectbox[1].set_value(key).run() + assert not app.exception, key + + +def test_form_waits_for_required_inputs_then_calculates(): + app = open_app("Thermo.conduction_heat_rate") + assert "Enter" in app.info[0].value + for name, value in { + "conductivity": 0.72, + "area": 12, + "delta_temperature": 25, + "thickness": 0.2, + }.items(): + app.number_input(key=f"in:Thermo.conduction_heat_rate:{name}").set_value(value) + app.run() + assert not app.exception + assert app.metric[0].value == "1080" + assert "## Inputs" in app.markdown[-1].value # the calc sheet tab + + +def test_uncertainty_tab_runs_monte_carlo(): + app = open_app("Thermo.conduction_heat_rate") + for name, value in { + "conductivity": 0.72, + "area": 12, + "delta_temperature": 25, + "thickness": 0.2, + }.items(): + app.number_input(key=f"in:Thermo.conduction_heat_rate:{name}").set_value(value) + app.run() + app.slider(key="pct:Thermo.conduction_heat_rate:conductivity").set_value(5.0).run() + assert not app.exception + labels = [m.label for m in app.metric] + assert "95 % interval" in labels + + +def test_search_and_error_message(): + app = AppTest.from_file(APP, default_timeout=30).run() + app.sidebar.text_input[0].set_value("reynolds").run() + assert app.sidebar.selectbox[0].value == "Fluids.reynolds_number" + for name, value in {"density": 998, "velocity": 2, "length": 0.05, "viscosity": 0}.items(): + app.number_input(key=f"in:Fluids.reynolds_number:{name}").set_value(value) + app.run() + assert app.error and "Error" in app.error[0].value diff --git a/tests/test_fatigue.py b/tests/test_fatigue.py new file mode 100644 index 0000000..f89e077 --- /dev/null +++ b/tests/test_fatigue.py @@ -0,0 +1,174 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""Tests for fpc.fatigue.Fatigue. + +Source for every equation: Shigley's Mechanical Engineering Design +(Budynas & Nisbett, 10th ed.), Ch. 6. ``test_reliability_factor_matches_table`` +asserts *published* table values (Table 6-5); the other expected numbers are +independent hand calculations of the cited equations. +""" + +import math + +import pytest + +from fpc.fatigue import Fatigue + +fatigue = Fatigue() +MPA = 1e6 + + +def test_endurance_limit_steel(): + """Shigley Eq. 6-8: Se' = 0.5 Sut up to 1400 MPa, then a 700 MPa plateau.""" + assert fatigue.endurance_limit_steel(ultimate_strength=600 * MPA) == pytest.approx(300 * MPA) + assert fatigue.endurance_limit_steel(ultimate_strength=1400 * MPA) == pytest.approx(700 * MPA) + assert fatigue.endurance_limit_steel(ultimate_strength=1800 * MPA) == pytest.approx(700 * MPA) + + +def test_surface_factor_hand_calc(): + """Shigley Eq. 6-19 with Table 6-2: machined, Sut = 520 MPa -> + ka = 4.51 * 520^-0.265 = 0.860 (hand calculation).""" + ka = fatigue.surface_factor(ultimate_strength=520 * MPA, finish="machined") + assert ka == pytest.approx(0.860, abs=5e-4) + + +@pytest.mark.parametrize( + ("finish", "a", "b"), + [ + ("ground", 1.58, -0.085), + ("machined", 4.51, -0.265), + ("cold-drawn", 4.51, -0.265), + ("hot-rolled", 57.7, -0.718), + ("as-forged", 272.0, -0.995), + ], +) +def test_surface_factor_uses_table_6_2_coefficients(finish, a, b): + """Shigley Table 6-2 coefficients (Sut in MPa), evaluated at Sut = 1000 MPa.""" + assert fatigue.surface_factor(ultimate_strength=1000 * MPA, finish=finish) == pytest.approx( + a * 1000**b + ) + + +def test_rougher_finish_lowers_the_surface_factor(): + factors = [ + fatigue.surface_factor(ultimate_strength=800 * MPA, finish=f) + for f in ("ground", "machined", "hot-rolled", "as-forged") + ] + assert factors == sorted(factors, reverse=True) + + +def test_size_factor_hand_calc(): + """Shigley Eq. 6-20: kb = 1.24 d^-0.107 (d <= 51 mm), 1.51 d^-0.157 above.""" + assert fatigue.size_factor(diameter=0.032) == pytest.approx(1.24 * 32**-0.107) + assert fatigue.size_factor(diameter=0.032) == pytest.approx(0.856, abs=5e-4) + assert fatigue.size_factor(diameter=0.100) == pytest.approx(1.51 * 100**-0.157) + assert fatigue.size_factor(diameter=0.100, loading="axial") == 1.0 + with pytest.raises(ValueError, match="metres"): + fatigue.size_factor(diameter=32.0) # millimetres passed by mistake + + +def test_load_factor(): + """Shigley Eq. 6-26: kc = 1 bending, 0.85 axial, 0.59 torsion.""" + assert fatigue.load_factor(loading="bending") == 1.0 + assert fatigue.load_factor(loading="axial") == 0.85 + assert fatigue.load_factor(loading="torsion") == 0.59 + + +@pytest.mark.parametrize( + ("reliability", "published_ke"), + [(0.50, 1.000), (0.90, 0.897), (0.95, 0.868), (0.99, 0.814), (0.999, 0.753), (0.9999, 0.702)], +) +def test_reliability_factor_matches_table(reliability, published_ke): + """Published values: Shigley 10th ed., Table 6-5 (ke = 1 - 0.08 za).""" + ke = fatigue.reliability_factor(reliability=reliability) + assert ke == pytest.approx(published_ke, abs=1e-3) + + +def test_marin_endurance_limit_multiplies_the_factors(): + se = fatigue.marin_endurance_limit( + specimen_endurance_limit=300 * MPA, + surface_factor=0.8, + size_factor=0.9, + reliability_factor=0.814, + ) + assert se == pytest.approx(300 * MPA * 0.8 * 0.9 * 0.814) + + +# Load point used for the mean-stress criteria (all MPa, hand calculations): +# sa = 100, sm = 100, Se = 200, Sut = 500, Sy = 400. +_POINT = {"alternating_stress": 100 * MPA, "mean_stress": 100 * MPA, "endurance_limit": 200 * MPA} + + +def test_goodman_and_soderberg_hand_calc(): + """1/n = sa/Se + sm/Sut = 0.5 + 0.2 -> 1.4286; Soderberg 0.5 + 0.25 -> 1.3333.""" + goodman = fatigue.goodman_safety_factor(**_POINT, ultimate_strength=500 * MPA) + soderberg = fatigue.soderberg_safety_factor(**_POINT, yield_strength=400 * MPA) + assert goodman == pytest.approx(1 / 0.7) + assert soderberg == pytest.approx(1 / 0.75) + + +def test_asme_elliptic_hand_calc(): + """n = 1/sqrt(0.5^2 + 0.25^2) = 1.78885.""" + n = fatigue.asme_elliptic_safety_factor(**_POINT, yield_strength=400 * MPA) + assert n == pytest.approx(1 / math.sqrt(0.25 + 0.0625)) + + +def test_gerber_satisfies_its_parabola(): + """Shigley Table 6-7: the Gerber n must satisfy n sa/Se + (n sm/Sut)^2 = 1.""" + n = fatigue.gerber_safety_factor(**_POINT, ultimate_strength=500 * MPA) + assert n * 100 / 200 + (n * 100 / 500) ** 2 == pytest.approx(1.0) + # Gerber lies above Goodman, which lies above Soderberg. + goodman = fatigue.goodman_safety_factor(**_POINT, ultimate_strength=500 * MPA) + soderberg = fatigue.soderberg_safety_factor(**_POINT, yield_strength=400 * MPA) + assert soderberg < goodman < n + + +def test_gerber_with_no_mean_stress_is_se_over_sa(): + n = fatigue.gerber_safety_factor( + alternating_stress=100 * MPA, + mean_stress=0.0, + endurance_limit=250 * MPA, + ultimate_strength=600 * MPA, + ) + assert n == pytest.approx(2.5) + + +def test_mean_stress_criteria_reject_compressive_mean(): + with pytest.raises(ValueError, match="mean_stress"): + fatigue.goodman_safety_factor( + alternating_stress=1.0, mean_stress=-1.0, endurance_limit=1.0, ultimate_strength=2.0 + ) + + +def test_sn_curve_coefficients_hand_calc(): + """Shigley Eqs. 6-14, 6-15 with Sut = 700, Se = 350 MPa, f = 0.9: + a = 630^2/350 = 1134 MPa, b = -log10(630/350)/3 = -0.085091.""" + coeffs = fatigue.sn_curve_coefficients(ultimate_strength=700 * MPA, endurance_limit=350 * MPA) + assert coeffs["a"] == pytest.approx(1134 * MPA) + assert coeffs["b"] == pytest.approx(-0.085091, rel=1e-4) + + +def test_cycles_to_failure_spans_1e3_to_1e6(): + """The Basquin line passes through (1e3, f*Sut) and (1e6, Se).""" + common = {"ultimate_strength": 700 * MPA, "endurance_limit": 350 * MPA} + assert fatigue.cycles_to_failure(alternating_stress=630 * MPA, **common) == pytest.approx(1e3) + just_above_se = fatigue.cycles_to_failure(alternating_stress=350.0001 * MPA, **common) + assert just_above_se == pytest.approx(1e6, rel=1e-4) + # Hand calc at 500 MPa: N = (500/1134)^(1/-0.085091) = 1.512e4 cycles. + assert fatigue.cycles_to_failure(alternating_stress=500 * MPA, **common) == pytest.approx( + 1.512e4, rel=1e-3 + ) + # Below the endurance limit: infinite life. + assert fatigue.cycles_to_failure(alternating_stress=300 * MPA, **common) == math.inf + with pytest.raises(ValueError, match="low-cycle"): + fatigue.cycles_to_failure(alternating_stress=650 * MPA, **common) + + +def test_invalid_inputs_raise(): + with pytest.raises(ValueError): + fatigue.endurance_limit_steel(ultimate_strength=0.0) + with pytest.raises(ValueError): + fatigue.reliability_factor(reliability=99.0) # percent instead of a fraction + with pytest.raises(ValueError): + fatigue.marin_endurance_limit(specimen_endurance_limit=300 * MPA, size_factor=0.0) diff --git a/tests/test_machine_elements.py b/tests/test_machine_elements.py new file mode 100644 index 0000000..9cd5476 --- /dev/null +++ b/tests/test_machine_elements.py @@ -0,0 +1,224 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""Tests for fpc.machine_elements.MachineElements. + +Equations are from Shigley's Mechanical Engineering Design (Budynas & Nisbett, +10th ed.), cited per test. The expected numbers are *independent hand +calculations* (or a different route to the same answer, such as numerically +integrating the pressure cone, or back-substituting a diameter into the stress +formulas) - not values copied from the book's worked examples. +""" + +import math + +import pytest +from scipy.integrate import quad + +from fpc.fatigue import Fatigue +from fpc.machine_elements import MachineElements + +me = MachineElements() + + +# --- Bolted joints ----------------------------------------------------------- + + +def test_tightening_torque(): + """Shigley Eq. 8-27, T = K*Fi*d: 0.2 * 20 kN * 12 mm = 48 N*m.""" + torque = me.bolt_tightening_torque(preload=20e3, nominal_diameter=0.012) + assert torque == pytest.approx(48.0) + + +@pytest.mark.parametrize(("connection", "fraction"), [("reusable", 0.75), ("permanent", 0.90)]) +def test_preload_is_a_fraction_of_proof_load(connection, fraction): + """Shigley Sec. 8-9: Fi = 0.75 Fp (reusable) or 0.90 Fp (permanent), Fp = At*Sp.""" + preload = me.bolt_preload( + proof_strength=600e6, tensile_stress_area=84.3e-6, connection=connection + ) + assert preload == pytest.approx(fraction * 600e6 * 84.3e-6) + + +def test_bolt_stiffness_reduces_to_a_plain_bar(): + """Shigley Eq. 8-17. With no thread in the grip it must equal Ad*E/ld, + and with only thread in the grip At*E/lt (one spring each).""" + d, at, e = 0.012, 84.3e-6, 207e9 + shank_area = math.pi * d**2 / 4 + all_shank = me.bolt_stiffness( + modulus=e, + nominal_diameter=d, + tensile_stress_area=at, + unthreaded_length=0.03, + threaded_length=0.0, + ) + all_thread = me.bolt_stiffness( + modulus=e, + nominal_diameter=d, + tensile_stress_area=at, + unthreaded_length=0.0, + threaded_length=0.03, + ) + assert all_shank == pytest.approx(shank_area * e / 0.03) + assert all_thread == pytest.approx(at * e / 0.03) + # Springs in series: the compliances 1/k add. + mixed = me.bolt_stiffness( + modulus=e, + nominal_diameter=d, + tensile_stress_area=at, + unthreaded_length=0.02, + threaded_length=0.01, + ) + assert 1 / mixed == pytest.approx(0.02 / (shank_area * e) + 0.01 / (at * e)) + + +def test_member_stiffness_matches_integrating_the_pressure_cones(): + """Shigley Eq. 8-23 vs a direct numerical integration of the two 30-degree + frusta (washer face 1.5 d) - an independent route to the same answer.""" + d, grip, e = 0.012, 0.04, 207e9 + tan30 = math.tan(math.radians(30)) + + def area(x): + outer_radius = 0.75 * d + x * tan30 # cone grows from the washer face + return math.pi * (outer_radius**2 - (d / 2) ** 2) + + # Each cone spans half the grip; two identical cones act in series. + one_cone_compliance, _ = quad(lambda x: 1 / (e * area(x)), 0, grip / 2) + expected = 1 / (2 * one_cone_compliance) + assert me.member_stiffness(modulus=e, nominal_diameter=d, grip_length=grip) == pytest.approx( + expected, rel=1e-6 + ) + + +def test_joint_constant_and_load_sharing(): + """C = kb/(kb+km); Fb = C*P + Fi, Fm = (1-C)*P - Fi, P0 = Fi/(1-C).""" + c = me.joint_stiffness_constant(bolt_stiffness=1e9, member_stiffness=3e9) + assert c == pytest.approx(0.25) + loads = me.bolted_joint_loads(preload=10e3, external_load=4e3, stiffness_constant=c) + assert loads["bolt_load"] == pytest.approx(11e3) + assert loads["member_load"] == pytest.approx(-7e3) # still clamped + assert loads["separation_load"] == pytest.approx(10e3 / 0.75) + with pytest.raises(ValueError, match="separates"): + me.bolted_joint_loads(preload=10e3, external_load=20e3, stiffness_constant=c) + + +# --- Shafts -------------------------------------------------------------------- + + +def test_static_shaft_diameter_back_substitutes_to_the_safety_factor(): + """Plug the diameter back into sigma = 32M/(pi d^3), tau = 16T/(pi d^3) and + von Mises sigma' = sqrt(sigma^2 + 3 tau^2): Sy / sigma' must equal n.""" + m, t, sy, n = 150.0, 200.0, 350e6, 2.5 + d = me.shaft_diameter_static(bending_moment=m, torque=t, yield_strength=sy, safety_factor=n) + sigma = 32 * m / (math.pi * d**3) + tau = 16 * t / (math.pi * d**3) + assert sy / math.sqrt(sigma**2 + 3 * tau**2) == pytest.approx(n) + + +def test_static_shaft_pure_bending_hand_calc(): + """Pure bending: d = (32 n M / (pi Sy))^(1/3) = (32*2*100/(pi*300e6))^(1/3) = 18.937 mm.""" + d = me.shaft_diameter_static( + bending_moment=100.0, torque=0.0, yield_strength=300e6, safety_factor=2.0 + ) + assert d == pytest.approx(0.018937, rel=1e-4) + + +def test_de_goodman_diameter_gives_the_design_factor_on_the_goodman_line(): + """Shigley Eq. 7-8. Back-substitute d into the von Mises alternating and mean + stresses and check the Goodman safety factor (fpc.Fatigue) equals n.""" + ma, tm, kf, kfs = 120.0, 90.0, 1.7, 1.5 + se, sut, n = 200e6, 700e6, 1.8 + d = me.shaft_diameter_de_goodman( + alternating_moment=ma, + mean_moment=0.0, + alternating_torque=0.0, + mean_torque=tm, + endurance_limit=se, + ultimate_strength=sut, + safety_factor=n, + fatigue_factor_bending=kf, + fatigue_factor_torsion=kfs, + ) + sigma_a = 32 * kf * ma / (math.pi * d**3) # bending only alternates + sigma_m = math.sqrt(3) * 16 * kfs * tm / (math.pi * d**3) # torsion only is steady + goodman = Fatigue().goodman_safety_factor( + alternating_stress=sigma_a, mean_stress=sigma_m, endurance_limit=se, ultimate_strength=sut + ) + assert goodman == pytest.approx(n) + + +# --- Springs --------------------------------------------------------------------- + + +def test_spring_rate_hand_calc(): + """Shigley Eq. 10-9: k = d^4 G / (8 D^3 Na) = (2e-3)^4 * 79.3e9 / (8 * 0.02^3 * 10).""" + k = me.spring_rate( + wire_diameter=2e-3, mean_coil_diameter=20e-3, active_coils=10, shear_modulus=79.3e9 + ) + assert k == pytest.approx(1982.5) + + +def test_spring_shear_stress_corrections(): + """C = D/d = 8: Wahl K = 31/28 + 0.615/8 = 1.18402, Bergstrasser (Shigley + Eq. 10-5) K = 34/29 = 1.17241; plain stress 8FD/(pi d^3).""" + plain = 8 * 100.0 * 0.016 / (math.pi * 0.002**3) + wahl = me.spring_shear_stress(force=100.0, wire_diameter=0.002, mean_coil_diameter=0.016) + berg = me.spring_shear_stress( + force=100.0, wire_diameter=0.002, mean_coil_diameter=0.016, correction="bergstrasser" + ) + assert wahl == pytest.approx(1.18402 * plain, rel=1e-5) + assert berg == pytest.approx(34 / 29 * plain) + assert wahl == pytest.approx(berg, rel=0.015) # the two agree within ~1 % + + +# --- Bearings -------------------------------------------------------------------- + + +def test_bearing_life(): + """L10 = (C/P)^a: C/P = 10 gives 1000 Mrev (ball, a=3) or 10^(10/3) (roller).""" + assert me.bearing_l10_life(dynamic_load_rating=30e3, equivalent_load=3e3) == pytest.approx( + 1000.0 + ) + roller = me.bearing_l10_life( + dynamic_load_rating=30e3, equivalent_load=3e3, bearing_type="roller" + ) + assert roller == pytest.approx(10 ** (10 / 3)) + # 1000e6 rev at 1500 rev/min = 1e9 / 90 000 rev/h = 11 111 h. + hours = me.bearing_l10_life_hours(dynamic_load_rating=30e3, equivalent_load=3e3, speed_rpm=1500) + assert hours == pytest.approx(11111.1, rel=1e-5) + + +def test_required_rating_round_trips_with_life(): + c = me.bearing_required_load_rating( + equivalent_load=2.5e3, life_hours=20e3, speed_rpm=900, bearing_type="roller" + ) + life = me.bearing_l10_life_hours( + dynamic_load_rating=c, equivalent_load=2.5e3, speed_rpm=900, bearing_type="roller" + ) + assert life == pytest.approx(20e3) + + +# --- Welds ----------------------------------------------------------------------- + + +def test_fillet_weld_throat_stress(): + """Shigley Sec. 9-3: tau = F / (0.707 h L) = 10 kN / (0.707 * 6 mm * 100 mm) = 23.57 MPa.""" + tau = me.fillet_weld_shear_stress(force=10e3, leg_size=0.006, weld_length=0.1) + assert tau == pytest.approx(23.57e6, rel=1e-3) + + +# --- Validation ------------------------------------------------------------------ + + +def test_invalid_inputs_raise(): + with pytest.raises(ValueError): + me.bolt_tightening_torque(preload=-1.0, nominal_diameter=0.01) + with pytest.raises(ValueError, match="D vs d"): + me.spring_rate( + wire_diameter=0.02, mean_coil_diameter=0.002, active_coils=5, shear_modulus=79e9 + ) + with pytest.raises(ValueError): + me.bearing_l10_life_hours(dynamic_load_rating=1e4, equivalent_load=1e3, speed_rpm=0) + with pytest.raises(ValueError): + me.shaft_diameter_static(bending_moment=0, torque=0, yield_strength=1e8, safety_factor=2) + with pytest.raises(ValueError): + me.joint_stiffness_constant(bolt_stiffness=0.0, member_stiffness=1.0) diff --git a/tests/test_mcp_server.py b/tests/test_mcp_server.py index 438be4d..c5e1364 100644 --- a/tests/test_mcp_server.py +++ b/tests/test_mcp_server.py @@ -68,3 +68,51 @@ def test_bad_input_comes_back_as_a_readable_error(): def test_reference_tables_list_columns(): tables = call("list_reference_tables").structured_content assert "density_kg_m3" in tables["water_liquid_1atm"] + + +# --- --domains: one tool per calculation ------------------------------------- + + +def list_tools(server): + async def go(): + async with Client(server) as client: + return {tool.name: tool for tool in (await client.list_tools()).tools} + + return asyncio.run(go()) + + +def test_domains_flag_adds_one_tool_per_calculation_with_the_registry_schema(): + from fpc import registry + + tools = list_tools(build_server(["Fluids"])) + fluids = [c for c in registry.calculations() if c.domain == "Fluids" and c.json_callable] + assert len(tools) == 5 + len(fluids) + + tool = tools["fluids_reynolds_number"] + schema = tool.input_schema + assert sorted(schema["required"]) == ["density", "length", "velocity", "viscosity"] + assert schema["properties"]["density"]["type"] == "number" + assert "kg/m^3" in schema["properties"]["density"]["description"] + assert "Reynolds" in tool.description + + +def test_direct_tool_calculates_and_explains_bad_input(): + server = build_server(["fluids"]) # any case + + async def go(arguments): + async with Client(server) as client: + return await client.call_tool("fluids_reynolds_number", arguments) + + args = {"density": 998, "velocity": 2, "length": 0.05, "viscosity": 0.001} + result = asyncio.run(go(args)) + assert not result.is_error + assert result.structured_content["result"] == pytest.approx(99800) + + bad = asyncio.run(go({**args, "viscosity": 0})) + assert bad.is_error + assert "ZeroDivisionError" in bad.content[0].text or "ValueError" in bad.content[0].text + + +def test_unknown_domain_is_rejected_with_choices(): + with pytest.raises(ValueError, match="Fluids"): + build_server(["plumbing"]) diff --git a/tests/test_psychrometrics.py b/tests/test_psychrometrics.py new file mode 100644 index 0000000..8cddad7 --- /dev/null +++ b/tests/test_psychrometrics.py @@ -0,0 +1,133 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""Tests for fpc.psychrometrics.Psychrometrics. + +Equations: ASHRAE Handbook - Fundamentals (2017), Ch. 1 "Psychrometrics". + +Published reference values asserted here: + +* Saturation pressure of water vapour - ASHRAE Handbook - Fundamentals 2017, + Ch. 1, Table 3 (Thermodynamic Properties of Water at Saturation). +* Dew point and humidity ratio at 25 degC / 50 % RH, sea level - standard + psychrometric chart values (e.g. ASHRAE Psychrometric Chart No. 1), read to + chart precision, so the tolerances are loose. + +Everything else is checked by hand calculation or by internal consistency +(substituting an answer back into the equation it should satisfy). +""" + +import pytest + +from fpc.psychrometrics import Psychrometrics + +psy = Psychrometrics() + + +@pytest.mark.parametrize( + ("temperature_c", "phase", "published_kpa"), + [ + (-20.0, "ice", 0.10326), + (0.0, "water", 0.6112), + (20.0, "water", 2.3392), + (25.0, "water", 3.1699), + (100.0, "water", 101.42), + ], +) +def test_saturation_pressure_matches_ashrae_table(temperature_c, phase, published_kpa): + """ASHRAE Handbook - Fundamentals 2017, Ch. 1, Table 3.""" + pws = psy.saturation_vapor_pressure(temperature_c=temperature_c, phase=phase) + assert pws / 1e3 == pytest.approx(published_kpa, rel=1e-3) + + +def test_auto_phase_uses_ice_below_freezing(): + auto = psy.saturation_vapor_pressure(temperature_c=-10.0) + ice = psy.saturation_vapor_pressure(temperature_c=-10.0, phase="ice") + water = psy.saturation_vapor_pressure(temperature_c=-10.0, phase="water") + assert auto == ice + assert ice < water # supercooled water has the higher vapour pressure + + +def test_standard_pressure_at_altitude(): + """ASHRAE 2017 Ch. 1 Eq. 3 by hand: 101.325 * (1 - 2.25577e-5 * 1500)^5.2559 = 84.556 kPa.""" + assert psy.standard_pressure(altitude=0.0) == pytest.approx(101325.0) + assert psy.standard_pressure(altitude=1500.0) == pytest.approx(84556, rel=1e-4) + + +def test_humidity_ratio_hand_calc_and_inverse(): + """ASHRAE 2017 Ch. 1 Eq. 20: W = 0.621945 * 2000 / (101325 - 2000) = 0.012523.""" + w = psy.humidity_ratio(vapor_pressure=2000.0) + assert w == pytest.approx(0.012523, rel=1e-4) + assert psy.vapor_pressure(humidity_ratio=w) == pytest.approx(2000.0) + + +def test_relative_humidity_round_trip(): + pw = 0.4 * psy.saturation_vapor_pressure(temperature_c=30.0) + assert psy.relative_humidity(temperature_c=30.0, vapor_pressure=pw) == pytest.approx(0.4) + + +def test_chart_point_25c_50_percent(): + """Psychrometric chart (sea level), 25 degC / 50 % RH: W ~ 9.9 g/kg and + dew point ~ 13.9 degC.""" + w = psy.humidity_ratio_from_relative_humidity(temperature_c=25.0, relative_humidity=0.5) + assert w == pytest.approx(0.0099, abs=1e-4) + assert psy.dew_point(temperature_c=25.0, relative_humidity=0.5) == pytest.approx(13.9, abs=0.1) + + +def test_dew_point_is_where_the_air_saturates(): + """At the dew point, pws(td) equals the air's actual vapour pressure.""" + td = psy.dew_point(temperature_c=30.0, relative_humidity=0.6) + actual_pw = 0.6 * psy.saturation_vapor_pressure(temperature_c=30.0) + assert psy.saturation_vapor_pressure(temperature_c=td) == pytest.approx(actual_pw, rel=1e-8) + assert psy.dew_point(temperature_c=30.0, relative_humidity=1.0) == 30.0 + + +def test_enthalpy_hand_calc(): + """ASHRAE 2017 Ch. 1 Eq. 32: h = 1.006 t + W (2501 + 1.86 t).""" + assert psy.moist_air_enthalpy(temperature_c=20.0, humidity_ratio=0.0) == pytest.approx(20.12) + # 1.006*25 + 0.01*(2501 + 46.5) = 25.15 + 25.475 = 50.625 kJ/kg + assert psy.moist_air_enthalpy(temperature_c=25.0, humidity_ratio=0.01) == pytest.approx(50.625) + + +def test_specific_volume_of_dry_air(): + """Ideal gas: v = 287.042 * 293.15 / 101325 = 0.83045 m^3/kg at 20 degC.""" + v = psy.specific_volume(temperature_c=20.0, humidity_ratio=0.0) + assert v == pytest.approx(0.83045, rel=1e-4) + # Water vapour is lighter than air, so moist air takes more room per kg dry air. + assert psy.specific_volume(temperature_c=20.0, humidity_ratio=0.01) > v + + +def test_wet_bulb_satisfies_the_adiabatic_saturation_balance(): + """Substitute t* back into ASHRAE 2017 Ch. 1 Eq. 33 and recover the air's W.""" + t, rh = 35.0, 0.3 + t_star = psy.wet_bulb(temperature_c=t, relative_humidity=rh) + ws_star = psy.humidity_ratio(vapor_pressure=psy.saturation_vapor_pressure(temperature_c=t_star)) + w_from_eq33 = ((2501 - 2.326 * t_star) * ws_star - 1.006 * (t - t_star)) / ( + 2501 + 1.86 * t - 4.186 * t_star + ) + w = psy.humidity_ratio_from_relative_humidity(temperature_c=t, relative_humidity=rh) + assert w_from_eq33 == pytest.approx(w, rel=1e-6) + # The wet bulb always lies between the dew point and the dry bulb. + assert psy.dew_point(temperature_c=t, relative_humidity=rh) < t_star < t + + +def test_wet_bulb_chart_value_and_limits(): + """Chart reading at 25 degC / 50 % RH: wet bulb ~ 17.9 degC.""" + assert psy.wet_bulb(temperature_c=25.0, relative_humidity=0.5) == pytest.approx(17.9, abs=0.2) + assert psy.wet_bulb(temperature_c=30.0, relative_humidity=1.0) == pytest.approx(30.0) + # Below freezing the ice form of the balance is used; still bracketed. + t_star = psy.wet_bulb(temperature_c=-5.0, relative_humidity=0.5) + assert psy.dew_point(temperature_c=-5.0, relative_humidity=0.5) < t_star < -5.0 + + +def test_invalid_inputs_raise(): + with pytest.raises(ValueError, match="fraction"): + psy.dew_point(temperature_c=25.0, relative_humidity=50.0) # percent, not fraction + with pytest.raises(ValueError): + psy.humidity_ratio(vapor_pressure=2e5, pressure=101325.0) + with pytest.raises(ValueError, match="ice"): + psy.saturation_vapor_pressure(temperature_c=10.0, phase="ice") + with pytest.raises(ValueError): + psy.saturation_vapor_pressure(temperature_c=250.0) + with pytest.raises(ValueError): + psy.dew_point(temperature_c=25.0, relative_humidity=0.0) diff --git a/tests/test_report.py b/tests/test_report.py new file mode 100644 index 0000000..331c1e5 --- /dev/null +++ b/tests/test_report.py @@ -0,0 +1,116 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""Tests for calc reports (fpc.report) and the report/uncertainty commands.""" + +import datetime +import json + +import pytest + +from fpc.cli import main +from fpc.report import calc_report +from fpc.uncertainty import Normal, monte_carlo + +WALL = {"conductivity": 0.72, "area": 12, "delta_temperature": 25, "thickness": 0.2} + + +def test_sheet_has_method_inputs_with_units_result_and_review(): + text = calc_report( + "Thermo.conduction_heat_rate", + WALL, + title="North wall heat loss", + checked_by="A. Reviewer", + date=datetime.date(2026, 11, 7), + ) + assert text.startswith("# North wall heat loss\n") + assert "| Checked by | A. Reviewer |" in text + assert "| Date | 2026-11-07 |" in text + assert "Q_dot = k * A * dT / L" in text # the equation, from the docstring + assert "| `conductivity` | 0.72 | W/(m*K) |" in text + assert "**Result: 1080**" in text + assert "- [ ] Method and assumptions suit this case" in text + + +def test_defaults_are_listed_and_dict_results_become_a_table(): + text = calc_report( + "Fluids.pipe_flow", + { + "flow": 0.012, + "diameter": 0.1, + "length": 120, + "roughness": 4.5e-5, + "density": 998, + "viscosity": 1e-3, + }, + ) + assert "| pressure_drop | 26690.8 |" in text + projectile = calc_report("Dynamics.projectile_range", {"speed": 20, "angle_deg": 45}) + assert "| `gravity` | 9.80665 (default) |" in projectile # shown, not hidden + + +def test_uncertainty_section(): + inputs = {**WALL, "conductivity": Normal(mean=0.72, std=0.05)} + mc = monte_carlo("Thermo.conduction_heat_rate", inputs, seed=0) + text = calc_report("Thermo.conduction_heat_rate", WALL, uncertainty=mc) + assert "## Uncertainty" in text + assert "- `conductivity`: 100%" in text + + +def test_bad_inputs_raise_before_writing(): + with pytest.raises(ValueError, match="missing"): + calc_report("Thermo.conduction_heat_rate", {"area": 1}) + + +def test_cli_report_and_uncertainty(tmp_path, capsys): + out = tmp_path / "wall.md" + main( + [ + "report", + "Thermo.conduction_heat_rate", + "conductivity=0.72", + "area=12", + "delta_temperature=25", + "thickness=0.2", + "--out", + str(out), + ] + ) + assert "**Result: 1080**" in out.read_text() + capsys.readouterr() + + main( + [ + "uncertainty", + "Thermo.conduction_heat_rate", + "conductivity=normal:0.72,0.05", + "area=12", + "delta_temperature=25", + "thickness=0.2", + "--seed", + "1", + "--samples", + "2000", + ] + ) + summary = json.loads(capsys.readouterr().out) + assert summary["mean"] == pytest.approx(1080, rel=0.01) + assert summary["samples"] == 2000 + + +def test_cli_uncertainty_tuple_output_index(capsys): + main( + [ + "uncertainty", + "Modal.natural_frequency", + "stiffness=normal:4000,100", + "mass=2.5", + "--output", + "1", + "--seed", + "0", + "--samples", + "500", + ] + ) + assert json.loads(capsys.readouterr().out)["mean"] == pytest.approx(6.366, rel=0.01) diff --git a/tests/test_statics_material.py b/tests/test_statics_material.py index ed71813..58921a0 100644 --- a/tests/test_statics_material.py +++ b/tests/test_statics_material.py @@ -3,6 +3,8 @@ """Tests for fpc.statics.Statics and fpc.material.Material.""" +import math + import pytest from fpc.material import Material @@ -81,3 +83,74 @@ def test_thermal_expansion_scales_with_temperature(): delta_temperature=100.0, ) assert big == pytest.approx(2 * small) + + +# --- Column buckling: Euler vs Johnson --------------------------------------- +# Formulas: Shigley's Mechanical Engineering Design, 10th ed., Ch. 4, +# "Columns with Central Loading" (Euler) and "Intermediate-Length Columns with +# Central Loading" (J. B. Johnson parabola). The numbers below are independent +# hand calculations, not values copied from the book. + +# A 25 mm solid round steel bar: A = pi d^2/4, I = pi d^4/64, so r = d/4. +_D = 0.025 +_AREA = math.pi * _D**2 / 4 +_I = math.pi * _D**4 / 64 +_E = 200e9 +_SY = 250e6 + + +def test_radius_of_gyration_of_a_round_bar_is_quarter_diameter(): + assert material.radius_of_gyration(moment_of_inertia=_I, area=_AREA) == pytest.approx(_D / 4) + + +def test_slenderness_ratios(): + # KL/r for a 1 m pinned column with r = 6.25 mm: 1 / 0.00625 = 160. + assert material.slenderness_ratio(length=1.0, radius_of_gyration=_D / 4) == pytest.approx(160.0) + # Hand calc: sqrt(2 pi^2 * 200e9 / 250e6) = pi * sqrt(1600) = 40 pi = 125.66. + transition = material.transition_slenderness_ratio(modulus=_E, yield_strength=_SY) + assert transition == pytest.approx(40 * math.pi) + + +def test_johnson_meets_euler_at_the_transition_with_half_the_yield_load(): + """At (KL/r)_1 both formulas give P = A*Sy/2, so the combined curve is continuous.""" + transition = material.transition_slenderness_ratio(modulus=_E, yield_strength=_SY) + common = {"modulus": _E, "moment_of_inertia": _I, "length": transition * _D / 4} + euler = material.euler_buckling_load(**common) + johnson = material.johnson_buckling_load(**common, area=_AREA, yield_strength=_SY) + assert euler == pytest.approx(_AREA * _SY / 2) + assert johnson == pytest.approx(_AREA * _SY / 2) + + +def test_johnson_hand_calculation(): + """L = 0.5 m pinned: KL/r = 80, Pcr/A = 250e6 - (250e6 * 80 / (2 pi))^2 / 200e9.""" + load = material.johnson_buckling_load( + modulus=_E, moment_of_inertia=_I, area=_AREA, length=0.5, yield_strength=_SY + ) + # (250e6 * 80 / 2pi)^2 / 200e9 = (3.1831e9)^2 / 200e9 = 50.66 MPa -> 199.34 MPa + assert load / _AREA == pytest.approx(199.34e6, rel=1e-4) + + +@pytest.mark.parametrize(("length", "formula"), [(0.5, "johnson"), (1.0, "euler")]) +def test_critical_buckling_load_picks_the_right_formula(length, formula): + result = material.critical_buckling_load( + modulus=_E, moment_of_inertia=_I, area=_AREA, length=length, yield_strength=_SY + ) + assert result["formula"] == formula + if formula == "euler": + expected = material.euler_buckling_load(modulus=_E, moment_of_inertia=_I, length=length) + else: + expected = material.johnson_buckling_load( + modulus=_E, moment_of_inertia=_I, area=_AREA, length=length, yield_strength=_SY + ) + assert result["critical_load"] == pytest.approx(expected) + # Neither formula may exceed the squash load A*Sy. + assert result["critical_load"] < _AREA * _SY + + +def test_buckling_rejects_bad_inputs(): + with pytest.raises(ValueError): + material.radius_of_gyration(moment_of_inertia=-1.0, area=1.0) + with pytest.raises(ValueError): + material.transition_slenderness_ratio(modulus=_E, yield_strength=0.0) + with pytest.raises(ValueError): + material.slenderness_ratio(length=0.0, radius_of_gyration=0.01) diff --git a/tests/test_uncertainty.py b/tests/test_uncertainty.py new file mode 100644 index 0000000..7e7e353 --- /dev/null +++ b/tests/test_uncertainty.py @@ -0,0 +1,105 @@ +# SPDX-License-Identifier: Apache-2.0 +# Copyright 2026 Evan Gress + +"""Tests for Monte Carlo uncertainty (fpc.uncertainty). + +Every test fixes ``seed`` so its random numbers, and so its result, are the +same on every run. Tolerances are set from the theory: the error in a +Monte Carlo mean is about std/sqrt(samples). +""" + +import math + +import pytest + +from fpc.uncertainty import Normal, Triangular, Uniform, monte_carlo, parse_distribution + + +def test_sum_of_normals_matches_theory(): + # For y = a + b with independent normal inputs, the theory says + # mean = mean_a + mean_b and std = sqrt(std_a^2 + std_b^2). + result = monte_carlo( + lambda *, a, b: a + b, + {"a": Normal(mean=10, std=3), "b": Normal(mean=5, std=4)}, + samples=50_000, + seed=1, + ) + assert result.mean == pytest.approx(15, abs=0.1) + assert result.std == pytest.approx(5, rel=0.02) + low, high = result.interval(95) + assert low == pytest.approx(15 - 1.96 * 5, abs=0.25) + assert high == pytest.approx(15 + 1.96 * 5, abs=0.25) + # b has the bigger spread: 16 of the 25 units of variance. + assert list(result.sensitivity) == ["b", "a"] + assert result.sensitivity["b"] == pytest.approx(16 / 25, abs=0.02) + + +def test_registry_key_with_fixed_and_uncertain_inputs(): + # Re = rho*v*L/mu is linear in v, so std(Re) = rho*L/mu * std(v). + result = monte_carlo( + "Fluids.reynolds_number", + {"density": 998, "velocity": Normal(mean=2, std=0.1), "length": 0.05, "viscosity": 1e-3}, + seed=2, + ) + assert result.mean == pytest.approx(99_800, rel=0.005) + assert result.std == pytest.approx(998 * 0.05 / 1e-3 * 0.1, rel=0.03) + assert list(result.sensitivity) == ["velocity"] + + +def test_non_vectorizable_calculation_falls_back_to_a_loop_and_picks_an_output(): + # pipe_flow solves Colebrook with a root finder, which cannot take arrays. + result = monte_carlo( + "Fluids.pipe_flow", + { + "flow": Normal(mean=0.012, std=0.0004), + "diameter": 0.1023, + "length": 120, + "roughness": Uniform(low=0.02e-3, high=0.09e-3), + "density": 998, + "viscosity": 1.0e-3, + }, + output="pressure_drop", + samples=1_000, + seed=3, + ) + assert len(result.samples) == 1_000 + assert result.interval(95)[0] < result.mean < result.interval(95)[1] + assert set(result.sensitivity) == {"flow", "roughness"} + assert sum(result.sensitivity.values()) == pytest.approx(1) + + +def test_tuple_result_needs_an_index(): + inputs = {"stiffness": Normal(mean=4000, std=200), "mass": 2.5} + with pytest.raises(ValueError, match="output="): + monte_carlo("Modal.natural_frequency", inputs, samples=10, seed=0) + hz = monte_carlo("Modal.natural_frequency", inputs, output=1, seed=0) + assert hz.mean == pytest.approx(math.sqrt(4000 / 2.5) / (2 * math.pi), rel=0.01) + + +def test_seed_makes_runs_repeatable(): + inputs = {"a": Uniform(low=0, high=1)} + first = monte_carlo(lambda *, a: a, inputs, samples=100, seed=7) + again = monte_carlo(lambda *, a: a, inputs, samples=100, seed=7) + assert (first.samples == again.samples).all() + + +def test_summary_is_plain_numbers(): + result = monte_carlo(lambda *, a: 2 * a, {"a": Triangular(low=0, mode=1, high=2)}, seed=0) + summary = result.summary() + assert set(summary) == {"mean", "std", "p5", "p50", "p95", "samples", "sensitivity"} + assert summary["p50"] == pytest.approx(2, abs=0.05) + + +def test_parse_distribution_and_bad_inputs(): + assert parse_distribution("998") == 998.0 + assert parse_distribution("normal:2,0.1") == Normal(2, 0.1) + assert parse_distribution("Uniform:1,3") == Uniform(1, 3) + assert parse_distribution("triangular:1,2,4") == Triangular(1, 2, 4) + with pytest.raises(ValueError, match="unknown distribution"): + parse_distribution("lognormal:1,2") + with pytest.raises(ValueError): + Normal(mean=1, std=-1) + with pytest.raises(ValueError): + Uniform(low=2, high=1) + with pytest.raises(ValueError): + monte_carlo(lambda *, a: a, {"a": 1.0}, samples=1)