Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion rocketpy/environment/environment_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -487,7 +487,7 @@ def __init_unit_system(self):
self.unit_system = {
"length": "m",
"velocity": "m/s",
"acceleration": "g",
"acceleration": "gs",
"mass": "kg",
"time": "s",
"pressure": "hPa",
Expand Down
4 changes: 2 additions & 2 deletions rocketpy/simulation/flight_data_importer.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@
import numpy as np

from rocketpy.mathutils import Function
from rocketpy.units import UNITS_CONVERSION_DICT
from rocketpy.units import convert_to_base_unit

logger = logging.getLogger(__name__)

Expand Down Expand Up @@ -287,7 +287,7 @@ def __create_attributes(self, filepath, interpolation, extrapolation):

# Convert units if necessary
if units and col in units:
values /= UNITS_CONVERSION_DICT[units[col]]
values = convert_to_base_unit(values, units[col])
logger.debug("Attribute '%s' converted from %s to SI", name, units[col])

# Create Function object and set as attribute
Expand Down
37 changes: 26 additions & 11 deletions rocketpy/units.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

from .mathutils.function import Function

# Each value is how many of that unit make one base unit (e.g. "km": 1e-3).
# Multiply by it to leave the base unit, divide by it to reach the base unit.
UNITS_CONVERSION_DICT = {
# Units of length. Meter "m" is the base unit.
"mm": 1e3,
Expand Down Expand Up @@ -33,8 +35,8 @@
"MPa": 1e-6,
"bar": 1e-5,
"atm": 1 / 101325,
"mmHg": 1 / 133.322,
"inHg": 1 / 3386.389,
"mmHg": 1 / 133.322387415,
"inHg": 1 / (25.4 * 133.322387415),
# Units of time. Seconds "s" is the base unit.
"s": 1,
"min": 1 / 60,
Expand All @@ -44,7 +46,7 @@
"mg": 1e6,
"g": 1e3,
"kg": 1,
"lb": 2.20462,
"lb": 1 / 0.45359237,
# Units of angle. Radian "rad" is the base unit.
"rad": 1,
"deg": 180 / np.pi,
Expand All @@ -53,7 +55,8 @@


def conversion_factor(from_unit, to_unit):
"""Returns the conversion factor from one unit to another."""
"""Returns the factor that multiplies a value in ``from_unit`` to give it
in ``to_unit``. See ``UNITS_CONVERSION_DICT`` for how the table is read."""
try:
incoming_factor = UNITS_CONVERSION_DICT[to_unit]
except KeyError as e:
Expand All @@ -66,10 +69,24 @@ def conversion_factor(from_unit, to_unit):
return incoming_factor / outgoing_factor


def convert_to_base_unit(variable, from_unit):
"""Returns ``variable`` converted from ``from_unit`` to its base unit, or to
"K" for temperatures. ``variable`` itself is not modified."""
if from_unit in ["K", "degC", "degF"]:
return convert_temperature(variable, from_unit, "K")
try:
return variable / UNITS_CONVERSION_DICT[from_unit]
except KeyError as e:
raise ValueError(f"Unit '{from_unit}' is not supported.") from e


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)
inputs = list(variable.__inputs__)
outputs = list(variable.__outputs__)
# Perform conversion, take special care with temperatures
variable_source = variable.get_source()
if from_unit in ["K", "degC", "degF"]:
variable_source[:, axis] = convert_temperature(
variable_source[:, axis], from_unit, to_unit
Expand All @@ -79,16 +96,14 @@ def convert_units_Functions(variable, from_unit, to_unit, axis=1):
# Rename axis labels
match axis:
case 0:
variable.__inputs__[0] = variable.__inputs__[0].replace(from_unit, to_unit)
inputs[0] = inputs[0].replace(from_unit, to_unit)
case 1:
variable.__outputs__[0] = variable.__outputs__[0].replace(
from_unit, to_unit
)
outputs[0] = outputs[0].replace(from_unit, to_unit)
# Create new Function instance with converted data
return Function(
source=variable_source,
inputs=variable.__inputs__,
outputs=variable.__outputs__,
inputs=inputs,
outputs=outputs,
interpolation=variable.__interpolation__,
extrapolation=variable.__extrapolation__,
)
Expand Down
41 changes: 41 additions & 0 deletions tests/integration/simulation/test_flight_data_importer.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Tests the FlightDataImporter class from rocketpy.simulation module."""

import numpy as np
import pytest

from rocketpy.simulation import FlightDataImporter

Expand Down Expand Up @@ -74,3 +75,43 @@ def test_flight_importer_converts_imperial_and_degree_columns(tmp_path):

assert np.isclose(fd.az(0), 32.174 * 0.3048)
assert np.isclose(fd.attitude_angle(0), np.pi / 2)


@pytest.mark.parametrize(
"unit, value_in_si",
[
("g", 1e-3),
("mg", 1e-6),
("atm", 101325),
("grad", np.pi / 200),
("degC", 274.15),
],
)
def test_flight_importer_converts_column_to_si(tmp_path, unit, value_in_si):
"""A column given in a non-SI unit should be converted to SI, while the
data read from the file keeps its original values."""
path = tmp_path / "log.csv"
path.write_text("time,value\n0,1\n1,1\n")

fd = FlightDataImporter(
paths=str(path),
columns_map={"time": "time", "value": "value"},
units={"value": unit},
)

assert np.isclose(fd.value(0), value_in_si)
data = next(iter(fd._data.values()))
np.testing.assert_array_equal(data[:, 1], [1, 1])


def test_flight_importer_unsupported_unit(tmp_path):
"""An unknown unit should raise the same error as the units module."""
path = tmp_path / "log.csv"
path.write_text("time,value\n0,1\n1,1\n")

with pytest.raises(ValueError, match="Unit 'furlong' is not supported."):
FlightDataImporter(
paths=str(path),
columns_map={"time": "time", "value": "value"},
units={"value": "furlong"},
)
34 changes: 34 additions & 0 deletions tests/unit/environment/test_environment_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@

from rocketpy import EnvironmentAnalysis
from rocketpy.tools import import_optional_dependency
from rocketpy.units import convert_units

plt.rcParams.update({"figure.max_open_warning": 0})

Expand Down Expand Up @@ -48,6 +49,39 @@ def test_missing_timezonefinder_defaults_to_utc(
assert analysis.end_date.tzinfo is not None


@pytest.mark.parametrize(
"unit_system, standard_gravity",
[("metric", 1), ("imperial", 9.80665 / 0.3048), ("SI", 9.80665)],
)
@patch("rocketpy.environment.environment_analysis._EnvironmentAnalysisPlots")
@patch("rocketpy.environment.environment_analysis._EnvironmentAnalysisPrints")
@patch.object(
EnvironmentAnalysis,
"_EnvironmentAnalysis__check_requirements",
)
def test_unit_system_acceleration_is_an_acceleration_unit(
_mock_check_requirements,
_mock_prints,
_mock_plots,
unit_system,
standard_gravity,
):
"""The acceleration unit of each unit system should convert standard
gravity as an acceleration, not as a mass ("g" is gram in the table)."""
analysis = EnvironmentAnalysis(
start_date=datetime(2026, 1, 1),
end_date=datetime(2026, 1, 2),
latitude=0,
longitude=0,
timezone="UTC",
unit_system=unit_system,
)

converted = convert_units(9.80665, "m/s^2", analysis.unit_system["acceleration"])

assert converted == pytest.approx(standard_gravity, rel=1e-9)


@patch("matplotlib.pyplot.show")
def test_distribution_plots(mock_show, env_analysis): # pylint: disable=unused-argument
"""Tests the distribution plots method of the EnvironmentAnalysis class. It
Expand Down
136 changes: 94 additions & 42 deletions tests/unit/test_units.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,49 @@
import pytest

from rocketpy import Function
from rocketpy.units import conversion_factor, convert_temperature, convert_units
from rocketpy.units import (
conversion_factor,
convert_temperature,
convert_to_base_unit,
convert_units,
)


# One of each unit and its exact value in the base unit, by SI definition.
UNIT_DEFINITIONS = [
("mm", "m", 1e-3),
("cm", "m", 1e-2),
("dm", "m", 1e-1),
("dam", "m", 1e1),
("hm", "m", 1e2),
("km", "m", 1e3),
("ft", "m", 0.3048),
("in", "m", 0.0254),
("mi", "m", 1609.344),
("nmi", "m", 1852),
("yd", "m", 0.9144),
("km/h", "m/s", 1 / 3.6),
("knot", "m/s", 1852 / 3600),
("mph", "m/s", 1609.344 / 3600),
("ft/s", "m/s", 0.3048),
("gs", "m/s^2", 9.80665),
("ft/s^2", "m/s^2", 0.3048),
("hPa", "Pa", 1e2),
("kPa", "Pa", 1e3),
("MPa", "Pa", 1e6),
("bar", "Pa", 1e5),
("atm", "Pa", 101325),
("mmHg", "Pa", 133.322387415),
("inHg", "Pa", 25.4 * 133.322387415),
("min", "s", 60),
("h", "s", 3600),
("d", "s", 86400),
("mg", "kg", 1e-6),
("g", "kg", 1e-3),
("lb", "kg", 0.45359237),
("deg", "rad", np.pi / 180),
("grad", "rad", np.pi / 200),
]


class TestConvertTemperature:
Expand Down Expand Up @@ -68,54 +110,17 @@ def test_conversion_factor_invalid_conversion(self):
class TestConvertUnits:
"""Tests for the convert_units function."""

@pytest.mark.parametrize(
"unit, base_unit, value_in_base",
[
("mm", "m", 1e-3),
("cm", "m", 1e-2),
("dm", "m", 1e-1),
("dam", "m", 1e1),
("hm", "m", 1e2),
("km", "m", 1e3),
("ft", "m", 0.3048),
("in", "m", 0.0254),
("mi", "m", 1609.344),
("nmi", "m", 1852),
("yd", "m", 0.9144),
("km/h", "m/s", 1 / 3.6),
("knot", "m/s", 1852 / 3600),
("mph", "m/s", 1609.344 / 3600),
("ft/s", "m/s", 0.3048),
("gs", "m/s^2", 9.80665),
("ft/s^2", "m/s^2", 0.3048),
("hPa", "Pa", 1e2),
("kPa", "Pa", 1e3),
("MPa", "Pa", 1e6),
("bar", "Pa", 1e5),
("atm", "Pa", 101325),
("mmHg", "Pa", 133.322387415),
("inHg", "Pa", 3386.389),
("min", "s", 60),
("h", "s", 3600),
("d", "s", 86400),
("mg", "kg", 1e-6),
("g", "kg", 1e-3),
("lb", "kg", 0.45359237),
("deg", "rad", np.pi / 180),
("grad", "rad", np.pi / 200),
],
)
@pytest.mark.parametrize("unit, base_unit, value_in_base", UNIT_DEFINITIONS)
def test_convert_units_matches_unit_definitions(
self, unit, base_unit, value_in_base
):
"""One of each unit should convert to its defined value in the base
unit, and back. The references are the exact SI definitions, so the
tolerance only allows for the rounded pound and mercury constants."""
unit, and back. The references are the exact SI definitions."""
assert convert_units(1, unit, base_unit) == pytest.approx(
value_in_base, rel=1e-5
value_in_base, rel=1e-9
)
assert convert_units(value_in_base, base_unit, unit) == pytest.approx(
1, rel=1e-5
1, rel=1e-9
)

def test_convert_units_same_unit(self):
Expand Down Expand Up @@ -172,3 +177,50 @@ def test_convert_units_function_temperature_output(self):
assert converted.__outputs__ == ["Temperature (degC)"]
assert converted.__interpolation__ == "linear"
assert converted.__extrapolation__ == "constant"

@pytest.mark.parametrize("unit, base_unit, value_in_base", UNIT_DEFINITIONS)
def test_convert_units_function_matches_unit_definitions(
self, unit, base_unit, value_in_base
):
"""A Function should be converted with the same factors as a scalar,
on either axis, without changing the Function passed in."""
source = np.array([[1.0, 1.0], [2.0, 2.0]])
function = Function(source.copy(), inputs=f"x ({unit})", outputs=f"y ({unit})")

converted_x = convert_units(function, unit, base_unit, axis=0)
converted_y = convert_units(function, unit, base_unit, axis=1)

np.testing.assert_allclose(
converted_x.get_source()[:, 0], source[:, 0] * value_in_base, rtol=1e-9
)
np.testing.assert_allclose(
converted_y.get_source()[:, 1], source[:, 1] * value_in_base, rtol=1e-9
)
assert converted_x.__inputs__ == [f"x ({base_unit})"]
assert converted_y.__outputs__ == [f"y ({base_unit})"]
np.testing.assert_array_equal(function.get_source(), source)
assert function.__inputs__ == [f"x ({unit})"]
assert function.__outputs__ == [f"y ({unit})"]


class TestConvertToBaseUnit:
"""Tests for the convert_to_base_unit function."""

@pytest.mark.parametrize("unit, base_unit, value_in_base", UNIT_DEFINITIONS)
def test_convert_to_base_unit_matches_unit_definitions(
self, unit, base_unit, value_in_base
): # pylint: disable=unused-argument
assert convert_to_base_unit(1, unit) == pytest.approx(value_in_base, rel=1e-9)

def test_convert_to_base_unit_temperature_to_kelvin(self):
assert convert_to_base_unit(0, "degC") == pytest.approx(273.15)
assert convert_to_base_unit(32, "degF") == pytest.approx(273.15)

def test_convert_to_base_unit_leaves_array_unchanged(self):
values = np.array([1.0, 2.0])
convert_to_base_unit(values, "km")
np.testing.assert_array_equal(values, [1.0, 2.0])

def test_convert_to_base_unit_unsupported_unit(self):
with pytest.raises(ValueError, match="Unit 'furlong' is not supported."):
convert_to_base_unit(1, "furlong")