Beispiel #1
0
 public SimulatedAnnealingSearch(IToDoubleFunction <Node <S, A> > h, Scheduler scheduler, NodeExpander <S, A> nodeExpander)
 {
     this.h            = h;
     this.scheduler    = scheduler;
     this.nodeExpander = nodeExpander;
     nodeExpander.addNodeListener((node) => metrics.incrementInt(METRIC_NODES_EXPANDED));
 }
Beispiel #2
0
 /** Modifies the evaluation function if it is a {@link HeuristicEvaluationFunction}. */
 public void setHeuristicFunction(IToDoubleFunction <Node <S, A> > h)
 {
     if (evalFn is HeuristicEvaluationFunction <S, A> )
     {
         ((HeuristicEvaluationFunction <S, A>)evalFn).setHeuristicFunction(h);
     }
 }
Beispiel #3
0
 public RecursiveBestFirstSearch(IToDoubleFunction <Node <S, A> > evalFn, bool avoidLoops,
                                 NodeExpander <S, A> nodeExpander)
 {
     this.evalFn       = evalFn;
     this.avoidLoops   = avoidLoops;
     this.nodeExpander = nodeExpander;
     nodeExpander.addNodeListener((node) => metrics.incrementInt(METRIC_NODES_EXPANDED));
     metrics = new Metrics();
 }
Beispiel #4
0
        /// <summary>This computes the average over all folds of the function we're trying to optimize.</summary>
        /// <remarks>
        /// This computes the average over all folds of the function we're trying to optimize.
        /// The input triple contains, in order, the train set, the test set, and the saved state.
        /// You don't have to use the saved state if you don't want to.
        /// </remarks>
        public virtual double ComputeAverage(IToDoubleFunction <Triple <GeneralDataset <L, F>, GeneralDataset <L, F>, CrossValidator.SavedState> > function)
        {
            double sum = 0;
            IEnumerator <Triple <GeneralDataset <L, F>, GeneralDataset <L, F>, CrossValidator.SavedState> > foldIt = Iterator();

            while (foldIt.MoveNext())
            {
                sum += function.ApplyAsDouble(foldIt.Current);
            }
            return(sum / kFold);
        }
Beispiel #5
0
        public void testHeuristicCalculation()
        {
            IToDoubleFunction <Node <EightPuzzleBoard, IAction> > h =
                EightPuzzleFunctions.createMisplacedTileHeuristicFunction();
            EightPuzzleBoard board = new EightPuzzleBoard(new int[] { 2, 0, 5, 6,
                                                                      4, 8, 3, 7, 1 });

            Assert.AreEqual(6.0, h.applyAsDouble(new Node <EightPuzzleBoard, IAction>(board)), 0.001);

            board = new EightPuzzleBoard(new int[] { 6, 2, 5, 3, 4, 8, 0, 7, 1 });
            Assert.AreEqual(5.0, h.applyAsDouble(new Node <EightPuzzleBoard, IAction>(board)), 0.001);

            board = new EightPuzzleBoard(new int[] { 6, 2, 5, 3, 4, 8, 7, 0, 1 });
            Assert.AreEqual(6.0, h.applyAsDouble(new Node <EightPuzzleBoard, IAction>(board)), 0.001);

            board = new EightPuzzleBoard(new int[] { 8, 1, 2, 3, 4, 5, 6, 7, 0 });
            Assert.AreEqual(1.0, h.applyAsDouble(new Node <EightPuzzleBoard, IAction>(board)), 0.001);

            board = new EightPuzzleBoard(new int[] { 0, 1, 2, 3, 4, 5, 6, 7, 8 });
            Assert.AreEqual(0.0, h.applyAsDouble(new Node <EightPuzzleBoard, IAction>(board)), 0.001);
        }
        public static T GetBestMatched <T>(IList <T> matches, IToDoubleFunction <MatchedExpression> scorer)
            where T : MatchedExpression
        {
            if (matches == null || matches.IsEmpty())
            {
                return(null);
            }
            T      best      = null;
            double bestScore = double.NegativeInfinity;

            foreach (T m in matches)
            {
                double s = scorer.ApplyAsDouble(m);
                if (best == null || s > bestScore)
                {
                    best      = m;
                    bestScore = s;
                }
            }
            return(best);
        }
