Skip to content

Reference

Command Line Interface

Simple 1-D ascent simulation

# run the simulation defined by sim_config.json
poetry run hab-toolbox simple-ascent sim_config.json

# run the model with verbose output, plot and save results to a file
poetry run hab-toolbox -v simple-ascent sim_config.json -o test.csv -p

API Reference

ascent_model

buoyancy(atmosphere, balloon)

Buoyancy force (N) from air displaced by lift gas at a given geometric altitude (m).

Parameters:

Name Type Description Default
atmosphere Atmosphere

Atmosphere object initialized at a specific altitude.

required
balloon Balloon

Balloon object.

required

Returns:

Type Description
float

float: Buoyancy force (positive up) in Newtons.

Source code in hab_toolbox/ascent_model.py
def buoyancy(atmosphere, balloon)->float:
    ''' Buoyancy force (N) from air displaced by lift gas at a given
    geometric altitude (m).

    Args:
        atmosphere (Atmosphere): Atmosphere object initialized at a specific
            altitude.
        balloon (Balloon): Balloon object.

    Returns:
        float: Buoyancy force (positive up) in Newtons.
    '''
    balloon.lift_gas.match_ambient(atmosphere)
    density_diff = balloon.lift_gas.density - atmosphere.density
    displaced_air = balloon.lift_gas.volume * density_diff
    return -atmosphere.grav_accel * displaced_air

drag(atmosphere, balloon, ascent_rate)

Drag force (N) from air against the windward cross-sectional area (m^2) at a given geometric altitude (m).

Parameters:

Name Type Description Default
atmosphere Atmosphere

Atmosphere object initialized at a specific altitude.

required
balloon Balloon

Balloon object.

required
ascent_rate float

Velocity (positive up) in meters/second.

required

Returns:

Type Description
float

float: Drag force (positive up) in Newtons.

Source code in hab_toolbox/ascent_model.py
def drag(atmosphere, balloon, ascent_rate)->float:
    ''' Drag force (N) from air against the windward cross-sectional area (m^2)
    at a given geometric altitude (m).

    Args:
        atmosphere (Atmosphere): Atmosphere object initialized at a specific
            altitude.
        balloon (Balloon): Balloon object.
        ascent_rate (float): Velocity (positive up) in meters/second.

    Returns:
        float: Drag force (positive up) in Newtons.
    '''
    Cd = balloon.cd
    area = balloon.projected_area
    direction = -np.sign(ascent_rate)  # always oppose direction of motion
    return direction * (1/2) * Cd * area * (ascent_rate ** 2) * atmosphere.density

run(sim_config)

Start a simulation. Specify initial conditions and configurable parameters with a dictionary containing special keys.

Simulation starts at a time 0 and increments the time index in steps of dt seconds until the duration is reached or a balloon burst event is detected.

The following sim_config key-value pairs are supported:

{
    "balloon": {
        "type": (string) Part number of the balloon to import from balloon_library,
        "reserve_mass_kg": (float) Mass of lift gas to always keep in balloon (kg),
        "bleed_mass_kg": (float) Mass of lift gas allowed to be bled from balloon (kg),
    },
    "payload": {
        "bus_mass_kg": (float) Mass of non-ballast payload mass (kg),
        "ballast_mass_kg": (float) Mass of ballast material (kg),
    },
    "pid": {
        "mode": (string) Altitude controller mode. [pwm, continuous],
        "bleed_rate_kgps": (float) Mass flow rate of lift gas bleed (kg/s),
        "ballast_rate_kgps": (float) Mass flow rate of ballast release (kg/s),
        "gains": {
            "kp": (float) Proportional gain,
            "ki": (float) Integral gain,
            "kd": (float) Derivative gain,
            "n":  (float) Filter coefficient,
        }
    },
    "simulation": {
        "id": (string) An identifier for the simulation,
        "duration": (float) Max time duration of simulation (seconds),
        "dt": (float) Time step (seconds),
        "initial_altitude": (float) Altitude at simulation start (m), [-5004 to 80000],
        "initial_velocity": (float) Velocity at simulation start (m/s)
    }
}

