Exemple #1
0
        public bool IsCriteriaMet(Hashtable hashAttributeValue)
        {
            if (string.IsNullOrWhiteSpace(_criteria))
            {
                return(true);
            }
            object[] input = new object[_attributesCriteria.Count];
            int      i     = 0;

            foreach (String str in _attributesCriteria)
            {
                input[i] = hashAttributeValue[str];
                i++;
            }
            try
            {
                if (_evaluate.m_methodInfo == null)
                {
                    if (_evaluate.m_cr == null)
                    {
                        _evaluate.BuildClass(_evaluate.Expression, false, cgOMS.Prefix + _table + "_" + _column + "_" + _performanceID);
                        _evaluate.CompileAssembly();
                        SimulationMessaging.SaveSerializedCalculateEvaluate(cgOMS.Prefix + _table, _column, _performanceID, _evaluate);
                    }
                }
                bool isMet = (bool)_evaluate.RunMethod(input);
                return(isMet);
            }
            catch (Exception exc)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error in RunMethod.   " + _evaluate.OriginalInput + " " + exc.Message));
                return(false);
            }
        }
Exemple #2
0
        public bool CalculateRemainingLifePiecewise(Hashtable hashAttributeValues, Hashtable hashPrevious, out double dRL)
        {
            double dLimit;
            double dRemainingLife = 0;

            dRL = dRemainingLife;

            if (!SimulationMessaging.GetDeficientLevel(this.Attribute, hashPrevious, out dLimit))
            {
                return(false);
            }
            this.RemainingLifeLimit = dLimit;

            double dValue = double.Parse(hashAttributeValues[this.Attribute].ToString());

            if (Shift)
            {
                double dAge = double.Parse(hashAttributeValues["AGE"].ToString());
                dRL = this.PiecewiseEquation.GetRemainingLife(dValue, dLimit, dAge);
            }
            else
            {
                dRL = this.PiecewiseEquation.GetRemainingLife(dValue, dLimit);
            }
            return(true);
        }
Exemple #3
0
        public bool LoadScheduled(List <Treatments> availableTreatments)
        {
            var select = "SELECT SCHEDULEDID, SCHEDULEDTREATMENTID, SCHEDULEDYEAR FROM SCHEDULED WHERE TREATMENTID='" + this.TreatmentID + "'";

            DataSet ds;

            try
            {
                ds = DBMgr.ExecuteQuery(select);


                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var scheduledId          = int.Parse(row["SCHEDULEDID"].ToString());
                    var scheduledTreatmentId = row["SCHEDULEDTREATMENTID"].ToString();
                    var scheduledYear        = int.Parse(row["SCHEDULEDYEAR"].ToString());
                    var scheduledTreatment   = availableTreatments.Find(t => t.TreatmentID == scheduledTreatmentId);

                    if (scheduledTreatment != null)
                    {
                        _scheduleds.Add(new Scheduled(scheduledId, scheduledTreatment, scheduledYear));
                    }
                }
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(
                    new SimulationMessage("Fatal Error: Opening SCHEDULED table. SQL Message - " + exception.Message));
                return(false);
            }
            return(true);
        }
Exemple #4
0
 public double GetCost(Hashtable hashAttributeValue)
 {
     if (this._isCompoundTreatment)
     {
         CompoundTreatment compoundTreatment = Simulation.CompoundTreatments.Find(delegate(CompoundTreatment ct) { return(ct.CompoundTreatmentName == _compoundTreatment); });
         return(compoundTreatment.GetCost(hashAttributeValue));
     }
     else
     {
         int      i     = 0;
         object[] input = new object[_attributesEquation.Count];
         foreach (String str in _attributesEquation)
         {
             if (hashAttributeValue[str] != null)
             {
                 input[i] = hashAttributeValue[str];
             }
             else
             {
                 input[i] = 0;
             }
             i++;
         }
         try
         {
             object result = _calculate.RunMethod(input);
             return((double)result);
         }
         catch (Exception exc)
         {
             SimulationMessaging.AddMessage(new SimulationMessage("Error in RunMethod. " + exc.Message));
             return(0);
         }
     }
 }
Exemple #5
0
        private bool GetCalculatedFieldData()
        {
            if (m_listCalculated == null)
            {
                m_listCalculated = new List <Deteriorate>();
            }
            String  strSelect = "SELECT ATTRIBUTE_,EQUATION,CRITERIA FROM " + cgOMS.Prefix + "ATTRIBUTES_CALCULATED";
            DataSet ds;

            try
            {
                ds = DBMgr.ExecuteQuery(strSelect);
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving Calculated Field data. SQL Message - " + exception.Message));
                return(false);
            }

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                Deteriorate deteriorate = new Deteriorate();

                deteriorate.Attribute = row["ATTRIBUTE_"].ToString();
                deteriorate.Equation  = row["EQUATION"].ToString();
                deteriorate.Criteria  = row["CRITERIA"].ToString();
                m_listCalculated.Add(deteriorate);
            }


            return(true);
        }
