Example #1
0
 public void SetOptions()
 {
     this.AnalyzerType = GetAnalyzerType();
     this.HCCalculatorParams.AnalyzerParms.AnalyzerType = this.AnalyzerType.ToString();
     if (this.HCCalculatorParams.AnalyzerParms.AnalyzerType == string.Empty ||
         this.HCCalculatorParams.AnalyzerParms.AnalyzerType == Constants.NONE)
     {
         this.HCCalculatorParams.ErrorMessage
             = Errors.MakeStandardErrorMsg("ANALYSES_CHOOSEONE");
     }
     this.HCCalculatorParams.AnalyzerParms.AnalyzerGeneralType
         = GetBaseAnalyzerType(this.AnalyzerType);
     this.HCCalculatorParams.AnalyzerParms.SubFolderType
         = AnalyzerHelper.GetSubFolderType(this.HCCalculatorParams.LinkedViewElement);
     this.HCCalculatorParams.AnalyzerParms.ComparisonType
         = AnalyzerHelper.GetComparisonType(this.HCCalculatorParams.LinkedViewElement);
     this.HCCalculatorParams.AnalyzerParms.AggregationType
         = AnalyzerHelper.GetAggregationType(this.HCCalculatorParams.LinkedViewElement);
     this.HCCalculatorParams.AnalyzerParms.FilesToAnalyzeExtensionType
         = CalculatorHelpers.GetAttribute(this.HCCalculatorParams.LinkedViewElement,
                                          Calculator1.cFilesToAnalyzeExtensionType);
     this.HCCalculatorParams.CalculatorType
         = this.HCCalculatorParams.AnalyzerParms.FilesToAnalyzeExtensionType;
     if (this.AnalyzerType != ANALYZER_TYPES.resources01)
     {
         //resources01 uses the calculator pattern, which does not change startingdoctocalc
         this.HCCalculatorParams.StartingDocToCalcNodeName
             = GetNodeNameFromFileExtensionType(this.HCCalculatorParams.AnalyzerParms.FilesToAnalyzeExtensionType);
     }
     this.HCCalculatorParams.SubApplicationType
         = CalculatorHelpers.GetSubAppTypeFromNodeName2(
               this.HCCalculatorParams.StartingDocToCalcNodeName);
 }
        public bool RunHCCalculations(CalculatorParameters calcParameters,
                                      HealthBenefit1Calculator hcBenefit1)
        {
            bool bHasCalculations = false;

            if (hcBenefit1 != null)
            {
                FixSelections(hcBenefit1);
                //calculate the adjusted benefit
                hcBenefit1.AdjustedBenefit = hcBenefit1.OutputCost * (hcBenefit1.BenefitAdjustment / 100);

                //set the base input properties
                //remember not to set amounts or the calcs have to be rerun in npv calcors
                hcBenefit1.Price = hcBenefit1.AdjustedBenefit;
                hcBenefit1.Unit  = (hcBenefit1.Unit != string.Empty && hcBenefit1.Unit != Constants.NONE)
                    ? hcBenefit1.Unit : Constants.EACH;
                //set the bcrating (equally weighted)
                SetAverageBenefitRating(hcBenefit1);
                bHasCalculations = true;
            }
            else
            {
                calcParameters.ErrorMessage = Errors.MakeStandardErrorMsg("CALCULATORS_WRONG_ONE");
            }
            return(bHasCalculations);
        }
        private bool RunOperationComponentStatistic(XElement currentElement)
        {
            bool bHasStatistics = false;

            if (this.AnalyzerType
                == ARSAnalyzerHelper.ANALYZER_TYPES.statistics01)
            {
                StatisticalAnalyzer1 statsAnalyzer1
                               = new StatisticalAnalyzer1(this.GCCalculatorParams);
                bHasStatistics = statsAnalyzer1.SetStatisticalCalculation(
                    currentElement);
                statsAnalyzer1 = null;
            }
            else if (ARSAnalyzerHelper.IsEffectivenessAnalysis(
                         this.AnalyzerType))
            {
                if (this.ceAnalyzer == null)
                {
                    this.ceAnalyzer
                        = new CostEffectivenessAnalyzer1(this.GCCalculatorParams);
                }
                bHasStatistics = SetEffectivenessStatistic(currentElement);
            }
            else
            {
                this.GCCalculatorParams.ErrorMessage
                    = Errors.MakeStandardErrorMsg("ANALYSES_NOANALYZER");
            }
            return(bHasStatistics);
        }
Example #4
0
        public ANALYZER_TYPES GetAnalyzerType(string analyzerType)
        {
            ANALYZER_TYPES eAnalyzerType = ANALYZER_TYPES.none;

            if (analyzerType == ANALYZER_TYPES.metotal1.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.metotal1;
            }
            else if (analyzerType == ANALYZER_TYPES.mechangeyr.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.mechangeyr;
            }
            else if (analyzerType == ANALYZER_TYPES.mechangeid.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.mechangeid;
            }
            else if (analyzerType == ANALYZER_TYPES.mechangealt.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.mechangealt;
            }
            else if (analyzerType == ANALYZER_TYPES.meprogress1.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.meprogress1;
            }
            else if (analyzerType == ANALYZER_TYPES.mestat1.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.mestat1;
            }
            if (eAnalyzerType == ANALYZER_TYPES.none)
            {
                this.ME2CalculatorParams.ErrorMessage
                    = Errors.MakeStandardErrorMsg("ANALYSES_CHOOSEONE");
            }
            return(eAnalyzerType);
        }
Example #5
0
 public void SetOptions()
 {
     this.AnalyzerType = GetAnalyzerType();
     this.ME2CalculatorParams.AnalyzerParms.AnalyzerType = this.AnalyzerType.ToString();
     if (this.ME2CalculatorParams.AnalyzerParms.AnalyzerType == string.Empty ||
         this.ME2CalculatorParams.AnalyzerParms.AnalyzerType == Constants.NONE)
     {
         this.ME2CalculatorParams.ErrorMessage
             = Errors.MakeStandardErrorMsg("ANALYSES_CHOOSEONE");
     }
     this.ME2CalculatorParams.AnalyzerParms.AnalyzerGeneralType
         = GetBaseAnalyzerType(this.AnalyzerType);
     this.ME2CalculatorParams.AnalyzerParms.SubFolderType
         = AnalyzerHelper.GetSubFolderType(this.ME2CalculatorParams.LinkedViewElement);
     this.ME2CalculatorParams.AnalyzerParms.ComparisonType
         = AnalyzerHelper.GetComparisonType(this.ME2CalculatorParams.LinkedViewElement);
     this.ME2CalculatorParams.AnalyzerParms.AggregationType
         = AnalyzerHelper.GetAggregationType(this.ME2CalculatorParams.LinkedViewElement);
     //new in v1.4.5 (user can choose whether or not to display full calcs)
     this.ME2CalculatorParams.NeedsFullView
         = AnalyzerHelper.GetDisplayFullViewOption(this.ME2CalculatorParams.LinkedViewElement);
     this.ME2CalculatorParams.AnalyzerParms.FilesToAnalyzeExtensionType
         = CalculatorHelpers.GetAttribute(this.ME2CalculatorParams.LinkedViewElement,
                                          Calculator1.cFilesToAnalyzeExtensionType);
     this.ME2CalculatorParams.StartingDocToCalcNodeName
         = GetNodeNameFromFileExtensionType(this.ME2CalculatorParams.AnalyzerParms.FilesToAnalyzeExtensionType);
     this.ME2CalculatorParams.SubApplicationType
         = CalculatorHelpers.GetSubAppTypeFromNodeName2(
               this.ME2CalculatorParams.StartingDocToCalcNodeName);
 }
Example #6
0
        public async Task <bool> DoStepAsync(ContentURI docToCalcURI, ContentURI calcDocURI,
                                             string extensionTypeName, IList <string> urisToAnalyze, IDictionary <string, string> updates,
                                             CancellationToken cancellationToken)
        {
            bool bIsStepDone = false;

            try
            {
                //extensiontypename (a parameter stored in db) determines
                //extension to run
                DoStepsHostView hostview = GetDoStepsView(calcDocURI,
                                                          extensionTypeName);
                if (hostview != null)
                {
                    //these extensions define their own number of steps internally
                    string sStepNumber = DataHelpers.AddInHelper.GetStepNumber(docToCalcURI);
                    //use the view to carry out the current step
                    bIsStepDone = await RunStepAsync(docToCalcURI, calcDocURI, sStepNumber,
                                                     hostview, urisToAnalyze, updates, cancellationToken);
                }
                else
                {
                    docToCalcURI.ErrorMessage = Errors.MakeStandardErrorMsg("CALCULATORS_MISSING_HOST");
                }
            }
            catch (CompositionException x)
            {
                docToCalcURI.ErrorMessage = x.ToString();
            }
            return(bIsStepDone);
        }
        public async Task <bool> RunAnalysis(IList <string> urisToAnalyze)
        {
            bool bHasAnalysis = false;
            //set the files needing analysis
            await CalculatorHelpers.SetFileOrFoldersToAnalyze(this.ARSCalculatorParams.AnalyzerParms.FilesToAnalyzeExtensionType,
                                                              this.ARSCalculatorParams, urisToAnalyze);

            //run the analysis
            if (this.ARSCalculatorParams.AnalyzerParms.FileOrFolderPaths != null)
            {
                if (this.ARSCalculatorParams.AnalyzerParms.FileOrFolderPaths.Count > 0)
                {
                    //build the base file needed by the regular analysis
                    this.ARSCalculatorParams.AnalyzerParms.ObservationsPath
                        = await CalculatorHelpers.GetFullCalculatorResultsPath(this.ARSCalculatorParams);

                    bHasAnalysis = await CalculatorHelpers.AddFilesToBaseDocument(this.ARSCalculatorParams);

                    if (bHasAnalysis)
                    {
                        //run the regular analysis
                        bHasAnalysis = await RunCalculations();

                        if (bHasAnalysis)
                        {
                            //v170 set devpack params
                            CalculatorHelpers.UpdateDevPackAnalyzerParams(this.ARSCalculatorParams);
                        }
                        //reset subapptype
                        this.ARSCalculatorParams.SubApplicationType = Constants.SUBAPPLICATION_TYPES.devpacks;
                    }
                    this.ARSCalculatorParams.ErrorMessage += this.ARSCalculatorParams.ErrorMessage;
                }
                else
                {
                    if (this.ARSCalculatorParams.DocToCalcNodeName
                        == Constants.LINKEDVIEWS_TYPES.linkedviewpack.ToString())
                    {
                        //setting default analyzer attribute values
                    }
                    else
                    {
                        this.ARSCalculatorParams.ErrorMessage
                            = Errors.MakeStandardErrorMsg("ANALYSES_NOFILES");
                    }
                }
            }
            else
            {
                this.ARSCalculatorParams.ErrorMessage
                    = Errors.MakeStandardErrorMsg("ANALYSES_NOFILES");
            }
            return(bHasAnalysis);
        }
