public void Init() { intVar = new InputVar<int>("intVar"); values = new int[] { -4, 78900, 0, 555 }; string[] valsAsStrs = Array.ConvertAll(values, new Converter<int, string>(Convert.ToString)); valuesAsStr = string.Join(" ", valsAsStrs); }
//--------------------------------------------------------------------- protected override void ReadBiomassMaps() { // TO DO: Probably should be required in the final release but made // it optional for now so that CBI doesn't have to update every // scenario in the short term. InputVar<string> biomassMapNames = new InputVar<string>("BiomassMaps"); string foo; if (ReadOptionalVar(biomassMapNames)) foo /*parameters.BiomassMapNames*/ = biomassMapNames.Value; }
//--------------------------------------------------------------------- protected InputValue <ISiteSelector> ReadSiteSelector(StringReader reader, out int index) { TextReader.SkipWhitespace(reader); index = reader.Index; string name = TextReader.ReadWord(reader); if (name == "") { throw new InputValueException(); // Missing value } ISiteSelector selector; StringBuilder valueAsStr = new StringBuilder(name); // Site selection -- Complete stand if (name == SiteSelection.Complete) { selector = new CompleteStand(); } // Site selection -- Target size with partial or complete spread else if (name == SiteSelection.CompleteAndSpreading || name == SiteSelection.TargetAndSpreading) { InputVar <double> minTargetSize = new InputVar <double>("the minimum target harvest size"); ReadValue(minTargetSize, reader); InputVar <double> maxTargetSize = new InputVar <double>("the maximum target harvest size"); ReadValue(maxTargetSize, reader); //validate the target size for spreading algorithms StandSpreading.ValidateTargetSizes(minTargetSize.Value, maxTargetSize.Value); if (name == SiteSelection.TargetAndSpreading) { // Site selection -- partial spread selector = new PartialStandSpreading(minTargetSize.Value.Actual, maxTargetSize.Value.Actual); } else { // Site selection -- complete stand selector = new CompleteStandSpreading(minTargetSize.Value.Actual, maxTargetSize.Value.Actual); } valueAsStr.AppendFormat(" {0}", minTargetSize.Value.String); valueAsStr.AppendFormat(" {0}", maxTargetSize.Value.String); } // Site selection -- Patch cutting else if (name == SiteSelection.Patch) { InputVar <Percentage> percentage = new InputVar <Percentage>("the site percentage for patch cutting"); ReadValue(percentage, reader); PatchCutting.ValidatePercentage(percentage.Value); InputVar <double> size = new InputVar <double>("the target patch size"); ReadValue(size, reader); PatchCutting.ValidateSize(size.Value); // priority is an optional value so we can't use ReadValue TextReader.SkipWhitespace(reader); index = reader.Index; string priority = TextReader.ReadWord(reader); selector = new PatchCutting(percentage.Value.Actual, size.Value.Actual, priority); valueAsStr.AppendFormat(" {0} {1} {2}", percentage.Value.String, size.Value.String, priority); } else { string[] methodList = new string[] { "Site selection methods:", " " + SiteSelection.Complete, " " + SiteSelection.CompleteAndSpreading, " " + SiteSelection.TargetAndSpreading, " " + SiteSelection.Patch }; throw new InputValueException(name, name + " is not a valid site selection method", new MultiLineText(methodList)); } return(new InputValue <ISiteSelector>(selector, valueAsStr.ToString())); }
//--------------------------------------------------------------------- protected IStandRankingMethod ReadRankingMethod() { //1. read which ranking method is chosen- eg. Random and MaxCohortAge //2. check for optional ranking requirements- eg. minimumAge and maximumAge //3. form rankingMethod and return it. InputVar <string> rankingName = new InputVar <string>("StandRanking"); ReadVar(rankingName); IStandRankingMethod rankingMethod; if (rankingName.Value.Actual == "Economic") { rankingMethod = new EconomicRank(ReadEconomicRankTable()); } else if (rankingName.Value.Actual == "MaxCohortAge") { rankingMethod = new MaxCohortAge(); } else if (rankingName.Value.Actual == "Random") { rankingMethod = new RandomRank(); } else if (rankingName.Value.Actual == "RegulateAges") { rankingMethod = new RegulateAgesRank(); } else if (rankingName.Value.Actual == "FireHazard") { rankingMethod = new FireRiskRank(ReadFireRiskTable()); } ////list of ranking methods which have not been implemented yet //else if ((rankingName.Value.Actual == "SpeciesBiomass") || // (rankingName.Value.Actual == "TotalBiomass")) { // throw new InputValueException(rankingName.Value.String, // rankingName.Value.String + " is not implemented yet"); //} else { string[] methodList = new string[] { "Stand ranking methods:", " Economic", " MaxCohortAge", " Random", " RegulateAges", " FireRisk" }; throw new InputValueException(rankingName.Value.String, rankingName.Value.String + " is not a valid stand ranking", new MultiLineText(methodList)); } // Read optional ranking requirements ushort? minAge = null; InputVar <ushort> minimumAge = new InputVar <ushort>("MinimumAge"); if (ReadOptionalVar(minimumAge)) { //get minAge minAge = minimumAge.Value.Actual; //add the minimumAge ranking requirement to this ranking method. rankingMethod.AddRequirement(new MinimumAge(minAge.Value)); } InputVar <ushort> maximumAge = new InputVar <ushort>("MaximumAge"); if (ReadOptionalVar(maximumAge)) { //get maxAge ushort maxAge = maximumAge.Value.Actual; //throw exception if maxAge < minAge if (minAge.HasValue && maxAge < minAge) { throw new InputValueException(maximumAge.Value.String, "{0} is < minimum age ({1})", maximumAge.Value.String, minimumAge.Value.String); } //add the maximumAge ranking requirement to this ranking method. rankingMethod.AddRequirement(new MaximumAge(maxAge)); } //stand adjacency variables and constraints InputVar <ushort> standAdjacency = new InputVar <ushort>("StandAdjacency"); InputVar <string> adjacencyType = new InputVar <string>("AdjacencyType"); InputVar <ushort> adjacencyNeighborSetAside = new InputVar <ushort>("AdjacencyNeighborSetAside"); //if stand-adjacency is defined, check flags if (ReadOptionalVar(standAdjacency)) { //get adjacency-type ushort adjacency = standAdjacency.Value.Actual; ReadVar(adjacencyType); if (adjacencyType.Value.String != "StandAge" && adjacencyType.Value.String != "MinimumTimeSinceLastHarvest") { string[] methodList = new string[] { "AdjacencyType methods:", " StandAge", " TimeSinceLastHarvested" }; throw new InputValueException(adjacencyType.Value.String, adjacencyType.Value.String + " is not a valid site selection method", new MultiLineText(methodList)); } string ad_type = adjacencyType.Value.String; //get set-aside var if defined ushort set_aside = 0; if (ReadOptionalVar(adjacencyNeighborSetAside)) { //Model.Core.UI.WriteLine("adjacencyNeighborSetAside = {0}", adjacencyNeighborSetAside.Value.Actual); set_aside = adjacencyNeighborSetAside.Value.Actual; } //add stand-adjacency to list of ranking requirements rankingMethod.AddRequirement(new StandAdjacency(adjacency, ad_type, set_aside)); } InputVar <ushort> spatialArrangement = new InputVar <ushort>("SpatialArrangement"); if (ReadOptionalVar(spatialArrangement)) { //get minimum age requirement ushort s_minAge = spatialArrangement.Value.Actual; //add ranking requirement for neighbor stands to be at least of minimum age (defined by s_minAge) rankingMethod.AddRequirement(new SpatialArrangement(s_minAge)); } InputVar <ushort> minimumTimeSinceLastHarvest = new InputVar <ushort>("MinimumTimeSinceLastHarvest"); if (ReadOptionalVar(minimumTimeSinceLastHarvest)) { //get minimum time requirement ushort min_time = minimumTimeSinceLastHarvest.Value.Actual; //add requirement for this stand to have not been harvested within the minimum //time ranking requirement specified (defined by min_time) rankingMethod.AddRequirement(new MinTimeSinceLastHarvest(min_time)); } return(rankingMethod); }
//--------------------------------------------------------------------- protected override IInputParameters Parse() { InputVar <string> landisData = new InputVar <string>("LandisData"); ReadVar(landisData); if (landisData.Value.Actual != PlugIn.PlugInName) { throw new InputValueException(landisData.Value.String, "The value is not \"{0}\"", PlugIn.PlugInName); } InputParameters parameters = new InputParameters(SpeciesDataset.Count); InputVar <int> timestep = new InputVar <int>("Timestep"); ReadVar(timestep); parameters.Timestep = timestep.Value; InputVar <int> outputTimestep = new InputVar <int>("OutputTimestep"); ReadVar(outputTimestep); parameters.OutputTimestep = outputTimestep.Value; // Template for filenames of reclass maps InputVar <string> mapFileNames = new InputVar <string>("MapFileNames"); ReadVar(mapFileNames); parameters.MapFileNames = mapFileNames.Value; InputVar <string> speciesName = new InputVar <string>("Species"); Dictionary <string, int> lineNumbers = new Dictionary <string, int>(); // Read list of Suitability Files InputVar <string> suitabilityFile = new InputVar <string>("SuitabilityFiles"); ReadVar(suitabilityFile); List <ISuitabilityParameters> suitabilityParameterList = new List <ISuitabilityParameters>(); SuitabilityFileParametersParser suitabilityParser = new SuitabilityFileParametersParser(); ISuitabilityParameters suitabilityParameters = Landis.Data.Load <ISuitabilityParameters>(suitabilityFile.Value, suitabilityParser); suitabilityParameterList.Add(suitabilityParameters); parameters.SuitabilityFiles.Add(suitabilityFile.Name); while (!AtEndOfInput) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(suitabilityFile, currentLine); CheckForRepeatedName(suitabilityFile.Value, "suitability file", lineNumbers); suitabilityParameters = Landis.Data.Load <ISuitabilityParameters>(suitabilityFile.Value, suitabilityParser); suitabilityParameterList.Add(suitabilityParameters); parameters.SuitabilityFiles.Add(suitabilityFile.Name); GetNextLine(); } parameters.SuitabilityParameters = suitabilityParameterList; CheckNoDataAfter(string.Format("the {0} parameter", "SuitabilityFiles")); return(parameters); //.GetComplete(); }
//--------------------------------------------------------------------- protected override Dictionary <int, IDynamicInputRecord[, ]> Parse() { //InputVar<string> landisData = new InputVar<string>("LandisData"); //ReadVar(landisData); //if (landisData.Value.Actual != FileName) // throw new InputValueException(landisData.Value.String, "The value is not \"{0}\"", PlugIn.ExtensionName); ReadLandisDataVar(); Dictionary <int, IDynamicInputRecord[, ]> allData = new Dictionary <int, IDynamicInputRecord[, ]>(); //--------------------------------------------------------------------- //Read in climate data: InputVar <int> year = new InputVar <int>("Time step for updating values"); InputVar <string> ecoregionName = new InputVar <string>("Ecoregion Name"); InputVar <string> speciesName = new InputVar <string>("Species Name"); InputVar <double> pest = new InputVar <double>("Probability of Establishment"); InputVar <int> anpp = new InputVar <int>("ANPP"); InputVar <int> bmax = new InputVar <int>("Maximum Biomass"); while (!AtEndOfInput) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(year, currentLine); int yr = year.Value.Actual; if (!allData.ContainsKey(yr)) { IDynamicInputRecord[,] inputTable = new IDynamicInputRecord[PlugIn.ModelCore.Species.Count, PlugIn.ModelCore.Ecoregions.Count]; allData.Add(yr, inputTable); PlugIn.ModelCore.UI.WriteLine(" Dynamic Input Parser: Add new year = {0}.", yr); } ReadValue(ecoregionName, currentLine); IEcoregion ecoregion = GetEcoregion(ecoregionName.Value); ReadValue(speciesName, currentLine); ISpecies species = GetSpecies(speciesName.Value); IDynamicInputRecord dynamicInputRecord = new DynamicInputRecord(); ReadValue(pest, currentLine); dynamicInputRecord.ProbEst = pest.Value; ReadValue(anpp, currentLine); dynamicInputRecord.ANPP_MAX_Spp = anpp.Value; ReadValue(bmax, currentLine); dynamicInputRecord.B_MAX_Spp = bmax.Value; allData[yr][species.Index, ecoregion.Index] = dynamicInputRecord; CheckNoDataAfter("the " + bmax.Name + " column", currentLine); GetNextLine(); } return(allData); }
//--------------------------------------------------------------------- new protected InputValue<ISiteSelector> ReadSiteSelector(StringReader reader, out int index) { TextReader.SkipWhitespace(reader); index = reader.Index; string name = TextReader.ReadWord(reader); if (name == "") throw new InputValueException(); // Missing value ISiteSelector selector; StringBuilder valueAsStr = new StringBuilder(name); // Site selection -- Complete stand if (name == SiteSelection.Complete) { selector = new CompleteStand(); } // Site selection -- Target size with partial or complete spread else if (name == SiteSelection.CompleteAndSpreading || name == SiteSelection.TargetAndSpreading) { InputVar<double> minTargetSize = new InputVar<double>("the minimum target harvest size"); ReadValue(minTargetSize, reader); InputVar<double> maxTargetSize = new InputVar<double>("the maximum target harvest size"); ReadValue(maxTargetSize, reader); //validate the target size for spreading algorithms StandSpreading.ValidateTargetSizes(minTargetSize.Value, maxTargetSize.Value); standSpreadMinTargetSize = minTargetSize.Value; standSpreadMaxTargetSize = maxTargetSize.Value; if (name == SiteSelection.TargetAndSpreading) { // Site selection -- partial spread selector = new PartialStandSpreading(minTargetSize.Value.Actual, maxTargetSize.Value.Actual); } else { // Site selection -- complete stand selector = new CompleteStandSpreading(minTargetSize.Value.Actual, maxTargetSize.Value.Actual); } valueAsStr.AppendFormat(" {0}", minTargetSize.Value.String); valueAsStr.AppendFormat(" {0}", maxTargetSize.Value.String); //validate the target size for spreading algorithms //StandSpreading.ValidateTargetSize(targetSize.Value); //standSpreadTargetSize = targetSize.Value; //if (name == SiteSelection.TargetAndSpreading) { // Site selection -- partial spread // selector = new PartialStandSpreading(targetSize.Value.Actual); //} //else { // Site selection -- complete stand // selector = new CompleteStandSpreading(targetSize.Value.Actual); //} //valueAsStr.AppendFormat(" {0}", targetSize.Value.String); } // Site selection -- Patch cutting else if (name == SiteSelection.Patch) { InputVar<Percentage> percentage = new InputVar<Percentage>("the site percentage for patch cutting"); ReadValue(percentage, reader); PatchCutting.ValidatePercentage(percentage.Value); InputVar<double> size = new InputVar<double>("the target patch size"); ReadValue(size, reader); PatchCutting.ValidateSize(size.Value); selector = new PatchCutting(percentage.Value.Actual, size.Value.Actual); valueAsStr.AppendFormat(" {0} {1}", percentage.Value.String, size.Value.String); } else { string[] methodList = new string[]{"Site selection methods:", " " + SiteSelection.Complete, " " + SiteSelection.CompleteAndSpreading, " " + SiteSelection.TargetAndSpreading, " " + SiteSelection.Patch}; throw new InputValueException(name, name + " is not a valid site selection method", new MultiLineText(methodList)); } return new InputValue<ISiteSelector>(selector, valueAsStr.ToString()); }
//--------------------------------------------------------------------- // Since this class derives from Base Harvest's parser, then the Parse // method below must return Base Harvest's interface to the parameters. // But the method uses Biomass Harvest's class for editable parameters, // so that the new BiomassMaps parameter can be read and validated. // The method returns an instance of Biomass Harvest's Parameters, so // the caller must cast the reference to Biomass Harvest's parameters // interface in order to access the new BiomassMaps parameter. protected override BaseHarvest.IInputParameters Parse() { RoundedRepeatIntervals.Clear(); ReadLandisDataVar(); Parameters parameters = new Parameters(); InputVar<int> timestep = new InputVar<int>("Timestep"); ReadVar(timestep); parameters.Timestep = timestep.Value; InputVar<string> mgmtAreaMap = new InputVar<string>("ManagementAreas"); ReadVar(mgmtAreaMap); parameters.ManagementAreaMap = mgmtAreaMap.Value; InputVar<string> standMap = new InputVar<string>("Stands"); ReadVar(standMap); parameters.StandMap = standMap.Value; ReadPrescriptions(parameters.Prescriptions, timestep.Value.Actual); ReadHarvestImplementations(parameters.ManagementAreas, parameters.Prescriptions); // Output file parameters InputVar<string> prescriptionMapNames = new InputVar<string>(Names.PrescriptionMaps); ReadVar(prescriptionMapNames); parameters.PrescriptionMapNames = prescriptionMapNames.Value; // TO DO: Probably should be required in the final release but made // it optional for now so that CBI doesn't have to update every // scenario in the short term. InputVar<string> biomassMapNames = new InputVar<string>("BiomassMaps"); if (ReadOptionalVar(biomassMapNames)) parameters.BiomassMapNames = biomassMapNames.Value; InputVar<string> eventLogFile = new InputVar<string>("EventLog"); ReadVar(eventLogFile); parameters.EventLog = eventLogFile.Value; InputVar<string> summaryLogFile = new InputVar<string>("SummaryLog"); ReadVar(summaryLogFile); parameters.SummaryLog = summaryLogFile.Value; CheckNoDataAfter("the " + summaryLogFile.Name + " parameter"); return parameters; }
//--------------------------------------------------------------------- /// <summary> /// Puts filename for BiomassMaps into the parameters /// </summary> /// <remarks> /// This overrides the base method in harvest-mgmt-lib /// </remarks> protected override void ReadBiomassMaps(InputParameters baseParameters) { InputVar<string> biomassMapNames = new InputVar<string>("BiomassMaps"); if (ReadOptionalVar(biomassMapNames)) { // Get the biomass harvest implementation of the InputParameters so we can set the biomassMaps property Parameters parameters = baseParameters as Parameters; parameters.BiomassMapNames = biomassMapNames.Value; } }
//--------------------------------------------------------------------- protected override IInputParameters Parse() { InputVar <string> landisData = new InputVar <string>("LandisData"); ReadVar(landisData); if (landisData.Value.Actual != PlugIn.ExtensionName) { throw new InputValueException(landisData.Value.String, "The value is not \"{0}\"", PlugIn.ExtensionName); } InputParameters parameters = new InputParameters(); InputVar <int> timestep = new InputVar <int>("Timestep"); ReadVar(timestep); parameters.Timestep = timestep.Value; //---------------------------------------------------------- // Read in Maps and Log file names. // - infection status (0=Susceptible;1=Infected;2=Diseased). - InputVar <string> statusMapNames = new InputVar <string>("MapNames"); ReadVar(statusMapNames); parameters.StatusMapNames = statusMapNames.Value; //check why this is different from others below // - mortality - InputVar <string> mortMapNames = new InputVar <string>("MORTMapNames"); try { ReadVar(mortMapNames); parameters.MortMapNames = mortMapNames.Value; } catch (LineReaderException errString) { if (!(errString.MultiLineMessage[1].Contains("Found the name \"EPDMapNames\" but expected \"MORTMapNames\""))) { throw errString; } } // - logfile - InputVar <string> logFile = new InputVar <string>("LogFile"); ReadVar(logFile); parameters.LogFileName = logFile.Value; //---------------------------------------------------------- // Last, read in Agent File names, // then parse the data in those files into agent parameters. InputVar <string> agentFileName = new InputVar <string>("EDAInputFiles"); ReadVar(agentFileName); List <IAgent> agentParameterList = new List <IAgent>(); AgentParameterParser agentParser = new AgentParameterParser(); IAgent agentParameters = Landis.Data.Load <IAgent>(agentFileName.Value, agentParser); agentParameterList.Add(agentParameters); while (!AtEndOfInput) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(agentFileName, currentLine); agentParameters = Landis.Data.Load <IAgent>(agentFileName.Value, agentParser); agentParameterList.Add(agentParameters); GetNextLine(); } foreach (IAgent activeAgent in agentParameterList) { if (agentParameters == null) { PlugIn.ModelCore.UI.WriteLine("PARSE: Agent Parameters NOT loading correctly."); } else { PlugIn.ModelCore.UI.WriteLine("Name of Agent = {0}", agentParameters.AgentName); } } parameters.ManyAgentParameters = agentParameterList; return(parameters); //.GetComplete(); }
//--------------------------------------------------------------------- /// <summary> /// Reads a list of species and their cohorts that should be removed. /// </summary> protected ICohortSelector ReadSpeciesAndCohorts(params string[] names) { List <string> namesThatFollow; if (names == null) { namesThatFollow = new List <string>(); } else { namesThatFollow = new List <string>(names); } cohortSelector = new MultiSpeciesCohortSelector(); SpeciesLineNumbers.Clear(); while (!AtEndOfInput && !namesThatFollow.Contains(CurrentName)) { StringReader currentLine = new StringReader(CurrentLine); // Species name ISpecies species = ReadSpecies(currentLine); // Cohort keyword, cohort age or cohort age range // keyword = (All, Youngest, AllExceptYoungest, Oldest, // AllExceptOldest, 1/{N}) TextReader.SkipWhitespace(currentLine); int indexOfDataAfterSpecies = currentLine.Index; string word = TextReader.ReadWord(currentLine); if (word == "") { throw NewParseException("No cohort keyword, age or age range after the species name"); } bool foundKeyword = false; if (keywordsEnabled) { if (word == "All") { cohortSelector[species] = SelectCohorts.All; foundKeyword = true; } else if (word == "Youngest") { cohortSelector[species] = SelectCohorts.Youngest; foundKeyword = true; } else if (word == "AllExceptYoungest") { cohortSelector[species] = SelectCohorts.AllExceptYoungest; foundKeyword = true; } else if (word == "Oldest") { cohortSelector[species] = SelectCohorts.Oldest; foundKeyword = true; } else if (word == "AllExceptOldest") { cohortSelector[species] = SelectCohorts.AllExceptOldest; foundKeyword = true; } else if (word.StartsWith("1/")) { InputVar <ushort> N = new InputVar <ushort>("1/N"); N.ReadValue(new StringReader(word.Substring(2))); if (N.Value.Actual == 0) { throw NewParseException("For \"1/N\", N must be > 0"); } cohortSelector[species] = new EveryNthCohort(N.Value.Actual).SelectCohorts; foundKeyword = true; } } if (foundKeyword) { CheckNoDataAfter("the keyword \"" + word + "\"", currentLine); } else { // Read one or more ages or age ranges List <ushort> ages = new List <ushort>(); List <AgeRange> ranges = new List <AgeRange>(); currentLine = new StringReader(CurrentLine.Substring(indexOfDataAfterSpecies)); InputVar <AgeRange> ageOrRange = new InputVar <AgeRange>("Age or Age Range"); while (currentLine.Peek() != -1) { ReadValue(ageOrRange, currentLine); ValidateAgeOrRange(ageOrRange.Value, ages, ranges); TextReader.SkipWhitespace(currentLine); } CreateCohortSelectionMethodFor(species, ages, ranges); } GetNextLine(); } if (SpeciesLineNumbers.Count == 0) { throw NewParseException("Expected a line starting with a species name"); } return(cohortSelector); }
//--------------------------------------------------------------------- protected override IParameters Parse() { ReadLandisDataVar(); EditableParameters parameters = new EditableParameters(SpeciesDataset.Count); InputVar <int> timestep = new InputVar <int>("Timestep"); ReadVar(timestep); parameters.Timestep = timestep.Value; // Table of reclass coefficients InputVar <string> speciesName = new InputVar <string>("Species"); InputVar <double> reclassCoeff = new InputVar <double>("Reclass Coefficient"); Dictionary <string, int> lineNumbers = new Dictionary <string, int>(); const string ReclassMaps = "ReclassMaps"; while (!AtEndOfInput && CurrentName != ReclassMaps) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(speciesName, currentLine); ISpecies species = GetSpecies(speciesName.Value); CheckForRepeatedName(speciesName.Value, "species", lineNumbers); ReadValue(reclassCoeff, currentLine); parameters.ReclassCoefficients[species.Index] = reclassCoeff.Value; CheckNoDataAfter(string.Format("the {0} column", reclassCoeff.Name), currentLine); GetNextLine(); } // Read definitions of reclass maps ReadName(ReclassMaps); InputVar <string> mapName = new InputVar <string>("Map Name"); InputVar <string> forestType = new InputVar <string>("Forest Type"); lineNumbers.Clear(); Dictionary <string, int> forestTypeLineNumbers = new Dictionary <string, int>(); const string MapFileNames = "MapFileNames"; const string nameDelimiter = "->"; // delimiter that separates map name and forest type IEditableMapDefinition mapDefn = null; while (!AtEndOfInput && CurrentName != MapFileNames) { StringReader currentLine = new StringReader(CurrentLine); // If the current line has the delimiter, then read the map // name. if (CurrentLine.Contains(nameDelimiter)) { ReadValue(mapName, currentLine); CheckForRepeatedName(mapName.Value, "map name", lineNumbers); mapDefn = new EditableMapDefinition(); mapDefn.Name = mapName.Value; parameters.ReclassMaps.Add(mapDefn); TextReader.SkipWhitespace(currentLine); string word = TextReader.ReadWord(currentLine); if (word != nameDelimiter) { throw NewParseException("Expected \"{0}\" after the map name {1}.", nameDelimiter, mapName.Value.String); } forestTypeLineNumbers.Clear(); } else { // If there is no name delimiter and we don't have the // name for the first map yet, then it's an error. if (mapDefn == null) { throw NewParseException("Expected a line with map name followed by \"{0}\"", nameDelimiter); } } ReadValue(forestType, currentLine); CheckForRepeatedName(forestType.Value, "forest type", forestTypeLineNumbers); IEditableForestType currentForestType = new EditableForestType(SpeciesDataset.Count); currentForestType.Name = forestType.Value; mapDefn.ForestTypes.Add(currentForestType); // Read species for forest types List <string> speciesNames = new List <string>(); TextReader.SkipWhitespace(currentLine); while (currentLine.Peek() != -1) { ReadValue(speciesName, currentLine); string name = speciesName.Value.Actual; bool negativeMultiplier = name.StartsWith("-"); if (negativeMultiplier) { name = name.Substring(1); if (name.Length == 0) { throw new InputValueException(speciesName.Value.String, "No species name after \"-\""); } } ISpecies species = GetSpecies(new InputValue <string>(name, speciesName.Value.String)); if (speciesNames.Contains(species.Name)) { throw NewParseException("The species {0} appears more than once.", species.Name); } speciesNames.Add(species.Name); currentForestType[species.Index] = negativeMultiplier ? -1 : 1; TextReader.SkipWhitespace(currentLine); } if (speciesNames.Count == 0) { throw NewParseException("At least one species is required."); } GetNextLine(); } // Template for filenames of reclass maps InputVar <string> mapFileNames = new InputVar <string>(MapFileNames); ReadVar(mapFileNames); parameters.MapFileNames = mapFileNames.Value; CheckNoDataAfter(string.Format("the {0} parameter", MapFileNames)); return(parameters.GetComplete()); }
//--------------------------------------------------------------------- protected override Dictionary <string, Parameter <string> > Parse() { try { Dictionary <string, Parameter <string> > parameters = new Dictionary <string, Parameter <string> >(StringComparer.InvariantCultureIgnoreCase); InputVar <string> landisData = new InputVar <string>("LandisData"); ReadVar(landisData); if (landisData.Value.Actual != this.KeyWord) { throw new InputValueException(landisData.Value.String, "Landis Keyword expected " + this.KeyWord + " but read \"{0}\"" + this.FileName, landisData.Value.Actual); } string line = new StringReader(CurrentLine).ReadLine().Trim(); while (line.Length == 0) { GetNextLine(); } List <string> ReadHeaderLabels = new List <string>(line.Split((char[])null, System.StringSplitOptions.RemoveEmptyEntries)); if (line.ToLower().Contains(KeyWord.ToLower()) == false) { throw new System.Exception("Expecting keyword " + KeyWord + " in headerline"); } if (ExpectedColumnHeaders != null) { ExpectedColumnHeaders.Add(KeyWord); foreach (string label in ReadHeaderLabels) { if (ListContains(ExpectedColumnHeaders, label) == false) { throw new PnetSpeciesParameterFileFormatException("Unrecognized column header " + label + " in " + FileName + "./nExpected headers are: " + string.Join(",", ExpectedColumnHeaders.ToArray())); } } } GetNextLine(); speciesLineNums.Clear(); while (!AtEndOfInput) { InputVar <string> RowLabel = new InputVar <string>("RowLabel"); StringReader s = new StringReader(CurrentLine); CheckHeaderCount(new StringReader(CurrentLine), ReadHeaderLabels.Count); for (int column = 0; column < ReadHeaderLabels.Count; column++) { Parameter <string> parameter = null; string parameterlabel = null; string valuekey = null; InputVar <string> var = new InputVar <string>(ReadHeaderLabels[column]); ReadValue(var, s); if (column == 0) { RowLabel = var; if (ExpectedRowLabels != null && ListContains(ExpectedRowLabels, RowLabel.Value) == false) { throw new PnetSpeciesParameterFileFormatException("Unknown parameter label [" + var.Value + "] in " + FileName + ".\nExpected labels are: [" + string.Join(" ,", ExpectedRowLabels.ToArray()) + "]."); } continue; } switch (transposed) { case true: parameterlabel = RowLabel.Value; valuekey = ReadHeaderLabels[column]; break; case false: parameterlabel = ReadHeaderLabels[column]; valuekey = RowLabel.Value; break; } if (parameters.TryGetValue(parameterlabel, out parameter) == false) { parameter = new Parameter <string>(parameterlabel); parameters.Add(parameterlabel, parameter); } if (parameter.ContainsKey(valuekey)) { throw new System.Exception("Duplicate parameter label [" + var.Value + "] for parameter " + parameterlabel); } parameter.Add(valuekey, var.Value); } GetNextLine(); } return(parameters); } catch (System.Exception e) { if (e is PnetSpeciesParameterFileFormatException) { throw e; } else { throw new System.Exception("Unexpected file format (dir,file) (" + System.IO.Directory.GetCurrentDirectory() + "," + this.FileName + ")" + " " + e.Message + "\n\nNOTE header line is mandatory"); } } }
//--------------------------------------------------------------------- private void ParseTable(IPercentageTable table, string tableName, string nextTableName) { ReadName(tableName); PlugIn.ModelCore.UI.WriteLine(" Reading {0}.", tableName); InputVar <string> disturbance = new InputVar <string>("Disturbance"); InputVar <Percentage> woodPercentage = new InputVar <Percentage>("Woody"); InputVar <Percentage> foliarPercentage = new InputVar <Percentage>("Non-Woody"); string lastColumn = "the " + foliarPercentage.Name + " column"; const string defaultName = "(default)"; bool defaultFound = false; lineNums.Clear(); while (!AtEndOfInput && CurrentName != nextTableName) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(disturbance, currentLine); int lineNum; if (lineNums.TryGetValue(disturbance.Value.Actual, out lineNum)) { throw new InputValueException(disturbance.Value.Actual, "The value \"{0}\" was previously used on line {1}", disturbance.Value.Actual, lineNum); } lineNums[disturbance.Value.String] = LineNumber; PoolPercentages percentages; if (disturbance.Value.Actual == defaultName) { defaultFound = true; percentages = table.Default; } else { ExtensionType disturbanceType = new ExtensionType("disturbance:" + disturbance.Value.Actual); //if(disturbance.Value.Actual == "Fire" || disturbance.Value.Actual == "fire") // throw new InputValueException(disturbance.Value.Actual, // "\"{0}\" is not an allowable disturbance type, line {1}", // disturbance.Value.Actual, // lineNum); //percentages = table[disturbanceType]; table[disturbanceType] = new PoolPercentages(); percentages = table[disturbanceType]; PlugIn.ModelCore.UI.WriteLine(" Adding {0}...", disturbanceType); } ReadValue(woodPercentage, currentLine); percentages.Wood = woodPercentage.Value; ReadValue(foliarPercentage, currentLine); percentages.Foliar = foliarPercentage.Value; CheckNoDataAfter(lastColumn, currentLine); GetNextLine(); } if (!defaultFound) { throw NewParseException("Missing the \"{0}\" row in the percentage table", defaultName); } }
//--------------------------------------------------------------------- protected override IAgent Parse() { //PlugIn.ModelCore.Log.WriteLine("Parsing 1; sppCnt={0}", Model.Species.Count); Agent agentParameters = new Agent(PlugIn.ModelCore.Species.Count, PlugIn.ModelCore.Ecoregions.Count, (int)DisturbanceType.Null); //The last disturb Type is Null InputVar <string> agentName = new InputVar <string>("BDAAgentName"); ReadVar(agentName); agentParameters.AgentName = agentName.Value; InputVar <int> bdpc = new InputVar <int>("BDPCalibrator"); ReadVar(bdpc); agentParameters.BDPCalibrator = bdpc.Value; InputVar <SRDmode> srd = new InputVar <SRDmode>("SRDMode"); ReadVar(srd); agentParameters.SRDmode = srd.Value; InputVar <int> tSLE = new InputVar <int>("TimeSinceLastEpidemic"); ReadVar(tSLE); agentParameters.TimeSinceLastEpidemic = tSLE.Value; InputVar <TemporalType> tt = new InputVar <TemporalType>("TemporalType"); ReadVar(tt); agentParameters.TempType = tt.Value; InputVar <RandomFunction> rf = new InputVar <RandomFunction>("RandomFunction"); ReadVar(rf); agentParameters.RandFunc = rf.Value; InputVar <double> rp1 = new InputVar <double>("RandomParameter1"); ReadVar(rp1); agentParameters.RandomParameter1 = rp1.Value; InputVar <double> rp2 = new InputVar <double>("RandomParameter2"); ReadVar(rp2); agentParameters.RandomParameter2 = rp2.Value; InputVar <int> minROS = new InputVar <int>("MinROS"); ReadVar(minROS); agentParameters.MinROS = minROS.Value; InputVar <int> maxROS = new InputVar <int>("MaxROS"); ReadVar(maxROS); agentParameters.MaxROS = maxROS.Value; InputVar <bool> d = new InputVar <bool>("Dispersal"); ReadVar(d); agentParameters.Dispersal = d.Value; InputVar <int> dr = new InputVar <int>("DispersalRate"); ReadVar(dr); agentParameters.DispersalRate = dr.Value; InputVar <double> et = new InputVar <double>("EpidemicThresh"); ReadVar(et); agentParameters.EpidemicThresh = et.Value; InputVar <int> ien = new InputVar <int>("InitialEpicenterNum"); ReadVar(ien); agentParameters.EpicenterNum = ien.Value; InputVar <double> oec = new InputVar <double>("OutbreakEpicenterCoeff"); ReadVar(oec); agentParameters.OutbreakEpicenterCoeff = oec.Value; InputVar <bool> se = new InputVar <bool>("SeedEpicenter"); ReadVar(se); agentParameters.SeedEpicenter = se.Value; InputVar <double> sec = new InputVar <double>("SeedEpicenterCoeff"); ReadVar(sec); agentParameters.SeedEpicenterCoeff = sec.Value; InputVar <DispersalTemplate> dispt = new InputVar <DispersalTemplate>("DispersalTemplate"); ReadVar(dispt); agentParameters.DispersalTemp = dispt.Value; InputVar <bool> nf = new InputVar <bool>("NeighborFlag"); ReadVar(nf); agentParameters.NeighborFlag = nf.Value; InputVar <NeighborSpeed> nspeed = new InputVar <NeighborSpeed>("NeighborSpeedUp"); ReadVar(nspeed); agentParameters.NeighborSpeedUp = nspeed.Value; InputVar <int> nr = new InputVar <int>("NeighborRadius"); ReadVar(nr); agentParameters.NeighborRadius = nr.Value; InputVar <NeighborShape> ns = new InputVar <NeighborShape>("NeighborShape"); ReadVar(ns); agentParameters.ShapeOfNeighbor = ns.Value; InputVar <double> nw = new InputVar <double>("NeighborWeight"); ReadVar(nw); agentParameters.NeighborWeight = nw.Value; //Added for budworm-BDA InputVar <double> class2_SV = new InputVar <double>("Class2_SV"); ReadVar(class2_SV); agentParameters.Class2_SV = class2_SV.Value; InputVar <double> class3_SV = new InputVar <double>("Class3_SV"); ReadVar(class3_SV); agentParameters.Class3_SV = class3_SV.Value; InputVar <int> bfAgeCutoff = new InputVar <int>("BFAgeCutoff"); ReadVar(bfAgeCutoff); agentParameters.BFAgeCutoff = bfAgeCutoff.Value; //--------- Read In Ecoreigon Table --------------------------------------- PlugIn.ModelCore.Log.WriteLine("Begin parsing ECOREGION table."); InputVar <string> ecoName = new InputVar <string>("Ecoregion Name"); InputVar <double> ecoModifier = new InputVar <double>("Ecoregion Modifier"); Dictionary <string, int> lineNumbers = new Dictionary <string, int>(); const string DistParms = "DisturbanceModifiers"; while (!AtEndOfInput && CurrentName != DistParms) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(ecoName, currentLine); IEcoregion ecoregion = EcoregionsDataset[ecoName.Value.Actual]; if (ecoregion == null) { throw new InputValueException(ecoName.Value.String, "{0} is not an ecoregion name.", ecoName.Value.String); } int lineNumber; if (lineNumbers.TryGetValue(ecoregion.Name, out lineNumber)) { throw new InputValueException(ecoName.Value.String, "The ecoregion {0} was previously used on line {1}", ecoName.Value.String, lineNumber); } else { lineNumbers[ecoregion.Name] = LineNumber; } IEcoParameters ecoParms = new EcoParameters(); agentParameters.EcoParameters[ecoregion.Index] = ecoParms; ReadValue(ecoModifier, currentLine); ecoParms.EcoModifier = ecoModifier.Value; CheckNoDataAfter("the " + ecoModifier.Name + " column", currentLine); GetNextLine(); } //--------- Read In Disturbance Modifier Table ------------------------------- PlugIn.ModelCore.Log.WriteLine("Begin parsing DISTURBANCE table."); ReadName(DistParms); InputVar <DisturbanceType> distType = new InputVar <DisturbanceType>("Disturbance Type"); InputVar <int> duration = new InputVar <int>("Duration"); InputVar <double> distModifier = new InputVar <double>("Disturbance Modifier"); lineNumbers = new Dictionary <string, int>(); const string SppParms = "BDASpeciesParameters"; while (!AtEndOfInput && CurrentName != SppParms) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(distType, currentLine); int dt = (int)distType.Value.Actual; IDistParameters distParms = new DistParameters(); agentParameters.DistParameters[dt] = distParms; ReadValue(duration, currentLine); distParms.Duration = duration.Value; ReadValue(distModifier, currentLine); distParms.DistModifier = distModifier.Value; CheckNoDataAfter("the " + distModifier.Name + " column", currentLine); GetNextLine(); } //--------- Read In Species Table --------------------------------------- PlugIn.ModelCore.Log.WriteLine("Begin parsing SPECIES table."); ReadName(SppParms); //const string FireCurves = "FireCurveTable"; InputVar <string> sppName = new InputVar <string>("Species"); InputVar <int> minorHostAge = new InputVar <int>("Minor Host Age"); InputVar <double> minorHostSRD = new InputVar <double>("Minor Host SRDProb"); InputVar <int> secondaryHostAge = new InputVar <int>("Second Host Age"); InputVar <double> secondaryHostSRD = new InputVar <double>("Secondary Host SRDProb"); InputVar <int> primaryHostAge = new InputVar <int>("Primary Host Age"); InputVar <double> primaryHostSRD = new InputVar <double>("Primary Host SRDProb"); InputVar <int> resistantHostAge = new InputVar <int>("Resistant Host Age"); InputVar <double> resistantHostVuln = new InputVar <double>("Resistant Host VulnProb"); InputVar <int> tolerantHostAge = new InputVar <int>("Tolerant Host Age"); InputVar <double> tolerantHostVuln = new InputVar <double>("Tolerant Host VulnProb"); InputVar <int> vulnerableHostAge = new InputVar <int>("Vulnerable Host Age"); InputVar <double> vulnerableHostVuln = new InputVar <double>("Vulnerable Host VulnProb"); InputVar <bool> cfsConifer = new InputVar <bool>("CFS Conifer type: yes/no"); const string NegSpp = "IgnoredSpecies"; while ((!AtEndOfInput) && (CurrentName != NegSpp)) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(sppName, currentLine); ISpecies species = SpeciesDataset[sppName.Value.Actual]; if (species == null) { throw new InputValueException(sppName.Value.String, "{0} is not a species name.", sppName.Value.String); } int lineNumber; if (lineNumbers.TryGetValue(species.Name, out lineNumber)) { throw new InputValueException(sppName.Value.String, "The species {0} was previously used on line {1}", sppName.Value.String, lineNumber); } else { lineNumbers[species.Name] = LineNumber; } ISppParameters sppParms = new SppParameters(); agentParameters.SppParameters[species.Index] = sppParms; ReadValue(minorHostAge, currentLine); sppParms.MinorHostAge = minorHostAge.Value; ReadValue(minorHostSRD, currentLine); sppParms.MinorHostSRD = minorHostSRD.Value; ReadValue(secondaryHostAge, currentLine); sppParms.SecondaryHostAge = secondaryHostAge.Value; ReadValue(secondaryHostSRD, currentLine); sppParms.SecondaryHostSRD = secondaryHostSRD.Value; ReadValue(primaryHostAge, currentLine); sppParms.PrimaryHostAge = primaryHostAge.Value; ReadValue(primaryHostSRD, currentLine); sppParms.PrimaryHostSRD = primaryHostSRD.Value; ReadValue(resistantHostAge, currentLine); sppParms.ResistantHostAge = resistantHostAge.Value; ReadValue(resistantHostVuln, currentLine); sppParms.ResistantHostVuln = resistantHostVuln.Value; ReadValue(tolerantHostAge, currentLine); sppParms.TolerantHostAge = tolerantHostAge.Value; ReadValue(tolerantHostVuln, currentLine); sppParms.TolerantHostVuln = tolerantHostVuln.Value; ReadValue(vulnerableHostAge, currentLine); sppParms.VulnerableHostAge = vulnerableHostAge.Value; ReadValue(vulnerableHostVuln, currentLine); sppParms.VulnerableHostVuln = vulnerableHostVuln.Value; ReadValue(cfsConifer, currentLine); sppParms.CFSConifer = cfsConifer.Value; CheckNoDataAfter("the " + cfsConifer.Name + " column", currentLine); GetNextLine(); } //--------- Read In Ignored Species List --------------------------------------- List <ISpecies> negSppList = new List <ISpecies>(); if (!AtEndOfInput) { ReadName(NegSpp); InputVar <string> negSppName = new InputVar <string>("Ignored Spp Name"); while (!AtEndOfInput) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(negSppName, currentLine); ISpecies species = SpeciesDataset[negSppName.Value.Actual]; if (species == null) { throw new InputValueException(negSppName.Value.String, "{0} is not a species name.", negSppName.Value.String); } int lineNumber; if (lineNumbers.TryGetValue(species.Name, out lineNumber)) { PlugIn.ModelCore.Log.WriteLine("WARNING: The species {0} was previously used on line {1}. Being listed in the IgnoredSpecies list will override any settings in the Host table.", negSppName.Value.String, lineNumber); } else { lineNumbers[species.Name] = LineNumber; } negSppList.Add(species); GetNextLine(); } } agentParameters.NegSppList = negSppList; return(agentParameters); //.GetComplete(); }
//--------------------------------------------------------------------- protected override IInputParameters Parse() { ReadLandisDataVar(); //InputVar<string> landisData = new InputVar<string>("LandisData"); //ReadVar(landisData); //if (landisData.Value.Actual != PlugIn.ExtensionName) // throw new InputValueException(landisData.Value.String, "The value is not \"{0}\"", PlugIn.ExtensionName); InputParameters parameters = new InputParameters(); InputVar <int> timestep = new InputVar <int>("Timestep"); ReadVar(timestep); parameters.Timestep = timestep.Value; InputVar <SeedingAlgorithms> seedAlg = new InputVar <SeedingAlgorithms>("SeedingAlgorithm"); ReadVar(seedAlg); parameters.SeedAlgorithm = seedAlg.Value; //--------------------------------------------------------------------------------- InputVar <string> initCommunities = new InputVar <string>("InitialCommunities"); ReadVar(initCommunities); parameters.InitialCommunities = initCommunities.Value; InputVar <string> communitiesMap = new InputVar <string>("InitialCommunitiesMap"); ReadVar(communitiesMap); parameters.InitialCommunitiesMap = communitiesMap.Value; //--------------------------------------------------------------------------------- InputVar <string> dynInputFile = new InputVar <string>("DynamicInputFile"); ReadVar(dynInputFile); parameters.DynamicInputFile = dynInputFile.Value; //ReadName("EstablishProbabilities"); //// Read ecoregion names as column headings //InputVar<string> ecoregionName = new InputVar<string>("Ecoregion"); //if (AtEndOfInput) // throw new InputVariableException(ecoregionName, // "Expected a line with the names of 1 or more active ecoregions."); //List<IEcoregion> ecoregions = new List<IEcoregion>(); //StringReader currentLine = new StringReader(CurrentLine); //TextReader.SkipWhitespace(currentLine); //while (currentLine.Peek() != -1) //{ // ReadValue(ecoregionName, currentLine); // IEcoregion ecoregion = PlugIn.ModelCore.Ecoregions[ecoregionName.Value.Actual]; // if (ecoregion == null) // throw new InputValueException(ecoregionName.Value.String, // "{0} is not an ecoregion name.", // ecoregionName.Value.String); // if (! ecoregion.Active) // throw new InputValueException(ecoregionName.Value.String, // "{0} is not an active ecoregion.", // ecoregionName.Value.String); // if (ecoregions.Contains(ecoregion)) // throw new InputValueException(ecoregionName.Value.String, // "The ecoregion {0} appears more than once.", // ecoregionName.Value.String); // ecoregions.Add(ecoregion); // TextReader.SkipWhitespace(currentLine); //} //GetNextLine(); //string lastEcoregion = ecoregions[ecoregions.Count-1].Name; //// Read species and their probabilities //InputVar<string> speciesName = new InputVar<string>("Species"); //Dictionary <string, int> speciesLineNumbers = new Dictionary<string, int>(); //while (! AtEndOfInput) { // currentLine = new StringReader(CurrentLine); // ReadValue(speciesName, currentLine); // //Species.ISpecies species = Model.Core.Species[speciesName.Value.Actual]; // ISpecies species = PlugIn.ModelCore.Species[speciesName.Value.Actual]; // if (species == null) // throw new InputValueException(speciesName.Value.String, // "{0} is not a species name.", // speciesName.Value.String); // int lineNumber; // if (speciesLineNumbers.TryGetValue(species.Name, out lineNumber)) // throw new InputValueException(speciesName.Value.String, // "The species {0} was previously used on line {1}", // speciesName.Value.String, lineNumber); // else // speciesLineNumbers[species.Name] = LineNumber; // foreach (IEcoregion ecoregion in ecoregions) { // InputVar<double> probability = new InputVar<double>("Ecoregion " + ecoregion.Name); // ReadValue(probability, currentLine); // if (probability.Value.Actual < 0.0 || probability.Value.Actual > 1.0) // throw new InputValueException(probability.Value.String, // "{0} is not between 0.0 and 1.0", // probability.Value.String); // parameters.SetProbability(ecoregion, species, probability.Value.Actual); // } // CheckNoDataAfter("the Ecoregion " + lastEcoregion + " column", // currentLine); // GetNextLine(); //} return(parameters); //.GetComplete(); }
public void Init() { inputVar = new InputVar <int>("Effective Seed Dist", EffectiveSeedDist.ReadMethod); }
//--------------------------------------------------------------------- protected override ExtensionInfo Parse() { ReadLandisDataVar(); EditableExtensionInfo extension = new EditableExtensionInfo(); InputVar <string> name = new InputVar <string>("Name"); ReadVar(name); extension.Name = name.Value; InputVar <string> version = new InputVar <string>("Version"); if (ReadOptionalVar(version)) { extension.Version = version.Value; } // If the extension is not being installed, but rather just an // entry for it is being added to the dataset, then we need its // type, assembly and class info. if (!App.InstallingExtension) { InputVar <string> type = new InputVar <string>("Type"); ReadVar(type); extension.Type = type.Value; InputVar <string> assemblyPath = new InputVar <string>("Assembly"); ReadVar(assemblyPath); extension.AssemblyName = assemblyPath.Value; InputVar <string> className = new InputVar <string>("Class"); ReadVar(className); extension.ClassName = className.Value; } InputVar <string> description = new InputVar <string>("Description"); if (ReadOptionalVar(description)) { extension.Description = description.Value; } InputVar <string> userGuide = new InputVar <string>("UserGuide"); if (ReadOptionalVar(userGuide)) { extension.UserGuidePath = userGuide.Value; } // CoreVersion is optional. We don't use ReadOptionalVar because // we want to be able to check for any data after the last known // parameter. But that last known parameter could Name, Version, // Class, Description, or UserGuide. And we want the error // message to list any optional variables that weren't found. So // instead, we use ReadVar if there's a non-blank line left in // the input. if (!AtEndOfInput) { InputVar <string> coreVersion = new InputVar <string>("CoreVersion"); ReadVar(coreVersion); extension.CoreVersion = coreVersion.Value; CheckNoDataAfter(string.Format("the {0} parameter", coreVersion.Name)); } return(extension.GetComplete()); }
public void Init() { strVar = new InputVar<string>("StringVar"); }
//--------------------------------------------------------------------- protected override IParameters Parse() { ReadLandisDataVar(); Parameters parameters = new Parameters(ecoregionDataset, speciesDataset); InputVar <int> timestep = new InputVar <int>(Names.Timestep); ReadVar(timestep); parameters.Timestep = timestep.Value; InputVar <SeedingAlgorithms> seedAlg = new InputVar <SeedingAlgorithms>(Names.SeedingAlgorithm); ReadVar(seedAlg); parameters.SeedAlgorithm = seedAlg.Value; InputVar <bool> calimode = new InputVar <bool>(Names.CalibrateMode); if (ReadOptionalVar(calimode)) { parameters.CalibrateMode = calimode.Value; } else { parameters.CalibrateMode = false; } InputVar <double> spinMort = new InputVar <double>("SpinupMortalityFraction"); if (ReadOptionalVar(spinMort)) { parameters.SpinupMortalityFraction = spinMort.Value; } else { parameters.SpinupMortalityFraction = 0.0; } ParseBiomassParameters(parameters, Names.AgeOnlyDisturbanceParms, Names.ClimateChange); // AgeOnlyDisturbances:BiomassParameters (optional) string lastParameter = null; if (!AtEndOfInput && CurrentName == Names.AgeOnlyDisturbanceParms) { InputVar <string> ageOnlyDisturbanceParms = new InputVar <string>(Names.AgeOnlyDisturbanceParms); ReadVar(ageOnlyDisturbanceParms); parameters.AgeOnlyDisturbanceParms = ageOnlyDisturbanceParms.Value; lastParameter = "the " + Names.AgeOnlyDisturbanceParms + " parameter"; } // Climate Change table (optional) if (ReadOptionalName(Names.ClimateChange)) { ReadClimateChangeTable(parameters.ClimateChangeUpdates); } else if (lastParameter != null) { CheckNoDataAfter(lastParameter); } return(parameters); //.GetComplete(); }
//---------------------------------------------------------------------- // Need to include a copy of this method because it modifies an // instance member "rankingMethod" in the original version. Bad // design; the ranking method should be passed as a parameter. protected void ReadForestTypeTable(IStandRankingMethod rankingMethod) { int optionalStatements = 0; //check if this is the ForestTypeTable if (CurrentName == Names.ForestTypeTable) { ReadName(Names.ForestTypeTable); //fresh input variables for table InputVar<string> inclusionRule = new InputVar<string>("Inclusion Rule"); InputVar<AgeRange> age_range = new InputVar<AgeRange>("Age Range", ParseAgeOrRange); InputVar<string> percentOfCells = new InputVar<string>("PercentOfCells"); //as a string so it can include keyword 'highest' InputVar<string> speciesName = new InputVar<string>("Species"); //list for each rule- each line is a separate rule List<InclusionRule> rule_list = new List<InclusionRule>(); //keep reading until no longer in the ForestTypeTable while (! AtEndOfInput && !namesThatFollowForestType.Contains(CurrentName)) { StringReader currentLine = new StringReader(CurrentLine); // inclusionRule column ReadValue(inclusionRule, currentLine); //verify inclusion rule = 'optional', 'required', or 'forbidden' if (inclusionRule.Value.Actual != "Optional" && inclusionRule.Value.Actual != "Required" && inclusionRule.Value.Actual != "Forbidden") { string[] ic_list = new string[]{"Valid Inclusion Rules:", " Optional", " Required", " Forbidden"}; throw new InputValueException(CurrentName, CurrentName + " is not a valid inclusion rule.", new MultiLineText(ic_list)); } if (inclusionRule.Value.Actual == "Optional") optionalStatements++; TextReader.SkipWhitespace(currentLine); ReadValue(age_range, currentLine); //percentage column TextReader.SkipWhitespace(currentLine); ReadValue(percentOfCells, currentLine); //PlugIn.ModelCore.UI.WriteLine("percentOfCells = {0}", percentOfCells.Value.String); //cannot validate until parsing is done. will do this in the inclusionRule constructor //a list in case there are multiple species on this line List<string> species_list = new List<string>(); //add each species to this rule's species list TextReader.SkipWhitespace(currentLine); while (currentLine.Peek() != -1) { //species column (build list) ReadValue(speciesName, currentLine); string name = speciesName.Value.String; ISpecies species = GetSpecies(new InputValue<string>(name, speciesName.Value.String)); if (species_list.Contains(species.Name)) throw NewParseException("The species {0} appears more than once.", species.Name); species_list.Add(species.Name); //species_list.Add(species.Value.String); TextReader.SkipWhitespace(currentLine); } //add this new inclusion rule (by parameters) to the requirement rule_list.Add(new InclusionRule(inclusionRule.Value.String, age_range.Value.Actual, percentOfCells.Value.String, species_list)); GetNextLine(); } //create a new requirement with this list of rules IRequirement inclusionRequirement = new InclusionRequirement(rule_list); //add this requirement to the ranking method rankingMethod.AddRequirement(inclusionRequirement); } if(optionalStatements > 0 && optionalStatements < 2) throw new InputValueException(CurrentName, "If there are optional statements, there must be more than one", "ForestTypeTable"); }
//--------------------------------------------------------------------- protected override IInputParameters Parse() { ReadLandisDataVar(); int numLitterTypes = 4; int numFunctionalTypes = 25; InputParameters parameters = new InputParameters(speciesDataset, numLitterTypes, numFunctionalTypes); InputVar <int> timestep = new InputVar <int>("Timestep"); ReadVar(timestep); parameters.Timestep = timestep.Value; InputVar <SeedingAlgorithms> seedAlg = new InputVar <SeedingAlgorithms>("SeedingAlgorithm"); ReadVar(seedAlg); parameters.SeedAlgorithm = seedAlg.Value; //--------------------------------------------------------------------------------- InputVar <string> initCommunities = new InputVar <string>("InitialCommunities"); ReadVar(initCommunities); parameters.InitialCommunities = initCommunities.Value; InputVar <string> communitiesMap = new InputVar <string>("InitialCommunitiesMap"); ReadVar(communitiesMap); parameters.InitialCommunitiesMap = communitiesMap.Value; InputVar <string> climateConfigFile = new InputVar <string>("ClimateConfigFile"); ReadVar(climateConfigFile); parameters.ClimateConfigFile = climateConfigFile.Value; InputVar <string> ageOnlyDisturbanceParms = new InputVar <string>("AgeOnlyDisturbances:BiomassParameters"); ReadVar(ageOnlyDisturbanceParms); parameters.AgeOnlyDisturbanceParms = ageOnlyDisturbanceParms.Value; InputVar <string> soilDepthMapName = new InputVar <string>("SoilDepthMapName"); ReadVar(soilDepthMapName); parameters.SoilDepthMapName = soilDepthMapName.Value; InputVar <string> soilDrainMapName = new InputVar <string>("SoilDrainMapName"); ReadVar(soilDrainMapName); parameters.SoilDrainMapName = soilDrainMapName.Value; InputVar <string> soilBaseFlowMapName = new InputVar <string>("SoilBaseFlowMapName"); ReadVar(soilBaseFlowMapName); parameters.SoilBaseFlowMapName = soilBaseFlowMapName.Value; InputVar <string> soilStormFlowMapName = new InputVar <string>("SoilStormFlowMapName"); ReadVar(soilStormFlowMapName); parameters.SoilStormFlowMapName = soilStormFlowMapName.Value; InputVar <string> soilFCMapName = new InputVar <string>("SoilFieldCapacityMapName"); ReadVar(soilFCMapName); parameters.SoilFieldCapacityMapName = soilFCMapName.Value; InputVar <string> soilWPMapName = new InputVar <string>("SoilWiltingPointMapName"); ReadVar(soilWPMapName); parameters.SoilWiltingPointMapName = soilWPMapName.Value; InputVar <string> soilSandMapName = new InputVar <string>("SoilPercentSandMapName"); ReadVar(soilSandMapName); parameters.SoilPercentSandMapName = soilSandMapName.Value; InputVar <string> soilClayMapName = new InputVar <string>("SoilPercentClayMapName"); ReadVar(soilClayMapName); parameters.SoilPercentClayMapName = soilClayMapName.Value; InputVar <string> som1CsurfMapName = new InputVar <string>("InitialSOM1CsurfMapName"); ReadVar(som1CsurfMapName); parameters.InitialSOM1CSurfaceMapName = som1CsurfMapName.Value; InputVar <string> som1NsurfMapName = new InputVar <string>("InitialSOM1NsurfMapName"); ReadVar(som1NsurfMapName); parameters.InitialSOM1NSurfaceMapName = som1NsurfMapName.Value; InputVar <string> som1CsoilMapName = new InputVar <string>("InitialSOM1CsoilMapName"); ReadVar(som1CsoilMapName); parameters.InitialSOM1CSoilMapName = som1CsoilMapName.Value; InputVar <string> som1NsoilMapName = new InputVar <string>("InitialSOM1NsoilMapName"); ReadVar(som1NsoilMapName); parameters.InitialSOM1NSoilMapName = som1NsoilMapName.Value; InputVar <string> som2CMapName = new InputVar <string>("InitialSOM2CMapName"); ReadVar(som2CMapName); parameters.InitialSOM2CMapName = som2CMapName.Value; InputVar <string> som2NMapName = new InputVar <string>("InitialSOM2NMapName"); ReadVar(som2NMapName); parameters.InitialSOM2NMapName = som2NMapName.Value; InputVar <string> som3CMapName = new InputVar <string>("InitialSOM3CMapName"); ReadVar(som3CMapName); parameters.InitialSOM3CMapName = som3CMapName.Value; InputVar <string> som3NMapName = new InputVar <string>("InitialSOM3NMapName"); ReadVar(som3NMapName); parameters.InitialSOM3NMapName = som3NMapName.Value; InputVar <string> deadSurfMapName = new InputVar <string>("InitialDeadWoodSurfaceMapName"); ReadVar(deadSurfMapName); parameters.InitialDeadSurfaceMapName = deadSurfMapName.Value; InputVar <string> deadSoilMapName = new InputVar <string>("InitialDeadWoodSoilMapName"); ReadVar(deadSoilMapName); parameters.InitialDeadSoilMapName = deadSoilMapName.Value; InputVar <bool> calimode = new InputVar <bool>("CalibrateMode"); if (ReadOptionalVar(calimode)) { parameters.CalibrateMode = calimode.Value; } else { parameters.CalibrateMode = false; } //InputVar<double> spinMort = new InputVar<double>("SpinupMortalityFraction"); //if (ReadOptionalVar(spinMort)) // parameters.SpinupMortalityFraction = spinMort.Value; //else // parameters.SpinupMortalityFraction = 0.0; InputVar <string> wt = new InputVar <string>("WaterDecayFunction"); ReadVar(wt); parameters.WType = WParse(wt.Value); InputVar <double> pea = new InputVar <double>("ProbabilityEstablishAdjust"); ReadVar(pea); parameters.ProbEstablishAdjustment = pea.Value; InputVar <double> iMN = new InputVar <double>("InitialMineralN"); ReadVar(iMN); parameters.SetInitMineralN(iMN.Value); InputVar <double> ans = new InputVar <double>("AtmosphericNSlope"); ReadVar(ans); parameters.SetAtmosNslope(ans.Value); InputVar <double> ani = new InputVar <double>("AtmosphericNIntercept"); ReadVar(ani); parameters.SetAtmosNintercept(ani.Value); InputVar <double> lat = new InputVar <double>("Latitude"); ReadVar(lat); parameters.SetLatitude(lat.Value); InputVar <double> denits = new InputVar <double>("DenitrificationRate"); ReadVar(denits); parameters.SetDenitrif(denits.Value); InputVar <double> drsoms = new InputVar <double>("DecayRateSurf"); ReadVar(drsoms); parameters.SetDecayRateSurf(drsoms.Value); InputVar <double> drsom1 = new InputVar <double>("DecayRateSOM1"); ReadVar(drsom1); parameters.SetDecayRateSOM1(drsom1.Value); InputVar <double> drsom2 = new InputVar <double>("DecayRateSOM2"); ReadVar(drsom2); parameters.SetDecayRateSOM2(drsom2.Value); InputVar <double> drsom3 = new InputVar <double>("DecayRateSOM3"); ReadVar(drsom3); parameters.SetDecayRateSOM3(drsom3.Value); //InputVar<string> soilCarbonMaps = new InputVar<string>("SoilCarbonMapNames"); //if (ReadOptionalVar(soilCarbonMaps)) //{ // PlugIn.SoilCarbonMapNames = soilCarbonMaps.Value; // InputVar<int> soilCarbonMapFreq = new InputVar<int>("SoilCarbonMapFrequency"); // ReadVar(soilCarbonMapFreq); // PlugIn.SoilCarbonMapFrequency = soilCarbonMapFreq.Value; //} //InputVar<string> soilNitrogenMaps = new InputVar<string>("SoilNitrogenMapNames"); //if (ReadOptionalVar(soilNitrogenMaps)) //{ // PlugIn.SoilNitrogenMapNames = soilNitrogenMaps.Value; // InputVar<int> soilNitrogenMapFreq = new InputVar<int>("SoilNitrogenMapFrequency"); // ReadVar(soilNitrogenMapFreq); // PlugIn.SoilNitrogenMapFrequency = soilNitrogenMapFreq.Value; //} InputVar <string> anppMaps = new InputVar <string>("ANPPMapNames"); if (ReadOptionalVar(anppMaps)) { PlugIn.ANPPMapNames = anppMaps.Value; InputVar <int> anppMapFreq = new InputVar <int>("ANPPMapFrequency"); ReadVar(anppMapFreq); PlugIn.ANPPMapFrequency = anppMapFreq.Value; } InputVar <string> aneeMaps = new InputVar <string>("ANEEMapNames"); if (ReadOptionalVar(aneeMaps)) { PlugIn.ANEEMapNames = aneeMaps.Value; InputVar <int> aneeMapFreq = new InputVar <int>("ANEEMapFrequency"); ReadVar(aneeMapFreq); PlugIn.ANEEMapFrequency = aneeMapFreq.Value; } InputVar <string> soilCarbonMaps = new InputVar <string>("SoilCarbonMapNames"); if (ReadOptionalVar(soilCarbonMaps)) { PlugIn.SoilCarbonMapNames = soilCarbonMaps.Value; InputVar <int> soilCarbonMapFreq = new InputVar <int>("SoilCarbonMapFrequency"); ReadVar(soilCarbonMapFreq); PlugIn.SoilCarbonMapFrequency = soilCarbonMapFreq.Value; } InputVar <string> soilNitrogenMaps = new InputVar <string>("SoilNitrogenMapNames"); if (ReadOptionalVar(soilNitrogenMaps)) { PlugIn.SoilNitrogenMapNames = soilNitrogenMaps.Value; InputVar <int> soilNitrogenMapFreq = new InputVar <int>("SoilNitrogenMapFrequency"); ReadVar(soilNitrogenMapFreq); PlugIn.SoilNitrogenMapFrequency = soilNitrogenMapFreq.Value; } InputVar <string> totalCMaps = new InputVar <string>("TotalCMapNames"); if (ReadOptionalVar(totalCMaps)) { PlugIn.TotalCMapNames = totalCMaps.Value; InputVar <int> totalCMapFreq = new InputVar <int>("TotalCMapFrequency"); ReadVar(totalCMapFreq); PlugIn.TotalCMapFrequency = totalCMapFreq.Value; } //InputVar<string> LAIMaps = new InputVar<string>("LAIMapNames"); //if (ReadOptionalVar(LAIMaps)) //{ // PlugIn.LAIMapNames = LAIMaps.Value; // InputVar<int> LAIMapFreq = new InputVar<int>("LAICMapFrequency"); // ReadVar(LAIMapFreq); // PlugIn.LAICMapFrequency = LAIMapFreq.Value; //} //InputVar<string> ShadeClassMaps = new InputVar<string>("ShadeClassMapNames"); //if (ReadOptionalVar(ShadeClassMaps)) //{ // PlugIn.TotalCMapNames = ShadeClassMaps.Value; // InputVar<int> ShadeClassMapFreq = new InputVar<int>("ShadeClassMapFrequency"); // ReadVar(ShadeClassMapFreq); // PlugIn.ShadeClassMapFrequency = ShadeClassMapFreq.Value; //} //-------------------------- // MinRelativeBiomass table ReadName("MaximumLAI"); //"AvailableLightBiomass"); InputVar <byte> shadeClassVar = new InputVar <byte>("Shade Class"); InputVar <double> maxLAI = new InputVar <double>("Maximum LAI"); //List<IEcoregion> ecoregions = ReadEcoregions(); //string lastEcoregion = ecoregions[ecoregions.Count-1].Name; for (byte shadeClass = 1; shadeClass <= 5; shadeClass++) { if (AtEndOfInput) { throw NewParseException("Expected a line with available light class {0}", shadeClass); } StringReader currentLine = new StringReader(CurrentLine); ReadValue(shadeClassVar, currentLine); if (shadeClassVar.Value.Actual != shadeClass) { throw new InputValueException(shadeClassVar.Value.String, "Expected the available light class {0}", shadeClass); } ReadValue(maxLAI, currentLine); parameters.SetMaximumShadeLAI(shadeClass, maxLAI.Value); //foreach (IEcoregion ecoregion in ecoregions) //{ // InputVar<Percentage> MinRelativeBiomass = new InputVar<Percentage>("Ecoregion " + ecoregion.Name); //} CheckNoDataAfter("the " + maxLAI + " column", currentLine); GetNextLine(); } //---------------------------------------------------------- // Read table of sufficient light probabilities. // Available light classes are in increasing order. ReadName("LightEstablishmentTable"); InputVar <byte> sc = new InputVar <byte>("Available Light Class"); InputVar <double> pl0 = new InputVar <double>("Probability of Germination - Light Level 0"); InputVar <double> pl1 = new InputVar <double>("Probability of Germination - Light Level 1"); InputVar <double> pl2 = new InputVar <double>("Probability of Germination - Light Level 2"); InputVar <double> pl3 = new InputVar <double>("Probability of Germination - Light Level 3"); InputVar <double> pl4 = new InputVar <double>("Probability of Germination - Light Level 4"); InputVar <double> pl5 = new InputVar <double>("Probability of Germination - Light Level 5"); int previousNumber = 0; while (!AtEndOfInput && CurrentName != Names.SpeciesParameters && previousNumber != 6) { StringReader currentLine = new StringReader(CurrentLine); ISufficientLight suffLight = new SufficientLight(); ReadValue(sc, currentLine); suffLight.ShadeClass = sc.Value; // Check that the current shade class is 1 more than // the previous number (numbers are must be in increasing order). if (sc.Value.Actual != (byte)previousNumber + 1) { throw new InputValueException(sc.Value.String, "Expected the severity number {0}", previousNumber + 1); } previousNumber = (int)sc.Value.Actual; ReadValue(pl0, currentLine); suffLight.ProbabilityLight0 = pl0.Value; ReadValue(pl1, currentLine); suffLight.ProbabilityLight1 = pl1.Value; ReadValue(pl2, currentLine); suffLight.ProbabilityLight2 = pl2.Value; ReadValue(pl3, currentLine); suffLight.ProbabilityLight3 = pl3.Value; ReadValue(pl4, currentLine); suffLight.ProbabilityLight4 = pl4.Value; ReadValue(pl5, currentLine); suffLight.ProbabilityLight5 = pl5.Value; parameters.LightClassProbabilities.Add(suffLight); CheckNoDataAfter("the " + pl5.Name + " column", currentLine); GetNextLine(); } if (parameters.LightClassProbabilities.Count == 0) { throw NewParseException("No sufficient light probabilities defined."); } if (previousNumber != 5) { throw NewParseException("Expected shade class {0}", previousNumber + 1); } //------------------------- // Species Parameters table ReadName("SpeciesParameters"); speciesLineNums.Clear(); // If parser re-used (i.e., for testing purposes) InputVar <int> ft = new InputVar <int>("Functional Type"); InputVar <bool> nt = new InputVar <bool>("Nitrogen Fixer"); InputVar <int> gddmn = new InputVar <int>("Growing Degree Day Minimum"); InputVar <int> gddmx = new InputVar <int>("Growing Degree Day Maximum"); InputVar <int> mjt = new InputVar <int>("Minimum January Temperature"); InputVar <double> maxd = new InputVar <double>("Maximum Allowable Drought"); InputVar <double> leafLongevity = new InputVar <double>("Leaf Longevity"); InputVar <bool> epicorm = new InputVar <bool>("Epicormic: Y/N"); InputVar <double> leafLignin = new InputVar <double>("Leaf Percent Lignin"); InputVar <double> wLignin = new InputVar <double>("Wood Percent Lignin"); InputVar <double> crLignin = new InputVar <double>("Coarse Root Percent Lignin"); InputVar <double> frLignin = new InputVar <double>("Fine Root Percent Lignin"); InputVar <double> leafCN = new InputVar <double>("Leaf CN Ratio"); InputVar <double> woodCN = new InputVar <double>("Wood CN Ratio"); InputVar <double> cRootCN = new InputVar <double>("Coarse Root CN Ratio"); InputVar <double> foliarCN = new InputVar <double>("Foliage CN Ratio"); InputVar <double> fRootCN = new InputVar <double>("Fine Root CN Ratio"); InputVar <int> maxANPP = new InputVar <int>("Maximum ANPP"); InputVar <int> maxBiomass = new InputVar <int>("Maximum Aboveground Biomass"); string lastColumn = "the " + maxBiomass.Name + " column"; while (!AtEndOfInput && CurrentName != Names.FunctionalGroupParameters) { StringReader currentLine = new StringReader(CurrentLine); ISpecies species = ReadSpecies(currentLine); ReadValue(ft, currentLine); parameters.SetFunctionalType(species, ft.Value); ReadValue(nt, currentLine); parameters.NFixer[species] = nt.Value; ReadValue(gddmn, currentLine); parameters.SetGDDmin(species, gddmn.Value); ReadValue(gddmx, currentLine); parameters.SetGDDmax(species, gddmx.Value); ReadValue(mjt, currentLine); parameters.SetMinJanTemp(species, mjt.Value); ReadValue(maxd, currentLine); parameters.SetMaxDrought(species, maxd.Value); ReadValue(leafLongevity, currentLine); parameters.SetLeafLongevity(species, leafLongevity.Value); ReadValue(epicorm, currentLine); parameters.Epicormic[species] = epicorm.Value; ReadValue(leafLignin, currentLine); parameters.SetLeafLignin(species, leafLignin.Value); ReadValue(frLignin, currentLine); parameters.SetFineRootLignin(species, frLignin.Value); ReadValue(wLignin, currentLine); parameters.SetWoodLignin(species, wLignin.Value); ReadValue(crLignin, currentLine); parameters.SetCoarseRootLignin(species, crLignin.Value); ReadValue(leafCN, currentLine); parameters.SetLeafCN(species, leafCN.Value); ReadValue(fRootCN, currentLine); parameters.SetFineRootCN(species, fRootCN.Value); ReadValue(woodCN, currentLine); parameters.SetWoodCN(species, woodCN.Value); ReadValue(cRootCN, currentLine); parameters.SetCoarseRootCN(species, cRootCN.Value); ReadValue(foliarCN, currentLine); parameters.SetFoliageLitterCN(species, foliarCN.Value); ReadValue(maxANPP, currentLine); parameters.SetMaxANPP(species, maxANPP.Value); ReadValue(maxBiomass, currentLine); parameters.SetMaxBiomass(species, maxBiomass.Value); CheckNoDataAfter(lastColumn, currentLine); GetNextLine(); } //--------- Read In Functional Group Table ------------------------------- PlugIn.ModelCore.UI.WriteLine(" Begin parsing FUNCTIONAL GROUP table."); ReadName("FunctionalGroupParameters"); //string InitialEcoregionParameters = "InitialEcoregionParameters"; InputVar <string> ftname = new InputVar <string>("Name"); InputVar <int> ftindex = new InputVar <int>("Index (< 25)"); InputVar <double> tempcurve1 = new InputVar <double>("TempCurve(1)"); InputVar <double> tempcurve2 = new InputVar <double>("TempCurve(2)"); InputVar <double> tempcurve3 = new InputVar <double>("TempCurve(3)"); InputVar <double> tempcurve4 = new InputVar <double>("TempCurve(4)"); InputVar <double> fcfleaf = new InputVar <double>("FCFRAC: Leaf"); InputVar <double> btolai = new InputVar <double>("BTOLAI"); InputVar <double> klai = new InputVar <double>("KLAI"); InputVar <double> maxlai = new InputVar <double>("MAXLAI"); InputVar <double> mwm = new InputVar <double>("Monthly Wood Mortality"); InputVar <double> wdr = new InputVar <double>("Wood Decay Rate"); InputVar <double> mortCurveShapeParm = new InputVar <double>("Mortality Curve Shape Parameter"); InputVar <int> leafNeedleDrop = new InputVar <int>("Leaf or Needle Drop Month"); InputVar <double> ppr2 = new InputVar <double>("MoistureCurve2"); InputVar <double> ppr3 = new InputVar <double>("MoistureCurve3"); InputVar <double> coarseRootFraction = new InputVar <double>("CRootFrac"); InputVar <double> fineRootFraction = new InputVar <double>("FRootFrac"); while (!AtEndOfInput && CurrentName != Names.FireReductionParameters) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(ftname, currentLine); ReadValue(ftindex, currentLine); int ln = (int)ftindex.Value.Actual; if (ln >= numFunctionalTypes) { throw new InputValueException(ftindex.Value.String, "The index: {0} exceeds the allowable number of functional groups, {1}", ftindex.Value.String, numFunctionalTypes - 1); } //IEditableFunctionalType funcTParms = new EditableFunctionalType(); FunctionalType funcTParms = new FunctionalType(); parameters.FunctionalTypes[ln] = funcTParms; ReadValue(tempcurve1, currentLine); funcTParms.TempCurve1 = tempcurve1.Value; ReadValue(tempcurve2, currentLine); funcTParms.TempCurve2 = tempcurve2.Value; ReadValue(tempcurve3, currentLine); funcTParms.TempCurve3 = tempcurve3.Value; ReadValue(tempcurve4, currentLine); funcTParms.TempCurve4 = tempcurve4.Value; ReadValue(fcfleaf, currentLine); funcTParms.FCFRACleaf = fcfleaf.Value; ReadValue(btolai, currentLine); funcTParms.BTOLAI = btolai.Value; ReadValue(klai, currentLine); funcTParms.KLAI = klai.Value; ReadValue(maxlai, currentLine); funcTParms.MAXLAI = maxlai.Value; ReadValue(ppr2, currentLine); funcTParms.MoistureCurve2 = ppr2.Value; ReadValue(ppr3, currentLine); funcTParms.MoistureCurve3 = ppr3.Value; ReadValue(wdr, currentLine); funcTParms.WoodDecayRate = wdr.Value; ReadValue(mwm, currentLine); funcTParms.MonthlyWoodMortality = mwm.Value; ReadValue(mortCurveShapeParm, currentLine); funcTParms.MortCurveShape = mortCurveShapeParm.Value; ReadValue(leafNeedleDrop, currentLine); funcTParms.LeafNeedleDrop = leafNeedleDrop.Value; ReadValue(coarseRootFraction, currentLine); funcTParms.CoarseRootFraction = coarseRootFraction.Value; ReadValue(fineRootFraction, currentLine); funcTParms.FineRootFraction = fineRootFraction.Value; //PlugIn.ModelCore.UI.WriteLine("PPRPTS2={0}.", parameters.FunctionalTypeTable[ln].PPRPTS2); CheckNoDataAfter("the " + fineRootFraction.Name + " column", currentLine); GetNextLine(); } //--------- Read In FIRST Ecoregion Table --------------------------- //PlugIn.ModelCore.UI.WriteLine(" Begin reading INITIAL ECOREGION parameters."); //ReadName(InitialEcoregionParameters); //InputVar<string> ecoregionName = new InputVar<string>("Ecoregion"); //InputVar<double> iS1surfC = new InputVar<double>("Initial SOM1 surface C"); //InputVar<double> iS1surfN = new InputVar<double>("Initial SOM1 surface N"); //InputVar<double> iS1soilC = new InputVar<double>("Initial SOM1 soil C"); //InputVar<double> iS1soilN = new InputVar<double>("Initial SOM1 soil N"); //InputVar<double> iS2C = new InputVar<double>("Initial SOM2 (intermediate turnover) C"); //InputVar<double> iS2N = new InputVar<double>("Initial SOM2 (intermediate turnover) N"); //InputVar<double> iS3C = new InputVar<double>("Initial SOM3 (slow turnover) C"); //InputVar<double> iS3N = new InputVar<double>("Initial SOM3 (slow turnover) N"); //Dictionary <string, int> lineNumbers2 = new Dictionary<string, int>(); //while (! AtEndOfInput && CurrentName != Names.FireReductionParameters){ //Names.EcoregionParameters ) { // StringReader currentLine = new StringReader(CurrentLine); // ReadValue(ecoregionName, currentLine); // IEcoregion ecoregion = GetEcoregion(ecoregionName.Value, // lineNumbers2); //ReadValue(iS1surfC, currentLine); //parameters.SetInitSOM1surfC(ecoregion, iS1surfC.Value); //ReadValue(iS1surfN, currentLine); //parameters.SetInitSOM1surfN(ecoregion, iS1surfN.Value); //ReadValue(iS1soilC, currentLine); //parameters.SetInitSOM1soilC(ecoregion, iS1soilC.Value); //ReadValue(iS1soilN, currentLine); //parameters.SetInitSOM1soilN(ecoregion, iS1soilN.Value); //ReadValue(iS2C, currentLine); //parameters.SetInitSOM2C(ecoregion, iS2C.Value); //ReadValue(iS2N, currentLine); //parameters.SetInitSOM2N(ecoregion, iS2N.Value); //ReadValue(iS3C, currentLine); //parameters.SetInitSOM3C(ecoregion, iS3C.Value); //ReadValue(iS3N, currentLine); //parameters.SetInitSOM3N(ecoregion, iS3N.Value); // CheckNoDataAfter("the " + ecoregionName.Name + " column", currentLine); // GetNextLine(); //} //--------- Read In SECOND Ecoregion Table --------------------------- // First, read table of additional parameters for ecoregions //PlugIn.ModelCore.UI.WriteLine(" Begin reading FIXED ECOREGION parameters."); //ReadName(Names.EcoregionParameters); //InputVar<double> pclay = new InputVar<double>("Percent Clay"); //InputVar<double> psand = new InputVar<double>("Percent Sand"); //InputVar<int> sd = new InputVar<int>("Soil Depth"); //InputVar<double> fc = new InputVar<double>("Field Capacity"); //InputVar<double> wp = new InputVar<double>("Wilting Point"); //InputVar<double> sff = new InputVar<double>("Storm Flow Fraction"); //InputVar<double> bff = new InputVar<double>("Base Flow Fraction"); //InputVar<double> drain = new InputVar<double>("Drain Fraction"); //InputVar<double> lat = new InputVar<double>("Latitude"); //InputVar<double> denits = new InputVar<double>("Denitrification"); //Dictionary<string, int> lineNumbers = new Dictionary<string, int>(); //while (! AtEndOfInput && CurrentName != Names.FireReductionParameters ) { // StringReader currentLine = new StringReader(CurrentLine); // ReadValue(ecoregionName, currentLine); // IEcoregion ecoregion = GetEcoregion(ecoregionName.Value, // lineNumbers); // //ReadValue(sd, currentLine); // //parameters.SetSoilDepth(ecoregion, sd.Value); // ReadValue(pclay, currentLine); // parameters.SetPercentClay(ecoregion, pclay.Value); //ReadValue(psand, currentLine); //parameters.SetPercentSand(ecoregion, psand.Value); //ReadValue(fc, currentLine); //parameters.SetFieldCapacity(ecoregion, fc.Value); //ReadValue(wp, currentLine); //parameters.SetWiltingPoint(ecoregion, wp.Value); //ReadValue(sff, currentLine); //parameters.SetStormFlowFraction(ecoregion, sff.Value); //ReadValue(bff, currentLine); //parameters.SetBaseFlowFraction(ecoregion, bff.Value); //ReadValue(drain, currentLine); //parameters.SetDrain(ecoregion, drain.Value); // CheckNoDataAfter("the " + pclay.Name + " column", currentLine); // GetNextLine(); //} //--------- Read In Fire Reductions Table --------------------------- PlugIn.ModelCore.UI.WriteLine(" Begin reading FIRE REDUCTION parameters."); ReadName(Names.FireReductionParameters); InputVar <int> frindex = new InputVar <int>("Fire Severity Index MUST = 1-5"); InputVar <double> wred = new InputVar <double>("Wood Reduction"); InputVar <double> lred = new InputVar <double>("Litter Reduction"); while (!AtEndOfInput && CurrentName != Names.HarvestReductionParameters && CurrentName != Names.AgeOnlyDisturbanceParms) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(frindex, currentLine); int ln = (int)frindex.Value.Actual; if (ln < 1 || ln > 5) { throw new InputValueException(ftindex.Value.String, "The fire severity index: {0} must be 1-5,", frindex.Value.String); } FireReductions inputFireReduction = new FireReductions(); // ignoring severity = zero parameters.FireReductionsTable[ln] = inputFireReduction; ReadValue(wred, currentLine); inputFireReduction.WoodReduction = wred.Value; ReadValue(lred, currentLine); inputFireReduction.LitterReduction = lred.Value; CheckNoDataAfter("the " + lred.Name + " column", currentLine); GetNextLine(); } //--------- Read In Harvest Reductions Table --------------------------- InputVar <string> hreds = new InputVar <string>("HarvestReductions"); ReadOptionalName(Names.HarvestReductionParameters); { PlugIn.ModelCore.UI.WriteLine(" Begin reading HARVEST REDUCTION parameters."); InputVar <string> prescriptionName = new InputVar <string>("Prescription"); InputVar <double> wred_pr = new InputVar <double>("Wood Reduction"); InputVar <double> lred_pr = new InputVar <double>("Litter Reduction"); List <string> prescriptionNames = new List <string>(); while (!AtEndOfInput && CurrentName != Names.AgeOnlyDisturbanceParms) { HarvestReductions harvReduction = new HarvestReductions(); parameters.HarvestReductionsTable.Add(harvReduction); StringReader currentLine = new StringReader(CurrentLine); ReadValue(prescriptionName, currentLine); harvReduction.PrescriptionName = prescriptionName.Value; ReadValue(wred_pr, currentLine); harvReduction.WoodReduction = wred.Value; ReadValue(lred_pr, currentLine); harvReduction.LitterReduction = lred.Value; GetNextLine(); } } return(parameters); }
//--------------------------------------------------------------------- protected override IInputParameters Parse() { InputVar <string> landisData = new InputVar <string>("LandisData"); ReadVar(landisData); if (landisData.Value.Actual != PlugIn.ExtensionName) { throw new InputValueException(landisData.Value.String, "The value is not \"{0}\"", PlugIn.ExtensionName); } InputParameters parameters = new InputParameters(); InputVar <int> timestep = new InputVar <int>("Timestep"); ReadVar(timestep); parameters.Timestep = timestep.Value; InputVar <string> varName = new InputVar <string>("VariableName"); ReadVar(varName); parameters.VarName = varName.Value; InputVar <double> minDroughtYears = new InputVar <double>("MinDroughtVar"); ReadVar(minDroughtYears); parameters.MinDroughtYears = minDroughtYears.Value; InputVar <double> maxDroughtYears = new InputVar <double>("MaxDroughtVar"); ReadVar(maxDroughtYears); parameters.MaxDroughtYears = maxDroughtYears.Value; InputVar <string> backTransform = new InputVar <string>("BackTransformation"); ReadVar(backTransform); parameters.BackTransform = backTransform.Value; InputVar <string> intCorrect = new InputVar <string>("InterceptCorrection"); ReadVar(intCorrect); parameters.IntCorrect = intCorrect.Value; //------------------------- // SpeciesParameters table ReadName("SpeciesParameters"); speciesLineNums.Clear(); // If parser re-used (i.e., for testing purposes) InputVar <double> drought_Y = new InputVar <double>("Drought Y"); InputVar <double> drought_YSE = new InputVar <double>("Drought YSE"); InputVar <double> drought_B = new InputVar <double>("Drought B"); InputVar <double> drought_BSE = new InputVar <double>("Drought BSE"); InputVar <double> drought_Sens = new InputVar <double>("Drought Sens"); while (!AtEndOfInput && CurrentName != Names.MapName) { StringReader currentLine = new StringReader(CurrentLine); ISpecies species = ReadSpecies(currentLine); ReadValue(drought_Y, currentLine); parameters.SetDrought_Y(species, drought_Y.Value); ReadValue(drought_YSE, currentLine); parameters.SetDrought_YSE(species, drought_YSE.Value); ReadValue(drought_B, currentLine); parameters.SetDrought_B(species, drought_B.Value); ReadValue(drought_BSE, currentLine); parameters.SetDrought_BSE(species, drought_BSE.Value); ReadValue(drought_Sens, currentLine); parameters.SetDrought_Sens(species, drought_Sens.Value); CheckNoDataAfter(drought_Sens.Name, currentLine); GetNextLine(); } InputVar <string> mapNames = new InputVar <string>("MapName"); ReadVar(mapNames); parameters.MapNamesTemplate = mapNames.Value; InputVar <string> logFile = new InputVar <string>("LogFile"); ReadVar(logFile); parameters.LogFileName = logFile.Value; return(parameters); }
//--------------------------------------------------------------------- protected override IInputParameters Parse() { ReadLandisDataVar(); InputParameters parameters = new InputParameters(); InputVar <int> timestep = new InputVar <int>(Names.Timestep); ReadVar(timestep); parameters.Timestep = timestep.Value; InputVar <SeedingAlgorithms> seedAlg = new InputVar <SeedingAlgorithms>(Names.SeedingAlgorithm); ReadVar(seedAlg); parameters.SeedAlgorithm = seedAlg.Value; //--------------------------------------------------------------------------------- InputVar <string> initCommunities = new InputVar <string>("InitialCommunities"); ReadVar(initCommunities); parameters.InitialCommunities = initCommunities.Value; InputVar <string> communitiesMap = new InputVar <string>("InitialCommunitiesMap"); ReadVar(communitiesMap); parameters.InitialCommunitiesMap = communitiesMap.Value; InputVar <string> climateConfigFile = new InputVar <string>(Names.ClimateConfigFile); if (ReadOptionalVar(climateConfigFile)) { parameters.ClimateConfigFile = climateConfigFile.Value; } else { parameters.ClimateConfigFile = null; } //--------------------------------------------------------------------------------- InputVar <bool> calimode = new InputVar <bool>(Names.CalibrateMode); if (ReadOptionalVar(calimode)) { parameters.CalibrateMode = calimode.Value; } else { parameters.CalibrateMode = false; } InputVar <double> spinMort = new InputVar <double>("SpinupMortalityFraction"); if (ReadOptionalVar(spinMort)) { parameters.SpinupMortalityFraction = spinMort.Value; } else { parameters.SpinupMortalityFraction = 0.0; } //-------------------------- // MinRelativeBiomass table ReadName("MinRelativeBiomass"); const string SufficientLight = "SufficientLight"; List <IEcoregion> ecoregions = ReadEcoregions(); string lastEcoregion = ecoregions[ecoregions.Count - 1].Name; InputVar <byte> shadeClassVar = new InputVar <byte>("Shade Class"); for (byte shadeClass = 1; shadeClass <= 5; shadeClass++) { if (AtEndOfInput) { throw NewParseException("Expected a line with shade class {0}", shadeClass); } StringReader currentLine = new StringReader(CurrentLine); ReadValue(shadeClassVar, currentLine); if (shadeClassVar.Value.Actual != shadeClass) { throw new InputValueException(shadeClassVar.Value.String, "Expected the shade class {0}", shadeClass); } foreach (IEcoregion ecoregion in ecoregions) { InputVar <Percentage> MinRelativeBiomass = new InputVar <Percentage>("Ecoregion " + ecoregion.Name); ReadValue(MinRelativeBiomass, currentLine); parameters.SetMinRelativeBiomass(shadeClass, ecoregion, MinRelativeBiomass.Value); } CheckNoDataAfter("the Ecoregion " + lastEcoregion + " column", currentLine); GetNextLine(); } //---------------------------------------------------------- // Read table of sufficient light probabilities. // Shade classes are in increasing order. ReadName(SufficientLight); const string SpeciesParameters = "SpeciesParameters"; InputVar <byte> sc = new InputVar <byte>("Shade Class"); InputVar <double> pl0 = new InputVar <double>("Probability of Germination - Light Level 0"); InputVar <double> pl1 = new InputVar <double>("Probability of Germination - Light Level 1"); InputVar <double> pl2 = new InputVar <double>("Probability of Germination - Light Level 2"); InputVar <double> pl3 = new InputVar <double>("Probability of Germination - Light Level 3"); InputVar <double> pl4 = new InputVar <double>("Probability of Germination - Light Level 4"); InputVar <double> pl5 = new InputVar <double>("Probability of Germination - Light Level 5"); int previousNumber = 0; while (!AtEndOfInput && CurrentName != SpeciesParameters && previousNumber != 6) { StringReader currentLine = new StringReader(CurrentLine); ISufficientLight suffLight = new SufficientLight(); parameters.LightClassProbabilities.Add(suffLight); ReadValue(sc, currentLine); suffLight.ShadeClass = sc.Value; // Check that the current shade class is 1 more than // the previous number (numbers are must be in increasing order). if (sc.Value.Actual != (byte)previousNumber + 1) { throw new InputValueException(sc.Value.String, "Expected the severity number {0}", previousNumber + 1); } previousNumber = (int)sc.Value.Actual; ReadValue(pl0, currentLine); suffLight.ProbabilityLight0 = pl0.Value; ReadValue(pl1, currentLine); suffLight.ProbabilityLight1 = pl1.Value; ReadValue(pl2, currentLine); suffLight.ProbabilityLight2 = pl2.Value; ReadValue(pl3, currentLine); suffLight.ProbabilityLight3 = pl3.Value; ReadValue(pl4, currentLine); suffLight.ProbabilityLight4 = pl4.Value; ReadValue(pl5, currentLine); suffLight.ProbabilityLight5 = pl5.Value; CheckNoDataAfter("the " + pl5.Name + " column", currentLine); GetNextLine(); } if (parameters.LightClassProbabilities.Count == 0) { throw NewParseException("No sufficient light probabilities defined."); } if (previousNumber != 5) { throw NewParseException("Expected shade class {0}", previousNumber + 1); } //------------------------- // SpeciesParameters table ReadName("SpeciesParameters"); const string EcoregionParameters = "EcoregionParameters"; speciesLineNums.Clear(); // If parser re-used (i.e., for testing purposes) InputVar <double> leafLongevity = new InputVar <double>("Leaf Longevity"); InputVar <double> woodyDecayRate = new InputVar <double>("Woody Decay Rate"); InputVar <double> mortCurveShapeParm = new InputVar <double>("Mortality Curve Shape Parameter"); InputVar <double> growthCurveShapeParm = new InputVar <double>("Mortality Curve Shape Parameter"); InputVar <double> leafLignin = new InputVar <double>("Leaf Percent Lignin"); InputVar <double> maxlai = new InputVar <double>("Maximum LAI"); InputVar <double> lec = new InputVar <double>("Light extinction coefficient"); InputVar <double> pctBio = new InputVar <double>("Pct Biomass Max LAI"); //string lastColumn = "the " + mortCurveShapeParm.Name + " column"; while (!AtEndOfInput && CurrentName != EcoregionParameters) { StringReader currentLine = new StringReader(CurrentLine); ISpecies species = ReadSpecies(currentLine); ReadValue(leafLongevity, currentLine); parameters.SetLeafLongevity(species, leafLongevity.Value); ReadValue(woodyDecayRate, currentLine); parameters.SetWoodyDecayRate(species, woodyDecayRate.Value); ReadValue(mortCurveShapeParm, currentLine); parameters.SetMortCurveShapeParm(species, mortCurveShapeParm.Value); ReadValue(growthCurveShapeParm, currentLine); parameters.SetGrowthCurveShapeParm(species, growthCurveShapeParm.Value); ReadValue(leafLignin, currentLine); parameters.SetLeafLignin(species, leafLignin.Value); CheckNoDataAfter(leafLignin.Name, currentLine); GetNextLine(); } ReadName("EcoregionParameters"); InputVar <string> ecoregionName = new InputVar <string>("Ecoregion Name"); InputVar <int> aet = new InputVar <int>("Actual Evapotranspiration"); Dictionary <string, int> lineNumbers = new Dictionary <string, int>(); string lastColumn = "the " + aet.Name + " column"; while (!AtEndOfInput && CurrentName != Names.DynamicInputFile) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(ecoregionName, currentLine); IEcoregion ecoregion = GetEcoregion(ecoregionName.Value, lineNumbers); ReadValue(aet, currentLine); parameters.SetAET(ecoregion, aet.Value); CheckNoDataAfter(lastColumn, currentLine); GetNextLine(); } InputVar <string> dynInputFile = new InputVar <string>(Names.DynamicInputFile); ReadVar(dynInputFile); parameters.DynamicInputFile = dynInputFile.Value; //--------- Read In Fire Reductions Table --------------------------- PlugIn.ModelCore.UI.WriteLine(" Begin reading FIRE REDUCTION parameters."); ReadName(Names.FireReductionParameters); InputVar <int> frindex = new InputVar <int>("Fire Severity Index MUST = 1-5"); InputVar <double> wred = new InputVar <double>("Coarse Litter Reduction"); InputVar <double> lred = new InputVar <double>("Fine Litter Reduction"); //InputVar<double> som_red = new InputVar<double>("SOM Reduction"); while (!AtEndOfInput && CurrentName != Names.HarvestReductionParameters) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(frindex, currentLine); int ln = (int)frindex.Value.Actual; if (ln < 1 || ln > 5) { throw new InputValueException(frindex.Value.String, "The fire severity index: {0} must be 1-5,", frindex.Value.String); } FireReductions inputFireReduction = new FireReductions(); // ignoring severity = zero parameters.FireReductionsTable[ln] = inputFireReduction; ReadValue(wred, currentLine); inputFireReduction.CoarseLitterReduction = wred.Value; ReadValue(lred, currentLine); inputFireReduction.FineLitterReduction = lred.Value; //ReadValue(som_red, currentLine); //inputFireReduction.SOMReduction = som_red.Value; CheckNoDataAfter("the " + lred.Name + " column", currentLine); GetNextLine(); } //--------- Read In Harvest Reductions Table --------------------------- InputVar <string> hreds = new InputVar <string>("HarvestReductions"); ReadName(Names.HarvestReductionParameters); PlugIn.ModelCore.UI.WriteLine(" Begin reading HARVEST REDUCTION parameters."); InputVar <string> prescriptionName = new InputVar <string>("Prescription"); InputVar <double> wred_pr = new InputVar <double>("Coarse Litter Reduction"); InputVar <double> lred_pr = new InputVar <double>("Fine Litter Reduction"); //InputVar<double> som_red_pr = new InputVar<double>("SOM Reduction"); InputVar <double> cohortw_red_pr = new InputVar <double>("Cohort Biomass Removal"); //InputVar<double> cohortl_red_pr = new InputVar<double>("Cohort Leaf Removal"); while (!AtEndOfInput) { StringReader currentLine = new StringReader(CurrentLine); HarvestReductions harvReduction = new HarvestReductions(); parameters.HarvestReductionsTable.Add(harvReduction); ReadValue(prescriptionName, currentLine); harvReduction.PrescriptionName = prescriptionName.Value; ReadValue(wred_pr, currentLine); harvReduction.CoarseLitterReduction = wred_pr.Value; ReadValue(lred_pr, currentLine); harvReduction.FineLitterReduction = lred_pr.Value; ReadValue(cohortw_red_pr, currentLine); harvReduction.CohortWoodReduction = cohortw_red_pr.Value; GetNextLine(); } //string lastParameter = null; //if (! AtEndOfInput && CurrentName == Names.AgeOnlyDisturbanceParms) { // InputVar<string> ageOnlyDisturbanceParms = new InputVar<string>(Names.AgeOnlyDisturbanceParms); // ReadVar(ageOnlyDisturbanceParms); // parameters.AgeOnlyDisturbanceParms = ageOnlyDisturbanceParms.Value; // lastParameter = "the " + Names.AgeOnlyDisturbanceParms + " parameter"; //} //if (lastParameter != null) // CheckNoDataAfter(lastParameter); return(parameters); }
protected override IInsect Parse() { InputVar <string> landisData = new InputVar <string>("LandisData"); ReadVar(landisData); if (landisData.Value.Actual != "InsectDefoliator") { throw new InputValueException(landisData.Value.String, "The value is not \"{0}\"", "InsectDefoliator"); } InsectParameters parameters = new InsectParameters(PlugIn.ModelCore.Species.Count); InputVar <string> insectName = new InputVar <string>("InsectName"); ReadVar(insectName); parameters.Name = insectName.Value; InputVar <int> insectStartYear = new InputVar <int>("StartYear"); if (ReadOptionalVar(insectStartYear)) { parameters.StartYear = insectStartYear.Value; } InputVar <DistributionType> ddt = new InputVar <DistributionType>("DurationDistribution"); ReadVar(ddt); parameters.DurationDistribution = ddt.Value; InputVar <double> mD = new InputVar <double>("DurationParameter1"); ReadVar(mD); parameters.DurationParameter1 = mD.Value; InputVar <double> sdD = new InputVar <double>("DurationParameter2"); ReadVar(sdD); parameters.DurationParameter2 = sdD.Value; InputVar <double> maxDur = new InputVar <double>("MaxDuration"); if (ReadOptionalVar(maxDur)) { ; } parameters.MaxDuration = maxDur.Value; InputVar <int> mTBO = new InputVar <int>("MeanTimeBetweenOutbreaks"); ReadVar(mTBO); parameters.MeanTimeBetweenOutbreaks = mTBO.Value; InputVar <int> sdTBO = new InputVar <int>("StdDevTimeBetweenOutbreaks"); ReadVar(sdTBO); parameters.StdDevTimeBetweenOutbreaks = sdTBO.Value; InputVar <int> nhs = new InputVar <int>("NeighborhoodSize"); ReadVar(nhs); parameters.NeighborhoodDistance = nhs.Value; InputVar <double> ipnc = new InputVar <double>("InitialPatchOutbreakSensitivity"); ReadVar(ipnc); parameters.InitialPatchOutbreakSensitivity = ipnc.Value; InputVar <DistributionType> ipdt = new InputVar <DistributionType>("InitialPatchDistribution"); ReadVar(ipdt); parameters.InitialPatchDistr = ipdt.Value; InputVar <double> ipv1 = new InputVar <double>("InitialPatchValue1"); ReadVar(ipv1); parameters.InitialPatchValue1 = ipv1.Value; InputVar <double> ipv2 = new InputVar <double>("InitialPatchValue2"); ReadVar(ipv2); parameters.InitialPatchValue2 = ipv2.Value; //--------- Read In Species Table --------------------------------------- PlugIn.ModelCore.UI.WriteLine(" Begin parsing SPECIES table."); ReadName("SpeciesParameters"); InputVar <string> annMort = new InputVar <string>("MortalityEstimate"); ReadVar(annMort); parameters.AnnMort = annMort.Value; InputVar <string> sppName = new InputVar <string>("Species"); InputVar <int> susc = new InputVar <int>("Species Susceptibility"); InputVar <double> grs = new InputVar <double>("Growth Reduction Slope"); InputVar <double> gri = new InputVar <double>("Growth Reduction Intercept"); InputVar <double> msl = new InputVar <double>("Mortality Slope"); InputVar <double> min = new InputVar <double>("Mortality Intercept"); Dictionary <string, int> lineNumbers = new Dictionary <string, int>(); const string Susceptiblities = "Susceptibilities"; while (!AtEndOfInput && CurrentName != Susceptiblities) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(sppName, currentLine); ISpecies species = PlugIn.ModelCore.Species[sppName.Value.Actual]; if (species == null) { throw new InputValueException(sppName.Value.String, "{0} is not a species name.", sppName.Value.String); } int lineNumber; if (lineNumbers.TryGetValue(species.Name, out lineNumber)) { throw new InputValueException(sppName.Value.String, "The species {0} was previously used on line {1}", sppName.Value.String, lineNumber); } else { lineNumbers[species.Name] = LineNumber; } ISppParameters sppParms = new SppParameters(); //parameters.SppTable[species.Index] = sppParms; (commented out; BMiranda 11 Aug 2017) parameters.SppTable.Add(sppParms); ReadValue(susc, currentLine); sppParms.Susceptibility = susc.Value; ReadValue(grs, currentLine); sppParms.GrowthReduceSlope = grs.Value; ReadValue(gri, currentLine); sppParms.GrowthReduceIntercept = gri.Value; ReadValue(msl, currentLine); sppParms.MortalitySlope = msl.Value; ReadValue(min, currentLine); sppParms.MortalityIntercept = min.Value; CheckNoDataAfter("the " + min.Name + " column", currentLine); GetNextLine(); } if (parameters.SppTable != null && PlugIn.ModelCore.Species != null && parameters.SppTable.Count != PlugIn.ModelCore.Species.Count) { throw new MultiLineException("The number of tree species differs between the Species input file (" + PlugIn.ModelCore.Species.Count + " species) and Biomass Insects (" + parameters.SppTable.Count + " species)."); } // Read table of Susceptibilities. // Susceptibilities are in decreasing order. ReadName(Susceptiblities); const string MapNames = "MapNames"; InputVar <byte> number = new InputVar <byte>("Susceptibility Number"); InputVar <DistributionType> dt = new InputVar <DistributionType>("Distribution"); InputVar <double> v1 = new InputVar <double>("Distribution Value 1"); InputVar <double> v2 = new InputVar <double>("Distribution Value 2"); byte previousNumber = 0; while (!AtEndOfInput && CurrentName != MapNames) { StringReader currentLine = new StringReader(CurrentLine); ISusceptible susceptible = new Susceptible(); parameters.SusceptibleTable.Add(susceptible); ReadValue(number, currentLine); susceptible.Number = number.Value; // Check that the current severity's number is 1 less than // the previous number (numbers are must be in decreasing // order). if (number.Value.Actual != previousNumber + 1) { throw new InputValueException(number.Value.String, "Expected the severity number {0}", previousNumber + 1); } previousNumber = number.Value.Actual; IDistribution distribution = new Distribution(); ReadValue(dt, currentLine); distribution.Name = dt.Value; ReadValue(v1, currentLine); distribution.Value1 = v1.Value; ReadValue(v2, currentLine); distribution.Value2 = v2.Value; susceptible.Distribution_80 = distribution; //.GetComplete(); distribution = new Distribution(); ReadValue(dt, currentLine); distribution.Name = dt.Value; ReadValue(v1, currentLine); distribution.Value1 = v1.Value; ReadValue(v2, currentLine); distribution.Value2 = v2.Value; susceptible.Distribution_60 = distribution; //.GetComplete(); distribution = new Distribution(); ReadValue(dt, currentLine); distribution.Name = dt.Value; ReadValue(v1, currentLine); distribution.Value1 = v1.Value; ReadValue(v2, currentLine); distribution.Value2 = v2.Value; susceptible.Distribution_40 = distribution; //.GetComplete(); distribution = new Distribution(); ReadValue(dt, currentLine); distribution.Name = dt.Value; ReadValue(v1, currentLine); distribution.Value1 = v1.Value; ReadValue(v2, currentLine); distribution.Value2 = v2.Value; susceptible.Distribution_20 = distribution; //.GetComplete(); distribution = new Distribution(); ReadValue(dt, currentLine); distribution.Name = dt.Value; ReadValue(v1, currentLine); distribution.Value1 = v1.Value; ReadValue(v2, currentLine); distribution.Value2 = v2.Value; susceptible.Distribution_0 = distribution; //.GetComplete(); CheckNoDataAfter("the " + v2.Name + " column", currentLine); GetNextLine(); } if (parameters.SusceptibleTable.Count == 0) { throw NewParseException("No susceptibilities defined."); } return(parameters);//.GetComplete(); }
public void Init() { intVar = new InputVar<int>("IntegerVariable"); strVar = new InputVar<string>("String_Var"); longExtraText = "1234567890 abcedefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ\n"; }
//--------------------------------------------------------------------- /// <summary> /// Reads 0 or more prescriptions from text input. /// </summary> protected void ReadPrescriptions(List <Prescription> prescriptions, int harvestTimestep) { Dictionary <string, int> lineNumbers = new Dictionary <string, int>(); InputVar <int> singleRepeat = new InputVar <int>(Names.SingleRepeat); InputVar <int> multipleRepeat = new InputVar <int>(Names.MultipleRepeat); int nameLineNumber = LineNumber; InputVar <string> prescriptionName = new InputVar <string>(Names.Prescription); while (ReadOptionalVar(prescriptionName)) { string name = prescriptionName.Value.Actual; int lineNumber; if (lineNumbers.TryGetValue(name, out lineNumber)) { throw new InputValueException(prescriptionName.Value.String, "The name {0} was previously used on line {1}", prescriptionName.Value.String, lineNumber); } else { lineNumbers[name] = nameLineNumber; } //get ranking method rankingMethod = ReadRankingMethod(); //get stand-harvesting requirements, will modify rankingMethod variable ReadForestTypeTable(); //get site selection method ISiteSelector siteSelector = ReadSiteSelector(); //get the minTimeSinceDamage int minTimeSinceDamage = 0; InputVar <int> minTimeSinceDamageVar = new InputVar <int>("MinTimeSinceDamage"); if (ReadOptionalVar(minTimeSinceDamageVar)) { minTimeSinceDamage = minTimeSinceDamageVar.Value; } bool preventEstablishment = ReadPreventEstablishment(); ICohortSelector cohortSelector = ReadCohortSelector(false); ICohortCutter cohortCutter = CreateCohortCutter(cohortSelector); Planting.SpeciesList speciesToPlant = ReadSpeciesToPlant(); // Repeat harvest? int repeatParamLineNumber = LineNumber; if (ReadOptionalVar(singleRepeat)) { int interval = ValidateRepeatInterval(singleRepeat.Value, repeatParamLineNumber, harvestTimestep); ICohortSelector additionalCohortSelector = ReadCohortSelector(true); ICohortCutter additionalCohortCutter = CreateCohortCutter(additionalCohortSelector); Planting.SpeciesList additionalSpeciesToPlant = ReadSpeciesToPlant(); ISiteSelector additionalSiteSelector = new CompleteStand(); prescriptions.Add(new SingleRepeatHarvest(name, rankingMethod, siteSelector, cohortCutter, speciesToPlant, additionalCohortCutter, additionalSpeciesToPlant, additionalSiteSelector, minTimeSinceDamage, preventEstablishment, interval)); } else if (ReadOptionalVar(multipleRepeat)) { int interval = ValidateRepeatInterval(multipleRepeat.Value, repeatParamLineNumber, harvestTimestep); ISiteSelector additionalSiteSelector = new CompleteStand(); prescriptions.Add(new RepeatHarvest(name, rankingMethod, siteSelector, cohortCutter, speciesToPlant, additionalSiteSelector, minTimeSinceDamage, preventEstablishment, interval)); } else { prescriptions.Add(new Prescription(name, rankingMethod, siteSelector, cohortCutter, speciesToPlant, minTimeSinceDamage, preventEstablishment)); } } }
//--------------------------------------------------------------------- protected override IInputParameters Parse() { InputVar <string> landisData = new InputVar <string>("LandisData"); ReadVar(landisData); if (landisData.Value.Actual != "Climate Config") { throw new InputValueException(landisData.Value.String, "The value is not \"{0}\"", "Climate Config"); } InputParameters parameters = new InputParameters(); string climateTimeSeries_PossibleValues = "Monthly_AverageAllYears, Monthly_AverageWithVariation, Monthly_RandomYears, Daily_RandomYears, Daily_AverageAllYears, Daily_SequencedYears, Monthly_SequencedYears"; string climateFileFormat_PossibleValues = "Daily_Temp-C_Precip-mmDay, Monthly_Temp-C_Precip-mmMonth, Daily_Temp-K_Precip-kgM2Sec, Monthly_Temp-K_Precip-kgM2Sec, mauer_daily, monthly_temp-k_precip-mmmonth, daily_temp-k_precip-mmday"; //InputVar<string> climateConfigFile = new InputVar<string>(Names.ClimateConfigFile); //ReadVar(climateConfigFile); //parameters.ClimateConfigFile = climateConfigFile.Value; InputVar <string> climateTimeSeries = new InputVar <string>(Names.ClimateTimeSeries); ReadVar(climateTimeSeries); parameters.ClimateTimeSeries = climateTimeSeries.Value; InputVar <string> climateFile = new InputVar <string>(Names.ClimateFile); ReadVar(climateFile); parameters.ClimateFile = climateFile.Value; InputVar <string> climateFileFormat = new InputVar <string>(Names.ClimateFileFormat); ReadVar(climateFileFormat); parameters.ClimateFileFormat = climateFileFormat.Value; InputVar <string> spinUpClimateTimeSeries = new InputVar <string>(Names.SpinUpClimateTimeSeries); ReadVar(spinUpClimateTimeSeries); parameters.SpinUpClimateTimeSeries = spinUpClimateTimeSeries.Value; InputVar <string> spinUpClimateFile = new InputVar <string>(Names.SpinUpClimateFile); InputVar <string> spinUpClimateFileFormat = new InputVar <string>(Names.SpinUpClimateFileFormat); ReadVar(spinUpClimateFile); parameters.SpinUpClimateFile = spinUpClimateFile.Value; ReadVar(spinUpClimateFileFormat); parameters.SpinUpClimateFileFormat = spinUpClimateFileFormat.Value; if (!climateTimeSeries_PossibleValues.ToLower().Contains(parameters.ClimateTimeSeries.ToLower()) || !climateTimeSeries_PossibleValues.ToLower().Contains(parameters.SpinUpClimateTimeSeries.ToLower())) { throw new ApplicationException("Error in parsing climate-generator input file: invalid value for ClimateTimeSeries or SpinupTimeSeries provided. Possible values are: " + climateTimeSeries_PossibleValues); } if (!climateFileFormat_PossibleValues.ToLower().Contains(parameters.ClimateFileFormat.ToLower()) || !climateFileFormat_PossibleValues.ToLower().Contains(parameters.SpinUpClimateFileFormat.ToLower())) { throw new ApplicationException("Error in parsing climate-generator input file: invalid value for File Format provided. Possible values are: " + climateFileFormat_PossibleValues); } if (parameters.ClimateTimeSeries.ToLower().Contains("daily") && !parameters.ClimateFileFormat.ToLower().Contains("daily")) { throw new ApplicationException("You are requesting a Daily Time Step but not inputting daily data:" + parameters.ClimateTimeSeries + " and " + parameters.ClimateFileFormat); } InputVar <double> rHSlopeAdjust = new InputVar <double>(Names.RHSlopeAdjust); ReadOptionalVar(rHSlopeAdjust); parameters.RHSlopeAdjust = rHSlopeAdjust.Value; return(parameters); }
//---------------------------------------------------------------------- protected void ReadForestTypeTable() { SpeciesLineNumbers.Clear(); // in case parser re-used int optionalStatements = 0; //check if this is the ForestTypeTable if (CurrentName == Names.ForestTypeTable) { ReadName(Names.ForestTypeTable); //fresh input variables for table InputVar <string> inclusionRule = new InputVar <string>("Inclusion Rule"); //InputVar<ushort> minAge = new InputVar<ushort>("Min Age"); //InputVar<ushort> maxAge = new InputVar<ushort>("Max Age"); InputVar <AgeRange> age_range = new InputVar <AgeRange>("Age Range"); InputVar <string> percentOfCells = new InputVar <string>("PercentOfCells"); //as a string so it can include keyword 'highest' InputVar <string> speciesName = new InputVar <string>("Species"); //list for each rule- each line is a separate rule List <InclusionRule> rule_list = new List <InclusionRule>(); //keep reading until no longer in the ForestTypeTable while (!AtEndOfInput && !namesThatFollowForestType.Contains(CurrentName)) { StringReader currentLine = new StringReader(CurrentLine); // inclusionRule column ReadValue(inclusionRule, currentLine); //verify inclusion rule = 'optional', 'required', or 'forbidden' if (inclusionRule.Value.Actual != "Optional" && inclusionRule.Value.Actual != "Required" && inclusionRule.Value.Actual != "Forbidden") { string[] ic_list = new string[] { "Valid Inclusion Rules:", " Optional", " Required", " Forbidden" }; throw new InputValueException(CurrentName, CurrentName + " is not a valid inclusion rule.", new MultiLineText(ic_list)); } if (inclusionRule.Value.Actual == "Optional") { optionalStatements++; } TextReader.SkipWhitespace(currentLine); ReadValue(age_range, currentLine); //percentage column TextReader.SkipWhitespace(currentLine); ReadValue(percentOfCells, currentLine); //Model.Core.UI.WriteLine("percentOfCells = {0}", percentOfCells.Value.String); //cannot validate until parsing is done. will do this in the inclusionRule constructor //a list in case there are multiple species on this line List <string> species_list = new List <string>(); //add each species to this rule's species list TextReader.SkipWhitespace(currentLine); while (currentLine.Peek() != -1) { //species column (build list) ReadValue(speciesName, currentLine); string name = speciesName.Value.String; ISpecies species = GetSpecies(new InputValue <string>(name, speciesName.Value.String)); if (species_list.Contains(species.Name)) { throw NewParseException("The species {0} appears more than once.", species.Name); } species_list.Add(species.Name); //species_list.Add(species.Value.String); TextReader.SkipWhitespace(currentLine); } //add this new inclusion rule (by parameters) to the requirement rule_list.Add(new InclusionRule(inclusionRule.Value.String, age_range.Value.Actual, percentOfCells.Value.String, species_list)); GetNextLine(); } //create a new requirement with this list of rules IRequirement inclusionRequirement = new InclusionRequirement(rule_list); //add this requirement to the ranking method rankingMethod.AddRequirement(inclusionRequirement); } if (optionalStatements > 0 && optionalStatements < 2) { throw new InputValueException(CurrentName, "If there are optional statements, there must be more than one", "ForestTypeTable"); } }
protected override Land_type_Attributes Parse() { ReadLandisDataVar(); InputVar <int> int_val = new InputVar <int>("int value"); InputVar <float> float_val = new InputVar <float>("float value"); Land_type_Attributes lt_att = new Land_type_Attributes(); StringReader currentLine = new StringReader(CurrentLine); int num_new_map_files = 0; if (PlugIn.gl_param.FlagforSECFile == 3) { ReadValue(int_val, currentLine); num_new_map_files = int_val.Value.Actual; CheckNoDataAfter("num_new_map_files", currentLine); GetNextLine(); InputVar <int> year = new InputVar <int>("year"); InputVar <string> mapf = new InputVar <string>("new map file name"); for (byte i = 0; i < num_new_map_files; i++) { currentLine = new StringReader(CurrentLine); ReadValue(year, currentLine); ReadValue(mapf, currentLine); lt_att.Set_new_landtype_map(year.Value.Actual, mapf.Value.Actual); lt_att.year_arr.Add(year.Value.Actual); CheckNoDataAfter("a new_map_file", currentLine); GetNextLine(); } currentLine = new StringReader(CurrentLine); } int num_landtype = Land_type_Attributes.Landtype_count; for (byte i = 0; i < num_landtype; i++) { ReadValue(int_val, currentLine); Land_type_Attributes.set_min_shade(i, int_val.Value.Actual); } CheckNoDataAfter("min_shade", currentLine); GetNextLine(); for (byte gsokind = 0; gsokind < 3; gsokind++) { currentLine = new StringReader(CurrentLine); for (byte j = 0; j < num_landtype; j++) { ReadValue(float_val, currentLine); Land_type_Attributes.set_gso(gsokind, j, float_val.Value.Actual); } //CheckNoDataAfter("gso" + gsokind.ToString(), currentLine); GetNextLine(); } for (int count = 0; count <= num_new_map_files; count++) { currentLine = new StringReader(CurrentLine); float[] max_gso_value = new float[num_landtype]; for (byte j = 0; j < num_landtype; j++) { ReadValue(float_val, currentLine); max_gso_value[j] = float_val.Value.Actual; } lt_att.set_maxgso(lt_att.year_arr[count], max_gso_value); //CheckNoDataAfter("max_gso", currentLine); GetNextLine(); } return(lt_att); }
//--------------------------------------------------------------------- /// <summary> /// Reads harvest implementations: which prescriptions are applied to /// which management areas. /// </summary> protected void ReadHarvestImplementations(ManagementAreaDataset mgmtAreas, List <Prescription> prescriptions) { ReadName(Names.HarvestImplementations); InputVar <ushort> mgmtAreaMapCode = new InputVar <ushort>("Mgmt Area"); InputVar <string> prescriptionName = new InputVar <string>("Prescription"); InputVar <int> beginTimeVar = new InputVar <int>("Begin Time"); InputVar <int> endTimeVar = new InputVar <int>("End Time"); InputVar <Percentage> areaToHarvest = new InputVar <Percentage>("Area To Harvest"); while (!AtEndOfInput && CurrentName != Names.PrescriptionMaps) { StringReader currentLine = new StringReader(CurrentLine); // Mgmt Area column ReadValue(mgmtAreaMapCode, currentLine); ushort mapCode = mgmtAreaMapCode.Value.Actual; ManagementArea mgmtArea = mgmtAreas.Find(mapCode); if (mgmtArea == null) { //add the management area, and add it to the collection of management areas mgmtArea = new ManagementArea(mapCode); mgmtAreas.Add(mgmtArea); } // Prescription column ReadValue(prescriptionName, currentLine); string name = prescriptionName.Value.Actual; Prescription prescription = prescriptions.Find(new MatchName(name).Predicate); if (prescription == null) { throw new InputValueException(prescriptionName.Value.String, prescriptionName.Value.String + " is an unknown prescription name"); } // Area to Harvest column ReadValue(areaToHarvest, currentLine); //get percentage to harvest (type Percentage ensures that it is in percent format) Percentage percentageToHarvest = areaToHarvest.Value.Actual; //check for valid percentage if (percentageToHarvest <= 0.0 || percentageToHarvest > 1.0) { throw new InputValueException(areaToHarvest.Value.String, "Percentage must be between 0% and 100%"); } // Begin Time and End Time columns // They are optional, so the possibilities are: // // Begin Time End Time // ---------- -------- // 1) present present // 2) present missing // 3) missing missing // The default values for the starting and ending times for // an applied prescription. int beginTime = scenarioStart; int endTime = scenarioEnd; TextReader.SkipWhitespace(currentLine); if (currentLine.Peek() != -1) { ReadValue(beginTimeVar, currentLine); beginTime = beginTimeVar.Value.Actual; if (beginTime < scenarioStart) { throw new InputValueException(beginTimeVar.Value.String, string.Format("Year {0} is before the scenario start year ({1})", beginTimeVar.Value.String, scenarioStart)); } if (beginTime > scenarioEnd) { throw new InputValueException(beginTimeVar.Value.String, string.Format("Year {0} is after the scenario' end year ({1})", beginTimeVar.Value.String, scenarioEnd)); } TextReader.SkipWhitespace(currentLine); if (currentLine.Peek() != -1) { ReadValue(endTimeVar, currentLine); endTime = endTimeVar.Value.Actual; if (endTime < beginTime) { throw new InputValueException(endTimeVar.Value.String, string.Format("Year {0} is before the Begin Time ({1})", endTimeVar.Value.String, beginTimeVar.Value.String)); } if (endTime > scenarioEnd) { throw new InputValueException(endTimeVar.Value.String, string.Format("Year {0} is after the scenario' end year ({1})", endTimeVar.Value.String, scenarioEnd)); } CheckNoDataAfter("the " + endTimeVar.Name + " column", currentLine); } } //if the perscription has already been applied to this management area //NOTE: .IsApplied has been modified, and this has been moved to AFTER the //begin and end times are founded. if (mgmtArea.IsApplied(prescriptionName.Value.String, beginTime, endTime)) { throw new InputValueException(prescriptionName.Value.String, "Prescription {0} has already been applied to management area {1} with begin time = {2} and end time = {3}", prescriptionName.Value.String, mgmtArea.MapCode, beginTime, endTime); } //begin applying prescription to this management area mgmtArea.ApplyPrescription(prescription, percentageToHarvest, beginTime, endTime); CheckNoDataAfter("the " + prescriptionName.Name + " column", currentLine); GetNextLine(); } }
//--------------------------------------------------------------------- protected override IAgent Parse() { //PlugIn.ModelCore.Log.WriteLine("Parsing 1; sppCnt={0}", Model.Species.Count); //Agent agentParameters = new Agent(PlugIn.ModelCore.Species.Count, PlugIn.ModelCore.Ecoregions.Count, (int) DisturbanceType.Null); //The last disturb Type is Null InputVar <string> landisData = new InputVar <string>("LandisData"); ReadVar(landisData); if (landisData.Value.Actual != LandisDataValue) { throw new InputValueException(landisData.Value.String, "The value is not \"{0}\"", LandisDataValue); } Agent agentParameters = new Agent(PlugIn.ModelCore.Species.Count, PlugIn.ModelCore.Ecoregions.Count); InputVar <string> agentName = new InputVar <string>("BDAAgentName"); ReadVar(agentName); agentParameters.AgentName = agentName.Value; InputVar <int> bdpc = new InputVar <int>("BDPCalibrator"); ReadVar(bdpc); agentParameters.BDPCalibrator = bdpc.Value; InputVar <SRDmode> srd = new InputVar <SRDmode>("SRDMode"); ReadVar(srd); agentParameters.SRDmode = srd.Value; InputVar <int> startYear = new InputVar <int>("StartYear"); if (CurrentName == "StartYear") { ReadVar(startYear); agentParameters.StartYear = startYear.Value; } else { agentParameters.StartYear = 0; } InputVar <int> endYear = new InputVar <int>("EndYear"); if (CurrentName == "EndYear") { ReadVar(endYear); agentParameters.EndYear = endYear.Value; } else { agentParameters.EndYear = PlugIn.ModelCore.EndTime; } InputVar <OutbreakPattern> rf = new InputVar <OutbreakPattern>("OutbreakPattern"); ReadVar(rf); agentParameters.RandFunc = rf.Value; InputVar <double> normMean = new InputVar <double>("Mean"); InputVar <double> normStDev = new InputVar <double>("StDev"); if ((rf.Value.ToString()) == "CyclicNormal") { ReadVar(normMean); agentParameters.NormMean = normMean.Value; ReadVar(normStDev); agentParameters.NormStDev = normStDev.Value; } else { agentParameters.NormMean = 0; agentParameters.NormStDev = 0; } InputVar <double> maxInterval = new InputVar <double>("MaxInterval"); InputVar <double> minInterval = new InputVar <double>("MinInterval"); if (rf.Value.ToString() == "CyclicUniform") { ReadVar(maxInterval); agentParameters.MaxInterval = maxInterval.Value; ReadVar(minInterval); agentParameters.MinInterval = minInterval.Value; } else { agentParameters.MaxInterval = 0; agentParameters.MinInterval = 0; } InputVar <int> tSLE = new InputVar <int>("TimeSinceLastEpidemic"); ReadVar(tSLE); agentParameters.TimeSinceLastEpidemic = tSLE.Value; InputVar <TemporalType> tt = new InputVar <TemporalType>("TemporalType"); ReadVar(tt); agentParameters.TempType = tt.Value; InputVar <int> minROS = new InputVar <int>("MinROS"); ReadVar(minROS); agentParameters.MinROS = minROS.Value; InputVar <int> maxROS = new InputVar <int>("MaxROS"); ReadVar(maxROS); agentParameters.MaxROS = maxROS.Value; InputVar <bool> d = new InputVar <bool>("Dispersal"); ReadVar(d); agentParameters.Dispersal = d.Value; InputVar <int> dr = new InputVar <int>("DispersalRate"); ReadVar(dr); agentParameters.DispersalRate = dr.Value; InputVar <double> et = new InputVar <double>("EpidemicThresh"); ReadVar(et); agentParameters.EpidemicThresh = et.Value; InputVar <int> ien = new InputVar <int>("InitialEpicenterNum"); ReadVar(ien); agentParameters.EpicenterNum = ien.Value; InputVar <double> oec = new InputVar <double>("OutbreakEpicenterCoeff"); ReadVar(oec); agentParameters.OutbreakEpicenterCoeff = oec.Value; InputVar <double> outEpiThresh = new InputVar <double>("OutbreakEpicenterThresh"); ReadVar(outEpiThresh); agentParameters.OutbreakEpicenterThresh = outEpiThresh.Value; InputVar <bool> se = new InputVar <bool>("SeedEpicenter"); ReadVar(se); agentParameters.SeedEpicenter = se.Value; InputVar <double> sec = new InputVar <double>("SeedEpicenterCoeff"); ReadVar(sec); agentParameters.SeedEpicenterCoeff = sec.Value; InputVar <DispersalTemplate> dispt = new InputVar <DispersalTemplate>("DispersalTemplate"); ReadVar(dispt); agentParameters.DispersalTemp = dispt.Value; InputVar <bool> nf = new InputVar <bool>("NeighborFlag"); ReadVar(nf); agentParameters.NeighborFlag = nf.Value; InputVar <NeighborSpeed> nspeed = new InputVar <NeighborSpeed>("NeighborSpeedUp"); ReadVar(nspeed); agentParameters.NeighborSpeedUp = nspeed.Value; InputVar <int> nr = new InputVar <int>("NeighborRadius"); ReadVar(nr); agentParameters.NeighborRadius = nr.Value; InputVar <NeighborShape> ns = new InputVar <NeighborShape>("NeighborShape"); ReadVar(ns); agentParameters.ShapeOfNeighbor = ns.Value; InputVar <double> nw = new InputVar <double>("NeighborWeight"); ReadVar(nw); agentParameters.NeighborWeight = nw.Value; InputVar <double> class2_SV = new InputVar <double>("IntensityClass2_BDP"); ReadVar(class2_SV); agentParameters.Class2_SV = class2_SV.Value; InputVar <double> class3_SV = new InputVar <double>("IntensityClass3_BDP"); ReadVar(class3_SV); agentParameters.Class3_SV = class3_SV.Value; //--------- Read In Ecoreigon Table --------------------------------------- PlugIn.ModelCore.UI.WriteLine("Begin parsing ECOREGION table."); InputVar <string> ecoName = new InputVar <string>("Ecoregion Name"); InputVar <double> ecoModifier = new InputVar <double>("Ecoregion Modifier"); Dictionary <string, int> lineNumbers = new Dictionary <string, int>(); const string DistParms = "DisturbanceModifiers"; const string SppParms = "BDASpeciesParameters"; while (!AtEndOfInput && CurrentName != DistParms && CurrentName != SppParms) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(ecoName, currentLine); IEcoregion ecoregion = EcoregionsDataset[ecoName.Value.Actual]; if (ecoregion == null) { throw new InputValueException(ecoName.Value.String, "{0} is not an ecoregion name.", ecoName.Value.String); } int lineNumber; if (lineNumbers.TryGetValue(ecoregion.Name, out lineNumber)) { throw new InputValueException(ecoName.Value.String, "The ecoregion {0} was previously used on line {1}", ecoName.Value.String, lineNumber); } else { lineNumbers[ecoregion.Name] = LineNumber; } IEcoParameters ecoParms = new EcoParameters(); agentParameters.EcoParameters[ecoregion.Index] = ecoParms; ReadValue(ecoModifier, currentLine); ecoParms.EcoModifier = ecoModifier.Value; CheckNoDataAfter("the " + ecoModifier.Name + " column", currentLine); GetNextLine(); } if (CurrentName == DistParms) { //--------- Read In Disturbance Modifier Table ------------------------------- PlugIn.ModelCore.UI.WriteLine("Begin parsing DISTURBANCE table."); ReadName(DistParms); InputVar <string> prescriptionName = new InputVar <string>("Disturbance Type"); InputVar <int> duration = new InputVar <int>("Duration"); InputVar <double> distModifier = new InputVar <double>("Disturbance Modifier"); lineNumbers = new Dictionary <string, int>(); Dictionary <int, int> DisturbanceTypeLineNumbers = new Dictionary <int, int>(); while (!AtEndOfInput && CurrentName != SppParms) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(distModifier, currentLine); IDisturbanceType currentDisturbanceType = new DisturbanceType(); agentParameters.DisturbanceTypes.Add(currentDisturbanceType); currentDisturbanceType.SRDModifier = distModifier.Value; //IDistParameters distParms = new DistParameters(); //agentParameters.DistParameters[dt] = distParms; ReadValue(duration, currentLine); currentDisturbanceType.MaxAge = duration.Value; List <string> prescriptionNames = new List <string>(); TextReader.SkipWhitespace(currentLine); while (currentLine.Peek() != -1) { ReadValue(prescriptionName, currentLine); prescriptionNames.Add(prescriptionName.Value); TextReader.SkipWhitespace(currentLine); } if (prescriptionNames.Count == 0) { throw NewParseException("At least one disturbance type is required."); } currentDisturbanceType.PrescriptionNames = prescriptionNames; //ReadValue(distType, currentLine); //int dt = (int)distType.Value.Actual; CheckNoDataAfter("the " + distModifier.Name + " column", currentLine); GetNextLine(); } } //--------- Read In Species Table --------------------------------------- PlugIn.ModelCore.UI.WriteLine("Begin parsing SPECIES table."); ReadName(SppParms); //const string FireCurves = "FireCurveTable"; InputVar <string> sppName = new InputVar <string>("Species"); InputVar <int> minorHostAge = new InputVar <int>("Minor Host Age"); InputVar <double> minorHostSRD = new InputVar <double>("Minor Host SRDProb"); InputVar <int> secondaryHostAge = new InputVar <int>("Second Host Age"); InputVar <double> secondaryHostSRD = new InputVar <double>("Secondary Host SRDProb"); InputVar <int> primaryHostAge = new InputVar <int>("Primary Host Age"); InputVar <double> primaryHostSRD = new InputVar <double>("Primary Host SRDProb"); InputVar <int> resistantHostAge = new InputVar <int>("Resistant Host Age"); InputVar <double> resistantHostVuln = new InputVar <double>("Resistant Host VulnProb"); InputVar <int> tolerantHostAge = new InputVar <int>("Tolerant Host Age"); InputVar <double> tolerantHostVuln = new InputVar <double>("Tolerant Host VulnProb"); InputVar <int> vulnerableHostAge = new InputVar <int>("Vulnerable Host Age"); InputVar <double> vulnerableHostVuln = new InputVar <double>("Vulnerable Host VulnProb"); InputVar <bool> cfsConifer = new InputVar <bool>("CFS Conifer type: yes/no"); const string NegSpp = "IgnoredSpecies"; const string AdvRegenSpp = "AdvancedRegenSpecies"; const string AdvRegenMaxAge = "AgeCutoff"; while ((!AtEndOfInput) && (CurrentName != NegSpp) && (CurrentName != AdvRegenSpp) && (CurrentName != AdvRegenMaxAge)) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(sppName, currentLine); ISpecies species = SpeciesDataset[sppName.Value.Actual]; if (species == null) { throw new InputValueException(sppName.Value.String, "{0} is not a species name.", sppName.Value.String); } int lineNumber; if (lineNumbers.TryGetValue(species.Name, out lineNumber)) { throw new InputValueException(sppName.Value.String, "The species {0} was previously used on line {1}", sppName.Value.String, lineNumber); } else { lineNumbers[species.Name] = LineNumber; } ISppParameters sppParms = new SppParameters(); agentParameters.SppParameters[species.Index] = sppParms; ReadValue(minorHostAge, currentLine); sppParms.MinorHostAge = minorHostAge.Value; ReadValue(minorHostSRD, currentLine); sppParms.MinorHostSRD = minorHostSRD.Value; ReadValue(secondaryHostAge, currentLine); sppParms.SecondaryHostAge = secondaryHostAge.Value; ReadValue(secondaryHostSRD, currentLine); sppParms.SecondaryHostSRD = secondaryHostSRD.Value; ReadValue(primaryHostAge, currentLine); sppParms.PrimaryHostAge = primaryHostAge.Value; ReadValue(primaryHostSRD, currentLine); sppParms.PrimaryHostSRD = primaryHostSRD.Value; ReadValue(resistantHostAge, currentLine); sppParms.ResistantHostAge = resistantHostAge.Value; ReadValue(resistantHostVuln, currentLine); sppParms.ResistantHostVuln = resistantHostVuln.Value; ReadValue(tolerantHostAge, currentLine); sppParms.TolerantHostAge = tolerantHostAge.Value; ReadValue(tolerantHostVuln, currentLine); sppParms.TolerantHostVuln = tolerantHostVuln.Value; ReadValue(vulnerableHostAge, currentLine); sppParms.VulnerableHostAge = vulnerableHostAge.Value; ReadValue(vulnerableHostVuln, currentLine); sppParms.VulnerableHostVuln = vulnerableHostVuln.Value; ReadValue(cfsConifer, currentLine); sppParms.CFSConifer = cfsConifer.Value; CheckNoDataAfter("the " + cfsConifer.Name + " column", currentLine); GetNextLine(); } //--------- Read In Ignored Species List --------------------------------------- List <ISpecies> negSppList = new List <ISpecies>(); if (!AtEndOfInput && (CurrentName != AdvRegenSpp) && (CurrentName != AdvRegenMaxAge)) { ReadName(NegSpp); InputVar <string> negSppName = new InputVar <string>("Ignored Spp Name"); while (!AtEndOfInput && (CurrentName != AdvRegenSpp) && (CurrentName != AdvRegenMaxAge)) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(negSppName, currentLine); ISpecies species = SpeciesDataset[negSppName.Value.Actual]; if (species == null) { throw new InputValueException(negSppName.Value.String, "{0} is not a species name.", negSppName.Value.String); } int lineNumber; if (lineNumbers.TryGetValue(species.Name, out lineNumber)) { PlugIn.ModelCore.UI.WriteLine("WARNING: The species {0} was previously used on line {1}. Being listed in the IgnoredSpecies list will override any settings in the Host table.", negSppName.Value.String, lineNumber); } else { lineNumbers[species.Name] = LineNumber; } negSppList.Add(species); GetNextLine(); } } agentParameters.NegSppList = negSppList; //--------- Read In Advanced Regen Species List --------------------------------------- List <ISpecies> advRegenSppList = new List <ISpecies>(); if (!AtEndOfInput && (CurrentName != AdvRegenMaxAge)) { ReadName(AdvRegenSpp); InputVar <string> advRegenSppName = new InputVar <string>("Advanced Regen Spp Name"); while (!AtEndOfInput && CurrentName != "AgeCutoff") { StringReader currentLine = new StringReader(CurrentLine); ReadValue(advRegenSppName, currentLine); ISpecies species = SpeciesDataset[advRegenSppName.Value.Actual]; if (species == null) { throw new InputValueException(advRegenSppName.Value.String, "{0} is not a species name.", advRegenSppName.Value.String); } lineNumbers[species.Name] = LineNumber; advRegenSppList.Add(species); GetNextLine(); } } agentParameters.AdvRegenSppList = advRegenSppList; InputVar <int> advRegenAgeCutoff = new InputVar <int>("AgeCutoff"); if (!AtEndOfInput) { ReadVar(advRegenAgeCutoff); agentParameters.AdvRegenAgeCutoff = advRegenAgeCutoff.Value; } else { agentParameters.AdvRegenAgeCutoff = 0; } return(agentParameters); //.GetComplete(); }
public void Init() { doubleVar = new InputVar<double>("Double Input Var"); values = new double[] { -4, 78900, 0, 555 }; string[] valsAsStrs = Array.ConvertAll(values, new Converter<double, string>(Convert.ToString)); valuesAsStr = string.Join(" ", valsAsStrs); }
//--------------------------------------------------------------------- protected override IInputParameters Parse() { ReadLandisDataVar(); InputParameters parameters = new InputParameters(PlugIn.ModelCore.Species.Count); InputVar <int> timestep = new InputVar <int>("Timestep"); ReadVar(timestep); parameters.Timestep = timestep.Value; // Table of Fuel coefficients InputVar <string> speciesName = new InputVar <string>("Species"); InputVar <double> FuelCoeff = new InputVar <double>("Fuel Coefficient"); Dictionary <string, int> lineNumbers = new Dictionary <string, int>(); const string HardwoodLabel = "HardwoodMaximum"; while (!AtEndOfInput && CurrentName != HardwoodLabel) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(speciesName, currentLine); ISpecies species = GetSpecies(speciesName.Value); CheckForRepeatedName(speciesName.Value, "species", lineNumbers); ReadValue(FuelCoeff, currentLine); parameters.FuelCoefficients[species.Index] = FuelCoeff.Value; CheckNoDataAfter(string.Format("the {0} column", FuelCoeff.Name), currentLine); GetNextLine(); } const string FuelTypeNames = "FuelTypes"; //------------------------------------------------------------ InputVar <int> hardwoodMax = new InputVar <int>("HardwoodMaximum"); ReadVar(hardwoodMax); parameters.HardwoodMax = hardwoodMax.Value; InputVar <int> deadFirMaxAge = new InputVar <int>("DeadFirMaxAge"); ReadVar(deadFirMaxAge); parameters.DeadFirMaxAge = deadFirMaxAge.Value; //------------------------------------------------------------ // Read definitions of Fuel maps PlugIn.ModelCore.UI.WriteLine(" Reading in the Fuel Assignment table..."); ReadName(FuelTypeNames); List <string> speciesNames = new List <string>(); InputVar <int> fi = new InputVar <int>("Fuel Index (should match table in dynamic fire input file)"); InputVar <BaseFuelType> bft = new InputVar <BaseFuelType>("Base Fuel Type"); InputVar <int> minAge = new InputVar <int>("Min Age"); InputVar <int> maxAge = new InputVar <int>("Max Age"); lineNumbers.Clear(); Dictionary <int, int> FuelTypeLineNumbers = new Dictionary <int, int>(); const string DisturbanceConversionTable = "DisturbanceConversionTable"; const string EcoregionTable = "EcoregionTable"; while (!AtEndOfInput && CurrentName != DisturbanceConversionTable && CurrentName != EcoregionTable) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(fi, currentLine); CheckForRepeatedIndex(fi.Value, "fuel type", FuelTypeLineNumbers); IFuelType currentFuelType = new FuelType(PlugIn.ModelCore.Species.Count, PlugIn.ModelCore.Ecoregions.Count); parameters.FuelTypes.Add(currentFuelType); currentFuelType.Index = fi.Value; ReadValue(bft, currentLine); currentFuelType.BaseFuel = bft.Value; // Read the age ranges for the species: ReadValue(minAge, currentLine); currentFuelType.MinAge = minAge.Value; TextReader.SkipWhitespace(currentLine); string word = TextReader.ReadWord(currentLine); if (word != "to") { StringBuilder message = new StringBuilder(); message.AppendFormat("Expected \"to\" after the minimum age ({0})", minAge.Value.String); if (word.Length > 0) { message.AppendFormat(", but found \"{0}\" instead", word); } throw NewParseException(message.ToString()); } ReadValue(maxAge, currentLine); currentFuelType.MaxAge = maxAge.Value; // Read the species for the fuel type: speciesNames = new List <string>(); TextReader.SkipWhitespace(currentLine); while (currentLine.Peek() != -1) { ReadValue(speciesName, currentLine); string name = speciesName.Value.Actual; bool negativeMultiplier = name.StartsWith("-"); if (negativeMultiplier) { name = name.Substring(1); if (name.Length == 0) { throw new InputValueException(speciesName.Value.String, "No species name after \"-\""); } } ISpecies species = GetSpecies(new InputValue <string>(name, speciesName.Value.String)); if (speciesNames.Contains(species.Name)) { throw NewParseException("The species {0} appears more than once.", species.Name); } speciesNames.Add(species.Name); currentFuelType[species.Index] = negativeMultiplier ? -1 : 1; TextReader.SkipWhitespace(currentLine); } if (speciesNames.Count == 0) { throw NewParseException("At least one species is required."); } GetNextLine(); } //---------------------------------------------------------- // Optional ecoregion data if (ReadOptionalName(EcoregionTable)) { PlugIn.ModelCore.UI.WriteLine(" Loading Ecoregion data..."); InputVar <int> fi2 = new InputVar <int>("Fuel Index (Ecoregion Table)"); InputVar <string> ecoregionName = new InputVar <string>("Ecoregion Name"); lineNumbers.Clear(); while (!AtEndOfInput && CurrentName != DisturbanceConversionTable) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(fi2, currentLine); IFuelType currentFuelType = GetFuelType(fi2, lineNumbers, parameters); bool[] ecoregions = new bool[PlugIn.ModelCore.Ecoregions.Count]; for (int i = 0; i < PlugIn.ModelCore.Ecoregions.Count; i++) { ecoregions[i] = false; } // Read the ecoregions for the fuel type: List <string> ecoNames = new List <string>(); TextReader.SkipWhitespace(currentLine); while (currentLine.Peek() != -1) { ReadValue(ecoregionName, currentLine); IEcoregion ecoregion = GetEcoregion(ecoregionName.Value); if (ecoNames.Contains(ecoregion.Name)) { throw NewParseException("The ecoregion {0} appears more than once.", ecoregion.Name); } ecoNames.Add(ecoregion.Name); ecoregions[ecoregion.Index] = true; TextReader.SkipWhitespace(currentLine); } currentFuelType.Ecoregions = ecoregions; GetNextLine(); } } //------------------------------------------------------------ // Read definitions of Disturbance Types PlugIn.ModelCore.UI.WriteLine(" Reading in the Disturbance Type table..."); ReadName(DisturbanceConversionTable); InputVar <int> fti = new InputVar <int>("Fuel Index"); InputVar <int> maxAgeS = new InputVar <int>("Max Age"); InputVar <string> prescriptionName = new InputVar <string>("Prescription"); lineNumbers.Clear(); Dictionary <int, int> distTypeLineNumbers = new Dictionary <int, int>(); const string MapFileNames = "MapFileNames"; const string PctConiferFileName = "PctConiferFileName"; const string PctDeadFirFileName = "PctDeadFirFileName"; while (!AtEndOfInput && CurrentName != MapFileNames) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(fti, currentLine); IDisturbanceType currentDisturbanceType = new DisturbanceType(); parameters.DisturbanceTypes.Add(currentDisturbanceType); currentDisturbanceType.FuelIndex = fti.Value; ReadValue(maxAgeS, currentLine); currentDisturbanceType.MaxAge = maxAgeS.Value; List <string> prescriptionNames = new List <string>(); TextReader.SkipWhitespace(currentLine); while (currentLine.Peek() != -1) { ReadValue(prescriptionName, currentLine); prescriptionNames.Add(prescriptionName.Value); TextReader.SkipWhitespace(currentLine); } if (prescriptionNames.Count == 0) { throw NewParseException("At least one prescription is required."); } currentDisturbanceType.PrescriptionNames = prescriptionNames; GetNextLine(); } //------------------------------------------------------------ // Template for filenames of Fuel maps PlugIn.ModelCore.UI.WriteLine(" Reading in map names..."); InputVar <string> mapFileNames = new InputVar <string>(MapFileNames); ReadVar(mapFileNames); parameters.MapFileNames = mapFileNames.Value; // //GetNextLine(); //------------------------------------------------------------ // Template for filenames of percent conifer maps InputVar <string> pctConiferFileName = new InputVar <string>(PctConiferFileName); ReadVar(pctConiferFileName); parameters.PctConiferFileName = pctConiferFileName.Value; //GetNextLine(); //------------------------------------------------------------ // Template for filenames of percent dead fir maps InputVar <string> pctDeadFirFileName = new InputVar <string>(PctDeadFirFileName); ReadVar(pctDeadFirFileName); parameters.PctDeadFirFileName = pctDeadFirFileName.Value; CheckNoDataAfter(string.Format("the {0} parameter", PctDeadFirFileName)); return(parameters); }
public void ReadMethodNull() { InputVar<int> var = new InputVar<int>("var", (ReadMethod<int>) null); }
public SpeciesParameterParser() { this.speciesLineNums = new Dictionary <string, int>(); this.speciesName = new InputVar <string>("Species"); }
public void Init() { yearVar = new InputVar<int>("Year", InputValidation.ReadYear); InputValidation.Initialize(startYear, endYear); }
protected override IInputParameters Parse() { StringReader currentLine; InputParameters parameters = new InputParameters(); // to get the option to read species parameters from an external file MakeSureFileContainsKeyWord(InputParametersParser.Names.PnETSpeciesParameters); currentLine = new StringReader(CurrentLine); string line = currentLine.ReadLine().Trim(); if (line.Contains("SpeciesName")) { line = line.Replace("SpeciesName", ""); string[] Headers = new string[] { "TOfol", "FolRet", "TOroot", "TOwood", "GDDFolSt", "AmaxA", "AmaxB", "HalfSat", "BFolResp", "GrMstSens", "WltPnt", "PsnAgeRed", "Q10", "PsnTMin", "PsnTOpt", "SLWmax", "SLWDel", "CDDFolEnd", "k", "FolN", "DVPD1", "DVPD2", "WUEcnst", "MaintResp", "DNSC", "RtStRatio", "EstMoist", "EstRad", "KWdLit", "FolLignin" }; headerlabels = CheckHeaderLabels(line, Headers); GetNextLine(); } speciesLineNums.Clear(); // If parser re-used (i.e., for testing purposes) InputVar <string> SpeciesNameHeader = new InputVar <string>("SpeciesName"); // Make sure that all index numbers are called, if not throw an error bool[] AccountedFor = new bool[PlugIn.ModelCore.Species.Count]; while (!AtEndOfInput && CurrentName != InputParametersParser.Names.EcoregionParameters) { currentLine = new StringReader(CurrentLine); ISpecies species = ReadSpecies(currentLine); AccountedFor[species.Index] = true; foreach (string label in headerlabels) { InputVar <float> var = new InputVar <float>(label); ReadValue(var, currentLine); if (TrySet(label, "TOfol", var.Value, 0, 1000, species, parameters.TOfol)) { continue; } if (TrySet(label, "FolRet", var.Value, 0, 1, species, parameters.FolRet)) { continue; } if (TrySet(label, "TOroot", var.Value, 0, 1, species, parameters.TOroot)) { continue; } if (TrySet(label, "TOwood", var.Value, 0, 1, species, parameters.TOwood)) { continue; } if (TrySet(label, "GDDFolSt", var.Value, 1, 2000, species, parameters.GDDFolSt)) { continue; } if (TrySet(label, "AmaxA", var.Value, -500, 500, species, parameters.AmaxA)) { continue; } if (TrySet(label, "AmaxB", var.Value, 0, float.MaxValue, species, parameters.AmaxB)) { continue; } if (TrySet(label, "HalfSat", var.Value, 0, float.MaxValue, species, parameters.HalfSat)) { continue; } if (TrySet(label, "BFolResp", var.Value, 0, 1000, species, parameters.BFolResp)) { continue; } if (TrySet(label, "GrMstSens", var.Value, 0.1F, float.MaxValue, species, parameters.GrMstSens)) { continue; } if (TrySet(label, "WltPnt", var.Value, 0, 1, species, parameters.WltPnt)) { continue; } if (TrySet(label, "PsnAgeRed", var.Value, 1.0F / float.MaxValue, float.MaxValue, species, parameters.PsnAgeRed)) { continue; } if (TrySet(label, "Q10", var.Value, 0, 10, species, parameters.Q10)) { continue; } if (TrySet(label, "PsnTMin", var.Value, -10, 10, species, parameters.PsnTMin)) { continue; } if (TrySet(label, "PsnTOpt", var.Value, 0, 40, species, parameters.PsnTOpt)) { continue; } if (TrySet(label, "SLWmax", var.Value, 0, 1000, species, parameters.SLWmax)) { continue; } if (TrySet(label, "SLWDel", var.Value, 0, 2, species, parameters.SLWDel)) { continue; } if (TrySet(label, "CDDFolEnd", var.Value, 0, 5000, species, parameters.CDDFolEnd)) { continue; } if (TrySet(label, "k", var.Value, 0, 2, species, parameters.K)) { continue; } if (TrySet(label, "FolN", var.Value, 0, 10, species, parameters.FolN)) { continue; } if (TrySet(label, "DVPD1", var.Value, 0, 5, species, parameters.DVPD1)) { continue; } if (TrySet(label, "DVPD2", var.Value, 0, 5, species, parameters.DVPD2)) { continue; } if (TrySet(label, "WUEcnst", var.Value, 0, float.MaxValue, species, parameters.WUEcnst)) { continue; } if (TrySet(label, "MaintResp", var.Value, 0, 1, species, parameters.MaintResp)) { continue; } if (TrySet(label, "DNSC", var.Value, 0, 10, species, parameters.DNSC)) { continue; } if (TrySet(label, "RtStRatio", var.Value, 0, 1, species, parameters.RtStRatio)) { continue; } if (TrySet(label, "EstMoist", var.Value, 0, float.MaxValue, species, parameters.EstMoist)) { continue; } if (TrySet(label, "EstRad", var.Value, 0, float.MaxValue, species, parameters.EstRad)) { continue; } if (TrySet(label, "KWdLit", var.Value, 0, float.MaxValue, species, parameters.KWdLit)) { continue; } if (label == "KNWdLit") { throw new System.Exception("KNWdLit is depreciated per 6/24/2014, foliage decomposition rate is calculated from leaf lignin (FolLignin) and site specific AET"); } if (TrySet(label, "FolLignin", var.Value, 0, float.MaxValue, species, parameters.FolLignin)) { continue; } throw new System.Exception("Undetermined parameter label name " + label); } GetNextLine(); } foreach (ISpecies spc in PlugIn.modelCore.Species) { if (AccountedFor[spc.Index] == false) { throw new System.Exception(spc.Name + " is not accounted for in PnET-Species parameter file"); } } return(parameters); }
public void Init() { inputVar = new InputVar<int>("Effective Seed Dist", EffectiveSeedDist.ReadMethod); }
//--------------------------------------------------------------------- protected override Dictionary <int, IClimateRecord[, ]> Parse() { ReadLandisDataVar(); Dictionary <int, IClimateRecord[, ]> allData = new Dictionary <int, IClimateRecord[, ]>(); const string nextTableName = "ClimateTable"; //--------------------------------------------------------------------- //Read in climate data: ReadName(nextTableName); //InputVar<string> ecoregionName = new InputVar<string>("Ecoregion"); InputVar <int> ecoregionIndex = new InputVar <int>("Ecoregion Index"); InputVar <int> year = new InputVar <int>("Time step for updating the climate"); InputVar <int> month = new InputVar <int>("The Month"); InputVar <double> avgMinTemp = new InputVar <double>("Monthly Minimum Temperature Value"); InputVar <double> avgMaxTemp = new InputVar <double>("Monthly Maximum Temperature Value"); InputVar <double> stdDevTemp = new InputVar <double>("Monthly Std Deviation Temperature Value"); InputVar <double> avgPpt = new InputVar <double>("Monthly Precipitation Value"); InputVar <double> stdDevPpt = new InputVar <double>("Monthly Std Deviation Precipitation Value"); InputVar <double> par = new InputVar <double>("Monthly Photosynthetically Active Radiation Value"); while (!AtEndOfInput) { StringReader currentLine = new StringReader(CurrentLine); //ReadValue(ecoregionName, currentLine); ReadValue(ecoregionIndex, currentLine); //IEcoregion ecoregion = GetEcoregion(ecoregionName.Value); ReadValue(year, currentLine); int yr = year.Value.Actual; if (!allData.ContainsKey(yr)) { IClimateRecord[,] climateTable = new IClimateRecord[ecoregionDataset.Count, 12]; allData.Add(yr, climateTable); //UI.WriteLine(" Climate Parser: Add new year = {0}.", yr); } ReadValue(month, currentLine); int mo = month.Value.Actual; IClimateRecord climateRecord = new ClimateRecord(); ReadValue(avgMinTemp, currentLine); climateRecord.AvgMinTemp = avgMinTemp.Value; ReadValue(avgMaxTemp, currentLine); climateRecord.AvgMaxTemp = avgMaxTemp.Value; ReadValue(stdDevTemp, currentLine); climateRecord.StdDevTemp = stdDevTemp.Value; ReadValue(avgPpt, currentLine); climateRecord.AvgPpt = avgPpt.Value; ReadValue(stdDevPpt, currentLine); climateRecord.StdDevPpt = stdDevPpt.Value; ReadValue(par, currentLine); climateRecord.PAR = par.Value; allData[yr][ecoregionIndex.Value, mo - 1] = climateRecord; //UI.WriteLine(" climateTable avgPpt={0:0.0}.", climateTable[ecoregion.Index, mo-1].AvgPpt); //UI.WriteLine(" allData yr={0}, mo={1}, avgPpt={2:0.0}.", yr, mo, allData[yr][ecoregion.Index, mo-1].AvgPpt); CheckNoDataAfter("the " + par.Name + " column", currentLine); GetNextLine(); } return(allData); }
//--------------------------------------------------------------------- /// <summary> /// Reads 0 or more prescriptions from text input. /// </summary> new protected void ReadPrescriptions(List<Prescription> prescriptions, int harvestTimestep) { Dictionary<string, int> lineNumbers = new Dictionary<string, int>(); InputVar<int> singleRepeat = new InputVar<int>(Names.SingleRepeat); InputVar<int> multipleRepeat = new InputVar<int>(Names.MultipleRepeat); int nameLineNumber = LineNumber; InputVar<string> prescriptionName = new InputVar<string>(Names.Prescription); while (ReadOptionalVar(prescriptionName)) { string name = prescriptionName.Value.Actual; int lineNumber; if (lineNumbers.TryGetValue(name, out lineNumber)) throw new InputValueException(prescriptionName.Value.String, "The name {0} was previously used on line {1}", prescriptionName.Value.String, lineNumber); else lineNumbers[name] = nameLineNumber; IStandRankingMethod rankingMethod = ReadRankingMethod(); // Modify the ranking method with the forest-type table ReadForestTypeTable(rankingMethod); ISiteSelector siteSelector = ReadSiteSelector(); bool isSiteSelectorWrapped = false; //get the minTimeSinceDamage minTimeSinceDamage = 0; InputVar<int> minTimeSinceDamageVar = new InputVar<int>("MinTimeSinceDamage"); if (ReadOptionalVar(minTimeSinceDamageVar)) { minTimeSinceDamage = minTimeSinceDamageVar.Value; } //get preventEstablishment bool preventEstablishment = false; if (ReadOptionalName("PreventEstablishment")) { preventEstablishment = true; } ICohortSelector cohortSelector = ReadCohortSelector(false); MultiSpeciesCohortSelector newCohortSelector = new MultiSpeciesCohortSelector(); if (ageOrRangeWasRead) { //PlugIn.ModelCore.UI.WriteLine("age or range was read"); siteSelector = WrapSiteSelector(siteSelector); isSiteSelectorWrapped = true; newCohortSelector = ReplaceSpecificAgeSelectors(cohortSelector); } Planting.SpeciesList speciesToPlant = ReadSpeciesToPlant(); // Repeat harvest? int repeatParamLineNumber = LineNumber; if (ReadOptionalVar(singleRepeat)) { MultiSpeciesCohortSelector newAddCohortSelector = new MultiSpeciesCohortSelector(); int interval = ValidateRepeatInterval(singleRepeat.Value, repeatParamLineNumber, harvestTimestep); ICohortSelector additionalCohortSelector = ReadCohortSelector(true); if (ageOrRangeWasRead) { newAddCohortSelector = ReplaceSpecificAgeSelectors(additionalCohortSelector); if (!isSiteSelectorWrapped) { siteSelector = WrapSiteSelector(siteSelector); isSiteSelectorWrapped = true; } } Planting.SpeciesList additionalSpeciesToPlant = ReadSpeciesToPlant(); ISiteSelector additionalSiteSelector = WrapSiteSelector(new CompleteStand()); prescriptions.Add(new SingleRepeatHarvest(name, rankingMethod, siteSelector, cohortSelector, speciesToPlant, additionalCohortSelector, additionalSpeciesToPlant, additionalSiteSelector, minTimeSinceDamage, preventEstablishment, interval)); } else if (ReadOptionalVar(multipleRepeat)) { int interval = ValidateRepeatInterval(multipleRepeat.Value, repeatParamLineNumber, harvestTimestep); // After initial site selection repeats must be complete stand ISiteSelector additionalSiteSelector = WrapSiteSelector(new CompleteStand()); prescriptions.Add(new RepeatHarvest(name, rankingMethod, siteSelector, cohortSelector, speciesToPlant, additionalSiteSelector, minTimeSinceDamage, preventEstablishment, interval)); } else { prescriptions.Add(new Prescription(name, rankingMethod, siteSelector, cohortSelector, speciesToPlant, minTimeSinceDamage, preventEstablishment)); } } }
//--------------------------------------------------------------------- protected override IDataset Parse() { // ReadLandisDataVar(); InputVar <string> landisData = new InputVar <string>("LandisData"); ReadVar(landisData); if (landisData.Value.Actual != name) { throw new InputValueException(landisData.Value.String, "The value is not \"{0}\"", name); } Dataset dataset = new Dataset(); InputVar <ushort> mapCode = new InputVar <ushort>("MapCode"); InputVar <string> speciesName = new InputVar <string>("Species"); InputVar <ushort> age = new InputVar <ushort>("Age"); Dictionary <ushort, int> mapCodeLineNumbers = new Dictionary <ushort, int>(); while (!AtEndOfInput) { // Read initial community int mapCodeLineNum = LineNumber; ReadVar(mapCode); int lineNumber; if (mapCodeLineNumbers.TryGetValue(mapCode.Value.Actual, out lineNumber)) { throw new InputValueException(mapCode.Value.String, "The map code {0} was previously used on line {1}", mapCode.Value.Actual, lineNumber); } else { mapCodeLineNumbers[mapCode.Value.Actual] = mapCodeLineNum; } // Read species and their ages List <ISpeciesCohorts> speciesCohortsList; //List<System.Collections.Generic.IEnumerable<Library.Cohort.AgeOnly.ISpeciesCohorts<Library.Cohort.AgeOnly.ICohort>>> speciesCohortsList; speciesCohortsList = new List <ISpeciesCohorts>(); //speciesCohortsList = new List<System.Collections.Generic.IEnumerable<Library.Cohort.AgeOnly.ISpeciesCohorts<Library.Cohort.AgeOnly.ICohort>>>(); Dictionary <string, int> speciesLineNumbers = new Dictionary <string, int>(); while (!AtEndOfInput && CurrentName != mapCode.Name) { StringReader currentLine = new StringReader(CurrentLine); ReadValue(speciesName, currentLine); //Species.ISpecies species = speciesDataset[speciesName.Value.Actual]; ISpecies species = speciesDataset[speciesName.Value.Actual]; if (species == null) { throw new InputValueException(speciesName.Value.String, "{0} is not a species name.", speciesName.Value.String); } if (speciesLineNumbers.TryGetValue(species.Name, out lineNumber)) { throw new InputValueException(speciesName.Value.String, "The species {0} was previously used on line {1}", speciesName.Value.String, lineNumber); } else { speciesLineNumbers[species.Name] = LineNumber; } // Read ages List <ushort> ages = new List <ushort>(); TextReader.SkipWhitespace(currentLine); while (currentLine.Peek() != -1) { ReadValue(age, currentLine); if (age.Value.Actual == 0) { throw new InputValueException(age.Value.String, "Ages must be > 0."); } if (ages.Contains(age.Value.Actual)) { throw new InputValueException(age.Value.String, "The age {0} appears more than once.", age.Value.String); } if (age.Value.Actual > species.Longevity) { throw new InputValueException(age.Value.String, "The age {0} is more than longevity ({1}).", age.Value.String, species.Longevity); } ages.Add(age.Value.Actual); TextReader.SkipWhitespace(currentLine); } if (ages.Count == 0) { // Try reading age which will throw exception ReadValue(age, currentLine); } ages = BinAges(ages); speciesCohortsList.Add(new SpeciesCohorts(species, ages)); GetNextLine(); } // dataset.Add(new Community(mapCode.Value.Actual, // new Library.Cohort.AgeOnly.SiteCohorts(ISpeciesCohorts<ICohort> speciesCohortsList))); dataset.Add(new Community(mapCode.Value.Actual, new SiteCohorts(speciesCohortsList))); } return(dataset); }
//--------------------------------------------------------------------- new protected ISiteSelector ReadSiteSelector() { InputVar<ISiteSelector> siteSelector = new InputVar<ISiteSelector>(Names.SiteSelection, ReadSiteSelector); ReadVar(siteSelector); return siteSelector.Value.Actual; }
public void Init() { // Need to reference the class so its static ctor is called before // any tests run; otherwise, they'll fail because a parse or read // method hasn't been registered with InputValues class. Percentage p = new Percentage(); percentVar = new InputVar<Percentage>("Percentage Var"); }
public void Init() { SeedingAlgorithmsUtil.RegisterForInputValues(); seedAlgVar = new InputVar<SeedingAlgorithms>("SeedingAlgorithm"); }
//--------------------------------------------------------------------- protected override IScenario Parse() { ReadLandisDataVar(); IEditableScenario scenario = new EditableScenario(); InputVar <int> duration = new InputVar <int>("Duration"); ReadVar(duration); scenario.Duration = duration.Value; InputVar <string> species = new InputVar <string>("Species"); ReadVar(species); scenario.Species = species.Value; InputVar <string> ecoregions = new InputVar <string>("Ecoregions"); ReadVar(ecoregions); scenario.Ecoregions = ecoregions.Value; InputVar <string> ecoregionsMap = new InputVar <string>("EcoregionsMap"); ReadVar(ecoregionsMap); scenario.EcoregionsMap = ecoregionsMap.Value; InputVar <string> initCommunities = new InputVar <string>("InitialCommunities"); ReadVar(initCommunities); scenario.InitialCommunities = initCommunities.Value; InputVar <string> communitiesMap = new InputVar <string>("InitialCommunitiesMap"); ReadVar(communitiesMap); scenario.InitialCommunitiesMap = communitiesMap.Value; if (AtEndOfInput) { throw ExpectedPlugInException(typeof(ISuccession)); } ReadPlugIn(scenario.Succession); // Disturbance plug-ins nameLineNumbers.Clear(); // Parse called more than once const string DisturbancesRandomOrder = "DisturbancesRandomOrder"; while (!AtEndOfInput && CurrentName != DisturbancesRandomOrder && scenario.Outputs.Count == 0) { IEditablePlugIn <IDisturbance> disturbPlugIn; IEditablePlugIn <IOutput> outputPlugIn; ReadPlugIn(out disturbPlugIn, out outputPlugIn); if (disturbPlugIn != null) { scenario.Disturbances.InsertAt(scenario.Disturbances.Count, disturbPlugIn); } else { scenario.Outputs.InsertAt(scenario.Outputs.Count, outputPlugIn); } } // Check for optional DisturbancesRandomOrder parameter InputVar <bool> randomOrder = new InputVar <bool>(DisturbancesRandomOrder); if (ReadOptionalVar(randomOrder)) { scenario.DisturbancesRandomOrder = randomOrder.Value; } // Output plug-ins if (scenario.Outputs.Count == 0) { nameLineNumbers.Clear(); } while (!AtEndOfInput) { IEditablePlugIn <IOutput> plugIn = new EditablePlugIn <IOutput>(); ReadPlugIn(plugIn); scenario.Outputs.InsertAt(scenario.Outputs.Count, plugIn); } if (scenario.Outputs.Count == 0) { throw ExpectedPlugInException(typeof(IOutput)); } return(scenario.GetComplete()); }