Exemple #6
0
        public bool LoadSupersedes(object APICall, IMongoCollection <SimulationModel> Simulations, string m_strSimulationID)
        {
            try
            {
                var     select = "SELECT SUPERSEDE_ID, SUPERSEDE_TREATMENT_ID, CRITERIA FROM SUPERSEDES WHERE TREATMENT_ID='" + this.TreatmentID + "'";
                DataSet ds     = DBMgr.ExecuteQuery(select);

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var supersedeId          = int.Parse(row["SUPERSEDE_ID"].ToString());
                    var supersedeTreatmentId = int.Parse(row["SUPERSEDE_TREATMENT_ID"].ToString());
                    var criteria             = "";

                    if (row["CRITERIA"] != DBNull.Value)
                    {
                        criteria = row["CRITERIA"].ToString();
                    }

                    Supersedes.Add(new Supersede(supersedeId, supersedeTreatmentId, criteria));
                }


                foreach (var supersede in Supersedes)
                {
                    foreach (String str in supersede.Criteria.CriteriaAttributes)
                    {
                        if (!SimulationMessaging.IsAttribute(str))
                        {
                            SimulationMessaging.AddMessage(new SimulationMessage("Error: " + str + " which is used by the Supersede criteria is not present in the database."));
                            if (APICall.Equals(true))
                            {
                                var updateStatus = Builders <SimulationModel> .Update
                                                   .Set(s => s.status, "Error: " + str + " which is used by the Supersede criteria is not present in the database");

                                Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                            }
                        }
                        if (!_attributes.Contains(str))
                        {
                            _attributes.Add(str);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(
                    new SimulationMessage("Fatal Error: Opening SUPERSEDE table. SQL Message - " + exception.Message));
                if (APICall.Equals(true))
                {
                    var updateStatus = Builders <SimulationModel> .Update
                                       .Set(s => s.status, "Fatal Error: Opening SUPERSEDE table. SQL Message - " + exception.Message);

                    Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                }
                return(false);
            }
            return(true);
        }
Exemple #7
0
 public ConditionalRSL(String attribute, Criterias criteria)
 {
     BinValues      = new Dictionary <int, double>();
     _values        = null;
     this.Attribute = attribute;
     _criteria      = criteria;
     _isAscending   = SimulationMessaging.GetAttributeAscending(attribute);
 }
Exemple #8
0
        public bool LoadSupersedes()
        {
            try
            {
                var     select = "SELECT SUPERSEDE_ID, SUPERSEDE_TREATMENT_ID, CRITERIA FROM SUPERSEDES WHERE TREATMENT_ID='" + this.TreatmentID + "'";
                DataSet ds     = DBMgr.ExecuteQuery(select);

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var supersedeId          = int.Parse(row["SUPERSEDE_ID"].ToString());
                    var supersedeTreatmentId = int.Parse(row["SUPERSEDE_TREATMENT_ID"].ToString());
                    var criteria             = "";

                    if (row["CRITERIA"] != DBNull.Value)
                    {
                        criteria = row["CRITERIA"].ToString();
                    }

                    Supersedes.Add(new Supersede(supersedeId, supersedeTreatmentId, criteria));
                }


                foreach (var supersede in Supersedes)
                {
                    foreach (String str in supersede.Criteria.CriteriaAttributes)
                    {
                        if (!SimulationMessaging.IsAttribute(str))
                        {
                            SimulationMessaging.AddMessage(new SimulationMessage("Error: " + str + " which is used by the Supersede criteria is not present in the database."));
                        }
                        if (!_attributes.Contains(str))
                        {
                            _attributes.Add(str);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(
                    new SimulationMessage("Fatal Error: Opening SUPERSEDE table. SQL Message - " + exception.Message));
                return(false);
            }
            return(true);
        }
Exemple #9
0
        internal void SetFunction(string equation)
        {
            _costEquation = equation;

            // Get list of attributes
            _attributesEquation = SimulationMessaging.ParseAttribute(_costEquation);
            if (_attributesEquation == null)
            {
                return;
            }

            if (_calculate == null)
            {
                _calculate = new CalculateEvaluate.CalculateEvaluate();

                //Allow functions to utilize strings and dates.
                string        functionEquation = _costEquation;
                List <string> attributes       = SimulationMessaging.ParseAttribute(functionEquation);

                foreach (String attribute in attributes)
                {
                    String attributeType = SimulationMessaging.GetAttributeType(attribute);
                    if (attributeType == "STRING")
                    {
                        String oldValue = "[" + attribute + "]";
                        String newValue = "[@" + attribute + "]";
                        functionEquation = functionEquation.Replace(oldValue, newValue);
                    }
                    else if (attributeType == "DATETIME")
                    {
                        String oldValue = "[" + attribute + "]";
                        String newValue = "[$" + attribute + "]";
                        functionEquation = functionEquation.Replace(oldValue, newValue);
                    }
                }

                _calculate.BuildFunctionClass(functionEquation, "double", cgOMS.Prefix + "COSTS_BINARY_EQUATION_" + CostID);
                if (_calculate.m_cr == null)
                {
                    _compilerResultsEquation = _calculate.CompileAssembly();
                    SimulationMessaging.SaveSerializedCalculateEvaluate(cgOMS.Prefix + "COSTS", "BINARY_EQUATION", CostID, _calculate);
                }
            }
        }
Exemple #10
0
        Hashtable m_hashPavmentCoefficient;// Key is pavement type.  Value is list of doubles.



        public CRS()
        {
            if (DBMgr.IsTableInDatabase("CRS_COEFFICIENT"))
            {
                String strSelect = "SELECT PAVEMENT,A,B,C,D FROM CRS_COEFFICIENT";
                try
                {
                    m_hashPavmentCoefficient = new Hashtable();
                    DataSet ds = DBMgr.ExecuteQuery(strSelect);
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        List <double> listCoefficient = new List <double>();

                        double dCoefficient = 0;
                        double.TryParse(dr[1].ToString(), out dCoefficient);
                        listCoefficient.Add(dCoefficient);

                        dCoefficient = 0;
                        double.TryParse(dr[2].ToString(), out dCoefficient);
                        listCoefficient.Add(dCoefficient);

                        dCoefficient = 0;
                        double.TryParse(dr[3].ToString(), out dCoefficient);
                        listCoefficient.Add(dCoefficient);

                        dCoefficient = 0;
                        double.TryParse(dr[4].ToString(), out dCoefficient);
                        listCoefficient.Add(dCoefficient);

                        m_hashPavmentCoefficient.Add(dr[0].ToString(), listCoefficient);
                    }
                }
                catch (Exception exception)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("CRS attribute load error.  Make sure CRS_COEFFICIENT table exists: " + exception.Message));
                }
            }
            else
            {
                m_hashPavmentCoefficient = new Hashtable();
            }
        }
Exemple #11
0
        public double ApplyDeterioration(Hashtable hashAttributeValue)
        {
            object[] input = new object[_attributesEquation.Count];

            int i = 0;

            foreach (String str in _attributesEquation)
            {
                input[i] = hashAttributeValue[str];
                i++;
            }

            double dReturn = 0;

            try
            {
                dReturn = (double)_calculate.RunMethod(input);
            }
            catch { SimulationMessaging.AddMessage(new SimulationMessage("Error: solving calculated fields for Compound Treatment.")); }
            return(dReturn);
        }
Exemple #12
0
        /// <summary>
        /// Get consequence given an input value set.
        /// </summary>
        /// <param name="hashAttributeValue"></param>
        /// <returns></returns>
        public double GetConsequence(Hashtable hashAttributeValue)
        {
            int i = 0;

            object[] input = new object[_attributesEquation.Count];
            foreach (String str in _attributesEquation)
            {
                input[i] = hashAttributeValue[str];
                i++;
            }
            try
            {
                object result = _calculate.RunMethod(input);
                return((double)result);
            }
            catch (Exception exc)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error in RunMethod. " + exc.Message));
                return(0);
            }
        }
Exemple #13
0
        public bool IsCriteriaMet(Hashtable hashAttributeValue)
        {
            if (string.IsNullOrWhiteSpace(m_strCriteria))
            {
                return(true);
            }

            object[] input = new object[this.m_listAttributesCriteria.Count];

            int i = 0;

            foreach (String str in this.m_listAttributesCriteria)
            {
                input[i] = hashAttributeValue[str];
                i++;
            }
            try
            {
                if (evaluate.m_methodInfo == null)
                {
                    if (evaluate.m_cr == null)
                    {
                        evaluate.BuildClass(evaluate.Expression, false, cgOMS.Prefix + _tableName + "_" + _columnName + "_" + _ID);
                        evaluate.CompileAssembly();
                        if (_tableName != null)
                        {
                            SimulationMessaging.SaveSerializedCalculateEvaluate(cgOMS.Prefix + _tableName, _columnName, _ID, evaluate);
                        }
                    }
                }

                Object result = this.Evaluate.RunMethod(input);
                return(bool.Parse(result.ToString()));
            }
            catch (Exception exc)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error in RunMethod.   " + Evaluate.OriginalInput + " " + exc.Message));
                return(false);
            }
        }
