diff --git a/.gitignore b/.gitignore index dc1124d..daf95cf 100644 --- a/.gitignore +++ b/.gitignore @@ -22,3 +22,7 @@ htmlcov/ # build artifacts *.egg-info/ dist/ + +# Validation downloads and results (validation/apc_uiuc.py) +validation/.cache/ +validation/results/ diff --git a/docs/images/validation/bias_by_size.png b/docs/images/validation/bias_by_size.png new file mode 100644 index 0000000..4568002 Binary files /dev/null and b/docs/images/validation/bias_by_size.png differ diff --git a/docs/images/validation/errors.png b/docs/images/validation/errors.png new file mode 100644 index 0000000..b29a490 Binary files /dev/null and b/docs/images/validation/errors.png differ diff --git a/docs/images/validation/operating_points.png b/docs/images/validation/operating_points.png new file mode 100644 index 0000000..114424b Binary files /dev/null and b/docs/images/validation/operating_points.png differ diff --git a/docs/index.md b/docs/index.md index 222cccb..f3f1501 100644 --- a/docs/index.md +++ b/docs/index.md @@ -20,7 +20,7 @@ Electric UAV propulsion design usually crosses several domains: aerodynamics, mo - **Manufacturer data** - Read APC performance files, or QPROP propeller and motor files for a blade-element model, and enter motor datasheet constants, instead of sizing only against abstract component assumptions. + Read APC performance files, QPROP propeller and motor files or APC and UIUC geometry files for a blade-element model, and enter motor datasheet constants, instead of sizing only against abstract component assumptions. - **Battery-aware analysis** diff --git a/docs/reference/blade_element_propeller.md b/docs/reference/blade_element_propeller.md index 33674ea..6fcb6f4 100644 --- a/docs/reference/blade_element_propeller.md +++ b/docs/reference/blade_element_propeller.md @@ -68,12 +68,115 @@ and uses `R` as written, so a file that gives `R` with `Rfac` other than 1 or Without `R`, or with the radii in metres, the two agree. `R` must not be less than the last station's radius. +## UIUC Geometry Files + +The [UIUC Propeller Database](https://m-selig.ae.illinois.edu/props/propDB.html) +gives the measured geometry of many small propellers next to their wind-tunnel +data. A geometry file, such as `apce_10x5_geom.txt`, has a header line +`r/R c/R beta` and one station per line from root to tip: radius and chord as +fractions of the tip radius, and the blade angle in degrees. + +The file gives neither the diameter, the blade count nor the airfoil, so +`pythrust.io.read_uiuc_geometry` takes them as arguments; the one `section` +applies to every station: + +```python +from pythrust.io import read_uiuc_geometry +from pythrust.propeller import BladeElementPropeller, BladeSection + +# The example section of the QPROP user guide, a generic starting point. +section = BladeSection( + cl0=0.50, cl_alpha_per_rad=5.8, cl_min=-0.3, cl_max=1.2, + cd0=0.028, cd2_upper=0.050, cd2_lower=0.020, cl_at_cd0=0.5, + reynolds_ref=70000.0, reynolds_exp=-0.7, +) +blade = read_uiuc_geometry("apce_10x5_geom.txt", diameter_m=0.254, section=section) +propeller = BladeElementPropeller(blade) +``` + +The section parameters set the accuracy. With the generic section above, the +APC Thin Electric 10x5 gives a static thrust coefficient 7–15% above the UIUC +measurement and a power coefficient 16–42% above it, the largest gap at the +lowest RPM. Section parameters fitted to the propeller's airfoil narrow the gap. + +## APC Geometry Files + +APC publishes a geometry file for each propeller, such as `10x5E-PERF.PE0`, on +its [technical data page](https://www.apcprop.com/propeller-technical-data/). +The file gives the chord and blade angle (`TWIST`) at about 50 stations in +inches, the tip radius, the hub transition radius, the blade count, and the +two airfoils of the blade: the first up to a transition start radius, the +second from a transition end radius. APC's thin electric propellers, for +example, go from an Eppler E63 to the APC12, equivalent to a NACA 4412. + +`pythrust.io.read_apc_geometry` reads the stations from the hub transition +outward. The blade angle is that of the chord line, between the leading- and +trailing-edge mold parting lines; the file's `TWIST` column matches its `LE-TE` +pitch, not the lower `PRATHER` pitch a gauge on the lower surface would read. + +`sections` is one section for the whole blade, or a mapping from the file's +airfoil names to sections. `apc_airfoil_polars()` gives the +[polars](#airfoil-polars) of the airfoils APC names, E63, APC12 and CLARK-Y, +computed with NeuralFoil: + +```python +from pythrust.io import read_apc_geometry +from pythrust.propeller import BladeElementPropeller, apc_airfoil_polars + +blade = read_apc_geometry("10x5E-PERF.PE0", apc_airfoil_polars()) +propeller = BladeElementPropeller(blade) +``` + +Between the two transition radii the stations mix the two airfoils: polars in a +`BlendedPolar`, `BladeSection` parameters linearly. + +Against UIUC's wind-tunnel measurements of 75 APC propellers, this model is +about as accurate as APC's own performance tables: some 10% mean error per +propeller in thrust and power, less than the tables' in thrust. See +[Validation](validation.md). + +## Airfoil Polars + +An `AirfoilPolar` tabulates an airfoil's lift and drag coefficients against +angle of attack and Reynolds number. `AirfoilPolar.from_neuralfoil` computes +them with [NeuralFoil](https://github.com/Setuav/NeuralFoil), a neural network +trained on XFOIL results, from a NACA 4- or 5-digit designation, a Selig or +Lednicer `.dat` file, or coordinates: + +```python +from pythrust.propeller import AirfoilPolar + +naca = AirfoilPolar.from_neuralfoil("NACA 4412") +e387 = AirfoilPolar.from_neuralfoil("e387.dat") +cl, cd = naca.coefficients(alpha_rad=0.1, reynolds=8e4, mach=0.1) +``` + +- NeuralFoil gives the table from -20 to 25 degrees, every 0.5 degree, at 13 + Reynolds numbers from 1e4 to 1e6. Beyond -35 and 40 degrees the section is + a flat plate, $c_l = \sin 2\alpha$ and $c_d = 2 \sin^2 \alpha$. Between the + table's points the coefficients are interpolated linearly in the angle of + attack and in $\log Re$; beyond its Reynolds numbers the nearest is used. +- The angle of attack is from the chord line. +- Lift is divided by $\sqrt{1 - M^2}$ (Prandtl-Glauert). +- `n_crit` is the amplification factor at which the boundary layer turns + turbulent: 9 for a quiet wind tunnel, lower for a turbulent free stream. + The default, 7, fits the [validation](validation.md) measurements best. +- Building one table takes about 0.2 s; `apc_airfoil_polars()` caches its + polars per `n_crit`. + +A blade's sections are all `BladeSection` or all polars. The analysis stations +mix the polars of the two nearest geometry stations linearly. A solved +operating point of the APC 10x5E takes about 60 ms. + ## API ### Blade Geometry -`pythrust.io.read_qprop_propeller(path)` reads a QPROP propeller file into a -`BladeGeometry`, the input of a blade-element propeller model: +`pythrust.io.read_qprop_propeller(path)` reads a QPROP propeller file, +`pythrust.io.read_uiuc_geometry(path, diameter_m, section, blade_count=2)` a +UIUC geometry file, and `pythrust.io.read_apc_geometry(path, sections)` an APC +geometry file into a `BladeGeometry`, the input of a blade-element propeller +model: | Field | Unit | Description | |---|---:|---| @@ -82,10 +185,11 @@ than the last station's radius. | `r_m` | m | Station radii, root to tip | | `chord_m` | m | Chord at each station | | `blade_angle_rad` | rad | Blade angle from the plane of rotation at each station | -| `sections` | - | `BladeSection` at each station | +| `sections` | - | `BladeSection`, `AirfoilPolar` or `BlendedPolar` at each station | `BladeSection` holds QPROP's airfoil parameters, listed with their symbols in -[Section lift and drag](#section-lift-and-drag). +[Section lift and drag](#section-lift-and-drag); `AirfoilPolar` and +`BlendedPolar` are [tabulated polars](#airfoil-polars). `section_coefficients(section, alpha_rad, reynolds, mach)` evaluates the section model on scalars or NumPy arrays and returns `(CL, CD)`. @@ -257,9 +361,13 @@ ratio at which the section at 75% radius has zero lift, ignoring the induced velocity, which is small near zero thrust: $$ -J_{\max} = \pi \, \frac{r_{75}}{R_{\text{tip}}} \tan\left(\beta_{75} + \frac{c_{l0}}{c_{l\alpha}}\right) +J_{\max} = \pi \, \frac{r_{75}}{R_{\text{tip}}} \tan\left(\beta_{75} - \alpha_{0}\right) $$ +where $\alpha_0$ is the section's zero-lift angle: $-c_{l0}/c_{l\alpha}$ for a +`BladeSection`, and for a polar the lowest over its Reynolds numbers, so that +the search starts past zero thrust. + ### Differences from QPROP - **Tip radius scaling.** A QPROP propeller file may give the tip radius on its diff --git a/docs/reference/propellers.md b/docs/reference/propellers.md index 9c10316..3e39813 100644 --- a/docs/reference/propellers.md +++ b/docs/reference/propellers.md @@ -7,7 +7,7 @@ a manufacturer's file and pick the model that reads it. | Model | Input | Page | |---|---|---| | `TablePropeller` | Tabulated thrust and power coefficients, such as an APC performance file | [Tabulated Propeller](table_propeller.md) | -| `BladeElementPropeller` | Blade geometry and airfoil parameters, such as a QPROP propeller file | [Blade-Element Propeller](blade_element_propeller.md) | +| `BladeElementPropeller` | Blade geometry and airfoil data, from a QPROP propeller file or an APC or UIUC geometry file, with QPROP section parameters or NeuralFoil polars | [Blade-Element Propeller](blade_element_propeller.md) | ## Model Interface diff --git a/docs/reference/validation.md b/docs/reference/validation.md new file mode 100644 index 0000000..c393d82 --- /dev/null +++ b/docs/reference/validation.md @@ -0,0 +1,103 @@ +# Validation + +How close PyThrust's propeller models come to wind-tunnel measurements, for every APC propeller +that the [UIUC Propeller Database](https://m-selig.ae.illinois.edu/props/propDB.html) measured +and APC publishes a geometry file for: 75 propellers, 7 to 21 inches, in three families. + +| Family | Propellers | Airfoils | +|---|---:|---| +| Thin Electric (E) | 34 | E63 at the root to APC12 (NACA 4412) | +| Sport | 30 | CLARK-Y | +| Slow Flyer (SF) | 11 | E63, or E63 to APC12 | + +## Method + +Four propeller models are compared with UIUC's static tests (thrust and power coefficients +against RPM) and forward-flight runs (against advance ratio, at a few RPM each): + +- **Blade-element model, NeuralFoil polars**: APC's geometry file read with + `read_apc_geometry(path, apc_airfoil_polars(n_crit))`. +- **Blade-element model, generic section**: the same geometry with the example section of the + QPROP user guide on every station. +- **APC table**: APC's own performance file, read with `read_apc`. It is a computation, not a + measurement. + +`n_crit` was chosen on every third propeller of each family (26) and the models compared on the +other 49. The error of a propeller is the mean over its points; forward points with a measured +thrust coefficient below 0.02 are left out, where relative errors lose meaning. + +## Coefficients + +Mean absolute error per propeller, the 49 test propellers (efficiency in percentage points): + +| Model | Static $C_T$ | Static $C_P$ | Forward $C_T$ | Forward $C_P$ | Forward efficiency | +|---|---:|---:|---:|---:|---:| +| Generic section | 9.6% | 14.3% | 20.0% | 16.7% | 4.7 | +| NeuralFoil, `n_crit` 9 | 13.3% | 12.5% | 17.1% | 14.3% | 5.3 | +| **NeuralFoil, `n_crit` 7** | **9.2%** | 13.5% | **12.3%** | 11.5% | 5.5 | +| APC table | 14.5% | 12.5% | 16.0% | 11.3% | 4.0 | + +![Error per propeller](../images/validation/errors.png) + +- With NeuralFoil polars the blade-element model is about as accurate as APC's own tables, and + better in thrust. +- `n_crit` 7 and 5 fit equally well (mean errors 11.58% and 11.59% on the calibration set); 9, + for a quiet wind tunnel, makes the slow, low-Reynolds-number points lose too much lift. The + default is 7. +- The model's and APC's errors go together: per propeller their static power errors correlate at + 0.93, their thrust errors at 0.6 to 0.7. Much of what is left is common to both computations. + +## By family + +Mean signed error over all propellers of a family: + +| Family | Model | Static $C_T$ | Static $C_P$ | Forward $C_T$ | Forward $C_P$ | +|---|---|---:|---:|---:|---:| +| Thin Electric | NeuralFoil, `n_crit` 7 | −3.7% | −6.1% | −2.5% | −1.6% | +| | APC table | +3.1% | −4.7% | +0.2% | +3.1% | +| Sport | NeuralFoil, `n_crit` 7 | −6.1% | −20.0% | −3.7% | −14.5% | +| | APC table | +13.6% | −14.6% | +10.0% | −0.5% | +| Slow Flyer | NeuralFoil, `n_crit` 7 | +10.6% | +7.1% | −17.1% | −9.0% | +| | APC table | +17.9% | +11.4% | +9.0% | +9.6% | + +![Bias by size and family](../images/validation/bias_by_size.png) + +- **Thin Electric**: within a few percent on average. +- **Sport**: the model gives 15 to 20% too little power; APC's table, 15% too little static + power. +- **Slow Flyer**: forward thrust 17% low. These thin, flexible blades bend under load, which + neither computation models; expect errors of 15 to 20%. + +## Operating points + +With a fixed-voltage battery and a motor whose no-load speed is 1.25 times the propeller's median +static test RPM, at full throttle, static and at an advance ratio of 0.3, the measured table being +the truth (49 test propellers, mean absolute error): + +| Model | Static current | Static thrust | Cruise current | Cruise thrust | +|---|---:|---:|---:|---:| +| Generic section | 8.9% | 7.9% | 10.4% | 11.1% | +| NeuralFoil, `n_crit` 7 | 11.2% | 7.8% | 7.4% | 8.3% | +| APC table | 11.0% | 12.3% | 6.7% | 12.6% | + +![Operating points](../images/validation/operating_points.png) + +The motor holds the RPM within 0.3%, so the power error shows in the current and the thrust error +in the thrust, each somewhat smaller than in the coefficients. + +## Range + +The measurements cover APC propellers of 7 to 21 inches, mostly below 8000 RPM. Above that, on +APC's own grid of RPM and advance ratio, the model gives 5 to 10% more thrust and power than +APC's tables, with no measurement to say which is right. The section lift has the +Prandtl-Glauert factor but the drag does not rise as the tip nears the speed of sound, so results +at high tip Mach numbers are outside what was validated. + +## Reproducing + +```bash +PYTHONPATH=. python validation/apc_uiuc.py # downloads into validation/.cache +PYTHONPATH=. python validation/report.py # tables, and the figures on this page +``` + +The data is downloaded from UIUC and APC on the first run and not kept in the repository. diff --git a/mkdocs.yml b/mkdocs.yml index 2c52f32..a144541 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -87,5 +87,6 @@ nav: - Battery: reference/battery.md - Propulsion Solver: reference/propulsion_solver.md - OpenMDAO: reference/openmdao.md + - Validation: reference/validation.md - Developer Guide: - Development & Testing: development.md diff --git a/pyproject.toml b/pyproject.toml index 8629e88..63c2e9c 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -24,6 +24,7 @@ requires-python = ">=3.10" dependencies = [ "numpy>=1.20", "scipy>=1.7", + "setuav-neuralfoil>=0.3.3.1", ] [project.optional-dependencies] diff --git a/pythrust/io/__init__.py b/pythrust/io/__init__.py index 171b63c..6fd1320 100644 --- a/pythrust/io/__init__.py +++ b/pythrust/io/__init__.py @@ -1,4 +1,5 @@ """Readers for propeller and motor data files.""" -from .apc import read_apc # noqa: F401 +from .apc import read_apc, read_apc_geometry # noqa: F401 from .qprop import read_qprop_motor, read_qprop_propeller # noqa: F401 +from .uiuc import read_uiuc_geometry, read_uiuc_performance # noqa: F401 diff --git a/pythrust/io/apc.py b/pythrust/io/apc.py index a33e796..3bd1487 100644 --- a/pythrust/io/apc.py +++ b/pythrust/io/apc.py @@ -1,12 +1,15 @@ -"""Reader for APC propeller performance files (``PER3_*.dat``).""" +"""Readers for APC propeller files: performance (``PER3_*.dat``) and geometry (``*-PERF.PE0``).""" from __future__ import annotations import math import re from pathlib import Path -from typing import Dict, List, Union +from dataclasses import fields +from typing import Dict, List, Mapping, Union +from pythrust.propeller.blade import BladeGeometry, BladeSection +from pythrust.propeller.polar import AirfoilPolar, BlendedPolar from pythrust.propeller.table import PropellerDataPoint, TablePropeller _RPM_RE = re.compile(r"PROP RPM\s*=\s*(\d+(?:\.\d+)?)") @@ -16,6 +19,13 @@ _J, _CT, _CP = 1, 3, 4 _INCH_TO_M = 0.0254 +_GEOMETRY_COLUMN_COUNT = 14 +"""Columns of a PE0 station row: station, chord, three pitches, sweep, rake, +thickness ratio, twist, max thickness, cross-section, zhigh, cgy, cgz.""" +_STATION, _CHORD, _TWIST = 0, 1, 8 +_GEOMETRY_VALUE_RE = re.compile(r"^\s*(RADIUS|HUBTRA|BLADES):\s*(\S+)", re.MULTILINE) +_AIRFOIL_RE = re.compile(r"^\s*AIRFOIL([12]):\s*([-+.\d]+)\s*,\s*(\S+)", re.MULTILINE) + def read_apc(path: Union[str, Path]) -> TablePropeller: """Read an APC ``PER3_*.dat`` performance file. @@ -63,3 +73,109 @@ def read_apc(path: Union[str, Path]) -> TablePropeller: diameter_m=float(match.group("diam")) * _INCH_TO_M, data_by_rpm={rpm: sorted(points, key=lambda p: p.j) for rpm, points in data_by_rpm.items()}, ) + + +def read_apc_geometry( + path: Union[str, Path], + sections: Union[BladeSection, AirfoilPolar, Mapping[str, Union[BladeSection, AirfoilPolar]]], +) -> BladeGeometry: + """Read an APC geometry file (``*-PERF.PE0``) into a blade geometry in SI units. + + The file gives the chord and blade angle (``TWIST``) at stations in + inches, the tip radius, the hub transition radius and the blade count. + Stations inside the hub transition are left out. The tip radius is the + file's ``RADIUS``, or the last station's where that is larger: ``RADIUS`` + is rounded to two decimals. The blade angle is that of + the chord line, between the leading- and trailing-edge mold parting lines; + the file also gives the lower-surface (Prather gauge) pitch, which is + lower. + + The file names two airfoils: the first up to the transition start radius, + the second from the transition end radius. ``sections`` is one section for + every station, or a mapping from those airfoil names to sections; a section + is a ``BladeSection`` or an ``AirfoilPolar``, such as those of + ``apc_airfoil_polars()``. Between the two radii, ``BladeSection`` parameters + are interpolated linearly, and polars are mixed in a ``BlendedPolar``. + + Raises ``ValueError`` naming what is missing from a malformed file, and + ``KeyError`` naming an airfoil that ``sections`` does not map. + """ + path = Path(path) + text = path.read_text(errors="ignore") + + values = {name: value for name, value in _GEOMETRY_VALUE_RE.findall(text)} + missing = [name for name in ("RADIUS", "HUBTRA", "BLADES") if name not in values] + if missing: + raise ValueError(f"{path.name}: no {', '.join(missing)} line") + try: + radius_in = float(values["RADIUS"]) + hub_transition_in = float(values["HUBTRA"]) + blade_count = int(values["BLADES"]) + except ValueError as error: + raise ValueError(f"{path.name}: {error}") from None + + if isinstance(sections, (BladeSection, AirfoilPolar)): + first = second = sections + start_in = end_in = 0.0 + else: + airfoils = {int(index): (float(r_in), name) for index, r_in, name in _AIRFOIL_RE.findall(text)} + if set(airfoils) != {1, 2}: + raise ValueError(f"{path.name}: expected AIRFOIL1 and AIRFOIL2 lines") + (start_in, first_name), (end_in, second_name) = airfoils[1], airfoils[2] + for name in (first_name, second_name): + if name not in sections: + raise KeyError(f"{path.name}: no section for airfoil {name!r}") + first, second = sections[first_name], sections[second_name] + + r_m, chord_m, blade_angle_rad, station_sections = [], [], [], [] + for line in text.splitlines(): + parts = line.split() + if len(parts) != _GEOMETRY_COLUMN_COUNT: + continue + try: + row = [float(part) for part in parts] + except ValueError: + continue + r_in = row[_STATION] + if r_in < hub_transition_in: + continue + r_m.append(r_in * _INCH_TO_M) + chord_m.append(row[_CHORD] * _INCH_TO_M) + blade_angle_rad.append(math.radians(row[_TWIST])) + station_sections.append(_blend(first, second, _fraction(r_in, start_in, end_in))) + + try: + return BladeGeometry( + blade_count=blade_count, + radius_m=max(radius_in * _INCH_TO_M, r_m[-1]) if r_m else radius_in * _INCH_TO_M, + r_m=tuple(r_m), + chord_m=tuple(chord_m), + blade_angle_rad=tuple(blade_angle_rad), + sections=tuple(station_sections), + ) + except ValueError as error: + raise ValueError(f"{path.name}: {error}") from error + + +def _fraction(r: float, start: float, end: float) -> float: + """Position of ``r`` in the transition from ``start`` to ``end``, clipped to [0, 1].""" + if end <= start: + return 0.0 if r < end else 1.0 + return min(max((r - start) / (end - start), 0.0), 1.0) + + +def _blend(first, second, weight: float): + if weight <= 0.0: + return first + if weight >= 1.0: + return second + if isinstance(first, AirfoilPolar) and isinstance(second, AirfoilPolar): + return BlendedPolar(first, second, weight) + if not (isinstance(first, BladeSection) and isinstance(second, BladeSection)): + raise TypeError("the two airfoils' sections must both be BladeSection or both AirfoilPolar") + return BladeSection( + **{ + field.name: (1.0 - weight) * getattr(first, field.name) + weight * getattr(second, field.name) + for field in fields(BladeSection) + } + ) diff --git a/pythrust/io/uiuc.py b/pythrust/io/uiuc.py new file mode 100644 index 0000000..958bcca --- /dev/null +++ b/pythrust/io/uiuc.py @@ -0,0 +1,132 @@ +"""Readers for the UIUC Propeller Database. + +The database, https://m-selig.ae.illinois.edu/props/propDB.html, gives blade +geometry and wind-tunnel measurements of small propellers. +""" + +from __future__ import annotations + +import math +import re +from pathlib import Path +from typing import Dict, List, Optional, Sequence, Union + +import numpy as np + +from pythrust.propeller.blade import BladeGeometry, BladeSection +from pythrust.propeller.table import PropellerDataPoint, TablePropeller + +_RPM_IN_NAME = re.compile(r"_(\d+(?:\.\d+)?)$") + + +def read_uiuc_geometry( + path: Union[str, Path], + diameter_m: float, + section: BladeSection, + blade_count: int = 2, +) -> BladeGeometry: + """Read a UIUC geometry file (``*_geom.txt``) into a blade geometry in SI units. + + The file has a header line ``r/R c/R beta`` and one line per station from + root to tip: the radius and the chord as fractions of the tip radius, and + the blade angle in degrees. It gives neither the diameter, the blade count + nor the airfoil, so they are arguments; ``section`` applies to every station. + + Raises ``ValueError`` naming the line of a malformed file. + """ + path = Path(path) + if not (math.isfinite(diameter_m) and diameter_m > 0.0): + raise ValueError(f"diameter_m must be positive, got {diameter_m}") + radius_m = 0.5 * diameter_m + + rows = [] + for number, raw in enumerate(path.read_text(errors="ignore").splitlines(), start=1): + tokens = raw.split() + if not tokens: + continue + if not rows and not _is_number(tokens[0]): + continue # the header line + if len(tokens) != 3: + raise ValueError(f"{path.name}:{number}: expected 'r/R c/R beta', got {len(tokens)} values") + values = [] + for token in tokens: + if not _is_number(token): + raise ValueError(f"{path.name}:{number}: {token!r} is not a number") + values.append(float(token)) + rows.append(values) + + try: + return BladeGeometry( + blade_count=blade_count, + radius_m=radius_m, + r_m=tuple(r * radius_m for r, _, _ in rows), + chord_m=tuple(c * radius_m for _, c, _ in rows), + blade_angle_rad=tuple(math.radians(beta) for _, _, beta in rows), + sections=(section,) * len(rows), + ) + except ValueError as error: + raise ValueError(f"{path.name}: {error}") from error + + +def _is_number(token: str) -> bool: + try: + return math.isfinite(float(token)) + except ValueError: + return False + + +def read_uiuc_performance( + diameter_m: float, + static: Optional[Union[str, Path]] = None, + forward: Sequence[Union[str, Path]] = (), +) -> TablePropeller: + """Build a ``TablePropeller`` from UIUC wind-tunnel measurements. + + ``static`` is a static test file (``*_static_*.txt``: ``RPM CT CP``), and + ``forward`` are forward-flight files (``J CT CP eta``), each measured at the + RPM that ends its name, such as ``apce_10x5_kt0823_6005.txt``. Each forward + file becomes an RPM band; the static file adds its thrust and power + coefficients, interpolated at that RPM, as the band's point at zero advance + ratio. Without forward files, each static RPM is a band with that one point. + + Raises ``ValueError`` naming the line of a malformed file, or a forward file + whose name does not end in its RPM. + """ + if not (math.isfinite(diameter_m) and diameter_m > 0.0): + raise ValueError(f"diameter_m must be positive, got {diameter_m}") + static_rows = _uiuc_rows(Path(static), 3) if static is not None else [] + static_rows.sort() + + data_by_rpm: Dict[float, List[PropellerDataPoint]] = {} + if not forward: + for rpm, ct, cp in static_rows: + data_by_rpm[rpm] = [PropellerDataPoint(j=0.0, ct=ct, cp=cp)] + for path in map(Path, forward): + match = _RPM_IN_NAME.search(path.stem) + if match is None: + raise ValueError(f"{path.name}: the file name does not end in the test RPM") + rpm = float(match.group(1)) + points = [] + if static_rows: + rpms, cts, cps = np.array(static_rows).T + points.append(PropellerDataPoint(j=0.0, ct=float(np.interp(rpm, rpms, cts)), cp=float(np.interp(rpm, rpms, cps)))) + for j, ct, cp, _ in sorted(_uiuc_rows(path, 4)): + if not points or j > points[-1].j: # J increasing, one point each + points.append(PropellerDataPoint(j=j, ct=ct, cp=cp)) + data_by_rpm[rpm] = points + if not data_by_rpm: + raise ValueError("no measurements: give a static file, forward files, or both") + return TablePropeller(diameter_m, data_by_rpm) + + +def _uiuc_rows(path: Path, columns: int) -> List[List[float]]: + """Numeric rows of a UIUC data file, after its header line.""" + rows = [] + for number, raw in enumerate(path.read_text(errors="ignore").splitlines(), start=1): + tokens = raw.split() + if not tokens or (not rows and not _is_number(tokens[0])): + continue + if len(tokens) != columns or not all(_is_number(t) for t in tokens): + raise ValueError(f"{path.name}:{number}: expected {columns} numbers") + rows.append([float(t) for t in tokens]) + return rows diff --git a/pythrust/propeller/__init__.py b/pythrust/propeller/__init__.py index cf65aa7..83ea550 100644 --- a/pythrust/propeller/__init__.py +++ b/pythrust/propeller/__init__.py @@ -1,7 +1,9 @@ """Propeller models.""" +from .airfoils import apc_airfoil_polars # noqa: F401 from .blade import BladeGeometry, BladeSection # noqa: F401 from .blade_element import BladeElementPropeller # noqa: F401 from .model import PropellerModel # noqa: F401 +from .polar import AirfoilPolar, BlendedPolar # noqa: F401 from .section import section_coefficients # noqa: F401 from .table import PropellerDataPoint, TablePropeller # noqa: F401 diff --git a/pythrust/propeller/airfoils.py b/pythrust/propeller/airfoils.py new file mode 100644 index 0000000..c0caf6e --- /dev/null +++ b/pythrust/propeller/airfoils.py @@ -0,0 +1,47 @@ +"""The airfoils APC names in its propeller geometry files.""" + +from __future__ import annotations + +from functools import lru_cache +from typing import Dict + +from .polar import AirfoilPolar + +# Kulfan (CST) parameters, 8 weights per side, fitted with setuav_neuralfoil.geometry to the +# coordinates in the UIUC Airfoil Coordinates Database (e63.dat, clarky.dat); NeuralFoil fits the +# same parameters to those coordinates itself. +_KULFAN = { + "E63": { + "upper_weights": (0.136310, 0.228128, 0.080441, 0.327311, 0.034266, 0.401917, 0.102548, 0.496576), + "lower_weights": (-0.019579, 0.111248, -0.023875, 0.215112, -0.013155, 0.266035, 0.082548, 0.362868), + "leading_edge_weight": -0.077701, + "TE_thickness": 0.0, + }, + "CLARK-Y": { + "upper_weights": (0.111461, 0.111148, 0.354036, 0.115449, 0.360527, 0.169056, 0.275045, 0.231965), + "lower_weights": (-0.210673, -0.242267, 0.085753, -0.183673, 0.050975, -0.102317, -0.014223, -0.044881), + "leading_edge_weight": 0.561800, + "TE_thickness": 0.001188, + }, +} + + +@lru_cache(maxsize=None) +def _apc_airfoil_polars(n_crit: float) -> Dict[str, AirfoilPolar]: + from setuav_neuralfoil import geometry + + shapes = {name: geometry.get_kulfan_coordinates(**parameters) for name, parameters in _KULFAN.items()} + shapes["APC12"] = geometry.naca("4412") # APC's note in its files: "APC12 airfoil is equivalent to NACA 4412". + return { + name: AirfoilPolar.from_neuralfoil(shape, n_crit=n_crit, name=name) + for name, shape in shapes.items() + } + + +def apc_airfoil_polars(n_crit: float = 7.0) -> Dict[str, AirfoilPolar]: + """Polars of the airfoils in APC geometry files: E63, APC12 (NACA 4412) and CLARK-Y. + + The result goes straight to ``read_apc_geometry(path, apc_airfoil_polars())``. The polars are + computed with NeuralFoil once per ``n_crit`` and cached. + """ + return dict(_apc_airfoil_polars(float(n_crit))) diff --git a/pythrust/propeller/bem.py b/pythrust/propeller/bem.py index ef281e1..68f0704 100644 --- a/pythrust/propeller/bem.py +++ b/pythrust/propeller/bem.py @@ -10,12 +10,13 @@ from __future__ import annotations from dataclasses import dataclass, fields -from typing import Sequence +from typing import Sequence, Union import numpy as np from numpy.typing import ArrayLike from .blade import BladeSection +from .polar import StationPolars from .section import section_coefficients _GRID_POINTS = 64 @@ -56,7 +57,7 @@ def solve_stations( r_m: ArrayLike, chord_m: ArrayLike, blade_angle_rad: ArrayLike, - sections: Sequence[BladeSection], + sections: Union[Sequence[BladeSection], StationPolars], airspeed_mps: float, omega_rad_s: float, rho: float, @@ -75,12 +76,22 @@ def solve_stations( where ``Gamma = W c CL / 2``. Where several roots exist, the one nearest the uninduced flow is taken. + + ``sections`` gives each station's lift and drag: one ``BladeSection`` per + station, or ``StationPolars``. """ r = np.asarray(r_m, dtype=float) chord = np.asarray(chord_m, dtype=float) beta = np.asarray(blade_angle_rad, dtype=float) - section = _stack(sections) blades = float(blade_count) + if isinstance(sections, StationPolars): + coefficients = sections.coefficients + else: + stacked = _stack(sections) + columns = _columns(stacked) + + def coefficients(alpha, reynolds, mach): + return section_coefficients(columns if np.ndim(alpha) == 2 else stacked, alpha, reynolds, mach) ua = np.full_like(r, float(airspeed_mps)) ut = float(omega_rad_s) * r @@ -94,14 +105,14 @@ def solve_stations( psi_high = psi_high - _EDGE * span @np.errstate(divide="ignore", invalid="ignore", over="ignore") - def flow(psi, rr, cc, bb, sec, uaa, utt, uu): + def flow(psi, rr, cc, bb, uaa, utt, uu): wa = 0.5 * (uaa + uu * np.sin(psi)) wt = 0.5 * (utt + uu * np.cos(psi)) w = np.hypot(wa, wt) alpha = bb - np.arctan2(wa, wt) reynolds = rho * w * cc / mu mach = w / speed_of_sound - cl, cd = section_coefficients(sec, alpha, reynolds, mach) + cl, cd = coefficients(alpha, reynolds, mach) wake_ratio = (rr / radius_m) * wa / wt tip = 0.5 * blades * (1.0 - rr / radius_m) / wake_ratio prandtl = (2.0 / np.pi) * np.arccos(np.exp(-tip)) @@ -114,9 +125,7 @@ def flow(psi, rr, cc, bb, sec, uaa, utt, uu): column = lambda a: a[:, None] # noqa: E731 grid = psi_low[:, None] + span[:, None] * (1.0 - 2.0 * _EDGE) * np.linspace(0.0, 1.0, _GRID_POINTS)[None, :] - residual = flow( - grid, column(r), column(chord), column(beta), _columns(section), column(ua), column(ut), column(u) - )[0] + residual = flow(grid, column(r), column(chord), column(beta), column(ua), column(ut), column(u))[0] change = np.signbit(residual[:, :-1]) != np.signbit(residual[:, 1:]) change &= np.isfinite(residual[:, :-1]) & np.isfinite(residual[:, 1:]) midpoints = 0.5 * (grid[:, :-1] + grid[:, 1:]) @@ -136,7 +145,7 @@ def flow(psi, rr, cc, bb, sec, uaa, utt, uu): if not active.any(): break c = np.where(active, (a * fb - b * fa) / (fb - fa), b) - fc = flow(c, r, chord, beta, section, ua, ut, u)[0] + fc = flow(c, r, chord, beta, ua, ut, u)[0] crossed = np.signbit(fc) != np.signbit(fb) a, fa = ( np.where(active & crossed, b, a), @@ -145,7 +154,7 @@ def flow(psi, rr, cc, bb, sec, uaa, utt, uu): b, fb = np.where(active, c, b), np.where(active, fc, fb) psi = np.where(converged, b, np.nan) - _, wa, wt, alpha, cl, cd, reynolds, mach, gamma = flow(psi, r, chord, beta, section, ua, ut, u) + _, wa, wt, alpha, cl, cd, reynolds, mach, gamma = flow(psi, r, chord, beta, ua, ut, u) return StationSolution( psi=psi, axial_velocity=wa, diff --git a/pythrust/propeller/blade.py b/pythrust/propeller/blade.py index fc00755..815dd16 100644 --- a/pythrust/propeller/blade.py +++ b/pythrust/propeller/blade.py @@ -3,7 +3,10 @@ from __future__ import annotations from dataclasses import dataclass -from typing import Tuple +from typing import TYPE_CHECKING, Tuple, Union + +if TYPE_CHECKING: + from .polar import AirfoilPolar, BlendedPolar @dataclass(frozen=True) @@ -39,7 +42,9 @@ class BladeGeometry: - chord_m: chord, m - blade_angle_rad: blade angle from the plane of rotation, rad - ``sections`` gives the airfoil parameters at each station. + ``sections`` gives the airfoil at each station: QPROP's ``BladeSection`` + parameters, or tabulated polars (``AirfoilPolar``, ``BlendedPolar``); a + blade uses one kind throughout. """ blade_count: int @@ -47,7 +52,7 @@ class BladeGeometry: r_m: Tuple[float, ...] chord_m: Tuple[float, ...] blade_angle_rad: Tuple[float, ...] - sections: Tuple[BladeSection, ...] + sections: Tuple[Union[BladeSection, "AirfoilPolar", "BlendedPolar"], ...] def __post_init__(self) -> None: count = len(self.r_m) diff --git a/pythrust/propeller/blade_element.py b/pythrust/propeller/blade_element.py index 6751c57..a8044ad 100644 --- a/pythrust/propeller/blade_element.py +++ b/pythrust/propeller/blade_element.py @@ -10,6 +10,7 @@ from .bem import solve_stations from .blade import BladeGeometry, BladeSection +from .polar import AirfoilPolar, BlendedPolar, StationPolars QPROP_MU = 1.78e-5 """QPROP's default air viscosity, kg/(m s).""" @@ -22,8 +23,10 @@ class BladeElementPropeller: The blade is analysed at ``stations`` points: the midpoints of equal intervals from the first to the last station of ``geometry``. Chord, blade - angle and section parameters there come from a cubic spline through the - geometry's stations, with zero third derivative in the end intervals. + angle and ``BladeSection`` parameters there come from a cubic spline through + the geometry's stations, with zero third derivative in the end intervals; + tabulated polars (``AirfoilPolar``, ``BlendedPolar``) are mixed linearly + between the two nearest stations instead. Thrust and torque sum each station's load over its interval (Drela, QPROP Formulation, section 3.2). @@ -50,7 +53,12 @@ def __init__( self._dr = np.diff(edges) self._chord = _spline(r, np.asarray(geometry.chord_m, dtype=float), self._r) self._beta = _spline(r, np.asarray(geometry.blade_angle_rad, dtype=float), self._r) - self._sections = _spline_sections(r, geometry.sections, self._r) + if all(isinstance(s, BladeSection) for s in geometry.sections): + self._sections = _spline_sections(r, geometry.sections, self._r) + elif all(isinstance(s, (AirfoilPolar, BlendedPolar)) for s in geometry.sections): + self._sections = StationPolars.interpolate(r, geometry.sections, self._r) + else: + raise TypeError("sections must be all BladeSection or all AirfoilPolar/BlendedPolar") @property def diameter_m(self) -> float: @@ -68,7 +76,10 @@ def max_advance_ratio(self) -> float: r75 = min(max(0.75 * radius, r[0]), r[-1]) beta = float(_spline(r, np.asarray(self.geometry.blade_angle_rad, dtype=float), np.array([r75]))[0]) section = self._sections[int(np.argmin(np.abs(self._r - r75)))] - phi = beta + section.cl0 / section.cl_alpha_per_rad + if isinstance(section, BladeSection): + phi = beta + section.cl0 / section.cl_alpha_per_rad + else: + phi = beta - section.zero_lift_alpha_rad if phi <= 0.0: return 0.0 if phi >= 0.5 * math.pi: diff --git a/pythrust/propeller/polar.py b/pythrust/propeller/polar.py new file mode 100644 index 0000000..bd9170a --- /dev/null +++ b/pythrust/propeller/polar.py @@ -0,0 +1,224 @@ +"""Airfoil sections from tabulated lift and drag polars, computed with NeuralFoil.""" + +from __future__ import annotations + +from dataclasses import dataclass +from os import PathLike +from typing import List, Optional, Sequence, Tuple, Union + +import numpy as np +from numpy.typing import ArrayLike + +AirfoilShape = Union[str, PathLike, np.ndarray] +"""A NACA 4- or 5-digit designation, the path of a .dat file, or (N, 2) coordinates.""" + +NEURALFOIL_ALPHA_DEG = np.arange(-20.0, 25.0 + 1e-9, 0.5) +"""Angles of attack evaluated with NeuralFoil, deg; its confidence falls quickly outside them.""" +FLAT_PLATE_ALPHA_DEG = np.concatenate([np.arange(-180.0, -35.0 + 1e-9, 5.0), np.arange(40.0, 180.0 + 1e-9, 5.0)]) +"""Angles of attack given flat-plate values, deg; the table interpolates linearly in between.""" +REYNOLDS = np.logspace(4.0, 6.0, 13) +"""Reynolds numbers of the table; outside them the nearest is used.""" + + +@dataclass(frozen=True, eq=False) +class AirfoilPolar: + """Lift and drag of an airfoil section, tabulated over angle of attack and Reynolds number. + + ``cl`` and ``cd`` have shape ``(len(alpha_rad), len(reynolds))``. Coefficients between the + table's points are interpolated linearly in the angle of attack and in ``log(Re)``. + ``alpha_rad`` is measured from the chord line, from the leading edge to the trailing edge. + """ + + name: str + alpha_rad: np.ndarray + reynolds: np.ndarray + cl: np.ndarray + cd: np.ndarray + + def __post_init__(self) -> None: + shape = (len(self.alpha_rad), len(self.reynolds)) + if np.shape(self.cl) != shape or np.shape(self.cd) != shape: + raise ValueError(f"cl and cd must have shape {shape}") + if np.any(np.diff(self.alpha_rad) <= 0) or np.any(np.diff(self.reynolds) <= 0): + raise ValueError("alpha_rad and reynolds must increase") + # Lookup arrays: both coefficients interpolated together, Reynolds number on a log scale. + object.__setattr__(self, "_table", np.stack([self.cl, self.cd], axis=-1)) + object.__setattr__(self, "_log_reynolds", np.log(self.reynolds)) + + @classmethod + def from_neuralfoil( + cls, + airfoil: AirfoilShape, + n_crit: float = 7.0, + name: Optional[str] = None, + model_size: str = "xlarge", + ) -> "AirfoilPolar": + """Tabulate an airfoil's polars with NeuralFoil (``setuav-neuralfoil``). + + NeuralFoil gives the coefficients from -20 to 25 degrees, at Reynolds numbers from 1e4 + to 1e6. Beyond -35 and 40 degrees the section is taken as a flat plate, + ``CL = sin(2 alpha)`` and ``CD = 2 sin(alpha)^2``; in between the table interpolates. + + ``n_crit`` is the transition amplification factor: 9 for a quiet wind tunnel, lower + for a turbulent free stream. The default, 7, fits UIUC's measurements of 75 APC + propellers best, with 5 nearly as well. ``model_size`` selects NeuralFoil's network. + """ + import setuav_neuralfoil as nf + + alpha_deg, re = np.meshgrid(NEURALFOIL_ALPHA_DEG, REYNOLDS, indexing="ij") + aero = nf.get_aero_from_coordinates( + _coordinates(airfoil), alpha=alpha_deg.ravel(), Re=re.ravel(), n_crit=n_crit, model_size=model_size + ) + shape = alpha_deg.shape + + plate = np.radians(FLAT_PLATE_ALPHA_DEG) + alpha = np.concatenate([plate[plate < 0], np.radians(NEURALFOIL_ALPHA_DEG), plate[plate > 0]]) + n_low = int(np.sum(plate < 0)) + cl = np.empty((alpha.size, REYNOLDS.size)) + cd = np.empty_like(cl) + cl[:] = np.sin(2.0 * alpha)[:, None] + cd[:] = (2.0 * np.sin(alpha) ** 2)[:, None] + rows = slice(n_low, n_low + NEURALFOIL_ALPHA_DEG.size) + cl[rows] = np.reshape(aero["CL"], shape) + cd[rows] = np.reshape(aero["CD"], shape) + + if name is None: + name = str(airfoil) if isinstance(airfoil, (str, PathLike)) else "airfoil" + return cls(name=name, alpha_rad=alpha, reynolds=REYNOLDS.copy(), cl=cl, cd=cd) + + @property + def zero_lift_alpha_rad(self) -> float: + """The lowest angle of zero lift over the table's Reynolds numbers, between -20 and 25 degrees. + + At each Reynolds number it takes the zero crossing of rising lift nearest zero angle, past + any wiggle of the lift curve at negative angles. + """ + inside = (self.alpha_rad >= np.radians(-20.0)) & (self.alpha_rad <= np.radians(25.0)) + alpha = self.alpha_rad[inside] + angles = [] + for cl in self.cl[inside].T: + rising = np.nonzero((cl[:-1] <= 0.0) & (cl[1:] > 0.0))[0] + crossings = alpha[rising] - cl[rising] * (alpha[rising + 1] - alpha[rising]) / (cl[rising + 1] - cl[rising]) + if crossings.size: + angles.append(crossings[np.argmin(np.abs(crossings))]) + if not angles: + raise ValueError(f"{self.name}: lift does not cross zero between -20 and 25 degrees") + return float(min(angles)) + + def coefficients(self, alpha_rad: ArrayLike, reynolds: ArrayLike, mach: ArrayLike) -> Tuple[np.ndarray, np.ndarray]: + """Lift and drag coefficients; the lift includes the Prandtl-Glauert factor ``1/sqrt(1 - M^2)``.""" + alpha = np.mod(np.asarray(alpha_rad, dtype=float) + np.pi, 2.0 * np.pi) - np.pi + log_re = np.log(np.clip(np.asarray(reynolds, dtype=float), self.reynolds[0], self.reynolds[-1])) + both = _bilinear(self.alpha_rad, self._log_reynolds, self._table, alpha, log_re) + return both[..., 0] / np.sqrt(1.0 - np.asarray(mach, dtype=float) ** 2), both[..., 1] + + +@dataclass(frozen=True) +class BlendedPolar: + """A section between two airfoils: their coefficients mixed, ``weight`` of ``second``.""" + + first: AirfoilPolar + second: AirfoilPolar + weight: float + + @property + def zero_lift_alpha_rad(self) -> float: + return min(self.first.zero_lift_alpha_rad, self.second.zero_lift_alpha_rad) + + def coefficients(self, alpha_rad: ArrayLike, reynolds: ArrayLike, mach: ArrayLike) -> Tuple[np.ndarray, np.ndarray]: + cl1, cd1 = self.first.coefficients(alpha_rad, reynolds, mach) + cl2, cd2 = self.second.coefficients(alpha_rad, reynolds, mach) + w = self.weight + return (1.0 - w) * cl1 + w * cl2, (1.0 - w) * cd1 + w * cd2 + + +PolarSection = Union[AirfoilPolar, BlendedPolar] + + +class StationPolars: + """The sections of a blade's analysis stations, each a weighted mix of a few polars. + + ``weights[k, j]`` is the share of ``polars[j]`` at station ``k``; each row sums to one. + """ + + def __init__(self, polars: Sequence[AirfoilPolar], weights: np.ndarray) -> None: + self.polars = list(polars) + self.weights = np.asarray(weights, dtype=float) + + @classmethod + def interpolate(cls, r: np.ndarray, sections: Sequence[PolarSection], at: np.ndarray) -> "StationPolars": + """Sections at radii ``at``, mixed linearly between the sections given at radii ``r``.""" + polars: List[AirfoilPolar] = [] + for section in sections: + for polar, _ in _components(section): + if not any(polar is known for known in polars): + polars.append(polar) + + weights = np.zeros((len(at), len(polars))) + i = np.clip(np.searchsorted(r, at) - 1, 0, len(r) - 2) + t = np.clip((at - r[i]) / (r[i + 1] - r[i]), 0.0, 1.0) + for k in range(len(at)): + for section, share in ((sections[i[k]], 1.0 - t[k]), (sections[i[k] + 1], t[k])): + for polar, part in _components(section): + j = next(j for j, known in enumerate(polars) if known is polar) + weights[k, j] += share * part + return cls(polars, weights) + + def __getitem__(self, k: int) -> "StationPolars": + return StationPolars(self.polars, self.weights[k : k + 1]) + + @property + def zero_lift_alpha_rad(self) -> float: + """The lowest zero-lift angle among the polars a station uses; for a single station.""" + return min(p.zero_lift_alpha_rad for p, w in zip(self.polars, self.weights[0]) if w > 0.0) + + def coefficients(self, alpha_rad: ArrayLike, reynolds: ArrayLike, mach: ArrayLike) -> Tuple[np.ndarray, np.ndarray]: + """Lift and drag coefficients; the first axis of the arrays runs over the stations.""" + alpha, reynolds, mach = np.broadcast_arrays( + np.asarray(alpha_rad, dtype=float), np.asarray(reynolds, dtype=float), np.asarray(mach, dtype=float) + ) + cl = np.zeros(alpha.shape) + cd = np.zeros(alpha.shape) + for j, polar in enumerate(self.polars): + rows = self.weights[:, j] > 0.0 + if not rows.any(): + continue + share = self.weights[rows, j].reshape((-1,) + (1,) * (alpha.ndim - 1)) + cl_j, cd_j = polar.coefficients(alpha[rows], reynolds[rows], mach[rows]) + cl[rows] += share * cl_j + cd[rows] += share * cd_j + return cl, cd + + +def _components(section: PolarSection): + if isinstance(section, BlendedPolar): + return ((section.first, 1.0 - section.weight), (section.second, section.weight)) + return ((section, 1.0),) + + +def _coordinates(airfoil: AirfoilShape) -> np.ndarray: + from setuav_neuralfoil import geometry + + if isinstance(airfoil, np.ndarray): + return airfoil + if isinstance(airfoil, str): + designation = airfoil.lower().replace("naca", "").replace(" ", "").replace("-", "") + if designation.isdigit() and len(designation) in (4, 5): + return geometry.naca(airfoil) + return geometry.read_dat(airfoil) + + +def _bilinear(x: np.ndarray, y: np.ndarray, table: np.ndarray, at_x: np.ndarray, at_y: np.ndarray) -> np.ndarray: + """Interpolate ``table[i, j, ...]`` given at ``(x[i], y[j])``; ``at_x`` within ``x``, ``at_y`` within ``y``. + + The result has the shape of ``at_x`` and ``at_y`` broadcast, followed by the table's trailing axes. + """ + at_x, at_y = np.broadcast_arrays(at_x, at_y) + i = np.minimum(np.maximum(np.searchsorted(x, at_x) - 1, 0), x.size - 2) + j = np.minimum(np.maximum(np.searchsorted(y, at_y) - 1, 0), y.size - 2) + extra = (...,) + (None,) * (table.ndim - 2) + tx = ((at_x - x[i]) / (x[i + 1] - x[i]))[extra] + ty = ((at_y - y[j]) / (y[j + 1] - y[j]))[extra] + low = table[i, j] + tx * (table[i + 1, j] - table[i, j]) + high = table[i, j + 1] + tx * (table[i + 1, j + 1] - table[i, j + 1]) + return low + ty * (high - low) diff --git a/requirements.txt b/requirements.txt index 8d6589d..3de42ff 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1,6 +1,7 @@ # Core Dependencies numpy>=1.20 scipy>=1.7 +setuav-neuralfoil>=0.3.3.1 # Optional Dependencies (For visualization and plotting) matplotlib>=3.4 diff --git a/tests/data/10x5E-PERF.PE0 b/tests/data/10x5E-PERF.PE0 new file mode 100644 index 0000000..69e903c --- /dev/null +++ b/tests/data/10x5E-PERF.PE0 @@ -0,0 +1,124 @@ +10x5E (10x5E.dat) +v2025-1001 +Simulation Date: 02/24/2026 + + + ----- AIRFOIL SUMMARY DATA ----- + + DEFINITIONS: + THE QUOTED PITCH REFLECTS, IN GENERAL, ANGULAR MEASURE + AS DEFINED WITH A FLAT BOTTOM SURFACE. THIS WILL + AGREE WITH A PRATHER GAGE MEASUREMENT OVER MOST OF THE + EFFECTIVE PORTION OF THE BLADE. (NOTE: QUOTED=INPUT) + THE LE-TE MEASURE IS DEFINED IN TERMS OF LEADING EDGE + AND TRAILING EDGE (MOLD) PARTING LINE DATUMS. + THE PRATHER MEASURE REFLECTS THE MOST LIKELY PITCH + INTERPRETATION FROM A PITCH MEASUREMENT DEVICE THAT + RESTS AGAINST THE LOWER SURFACE. + SWEEP & RAKE ARE DEFINED WITH (MOLD) LE PARTING LINE. + ZHIGH IS HIGHEST ELEVATION ON TOP SURFACE. + TWIST IS DEFINED WITH (MOLD) LE AND TE PARTING LINE DATUMS. + CHORD IS THE LENGTH BETWEEN (MOLD) LE AND TE PARTING LINES. + CGY IS MASS OFFSET, FORE-AFT. + CGZ IS MASS OFFSET, ELEVATION. + + + STATION CHORD PITCH PITCH PITCH SWEEP(Y) RAKE(Z) THICKNESS TWIST MAX-THICK CROSS-SECTION ZHIGH CGY CGZ + (IN) (IN) (QUOTED) (LE-TE) (PRATHER) (IN) (IN) RATIO (DEG) (IN) (IN**2) (IN) (IN) (IN) + + 0.0000 0.8000 2.1503 0.0000 0.0000 0.4000 0.0000 0.4000 0.0000 0.3200 0.0000 0.0450 0.0000 0.0000 + 0.0950 0.7665 2.4719 0.0089 -0.4120 0.3948 0.0061 0.3974 0.8509 0.3046 0.2060 0.0500 0.0068 -0.1003 + 0.1900 0.7265 2.7742 0.0700 -0.8065 0.3890 0.0228 0.3896 3.3567 0.2830 0.1994 0.0636 0.0218 -0.0919 + 0.2850 0.6867 3.0572 0.2347 -1.1013 0.3833 0.0470 0.3765 7.4669 0.2586 0.1885 0.0829 0.0390 -0.0787 + 0.3800 0.6544 3.3210 0.5515 -1.1494 0.3783 0.0761 0.3583 13.0073 0.2344 0.1695 0.1055 0.0573 -0.0614 + 0.4750 0.6358 3.5656 1.0558 -0.8383 0.3744 0.1073 0.3348 19.4815 0.2129 0.1471 0.1300 0.0750 -0.0416 + 0.5700 0.6351 3.7909 1.7508 -0.1077 0.3723 0.1380 0.3063 26.0526 0.1945 0.1252 0.1550 0.0906 -0.0210 + 0.6650 0.6527 3.9970 2.5840 0.9980 0.3723 0.1657 0.2780 31.7340 0.1815 0.1064 0.1784 0.1026 -0.0014 + 0.7600 0.6863 4.1838 3.4326 2.2773 0.3751 0.1877 0.2527 35.7096 0.1734 0.0922 0.1978 0.1099 0.0154 + 0.8550 0.7326 4.3514 4.1242 3.3172 0.3811 0.2015 0.2300 37.5136 0.1685 0.0841 0.2106 0.1111 0.0265 + 0.9500 0.7898 4.4998 4.4978 3.8788 0.3908 0.2043 0.2100 36.9991 0.1658 0.0839 0.2139 0.1035 0.0277 + 1.0467 0.8498 4.6311 4.6311 4.0775 0.4026 0.1991 0.1920 35.1520 0.1631 0.0885 0.2102 0.0897 0.0211 + 1.1728 0.9092 4.7722 4.7722 4.3026 0.4158 0.1909 0.1720 32.9287 0.1564 0.0906 0.2038 0.0756 0.0153 + 1.3005 0.9501 4.8807 4.8807 4.4931 0.4268 0.1812 0.1553 30.8497 0.1476 0.0895 0.1956 0.0651 0.0112 + 1.4283 0.9819 4.9544 4.9544 4.6389 0.4354 0.1698 0.1420 28.9023 0.1394 0.0879 0.1858 0.0550 0.0067 + 1.5560 1.0065 4.9934 4.9934 4.7367 0.4418 0.1566 0.1315 27.0549 0.1323 0.0861 0.1746 0.0458 0.0017 + 1.6838 1.0241 5.0000 5.0000 4.7878 0.4460 0.1418 0.1235 25.2958 0.1265 0.0844 0.1620 0.0370 -0.0042 + 1.8116 1.0352 5.0000 5.0000 4.8180 0.4481 0.1257 0.1177 23.7148 0.1218 0.0831 0.1482 0.0290 -0.0114 + 1.9393 1.0402 5.0000 5.0000 4.8354 0.4482 0.1085 0.1135 22.3103 0.1181 0.0820 0.1333 0.0219 -0.0202 + 2.0671 1.0394 5.0000 5.0000 4.8417 0.4464 0.0903 0.1108 21.0556 0.1151 0.0811 0.1174 0.0155 -0.0304 + 2.1948 1.0332 5.0000 5.0000 4.8393 0.4428 0.0714 0.1090 19.9290 0.1126 0.0802 0.1006 0.0098 -0.0417 + 2.3226 1.0220 5.0000 5.0000 4.8317 0.4375 0.0519 0.1078 18.9127 0.1101 0.0789 0.0831 0.0049 -0.0538 + 2.4503 1.0063 5.0000 5.0000 4.8189 0.4307 0.0322 0.1067 17.9917 0.1074 0.0771 0.0649 0.0006 -0.0666 + 2.5781 0.9863 5.0000 5.0000 4.8031 0.4223 0.0123 0.1057 17.1537 0.1043 0.0746 0.0462 -0.0029 -0.0798 + 2.7059 0.9625 5.0000 5.0000 4.7865 0.4124 -0.0077 0.1048 16.3882 0.1009 0.0716 0.0271 -0.0058 -0.0933 + 2.8336 0.9353 5.0000 5.0000 4.7693 0.4013 -0.0276 0.1040 15.6865 0.0972 0.0681 0.0076 -0.0080 -0.1070 + 2.9614 0.9051 5.0000 5.0000 4.7522 0.3889 -0.0473 0.1032 15.0411 0.0934 0.0641 -0.0120 -0.0097 -0.1207 + 3.0891 0.8722 5.0000 5.0000 4.7356 0.3754 -0.0668 0.1025 14.4456 0.0894 0.0598 -0.0316 -0.0109 -0.1344 + 3.2169 0.8370 5.0000 5.0000 4.7201 0.3608 -0.0860 0.1018 13.8945 0.0852 0.0553 -0.0512 -0.0118 -0.1479 + 3.3447 0.8000 5.0000 5.0000 4.7059 0.3453 -0.1047 0.1012 13.3832 0.0810 0.0506 -0.0706 -0.0123 -0.1613 + 3.4724 0.7615 5.0000 5.0000 4.6938 0.3289 -0.1229 0.1007 12.9076 0.0767 0.0459 -0.0897 -0.0126 -0.1743 + 3.6002 0.7219 5.0000 5.0000 4.6841 0.3118 -0.1405 0.1003 12.4641 0.0724 0.0413 -0.1084 -0.0128 -0.1870 + 3.7279 0.6817 5.0000 5.0000 4.6769 0.2940 -0.1575 0.0999 12.0497 0.0681 0.0367 -0.1266 -0.0132 -0.1993 + 3.8557 0.6411 5.0000 5.0000 4.6703 0.2756 -0.1737 0.0996 11.6615 0.0639 0.0324 -0.1442 -0.0138 -0.2111 + 3.9834 0.6005 5.0000 5.0000 4.6643 0.2567 -0.1891 0.0994 11.2973 0.0597 0.0285 -0.1609 -0.0149 -0.2225 + 4.1112 0.5605 5.0000 5.0000 4.6590 0.2374 -0.2035 0.0992 10.9548 0.0556 0.0248 -0.1768 -0.0166 -0.2333 + 4.2390 0.5213 5.0000 5.0000 4.6542 0.2179 -0.2169 0.0991 10.6323 0.0517 0.0215 -0.1917 -0.0188 -0.2434 + 4.3667 0.4833 5.0000 5.0000 4.6420 0.1981 -0.2292 0.0991 10.3280 0.0479 0.0185 -0.2057 -0.0218 -0.2529 + 4.4945 0.4470 5.0000 5.0000 4.6095 0.1782 -0.2403 0.0991 10.0405 0.0443 0.0158 -0.2190 -0.0255 -0.2621 + 4.6222 0.4127 5.0000 5.0000 4.5520 0.1583 -0.2502 0.0992 9.7684 0.0410 0.0135 -0.2312 -0.0300 -0.2706 + 4.7447 0.3820 5.0000 5.0000 4.4659 0.1393 -0.2582 0.0994 9.5210 0.0380 0.0116 -0.2417 -0.0353 -0.2779 + 4.7753 0.3725 5.0000 5.0000 4.3830 0.1324 -0.2604 0.0995 9.4611 0.0370 0.0111 -0.2446 -0.0380 -0.2798 + 4.8005 0.3618 5.0000 5.0000 4.3055 0.1237 -0.2627 0.0995 9.4123 0.0360 0.0104 -0.2476 -0.0418 -0.2817 + 4.8258 0.3481 5.0000 5.0000 4.2323 0.1121 -0.2653 0.0995 9.3639 0.0347 0.0097 -0.2510 -0.0473 -0.2839 + 4.8510 0.3311 5.0000 5.0000 4.1651 0.0969 -0.2685 0.0996 9.3160 0.0330 0.0088 -0.2551 -0.0548 -0.2864 + 4.8763 0.3099 5.0000 5.0000 4.1039 0.0775 -0.2722 0.0997 9.2686 0.0309 0.0077 -0.2600 -0.0646 -0.2893 + 4.9015 0.2831 5.0000 5.0000 4.0556 0.0526 -0.2768 0.0997 9.2217 0.0282 0.0064 -0.2659 -0.0775 -0.2927 + 4.9268 0.2478 5.0000 5.0000 4.0378 0.0191 -0.2827 0.0998 9.1752 0.0247 0.0049 -0.2733 -0.0951 -0.2968 + 4.9520 0.1951 5.0000 5.0000 4.1194 -0.0317 -0.2912 0.0998 9.1292 0.0195 0.0031 -0.2840 -0.1222 -0.3026 + 4.9773 0.1031 5.0000 5.0000 4.8007 -0.1214 -0.3058 0.0999 9.0837 0.0103 0.0009 -0.3021 -0.1705 -0.3122 + 5.0000 0.0163 5.0000 5.0025 5.0025 -0.2063 -0.3195 0.1000 9.0475 0.0016 0.0000 -0.3195 0.0000 0.0000 + + + RADIUS: 5.00 PROPELLER RADIUS (IN) + HUBRAD: 0.40 HUB RADIUS (IN) + HUBTRA: 0.95 HUB TRANSITION (IN) + BLADES: 2 NUMBER OF BLADES + + + ----- INERTIA AND AREA DATA ----- + + TOTAL WEIGHT (LB) = 0.044773 + TOTAL WEIGHT (Kg) = 0.020305 + TOTAL VOLUME (IN**3) = 0.729408 + TOTAL PROJECTED AREA (IN**2) = 7.1841 + MOMENT OF INERTIA (SNAIL-IN**2) = 0.000490 + MOMENT OF INERTIA (Kg-M**2) = 0.000055 + STATIC MOMENT, ONE SIDE (IN-LB) = 0.036633 + + SANITY CHECK DATA ARE BELOW + DENSITY (SPECIFIC GRAVITY, INPUT FILE) = 1.700 + DENSITY (INPUT FILE, LB/IN**3) = 0.6138E-01 + AVERAGE DENSITY (FROM WT & VOL ABOVE, LB/IN**3) = 0.6138E-01 + + ACTIVITY FACTOR = 91.860 + INNER LIMIT (NORMALIZED BY RADIUS) = 0.080 + + + + ----- NATURAL FREQUENCY DATA ----- + + LOWEST NATURAL BENDING FREQUENCY (IN TERMS OF RPM) = 14545.21 + + BASED ON MODULUS (MILLION) = 2.70 + AND, MATERIAL DENSITY (S.G.) = 1.70 + + + ----- AIRFOIL SECTIONS ----- + + AIRFOIL1: 0.95, E63 (Transition Start, Airfoil 1) + AIRFOIL2: 3.66, APC12 (Transition End, Airfoil 2) + + AIRFOILS ARE SCALED BASED ON THICKNESS RATIO IN TABLE ABOVE. + + NOTE: APC12 airfoil is equivalent to NACA 4412 + diff --git a/tests/data/apce_10x5_geom.txt b/tests/data/apce_10x5_geom.txt new file mode 100644 index 0000000..ee126c9 --- /dev/null +++ b/tests/data/apce_10x5_geom.txt @@ -0,0 +1,19 @@ +r/R c/R beta +0.15 0.130 32.76 +0.20 0.149 37.19 +0.25 0.173 33.54 +0.30 0.189 29.25 +0.35 0.197 25.64 +0.40 0.201 22.54 +0.45 0.200 20.27 +0.50 0.194 18.46 +0.55 0.186 17.05 +0.60 0.174 15.97 +0.65 0.160 14.87 +0.70 0.145 14.09 +0.75 0.128 13.39 +0.80 0.112 12.84 +0.85 0.096 12.25 +0.90 0.081 11.37 +0.95 0.061 10.19 +1.00 0.041 8.99 diff --git a/tests/data/apce_10x5_kt0823_6005.txt b/tests/data/apce_10x5_kt0823_6005.txt new file mode 100644 index 0000000..bf64dcf --- /dev/null +++ b/tests/data/apce_10x5_kt0823_6005.txt @@ -0,0 +1,18 @@ +J CT CP eta +0.093 0.0942 0.0385 0.227 +0.121 0.0922 0.0388 0.288 +0.146 0.0910 0.0392 0.339 +0.170 0.0892 0.0394 0.384 +0.194 0.0868 0.0396 0.425 +0.218 0.0843 0.0398 0.462 +0.241 0.0814 0.0397 0.495 +0.266 0.0778 0.0395 0.525 +0.291 0.0732 0.0387 0.551 +0.314 0.0679 0.0373 0.572 +0.335 0.0633 0.0360 0.589 +0.357 0.0578 0.0342 0.603 +0.380 0.0527 0.0324 0.619 +0.406 0.0474 0.0304 0.633 +0.428 0.0433 0.0289 0.643 +0.452 0.0392 0.0272 0.652 +0.484 0.0338 0.0249 0.658 diff --git a/tests/data/apce_10x5_static_pg0819.txt b/tests/data/apce_10x5_static_pg0819.txt new file mode 100644 index 0000000..f197de4 --- /dev/null +++ b/tests/data/apce_10x5_static_pg0819.txt @@ -0,0 +1,17 @@ +RPM CT CP +2508 0.0914 0.0374 +2795 0.0932 0.0374 +3093 0.0937 0.0371 +3344 0.0937 0.0368 +3630 0.0940 0.0366 +3919 0.0943 0.0366 +4176 0.0950 0.0367 +4446 0.0956 0.0368 +4743 0.0959 0.0367 +5025 0.0964 0.0369 +5314 0.0969 0.0370 +5596 0.0975 0.0373 +5869 0.0977 0.0373 +6146 0.0983 0.0374 +6434 0.0987 0.0377 +6708 0.0994 0.0379 diff --git a/tests/test_io_apc.py b/tests/test_io_apc.py index dd727e1..5df5066 100644 --- a/tests/test_io_apc.py +++ b/tests/test_io_apc.py @@ -1,10 +1,29 @@ +import math +from dataclasses import replace from pathlib import Path import pytest -from pythrust.io import read_apc +from pythrust.io import read_apc, read_apc_geometry +from pythrust.propeller import BladeElementPropeller, BladeGeometry, BladeSection APC_FILE = Path(__file__).parent / "data" / "PER3_13x65E.dat" +GEOMETRY_FILE = Path(__file__).parent / "data" / "10x5E-PERF.PE0" +INCH = 0.0254 + +E63 = BladeSection( + cl0=0.50, + cl_alpha_per_rad=5.8, + cl_min=-0.3, + cl_max=1.2, + cd0=0.028, + cd2_upper=0.050, + cd2_lower=0.020, + cl_at_cd0=0.5, + reynolds_ref=70000.0, + reynolds_exp=-0.7, +) +APC12 = replace(E63, cl0=0.30, cd0=0.010) def test_read_apc_file(): @@ -59,3 +78,73 @@ def test_read_apc_rejects_a_file_without_data(tmp_path): with pytest.raises(ValueError, match="no performance data"): read_apc(path) + + +def test_read_apc_geometry_in_si_units(): + blade = read_apc_geometry(GEOMETRY_FILE, E63) + + assert isinstance(blade, BladeGeometry) + assert blade.blade_count == 2 + assert blade.radius_m == pytest.approx(5.0 * INCH) + assert len(blade.r_m) == 41 # the 53 stations from the hub transition at 0.95 in + assert (blade.r_m[0], blade.chord_m[0], blade.blade_angle_rad[0]) == pytest.approx( + (0.95 * INCH, 0.7898 * INCH, math.radians(36.9991)) + ) + assert (blade.r_m[-1], blade.chord_m[-1], blade.blade_angle_rad[-1]) == pytest.approx( + (5.0 * INCH, 0.0163 * INCH, math.radians(9.0475)) + ) + assert blade.sections == (E63,) * 41 + + +def test_read_apc_geometry_blends_the_two_airfoils_across_the_transition(): + """AIRFOIL1 E63 at 0.95 in, AIRFOIL2 APC12 from 3.66 in.""" + blade = read_apc_geometry(GEOMETRY_FILE, {"E63": E63, "APC12": APC12}) + + r_in = [r / INCH for r in blade.r_m] + for r, section in zip(r_in, blade.sections): + weight = min(max((r - 0.95) / (3.66 - 0.95), 0.0), 1.0) + assert section.cl0 == pytest.approx(0.50 + (0.30 - 0.50) * weight) + assert section.cd0 == pytest.approx(0.028 + (0.010 - 0.028) * weight) + assert section.cl_alpha_per_rad == pytest.approx(5.8) + assert blade.sections[0] == E63 + assert blade.sections[-1] == APC12 + + +def test_read_apc_geometry_names_a_missing_airfoil(): + with pytest.raises(KeyError, match="no section for airfoil 'APC12'"): + read_apc_geometry(GEOMETRY_FILE, {"E63": E63}) + + +@pytest.mark.parametrize( + "edit, message", + [ + (lambda text: text.replace(" BLADES:", " BLADE:"), "no BLADES line"), + (lambda text: text.replace(" RADIUS:", " RADIUS ").replace(" HUBTRA:", " HUBTRA "), "no RADIUS, HUBTRA line"), + (lambda text: text.replace(" AIRFOIL2:", " AIRFOIL :"), "expected AIRFOIL1 and AIRFOIL2 lines"), + (lambda text: text.replace("HUBTRA: 0.95", "HUBTRA: 4.99"), "a blade needs at least two stations"), + ], +) +def test_read_apc_geometry_rejects_a_malformed_file(tmp_path, edit, message): + path = tmp_path / "prop.PE0" + path.write_text(edit(GEOMETRY_FILE.read_text())) + + with pytest.raises(ValueError, match=f"prop.PE0: {message}"): + read_apc_geometry(path, {"E63": E63, "APC12": APC12}) + + +def test_apc_geometry_gives_a_working_propeller_model(): + propeller = BladeElementPropeller(read_apc_geometry(GEOMETRY_FILE, E63)) + thrust, torque = propeller.thrust_torque(1.225, 0.0, 6000.0) + + assert propeller.diameter_m == pytest.approx(10.0 * INCH) + assert thrust > 0.0 and torque > 0.0 + + +def test_read_apc_geometry_tip_radius_is_at_least_the_last_station(tmp_path): + """RADIUS is rounded to two decimals: 13x8E gives 6.47 in, its last station 6.475 in.""" + path = tmp_path / "prop.PE0" + path.write_text(GEOMETRY_FILE.read_text().replace(" RADIUS: 5.00", " RADIUS: 4.99")) + + blade = read_apc_geometry(path, E63) + + assert blade.radius_m == pytest.approx(5.0 * INCH) diff --git a/tests/test_io_uiuc.py b/tests/test_io_uiuc.py new file mode 100644 index 0000000..87f3709 --- /dev/null +++ b/tests/test_io_uiuc.py @@ -0,0 +1,157 @@ +import math +from pathlib import Path + +import pytest + +from pythrust.battery import FixedVoltageBattery +from pythrust.io import read_uiuc_geometry, read_uiuc_performance +from pythrust.motor import MotorSpec +from pythrust.propeller import BladeElementPropeller, BladeGeometry, BladeSection +from pythrust.propulsion import PropulsionSolver, SystemSpec + +DATA = Path(__file__).parent / "data" +RHO = 1.225 +DIAMETER = 10 * 0.0254 + +# The example section of the QPROP user guide; UIUC files give no airfoil data. +SECTION = BladeSection( + cl0=0.50, + cl_alpha_per_rad=5.8, + cl_min=-0.3, + cl_max=1.2, + cd0=0.028, + cd2_upper=0.050, + cd2_lower=0.020, + cl_at_cd0=0.5, + reynolds_ref=70000.0, + reynolds_exp=-0.7, +) + +GEOMETRY = "r/R c/R beta\n0.15 0.130 32.76\n0.60 0.174 15.97\n1.00 0.041 8.99\n" + + +def _write(tmp_path, text, newline="\n"): + path = tmp_path / "prop_geom.txt" + path.write_bytes(text.replace("\n", newline).encode()) + return path + + +def test_reads_geometry_in_si_units(): + blade = read_uiuc_geometry(DATA / "apce_10x5_geom.txt", DIAMETER, SECTION) + + radius = 0.5 * DIAMETER + assert isinstance(blade, BladeGeometry) + assert blade.blade_count == 2 + assert blade.radius_m == pytest.approx(radius) + assert len(blade.r_m) == 18 + assert (blade.r_m[0], blade.chord_m[0], blade.blade_angle_rad[0]) == pytest.approx( + (0.15 * radius, 0.130 * radius, math.radians(32.76)) + ) + assert (blade.r_m[-1], blade.chord_m[-1], blade.blade_angle_rad[-1]) == pytest.approx( + (radius, 0.041 * radius, math.radians(8.99)) + ) + assert blade.sections == (SECTION,) * 18 + + +@pytest.mark.parametrize("newline", ["\n", "\r\n"]) +def test_reads_either_line_ending(tmp_path, newline): + blade = read_uiuc_geometry(_write(tmp_path, GEOMETRY + "\n", newline), 0.2, SECTION, blade_count=3) + + assert blade.blade_count == 3 + assert blade.r_m == pytest.approx([0.015, 0.06, 0.1]) + + +@pytest.mark.parametrize( + "text, message", + [ + (GEOMETRY.replace("0.174", "abc"), r"prop_geom\.txt:3: 'abc' is not a number"), + (GEOMETRY.replace(" 15.97", ""), r"prop_geom\.txt:3: expected 'r/R c/R beta', got 2 values"), + (GEOMETRY.replace("0.60", "0.10"), r"prop_geom\.txt: station radii must increase"), + ("r/R c/R beta\n0.15 0.130 32.76\n", r"prop_geom\.txt: a blade needs at least two stations"), + ], +) +def test_rejects_a_malformed_file(tmp_path, text, message): + with pytest.raises(ValueError, match=message): + read_uiuc_geometry(_write(tmp_path, text), 0.2, SECTION) + + +@pytest.mark.parametrize("diameter", [0.0, -0.2, math.nan]) +def test_rejects_a_non_positive_diameter(tmp_path, diameter): + with pytest.raises(ValueError, match="diameter_m must be positive"): + read_uiuc_geometry(_write(tmp_path, GEOMETRY), diameter, SECTION) + + +def test_static_thrust_is_near_the_wind_tunnel_measurement(): + """With a generic section the model is a rough estimate: within 20 % of the measured CT.""" + propeller = BladeElementPropeller(read_uiuc_geometry(DATA / "apce_10x5_geom.txt", DIAMETER, SECTION)) + lines = (DATA / "apce_10x5_static_pg0819.txt").read_text().split("\n")[1:] + measured = [tuple(float(value) for value in line.split()) for line in lines if line.strip()] + + for rpm, ct_measured, _ in measured: + n = rpm / 60.0 + thrust, _ = propeller.thrust_torque(RHO, 0.0, rpm) + assert thrust / (RHO * n**2 * DIAMETER**4) == pytest.approx(ct_measured, rel=0.20) + + +def test_solver_runs_with_a_uiuc_propeller(): + propeller = BladeElementPropeller(read_uiuc_geometry(DATA / "apce_10x5_geom.txt", DIAMETER, SECTION)) + + point = PropulsionSolver().solve_operating_point( + motor=MotorSpec(kv_rpm_per_v=1000.0, resistance_ohm=0.08, no_load_current_a=0.6, current_max_a=40.0), + battery=FixedVoltageBattery(voltage_v=11.1), + system=SystemSpec(resistance_ohm=0.02), + propeller=propeller, + rho=RHO, + airspeed_mps=8.0, + throttle=0.8, + ) + + assert point.is_feasible + assert 0.0 < point.propeller_efficiency < 1.0 + + +STATIC = DATA / "apce_10x5_static_pg0819.txt" +FORWARD = DATA / "apce_10x5_kt0823_6005.txt" + + +def test_performance_bands_start_at_the_static_point(): + table = read_uiuc_performance(DIAMETER, STATIC, [FORWARD]) + + assert table.diameter_m == DIAMETER + assert table.rpm_levels == [6005.0] + points = table.data_by_rpm[6005.0] + # Static: 5869 RPM CT 0.0977 CP 0.0373, 6146 RPM CT 0.0983 CP 0.0374. + assert (points[0].j, points[0].ct, points[0].cp) == pytest.approx( + (0.0, 0.0977 + (6005 - 5869) / (6146 - 5869) * 0.0006, 0.0373 + (6005 - 5869) / (6146 - 5869) * 0.0001) + ) + assert (points[1].j, points[1].ct, points[1].cp) == (0.093, 0.0942, 0.0385) + assert (points[-1].j, points[-1].ct, points[-1].cp) == (0.484, 0.0338, 0.0249) + assert len(points) == 18 + + +def test_performance_from_static_data_only(): + table = read_uiuc_performance(DIAMETER, STATIC) + + assert len(table.rpm_levels) == 16 + assert table.get_coefficients(2508.0, 0.0) == pytest.approx((0.0914, 0.0374)) + + +def test_performance_needs_the_rpm_in_a_forward_file_name(tmp_path): + path = tmp_path / "apce_10x5_forward.txt" + path.write_text(FORWARD.read_text()) + + with pytest.raises(ValueError, match="does not end in the test RPM"): + read_uiuc_performance(DIAMETER, forward=[path]) + + +def test_performance_rejects_a_malformed_row(tmp_path): + path = tmp_path / "apce_10x5_kt0823_6005.txt" + path.write_text("J CT CP eta\n0.1 0.09 0.04\n") + + with pytest.raises(ValueError, match="apce_10x5_kt0823_6005.txt:2: expected 4 numbers"): + read_uiuc_performance(DIAMETER, forward=[path]) + + +def test_performance_needs_some_data(): + with pytest.raises(ValueError, match="no measurements"): + read_uiuc_performance(DIAMETER) diff --git a/tests/test_polar.py b/tests/test_polar.py new file mode 100644 index 0000000..58e5371 --- /dev/null +++ b/tests/test_polar.py @@ -0,0 +1,215 @@ +import math +from pathlib import Path + +import numpy as np +import pytest +import setuav_neuralfoil as nf +from setuav_neuralfoil import geometry + +from pythrust.battery import FixedVoltageBattery +from pythrust.io import read_apc_geometry +from pythrust.motor import MotorSpec +from pythrust.propeller import AirfoilPolar, BladeElementPropeller, BladeGeometry, BladeSection, BlendedPolar +from pythrust.propeller import apc_airfoil_polars +from pythrust.propeller.polar import NEURALFOIL_ALPHA_DEG, REYNOLDS, StationPolars +from pythrust.propulsion import PropulsionSolver, SystemSpec + +DATA = Path(__file__).parent / "data" +RHO = 1.225 + + +def _polar(cl, cd, name="test"): + """A 3 x 2 table: alpha -0.1, 0, 0.1 rad; Re 1e4, 1e5.""" + return AirfoilPolar( + name=name, alpha_rad=np.array([-0.1, 0.0, 0.1]), reynolds=np.array([1e4, 1e5]), cl=np.array(cl), cd=np.array(cd) + ) + + +LINEAR = _polar(cl=[[-0.4, -0.2], [0.2, 0.4], [0.8, 1.0]], cd=[[0.03, 0.02], [0.02, 0.01], [0.04, 0.03]]) + + +@pytest.fixture(scope="module") +def naca4412(): + return AirfoilPolar.from_neuralfoil("NACA 4412", n_crit=9.0) + + +### Table + + +def test_table_shape_and_order_are_checked(): + with pytest.raises(ValueError, match="shape"): + _polar(cl=[[0.0, 0.0]], cd=[[0.0, 0.0]]) + with pytest.raises(ValueError, match="increase"): + AirfoilPolar("x", np.array([0.1, 0.0]), np.array([1e4, 1e5]), np.zeros((2, 2)), np.zeros((2, 2))) + + +def test_interpolates_linearly_in_alpha_and_log_reynolds(): + alpha = np.array([0.0, 0.05, 0.0, 0.05]) + reynolds = np.array([1e4, 1e4, 10**4.5, 10**4.5]) + + cl, cd = LINEAR.coefficients(alpha, reynolds, np.zeros(4)) + + np.testing.assert_allclose(cl, [0.2, 0.5, 0.3, 0.6]) + np.testing.assert_allclose(cd, [0.02, 0.03, 0.015, 0.025]) + + +def test_reynolds_beyond_the_table_uses_its_ends(): + cl, _ = LINEAR.coefficients(np.zeros(2), np.array([1e2, 1e7]), np.zeros(2)) + + np.testing.assert_allclose(cl, [0.2, 0.4]) + + +def test_lift_has_the_prandtl_glauert_factor(): + cl0, cd0 = LINEAR.coefficients(0.05, 1e4, 0.0) + cl, cd = LINEAR.coefficients(0.05, 1e4, 0.6) + + assert cl == pytest.approx(cl0 / 0.8) + assert cd == pytest.approx(cd0) + + +def test_angles_wrap_around_a_full_turn(): + a, b = LINEAR.coefficients(np.array([0.05, 0.05 + 2 * np.pi]), 1e4, 0.0) + + assert a[0] == pytest.approx(a[1]) + + +def test_keeps_the_shape_of_a_station_grid(): + cl, cd = LINEAR.coefficients(np.zeros((3, 5)), np.full((3, 5), 1e4), np.zeros((3, 5))) + + assert cl.shape == cd.shape == (3, 5) + + +### NeuralFoil + + +def test_matches_neuralfoil_at_the_table_points(naca4412): + alpha_deg = np.array([-8.0, 0.0, 6.5, 12.0]) + for re in (REYNOLDS[3], REYNOLDS[8]): + expected = nf.get_aero_from_naca("4412", alpha=alpha_deg, Re=re, n_crit=9.0) + + cl, cd = naca4412.coefficients(np.radians(alpha_deg), re, 0.0) + + np.testing.assert_allclose(cl, expected["CL"], rtol=1e-10) + np.testing.assert_allclose(cd, expected["CD"], rtol=1e-10) + + +def test_flat_plate_beyond_neuralfoils_range(naca4412): + alpha = np.radians([-90.0, 60.0, 150.0]) + + cl, cd = naca4412.coefficients(alpha, 1e5, 0.0) + + np.testing.assert_allclose(cl, np.sin(2 * alpha), atol=1e-12) + np.testing.assert_allclose(cd, 2 * np.sin(alpha) ** 2, atol=1e-12) + + +def test_default_n_crit_is_7(): + assert AirfoilPolar.from_neuralfoil.__defaults__[0] == 7.0 + assert apc_airfoil_polars() is not None and apc_airfoil_polars()["E63"] is apc_airfoil_polars(7.0)["E63"] + + +def test_zero_lift_angle(): + """The lowest over the Reynolds numbers; near Re 5e4 the NACA 0012's lift bends about zero angle.""" + symmetric = AirfoilPolar.from_neuralfoil("0012") + cambered = AirfoilPolar.from_neuralfoil("4412") + + assert symmetric.zero_lift_alpha_rad == pytest.approx(0.0, abs=math.radians(1.0)) + assert cambered.zero_lift_alpha_rad == pytest.approx(math.radians(-4.4), abs=math.radians(0.2)) + + +def test_dat_file_and_coordinates_give_the_naca_polar(tmp_path, naca4412): + coordinates = geometry.naca("4412") + path = tmp_path / "naca4412.dat" + path.write_text("NACA 4412\n" + "\n".join(f"{x:.16f} {y:.16f}" for x, y in coordinates) + "\n") + + from_file = AirfoilPolar.from_neuralfoil(path, n_crit=9.0) + from_coordinates = AirfoilPolar.from_neuralfoil(coordinates, n_crit=9.0) + + np.testing.assert_allclose(from_file.cl, naca4412.cl, rtol=1e-8) + np.testing.assert_array_equal(from_coordinates.cl, naca4412.cl) + assert from_file.name == str(path) + + +### Mixing + + +def test_blended_polar_mixes_the_coefficients(): + other = _polar(cl=[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], cd=[[0.1, 0.1], [0.1, 0.1], [0.1, 0.1]]) + blend = BlendedPolar(LINEAR, other, 0.25) + + cl, cd = blend.coefficients(0.05, 1e4, 0.0) + + assert cl == pytest.approx(0.75 * 0.5) + assert cd == pytest.approx(0.75 * 0.03 + 0.25 * 0.1) + + +def test_station_polars_mix_the_nearest_sections(): + other = _polar(cl=[[0.0, 0.0], [0.0, 0.0], [0.0, 0.0]], cd=[[0.1, 0.1], [0.1, 0.1], [0.1, 0.1]]) + sections = [LINEAR, BlendedPolar(LINEAR, other, 0.5), other] + + stations = StationPolars.interpolate(np.array([0.0, 1.0, 2.0]), sections, np.array([0.0, 0.5, 1.5, 2.0])) + + assert stations.polars == [LINEAR, other] + np.testing.assert_allclose(stations.weights, [[1.0, 0.0], [0.75, 0.25], [0.25, 0.75], [0.0, 1.0]]) + cl, _ = stations.coefficients(np.full((4, 2), 0.05), np.full((4, 2), 1e4), np.zeros((4, 2))) + np.testing.assert_allclose(cl[:, 0], [0.5, 0.375, 0.125, 0.0]) + + +### Blade-element propeller + + +def test_a_blade_takes_one_kind_of_section(): + qprop = BladeSection(0.5, 5.8, -0.3, 1.2, 0.028, 0.05, 0.02, 0.5, 70000.0, -0.7) + blade = BladeGeometry(2, 0.1, (0.02, 0.1), (0.01, 0.01), (0.3, 0.2), (qprop, LINEAR)) + + with pytest.raises(TypeError, match="all BladeSection"): + BladeElementPropeller(blade) + + +def test_apc_airfoil_polars_are_cached_per_n_crit(): + polars = apc_airfoil_polars(5.0) + + assert set(polars) == {"E63", "APC12", "CLARK-Y"} + assert apc_airfoil_polars(5.0)["E63"] is polars["E63"] + assert apc_airfoil_polars(9.0)["E63"] is not polars["E63"] + + +def test_apc_geometry_blends_the_airfoils_across_the_transition(): + polars = apc_airfoil_polars(5.0) + blade = read_apc_geometry(DATA / "10x5E-PERF.PE0", polars) + + assert blade.sections[0] is polars["E63"] + assert blade.sections[-1] is polars["APC12"] + middle = [s for s in blade.sections if isinstance(s, BlendedPolar)] + assert middle and all(0.0 < s.weight < 1.0 for s in middle) + + +def test_static_coefficients_are_near_the_wind_tunnel_measurement(): + """APC 10x5E geometry with NeuralFoil polars (n_crit 5) against UIUC static data: 2500-6700 RPM.""" + propeller = BladeElementPropeller(read_apc_geometry(DATA / "10x5E-PERF.PE0", apc_airfoil_polars(5.0))) + lines = (DATA / "apce_10x5_static_pg0819.txt").read_text().split("\n")[1:] + measured = [tuple(float(value) for value in line.split()) for line in lines if line.strip()] + diameter = propeller.diameter_m + + for rpm, ct_measured, cp_measured in measured: + n = rpm / 60.0 + thrust, torque = propeller.thrust_torque(RHO, 0.0, rpm) + assert thrust / (RHO * n**2 * diameter**4) == pytest.approx(ct_measured, rel=0.08) + assert 2 * math.pi * torque / (RHO * n**2 * diameter**5) == pytest.approx(cp_measured, rel=0.08) + + +@pytest.mark.parametrize("airspeed", [0.0, 8.0, 15.0]) +def test_solver_finds_an_operating_point(airspeed): + propeller = BladeElementPropeller(read_apc_geometry(DATA / "10x5E-PERF.PE0", apc_airfoil_polars(5.0))) + + point = PropulsionSolver().solve_operating_point( + motor=MotorSpec(kv_rpm_per_v=1000.0, resistance_ohm=0.08, no_load_current_a=0.6, current_max_a=40.0), + battery=FixedVoltageBattery(voltage_v=11.1), + system=SystemSpec(resistance_ohm=0.02), + propeller=propeller, + rho=RHO, + airspeed_mps=airspeed, + throttle=0.8, + ) + + assert point.is_feasible + assert 0.0 < point.propeller_efficiency < 1.0 or airspeed == 0.0 diff --git a/validation/README.md b/validation/README.md new file mode 100644 index 0000000..9752a0f --- /dev/null +++ b/validation/README.md @@ -0,0 +1,24 @@ +# Validation + +Accuracy of PyThrust's propeller models against wind-tunnel data. The data is downloaded, not +kept in the repository. + +## APC propellers against UIUC measurements + +```bash +PYTHONPATH=. python validation/apc_uiuc.py # downloads to validation/.cache, writes validation/results +PYTHONPATH=. python validation/report.py # prints tables, writes docs/images/validation +``` + +`apc_uiuc.py` takes every APC propeller of the +[UIUC Propeller Database](https://m-selig.ae.illinois.edu/props/propDB.html) with static and +forward-flight measurements whose geometry file APC publishes, and compares the measured thrust +and power coefficients with: + +- the blade-element model on APC's geometry with NeuralFoil polars, at n_crit 3, 5, 7 and 9; +- the same with the generic section of the QPROP user guide; +- APC's performance table. + +n_crit is chosen on every third propeller of each family and the models are compared on the +rest. Operating points are also solved with a fixed motor and battery, with the measured table as +the truth. The results are on the [Validation](../docs/reference/validation.md) page. diff --git a/validation/apc_uiuc.py b/validation/apc_uiuc.py new file mode 100644 index 0000000..f72f02a --- /dev/null +++ b/validation/apc_uiuc.py @@ -0,0 +1,272 @@ +"""Accuracy of PyThrust's propeller models against UIUC wind-tunnel data for APC propellers. + +For every APC propeller that the UIUC Propeller Database measured and APC publishes a geometry file +for, this compares measured thrust and power coefficients with: + +- the blade-element model on APC's geometry, with NeuralFoil polars at several n_crit, +- the same with the generic section of the QPROP user guide, +- APC's own performance table. + +It also solves operating points with a fixed motor and battery, taking the measured table as the +truth, to show what the coefficient errors do to RPM, current and thrust. + +Usage, from the repository root: + + PYTHONPATH=. python validation/apc_uiuc.py + +Downloads go to validation/.cache (not in the repository); results to validation/results and +figures to docs/images/validation. +""" + +from __future__ import annotations + +import json +import math +import re +import statistics +import sys +import time +import urllib.request +from concurrent.futures import ProcessPoolExecutor +from pathlib import Path + +import numpy as np + +ROOT = Path(__file__).resolve().parent +CACHE = ROOT / ".cache" +RESULTS = ROOT / "results" +FIGURES = ROOT.parent / "docs" / "images" / "validation" + +UIUC = "https://m-selig.ae.illinois.edu/props" +APC_GEOMETRY = "https://www.apcprop.com/propeller-technical-data-files/{name}-PERF.PE0" +APC_PERFORMANCE = "https://www.apcprop.com/files/PER3_{name}.dat" +USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) PyThrust-validation" + +FAMILIES = {"apce": ("E", "Thin Electric"), "apcsf": ("SF", "Slow Flyer"), "apcsp": ("", "Sport")} +N_CRITS = (3.0, 5.0, 7.0, 9.0) +RHO = 1.225 +MIN_CT = 0.02 +"""Forward points with less measured thrust are left out of relative errors.""" + + +# ----------------------------------------------------------------------------- data + + +def fetch(url: str, path: Path) -> Path | None: + """Download once into the cache; None if the server has no such file.""" + if path.exists(): + return path if path.stat().st_size > 0 else None + path.parent.mkdir(parents=True, exist_ok=True) + request = urllib.request.Request(url, headers={"User-Agent": USER_AGENT}) + try: + with urllib.request.urlopen(request, timeout=60) as response: + data = response.read() + except Exception: + data = b"" + time.sleep(0.5) + if url.endswith(".PE0") and b"STATION" not in data: + data = b"" + path.write_bytes(data) + return path if data else None + + +def catalog() -> list[dict]: + """APC propellers in the UIUC database with static and forward data, and their files.""" + propellers: dict[str, dict] = {} + for volume in (1, 2, 3, 4): + page = fetch(f"{UIUC}/volume-{volume}/propDB-volume-{volume}.html", CACHE / "uiuc" / f"volume-{volume}.html") + html = page.read_text(errors="ignore") + for name in sorted(set(re.findall(r'data/(apc[a-z]*_[0-9.]+x[0-9.]+_[^"]+?)\.txt', html))): + match = re.match(r"(apc[a-z]*)_([0-9.]+)x([0-9.]+)_(.*)", name) + family, diameter, pitch, rest = match.groups() + if family not in FAMILIES: + continue + key = f"{family}_{diameter}x{pitch}" + entry = propellers.setdefault( + key, + dict(key=key, family=family, diameter_in=float(diameter), pitch_in=float(pitch), + static=[], forward=[], volume=volume), + ) + url = f"{UIUC}/volume-{volume}/data/{name}.txt" + if rest.startswith("static"): + entry["static"].append(url) + elif re.search(r"_\d+$", rest): + entry["forward"].append(url) + result = [] + for entry in propellers.values(): + if not (entry["static"] and entry["forward"]): + continue + suffix = FAMILIES[entry["family"]][0] + diameter, pitch = entry["key"].split("_")[1].split("x") + entry["apc_name"] = f"{diameter}x{pitch.replace('.', '')}{suffix}" + result.append(entry) + return sorted(result, key=lambda e: (e["family"], e["diameter_in"], e["pitch_in"])) + + +def download(entry: dict) -> dict | None: + """Local paths of a propeller's files; None without APC's geometry and performance files.""" + folder = CACHE / "uiuc" / entry["key"] + local = dict(entry) + local["static"] = [str(fetch(u, folder / u.rsplit("/", 1)[1])) for u in entry["static"][:1]] + local["forward"] = [str(p) for p in (fetch(u, folder / u.rsplit("/", 1)[1]) for u in entry["forward"]) if p] + name = entry["apc_name"] + pe0 = fetch(APC_GEOMETRY.format(name=name), CACHE / "apc" / f"{name}-PERF.PE0") + per3 = fetch(APC_PERFORMANCE.format(name=name), CACHE / "apc" / f"PER3_{name}.dat") + if pe0 is None or per3 is None or not local["forward"]: + return None + local["pe0"], local["per3"] = str(pe0), str(per3) + return local + + +# ----------------------------------------------------------------------------- evaluation + + +def rows(path: str) -> list[list[float]]: + out = [] + for line in Path(path).read_text(errors="ignore").splitlines(): + tokens = line.split() + try: + out.append([float(t) for t in tokens]) + except ValueError: + continue + return [r for r in out if r] + + +def models(entry: dict) -> dict: + from pythrust.io import read_apc, read_apc_geometry + from pythrust.propeller import BladeElementPropeller, BladeSection, apc_airfoil_polars + + generic = BladeSection(0.50, 5.8, -0.3, 1.2, 0.028, 0.050, 0.020, 0.5, 70000.0, -0.7) + result = {"generic": BladeElementPropeller(read_apc_geometry(entry["pe0"], generic)), "apc": read_apc(entry["per3"])} + for n_crit in N_CRITS: + result[f"nf{n_crit:g}"] = BladeElementPropeller(read_apc_geometry(entry["pe0"], apc_airfoil_polars(n_crit))) + return result + + +def coefficients(model, diameter: float, airspeed: float, rpm: float) -> tuple[float, float]: + n = rpm / 60.0 + if hasattr(model, "get_coefficients"): # APC's table: no extrapolation past its data. + return model.get_coefficients(rpm, airspeed / (n * diameter)) + thrust, torque = model.thrust_torque(RHO, airspeed, rpm) + return thrust / (RHO * n**2 * diameter**4), 2 * math.pi * torque / (RHO * n**2 * diameter**5) + + +def evaluate_or_report(entry: dict) -> dict: + """``evaluate``, or the propeller's key and the error that stopped it.""" + try: + return evaluate(entry) + except Exception as error: # Report and go on with the other propellers. + return {"key": entry["key"], "error": f"{type(error).__name__}: {error}"} + + +def evaluate(entry: dict) -> dict: + """Coefficient errors of every model on one propeller, and its operating points.""" + diameter = entry["diameter_in"] * 0.0254 + all_models = models(entry) + static = rows(entry["static"][0]) + forward = [] + for path in entry["forward"]: + rpm = float(re.search(r"_(\d+)\.txt$", path).group(1)) + forward += [(rpm, *r[:3]) for r in rows(path) if len(r) == 4] + + out = {"key": entry["key"], "family": entry["family"], "diameter_in": entry["diameter_in"], + "pitch_in": entry["pitch_in"], "models": {}} + for name, model in all_models.items(): + s_ct, s_cp, f_ct, f_cp, f_eta, eta_max = [], [], [], [], [], [] + for rpm, ct, cp in (r for r in static if len(r) == 3): + m_ct, m_cp = coefficients(model, diameter, 0.0, rpm) + if m_cp > 0: + s_ct.append(m_ct / ct - 1) + s_cp.append(m_cp / cp - 1) + runs: dict[float, list] = {} + for rpm, j, ct, cp in forward: + m_ct, m_cp = coefficients(model, diameter, j * rpm / 60.0 * diameter, rpm) + if not (m_cp > 0 and math.isfinite(m_ct)): + continue + runs.setdefault(rpm, []).append((j * ct / cp, j * m_ct / m_cp)) + if ct >= MIN_CT: + f_ct.append(m_ct / ct - 1) + f_cp.append(m_cp / cp - 1) + f_eta.append(j * m_ct / m_cp - j * ct / cp) + for points in runs.values(): + measured, modelled = zip(*points) + eta_max.append(max(modelled) - max(measured)) + out["models"][name] = dict(static_ct=s_ct, static_cp=s_cp, forward_ct=f_ct, forward_cp=f_cp, + forward_eta=f_eta, eta_max=eta_max) + out["operating_points"] = operating_points(entry, all_models, diameter) + return out + + +def operating_points(entry: dict, all_models: dict, diameter: float) -> dict: + """RPM, current and thrust with a fixed motor and battery; the measured table is the truth.""" + from pythrust.battery import FixedVoltageBattery + from pythrust.io import read_uiuc_performance + from pythrust.motor import MotorSpec + from pythrust.propulsion import PropulsionSolver, SystemSpec + + truth = read_uiuc_performance(diameter, entry["static"][0], entry["forward"]) + target = statistics.median(r[0] for r in rows(entry["static"][0]) if len(r) == 3) + voltage = 11.1 + motor = MotorSpec(kv_rpm_per_v=1.25 * target / voltage, resistance_ohm=0.05, no_load_current_a=0.5, + current_max_a=1e3) + cases = {"static": 0.0, "cruise": 0.3 * target / 60.0 * diameter} + result = {} + for case, airspeed in cases.items(): + def solve(propeller): + return PropulsionSolver().solve_operating_point( + motor=motor, battery=FixedVoltageBattery(voltage_v=voltage), system=SystemSpec(resistance_ohm=0.0), + propeller=propeller, rho=RHO, airspeed_mps=airspeed, throttle=1.0) + reference = solve(truth) + if not reference.is_feasible: + continue + result[case] = {} + for name, model in all_models.items(): + point = solve(model) + if point.is_feasible: + result[case][name] = dict( + rpm=point.rpm / reference.rpm - 1, + current=point.motor_current_a / reference.motor_current_a - 1, + thrust=point.thrust_n / reference.thrust_n - 1, + ) + return result + + +# ----------------------------------------------------------------------------- summary + + +def mean_abs(values) -> float: + return float(np.mean(np.abs(values))) if len(values) else math.nan + + +def summarize(results: list[dict]) -> dict: + keys = sorted(r["key"] for r in results) + calibration = {k for f in FAMILIES for k in [k for k in keys if k.startswith(f + "_")][::3]} + score = {} + for n_crit in N_CRITS: + name = f"nf{n_crit:g}" + score[name] = float(np.mean([ + np.mean([mean_abs(r["models"][name][q]) for q in ("static_ct", "static_cp", "forward_ct", "forward_cp")]) + for r in results if r["key"] in calibration])) + chosen = min(score, key=score.get) + return dict(calibration=sorted(calibration), calibration_score=score, chosen=chosen) + + +def main() -> None: + sys.path.insert(0, str(ROOT.parent)) + entries = [e for e in (download(e) for e in catalog()) if e] + print(f"{len(entries)} propellers with UIUC data and APC files", flush=True) + with ProcessPoolExecutor() as pool: + evaluated = list(pool.map(evaluate_or_report, entries)) + failed = [r for r in evaluated if "error" in r] + for r in failed: + print(f"{r['key']}: {r['error']}") + results = [r for r in evaluated if "error" not in r] + print(f"{len(results)} evaluated, {len(failed)} failed") + summary = summarize(results) + RESULTS.mkdir(exist_ok=True) + (RESULTS / "results.json").write_text(json.dumps(dict(summary=summary, propellers=results, failed=failed))) + print(json.dumps(summary, indent=1)) + + +if __name__ == "__main__": + main() diff --git a/validation/report.py b/validation/report.py new file mode 100644 index 0000000..2fb2776 --- /dev/null +++ b/validation/report.py @@ -0,0 +1,166 @@ +"""Tables and figures from validation/results/results.json (written by apc_uiuc.py). + + PYTHONPATH=. python validation/report.py + +Prints Markdown tables; writes figures to docs/images/validation. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import matplotlib + +matplotlib.use("Agg") +import matplotlib.pyplot as plt # noqa: E402 +import numpy as np # noqa: E402 + +ROOT = Path(__file__).resolve().parent +FIGURES = ROOT.parent / "docs" / "images" / "validation" +QUANTITIES = [ + ("static_ct", "Static $C_T$", "%"), + ("static_cp", "Static $C_P$", "%"), + ("forward_ct", "Forward $C_T$", "%"), + ("forward_cp", "Forward $C_P$", "%"), + ("forward_eta", "Forward efficiency", "pt"), +] +FAMILY_NAMES = {"apce": "Thin Electric", "apcsf": "Slow Flyer", "apcsp": "Sport"} +COLORS = {"generic": "#adb5bd", "nf9": "#f4a261", "chosen": "#d1495b", "apc": "#2e86ab"} + + +def load(): + data = json.loads((ROOT / "results" / "results.json").read_text()) + return data["summary"], data["propellers"] + + +def labels(summary): + chosen = summary["chosen"] + return { + "generic": "Generic section", + "nf9": "NeuralFoil, n_crit 9", + chosen: f"NeuralFoil, n_crit {chosen[2:]}", + "apc": "APC table", + } + + +def per_propeller(results, model, quantity, signed=False): + """One number per propeller: the mean (absolute or signed) error, in % or efficiency points.""" + values = [] + for r in results: + errors = r["models"][model][quantity] + if errors: + values.append(100 * (np.mean(errors) if signed else np.mean(np.abs(errors)))) + return np.array(values) + + +def table(results, models, names, title, signed=False): + lines = [f"\n{title}\n", "| Model | " + " | ".join(q[1] for q in QUANTITIES) + " |", + "|---|" + "---:|" * len(QUANTITIES)] + for model in models: + cells = [] + for quantity, _, unit in QUANTITIES: + v = per_propeller(results, model, quantity, signed) + cells.append(f"{np.mean(v):+.1f}" if signed else f"{np.mean(v):.1f}") + lines.append(f"| {names[model]} | " + " | ".join(cells) + " |") + print("\n".join(lines)) + + +def main(): + summary, results = load() + chosen = summary["chosen"] + names = labels(summary) + models = ["generic", "nf9", chosen, "apc"] if chosen != "nf9" else ["generic", chosen, "apc"] + test = [r for r in results if r["key"] not in summary["calibration"]] + FIGURES.mkdir(parents=True, exist_ok=True) + + print(f"{len(results)} propellers; n_crit calibrated on {len(summary['calibration'])}, tested on {len(test)}.") + print("Calibration score (mean of the four coefficient errors):", + {k: round(100 * v, 2) for k, v in summary["calibration_score"].items()}, "-> chosen", chosen) + table(test, models, names, "Test set, mean absolute error per propeller (% ; efficiency in points)") + table(test, models, names, "Test set, mean signed error (bias)", signed=True) + for family, family_name in FAMILY_NAMES.items(): + subset = [r for r in test if r["family"] == family] + table(subset, models, names, f"{family_name} ({len(subset)} propellers), mean absolute error") + + # Operating points. + print("\nOperating points (test set), mean absolute error in % against the measured table:") + for case in ("static", "cruise"): + for model in models: + cells = [] + for q in ("rpm", "current", "thrust"): + v = [100 * abs(r["operating_points"][case][model][q]) for r in test + if case in r["operating_points"] and model in r["operating_points"][case]] + cells.append(f"{q} {np.mean(v):.1f}% (n={len(v)})") + print(f" {case:6s} {names[model]:22s} " + ", ".join(cells)) + + figure_errors(test, models, names, chosen) + figure_bias_by_size(test, names, chosen) + figure_operating_points(test, models, names, chosen) + + +def color(model, chosen): + return COLORS["chosen" if model == chosen else model] + + +def figure_errors(test, models, names, chosen): + fig, axes = plt.subplots(1, len(QUANTITIES), figsize=(20, 4.6)) + for ax, (quantity, title, unit) in zip(axes, QUANTITIES): + data = [per_propeller(test, m, quantity) for m in models] + box = ax.boxplot(data, patch_artist=True, showfliers=True, widths=0.6) + for patch, m in zip(box["boxes"], models): + patch.set_facecolor(color(m, chosen)) + patch.set_alpha(0.8) + ax.set_xticks(range(1, len(models) + 1), [names[m].replace(", ", "\n") for m in models], fontsize=8) + ax.set_title(title) + ax.set_ylabel("error per propeller, " + ("%" if unit == "%" else "points")) + ax.grid(alpha=0.3, axis="y") + fig.suptitle(f"Mean absolute error per propeller, {len(test)} APC propellers not used to choose n_crit", fontsize=13) + fig.tight_layout() + fig.savefig(FIGURES / "errors.png", dpi=100) + + +def figure_bias_by_size(test, names, chosen): + fig, axes = plt.subplots(1, 4, figsize=(20, 4.6)) + markers = {"apce": "o", "apcsf": "s", "apcsp": "^"} + for ax, (quantity, title, _) in zip(axes, QUANTITIES[:4]): + for model in (chosen, "apc"): + for family, marker in markers.items(): + subset = [r for r in test if r["family"] == family and r["models"][model][quantity]] + ax.scatter([r["diameter_in"] for r in subset], + [100 * np.mean(r["models"][model][quantity]) for r in subset], + marker=marker, color=color(model, chosen), alpha=0.75, s=28, + label=f"{names[model]}, {FAMILY_NAMES[family]}") + ax.axhline(0, color="#222", lw=0.8) + ax.set_title(title + ": signed error") + ax.set_xlabel("diameter, in") + ax.set_ylabel("%") + ax.grid(alpha=0.3) + axes[0].legend(fontsize=7) + fig.suptitle("Bias by propeller size and family", fontsize=13) + fig.tight_layout() + fig.savefig(FIGURES / "bias_by_size.png", dpi=100) + + +def figure_operating_points(test, models, names, chosen): + fig, axes = plt.subplots(1, 4, figsize=(20, 4.6)) + panels = [("static", "current"), ("static", "thrust"), ("cruise", "current"), ("cruise", "thrust")] + for ax, (case, q) in zip(axes, panels): + data = [[100 * r["operating_points"][case][m][q] for r in test + if case in r["operating_points"] and m in r["operating_points"][case]] for m in models] + box = ax.boxplot(data, patch_artist=True, widths=0.6) + for patch, m in zip(box["boxes"], models): + patch.set_facecolor(color(m, chosen)) + patch.set_alpha(0.8) + ax.axhline(0, color="#222", lw=0.8) + ax.set_xticks(range(1, len(models) + 1), [names[m].replace(", ", "\n") for m in models], fontsize=8) + ax.set_title(f"{case.capitalize()} {q}: signed error") + ax.set_ylabel("%") + ax.grid(alpha=0.3, axis="y") + fig.suptitle("Operating point with a fixed motor and battery, against the measured table", fontsize=13) + fig.tight_layout() + fig.savefig(FIGURES / "operating_points.png", dpi=100) + + +if __name__ == "__main__": + main()