コード例 #1
0
        private bool EvaluateOperator(object left, object right, IOperator op)
        {
            var leftResult  = _compileResultFactory.Create(left);
            var rightResult = _compileResultFactory.Create(right);
            var result      = op.Apply(leftResult, rightResult);

            if (result.DataType != DataType.Boolean)
            {
                throw new ArgumentException("Illegal operator in expression");
            }
            return((bool)result.Result);
        }
コード例 #2
0
        /// <summary>
        /// Apply the operator until no more improvements can be found.
        /// </summary>
        /// <returns></returns>
        public static bool ApplyUntil <TWeight, TProblem, TObjective, TSolution, TFitness>(this IOperator <TWeight, TProblem, TObjective, TSolution, TFitness> oper,
                                                                                           TProblem problem, TObjective objective, TSolution solution, out TFitness delta)
            where TObjective : ObjectiveBase <TProblem, TSolution, TFitness>
            where TWeight : struct
        {
            delta = objective.Zero;
            var localDelta = delta;

            while (oper.Apply(problem, objective, solution, out localDelta))
            {
                delta = objective.Add(problem, delta, localDelta);
            }
            return(!objective.IsZero(problem, delta));
        }
コード例 #3
0
        public GameResults Generate(int current)
        {
            var randomNumber  = numberGenerator.Generate();
            var correctResult = mathOperator.Apply(current, randomNumber);
            var correct       = new GameResult(correctResult);
            var results       = new List <GameResult> {
                correct
            };

            for (var i = 0; i < quantity - 1; i++)
            {
                var incorrectResult = Random.Range(correctResult + 2, correctResult + 10);
                results.Add(new GameResult(incorrectResult));
            }

            return(new GameResults(mathOperator, results, current, randomNumber));
        }
コード例 #4
0
        /// <summary>
        /// Applies the specified operator to the specified search node.
        /// </summary>
        /// <param name="node">Search node.</param>
        /// <param name="oper">Operator to be applied.</param>
        /// <returns>New search node.</returns>
        protected ISearchNode Apply(ISearchNode node, IOperator oper)
        {
            switch (SearchType)
            {
            case SearchType.Forward:
                return(oper.Apply((IState)node));

            case SearchType.BackwardWithConditions:
                return(oper.ApplyBackwards((IConditions)node));

            case SearchType.BackwardWithStates:
                return(oper.ApplyBackwards((IRelativeState)node).First());

            default:
                throw new NotSupportedException("Unknown search type!");
            }
        }
コード例 #5
0
        /// <summary>
        /// Applies this operation.
        /// </summary>param>
        /// <returns></returns>
        public bool Apply(TProblem problem, TObjective objective, TSolution solution, out TFitness delta)
        {
            var best        = solution;
            var bestFitness = objective.Calculate(problem, solution);

            delta = objective.Zero;
            var success = false;

            for (var i = 0; i < _n; i++)
            {
                TFitness localDelta;
                if (_operator.Apply(problem, objective, solution, out localDelta))
                {
                    delta       = objective.Add(problem, delta, localDelta);
                    bestFitness = objective.Subtract(problem, bestFitness, localDelta);
                    success     = true;
                }
                else if (_stopAtFail)
                { // stop at first fail.
                    break;
                }
            }
            return(success);
        }
コード例 #6
0
 private bool EvaluateOperator(object left, object right, IOperator op)
 {
     var leftResult = _compileResultFactory.Create(left);
     var rightResult = _compileResultFactory.Create(right);
     var result = op.Apply(leftResult, rightResult);
     if (result.DataType != DataType.Boolean)
     {
         throw new ArgumentException("Illegal operator in expression");
     }
     return (bool)result.Result;
 }