Exemple #14
0
        /// <summary>
        /// True if this target is met.
        /// </summary>
        /// <returns></returns>
        public bool IsTargetMet(int nYear)
        {
            double dTargetArea = 0;

            if (m_hashYearTargetArea.Contains(nYear))
            {
                dTargetArea = (double)this.m_hashYearTargetArea[nYear];
            }


            double dSumArea = 0;

            if (this.m_hashYearSumArea.Contains(nYear))
            {
                dSumArea = (double)this.m_hashYearSumArea[nYear];
            }
            if (dSumArea == 0)
            {
                return(true);
            }

            double dTarget = dTargetArea / dSumArea;
            double dGoal   = this.Target;

            if (SimulationMessaging.GetAttributeAscending(this.Attribute))
            {
                if (dGoal < dTarget)
                {
                    return(true);
                }
            }
            else
            {
                if (dGoal > dTarget)
                {
                    return(true);
                }
            }
            return(false);
        }
Exemple #15
0
        public bool LoadScheduled(List <Treatments> availableTreatments, object APICall, IMongoCollection <SimulationModel> Simulations, string m_strSimulationID)
        {
            var select = "SELECT SCHEDULEDID, SCHEDULEDTREATMENTID, SCHEDULEDYEAR FROM SCHEDULED WHERE TREATMENTID='" + this.TreatmentID + "'";

            DataSet ds;

            try
            {
                ds = DBMgr.ExecuteQuery(select);


                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    var scheduledId          = int.Parse(row["SCHEDULEDID"].ToString());
                    var scheduledTreatmentId = row["SCHEDULEDTREATMENTID"].ToString();
                    var scheduledYear        = int.Parse(row["SCHEDULEDYEAR"].ToString());
                    var scheduledTreatment   = availableTreatments.Find(t => t.TreatmentID == scheduledTreatmentId);

                    if (scheduledTreatment != null)
                    {
                        _scheduleds.Add(new Scheduled(scheduledId, scheduledTreatment, scheduledYear));
                    }
                }
            }
            catch (Exception exception)
            {
                SimulationMessaging.AddMessage(
                    new SimulationMessage("Fatal Error: Opening SCHEDULED table. SQL Message - " + exception.Message));
                if (APICall.Equals(true))
                {
                    var updateStatus = Builders <SimulationModel> .Update
                                       .Set(s => s.status, "Fatal Error: Opening SCHEDULED table. SQL Message - " + exception.Message);

                    Simulations.UpdateOne(s => s.simulationId == Convert.ToInt32(m_strSimulationID), updateStatus);
                }
                return(false);
            }
            return(true);
        }
Exemple #16
0
        public RemainingLife(int remainingLifeId, string attribute, double remainingLifeLimit, string criteria)
        {
            RemainingLifeId    = remainingLifeId;
            Attribute          = attribute;
            RemainingLifeLimit = remainingLifeLimit;

            Criteria = new Criterias("REMAINING_LIFE", "BINARY_CRITERIA", RemainingLifeId.ToString());
            byte[] assemblyCriteria = null;
            string currentCriteria  = "";

            if (!string.IsNullOrWhiteSpace(criteria))
            {
                currentCriteria = Simulation.ConvertOMSAttribute(criteria);
            }
            assemblyCriteria = SimulationMessaging.GetSerializedCalculateEvaluate("REMAINING_LIFE", "BINARY_CRITERIA", RemainingLifeId.ToString(), assemblyCriteria);
            if (assemblyCriteria != null && assemblyCriteria.Length > 0)
            {
                Criteria.Evaluate = (CalculateEvaluate.CalculateEvaluate)AssemblySerialize.DeSerializeObjectFromByteArray(assemblyCriteria);
                if (Criteria.Evaluate.OriginalInput != currentCriteria)
                {
                    Criteria.Evaluate = null;
                }
            }

            if (Criteria.Evaluate != null && Criteria.Evaluate.m_cr != null)
            {
                if (!File.Exists(Criteria.Evaluate.m_cr.PathToAssembly))
                {
                    Criteria.Evaluate = null;
                }
            }

            Criteria.Criteria = criteria;
            foreach (String str in Criteria.Errors)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Supersede criteria for " + criteria + " :" + str));
            }
        }
Exemple #17
0
        public double IterateSpanPiecewise(Hashtable hashAttributeValues, double span, out bool bOutOfRange)
        {
            double apparentAge = 0;

            bOutOfRange = false;
            double dValue  = double.Parse(hashAttributeValues[this.Attribute].ToString());
            double dAnswer = double.NaN;
            double dAge    = 0;

            if (Shift)
            {
                dAge    = double.Parse(hashAttributeValues["AGE"].ToString());
                dAnswer = this.PiecewiseEquation.GetNextValue(dValue, dAge, span, out apparentAge).Value;
            }
            else
            {
                dAnswer = this.PiecewiseEquation.GetNextValue(dValue, span).Value;
            }

            double dMinimum;
            double dMaximum;

            if (SimulationMessaging.GetAttributeMinimum(this.Attribute, out dMinimum))
            {
                if (dMinimum > dAnswer)
                {
                    dAnswer = dMinimum;
                }
            }
            if (SimulationMessaging.GetAttributeMaximum(this.Attribute, out dMaximum))
            {
                if (dMaximum < dAnswer)
                {
                    dAnswer = dMaximum;
                }
            }
            return(dAnswer);
        }
Exemple #18
0
        public SplitTreatment(string splitTreamentId, string description, string criteria, List <ISplitTreatmentLimit> limits)
        {
            Id          = splitTreamentId;
            Description = description;
            Limits      = limits;
            Criteria    = new Criterias("SPLIT_TREATMENT", "BINARY_CRITERIA", splitTreamentId);
            byte[] assemblyCriteria = null;
            string currentCriteria  = "";

            if (!string.IsNullOrWhiteSpace(criteria))
            {
                currentCriteria = Simulation.ConvertOMSAttribute(criteria);
            }
            assemblyCriteria = SimulationMessaging.GetSerializedCalculateEvaluate("SPLIT_TREATMENT", "BINARY_CRITERIA", splitTreamentId, assemblyCriteria);
            if (assemblyCriteria != null && assemblyCriteria.Length > 0)
            {
                Criteria.Evaluate = (CalculateEvaluate.CalculateEvaluate)RoadCareGlobalOperations.AssemblySerialize.DeSerializeObjectFromByteArray(assemblyCriteria);
                if (Criteria.Evaluate.OriginalInput != currentCriteria)
                {
                    Criteria.Evaluate = null;
                }
            }

            if (Criteria.Evaluate != null && Criteria.Evaluate.m_cr != null)
            {
                if (!File.Exists(Criteria.Evaluate.m_cr.PathToAssembly))
                {
                    Criteria.Evaluate = null;
                }
            }

            Criteria.Criteria = criteria;
            foreach (String str in Criteria.Errors)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Split treatment criteria for " + criteria + " :" + str));
            }
        }