Beispiel #7
0
 /**
  * Sets the heuristic function of this agent.
  *
  * @param h
  *            heuristic function <em>h(n)</em>, which estimates the cost of
  *            the cheapest path from the state at node <em>n</em> to a goal
  *            state.
  */
 public void setHeuristicFunction(IToDoubleFunction <S> h)
 {
     this.h = h;
 }
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="System.TypeLoadException"/>
        internal virtual ICounter <E> Convert2OneDim(string label, IToDoubleFunction <Pair <E, CandidatePhrase> > scoringFunction, ICollection <CandidatePhrase> allCandidatePhrases, TwoDimensionalCounter <E, CandidatePhrase> positivePatternsAndWords, bool
                                                     sqrtPatScore, bool scorePhrasesInPatSelection, ICounter <CandidatePhrase> dictOddsWordWeights, bool useFreqPhraseExtractedByPat)
        {
            //    if (Data.googleNGram.size() == 0 && Data.googleNGramsFile != null) {
            //      Data.loadGoogleNGrams();
            //    }
            ICounter <E> patterns = new ClassicCounter <E>();
            ICounter <CandidatePhrase> googleNgramNormScores     = new ClassicCounter <CandidatePhrase>();
            ICounter <CandidatePhrase> domainNgramNormScores     = new ClassicCounter <CandidatePhrase>();
            ICounter <CandidatePhrase> externalFeatWtsNormalized = new ClassicCounter <CandidatePhrase>();
            ICounter <CandidatePhrase> editDistanceFromOtherSemanticBinaryScores    = new ClassicCounter <CandidatePhrase>();
            ICounter <CandidatePhrase> editDistanceFromAlreadyExtractedBinaryScores = new ClassicCounter <CandidatePhrase>();
            double            externalWtsDefault = 0.5;
            ICounter <string> classifierScores   = null;

            if ((patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.PhEvalInPat) || patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.PhEvalInPatLogP)) && scorePhrasesInPatSelection)
            {
                foreach (CandidatePhrase gc in allCandidatePhrases)
                {
                    string g = gc.GetPhrase();
                    if (constVars.usePatternEvalEditDistOther)
                    {
                        editDistanceFromOtherSemanticBinaryScores.SetCount(gc, constVars.GetEditDistanceScoresOtherClassThreshold(label, g));
                    }
                    if (constVars.usePatternEvalEditDistSame)
                    {
                        editDistanceFromAlreadyExtractedBinaryScores.SetCount(gc, 1 - constVars.GetEditDistanceScoresThisClassThreshold(label, g));
                    }
                    if (constVars.usePatternEvalGoogleNgram)
                    {
                        googleNgramNormScores.SetCount(gc, PhraseScorer.GetGoogleNgramScore(gc));
                    }
                    if (constVars.usePatternEvalDomainNgram)
                    {
                        // calculate domain-ngram wts
                        if (Data.domainNGramRawFreq.ContainsKey(g))
                        {
                            System.Diagnostics.Debug.Assert((Data.rawFreq.ContainsKey(gc)));
                            domainNgramNormScores.SetCount(gc, scorePhrases.phraseScorer.GetDomainNgramScore(g));
                        }
                    }
                    if (constVars.usePatternEvalWordClass)
                    {
                        int num = constVars.GetWordClassClusters()[g];
                        if (num == null)
                        {
                            num = constVars.GetWordClassClusters()[g.ToLower()];
                        }
                        if (num != null && constVars.distSimWeights[label].ContainsKey(num))
                        {
                            externalFeatWtsNormalized.SetCount(gc, constVars.distSimWeights[label].GetCount(num));
                        }
                        else
                        {
                            externalFeatWtsNormalized.SetCount(gc, externalWtsDefault);
                        }
                    }
                }
                if (constVars.usePatternEvalGoogleNgram)
                {
                    googleNgramNormScores = GetPatternsFromDataMultiClass.NormalizeSoftMaxMinMaxScores(googleNgramNormScores, true, true, false);
                }
                if (constVars.usePatternEvalDomainNgram)
                {
                    domainNgramNormScores = GetPatternsFromDataMultiClass.NormalizeSoftMaxMinMaxScores(domainNgramNormScores, true, true, false);
                }
                if (constVars.usePatternEvalWordClass)
                {
                    externalFeatWtsNormalized = GetPatternsFromDataMultiClass.NormalizeSoftMaxMinMaxScores(externalFeatWtsNormalized, true, true, false);
                }
            }
            else
            {
                if ((patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.Logreg) || patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.LOGREGlogP)) && scorePhrasesInPatSelection)
                {
                    Properties props2 = new Properties();
                    props2.PutAll(props);
                    props2.SetProperty("phraseScorerClass", "edu.stanford.nlp.patterns.ScorePhrasesLearnFeatWt");
                    ScorePhrases scoreclassifier = new ScorePhrases(props2, constVars);
                    System.Console.Out.WriteLine("file is " + props.GetProperty("domainNGramsFile"));
                    ArgumentParser.FillOptions(typeof(Data), props2);
                    classifierScores = scoreclassifier.phraseScorer.ScorePhrases(label, allCandidatePhrases, true);
                }
            }
            ICounter <CandidatePhrase> cachedScoresForThisIter = new ClassicCounter <CandidatePhrase>();

            foreach (KeyValuePair <E, ClassicCounter <CandidatePhrase> > en in positivePatternsAndWords.EntrySet())
            {
                foreach (KeyValuePair <CandidatePhrase, double> en2 in en.Value.EntrySet())
                {
                    CandidatePhrase word = en2.Key;
                    ICounter <ConstantsAndVariables.ScorePhraseMeasures> scoreslist = new ClassicCounter <ConstantsAndVariables.ScorePhraseMeasures>();
                    double score = 1;
                    if ((patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.PhEvalInPat) || patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.PhEvalInPatLogP)) && scorePhrasesInPatSelection)
                    {
                        if (cachedScoresForThisIter.ContainsKey(word))
                        {
                            score = cachedScoresForThisIter.GetCount(word);
                        }
                        else
                        {
                            if (constVars.GetOtherSemanticClassesWords().Contains(word) || constVars.GetCommonEngWords().Contains(word))
                            {
                                score = 1;
                            }
                            else
                            {
                                if (constVars.usePatternEvalSemanticOdds)
                                {
                                    double semanticClassOdds = 1;
                                    if (dictOddsWordWeights.ContainsKey(word))
                                    {
                                        semanticClassOdds = 1 - dictOddsWordWeights.GetCount(word);
                                    }
                                    scoreslist.SetCount(ConstantsAndVariables.ScorePhraseMeasures.Semanticodds, semanticClassOdds);
                                }
                                if (constVars.usePatternEvalGoogleNgram)
                                {
                                    double gscore = 0;
                                    if (googleNgramNormScores.ContainsKey(word))
                                    {
                                        gscore = 1 - googleNgramNormScores.GetCount(word);
                                    }
                                    scoreslist.SetCount(ConstantsAndVariables.ScorePhraseMeasures.Googlengram, gscore);
                                }
                                if (constVars.usePatternEvalDomainNgram)
                                {
                                    double domainscore;
                                    if (domainNgramNormScores.ContainsKey(word))
                                    {
                                        domainscore = 1 - domainNgramNormScores.GetCount(word);
                                    }
                                    else
                                    {
                                        domainscore = 1 - scorePhrases.phraseScorer.GetPhraseWeightFromWords(domainNgramNormScores, word, scorePhrases.phraseScorer.OOVDomainNgramScore);
                                    }
                                    scoreslist.SetCount(ConstantsAndVariables.ScorePhraseMeasures.Domainngram, domainscore);
                                }
                                if (constVars.usePatternEvalWordClass)
                                {
                                    double externalFeatureWt = externalWtsDefault;
                                    if (externalFeatWtsNormalized.ContainsKey(word))
                                    {
                                        externalFeatureWt = 1 - externalFeatWtsNormalized.GetCount(word);
                                    }
                                    scoreslist.SetCount(ConstantsAndVariables.ScorePhraseMeasures.Distsim, externalFeatureWt);
                                }
                                if (constVars.usePatternEvalEditDistOther)
                                {
                                    System.Diagnostics.Debug.Assert(editDistanceFromOtherSemanticBinaryScores.ContainsKey(word), "How come no edit distance info for word " + word + string.Empty);
                                    scoreslist.SetCount(ConstantsAndVariables.ScorePhraseMeasures.Editdistother, editDistanceFromOtherSemanticBinaryScores.GetCount(word));
                                }
                                if (constVars.usePatternEvalEditDistSame)
                                {
                                    scoreslist.SetCount(ConstantsAndVariables.ScorePhraseMeasures.Editdistsame, editDistanceFromAlreadyExtractedBinaryScores.GetCount(word));
                                }
                                // taking average
                                score = Counters.Mean(scoreslist);
                                phInPatScores.SetCounter(word, scoreslist);
                            }
                            cachedScoresForThisIter.SetCount(word, score);
                        }
                    }
                    else
                    {
                        if ((patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.Logreg) || patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.LOGREGlogP)) && scorePhrasesInPatSelection)
                        {
                            score = 1 - classifierScores.GetCount(word);
                        }
                    }
                    // score = 1 - scorePhrases.scoreUsingClassifer(classifier,
                    // e.getKey(), label, true, null, null, dictOddsWordWeights);
                    // throw new RuntimeException("not implemented yet");
                    if (useFreqPhraseExtractedByPat)
                    {
                        score = score * scoringFunction.ApplyAsDouble(new Pair <E, CandidatePhrase>(en.Key, word));
                    }
                    if (constVars.sqrtPatScore)
                    {
                        patterns.IncrementCount(en.Key, Math.Sqrt(score));
                    }
                    else
                    {
                        patterns.IncrementCount(en.Key, score);
                    }
                }
            }
            return(patterns);
        }
        /// <exception cref="System.IO.IOException"/>
        /// <exception cref="System.TypeLoadException"/>
        public override ICounter <E> Score()
        {
            ICounter <CandidatePhrase> externalWordWeightsNormalized = null;

            if (constVars.dictOddsWeights.Contains(label))
            {
                externalWordWeightsNormalized = GetPatternsFromDataMultiClass.NormalizeSoftMaxMinMaxScores(constVars.dictOddsWeights[label], true, true, false);
            }
            ICounter <E> currentPatternWeights4Label = new ClassicCounter <E>();
            bool         useFreqPhraseExtractedByPat = false;

            if (patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.SqrtAllRatio))
            {
                useFreqPhraseExtractedByPat = true;
            }
            IToDoubleFunction <Pair <E, CandidatePhrase> > numeratorScore = null;
            ICounter <E> numeratorPatWt   = this.Convert2OneDim(label, numeratorScore, allCandidatePhrases, patternsandWords4Label, constVars.sqrtPatScore, false, null, useFreqPhraseExtractedByPat);
            ICounter <E> denominatorPatWt = null;
            IToDoubleFunction <Pair <E, CandidatePhrase> > denoScore;

            if (patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.PosNegUnlabOdds))
            {
                denoScore        = null;
                denominatorPatWt = this.Convert2OneDim(label, denoScore, allCandidatePhrases, patternsandWords4Label, constVars.sqrtPatScore, false, externalWordWeightsNormalized, useFreqPhraseExtractedByPat);
            }
            else
            {
                if (patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.RatioAll))
                {
                    denoScore        = null;
                    denominatorPatWt = this.Convert2OneDim(label, denoScore, allCandidatePhrases, patternsandWords4Label, constVars.sqrtPatScore, false, externalWordWeightsNormalized, useFreqPhraseExtractedByPat);
                }
                else
                {
                    if (patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.PosNegOdds))
                    {
                        denoScore        = null;
                        denominatorPatWt = this.Convert2OneDim(label, denoScore, allCandidatePhrases, patternsandWords4Label, constVars.sqrtPatScore, false, externalWordWeightsNormalized, useFreqPhraseExtractedByPat);
                    }
                    else
                    {
                        if (patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.PhEvalInPat) || patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.PhEvalInPatLogP) || patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.
                                                                                                                                                                                                                            Logreg) || patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.LOGREGlogP))
                        {
                            denoScore        = null;
                            denominatorPatWt = this.Convert2OneDim(label, denoScore, allCandidatePhrases, patternsandWords4Label, constVars.sqrtPatScore, true, externalWordWeightsNormalized, useFreqPhraseExtractedByPat);
                        }
                        else
                        {
                            if (patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.SqrtAllRatio))
                            {
                                denoScore        = null;
                                denominatorPatWt = this.Convert2OneDim(label, denoScore, allCandidatePhrases, patternsandWords4Label, true, false, externalWordWeightsNormalized, useFreqPhraseExtractedByPat);
                            }
                            else
                            {
                                throw new Exception("Cannot understand patterns scoring");
                            }
                        }
                    }
                }
            }
            currentPatternWeights4Label = Counters.DivisionNonNaN(numeratorPatWt, denominatorPatWt);
            //Multiplying by logP
            if (patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.PhEvalInPatLogP) || patternScoring.Equals(GetPatternsFromDataMultiClass.PatternScoring.LOGREGlogP))
            {
                ICounter <E> logpos_i = new ClassicCounter <E>();
                foreach (KeyValuePair <E, ClassicCounter <CandidatePhrase> > en in patternsandWords4Label.EntrySet())
                {
                    logpos_i.SetCount(en.Key, Math.Log(en.Value.Size()));
                }
                Counters.MultiplyInPlace(currentPatternWeights4Label, logpos_i);
            }
            Counters.RetainNonZeros(currentPatternWeights4Label);
            return(currentPatternWeights4Label);
        }
 public EvalFunction(IToDoubleFunction <Node <S, A> > h)
 {
     this.h = h;
 }
