Ejemplo n.º 1
0
        public static void SaveScenarios(IEnumerable <Madingley.Common.ScenarioParameters> scenarioParameters, string filename)
        {
            var header = new string[] { "label", "npp", "temperature", "harvesting", "simulation number" };

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

                scenarioParameters.ToList().ForEach(si =>
                {
                    var s3 = si.Parameters;

                    var p3 = new Madingley.Common.ScenarioParameter[] { s3["npp"], s3["temperature"], s3["harvesting"] }.Select
                        (s3i => String.Format("{0} {1} {2}", s3i.ParamString, s3i.ParamDouble1.ToString(), s3i.ParamDouble2.ToString()));

                    var q3 = String.Join(",", p3);

                    writer.WriteLine(String.Format("{0},{1},{2}", si.Label, q3, si.SimulationNumber.ToString()));
                });
            }
        }
        public static void SaveScenarios(IEnumerable<Madingley.Common.ScenarioParameters> scenarioParameters, string filename)
        {
            var header = new string[] { "label", "npp", "temperature", "harvesting", "simulation number" };

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

                scenarioParameters.ToList().ForEach(si =>
                {
                    var s3 = si.Parameters;

                    var p3 = new Madingley.Common.ScenarioParameter[] { s3["npp"], s3["temperature"], s3["harvesting"] }.Select
                            (s3i => String.Format("{0} {1} {2}", s3i.ParamString, s3i.ParamDouble1.ToString(), s3i.ParamDouble2.ToString()));

                    var q3 = String.Join(",", p3);

                    writer.WriteLine(String.Format("{0},{1},{2}", si.Label, q3, si.SimulationNumber.ToString()));
                });
            }
        }
Ejemplo n.º 3
0
        public static Madingley.Common.Configuration Deserialize(TextReader sr)
        {
            Func <Newtonsoft.Json.JsonTextReader, Madingley.Common.FunctionalGroupDefinition> JsonReadFunctionalGroupDefinition = (reader) =>
            {
                var ret = new Madingley.Common.FunctionalGroupDefinition();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "Definitions": ret.Definitions = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadString); break;

                    case "Properties": ret.Properties = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadDouble); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return(ret);
            };

            Func <Newtonsoft.Json.JsonTextReader, Madingley.Common.FunctionalGroupDefinitions> JsonReadFunctionalGroupDefinitions = (reader) =>
            {
                var ret = new Madingley.Common.FunctionalGroupDefinitions();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "Data": ret.Data = Common.Reader.ReadArray(reader, JsonReadFunctionalGroupDefinition); break;

                    case "Definitions": ret.Definitions = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;

                    case "Properties": ret.Properties = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return(ret);
            };

            Func <Newtonsoft.Json.JsonTextReader, Madingley.Common.ScenarioParameter> JsonReadScenarioParameter = (reader) =>
            {
                var ret = new Madingley.Common.ScenarioParameter();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "ParamString": ret.ParamString = Common.Reader.ReadString(reader); break;

                    case "ParamDouble1": ret.ParamDouble1 = Common.Reader.ReadDouble(reader); break;

                    case "ParamDouble2": ret.ParamDouble2 = Common.Reader.ReadDouble(reader); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return(ret);
            };

            Func <Newtonsoft.Json.JsonTextReader, IDictionary <string, Madingley.Common.ScenarioParameter> > JsonReadKVPScenarioParameter = (reader) =>
            {
                var ret = new Dictionary <string, Madingley.Common.ScenarioParameter>();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var key = Convert.ToString(reader.Value);
                    reader.Read();
                    var value = JsonReadScenarioParameter(reader);

                    ret.Add(key, value);
                }

                return(ret);
            };

            Func <Newtonsoft.Json.JsonTextReader, Madingley.Common.ScenarioParameters> JsonReadScenarioParameters = (reader) =>
            {
                var ret = new Madingley.Common.ScenarioParameters();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "Label": ret.Label = Common.Reader.ReadString(reader); break;

                    case "SimulationNumber": ret.SimulationNumber = Common.Reader.ReadInt(reader); break;

                    case "Parameters": ret.Parameters = JsonReadKVPScenarioParameter(reader); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return(ret);
            };

            Func <Newtonsoft.Json.JsonTextReader, Madingley.Common.EcologicalParameters> JsonReadEcologicalParameters = (reader) =>
            {
                var ret = new Madingley.Common.EcologicalParameters();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "Parameters": ret.Parameters = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadDouble); break;

                    case "TimeUnits": ret.TimeUnits = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return(ret);
            };

            var configuration = new Madingley.Common.Configuration();

            using (var reader = new Newtonsoft.Json.JsonTextReader(sr))
            {
                reader.Read();
                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                       reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                    case "GlobalModelTimeStepUnit": configuration.GlobalModelTimeStepUnit = Common.Reader.ReadString(reader); break;

                    case "NumTimeSteps": configuration.NumTimeSteps = Common.Reader.ReadInt(reader); break;

                    case "BurninTimeSteps": configuration.BurninTimeSteps = Common.Reader.ReadInt(reader); break;

                    case "ImpactTimeSteps": configuration.ImpactTimeSteps = Common.Reader.ReadInt(reader); break;

                    case "RecoveryTimeSteps": configuration.RecoveryTimeSteps = Common.Reader.ReadInt(reader); break;

                    case "RunCellsInParallel": configuration.RunCellsInParallel = Common.Reader.ReadBoolean(reader); break;

                    case "RunSimulationsInParallel": configuration.RunSimulationsInParallel = Common.Reader.ReadBoolean(reader); break;

                    case "RunRealm": configuration.RunRealm = Common.Reader.ReadString(reader); break;

                    case "DrawRandomly": configuration.DrawRandomly = Common.Reader.ReadBoolean(reader); break;

                    case "ExtinctionThreshold": configuration.ExtinctionThreshold = Common.Reader.ReadDouble(reader); break;

                    case "MaxNumberOfCohorts": configuration.MaxNumberOfCohorts = Common.Reader.ReadInt(reader); break;

                    case "DispersalOnly": configuration.DispersalOnly = Common.Reader.ReadBoolean(reader); break;

                    case "DispersalOnlyType": configuration.DispersalOnlyType = Common.Reader.ReadString(reader); break;

                    case "PlanktonDispersalThreshold": configuration.PlanktonDispersalThreshold = Common.Reader.ReadDouble(reader); break;

                    case "CohortFunctionalGroupDefinitions": configuration.CohortFunctionalGroupDefinitions = JsonReadFunctionalGroupDefinitions(reader); break;

                    case "StockFunctionalGroupDefinitions": configuration.StockFunctionalGroupDefinitions = JsonReadFunctionalGroupDefinitions(reader); break;

                    case "ImpactCellIndices": configuration.ImpactCellIndices = Common.Reader.ReadArray(reader, Common.Reader.ReadInt); break;

                    case "ImpactAll": configuration.ImpactAll = Common.Reader.ReadBoolean(reader); break;

                    case "ScenarioParameters": configuration.ScenarioParameters = Common.Reader.ReadArray(reader, JsonReadScenarioParameters).ToList(); break;

                    case "ScenarioIndex": configuration.ScenarioIndex = Common.Reader.ReadInt(reader); break;

                    case "Simulation": configuration.Simulation = Common.Reader.ReadInt(reader); break;

                    case "EcologicalParameters": configuration.EcologicalParameters = JsonReadEcologicalParameters(reader); break;

                    case "FileNames": configuration.FileNames = Common.Reader.ReadArray(reader, Common.Reader.ReadString).ToList(); break;

                    default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }
            }

            return(configuration);
        }
