#region License Information /* HeuristicLab * Copyright (C) 2002-2014 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 System.Reflection; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; using HeuristicLab.Scripting; namespace HeuristicLab.Problems.Programmable { [Item("ProblemDefinitionScript", "Script that defines the parameter vector and evaluates the solution for a programmable problem.")] [StorableClass] public abstract class ProblemDefinitionScript : Script { protected bool SuppressEvents { get; set; } [Storable] private VariableStore variableStore; public VariableStore VariableStore { get { return variableStore; } } [StorableConstructor] protected ProblemDefinitionScript(bool deserializing) : base(deserializing) { } protected ProblemDefinitionScript(ProblemDefinitionScript original, Cloner cloner) : base(original, cloner) { variableStore = cloner.Clone(original.variableStore); } protected ProblemDefinitionScript() { variableStore = new VariableStore(); } private volatile IProblemDefinition instance; private object locker = new object(); public IProblemDefinition Instance { get { SuppressEvents = true; try { var oldInstance = instance; var compilationNecessary = false; if (instance == null) { lock (locker) { if (instance == null) { compilationNecessary = true; Compile(); } } } if (compilationNecessary && (oldInstance != null || instance != null)) OnInstanceChanged(); return instance; } finally { SuppressEvents = false; } } protected set { instance = value; if (!SuppressEvents) OnInstanceChanged(); } } public override Assembly Compile() { var assembly = base.Compile(); var types = assembly.GetTypes(); try { var inst = (ProblemDefinition)Activator.CreateInstance(types.First(x => typeof(ProblemDefinition).IsAssignableFrom(x))); inst.vars = new Variables(VariableStore); inst.Initialize(); Instance = inst; } catch { Instance = null; } return assembly; } protected override void OnCodeChanged() { base.OnCodeChanged(); instance = null; } public event EventHandler InstanceChanged; protected void OnInstanceChanged() { var handler = InstanceChanged; if (handler != null) handler(this, EventArgs.Empty); } } }