Free cookie consent management tool by TermsFeed Policy Generator

source: branches/CEDMA-Exporter-715/sources/HeuristicLab.FixedOperators/3.2/FixedSAMain.cs @ 3921

Last change on this file since 3921 was 2158, checked in by dtraxing, 15 years ago

FixedGAMainBase: fixed type in operator name; added virtual modifier to GetOperatorsFromScope Method
FixedOperatorBase: removed general exception catching
added fixed operator for evolution strategies
(ticket #580)

File size: 8.7 KB
Line 
1using System;
2using System.Collections.Generic;
3using System.Linq;
4using System.Text;
5using HeuristicLab.Core;
6using HeuristicLab.Selection;
7using HeuristicLab.Operators;
8using HeuristicLab.Operators.Programmable;
9using HeuristicLab.SA;
10using HeuristicLab.Logging;
11using HeuristicLab.Data;
12
13namespace HeuristicLab.FixedOperators {
14  class FixedSAMain : FixedOperatorBase{
15    protected LeftSelector ls;
16    protected RightReducer rr;
17    protected LeftReducer lr;
18    protected EmptyOperator empty;
19    protected ProgrammableOperator fastFitnessComparer;
20    protected ProgrammableOperator moduloComparer;
21    protected MultiplicativeAnnealing multiAnnealing;
22    protected Counter iterationCounter;
23    protected Counter evalSolutionsCounter;
24    protected OperatorBase mutator;
25    protected OperatorBase evaluator;
26    protected BestAverageWorstQualityCalculator bawqc;
27    protected DataCollector dc;
28    protected LinechartInjector lci;
29    protected ConditionalBranch acceptMutant;
30    protected ConditionalBranch logInterval;
31
32    public FixedSAMain() {
33      Name = this.GetType().Name;
34      Init();
35    } // FixedSAMain
36
37    private void Init() {
38      ls = new LeftSelector();
39      ls.GetVariable("CopySelected").GetValue<BoolData>().Data = true;
40      ls.GetVariableInfo("Selected").Local = true;
41      ls.AddVariable(new Variable("Selected", new IntData(1)));
42
43      rr = new RightReducer();
44      lr = new LeftReducer();
45      empty = new EmptyOperator();
46     
47      fastFitnessComparer = new ProgrammableOperator();
48      fastFitnessComparer.Code = @"string qualityString = scope.TranslateName(""Quality"");
49      IScope mutant = scope.SubScopes[1].SubScopes[0];
50      double mutantQuality = mutant.GetVariableValue<DoubleData>(qualityString, false).Data;
51      double parentQuality = scope.SubScopes[0].SubScopes[0].GetVariableValue<DoubleData>(qualityString, false).Data;
52
53      if (mutantQuality < parentQuality) {
54        BoolData sc = op.GetVariableValue<BoolData>(""AcceptMutant"", scope, false, false);
55        if (sc == null) {
56          scope.AddVariable(new Variable(""AcceptMutant"", new BoolData(true)));
57        } else sc.Data = true;
58        return null;
59      }
60
61
62      double temperature = op.GetVariableValue<DoubleData>(""Temperature"", scope, true).Data;
63      double probability = Math.Exp(-Math.Abs(mutantQuality - parentQuality) / temperature);
64      IRandom random = op.GetVariableValue<IRandom>(""Random"", scope, true);
65      bool success = random.NextDouble() < probability;
66      BoolData sc2 = op.GetVariableValue<BoolData>(""AcceptMutant"", scope, false, false);
67      if (sc2 == null) {
68        scope.AddVariable(new Variable(""AcceptMutant"", new BoolData(success)));
69      } else sc2.Data = success;
70      return null;";
71      fastFitnessComparer.AddVariableInfo(new VariableInfo("AcceptMutant", "AcceptMutant", typeof(BoolData), VariableKind.New | VariableKind.Out));
72      fastFitnessComparer.AddVariableInfo(new VariableInfo("Random", "Random", typeof(IRandom), VariableKind.In));
73      fastFitnessComparer.AddVariableInfo(new VariableInfo("Temperature", "Temperature", typeof(DoubleData), VariableKind.In));
74
75      moduloComparer = new ProgrammableOperator();
76      moduloComparer.Code = @"Result.Data = (LeftSide.Data % Periodicity.Data == RightSide.Data);";
77      moduloComparer.AddVariableInfo(new VariableInfo("LeftSide", "LeftSide", typeof(IntData), VariableKind.In));
78      moduloComparer.GetVariableInfo("LeftSide").ActualName = "Iteration";
79      //moduloComparer.AddVariableInfo(new VariableInfo("Result", "LogCondition", typeof(BoolData), VariableKind.New | VariableKind.Out));
80      moduloComparer.GetVariableInfo("Result").ActualName = "LogCondition";
81      moduloComparer.AddVariableInfo(new VariableInfo("Periodicity", "Periodicity", typeof(IntData), VariableKind.In));
82      moduloComparer.GetVariableInfo("Periodicity").ActualName = "LogInterval";
83      moduloComparer.AddVariableInfo(new VariableInfo("RightSide", "RightSide", typeof(IntData), VariableKind.In));
84      moduloComparer.GetVariableInfo("RightSide").Local = true;
85      moduloComparer.AddVariable(new Variable("RightSide", new IntData(0)));
86
87
88      multiAnnealing = new MultiplicativeAnnealing();
89      iterationCounter = new Counter();
90      iterationCounter.GetVariableInfo("Value").ActualName = "Iteration";
91      evalSolutionsCounter = new Counter();
92      evalSolutionsCounter.GetVariableInfo("Value").ActualName = "EvaluatedSolutions";
93
94
95      bawqc = new BestAverageWorstQualityCalculator();
96      bawqc.GetVariableInfo("AverageQuality").Local = true;
97      bawqc.GetVariableInfo("WorstQuality").Local = true;
98      bawqc.AddVariable(new Variable("AverageQuality", new DoubleData(6601)));
99      bawqc.AddVariable(new Variable("WorstQuality", new DoubleData(6601)));
100     
101      dc = new DataCollector();
102      dc.GetVariableInfo("Values").ActualName = "QualityValues";
103
104      ItemList<StringData> names = dc.GetVariable("VariableNames").GetValue<ItemList<StringData>>();
105      names.Add(new StringData("BestQuality"));
106
107      lci = new LinechartInjector();
108      lci.GetVariableInfo("Linechart").ActualName = "QualityLinechart";
109      lci.GetVariableInfo("Values").ActualName = "QualityValues";
110      lci.GetVariable("NumberOfLines").GetValue<IntData>().Data = 1;
111
112      acceptMutant = new ConditionalBranch();
113      acceptMutant.GetVariableInfo("Condition").ActualName = "AcceptMutant";
114      acceptMutant.AddSubOperator(rr);
115      acceptMutant.AddSubOperator(lr);
116
117      SequentialProcessor sp = new SequentialProcessor();
118      logInterval = new ConditionalBranch();
119      logInterval.GetVariableInfo("Condition").ActualName = "LogCondition";
120      logInterval.AddSubOperator(sp);
121      sp.AddSubOperator(bawqc);
122      sp.AddSubOperator(dc);
123      sp.AddSubOperator(lci);
124
125    } // Init
126
127    public override IOperation Apply(IScope scope) {
128      base.Apply(scope);
129
130
131      IntData maxIterations = scope.GetVariableValue<IntData>("MaximumIterations", false);
132      IntData nrOfIterations = scope.GetVariableValue<IntData>("Iteration", false);
133      IntData subscopeNr;
134
135      try {
136        subscopeNr = scope.GetVariableValue<IntData>("SubScopeNr", false);
137      }
138      catch (Exception) {
139        subscopeNr = new IntData(0);
140        scope.AddVariable(new Variable("SubScopeNr", subscopeNr));
141      }
142
143      DoubleData temperature = null;
144      DoubleData minTemperature = null;
145      try {
146        temperature = scope.GetVariableValue<DoubleData>("Temperature", false);
147        minTemperature = scope.GetVariableValue<DoubleData>("MinimumTemperature", false);
148      }
149      catch (Exception) {
150      }
151
152
153      //GetOperatorsFromScope(scope);
154
155
156      IScope s;
157      IScope s2;
158      bool loopSkipped = true;
159      tempExePointer = new int[10];
160      tempPersExePointer = new int[10];
161
162      mutator = scope.GetVariableValue<OperatorBase>("Mutator", false);
163      evaluator = scope.GetVariableValue<OperatorBase>("Evaluator", false);
164
165      try {
166        for (; nrOfIterations.Data < maxIterations.Data; nrOfIterations.Data++) {
167
168          Execute(ls, scope);
169          s = scope.SubScopes[1];
170
171          SaveExecutionPointer(0);
172          // UniformSequentialSubScopesProcessor
173          for (; subscopeNr.Data < s.SubScopes.Count; subscopeNr.Data++) {
174            SetExecutionPointerToLastSaved(0);
175            s2 = s.SubScopes[subscopeNr.Data];
176            Execute(mutator, s2);
177            Execute(evaluator, s2);
178            Execute(evalSolutionsCounter, s2);
179            loopSkipped = false;
180          } // foreach
181
182          // if for loop skipped, we had to add skiped operations
183          // to execution pointer.
184          if (loopSkipped)
185            executionPointer += 3;
186
187          Execute(fastFitnessComparer, scope);
188          Execute(acceptMutant, scope);
189          Execute(moduloComparer, scope);
190          Execute(logInterval, scope);
191          Execute(multiAnnealing, scope);
192          subscopeNr.Data = 0;
193          ResetExecutionPointer();
194          if (temperature.Data <= minTemperature.Data)
195            break;
196        } // for nrOfGenerations
197
198      } // try
199      catch (CancelException) {
200        return new AtomicOperation(this, scope);
201      }
202      catch (Exception ex) {
203        System.Diagnostics.StackTrace trace = new System.Diagnostics.StackTrace(ex, false);
204
205        foreach (var sf in trace.GetFrames()) {
206          Console.WriteLine(sf.GetMethod().Name);
207          Console.WriteLine("Line: " + sf.GetFileLineNumber());
208          Console.WriteLine("Column: " + sf.GetFileColumnNumber());
209        }
210      }
211      return null;
212    } // Apply
213
214
215  } // class FixedSAMain
216} // namespace HeuristicLab.FixedOperators
Note: See TracBrowser for help on using the repository browser.