示例#1
0
        public static List <InputModelState> ConvertModelStates(
            Madingley.Common.ModelState modelState,
            Madingley.Common.Configuration c,
            Madingley.Common.Environment e)
        {
            var numLatCells = (UInt32)((e.TopLatitude - e.BottomLatitude) / e.CellSize);
            var numLonCells = (UInt32)((e.RightmostLongitude - e.LeftmostLongitude) / e.CellSize);

            // Set up a grid of grid cells
            var gridCellCohorts = new GridCellCohortHandler[numLatCells, numLonCells];
            var gridCellStocks  = new GridCellStockHandler[numLatCells, numLonCells];

            gridCellCohorts[0, 0] = new GridCellCohortHandler(c.CohortFunctionalGroupDefinitions.Data.Count());

            var cellList  = e.FocusCells.ToArray();
            var gridCells = modelState.GridCells.ToArray();

            for (var ii = 0; ii < cellList.Count(); ii++)
            {
                var gridCell = gridCells[ii];

                gridCellCohorts[cellList[ii].Item1, cellList[ii].Item2] = ConvertCohorts(gridCell.Cohorts);
                gridCellStocks[cellList[ii].Item1, cellList[ii].Item2]  = ConvertStocks(gridCell.Stocks);
            }

            var inputModelState = new InputModelState(gridCellCohorts, gridCellStocks);

            return(new List <InputModelState>()
            {
                inputModelState
            });
        }
        /// <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)
        {
            // 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
                EcosystemModelGrid = new ModelGrid(BottomLatitude, LeftmostLongitude, TopLatitude, RightmostLongitude,
                    CellSize, CellSize, _CellList, EnviroStack, CohortFunctionalGroupDefinitions, StockFunctionalGroupDefinitions,
                    GlobalDiagnosticVariables, initialisation.TrackProcesses, SpecificLocations, RunGridCellsInParallel,GlobalModelTimeStepUnit);
            }
            else
            {
                _CellList = new List<uint[]>();
                //Switched order so we create cell list first then initialise cells using list rather than grid.

                uint NumLatCells = (uint)((TopLatitude - BottomLatitude) / CellSize);
                uint NumLonCells = (uint)((RightmostLongitude - LeftmostLongitude) / CellSize);

                // Loop over all cells in the model
                for (uint ii = 0; ii < NumLatCells; ii += 1)
                {
                    for (uint jj = 0; jj < NumLonCells; jj += 1)
                    {
                        // Define a vector to hold the pair of latitude and longitude indices for this grid cell
                        uint[] cellIndices = new uint[2];

                        // Add the latitude and longitude indices to this vector
                        cellIndices[0] = ii;
                        cellIndices[1] = jj;

                        // Add the vector to the list of all active grid cells
                        _CellList.Add(cellIndices);

                    }
                }

                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
                EcosystemModelGrid = new ModelGrid(BottomLatitude, LeftmostLongitude, TopLatitude, RightmostLongitude,
                    CellSize, CellSize, _CellList, EnviroStack, CohortFunctionalGroupDefinitions, StockFunctionalGroupDefinitions,
                    GlobalDiagnosticVariables, initialisation.TrackProcesses, SpecificLocations, RunGridCellsInParallel, GlobalModelTimeStepUnit);

                List<int> cellsToRemove = new List<int>();
                if (initialisation.RunRealm == "terrestrial")
                {
                    for (int ii = 0; ii < _CellList.Count; ii += 1)
                    {
                        if ((EcosystemModelGrid.GetCellEnvironment(_CellList[ii][0], _CellList[ii][1])["Realm"][0] == 2.0) ||
                            (EcosystemModelGrid.GetCellEnvironment(_CellList[ii][0], _CellList[ii][1])["LandSeaMask"][0] == 0.0))
                        {
                            cellsToRemove.Add(ii);
                        }
                    }
                }
                else if (initialisation.RunRealm == "marine")
                {
                    for (int ii = 0; ii < _CellList.Count; ii += 1)
                    {
                        if (EcosystemModelGrid.GetCellEnvironment(_CellList[ii][0], _CellList[ii][1])["Realm"][0] == 1.0)
                        {
                            cellsToRemove.Add(ii);
                        }
                    }
                }

                for (int ii = (cellsToRemove.Count - 1); ii >= 0; ii--)
                {
                    _CellList.RemoveAt(cellsToRemove[ii]);
                }

                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;

            }

            if (initialisation.InputState)
            {
                InputModelState = new InputModelState(initialisation.ModelStatePath[simulation],
                    initialisation.ModelStateFilename[simulation],EcosystemModelGrid, _CellList);
            }

            // When the last simulation for the current scenario
            // if ((scenarioParameters.scenarioSimulationsNumber.Count == 1) && (scenarioIndex == scenarioParameters.scenarioSimulationsNumber[scenarioIndex] - 1)) EnviroStack.Clear();
            // Seed stocks and cohorts in the grid cells
            // If input state from output from a previous simulation
            if (initialisation.InputState)
            {
                // Seed grid cell cohort and stocks
                EcosystemModelGrid.SeedGridCellStocksAndCohorts(_CellList, InputModelState, CohortFunctionalGroupDefinitions, StockFunctionalGroupDefinitions);

                //remove cohorts that do not contain any biomass
                foreach (uint[] CellPair in _CellList)
                {

                    GridCellCohortHandler workingGridCellCohorts = EcosystemModelGrid.GetGridCellCohorts(CellPair[0], CellPair[1]);

                    for (int kk = 0; kk < CohortFunctionalGroupDefinitions.GetNumberOfFunctionalGroups(); kk++)
                    {
                        // Loop through each cohort in the functional group
                        for (int ll = (workingGridCellCohorts[kk].Count - 1); ll >= 0; ll--)
                        {
                            // If cohort abundance is less than the extinction threshold then add to the list for extinction
                            if (workingGridCellCohorts[kk][ll].CohortAbundance.CompareTo(0) <= 0 || workingGridCellCohorts[kk][ll].IndividualBodyMass.CompareTo(0.0) == 0)
                            {
                                // Remove the extinct cohort from the list of cohorts
                                workingGridCellCohorts[kk].RemoveAt(ll);
                            }
                        }

                    }
                }

            }
            else
            {
                EcosystemModelGrid.SeedGridCellStocksAndCohorts(_CellList, CohortFunctionalGroupDefinitions, StockFunctionalGroupDefinitions,
                    GlobalDiagnosticVariables, ref NextCohortID, InitialisationFileStrings["OutputDetail"] == "high", DrawRandomly,
                    initialisation.DispersalOnly, InitialisationFileStrings["DispersalOnlyType"], RunGridCellsInParallel);
            }

            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;
        }
        /// <summary>
        /// Seed the stocks and cohorts from output from a previous simulation
        /// </summary>
        /// <param name="cellIndices">A list of the active cells in the model grid</param>
        /// <param name="cohortFunctionalGroupDefinitions">The functional group definitions for cohorts in the model</param>
        /// <param name="stockFunctionalGroupDefinitions">The functional group definitions for stocks in the model</param>
        /// <param name="globalDiagnostics">A list of global diagnostic variables</param>
        /// <param name="nextCohortID">The ID number to be assigned to the next produced cohort</param>
        /// <param name="tracking">Whether process-tracking is enabled</param>
        /// <param name="DrawRandomly">Whether the model is set to use a random draw</param>
        /// <param name="dispersalOnly">Whether to run dispersal only (i.e. to turn off all other ecological processes</param>
        /// <param name="processTrackers">An instance of the ecological process tracker</param>
        public void SeedGridCellStocksAndCohorts(List<uint[]> cellIndices,
            InputModelState inputModelState,
            FunctionalGroupDefinitions cohortFunctionalGroupDefinitions,
            FunctionalGroupDefinitions stockFunctionalGroupDefinitions)
        {
            int ii = 1;
            Console.WriteLine("Seeding grid cell stocks and cohorts:");

            //Check to see if the correct number of functional groups exist in the definitions file and in the input state

            if (cohortFunctionalGroupDefinitions.GetNumberOfFunctionalGroups() != inputModelState.GridCellCohorts[
                cellIndices[0][0],cellIndices[0][1]].Count)
            {
                Console.WriteLine("Mismatch in the number of functional groups defined in CohortFunctionalGroupDefinitions.csv set-up file and the Model State being read in");
                Environment.Exit(0);
            }

            int[] TerrestrialStockFunctionalIndices = stockFunctionalGroupDefinitions.GetFunctionalGroupIndex("Realm", "Terrestrial", false);
            int[] MarineStockFunctionalIndices = stockFunctionalGroupDefinitions.GetFunctionalGroupIndex("Realm", "Marine", false);

            int[] TerrestrialCohortFunctionalIndices = cohortFunctionalGroupDefinitions.GetFunctionalGroupIndex("Realm", "Terrestrial", false);
            int[] MarineCohortFunctionalIndices = cohortFunctionalGroupDefinitions.GetFunctionalGroupIndex("Realm", "Marine", false);

            foreach (uint[] cellIndexPair in cellIndices)
            {

                for (int i = 0; i < inputModelState.GridCellCohorts[cellIndexPair[0], cellIndexPair[1]].Count; i++)
                {
                    InternalGrid[cellIndexPair[0], cellIndexPair[1]].GridCellCohorts[i] = new List<Cohort>();
                }
                //Check which cohorts should be initialised for each cell
                if (InternalGrid[cellIndexPair[0], cellIndexPair[1]].CellEnvironment["Realm"][0] == 1)
                {
                    //This is a terrestrial cell so only add the terrestrial stocks
                    foreach (int fg in TerrestrialCohortFunctionalIndices)
                    {
                        //Cohort[] tempGridCellCohorts = (Cohort[])inputModelState.GridCellCohorts[cellIndexPair[0], cellIndexPair[1]][fg].ToArray().Clone();
                        //Cohort[] tempGridCellCohorts = (Cohort[])Array.ConvertAll(inputModelState.GridCellCohorts[cellIndexPair[0], cellIndexPair[1]][fg].ToArray(),
                        //    element => (Cohort)element.Clone());
                        Cohort[] tempGridCellCohorts = inputModelState.GridCellCohorts[cellIndexPair[0], cellIndexPair[1]][fg].ToArray().Select(cohort => new Cohort(cohort)).ToArray();
                        InternalGrid[cellIndexPair[0], cellIndexPair[1]].GridCellCohorts[fg] = tempGridCellCohorts.ToList();
                    }
                }
                else
                {
                    // this is a marine cell so only add the marine stocks
                    foreach (int fg in MarineCohortFunctionalIndices)
                    {
                        //Cohort[] tempGridCellCohorts = (Cohort[])inputModelState.GridCellCohorts[cellIndexPair[0], cellIndexPair[1]][fg].ToArray().Clone();
                        //Cohort[] tempGridCellCohorts = (Cohort[])Array.ConvertAll(inputModelState.GridCellCohorts[cellIndexPair[0], cellIndexPair[1]][fg].ToArray(),
                        //     element => (Cohort)element.Clone());
                        Cohort[] tempGridCellCohorts = inputModelState.GridCellCohorts[cellIndexPair[0], cellIndexPair[1]][fg].ToArray().Select(cohort => new Cohort(cohort)).ToArray();
                        InternalGrid[cellIndexPair[0], cellIndexPair[1]].GridCellCohorts[fg] = tempGridCellCohorts.ToList();
                    }
                }

                for (int i = 0; i < inputModelState.GridCellStocks[cellIndexPair[0], cellIndexPair[1]].Count; i++)
                {
                    InternalGrid[cellIndexPair[0], cellIndexPair[1]].GridCellStocks[i] = new List<Stock>();
                }

                //Check which stocks should be initialised for each cell
                if (InternalGrid[cellIndexPair[0], cellIndexPair[1]].CellEnvironment["Realm"][0] == 1)
                {
                    //This is a terrestrial cell so only add the terrestrial stocks
                    foreach (int fg in TerrestrialStockFunctionalIndices)
                    {
                        //Stock[] tempGridCellStocks = (Stock[])inputModelState.GridCellStocks[cellIndexPair[0], cellIndexPair[1]][fg].ToArray().Clone();
                        //Stock[] tempGridCellStocks = (Stock[])Array.ConvertAll(inputModelState.GridCellStocks[cellIndexPair[0], cellIndexPair[1]][fg].ToArray(),
                        //     element => (Stock)element.Clone());
                        Stock[] tempGridCellStocks = inputModelState.GridCellStocks[cellIndexPair[0], cellIndexPair[1]][fg].ToArray().Select(stock => new Stock(stock)).ToArray();
                        InternalGrid[cellIndexPair[0], cellIndexPair[1]].GridCellStocks[fg] = tempGridCellStocks.ToList();
                    }
                }
                else
                {
                    // this is a marine cell so only add the marine stocks
                    foreach (int fg in MarineStockFunctionalIndices)
                    {
                        //Stock[] tempGridCellStocks = (Stock[])inputModelState.GridCellStocks[cellIndexPair[0], cellIndexPair[1]][fg].ToArray().Clone();
                        //Stock[] tempGridCellStocks = (Stock[])Array.ConvertAll(inputModelState.GridCellStocks[cellIndexPair[0], cellIndexPair[1]][fg].ToArray(),
                        //     element => (Stock)element.Clone());
                        Stock[] tempGridCellStocks = inputModelState.GridCellStocks[cellIndexPair[0], cellIndexPair[1]][fg].ToArray().Select(stock => new Stock(stock)).ToArray();
                        InternalGrid[cellIndexPair[0], cellIndexPair[1]].GridCellStocks[fg] = tempGridCellStocks.ToList();
                    }
                }

                Console.Write("\rGrid Cell: {0} of {1}", ii++, cellIndices.Count);

            }

            Console.WriteLine("");
            Console.WriteLine("");
        }
        public static List<InputModelState> ConvertModelStates(
            Madingley.Common.ModelState modelState,
            Madingley.Common.Configuration c,
            Madingley.Common.Environment e)
        {
            var numLatCells = (UInt32)((e.TopLatitude - e.BottomLatitude) / e.CellSize);
            var numLonCells = (UInt32)((e.RightmostLongitude - e.LeftmostLongitude) / e.CellSize);

            // Set up a grid of grid cells
            var gridCellCohorts = new GridCellCohortHandler[numLatCells, numLonCells];
            var gridCellStocks = new GridCellStockHandler[numLatCells, numLonCells];

            gridCellCohorts[0, 0] = new GridCellCohortHandler(c.CohortFunctionalGroupDefinitions.Data.Count());

            var cellList = e.FocusCells.ToArray();
            var gridCells = modelState.GridCells.ToArray();

            for (var ii = 0; ii < cellList.Count(); ii++)
            {
                var gridCell = gridCells[ii];

                gridCellCohorts[cellList[ii].Item1, cellList[ii].Item2] = ConvertCohorts(gridCell.Cohorts);
                gridCellStocks[cellList[ii].Item1, cellList[ii].Item2] = ConvertStocks(gridCell.Stocks);
            }

            var inputModelState = new InputModelState(gridCellCohorts, gridCellStocks);

            return new List<InputModelState>() { inputModelState };
        }