Exemple #1
0
        public static void RunTest(SemgrexPattern pattern, SemanticGraph graph, params string[] expectedMatches)
        {
            // results are not in the order I would expect.  Using a counter
            // allows them to be in any order
            IntCounter <string> counts = new IntCounter <string>();

            for (int i = 0; i < expectedMatches.Length; ++i)
            {
                counts.IncrementCount(expectedMatches[i]);
            }
            IntCounter <string> originalCounts = new IntCounter <string>(counts);
            SemgrexMatcher      matcher        = pattern.Matcher(graph);

            for (int i_1 = 0; i_1 < expectedMatches.Length; ++i_1)
            {
                if (!matcher.Find())
                {
                    throw new AssertionFailedError("Expected " + expectedMatches.Length + " matches for pattern " + pattern + " on " + graph + ", only got " + i_1);
                }
                string match = matcher.GetMatch().ToString();
                if (!counts.ContainsKey(match))
                {
                    throw new AssertionFailedError("Unexpected match " + match + " for pattern " + pattern + " on " + graph);
                }
                counts.DecrementCount(match);
                if (counts.GetCount(match) < 0)
                {
                    throw new AssertionFailedError("Found too many matches for " + match + " for pattern " + pattern + " on " + graph);
                }
            }
            if (matcher.FindNextMatchingNode())
            {
                throw new AssertionFailedError("Found more than " + expectedMatches.Length + " matches for pattern " + pattern + " on " + graph + "... extra match is " + matcher.GetMatch());
            }
        }
            public override object Aggregate <_T0>(Type key, IList <_T0> @in)
            {
                if (@in == null)
                {
                    return(null);
                }
                IntCounter <object> counter = new IntCounter <object>();

                foreach (ICoreMap cm in @in)
                {
                    object obj = cm.Get(key);
                    if (obj != null && (ignoreSet == null || !ignoreSet.Contains(obj)))
                    {
                        counter.IncrementCount(obj);
                    }
                }
                if (counter.Size() > 0)
                {
                    return(counter.Argmax());
                }
                else
                {
                    return(null);
                }
            }
Exemple #3
0
        public double[] ChangeConstantsToLeaf()
        {
            _leafCounter = (-1).ToIntCounter();
            _dicOfLeafs  = new Dictionary <int, string>();
            RecurceChangeToLeaf(MathTree[0].Child);
            var outCons = _dicOfLeafs.Select(dbl => dbl.Value.ToDbl()).ToArray();

            return(outCons);
        }
Exemple #4
0
 public RecordChange(MutableLongObjectMap <RecordAccess_RecordProxy <RECORD, ADDITIONAL> > allChanges, IntCounter changeCounter, long key, RECORD record, RecordAccess_Loader <RECORD, ADDITIONAL> loader, bool created, ADDITIONAL additionalData)
 {
     this.AllChanges             = allChanges;
     this.ChangeCounter          = changeCounter;
     this.KeyConflict            = key;
     this.Record                 = record;
     this.Loader                 = loader;
     this.CreatedConflict        = created;
     this.AdditionalDataConflict = additionalData;
 }
 public ChineseWordFeatureExtractor(int featureLevel)
 {
     /*
      * public ChineseWordFeatureExtractor() {
      * this(trees, 2);
      * }
      */
     wordCounter = new IntCounter();
     SetFeatureLevel(featureLevel);
 }
Exemple #6
0
 // only used at training time
 public virtual void InitializeTraining(double numTrees)
 {
     Verbose("Training ChineseMaxentLexicon.");
     Verbose("trainOnLowCount = " + trainOnLowCount + ", trainByType = " + trainByType + ", featureLevel = " + featureLevel + ", tuneSigma = " + tuneSigma);
     Verbose("Making dataset...");
     if (featExtractor == null)
     {
         featExtractor = new ChineseWordFeatureExtractor(featureLevel);
     }
     this.datumCounter = new IntCounter <TaggedWord>();
 }
Exemple #7
0
 internal TagCount(IntCounter <string> tagCounts)
 {
     /* This is a numeric ID shared by all words that have the same set of possible tags. */
     // = null;
     // used internally
     foreach (string tag in tagCounts.KeySet())
     {
         map[tag] = tagCounts.GetIntCount(tag);
     }
     getTagsCache = Sharpen.Collections.ToArray(map.Keys, new string[map.Keys.Count]);
     sumCache     = CalculateSumCache();
 }
        public virtual void ApplyFeatureCountThreshold(ICollection <string> data, int thresh)
        {
            IntCounter c = new IntCounter();

            foreach (string datum in data)
            {
                foreach (string feat in MakeFeatures(datum))
                {
                    c.IncrementCount(feat);
                }
            }
            threshedFeatures = c.KeysAbove(thresh);
            log.Info((c.Size() - threshedFeatures.Count) + " word features removed due to thresholding.");
        }
Exemple #9
0
        // return strings sorted by frequency, and filter out those with freq. less than cutOff.
        /// <summary>Build a dictionary of words collected from a corpus.</summary>
        /// <remarks>
        /// Build a dictionary of words collected from a corpus.
        /// <p>
        /// Filters out words with a frequency below the given
        /// <paramref name="cutOff"/>
        /// .
        /// </remarks>
        /// <returns>
        /// Words sorted by decreasing frequency, filtered to remove
        /// any words with a frequency below
        /// <paramref name="cutOff"/>
        /// </returns>
        public static IList <string> GenerateDict(IList <string> str, int cutOff)
        {
            ICounter <string> freq = new IntCounter <string>();

            foreach (string aStr in str)
            {
                freq.IncrementCount(aStr);
            }
            IList <string> keys = Counters.ToSortedList(freq, false);
            IList <string> dict = new List <string>();

            foreach (string word in keys)
            {
                if (freq.GetCount(word) >= cutOff)
                {
                    dict.Add(word);
                }
            }
            return(dict);
        }
 public virtual void Reset()
 {
     labelsCorrect         = 0;
     labelsIncorrect       = 0;
     labelConfusion        = new int[op.numClasses][];
     rootLabelsCorrect     = 0;
     rootLabelsIncorrect   = 0;
     rootLabelConfusion    = new int[op.numClasses][];
     lengthLabelsCorrect   = new IntCounter <int>();
     lengthLabelsIncorrect = new IntCounter <int>();
     equivalenceClasses    = op.equivalenceClasses;
     equivalenceClassNames = op.equivalenceClassNames;
     if (op.testOptions.ngramRecordSize > 0)
     {
         ngrams = new TopNGramRecord(op.numClasses, op.testOptions.ngramRecordSize, op.testOptions.ngramRecordMaximumLength);
     }
     else
     {
         ngrams = null;
     }
 }
Exemple #11
0
        public virtual void FinishTraining()
        {
            IntCounter <string> tagCounter = new IntCounter <string>();
            WeightedDataset     data       = new WeightedDataset(datumCounter.Size());

            foreach (TaggedWord word in datumCounter.KeySet())
            {
                int count = datumCounter.GetIntCount(word);
                if (trainOnLowCount && count > trainCountThreshold)
                {
                    continue;
                }
                if (functionWordTags.Contains(word.Word()))
                {
                    continue;
                }
                tagCounter.IncrementCount(word.Tag());
                if (trainByType)
                {
                    count = 1;
                }
                data.Add(new BasicDatum(featExtractor.MakeFeatures(word.Word()), word.Tag()), count);
            }
            datumCounter = null;
            tagDist      = Distribution.LaplaceSmoothedDistribution(tagCounter, tagCounter.Size(), 0.5);
            tagCounter   = null;
            ApplyThresholds(data);
            Verbose("Making classifier...");
            QNMinimizer minim = new QNMinimizer();
            //new ResultStoringMonitor(5, "weights"));
            //    minim.shutUp();
            LinearClassifierFactory factory = new LinearClassifierFactory(minim);

            factory.SetTol(tol);
            factory.SetSigma(sigma);
            scorer = factory.TrainClassifier(data);
            Verbose("Done training.");
        }
