Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/Build.cmd
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/Build.cmd (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/Build.cmd (revision 9852)
@@ -0,0 +1,94 @@
+@ECHO OFF
+
+SET CLEANBEFOREBUILD=0
+
+SET SELECTED=
+SET CONFIGURATION=
+SET PLATFORM=
+
+IF "%~1"=="" GOTO :prompt_solution
+
+SET SELECTED=%1
+IF NOT EXIST %SELECTED% (
+ ECHO Solution file %SELECTED% could not be found.
+ GOTO :end
+)
+ECHO Building solution %SELECTED% ...
+GOTO :config_selection
+
+:prompt_solution
+SET /A COUNT=0
+FOR /F "tokens=*" %%A IN ('dir /B *.sln') DO (
+ CALL :forloopbody "%%A"
+)
+
+IF "%COUNT%"=="1" (
+ SET SELECTED=%SOLUTIONS.1%
+ ECHO Building %SOLUTIONS.1% as it is the only solution that was found ...
+ GOTO :config_selection
+)
+
+ECHO Found the following solutions:
+FOR /F "tokens=2* delims=.=" %%A IN ('SET SOLUTIONS.') DO ECHO %%A = %%B
+ECHO.
+SET /P SOLUTIONINDEX=Which solution to build? Type the number:
+
+SET SELECTED=""
+FOR /F "tokens=2* delims=.=" %%A IN ('SET SOLUTIONS.') DO (
+ IF "%%A"=="%SOLUTIONINDEX%" SET SELECTED=%%B
+)
+
+IF %SELECTED%=="" GOTO :eof
+
+:config_selection
+IF "%~2"=="" GOTO :prompt_config
+
+SET CONFIGURATION=%~2
+ECHO Building configuration %CONFIGURATION% ...
+GOTO :platform_selection
+
+:prompt_config
+SET /P CONFIGURATION=Which configuration to build [Release]:
+IF "%CONFIGURATION%"=="" SET CONFIGURATION=Release
+
+:platform_selection
+IF "%~3"=="" GOTO :prompt_platform
+
+SET PLATFORM=%~3
+ECHO Building platform %PLATFORM% ...
+GOTO :main
+
+:prompt_platform
+SET /P PLATFORM=Which platform to build [Any CPU]:
+IF "%PLATFORM%"=="" SET PLATFORM=Any CPU
+
+:main
+REM First find the path to the msbuild.exe by performing a registry query
+FOR /F "tokens=1,3 delims= " %%A IN ('REG QUERY "HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\MSBuild\ToolsVersions\4.0"') DO (
+ IF "%%A"=="MSBuildToolsPath" SET MSBUILDPATH=%%B)
+
+REM Then execute msbuild to clean and build the solution
+REM Disable that msbuild creates a cache file of the solution
+SET MSBuildUseNoSolutionCache=1
+REM Run msbuild to clean and then build
+IF "%CLEANBEFOREBUILD%"=="1" (
+ ECHO Cleaning ...
+ %MSBUILDPATH%msbuild.exe %SELECTED% /target:Clean /p:Configuration="%CONFIGURATION%",Platform="%PLATFORM%" /m:2 /nologo /verbosity:q /clp:ErrorsOnly
+)
+ECHO Building ...
+%MSBUILDPATH%msbuild.exe %SELECTED% /target:Rebuild /p:Configuration="%CONFIGURATION%",Platform="%PLATFORM%" /m:2 /nologo /verbosity:q /clp:ErrorsOnly
+
+ECHO.
+ECHO DONE.
+
+:end
+
+PAUSE
+
+GOTO :eof
+
+REM This workaround is necessary so that COUNT gets reevaluated
+:forloopbody
+SET /A COUNT+=1
+SET SOLUTIONS.%COUNT%=%1
+GOTO :eof
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/GraphicalSymbolicExpressionTreeView.Designer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/GraphicalSymbolicExpressionTreeView.Designer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/GraphicalSymbolicExpressionTreeView.Designer.cs (revision 9852)
@@ -0,0 +1,79 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ partial class GraphicalSymbolicExpressionTreeView {
+ ///
+ /// Required designer variable.
+ ///
+ private System.ComponentModel.IContainer components = null;
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ /// true if managed resources should be disposed; otherwise, false.
+ protected override void Dispose(bool disposing) {
+ if (disposing && (components != null)) {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Component Designer generated code
+
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ private void InitializeComponent() {
+ this.symbolicExpressionTreeChart = new HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views.SymbolicExpressionTreeChart();
+ this.SuspendLayout();
+ //
+ // functionTreeChart
+ //
+ this.symbolicExpressionTreeChart.BackgroundColor = System.Drawing.Color.White;
+ this.symbolicExpressionTreeChart.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.symbolicExpressionTreeChart.Tree = null;
+ this.symbolicExpressionTreeChart.LineColor = System.Drawing.Color.Black;
+ this.symbolicExpressionTreeChart.Location = new System.Drawing.Point(0, 0);
+ this.symbolicExpressionTreeChart.Name = "functionTreeChart";
+ this.symbolicExpressionTreeChart.Size = new System.Drawing.Size(407, 367);
+ this.symbolicExpressionTreeChart.Spacing = 5;
+ this.symbolicExpressionTreeChart.TabIndex = 0;
+ this.symbolicExpressionTreeChart.TextFont = new System.Drawing.Font("Times New Roman", 6F);
+ //
+ // FunctionTreeView
+ //
+ this.AllowDrop = true;
+ this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
+ this.Controls.Add(this.symbolicExpressionTreeChart);
+ this.Name = "FunctionTreeView";
+ this.Size = new System.Drawing.Size(407, 367);
+ this.ResumeLayout(false);
+
+ }
+
+ #endregion
+
+ private SymbolicExpressionTreeChart symbolicExpressionTreeChart;
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/GraphicalSymbolicExpressionTreeView.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/GraphicalSymbolicExpressionTreeView.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/GraphicalSymbolicExpressionTreeView.cs (revision 9852)
@@ -0,0 +1,55 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Windows.Forms;
+using HeuristicLab.Core.Views;
+using HeuristicLab.MainForm;
+using HeuristicLab.MainForm.WindowsForms;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ [View("Graphical SymbolicExpressionTree View")]
+ [Content(typeof(ISymbolicExpressionTree), true)]
+ public partial class GraphicalSymbolicExpressionTreeView : ItemView {
+ public new ISymbolicExpressionTree Content {
+ get { return (ISymbolicExpressionTree)base.Content; }
+ set { base.Content = value; }
+ }
+
+ public GraphicalSymbolicExpressionTreeView()
+ : base() {
+ InitializeComponent();
+ }
+
+ protected override void OnContentChanged() {
+ base.OnContentChanged();
+ if (Content == null) {
+ symbolicExpressionTreeChart.Tree = null;
+ } else {
+ symbolicExpressionTreeChart.Tree = Content;
+ }
+ }
+
+ protected override void SetEnabledStateOfControls() {
+ base.SetEnabledStateOfControls();
+ symbolicExpressionTreeChart.Enabled = Content != null;
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.4.csproj
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.4.csproj (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.4.csproj (revision 9852)
@@ -0,0 +1,277 @@
+
+
+
+ Debug
+ AnyCPU
+ 9.0.30729
+ 2.0
+ {423BD94F-963A-438E-BA45-3BB3D61CD03B}
+ Library
+ Properties
+ HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views
+ HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.4
+ v4.0
+
+
+ 512
+ true
+ HeuristicLab.snk
+
+
+ 3.5
+
+ publish\
+ true
+ Disk
+ false
+ Foreground
+ 7
+ Days
+ false
+ false
+ true
+ 0
+ 1.0.0.%2a
+ false
+ false
+ true
+
+
+ true
+ full
+ false
+ ..\..\..\..\trunk\sources\bin\
+ DEBUG;TRACE
+ prompt
+ 4
+ AllRules.ruleset
+
+
+ pdbonly
+ true
+ ..\..\..\..\trunk\sources\bin\
+ TRACE
+ prompt
+ 4
+ AllRules.ruleset
+
+
+ true
+ ..\..\..\..\trunk\sources\bin\
+ DEBUG;TRACE
+ full
+ x64
+ prompt
+ AllRules.ruleset
+
+
+ ..\..\..\..\trunk\sources\bin\
+ TRACE
+ true
+ pdbonly
+ x64
+ prompt
+ AllRules.ruleset
+
+
+ true
+ ..\..\..\..\trunk\sources\bin\
+ DEBUG;TRACE
+ full
+ x86
+ prompt
+ AllRules.ruleset
+
+
+ ..\..\..\..\trunk\sources\bin\
+ TRACE
+ true
+ pdbonly
+ x86
+ prompt
+ AllRules.ruleset
+
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Collections-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Common-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Common.Resources-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Core-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Core.Views-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Data-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Data.Views-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.MainForm-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.MainForm.WindowsForms-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Operators-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Optimization-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Optimization.Views-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.PluginInfrastructure-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Random-3.3.dll
+ False
+
+
+ ..\..\..\..\trunk\sources\bin\HeuristicLab.Visualization.ChartControlsExtensions-3.3.dll
+ False
+
+
+
+ 3.5
+
+
+
+
+
+ 3.5
+
+
+ 3.5
+
+
+
+
+
+
+
+ UserControl
+
+
+ SymbolicExpressionGrammarAllowedChildSymbolsControl.cs
+
+
+ UserControl
+
+
+ SymbolicExpressionGrammarEditorView.cs
+
+
+ UserControl
+
+
+ SymbolicExpressionGrammarSampleExpressionTreeView.cs
+
+
+ UserControl
+
+
+ SymbolicExpressionGrammarView.cs
+
+
+ UserControl
+
+
+ SymbolView.cs
+
+
+ UserControl
+
+
+ GraphicalSymbolicExpressionTreeView.cs
+
+
+
+ UserControl
+
+
+ SymbolicExpressionTreeChart.cs
+
+
+ UserControl
+
+
+ SymbolicExpressionView.cs
+
+
+
+
+
+
+ {06D4A186-9319-48A0-BADE-A2058D462EEA}
+ HeuristicLab.Encodings.SymbolicExpressionTreeEncoding-3.4
+ False
+
+
+
+
+
+
+
+
+
+ False
+ .NET Framework 3.5 SP1 Client Profile
+ false
+
+
+ False
+ .NET Framework 3.5 SP1
+ true
+
+
+ False
+ Windows Installer 3.1
+ true
+
+
+
+
+
+ set Path=%25Path%25;$(ProjectDir);$(SolutionDir)
+set ProjectDir=$(ProjectDir)
+set SolutionDir=$(SolutionDir)
+set Outdir=$(Outdir)
+
+call PreBuildEvent.cmd
+
+
+export ProjectDir=$(ProjectDir)
+export SolutionDir=$(SolutionDir)
+
+$SolutionDir/PreBuildEvent.sh
+
+
+
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.4.csproj.user
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.4.csproj.user (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.4.csproj.user (revision 9852)
@@ -0,0 +1,30 @@
+
+
+
+ ShowAllFiles
+
+
+ Program
+ C:\Users\P40913\Projects\HeuristicLab\trunk\sources\bin\HeuristicLab 3.3.exe
+
+
+ Program
+ C:\Users\P40913\Projects\HeuristicLab\trunk\sources\bin\HeuristicLab 3.3.exe
+
+
+ Program
+ C:\Users\P40913\Projects\HeuristicLab\trunk\sources\bin\HeuristicLab 3.3.exe
+
+
+ Program
+ C:\Users\P40913\Projects\HeuristicLab\trunk\sources\bin\HeuristicLab 3.3.exe
+
+
+ Program
+ C:\Users\P40913\Projects\HeuristicLab\trunk\sources\bin\HeuristicLab 3.3.exe
+
+
+ Program
+ C:\Users\P40913\Projects\HeuristicLab\trunk\sources\bin\HeuristicLab 3.3.exe
+
+
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Plugin.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Plugin.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Plugin.cs (revision 9852)
@@ -0,0 +1,41 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Text;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ [Plugin("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views","Provides views for the symbolic expression tree encoding.", "3.4.4.9821")]
+ [PluginFile("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.4.dll", PluginFileType.Assembly)]
+ [PluginDependency("HeuristicLab.Collections", "3.3")]
+ [PluginDependency("HeuristicLab.Common", "3.3")]
+ [PluginDependency("HeuristicLab.Common.Resources", "3.3")]
+ [PluginDependency("HeuristicLab.Core", "3.3")]
+ [PluginDependency("HeuristicLab.Core.Views", "3.3")]
+ [PluginDependency("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding", "3.4")]
+ [PluginDependency("HeuristicLab.MainForm", "3.3")]
+ [PluginDependency("HeuristicLab.MainForm.WindowsForms", "3.3")]
+ [PluginDependency("HeuristicLab.Random","3.3")]
+ public class HeuristicLabEncodingsSymbolicExpressionTreeEncodingViewsPlugin : PluginBase {
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Plugin.cs.frame
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Plugin.cs.frame (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Plugin.cs.frame (revision 9852)
@@ -0,0 +1,41 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Text;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ [Plugin("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views","Provides views for the symbolic expression tree encoding.", "3.4.4.$WCREV$")]
+ [PluginFile("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views-3.4.dll", PluginFileType.Assembly)]
+ [PluginDependency("HeuristicLab.Collections", "3.3")]
+ [PluginDependency("HeuristicLab.Common", "3.3")]
+ [PluginDependency("HeuristicLab.Common.Resources", "3.3")]
+ [PluginDependency("HeuristicLab.Core", "3.3")]
+ [PluginDependency("HeuristicLab.Core.Views", "3.3")]
+ [PluginDependency("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding", "3.4")]
+ [PluginDependency("HeuristicLab.MainForm", "3.3")]
+ [PluginDependency("HeuristicLab.MainForm.WindowsForms", "3.3")]
+ [PluginDependency("HeuristicLab.Random","3.3")]
+ public class HeuristicLabEncodingsSymbolicExpressionTreeEncodingViewsPlugin : PluginBase {
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Properties/AssemblyInfo.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Properties/AssemblyInfo.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Properties/AssemblyInfo.cs (revision 9852)
@@ -0,0 +1,47 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views")]
+[assembly: AssemblyDescription("Provides views for the symbolic expression tree encoding.")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("HeuristicLab")]
+[assembly: AssemblyCopyright("(c) 2002-2013 HEAL")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("673A0460-B43A-4853-84D2-4125532B7F51")]
+
+[assembly: AssemblyVersion("3.4.0.0")]
+[assembly: AssemblyFileVersion("3.4.4.9821")]
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Properties/AssemblyInfo.cs.frame
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Properties/AssemblyInfo.cs.frame (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/Properties/AssemblyInfo.cs.frame (revision 9852)
@@ -0,0 +1,47 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Reflection;
+using System.Runtime.CompilerServices;
+using System.Runtime.InteropServices;
+
+// General Information about an assembly is controlled through the following
+// set of attributes. Change these attribute values to modify the information
+// associated with an assembly.
+[assembly: AssemblyTitle("HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views")]
+[assembly: AssemblyDescription("Provides views for the symbolic expression tree encoding.")]
+[assembly: AssemblyConfiguration("")]
+[assembly: AssemblyCompany("")]
+[assembly: AssemblyProduct("HeuristicLab")]
+[assembly: AssemblyCopyright("(c) 2002-2013 HEAL")]
+[assembly: AssemblyTrademark("")]
+[assembly: AssemblyCulture("")]
+
+// Setting ComVisible to false makes the types in this assembly not visible
+// to COM components. If you need to access a type in this assembly from
+// COM, set the ComVisible attribute to true on that type.
+[assembly: ComVisible(false)]
+
+// The following GUID is for the ID of the typelib if this project is exposed to COM
+[assembly: Guid("673A0460-B43A-4853-84D2-4125532B7F51")]
+
+[assembly: AssemblyVersion("3.4.0.0")]
+[assembly: AssemblyFileVersion("3.4.4.$WCREV$")]
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolView.Designer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolView.Designer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolView.Designer.cs (revision 9852)
@@ -0,0 +1,184 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ partial class SymbolView {
+ ///
+ /// Required designer variable.
+ ///
+ private System.ComponentModel.IContainer components = null;
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ /// true if managed resources should be disposed; otherwise, false.
+ protected override void Dispose(bool disposing) {
+ if (disposing && (components != null)) {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Component Designer generated code
+
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ private void InitializeComponent() {
+ this.initialFrequencyLabel = new System.Windows.Forms.Label();
+ this.initialFrequencyTextBox = new System.Windows.Forms.TextBox();
+ this.enabledCheckBox = new System.Windows.Forms.CheckBox();
+ this.minimumArityLabel = new System.Windows.Forms.Label();
+ this.maximumArityLabel = new System.Windows.Forms.Label();
+ this.minimumArityTextBox = new System.Windows.Forms.TextBox();
+ this.maximumArityTextBox = new System.Windows.Forms.TextBox();
+ ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit();
+ this.SuspendLayout();
+ //
+ // nameTextBox
+ //
+ this.errorProvider.SetIconAlignment(this.nameTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft);
+ this.errorProvider.SetIconPadding(this.nameTextBox, 2);
+ this.nameTextBox.Location = new System.Drawing.Point(93, 0);
+ this.nameTextBox.Size = new System.Drawing.Size(202, 20);
+ //
+ // infoLabel
+ //
+ this.infoLabel.Location = new System.Drawing.Point(301, 3);
+ //
+ // initialFrequencyLabel
+ //
+ this.initialFrequencyLabel.AutoSize = true;
+ this.initialFrequencyLabel.Location = new System.Drawing.Point(3, 29);
+ this.initialFrequencyLabel.Name = "initialFrequencyLabel";
+ this.initialFrequencyLabel.Size = new System.Drawing.Size(84, 13);
+ this.initialFrequencyLabel.TabIndex = 3;
+ this.initialFrequencyLabel.Text = "Initial frequency:";
+ this.toolTip.SetToolTip(this.initialFrequencyLabel, "Relative frequency of the symbol in randomly created trees");
+ //
+ // initialFrequencyTextBox
+ //
+ this.initialFrequencyTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.errorProvider.SetIconAlignment(this.initialFrequencyTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft);
+ this.initialFrequencyTextBox.Location = new System.Drawing.Point(93, 26);
+ this.initialFrequencyTextBox.Name = "initialFrequencyTextBox";
+ this.initialFrequencyTextBox.Size = new System.Drawing.Size(227, 20);
+ this.initialFrequencyTextBox.TabIndex = 4;
+ this.initialFrequencyTextBox.KeyDown += new System.Windows.Forms.KeyEventHandler(this.initialFrequencyTextBox_KeyDown);
+ this.initialFrequencyTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.initialFrequencyTextBox_Validating);
+ this.initialFrequencyTextBox.Validated += new System.EventHandler(this.initialFrequencyTextBox_Validated);
+ //
+ // enabledCheckBox
+ //
+ this.enabledCheckBox.AutoSize = true;
+ this.enabledCheckBox.Location = new System.Drawing.Point(93, 104);
+ this.enabledCheckBox.Name = "enabledCheckBox";
+ this.enabledCheckBox.Size = new System.Drawing.Size(65, 17);
+ this.enabledCheckBox.TabIndex = 5;
+ this.enabledCheckBox.Text = "Enabled";
+ this.enabledCheckBox.UseVisualStyleBackColor = true;
+ this.enabledCheckBox.CheckedChanged += new System.EventHandler(this.checkBoxEnabled_CheckedChanged);
+ //
+ // minimumArityLabel
+ //
+ this.minimumArityLabel.AutoSize = true;
+ this.minimumArityLabel.Location = new System.Drawing.Point(3, 55);
+ this.minimumArityLabel.Name = "minimumArityLabel";
+ this.minimumArityLabel.Size = new System.Drawing.Size(74, 13);
+ this.minimumArityLabel.TabIndex = 8;
+ this.minimumArityLabel.Text = "Minimum Arity:";
+ this.toolTip.SetToolTip(this.minimumArityLabel, "The minimum arity of the symbol");
+ //
+ // maximumArityLabel
+ //
+ this.maximumArityLabel.AutoSize = true;
+ this.maximumArityLabel.Location = new System.Drawing.Point(3, 81);
+ this.maximumArityLabel.Name = "maximumArityLabel";
+ this.maximumArityLabel.Size = new System.Drawing.Size(74, 13);
+ this.maximumArityLabel.TabIndex = 6;
+ this.maximumArityLabel.Text = "Maximum Arity";
+ this.toolTip.SetToolTip(this.maximumArityLabel, "The maximum arity of the symbol");
+ //
+ // minimumArityTextBox
+ //
+ this.minimumArityTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.errorProvider.SetIconAlignment(this.minimumArityTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft);
+ this.minimumArityTextBox.Location = new System.Drawing.Point(93, 52);
+ this.minimumArityTextBox.Name = "minimumArityTextBox";
+ this.minimumArityTextBox.ReadOnly = true;
+ this.minimumArityTextBox.Size = new System.Drawing.Size(227, 20);
+ this.minimumArityTextBox.TabIndex = 9;
+ //
+ // maximumArityTextBox
+ //
+ this.maximumArityTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.errorProvider.SetIconAlignment(this.maximumArityTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft);
+ this.maximumArityTextBox.Location = new System.Drawing.Point(93, 78);
+ this.maximumArityTextBox.Name = "maximumArityTextBox";
+ this.maximumArityTextBox.ReadOnly = true;
+ this.maximumArityTextBox.Size = new System.Drawing.Size(227, 20);
+ this.maximumArityTextBox.TabIndex = 7;
+ //
+ // SymbolView
+ //
+ this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
+ this.Controls.Add(this.minimumArityTextBox);
+ this.Controls.Add(this.minimumArityLabel);
+ this.Controls.Add(this.maximumArityTextBox);
+ this.Controls.Add(this.maximumArityLabel);
+ this.Controls.Add(this.initialFrequencyTextBox);
+ this.Controls.Add(this.initialFrequencyLabel);
+ this.Controls.Add(this.enabledCheckBox);
+ this.Name = "SymbolView";
+ this.Size = new System.Drawing.Size(320, 123);
+ this.Controls.SetChildIndex(this.enabledCheckBox, 0);
+ this.Controls.SetChildIndex(this.initialFrequencyLabel, 0);
+ this.Controls.SetChildIndex(this.initialFrequencyTextBox, 0);
+ this.Controls.SetChildIndex(this.maximumArityLabel, 0);
+ this.Controls.SetChildIndex(this.maximumArityTextBox, 0);
+ this.Controls.SetChildIndex(this.minimumArityLabel, 0);
+ this.Controls.SetChildIndex(this.minimumArityTextBox, 0);
+ this.Controls.SetChildIndex(this.infoLabel, 0);
+ this.Controls.SetChildIndex(this.nameLabel, 0);
+ this.Controls.SetChildIndex(this.nameTextBox, 0);
+ ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).EndInit();
+ this.ResumeLayout(false);
+ this.PerformLayout();
+
+ }
+
+ #endregion
+
+ protected System.Windows.Forms.Label initialFrequencyLabel;
+ protected System.Windows.Forms.TextBox initialFrequencyTextBox;
+ protected System.Windows.Forms.CheckBox enabledCheckBox;
+ protected System.Windows.Forms.Label minimumArityLabel;
+ protected System.Windows.Forms.Label maximumArityLabel;
+ protected System.Windows.Forms.TextBox minimumArityTextBox;
+ protected System.Windows.Forms.TextBox maximumArityTextBox;
+
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolView.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolView.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolView.cs (revision 9852)
@@ -0,0 +1,121 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.ComponentModel;
+using System.Windows.Forms;
+using HeuristicLab.Core.Views;
+using HeuristicLab.MainForm;
+using HeuristicLab.MainForm.WindowsForms;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ [View("Symbol View")]
+ [Content(typeof(ISymbol), true)]
+ public partial class SymbolView : NamedItemView {
+ public new ISymbol Content {
+ get { return (ISymbol)base.Content; }
+ set { base.Content = value; }
+ }
+
+ public SymbolView() {
+ InitializeComponent();
+ }
+
+ protected override void RegisterContentEvents() {
+ base.RegisterContentEvents();
+ Content.Changed += new EventHandler(Content_Changed);
+ }
+
+ protected override void DeregisterContentEvents() {
+ base.DeregisterContentEvents();
+ Content.Changed -= new EventHandler(Content_Changed);
+ }
+
+ protected override void OnContentChanged() {
+ base.OnContentChanged();
+ UpdateControl();
+ }
+
+ protected override void SetEnabledStateOfControls() {
+ base.SetEnabledStateOfControls();
+ initialFrequencyTextBox.Enabled = Content != null && !Locked;
+ initialFrequencyTextBox.ReadOnly = ReadOnly;
+ enabledCheckBox.Enabled = Content != null && !Locked && !ReadOnly;
+ }
+
+ #region content event handlers
+ private void Content_Changed(object sender, EventArgs e) {
+ UpdateControl();
+ }
+ #endregion
+
+ #region control event handlers
+ private void initialFrequencyTextBox_KeyDown(object sender, KeyEventArgs e) {
+ if ((e.KeyCode == Keys.Enter) || (e.KeyCode == Keys.Return))
+ initialFrequencyLabel.Select(); // select label to validate data
+
+ if (e.KeyCode == Keys.Escape) {
+ initialFrequencyTextBox.Text = Content.InitialFrequency.ToString();
+ initialFrequencyLabel.Select(); // select label to validate data
+ }
+ }
+ private void initialFrequencyTextBox_Validating(object sender, CancelEventArgs e) {
+ double freq;
+ if (double.TryParse(initialFrequencyTextBox.Text, out freq) && freq >= 0.0) {
+ errorProvider.SetError(initialFrequencyTextBox, string.Empty);
+ e.Cancel = false;
+ } else {
+ errorProvider.SetError(initialFrequencyTextBox, "Invalid value");
+ e.Cancel = true;
+ }
+ }
+ private void initialFrequencyTextBox_Validated(object sender, EventArgs e) {
+ double freq;
+ if (double.TryParse(initialFrequencyTextBox.Text, out freq) && freq >= 0.0) {
+ Content.InitialFrequency = freq;
+ }
+ }
+
+ private void checkBoxEnabled_CheckedChanged(object sender, EventArgs e) {
+ if (Content != null)
+ Content.Enabled = enabledCheckBox.Checked;
+ }
+ #endregion
+
+ #region helpers
+ private void UpdateControl() {
+ if (Content == null) {
+ initialFrequencyTextBox.Text = string.Empty;
+ minimumArityTextBox.Text = string.Empty;
+ maximumArityTextBox.Text = string.Empty;
+ enabledCheckBox.Checked = false;
+ } else {
+ initialFrequencyTextBox.Text = Content.InitialFrequency.ToString();
+ minimumArityTextBox.Text = Content.MinimumArity.ToString();
+ maximumArityTextBox.Text = Content.MaximumArity.ToString();
+ enabledCheckBox.Checked = Content.Enabled;
+ }
+ SetEnabledStateOfControls();
+ }
+ #endregion
+
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarAllowedChildSymbolsControl.Designer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarAllowedChildSymbolsControl.Designer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarAllowedChildSymbolsControl.Designer.cs (revision 9852)
@@ -0,0 +1,102 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ partial class SymbolicExpressionGrammarAllowedChildSymbolsControl {
+ ///
+ /// Required designer variable.
+ ///
+ private System.ComponentModel.IContainer components = null;
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ /// true if managed resources should be disposed; otherwise, false.
+ protected override void Dispose(bool disposing) {
+ if (disposing && (components != null)) {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Component Designer generated code
+
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ private void InitializeComponent() {
+ this.allowedChildSymbolsGroupBox = new System.Windows.Forms.GroupBox();
+ this.symbolicExpressionTreeChart = new HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views.SymbolicExpressionTreeChart();
+ this.allowedChildSymbolsGroupBox.SuspendLayout();
+ this.SuspendLayout();
+ //
+ // allowedChildSymbolsGroupBox
+ //
+ this.allowedChildSymbolsGroupBox.Controls.Add(this.symbolicExpressionTreeChart);
+ this.allowedChildSymbolsGroupBox.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.allowedChildSymbolsGroupBox.Location = new System.Drawing.Point(0, 0);
+ this.allowedChildSymbolsGroupBox.Name = "allowedChildSymbolsGroupBox";
+ this.allowedChildSymbolsGroupBox.Size = new System.Drawing.Size(651, 405);
+ this.allowedChildSymbolsGroupBox.TabIndex = 2;
+ this.allowedChildSymbolsGroupBox.TabStop = false;
+ this.allowedChildSymbolsGroupBox.Text = "Allowed Child Symbols";
+ //
+ // allowedChildSymbolsControl
+ //
+ this.symbolicExpressionTreeChart.AllowDrop = true;
+ this.symbolicExpressionTreeChart.BackgroundColor = System.Drawing.Color.White;
+ this.symbolicExpressionTreeChart.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.symbolicExpressionTreeChart.LineColor = System.Drawing.Color.Black;
+ this.symbolicExpressionTreeChart.Location = new System.Drawing.Point(3, 16);
+ this.symbolicExpressionTreeChart.Name = "allowedChildSymbolsControl";
+ this.symbolicExpressionTreeChart.Size = new System.Drawing.Size(645, 386);
+ this.symbolicExpressionTreeChart.Spacing = 5;
+ this.symbolicExpressionTreeChart.SuspendRepaint = false;
+ this.symbolicExpressionTreeChart.TabIndex = 0;
+ this.symbolicExpressionTreeChart.TextFont = new System.Drawing.Font("Times New Roman", 8F);
+ this.symbolicExpressionTreeChart.Tree = null;
+ this.symbolicExpressionTreeChart.SymbolicExpressionTreeNodeClicked += new System.Windows.Forms.MouseEventHandler(this.symbolicExpressionTreeChart_SymbolicExpressionTreeNodeClicked);
+ this.symbolicExpressionTreeChart.DragDrop += new System.Windows.Forms.DragEventHandler(this.symbolicExpressionTreeChart_DragDrop);
+ this.symbolicExpressionTreeChart.DragEnter += new System.Windows.Forms.DragEventHandler(this.symbolicExpressionTreeChart_DragEnter);
+ this.symbolicExpressionTreeChart.DragOver += new System.Windows.Forms.DragEventHandler(this.symbolicExpressionTreeChart_DragOver);
+ this.symbolicExpressionTreeChart.Paint += new System.Windows.Forms.PaintEventHandler(this.allowedChildSymbolsControl_Paint);
+ this.symbolicExpressionTreeChart.KeyDown += new System.Windows.Forms.KeyEventHandler(this.symbolicExpressionTreeChart_KeyDown);
+ this.symbolicExpressionTreeChart.MouseDown += new System.Windows.Forms.MouseEventHandler(this.allowedChildSymbolsControl_MouseDown);
+ //
+ // SymbolicExpressionGrammarAllowedChildSymbolsControl
+ //
+ this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
+ this.Controls.Add(this.allowedChildSymbolsGroupBox);
+ this.Name = "SymbolicExpressionGrammarAllowedChildSymbolsControl";
+ this.Size = new System.Drawing.Size(651, 405);
+ this.allowedChildSymbolsGroupBox.ResumeLayout(false);
+ this.ResumeLayout(false);
+
+ }
+
+ #endregion
+
+ private System.Windows.Forms.GroupBox allowedChildSymbolsGroupBox;
+ private SymbolicExpressionTreeChart symbolicExpressionTreeChart;
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarAllowedChildSymbolsControl.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarAllowedChildSymbolsControl.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarAllowedChildSymbolsControl.cs (revision 9852)
@@ -0,0 +1,341 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Drawing;
+using System.Linq;
+using System.Windows.Forms;
+using HeuristicLab.Collections;
+using HeuristicLab.Common;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ public sealed partial class SymbolicExpressionGrammarAllowedChildSymbolsControl : UserControl {
+ private ObservableList selectedSymbolicExpressionTreeNodes;
+
+ public SymbolicExpressionGrammarAllowedChildSymbolsControl() {
+ InitializeComponent();
+ selectedSymbolicExpressionTreeNodes = new ObservableList();
+ }
+
+ private ISymbolicExpressionGrammar grammar;
+ public ISymbolicExpressionGrammar Grammar {
+ get { return grammar; }
+ set {
+ if (grammar != value) {
+ if (grammar != null) DeregisterGrammarEvents();
+ grammar = value;
+ if (grammar != null) RegisterGrammarEvents();
+ OnGrammarChanged();
+ }
+ }
+ }
+
+ private ISymbol symbol;
+ public ISymbol Symbol {
+ get { return symbol; }
+ set {
+ if (symbol != value) {
+ if (value != null && grammar == null) throw new InvalidOperationException("grammar is null");
+ if (value != null && !grammar.ContainsSymbol(value)) throw new ArgumentException("grammar does not contain symbol.");
+ symbol = value;
+ OnSymbolChanged();
+ }
+ }
+ }
+
+ private void RegisterGrammarEvents() {
+ grammar.Changed += new EventHandler(Grammar_Changed);
+ grammar.ReadOnlyChanged += new EventHandler(Grammar_ReadOnlyChanged);
+ }
+ private void DeregisterGrammarEvents() {
+ grammar.Changed -= new EventHandler(Grammar_Changed);
+ grammar.ReadOnlyChanged -= new EventHandler(Grammar_ReadOnlyChanged);
+ }
+
+ private void Grammar_Changed(object sender, EventArgs e) {
+ if (Grammar == null) return;
+ if (Symbol == null) return;
+ if (Symbol != null && !Grammar.ContainsSymbol(Symbol)) Symbol = null;
+ else BuildAllowedChildSymbolsTree();
+ }
+
+ private void Grammar_ReadOnlyChanged(object sender, EventArgs e) {
+ if (InvokeRequired) Invoke((MethodInvoker)BuildAllowedChildSymbolsTree);
+ else BuildAllowedChildSymbolsTree();
+ }
+
+ private void OnGrammarChanged() {
+ if (Grammar == null) {
+ symbolicExpressionTreeChart.Tree = null;
+ Symbol = null;
+ }
+ }
+ private void OnSymbolChanged() {
+ if (Symbol == null) symbolicExpressionTreeChart.Tree = null;
+ else BuildAllowedChildSymbolsTree();
+ }
+
+ private void BuildAllowedChildSymbolsTree() {
+ if (Symbol == null) {
+ symbolicExpressionTreeChart.Tree = null;
+ return;
+ }
+
+ var tree = new SymbolicExpressionTree(new SymbolicExpressionTreeNode(Symbol));
+ symbolicExpressionTreeChart.SuspendRepaint = true;
+ if (Grammar.GetMaximumSubtreeCount(Symbol) > 0) {
+ for (int i = 0; i < Grammar.GetMaximumSubtreeCount(Symbol); i++) {
+ var node = new DummySymbol("Subtree " + i).CreateTreeNode();
+ var groupSymbols = grammar.GetAllowedChildSymbols(Symbol, i).OfType().ToList();
+ foreach (var childSymbol in Grammar.GetAllowedChildSymbols(Symbol, i)) {
+ if (!groupSymbols.Any(g => g != childSymbol && g.Flatten().Contains(childSymbol)))
+ node.AddSubtree(new SymbolicExpressionTreeNode(childSymbol));
+ }
+ tree.Root.AddSubtree(node);
+ }
+ }
+ symbolicExpressionTreeChart.Tree = tree;
+
+ foreach (var subtreeNode in tree.Root.Subtrees) {
+ foreach (var allowedChildNode in subtreeNode.Subtrees) {
+ var visualLine = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNodeConnection(subtreeNode, allowedChildNode);
+ visualLine.DashStyle = System.Drawing.Drawing2D.DashStyle.Dot;
+ }
+ }
+
+ for (int i = Grammar.GetMinimumSubtreeCount(symbol); i < Grammar.GetMaximumSubtreeCount(symbol); i++) {
+ var subtreeNode = tree.Root.GetSubtree(i);
+ var visualTreeNode = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNode(subtreeNode);
+ visualTreeNode.TextColor = Color.Gray;
+ visualTreeNode.LineColor = Color.LightGray;
+
+ var visualLine = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNodeConnection(tree.Root, subtreeNode);
+ visualLine.LineColor = Color.LightGray;
+
+ foreach (var allowedChildNode in subtreeNode.Subtrees) {
+ visualTreeNode = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNode(allowedChildNode);
+ visualTreeNode.TextColor = Color.Gray;
+ visualTreeNode.LineColor = Color.LightGray;
+
+ visualLine = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNodeConnection(subtreeNode, allowedChildNode);
+ visualLine.LineColor = Color.LightGray;
+ }
+ }
+
+ symbolicExpressionTreeChart.SuspendRepaint = false;
+ UpdateSelectedSymbolicExpressionTreeNodes();
+ }
+
+ private void UpdateSelectedSymbolicExpressionTreeNodes() {
+ foreach (var node in symbolicExpressionTreeChart.Tree.IterateNodesPrefix()) {
+ var visualNode = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNode(node);
+ if (!selectedSymbolicExpressionTreeNodes.Contains(node)) visualNode.FillColor = Color.White;
+ else visualNode.FillColor = Color.LightSteelBlue;
+ }
+ symbolicExpressionTreeChart.Repaint();
+ }
+
+ private void symbolicExpressionTreeChart_SymbolicExpressionTreeNodeClicked(object sender, MouseEventArgs e) {
+ if (Grammar.ReadOnly) return;
+ if ((Control.ModifierKeys & Keys.Control) == 0)
+ selectedSymbolicExpressionTreeNodes.Clear();
+
+ VisualSymbolicExpressionTreeNode clickedNode = (VisualSymbolicExpressionTreeNode)sender;
+ var selectedNode = clickedNode.SymbolicExpressionTreeNode;
+ if (selectedNode.SubtreeCount == 0) {
+ if (!selectedSymbolicExpressionTreeNodes.Contains(selectedNode))
+ selectedSymbolicExpressionTreeNodes.Add(selectedNode);
+ else
+ selectedSymbolicExpressionTreeNodes.Remove(selectedNode);
+ }
+
+ UpdateSelectedSymbolicExpressionTreeNodes();
+ }
+
+ private void symbolicExpressionTreeChart_KeyDown(object sender, KeyEventArgs e) {
+ if (Grammar.ReadOnly) return;
+ if (e.KeyCode == Keys.Delete) {
+ var root = symbolicExpressionTreeChart.Tree.Root;
+ Grammar.StartGrammarManipulation();
+ foreach (var node in selectedSymbolicExpressionTreeNodes) {
+ int argIndex = root.IndexOfSubtree(node.Parent);
+ Grammar.RemoveAllowedChildSymbol(root.Symbol, node.Symbol, argIndex);
+ }
+
+ selectedSymbolicExpressionTreeNodes.Clear();
+ Grammar.FinishedGrammarManipulation();
+ }
+ }
+
+ #region drag & drop operations
+ private bool validDragOperation;
+ private void symbolicExpressionTreeChart_DragEnter(object sender, DragEventArgs e) {
+ validDragOperation = false;
+ if (Grammar.ReadOnly) return;
+
+ var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
+ var symbol = data as ISymbol;
+ var symbols = data as IEnumerable;
+ if (symbol != null && !(symbol is IReadOnlySymbol) && Grammar.ContainsSymbol(symbol)) validDragOperation = true;
+ else if (symbols != null && symbols.All(s => !(symbol is IReadOnlySymbol) && Grammar.ContainsSymbol(s))) validDragOperation = true;
+ }
+
+ private void symbolicExpressionTreeChart_DragOver(object sender, DragEventArgs e) {
+ e.Effect = DragDropEffects.None;
+ if (validDragOperation) {
+ Point coordinates = symbolicExpressionTreeChart.PointToClient(new Point(e.X, e.Y));
+ var visualNode = symbolicExpressionTreeChart.FindVisualSymbolicExpressionTreeNodeAt(coordinates.X, coordinates.Y);
+ if (visualNode != null) {
+ var node = visualNode.SymbolicExpressionTreeNode;
+ var root = symbolicExpressionTreeChart.Tree.Root;
+ if (node == root || node.Parent == root) e.Effect = DragDropEffects.Copy;
+ }
+ }
+ }
+
+ private void symbolicExpressionTreeChart_DragDrop(object sender, DragEventArgs e) {
+ Point coordinates = symbolicExpressionTreeChart.PointToClient(new Point(e.X, e.Y));
+ var node = symbolicExpressionTreeChart.FindVisualSymbolicExpressionTreeNodeAt(coordinates.X, coordinates.Y);
+ var root = symbolicExpressionTreeChart.Tree.Root;
+
+ var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
+ var symbol = data as ISymbol;
+ var symbols = data as IEnumerable;
+
+ if (node.SymbolicExpressionTreeNode == root) {
+ if (symbol != null)
+ Grammar.AddAllowedChildSymbol(root.Symbol, symbol);
+ else if (symbols != null)
+ foreach (var s in symbols) Grammar.AddAllowedChildSymbol(root.Symbol, s);
+ } else {
+ int argumentIndex = root.IndexOfSubtree(node.SymbolicExpressionTreeNode);
+ if (symbol != null)
+ Grammar.AddAllowedChildSymbol(root.Symbol, symbol, argumentIndex);
+ else if (symbols != null)
+ foreach (var s in symbols) Grammar.AddAllowedChildSymbol(root.Symbol, s, argumentIndex);
+ }
+ BuildAllowedChildSymbolsTree();
+ }
+ #endregion
+
+ #region draw and handle root node with buttons to manipulate the subtree count
+ private RectangleF increaseMinimumSubtreeCountRectangle;
+ private RectangleF decreaseMinimumSubtreeCountRectangle;
+ private RectangleF increaseMaximumSubtreeCountRectangle;
+ private RectangleF decreaseMaximumSubtreeCountRectangle;
+ private void allowedChildSymbolsControl_Paint(object sender, PaintEventArgs e) {
+ increaseMinimumSubtreeCountRectangle = RectangleF.Empty;
+ decreaseMinimumSubtreeCountRectangle = RectangleF.Empty;
+ increaseMaximumSubtreeCountRectangle = RectangleF.Empty;
+ decreaseMaximumSubtreeCountRectangle = RectangleF.Empty;
+
+ if (Grammar == null) return;
+ if (symbolicExpressionTreeChart.Tree == null) return;
+
+ var rootNode = symbolicExpressionTreeChart.Tree.Root;
+ var visualRootNode = symbolicExpressionTreeChart.GetVisualSymbolicExpressionTreeNode(rootNode);
+ var graphics = e.Graphics;
+
+ if (rootNode.Symbol is IReadOnlySymbol) return;
+ if (rootNode.Symbol.MinimumArity == rootNode.Symbol.MaximumArity) return;
+
+ using (Pen pen = new Pen(Color.Black)) {
+ using (Font font = new Font("Times New Roman", 8)) {
+ var stringFormat = new StringFormat();
+ stringFormat.Alignment = StringAlignment.Center;
+ stringFormat.LineAlignment = StringAlignment.Center;
+ int spacing = 5;
+ int size = (visualRootNode.Height - spacing * 3) / 2;
+
+ increaseMinimumSubtreeCountRectangle = new RectangleF(visualRootNode.X - spacing - size, visualRootNode.Y + spacing, size, size);
+ decreaseMinimumSubtreeCountRectangle = new RectangleF(visualRootNode.X - spacing - size, visualRootNode.Y + size + 2 * spacing, size, size);
+ increaseMaximumSubtreeCountRectangle = new RectangleF(visualRootNode.X + visualRootNode.Width + spacing, visualRootNode.Y + spacing, size, size);
+ decreaseMaximumSubtreeCountRectangle = new RectangleF(visualRootNode.X + visualRootNode.Width + spacing, visualRootNode.Y + size + 2 * spacing, size, size);
+
+ pen.Color = Grammar.ReadOnly || Grammar.GetMaximumSubtreeCount(rootNode.Symbol) == Grammar.GetMinimumSubtreeCount(rootNode.Symbol) ? Color.LightGray : Color.Black;
+ graphics.DrawString("+", font, pen.Brush, increaseMinimumSubtreeCountRectangle, stringFormat);
+ graphics.DrawRectangle(pen, Rectangle.Round(increaseMinimumSubtreeCountRectangle));
+ if (pen.Color == Color.LightGray) increaseMinimumSubtreeCountRectangle = RectangleF.Empty;
+
+ pen.Color = Grammar.ReadOnly || Grammar.GetMinimumSubtreeCount(rootNode.Symbol) == rootNode.Symbol.MinimumArity ? Color.LightGray : Color.Black;
+ graphics.DrawString("-", font, pen.Brush, decreaseMinimumSubtreeCountRectangle, stringFormat);
+ graphics.DrawRectangle(pen, Rectangle.Round(decreaseMinimumSubtreeCountRectangle));
+ if (pen.Color == Color.LightGray) decreaseMinimumSubtreeCountRectangle = RectangleF.Empty;
+
+ pen.Color = Grammar.ReadOnly || Grammar.GetMaximumSubtreeCount(rootNode.Symbol) == rootNode.Symbol.MaximumArity ? Color.LightGray : Color.Black;
+ graphics.DrawRectangle(pen, Rectangle.Round(increaseMaximumSubtreeCountRectangle));
+ graphics.DrawString("+", font, pen.Brush, increaseMaximumSubtreeCountRectangle, stringFormat);
+ if (pen.Color == Color.LightGray) increaseMaximumSubtreeCountRectangle = RectangleF.Empty;
+
+ pen.Color = Grammar.ReadOnly || Grammar.GetMaximumSubtreeCount(rootNode.Symbol) == Grammar.GetMinimumSubtreeCount(rootNode.Symbol) ? Color.LightGray : Color.Black;
+ graphics.DrawRectangle(pen, Rectangle.Round(decreaseMaximumSubtreeCountRectangle));
+ graphics.DrawString("-", font, pen.Brush, decreaseMaximumSubtreeCountRectangle, stringFormat);
+ if (pen.Color == Color.LightGray) decreaseMaximumSubtreeCountRectangle = RectangleF.Empty;
+ }
+ }
+ }
+
+ private void allowedChildSymbolsControl_MouseDown(object sender, MouseEventArgs e) {
+ if (Grammar == null || Grammar.ReadOnly) return;
+ if (symbolicExpressionTreeChart.Tree == null) return;
+
+ var pointF = new PointF(e.X, e.Y);
+ var rootSymbol = symbolicExpressionTreeChart.Tree.Root.Symbol;
+ int minimumSubtreeCount = Grammar.GetMinimumSubtreeCount(rootSymbol);
+ int maximumSubtreecount = Grammar.GetMaximumSubtreeCount(rootSymbol);
+
+ bool changed = true;
+ if (increaseMinimumSubtreeCountRectangle.Contains(pointF))
+ Grammar.SetSubtreeCount(rootSymbol, minimumSubtreeCount + 1, maximumSubtreecount);
+ else if (decreaseMinimumSubtreeCountRectangle.Contains(pointF))
+ Grammar.SetSubtreeCount(rootSymbol, minimumSubtreeCount - 1, maximumSubtreecount);
+ else if (increaseMaximumSubtreeCountRectangle.Contains(pointF))
+ Grammar.SetSubtreeCount(rootSymbol, minimumSubtreeCount, maximumSubtreecount + 1);
+ else if (decreaseMaximumSubtreeCountRectangle.Contains(pointF))
+ Grammar.SetSubtreeCount(rootSymbol, minimumSubtreeCount, maximumSubtreecount - 1);
+ else
+ changed = false;
+
+ if (changed) BuildAllowedChildSymbolsTree();
+ }
+ #endregion
+
+ }
+
+ [NonDiscoverableType]
+ internal class DummySymbol : Symbol {
+ private const int minimumArity = 1;
+ private const int maximumArity = byte.MaxValue;
+
+ public override int MinimumArity {
+ get { return minimumArity; }
+ }
+ public override int MaximumArity {
+ get { return maximumArity; }
+ }
+
+ public DummySymbol(DummySymbol original, Cloner cloner) : base(original, cloner) { }
+ public DummySymbol(string name) : base(name, "DummySymbol for views") { }
+ public override IDeepCloneable Clone(Cloner cloner) { return new DummySymbol(this, cloner); }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarEditorView.Designer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarEditorView.Designer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarEditorView.Designer.cs (revision 9852)
@@ -0,0 +1,309 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ partial class SymbolicExpressionGrammarEditorView {
+ ///
+ /// Required designer variable.
+ ///
+ private System.ComponentModel.IContainer components = null;
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ /// true if managed resources should be disposed; otherwise, false.
+ protected override void Dispose(bool disposing) {
+ if (disposing && (components != null)) {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Component Designer generated code
+
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ private void InitializeComponent() {
+ this.components = new System.ComponentModel.Container();
+ System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SymbolicExpressionGrammarEditorView));
+ this.grpSymbols = new System.Windows.Forms.GroupBox();
+ this.splitContainer1 = new System.Windows.Forms.SplitContainer();
+ this.copyButton = new System.Windows.Forms.Button();
+ this.showDetailsCheckBox = new System.Windows.Forms.CheckBox();
+ this.removeButton = new System.Windows.Forms.Button();
+ this.addButton = new System.Windows.Forms.Button();
+ this.symbolsTreeView = new HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views.CheckBoxTreeView();
+ this.imageList = new System.Windows.Forms.ImageList(this.components);
+ this.splitContainer2 = new System.Windows.Forms.SplitContainer();
+ this.allowedChildSymbolsControl = new HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views.SymbolicExpressionGrammarAllowedChildSymbolsControl();
+ this.symbolDetailsGroupBox = new System.Windows.Forms.GroupBox();
+ this.symbolDetailsViewHost = new HeuristicLab.MainForm.WindowsForms.ViewHost();
+ this.showSampleTreeButton = new System.Windows.Forms.Button();
+ ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit();
+ this.grpSymbols.SuspendLayout();
+ ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).BeginInit();
+ this.splitContainer1.Panel1.SuspendLayout();
+ this.splitContainer1.Panel2.SuspendLayout();
+ this.splitContainer1.SuspendLayout();
+ ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).BeginInit();
+ this.splitContainer2.Panel1.SuspendLayout();
+ this.splitContainer2.Panel2.SuspendLayout();
+ this.splitContainer2.SuspendLayout();
+ this.symbolDetailsGroupBox.SuspendLayout();
+ this.SuspendLayout();
+ //
+ // nameTextBox
+ //
+ this.errorProvider.SetIconAlignment(this.nameTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft);
+ this.errorProvider.SetIconPadding(this.nameTextBox, 2);
+ this.nameTextBox.Size = new System.Drawing.Size(686, 20);
+ //
+ // infoLabel
+ //
+ this.infoLabel.Location = new System.Drawing.Point(750, 3);
+ //
+ // grpSymbols
+ //
+ this.grpSymbols.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.grpSymbols.Controls.Add(this.splitContainer1);
+ this.grpSymbols.Location = new System.Drawing.Point(0, 26);
+ this.grpSymbols.Name = "grpSymbols";
+ this.grpSymbols.Size = new System.Drawing.Size(769, 378);
+ this.grpSymbols.TabIndex = 3;
+ this.grpSymbols.TabStop = false;
+ this.grpSymbols.Text = "Symbols";
+ //
+ // splitContainer1
+ //
+ this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.splitContainer1.Location = new System.Drawing.Point(3, 16);
+ this.splitContainer1.Name = "splitContainer1";
+ //
+ // splitContainer1.Panel1
+ //
+ this.splitContainer1.Panel1.Controls.Add(this.showSampleTreeButton);
+ this.splitContainer1.Panel1.Controls.Add(this.copyButton);
+ this.splitContainer1.Panel1.Controls.Add(this.showDetailsCheckBox);
+ this.splitContainer1.Panel1.Controls.Add(this.removeButton);
+ this.splitContainer1.Panel1.Controls.Add(this.addButton);
+ this.splitContainer1.Panel1.Controls.Add(this.symbolsTreeView);
+ //
+ // splitContainer1.Panel2
+ //
+ this.splitContainer1.Panel2.Controls.Add(this.splitContainer2);
+ this.splitContainer1.Size = new System.Drawing.Size(763, 359);
+ this.splitContainer1.SplitterDistance = 191;
+ this.splitContainer1.TabIndex = 0;
+ //
+ // copyButton
+ //
+ this.copyButton.Enabled = false;
+ this.copyButton.Image = HeuristicLab.Common.Resources.VSImageLibrary.Copy;
+ this.copyButton.Location = new System.Drawing.Point(33, 3);
+ this.copyButton.Name = "copyButton";
+ this.copyButton.Size = new System.Drawing.Size(24, 24);
+ this.copyButton.TabIndex = 8;
+ this.toolTip.SetToolTip(this.copyButton, "Copy Symbol");
+ this.copyButton.UseVisualStyleBackColor = true;
+ this.copyButton.Click += new System.EventHandler(this.copyButton_Click);
+ //
+ // showDetailsCheckBox
+ //
+ this.showDetailsCheckBox.Appearance = System.Windows.Forms.Appearance.Button;
+ this.showDetailsCheckBox.Checked = true;
+ this.showDetailsCheckBox.CheckState = System.Windows.Forms.CheckState.Checked;
+ this.showDetailsCheckBox.Image = HeuristicLab.Common.Resources.VSImageLibrary.Properties;
+ this.showDetailsCheckBox.Location = new System.Drawing.Point(93, 3);
+ this.showDetailsCheckBox.Name = "showDetailsCheckBox";
+ this.showDetailsCheckBox.Size = new System.Drawing.Size(24, 24);
+ this.showDetailsCheckBox.TabIndex = 7;
+ this.toolTip.SetToolTip(this.showDetailsCheckBox, "Show/Hide Details");
+ this.showDetailsCheckBox.UseVisualStyleBackColor = true;
+ this.showDetailsCheckBox.CheckedChanged += new System.EventHandler(this.showDetailsCheckBox_CheckedChanged);
+ //
+ // removeButton
+ //
+ this.removeButton.Enabled = false;
+ this.removeButton.Image = HeuristicLab.Common.Resources.VSImageLibrary.Remove;
+ this.removeButton.Location = new System.Drawing.Point(63, 3);
+ this.removeButton.Name = "removeButton";
+ this.removeButton.Size = new System.Drawing.Size(24, 24);
+ this.removeButton.TabIndex = 6;
+ this.toolTip.SetToolTip(this.removeButton, "Remove Symbol");
+ this.removeButton.UseVisualStyleBackColor = true;
+ this.removeButton.Click += new System.EventHandler(this.removeButton_Click);
+ //
+ // addButton
+ //
+ this.addButton.Image = HeuristicLab.Common.Resources.VSImageLibrary.Add;
+ this.addButton.Location = new System.Drawing.Point(3, 3);
+ this.addButton.Name = "addButton";
+ this.addButton.Size = new System.Drawing.Size(24, 24);
+ this.addButton.TabIndex = 5;
+ this.toolTip.SetToolTip(this.addButton, "Add Symbol");
+ this.addButton.UseVisualStyleBackColor = true;
+ this.addButton.Click += new System.EventHandler(this.addButton_Click);
+ //
+ // symbolsTreeView
+ //
+ this.symbolsTreeView.AllowDrop = true;
+ this.symbolsTreeView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.symbolsTreeView.CheckBoxes = true;
+ this.symbolsTreeView.HideSelection = false;
+ this.symbolsTreeView.ImageIndex = 0;
+ this.symbolsTreeView.ImageList = this.imageList;
+ this.symbolsTreeView.Location = new System.Drawing.Point(3, 28);
+ this.symbolsTreeView.Name = "symbolsTreeView";
+ this.symbolsTreeView.SelectedImageIndex = 0;
+ this.symbolsTreeView.Size = new System.Drawing.Size(185, 299);
+ this.symbolsTreeView.TabIndex = 0;
+ this.symbolsTreeView.AfterCheck += new System.Windows.Forms.TreeViewEventHandler(this.symbolsTreeView_AfterCheck);
+ this.symbolsTreeView.BeforeCheck += new System.Windows.Forms.TreeViewCancelEventHandler(symbolsTreeView_BeforeCheck);
+ this.symbolsTreeView.ItemDrag += new System.Windows.Forms.ItemDragEventHandler(this.symbolsTreeView_ItemDrag);
+ this.symbolsTreeView.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.symbolsTreeView_AfterSelect);
+ this.symbolsTreeView.DragDrop += new System.Windows.Forms.DragEventHandler(this.symbolsTreeView_DragDrop);
+ this.symbolsTreeView.DragEnter += new System.Windows.Forms.DragEventHandler(this.symbolsTreeView_DragEnter);
+ this.symbolsTreeView.DragOver += new System.Windows.Forms.DragEventHandler(this.symbolsTreeView_DragOver);
+ this.symbolsTreeView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.symbolsTreeView_KeyDown);
+ this.symbolsTreeView.MouseDown += new System.Windows.Forms.MouseEventHandler(this.symbolsTreeView_MouseDown);
+ this.symbolsTreeView.NodeMouseDoubleClick += new System.Windows.Forms.TreeNodeMouseClickEventHandler(symbolsTreeView_NodeMouseDoubleClick);
+ //
+ // imageList
+ //
+ this.imageList.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit;
+ this.imageList.ImageSize = new System.Drawing.Size(16, 16);
+ this.imageList.TransparentColor = System.Drawing.Color.Transparent;
+ //
+ // splitContainer2
+ //
+ this.splitContainer2.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.splitContainer2.Location = new System.Drawing.Point(0, 0);
+ this.splitContainer2.Name = "splitContainer2";
+ this.splitContainer2.Orientation = System.Windows.Forms.Orientation.Horizontal;
+ //
+ // splitContainer2.Panel1
+ //
+ this.splitContainer2.Panel1.Controls.Add(this.allowedChildSymbolsControl);
+ //
+ // splitContainer2.Panel2
+ //
+ this.splitContainer2.Panel2.Controls.Add(this.symbolDetailsGroupBox);
+ this.splitContainer2.Size = new System.Drawing.Size(568, 359);
+ this.splitContainer2.SplitterDistance = 165;
+ this.splitContainer2.TabIndex = 0;
+ //
+ // allowedChildSymbolsControl
+ //
+ this.allowedChildSymbolsControl.AllowDrop = true;
+ this.allowedChildSymbolsControl.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.allowedChildSymbolsControl.Grammar = null;
+ this.allowedChildSymbolsControl.Location = new System.Drawing.Point(0, 0);
+ this.allowedChildSymbolsControl.Name = "allowedChildSymbolsControl";
+ this.allowedChildSymbolsControl.Size = new System.Drawing.Size(568, 165);
+ this.allowedChildSymbolsControl.Symbol = null;
+ this.allowedChildSymbolsControl.TabIndex = 0;
+ //
+ // symbolDetailsGroupBox
+ //
+ this.symbolDetailsGroupBox.Controls.Add(this.symbolDetailsViewHost);
+ this.symbolDetailsGroupBox.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.symbolDetailsGroupBox.Location = new System.Drawing.Point(0, 0);
+ this.symbolDetailsGroupBox.Name = "symbolDetailsGroupBox";
+ this.symbolDetailsGroupBox.Size = new System.Drawing.Size(568, 190);
+ this.symbolDetailsGroupBox.TabIndex = 1;
+ this.symbolDetailsGroupBox.TabStop = false;
+ this.symbolDetailsGroupBox.Text = "Symbol Details";
+ //
+ // symbolDetailsViewHost
+ //
+ this.symbolDetailsViewHost.Caption = "View";
+ this.symbolDetailsViewHost.Content = null;
+ this.symbolDetailsViewHost.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.symbolDetailsViewHost.Enabled = false;
+ this.symbolDetailsViewHost.Location = new System.Drawing.Point(3, 16);
+ this.symbolDetailsViewHost.Name = "symbolDetailsViewHost";
+ this.symbolDetailsViewHost.ReadOnly = false;
+ this.symbolDetailsViewHost.Size = new System.Drawing.Size(562, 171);
+ this.symbolDetailsViewHost.TabIndex = 1;
+ this.symbolDetailsViewHost.ViewsLabelVisible = true;
+ this.symbolDetailsViewHost.ViewType = null;
+ //
+ // showSampleTreeButton
+ //
+ this.showSampleTreeButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.showSampleTreeButton.Location = new System.Drawing.Point(3, 333);
+ this.showSampleTreeButton.Name = "showSampleTreeButton";
+ this.showSampleTreeButton.Size = new System.Drawing.Size(185, 23);
+ this.showSampleTreeButton.TabIndex = 9;
+ this.showSampleTreeButton.Text = "Show Sample Tree";
+ this.showSampleTreeButton.UseVisualStyleBackColor = true;
+ this.showSampleTreeButton.Click += new System.EventHandler(this.showSampleTreeButton_Click);
+ //
+ // SymbolicExpressionGrammarEditorView
+ //
+ this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
+ this.Controls.Add(this.grpSymbols);
+ this.Name = "SymbolicExpressionGrammarEditorView";
+ this.Size = new System.Drawing.Size(769, 404);
+ this.Controls.SetChildIndex(this.grpSymbols, 0);
+ this.Controls.SetChildIndex(this.nameLabel, 0);
+ this.Controls.SetChildIndex(this.nameTextBox, 0);
+ this.Controls.SetChildIndex(this.infoLabel, 0);
+ ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).EndInit();
+ this.grpSymbols.ResumeLayout(false);
+ this.splitContainer1.Panel1.ResumeLayout(false);
+ this.splitContainer1.Panel2.ResumeLayout(false);
+ ((System.ComponentModel.ISupportInitialize)(this.splitContainer1)).EndInit();
+ this.splitContainer1.ResumeLayout(false);
+ this.splitContainer2.Panel1.ResumeLayout(false);
+ this.splitContainer2.Panel2.ResumeLayout(false);
+ ((System.ComponentModel.ISupportInitialize)(this.splitContainer2)).EndInit();
+ this.splitContainer2.ResumeLayout(false);
+ this.symbolDetailsGroupBox.ResumeLayout(false);
+ this.ResumeLayout(false);
+ this.PerformLayout();
+
+ }
+ #endregion
+
+ private System.Windows.Forms.GroupBox grpSymbols;
+ private System.Windows.Forms.SplitContainer splitContainer1;
+ private CheckBoxTreeView symbolsTreeView;
+ private System.Windows.Forms.SplitContainer splitContainer2;
+ private System.Windows.Forms.ImageList imageList;
+ protected System.Windows.Forms.CheckBox showDetailsCheckBox;
+ protected System.Windows.Forms.Button removeButton;
+ protected System.Windows.Forms.Button addButton;
+ private System.Windows.Forms.GroupBox symbolDetailsGroupBox;
+ private MainForm.WindowsForms.ViewHost symbolDetailsViewHost;
+ protected System.Windows.Forms.Button copyButton;
+ private SymbolicExpressionGrammarAllowedChildSymbolsControl allowedChildSymbolsControl;
+ private System.Windows.Forms.Button showSampleTreeButton;
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarEditorView.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarEditorView.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarEditorView.cs (revision 9852)
@@ -0,0 +1,450 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Drawing;
+using System.Linq;
+using System.Windows.Forms;
+using HeuristicLab.Common;
+using HeuristicLab.Core.Views;
+using HeuristicLab.MainForm;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ [View("Symbolic Expression Grammar Editor")]
+ [Content(typeof(ISymbolicExpressionGrammar), true)]
+ public partial class SymbolicExpressionGrammarEditorView : NamedItemView {
+ public SymbolicExpressionGrammarEditorView() {
+ InitializeComponent();
+ }
+
+ public override bool ReadOnly {
+ get {
+ if ((Content != null) && Content.ReadOnly) return true;
+ return base.ReadOnly;
+ }
+ set {
+ if ((Content != null) && Content.ReadOnly) base.ReadOnly = true;
+ else base.ReadOnly = value;
+ }
+ }
+
+ public new ISymbolicExpressionGrammar Content {
+ get { return (ISymbolicExpressionGrammar)base.Content; }
+ set { base.Content = value; }
+ }
+
+ private Color treeViewBackColor = Color.Empty;
+ protected override void SetEnabledStateOfControls() {
+ base.SetEnabledStateOfControls();
+ if (Content == null || Content.ReadOnly || ReadOnly || Locked) {
+ addButton.Enabled = false;
+ removeButton.Enabled = false;
+ copyButton.Enabled = false;
+ treeViewBackColor = symbolsTreeView.BackColor;
+ symbolsTreeView.BackColor = Color.FromArgb(255, 240, 240, 240);
+ } else {
+ addButton.Enabled = true;
+ if (symbolsTreeView.SelectedNode != null && !(symbolsTreeView.SelectedNode.Tag is IReadOnlySymbol)) {
+ removeButton.Enabled = true;
+ copyButton.Enabled = true;
+ }
+ treeViewBackColor = Color.Empty;
+ symbolsTreeView.BackColor = treeViewBackColor;
+ }
+ }
+
+ protected override void OnContentChanged() {
+ base.OnContentChanged();
+ if (Content != null) {
+ symbolsTreeView.Nodes.Clear();
+ UpdateSymbolsTreeView();
+
+ symbolsTreeView.CollapseAll();
+ foreach (var node in IterateTreeNodes())
+ if (node.Checked) node.Expand();
+
+ allowedChildSymbolsControl.Grammar = Content;
+ allowedChildSymbolsControl.Symbol = null;
+ symbolDetailsViewHost.Content = null;
+ } else {
+ symbolsTreeView.Nodes.Clear();
+ allowedChildSymbolsControl.Grammar = null;
+ symbolDetailsViewHost.Content = null;
+ }
+ }
+
+ #region events
+ protected override void RegisterContentEvents() {
+ base.RegisterContentEvents();
+ Content.ReadOnlyChanged += new System.EventHandler(Content_ReadOnlyChanged);
+ Content.Changed += new System.EventHandler(Content_Changed);
+ }
+ protected override void DeregisterContentEvents() {
+ Content.ReadOnlyChanged -= new System.EventHandler(Content_ReadOnlyChanged);
+ Content.Changed -= new System.EventHandler(Content_Changed);
+ base.DeregisterContentEvents();
+ }
+
+ private void Content_ReadOnlyChanged(object sender, EventArgs e) {
+ ReadOnly = Content.ReadOnly;
+ }
+
+ private void Content_Changed(object sender, EventArgs e) {
+ ISymbol symbol = null;
+ if (symbolsTreeView.SelectedNode != null)
+ symbol = (ISymbol)symbolsTreeView.SelectedNode.Tag;
+
+ allowedChildSymbolsControl.Grammar = Content;
+
+ UpdateSymbolsTreeView();
+ if (symbol != null && Content.ContainsSymbol(symbol)) {
+ symbolsTreeView.SelectedNode = IterateTreeNodes().Where(n => n.Tag == symbol).ToList().FirstOrDefault();
+ UpdateSymbolDetailsViews();
+ }
+ }
+ #endregion
+
+ private void UpdateSymbolsTreeView() {
+ var symbols = Content.Symbols.ToList();
+ foreach (var treeNode in IterateTreeNodes().ToList()) {
+ var symbol = treeNode.Tag as ISymbol;
+ if (!symbols.Contains(symbol))
+ treeNode.Remove();
+ }
+
+ var groupSymbols = symbols.OfType().ToList();
+ var topLevelSymbols = Content.Symbols.Where(s => !groupSymbols.Any(g => g.Symbols.Contains(s)));
+ UpdateChildTreeNodes(symbolsTreeView.Nodes, topLevelSymbols);
+
+ RebuildImageList();
+ }
+
+ private void UpdateChildTreeNodes(TreeNodeCollection collection, IEnumerable symbols) {
+ foreach (ISymbol symbol in symbols) {
+ if (symbol is ProgramRootSymbol) continue;
+ if (symbol is Defun) continue;
+
+ TreeNode node = collection.Cast().Where(n => n.Tag == symbol).FirstOrDefault();
+ if (node == null) {
+ node = new TreeNode();
+ node.Tag = symbol;
+ collection.Add(node);
+ }
+ node.Checked = symbol.Enabled;
+ node.Text = symbol.Name;
+
+ var groupSymbol = symbol as GroupSymbol;
+ if (groupSymbol != null) UpdateChildTreeNodes(node.Nodes, groupSymbol.Symbols);
+ }
+ }
+
+ private void symbolsTreeView_AfterSelect(object sender, TreeViewEventArgs e) {
+ if (e.Action != TreeViewAction.Unknown) UpdateSymbolDetailsViews();
+ SetEnabledStateOfControls();
+ }
+
+ private void symbolsTreeView_BeforeCheck(object sender, TreeViewCancelEventArgs e) {
+ if (e.Action == TreeViewAction.Unknown) return;
+ e.Cancel = Content == null || Content.ReadOnly || ReadOnly || Locked;
+ }
+
+ private void symbolsTreeView_AfterCheck(object sender, TreeViewEventArgs e) {
+ if (e.Action == TreeViewAction.Unknown) return;
+ Content.StartGrammarManipulation();
+ allowedChildSymbolsControl.Symbol = null;
+ var symbol = (ISymbol)e.Node.Tag;
+ symbol.Enabled = e.Node.Checked;
+ foreach (var node in IterateTreeNodes())
+ node.Checked = ((ISymbol)node.Tag).Enabled;
+
+ Content.FinishedGrammarManipulation();
+ }
+
+ #region drag & drop operations
+ private void symbolsTreeView_ItemDrag(object sender, ItemDragEventArgs e) {
+ if (!Locked) {
+ var treeNode = e.Item as TreeNode;
+ var data = new DataObject();
+ data.SetData(HeuristicLab.Common.Constants.DragDropDataFormat, treeNode.Tag);
+ validDragOperation = true;
+ DoDragDrop(data, DragDropEffects.Copy | DragDropEffects.Move);
+ }
+ }
+
+
+ private bool validDragOperation;
+ private void symbolsTreeView_DragEnter(object sender, DragEventArgs e) {
+ validDragOperation = false;
+ if (Content == null || Content.ReadOnly || ReadOnly || Locked) return;
+
+ var data = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
+ var symbol = data as ISymbol;
+ if (symbol != null && !(symbol is IReadOnlySymbol)) validDragOperation = true;
+ }
+ private void symbolsTreeView_DragOver(object sender, DragEventArgs e) {
+ e.Effect = DragDropEffects.None;
+ if (validDragOperation) {
+ GroupSymbol groupSymbol = null;
+ Point mouse = symbolsTreeView.PointToClient(new Point(e.X, e.Y));
+ TreeNode node = symbolsTreeView.GetNodeAt(mouse);
+ if (node == null) return;
+ groupSymbol = node.Tag as GroupSymbol;
+ if (groupSymbol == null) return;
+ var symbol = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat);
+ if (symbol == groupSymbol) return;
+
+ if (e.AllowedEffect.HasFlag(DragDropEffects.Copy)) e.Effect = DragDropEffects.Copy;
+ }
+ }
+ private void symbolsTreeView_DragDrop(object sender, DragEventArgs e) {
+ var symbol = e.Data.GetData(HeuristicLab.Common.Constants.DragDropDataFormat) as ISymbol;
+
+ GroupSymbol groupSymbol = null;
+ Point mouse = symbolsTreeView.PointToClient(new Point(e.X, e.Y));
+ TreeNode node = symbolsTreeView.GetNodeAt(mouse);
+ if (node != null) groupSymbol = node.Tag as GroupSymbol;
+ if (node != null && groupSymbol == null) groupSymbol = node.Parent.Tag as GroupSymbol;
+
+ Content.StartGrammarManipulation();
+ Cloner cloner = new Cloner();
+ var clonedSymbol = cloner.Clone(symbol);
+ ChangeDuplicateSymbolNames(clonedSymbol);
+
+ if (groupSymbol != null) groupSymbol.SymbolsCollection.Add(clonedSymbol);
+ else Content.AddSymbol(clonedSymbol);
+
+ UpdateGrammerConstraintsForClonedSymbol(symbol, cloner);
+ Content.FinishedGrammarManipulation();
+ }
+ #endregion
+
+ private void symbolsTreeView_MouseDown(object sender, MouseEventArgs e) {
+ // enables deselection of treeNodes
+ Point coordinates = new Point(e.X, e.Y);
+ TreeNode node = symbolsTreeView.GetNodeAt(coordinates);
+ if (e.Button == MouseButtons.Left && node == null) {
+ symbolsTreeView.SelectedNode = null;
+ symbolDetailsViewHost.Content = null;
+ SetEnabledStateOfControls();
+ }
+ }
+
+ private void symbolsTreeView_NodeMouseDoubleClick(object sender, TreeNodeMouseClickEventArgs e) {
+ var symbol = e.Node.Tag as ISymbol;
+ if (symbol == null) return;
+ if (e.Button != MouseButtons.Left) return;
+ if (e.X < e.Node.Bounds.Left - symbolsTreeView.ImageList.Images[e.Node.ImageIndex].Width || e.X > e.Node.Bounds.Right) return;
+ MainFormManager.MainForm.ShowContent(symbol);
+ e.Node.Toggle();
+ }
+
+ private void symbolsTreeView_KeyDown(object sender, KeyEventArgs e) {
+ if (Content == null || Content.ReadOnly || ReadOnly || Locked) return;
+ if (symbolsTreeView.SelectedNode == null) return;
+ if (e.KeyCode != Keys.Delete) return;
+
+ var symbol = (ISymbol)symbolsTreeView.SelectedNode.Tag;
+ if (!(symbol is IReadOnlySymbol))
+ Content.RemoveSymbol(symbol);
+
+ SetEnabledStateOfControls();
+ UpdateSymbolDetailsViews();
+ RebuildImageList();
+ }
+
+ #region button events
+ private TypeSelectorDialog typeSelectorDialog;
+ private void addButton_Click(object sender, EventArgs e) {
+ if (typeSelectorDialog == null) {
+ typeSelectorDialog = new TypeSelectorDialog();
+ typeSelectorDialog.Caption = "Select Symbol";
+ typeSelectorDialog.TypeSelector.Caption = "Available Symbols";
+ typeSelectorDialog.TypeSelector.Configure(typeof(ISymbol), false, false, (t) => { return !typeof(IReadOnlySymbol).IsAssignableFrom(t); });
+ }
+ if (typeSelectorDialog.ShowDialog(this) == DialogResult.OK) {
+ try {
+ ISymbol symbol = (ISymbol)typeSelectorDialog.TypeSelector.CreateInstanceOfSelectedType();
+ ChangeDuplicateSymbolNames(symbol);
+ GroupSymbol groupSymbol = null;
+
+ TreeNode selectedNode = symbolsTreeView.SelectedNode;
+ if (selectedNode != null) {
+ groupSymbol = selectedNode.Tag as GroupSymbol;
+ if (groupSymbol == null && selectedNode.Parent != null) groupSymbol = selectedNode.Parent.Tag as GroupSymbol;
+ }
+ if (groupSymbol != null) groupSymbol.SymbolsCollection.Add(symbol);
+ else Content.AddSymbol(symbol);
+ }
+ catch (Exception ex) {
+ ErrorHandling.ShowErrorDialog(this, ex);
+ }
+ }
+ }
+
+ private void copyButton_Click(object sender, EventArgs e) {
+ var symbol = symbolsTreeView.SelectedNode.Tag as ISymbol;
+ if (symbol != null && !(symbol is IReadOnlySymbol)) {
+
+ Content.StartGrammarManipulation();
+ Cloner cloner = new Cloner();
+ var clonedSymbol = cloner.Clone(symbol);
+ ChangeDuplicateSymbolNames(clonedSymbol);
+
+ GroupSymbol groupSymbol = null;
+ if (symbolsTreeView.SelectedNode.Parent != null) groupSymbol = symbolsTreeView.SelectedNode.Parent.Tag as GroupSymbol;
+
+ if (groupSymbol != null) groupSymbol.SymbolsCollection.Add(clonedSymbol);
+ else Content.AddSymbol(clonedSymbol);
+
+ UpdateGrammerConstraintsForClonedSymbol(symbol, cloner);
+ Content.FinishedGrammarManipulation();
+ }
+ }
+
+ private void removeButton_Click(object sender, EventArgs e) {
+ var symbol = symbolsTreeView.SelectedNode.Tag as ISymbol;
+ if (symbol != null && !(symbol is IReadOnlySymbol)) {
+ Content.RemoveSymbol(symbol);
+ }
+ }
+
+ private void showDetailsCheckBox_CheckedChanged(object sender, EventArgs e) {
+ splitContainer1.Panel2Collapsed = !showDetailsCheckBox.Checked;
+ }
+
+ private void showSampleTreeButton_Click(object sender, EventArgs e) {
+ SymbolicExpressionGrammarSampleExpressionTreeView view = new SymbolicExpressionGrammarSampleExpressionTreeView();
+ view.Content = Content;
+ view.Show();
+ }
+
+ #endregion
+
+ #region helpers
+ private void UpdateGrammerConstraintsForClonedSymbol(ISymbol symbol, Cloner cloner) {
+ foreach (var s in symbol.Flatten().Where(x => !(x is GroupSymbol))) {
+ if (!cloner.ClonedObjectRegistered(s)) throw new InvalidOperationException();
+ var clone = cloner.Clone(s);
+ Content.SetSubtreeCount(clone, Content.GetMinimumSubtreeCount(s), Content.GetMaximumSubtreeCount(s));
+ foreach (var childSymbol in Content.GetAllowedChildSymbols(s)) {
+ var newChildSymbol = childSymbol;
+ if (cloner.ClonedObjectRegistered(childSymbol)) newChildSymbol = cloner.Clone(childSymbol);
+ Content.AddAllowedChildSymbol(clone, newChildSymbol);
+ }
+ for (int i = 0; i < Content.GetMaximumSubtreeCount(s); i++) {
+ foreach (var childSymbol in Content.GetAllowedChildSymbols(s, i)) {
+ var newChildSymbol = childSymbol;
+ if (cloner.ClonedObjectRegistered(childSymbol)) newChildSymbol = cloner.Clone(childSymbol);
+ Content.AddAllowedChildSymbol(clone, newChildSymbol, i);
+ }
+ }
+ }
+ }
+
+ private void ChangeDuplicateSymbolNames(ISymbol symbol) {
+ foreach (var s in symbol.Flatten()) {
+ var originalSymbolName = s.Name;
+ int i = 1;
+ while (Content.ContainsSymbol(s)) {
+ s.Name = originalSymbolName + i;
+ i++;
+ }
+ }
+ }
+
+ private void UpdateSymbolDetailsViews() {
+ if (symbolsTreeView.SelectedNode != null) {
+ symbolDetailsViewHost.Content = (ISymbol)symbolsTreeView.SelectedNode.Tag;
+ allowedChildSymbolsControl.Symbol = (ISymbol)symbolsTreeView.SelectedNode.Tag;
+ } else {
+ symbolDetailsViewHost.Content = null;
+ allowedChildSymbolsControl.Symbol = null;
+ }
+ }
+
+ private IEnumerable IterateTreeNodes(TreeNode node = null) {
+ TreeNodeCollection nodes;
+ if (node == null)
+ nodes = symbolsTreeView.Nodes;
+ else {
+ nodes = node.Nodes;
+ yield return node;
+ }
+
+ foreach (var childNode in nodes.OfType())
+ foreach (var n in IterateTreeNodes(childNode))
+ yield return n;
+ }
+
+ protected virtual void RebuildImageList() {
+ symbolsTreeView.ImageList.Images.Clear();
+ foreach (TreeNode treeNode in IterateTreeNodes()) {
+ var symbol = (ISymbol)treeNode.Tag;
+ symbolsTreeView.ImageList.Images.Add(symbol == null ? HeuristicLab.Common.Resources.VSImageLibrary.Nothing : symbol.ItemImage);
+ treeNode.ImageIndex = symbolsTreeView.ImageList.Images.Count - 1;
+ }
+ }
+
+ //necessary code to handle dock correctly regarding the expanded nodes
+ bool[] expandendedState;
+ protected override void OnHandleCreated(EventArgs e) {
+ base.OnHandleCreated(e);
+ if (expandendedState == null) return;
+ var nodes = IterateTreeNodes().ToList();
+ for (int i = 0; i < nodes.Count; i++)
+ if (expandendedState[i]) nodes[i].Expand();
+ }
+ protected override void OnHandleDestroyed(EventArgs e) {
+ base.OnHandleDestroyed(e);
+ var nodes = IterateTreeNodes().ToList();
+ expandendedState = new bool[nodes.Count];
+ for (int i = 0; i < nodes.Count; i++)
+ expandendedState[i] = nodes[i].IsExpanded;
+ }
+ #endregion
+ }
+
+ //this class is necessary to prevent double clicks which do not fire the checkbox checked event
+ //workaround taken from http://connect.microsoft.com/VisualStudio/feedback/details/374516/treeview-control-does-not-fire-events-reliably-when-double-clicking-on-checkbox
+ internal class CheckBoxTreeView : TreeView {
+ protected override void WndProc(ref Message m) {
+ // Suppress WM_LBUTTONDBLCLK
+ if (m.Msg == 0x203 && IsOnCheckBox(m)) { m.Result = IntPtr.Zero; } else base.WndProc(ref m);
+ }
+
+ private int GetXLParam(IntPtr lParam) {
+ return lParam.ToInt32() & 0xffff;
+ }
+
+ private int GetYLParam(IntPtr lParam) {
+ return lParam.ToInt32() >> 16;
+ }
+
+ private bool IsOnCheckBox(Message m) {
+ int x = GetXLParam(m.LParam);
+ int y = GetYLParam(m.LParam);
+ TreeNode node = this.GetNodeAt(x, y);
+ return ((x <= node.Bounds.Left - 20) && (x >= node.Bounds.Left - 32));
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarSampleExpressionTreeView.Designer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarSampleExpressionTreeView.Designer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarSampleExpressionTreeView.Designer.cs (revision 9852)
@@ -0,0 +1,215 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ partial class SymbolicExpressionGrammarSampleExpressionTreeView {
+ ///
+ /// Required designer variable.
+ ///
+ private System.ComponentModel.IContainer components = null;
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ /// true if managed resources should be disposed; otherwise, false.
+ protected override void Dispose(bool disposing) {
+ if (disposing && (components != null)) {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Component Designer generated code
+
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ private void InitializeComponent() {
+ this.sampleTreeGroupBox = new System.Windows.Forms.GroupBox();
+ this.sampleTreeView = new HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views.GraphicalSymbolicExpressionTreeView();
+ this.maxTreeLengthLabel = new System.Windows.Forms.Label();
+ this.maxTreeDepthLabel = new System.Windows.Forms.Label();
+ this.maxTreeLengthTextBox = new System.Windows.Forms.TextBox();
+ this.maxTreeDepthTextBox = new System.Windows.Forms.TextBox();
+ this.generateSampleTreeButton = new System.Windows.Forms.Button();
+ this.treeCreatorComboBox = new System.Windows.Forms.ComboBox();
+ this.treeCreatorLabel = new System.Windows.Forms.Label();
+ ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).BeginInit();
+ this.sampleTreeGroupBox.SuspendLayout();
+ this.SuspendLayout();
+ //
+ // nameTextBox
+ //
+ this.errorProvider.SetIconAlignment(this.nameTextBox, System.Windows.Forms.ErrorIconAlignment.MiddleLeft);
+ this.errorProvider.SetIconPadding(this.nameTextBox, 2);
+ this.nameTextBox.Location = new System.Drawing.Point(93, 0);
+ this.nameTextBox.Size = new System.Drawing.Size(319, 20);
+ //
+ // infoLabel
+ //
+ this.infoLabel.Location = new System.Drawing.Point(418, 3);
+ //
+ // sampleTreeGroupBox
+ //
+ this.sampleTreeGroupBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.sampleTreeGroupBox.Controls.Add(this.sampleTreeView);
+ this.sampleTreeGroupBox.Location = new System.Drawing.Point(3, 134);
+ this.sampleTreeGroupBox.Name = "sampleTreeGroupBox";
+ this.sampleTreeGroupBox.Size = new System.Drawing.Size(431, 265);
+ this.sampleTreeGroupBox.TabIndex = 3;
+ this.sampleTreeGroupBox.TabStop = false;
+ this.sampleTreeGroupBox.Text = "Sample SymbolicExpressionTree";
+ //
+ // sampleTreeView
+ //
+ this.sampleTreeView.AllowDrop = true;
+ this.sampleTreeView.Caption = "Graphical SymbolicExpressionTree View";
+ this.sampleTreeView.Content = null;
+ this.sampleTreeView.Dock = System.Windows.Forms.DockStyle.Fill;
+ this.sampleTreeView.Location = new System.Drawing.Point(3, 16);
+ this.sampleTreeView.Name = "sampleTreeView";
+ this.sampleTreeView.ReadOnly = false;
+ this.sampleTreeView.Size = new System.Drawing.Size(425, 246);
+ this.sampleTreeView.TabIndex = 0;
+ //
+ // maxTreeLengthLabel
+ //
+ this.maxTreeLengthLabel.AutoSize = true;
+ this.maxTreeLengthLabel.Location = new System.Drawing.Point(3, 29);
+ this.maxTreeLengthLabel.Name = "maxTreeLengthLabel";
+ this.maxTreeLengthLabel.Size = new System.Drawing.Size(88, 13);
+ this.maxTreeLengthLabel.TabIndex = 4;
+ this.maxTreeLengthLabel.Text = "Max TreeLength:";
+ //
+ // maxTreeDepthLabel
+ //
+ this.maxTreeDepthLabel.AutoSize = true;
+ this.maxTreeDepthLabel.Location = new System.Drawing.Point(3, 55);
+ this.maxTreeDepthLabel.Name = "maxTreeDepthLabel";
+ this.maxTreeDepthLabel.Size = new System.Drawing.Size(84, 13);
+ this.maxTreeDepthLabel.TabIndex = 5;
+ this.maxTreeDepthLabel.Text = "Max TreeDepth:";
+ //
+ // maxTreeLengthTextBox
+ //
+ this.maxTreeLengthTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.maxTreeLengthTextBox.Location = new System.Drawing.Point(93, 26);
+ this.maxTreeLengthTextBox.Name = "maxTreeLengthTextBox";
+ this.maxTreeLengthTextBox.Size = new System.Drawing.Size(341, 20);
+ this.maxTreeLengthTextBox.TabIndex = 6;
+ this.maxTreeLengthTextBox.Text = "50";
+ this.maxTreeLengthTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.maxTreeLengthTextBox_Validating);
+ this.maxTreeLengthTextBox.Validated += new System.EventHandler(this.maxTreeLengthTextBox_Validated);
+ //
+ // maxTreeDepthTextBox
+ //
+ this.maxTreeDepthTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.maxTreeDepthTextBox.Location = new System.Drawing.Point(93, 52);
+ this.maxTreeDepthTextBox.Name = "maxTreeDepthTextBox";
+ this.maxTreeDepthTextBox.Size = new System.Drawing.Size(341, 20);
+ this.maxTreeDepthTextBox.TabIndex = 7;
+ this.maxTreeDepthTextBox.Text = "10";
+ this.maxTreeDepthTextBox.Validating += new System.ComponentModel.CancelEventHandler(this.maxTreeDepthTextBox_Validating);
+ this.maxTreeDepthTextBox.Validated += new System.EventHandler(this.maxTreeDepthTextBox_Validated);
+ //
+ // generateSampleTreeButton
+ //
+ this.generateSampleTreeButton.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.generateSampleTreeButton.Location = new System.Drawing.Point(6, 105);
+ this.generateSampleTreeButton.Name = "generateSampleTreeButton";
+ this.generateSampleTreeButton.Size = new System.Drawing.Size(431, 23);
+ this.generateSampleTreeButton.TabIndex = 8;
+ this.generateSampleTreeButton.Text = "Generate SymbolicExpressionTree";
+ this.generateSampleTreeButton.UseVisualStyleBackColor = true;
+ this.generateSampleTreeButton.Click += new System.EventHandler(this.generateSampleTreeButton_Click);
+ //
+ // treeCreatorComboBox
+ //
+ this.treeCreatorComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.treeCreatorComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
+ this.treeCreatorComboBox.FormattingEnabled = true;
+ this.treeCreatorComboBox.Location = new System.Drawing.Point(93, 78);
+ this.treeCreatorComboBox.Name = "treeCreatorComboBox";
+ this.treeCreatorComboBox.Size = new System.Drawing.Size(341, 21);
+ this.treeCreatorComboBox.TabIndex = 9;
+ this.treeCreatorComboBox.SelectedIndexChanged += new System.EventHandler(this.treeCreatorComboBox_SelectedIndexChanged);
+ //
+ // treeCreatorLabel
+ //
+ this.treeCreatorLabel.AutoSize = true;
+ this.treeCreatorLabel.Location = new System.Drawing.Point(3, 81);
+ this.treeCreatorLabel.Name = "treeCreatorLabel";
+ this.treeCreatorLabel.Size = new System.Drawing.Size(69, 13);
+ this.treeCreatorLabel.TabIndex = 10;
+ this.treeCreatorLabel.Text = "Tree Creator:";
+ //
+ // SymbolicExpressionGrammarSampleExpressionTreeView
+ //
+ this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
+ this.Controls.Add(this.treeCreatorLabel);
+ this.Controls.Add(this.sampleTreeGroupBox);
+ this.Controls.Add(this.maxTreeDepthLabel);
+ this.Controls.Add(this.maxTreeLengthTextBox);
+ this.Controls.Add(this.treeCreatorComboBox);
+ this.Controls.Add(this.maxTreeLengthLabel);
+ this.Controls.Add(this.maxTreeDepthTextBox);
+ this.Controls.Add(this.generateSampleTreeButton);
+ this.Name = "SymbolicExpressionGrammarSampleExpressionTreeView";
+ this.Size = new System.Drawing.Size(437, 402);
+ this.Controls.SetChildIndex(this.generateSampleTreeButton, 0);
+ this.Controls.SetChildIndex(this.maxTreeDepthTextBox, 0);
+ this.Controls.SetChildIndex(this.maxTreeLengthLabel, 0);
+ this.Controls.SetChildIndex(this.treeCreatorComboBox, 0);
+ this.Controls.SetChildIndex(this.maxTreeLengthTextBox, 0);
+ this.Controls.SetChildIndex(this.maxTreeDepthLabel, 0);
+ this.Controls.SetChildIndex(this.sampleTreeGroupBox, 0);
+ this.Controls.SetChildIndex(this.treeCreatorLabel, 0);
+ this.Controls.SetChildIndex(this.nameTextBox, 0);
+ this.Controls.SetChildIndex(this.infoLabel, 0);
+ this.Controls.SetChildIndex(this.nameLabel, 0);
+ ((System.ComponentModel.ISupportInitialize)(this.errorProvider)).EndInit();
+ this.sampleTreeGroupBox.ResumeLayout(false);
+ this.ResumeLayout(false);
+ this.PerformLayout();
+
+ }
+
+ #endregion
+
+ private System.Windows.Forms.GroupBox sampleTreeGroupBox;
+ private System.Windows.Forms.Label maxTreeLengthLabel;
+ private System.Windows.Forms.Label maxTreeDepthLabel;
+ private System.Windows.Forms.TextBox maxTreeLengthTextBox;
+ private System.Windows.Forms.TextBox maxTreeDepthTextBox;
+ private System.Windows.Forms.Button generateSampleTreeButton;
+ private GraphicalSymbolicExpressionTreeView sampleTreeView;
+ private System.Windows.Forms.ComboBox treeCreatorComboBox;
+ private System.Windows.Forms.Label treeCreatorLabel;
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarSampleExpressionTreeView.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarSampleExpressionTreeView.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarSampleExpressionTreeView.cs (revision 9852)
@@ -0,0 +1,158 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.ComponentModel;
+using System.Linq;
+using System.Windows.Forms;
+using HeuristicLab.Core;
+using HeuristicLab.Core.Views;
+using HeuristicLab.MainForm;
+using HeuristicLab.PluginInfrastructure;
+using HeuristicLab.Random;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ [View("Symbolic Expression Grammar Sample Tree")]
+ public partial class SymbolicExpressionGrammarSampleExpressionTreeView : NamedItemView {
+ private IRandom random;
+ public SymbolicExpressionGrammarSampleExpressionTreeView() {
+ InitializeComponent();
+ random = new MersenneTwister();
+ maxSampleTreeLength = int.Parse(maxTreeLengthTextBox.Text);
+ maxSampleTreeDepth = int.Parse(maxTreeDepthTextBox.Text);
+ foreach (var treeCreator in ApplicationManager.Manager.GetInstances()) {
+ treeCreatorComboBox.Items.Add(treeCreator);
+ }
+ treeCreatorComboBox.SelectedIndex = 0;
+ }
+
+ private int maxSampleTreeLength;
+ public int MaxSampleTreeLength {
+ get { return maxSampleTreeLength; }
+ set {
+ if (maxSampleTreeLength != value) {
+ maxSampleTreeLength = value;
+ UpdateSampleTreeView();
+ }
+ }
+ }
+
+ private int maxSampleTreeDepth;
+ public int MaxSampleTreeDepth {
+ get { return maxSampleTreeDepth; }
+ set {
+ if (maxSampleTreeDepth != value) {
+ maxSampleTreeDepth = value;
+ UpdateSampleTreeView();
+ }
+ }
+ }
+
+ public new ISymbolicExpressionGrammar Content {
+ get { return (ISymbolicExpressionGrammar)base.Content; }
+ set { base.Content = value; }
+ }
+
+ protected override void SetEnabledStateOfControls() {
+ base.SetEnabledStateOfControls();
+ maxTreeLengthTextBox.Enabled = Content != null;
+ maxTreeDepthTextBox.Enabled = Content != null;
+ generateSampleTreeButton.Enabled = Content != null;
+ }
+
+ protected override void RegisterContentEvents() {
+ base.RegisterContentEvents();
+ Content.Changed += new EventHandler(Content_Changed);
+ }
+
+ protected override void DeregisterContentEvents() {
+ Content.Changed -= new EventHandler(Content_Changed);
+ base.DeregisterContentEvents();
+ }
+
+ protected override void OnContentChanged() {
+ base.OnContentChanged();
+ if (Content == null) sampleTreeView.Content = null;
+ else UpdateSampleTreeView();
+ }
+
+ private void Content_Changed(object sender, System.EventArgs e) {
+ UpdateSampleTreeView();
+ }
+
+ private void UpdateSampleTreeView() {
+ try {
+ ISymbolicExpressionTreeCreator creator = (ISymbolicExpressionTreeCreator)treeCreatorComboBox.SelectedItem;
+ ISymbolicExpressionTree tree = creator.CreateTree(random, Content, MaxSampleTreeLength, MaxSampleTreeDepth);
+ foreach (var node in tree.Root.IterateNodesPrefix().OfType())
+ node.SetGrammar(null);
+ sampleTreeView.Content = tree;
+ }
+ catch (Exception ex) {
+ sampleTreeView.Content = null;
+ ErrorHandling.ShowErrorDialog(ex);
+ }
+ }
+
+ #region control events
+ private void generateSampleTreeButton_Click(object sender, EventArgs e) {
+ UpdateSampleTreeView();
+ }
+
+ private void maxTreeLengthTextBox_Validating(object sender, CancelEventArgs e) {
+ int maxTreeLength;
+ if (int.TryParse(maxTreeLengthTextBox.Text, out maxTreeLength) && maxTreeLength > 3) {
+ errorProvider.SetError(maxTreeLengthTextBox, string.Empty);
+ e.Cancel = false;
+ } else {
+ errorProvider.SetError(maxTreeLengthTextBox, "Invalid value: maximum tree length must be larger than 3.");
+ e.Cancel = true;
+ }
+ }
+ private void maxTreeLengthTextBox_Validated(object sender, EventArgs e) {
+ int maxTreeLength;
+ if (int.TryParse(maxTreeLengthTextBox.Text, out maxTreeLength) && maxTreeLength > 3) {
+ MaxSampleTreeLength = maxTreeLength;
+ }
+ }
+
+ private void maxTreeDepthTextBox_Validating(object sender, CancelEventArgs e) {
+ int maxTreeDepth;
+ if (int.TryParse(maxTreeDepthTextBox.Text, out maxTreeDepth) && maxTreeDepth > 3) {
+ errorProvider.SetError(maxTreeDepthTextBox, string.Empty);
+ e.Cancel = false;
+ } else {
+ errorProvider.SetError(maxTreeDepthTextBox, "Invalid value: maximum tree depth must be larger than 3.");
+ e.Cancel = true;
+ }
+ }
+ private void maxTreeDepthTextBox_Validated(object sender, EventArgs e) {
+ int maxTreeDepth;
+ if (int.TryParse(maxTreeDepthTextBox.Text, out maxTreeDepth) && maxTreeDepth > 3) {
+ MaxSampleTreeDepth = maxTreeDepth;
+ }
+ }
+ #endregion
+
+ private void treeCreatorComboBox_SelectedIndexChanged(object sender, EventArgs e) {
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarView.Designer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarView.Designer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarView.Designer.cs (revision 9852)
@@ -0,0 +1,72 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ partial class SymbolicExpressionGrammarView {
+ ///
+ /// Required designer variable.
+ ///
+ private System.ComponentModel.IContainer components = null;
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ /// true if managed resources should be disposed; otherwise, false.
+ protected override void Dispose(bool disposing) {
+ if (disposing && (components != null)) {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Component Designer generated code
+
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ private void InitializeComponent() {
+ this.checkedItemListView = new HeuristicLab.Core.Views.CheckedItemListView();
+ this.SuspendLayout();
+ this.checkedItemListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.checkedItemListView.Location = new System.Drawing.Point(0, 52);
+ this.checkedItemListView.Name = "itemListView";
+ this.checkedItemListView.Size = new System.Drawing.Size(351, 190);
+ this.checkedItemListView.TabIndex = 0;
+ //
+ // DefaultSymbolicExpressionGrammarView
+ //
+ this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
+ this.Controls.Add(this.checkedItemListView);
+ this.Name = "DefaultSymbolicExpressionGrammarView";
+ this.Size = new System.Drawing.Size(351, 245);
+ this.ResumeLayout(false);
+
+ }
+
+ #endregion
+
+ protected HeuristicLab.Core.Views.CheckedItemListView checkedItemListView;
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarView.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarView.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionGrammarView.cs (revision 9852)
@@ -0,0 +1,118 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Windows.Forms;
+using HeuristicLab.Collections;
+using HeuristicLab.Core;
+using HeuristicLab.Core.Views;
+using HeuristicLab.MainForm;
+using HeuristicLab.MainForm.WindowsForms;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ [View("Symbolic Expression Grammar View")]
+ [Content(typeof(ISymbolicExpressionGrammar), false)]
+ public partial class SymbolicExpressionGrammarView : NamedItemView {
+ private CheckedItemList symbols;
+
+ public new ISymbolicExpressionGrammar Content {
+ get { return (ISymbolicExpressionGrammar)base.Content; }
+ set { base.Content = value; }
+ }
+
+ public override bool ReadOnly {
+ get {
+ if ((Content != null) && Content.ReadOnly) return true;
+ return base.ReadOnly;
+ }
+ set {
+ if ((Content != null) && Content.ReadOnly) base.ReadOnly = true;
+ else base.ReadOnly = value;
+ }
+ }
+
+ public SymbolicExpressionGrammarView() {
+ InitializeComponent();
+ symbols = new CheckedItemList();
+ symbols.CheckedItemsChanged += new CollectionItemsChangedEventHandler>(symbols_CheckedItemsChanged);
+ }
+
+ protected override void RegisterContentEvents() {
+ base.RegisterContentEvents();
+ Content.ReadOnlyChanged += new EventHandler(Content_ReadOnlyChanged);
+ }
+ protected override void DeregisterContentEvents() {
+ base.DeregisterContentEvents();
+ Content.ReadOnlyChanged -= new EventHandler(Content_ReadOnlyChanged);
+ }
+
+ protected override void OnContentChanged() {
+ base.OnContentChanged();
+ UpdateControl();
+ }
+
+ private void Content_ReadOnlyChanged(object sender, EventArgs e) {
+ ReadOnly = Content.ReadOnly;
+ }
+
+ #region content event handlers
+ private void Content_Changed(object sender, EventArgs e) {
+ UpdateControl();
+ }
+ #endregion
+
+ #region helpers
+ private void UpdateControl() {
+ if (Content == null) {
+ ClearSymbols();
+ checkedItemListView.Content = symbols.AsReadOnly();
+ } else {
+ ClearSymbols();
+ foreach (ISymbol symbol in Content.Symbols) {
+ if (!(symbol is IReadOnlySymbol)) {
+ symbol.Changed += new EventHandler(symbol_Changed);
+ symbols.Add(symbol, symbol.Enabled);
+ }
+ }
+ checkedItemListView.Content = symbols.AsReadOnly();
+ }
+ SetEnabledStateOfControls();
+ }
+
+
+ private void symbol_Changed(object sender, EventArgs e) {
+ ISymbol symbol = (ISymbol)sender;
+ symbols.SetItemCheckedState(symbol, symbol.Enabled);
+ }
+
+ private void symbols_CheckedItemsChanged(object sender, CollectionItemsChangedEventArgs> e) {
+ ICheckedItemList checkedItemList = (ICheckedItemList)sender;
+ foreach (var indexedItem in e.Items)
+ indexedItem.Value.Enabled = checkedItemList.ItemChecked(indexedItem.Value);
+ }
+ private void ClearSymbols() {
+ foreach (Symbol s in symbols)
+ s.Changed -= new EventHandler(symbol_Changed);
+ symbols.Clear();
+ }
+ #endregion
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionTreeChart.Designer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionTreeChart.Designer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionTreeChart.Designer.cs (revision 9852)
@@ -0,0 +1,106 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ public partial class SymbolicExpressionTreeChart {
+ ///
+ /// Required designer variable.
+ ///
+ private System.ComponentModel.IContainer components = null;
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ /// true if managed resources should be disposed; otherwise, false.
+ protected override void Dispose(bool disposing) {
+ if (disposing && (components != null)) {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Component Designer generated code
+
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ private void InitializeComponent() {
+ this.components = new System.ComponentModel.Container();
+ this.toolTip = new System.Windows.Forms.ToolTip(this.components);
+ this.contextMenuStrip = new System.Windows.Forms.ContextMenuStrip(this.components);
+ this.saveImageToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.saveFileDialog = new System.Windows.Forms.SaveFileDialog();
+ this.exportLatexToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
+ this.contextMenuStrip.SuspendLayout();
+ this.SuspendLayout();
+ //
+ // contextMenuStrip
+ //
+ this.contextMenuStrip.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
+ this.saveImageToolStripMenuItem,
+ this.exportLatexToolStripMenuItem});
+ this.contextMenuStrip.Name = "contextMenuStrip";
+ this.contextMenuStrip.Size = new System.Drawing.Size(161, 70);
+ //
+ // saveImageToolStripMenuItem
+ //
+ this.saveImageToolStripMenuItem.Name = "saveImageToolStripMenuItem";
+ this.saveImageToolStripMenuItem.Size = new System.Drawing.Size(160, 22);
+ this.saveImageToolStripMenuItem.Text = "Save Image";
+ this.saveImageToolStripMenuItem.Click += new System.EventHandler(this.saveImageToolStripMenuItem_Click);
+ //
+ // saveFileDialog
+ //
+ this.saveFileDialog.Filter = "Bitmap (*.bmp)|*.bmp|EMF (*.emf)|*.emf";
+ //
+ // exportLatexToolStripMenuItem
+ //
+ this.exportLatexToolStripMenuItem.Name = "exportLatexToolStripMenuItem";
+ this.exportLatexToolStripMenuItem.Size = new System.Drawing.Size(160, 22);
+ this.exportLatexToolStripMenuItem.Text = "Export Pgf/Latex";
+ this.exportLatexToolStripMenuItem.Click += new System.EventHandler(this.exportLatexToolStripMenuItem_Click);
+ //
+ // SymbolicExpressionTreeChart
+ //
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
+ this.ContextMenuStrip = this.contextMenuStrip;
+ this.DoubleBuffered = true;
+ this.Name = "SymbolicExpressionTreeChart";
+ this.MouseClick += new System.Windows.Forms.MouseEventHandler(this.SymbolicExpressionTreeChart_MouseClick);
+ this.MouseDoubleClick += new System.Windows.Forms.MouseEventHandler(this.SymbolicExpressionTreeChart_MouseDoubleClick);
+ this.MouseDown += new System.Windows.Forms.MouseEventHandler(this.SymbolicExpressionTreeChart_MouseDown);
+ this.MouseMove += new System.Windows.Forms.MouseEventHandler(this.SymbolicExpressionTreeChart_MouseMove);
+ this.MouseUp += new System.Windows.Forms.MouseEventHandler(this.SymbolicExpressionTreeChart_MouseUp);
+ this.contextMenuStrip.ResumeLayout(false);
+ this.ResumeLayout(false);
+
+ }
+
+ #endregion
+
+ protected System.Windows.Forms.ToolTip toolTip;
+ protected System.Windows.Forms.ContextMenuStrip contextMenuStrip;
+ protected System.Windows.Forms.ToolStripMenuItem saveImageToolStripMenuItem;
+ protected System.Windows.Forms.SaveFileDialog saveFileDialog;
+ private System.Windows.Forms.ToolStripMenuItem exportLatexToolStripMenuItem;
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionTreeChart.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionTreeChart.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionTreeChart.cs (revision 9852)
@@ -0,0 +1,379 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Drawing;
+using System.Drawing.Imaging;
+using System.IO;
+using System.Windows.Forms;
+using Point = System.Drawing.Point;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ public partial class SymbolicExpressionTreeChart : UserControl {
+ private Image image;
+ private StringFormat stringFormat;
+ private Dictionary visualTreeNodes;
+ private Dictionary, VisualSymbolicExpressionTreeNodeConnection> visualLines;
+ private readonly ReingoldTilfordLayoutEngine tl = new ReingoldTilfordLayoutEngine { Distance = 5 };
+
+
+ public SymbolicExpressionTreeChart() {
+ InitializeComponent();
+ this.image = new Bitmap(Width, Height);
+ this.stringFormat = new StringFormat { Alignment = StringAlignment.Center, LineAlignment = StringAlignment.Center };
+ this.spacing = 5;
+ this.lineColor = Color.Black;
+ this.backgroundColor = Color.White;
+ this.textFont = new Font("Times New Roman", 8);
+ }
+
+ public SymbolicExpressionTreeChart(ISymbolicExpressionTree tree)
+ : this() {
+ this.Tree = tree;
+ }
+
+ #region Public properties
+ private int spacing;
+ public int Spacing {
+ get { return this.spacing; }
+ set {
+ this.spacing = value;
+ this.Repaint();
+ }
+ }
+
+ private Color lineColor;
+ public Color LineColor {
+ get { return this.lineColor; }
+ set {
+ this.lineColor = value;
+ this.Repaint();
+ }
+ }
+
+ private Color backgroundColor;
+ public Color BackgroundColor {
+ get { return this.backgroundColor; }
+ set {
+ this.backgroundColor = value;
+ this.Repaint();
+ }
+ }
+
+ private Font textFont;
+ public Font TextFont {
+ get { return this.textFont; }
+ set {
+ this.textFont = value;
+ this.Repaint();
+ }
+ }
+
+ private ISymbolicExpressionTree tree;
+ public ISymbolicExpressionTree Tree {
+ get { return this.tree; }
+ set {
+ tree = value;
+ visualTreeNodes = new Dictionary();
+ visualLines = new Dictionary, VisualSymbolicExpressionTreeNodeConnection>();
+ if (tree != null) {
+ foreach (ISymbolicExpressionTreeNode node in tree.IterateNodesPrefix()) {
+ visualTreeNodes[node] = new VisualSymbolicExpressionTreeNode(node);
+ if (node.Parent != null) visualLines[Tuple.Create(node.Parent, node)] = new VisualSymbolicExpressionTreeNodeConnection();
+ }
+ }
+ Repaint();
+ }
+ }
+
+ private bool suspendRepaint;
+ public bool SuspendRepaint {
+ get { return suspendRepaint; }
+ set { suspendRepaint = value; }
+ }
+ #endregion
+
+ protected override void OnPaint(PaintEventArgs e) {
+ e.Graphics.DrawImage(image, 0, 0);
+ base.OnPaint(e);
+ }
+ protected override void OnResize(EventArgs e) {
+ base.OnResize(e);
+ if (this.Width <= 1 || this.Height <= 1)
+ this.image = new Bitmap(1, 1);
+ else
+ this.image = new Bitmap(Width, Height);
+ this.Repaint();
+ }
+
+ public void Repaint() {
+ if (!suspendRepaint) {
+ this.GenerateImage();
+ this.Refresh();
+ }
+ }
+
+ public void RepaintNodes() {
+ if (!suspendRepaint) {
+ using (var graphics = Graphics.FromImage(image)) {
+ graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
+ graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
+ foreach (var visualNode in visualTreeNodes.Values) {
+ DrawTreeNode(graphics, visualNode);
+ }
+ }
+ this.Refresh();
+ }
+ }
+
+ public void RepaintNode(VisualSymbolicExpressionTreeNode visualNode) {
+ if (!suspendRepaint) {
+ using (var graphics = Graphics.FromImage(image)) {
+ graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
+ graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
+ DrawTreeNode(graphics, visualNode);
+ }
+ this.Refresh();
+ }
+ }
+
+ private void GenerateImage() {
+ using (Graphics graphics = Graphics.FromImage(image)) {
+ graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
+ graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
+ graphics.Clear(backgroundColor);
+ if (tree != null) {
+ DrawFunctionTree(tree, graphics, 70, 46, 20, 50);
+ }
+ }
+ }
+
+ public VisualSymbolicExpressionTreeNode GetVisualSymbolicExpressionTreeNode(ISymbolicExpressionTreeNode symbolicExpressionTreeNode) {
+ if (visualTreeNodes.ContainsKey(symbolicExpressionTreeNode))
+ return visualTreeNodes[symbolicExpressionTreeNode];
+ return null;
+ }
+
+ public VisualSymbolicExpressionTreeNodeConnection GetVisualSymbolicExpressionTreeNodeConnection(ISymbolicExpressionTreeNode parent, ISymbolicExpressionTreeNode child) {
+ if (child.Parent != parent) throw new ArgumentException();
+ var key = Tuple.Create(parent, child);
+ VisualSymbolicExpressionTreeNodeConnection connection = null;
+ visualLines.TryGetValue(key, out connection);
+ return connection;
+ }
+
+ #region events
+ public event MouseEventHandler SymbolicExpressionTreeNodeClicked;
+ protected virtual void OnSymbolicExpressionTreeNodeClicked(object sender, MouseEventArgs e) {
+ var clicked = SymbolicExpressionTreeNodeClicked;
+ if (clicked != null)
+ clicked(sender, e);
+ }
+
+ protected virtual void SymbolicExpressionTreeChart_MouseClick(object sender, MouseEventArgs e) {
+ VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
+ if (visualTreeNode != null) {
+ OnSymbolicExpressionTreeNodeClicked(visualTreeNode, e);
+ }
+ }
+
+ public event MouseEventHandler SymbolicExpressionTreeNodeDoubleClicked;
+ protected virtual void OnSymbolicExpressionTreeNodeDoubleClicked(object sender, MouseEventArgs e) {
+ var doubleClicked = SymbolicExpressionTreeNodeDoubleClicked;
+ if (doubleClicked != null)
+ doubleClicked(sender, e);
+ }
+
+ protected virtual void SymbolicExpressionTreeChart_MouseDoubleClick(object sender, MouseEventArgs e) {
+ VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
+ if (visualTreeNode != null)
+ OnSymbolicExpressionTreeNodeDoubleClicked(visualTreeNode, e);
+ }
+
+ public event ItemDragEventHandler SymbolicExpressionTreeNodeDrag;
+ protected virtual void OnSymbolicExpressionTreeNodeDragDrag(object sender, ItemDragEventArgs e) {
+ var dragged = SymbolicExpressionTreeNodeDrag;
+ if (dragged != null)
+ dragged(sender, e);
+ }
+
+ private VisualSymbolicExpressionTreeNode draggedSymbolicExpressionTree;
+ private MouseButtons dragButtons;
+ private void SymbolicExpressionTreeChart_MouseDown(object sender, MouseEventArgs e) {
+ this.dragButtons = e.Button;
+ this.draggedSymbolicExpressionTree = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
+ }
+ private void SymbolicExpressionTreeChart_MouseUp(object sender, MouseEventArgs e) {
+ this.draggedSymbolicExpressionTree = null;
+ this.dragButtons = MouseButtons.None;
+ }
+
+ private void SymbolicExpressionTreeChart_MouseMove(object sender, MouseEventArgs e) {
+ VisualSymbolicExpressionTreeNode visualTreeNode = FindVisualSymbolicExpressionTreeNodeAt(e.X, e.Y);
+ if (draggedSymbolicExpressionTree != null &&
+ draggedSymbolicExpressionTree != visualTreeNode) {
+ OnSymbolicExpressionTreeNodeDragDrag(draggedSymbolicExpressionTree, new ItemDragEventArgs(dragButtons, draggedSymbolicExpressionTree));
+ draggedSymbolicExpressionTree = null;
+ } else if (draggedSymbolicExpressionTree == null &&
+ visualTreeNode != null) {
+ string tooltipText = visualTreeNode.ToolTip;
+ if (this.toolTip.GetToolTip(this) != tooltipText)
+ this.toolTip.SetToolTip(this, tooltipText);
+
+ } else if (visualTreeNode == null)
+ this.toolTip.SetToolTip(this, "");
+ }
+
+ public VisualSymbolicExpressionTreeNode FindVisualSymbolicExpressionTreeNodeAt(int x, int y) {
+ foreach (var visualTreeNode in visualTreeNodes.Values) {
+ if (x >= visualTreeNode.X && x <= visualTreeNode.X + visualTreeNode.Width &&
+ y >= visualTreeNode.Y && y <= visualTreeNode.Y + visualTreeNode.Height)
+ return visualTreeNode;
+ }
+ return null;
+ }
+ #endregion
+
+ #region methods for painting the symbolic expression tree
+
+ private void DrawFunctionTree(ISymbolicExpressionTree tree, Graphics graphics, int preferredWidth, int preferredHeight, int minDistance, int maxDistance) {
+ tl.SymbolicExpressionTree = tree; // nodes layout is calculated in the SymbolicExpressionTreeSetter of the tl
+ var nodePositions = tl.GetNodeCoordinates();
+ var bounds = tl.Bounds();
+
+ double sx = Width / bounds.Width;
+ double sy = Height / bounds.Height;
+
+ double dx = tl.Distance * sx; // scaled horizontal distance
+ double dy = tl.Distance * sy; // scaled vertical distance
+
+ int maxWidth = (int)Math.Round(dx);
+ int maxHeight = (int)Math.Round(dy);
+
+ // instead of using the preferred with/height of each node inside the foreach loop below,
+ // we assume the same width/height for all nodes
+ int w = Math.Min(preferredWidth, maxWidth - minDistance / 2);
+ int h = Math.Min(preferredHeight, maxHeight - minDistance / 2);
+ // adjust scaling factor so that nodes will be at most maxDistance far from each other on the horizontal axis
+ double offset = 0;
+ if (maxDistance + w < maxWidth) {
+ sx *= (double)(maxDistance + w) / maxWidth;
+ offset = (Width - (sx * bounds.Width)) / 2;
+ }
+ foreach (var node in visualTreeNodes.Keys) {
+ var visualNode = visualTreeNodes[node];
+ var pos = nodePositions[node];
+ visualNode.Width = w;
+ visualNode.Height = h;
+ visualNode.X = (int)Math.Round(pos.X * sx + offset); ;
+ visualNode.Y = (int)Math.Round(pos.Y * sy);
+ DrawTreeNode(graphics, visualNode);
+ }
+ graphics.ResetClip(); // reset clip region
+ foreach (var visualNode in visualTreeNodes.Values) {
+ var node = visualNode.SymbolicExpressionTreeNode;
+ foreach (var subtree in node.Subtrees) {
+ var visualLine = GetVisualSymbolicExpressionTreeNodeConnection(node, subtree);
+ var visualSubtree = visualTreeNodes[subtree];
+ var origin = new Point(visualNode.X + visualNode.Width / 2, visualNode.Y + visualNode.Height);
+ var target = new Point(visualSubtree.X + visualSubtree.Width / 2, visualSubtree.Y);
+ using (var linePen = new Pen(visualLine.LineColor)) {
+ linePen.DashStyle = visualLine.DashStyle;
+ graphics.DrawLine(linePen, origin, target);
+ }
+ }
+ }
+ }
+
+ protected void DrawTreeNode(VisualSymbolicExpressionTreeNode visualTreeNode) {
+ using (var graphics = Graphics.FromImage(image)) {
+ graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.High;
+ graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
+ DrawTreeNode(graphics, visualTreeNode);
+ }
+ }
+
+ protected void DrawTreeNode(Graphics graphics, VisualSymbolicExpressionTreeNode visualTreeNode) {
+ graphics.Clip = new Region(new Rectangle(visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width + 1, visualTreeNode.Height + 1));
+ graphics.Clear(backgroundColor);
+ var node = visualTreeNode.SymbolicExpressionTreeNode;
+ using (var textBrush = new SolidBrush(visualTreeNode.TextColor))
+ using (var nodeLinePen = new Pen(visualTreeNode.LineColor))
+ using (var nodeFillBrush = new SolidBrush(visualTreeNode.FillColor)) {
+ //draw terminal node
+ if (node.SubtreeCount == 0) {
+ graphics.FillRectangle(nodeFillBrush, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
+ graphics.DrawRectangle(nodeLinePen, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
+ } else {
+ graphics.FillEllipse(nodeFillBrush, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
+ graphics.DrawEllipse(nodeLinePen, visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height);
+ }
+ //draw name of symbol
+ var text = node.ToString();
+ graphics.DrawString(text, textFont, textBrush, new RectangleF(visualTreeNode.X, visualTreeNode.Y, visualTreeNode.Width, visualTreeNode.Height), stringFormat);
+ }
+ }
+ #endregion
+ #region save image
+ private void saveImageToolStripMenuItem_Click(object sender, EventArgs e) {
+ if (saveFileDialog.ShowDialog() == DialogResult.OK) {
+ string filename = saveFileDialog.FileName.ToLower();
+ if (filename.EndsWith("bmp")) SaveImageAsBitmap(filename);
+ else if (filename.EndsWith("emf")) SaveImageAsEmf(filename);
+ else SaveImageAsBitmap(filename);
+ }
+ }
+
+ public void SaveImageAsBitmap(string filename) {
+ if (tree == null) return;
+ Image image = new Bitmap(Width, Height);
+ using (Graphics g = Graphics.FromImage(image)) {
+ int height = this.Height / tree.Depth;
+ DrawFunctionTree(tree, g, 0, 0, Width, height);
+ }
+ image.Save(filename);
+ }
+
+ public void SaveImageAsEmf(string filename) {
+ if (tree == null) return;
+ using (Graphics g = CreateGraphics()) {
+ using (Metafile file = new Metafile(filename, g.GetHdc())) {
+ using (Graphics emfFile = Graphics.FromImage(file)) {
+ int height = this.Height / tree.Depth;
+ DrawFunctionTree(tree, emfFile, 0, 0, Width, height);
+ }
+ }
+ g.ReleaseHdc();
+ }
+ }
+ #endregion
+ #region
+ private void exportLatexToolStripMenuItem_Click(object sender, EventArgs e) {
+ var dialog = new SaveFileDialog { Filter = "Tex (*.tex)|*.tex" };
+ if (dialog.ShowDialog() != DialogResult.OK) return;
+ string filename = dialog.FileName.ToLower();
+ var formatter = new SymbolicExpressionTreeLatexFormatter();
+ File.WriteAllText(filename, formatter.Format(Tree));
+ }
+ #endregion
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionView.Designer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionView.Designer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionView.Designer.cs (revision 9852)
@@ -0,0 +1,107 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ partial class SymbolicExpressionView {
+ ///
+ /// Required designer variable.
+ ///
+ private System.ComponentModel.IContainer components = null;
+
+ ///
+ /// Clean up any resources being used.
+ ///
+ /// true if managed resources should be disposed; otherwise, false.
+ protected override void Dispose(bool disposing) {
+ if (disposing && (components != null)) {
+ components.Dispose();
+ }
+ base.Dispose(disposing);
+ }
+
+ #region Component Designer generated code
+
+ ///
+ /// Required method for Designer support - do not modify
+ /// the contents of this method with the code editor.
+ ///
+ private void InitializeComponent() {
+ this.textBox = new System.Windows.Forms.TextBox();
+ this.formattersComboBox = new System.Windows.Forms.ComboBox();
+ this.formatterLabel = new System.Windows.Forms.Label();
+ this.SuspendLayout();
+ //
+ // textBox
+ //
+ this.textBox.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom)
+ | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.textBox.BackColor = System.Drawing.Color.White;
+ this.textBox.Location = new System.Drawing.Point(3, 30);
+ this.textBox.Multiline = true;
+ this.textBox.Name = "textBox";
+ this.textBox.ReadOnly = true;
+ this.textBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
+ this.textBox.Size = new System.Drawing.Size(475, 282);
+ this.textBox.TabIndex = 0;
+ //
+ // formattersComboBox
+ //
+ this.formattersComboBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
+ | System.Windows.Forms.AnchorStyles.Right)));
+ this.formattersComboBox.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
+ this.formattersComboBox.FormattingEnabled = true;
+ this.formattersComboBox.Location = new System.Drawing.Point(72, 3);
+ this.formattersComboBox.Name = "formattersComboBox";
+ this.formattersComboBox.Size = new System.Drawing.Size(406, 21);
+ this.formattersComboBox.TabIndex = 1;
+ this.formattersComboBox.SelectedIndexChanged += new System.EventHandler(this.formattersComboBox_SelectedIndexChanged);
+ //
+ // formatterLabel
+ //
+ this.formatterLabel.AutoSize = true;
+ this.formatterLabel.Location = new System.Drawing.Point(3, 6);
+ this.formatterLabel.Name = "formatterLabel";
+ this.formatterLabel.Size = new System.Drawing.Size(54, 13);
+ this.formatterLabel.TabIndex = 2;
+ this.formatterLabel.Text = "Formatter:";
+ //
+ // SymbolicExpressionView
+ //
+ this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
+ this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Inherit;
+ this.Controls.Add(this.formatterLabel);
+ this.Controls.Add(this.formattersComboBox);
+ this.Controls.Add(this.textBox);
+ this.Name = "SymbolicExpressionView";
+ this.Size = new System.Drawing.Size(481, 315);
+ this.ResumeLayout(false);
+ this.PerformLayout();
+
+ }
+
+ #endregion
+
+ private System.Windows.Forms.TextBox textBox;
+ private System.Windows.Forms.ComboBox formattersComboBox;
+ private System.Windows.Forms.Label formatterLabel;
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionView.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionView.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/SymbolicExpressionView.cs (revision 9852)
@@ -0,0 +1,81 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Windows.Forms;
+using HeuristicLab.MainForm;
+using HeuristicLab.MainForm.WindowsForms;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ [View("SymbolicExpression View")]
+ [Content(typeof(ISymbolicExpressionTree), false)]
+ public partial class SymbolicExpressionView : AsynchronousContentView {
+ private readonly List treeFormattersList = new List();
+
+ public new ISymbolicExpressionTree Content {
+ get { return (ISymbolicExpressionTree)base.Content; }
+ set { base.Content = value; }
+ }
+
+ public SymbolicExpressionView() {
+ InitializeComponent();
+ IEnumerable formatters = ApplicationManager.Manager.GetInstances();
+ treeFormattersList = new List();
+ foreach (ISymbolicExpressionTreeStringFormatter formatter in formatters) {
+ treeFormattersList.Add(formatter);
+ formattersComboBox.Items.Add(formatter.Name);
+ }
+ if (formattersComboBox.Items.Count > 0)
+ formattersComboBox.SelectedIndex = treeFormattersList.FindIndex(0, treeFormattersList.Count, (f) => f.Name.Contains("Default"));
+ else
+ formattersComboBox.SelectedIndex = -1;
+ }
+
+ protected override void OnContentChanged() {
+ base.OnContentChanged();
+ UpdateTextbox();
+ }
+
+ private void UpdateTextbox() {
+ if (Content == null || formattersComboBox.SelectedIndex < 0)
+ textBox.Text = string.Empty;
+ else {
+ try {
+ textBox.Text = treeFormattersList[formattersComboBox.SelectedIndex].Format(Content);
+ }
+ catch (ArgumentException) { textBox.Text = "Cannot format the symbolic expression tree with the selected formatter."; }
+ catch (NotSupportedException) { textBox.Text = "Formatting of the symbolic expression tree is not supported by the selected formatter."; }
+ }
+ }
+
+ protected override void SetEnabledStateOfControls() {
+ base.SetEnabledStateOfControls();
+ textBox.Enabled = Content != null;
+ textBox.ReadOnly = ReadOnly;
+ }
+
+ private void formattersComboBox_SelectedIndexChanged(object sender, System.EventArgs e) {
+ UpdateTextbox();
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/VisualSymbolicExpressionTreeNode.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/VisualSymbolicExpressionTreeNode.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/VisualSymbolicExpressionTreeNode.cs (revision 9852)
@@ -0,0 +1,129 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Drawing;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ public class VisualSymbolicExpressionTreeNode : object {
+ private static readonly Color defaultLineColor = Color.Black;
+ private static readonly Color defaultTextColor = Color.Black;
+ private static readonly Color defaultFillColor = Color.White;
+ private const int defaultPreferredWidth = 70;
+ private const int defaultPreferredHeight = 46;
+
+ public VisualSymbolicExpressionTreeNode(ISymbolicExpressionTreeNode symbolicExpressionTreeNode) :
+ this(symbolicExpressionTreeNode, defaultLineColor) {
+ }
+
+ public VisualSymbolicExpressionTreeNode(ISymbolicExpressionTreeNode symbolicExpressionTreeNode, Color lineColor) :
+ this(symbolicExpressionTreeNode, lineColor, defaultTextColor) {
+ }
+
+ public VisualSymbolicExpressionTreeNode(ISymbolicExpressionTreeNode symbolicExpressionTreeNode, Color lineColor, Color textColor) :
+ this(symbolicExpressionTreeNode, lineColor, textColor, defaultFillColor) {
+ }
+
+ public VisualSymbolicExpressionTreeNode(ISymbolicExpressionTreeNode symbolicExpressionTreeNode, Color lineColor, Color textColor, Color fillColor) :
+ this(symbolicExpressionTreeNode, lineColor, textColor, fillColor, defaultPreferredWidth, defaultPreferredHeight) {
+ }
+
+ public VisualSymbolicExpressionTreeNode(ISymbolicExpressionTreeNode symbolicExpressionTreeNode, Color lineColor, Color textColor, Color fillColor, int width, int height) {
+ this.symbolicExpressionTreeNode = symbolicExpressionTreeNode;
+ this.lineColor = lineColor;
+ this.textColor = textColor;
+ this.fillColor = fillColor;
+ this.preferredWidth = width;
+ this.preferredHeight = height;
+ this.ToolTip = symbolicExpressionTreeNode.ToString();
+ }
+
+ #region members for internal use only
+ private int x;
+ public int X {
+ get { return x; }
+ internal set { this.x = value; }
+ }
+
+ private int y;
+ public int Y {
+ get { return y; }
+ internal set { this.y = value; }
+ }
+
+ private int width;
+ public int Width {
+ get { return this.width; }
+ internal set { this.width = value; }
+ }
+
+ private int height;
+ public int Height {
+ get { return this.height; }
+ internal set { this.height = value; }
+ }
+ #endregion
+
+ private ISymbolicExpressionTreeNode symbolicExpressionTreeNode;
+ public ISymbolicExpressionTreeNode SymbolicExpressionTreeNode {
+ get { return this.symbolicExpressionTreeNode; }
+ set {
+ symbolicExpressionTreeNode = value;
+ ToolTip = SymbolicExpressionTreeNode.ToString();
+ }
+ }
+
+ private int preferredWidth;
+ public int PreferredWidth {
+ get { return this.preferredWidth; }
+ set { this.preferredWidth = value; }
+ }
+
+ private int preferredHeight;
+ public int PreferredHeight {
+ get { return this.preferredHeight; }
+ set { this.preferredHeight = value; }
+ }
+
+ private Color lineColor;
+ public Color LineColor {
+ get { return this.lineColor; }
+ set { this.lineColor = value; }
+ }
+
+ private Color textColor;
+ public Color TextColor {
+ get { return this.textColor; }
+ set { this.textColor = value; }
+ }
+
+ private Color fillColor;
+ public Color FillColor {
+ get { return this.fillColor; }
+ set { this.fillColor = value; }
+ }
+
+ private string toolTip;
+ public string ToolTip {
+ get { return toolTip; }
+ set { toolTip = value; }
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/VisualSymbolicExpressionTreeNodeConnection.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/VisualSymbolicExpressionTreeNodeConnection.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views/3.4/VisualSymbolicExpressionTreeNodeConnection.cs (revision 9852)
@@ -0,0 +1,48 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Drawing;
+using System.Drawing.Drawing2D;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding.Views {
+ public class VisualSymbolicExpressionTreeNodeConnection : object {
+ private static readonly Color defaultLineColor = Color.Black;
+ private static readonly DashStyle defaultDashStyle = DashStyle.Solid;
+
+ private Color lineColor;
+ public Color LineColor {
+ get { return lineColor; }
+ set { lineColor = value; }
+ }
+
+ private DashStyle dashStyle;
+ public DashStyle DashStyle {
+ get { return dashStyle; }
+ set { dashStyle = value; }
+ }
+
+ public VisualSymbolicExpressionTreeNodeConnection()
+ : base() {
+ lineColor = defaultLineColor;
+ dashStyle = defaultDashStyle;
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/BestSymbolicExpressionTreeAnalyzer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/BestSymbolicExpressionTreeAnalyzer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/BestSymbolicExpressionTreeAnalyzer.cs (revision 9852)
@@ -0,0 +1,132 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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 HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Operators;
+using HeuristicLab.Optimization;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// An operator that tracks the best symbolic expression trees
+ ///
+ [Item("BestSymbolicExpressionTreeAnalyzer", "An operator that tracks the best symbolic expression trees")]
+ [StorableClass]
+ [NonDiscoverableType]
+ public sealed class BestSymbolicExpressionTreeAnalyzer : SingleSuccessorOperator, ISymbolicExpressionTreeAnalyzer {
+ private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
+ private const string ResultsParameterName = "Results";
+ private const string QualityParameterName = "Quality";
+ private const string BestTreeQualityParameterName = "BestTreeQuality";
+ private const string MaximizationParameterName = "Maximization";
+
+ #region Parameter properties
+ public IScopeTreeLookupParameter SymbolicExpressionTreeParameter {
+ get { return (IScopeTreeLookupParameter)Parameters[SymbolicExpressionTreeParameterName]; }
+ }
+ public IScopeTreeLookupParameter QualityParameter {
+ get { return (IScopeTreeLookupParameter)Parameters[QualityParameterName]; }
+ }
+ public ILookupParameter MaximizationParameter {
+ get { return (ILookupParameter)Parameters[MaximizationParameterName]; }
+ }
+ public ILookupParameter BestTreeQualityParameter {
+ get { return (ILookupParameter)Parameters[BestTreeQualityParameterName]; }
+ }
+ public ILookupParameter ResultsParameter {
+ get { return (ILookupParameter)Parameters[ResultsParameterName]; }
+ }
+ #endregion
+
+ #region Properties
+ public bool EnabledByDefault {
+ get { return true; }
+ }
+ #endregion
+
+ [StorableConstructor]
+ private BestSymbolicExpressionTreeAnalyzer(bool deserializing) : base(deserializing) { }
+ private BestSymbolicExpressionTreeAnalyzer(BestSymbolicExpressionTreeAnalyzer original, Cloner cloner)
+ : base(original, cloner) {
+ }
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new BestSymbolicExpressionTreeAnalyzer(this, cloner);
+ }
+ public BestSymbolicExpressionTreeAnalyzer()
+ : base() {
+ Parameters.Add(new ScopeTreeLookupParameter(SymbolicExpressionTreeParameterName, "The symbolic expression trees from which the best should be determined."));
+ Parameters.Add(new ScopeTreeLookupParameter(QualityParameterName, "The quality value of a tree."));
+ Parameters.Add(new LookupParameter(MaximizationParameterName, "The order relation for qualities of trees."));
+ Parameters.Add(new LookupParameter(BestTreeQualityParameterName, "The quality of the best tree so far."));
+ Parameters.Add(new LookupParameter(ResultsParameterName, "The results collection where the best symbolic expression tree should be stored."));
+
+ SymbolicExpressionTreeParameter.Hidden = true;
+ QualityParameter.Hidden = true;
+ MaximizationParameter.Hidden = true;
+ ResultsParameter.Hidden = true;
+ }
+
+ [StorableHook(HookType.AfterDeserialization)]
+ private void AfterDeserialization() {
+ }
+
+ public override IOperation Apply() {
+ var qualities = QualityParameter.ActualValue;
+ var trees = SymbolicExpressionTreeParameter.ActualValue;
+ bool maximization = MaximizationParameter.ActualValue.Value;
+ int bestIdx = 0;
+ double bestQuality = qualities[bestIdx].Value;
+ if (maximization) {
+ for (int i = 1; i < qualities.Length; i++)
+ if (qualities[i].Value > bestQuality) {
+ bestIdx = i;
+ bestQuality = qualities[i].Value;
+ }
+ } else {
+ for (int i = 1; i < qualities.Length; i++)
+ if (qualities[i].Value < bestQuality) {
+ bestIdx = i;
+ bestQuality = qualities[i].Value;
+ }
+ }
+ var bestTree = trees[bestIdx];
+
+ var res = ResultsParameter.ActualValue;
+ if (res.ContainsKey("Best tree")) {
+ var prevBestQuality = (DoubleValue)BestTreeQualityParameter.ActualValue;
+ if ((maximization && prevBestQuality.Value < bestQuality) ||
+ (!maximization && prevBestQuality.Value > bestQuality)) {
+ res["Best tree"].Value = bestTree;
+ prevBestQuality.Value = bestQuality;
+ }
+ } else {
+ BestTreeQualityParameter.ActualValue = new DoubleValue(bestQuality);
+ res.Add(new Result("Best tree", bestTree));
+ }
+
+ return base.Apply();
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/MinAverageMaxSymbolicExpressionTreeLengthAnalyzer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/MinAverageMaxSymbolicExpressionTreeLengthAnalyzer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/MinAverageMaxSymbolicExpressionTreeLengthAnalyzer.cs (revision 9852)
@@ -0,0 +1,136 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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 HeuristicLab.Analysis;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Operators;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// An operator that tracks the min average and max length of symbolic expression trees.
+ ///
+ [Item("MinAverageMaxSymbolicExpressionTreeLengthAnalyzer", "An operator that tracks the min avgerage and max length of symbolic expression trees.")]
+ [StorableClass]
+ public sealed class MinAverageMaxSymbolicExpressionTreeLengthAnalyzer : AlgorithmOperator, ISymbolicExpressionTreeAnalyzer {
+ private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
+ private const string SymbolicExpressionTreeLengthParameterName = "SymbolicExpressionTreeLength";
+ private const string SymbolicExpressionTreeLengthsParameterName = "Symbolic expression tree length";
+ private const string MinTreeLengthParameterName = "Minimal symbolic expression tree length";
+ private const string AverageTreeLengthParameterName = "Average symbolic expression tree length";
+ private const string MaxTreeLengthParameterName = "Maximal symbolic expression tree length";
+ private const string ResultsParameterName = "Results";
+
+ public bool EnabledByDefault {
+ get { return true; }
+ }
+
+ #region parameter properties
+ public IScopeTreeLookupParameter SymbolicExpressionTreeParameter {
+ get { return (IScopeTreeLookupParameter)Parameters[SymbolicExpressionTreeParameterName]; }
+ }
+ public ScopeTreeLookupParameter SymbolicExpressionTreeLengthParameter {
+ get { return (ScopeTreeLookupParameter)Parameters[SymbolicExpressionTreeLengthParameterName]; }
+ }
+ public ValueLookupParameter SymbolicExpressionTreeLengthsParameter {
+ get { return (ValueLookupParameter)Parameters[SymbolicExpressionTreeLengthsParameterName]; }
+ }
+ public ValueLookupParameter ResultsParameter {
+ get { return (ValueLookupParameter)Parameters[ResultsParameterName]; }
+ }
+
+ [Storable]
+ private MinAverageMaxValueAnalyzer valueAnalyzer;
+ [Storable]
+ private UniformSubScopesProcessor subScopesProcessor;
+
+ #endregion
+
+ [StorableConstructor]
+ private MinAverageMaxSymbolicExpressionTreeLengthAnalyzer(bool deserializing) : base() { }
+ private MinAverageMaxSymbolicExpressionTreeLengthAnalyzer(MinAverageMaxSymbolicExpressionTreeLengthAnalyzer original, Cloner cloner)
+ : base(original, cloner) {
+ valueAnalyzer = cloner.Clone(original.valueAnalyzer);
+ subScopesProcessor = cloner.Clone(original.subScopesProcessor);
+ AfterDeserialization();
+ }
+ public MinAverageMaxSymbolicExpressionTreeLengthAnalyzer()
+ : base() {
+ Parameters.Add(new ScopeTreeLookupParameter(SymbolicExpressionTreeParameterName, "The symbolic expression tree whose length should be calculated."));
+ Parameters.Add(new ScopeTreeLookupParameter(SymbolicExpressionTreeLengthParameterName, "The length of the symbolic expression tree."));
+ Parameters.Add(new ValueLookupParameter(SymbolicExpressionTreeLengthsParameterName, "The data table to store the symbolic expression tree lengths."));
+ Parameters.Add(new ValueLookupParameter(ResultsParameterName, "The results collection where the analysis values should be stored."));
+
+ subScopesProcessor = new UniformSubScopesProcessor();
+ SymbolicExpressionTreeLengthCalculator lengthCalculator = new SymbolicExpressionTreeLengthCalculator();
+ valueAnalyzer = new MinAverageMaxValueAnalyzer();
+
+ subScopesProcessor.Depth.Value = SymbolicExpressionTreeParameter.Depth;
+ lengthCalculator.SymbolicExpressionTreeParameter.ActualName = SymbolicExpressionTreeParameter.Name;
+ lengthCalculator.SymbolicExpressionTreeLengthParameter.ActualName = SymbolicExpressionTreeLengthParameter.Name;
+ valueAnalyzer.ValueParameter.ActualName = lengthCalculator.SymbolicExpressionTreeLengthParameter.Name;
+ valueAnalyzer.ValueParameter.Depth = SymbolicExpressionTreeLengthParameter.Depth;
+ valueAnalyzer.AverageValueParameter.ActualName = AverageTreeLengthParameterName;
+ valueAnalyzer.CollectAverageValueInResultsParameter.Value = new BoolValue(false);
+ valueAnalyzer.MaxValueParameter.ActualName = MaxTreeLengthParameterName;
+ valueAnalyzer.CollectMaxValueInResultsParameter.Value = new BoolValue(false);
+ valueAnalyzer.MinValueParameter.ActualName = MinTreeLengthParameterName;
+ valueAnalyzer.CollectMinValueInResultsParameter.Value = new BoolValue(false);
+ valueAnalyzer.ValuesParameter.ActualName = SymbolicExpressionTreeLengthsParameter.Name;
+
+ OperatorGraph.InitialOperator = subScopesProcessor;
+ subScopesProcessor.Operator = lengthCalculator;
+ lengthCalculator.Successor = null;
+ subScopesProcessor.Successor = valueAnalyzer;
+ valueAnalyzer.Successor = null;
+
+ AfterDeserialization();
+ }
+
+
+ [StorableHook(HookType.AfterDeserialization)]
+ private void AfterDeserialization() {
+ SymbolicExpressionTreeParameter.DepthChanged += new EventHandler(SymbolicExpressionTreeParameter_DepthChanged);
+ SymbolicExpressionTreeLengthParameter.DepthChanged += new EventHandler(SymbolicExpressionTreeLengthParameter_DepthChanged);
+ }
+
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new MinAverageMaxSymbolicExpressionTreeLengthAnalyzer(this, cloner);
+ }
+
+ private void SymbolicExpressionTreeParameter_DepthChanged(object sender, EventArgs e) {
+ OnDepthParameterChanged();
+ }
+
+ private void SymbolicExpressionTreeLengthParameter_DepthChanged(object sender, EventArgs e) {
+ OnDepthParameterChanged();
+ }
+
+ private void OnDepthParameterChanged() {
+ valueAnalyzer.ValueParameter.Depth = SymbolicExpressionTreeParameter.Depth;
+ subScopesProcessor.Depth.Value = SymbolicExpressionTreeParameter.Depth;
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionSymbolFrequencyAnalyzer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionSymbolFrequencyAnalyzer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionSymbolFrequencyAnalyzer.cs (revision 9852)
@@ -0,0 +1,143 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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 HeuristicLab.Analysis;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Operators;
+using HeuristicLab.Optimization;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// An operator that tracks the frequencies of distinct symbols in symbolic expression trees.
+ ///
+ [Item("SymbolicExpressionSymbolFrequencyAnalyzer", "An operator that tracks frequencies of symbols in symbolic expression trees.")]
+ [StorableClass]
+ public class SymbolicExpressionSymbolFrequencyAnalyzer : SingleSuccessorOperator, ISymbolicExpressionTreeAnalyzer {
+ private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
+ private const string ResultsParameterName = "Results";
+ private const string SymbolFrequenciesParameterName = "SymbolFrequencies";
+ private const string AggregateSymbolsWithDifferentSubtreeCountParameterName = "AggregateSymbolsWithDifferentSubtreeCount";
+
+ #region parameter properties
+ public IScopeTreeLookupParameter SymbolicExpressionTreeParameter {
+ get { return (IScopeTreeLookupParameter)Parameters[SymbolicExpressionTreeParameterName]; }
+ }
+ public ILookupParameter SymbolFrequenciesParameter {
+ get { return (ILookupParameter)Parameters[SymbolFrequenciesParameterName]; }
+ }
+ public ILookupParameter ResultsParameter {
+ get { return (ILookupParameter)Parameters[ResultsParameterName]; }
+ }
+ public IValueParameter AggregateSymbolsWithDifferentSubtreeCountParameter {
+ get { return (IValueParameter)Parameters[AggregateSymbolsWithDifferentSubtreeCountParameterName]; }
+ }
+ #endregion
+ #region properties
+ public virtual bool EnabledByDefault {
+ get { return true; }
+ }
+ public BoolValue AggregrateSymbolsWithDifferentSubtreeCount {
+ get { return AggregateSymbolsWithDifferentSubtreeCountParameter.Value; }
+ set { AggregateSymbolsWithDifferentSubtreeCountParameter.Value = value; }
+ }
+ #endregion
+
+ [StorableConstructor]
+ protected SymbolicExpressionSymbolFrequencyAnalyzer(bool deserializing) : base(deserializing) { }
+ protected SymbolicExpressionSymbolFrequencyAnalyzer(SymbolicExpressionSymbolFrequencyAnalyzer original, Cloner cloner) : base(original, cloner) { }
+ public SymbolicExpressionSymbolFrequencyAnalyzer()
+ : base() {
+ Parameters.Add(new ScopeTreeLookupParameter(SymbolicExpressionTreeParameterName, "The symbolic expression trees to analyze."));
+ Parameters.Add(new LookupParameter(SymbolFrequenciesParameterName, "The data table to store the symbol frequencies."));
+ Parameters.Add(new LookupParameter(ResultsParameterName, "The result collection where the symbol frequencies should be stored."));
+ Parameters.Add(new ValueParameter(AggregateSymbolsWithDifferentSubtreeCountParameterName, "Flag that indicates if the frequencies of symbols with the same name but different number of sub-trees should be aggregated.", new BoolValue(true)));
+ }
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new SymbolicExpressionSymbolFrequencyAnalyzer(this, cloner);
+ }
+
+ [StorableHook(HookType.AfterDeserialization)]
+ private void AfterDeserialization() {
+ #region remove with HL 3.4
+ if (!Parameters.ContainsKey(AggregateSymbolsWithDifferentSubtreeCountParameterName))
+ Parameters.Add(new ValueParameter(AggregateSymbolsWithDifferentSubtreeCountParameterName, "Flag that indicates if the frequencies of symbols with the same name but different number of sub-trees should be aggregated.", new BoolValue(true)));
+ #endregion
+ }
+
+ public override IOperation Apply() {
+ ItemArray expressions = SymbolicExpressionTreeParameter.ActualValue;
+ ResultCollection results = ResultsParameter.ActualValue;
+ DataTable symbolFrequencies = SymbolFrequenciesParameter.ActualValue;
+ if (symbolFrequencies == null) {
+ symbolFrequencies = new DataTable("Symbol frequencies", "Relative frequency of symbols aggregated over the whole population.");
+ symbolFrequencies.VisualProperties.YAxisTitle = "Relative Symbol Frequency";
+
+ SymbolFrequenciesParameter.ActualValue = symbolFrequencies;
+ results.Add(new Result("Symbol frequencies", symbolFrequencies));
+ }
+
+ // all rows must have the same number of values so we can just take the first
+ int numberOfValues = symbolFrequencies.Rows.Select(r => r.Values.Count).DefaultIfEmpty().First();
+
+ foreach (var pair in SymbolicExpressionSymbolFrequencyAnalyzer.CalculateSymbolFrequencies(expressions, AggregrateSymbolsWithDifferentSubtreeCount.Value)) {
+ if (!symbolFrequencies.Rows.ContainsKey(pair.Key)) {
+ // initialize a new row for the symbol and pad with zeros
+ DataRow row = new DataRow(pair.Key, "", Enumerable.Repeat(0.0, numberOfValues));
+ row.VisualProperties.StartIndexZero = true;
+ symbolFrequencies.Rows.Add(row);
+ }
+ symbolFrequencies.Rows[pair.Key].Values.Add(Math.Round(pair.Value, 3));
+ }
+
+ // add a zero for each data row that was not modified in the previous loop
+ foreach (var row in symbolFrequencies.Rows.Where(r => r.Values.Count != numberOfValues + 1))
+ row.Values.Add(0.0);
+
+ return base.Apply();
+ }
+
+ public static IEnumerable> CalculateSymbolFrequencies(IEnumerable trees, bool aggregateDifferentNumberOfSubtrees = true) {
+ Dictionary symbolFrequencies = new Dictionary();
+ int totalNumberOfSymbols = 0;
+
+ foreach (var tree in trees) {
+ foreach (var node in tree.IterateNodesPrefix()) {
+ string symbolName;
+ if (aggregateDifferentNumberOfSubtrees) symbolName = node.Symbol.Name;
+ else symbolName = node.Symbol.Name + "-" + node.SubtreeCount;
+ if (symbolFrequencies.ContainsKey(symbolName)) symbolFrequencies[symbolName] += 1;
+ else symbolFrequencies.Add(symbolName, 1);
+ totalNumberOfSymbols++;
+ }
+ }
+
+ foreach (var pair in symbolFrequencies)
+ yield return new KeyValuePair(pair.Key, pair.Value / totalNumberOfSymbols);
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionTreeLengthAnalyzer.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionTreeLengthAnalyzer.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionTreeLengthAnalyzer.cs (revision 9852)
@@ -0,0 +1,253 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Linq;
+using HeuristicLab.Analysis;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Operators;
+using HeuristicLab.Optimization;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// An operator that tracks tree lengths of Symbolic Expression Trees
+ ///
+ [Item("SymbolicExpressionTreeLengthAnalyzer", "An operator that tracks tree lengths of Symbolic Expression Trees")]
+ [StorableClass]
+ public sealed class SymbolicExpressionTreeLengthAnalyzer : SingleSuccessorOperator, ISymbolicExpressionTreeAnalyzer {
+ private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
+ private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
+ private const string SymbolicExpressionTreeLengthsParameterName = "SymbolicExpressionTreeLengthsTable";
+ private const string SymbolicExpressionTreeLengthsHistoryParameterName = "SymbolicExpressionTreeLengthsHistoryTable";
+ private const string ResultsParameterName = "Results";
+ private const string StoreHistoryParameterName = "StoreHistory";
+ private const string UpdateIntervalParameterName = "UpdateInterval";
+ private const string UpdateCounterParameterName = "UpdateCounter";
+
+ #region Parameter properties
+ public IScopeTreeLookupParameter SymbolicExpressionTreeParameter {
+ get { return (IScopeTreeLookupParameter)Parameters[SymbolicExpressionTreeParameterName]; }
+ }
+ public ValueLookupParameter SymbolicExpressionTreeLengthsParameter {
+ get { return (ValueLookupParameter)Parameters[SymbolicExpressionTreeLengthsParameterName]; }
+ }
+ public ValueLookupParameter SymbolicExpressionTreeLengthsHistoryParameter {
+ get { return (ValueLookupParameter)Parameters[SymbolicExpressionTreeLengthsHistoryParameterName]; }
+ }
+ public ValueLookupParameter ResultsParameter {
+ get { return (ValueLookupParameter)Parameters[ResultsParameterName]; }
+ }
+ // history
+ public ValueParameter StoreHistoryParameter {
+ get { return (ValueParameter)Parameters[StoreHistoryParameterName]; }
+ }
+ public ValueParameter UpdateIntervalParameter {
+ get { return (ValueParameter)Parameters[UpdateIntervalParameterName]; }
+ }
+ public ValueParameter UpdateCounterParameter {
+ get { return (ValueParameter)Parameters[UpdateCounterParameterName]; }
+ }
+ #endregion
+
+ #region Properties
+ public bool EnabledByDefault {
+ get { return true; }
+ }
+ public IntValue UpdateInterval {
+ get { return UpdateIntervalParameter.Value; }
+ }
+ public IntValue UpdateCounter {
+ get { return UpdateCounterParameter.Value; }
+ }
+ public BoolValue StoreHistory {
+ get { return StoreHistoryParameter.Value; }
+ }
+ #endregion
+
+ [StorableConstructor]
+ private SymbolicExpressionTreeLengthAnalyzer(bool deserializing) : base(deserializing) { }
+ private SymbolicExpressionTreeLengthAnalyzer(SymbolicExpressionTreeLengthAnalyzer original, Cloner cloner)
+ : base(original, cloner) {
+ }
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new SymbolicExpressionTreeLengthAnalyzer(this, cloner);
+ }
+ public SymbolicExpressionTreeLengthAnalyzer()
+ : base() {
+ Parameters.Add(new ScopeTreeLookupParameter(SymbolicExpressionTreeParameterName, "The symbolic expression tree whose length should be calculated."));
+ Parameters.Add(new LookupParameter(MaximumSymbolicExpressionTreeLengthParameterName, "The maximum allowed symbolic expression tree length"));
+ Parameters.Add(new ValueLookupParameter(SymbolicExpressionTreeLengthsParameterName, "The data table to store the symbolic expression tree lengths."));
+ Parameters.Add(new ValueLookupParameter(SymbolicExpressionTreeLengthsHistoryParameterName, "The data table to store the symbolic expression tree lengths history."));
+ Parameters.Add(new ValueLookupParameter(ResultsParameterName, "The results collection where the analysis values should be stored."));
+ Parameters.Add(new ValueParameter(StoreHistoryParameterName, "True if the tree lengths history of the population should be stored.", new BoolValue(false)));
+ Parameters.Add(new ValueParameter(UpdateIntervalParameterName, "The interval in which the tree length analysis should be applied.", new IntValue(1)));
+ Parameters.Add(new ValueParameter(UpdateCounterParameterName, "The value which counts how many times the operator was called since the last update", new IntValue(0)));
+
+ SymbolicExpressionTreeLengthsParameter.Hidden = true;
+ SymbolicExpressionTreeLengthsHistoryParameter.Hidden = true;
+ ResultsParameter.Hidden = true;
+ UpdateCounterParameter.Hidden = true;
+ }
+
+ [StorableHook(HookType.AfterDeserialization)]
+ private void AfterDeserialization() {
+ // check if all the parameters are present and accounted for
+ if (!Parameters.ContainsKey(StoreHistoryParameterName)) {
+ Parameters.Add(new ValueParameter(StoreHistoryParameterName, "True if the tree lengths history of the population should be stored.", new BoolValue(false)));
+ }
+ if (!Parameters.ContainsKey(UpdateIntervalParameterName)) {
+ Parameters.Add(new ValueParameter(UpdateIntervalParameterName, "The interval in which the tree length analysis should be applied.", new IntValue(1)));
+ }
+ //necessary code to correct UpdateCounterParameter - type was changed from LookupParameter to ValueParameter
+ if (Parameters.ContainsKey(UpdateCounterParameterName) && (Parameters[UpdateCounterParameterName] is LookupParameter))
+ Parameters.Remove(UpdateCounterParameterName);
+ if (!Parameters.ContainsKey(UpdateCounterParameterName)) {
+ Parameters.Add(new ValueParameter(UpdateCounterParameterName, "The value which counts how many times the operator was called since the last update", new IntValue(0)));
+ UpdateCounterParameter.Hidden = true;
+ }
+ }
+
+ #region IStatefulItem members
+ public override void InitializeState() {
+ base.InitializeState();
+ UpdateCounter.Value = 0;
+ }
+ public override void ClearState() {
+ base.ClearState();
+ UpdateCounter.Value = 0;
+ }
+ #endregion
+
+ public override IOperation Apply() {
+ UpdateCounter.Value++;
+ // the analyzer runs periodically, every 'updateInterval' times
+ if (UpdateCounter.Value == UpdateInterval.Value) {
+ UpdateCounter.Value = 0; // reset counter
+
+ // compute all tree lengths and store them in the lengthsTable
+ var solutions = SymbolicExpressionTreeParameter.ActualValue;
+
+ var treeLengthsTable = SymbolicExpressionTreeLengthsParameter.ActualValue;
+ // if the table was not created yet, we create it here
+ if (treeLengthsTable == null) {
+ treeLengthsTable = new DataTable("Tree Length Histogram");
+ SymbolicExpressionTreeLengthsParameter.ActualValue = treeLengthsTable;
+ }
+
+ // data table which stores tree length values
+ DataRow treeLengthsTableRow;
+
+ const string treeLengthsTableRowName = "Symbolic expression tree lengths";
+ const string treeLengthsTableRowDesc = "The distribution of symbolic expression tree lengths";
+ const string xAxisTitle = "Symbolic expression tree lengths";
+ const string yAxisTitle = "Frequency / Number of tree individuals";
+
+ var treeLengths = solutions.Select(s => (int)s.Length).ToList();
+
+ int maxLength = treeLengths.Max(t => t);
+ int minLength = treeLengths.Min(t => t);
+
+ if (!treeLengthsTable.Rows.ContainsKey(treeLengthsTableRowName)) {
+ treeLengthsTableRow = new DataRow(treeLengthsTableRowName, treeLengthsTableRowDesc, treeLengths.Select(x => (double)x));
+ treeLengthsTable.Rows.Add(treeLengthsTableRow);
+ } else {
+ treeLengthsTableRow = treeLengthsTable.Rows[treeLengthsTableRowName];
+ treeLengthsTableRow.Values.Replace(treeLengths.Select(x => (double)x));
+ }
+
+ double maximumAllowedTreeLength = ((LookupParameter)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]).ActualValue.Value;
+
+ treeLengthsTableRow.VisualProperties.ChartType = DataRowVisualProperties.DataRowChartType.Histogram;
+ treeLengthsTableRow.VisualProperties.ExactBins = false;
+
+ int range = maxLength - minLength;
+ if (range == 0) range = 1;
+ // the following trick should result in an integer intervalWidth of 1,2,4,...
+ treeLengthsTableRow.VisualProperties.Bins = range;
+
+ if (maxLength <= 25) // [0,25]
+ treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0;
+ else if (maxLength <= 100) // [26,100]
+ treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 2.0;
+ else if (maxLength <= 250) // [101,250]
+ treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 5.0;
+ else if (maxLength <= 500) // [251,500]
+ treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 10.0;
+ else
+ treeLengthsTableRow.VisualProperties.ScaleFactor = 1.0 / 20.0; // [501,inf]
+
+ treeLengthsTableRow.VisualProperties.IsVisibleInLegend = false;
+
+ // visual properties for the X-axis
+ treeLengthsTable.VisualProperties.XAxisMinimumAuto = false;
+ treeLengthsTable.VisualProperties.XAxisMaximumAuto = false;
+ treeLengthsTable.VisualProperties.XAxisMinimumFixedValue = 0.0;
+ if (maxLength > maximumAllowedTreeLength + 1)
+ treeLengthsTable.VisualProperties.XAxisMaximumFixedValue = maxLength + 1; // +1 so the histogram column for the maximum length won't get trimmed
+ else
+ treeLengthsTable.VisualProperties.XAxisMaximumFixedValue = maximumAllowedTreeLength + 1;
+ treeLengthsTable.VisualProperties.XAxisTitle = xAxisTitle;
+ //visual properties for the Y-axis
+ treeLengthsTable.VisualProperties.YAxisMinimumAuto = false;
+ treeLengthsTable.VisualProperties.YAxisMaximumAuto = false;
+ treeLengthsTable.VisualProperties.YAxisMinimumFixedValue = 0.0;
+ int maxFreq = (int)Math.Round(solutions.GroupBy(s => s.Length).Max(g => g.Count()) / treeLengthsTableRow.VisualProperties.ScaleFactor);
+ if (maxFreq % 5 != 0)
+ maxFreq += (5 - maxFreq % 5);
+ double yAxisMaximumFixedValue = maxFreq;
+
+ treeLengthsTable.VisualProperties.YAxisMaximumFixedValue = yAxisMaximumFixedValue;
+ treeLengthsTable.VisualProperties.YAxisTitle = yAxisTitle;
+
+ var results = ResultsParameter.ActualValue;
+
+ if (!results.ContainsKey(treeLengthsTableRowName)) {
+ results.Add(new Result(treeLengthsTableRowName, treeLengthsTable));
+ } else {
+ results[treeLengthsTableRowName].Value = treeLengthsTable;
+ }
+
+ bool storeHistory = StoreHistoryParameter.Value.Value;
+ const string treeLengthHistoryTableName = "Tree lengths history";
+
+ if (storeHistory) {
+ var treeLengthsHistory = SymbolicExpressionTreeLengthsHistoryParameter.ActualValue;
+ if (treeLengthsHistory == null) {
+ treeLengthsHistory = new DataTableHistory();
+ SymbolicExpressionTreeLengthsHistoryParameter.ActualValue = treeLengthsHistory;
+ }
+ treeLengthsHistory.Add((DataTable)treeLengthsTable.Clone());
+
+ if (!results.ContainsKey(treeLengthHistoryTableName)) {
+ results.Add(new Result(treeLengthHistoryTableName, treeLengthsHistory));
+ } else {
+ results[treeLengthHistoryTableName].Value = treeLengthsHistory;
+ }
+ }
+ }
+ return base.Apply();
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionTreeLengthCalculator.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionTreeLengthCalculator.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Analyzers/SymbolicExpressionTreeLengthCalculator.cs (revision 9852)
@@ -0,0 +1,76 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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 HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Operators;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// An operator that outputs the length of a symbolic expression tree.
+ ///
+ [Item("SymbolicExpressionTreeLengthCalculator", "An operator that outputs the length of a symbolic expression tree.")]
+ [StorableClass]
+ public sealed class SymbolicExpressionTreeLengthCalculator : SingleSuccessorOperator {
+ private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
+ private const string SymbolicExpressionTreeLengthParameterName = "SymbolicExpressionTreeLength";
+
+ #region parameter properties
+ public ILookupParameter SymbolicExpressionTreeParameter {
+ get { return (ILookupParameter)Parameters[SymbolicExpressionTreeParameterName]; }
+ }
+ public ILookupParameter SymbolicExpressionTreeLengthParameter {
+ get { return (ILookupParameter)Parameters[SymbolicExpressionTreeLengthParameterName]; }
+ }
+ #endregion
+
+ #region properties
+ public SymbolicExpressionTree SymbolicExpressionTree {
+ get { return SymbolicExpressionTreeParameter.ActualValue; }
+ }
+ public DoubleValue SymbolicExpressionTreeLength {
+ get { return SymbolicExpressionTreeLengthParameter.ActualValue; }
+ set { SymbolicExpressionTreeLengthParameter.ActualValue = value; }
+ }
+ #endregion
+
+ [StorableConstructor]
+ private SymbolicExpressionTreeLengthCalculator(bool deserializing) : base(deserializing) { }
+ private SymbolicExpressionTreeLengthCalculator(SymbolicExpressionTreeLengthCalculator original, Cloner cloner) : base(original, cloner) { }
+ public SymbolicExpressionTreeLengthCalculator()
+ : base() {
+ Parameters.Add(new LookupParameter(SymbolicExpressionTreeParameterName, "The symbolic expression tree whose length should be calculated."));
+ Parameters.Add(new LookupParameter(SymbolicExpressionTreeLengthParameterName, "The length of the symbolic expression tree."));
+ }
+
+ public override IOperation Apply() {
+ SymbolicExpressionTreeLength = new DoubleValue(SymbolicExpressionTree.Length);
+ return base.Apply();
+ }
+
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new SymbolicExpressionTreeLengthCalculator(this, cloner);
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentCreater.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentCreater.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentCreater.cs (revision 9852)
@@ -0,0 +1,213 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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 HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// Creates a new argument within one function-defining branch of a symbolic expression tree.
+ /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 106
+ ///
+ [Item("ArgumentCreater", "Manipulates a symbolic expression by creating a new argument within one function-defining branch. As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 106")]
+ [StorableClass]
+ public sealed class ArgumentCreater : SymbolicExpressionTreeArchitectureManipulator, ISymbolicExpressionTreeSizeConstraintOperator {
+ private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
+ private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
+ #region Parameter Properties
+ public IValueLookupParameter MaximumSymbolicExpressionTreeLengthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
+ }
+ public IValueLookupParameter MaximumSymbolicExpressionTreeDepthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
+ }
+ #endregion
+ #region Properties
+ public IntValue MaximumSymbolicExpressionTreeLength {
+ get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
+ }
+ public IntValue MaximumSymbolicExpressionTreeDepth {
+ get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
+ }
+ #endregion
+ [StorableConstructor]
+ private ArgumentCreater(bool deserializing) : base(deserializing) { }
+ private ArgumentCreater(ArgumentCreater original, Cloner cloner) : base(original, cloner) { }
+ public ArgumentCreater()
+ : base() {
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
+ }
+
+ public override sealed void ModifyArchitecture(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
+ CreateNewArgument(random, symbolicExpressionTree, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
+ }
+
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new ArgumentCreater(this, cloner);
+ }
+
+ public static bool CreateNewArgument(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ int maxTreeLength, int maxTreeDepth,
+ int maxFunctionDefinitions, int maxFunctionArguments) {
+ // work on a copy in case we find out later that the tree would be too big
+ // in this case it's easiest to simply return the original tree.
+ ISymbolicExpressionTree clonedTree = (ISymbolicExpressionTree)symbolicExpressionTree.Clone();
+
+ var functionDefiningBranches = clonedTree.IterateNodesPrefix().OfType();
+ if (functionDefiningBranches.Count() == 0)
+ // no function defining branch found => abort
+ return false;
+
+ // select a random function defining branch
+ var selectedDefunBranch = functionDefiningBranches.SelectRandom(random);
+ var definedArguments = (from symbol in selectedDefunBranch.Grammar.Symbols.OfType()
+ select symbol.ArgumentIndex).Distinct();
+ if (definedArguments.Count() >= maxFunctionArguments)
+ // max number of arguments reached => abort
+ return false;
+
+ var allowedArgumentIndexes = Enumerable.Range(0, maxFunctionArguments);
+ var newArgumentIndex = allowedArgumentIndexes.Except(definedArguments).First();
+ ArgumentTreeNode newArgumentNode = MakeArgumentNode(newArgumentIndex);
+
+ // this operation potentially creates very big trees so the access to the length property might throw overflow exception
+ try {
+ if (CreateNewArgumentForDefun(random, clonedTree, selectedDefunBranch, newArgumentNode) && clonedTree.Length <= maxTreeLength && clonedTree.Depth <= maxTreeDepth) {
+
+ // size constraints are fulfilled
+ // replace root of original tree with root of manipulated tree
+ symbolicExpressionTree.Root = clonedTree.Root;
+ return true;
+ } else {
+ // keep originalTree
+ return false;
+ }
+ }
+ catch (OverflowException) {
+ // keep original tree
+ return false;
+ }
+ }
+
+ private static bool CreateNewArgumentForDefun(IRandom random, ISymbolicExpressionTree tree, DefunTreeNode defunBranch, ArgumentTreeNode newArgumentNode) {
+ // select a random cut point in the function defining branch
+ // the branch at the cut point is to be replaced by a new argument node
+ var cutPoints = (from node in defunBranch.IterateNodesPrefix()
+ where node.Subtrees.Count() > 0 &&
+ !node.IterateNodesPrefix().OfType().Any() &&
+ !node.IterateNodesPrefix().OfType().Any()
+ from subtree in node.Subtrees
+ select new CutPoint(node, subtree)).ToList();
+
+ if (cutPoints.Count() == 0)
+ // no cut point found => abort;
+ return false;
+ var selectedCutPoint = cutPoints[random.Next(cutPoints.Count)];
+ // replace the branch at the cut point with an argument node
+ var replacedBranch = selectedCutPoint.Child;
+ selectedCutPoint.Parent.RemoveSubtree(selectedCutPoint.ChildIndex);
+ selectedCutPoint.Parent.InsertSubtree(selectedCutPoint.ChildIndex, newArgumentNode);
+
+ // find all old invocations of the selected ADF and attach a cloned version of the replaced branch (with all argument-nodes expanded)
+ // iterate in post-fix order to make sure that the subtrees of n are already adapted when n is processed
+ var invocationNodes = (from node in tree.IterateNodesPostfix().OfType()
+ where node.Symbol.FunctionName == defunBranch.FunctionName
+ where node.Subtrees.Count() == defunBranch.NumberOfArguments
+ select node).ToList();
+ // do this repeatedly until no matching invocations are found
+ while (invocationNodes.Count > 0) {
+ List newlyAddedBranches = new List();
+ foreach (var invocationNode in invocationNodes) {
+ // check that the invocation node really has the correct number of arguments
+ if (invocationNode.Subtrees.Count() != defunBranch.NumberOfArguments) throw new InvalidOperationException();
+ // append a new argument branch after expanding all argument nodes
+ var clonedBranch = (ISymbolicExpressionTreeNode)replacedBranch.Clone();
+ clonedBranch = ReplaceArgumentsInBranch(clonedBranch, invocationNode.Subtrees);
+ invocationNode.InsertSubtree(newArgumentNode.Symbol.ArgumentIndex, clonedBranch);
+ newlyAddedBranches.Add(clonedBranch);
+ }
+ // iterate in post-fix order to make sure that the subtrees of n are already adapted when n is processed
+ invocationNodes = (from newlyAddedBranch in newlyAddedBranches
+ from node in newlyAddedBranch.IterateNodesPostfix().OfType()
+ where node.Symbol.FunctionName == defunBranch.FunctionName
+ where node.Subtrees.Count() == defunBranch.NumberOfArguments
+ select node).ToList();
+ }
+ // increase expected number of arguments of function defining branch
+ // it's possible that the number of actually referenced arguments was reduced (all references were replaced by a single new argument)
+ // but the number of expected arguments is increased anyway
+ defunBranch.NumberOfArguments++;
+ defunBranch.Grammar.AddSymbol(newArgumentNode.Symbol);
+ defunBranch.Grammar.SetSubtreeCount(newArgumentNode.Symbol, 0, 0);
+ // allow the argument as child of any other symbol
+ GrammarModifier.SetAllowedParentSymbols(defunBranch.Grammar, selectedCutPoint.Child.Symbol, newArgumentNode.Symbol);
+
+ foreach (var subtree in tree.Root.Subtrees) {
+ // when the changed function is known in the branch then update the number of arguments
+ var matchingSymbol = subtree.Grammar.Symbols.OfType().Where(s => s.FunctionName == defunBranch.FunctionName).SingleOrDefault();
+ if (matchingSymbol != null) {
+ subtree.Grammar.SetSubtreeCount(matchingSymbol, defunBranch.NumberOfArguments, defunBranch.NumberOfArguments);
+ foreach (var symb in subtree.Grammar.Symbols) {
+ if (symb is StartSymbol || symb is ProgramRootSymbol) continue;
+ if (symb.Name == matchingSymbol.Name) continue; //don't allow invoke as child of invoke
+ if (subtree.Grammar.IsAllowedChildSymbol(selectedCutPoint.Parent.Symbol, symb, selectedCutPoint.ChildIndex))
+ subtree.Grammar.AddAllowedChildSymbol(matchingSymbol, symb, newArgumentNode.Symbol.ArgumentIndex);
+ }
+ }
+ }
+
+ return true;
+ }
+
+ private static ISymbolicExpressionTreeNode ReplaceArgumentsInBranch(ISymbolicExpressionTreeNode branch, IEnumerable argumentTrees) {
+ ArgumentTreeNode argNode = branch as ArgumentTreeNode;
+ if (argNode != null) {
+ // replace argument nodes by a clone of the original subtree that provided the result for the argument node
+ return (SymbolicExpressionTreeNode)argumentTrees.ElementAt(argNode.Symbol.ArgumentIndex).Clone();
+ } else {
+ // call recursively for all subtree
+ List subtrees = new List(branch.Subtrees);
+ while (branch.Subtrees.Count() > 0) branch.RemoveSubtree(0);
+ foreach (var subtree in subtrees) {
+ branch.AddSubtree(ReplaceArgumentsInBranch(subtree, argumentTrees));
+ }
+ return branch;
+ }
+ }
+
+ private static ArgumentTreeNode MakeArgumentNode(int argIndex) {
+ var node = (ArgumentTreeNode)(new Argument(argIndex)).CreateTreeNode();
+ return node;
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDeleter.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDeleter.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDeleter.cs (revision 9852)
@@ -0,0 +1,106 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Linq;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 112
+ ///
+ [Item("ArgumentDeleter", "Manipulates a symbolic expression by deleting an argument from an existing function defining branch. As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 112")]
+ [StorableClass]
+ public sealed class ArgumentDeleter : SymbolicExpressionTreeArchitectureManipulator {
+ [StorableConstructor]
+ private ArgumentDeleter(bool deserializing) : base(deserializing) { }
+ private ArgumentDeleter(ArgumentDeleter original, Cloner cloner) : base(original, cloner) { }
+ public ArgumentDeleter() : base() { }
+
+ public override sealed void ModifyArchitecture(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
+ DeleteArgument(random, symbolicExpressionTree, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
+ }
+
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new ArgumentDeleter(this, cloner);
+ }
+
+ public static bool DeleteArgument(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ int maxFunctionDefinitions, int maxFunctionArguments) {
+
+ var functionDefiningBranches = symbolicExpressionTree.IterateNodesPrefix().OfType();
+ if (functionDefiningBranches.Count() == 0)
+ // no function defining branch => abort
+ return false;
+ var selectedDefunBranch = functionDefiningBranches.SelectRandom(random);
+ if (selectedDefunBranch.NumberOfArguments <= 1)
+ // argument deletion by consolidation is not possible => abort
+ return false;
+ // the argument to be removed is always the one with the largest index
+ // (otherwise we would have to decrement the index of the larger argument symbols)
+ var removedArgument = (from sym in selectedDefunBranch.Grammar.Symbols.OfType()
+ select sym.ArgumentIndex).Distinct().OrderBy(x => x).Last();
+ // find invocations of the manipulated funcion and remove the specified argument tree
+ var invocationNodes = (from node in symbolicExpressionTree.IterateNodesPrefix().OfType()
+ where node.Symbol.FunctionName == selectedDefunBranch.FunctionName
+ select node).ToList();
+ foreach (var invokeNode in invocationNodes) {
+ invokeNode.RemoveSubtree(removedArgument);
+ }
+
+ DeleteArgumentByConsolidation(random, selectedDefunBranch, removedArgument);
+
+ // delete the dynamic argument symbol that matches the argument to be removed
+ var matchingSymbol = selectedDefunBranch.Grammar.Symbols.OfType().Where(s => s.ArgumentIndex == removedArgument).Single();
+ selectedDefunBranch.Grammar.RemoveSymbol(matchingSymbol);
+ selectedDefunBranch.NumberOfArguments--;
+ // reduce arity in known functions of all root branches
+ foreach (var subtree in symbolicExpressionTree.Root.Subtrees) {
+ var matchingInvokeSymbol = subtree.Grammar.Symbols.OfType().Where(s => s.FunctionName == selectedDefunBranch.FunctionName).SingleOrDefault();
+ if (matchingInvokeSymbol != null) {
+ subtree.Grammar.SetSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments, selectedDefunBranch.NumberOfArguments);
+ }
+ }
+ return true;
+ }
+
+ private static void DeleteArgumentByConsolidation(IRandom random, DefunTreeNode branch, int removedArgumentIndex) {
+ // replace references to the deleted argument with random references to existing arguments
+ var possibleArgumentSymbols = (from sym in branch.Grammar.Symbols.OfType()
+ where sym.ArgumentIndex != removedArgumentIndex
+ select sym).ToList();
+ var argNodes = from node in branch.IterateNodesPrefix().OfType()
+ where node.Symbol.ArgumentIndex == removedArgumentIndex
+ select node;
+ foreach (var argNode in argNodes) {
+ var replacementSymbol = possibleArgumentSymbols.SelectRandom(random);
+ argNode.Symbol = replacementSymbol;
+ }
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDuplicater.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDuplicater.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/ArgumentDuplicater.cs (revision 9852)
@@ -0,0 +1,131 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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 HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// Manipulates a symbolic expression by duplicating an existing argument node of a function-defining branch.
+ /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 94
+ ///
+ [Item("ArgumentDuplicater", "Manipulates a symbolic expression by duplicating an existing argument node of a function-defining branch. As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 94")]
+ [StorableClass]
+ public sealed class ArgumentDuplicater : SymbolicExpressionTreeArchitectureManipulator {
+ [StorableConstructor]
+ private ArgumentDuplicater(bool deserializing) : base(deserializing) { }
+ private ArgumentDuplicater(ArgumentDuplicater original, Cloner cloner) : base(original, cloner) { }
+ public ArgumentDuplicater() : base() { }
+
+ public override sealed void ModifyArchitecture(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
+ DuplicateArgument(random, symbolicExpressionTree, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
+ }
+
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new ArgumentDuplicater(this, cloner);
+ }
+
+ public static bool DuplicateArgument(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ int maxFunctionDefinitions, int maxFunctionArguments) {
+ var functionDefiningBranches = symbolicExpressionTree.IterateNodesPrefix().OfType();
+
+ var allowedArgumentIndexes = Enumerable.Range(0, maxFunctionArguments);
+ if (functionDefiningBranches.Count() == 0)
+ // no function defining branches => abort
+ return false;
+
+ var selectedDefunBranch = functionDefiningBranches.SelectRandom(random);
+ var argumentSymbols = selectedDefunBranch.Grammar.Symbols.OfType();
+ if (argumentSymbols.Count() == 0 || argumentSymbols.Count() >= maxFunctionArguments)
+ // when no argument or number of arguments is already at max allowed value => abort
+ return false;
+ var selectedArgumentSymbol = argumentSymbols.SelectRandom(random);
+ var takenIndexes = argumentSymbols.Select(s => s.ArgumentIndex);
+ var newArgumentIndex = allowedArgumentIndexes.Except(takenIndexes).First();
+
+ var newArgSymbol = new Argument(newArgumentIndex);
+
+ // replace existing references to the original argument with references to the new argument randomly in the selectedBranch
+ var argumentNodes = selectedDefunBranch.IterateNodesPrefix().OfType();
+ foreach (var argNode in argumentNodes) {
+ if (argNode.Symbol == selectedArgumentSymbol) {
+ if (random.NextDouble() < 0.5) {
+ argNode.Symbol = newArgSymbol;
+ }
+ }
+ }
+ // find invocations of the functions and duplicate the matching argument branch
+ var invocationNodes = (from node in symbolicExpressionTree.IterateNodesPrefix().OfType()
+ where node.Symbol.FunctionName == selectedDefunBranch.FunctionName
+ where node.Subtrees.Count() == selectedDefunBranch.NumberOfArguments
+ select node).ToList();
+ // do this repeatedly until no matching invocations are found
+ while (invocationNodes.Count() > 0) {
+ List newlyAddedBranches = new List();
+ foreach (var invokeNode in invocationNodes) {
+ // check that the invocation node really has the correct number of arguments
+ if (invokeNode.Subtrees.Count() != selectedDefunBranch.NumberOfArguments) throw new InvalidOperationException();
+ var argumentBranch = invokeNode.GetSubtree(selectedArgumentSymbol.ArgumentIndex);
+ var clonedArgumentBranch = (ISymbolicExpressionTreeNode)argumentBranch.Clone();
+ invokeNode.InsertSubtree(newArgumentIndex, clonedArgumentBranch);
+ newlyAddedBranches.Add(clonedArgumentBranch);
+ }
+ invocationNodes = (from newlyAddedBranch in newlyAddedBranches
+ from node in newlyAddedBranch.IterateNodesPrefix().OfType()
+ where node.Symbol.FunctionName == selectedDefunBranch.FunctionName
+ where node.Subtrees.Count() == selectedDefunBranch.NumberOfArguments
+ select node).ToList();
+ }
+ // register the new argument symbol and increase the number of arguments of the ADF
+ selectedDefunBranch.Grammar.AddSymbol(newArgSymbol);
+ selectedDefunBranch.Grammar.SetSubtreeCount(newArgSymbol, 0, 0);
+ // allow the duplicated argument as child of all other arguments where the orginal argument was allowed
+ GrammarModifier.SetAllowedParentSymbols(selectedDefunBranch.Grammar, selectedArgumentSymbol, newArgSymbol);
+ selectedDefunBranch.NumberOfArguments++;
+
+ // increase the arity of the changed ADF in all branches that can use this ADF
+ foreach (var subtree in symbolicExpressionTree.Root.Subtrees) {
+ var matchingInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType()
+ where symb.FunctionName == selectedDefunBranch.FunctionName
+ select symb).SingleOrDefault();
+ if (matchingInvokeSymbol != null) {
+ subtree.Grammar.SetSubtreeCount(matchingInvokeSymbol, selectedDefunBranch.NumberOfArguments, selectedDefunBranch.NumberOfArguments);
+ foreach (var symb in subtree.Grammar.Symbols) {
+ if (symb is StartSymbol || symb is ProgramRootSymbol) continue;
+ if (subtree.Grammar.IsAllowedChildSymbol(matchingInvokeSymbol, symb, selectedArgumentSymbol.ArgumentIndex))
+ subtree.Grammar.AddAllowedChildSymbol(matchingInvokeSymbol, symb, newArgumentIndex);
+ }
+ }
+ }
+ return true;
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/GrammarModifier.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/GrammarModifier.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/GrammarModifier.cs (revision 9852)
@@ -0,0 +1,88 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Collections.Generic;
+using System.Linq;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ public static class GrammarModifier {
+ internal static void AddInvokeSymbol(ISymbolicExpressionTreeGrammar grammar, string functionName, int nArgs, CutPoint startCutPoint, IEnumerable argumentCutPoints) {
+ if (!grammar.ContainsSymbol(startCutPoint.Child.Symbol)) return;
+
+ var invokeSym = new InvokeFunction(functionName);
+ grammar.AddSymbol(invokeSym);
+ grammar.SetSubtreeCount(invokeSym, nArgs, nArgs);
+
+ //allow invoke symbol everywhere, where the child of the startCutPoint was allowed
+ SetAllowedParentSymbols(grammar, startCutPoint.Child.Symbol, invokeSym);
+
+ if (nArgs > 0) {
+ //set allowed child symbols of invoke symbol
+ foreach (ISymbol child in grammar.Symbols) {
+ if (child.Name == invokeSym.Name) continue;
+ int i = 0;
+ foreach (CutPoint argumentCutPoint in argumentCutPoints) {
+ if (grammar.IsAllowedChildSymbol(argumentCutPoint.Parent.Symbol, child, argumentCutPoint.ChildIndex))
+ grammar.AddAllowedChildSymbol(invokeSym, child, i);
+ i++;
+ }
+ }
+ }
+ }
+
+
+
+ internal static void AddArgumentSymbol(ISymbolicExpressionTreeGrammar originalGrammar, ISymbolicExpressionTreeGrammar grammar, IEnumerable argumentIndexes, IEnumerable argumentCutPoints) {
+ foreach (var pair in argumentIndexes.Zip(argumentCutPoints, (a, b) => new { Index = a, CutPoint = b })) {
+ var argSymbol = new Argument(pair.Index);
+ grammar.AddSymbol(argSymbol);
+ grammar.SetSubtreeCount(argSymbol, 0, 0);
+
+ foreach (var symb in grammar.Symbols) {
+ if (symb is ProgramRootSymbol || symb is StartSymbol) continue;
+ if (originalGrammar.IsAllowedChildSymbol(symb, pair.CutPoint.Child.Symbol))
+ grammar.AddAllowedChildSymbol(symb, argSymbol);
+ else {
+ for (int i = 0; i < grammar.GetMaximumSubtreeCount(symb); i++) {
+ if (originalGrammar.IsAllowedChildSymbol(symb, pair.CutPoint.Child.Symbol, i))
+ grammar.AddAllowedChildSymbol(symb, argSymbol, i);
+ }
+ }
+ }
+ }
+ }
+
+ internal static void SetAllowedParentSymbols(ISymbolicExpressionTreeGrammar grammar, ISymbol symbol, ISymbol newSymbol) {
+ foreach (var symb in grammar.Symbols) {
+ if (symb is ProgramRootSymbol) continue;
+ if (newSymbol is Argument && symb is StartSymbol) continue;
+ if (grammar.IsAllowedChildSymbol(symb, symbol))
+ grammar.AddAllowedChildSymbol(symb, newSymbol);
+ else {
+ for (int i = 0; i < grammar.GetMaximumSubtreeCount(symb); i++) {
+ if (grammar.IsAllowedChildSymbol(symb, symbol, i))
+ grammar.AddAllowedChildSymbol(symb, newSymbol, i);
+ }
+ }
+ }
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/MultiSymbolicExpressionTreeArchitectureManipulator.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/MultiSymbolicExpressionTreeArchitectureManipulator.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/MultiSymbolicExpressionTreeArchitectureManipulator.cs (revision 9852)
@@ -0,0 +1,141 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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 HeuristicLab.Collections;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Operators;
+using HeuristicLab.Optimization;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ [Item("MultiSymbolicExpressionTreeArchitectureManipulator", "Randomly selects and applies one of its architecture manipulators every time it is called.")]
+ [StorableClass]
+ public sealed class MultiSymbolicExpressionTreeArchitectureManipulator : StochasticMultiBranch,
+ ISymbolicExpressionTreeArchitectureManipulator,
+ ISymbolicExpressionTreeSizeConstraintOperator,
+ IStochasticOperator {
+ private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
+ private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
+ private const string SymbolicExpressionTreeParameterName = "SymbolicExpressionTree";
+ private const string MaximumFunctionArgumentsParameterName = "MaximumFunctionArguments";
+ private const string MaximumFunctionDefinitionsParameterName = "MaximumFunctionDefinitions";
+
+ public override bool CanChangeName {
+ get { return false; }
+ }
+ protected override bool CreateChildOperation {
+ get { return true; }
+ }
+ #region Parameter properties
+ public ILookupParameter SymbolicExpressionTreeParameter {
+ get { return (ILookupParameter)Parameters[SymbolicExpressionTreeParameterName]; }
+ }
+ public IValueLookupParameter MaximumFunctionDefinitionsParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumFunctionDefinitionsParameterName]; }
+ }
+ public IValueLookupParameter MaximumFunctionArgumentsParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumFunctionArgumentsParameterName]; }
+ }
+ public IValueLookupParameter MaximumSymbolicExpressionTreeLengthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
+ }
+ public IValueLookupParameter MaximumSymbolicExpressionTreeDepthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
+ }
+ #endregion
+ #region Parameter Properties
+ public IntValue MaximumFunctionDefinitions {
+ get { return MaximumFunctionDefinitionsParameter.ActualValue; }
+ }
+ public IntValue MaximumFunctionArguments {
+ get { return MaximumFunctionArgumentsParameter.ActualValue; }
+ }
+ public IntValue MaximumSymbolicExpressionTreeLength {
+ get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
+ }
+ public IntValue MaximumSymbolicExpressionTreeDepth {
+ get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
+ }
+ #endregion
+
+
+ [StorableConstructor]
+ private MultiSymbolicExpressionTreeArchitectureManipulator(bool deserializing) : base(deserializing) { }
+ private MultiSymbolicExpressionTreeArchitectureManipulator(MultiSymbolicExpressionTreeArchitectureManipulator original, Cloner cloner) : base(original, cloner) { }
+ public MultiSymbolicExpressionTreeArchitectureManipulator()
+ : base() {
+ Parameters.Add(new LookupParameter(SymbolicExpressionTreeParameterName, "The symbolic expression tree on which the operator should be applied."));
+ Parameters.Add(new ValueLookupParameter(MaximumFunctionDefinitionsParameterName, "The maximal allowed number of automatically defined functions."));
+ Parameters.Add(new ValueLookupParameter(MaximumFunctionArgumentsParameterName, "The maximal allowed number of arguments of a automatically defined functions."));
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
+
+ List list = new List();
+ foreach (Type type in ApplicationManager.Manager.GetTypes(typeof(ISymbolicExpressionTreeManipulator))) {
+ if (this.GetType().Assembly != type.Assembly) continue;
+ if (typeof(IMultiOperator).IsAssignableFrom(type)) continue;
+ list.Add((ISymbolicExpressionTreeManipulator)Activator.CreateInstance(type));
+ }
+ CheckedItemList checkedItemList = new CheckedItemList();
+ checkedItemList.AddRange(list.OrderBy(op => op.Name));
+ Operators = checkedItemList.AsReadOnly();
+ Operators_ItemsAdded(this, new CollectionItemsChangedEventArgs>(Operators.CheckedItems));
+ }
+
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new MultiSymbolicExpressionTreeArchitectureManipulator(this, cloner);
+ }
+
+ protected override void Operators_ItemsReplaced(object sender, CollectionItemsChangedEventArgs> e) {
+ base.Operators_ItemsReplaced(sender, e);
+ ParameterizeManipulators();
+ }
+
+ protected override void Operators_ItemsAdded(object sender, CollectionItemsChangedEventArgs> e) {
+ base.Operators_ItemsAdded(sender, e);
+ ParameterizeManipulators();
+ }
+
+ private void ParameterizeManipulators() {
+ foreach (ISymbolicExpressionTreeArchitectureManipulator manipulator in Operators.OfType()) {
+ manipulator.MaximumFunctionArgumentsParameter.ActualName = MaximumFunctionArgumentsParameter.Name;
+ manipulator.MaximumFunctionDefinitionsParameter.ActualName = MaximumFunctionDefinitionsParameter.Name;
+ }
+ foreach (ISymbolicExpressionTreeSizeConstraintOperator manipulator in Operators.OfType()) {
+ manipulator.MaximumSymbolicExpressionTreeDepthParameter.ActualName = MaximumSymbolicExpressionTreeDepthParameter.Name;
+ manipulator.MaximumSymbolicExpressionTreeLengthParameter.ActualName = MaximumSymbolicExpressionTreeLengthParameter.Name;
+ }
+ foreach (ISymbolicExpressionTreeManipulator manipulator in Operators.OfType()) {
+ manipulator.SymbolicExpressionTreeParameter.ActualName = SymbolicExpressionTreeParameter.Name;
+ }
+ foreach (IStochasticOperator manipulator in Operators.OfType()) {
+ manipulator.RandomParameter.ActualName = RandomParameter.Name;
+ }
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineCreater.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineCreater.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineCreater.cs (revision 9852)
@@ -0,0 +1,248 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// Manipulates a symbolic expression by adding one new function-defining branch containing
+ /// a proportion of a preexisting branch and by creating a reference to the new branch.
+ /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 97
+ ///
+ [Item("SubroutineCreater", "Manipulates a symbolic expression by adding one new function-defining branch containing a proportion of a preexisting branch and by creating a reference to the new branch. As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 97")]
+ [StorableClass]
+ public sealed class SubroutineCreater : SymbolicExpressionTreeArchitectureManipulator, ISymbolicExpressionTreeSizeConstraintOperator {
+ private const double ARGUMENT_CUTOFF_PROBABILITY = 0.05;
+ private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
+ private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
+ #region Parameter Properties
+ public IValueLookupParameter MaximumSymbolicExpressionTreeLengthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
+ }
+ public IValueLookupParameter MaximumSymbolicExpressionTreeDepthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
+ }
+ #endregion
+ #region Properties
+ public IntValue MaximumSymbolicExpressionTreeLength {
+ get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
+ }
+ public IntValue MaximumSymbolicExpressionTreeDepth {
+ get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
+ }
+ #endregion
+ [StorableConstructor]
+ private SubroutineCreater(bool deserializing) : base(deserializing) { }
+ private SubroutineCreater(SubroutineCreater original, Cloner cloner) : base(original, cloner) { }
+ public SubroutineCreater()
+ : base() {
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
+ }
+
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new SubroutineCreater(this, cloner);
+ }
+
+ public override sealed void ModifyArchitecture(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
+ CreateSubroutine(random, symbolicExpressionTree, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
+ }
+
+ public static bool CreateSubroutine(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ int maxTreeLength, int maxTreeDepth,
+ int maxFunctionDefinitions, int maxFunctionArguments) {
+ var functionDefiningBranches = symbolicExpressionTree.IterateNodesPrefix().OfType();
+ if (functionDefiningBranches.Count() >= maxFunctionDefinitions)
+ // allowed maximum number of ADF reached => abort
+ return false;
+ if (symbolicExpressionTree.Length + 4 > maxTreeLength)
+ // defining a new function causes an length increase by 4 nodes (max) if the max tree length is reached => abort
+ return false;
+ string formatString = new StringBuilder().Append('0', (int)Math.Log10(maxFunctionDefinitions * 10 - 1)).ToString(); // >= 100 functions => ###
+ var allowedFunctionNames = from index in Enumerable.Range(0, maxFunctionDefinitions)
+ select "ADF" + index.ToString(formatString);
+
+ // select a random body (either the result producing branch or an ADF branch)
+ var bodies = from node in symbolicExpressionTree.Root.Subtrees
+ select new { Tree = node, Length = node.GetLength() };
+ var totalNumberOfBodyNodes = bodies.Select(x => x.Length).Sum();
+ int r = random.Next(totalNumberOfBodyNodes);
+ int aggregatedNumberOfBodyNodes = 0;
+ ISymbolicExpressionTreeNode selectedBody = null;
+ foreach (var body in bodies) {
+ aggregatedNumberOfBodyNodes += body.Length;
+ if (aggregatedNumberOfBodyNodes > r)
+ selectedBody = body.Tree;
+ }
+ // sanity check
+ if (selectedBody == null) throw new InvalidOperationException();
+
+ // select a random cut point in the selected branch
+ var allCutPoints = (from parent in selectedBody.IterateNodesPrefix()
+ from subtree in parent.Subtrees
+ select new CutPoint(parent, subtree)).ToList();
+ if (allCutPoints.Count() == 0)
+ // no cut points => abort
+ return false;
+ string newFunctionName = allowedFunctionNames.Except(functionDefiningBranches.Select(x => x.FunctionName)).First();
+ var selectedCutPoint = allCutPoints.SelectRandom(random);
+ // select random branches as argument cut-off points (replaced by argument terminal nodes in the function)
+ List argumentCutPoints = SelectRandomArgumentBranches(selectedCutPoint.Child, random, ARGUMENT_CUTOFF_PROBABILITY, maxFunctionArguments);
+ ISymbolicExpressionTreeNode functionBody = selectedCutPoint.Child;
+ // disconnect the function body from the tree
+ selectedCutPoint.Parent.RemoveSubtree(selectedCutPoint.ChildIndex);
+ // disconnect the argument branches from the function
+ functionBody = DisconnectBranches(functionBody, argumentCutPoints);
+ // insert a function invocation symbol instead
+ var invokeNode = (InvokeFunctionTreeNode)(new InvokeFunction(newFunctionName)).CreateTreeNode();
+ selectedCutPoint.Parent.InsertSubtree(selectedCutPoint.ChildIndex, invokeNode);
+ // add the branches selected as argument as subtrees of the function invocation node
+ foreach (var argumentCutPoint in argumentCutPoints)
+ invokeNode.AddSubtree(argumentCutPoint.Child);
+
+ // insert a new function defining branch
+ var defunNode = (DefunTreeNode)(new Defun()).CreateTreeNode();
+ defunNode.FunctionName = newFunctionName;
+ defunNode.AddSubtree(functionBody);
+ symbolicExpressionTree.Root.AddSubtree(defunNode);
+ // the grammar in the newly defined function is a clone of the grammar of the originating branch
+ defunNode.SetGrammar((ISymbolicExpressionTreeGrammar)selectedBody.Grammar.Clone());
+
+ var allowedChildSymbols = selectedBody.Grammar.GetAllowedChildSymbols(selectedBody.Symbol);
+ foreach (var allowedChildSymbol in allowedChildSymbols)
+ defunNode.Grammar.AddAllowedChildSymbol(defunNode.Symbol, allowedChildSymbol);
+ var maxSubtrees = selectedBody.Grammar.GetMaximumSubtreeCount(selectedBody.Symbol);
+ for (int i = 0; i < maxSubtrees; i++) {
+ foreach (var allowedChildSymbol in selectedBody.Grammar.GetAllowedChildSymbols(selectedBody.Symbol, i))
+ defunNode.Grammar.AddAllowedChildSymbol(defunNode.Symbol, allowedChildSymbol);
+ }
+
+ // remove all argument symbols from grammar except that one contained in cutpoints
+ var oldArgumentSymbols = selectedBody.Grammar.Symbols.OfType().ToList();
+ foreach (var oldArgSymb in oldArgumentSymbols)
+ defunNode.Grammar.RemoveSymbol(oldArgSymb);
+ // find unique argument indexes and matching symbols in the function defining branch
+ var newArgumentIndexes = (from node in defunNode.IterateNodesPrefix().OfType()
+ select node.Symbol.ArgumentIndex).Distinct();
+ // add argument symbols to grammar of function defining branch
+ GrammarModifier.AddArgumentSymbol(selectedBody.Grammar, defunNode.Grammar, newArgumentIndexes, argumentCutPoints);
+ defunNode.NumberOfArguments = newArgumentIndexes.Count();
+ if (defunNode.NumberOfArguments != argumentCutPoints.Count) throw new InvalidOperationException();
+ // add invoke symbol for newly defined function to the original branch
+ GrammarModifier.AddInvokeSymbol(selectedBody.Grammar, defunNode.FunctionName, defunNode.NumberOfArguments, selectedCutPoint, argumentCutPoints);
+
+ // when the new function body was taken from another function definition
+ // add invoke symbol for newly defined function to all branches that are allowed to invoke the original branch
+ if (selectedBody.Symbol is Defun) {
+ var originalFunctionDefinition = selectedBody as DefunTreeNode;
+ foreach (var subtree in symbolicExpressionTree.Root.Subtrees) {
+ var originalBranchInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType()
+ where symb.FunctionName == originalFunctionDefinition.FunctionName
+ select symb).SingleOrDefault();
+ // when the original branch can be invoked from the subtree then also allow invocation of the function
+ if (originalBranchInvokeSymbol != null) {
+ GrammarModifier.AddInvokeSymbol(subtree.Grammar, defunNode.FunctionName, defunNode.NumberOfArguments, selectedCutPoint, argumentCutPoints);
+ }
+ }
+ }
+ return true;
+ }
+
+ private static ISymbolicExpressionTreeNode DisconnectBranches(ISymbolicExpressionTreeNode node, List argumentCutPoints) {
+ int argumentIndex = argumentCutPoints.FindIndex(x => x.Child == node);
+ if (argumentIndex != -1) {
+ var argSymbol = new Argument(argumentIndex);
+ return argSymbol.CreateTreeNode();
+ }
+ // remove the subtrees so that we can clone only the root node
+ List subtrees = new List(node.Subtrees);
+ while (node.Subtrees.Count() > 0) node.RemoveSubtree(0);
+ // recursively apply function for subtrees or append a argument terminal node
+ foreach (var subtree in subtrees) {
+ node.AddSubtree(DisconnectBranches(subtree, argumentCutPoints));
+ }
+ return node;
+ }
+
+ private static List SelectRandomArgumentBranches(ISymbolicExpressionTreeNode selectedRoot,
+ IRandom random,
+ double cutProbability,
+ int maxArguments) {
+ // breadth first determination of argument cut-off points
+ // we must make sure that we cut off all original argument nodes and that the number of new argument is smaller than the limit
+ List argumentBranches = new List();
+ if (selectedRoot is ArgumentTreeNode) {
+ argumentBranches.Add(new CutPoint(selectedRoot.Parent, selectedRoot));
+ return argumentBranches;
+ } else {
+ // get the number of argument nodes (which must be cut-off) in the sub-trees
+ var numberOfArgumentsInSubtrees = (from subtree in selectedRoot.Subtrees
+ let nArgumentsInTree = subtree.IterateNodesPrefix().OfType().Count()
+ select nArgumentsInTree).ToList();
+ // determine the minimal number of new argument nodes for each sub-tree
+ //if we exceed the maxArguments return the same cutpoint as the start cutpoint to create a ADF that returns only its argument
+ var minNewArgumentsForSubtrees = numberOfArgumentsInSubtrees.Select(x => x > 0 ? 1 : 0).ToList();
+ if (minNewArgumentsForSubtrees.Sum() > maxArguments) {
+ argumentBranches.Add(new CutPoint(selectedRoot.Parent, selectedRoot));
+ return argumentBranches;
+ }
+ // cut-off in the sub-trees in random order
+ var randomIndexes = (from index in Enumerable.Range(0, selectedRoot.Subtrees.Count())
+ select new { Index = index, OrderValue = random.NextDouble() })
+ .OrderBy(x => x.OrderValue)
+ .Select(x => x.Index);
+ foreach (var subtreeIndex in randomIndexes) {
+ var subtree = selectedRoot.GetSubtree(subtreeIndex);
+ minNewArgumentsForSubtrees[subtreeIndex] = 0;
+ // => cut-off at 0..n points somewhere in the current sub-tree
+ // determine the maximum number of new arguments that should be created in the branch
+ // as the maximum for the whole branch minus already added arguments minus minimal number of arguments still left
+ int maxArgumentsFromBranch = maxArguments - argumentBranches.Count - minNewArgumentsForSubtrees.Sum();
+ // when no argument is allowed from the current branch then we have to include the whole branch into the function
+ // otherwise: choose randomly wether to cut off immediately or wether to extend the function body into the branch
+ if (maxArgumentsFromBranch == 0) {
+ // don't cut at all => the whole sub-tree branch is included in the function body
+ // (we already checked ahead of time that there are no arguments left over in the subtree)
+ } else if (random.NextDouble() >= cutProbability) {
+ argumentBranches.AddRange(SelectRandomArgumentBranches(subtree, random, cutProbability, maxArgumentsFromBranch));
+ } else {
+ // cut-off at current sub-tree
+ argumentBranches.Add(new CutPoint(subtree.Parent, subtree));
+ }
+ }
+ return argumentBranches;
+ }
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineDeleter.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineDeleter.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineDeleter.cs (revision 9852)
@@ -0,0 +1,115 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Linq;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// Manipulates a symbolic expression by deleting a preexisting function-defining branch.
+ /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 108
+ ///
+ [Item("SubroutineDeleter", "Manipulates a symbolic expression by deleting a preexisting function-defining branch. As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 108")]
+ [StorableClass]
+ public sealed class SubroutineDeleter : SymbolicExpressionTreeArchitectureManipulator {
+ [StorableConstructor]
+ private SubroutineDeleter(bool deserializing) : base(deserializing) { }
+ private SubroutineDeleter(SubroutineDeleter original, Cloner cloner) : base(original, cloner) { }
+ public SubroutineDeleter() : base() { }
+
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new SubroutineDeleter(this, cloner);
+ }
+
+ public override sealed void ModifyArchitecture(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
+ DeleteSubroutine(random, symbolicExpressionTree, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
+ }
+
+ public static bool DeleteSubroutine(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ int maxFunctionDefinitions, int maxFunctionArguments) {
+ var functionDefiningBranches = symbolicExpressionTree.IterateNodesPrefix().OfType();
+
+ if (functionDefiningBranches.Count() == 0)
+ // no ADF to delete => abort
+ return false;
+ var selectedDefunBranch = functionDefiningBranches.SelectRandom(random);
+ // remove the selected defun
+ int defunSubtreeIndex = symbolicExpressionTree.Root.IndexOfSubtree(selectedDefunBranch);
+ symbolicExpressionTree.Root.RemoveSubtree(defunSubtreeIndex);
+
+ // remove references to deleted function
+ foreach (var subtree in symbolicExpressionTree.Root.Subtrees.OfType()) {
+ var matchingInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType()
+ where symb.FunctionName == selectedDefunBranch.FunctionName
+ select symb).SingleOrDefault();
+ if (matchingInvokeSymbol != null) {
+ subtree.Grammar.RemoveSymbol(matchingInvokeSymbol);
+ }
+ }
+
+ DeletionByRandomRegeneration(random, symbolicExpressionTree, selectedDefunBranch);
+ return true;
+ }
+
+ private static void DeletionByRandomRegeneration(IRandom random, ISymbolicExpressionTree symbolicExpressionTree, DefunTreeNode selectedDefunBranch) {
+ // find first invocation and replace it with a randomly generated tree
+ // can't find all invocations in one step because once we replaced a top level invocation
+ // the invocations below it are removed already
+ var invocationCutPoint = (from node in symbolicExpressionTree.IterateNodesPrefix()
+ from subtree in node.Subtrees.OfType()
+ where subtree.Symbol.FunctionName == selectedDefunBranch.FunctionName
+ select new CutPoint(node, subtree)).FirstOrDefault();
+ while (invocationCutPoint != null) {
+ // deletion by random regeneration
+ ISymbolicExpressionTreeNode replacementTree = null;
+ var allowedSymbolsList = invocationCutPoint.Parent.Grammar.GetAllowedChildSymbols(invocationCutPoint.Parent.Symbol, invocationCutPoint.ChildIndex).ToList();
+ var weights = allowedSymbolsList.Select(s => s.InitialFrequency);
+ var selectedSymbol = allowedSymbolsList.SelectRandom(weights, random);
+
+ int minPossibleLength = invocationCutPoint.Parent.Grammar.GetMinimumExpressionLength(selectedSymbol);
+ int maxLength = Math.Max(minPossibleLength, invocationCutPoint.Child.GetLength());
+ int minPossibleDepth = invocationCutPoint.Parent.Grammar.GetMinimumExpressionDepth(selectedSymbol);
+ int maxDepth = Math.Max(minPossibleDepth, invocationCutPoint.Child.GetDepth());
+ replacementTree = selectedSymbol.CreateTreeNode();
+ if (replacementTree.HasLocalParameters)
+ replacementTree.ResetLocalParameters(random);
+ invocationCutPoint.Parent.RemoveSubtree(invocationCutPoint.ChildIndex);
+ invocationCutPoint.Parent.InsertSubtree(invocationCutPoint.ChildIndex, replacementTree);
+
+ ProbabilisticTreeCreator.PTC2(random, replacementTree, maxLength, maxDepth);
+
+ invocationCutPoint = (from node in symbolicExpressionTree.IterateNodesPrefix()
+ from subtree in node.Subtrees.OfType()
+ where subtree.Symbol.FunctionName == selectedDefunBranch.FunctionName
+ select new CutPoint(node, subtree)).FirstOrDefault();
+ }
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineDuplicater.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineDuplicater.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SubroutineDuplicater.cs (revision 9852)
@@ -0,0 +1,137 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// Manipulates a symbolic expression by duplicating a preexisting function-defining branch.
+ /// As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 88
+ ///
+ [Item("SubroutineDuplicater", "Manipulates a symbolic expression by duplicating a preexisting function-defining branch. As described in Koza, Bennett, Andre, Keane, Genetic Programming III - Darwinian Invention and Problem Solving, 1999, pp. 88")]
+ [StorableClass]
+ public sealed class SubroutineDuplicater : SymbolicExpressionTreeArchitectureManipulator {
+ [StorableConstructor]
+ private SubroutineDuplicater(bool deserializing) : base(deserializing) { }
+ private SubroutineDuplicater(SubroutineDuplicater original, Cloner cloner)
+ : base(original, cloner) {
+ }
+ public SubroutineDuplicater() : base() { }
+
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new SubroutineDuplicater(this, cloner);
+ }
+
+ public override sealed void ModifyArchitecture(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ IntValue maxFunctionDefinitions, IntValue maxFunctionArguments) {
+ DuplicateSubroutine(random, symbolicExpressionTree, maxFunctionDefinitions.Value, maxFunctionArguments.Value);
+ }
+
+ public static bool DuplicateSubroutine(
+ IRandom random,
+ ISymbolicExpressionTree symbolicExpressionTree,
+ int maxFunctionDefinitions, int maxFunctionArguments) {
+ var functionDefiningBranches = symbolicExpressionTree.IterateNodesPrefix().OfType();
+ if (functionDefiningBranches.Count() == 0 || functionDefiningBranches.Count() == maxFunctionDefinitions)
+ // no function defining branches to duplicate or already reached the max number of ADFs
+ return false;
+
+ string formatString = new StringBuilder().Append('0', (int)Math.Log10(maxFunctionDefinitions) + 1).ToString(); // >= 100 functions => ###
+ var allowedFunctionNames = from index in Enumerable.Range(0, maxFunctionDefinitions)
+ select "ADF" + index.ToString(formatString);
+ var selectedBranch = functionDefiningBranches.SelectRandom(random);
+ var duplicatedDefunBranch = (DefunTreeNode)selectedBranch.Clone();
+ string newFunctionName = allowedFunctionNames.Except(UsedFunctionNames(symbolicExpressionTree)).First();
+ duplicatedDefunBranch.FunctionName = newFunctionName;
+ symbolicExpressionTree.Root.AddSubtree(duplicatedDefunBranch);
+ duplicatedDefunBranch.SetGrammar((ISymbolicExpressionTreeGrammar)selectedBranch.Grammar.Clone());
+
+ var allowedChildSymbols = selectedBranch.Grammar.GetAllowedChildSymbols(selectedBranch.Symbol);
+ foreach (var allowedChildSymbol in allowedChildSymbols)
+ duplicatedDefunBranch.Grammar.AddAllowedChildSymbol(duplicatedDefunBranch.Symbol, allowedChildSymbol);
+ var maxSubtrees = selectedBranch.Grammar.GetMaximumSubtreeCount(selectedBranch.Symbol);
+ for (int i = 0; i < maxSubtrees; i++) {
+ foreach (var allowedChildSymbol in selectedBranch.Grammar.GetAllowedChildSymbols(selectedBranch.Symbol, i))
+ duplicatedDefunBranch.Grammar.AddAllowedChildSymbol(duplicatedDefunBranch.Symbol, allowedChildSymbol);
+ }
+
+ // add an invoke symbol for each branch that is allowed to invoke the original function
+ foreach (var subtree in symbolicExpressionTree.Root.Subtrees.OfType()) {
+ var matchingInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType()
+ where symb.FunctionName == selectedBranch.FunctionName
+ select symb).SingleOrDefault();
+ if (matchingInvokeSymbol != null) {
+ var invokeSymbol = new InvokeFunction(duplicatedDefunBranch.FunctionName);
+ subtree.Grammar.AddSymbol(invokeSymbol);
+ subtree.Grammar.SetSubtreeCount(invokeSymbol, duplicatedDefunBranch.NumberOfArguments, duplicatedDefunBranch.NumberOfArguments);
+
+ foreach (ISymbol symbol in subtree.Grammar.Symbols) {
+ if (subtree.Grammar.IsAllowedChildSymbol(symbol, matchingInvokeSymbol))
+ subtree.Grammar.AddAllowedChildSymbol(symbol, invokeSymbol);
+ else {
+ for (int i = 0; i < subtree.Grammar.GetMaximumSubtreeCount(symbol); i++)
+ if (subtree.Grammar.IsAllowedChildSymbol(symbol, matchingInvokeSymbol, i))
+ subtree.Grammar.AddAllowedChildSymbol(symbol, invokeSymbol, i);
+ }
+ }
+
+ foreach (ISymbol symbol in subtree.Grammar.GetAllowedChildSymbols(matchingInvokeSymbol))
+ if (symbol != invokeSymbol) //avoid duplicate entry invokesymbol / invokesymbol
+ subtree.Grammar.AddAllowedChildSymbol(invokeSymbol, symbol);
+ for (int i = 0; i < subtree.Grammar.GetMaximumSubtreeCount(matchingInvokeSymbol); i++) {
+ foreach (ISymbol symbol in subtree.Grammar.GetAllowedChildSymbols(matchingInvokeSymbol, i).Except(subtree.Grammar.GetAllowedChildSymbols(matchingInvokeSymbol)))
+ subtree.Grammar.AddAllowedChildSymbol(invokeSymbol, symbol, i);
+ }
+ }
+ // in the current subtree:
+ // for all invoke nodes of the original function replace the invoke of the original function with an invoke of the new function randomly
+ var originalFunctionInvocations = from node in subtree.IterateNodesPrefix().OfType()
+ where node.Symbol.FunctionName == selectedBranch.FunctionName
+ select node;
+ foreach (var originalFunctionInvokeNode in originalFunctionInvocations) {
+ var newInvokeSymbol = (from symb in subtree.Grammar.Symbols.OfType()
+ where symb.FunctionName == duplicatedDefunBranch.FunctionName
+ select symb).Single();
+ // flip coin wether to replace with newly defined function
+ if (random.NextDouble() < 0.5) {
+ originalFunctionInvokeNode.Symbol = newInvokeSymbol;
+ }
+ }
+ }
+ return true;
+ }
+
+ private static IEnumerable UsedFunctionNames(ISymbolicExpressionTree symbolicExpressionTree) {
+ return from node in symbolicExpressionTree.IterateNodesPrefix()
+ where node.Symbol is Defun
+ select ((DefunTreeNode)node).FunctionName;
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SymbolicExpressionTreeArchitectureManipulator.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SymbolicExpressionTreeArchitectureManipulator.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/ArchitectureManipulators/SymbolicExpressionTreeArchitectureManipulator.cs (revision 9852)
@@ -0,0 +1,74 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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 HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ ///
+ /// Base class for architecture altering operators for symbolic expression trees.
+ ///
+ [StorableClass]
+ public abstract class SymbolicExpressionTreeArchitectureManipulator : SymbolicExpressionTreeManipulator, ISymbolicExpressionTreeArchitectureManipulator {
+ private const string MaximumFunctionArgumentsParameterName = "MaximumFunctionArguments";
+ private const string MaximumFunctionDefinitionsParameterName = "MaximumFunctionDefinitions";
+ public override bool CanChangeName {
+ get { return false; }
+ }
+ #region parameter properties
+ public IValueLookupParameter MaximumFunctionDefinitionsParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumFunctionDefinitionsParameterName]; }
+ }
+ public IValueLookupParameter MaximumFunctionArgumentsParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumFunctionArgumentsParameterName]; }
+ }
+ #endregion
+ #region properties
+ public IntValue MaximumFunctionDefinitions {
+ get { return MaximumFunctionDefinitionsParameter.ActualValue; }
+ }
+ public IntValue MaximumFunctionArguments {
+ get { return MaximumFunctionArgumentsParameter.ActualValue; }
+ }
+ #endregion
+ [StorableConstructor]
+ protected SymbolicExpressionTreeArchitectureManipulator(bool deserializing) : base(deserializing) { }
+ protected SymbolicExpressionTreeArchitectureManipulator(SymbolicExpressionTreeArchitectureManipulator original, Cloner cloner) : base(original, cloner) { }
+ public SymbolicExpressionTreeArchitectureManipulator()
+ : base() {
+ Parameters.Add(new ValueLookupParameter(MaximumFunctionDefinitionsParameterName, "The maximal allowed number of automatically defined functions."));
+ Parameters.Add(new ValueLookupParameter(MaximumFunctionArgumentsParameterName, "The maximal allowed number of arguments of a automatically defined functions."));
+ }
+
+ protected override sealed void Manipulate(IRandom random, ISymbolicExpressionTree symbolicExpressionTree) {
+ ModifyArchitecture(random, symbolicExpressionTree, MaximumFunctionDefinitions, MaximumFunctionArguments);
+ }
+
+ public abstract void ModifyArchitecture(
+ IRandom random,
+ ISymbolicExpressionTree tree,
+ IntValue maxFunctionDefinitions,
+ IntValue maxFunctionArguments);
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/Instruction.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/Instruction.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/Instruction.cs (revision 9852)
@@ -0,0 +1,35 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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
+
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ // total size of this class should be small to improve cache access while executing the code
+ public class Instruction {
+ // the tree node can hold additional data that is necessary for the execution of this instruction
+ public ISymbolicExpressionTreeNode dynamicNode;
+ // op code of the function that determines what operation should be executed
+ public byte opCode;
+ // number of arguments of the current instruction
+ public byte nArguments;
+ // an optional object value (addresses for calls, argument index for arguments)
+ public object data;
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/LinearInstruction.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/LinearInstruction.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/LinearInstruction.cs (revision 9852)
@@ -0,0 +1,30 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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
+
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ // total size of this class should be small to improve cache access while executing the code
+ public class LinearInstruction : Instruction {
+ public double value;
+ public byte childIndex;
+ public bool skip;
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/SymbolicExpressionTreeCompiler.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/SymbolicExpressionTreeCompiler.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/SymbolicExpressionTreeCompiler.cs (revision 9852)
@@ -0,0 +1,80 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ public static class SymbolicExpressionTreeCompiler {
+
+ public static Instruction[] Compile(ISymbolicExpressionTree tree, Func opCodeMapper) {
+ return Compile(tree, opCodeMapper, Enumerable.Empty>());
+ }
+ public static Instruction[] Compile(ISymbolicExpressionTree tree, Func opCodeMapper, IEnumerable> postInstructionCompiledHooks) {
+ Dictionary entryPoint = new Dictionary();
+ List code = new List();
+ // compile main body branches
+ foreach (var branch in tree.Root.GetSubtree(0).Subtrees) {
+ code.AddRange(Compile(branch, opCodeMapper, postInstructionCompiledHooks));
+ }
+ // compile function branches
+ var functionBranches = from node in tree.IterateNodesPrefix()
+ where node.Symbol is Defun
+ select node;
+ foreach (DefunTreeNode branch in functionBranches) {
+ if (code.Count > ushort.MaxValue) throw new ArgumentException("Code for the tree is too long (> ushort.MaxValue).");
+ entryPoint[branch.FunctionName] = (ushort)code.Count;
+ code.AddRange(Compile(branch.GetSubtree(0), opCodeMapper, postInstructionCompiledHooks));
+ }
+ // address of all functions is fixed now
+ // iterate through code again and fill in the jump locations
+ for (int i = 0; i < code.Count; i++) {
+ Instruction instr = code[i];
+ if (instr.dynamicNode.Symbol is InvokeFunction) {
+ var invokeNode = (InvokeFunctionTreeNode)instr.dynamicNode;
+ instr.data = entryPoint[invokeNode.Symbol.FunctionName];
+ }
+ }
+
+ return code.ToArray();
+ }
+
+ private static IEnumerable Compile(ISymbolicExpressionTreeNode branch, Func opCodeMapper, IEnumerable> postInstructionCompiledHooks) {
+ foreach (var node in branch.IterateNodesPrefix()) {
+ Instruction instr = new Instruction();
+ int subtreesCount = node.SubtreeCount;
+ if (subtreesCount > 255) throw new ArgumentException("Number of subtrees is too big (>255)");
+ instr.nArguments = (byte)subtreesCount;
+ instr.opCode = opCodeMapper(node);
+ if (node.Symbol is Argument) {
+ var argNode = (ArgumentTreeNode)node;
+ instr.data = (ushort)argNode.Symbol.ArgumentIndex;
+ }
+ instr.dynamicNode = node;
+ foreach (var hook in postInstructionCompiledHooks) {
+ instr = hook(instr);
+ }
+ yield return instr;
+ }
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/SymbolicExpressionTreeLinearCompiler.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/SymbolicExpressionTreeLinearCompiler.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Compiler/SymbolicExpressionTreeLinearCompiler.cs (revision 9852)
@@ -0,0 +1,43 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ public static class SymbolicExpressionTreeLinearCompiler {
+ public static LinearInstruction[] Compile(ISymbolicExpressionTree tree, Func opCodeMapper) {
+ var root = tree.Root.GetSubtree(0).GetSubtree(0);
+ var code = new LinearInstruction[root.GetLength()];
+ code[0] = new LinearInstruction { dynamicNode = root, nArguments = (byte)root.SubtreeCount, opCode = opCodeMapper(root) };
+ int c = 1, i = 0;
+ foreach (var node in root.IterateNodesBreadth()) {
+ for (int j = 0; j < node.SubtreeCount; ++j) {
+ var s = node.GetSubtree(j);
+ code[c + j] = new LinearInstruction { dynamicNode = s, nArguments = (byte)s.SubtreeCount, opCode = opCodeMapper(s) };
+ }
+ code[i].childIndex = (byte)c;
+ c += node.SubtreeCount;
+ ++i;
+ }
+ return code;
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/FullTreeCreator.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/FullTreeCreator.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/FullTreeCreator.cs (revision 9852)
@@ -0,0 +1,207 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Linq;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ [NonDiscoverableType]
+ [StorableClass]
+ [Item("FullTreeCreator", "An operator that creates new symbolic expression trees using the 'Full' method")]
+ public class FullTreeCreator : SymbolicExpressionTreeCreator,
+ ISymbolicExpressionTreeSizeConstraintOperator,
+ ISymbolicExpressionTreeGrammarBasedOperator {
+ private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
+ private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
+ private const string SymbolicExpressionTreeGrammarParameterName = "SymbolicExpressionTreeGrammar";
+ private const string ClonedSymbolicExpressionTreeGrammarParameterName = "ClonedSymbolicExpressionTreeGrammar";
+
+ #region Parameter Properties
+ public IValueLookupParameter MaximumSymbolicExpressionTreeLengthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
+ }
+
+ public IValueLookupParameter MaximumSymbolicExpressionTreeDepthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
+ }
+
+ public IValueLookupParameter SymbolicExpressionTreeGrammarParameter {
+ get { return (IValueLookupParameter)Parameters[SymbolicExpressionTreeGrammarParameterName]; }
+ }
+
+ public ILookupParameter ClonedSymbolicExpressionTreeGrammarParameter {
+ get { return (ILookupParameter)Parameters[ClonedSymbolicExpressionTreeGrammarParameterName]; }
+ }
+
+ #endregion
+ #region Properties
+ public IntValue MaximumSymbolicExpressionTreeDepth {
+ get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
+ }
+
+ public IntValue MaximumSymbolicExpressionTreeLength {
+ get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
+ }
+
+ public ISymbolicExpressionGrammar ClonedSymbolicExpressionTreeGrammar {
+ get { return ClonedSymbolicExpressionTreeGrammarParameter.ActualValue; }
+ }
+
+ #endregion
+
+ [StorableConstructor]
+ protected FullTreeCreator(bool deserializing) : base(deserializing) { }
+ protected FullTreeCreator(FullTreeCreator original, Cloner cloner) : base(original, cloner) { }
+
+ public FullTreeCreator()
+ : base() {
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeLengthParameterName,
+ "The maximal length (number of nodes) of the symbolic expression tree (this parameter is ignored)."));
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeDepthParameterName,
+ "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
+ Parameters.Add(new ValueLookupParameter(SymbolicExpressionTreeGrammarParameterName,
+ "The tree grammar that defines the correct syntax of symbolic expression trees that should be created."));
+ Parameters.Add(new LookupParameter(ClonedSymbolicExpressionTreeGrammarParameterName,
+ "An immutable clone of the concrete grammar that is actually used to create and manipulate trees."));
+ }
+
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new FullTreeCreator(this, cloner);
+ }
+
+ public override IOperation Apply() {
+ if (ClonedSymbolicExpressionTreeGrammarParameter.ActualValue == null) {
+ SymbolicExpressionTreeGrammarParameter.ActualValue.ReadOnly = true;
+ IScope globalScope = ExecutionContext.Scope;
+ while (globalScope.Parent != null)
+ globalScope = globalScope.Parent;
+
+ globalScope.Variables.Add(new Variable(ClonedSymbolicExpressionTreeGrammarParameterName,
+ (ISymbolicExpressionGrammar)SymbolicExpressionTreeGrammarParameter.ActualValue.Clone()));
+ }
+ return base.Apply();
+ }
+
+ protected override ISymbolicExpressionTree Create(IRandom random) {
+ return Create(random, ClonedSymbolicExpressionTreeGrammar, MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
+ }
+
+ public override ISymbolicExpressionTree CreateTree(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
+ return Create(random, grammar, maxTreeLength, maxTreeDepth);
+ }
+
+ ///
+ /// Create a symbolic expression tree using the 'Full' method.
+ /// Function symbols are used for all nodes situated on a level above the maximum tree depth.
+ /// Nodes on the last tree level will have Terminal symbols.
+ ///
+ /// Random generator
+ /// Available tree grammar
+ /// Maximum tree depth
+ /// Maximum tree length. This parameter is not used.
+ ///
+ public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
+ var tree = new SymbolicExpressionTree();
+ var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
+ if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
+ rootNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
+
+ var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
+ if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
+ startNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
+
+ rootNode.AddSubtree(startNode);
+
+ Create(random, startNode, maxTreeDepth - 2);
+ tree.Root = rootNode;
+ return tree;
+ }
+
+ public static void Create(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
+ // make sure it is possible to create a trees smaller than maxDepth
+ if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
+ throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
+
+
+ int arity = seedNode.Grammar.GetMaximumSubtreeCount(seedNode.Symbol);
+ // Throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree.
+ if (arity <= 0)
+ throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
+
+ var allowedSymbols = seedNode.Grammar.AllowedSymbols
+ .Where(s => s.InitialFrequency > 0.0 && seedNode.Grammar.GetMaximumSubtreeCount(s) > 0)
+ .ToList();
+
+ for (var i = 0; i < arity; i++) {
+ var possibleSymbols = allowedSymbols
+ .Where(s => seedNode.Grammar.IsAllowedChildSymbol(seedNode.Symbol, s, i))
+ .ToList();
+ var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
+ var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
+ var tree = selectedSymbol.CreateTreeNode();
+ if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
+ seedNode.AddSubtree(tree);
+ }
+
+ // Only iterate over the non-terminal nodes (those which have arity > 0)
+ // Start from depth 2 since the first two levels are formed by the rootNode and the seedNode
+ foreach (var subTree in seedNode.Subtrees)
+ if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
+ RecursiveCreate(random, subTree, 2, maxDepth);
+ }
+
+ private static void RecursiveCreate(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
+ var arity = root.Grammar.GetMaximumSubtreeCount(root.Symbol);
+ // In the 'Full' grow method, we cannot have terminals on the intermediate tree levels.
+ if (arity <= 0)
+ throw new ArgumentException("Cannot grow node of arity zero. Expected a function node.");
+
+ var allowedSymbols = root.Grammar.AllowedSymbols
+ .Where(s => s.InitialFrequency > 0.0)
+ .ToList();
+
+ for (var i = 0; i < arity; i++) {
+ var possibleSymbols = allowedSymbols
+ .Where(s => root.Grammar.IsAllowedChildSymbol(root.Symbol, s, i) &&
+ root.Grammar.GetMinimumExpressionDepth(s) - 1 <= maxDepth - currentDepth &&
+ root.Grammar.GetMaximumExpressionDepth(s) > maxDepth - currentDepth)
+ .ToList();
+ if (!possibleSymbols.Any())
+ throw new InvalidOperationException("No symbols are available for the tree.");
+ var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
+ var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
+ var tree = selectedSymbol.CreateTreeNode();
+ if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
+ root.AddSubtree(tree);
+ }
+
+ foreach (var subTree in root.Subtrees)
+ if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
+ RecursiveCreate(random, subTree, currentDepth + 1, maxDepth);
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/GrowTreeCreator.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/GrowTreeCreator.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/GrowTreeCreator.cs (revision 9852)
@@ -0,0 +1,210 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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.Linq;
+using HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ [NonDiscoverableType]
+ [StorableClass]
+ [Item("GrowTreeCreator", "An operator that creates new symbolic expression trees using the 'Grow' method")]
+ public class GrowTreeCreator : SymbolicExpressionTreeCreator,
+ ISymbolicExpressionTreeSizeConstraintOperator,
+ ISymbolicExpressionTreeGrammarBasedOperator {
+ private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
+ private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
+ private const string SymbolicExpressionTreeGrammarParameterName = "SymbolicExpressionTreeGrammar";
+ private const string ClonedSymbolicExpressionTreeGrammarParameterName = "ClonedSymbolicExpressionTreeGrammar";
+
+ #region Parameter Properties
+ public IValueLookupParameter MaximumSymbolicExpressionTreeLengthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
+ }
+
+ public IValueLookupParameter MaximumSymbolicExpressionTreeDepthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
+ }
+
+ public IValueLookupParameter SymbolicExpressionTreeGrammarParameter {
+ get { return (IValueLookupParameter)Parameters[SymbolicExpressionTreeGrammarParameterName]; }
+ }
+
+ public ILookupParameter ClonedSymbolicExpressionTreeGrammarParameter {
+ get { return (ILookupParameter)Parameters[ClonedSymbolicExpressionTreeGrammarParameterName]; }
+ }
+
+ #endregion
+ #region Properties
+ public IntValue MaximumSymbolicExpressionTreeDepth {
+ get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
+ }
+
+ public IntValue MaximumSymbolicExpressionTreeLength {
+ get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
+ }
+
+ public ISymbolicExpressionGrammar ClonedSymbolicExpressionTreeGrammar {
+ get { return ClonedSymbolicExpressionTreeGrammarParameter.ActualValue; }
+ }
+
+ #endregion
+
+ [StorableConstructor]
+ protected GrowTreeCreator(bool deserializing) : base(deserializing) { }
+ protected GrowTreeCreator(GrowTreeCreator original, Cloner cloner) : base(original, cloner) { }
+
+ public GrowTreeCreator()
+ : base() {
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeLengthParameterName,
+ "The maximal length (number of nodes) of the symbolic expression tree (this parameter is ignored)."));
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeDepthParameterName,
+ "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
+ Parameters.Add(new ValueLookupParameter(SymbolicExpressionTreeGrammarParameterName,
+ "The tree grammar that defines the correct syntax of symbolic expression trees that should be created."));
+ Parameters.Add(new LookupParameter(ClonedSymbolicExpressionTreeGrammarParameterName,
+ "An immutable clone of the concrete grammar that is actually used to create and manipulate trees."));
+ }
+
+ public override IDeepCloneable Clone(Cloner cloner) {
+ return new GrowTreeCreator(this, cloner);
+ }
+
+ public override IOperation Apply() {
+ if (ClonedSymbolicExpressionTreeGrammarParameter.ActualValue == null) {
+ SymbolicExpressionTreeGrammarParameter.ActualValue.ReadOnly = true;
+ IScope globalScope = ExecutionContext.Scope;
+ while (globalScope.Parent != null)
+ globalScope = globalScope.Parent;
+
+ globalScope.Variables.Add(new Variable(ClonedSymbolicExpressionTreeGrammarParameterName,
+ (ISymbolicExpressionGrammar)SymbolicExpressionTreeGrammarParameter.ActualValue.Clone()));
+ }
+ return base.Apply();
+ }
+
+ protected override ISymbolicExpressionTree Create(IRandom random) {
+ return Create(random, ClonedSymbolicExpressionTreeGrammar,
+ MaximumSymbolicExpressionTreeLength.Value, MaximumSymbolicExpressionTreeDepth.Value);
+ }
+
+ public override ISymbolicExpressionTree CreateTree(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
+ return Create(random, grammar, maxTreeLength, maxTreeDepth);
+ }
+
+ ///
+ /// Create a symbolic expression tree using the 'Grow' method.
+ /// All symbols are allowed for nodes, so the resulting trees can be of any shape and size.
+ ///
+ /// Random generator
+ /// Available tree grammar
+ /// Maximum tree depth
+ /// Maximum tree length. This parameter is not used.
+ ///
+ public static ISymbolicExpressionTree Create(IRandom random, ISymbolicExpressionGrammar grammar, int maxTreeLength, int maxTreeDepth) {
+ var tree = new SymbolicExpressionTree();
+ var rootNode = (SymbolicExpressionTreeTopLevelNode)grammar.ProgramRootSymbol.CreateTreeNode();
+ rootNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
+ if (rootNode.HasLocalParameters) rootNode.ResetLocalParameters(random);
+
+ var startNode = (SymbolicExpressionTreeTopLevelNode)grammar.StartSymbol.CreateTreeNode();
+ if (startNode.HasLocalParameters) startNode.ResetLocalParameters(random);
+ startNode.SetGrammar(new SymbolicExpressionTreeGrammar(grammar));
+
+ rootNode.AddSubtree(startNode);
+
+ Create(random, startNode, maxTreeDepth - 2);
+ tree.Root = rootNode;
+ return tree;
+ }
+
+ public static void Create(IRandom random, ISymbolicExpressionTreeNode seedNode, int maxDepth) {
+ // make sure it is possible to create a trees smaller than maxDepth
+ if (seedNode.Grammar.GetMinimumExpressionDepth(seedNode.Symbol) > maxDepth)
+ throw new ArgumentException("Cannot create trees of depth " + maxDepth + " or smaller because of grammar constraints.", "maxDepth");
+
+ var arity = SampleArity(random, seedNode);
+ // throw an exception if the seedNode happens to be a terminal, since in this case we cannot grow a tree
+ if (arity <= 0)
+ throw new ArgumentException("Cannot grow tree. Seed node shouldn't have arity zero.");
+
+ var allowedSymbols = seedNode.Grammar.AllowedSymbols
+ .Where(s => s.InitialFrequency > 0.0)
+ .ToList();
+
+ for (var i = 0; i < arity; i++) {
+ var possibleSymbols = allowedSymbols
+ .Where(s => seedNode.Grammar.IsAllowedChildSymbol(seedNode.Symbol, s, i))
+ .ToList();
+ var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
+ var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
+ var tree = selectedSymbol.CreateTreeNode();
+ if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
+ seedNode.AddSubtree(tree);
+ }
+
+ // Only iterate over the non-terminal nodes (those which have arity > 0)
+ // Start from depth 2 since the first two levels are formed by the rootNode and the seedNode
+ foreach (var subTree in seedNode.Subtrees)
+ if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) > 0)
+ RecursiveCreate(random, subTree, 2, maxDepth);
+ }
+
+ private static void RecursiveCreate(IRandom random, ISymbolicExpressionTreeNode root, int currentDepth, int maxDepth) {
+ var arity = SampleArity(random, root);
+ if (arity <= 0)
+ throw new ArgumentException("Cannot grow node of arity zero. Expected a function node.");
+
+ var allowedSymbols = root.Grammar.AllowedSymbols.Where(s => s.InitialFrequency > 0.0).ToList();
+
+ for (var i = 0; i < arity; i++) {
+ var possibleSymbols = allowedSymbols
+ .Where(s => root.Grammar.IsAllowedChildSymbol(root.Symbol, s, i) &&
+ root.Grammar.GetMinimumExpressionDepth(s) - 1 <= maxDepth - currentDepth)
+ .ToList();
+
+ if (!possibleSymbols.Any())
+ throw new InvalidOperationException("No symbols are available for the tree.");
+ var weights = possibleSymbols.Select(s => s.InitialFrequency).ToList();
+ var selectedSymbol = possibleSymbols.SelectRandom(weights, random);
+ var tree = selectedSymbol.CreateTreeNode();
+ if (tree.HasLocalParameters) tree.ResetLocalParameters(random);
+ root.AddSubtree(tree);
+ }
+
+ foreach (var subTree in root.Subtrees)
+ if (subTree.Grammar.GetMaximumSubtreeCount(subTree.Symbol) != 0)
+ RecursiveCreate(random, subTree, currentDepth + 1, maxDepth);
+ }
+
+ private static int SampleArity(IRandom random, ISymbolicExpressionTreeNode node) {
+ var minArity = node.Grammar.GetMinimumSubtreeCount(node.Symbol);
+ var maxArity = node.Grammar.GetMaximumSubtreeCount(node.Symbol);
+
+ return random.Next(minArity, maxArity + 1);
+ }
+ }
+}
Index: /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/ProbabilisticTreeCreator.cs
===================================================================
--- /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/ProbabilisticTreeCreator.cs (revision 9852)
+++ /branches/HeuristicLab.ReingoldTilfordTreeLayout/HeuristicLab.Encodings.SymbolicExpressionTreeEncoding/3.4/Creators/ProbabilisticTreeCreator.cs (revision 9852)
@@ -0,0 +1,334 @@
+#region License Information
+/* HeuristicLab
+ * Copyright (C) 2002-2013 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 HeuristicLab.Common;
+using HeuristicLab.Core;
+using HeuristicLab.Data;
+using HeuristicLab.Parameters;
+using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
+using HeuristicLab.PluginInfrastructure;
+
+namespace HeuristicLab.Encodings.SymbolicExpressionTreeEncoding {
+ [NonDiscoverableType]
+ [StorableClass]
+ [Item("ProbabilisticTreeCreator", "An operator that creates new symbolic expression trees with uniformly distributed length")]
+ public class ProbabilisticTreeCreator : SymbolicExpressionTreeCreator,
+ ISymbolicExpressionTreeSizeConstraintOperator, ISymbolicExpressionTreeGrammarBasedOperator {
+ private const int MAX_TRIES = 100;
+ private const string MaximumSymbolicExpressionTreeLengthParameterName = "MaximumSymbolicExpressionTreeLength";
+ private const string MaximumSymbolicExpressionTreeDepthParameterName = "MaximumSymbolicExpressionTreeDepth";
+ private const string SymbolicExpressionTreeGrammarParameterName = "SymbolicExpressionTreeGrammar";
+ private const string ClonedSymbolicExpressionTreeGrammarParameterName = "ClonedSymbolicExpressionTreeGrammar";
+ #region Parameter Properties
+ public IValueLookupParameter MaximumSymbolicExpressionTreeLengthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeLengthParameterName]; }
+ }
+ public IValueLookupParameter MaximumSymbolicExpressionTreeDepthParameter {
+ get { return (IValueLookupParameter)Parameters[MaximumSymbolicExpressionTreeDepthParameterName]; }
+ }
+ public IValueLookupParameter SymbolicExpressionTreeGrammarParameter {
+ get { return (IValueLookupParameter)Parameters[SymbolicExpressionTreeGrammarParameterName]; }
+ }
+ public ILookupParameter ClonedSymbolicExpressionTreeGrammarParameter {
+ get { return (ILookupParameter)Parameters[ClonedSymbolicExpressionTreeGrammarParameterName]; }
+ }
+ #endregion
+ #region Properties
+ public IntValue MaximumSymbolicExpressionTreeLength {
+ get { return MaximumSymbolicExpressionTreeLengthParameter.ActualValue; }
+ }
+ public IntValue MaximumSymbolicExpressionTreeDepth {
+ get { return MaximumSymbolicExpressionTreeDepthParameter.ActualValue; }
+ }
+ public ISymbolicExpressionGrammar SymbolicExpressionTreeGrammar {
+ get { return ClonedSymbolicExpressionTreeGrammarParameter.ActualValue; }
+ }
+ #endregion
+
+ [StorableConstructor]
+ protected ProbabilisticTreeCreator(bool deserializing) : base(deserializing) { }
+ protected ProbabilisticTreeCreator(ProbabilisticTreeCreator original, Cloner cloner) : base(original, cloner) { }
+ public ProbabilisticTreeCreator()
+ : base() {
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeLengthParameterName, "The maximal length (number of nodes) of the symbolic expression tree."));
+ Parameters.Add(new ValueLookupParameter(MaximumSymbolicExpressionTreeDepthParameterName, "The maximal depth of the symbolic expression tree (a tree with one node has depth = 0)."));
+ Parameters.Add(new ValueLookupParameter(SymbolicExpressionTreeGrammarParameterName, "The tree grammar that defines the correct syntax of symbolic expression trees that should be created."));
+ Parameters.Add(new LookupParameter