Parameters:

Name Type Description Default
sim_config dict

Dictionary of simulation config parameters.

required

Returns:

Type Description
tuple

Tuple containing timeserieses of simulation values:

  • tspan (array): Array of time indices in seconds.
  • altitude (array): Instantaneous acceleration (positive up) in meters/second^2.
  • altitude (array): Array of altitudes. One entry for each time index.
  • velocity (array): Array of ascent velocities. One entry for each time index. Positive up.
  • acceleration (array): Array of ascent accelerations. One entry for each time index. Positive up.
Source code in hab_toolbox/ascent_model.py
def run(sim_config):
    ''' Start a simulation. Specify initial conditions and configurable
    parameters with a dictionary containing special keys.

    Simulation starts at a time 0 and increments the time index in steps of
    `dt` seconds until the `duration` is reached or a balloon burst event is
    detected.

    The following `sim_config` key-value pairs are supported:
    ``` json
    {
        "balloon": {
            "type": (string) Part number of the balloon to import from balloon_library,
            "reserve_mass_kg": (float) Mass of lift gas to always keep in balloon (kg),
            "bleed_mass_kg": (float) Mass of lift gas allowed to be bled from balloon (kg),
        },
        "payload": {
            "bus_mass_kg": (float) Mass of non-ballast payload mass (kg),
            "ballast_mass_kg": (float) Mass of ballast material (kg),
        },
        "pid": {
            "mode": (string) Altitude controller mode. [pwm, continuous],
            "bleed_rate_kgps": (float) Mass flow rate of lift gas bleed (kg/s),
            "ballast_rate_kgps": (float) Mass flow rate of ballast release (kg/s),
            "gains": {
                "kp": (float) Proportional gain,
                "ki": (float) Integral gain,
                "kd": (float) Derivative gain,
                "n":  (float) Filter coefficient,
            }
        },
        "simulation": {
            "id": (string) An identifier for the simulation,
            "duration": (float) Max time duration of simulation (seconds),
            "dt": (float) Time step (seconds),
            "initial_altitude": (float) Altitude at simulation start (m), [-5004 to 80000],
            "initial_velocity": (float) Velocity at simulation start (m/s)
        }
    }
    ```
    Args:
        sim_config (dict): Dictionary of simulation config parameters.

    Returns:
        tuple: Tuple containing timeserieses of simulation values:

        - `tspan` (`array`): Array of time indices in seconds.
        - `altitude` (`array`): Instantaneous acceleration (positive up) in
                meters/second^2.
        - `altitude` (`array`): Array of altitudes.
            One entry for each time index.
        - `velocity` (`array`): Array of ascent velocities.
            One entry for each time index. Positive up.
        - `acceleration` (`array`): Array of ascent accelerations.
            One entry for each time index. Positive up.
    '''
    altitude=np.array([])
    ascent_rate=np.array([])
    ascent_accel=np.array([])

    balloon = Balloon(sim_config['balloon']['type'])
    balloon.reserve_gas = sim_config['balloon']['reserve_mass_kg']
    balloon.bleed_gas = sim_config['balloon']['bleed_mass_kg']
    balloon.lift_gas = Gas(balloon.spec['lifting_gas'],
                           mass=balloon.reserve_gas+balloon.bleed_gas)
    bus_mass = sim_config['payload']['bus_mass_kg']
    ballast_mass = sim_config['payload']['ballast_mass_kg']
    payload = Payload(dry_mass=bus_mass, ballast_mass=ballast_mass)

    duration = sim_config['simulation']['duration']
    dt = sim_config['simulation']['dt']
    if dt < MIN_ALLOWED_DT or dt > MAX_ALLOWED_DT:
        # solver gets unstable with time steps above 0.5
        log.error(f'Time step must be between 0.001 and 0.5 seconds, not {dt}')
        if dt < MIN_ALLOWED_DT:
            dt = MIN_ALLOWED_DT
        elif dt > MAX_ALLOWED_DT:
            dt = MAX_ALLOWED_DT
        log.warning(f'Using closest allowed time step: {dt} seconds')

    tspan = np.arange(0, duration, step=dt)

    h = sim_config['simulation']['initial_altitude']
    v = sim_config['simulation']['initial_velocity']
    a = Atmosphere(h).grav_accel

    log.warning(
        f'Starting simulation: '
        f'balloon: {balloon.name} | '
        f'duration: {duration} s | '
        f'dt: {dt} s')
    for t in tspan:
        if balloon.burst_threshold_exceeded:
            log.warning('Balloon burst threshold exceeded: time %s, altitude %s m, diameter %s m' % (
                t, h, balloon.diameter))
            # truncate timesteps that weren't simulated
            tspan = np.transpose(tspan[np.where(tspan < t)])
            break
        a, dv, dh = step(dt, a, v, h, balloon, payload)
        v += dv
        h += dh
        log.info(' | '.join([
            f'{t:6.1f} s',
            f'{a} m/s^2',
            f'{v} m/s | {h} m',
        ]))
        altitude = np.append(altitude, h)
        ascent_rate = np.append(ascent_rate, v)
        ascent_accel = np.append(ascent_accel, a)

    return tspan, altitude, ascent_rate, ascent_accel

