コード例 #1
0
    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)
コード例 #2
0
    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()
コード例 #3
0
    def _plotSimulationResults(self, rocketStages, simDefinition, flights, logFilePaths):
        ''' Plot simulation results (as/if specified in sim definition) '''

        plotsToMake = simDefinition.getValue("SimControl.plot").split()

        if plotsToMake != ["None"]:

            if "FlightAnimation" in plotsToMake:
                print("Showing flight animation")

                # Show animation
                Plotting.flightAnimation(flights)

                # Done, remove from plotsToMake
                plotsToMake.remove("FlightAnimation")

            if "FlightPaths" in plotsToMake:
                earthModel = self.simDefinition.getValue("Environment.EarthModel")
                if earthModel in [ "None", "Flat" ]:
                    Plotting.plotFlightPaths_NoEarth(flights)
                else:
                    Plotting.plotFlightPaths_FullEarth(flights)

                plotsToMake.remove("FlightPaths")

            # Plot all other columns from log files
            for plotDefinitionString in plotsToMake:
                Plotting.plotFromLogFiles(logFilePaths, plotDefinitionString)
コード例 #4
0
    def postProcess(flight):
        # Save results
        landingLocations.append(flight.getLandingLocation())
        apogees.append(flight.getApogee())
        maxSpeeds.append(flight.getMaxSpeed())
        flightTimes.append(flight.getFlightTime())
        maxHorizontalVels.append(flight.getMaxHorizontalVel())

        if "flightPaths" in resultsToOutput:
            flight = Plotting._keepNTimeSteps(
                flight, 900
            )  # Limit the number of time steps saved to avoid wasting memory
            flights.append(flight)
コード例 #5
0
def OptimizationFunction(logFilesList):

    #print(logFilesList)
    #print("HEEEEEYYYYYY!!!!!!", file=sys.__stdout__)
    #print(logFilesList, file=sys.__stdout__)

    filePath = None
    for logFile in logFilesList:
        if ("ControlSystem_Log.csv" in logFile):
            filePath = logFile
            break

    if filePath == None:
        raise ValueError("ERROR: could not find controlSystemEvaluationLog. Make sure logging level is at least 4. Available log files: {}".format(logFilesList))

    columnSpecs = ["Time","Error"]

    columns, columnNames = Plotting.getLoggedColumns(filePath, columnSpecs, enableCache=False)

    pitchErrorIntegral = 0
    yawErrorIntegral = 0
    rollErrorIntegral = 0

    #print(columnNames,file=sys.__stdout__)
    #print(columns,file=sys.__stdout__)

    for i in range(len(columns[0])):

        if i == 0:
            pass
        
        else:
            deltaT = columns[0][i] - columns[0][i-1]
            pitchErrorIntegral += ((columns[1][i])**2)*deltaT
            yawErrorIntegral += ((columns[2][i])**2)*deltaT
            rollErrorIntegral += ((columns[3][i])**2)*deltaT
    
    #print(deltaT, file=sys.__stdout__)
    #print(pitchErrorIntegral, file=sys.__stdout__)
    #print(yawErrorIntegral, file=sys.__stdout__)
    #print(rollErrorIntegral, file=sys.__stdout__)

    cost = 100*(0.5*pitchErrorIntegral + 0.5*yawErrorIntegral + rollErrorIntegral)

    print(cost, file=sys.__stdout__)

    for logFileName in logFilesList:
        os.remove(logFileName)


    return cost
コード例 #6
0
 def test_flightAnimation(self):
     Plotting.flightAnimation([self.flight], showPlot=False)
     plt.clf()
     
     maxDimension = 1
     centerOfPlot = Vector(0,0,0)
     refAxis, perpVectors = Plotting._createReferenceVectors(3, maxDimension)
     fig, ax = Plotting._createAnimationFigure(maxDimension, centerOfPlot)
     cgPoints, flightPathLines, longitudinalRocketLines, allCanardLines, allPerpLines = Plotting._createInitialFlightAnimationPlot(ax, 3, [self.flight], refAxis, perpVectors)
     
     # Try updating the plot
     Plotting._update_plot(2, [self.flight], refAxis, perpVectors, cgPoints, flightPathLines, longitudinalRocketLines, allCanardLines, allPerpLines)
コード例 #7
0
    def postProcess(rayObject):
        ''' Gets sim results from worker, appends results to outputLists '''
        # Get sim results
        stagePaths, logPaths = ray.get(rayObject)

        # Save results from the top stage
        flight = stagePaths[0]

        landingLocations.append(flight.getLandingLocation())
        apogees.append(flight.getApogee())
        maxSpeeds.append(flight.getMaxSpeed())
        flightTimes.append(flight.getFlightTime())
        maxHorizontalVels.append(flight.getMaxHorizontalVel())

        if "flightPaths" in resultsToOutput:
            flight = Plotting._keepNTimeSteps(
                flight, 900
            )  # Limit the number of time steps saved to avoid wasting memory
            flights.append(flight)
コード例 #8
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")
コード例 #9
0
 def test_plotAndSummarizeScalarResult(self):
     scalarList = [ 1, 2, 3 ]
     Plotting.plotAndSummarizeScalarResult(scalarList, showPlot=False)
コード例 #10
0
 def test_plotAndSummarizeVectorResult(self):
     vectorList = [ Vector(0,1,2), Vector(1,2,3)]
     Plotting.plotAndSummarizeVectorResult(vectorList, showPlot=False)
コード例 #11
0
 def test_KeepNTimeSteps(self):
     Plotting._keepNTimeSteps([self.flight], nFramesToKeep=2)
コード例 #12
0
 def test_plotFlightPaths(self):
     Plotting.plotFlightPaths_NoEarth([self.flight], showPlot=False)
コード例 #13
0
def _showResults(simDefinition, outputLists, mCLogger):
    landingLocations, apogees, maxSpeeds, flightTimes, maxHorizontalVels, flights = outputLists
    resultsToOutput = simDefinition.getValue("MonteCarlo.output")

    mCLogger.log("")
    mCLogger.log("Monte Carlo results:")

    if "landingLocations" in resultsToOutput:
        Plotting.plotAndSummarizeVectorResult(landingLocations,
                                              name="Landing location",
                                              monteCarloLogger=mCLogger)
    if "apogees" in resultsToOutput:
        Plotting.plotAndSummarizeScalarResult(apogees,
                                              name="Apogee",
                                              monteCarloLogger=mCLogger)
    if "maxSpeeds" in resultsToOutput:
        Plotting.plotAndSummarizeScalarResult(maxSpeeds,
                                              name="Max speed",
                                              monteCarloLogger=mCLogger)
    if "flightTimes" in resultsToOutput:
        Plotting.plotAndSummarizeScalarResult(flightTimes,
                                              name="Flight time",
                                              monteCarloLogger=mCLogger)
    if "maxHorizontalVels" in resultsToOutput:
        Plotting.plotAndSummarizeScalarResult(maxHorizontalVels,
                                              name="Max horizontal speed",
                                              monteCarloLogger=mCLogger)
    if "flightPaths" in resultsToOutput:
        Plotting.plotFlightPaths_NoEarth(flights)

    if resultsToOutput != "None" and len(resultsToOutput) > 0:
        dotIndex = simDefinition.fileName.rfind('.')
        extensionFreeSimDefFileName = simDefinition.fileName[0:dotIndex]
        logFilePath = extensionFreeSimDefFileName + "_monteCarloLog_run"

        logPath = mCLogger.writeToFile(fileBaseName=logFilePath)
        print("Wrote Monte Carlo Log to: {}".format(logPath))