Exemple #19
0
        public BudgetCriteria(int budgetCriteriaId, string budgetName, string criteria)
        {
            BudgetCriteriaId = budgetCriteriaId;
            BudgetName       = budgetName;

            Criteria = new Criterias("BUDGET", "BINARY_CRITERIA", BudgetCriteriaId.ToString());
            byte[] assemblyCriteria = null;
            string currentCriteria  = "";

            if (!string.IsNullOrWhiteSpace(criteria))
            {
                currentCriteria = Simulation.ConvertOMSAttribute(criteria);
            }
            assemblyCriteria = SimulationMessaging.GetSerializedCalculateEvaluate("BUDGET", "BINARY_CRITERIA", BudgetCriteriaId.ToString(), assemblyCriteria);
            if (assemblyCriteria != null && assemblyCriteria.Length > 0)
            {
                Criteria.Evaluate = (CalculateEvaluate.CalculateEvaluate)AssemblySerialize.DeSerializeObjectFromByteArray(assemblyCriteria);
                if (Criteria.Evaluate.OriginalInput != currentCriteria)
                {
                    Criteria.Evaluate = null;
                }
            }

            if (Criteria.Evaluate != null && Criteria.Evaluate.m_cr != null)
            {
                if (!File.Exists(Criteria.Evaluate.m_cr.PathToAssembly))
                {
                    Criteria.Evaluate = null;
                }
            }

            Criteria.Criteria = criteria;
            foreach (String str in Criteria.Errors)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Supersede criteria for " + criteria + " :" + str));
            }
        }
Exemple #20
0
        /// <summary>
        /// Sets the function version of consequences.
        /// </summary>
        /// <param name="equation"></param>
        public void SetFunction(string equation)
        {
            _consequenceEquation = equation;
            IsEquation           = true;
            _attributesEquation  = SimulationMessaging.ParseAttribute(_consequenceEquation);
            if (_calculate == null)
            {
                _calculate = new CalculateEvaluate.CalculateEvaluate();
                string functionEquation = _consequenceEquation;

                foreach (String attribute in _attributesEquation)
                {
                    String attributeType = SimulationMessaging.GetAttributeType(attribute);
                    if (attributeType == "STRING")
                    {
                        String oldValue = "[" + attribute + "]";
                        String newValue = "[@" + attribute + "]";
                        functionEquation = functionEquation.Replace(oldValue, newValue);
                    }
                    else if (attributeType == "DATETIME")
                    {
                        String oldValue = "[" + attribute + "]";
                        String newValue = "[$" + attribute + "]";
                        functionEquation = functionEquation.Replace(oldValue, newValue);
                    }
                }

                _calculate.BuildFunctionClass(_consequenceEquation, "double", cgOMS.Prefix + "CONSEQUENCES_BINARY_EQUATION_" + _id);

                if (_calculate.m_cr == null)
                {
                    _compilerResultsEquation = _calculate.CompileAssembly();
                    SimulationMessaging.SaveSerializedCalculateEvaluate(cgOMS.Prefix + "CONSEQUENCES", "BINARY_EQUATION", _id, _calculate);
                }
            }
        }
Exemple #21
0
        public void LoadBudgets()
        {
            string[] budgets = BudgetOrderString.Split(',');
            String   strBudget;

            for (int i = 0; i < budgets.Length; i++)
            {
                strBudget = budgets[i];
                m_listBudgetOrder.Add(strBudget);
            }

            String  strSelect = "SELECT YEAR_,BUDGETNAME,AMOUNT FROM " + cgOMS.Prefix + "YEARLYINVESTMENT WHERE SIMULATIONID='" + this.InvestmentID + "' ORDER BY YEAR_";
            DataSet ds        = null;

            try
            {
                ds = DBMgr.ExecuteQuery(strSelect);
            }
            catch (Exception ex)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Loading YEARLYINVESTMENT table." + ex.Message));
                return;
            }

            String strYear;

            String strAmount;

            MaximumYear = Int32.MinValue;

            foreach (DataRow row in ds.Tables[0].Rows)
            {
                strYear = row[0].ToString();
                var year = Convert.ToInt32(strYear);
                if (year > MaximumYear)
                {
                    MaximumYear = year;
                }
                strBudget = row[1].ToString();
                strAmount = row[2].ToString();

                if (BudgetYear.Contains(strBudget))
                {
                    Hashtable hashYearAmount         = (Hashtable)BudgetYear[strBudget];
                    Hashtable hashYearAmountOriginal = (Hashtable)BudgetYearOriginal[strBudget];

                    m_hashBudgetYear.Remove(strBudget);
                    m_hashBudgetYearOriginal.Remove(strBudget);

                    if (strAmount == "")
                    {
                        hashYearAmount.Add(strYear, 0.0);
                        hashYearAmountOriginal.Add(strYear, 0.0);
                    }
                    else
                    {
                        hashYearAmount.Add(strYear, float.Parse(strAmount));
                        hashYearAmountOriginal.Add(strYear, float.Parse(strAmount));
                    }

                    BudgetYear.Add(strBudget, hashYearAmount);
                    BudgetYearOriginal.Add(strBudget, hashYearAmountOriginal);
                }
                else
                {
                    Hashtable hashYearAmount         = new Hashtable();
                    Hashtable hashYearAmountOriginal = new Hashtable();

                    if (strAmount == "")
                    {
                        hashYearAmount.Add(strYear, 0.0);
                        hashYearAmountOriginal.Add(strYear, 0.0);
                    }
                    else
                    {
                        hashYearAmount.Add(strYear, float.Parse(strAmount));
                        hashYearAmountOriginal.Add(strYear, float.Parse(strAmount));
                    }



                    BudgetYear.Add(strBudget, hashYearAmount);
                    BudgetYearOriginal.Add(strBudget, hashYearAmountOriginal);
                }
            }

            foreach (var budget in BudgetYear.Keys)
            {
                var hashYearAmount         = (Hashtable)BudgetYear[budget];
                var hashYearAmountOriginal = (Hashtable)BudgetYearOriginal[budget];

                for (int year = MaximumYear + 1; year < MaximumYear + 101; year++)
                {
                    hashYearAmount.Add(year.ToString(), hashYearAmount[MaximumYear.ToString()]);
                    hashYearAmountOriginal.Add(year.ToString(), hashYearAmountOriginal[MaximumYear.ToString()]);
                }
            }
        }
