Skip to content

API reference

Everything below is importable from the top level: import orhelper.

Starting OpenRocket

OpenRocketInstance

OpenRocketInstance(jar_path: Optional[Union[str, PathLike]] = None, log_level: Union[OrLogLevel, str] = INFO, **kwargs)

Starts OpenRocket (a Java virtual machine) for the duration of a with block.

Everything that talks to OpenRocket has to happen inside the block; leaving it shuts the JVM down. Java can be started only once per Python process, so keep all OpenRocket work in a single block (a second block, even after the first one ended, raises JVMAlreadyStartedError).

By default the installed OpenRocket is used. Pass jar, jvm or orhome to choose another one.

Example
import orhelper

with orhelper.OpenRocketInstance() as instance:
    helper = orhelper.Helper(instance)
    ...

Attributes:

  • jar (Path) –

    The OpenRocket jar that is used.

  • jvm (Path) –

    The Java virtual machine library that is used.

  • jvm_args (tuple[str, ...]) –

    Extra arguments given to the JVM.

  • or_log_level (OrLogLevel) –

    The log level.

  • started (bool) –

    True while the JVM is running.

  • openrocket_core –

    The Java package that holds OpenRocket's core classes, for example instance.openrocket_core.simulation.FlightDataType. This is info.openrocket.core, or net.sf.openrocket in OpenRocket 22.02 and 23.09. None until the JVM has started.

  • openrocket_swing –

    The Java package with OpenRocket's user interface classes (the same package as openrocket_core in 22.02 and 23.09). None until the JVM has started.

Prepare to start OpenRocket. The JVM itself starts when the with block is entered.

Where to find OpenRocket is decided in this order: an explicit jar (or jar_path), then the installation given by orhome, then the default installation location of your platform (~/OpenRocket on Linux, /Applications/OpenRocket.app on macOS, %PROGRAMFILES%\OpenRocket on Windows), then the CLASSPATH environment variable or ./OpenRocket.jar. The Java runtime is taken from the installation when there is one, else the system default.

Parameters:

  • jar_path (Optional[Union[str, PathLike]], default: None ) –

    Location of the OpenRocket jar file; the same as the jar keyword argument (which wins if both are given). An explicit jar always takes precedence over the installed one.

  • log_level (Union[OrLogLevel, str], default: INFO ) –

    Log level, as an OrLogLevel or its name (case-insensitive): OFF, ERROR, WARN, INFO (the default), DEBUG, TRACE or ALL. This sets the level of OpenRocket's own Java logging and of the orhelper Python logger. orhelper does not configure Python logging handlers; call logging.basicConfig() to see its messages.

  • **kwargs –

    Keyword arguments, all optional:

    • orhome: location of an installed OpenRocket.
    • jar: location of the OpenRocket jar file.
    • jvm: location of the Java virtual machine library (libjvm.so, libjvm.dylib or jvm.dll).
    • jvm_args: list of extra arguments for the JVM, for example ["-Xmx2g"] or ["-Djava.awt.headless=true"].
    • loglevel: the same as log_level; takes precedence over it.

Raises:

  • TypeError –

    For an unknown keyword argument or an argument of the wrong type.

  • ValueError –

    For an unknown log level.

  • OpenRocketNotFoundError –

    If the installation or the jar can't be found.

  • JVMNotFoundError –

    If no Java virtual machine can be found.

__enter__

__enter__()

Start the JVM and initialise OpenRocket.

Returns:

  • –

    This instance.

Raises:

  • JVMAlreadyStartedError –

    If a JVM is running in this process, or one was started and shut down before: JPype can't restart it.

__exit__

__exit__(ex, value, tb)

Shut the JVM down. An exception raised in the with block is logged and then propagates.

OrLogLevel

Bases: Enum

Log levels for OpenRocketInstance.

Instead of a member you can pass its name as a string, in any case, for example log_level="error". From quiet to chatty: OFF, ERROR, WARN, INFO (the default), DEBUG, TRACE, ALL.