Beispiel #11
0
 /**
  * Constructs a simulated annealing search from the specified heuristic
  * function and scheduler.
  *
  * @param h
  *            a heuristic function
  * @param scheduler
  *            a mapping from time to "temperature"
  */
 public SimulatedAnnealingSearch(IToDoubleFunction <Node <S, A> > h, Scheduler scheduler)
     : this(h, scheduler, new NodeExpander <S, A>())
 {
 }
Beispiel #12
0
 public BestFirstSearchComparer(IToDoubleFunction <Node <S, A> > evalFn)
 {
     this.evalFn = evalFn;
 }
 public HillClimbingSearch(IToDoubleFunction <Node <S, A> > h, NodeExpander <S, A> nodeExpander)
 {
     this.h            = h;
     this.nodeExpander = nodeExpander;
     nodeExpander.addNodeListener((node) => metrics.incrementInt(METRIC_NODES_EXPANDED));
 }
 public virtual IList <Match <K, V> > Segment <_T0>(IList <K> list, IToDoubleFunction <_T0> scoreFunc)
 {
     return(Segment(list, 0, list.Count, scoreFunc));
 }
 public virtual IList <Match <K, V> > GetNonOverlapping <_T0>(IList <Match <K, V> > allMatches, IToDoubleFunction <_T0> scoreFunc)
 {
     return(IntervalTree.GetNonOverlappingMaxScore(allMatches, scoreFunc));
 }
        /// <summary>Given a sequence to search through (e.g.</summary>
        /// <remarks>
        /// Given a sequence to search through (e.g. piece of text would be a sequence of words),
        /// finds all non-overlapping matching sub-sequences that matches entries in the trie while attempting to maximize the scoreFunc.
        /// </remarks>
        /// <param name="list">Sequence to search through</param>
        /// <param name="start">start index to start search at</param>
        /// <param name="end">end index (exclusive) to end search at</param>
        /// <param name="scoreFunc">Scoring function indicating how good the match is</param>
        /// <returns>List of matches sorted by start position</returns>
        public virtual IList <Match <K, V> > FindNonOverlapping <_T0>(IList <K> list, int start, int end, IToDoubleFunction <_T0> scoreFunc)
        {
            IList <Match <K, V> > allMatches = FindAllMatches(list, start, end);

            return(GetNonOverlapping(allMatches, scoreFunc));
        }
        /// <summary>
        /// Segment a sequence into sequence of sub-sequences by attempting to maximize the total score
        /// Non-matched parts will be included as a match with a null value.
        /// </summary>
        /// <param name="list">Sequence to search through</param>
        /// <param name="start">start index to start search at</param>
        /// <param name="end">end index (exclusive) to end search at</param>
        /// <param name="scoreFunc">Scoring function indicating how good the match is</param>
        /// <returns>List of segments (as matches) sorted by start position</returns>
        public virtual IList <Match <K, V> > Segment <_T0>(IList <K> list, int start, int end, IToDoubleFunction <_T0> scoreFunc)
        {
            IList <Match <K, V> > nonOverlapping = FindNonOverlapping(list, start, end, scoreFunc);
            IList <Match <K, V> > segments       = new List <Match <K, V> >(nonOverlapping.Count);
            int last = 0;

            foreach (Match <K, V> match in nonOverlapping)
            {
                if (match.begin > last)
                {
                    // Create empty match and add to segments
                    Match <K, V> empty = new Match <K, V>(list.SubList(last, match.begin), null, last, match.begin);
                    segments.Add(empty);
                }
                segments.Add(match);
                last = match.end;
            }
            if (list.Count > last)
            {
                Match <K, V> empty = new Match <K, V>(list.SubList(last, list.Count), null, last, list.Count);
                segments.Add(empty);
            }
            return(segments);
        }
