예제 #1
0
 def __init__(self,
              simDefinitionFilePath=None,
              simDefinition=None,
              silent=False):
     Simulation.__init__(self,
                         simDefinitionFilePath=simDefinitionFilePath,
                         simDefinition=simDefinition,
                         silent=silent)
예제 #2
0
    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)
예제 #3
0
    def test_RK45AdaptSim(self):
        # Smoke test
        simDef = SimDefinition("MAPLEAF/Examples/Simulations/Wind.mapleaf",
                               silent=True)
        simDef.setValue("SimControl.timeDiscretization", "RK45Adaptive")
        simDef.setValue("SimControl.TimeStepAdaptation.controller", "PID")
        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)
예제 #4
0
    def test_Initialization_NASASphere(self):
        simRunner = Simulation("./MAPLEAF/Examples/Simulations/NASASphere.mapleaf")
        sphere = simRunner.createRocket()

        # Should be at an altitude of 9144 m above earth's surface
        distanceFromEarthCenter = sphere.rigidBody.state.position.length()
        expected = sphere.environment.earthModel.a + 9144
        self.assertAlmostEqual(distanceFromEarthCenter, expected)

        # Should have zero angular velocity in inertial frame
        angVel = sphere.rigidBody.state.angularVelocity.length()
        self.assertAlmostEqual(angVel, 0.0)

        # Velocity should be zero in earth-fixed frame
        rotationVel = distanceFromEarthCenter * sphere.environment.earthModel.rotationRate
        inertialVel = sphere.rigidBody.state.velocity
        assertVectorsAlmostEqual(self, inertialVel, Vector(0, rotationVel, 0))
예제 #5
0
    def test_bodyTubeDampingMoment(self):
        simRunner = Simulation("MAPLEAF/Examples/Simulations/test3.mapleaf",
                               silent=True)
        rocket = simRunner.createRocket()

        bodyTube = rocket.stages[0].getComponentsOfType(BodyTube)[0]

        # Create a rigid body state rotating at 2 rad/s about the x-axis
        pos = Vector(0, 0, 0)
        vel = Vector(0, 0, 0)
        orientation = Quaternion(1, 0, 0, 0)
        angVel = AngularVelocity(2, 0, 0)
        xRotatingState = RigidBodyState(pos, vel, orientation, angVel)
        envConditions = rocket.environment.getAirProperties(Vector(0, 0, 0))

        #### CoR = Middle of the body tube ####
        fakeRocketCG = Vector(0, 0, -1.762)

        # Get computed (numerically-integrated) result
        calculatedDampingMoment = bodyTube._computeLongitudinalDampingMoments(
            xRotatingState, envConditions, fakeRocketCG, nSegments=100)

        # Compute analytical result (Niskanen Eqn 3.58) * 2 for both halves of the body tube (above and below center of rotation)
        expectedXDampingMoment = 2 * 0.275 * envConditions.Density * (
            bodyTube.outerDiameter / 2) * 4
        expectedTotalDampingMoment = Vector(-expectedXDampingMoment, 0, 0)

        # Compare
        assertVectorsAlmostEqual(self, calculatedDampingMoment,
                                 expectedTotalDampingMoment, 4)

        #### Case 2: CoR at End of Body Tube ####
        fakeRocketCG = Vector(0, 0, -2.762)

        # Get computed (numerically-integrated) result
        calculatedDampingMoment = bodyTube._computeLongitudinalDampingMoments(
            xRotatingState, envConditions, fakeRocketCG, nSegments=150)

        # Factor of 16 from moving to a tube length of two (2^4 = 16), but dividing by two (one half instead of two)
        expectedTotalDampingMoment *= 8

        # Compare
        assertVectorsAlmostEqual(self, calculatedDampingMoment,
                                 expectedTotalDampingMoment, 4)