Working with simulations

Helper

Helper(open_rocket_instance: OpenRocketInstance)

Python-friendly operations on OpenRocket documents and simulations.

Load and save .ork files, run simulations (optionally with Python listeners), and read the results as NumPy arrays. Everything else in OpenRocket is reached by calling the Java objects that these methods return and accept: documents, simulations, rockets and components are plain JPype Java objects.

Example
with orhelper.OpenRocketInstance() as instance:
    helper = orhelper.Helper(instance)
    document = helper.load_doc("my_rocket.ork")
    simulation = document.getSimulation(0)
    helper.run_simulation(simulation)
    data = helper.get_timeseries(simulation, [orhelper.FlightDataType.TYPE_ALTITUDE])

Attributes:

  • openrocket_core –

    The Java package with OpenRocket's core classes (see OpenRocketInstance).

  • openrocket_swing –

    The Java package with OpenRocket's user interface classes.

Create a helper for a started OpenRocket.

Parameters:

  • open_rocket_instance (OpenRocketInstance) –

    The instance from with OpenRocketInstance() as instance.

Raises:

  • OrHelperError –

    If the instance has not been started, that is, when it is used outside its with block.

load_doc

load_doc(or_filename: Union[str, PathLike])

Load an OpenRocket (.ork) file.

Parameters:

  • or_filename (Union[str, PathLike]) –

    Path of the file.

Returns:

  • –

    The Java OpenRocketDocument. Use document.getRocket() for the rocket and document.getSimulation(0) (or getSimulations()) for its simulations.

Raises:

  • RocketLoadException –

    (a Java exception) If the file is missing or can't be read.

save_doc

save_doc(or_filename: Union[str, PathLike], doc)

Save an OpenRocket document, with the changes you made to it, to an .ork file.

Parameters:

  • or_filename (Union[str, PathLike]) –

    Path of the file to write. It is overwritten if it exists.

  • doc –

    The Java OpenRocketDocument, as returned by load_doc.

run_simulation

run_simulation(sim, listeners: Optional[Iterable[AbstractSimulationListener]] = None)

Run a simulation. This wraps Java's Simulation.simulate().

The results are stored in the simulation; read them with get_timeseries, get_final_values and get_events, or from Java with sim.getSimulatedData().

Note

Each run starts by drawing a new random seed (sim.getOptions().randomizeSeed()), so repeated runs of identical settings give slightly different results when turbulence is on. This also changes the seed stored in the simulation's options.

Parameters:

translate_flight_data_type

translate_flight_data_type(flight_data_type: Union[FlightDataType, str])

Look up the Java flight data type of the OpenRocket version that is running.

TYPE_PROPELLANT_MASS is a legacy name of TYPE_MOTOR_MASS; either works in every version.

Parameters:

Returns:

  • –

    The Java FlightDataType constant.

Raises:

  • TypeError –

    If the argument is neither a FlightDataType nor a string.

  • AttributeError –

    If this OpenRocket version doesn't have the variable.

get_timeseries

get_timeseries(simulation, variables: Iterable[Union[FlightDataType, str]], branch_number=0) -> Dict[Union[FlightDataType, str], ndarray]

Get the values of variables at every time step of a simulation.

The values are in SI units (see Flight data variables). Some variables are nan at some time steps, for example at the first one, so use numpy.nanmax and friends for statistics. Request TYPE_TIME to get the matching times.

Parameters:

  • simulation –

    The Java Simulation, after run_simulation.

  • variables (Iterable[Union[FlightDataType, str]]) –

    The FlightDataType members, or their names, to get.

  • branch_number –

    The flight branch to read: 0 is the sustainer, 1 and up are boosters.

Returns:

  • Dict[Union[FlightDataType, str], ndarray] –

    A dictionary with one NumPy array per variable, under the same key you asked with.

