Free cookie consent management tool by TermsFeed Policy Generator

source: trunk/sources/HeuristicLab.Operators.Programmable/3.3/ProgrammableOperator.cs @ 3051

Last change on this file since 3051 was 3048, checked in by swagner, 15 years ago

Renamed classes of HeuristicLab.Data (#909)

File size: 14.2 KB
RevLine 
[2]1#region License Information
2/* HeuristicLab
[2911]3 * Copyright (C) 2002-2010 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
[2]4 *
5 * This file is part of HeuristicLab.
6 *
7 * HeuristicLab is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation, either version 3 of the License, or
10 * (at your option) any later version.
11 *
12 * HeuristicLab is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with HeuristicLab. If not, see <http://www.gnu.org/licenses/>.
19 */
20#endregion
21
22using System;
23using System.Collections.Generic;
24using System.Text;
25using System.Xml;
26using System.IO;
[694]27using System.Linq;
[2]28using System.Reflection;
29using System.CodeDom;
30using System.CodeDom.Compiler;
31using Microsoft.CSharp;
32using System.Text.RegularExpressions;
33using HeuristicLab.Core;
34using HeuristicLab.Data;
[694]35using System.Data.Linq;
[2799]36using System.Xml.XPath;
37using HeuristicLab.PluginInfrastructure;
[1872]38using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
[2932]39using HeuristicLab.Collections;
[2]40
41namespace HeuristicLab.Operators.Programmable {
42
[2877]43  [Item("ProgrammableOperator", "An operator that can be programmed for arbitrary needs.")]
44  [Creatable("Test")]
[3017]45  [StorableClass] 
[3008]46  public class ProgrammableOperator : Operator, IParameterizedNamedItem {
[1872]47
[2799]48    #region Fields & Properties
49
[3014]50    public new ParameterCollection Parameters {
[3008]51      get { return base.Parameters; }
52    }
53
[2799]54    private MethodInfo executeMethod;
55    public CompilerErrorCollection CompileErrors { get; private set; }
56    public string CompilationUnitCode { get; private set; }
[2897]57
[1872]58    [Storable]
[2799]59    private string code;
[2]60    public string Code {
[2799]61      get { return code; }
[2]62      set {
[2799]63        if (value != code) {
64          code = value;
[2]65          executeMethod = null;
66          OnCodeChanged();
67        }
68      }
69    }
70
[1211]71    private object syncRoot = new object();
72
[2799]73    private static object initLock = new object();
74    private static Dictionary<string, List<Assembly>> defaultPluginDict;
75    private static Dictionary<Assembly, bool> defaultAssemblyDict;
76
77    public readonly Dictionary<string, List<Assembly>> Plugins;
78
79    protected Dictionary<Assembly, bool> Assemblies;
80
81    [Storable]
[3008]82    private List<string> _persistedAssemblyNames {
[2897]83      get {
[3008]84        return Assemblies.Keys.Select(a => a.FullName).ToList();
[2799]85      }
86      set {
[2897]87        var selectedAssemblyNames = new HashSet<string>(value);
[2799]88        foreach (var a in Assemblies.Keys.ToList()) {
89          Assemblies[a] = selectedAssemblyNames.Contains(a.FullName);
[2897]90        }
[2799]91      }
[2]92    }
93
[2799]94    public IEnumerable<Assembly> AvailableAssemblies {
95      get { return Assemblies.Keys; }
96    }
97
98    public IEnumerable<Assembly> SelectedAssemblies {
99      get { return Assemblies.Where(kvp => kvp.Value).Select(kvp => kvp.Key); }
100    }
101
102    [Storable]
103    private HashSet<string> namespaces;
104    public IEnumerable<string> Namespaces {
105      get { return namespaces; }
106    }
107
[2877]108    public override bool CanChangeDescription {
[3024]109      get { return true; }
110    }
[2877]111
[2799]112    #endregion
113
114    #region Extended Accessors
115
116    public void SelectAssembly(Assembly a) {
117      if (a != null && Assemblies.ContainsKey(a))
118        Assemblies[a] = true;
119    }
120
121    public void UnselectAssembly(Assembly a) {
122      if (a != null && Assemblies.ContainsKey(a))
123        Assemblies[a] = false;
124    }
125
126    public void SelectNamespace(string ns) {
127      namespaces.Add(ns);
128    }
129
130    public void UnselectNamespace(string ns) {
131      namespaces.Remove(ns);
132    }
133
[2]134    public void SetDescription(string description) {
135      if (description == null)
[2897]136        throw new NullReferenceException("description must not be null");
137      Description = description;
[2799]138    }
[2]139
[2799]140    public IEnumerable<string> GetAllNamespaces(bool selectedAssembliesOnly) {
141      var namespaces = new HashSet<string>();
142      foreach (var a in Assemblies) {
143        if (!selectedAssembliesOnly || a.Value) {
144          foreach (var t in a.Key.GetTypes()) {
145            if (t.IsPublic) {
146              foreach (string ns in GetNamespaceHierachy(t.Namespace)) {
147                namespaces.Add(ns);
148              }
149            }
150          }
151        }
[2]152      }
[2799]153      return namespaces;
[2]154    }
155
[2799]156    private IEnumerable<string> GetNamespaceHierachy(string ns) {
157      for (int i = ns.Length; i != -1; i = ns.LastIndexOf('.', i - 1)) {
158        yield return ns.Substring(0, i);
159      }
160    }
[2]161
[2799]162    #endregion
[2]163
[2799]164    #region Construction & Initialization
[2]165
[2897]166    public ProgrammableOperator() {
167      code = "";
[2799]168      executeMethod = null;
169      ProgrammableOperator.StaticInitialize();
170      Assemblies = defaultAssemblyDict;
171      Plugins = defaultPluginDict;
[3014]172      namespaces = new HashSet<string>(DiscoverNamespaces());
173      RegisterEvents();
[2799]174    }
175
[3014]176    [StorableHook(HookType.AfterDeserialization)]
177    private void RegisterEvents() {
178      Parameters.ItemsAdded += OnSignatureChanged;
179      Parameters.ItemsRemoved += OnSignatureChanged;
180      Parameters.ItemsReplaced += OnSignatureChanged;
181      Parameters.CollectionReset += OnSignatureChanged;
182    }
183
[2932]184    protected void OnSignatureChanged(object sender, CollectionItemsChangedEventArgs<IParameter> args) {
[2897]185      if (SignatureChanged != null)
[2932]186        SignatureChanged(sender, EventArgs.Empty);
[2897]187    }
188
[2799]189    private static void StaticInitialize() {
190      lock (initLock) {
191        if (defaultPluginDict != null || defaultAssemblyDict != null) return;
192        defaultAssemblyDict = DiscoverAssemblies();
193        defaultPluginDict = GroupAssemblies(defaultAssemblyDict.Keys);
194      }
195    }
196
197    private static Dictionary<string, List<Assembly>> GroupAssemblies(IEnumerable<Assembly> assemblies) {
198      var plugins = new Dictionary<string, List<Assembly>>();
199      var locationTable = assemblies.ToDictionary(a => a.Location, a => a);
200      foreach (var plugin in ApplicationManager.Manager.Plugins) {
201        var aList = new List<Assembly>();
202        foreach (var aName in from file in plugin.Files
203                              where file.Type == PluginFileType.Assembly
204                              select file.Name) {
205          Assembly a;
206          locationTable.TryGetValue(aName, out a);
207          if (a != null) {
208            aList.Add(a);
209            locationTable.Remove(aName);
210          }
211        }
212        plugins[plugin.Name] = aList;
213      }
214      plugins["other"] = locationTable.Values.ToList();
215      return plugins;
216    }
217
[2897]218    protected static List<Assembly> defaultAssemblies = new List<Assembly>() {
[2799]219      typeof(System.Linq.Enumerable).Assembly,  // add reference to version 3.5 of System.dll
220      typeof(System.Collections.Generic.List<>).Assembly,
[2897]221      typeof(System.Text.StringBuilder).Assembly,
[2799]222      typeof(System.Data.Linq.DataContext).Assembly,
[2897]223      typeof(HeuristicLab.Core.Item).Assembly,
[3048]224      typeof(HeuristicLab.Data.IntValue).Assembly,
[2799]225    };
226
227    protected static Dictionary<Assembly, bool> DiscoverAssemblies() {
228      var assemblies = new Dictionary<Assembly, bool>();
229      foreach (var a in AppDomain.CurrentDomain.GetAssemblies()) {
230        try {
231          if (File.Exists(a.Location)) {
232            assemblies.Add(a, false);
233          }
[2897]234        } catch (NotSupportedException) {
[2799]235          // NotSupportedException is thrown while accessing
236          // the Location property of the anonymously hosted
237          // dynamic methods assembly, which is related to
238          // LINQ queries
239        }
240      }
241      foreach (var a in defaultAssemblies) {
242        if (assemblies.ContainsKey(a)) {
243          assemblies[a] = true;
244        } else {
245          assemblies.Add(a, true);
246        }
247      }
248      return assemblies;
249    }
250
251    protected static List<string> DiscoverNamespaces() {
252      return new List<string>() {
253        "System",
254        "System.Collections.Generic",
255        "System.Text",
256        "System.Linq",
257        "System.Data.Linq",
258        "HeuristicLab.Core",
259        "HeuristicLab.Data",
260      };
261    }
262
263    #endregion
264
265    #region Compilation
266
267    private static CSharpCodeProvider codeProvider =
268      new CSharpCodeProvider(
269        new Dictionary<string, string>() {
270          { "CompilerVersion", "v3.5" },  // support C# 3.0 syntax
271        });
272
273    private CompilerResults DoCompile() {
[2]274      CompilerParameters parameters = new CompilerParameters();
275      parameters.GenerateExecutable = false;
276      parameters.GenerateInMemory = true;
277      parameters.IncludeDebugInformation = false;
[2799]278      parameters.ReferencedAssemblies.AddRange(SelectedAssemblies.Select(a => a.Location).ToArray());
279      var unit = CreateCompilationUnit();
280      var writer = new StringWriter();
281      codeProvider.GenerateCodeFromCompileUnit(
282        unit,
283        writer,
284        new CodeGeneratorOptions() {
285          BracingStyle = "C",
286          ElseOnClosing = true,
287          IndentString = "  ",
288        });
289      CompilationUnitCode = writer.ToString();
290      return codeProvider.CompileAssemblyFromDom(parameters, unit);
291    }
[2]292
[2799]293    public virtual void Compile() {
294      var results = DoCompile();
[2]295      executeMethod = null;
296      if (results.Errors.HasErrors) {
[2799]297        CompileErrors = results.Errors;
298        StringBuilder sb = new StringBuilder();
[2]299        foreach (CompilerError error in results.Errors) {
[2799]300          sb.Append(error.Line).Append(':')
301            .Append(error.Column).Append(": ")
302            .AppendLine(error.ErrorText);
[2]303        }
[2799]304        throw new Exception(string.Format(
305          "Compilation of \"{0}\" failed:{1}{2}",
306          Name, Environment.NewLine,
307          sb.ToString()));
[2]308      } else {
[2799]309        CompileErrors = null;
[2]310        Assembly assembly = results.CompiledAssembly;
311        Type[] types = assembly.GetTypes();
312        executeMethod = types[0].GetMethod("Execute");
313      }
314    }
315
[2799]316    private CodeCompileUnit CreateCompilationUnit() {
317      CodeNamespace ns = new CodeNamespace("HeuristicLab.Operators.Programmable.CustomOperators");
318      ns.Types.Add(CreateType());
319      ns.Imports.AddRange(
320        GetSelectedAndValidNamespaces()
321        .Select(n => new CodeNamespaceImport(n))
322        .ToArray());
323      CodeCompileUnit unit = new CodeCompileUnit();
324      unit.Namespaces.Add(ns);
325      return unit;
[2]326    }
327
[2799]328    public IEnumerable<string> GetSelectedAndValidNamespaces() {
329      var possibleNamespaces = new HashSet<string>(GetAllNamespaces(true));
330      foreach (var ns in Namespaces)
331        if (possibleNamespaces.Contains(ns))
332          yield return ns;
333    }
334
335    public static readonly Regex SafeTypeNameCharRegex = new Regex("[_a-zA-Z0-9]+");
336    public static readonly Regex SafeTypeNameRegex = new Regex("[_a-zA-Z][_a-zA-Z0-9]*");
337
338    public string CompiledTypeName {
339      get {
340        var sb = new StringBuilder();
341        foreach (string s in SafeTypeNameCharRegex.Matches(Name).Cast<Match>().Select(m => m.Value)) {
342          sb.Append(s);
[1211]343        }
[2799]344        return SafeTypeNameRegex.Match(sb.ToString()).Value;
[116]345      }
[2799]346    }
[2]347
[2799]348    private CodeTypeDeclaration CreateType() {
349      CodeTypeDeclaration typeDecl = new CodeTypeDeclaration(CompiledTypeName) {
350        IsClass = true,
351        TypeAttributes = TypeAttributes.Public,
352      };
353      typeDecl.Members.Add(CreateMethod());
354      return typeDecl;
355    }
356
357    public string Signature {
358      get {
359        var sb = new StringBuilder()
[2897]360        .Append("public static IOperation Execute(IOperator op, IExecutionContext context");
[2799]361        foreach (IParameter param in Parameters) {
362          sb.Append(String.Format(", {0} {1}", param.DataType.Name, param.Name));
[2897]363        }
[2799]364        return sb.Append(")").ToString();
[2]365      }
[2799]366    }
[2]367
[2897]368    public event EventHandler SignatureChanged;
369
[2799]370    private static Regex lineSplitter = new Regex(@"\r\n|\r|\n");
371
372    private CodeMemberMethod CreateMethod() {
373      CodeMemberMethod method = new CodeMemberMethod();
374      method.Name = "Execute";
[2897]375      method.ReturnType = new CodeTypeReference(typeof(IOperation));
[2799]376      method.Attributes = MemberAttributes.Public | MemberAttributes.Static;
[2897]377      method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IOperator), "op"));
378      method.Parameters.Add(new CodeParameterDeclarationExpression(typeof(IExecutionContext), "context"));
[2799]379      foreach (var param in Parameters)
380        method.Parameters.Add(new CodeParameterDeclarationExpression(param.DataType, param.Name));
381      string[] codeLines = lineSplitter.Split(code);
382      for (int i = 0; i < codeLines.Length; i++) {
383        codeLines[i] = string.Format("#line {0} \"ProgrammableOperator\"{1}{2}", i + 1, "\r\n", codeLines[i]);
384      }
385      method.Statements.Add(new CodeSnippetStatement(
386        string.Join("\r\n", codeLines) +
387        "\r\nreturn null;"));
388      return method;
[2]389    }
390
[2799]391    #endregion
392
393    #region HeuristicLab interfaces
[2877]394
395    public override IOperation Apply() {
[2799]396      lock (syncRoot) {
397        if (executeMethod == null) {
398          Compile();
399        }
400      }
401
[2897]402      var parameters = new List<object>() { this, ExecutionContext };
[2799]403      parameters.AddRange(Parameters.Select(p => (object)p.ActualValue));
[2877]404      return (IOperation)executeMethod.Invoke(null, parameters.ToArray());
[2]405    }
[2897]406
[2]407    public event EventHandler CodeChanged;
408    protected virtual void OnCodeChanged() {
409      if (CodeChanged != null)
410        CodeChanged(this, new EventArgs());
411    }
[2799]412
413    #endregion
414
[2897]415    #region Cloning
[2799]416
417    public override IDeepCloneable Clone(Cloner cloner) {
418      ProgrammableOperator clone = (ProgrammableOperator)base.Clone(cloner);
419      clone.Description = Description;
420      clone.code = Code;
421      clone.executeMethod = executeMethod;
422      clone.Assemblies = Assemblies.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
423      clone.namespaces = namespaces;
424      clone.CompilationUnitCode = CompilationUnitCode;
425      clone.CompileErrors = CompileErrors;
[3014]426      clone.RegisterEvents();
[2799]427      return clone;
428    }
[2897]429
[2799]430    #endregion
[2897]431
[2]432  }
433}
Note: See TracBrowser for help on using the repository browser.