step(dt, a, v, h, balloon, payload)

Progress the simulation by one time step.

Parameters:

Name Type Description Default
dt float

Time step size in seconds.

required
a float

Acceleration (positive up) in meters/second^2.

required
v float

Velocity (positive up) in meters/second.

required
h float

Altitude in meters.

required
balloon Balloon

Balloon object.

required
payload Payload

Payload object.

required

Returns:

Type Description
tuple

Tuple containing rates of change over the time step:

  • a (float): Instantaneous acceleration (positive up) in meters/second^2.
  • dv (float): Delta velocity (positive up) between the previous time index and the latest one in meters/second.
  • dh (float): Delta altitude between the previous time index and the latest one in meters.
Source code in hab_toolbox/ascent_model.py
def step(dt, a, v, h, balloon, payload):
    ''' Progress the simulation by one time step.

    Args:
        dt (float): Time step size in seconds.
        a (float): Acceleration (positive up) in meters/second^2.
        v (float): Velocity (positive up) in meters/second.
        h (float): Altitude in meters.
        balloon (Balloon): Balloon object.
        payload (Payload): Payload object.

    Returns:
        tuple: Tuple containing rates of change over the time step:

        - `a` (`float`): Instantaneous acceleration (positive up) in
                meters/second^2.
        - `dv` (`float`): Delta velocity (positive up) between the previous
                time index and the latest one in meters/second.
        - `dh` (`float`): Delta altitude between the previous time index and
                the latest one in meters.
    '''
    atmosphere = Atmosphere(h)
    balloon.match_ambient(atmosphere)
    total_mass = balloon.mass + payload.total_mass

    f_weight = weight(atmosphere, total_mass)
    f_buoyancy = buoyancy(atmosphere, balloon)
    f_drag = drag(atmosphere, balloon, v)
    f_net = f_weight + f_buoyancy + f_drag

    a = f_net/total_mass
    dv = a*dt
    dh = v*dt
    log.debug(' | '.join([
        f'f_net {f_net[0]} N',
        f'f_weight {f_weight[0]} N',
        f'f_buoyancy {f_buoyancy[0]} N',
        f'f_drag {f_drag[0]} N',
        f''
    ]))
    return a, dv, dh

weight(atmosphere, total_mass)

Weight (N) as a function of gropotential altitude (m) and mass (kg).

Parameters:

Name Type Description Default
atmosphere Atmosphere

Atmosphere object initialized at a specific altitude.

required
total_mass float

Total dry mass in kilograms.

required

Returns:

Type Description
float

