Beispiel #1
0
        public async Task <bool> RunAlgorithmAsync(List <List <double> > data)
        {
            bool bHasCalculation = false;

            try
            {
                //add the qs to end of list for running in algo
                data.Add(_qs);
                //this algorith uses standard arrays
                double[,] problemData = Shared.GetDoubleArray(data);
                StringBuilder sb = new StringBuilder();
                //set the rank params needed for the needed matrixes
                rows          = problemData.GetUpperBound(0) + 1;
                cols          = problemData.GetUpperBound(1) + 1;
                outs          = GetDistinctOutputValues(problemData, cols);
                inputVarCount = cols - 1;
                if (inputVarCount > maxInputs)
                {
                    //no: need to catch it before the data is sent here
                }
                outputValCount = outs.Count();

                rnd = new Random(159); // 159 makes 'good' output

                double[][] trainMatrix = null;
                double[][] testMatrix  = null;
                //Generating train and test matrices using an 80%-20% split
                MakeTrainAndTest(problemData, out trainMatrix, out testMatrix);

                sb.AppendLine("\nFirst few rows of training matrix, using an 80%-20% split, are:");
                //First few rows of training matrix are
                Helpers.ShowMatrix(sb, trainMatrix, inputVarCount, 5);

                //the first and last params are legit; not sure of the correct basis for 2nd
                NeuralNetwork nn = new NeuralNetwork(inputVarCount, inputVarCount + 1, outputValCount);

                //Training to find best neural network weights using PSO with cross entropy error
                double[] bestWeights = nn.Train(sb, trainMatrix);
                sb.AppendLine("\nBest weights found:");
                Helpers.ShowVector(sb, bestWeights, 2, true);


                //Loading best weights into neural network
                nn.SetWeights(bestWeights);

                sb.AppendLine("\nExamples of the neural network accuracy:\n");
                //Analyzing the neural network accuracy on the test data
                double accuracy = nn.Test(sb, testMatrix);
                this.QTL     = accuracy;
                this.QTLUnit = "percent accuracy";
                sb.AppendLine("Prediction accuracy = " + accuracy.ToString("F4"));
                this.QTPredicted = nn.QTPredicted;
                sb.AppendLine("Predicted QT = " + this.QTPredicted.ToString("F4"));
                if (this.MathResult.ToLower().StartsWith("http"))
                {
                    string 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();
                }
                bHasCalculation = true;
            }
            catch (Exception ex)
            {
                this.ErrorMessage = ex.Message;
            }
            return(bHasCalculation);
        }
        /// <summary>
        /// Run the simulated annealing algo
        /// </summary>
        /// <param name="problemData">matrix of energy requirements (hour to complete task)</param>
        /// <param name="currTemp">initial temperature from which cooldown starts</param>
        /// <param name="alpha">cooling rate</param>
        /// <param name="penalty">a penalty when a worker has more than 1 task</param>
        /// <param name="maxIteration">number of iterations</param>
        public async Task <bool> RunAlgorithmAsync(List <List <double> > data)
        {
            bool bHasCalculation = false;

            try
            {
                random = new Random(0);
                //this algorith uses standard arrays
                double[,] problemData = Shared.GetDoubleArray(data);
                int[]  state      = RandomState(problemData);
                double energy     = Energy(state, problemData, _penalty);
                int[]  bestState  = state;
                double bestEnergy = energy;
                int[]  adjState;
                double adjEnergy;

                int iteration = 0;
                while (iteration < _maxiteration && _currtemp > 0.0001)
                {
                    adjState  = AdjacentState(state, problemData);
                    adjEnergy = Energy(adjState, problemData, _penalty);

                    if (adjEnergy < bestEnergy)
                    {
                        bestState  = adjState;
                        bestEnergy = adjEnergy;
                    }

                    double p = random.NextDouble(); // [0, 1.0)
                    if (AcceptanceProb(energy, adjEnergy, _currtemp) > p)
                    {
                        state  = adjState;
                        energy = adjEnergy;
                    }

                    _currtemp = _currtemp * _alpha; // cool down; annealing schedule
                    ++iteration;
                } // while
                this.BestEnergy = bestEnergy;
                if (this.MathResult.ToLower().StartsWith("http"))
                {
                    bool bHasSaved = await CalculatorHelpers.SaveTextInURI(_params.ExtensionDocToCalcURI,
                                                                           Interpret(bestState, problemData), this.MathResult);

                    if (!string.IsNullOrEmpty(_params.ExtensionDocToCalcURI.ErrorMessage))
                    {
                        this.MathResult += _params.ExtensionDocToCalcURI.ErrorMessage;
                        //done with errormsg
                        _params.ExtensionDocToCalcURI.ErrorMessage = string.Empty;
                    }
                }
                else
                {
                    this.MathResult = Interpret(bestState, problemData);
                }
                bHasCalculation = true;
            }
            catch (Exception ex)
            {
                ErrorMessage = ex.Message;
            }
            return(bHasCalculation);
        }