public void ReadMethod_NumWithWhiteSpace()
 {
     StringReader reader = new StringReader(" \t -1,234 \n ");
     inputVar.ReadValue(reader);
     Assert.AreEqual(-1234, inputVar.Value.Actual);
     Assert.AreEqual("-1,234", inputVar.Value.String);
     Assert.AreEqual(3, inputVar.Index);
 }
 public void IntVar_MinusDigits()
 {
     StringReader reader = new StringReader("-1234");
     intVar.ReadValue(reader);
     Assert.AreEqual(-1234, intVar.Value.Actual);
     Assert.AreEqual("-1234", intVar.Value.String);
     Assert.AreEqual(0, intVar.Index);
 }
 public void ReadMethod_PlusDigits()
 {
     StringReader reader = new StringReader("+1,234");
     inputVar.ReadValue(reader);
     Assert.AreEqual(1234, inputVar.Value.Actual);
     Assert.AreEqual("+1,234", inputVar.Value.String);
     Assert.AreEqual(0, inputVar.Index);
 }
 public void IntVar_LeadingWhiteSpace()
 {
     StringReader reader = new StringReader(" \t -1234");
     intVar.ReadValue(reader);
     Assert.AreEqual(-1234, intVar.Value.Actual);
     Assert.AreEqual("-1234", intVar.Value.String);
     Assert.AreEqual(3, intVar.Index);
 }
        //---------------------------------------------------------------------

        /// <summary>
        /// Reads a year or a year expression.
        /// </summary>
        /// A year expression is an expression that refers to a year by its
        /// relation to either the scenario's starting or ending year.  The
        /// valid format for a year expression is:
        /// 
        /// <pre>
        ///    start
        ///    start+<i>integer</i>
        ///    end
        ///    end-<i>integer</i>
        /// </pre>
        /// </remarks>
        public static InputValue<int> ReadYear(StringReader reader,
                                               out int      index)
        {
            CheckForInitialization();
            TextReader.SkipWhitespace(reader);
            index = reader.Index;
            string word = TextReader.ReadWord(reader);
            return new InputValue<int>(ParseYear(word), word);
        }
 //---------------------------------------------------------------------
 private void PrintInputVarException(string input)
 {
     try {
         StringReader reader = new StringReader(input);
         seedAlgVar.ReadValue(reader);
     }
     catch (InputVariableException exc) {
         Data.Output.WriteLine(exc.Message);
         throw exc;
     }
 }
 public void ReadAgeOrRange_AgeWhitespacePercentage()
 {
     StringReader reader = new StringReader("66 ( 50% )\t");
     int index;
     eventHandlerCalled = false;
     expectedRange = new AgeRange(66, 66);
     expectedPercentage = Percentage.Parse("50%");
     InputValue<AgeRange> ageRange = PartialThinning.ReadAgeOrRange(reader, out index);
     Assert.IsTrue(eventHandlerCalled);
     Assert.AreEqual(0, index);
     Assert.AreEqual('\t', reader.Peek());
 }
 public void ReadAgeOrRange_RangeWhitespacePercentage()
 {
     StringReader reader = new StringReader(" 1-100 (22.2%)Hi");
     int index;
     eventHandlerCalled = false;
     expectedRange = new AgeRange(1, 100);
     expectedPercentage = Percentage.Parse("22.2%");
     InputValue<AgeRange> ageRange = PartialThinning.ReadAgeOrRange(reader, out index);
     Assert.IsTrue(eventHandlerCalled);
     Assert.AreEqual(1, index);
     Assert.AreEqual('H', reader.Peek());
 }
 public void ReadAgeOrRange_RangePercentage()
 {
     StringReader reader = new StringReader("30-75(10%)");
     int index;
     eventHandlerCalled = false;
     expectedRange = new AgeRange(30, 75);
     expectedPercentage = Percentage.Parse("10%");
     InputValue<AgeRange> ageRange = PartialThinning.ReadAgeOrRange(reader, out index);
     Assert.IsTrue(eventHandlerCalled);
     Assert.AreEqual(0, index);
     Assert.AreEqual(-1, reader.Peek());
 }
        //---------------------------------------------------------------------

        /// <summary>
        /// Reads a percentage for partial thinning of a cohort age or age
        /// range.
        /// </summary>
        /// <remarks>
        /// The percentage is bracketed by parentheses.
        /// </remarks>
        public static InputValue<Percentage> ReadPercentage(StringReader reader,
                                                            out int      index)
        {
            TextReader.SkipWhitespace(reader);
            index = reader.Index;

            //  Read left parenthesis
            int nextChar = reader.Peek();
            if (nextChar == -1)
                throw new InputValueException();  // Missing value
            if (nextChar != '(')
                throw MakeInputValueException(TextReader.ReadWord(reader),
                                              "Value does not start with \"(\"");
            StringBuilder valueAsStr = new StringBuilder();
            valueAsStr.Append((char) (reader.Read()));

            //  Read whitespace between '(' and percentage
            valueAsStr.Append(ReadWhitespace(reader));

            //  Read percentage
            string word = ReadWord(reader, ')');
            if (word == "")
                throw MakeInputValueException(valueAsStr.ToString(),
                                              "No percentage after \"(\"");
            valueAsStr.Append(word);
            Percentage percentage;
            try {
                percentage = Percentage.Parse(word);
            }
            catch (System.FormatException exc) {
                throw MakeInputValueException(valueAsStr.ToString(),
                                              exc.Message);
            }
            if (percentage < 0.0 || percentage > 1.0)
                throw MakeInputValueException(valueAsStr.ToString(),
                                              string.Format("{0} is not between 0% and 100%", word));

            //  Read whitespace and ')'
            valueAsStr.Append(ReadWhitespace(reader));
            char? ch = TextReader.ReadChar(reader);
            if (! ch.HasValue)
                throw MakeInputValueException(valueAsStr.ToString(),
                                              "Missing \")\"");
            valueAsStr.Append(ch.Value);
            if (ch != ')')
                throw MakeInputValueException(valueAsStr.ToString(),
                                              string.Format("Value ends with \"{0}\" instead of \")\"", ch));

            return new InputValue<Percentage>(percentage, valueAsStr.ToString());
        }
		/// <summary>
		/// Reads a plug-in name from a text reader and returns the
		/// information for the plug-in.
		/// </summary>
		public static InputValue<Edu.Wisc.Forest.Flel.Util.PlugIns.Info> Read(StringReader reader,
	                                                                          out int      index)
		{
			ReadMethod<string> strReadMethod = InputValues.GetReadMethod<string>();
			InputValue<string> name = strReadMethod(reader, out index);
			if (name.Actual.Trim(null) == "")
				throw new InputValueException(name.Actual,
				                              name.String + " is not a valid plug-in name.");
			Edu.Wisc.Forest.Flel.Util.PlugIns.Info info = (Edu.Wisc.Forest.Flel.Util.PlugIns.Info) PlugIns.Manager.GetInfo(name.Actual);
			if (info == null)
				throw new InputValueException(name.Actual,
				                              "No plug-in with the name \"{0}\".",
				                              name.Actual);
			return new InputValue<Edu.Wisc.Forest.Flel.Util.PlugIns.Info>(info, name.Actual);
		}
 public void NonEmptyString()
 {
     string str = "Hello World!";
     StringReader reader = new StringReader(str);
     int expectedIndex = 0;
     foreach (char expectedCh in str) {
         Assert.AreEqual(expectedIndex, reader.Index);
         int i = reader.Read();
         Assert.IsTrue(i != -1);
         Assert.AreEqual(expectedCh, (char) i);
         expectedIndex++;
     }
     Assert.AreEqual(expectedIndex, reader.Index);
     Assert.AreEqual(-1, reader.Peek());
 }
		//---------------------------------------------------------------------

		/// <summary>
		/// Reads a plug-in name from a text reader and returns the
		/// information for the plug-in.
		/// </summary>
		public static InputValue<PlugIns.PlugInInfo> Read(StringReader reader,
	                                                      out int      index)
		{
			ReadMethod<string> strReadMethod = InputValues.GetReadMethod<string>();
			InputValue<string> name = strReadMethod(reader, out index);
			if (name.Actual.Trim(null) == "")
				throw new InputValueException(name.Actual,
				                              name.String + " is not a valid plug-in name.");
			PlugIns.PlugInInfo info = installedPlugIns[name.Actual];
			if (info == null)
				throw new InputValueException(name.Actual,
				                              "No plug-in with the name \"{0}\".",
				                              name.Actual);
			return new InputValue<PlugIns.PlugInInfo>(info, name.Actual);
		}
        public void ReadBlock()
        {
            string str = "Four score and seven years ago ...";
            StringReader reader = new StringReader(str);
            char[] buffer = new char[str.Length];
            int blockSize = 5;

            for (int bufferIndex = 0; bufferIndex < buffer.Length; bufferIndex += blockSize) {
                Assert.AreEqual(bufferIndex, reader.Index);
                int countToRead;
                if (bufferIndex + blockSize > buffer.Length)
                    countToRead = buffer.Length - bufferIndex;
                else
                    countToRead = blockSize;
                Assert.AreEqual(countToRead, reader.Read(buffer, bufferIndex,
                                                         countToRead));
            }
            Assert.AreEqual(str.Length, reader.Index);
            Assert.AreEqual(-1, reader.Peek());
            Assert.AreEqual(str, new string(buffer));
        }
 //---------------------------------------------------------------------
 ///    <summary>
 /// Reads an integer input value for an effective seed-dispersal
 /// distance.
 /// </summary>
 /// <param name="reader">
 /// The string reader from which the input value is read.
 /// </param>
 /// <param name="index">
 /// The starting index in the reader's input stream where the input
 /// value was located.
 /// </param>
 /// <remarks>
 /// This method uses the registered ReadMethod for integer values.
 /// The input value "uni" is treated specially, and yield an integer
 /// input value equal to the Universal constant.
 /// </remarks>
 public static InputValue<int> ReadMethod(StringReader reader,
     out int      index)
 {
     ReadMethod<int> intRead = InputValues.GetReadMethod<int>();
     try {
         return intRead(reader, out index);
     }
     catch (InputValueException exc) {
         if (exc.Value == UniversalAsString) {
             index = reader.Index - exc.Value.Length;
             return new InputValue<int>(Universal, exc.Value);
         }
         else if (exc.Message.Contains("outside the range")) {
             //    Overflow exception with integer value
             throw;
         }
         else {
             string message = string.Format("\"{0}\" is not a valid integer or \"{1}\"",
                                            exc.Value, UniversalAsString);
             throw new InputValueException(exc.Value, message);
         }
     }
 }
        //---------------------------------------------------------------------
        /// <summary>
        /// Reads a cohort age or a range of ages (format: age-age) followed
        /// by an optional percentage for partial thinning.
        /// </summary>
        /// <remarks>
        /// The optional percentage is bracketed by parenthesis.
        /// </remarks>
        public static InputValue<AgeRange> ReadAgeOrRange(StringReader reader,
            out int      index)
        {
            TextReader.SkipWhitespace(reader);
            index = reader.Index;

            string word = ReadWord(reader, '(');
            if (word == "")
                throw new InputValueException();  // Missing value

            AgeRange ageRange = AgeRangeParsing.ParseAgeOrRange(word);

            //  Does a percentage follow?
            TextReader.SkipWhitespace(reader);
            if (reader.Peek() == '(') {
                int ignore;
                InputValue<Percentage> percentage = ReadPercentage(reader, out ignore);
                percentages[ageRange.Start] = percentage;
            }

            return new InputValue<AgeRange>(ageRange, word);
        }
 //---------------------------------------------------------------------
 /// <summary>
 /// Reads whitespace from a string reader.
 /// </summary>
 public static string ReadWhitespace(StringReader reader)
 {
     StringBuilder whitespace = new StringBuilder();
     int i = reader.Peek();
     while (i != -1 && char.IsWhiteSpace((char) i)) {
         whitespace.Append((char) reader.Read());
         i = reader.Peek();
     }
     return whitespace.ToString();
 }
 public void Read_SingleQuote_TextNoEnd()
 {
     StringReader reader = new StringReader("'Four score and ");
     PrintInputVarException(reader);
 }
 //---------------------------------------------------------------------
 private void ReadInputVar(string input)
 {
     StringReader reader = new StringReader(input);
     seedAlgVar.ReadValue(reader);
 }
        //---------------------------------------------------------------------

        /// <summary>
        /// Reads a cohort age or a range of ages (format: age-age) followed
        /// by an optional percentage for partial thinning.
        /// </summary>
        /// <remarks>
        /// The optional percentage is bracketed by parenthesis.
        /// </remarks>
        public static InputValue<AgeRange> ReadAgeOrRange(StringReader reader,
                                                          out int      index)
        {
            TextReader.SkipWhitespace(reader);
            index = reader.Index;

            string word = ReadWord(reader, '(');
            if (word == "")
                throw new InputValueException();  // Missing value

            AgeRange ageRange = BaseHarvest.InputParametersParser.ParseAgeOrRange(word);

            //  Does a percentage follow?
            TextReader.SkipWhitespace(reader);
            if (reader.Peek() == '(') {
                int ignore;
                InputValue<Percentage> percentage = ReadPercentage(reader, out ignore);
                if (ReadAgeOrRangeEvent != null)
                    ReadAgeOrRangeEvent(ageRange, percentage.Actual);
            }
            else {
                if (ReadAgeOrRangeEvent != null)
                    ReadAgeOrRangeEvent(ageRange, null);
            }

            return new InputValue<AgeRange>(ageRange, word);
        }
 public void Read_Whitespace()
 {
     StringReader reader = new StringReader("\t \n\r");
     PrintInputVarException(reader);
 }
        //----------------------------------------------------------------------

        //  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");
            
        }
        //---------------------------------------------------------------------

        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());
        }
 //---------------------------------------------------------------------
 private void CheckReadResults(string readerInitVal,
     string expectedReadResult,
     string readerValAfterRead)
 {
     StringReader reader = new StringReader(readerInitVal);
     strVar.ReadValue(reader);
     Assert.AreEqual(expectedReadResult, strVar.Value.Actual);
     Assert.AreEqual(readerValAfterRead, reader.ReadToEnd());
 }
 //---------------------------------------------------------------------
 private void CheckReadResults(string readerInitVal,
     string expectedReadResult)
 {
     StringReader reader = new StringReader(readerInitVal);
     strVar.ReadValue(reader);
     Assert.AreEqual(expectedReadResult, strVar.Value.Actual);
     Assert.AreEqual(-1, reader.Peek());
 }
 //---------------------------------------------------------------------
 private void PrintInputVarException(StringReader reader)
 {
     try {
         strVar.ReadValue(reader);
     }
     catch (InputVariableException exc) {
         Data.Output.WriteLine(exc.Message);
         throw exc;
     }
 }
 //---------------------------------------------------------------------
 private void TryRead(string input)
 {
     try {
         StringReader reader = new StringReader(input);
         inputVar.ReadValue(reader);
     }
     catch (InputVariableException exc) {
         Data.Output.WriteLine(exc.Message);
         Data.Output.WriteLine();
         Assert.AreEqual((InputVariable)inputVar, exc.Variable);
         throw;
     }
 }
 //---------------------------------------------------------------------
 /// <summary>
 /// Reads a word from a string reader.
 /// </summary>
 /// <remarks>
 /// The word is terminated by whitespace, the end of input, or a
 /// particular delimiter character.
 /// </remarks>
 public static string ReadWord(StringReader reader,
     char         delimiter)
 {
     StringBuilder word = new StringBuilder();
     int i = reader.Peek();
     while (i != -1 && ! char.IsWhiteSpace((char) i) && i != delimiter) {
         word.Append((char) reader.Read());
         i = reader.Peek();
     }
     return word.ToString();
 }
 //---------------------------------------------------------------------
 private bool ReadVariable(InputVariable var,
     bool          optional)
 {
     if (var == null)
         throw new System.ArgumentNullException();
     if (VariableNameMatches(var.Name, optional)) {
         //  Read the variable's value
         StringReader strReader = new StringReader(textAfterName);
         try {
             var.ReadValue(strReader);
         }
         catch (InputVariableException exc) {
             throw new LineReaderException(reader, exc);
         }
         TextReader.SkipWhitespace(strReader);
         string textAfterValue = strReader.ReadToEnd();
         if (textAfterValue.Length == 0)
             return true;
         string message = string.Format("Extra text after the value for \"{0}\"",
                                        var.Name);
         throw ExtraTextException(message, textAfterValue);
     }
     return false;
 }
 public void ReadMethod_UniWithWhitespace()
 {
     StringReader reader = new StringReader(" \t uni \n ");
     inputVar.ReadValue(reader);
     Assert.AreEqual(EffectiveSeedDist.Universal, inputVar.Value.Actual);
     Assert.AreEqual("uni", inputVar.Value.String);
     Assert.AreEqual(3, inputVar.Index);
 }