RocketPy Documentation

repository·master·Indexed 21 days ago

https://github.com/rocketpy-team/rocketpy

RocketPy is a high-fidelity 6 degrees of freedom (6DoF) trajectory simulation library for high-power rocketry written in Python. Version 1.13.0 supports nonlinear simulations with LSODA solvers, multi-stage rockets, motor modeling (Solid, Hybrid, and Liquid), and Monte Carlo dispersion analysis. It includes tools for weather modeling, aerodynamics via Barrowman equations, and parachute simulation, with integration for MATLAB and Google Earth (.kml) exports.

Tokens
62.1K
Snippets
172
Records
223
Agent score
76%

What's inside RocketPy

  1. Overview of RocketPy capabilities

    master

    RocketPy is a Python library designed for high-fidelity trajectory simulation in High-Power Rocketry. It provides a 6 degrees of freedom (6DoF) simulation environment that includes:

    • High-fidelity variable mass effects: Accurate modeling of mass changes during flight.
    • Descent modeling: Simulation of descent under parachutes.
    • Weather integration: Ability to import wind profiles and other weather datasets for realistic flight scenarios.
    • Complex mission profiles: Support for multi-stage rockets, design and trajectory optimization, and dispersion analysis.
  2. Overview of RocketPy features

    master

    RocketPy is a Python library for 6 degrees of freedom (6DoF) high-power rocket trajectory simulations. Key capabilities include:

    • 6DoF Simulations: Nonlinear simulations with rigorous mass variation treatment using LSODA solvers.
    • Weather Modeling: Support for International Standard Atmosphere (1976), custom profiles, Wyoming Soundings, and weather forecasts/ensembles.
    • Aerodynamics: Barrowman equations for lift and easy import of drag coefficients (e.g., from CFD).
    • Motor Models: Support for Solid, Hybrid, and Liquid motors using CSV or ENG file formats.
    • Parachutes: Simulation of descent with external trigger functions and sensor noise augmentation.
    • Advanced Analysis: Monte Carlo simulations for dispersion and sensitivity analysis, multi-stage rocket support, and MATLAB® integration.
  3. Overview of the Juno III rocket launch data

    master

    This dataset contains flight data for the Juno III rocket, designed by Projeto Jupiter (Univ. of São Paulo, Brazil). The rocket was launched during SACup 2023 on June 23rd.

    Flight Highlights:

    • Registered Apogee: 3213 m
    • Last Simulated Apogee: 3026.054 m
    • Flight Performance Note: Only the drogue chute was ejected during the flight.
  4. Use FlightComparator to validate simulations against external data

    master

    The rocketpy.simulation.FlightComparator class is used to compare a primary RocketPy Flight simulation (the "Reference") against external data sources like real flight logs (CSV, GPS), other simulators (OpenRocket, RASAero), or theoretical models.

    Unlike standard comparison tools that compare two RocketPy simulations, FlightComparator is specifically designed to handle alignment between different time steps and calculate error metrics such as RMSE (Root Mean Square Error) and MAE (Mean Absolute Error).

    from rocketpy.simulation import FlightComparator
    
    # Initialize with your reference flight
    comparator = FlightComparator(reference_flight)
  5. Use Function classes in RocketPy

    master
    In RocketPy, rocketpy.Function classes are used to define mathematical functions that can be used throughout the simulation. These functions can represent time-varying parameters, such as mass, thrust, or atmospheric properties. For detailed usage patterns and implementation details, refer to the Function Class Usage guide.
  6. Introduce dependency between parameters using Custom Samplers

    master

    By default, RocketPy's Monte Carlo simulations sample parameters independently. To model correlations between parameters (e.g., correlated wind speeds on the X and Y axes), you must implement a CustomSampler and use a shared generator object.

    The Core Pattern:

    1. Create a common generator class: This class generates multivariate samples (e.g., using np.random.multivariate_normal) and stores them in a list.
    2. Implement multiple CustomSampler subclasses: Each subclass represents one parameter. Instead of generating new random numbers, these samplers call the shared generator to retrieve specific indices/axes from the pre-generated sample list.
    3. Inject samplers into Stochastic objects: Pass the custom sampler instances into the relevant arguments of stochastic classes (like StochasticEnvironment).
    from rocketpy import Environment, StochasticEnvironment
    from datetime import datetime, timedelta
    import numpy as np
    
    # 1. Define a shared generator to handle correlations
    class BivariateGaussianGenerator:
        def __init__(self, mean, cov, seed=None):
            self.mean = mean
            self.cov = cov
            self.samples_list = []
            self.samples_generated = 0
            self.used_samples_x = 0
            self.used_samples_y = 0
            self.generate_samples(1000)
    
        def generate_samples(self, n_samples=1):
            samples = np.random.multivariate_normal(self.mean, self.cov, n_samples)
            self.samples_generated += n_samples
            self.samples_list += list(samples)
    
        def get_samples(self, n_samples, axis):
            # Logic to slice the pre-generated samples based on axis 'x' or 'y'
            # ... (implementation details)
            return samples_list
    
    # 2. Create specific samplers that use the generator
    class WindXSampler(CustomSampler):
        def __init__(self, generator):
            self.generator = generator
        def sample(self, n_samples=1):
            return self.generator.get_samples(n_samples, "x")
    
    class WindYSampler(CustomSampler):
        def __init__(self, generator):
            self.generator = generator
        def sample(self, n_samples=1):
            return self.generator.get_samples(n_samples, "y")
    
    # 3. Initialize and use in a StochasticEnvironment
    mean = [1, 2]
    cov_mat = [[0.2, 0.171], [0.171, 0.3]]
    gen = BivariateGaussianGenerator(mean, cov_mat)
    
    stochastic_env = StochasticEnvironment(
        environment=spaceport_env,
        wind_velocity_x_factor=WindXSampler(gen),
        wind_velocity_y_factor=WindYSampler(gen)
    )
  7. Understand the RocketPy Continuous Integration (CI) pipeline

    master

    RocketPy uses CI to maintain code quality. The pipeline runs automatically upon pushing to a branch or opening a PR. The checks include:

    • Linting: Runs flake8, pylint, black, and isort to check code style.
    • Testing: Executes tests in the tests folder across multiple Python versions and operating systems (Windows, Linux, MacOS).
    • Coverage: Monitors code coverage to ensure changes do not decrease coverage and identifies untested lines.

    Note: You should run all these checks locally before pushing your changes to avoid CI failures.

  8. Implement custom parachute triggers using acceleration

    master

    RocketPy allows you to define custom parachute trigger functions that can access the state derivative u_dot (containing accelerations at indices [3:6]) in addition to pressure, height, and the state vector. This enables avionics-style logic like detecting motor burnout, free-fall, or liftoff.

    To implement a custom trigger, define a callable function with one of the following signatures:

    • (pressure, height, state_vector): The classic signature.
    • (pressure, height, state_vector, u_dot): To receive the derivative, name the 4th argument u_dot, udot, acc, or acceleration. Any other name will cause the 4th argument to be the sensors list instead.
    • (pressure, height, state_vector, sensors, u_dot): To receive both the sensors list and the derivative.

    Data Formats:

    • state_vector: [x, y, z, vx, vy, vz, e0, e1, e2, e3, w1, w2, w3]
    • u_dot: [vx, vy, vz, ax, ay, az, ...]

    For realistic noisy measurements, attach an Accelerometer sensor to the rocket and access it via the sensors argument inside your trigger function.

    def my_custom_trigger(pressure, height, state_vector, u_dot):
        az = u_dot[5]
        vz = state_vector[5]
        return az < -5.0 and vz < -1.0
  9. What are target variables in sensitivity analysis?

    master

    A target variable $y(x)$ is a specific quantity extracted from a simulated trajectory $f(t, x)$ at a particular time instant. Because these quantities often depend on the input parameters $x$, the time at which they occur is also a function of those parameters.

    Common examples of target variables include:

    • Apogee: The maximum altitude reached. The time to reach apogee $t_a(x)$ is a function of the parameters, and the apogee itself is $y(x) = f(t_a(x), x)$.
    • Impact Point: The coordinates on the Earth's surface where the rocket lands. The time until impact $t_i(x)$ is a function of the parameters, and the impact point is $y(x) = f(t_i(x), x)$.
    • Time of Event: The specific time until an event occurs (e.g., $t_i(x)$ or $t_a(x)$) can be treated as a target variable itself.
  10. How Stochastic objects work in RocketPy

    master

    RocketPy provides Stochastic counterparts for its core classes (e.g., StochasticEnvironment, StochasticSolidMotor, StochasticRocket). These classes allow you to extend a deterministic model by assigning uncertainties to its input parameters.

    Mental Model

    1. Deterministic Object: You start with a standard, deterministic object (e.g., SolidMotor) that contains nominal values.
    2. Stochastic Counterpart: You wrap that object in a Stochastic class (e.g., StochasticSolidMotor).
    3. Uncertainty Assignment: You pass arguments to the Stochastic class to define how specific parameters should vary. If a parameter is not specified, the Stochastic object uses the nominal value from the deterministic object.
    4. Sampling: You call .create_object() on the stochastic instance to generate a new, deterministic instance where all parameters have been randomly sampled from their defined distributions.

    This workflow enables realistic Monte Carlo simulations by reflecting real-world data uncertainties.

    from rocketpy import SolidMotor, StochasticSolidMotor
    
    # 1. Create deterministic object
    motor = SolidMotor(thrust_source="...", dry_mass=1.815, ...)
    
    # 2. Create stochastic counterpart with uncertainties
    stochastic_motor = StochasticSolidMotor(
        solid_motor=motor,
        burn_start_time=(0, 0.1, "binomial"),
        grain_density=10
    )
    
    # 3. Sample a new deterministic object
    sampled_motor = stochastic_motor.create_object()
  11. Configure Air Brakes drag coefficient behavior

    master

    When defining the drag coefficient for air brakes, you can control how it interacts with the rocket's existing drag using the override_rocket_drag parameter:

    • override_rocket_drag=False (Default): The drag coefficient provided by the curve represents only the air brakes. This value is added to the rocket's existing drag coefficient.
    • override_rocket_drag=True: The drag coefficient provided by the curve represents both the air brakes and the rocket. The rocket's total drag coefficient will be set to match the value from the curve. This is useful for incorporating wind tunnel data of the entire vehicle.

    Additionally, the reference_area parameter determines the area used for drag force calculations:

    • If reference_area=None, the rocket's own reference area (cross-section) is used.
    • Otherwise, the specified value is used.
  12. Limitations and warnings for 3-DOF simulations

    master

    When using 3-DOF simulations, be aware of the following critical limitations and safety warnings:

    Critical Limitations

    • No stability checking: The simulation cannot detect if a rocket design is unstable.
    • No attitude control: Support for air brakes and thrust vectoring is not available.
    • Simplified weathercocking: Uses a proportional alignment model rather than full attitude dynamics.

    When NOT to use 3-DOF

    Do not use 3-DOF simulations for:

    • Final design verification
    • Stability margin analysis
    • Control system design
    • Fin sizing and optimization
    • Safety-critical trajectory predictions