def setUp(self): self.rocket = "fakeNewsRocket" # May have to convert this into a real Rocket at some point, but it's faster this way self.simDefinition = SimDefinition( "MAPLEAF/Examples/Simulations/Wind.mapleaf", silent=True) self.simDefinition.setValue("Environment.MeanWindModel", "Constant") envReader = SubDictReader("Environment", self.simDefinition) self.mWM = meanWindModelFactory(envReader, self.rocket)
def _loadBatchOptimization(self): if not self.silent: print("Batch Optimization") # Optimization dictionary now requires an entry called batchDefinition # In this case the 'simDefinition' might only contain an Optimization dictionary # Could also contain the Rocket definition, if the same 'simDefinition' file is referenced in the Batch Definition batchDefinitionPath = self.optimizationReader.getString("Optimization.batchDefinition") batchDefinitionPath = getAbsoluteFilePath(batchDefinitionPath) # Make sure path points to a real file, turn it into an absolute path # Load batch definition file batchDefinition = SimDefinition(batchDefinitionPath) # Prep and store the cases it references self.simDefinitions = [] caseDictNames = batchDefinition.getImmediateSubDicts("") # Each root-level dictionary represents a case print("Found the following cases:") for case in sorted(caseDictNames): print(case, file=sys.__stdout__) # Get sim definition file path simDefPath = batchDefinition.getValue("{}.simDefinitionFile".format(case)) simDefPath = getAbsoluteFilePath(simDefPath) # Load it, implement overrides defined in the batch file caseDefinition = SimDefinition(simDefPath, silent=True) _implementParameterOverrides(case, batchDefinition, caseDefinition) # Save self.simDefinitions.append(caseDefinition) print("") # Add some white space
def test_writeToFile(self): #### Check rocket-only autowriting #### self.simDef.writeToFile("test/test_IO/testWrite.mapleaf") # Get output file1 = open("test/test_IO/testWrite.mapleaf", 'r') f1 = file1.read() f1 = re.sub("# Autowritten on:.+?\\n", "", f1) file1.close() # Get Correct output file2 = open("test/test_IO/testWriteCorrectOutput.mapleaf", 'r') f2 = file2.read() f2 = re.sub("# Autowritten on:.+?\\n", "", f2) file2.close() # Compare self.assertEqual(f1, f2) #### Check simConfig autowriting #### simConfig = SimDefinition("test/test_IO/testSimDefinition.mapleaf", silent=True) testWritePath = "test/test_IO/testSimConfigWrite.mapleaf" simConfig.writeToFile(testWritePath) simConfig2 = SimDefinition(testWritePath, silent=True) self.assertEqual(simConfig, simConfig2)
def test_PSOOptimization(self): simDef = SimDefinition( "MAPLEAF/Examples/Simulations/Optimization.mapleaf", silent=True) optSimRunner = optimizationRunnerFactory(simDefinition=simDef, silent=True) # Check output of _loadIndependentVariables() self.assertEqual(optSimRunner.varKeys, ["Rocket.Sustainer.UpperBodyTube.mass"]) self.assertEqual(optSimRunner.varNames, ["bodyWeight"]) self.assertEqual(optSimRunner.minVals, [0.01]) self.assertEqual(optSimRunner.maxVals, [0.2]) # Check out of _loadDependentVariables() self.assertEqual(optSimRunner.dependentVars, ["Rocket.Sustainer.Nosecone.mass"]) self.assertEqual(optSimRunner.dependentVarDefinitions, ["!0.007506 + 0.015/bodyWeight!"]) # Check output of _createOptimizer() self.assertEqual(optSimRunner.nIterations, 20) self.assertEqual(optSimRunner.showConvergence, True) self.assertEqual(optSimRunner.optimizer.n_particles, 5) # Check updating independent variable values indVarDict = optSimRunner._updateIndependentVariableValues( simDef, [0.15]) self.assertEqual( simDef.getValue("Rocket.Sustainer.UpperBodyTube.mass"), "0.15") self.assertEqual(indVarDict, {"bodyWeight": 0.15}) # Check updating dependent variables values optSimRunner._updateDependentVariableValues(simDef, indVarDict) self.assertAlmostEqual( float(simDef.getValue("Rocket.Sustainer.Nosecone.mass")), 0.107506)
def test_burnTimeAdjustFactor(self): simDef = SimDefinition("MAPLEAF/Examples/Simulations/test2.mapleaf") # Create normal motor rocketDictReader1 = SubDictReader("Rocket", simDef) motorRocket1 = Rocket(rocketDictReader1) motor1 = motorRocket1.stages[0].getComponentsOfType(TabulatedMotor)[0] burnTimeAdjustFactor = "1.11" # Create impulse-adjusted motor simDef.setValue("Rocket.Sustainer.Motor.burnTimeAdjustFactor", burnTimeAdjustFactor) rocketDictReader2 = SubDictReader("Rocket", simDef) motorRocket2 = Rocket(rocketDictReader2) motor2 = motorRocket2.stages[0].getComponentsOfType(TabulatedMotor)[0] # Check that total impulse hasn't changed impulse1 = motor1.getTotalImpulse() impulse2 = motor2.getTotalImpulse() self.assertAlmostEqual(impulse1, impulse2) # Check that burn time has changed burnTime1 = motor1.times[-1] burnTime2 = motor2.times[-1] self.assertAlmostEqual(burnTime2 / burnTime1, float(burnTimeAdjustFactor))
def setUp(self): self.rocket = "fakeNewsRocket" # May have to convert this into a real Rocket at some point, but it's faster this way self.simDefinition = SimDefinition( "MAPLEAF/Examples/Simulations/Wind.mapleaf", silent=True) self.simDefinition.setValue("Environment.MeanWindModel", "Constant") self.simDefinition.setValue("Environment.ConstantMeanWind.velocity", "(0 0 0)")
def test_isBatchSim(self): # Checks whether the batch sim detection function is working batchDefinition = SimDefinition("batchRunTemplate.mapleaf") self.assertTrue(isBatchSim(batchDefinition)) normalDefinition = SimDefinition( "MAPLEAF/Examples/Simulations/Wind.mapleaf") self.assertFalse(isBatchSim(normalDefinition))
def test_isMonteCarloSim(self): monteCarloSimDef = SimDefinition( "MAPLEAF/Examples/Simulations/MonteCarlo.mapleaf", silent=True) self.assertTrue(isMonteCarloSimulation(monteCarloSimDef)) nonMonteCarloSimDef = SimDefinition( "MAPLEAF/Examples/Simulations/Wind.mapleaf", silent=True) self.assertFalse(isMonteCarloSimulation(nonMonteCarloSimDef))
def test_classBasedDefaultValues(self): simConfig = SimDefinition("test/test_IO/testSimDefinition.mapleaf", silent=True) self.assertEqual( simConfig.getValue( "Rocket.Sustainer.TailFins.Actuators.controller"), "TableInterpolating") self.assertEqual( simConfig.getValue("Rocket.Sustainer.TailFins.finCantAngle"), "0")
def setUp(self): configFilePath = "MAPLEAF/Examples/Simulations/Wind.mapleaf" self.simDef = SimDefinition(configFilePath, silent=True) self.simDef.setValue("Environment.MeanWindModel", "Constant") self.simDef.setValue("SimControl.loggingLevel", "0") rocketDictReader = SubDictReader("Rocket", self.simDef) envReader = SubDictReader("Environment", self.simDef) self.rocket = Rocket(rocketDictReader, silent=True) self.mWM = meanWindModelFactory(envReader, self.rocket)
def setUp(self): simDef = SimDefinition("MAPLEAF/Examples/Simulations/Canards.mapleaf", silent=True) simDef.setValue("SimControl.loggingLevel", "0") simDef.setValue("Rocket.ControlSystem.MomentController.gainTableFilePath", "MAPLEAF/Examples/TabulatedData/testPIDControlLaw.txt") simDef.setValue("Rocket.Sustainer.Canards.Actuators.deflectionTablePath","MAPLEAF/Examples/TabulatedData/testFinDeflectionLaw.txt") simDef.removeKey("Rocket.ControlSystem.FlightPlan.filePath") simRunner = Simulation(simDefinition=simDef, silent=True) self.rocket = simRunner.createRocket()
def test_relativeFilepath(self): simulationDefinition = SimDefinition( 'test/test_IO/testRelativeMotorPath.mapleaf', silent=True) motorFilePath = simulationDefinition.getValue( 'Rocket.Sustainer.Motor.path') self.assertTrue(os.path.isfile(motorFilePath)) # Ensure relative path expansion does not corrupt plot line formats self.assertEqual( simulationDefinition.getValue('Rocket.Sustainer.Motor.lineFormat'), '.')
def test_rocketCGCalculation(self): # Check actual CG Loc Calculation # Top stage CG: # # Nosecone: 1 kg @ 0m # Recovery: 5 kg @ -2m # BodyTube: 1 kg @ -0.762m # Mass: 50 kg @ -2.6m # Motor: 11.4885 kg @ 2.130434783 # Fins: 1 kg @ -4.011m # Total Weight = 69.4885 kg # Stage 1 CG: -2.4564359077698 expectedCG = Vector(0, 0, -1.731185736) # Remove overrides from rocket definition file simDef = SimDefinition("MAPLEAF/Examples/Simulations/Wind.mapleaf", silent=True) simDef.removeKey("Rocket.Sustainer.constCG") simDef.removeKey("Rocket.Sustainer.constMass") simDef.removeKey("Rocket.Sustainer.constMOI") rocketDictReader = SubDictReader("Rocket", simDef) rocket = Rocket(rocketDictReader, silent=True) rocketInertia = rocket.getInertia(0, rocket.rigidBody.state) assertVectorsAlmostEqual(self, rocketInertia.CG, expectedCG, n=4)
def setUp(self): simDef = SimDefinition("MAPLEAF/Examples/Simulations/test3.mapleaf", silent=True) rocketDictReader = SubDictReader("Rocket", simDef) self.rocket = Rocket(rocketDictReader, silent=True) simDef = SimDefinition("MAPLEAF/Examples/Simulations/test6.mapleaf", silent=True) rocketDictReader = SubDictReader("Rocket", simDef) self.rocket2 = Rocket(rocketDictReader, silent=True) self.finSet1 = self.rocket2.stages[0].getComponentsOfType(FinSet)[0] self.finSet2 = self.rocket2.stages[0].getComponentsOfType(FinSet)[1] self.dummyVelocity1 = Vector(0, 0, 50) self.dummyVelocity2 = Vector(1, 0, 20) self.dummyVelocity3 = Vector(0, 0, -100) self.dummyOrientation1 = Quaternion(Vector(1, 0, 0), math.radians(2)) self.dummyOrientation2 = Quaternion(Vector(1, 0, 0), math.radians(-2)) self.dummyOrientation3 = Quaternion(Vector(0, 1, 0), math.radians(2)) self.dummyOrientation4 = Quaternion(Vector(1, 0, 0), 0) self.dummyOrientation5 = Quaternion(Vector(1, 1, 0), math.radians(2)) self.dummyOrientation6 = Quaternion(Vector(1,0,0), math.radians(90)) self.dummyAngularVelocity1 = AngularVelocity(rotationVector = Vector(0,0,0)) self.dummyAngularVelocity2 = AngularVelocity(rotationVector = Vector(0,0,1)) self.dummyAngularVelocity3 = AngularVelocity(rotationVector = Vector(0,0,-1)) self.dummyAngularVelocity4 = AngularVelocity(rotationVector = Vector(1,0,0)) self.dummyAngularVelocity5 = AngularVelocity(rotationVector = Vector(-1,0,0)) self.dummyAngularVelocity6 = AngularVelocity(rotationVector = Vector(0,1,0)) self.dummyAngularVelocity7 = AngularVelocity(rotationVector = Vector(0,-1,0)) self.dummyAngularVelocity8 = AngularVelocity(rotationVector = Vector(1,1,0)) self.currentConditions = self.rocket2.environment.getAirProperties(Vector(0,0,200)) # m self.rocketState1 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, 200), Quaternion(Vector(0, 0, 1), 0), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState2 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, 200), Quaternion(Vector(1, 0, 0), math.radians(2)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState3 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, 500), Quaternion(Vector(1, 0, 0), math.radians(2)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState4 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, -200), Quaternion(Vector(1, 0, 0), math.radians(180)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState5 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, -200), Quaternion(Vector(1, 0, 0), math.radians(178)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState6 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, -200), Quaternion(Vector(1, 0, 0), math.radians(182)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState7 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, -200), Quaternion(Vector(1, 0, 0), math.radians(90)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState8 = RigidBodyState(Vector(0, 0, 200), Vector(20.04, -0.12, -52.78), Quaternion(Vector(0, 1, 0), math.radians(90)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState9 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, 200), Quaternion(Vector(1, 0, 0), math.radians(-2)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState10 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, 200), Quaternion(Vector(0, 0, 1), 0), AngularVelocity(rotationVector=Vector(0, 0, 1))) self.rocketState11 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, 200), Quaternion(Vector(0, 1, 0), math.radians(2)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState12 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, 200), Quaternion(Vector(0, 1, 0), math.radians(-2)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState13 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, 500), Quaternion(Vector(1, 0, 0), math.radians(4)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState14 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, 500), Quaternion(Vector(1, 0, 0), math.radians(6)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState15 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, 500), Quaternion(Vector(1, 0, 0), math.radians(8)), AngularVelocity(rotationVector=Vector(0, 0, 0))) self.rocketState16 = RigidBodyState(Vector(0, 0, 200), Vector(0, 0, 344), Quaternion(Vector(1, 0, 0), math.radians(0)), AngularVelocity(rotationVector=Vector(0, 0, 0)))
def test_initPosition(self): # Modify file to include a launch rail simDef = SimDefinition( "MAPLEAF/Examples/Simulations/AdaptTimeStep.mapleaf") simDef.setValue("Environment.LaunchSite.railLength", "10") # Initialize environment with launch rail env = Environment(simDef) # Check that launch rail has been created self.assertTrue(env.launchRail != None) # Check initial launch rail position and direction initPos = Vector(0, 0, 15 + 755) # Rocket position + launch site elevation assertVectorsAlmostEqual(self, initPos, env.launchRail.initialPosition)
def test_TabulatedAeroForce(self): # Init rocket that uses tabulated aero data simDef = SimDefinition("MAPLEAF/Examples/Simulations/NASATwoStageOrbitalRocket.mapleaf", silent=True) rocketDictReader = SubDictReader("Rocket", simDef) rocket = Rocket(rocketDictReader, silent=True) comp1, comp2, comp3 = rocket.stages[0].getComponentsOfType(TabulatedAeroForce) if comp1.Lref == 3.0: tabMoment = comp1 tabFOrce = comp2 else: tabMoment = comp2 tabForce = comp1 zeroAOAState = RigidBodyState(Vector(0,0,0), Vector(0,0,100), Quaternion(1,0,0,0), Vector(0,0,0)) # CD, CL, CMx, CMy, CMz expectedAero = [ 0.21, 0, 0, 0, 0 ] calculatedAero = tabForce._getAeroCoefficients(zeroAOAState, self.currentConditions) assertIterablesAlmostEqual(self, expectedAero, calculatedAero) expectedAero = [ 0, 0, 0, 0, 0 ] calculatedAero = tabMoment._getAeroCoefficients(zeroAOAState, self.currentConditions) assertIterablesAlmostEqual(self, expectedAero, calculatedAero)
def test_convergenceSimulations(self): #### Set up sim definition #### convSimDef = SimDefinition( "MAPLEAF/Examples/Simulations/AdaptTimeStep.mapleaf", silent=True) test.testUtilities.setUpSimDefForMinimalRunCheck(convSimDef) #### Run Convergence Simulations #### convSR = ConvergenceSimRunner(simDefinition=convSimDef, silent=True) convSR.convergeSimEndPosition(simLimit=2, showPlot=False) tempTestFilePath = "testConvergResult.csv" convSR.compareClassicalIntegrationSchemes( showPlot=False, simLimit=2, integrationSchemes=["Euler"], convergenceResultFilePath=tempTestFilePath) convSR.simDefinition.setValue( "SimControl.TimeStepAdaptation.targetError", "1e-4") convSR.simDefinition.setValue( "SimControl.TimeStepAdaptation.controller", "PID") convSR.compareAdaptiveIntegrationSchemes( showPlot=False, simLimit=2, integrationSchemes=["RK12Adaptive"], convergenceResultFilePath=tempTestFilePath) # Remove temp file os.remove(tempTestFilePath)
def test_plotColumn(self): # Load sim definition file simDef = SimDefinition("MAPLEAF/Examples/Simulations/AdaptTimeStep.mapleaf", silent=True) test.testUtilities.setUpSimDefForMinimalRunCheck(simDef) simDef.setValue("SimControl.EndConditionValue", "0.03") # Generate log file from a simulation simDef.setValue("SimControl.loggingLevel", "2") simDef.fileName = "test/tempTestFileasdf.txt" simRunner = Main.Simulation(simDefinition=simDef, silent=True) _, logfilePaths = simRunner.run() # Try to plot one of its columns (AeroForce) Plotting.tryPlottingFromLog(logfilePaths[1], ["AeroF"], showPlot=False) ax = plt.gca() nLines = len(ax.lines) self.assertEqual(nLines, 3) Plotting.tryPlottingFromLog(logfilePaths[0], ["Position"], showPlot=False) ax = plt.gca() nLines = len(ax.lines) self.assertEqual(nLines, 3) # Delete temp files logDirectory = os.path.dirname(logfilePaths[0]) shutil.rmtree(logDirectory)
def test_plotFromLog(self): # Load sim definition file simDef = SimDefinition("MAPLEAF/Examples/Simulations/AdaptTimeStep.mapleaf", silent=True) test.testUtilities.setUpSimDefForMinimalRunCheck(simDef) simDef.setValue("SimControl.EndConditionValue", "0.03") # Generate log file from a simulation simDef.setValue("SimControl.loggingLevel", "2") simDef.fileName = "test/tempTestFileasdf.txt" simRunner = Main.Simulation(simDefinition=simDef, silent=True) _, logfilePaths = simRunner.run() # Try to plot one of its columns (AeroForce) Plotting.plotFromLogFiles(logfilePaths, "Position&^Velocity", showPlot=False) # The '^' in front of Velocity is for a Regex match, indicating the start of a line # This will prevent it from also plotting the AngularVelocity along with the Position and Velocity columns ax = plt.gca() nLines = len(ax.lines) self.assertEqual(nLines, 6) # Try to plot one of its columns (AeroForce) Plotting.plotFromLogFiles(logfilePaths, "Position&Velocity", showPlot=False) ax = plt.gca() nLines = len(ax.lines) self.assertEqual(nLines, 9) # Delete temp files logDirectory = os.path.dirname(logfilePaths[0]) shutil.rmtree(logDirectory) # Clear the plot plt.clf()
def test_fixedForceInit(self): simDef = SimDefinition("MAPLEAF/Examples/Simulations/FixedForce.mapleaf", silent=True) rocketDictReader = SubDictReader("Rocket", simDef) rocket = Rocket(rocketDictReader, silent=True) fixedForce = rocket.stages[0].getComponentsOfType(FixedForce)[0] expectedFMS = ForceMomentSystem(Vector(0,0,0), Vector(0,0,0), Vector(0,1,0)) assertForceMomentSystemsAlmostEqual(self, fixedForce.force, expectedFMS)
def test_SolidMotor(self): simDef = SimDefinition("MAPLEAF/Examples/Simulations/Jake1.mapleaf") rocketDictReader = SubDictReader("Rocket", simDef) motorRocket = Rocket(rocketDictReader) motor = motorRocket.stages[0].motor # Try getting thrust, if it works with 0 oxidizer flow rate, then we're good t = motor.getAppliedForce('fakeState', 0.12, 'fakeEnv', 'fakeCG').force.Z
def test_getFixedForceInertia(self): simDef = SimDefinition("MAPLEAF/Examples/Simulations/FixedForce.mapleaf", silent=True) rocketDictReader = SubDictReader("Rocket", simDef) rocket = Rocket(rocketDictReader, silent=True) fixedForce = rocket.stages[0].getComponentsOfType(FixedForce)[0] inertia = fixedForce.getInertia(0, "fakeState") expectedInertia = Inertia(Vector(0,0,0), Vector(0,0,0), 0) self.assertEqual(inertia, expectedInertia)
def test_MotorMOI(self): motorRocket = self.motorRocket motor = self.motorRocket.stages[0].getComponentsOfType( TabulatedMotor)[0] ### Oxidizer MOI Tests ### def getOxMOI(time): return motor._getOxInertia(time).MOI ActualOxMOI = getOxMOI(0) expectedOxMOI = Vector(1.0, 1.0, 0.1) assertIterablesAlmostEqual(self, ActualOxMOI, expectedOxMOI) ActualOxMOI = getOxMOI(2.505) expectedOxMOI = Vector(0.5, 0.5, 0.05) assertIterablesAlmostEqual(self, ActualOxMOI, expectedOxMOI) ActualOxMOI = getOxMOI(5.0) expectedOxMOI = Vector(0, 0, 0) assertIterablesAlmostEqual(self, ActualOxMOI, expectedOxMOI) ActualOxMOI = getOxMOI(10) expectedOxMOI = Vector(0, 0, 0) assertIterablesAlmostEqual(self, ActualOxMOI, expectedOxMOI) ### Fuel MOI Tests ### def getFuelMOI(time): return motor._getFuelInertia(time).MOI ActualFuelMOI = getFuelMOI(0) expectedFuelMOI = Vector(0.15, 0.15, 0.02) assertIterablesAlmostEqual(self, ActualFuelMOI, expectedFuelMOI) ActualFuelMOI = getFuelMOI(2.505) expectedFuelMOI = Vector(0.075, 0.075, 0.01) assertIterablesAlmostEqual(self, ActualFuelMOI, expectedFuelMOI) ActualFuelMOI = getFuelMOI(5) expectedFuelMOI = Vector(0, 0, 0) assertIterablesAlmostEqual(self, ActualFuelMOI, expectedFuelMOI) ActualFuelMOI = getFuelMOI(10) expectedFuelMOI = Vector(0, 0, 0) assertIterablesAlmostEqual(self, ActualFuelMOI, expectedFuelMOI) simDef = SimDefinition("MAPLEAF/Examples/Simulations/Jake1.mapleaf") rocketDictReader = SubDictReader("Rocket", simDef) jakeRocket = Rocket(rocketDictReader) motor = jakeRocket.stages[0].motor motorInertia = motor.getInertia(3, jakeRocket.rigidBody.state) expectedInertiaAfterBurnout = Inertia(Vector(0, 0, 0), Vector(0, 0, 0), 0.0) assertInertiasAlmostEqual(self, motorInertia, expectedInertiaAfterBurnout)
def test_MonteCarlo(self): #### Set up sim definition #### mCSimDef = SimDefinition( "MAPLEAF/Examples/Simulations/MonteCarlo.mapleaf", silent=True) test.testUtilities.setUpSimDefForMinimalRunCheck_MonteCarlo(mCSimDef) #### Run Monte Carlo Simulations #### runMonteCarloSimulation(simDefinition=mCSimDef, silent=True) # Make sure monte carlo sampling is occurring wind = mCSimDef.getValue("Environment.ConstantMeanWind.velocity") self.assertNotEqual(wind, "( 2 0 0 )") self.assertTrue( "Environment.ConstantMeanWind.velocity_mean" in mCSimDef.dict) # Run second simulation, expect new wind value runMonteCarloSimulation(simDefinition=mCSimDef, silent=True) wind2 = mCSimDef.getValue("Environment.ConstantMeanWind.velocity") self.assertNotEqual(wind, wind2)
def test_getFixedForce(self): simDef = SimDefinition("MAPLEAF/Examples/Simulations/FixedForce.mapleaf", silent=True) rocketDictReader = SubDictReader("Rocket", simDef) rocket = Rocket(rocketDictReader, silent=True) fixedForce = rocket.stages[0].getComponentsOfType(FixedForce)[0] force = fixedForce.getAppliedForce("fakeState", 0, "fakeEnv", Vector(0,0,0)) expectedForce = ForceMomentSystem(Vector(0,0,0), moment=Vector(0,1,0)) self.assertEqual(force.force, expectedForce.force) self.assertEqual(force.moment, expectedForce.moment)
def loadSimDefinition(simDefinitionFilePath=None, simDefinition=None, silent=False): ''' Loads a simulation definition file into a `MAPLEAF.IO.SimDefinition` object - accepts either a file path or a `MAPLEAF.IO.SimDefinition` object as input ''' if simDefinition == None and simDefinitionFilePath != None: return SimDefinition(simDefinitionFilePath, silent=silent) # Parse simulation definition file elif simDefinition != None: return simDefinition # Use the SimDefinition that was passed in else: raise ValueError(""" Insufficient information to initialize a Simulation. Please provide either simDefinitionFilePath (string) or fW (SimDefinition), which has been created from the desired Sim Definition file. If both are provided, the SimDefinition is used.""")
def test_RK4Sim(self): # Smoke test simDef = SimDefinition("MAPLEAF/Examples/Simulations/Wind.mapleaf", silent=True) simRunner = Simulation(simDefinition=simDef, silent=True) rocket = simRunner.createRocket() # 6-DoF time step rocket.timeStep(0.05) # 3-DoF time step rocket.isUnderChute = True rocket._switchTo3DoF() rocket.timeStep(0.05)
def test_checkForOutOfDateDefaultValues(self): AllPossibleOptions = SimDefinition("SimDefinitionTemplate.mapleaf") for key in defaultConfigValues: # Can only perform this check for keys that aren't class-based (start with one of the root dictionary names) if "." not in key or key[:key.index('.')] not in [ "Rocket", "Environment", "SimControl", "MonteCarlo" ]: continue if not key in AllPossibleOptions.dict: raise ValueError( "Key {} in default values, not in Sim Definition Template. Update which ever one is out of date" .format(key))
def test_init(self): # Modify file to include a launch rail simDef = SimDefinition( "MAPLEAF/Examples/Simulations/NASATwoStageOrbitalRocket.mapleaf") simDef.setValue("Environment.LaunchSite.railLength", "15") # Initialize environment with launch rail env = Environment(simDef) # Check that launch rail has been created self.assertTrue(env.launchRail != None) # Check initial launch rail position and direction r = 6378137 + 13.89622 initPos = Vector(r, 0, 0) assertVectorsAlmostEqual(self, initPos, env.launchRail.initialPosition) initDir = Vector(math.cos(math.radians(34.78)), math.sin(math.radians(34.78)), 0).normalize() assertVectorsAlmostEqual(self, initDir, env.launchRail.initialDirection) self.assertAlmostEqual(env.launchRail.length, 15)
def test_Initialization_Velocity(self): # Zero velocity in launch tower frame simDef = SimDefinition("MAPLEAF/Examples/Simulations/NASATwoStageOrbitalRocket.mapleaf", silent=True) simDef.setValue("Rocket.velocity", "(0 0 0)") simRunner = Simulation(simDefinition=simDef, silent=True) rocket = simRunner.createRocket() computedInitGlobalFrameVel = rocket.rigidBody.state.velocity expectdedVel = Vector(0, 465.1020982258931, 0) # Earth's surface velocity at 0 lat, 0 long assertVectorsAlmostEqual(self, computedInitGlobalFrameVel, expectdedVel) # Velocity in the +x (East) direction in the launch tower frame simDef.setValue("Rocket.velocity", "(1 0 0)") simRunner = Simulation(simDefinition=simDef, silent=True) rocket = simRunner.createRocket() computedInitGlobalFrameVel = rocket.rigidBody.state.velocity expectdedVel = Vector(0, 466.1020982258931, 0) # Earth's surface velocity at 0 lat, 0 long + 1m/s east assertVectorsAlmostEqual(self, computedInitGlobalFrameVel, expectdedVel) # Velocity in the +y (North) direction in the launch tower frame simDef.setValue("Rocket.velocity", "(0 1 0)") simRunner = Simulation(simDefinition=simDef, silent=True) rocket = simRunner.createRocket() computedInitGlobalFrameVel = rocket.rigidBody.state.velocity expectdedVel = Vector(0, 465.1020982258931, 1) # Earth's surface velocity at 0 lat, 0 long + 1m/s north assertVectorsAlmostEqual(self, computedInitGlobalFrameVel, expectdedVel) # Velocity in the +z (Up) direction in the launch tower frame simDef.setValue("Rocket.velocity", "(0 0 1)") simRunner = Simulation(simDefinition=simDef, silent=True) rocket = simRunner.createRocket() computedInitGlobalFrameVel = rocket.rigidBody.state.velocity expectdedVel = Vector(1, 465.1020982258931, 0) # Earth's surface velocity at 0 lat, 0 long + 1m/s up assertVectorsAlmostEqual(self, computedInitGlobalFrameVel, expectdedVel)