Tools functions#
The module rocketpy.tools contains a set of functions that are used throughout the rocketpy package. These functions are not specific to any particular class or module, and are used to perform general tasks that are required by multiple classes or modules. These functions can be modified or expanded to suit the needs of other modules and may present breaking changes between minor versions if necessary, although this will be always avoided.
- rocketpy.tools.deprecated(reason=None, version=None, alternative=None)[source]#
Decorator to mark functions or methods as deprecated.
This decorator issues a DeprecationWarning when the decorated function is called, indicating that it will be removed in future versions.
- Parameters:
reason (
str, optional) – Custom deprecation message. If not provided, a default message will be used.version (
str, optional) – Version when the function will be removed. If provided, it will be included in the warning message.alternative (
str, optional) – Name of the alternative function/method that should be used instead. If provided, it will be included in the warning message.
- Returns:
The decorated function with deprecation warning functionality.
- Return type:
callable
Examples
>>> @deprecated(reason="This function is obsolete", version="v2.0.0", ... alternative="new_function") ... def old_function(): ... return "old result"
>>> @deprecated() ... def another_old_function(): ... return "result"
- rocketpy.tools.tuple_handler(value)[source]#
Transforms the input value into a tuple that represents a range. If the input is an int or float, the output is a tuple from zero to the input value. If the input is a tuple or list, the output is a tuple with the same range.
- Parameters:
value (
int,float,tuple,list) – Input value.- Returns:
Tuple that represents the inputted range.
- Return type:
tuple
- rocketpy.tools.calculate_cubic_hermite_coefficients(x0, x1, y0, yp0, y1, yp1)[source]#
Calculate the coefficients of a cubic Hermite interpolation function. The function is defined as ax**3 + bx**2 + cx + d.
- Parameters:
x0 (
float) – Position of the first point.x1 (
float) – Position of the second point.y0 (
float) – Value of the function evaluated at the first point.yp0 (
float) – Value of the derivative of the function evaluated at the first point.y1 (
float) – Value of the function evaluated at the second point.yp1 (
float) – Value of the derivative of the function evaluated at the second point.
- Returns:
The coefficients of the cubic Hermite interpolation function.
- Return type:
tuple[float,float,float,float]
- rocketpy.tools.find_roots_cubic_function(a, b, c, d)[source]#
Calculate the roots of a cubic function using Cardano’s method.
This method applies Cardano’s method to find the roots of a cubic function of the form ax^3 + bx^2 + cx + d. The roots may be complex numbers.
- Parameters:
a (
float) – Coefficient of the cubic term (x^3).b (
float) – Coefficient of the quadratic term (x^2).c (
float) – Coefficient of the linear term (x).d (
float) – Constant term.
- Returns:
A tuple containing the real and complex roots of the cubic function. Note that the roots may be complex numbers. The roots are ordered in the tuple as x1, x2, x3.
- Return type:
tuple[complex,complex,complex]
References
Cardano’s method: https://en.wikipedia.org/wiki/Cubic_function#Cardano’s_method
Examples
>>> from rocketpy.tools import find_roots_cubic_function >>> import cmath
First we define the coefficients of the function ax**3 + bx**2 + cx + d >>> a, b, c, d = 1, -3, -1, 3 >>> x1, x2, x3 = find_roots_cubic_function(a, b, c, d) >>> cmath.isclose(x1, (-1+0j)) True
To get the real part of the roots, use the real attribute of the complex number. >>> x1.real, x2.real, x3.real (-1.0, 3.0, 1.0)
- rocketpy.tools.find_root_linear_interpolation(x0, x1, y0, y1, y)[source]#
Calculate the root of a linear interpolation function.
This method calculates the root of a linear interpolation function given two points (x0, y0) and (x1, y1) and a value y. The function is defined as y = m*x + c.
- Parameters:
x0 (
float) – Position of the first point.x1 (
float) – Position of the second point.y0 (
float) – Value of the function evaluated at the first point.y1 (
float) – Value of the function evaluated at the second point.y (
float) – Value of the function at the desired point.
- Returns:
The root of the linear interpolation function. This represents the value of x at which the function evaluates to y.
- Return type:
float
Examples
>>> from rocketpy.tools import find_root_linear_interpolation >>> x0, x1, y0, y1, y = 0, 1, 0, 1, 0.5 >>> x = find_root_linear_interpolation(x0, x1, y0, y1, y) >>> x 0.5
- rocketpy.tools.bilinear_interpolation(x, y, x1, x2, y1, y2, z11, z12, z21, z22)[source]#
Bilinear interpolation. It considers the values of the four points around the point to be interpolated and returns the interpolated value. Made with a lot of help from GitHub Copilot.
- Parameters:
x (
float) – x coordinate to which the value will be interpolated.y (
float) – y coordinate to which the value will be interpolated.x1 (
float) – x coordinate of the first point.x2 (
float) – x coordinate of the second point.y1 (
float) – y coordinate of the first point.y2 (
float) – y coordinate of the second point.z11 (
float) – Value at the first point.z12 (
float) – Value at the second point.z21 (
float) – Value at the third point.z22 (
float) – Value at the fourth point.
- Returns:
Interpolated value.
- Return type:
float
Examples
>>> from rocketpy.tools import bilinear_interpolation >>> bilinear_interpolation(0.5, 0.5, 0, 1, 0, 1, 0, 1, 1, 0) 0.5
- rocketpy.tools.get_distribution(distribution_function_name, random_number_generator=None)[source]#
Sets the distribution function to be used in the monte carlo analysis.
- Parameters:
distribution_function_name (
string) – The type of distribution to be used in the analysis. It can be ‘uniform’, ‘normal’, ‘lognormal’, etc.random_number_generator (
np.random.Generator, optional) – The random number generator to be used. If None, the default generatornumpy.random.default_rngis used.
- Returns:
The distribution function to be used in the analysis.
- Return type:
np.random distribution function
- rocketpy.tools.haversine(lat0, lon0, lat1, lon1, earth_radius=6378100.0)[source]#
Returns the distance between two points in meters. The points are defined by their latitude and longitude coordinates.
- Parameters:
lat0 (
float) – Latitude of the first point, in degrees.lon0 (
float) – Longitude of the first point, in degrees.lat1 (
float) – Latitude of the second point, in degrees.lon1 (
float) – Longitude of the second point, in degrees.earth_radius (
float, optional) – Earth’s radius in meters. Default value is 6.3781e6.
- Returns:
Distance between the two points in meters.
- Return type:
float
- rocketpy.tools.inverted_haversine(lat0, lon0, distance, bearing, earth_radius=6378100.0)[source]#
Returns a tuple with new latitude and longitude coordinates considering a displacement of a given distance in a given direction (bearing compass) starting from a point defined by (lat0, lon0). This is the opposite of Haversine function.
- Parameters:
lat0 (
float) – Origin latitude coordinate, in degrees.lon0 (
float) – Origin longitude coordinate, in degrees.distance (
float) – Distance from the origin point, in meters.bearing (
float) – Azimuth (or bearing compass) from the origin point, in degrees.earth_radius (
float, optional) – Earth radius, in meters. Default value is 6.3781e6. See the Environment.calculateEarthRadius() function for more accuracy.
- Returns:
lat1 (
float) – New latitude coordinate, in degrees.lon1 (
float) – New longitude coordinate, in degrees.
- rocketpy.tools.mercator_to_wgs84(x, y, earth_radius=6378100.0)[source]#
Convert Web Mercator (EPSG:3857) coordinates to WGS84 (EPSG:4326) coordinates.
This function converts coordinates from Web Mercator projection to WGS84 latitude/longitude without requiring the pyproj dependency.
- Parameters:
x (
float) – X coordinate in Web Mercator projection (meters).y (
float) – Y coordinate in Web Mercator projection (meters).earth_radius (
float, optional) – Earth’s radius in meters. Default value is 6.3781e6.
- Returns:
A tuple containing (latitude, longitude) in degrees.
- Return type:
tuple[float,float]
- rocketpy.tools.convert_local_extent_to_wgs84(local_extent, origin_lat, origin_lon, earth_radius=6378100.0)[source]#
Convert local extent to geographic extent (latitude/longitude bounding box).
This function converts a local extent (bounding box in meters relative to an origin point) to a geographic extent (bounding box in latitude/longitude degrees).
- Parameters:
local_extent (
list[float]) – Local extent [x_min, x_max, y_min, y_max] in meters relative to the origin.origin_lat (
float) – Origin latitude in degrees.origin_lon (
float) – Origin longitude in degrees.earth_radius (
float, optional) – Earth’s radius in meters. Default value is 6.3781e6.
- Returns:
Geographic extent (west, south, east, north) in degrees.
- Return type:
tuple[float,float,float,float]
- rocketpy.tools.convert_mercator_extent_to_local(mercator_extent, origin_lat, origin_lon, earth_radius=6378100.0)[source]#
Convert Mercator extent to local extent (coordinates relative to origin).
This function converts a geographic extent from Web Mercator coordinates to a local extent (bounding box in meters relative to an origin point).
- Parameters:
mercator_extent (
list[float]) – Mercator extent [minX, maxX, minY, maxY] in meters.origin_lat (
float) – Origin latitude in degrees.origin_lon (
float) – Origin longitude in degrees.earth_radius (
float, optional) – Earth’s radius in meters. Default value is 6.3781e6.
- Returns:
Local extent [x_min, x_max, y_min, y_max] in meters relative to the origin.
- Return type:
list[float]
- rocketpy.tools.calculate_confidence_ellipse(list_x, list_y, n_std=3)[source]#
Given a list of x and y coordinates, calculate the confidence ellipse parameters (theta, width, height) for a given number of standard deviations.
- rocketpy.tools.create_matplotlib_ellipse(x, y, w, h, theta, rgb, opacity)[source]#
Create a matplotlib.patches.Ellipse object.
- Parameters:
x (
listornp.array) – List of x coordinates.y (
listornp.array) – List of y coordinates.w (
float) – Width of the ellipse.h (
float) – Height of the ellipse.theta (
float) – Angle of the ellipse.rgb (
tuple) – Tuple containing the color of the ellipse in RGB format. For example, (0, 0, 1) will create a blue ellipse.
- Returns:
One matplotlib.patches.Ellipse objects.
- Return type:
matplotlib.patches.Ellipse
- rocketpy.tools.generate_monte_carlo_ellipses(apogee_x=array([], dtype=float64), apogee_y=array([], dtype=float64), impact_x=array([], dtype=float64), impact_y=array([], dtype=float64), n_apogee=[1, 2, 3], n_impact=[1, 2, 3], apogee_rgb=(0, 1, 0), impact_rgb=(0, 0, 1), opacity=0.2)[source]#
Function to generate Monte Carlo ellipses for apogee and impact points.
- Parameters:
apogee_x (
np.ndarray, optional) – Array of x-coordinates for apogee points, by default np.array([])apogee_y (
np.ndarray, optional) – Array of y-coordinates for apogee points, by default np.array([])impact_x (
np.ndarray, optional) – Array of x-coordinates for impact points, by default np.array([])impact_y (
np.ndarray, optional) – Array of y-coordinates for impact points, by default np.array([])n_apogee (
list, optional) – List of integers representing the number of standard deviations for apogee ellipses, by default [1, 2, 3]n_impact (
list, optional) – List of integers representing the number of standard deviations for impact ellipses, by default [1, 2, 3]apogee_rgb (
tuple, optional) – RGB color tuple for apogee ellipses, by default (0, 1, 0).impact_rgb (
tuple, optional) – RGB color tuple for impact ellipses, by default (0, 0, 1).opacity (
float, optional) – The alpha parameter for the solid face of the ellipses, by default 0.2
- Returns:
A tuple containing two lists: - List of matplotlib.patches.Ellipse objects for apogee ellipses. - List of matplotlib.patches.Ellipse objects for impact ellipses.
- Return type:
tuple[list[matplotlib.patches.Ellipse],list[matplotlib.patches.Ellipse]]
- rocketpy.tools.generate_monte_carlo_ellipses_coordinates(ellipses, origin_lat, origin_lon, resolution=100)[source]#
Generate a list of latitude and longitude points for each ellipse in ellipses.
- Parameters:
ellipses (
list[matplotlib.patches.Ellipse]) – List of matplotlib.patches.Ellipse objects.origin_lat (
float) – Latitude of the origin of the coordinate system.origin_lon (
float) – Longitude of the origin of the coordinate system.resolution (
int, optional) – Number of points to generate for each ellipse, by default 100
- Returns:
List of lists of tuples containing the latitude and longitude of each point in each ellipse.
- Return type:
list[list[tuple[float,float]]]
- rocketpy.tools.flatten_dict(original_dict)[source]#
Flatten a dictionary for easy handling of nested variables
This function is mainly used for handling data in sensitivity analysis and in the MRS.
- Parameters:
original_dict (
dict) – A dictionary possibly containing nested variables. This means that a key might contain another dictionary inside of it.- Returns:
flatted_dict – The flatted dictionary which, ideally, should not contain nested variables. All nested information should be available directly in the first level (access by key). Variables that were available inside the first level retain their original key name. Variables that were nested are created by appending the name of the outer key used to access it concatenated with a ‘_’ and the key name of the variable.
- Return type:
dict
- rocketpy.tools.load_monte_carlo_data(input_filename, output_filename, parameters_list, target_variables_list)[source]#
Reads MonteCarlo simulation data file and builds parameters and flight variables matrices
- Parameters:
input_filename (
str) – Input file exported by MonteCarlo class. Each line is a sample unit described by a dictionary where keys are parameters names and the values are the sampled parameters values.output_filename (
str) – Output file exported by MonteCarlo.simulate function. Each line is a sample unit described by a dictionary where keys are target variables names and the values are the obtained values from the flight simulation.parameters_list (
list[str]) – List of parameters whose values will be extracted.target_variables_list (
list[str]) – List of target variables whose values will be extracted.
- Returns:
parameters_matrix (
np.matrix) – Numpy matrix containing input parameters values. Each column correspond to a parameter in the same order specified by ‘parameters_list’ input.target_variables_matrix (
np.matrix) – Numpy matrix containing target variables values. Each column correspond to a target variable in the same order specified by ‘target_variables_list’ input.
- rocketpy.tools.find_two_closest_integers(number)[source]#
Find the two closest integer factors of a number.
- Parameters:
number (
int)- Returns:
Two closest integer factors of the number.
- Return type:
tuple
Examples
>>> from rocketpy.tools import find_two_closest_integers >>> find_two_closest_integers(10) (2, 5) >>> find_two_closest_integers(12) (3, 4) >>> find_two_closest_integers(13) (1, 13) >>> find_two_closest_integers(150) (10, 15)
- rocketpy.tools.time_num_to_date_string(time_num, units, timezone, calendar='gregorian')[source]#
Convert time number (usually hours before a certain date) into two strings: one for the date (example: 2022.04.31) and one for the hour (example: 14). See cftime.num2date for details on units and calendar. Automatically converts time number from UTC to local time zone based on lat, lon coordinates. This function was created originally for the EnvironmentAnalysis class.
- Parameters:
time_num (
float) – Time number to be converted.units (
str) – Units of the time number. See cftime.num2date for details.timezone (
pytz.timezone) – Timezone to which the time number will be converted. See pytz.timezone for details.calendar (
str, optional) – Calendar to be used. See cftime.num2date for details.
- Returns:
date_string (
str) – Date string.hour_string (
str) – Hour string.date_time (
datetime.datetime) – Datetime object.
- rocketpy.tools.geopotential_height_to_geometric_height(geopotential_height, radius=63781370.0)[source]#
Converts geopotential height to geometric height.
- Parameters:
geopotential_height (
float) – Geopotential height in meters. This vertical coordinate, referenced to Earth’s mean sea level, accounts for variations in gravity with altitude and latitude.radius (
float, optional) – The Earth’s radius in meters, defaulting to 6378137.0.
- Returns:
geometric_height – Geometric height in meters.
- Return type:
float
Examples
>>> from rocketpy.tools import geopotential_height_to_geometric_height >>> geopotential_height_to_geometric_height(0) 0.0 >>> geopotential_height_to_geometric_height(10000) 10001.568101798659 >>> geopotential_height_to_geometric_height(20000) 20006.2733909262
- rocketpy.tools.geopotential_to_height_asl(geopotential, radius=63781370, g=9.80665)[source]#
Compute height above sea level from geopotential.
Source: https://en.wikipedia.org/wiki/Geopotential
- Parameters:
geopotential (
float) – Geopotential in m^2/s^2. It is the geopotential value at a given pressure level, to be converted to height above sea level.radius (
float, optional) – Earth radius in m. Default is 63781370 m.g (
float, optional) – Gravity acceleration in m/s^2. Default is 9.80665 m/s^2.
- Returns:
geopotential_to_height_asl – Height above sea level in m
- Return type:
float
Examples
>>> from rocketpy.tools import geopotential_to_height_asl >>> geopotential_to_height_asl(0) 0.0 >>> geopotential_to_height_asl(100000) 10198.792680243916 >>> geopotential_to_height_asl(200000) 20400.84750449947
- rocketpy.tools.geopotential_to_height_agl(geopotential, elevation, radius=63781370, g=9.80665)[source]#
Compute height above ground level from geopotential and elevation.
- Parameters:
geopotential (
float) – Geopotential in m^2/s^2. It is the geopotential value at a given pressure level, to be converted to height above ground level.elevation (
float) – Surface elevation in mradius (
float, optional) – Earth radius in m. Default is 63781370 m.g (
float, optional) – Gravity acceleration in m/s^2. Default is 9.80665 m/s^2.
- Returns:
height_above_ground_level – Height above ground level in m
- Return type:
float
Examples
>>> from rocketpy.tools import geopotential_to_height_agl >>> geopotential_to_height_agl(0, 0) 0.0 >>> geopotential_to_height_agl(100000, 0) 10198.792680243916 >>> geopotential_to_height_agl(100000, 1000) 9198.792680243916
- rocketpy.tools.find_closest(ordered_sequence, value)[source]#
Find the index of the closest value to a given value within an ordered sequence.
- Parameters:
ordered_sequence (
list) – A sequence of values that is ordered from smallest to largest.value (
float) – The value to which you want to find the closest value.
- Returns:
index – The index of the closest value to the given value within the ordered sequence. If the given value is lower than the first value in the sequence, then 0 is returned. If the given value is greater than the last value in the sequence, then the index of the last value in the sequence is returned.
- Return type:
int
Examples
>>> from rocketpy.tools import find_closest >>> find_closest([1, 2, 3, 4, 5], 0) 0 >>> find_closest([1, 2, 3, 4, 5], 1.5) 0 >>> find_closest([1, 2, 3, 4, 5], 2.0) 1 >>> find_closest([1, 2, 3, 4, 5], 2.8) 2 >>> find_closest([1, 2, 3, 4, 5], 4.9) 4 >>> find_closest([1, 2, 3, 4, 5], 5.5) 4 >>> find_closest([], 10) 0
- rocketpy.tools.import_optional_dependency(name)[source]#
Import an optional dependency. If the dependency is not installed, an ImportError is raised. This function is based on the implementation found in pandas repository: github.com/pandas-dev/pandas/blob/main/pandas/compat/_optional.py
- Parameters:
name (
str) – The name of the module to import. Can be used to import submodules too. The name will be used as an argument to importlib.import_module method.Examples
---------
import_optional_dependency (>>> from rocketpy.tools import)
import_optional_dependency("matplotlib") (>>> matplotlib =)
matplotlib.__name__ (>>>)
'matplotlib'
import_optional_dependency("matplotlib.pyplot") (>>> plt =)
plt.__name__ (>>>)
'matplotlib.pyplot'
- rocketpy.tools.check_requirement_version(module_name, version)[source]#
This function tests if a module is installed and if the version is correct. If the module is not installed, an ImportError is raised. If the version is not correct, an error is raised.
- Parameters:
module_name (
str) – The name of the module to be tested.version (
str) – The version of the module that is required. The string must start with one of the following operators: “>”, “<”, “>=”, “<=”, “==”, “!=”.Example
--------
check_requirement_version (>>> from rocketpy.tools import)
check_requirement_version("numpy" (>>>)
">=1.0.0")
True
check_requirement_version("matplotlib" (>>>)
">=3.0")
True
- rocketpy.tools.parallel_axis_theorem_from_com(com_inertia_moment, mass, distance)[source]#
Calculates the moment of inertia of a object relative to a new axis using the parallel axis theorem. The new axis is parallel to and at a distance ‘distance’ from the original axis, which must passes through the object’s center of mass.
- Parameters:
com_inertia_moment (
float) – Moment of inertia relative to the center of mass of the object.mass (
float) – Mass of the object.distance (
float) – Perpendicular distance between the original and new axis.
- Returns:
Moment of inertia relative to the new axis.
- Return type:
float
- rocketpy.tools.quaternions_to_precession(e0, e1, e2, e3)[source]#
Calculates the Precession angle
- Parameters:
e0 (
float) – Euler parameter 0, must be between -1 and 1e1 (
float) – Euler parameter 1, must be between -1 and 1e2 (
float) – Euler parameter 2, must be between -1 and 1e3 (
float) – Euler parameter 3, must be between -1 and 1
- Returns:
Euler Precession angle in degrees
- Return type:
float
References
Baruh, Haim. Analytical dynamics
- rocketpy.tools.quaternions_to_spin(e0, e1, e2, e3)[source]#
Calculates the Spin angle from quaternions.
- Parameters:
e0 (
float) – Euler parameter 0, must be between -1 and 1e1 (
float) – Euler parameter 1, must be between -1 and 1e2 (
float) – Euler parameter 2, must be between -1 and 1e3 (
float) – Euler parameter 3, must be between -1 and 1
- Returns:
Euler Spin angle in degrees
- Return type:
float
References
Baruh, Haim. Analytical dynamics
- rocketpy.tools.quaternions_to_nutation(e1, e2)[source]#
Calculates the Nutation angle from quaternions.
- Parameters:
e1 (
float) – Euler parameter 1, must be between -1 and 1e2 (
float) – Euler parameter 2, must be between -1 and 1
- Returns:
Euler Nutation angle in degrees
- Return type:
float
References
Baruh, Haim. Analytical dynamics
- rocketpy.tools.normalize_quaternions(quaternions)[source]#
Normalizes the quaternions (Euler parameters) to have unit magnitude.
- Parameters:
quaternions (
tuple) – Tuple containing the Euler parameters e0, e1, e2, e3- Returns:
Tuple containing the Euler parameters e0, e1, e2, e3
- Return type:
tuple
- rocketpy.tools.euler313_to_quaternions(phi, theta, psi)[source]#
Convert 3-1-3 Euler angles to Euler parameters (quaternions).
- Parameters:
phi (
float) – Rotation angle around the z-axis (in radians). Represents the precession angle or the roll angle.theta (
float) – Rotation angle around the x-axis (in radians). Represents the nutation angle or the pitch angle.psi (
float) – Rotation angle around the z-axis (in radians). Represents the spin angle or the roll angle.
- Returns:
The Euler parameters or quaternions (e0, e1, e2, e3)
- Return type:
tuple[float,float,float,float]
- rocketpy.tools.get_matplotlib_supported_file_endings()[source]#
Gets the file endings supported by matplotlib.
- Returns:
List of file endings prepended with a dot
- Return type:
list[str]
- rocketpy.tools.to_hex_encode(obj, encoder=<function b85encode>)[source]#
Converts an object to hex representation using dill.
- Parameters:
obj (
object) – Object to be converted to hex.encoder (
callable, optional) – Function to encode the bytes. Default is base64.b85encode.
- Returns:
Object converted to bytes.
- Return type:
bytes
- rocketpy.tools.from_hex_decode(obj_bytes, decoder=<function b85decode>)[source]#
Converts an object from hex representation using dill.
- Parameters:
obj_bytes (
str) – Hex string to be converted to object.decoder (
callable, optional) – Function to decode the bytes. Default is base64.b85decode.
- Returns:
Object converted from bytes.
- Return type:
object
- rocketpy.tools.find_obj_from_hash(obj, hash_, depth_limit=None)[source]#
Searches the object (and its children) for an object whose ‘__rpy_hash’ field has a particular hash value.
- Parameters:
obj (
object) – Object to search.hash (
int) – Hash value to search for in the ‘__rpy_hash’ field.depth_limit (
int, optional) – Maximum depth to search recursively. If None, no limit.
- Returns:
The object whose ‘__rpy_hash’ matches
hash_, or None if not found.- Return type:
object