float: Weight force (positive up) in Newtons.

Source code in hab_toolbox/ascent_model.py
def weight(atmosphere, total_mass)->float:
    ''' Weight (N) as a function of gropotential altitude (m) and mass (kg).

    Args:
        atmosphere (Atmosphere): Atmosphere object initialized at a specific
            altitude.
        total_mass (float): Total dry mass in kilograms.

    Returns:
        float: Weight force (positive up) in Newtons.
    '''
    return -atmosphere.grav_accel * total_mass

balloon_library special

balloon

Balloon and Gas properties.

This module defines Balloon objects and Gas objects for use in high altitude balloon simulations.

Balloon objects are initialized from a specification definition file, which is a JSON that lives in the same directory as this module. These definition files are generated from high altitude balloon specification datasheets provided by the balloon's manufacturer. It includes attributes such as the size, mass, volume limits, approximate drag coefficient, and other useful metrics. The Balloon object has class methods

GAS_PROPERTIES_CONFIG

Dictionary of gasses species and their special properties.

Source: US Standard Atmosphere, 1976

Key Species Molar Weight (kg/mol)
Air Air 0.02897
He Helium 0.0040026
H2 Hydrogen 0.00201594
N2 Nitrogen 0.0280134
O2 Oxygen 0.0319988
Ar Argon 0.039948
CO2 Carbon Dioxide 0.04400995
Ne Neon 0.020183
Kr Krypton 0.08380
Xe Xenon 0.13130
CH4 Methane 0.01604303

Note

All properties are measured from dry gasses at sea level.

Balloon

Object for handling properties of a Balloon.

A valid specification file is needed to initialize a balloon. Specififcations are JSON files in the balloon_library directory.

Property Description
name Part name of the Balloon
datasheet Link to the specification PDF
part_number Part number of the Balloon
lift_gas Gas object representing gas "inside" the balloon
cd Approximate drag coefficient (assumes spherical balloon)
mass Mass of the balloon itself
burst_diameter Maximum diameter of the balloon before it bursts

A dictionary of more specific manufacturer recommendations, estimate values and other properties are contained within the spec property. This property provides direct access to the spec portion of the specification JSON, which is basically everything besides the naming metadata. For example, Balloon.spec.lifting_gas returns the manufacturer recommended species for lifting gas as a string.

In order to interact with the gas properties of the lift gas "inside" the Balloon, access its properties and methods directly. For example,

b = Balloon('HAB-2000')  # initialize the Balloon object

print(b.lift_gas)        # Gas object is initialized inside the balloon,
                         # where the species is set to the manufacturer
                         # recommendation since none was specified

b.lift_gas.mass = 1.0    # set the mass of the Gas object to 1 kg

Parameters:

Name Type Description Default
spec_name string

Initialize the Balloon object with a specific part number corresponding to a valid JSON in the balloon_library directory. Balloon properties are imported from this JSON.

required
lift_gas string

Initialize the Balloon object with Gas to use "inside" the balloon, specifying the species as a string. For a complete list of gasses to choose from, use list_known_species(). Optional, defaults to the lift gas species identified in the specification JSON.

required

Note

When initializing a Balloon with a lift_gas, it is just assigning a gas type. To do volume calculations, make sure to "fill" the balloon by assigning Balloon.lift_gas.mass a nonzero value.

burst_threshold_exceeded: bool property readonly

Check if the given volume (m^3) is greater than or equal to the burst volume (m^3) from the spec sheet.

projected_area: float property readonly

Projected cross-sectional area of the balloon (m^2) for use in drag calculations assuming the balloon is a sphere with nonzero volume (m^3).

volume: float property readonly

Ideal gas volume (m^3) from temperature (K) and pressure (Pa) for the current mass (kg) of lift gas in the balloon.

match_ambient(self, atmosphere)

Update temperature (K), pressure (Pa), and density (kg/m^3) to match ambient air conditions at a given geopotential altitude (m).

