Free cookie consent management tool by TermsFeed Policy Generator

Changeset 142


Ignore:
Timestamp:
04/21/08 00:17:54 (17 years ago)
Author:
gkronber
Message:

Created a branch for refactoring functions and structId. Largest change: splitting IFunction/FunctionBase into two classes, one for the function and one for the treenode+local variables. _work in progress_

Location:
branches/FunctionsAndStructIdRefactoring
Files:
3 added
1 deleted
38 edited
1 copied

Legend:

Unmodified
Added
Removed
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Addition.cs

    r2 r142  
    3333    public override string Description {
    3434      get {
    35         return @"Returns the sum of all sub-operator results.
     35        return @"Returns the sum of all sub-tree results.
    3636    (+ 3) => 3
    3737    (+ 2 3) => 5
     
    4646    }
    4747
    48     public Addition(Addition source, IDictionary<Guid, object> clonedObjects)
    49       : base(source, clonedObjects) {
    50     }
    51 
    52 
    53     public override double Evaluate(Dataset dataset, int sampleIndex) {
     48    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
    5449      // (+ 3) => 3
    5550      // (+ 2 3) => 5
    5651      // (+ 3 4 5) => 12
    5752      double sum = 0.0;
    58       for (int i = SubFunctions.Count - 1; i >= 0; i--) {
    59         sum += SubFunctions[i].Evaluate(dataset, sampleIndex);
     53      for (int i = 0; i < args.Length; i++) {
     54        sum += args[i];
    6055      }
    6156      return sum;
    62     }
    63 
    64     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    65       Addition clone = new Addition(this, clonedObjects);
    66       clonedObjects.Add(clone.Guid, clone);
    67       return clone;
    6857    }
    6958
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/And.cs

    r2 r142  
    3131    public override string Description {
    3232      get {
    33         return @"Logical AND operation. Only defined for sub-operator-results 0.0 and 1.0.";
     33        return @"Logical AND operation. Only defined for sub-tree-results 0.0 and 1.0.
     34AND is a special form, sub-trees are evaluated from the first to the last. Evaluation is
     35stopped as soon as one of the sub-trees evaluates to 0.0 (false).";
    3436      }
    3537    }
     
    4042    }
    4143
    42     public And(And source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
    44     }
    45 
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
    48       foreach(IFunction subFunction in SubFunctions) {
     44    // special form
     45    public override double Evaluate(Dataset dataset, int sampleIndex, IList<IFunctionTree> subFunctions) {
     46      foreach(IFunctionTree subFunction in subFunctions) {
    4947        double result = Math.Round(subFunction.Evaluate(dataset, sampleIndex));
    50         if(result == 0.0) return 0.0;
     48        if(result == 0.0) return 0.0; // one sub-tree is 0.0 (false) => return false
    5149        else if(result != 1.0) return double.NaN;
    5250      }
     51      // all sub-trees evaluated to 1.0 (true) => return 1.0 (true)
    5352      return 1.0;
    5453    }
    5554
    56     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    57       And clone = new And(this, clonedObjects);
    58       clonedObjects.Add(clone.Guid, clone);
    59       return clone;
     55    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     56      throw new NotImplementedException();
    6057    }
    6158
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Average.cs

    r2 r142  
    3131    public override string Description {
    3232      get {
    33         return @"Returns the average (arithmetic mean) of all sub-operator results.";
     33        return @"Returns the average (arithmetic mean) of all sub-tree results.";
    3434      }
    3535    }
     
    4040    }
    4141
    42     public Average(Average source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
    44     }
    45 
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
    4843      double sum = 0.0;
    49       for(int i = 0; i < SubFunctions.Count; i++) {
    50         sum += SubFunctions[i].Evaluate(dataset, sampleIndex);
     44      for(int i = 0; i < args.Length; i++) {
     45        sum += args[i];
    5146      }
    52       return sum / SubFunctions.Count;
    53     }
    54 
    55     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    56       Average clone = new Average(this, clonedObjects);
    57       clonedObjects.Add(clone.Guid, clone);
    58       return clone;
     47      return sum / args.Length;
    5948    }
    6049
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Constant.cs

    r2 r142  
    3131namespace HeuristicLab.Functions {
    3232  public class Constant : FunctionBase {
    33 
    34     private IVariable value;
    35 
    3633    public override string Description {
    3734      get { return "Returns the value of local variable 'Value'."; }
    3835    }
    3936
     37    private ConstrainedDoubleData value;
    4038    public ConstrainedDoubleData Value {
    4139      get {
    42         return (ConstrainedDoubleData)value.Value;
     40        return value;
    4341      }
    4442    }
     
    5452
    5553      // create the local variable
    56       value = new HeuristicLab.Core.Variable("Value", valueData);
    57       AddLocalVariable(value);
     54      HeuristicLab.Core.Variable value = new HeuristicLab.Core.Variable("Value", valueData);
     55      AddVariable(value);
    5856
    5957      // constant can't have suboperators
     
    6159    }
    6260
    63     public Constant(Constant source, IDictionary<Guid, object> clonedObjects)
    64       : base(source, clonedObjects) {
    65       value = GetVariable("Value");
    66     }
    67 
    6861    public override object Clone(IDictionary<Guid, object> clonedObjects) {
    69       Constant clone = new Constant(this, clonedObjects);
    70       clonedObjects.Add(clone.Guid, clone);
     62      Constant clone = (Constant)base.Clone(clonedObjects);
     63      clone.value = (ConstrainedDoubleData)clone.GetVariable("Value").Value;
    7164      return clone;
    7265    }
    7366
    74 
    7567    public override void Populate(XmlNode node, IDictionary<Guid,IStorable> restoredObjects) {
    7668      base.Populate(node, restoredObjects);
    77 
    78       value = GetVariable("Value");
     69      value = (ConstrainedDoubleData)GetVariable("Value").Value;
    7970    }
    8071
    81     public override double Evaluate(Dataset dataset, int sampleIndex) {
    82       return ((ConstrainedDoubleData)value.Value).Data;
     72    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     73      return value.Data;
    8374    }
    8475
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Cosinus.cs

    r2 r142  
    3131  public class Cosinus : FunctionBase {
    3232    public override string Description {
    33       get { return "Returns the cosinus of the first sub-operator."; }
     33      get { return "Returns the cosinus of the first sub-tree."; }
    3434    }
    3535
    3636    public Cosinus()
    3737      : base() {
    38 
    3938      // must have exactly one subfunction
    4039      AddConstraint(new NumberOfSubOperatorsConstraint(1, 1));
    4140    }
    4241
    43     public Cosinus(Cosinus source, IDictionary<Guid, object> clonedObjects)
    44       : base(source, clonedObjects) {
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     43      return Math.Cos(args[0]);
    4544    }
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
    48       return Math.Cos(SubFunctions[0].Evaluate(dataset, sampleIndex));
    49     }
    50 
    51     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    52       Cosinus clone = new Cosinus(this, clonedObjects);
    53       clonedObjects.Add(clone.Guid, clone);
    54       return clone;
    55     }
    56 
    5745
    5846    public override void Accept(IFunctionVisitor visitor) {
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Division.cs

    r2 r142  
    3636      get {
    3737        return @"Protected division
    38 Divides the result of the first sub-operator by the results of the following sub-operators.
     38Divides the result of the first sub-tree by the results of the following sub-tree.
    3939In case one of the divisors is 0 returns 0.
    4040    (/ 3) => 1/3
     
    4848    public Division()
    4949      : base() {
    50 
    5150      // 2 - 3 seems like an reasonable defaut (used for +,-,*,/) (discussion with swinkler and maffenze)
    5251      AddConstraint(new NumberOfSubOperatorsConstraint(2, 3));
    5352    }
    5453
    55     public Division(Division source, IDictionary<Guid, object> clonedObjects)
    56       : base(source, clonedObjects) {
    57     }
    58 
    59     public override double Evaluate(Dataset dataset, int sampleIndex) {
     54    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
    6055      // (/ 3) => 1/3
    6156      // (/ 2 3) => 2/3
    6257      // (/ 3 4 5) => 3/20
    6358
    64       if(SubFunctions.Count == 1) {
    65         double divisor = SubFunctions[0].Evaluate(dataset, sampleIndex);
     59      if(args.Length == 1) {
     60        double divisor = args[0];
    6661        if(Math.Abs(divisor) < EPSILON) return 0;
    6762        else return 1.0 / divisor;
    6863      } else {
    69         double result = SubFunctions[0].Evaluate(dataset, sampleIndex);
    70         for(int i = 1; i < SubFunctions.Count; i++) {
    71           double divisor = SubFunctions[i].Evaluate(dataset, sampleIndex);
     64        double result = args[0];
     65        for(int i = 1; i < args.Length; i++) {
     66          double divisor = args[i];
    7267          if(Math.Abs(divisor) < EPSILON) return 0.0;
    7368          result /= divisor;
     
    7772    }
    7873
    79     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    80       Division clone = new Division(this, clonedObjects);
    81       clonedObjects.Add(clone.Guid, clone);
    82       return clone;
    83     }
    84 
    8574    public override void Accept(IFunctionVisitor visitor) {
    8675      visitor.Visit(this);
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Equal.cs

    r2 r142  
    3131    public override string Description {
    3232      get {
    33         return @"Equal condition. Returns 1.0 if both sub-functions evaluate to the same value and 0.0 if they differ.";
     33        return @"Equal condition. Returns 1.0 if both sub-trees evaluate to the same value and 0.0 if they differ.";
    3434      }
    3535    }
     
    4040    }
    4141
    42     public Equal(Equal source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
    44     }
    45 
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
    48       if(SubFunctions[0].Evaluate(dataset, sampleIndex) == SubFunctions[1].Evaluate(dataset, sampleIndex)) return 1.0;
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     43      if(args[0] == args[1]) return 1.0;
    4944      else return 0.0;
    50     }
    51 
    52     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    53       Equal clone = new Equal(this, clonedObjects);
    54       clonedObjects.Add(clone.Guid, clone);
    55       return clone;
    5645    }
    5746
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Exponential.cs

    r2 r142  
    3131  public class Exponential : FunctionBase {
    3232    public override string Description {
    33       get { return "Returns returns exponential of the first sub-operator (power(e, x))."; }
     33      get { return "Returns returns exponential of the first sub-tree (power(e, x))."; }
    3434    }
    3535
     
    3939      AddConstraint(new NumberOfSubOperatorsConstraint(1, 1));
    4040    }
    41     public Exponential(Exponential source, IDictionary<Guid, object> clonedObjects)
    42       : base(source, clonedObjects) {
     41
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     43      return Math.Exp(args[0]);
    4344    }
    44 
    45 
    46     public override double Evaluate(Dataset dataset, int sampleIndex) {
    47       return Math.Exp(SubFunctions[0].Evaluate(dataset, sampleIndex));
    48     }
    49 
    50     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    51       Exponential clone = new Exponential(this, clonedObjects);
    52       clonedObjects.Add(clone.Guid, clone);
    53       return clone;
    54     }
    55 
    5645
    5746    public override void Accept(IFunctionVisitor visitor) {
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/FunctionBase.cs

    r2 r142  
    2929
    3030namespace HeuristicLab.Functions {
     31  /// <summary>
     32  /// Functions are like operators except that they do not allow sub-operators and the normal form of evaluation
     33  /// is to evaluate all children first.
     34  /// </summary>
    3135  public abstract class FunctionBase : OperatorBase, IFunction {
    32     private List<IFunction> subFunctions;
    33     // instance subfunctions
    34     public IList<IFunction> SubFunctions {
    35       get {
    36         return subFunctions;
     36   
     37    public virtual double Evaluate(Dataset dataset, int sampleIndex, IList<IFunctionTree> subTrees) {
     38      if(subTrees.Count > 0) {
     39        double[] evaluationResults = new double[subTrees.Count];
     40        for(int i = 0; i < evaluationResults.Length; i++) {
     41          evaluationResults[i] = subTrees[i].Evaluate(dataset, sampleIndex);
     42        }
     43        return Apply(dataset, sampleIndex, evaluationResults);
     44      } else {
     45        return Apply(dataset, sampleIndex, null);
    3746      }
    3847    }
    3948
    40     // instance variables
    41     private List<IVariable> variables;
    42     public ICollection<IVariable> LocalVariables {
    43       get { return variables.AsReadOnly(); }
     49    public abstract double Apply(Dataset dataset, int sampleIndex, double[] args);
     50
     51    // operator-tree style evaluation is not supported for functions.
     52    public override IOperation Apply(IScope scope) {
     53      throw new NotSupportedException();
    4454    }
    45 
    46     // reference to the 'type' of the function
    47     private FunctionBase metaObject;
    48     public IFunction MetaObject {
    49       get { return metaObject; }
    50     }
    51 
    52     public FunctionBase() {
    53       metaObject = this; // (FunctionBase)Activator.CreateInstance(this.GetType());
    54       AddVariableInfo(new VariableInfo("Dataset", "Dataset from which to read samples", typeof(DoubleMatrixData), VariableKind.In));
    55       AddVariableInfo(new VariableInfo("SampleIndex", "Gives the row index from which to read the sample", typeof(IntData), VariableKind.In));
    56       AddVariableInfo(new VariableInfo("Result", "The result of the evaluation of the function", typeof(DoubleData), VariableKind.Out));
    57 
    58       subFunctions = new List<IFunction>();
    59       variables = new List<IVariable>();
    60     }
    61 
    62     public FunctionBase(FunctionBase source, IDictionary<Guid, object> clonedObjects)
    63       : base() {
    64       this.metaObject = source.metaObject;
    65       variables = new List<IVariable>();
    66       subFunctions = new List<IFunction>();
    67       foreach (IFunction subFunction in source.SubFunctions) {
    68         subFunctions.Add((IFunction)Auxiliary.Clone(subFunction, clonedObjects));
    69       }
    70       foreach (IVariable variable in source.variables) {
    71         variables.Add((IVariable)Auxiliary.Clone(variable, clonedObjects));
    72       }
    73     }
    74 
    75     public abstract double Evaluate(Dataset dataset, int sampleIndex);
    76 
    77     public override IOperation Apply(IScope scope) {
    78       DoubleData result = this.GetVariableValue<DoubleData>("Result", scope, false);
    79       Dataset dataset = GetVariableValue<Dataset>("Dataset", scope, true);
    80       IntData sampleIndex = GetVariableValue<IntData>("SampleIndex", scope, true);
    81       result.Data = Evaluate(dataset, sampleIndex.Data);
    82       return null;
    83     }
    84 
    8555    public virtual void Accept(IFunctionVisitor visitor) {
    8656      visitor.Visit(this);
    8757    }
    8858
     59    public override IList<IOperator> SubOperators {
     60      get { throw new NotSupportedException(); }
     61    }
     62
    8963    public override void AddSubOperator(IOperator subOperator) {
    90       subFunctions.Add((IFunction)subOperator);
     64      throw new NotSupportedException();
    9165    }
    9266
    9367    public override bool TryAddSubOperator(IOperator subOperator) {
    94       subFunctions.Add((IFunction)subOperator);
    95       bool valid = IsValid();
    96       if (!valid) {
    97         subFunctions.RemoveAt(subFunctions.Count - 1);
    98       }
    99 
    100       return valid;
     68      throw new NotSupportedException();
    10169    }
    10270
    10371    public override bool TryAddSubOperator(IOperator subOperator, int index) {
    104       subFunctions.Insert(index, (IFunction)subOperator);
    105       bool valid = IsValid();
    106       if (!valid) {
    107         subFunctions.RemoveAt(index);
    108       }
    109       return valid;
     72      throw new NotSupportedException();
    11073    }
    11174
    11275    public override bool TryAddSubOperator(IOperator subOperator, int index, out ICollection<IConstraint> violatedConstraints) {
    113       subFunctions.Insert(index, (IFunction)subOperator);
    114       bool valid = IsValid(out violatedConstraints);
    115       if (!valid) {
    116         subFunctions.RemoveAt(index);
    117       }
    118       return valid;
     76      throw new NotSupportedException();
    11977    }
    12078
    12179    public override bool TryAddSubOperator(IOperator subOperator, out ICollection<IConstraint> violatedConstraints) {
    122       subFunctions.Add((IFunction)subOperator);
    123       bool valid = IsValid(out violatedConstraints);
    124       if (!valid) {
    125         subFunctions.RemoveAt(subFunctions.Count - 1);
    126       }
    127 
    128       return valid;
     80      throw new NotSupportedException();
    12981    }
    13082
    13183    public override void AddSubOperator(IOperator subOperator, int index) {
    132       subFunctions.Insert(index, (IFunction)subOperator);
     84      throw new NotSupportedException();
    13385    }
    13486
    13587    public override void RemoveSubOperator(int index) {
    136       if (index >= subFunctions.Count) throw new InvalidOperationException();
    137       subFunctions.RemoveAt(index);
     88      throw new NotSupportedException();
    13889    }
    13990
    140     public override IList<IOperator> SubOperators {
    141       get { return subFunctions.ConvertAll(f => (IOperator)f); }
    142     }
    143 
    144     public override ICollection<IVariable> Variables {
    145       get {
    146         List<IVariable> mergedVariables = new List<IVariable>(variables);
    147         if (this == metaObject) {
    148           foreach (IVariable variable in base.Variables) {
    149             if (!IsLocalVariable(variable.Name)) {
    150               mergedVariables.Add(variable);
    151             }
    152           }
    153         } else {
    154           foreach (IVariable variable in metaObject.Variables) {
    155             if (!IsLocalVariable(variable.Name)) {
    156               mergedVariables.Add(variable);
    157             }
    158           }
    159         }
    160         return mergedVariables;
    161       }
    162     }
    163 
    164     private bool IsLocalVariable(string name) {
    165       foreach (IVariable variable in variables) {
    166         if (variable.Name == name) return true;
    167       }
    168       return false;
    169     }
    170 
    171 
    17291    public override bool TryRemoveSubOperator(int index) {
    173       IFunction removedFunction = subFunctions[index];
    174       subFunctions.RemoveAt(index);
    175       bool valid = IsValid();
    176       if (!valid) {
    177         subFunctions.Insert(index, removedFunction);
    178       }
    179 
    180       return valid;
     92      throw new NotSupportedException();
    18193    }
    18294
    18395    public override bool TryRemoveSubOperator(int index, out ICollection<IConstraint> violatedConstraints) {
    184       IFunction removedFunction = subFunctions[index];
    185       subFunctions.RemoveAt(index);
    186       bool valid = IsValid(out violatedConstraints);
    187       if (!valid) {
    188         subFunctions.Insert(index, removedFunction);
    189       }
    190 
    191       return valid;
    192     }
    193 
    194     public override void AddVariable(IVariable variable) {
    195       if (metaObject == this) {
    196         base.AddVariable(variable);
    197       } else {
    198         metaObject.AddVariable(variable);
    199       }
    200     }
    201 
    202     public override IVariable GetVariable(string name) {
    203       foreach (IVariable variable in variables) {
    204         if (variable.Name == name) return variable;
    205       }
    206       if (metaObject == this) {
    207         return base.GetVariable(name);
    208       } else {
    209         return metaObject.GetVariable(name);
    210       }
    211     }
    212 
    213     public void AddLocalVariable(IVariable variable) {
    214       variables.Add(variable);
    215     }
    216 
    217     public override void RemoveVariable(string name) {
    218       foreach (IVariable variable in variables) {
    219         if (variable.Name == name) {
    220           variables.Remove(variable);
    221           return;
    222         }
    223       }
    224       if (metaObject == this) {
    225         base.RemoveVariable(name);
    226       } else {
    227         metaObject.RemoveVariable(name);
    228       }
    229     }
    230 
    231     public override IItem GetVariableValue(string formalName, IScope scope, bool recursiveLookup, bool throwOnError) {
    232       foreach (IVariable variable in Variables) {
    233         if (variable.Name == formalName) {
    234           return variable.Value;
    235         }
    236       }
    237       return metaObject.GetVariableValue(formalName, scope, recursiveLookup, throwOnError);
    238     }
    239 
    240     public override ICollection<IVariableInfo> VariableInfos {
    241       get {
    242         if (metaObject == this) {
    243           return base.VariableInfos;
    244         } else {
    245           return metaObject.VariableInfos;
    246         }
    247       }
    248     }
    249 
    250     public override void AddVariableInfo(IVariableInfo variableInfo) {
    251       if (metaObject == this) {
    252         base.AddVariableInfo(variableInfo);
    253       } else {
    254         metaObject.AddVariableInfo(variableInfo);
    255       }
    256     }
    257 
    258     public override void RemoveVariableInfo(string formalName) {
    259       if (metaObject == this) {
    260         base.RemoveVariableInfo(formalName);
    261       } else {
    262         metaObject.RemoveVariableInfo(formalName);
    263       }
    264     }
    265 
    266     public override ICollection<IConstraint> Constraints {
    267       get {
    268         if (metaObject == this) {
    269           return base.Constraints;
    270         } else {
    271           return metaObject.Constraints;
    272         }
    273       }
    274     }
    275 
    276     public override void AddConstraint(IConstraint constraint) {
    277       if (metaObject == this) {
    278         base.AddConstraint(constraint);
    279       } else {
    280         metaObject.AddConstraint(constraint);
    281       }
    282     }
    283     public override void RemoveConstraint(IConstraint constraint) {
    284       if (metaObject == this) {
    285         base.RemoveConstraint(constraint);
    286       } else {
    287         metaObject.RemoveConstraint(constraint);
    288       }
    289     }
    290 
    291     public override XmlNode GetXmlNode(string name, XmlDocument document, IDictionary<Guid, IStorable> persistedObjects) {
    292       XmlNode node = base.GetXmlNode(name, document, persistedObjects);
    293       if (metaObject != this) {
    294         XmlNode functionTemplateNode = document.CreateElement("FunctionTemplate");
    295         functionTemplateNode.AppendChild(PersistenceManager.Persist(metaObject, document, persistedObjects));
    296         node.AppendChild(functionTemplateNode);
    297       }
    298 
    299       // don't need to persist the sub-functions because OperatorBase.GetXmlNode already persisted the sub-operators
    300 
    301       // persist local variables
    302       XmlNode variablesNode = document.CreateNode(XmlNodeType.Element, "LocalVariables", null);
    303       foreach (IVariable variable in variables) {
    304         variablesNode.AppendChild(PersistenceManager.Persist(variable, document, persistedObjects));
    305       }
    306       node.AppendChild(variablesNode);
    307       return node;
    308     }
    309 
    310     public override void Populate(XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
    311       base.Populate(node, restoredObjects);
    312       XmlNode functionTemplateNode = node.SelectSingleNode("FunctionTemplate");
    313       if (functionTemplateNode != null) {
    314         metaObject = (FunctionBase)PersistenceManager.Restore(functionTemplateNode.ChildNodes[0], restoredObjects);
    315       } else {
    316         metaObject = this;
    317       }
    318       // don't need to explicitly load the sub-functions because that has already been done in OperatorBase.Populate()
    319 
    320       // load local variables
    321       XmlNode variablesNode = node.SelectSingleNode("LocalVariables");
    322      
    323       // remove the variables that have been added in a constructor
    324       variables.Clear();
    325       // load the persisted variables
    326       foreach (XmlNode variableNode in variablesNode.ChildNodes)
    327         variables.Add((IVariable)PersistenceManager.Restore(variableNode, restoredObjects));
    328     }
    329 
    330     public override IView CreateView() {
    331       return new FunctionView(this);
     96      throw new NotSupportedException();
    33297    }
    33398  }
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/FunctionView.Designer.cs

    r2 r142  
    2222using System;
    2323namespace HeuristicLab.Functions {
    24   partial class FunctionView {
     24  partial class FunctionTreeView {
    2525    /// <summary>
    2626    /// Required designer variable.
     
    167167            this.copyToClipboardMenuItem});
    168168      this.treeNodeContextMenu.Name = "treeNodeContextMenu";
    169       this.treeNodeContextMenu.Size = new System.Drawing.Size(259, 26);
     169      this.treeNodeContextMenu.Size = new System.Drawing.Size(248, 26);
    170170      //
    171171      // copyToClipboardMenuItem
    172172      //
    173173      this.copyToClipboardMenuItem.Name = "copyToClipboardMenuItem";
    174       this.copyToClipboardMenuItem.Size = new System.Drawing.Size(258, 22);
     174      this.copyToClipboardMenuItem.Size = new System.Drawing.Size(247, 22);
    175175      this.copyToClipboardMenuItem.Text = "Copy to clip-board (Model-Analyzer)";
    176176      this.copyToClipboardMenuItem.Click += new System.EventHandler(this.copyToClipboardMenuItem_Click);
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/FunctionView.cs

    r2 r142  
    3232
    3333namespace HeuristicLab.Functions {
    34   public partial class FunctionView : ViewBase {
    35     private IFunction function;
    36 
    37     private IFunction selectedFunction;
     34  public partial class FunctionTreeView : ViewBase {
     35    private IFunctionTree functionTree;
     36
     37    private IFunctionTree selectedBranch;
    3838    private IVariable selectedVariable;
    3939
    4040    private FunctionNameVisitor functionNameVisitor;
    41     public FunctionView() {
     41    public FunctionTreeView() {
    4242      InitializeComponent();
    4343      functionNameVisitor = new FunctionNameVisitor();
    4444    }
    4545
    46     public FunctionView(IFunction function)
     46    public FunctionTreeView(IFunctionTree functionTree)
    4747      : this() {
    48       this.function = function;
     48      this.functionTree = functionTree;
    4949      Refresh();
    5050    }
     
    5252    protected override void UpdateControls() {
    5353      functionTreeView.Nodes.Clear();
    54       function.Accept(functionNameVisitor);
     54      //functionTree.Accept(functionNameVisitor);
    5555      TreeNode rootNode = new TreeNode();
    56       rootNode.Name = function.Name;
    57       rootNode.Text = functionNameVisitor.Name;
    58       rootNode.Tag = function;
     56      rootNode.Name = "TASK";// function.Name;
     57      rootNode.Text = "TASK"; // functionNameVisitor.Name;
     58      rootNode.Tag = functionTree;
    5959      rootNode.ContextMenuStrip = treeNodeContextMenu;
    6060      functionTreeView.Nodes.Add(rootNode);
    6161
    62       foreach(IFunction subFunction in function.SubFunctions) {
    63         CreateTree(rootNode, subFunction);
     62      foreach(IFunctionTree subTree in functionTree.SubTrees) {
     63        CreateTree(rootNode, subTree);
    6464      }
    6565      functionTreeView.ExpandAll();
    6666    }
    6767
    68     private void CreateTree(TreeNode rootNode, IFunction function) {
     68    private void CreateTree(TreeNode rootNode, IFunctionTree functionTree) {
    6969      TreeNode node = new TreeNode();
    70       function.Accept(functionNameVisitor);
    71       node.Tag = function;
    72       node.Name = function.Name;
    73       node.Text = functionNameVisitor.Name;
     70      //functionTree.Accept(functionNameVisitor);
     71      node.Name = "TASK"; // function.Name;
     72      node.Text = "TASK"; // functionNameVisitor.Name;
     73      node.Tag = functionTree;
    7474      node.ContextMenuStrip = treeNodeContextMenu;
    7575      rootNode.Nodes.Add(node);
    76       foreach(IFunction subFunction in function.SubFunctions) {
    77         CreateTree(node, subFunction);
     76      foreach(IFunctionTree subTree in functionTree.SubTrees) {
     77        CreateTree(node, subTree);
    7878      }
    7979    }
     
    8585      editButton.Enabled = false;
    8686      if(functionTreeView.SelectedNode != null && functionTreeView.SelectedNode.Tag != null) {
    87         IFunction selectedFunction = (IFunction)functionTreeView.SelectedNode.Tag;
    88         UpdateVariablesList(selectedFunction);
    89         templateTextBox.Text = selectedFunction.MetaObject.Name;
    90         this.selectedFunction = selectedFunction;
     87        IFunctionTree selectedBranch = (IFunctionTree)functionTreeView.SelectedNode.Tag;
     88        UpdateVariablesList(selectedBranch);
     89        templateTextBox.Text = selectedBranch.Function.Name;
     90        this.selectedBranch = selectedBranch;
    9191        editButton.Enabled = true;
    9292      }
    9393    }
    9494
    95     private void UpdateVariablesList(IFunction function) {
    96       foreach(IVariable variable in function.LocalVariables) {
     95    private void UpdateVariablesList(IFunctionTree functionTree) {
     96      foreach(IVariable variable in functionTree.LocalVariables) {
    9797        variablesListBox.Items.Add(variable.Name);
    9898      }
     
    106106      if(variablesListBox.SelectedItem != null) {
    107107        string selectedVariableName = (string)variablesListBox.SelectedItem;
    108         selectedVariable = selectedFunction.GetVariable(selectedVariableName);
     108        selectedVariable = selectedBranch.GetLocalVariable(selectedVariableName);
    109109        variablesSplitContainer.Panel2.Controls.Clear();
    110110        Control editor = (Control)selectedVariable.CreateView();
     
    121121      if(functionTreeView.SelectedNode != null && functionTreeView.SelectedNode.Tag != null) {
    122122        TreeNode node = functionTreeView.SelectedNode;
    123         selectedFunction.Accept(functionNameVisitor);
    124         node.Text = functionNameVisitor.Name;
    125       }
    126     }
    127 
    128     private void editButton_Click(object sender, EventArgs e) {
    129       OperatorBaseView operatorView = new OperatorBaseView(selectedFunction.MetaObject);
    130       PluginManager.ControlManager.ShowControl(operatorView);
     123        // selectedFunctionTree.Accept(functionNameVisitor);
     124        node.Text = "TASK"; // functionNameVisitor.Name;
     125      }
     126    }
     127
     128    protected virtual void editButton_Click(object sender, EventArgs e) {
     129      PluginManager.ControlManager.ShowControl(selectedBranch.Function.CreateView());
    131130    }
    132131
     
    135134      if(node == null || node.Tag == null) return;
    136135
    137       ModelAnalyzerExportVisitor visitor = new ModelAnalyzerExportVisitor();
    138       ((IFunction)node.Tag).Accept(visitor);
    139       Clipboard.SetText(visitor.ModelAnalyzerPrefix);
     136      // ModelAnalyzerExportVisitor visitor = new ModelAnalyzerExportVisitor();
     137      // ((IFunctionTree)node.Tag).Accept(visitor);
     138      // Clipboard.SetText(visitor.ModelAnalyzerPrefix);
    140139    }
    141140
     
    252251    }
    253252
    254     private class ModelAnalyzerExportVisitor : IFunctionVisitor {
    255       private string prefix;
    256       private string currentIndend = "";
    257       public string ModelAnalyzerPrefix {
    258         get { return prefix; }
    259       }
    260       public void Reset() {
    261         prefix = "";
    262       }
    263 
    264       private void VisitFunction(string name, IFunction f) {
    265         prefix += currentIndend + "[F]"+name+"(\n";
    266         currentIndend += "  ";
    267         foreach(IFunction subFunction in f.SubFunctions) {
    268           subFunction.Accept(this);
    269           prefix += ";\n";
    270         }
    271         prefix = prefix.TrimEnd(';','\n');
    272         prefix += ")";
    273         currentIndend = currentIndend.Remove(0, 2);
    274       }
    275 
    276       #region IFunctionVisitor Members
    277 
    278       public void Visit(IFunction function) {
    279         prefix += function.Name;
    280       }
    281 
    282       public void Visit(Addition addition) {
    283         VisitFunction("Addition[0]", addition);
    284       }
    285 
    286       public void Visit(Constant constant) {
    287         prefix += currentIndend + "[T]Constant(" + constant.Value.Data.ToString() + ";0;0)";
    288       }
    289 
    290       public void Visit(Cosinus cosinus) {
    291         VisitFunction("Trigonometrics[1]", cosinus);
    292       }
    293 
    294       public void Visit(Division division) {
    295         VisitFunction("Division[0]", division);
    296       }
    297 
    298       public void Visit(Exponential exponential) {
    299         VisitFunction("Exponential[0]", exponential);
    300       }
    301 
    302       public void Visit(Logarithm logarithm) {
    303         VisitFunction("Logarithm[0]", logarithm);
    304       }
    305 
    306       public void Visit(Multiplication multiplication) {
    307         VisitFunction("Multiplication[0]", multiplication);
    308       }
    309 
    310       public void Visit(Power power) {
    311         VisitFunction("Power[0]", power);
    312       }
    313 
    314       public void Visit(Signum signum) {
    315         VisitFunction("Signum[0]", signum);
    316       }
    317 
    318       public void Visit(Sinus sinus) {
    319         VisitFunction("Trigonometrics[0]", sinus);
    320       }
    321 
    322       public void Visit(Sqrt sqrt) {
    323         VisitFunction("Sqrt[0]", sqrt);
    324       }
    325 
    326       public void Visit(Substraction substraction) {
    327         VisitFunction("Substraction[0]", substraction);
    328       }
    329 
    330       public void Visit(Tangens tangens) {
    331         VisitFunction("Trigonometrics[2]", tangens);
    332       }
    333 
    334       public void Visit(HeuristicLab.Functions.Variable variable) {
    335         prefix += currentIndend + "[T]Variable(" + variable.Weight + ";" + variable.VariableIndex + ";" + -variable.SampleOffset + ")";
    336       }
    337 
    338       public void Visit(And and) {
    339         VisitFunction("Logical[0]", and);
    340       }
    341 
    342       public void Visit(Average average) {
    343         VisitFunction("N/A (average)", average);
    344       }
    345 
    346       public void Visit(IfThenElse ifThenElse) {
    347         VisitFunction("Conditional[0]", ifThenElse);
    348       }
    349 
    350       public void Visit(Not not) {
    351         VisitFunction("Logical[2]", not);
    352       }
    353 
    354       public void Visit(Or or) {
    355         VisitFunction("Logical[1]", or);
    356       }
    357 
    358       public void Visit(Xor xor) {
    359         VisitFunction("N/A (xor)", xor);
    360       }
    361 
    362       public void Visit(Equal equal) {
    363         VisitFunction("Boolean[2]", equal);
    364       }
    365 
    366       public void Visit(LessThan lessThan) {
    367         VisitFunction("Boolean[0]", lessThan);
    368       }
    369 
    370       #endregion
    371     }
     253    //private class ModelAnalyzerExportVisitor : IFunctionVisitor {
     254    //  private string prefix;
     255    //  private string currentIndend = "";
     256    //  public string ModelAnalyzerPrefix {
     257    //    get { return prefix; }
     258    //  }
     259    //  public void Reset() {
     260    //    prefix = "";
     261    //  }
     262
     263    //  private void VisitFunction(string name, IFunction f) {
     264    //    prefix += currentIndend + "[F]"+name+"(\n";
     265    //    currentIndend += "  ";
     266    //    foreach(IFunction subFunction in f.SubTrees) {
     267    //      subFunction.Accept(this);
     268    //      prefix += ";\n";
     269    //    }
     270    //    prefix = prefix.TrimEnd(';','\n');
     271    //    prefix += ")";
     272    //    currentIndend = currentIndend.Remove(0, 2);
     273    //  }
     274
     275    //  #region IFunctionVisitor Members
     276
     277    //  public void Visit(IFunction function) {
     278    //    prefix += function.Name;
     279    //  }
     280
     281    //  public void Visit(Addition addition) {
     282    //    VisitFunction("Addition[0]", addition);
     283    //  }
     284
     285    //  public void Visit(Constant constant) {
     286    //    prefix += currentIndend + "[T]Constant(" + constant.Value.Data.ToString() + ";0;0)";
     287    //  }
     288
     289    //  public void Visit(Cosinus cosinus) {
     290    //    VisitFunction("Trigonometrics[1]", cosinus);
     291    //  }
     292
     293    //  public void Visit(Division division) {
     294    //    VisitFunction("Division[0]", division);
     295    //  }
     296
     297    //  public void Visit(Exponential exponential) {
     298    //    VisitFunction("Exponential[0]", exponential);
     299    //  }
     300
     301    //  public void Visit(Logarithm logarithm) {
     302    //    VisitFunction("Logarithm[0]", logarithm);
     303    //  }
     304
     305    //  public void Visit(Multiplication multiplication) {
     306    //    VisitFunction("Multiplication[0]", multiplication);
     307    //  }
     308
     309    //  public void Visit(Power power) {
     310    //    VisitFunction("Power[0]", power);
     311    //  }
     312
     313    //  public void Visit(Signum signum) {
     314    //    VisitFunction("Signum[0]", signum);
     315    //  }
     316
     317    //  public void Visit(Sinus sinus) {
     318    //    VisitFunction("Trigonometrics[0]", sinus);
     319    //  }
     320
     321    //  public void Visit(Sqrt sqrt) {
     322    //    VisitFunction("Sqrt[0]", sqrt);
     323    //  }
     324
     325    //  public void Visit(Substraction substraction) {
     326    //    VisitFunction("Substraction[0]", substraction);
     327    //  }
     328
     329    //  public void Visit(Tangens tangens) {
     330    //    VisitFunction("Trigonometrics[2]", tangens);
     331    //  }
     332
     333    //  public void Visit(HeuristicLab.Functions.Variable variable) {
     334    //    prefix += currentIndend + "[T]Variable(" + variable.Weight + ";" + variable.VariableIndex + ";" + -variable.SampleOffset + ")";
     335    //  }
     336
     337    //  public void Visit(And and) {
     338    //    VisitFunction("Logical[0]", and);
     339    //  }
     340
     341    //  public void Visit(Average average) {
     342    //    VisitFunction("N/A (average)", average);
     343    //  }
     344
     345    //  public void Visit(IfThenElse ifThenElse) {
     346    //    VisitFunction("Conditional[0]", ifThenElse);
     347    //  }
     348
     349    //  public void Visit(Not not) {
     350    //    VisitFunction("Logical[2]", not);
     351    //  }
     352
     353    //  public void Visit(Or or) {
     354    //    VisitFunction("Logical[1]", or);
     355    //  }
     356
     357    //  public void Visit(Xor xor) {
     358    //    VisitFunction("N/A (xor)", xor);
     359    //  }
     360
     361    //  public void Visit(Equal equal) {
     362    //    VisitFunction("Boolean[2]", equal);
     363    //  }
     364
     365    //  public void Visit(LessThan lessThan) {
     366    //    VisitFunction("Boolean[0]", lessThan);
     367    //  }
     368
     369    //  #endregion
     370    //}
    372371
    373372  }
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/HeuristicLab.Functions.csproj

    r30 r142  
    5252    <Compile Include="Average.cs" />
    5353    <Compile Include="Constant.cs" />
     54    <Compile Include="FunctionTree.cs" />
     55    <Compile Include="IFunctionTree.cs" />
     56    <Compile Include="ProgrammableFunction.cs" />
    5457    <Compile Include="Equal.cs" />
    5558    <Compile Include="FunctionView.cs">
     
    99102      <Name>HeuristicLab.Data</Name>
    100103    </ProjectReference>
     104    <ProjectReference Include="..\HeuristicLab.Operators.Programmable\HeuristicLab.Operators.Programmable.csproj">
     105      <Project>{E3CCBFC6-900C-41B6-AFB8-6646DB097435}</Project>
     106      <Name>HeuristicLab.Operators.Programmable</Name>
     107    </ProjectReference>
    101108    <ProjectReference Include="..\HeuristicLab.PluginInfrastructure\HeuristicLab.PluginInfrastructure.csproj">
    102109      <Project>{94186A6A-5176-4402-AE83-886557B53CCA}</Project>
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/IFunction.cs

    r2 r142  
    2828namespace HeuristicLab.Functions {
    2929  public interface IFunction : IOperator {
    30     IList<IFunction> SubFunctions { get;}
    31     ICollection<IVariable> LocalVariables { get; }
    32     IFunction MetaObject { get; }
    33     double Evaluate(Dataset dataset, int sampleIndex);
     30    double Evaluate(Dataset dataset, int sampleIndex, IList<IFunctionTree> subTrees);
     31    double Apply(Dataset dataset, int sampleIndex, double[] args);
    3432    void Accept(IFunctionVisitor visitor);
    3533  }
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/IfThenElse.cs

    r2 r142  
    3131    public override string Description {
    3232      get {
    33         return @"Returns the result of the second branch if the first branch evaluates to a value >= 0.5 and the result
    34 of the third branch if the first branch evaluates to < 0.5.";
     33        return @"Returns the result of the second sub-tree if the first sub-tree evaluates to a value < 0.5 and the result
     34of the third sub-tree if the first sub-tree evaluates to >= 0.5.";
    3535      }
    3636    }
     
    4141    }
    4242
    43     public IfThenElse(IfThenElse source, IDictionary<Guid, object> clonedObjects)
    44       : base(source, clonedObjects) {
    45     }
    46 
    47 
    48     public override double Evaluate(Dataset dataset, int sampleIndex) {
    49       double condition = Math.Round(SubFunctions[0].Evaluate(dataset, sampleIndex));
    50       if(condition >= .5) return SubFunctions[2].Evaluate(dataset, sampleIndex);
    51       else if(condition < .5) return SubFunctions[1].Evaluate(dataset, sampleIndex);
     43    // special form
     44    public override double Evaluate(Dataset dataset, int sampleIndex, IList<IFunctionTree> subTrees) {
     45      double condition = Math.Round(subTrees[0].Evaluate(dataset, sampleIndex));
     46      if(condition < .5) return subTrees[1].Evaluate(dataset, sampleIndex);
     47      else if(condition >= .5) return subTrees[2].Evaluate(dataset, sampleIndex);
    5248      else return double.NaN;
    5349    }
    5450
    55     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    56       IfThenElse clone = new IfThenElse(this, clonedObjects);
    57       clonedObjects.Add(clone.Guid, clone);
    58       return clone;
     51    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     52      throw new NotImplementedException();
    5953    }
    6054
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/LessThan.cs

    r2 r142  
    3131    public override string Description {
    3232      get {
    33         return @"Less-than condition. Returns 1.0 if the value of the first sub-function is less than the value of the second sub-function and 0.0 otherwise.";
     33        return @"Less-than condition. Returns 1.0 if the value of the first sub-tree is less than the value of the second sub-tree and 0.0 otherwise.";
    3434      }
    3535    }
     
    4040    }
    4141
    42     public LessThan(LessThan source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
    44     }
    45 
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
    48       if(SubFunctions[0].Evaluate(dataset, sampleIndex) < SubFunctions[1].Evaluate(dataset, sampleIndex)) return 1.0;
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     43      if(args[0] < args[1]) return 1.0;
    4944      else return 0.0;
    50     }
    51 
    52     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    53       LessThan clone = new LessThan(this, clonedObjects);
    54       clonedObjects.Add(clone.Guid, clone);
    55       return clone;
    5645    }
    5746
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Logarithm.cs

    r2 r142  
    3131  public class Logarithm : FunctionBase {
    3232    public override string Description {
    33       get { return "Returns the natural (base e) logarithm of the first sub-operator."; }
     33      get { return "Returns the natural (base e) logarithm of the first sub-tree."; }
    3434    }
    3535
     
    4040    }
    4141
    42     public Logarithm(Logarithm source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
    44     }
    45 
    46     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    47       Logarithm clone = new Logarithm(this, clonedObjects);
    48       clonedObjects.Add(clone.Guid, clone);
    49       return clone;
    50     }
    51 
    52     public override double Evaluate(Dataset dataset, int sampleIndex) {
    53       return Math.Log(SubFunctions[0].Evaluate(dataset, sampleIndex));
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     43      return Math.Log(args[0]);
    5444    }
    5545
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Multiplication.cs

    r2 r142  
    3333    public override string Description {
    3434      get {
    35         return @"Returns the product of the results of all sub-operators.
     35        return @"Returns the product of the results of all sub-tree.
    3636  (* 3) => 3
    3737  (* 2 3) => 6
     
    4646    }
    4747
    48     public Multiplication(Multiplication source, IDictionary<Guid, object> clonedObjects)
    49       : base(source, clonedObjects) {
    50     }
    51 
    52 
    53     public override double Evaluate(Dataset dataset, int sampleIndex) {
     48    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
    5449      // (* 3) => 3
    5550      // (* 2 3) => 6
    5651      // (* 3 4 5) => 60
    5752      double result = 1.0;
    58       for(int i = SubFunctions.Count - 1; i >= 0; i--) {
    59         result *= SubFunctions[i].Evaluate(dataset, sampleIndex);
     53      for(int i = 0; i < args.Length; i++) {
     54        result *= args[i];
    6055      }
    6156      return result;
    62     }
    63 
    64     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    65       Multiplication clone = new Multiplication(this, clonedObjects);
    66       clonedObjects.Add(clone.Guid, clone);
    67       return clone;
    6857    }
    6958
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Not.cs

    r2 r142  
    3131    public override string Description {
    3232      get {
    33         return @"Logical NOT operation. Only defined for sub-operator-results 0.0 and 1.0.";
     33        return @"Logical NOT operation. Only defined for sub-tree-results 0.0 and 1.0.";
    3434      }
    3535    }
     
    4040    }
    4141
    42     public Not(Not source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
    44     }
    45 
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
    48       double result = Math.Round(SubFunctions[0].Evaluate(dataset, sampleIndex));
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     43      double result = Math.Round(args[0]);
    4944      if(result == 0.0) return 1.0;
    5045      else if(result == 1.0) return 0.0;
    5146      else return double.NaN;
    52     }
    53 
    54     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    55       Not clone = new Not(this, clonedObjects);
    56       clonedObjects.Add(clone.Guid, clone);
    57       return clone;
    5847    }
    5948
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Or.cs

    r2 r142  
    3131    public override string Description {
    3232      get {
    33         return @"Logical OR operation. Only defined for sub-operator-results 0.0 and 1.0.";
     33        return @"Logical OR operation. Only defined for sub-tree-results 0.0 and 1.0.
     34Special form, evaluation stops at first sub-tree that evaluates to 1.0 (true).";
    3435      }
    3536    }
     
    4041    }
    4142
    42     public Or(Or source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
    44     }
    45 
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
    48       foreach(IFunction subFunction in SubFunctions) {
    49         double result = Math.Round(subFunction.Evaluate(dataset, sampleIndex));
    50         if(result == 1.0) return 1.0;
     43    public override double Evaluate(Dataset dataset, int sampleIndex, IList<IFunctionTree> subTrees) {
     44      foreach(IFunctionTree subTree in subTrees) {
     45        double result = Math.Round(subTree.Evaluate(dataset, sampleIndex));
     46        if(result == 1.0) return 1.0; // sub-tree evaluates to 1.0 (true) return 1.0
    5147        else if(result != 0.0) return double.NaN;
    5248      }
     49      // all sub-trees evaluated to 0.0 (false) return false
    5350      return 0.0;
    5451    }
    5552
    56     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    57       Or clone = new Or(this, clonedObjects);
    58       clonedObjects.Add(clone.Guid, clone);
    59       return clone;
     53    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     54      throw new NotImplementedException();
    6055    }
    61 
    6256    public override void Accept(IFunctionVisitor visitor) {
    6357      visitor.Visit(this);
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Power.cs

    r2 r142  
    3131  public class Power : FunctionBase {
    3232    public override string Description {
    33       get { return "Returns the result of the first sub-operator to the power of the second sub-operator (power(x, y))."; }
     33      get { return "Returns the result of the first sub-tree to the power of the second sub-tree (power(x, y))."; }
    3434    }
    3535
     
    4040    }
    4141
    42     public Power(Power source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     43      return Math.Pow(args[0], args[1]);
    4444    }
    45 
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
    48       return Math.Pow(SubFunctions[0].Evaluate(dataset, sampleIndex), SubFunctions[1].Evaluate(dataset, sampleIndex));
    49     }
    50 
    51     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    52       Power clone = new Power(this, clonedObjects);
    53       clonedObjects.Add(clone.Guid, clone);
    54       return clone;
    55     }
    56 
    5745
    5846    public override void Accept(IFunctionVisitor visitor) {
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Signum.cs

    r2 r142  
    3131  public class Signum : FunctionBase {
    3232    public override string Description {
    33       get { return "Returns the signum of the first sub-operator."; }
     33      get { return "Returns the signum of the first sub-tree."; }
    3434    }
    3535
     
    4040    }
    4141
    42     public Signum(Signum source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
    44     }
    45 
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
    48       double value = SubFunctions[0].Evaluate(dataset, sampleIndex);
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     43      double value = args[0];
    4944      if(value < 0) return -1;
    5045      if(value > 0) return 1;
    5146      return 0;
    5247    }
    53 
    54     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    55       Signum clone = new Signum(this, clonedObjects);
    56       clonedObjects.Add(clone.Guid, clone);
    57       return clone;
    58     }
    59 
    6048
    6149    public override void Accept(IFunctionVisitor visitor) {
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Sinus.cs

    r2 r142  
    3131  public class Sinus : FunctionBase {
    3232    public override string Description {
    33       get { return "Returns the sinus of the first sub-operator."; }
     33      get { return "Returns the sinus of the first sub-tree."; }
    3434    }
    3535
     
    4040    }
    4141
    42     public Sinus(Sinus source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     43      return Math.Sin(args[0]);
    4444    }
    45 
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
    48       return Math.Sin(SubFunctions[0].Evaluate(dataset, sampleIndex));
    49     }
    50 
    51     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    52       Sinus clone = new Sinus(this, clonedObjects);
    53       clonedObjects.Add(clone.Guid, clone);
    54       return clone;
    55     }
    56 
    5745
    5846    public override void Accept(IFunctionVisitor visitor) {
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Sqrt.cs

    r2 r142  
    3131  public class Sqrt : FunctionBase {
    3232    public override string Description {
    33       get { return "Returns the square root of the first sub-operator."; }
     33      get { return "Returns the square root of the first sub-tree."; }
    3434    }
    3535
     
    4040    }
    4141
    42     public Sqrt(Sqrt source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
     42
     43    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     44      return Math.Sqrt(args[0]);
    4445    }
    45 
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
    48       return Math.Sqrt(SubFunctions[0].Evaluate(dataset, sampleIndex));
    49     }
    50 
    51     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    52       Sqrt clone = new Sqrt(this, clonedObjects);
    53       clonedObjects.Add(clone.Guid, clone);
    54       return clone;
    55     }
    56 
    5746
    5847    public override void Accept(IFunctionVisitor visitor) {
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Substraction.cs

    r2 r142  
    3333    public override string Description {
    3434      get {
    35         return @"Substracts the results of sub-operators 2..n from the result of the first sub-operator.
     35        return @"Substracts the results of sub-tree 2..n from the result of the first sub-tree.
    3636    (- 3) => -3
    3737    (- 2 3) => -1
     
    4646    }
    4747
    48     public Substraction(Substraction source, IDictionary<Guid, object> clonedObjects)
    49       : base(source, clonedObjects) {
    50     }
    5148
    52 
    53     public override double Evaluate(Dataset dataset, int sampleIndex) {
    54 
    55       if(SubFunctions.Count == 1) {
    56         return -SubFunctions[0].Evaluate(dataset, sampleIndex);
     49    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     50      if(args.Length == 1) {
     51        return -args[0];
    5752      } else {
    58         double result = SubFunctions[0].Evaluate(dataset, sampleIndex);
    59         for(int i = 1; i < SubFunctions.Count; i++) {
    60           result -= SubFunctions[i].Evaluate(dataset, sampleIndex);
     53        double result = args[0];
     54        for(int i = 1; i < args.Length; i++) {
     55          result -= args[i];
    6156        }
    6257        return result;
    6358      }
    64     }
    65 
    66     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    67       Substraction clone = new Substraction(this, clonedObjects);
    68       clonedObjects.Add(clone.Guid, clone);
    69       return clone;
    7059    }
    7160
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Tangens.cs

    r2 r142  
    3131  public class Tangens : FunctionBase {
    3232    public override string Description {
    33       get { return "Returns the tangens of the first sub-operator."; }
     33      get { return "Returns the tangens of the first sub-tree."; }
    3434    }
    3535
     
    4040    }
    4141
    42     public Tangens(Tangens source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     43      return Math.Tan(args[0]);
    4444    }
    45 
    46     public override double Evaluate(Dataset dataset, int sampleIndex) {
    47       return Math.Tan(SubFunctions[0].Evaluate(dataset, sampleIndex));
    48     }
    49 
    50     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    51       Tangens clone = new Tangens(this, clonedObjects);
    52       clonedObjects.Add(clone.Guid, clone);
    53       return clone;
    54     }
    55 
    5645
    5746    public override void Accept(IFunctionVisitor visitor) {
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Variable.cs

    r133 r142  
    6464
    6565      variable = new ConstrainedIntData();
    66       AddLocalVariable(new HeuristicLab.Core.Variable("Variable", variable));
     66      AddVariable(new HeuristicLab.Core.Variable("Variable", variable));
    6767
    6868      weight = new ConstrainedDoubleData();
    6969      // initialize a totally arbitrary range for the weight = [-20.0, 20.0]
    7070      weight.AddConstraint(new DoubleBoundedConstraint(-20.0, 20.0));
    71       AddLocalVariable(new HeuristicLab.Core.Variable("Weight", weight));
     71      AddVariable(new HeuristicLab.Core.Variable("Weight", weight));
    7272
    7373      sampleOffset = new ConstrainedIntData();
    7474      // initialize a totally arbitrary default range for sampleoffset = [-10, 10]
    7575      sampleOffset.AddConstraint(new IntBoundedConstraint(0, 0));
    76       AddLocalVariable(new HeuristicLab.Core.Variable("SampleOffset", sampleOffset));
     76      AddVariable(new HeuristicLab.Core.Variable("SampleOffset", sampleOffset));
    7777
    7878      // samplefeature can't have suboperators
     
    8080    }
    8181
    82     public Variable(Variable source, IDictionary<Guid, object> clonedObjects)
    83       : base(source, clonedObjects) {
    84 
     82    public override object Clone(IDictionary<Guid, object> clonedObjects) {
     83      HeuristicLab.Functions.Variable clone = (HeuristicLab.Functions.Variable)base.Clone(clonedObjects);
     84      clone.variable = (ConstrainedIntData)clone.GetVariable("Variable").Value;
     85      clone.weight = (ConstrainedDoubleData)clone.GetVariable("Weight").Value;
     86      clone.sampleOffset = (ConstrainedIntData)clone.GetVariable("SampleOffset").Value;
     87      return clone;
     88    }
     89   
     90    public override void Populate(System.Xml.XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
     91      base.Populate(node, restoredObjects);
    8592      variable = (ConstrainedIntData)GetVariable("Variable").Value;
    8693      weight = (ConstrainedDoubleData)GetVariable("Weight").Value;
     
    8895    }
    8996
    90     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    91       Variable clone = new Variable(this, clonedObjects);
    92       clonedObjects.Add(clone.Guid, clone);
    93       return clone;
    94     }
    95 
    96     public override void Populate(System.Xml.XmlNode node, IDictionary<Guid, IStorable> restoredObjects) {
    97       base.Populate(node, restoredObjects);
    98 
    99       variable = (ConstrainedIntData)GetVariable("Variable").Value;
    100       weight = (ConstrainedDoubleData)GetVariable("Weight").Value;
    101       sampleOffset = (ConstrainedIntData)GetVariable("SampleOffset").Value;
    102     }
    103 
    104 
    105     public override double Evaluate(Dataset dataset, int sampleIndex) {
     97    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
    10698      // local variables
    10799      int v = variable.Data;
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.Functions/Xor.cs

    r2 r142  
    3131    public override string Description {
    3232      get {
    33         return @"Logical XOR operation. Only defined for sub-operator-results 0.0 and 1.0.";
     33        return @"Logical XOR operation. Only defined for sub-tree-results 0.0 and 1.0.";
    3434      }
    3535    }
     
    4040    }
    4141
    42     public Xor(Xor source, IDictionary<Guid, object> clonedObjects)
    43       : base(source, clonedObjects) {
    44     }
    45 
    46 
    47     public override double Evaluate(Dataset dataset, int sampleIndex) {
    48       double r0 = Math.Round(SubFunctions[0].Evaluate(dataset, sampleIndex));
    49       double r1 = Math.Round(SubFunctions[1].Evaluate(dataset, sampleIndex));
    50       if((r0 == 0.0 && r1 == 0.0) ||
    51         (r0 == 1.0 && r1 == 1.0)) return 0.0;
    52       else if((r0 == 0.0 && r1 == 1.0) ||
    53         (r0 == 1.0 && r1 == 0.0)) return 1.0;
    54       else return double.NaN;
    55     }
    56 
    57     public override object Clone(IDictionary<Guid, object> clonedObjects) {
    58       Xor clone = new Xor(this, clonedObjects);
    59       clonedObjects.Add(clone.Guid, clone);
    60       return clone;
     42    public override double Apply(Dataset dataset, int sampleIndex, double[] args) {
     43      if(args[0] == 0.0 && args[1] == 0.0) return 0.0;
     44      if(args[0] * args[1] == 0.0) return 1.0;
     45      return 0.0;
    6146    }
    6247
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.StructureIdentification/Evaluation/CoefficientOfDeterminationEvaluator.cs

    r128 r142  
    3434    public override string Description {
    3535      get {
    36         return @"Applies 'OperatorTree' to all samples of 'Dataset' and calculates
     36        return @"Evaluates 'FunctionTree' for all samples of 'Dataset' and calculates
    3737the 'coefficient of determination' of estimated values vs. real values of 'TargetVariable'.";
    3838      }
     
    4343    }
    4444
    45     public override double Evaluate(IScope scope, IFunction function, int targetVariable, Dataset dataset) {
     45    public override double Evaluate(IScope scope, IFunctionTree functionTree, int targetVariable, Dataset dataset) {
    4646      double errorsSquaredSum = 0.0;
    4747      double originalDeviationTotalSumOfSquares = 0.0;
    4848      double targetMean = dataset.GetMean(targetVariable);
    4949      for(int sample = 0; sample < dataset.Rows; sample++) {
    50         double estimated = function.Evaluate(dataset, sample);
     50        double estimated = functionTree.Evaluate(dataset, sample);
    5151        double original = dataset.GetValue(sample, targetVariable);
    5252        if(!double.IsNaN(original) && !double.IsInfinity(original)) {
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.StructureIdentification/Evaluation/EarlyStoppingMeanSquaredErrorEvaluator.cs

    r136 r142  
    3434    public override string Description {
    3535      get {
    36         return @"Evaluates 'OperatorTree' for all samples of the dataset and calculates the mean-squared-error
     36        return @"Evaluates 'FunctionTree' for all samples of the dataset and calculates the mean-squared-error
    3737for the estimated values vs. the real values of 'TargetVariable'.
    3838This operator stops the computation as soon as an upper limit for the mean-squared-error is reached.";
     
    4545    }
    4646
    47     public override double Evaluate(IScope scope, IFunction function, int targetVariable, Dataset dataset) {
     47    public override double Evaluate(IScope scope, IFunctionTree functionTree, int targetVariable, Dataset dataset) {
    4848      double qualityLimit = GetVariableValue<DoubleData>("QualityLimit", scope, false).Data;
    4949      double errorsSquaredSum = 0;
    5050      double targetMean = dataset.GetMean(targetVariable);
    5151      for(int sample = 0; sample < dataset.Rows; sample++) {
    52         double estimated = function.Evaluate(dataset, sample);
     52        double estimated = functionTree.Evaluate(dataset, sample);
    5353        double original = dataset.GetValue(sample, targetVariable);
    5454        if(double.IsNaN(estimated) || double.IsInfinity(estimated)) {
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.StructureIdentification/Evaluation/GPEvaluatorBase.cs

    r135 r142  
    3636    public GPEvaluatorBase()
    3737      : base() {
    38       AddVariableInfo(new VariableInfo("OperatorTree", "The function tree that should be evaluated", typeof(IFunction), VariableKind.In));
     38      AddVariableInfo(new VariableInfo("FunctionTree", "The function tree that should be evaluated", typeof(IFunctionTree), VariableKind.In));
    3939      AddVariableInfo(new VariableInfo("Dataset", "Dataset with all samples on which to apply the function", typeof(Dataset), VariableKind.In));
    4040      AddVariableInfo(new VariableInfo("TargetVariable", "Index of the column of the dataset that holds the target variable", typeof(IntData), VariableKind.In));
     
    4646      int targetVariable = GetVariableValue<IntData>("TargetVariable", scope, true).Data;
    4747      Dataset dataset = GetVariableValue<Dataset>("Dataset", scope, true);
    48       IFunction function = GetVariableValue<IFunction>("OperatorTree", scope, true);
     48      IFunctionTree functionTree = GetVariableValue<IFunctionTree>("FunctionTree", scope, true);
    4949      this.maximumPunishment = GetVariableValue<DoubleData>("PunishmentFactor", scope, true).Data * dataset.GetRange(targetVariable);
    5050
    51       double result = Evaluate(scope, function, targetVariable, dataset);
     51      double result = Evaluate(scope, functionTree, targetVariable, dataset);
    5252      scope.AddVariable(new HeuristicLab.Core.Variable(scope.TranslateName("Quality"), new DoubleData(result)));
    5353      return null;
    5454    }
    5555
    56     public abstract double Evaluate(IScope scope, IFunction function, int targetVariable, Dataset dataset);
     56    public abstract double Evaluate(IScope scope, IFunctionTree functionTree, int targetVariable, Dataset dataset);
    5757  }
    5858}
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.StructureIdentification/Evaluation/MeanSquaredErrorEvaluator.cs

    r128 r142  
    3434    public override string Description {
    3535      get {
    36         return @"Evaluates 'OperatorTree' for all samples of 'DataSet' and calculates the mean-squared-error
     36        return @"Evaluates 'FunctionTree' for all samples of 'DataSet' and calculates the mean-squared-error
    3737for the estimated values vs. the real values of 'TargetVariable'.";
    3838      }
     
    4343    }
    4444
    45     public override double Evaluate(IScope scope, IFunction function, int targetVariable, Dataset dataset) {
     45    public override double Evaluate(IScope scope, IFunctionTree functionTree, int targetVariable, Dataset dataset) {
    4646      double errorsSquaredSum = 0;
    4747      double targetMean = dataset.GetMean(targetVariable);
    4848      for(int sample = 0; sample < dataset.Rows; sample++) {
    49         double estimated = function.Evaluate(dataset, sample);
     49        double estimated = functionTree.Evaluate(dataset, sample);
    5050        double original = dataset.GetValue(sample, targetVariable);
    5151        if(double.IsNaN(estimated) || double.IsInfinity(estimated)) {
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.StructureIdentification/Evaluation/VarianceAccountedForEvaluator.cs

    r128 r142  
    3434    public override string Description {
    3535      get {
    36         return @"Evaluates 'OperatorTree' for all samples of 'DataSet' and calculates
     36        return @"Evaluates 'FunctionTree' for all samples of 'DataSet' and calculates
    3737the variance-accounted-for quality measure for the estimated values vs. the real values of 'TargetVariable'.
    3838
     
    5353
    5454
    55     public override double Evaluate(IScope scope, IFunction function, int targetVariable, Dataset dataset) {
     55    public override double Evaluate(IScope scope, IFunctionTree functionTree, int targetVariable, Dataset dataset) {
    5656      double[] errors = new double[dataset.Rows];
    5757      double[] originalTargetVariableValues = new double[dataset.Rows];
    5858      double targetMean = dataset.GetMean(targetVariable);
    5959      for(int sample = 0; sample < dataset.Rows; sample++) {
    60         double estimated = function.Evaluate(dataset, sample);
     60        double estimated = functionTree.Evaluate(dataset, sample);
    6161        double original = dataset.GetValue(sample, targetVariable);
    6262        if(!double.IsNaN(original) && !double.IsInfinity(original)) {
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.StructureIdentification/HeuristicLab.StructureIdentification.csproj

    r128 r142  
    6767    <Compile Include="Manipulation\OnePointShaker.cs" />
    6868    <Compile Include="Manipulation\SubstituteSubTreeManipulation.cs" />
    69     <Compile Include="PopulationAnalyser.cs" />
    7069    <Compile Include="HeuristicLabStructureIdentificationPlugin.cs" />
    7170    <Compile Include="Properties\AssemblyInfo.cs" />
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.StructureIdentification/Manipulation/ChangeNodeTypeManipulation.cs

    r23 r142  
    2929using HeuristicLab.Data;
    3030using HeuristicLab.Constraints;
     31using HeuristicLab.Functions;
    3132
    3233namespace HeuristicLab.StructureIdentification {
     
    3940      AddVariableInfo(new VariableInfo("MaxTreeSize", "The maximal allowed size (number of nodes) of the tree", typeof(IntData), VariableKind.In));
    4041      AddVariableInfo(new VariableInfo("BalancedTreesRate", "Determines how many trees should be balanced", typeof(DoubleData), VariableKind.In));
    41       AddVariableInfo(new VariableInfo("OperatorTree", "The tree to mutate", typeof(IOperator), VariableKind.In));
    42       AddVariableInfo(new VariableInfo("TreeSize", "The size (number of nodes) of the tree", typeof(IntData), VariableKind.In));
    43       AddVariableInfo(new VariableInfo("TreeHeight", "The height of the tree", typeof(IntData), VariableKind.In));
     42      AddVariableInfo(new VariableInfo("FunctionTree", "The tree to mutate", typeof(IFunctionTree), VariableKind.In | VariableKind.Out));
     43      AddVariableInfo(new VariableInfo("TreeSize", "The size (number of nodes) of the tree", typeof(IntData), VariableKind.In | VariableKind.Out));
     44      AddVariableInfo(new VariableInfo("TreeHeight", "The height of the tree", typeof(IntData), VariableKind.In | VariableKind.Out));
    4445    }
    4546
    4647
    4748    public override IOperation Apply(IScope scope) {
    48       IOperator rootOperator = GetVariableValue<IOperator>("OperatorTree", scope, false);
     49      IFunctionTree root = GetVariableValue<IFunctionTree>("FunctionTree", scope, false);
    4950      MersenneTwister random = GetVariableValue<MersenneTwister>("Random", scope, true);
    5051      GPOperatorLibrary library = GetVariableValue<GPOperatorLibrary>("OperatorLibrary", scope, true);
     
    5657
    5758      TreeGardener gardener = new TreeGardener(random, library);
    58 
    59       IOperator parent = gardener.GetRandomParentNode(rootOperator);
    60 
    61       IOperator selectedChild;
     59      IFunctionTree parent = gardener.GetRandomParentNode(root);
     60
     61      IFunctionTree selectedChild;
    6262      int selectedChildIndex;
    6363      if (parent == null) {
    6464        selectedChildIndex = 0;
    65         selectedChild = rootOperator;
    66       } else {
    67         selectedChildIndex = random.Next(parent.SubOperators.Count);
    68         selectedChild = parent.SubOperators[selectedChildIndex];
    69       }
    70 
    71       if (selectedChild.SubOperators.Count == 0) {
    72         IOperator newTerminal = ChangeTerminalType(parent, selectedChild, selectedChildIndex, gardener, random);
     65        selectedChild = root;
     66      } else {
     67        selectedChildIndex = random.Next(parent.SubTrees.Count);
     68        selectedChild = parent.SubTrees [selectedChildIndex];
     69      }
     70
     71      if (selectedChild.SubTrees.Count == 0) {
     72        IFunctionTree newTerminal = ChangeTerminalType(parent, selectedChild, selectedChildIndex, gardener, random);
    7373
    7474        if (parent == null) {
    7575          // no parent means the new child is the initial operator
    7676          // and we have to update the value in the variable
    77           scope.GetVariable("OperatorTree").Value = newTerminal;
     77          scope.GetVariable("FunctionTree").Value = newTerminal;
    7878        } else {
    79           parent.RemoveSubOperator(selectedChildIndex);
    80           parent.AddSubOperator(newTerminal, selectedChildIndex);
     79          parent.RemoveSubTree(selectedChildIndex);
     80          parent.InsertSubTree(selectedChildIndex, newTerminal);
    8181          // updating the variable is not necessary because it stays the same
    8282        }
     
    8686        return gardener.CreateInitializationOperation(gardener.GetAllOperators(newTerminal), scope);
    8787      } else {
    88         List<IOperator> uninitializedOperators;
    89         IOperator newFunction = ChangeFunctionType(parent, selectedChild, selectedChildIndex, gardener, random, balancedTreesRate, out uninitializedOperators);
     88        List<IFunctionTree> uninitializedBranches;
     89        IFunctionTree newFunction = ChangeFunctionType(parent, selectedChild, selectedChildIndex, gardener, random, balancedTreesRate, out uninitializedBranches);
    9090
    9191        if (parent == null) {
    9292          // no parent means the new function is the initial operator
    9393          // and we have to update the value in the variable
    94           scope.GetVariable("OperatorTree").Value = newFunction;
    95           rootOperator = newFunction;
     94          scope.GetVariable("FunctionTree").Value = newFunction;
     95          root = newFunction;
    9696        } else {
    9797          // remove the old child
    98           parent.RemoveSubOperator(selectedChildIndex);
     98          parent.RemoveSubTree(selectedChildIndex);
    9999          // add the new child as sub-tree of parent
    100           parent.AddSubOperator(newFunction, selectedChildIndex);
     100          parent.InsertSubTree(selectedChildIndex, newFunction);
    101101        }
    102102
    103103        // recalculate size and height
    104         treeSize.Data = gardener.GetTreeSize(rootOperator);
    105         treeHeight.Data = gardener.GetTreeHeight(rootOperator);
     104        treeSize.Data = gardener.GetTreeSize(root);
     105        treeHeight.Data = gardener.GetTreeHeight(root);
    106106
    107107        // check if the size of the new tree is still in the allowed bounds
     
    112112
    113113        // check if whole tree is ok
    114         if (!gardener.IsValidTree(rootOperator)) {
     114        if (!gardener.IsValidTree(root)) {
    115115          throw new InvalidProgramException();
    116116        }
    117117
    118118        // return a composite operation that initializes all created sub-trees
    119         return gardener.CreateInitializationOperation(uninitializedOperators, scope);
    120       }
    121     }
    122 
    123 
    124     private IOperator ChangeTerminalType(IOperator parent, IOperator child, int childIndex, TreeGardener gardener, MersenneTwister random) {
     119        return gardener.CreateInitializationOperation(uninitializedBranches, scope);
     120      }
     121    }
     122
     123
     124    private IFunctionTree ChangeTerminalType(IFunctionTree parent, IFunctionTree child, int childIndex, TreeGardener gardener, MersenneTwister random) {
    125125
    126126      IList<IOperator> allowedChildren;
     
    138138    }
    139139
    140     private IOperator ChangeFunctionType(IOperator parent, IOperator child, int childIndex, TreeGardener gardener, MersenneTwister random,
    141       double balancedTreesRate, out List<IOperator> uninitializedOperators) {
    142       // since there are suboperators, we have to check which
    143       // and how many of the existing suboperators we can reuse
     140    private IFunctionTree ChangeFunctionType(IFunctionTree parent, IFunctionTree child, int childIndex, TreeGardener gardener, MersenneTwister random,
     141      double balancedTreesRate, out List<IFunctionTree> uninitializedBranches) {
     142      // since there are subtrees, we have to check which
     143      // and how many of the existing subtrees we can reuse
    144144
    145145      // let's choose the operator we want to use instead of the old child. For this we have to determine the
     
    155155
    156156      // try to make a tree with the same arity as the old child.
    157       int actualArity = child.SubOperators.Count;
     157      int actualArity = child.SubTrees.Count;
    158158      // arity of the selected operator
    159159      int minArity;
     
    165165      }).ToList();
    166166
    167       IOperator newOperator = (IOperator)allowedSubOperators[random.Next(allowedSubOperators.Count)].Clone();
     167      IFunctionTree newTree = new FunctionTree((IOperator)allowedSubOperators[random.Next(allowedSubOperators.Count)]);
    168168
    169169      gardener.GetMinMaxArity(newOperator, out minArity, out maxArity);
     
    175175      // use the size of the smallest subtree as the maximal allowed size for new subtrees to
    176176      // prevent that we ever create trees over the MaxTreeSize limit
    177       int maxSubTreeSize = child.SubOperators.Select(subOp => gardener.GetTreeSize(subOp)).Min();
     177      int maxSubTreeSize = child.SubTrees.Select(subTree => gardener.GetTreeSize(subTree)).Min();
    178178      int maxSubTreeHeight = gardener.GetTreeHeight(child) - 1;
    179179
    180180      // create a list that holds old sub-trees that we can reuse in the new tree
    181       List<IOperator> availableSubOperators = new List<IOperator>(child.SubOperators);
    182       List<IOperator> freshSubTrees = new List<IOperator>() { newOperator };
     181      List<IFunctionTree> availableSubTrees = new List<IFunctionTree>(child.SubTrees);
     182      List<IFunctionTree> freshSubTrees = new List<IFunctionTree>() { new FunctionTree(newOperator) };
    183183
    184184      // randomly select the suboperators that we keep
     
    189189        // that fit in the given slot then create a new random tree and use it for the slot
    190190        IList<IOperator> allowedOperators = analyser.GetAllowedOperators(newOperator, i);
    191         var matchingOperators = availableSubOperators.Where(subOp => allowedOperators.Contains(subOp, new TreeGardener.OperatorEqualityComparer()));
    192 
    193         if (matchingOperators.Count() > 0) {
    194           IOperator selectedSubOperator = matchingOperators.ElementAt(random.Next(matchingOperators.Count()));
     191        var matchingSubTrees = availableSubTrees.Where(subTree => allowedOperators.Contains(subTree.Function));
     192
     193        if (matchingSubTrees.Count() > 0) {
     194          IFunctionTree selectedSubTree = matchingSubTrees.ElementAt(random.Next(matchingTrees.Count()));
    195195          // we can just add it as suboperator
    196           newOperator.AddSubOperator(selectedSubOperator, i);
    197           availableSubOperators.Remove(selectedSubOperator); // the operator shouldn't be available for the following slots
     196          newTree.InsertSubTree(i, selectedSubTree);
     197          availableSubTrees.Remove(selectedSubTree); // the branch shouldn't be available for the following slots
    198198        } else {
    199           IOperator freshOperatorTree;
     199          IFunctionTree freshTree;
    200200          if(random.NextDouble() <= balancedTreesRate) {
    201             freshOperatorTree = gardener.CreateRandomTree(allowedOperators, maxSubTreeSize, maxSubTreeHeight, true);
     201            freshTree = gardener.CreateRandomTree(allowedOperators, maxSubTreeSize, maxSubTreeHeight, true);
    202202          } else {
    203             freshOperatorTree = gardener.CreateRandomTree(allowedOperators, maxSubTreeSize, maxSubTreeHeight, false);
     203            freshTree = gardener.CreateRandomTree(allowedOperators, maxSubTreeSize, maxSubTreeHeight, false);
    204204          }
    205           freshSubTrees.AddRange(gardener.GetAllOperators(freshOperatorTree));
    206 
    207           newOperator.AddSubOperator(freshOperatorTree, i);
    208         }
    209       }
    210 
    211       uninitializedOperators = freshSubTrees;
    212       return newOperator;
     205          freshSubTrees.AddRange(gardener.GetAllOperators(freshTree));
     206
     207          newTree.InsertSubTree(i, freshTree);
     208        }
     209      }
     210
     211      uninitializedBranches = freshSubTrees;
     212      return newTree;
    213213    }
    214214  }
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.StructureIdentification/RandomTreeCreator.cs

    r23 r142  
    2626using System;
    2727using HeuristicLab.Random;
     28using HeuristicLab.Functions;
    2829
    2930namespace HeuristicLab.StructureIdentification {
     
    4041      AddVariableInfo(new VariableInfo("MaxTreeSize", "The maximal allowed size (number of nodes) of the tree", typeof(IntData), VariableKind.In));
    4142      AddVariableInfo(new VariableInfo("BalancedTreesRate", "Determines how many trees should be balanced", typeof(DoubleData), VariableKind.In));
    42       AddVariableInfo(new VariableInfo("OperatorTree", "The tree to mutate", typeof(IOperator), VariableKind.In));
     43      AddVariableInfo(new VariableInfo("OperatorTree", "The tree to mutate", typeof(IFunctionTree), VariableKind.In));
    4344      AddVariableInfo(new VariableInfo("TreeSize", "The size (number of nodes) of the tree", typeof(IntData), VariableKind.In));
    4445      AddVariableInfo(new VariableInfo("TreeHeight", "The height of the tree", typeof(IntData), VariableKind.In));
     
    5657      int treeHeight = random.Next(1, maxTreeHeight + 1);
    5758      int treeSize = random.Next(1, maxTreeSize + 1);
    58       IOperator rootOperator;
     59      IFunctionTree root;
    5960      if(random.NextDouble() <= balancedTreesRate) {
    60         rootOperator = gardener.CreateRandomTree(treeSize, treeHeight, true);
     61        root = gardener.CreateRandomTree(treeSize, treeHeight, true);
    6162      } else {
    62         rootOperator = gardener.CreateRandomTree(treeSize, treeHeight, false);
     63        root = gardener.CreateRandomTree(treeSize, treeHeight, false);
    6364      }
    6465
    65       int actualTreeSize = gardener.GetTreeSize(rootOperator);
    66       int actualTreeHeight = gardener.GetTreeHeight(rootOperator);
     66      int actualTreeSize = gardener.GetTreeSize(root);
     67      int actualTreeHeight = gardener.GetTreeHeight(root);
    6768
    68       scope.AddVariable(new Variable("OperatorTree", rootOperator));
    69       scope.AddVariable(new Variable("TreeSize", new IntData(actualTreeSize)));
    70       scope.AddVariable(new Variable("TreeHeight", new IntData(actualTreeHeight)));
     69      scope.AddVariable(new HeuristicLab.Core.Variable("OperatorTree", root));
     70      scope.AddVariable(new HeuristicLab.Core.Variable("TreeSize", new IntData(actualTreeSize)));
     71      scope.AddVariable(new HeuristicLab.Core.Variable("TreeHeight", new IntData(actualTreeHeight)));
    7172
    72       if(!gardener.IsValidTree(rootOperator)) { throw new InvalidProgramException(); }
     73      if(!gardener.IsValidTree(root)) { throw new InvalidProgramException(); }
    7374
    7475      if(actualTreeSize > maxTreeSize ||
     
    7778      }
    7879
    79       return gardener.CreateInitializationOperation(gardener.GetAllOperators(rootOperator), scope);
     80      return gardener.CreateInitializationOperation(gardener.GetAllOperators(root), scope);
    8081    }
    8182  }
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.StructureIdentification/Recombination/SinglePointCrossOver.cs

    r23 r142  
    2929using HeuristicLab.Data;
    3030using HeuristicLab.Constraints;
     31using HeuristicLab.Functions;
    3132
    3233namespace HeuristicLab.StructureIdentification {
     
    4445      AddVariableInfo(new VariableInfo("MaxTreeHeight", "The maximal allowed height of the tree", typeof(IntData), VariableKind.In));
    4546      AddVariableInfo(new VariableInfo("MaxTreeSize", "The maximal allowed size (number of nodes) of the tree", typeof(IntData), VariableKind.In));
    46       AddVariableInfo(new VariableInfo("OperatorTree", "The tree to mutate", typeof(IOperator), VariableKind.In));
    47       AddVariableInfo(new VariableInfo("TreeSize", "The size (number of nodes) of the tree", typeof(IntData), VariableKind.In));
    48       AddVariableInfo(new VariableInfo("TreeHeight", "The height of the tree", typeof(IntData), VariableKind.In));
     47      AddVariableInfo(new VariableInfo("FunctionTree", "The tree to mutate", typeof(IFunctionTree), VariableKind.In | VariableKind.New));
     48      AddVariableInfo(new VariableInfo("TreeSize", "The size (number of nodes) of the tree", typeof(IntData), VariableKind.New));
     49      AddVariableInfo(new VariableInfo("TreeHeight", "The height of the tree", typeof(IntData), VariableKind.New));
    4950    }
    5051
     
    9091      int newTreeSize = gardener.GetTreeSize(newTree);
    9192      int newTreeHeight = gardener.GetTreeHeight(newTree);
    92       child.AddVariable(new Variable("OperatorTree", newTree));
     93      child.AddVariable(new Variable("FunctionTree", newTree));
    9394      child.AddVariable(new Variable("TreeSize", new IntData(newTreeSize)));
    9495      child.AddVariable(new Variable("TreeHeight", new IntData(newTreeHeight)));
     
    105106
    106107
    107     private IOperator Cross(TreeGardener gardener, IScope f, IScope g, MersenneTwister random, int maxTreeSize, int maxTreeHeight, out List<IOperator> newOperators) {
    108       IOperator tree0 = f.GetVariableValue<IOperator>("OperatorTree", false);
     108    private IFunctionTree Cross(TreeGardener gardener, IScope f, IScope g, MersenneTwister random, int maxTreeSize, int maxTreeHeight, out List<IFunctionTree> newBranches) {
     109      IFunctionTree tree0 = f.GetVariableValue<IFunctionTree>("FunctionTree", false);
    109110      int tree0Height = f.GetVariableValue<IntData>("TreeHeight", false).Data;
    110111      int tree0Size = f.GetVariableValue<IntData>("TreeSize", false).Data;
    111112
    112       IOperator tree1 = g.GetVariableValue<IOperator>("OperatorTree", false);
     113      IFunctionTree tree1 = g.GetVariableValue<IFunctionTree>("FunctionTree", false);
    113114      int tree1Height = g.GetVariableValue<IntData>("TreeHeight", false).Data;
    114115      int tree1Size = g.GetVariableValue<IntData>("TreeSize", false).Data;
    115116
    116117      if(tree0Size == 1 && tree1Size == 1) {
    117         return CombineTerminals(gardener, tree0, tree1, random, maxTreeHeight, out newOperators);
     118        return CombineTerminals(gardener, tree0, tree1, random, maxTreeHeight, out newBranches);
    118119      } else {
    119120        // we are going to insert tree1 into tree0 at a random place so we have to make sure that tree0 is not a terminal
    120121        // in case both trees are higher than 1 we swap the trees with probability 50%
    121122        if(tree0Height == 1 || (tree1Height > 1 && random.Next(2) == 0)) {
    122           IOperator tmp = tree0; tree0 = tree1; tree1 = tmp;
     123          IFunctionTree tmp = tree0; tree0 = tree1; tree1 = tmp;
    123124          int tmpHeight = tree0Height; tree0Height = tree1Height; tree1Height = tmpHeight;
    124125          int tmpSize = tree0Size; tree0Size = tree1Size; tree1Size = tmpSize;
     
    126127
    127128        // save the root because later on we change tree0 and tree1 while searching a valid tree configuration
    128         IOperator root = tree0;
     129        IFunctionTree root = tree0;
    129130        int rootSize = tree0Size;
    130131
     
    146147        // to merge the trees then throw an exception
    147148        // find the list of allowed indices (regarding allowed sub-operators, maxTreeSize and maxTreeHeight)
    148         for(int i = 0; i < tree0.SubOperators.Count; i++) {
    149           int subOperatorSize = gardener.GetTreeSize(tree0.SubOperators[i]);
     149        for(int i = 0; i < tree0.SubTrees.Count; i++) {
     150          int subOperatorSize = gardener.GetTreeSize(tree0.SubTrees[i]);
    150151
    151152          // the index is ok when the operator is allowed as sub-operator and we don't violate the maxSize and maxHeight constraints
     
    160161          // ok we couln't find a possible configuration given the current tree0 and tree1
    161162          // possible reasons for this are:
    162           //  - tree1 is not allowed as sub-operator of tree0
     163          //  - tree1 is not allowed as sub-tree of tree0
    163164          //  - appending tree1 as child of tree0 would create a tree that exceedes the maxTreeHeight
    164165          //  - replacing any child of tree0 with tree1 woulde create a tree that exceedes the maxTeeSize
     
    166167          //  - go up in tree0 => the insert position allows larger trees
    167168          //  - go down in tree1 => the tree that is inserted becomes smaller
    168           //  - however we have to get lucky to solve the 'allowed sub-operators' problem
     169          //  - however we have to get lucky to solve the 'allowed sub-trees' problem
    169170          if(tree1Height == 1 || (tree0Level>0 && random.Next(2) == 0)) {
    170171            // go up in tree0
    171172            tree0Level--;
    172173            tree0 = gardener.GetRandomNode(root, tree0Level);
    173           } else if(tree1.SubOperators.Count > 0) {
     174          } else if(tree1.SubTrees.Count > 0) {
    174175            // go down in node2:
    175             tree1 = tree1.SubOperators[random.Next(tree1.SubOperators.Count)];
     176            tree1 = tree1.SubTrees[random.Next(tree1.SubTrees.Count)];
    176177            tree1Size = gardener.GetTreeSize(tree1);
    177178            tree1Height = gardener.GetTreeHeight(tree1);
     
    183184          // recalculate the list of possible indices
    184185          possibleChildIndices.Clear();
    185           for(int i = 0; i < tree0.SubOperators.Count; i++) {
    186             int subOperatorSize = gardener.GetTreeSize(tree0.SubOperators[i]);
     186          for(int i = 0; i < tree0.SubTrees.Count; i++) {
     187            int subOperatorSize = gardener.GetTreeSize(tree0.SubTrees[i]);
    187188
    188189            // when the operator is allowed as sub-operator and we don't violate the maxSize and maxHeight constraints
     
    203204        // replace the existing sub-tree at a random index in tree0 with tree1
    204205        int selectedIndex = possibleChildIndices[random.Next(possibleChildIndices.Count)];
    205         tree0.RemoveSubOperator(selectedIndex);
    206         tree0.AddSubOperator(tree1, selectedIndex);
     206        tree0.RemoveSubTree(selectedIndex);
     207        tree0.AddSubTree(tree1, selectedIndex);
    207208
    208209        // no new operators where needed
    209         newOperators = new List<IOperator>();
     210        newBranches = new List<IFunctionTree>();
    210211        return root;
    211212      }
     
    217218    }
    218219
    219     private IOperator CombineTerminals(TreeGardener gardener, IOperator f, IOperator g, MersenneTwister random, int maxTreeHeight, out List<IOperator> newOperators) {
    220       newOperators = new List<IOperator>();
    221       ICollection<IOperator> possibleParents = gardener.GetPossibleParents(new List<IOperator>() { f, g });
     220    private IFunctionTree CombineTerminals(TreeGardener gardener, IFunctionTree f, IFunctionTree g, MersenneTwister random, int maxTreeHeight, out List<IFunctionTree> newBranches) {
     221      newBranches = new List<IFunctionTree>();
     222      ICollection<IOperator> possibleParents = gardener.GetPossibleParents(new List<IOperator>() { f.Function, g.Function });
    222223      if(possibleParents.Count == 0) throw new InvalidProgramException();
    223224
     
    233234
    234235      SubOperatorsConstraintAnalyser analyser = new SubOperatorsConstraintAnalyser();
    235       analyser.AllPossibleOperators = new List<IOperator>() { g, f };
     236      analyser.AllPossibleOperators = new List<IOperator>() { g.Function, f.Function };
    236237      for(int slot = 0; slot < nSlots; slot++) {
    237238        HashSet<IOperator> slotSet = new HashSet<IOperator>(analyser.GetAllowedOperators(parent, slot));
     
    248249          var allowedOperators = GetAllowedOperators(parent, slot);
    249250          selectedOperators[slot] = gardener.CreateRandomTree(allowedOperators, 1, 1, true);
    250           newOperators.AddRange(gardener.GetAllOperators(selectedOperators[slot]));
     251          newBranches.AddRange(gardener.GetAllOperators(selectedOperators[slot]));
    251252        } else {
    252253          IOperator selectedOperator = slotSet.ElementAt(random.Next(slotSet.Count()));
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab.StructureIdentification/TreeGardener.cs

    r23 r142  
    3131using HeuristicLab.Operators;
    3232using HeuristicLab.Selection;
     33using HeuristicLab.Functions;
    3334
    3435namespace HeuristicLab.StructureIdentification {
     
    7273
    7374    #region random initialization
    74     internal IOperator CreateRandomTree(ICollection<IOperator> allowedOperators, int maxTreeSize, int maxTreeHeight, bool balanceTrees) {
     75    internal IFunctionTree CreateRandomTree(ICollection<IOperator> allowedOperators, int maxTreeSize, int maxTreeHeight, bool balanceTrees) {
    7576
    7677      int minTreeHeight = allowedOperators.Select(op => ((IntData)op.GetVariable(GPOperatorLibrary.MIN_TREE_HEIGHT).Value).Data).Min();
     
    8788      IOperator[] possibleOperators = allowedOperators.Where(op => ((IntData)op.GetVariable(GPOperatorLibrary.MIN_TREE_HEIGHT).Value).Data <= treeHeight &&
    8889        ((IntData)op.GetVariable(GPOperatorLibrary.MIN_TREE_SIZE).Value).Data <= treeSize).ToArray();
    89       IOperator selectedOperator = (IOperator)possibleOperators[random.Next(possibleOperators.Length)].Clone();
    90 
    91       IOperator rootOperator = CreateRandomTree(selectedOperator, treeSize, treeHeight, balanceTrees);
    92 
    93       return rootOperator;
    94     }
    95 
    96     internal IOperator CreateRandomTree(int maxTreeSize, int maxTreeHeight, bool balanceTrees) {
     90      IOperator selectedOperator = possibleOperators[random.Next(possibleOperators.Length)];
     91
     92      return CreateRandomTree(selectedOperator, treeSize, treeHeight, balanceTrees);
     93    }
     94
     95    internal IFunctionTree CreateRandomTree(int maxTreeSize, int maxTreeHeight, bool balanceTrees) {
    9796      if (balanceTrees) {
    9897        if (maxTreeHeight == 1 || maxTreeSize==1) {
    99           IOperator selectedTerminal = (IOperator)terminals[random.Next(terminals.Count())].Clone();
    100           return selectedTerminal;
     98          IOperator selectedTerminal = terminals[random.Next(terminals.Count())];
     99          return new FunctionTree(selectedTerminal);
    101100        } else {
    102101          IOperator[] possibleFunctions = functions.Where(f => GetMinimalTreeHeight(f) <= maxTreeHeight &&
    103102            GetMinimalTreeSize(f) <= maxTreeSize).ToArray();
    104           IOperator selectedFunction = (IOperator)possibleFunctions[random.Next(possibleFunctions.Length)].Clone();
    105           MakeBalancedTree(selectedFunction, maxTreeSize - 1, maxTreeHeight - 1);
    106           return selectedFunction;
     103          IOperator selectedFunction = possibleFunctions[random.Next(possibleFunctions.Length)];
     104          FunctionTree root = new FunctionTree(selectedFunction);
     105          MakeBalancedTree(root, maxTreeSize - 1, maxTreeHeight - 1);
     106          return root;
    107107        }
    108108
     
    110110        IOperator[] possibleOperators = allOperators.Where(op => GetMinimalTreeHeight(op) <= maxTreeHeight &&
    111111          GetMinimalTreeSize(op) <= maxTreeSize).ToArray();
    112         IOperator selectedOperator = (IOperator)possibleOperators[random.Next(possibleOperators.Length)].Clone();
    113         MakeUnbalancedTree(selectedOperator, maxTreeSize - 1, maxTreeHeight - 1);
    114         return selectedOperator;
    115       }
    116     }
    117 
    118     internal IOperator CreateRandomTree(IOperator root, int maxTreeSize, int maxTreeHeight, bool balanceTrees) {
     112        IOperator selectedOperator = possibleOperators[random.Next(possibleOperators.Length)];
     113        FunctionTree root = new FunctionTree(selectedOperator);
     114        MakeUnbalancedTree(root, maxTreeSize - 1, maxTreeHeight - 1);
     115        return root;
     116      }
     117    }
     118
     119    internal IFunctionTree CreateRandomTree(IOperator rootOp, int maxTreeSize, int maxTreeHeight, bool balanceTrees) {
     120      IFunctionTree root = new FunctionTree(rootOp);
    119121      if (balanceTrees) {
    120122        MakeBalancedTree(root, maxTreeSize - 1, maxTreeHeight - 1);
     
    130132
    131133
    132     private void MakeUnbalancedTree(IOperator parent, int maxTreeSize, int maxTreeHeight) {
     134    private void MakeUnbalancedTree(IFunctionTree parent, int maxTreeSize, int maxTreeHeight) {
    133135      if (maxTreeHeight == 0 || maxTreeSize == 0) return;
    134136      int minArity;
    135137      int maxArity;
    136       GetMinMaxArity(parent, out minArity, out maxArity);
     138      GetMinMaxArity(parent.Function, out minArity, out maxArity);
    137139      if (maxArity >= maxTreeSize) {
    138140        maxArity = maxTreeSize;
     
    142144        int maxSubTreeSize = maxTreeSize / actualArity;
    143145        for (int i = 0; i < actualArity; i++) {
    144           IOperator[] possibleOperators = GetAllowedSubOperators(parent, i).Where(op => GetMinimalTreeHeight(op) <= maxTreeHeight &&
     146          IOperator[] possibleOperators = GetAllowedSubOperators(parent.Function, i).Where(op => GetMinimalTreeHeight(op) <= maxTreeHeight &&
    145147            GetMinimalTreeSize(op) <= maxSubTreeSize).ToArray();
    146           IOperator selectedOperator = (IOperator)possibleOperators[random.Next(possibleOperators.Length)].Clone();
    147           parent.AddSubOperator(selectedOperator, i);
    148           MakeUnbalancedTree(selectedOperator, maxSubTreeSize - 1, maxTreeHeight - 1);
     148          IOperator selectedOperator = possibleOperators[random.Next(possibleOperators.Length)];
     149          FunctionTree newSubTree = new FunctionTree(selectedOperator);
     150          MakeUnbalancedTree(newSubTree, maxSubTreeSize - 1, maxTreeHeight - 1);
     151          parent.InsertSubTree(i, newSubTree);
    149152        }
    150153      }
     
    153156    // NOTE: this method doesn't build fully balanced trees because we have constraints on the
    154157    // types of possible suboperators which can indirectly impose a limit for the depth of a given suboperator
    155     private void MakeBalancedTree(IOperator parent, int maxTreeSize, int maxTreeHeight) {
     158    private void MakeBalancedTree(IFunctionTree parent, int maxTreeSize, int maxTreeHeight) {
    156159      if (maxTreeHeight == 0 || maxTreeSize == 0) return; // should never happen anyway
    157160      int minArity;
    158161      int maxArity;
    159       GetMinMaxArity(parent, out minArity, out maxArity);
     162      GetMinMaxArity(parent.Function, out minArity, out maxArity);
    160163      if (maxArity >= maxTreeSize) {
    161164        maxArity = maxTreeSize;
     
    166169        for (int i = 0; i < actualArity; i++) {
    167170          if (maxTreeHeight == 1 || maxSubTreeSize == 1) {
    168             IOperator[] possibleTerminals = GetAllowedSubOperators(parent, i).Where(
     171            IOperator[] possibleTerminals = GetAllowedSubOperators(parent.Function, i).Where(
    169172              op => GetMinimalTreeHeight(op) <= maxTreeHeight &&
    170173              GetMinimalTreeSize(op) <= maxSubTreeSize &&
    171174              IsTerminal(op)).ToArray();
    172             IOperator selectedTerminal = (IOperator)possibleTerminals[random.Next(possibleTerminals.Length)].Clone();
    173             parent.AddSubOperator(selectedTerminal, i);
     175            IOperator selectedTerminal = possibleTerminals[random.Next(possibleTerminals.Length)];
     176            IFunctionTree newTree = new FunctionTree(selectedTerminal);
     177            parent.InsertSubTree(i, newTree);
    174178          } else {
    175             IOperator[] possibleFunctions = GetAllowedSubOperators(parent, i).Where(
     179            IOperator[] possibleFunctions = GetAllowedSubOperators(parent.Function, i).Where(
    176180              op => GetMinimalTreeHeight(op) <= maxTreeHeight &&
    177181              GetMinimalTreeSize(op) <= maxSubTreeSize &&
    178182              !IsTerminal(op)).ToArray();
    179             IOperator selectedFunction = (IOperator)possibleFunctions[random.Next(possibleFunctions.Length)].Clone();
    180             parent.AddSubOperator(selectedFunction, i);
    181             MakeBalancedTree(selectedFunction, maxSubTreeSize - 1, maxTreeHeight - 1);
     183            IOperator selectedFunction = possibleFunctions[random.Next(possibleFunctions.Length)];
     184            FunctionTree newTree = new FunctionTree(selectedFunction);
     185            parent.InsertSubTree(i, newTree);
     186            MakeBalancedTree(newTree, maxSubTreeSize - 1, maxTreeHeight - 1);
    182187          }
    183188        }
     
    185190    }
    186191
    187     internal CompositeOperation CreateInitializationOperation(ICollection<IOperator> operators, IScope scope) {
     192    internal CompositeOperation CreateInitializationOperation(ICollection<IFunctionTree> trees, IScope scope) {
    188193      // needed for the parameter shaking operation
    189194      CompositeOperation initializationOperation = new CompositeOperation();
    190195      Scope tempScope = new Scope("Temp. initialization scope");
    191196
    192       var parametricOperators = operators.Where(o => o.GetVariable(GPOperatorLibrary.INITIALIZATION) != null);
    193 
    194       foreach (IOperator op in parametricOperators) {
     197      var parametricTrees = trees.Where(o => o.Function.GetVariable(GPOperatorLibrary.INITIALIZATION) != null);
     198
     199      foreach (IFunctionTree tree in parametricTrees) {
    195200        // enqueue an initialization operation for each operator with local variables
    196         IOperator initialization = (IOperator)op.GetVariable(GPOperatorLibrary.INITIALIZATION).Value;
     201        IOperator initialization = (IOperator)tree.Function.GetVariable(GPOperatorLibrary.INITIALIZATION).Value;
    197202        Scope initScope = new Scope();
    198203
    199204        // copy the local variables into a temporary scope used for initialization
    200         foreach (VariableInfo info in op.VariableInfos) {
    201           if (info.Local) {
    202             initScope.AddVariable(op.GetVariable(info.FormalName));
    203           }
     205        foreach (IVariable variable in tree.LocalVariables) {
     206          initScope.AddVariable(variable);
    204207        }
    205208
     
    223226
    224227    #region tree information gathering
    225     internal int GetTreeSize(IOperator tree) {
    226       return 1 + tree.SubOperators.Sum(f => GetTreeSize(f));
    227     }
    228 
    229     internal int GetTreeHeight(IOperator tree) {
    230       if (tree.SubOperators.Count == 0) return 1;
    231       return 1 + tree.SubOperators.Max(f => GetTreeHeight(f));
    232     }
    233 
    234     internal IOperator GetRandomParentNode(IOperator tree) {
    235       List<IOperator> parentNodes = new List<IOperator>();
     228    internal int GetTreeSize(IFunctionTree tree) {
     229      return 1 + tree.SubTrees.Sum(f => GetTreeSize(f));
     230    }
     231
     232    internal int GetTreeHeight(IFunctionTree tree) {
     233      if (tree.SubTrees.Count == 0) return 1;
     234      return 1 + tree.SubTrees.Max(f => GetTreeHeight(f));
     235    }
     236
     237    internal IFunctionTree GetRandomParentNode(IFunctionTree tree) {
     238      List<IFunctionTree> parentNodes = new List<IFunctionTree>();
    236239
    237240      // add null for the parent of the root node
    238241      parentNodes.Add(null);
    239242
    240       TreeForEach(tree, delegate(IOperator op) {
    241         if (op.SubOperators.Count > 0) {
    242           parentNodes.Add(op);
     243      TreeForEach(tree, delegate(IFunctionTree possibleParentNode) {
     244        if (possibleParentNode.SubTrees.Count > 0) {
     245          parentNodes.Add(possibleParentNode);
    243246        }
    244247      });
     
    289292    }
    290293
    291     internal ICollection<IOperator> GetAllOperators(IOperator root) {
    292       List<IOperator> allOps = new List<IOperator>();
     294    internal ICollection<IFunctionTree> GetAllOperators(IFunctionTree root) {
     295      List<IFunctionTree> allOps = new List<IFunctionTree>();
    293296      TreeForEach(root, t => { allOps.Add(t); });
    294297      return allOps;
     
    305308    /// <param name="op">operater that is searched in the tree</param>
    306309    /// <returns></returns>
    307     internal int GetNodeLevel(IOperator tree, IOperator op) {
     310    internal int GetNodeLevel(IFunctionTree tree, IFunctionTree op) {
    308311      return GetNodeLevelHelper(tree, op, 1);
    309312    }
    310313
    311     private int GetNodeLevelHelper(IOperator tree, IOperator op, int level) {
     314    private int GetNodeLevelHelper(IFunctionTree tree, IFunctionTree op, int level) {
    312315      if (op == tree) return level;
    313316
    314       foreach (IOperator subTree in tree.SubOperators) {
     317      foreach (IFunctionTree subTree in tree.SubTrees) {
    315318        int result = GetNodeLevelHelper(subTree, op, level + 1);
    316319        if (result != -1) return result;
     
    320323    }
    321324
    322     internal bool IsValidTree(IOperator tree) {
    323       if (!tree.IsValid())
     325    internal bool IsValidTree(IFunctionTree tree) {
     326      if (!tree.Function.IsValid())
    324327        return false;
    325       foreach (IOperator subTree in tree.SubOperators) {
    326         if (!subTree.IsValid())
     328      foreach (IFunctionTree subTree in tree.SubTrees) {
     329        if (!subTree.Function.IsValid())
    327330          return false;
    328331      }
     
    332335
    333336    // returns a random node from the specified level in the tree
    334     internal IOperator GetRandomNode(IOperator tree, int level) {
     337    internal IFunctionTree GetRandomNode(IFunctionTree tree, int level) {
    335338      if (level == 0) return tree;
    336       List<IOperator> nodes = GetOperatorsAtLevel(tree, level);
     339      List<IFunctionTree> nodes = GetOperatorsAtLevel(tree, level);
    337340      return nodes[random.Next(nodes.Count)];
    338341    }
     
    349352    }
    350353
    351     private void TreeForEach(IOperator tree, Action<IOperator> action) {
     354    private void TreeForEach(IFunctionTree tree, Action<IFunctionTree> action) {
    352355      action(tree);
    353       foreach (IOperator child in tree.SubOperators) {
    354         TreeForEach(child, action);
    355       }
    356     }
    357 
    358     private List<IOperator> GetOperatorsAtLevel(IOperator tree, int level) {
    359       if (level == 1) return new List<IOperator>(tree.SubOperators);
    360 
    361       List<IOperator> result = new List<IOperator>();
    362       foreach (IOperator subOperator in tree.SubOperators) {
    363         result.AddRange(GetOperatorsAtLevel(subOperator, level - 1));
     356      foreach (IFunctionTree subTree in tree.SubTrees) {
     357        TreeForEach(subTree, action);
     358      }
     359    }
     360
     361    private List<IFunctionTree> GetOperatorsAtLevel(IFunctionTree tree, int level) {
     362      if (level == 1) return new List<IFunctionTree>(tree.SubTrees);
     363
     364      List<IFunctionTree> result = new List<IFunctionTree>();
     365      foreach (IFunctionTree subTree in tree.SubTrees) {
     366        result.AddRange(GetOperatorsAtLevel(subTree, level - 1));
    364367      }
    365368      return result;
     
    371374    internal class OperatorEqualityComparer : IEqualityComparer<IOperator> {
    372375      #region IEqualityComparer<IOperator> Members
    373 
    374376      public bool Equals(IOperator x, IOperator y) {
    375         return ((StringData)x.GetVariable(GPOperatorLibrary.TYPE_ID).Value).Data ==
     377        return  x==y ||
     378          ((StringData)x.GetVariable(GPOperatorLibrary.TYPE_ID).Value).Data ==
    376379          ((StringData)y.GetVariable(GPOperatorLibrary.TYPE_ID).Value).Data;
    377380      }
     
    380383        return ((StringData)obj.GetVariable(GPOperatorLibrary.TYPE_ID).Value).Data.GetHashCode();
    381384      }
    382 
    383385      #endregion
    384386    }
  • branches/FunctionsAndStructIdRefactoring/HeuristicLab/UpdateLocalInstallation.cmd

    r45 r142  
    1 set target=C:\Program Files\HeuristicLab 3.0
     1set target=G:\Program Files\HeuristicLab 3.0
    22
    33copy "HeuristicLab.exe" "%target%"
Note: See TracChangeset for help on using the changeset viewer.