Repository navigation
Conversation
Each UNITS_CONVERSION_DICT entry is the number of that unit in one base unit (1 m = 1e3 mm). Six entries did not follow that: deg, grad, mg and g were inverted, ft/s^2 used the inverse of ft/s, and atm was 1.01325e-5 instead of 1/101325. convert_units(np.pi, "rad", "deg") returned 0.0548. Add a table-driven test that checks every non-temperature unit against its exact SI definition in both directions.
FlightDataImporter divides imported columns by UNITS_CONVERSION_DICT entries, so the wrong ft/s^2 and deg factors made a log recorded in ft/s^2 read 10.8x too large and one recorded in degrees 3283x too large.
Document how the conversion table is read (units per base unit), the convention the inverted entries broke, and replace the rounded lb, mmHg and inHg constants with their exact definitions so the definition test can run at rel=1e-9. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XDW574kgc6gnnChDhsWmRZ
"g" is gram in the units table, so converting with the metric unit_system["acceleration"] would apply a mass factor. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XDW574kgc6gnnChDhsWmRZ
convert_units_Functions scaled get_source() and renamed the axis labels in place, so converting a Function twice applied the factor to data already converted. Work on copies, and run every unit definition through the Function path on both axes. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XDW574kgc6gnnChDhsWmRZ
The importer divided a view of _data in place by UNITS_CONVERSION_DICT, so the stored data turned into SI while still labelled with the original units, and a unit outside the table (degC included) raised a bare KeyError. Convert through a new units.convert_to_base_unit, which handles temperatures and raises the module's ValueError. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01XDW574kgc6gnnChDhsWmRZ
|
@rundvd I opened rundvd#1 against this branch with the follow-ups from my review: |
54c844b to
10aec43
Compare
|
@Gui-FernandesBR Merged, thanks. I added the changelog note to the description, including that |
Gui-FernandesBR
left a comment
There was a problem hiding this comment.
Thanks for fixing the table! One regression in EnvironmentAnalysis (comment on units.py), plus a few smaller points inline.
Also: since ft/s^2, atm, mg, g, deg and grad now return different values, please add a line under [Unreleased] > Fixed in CHANGELOG.md saying results computed with those units change.
| def convert_units_Functions(variable, from_unit, to_unit, axis=1): | ||
| """See units.convert_units() for documentation.""" | ||
| # Work on copies so the Function passed in is left unchanged | ||
| variable_source = np.array(variable.get_source(), dtype=float) |
There was a problem hiding this comment.
This copy breaks the imperial height conversion in EnvironmentAnalysis.converted_pressure_level_data.
There (environment_analysis.py ~L975-993) the axis=0 result is discarded and the axis=1 call starts again from value. It only worked because get_source() returns self.source by reference and the old code mutated it. Now the heights and the Height Above Ground Level (m) label stay in metres while unit_system["length"] is ft, and to_environment() converts them ft→m a second time.
Passing variable instead of value to the second call should fix it; then worth checking that altitude_AGL_range and to_environment still assume the same convention. A test with unit_system="imperial" would have caught this.
| # Convert units if necessary | ||
| if units and col in units: | ||
| values /= UNITS_CONVERSION_DICT[units[col]] | ||
| values = convert_to_base_unit(values, units[col]) |
There was a problem hiding this comment.
A units entry for the time column is still ignored.
The name == "time" branch (L273) uses the raw times before reaching this line, so units={"time": "min"} builds every Function on a 60x longer time axis, and units={"time": "furlong"} doesn't raise. Not introduced here, but since this PR now validates units, consider converting (or rejecting) the time column too.
| # Convert units if necessary | ||
| if units and col in units: | ||
| values /= UNITS_CONVERSION_DICT[units[col]] | ||
| values = convert_to_base_unit(values, units[col]) |
There was a problem hiding this comment.
An acceleration column logged in g and passed as units={"az": "g"} is now read as grams (divided by 1e3) with no error.
Standard gravity is "gs" in the table. Worth saying so in the units docstring, and maybe rejecting mass/angle units on acceleration columns.
| variable.__outputs__[0] = variable.__outputs__[0].replace( | ||
| from_unit, to_unit | ||
| ) | ||
| outputs[0] = outputs[0].replace(from_unit, to_unit) |
There was a problem hiding this comment.
str.replace rewrites every occurrence of the unit in the label, not only the unit itself: converting "Maximum Height (m)" from m to ft gives "Maxiftuft Height (ft)".
Pre-existing, but since these lines are being rewritten: replacing only the parenthesised unit avoids it, e.g. re.sub(rf"\({re.escape(from_unit)}\)", f"({to_unit})", outputs[0]) (same for inputs[0] above).
| return incoming_factor / outgoing_factor | ||
|
|
||
|
|
||
| def convert_to_base_unit(variable, from_unit): |
There was a problem hiding this comment.
convert_to_base_unit is public, so it should get the numpydoc Parameters/Returns/Raises sections like convert_units.
The FlightDataImporter docstrings should also mention that an unknown unit now raises ValueError (it used to be KeyError) and that K, degC and degF are accepted.
| units={"value": unit}, | ||
| ) | ||
|
|
||
| assert np.isclose(fd.value(0), value_in_si) |
There was a problem hiding this comment.
np.isclose's default atol=1e-8 hides errors at this scale: for mg (1e-6) a factor off by 1% still passes.
| assert np.isclose(fd.value(0), value_in_si) | |
| assert fd.value(0) == pytest.approx(value_in_si, rel=1e-9) |
The heights of converted_pressure_level_data stayed in metres with the imperial unit system, since the converted x axis was discarded. Convert the y axis of that result instead, and read altitude_AGL_range and the pressures at 1000, 10000 and 30000 ft in the same length unit.
Converting "Maximum Height (m)" to ft gave "Maxiftuft Height (ft)". Also document convert_to_base_unit.
A units entry for the time column was ignored. Time and acceleration columns now also reject units of other quantities, such as "g" (gram) for an acceleration.
|
Thanks for the detailed review. I merged
I left one thing alone because it's in the plots: the hourly forecast plot passes AGL heights to a function of ASL, in feet with imperial. It currently fails earlier with a |
Pull request type
Checklist
ruff format --check,ruff checkandpylintpass on the changed filestests/unitpasses locally; the environment analysis (with--runslow) and flight data importer integration tests also passCurrent behavior
Each
UNITS_CONVERSION_DICTentry is the number of that unit in one base unit (1 m = 1e3 mm), but six entries do not follow that:deg,grad,mgandgare inverted,ft/s^2holds the inverse of the correct factor, andatmis 1.01325e-5 instead of 1/101325.convert_units(np.pi, "rad", "deg")returns 0.0548. BecauseFlightDataImporterdivides by these factors, a flight log recorded in ft/s^2 imports 10.8x too large and one recorded in degrees 3283x too large.New behavior
The six factors are corrected. Parametrized tests check every non-temperature unit against its exact SI definition in both directions, and a new
FlightDataImportertest covers ft/s^2 and degree columns.From the first review (rundvd#1):
convert_unitsno longer modifies theFunctionit is given;FlightDataImporterconverts through a newconvert_to_base_unitinstead of dividing the stored data in place (which left it in SI under the original unit labels), converts temperature columns (degC,degF) to K, and raisesValueErrorrather thanKeyErrorfor an unsupported unit;lb,mmHgandinHguse their exact definitions; and the metric acceleration unit ofEnvironmentAnalysisis"gs", since"g"is gram.From the second review:
EnvironmentAnalysisuses one height unit throughout. The converted heights,altitude_AGL_rangeand the pressures at 1000, 10000 and 30000 ft are all in the length unit of the unit system, and the forecastEnvironmentgets its elevation in metres.create_environment_objectgives the same atmosphere in SI, metric and imperial.FlightDataImporterconverts the time column when its unit is given. It rejects units that are not of time for the time column, and mass and angle units foracceleration,ax,ayandaz. A secondread_datacall no longer converts the files of the first one again.convert_unitsrenames only the unit in parentheses in the axis label of aFunction.Breaking change
ft/s^2,atm,mg,g,degandgradnow return different (correct) values, so any result computed with those units changes. Conversions withlb,mmHgandinHgchange by at most about 3 parts per million.EnvironmentAnalysisat 1000, 10000 and 30000 ft change, since they were evaluated at the wrong height.original_pressure_level_datanow keeps the units of the file instead of being overwritten by the converted values.FlightDataImporterraisesValueErrorfor the rejected units above, and for a time unit that is not supported (it was ignored before).