Example #8
0
        //add a Machinery1Input to the baseStat.MachineryStocks dictionary
        public static bool AddMachinery1StocksToDictionary(
            this Machinery1Stock baseStat,
            int filePosition, int nodePosition, Machinery1Input calculator)
        {
            bool bIsAdded = false;

            if (filePosition < 0 || nodePosition < 0)
            {
                baseStat.ErrorMessage
                    = Errors.MakeStandardErrorMsg("ANALYSES_INDEX_OUTOFBOUNDS");
                return(false);
            }
            if (baseStat.MachineryStocks == null)
            {
                baseStat.MachineryStocks
                    = new Dictionary <int, List <Machinery1Input> >();
            }
            if (baseStat.MachineryStocks.ContainsKey(filePosition))
            {
                if (baseStat.MachineryStocks[filePosition] != null)
                {
                    for (int i = 0; i <= nodePosition; i++)
                    {
                        if (baseStat.MachineryStocks[filePosition].Count <= i)
                        {
                            baseStat.MachineryStocks[filePosition]
                            .Add(new Machinery1Input());
                        }
                    }
                    baseStat.MachineryStocks[filePosition][nodePosition]
                             = calculator;
                    bIsAdded = true;
                }
            }
            else
            {
                //add the missing dictionary entry
                List <Machinery1Input> baseStats
                    = new List <Machinery1Input>();
                KeyValuePair <int, List <Machinery1Input> > newStat
                    = new KeyValuePair <int, List <Machinery1Input> >(
                          filePosition, baseStats);
                baseStat.MachineryStocks.Add(newStat);
                bIsAdded = AddMachinery1StocksToDictionary(baseStat,
                                                           filePosition, nodePosition, calculator);
            }
            return(bIsAdded);
        }
Example #9
0
        //add a hcOutputfact to the baseStat.HealthCareBenefit1s dictionary
        public static bool AddOutputHCStocksToDictionary(this OutputHCStock baseStat,
                                                         int filePosition, int nodePosition, HealthBenefit1Calculator hcOutputStock)
        {
            bool bIsAdded = false;

            if (filePosition < 0 || nodePosition < 0)
            {
                baseStat.ErrorMessage
                    = Errors.MakeStandardErrorMsg("ANALYSES_INDEX_OUTOFBOUNDS");
                return(false);
            }
            if (baseStat.HealthCareBenefit1s == null)
            {
                baseStat.HealthCareBenefit1s
                    = new Dictionary <int, List <HealthBenefit1Calculator> >();
            }
            if (baseStat.HealthCareBenefit1s.ContainsKey(filePosition))
            {
                if (baseStat.HealthCareBenefit1s[filePosition] != null)
                {
                    for (int i = 0; i <= nodePosition; i++)
                    {
                        if (baseStat.HealthCareBenefit1s[filePosition].Count <= i)
                        {
                            baseStat.HealthCareBenefit1s[filePosition]
                            .Add(new HealthBenefit1Calculator());
                        }
                    }
                    baseStat.HealthCareBenefit1s[filePosition][nodePosition]
                             = hcOutputStock;
                    bIsAdded = true;
                }
            }
            else
            {
                //add the missing dictionary entry
                List <HealthBenefit1Calculator> baseStats
                    = new List <HealthBenefit1Calculator>();
                KeyValuePair <int, List <HealthBenefit1Calculator> > newStat
                    = new KeyValuePair <int, List <HealthBenefit1Calculator> >(
                          filePosition, baseStats);
                baseStat.HealthCareBenefit1s.Add(newStat);
                bIsAdded = AddOutputHCStocksToDictionary(baseStat,
                                                         filePosition, nodePosition, hcOutputStock);
            }
            return(bIsAdded);
        }
Example #10
0
        //add a foodfact to the baseStat.FoodNutritionStocks dictionary
        public static bool AddFNSR01StocksToDictionary(this FNSR01Stock baseStat,
                                                       int filePosition, int nodePosition, FNSR01Calculator foodStock)
        {
            bool bIsAdded = false;

            if (filePosition < 0 || nodePosition < 0)
            {
                baseStat.ErrorMessage
                    = Errors.MakeStandardErrorMsg("ANALYSES_INDEX_OUTOFBOUNDS");
                return(false);
            }
            if (baseStat.FoodNutritionStocks == null)
            {
                baseStat.FoodNutritionStocks
                    = new Dictionary <int, List <FNSR01Calculator> >();
            }
            if (baseStat.FoodNutritionStocks.ContainsKey(filePosition))
            {
                if (baseStat.FoodNutritionStocks[filePosition] != null)
                {
                    for (int i = 0; i <= nodePosition; i++)
                    {
                        if (baseStat.FoodNutritionStocks[filePosition].Count <= i)
                        {
                            baseStat.FoodNutritionStocks[filePosition]
                            .Add(new FNSR01Calculator());
                        }
                    }
                    baseStat.FoodNutritionStocks[filePosition][nodePosition]
                             = foodStock;
                    bIsAdded = true;
                }
            }
            else
            {
                //add the missing dictionary entry
                List <FNSR01Calculator> baseStats
                    = new List <FNSR01Calculator>();
                KeyValuePair <int, List <FNSR01Calculator> > newStat
                    = new KeyValuePair <int, List <FNSR01Calculator> >(
                          filePosition, baseStats);
                baseStat.FoodNutritionStocks.Add(newStat);
                bIsAdded = AddFNSR01StocksToDictionary(baseStat,
                                                       filePosition, nodePosition, foodStock);
            }
            return(bIsAdded);
        }
Example #11
0
        //add a base health input stock to the baseStat.BuildCost1s dictionary
        public static bool AddSubPrice3StocksToDictionary(this SubPrice3Stock baseStat,
                                                          string filePosition, int nodePosition, SubPrice3 indicators)
        {
            bool bIsAdded = false;

            if (string.IsNullOrEmpty(filePosition) || nodePosition < 0)
            {
                baseStat.ErrorMessage
                    = Errors.MakeStandardErrorMsg("ANALYSES_INDEX_OUTOFBOUNDS");
                return(false);
            }
            if (baseStat.SubPrice3Labels == null)
            {
                baseStat.SubPrice3Labels
                    = new Dictionary <string, List <SubPrice3> >();
            }
            if (baseStat.SubPrice3Labels.ContainsKey(filePosition))
            {
                if (baseStat.SubPrice3Labels[filePosition] != null)
                {
                    for (int i = 0; i <= nodePosition; i++)
                    {
                        if (baseStat.SubPrice3Labels[filePosition].Count <= i)
                        {
                            baseStat.SubPrice3Labels[filePosition]
                            .Add(new SubPrice3());
                        }
                    }
                    baseStat.SubPrice3Labels[filePosition][nodePosition]
                             = indicators;
                    bIsAdded = true;
                }
            }
            else
            {
                //add the missing dictionary entry
                List <SubPrice3> baseStats
                    = new List <SubPrice3>();
                KeyValuePair <string, List <SubPrice3> > newStat
                    = new KeyValuePair <string, List <SubPrice3> >(
                          filePosition, baseStats);
                baseStat.SubPrice3Labels.Add(newStat);
                bIsAdded = AddSubPrice3StocksToDictionary(baseStat,
                                                          filePosition, nodePosition, indicators);
            }
            return(bIsAdded);
        }
Example #12
0
 public virtual void SetCostsMemberProperty(int filePosition, int nodePosition,
                                            string attName, string attValue, string nodeName)
 {
     if (filePosition < 0 || nodePosition < 0)
     {
         this.CalcParams.ErrorMessage
             = Errors.MakeStandardErrorMsg("ANALYSES_INDEX_OUTOFBOUNDS");
         return;
     }
     if (this.CalcParams.AnalyzerParms.CostStatistics.ContainsKey(filePosition))
     {
         if (this.CalcParams.AnalyzerParms.CostStatistics[filePosition] != null)
         {
             for (int i = 0; i <= nodePosition; i++)
             {
                 if (this.CalcParams.AnalyzerParms.CostStatistics[filePosition].Count <= i)
                 {
                     this.CalcParams.AnalyzerParms.CostStatistics[filePosition]
                     .Add(new CostBenefitStatistic01());
                 }
             }
             SetCostStatisticProperty(filePosition, nodePosition,
                                      attName, attValue, nodeName);
             if (NeedsBenefitStatsWithCosts(nodeName))
             {
                 //use the costs collection to set a benefits property
                 SetBenefitStatisticPropertyForCosts(filePosition, nodePosition,
                                                     attName, attValue, nodeName);
             }
         }
         else
         {
             AddCostStatisticsToDictionary(
                 filePosition, nodePosition, new CostBenefitStatistic01());
             SetCostsMemberProperty(filePosition, nodePosition,
                                    attName, attValue, nodeName);
         }
     }
     else
     {
         AddCostStatisticsToDictionary(
             filePosition, nodePosition, new CostBenefitStatistic01());
         SetCostsMemberProperty(filePosition, nodePosition,
                                attName, attValue, nodeName);
     }
 }