Exemple #22
0
        public static object ConvertToRoadCareObject(object value, string attribute)
        {
            string type = "";

            switch (attribute)
            {
            case "LENGTH":
            case "AREA":
                type = "NUMBER";
                break;

            default:
                type = SimulationMessaging.GetAttributeType(attribute);
                break;
            }
            object rcValue = null;

            if (type == "STRING")
            {
                if (value == null)
                {
                    rcValue = null;
                }
                else
                {
                    rcValue = value.ToString();
                }
            }
            else if (type == "DATETIME")
            {
                if (value == null)
                {
                    rcValue = null;
                }
                else
                {
                    rcValue = Convert.ToDateTime(value);
                }
            }
            else
            {
                if (value == null)
                {
                    rcValue = null;
                }
                else
                {
                    if (String.IsNullOrWhiteSpace(value.ToString()))
                    {
                        rcValue = null;
                    }
                    else //At this point this should only contain valid numbers, catch block is in case.
                    {
                        try
                        {
                            rcValue = Convert.ToDouble(value);
                        }
                        catch
                        {
                            rcValue = null;
                        }
                    }
                }
            }
            return(rcValue);
        }
Exemple #23
0
        public static string GetDecisionEngineCritera(string omsCriteria)
        {
            omsCriteria = omsCriteria.Replace("[]", "cgde_timeperiodof"); // Square brackets denote variables.  [] messes this up.
            string        deCriteria  = "";
            List <string> expressions = new List <string>();              //List of omsExpressions

            int lastOpen = -1;
            int i        = 0;

            while (i < omsCriteria.Length)//Find all expressions
            {
                if (omsCriteria[i] == '(')
                {
                    lastOpen = i;
                }
                if (omsCriteria[i] == ')' && lastOpen >= 0)
                {
                    string expression = omsCriteria.Substring(lastOpen, i - lastOpen + 1);
                    if (expression.Contains("["))
                    {
                        byte   numberExpressions = (byte)expressions.Count;
                        string placeHolder       = numberExpressions.ToString("x2");
                        expressions.Add(expression);
                        omsCriteria = omsCriteria.Replace(expression, placeHolder);
                        i           = 0;
                    }
                    lastOpen = -1;
                }
                else
                {
                    i++;
                }
            }

            omsCriteria = omsCriteria.Replace("AND", "&&").Replace("OR", "||").Replace("NOT", "!");

            if (CheckMatchingParentheses(omsCriteria))
            {
                byte index = 0;
                deCriteria = omsCriteria;
                foreach (string expression in expressions)
                {
                    string variable  = GetVariable(expression);
                    string fieldType = SimulationMessaging.GetAttributeType(variable);
                    if (fieldType != null)
                    {
                        string placeholder  = index.ToString("x2");
                        string deExpression = ConvertToDecisionEngine(expression, fieldType);
                        deCriteria = deCriteria.Replace(placeholder, deExpression);
                    }
                    else
                    {
                        deCriteria = "Variable = " + variable + " not found.";
                        break;
                    }
                    index++;
                }
            }
            else
            {
                deCriteria = "Parentheses in input criteria do not match.";
            }
            return(deCriteria);
        }
Exemple #24
0
        public bool CalculateRemainingLifeEquation(Hashtable hashAttributeValues, Hashtable hashPrevious, out double dRL)
        {
            double increment;
            double delta;
            double ratioAnswer    = 0;
            int    iAnswer        = -1;
            double ratioDeficient = 0;
            int    iDeficient     = -1;
            double dRemainingLife = 0;

            dRL = dRemainingLife;

            double dValue = double.Parse(hashAttributeValues[this.Attribute].ToString());

            if (!_isAgeOnly)
            {
                Solve(hashPrevious);
            }
            double dAge = 0;

            if (Shift)
            {
                dAge = double.Parse(hashAttributeValues["AGE"].ToString());
            }

            double dLimit;

            if (!SimulationMessaging.GetDeficientLevel(this.Attribute, hashPrevious, out dLimit))
            {
                return(false);
            }
            this.RemainingLifeLimit = dLimit;
            for (int i = 0; i < 98; i++)
            {
                //This eliminates ascending / descending problem.  Just looking for a number in between.
                if ((_answer[i] >= dValue && dValue > _answer[i + 1]) || (_answer[i] <= dValue && dValue < _answer[i + 1]))
                {
                    delta     = dValue - _answer[i + 1];
                    increment = _answer[i] - _answer[i + 1];
                    if (increment == 0)
                    {
                        ratioAnswer = 0;
                    }
                    else
                    {
                        ratioAnswer = 1 - (delta / increment);
                    }
                    iAnswer = i;
                }


                if ((_answer[i] >= this.RemainingLifeLimit && this.RemainingLifeLimit > _answer[i + 1]) || (_answer[i] <= this.RemainingLifeLimit && this.RemainingLifeLimit < _answer[i + 1]))
                {
                    delta     = this.RemainingLifeLimit - _answer[i + 1];
                    increment = _answer[i] - _answer[i + 1];
                    if (increment == 0)
                    {
                        ratioDeficient = 0;
                    }
                    else
                    {
                        ratioDeficient = 1 - (delta / increment);
                    }
                    iDeficient = i;
                }

                if (iAnswer >= 0 && iDeficient >= 0)
                {
                    //Then we have solve remaining life
                    dRemainingLife = ((double)iDeficient + ratioDeficient) - ((double)iAnswer + ratioAnswer);
                    dRL            = dRemainingLife;

                    if (Shift && i > 0 && dAge > 0)
                    {
                        double dApparentAge = (double)iAnswer + ratioAnswer;
                        double dAgeRatio    = dApparentAge / (dAge);
                        dRL = dRL / dAgeRatio;
                    }

                    if (dRL < 0)
                    {
                        dRL = 0;
                    }
                    return(true);
                }
            }

            if (iAnswer >= 0 && iDeficient == -1)
            {
                dRemainingLife = 99;
                dRL            = dRemainingLife;
                return(true);
            }

            if (iDeficient >= 0 && iAnswer == -1)
            {
                dRemainingLife = 0;
                dRL            = dRemainingLife;
                return(true);
            }
            dRL = 0;
            return(false);
        }