Source code in hab_toolbox/balloon_library/balloon.py
def match_ambient(self, atmosphere):
    ''' Update temperature (K), pressure (Pa), and density (kg/m^3) to
    match ambient air conditions at a given geopotential altitude (m).
    '''
    self.lift_gas.match_ambient(atmosphere)
    return self
match_conditions(self, temperature, pressure)

Update temperature (K), pressure (Pa) to match specific values.

Source code in hab_toolbox/balloon_library/balloon.py
def match_conditions(self, temperature, pressure):
    ''' Update temperature (K), pressure (Pa) to match specific values.
    '''
    self.lift_gas.match_conditions(temperature, pressure)
    return self

Gas

Object for handling ideal gas properties of a finite volume of lift gas inside a Balloon.

Parameters:

Name Type Description Default
species string

Initialize the Gas object with a species of gas to use for ideal gas calculations. For a complete list of gasses to choose from, use list_known_species()

required
mass float

Initialize the Gas object with positive nonzero mass in kilograms. Optional, defaults to 0.

required

Note

While Gas objects function alone, they are best used when set as the lift_gas attribute of a Balloon.

density property readonly

Ideal gas density (kg/m^3) from temperature (K) and pressure (Pa).

Note

Since density is a property per unit mass, this property is still valid for an unspecified (or zero) Gas.mass.

volume property readonly

Ideal gas volume (m^3) from temperature (K) and pressure (Pa) for a given mass (kg) of gas.

Note

If Gas.mass is zero, volume is also zero. Likewise, a negative (nonphysical) mass will result in a negative (nonphysical) volume.

match_ambient(self, atmosphere)

Update temperature (K), pressure (Pa), and density (kg/m^3) to match ambient air conditions at a given geopotential altitude (m).

Parameters:

Name Type Description Default
atmosphere Atmosphere

An ambiance.Atmosphere object with valid temperature and pressure attributes.

required

Returns:

Type Description
Gas

Updates the temperature and pressure properties to be equal to those of the input atmosphere, then returns itself.

Source code in hab_toolbox/balloon_library/balloon.py
def match_ambient(self, atmosphere):
    ''' Update temperature (K), pressure (Pa), and density (kg/m^3) to
    match ambient air conditions at a given geopotential altitude (m).

    Args:
        atmosphere (Atmosphere): An `ambiance.Atmosphere` object with
            valid `temperature` and `pressure` attributes.

    Returns:
        Gas: Updates the `temperature` and `pressure` properties to be
            equal to those of the input `atmosphere`, then returns itself.
    '''
    log.debug('Matching %s temperature and pressure to ambient at %s meters (geometric altitude)' % (
        self.species, atmosphere.h
    ))
    self.temperature = atmosphere.temperature
    self.pressure = atmosphere.pressure
    return self
match_conditions(self, temperature, pressure)

Update temperature (K), pressure (Pa) to match specific values.

Parameters:

Name Type Description Default
temperature float

Temperature in Kelvin

required
pressure float

Pressure in Pascals

required

Returns:

Type Description
Gas

Updates the temperature and pressure properties to be equal to the input temperature and pressure, then returns itself.

Source code in hab_toolbox/balloon_library/balloon.py
def match_conditions(self, temperature, pressure):
    ''' Update temperature (K), pressure (Pa) to match specific values.

    Args:
        temperature (float): Temperature in Kelvin
        pressure (float): Pressure in Pascals

    Returns:
        Gas: Updates the `temperature` and `pressure` properties to be
            equal to the input `temperature` and `pressure`, then returns
            itself.
    '''
    log.debug('Matching %s temperature and pressure to %s K, %s Pa' % (
        self.species, temperature, pressure
    ))
    self.temperature = temperature
    self.pressure = pressure
    return self

Payload

The thing carried by a balloon.

Parameters:

Name Type Description Default
dry_mass float

Mass of the payload in kilograms. If there are consumables on board like ballast, this is not included in dry mass. Optional, default is 2.0.