Example #13
0
 public virtual void AddCostStatisticsToDictionary(
     int filePosition, int nodePosition, CostBenefitStatistic01 baseStat)
 {
     if (filePosition < 0 || nodePosition < 0)
     {
         this.CalcParams.ErrorMessage
             = Errors.MakeStandardErrorMsg("ANALYSES_INDEX_OUTOFBOUNDS");
         return;
     }
     if (this.CalcParams.AnalyzerParms.CostStatistics == null)
     {
         this.CalcParams.AnalyzerParms.CostStatistics
             = new Dictionary <int, List <CostBenefitStatistic01> >();
     }
     if (this.CalcParams.AnalyzerParms.CostStatistics.ContainsKey(filePosition))
     {
         if (this.CalcParams.AnalyzerParms.CostStatistics[filePosition] != null)
         {
             for (int i = 0; i <= nodePosition; i++)
             {
                 if (this.CalcParams.AnalyzerParms.CostStatistics[filePosition].Count <= i)
                 {
                     this.CalcParams.AnalyzerParms.CostStatistics[filePosition]
                     .Add(new CostBenefitStatistic01());
                 }
             }
             this.CalcParams.AnalyzerParms.CostStatistics[filePosition][nodePosition]
                 = baseStat;
         }
     }
     else
     {
         //add the missing dictionary entry
         List <CostBenefitStatistic01> baseStats
             = new List <CostBenefitStatistic01>();
         KeyValuePair <int, List <CostBenefitStatistic01> > newStat
             = new KeyValuePair <int, List <CostBenefitStatistic01> >(
                   filePosition, baseStats);
         this.CalcParams.AnalyzerParms.CostStatistics.Add(newStat);
         AddCostStatisticsToDictionary(filePosition, nodePosition,
                                       baseStat);
     }
 }
Example #14
0
        public static bool SetLinkedListsState(CalculatorParameters calcParameters)
        {
            bool bIsDone = false;

            //step two passes in constants and other lists of data
            if (calcParameters.LinkedViewElement != null)
            {
                AddConstants(CONSTANTS_TYPES.priceconstant,
                             calcParameters);
                //save the tempdoc with changes and bIsDone = true
                bIsDone = CalculatorHelpers.SaveNewCalculationsDocument(
                    calcParameters);
            }
            else
            {
                calcParameters.ErrorMessage
                    = Errors.MakeStandardErrorMsg("CALCSHELPER_FILE_NOTFOUND");
            }
            return(bIsDone);
        }
        private bool RunStatisticalCalculation(XElement currentElement)
        {
            bool bHasCalculations = false;

            //1. set parameters needed by updates collection
            this.GCCalculatorParams.CurrentElementNodeName
                = currentElement.Name.LocalName;
            this.GCCalculatorParams.CurrentElementURIPattern
                = CalculatorHelpers.MakeNewURIPatternFromElement(
                      this.GCCalculatorParams.ExtensionDocToCalcURI.URIPattern, currentElement);
            //2. carry out calculations
            bHasCalculations = RunOperationComponentStatistic(currentElement);
            if (!bHasCalculations &&
                string.IsNullOrEmpty(this.GCCalculatorParams.ErrorMessage))
            {
                this.GCCalculatorParams.ErrorMessage
                    += Errors.MakeStandardErrorMsg("ANALYSES_CANTRUN");
            }
            return(bHasCalculations);
        }
Example #16
0
        public bool SetGeneralCapitalStockCalculations(double multiplier,
                                                       CalculatorParameters calcParameters, GeneralCapital1Input machInput)
        {
            bool bHasCalculations = false;

            if (machInput != null)
            {
                //don't adjust machinery per hour costs by any multiplier
                //pattern is fine but not appropriate here
                //in this extension, calculations are carried out in the
                //budget/investment calculators
                //BIGeneralCapitalStockCalculator biCalculator = new BIGeneralCapitalStockCalculator();
                //biCalculator.ChangeGeneralCapitalInputByMultiplier(machInput, multiplier);
                //bHasCalculations = true;
            }
            else
            {
                calcParameters.ErrorMessage = Errors.MakeStandardErrorMsg("CALCULATORS_WRONG_ONE");
            }
            return(bHasCalculations);
        }
Example #17
0
        public ANALYZER_TYPES GetAnalyzerType(string analyzerType)
        {
            ANALYZER_TYPES eAnalyzerType = ANALYZER_TYPES.none;

            if (analyzerType == ANALYZER_TYPES.effectiveness01a.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.effectiveness01a;
            }
            else if (analyzerType == ANALYZER_TYPES.effectiveness01b.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.effectiveness01b;
            }
            else if (analyzerType == ANALYZER_TYPES.effectiveness02a.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.effectiveness02a;
            }
            else if (analyzerType == ANALYZER_TYPES.effectiveness02b.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.effectiveness02b;
            }
            else if (analyzerType == ANALYZER_TYPES.none.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.none;
            }
            else if (analyzerType == ANALYZER_TYPES.resources01.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.resources01;
            }
            else if (analyzerType == ANALYZER_TYPES.statistics01.ToString())
            {
                eAnalyzerType = ANALYZER_TYPES.statistics01;
            }
            if (eAnalyzerType == ANALYZER_TYPES.none)
            {
                this.HCCalculatorParams.ErrorMessage
                    = Errors.MakeStandardErrorMsg("ANALYSES_CHOOSEONE");
            }
            return(eAnalyzerType);
        }
Example #18
0
        public async Task <bool> DoStepAsync(ContentURI docToCalcURI, ContentURI calcDocURI,
                                             string extensionTypeName, IList <string> urisToAnalyze, IDictionary <string, string> updates,
                                             CancellationToken cancellationToken)
        {
            bool bIsStepDone = false;

            try
            {
                //extensiontypename (a parameter stored in db) determines
                //extension to run
                IDoStepsHostMetaData hostview = GetDoStepsView(calcDocURI,
                                                               extensionTypeName);
                if (hostview != null)
                {
                    //these extensions define their own number of steps internally
                    string sStepNumber = DataHelpers.AddInHelper.GetStepNumber(docToCalcURI);
                    //use the view to carry out the current step
                    bIsStepDone = await RunStepAsync(docToCalcURI, calcDocURI, sStepNumber,
                                                     hostview, urisToAnalyze, updates, cancellationToken);
                }
                else
                {
                    //216: azure bug to release path
                    docToCalcURI.ErrorMessage = string.Concat(
                        Errors.MakeStandardErrorMsg("CALCULATORS_MISSING_HOST")
                        , " ext_typename:", extensionTypeName
                        , " ext_path:", DataHelpers.AppSettings.GetExtensionsRelPath(calcDocURI)
                        , " defaultrootpath:", DataHelpers.AppSettings.GetWebContentFullPath(
                            calcDocURI, "Extensions", "AgBudgetingCalculators.dll")
                        , " defaultroot_path:", calcDocURI.URIDataManager.DefaultRootFullFilePath);
                }
            }
            catch (Exception x)
            {
                docToCalcURI.ErrorMessage = x.ToString();
            }
            return(bIsStepDone);
        }
Example #19
0
        public static ANALYZER_GENERAL_TYPES GetAnalyzerType(
            string analyzerType, ref string errorMsg)
        {
            ANALYZER_GENERAL_TYPES eAnalyzerType = ANALYZER_GENERAL_TYPES.none;

            if (analyzerType == ANALYZER_GENERAL_TYPES.basic.ToString())
            {
                eAnalyzerType = ANALYZER_GENERAL_TYPES.basic;
            }
            else if (analyzerType == ANALYZER_GENERAL_TYPES.inputbased.ToString())
            {
                eAnalyzerType = ANALYZER_GENERAL_TYPES.inputbased;
            }
            else if (analyzerType == ANALYZER_GENERAL_TYPES.outputbased.ToString())
            {
                eAnalyzerType = ANALYZER_GENERAL_TYPES.outputbased;
            }
            if (eAnalyzerType == ANALYZER_GENERAL_TYPES.none)
            {
                errorMsg = Errors.MakeStandardErrorMsg("ANALYSES_CHOOSEONE");
            }
            return(eAnalyzerType);
        }
Example #20
0
        private bool RunStatisticalCalculation(ref XElement currentElement)
        {
            bool bHasCalculations = false;

            //1. set parameters needed by updates collection
            this.GCCalculatorParams.CurrentElementNodeName
                = currentElement.Name.LocalName;
            this.GCCalculatorParams.CurrentElementURIPattern
                = CalculatorHelpers.MakeNewURIPatternFromElement(
                      this.GCCalculatorParams.ExtensionDocToCalcURI.URIPattern,
                      currentElement);
            GCArguments.CurrentElement = currentElement;
            OnRunCalculation(GCArguments);
            currentElement   = GCArguments.CurrentElement;
            bHasCalculations = GCArguments.HasCalculations;
            if (!bHasCalculations &&
                string.IsNullOrEmpty(this.GCCalculatorParams.ErrorMessage))
            {
                this.GCCalculatorParams.ErrorMessage
                    += Errors.MakeStandardErrorMsg("ANALYSES_CANTRUN");
            }
            return(bHasCalculations);
        }