Beispiel #18
0
        /// <summary>
        /// This method will cross validate on the given data and number of folds
        /// to find the optimal C.
        /// </summary>
        /// <remarks>
        /// This method will cross validate on the given data and number of folds
        /// to find the optimal C.  The scorer is how you determine what to
        /// optimize for (F-score, accuracy, etc).  The C is then saved, so that
        /// if you train a classifier after calling this method, that C will be used.
        /// </remarks>
        public virtual void CrossValidateSetC(GeneralDataset <L, F> dataset, int numFolds, IScorer <L> scorer, ILineSearcher minimizer)
        {
            System.Console.Out.WriteLine("in Cross Validate");
            useAlphaFile = true;
            bool oldUseSigmoid = useSigmoid;

            useSigmoid = false;
            CrossValidator <L, F> crossValidator = new CrossValidator <L, F>(dataset, numFolds);
            IToDoubleFunction <Triple <GeneralDataset <L, F>, GeneralDataset <L, F>, CrossValidator.SavedState> > score = null;
            //train(trainSet,true,true);
            IDoubleUnaryOperator negativeScorer = null;

            C            = minimizer.Minimize(negativeScorer);
            useAlphaFile = false;
            useSigmoid   = oldUseSigmoid;
        }
Beispiel #19
0
        /**
         * Creates a search instance.
         *
         * @param strategy
         *            search strategy. See static constants.
         * @param qSearchImpl
         *            queue search implementation: e.g. {@link #TREE_SEARCH}, {@link #GRAPH_SEARCH}
         *
         */
        public ISearchForActions <S, A> createSearch <S, A>(int strategy, int qSearchImpl, IToDoubleFunction <Node <S, A> > h)
        {
            QueueSearch <S, A>       qs     = null;
            ISearchForActions <S, A> result = null;

            switch (qSearchImpl)
            {
            case TREE_SEARCH:
                qs = new TreeSearch <S, A>();
                break;

            case GRAPH_SEARCH:
                qs = new GraphSearch <S, A>();
                break;

            case GRAPH_SEARCH_RED_FRONTIER:
                qs = new GraphSearchReducedFrontier <S, A>();
                break;

            case GRAPH_SEARCH_BFS:
                qs = new GraphSearchBFS <S, A>();
                break;

            case BIDIRECTIONAL_SEARCH:
                qs = new BidirectionalSearch <S, A>();
                break;
            }
            switch (strategy)
            {
            case DF_SEARCH:
                result = new DepthFirstSearch <S, A>(qs);
                break;

            case BF_SEARCH:
                result = new BreadthFirstSearch <S, A>(qs);
                break;

            case ID_SEARCH:
                result = new IterativeDeepeningSearch <S, A>();
                break;

            case UC_SEARCH:
                result = new UniformCostSearch <S, A>(qs);
                break;

            case GBF_SEARCH:
                result = new GreedyBestFirstSearch <S, A>(qs, h);
                break;

            case ASTAR_SEARCH:
                result = new AStarSearch <S, A>(qs, h);
                break;

            case RBF_SEARCH:
                result = new RecursiveBestFirstSearch <S, A>(new AStarSearch <S, A> .EvalFunction(h));
                break;

            case RBF_AL_SEARCH:
                result = new RecursiveBestFirstSearch <S, A>(new AStarSearch <S, A> .EvalFunction(h), true);
                break;

            case HILL_SEARCH:
                result = new HillClimbingSearch <S, A>(h);
                break;
            }
            return(result);
        }
        public static IList <T> GetNonOverlappingMaxScore <T, E, _T2, _T3>(IList <_T2> items, IToDoubleFunction <_T3> scoreFunc)
            where T : IHasInterval <E>
            where E : IComparable <E>
            where _T2 : T
        {
            IFunction <T, Interval <E> > toIntervalFunc = null;

            return(GetNonOverlappingMaxScore(items, toIntervalFunc, scoreFunc));
        }