Raises:

  • AttributeError –

    If a variable doesn't exist in this OpenRocket version.

  • IndexOutOfBoundsException –

    (a Java exception) If the simulation has no such branch.

get_final_values

get_final_values(simulation, variables: Iterable[Union[FlightDataType, str]], branch_number=0) -> Dict[Union[FlightDataType, str], float]

Get the last value of variables in a simulation, for example where the rocket landed.

This is the last sample of the time series, which can be nan for variables that are not recorded on the last data point (this depends on the OpenRocket version).

Parameters:

  • simulation –

    The Java Simulation, after run_simulation.

  • variables (Iterable[Union[FlightDataType, str]]) –

    The FlightDataType members, or their names, to get.

  • branch_number –

    The flight branch to read: 0 is the sustainer, 1 and up are boosters.

Returns:

  • Dict[Union[FlightDataType, str], float] –

    A dictionary that maps each variable to its final value, in SI units.

Raises:

  • AttributeError –

    If a variable doesn't exist in this OpenRocket version.

translate_flight_event

translate_flight_event(flight_event) -> FlightEvent

Convert a Java FlightEvent.Type to the FlightEvent enum.

Raises:

  • KeyError –

    If the event type is not in the FlightEvent enum, for example one added by a newer OpenRocket.

get_events

get_events(simulation, branch_number=0) -> Dict[FlightEvent, List[float]]

Get the events that happened during a simulated flight, and when.

Events that the FlightEvent enum doesn't know, from a newer OpenRocket, are skipped with a warning in the log.

Parameters:

  • simulation –

    The Java Simulation, after run_simulation.

  • branch_number –

    The flight branch to read: 0 is the sustainer, 1 and up are boosters.

Returns:

  • Dict[FlightEvent, List[float]] –

    A dictionary that maps each FlightEvent that occurred to the list of times, in seconds, at which it did. Most events occur once.

get_component_named

get_component_named(root, name)

Find a part of the rocket by its name.

Parameters:

  • root –

    The Java component to search from, usually the rocket: document.getRocket(). Its sub-components are searched too.

  • name –

    The name of the component, as shown in OpenRocket.

Returns:

  • –

    The first Java RocketComponent with that name. Change it with its Java setters, for example setLength(...) or setOverrideMass(...).

Raises:

  • ValueError –

    If there is no component with that name.

JIterator

JIterator(jit)

Wraps a Java rocket component so that you can walk its tree of sub-components in a for loop.

Example
for component in orhelper.JIterator(document.getRocket()):
    print(component.getName())

Wrap a component.

Parameters:

  • jit –

    A Java object that has an iterator(True) method, such as a RocketComponent.

Listeners

AbstractSimulationListener

Base class for Python code that runs during an OpenRocket simulation.

Subclass it, override the hooks you need and pass instances to Helper.run_simulation. This is a Python version of OpenRocket's AbstractSimulationListener, so the hook names are the Java ones (camelCase) and the arguments are Java objects; status, for example, is a SimulationStatus. Every hook does nothing by default, so the simulation is only affected by the hooks you override.

There are three groups of hooks:

  • Lifecycle hooks: startSimulation, endSimulation, their ...Branch versions, preStep and postStep.
  • Event hooks (addFlightEvent, handleFlightEvent, motorIgnition, recoveryDeviceDeployment): return True to let things happen normally (the default) or False to prevent it.
  • Computation hooks (pre... and post...): called around the models OpenRocket evaluates in each step. Return None (for the hooks that return a number: float("nan")) to leave the simulation alone, which is the default. Return a value of the type OpenRocket expects to replace the result: the pre... hooks replace the value before it is computed, the post... hooks replace the value that was computed.
Keep results in a list or dict, not in a number

OpenRocket doesn't use the object you pass in: it clones it (shallow copy) for the simulation. Lists and dicts created in __init__ are shared with the copy, so you can read them afterwards. A number or string that a hook assigns (self.count += 1) is changed on the copy only, and the object you hold still has the old value.