コード例 #7
0
        /// <summary>
        /// Solves the given problem.
        /// </summary>
        /// <returns></returns>
        public override TSolution Solve(TProblem problem, TObjective objective, out TFitness fitness)
        {
            var zero = objective.Zero;

            _log.Log(Logging.TraceEventType.Information, "Started generating initial solution...");

            TFitness globalBestFitness;
            var      globalBest = _generator.Solve(problem, objective, out globalBestFitness);

            _log.Log(Logging.TraceEventType.Information, "Initial solution generated: {0}.", globalBestFitness);

            // report new solution.
            this.ReportIntermidiateResult(globalBest);

            var difference = objective.Zero;

            if (_localSearch.Apply(problem, objective, globalBest, out difference))
            { // localsearch leads to better solution, adjust the fitness.
                globalBestFitness = objective.Subtract(problem, globalBestFitness, difference);

                _log.Log(Logging.TraceEventType.Information, "Improvement found by local search: {0}.", globalBestFitness);

                // report new solution.
                this.ReportIntermidiateResult(globalBest);
            }

            var i     = 0;
            var level = 1;

            while (!this.IsStopped &&
                   (_stopCondition == null || !_stopCondition.Invoke(i, level, problem, objective, globalBest)))
            { // keep running until stop condition is true or this solver is stopped.
                // shake things up a bit, or in other word change neighbourhood.
                var perturbedSolution   = (TSolution)globalBest.Clone();
                var perturbedDifference = objective.Zero;
                _perturber.Apply(problem, objective, perturbedSolution, level, out perturbedDifference);

                // improve things by using a local search procedure.
                var localSearchDifference = objective.Zero;
                _localSearch.ApplyUntil(problem, objective, perturbedSolution, out localSearchDifference);

                // calculate new fitness and compare.
                TFitness newFitness = default(TFitness);
                if (!objective.IsNonContinuous)
                { // solution fitness can be updated by adding the differences.
                    newFitness = objective.Add(problem, globalBestFitness, perturbedDifference);
                    newFitness = objective.Add(problem, newFitness, localSearchDifference);
                }
                else
                { // solution fitness needs to updated every time.
                    newFitness = objective.Calculate(problem, perturbedSolution);
                }

                if (objective.IsBetterThan(problem, newFitness, globalBestFitness))
                { // there was an improvement, keep new solution as global.
                    globalBestFitness = newFitness;
                    globalBest        = perturbedSolution;
                    level             = 1; // reset level.

                    _log.Log(Logging.TraceEventType.Information, "Improvement found by perturber and local search: {0}.", globalBestFitness);

                    // report new solution.
                    this.ReportIntermidiateResult(globalBest);
                }
                else
                {
                    level = level + 1;
                }
            }

            _log.Log(Logging.TraceEventType.Information, "Stop condition reached, best: {0}.", globalBestFitness);

            fitness = globalBestFitness;
            return(globalBest);
        }
コード例 #8
0
 private void ApplyOperator3(Node expr)
 {
     mExpression3 = mOperator3.Apply(mExpression3, expr);
     mOperator3   = null;
 }
コード例 #9
0
 private void ApplyOperator2(Node expr)
 {
     mExpression2 = mOperator2.Apply(mExpression2, expr);
     mOperator2   = null;
     mExpression3 = null;
 }
コード例 #10
0
 private void ApplyOperator1(Node expr)
 {
     mExpression1 = mOperator1.Apply(mExpression1, expr);
     mOperator1   = null;
     mExpression2 = null;
 }
コード例 #11
0
        /// <summary>
        /// Builds the relaxed planning graph and computes the FF heuristic value.
        /// </summary>
        /// <param name="state">Starting state.</param>
        /// <param name="goalConditions">Goal conditions.</param>
        /// <returns>FF cost heuristic value from the specified state.</returns>
        private double ComputeFFCost(IState state, IConditions goalConditions)
        {
            // build an explicit relaxed planning graph

            StateLayers.Clear();
            ActionLayers.Clear();
            StateLayers.Add(CreateFFStateLayer(state.GetRelaxedState()));

            while (true)
            {
                // check goal conditions

                IStateLayer stateLayer = StateLayers[StateLayers.Count - 1];

                if (goalConditions.Evaluate(stateLayer.GetState()))
                {
                    ActionLayers.Add(new ActionLayer {
                        CreateFFGoalActionNode(goalConditions, stateLayer.GetState())
                    });
                    break;
                }

                // build new action layer and the next state layer

                ActionLayer actionLayer = new ActionLayer();
                IState      newState    = stateLayer.GetState().Clone();

                foreach (var successor in RelaxedProblem.GetSuccessors(stateLayer.GetState()))
                {
                    IOperator appliedOperator = successor.GetAppliedOperator();

                    actionLayer.Add(CreateFFActionNode(appliedOperator, stateLayer.GetState()));

                    newState = appliedOperator.Apply(newState, true);
                }

                ActionLayers.Add(actionLayer);
                StateLayers.Add(CreateFFStateLayer(newState));
            }

            // compute FF value

            UnsatisfiedOnCurrentLayer.Clear();
            UnsatisfiedOnNextLayer.Clear();
            MarkedActionNodes.Clear();

            var goalNode = ActionLayers[ActionLayers.Count - 1][0];

            foreach (var proposition in goalNode.Predecessors)
            {
                UnsatisfiedOnCurrentLayer.Push(proposition);
            }

            for (int i = StateLayers.Count - 1; i > 0; --i)
            {
                IStateLayer nextStateLayer     = StateLayers[i - 1];
                ActionLayer currentActionLayer = ActionLayers[i - 1];

                while (UnsatisfiedOnCurrentLayer.Count != 0)
                {
                    IProposition proposition = UnsatisfiedOnCurrentLayer.Pop();

                    // 1.) try to satisfy the proposition by an idle arc to the next state layer

                    if (nextStateLayer.HasProposition(proposition))
                    {
                        UnsatisfiedOnNextLayer.Push(proposition);
                        continue;
                    }

                    // 2.) try to satisfy the proposition by a support action node

                    ActionNode relevantActionNode = GetBestRelevantActionNodeFF(proposition, currentActionLayer);
                    if (relevantActionNode != null)
                    {
                        MarkedActionNodes.Add(relevantActionNode.Operator);
                        foreach (var prevProposition in relevantActionNode.Predecessors)
                        {
                            UnsatisfiedOnNextLayer.Push(prevProposition);
                        }
                    }
                }

                UnsatisfiedSwapper        = UnsatisfiedOnNextLayer;
                UnsatisfiedOnNextLayer    = UnsatisfiedOnCurrentLayer;
                UnsatisfiedOnCurrentLayer = UnsatisfiedSwapper;
                UnsatisfiedOnNextLayer.Clear();
            }

            // the result value is a sum of costs of marked action nodes

            double result = 0;

            foreach (var markedActionNode in MarkedActionNodes)
            {
                result += markedActionNode.GetCost();
            }
            return(result);
        }
コード例 #12
0
 private void ApplyOperator2(Expression expr)
 {
     _expression2 = _operator2.Apply(_expression2, expr);
     _operator2   = null;
     _expression3 = null;
 }
コード例 #13
0
 private void ApplyOperator1(Expression expr)
 {
     _expression1 = _operator1.Apply(_expression1, expr);
     _operator1   = null;
     _expression2 = null;
 }
コード例 #14
0
 public void Visit(IOperator visitee)
 {
     visitee.Apply();
     Console.WriteLine(visitee.GetValue());
     value = int.Parse(visitee.GetValue());
 }
コード例 #15
0
ファイル: Expr.cs プロジェクト: sujit1779/writeasync
 public static BasicExpression Apply(IOperator op, BasicExpression x, BasicExpression y)
 {
     return(op.Apply(x, y));
 }
コード例 #16
0
        /// <summary>
        /// Solves the given problem.
        /// </summary>
        /// <returns></returns>
        public override TSolution Solve(TProblem problem, TObjective objective, out TFitness fitness)
        {
            var population = new Individual <TSolution, TFitness> [_settings.PopulationSize];

            // generate initial population.
            var solutionCount = 0;

            while (solutionCount < _settings.PopulationSize)
            {
                TFitness localFitness;
                var      solution = _generator.Solve(problem, objective, out localFitness);
                population[solutionCount] = new Individual <TSolution, TFitness>()
                {
                    Fitness  = localFitness,
                    Solution = solution
                };
                solutionCount++;
            }

            // sort population.
            Array.Sort(population, (x, y) =>
            {
                return(objective.CompareTo(problem, x.Fitness, y.Fitness));
            });
            var bestIndividual = population[0];

            this.ReportIntermidiateResult(bestIndividual.Solution);

            // mutate/crossover population.
            var stagnation           = 0;
            var generation           = 0;
            var elitism              = (int)(_settings.PopulationSize * (_settings.ElitismPercentage / 100.0));
            var crossOver            = (int)(_settings.PopulationSize * (_settings.CrossOverPercentage / 100.0));
            var crossOverIndividuals = new Individual <TSolution, TFitness> [crossOver];
            var exclude              = new HashSet <int>();

            while (stagnation < _settings.StagnationCount &&
                   generation < _settings.MaxGenerations &&
                   !this.IsStopped)
            {
                // select individuals for crossover.
                exclude.Clear();
                for (int i = 0; i < crossOver; i++)
                {
                    // select individual.
                    var selected = -1;
                    while (selected < 0)
                    {
                        selected = _selection.Select(problem, objective, population, exclude);
                    }
                    crossOverIndividuals[i] = population[selected];
                    exclude.Add(selected);
                }

                // replace part of the population by offspring.
                for (int i = elitism; i < population.Length; i++)
                {
                    // take two random parents.
                    var individual1 = _random.Next(crossOver);
                    var individual2 = _random.Next(crossOver - 1);
                    if (individual1 <= individual2)
                    { // make sure they are different.
                        individual2++;
                    }

                    // create offspring.
                    TFitness offspringFitness;
                    var      offspring = _crossOver.Apply(problem, objective, population[individual1].Solution,
                                                          population[individual2].Solution, out offspringFitness);
                    population[i] = new Individual <TSolution, TFitness>()
                    {
                        Solution = offspring,
                        Fitness  = offspringFitness
                    };
                }

                // mutate part of the population.
                for (int i = elitism; i < population.Length; i++)
                {
                    if (_random.Next(100) <= _settings.MutationPercentage)
                    { // ok, mutate this individual.
                        TFitness mutatedDelta;
                        if (_mutation.Apply(problem, objective, population[i].Solution, out mutatedDelta))
                        { // mutation succeeded.
                            population[i].Fitness = objective.Subtract(problem, population[i].Fitness, mutatedDelta);
                        }
                    }
                }

                // sort new population.
                Array.Sort(population, (x, y) =>
                {
                    return(objective.CompareTo(problem, x.Fitness, y.Fitness));
                });
                if (objective.IsBetterThan(problem, bestIndividual.Fitness, population[0].Fitness))
                {                       // a better individual was found.
                    bestIndividual = population[0];
                    stagnation     = 0; // reset stagnation flag.
                    this.ReportIntermidiateResult(bestIndividual.Solution);
                }
                else
                { // no better solution found.
                    stagnation++;
                }
            }

            fitness = bestIndividual.Fitness;
            return(bestIndividual.Solution);
        }
コード例 #17
0
ファイル: IPerturber.cs プロジェクト: tikyau/optimization
 /// <summary>
 /// Returns true if there was an improvement, false otherwise.
 /// </summary>
 /// <param name="problem">The problem.</param>
 /// <param name="objective">The objective.</param>
 /// <param name="solution">The solution.</param>
 /// <param name="delta">The difference in fitness, when > 0 there was an improvement and a reduction in fitness.</param>
 /// <returns></returns>
 public bool Apply(TProblem problem, TObjective objective, TSolution solution, out TFitness delta)
 {
     return(_operator.Apply(problem, objective, solution, out delta));
 }
コード例 #18
0
 private void ApplyOperator3(Expression expr)
 {
     _expression3 = _operator3.Apply(_expression3, expr);
     _operator3   = null;
 }