Skip to content

BUG: fix inverted and wrong factors in the units conversion table - #1199

Open
rundvd wants to merge 11 commits into
RocketPy-Team:developfrom
rundvd:bug/units-conversion-factors
Open

rundvd wants to merge 11 commits into
RocketPy-Team:developfrom
rundvd:bug/units-conversion-factors

Conversation

@rundvd

@rundvd rundvd commented Sep 26, 2026 •

Copy link
Copy Markdown

Pull request type

  • Code changes (bugfix, features)

Checklist

  • Tests for the changes have been added
  • ruff format --check, ruff check and pylint pass on the changed files
  • tests/unit passes locally; the environment analysis (with --runslow) and flight data importer integration tests also pass

Current behavior

Each UNITS_CONVERSION_DICT entry is the number of that unit in one base unit (1 m = 1e3 mm), but six entries do not follow that: deg, grad, mg and g are inverted, ft/s^2 holds the inverse of the correct factor, and atm is 1.01325e-5 instead of 1/101325. convert_units(np.pi, "rad", "deg") returns 0.0548. Because FlightDataImporter divides 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 FlightDataImporter test covers ft/s^2 and degree columns.

From the first review (rundvd#1): convert_units no longer modifies the Function it is given; FlightDataImporter converts through a new convert_to_base_unit instead 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 raises ValueError rather than KeyError for an unsupported unit; lb, mmHg and inHg use their exact definitions; and the metric acceleration unit of EnvironmentAnalysis is "gs", since "g" is gram.

From the second review:

  • EnvironmentAnalysis uses one height unit throughout. The converted heights, altitude_AGL_range and the pressures at 1000, 10000 and 30000 ft are all in the length unit of the unit system, and the forecast Environment gets its elevation in metres. create_environment_object gives the same atmosphere in SI, metric and imperial.
  • FlightDataImporter converts 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 for acceleration, ax, ay and az. A second read_data call no longer converts the files of the first one again.
  • convert_units renames only the unit in parentheses in the axis label of a Function.

Breaking change

  • Yes: conversions with ft/s^2, atm, mg, g, deg and grad now return different (correct) values, so any result computed with those units changes. Conversions with lb, mmHg and inHg change by at most about 3 parts per million.
  • With the imperial unit system, the pressures of EnvironmentAnalysis at 1000, 10000 and 30000 ft change, since they were evaluated at the wrong height. original_pressure_level_data now keeps the units of the file instead of being overwritten by the converted values.
  • FlightDataImporter raises ValueError for the rejected units above, and for a time unit that is not supported (it was ignored before).

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.
@rundvd
rundvd requested a review from a team as a code owner September 26, 2026 01:35
Gui-FernandesBR and others added 4 commits November 15, 2026 23:28
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
@Gui-FernandesBR

Copy link
Copy Markdown
Member

@rundvd I opened rundvd#1 against this branch with the follow-ups from my review: convert_units and FlightDataImporter no longer modify their inputs, the exact pound and mercury constants, and "gs" as the metric acceleration unit of EnvironmentAnalysis. Could you merge it into bug/units-conversion-factors so it lands here? Since the changelog is generated from this PR's description, please also add a note that conversions with ft/s^2, atm, mg, g, deg and grad now return different values.

@rundvd
rundvd force-pushed the bug/units-conversion-factors branch from 54c844b to 10aec43 Compare November 17, 2026 07:08
@rundvd

rundvd commented Nov 17, 2026

Copy link
Copy Markdown
Author

@Gui-FernandesBR Merged, thanks. I added the changelog note to the description, including that lb, mmHg and inHg shift by at most about 3 parts per million now that they use the exact constants. I reworded my two commit messages after merging, so the branch was force-pushed and your commits are on it under new hashes; the code is identical to your merge.

@Gui-FernandesBR Gui-FernandesBR left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread rocketpy/units.py
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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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])

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread rocketpy/units.py Outdated
variable.__outputs__[0] = variable.__outputs__[0].replace(
from_unit, to_unit
)
outputs[0] = outputs[0].replace(from_unit, to_unit)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread rocketpy/units.py
return incoming_factor / outgoing_factor


def convert_to_base_unit(variable, from_unit):

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

np.isclose's default atol=1e-8 hides errors at this scale: for mg (1e-6) a factor off by 1% still passes.

Suggested change
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.
@rundvd rundvd changed the title Fix inverted and wrong factors in the units conversion table BUG: fix inverted and wrong factors in the units conversion table Dec 1, 2026
@rundvd

rundvd commented Dec 1, 2026

Copy link
Copy Markdown
Author

Thanks for the detailed review. I merged develop into the branch to resolve the conflict in test_environment_analysis.py and pushed the changes:

  • EnvironmentAnalysis: the second call now takes variable. Two other places didn't follow the same convention: altitude_AGL_range read the original data, and the pressures at 1000, 10000 and 30000 ft were looked up in metres. The second one is already wrong on develop in imperial, where the 10000 ft pressure is read at 3048 ft. The forecast Environment was also getting its elevation in feet. The new tests check the heights in feet and that create_environment_object gives the same atmosphere in SI, metric and imperial. I also compared the three on the EuroC files, and they agree.
  • Time column: converted when a unit is given, and a unit that isn't one of time raises ValueError. Since read_data looped over every file read so far, a second call would have converted the first file's time too, so it now loops over the new files only.
  • "g" on an acceleration: the docstring points to "gs", and mass and angle units raise ValueError for acceleration, ax, ay and az. Columns mapped to other names, like acceleration_x, aren't checked.
  • Labels: only the unit in parentheses is renamed, on both axes. I used str.replace with the parentheses included, since it doesn't need escaping.
  • convert_to_base_unit has the numpydoc sections, and the importer docstrings list the supported units and the ValueError.
  • The importer test uses pytest.approx(rel=1e-9).
  • CHANGELOG.md has the line you asked for, plus one each for the EnvironmentAnalysis and FlightDataImporter changes. I updated the description to match and added the BUG: prefix to the title.

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 KeyError, since forecast has string keys and hours has integers. I can fix it in a separate PR if you'd like.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants