Пример #1
0
    def add_simulations(self, num):
        with orhelper.OpenRocketInstance() as instance:

            # Load the document and get simulation
            orh = orhelper.Helper(instance)
            doc = orh.load_doc(os.path.join('examples', 'simple.ork'))
            sim = doc.getSimulation(0)

            # 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 = orh.get_component_named(rocket, component_name)
                    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 add_simulations(self, num):
        with orhelper.OpenRocketInstance('../lib/build/jar/OpenRocket.jar', log_level='ERROR'):

            # Load the document and get simulation
            orh = orhelper.Helper()

            doc = orh.load_doc(self.args.rocket)
            parachute_setting = doc.getRocket().getParachute().getDeployEvent().toString()
            parachuteFlag = False

            # Run num simulations and add to self
            print("Running {} sims".format(num))
            for p in range(num):
                print ('Running simulation ', p+1)

                sim = doc.getSimulation(0)
                # Randomize various parameters
                opts = sim.getOptions()
                rocket = opts.getRocket()
                
                if (p == (num - self.args.parachute)):
                    doc.getRocket().getParachute().setDeployEventCustom("never")
                    parachuteFlag = True

                # Set latitude and longitude
                sim.getOptions().setLaunchLatitude(self.args.startLat)
                sim.getOptions().setLaunchLongitude(self.args.startLong)

                sim.getOptions().setLaunchRodAngle(math.pi/3)
                
                opts.setLaunchRodAngle(math.radians( gauss(self.args.rodAngle, self.args.rodAngleSigma) ))
                opts.setLaunchRodDirection(math.radians( gauss(self.args.rodDirection, self.args.rodDirectionSigma) ))
                opts.setWindSpeedAverage( gauss(self.args.windSpeed, self.args.windSpeedSigma) )
                for component_name in ('Nose cone', 'Body tube'):
                    component = orh.get_component_named( rocket, component_name )
                    mass = component.getMass()
                    component.setMassOverridden(True)
                    component.setOverrideMass( mass * gauss(1.0, 0.05) )
                
                # Call computation listeners
                ma = MaxAltitude()
                lp = LandingPoint()
                pu = PositionUpwind()
                pp = PositionParallel()
                lm = LateralMovement()

                wd = WindListener(self.args.windDirection, self.args.windSpeed)
                mp = MotorPerformance(self.args.motorPerformance)

                rf = FinListener(self.args.pValue, self.args.iValue)
                orh.run_simulation(sim, [lp, ma, pu, pp, lm,wd,mp, rf])
                self.landing_points.append( lp )
                self.max_altitudes.append( ma )
                self.upwind.append( pu )
                self.parallel.append ( pp )
                self.lateral_movement.append( lm )   
                self.parachute_fail.append (parachuteFlag)
Пример #3
0
def run_sims(settings):
    log_file = "logs/" + settings['id'] + ".cass"

    points_done = -1
    if not os.path.isfile(log_file):
        with open(log_file,'w') as sim_file:
            sim_file.write('MIT Rocket Team Cassandra v0.1 Analysis' + os.linesep)
            sim_file.write('Date: ' + datetime.now().strftime("%Y-%m-%d %H:%M") + os.linesep)
            sim_file.write('Params: ' + json.dumps(settings) + os.linesep + os.linesep)
    else:
        get_points(settings['id'],settings['points'])
        points_done = len(settings['points'])

    print("Current directory: " + str(os.getcwd()))
    with orhelper.OpenRocketInstance('/app/req/OpenRocket.jar', log_level='DEBUG'):
        # Load the document and get simulation
        orh = orhelper.Helper()
        doc = orh.load_doc('/app/rockets/'+settings['filename'])
        sim = doc.getSimulation(0)

        opts = sim.getOptions()
        rocket = opts.getRocket()

        for p in range(points_done,settings['iters']):
            print('Running simulation ', p+1)

            wind_dir = get_prop(settings['gauss'],'Wind direction')

            opts.setLaunchRodAngle(math.radians(get_prop(settings['gauss'],'Rod angle',angle=True)))
            opts.setLaunchRodDirection(math.radians(get_prop(settings['gauss'],'Rod direction',angle=True)-wind_dir))

            opts.setWindSpeedAverage(get_prop(settings['gauss'],'Wind speed'))
            opts.setLaunchTemperature(273.15+get_prop(settings['gauss'],'Launch temperature'))
            opts.setLaunchPressure(get_prop(settings['gauss'],'Launch pressure'))
            opts.setLaunchRodLength(get_prop(settings['gauss'],'Rod length'))

            orh.run_simulation(sim)
            data = orh.get_timeseries(sim,DEFAULT_STATS+settings['params'])
            events = orh.get_events(sim)

            for key in data:
                if key == "Lateral direction":
                    data[key] += math.radians(wind_dir)
                data[key] = data[key].tolist()

            datapoint = {'data':data,'events':events}
            with open(log_file,'a') as sim_file:
                json.dump(datapoint, sim_file)
                sim_file.write(os.linesep)
Пример #4
0
    def solve_nonlinear(self, params, unknowns, resids):
        # Instantiate OpenRocket if it has not been already
        if self.openRocket == None:
            dir = path.dirname(path.realpath(__file__))
            jarpath = dir.replace("scripts", "openmeta-OpenRocket.jar")
            self.openRocket = orhelper.OpenRocketInstance(jarpath)

        # opens Open Rocket
        orh = orhelper.Helper()

        # Load document
        doc = orh.load_doc('rocket.ork')

        # Run OpenRocket simulation (first sim has a faulty motor)
        sim = doc.getSimulation(1)
        simOptions = sim.getOptions(
        )  # get handle for simulation options class
        simOptions.setRandomSeed(0)  # get rid of randomization
        simOptions.setWindSpeedAverage(params['WindSpeed'])  # set wind speed

        orh.run_simulation(sim)

        flightData = sim.getSimulatedData()
        data = orh.get_timeseries(sim, [
            'Time', 'Altitude', 'Stability margin calibers', 'Mass', 'Thrust'
        ])
        events = orh.get_events(sim)
        self.plot(data, events)

        # derive stability and mass info
        try:
            launchRodCleared = events['Launch rod clearance']
            index_launchRodCleared = np.where(data['Time'] == launchRodCleared)
            stability_launchRodCleared = data['Stability margin calibers'][
                index_launchRodCleared]
            mass_launchRodCleared = data['Mass'][index_launchRodCleared]
        except:
            # sometimes the simulation shuts down before launch rod clearance, so set values to -1 (error)
            stability_launchRodCleared = -1
            mass_launchRodCleared = -1

        try:
            motorBurnout = events['Motor burnout']
            index_motorBurnout = np.where(data['Time'] == motorBurnout)
            stability_motorBurnout = data['Stability margin calibers'][
                index_motorBurnout]
            mass_motorBurnout = data['Mass'][index_motorBurnout]
        except:
            # sometimes the simulation shuts down before the motors burnout, so set burnout mass to -1 (error)
            mass_motorBurnout = -1

        try:
            index_maxStability = np.nanargmax(
                data['Stability margin calibers'])
            maxStability = data['Stability margin calibers'][
                index_maxStability]
        except:
            # sometimes the simulation doesn't record stability, so set burnout mass to -1
            maxStability = -1

        # export flight data
        unknowns['MaxVelocity'] = flightData.getMaxVelocity()
        unknowns['MaxAltitude'] = flightData.getMaxAltitude()
        unknowns['MaxAcceleration'] = flightData.getMaxAcceleration()
        unknowns['MaxMach'] = flightData.getMaxMachNumber()
        unknowns['GroundHitVelocity'] = flightData.getGroundHitVelocity()
        unknowns['LaunchRodVelocity'] = flightData.getLaunchRodVelocity()
        unknowns['FlightTime'] = flightData.getFlightTime()
        unknowns['MaxStability'] = maxStability
        unknowns['LaunchRodClearanceStability'] = stability_launchRodCleared
        unknowns['LaunchRodClearanceMass'] = mass_launchRodCleared
        unknowns['BurnoutMass'] = mass_motorBurnout
Пример #5
0
import numpy as np
from matplotlib import pyplot as plt

import orhelper

with orhelper.OpenRocketInstance():
    orh = orhelper.Helper()

    # Load document, run simulation and get data and events

    doc = orh.load_doc('estes_gnome.ork')
    sim = doc.getSimulation(0)
    orh.run_simulation(sim)
    data = orh.get_timeseries(sim, ['Time', 'Altitude', 'Vertical velocity'])
    events = orh.get_events(sim)

    # Make a custom plot the simulation

    events_to_annotate = ['Motor burnout', 'Apogee', 'Launch rod clearance']
    fig = plt.figure()
    ax1 = fig.add_subplot(111)
    ax2 = ax1.twinx()

    ax1.plot(data['Time'], data['Altitude'], 'b-')
    ax2.plot(data['Time'], data['Vertical velocity'], 'r-')
    ax1.set_xlabel('Time (s)')
    ax1.set_ylabel('Altitude (m)', color='b')
    ax2.set_ylabel('Vertical Velocity (m/s)', color='r')
    change_color = lambda ax, col: [
        x.set_color(col) for x in ax.get_yticklabels()
    ]
Пример #6
0
import os

import numpy as np
from matplotlib import pyplot as plt

import orhelper
from orhelper import FlightDataType, FlightEvent

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

    # Load document, run simulation and get data and events

    doc = orh.load_doc(os.path.join('examples', 'simple.ork'))
    sim = doc.getSimulation(0)
    orh.run_simulation(sim)
    data = orh.get_timeseries(sim, [
        FlightDataType.TYPE_TIME, FlightDataType.TYPE_ALTITUDE,
        FlightDataType.TYPE_VELOCITY_Z
    ])
    events = orh.get_events(sim)

    # Make a custom plot of the simulation

    events_to_annotate = {
        FlightEvent.BURNOUT: 'Motor burnout',
        FlightEvent.APOGEE: 'Apogee',
        FlightEvent.LAUNCHROD: 'Launch rod clearance'
    }

    fig = plt.figure()