You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
import sys
import os
import logging
import orhelper as orh
import jpype
import numpy as np
import math
from random import gauss
import matplotlib.pyplot as plt
from jpype.types import *
num=20
# Configure logging
logging.basicConfig(level=logging.DEBUG)
# Set the rocket file path
rocket_file_path = r"E:/Dispersion Simulations/Dispersion Undeleted/Average Wind Speed.ork" # Use a raw string for Windows paths
if not os.path.exists(rocket_file_path):
logging.error(f"Rocket file not found at {rocket_file_path}")
sys.exit(1)
# Ensure JAVA_HOME is correctly set
os.environ['JAVA_HOME'] = r"C:/Program Files/Java/jdk1.8.0_202"
try:
with orh.OpenRocketInstance() as instance:
import java.awt
logging.info("OpenRocket instance started.")
# Initialize the helper
orh_helper = orh.Helper(instance)
# Try loading the rocket file
try:
logging.info("Loading rocket file...")
doc = orh_helper.load_doc(rocket_file_path)
logging.info("Rocket file loaded successfully.")
except Exception as e:
logging.error(f"Failed to load rocket file: {e}")
raise
# Perform operations with the loaded document
try:
sim = doc.getSimulation(0)
opts = sim.getOptions()
rocket = opts.getRocket()
logging.info("Rocket and simulation loaded successfully.")
if __name__ == '__main__':
def list_simulations_and_motor_configs(doc):
num_sims = doc.getSimulationCount()
print(f"Total Simulations: {num_sims}")
for i in range(num_sims):
sim = doc.getSimulation(i)
motor_config = sim.getOptions().getMotorConfigurationID()
print(f"Simulation {i}: Motor Configuration = {motor_config}")
# Call this function after loading the document
list_simulations_and_motor_configs(doc)
def get_motor_configuration_name(simulation):
config = simulation.getOptions().getMotorConfigurationID() # Get motor configuration ID
return config if config else "No motor configuration set"
for stage_index, stage in enumerate(stages):
motors = stage.getMotors()
motor_counts = {}
# Count occurrences of each motor type
for motor in motors:
motor_designation = motor.getMotorDesignation()
if motor_designation in motor_counts:
motor_counts[motor_designation] += 1
else:
motor_counts[motor_designation] = 1
# Build stage motor name
stage_name = " + ".join(
[f"{count}x{motor}" if count > 1 else motor for motor, count in motor_counts.items()]
)
config_names.append(stage_name)
return " + ".join(config_names)
# Open OpenRocket and load a .ork file
sim = doc.getSimulation(0) # Get first simulation
motor_config_name = get_motor_configuration_name(sim)
print("Motor Configuration:", motor_config_name)
# Example simulation listener
class LandingPoints(orh.AbstractSimulationListener):
def __init__(self):
self.ranges = []
self.bearings = []
def startSimulation(self, status):
position = status.getRocketPosition()
self.ranges.append(position.getRange())
self.bearings.append(position.getBearing())
def print_stats(self):
if not self.ranges or not self.bearings:
print("No landing points to analyze.")
return
print(f'Rocket landing zone: {np.mean(self.ranges):.2f} m ± {np.std(self.ranges):.2f} m bearing '
f'{np.degrees(np.mean(self.bearings)):.2f} deg ± {np.degrees(np.std(self.bearings)):.4f} deg '
f'from launch site. Based on {len(self.ranges)} simulations.')
def plot_landing_zones(self):
if not self.ranges or not self.bearings:
print("No data to plot.")
return
plt.figure(figsize=(10, 6))
plt.scatter(self.ranges, np.degrees(self.bearings), c='blue', marker='o')
plt.title('Landing Zones')
plt.xlabel('Range (m)')
plt.ylabel('Bearing (degrees)')
plt.grid(True)
plt.show()
# Randomize various parameters
opts = sim.getOptions()
rocket = opts.getRocket()
# Run num simulations and add to self
for p in range(num):
print('Running simulation ', p)
opts.setLaunchRodAngle(math.radians(gauss(45, 5))) # 45 +- 5 deg in direction
opts.setLaunchRodDirection(math.radians(gauss(0, 5))) # 0 +- 5 deg in direction
opts.setWindSpeedAverage(gauss(15, 5)) # 15 +- 5 m/s in wind
#for component_name in ('Nose cone', 'Body tube'): # 5% in the mass of various components
#component = shape
#mass = component.getMass()
#component.setMassOverridden(True)
#component.setOverrideMass(mass * gauss(1.0, 0.05))
#airstarter = AirStart(gauss(1000, 50)) # simulation listener to drop from 1000 m +- 50
#lp = LandingPoint(self.ranges, self.bearings)
#orh.run_simulation(sim, listeners=(airstarter, lp))
#self.append(lp)
def print_stats(self):
print(
'Rocket landing zone %3.2f m +- %3.2f m bearing %3.2f deg +- %3.4f deg from launch site. Based on %i simulations.' % \
(np.mean(self.ranges), np.std(self.ranges), np.degrees(np.mean(self.bearings)),
np.degrees(np.std(self.bearings)), len(self)))
class LandingPoint(orh.AbstractSimulationListener):
def __init__(self, ranges, bearings):
self.ranges = ranges
self.bearings = bearings
def endSimulation(self, status, simulation_exception):
worldpos = status.getRocketWorldPosition()
conditions = status.getSimulationConditions()
launchpos = conditions.getLaunchSite()
geodetic_computation = conditions.getGeodeticComputation()
if geodetic_computation != geodetic_computation.FLAT:
raise Exception("GeodeticComputationStrategy type not supported")
self.ranges.append(range_flat(launchpos, worldpos))
self.bearings.append(bearing_flat(launchpos, worldpos))
class AirStart(orh.AbstractSimulationListener):
def __init__(self, altitude):
self.start_altitude = altitude
def startSimulation(self, status):
position = status.getRocketPosition()
position = position.add(0.0, 0.0, self.start_altitude)
status.setRocketPosition(position)
METERS_PER_DEGREE_LATITUDE = 111325
METERS_PER_DEGREE_LONGITUDE_EQUATOR = 111050
def range_flat(start, end):
dy = (end.getLatitudeDeg() - start.getLatitudeDeg()) * METERS_PER_DEGREE_LATITUDE
dx = (end.getLongitudeDeg() - start.getLongitudeDeg()) * METERS_PER_DEGREE_LONGITUDE_EQUATOR
return math.sqrt(dy * dy + dx * dx)
def bearing_flat(start, end):
dy = (end.getLatitudeDeg() - start.getLatitudeDeg()) * METERS_PER_DEGREE_LATITUDE
dx = (end.getLongitudeDeg() - start.getLongitudeDeg()) * METERS_PER_DEGREE_LONGITUDE_EQUATOR
return math.pi / 2 - math.atan(dy / dx)
if __name__ == '__main__':
points = LandingPoints()
#points.add_simulations(20)
points.print_stats()
except Exception as e:
logging.error(f"An error occurred: {e}", exc_info=True)
finally:
if jpype.isJVMStarted():
logging.info("JVM is still running.")
except Exception as e:
logging.error(f"Error processing rocket file: {e}")
raise
INFO:orhelper._orhelper:Starting JVM from C:\Program Files\Java\jdk1.8.0_202\jre\bin\server\jvm.dll CLASSPATH=OpenRocket-15.03.jar
00:42:56.077 [main] INFO n.s.o.s.providers.TranslatorProvider - Using default locale en_US
00:42:56.083 [main] INFO n.s.o.s.providers.TranslatorProvider - Set up translation for locale en_US, debug.currentFile=messages.properties
00:42:56.088 [DatabaseLoadingThread] INFO n.s.o.d.ComponentPresetDatabaseLoader - Loading component presets from datafiles/presets
00:42:56.089 [DatabaseLoadingThread] DEBUG net.sf.openrocket.util.JarUtil - Found jar file using codeSource
00:42:56.089 [DatabaseLoadingThread] INFO n.s.o.database.MotorDatabaseLoader - Starting reading serialized motor database
00:42:56.089 [DatabaseLoadingThread] DEBUG net.sf.openrocket.util.JarUtil - Found jar file using codeSource
00:42:56.101 [DatabaseLoadingThread] DEBUG n.s.o.database.MotorDatabaseLoader - Reading motors from file datafiles/thrustcurves/thrustcurves.ser
00:42:56.247 [DatabaseLoadingThread] INFO n.s.o.database.MotorDatabaseLoader - Ending reading serialized motor database, motorCount=1721
00:42:56.247 [DatabaseLoadingThread] INFO n.s.o.database.MotorDatabaseLoader - Starting reading user-defined motors
00:42:56.253 [DatabaseLoadingThread] INFO n.s.o.database.MotorDatabaseLoader - Ending reading user-defined motors, motorCount=1721
00:42:56.265 [DatabaseLoadingThread] DEBUG n.s.o.d.ComponentPresetDatabaseLoader - Time to load presets: 177ms 1622 loaded from 1 files
INFO:root:OpenRocket instance started.
INFO:root:Loading rocket file...
INFO:root:Rocket file loaded successfully.
INFO:root:Rocket and simulation loaded successfully.
Total Simulations: 1
Simulation 0: Motor Configuration = None
Motor Configuration: No motor configuration set
Running simulation 0
Running simulation 1
Running simulation 2
Running simulation 3
Running simulation 4
Running simulation 5
Running simulation 6
Running simulation 7
Running simulation 8
Running simulation 9
Running simulation 10
Running simulation 11
Running simulation 12
Running simulation 13
Running simulation 14
Running simulation 15
Running simulation 16
Running simulation 17
Running simulation 18
Running simulation 19
No landing points to analyze.
INFO:root:JVM is still running.
INFO:orhelper._orhelper:JVM shut down
(program exited with code: 0)
Press any key to continue . . .
Updated Monte Carlo Python Code, issue in detection of motor configuration, need help. For code to work follow original orhelper documentation for setup, also make sure to select all and left indent everything using "Ctrl + U" (shortcut depends on IDE) until the indentation is aligned with left most wall of the IDE.
The text was updated successfully, but these errors were encountered:
1.) Is the only issue you experience with the monte carlo sim that the motor configurations are not detected?
The old code had a lot more errors and would not work at all.
I fixed all of that and put it into the new code
The new code will give an output but the only issue is the motor configurations
Once that issue is fixed, and another issue arises, I can fix that on my end as long as it is fixable on my end, I can ask for help after that if this is the case
2.) Does your PR do anything to solve that issue? If not, what does your PR do, in simple terms (don't explain the code, explain what the code aims to do).
Logging and Error Handling
The new script adds logging for debugging, making it easier to track errors and program flow.
It includes error handling for missing files, JVM issues, and simulation errors, preventing crashes and making debugging easier.
JVM Configuration Runs Properly
The new script runs JVM for the entire time the code is running without stopping midway.
Simulation and Motor Configuration Listing
The new script includes functions (list_simulations_and_motor_configs and get_motor_configuration_name) to list available simulations and motor configurations.
This improves flexibility by allowing users to inspect and select different simulations rather than assuming a single default.
Fixes all Compile Errors due to Mishandling of Variables
The new script successfully compiles because of error logging and try catch, which allows the code to run and for an output to be seen, and many of the bugs were fixed. If the user was to compile the old code, there would be no output at all, and openrocket would not even be used. I cannot list everything that it fixes because I fixed so many errors as I was debugging, but most was basically having try catch exceptions, and logging to ensure code can get fixed.
INFO:orhelper._orhelper:Starting JVM from C:\Program Files\Java\jdk1.8.0_202\jre\bin\server\jvm.dll CLASSPATH=OpenRocket-15.03.jar
00:42:56.077 [main] INFO n.s.o.s.providers.TranslatorProvider - Using default locale en_US
00:42:56.083 [main] INFO n.s.o.s.providers.TranslatorProvider - Set up translation for locale en_US, debug.currentFile=messages.properties
00:42:56.088 [DatabaseLoadingThread] INFO n.s.o.d.ComponentPresetDatabaseLoader - Loading component presets from datafiles/presets
00:42:56.089 [DatabaseLoadingThread] DEBUG net.sf.openrocket.util.JarUtil - Found jar file using codeSource
00:42:56.089 [DatabaseLoadingThread] INFO n.s.o.database.MotorDatabaseLoader - Starting reading serialized motor database
00:42:56.089 [DatabaseLoadingThread] DEBUG net.sf.openrocket.util.JarUtil - Found jar file using codeSource
00:42:56.101 [DatabaseLoadingThread] DEBUG n.s.o.database.MotorDatabaseLoader - Reading motors from file datafiles/thrustcurves/thrustcurves.ser
00:42:56.247 [DatabaseLoadingThread] INFO n.s.o.database.MotorDatabaseLoader - Ending reading serialized motor database, motorCount=1721
00:42:56.247 [DatabaseLoadingThread] INFO n.s.o.database.MotorDatabaseLoader - Starting reading user-defined motors
00:42:56.253 [DatabaseLoadingThread] INFO n.s.o.database.MotorDatabaseLoader - Ending reading user-defined motors, motorCount=1721
00:42:56.265 [DatabaseLoadingThread] DEBUG n.s.o.d.ComponentPresetDatabaseLoader - Time to load presets: 177ms 1622 loaded from 1 files
INFO:root:OpenRocket instance started.
INFO:root:Loading rocket file...
INFO:root:Rocket file loaded successfully.
INFO:root:Rocket and simulation loaded successfully.
Total Simulations: 1
Simulation 0: Motor Configuration = None
Motor Configuration: No motor configuration set
Running simulation 0
Running simulation 1
Running simulation 2
Running simulation 3
Running simulation 4
Running simulation 5
Running simulation 6
Running simulation 7
Running simulation 8
Running simulation 9
Running simulation 10
Running simulation 11
Running simulation 12
Running simulation 13
Running simulation 14
Running simulation 15
Running simulation 16
Running simulation 17
Running simulation 18
Running simulation 19
No landing points to analyze.
INFO:root:JVM is still running.
INFO:orhelper._orhelper:JVM shut down
(program exited with code: 0)
Press any key to continue . . .
Updated Monte Carlo Python Code, issue in detection of motor configuration, need help. For code to work follow original orhelper documentation for setup, also make sure to select all and left indent everything using "Ctrl + U" (shortcut depends on IDE) until the indentation is aligned with left most wall of the IDE.
The text was updated successfully, but these errors were encountered: