Free cookie consent management tool by TermsFeed Policy Generator

Changeset 15957


Ignore:
Timestamp:
06/13/18 14:41:46 (4 years ago)
Author:
bburlacu
Message:

#2886: Minor refactor; fix multiple analyzer event registration

File:
1 edited

Legend:

Unmodified
Added
Removed
  • branches/2886_SymRegGrammarEnumeration/HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration/GrammarEnumeration/GrammarEnumerationAlgorithm.cs

    r15950 r15957  
    44using System.Threading;
    55using HeuristicLab.Algorithms.DataAnalysis.SymRegGrammarEnumeration.GrammarEnumeration;
     6using HeuristicLab.Collections;
    67using HeuristicLab.Common;
    78using HeuristicLab.Core;
     
    128129
    129130    public GrammarEnumerationAlgorithm() {
    130       Problem = new RegressionProblem() {
    131         ProblemData = new HeuristicLab.Problems.Instances.DataAnalysis.PolyTen(seed: 1234).GenerateRegressionData()
    132       };
    133 
    134131      Parameters.Add(new ValueParameter<DoubleValue>(VariableImportanceWeightName, "Variable Weight.", new DoubleValue(1.0)));
    135132      Parameters.Add(new ValueParameter<BoolValue>(OptimizeConstantsParameterName, "Run constant optimization in sentence evaluation.", new BoolValue(false)));
     
    148145        new CheckedItemCollection<IGrammarEnumerationAnalyzer>(availableAnalyzers).AsReadOnly()));
    149146
     147      Analyzers.CheckedItemsChanged += Analyzers_CheckedItemsChanged;
     148
    150149      foreach (var analyzer in Analyzers) {
    151150        Analyzers.SetItemCheckedState(analyzer, false);
    152151      }
    153152      Analyzers.SetItemCheckedState(Analyzers.First(analyzer => analyzer is RSquaredEvaluator), true);
    154       //Analyzers.SetItemCheckedState(Analyzers.First(analyzer => analyzer is SentenceLogger), true);
    155153
    156154      var grammarSymbols = Enum.GetValues(typeof(GrammarRule))
     
    165163        GrammarSymbols.SetItemCheckedState(grammarSymbol, true);
    166164      }
     165
     166      // set a default problem
     167      Problem = new RegressionProblem() {
     168        ProblemData = new HeuristicLab.Problems.Instances.DataAnalysis.PolyTen(seed: 1234).GenerateRegressionData()
     169      };
    167170    }
    168171
    169172    public GrammarEnumerationAlgorithm(GrammarEnumerationAlgorithm original, Cloner cloner) : base(original, cloner) {
     173      foreach (var analyzer in Analyzers.CheckedItems)
     174        analyzer.Register(this);
     175      Analyzers.CheckedItemsChanged += Analyzers_CheckedItemsChanged;
    170176    }
    171177    #endregion
     
    173179    private Dictionary<VariableTerminalSymbol, double> variableImportance;
    174180
    175     protected override void Run(CancellationToken cancellationToken) {
    176       #region init
    177       InitResults();
    178 
    179       foreach (IGrammarEnumerationAnalyzer grammarEnumerationAnalyzer in Analyzers) {
    180         if (Analyzers.ItemChecked(grammarEnumerationAnalyzer)) {
    181           grammarEnumerationAnalyzer.Register(this);
    182         } else {
    183           grammarEnumerationAnalyzer.Deregister(this);
    184         }
    185       }
    186 
    187       Analyzers.OfType<RSquaredEvaluator>().First().OptimizeConstants = OptimizeConstants;
    188 
     181    public override void Prepare() {
     182      DistinctSentencesComplexity = new Dictionary<int, int>();
    189183      ArchivedPhrases = new HashSet<int>();
    190 
    191       DistinctSentencesComplexity = new Dictionary<int, int>();
    192184      AllGeneratedSentencesCount = 0;
    193185      OverwrittenSentencesCount = 0;
    194186      PhraseExpansionCount = 0;
    195187
     188      Analyzers.OfType<RSquaredEvaluator>().First().OptimizeConstants = OptimizeConstants;
    196189      Grammar = new Grammar(Problem.ProblemData.AllowedInputVariables.ToArray(), GrammarSymbols.CheckedItems.Select(v => v.Value));
    197 
    198190      OpenPhrases = new SearchDataStore(SearchDataStructure); // Select search strategy
     191
     192      base.Prepare(); // this actually clears the results which will get reinitialized on Run()
     193    }
     194
     195    protected override void Run(CancellationToken cancellationToken) {
     196      InitResults();
    199197      var phrase0 = new SymbolString(new[] { Grammar.StartSymbol });
    200198      var phrase0Hash = Grammar.Hasher.CalcHashCode(phrase0);
    201       #endregion
    202199
    203200      #region Variable Importance
     
    249246          int newPhraseComplexity = Grammar.GetComplexity(newPhrase);
    250247
    251           if (newPhraseComplexity <= MaxComplexity) {
    252             var phraseHash = Grammar.Hasher.CalcHashCode(newPhrase);
    253 
    254             OnPhraseDerived(fetchedSearchNode.Hash, fetchedSearchNode.SymbolString, phraseHash, newPhrase, expandedSymbol, appliedProductions[i]);
    255 
    256             if (newPhrase.IsSentence()) {
    257               AllGeneratedSentencesCount++;
    258 
    259               OnSentenceGenerated(fetchedSearchNode.Hash, fetchedSearchNode.SymbolString, phraseHash, newPhrase, expandedSymbol, appliedProductions[i]);
    260 
    261               // Is the best solution found? (only if RSquaredEvaluator is activated)
    262               if (Results.ContainsKey(RSquaredEvaluator.BestTrainingQualityResultName)) {
    263                 double r2 = ((DoubleValue)Results[RSquaredEvaluator.BestTrainingQualityResultName].Value).Value;
    264                 if (r2.IsAlmost(1.0)) {
    265                   UpdateView(force: true);
    266                   return;
    267                 }
     248          if (newPhraseComplexity > MaxComplexity)
     249            continue;
     250
     251          var phraseHash = Grammar.Hasher.CalcHashCode(newPhrase);
     252
     253          OnPhraseDerived(fetchedSearchNode.Hash, fetchedSearchNode.SymbolString, phraseHash, newPhrase, expandedSymbol, appliedProductions[i]);
     254
     255          if (newPhrase.IsSentence()) {
     256            AllGeneratedSentencesCount++;
     257
     258            OnSentenceGenerated(fetchedSearchNode.Hash, fetchedSearchNode.SymbolString, phraseHash, newPhrase, expandedSymbol, appliedProductions[i]);
     259
     260            // Is the best solution found? (only if RSquaredEvaluator is activated)
     261            if (Results.ContainsKey(RSquaredEvaluator.BestTrainingQualityResultName)) {
     262              double r2 = ((DoubleValue)Results[RSquaredEvaluator.BestTrainingQualityResultName].Value).Value;
     263              if (r2.IsAlmost(1.0)) {
     264                UpdateView(force: true);
     265                return;
    268266              }
    269 
    270               if (!DistinctSentencesComplexity.ContainsKey(phraseHash) || DistinctSentencesComplexity[phraseHash] > newPhraseComplexity) {
    271                 if (DistinctSentencesComplexity.ContainsKey(phraseHash)) OverwrittenSentencesCount++; // for analysis only
    272 
    273                 DistinctSentencesComplexity[phraseHash] = newPhraseComplexity;
    274                 OnDistinctSentenceGenerated(fetchedSearchNode.Hash, fetchedSearchNode.SymbolString, phraseHash, newPhrase, expandedSymbol, appliedProductions[i]);
    275               }
    276               UpdateView();
    277 
    278             } else if (!OpenPhrases.Contains(phraseHash) && !ArchivedPhrases.Contains(phraseHash)) {
    279 
    280               double r2 = GetR2(newPhrase, fetchedSearchNode.R2);
    281               double phrasePriority = GetPriority(newPhrase, r2, maxSentenceLength, errorWeight, variableImportanceWeight);
    282 
    283               SearchNode newSearchNode = new SearchNode(phraseHash, phrasePriority, r2, newPhrase);
    284               OpenPhrases.Store(newSearchNode);
    285267            }
     268
     269            if (!DistinctSentencesComplexity.ContainsKey(phraseHash) || DistinctSentencesComplexity[phraseHash] > newPhraseComplexity) {
     270              if (DistinctSentencesComplexity.ContainsKey(phraseHash)) OverwrittenSentencesCount++; // for analysis only
     271
     272              DistinctSentencesComplexity[phraseHash] = newPhraseComplexity;
     273              OnDistinctSentenceGenerated(fetchedSearchNode.Hash, fetchedSearchNode.SymbolString, phraseHash, newPhrase, expandedSymbol, appliedProductions[i]);
     274            }
     275            UpdateView();
     276
     277          } else if (!OpenPhrases.Contains(phraseHash) && !ArchivedPhrases.Contains(phraseHash)) {
     278
     279            double r2 = GetR2(newPhrase, fetchedSearchNode.R2);
     280            double phrasePriority = GetPriority(newPhrase, r2, maxSentenceLength, errorWeight, variableImportanceWeight);
     281
     282            SearchNode newSearchNode = new SearchNode(phraseHash, phrasePriority, r2, newPhrase);
     283            OpenPhrases.Store(newSearchNode);
    286284          }
    287285        }
     
    349347    // Initialize entries in result set.
    350348    private void InitResults() {
     349      Results.Clear();
    351350      Results.Add(new Result(GeneratedPhrasesName, new IntValue(0)));
    352351      Results.Add(new Result(SearchStructureSizeName, new IntValue(0)));
     
    379378
    380379    #region events
     380
     381    // private event handlers for analyzers
     382    private void Analyzers_CheckedItemsChanged(object sender, CollectionItemsChangedEventArgs<IGrammarEnumerationAnalyzer> args) {
     383      // newly added items
     384      foreach (var item in args.Items.Except(args.OldItems).Union(args.OldItems.Except(args.Items))) {
     385        if (Analyzers.ItemChecked(item)) {
     386          item.Register(this);
     387        } else {
     388          item.Deregister(this);
     389        }
     390      }
     391    }
     392
    381393    public event EventHandler<PhraseEventArgs> PhraseFetched;
    382394    private void OnPhraseFetched(int hash, SymbolString symbolString) {
Note: See TracChangeset for help on using the changeset viewer.