Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
07/20/09 20:14:47 (15 years ago)
Author:
gkronber
Message:

Implemented #302 (Show variable names instead of var<index> in GP function trees).

  • Added a new operator that chooses a random value from a list of possible values.
  • Changed mutation operator for variables and differentials
  • Changed internal linear representation of function trees to support different types for local data.
File:
1 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.GP/3.3/BakedFunctionTree.cs

    r1529 r2174  
    3434    public byte arity = 0;
    3535    public IFunction functionType;
    36     public List<double> data = new List<double>();
     36    public List<object> localData = new List<object>();
    3737
    3838    public LightWeightFunction Clone() {
     
    4040      clone.arity = arity;
    4141      clone.functionType = functionType;
    42       clone.data.AddRange(data);
     42      clone.localData.AddRange(localData);
    4343      return clone;
    4444    }
     
    5050      get {
    5151        FlattenVariables();
    52         FlattenTrees(); 
     52        FlattenTrees();
    5353        return linearRepresentation;
    5454      }
     
    7272      variables = new List<IVariable>();
    7373      variablesExpanded = true;
    74       foreach(IVariableInfo variableInfo in function.VariableInfos) {
    75         if(variableInfo.Local) {
     74      foreach (IVariableInfo variableInfo in function.VariableInfos) {
     75        if (variableInfo.Local) {
    7676          variables.Add((IVariable)function.GetVariable(variableInfo.FormalName).Clone());
    7777        }
     
    8484      fun.functionType = tree.Function;
    8585      linearRepresentation.Add(fun);
    86       foreach(IVariable variable in tree.LocalVariables) {
    87         IItem value = variable.Value;
    88         fun.data.Add(GetDoubleValue(value));
    89       }
    90       foreach(IFunctionTree subTree in tree.SubTrees) {
     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) {
    9191        AddSubTree(new BakedFunctionTree(subTree));
    9292      }
    93     }
    94 
    95     private double GetDoubleValue(IItem value) {
    96       if(value is DoubleData) {
    97         return ((DoubleData)value).Data;
    98       } else if(value is ConstrainedDoubleData) {
    99         return ((ConstrainedDoubleData)value).Data;
    100       } else if(value is IntData) {
    101         return ((IntData)value).Data;
    102       } else if(value is ConstrainedIntData) {
    103         return ((ConstrainedIntData)value).Data;
    104       } else throw new NotSupportedException("Invalid datatype of local variable for GP");
    10593    }
    10694
     
    10896      int arity = linearRepresentation[branchRoot].arity;
    10997      int length = 1;
    110       for(int i = 0; i < arity; i++) {
     98      for (int i = 0; i < arity; i++) {
    11199        length += BranchLength(branchRoot + length);
    112100      }
     
    115103
    116104    private void FlattenTrees() {
    117       if(treesExpanded) {
     105      if (treesExpanded) {
    118106        linearRepresentation[0].arity = (byte)subTrees.Count;
    119         foreach(BakedFunctionTree subTree in subTrees) {
     107        foreach (BakedFunctionTree subTree in subTrees) {
    120108          subTree.FlattenVariables();
    121109          subTree.FlattenTrees();
     
    128116
    129117    private void FlattenVariables() {
    130       if(variablesExpanded) {
    131         linearRepresentation[0].data.Clear();
    132         foreach(IVariable variable in variables) {
    133           linearRepresentation[0].data.Add(GetDoubleValue(variable.Value));
     118      if (variablesExpanded) {
     119        linearRepresentation[0].localData.Clear();
     120        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);
    134124        }
    135125        variablesExpanded = false;
     
    140130    public int Size {
    141131      get {
    142         if(treesExpanded) {
     132        if (treesExpanded) {
    143133          int size = 1;
    144           foreach(BakedFunctionTree tree in subTrees) {
     134          foreach (BakedFunctionTree tree in subTrees) {
    145135            size += tree.Size;
    146136          }
    147137          return size;
    148         } else 
    149         return linearRepresentation.Count;
     138        } else
     139          return linearRepresentation.Count;
    150140      }
    151141    }
     
    153143    public int Height {
    154144      get {
    155         if(treesExpanded) {
     145        if (treesExpanded) {
    156146          int height = 0;
    157           foreach(IFunctionTree subTree in subTrees) {
     147          foreach (IFunctionTree subTree in subTrees) {
    158148            int curHeight = subTree.Height;
    159             if(curHeight > height) height = curHeight;
    160           }
    161           return height+1;
     149            if (curHeight > height) height = curHeight;
     150          }
     151          return height + 1;
    162152        } else {
    163153          int nextBranchStart;
     
    171161      int height = 0;
    172162      branchStart++;
    173       for(int i = 0; i < f.arity; i++) {
     163      for (int i = 0; i < f.arity; i++) {
    174164        int curHeight = BranchHeight(branchStart, out nextBranchStart);
    175         if(curHeight > height) height = curHeight;
     165        if (curHeight > height) height = curHeight;
    176166        branchStart = nextBranchStart;
    177167      }
     
    182172    public IList<IFunctionTree> SubTrees {
    183173      get {
    184         if(!treesExpanded) {
     174        if (!treesExpanded) {
    185175          subTrees = new List<IFunctionTree>();
    186176          int arity = linearRepresentation[0].arity;
    187177          int branchIndex = 1;
    188           for(int i = 0; i < arity; i++) {
     178          for (int i = 0; i < arity; i++) {
    189179            BakedFunctionTree subTree = new BakedFunctionTree();
    190180            int length = BranchLength(branchIndex);
    191             for(int j = branchIndex; j < branchIndex + length; j++) {
     181            for (int j = branchIndex; j < branchIndex + length; j++) {
    192182              subTree.linearRepresentation.Add(linearRepresentation[j]);
    193183            }
     
    205195    public ICollection<IVariable> LocalVariables {
    206196      get {
    207         if(!variablesExpanded) {
     197        if (!variablesExpanded) {
    208198          variables = new List<IVariable>();
    209199          IFunction function = Function;
    210200          int localVariableIndex = 0;
    211           foreach(IVariableInfo variableInfo in function.VariableInfos) {
    212             if(variableInfo.Local) {
     201          foreach (IVariableInfo variableInfo in function.VariableInfos) {
     202            if (variableInfo.Local) {
    213203              IVariable clone = (IVariable)function.GetVariable(variableInfo.FormalName).Clone();
    214               IItem value = clone.Value;
    215               if(value is ConstrainedDoubleData) {
    216                 ((ConstrainedDoubleData)value).Data = linearRepresentation[0].data[localVariableIndex];
    217               } else if(value is ConstrainedIntData) {
    218                 ((ConstrainedIntData)value).Data = (int)linearRepresentation[0].data[localVariableIndex];
    219               } else if(value is DoubleData) {
    220                 ((DoubleData)value).Data = linearRepresentation[0].data[localVariableIndex];
    221               } else if(value is IntData) {
    222                 ((IntData)value).Data = (int)linearRepresentation[0].data[localVariableIndex];
    223               } else throw new NotSupportedException("Invalid local variable type for GP.");
     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              }
    224212              variables.Add(clone);
    225213              localVariableIndex++;
     
    227215          }
    228216          variablesExpanded = true;
    229           linearRepresentation[0].data.Clear();
     217          linearRepresentation[0].localData.Clear();
    230218        }
    231219        return variables;
     
    238226
    239227    public IVariable GetLocalVariable(string name) {
    240       foreach(IVariable var in LocalVariables) {
    241         if(var.Name == name) return var;
     228      foreach (IVariable var in LocalVariables) {
     229        if (var.Name == name) return var;
    242230      }
    243231      return null;
     
    253241
    254242    public void AddSubTree(IFunctionTree tree) {
    255       if(!treesExpanded) throw new InvalidOperationException();
     243      if (!treesExpanded) throw new InvalidOperationException();
    256244      subTrees.Add(tree);
    257245    }
    258246
    259247    public void InsertSubTree(int index, IFunctionTree tree) {
    260       if(!treesExpanded) throw new InvalidOperationException();
     248      if (!treesExpanded) throw new InvalidOperationException();
    261249      subTrees.Insert(index, tree);
    262250    }
     
    264252    public void RemoveSubTree(int index) {
    265253      // sanity check
    266       if(!treesExpanded) throw new InvalidOperationException();
     254      if (!treesExpanded) throw new InvalidOperationException();
    267255      subTrees.RemoveAt(index);
    268256    }
     
    273261      XmlNode node = base.GetXmlNode(name, document, persistedObjects);
    274262      XmlNode linearRepresentationNode = document.CreateElement("LinearRepresentation");
    275       foreach(LightWeightFunction f in linearRepresentation) {
    276         XmlNode entryNode = PersistenceManager.Persist("FunctionType", f.functionType, document, persistedObjects);
     263      foreach (LightWeightFunction f in linearRepresentation) {
     264        XmlNode entryNode = PersistenceManager.Persist("Function", f.functionType, document, persistedObjects);
    277265        XmlAttribute arityAttribute = document.CreateAttribute("Arity");
    278         arityAttribute.Value = f.arity+"";
     266        arityAttribute.Value = XmlConvert.ToString(f.arity);
    279267        entryNode.Attributes.Append(arityAttribute);
    280         if(f.data.Count > 0) {
    281           XmlAttribute dataAttribute = document.CreateAttribute("Data");
    282           dataAttribute.Value = GetString(f.data);
    283           entryNode.Attributes.Append(dataAttribute);
     268        foreach (object o in f.localData) {
     269          if (f.localData.Count > 0) {
     270            entryNode.AppendChild(CreateDataNode(document, o));
     271          }
    284272        }
    285273        linearRepresentationNode.AppendChild(entryNode);
     
    287275
    288276      node.AppendChild(linearRepresentationNode);
     277      return node;
     278    }
     279
     280    private XmlNode CreateDataNode(XmlDocument doc, object o) {
     281      XmlNode node = doc.CreateElement("Data");
     282      XmlAttribute typeAttr = doc.CreateAttribute("Type");
     283      node.Attributes.Append(typeAttr);
     284      if (o is double) {
     285        node.Value = XmlConvert.ToString((double)o);
     286        typeAttr.Value = "d";
     287      } else if (o is int) {
     288        node.Value = XmlConvert.ToString((int)o);
     289        typeAttr.Value = "i";
     290      } else if (o is string) {
     291        node.Value = (string)o;
     292        typeAttr.Value = "s";
     293      } else throw new ArgumentException("Invalid type for local data element: " + o);
    289294      return node;
    290295    }
     
    293298      base.Populate(node, restoredObjects);
    294299      XmlNode linearRepresentationNode = node.SelectSingleNode("LinearRepresentation");
    295       foreach(XmlNode entryNode in linearRepresentationNode.ChildNodes) {
     300      foreach (XmlNode entryNode in linearRepresentationNode.ChildNodes) {
    296301        LightWeightFunction f = new LightWeightFunction();
    297         f.arity = byte.Parse(entryNode.Attributes["Arity"].Value, CultureInfo.InvariantCulture);
    298         if(entryNode.Attributes["Data"]!=null)
    299           f.data = GetList<double>(entryNode.Attributes["Data"].Value, s => double.Parse(s, CultureInfo.InvariantCulture));
     302        f.arity = XmlConvert.ToByte(entryNode.Attributes["Arity"].Value);
     303        foreach (XmlNode dataNode in entryNode.ChildNodes) {
     304          f.localData.Add(ParseDataNode(dataNode));
     305        }
    300306        f.functionType = (IFunction)PersistenceManager.Restore(entryNode, restoredObjects);
    301307        linearRepresentation.Add(f);
     
    305311    }
    306312
    307     private string GetString(IEnumerable<double> xs) {
    308       StringBuilder builder = new StringBuilder();
    309       foreach(double x in xs) {
    310         builder.Append(x.ToString("r", CultureInfo.InvariantCulture) + "; ");
    311       }
    312       if(builder.Length > 0) builder.Remove(builder.Length - 2, 2);
    313       return builder.ToString();
    314     }
    315 
    316     private List<T> GetList<T>(string s, Converter<string, T> converter) {
    317       List<T> result = new List<T>();
    318       string[] tokens = s.Split(new char[] { ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
    319       foreach(string token in tokens) {
    320         T x = converter(token.Trim());
    321         result.Add(x);
    322       }
    323       return result;
    324     }
     313    private object ParseDataNode(XmlNode dataNode) {
     314      string type = dataNode.Attributes["Type"].Value;
     315      if (type == "d") {
     316        return XmlConvert.ToDouble(dataNode.Value);
     317      } else if (type == "i") {
     318        return XmlConvert.ToInt32(dataNode.Value);
     319      } else if (type == "s") {
     320        return dataNode.Value;
     321      } else throw new FormatException("Can't parse type \"" + type + "\" \"" + dataNode.Value + "\" as local data for GP trees");
     322    }
     323
     324    //private string GetString(IEnumerable<double> xs) {
     325    //  StringBuilder builder = new StringBuilder();
     326    //  foreach (double x in xs) {
     327    //    builder.Append(x.ToString("r", CultureInfo.InvariantCulture) + "; ");
     328    //  }
     329    //  if (builder.Length > 0) builder.Remove(builder.Length - 2, 2);
     330    //  return builder.ToString();
     331    //}
     332
     333    //private List<T> GetList<T>(string s, Converter<string, T> converter) {
     334    //  List<T> result = new List<T>();
     335    //  string[] tokens = s.Split(new char[] { ';', ' ' }, StringSplitOptions.RemoveEmptyEntries);
     336    //  foreach (string token in tokens) {
     337    //    T x = converter(token.Trim());
     338    //    result.Add(x);
     339    //  }
     340    //  return result;
     341    //}
    325342
    326343    public override object Clone(IDictionary<Guid, object> clonedObjects) {
    327344      BakedFunctionTree clone = new BakedFunctionTree();
    328345      // in case the user (de)serialized the tree between evaluation and selection we have to flatten the tree again.
    329       if(treesExpanded) FlattenTrees();
    330       if(variablesExpanded) FlattenVariables();
    331       foreach(LightWeightFunction f in linearRepresentation) {
     346      if (treesExpanded) FlattenTrees();
     347      if (variablesExpanded) FlattenVariables();
     348      foreach (LightWeightFunction f in linearRepresentation) {
    332349        clone.linearRepresentation.Add(f.Clone());
    333350      }
Note: See TracChangeset for help on using the changeset viewer.