/// <summary> /// Runs a single simulation of the Madingley model /// </summary> /// <param name="scenarios">Parameter information and simulation number for all scenarios to be run</param> /// <param name="scenarioIndex">The index of the scenario to be run in this simulation</param> /// <param name="initialiseMadingley">Model initialization information for all simulations</param> /// <param name="outputFileSuffix">Suffix to be applied to the names of files written out by this simulation</param> /// <param name="simulation">The index of the simulation being run</param> public void RunSimulation(ScenarioParameterInitialisation scenarios, int scenarioIndex, MadingleyModelInitialisation initialiseMadingley, string outputFileSuffix, int simulation) { // Declare an instance of the class that runs a Madingley model simulation MadingleyModel MadingleyEcosystemModel; // Declare and start a timer StopWatch s = new StopWatch(); s.Start(); StopWatch t = new StopWatch(); t.Start(); // Initialize the instance of MadingleyModel MadingleyEcosystemModel = new MadingleyModel(initialiseMadingley, scenarios, scenarioIndex, outputFileSuffix, initialiseMadingley.GlobalModelTimeStepUnit, simulation); t.Stop(); // Run the simulation MadingleyEcosystemModel.RunMadingley(initialiseMadingley); // Stop the timer and write out the time taken to run this simulation s.Stop(); Console.WriteLine("Model run finished"); Console.WriteLine("Total elapsed time was {0} seconds", s.GetElapsedTimeSecs()); Console.WriteLine("Model setup time was {0} seconds", t.GetElapsedTimeSecs()); Console.WriteLine("Model run time was {0} seconds", s.GetElapsedTimeSecs() - t.GetElapsedTimeSecs()); }
/// <summary> /// Generates the console outputs for the current time step /// </summary> /// <param name="currentTimeStep">The current model time step</param> /// <param name="currentMonth">The current month in the model run</param> /// <param name="timeStepTimer">The timer for the current time step</param> private void TimeStepConsoleOutputs(uint currentTimeStep, uint currentMonth, StopWatch timeStepTimer) { // Console outputs for all levels of detail Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Completed time step " + (currentTimeStep + 1) + "(Month: " + (currentMonth + 1) + ")\n"); Console.ForegroundColor = ConsoleColor.White; Console.WriteLine("Elapsed time in seconds this time step: " + timeStepTimer.GetElapsedTimeSecs() + "\n"); Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Living biomass = " + String.Format("{0:E}", TotalLivingBiomass / 1000) + " kg"); Console.WriteLine("Total abundance = " + String.Format("{0:E}", TotalAbundance) + " inds / km^2"); // Console outputs for medium or high detail levels if ((ModelOutputDetail == OutputDetailLevel.Medium) || (ModelOutputDetail == OutputDetailLevel.High)) { Console.WriteLine("Total number of cohorts = " + TotalNumberOfCohorts); Console.WriteLine("Total number of stocks = " + TotalNumberOfStocks); Console.WriteLine("Number of cohorts extinct = " + NumberOfCohortsExtinct); Console.WriteLine("Number of cohorts produced = " + NumberOfCohortsProduced); Console.WriteLine("Number of cohorts combined = " + NumberOfCohortsCombined); // Console ouputs for high detail level if (ModelOutputDetail == OutputDetailLevel.High) { Console.WriteLine("Total biomass (all) = " + String.Format("{0:E}", TotalBiomass / 1000) + " kg"); Console.WriteLine("Respiratory pool biomass = " + String.Format("{0:E}", RespiratoryPoolOut / 1000) + " kg"); Console.WriteLine("Organic pool biomass = " + String.Format("{0:E}", OrganicPoolOut / 1000) + " kg"); } } // Blank line at end of console time step outputs Console.WriteLine(" "); Console.ForegroundColor = ConsoleColor.White; }
/// <summary> /// Sets up the model grid within a Madingley model run /// </summary> /// <param name="initialisation">An instance of the model initialisation class</param> /// <param name="scenarioParameters">The parameters for the scenarios to run</param> /// <param name="scenarioIndex">The index of the scenario that this model is to run</param> public void SetUpModelGrid(MadingleyModelInitialisation initialisation, ScenarioParameterInitialisation scenarioParameters, int scenarioIndex, int simulation) #endif { // If the intialisation file contains a column pointing to another file of specific locations, and if this column is not blank then read the // file indicated if (SpecificLocations) { // Set up the model grid using these locations #if true EcosystemModelGrid = new ModelGrid(BottomLatitude, LeftmostLongitude, TopLatitude, RightmostLongitude, CellSize, CellSize, _CellList, CohortFunctionalGroupDefinitions, StockFunctionalGroupDefinitions, GlobalDiagnosticVariables, initialisation.TrackProcesses, SpecificLocations, RunGridCellsInParallel); #else EcosystemModelGrid = new ModelGrid(BottomLatitude, LeftmostLongitude, TopLatitude, RightmostLongitude, CellSize, CellSize, _CellList, EnviroStack, CohortFunctionalGroupDefinitions, StockFunctionalGroupDefinitions, GlobalDiagnosticVariables, initialisation.TrackProcesses, SpecificLocations,RunGridCellsInParallel); #endif } else { EcologyTimer = new StopWatch(); EcologyTimer.Start(); // Set up a full model grid (i.e. not for specific locations) // Set up the model grid using these locations #if true EcosystemModelGrid = new ModelGrid(BottomLatitude, LeftmostLongitude, TopLatitude, RightmostLongitude, CellSize, CellSize, _CellList, CohortFunctionalGroupDefinitions, StockFunctionalGroupDefinitions, GlobalDiagnosticVariables, initialisation.TrackProcesses, SpecificLocations, RunGridCellsInParallel); #else EcosystemModelGrid = new ModelGrid(BottomLatitude, LeftmostLongitude, TopLatitude, RightmostLongitude, CellSize, CellSize, _CellList, EnviroStack, CohortFunctionalGroupDefinitions, StockFunctionalGroupDefinitions, GlobalDiagnosticVariables, initialisation.TrackProcesses, SpecificLocations, RunGridCellsInParallel); #endif EcologyTimer.Stop(); Console.WriteLine("Time to initialise cells: {0}", EcologyTimer.GetElapsedTimeSecs()); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Madingley Model memory usage post grid cell seed: {0}", GC.GetTotalMemory(true) / 1E9, " (G Bytes)\n"); Console.ForegroundColor = ConsoleColor.White; } Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Madingley Model memory usage pre Collect: {0}", Math.Round(GC.GetTotalMemory(true) / 1E9, 2), " (GBytes)"); Console.ForegroundColor = ConsoleColor.White; GC.Collect(); Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Madingley Model memory usage post Collect: {0}", Math.Round(GC.GetTotalMemory(true) / 1E9, 5), " (GBytes)\n"); Console.ForegroundColor = ConsoleColor.White; }
private static void Main(string[] args) { CLP.About(); if (args.Length == 0) { char[] delimiterChars = { ' ' }; if (File.Exists("tpccbench.txt")) { //attempt to open file with command line args in it StreamReader re = File.OpenText("tpccbench.txt"); string input = re.ReadToEnd(); string[] cmdargs = input.Split(delimiterChars); re.Close(); //send the command line to the parser CLP.Cmdline(cmdargs); } else { Globals.Err = 1; Console.WriteLine("tpccbench.txt not found, no commands on command line found."); } } else { CLP.Cmdline(args); } if (Globals.Err == 1) { Console.WriteLine("Error detected, execution stopped."); } else if (Globals.Err == 2) { Console.WriteLine("Program Exit."); } else { //LoadGlobal.LoadGeneralGlobals(); LoadGlobals.LoadMasterConnectionString(); LoadGlobals.LoadLogFilePath(); var trd = new Thread(PLOG.WriteLog); //trd.IsBackground = true; trd.Start(); PLOG.Write("Running Benchmark on server: " + Globals.ServerName); PLOG.Write("Running Benchmark on database: " + Globals.DatabaseName); const string query = "select @@version"; //Console.WriteLine(query); try { //Globals.SQLVersion = ClientDataAccess.RunProc(Globals.StrPublisherConn, query); } catch { Console.WriteLine("Unable to connect to database, correct and retry"); PLOG.Write("Unable to connect to database, correct and retry", 1); Thread.Sleep(1000); Globals.Err = 1; } if (Globals.Err == 1) { Console.WriteLine("Error detected, execution stopped."); } else { if (Globals.Heartbeat == 1) { PLOG.Write("Heartbeat enabled."); var heartbeat = new Thread(TpcUtils.Heartbeat) { IsBackground = true }; heartbeat.Start(); } var stpStartInfo = new STPStartInfo(); if (!(Globals.StaggeredLoad == 0)) { stpStartInfo.StartSuspended = false; stpStartInfo.MaxWorkerThreads = Globals.NumClients + 1; stpStartInfo.MinWorkerThreads = Globals.NumClients + 1; stpStartInfo.IdleTimeout = 10 * 1000; } else { stpStartInfo.StartSuspended = true; stpStartInfo.MaxWorkerThreads = Globals.NumClients + 1; stpStartInfo.MinWorkerThreads = Globals.NumClients + 1; stpStartInfo.IdleTimeout = 10 * 1000; } var smartThreadPool = new SmartThreadPool(stpStartInfo); var s = new StopWatch(); int i = 0; var clients = new Tpcc[Globals.NumClients]; PLOG.Write("Start TPC benchmark :" + DateTime.Now); s.Start(); if (!(Globals.StaggeredLoad == 0)) { while (i < Globals.NumClients) { clients[i] = new Tpcc { Clientid = i + 1 }; smartThreadPool.QueueWorkItem(new WorkItemCallback(clients[i].Client)); Console.WriteLine("Client " + i + " Loaded."); Thread.Sleep(Globals.StaggeredLoad); i++; } } else { while (i < Globals.NumClients) { clients[i] = new Tpcc { Clientid = i + 1 }; smartThreadPool.QueueWorkItem(new WorkItemCallback(clients[i].Client)); i++; } } PLOG.Write("Started On: " + DateTime.Now); if (Globals.NumLoops == 0) { PLOG.Write("Target Run Time: " + (Globals.MaxRunTimeMin)); } else { PLOG.Write("Number of Loops: " + (Globals.NumLoops)); } PLOG.Write("number of clients to load: " + i); PLOG.Write("Work load Mix:"); if (Globals.RawWrite == 0) { PLOG.Write("Percent New Orders: " + Globals.PNO); PLOG.Write("Percent Order Status: " + (Globals.POS)); PLOG.Write("Percent Stock Level: " + (Globals.PSL)); PLOG.Write("Percent Payment: " + (Globals.PP)); PLOG.Write("Percent Delivery: " + (Globals.PD)); PLOG.Write("Total Percent: " + ((Globals.PNO) + (Globals.POS) + (Globals.PSL) + (Globals.PD) + (Globals.PP))); } else { PLOG.Write("Raw Inserts: 100"); } PLOG.Read(); //Console.WriteLine("Threads waiting callback: " + smartThreadPool.WaitingCallbacks); if (Globals.StaggeredLoad == 0) { smartThreadPool.Start(); } // Wait for the completion of all work items smartThreadPool.WaitForIdle(); s.Stop(); smartThreadPool.Shutdown(); if (Globals.RawWrite == 1) { PLOG.Write("Total number of operations: " + Globals.TotalCount); PLOG.Write("elapsed time in seconds: " + s.GetElapsedTimeSecs()); PLOG.Write("elapsed time in minutes: " + s.GetElapsedTimeSecs() / 60); PLOG.Write("Total number of operations per minute: " + (Globals.TotalCount / (s.GetElapsedTimeSecs() / 60))); } else { PLOG.Write("Total number of new orders: " + Globals.Countno); PLOG.Write("Total number of order status: " + Globals.Countos); PLOG.Write("Total number of payments: " + Globals.Countp); PLOG.Write("Total number of new diliveries: " + Globals.Countd); PLOG.Write("Total number of new stock level: " + Globals.Countsl); PLOG.Write("Total number of operations: " + (Globals.Countno + Globals.Countos + Globals.Countp + Globals.Countd + Globals.Countsl)); PLOG.Write("elapsed time in seconds: " + s.GetElapsedTimeSecs()); PLOG.Write("elapsed time in minutes: " + s.GetElapsedTimeSecs() / 60); PLOG.Write("Total number of new orders per minute: " + (Globals.Countno / (s.GetElapsedTimeSecs() / 60))); } PLOG.Write("end TPC benchmark :" + DateTime.Now); PLOG.Read(); Globals.RunFlag = 1; } trd.Join(10000); //Console.ReadKey(); } }
/// <summary> /// Runs the specified number of simulations for each of the specified scenarios /// </summary> /// <param name="simulationInitialisationFilename">Filename of the file from which to read initialisation information</param> /// <param name="scenarios">Contains scenario information for this set of simulations</param> /// <param name="outputPath">The path to which outputs should be written</param> public void RunAllSimulations(string simulationInitialisationFilename, string definitionsFilename, string outputsFilename, ScenarioParameterInitialisation scenarios, string outputPath) { // Declare an instance of the class for initializing the Madingley model MadingleyModelInitialisation InitialiseMadingley = new MadingleyModelInitialisation(simulationInitialisationFilename, definitionsFilename, outputsFilename, outputPath); // Specify the output path in this instance InitialiseMadingley.OutputPath = outputPath; // List to hold the names of the scenarios to run List <string> ScenarioNames = new List <string>(); // String variable to hold the index suffix to apply to output files for a given simulation string OutputFilesSuffix; // Loop over scenario names and add the name of the scenario to the list of scenarion names foreach (var scenario in scenarios.scenarioParameters) { ScenarioNames.Add(scenario.Item1); } // Check whether there is only one simulation to run if (scenarios.scenarioNumber == 1 && scenarios.scenarioParameters.ElementAt(scenarios.scenarioNumber - 1).Item2 == 1) { // For a single simulation // Set-up the suffix for the output files OutputFilesSuffix = "_"; // Loop over the parameters for this scenario for (int i = 0; i < ScenarioNames.Count; i++) { // Add the parameter information to the suffix for this simulation OutputFilesSuffix += ScenarioNames[0] + "_"; } // Add a zero index to the end of the suffix OutputFilesSuffix += "0"; //Run the simulation RunSimulation(scenarios, 0, InitialiseMadingley, OutputFilesSuffix, 0); } else { if (InitialiseMadingley.RunSimulationsInParallel) { // Loop over specified scenarios iteratively for (int ScenarioIndex = 0; ScenarioIndex < scenarios.scenarioNumber; ScenarioIndex++) { //Create an array of new MadingleyModel instances for simulations under this scenario combination MadingleyModel[] MadingleyEcosystemModels = new MadingleyModel [scenarios.scenarioParameters.ElementAt(ScenarioIndex).Item2]; for (int simulation = 0; simulation < scenarios.scenarioParameters.ElementAt(ScenarioIndex).Item2; simulation++) { // Set up the suffix for the output files OutputFilesSuffix = "_"; // Add the scenario label to the suffix for the output files OutputFilesSuffix += ScenarioNames[ScenarioIndex] + "_"; // Add the simulation index number to the suffix OutputFilesSuffix += simulation.ToString(); // Initialize the instance of MadingleyModel MadingleyEcosystemModels[simulation] = new MadingleyModel(InitialiseMadingley, scenarios, ScenarioIndex, OutputFilesSuffix, InitialiseMadingley.GlobalModelTimeStepUnit, simulation); } // Loop over the specified number of simulations for each scenario //for (int simulation = 0; simulation< scenarios.scenarioSimulationsNumber[ScenarioIndex]; simulation++) Parallel.For(0, scenarios.scenarioParameters.ElementAt(ScenarioIndex).Item2, simulation => { // Declare and start a timer StopWatch s = new StopWatch(); s.Start(); // Run the simulation MadingleyEcosystemModels[simulation].RunMadingley(InitialiseMadingley); // Stop the timer and write out the time taken to run this simulation s.Stop(); Console.WriteLine("Model run finished"); Console.WriteLine("Total elapsed time was {0} seconds", s.GetElapsedTimeSecs()); }); } } else { //Run simulations sequentially // Loop over specified scenarios for (int ScenarioIndex = 0; ScenarioIndex < scenarios.scenarioNumber; ScenarioIndex++) { // Loop over the specified number of simulations for each scenario for (int simulation = 0; simulation < scenarios.scenarioParameters.ElementAt(ScenarioIndex).Item2; simulation++) { // Set up the suffix for the output files OutputFilesSuffix = "_"; // Add the scenario label to the suffix for the output files OutputFilesSuffix += ScenarioNames[ScenarioIndex] + "_"; // Add the simulation index number to the suffix OutputFilesSuffix += simulation.ToString(); // Run the current simulation RunSimulation(scenarios, ScenarioIndex, InitialiseMadingley, OutputFilesSuffix, simulation); } } } } }
public void SaveTimestep(int currentTimestep) { UInt32 hh = this.CurrentTimeStep; MadingleyModelInitialisation initialisation = this.ModelInitialisation; // Temporary variables Boolean varExists; // For runs with specific locations and where track processes has been specified, write out mass flows data and reset the mass flow tracker // for the next time step if (SpecificLocations) { for (var cellIndex = 0; cellIndex < _CellList.Count; cellIndex++) { if (ProcessTrackers[cellIndex].TrackProcesses) { ProcessTrackers[cellIndex].EndTimeStepPredationTracking(CurrentTimeStep); ProcessTrackers[cellIndex].EndTimeStepHerbvioryTracking(CurrentTimeStep); } } } if (TrackGlobalProcesses.TrackProcesses) { for (uint ii = 0; ii < StockFunctionalGroupDefinitions.GetNumberOfFunctionalGroups(); ii++) { TrackGlobalProcesses.StoreNPPGrid(hh, ii); TrackGlobalProcesses.StoreHANPPGrid(hh, ii); } } #endif OutputTimer.Start(); // Write the global outputs for this time step GlobalOutputs.TimeStepOutputs(EcosystemModelGrid, CurrentTimeStep, CurrentMonth, TimeStepTimer, CohortFunctionalGroupDefinitions, StockFunctionalGroupDefinitions, _CellList, GlobalDiagnosticVariables, initialisation); OutputTimer.Stop(); Console.WriteLine("Global Outputs took: {0}", OutputTimer.GetElapsedTimeSecs()); OutputTimer.Start(); if (SpecificLocations) { // Loop over grid cells and write (a) time step outputs, and (b) trophic flow data (if process tracking is on) for (int i = 0; i < _CellList.Count; i++) { // Write out the grid cell outputs for this time step CellOutputs[i].TimeStepOutputs(EcosystemModelGrid, CohortFunctionalGroupDefinitions, StockFunctionalGroupDefinitions, _CellList, i, GlobalDiagnosticVariables, TimeStepTimer, NumTimeSteps, CurrentTimeStep, initialisation, CurrentMonth, EcosystemModelGrid.GetEnviroLayer("Realm", 0, _CellList[i][0], _CellList[i][1], out varExists) == 2.0); // Write out trophic flow data for this time step if (ProcessTrackers[i].TrackProcesses) ProcessTrackers[i].WriteTimeStepTrophicFlows(CurrentTimeStep, EcosystemModelGrid.NumLatCells, EcosystemModelGrid.NumLonCells, initialisation, EcosystemModelGrid.GetEnviroLayer("Realm", 0, _CellList[i][0], _CellList[i][1], out varExists) == 2.0); } } else { // Write out grid outputs for this time step GridOutputs.TimeStepOutputs(EcosystemModelGrid, CohortFunctionalGroupDefinitions, StockFunctionalGroupDefinitions, _CellList, CurrentTimeStep, initialisation); } OutputTimer.Stop(); Console.WriteLine("Cell/Grid Outputs took: {0}", OutputTimer.GetElapsedTimeSecs()); // Write the results of dispersal to the console Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Number of cohorts that dispersed this time step: {0}\n", Dispersals); Console.ForegroundColor = ConsoleColor.White; Dispersals = 0; if (OutputModelStateTimestep.Contains(hh)) { OutputTimer.Start(); Console.WriteLine("Outputting model state"); //Writing to text based output WriteModelState.OutputCurrentModelState(EcosystemModelGrid, _CellList, hh); WriteModelState.OutputCurrentModelState(EcosystemModelGrid, CohortFunctionalGroupDefinitions, _CellList, CurrentTimeStep, initialisation.MaxNumberOfCohorts, "ModelState"); OutputTimer.Stop(); // Write the results of dispersal to the console Console.ForegroundColor = ConsoleColor.Green; Console.WriteLine("Writing model state took: {0}", OutputTimer.GetElapsedTimeSecs()); Console.ForegroundColor = ConsoleColor.White; /*ReadModelState = new InputModelState( initialisation.OutputPath, "ModelState0");*/ } }
public static void Main(string[] args) { StopWatch s = new StopWatch(); do { Field x = new Field(9, 9, 10); s.Start(); bool stillPlaying = true; DisplayField(x); do { int[] coordinates = ResponseAction(); int rowPick = coordinates[0]; int colPick = coordinates[1]; if (coordinates[2] == 0) //player is not flagging a tile { if (x.Click(rowPick, colPick)) { for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { if (x[row, col].Mined == true) { x.Click(row, col); } } } DisplayField(x); Console.WriteLine("Game Over!"); stillPlaying = false; } else { if (x.AllUnminedRevealed) { s.Stop(); for (int row = 0; row < 9; row++) { for (int col = 0; col < 9; col++) { if (x[row, col].Mined == true) { x.Click(row, col); } } } DisplayField(x); Console.WriteLine("Congratulations! You win!"); Console.WriteLine("You found all the mines in " + Convert.ToInt32(s.GetElapsedTimeSecs()) + " seconds!"); stillPlaying = false; } else { stillPlaying = true; DisplayField(x); } } } else //player is flagging a tile { if (!(x[rowPick, colPick].Flagged)) { x.Flag(rowPick, colPick); } else { x.Unflag(rowPick, colPick); } DisplayField(x); stillPlaying = true; } } while (stillPlaying == true); Console.WriteLine("Thanks for playing!"); Console.Write("Play again? (Press any key to continue) "); Console.ReadKey(); } while (true); }