Example
class AltitudeTracker(orhelper.AbstractSimulationListener):
    def __init__(self):
        self.altitudes = []          # shared with the copy that OpenRocket runs

    def postStep(self, status):
        self.altitudes.append(status.getRocketPosition().z)

tracker = AltitudeTracker()
helper.run_simulation(simulation, listeners=[tracker])
print(max(tracker.altitudes))

startSimulation

startSimulation(status) -> None

Called when the simulation starts.

Parameters:

  • status –

    The Java SimulationStatus. You can change it, for example to start the rocket at another position.

endSimulation

endSimulation(status, simulation_exception) -> None

Called when the simulation ends, normally or because of an error.

Parameters:

  • status –

    The Java SimulationStatus.

  • simulation_exception –

    The Java SimulationException that ended the simulation, or None if it ended normally.

startSimulationBranch

startSimulationBranch(status) -> None

Called when a branch starts: the sustainer, and each booster created at stage separation.

This hook exists only in OpenRocket 26.xx; in 22.02, 23.09 and 24.12 it is never called.

Parameters:

  • status –

    The Java SimulationStatus of the branch.

endSimulationBranch

endSimulationBranch(status, simulation_exception) -> None

Called when a branch ends, normally or because of an error. Like startSimulationBranch, only OpenRocket 26.xx calls it.

Parameters:

  • status –

    The Java SimulationStatus of the branch.

  • simulation_exception –

    The Java SimulationException that ended the branch, or None.

preStep

preStep(status) -> bool

Called before every simulation step.

Parameters:

  • status –

    The Java SimulationStatus.

Returns:

  • bool –

    True to take the step (the default), False to skip it. A skipped step does not advance the simulation, so don't return False on every call.

postStep

postStep(status) -> None

Called after every simulation step, also when preStep skipped it.

Parameters:

  • status –

    The Java SimulationStatus, for example status.getSimulationTime() or status.getRocketPosition().

isSystemListener

isSystemListener() -> bool

Whether this is one of OpenRocket's own listeners. Leave this as False for your own code.

addFlightEvent

addFlightEvent(status, flight_event) -> bool

Called before an event is added to the event queue.

Parameters:

  • status –

    The Java SimulationStatus.

  • flight_event –

    The Java FlightEvent that is about to be added.

Returns:

  • bool –

    True to add the event (the default), False to leave it out.

handleFlightEvent

handleFlightEvent(status, flight_event) -> bool

Called before an event is handled.

Parameters:

  • status –

    The Java SimulationStatus.

  • flight_event –

    The Java FlightEvent that is taking place.

Returns:

  • bool –

    True to handle the event (the default), False to ignore it.

motorIgnition

motorIgnition(status, motor_id, motor_mount, motor_instance) -> bool

Called when a motor is about to ignite.

Parameters:

  • status –

    The Java SimulationStatus.

  • motor_id –

    The id of the motor configuration.

  • motor_mount –

    The Java motor mount that holds the motor.

  • motor_instance –

    The motor that is being ignited.

Returns:

  • bool –

    True to ignite the motor (the default), False to prevent it.

recoveryDeviceDeployment

recoveryDeviceDeployment(status, recovery_device) -> bool

Called when a recovery device (a parachute, for example) is about to deploy.

Parameters:

  • status –

    The Java SimulationStatus.

  • recovery_device –

    The Java recovery device.

Returns:

  • bool –

    True to deploy it (the default), False to prevent it.

preAccelerationCalculation

preAccelerationCalculation(status)

Replace the acceleration before it is computed. Return a Java AccelerationData, or None.

preAerodynamicCalculation

preAerodynamicCalculation(status)

Replace the aerodynamic forces before they are computed. Return a Java AerodynamicForces, or None.

preAtmosphericModel

preAtmosphericModel(status)

Replace the atmospheric conditions before they are computed. Return Java AtmosphericConditions, or None.

preFlightConditions

preFlightConditions(status)

