#region License Information /* HeuristicLab * Copyright (C) 2002-2008 Heuristic and Evolutionary Algorithms Laboratory (HEAL) * * This file is part of HeuristicLab. * * HeuristicLab is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HeuristicLab is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HeuristicLab. If not, see . */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Text; using HeuristicLab.Core; using HeuristicLab.Operators; using HeuristicLab.Random; using HeuristicLab.Data; using HeuristicLab.Constraints; using System.Diagnostics; namespace HeuristicLab.GP { public abstract class SizeConstrictedGPCrossoverBase : GPCrossoverBase{ public SizeConstrictedGPCrossoverBase() : base() { AddVariableInfo(new VariableInfo("MaxTreeHeight", "The maximal allowed height of the tree", typeof(IntData), VariableKind.In)); AddVariableInfo(new VariableInfo("MaxTreeSize", "The maximal allowed size (number of nodes) of the tree", typeof(IntData), VariableKind.In)); } internal override IFunctionTree Cross(IScope scope, TreeGardener gardener, MersenneTwister random, IFunctionTree tree0, IFunctionTree tree1) { int maxTreeHeight = GetVariableValue("MaxTreeHeight", scope, true).Data; int maxTreeSize = GetVariableValue("MaxTreeSize", scope, true).Data; // when tree0 is terminal then try to cross into tree1, when tree1 is also terminal just return tree0 unchanged. IFunctionTree newTree; if (tree0.SubTrees.Count > 0) { newTree = Cross(gardener, random, tree0, tree1, maxTreeSize, maxTreeHeight); } else if (tree1.SubTrees.Count > 0) { newTree = Cross(gardener, random, tree1, tree0, maxTreeSize, maxTreeHeight); } else newTree = tree0; // check if the size and height of the new tree are still within the allowed bounds Debug.Assert(newTree.Height <= maxTreeHeight); Debug.Assert(newTree.Size <= maxTreeSize); return newTree; } internal abstract IFunctionTree Cross(TreeGardener gardener, MersenneTwister random, IFunctionTree tree0, IFunctionTree tree1, int maxTreeSize, int maxTreeHeight); private IFunctionTree TakeNextParent(IScope scope) { IFunctionTree parent = GetVariableValue("FunctionTree", scope.SubScopes[0], false); scope.RemoveSubScope(scope.SubScopes[0]); return parent; } } }