Example #21
0
 private void InitCollections(List <TimelinessTimePeriod1> timelinessTimePeriods)
 {
     if (timelinessTimePeriods != null)
     {
         if (timelinessTimePeriods.Count > 0)
         {
             //make the optimization array of uniqueopcomp, feasibleopcomp
             MakeOrderedTOCs(timelinessTimePeriods);
             if (this.TOpComps == null || this.WOpComps == null)
             {
                 this.ErrorMessage = Errors.GetMessage("RESOURCESTOCKS_NOPOWERORNONPOWERINPUTS");
             }
         }
         else
         {
             this.ErrorMessage = Errors.GetMessage("RESOURCESTOCKS_NOPOWERORNONPOWERINPUTS");
         }
     }
     else
     {
         this.ErrorMessage = Errors.GetMessage("RESOURCESTOCKS_NOPOWERORNONPOWERINPUTS");
     }
 }
        public async Task <bool> RunCalculations()
        {
            bool bHasCalculations = false;

            //these calculators use a mix of calculator and analyzer patterns
            this.ARSCalculatorParams.RunCalculatorType
                = CalculatorHelpers.RUN_CALCULATOR_TYPES.iotechnology;
            //urisToAnalyze has the summary calculated results path in position 0.
            //This calculator uses that path to derive the full calculated
            //results path. The full path document is used to run the calculations
            //(it has the input and output calculated results that are
            //the basis for most resource stock calculations).
            this.ARSCalculatorParams.AnalyzerParms.ObservationsPath
                = await CalculatorHelpers.GetFullCalculatorResultsPath(
                      this.ARSCalculatorParams);

            if (!await CalculatorHelpers.URIAbsoluteExists(this.ARSCalculatorParams.ExtensionDocToCalcURI,
                                                           this.ARSCalculatorParams.AnalyzerParms.ObservationsPath))
            {
                this.ARSCalculatorParams.ErrorMessage
                    = Errors.MakeStandardErrorMsg("ANALYZER_BASECALCS_MISSING");
                return(false);
            }
            //can run npv calcs or base input calculators
            if (this.ARSCalculatorParams.CalculatorType
                == CalculatorHelpers.CALCULATOR_TYPES.input.ToString() ||
                this.ARSCalculatorParams.CalculatorType
                == AgBudgetingHelpers.CALCULATOR_TYPES.agmachinery.ToString() ||
                this.ARSCalculatorParams.CalculatorType
                == AgBudgetingHelpers.CALCULATOR_TYPES.irrpower.ToString() ||
                this.ARSCalculatorParams.CalculatorType
                == AgBudgetingHelpers.CALCULATOR_TYPES.gencapital.ToString())
            {
                IOMachineryStockSubscriber subInput
                    = new IOMachineryStockSubscriber(this.ARSCalculatorParams);
                bHasCalculations = await subInput.RunCalculator();

                CalculatorHelpers.UpdateCalculatorParams(this.ARSCalculatorParams,
                                                         subInput.GCCalculatorParams);
                subInput = null;
            }
            else if (this.ARSCalculatorParams.CalculatorType.StartsWith(
                         CalculatorHelpers.CALCULATOR_TYPES.operation.ToString()) ||
                     this.ARSCalculatorParams.CalculatorType.StartsWith(
                         CalculatorHelpers.CALCULATOR_TYPES.component.ToString()))
            {
                OCMachineryStockSubscriber subOperation
                    = new OCMachineryStockSubscriber(this.ARSCalculatorParams);
                bHasCalculations = await subOperation.RunCalculator();

                CalculatorHelpers.UpdateCalculatorParams(this.ARSCalculatorParams,
                                                         subOperation.GCCalculatorParams);
                subOperation = null;
            }
            else if (this.ARSCalculatorParams.CalculatorType
                     == CalculatorHelpers.CALCULATOR_TYPES.budget.ToString() ||
                     this.ARSCalculatorParams.CalculatorType
                     == CalculatorHelpers.CALCULATOR_TYPES.investment.ToString())
            {
                BIMachineryStockSubscriber subBudget
                    = new BIMachineryStockSubscriber(this.ARSCalculatorParams);
                bHasCalculations = await subBudget.RunCalculator();

                CalculatorHelpers.UpdateCalculatorParams(this.ARSCalculatorParams,
                                                         subBudget.GCCalculatorParams);
                subBudget = null;
            }
            return(bHasCalculations);
        }
        //allows derived classes to override the default streaming
        //and save method
        protected virtual bool StreamAndSaveObservation()
        {
            HasGoodObservationFile = false;
            if (this.ObsCalculatorParams.AnalyzerParms.FileOrFolderPaths == null)
            {
                this.ObsCalculatorParams.ErrorMessage
                    = Errors.MakeStandardErrorMsg("OBSERVATIONS_NOFILES_SAVETEXT");
                return(false);
            }
            else
            {
                if (this.ObsCalculatorParams.AnalyzerParms.FileOrFolderPaths.Count <= 0)
                {
                    this.ObsCalculatorParams.ErrorMessage
                        = Errors.MakeStandardErrorMsg("OBSERVATIONS_NOFILES_SAVETEXT");
                    return(false);
                }
            }
            bool bHasInitialColumnDictionary = InitColumnDictionary();

            this.ObsCalculatorParams.AnalyzerParms.ObservationsPath
                = GetObservationFilePath(this.ObsCalculatorParams.ExtensionDocToCalcURI.URIDataManager.TempDocPath);
            if (!string.IsNullOrEmpty(this.ObsCalculatorParams.AnalyzerParms.ObservationsPath))
            {
                if (bHasInitialColumnDictionary)
                {
                    TextFile = new StreamWriter(
                        this.ObsCalculatorParams.AnalyzerParms.ObservationsPath);
                    //write the column headings
                    WriteColumnNameRow();
                }
                //+1 because the first column holds the stats for all comparisons
                //int iFileComparisonsCount = fileOrFolderPaths.Count + 1;
                //subscribers set a "Files" attribute property using this property
                this.ObsCalculatorParams.AnalyzerParms.FilesComparisonsCount
                    = this.ObsCalculatorParams.AnalyzerParms.FileOrFolderPaths.Count + 1;
                string sId            = string.Empty;
                string sFileToAnalyze = string.Empty;
                int    i = 0;
                //file order is not relevant in this addin,
                //but parallel won't work (yet) because of the way
                //the observationRoot gets built
                foreach (KeyValuePair <string, string> kvp
                         in this.ObsCalculatorParams.AnalyzerParms.FileOrFolderPaths)
                {
                    sId            = kvp.Key;
                    sFileToAnalyze = kvp.Value;
                    if (CalculatorHelpers.URIAbsoluteExists(
                            this.ObsCalculatorParams.ExtensionDocToCalcURI,
                            sFileToAnalyze))
                    {
                        this.ObsCalculatorParams.AnalyzerParms.ObservationFile   = sFileToAnalyze;
                        this.ObsCalculatorParams.AnalyzerParms.FilePositionIndex = i;
                        //stream and add the calculation (observation)
                        //to the observationsRoot
                        if (!CalculatorHelpers.URIAbsoluteExists(
                                this.ObsCalculatorParams.ExtensionDocToCalcURI,
                                this.ObsCalculatorParams.AnalyzerParms.ObservationFile))
                        {
                            return(HasGoodObservationFile);
                        }
                        this.ObsCalculatorParams.DocToCalcReader
                            = DevTreks.Data.Helpers.FileStorageIO.GetXmlReader(
                                  this.ObsCalculatorParams.ExtensionDocToCalcURI.URIDataManager.InitialDocToCalcURI,
                                  this.ObsCalculatorParams.AnalyzerParms.ObservationFile);
                        if (this.ObsCalculatorParams.DocToCalcReader != null)
                        {
                            using (this.ObsCalculatorParams.DocToCalcReader)
                            {
                                this.ObsCalculatorParams.DocToCalcReader.MoveToContent();
                                this.ObsCalculatorParams.AnalyzerParms.Ancestors.Clear();
                                this.ObsCalculatorParams.CurrentElementNodeName
                                    = string.Empty;
                                this.ObsCalculatorParams.ParentElementNodeName
                                                = string.Empty;
                                LinkedViewCount = 0;
                                AddObservations(bHasInitialColumnDictionary);
                            }
                        }
                        if (this.ObsCalculatorParams.ErrorMessage != string.Empty)
                        {
                            //fix all errors before running an analysis
                            this.ObsCalculatorParams.ErrorMessage
                                = this.ObsCalculatorParams.ErrorMessage;
                            break;
                        }
                        i++;
                    }
                }
                if (this.ObsCalculatorParams.ErrorMessage == string.Empty)
                {
                    if (bHasInitialColumnDictionary)
                    {
                        //save the observations file
                        if (TextFile != null)
                        {
                            //2 passes means using syntax can't be used
                            TextFile.Flush();
                            TextFile.Close();
                            HasGoodObservationFile = true;
                        }
                    }
                    else
                    {
                        //second pass builds the observations
                        StreamAndSaveObservation();
                    }
                }
            }
            return(HasGoodObservationFile);
        }
        public bool SetFNSRStockCalculations(double multiplier,
                                             CalculatorParameters calcParameters, FNSR01Calculator foodNutSR)
        {
            bool bHasCalculations = false;

            if (foodNutSR != null)
            {
                foodNutSR.ActualWater_g        = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Water_g);
                foodNutSR.ActualEnerg_Kcal     = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Energ_Kcal);
                foodNutSR.ActualProtein_g      = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Protein_g);
                foodNutSR.ActualLipid_Tot_g    = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Lipid_Tot_g);
                foodNutSR.ActualAsh_g          = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Ash_g);
                foodNutSR.ActualCarbohydrt_g   = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Carbohydrt_g);
                foodNutSR.ActualFiber_TD_g     = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Fiber_TD_g);
                foodNutSR.ActualSugar_Tot_g    = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Sugar_Tot_g);
                foodNutSR.ActualCalcium_mg     = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Calcium_mg);
                foodNutSR.ActualIron_mg        = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Iron_mg);
                foodNutSR.ActualMagnesium_mg   = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Magnesium_mg);
                foodNutSR.ActualPhosphorus_mg  = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Phosphorus_mg);
                foodNutSR.ActualPotassium_mg   = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Potassium_mg);
                foodNutSR.ActualSodium_mg      = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Sodium_mg);
                foodNutSR.ActualZinc_mg        = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Zinc_mg);
                foodNutSR.ActualCopper_mg      = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Copper_mg);
                foodNutSR.ActualManganese_mg   = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Manganese_mg);
                foodNutSR.ActualSelenium_pg    = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Selenium_pg);
                foodNutSR.ActualVit_C_mg       = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Vit_C_mg);
                foodNutSR.ActualThiamin_mg     = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Thiamin_mg);
                foodNutSR.ActualRiboflavin_mg  = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Riboflavin_mg);
                foodNutSR.ActualNiacin_mg      = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Niacin_mg);
                foodNutSR.ActualPanto_Acid_mg  = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Panto_Acid_mg);
                foodNutSR.ActualVit_B6_mg      = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Vit_B6_mg);
                foodNutSR.ActualFolate_Tot_pg  = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Folate_Tot_pg);
                foodNutSR.ActualFolic_Acid_pg  = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Folic_Acid_pg);
                foodNutSR.ActualFood_Folate_pg = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Food_Folate_pg);
                foodNutSR.ActualFolate_DFE_pg  = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Folate_DFE_pg);
                foodNutSR.ActualCholine_Tot_mg = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Choline_Tot_mg);
                foodNutSR.ActualVit_B12_pg     = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Vit_B12_pg);
                foodNutSR.ActualVit_A_IU       = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Vit_A_IU);
                foodNutSR.ActualVit_A_RAE      = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Vit_A_RAE);
                foodNutSR.ActualRetinol_pg     = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Retinol_pg);
                foodNutSR.ActualAlpha_Carot_pg = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Alpha_Carot_pg);
                foodNutSR.ActualBeta_Carot_pg  = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Beta_Carot_pg);
                foodNutSR.ActualBeta_Crypt_pg  = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Beta_Crypt_pg);
                foodNutSR.ActualLycopene_pg    = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Lycopene_pg);
                foodNutSR.ActualLut_Zea_pg     = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Lut_Zea_pg);
                foodNutSR.ActualVit_E_mg       = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Vit_E_mg);
                foodNutSR.ActualVit_D_pg       = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Vit_D_pg);
                foodNutSR.ActualViVit_D_IU     = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.ViVit_D_IU);
                foodNutSR.ActualVit_K_pg       = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Vit_K_pg);
                foodNutSR.ActualFA_Sat_g       = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.FA_Sat_g);
                foodNutSR.ActualFA_Mono_g      = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.FA_Mono_g);
                foodNutSR.ActualFA_Poly_g      = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.FA_Poly_g);
                foodNutSR.ActualCholestrl_mg   = GetActualFoodNutrientProperty(foodNutSR, foodNutSR.Cholestrl_mg);

                SetFoodNutritionInputCosts(calcParameters, ref foodNutSR);

                bHasCalculations = true;
            }
            else
            {
                calcParameters.ErrorMessage = Errors.MakeStandardErrorMsg("CALCULATORS_WRONG_ONE");
            }
            return(bHasCalculations);
        }
