public MadingleyModelOutput(
            string outputFilesSuffix,
            Madingley.Common.Environment environment,
            Madingley.Common.Configuration configuration,
            MadingleyModelInitialisation outputSettings,
            Madingley.Common.ModelState modelState)
        {
            var modelInitialisation = Converters.ConvertInitialisation(
                outputSettings,
                configuration,
                environment);

            this.ProcessTracker = new Madingley.Common.IProcessTracker[environment.FocusCells.Count()][];
            for (var cellIndex = 0; cellIndex < environment.FocusCells.Count(); cellIndex++)
            {
                var processTracker = new GEMProcessTracker(cellIndex, this);

                this.ProcessTracker[cellIndex] = new Madingley.Common.IProcessTracker[] { processTracker };
            }

            var globalProcessTracker = new GEMGlobalProcessTracker(this);
            this.GlobalProcessTracker = new Madingley.Common.IGlobalProcessTracker[] { globalProcessTracker };

            var crossCellProcessTracker = new GEMCrossCellProcessTracker(this);
            this.CrossCellProcessTracker = new Madingley.Common.ICrossCellProcessTracker[] { crossCellProcessTracker };

            this.model = new MadingleyModel(
                modelInitialisation,
                outputFilesSuffix,
                configuration.Simulation,
                modelState);
        }
        public static void Serialize(Madingley.Common.Environment environment, TextWriter sw)
        {
            Action<Newtonsoft.Json.JsonWriter, Tuple<int, int>> JsonAddPropertyFocusCell = (jsonWriter, value) =>
            {
                jsonWriter.WriteStartArray();
                Common.Writer.WriteInt(jsonWriter, value.Item1);
                Common.Writer.WriteInt(jsonWriter, value.Item2);
                jsonWriter.WriteEndArray();
            };

            Action<Newtonsoft.Json.JsonWriter, IEnumerable<KeyValuePair<string, double[]>>> JsonAddPropertyCellEnvironment = (jsonWriter, value) =>
            {
                Common.Writer.WriteKeyValuePairs(jsonWriter, value, (JsonWriter, key, val) => Common.Writer.PropertyInlineArray(JsonWriter, key, val, Common.Writer.WriteDouble));
            };

            using (var writer = new Newtonsoft.Json.JsonTextWriter(sw))
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;

                writer.WriteStartObject();
                Common.Writer.PropertyDouble(writer, "CellSize", environment.CellSize);
                Common.Writer.PropertyDouble(writer, "BottomLatitude", environment.BottomLatitude);
                Common.Writer.PropertyDouble(writer, "TopLatitude", environment.TopLatitude);
                Common.Writer.PropertyDouble(writer, "LeftmostLongitude", environment.LeftmostLongitude);
                Common.Writer.PropertyDouble(writer, "RightmostLongitude", environment.RightmostLongitude);
                Common.Writer.PropertyKeyValuePairs(writer, "Units", environment.Units, Common.Writer.PropertyString);
                Common.Writer.PropertyBoolean(writer, "SpecificLocations", environment.SpecificLocations);
                Common.Writer.PropertyInlineArray(writer, "FocusCells", environment.FocusCells, JsonAddPropertyFocusCell);
                Common.Writer.PropertyArray(writer, "CellEnvironment", environment.CellEnvironment, JsonAddPropertyCellEnvironment);
                Common.Writer.PropertyInlineArray(writer, "FileNames", environment.FileNames, Common.Writer.WriteString);
                writer.WriteEndObject();
            }
        }
Exemplo n.º 3
0
 public static Stock ConvertStock(Madingley.Common.Stock stock, byte functionalGroupIndex)
 {
     return new Stock(
         functionalGroupIndex,
         stock.IndividualBodyMass,
         stock.TotalBiomass);
 }
        public static void Save(Madingley.Common.FunctionalGroupDefinitions c, string filename)
        {
            var definitionHeaders = c.Definitions.Select(k => String.Format("DEFINITION_{0}", k));

            var propertyHeaders = c.Properties.Select(k => String.Format("PROPERTY_{0}", k));

            var cohortRows =
                c.Data.Select(data =>
                {
                    var definitionsElements =
                        c.Definitions.Select(definition =>
                                data.Definitions.ContainsKey(definition) ? data.Definitions[definition] : "");

                    var propertyElements =
                        c.Properties.Select(property =>
                                data.Properties.ContainsKey(property) ? data.Properties[property].ToString("G17") : "");

                    var allElements = definitionsElements.Concat(propertyElements);

                    return System.String.Join(",", allElements);
                });

            var allHeaders = definitionHeaders.Concat(propertyHeaders);
            var header = System.String.Join(",", allHeaders);
            using (var writer = new StreamWriter(filename))
            {
                writer.WriteLine(header);

                cohortRows.ToList().ForEach(line => writer.WriteLine(line));
            }
        }
 public static void Save(Madingley.Common.EcologicalParameters ecologicalParameters, string path)
 {
     using (var writer = new StreamWriter(path))
     {
         writer.WriteLine("Parameter,Value");
         ecologicalParameters.Parameters.ToList().ForEach(kv => writer.WriteLine(String.Format("{0},{1}", kv.Key, kv.Value)));
     }
 }