Beispiel #21
0
 /**
  * Constructs a LRTA* agent with the specified search problem, percept to
  * state function, and heuristic function.
  *
  * @param problem
  *            an online search problem for this agent to solve.
  * @param ptsFn
  *            a function which returns the problem state associated with a
  *            given Percept.
  * @param h
  *            heuristic function <em>h(n)</em>, which estimates the cost of
  *            the cheapest path from the state at node <em>n</em> to a goal
  *            state.
  */
 public LRTAStarAgent(IOnlineSearchProblem <S, A> problem, Function <IPercept, S> ptsFn, IToDoubleFunction <S> h)
 {
     setProblem(problem);
     setPerceptToStateFunction(ptsFn);
     setHeuristicFunction(h);
 }
 /**
  * Constructs a hill-climbing search from the specified heuristic function.
  *
  * @param h a heuristic function
  */
 public HillClimbingSearch(IToDoubleFunction <Node <S, A> > h)
     : this(h, new NodeExpander <S, A>())
 {
 }
Beispiel #23
0
 public virtual void setHeuristicFunction(IToDoubleFunction <Node <S, A> > h)
 {
     this.h = h;
 }
Beispiel #24
0
 /**
  * Constructor which allows to enable the loop avoidance strategy.
  */
 public RecursiveBestFirstSearch(IToDoubleFunction <Node <S, A> > evalFn, bool avoidLoops)
     : this(evalFn, avoidLoops, new NodeExpander <S, A>())
 {
 }