Replace the flight conditions before they are computed. Return a Java FlightConditions, or None.

preGravityModel

preGravityModel(status)

Replace the gravitational acceleration (m/s²) before it is computed. Return a number, or nan.

preMassCalculation

preMassCalculation(status)

Replace the mass properties before they are computed. Return a Java RigidBody, or None.

preSimpleThrustCalculation

preSimpleThrustCalculation(status)

Replace the thrust (N) before it is computed. Return a number, or nan.

preWindModel

preWindModel(status)

Replace the wind velocity before it is computed. Return a Java Coordinate (m/s), or None.

For example, return instance.openrocket_core.util.Coordinate(10.0, 0.0, 0.0) gives a constant 10 m/s wind along the x axis.

postAccelerationCalculation

postAccelerationCalculation(status, acceleration_data)

Replace the computed acceleration. Return a Java AccelerationData, or None to keep it.

postAerodynamicCalculation

postAerodynamicCalculation(status, aerodynamic_forces)

Replace the computed aerodynamic forces. Return a Java AerodynamicForces, or None to keep them.

postAtmosphericModel

postAtmosphericModel(status, atmospheric_conditions)

Replace the computed atmospheric conditions. Return Java AtmosphericConditions, or None.

postFlightConditions

postFlightConditions(status, flight_conditions)

Replace the computed flight conditions. Return a Java FlightConditions, or None to keep them.

postGravityModel

postGravityModel(status, gravity)

Replace the computed gravitational acceleration (m/s²). Return a number, or nan to keep it.

postMassCalculation

postMassCalculation(status, mass_data)

Replace the computed mass properties. Return a Java RigidBody, or None to keep them.

postSimpleThrustCalculation

postSimpleThrustCalculation(status, thrust)

Replace the computed thrust (N). Return a number, or nan to keep it.

postWindModel

postWindModel(status, wind)

Replace the computed wind velocity. Return a Java Coordinate (m/s), or None to keep it.

clone

clone()

Called by OpenRocket to copy the listener. This is a shallow copy; see the warning above.

Flight data and events

The two enums mirror OpenRocket's own. All their members are listed, with their units and the versions that have them, in Flight data variables and Flight events.

FlightDataType

Bases: Enum

The variables OpenRocket records during a simulation, for example TYPE_ALTITUDE.

Pass members, or their names as strings, to Helper.get_timeseries and Helper.get_final_values. Values are in SI units. See Flight data variables for every member, with its unit and the OpenRocket versions that have it.

FlightEvent

Bases: Enum

The kinds of event OpenRocket records during a flight, for example APOGEE or BURNOUT.

Helper.get_events returns them as dictionary keys. See Flight events for every member.

Sample data

sample_ork_path

sample_ork_path() -> str

Return the path of the sample rocket (simple.ork) bundled with orhelper.

Handy for trying the library without a rocket file of your own::

doc = helper.load_doc(orhelper.sample_ork_path())

Exceptions

All of orhelper's own errors derive from OrHelperError, which is a RuntimeError. Errors from OpenRocket itself are Java exceptions raised by JPype.

OrHelperError

Bases: RuntimeError

Base class for errors raised by orhelper itself.

OpenRocketNotFoundError

Bases: OrHelperError

The OpenRocket installation or jar file could not be found.

Point orhelper at it with OpenRocketInstance(jar="/path/to/OpenRocket.jar") or OpenRocketInstance(orhome="/path/to/OpenRocket").

JVMNotFoundError

Bases: OrHelperError

No usable Java Virtual Machine could be found.

Point orhelper at one with OpenRocketInstance(jvm="/path/to/libjvm.so"), or install a Java runtime (Java 17 for OpenRocket 23.09 and newer).

JVMAlreadyStartedError

Bases: OrHelperError

The JVM was already started in this Python process.

JPype can start the JVM only once per process, even after it was shut down. Do all OpenRocket work inside a single with OpenRocketInstance() block, or use a new process.