Example #25
0
        //kept for consistency with Extension pattern, but NPV calculators use the NPVCalcs extension
        public async Task <bool> RunCalculatorStep(
            ExtensionContentURI extDocToCalcURI, ExtensionContentURI extCalcDocURI,
            string stepNumber, IList <string> urisToAnalyze,
            IDictionary <string, string> updates, CancellationToken cancellationToken)
        {
            bool bHasCalculation = false;
            CalculatorHelpers    eCalcHelpers = new CalculatorHelpers();
            CalculatorParameters NPV1CalcParams
                = CalculatorHelpers.SetCalculatorParameters(
                      extDocToCalcURI, extCalcDocURI, stepNumber, urisToAnalyze,
                      updates);
            NPV1CalculatorHelper npv1BudgetHelper
                = new NPV1CalculatorHelper(NPV1CalcParams);

            ContractHelpers.EXTENSION_STEPS eStepNumber
                = ContractHelpers.GetEnumStepNumber(stepNumber);
            bool bHasUpdates = false;

            switch (eStepNumber)
            {
            case ContractHelpers.EXTENSION_STEPS.stepzero:
                bHasCalculation = true;
                break;

            case ContractHelpers.EXTENSION_STEPS.stepone:
                bHasCalculation = true;
                break;

            case ContractHelpers.EXTENSION_STEPS.steptwo:
                //clear updates collection
                updates.Clear();
                if (NPV1CalcParams != null)
                {
                    //set constants for this step
                    bHasCalculation
                        = await NPV1CalculatorHelper.SetConstants(NPV1CalcParams);
                }
                extDocToCalcURI.URIDataManager.NeedsFullView    = false;
                extDocToCalcURI.URIDataManager.NeedsSummaryView = false;
                break;

            case ContractHelpers.EXTENSION_STEPS.stepthree:
                //get rid of any update member that was added after running the same step 2x
                bHasUpdates = await CalculatorHelpers.RefreshUpdates(NPV1CalcParams, stepNumber, updates);

                if (NPV1CalcParams != null)
                {
                    //no constants; just an xml edit of NRImpacts
                    bHasCalculation = true;
                }
                extDocToCalcURI.URIDataManager.NeedsFullView    = false;
                extDocToCalcURI.URIDataManager.NeedsSummaryView = false;
                break;

            case ContractHelpers.EXTENSION_STEPS.stepfour:
                //get rid of any update member that was added after running the same step 2x
                bHasUpdates = await CalculatorHelpers.RefreshUpdates(NPV1CalcParams, stepNumber, updates);

                if (NPV1CalcParams != null)
                {
                    if (NPV1CalcParams.ExtensionDocToCalcURI.URIDataManager.SubAppType
                        != Constants.SUBAPPLICATION_TYPES.devpacks.ToString())
                    {
                        //run the calculations
                        bHasCalculation = await npv1BudgetHelper.RunNPV1CalculatorCalculations();
                    }
                    else
                    {
                        //run custom document calculations
                        bHasCalculation
                            = await npv1BudgetHelper.RunDevPacksCalculations(NPV1CalcParams);
                    }
                    extDocToCalcURI.ErrorMessage  = NPV1CalcParams.ErrorMessage;
                    extDocToCalcURI.ErrorMessage += NPV1CalcParams.ExtensionDocToCalcURI.ErrorMessage;
                    if (!bHasCalculation)
                    {
                        extDocToCalcURI.ErrorMessage = (extDocToCalcURI.ErrorMessage == string.Empty) ?
                                                       Errors.MakeStandardErrorMsg("CALCULATORS_URI_MISMATCH")
                                : extDocToCalcURI.ErrorMessage;
                        return(bHasCalculation);
                    }
                    if (string.IsNullOrEmpty(extDocToCalcURI.ErrorMessage))
                    {
                        //two step calculators need to be saved now
                        CheckForLastStepCalculator(NPV1CalcParams,
                                                   eStepNumber, extDocToCalcURI);
                        //replace the old calculator with the new one
                        //and save the new calculations document
                        bHasCalculation
                            = await CalculatorHelpers.SaveNewCalculationsDocument(NPV1CalcParams);
                    }
                    else
                    {
                        bHasCalculation = false;
                    }
                }
                extDocToCalcURI.URIDataManager.NeedsFullView    = true;
                extDocToCalcURI.URIDataManager.NeedsSummaryView = false;
                break;

            case ContractHelpers.EXTENSION_STEPS.stepfive:
                extDocToCalcURI.URIDataManager.NeedsFullView    = false;
                extDocToCalcURI.URIDataManager.NeedsSummaryView = true;
                extCalcDocURI.URIFileExtensionType = CalculatorHelpers.GetAttribute(NPV1CalcParams.LinkedViewElement,
                                                                                    Calculator1.cFileExtensionType);
                bHasCalculation = true;
                //tells addinhelper to save calcs
                CalculatorHelpers.SetTempDocSaveCalcsProperty(extDocToCalcURI);
                break;

            default:
                //as many steps as needed can be added to this addin
                break;
            }
            extDocToCalcURI.ErrorMessage += NPV1CalcParams.ErrorMessage;
            return(bHasCalculation);
        }