Ejemplo n.º 4
0
 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 Madingley.Common.Configuration Deserialize(TextReader sr)
        {
            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.FunctionalGroupDefinition> JsonReadFunctionalGroupDefinition = (reader) =>
            {
                var ret = new Madingley.Common.FunctionalGroupDefinition();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                        case "Definitions": ret.Definitions = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadString); break;
                        case "Properties": ret.Properties = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadDouble); break;
                        default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return ret;
            };

            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.FunctionalGroupDefinitions> JsonReadFunctionalGroupDefinitions = (reader) =>
                {
                    var ret = new Madingley.Common.FunctionalGroupDefinitions();

                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                    while (reader.Read() &&
                        reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                    {
                        Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                        Debug.Assert(reader.ValueType == typeof(string));

                        var property = Convert.ToString(reader.Value);
                        reader.Read();

                        switch (property)
                        {
                            case "Data": ret.Data = Common.Reader.ReadArray(reader, JsonReadFunctionalGroupDefinition); break;
                            case "Definitions": ret.Definitions = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;
                            case "Properties": ret.Properties = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;
                            default: throw new Exception(string.Format("Unexpected property: {0}", property));
                        }
                    }

                    return ret;
                };

            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.ScenarioParameter> JsonReadScenarioParameter = (reader) =>
            {
                var ret = new Madingley.Common.ScenarioParameter();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                        case "ParamString": ret.ParamString = Common.Reader.ReadString(reader); break;
                        case "ParamDouble1": ret.ParamDouble1 = Common.Reader.ReadDouble(reader); break;
                        case "ParamDouble2": ret.ParamDouble2 = Common.Reader.ReadDouble(reader); break;
                        default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }

                return ret;
            };

            Func<Newtonsoft.Json.JsonTextReader, IDictionary<string, Madingley.Common.ScenarioParameter>> JsonReadKVPScenarioParameter = (reader) =>
            {
                var ret = new Dictionary<string, Madingley.Common.ScenarioParameter>();

                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var key = Convert.ToString(reader.Value);
                    reader.Read();
                    var value = JsonReadScenarioParameter(reader);

                    ret.Add(key, value);
                }

                return ret;
            };

            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.ScenarioParameters> JsonReadScenarioParameters = (reader) =>
                {
                    var ret = new Madingley.Common.ScenarioParameters();

                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                    while (reader.Read() &&
                        reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                    {
                        Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                        Debug.Assert(reader.ValueType == typeof(string));

                        var property = Convert.ToString(reader.Value);
                        reader.Read();

                        switch (property)
                        {
                            case "Label": ret.Label = Common.Reader.ReadString(reader); break;
                            case "SimulationNumber": ret.SimulationNumber = Common.Reader.ReadInt(reader); break;
                            case "Parameters": ret.Parameters = JsonReadKVPScenarioParameter(reader); break;
                            default: throw new Exception(string.Format("Unexpected property: {0}", property));
                        }
                    }

                    return ret;
                };

            Func<Newtonsoft.Json.JsonTextReader, Madingley.Common.EcologicalParameters> JsonReadEcologicalParameters = (reader) =>
                {
                    var ret = new Madingley.Common.EcologicalParameters();

                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                    while (reader.Read() &&
                        reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                    {
                        Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                        Debug.Assert(reader.ValueType == typeof(string));

                        var property = Convert.ToString(reader.Value);
                        reader.Read();

                        switch (property)
                        {
                            case "Parameters": ret.Parameters = Common.Reader.ReadKeyValuePairs(reader, Common.Reader.ReadDouble); break;
                            case "TimeUnits": ret.TimeUnits = Common.Reader.ReadArray(reader, Common.Reader.ReadString); break;
                            default: throw new Exception(string.Format("Unexpected property: {0}", property));
                        }
                    }

                    return ret;
                };

            var configuration = new Madingley.Common.Configuration();

            using (var reader = new Newtonsoft.Json.JsonTextReader(sr))
            {
                reader.Read();
                Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.StartObject);

                while (reader.Read() &&
                    reader.TokenType != Newtonsoft.Json.JsonToken.EndObject)
                {
                    Debug.Assert(reader.TokenType == Newtonsoft.Json.JsonToken.PropertyName);
                    Debug.Assert(reader.ValueType == typeof(string));

                    var property = Convert.ToString(reader.Value);
                    reader.Read();

                    switch (property)
                    {
                        case "GlobalModelTimeStepUnit": configuration.GlobalModelTimeStepUnit = Common.Reader.ReadString(reader); break;
                        case "NumTimeSteps": configuration.NumTimeSteps = Common.Reader.ReadInt(reader); break;
                        case "BurninTimeSteps": configuration.BurninTimeSteps = Common.Reader.ReadInt(reader); break;
                        case "ImpactTimeSteps": configuration.ImpactTimeSteps = Common.Reader.ReadInt(reader); break;
                        case "RecoveryTimeSteps": configuration.RecoveryTimeSteps = Common.Reader.ReadInt(reader); break;
                        case "RunCellsInParallel": configuration.RunCellsInParallel = Common.Reader.ReadBoolean(reader); break;
                        case "RunSimulationsInParallel": configuration.RunSimulationsInParallel = Common.Reader.ReadBoolean(reader); break;
                        case "RunRealm": configuration.RunRealm = Common.Reader.ReadString(reader); break;
                        case "DrawRandomly": configuration.DrawRandomly = Common.Reader.ReadBoolean(reader); break;
                        case "ExtinctionThreshold": configuration.ExtinctionThreshold = Common.Reader.ReadDouble(reader); break;
                        case "MaxNumberOfCohorts": configuration.MaxNumberOfCohorts = Common.Reader.ReadInt(reader); break;
                        case "DispersalOnly": configuration.DispersalOnly = Common.Reader.ReadBoolean(reader); break;
                        case "DispersalOnlyType": configuration.DispersalOnlyType = Common.Reader.ReadString(reader); break;
                        case "PlanktonDispersalThreshold": configuration.PlanktonDispersalThreshold = Common.Reader.ReadDouble(reader); break;
                        case "CohortFunctionalGroupDefinitions": configuration.CohortFunctionalGroupDefinitions = JsonReadFunctionalGroupDefinitions(reader); break;
                        case "StockFunctionalGroupDefinitions": configuration.StockFunctionalGroupDefinitions = JsonReadFunctionalGroupDefinitions(reader); break;
                        case "ImpactCellIndices": configuration.ImpactCellIndices = Common.Reader.ReadArray(reader, Common.Reader.ReadInt); break;
                        case "ImpactAll": configuration.ImpactAll = Common.Reader.ReadBoolean(reader); break;
                        case "ScenarioParameters": configuration.ScenarioParameters = Common.Reader.ReadArray(reader, JsonReadScenarioParameters).ToList(); break;
                        case "ScenarioIndex": configuration.ScenarioIndex = Common.Reader.ReadInt(reader); break;
                        case "Simulation": configuration.Simulation = Common.Reader.ReadInt(reader); break;
                        case "EcologicalParameters": configuration.EcologicalParameters = JsonReadEcologicalParameters(reader); break;
                        case "FileNames": configuration.FileNames = Common.Reader.ReadArray(reader, Common.Reader.ReadString).ToList(); break;
                        default: throw new Exception(string.Format("Unexpected property: {0}", property));
                    }
                }
            }

            return configuration;
        }
Ejemplo n.º 6
0
        /// <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");
            }
        }
Ejemplo n.º 7
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);
        }
Ejemplo n.º 8
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");
                    }
                }
            }
        }