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
3 changes: 3 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -41,6 +41,9 @@ Attention: The newest changes should be on top -->
### Fixed

- BUG: fetch Windy forecasts from the official Point Forecast API, which requires an API key [#1254](https://github.com/RocketPy-Team/RocketPy/pull/1254)
- BUG: Fix inverted and wrong factors in the units conversion table. Results computed with `ft/s^2`, `atm`, `mg`, `g`, `deg` and `grad` change, and those with `lb`, `mmHg` and `inHg` change by at most about 3 parts per million. [#1199](https://github.com/RocketPy-Team/RocketPy/pull/1199)
- BUG: Use one height unit throughout `EnvironmentAnalysis`. With the imperial unit system, the pressures 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. [#1199](https://github.com/RocketPy-Team/RocketPy/pull/1199)
- BUG: `FlightDataImporter` converts the time column when its unit is given, and raises `ValueError` for unsupported units (it was `KeyError`), for a time column in a unit that is not of time, and for accelerations in mass or angle units. [#1199](https://github.com/RocketPy-Team/RocketPy/pull/1199)

## [v1.14.0] - 2026-11-29

Expand Down
23 changes: 12 additions & 11 deletions rocketpy/environment/environment_analysis.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,7 +153,8 @@ def __init__( # pylint: disable=too-many-statements
Arguments for setting the forecast on the Environment class. With this argument
it is possible to change the forecast model being used.
max_expected_altitude : float, optional
Maximum expected altitude for your analysis. This is used to calculate
Maximum expected altitude for your analysis, above ground level and
in the length unit of ``unit_system``. This is used to calculate
plot limits from pressure level data profiles. If None is set, the
maximum altitude will be calculated from the pressure level data.
Default is None.
Expand Down Expand Up @@ -208,7 +209,7 @@ def __init__( # pylint: disable=too-many-statements
date=hour_date_time,
latitude=self.latitude,
longitude=self.longitude,
elevation=self.converted_elevation,
elevation=self.original_elevation,
)
forecast_args = forecast_args or {"type": "Forecast", "file": "GFS"}
env.set_atmospheric_model(**forecast_args)
Expand Down Expand Up @@ -487,7 +488,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 Expand Up @@ -982,7 +983,7 @@ def converted_pressure_level_data(self):
self.updated_units["height_ASL"] = self.unit_system["length"]
# Convert y axis
variable = convert_units(
variable=value,
variable=variable,
from_unit=self.current_units[key],
to_unit=conversion_dict[key],
axis=1,
Expand Down Expand Up @@ -2102,7 +2103,7 @@ def altitude_AGL_range(self): # pylint: disable=invalid-name
"""The altitude range for the pressure level data. The minimum altitude
is always 0, and the maximum altitude is the maximum altitude of the
pressure level data, or the maximum expected altitude if it is set.
Units are kept as they are in the original data.
Altitudes are in the length unit of the preferred unit system.

Returns
-------
Expand All @@ -2114,7 +2115,7 @@ def altitude_AGL_range(self): # pylint: disable=invalid-name
if self.max_expected_altitude is None:
max_altitudes = [
np.max(day_dict[hour]["wind_speed"].source[-1, 0])
for day_dict in self.original_pressure_level_data.values()
for day_dict in self.converted_pressure_level_data.values()
for hour in day_dict.keys()
]
max_altitude = np.min(max_altitudes)
Expand All @@ -2126,8 +2127,8 @@ def altitude_AGL_range(self): # pylint: disable=invalid-name
def altitude_list(self, points=200): # pylint: disable=property-with-parameters
"""A list of altitudes, from 0 to the maximum altitude of the pressure
level data, or the maximum expected altitude if it is set. The list is
cached so that the computation is only done once. Units are kept as they
are in the original data.
cached so that the computation is only done once. Altitudes are in the
length unit of the preferred unit system.

Parameters
----------
Expand All @@ -2152,7 +2153,7 @@ def pressure_at_1000ft_list(self):
"""
return [
day_dict[hour]["pressure"](
convert_units(1000, "ft", self.current_units["height_ASL"])
convert_units(1000, "ft", self.unit_system["length"])
)
for day_dict in self.converted_pressure_level_data.values()
for hour in day_dict.keys()
Expand All @@ -2174,7 +2175,7 @@ def pressure_at_10000ft_list(self):
# Pressure at 10000 feet
return [
day_dict[hour]["pressure"](
convert_units(10000, "ft", self.current_units["height_ASL"])
convert_units(10000, "ft", self.unit_system["length"])
)
for day_dict in self.converted_pressure_level_data.values()
for hour in day_dict.keys()
Expand All @@ -2196,7 +2197,7 @@ def pressure_at_30000ft_list(self):
# Pressure at 30000 feet
return [
day_dict[hour]["pressure"](
convert_units(30000, "ft", self.current_units["height_ASL"])
convert_units(30000, "ft", self.unit_system["length"])
)
for day_dict in self.converted_pressure_level_data.values()
for hour in day_dict.keys()
Expand Down
8 changes: 6 additions & 2 deletions rocketpy/plots/environment_analysis_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -1535,9 +1535,13 @@ def wind_speed_profile_grid(self, clear_range_limits=False, *, filename=None):
if self.env_analysis.forecast:
forecast = self.env_analysis.forecast
y = self.env_analysis.average_wind_speed_profile_by_hour[hour][1]
x = forecast[hour].wind_speed.get_value_opt(y) * convert_units(
1, "m/s", self.env_analysis.unit_system["wind_speed"]
altitude_asl_m = (
convert_units(y, self.env_analysis.unit_system["length"], "m")
+ self.env_analysis.original_elevation
)
x = forecast[str(hour)].wind_speed.get_value_opt(
altitude_asl_m
) * convert_units(1, "m/s", self.env_analysis.unit_system["wind_speed"])
ax.plot(x, y, "b--")

ax.label_outer()
Expand Down
86 changes: 75 additions & 11 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 @@ -47,6 +47,12 @@
"z": "Position z (m)",
}

# Used to reject units of another quantity that are easily given by mistake,
# such as "m" (meter) for a time or "g" (gram) for an acceleration.
TIME_UNITS = ("s", "min", "h", "d")
MASS_AND_ANGLE_UNITS = ("mg", "g", "kg", "lb", "rad", "deg", "grad")
ACCELERATION_ATTRIBUTES = ("acceleration", "ax", "ay", "az")


class FlightDataImporter:
"""A class used to import flight data from a .csv or .txt file and build an
Expand Down Expand Up @@ -80,11 +86,16 @@ def __init__(
dictionary keys must be the original column names and the values
must be the desired column names.
units : dict, optional
A dictionary mapping column names to desired units.
A dictionary mapping column names to the units of their data.
Defaults to None, which will consider that all the data is in SI.
The dictionary keys must be the original column names and the
values must be the units of the data in the column. There is no need
to specify the units for a column that is already in SI.
The supported units are the ones in
``rocketpy.units.UNITS_CONVERSION_DICT``, plus "K", "degC" and
"degF" for temperatures, which are converted to K. The time column
is converted to seconds. Note that "g" is gram: accelerations in
multiples of standard gravity must use "gs".
interpolation : str, optional
The interpolation method to use for missing data.
Defaults to "linear", see rocketpy.mathutils.Function for more
Expand All @@ -98,6 +109,13 @@ def __init__(
encoding : str, optional
The encoding of the data file. Defaults to "utf-8".

Raises
------
ValueError
If a unit is not supported, if it is not a time unit for the time
column, or if it is a mass or angle unit for the ``acceleration``,
``ax``, ``ay`` and ``az`` columns.

Notes
-----
Try to avoid using forbidden characters in the column names, such as
Expand Down Expand Up @@ -200,9 +218,9 @@ def __handle_dataset(self, filepath, delimiter, encoding):
]

def __define_time_column(self, filepath):
"""Defines the time column of the data frame. The time column must be in
seconds and must be named 'time'. Alternatively, you can specify the
time column using the 'columns_map' argument.
"""Defines the time column of the data frame. The time column must be
named 'time'. Alternatively, you can specify the time column using the
'columns_map' argument.

Parameters
----------
Expand All @@ -228,12 +246,49 @@ def __define_time_column(self, filepath):
return None
raise ValueError(
"Unable to determine the time column, please specify it. The time column "
+ "must be in seconds and must be named 'time'. Alternatively, you "
+ "must be named 'time'. Alternatively, you "
+ "can specify the time column using the 'columns_map' argument. "
+ "Available columns are: "
+ str(self._columns[filepath])
)

@staticmethod
def __convert_to_si(values, name, unit):
"""Converts the values of a column to SI.

Parameters
----------
values : numpy.ndarray
The values of the column, which are not modified.
name : str
The name of the attribute the column is saved to.
unit : str
The unit of the values.

Returns
-------
numpy.ndarray
The values in SI.

Raises
------
ValueError
If the unit is not supported or does not fit the attribute.
"""
converted = convert_to_base_unit(values, unit)
if name == "time" and unit not in TIME_UNITS:
raise ValueError(
f"Unit '{unit}' can't be used for '{name}'. "
f"The accepted units are: {', '.join(TIME_UNITS)}."
)
if name in ACCELERATION_ATTRIBUTES and unit in MASS_AND_ANGLE_UNITS:
raise ValueError(
f"Unit '{unit}' can't be used for '{name}'. "
"Use 'gs' for multiples of standard gravity."
)
logger.debug("Attribute '%s' converted from %s to SI", name, unit)
return converted

def __create_attributes(self, filepath, interpolation, extrapolation):
"""Creates the attributes to emulate a Flight object.

Expand All @@ -251,7 +306,8 @@ def __create_attributes(self, filepath, interpolation, extrapolation):
Raises
------
ValueError
If the time column is not found in the header of the file.
If the time column is not found in the header of the file, or if a
unit is not supported or does not fit its column.
"""
time_col = self._time_cols[filepath]
units = self._units[filepath]
Expand All @@ -267,6 +323,8 @@ def __create_attributes(self, filepath, interpolation, extrapolation):
+ "The available columns are:"
+ str(self._original_columns[filepath])
) from e
if units and time_col in units:
times = self.__convert_to_si(times, "time", units[time_col])

created = []
for col, name in self._columns_map[filepath].items():
Expand All @@ -287,8 +345,7 @@ def __create_attributes(self, filepath, interpolation, extrapolation):

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

# Create Function object and set as attribute
setattr(
Expand Down Expand Up @@ -329,8 +386,9 @@ def read_data(
A dictionary mapping column names to desired column names.
Defaults to None, which will keep the original column names.
units : dict, optional
A dictionary mapping column names to desired units.
A dictionary mapping column names to the units of their data.
Defaults to None, which will consider that all the data is in SI.
See the class constructor for the supported units.
interpolation : str, optional
The interpolation method to use for missing data.
Defaults to "linear", see rocketpy.mathutils.Function for more
Expand All @@ -348,6 +406,12 @@ def read_data(
-------
None

Raises
------
ValueError
If a unit is not supported, or does not fit its column. See the
class constructor for details.

Notes
-----
This method handles multiple files within the same path and processes
Expand All @@ -366,7 +430,7 @@ def read_data(
self._files.extend(list_of_files)

# Loop through the files and read each of them
for filepath in self._files:
for filepath in list_of_files:
self._units[filepath] = units
self._columns_map[filepath] = columns_map
self._encodings[filepath] = encoding
Expand Down
Loading
Loading