Example #26
0
        public async Task <bool> RunAnalyzerStep(
            ExtensionContentURI extDocToCalcURI, ExtensionContentURI extCalcDocURI,
            string stepNumber, IList <string> urisToAnalyze,
            IDictionary <string, string> updates, CancellationToken cancellationToken)
        {
            bool bHasAnalysis = false;
            CalculatorParameters npv1CalcParams
                = CalculatorHelpers.SetCalculatorParameters(
                      extDocToCalcURI, extCalcDocURI, stepNumber, urisToAnalyze,
                      updates);
            NPV1AnalyzerHelper npv1AnalyzerHelper = new NPV1AnalyzerHelper(npv1CalcParams);

            //check to make sure the analyzer can be run
            npv1AnalyzerHelper.SetOptions();
            bool bHasUpdates = false;

            if (npv1AnalyzerHelper.NPV1CalculatorParams.ErrorMessage != string.Empty)
            {
                extDocToCalcURI.ErrorMessage += npv1AnalyzerHelper.NPV1CalculatorParams.ErrorMessage;
                return(false);
            }
            ContractHelpers.EXTENSION_STEPS eStepNumber
                = ContractHelpers.GetEnumStepNumber(stepNumber);
            switch (eStepNumber)
            {
            case ContractHelpers.EXTENSION_STEPS.stepzero:
                bHasAnalysis = true;
                break;

            case ContractHelpers.EXTENSION_STEPS.stepone:
                bHasAnalysis = true;
                break;

            case ContractHelpers.EXTENSION_STEPS.steptwo:
                //clear updates collection
                updates.Clear();
                //just need the html form edits in this step
                bHasAnalysis = true;
                extDocToCalcURI.URIDataManager.NeedsFullView    = false;
                extDocToCalcURI.URIDataManager.NeedsSummaryView = false;
                break;

            case ContractHelpers.EXTENSION_STEPS.stepthree:
                //get rid of any update member that was added after running the same step 2x
                bHasUpdates = await CalculatorHelpers.RefreshUpdates(npv1CalcParams, stepNumber, updates);

                //linked view insertions needs some analysis parameters
                SetAnalyzerParameters(npv1AnalyzerHelper, npv1CalcParams);
                if (npv1CalcParams.SubApplicationType == Constants.SUBAPPLICATION_TYPES.devpacks)
                {
                    bHasAnalysis = await npv1AnalyzerHelper.RunAnalysis(npv1CalcParams.UrisToAnalyze);
                }
                else
                {
                    bHasAnalysis = await npv1AnalyzerHelper.RunAnalysis();
                }
                extDocToCalcURI.ErrorMessage  = npv1CalcParams.ErrorMessage;
                extDocToCalcURI.ErrorMessage += npv1AnalyzerHelper.NPV1CalculatorParams.ErrorMessage;
                if (!bHasAnalysis)
                {
                    extDocToCalcURI.ErrorMessage = (extDocToCalcURI.ErrorMessage == string.Empty) ?
                                                   Errors.MakeStandardErrorMsg("CALCULATORS_URI_MISMATCH")
                            : extDocToCalcURI.ErrorMessage;
                    return(bHasAnalysis);
                }
                if (string.IsNullOrEmpty(extDocToCalcURI.ErrorMessage))
                {
                    //two step analyzers need to be saved now
                    NPV1AnalyzerHelper.ANALYZER_TYPES eAnalyzerType
                        = npv1AnalyzerHelper.GetAnalyzerType(
                              npv1AnalyzerHelper.NPV1CalculatorParams.AnalyzerParms.AnalyzerType);
                    //when 3+ step analyzers start being used
                    CheckForLastStepAnalyzer(eAnalyzerType,
                                             eStepNumber, extDocToCalcURI);
                    if (!CalculatorHelpers.IsSaveAction(extDocToCalcURI))
                    {
                        //replace the old calculator with the new one
                        //and save the new calculations document
                        bool bHasReplacedCalcDoc
                            = await CalculatorHelpers.SaveNewCalculationsDocument(
                                  npv1AnalyzerHelper.NPV1CalculatorParams);

                        if (bHasReplacedCalcDoc)
                        {
                            bHasAnalysis = true;
                        }
                        else
                        {
                            extDocToCalcURI.ErrorMessage = Errors.MakeStandardErrorMsg("ANALYSES_ID_MISMATCH");
                        }
                    }
                }
                else
                {
                    bHasAnalysis = false;
                }
                extDocToCalcURI.URIDataManager.NeedsFullView    = true;
                extDocToCalcURI.URIDataManager.NeedsSummaryView = false;
                break;

            case ContractHelpers.EXTENSION_STEPS.stepfour:
                bHasAnalysis = true;
                if (npv1AnalyzerHelper.AnalyzerType
                    == NPV1AnalyzerHelper.ANALYZER_TYPES.npvtotal1 ||
                    npv1AnalyzerHelper.AnalyzerType
                    == NPV1AnalyzerHelper.ANALYZER_TYPES.npvstat1 ||
                    npv1AnalyzerHelper.AnalyzerType
                    == NPV1AnalyzerHelper.ANALYZER_TYPES.npvchangeyr ||
                    npv1AnalyzerHelper.AnalyzerType
                    == NPV1AnalyzerHelper.ANALYZER_TYPES.npvchangeid ||
                    npv1AnalyzerHelper.AnalyzerType
                    == NPV1AnalyzerHelper.ANALYZER_TYPES.npvchangealt ||
                    npv1AnalyzerHelper.AnalyzerType
                    == NPV1AnalyzerHelper.ANALYZER_TYPES.npvprogress1)
                {
                    if (npv1CalcParams.NeedsFullView)
                    {
                        extDocToCalcURI.URIDataManager.NeedsFullView    = true;
                        extDocToCalcURI.URIDataManager.NeedsSummaryView = false;
                    }
                    else
                    {
                        extDocToCalcURI.URIDataManager.NeedsFullView    = false;
                        extDocToCalcURI.URIDataManager.NeedsSummaryView = true;
                    }
                    extCalcDocURI.URIFileExtensionType = CalculatorHelpers.GetAttribute(npv1CalcParams.LinkedViewElement,
                                                                                        Calculator1.cFileExtensionType);
                }
                if (extDocToCalcURI.URIDataManager.TempDocSaveMethod
                    == Constants.SAVECALCS_METHOD.saveastext.ToString())
                {
                    //analyzers aren't yet available
                }
                else
                {
                    //tells addinhelper to save calcs
                    CalculatorHelpers.SetTempDocSaveAnalysesProperty(extDocToCalcURI);
                }
                break;

            default:
                //as many steps as needed can be added to this addin
                break;
            }
            extDocToCalcURI.ErrorMessage += npv1AnalyzerHelper.NPV1CalculatorParams.ErrorMessage;
            return(bHasAnalysis);
        }
Example #27
0
        public async Task <bool> RunAnalyzerStep(
            ExtensionContentURI extDocToCalcURI, ExtensionContentURI extCalcDocURI,
            string stepNumber, IList <string> urisToAnalyze,
            IDictionary <string, string> updates, CancellationToken cancellationToken)
        {
            bool bHasAnalysis = false;
            CalculatorParameters fnCalcParams
                = CalculatorHelpers.SetCalculatorParameters(
                      extDocToCalcURI, extCalcDocURI, stepNumber, urisToAnalyze,
                      updates);
            FNAnalyzerHelper fnAnalyzerHelper = new FNAnalyzerHelper(fnCalcParams);

            //check to make sure the analyzer can be run
            fnAnalyzerHelper.SetOptions();
            if (fnAnalyzerHelper.FNCalculatorParams.ErrorMessage != string.Empty)
            {
                extDocToCalcURI.ErrorMessage += fnAnalyzerHelper.FNCalculatorParams.ErrorMessage;
                return(false);
            }
            ContractHelpers.EXTENSION_STEPS eStepNumber
                = ContractHelpers.GetEnumStepNumber(stepNumber);
            bool bHasUpdates = false;

            switch (eStepNumber)
            {
            case ContractHelpers.EXTENSION_STEPS.stepzero:
                bHasAnalysis = true;
                break;

            case ContractHelpers.EXTENSION_STEPS.stepone:
                bHasAnalysis = true;
                break;

            case ContractHelpers.EXTENSION_STEPS.steptwo:
                //clear updates collection
                updates.Clear();
                //just need the html form edits in this step
                bHasAnalysis = true;
                extDocToCalcURI.URIDataManager.NeedsFullView    = false;
                extDocToCalcURI.URIDataManager.NeedsSummaryView = false;
                break;

            case ContractHelpers.EXTENSION_STEPS.stepthree:
                //get rid of any update member that was added after running the same step 2x
                bHasUpdates = await CalculatorHelpers.RefreshUpdates(fnCalcParams, stepNumber, updates);

                if (fnAnalyzerHelper.AnalyzerType
                    == FNAnalyzerHelper.ANALYZER_TYPES.resources01)
                {
                    //linked view insertions needs some analysis parameters
                    SetAnalyzerParameters(fnAnalyzerHelper, fnCalcParams);
                    //the calculator pattern handles children linked view insertions
                    //better than the analyzer pattern
                    FNCalculatorHelper fnCalculatorHelper
                                 = new FNCalculatorHelper(fnCalcParams);
                    bHasAnalysis = await fnCalculatorHelper.RunCalculations();
                }
                else
                {
                    //run the analysis (when analyses are available)
                    //bHasAnalysis = fnAnalyzerHelper
                    //    .RunAnalysis(urisToAnalyze);
                }
                extDocToCalcURI.ErrorMessage  = fnCalcParams.ErrorMessage;
                extDocToCalcURI.ErrorMessage += fnAnalyzerHelper.FNCalculatorParams.ErrorMessage;
                if (!bHasAnalysis)
                {
                    extDocToCalcURI.ErrorMessage = (extDocToCalcURI.ErrorMessage == string.Empty) ?
                                                   Errors.MakeStandardErrorMsg("CALCULATORS_URI_MISMATCH")
                            : extDocToCalcURI.ErrorMessage;
                    return(bHasAnalysis);
                }
                if (string.IsNullOrEmpty(extDocToCalcURI.ErrorMessage))
                {
                    //two step analyzers need to be saved now
                    FNAnalyzerHelper.ANALYZER_TYPES eAnalyzerType
                        = fnAnalyzerHelper.GetAnalyzerType(
                              fnAnalyzerHelper.FNCalculatorParams.AnalyzerParms.AnalyzerType);
                    //when 3+ step analyzers start being used
                    CheckForLastStepAnalyzer(eAnalyzerType,
                                             eStepNumber, extDocToCalcURI);
                    if (!CalculatorHelpers.IsSaveAction(extDocToCalcURI))
                    {
                        //replace the old calculator with the new one
                        //and save the new calculations document
                        bool bHasReplacedCalcDoc
                            = await CalculatorHelpers.SaveNewCalculationsDocument(
                                  fnAnalyzerHelper.FNCalculatorParams);

                        if (bHasReplacedCalcDoc)
                        {
                            //the resource01 app uses the calculator, rather
                            //than analyzer, pattern (i.e. children linked views
                            //can be inserted)
                            if (fnAnalyzerHelper.AnalyzerType
                                != FNAnalyzerHelper.ANALYZER_TYPES.resources01)
                            {
                                //and add xmldoc params to update collection
                                //only doctocalc gets updated
                                CalculatorHelpers.AddXmlDocAndXmlDocIdsToUpdates(
                                    fnAnalyzerHelper.FNCalculatorParams);
                            }
                            bHasAnalysis = true;
                        }
                        else
                        {
                            extDocToCalcURI.ErrorMessage = Errors.MakeStandardErrorMsg("ANALYSES_ID_MISMATCH");
                        }
                    }
                }
                else
                {
                    bHasAnalysis = false;
                }
                extDocToCalcURI.URIDataManager.NeedsFullView    = true;
                extDocToCalcURI.URIDataManager.NeedsSummaryView = false;
                break;

            case ContractHelpers.EXTENSION_STEPS.stepfour:
                bHasAnalysis = true;
                if (fnAnalyzerHelper.AnalyzerType
                    == FNAnalyzerHelper.ANALYZER_TYPES.resources01)
                {
                    extDocToCalcURI.URIDataManager.NeedsFullView    = false;
                    extDocToCalcURI.URIDataManager.NeedsSummaryView = true;
                    extCalcDocURI.URIFileExtensionType = CalculatorHelpers.GetAttribute(fnCalcParams.LinkedViewElement,
                                                                                        Calculator1.cFileExtensionType);
                }
                if (extDocToCalcURI.URIDataManager.TempDocSaveMethod
                    == Constants.SAVECALCS_METHOD.saveastext.ToString())
                {
                    //analyzers aren't yet available
                }
                else
                {
                    //tells addinhelper to save calcs
                    CalculatorHelpers.SetTempDocSaveAnalysesProperty(extDocToCalcURI);
                }
                break;

            default:
                //as many steps as needed can be added to this addin
                break;
            }
            extDocToCalcURI.ErrorMessage += fnAnalyzerHelper.FNCalculatorParams.ErrorMessage;
            return(bHasAnalysis);
        }