예제 #6
0
    def test_Init(self):
        with self.assertRaises(ValueError):
            shouldCrash = Simulation()  # Needs a sim definition file

        shouldntCrash = Simulation(
            "MAPLEAF/Examples/Simulations/AdaptTimeStep.mapleaf", silent=True)
        simDefinition = shouldntCrash.simDefinition
        shouldntCrash2 = Simulation(
            simDefinitionFilePath=
            "MAPLEAF/Examples/Simulations/AdaptTimeStep.mapleaf",
            simDefinition=simDefinition,
            silent=True)

        #### Set up sim definition ####
        test.testUtilities.setUpSimDefForMinimalRunCheck(simDefinition)
        shouldntCrash2 = Simulation(simDefinition=simDefinition, silent=True)
        shouldntCrash2.run()
예제 #7
0
def main(argv=None) -> int:
    ''' 
        Main function to run a MAPLEAF simulation. 
        Expects to be called from the command line, usually using the `mapleaf` command
        
        For testing purposes, can also pass a list of command line arguments into the argv parameter
    '''
    startTime = time.time()

    # Parse command line call, check for errors
    parser = buildParser()
    args = parser.parse_args(argv)

    if len(args.plotFromLog):
        # Just plot a column from a log file, and not run a whole simulation
        Plotting.plotFromLogFiles([args.plotFromLog[1]], args.plotFromLog[0])
        print("Exiting")
        sys.exit()

    # Load simulation definition file
    simDefPath = findSimDefinitionFile(args.simDefinitionFile)
    simDef = SimDefinition(simDefPath)

    #### Run simulation(s) ####
    if args.parallel:
        try:
            import ray
        except:
            print("""
            Error importing ray. 
            Ensure ray is installed (`pip install -U ray`) and importable (`import ray` should not throw an error). 
            If on windows, consider trying Linux or running in WSL, at the time this was written, ray on windows was still in beta and unreliable.
            Alternatively, run without parallelization.
            """)

    if isOptimizationProblem(simDef):
        optSimRunner = optimizationRunnerFactory(simDefinition=simDef,
                                                 silent=args.silent,
                                                 parallel=args.parallel)
        optSimRunner.runOptimization()

    elif isMonteCarloSimulation(simDef):
        if not args.parallel:
            nCores = 1
        else:
            import multiprocessing
            nCores = multiprocessing.cpu_count()

        runMonteCarloSimulation(simDefinition=simDef,
                                silent=args.silent,
                                nCores=nCores)

    elif args.parallel:
        raise ValueError(
            "ERROR: Can only run Monte Carlo of Optimization-type simulations in multi-threaded mode. Support for multi-threaded batch simulations coming soon."
        )

    elif isBatchSim(simDef):
        print("Batch Simulation\n")
        batchMain([simDef.fileName])

    elif args.converge or args.compareIntegrationSchemes or args.compareAdaptiveIntegrationSchemes:
        cSimRunner = ConvergenceSimRunner(simDefinition=simDef,
                                          silent=args.silent)
        if args.converge:
            cSimRunner.convergeSimEndPosition()
        elif args.compareIntegrationSchemes:
            cSimRunner.compareClassicalIntegrationSchemes(
                convergenceResultFilePath='convergenceResult.csv')
        elif args.compareAdaptiveIntegrationSchemes:
            cSimRunner.compareAdaptiveIntegrationSchemes(
                convergenceResultFilePath='adaptiveConvergenceResult.csv')

    else:
        # Run a regular, single simulation
        sim = Simulation(simDefinition=simDef, silent=args.silent)
        sim.run()

    Logging.removeLogger()

    print("Run time: {:1.2f} seconds".format(time.time() - startTime))
    print("Exiting")
예제 #8
0
 def setup(self):
     simDef = SimDefinition(
         "MAPLEAF/Examples/Simulations/benchmarkSim.mapleaf")
     simDef.setValue("SimControl.loggingLevel", "2")
     sim = Simulation(simDefinition=simDef, silent=True)
     self.rocket = sim.createRocket()
예제 #9
0
 def setup(self):
     simDef = SimDefinition(
         "MAPLEAF/Examples/Simulations/benchmarkSim.mapleaf")
     sim = Simulation(simDefinition=simDef, silent=True)
     self.rocket = sim.createRocket()
예제 #10
0
 def time_initializeSimulationAndRocket(self):
     sim = Simulation("MAPLEAF/Examples/Simulations/benchmarkSim.mapleaf",
                      silent=True)
     sim.createRocket()
예제 #11
0
    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)