Exemple #25
0
        public void MoveBudgetAcross(string budget, string year, Priorities priority)
        {
            //Get next budget.
            var nextBudget = GetNextBudget(budget);

            //Add what is left from current budget (and priority) to the the next budget.

            string    budgetCheck = budget.Trim();
            Hashtable hashYearAmount;
            Hashtable hashYearAmountOriginal;
            float     available = 0;
            float     original  = 0;

            //Budget not defined
            try
            {
                if (!BudgetYear.Contains(budgetCheck))
                {
                    return;
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year. " + e.Message));
                throw e;
            }


            try
            {
                hashYearAmount = (Hashtable)BudgetYear[budgetCheck];
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year. " + e.Message));
                throw e;
            }
            try
            {
                if (!hashYearAmount.Contains(year))
                {
                    return;
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking year amount. " + e.Message));
                throw e;
            }

            try
            {
                available = (float)hashYearAmount[year];
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount. " + e.Message));
                throw e;
            }

            try
            {
                if (!BudgetYearOriginal.Contains(budgetCheck))
                {
                    return;
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year original. " + e.Message));
                throw e;
            }

            try
            {
                hashYearAmountOriginal = (Hashtable)BudgetYearOriginal[budgetCheck];
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year original. " + e.Message));
                throw e;
            }


            try
            {
                if (!hashYearAmountOriginal.Contains(year))
                {
                    return;
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking year amount original. " + e.Message));
                throw e;
            }

            try
            {
                original = (float)hashYearAmountOriginal[year];
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount original. " + e.Message));
                throw e;
            }


            if (original <= 0)
            {
                return;
            }
            var percent = (1 - available / original) * 100;

            try
            {
                var percentLimit = (float)priority.BudgetPercent[budgetCheck];
                if (percent < percentLimit)
                {
                    var difference   = percentLimit - percent;
                    var budgetToMove = original * difference / 100;
                    hashYearAmount[year] = (float)hashYearAmount[year] - budgetToMove;

                    hashYearAmount       = (Hashtable)BudgetYear[nextBudget];
                    hashYearAmount[year] = (float)hashYearAmount[year] + budgetToMove;
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year original. " + e.Message));
                throw e;
            }
        }
Exemple #26
0
        /// <summary>
        ///
        /// Calculates the next years values AND files in the Answer array for base RemainingLife and Benefit cost.
        /// </summary>
        /// <param name="hashAttributeValues">Values for other attributes</param>
        /// <returns>Value for next year</returns>
        public double IterateOneYearEquation(Hashtable hashAttributeValues, int apparentAgeHint, out double apparentAge, out bool bOutOfRange)
        {
            double increment;
            double delta;
            double ratio;
            double dAnswer;
            double dAge = 0;

            apparentAge = 0;
            if (Shift)
            {
                dAge = double.Parse(hashAttributeValues["AGE"].ToString());
            }

            bOutOfRange = true;
            double dValue = double.Parse(hashAttributeValues[this.Attribute].ToString());

            //TODO: Does this need to be solved everytime on
            if (!_isAgeOnly)
            {
                Solve(hashAttributeValues);
            }

            //Check if 99 year value is input
            if (dValue > _answer[98] && !SimulationMessaging.GetAttributeAscending(Attribute))
            {
                bOutOfRange = false;
                return(dValue);
            }
            else if (dValue < _answer[98] && SimulationMessaging.GetAttributeAscending(Attribute))
            {
                bOutOfRange = false;
                return(dValue);
            }
            double dMinimum;
            double dMaximum;

            for (int i = 0; i < 98; i++)
            {
                //This eliminates ascending / descending problem.  Just looking for a number in between.
                if ((_answer[i] >= dValue && dValue > _answer[i + 1]) || (_answer[i] <= dValue && dValue < _answer[i + 1]))
                {
                    if (!Shift || i == 0 || dAge == 0)
                    {
                        delta     = dValue - _answer[i + 1];
                        increment = _answer[i] - _answer[i + 1];
                        if (increment == 0)
                        {
                            return(_answer[i + 1]);
                        }
                        ratio     = 1 - (delta / increment);
                        increment = _answer[i + 1] - _answer[i + 2];
                        delta     = ratio * increment;
                        dAnswer   = _answer[i + 1] - delta;
                    }
                    else // Must be SHIFT and i not 0
                    {
                        delta     = dValue - _answer[i + 1];
                        increment = _answer[i] - _answer[i + 1];
                        double dApparentAge   = (double)i + (1 - (delta / increment)); // Determine apparent age
                        double dApparentRatio = dApparentAge / dAge;                   // Determine rate that age is changing.
                        double dNextAge       = dApparentRatio + dApparentAge;
                        int    iNextAge       = (int)Math.Floor(dNextAge);
                        double dNextRatio     = dNextAge - Math.Floor(dNextAge);
                        if (iNextAge < 99)
                        {
                            increment = _answer[iNextAge] - _answer[iNextAge + 1];
                            delta     = dNextRatio * increment;
                            dAnswer   = _answer[iNextAge] - delta;
                        }
                        else
                        {
                            dAnswer = _answer[99];
                        }
                    }
                    if (SimulationMessaging.GetAttributeMinimum(this.Attribute, out dMinimum))
                    {
                        if (dMinimum > dAnswer)
                        {
                            return(dMinimum);
                        }
                    }
                    if (SimulationMessaging.GetAttributeMaximum(this.Attribute, out dMaximum))
                    {
                        if (dMaximum < dAnswer)
                        {
                            return(dMaximum);
                        }
                    }
                    bOutOfRange = false;
                    return(dAnswer);
                }
            }

            dValue = _answer[0];
            if (SimulationMessaging.GetAttributeMinimum(this.Attribute, out dMinimum))
            {
                if (dMinimum > dValue)
                {
                    return(dMinimum);
                }
            }

            if (SimulationMessaging.GetAttributeMaximum(this.Attribute, out dMaximum))
            {
                if (dMaximum < dValue)
                {
                    return(dMaximum);
                }
            }
            return(dValue);
        }
Exemple #27
0
        internal void SetFunction(string equation)
        {
            _equation = equation;

            // Get list of attributes
            _attributesEquation = SimulationMessaging.ParseAttribute(_equation);
            if (_attributesEquation == null)
            {
                return;
            }

            if (_attributesEquation.Count == 1 && _attributesEquation[0].ToUpper() == "AGE")
            {
                _isAgeOnly = true;
            }

            if (_equation.Length >= 6 && _equation.Substring(0, 6) == "MODULE")
            {
                IsModule = true;
                //this will crash the program for equations with less than 10 characters
                //if (m_strEquation.Substring(0, 6) == "MODULE")
                if (_equation.Length >= 10 && _equation.Substring(7, 3) == "CRS")
                {
                    IsCRS = true;
                }
                else if (_equation.Length >= 10 && _equation.Substring(7, 3) == "OCI")
                {
                    IsOCI = true;
                }
                return;
            }
            else
            {
                if (_calculate == null)
                {
                    _calculate = new CalculateEvaluate.CalculateEvaluate();

                    //Allow functions to utilize strings and dates.
                    string        functionEquation = _equation;
                    List <string> attributes       = SimulationMessaging.ParseAttribute(functionEquation);

                    foreach (String attribute in attributes)
                    {
                        String attributeType = SimulationMessaging.GetAttributeType(attribute);
                        if (attributeType == "STRING")
                        {
                            String oldValue = "[" + attribute + "]";
                            String newValue = "[@" + attribute + "]";
                            functionEquation = functionEquation.Replace(oldValue, newValue);
                        }
                        else if (attributeType == "DATETIME")
                        {
                            String oldValue = "[" + attribute + "]";
                            String newValue = "[$" + attribute + "]";
                            functionEquation = functionEquation.Replace(oldValue, newValue);
                        }
                    }
                    _calculate.BuildFunctionClass(functionEquation, "double", cgOMS.Prefix + _table + "_BINARY_EQUATION_" + _performanceID);

                    if (_calculate.m_cr == null)
                    {
                        _compilerResultsEquation = _calculate.CompileAssembly();
                        if (_table != null)
                        {
                            SimulationMessaging.SaveSerializedCalculateEvaluate(cgOMS.Prefix + _table, "BINARY_EQUATION", _performanceID, _calculate);
                        }
                    }

                    if (_calculate.m_listError.Count > 0)
                    {
                        foreach (String str in _calculate.m_listError)
                        {
                            _errors.Add(str);
                        }
                    }
                }
                //If [AGE] is the only variable.  This only needs to be solved once so might
                //as well solve it right now.
                if (_isAgeOnly)
                {
                    Hashtable hash = new Hashtable();
                    hash.Add("AGE", "0");
                    this.Solve(hash);
                }
            }
        }
Exemple #28
0
        public void Solve(Hashtable hashAttributeValue)
        {
            double dValue;
            double dMinimum;
            double dMaximum;

            _answer = new double[100];
            if (IsModule)
            {
                if (IsCRS)
                {
                    String strType     = hashAttributeValue[_attributesEquation[0].ToString()].ToString();
                    double dCRS        = Convert.ToDouble(hashAttributeValue[_attributesEquation[1].ToString()]);
                    double dThick      = Convert.ToDouble(hashAttributeValue[_attributesEquation[2].ToString()]);
                    double dESAL       = Convert.ToDouble(hashAttributeValue[_attributesEquation[3].ToString()]);
                    double dESALGrowth = Convert.ToDouble(hashAttributeValue[_attributesEquation[4].ToString()]);

                    double dRSL;
                    double dBenefit;
                    _answer[0] = dCRS;
                    for (int n = 1; n < 100; n++)
                    {
                        double dAge = (double)n;
                        dValue = SimulationMessaging.crs.CalculateCRSBenefit(false, strType, dCRS, dThick, dESAL, dESALGrowth, 1, dAge, SimulationMessaging.Method.BenefitLimit, out dBenefit, out dRSL);
                        try
                        {
                            if (SimulationMessaging.GetAttributeMaximum(this.Attribute, out dMaximum))
                            {
                                if (dValue > dMaximum)
                                {
                                    dValue = dMaximum;
                                }
                            }

                            if (SimulationMessaging.GetAttributeMinimum(this.Attribute, out dMinimum))
                            {
                                if (dValue < dMinimum)
                                {
                                    dValue = dMinimum;
                                }
                            }
                        }
                        catch
                        {
                            String strValue = SimulationMessaging.GetAttributeDefault(this.Attribute);
                            dValue = double.Parse(strValue);
                        }
                        _answer[n] = dValue;
                    }
                    return;
                }
                else if (IsOCI)
                {
                }
            }

            object[] input = new object[_attributesEquation.Count];

            int i    = 0;
            int nAge = -1;

            foreach (String str in _attributesEquation)
            {
                if (str == "AGE")
                {
                    nAge = i;
                }
                input[i] = hashAttributeValue[str];;
                i++;
            }

            for (int n = 0; n < 100; n++)
            {
                double dAge = (double)n;
                if (nAge >= 0)
                {
                    input[nAge] = dAge;
                }
                try
                {
                    object result = _calculate.RunMethod(input);
                    try
                    {
                        dValue = (double)result;
                        if (SimulationMessaging.GetAttributeMaximum(this.Attribute, out dMaximum))
                        {
                            if (dValue > dMaximum)
                            {
                                dValue = dMaximum;
                            }
                        }

                        if (SimulationMessaging.GetAttributeMinimum(this.Attribute, out dMinimum))
                        {
                            if (dValue < dMinimum)
                            {
                                dValue = dMinimum;
                            }
                        }
                    }
                    catch
                    {
                        String strValue = SimulationMessaging.GetAttributeDefault(this.Attribute);
                        dValue = double.Parse(strValue);
                    }
                    _answer[n] = dValue;
                }
                catch (Exception exc)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error in RunMethod.   " + _calculate.OriginalInput + " " + exc.Message));
                }
            }
            return;
        }
Exemple #29
0
        public bool LoadBudgetPercentages(List <String> listBudgets)
        {
            //Cleanup unused Budgets
            String strDelete = "DELETE FROM " + cgOMS.Prefix + "PRIORITYFUND WHERE PRIORITYID='" + this.PriorityID + "'";

            if (listBudgets.Count > 0)
            {
                strDelete += " AND (";
            }
            int nBudget = 0;

            foreach (String sBudget in listBudgets)
            {
                if (nBudget > 0)
                {
                    strDelete += " AND ";
                }
                strDelete += "BUDGET<>'" + sBudget + "'";
                nBudget++;
            }
            if (listBudgets.Count > 0)
            {
                strDelete += ")";
            }

            try
            {
                DBMgr.ExecuteNonQuery(strDelete);
            }
            catch (Exception except)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Fatal Error: Error removing non-used budget priorities. " + except.Message));
                return(false);
            }

            if (SimulationMessaging.IsOMS)
            {
                foreach (string budget in listBudgets)
                {
                    m_hashBudgetPercent.Add(budget, 100f);
                }
            }
            else
            {
                String  strSelect = "SELECT BUDGET, FUNDING FROM " + cgOMS.Prefix + "PRIORITYFUND WHERE PRIORITYID='" + this.PriorityID + "'";
                DataSet ds;
                try
                {
                    ds = DBMgr.ExecuteQuery(strSelect);
                    if (ds.Tables[0].Rows.Count != listBudgets.Count)
                    {
                        SimulationMessaging.AddMessage(new SimulationMessage("Fatal Error: Each budget must have a funding level for each priority level."));
                        return(false);
                    }
                }
                catch
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Filling Priority budgets and funding"));
                    return(false);
                }

                String strBudget;
                String strFunding;
                float  fFunding;

                foreach (DataRow row in ds.Tables[0].Rows)
                {
                    strBudget  = row[0].ToString();
                    fFunding   = 100;
                    strFunding = row[1].ToString();
                    float.TryParse(strFunding, out fFunding);
                    m_hashBudgetPercent.Add(strBudget, fFunding);
                }
            }
            return(true);
        }
Exemple #30
0
        /// <summary>
        /// Check if budget can support treatment.  Checks for each priority.
        /// </summary>
        /// <param name="fAmount"></param>
        /// <param name="strBudget"></param>
        /// <param name="strYear"></param>
        /// <param name="hashAttributeValue"></param>
        /// <param name="priority"></param>
        /// <param name="limits">Limits where treatments are split over multiple years</param>
        /// <returns></returns>
        public string IsBudgetAvailable(float fAmount, string strBudget, String strYear, Hashtable hashAttributeValue, Priorities priority, List <ISplitTreatmentLimit> limits, string budgetLimitType, out string budgetHash, out ISplitTreatmentLimit splitTreatmentLimit, out string reasonNoBudget)
        {
            reasonNoBudget = "";
            string noBudgetAvailable = "";

            splitTreatmentLimit = limits[0];

            //Check priority.  If not possible just return null.
            if (!(priority.IsAllSections || priority.Criteria.IsCriteriaMet(hashAttributeValue)))
            {
                budgetHash     = "";
                reasonNoBudget = "Priority (" + priority.PriorityLevel + ") criteria not met for year " + strYear;
                return(noBudgetAvailable);
            }

            string[] possibleBudgets;


            foreach (var limit in limits)
            {
                if (limit.Amount > fAmount)
                {
                    splitTreatmentLimit = limit;
                    break;
                }
            }



            budgetHash = "";
            try
            {
                possibleBudgets = strBudget.Split('|');

                for (int i = 0; i < possibleBudgets.Length; i++)
                {
                    possibleBudgets[i] = possibleBudgets[i].Trim();
                }
            }
            catch (Exception e)
            {
                SimulationMessaging.AddMessage(new SimulationMessage("Error: Budget is null." + e.Message));
                throw e;
            }

            //If there are no budget criteria, then ignore.  The list is enforced.

            var budgets = new List <string>();

            if (SimulationMessaging.BudgetCriterias.Count > 0)
            {
                var listAvailableBudget = new List <BudgetCriteria>();
                foreach (var budgetCriteria in SimulationMessaging.BudgetCriterias)
                {
                    if (budgetCriteria.Criteria.IsCriteriaMet(hashAttributeValue))
                    {
                        listAvailableBudget.Add(budgetCriteria);
                    }
                }


                foreach (var budget in possibleBudgets)
                {
                    var available = listAvailableBudget.Find(b => b.BudgetName == budget);
                    if (available != null && !budgets.Contains(available.BudgetName))
                    {
                        budgets.Add(available.BudgetName);
                    }
                }
            }
            else
            {
                foreach (var budget in possibleBudgets)
                {
                    budgets.Add(budget);
                }
            }

            if (budgets.Count == 0)
            {
                reasonNoBudget = "Budget (" + strBudget + ") did not meet budget criteria.";
            }

            foreach (string budget in budgets)
            {
                string    budgetCheck = budget.Trim();
                Hashtable hashYearAmount;
                Hashtable hashYearAmountOriginal;
                float     fAvailable;
                float     fOriginal;
                float     fAfterSpending;
                float     fPercent;

                //Budget not defined
                try
                {
                    if (!BudgetYear.Contains(budgetCheck))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year. " + e.Message));
                    throw e;
                }


                try
                {
                    hashYearAmount = (Hashtable)BudgetYear[budgetCheck];
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year. " + e.Message));
                    throw e;
                }

                try
                {
                    if (!BudgetYearOriginal.Contains(budgetCheck))
                    {
                        continue;
                    }
                }
                catch (Exception e)
                {
                    SimulationMessaging.AddMessage(new SimulationMessage("Error: Checking budget year original. " + e.Message));
                    throw e;
                }

                bool currentBudgetAvailable = true;

                if (budgetLimitType.ToLower() == "unlimited")//If the budget is available (possible budget) and is unlimited... we are good.
                {
                    return(budgetCheck);
                }


                //Starting here need to loop through year amounts.
                var year = Convert.ToInt32(strYear);
                for (int i = 0; i < splitTreatmentLimit.Percentages.Count; i++)
                {
                    var currentYearAmount = fAmount * splitTreatmentLimit.Percentages[i] / 100;
                    var currentYear       = year + i;

                    //Priority must be all years, match the current year or the current year must be greater than maximum year and the Maximum year must be a priority.
                    if (!(priority.IsAllYears || priority.Years == currentYear || (currentYear > MaximumYear && priority.Years == MaximumYear)))
                    {
                        reasonNoBudget = "Priority is not set for year " + currentYear;
                        return(null);
                    }

                    try
                    {
                        //This occurs when a split treament goes past then end.
                        if (!hashYearAmount.Contains(currentYear.ToString()))
                        {
                            continue;
                        }
                        //Not past end of analysis.
                        fAvailable = (float)hashYearAmount[currentYear.ToString()];
                    }
                    catch (Exception e)
                    {
                        SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount. " + e.Message));
                        throw e;
                    }


                    //This gets a hash of all years and the amount of budgets originally available.
                    try
                    {
                        hashYearAmountOriginal = (Hashtable)BudgetYearOriginal[budgetCheck];
                        //This occurs when a split treament goes pas then end.
                        if (!hashYearAmountOriginal.ContainsKey(currentYear.ToString()))
                        {
                            continue;
                        }
                    }
                    catch (Exception e)
                    {
                        SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving budget year original. " + e.Message));
                        throw e;
                    }


                    try
                    {
                        if (!hashYearAmountOriginal.Contains(currentYear.ToString()))
                        {
                            continue;
                        }
                        fOriginal = (float)hashYearAmountOriginal[currentYear.ToString()];
                    }
                    catch (Exception e)
                    {
                        SimulationMessaging.AddMessage(new SimulationMessage("Error: Retrieving year amount original. " + e.Message));
                        throw e;
                    }

                    fAfterSpending = fAvailable - currentYearAmount;
                    if (fOriginal <= 0)
                    {
                        continue;
                    }
                    fPercent = (1 - fAfterSpending / fOriginal) * 100;


                    try
                    {
                        float fPercentLimit = (float)priority.BudgetPercent[budgetCheck];
                        var   original      = (float)priority.BudgetPercent[budgetCheck] * fOriginal / 100;
                        budgetHash = currentYearAmount.ToString("#,##0.##") + "/" + fAmount.ToString("#,##0.##") + "/" + fAvailable.ToString("#,##0.##") + "/" + original.ToString("#,##0.##");
                        //if (fPercent < fPercentLimit) return budgetCheck;
                        if (fPercent > fPercentLimit)
                        {
                            currentBudgetAvailable = false;
                            reasonNoBudget         = "Percent after spending greater than priority limit " + fPercent.ToString("f2") + "/" + fPercentLimit.ToString("f2") + " for year(" + currentYear + ")";
                            return(noBudgetAvailable);
                        }
                    }
                    catch (Exception e)
                    {
                        SimulationMessaging.AddMessage(new SimulationMessage("Error: Evaluating priority. " + e.Message));
                        throw e;
                    }
                }
                //To be true here, there must be money available for each year.
                if (currentBudgetAvailable)
                {
                    return(budgetCheck);
                }
            }
            return(noBudgetAvailable);
        }