Example #28
0
        public async Task <bool> RunSubAlgorithm3Async(string inputFile1Path, string inputFile2Path)
        {
            bool   bHasCalcs = false;
            string sBaseURL  =
                "https://ussouthcentral.services.azureml.net/workspaces/d454361ecdcb4ec4b03fa1aec5a7c0e2/services/8b1074b465ea4258a11ec48ce64ae257/jobs";
            string sPlatForm = CalculatorHelpers.GetPlatform(_params.ExtensionDocToCalcURI, inputFile1Path);

            if (sPlatForm != CalculatorHelpers.PLATFORM_TYPES.azure.ToString())
            {
                sBaseURL = "https://ussouthcentral.services.azureml.net/workspaces/d454361ecdcb4ec4b03fa1aec5a7c0e2/services/8b1074b465ea4258a11ec48ce64ae257/execute?api-version=2.0&details=true";
            }
            string sApiKey =
                "RO2Ev5dRSKqNJ4jz+zoT0qDntEsKbyizbgZKlhOR2vGztsjBD3S3C8nmIlZI9TbbmCcsw+unwhky1GgZ5qiHmg==";
            string sError = string.Empty;


            //web server expects to store in temp/randomid/name.csv
            //scoring results
            string sOutputData1URL = CalculatorHelpers.GetTempContainerPath("outputdata1.csv");
            //model results
            string sOutputData2URL = CalculatorHelpers.GetTempContainerPath("outputdata2.csv");
            //web service expects urls that start with container names
            string sInput1ContainerPath = CalculatorHelpers.GetContainerPathFromFullURIPath("resources", inputFile1Path);
            string sInput2ContainerPath = CalculatorHelpers.GetContainerPathFromFullURIPath("resources", inputFile2Path);

            //async wait so that results can be stored in output file location and parsed into string lines
            SetResponse2(sBaseURL, sApiKey, sInput1ContainerPath, sInput2ContainerPath, sOutputData1URL, sOutputData2URL).Wait();
            StringBuilder sb = new StringBuilder();

            //if web service successully saved the results, the response will start with Success
            if (_response.StartsWith("Success"))
            {
                //return the output file contents in a string list of lines
                //must convert container path to full path
                string        sOutput1FullDataURL = string.Concat("https://devtreks1.blob.core.windows.net/", sOutputData1URL);
                List <string> lines = new List <string>();
                //azure emulator can't process real Azure URL so this won't work
                //instead, double check that output url is actually saved
                lines              = CalculatorHelpers.ReadLines(_params.ExtensionDocToCalcURI, sOutput1FullDataURL, out sError);
                this.ErrorMessage += sError;
                //this results in endless wait
                //lines = await CalculatorHelpers.ReadLinesAsync(sOutputDataURL);
                if (lines == null)
                {
                    this.ErrorMessage += string.Concat(" ", Errors.MakeStandardErrorMsg("DATAURL_BAD"));
                    return(bHasCalcs);
                }
                if (lines.Count == 0)
                {
                    this.ErrorMessage += string.Concat(" ", Errors.MakeStandardErrorMsg("DATAURL_BAD"));
                    return(bHasCalcs);
                }
                sb = new StringBuilder();
                sb.AppendLine("aml results");
                //dep var has to be in the R project 1st column
                //string sLine = string.Concat("first variable:  ", _colNames[0]);
                string[] line = new List <string>().ToArray();
                int      iPos = 0;
                for (int i = 0; i < lines.Count(); i++)
                {
                    line = lines[i].Split(Constants.CSV_DELIMITERS);
                    //lineout[1] = CalculatorHelpers.ConvertStringToDouble(line[0]).ToString("N4", CultureInfo.InvariantCulture);
                    sb.AppendLine(Shared.GetLine(line, false));
                }
                if (this.MathResult.ToLower().StartsWith("http"))
                {
                    sError = string.Empty;
                    bool bHasSaved = CalculatorHelpers.SaveTextInURI(
                        _params.ExtensionDocToCalcURI, sb.ToString(), this.MathResult, out sError);
                    if (!string.IsNullOrEmpty(sError))
                    {
                        this.MathResult += sError;
                    }
                }
                else
                {
                    this.MathResult = sb.ToString();
                }
                bHasCalcs = true;
                //last line of string should have the QTM vars
                if (line != null)
                {
                    //last string is prediction
                    iPos = line.Count() - 1;
                    //int iPos = line.Count() - 3;
                    if (line[iPos] != null)
                    {
                        this.QTPredicted = CalculatorHelpers.ConvertStringToDouble(line[iPos]);
                    }
                }
                string sOutput2FullDataURL = string.Concat("https://devtreks1.blob.core.windows.net/", sOutputData2URL);
                lines = new List <string>();
                //azure emulator can't process real Azure URL so this won't work
                //instead, double check that output url is actually saved
                lines              = CalculatorHelpers.ReadLines(_params.ExtensionDocToCalcURI, sOutput2FullDataURL, out sError);
                this.ErrorMessage += sError;
                if (lines == null)
                {
                    this.ErrorMessage += string.Concat(" ", Errors.MakeStandardErrorMsg("DATAURL_BAD"));
                    return(bHasCalcs);
                }
                if (lines.Count == 0)
                {
                    this.ErrorMessage += string.Concat(" ", Errors.MakeStandardErrorMsg("DATAURL_BAD"));
                    return(bHasCalcs);
                }
                sb = new StringBuilder();
                //dep var has to be in the R project 1st column
                //string sLine = string.Concat("first variable:  ", _colNames[0]);
                line = new List <string>().ToArray();
                double dbCI = 0;
                for (int i = 0; i < lines.Count(); i++)
                {
                    line = lines[i].Split(Constants.CSV_DELIMITERS);
                    if (line != null)
                    {
                        iPos = 0;
                        //used to derive conf interval
                        dbCI = CalculatorHelpers.ConvertStringToDouble(line[iPos]);
                        sb.AppendLine(string.Format("{0} {1}", "Mean Absolute Error: ", dbCI.ToString()));
                        double dbScore = 0;
                        if (line.Count() >= 2)
                        {
                            iPos    = 1;
                            dbScore = CalculatorHelpers.ConvertStringToDouble(line[iPos]);
                            sb.AppendLine(string.Format("{0} {1}", "Root Mean Squared Error: ", dbScore.ToString()));
                        }
                        if (line.Count() >= 3)
                        {
                            iPos    = 2;
                            dbScore = CalculatorHelpers.ConvertStringToDouble(line[iPos]);
                            sb.AppendLine(string.Format("{0} {1}", "Relative Absolute Error: ", dbScore.ToString()));
                        }
                        if (line.Count() >= 4)
                        {
                            iPos    = 3;
                            dbScore = CalculatorHelpers.ConvertStringToDouble(line[iPos]);
                            sb.AppendLine(string.Format("{0} {1}", "Relative Squared Error: ", dbScore.ToString()));
                        }
                        if (line.Count() >= 5)
                        {
                            iPos    = 4;
                            dbScore = CalculatorHelpers.ConvertStringToDouble(line[iPos]);
                            sb.AppendLine(string.Format("{0} {1}", "Coefficient of Determination: ", dbScore.ToString()));
                        }
                        //sb.AppendLine(Shared.GetLine(line, false));
                    }
                }
                this.MathResult += sb.ToString();
                bHasCalcs        = true;
                //last line of string should have the QTM vars
                if (line != null)
                {
                    if (line[iPos] != null)
                    {
                        dbCI = CalculatorHelpers.ConvertStringToDouble(line[iPos]);
                    }
                    this.QTL = this.QTPredicted - dbCI;
                    this.QTU = this.QTPredicted + dbCI;
                }
            }
            else
            {
                this.ErrorMessage += "The calculations could not be run using the web service.";
            }
            return(bHasCalcs);
        }