required
ballast_mass float

Mass of ballast to be dropped (consumed) in kilograms. It is assumed that the payload is an open-mass system with respect to ballast. Optional, default is 0.0.

required
total_mass: float property readonly

Get the total mass of the payload, including dry mass and ballast.

get_balloon(spec_name)

Get balloon spec sheet definitions as a dictionary.

Balloon definition files are JSON files in the balloon_library directory.

Parameters:

Name Type Description Default
spec_name string

Name of the balloon spec to use. Case sensitive and does not include the file (i.e. HAB-3000 corresponds to ballon_library/HAB-3000.json).

required

Returns:

Type Description
dict

Dictionary of balloon specification parameters.

Source code in hab_toolbox/balloon_library/balloon.py
def get_balloon(spec_name):
    ''' Get balloon spec sheet definitions as a dictionary.

    Balloon definition files are JSON files in the `balloon_library` directory.

    Args:
        spec_name (string): Name of the balloon spec to use. Case sensitive and
            does not include the file (i.e. `HAB-3000` corresponds to
            `ballon_library/HAB-3000.json`).

    Returns:
        dict: Dictionary of balloon specification parameters.
    '''
    if is_valid_balloon(spec_name):
        config_filename = '%s.json' % spec_name
        config_path = os.path.join(BALLOON_LIBRARY_DIR, config_filename)
        with open(config_path) as config_json_data:
            config_data = json.load(config_json_data)
        return config_data
    else:
        raise ValueError('No valid balloon named %s' % spec_name)

get_gas_properties()

Return the dictionary of gas species and their molar mass (kg/mol).

Source code in hab_toolbox/balloon_library/balloon.py
def get_gas_properties():
    ''' Return the dictionary of gas species and their molar mass (kg/mol).
    '''
    gas_properties = GAS_PROPERTIES_CONFIG['gas_properties']
    units = GAS_PROPERTIES_CONFIG['units']

    known_species = {}
    for gas in gas_properties:
        for gas_name in gas['species']:
            known_species[gas_name] = gas['molar_mass']
    log.debug('Known gas species: %s' % known_species)
    return known_species, units

is_valid_balloon(spec_name)

Returns True if spec_name matches the name of a known balloon definition.

Balloon definition files are JSON files in the balloon_library directory.

Parameters:

Name Type Description Default
spec_name string

Name of the balloon spec to use. Case sensitive and does not include the file (i.e. HAB-3000 corresponds to ballon_library/HAB-3000.json).

required

Returns:

Type Description
bool

Returns True if spec_name matches the name of a known balloon definition.

Source code in hab_toolbox/balloon_library/balloon.py
def is_valid_balloon(spec_name):
    ''' Returns True if `spec_name` matches the name of a known balloon
    definition.

    Balloon definition files are JSON files in the `balloon_library` directory.

    Args:
        spec_name (string): Name of the balloon spec to use. Case sensitive and
            does not include the file (i.e. `HAB-3000` corresponds to
            `ballon_library/HAB-3000.json`).

    Returns:
        bool: Returns True if `spec_name` matches the name of a known balloon
        definition.
    '''
    known_balloons = []
    for f in os.listdir(BALLOON_LIBRARY_DIR):
        if os.path.isfile(os.path.join(BALLOON_LIBRARY_DIR, f)):
            fileparts = os.path.splitext(f)
            if fileparts[1] == '.json':
                known_balloons.append(fileparts[0])
    log.debug('Known balloons: %s' % known_balloons)
    return spec_name in known_balloons

is_valid_gas(species)

Return True if there is a known molecular weight for the input species.

Parameters:

Name Type Description Default
species string

Name or abbreviation of a gas (i.e. he or helium)

required

Returns:

Type Description
bool

Returns True if species is in the known list of gas species.

Source code in hab_toolbox/balloon_library/balloon.py
def is_valid_gas(species):
    ''' Return True if there is a known molecular weight for the input
    `species`.

    Args:
        species (string): Name or abbreviation of a gas (i.e. `he` or `helium`)

    Returns:
        bool: Returns `True` if `species` is in the known list of gas species.
    '''
    return species in list_known_species()

