Changeset 2202 for branches/GP-Refactoring-713/sources/HeuristicLab.GP
- Timestamp:
- 07/28/09 19:24:23 (15 years ago)
- Location:
- branches/GP-Refactoring-713
- Files:
-
- 2 added
- 8 deleted
- 17 edited
- 9 copied
Legend:
- Unmodified
- Added
- Removed
-
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/BakedFunctionTree.cs
r2174 r2202 34 34 public byte arity = 0; 35 35 public IFunction functionType; 36 public List< object> localData = new List<object>();36 public List<IVariable> localData = new List<IVariable>(); 37 37 38 38 public LightWeightFunction Clone() { … … 40 40 clone.arity = arity; 41 41 clone.functionType = functionType; 42 clone.localData .AddRange(localData);42 clone.localData = localData.Select(v=>(IVariable)v.Clone()).ToList(); 43 43 return clone; 44 44 } … … 57 57 private List<IFunctionTree> subTrees; 58 58 private bool variablesExpanded = false; 59 private List<IVariable> variables; 59 private List<IVariable> variables = new List<IVariable>(); 60 61 public IOperator Initializer { 62 get { return Function.Initializer; } 63 } 64 65 public IOperator Manipulator { 66 get { return Function.Manipulator; } 67 } 60 68 61 69 public BakedFunctionTree() { … … 63 71 } 64 72 65 internalBakedFunctionTree(IFunction function)73 public BakedFunctionTree(IFunction function) 66 74 : this() { 67 75 LightWeightFunction fun = new LightWeightFunction(); … … 72 80 variables = new List<IVariable>(); 73 81 variablesExpanded = true; 74 foreach (IVariableInfo variableInfo in function.VariableInfos) { 75 if (variableInfo.Local) { 76 variables.Add((IVariable)function.GetVariable(variableInfo.FormalName).Clone()); 77 } 78 } 79 } 80 81 internal BakedFunctionTree(IFunctionTree tree) 82 : this() { 83 LightWeightFunction fun = new LightWeightFunction(); 84 fun.functionType = tree.Function; 85 linearRepresentation.Add(fun); 86 foreach (IVariable variable in tree.LocalVariables) { 87 IObjectData value = (IObjectData)variable.Value; 88 fun.localData.Add(value.Data); 89 } 90 foreach (IFunctionTree subTree in tree.SubTrees) { 91 AddSubTree(new BakedFunctionTree(subTree)); 92 } 93 } 82 } 83 84 //internal BakedFunctionTree(IFunctionTree tree) 85 // : this() { 86 // LightWeightFunction fun = new LightWeightFunction(); 87 // fun.functionType = tree.Function; 88 // linearRepresentation.Add(fun); 89 // foreach (IVariable variable in tree.LocalVariables) { 90 // IObjectData value = (IObjectData)variable.Value; 91 // fun.localData.Add(value.Data); 92 // } 93 // foreach (IFunctionTree subTree in tree.SubTrees) { 94 // AddSubTree(new BakedFunctionTree(subTree)); 95 // } 96 //} 94 97 95 98 private int BranchLength(int branchRoot) { … … 119 122 linearRepresentation[0].localData.Clear(); 120 123 foreach (IVariable variable in variables) { 121 object objData = variable.Value; 122 while (objData is IObjectData) objData = ((IObjectData)objData).Data; 123 linearRepresentation[0].localData.Add(objData); 124 //object objData = variable.Value; 125 //while (objData is IObjectData) objData = ((IObjectData)objData).Data; 126 //linearRepresentation[0].localData[variable.Name] = objData; 127 linearRepresentation[0].localData.Add(variable); 124 128 } 125 129 variablesExpanded = false; … … 197 201 if (!variablesExpanded) { 198 202 variables = new List<IVariable>(); 199 IFunction function = Function; 200 int localVariableIndex = 0; 201 foreach (IVariableInfo variableInfo in function.VariableInfos) { 202 if (variableInfo.Local) { 203 IVariable clone = (IVariable)function.GetVariable(variableInfo.FormalName).Clone(); 204 IObjectData objData = (IObjectData)clone.Value; 205 if (objData is ConstrainedDoubleData) { 206 ((ConstrainedDoubleData)objData).Data = (double)linearRepresentation[0].localData[localVariableIndex]; 207 } else if (objData is ConstrainedIntData) { 208 ((ConstrainedIntData)objData).Data = (int)linearRepresentation[0].localData[localVariableIndex]; 209 } else { 210 objData.Data = linearRepresentation[0].localData[localVariableIndex]; 211 } 212 variables.Add(clone); 213 localVariableIndex++; 214 } 203 IFunction function = Function; 204 //int localVariableIndex = 0; 205 foreach (IVariable v in linearRepresentation[0].localData) { 206 //IObjectData objData = (IObjectData)clone.Value; 207 //if (objData is ConstrainedDoubleData) { 208 // ((ConstrainedDoubleData)objData).Data = (double)linearRepresentation[0].localData[localVariableIndex]; 209 //} else if (objData is ConstrainedIntData) { 210 // ((ConstrainedIntData)objData).Data = (int)linearRepresentation[0].localData[localVariableIndex]; 211 //} else { 212 // objData.Data = linearRepresentation[0].localData[localVariableIndex]; 213 //} 214 variables.Add(v); 215 //localVariableIndex++; 215 216 } 216 217 variablesExpanded = true; … … 233 234 234 235 public void AddVariable(IVariable variable) { 235 throw new NotSupportedException(); 236 if (!variablesExpanded) throw new InvalidOperationException(); 237 if (!variables.Exists(v => v.Name == variable.Name)) 238 variables.Add(variable); 236 239 } 237 240 238 241 public void RemoveVariable(string name) { 239 throw new NotSupportedException(); 242 if (!variablesExpanded) throw new InvalidOperationException(); 243 variables.RemoveAll(v => v.Name == name); 240 244 } 241 245 … … 256 260 } 257 261 258 public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {259 FlattenVariables();260 FlattenTrees();261 XmlNode node = base.GetXmlNode(name, document, persistedObjects);262 XmlNode linearRepresentationNode = document.CreateElement("LinearRepresentation");263 foreach (LightWeightFunction f in linearRepresentation) {264 XmlNode entryNode = PersistenceManager.Persist("Function", f.functionType, document, persistedObjects);265 XmlAttribute arityAttribute = document.CreateAttribute("Arity");266 arityAttribute.Value = XmlConvert.ToString(f.arity);267 entryNode.Attributes.Append(arityAttribute);268 foreach (object o in f.localData) {269 if (f.localData.Count > 0) {270 entryNode.AppendChild(CreateDataNode(document, o));271 }272 }273 linearRepresentationNode.AppendChild(entryNode);274 }275 276 node.AppendChild(linearRepresentationNode);277 return node;278 }262 //public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) { 263 // FlattenVariables(); 264 // FlattenTrees(); 265 // XmlNode node = base.GetXmlNode(name, document, persistedObjects); 266 // XmlNode linearRepresentationNode = document.CreateElement("LinearRepresentation"); 267 // foreach (LightWeightFunction f in linearRepresentation) { 268 // XmlNode entryNode = PersistenceManager.Persist("Function", f.functionType, document, persistedObjects); 269 // XmlAttribute arityAttribute = document.CreateAttribute("Arity"); 270 // arityAttribute.Value = XmlConvert.ToString(f.arity); 271 // entryNode.Attributes.Append(arityAttribute); 272 // foreach (object o in f.localData) { 273 // if (f.localData.Count > 0) { 274 // entryNode.AppendChild(CreateDataNode(document, o)); 275 // } 276 // } 277 // linearRepresentationNode.AppendChild(entryNode); 278 // } 279 280 // node.AppendChild(linearRepresentationNode); 281 // return node; 282 //} 279 283 280 284 private XmlNode CreateDataNode(XmlDocument doc, object o) { … … 295 299 } 296 300 297 public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {298 base.Populate(node, restoredObjects);299 XmlNode linearRepresentationNode = node.SelectSingleNode("LinearRepresentation");300 foreach (XmlNode entryNode in linearRepresentationNode.ChildNodes) {301 LightWeightFunction f = new LightWeightFunction();302 f.arity = XmlConvert.ToByte(entryNode.Attributes["Arity"].Value);303 foreach (XmlNode dataNode in entryNode.ChildNodes) {304 f.localData.Add(ParseDataNode(dataNode));305 }306 f.functionType = (IFunction)PersistenceManager.Restore(entryNode, restoredObjects);307 linearRepresentation.Add(f);308 }309 treesExpanded = false;310 variablesExpanded = false;311 }301 //public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) { 302 // base.Populate(node, restoredObjects); 303 // XmlNode linearRepresentationNode = node.SelectSingleNode("LinearRepresentation"); 304 // foreach (XmlNode entryNode in linearRepresentationNode.ChildNodes) { 305 // LightWeightFunction f = new LightWeightFunction(); 306 // f.arity = XmlConvert.ToByte(entryNode.Attributes["Arity"].Value); 307 // foreach (XmlNode dataNode in entryNode.ChildNodes) { 308 // f.localData.Add(ParseDataNode(dataNode)); 309 // } 310 // f.functionType = (IFunction)PersistenceManager.Restore(entryNode, restoredObjects); 311 // linearRepresentation.Add(f); 312 // } 313 // treesExpanded = false; 314 // variablesExpanded = false; 315 //} 312 316 313 317 private object ParseDataNode(XmlNode dataNode) { -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/FunctionBase.cs
r1529 r2202 30 30 31 31 namespace HeuristicLab.GP { 32 /// <summary> 33 /// Functions are like operators except that they do not allow sub-operators and the normal form of evaluation 34 /// is to evaluate all children first. 35 /// </summary> 36 public abstract class FunctionBase : OperatorBase, IFunction { 37 public const string INITIALIZATION = "Initialization"; 38 public const string MANIPULATION = "Manipulation"; 39 private List<IFunction>[] allowedSubFunctions; 32 public abstract class FunctionBase : ItemBase, IFunction { 33 private List<List<IFunction>> allowedSubFunctions = new List<List<IFunction>>(); 40 34 private int minArity = -1; 41 35 private int maxArity = -1; 42 43 public virtual double Apply() { 44 throw new NotImplementedException(); 36 private double tickets = 1.0; 37 private IOperator initializer; 38 private IOperator manipulator; 39 private int minTreeHeight = -1; 40 private int minTreeSize = -1; 41 42 public virtual string Name { 43 get { return this.GetType().Name; } 44 } 45 46 public virtual string Description { 47 get { return "Description for this function is missing (TODO)"; } 48 } 49 50 public int MinArity { 51 get { 52 return minArity; 53 } 54 protected set { 55 minArity = value; 56 while (minArity > allowedSubFunctions.Count) allowedSubFunctions.Add(new List<IFunction>()); 57 } 58 } 59 60 public int MaxArity { 61 get { 62 return maxArity; 63 } 64 protected set { 65 maxArity = value; 66 while (allowedSubFunctions.Count > maxArity) allowedSubFunctions.RemoveAt(allowedSubFunctions.Count - 1); 67 while (maxArity > allowedSubFunctions.Count) allowedSubFunctions.Add(new List<IFunction>()); 68 } 69 } 70 71 72 public int MinTreeSize { 73 get { 74 if (minTreeSize <= 0) RecalculateMinimalTreeSize(); 75 return minTreeSize; 76 } 77 } 78 79 public int MinTreeHeight { 80 get { 81 if (minTreeHeight <= 0) RecalculateMinimalTreeHeight(); 82 return minTreeHeight; 83 } 84 } 85 86 public double Tickets { 87 get { return tickets; } 88 set { 89 if (value < 0.0) throw new ArgumentException("Number of tickets must be positive"); 90 else tickets = value; 91 } 92 } 93 94 public IOperator Initializer { 95 get { return initializer; } 96 set { initializer = value; } 97 } 98 99 public IOperator Manipulator { 100 get { return manipulator; } 101 set { manipulator = value; } 102 } 103 104 public virtual IEnumerable<string> LocalParameterNames { 105 get { return new string[0]; } 45 106 } 46 107 … … 49 110 } 50 111 51 public int MinArity { 52 get { 53 if(minArity < 0) RefreshArity(); 54 return minArity; 55 } 56 } 57 58 public int MaxArity { 59 get { 60 if(maxArity < 0) RefreshArity(); 61 return maxArity; 62 } 63 } 64 65 private void RefreshArity() { 66 minArity = 2; maxArity = 2; // default arity is 2 67 foreach(IConstraint constraint in Constraints) { 68 NumberOfSubOperatorsConstraint theConstraint = constraint as NumberOfSubOperatorsConstraint; 69 if(theConstraint != null) { 70 minArity = theConstraint.MinOperators.Data; 71 maxArity = theConstraint.MaxOperators.Data; 112 113 //private List<IConstraint> constraints = new List<IConstraint>(); 114 //public ICollection<IConstraint> Constraints { 115 // get { return constraints; } 116 //} 117 118 //private void RefreshArity() { 119 // minArity = 2; maxArity = 2; // default arity is 2 120 // foreach (IConstraint constraint in Constraints) { 121 // NumberOfSubOperatorsConstraint theConstraint = constraint as NumberOfSubOperatorsConstraint; 122 // if (theConstraint != null) { 123 // minArity = theConstraint.MinOperators.Data; 124 // maxArity = theConstraint.MaxOperators.Data; 125 // } 126 // } 127 //} 128 129 public ICollection<IFunction> GetAllowedSubFunctions(int index) { 130 if (index < 0 || index > MaxArity) throw new ArgumentException("Index outside of allowed range. index = " + index); 131 //if (allowedSubFunctions == null) { 132 // // first time: analyze the constraint and create a cached copy of the allowed sub-functions 133 // allowedSubFunctions = new List<IFunction>[MaxArity]; 134 // for (int i = 0; i < MaxArity; i++) { 135 // allowedSubFunctions[i] = GetAllowedSubFunctions(i); 136 // } 137 //} 138 return allowedSubFunctions[index]; 139 } 140 141 public void AddAllowedSubFunction(IFunction function, int index) { 142 if (index < 0 || index > MaxArity) throw new ArgumentException("Index outside of allowed range. index = " + index); 143 if (allowedSubFunctions[index] == null) { 144 allowedSubFunctions[index] = new List<IFunction>(); 145 } 146 if (!allowedSubFunctions[index].Contains(function)) { 147 allowedSubFunctions[index].Add(function); 148 } 149 } 150 151 public void RemoveAllowedSubFunction(IFunction function, int index) { 152 if (index < 0 || index > MaxArity) throw new ArgumentException("Index outside of allowed range. index = " + index); 153 allowedSubFunctions[index].Add(function); 154 } 155 156 public bool IsAllowedSubFunction(IFunction function, int index) { 157 return GetAllowedSubFunctions(index).Contains(function); 158 } 159 160 //private List<IFunction> GetAllowedSubFunctions(int index) { 161 // List<IFunction> allowedSubFunctions = new List<IFunction>(); 162 // foreach (IConstraint constraint in Constraints) { 163 // if (constraint is SubOperatorTypeConstraint) { 164 // SubOperatorTypeConstraint subOpConstraint = constraint as SubOperatorTypeConstraint; 165 // if (subOpConstraint.SubOperatorIndex.Data == index) { 166 // foreach (IFunction f in subOpConstraint.AllowedSubOperators) allowedSubFunctions.Add(f); 167 // subOpConstraint.Changed += new EventHandler(subOpConstraint_Changed); // register an event-handler to invalidate the cache on constraint changes 168 // return allowedSubFunctions; 169 // } 170 // } else if (constraint is AllSubOperatorsTypeConstraint) { 171 // AllSubOperatorsTypeConstraint subOpConstraint = constraint as AllSubOperatorsTypeConstraint; 172 // foreach (IFunction f in subOpConstraint.AllowedSubOperators) allowedSubFunctions.Add(f); 173 // subOpConstraint.Changed += new EventHandler(subOpConstraint_Changed); // register an event-handler to invalidate the cache on constraint changes 174 // return allowedSubFunctions; 175 // } 176 // } 177 // return allowedSubFunctions; 178 //} 179 180 //private void subOpConstraint_Changed(object sender, EventArgs e) { 181 // allowedSubFunctions = null; 182 //} 183 184 public override IView CreateView() { 185 return new FunView(this); 186 } 187 188 private void RecalculateMinimalTreeSize() { 189 minTreeSize = int.MaxValue; 190 int sum = 1; 191 int minSize = int.MaxValue; 192 for (int i = 0; i < MinArity; i++) { 193 foreach (IFunction subFun in GetAllowedSubFunctions(i)) { 194 minSize = Math.Min(minSize, subFun.MinTreeSize); 72 195 } 73 } 74 } 75 76 public IList<IFunction> AllowedSubFunctions(int index) { 77 if(allowedSubFunctions == null) { 78 // first time: analyze the constraint and create a cached copy of the allowed sub-functions 79 allowedSubFunctions = new List<IFunction>[MaxArity]; 80 for(int i = 0; i < MaxArity; i++) { 81 allowedSubFunctions[i] = GetAllowedSubFunctions(i); 196 sum += minSize; 197 } 198 minTreeSize = sum; 199 } 200 201 private void RecalculateMinimalTreeHeight() { 202 minTreeHeight = int.MaxValue; 203 int height = 0; 204 int minHeight = int.MaxValue; 205 for (int i = 0; i < MinArity; i++) { 206 foreach (IFunction subFun in GetAllowedSubFunctions(i)) { 207 minHeight = Math.Min(minHeight, subFun.MinTreeHeight); 82 208 } 83 } 84 return allowedSubFunctions[index]; 85 } 86 87 private List<IFunction> GetAllowedSubFunctions(int index) { 88 List<IFunction> allowedSubFunctions = new List<IFunction>(); 89 foreach(IConstraint constraint in Constraints) { 90 if(constraint is SubOperatorTypeConstraint) { 91 SubOperatorTypeConstraint subOpConstraint = constraint as SubOperatorTypeConstraint; 92 if(subOpConstraint.SubOperatorIndex.Data == index) { 93 foreach(IFunction f in subOpConstraint.AllowedSubOperators) allowedSubFunctions.Add(f); 94 subOpConstraint.Changed += new EventHandler(subOpConstraint_Changed); // register an event-handler to invalidate the cache on constraing changes 95 return allowedSubFunctions; 96 } 97 } else if(constraint is AllSubOperatorsTypeConstraint) { 98 AllSubOperatorsTypeConstraint subOpConstraint = constraint as AllSubOperatorsTypeConstraint; 99 foreach(IFunction f in subOpConstraint.AllowedSubOperators) allowedSubFunctions.Add(f); 100 subOpConstraint.Changed += new EventHandler(subOpConstraint_Changed); // register an event-handler to invalidate the cache on constraint changes 101 return allowedSubFunctions; 102 } 103 } 104 return allowedSubFunctions; 105 } 106 107 private void subOpConstraint_Changed(object sender, EventArgs e) { 108 allowedSubFunctions = null; 109 } 110 111 // operator-tree style evaluation is not supported for functions. 112 public override IOperation Apply(IScope scope) { 113 throw new NotSupportedException(); 114 } 115 116 private static readonly List<IOperator> emptySubOperatorList = new List<IOperator>(); 117 public override IList<IOperator> SubOperators { 118 get { return emptySubOperatorList; } 119 } 120 121 public override void AddSubOperator(IOperator subOperator) { 122 throw new NotSupportedException(); 123 } 124 125 public override bool TryAddSubOperator(IOperator subOperator) { 126 throw new NotSupportedException(); 127 } 128 129 public override bool TryAddSubOperator(IOperator subOperator, int index) { 130 throw new NotSupportedException(); 131 } 132 133 public override bool TryAddSubOperator(IOperator subOperator, int index, out ICollection<IConstraint> violatedConstraints) { 134 throw new NotSupportedException(); 135 } 136 137 public override bool TryAddSubOperator(IOperator subOperator, out ICollection<IConstraint> violatedConstraints) { 138 throw new NotSupportedException(); 139 } 140 141 public override void AddSubOperator(IOperator subOperator, int index) { 142 throw new NotSupportedException(); 143 } 144 145 public override void RemoveSubOperator(int index) { 146 throw new NotSupportedException(); 147 } 148 149 public override bool TryRemoveSubOperator(int index) { 150 throw new NotSupportedException(); 151 } 152 153 public override bool TryRemoveSubOperator(int index, out ICollection<IConstraint> violatedConstraints) { 154 throw new NotSupportedException(); 209 height = Math.Max(height, minHeight); 210 } 211 minTreeHeight = height + 1; 155 212 } 156 213 } -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/FunctionGroup.cs
r2183 r2202 31 31 32 32 namespace HeuristicLab.GP { 33 public class GPOperatorGroup : OperatorGroup { 34 private Dictionary<IOperator, int> minTreeHeight = new Dictionary<IOperator, int>(); 35 private Dictionary<IOperator, int> minTreeSize = new Dictionary<IOperator, int>(); 36 private SubOperatorsConstraintAnalyser constraintAnalyser = new SubOperatorsConstraintAnalyser(); 37 38 public GPOperatorGroup() 39 : base() { 40 } 41 42 public override void AddOperator(IOperator op) { 43 base.AddOperator(op); 44 var localVariableInfos = op.VariableInfos.Where(f => f.Local); 45 46 if(op.GetVariable(GPOperatorLibrary.MIN_TREE_HEIGHT) == null) { 47 op.AddVariable(new Variable(GPOperatorLibrary.MIN_TREE_HEIGHT, new IntData(-1))); 48 } 49 if(op.GetVariable(GPOperatorLibrary.MIN_TREE_SIZE) == null) { 50 op.AddVariable(new Variable(GPOperatorLibrary.MIN_TREE_SIZE, new IntData(-1))); 51 } 52 if(op.GetVariable(GPOperatorLibrary.TICKETS) == null) { 53 op.AddVariable(new Variable(GPOperatorLibrary.TICKETS, new DoubleData(1.0))); 54 } 55 foreach(IConstraint c in op.Constraints) { 56 if(c is SubOperatorTypeConstraint || c is AllSubOperatorsTypeConstraint) c.Changed += new EventHandler(UpdateTreeBounds); 57 } 58 RecalculateMinimalTreeBounds(); 59 OnOperatorAdded(op); 60 } 61 62 void UpdateTreeBounds(object sender, EventArgs e) { 63 RecalculateMinimalTreeBounds(); 64 } 65 66 private void RecalculateMinimalTreeBounds() { 67 minTreeHeight.Clear(); 68 minTreeSize.Clear(); 69 constraintAnalyser.AllPossibleOperators = Operators; 70 71 foreach(IOperator op in Operators) { 72 ((IntData)op.GetVariable(GPOperatorLibrary.MIN_TREE_HEIGHT).Value).Data = RecalculateMinimalTreeHeight(op); 73 ((IntData)op.GetVariable(GPOperatorLibrary.MIN_TREE_SIZE).Value).Data = RecalculateMinimalTreeSize(op); 74 } 75 } 76 77 private int RecalculateMinimalTreeSize(IOperator op) { 78 // check for memoized value 79 if(minTreeSize.ContainsKey(op)) { 80 return minTreeSize[op]; 81 } 82 83 int minArity; 84 int maxArity; 85 GetMinMaxArity(op, out minArity, out maxArity); 86 // no suboperators possible => minimalTreeSize == 1 (the current node) 87 if(minArity == 0 && maxArity == 0) { 88 minTreeSize[op] = 1; 89 return 1; 90 } 91 92 // when suboperators are necessary we have to find the smallest possible tree (recursively) 93 // the minimal size of the parent is 1 + the sum of the minimal sizes of all subtrees 94 int subTreeSizeSum = 0; 95 96 // mark the currently processed operator to prevent infinite recursions and stack overflow 97 minTreeSize[op] = 9999; 98 for(int i = 0; i < minArity; i++) { 99 // calculate the minTreeSize of all allowed sub-operators 100 // if the list of allowed suboperators is empty because the operator needs suboperators 101 // but there are no valid suboperators defined in the current group then we just use an impossible 102 // tree size here to indicate that there was a problem. 103 // usually as more operators are added to the group the problem will be corrected (by adding the missing operator). 104 // however if the missing operator is never added the high min tree size here has the effect that this operator 105 // will not be included in generated subtrees because the resulting size would always be higher than a reasonably set 106 // maximal tree size. 107 int minSubTreeSize = constraintAnalyser.GetAllowedOperators(op, i).Select(subOp => RecalculateMinimalTreeSize(subOp)) 108 .Concat(Enumerable.Repeat(9999, 1)).Min(); 109 subTreeSizeSum += minSubTreeSize; 110 } 111 112 minTreeSize[op] = subTreeSizeSum + 1; 113 return subTreeSizeSum + 1; 114 } 115 116 private int RecalculateMinimalTreeHeight(IOperator op) { 117 // check for memoized value 118 if(minTreeHeight.ContainsKey(op)) { 119 return minTreeHeight[op]; 120 } 121 122 int minArity; 123 int maxArity; 124 GetMinMaxArity(op, out minArity, out maxArity); 125 // no suboperators possible => minimalTreeHeight == 1 126 if(minArity == 0 && maxArity == 0) { 127 minTreeHeight[op] = 1; 128 return 1; 129 } 130 131 // when suboperators are necessary we have to find the smallest possible tree (recursively) 132 // the minimal height of the parent is 1 + the height of the largest subtree 133 int maxSubTreeHeight = 0; 134 135 // mark the currently processed operator to prevent infinite recursions leading to stack overflow 136 minTreeHeight[op] = 9999; 137 for(int i = 0; i < minArity; i++) { 138 // calculate the minTreeHeight of all possible sub-operators. 139 // use the smallest possible subTree as lower bound for the subTreeHeight. 140 // if the list of allowed suboperators is empty because the operator needs suboperators 141 // but there are no valid suboperators defined in the current group then we use an impossible tree height 142 // to indicate that there was a problem. 143 // usually as more operators are added to the group the problem will be corrected (by adding the missing operator). 144 // however if the missing operator is never added the high min tree height here has the effect that this operator 145 // will not be included in generated subtrees because the resulting (virtual) height would always be higher than a reasonably set 146 // maximal tree height. 147 int minSubTreeHeight = constraintAnalyser.GetAllowedOperators(op, i).Select(subOp => RecalculateMinimalTreeHeight(subOp)) 148 .Concat(Enumerable.Repeat(9999, 1)).Min(); 149 150 // if the smallest height of this subtree is larger than all other subtrees before we have to update the min height of the parent 151 if(minSubTreeHeight > maxSubTreeHeight) { 152 maxSubTreeHeight = minSubTreeHeight; 153 } 154 } 155 156 minTreeHeight[op] = maxSubTreeHeight + 1; 157 return maxSubTreeHeight + 1; 158 } 159 160 private void GetMinMaxArity(IOperator op, out int minArity, out int maxArity) { 161 foreach(IConstraint constraint in op.Constraints) { 162 NumberOfSubOperatorsConstraint theConstraint = constraint as NumberOfSubOperatorsConstraint; 163 if(theConstraint != null) { 164 minArity = theConstraint.MinOperators.Data; 165 maxArity = theConstraint.MaxOperators.Data; 166 return; 167 } 168 } 169 // the default arity is 2 170 minArity = 2; 171 maxArity = 2; 172 } 173 174 public override void AddSubGroup(IOperatorGroup group) { 175 throw new NotSupportedException(); 176 } 177 178 public override void RemoveOperator(IOperator op) { 179 base.RemoveOperator(op); 180 op.RemoveVariable(GPOperatorLibrary.MIN_TREE_SIZE); 181 op.RemoveVariable(GPOperatorLibrary.MIN_TREE_HEIGHT); 182 op.RemoveVariable(GPOperatorLibrary.TICKETS); 183 foreach(IConstraint c in op.Constraints) { 184 if(c is SubOperatorTypeConstraint || c is AllSubOperatorsTypeConstraint) c.Changed -= new EventHandler(UpdateTreeBounds); 185 } 186 187 // remove the operator from the allowed sub-functions of the remaining operators 188 foreach(IOperator o in Operators) { 189 if(o != op) { 190 foreach(IConstraint c in o.Constraints) { 191 if(c is SubOperatorTypeConstraint) { 192 ((SubOperatorTypeConstraint)c).RemoveOperator(op); 193 } else if(c is AllSubOperatorsTypeConstraint) { 194 ((AllSubOperatorsTypeConstraint)c).RemoveOperator(op); 195 } 196 } 197 } 198 } 199 OnOperatorRemoved(op); 200 } 201 202 public override void RemoveSubGroup(IOperatorGroup group) { 203 throw new NotSupportedException(); 204 } 205 206 public event EventHandler OperatorAdded; 207 public event EventHandler OperatorRemoved; 208 209 protected virtual void OnOperatorAdded(IOperator op) { 210 if(OperatorAdded != null) { 211 OperatorAdded(this, new OperatorEventArgs(op)); 212 } 213 } 214 protected virtual void OnOperatorRemoved(IOperator op) { 215 if(OperatorRemoved != null) { 216 OperatorRemoved(this, new OperatorEventArgs(op)); 217 } 218 } 219 } 220 221 internal class OperatorEventArgs : EventArgs { 222 public IOperator op; 223 224 public OperatorEventArgs(IOperator op) { 225 this.op = op; 226 } 227 } 33 public class FunctionGroup : StorableBase { 228 34 } -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/FunctionLibrary.cs
r2183 r2202 26 26 using HeuristicLab.Core; 27 27 using System.Xml; 28 using HeuristicLab.Data; 29 using HeuristicLab.Constraints; 28 30 29 31 namespace HeuristicLab.GP { 30 public class GPOperatorLibrary : ItemBase, IOperatorLibrary, IEditable { 31 // constants for variable names 32 internal const string MIN_TREE_HEIGHT = "MinTreeHeight"; 33 internal const string MIN_TREE_SIZE = "MinTreeSize"; 34 internal const string TICKETS = "Tickets"; 35 36 private GPOperatorGroup group; 37 38 public GPOperatorGroup GPOperatorGroup { 39 get { return group; } 40 } 41 #region IOperatorLibrary Members 42 43 public IOperatorGroup Group { 44 get { return group; } 32 public class FunctionLibrary : ItemBase, IEditable { 33 private List<IFunction> functions = new List<IFunction>(); 34 public IEnumerable<IFunction> Functions { 35 get { return functions; } 45 36 } 46 37 47 #endregion 38 public FunctionLibrary() 39 : base() { 40 } 48 41 49 42 50 public GPOperatorLibrary()51 : base() {52 group = new GPOperatorGroup();43 public void AddFunction(IFunction fun) { 44 if (!functions.Contains(fun)) functions.Add(fun); 45 // OnFunctionAdded(fun); 53 46 } 54 47 55 public override IView CreateView() { 56 return new GPOperatorLibraryEditor(this); 48 //void UpdateTreeBounds(object sender, EventArgs e) { 49 // RecalculateMinimalTreeBounds(); 50 //} 51 52 53 //private void GetMinMaxArity(IOperator op, out int minArity, out int maxArity) { 54 // foreach (IConstraint constraint in op.Constraints) { 55 // NumberOfSubOperatorsConstraint theConstraint = constraint as NumberOfSubOperatorsConstraint; 56 // if (theConstraint != null) { 57 // minArity = theConstraint.MinOperators.Data; 58 // maxArity = theConstraint.MaxOperators.Data; 59 // return; 60 // } 61 // } 62 // // the default arity is 2 63 // minArity = 2; 64 // maxArity = 2; 65 //} 66 67 public void RemoveFunction(IFunction fun) { 68 functions.Remove(fun); 69 70 // remove the operator from the allowed sub-functions of the remaining operators 71 foreach (IFunction f in Functions) { 72 if (f != fun) { 73 } 74 } 75 // OnFunctionRemoved(fun); 57 76 } 58 77 59 public override object Clone(IDictionary<Guid, object> clonedObjects) { 60 GPOperatorLibrary clone = (GPOperatorLibrary)base.Clone(clonedObjects); 61 clone.group = (GPOperatorGroup)group.Clone(clonedObjects); 62 return clone; 78 //public event EventHandler FunctionAdded; 79 //public event EventHandler FunctionRemoved; 80 81 //protected virtual void OnFunctionAdded(IFunction fun) { 82 // if (FunctionAdded != null) { 83 // FunctionAdded(this, new EventArgs(fun)); 84 // } 85 //} 86 //protected virtual void OnFunctionRemoved(IFunction fun) { 87 // if (FunctionRemoved != null) { 88 // FunctionRemoved(this, new EventArgs(fun)); 89 // } 90 //} 91 92 public override IView CreateView() { 93 return new FunctionLibraryEditor(this); 63 94 } 64 65 #region persistence66 public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {67 XmlNode node = base.GetXmlNode(name, document, persistedObjects);68 node.AppendChild(PersistenceManager.Persist("Group", group, document, persistedObjects));69 return node;70 }71 72 public override void Populate(System.Xml.XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {73 base.Populate(node, restoredObjects);74 group = (GPOperatorGroup) PersistenceManager.Restore(node.SelectSingleNode("Group"), restoredObjects);75 }76 #endregion77 95 78 96 #region IEditable Members 79 97 80 98 public IEditor CreateEditor() { 81 return new GPOperatorLibraryEditor(this);99 return new FunctionLibraryEditor(this); 82 100 } 83 101 -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/FunctionLibraryEditor.Designer.cs
r2183 r2202 21 21 22 22 namespace HeuristicLab.GP { 23 partial class GPOperatorLibraryEditor {23 partial class FunctionLibraryEditor { 24 24 /// <summary> 25 25 /// Required designer variable. -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/FunctionLibraryEditor.cs
r2183 r2202 35 35 36 36 namespace HeuristicLab.GP { 37 public partial class GPOperatorLibraryEditor : EditorBase {38 public IOperatorLibrary OperatorLibrary {39 get { return ( IOperatorLibrary)Item; }37 public partial class FunctionLibraryEditor : EditorBase { 38 public FunctionLibrary FunctionLibrary { 39 get { return (FunctionLibrary)Item; } 40 40 set { base.Item = value; } 41 41 } 42 42 43 public GPOperatorLibraryEditor(GPOperatorLibrary library)43 public FunctionLibraryEditor(FunctionLibrary library) 44 44 : base() { 45 45 InitializeComponent(); 46 OperatorLibrary = library; 47 operatorLibraryEditor.OperatorLibrary = library; 48 49 library.GPOperatorGroup.OperatorAdded += new EventHandler(GPOperatorLibraryView_OperatorAdded); 50 library.GPOperatorGroup.OperatorRemoved += new EventHandler(GPOperatorGroup_OperatorRemoved); 46 FunctionLibrary = library; 51 47 52 48 mutationVariableView.Enabled = false; 53 49 initVariableView.Enabled = false; 54 50 55 foreach (IOperator op in library.Group.Operators) {56 if (op.GetVariable(FunctionBase.MANIPULATION)!= null) {51 foreach (IFunction fun in library.Functions) { 52 if (fun.Manipulator != null) { 57 53 ListViewItem item = new ListViewItem(); 58 item.Text = op.Name;59 item.Name = op.Name;60 item.Tag = op;54 item.Text = fun.Name; 55 item.Name = fun.Name; 56 item.Tag = fun; 61 57 mutationListView.Items.Add(item); 62 58 } 63 if (op.GetVariable(FunctionBase.INITIALIZATION)!= null) {59 if (fun.Initializer != null) { 64 60 ListViewItem item = new ListViewItem(); 65 item.Name = op.Name;66 item.Text = op.Name;67 item.Tag = op;61 item.Name = fun.Name; 62 item.Text = fun.Name; 63 item.Tag = fun; 68 64 initListView.Items.Add(item); 69 65 } … … 71 67 } 72 68 73 74 private void GPOperatorLibraryView_OperatorAdded(object sender, EventArgs e) { 75 IOperator op = ((OperatorEventArgs)e).op; 76 if(op.GetVariable(FunctionBase.MANIPULATION) != null) { 77 ListViewItem operatorMutationItem = new ListViewItem(); 78 operatorMutationItem.Name = op.Name; 79 operatorMutationItem.Text = op.Name; 80 operatorMutationItem.Tag = op; 81 mutationListView.Items.Add(operatorMutationItem); 82 } 83 84 if(op.GetVariable(FunctionBase.INITIALIZATION) != null) { 85 ListViewItem operatorInitItem = new ListViewItem(); 86 operatorInitItem.Name = op.Name; 87 operatorInitItem.Text = op.Name; 88 operatorInitItem.Tag = op; 89 initListView.Items.Add(operatorInitItem); 90 } 91 92 op.NameChanged += new EventHandler(op_NameChanged); 93 Refresh(); 69 protected override void AddItemEvents() { 70 base.AddItemEvents(); 71 base.Item.Changed += (sender, args) => UpdateControls(); 94 72 } 95 73 96 private void op_NameChanged(object sender, EventArgs e) { 97 IOperator srcOp = (IOperator)sender; 98 foreach(ListViewItem item in mutationListView.Items) { 99 if(item.Tag == srcOp) { 100 item.Name = srcOp.Name; 101 item.Text = srcOp.Name; 102 break; 103 } 104 } 105 foreach(ListViewItem item in initListView.Items) { 106 if(item.Tag == srcOp) { 107 item.Name = srcOp.Name; 108 item.Text = srcOp.Name; 109 break; 110 } 111 } 74 protected override void UpdateControls() { 75 base.UpdateControls(); 112 76 } 113 77 78 //private void GPOperatorLibraryView_OperatorAdded(object sender, EventArgs e) { 79 // IOperator op = ((OperatorEventArgs)e).op; 80 // if(op.GetVariable(FunctionBase.MANIPULATION) != null) { 81 // ListViewItem operatorMutationItem = new ListViewItem(); 82 // operatorMutationItem.Name = op.Name; 83 // operatorMutationItem.Text = op.Name; 84 // operatorMutationItem.Tag = op; 85 // mutationListView.Items.Add(operatorMutationItem); 86 // } 114 87 115 private void GPOperatorGroup_OperatorRemoved(object sender, EventArgs e) { 116 IOperator op = ((OperatorEventArgs)e).op; 88 // if(op.GetVariable(FunctionBase.INITIALIZATION) != null) { 89 // ListViewItem operatorInitItem = new ListViewItem(); 90 // operatorInitItem.Name = op.Name; 91 // operatorInitItem.Text = op.Name; 92 // operatorInitItem.Tag = op; 93 // initListView.Items.Add(operatorInitItem); 94 // } 117 95 118 foreach(ListViewItem item in mutationListView.Items) { 119 if(item.Tag == op) { 120 mutationListView.Items.Remove(item); 121 break; 122 } 123 } 96 // op.NameChanged += new EventHandler(op_NameChanged); 97 // Refresh(); 98 //} 124 99 125 foreach(ListViewItem item in initListView.Items) { 126 if(item.Tag == op) { 127 initListView.Items.Remove(item); 128 break; 129 } 130 } 131 } 100 //private void op_NameChanged(object sender, EventArgs e) { 101 // IOperator srcOp = (IOperator)sender; 102 // foreach(ListViewItem item in mutationListView.Items) { 103 // if(item.Tag == srcOp) { 104 // item.Name = srcOp.Name; 105 // item.Text = srcOp.Name; 106 // break; 107 // } 108 // } 109 // foreach(ListViewItem item in initListView.Items) { 110 // if(item.Tag == srcOp) { 111 // item.Name = srcOp.Name; 112 // item.Text = srcOp.Name; 113 // break; 114 // } 115 // } 116 //} 117 118 119 //private void GPOperatorGroup_OperatorRemoved(object sender, EventArgs e) { 120 // IOperator op = ((OperatorEventArgs)e).op; 121 122 // foreach(ListViewItem item in mutationListView.Items) { 123 // if(item.Tag == op) { 124 // mutationListView.Items.Remove(item); 125 // break; 126 // } 127 // } 128 129 // foreach(ListViewItem item in initListView.Items) { 130 // if(item.Tag == op) { 131 // initListView.Items.Remove(item); 132 // break; 133 // } 134 // } 135 //} 132 136 133 137 private void mutationListView_SelectedIndexChanged(object sender, EventArgs e) { 134 if(mutationListView.SelectedItems.Count>0 && mutationListView.SelectedItems[0].Tag != null) {135 IVariable variable = ((IOperator)mutationListView.SelectedItems[0].Tag).GetVariable(FunctionBase.MANIPULATION);136 mutationVariableView.Enabled = true;137 mutationVariableView.Variable = variable;138 } else {139 mutationVariableView.Enabled = false;140 }138 //if(mutationListView.SelectedItems.Count>0 && mutationListView.SelectedItems[0].Tag != null) { 139 // IVariable variable = ((IFunction)mutationListView.SelectedItems[0].Tag).Manipulator; 140 // mutationVariableView.Enabled = true; 141 // mutationVariableView.Variable = variable; 142 //} else { 143 // mutationVariableView.Enabled = false; 144 //} 141 145 } 142 146 143 147 private void initListView_SelectedIndexChanged(object sender, EventArgs e) { 144 if(initListView.SelectedItems.Count>0 && initListView.SelectedItems[0].Tag != null) {145 IVariable variable = ((IOperator)initListView.SelectedItems[0].Tag).GetVariable(FunctionBase.INITIALIZATION);146 initVariableView.Enabled = true;147 initVariableView.Variable = variable;148 } else {149 initVariableView.Enabled = false;150 }148 //if(initListView.SelectedItems.Count>0 && initListView.SelectedItems[0].Tag != null) { 149 // IVariable variable = ((IFunction)initListView.SelectedItems[0].Tag).Initializer; 150 // initVariableView.Enabled = true; 151 // initVariableView.Variable = variable; 152 //} else { 153 // initVariableView.Enabled = false; 154 //} 151 155 } 152 156 } -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/HeuristicLab.GP-3.3.csproj
r1534 r2202 83 83 <ItemGroup> 84 84 <Compile Include="BakedFunctionTree.cs" /> 85 <Compile Include="FunctionLibrary.cs" /> 86 <Compile Include="FunctionLibraryEditor.cs"> 87 <SubType>UserControl</SubType> 88 </Compile> 89 <Compile Include="FunctionLibraryEditor.Designer.cs"> 90 <DependentUpon>FunctionLibraryEditor.cs</DependentUpon> 91 </Compile> 92 <Compile Include="FunctionTreeView.cs"> 93 <SubType>UserControl</SubType> 94 </Compile> 95 <Compile Include="FunctionTreeView.Designer.cs"> 96 <DependentUpon>FunctionTreeView.cs</DependentUpon> 97 </Compile> 98 <Compile Include="FunView.cs"> 99 <SubType>UserControl</SubType> 100 </Compile> 101 <Compile Include="FunView.Designer.cs"> 102 <DependentUpon>FunView.cs</DependentUpon> 103 </Compile> 85 104 <Compile Include="TrainingWindowSlider.cs" /> 86 105 <Compile Include="DefaultFunctionTreeNameGenerator.cs" /> … … 95 114 <Compile Include="IFunctionTreeExporter.cs" /> 96 115 <Compile Include="FunctionBase.cs" /> 97 <Compile Include="FunctionView.cs">98 <SubType>UserControl</SubType>99 </Compile>100 <Compile Include="FunctionView.Designer.cs">101 <DependentUpon>FunctionView.cs</DependentUpon>102 </Compile>103 <Compile Include="GPOperatorGroup.cs" />104 <Compile Include="GPOperatorLibrary.cs" />105 <Compile Include="GPOperatorLibraryEditor.cs">106 <SubType>UserControl</SubType>107 </Compile>108 <Compile Include="GPOperatorLibraryEditor.Designer.cs">109 <DependentUpon>GPOperatorLibraryEditor.cs</DependentUpon>110 </Compile>111 116 <Compile Include="HeuristicLabGPPlugin.cs" /> 112 117 <Compile Include="IFunction.cs" /> … … 162 167 </ItemGroup> 163 168 <ItemGroup> 164 <EmbeddedResource Include="FunctionView.resx"> 165 <DependentUpon>FunctionView.cs</DependentUpon> 166 <SubType>Designer</SubType> 169 <EmbeddedResource Include="FunctionLibraryEditor.resx"> 170 <DependentUpon>FunctionLibraryEditor.cs</DependentUpon> 167 171 </EmbeddedResource> 168 <EmbeddedResource Include="GPOperatorLibraryEditor.resx"> 169 <DependentUpon>GPOperatorLibraryEditor.cs</DependentUpon> 170 <SubType>Designer</SubType> 172 <EmbeddedResource Include="FunctionTreeView.resx"> 173 <DependentUpon>FunctionTreeView.cs</DependentUpon> 171 174 </EmbeddedResource> 172 175 </ItemGroup> -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/IFunction.cs
r1529 r2202 26 26 27 27 namespace HeuristicLab.GP { 28 public interface IFunction : IOperator { 28 public interface IFunction : IItem { 29 string Name { get; } 29 30 IFunctionTree GetTreeNode(); 30 double Apply(); 31 IList<IFunction> AllowedSubFunctions(int index); 31 ICollection<IFunction> GetAllowedSubFunctions(int index); 32 void AddAllowedSubFunction(IFunction f, int index); 33 void RemoveAllowedSubFunction(IFunction f, int index); 34 bool IsAllowedSubFunction(IFunction f, int index); 32 35 int MinArity { get; } 33 36 int MaxArity { get; } 37 int MinTreeHeight { get; } 38 int MinTreeSize { get; } 39 double Tickets { get; } 40 IEnumerable<string> LocalParameterNames { get; } 41 IOperator Initializer { get; } 42 IOperator Manipulator { get; } 34 43 } 35 44 } -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/IFunctionTree.cs
r1529 r2202 32 32 ICollection<IVariable> LocalVariables { get; } 33 33 IFunction Function { get; } 34 IOperator Manipulator { get; } 35 IOperator Initializer { get; } 34 36 IVariable GetLocalVariable(string name); 35 37 void AddVariable(IVariable variable); -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/Manipulation/ChangeNodeTypeManipulation.cs
r656 r2202 45 45 : base() { 46 46 AddVariableInfo(new VariableInfo("Random", "Uniform random number generator", typeof(MersenneTwister), VariableKind.In)); 47 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof( GPOperatorLibrary), VariableKind.In));47 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof(FunctionLibrary), VariableKind.In)); 48 48 AddVariableInfo(new VariableInfo("MaxTreeHeight", "The maximal allowed height of the tree", typeof(IntData), VariableKind.In)); 49 49 AddVariableInfo(new VariableInfo("MaxTreeSize", "The maximal allowed size (number of nodes) of the tree", typeof(IntData), VariableKind.In)); … … 57 57 IFunctionTree root = GetVariableValue<IFunctionTree>("FunctionTree", scope, false); 58 58 MersenneTwister random = GetVariableValue<MersenneTwister>("Random", scope, true); 59 GPOperatorLibrary library = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);59 FunctionLibrary library = GetVariableValue<FunctionLibrary>("OperatorLibrary", scope, true); 60 60 IntData treeSize = GetVariableValue<IntData>("TreeSize", scope, false); 61 61 IntData treeHeight = GetVariableValue<IntData>("TreeHeight", scope, false); … … 148 148 // first let's choose the function we want to use instead of the old child. For this we have to determine the 149 149 // pool of allowed functions based on constraints of the parent if there is one. 150 IList<IFunction> allowedFunctions = gardener.GetAllowedSubFunctions(parent!=null?parent.Function:null, childIndex);150 List<IFunction> allowedFunctions = new List<IFunction>(gardener.GetAllowedSubFunctions(parent != null ? parent.Function : null, childIndex)); 151 151 // try to make a tree with the same arity as the old child. 152 152 int actualArity = child.SubTrees.Count; -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/Manipulation/CutOutNodeManipulation.cs
r656 r2202 50 50 : base() { 51 51 AddVariableInfo(new VariableInfo("Random", "Uniform random number generator", typeof(MersenneTwister), VariableKind.In)); 52 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof( GPOperatorLibrary), VariableKind.In));52 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof(FunctionLibrary), VariableKind.In)); 53 53 AddVariableInfo(new VariableInfo("MaxTreeHeight", "The maximal allowed height of the tree", typeof(IntData), VariableKind.In)); 54 54 AddVariableInfo(new VariableInfo("MaxTreeSize", "The maximal allowed size (number of nodes) of the tree", typeof(IntData), VariableKind.In)); … … 62 62 IFunctionTree root = GetVariableValue<IFunctionTree>("FunctionTree", scope, true); 63 63 MersenneTwister random = GetVariableValue<MersenneTwister>("Random", scope, true); 64 GPOperatorLibrary library = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);64 FunctionLibrary library = GetVariableValue<FunctionLibrary>("OperatorLibrary", scope, true); 65 65 int maxTreeHeight = GetVariableValue<IntData>("MaxTreeHeight", scope, true).Data; 66 66 int maxTreeSize = GetVariableValue<IntData>("MaxTreeSize", scope, true).Data; -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/Manipulation/DeleteSubTreeManipulation.cs
r656 r2202 40 40 : base() { 41 41 AddVariableInfo(new VariableInfo("Random", "Uniform random number generator", typeof(MersenneTwister), VariableKind.In)); 42 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof( GPOperatorLibrary), VariableKind.In));42 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof(FunctionLibrary), VariableKind.In)); 43 43 AddVariableInfo(new VariableInfo("MaxTreeHeight", "The maximal allowed height of the tree", typeof(IntData), VariableKind.In)); 44 44 AddVariableInfo(new VariableInfo("MaxTreeSize", "The maximal allowed size (number of nodes) of the tree", typeof(IntData), VariableKind.In)); … … 52 52 IFunctionTree root = GetVariableValue<IFunctionTree>("FunctionTree", scope, true); 53 53 MersenneTwister random = GetVariableValue<MersenneTwister>("Random", scope, true); 54 GPOperatorLibrary library = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);54 FunctionLibrary library = GetVariableValue<FunctionLibrary>("OperatorLibrary", scope, true); 55 55 TreeGardener gardener = new TreeGardener(random, library); 56 56 IFunctionTree parent = gardener.GetRandomParentNode(root); -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/Manipulation/FullTreeShaker.cs
r706 r2202 33 33 public class FullTreeShaker : DelegatingOperator { 34 34 public override string Description { 35 get { return "Manipulates all tree nodes for which a '" + FunctionBase.MANIPULATION + "' variableis defined."; }35 get { return "Manipulates all tree nodes for which a manipulator is defined."; } 36 36 } 37 37 … … 39 39 : base() { 40 40 AddVariableInfo(new VariableInfo("Random", "A random generator (uniform)", typeof(MersenneTwister), VariableKind.In)); 41 AddVariableInfo(new VariableInfo("OperatorLibrary", "Operator library that defines operator mutations", typeof( GPOperatorLibrary), VariableKind.In));41 AddVariableInfo(new VariableInfo("OperatorLibrary", "Operator library that defines operator mutations", typeof(FunctionLibrary), VariableKind.In)); 42 42 AddVariableInfo(new VariableInfo("ShakingFactor", "Variable that determines the force of the shaking operation", typeof(DoubleData), VariableKind.In)); 43 43 AddVariableInfo(new VariableInfo("FunctionTree", "The function tree that should be mutated", typeof(IFunctionTree), VariableKind.In | VariableKind.Out)); … … 45 45 46 46 public override IOperation Apply(IScope scope) { 47 GPOperatorLibrary library = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);47 FunctionLibrary library = GetVariableValue<FunctionLibrary>("OperatorLibrary", scope, true); 48 48 IFunctionTree tree = GetVariableValue<IFunctionTree>("FunctionTree", scope, false); 49 49 MersenneTwister mt = GetVariableValue<MersenneTwister>("Random", scope, true); … … 56 56 57 57 TreeGardener gardener = new TreeGardener(mt, library); 58 var parametricBranches = gardener.GetAllSubTrees(tree).Where(branch => branch. Function.GetVariable(FunctionBase.MANIPULATION)!= null);58 var parametricBranches = gardener.GetAllSubTrees(tree).Where(branch => branch.Manipulator!= null); 59 59 foreach(IFunctionTree subTree in parametricBranches) { 60 IOperator mutation = (IOperator)subTree.Function.GetVariable(FunctionBase.MANIPULATION).Value;60 IOperator mutation = subTree.Manipulator; 61 61 62 62 // store all local variables into a temporary scope -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/Manipulation/OnePointShaker.cs
r1039 r2202 33 33 public class OnePointShaker : DelegatingOperator { 34 34 public override string Description { 35 get { return "Selects a random node of all tree-nodes that have a '"+FunctionBase.MANIPULATION+"' variabledefined and manipulates the selected node."; }35 get { return "Selects a random node of all tree-nodes that have a manipulator defined and manipulates the selected node."; } 36 36 } 37 37 38 38 public OnePointShaker() 39 39 : base() { 40 AddVariableInfo(new VariableInfo("OperatorLibrary", "Operator library that defines mutation operations for operators", typeof( GPOperatorLibrary), VariableKind.In));40 AddVariableInfo(new VariableInfo("OperatorLibrary", "Operator library that defines mutation operations for operators", typeof(FunctionLibrary), VariableKind.In)); 41 41 AddVariableInfo(new VariableInfo("Random", "A random generator (uniform)", typeof(MersenneTwister), VariableKind.In)); 42 42 AddVariableInfo(new VariableInfo("ShakingFactor", "Factor that determines the force of the shaking operation", typeof(DoubleData), VariableKind.In)); … … 45 45 46 46 public override IOperation Apply(IScope scope) { 47 GPOperatorLibrary library = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);47 FunctionLibrary library = GetVariableValue<FunctionLibrary>("OperatorLibrary", scope, true); 48 48 IFunctionTree tree = GetVariableValue<IFunctionTree>("FunctionTree", scope, false); 49 49 MersenneTwister mt = GetVariableValue<MersenneTwister>("Random", scope, true); … … 51 51 52 52 // get all nodes for which a manipulation is defined 53 var parametricBranches = gardener.GetAllSubTrees(tree).Where(branch => branch. Function.GetVariable(FunctionBase.MANIPULATION)!= null);53 var parametricBranches = gardener.GetAllSubTrees(tree).Where(branch => branch.Manipulator != null); 54 54 55 55 if(parametricBranches.Count() == 0) return null; // don't manipulate anything if there are no nodes with a manipulation operator 56 56 57 57 IFunctionTree selectedBranch = parametricBranches.ElementAt(mt.Next(parametricBranches.Count())); 58 IOperator mutation = (IOperator)selectedBranch.Function.GetVariable(FunctionBase.MANIPULATION).Value;58 IOperator mutation = selectedBranch.Manipulator; 59 59 CompositeOperation next = new CompositeOperation(); 60 60 -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/Manipulation/SubstituteSubTreeManipulation.cs
r656 r2202 39 39 : base() { 40 40 AddVariableInfo(new VariableInfo("Random", "Uniform random number generator", typeof(MersenneTwister), VariableKind.In)); 41 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof( GPOperatorLibrary), VariableKind.In));41 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof(FunctionLibrary), VariableKind.In)); 42 42 AddVariableInfo(new VariableInfo("MaxTreeHeight", "The maximal allowed height of the tree", typeof(IntData), VariableKind.In)); 43 43 AddVariableInfo(new VariableInfo("MaxTreeSize", "The maximal allowed size (number of nodes) of the tree", typeof(IntData), VariableKind.In)); … … 50 50 IFunctionTree root = GetVariableValue<IFunctionTree>("FunctionTree", scope, true); 51 51 MersenneTwister random = GetVariableValue<MersenneTwister>("Random", scope, true); 52 GPOperatorLibrary library = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);52 FunctionLibrary library = GetVariableValue<FunctionLibrary>("OperatorLibrary", scope, true); 53 53 int maxTreeHeight = GetVariableValue<IntData>("MaxTreeHeight", scope, true).Data; 54 54 int maxTreeSize = GetVariableValue<IntData>("MaxTreeSize", scope, true).Data; -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/ProbabilisticTreeCreator.cs
r1529 r2202 39 39 : base() { 40 40 AddVariableInfo(new VariableInfo("Random", "Uniform random number generator", typeof(MersenneTwister), VariableKind.In)); 41 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof( GPOperatorLibrary), VariableKind.In));41 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof(FunctionLibrary), VariableKind.In)); 42 42 AddVariableInfo(new VariableInfo("MinTreeSize", "The minimal allowed size of the tree", typeof(IntData), VariableKind.In)); 43 43 AddVariableInfo(new VariableInfo("MaxTreeSize", "The maximal allowed size of the tree", typeof(IntData), VariableKind.In)); … … 50 50 public override IOperation Apply(IScope scope) { 51 51 IRandom random = GetVariableValue<IRandom>("Random", scope, true); 52 GPOperatorLibrary opLibrary = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);52 FunctionLibrary opLibrary = GetVariableValue<FunctionLibrary>("OperatorLibrary", scope, true); 53 53 int minTreeSize = GetVariableValue<IntData>("MinTreeSize", scope, true).Data; 54 54 int maxTreeSize = GetVariableValue<IntData>("MaxTreeSize", scope, true).Data; -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/RampedTreeCreator.cs
r1529 r2202 37 37 : base() { 38 38 AddVariableInfo(new VariableInfo("Random", "Uniform random number generator", typeof(MersenneTwister), VariableKind.In)); 39 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof( GPOperatorLibrary), VariableKind.In));39 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof(FunctionLibrary), VariableKind.In)); 40 40 AddVariableInfo(new VariableInfo("MinTreeHeight", "The minimal allowed height of the tree", typeof(IntData), VariableKind.In)); 41 41 AddVariableInfo(new VariableInfo("MaxTreeHeight", "The maximal allowed height of the tree", typeof(IntData), VariableKind.In)); … … 48 48 public override IOperation Apply(IScope scope) { 49 49 IRandom random = GetVariableValue<IRandom>("Random", scope, true); 50 GPOperatorLibrary opLibrary = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);50 FunctionLibrary opLibrary = GetVariableValue<FunctionLibrary>("OperatorLibrary", scope, true); 51 51 int minTreeHeight = GetVariableValue<IntData>("MinTreeHeight", scope, true).Data; 52 52 int maxTreeHeight = GetVariableValue<IntData>("MaxTreeHeight", scope, true).Data; -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/Recombination/GPCrossoverBase.cs
r1286 r2202 36 36 public GPCrossoverBase() 37 37 : base() { 38 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof( GPOperatorLibrary), VariableKind.In));38 AddVariableInfo(new VariableInfo("OperatorLibrary", "The operator library containing all available operators", typeof(FunctionLibrary), VariableKind.In)); 39 39 AddVariableInfo(new VariableInfo("FunctionTree", "The tree to mutate", typeof(IFunctionTree), VariableKind.In | VariableKind.New)); 40 40 AddVariableInfo(new VariableInfo("TreeSize", "The size (number of nodes) of the tree", typeof(IntData), VariableKind.New)); … … 45 45 46 46 protected override void Cross(IScope scope, IRandom random) { 47 GPOperatorLibrary opLibrary = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);47 FunctionLibrary opLibrary = GetVariableValue<FunctionLibrary>("OperatorLibrary", scope, true); 48 48 TreeGardener gardener = new TreeGardener(random, opLibrary); 49 49 -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/Recombination/SizeFairCrossOver.cs
r1286 r2202 68 68 69 69 private IFunctionTree GetReplacementBranch(MersenneTwister random, TreeGardener gardener, IFunctionTree intoTree, IFunctionTree parent, int replacedBranchIndex, IFunctionTree fromTree, int maxTreeSize, int maxTreeHeight) { 70 IList<IFunction> allowedFunctions = gardener.GetAllowedSubFunctions(parent.Function, replacedBranchIndex);70 IList<IFunction> allowedFunctions = new List<IFunction>(gardener.GetAllowedSubFunctions(parent.Function, replacedBranchIndex)); 71 71 int removedBranchSize = parent.SubTrees[replacedBranchIndex].Size; 72 72 int maxBranchSize = maxTreeSize - (intoTree.Size - removedBranchSize); -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/Recombination/StandardCrossOver.cs
r1286 r2202 60 60 int maxInsertedBranchHeight = maxTreeHeight - gardener.GetBranchLevel(tree0, parent0); // branchlevel is 1 if tree0==parent0 61 61 62 IList<IFunction> allowedFunctions = gardener.GetAllowedSubFunctions(parent0.Function, replacedChildIndex);62 IList<IFunction> allowedFunctions = new List<IFunction>(gardener.GetAllowedSubFunctions(parent0.Function, replacedChildIndex)); 63 63 allowedCrossoverPoints = GetPossibleCrossoverPoints(gardener, tree1, maxInsertedBranchSize, maxInsertedBranchHeight, allowedFunctions); 64 64 } while (allowedCrossoverPoints.Count == 0 && tries++ < MaxRecombinationTries); -
branches/GP-Refactoring-713/sources/HeuristicLab.GP/3.3/TreeGardener.cs
r1529 r2202 36 36 internal class TreeGardener { 37 37 private IRandom random; 38 private GPOperatorLibrary funLibrary;38 private FunctionLibrary funLibrary; 39 39 private List<IFunction> functions; 40 40 … … 50 50 51 51 #region constructors 52 internal TreeGardener(IRandom random, GPOperatorLibrary funLibrary) {52 internal TreeGardener(IRandom random, FunctionLibrary funLibrary) { 53 53 this.random = random; 54 54 this.funLibrary = funLibrary; … … 57 57 functions = new List<IFunction>(); 58 58 // init functions and terminals based on constraints 59 foreach(IFunction fun in funLibrary. Group.Operators) {59 foreach(IFunction fun in funLibrary.Functions) { 60 60 if(fun.MaxArity == 0) { 61 61 terminals.Add(fun); … … 112 112 } 113 113 int actualArity = random.Next(minArity, maxArity + 1); 114 totalListMinSize += GetMinimalTreeSize(root.Function)- 1;114 totalListMinSize += root.Function.MinTreeSize - 1; 115 115 for(int i = 0; i < actualArity; i++) { 116 116 // insert a dummy sub-tree and add the pending extension to the list … … 134 134 } else { 135 135 IFunction selectedFunction = RandomSelect(GetAllowedSubFunctions(parent.Function, a).Where( 136 f => !IsTerminal(f) && GetMinimalTreeHeight(f)+ (d - 1) <= maxDepth).ToArray());136 f => !IsTerminal(f) && f.MinTreeHeight + (d - 1) <= maxDepth).ToArray()); 137 137 IFunctionTree newTree = selectedFunction.GetTreeNode(); 138 138 parent.RemoveSubTree(a); … … 152 152 list.Add(new object[] { newTree, i, d + 1 }); 153 153 } 154 totalListMinSize += GetMinimalTreeSize(newTree.Function)- 1;154 totalListMinSize += newTree.Function.MinTreeSize - 1; 155 155 } 156 156 } … … 178 178 internal IFunctionTree CreateRandomTree(ICollection<IFunction> allowedFunctions, int maxTreeSize, int maxTreeHeight) { 179 179 // get the minimal needed height based on allowed functions and extend the max-height if necessary 180 int minTreeHeight = allowedFunctions.Select(f => GetMinimalTreeHeight(f)).Min();180 int minTreeHeight = allowedFunctions.Select(f => f.MinTreeHeight).Min(); 181 181 if(minTreeHeight > maxTreeHeight) 182 182 maxTreeHeight = minTreeHeight; 183 183 // get the minimal needed size based on allowed functions and extend the max-size if necessary 184 int minTreeSize = allowedFunctions.Select(f => GetMinimalTreeSize(f)).Min();184 int minTreeSize = allowedFunctions.Select(f => f.MinTreeSize).Min(); 185 185 if(minTreeSize > maxTreeSize) 186 186 maxTreeSize = minTreeSize; … … 191 191 192 192 // filter the set of allowed functions and select only from those that fit into the given maximal size and height limits 193 IFunction[] possibleFunctions = allowedFunctions.Where(f => GetMinimalTreeHeight(f)<= treeHeight &&194 GetMinimalTreeSize(f)<= treeSize).ToArray();193 IFunction[] possibleFunctions = allowedFunctions.Where(f => f.MinTreeHeight <= treeHeight && 194 f.MinTreeSize <= treeSize).ToArray(); 195 195 IFunction selectedFunction = RandomSelect(possibleFunctions); 196 196 … … 206 206 Scope tempScope = new Scope("Temp. initialization scope"); 207 207 208 var parametricTrees = trees.Where(t => t. Function.GetVariable(FunctionBase.INITIALIZATION)!= null);208 var parametricTrees = trees.Where(t => t.Initializer != null); 209 209 foreach(IFunctionTree tree in parametricTrees) { 210 210 // enqueue an initialization operation for each operator with local variables 211 IOperator initialization = (IOperator)tree.Function.GetVariable(FunctionBase.INITIALIZATION).Value;211 IOperator initialization = tree.Initializer; 212 212 Scope initScope = new Scope(); 213 213 // copy the local variables into a temporary scope used for initialization … … 280 280 internal bool IsValidTree(IFunctionTree tree) { 281 281 for(int i = 0; i < tree.SubTrees.Count; i++) { 282 if(!tree.Function. AllowedSubFunctions(i).Contains(tree.SubTrees[i].Function)) return false;282 if(!tree.Function.GetAllowedSubFunctions(i).Contains(tree.SubTrees[i].Function)) return false; 283 283 } 284 284 … … 329 329 // we only count those slots that can hold at least one of the children that we should combine 330 330 for(int slot = 0; slot < nSlots; slot++) { 331 HashSet<IFunction> functionSet = new HashSet<IFunction>(f. AllowedSubFunctions(slot));331 HashSet<IFunction> functionSet = new HashSet<IFunction>(f.GetAllowedSubFunctions(slot)); 332 332 if(functionSet.Count() > 0) { 333 333 slotSets.Add(functionSet); … … 378 378 return f.MinArity == 0 && f.MaxArity == 0; 379 379 } 380 internal I List<IFunction> GetAllowedSubFunctions(IFunction f, int index) {380 internal ICollection<IFunction> GetAllowedSubFunctions(IFunction f, int index) { 381 381 if(f == null) { 382 382 return allFunctions; 383 383 } else { 384 return f. AllowedSubFunctions(index);384 return f.GetAllowedSubFunctions(index); 385 385 } 386 386 } … … 393 393 return selectedTerminal; 394 394 } else { 395 IFunction[] possibleFunctions = functions.Where(f => GetMinimalTreeHeight(f)<= maxTreeHeight &&396 GetMinimalTreeSize(f)<= maxTreeSize).ToArray();395 IFunction[] possibleFunctions = functions.Where(f => f.MinTreeHeight <= maxTreeHeight && 396 f.MinTreeSize <= maxTreeSize).ToArray(); 397 397 IFunction selectedFunction = RandomSelect(possibleFunctions); 398 398 return selectedFunction; … … 409 409 IFunctionTree parentTree = parent.GetTreeNode(); 410 410 for(int i = 0; i < actualArity; i++) { 411 IFunction[] possibleFunctions = GetAllowedSubFunctions(parent, i).Where(f => GetMinimalTreeHeight(f)<= maxTreeHeight).ToArray();411 IFunction[] possibleFunctions = GetAllowedSubFunctions(parent, i).Where(f => f.MinTreeHeight <= maxTreeHeight).ToArray(); 412 412 IFunction selectedFunction = RandomSelect(possibleFunctions); 413 413 IFunctionTree newSubTree = MakeUnbalancedTree(selectedFunction, maxTreeHeight - 1); … … 431 431 for(int i = 0; i < actualArity; i++) { 432 432 // first try to find a function that fits into the maxHeight limit 433 IFunction[] possibleFunctions = GetAllowedSubFunctions(parent, i).Where(f => GetMinimalTreeHeight(f)<= maxTreeHeight &&433 IFunction[] possibleFunctions = GetAllowedSubFunctions(parent, i).Where(f => f.MinTreeHeight <= maxTreeHeight && 434 434 !IsTerminal(f)).ToArray(); 435 435 // no possible function found => extend function set to terminals … … 450 450 } 451 451 452 private int GetMinimalTreeHeight(IOperator op) {453 return ((IntData)op.GetVariable(GPOperatorLibrary.MIN_TREE_HEIGHT).Value).Data;454 }455 456 private int GetMinimalTreeSize(IOperator op) {457 return ((IntData)op.GetVariable(GPOperatorLibrary.MIN_TREE_SIZE).Value).Data;458 }459 460 452 private void TreeForEach(IFunctionTree tree, Action<IFunctionTree> action) { 461 453 action(tree); … … 479 471 // precalculate the slot-sizes 480 472 foreach(IFunction function in functionSet) { 481 ticketAccumulator += ((DoubleData)function.GetVariable(GPOperatorLibrary.TICKETS).Value).Data;473 ticketAccumulator += function.Tickets; 482 474 accumulatedTickets[i] = ticketAccumulator; 483 475 i++;
Note: See TracChangeset
for help on using the changeset viewer.