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
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 isinfo.openrocket.core, ornet.sf.openrocketin OpenRocket 22.02 and 23.09.Noneuntil the JVM has started. -
openrocket_swing–The Java package with OpenRocket's user interface classes (the same package as
openrocket_corein 22.02 and 23.09).Noneuntil 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
jarkeyword 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
OrLogLevelor its name (case-insensitive):OFF,ERROR,WARN,INFO(the default),DEBUG,TRACEorALL. This sets the level of OpenRocket's own Java logging and of theorhelperPython logger. orhelper does not configure Python logging handlers; calllogging.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.dyliborjvm.dll).jvm_args: list of extra arguments for the JVM, for example["-Xmx2g"]or["-Djava.awt.headless=true"].loglevel: the same aslog_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__
¶
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__
¶
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
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
withblock.
load_doc
¶
Load an OpenRocket (.ork) file.
Parameters:
-
or_filename(Union[str, PathLike]) –Path of the file.
Returns:
-
–
The Java
OpenRocketDocument. Usedocument.getRocket()for the rocket anddocument.getSimulation(0)(orgetSimulations()) for its simulations.
Raises:
-
RocketLoadException–(a Java exception) If the file is missing or can't be read.
save_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 byload_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:
-
sim–The Java
Simulation, for exampledocument.getSimulation(0). -
listeners(Optional[Iterable[AbstractSimulationListener]], default:None) –Optional
AbstractSimulationListenerinstances to call during the simulation.
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:
-
flight_data_type(Union[FlightDataType, str]) –A
FlightDataTypemember or its name.
Returns:
-
–
The Java
FlightDataTypeconstant.
Raises:
-
TypeError–If the argument is neither a
FlightDataTypenor 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, afterrun_simulation. -
variables(Iterable[Union[FlightDataType, str]]) –The
FlightDataTypemembers, 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, afterrun_simulation. -
variables(Iterable[Union[FlightDataType, str]]) –The
FlightDataTypemembers, 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
FlightEventenum, 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, afterrun_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
FlightEventthat occurred to the list of times, in seconds, at which it did. Most events occur once.
get_component_named
¶
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
RocketComponentwith that name. Change it with its Java setters, for examplesetLength(...)orsetOverrideMass(...).
Raises:
-
ValueError–If there is no component with that name.
JIterator
¶
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...Branchversions,preStepandpostStep. - Event hooks (
addFlightEvent,handleFlightEvent,motorIgnition,recoveryDeviceDeployment): returnTrueto let things happen normally (the default) orFalseto prevent it. - Computation hooks (
pre...andpost...): called around the models OpenRocket evaluates in each step. ReturnNone(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: thepre...hooks replace the value before it is computed, thepost...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
¶
Called when the simulation starts.
Parameters:
-
status–The Java
SimulationStatus. You can change it, for example to start the rocket at another position.
endSimulation
¶
Called when the simulation ends, normally or because of an error.
Parameters:
-
status–The Java
SimulationStatus. -
simulation_exception–The Java
SimulationExceptionthat ended the simulation, orNoneif it ended normally.
startSimulationBranch
¶
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
SimulationStatusof the branch.
endSimulationBranch
¶
Called when a branch ends, normally or because of an error. Like startSimulationBranch, only
OpenRocket 26.xx calls it.
Parameters:
-
status–The Java
SimulationStatusof the branch. -
simulation_exception–The Java
SimulationExceptionthat ended the branch, orNone.
preStep
¶
Called before every simulation step.
Parameters:
-
status–The Java
SimulationStatus.
Returns:
-
bool–Trueto take the step (the default),Falseto skip it. A skipped step does not advance the simulation, so don't returnFalseon every call.
postStep
¶
Called after every simulation step, also when preStep skipped it.
Parameters:
-
status–The Java
SimulationStatus, for examplestatus.getSimulationTime()orstatus.getRocketPosition().
isSystemListener
¶
Whether this is one of OpenRocket's own listeners. Leave this as False for your own code.
addFlightEvent
¶
Called before an event is added to the event queue.
Parameters:
-
status–The Java
SimulationStatus. -
flight_event–The Java
FlightEventthat is about to be added.
Returns:
-
bool–Trueto add the event (the default),Falseto leave it out.
handleFlightEvent
¶
Called before an event is handled.
Parameters:
-
status–The Java
SimulationStatus. -
flight_event–The Java
FlightEventthat is taking place.
Returns:
-
bool–Trueto handle the event (the default),Falseto ignore it.
motorIgnition
¶
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–Trueto ignite the motor (the default),Falseto prevent it.
recoveryDeviceDeployment
¶
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–Trueto deploy it (the default),Falseto prevent it.
preAccelerationCalculation
¶
Replace the acceleration before it is computed. Return a Java AccelerationData, or None.
preAerodynamicCalculation
¶
Replace the aerodynamic forces before they are computed. Return a Java AerodynamicForces, or None.
preAtmosphericModel
¶
Replace the atmospheric conditions before they are computed. Return Java AtmosphericConditions, or None.
preFlightConditions
¶
Replace the flight conditions before they are computed. Return a Java FlightConditions, or None.
preGravityModel
¶
Replace the gravitational acceleration (m/s²) before it is computed. Return a number, or nan.
preMassCalculation
¶
Replace the mass properties before they are computed. Return a Java RigidBody, or None.
preSimpleThrustCalculation
¶
Replace the thrust (N) before it is computed. Return a number, or nan.
preWindModel
¶
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
¶
Replace the computed acceleration. Return a Java AccelerationData, or None to keep it.
postAerodynamicCalculation
¶
Replace the computed aerodynamic forces. Return a Java AerodynamicForces, or None to keep them.
postAtmosphericModel
¶
Replace the computed atmospheric conditions. Return Java AtmosphericConditions, or None.
postFlightConditions
¶
Replace the computed flight conditions. Return a Java FlightConditions, or None to keep them.
postGravityModel
¶
Replace the computed gravitational acceleration (m/s²). Return a number, or nan to keep it.
postMassCalculation
¶
Replace the computed mass properties. Return a Java RigidBody, or None to keep them.
postSimpleThrustCalculation
¶
Replace the computed thrust (N). Return a number, or nan to keep it.
postWindModel
¶
Replace the computed wind velocity. Return a Java Coordinate (m/s), or None to keep it.
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
¶
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.