list_known_species()

Return all species listed in get_gas_properties.

Returns:

Type Description
list

Keys of valid gas species.

Source code in hab_toolbox/balloon_library/balloon.py
def list_known_species():
    ''' Return all species listed in `get_gas_properties`.

    Returns:
        list: Keys of valid gas species.
    '''
    known_species, _ = get_gas_properties()
    return list(known_species.keys())

plot_tools

plot_ascent(time, altitude, velocity, acceleration, title='', show=True, save_fig=None)

Create plots for altitude, velocity, and acceleration over time.

Expects all input arrays to be the same length. Best results when used with hab_toolbox.cli.simple_ascent or hab_toolbox.cli.plot_ascent.

Parameters:

Name Type Description Default
time array

Array of time indices.

required
altitude array

Array of altitudes. One entry for each time index.

required
velocity array

Array of ascent velocities. One entry for each time index. Positive up.

required
acceleration array

Array of ascent accelerations. One entry for each time index. Positive up.

required
title string

Plot title. Defaults to ''.

''
show bool

Whether to display the plots (True, default) or just create the plot objects and return them (False).

True
save_fig string

Filename to use for a saved figure. If not specified, the figure is not saved. If no file extension is given, the figure will be saved as a .png

None

Returns:

Type Description
tuple

Figure and Axis plot objects.

Source code in hab_toolbox/plot_tools.py
def plot_ascent(time,
                altitude,
                velocity,
                acceleration,
                title='',
                show=True,
                save_fig=None):
    ''' Create plots for altitude, velocity, and acceleration over time.

    Expects all input arrays to be the same length. Best results when used
    with `hab_toolbox.cli.simple_ascent` or `hab_toolbox.cli.plot_ascent`.

    Args:
        time (array): Array of time indices.
        altitude (array): Array of altitudes.
            One entry for each time index.
        velocity (array): Array of ascent velocities.
            One entry for each time index. Positive up.
        acceleration (array): Array of ascent accelerations.
            One entry for each time index. Positive up.
        title (string, optional): Plot title. Defaults to `''`.
        show (bool, optional): Whether to display the plots (`True`, default)
            or just create the plot objects and return them (`False`).
        save_fig (string, optional): Filename to use for a saved figure.
            If not specified, the figure is not saved.
            If no file extension is given, the figure will be saved as a `.png`

    Returns:
        tuple: Figure and Axis plot objects.
    '''
    fig, axs = plt.subplots(3, 1)
    if title:
        fig.suptitle(title)

    axs[0].plot(time, altitude)
    axs[0].set_ylabel('Altitude (m)')

    axs[1].plot(time, velocity)
    axs[1].set_ylabel('Velocity (m/s)')

    axs[2].plot(time, acceleration)
    axs[2].set_ylabel('Acceleration (m/s^2)')

    for ax in axs:
        ax.set_xlabel('Time (s)')
        ax.grid(True)
        ax.set_frame_on(False)

    if show:
        show_figure(save_fig=save_fig)

    return fig, axs

show_figure(save_fig=None)

Show all plots.

A simple wrapper for matplotlib.pyplot.show()

Parameters:

Name Type Description Default
save_fig string

Filename to use for a saved figure. If not specified, the figure is not saved. If no file extension is given, the figure will be saved as a .png

None
Source code in hab_toolbox/plot_tools.py
def show_figure(save_fig=None):
    ''' Show all plots.

    A simple wrapper for `matplotlib.pyplot.show()`

    Args:
        save_fig (string, optional): Filename to use for a saved figure.
            If not specified, the figure is not saved.
            If no file extension is given, the figure will be saved as a `.png`
    '''
    plt.show()
    if save_fig:
        plt.savefig(save_fig)
        log.warning(f'Plot saved to {save_fig}.png')