Example #29
0
        public async Task <bool> RunSubAlgorithm1or2Async(string inputFilePath, string rFile)
        {
            bool   bHasCalcs = false;
            string sBaseURL  =
                "https://ussouthcentral.services.azureml.net/workspaces/d454361ecdcb4ec4b03fa1aec5a7c0e2/services/b10e6b4c4e63438999cc45147bbe006c/jobs";

            if (_subalgorithm == Calculator1.MATH_SUBTYPES.subalgorithm2.ToString())
            {
                sBaseURL = "https://ussouthcentral.services.azureml.net/workspaces/d454361ecdcb4ec4b03fa1aec5a7c0e2/services/abd32060dc014d0e8fe1256e0f694daa/jobs";
            }
            string sPlatForm = _params.ExtensionDocToCalcURI.URIDataManager.PlatformType.ToString();

            if (sPlatForm != CalculatorHelpers.PLATFORM_TYPES.azure.ToString())
            {
                sBaseURL = "https://ussouthcentral.services.azureml.net/workspaces/d454361ecdcb4ec4b03fa1aec5a7c0e2/services/b10e6b4c4e63438999cc45147bbe006c/execute?api-version=2.0&details=true";
                if (_subalgorithm == Calculator1.MATH_SUBTYPES.subalgorithm2.ToString())
                {
                    sBaseURL = "https://ussouthcentral.services.azureml.net/workspaces/d454361ecdcb4ec4b03fa1aec5a7c0e2/services/abd32060dc014d0e8fe1256e0f694daa/execute?api-version=2.0&details=true";
                }
            }
            //r web service is default
            string sApiKey =
                "fxBeL9LJ3ORm0kW0DtKhT99OfUK6YgBlc59crizYhlxKoEjRd3kuDHvPRuehCQ02VJhPPXcdYTp2pDUynb9gMA==";

            if (_subalgorithm == Calculator1.MATH_SUBTYPES.subalgorithm2.ToString())
            {
                //python
                sApiKey =
                    "/bjDNKx4OWdMIQu6CkvWCIhcfUOCTp9jUE9kD7uylwhOYyhVFOqAFA7M75mJjHS6p6jnAhCvFn1jSl678gzPVA==";
            }
            string sError = string.Empty;
            //convert the script file to the script string expected by the algorithm
            List <string> rlines = new List <string>();

            rlines             = CalculatorHelpers.ReadLines(_params.ExtensionDocToCalcURI, rFile, out sError);
            this.ErrorMessage += sError;
            if (rlines == null)
            {
                this.ErrorMessage += string.Concat(" ", Errors.MakeStandardErrorMsg("DATAURL_BAD"));
                return(bHasCalcs);
            }
            if (rlines.Count == 0)
            {
                this.ErrorMessage += string.Concat(" ", Errors.MakeStandardErrorMsg("DATAURL_BAD"));
                return(bHasCalcs);
            }
            StringBuilder sbR = new StringBuilder();

            for (int i = 0; i < rlines.Count(); i++)
            {
                sbR.AppendLine(rlines[i]);
            }
            string rScript = sbR.ToString();

            //web server expects to store in temp/randomid/name.csv
            //web service stores in temp blob
            string sOutputDataURL = CalculatorHelpers.GetTempContainerPath("Routput.csv");

            //web service expects urls that start with container names
            //regular rproject file must be stored in JDataURL
            string sInputContainerPath = CalculatorHelpers.GetContainerPathFromFullURIPath("resources", inputFilePath);

            //async wait so that results can be stored in output file location and parsed into string lines
            SetResponse(sBaseURL, sApiKey, sInputContainerPath, sOutputDataURL, rScript).Wait();
            StringBuilder sb = new StringBuilder();

            //if web service successully saved the results, the response will start with Success
            if (_response.StartsWith("Success"))
            {
                //return the output file contents in a string list of lines
                //must convert container path to full path
                string        sOutputFullDataURL = string.Concat("https://devtreks1.blob.core.windows.net/", sOutputDataURL);
                List <string> lines = new List <string>();
                //azure emulator can't process real Azure URL so this won't work
                //instead, double check that output url is actually saved
                lines              = CalculatorHelpers.ReadLines(_params.ExtensionDocToCalcURI, sOutputFullDataURL, out sError);
                this.ErrorMessage += sError;
                //this results in endless wait-try ReadLinesAsync(sOutputDataURL).ConfigureAwait(false)
                //lines = await CalculatorHelpers.ReadLinesAsync(sOutputDataURL);
                if (lines == null)
                {
                    this.ErrorMessage += string.Concat(" ", Errors.MakeStandardErrorMsg("DATAURL_BAD"));
                    return(bHasCalcs);
                }
                if (lines.Count == 0)
                {
                    this.ErrorMessage += string.Concat(" ", Errors.MakeStandardErrorMsg("DATAURL_BAD"));
                    return(bHasCalcs);
                }
                sb = new StringBuilder();
                if (_subalgorithm == Calculator1.MATH_SUBTYPES.subalgorithm2.ToString())
                {
                    sb.AppendLine("py results");
                }
                else
                {
                    sb.AppendLine("r results");
                }
                //dep var has to be in the R project 1st column
                string   sLine = string.Concat("first variable:  ", _colNames[0]);
                string[] line  = new List <string>().ToArray();
                for (int i = 0; i < lines.Count(); i++)
                {
                    line = lines[i].Split(Constants.CSV_DELIMITERS);
                    //lineout[1] = CalculatorHelpers.ConvertStringToDouble(line[0]).ToString("N4", CultureInfo.InvariantCulture);
                    sb.AppendLine(Shared.GetLine(line, false));
                }
                if (this.MathResult.ToLower().StartsWith("http"))
                {
                    sError = string.Empty;
                    bool bHasSaved = CalculatorHelpers.SaveTextInURI(
                        _params.ExtensionDocToCalcURI, sb.ToString(), this.MathResult, out sError);
                    if (!string.IsNullOrEmpty(sError))
                    {
                        this.MathResult += sError;
                    }
                }
                else
                {
                    this.MathResult = sb.ToString();
                }
                bHasCalcs = true;
                //last line of string should have the QTM vars
                if (line != null)
                {
                    int iPos = 0;
                    if (line[iPos] != null)
                    {
                        this.QTPredicted = CalculatorHelpers.ConvertStringToDouble(line[iPos]);
                    }
                    iPos = 1;
                    if (line[iPos] != null)
                    {
                        this.QTL = CalculatorHelpers.ConvertStringToDouble(line[iPos]);
                    }
                    iPos = 2;
                    if (line[iPos] != null)
                    {
                        this.QTU = CalculatorHelpers.ConvertStringToDouble(line[iPos]);
                    }
                }
            }
            else
            {
                this.ErrorMessage += string.Concat(_response, "The calculations could not be run using the web service.");
            }
            return(bHasCalcs);
        }
Example #30
0
        public void RunOptimization(
            List <TimelinessTimePeriod1> timelinessTimePeriods)
        {
            InitCollections(timelinessTimePeriods);
            if (this.ErrorMessage == string.Empty)
            {
                try
                {
                    //initial collections of TP.OpComps (with each OpComp holding feasible OpComp.TimelinessOpComps)
                    random = new Random(0);
                    // total cost index for problem definition
                    double[][] problemData = MakeProblemData(timelinessTimePeriods);
                    //state represents a solution int array where the first index is the feasibleOpComp
                    //and the second index is the uniqueOpComp
                    //(uniqueOpComp - feasibleOpComp combos that are not possible must have a zero total cost)
                    int[]  state  = RandomState(problemData);
                    double energy = Energy(state, problemData);
                    //best state is the least cost vector of 1 unique opcomp and 1 feasible opcomp
                    int[]  bestState  = state;
                    double bestEnergy = energy;
                    int[]  adjState;
                    double adjEnergy;

                    int iteration = 0;
                    //the higher these are, the longer the algorithm runs
                    //the longer the algo runs the more optimal the solution
                    int    maxIteration = 1000000;
                    double currTemp     = 10000.0;
                    // cooling rate
                    double alpha = 0.995;

                    while (iteration < maxIteration && currTemp > 0.0001)
                    {
                        //adjacent state doesn't allow nonfeasible selections (w,t = 0)
                        adjState  = AdjacentState(state, problemData);
                        adjEnergy = Energy(adjState, problemData);

                        if (adjEnergy < bestEnergy)
                        {
                            bestState  = adjState;
                            bestEnergy = adjEnergy;
                        }
                        // [0, 1.0)
                        double p = random.NextDouble();
                        if (AcceptanceProb(energy, adjEnergy, currTemp) > p)
                        {
                            state  = adjState;
                            energy = adjEnergy;
                        }
                        // cool down; annealing schedule
                        currTemp = currTemp * alpha;
                        ++iteration;
                    }
                    //temperature has cooled to (almost) zero at final iteration
                    MakeBestMachineryCombos(timelinessTimePeriods, bestState, problemData);
                }
                catch (Exception ex)
                {
                    this.ErrorMessage = string.Concat(Errors.GetMessage("RESOURCESTOCKS_NOSIMULATEDANNEALING"),
                                                      ex.ToString());
                }
            }
        }