Beispiel #25
0
 /**
  * Constructs a best first search from a specified search problem and
  * evaluation function.
  *
  * @param impl
  *            a search space exploration strategy.
  * @param evalFn
  *            an evaluation function, which returns a number purporting to
  *            describe the desirability (or lack thereof) of expanding a
  *            node.
  */
 public BestFirstSearch(QueueSearch <S, A> impl, IToDoubleFunction <Node <S, A> > evalFn)
     : base(impl, CollectionFactory.CreatePriorityQueue <Node <S, A> >(new BestFirstSearchComparer(evalFn)))
 {
     this.evalFn = evalFn;
 }
 public static IList <T> GetNonOverlappingMaxScore <T, E, _T2, _T3, _T4>(IList <_T2> items, IFunction <_T3> toIntervalFunc, IToDoubleFunction <_T4> scoreFunc)
     where E : IComparable <E>
     where _T2 : T
 {
     if (items.Count > 1)
     {
         IDictionary <E, IntervalTree.PartialScoredList <T, E> > bestNonOverlapping = new SortedDictionary <E, IntervalTree.PartialScoredList <T, E> >();
         foreach (T item in items)
         {
             Interval <E> itemInterval = toIntervalFunc.Apply(item);
             E            mBegin       = itemInterval.GetBegin();
             E            mEnd         = itemInterval.GetEnd();
             IntervalTree.PartialScoredList <T, E> bestk = bestNonOverlapping[mEnd];
             double itemScore = scoreFunc.ApplyAsDouble(item);
             if (bestk == null)
             {
                 bestk                    = new IntervalTree.PartialScoredList <T, E>();
                 bestk.size               = 1;
                 bestk.score              = itemScore;
                 bestk.@object            = item;
                 bestNonOverlapping[mEnd] = bestk;
             }
             // Assumes map is ordered
             foreach (E j in bestNonOverlapping.Keys)
             {
                 if (j.CompareTo(mBegin) > 0)
                 {
                     break;
                 }
                 // Consider adding this match into the bestNonOverlapping strand at j
                 IntervalTree.PartialScoredList <T, E> bestj = bestNonOverlapping[j];
                 double withMatchScore = bestj.score + itemScore;
                 bool   better         = false;
                 if (withMatchScore > bestk.score)
                 {
                     better = true;
                 }
                 else
                 {
                     if (withMatchScore == bestk.score)
                     {
                         if (bestj.size + 1 < bestk.size)
                         {
                             better = true;
                         }
                     }
                 }
                 if (better)
                 {
                     bestk.size         = bestj.size + 1;
                     bestk.score        = withMatchScore;
                     bestk.@object      = item;
                     bestk.lastMatchKey = j;
                 }
             }
         }
         IntervalTree.PartialScoredList <T, E> best = null;
         foreach (IntervalTree.PartialScoredList <T, E> v in bestNonOverlapping.Values)
         {
             if (best == null || v.score > best.score)
             {
                 best = v;
             }
         }
         IList <T> nonOverlapping = new List <T>(best.size);
         IntervalTree.PartialScoredList <T, E> prev = best;
         while (prev != null)
         {
             if (prev.@object != null)
             {
                 nonOverlapping.Add(prev.@object);
             }
             if (prev.lastMatchKey != null)
             {
                 prev = bestNonOverlapping[prev.lastMatchKey];
             }
             else
             {
                 prev = null;
             }
         }
         Java.Util.Collections.Reverse(nonOverlapping);
         return(nonOverlapping);
     }
     else
     {
         IList <T> nonOverlapping = new List <T>(items);
         return(nonOverlapping);
     }
 }
 /**
  * Constructs a greedy best-first search from a specified search space
  * exploration strategy and a heuristic function.
  *
  * @param impl
  *            a search space exploration strategy (e.g. TreeSearch,
  *            GraphSearch).
  * @param h
  *            a heuristic function <em>h(n)</em>, which estimates the
  *            cheapest path from the state at node <em>n</em> to a goal
  *            state.
  */
 public GreedyBestFirstSearch(QueueSearch <S, A> impl, IToDoubleFunction <Node <S, A> > h)
     : base(impl, new EvalFunction(h))
 {
 }
Beispiel #28
0
 public BoundedCostOrderedMap(IToDoubleFunction <V> costFunction, int maxSize, double maxCost)
 {
     this.costFunction = costFunction;
     this.maxSize      = maxSize;
     this.maxCost      = maxCost;
 }
Beispiel #29
0
 public RecursiveBestFirstSearch(IToDoubleFunction <Node <S, A> > evalFn)
     : this(evalFn, false)
 {
 }
Beispiel #30
0
 /**
  * Constructs a simulated annealing search from the specified heuristic
  * function and a default scheduler.
  *
  * @param h
  *            a heuristic function
  */
 public SimulatedAnnealingSearch(IToDoubleFunction <Node <S, A> > h)
     : this(h, new Scheduler())
 {
 }