Exemple #12
0
        private void Initialize()
        {
            #region Create parameters
            Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
            Parameters.Add(new LookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution."));
            Parameters.Add(new LookupParameter <DoubleValue>("BestLocalQuality", "The value which represents the best quality found so far."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The problem's best known quality value found so far."));
            Parameters.Add(new LookupParameter <DoubleValue>("MoveQuality", "The value which represents the quality of a move."));
            Parameters.Add(new LookupParameter <IntValue>("Iterations", "The number of iterations performed."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumIterations", "The maximum number of generations which should be processed."));
            Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored."));

            Parameters.Add(new ValueLookupParameter <IOperator>("MoveGenerator", "The operator that generates the moves."));
            Parameters.Add(new ValueLookupParameter <IOperator>("MoveMaker", "The operator that performs a move and updates the quality."));
            Parameters.Add(new ValueLookupParameter <IOperator>("MoveEvaluator", "The operator that evaluates a move."));

            Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze the solution and moves."));
            Parameters.Add(new LookupParameter <IntValue>("EvaluatedMoves", "The number of evaluated moves."));
            #endregion

            #region Create operators
            SubScopesProcessor        subScopesProcessor0    = new SubScopesProcessor();
            Assigner                  bestQualityInitializer = new Assigner();
            Placeholder               analyzer1                   = new Placeholder();
            ResultsCollector          resultsCollector1           = new ResultsCollector();
            SubScopesProcessor        mainProcessor               = new SubScopesProcessor();
            Placeholder               moveGenerator               = new Placeholder();
            UniformSubScopesProcessor moveEvaluationProcessor     = new UniformSubScopesProcessor();
            Placeholder               moveEvaluator               = new Placeholder();
            SubScopesCounter          subScopesCounter            = new SubScopesCounter();
            BestSelector              bestSelector                = new BestSelector();
            SubScopesProcessor        moveMakingProcessor         = new SubScopesProcessor();
            UniformSubScopesProcessor selectedMoveMakingProcessor = new UniformSubScopesProcessor();
            QualityComparator         qualityComparator           = new QualityComparator();
            ConditionalBranch         improvesQualityBranch       = new ConditionalBranch();
            Placeholder               moveMaker                   = new Placeholder();
            Assigner                  bestQualityUpdater          = new Assigner();
            ResultsCollector          resultsCollector2           = new ResultsCollector();
            MergingReducer            mergingReducer              = new MergingReducer();
            Placeholder               analyzer2                   = new Placeholder();
            SubScopesRemover          subScopesRemover            = new SubScopesRemover();
            IntCounter                iterationsCounter           = new IntCounter();
            Comparator                iterationsComparator        = new Comparator();
            ConditionalBranch         iterationsTermination       = new ConditionalBranch();

            bestQualityInitializer.Name = "Initialize BestQuality";
            bestQualityInitializer.LeftSideParameter.ActualName  = BestLocalQualityParameter.Name;
            bestQualityInitializer.RightSideParameter.ActualName = QualityParameter.Name;

            analyzer1.Name = "Analyzer (placeholder)";
            analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name;

            resultsCollector1.CopyValue = new BoolValue(false);
            resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>(IterationsParameter.Name));
            resultsCollector1.CollectedValues.Add(new LookupParameter <DoubleValue>(BestLocalQualityParameter.Name, null, BestLocalQualityParameter.Name));
            resultsCollector1.ResultsParameter.ActualName = ResultsParameter.Name;

            moveGenerator.Name = "MoveGenerator (placeholder)";
            moveGenerator.OperatorParameter.ActualName = MoveGeneratorParameter.Name;

            moveEvaluationProcessor.Parallel = new BoolValue(true);

            moveEvaluator.Name = "MoveEvaluator (placeholder)";
            moveEvaluator.OperatorParameter.ActualName = MoveEvaluatorParameter.Name;

            subScopesCounter.Name = "Increment EvaluatedMoves";
            subScopesCounter.ValueParameter.ActualName = EvaluatedMovesParameter.Name;

            bestSelector.CopySelected = new BoolValue(false);
            bestSelector.MaximizationParameter.ActualName         = MaximizationParameter.Name;
            bestSelector.NumberOfSelectedSubScopesParameter.Value = new IntValue(1);
            bestSelector.QualityParameter.ActualName = MoveQualityParameter.Name;

            qualityComparator.LeftSideParameter.ActualName  = MoveQualityParameter.Name;
            qualityComparator.RightSideParameter.ActualName = QualityParameter.Name;
            qualityComparator.ResultParameter.ActualName    = "IsBetter";

            improvesQualityBranch.ConditionParameter.ActualName = "IsBetter";

            moveMaker.Name = "MoveMaker (placeholder)";
            moveMaker.OperatorParameter.ActualName = MoveMakerParameter.Name;

            bestQualityUpdater.Name = "Update BestQuality";
            bestQualityUpdater.LeftSideParameter.ActualName  = BestLocalQualityParameter.Name;
            bestQualityUpdater.RightSideParameter.ActualName = QualityParameter.Name;

            resultsCollector2.CopyValue = new BoolValue(false);
            resultsCollector2.CollectedValues.Add(new LookupParameter <DoubleValue>(BestLocalQualityParameter.Name, null, BestLocalQualityParameter.Name));
            resultsCollector2.ResultsParameter.ActualName = ResultsParameter.Name;

            analyzer2.Name = "Analyzer (placeholder)";
            analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name;

            subScopesRemover.RemoveAllSubScopes = true;

            iterationsCounter.Name      = "Iterations Counter";
            iterationsCounter.Increment = new IntValue(1);
            iterationsCounter.ValueParameter.ActualName = IterationsParameter.Name;

            iterationsComparator.Name       = "Iterations >= MaximumIterations";
            iterationsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            iterationsComparator.LeftSideParameter.ActualName  = IterationsParameter.Name;
            iterationsComparator.RightSideParameter.ActualName = MaximumIterationsParameter.Name;
            iterationsComparator.ResultParameter.ActualName    = "Terminate";

            iterationsTermination.Name = "Iterations Termination Condition";
            iterationsTermination.ConditionParameter.ActualName = "Terminate";
            #endregion

            #region Create operator graph
            OperatorGraph.InitialOperator = subScopesProcessor0; // don't change this without adapting the constructor of LocalSearchImprovementOperator
            subScopesProcessor0.Operators.Add(bestQualityInitializer);
            subScopesProcessor0.Successor    = resultsCollector1;
            bestQualityInitializer.Successor = analyzer1;
            analyzer1.Successor         = null;
            resultsCollector1.Successor = mainProcessor;
            mainProcessor.Operators.Add(moveGenerator);
            mainProcessor.Successor           = iterationsCounter;
            moveGenerator.Successor           = moveEvaluationProcessor;
            moveEvaluationProcessor.Operator  = moveEvaluator;
            moveEvaluationProcessor.Successor = subScopesCounter;
            moveEvaluator.Successor           = null;
            subScopesCounter.Successor        = bestSelector;
            bestSelector.Successor            = moveMakingProcessor;
            moveMakingProcessor.Operators.Add(new EmptyOperator());
            moveMakingProcessor.Operators.Add(selectedMoveMakingProcessor);
            moveMakingProcessor.Successor        = mergingReducer;
            selectedMoveMakingProcessor.Operator = qualityComparator;
            qualityComparator.Successor          = improvesQualityBranch;
            improvesQualityBranch.TrueBranch     = moveMaker;
            improvesQualityBranch.FalseBranch    = null;
            improvesQualityBranch.Successor      = null;
            moveMaker.Successor               = bestQualityUpdater;
            bestQualityUpdater.Successor      = null;
            mergingReducer.Successor          = analyzer2;
            analyzer2.Successor               = subScopesRemover;
            subScopesRemover.Successor        = null;
            iterationsCounter.Successor       = iterationsComparator;
            iterationsComparator.Successor    = iterationsTermination;
            iterationsTermination.TrueBranch  = null;
            iterationsTermination.FalseBranch = mainProcessor;
            #endregion
        }
        private void Initialize()
        {
            #region Create parameters
            Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
            Parameters.Add(new LookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Evaluator", "The operator used to evaluate solutions. This operator is executed in parallel, if an engine is used which supports parallelization."));
            Parameters.Add(new LookupParameter <IntValue>("Iterations", "The iterations to count."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumIterations", "The maximum number of generations which should be processed."));
            Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze the solution."));
            Parameters.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "The number of evaluated solutions."));
            Parameters.Add(new ValueLookupParameter <ILocalImprovementOperator>("LocalImprovement", "The local improvement operation."));
            Parameters.Add(new ValueLookupParameter <IMultiNeighborhoodShakingOperator>("ShakingOperator", "The shaking operation."));
            Parameters.Add(new LookupParameter <IntValue>("CurrentNeighborhoodIndex", "The index of the current shaking operation that should be applied."));
            Parameters.Add(new LookupParameter <IntValue>("NeighborhoodCount", "The number of neighborhood operators used for shaking."));
            #endregion

            #region Create operators
            VariableCreator    variableCreator        = new VariableCreator();
            SubScopesProcessor subScopesProcessor0    = new SubScopesProcessor();
            Assigner           bestQualityInitializer = new Assigner();
            Placeholder        analyzer1         = new Placeholder();
            ResultsCollector   resultsCollector1 = new ResultsCollector();

            CombinedOperator iteration     = new CombinedOperator();
            Assigner         iterationInit = new Assigner();

            SubScopesCloner    createChild    = new SubScopesCloner();
            SubScopesProcessor childProcessor = new SubScopesProcessor();

            Assigner    qualityAssigner  = new Assigner();
            Placeholder shaking          = new Placeholder();
            Placeholder localImprovement = new Placeholder();
            Placeholder evaluator        = new Placeholder();
            IntCounter  evalCounter      = new IntCounter();

            QualityComparator qualityComparator     = new QualityComparator();
            ConditionalBranch improvesQualityBranch = new ConditionalBranch();

            Assigner bestQualityUpdater = new Assigner();

            BestSelector bestSelector = new BestSelector();
            RightReducer rightReducer = new RightReducer();

            IntCounter indexCounter  = new IntCounter();
            Assigner   indexResetter = new Assigner();

            Placeholder analyzer2 = new Placeholder();

            Comparator        indexComparator  = new Comparator();
            ConditionalBranch indexTermination = new ConditionalBranch();

            IntCounter        iterationsCounter     = new IntCounter();
            Comparator        iterationsComparator  = new Comparator();
            ConditionalBranch iterationsTermination = new ConditionalBranch();

            variableCreator.CollectedValues.Add(new ValueParameter <BoolValue>("IsBetter", new BoolValue(false)));
            variableCreator.CollectedValues.Add(new ValueParameter <DoubleValue>("BestQuality", new DoubleValue(0)));

            bestQualityInitializer.Name = "Initialize BestQuality";
            bestQualityInitializer.LeftSideParameter.ActualName  = "BestQuality";
            bestQualityInitializer.RightSideParameter.ActualName = QualityParameter.Name;

            analyzer1.Name = "Analyzer (placeholder)";
            analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name;

            resultsCollector1.CopyValue = new BoolValue(false);
            resultsCollector1.CollectedValues.Add(new LookupParameter <DoubleValue>("Best Quality", null, "BestQuality"));
            resultsCollector1.ResultsParameter.ActualName = ResultsParameter.Name;

            iteration.Name = "MainLoop Body";

            iterationInit.Name = "Init k = 0";
            iterationInit.LeftSideParameter.ActualName = CurrentNeighborhoodIndexParameter.Name;
            iterationInit.RightSideParameter.Value     = new IntValue(0);

            createChild.Name = "Clone solution";

            qualityAssigner.Name = "Assign quality";
            qualityAssigner.LeftSideParameter.ActualName  = "OriginalQuality";
            qualityAssigner.RightSideParameter.ActualName = QualityParameter.Name;

            shaking.Name = "Shaking operator (placeholder)";
            shaking.OperatorParameter.ActualName = ShakingOperatorParameter.Name;

            localImprovement.Name = "Local improvement operator (placeholder)";
            localImprovement.OperatorParameter.ActualName = LocalImprovementParameter.Name;

            evaluator.Name = "Evaluation operator (placeholder)";
            evaluator.OperatorParameter.ActualName = EvaluatorParameter.Name;

            evalCounter.Name                      = "Count evaluations";
            evalCounter.Increment.Value           = 1;
            evalCounter.ValueParameter.ActualName = EvaluatedSolutionsParameter.ActualName;

            qualityComparator.LeftSideParameter.ActualName  = QualityParameter.Name;
            qualityComparator.RightSideParameter.ActualName = "OriginalQuality";
            qualityComparator.ResultParameter.ActualName    = "IsBetter";

            improvesQualityBranch.ConditionParameter.ActualName = "IsBetter";

            bestQualityUpdater.Name = "Update BestQuality";
            bestQualityUpdater.LeftSideParameter.ActualName  = "BestQuality";
            bestQualityUpdater.RightSideParameter.ActualName = QualityParameter.Name;

            bestSelector.CopySelected = new BoolValue(false);
            bestSelector.MaximizationParameter.ActualName         = MaximizationParameter.Name;
            bestSelector.NumberOfSelectedSubScopesParameter.Value = new IntValue(1);
            bestSelector.QualityParameter.ActualName = QualityParameter.Name;

            indexCounter.Name                      = "Count neighborhood index";
            indexCounter.Increment.Value           = 1;
            indexCounter.ValueParameter.ActualName = CurrentNeighborhoodIndexParameter.Name;

            indexResetter.Name = "Reset neighborhood index";
            indexResetter.LeftSideParameter.ActualName = CurrentNeighborhoodIndexParameter.Name;
            indexResetter.RightSideParameter.Value     = new IntValue(0);

            analyzer2.Name = "Analyzer (placeholder)";
            analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name;

            iterationsCounter.Name      = "Iterations Counter";
            iterationsCounter.Increment = new IntValue(1);
            iterationsCounter.ValueParameter.ActualName = IterationsParameter.Name;

            iterationsComparator.Name       = "Iterations >= MaximumIterations";
            iterationsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            iterationsComparator.LeftSideParameter.ActualName  = IterationsParameter.Name;
            iterationsComparator.RightSideParameter.ActualName = MaximumIterationsParameter.Name;
            iterationsComparator.ResultParameter.ActualName    = "Terminate";

            iterationsTermination.Name = "Iterations Termination Condition";
            iterationsTermination.ConditionParameter.ActualName = "Terminate";

            indexComparator.Name = "k < k_max (index condition)";
            indexComparator.LeftSideParameter.ActualName  = CurrentNeighborhoodIndexParameter.Name;
            indexComparator.RightSideParameter.ActualName = NeighborhoodCountParameter.Name;
            indexComparator.Comparison = new Comparison(ComparisonType.Less);
            indexComparator.ResultParameter.ActualName = "ContinueIteration";

            indexTermination.Name = "Index Termination Condition";
            indexTermination.ConditionParameter.ActualName = "ContinueIteration";
            #endregion

            #region Create operator graph
            OperatorGraph.InitialOperator = variableCreator;
            variableCreator.Successor     = subScopesProcessor0;
            subScopesProcessor0.Operators.Add(bestQualityInitializer);
            subScopesProcessor0.Successor = analyzer1;
            analyzer1.Successor           = resultsCollector1;
            /////////
            resultsCollector1.Successor = iteration;

            iteration.OperatorGraph.InitialOperator = iterationInit;
            iteration.Successor     = iterationsCounter;
            iterationInit.Successor = createChild;

            createChild.Successor = childProcessor;
            childProcessor.Operators.Add(new EmptyOperator());
            childProcessor.Operators.Add(qualityAssigner);
            childProcessor.Successor = bestSelector;
            /////////
            qualityAssigner.Successor         = shaking;
            shaking.Successor                 = evaluator;
            evaluator.Successor               = evalCounter;
            evalCounter.Successor             = localImprovement;
            localImprovement.Successor        = qualityComparator;
            qualityComparator.Successor       = improvesQualityBranch;
            improvesQualityBranch.TrueBranch  = bestQualityUpdater;
            improvesQualityBranch.FalseBranch = indexCounter;

            bestQualityUpdater.Successor = indexResetter;
            indexResetter.Successor      = null;

            indexCounter.Successor = null;
            /////////
            bestSelector.Successor       = rightReducer;
            rightReducer.Successor       = analyzer2;
            analyzer2.Successor          = indexComparator;
            indexComparator.Successor    = indexTermination;
            indexTermination.TrueBranch  = createChild;
            indexTermination.FalseBranch = null;

            iterationsCounter.Successor       = iterationsComparator;
            iterationsComparator.Successor    = iterationsTermination;
            iterationsTermination.TrueBranch  = null;
            iterationsTermination.FalseBranch = iteration;
            #endregion
        }
Exemple #14
0
        private void Initialize()
        {
            #region Create parameters
            Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
            Parameters.Add(new LookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far."));
            Parameters.Add(new LookupParameter <DoubleValue>("MoveQuality", "The value which represents the quality of a move."));
            Parameters.Add(new LookupParameter <BoolValue>("MoveTabu", "The value that indicates if a move is tabu or not."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumIterations", "The maximum number of generations which should be processed."));
            Parameters.Add(new ValueLookupParameter <IntValue>("TabuTenure", "The length of the tabu list, and also means the number of iterations a move is kept tabu"));

            Parameters.Add(new ValueLookupParameter <IOperator>("MoveGenerator", "The operator that generates the moves."));
            Parameters.Add(new ValueLookupParameter <IOperator>("MoveMaker", "The operator that performs a move and updates the quality."));
            Parameters.Add(new ValueLookupParameter <IOperator>("MoveEvaluator", "The operator that evaluates a move."));
            Parameters.Add(new ValueLookupParameter <IOperator>("TabuChecker", "The operator that checks whether a move is tabu."));
            Parameters.Add(new ValueLookupParameter <IOperator>("TabuMaker", "The operator that declares a move tabu."));

            Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze the solution and moves."));
            Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored."));
            Parameters.Add(new LookupParameter <IntValue>("EvaluatedMoves", "The number of evaluated moves."));
            #endregion

            #region Create operators
            VariableCreator           variableCreator        = new VariableCreator();
            SubScopesProcessor        subScopesProcessor0    = new SubScopesProcessor();
            Assigner                  bestQualityInitializer = new Assigner();
            Placeholder               analyzer1                  = new Placeholder();
            ResultsCollector          resultsCollector1          = new ResultsCollector();
            SubScopesProcessor        solutionProcessor          = new SubScopesProcessor();
            Placeholder               moveGenerator              = new Placeholder();
            UniformSubScopesProcessor moveEvaluationProcessor    = new UniformSubScopesProcessor();
            Placeholder               moveEvaluator              = new Placeholder();
            Placeholder               tabuChecker                = new Placeholder();
            SubScopesCounter          subScopesCounter           = new SubScopesCounter();
            SubScopesSorter           moveQualitySorter          = new SubScopesSorter();
            TabuSelector              tabuSelector               = new TabuSelector();
            ConditionalBranch         emptyNeighborhoodBranch1   = new ConditionalBranch();
            SubScopesProcessor        moveMakingProcessor        = new SubScopesProcessor();
            UniformSubScopesProcessor selectedMoveMakingProcesor = new UniformSubScopesProcessor();
            Placeholder               tabuMaker                  = new Placeholder();
            Placeholder               moveMaker                  = new Placeholder();
            MergingReducer            mergingReducer             = new MergingReducer();
            Placeholder               analyzer2                  = new Placeholder();
            SubScopesRemover          subScopesRemover           = new SubScopesRemover();
            ConditionalBranch         emptyNeighborhoodBranch2   = new ConditionalBranch();
            BestQualityMemorizer      bestQualityUpdater         = new BestQualityMemorizer();
            IntCounter                iterationsCounter          = new IntCounter();
            Comparator                iterationsComparator       = new Comparator();
            ConditionalBranch         iterationsTermination      = new ConditionalBranch();

            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Iterations", new IntValue(0))); // Class TabuSearch expects this to be called Iterations
            variableCreator.CollectedValues.Add(new ValueParameter <BoolValue>("EmptyNeighborhood", new BoolValue(false)));
            variableCreator.CollectedValues.Add(new ValueParameter <ItemList <IItem> >("TabuList", new ItemList <IItem>()));
            variableCreator.CollectedValues.Add(new ValueParameter <VariableCollection>("Memories", new VariableCollection()));
            variableCreator.CollectedValues.Add(new ValueParameter <DoubleValue>("BestQuality", new DoubleValue(0)));

            bestQualityInitializer.Name = "Initialize BestQuality";
            bestQualityInitializer.LeftSideParameter.ActualName  = "BestQuality";
            bestQualityInitializer.RightSideParameter.ActualName = QualityParameter.Name;

            analyzer1.Name = "Analyzer (placeholder)";
            analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name;

            resultsCollector1.CopyValue = new BoolValue(false);
            resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>("Iterations"));
            resultsCollector1.CollectedValues.Add(new LookupParameter <DoubleValue>("Best Quality", null, "BestQuality"));
            resultsCollector1.ResultsParameter.ActualName = ResultsParameter.Name;

            moveGenerator.Name = "MoveGenerator (placeholder)";
            moveGenerator.OperatorParameter.ActualName = MoveGeneratorParameter.Name;

            moveEvaluationProcessor.Parallel = new BoolValue(true);

            moveEvaluator.Name = "MoveEvaluator (placeholder)";
            moveEvaluator.OperatorParameter.ActualName = MoveEvaluatorParameter.Name;

            tabuChecker.Name = "TabuChecker (placeholder)";
            tabuChecker.OperatorParameter.ActualName = TabuCheckerParameter.Name;

            subScopesCounter.Name = "Increment EvaluatedMoves";
            subScopesCounter.ValueParameter.ActualName = EvaluatedMovesParameter.Name;

            moveQualitySorter.DescendingParameter.ActualName = MaximizationParameter.Name;
            moveQualitySorter.ValueParameter.ActualName      = MoveQualityParameter.Name;

            tabuSelector.AspirationParameter.Value       = new BoolValue(true);
            tabuSelector.BestQualityParameter.ActualName = "BestQuality";
            tabuSelector.CopySelected = new BoolValue(false);
            tabuSelector.EmptyNeighborhoodParameter.ActualName = "EmptyNeighborhood";
            tabuSelector.MaximizationParameter.ActualName      = MaximizationParameter.Name;
            tabuSelector.MoveQualityParameter.ActualName       = MoveQualityParameter.Name;
            tabuSelector.MoveTabuParameter.ActualName          = MoveTabuParameter.Name;

            moveMakingProcessor.Name = "MoveMaking processor (UniformSubScopesProcessor)";

            emptyNeighborhoodBranch1.Name = "Neighborhood empty?";
            emptyNeighborhoodBranch1.ConditionParameter.ActualName = "EmptyNeighborhood";

            tabuMaker.Name = "TabuMaker (placeholder)";
            tabuMaker.OperatorParameter.ActualName = TabuMakerParameter.Name;

            moveMaker.Name = "MoveMaker (placeholder)";
            moveMaker.OperatorParameter.ActualName = MoveMakerParameter.Name;

            analyzer2.Name = "Analyzer (placeholder)";
            analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name;

            subScopesRemover.RemoveAllSubScopes = true;

            bestQualityUpdater.Name = "Update BestQuality";
            bestQualityUpdater.MaximizationParameter.ActualName = MaximizationParameter.Name;
            bestQualityUpdater.QualityParameter.ActualName      = QualityParameter.Name;
            bestQualityUpdater.BestQualityParameter.ActualName  = "BestQuality";

            iterationsCounter.Name      = "Iterations Counter";
            iterationsCounter.Increment = new IntValue(1);
            iterationsCounter.ValueParameter.ActualName = "Iterations";

            iterationsComparator.Name       = "Iterations >= MaximumIterations";
            iterationsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            iterationsComparator.LeftSideParameter.ActualName  = "Iterations";
            iterationsComparator.RightSideParameter.ActualName = MaximumIterationsParameter.Name;
            iterationsComparator.ResultParameter.ActualName    = "Terminate";

            emptyNeighborhoodBranch2.Name = "Neighborhood empty?";
            emptyNeighborhoodBranch2.ConditionParameter.ActualName = "EmptyNeighborhood";

            iterationsTermination.Name = "Iterations Termination Condition";
            iterationsTermination.ConditionParameter.ActualName = "Terminate";
            #endregion

            #region Create operator graph
            OperatorGraph.InitialOperator = variableCreator;
            variableCreator.Successor     = subScopesProcessor0;
            subScopesProcessor0.Operators.Add(bestQualityInitializer);
            subScopesProcessor0.Successor    = resultsCollector1;
            bestQualityInitializer.Successor = analyzer1;
            analyzer1.Successor         = null;
            resultsCollector1.Successor = solutionProcessor;
            solutionProcessor.Operators.Add(moveGenerator);
            solutionProcessor.Successor          = iterationsCounter;
            moveGenerator.Successor              = moveEvaluationProcessor;
            moveEvaluationProcessor.Operator     = moveEvaluator;
            moveEvaluationProcessor.Successor    = subScopesCounter;
            moveEvaluator.Successor              = tabuChecker;
            tabuChecker.Successor                = null;
            subScopesCounter.Successor           = moveQualitySorter;
            moveQualitySorter.Successor          = tabuSelector;
            tabuSelector.Successor               = emptyNeighborhoodBranch1;
            emptyNeighborhoodBranch1.FalseBranch = moveMakingProcessor;
            emptyNeighborhoodBranch1.TrueBranch  = null;
            emptyNeighborhoodBranch1.Successor   = subScopesRemover;
            moveMakingProcessor.Operators.Add(new EmptyOperator());
            moveMakingProcessor.Operators.Add(selectedMoveMakingProcesor);
            moveMakingProcessor.Successor        = mergingReducer;
            selectedMoveMakingProcesor.Operator  = tabuMaker;
            selectedMoveMakingProcesor.Successor = null;
            tabuMaker.Successor                  = moveMaker;
            moveMaker.Successor                  = null;
            mergingReducer.Successor             = analyzer2;
            analyzer2.Successor                  = null;
            subScopesRemover.Successor           = null;
            iterationsCounter.Successor          = iterationsComparator;
            iterationsComparator.Successor       = emptyNeighborhoodBranch2;
            emptyNeighborhoodBranch2.TrueBranch  = null;
            emptyNeighborhoodBranch2.FalseBranch = iterationsTermination;
            emptyNeighborhoodBranch2.Successor   = null;
            iterationsTermination.TrueBranch     = null;
            iterationsTermination.FalseBranch    = solutionProcessor;
            #endregion
        }
        public void Compile(double targetDeviation, int iterationNum)
        {
            IntCounter errCount = 0.ToIntCounter();

RestartIfErr:
            var recurseFilterIndex = 0;

            if (_convolutionMode)
            {
                RecurseFilter();
                recurseFilterIndex = _selectionConfig.MaxConstantsCount - 1;
            }
            Child[] childs = _selectionProvider.NewGenotypes();

            string switchGenotypes = childs.ToList()
                                     .Select((e, i) => "               case " + i + ": return " + e.Genotype + ";")
                                     .Aggregate(string.Empty, (all, next) => all + next + "\r\n");

            string pointsReader = _arguments.Select((arr, row) => string.Join("\r\n",
                                                                              arr.Select((d, column) => "       Arg[" + column + "," + row + "]=" + d.ToString(CultureInfo.InvariantCulture) + ";")))
                                  .Aggregate(string.Empty, (all, next) => all + next + "\r\n");

            #region code

            ClassCode = @"using System;
using System.Collections.Generic;

namespace WFA.KSAF.Generated
{
    public class Estimator
    {
       private readonly double[,] Arg = new double[" + (_arguments.Rows + 1) + ", " + _arguments.Count + @"];
       private int PointsCount;
       public List<double[]> BestLeafs = new List<double[]>();

       public Estimator()
       {
           Reader();
       }

       private static bool CompareToZero(double d) => Math.Abs(d) < Double.Epsilon;
       private static double Sin(double arg) => Math.Sin(arg);
       private static double Cos(double arg) => Math.Cos(arg);
       private static double Tan(double arg) => Math.Tan(arg);
       private static double Exp(double arg) => Math.Exp(arg);
       private static double Log(double leaf, double arg) => Math.Log(arg, leaf);
       private static double Pow(double arg, double leaf)
       {
           if (arg > 0) return Math.Pow(arg, leaf);
           double tmp = arg;
           while ((int)tmp % 10 == 0  && CompareToZero(tmp) == false)
               tmp *= 10;
           var negativeArgument = false;

           if (CompareToZero(leaf % 2) == false)
           {
               arg = arg * -1;
              negativeArgument = true;
           }
           double result = Math.Pow(arg, leaf);
           if (negativeArgument) result = result * -1;
           return result;
       }

       private void Reader()
       {
           PointsCount = " + _arguments.Count + @";
" + pointsReader +
                        @"       }

       private double GenotypeCollections(int GenotypeIndex, int n, double[] Leaf)
       {
           switch (GenotypeIndex)
           {
" + switchGenotypes + @"
               default:
                   throw new Exception(" + "\"Error 10241610. Размер популяции был изменен.\"" + @");
           }
       }

       public double DeviationCollections(double[] Leaf, int index)
       {
           double temp = 0;
           for (int i = 0 + " + recurseFilterIndex + @"; i < PointsCount; i++)
               temp += Math.Abs((Arg[" + _arguments.Rows + @", i] - GenotypeCollections(index, i, Leaf)));
           
           if (double.IsNaN(temp)) temp = Math.Pow(10, 300);
           return temp;
       }

            //Возвращает график математической функции.
       public List<double> GetFunctionPoints(double[] leafs, int index)
       {
           var points = new List<double>();
           for (int i = 0 + " + recurseFilterIndex + @"; i < PointsCount; i++)
               points.Add(GenotypeCollections(index, i, leafs));

           return points;
       }
   }
}";
            #endregion

            var results = _csharpCompiler.Compile(ClassCode);

            if (results.Errors.HasErrors)
            {
                if (errCount.Val == 10)
                {
                    return;
                }

                string err = results.Errors.Cast <object>().Aggregate(string.Empty, (current, e) => current + e + "\r\n");

                _selectionStatus.Log.CompileErrors.Add(new CompileError {
                    Iteration = iterationNum, Code = ClassCode, ErrorText = err
                });
                errCount.Inc();
                goto RestartIfErr;
            }

            Assembly assembly = results.CompiledAssembly;

            //Новая популяция жизнеспособна
            for (var i = 0; i < _populationSize; i++)
            {
                Individual[i] = childs[i].ToIndividual();
            }

            //Вычисляем приспособленность новой популяции
            var tester = new SurvivalTester(Individual, _populationSize);
            tester.CollectFitnessFunctions(assembly, _selectionConfig.MaxNelrodMidIterations);

            BestGenotypeNumber = tester.BestGenotypeNumber;
            GraphPoints        = tester.Points;
            double simpPopul = iterationNum / 10.0;

            if (_convolutionMode == false && Math.Abs(simpPopul / Math.Truncate(simpPopul)).Equals(1))
            {
                SimplifyPopulation();
            }
        }
Exemple #16
0
        private void Initialize()
        {
            #region Create parameters
            Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
            Parameters.Add(new ScopeTreeLookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far."));
            Parameters.Add(new ValueLookupParameter <IntValue>("PopulationSize", "µ (mu) - the size of the population."));
            Parameters.Add(new ValueLookupParameter <IntValue>("ParentsPerChild", "ρ (rho) - how many parents should be recombined."));
            Parameters.Add(new ValueLookupParameter <IntValue>("Children", "λ (lambda) - the size of the offspring population."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumGenerations", "The maximum number of generations which should be processed."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("PlusSelection", "True for plus selection (elitist population), false for comma selection (non-elitist population)."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)"));
            Parameters.Add(new ValueLookupParameter <IOperator>("Mutator", "The operator used to mutate solutions."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Recombinator", "The operator used to cross solutions."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Evaluator", "The operator used to evaluate solutions. This operator is executed in parallel, if an engine is used which supports parallelization."));
            Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze each generation."));
            Parameters.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "The number of times solutions have been evaluated."));
            Parameters.Add(new ScopeParameter("CurrentScope", "The current scope which represents a population of solutions on which the EvolutionStrategy should be applied."));
            Parameters.Add(new ValueLookupParameter <IOperator>("StrategyParameterManipulator", "The operator to mutate the endogeneous strategy parameters."));
            Parameters.Add(new ValueLookupParameter <IOperator>("StrategyParameterCrossover", "The operator to cross the endogeneous strategy parameters."));
            #endregion

            #region Create operators
            VariableCreator  variableCreator                       = new VariableCreator();
            ResultsCollector resultsCollector1                     = new ResultsCollector();
            Placeholder      analyzer1                             = new Placeholder();
            WithoutRepeatingBatchedRandomSelector selector         = new WithoutRepeatingBatchedRandomSelector();
            SubScopesProcessor        subScopesProcessor1          = new SubScopesProcessor();
            Comparator                useRecombinationComparator   = new Comparator();
            ConditionalBranch         useRecombinationBranch       = new ConditionalBranch();
            ChildrenCreator           childrenCreator              = new ChildrenCreator();
            UniformSubScopesProcessor uniformSubScopesProcessor1   = new UniformSubScopesProcessor();
            Placeholder               recombinator                 = new Placeholder();
            Placeholder               strategyRecombinator         = new Placeholder();
            Placeholder               strategyMutator1             = new Placeholder();
            Placeholder               mutator1                     = new Placeholder();
            SubScopesRemover          subScopesRemover             = new SubScopesRemover();
            UniformSubScopesProcessor uniformSubScopesProcessor2   = new UniformSubScopesProcessor();
            Placeholder               strategyMutator2             = new Placeholder();
            Placeholder               mutator2                     = new Placeholder();
            UniformSubScopesProcessor uniformSubScopesProcessor3   = new UniformSubScopesProcessor();
            Placeholder               evaluator                    = new Placeholder();
            SubScopesCounter          subScopesCounter             = new SubScopesCounter();
            ConditionalBranch         plusOrCommaReplacementBranch = new ConditionalBranch();
            MergingReducer            plusReplacement              = new MergingReducer();
            RightReducer              commaReplacement             = new RightReducer();
            BestSelector              bestSelector                 = new BestSelector();
            RightReducer              rightReducer                 = new RightReducer();
            IntCounter                intCounter                   = new IntCounter();
            Comparator                comparator                   = new Comparator();
            Placeholder               analyzer2                    = new Placeholder();
            ConditionalBranch         conditionalBranch            = new ConditionalBranch();
            ConditionalBranch         reevaluateElitesBranch       = new ConditionalBranch();
            SubScopesProcessor        subScopesProcessor2          = new SubScopesProcessor();
            UniformSubScopesProcessor uniformSubScopesProcessor4   = new UniformSubScopesProcessor();
            Placeholder               evaluator2                   = new Placeholder();
            SubScopesCounter          subScopesCounter2            = new SubScopesCounter();


            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Generations", new IntValue(0))); // Class EvolutionStrategy expects this to be called Generations

            resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>("Generations"));
            resultsCollector1.ResultsParameter.ActualName = "Results";

            analyzer1.Name = "Analyzer (placeholder)";
            analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name;

            selector.Name = "ES Random Selector";
            selector.RandomParameter.ActualName          = RandomParameter.Name;
            selector.ParentsPerChildParameter.ActualName = ParentsPerChildParameter.Name;
            selector.ChildrenParameter.ActualName        = ChildrenParameter.Name;

            useRecombinationComparator.Name = "ParentsPerChild > 1";
            useRecombinationComparator.LeftSideParameter.ActualName = ParentsPerChildParameter.Name;
            useRecombinationComparator.RightSideParameter.Value     = new IntValue(1);
            useRecombinationComparator.Comparison = new Comparison(ComparisonType.Greater);
            useRecombinationComparator.ResultParameter.ActualName = "UseRecombination";

            useRecombinationBranch.Name = "Use Recombination?";
            useRecombinationBranch.ConditionParameter.ActualName = "UseRecombination";

            childrenCreator.ParentsPerChild = null;
            childrenCreator.ParentsPerChildParameter.ActualName = ParentsPerChildParameter.Name;

            recombinator.Name = "Recombinator (placeholder)";
            recombinator.OperatorParameter.ActualName = RecombinatorParameter.Name;

            strategyRecombinator.Name = "Strategy Parameter Recombinator (placeholder)";
            strategyRecombinator.OperatorParameter.ActualName = StrategyParameterCrossoverParameter.Name;

            strategyMutator1.Name = "Strategy Parameter Manipulator (placeholder)";
            strategyMutator1.OperatorParameter.ActualName = StrategyParameterManipulatorParameter.Name;

            mutator1.Name = "Mutator (placeholder)";
            mutator1.OperatorParameter.ActualName = MutatorParameter.Name;

            subScopesRemover.RemoveAllSubScopes = true;

            strategyMutator2.Name = "Strategy Parameter Manipulator (placeholder)";
            strategyMutator2.OperatorParameter.ActualName = StrategyParameterManipulatorParameter.Name;

            mutator2.Name = "Mutator (placeholder)";
            mutator2.OperatorParameter.ActualName = MutatorParameter.Name;

            uniformSubScopesProcessor3.Parallel.Value = true;

            evaluator.Name = "Evaluator (placeholder)";
            evaluator.OperatorParameter.ActualName = EvaluatorParameter.Name;

            subScopesCounter.Name = "Increment EvaluatedSolutions";
            subScopesCounter.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name;

            plusOrCommaReplacementBranch.ConditionParameter.ActualName = PlusSelectionParameter.Name;

            bestSelector.CopySelected = new BoolValue(false);
            bestSelector.MaximizationParameter.ActualName = MaximizationParameter.Name;
            bestSelector.NumberOfSelectedSubScopesParameter.ActualName = PopulationSizeParameter.Name;
            bestSelector.QualityParameter.ActualName = QualityParameter.Name;

            intCounter.Increment = new IntValue(1);
            intCounter.ValueParameter.ActualName = "Generations";

            comparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            comparator.LeftSideParameter.ActualName  = "Generations";
            comparator.ResultParameter.ActualName    = "Terminate";
            comparator.RightSideParameter.ActualName = MaximumGenerationsParameter.Name;

            analyzer2.Name = "Analyzer (placeholder)";
            analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name;

            conditionalBranch.ConditionParameter.ActualName = "Terminate";

            reevaluateElitesBranch.ConditionParameter.ActualName = "ReevaluateElites";
            reevaluateElitesBranch.Name = "Reevaluate elites ?";

            uniformSubScopesProcessor4.Parallel.Value = true;

            evaluator2.Name = "Evaluator (placeholder)";
            evaluator2.OperatorParameter.ActualName = EvaluatorParameter.Name;

            subScopesCounter2.Name = "Increment EvaluatedSolutions";
            subScopesCounter2.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name;
            #endregion

            #region Create operator graph
            OperatorGraph.InitialOperator = variableCreator;
            variableCreator.Successor     = resultsCollector1;
            resultsCollector1.Successor   = analyzer1;
            analyzer1.Successor           = selector;
            selector.Successor            = subScopesProcessor1;
            subScopesProcessor1.Operators.Add(new EmptyOperator());
            subScopesProcessor1.Operators.Add(useRecombinationComparator);
            subScopesProcessor1.Successor        = plusOrCommaReplacementBranch;
            useRecombinationComparator.Successor = useRecombinationBranch;
            useRecombinationBranch.TrueBranch    = childrenCreator;
            useRecombinationBranch.FalseBranch   = uniformSubScopesProcessor2;
            useRecombinationBranch.Successor     = uniformSubScopesProcessor3;
            childrenCreator.Successor            = uniformSubScopesProcessor1;
            uniformSubScopesProcessor1.Operator  = recombinator;
            uniformSubScopesProcessor1.Successor = null;
            recombinator.Successor               = strategyRecombinator;
            strategyRecombinator.Successor       = strategyMutator1;
            strategyMutator1.Successor           = mutator1;
            mutator1.Successor                   = subScopesRemover;
            subScopesRemover.Successor           = null;
            uniformSubScopesProcessor2.Operator  = strategyMutator2;
            uniformSubScopesProcessor2.Successor = null;
            strategyMutator2.Successor           = mutator2;
            mutator2.Successor                   = null;
            uniformSubScopesProcessor3.Operator  = evaluator;
            uniformSubScopesProcessor3.Successor = subScopesCounter;
            evaluator.Successor                  = null;
            subScopesCounter.Successor           = null;

            plusOrCommaReplacementBranch.TrueBranch = reevaluateElitesBranch;
            reevaluateElitesBranch.TrueBranch       = subScopesProcessor2;
            reevaluateElitesBranch.FalseBranch      = null;
            subScopesProcessor2.Operators.Add(uniformSubScopesProcessor4);
            subScopesProcessor2.Operators.Add(new EmptyOperator());
            uniformSubScopesProcessor4.Operator  = evaluator2;
            uniformSubScopesProcessor4.Successor = subScopesCounter2;
            subScopesCounter2.Successor          = null;
            reevaluateElitesBranch.Successor     = plusReplacement;

            plusOrCommaReplacementBranch.FalseBranch = commaReplacement;
            plusOrCommaReplacementBranch.Successor   = bestSelector;
            bestSelector.Successor        = rightReducer;
            rightReducer.Successor        = intCounter;
            intCounter.Successor          = comparator;
            comparator.Successor          = analyzer2;
            analyzer2.Successor           = conditionalBranch;
            conditionalBranch.FalseBranch = selector;
            conditionalBranch.TrueBranch  = null;
            conditionalBranch.Successor   = null;
            #endregion
        }
Exemple #17
0
        public RandomSearchAlgorithm()
            : base()
        {
            #region Add parameters
            Parameters.Add(new FixedValueParameter <IntValue>("Seed", "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
            Parameters.Add(new FixedValueParameter <BoolValue>("SetSeedRandomly", "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
            Parameters.Add(new FixedValueParameter <MultiAnalyzer>("Analyzer", "The operator used to analyze the solutions each iteration.", new MultiAnalyzer()));
            Parameters.Add(new FixedValueParameter <IntValue>("MaximumEvaluatedSolutions", "The number of random solutions the algorithm should evaluate.", new IntValue(1000)));
            Parameters.Add(new FixedValueParameter <IntValue>("BatchSize", "The number of random solutions that are evaluated (in parallel) per iteration.", new IntValue(100)));
            Parameters.Add(new FixedValueParameter <IntValue>("MaximumIterations", "The number of iterations that the algorithm will run.", new IntValue(10))
            {
                Hidden = true
            });
            Parameters.Add(new FixedValueParameter <MultiTerminator>("Terminator", "The termination criteria that defines if the algorithm should continue or stop.", new MultiTerminator())
            {
                Hidden = true
            });
            #endregion

            #region Create operators
            var randomCreator   = new RandomCreator();
            var variableCreator = new VariableCreator()
            {
                Name = "Initialize Variables"
            };
            var resultsCollector = new ResultsCollector();
            var solutionCreator  = new SolutionsCreator()
            {
                Name = "Create Solutions"
            };
            var analyzerPlaceholder = new Placeholder()
            {
                Name = "Analyzer (Placeholder)"
            };
            var evaluationsCounter = new IntCounter()
            {
                Name = "Increment EvaluatedSolutions"
            };
            var subScopesRemover  = new SubScopesRemover();
            var iterationsCounter = new IntCounter()
            {
                Name = "Increment Iterations"
            };
            var terminationOperator = new TerminationOperator();
            #endregion

            #region Create and parameterize operator graph
            OperatorGraph.InitialOperator = randomCreator;

            randomCreator.SeedParameter.Value                 = null;
            randomCreator.SeedParameter.ActualName            = SeedParameter.Name;
            randomCreator.SetSeedRandomlyParameter.Value      = null;
            randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
            randomCreator.Successor = variableCreator;

            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Iterations", new IntValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("EvaluatedSolutions", new IntValue(0)));
            variableCreator.Successor = resultsCollector;

            resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("Iterations", "The current iteration number."));
            resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "The current number of evaluated solutions."));
            resultsCollector.Successor = solutionCreator;

            solutionCreator.NumberOfSolutionsParameter.ActualName = BatchSizeParameter.Name;
            solutionCreator.ParallelParameter.Value.Value         = true;
            solutionCreator.Successor = evaluationsCounter;

            evaluationsCounter.ValueParameter.ActualName = "EvaluatedSolutions";
            evaluationsCounter.Increment = null;
            evaluationsCounter.IncrementParameter.ActualName = BatchSizeParameter.Name;
            evaluationsCounter.Successor = analyzerPlaceholder;

            analyzerPlaceholder.OperatorParameter.ActualName = AnalyzerParameter.Name;
            analyzerPlaceholder.Successor = subScopesRemover;

            subScopesRemover.RemoveAllSubScopes = true;
            subScopesRemover.Successor          = iterationsCounter;

            iterationsCounter.ValueParameter.ActualName = "Iterations";
            iterationsCounter.Increment = new IntValue(1);
            iterationsCounter.Successor = terminationOperator;

            terminationOperator.TerminatorParameter.ActualName = TerminatorParameter.Name;
            terminationOperator.ContinueBranch = solutionCreator;
            #endregion

            #region Create analyzers
            singleObjectiveQualityAnalyzer = new BestAverageWorstQualityAnalyzer();
            #endregion

            #region Create terminators
            evaluationsTerminator = new ComparisonTerminator <IntValue>("EvaluatedSolutions", ComparisonType.Less, MaximumEvaluatedSolutionsParameter)
            {
                Name = "Evaluated solutions."
            };
            qualityTerminator = new SingleObjectiveQualityTerminator()
            {
                Name = "Quality"
            };
            executionTimeTerminator = new ExecutionTimeTerminator(this, new TimeSpanValue(TimeSpan.FromMinutes(5)));
            #endregion

            #region Parameterize
            UpdateAnalyzers();
            ParameterizeAnalyzers();
            UpdateTerminators();
            #endregion

            Initialize();
        }
        private void Initialize()
        {
            #region Create parameters
            Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator."));
            Parameters.Add(new ValueLookupParameter <IntValue>("SwarmSize", "Size of the particle swarm."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaxIterations", "Maximal number of iterations."));

            Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze each generation."));

            Parameters.Add(new ValueLookupParameter <DoubleValue>("CurrentInertia", "Inertia weight on a particle's movement (omega)."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("PersonalBestAttraction", "Weight for particle's pull towards its personal best soution (phi_p)."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("NeighborBestAttraction", "Weight for pull towards the neighborhood best solution or global best solution in case of a totally connected topology (phi_g)."));

            Parameters.Add(new ValueLookupParameter <IOperator>("ParticleUpdater", "Operator that calculates new position and velocity of a particle"));
            Parameters.Add(new ValueLookupParameter <IOperator>("TopologyUpdater", "Updates the neighborhood description vectors"));
            Parameters.Add(new ValueLookupParameter <IOperator>("InertiaUpdater", "Updates the omega parameter"));
            Parameters.Add(new ValueLookupParameter <IOperator>("Evaluator", "Evaluates a particle solution."));

            Parameters.Add(new ValueLookupParameter <ResultCollection>("Results", "The variable collection where results should be stored."));
            Parameters.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "The number of times solutions have been evaluated."));

            Parameters.Add(new ValueLookupParameter <ISwarmUpdater>("SwarmUpdater", "The encoding-specific swarm updater."));
            #endregion

            #region Create operators
            ResultsCollector          resultsCollector           = new ResultsCollector();
            Placeholder               swarmUpdaterPlaceholer1    = new Placeholder();
            Placeholder               evaluatorPlaceholder       = new Placeholder();
            Placeholder               analyzerPlaceholder        = new Placeholder();
            Placeholder               analyzer2Placeholder       = new Placeholder();
            UniformSubScopesProcessor uniformSubScopeProcessor   = new UniformSubScopesProcessor();
            Placeholder               particleUpdaterPlaceholder = new Placeholder();
            Placeholder               topologyUpdaterPlaceholder = new Placeholder();
            UniformSubScopesProcessor evaluationProcessor        = new UniformSubScopesProcessor();
            Placeholder               swarmUpdater      = new Placeholder();
            IntCounter        iterationsCounter         = new IntCounter();
            Comparator        iterationsComparator      = new Comparator();
            ConditionalBranch conditionalBranch         = new ConditionalBranch();
            Placeholder       inertiaUpdaterPlaceholder = new Placeholder();
            SubScopesCounter  subScopesCounter          = new SubScopesCounter();
            #endregion

            #region Create operator graph
            OperatorGraph.InitialOperator = resultsCollector;
            resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("Iterations"));
            resultsCollector.CollectedValues.Add(new LookupParameter <DoubleValue>("CurrentInertia"));
            resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("Evaluated Solutions", null, "EvaluatedSolutions"));
            resultsCollector.ResultsParameter.ActualName = "Results";
            resultsCollector.Successor = swarmUpdaterPlaceholer1;

            swarmUpdaterPlaceholer1.Name = "(Swarm Updater)";
            swarmUpdaterPlaceholer1.OperatorParameter.ActualName = SwarmUpdaterParameter.ActualName;
            swarmUpdaterPlaceholer1.Successor = analyzerPlaceholder;

            analyzerPlaceholder.Name = "(Analyzer)";
            analyzerPlaceholder.OperatorParameter.ActualName = AnalyzerParameter.Name;
            analyzerPlaceholder.Successor = uniformSubScopeProcessor;

            uniformSubScopeProcessor.Operator  = particleUpdaterPlaceholder;
            uniformSubScopeProcessor.Successor = evaluationProcessor;

            particleUpdaterPlaceholder.Name = "(ParticleUpdater)";
            particleUpdaterPlaceholder.OperatorParameter.ActualName = ParticleUpdaterParameter.Name;

            evaluationProcessor.Parallel  = new BoolValue(true);
            evaluationProcessor.Operator  = evaluatorPlaceholder;
            evaluationProcessor.Successor = subScopesCounter;

            evaluatorPlaceholder.Name = "(Evaluator)";
            evaluatorPlaceholder.OperatorParameter.ActualName = EvaluatorParameter.Name;

            subScopesCounter.Name = "Increment EvaluatedSolutions";
            subScopesCounter.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name;
            subScopesCounter.Successor = topologyUpdaterPlaceholder;

            topologyUpdaterPlaceholder.Name = "(TopologyUpdater)";
            topologyUpdaterPlaceholder.OperatorParameter.ActualName = TopologyUpdaterParameter.Name;
            topologyUpdaterPlaceholder.Successor = swarmUpdater;

            swarmUpdater.Name = "(Swarm Updater)";
            swarmUpdater.OperatorParameter.ActualName = SwarmUpdaterParameter.ActualName;
            swarmUpdater.Successor = inertiaUpdaterPlaceholder;

            inertiaUpdaterPlaceholder.Name = "(Inertia Updater)";
            inertiaUpdaterPlaceholder.OperatorParameter.ActualName = InertiaUpdaterParameter.ActualName;
            inertiaUpdaterPlaceholder.Successor = iterationsCounter;

            iterationsCounter.Name = "Iterations++";
            iterationsCounter.ValueParameter.ActualName = "Iterations";
            iterationsCounter.Successor = iterationsComparator;

            iterationsComparator.LeftSideParameter.ActualName = "Iterations";
            iterationsComparator.Comparison = new Comparison(ComparisonType.Less);
            iterationsComparator.RightSideParameter.ActualName = "MaxIterations";
            iterationsComparator.ResultParameter.ActualName    = "ContinueIteration";
            iterationsComparator.Successor = conditionalBranch;

            conditionalBranch.Name = "ContinueIteration?";
            conditionalBranch.ConditionParameter.ActualName = "ContinueIteration";
            conditionalBranch.TrueBranch  = analyzerPlaceholder;
            conditionalBranch.FalseBranch = analyzer2Placeholder;

            analyzer2Placeholder.Name = "(Analyzer)";
            analyzer2Placeholder.OperatorParameter.ActualName = AnalyzerParameter.Name;
            #endregion
        }
Exemple #19
0
        private void LoadFile(ITaggedFileReader reader, IDictionary <string, IntCounter <string> > wordTagCounts)
        {
            log.Info("Loading tagged words from " + reader.Filename());
            List <string> words        = new List <string>();
            List <string> tags         = new List <string>();
            int           numSentences = 0;
            int           numWords     = 0;
            int           maxLen       = int.MinValue;
            int           minLen       = int.MaxValue;

            foreach (IList <TaggedWord> sentence in reader)
            {
                if (maxentTagger.wordFunction != null)
                {
                    IList <TaggedWord> newSentence = new List <TaggedWord>(sentence.Count);
                    foreach (TaggedWord word in sentence)
                    {
                        TaggedWord newWord = new TaggedWord(maxentTagger.wordFunction.Apply(word.Word()), word.Tag());
                        newSentence.Add(newWord);
                    }
                    sentence = newSentence;
                }
                foreach (TaggedWord tw in sentence)
                {
                    if (tw != null)
                    {
                        words.Add(tw.Word());
                        tags.Add(tw.Tag());
                        if (!maxentTagger.tagTokens.Contains(tw.Tag()))
                        {
                            maxentTagger.tagTokens[tw.Tag()] = Generics.NewHashSet <string>();
                        }
                        maxentTagger.tagTokens[tw.Tag()].Add(tw.Word());
                    }
                }
                maxLen = (sentence.Count > maxLen ? sentence.Count : maxLen);
                minLen = (sentence.Count < minLen ? sentence.Count : minLen);
                words.Add(Edu.Stanford.Nlp.Tagger.Common.Tagger.EosWord);
                tags.Add(Edu.Stanford.Nlp.Tagger.Common.Tagger.EosTag);
                numElements = numElements + sentence.Count + 1;
                // iterate over the words in the sentence
                for (int i = 0; i < sentence.Count + 1; i++)
                {
                    History h    = new History(totalWords + totalSentences, totalWords + totalSentences + sentence.Count, totalWords + totalSentences + i, pairs, maxentTagger.extractors);
                    string  tag  = tags[i];
                    string  word = words[i];
                    pairs.Add(new WordTag(word, tag));
                    int         y   = maxentTagger.AddTag(tag);
                    DataWordTag dat = new DataWordTag(h, y, tag);
                    v.Add(dat);
                    IntCounter <string> tagCounts = wordTagCounts[word];
                    if (tagCounts == null)
                    {
                        tagCounts           = new IntCounter <string>();
                        wordTagCounts[word] = tagCounts;
                    }
                    tagCounts.IncrementCount(tag, 1);
                }
                totalSentences++;
                totalWords += sentence.Count;
                numSentences++;
                numWords += sentence.Count;
                words.Clear();
                tags.Clear();
                if ((numSentences % 100000) == 0)
                {
                    log.Info("Read " + numSentences + " sentences, min " + minLen + " words, max " + maxLen + " words ... [still reading]");
                }
            }
            log.Info("Read " + numWords + " words from " + reader.Filename() + " [done].");
            log.Info("Read " + numSentences + " sentences, min " + minLen + " words, max " + maxLen + " words.");
        }
Exemple #20
0
        public RobustTabooSearch()
        {
            Parameters.Add(new ValueParameter <MultiAnalyzer>("Analyzer", "The analyzers that are applied after each iteration.", new MultiAnalyzer()));
            Parameters.Add(new FixedValueParameter <IntValue>("Seed", "The seed value of the random number generator.", new IntValue(0)));
            Parameters.Add(new FixedValueParameter <BoolValue>("SetSeedRandomly", "True whether the seed should be set randomly for each run, false if it should be fixed.", new BoolValue(true)));
            Parameters.Add(new FixedValueParameter <IntValue>("MaximumIterations", "The number of iterations that the algorithm should run.", new IntValue(10000)));
            Parameters.Add(new FixedValueParameter <IntValue>("MinimumTabuTenure", "The minimum tabu tenure.", new IntValue(10)));
            Parameters.Add(new FixedValueParameter <IntValue>("MaximumTabuTenure", "The maximum tabu tenure.", new IntValue(20)));
            Parameters.Add(new FixedValueParameter <BoolValue>("UseAlternativeAspiration", "True if the alternative aspiration condition should be used that takes moves that have not been made for some time above others.", new BoolValue(false)));
            Parameters.Add(new FixedValueParameter <IntValue>("AlternativeAspirationTenure", "The time t that a move will be remembered for the alternative aspiration condition.", new IntValue(int.MaxValue)));
            Parameters.Add(new FixedValueParameter <BoolValue>("TerminateOnOptimalSolution", "True when the algorithm should stop if it reached a quality equal or smaller to the BestKnownQuality.", new BoolValue(false)));
            Parameters.Add(new FixedValueParameter <BoolValue>("UseNewTabuTenureAdaptionScheme", @"In an updated version of his implementation, Eric Taillard introduced a different way to change the tabu tenure.
Instead of setting it uniformly between min and max, it will be set between 0 and max according to a right-skewed distribution.
Set this option to false if you want to optimize using the earlier 1991 version, and set to true if you want to optimize using the newer version.
Please note that the MinimumTabuTenure parameter has no effect in the new version.", new BoolValue(true)));

            TerminateOnOptimalSolutionParameter.Hidden = true;

            qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
            qualityAnalyzer.ResultsParameter.ActualName = "Results";
            AnalyzerParameter.Value.Operators.Add(qualityAnalyzer);

            RandomCreator randomCreator = new RandomCreator();

            randomCreator.RandomParameter.ActualName          = "Random";
            randomCreator.SeedParameter.Value                 = null;
            randomCreator.SeedParameter.ActualName            = SeedParameter.Name;
            randomCreator.SetSeedRandomlyParameter.Value      = null;
            randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;

            VariableCreator variableCreator = new VariableCreator();

            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Iterations", new IntValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("EvaluatedSolutions", new IntValue(1)));
            variableCreator.CollectedValues.Add(new ValueParameter <DoubleValue>("EvaluatedSolutionEquivalents", new DoubleValue(1)));

            ResultsCollector resultsCollector = new ResultsCollector();

            resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("Iterations", "The actual iteration."));
            resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "Number of evaluated solutions."));

            solutionsCreator = new SolutionsCreator();
            solutionsCreator.NumberOfSolutions = new IntValue(1);

            Placeholder analyzer = new Placeholder();

            analyzer.Name = "(Analyzer)";
            analyzer.OperatorParameter.ActualName = AnalyzerParameter.Name;

            UniformSubScopesProcessor ussp = new UniformSubScopesProcessor();

            mainOperator = new RobustTabooSeachOperator();
            mainOperator.AlternativeAspirationTenureParameter.ActualName = AlternativeAspirationTenureParameter.Name;
            mainOperator.BestQualityParameter.ActualName                  = "BestSoFarQuality";
            mainOperator.IterationsParameter.ActualName                   = "Iterations";
            mainOperator.LastMoveParameter.ActualName                     = "LastMove";
            mainOperator.MaximumIterationsParameter.ActualName            = MaximumIterationsParameter.Name;
            mainOperator.MaximumTabuTenureParameter.ActualName            = MaximumTabuTenureParameter.Name;
            mainOperator.MinimumTabuTenureParameter.ActualName            = MinimumTabuTenureParameter.Name;
            mainOperator.MoveQualityMatrixParameter.ActualName            = "MoveQualityMatrix";
            mainOperator.RandomParameter.ActualName                       = "Random";
            mainOperator.ResultsParameter.ActualName                      = "Results";
            mainOperator.ShortTermMemoryParameter.ActualName              = "ShortTermMemory";
            mainOperator.UseAlternativeAspirationParameter.ActualName     = UseAlternativeAspirationParameter.Name;
            mainOperator.EvaluatedSolutionsParameter.ActualName           = "EvaluatedSolutions";
            mainOperator.EvaluatedSolutionEquivalentsParameter.ActualName = "EvaluatedSolutionEquivalents";

            ConditionalBranch qualityStopBranch = new ConditionalBranch();

            qualityStopBranch.Name = "Terminate on optimal quality?";
            qualityStopBranch.ConditionParameter.ActualName = "TerminateOnOptimalSolution";

            Comparator qualityComparator = new Comparator();

            qualityComparator.Comparison = new Comparison(ComparisonType.Greater);
            qualityComparator.LeftSideParameter.ActualName  = "BestQuality";
            qualityComparator.RightSideParameter.ActualName = "BestKnownQuality";
            qualityComparator.ResultParameter.ActualName    = "ContinueByQuality";

            ConditionalBranch continueByQualityBranch = new ConditionalBranch();

            continueByQualityBranch.ConditionParameter.ActualName = "ContinueByQuality";

            IntCounter iterationsCounter = new IntCounter();

            iterationsCounter.ValueParameter.ActualName = "Iterations";
            iterationsCounter.Increment = new IntValue(1);

            Comparator comparator = new Comparator();

            comparator.Name = "Iterations < MaximumIterations ?";
            comparator.LeftSideParameter.ActualName  = "Iterations";
            comparator.RightSideParameter.ActualName = MaximumIterationsParameter.Name;
            comparator.Comparison = new Comparison(ComparisonType.Less);
            comparator.ResultParameter.ActualName = "ContinueByIteration";

            ConditionalBranch continueByIterationBranch = new ConditionalBranch();

            continueByIterationBranch.ConditionParameter.ActualName = "ContinueByIteration";

            OperatorGraph.InitialOperator = randomCreator;
            randomCreator.Successor       = variableCreator;
            variableCreator.Successor     = resultsCollector;
            resultsCollector.Successor    = solutionsCreator;
            solutionsCreator.Successor    = analyzer;
            analyzer.Successor            = ussp;
            ussp.Operator  = mainOperator;
            ussp.Successor = qualityStopBranch;
            qualityStopBranch.FalseBranch       = iterationsCounter;
            qualityStopBranch.TrueBranch        = qualityComparator;
            qualityStopBranch.Successor         = null;
            qualityComparator.Successor         = continueByQualityBranch;
            continueByQualityBranch.TrueBranch  = iterationsCounter;
            continueByQualityBranch.FalseBranch = null;
            continueByQualityBranch.Successor   = null;
            iterationsCounter.Successor         = comparator;
            comparator.Successor = continueByIterationBranch;
            continueByIterationBranch.TrueBranch  = analyzer;
            continueByIterationBranch.FalseBranch = null;
            continueByIterationBranch.Successor   = null;

            RegisterEventHandlers();
            Problem = new QuadraticAssignmentProblem();
        }
Exemple #21
0
        private void Initialize()
        {
            #region Create parameters
            Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
            Parameters.Add(new LookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far."));
            Parameters.Add(new LookupParameter <DoubleValue>("MoveQuality", "The value which represents the quality of a move."));
            Parameters.Add(new LookupParameter <DoubleValue>("Temperature", "The current temperature."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("StartTemperature", "The initial temperature."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("EndTemperature", "The end temperature."));
            Parameters.Add(new ValueLookupParameter <IntValue>("InnerIterations", "The amount of inner iterations (number of moves before temperature is adjusted again)."));
            Parameters.Add(new LookupParameter <IntValue>("Iterations", "The number of iterations."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumIterations", "The maximum number of iterations which should be processed."));

            Parameters.Add(new ValueLookupParameter <IOperator>("MoveGenerator", "The operator that generates the moves."));
            Parameters.Add(new ValueLookupParameter <IOperator>("MoveEvaluator", "The operator that evaluates a move."));
            Parameters.Add(new ValueLookupParameter <IOperator>("MoveMaker", "The operator that performs a move and updates the quality."));
            Parameters.Add(new ValueLookupParameter <IOperator>("AnnealingOperator", "The operator that modifies the temperature."));

            Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze each generation."));
            Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored."));
            Parameters.Add(new LookupParameter <IntValue>("EvaluatedMoves", "The number of evaluated moves."));
            #endregion

            #region Create operators
            Assigner                       temperatureInitializer = new Assigner();
            ResultsCollector               resultsCollector1      = new ResultsCollector();
            SubScopesProcessor             subScopesProcessor0    = new SubScopesProcessor();
            Placeholder                    analyzer1               = new Placeholder();
            SubScopesProcessor             sssp                    = new SubScopesProcessor();
            ResultsCollector               resultsCollector        = new ResultsCollector();
            Placeholder                    annealingOperator       = new Placeholder();
            UniformSubScopesProcessor      mainProcessor           = new UniformSubScopesProcessor();
            Placeholder                    moveGenerator           = new Placeholder();
            UniformSubScopesProcessor      moveEvaluationProcessor = new UniformSubScopesProcessor();
            Placeholder                    moveEvaluator           = new Placeholder();
            SubScopesCounter               subScopesCounter        = new SubScopesCounter();
            ProbabilisticQualityComparator qualityComparator       = new ProbabilisticQualityComparator();
            ConditionalBranch              improvesQualityBranch   = new ConditionalBranch();
            Placeholder                    moveMaker               = new Placeholder();
            SubScopesRemover               subScopesRemover        = new SubScopesRemover();
            IntCounter                     iterationsCounter       = new IntCounter();
            Comparator                     iterationsComparator    = new Comparator();
            SubScopesProcessor             subScopesProcessor1     = new SubScopesProcessor();
            Placeholder                    analyzer2               = new Placeholder();
            ConditionalBranch              iterationsTermination   = new ConditionalBranch();

            temperatureInitializer.LeftSideParameter.ActualName  = TemperatureParameter.ActualName;
            temperatureInitializer.RightSideParameter.ActualName = StartTemperatureParameter.Name;

            resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>(IterationsParameter.Name));
            resultsCollector1.ResultsParameter.ActualName = ResultsParameter.Name;

            analyzer1.Name = "Analyzer (placeholder)";
            analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name;

            annealingOperator.Name = "Annealing operator (placeholder)";
            annealingOperator.OperatorParameter.ActualName = AnnealingOperatorParameter.Name;

            moveGenerator.Name = "Move generator (placeholder)";
            moveGenerator.OperatorParameter.ActualName = MoveGeneratorParameter.Name;

            moveEvaluator.Name = "Move evaluator (placeholder)";
            moveEvaluator.OperatorParameter.ActualName = MoveEvaluatorParameter.Name;

            subScopesCounter.Name = "Increment EvaluatedMoves";
            subScopesCounter.ValueParameter.ActualName = EvaluatedMovesParameter.Name;

            qualityComparator.LeftSideParameter.ActualName  = MoveQualityParameter.Name;
            qualityComparator.RightSideParameter.ActualName = QualityParameter.Name;
            qualityComparator.ResultParameter.ActualName    = "IsBetter";
            qualityComparator.DampeningParameter.ActualName = "Temperature";

            improvesQualityBranch.ConditionParameter.ActualName = "IsBetter";

            moveMaker.Name = "Move maker (placeholder)";
            moveMaker.OperatorParameter.ActualName = MoveMakerParameter.Name;

            subScopesRemover.RemoveAllSubScopes = true;

            iterationsCounter.Name      = "Increment Iterations";
            iterationsCounter.Increment = new IntValue(1);
            iterationsCounter.ValueParameter.ActualName = IterationsParameter.Name;

            iterationsComparator.Name = "Iterations >= MaximumIterations";
            iterationsComparator.LeftSideParameter.ActualName  = IterationsParameter.Name;
            iterationsComparator.RightSideParameter.ActualName = MaximumIterationsParameter.Name;
            iterationsComparator.ResultParameter.ActualName    = "Terminate";
            iterationsComparator.Comparison.Value = ComparisonType.GreaterOrEqual;

            analyzer2.Name = "Analyzer (placeholder)";
            analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name;

            iterationsTermination.Name = "Iterations termination condition";
            iterationsTermination.ConditionParameter.ActualName = "Terminate";
            #endregion

            #region Create operator graph
            OperatorGraph.InitialOperator    = temperatureInitializer;
            temperatureInitializer.Successor = resultsCollector1;
            resultsCollector1.Successor      = subScopesProcessor0;
            subScopesProcessor0.Operators.Add(analyzer1);
            subScopesProcessor0.Successor = sssp;
            analyzer1.Successor           = null;
            sssp.Operators.Add(resultsCollector);
            sssp.Successor                    = annealingOperator;
            resultsCollector.Successor        = null;
            annealingOperator.Successor       = mainProcessor;
            mainProcessor.Operator            = moveGenerator;
            mainProcessor.Successor           = iterationsCounter;
            moveGenerator.Successor           = moveEvaluationProcessor;
            moveEvaluationProcessor.Operator  = moveEvaluator;
            moveEvaluationProcessor.Successor = subScopesCounter;
            moveEvaluator.Successor           = qualityComparator;
            qualityComparator.Successor       = improvesQualityBranch;
            improvesQualityBranch.TrueBranch  = moveMaker;
            improvesQualityBranch.FalseBranch = null;
            improvesQualityBranch.Successor   = null;
            moveMaker.Successor               = null;
            subScopesCounter.Successor        = subScopesRemover;
            subScopesRemover.Successor        = null;
            iterationsCounter.Successor       = iterationsComparator;
            iterationsComparator.Successor    = subScopesProcessor1;
            subScopesProcessor1.Operators.Add(analyzer2);
            subScopesProcessor1.Successor     = iterationsTermination;
            iterationsTermination.TrueBranch  = null;
            iterationsTermination.FalseBranch = annealingOperator;
            #endregion
        }
        private void Initialize()
        {
            #region Create parameters
            Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
            Parameters.Add(new ScopeTreeLookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far."));
            Parameters.Add(new ValueLookupParameter <IntValue>("PopulationSize", "µ (mu) - the size of the population."));
            Parameters.Add(new ValueLookupParameter <IntValue>("ParentsPerChild", "ρ (rho) - how many parents should be recombined."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumGenerations", "The maximum number of generations which should be processed."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("PlusSelection", "True for plus selection (elitist population), false for comma selection (non-elitist population)."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)"));
            Parameters.Add(new ValueLookupParameter <IOperator>("Mutator", "The operator used to mutate solutions."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Recombinator", "The operator used to cross solutions."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Evaluator", "The operator used to evaluate solutions. This operator is executed in parallel, if an engine is used which supports parallelization."));
            Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze each generation."));
            Parameters.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "The number of times solutions have been evaluated."));
            Parameters.Add(new ScopeParameter("CurrentScope", "The current scope which represents a population of solutions on which the OffspringSelectionEvolutionStrategy should be applied."));
            Parameters.Add(new ValueLookupParameter <IOperator>("StrategyParameterManipulator", "The operator to mutate the endogeneous strategy parameters."));
            Parameters.Add(new ValueLookupParameter <IOperator>("StrategyParameterCrossover", "The operator to cross the endogeneous strategy parameters."));

            Parameters.Add(new LookupParameter <DoubleValue>("CurrentSuccessRatio", "The current success ratio."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("SuccessRatio", "The ratio of successful to total children that should be achieved."));
            Parameters.Add(new LookupParameter <DoubleValue>("SelectionPressure", "The actual selection pressure."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("MaximumSelectionPressure", "The maximum selection pressure that terminates the algorithm."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumEvaluatedSolutions", "The maximum number of evaluated solutions."));
            Parameters.Add(new ValueLookupParameter <IntValue>("SelectedParents", "How much parents should be selected each time the offspring selection step is performed until the population is filled. This parameter should be about the same or twice the size of PopulationSize for smaller problems, and less for large problems."));
            Parameters.Add(new LookupParameter <DoubleValue>("ComparisonFactor", "The comparison factor is used to determine whether the offspring should be compared to the better parent, the worse parent or a quality value linearly interpolated between them. It is in the range [0;1]."));

            #endregion

            #region Create operators
            VariableCreator  variableCreator                                           = new VariableCreator();
            ResultsCollector resultsCollector1                                         = new ResultsCollector();
            Placeholder      analyzer1                                                 = new Placeholder();
            WithoutRepeatingBatchedRandomSelector selector                             = new WithoutRepeatingBatchedRandomSelector();
            SubScopesProcessor                 subScopesProcessor1                     = new SubScopesProcessor();
            Comparator                         useRecombinationComparator              = new Comparator();
            ConditionalBranch                  useRecombinationBranch                  = new ConditionalBranch();
            ChildrenCreator                    childrenCreator                         = new ChildrenCreator();
            UniformSubScopesProcessor          uniformSubScopesProcessor1              = new UniformSubScopesProcessor();
            Placeholder                        recombinator                            = new Placeholder();
            Placeholder                        strategyRecombinator                    = new Placeholder();
            Placeholder                        strategyMutator1                        = new Placeholder();
            Placeholder                        mutator1                                = new Placeholder();
            SubScopesRemover                   subScopesRemover                        = new SubScopesRemover();
            UniformSubScopesProcessor          uniformSubScopesProcessor2              = new UniformSubScopesProcessor();
            Placeholder                        strategyMutator2                        = new Placeholder();
            Placeholder                        mutator2                                = new Placeholder();
            UniformSubScopesProcessor          uniformSubScopesProcessor3              = new UniformSubScopesProcessor();
            Placeholder                        evaluator                               = new Placeholder();
            SubScopesCounter                   subScopesCounter                        = new SubScopesCounter();
            ConditionalBranch                  plusOrCommaReplacementBranch            = new ConditionalBranch();
            MergingReducer                     plusReplacement                         = new MergingReducer();
            RightReducer                       commaReplacement                        = new RightReducer();
            BestSelector                       bestSelector                            = new BestSelector();
            RightReducer                       rightReducer                            = new RightReducer();
            IntCounter                         intCounter                              = new IntCounter();
            Comparator                         maxGenerationsComparator                = new Comparator();
            Placeholder                        analyzer2                               = new Placeholder();
            ConditionalBranch                  conditionalBranchTerminate              = new ConditionalBranch();
            ConditionalBranch                  reevaluateElitesBranch                  = new ConditionalBranch();
            SubScopesProcessor                 subScopesProcessor2                     = new SubScopesProcessor();
            UniformSubScopesProcessor          uniformSubScopesProcessor4              = new UniformSubScopesProcessor();
            Placeholder                        evaluator2                              = new Placeholder();
            SubScopesCounter                   subScopesCounter2                       = new SubScopesCounter();
            WeightedParentsQualityComparator   parentsComparator                       = new WeightedParentsQualityComparator();
            SubScopesRemover                   subScopesRemover_afterCompare           = new SubScopesRemover();
            EvolutionStrategyOffspringSelector offspringSelector                       = new EvolutionStrategyOffspringSelector();
            ChildrenCopyCreator                childrenCopyCreator                     = new ChildrenCopyCreator();
            Comparator                         maxSelectionPressureComparator          = new Comparator();
            ConditionalBranch                  conditionalBranchTerminateSelPressure   = new ConditionalBranch();
            Comparator                         maxEvaluatedSolutionsComparator         = new Comparator();
            ConditionalBranch                  conditionalBranchTerminateEvalSolutions = new ConditionalBranch();

            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Generations", new IntValue(0))); // Class OffspringSelectionEvolutionStrategy expects this to be called Generations
            variableCreator.CollectedValues.Add(new ValueParameter <DoubleValue>("SelectionPressure", new DoubleValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <DoubleValue>("CurrentSuccessRatio", new DoubleValue(0)));

            resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>("Generations"));
            resultsCollector1.CollectedValues.Add(new LookupParameter <DoubleValue>("Current Selection Pressure", "Displays the rising selection pressure during a generation.", "SelectionPressure"));
            resultsCollector1.CollectedValues.Add(new LookupParameter <DoubleValue>("Current Success Ratio", "Indicates how many successful children were already found during a generation (relative to the population size).", "CurrentSuccessRatio"));
            resultsCollector1.CopyValue = new BoolValue(false);
            resultsCollector1.ResultsParameter.ActualName = ResultsParameter.Name;

            analyzer1.Name = "Analyzer (placeholder)";
            analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name;

            selector.Name = "ES Random Selector";
            selector.RandomParameter.ActualName          = RandomParameter.Name;
            selector.ParentsPerChildParameter.ActualName = ParentsPerChildParameter.Name;
            selector.ChildrenParameter.ActualName        = SelectedParentsParameter.Name;

            useRecombinationComparator.Name = "ParentsPerChild > 1";
            useRecombinationComparator.LeftSideParameter.ActualName = ParentsPerChildParameter.Name;
            useRecombinationComparator.RightSideParameter.Value     = new IntValue(1);
            useRecombinationComparator.Comparison = new Comparison(ComparisonType.Greater);
            useRecombinationComparator.ResultParameter.ActualName = "UseRecombination";

            useRecombinationBranch.Name = "Use Recombination?";
            useRecombinationBranch.ConditionParameter.ActualName = "UseRecombination";

            childrenCreator.ParentsPerChild = null;
            childrenCreator.ParentsPerChildParameter.ActualName = ParentsPerChildParameter.Name;

            recombinator.Name = "Recombinator (placeholder)";
            recombinator.OperatorParameter.ActualName = RecombinatorParameter.Name;

            strategyRecombinator.Name = "Strategy Parameter Recombinator (placeholder)";
            strategyRecombinator.OperatorParameter.ActualName = StrategyParameterCrossoverParameter.Name;

            strategyMutator1.Name = "Strategy Parameter Manipulator (placeholder)";
            strategyMutator1.OperatorParameter.ActualName = StrategyParameterManipulatorParameter.Name;

            mutator1.Name = "Mutator (placeholder)";
            mutator1.OperatorParameter.ActualName = MutatorParameter.Name;

            subScopesRemover.RemoveAllSubScopes = true;

            strategyMutator2.Name = "Strategy Parameter Manipulator (placeholder)";
            strategyMutator2.OperatorParameter.ActualName = StrategyParameterManipulatorParameter.Name;

            mutator2.Name = "Mutator (placeholder)";
            mutator2.OperatorParameter.ActualName = MutatorParameter.Name;

            uniformSubScopesProcessor3.Parallel.Value = true;

            evaluator.Name = "Evaluator (placeholder)";
            evaluator.OperatorParameter.ActualName = EvaluatorParameter.Name;

            subScopesCounter.Name = "Increment EvaluatedSolutions";
            subScopesCounter.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name;

            plusOrCommaReplacementBranch.ConditionParameter.ActualName = PlusSelectionParameter.Name;

            bestSelector.CopySelected = new BoolValue(false);
            bestSelector.MaximizationParameter.ActualName = MaximizationParameter.Name;
            bestSelector.NumberOfSelectedSubScopesParameter.ActualName = PopulationSizeParameter.Name;
            bestSelector.QualityParameter.ActualName = QualityParameter.Name;

            intCounter.Increment = new IntValue(1);
            intCounter.ValueParameter.ActualName = "Generations";

            maxGenerationsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            maxGenerationsComparator.LeftSideParameter.ActualName  = "Generations";
            maxGenerationsComparator.ResultParameter.ActualName    = "Terminate";
            maxGenerationsComparator.RightSideParameter.ActualName = MaximumGenerationsParameter.Name;

            analyzer2.Name = "Analyzer (placeholder)";
            analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name;

            conditionalBranchTerminate.ConditionParameter.ActualName = "Terminate";

            reevaluateElitesBranch.ConditionParameter.ActualName = "ReevaluateElites";
            reevaluateElitesBranch.Name = "Reevaluate elites ?";

            uniformSubScopesProcessor4.Parallel.Value = true;

            evaluator2.Name = "Evaluator (placeholder)";
            evaluator2.OperatorParameter.ActualName = EvaluatorParameter.Name;

            subScopesCounter2.Name = "Increment EvaluatedSolutions";
            subScopesCounter2.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name;

            parentsComparator.ComparisonFactorParameter.ActualName = ComparisonFactorParameter.Name;
            parentsComparator.LeftSideParameter.ActualName         = QualityParameter.Name;
            parentsComparator.RightSideParameter.ActualName        = QualityParameter.Name;
            parentsComparator.MaximizationParameter.ActualName     = MaximizationParameter.Name;
            parentsComparator.ResultParameter.ActualName           = "SuccessfulOffspring";

            subScopesRemover_afterCompare.RemoveAllSubScopes = true;

            offspringSelector.CurrentSuccessRatioParameter.ActualName        = CurrentSuccessRatioParameter.Name;
            offspringSelector.MaximumSelectionPressureParameter.ActualName   = MaximumSelectionPressureParameter.Name;
            offspringSelector.SelectionPressureParameter.ActualName          = SelectionPressureParameter.Name;
            offspringSelector.SuccessRatioParameter.ActualName               = SuccessRatioParameter.Name;
            offspringSelector.OffspringPopulationParameter.ActualName        = "OffspringPopulation";
            offspringSelector.OffspringPopulationWinnersParameter.ActualName = "OffspringPopulationWinners";
            offspringSelector.SuccessfulOffspringParameter.ActualName        = "SuccessfulOffspring";
            offspringSelector.QualityParameter.ActualName = QualityParameter.Name;

            maxSelectionPressureComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            maxSelectionPressureComparator.LeftSideParameter.ActualName  = "SelectionPressure";
            maxSelectionPressureComparator.ResultParameter.ActualName    = "TerminateSelectionPressure";
            maxSelectionPressureComparator.RightSideParameter.ActualName = MaximumSelectionPressureParameter.Name;

            conditionalBranchTerminateSelPressure.ConditionParameter.ActualName = "TerminateSelectionPressure";

            maxEvaluatedSolutionsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            maxEvaluatedSolutionsComparator.LeftSideParameter.ActualName  = "EvaluatedSolutions";
            maxEvaluatedSolutionsComparator.ResultParameter.ActualName    = "TerminateEvaluatedSolutions";
            maxEvaluatedSolutionsComparator.RightSideParameter.ActualName = MaximumEvaluatedSolutionsParameter.Name;

            conditionalBranchTerminateEvalSolutions.ConditionParameter.ActualName = "TerminateEvaluatedSolutions";

            #endregion

            #region Create operator graph
            OperatorGraph.InitialOperator = variableCreator;
            variableCreator.Successor     = resultsCollector1;
            resultsCollector1.Successor   = analyzer1;
            analyzer1.Successor           = selector;
            selector.Successor            = subScopesProcessor1;
            subScopesProcessor1.Operators.Add(new EmptyOperator());
            subScopesProcessor1.Operators.Add(useRecombinationComparator);

            subScopesProcessor1.Successor      = offspringSelector;
            offspringSelector.OffspringCreator = selector;
            offspringSelector.Successor        = plusOrCommaReplacementBranch;

            useRecombinationComparator.Successor = useRecombinationBranch;
            useRecombinationBranch.TrueBranch    = childrenCreator;

            useRecombinationBranch.FalseBranch = childrenCopyCreator;
            childrenCopyCreator.Successor      = uniformSubScopesProcessor2;

            useRecombinationBranch.Successor     = uniformSubScopesProcessor3;
            childrenCreator.Successor            = uniformSubScopesProcessor1;
            uniformSubScopesProcessor1.Operator  = recombinator;
            uniformSubScopesProcessor1.Successor = null;
            recombinator.Successor         = strategyRecombinator;
            strategyRecombinator.Successor = strategyMutator1;
            strategyMutator1.Successor     = mutator1;

            mutator1.Successor = null;

            uniformSubScopesProcessor2.Operator  = strategyMutator2;
            uniformSubScopesProcessor2.Successor = null;
            strategyMutator2.Successor           = mutator2;
            mutator2.Successor = null;
            uniformSubScopesProcessor3.Operator  = evaluator;
            uniformSubScopesProcessor3.Successor = subScopesCounter;

            evaluator.Successor                     = parentsComparator;
            parentsComparator.Successor             = subScopesRemover_afterCompare;
            subScopesRemover_afterCompare.Successor = null;
            subScopesCounter.Successor              = null;

            plusOrCommaReplacementBranch.TrueBranch = reevaluateElitesBranch;
            reevaluateElitesBranch.TrueBranch       = subScopesProcessor2;
            reevaluateElitesBranch.FalseBranch      = null;
            subScopesProcessor2.Operators.Add(uniformSubScopesProcessor4);
            subScopesProcessor2.Operators.Add(new EmptyOperator());
            uniformSubScopesProcessor4.Operator  = evaluator2;
            uniformSubScopesProcessor4.Successor = subScopesCounter2;
            subScopesCounter2.Successor          = null;
            reevaluateElitesBranch.Successor     = plusReplacement;

            plusReplacement.Successor = bestSelector;
            bestSelector.Successor    = rightReducer;

            plusOrCommaReplacementBranch.FalseBranch = commaReplacement;
            plusOrCommaReplacementBranch.Successor   = intCounter;


            intCounter.Successor = maxGenerationsComparator;
            maxGenerationsComparator.Successor        = maxSelectionPressureComparator;
            maxSelectionPressureComparator.Successor  = maxEvaluatedSolutionsComparator;
            maxEvaluatedSolutionsComparator.Successor = analyzer2;
            analyzer2.Successor = conditionalBranchTerminate;
            conditionalBranchTerminate.FalseBranch              = conditionalBranchTerminateSelPressure;
            conditionalBranchTerminate.TrueBranch               = null;
            conditionalBranchTerminate.Successor                = null;
            conditionalBranchTerminateSelPressure.FalseBranch   = conditionalBranchTerminateEvalSolutions;
            conditionalBranchTerminateSelPressure.TrueBranch    = null;
            conditionalBranchTerminateSelPressure.Successor     = null;
            conditionalBranchTerminateEvalSolutions.FalseBranch = selector;
            conditionalBranchTerminateEvalSolutions.TrueBranch  = null;
            conditionalBranchTerminateEvalSolutions.Successor   = null;

            #endregion
        }
 public VariableStrings()
 {
     varsToStrings = ArrayMap.NewArrayMap();
     numVarsSet    = new IntCounter <string>(MapFactory.ArrayMapFactory <string, MutableInteger>());
 }
Exemple #24
0
        private void TrainModel(string serializedPath, Edu.Stanford.Nlp.Tagger.Common.Tagger tagger, Random random, IList <Tree> binarizedTrees, IList <IList <ITransition> > transitionLists, Treebank devTreebank, int nThreads, ICollection <string> allowedFeatures
                                )
        {
            double bestScore     = 0.0;
            int    bestIteration = 0;
            PriorityQueue <ScoredObject <PerceptronModel> > bestModels = null;

            if (op.TrainOptions().averagedModels > 0)
            {
                bestModels = new PriorityQueue <ScoredObject <PerceptronModel> >(op.TrainOptions().averagedModels + 1, ScoredComparator.AscendingComparator);
            }
            IList <int> indices = Generics.NewArrayList();

            for (int i = 0; i < binarizedTrees.Count; ++i)
            {
                indices.Add(i);
            }
            Oracle oracle = null;

            if (op.TrainOptions().trainingMethod == ShiftReduceTrainOptions.TrainingMethod.Oracle)
            {
                oracle = new Oracle(binarizedTrees, op.compoundUnaries, rootStates);
            }
            IList <PerceptronModel.Update>           updates = Generics.NewArrayList();
            MulticoreWrapper <int, Pair <int, int> > wrapper = null;

            if (nThreads != 1)
            {
                updates = Java.Util.Collections.SynchronizedList(updates);
                wrapper = new MulticoreWrapper <int, Pair <int, int> >(op.trainOptions.trainingThreads, new PerceptronModel.TrainTreeProcessor(this, binarizedTrees, transitionLists, updates, oracle));
            }
            IntCounter <string> featureFrequencies = null;

            if (op.TrainOptions().featureFrequencyCutoff > 1)
            {
                featureFrequencies = new IntCounter <string>();
            }
            for (int iteration = 1; iteration <= op.trainOptions.trainingIterations; ++iteration)
            {
                Timing trainingTimer = new Timing();
                int    numCorrect    = 0;
                int    numWrong      = 0;
                Java.Util.Collections.Shuffle(indices, random);
                for (int start = 0; start < indices.Count; start += op.trainOptions.batchSize)
                {
                    int end = Math.Min(start + op.trainOptions.batchSize, indices.Count);
                    Triple <IList <PerceptronModel.Update>, int, int> result = TrainBatch(indices.SubList(start, end), binarizedTrees, transitionLists, updates, oracle, wrapper);
                    numCorrect += result.second;
                    numWrong   += result.third;
                    foreach (PerceptronModel.Update update in result.first)
                    {
                        foreach (string feature in update.features)
                        {
                            if (allowedFeatures != null && !allowedFeatures.Contains(feature))
                            {
                                continue;
                            }
                            Weight weights = featureWeights[feature];
                            if (weights == null)
                            {
                                weights = new Weight();
                                featureWeights[feature] = weights;
                            }
                            weights.UpdateWeight(update.goldTransition, update.delta);
                            weights.UpdateWeight(update.predictedTransition, -update.delta);
                            if (featureFrequencies != null)
                            {
                                featureFrequencies.IncrementCount(feature, (update.goldTransition >= 0 && update.predictedTransition >= 0) ? 2 : 1);
                            }
                        }
                    }
                    updates.Clear();
                }
                trainingTimer.Done("Iteration " + iteration);
                log.Info("While training, got " + numCorrect + " transitions correct and " + numWrong + " transitions wrong");
                OutputStats();
                double labelF1 = 0.0;
                if (devTreebank != null)
                {
                    EvaluateTreebank evaluator = new EvaluateTreebank(op, null, new ShiftReduceParser(op, this), tagger);
                    evaluator.TestOnTreebank(devTreebank);
                    labelF1 = evaluator.GetLBScore();
                    log.Info("Label F1 after " + iteration + " iterations: " + labelF1);
                    if (labelF1 > bestScore)
                    {
                        log.Info("New best dev score (previous best " + bestScore + ")");
                        bestScore     = labelF1;
                        bestIteration = iteration;
                    }
                    else
                    {
                        log.Info("Failed to improve for " + (iteration - bestIteration) + " iteration(s) on previous best score of " + bestScore);
                        if (op.trainOptions.stalledIterationLimit > 0 && (iteration - bestIteration >= op.trainOptions.stalledIterationLimit))
                        {
                            log.Info("Failed to improve for too long, stopping training");
                            break;
                        }
                    }
                    log.Info();
                    if (bestModels != null)
                    {
                        bestModels.Add(new ScoredObject <PerceptronModel>(new PerceptronModel(this), labelF1));
                        if (bestModels.Count > op.TrainOptions().averagedModels)
                        {
                            bestModels.Poll();
                        }
                    }
                }
                if (op.TrainOptions().saveIntermediateModels&& serializedPath != null && op.trainOptions.debugOutputFrequency > 0)
                {
                    string            tempName = Sharpen.Runtime.Substring(serializedPath, 0, serializedPath.Length - 7) + "-" + Filename.Format(iteration) + "-" + Nf.Format(labelF1) + ".ser.gz";
                    ShiftReduceParser temp     = new ShiftReduceParser(op, this);
                    temp.SaveModel(tempName);
                }
                // TODO: we could save a cutoff version of the model,
                // especially if we also get a dev set number for it, but that
                // might be overkill
                if (iteration % 10 == 0 && op.TrainOptions().decayLearningRate > 0.0)
                {
                    learningRate *= op.TrainOptions().decayLearningRate;
                }
            }
            // end for iterations
            if (wrapper != null)
            {
                wrapper.Join();
            }
            if (bestModels != null)
            {
                if (op.TrainOptions().cvAveragedModels&& devTreebank != null)
                {
                    IList <ScoredObject <PerceptronModel> > models = Generics.NewArrayList();
                    while (bestModels.Count > 0)
                    {
                        models.Add(bestModels.Poll());
                    }
                    Java.Util.Collections.Reverse(models);
                    double bestF1   = 0.0;
                    int    bestSize = 0;
                    for (int i_1 = 1; i_1 <= models.Count; ++i_1)
                    {
                        log.Info("Testing with " + i_1 + " models averaged together");
                        // TODO: this is kind of ugly, would prefer a separate object
                        AverageScoredModels(models.SubList(0, i_1));
                        ShiftReduceParser temp      = new ShiftReduceParser(op, this);
                        EvaluateTreebank  evaluator = new EvaluateTreebank(temp.GetOp(), null, temp, tagger);
                        evaluator.TestOnTreebank(devTreebank);
                        double labelF1 = evaluator.GetLBScore();
                        log.Info("Label F1 for " + i_1 + " models: " + labelF1);
                        if (labelF1 > bestF1)
                        {
                            bestF1   = labelF1;
                            bestSize = i_1;
                        }
                    }
                    AverageScoredModels(models.SubList(0, bestSize));
                }
                else
                {
                    AverageScoredModels(bestModels);
                }
            }
            // TODO: perhaps we should filter the features and then get dev
            // set scores.  That way we can merge the models which are best
            // after filtering.
            if (featureFrequencies != null)
            {
                FilterFeatures(featureFrequencies.KeysAbove(op.TrainOptions().featureFrequencyCutoff));
            }
            CondenseFeatures();
        }
Exemple #25
0
        private void Initialize()
        {
            #region Create parameters
            Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
            Parameters.Add(new ScopeTreeLookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Selector", "The operator used to select solutions for reproduction."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Crossover", "The operator used to cross solutions."));
            Parameters.Add(new ValueLookupParameter <PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Mutator", "The operator used to mutate solutions."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Evaluator", "The operator used to evaluate solutions. This operator is executed in parallel, if an engine is used which supports parallelization."));
            Parameters.Add(new ValueLookupParameter <IntValue>("Elites", "The numer of elite solutions which are kept in each generation."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)"));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumGenerations", "The maximum number of generations which should be processed."));
            Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to analyze each generation."));
            Parameters.Add(new ValueLookupParameter <IntValue>("EvaluatedSolutions", "The number of times solutions have been evaluated."));
            Parameters.Add(new ValueLookupParameter <IntValue>("PopulationSize", "The size of the population."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MinimumPopulationSize", "The minimum size of the population of solutions."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumPopulationSize", "The maximum size of the population of solutions."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("ComparisonFactor", "The comparison factor."));
            Parameters.Add(new ValueLookupParameter <IntValue>("Effort", "The maximum number of offspring created in each generation."));
            Parameters.Add(new ValueLookupParameter <IntValue>("BatchSize", "The number of children that should be created during one iteration of the offspring creation process."));
            Parameters.Add(new ValueLookupParameter <ISolutionSimilarityCalculator>("SimilarityCalculator", "The operator used to calculate the similarity between two solutions."));
            Parameters.Add(new ScopeParameter("CurrentScope", "The current scope which represents a population of solutions on which the genetic algorithm should be applied."));
            #endregion

            #region Create operators
            VariableCreator                  variableCreator           = new VariableCreator();
            Assigner                         assigner1                 = new Assigner();
            ResultsCollector                 resultsCollector          = new ResultsCollector();
            Placeholder                      analyzer1                 = new Placeholder();
            Placeholder                      selector                  = new Placeholder();
            SubScopesProcessor               subScopesProcessor1       = new SubScopesProcessor();
            ChildrenCreator                  childrenCreator           = new ChildrenCreator();
            UniformSubScopesProcessor        uniformSubScopesProcessor = new UniformSubScopesProcessor();
            Placeholder                      crossover                 = new Placeholder();
            StochasticBranch                 stochasticBranch          = new StochasticBranch();
            Placeholder                      mutator   = new Placeholder();
            Placeholder                      evaluator = new Placeholder();
            WeightedParentsQualityComparator weightedParentsQualityComparator = new WeightedParentsQualityComparator();
            SubScopesRemover                 subScopesRemover             = new SubScopesRemover();
            IntCounter                       intCounter1                  = new IntCounter();
            IntCounter                       intCounter2                  = new IntCounter();
            ConditionalSelector              conditionalSelector          = new ConditionalSelector();
            RightReducer                     rightReducer1                = new RightReducer();
            DuplicatesSelector               duplicateSelector            = new DuplicatesSelector();
            LeftReducer                      leftReducer1                 = new LeftReducer();
            ProgressiveOffspringPreserver    progressiveOffspringSelector = new ProgressiveOffspringPreserver();
            SubScopesCounter                 subScopesCounter2            = new SubScopesCounter();
            ExpressionCalculator             calculator1                  = new ExpressionCalculator();
            ConditionalBranch                conditionalBranch1           = new ConditionalBranch();
            Comparator                       comparator1                  = new Comparator();
            ConditionalBranch                conditionalBranch2           = new ConditionalBranch();
            LeftReducer                      leftReducer2                 = new LeftReducer();
            SubScopesProcessor               subScopesProcessor2          = new SubScopesProcessor();
            BestSelector                     bestSelector                 = new BestSelector();
            RightReducer                     rightReducer2                = new RightReducer();
            ScopeCleaner                     scopeCleaner                 = new ScopeCleaner();
            ScopeRestorer                    scopeRestorer                = new ScopeRestorer();
            MergingReducer                   mergingReducer               = new MergingReducer();
            IntCounter                       intCounter3                  = new IntCounter();
            SubScopesCounter                 subScopesCounter3            = new SubScopesCounter();
            ExpressionCalculator             calculator2                  = new ExpressionCalculator();
            Comparator                       comparator2                  = new Comparator();
            ConditionalBranch                conditionalBranch3           = new ConditionalBranch();
            Placeholder                      analyzer2                  = new Placeholder();
            Comparator                       comparator3                = new Comparator();
            ConditionalBranch                conditionalBranch4         = new ConditionalBranch();
            Comparator                       comparator4                = new Comparator();
            ConditionalBranch                conditionalBranch5         = new ConditionalBranch();
            Assigner                         assigner3                  = new Assigner();
            Assigner                         assigner4                  = new Assigner();
            Assigner                         assigner5                  = new Assigner();
            ConditionalBranch                reevaluateElitesBranch     = new ConditionalBranch();
            UniformSubScopesProcessor        uniformSubScopesProcessor2 = new UniformSubScopesProcessor();
            Placeholder                      evaluator2                 = new Placeholder();
            SubScopesCounter                 subScopesCounter4          = new SubScopesCounter();

            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Generations", new IntValue(0))); // Class RAPGA expects this to be called Generations
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("CurrentPopulationSize", new IntValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("NumberOfCreatedOffspring", new IntValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("NumberOfSuccessfulOffspring", new IntValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <ScopeList>("OffspringList", new ScopeList()));

            assigner1.Name = "Initialize CurrentPopulationSize";
            assigner1.LeftSideParameter.ActualName  = "CurrentPopulationSize";
            assigner1.RightSideParameter.ActualName = PopulationSizeParameter.Name;

            resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("Generations"));
            resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("CurrentPopulationSize"));
            resultsCollector.ResultsParameter.ActualName = "Results";

            analyzer1.Name = "Analyzer";
            analyzer1.OperatorParameter.ActualName = "Analyzer";

            selector.Name = "Selector";
            selector.OperatorParameter.ActualName = "Selector";

            childrenCreator.ParentsPerChild = new IntValue(2);

            uniformSubScopesProcessor.Parallel.Value = true;

            crossover.Name = "Crossover";
            crossover.OperatorParameter.ActualName = "Crossover";

            stochasticBranch.ProbabilityParameter.ActualName = "MutationProbability";
            stochasticBranch.RandomParameter.ActualName      = "Random";

            mutator.Name = "Mutator";
            mutator.OperatorParameter.ActualName = "Mutator";

            evaluator.Name = "Evaluator";
            evaluator.OperatorParameter.ActualName = "Evaluator";

            weightedParentsQualityComparator.ComparisonFactorParameter.ActualName = ComparisonFactorParameter.Name;
            weightedParentsQualityComparator.LeftSideParameter.ActualName         = QualityParameter.Name;
            weightedParentsQualityComparator.MaximizationParameter.ActualName     = MaximizationParameter.Name;
            weightedParentsQualityComparator.RightSideParameter.ActualName        = QualityParameter.Name;
            weightedParentsQualityComparator.ResultParameter.ActualName           = "SuccessfulOffspring";

            subScopesRemover.RemoveAllSubScopes = true;

            intCounter1.Name = "Increment NumberOfCreatedOffspring";
            intCounter1.ValueParameter.ActualName = "NumberOfCreatedOffspring";
            intCounter1.Increment = null;
            intCounter1.IncrementParameter.ActualName = BatchSizeParameter.Name;

            intCounter2.Name = "Increment EvaluatedSolutions";
            intCounter2.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name;
            intCounter2.Increment = null;
            intCounter2.IncrementParameter.ActualName = BatchSizeParameter.Name;

            conditionalSelector.ConditionParameter.ActualName = "SuccessfulOffspring";
            conditionalSelector.ConditionParameter.Depth      = 1;
            conditionalSelector.CopySelected.Value            = false;

            duplicateSelector.CopySelected.Value = false;

            progressiveOffspringSelector.OffspringListParameter.ActualName         = "OffspringList";
            progressiveOffspringSelector.ElitesParameter.ActualName                = ElitesParameter.Name;
            progressiveOffspringSelector.MaximumPopulationSizeParameter.ActualName = MaximumPopulationSizeParameter.Name;

            subScopesCounter2.Name = "Count Successful Offspring";
            subScopesCounter2.ValueParameter.ActualName = "NumberOfSuccessfulOffspring";

            calculator1.Name = "NumberOfSuccessfulOffspring == MaximumPopulationSize - Elites";
            calculator1.CollectedValues.Add(new ValueLookupParameter <IntValue>("NumberOfSuccessfulOffspring"));
            calculator1.CollectedValues.Add(new ValueLookupParameter <IntValue>("MaximumPopulationSize"));
            calculator1.CollectedValues.Add(new ValueLookupParameter <IntValue>("Elites"));
            calculator1.ExpressionParameter.Value            = new StringValue("NumberOfSuccessfulOffspring MaximumPopulationSize Elites - ==");
            calculator1.ExpressionResultParameter.ActualName = "Break";

            conditionalBranch1.Name = "Break?";
            conditionalBranch1.ConditionParameter.ActualName = "Break";

            comparator1.Name       = "NumberOfCreatedOffspring >= Effort";
            comparator1.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            comparator1.LeftSideParameter.ActualName  = "NumberOfCreatedOffspring";
            comparator1.RightSideParameter.ActualName = EffortParameter.Name;
            comparator1.ResultParameter.ActualName    = "Break";

            conditionalBranch2.Name = "Break?";
            conditionalBranch2.ConditionParameter.ActualName = "Break";

            bestSelector.CopySelected = new BoolValue(false);
            bestSelector.MaximizationParameter.ActualName = MaximizationParameter.Name;
            bestSelector.NumberOfSelectedSubScopesParameter.ActualName = "Elites";
            bestSelector.QualityParameter.ActualName = QualityParameter.Name;

            intCounter3.Name      = "Increment Generations";
            intCounter3.Increment = new IntValue(1);
            intCounter3.ValueParameter.ActualName = "Generations";

            subScopesCounter3.Name = "Update CurrentPopulationSize";
            subScopesCounter3.ValueParameter.ActualName = "CurrentPopulationSize";
            subScopesCounter3.AccumulateParameter.Value = new BoolValue(false);

            calculator2.Name = "Evaluate ActualSelectionPressure";
            calculator2.CollectedValues.Add(new ValueLookupParameter <IntValue>("NumberOfCreatedOffspring"));
            calculator2.CollectedValues.Add(new ValueLookupParameter <IntValue>("Elites"));
            calculator2.CollectedValues.Add(new ValueLookupParameter <IntValue>("CurrentPopulationSize"));
            calculator2.ExpressionParameter.Value            = new StringValue("NumberOfCreatedOffspring Elites + CurrentPopulationSize /");
            calculator2.ExpressionResultParameter.ActualName = "ActualSelectionPressure";

            comparator2.Name       = "CurrentPopulationSize < 1";
            comparator2.Comparison = new Comparison(ComparisonType.Less);
            comparator2.LeftSideParameter.ActualName = "CurrentPopulationSize";
            comparator2.RightSideParameter.Value     = new IntValue(1);
            comparator2.ResultParameter.ActualName   = "Terminate";

            conditionalBranch3.Name = "Terminate?";
            conditionalBranch3.ConditionParameter.ActualName = "Terminate";

            analyzer2.Name = "Analyzer";
            analyzer2.OperatorParameter.ActualName = "Analyzer";

            comparator3.Name       = "Generations >= MaximumGenerations";
            comparator3.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            comparator3.LeftSideParameter.ActualName  = "Generations";
            comparator3.ResultParameter.ActualName    = "Terminate";
            comparator3.RightSideParameter.ActualName = MaximumGenerationsParameter.Name;

            conditionalBranch4.Name = "Terminate?";
            conditionalBranch4.ConditionParameter.ActualName = "Terminate";

            comparator4.Name       = "CurrentPopulationSize < MinimumPopulationSize";
            comparator4.Comparison = new Comparison(ComparisonType.Less);
            comparator4.LeftSideParameter.ActualName  = "CurrentPopulationSize";
            comparator4.RightSideParameter.ActualName = MinimumPopulationSizeParameter.Name;
            comparator4.ResultParameter.ActualName    = "Terminate";

            conditionalBranch5.Name = "Terminate?";
            conditionalBranch5.ConditionParameter.ActualName = "Terminate";

            assigner3.Name = "Reset NumberOfCreatedOffspring";
            assigner3.LeftSideParameter.ActualName = "NumberOfCreatedOffspring";
            assigner3.RightSideParameter.Value     = new IntValue(0);

            assigner4.Name = "Reset NumberOfSuccessfulOffspring";
            assigner4.LeftSideParameter.ActualName = "NumberOfSuccessfulOffspring";
            assigner4.RightSideParameter.Value     = new IntValue(0);

            assigner5.Name = "Reset OffspringList";
            assigner5.LeftSideParameter.ActualName = "OffspringList";
            assigner5.RightSideParameter.Value     = new ScopeList();

            reevaluateElitesBranch.ConditionParameter.ActualName = "ReevaluateElites";
            reevaluateElitesBranch.Name = "Reevaluate elites ?";

            uniformSubScopesProcessor2.Parallel.Value = true;

            evaluator2.Name = "Evaluator (placeholder)";
            evaluator2.OperatorParameter.ActualName = EvaluatorParameter.Name;

            subScopesCounter4.Name = "Increment EvaluatedSolutions";
            subScopesCounter4.ValueParameter.ActualName = EvaluatedSolutionsParameter.Name;
            #endregion

            #region Create operator graph
            OperatorGraph.InitialOperator = variableCreator;
            variableCreator.Successor     = assigner1;
            assigner1.Successor           = resultsCollector;
            resultsCollector.Successor    = analyzer1;
            analyzer1.Successor           = selector;
            selector.Successor            = subScopesProcessor1;
            subScopesProcessor1.Operators.Add(new EmptyOperator());
            subScopesProcessor1.Operators.Add(childrenCreator);
            subScopesProcessor1.Successor       = calculator1;
            childrenCreator.Successor           = uniformSubScopesProcessor;
            uniformSubScopesProcessor.Operator  = crossover;
            uniformSubScopesProcessor.Successor = intCounter1;
            crossover.Successor           = stochasticBranch;
            stochasticBranch.FirstBranch  = mutator;
            stochasticBranch.SecondBranch = null;
            mutator.Successor             = null;
            stochasticBranch.Successor    = evaluator;
            evaluator.Successor           = weightedParentsQualityComparator;
            weightedParentsQualityComparator.Successor = subScopesRemover;
            intCounter1.Successor                  = intCounter2;
            intCounter2.Successor                  = conditionalSelector;
            conditionalSelector.Successor          = rightReducer1;
            rightReducer1.Successor                = duplicateSelector;
            duplicateSelector.Successor            = leftReducer1;
            leftReducer1.Successor                 = progressiveOffspringSelector;
            progressiveOffspringSelector.Successor = subScopesCounter2;
            calculator1.Successor                  = conditionalBranch1;
            conditionalBranch1.FalseBranch         = comparator1;
            conditionalBranch1.TrueBranch          = subScopesProcessor2;
            comparator1.Successor                  = conditionalBranch2;
            conditionalBranch2.FalseBranch         = leftReducer2;
            conditionalBranch2.TrueBranch          = subScopesProcessor2;
            leftReducer2.Successor                 = selector;
            subScopesProcessor2.Operators.Add(bestSelector);
            subScopesProcessor2.Operators.Add(scopeCleaner);
            subScopesProcessor2.Successor        = mergingReducer;
            bestSelector.Successor               = rightReducer2;
            rightReducer2.Successor              = reevaluateElitesBranch;
            reevaluateElitesBranch.TrueBranch    = uniformSubScopesProcessor2;
            uniformSubScopesProcessor2.Operator  = evaluator2;
            uniformSubScopesProcessor2.Successor = subScopesCounter4;
            evaluator2.Successor               = null;
            subScopesCounter4.Successor        = null;
            reevaluateElitesBranch.FalseBranch = null;
            reevaluateElitesBranch.Successor   = null;
            scopeCleaner.Successor             = scopeRestorer;
            mergingReducer.Successor           = intCounter3;
            intCounter3.Successor              = subScopesCounter3;
            subScopesCounter3.Successor        = calculator2;
            calculator2.Successor              = comparator2;
            comparator2.Successor              = conditionalBranch3;
            conditionalBranch3.FalseBranch     = analyzer2;
            conditionalBranch3.TrueBranch      = null;
            analyzer2.Successor            = comparator3;
            comparator3.Successor          = conditionalBranch4;
            conditionalBranch4.FalseBranch = comparator4;
            conditionalBranch4.TrueBranch  = null;
            conditionalBranch4.Successor   = null;
            comparator4.Successor          = conditionalBranch5;
            conditionalBranch5.FalseBranch = assigner3;
            conditionalBranch5.TrueBranch  = null;
            conditionalBranch5.Successor   = null;
            assigner3.Successor            = assigner4;
            assigner4.Successor            = assigner5;
            assigner5.Successor            = selector;

            #endregion
        }
Exemple #26
0
 public LocalIntCounter(IntCounter globalCounter)
 {
     this._global = globalCounter;
 }
        public IslandGeneticAlgorithmMainLoop()
            : base()
        {
            #region Create parameters
            Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
            Parameters.Add(new ScopeTreeLookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far."));
            Parameters.Add(new ValueLookupParameter <IntValue>("NumberOfIslands", "The number of islands."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MigrationInterval", "The number of generations that should pass between migration phases."));
            Parameters.Add(new ValueLookupParameter <PercentValue>("MigrationRate", "The proportion of individuals that should migrate between the islands."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Migrator", "The migration strategy."));
            Parameters.Add(new ValueLookupParameter <IOperator>("EmigrantsSelector", "Selects the individuals that will be migrated."));
            Parameters.Add(new ValueLookupParameter <IOperator>("ImmigrationReplacer", "Replaces some of the original population with the immigrants."));
            Parameters.Add(new ValueLookupParameter <IntValue>("PopulationSize", "The size of the population of solutions."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumGenerations", "The maximum number of generations that the algorithm should process."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Selector", "The operator used to select solutions for reproduction."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Crossover", "The operator used to cross solutions."));
            Parameters.Add(new ValueLookupParameter <PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Mutator", "The operator used to mutate solutions."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Evaluator", "The operator used to evaluate solutions."));
            Parameters.Add(new ValueLookupParameter <IntValue>("Elites", "The numer of elite solutions which are kept in each generation."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)"));
            Parameters.Add(new ValueLookupParameter <ResultCollection>("Results", "The results collection to store the results."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to the analyze the islands."));
            Parameters.Add(new ValueLookupParameter <IOperator>("IslandAnalyzer", "The operator used to analyze each island."));
            Parameters.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "The number of times a solution has been evaluated."));
            Parameters.Add(new LookupParameter <IntValue>("IslandGenerations", "The number of generations calculated on one island."));
            Parameters.Add(new LookupParameter <IntValue>("IslandEvaluatedSolutions", "The number of times a solution has been evaluated on one island."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("Migrate", "Migrate the island?"));
            #endregion

            #region Create operators
            VariableCreator           variableCreator            = new VariableCreator();
            UniformSubScopesProcessor uniformSubScopesProcessor0 = new UniformSubScopesProcessor();
            VariableCreator           islandVariableCreator      = new VariableCreator();
            Placeholder               islandAnalyzer1            = new Placeholder();
            LocalRandomCreator        localRandomCreator         = new LocalRandomCreator();
            Placeholder               analyzer1                  = new Placeholder();
            ResultsCollector          resultsCollector1          = new ResultsCollector();
            UniformSubScopesProcessor uniformSubScopesProcessor1 = new UniformSubScopesProcessor();
            Assigner                  generationsAssigner        = new Assigner();
            Assigner                  evaluatedSolutionsAssigner = new Assigner();
            Placeholder               selector                   = new Placeholder();
            SubScopesProcessor        subScopesProcessor1        = new SubScopesProcessor();
            ChildrenCreator           childrenCreator            = new ChildrenCreator();
            UniformSubScopesProcessor uniformSubScopesProcessor2 = new UniformSubScopesProcessor();
            Placeholder               crossover                  = new Placeholder();
            StochasticBranch          stochasticBranch           = new StochasticBranch();
            Placeholder               mutator                              = new Placeholder();
            SubScopesRemover          subScopesRemover                     = new SubScopesRemover();
            UniformSubScopesProcessor uniformSubScopesProcessor3           = new UniformSubScopesProcessor();
            Placeholder               evaluator                            = new Placeholder();
            SubScopesCounter          subScopesCounter                     = new SubScopesCounter();
            SubScopesProcessor        subScopesProcessor2                  = new SubScopesProcessor();
            BestSelector              bestSelector                         = new BestSelector();
            RightReducer              rightReducer                         = new RightReducer();
            MergingReducer            mergingReducer                       = new MergingReducer();
            IntCounter                islandGenerationsCounter             = new IntCounter();
            Comparator                checkIslandGenerationsReachedMaximum = new Comparator();
            ConditionalBranch         checkContinueEvolution               = new ConditionalBranch();
            DataReducer               generationsReducer                   = new DataReducer();
            DataReducer               evaluatedSolutionsReducer            = new DataReducer();
            Placeholder               islandAnalyzer2                      = new Placeholder();
            UniformSubScopesProcessor uniformSubScopesProcessor5           = new UniformSubScopesProcessor();
            Placeholder               emigrantsSelector                    = new Placeholder();
            IntCounter                migrationsCounter                    = new IntCounter();
            Placeholder               migrator                             = new Placeholder();
            UniformSubScopesProcessor uniformSubScopesProcessor6           = new UniformSubScopesProcessor();
            Placeholder               immigrationReplacer                  = new Placeholder();
            Comparator                generationsComparator                = new Comparator();
            Placeholder               analyzer2                            = new Placeholder();
            ConditionalBranch         generationsTerminationCondition      = new ConditionalBranch();
            ConditionalBranch         reevaluateElitesBranch               = new ConditionalBranch();


            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Migrations", new IntValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("GenerationsSinceLastMigration", new IntValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Generations", new IntValue(0))); // Class IslandGeneticAlgorithm expects this to be called Generations

            islandVariableCreator.CollectedValues.Add(new ValueParameter <ResultCollection>("Results", new ResultCollection()));
            islandVariableCreator.CollectedValues.Add(new ValueParameter <IntValue>("IslandGenerations", new IntValue(0)));
            islandVariableCreator.CollectedValues.Add(new ValueParameter <IntValue>("IslandEvaluatedSolutions", new IntValue(0)));

            islandAnalyzer1.Name = "Island Analyzer (placeholder)";
            islandAnalyzer1.OperatorParameter.ActualName = IslandAnalyzerParameter.Name;

            analyzer1.Name = "Analyzer (placeholder)";
            analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name;

            resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>("Migrations"));
            resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>("Generations"));
            resultsCollector1.CollectedValues.Add(new ScopeTreeLookupParameter <ResultCollection>("IslandResults", "Result set for each island", "Results"));
            resultsCollector1.ResultsParameter.ActualName = ResultsParameter.Name;

            uniformSubScopesProcessor1.Parallel.Value = true;

            generationsAssigner.Name = "Initialize Island Generations";
            generationsAssigner.LeftSideParameter.ActualName = IslandGenerations.Name;
            generationsAssigner.RightSideParameter.Value     = new IntValue(0);

            evaluatedSolutionsAssigner.Name = "Initialize Island evaluated solutions";
            evaluatedSolutionsAssigner.LeftSideParameter.ActualName = IslandEvaluatedSolutions.Name;
            evaluatedSolutionsAssigner.RightSideParameter.Value     = new IntValue(0);

            selector.Name = "Selector (placeholder)";
            selector.OperatorParameter.ActualName = SelectorParameter.Name;

            childrenCreator.ParentsPerChild = new IntValue(2);

            crossover.Name = "Crossover (placeholder)";
            crossover.OperatorParameter.ActualName = CrossoverParameter.Name;

            stochasticBranch.ProbabilityParameter.ActualName = MutationProbabilityParameter.Name;
            //set it to the random number generator of the island
            stochasticBranch.RandomParameter.ActualName = "LocalRandom";

            mutator.Name = "Mutator (placeholder)";
            mutator.OperatorParameter.ActualName = MutatorParameter.Name;

            subScopesRemover.RemoveAllSubScopes = true;

            evaluator.Name = "Evaluator (placeholder)";
            evaluator.OperatorParameter.ActualName = EvaluatorParameter.Name;

            subScopesCounter.Name = "Increment EvaluatedSolutions";
            subScopesCounter.ValueParameter.ActualName = IslandEvaluatedSolutions.Name;

            bestSelector.CopySelected = new BoolValue(false);
            bestSelector.MaximizationParameter.ActualName = MaximizationParameter.Name;
            bestSelector.NumberOfSelectedSubScopesParameter.ActualName = ElitesParameter.Name;
            bestSelector.QualityParameter.ActualName = QualityParameter.Name;

            islandGenerationsCounter.Name = "Increment island generatrions";
            islandGenerationsCounter.ValueParameter.ActualName = IslandGenerations.Name;
            islandGenerationsCounter.Increment = new IntValue(1);

            checkIslandGenerationsReachedMaximum.LeftSideParameter.ActualName  = IslandGenerations.Name;
            checkIslandGenerationsReachedMaximum.RightSideParameter.ActualName = MigrationIntervalParameter.Name;
            checkIslandGenerationsReachedMaximum.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            checkIslandGenerationsReachedMaximum.ResultParameter.ActualName = Migrate.Name;

            checkContinueEvolution.Name = "Migrate?";
            checkContinueEvolution.ConditionParameter.ActualName = Migrate.Name;
            checkContinueEvolution.FalseBranch = selector;

            islandAnalyzer2.Name = "Island Analyzer (placeholder)";
            islandAnalyzer2.OperatorParameter.ActualName = IslandAnalyzerParameter.Name;

            generationsReducer.Name = "Increment Generations";
            generationsReducer.ParameterToReduce.ActualName = islandGenerationsCounter.ValueParameter.ActualName;
            generationsReducer.TargetParameter.ActualName   = "Generations";
            generationsReducer.ReductionOperation.Value     = new ReductionOperation(ReductionOperations.Min);
            generationsReducer.TargetOperation.Value        = new ReductionOperation(ReductionOperations.Sum);

            evaluatedSolutionsReducer.Name = "Increment Evaluated Solutions";
            evaluatedSolutionsReducer.ParameterToReduce.ActualName = IslandEvaluatedSolutions.Name;
            evaluatedSolutionsReducer.TargetParameter.ActualName   = EvaluatedSolutionsParameter.Name;
            evaluatedSolutionsReducer.ReductionOperation.Value     = new ReductionOperation(ReductionOperations.Sum);
            evaluatedSolutionsReducer.TargetOperation.Value        = new ReductionOperation(ReductionOperations.Sum);

            emigrantsSelector.Name = "Emigrants Selector (placeholder)";
            emigrantsSelector.OperatorParameter.ActualName = EmigrantsSelectorParameter.Name;

            migrationsCounter.Name = "Increment number of Migrations";
            migrationsCounter.ValueParameter.ActualName = "Migrations";
            migrationsCounter.Increment = new IntValue(1);

            migrator.Name = "Migrator (placeholder)";
            migrator.OperatorParameter.ActualName = MigratorParameter.Name;

            immigrationReplacer.Name = "Immigration Replacer (placeholder)";
            immigrationReplacer.OperatorParameter.ActualName = ImmigrationReplacerParameter.Name;

            generationsComparator.Name       = "Generations >= MaximumGenerations ?";
            generationsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            generationsComparator.LeftSideParameter.ActualName  = "Generations";
            generationsComparator.ResultParameter.ActualName    = "TerminateGenerations";
            generationsComparator.RightSideParameter.ActualName = MaximumGenerationsParameter.Name;

            analyzer2.Name = "Analyzer (placeholder)";
            analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name;

            generationsTerminationCondition.Name = "Terminate?";
            generationsTerminationCondition.ConditionParameter.ActualName = "TerminateGenerations";

            reevaluateElitesBranch.ConditionParameter.ActualName = "ReevaluateElites";
            reevaluateElitesBranch.Name = "Reevaluate elites ?";
            #endregion

            #region Create operator graph
            OperatorGraph.InitialOperator        = variableCreator;
            variableCreator.Successor            = uniformSubScopesProcessor0;
            uniformSubScopesProcessor0.Operator  = islandVariableCreator;
            uniformSubScopesProcessor0.Successor = analyzer1;
            islandVariableCreator.Successor      = islandAnalyzer1;
            // BackwardsCompatibility3.3
            //the local randoms are created by the island GA itself and are only here to ensure same algorithm results
            #region Backwards compatible code, remove local random creator with 3.4 and rewire the operator graph
            islandAnalyzer1.Successor    = localRandomCreator;
            localRandomCreator.Successor = null;
            #endregion
            analyzer1.Successor                  = resultsCollector1;
            resultsCollector1.Successor          = uniformSubScopesProcessor1;
            uniformSubScopesProcessor1.Operator  = generationsAssigner;
            uniformSubScopesProcessor1.Successor = generationsReducer;
            generationsReducer.Successor         = evaluatedSolutionsReducer;
            evaluatedSolutionsReducer.Successor  = migrationsCounter;
            migrationsCounter.Successor          = uniformSubScopesProcessor5;
            generationsAssigner.Successor        = evaluatedSolutionsAssigner;
            evaluatedSolutionsAssigner.Successor = selector;
            selector.Successor = subScopesProcessor1;
            subScopesProcessor1.Operators.Add(new EmptyOperator());
            subScopesProcessor1.Operators.Add(childrenCreator);
            subScopesProcessor1.Successor        = subScopesProcessor2;
            childrenCreator.Successor            = uniformSubScopesProcessor2;
            uniformSubScopesProcessor2.Operator  = crossover;
            uniformSubScopesProcessor2.Successor = uniformSubScopesProcessor3;
            crossover.Successor                  = stochasticBranch;
            stochasticBranch.FirstBranch         = mutator;
            stochasticBranch.SecondBranch        = null;
            stochasticBranch.Successor           = subScopesRemover;
            mutator.Successor                    = null;
            subScopesRemover.Successor           = null;
            uniformSubScopesProcessor3.Operator  = evaluator;
            uniformSubScopesProcessor3.Successor = subScopesCounter;
            evaluator.Successor                  = null;
            subScopesCounter.Successor           = null;
            subScopesProcessor2.Operators.Add(bestSelector);
            subScopesProcessor2.Operators.Add(new EmptyOperator());
            subScopesProcessor2.Successor                  = mergingReducer;
            mergingReducer.Successor                       = islandAnalyzer2;
            bestSelector.Successor                         = rightReducer;
            rightReducer.Successor                         = reevaluateElitesBranch;
            reevaluateElitesBranch.TrueBranch              = uniformSubScopesProcessor3;
            reevaluateElitesBranch.FalseBranch             = null;
            reevaluateElitesBranch.Successor               = null;
            islandAnalyzer2.Successor                      = islandGenerationsCounter;
            islandGenerationsCounter.Successor             = checkIslandGenerationsReachedMaximum;
            checkIslandGenerationsReachedMaximum.Successor = checkContinueEvolution;
            uniformSubScopesProcessor5.Operator            = emigrantsSelector;
            emigrantsSelector.Successor                    = null;
            uniformSubScopesProcessor5.Successor           = migrator;
            migrator.Successor = uniformSubScopesProcessor6;
            uniformSubScopesProcessor6.Operator  = immigrationReplacer;
            uniformSubScopesProcessor6.Successor = generationsComparator;
            generationsComparator.Successor      = analyzer2;
            analyzer2.Successor = generationsTerminationCondition;
            generationsTerminationCondition.TrueBranch  = null;
            generationsTerminationCondition.FalseBranch = uniformSubScopesProcessor1;
            generationsTerminationCondition.Successor   = null;
            #endregion
        }
        private void Initialize()
        {
            #region Create parameters
            Parameters.Add(new ValueLookupParameter <IMultiAnalyzer>("Analyzer", "The analyzer used to analyze each iteration."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far."));
            Parameters.Add(new ValueLookupParameter <ICrossover>("Crossover", "The operator used to cross solutions."));
            Parameters.Add(new ValueLookupParameter <IntValue>("EvaluatedSolutions", "The number of times solutions have been evaluated."));
            Parameters.Add(new ValueLookupParameter <IEvaluator>("Evaluator", "The operator used to evaluate solutions. This operator is executed in parallel, if an engine is used which supports parallelization."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("ExecutePathRelinking", "True if path relinking should be executed instead of crossover, otherwise false."));
            Parameters.Add(new ValueLookupParameter <IImprovementOperator>("Improver", "The operator used to improve solutions."));
            Parameters.Add(new ValueLookupParameter <IntValue>("Iterations", "The number of iterations performed."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumIterations", "The maximum number of iterations which should be processed."));
            Parameters.Add(new ValueLookupParameter <IntValue>("NumberOfHighQualitySolutions", "The number of high quality solutions in the reference set."));
            Parameters.Add(new ValueLookupParameter <IPathRelinker>("PathRelinker", "The operator used to execute path relinking."));
            Parameters.Add(new ValueLookupParameter <IntValue>("PopulationSize", "The size of the population of solutions."));
            Parameters.Add(new ValueLookupParameter <IntValue>("ReferenceSetSize", "The size of the reference set."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("Quality", "This parameter is used for name translation only."));
            Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator."));
            Parameters.Add(new ValueLookupParameter <VariableCollection>("Results", "The variable collection where results should be stored."));
            Parameters.Add(new ValueLookupParameter <ISolutionSimilarityCalculator>("SimilarityCalculator", "The operator used to calculate the similarity between two solutions."));
            #endregion

            #region Create operators
            Placeholder               analyzer                   = new Placeholder();
            Assigner                  assigner1                  = new Assigner();
            Assigner                  assigner2                  = new Assigner();
            ChildrenCreator           childrenCreator            = new ChildrenCreator();
            Placeholder               crossover                  = new Placeholder();
            Comparator                iterationsChecker          = new Comparator();
            IntCounter                iterationsCounter          = new IntCounter();
            MergingReducer            mergingReducer             = new MergingReducer();
            ConditionalBranch         executePathRelinkingBranch = new ConditionalBranch();
            ConditionalBranch         newSolutionsBranch         = new ConditionalBranch();
            OffspringProcessor        offspringProcessor         = new OffspringProcessor();
            Placeholder               pathRelinker               = new Placeholder();
            PopulationRebuildMethod   populationRebuildMethod    = new PopulationRebuildMethod();
            ReferenceSetUpdateMethod  referenceSetUpdateMethod   = new ReferenceSetUpdateMethod();
            ResultsCollector          resultsCollector           = new ResultsCollector();
            RightSelector             rightSelector              = new RightSelector();
            Placeholder               solutionEvaluator1         = new Placeholder();
            Placeholder               solutionEvaluator2         = new Placeholder();
            Placeholder               solutionImprover1          = new Placeholder();
            Placeholder               solutionImprover2          = new Placeholder();
            SolutionPoolUpdateMethod  solutionPoolUpdateMethod   = new SolutionPoolUpdateMethod();
            SolutionsCreator          solutionsCreator           = new SolutionsCreator();
            DataReducer               dataReducer1               = new DataReducer();
            DataReducer               dataReducer2               = new DataReducer();
            SubScopesProcessor        subScopesProcessor1        = new SubScopesProcessor();
            SubScopesProcessor        subScopesProcessor2        = new SubScopesProcessor();
            SubScopesProcessor        subScopesProcessor3        = new SubScopesProcessor();
            SubScopesProcessor        subScopesProcessor4        = new SubScopesProcessor();
            ConditionalBranch         terminateBranch            = new ConditionalBranch();
            UniformSubScopesProcessor uniformSubScopesProcessor1 = new UniformSubScopesProcessor();
            UniformSubScopesProcessor uniformSubScopesProcessor2 = new UniformSubScopesProcessor();
            UniformSubScopesProcessor uniformSubScopesProcessor3 = new UniformSubScopesProcessor();
            VariableCreator           variableCreator            = new VariableCreator();
            #endregion

            #region Create operator graph
            OperatorGraph.InitialOperator = variableCreator;
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>(IterationsParameter.Name, new IntValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <BoolValue>("NewSolutions", new BoolValue(false)));
            variableCreator.Successor = resultsCollector;

            resultsCollector.CopyValue = new BoolValue(false);
            resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>(IterationsParameter.Name));
            resultsCollector.ResultsParameter.ActualName = ResultsParameter.Name;
            resultsCollector.Successor = iterationsChecker;

            iterationsChecker.Name                          = "IterationsChecker";
            iterationsChecker.Comparison.Value              = ComparisonType.GreaterOrEqual;
            iterationsChecker.LeftSideParameter.ActualName  = IterationsParameter.Name;
            iterationsChecker.RightSideParameter.ActualName = MaximumIterationsParameter.Name;
            iterationsChecker.ResultParameter.ActualName    = "Terminate";
            iterationsChecker.Successor                     = terminateBranch;

            terminateBranch.Name = "TerminateChecker";
            terminateBranch.ConditionParameter.ActualName = "Terminate";
            terminateBranch.FalseBranch = referenceSetUpdateMethod;

            referenceSetUpdateMethod.Successor = assigner1;

            assigner1.Name = "NewSolutions = true";
            assigner1.LeftSideParameter.ActualName = "NewSolutions";
            assigner1.RightSideParameter.Value     = new BoolValue(true);
            assigner1.Successor = subScopesProcessor1;

            subScopesProcessor1.DepthParameter.Value = new IntValue(1);
            subScopesProcessor1.Operators.Add(new EmptyOperator());
            subScopesProcessor1.Operators.Add(childrenCreator);
            subScopesProcessor1.Successor = newSolutionsBranch;

            childrenCreator.Name = "SubsetGenerator";
            childrenCreator.ParentsPerChildParameter.Value = new IntValue(2);
            childrenCreator.Successor = assigner2;

            assigner2.Name = "NewSolutions = false";
            assigner2.LeftSideParameter.ActualName = "NewSolutions";
            assigner2.RightSideParameter.Value     = new BoolValue(false);
            assigner2.Successor = uniformSubScopesProcessor1;

            uniformSubScopesProcessor1.DepthParameter.Value = new IntValue(1);
            uniformSubScopesProcessor1.Operator             = executePathRelinkingBranch;
            uniformSubScopesProcessor1.Successor            = solutionPoolUpdateMethod;

            executePathRelinkingBranch.Name = "ExecutePathRelinkingChecker";
            executePathRelinkingBranch.ConditionParameter.ActualName = ExecutePathRelinkingParameter.ActualName;
            executePathRelinkingBranch.TrueBranch  = pathRelinker;
            executePathRelinkingBranch.FalseBranch = crossover;

            pathRelinker.Name = "PathRelinker";
            pathRelinker.OperatorParameter.ActualName = PathRelinkerParameter.Name;
            pathRelinker.Successor = rightSelector;

            crossover.Name = "Crossover";
            crossover.OperatorParameter.ActualName = CrossoverParameter.Name;
            crossover.Successor = offspringProcessor;

            offspringProcessor.Successor = rightSelector;

            rightSelector.NumberOfSelectedSubScopesParameter.Value = new IntValue(1);
            rightSelector.CopySelected = new BoolValue(false);
            rightSelector.Successor    = subScopesProcessor2;

            subScopesProcessor2.DepthParameter.Value = new IntValue(1);
            subScopesProcessor2.Operators.Add(new EmptyOperator());
            subScopesProcessor2.Operators.Add(uniformSubScopesProcessor2);
            subScopesProcessor2.Successor = mergingReducer;

            uniformSubScopesProcessor2.DepthParameter.Value    = new IntValue(2);
            uniformSubScopesProcessor2.Operator                = solutionImprover1;
            uniformSubScopesProcessor2.ParallelParameter.Value = new BoolValue(true);
            uniformSubScopesProcessor2.Successor               = subScopesProcessor4;

            solutionImprover1.Name = "SolutionImprover";
            solutionImprover1.OperatorParameter.ActualName = ImproverParameter.Name;
            solutionImprover1.Successor = solutionEvaluator1;

            solutionEvaluator1.Name = "SolutionEvaluator";
            solutionEvaluator1.OperatorParameter.ActualName = EvaluatorParameter.Name;

            subScopesProcessor4.Operators.Add(dataReducer1);

            dataReducer1.Name = "Increment EvaluatedSolutions";
            dataReducer1.ParameterToReduce.ActualName = "LocalEvaluatedSolutions";
            dataReducer1.TargetParameter.ActualName   = EvaluatedSolutionsParameter.Name;
            dataReducer1.ReductionOperation.Value     = new ReductionOperation(ReductionOperations.Sum);
            dataReducer1.TargetOperation.Value        = new ReductionOperation(ReductionOperations.Sum);

            solutionPoolUpdateMethod.QualityParameter.ActualName = QualityParameter.ActualName;
            solutionPoolUpdateMethod.Successor = analyzer;

            analyzer.Name = "Analyzer";
            analyzer.OperatorParameter.ActualName = AnalyzerParameter.Name;

            newSolutionsBranch.Name = "NewSolutionsChecker";
            newSolutionsBranch.ConditionParameter.ActualName = "NewSolutions";
            newSolutionsBranch.TrueBranch  = subScopesProcessor1;
            newSolutionsBranch.FalseBranch = populationRebuildMethod;

            populationRebuildMethod.QualityParameter.ActualName = QualityParameter.ActualName;
            populationRebuildMethod.Successor = subScopesProcessor3;

            subScopesProcessor3.DepthParameter.Value = new IntValue(1);
            subScopesProcessor3.Operators.Add(solutionsCreator);
            subScopesProcessor3.Operators.Add(new EmptyOperator());
            subScopesProcessor3.Successor = iterationsCounter;

            solutionsCreator.Name = "DiversificationGenerationMethod";
            solutionsCreator.NumberOfSolutionsParameter.ActualName = PopulationSizeParameter.Name;
            solutionsCreator.Successor = uniformSubScopesProcessor3;

            uniformSubScopesProcessor3.DepthParameter.Value    = new IntValue(1);
            uniformSubScopesProcessor3.Operator                = solutionImprover2;
            uniformSubScopesProcessor3.ParallelParameter.Value = new BoolValue(true);
            uniformSubScopesProcessor3.Successor               = dataReducer2;

            solutionImprover2.Name = "SolutionImprover";
            solutionImprover2.OperatorParameter.ActualName = ImproverParameter.Name;
            solutionImprover2.Successor = solutionEvaluator2;

            solutionEvaluator2.Name = "SolutionEvaluator";
            solutionEvaluator2.OperatorParameter.ActualName = EvaluatorParameter.Name;

            dataReducer2.Name = "Increment EvaluatedSolutions";
            dataReducer2.ParameterToReduce.ActualName = "LocalEvaluatedSolutions";
            dataReducer2.TargetParameter.ActualName   = EvaluatedSolutionsParameter.Name;
            dataReducer2.ReductionOperation.Value     = new ReductionOperation(ReductionOperations.Sum);
            dataReducer2.TargetOperation.Value        = new ReductionOperation(ReductionOperations.Sum);

            iterationsCounter.Name = "IterationCounter";
            iterationsCounter.IncrementParameter.Value  = new IntValue(1);
            iterationsCounter.ValueParameter.ActualName = IterationsParameter.Name;
            iterationsCounter.Successor = resultsCollector;
            #endregion
        }
Exemple #29
0
        public CMAEvolutionStrategy()
            : base()
        {
            Parameters.Add(new FixedValueParameter <IntValue>(SeedName, "The random seed used to initialize the new pseudo random number generator.", new IntValue(0)));
            Parameters.Add(new FixedValueParameter <BoolValue>(SetSeedRandomlyName, "True if the random seed should be set to a random value, otherwise false.", new BoolValue(true)));
            Parameters.Add(new FixedValueParameter <IntValue>(PopulationSizeName, "λ (lambda) - the size of the offspring population.", new IntValue(20)));
            Parameters.Add(new FixedValueParameter <IntValue>(InitialIterationsName, "The number of iterations that should be performed with only axis parallel mutation.", new IntValue(0)));
            Parameters.Add(new FixedValueParameter <DoubleArray>(InitialSigmaName, "The initial sigma can be a single value or a value for each dimension. All values need to be > 0.", new DoubleArray(new[] { 0.5 })));
            Parameters.Add(new OptionalValueParameter <IntValue>(MuName, "Optional, the mu best offspring that should be considered for update of the new mean and strategy parameters. If not given it will be automatically calculated."));
            Parameters.Add(new ConstrainedValueParameter <ICMARecombinator>(CMARecombinatorName, "The operator used to calculate the new mean."));
            Parameters.Add(new ConstrainedValueParameter <ICMAManipulator>(CMAMutatorName, "The operator used to manipulate a point."));
            Parameters.Add(new ConstrainedValueParameter <ICMAInitializer>(CMAInitializerName, "The operator that initializes the covariance matrix and strategy parameters."));
            Parameters.Add(new ConstrainedValueParameter <ICMAUpdater>(CMAUpdaterName, "The operator that updates the covariance matrix and strategy parameters."));
            Parameters.Add(new ValueParameter <MultiAnalyzer>(AnalyzerName, "The operator used to analyze each generation.", new MultiAnalyzer()));
            Parameters.Add(new FixedValueParameter <IntValue>(MaximumGenerationsName, "The maximum number of generations which should be processed.", new IntValue(1000)));
            Parameters.Add(new FixedValueParameter <IntValue>(MaximumEvaluatedSolutionsName, "The maximum number of evaluated solutions that should be computed.", new IntValue(int.MaxValue)));
            Parameters.Add(new FixedValueParameter <DoubleValue>(TargetQualityName, "(stopFitness) Surpassing this quality value terminates the algorithm.", new DoubleValue(double.NaN)));
            Parameters.Add(new FixedValueParameter <DoubleValue>(MinimumQualityChangeName, "(stopTolFun) If the range of fitness values is less than a certain value the algorithm terminates (set to 0 or positive value to enable).", new DoubleValue(double.NaN)));
            Parameters.Add(new FixedValueParameter <DoubleValue>(MinimumQualityHistoryChangeName, "(stopTolFunHist) If the range of fitness values is less than a certain value for a certain time the algorithm terminates (set to 0 or positive to enable).", new DoubleValue(double.NaN)));
            Parameters.Add(new FixedValueParameter <DoubleValue>(MinimumStandardDeviationName, "(stopTolXFactor) If the standard deviation falls below a certain value the algorithm terminates (set to 0 or positive to enable).", new DoubleValue(double.NaN)));
            Parameters.Add(new FixedValueParameter <DoubleValue>(MaximumStandardDeviationChangeName, "(stopTolUpXFactor) If the standard deviation changes by a value larger than this parameter the algorithm stops (set to a value > 0 to enable).", new DoubleValue(double.NaN)));

            var randomCreator    = new RandomCreator();
            var variableCreator  = new VariableCreator();
            var resultsCollector = new ResultsCollector();
            var cmaInitializer   = new Placeholder();

            solutionCreator = new Placeholder();
            var subScopesCreator = new SubScopesCreator();
            var ussp1            = new UniformSubScopesProcessor();

            populationSolutionCreator = new Placeholder();
            var cmaMutator = new Placeholder();
            var ussp2      = new UniformSubScopesProcessor();

            evaluator = new Placeholder();
            var subScopesCounter = new SubScopesCounter();

            sorter = new SubScopesSorter();
            var analyzer           = new Placeholder();
            var cmaRecombinator    = new Placeholder();
            var generationsCounter = new IntCounter();
            var cmaUpdater         = new Placeholder();

            terminator = new Terminator();

            OperatorGraph.InitialOperator = randomCreator;

            randomCreator.RandomParameter.ActualName          = "Random";
            randomCreator.SeedParameter.ActualName            = SeedParameter.Name;
            randomCreator.SeedParameter.Value                 = null;
            randomCreator.SetSeedRandomlyParameter.ActualName = SetSeedRandomlyParameter.Name;
            randomCreator.SetSeedRandomlyParameter.Value      = null;
            randomCreator.Successor = variableCreator;

            variableCreator.Name = "Initialize Variables";
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("EvaluatedSolutions", new IntValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Generations", new IntValue(0)));
            variableCreator.Successor = resultsCollector;

            resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("EvaluatedSolutions"));
            resultsCollector.CollectedValues.Add(new LookupParameter <IntValue>("Generations"));
            resultsCollector.ResultsParameter.ActualName = "Results";
            resultsCollector.Successor = cmaInitializer;

            cmaInitializer.Name = "Initialize Strategy Parameters";
            cmaInitializer.OperatorParameter.ActualName = CMAInitializerParameter.Name;
            cmaInitializer.Successor = subScopesCreator;

            subScopesCreator.NumberOfSubScopesParameter.ActualName = PopulationSizeParameter.Name;
            subScopesCreator.Successor = ussp1;

            ussp1.Name      = "Create population";
            ussp1.Parallel  = new BoolValue(false);
            ussp1.Operator  = populationSolutionCreator;
            ussp1.Successor = solutionCreator;

            populationSolutionCreator.Name = "Initialize arx";
            // populationSolutionCreator.OperatorParameter will be wired
            populationSolutionCreator.Successor = null;

            solutionCreator.Name = "Initialize xmean";
            // solutionCreator.OperatorParameter will be wired
            solutionCreator.Successor = cmaMutator;

            cmaMutator.Name = "Sample population";
            cmaMutator.OperatorParameter.ActualName = CMAMutatorParameter.Name;
            cmaMutator.Successor = ussp2;

            ussp2.Name      = "Evaluate offspring";
            ussp2.Parallel  = new BoolValue(true);
            ussp2.Operator  = evaluator;
            ussp2.Successor = subScopesCounter;

            evaluator.Name = "Evaluator";
            // evaluator.OperatorParameter will be wired
            evaluator.Successor = null;

            subScopesCounter.Name = "Count EvaluatedSolutions";
            subScopesCounter.AccumulateParameter.Value = new BoolValue(true);
            subScopesCounter.ValueParameter.ActualName = "EvaluatedSolutions";
            subScopesCounter.Successor = sorter;

            // sorter.ValueParameter will be wired
            // sorter.DescendingParameter will be wired
            sorter.Successor = analyzer;

            analyzer.Name = "Analyzer";
            analyzer.OperatorParameter.ActualName = AnalyzerParameter.Name;
            analyzer.Successor = cmaRecombinator;

            cmaRecombinator.Name = "Create new xmean";
            cmaRecombinator.OperatorParameter.ActualName = CMARecombinatorParameter.Name;
            cmaRecombinator.Successor = generationsCounter;

            generationsCounter.Name = "Generations++";
            generationsCounter.IncrementParameter.Value  = new IntValue(1);
            generationsCounter.ValueParameter.ActualName = "Generations";
            generationsCounter.Successor = cmaUpdater;

            cmaUpdater.Name = "Update distributions";
            cmaUpdater.OperatorParameter.ActualName = CMAUpdaterParameter.Name;
            cmaUpdater.Successor = terminator;

            terminator.Continue  = cmaMutator;
            terminator.Terminate = null;

            qualityAnalyzer = new BestAverageWorstQualityAnalyzer();
            cmaAnalyzer     = new CMAAnalyzer();

            InitializeOperators();
            RegisterEventHandlers();
            Parameterize();
        }
        public IslandOffspringSelectionGeneticAlgorithmMainLoop()
            : base()
        {
            #region Create parameters
            Parameters.Add(new ValueLookupParameter <IRandom>("Random", "A pseudo random number generator."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("Maximization", "True if the problem is a maximization problem, otherwise false."));
            Parameters.Add(new ScopeTreeLookupParameter <DoubleValue>("Quality", "The value which represents the quality of a solution."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("BestKnownQuality", "The best known quality value found so far."));
            Parameters.Add(new ValueLookupParameter <IntValue>("NumberOfIslands", "The number of islands."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MigrationInterval", "The number of generations that should pass between migration phases."));
            Parameters.Add(new ValueLookupParameter <PercentValue>("MigrationRate", "The proportion of individuals that should migrate between the islands."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Migrator", "The migration strategy."));
            Parameters.Add(new ValueLookupParameter <IOperator>("EmigrantsSelector", "Selects the individuals that will be migrated."));
            Parameters.Add(new ValueLookupParameter <IOperator>("ImmigrationReplacer", "Replaces part of the original population with the immigrants."));
            Parameters.Add(new ValueLookupParameter <IntValue>("PopulationSize", "The size of the population of solutions."));
            Parameters.Add(new ValueLookupParameter <IntValue>("MaximumGenerations", "The maximum number of generations that should be processed."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Selector", "The operator used to select solutions for reproduction."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Crossover", "The operator used to cross solutions."));
            Parameters.Add(new ValueLookupParameter <PercentValue>("MutationProbability", "The probability that the mutation operator is applied on a solution."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Mutator", "The operator used to mutate solutions."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Evaluator", "The operator used to evaluate solutions. This operator is executed in parallel, if an engine is used which supports parallelization."));
            Parameters.Add(new ValueLookupParameter <IntValue>("Elites", "The numer of elite solutions which are kept in each generation."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("ReevaluateElites", "Flag to determine if elite individuals should be reevaluated (i.e., if stochastic fitness functions are used.)"));
            Parameters.Add(new ValueLookupParameter <ResultCollection>("Results", "The results collection to store the results."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Visualizer", "The operator used to visualize solutions."));
            Parameters.Add(new LookupParameter <IItem>("Visualization", "The item which represents the visualization of solutions."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("SuccessRatio", "The ratio of successful to total children that should be achieved."));
            Parameters.Add(new LookupParameter <DoubleValue>("ComparisonFactor", "The comparison factor is used to determine whether the offspring should be compared to the better parent, the worse parent or a quality value linearly interpolated between them. It is in the range [0;1]."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("ComparisonFactorStart", "The initial value for the comparison factor."));
            Parameters.Add(new ValueLookupParameter <IOperator>("ComparisonFactorModifier", "The operator used to modify the comparison factor."));
            Parameters.Add(new ValueLookupParameter <DoubleValue>("MaximumSelectionPressure", "The maximum selection pressure that terminates the algorithm."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("OffspringSelectionBeforeMutation", "True if the offspring selection step should be applied before mutation, false if it should be applied after mutation."));
            Parameters.Add(new ValueLookupParameter <IOperator>("Analyzer", "The operator used to the analyze the islands."));
            Parameters.Add(new ValueLookupParameter <IOperator>("IslandAnalyzer", "The operator used to analyze each island."));
            Parameters.Add(new LookupParameter <IntValue>("EvaluatedSolutions", "The number of times solutions have been evaluated."));
            Parameters.Add(new ValueLookupParameter <BoolValue>("FillPopulationWithParents", "True if the population should be filled with parent individual or false if worse children should be used when the maximum selection pressure is exceeded."));
            #endregion

            #region Create operators
            VariableCreator           variableCreator             = new VariableCreator();
            UniformSubScopesProcessor uniformSubScopesProcessor0  = new UniformSubScopesProcessor();
            VariableCreator           islandVariableCreator       = new VariableCreator();
            Placeholder               islandAnalyzer1             = new Placeholder();
            ResultsCollector          islandResultsCollector1     = new ResultsCollector();
            Assigner                  comparisonFactorInitializer = new Assigner();
            Placeholder               analyzer1                                  = new Placeholder();
            ResultsCollector          resultsCollector1                          = new ResultsCollector();
            UniformSubScopesProcessor uniformSubScopesProcessor1                 = new UniformSubScopesProcessor();
            ConditionalBranch         islandTerminatedBySelectionPressure1       = new ConditionalBranch();
            OffspringSelectionGeneticAlgorithmMainOperator mainOperator          = new OffspringSelectionGeneticAlgorithmMainOperator();
            Placeholder               islandAnalyzer2                            = new Placeholder();
            ResultsCollector          islandResultsCollector2                    = new ResultsCollector();
            Comparator                islandSelectionPressureComparator          = new Comparator();
            ConditionalBranch         islandTerminatedBySelectionPressure2       = new ConditionalBranch();
            IntCounter                terminatedIslandsCounter                   = new IntCounter();
            IntCounter                generationsCounter                         = new IntCounter();
            IntCounter                generationsSinceLastMigrationCounter       = new IntCounter();
            Comparator                migrationComparator                        = new Comparator();
            ConditionalBranch         migrationBranch                            = new ConditionalBranch();
            Assigner                  resetTerminatedIslandsAssigner             = new Assigner();
            Assigner                  resetGenerationsSinceLastMigrationAssigner = new Assigner();
            IntCounter                migrationsCounter                          = new IntCounter();
            UniformSubScopesProcessor uniformSubScopesProcessor2                 = new UniformSubScopesProcessor();
            Assigner                  reviveIslandAssigner                       = new Assigner();
            Placeholder               emigrantsSelector                          = new Placeholder();
            Placeholder               migrator = new Placeholder();
            UniformSubScopesProcessor uniformSubScopesProcessor3      = new UniformSubScopesProcessor();
            Placeholder               immigrationReplacer             = new Placeholder();
            Comparator                generationsComparator           = new Comparator();
            Comparator                terminatedIslandsComparator     = new Comparator();
            Comparator                maxEvaluatedSolutionsComparator = new Comparator();
            Placeholder               comparisonFactorModifier        = new Placeholder();
            Placeholder               analyzer2 = new Placeholder();
            ConditionalBranch         generationsTerminationCondition        = new ConditionalBranch();
            ConditionalBranch         terminatedIslandsCondition             = new ConditionalBranch();
            ConditionalBranch         evaluatedSolutionsTerminationCondition = new ConditionalBranch();

            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Migrations", new IntValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("Generations", new IntValue(0))); // Class IslandOffspringSelectionGeneticAlgorithm expects this to be called Generations
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("GenerationsSinceLastMigration", new IntValue(0)));
            variableCreator.CollectedValues.Add(new ValueParameter <IntValue>("TerminatedIslands", new IntValue(0)));

            islandVariableCreator.CollectedValues.Add(new ValueParameter <ResultCollection>(ResultsParameter.Name, new ResultCollection()));
            islandVariableCreator.CollectedValues.Add(new ValueParameter <BoolValue>("TerminateSelectionPressure", new BoolValue(false)));
            islandVariableCreator.CollectedValues.Add(new ValueParameter <DoubleValue>("SelectionPressure", new DoubleValue(0)));

            islandAnalyzer1.Name = "Island Analyzer (placeholder)";
            islandAnalyzer1.OperatorParameter.ActualName = IslandAnalyzerParameter.Name;

            islandResultsCollector1.CollectedValues.Add(new LookupParameter <DoubleValue>("Current Selection Pressure", "Displays the rising selection pressure during a generation.", "SelectionPressure"));
            islandResultsCollector1.CollectedValues.Add(new LookupParameter <DoubleValue>("Current Success Ratio", "Indicates how many successful children were already found during a generation (relative to the population size).", "CurrentSuccessRatio"));
            islandResultsCollector1.ResultsParameter.ActualName = ResultsParameter.Name;

            comparisonFactorInitializer.Name = "Initialize Comparison Factor";
            comparisonFactorInitializer.LeftSideParameter.ActualName  = ComparisonFactorParameter.Name;
            comparisonFactorInitializer.RightSideParameter.ActualName = ComparisonFactorStartParameter.Name;

            analyzer1.Name = "Analyzer (placeholder)";
            analyzer1.OperatorParameter.ActualName = AnalyzerParameter.Name;

            resultsCollector1.CopyValue = new BoolValue(false);
            resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>("Migrations"));
            resultsCollector1.CollectedValues.Add(new LookupParameter <IntValue>("Generations"));
            resultsCollector1.CollectedValues.Add(new LookupParameter <DoubleValue>("Current Comparison Factor", null, ComparisonFactorParameter.Name));
            resultsCollector1.CollectedValues.Add(new ScopeTreeLookupParameter <ResultCollection>("IslandResults", "Result set for each island", ResultsParameter.Name));
            resultsCollector1.ResultsParameter.ActualName = ResultsParameter.Name;

            islandTerminatedBySelectionPressure1.Name = "Island Terminated ?";
            islandTerminatedBySelectionPressure1.ConditionParameter.ActualName = "TerminateSelectionPressure";

            mainOperator.ComparisonFactorParameter.ActualName    = ComparisonFactorParameter.Name;
            mainOperator.CrossoverParameter.ActualName           = CrossoverParameter.Name;
            mainOperator.CurrentSuccessRatioParameter.ActualName = "CurrentSuccessRatio";
            mainOperator.ElitesParameter.ActualName                           = ElitesParameter.Name;
            mainOperator.ReevaluateElitesParameter.ActualName                 = ReevaluateElitesParameter.Name;
            mainOperator.EvaluatedSolutionsParameter.ActualName               = EvaluatedSolutionsParameter.Name;
            mainOperator.EvaluatorParameter.ActualName                        = EvaluatorParameter.Name;
            mainOperator.MaximizationParameter.ActualName                     = MaximizationParameter.Name;
            mainOperator.MaximumSelectionPressureParameter.ActualName         = MaximumSelectionPressureParameter.Name;
            mainOperator.MutationProbabilityParameter.ActualName              = MutationProbabilityParameter.Name;
            mainOperator.MutatorParameter.ActualName                          = MutatorParameter.Name;
            mainOperator.OffspringSelectionBeforeMutationParameter.ActualName = OffspringSelectionBeforeMutationParameter.Name;
            mainOperator.QualityParameter.ActualName                          = QualityParameter.Name;
            mainOperator.RandomParameter.ActualName                           = RandomParameter.Name;
            mainOperator.SelectionPressureParameter.ActualName                = "SelectionPressure";
            mainOperator.SelectorParameter.ActualName                         = SelectorParameter.Name;
            mainOperator.SuccessRatioParameter.ActualName                     = SuccessRatioParameter.Name;
            mainOperator.FillPopulationWithParentsParameter.ActualName        = FillPopulationWithParentsParameter.Name;

            islandAnalyzer2.Name = "Island Analyzer (placeholder)";
            islandAnalyzer2.OperatorParameter.ActualName = IslandAnalyzerParameter.Name;

            islandResultsCollector2.CollectedValues.Add(new LookupParameter <DoubleValue>("Current Selection Pressure", "Displays the rising selection pressure during a generation.", "SelectionPressure"));
            islandResultsCollector2.CollectedValues.Add(new LookupParameter <DoubleValue>("Current Success Ratio", "Indicates how many successful children were already found during a generation (relative to the population size).", "CurrentSuccessRatio"));
            islandResultsCollector2.ResultsParameter.ActualName = "Results";

            islandSelectionPressureComparator.Name = "SelectionPressure >= MaximumSelectionPressure ?";
            islandSelectionPressureComparator.LeftSideParameter.ActualName = "SelectionPressure";
            islandSelectionPressureComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            islandSelectionPressureComparator.RightSideParameter.ActualName = MaximumSelectionPressureParameter.Name;
            islandSelectionPressureComparator.ResultParameter.ActualName    = "TerminateSelectionPressure";

            islandTerminatedBySelectionPressure2.Name = "Island Terminated ?";
            islandTerminatedBySelectionPressure2.ConditionParameter.ActualName = "TerminateSelectionPressure";

            terminatedIslandsCounter.Name = "TerminatedIslands + 1";
            terminatedIslandsCounter.ValueParameter.ActualName = "TerminatedIslands";
            terminatedIslandsCounter.Increment = new IntValue(1);

            generationsCounter.Name = "Generations + 1";
            generationsCounter.ValueParameter.ActualName = "Generations";
            generationsCounter.Increment = new IntValue(1);

            generationsSinceLastMigrationCounter.Name = "GenerationsSinceLastMigration + 1";
            generationsSinceLastMigrationCounter.ValueParameter.ActualName = "GenerationsSinceLastMigration";
            generationsSinceLastMigrationCounter.Increment = new IntValue(1);

            migrationComparator.Name = "GenerationsSinceLastMigration = MigrationInterval ?";
            migrationComparator.LeftSideParameter.ActualName = "GenerationsSinceLastMigration";
            migrationComparator.Comparison = new Comparison(ComparisonType.Equal);
            migrationComparator.RightSideParameter.ActualName = MigrationIntervalParameter.Name;
            migrationComparator.ResultParameter.ActualName    = "Migrate";

            migrationBranch.Name = "Migrate?";
            migrationBranch.ConditionParameter.ActualName = "Migrate";

            resetTerminatedIslandsAssigner.Name = "Reset TerminatedIslands";
            resetTerminatedIslandsAssigner.LeftSideParameter.ActualName = "TerminatedIslands";
            resetTerminatedIslandsAssigner.RightSideParameter.Value     = new IntValue(0);

            resetGenerationsSinceLastMigrationAssigner.Name = "Reset GenerationsSinceLastMigration";
            resetGenerationsSinceLastMigrationAssigner.LeftSideParameter.ActualName = "GenerationsSinceLastMigration";
            resetGenerationsSinceLastMigrationAssigner.RightSideParameter.Value     = new IntValue(0);

            migrationsCounter.Name = "Migrations + 1";
            migrationsCounter.IncrementParameter.Value  = new IntValue(1);
            migrationsCounter.ValueParameter.ActualName = "Migrations";

            reviveIslandAssigner.Name = "Revive Island";
            reviveIslandAssigner.LeftSideParameter.ActualName = "TerminateSelectionPressure";
            reviveIslandAssigner.RightSideParameter.Value     = new BoolValue(false);

            emigrantsSelector.Name = "Emigrants Selector (placeholder)";
            emigrantsSelector.OperatorParameter.ActualName = EmigrantsSelectorParameter.Name;

            migrator.Name = "Migrator (placeholder)";
            migrator.OperatorParameter.ActualName = MigratorParameter.Name;

            immigrationReplacer.Name = "Immigration Replacer (placeholder)";
            immigrationReplacer.OperatorParameter.ActualName = ImmigrationReplacerParameter.Name;

            generationsComparator.Name = "Generations >= MaximumGenerations ?";
            generationsComparator.LeftSideParameter.ActualName = "Generations";
            generationsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            generationsComparator.RightSideParameter.ActualName = MaximumGenerationsParameter.Name;
            generationsComparator.ResultParameter.ActualName    = "TerminateGenerations";

            terminatedIslandsComparator.Name = "All Islands terminated ?";
            terminatedIslandsComparator.LeftSideParameter.ActualName = "TerminatedIslands";
            terminatedIslandsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            terminatedIslandsComparator.RightSideParameter.ActualName = NumberOfIslandsParameter.Name;
            terminatedIslandsComparator.ResultParameter.ActualName    = "TerminateTerminatedIslands";

            maxEvaluatedSolutionsComparator.Name       = "EvaluatedSolutions >= MaximumEvaluatedSolutions ?";
            maxEvaluatedSolutionsComparator.Comparison = new Comparison(ComparisonType.GreaterOrEqual);
            maxEvaluatedSolutionsComparator.LeftSideParameter.ActualName  = EvaluatedSolutionsParameter.Name;
            maxEvaluatedSolutionsComparator.ResultParameter.ActualName    = "TerminateEvaluatedSolutions";
            maxEvaluatedSolutionsComparator.RightSideParameter.ActualName = "MaximumEvaluatedSolutions";

            comparisonFactorModifier.Name = "Update Comparison Factor (Placeholder)";
            comparisonFactorModifier.OperatorParameter.ActualName = ComparisonFactorModifierParameter.Name;

            analyzer2.Name = "Analyzer (placeholder)";
            analyzer2.OperatorParameter.ActualName = AnalyzerParameter.Name;

            generationsTerminationCondition.Name = "Terminate (MaxGenerations) ?";
            generationsTerminationCondition.ConditionParameter.ActualName = "TerminateGenerations";

            terminatedIslandsCondition.Name = "Terminate (TerminatedIslands) ?";
            terminatedIslandsCondition.ConditionParameter.ActualName = "TerminateTerminatedIslands";

            evaluatedSolutionsTerminationCondition.Name = "Terminate (EvaluatedSolutions) ?";
            evaluatedSolutionsTerminationCondition.ConditionParameter.ActualName = "TerminateEvaluatedSolutions";
            #endregion

            #region Create operator graph
            OperatorGraph.InitialOperator         = variableCreator;
            variableCreator.Successor             = uniformSubScopesProcessor0;
            uniformSubScopesProcessor0.Operator   = islandVariableCreator;
            uniformSubScopesProcessor0.Successor  = comparisonFactorInitializer;
            islandVariableCreator.Successor       = islandAnalyzer1;
            islandAnalyzer1.Successor             = islandResultsCollector1;
            islandResultsCollector1.Successor     = null;
            comparisonFactorInitializer.Successor = analyzer1;
            analyzer1.Successor                                  = resultsCollector1;
            resultsCollector1.Successor                          = uniformSubScopesProcessor1;
            uniformSubScopesProcessor1.Operator                  = islandTerminatedBySelectionPressure1;
            uniformSubScopesProcessor1.Successor                 = generationsCounter;
            islandTerminatedBySelectionPressure1.TrueBranch      = null;
            islandTerminatedBySelectionPressure1.FalseBranch     = mainOperator;
            islandTerminatedBySelectionPressure1.Successor       = null;
            mainOperator.Successor                               = islandAnalyzer2;
            islandAnalyzer2.Successor                            = islandResultsCollector2;
            islandResultsCollector2.Successor                    = islandSelectionPressureComparator;
            islandSelectionPressureComparator.Successor          = islandTerminatedBySelectionPressure2;
            islandTerminatedBySelectionPressure2.TrueBranch      = terminatedIslandsCounter;
            islandTerminatedBySelectionPressure2.FalseBranch     = null;
            islandTerminatedBySelectionPressure2.Successor       = null;
            generationsCounter.Successor                         = generationsSinceLastMigrationCounter;
            generationsSinceLastMigrationCounter.Successor       = migrationComparator;
            migrationComparator.Successor                        = migrationBranch;
            migrationBranch.TrueBranch                           = resetTerminatedIslandsAssigner;
            migrationBranch.FalseBranch                          = null;
            migrationBranch.Successor                            = generationsComparator;
            resetTerminatedIslandsAssigner.Successor             = resetGenerationsSinceLastMigrationAssigner;
            resetGenerationsSinceLastMigrationAssigner.Successor = migrationsCounter;
            migrationsCounter.Successor                          = uniformSubScopesProcessor2;
            uniformSubScopesProcessor2.Operator                  = reviveIslandAssigner;
            uniformSubScopesProcessor2.Successor                 = migrator;
            reviveIslandAssigner.Successor                       = emigrantsSelector;
            emigrantsSelector.Successor                          = null;
            migrator.Successor = uniformSubScopesProcessor3;
            uniformSubScopesProcessor3.Operator       = immigrationReplacer;
            uniformSubScopesProcessor3.Successor      = null;
            immigrationReplacer.Successor             = null;
            generationsComparator.Successor           = terminatedIslandsComparator;
            terminatedIslandsComparator.Successor     = maxEvaluatedSolutionsComparator;
            maxEvaluatedSolutionsComparator.Successor = comparisonFactorModifier;
            comparisonFactorModifier.Successor        = analyzer2;
            analyzer2.Successor = generationsTerminationCondition;
            generationsTerminationCondition.TrueBranch         = null;
            generationsTerminationCondition.FalseBranch        = terminatedIslandsCondition;
            generationsTerminationCondition.Successor          = null;
            terminatedIslandsCondition.TrueBranch              = null;
            terminatedIslandsCondition.FalseBranch             = evaluatedSolutionsTerminationCondition;
            terminatedIslandsCondition.Successor               = null;
            evaluatedSolutionsTerminationCondition.TrueBranch  = null;
            evaluatedSolutionsTerminationCondition.FalseBranch = uniformSubScopesProcessor1;
            evaluatedSolutionsTerminationCondition.Successor   = null;
            #endregion
        }