Exemplo n.º 6
0
        public static void Serialize(Madingley.Common.ModelState modelState, TextWriter sw)
        {
            Action<Newtonsoft.Json.JsonWriter, Madingley.Common.Cohort> JsonAddPropertyCohort = (jsonWriter, value) =>
            {
                jsonWriter.WriteStartObject();
                Common.Writer.PropertyInt(jsonWriter, "FunctionalGroupIndex", value.FunctionalGroupIndex);
                Common.Writer.PropertyInt(jsonWriter, "BirthTimeStep", value.BirthTimeStep);
                Common.Writer.PropertyInt(jsonWriter, "MaturityTimeStep", value.MaturityTimeStep);
                Common.Writer.PropertyInlineArray(jsonWriter, "IDs", value.IDs, Common.Writer.WriteInt);
                Common.Writer.PropertyDouble(jsonWriter, "JuvenileMass", value.JuvenileMass);
                Common.Writer.PropertyDouble(jsonWriter, "AdultMass", value.AdultMass);
                Common.Writer.PropertyDouble(jsonWriter, "IndividualBodyMass", value.IndividualBodyMass);
                Common.Writer.PropertyDouble(jsonWriter, "IndividualReproductivePotentialMass", value.IndividualReproductivePotentialMass);
                Common.Writer.PropertyDouble(jsonWriter, "MaximumAchievedBodyMass", value.MaximumAchievedBodyMass);
                Common.Writer.PropertyDouble(jsonWriter, "Abundance", value.Abundance);
                Common.Writer.PropertyBoolean(jsonWriter, "Merged", value.Merged);
                Common.Writer.PropertyDouble(jsonWriter, "ProportionTimeActive", value.ProportionTimeActive);
                Common.Writer.PropertyDouble(jsonWriter, "TrophicIndex", value.TrophicIndex);
                Common.Writer.PropertyDouble(jsonWriter, "LogOptimalPreyBodySizeRatio", value.LogOptimalPreyBodySizeRatio);
                jsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, Madingley.Common.Stock> JsonAddPropertyStock = (jsonWriter, value) =>
            {
                jsonWriter.WriteStartObject();
                Common.Writer.PropertyInt(jsonWriter, "FunctionalGroupIndex", value.FunctionalGroupIndex);
                Common.Writer.PropertyDouble(jsonWriter, "IndividualBodyMass", value.IndividualBodyMass);
                Common.Writer.PropertyDouble(jsonWriter, "TotalBiomass", value.TotalBiomass);
                jsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, Madingley.Common.GridCell> JsonAddPropertyGridCell = (jsonWriter, gridCell) =>
            {
                jsonWriter.WriteStartObject();
                Common.Writer.PropertyDouble(jsonWriter, "Latitude", gridCell.Latitude);
                Common.Writer.PropertyDouble(jsonWriter, "Longitude", gridCell.Longitude);
                Common.Writer.PropertyArray(jsonWriter, "Cohorts", gridCell.Cohorts, (JsonWriter, value) => Common.Writer.WriteArray(JsonWriter, value, JsonAddPropertyCohort));
                Common.Writer.PropertyArray(jsonWriter, "Stocks", gridCell.Stocks, (JsonWriter, value) => Common.Writer.WriteArray(JsonWriter, value, JsonAddPropertyStock));
                Common.Writer.PropertyKeyValuePairs(jsonWriter, "Environment", gridCell.Environment, (JsonWriter, key, val) => Common.Writer.PropertyInlineArray(JsonWriter, key, val, Common.Writer.WriteDouble));
                jsonWriter.WriteEndObject();
            };

            using (var writer = new Newtonsoft.Json.JsonTextWriter(sw))
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;

                writer.WriteStartObject();
                Common.Writer.PropertyInt(writer, "TimestepsComplete", modelState.TimestepsComplete);
                Common.Writer.PropertyKeyValuePairs(writer, "GlobalDiagnosticVariables", modelState.GlobalDiagnosticVariables, Common.Writer.PropertyDouble);
                Common.Writer.PropertyArray(writer, "GridCells", modelState.GridCells, JsonAddPropertyGridCell);
                Common.Writer.PropertyLong(writer, "NextCohortID", modelState.NextCohortID);
                writer.WriteEndObject();
            }
        }
Exemplo n.º 7
0
 public static Cohort ConvertCohort(Madingley.Common.Cohort cohort, byte functionalGroupIndex)
 {
     return new Cohort(
         (uint)cohort.BirthTimeStep,
         (uint)cohort.MaturityTimeStep,
          cohort.IDs.Select(cs => (uint)cs).ToList(),
         cohort.JuvenileMass,
         cohort.AdultMass,
         cohort.IndividualBodyMass,
         cohort.IndividualReproductivePotentialMass,
         cohort.MaximumAchievedBodyMass,
         cohort.Abundance,
         functionalGroupIndex,
         cohort.Merged,
         cohort.ProportionTimeActive,
         cohort.TrophicIndex,
         cohort.LogOptimalPreyBodySizeRatio);
 }
        /// <summary>
        /// Run ecological processes that operate on stocks within a single grid cell
        /// </summary>
        ///<param name="gridCellStocks">The stocks in the current grid cell</param>
        ///<param name="actingStock">The acting stock</param>
        ///<param name="cellEnvironment">The stocks in the current grid cell</param>
        ///<param name="environmentalDataUnits">List of units associated with the environmental variables</param>
        ///<param name="humanNPPScenario">The human appropriation of NPP scenario to apply</param>
        ///<param name="madingleyStockDefinitions">The functional group definitions for stocks in the model</param>
        ///<param name="currentTimeStep">The current model time step</param>
        ///<param name="burninSteps">The number of time steps to spin the model up for before applying human impacts</param>
        ///<param name="impactSteps">The number of time steps to apply human impacts for</param>
        ///<param name="globalModelTimeStepUnit">The time step unit used in the model</param>
        ///<param name="trackProcesses">Whether to track properties of ecological processes</param>
        ///<param name="tracker">An instance of the ecological process tracker</param>
        ///<param name="globalTracker">An instance of the global process tracker</param>
        ///<param name="currentMonth">The current model month</param>
        ///<param name="outputDetail">The level of detail to use in outputs</param>
        ///<param name="specificLocations">Whether to run the model for specific locations</param>
        ///<param name="impactCell">Whether this cell should have human impacts applied</param>
        public void RunWithinCellEcology(GridCellStockHandler gridCellStocks, int[] actingStock, SortedList<string, double[]> cellEnvironment,
            SortedList<string, string> environmentalDataUnits, Madingley.Common.ScenarioParameter humanNPPScenario,
            FunctionalGroupDefinitions madingleyStockDefinitions,
            uint currentTimeStep, uint burninSteps, uint impactSteps, uint recoverySteps, uint instantStep, uint numInstantSteps, string globalModelTimeStepUnit, Boolean trackProcesses,
            ProcessTracker tracker,
            GlobalProcessTracker globalTracker, uint currentMonth,
            string outputDetail, bool specificLocations, Boolean impactCell)
        {
            if (madingleyStockDefinitions.GetTraitNames("Realm", actingStock[0]) == "marine")
            {
                // Run the autotroph processor
                MarineNPPtoAutotrophStock.ConvertNPPToAutotroph(cellEnvironment, gridCellStocks, actingStock, environmentalDataUnits["LandNPP"],
                    environmentalDataUnits["OceanNPP"], currentTimeStep, globalModelTimeStepUnit, tracker, globalTracker, outputDetail, specificLocations, currentMonth);
            }
            else if (madingleyStockDefinitions.GetTraitNames("Realm", actingStock[0]) == "terrestrial")
            {

                // Run the dynamic plant model to update the leaf stock for this time step
                double WetMatterNPP = DynamicPlantModel.UpdateLeafStock(cellEnvironment, gridCellStocks, actingStock, currentTimeStep, madingleyStockDefinitions.
                    GetTraitNames("leaf strategy", actingStock[0]).Equals("deciduous"), globalModelTimeStepUnit, tracker, globalTracker, currentMonth,
                    outputDetail, specificLocations);
                /// <summary>

                double fhanpp = HANPP.RemoveHumanAppropriatedMatter(WetMatterNPP, cellEnvironment, humanNPPScenario, gridCellStocks, actingStock,
                    currentTimeStep, burninSteps, impactSteps, recoverySteps, instantStep, numInstantSteps, impactCell, globalModelTimeStepUnit);

                // Apply human appropriation of NPP
                gridCellStocks[actingStock].TotalBiomass += WetMatterNPP * (1.0 - fhanpp);

                if (globalTracker.TrackProcesses)
                {
                    globalTracker.RecordHANPP((uint)cellEnvironment["LatIndex"][0], (uint)cellEnvironment["LonIndex"][0], (uint)actingStock[0],
                        fhanpp);
                }

                if (gridCellStocks[actingStock].TotalBiomass < 0.0) gridCellStocks[actingStock].TotalBiomass = 0.0;

            }
            else
            {
                Debug.Fail("Stock must be classified as belonging to either the marine or terrestrial realm");
            }
        }
Exemplo n.º 9
0
 public Data(
     bool terrestrial,
     int rowCount,
     string pathToModelSetup,
     Madingley.Test.Common.LookupColumnNames expectedGlobalVariableNames,
     Madingley.Test.Common.LookupColumnTest expectedGlobalLookupData,
     Madingley.Test.Common.LookupColumnNames expectedCellVariableNames,
     Madingley.Test.Common.LookupColumnTest[] expectedCellLookupDatas,
     Madingley.Test.Common.LookupColumnNames expectedGridVariableNames,
     Madingley.Test.Common.LookupColumnTest expectedGridLookupData,
     Madingley.Test.Common.LookupColumn3dTest expectedGridLookupData3d,
     Madingley.Test.Common.LookupColumnTest expectedGridLookupData3dFlattened,
     Madingley.Test.Common.LookupColumnNames expectedDispersalVariableNames,
     Madingley.Test.Common.LookupColumnTest expectedDispersalLookupData,
     Madingley.Test.Common.LookupColumnNames expectedNPPVariableNames,
     Madingley.Test.Common.LookupColumnTest expectedNPPLookupData,
     Madingley.Test.Common.LookupColumn3dTest expectedNPPLookupData3d,
     Madingley.Test.Common.LookupColumnTest expectedNPPLookupData3dFlattened)
 {
     this.Terrestrial = terrestrial;
     this.RowCount = rowCount;
     this.PathToModelSetup = pathToModelSetup;
     this.ExpectedGlobalVariableNames = expectedGlobalVariableNames;
     this.ExpectedGlobalLookupColumnTest = expectedGlobalLookupData;
     this.ExpectedCellVariableNames = expectedCellVariableNames;
     this.ExpectedCellLookupColumnTests = expectedCellLookupDatas;
     this.ExpectedGridVariableNames = expectedGridVariableNames;
     this.ExpectedGridLookupColumnTest = expectedGridLookupData;
     this.ExpectedGridLookupColumn3dTest = expectedGridLookupData3d;
     this.ExpectedGridLookupColumn3dTestFlattened = expectedGridLookupData3dFlattened;
     this.ExpectedDispersalVariableNames = expectedDispersalVariableNames;
     this.ExpectedDispersalLookupColumnTest = expectedDispersalLookupData;
     this.ExpectedNPPVariableNames = expectedNPPVariableNames;
     this.ExpectedNPPLookupColumnTest = expectedNPPLookupData;
     this.ExpectedNPPLookupColumn3dTest = expectedNPPLookupData3d;
     this.ExpectedNPPLookupColumn3dTestFlattened = expectedNPPLookupData3dFlattened;
 }
 public void EndTimestep(
     int currentTimestep,
     Madingley.Common.ModelState modelState)
 {
     this.model.EndTimestep(currentTimestep, modelState);
 }
        /// <summary>
        /// Reads the environmental layers listed in the specified file containing a list of environmental layers
        /// </summary>
        /// <param name="e">Environment object.</param>
        /// <param name="inputEnvironmentalLayerFileName">The name of the file containing the list of environmental layers</param>
        /// <param name="environmentDataRoot">The path to folder which contains the data inputs</param>
        public static SortedList<string, EnviroData> ReadEnvironmentalLayers(
            Madingley.Common.Environment e,
            string inputEnvironmentalLayerFileName,
            string environmentDataRoot,
            bool readData)
        {
            Console.WriteLine("Reading in environmental data:");

            // Declare lists to hold the information required to read the environmental layers
            List<string> Sources = new List<string>();
            List<string> Folders = new List<string>();
            List<string> Filenames = new List<string>();
            List<string> DatasetNames = new List<string>();
            List<string> FileTypes = new List<string>();
            List<string> LayerName = new List<string>();
            List<string> StaticLayer = new List<string>();
            List<string> Extensions = new List<string>();
            List<string> Resolutions = new List<string>();
            List<string> MethodUnits = new List<string>();

            // Variable to store the file name of the environmental data files
            string TempFilename;

            // Construct the full URI for the file  containing the list of environmental layers
            string FileString = "msds:csv?file=" + inputEnvironmentalLayerFileName + "&openMode=readOnly";

            StreamReader r_env = new StreamReader(inputEnvironmentalLayerFileName);

            var EnviroStack = new SortedList<string, EnviroData>();

            string l;
            char[] comma = ",".ToCharArray();

            string[] f;
            int col;
            // Read in the data
            l = r_env.ReadLine();
            while (!r_env.EndOfStream)
            {
                l = r_env.ReadLine();
                // Split fields by commas
                f = l.Split(comma);
                //zero the column index
                col = 0;
                // Lists of the different fields
                Sources.Add(f[col++]);
                Folders.Add(f[col++]);
                Filenames.Add(f[col++]);
                Extensions.Add(f[col++]);
                DatasetNames.Add(f[col++]);
                FileTypes.Add(f[col++]);
                LayerName.Add(f[col++]);
                StaticLayer.Add(f[col++]);
                Resolutions.Add(f[col++]);
                MethodUnits.Add(f[col++]);
            }

            for (int ii = 0; ii < MethodUnits.Count; ii++)
            {
                e.Units.Add(LayerName[ii], MethodUnits[ii]);
            }

            // Check that there are the same number of values for all parameters
            Debug.Assert(Folders.Count() == Filenames.Count() && Filenames.Count() == DatasetNames.Count() && DatasetNames.Count() == FileTypes.Count() && FileTypes.Count() == LayerName.Count(),
                "Error in Environmental Data Layer import lists - unequal number of filenames, dataset names, filetypes and datalayer names");

            // Loop over parameter values
            for (int ii = 0; ii < Filenames.Count(); ii++)
            {
                Console.Write("\r{0} Variable {1} of {2}: {3}\n", Sources[ii], ii + 1, Filenames.Count, Filenames[ii]);
                // If the layers are not static, then suffix the file name with '1' - not currently implemented
                if (StaticLayer[ii].ToLower().Equals("n"))
                {
                    Debug.Fail("This option is currently not supported");
                    Filenames[ii] = Filenames[ii] + "1";
                }
                if (Sources[ii].ToLower().Equals("local"))
                {
                    // For layers where the file format is ESRI ASCII grid, the dataset name is the same as the file name
                    if (FileTypes[ii].ToLower().Equals("esriasciigrid"))
                    {
                        DatasetNames[ii] = Filenames[ii];
                    }
                    // Generate the appropriate file name for the environmental data layer
#if true
                    TempFilename = System.IO.Path.Combine(environmentDataRoot, Folders[ii], Filenames[ii]);

                    Filenames[ii] = System.IO.Path.ChangeExtension(TempFilename, Extensions[ii]);
#else
                    if (Folders[ii].ToLower().Equals("input"))
                    {
                        TempFilename = "input/Data/" + Filenames[ii];
                    }
                    else
                    {
                        TempFilename = Folders[ii] + "/" + Filenames[ii];
                    }
                    Filenames[ii] = TempFilename + Extensions[ii];
#endif
                    // Read in and store the environmental data
                    if (File.Exists(Filenames[ii]))
                    {
                        if (readData)
                        {
                            EnviroStack.Add(LayerName[ii], new EnviroData(Filenames[ii], DatasetNames[ii], FileTypes[ii], Resolutions[ii], MethodUnits[ii]));
                        }
                        else
                        {
                            EnviroStack.Add(LayerName[ii], null);
                        }
                    }
                    else
                    {
                        throw new Exception(string.Format("ERROR: Cannot find data file: {0} ({1}), have you added the data files from https://github.com/Madingley/Madingley/releases?", Filenames[ii], System.IO.Path.GetFullPath(Filenames[ii])));
                    }
                }
                else if (Sources[ii].ToLower().Equals("fetchclimate"))
                {

                    if (!EnviroStack.ContainsKey(LayerName[ii]))
                    {
                        if (readData)
                        {
                            if (e.SpecificLocations)
                            {
                                EnviroStack.Add(LayerName[ii], new EnviroData(DatasetNames[ii], Resolutions[ii], e.BottomLatitude, e.LeftmostLongitude, e.TopLatitude, e.RightmostLongitude, e.CellSize, e.FocusCells, EnvironmentalDataSource.ANY));
                            }
                            else
                            {
                                EnviroStack.Add(LayerName[ii], new EnviroData(DatasetNames[ii], Resolutions[ii], e.BottomLatitude, e.LeftmostLongitude, e.TopLatitude, e.RightmostLongitude, e.CellSize, EnvironmentalDataSource.ANY));
                            }
                        }
                        else
                        {
                            EnviroStack.Add(LayerName[ii], null);
                        }
                    }
                }
            }

            return EnviroStack;
        }
Exemplo n.º 12
0
        public static MadingleyModelInitialisation ConvertInitialisation(
            Madingley.Common.ModelState m,
            Madingley.Common.Configuration d,
            Madingley.Common.Environment e)
        {
            var i = new MadingleyModelInitialisation("", "", "", "");

            i.GlobalModelTimeStepUnit = d.GlobalModelTimeStepUnit;
            i.NumTimeSteps = (uint)d.NumTimeSteps;
            i.BurninTimeSteps = (uint)d.BurninTimeSteps;
            i.ImpactTimeSteps = (uint)d.ImpactTimeSteps;
            i.RecoveryTimeSteps = (uint)d.RecoveryTimeSteps;
            i.CellSize = e.CellSize;
            i.BottomLatitude = (float)e.BottomLatitude;
            i.TopLatitude = (float)e.TopLatitude;
            i.LeftmostLongitude = (float)e.LeftmostLongitude;
            i.RightmostLongitude = (float)e.RightmostLongitude;
            i.RunCellsInParallel = d.RunCellsInParallel;
            i.RunSimulationsInParallel = d.RunSimulationsInParallel;
            i.RunRealm = d.RunRealm;
            i.DrawRandomly = d.DrawRandomly;
            i.ExtinctionThreshold = d.ExtinctionThreshold;
            i.MaxNumberOfCohorts = d.MaxNumberOfCohorts;
            i.DispersalOnly = d.DispersalOnly;
            i.PlanktonDispersalThreshold = d.PlanktonDispersalThreshold;
            i.SpecificLocations = e.SpecificLocations;
            i.InitialisationFileStrings = new SortedList<string, string>();
            i.InitialisationFileStrings["OutputDetail"] = "high";
            i.InitialisationFileStrings["DispersalOnlyType"] = d.DispersalOnlyType;
            i.CohortFunctionalGroupDefinitions = ConvertFunctionalGroupDefinitions(d.CohortFunctionalGroupDefinitions);
            i.StockFunctionalGroupDefinitions = ConvertFunctionalGroupDefinitions(d.StockFunctionalGroupDefinitions);
            if (m != null)
            {
                i.EnviroStack = ConvertEnvironment(m.GridCells);
            }
            else
            {
                i.EnviroStack = ConvertEnvironment(e.CellEnvironment);
            }
            i.CellList = e.FocusCells.Select(a => new UInt32[] { (uint)a.Item1, (uint)a.Item2 }).ToList();
            i.TrackProcesses = true;
            i.TrackCrossCellProcesses = true;
            i.TrackGlobalProcesses = true;
            i.Units = new SortedList<string, string>(e.Units);
            i.ImpactCellIndices = d.ImpactCellIndices.Select(ii => (uint)ii).ToList();
            i.ImpactAll = d.ImpactAll;
            if (m != null)
            {
                i.ModelStates = ConvertModelStates(m, d, e);
                i.InputState = true;
                i.InputGlobalDiagnosticVariables = new SortedList<string, double>(m.GlobalDiagnosticVariables);
            }
            else
            {
                i.ModelStates = null;
                i.InputState = false;
            }

            return i;
        }
        public void ApplyTemperatureScenario(SortedList<string, double[]> cellEnvironment,
            Madingley.Common.ScenarioParameter temperatureScenario, uint currentTimestep, uint currentMonth, uint burninSteps,
            uint impactSteps, Boolean impactCell)
        {
            if (impactCell)
            {
                if (temperatureScenario.ParamString == "no")
                {
                }
                else if (temperatureScenario.ParamString == "constant")
                {
                    // Check to see whether this time step is at the transition between burn-in and impact
                    if ((currentTimestep >= (burninSteps + 1)) && (currentTimestep <= (burninSteps + 12)))
                    {
                        // Increment temperature
                        cellEnvironment["Temperature"][currentMonth] += temperatureScenario.ParamDouble1;
                    }
                    else
                    {
                    }
                }
                else if (temperatureScenario.ParamString == "temporary")
                {
                    // Check to see whether this time step is at the transition between burn-in and impact
                    // or at the transition between impact and post-impat
                    if ((currentTimestep >= (burninSteps + 1)) && (currentTimestep <= (burninSteps + 12)))
                    {
                        // Increment temperature
                        cellEnvironment["Temperature"][currentMonth] += temperatureScenario.ParamDouble1;
                    }
                    else if ((currentTimestep >= (burninSteps + impactSteps + 1)) && (currentTimestep <= (burninSteps + impactSteps + 12)))
                    {
                        // Revert temperature to original value
                        cellEnvironment["Temperature"][currentMonth] -= temperatureScenario.ParamDouble1;
                    }
                    else
                    {
                    }
                }
                else if (temperatureScenario.ParamString == "escalating")
                {

                    // If this is the first time step, add items to the cell environment to store the original cell temperature
                    if (currentTimestep == 0)
                    {
                        cellEnvironment.Add("Original Temperature", new double[12]);
                        for (int m = 0; m < 12; m++)
                        {
                            cellEnvironment["Original Temperature"][m] = cellEnvironment["Temperature"][m];
                        }
                    }
                    // If the spin-up period has been completed, then increment cell temperature
                    // according to the number of time-steps that have elapsed since the spin-up ended
                    if (currentTimestep > burninSteps)
                    {
                        cellEnvironment["Temperature"][currentMonth] = Math.Min((cellEnvironment["Original Temperature"][currentMonth] + 5.0),
                            cellEnvironment["Temperature"][currentMonth] + ((((currentTimestep - burninSteps) / 12) + 1) *
                            temperatureScenario.ParamDouble1));
                        // cellEnvironment["Temperature"][currentMonth] += gridCellStocks[actingStock].TotalBiomass *
                        //     (Math.Min(5.0, (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.Item2)));
                    }
                }
                else
                {
                    Debug.Fail("There is no method for the climate change (temperature) scenario specified");
                }

            }
        }
        public static void Serialize(Madingley.Common.Configuration configuration, TextWriter textWriter)
        {
            Action<Newtonsoft.Json.JsonWriter, Madingley.Common.FunctionalGroupDefinition> JsonAddPropertyFunctionalGroupDefinition = (JsonWriter, value) =>
            {
                JsonWriter.WriteStartObject();
                Common.Writer.PropertyKeyValuePairs(JsonWriter, "Definitions", value.Definitions, Common.Writer.PropertyString);
                Common.Writer.PropertyKeyValuePairs(JsonWriter, "Properties", value.Properties, Common.Writer.PropertyDouble);
                JsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, string, Madingley.Common.FunctionalGroupDefinitions> JsonAddPropertyFunctionalGroupDefinitions = (JsonWriter, name, value) =>
            {
                JsonWriter.WritePropertyName(name);
                JsonWriter.WriteStartObject();
                Common.Writer.PropertyArray(JsonWriter, "Data", value.Data, JsonAddPropertyFunctionalGroupDefinition);
                Common.Writer.PropertyInlineArray(JsonWriter, "Definitions", value.Definitions, Common.Writer.WriteString);
                Common.Writer.PropertyInlineArray(JsonWriter, "Properties", value.Properties, Common.Writer.WriteString);
                JsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, string, Madingley.Common.ScenarioParameter> JsonAddPropertyScenarioParameter = (JsonWriter, name, value) =>
            {
                JsonWriter.WritePropertyName(name);
                JsonWriter.WriteStartObject();
                Common.Writer.PropertyString(JsonWriter, "ParamString", value.ParamString);
                Common.Writer.PropertyDouble(JsonWriter, "ParamDouble1", value.ParamDouble1);
                Common.Writer.PropertyDouble(JsonWriter, "ParamDouble2", value.ParamDouble2);
                JsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, Madingley.Common.ScenarioParameters> JsonAddScenarioParameter = (JsonWriter, value) =>
            {
                JsonWriter.WriteStartObject();
                Common.Writer.PropertyString(JsonWriter, "Label", value.Label);
                Common.Writer.PropertyInt(JsonWriter, "SimulationNumber", value.SimulationNumber);
                Common.Writer.PropertyKeyValuePairs(JsonWriter, "Parameters", value.Parameters, JsonAddPropertyScenarioParameter);
                JsonWriter.WriteEndObject();
            };

            Action<Newtonsoft.Json.JsonWriter, string, Madingley.Common.EcologicalParameters> JsonAddEcologicalParameters = (JsonWriter, name, ecologicalParameters) =>
            {
                JsonWriter.WritePropertyName(name);
                JsonWriter.WriteStartObject();
                Common.Writer.PropertyKeyValuePairs(JsonWriter, "Parameters", ecologicalParameters.Parameters, Common.Writer.PropertyDouble);
                Common.Writer.PropertyInlineArray(JsonWriter, "TimeUnits", ecologicalParameters.TimeUnits, Common.Writer.WriteString);
                JsonWriter.WriteEndObject();
            };

            using (var writer = new Newtonsoft.Json.JsonTextWriter(textWriter))
            {
                writer.Formatting = Newtonsoft.Json.Formatting.Indented;

                writer.WriteStartObject();
                Common.Writer.PropertyString(writer, "GlobalModelTimeStepUnit", configuration.GlobalModelTimeStepUnit);
                Common.Writer.PropertyInt(writer, "NumTimeSteps", configuration.NumTimeSteps);
                Common.Writer.PropertyInt(writer, "BurninTimeSteps", configuration.BurninTimeSteps);
                Common.Writer.PropertyInt(writer, "ImpactTimeSteps", configuration.ImpactTimeSteps);
                Common.Writer.PropertyInt(writer, "RecoveryTimeSteps", configuration.RecoveryTimeSteps);
                Common.Writer.PropertyBoolean(writer, "RunCellsInParallel", configuration.RunCellsInParallel);
                Common.Writer.PropertyBoolean(writer, "RunSimulationsInParallel", configuration.RunSimulationsInParallel);
                Common.Writer.PropertyString(writer, "RunRealm", configuration.RunRealm);
                Common.Writer.PropertyBoolean(writer, "DrawRandomly", configuration.DrawRandomly);
                Common.Writer.PropertyDouble(writer, "ExtinctionThreshold", configuration.ExtinctionThreshold);
                Common.Writer.PropertyInt(writer, "MaxNumberOfCohorts", configuration.MaxNumberOfCohorts);
                Common.Writer.PropertyBoolean(writer, "DispersalOnly", configuration.DispersalOnly);
                Common.Writer.PropertyString(writer, "DispersalOnlyType", configuration.DispersalOnlyType);
                Common.Writer.PropertyDouble(writer, "PlanktonDispersalThreshold", configuration.PlanktonDispersalThreshold);
                JsonAddPropertyFunctionalGroupDefinitions(writer, "CohortFunctionalGroupDefinitions", configuration.CohortFunctionalGroupDefinitions);
                JsonAddPropertyFunctionalGroupDefinitions(writer, "StockFunctionalGroupDefinitions", configuration.StockFunctionalGroupDefinitions);
                Common.Writer.PropertyInlineArray(writer, "ImpactCellIndices", configuration.ImpactCellIndices, Common.Writer.WriteInt);
                Common.Writer.PropertyBoolean(writer, "ImpactAll", configuration.ImpactAll);
                Common.Writer.PropertyArray(writer, "ScenarioParameters", configuration.ScenarioParameters, JsonAddScenarioParameter);
                Common.Writer.PropertyInt(writer, "ScenarioIndex", configuration.ScenarioIndex);
                Common.Writer.PropertyInt(writer, "Simulation", configuration.Simulation);
                JsonAddEcologicalParameters(writer, "EcologicalParameters", configuration.EcologicalParameters);
                Common.Writer.PropertyInlineArray(writer, "FileNames", configuration.FileNames, Common.Writer.WriteString);
                writer.WriteEndObject();
            }
        }
Exemplo n.º 15
0
        public static Madingley.Common.IOutput Create(
            Madingley.Common.RunState state,
            Madingley.Common.Configuration configuration,
            Madingley.Common.Environment environment,
            Madingley.Common.ModelState modelState)
        {
            // Specify the working directory
            string OutputDir = "Parameters";
            OutputDir += System.DateTime.Now.Year + "-"
                + System.DateTime.Now.Month + "-"
                + System.DateTime.Now.Day + "_"
                + System.DateTime.Now.Hour + "."
                + System.DateTime.Now.Minute + "."
                + System.DateTime.Now.Second + "/";

            // Create the working directory if this does not already exist
            System.IO.Directory.CreateDirectory(OutputDir);

            foreach (var sourceFileName in configuration.FileNames)
            {
                var fileName = System.IO.Path.GetFileName(sourceFileName);
                var destFileName = System.IO.Path.Combine(OutputDir, fileName);

                System.IO.File.Copy(sourceFileName, destFileName, true);
            }

            foreach (var sourceFileName in environment.FileNames)
            {
                var fileName = System.IO.Path.GetFileName(sourceFileName);
                var destFileName = System.IO.Path.Combine(OutputDir, fileName);

                System.IO.File.Copy(sourceFileName, destFileName, true);
            }

            // Set up the suffix for the output files
            var OutputFilesSuffix = "_";

            // Add the scenario label to the suffix for the output files
            OutputFilesSuffix += configuration.ScenarioParameters[configuration.ScenarioIndex].Label + "_";

            // Add the simulation index number to the suffix
            OutputFilesSuffix += configuration.Simulation.ToString();

            var i = new MadingleyModelInitialisation(simulationInitialisationFile, definitionsFilename, outputsFilename, outputPath, inputPath);
            i.OutputPath = OutputDir;

            var output = new Madingley.Output.MadingleyModelOutput(
                OutputFilesSuffix,
                environment,
                configuration,
                i,
                modelState);

            if (state != null)
            {
                var existing = (Madingley.Output.MadingleyModelOutput)state.Output;
                output.model.Copy(existing.model);
            }

            return output;
        }
Exemplo n.º 16
0
        public static FunctionalGroupDefinitions ConvertFunctionalGroupDefinitions(Madingley.Common.FunctionalGroupDefinitions data)
        {
            // Initialise the lists
            var length = data.Data.Count();

            var IndexLookupFromTrait = new SortedDictionary<string, SortedDictionary<string, int[]>>();
            var FunctionalGroupProperties = new SortedList<string, double[]>();
            var TraitLookupFromIndex = new SortedDictionary<string, string[]>();
            var AllFunctionalGroupsIndex = new int[length];

            // Loop over columns in the functional group definitions file
            foreach (var traitName in data.Definitions)
            {
                var traitValues =
                    data.Data.Select(d => d.Definitions.First(kv => kv.Key == traitName).Value).ToArray();

                // Declare a sorted dictionary to hold the index values for each unique trait value
                SortedDictionary<string, int[]> TraitIndexValuesList = new SortedDictionary<string, int[]>();
                // Create a string array with the values of this trait
                for (int nn = 0; nn < length; nn++)
                {
                    // Add the functional group index to the list of all indices
                    AllFunctionalGroupsIndex[nn] = nn;
                }
                // Add the trait values to the trait-value lookup list
                TraitLookupFromIndex.Add(traitName, traitValues);

                // Get the unique values for this trait
                var DistinctValues = traitValues.Distinct().ToArray();
                //Loop over the unique values for this trait and list all the functional group indices with the value
                foreach (string DistinctTraitValue in DistinctValues.ToArray())
                {
                    List<int> FunctionalGroupIndex = new List<int>();
                    //Loop over the string array associated with this trait and add the index values of matching string to a list
                    for (int kk = 0; kk < traitValues.Length; kk++)
                    {
                        if (traitValues[kk].Equals(DistinctTraitValue))
                        {
                            FunctionalGroupIndex.Add(kk);
                        }
                    }
                    //Add the unique trait value and the functional group indices to the temporary list
                    TraitIndexValuesList.Add(DistinctTraitValue, FunctionalGroupIndex.ToArray());
                }
                // Add the unique trait values and corresponding functional group indices to the functional group index lookup
                IndexLookupFromTrait.Add(traitName, TraitIndexValuesList);
            }

            // For functional group properties
            foreach (var traitName in data.Properties)
            {
                var traitValues =
                    data.Data.Select(d => d.Properties.First(kv => kv.Key == traitName).Value).ToArray();

                // Get the values for this property
                double[] TempDouble = new double[length];
                for (int nn = 0; nn < length; nn++)
                {
                    TempDouble[nn] = Convert.ToDouble(traitValues.GetValue(nn));
                }
                // Add the values to the list of functional group properties
                FunctionalGroupProperties.Add(traitName, TempDouble);
            }

            return new FunctionalGroupDefinitions(
                IndexLookupFromTrait,
                FunctionalGroupProperties,
                TraitLookupFromIndex,
                AllFunctionalGroupsIndex);
        }
Exemplo n.º 17
0
 public static void ConvertEcologicalParameters(Madingley.Common.EcologicalParameters ecologicalParameters)
 {
     EcologicalParameters.Parameters = new Dictionary<string, double>(ecologicalParameters.Parameters);
     EcologicalParameters.TimeUnits = ecologicalParameters.TimeUnits.ToArray();
 }
Exemplo n.º 18
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 };
        }
        public static void Save(string directory, Madingley.Common.Configuration c)
        {
            CreateDirectories(directory);

            var convertTimeSteps = 12;

            var parameters = new Tuple<string, string>[]
                {
                    Tuple.Create("Parameter", "Value"),
                    Tuple.Create("Timestep Units", c.GlobalModelTimeStepUnit),
                    Tuple.Create("Length of simulation (years)", (c.NumTimeSteps / convertTimeSteps).ToString()),
                    Tuple.Create("Burn-in (years)", (c.BurninTimeSteps / convertTimeSteps).ToString()),
                    Tuple.Create("Impact duration (years)", (c.ImpactTimeSteps / convertTimeSteps).ToString()),
                    Tuple.Create("Recovery duration (years)", (c.RecoveryTimeSteps / convertTimeSteps).ToString()),
                    Tuple.Create("Plankton size threshold", c.PlanktonDispersalThreshold.ToString()),
                    Tuple.Create("Draw Randomly", c.DrawRandomly ? "yes" : "no"),
                    Tuple.Create("Extinction Threshold", c.ExtinctionThreshold.ToString()),
                    Tuple.Create("Maximum Number Of Cohorts", c.MaxNumberOfCohorts.ToString()),
                    Tuple.Create("Run Cells In Parallel", c.RunCellsInParallel ? "yes" : "no"),
                    Tuple.Create("Run Simulations In Parallel", c.RunSimulationsInParallel ? "yes" : "no"),
                    Tuple.Create("Run Single Realm", c.RunRealm),
                    Tuple.Create("Impact Cell Index", System.String.Join(";", c.ImpactCellIndices)),
                    // Tuple.Create("ImpactAll", if c.ImpactAll then "yes" else "no"),
                    Tuple.Create("Dispersal only", c.DispersalOnly ? "yes" : "no"),
                    Tuple.Create("Dispersal only type", c.DispersalOnlyType)
                };

            using (var writer = new StreamWriter(Path.Combine(directory, "SimulationControlParameters.csv")))
            {
                parameters.ToList().ForEach(kv => writer.WriteLine(String.Format("{0},{1}", kv.Item1, kv.Item2)));
            }

            var fileLocationParameters = new Tuple<string, string>[]
                {
                    Tuple.Create("Parameter", "Value"),
                    Tuple.Create("Mass Bin Filename", "MassBinDefinitions.csv"),
                    Tuple.Create("Environmental Data File", "EnvironmentalDataLayers.csv"),
                    Tuple.Create("Cohort Functional Group Definitions File", "CohortFunctionalGroupDefinitions.csv"),
                    Tuple.Create("Stock Functional Group Definitions File", "StockFunctionalGroupDefinitions.csv"),
                    Tuple.Create("Ecological parameters file","EcologicalParameters.csv")
                };

            using (var writer = new StreamWriter(Path.Combine(directory, "FileLocationParameters.csv")))
            {
                fileLocationParameters.ToList().ForEach(kv => writer.WriteLine(String.Format("{0},{1}", kv.Item1, kv.Item2)));
            }

            EcologicalParameters.Save(c.EcologicalParameters, Path.Combine(directory, "Ecological Definition Files", "EcologicalParameters.csv"));

            FunctionalGroupDefinitions.Save(c.CohortFunctionalGroupDefinitions, Path.Combine(directory, "Ecological Definition Files", "CohortFunctionalGroupDefinitions.csv"));
            FunctionalGroupDefinitions.Save(c.StockFunctionalGroupDefinitions, Path.Combine(directory, "Ecological Definition Files", "StockFunctionalGroupDefinitions.csv"));

            ScenarioParameters.SaveScenarios(c.ScenarioParameters, Path.Combine(directory, "Initial Model State Setup", "Scenarios.csv"));
        }
        /// <summary>
        /// Read in the specified locations in which to run the model
        /// </summary>
        /// <param name="environment">Environment object</param>
        /// <param name="fileName">The name of the file with specific locations information</param>
        public static void ReadSpecificLocations(Madingley.Common.Environment environment, string fileName)
        {
            var CellList = new List<Tuple<int, int>>();

            List<double> LatitudeList = new List<double>();
            List<double> LongitudeList = new List<double>();

            Console.WriteLine("Reading in specific location data");
            Console.WriteLine("");

            // construct file name
            string FileString = "msds:csv?file=" + fileName + "&openMode=readOnly";

            // Read in the data
            DataSet InternalData = DataSet.Open(FileString);

            foreach (Variable v in InternalData.Variables)
            {
                //Get the name of the variable currently referenced in the dataset
                string HeaderName = v.Name;
                //Copy the values for this variable into an array
                var TempValues = v.GetData();

                switch (HeaderName.ToLower())
                {
                    // Add the latitude and longitude values to the appropriate list
                    case "latitude":
                        for (int ii = 0; ii < TempValues.Length; ii++) LatitudeList.Add(Convert.ToDouble(TempValues.GetValue(ii).ToString()));
                        break;
                    case "longitude":
                        for (int ii = 0; ii < TempValues.Length; ii++) LongitudeList.Add(Convert.ToDouble(TempValues.GetValue(ii).ToString()));
                        break;
                    default:
                        Console.WriteLine("Variable defined in the specific location file but not processed: ", HeaderName);
                        break;
                }
            }

            InternalData.Dispose();

            // Loop over cells defined in the specific locations file
            for (int ii = 0; ii < LatitudeList.Count; ii++)
            {
                // Get the longitude and latitude indices for the current grid cell
                var latitudeIndex = (int)Math.Floor((LatitudeList.ElementAt(ii) - environment.BottomLatitude) / environment.CellSize);
                var longitudeIndex = (int)Math.Floor((LongitudeList.ElementAt(ii) - environment.LeftmostLongitude) / environment.CellSize);

                // Add these indices to the list of active cells
                CellList.Add(Tuple.Create(latitudeIndex, longitudeIndex));
            }

            environment.FocusCells = CellList;
        }
Exemplo n.º 21
0
        /// <summary>
        /// Remove individuals lost from cohorts through direct harvesting of animals
        /// </summary>
        /// <param name="gridCellCohorts">The cohorts in the current grid cell</param>
        /// <param name="harvestingScenario">The scenario of direct harvesting of animals to apply</param>
        /// <param name="currentTimestep">The current model time step</param>
        /// <param name="burninSteps">The number of time steps to spin the model up for before applying the harvesting scenario</param>
        /// <param name="impactSteps">The number of time steps to apply the scenario for</param>
        /// <param name="cellEnvironment">The environment in the current grid cell</param>
        /// <param name="impactCell">The index of the cell, within the list of all cells to run, to apply the scenario for</param>
        public void RemoveHarvestedIndividuals(GridCellCohortHandler gridCellCohorts,
            Madingley.Common.ScenarioParameter harvestingScenario, uint currentTimestep, uint burninSteps, uint impactSteps, uint totalSteps,
            SortedList<string, double[]> cellEnvironment, Boolean impactCell, string globalModelTimestepUnits, FunctionalGroupDefinitions cohortFGs)
        {
            if (impactCell)
            {

                //If this is marine cell
                if (cellEnvironment["Realm"][0] == 2.0)
                {
                    if (harvestingScenario.ParamString == "no")
                    {
                        // Do not apply any harvesting
                    }
                    else if (harvestingScenario.ParamString == "constant")
                    {
                        double TargetBiomass;
                        if (FisheriesCatch != null)
                        {
                            TargetBiomass = (1000 *
                            FisheriesCatch.ModelGridCatchTotal[Convert.ToInt32(cellEnvironment["LatIndex"][0]), Convert.ToInt32(cellEnvironment["LonIndex"][0])])
                            / 12.0;
                        }
                        else
                        {
                            TargetBiomass = harvestingScenario.ParamDouble1;
                        }
                        // If the burn-in period has been completed, then apply
                        // the harvesting scenario
                        if (currentTimestep > burninSteps)
                        {
                            ApplyHarvesting(gridCellCohorts, TargetBiomass, cellEnvironment, currentTimestep);
                        }
                    }
                    else if (harvestingScenario.ParamString == "fish-catch")
                    {
                        //Initialise an instance of ApplyFishingCatches for this cell
                        if (currentTimestep == burninSteps)
                            ApplyCatches[Convert.ToInt32(cellEnvironment["LatIndex"][0]),
                            Convert.ToInt32(cellEnvironment["LonIndex"][0])] = new ApplyFishingCatches(FisheriesCatch);

                        if (currentTimestep > burninSteps)
                        {
                            //Bin the cohorts of the current cell
                            ApplyCatches[Convert.ToInt32(cellEnvironment["LatIndex"][0]),
                            Convert.ToInt32(cellEnvironment["LonIndex"][0])].BinCohorts(gridCellCohorts, FisheriesCatch, cohortFGs);
                            //Now remove the catch
                            ApplyCatches[Convert.ToInt32(cellEnvironment["LatIndex"][0]),
                            Convert.ToInt32(cellEnvironment["LonIndex"][0])].ApplyCatches(gridCellCohorts, FisheriesCatch,
                                Convert.ToInt32(cellEnvironment["LatIndex"][0]),
                                Convert.ToInt32(cellEnvironment["LonIndex"][0]));
                        }
                    }

                }
                else
                {

                    if (harvestingScenario.ParamString == "no")
                    {
                        // Do not apply any harvesting
                    }
                    else if (harvestingScenario.ParamString == "constant")
                    {
                        // If the burn-in period has been completed, then apply
                        // the harvesting scenario
                        if (currentTimestep > burninSteps)
                        {
                            ApplyHarvesting(gridCellCohorts, harvestingScenario.ParamDouble1, cellEnvironment, currentTimestep);
                        }
                    }
                    else if (harvestingScenario.ParamString == "temporary")
                    {
                        // If the burn-in period has been completed and the period of impact has not elapsed,
                        // then apply the harvesting scenario
                        if ((currentTimestep > burninSteps) && (currentTimestep <= (burninSteps + impactSteps)))
                        {
                            ApplyHarvesting(gridCellCohorts, harvestingScenario.ParamDouble1, cellEnvironment, currentTimestep);
                        }
                    }
                    else if (harvestingScenario.ParamString == "escalating")
                    {
                        // If the spin-up period has been completed, then apply a level of harvesting
                        // according to the number of time-steps that have elapsed since the spin-up ended
                        if (currentTimestep > burninSteps)
                        {
                            // Calculate the target biomass for harvesting based on the number of time steps that have elapsed since the spin-up
                            double TargetBiomass = (Math.Min(50000, (((currentTimestep - burninSteps) / 12.0) * harvestingScenario.ParamDouble1)));

                            // Apply the harvesting scenario using the calculated target biomass
                            ApplyHarvesting(gridCellCohorts, TargetBiomass, cellEnvironment, currentTimestep);
                        }

                    }
                    else if (harvestingScenario.ParamString == "temp-escalating-declining")
                    {
                        // If the spin-up period has been completed, then apply a level of harvesting
                        // according to the number of time-steps that have elapsed since the spin-up ended
                        if ((currentTimestep > burninSteps) && (currentTimestep <= (burninSteps + impactSteps)))
                        {
                            // Calculate the target biomass for harvesting based on the number of time steps that have elapsed since the spin-up
                            double TargetBiomass = (Math.Min(50000, (((currentTimestep - burninSteps) / 12.0) * harvestingScenario.ParamDouble1)));

                            // Apply the harvesting scenario using the calculated target biomass
                            ApplyHarvesting(gridCellCohorts, TargetBiomass, cellEnvironment, currentTimestep);
                        }
                        else if (currentTimestep > (burninSteps + impactSteps))
                        {
                            // Calculate the target biomass for harvesting based on the number of time steps that have elapsed since the spin-up
                            double TargetBiomass = (Math.Min(50000, ((-(totalSteps - currentTimestep) / 12.0) * harvestingScenario.ParamDouble1)));

                            // Apply the harvesting scenario using the calculated target biomass
                            ApplyHarvesting(gridCellCohorts, TargetBiomass, cellEnvironment, currentTimestep);
                        }

                    }
                    else if (harvestingScenario.ParamString == "temp-escalating")
                    {
                        // If the spin-up period has been completed and the period of impact has not elapsed,
                        // then remove a proportion of plant matter
                        // according to the number of time-steps that have elapsed since the spin-up ended
                        if ((currentTimestep > burninSteps) && (currentTimestep <= (burninSteps + impactSteps)))
                        {
                            // Calculate the target biomass for harvesting based on the number of time steps that have elapsed since the spin-up
                            double TargetBiomass = (Math.Min(50000, (((currentTimestep - burninSteps) / 12.0) * harvestingScenario.ParamDouble1)));

                            // Apply the harvesting scenarion using the calculated target biomass
                            ApplyHarvesting(gridCellCohorts, TargetBiomass, cellEnvironment, currentTimestep);
                        }
                    }
                    else if (harvestingScenario.ParamString == "temp-escalating-const-rate")
                    {
                        // If the spin-up period has been completed and the period of impact (specified by the third scenario element
                        // has not elapsed,
                        // then remove a portion of  plant matter
                        // according to the number of time-steps that have elapsed since the spin-up ended

                        int ConstImpactSteps = Convert.ToInt32(harvestingScenario.ParamDouble2 * Utilities.ConvertTimeUnits("year", globalModelTimestepUnits));

                        if ((currentTimestep > burninSteps) && (currentTimestep <= (burninSteps + ConstImpactSteps)))
                        {
                            // Calculate the target biomass for harvesting based on the number of time steps that have elapsed since the spin-up
                            double TargetBiomass = (Math.Min(200000, (((currentTimestep - burninSteps) / 12.0) * harvestingScenario.ParamDouble1)));

                            // Apply the harvesting scenarion using the calculated target biomass
                            ApplyHarvesting(gridCellCohorts, TargetBiomass, cellEnvironment, currentTimestep);
                        }
                    }
                    else if (harvestingScenario.ParamString == "temp-escalating-const-rate-duration")
                    {
                        // If the spin-up period has been completed and the period of impact (specified by the third scenario element
                        // has not elapsed,
                        // then remove a proportion of plant matter
                        // according to the number of time-steps that have elapsed since the spin-up ended

                        int ConstImpactSteps = Convert.ToInt32(harvestingScenario.ParamDouble2 * Utilities.ConvertTimeUnits("year", globalModelTimestepUnits));

                        if ((currentTimestep > burninSteps) && (currentTimestep <= (burninSteps + impactSteps)))
                        {
                            //gridCellStocks[actingStock].TotalBiomass -= gridCellStocks[actingStock].TotalBiomass *
                            //    (Math.Min(1.0, (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.Item2)));

                            double TargetBiomass = (Math.Min(200000,
                                            Math.Min(((ConstImpactSteps / 12.0) * harvestingScenario.ParamDouble1),
                                            (((currentTimestep - burninSteps) / 12.0) * harvestingScenario.ParamDouble1))));

                            // Apply the harvesting scenarion using the calculated target biomass
                            ApplyHarvesting(gridCellCohorts, TargetBiomass, cellEnvironment, currentTimestep);
                        }
                    }
                    else
                    {
                        Debug.Fail("There is no method for the harvesting scenario specified");
                    }

                }
            }
        }
Exemplo n.º 22
0
        /// <summary>
        /// Remove human appropriated matter from the grid cell autotroph stocks
        /// </summary>
        /// <param name="cellEnvironment">The environment in the current grid cell</param>
        /// <param name="humanNPPScenario">The type of NPP extraction to apply</param>
        /// <param name="gridCellStocks">The stocks in the current grid cell</param>
        /// <param name="actingStock">The position of the acting stock in the jagged array of grid cell stocks</param>
        /// <param name="currentTimestep">The current model time step</param>
        /// <param name="burninSteps">The number of steps to run before impact is simulated</param>
        /// <param name="impactSteps">The number of time steps to apply the impact for (for 'temporary' scenarios)</param>
        /// <param name="impactCell">Whether this cell should have human impacts applied</param>
        /// <remarks>Scenario types are: 'no' = no removal; 'hanpp' = appropriated NPP estimate from input map; constant = constant appropriation after burn-in; 
        /// temporary = constant after burn-in until specified time; value = proportion of plant biomass appropriated</remarks>
        public double RemoveHumanAppropriatedMatter(double wetMatterNPP, SortedList<string, double[]> cellEnvironment,
            Madingley.Common.ScenarioParameter humanNPPScenario, GridCellStockHandler
            gridCellStocks, int[] actingStock, uint currentTimestep, uint burninSteps,
            uint impactSteps, uint recoverySteps, uint instantStep, uint numInstantStep, Boolean impactCell,
            string globalModelTimestepUnits)
        {

            double RemovalRate = 0.0;

            if (impactCell)
            {
                // Factor to convert NPP from units per m2 to units per km2
                double m2Tokm2Conversion = 1000000.0;

                if (humanNPPScenario.ParamString == "hanpp")
                {

                    if (currentTimestep > burninSteps)
                    {
                        // Loop over stocks in the grid cell and calculate the total biomass of all stocks
                        double TotalAutotrophBiomass = 0.0;
                        foreach (var stockFunctionalGroup in gridCellStocks)
                        {
                            for (int i = 0; i < stockFunctionalGroup.Count; i++)
                            {
                                TotalAutotrophBiomass += stockFunctionalGroup[i].TotalBiomass;
                            }
                        }

                        // Get the total amount of NPP appropriated by humans from this cell
                        double HANPP = cellEnvironment["HANPP"][0] * cellEnvironment["Seasonality"][currentTimestep % 12];

                        // If HANPP value is missing, then assume zero
                        if (HANPP == cellEnvironment["Missing Value"][0]) HANPP = 0.0;

                        // Allocate HANPP for this stock according to the proportion of total autotroph biomass that the stock represents
                        if (TotalAutotrophBiomass == 0.0)
                        {
                            HANPP = 0.0;
                        }
                        else
                        {
                            HANPP *= (gridCellStocks[actingStock].TotalBiomass / TotalAutotrophBiomass);
                        }

                        // Convert gC/m2/month to gC/km2/month
                        HANPP *= m2Tokm2Conversion;

                        // Multiply by cell area (in km2) to get g/cell/day
                        HANPP *= cellEnvironment["Cell Area"][0];

                        // Convert from gC to g dry matter
                        double DryMatterAppropriated = HANPP * 2;

                        // Convert from g dry matter to g wet matter
                        double WetMatterAppropriated = DryMatterAppropriated * 2;

                        //Calculate the rate of HANPP offtake
                        RemovalRate = Math.Min(1.0, WetMatterAppropriated / wetMatterNPP);

                        // Remove human appropriated autotroph biomass from total autotroph biomass
                        //gridCellStocks[actingStock].TotalBiomass -= WetMatterAppropriated;

                        //if (gridCellStocks[actingStock].TotalBiomass < 0.0) gridCellStocks[actingStock].TotalBiomass = 0.0;
                    }
                }
                else if (humanNPPScenario.ParamString == "no")
                {
                    // Do not remove any autotroph biomass
                }
                else if (humanNPPScenario.ParamString == "constant")
                {
                    // If the burn-in period has been completed, then remove the specified constant
                    // fraction from the acting autotroph stock
                    if (currentTimestep > burninSteps)
                    {
                        //gridCellStocks[actingStock].TotalBiomass -= (gridCellStocks[actingStock].TotalBiomass *
                        //    humanNPPScenario.Item2);
                        RemovalRate = humanNPPScenario.ParamDouble1;
                    }
                }
#if true
                else if (humanNPPScenario.ParamString == "reallyconstant")
                {
                    RemovalRate = humanNPPScenario.ParamDouble1;
                }
#endif
                else if (humanNPPScenario.ParamString == "temporary")
                {
                    // If the spin-up period has been completed and the period of impact has not elapsed,
                    // then remove the specified constant fraction from the acting autotroph stock
                    if ((currentTimestep > burninSteps) && (currentTimestep <= (burninSteps + impactSteps)))
                    {
                        //gridCellStocks[actingStock].TotalBiomass -= (gridCellStocks[actingStock].TotalBiomass *
                        //    humanNPPScenario.Item2);
                        RemovalRate = humanNPPScenario.ParamDouble1;
                    }

                }
                else if (humanNPPScenario.ParamString == "escalating")
                {
                    // If the spin-up period has been completed, then remove a proportion of plant matter
                    // according to the number of time-steps that have elapsed since the spin-up ended
                    if (currentTimestep > burninSteps)
                    {
                        //gridCellStocks[actingStock].TotalBiomass -= gridCellStocks[actingStock].TotalBiomass *
                        //    (Math.Min(1.0, (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.Item2)));

                        RemovalRate = (Math.Min(1.0, (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.ParamDouble1)));

                    }
                }
                else if (humanNPPScenario.ParamString == "temp-escalating")
                {
                    // If the spin-up period has been completed and the period of impact has not elapsed, 
                    // then remove a proportion of plant matter
                    // according to the number of time-steps that have elapsed since the spin-up ended
                    if ((currentTimestep > burninSteps) && (currentTimestep <= (burninSteps + impactSteps)))
                    {
                        //gridCellStocks[actingStock].TotalBiomass -= gridCellStocks[actingStock].TotalBiomass *
                        //    (Math.Min(1.0, (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.Item2)));

                        RemovalRate = (Math.Min(1.0, (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.ParamDouble1)));
                    }

                }
                else if (humanNPPScenario.ParamString == "temp-escalating-const-rate")
                {
                    // If the spin-up period has been completed and the period of impact (specified by the third scenario element
                    // has not elapsed, 
                    // then remove a proportion of plant matter
                    // according to the number of time-steps that have elapsed since the spin-up ended

                    int ConstImpactSteps = Convert.ToInt32(humanNPPScenario.ParamDouble2 * Utilities.ConvertTimeUnits("year", globalModelTimestepUnits));

                    if ((currentTimestep > burninSteps) && (currentTimestep <= (burninSteps + ConstImpactSteps)))
                    {
                        //gridCellStocks[actingStock].TotalBiomass -= gridCellStocks[actingStock].TotalBiomass *
                        //    (Math.Min(1.0, (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.Item2)));

                        RemovalRate = (Math.Min(1.0, (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.ParamDouble1)));
                    }
                }
                else if (humanNPPScenario.ParamString == "temp-escalating-const-rate-duration")
                {
                    // If the spin-up period has been completed and the period of impact (specified by the third scenario element
                    // has not elapsed, 
                    // then remove a proportion of plant matter
                    // according to the number of time-steps that have elapsed since the spin-up ended

                    int ConstImpactSteps = Convert.ToInt32(humanNPPScenario.ParamDouble2 * Utilities.ConvertTimeUnits("year", globalModelTimestepUnits));

                    if ((currentTimestep > burninSteps) && (currentTimestep <= (burninSteps + impactSteps)))
                    {
                        //gridCellStocks[actingStock].TotalBiomass -= gridCellStocks[actingStock].TotalBiomass *
                        //    (Math.Min(1.0, (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.Item2)));

                        RemovalRate = (Math.Min(1.0,
                                        Math.Min(((ConstImpactSteps / 12.0) * humanNPPScenario.ParamDouble1),
                                        (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.ParamDouble1))));
                    }
                }
                else if (humanNPPScenario.ParamString == "temp-escalating-declining")
                {
                    // If the spin-up period has been completed, then apply a level of harvesting
                    // according to the number of time-steps that have elapsed since the spin-up ended
                    if ((currentTimestep > burninSteps) && (currentTimestep <= (burninSteps + impactSteps)))
                    {
                        //gridCellStocks[actingStock].TotalBiomass -= gridCellStocks[actingStock].TotalBiomass *
                        //    (Math.Min(1.0, (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.Item2)));

                        RemovalRate = (Math.Min(1.0, (((currentTimestep - burninSteps) / 12.0) * humanNPPScenario.ParamDouble1)));
                    }
                    else if ((currentTimestep > (burninSteps + impactSteps)) & (currentTimestep <= (burninSteps + impactSteps + recoverySteps)))
                    {
                        //gridCellStocks[actingStock].TotalBiomass -= gridCellStocks[actingStock].TotalBiomass *
                        //    (Math.Min(1.0, (((burninSteps + impactSteps + recoverySteps - currentTimestep) / 12.0) * humanNPPScenario.Item2)));

                        RemovalRate = (Math.Min(1.0, (((burninSteps + impactSteps + recoverySteps - currentTimestep) / 12.0) * humanNPPScenario.ParamDouble1)));
                    }

                }
                else
                {
                    Debug.Fail("There is no method for the human extraction of NPP scenario specified");
                }
            }

            return (RemovalRate);
        }