Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
01/20/10 05:00:28 (14 years ago)
Author:
swagner
Message:

Committing first results of the refactoring of HeuristicLab.Core and related plugins (#95)

Location:
trunk/sources/HeuristicLab.Core/3.3
Files:
28 added
16 deleted
12 edited

Legend:

Unmodified
Added
Removed
  • trunk/sources/HeuristicLab.Core/3.3/Cloner.cs

    r2526 r2653  
    2828  /// A helper class which is used to create deep clones of object graphs.
    2929  /// </summary>
    30   public class Cloner : ICloner {
    31     private class ReferenceEqualityComparer : IEqualityComparer<IItem> {
    32       public bool Equals(IItem x, IItem y) {
     30  public sealed class Cloner {
     31    private class ReferenceEqualityComparer : IEqualityComparer<IDeepCloneable> {
     32      bool IEqualityComparer<IDeepCloneable>.Equals(IDeepCloneable x, IDeepCloneable y) {
    3333        return object.ReferenceEquals(x, y);
    3434      }
    3535
    36       public int GetHashCode(IItem item) {
    37         if (item == null) return 0;
    38         return item.GetHashCode();
     36      int IEqualityComparer<IDeepCloneable>.GetHashCode(IDeepCloneable obj) {
     37        if (obj == null) return 0;
     38        return obj.GetHashCode();
    3939      }
    4040    }
    4141
    42     private Dictionary<IItem, IItem> mapping;
     42    private Dictionary<IDeepCloneable, IDeepCloneable> mapping;
    4343
    4444    /// <summary>
     
    4646    /// </summary>
    4747    public Cloner() {
    48       mapping = new Dictionary<IItem, IItem>(new ReferenceEqualityComparer());
     48      mapping = new Dictionary<IDeepCloneable, IDeepCloneable>(new ReferenceEqualityComparer());
    4949    }
    5050
    5151    /// <summary>
    52     /// Creates a deep clone of a given item.
     52    /// Creates a deep clone of a given deeply cloneable object.
    5353    /// </summary>
    54     /// <param name="item">The item which should be cloned.</param>
    55     /// <returns>A clone of the given item.</returns>
    56     public IItem Clone(IItem item) {
    57       if (item == null) return null;
    58       IItem clone;
    59       if (mapping.TryGetValue(item, out clone))
     54    /// <param name="item">The object which should be cloned.</param>
     55    /// <returns>A clone of the given object.</returns>
     56    public IDeepCloneable Clone(IDeepCloneable obj) {
     57      if (obj == null) return null;
     58      IDeepCloneable clone;
     59      if (mapping.TryGetValue(obj, out clone))
    6060        return clone;
    6161      else
    62         return item.Clone(this);
     62        return obj.Clone(this);
    6363    }
    6464    /// <summary>
    65     /// Registers a new clone for a given item.
     65    /// Registers a new clone for a given deeply cloneable object.
    6666    /// </summary>
    67     /// <param name="item">The original item.</param>
    68     /// <param name="clone">The clone of the original item.</param>
    69     public void RegisterClonedObject(IItem item, IItem clone) {
     67    /// <param name="item">The original object.</param>
     68    /// <param name="clone">The clone of the original object.</param>
     69    public void RegisterClonedObject(IDeepCloneable item, IDeepCloneable clone) {
    7070      mapping.Add(item, clone);
    7171    }
  • trunk/sources/HeuristicLab.Core/3.3/EngineBase.cs

    r2526 r2653  
    2525using System.Xml;
    2626using System.Threading;
     27using System.Drawing;
    2728using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2829using HeuristicLab.Common;
     
    3435  /// one execution and can handle parallel executions.
    3536  /// </summary>
     37  [Item("EngineBase", "A base class for engines.")]
    3638  public abstract class EngineBase : ItemBase, IEngine {
     39    public override Image ItemImage {
     40      get { return HeuristicLab.Common.Resources.VS2008ImageLibrary.Event; }
     41    }
    3742
    3843    /// <summary>
    3944    /// Field of the current instance that represent the operator graph.
    4045    /// </summary>
    41     [Storable]
    42     protected IOperatorGraph myOperatorGraph;
     46    private OperatorGraph operatorGraph;
    4347    /// <summary>
    4448    /// Gets the current operator graph.
    4549    /// </summary>
    46     public IOperatorGraph OperatorGraph {
    47       get { return myOperatorGraph; }
    48     }
     50    [Storable]
     51    public OperatorGraph OperatorGraph {
     52      get { return operatorGraph; }
     53      set {
     54        if (value == null) throw new ArgumentNullException();
     55        if (value != operatorGraph) {
     56          if (operatorGraph != null) operatorGraph.InitialOperatorChanged -= new EventHandler(operatorGraph_InitialOperatorChanged);
     57          operatorGraph = value;
     58          if (operatorGraph != null) operatorGraph.InitialOperatorChanged += new EventHandler(operatorGraph_InitialOperatorChanged);
     59          OnOperatorGraphChanged();
     60          Initialize();
     61        }
     62      }
     63    }
     64
    4965    /// <summary>
    5066    /// Field of the current instance that represent the global scope.
    5167    /// </summary>
    5268    [Storable]
    53     protected IScope myGlobalScope;
     69    private Scope globalScope;
    5470    /// <summary>
    5571    /// Gets the current global scope.
    5672    /// </summary>
    57     public IScope GlobalScope {
    58       get { return myGlobalScope; }
    59     }
    60 
    61     [Storable]
    62     private TimeSpan myExecutionTime;
     73    public Scope GlobalScope {
     74      get { return globalScope; }
     75    }
     76
     77    [Storable]
     78    private TimeSpan executionTime;
    6379    /// <summary>
    6480    /// Gets or sets the execution time.
     
    6682    /// <remarks>Calls <see cref="OnExecutionTimeChanged"/> in the setter.</remarks>
    6783    public TimeSpan ExecutionTime {
    68       get { return myExecutionTime; }
     84      get { return executionTime; }
    6985      protected set {
    70         myExecutionTime = value;
     86        executionTime = value;
    7187        OnExecutionTimeChanged();
    7288      }
     
    7793    /// </summary>
    7894    [Storable]
    79     protected Stack<IOperation> myExecutionStack;
     95    private Stack<ExecutionContext> executionStack;
    8096    /// <summary>
    8197    /// Gets the current execution stack.
    8298    /// </summary>
    83     public Stack<IOperation> ExecutionStack {
    84       get { return myExecutionStack; }
     99    protected Stack<ExecutionContext> ExecutionStack {
     100      get { return executionStack; }
    85101    }
    86102
     
    88104    /// Flag of the current instance whether it is currently running.
    89105    /// </summary>
    90     protected bool myRunning;
     106    private bool running;
    91107    /// <summary>
    92108    /// Gets information whether the instance is currently running.
    93109    /// </summary>
    94110    public bool Running {
    95       get { return myRunning; }
     111      get { return running; }
    96112    }
    97113
     
    99115    /// Flag of the current instance whether it is canceled.
    100116    /// </summary>
    101     protected bool myCanceled;
     117    private bool canceled;
    102118    /// <summary>
    103119    /// Gets information whether the instance is currently canceled.
    104120    /// </summary>
    105     public bool Canceled {
    106       get { return myCanceled; }
     121    protected bool Canceled {
     122      get { return canceled; }
    107123    }
    108124    /// <summary>
    109125    /// Gets information whether the instance has already terminated.
    110126    /// </summary>
    111     public virtual bool Terminated {
    112       get { return ExecutionStack.Count == 0; }
     127    public bool Finished {
     128      get { return executionStack.Count == 0; }
    113129    }
    114130
     
    118134    /// <remarks>Calls <see cref="Reset"/>.</remarks>
    119135    protected EngineBase() {
    120       myOperatorGraph = new OperatorGraph();
    121       myGlobalScope = new Scope("Global");
    122       myExecutionStack = new Stack<IOperation>();
    123       Reset();
     136      globalScope = new Scope("Global");
     137      executionStack = new Stack<ExecutionContext>();
     138      OperatorGraph = new OperatorGraph();
    124139    }
    125140
     
    131146    /// <param name="clonedObjects">Dictionary of all already clone objects. (Needed to avoid cycles.)</param>
    132147    /// <returns>The cloned object as <see cref="EngineBase"/>.</returns>
    133     public override IItem Clone(ICloner cloner) {
     148    public override IDeepCloneable Clone(Cloner cloner) {
    134149      EngineBase clone = (EngineBase)base.Clone(cloner);
    135       clone.myOperatorGraph = (IOperatorGraph)cloner.Clone(OperatorGraph);
    136       clone.myGlobalScope = (IScope)cloner.Clone(GlobalScope);
    137       clone.myExecutionTime = ExecutionTime;
    138       IOperation[] operations = new IOperation[ExecutionStack.Count];
    139       ExecutionStack.CopyTo(operations, 0);
    140       for (int i = operations.Length - 1; i >= 0; i--)
    141         clone.myExecutionStack.Push((IOperation)cloner.Clone(operations[i]));
    142       clone.myRunning = Running;
    143       clone.myCanceled = Canceled;
     150      clone.OperatorGraph = (OperatorGraph)cloner.Clone(operatorGraph);
     151      clone.globalScope = (Scope)cloner.Clone(globalScope);
     152      clone.executionTime = executionTime;
     153      ExecutionContext[] contexts = executionStack.ToArray();
     154      for (int i = contexts.Length - 1; i >= 0; i--)
     155        clone.executionStack.Push((ExecutionContext)cloner.Clone(contexts[i]));
     156      clone.running = running;
     157      clone.canceled = canceled;
    144158      return clone;
    145159    }
    146160
    147     /// <inheritdoc/>
    148     /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
    149     /// of class <see cref="ThreadPool"/>.</remarks>
    150     public virtual void Execute() {
    151       myRunning = true;
    152       myCanceled = false;
    153       ThreadPool.QueueUserWorkItem(new WaitCallback(Run), null);
    154     }
    155     /// <inheritdoc/>
    156     /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
    157     /// of class <see cref="ThreadPool"/>.</remarks>
    158     public virtual void ExecuteSteps(int steps) {
    159       myRunning = true;
    160       myCanceled = false;
    161       ThreadPool.QueueUserWorkItem(new WaitCallback(Run), steps);
    162     }
    163     /// <inheritdoc/>
    164     /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
    165     /// of class <see cref="ThreadPool"/>.</remarks>
    166     public void ExecuteStep() {
    167       ExecuteSteps(1);
    168     }
    169     /// <inheritdoc/>
    170     /// <remarks>Sets the protected flag <c>myCanceled</c> to <c>true</c>.</remarks>
    171     public virtual void Abort() {
    172       myCanceled = true;
    173     }
    174161    /// <inheritdoc/>
    175162    /// <remarks>Sets <c>myCanceled</c> and <c>myRunning</c> to <c>false</c>. The global scope is cleared,
     
    177164    /// with the initial operator is added. <br/>
    178165    /// Calls <see cref="OnInitialized"/>.</remarks>
    179     public virtual void Reset() {
    180       myCanceled = false;
    181       myRunning = false;
     166    public void Initialize() {
     167      canceled = false;
     168      running = false;
    182169      GlobalScope.Clear();
    183170      ExecutionTime = new TimeSpan();
    184       myExecutionStack.Clear();
     171      executionStack.Clear();
    185172      if (OperatorGraph.InitialOperator != null)
    186         myExecutionStack.Push(new AtomicOperation(OperatorGraph.InitialOperator, GlobalScope));
     173        executionStack.Push(new ExecutionContext(null, OperatorGraph.InitialOperator, GlobalScope));
    187174      OnInitialized();
    188175    }
     176    /// <inheritdoc/>
     177    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
     178    /// of class <see cref="ThreadPool"/>.</remarks>
     179    public void Start() {
     180      running = true;
     181      canceled = false;
     182      ThreadPool.QueueUserWorkItem(new WaitCallback(Run), null);
     183    }
     184    /// <inheritdoc/>
     185    /// <remarks>Calls <see cref="ThreadPool.QueueUserWorkItem(System.Threading.WaitCallback, object)"/>
     186    /// of class <see cref="ThreadPool"/>.</remarks>
     187    public void Step() {
     188      running = true;
     189      canceled = false;
     190      ThreadPool.QueueUserWorkItem(new WaitCallback(RunStep), null);
     191    }
     192    /// <inheritdoc/>
     193    /// <remarks>Sets the protected flag <c>myCanceled</c> to <c>true</c>.</remarks>
     194    public virtual void Stop() {
     195      canceled = true;
     196    }
    189197
    190198    private void Run(object state) {
    191       if (state == null) Run();
    192       else RunSteps((int)state);
    193       myRunning = false;
    194       OnFinished();
    195     }
    196     private void Run() {
     199      OnStarted();
    197200      DateTime start = DateTime.Now;
    198201      DateTime end;
    199       while ((!Canceled) && (!Terminated)) {
    200         ProcessNextOperation();
     202      while ((!Canceled) && (!Finished)) {
     203        ProcessNextOperator();
    201204        end = DateTime.Now;
    202205        ExecutionTime += end - start;
     
    204207      }
    205208      ExecutionTime += DateTime.Now - start;
    206     }
    207     private void RunSteps(int steps) {
     209      running = false;
     210      OnStopped();
     211    }
     212    private void RunStep(object state) {
     213      OnStarted();
    208214      DateTime start = DateTime.Now;
    209       DateTime end;
    210       int step = 0;
    211       while ((!Canceled) && (!Terminated) && (step < steps)) {
    212         ProcessNextOperation();
    213         step++;
    214         end = DateTime.Now;
    215         ExecutionTime += end - start;
    216         start = end;
    217       }
     215      if ((!Canceled) && (!Finished))
     216        ProcessNextOperator();
    218217      ExecutionTime += DateTime.Now - start;
     218      running = false;
     219      OnStopped();
    219220    }
    220221
     
    222223    /// Performs the next operation.
    223224    /// </summary>
    224     protected abstract void ProcessNextOperation();
    225 
    226     /// <summary>
    227     /// Occurs when the current instance is initialized.
     225    protected abstract void ProcessNextOperator();
     226
     227    private void operatorGraph_InitialOperatorChanged(object sender, EventArgs e) {
     228      Initialize();
     229    }
     230
     231    public event EventHandler OperatorGraphChanged;
     232    protected virtual void OnOperatorGraphChanged() {
     233      if (OperatorGraphChanged != null)
     234        OperatorGraphChanged(this, EventArgs.Empty);
     235    }
     236    /// <summary>
     237    /// Occurs when the execution time changed.
     238    /// </summary>
     239    public event EventHandler ExecutionTimeChanged;
     240    /// <summary>
     241    /// Fires a new <c>ExecutionTimeChanged</c> event.
     242    /// </summary>
     243    protected virtual void OnExecutionTimeChanged() {
     244      if (ExecutionTimeChanged != null)
     245        ExecutionTimeChanged(this, new EventArgs());
     246    }
     247    /// <summary>
     248    /// Occurs when the execution is initialized.
    228249    /// </summary>
    229250    public event EventHandler Initialized;
     
    236257    }
    237258    /// <summary>
    238     /// Occurs when an operation is executed.
    239     /// </summary>
    240     public event EventHandler<EventArgs<IOperation>> OperationExecuted;
    241     /// <summary>
    242     /// Fires a new <c>OperationExecuted</c> event.
    243     /// </summary>
    244     /// <param name="operation">The operation that has been executed.</param>
    245     protected virtual void OnOperationExecuted(IOperation operation) {
    246       if (OperationExecuted != null)
    247         OperationExecuted(this, new EventArgs<IOperation>(operation));
     259    /// Occurs when the execution is executed.
     260    /// </summary>
     261    public event EventHandler Started;
     262    /// <summary>
     263    /// Fires a new <c>Started</c> event.
     264    /// </summary>
     265    protected virtual void OnStarted() {
     266      if (Started != null)
     267        Started(this, new EventArgs());
     268    }
     269    /// <summary>
     270    /// Occurs when the execution is finished.
     271    /// </summary>
     272    public event EventHandler Stopped;
     273    /// <summary>
     274    /// Fires a new <c>Stopped</c> event.
     275    /// </summary>
     276    protected virtual void OnStopped() {
     277      if (Stopped != null)
     278        Stopped(this, new EventArgs());
    248279    }
    249280    /// <summary>
     
    256287    /// <param name="exception">The exception that was thrown.</param>
    257288    protected virtual void OnExceptionOccurred(Exception exception) {
    258       Abort();
    259289      if (ExceptionOccurred != null)
    260290        ExceptionOccurred(this, new EventArgs<Exception>(exception));
    261291    }
    262     /// <summary>
    263     /// Occurs when the execution time changed.
    264     /// </summary>
    265     public event EventHandler ExecutionTimeChanged;
    266     /// <summary>
    267     /// Fires a new <c>ExecutionTimeChanged</c> event.
    268     /// </summary>
    269     protected virtual void OnExecutionTimeChanged() {
    270       if (ExecutionTimeChanged != null)
    271         ExecutionTimeChanged(this, new EventArgs());
    272     }
    273     /// <summary>
    274     /// Occurs when the execution is finished.
    275     /// </summary>
    276     public event EventHandler Finished;
    277     /// <summary>
    278     /// Fires a new <c>Finished</c> event.
    279     /// </summary>
    280     protected virtual void OnFinished() {
    281       if (Finished != null)
    282         Finished(this, new EventArgs());
    283     }
    284292  }
    285293}
  • trunk/sources/HeuristicLab.Core/3.3/HeuristicLab.Core-3.3.csproj

    r2546 r2653  
    9999  </ItemGroup>
    100100  <ItemGroup>
    101     <Compile Include="AtomicOperation.cs" />
    102101    <Compile Include="Attributes\ItemAttribute.cs" />
    103     <Compile Include="CompositeOperation.cs" />
    104102    <Compile Include="Cloner.cs" />
    105103    <Compile Include="Attributes\CreatableAttribute.cs" />
    106     <Compile Include="Interfaces\ICloner.cs" />
    107     <Compile Include="Interfaces\IOperation.cs" />
    108     <Compile Include="Interfaces\IOperatorLibrary.cs" />
    109     <Compile Include="Interfaces\IVisualizationItem.cs" />
     104    <Compile Include="CombinedOperator.cs" />
     105    <Compile Include="ChangedEventArgs.cs" />
     106    <Compile Include="Interfaces\IOperatorParameter.cs" />
     107    <Compile Include="OperatorGraph.cs" />
     108    <Compile Include="OperatorParameter.cs" />
     109    <Compile Include="ParameterBase.cs" />
     110    <Compile Include="Interfaces\IParameter.cs" />
     111    <Compile Include="OperatorCollection.cs" />
     112    <Compile Include="ItemCollection.cs" />
     113    <Compile Include="OperatorSet.cs" />
     114    <Compile Include="ItemSet.cs" />
     115    <Compile Include="StandardOperatorBase.cs" />
     116    <Compile Include="ItemList.cs" />
     117    <Compile Include="SequentialProcessor.cs" />
     118    <Compile Include="CounterOperator.cs" />
     119    <Compile Include="IntData.cs" />
     120    <Compile Include="EmptyOperator.cs" />
     121    <Compile Include="EngineBase.cs">
     122      <SubType>Code</SubType>
     123    </Compile>
     124    <Compile Include="Interfaces\IEngine.cs">
     125      <SubType>Code</SubType>
     126    </Compile>
     127    <Compile Include="ExecutionContextCollection.cs" />
     128    <Compile Include="ExecutionContext.cs" />
     129    <Compile Include="OperatorList.cs" />
     130    <Compile Include="ParameterCollection.cs" />
     131    <Compile Include="VariableCollection.cs" />
     132    <Compile Include="Parameter.cs" />
     133    <Compile Include="ScopeList.cs" />
     134    <Compile Include="DeepCloneableBase.cs" />
     135    <Compile Include="Interfaces\IDeepCloneable.cs" />
     136    <Compile Include="NamedItemCollection.cs" />
     137    <Compile Include="Interfaces\INamedItem.cs" />
     138    <Compile Include="NamedItemBase.cs" />
    110139    <Compile Include="Interfaces\IItem.cs" />
    111140    <Compile Include="ItemBase.cs" />
    112     <Compile Include="OperatorLibrary.cs" />
    113     <Compile Include="Interfaces\IOperatorGroup.cs" />
    114     <Compile Include="Interfaces\IOperatorGraph.cs" />
    115     <Compile Include="Interfaces\IScope.cs" />
    116     <Compile Include="Interfaces\IVariable.cs" />
    117     <Compile Include="Interfaces\IVariableInfo.cs" />
    118     <Compile Include="OperatorGroup.cs">
    119       <SubType>Code</SubType>
    120     </Compile>
    121141    <Compile Include="OperatorBase.cs" />
    122142    <Compile Include="Interfaces\IRandom.cs" />
    123     <Compile Include="OperatorGraph.cs" />
    124143    <Compile Include="Scope.cs" />
    125     <Compile Include="EngineBase.cs" />
    126     <Compile Include="Interfaces\IEngine.cs" />
    127144    <Compile Include="Interfaces\IOperator.cs" />
    128     <Compile Include="PersistenceManager.cs" />
    129145    <Compile Include="HeuristicLabCorePlugin.cs" />
    130146    <Compile Include="Properties\AssemblyInfo.cs" />
    131147    <Compile Include="Variable.cs" />
    132     <Compile Include="VariableInfo.cs" />
    133     <Compile Include="VariableKind.cs" />
    134148  </ItemGroup>
    135149  <ItemGroup>
     
    138152  </ItemGroup>
    139153  <ItemGroup>
     154    <ProjectReference Include="..\..\HeuristicLab.Collections\3.3\HeuristicLab.Collections-3.3.csproj">
     155      <Project>{958B43BC-CC5C-4FA2-8628-2B3B01D890B6}</Project>
     156      <Name>HeuristicLab.Collections-3.3</Name>
     157    </ProjectReference>
    140158    <ProjectReference Include="..\..\HeuristicLab.Common.Resources\3.2\HeuristicLab.Common.Resources-3.2.csproj">
    141159      <Project>{0E27A536-1C4A-4624-A65E-DC4F4F23E3E1}</Project>
  • trunk/sources/HeuristicLab.Core/3.3/HeuristicLabCorePlugin.cs

    r2546 r2653  
    2929  /// Plugin class for HeuristicLab.Core plugin.
    3030  /// </summary>
    31   [ClassInfo(Name = "HeuristicLab.Core-3.3")]
    32   [PluginFile(Filename = "HeuristicLab.Core-3.3.dll", Filetype = PluginFileType.Assembly)]
    33   [Dependency(Dependency = "HeuristicLab.Common-3.2")]
    34   [Dependency(Dependency = "HeuristicLab.Common.Resources-3.2")]
    35   [Dependency(Dependency = "HeuristicLab.Persistence-3.3")]
     31  [Plugin("HeuristicLab.Core-3.3")]
     32  [PluginFile("HeuristicLab.Core-3.3.dll", PluginFileType.Assembly)]
     33  [PluginDependency("HeuristicLab.Collections-3.3")]
     34  [PluginDependency("HeuristicLab.Common-3.2")]
     35  [PluginDependency("HeuristicLab.Common.Resources-3.2")]
     36  [PluginDependency("HeuristicLab.Persistence-3.3")]
    3637  public class HeuristicLabCorePlugin : PluginBase {
    3738  }
  • trunk/sources/HeuristicLab.Core/3.3/Interfaces/IEngine.cs

    r2474 r2653  
    3535    /// Gets the operator graph of the current instance.
    3636    /// </summary>
    37     IOperatorGraph OperatorGraph { get; }
     37    OperatorGraph OperatorGraph { get; set; }
    3838    /// <summary>
    3939    /// Gets the global scope of the current instance.
    4040    /// </summary>
    41     IScope GlobalScope { get; }
     41    Scope GlobalScope { get; }
    4242
    4343    /// <summary>
     
    5151    bool Running { get; }
    5252    /// <summary>
    53     /// Gets information whether the engine is canceled.
    54     /// </summary>
    55     bool Canceled { get; }
    56     /// <summary>
    5753    /// Gets information whether the engine has already terminated.
    5854    /// </summary>
    59     bool Terminated { get; }
     55    bool Finished { get; }
    6056
     57    /// <summary>
     58    /// Resets the current instance.
     59    /// </summary>
     60    void Initialize();
    6161    /// <summary>
    6262    /// Executes the whole run.
    6363    /// </summary>
    64     void Execute();
     64    void Start();
    6565    /// <summary>
    6666    /// Executes one step (one operation).
    6767    /// </summary>
    68     void ExecuteStep();
    69     /// <summary>
    70     /// Executes the given number of steps.
    71     /// </summary>
    72     /// <param name="steps">The number of steps to execute.</param>
    73     void ExecuteSteps(int steps);
     68    void Step();
    7469    /// <summary>
    7570    /// Aborts the engine run.
    7671    /// </summary>
    77     void Abort();
    78     /// <summary>
    79     /// Resets the current instance.
    80     /// </summary>
    81     void Reset();
     72    void Stop();
    8273
    83     /// <summary>
    84     /// Occurs when the current instance is initialized.
    85     /// </summary>
    86     event EventHandler Initialized;
    87     /// <summary>
    88     /// Occurs when an operation is executed.
    89     /// </summary>
    90     event EventHandler<EventArgs<IOperation>> OperationExecuted;
    91     /// <summary>
    92     /// Occurs when an exception was thrown.
    93     /// </summary>
    94     event EventHandler<EventArgs<Exception>> ExceptionOccurred;
     74    event EventHandler OperatorGraphChanged;
    9575    /// <summary>
    9676    /// Occurs when the execution time was changed.
     
    9878    event EventHandler ExecutionTimeChanged;
    9979    /// <summary>
     80    /// Occurs when the engine is initialized.
     81    /// </summary>
     82    event EventHandler Initialized;
     83    /// <summary>
     84    /// Occurs when the engine is executed.
     85    /// </summary>
     86    event EventHandler Started;
     87    /// <summary>
    10088    /// Occurs when the engine is finished.
    10189    /// </summary>
    102     event EventHandler Finished;
     90    event EventHandler Stopped;
     91    /// <summary>
     92    /// Occurs when an exception was thrown.
     93    /// </summary>
     94    event EventHandler<EventArgs<Exception>> ExceptionOccurred;
    10395  }
    10496}
  • trunk/sources/HeuristicLab.Core/3.3/Interfaces/IItem.cs

    r2546 r2653  
    2222using System;
    2323using System.Collections.Generic;
     24using System.ComponentModel;
    2425using System.Text;
    2526using System.Drawing;
     
    2930  /// Interface to represent (almost) every HeuristicLab object (an object, an operator,...).
    3031  /// </summary>
    31   public interface IItem : ICloneable {
    32     string Name { get; }
    33     string Description { get; }
    34     Image Image { get; }
     32  public interface IItem : IDeepCloneable {
     33    string ItemName { get; }
     34    string ItemDescription { get; }
     35    Image ItemImage { get; }
    3536
    36     /// <summary>
    37     /// Creates a deep clone of this item.
    38     /// </summary>
    39     /// <param name="cloner">The cloner which is responsible for keeping track of all already
    40     /// cloned objects.</param>
    41     /// <returns>A clone of this instance.</returns>
    42     IItem Clone(ICloner cloner);
    43 
    44     /// <summary>
    45     /// Fires a new <c>Changed</c> event.
    46     /// </summary>
    47     void FireChanged();
    48 
    49     /// <summary>
    50     /// Occurs when the current instance has changed.
    51     /// </summary>
    52     event EventHandler Changed;
     37    event ChangedEventHandler Changed;
    5338  }
    5439}
  • trunk/sources/HeuristicLab.Core/3.3/Interfaces/IOperator.cs

    r2524 r2653  
    2424using System.Text;
    2525using HeuristicLab.Common;
     26using HeuristicLab.Collections;
    2627
    2728namespace HeuristicLab.Core {
     
    3031  /// a basic instruction of an algorithm.
    3132  /// </summary>
    32   public interface IOperator : IItem {
    33     /// <summary>
    34     /// Gets or sets the name of the current instance.
    35     /// </summary>
    36     string Name { get; set; }
    37     /// <summary>
    38     /// Gets or sets the description of the current instance.
    39     /// </summary>
    40     string Description { get; }
     33  public interface IOperator : INamedItem {
     34    IObservableKeyedCollection<string, IParameter> Parameters { get; }
    4135
    42     /// <summary>
    43     /// Gets information whether the current operator has been canceled.
    44     /// </summary>
    45     bool Canceled { get; }
    4636    /// <summary>
    4737    /// Gets or sets a boolean value whether the engine should stop here during the run.
     
    5040
    5141    /// <summary>
    52     /// Gets a list of all sub operators.
    53     /// </summary>
    54     IList<IOperator> SubOperators { get; }
    55     /// <summary>
    56     /// Gets a collection of all variable (parameter) infos.
    57     /// </summary>
    58     ICollection<IVariableInfo> VariableInfos { get; }
    59     /// <summary>
    60     /// Gets a collection of all variables of the current operator.
    61     /// </summary>
    62     ICollection<IVariable> Variables { get; }
    63 
    64     /// <summary>
    65     /// Adds the given sub operator to the current instance.
    66     /// </summary>
    67     /// <param name="op">The operator to add.</param>
    68     void AddSubOperator(IOperator op);
    69     /// <summary>
    70     /// Adds the given sub operator at a the specified <paramref name="index"/>.
    71     /// </summary>
    72     /// <param name="op">The operator to add.</param>
    73     /// <param name="index">The position where to add the operator.</param>
    74     void AddSubOperator(IOperator op, int index);
    75     /// <summary>
    76     /// Removes a sub operator at the specified <paramref name="index"/>.
    77     /// </summary>
    78     /// <param name="index">The position where to delete the operator.</param>
    79     void RemoveSubOperator(int index);
    80 
    81     /// <summary>
    82     /// Gets the variable info with the given <paramref name="formalName"/>.
    83     /// </summary>
    84     /// <param name="formalName">The formal name of the variable info.</param>
    85     /// <returns>The variable info with the specified formal name.</returns>
    86     IVariableInfo GetVariableInfo(string formalName);
    87     /// <summary>
    88     /// Adds the specified variable info to the current instance.
    89     /// </summary>
    90     /// <param name="variableInfo">The variable info to add.</param>
    91     void AddVariableInfo(IVariableInfo variableInfo);
    92     /// <summary>
    93     /// Removes the variable info with the given formal name.
    94     /// </summary>
    95     /// <param name="formalName">The formal name of the variable info to remove.</param>
    96     void RemoveVariableInfo(string formalName);
    97 
    98     /// <summary>
    99     /// Gets a variable with the given <paramref name="name"/>.
    100     /// </summary>
    101     /// <param name="name">The name of the variable.</param>
    102     /// <returns>The variable with the specified name.</returns>
    103     IVariable GetVariable(string name);
    104     /// <summary>
    105     /// Adds the specified <paramref name="variable"/> to the current instance.
    106     /// </summary>
    107     /// <param name="variable">The variable to add.</param>
    108     void AddVariable(IVariable variable);
    109     /// <summary>
    110     /// Deletes the variable with the specified <paramref name="name"/>.
    111     /// </summary>
    112     /// <param name="name">The name of the variable to delete.</param>
    113     void RemoveVariable(string name);
    114 
    115     /// <inheritdoc cref="GetVariableValue(string, HeuristicLab.Core.IScope, bool)"/>
    116     /// <typeparam name="T">The type of the value that is searched.</typeparam>       
    117     T GetVariableValue<T>(string formalName, IScope scope, bool recursiveLookup) where T : class, IItem;
    118     /// <inheritdoc cref="GetVariableValue(string, HeuristicLab.Core.IScope, bool, bool)"/>
    119     /// <typeparam name="T">The type of the value that is searched.</typeparam>
    120     T GetVariableValue<T>(string formalName, IScope scope, bool recursiveLookup, bool throwOnError) where T : class, IItem;
    121     /// <inheritdoc cref="GetVariableValue(System.String, IScope, bool, bool)"
    122     /// select="summary"/>
    123     /// <param name="formalName">The formal name of the variable info whose variable value is searched.</param>
    124     /// <param name="scope">The scope where to look for the variable.</param>
    125     /// <param name="recursiveLookup">Boolean value, whether also the parent scopes shall be searched if
    126     /// the variable is not found in the specified <paramref name="scope"/>.</param>
    127     /// <returns>The value of the searched variable or null if it is not found.</returns>
    128     IItem GetVariableValue(string formalName, IScope scope, bool recursiveLookup);
    129     /// <summary>
    130     /// Gets the value of the variable in the specified <paramref name="scope"/>
    131     /// whose variable(parameter) info has the specified <paramref name="formalName"/>.
    132     /// </summary>
    133     /// <param name="formalName">The formal name of the variable info whose variable value is searched.</param>
    134     /// <param name="scope">The scope where to look for the variable.</param>
    135     /// <param name="recursiveLookup">Boolean value, whether also the parent scopes shall be searched if
    136     /// the variable is not found in the specified <paramref name="scope"/>.</param>
    137     /// <param name="throwOnError">Boolean value, whether an exception shall be thrown, if the variable
    138     /// cannot be found or just <c>null</c> shall be returned.</param>
    139     /// <returns>The value of the searched variable (or null if the variable is not
    140     /// found and <paramref name="throwOnError"/> is set to false).</returns>
    141     IItem GetVariableValue(string formalName, IScope scope, bool recursiveLookup, bool throwOnError);
    142 
    143     /// <summary>
    14442    /// Executes the current instance on the specified <paramref name="scope"/>.
    14543    /// </summary>
    14644    /// <param name="scope">The scope where to execute the current instance.</param>
    14745    /// <returns>The next operation.</returns>
    148     IOperation Execute(IScope scope);
     46    ExecutionContextCollection Execute(ExecutionContext context);
    14947    /// <summary>
    15048    /// Aborts the current operator.
     
    15351
    15452    /// <summary>
    155     /// Occurs when the name of the operator was changed.
    156     /// </summary>
    157     event EventHandler NameChanged;
    158     /// <summary>
    15953    /// Occurs when the breakpoint flag of the current instance was changed.
    16054    /// </summary>
    16155    event EventHandler BreakpointChanged;
    162     /// <summary>
    163     /// Occurs when a sub operator has been added.
    164     /// </summary>
    165     event EventHandler<EventArgs<IOperator, int>> SubOperatorAdded;
    166     /// <summary>
    167     /// Occurs when a sub operator has been deleted.
    168     /// </summary>
    169     event EventHandler<EventArgs<IOperator, int>> SubOperatorRemoved;
    170     /// <summary>
    171     /// Occurs when a variable info has been added.
    172     /// </summary>
    173     event EventHandler<EventArgs<IVariableInfo>> VariableInfoAdded;
    174     /// <summary>
    175     /// Occurs when a variable info has been deleted.
    176     /// </summary>
    177     event EventHandler<EventArgs<IVariableInfo>> VariableInfoRemoved;
    178     /// <summary>
    179     /// Occurs when a variable has been added.
    180     /// </summary>
    181     event EventHandler<EventArgs<IVariable>> VariableAdded;
    182     /// <summary>
    183     /// Occurs when a variable has been deleted.
    184     /// </summary>
    185     event EventHandler<EventArgs<IVariable>> VariableRemoved;
    18656    /// <summary>
    18757    /// Occurs when the current instance is executed.
  • trunk/sources/HeuristicLab.Core/3.3/ItemBase.cs

    r2546 r2653  
    2222using System;
    2323using System.Collections.Generic;
     24using System.ComponentModel;
    2425using System.Text;
    2526using System.Xml;
     
    3334  /// Represents the base class for all basic item types.
    3435  /// </summary>
     36  [EmptyStorableClass]
    3537  [Item("ItemBase", "Base class for all HeuristicLab items.")]
    36   [EmptyStorableClass]
    37   public abstract class ItemBase : IItem {
    38     public virtual string Name {
    39       get {
    40         if (ItemAttribute.GetName(this.GetType()) != null)
    41           return ItemAttribute.GetName(this.GetType());
    42         else
    43           return this.GetType().Name;
    44       }
     38  public abstract class ItemBase : DeepCloneableBase, IItem {
     39    public virtual string ItemName {
     40      get { return ItemAttribute.GetName(this.GetType()); }
    4541    }
    46     public virtual string Description {
    47       get {
    48         if (ItemAttribute.GetDescription(this.GetType()) != null)
    49           return ItemAttribute.GetDescription(this.GetType());
    50         else
    51           return "No description available.";
    52       }
     42    public virtual string ItemDescription {
     43      get { return ItemAttribute.GetDescription(this.GetType()); }
    5344    }
    54     public virtual Image Image {
    55       get { return Resources.HeuristicLab; }
    56     }
    57 
    58     /// <summary>
    59     /// Creates a deep clone of this instance.
    60     /// </summary>
    61     /// <remarks>
    62     /// This method is the entry point for creating a deep clone of a whole object graph.
    63     /// </remarks>
    64     /// <returns>A clone of this instance.</returns>
    65     public object Clone() {
    66       return Clone(new Cloner());
    67     }
    68 
    69     /// <summary>
    70     /// Creates a deep clone of this instance.
    71     /// </summary>
    72     /// <remarks>This method should not be called directly. It is used for creating clones of
    73     /// objects which are contained in the object that is currently cloned.</remarks>
    74     /// <param name="cloner">The cloner which is responsible for keeping track of all already
    75     /// cloned objects.</param>
    76     /// <returns>A clone of this instance.</returns>
    77     public virtual IItem Clone(ICloner cloner) {
    78       ItemBase clone = (ItemBase)Activator.CreateInstance(this.GetType());
    79       cloner.RegisterClonedObject(this, clone);
    80       return clone;
     45    public virtual Image ItemImage {
     46      get { return VS2008ImageLibrary.Class; }
    8147    }
    8248
     
    8652    /// <returns>The type name of the current instance.</returns>
    8753    public override string ToString() {
    88       return GetType().Name;
     54      return ItemName;
    8955    }
    9056
    91     /// <summary>
    92     /// Fires a new <c>Changed</c> event.
    93     /// </summary>
    94     /// <remarks>Calls <see cref="OnChanged"/>.</remarks>
    95     public void FireChanged() {
    96       OnChanged();
     57    public event ChangedEventHandler Changed;
     58    protected void OnChanged() {
     59      OnChanged(new ChangedEventArgs());
    9760    }
    98 
    99     /// <summary>
    100     /// Occurs when the current item was changed.
    101     /// </summary>
    102     public event EventHandler Changed;
    103     /// <summary>
    104     /// Fires a new <c>Changed</c> event.
    105     /// </summary>
    106     protected virtual void OnChanged() {
    107       if (Changed != null)
    108         Changed(this, new EventArgs());
     61    protected virtual void OnChanged(ChangedEventArgs e) {
     62      if ((e.RegisterChangedObject(this)) && (Changed != null))
     63          Changed(this, e);
    10964    }
    11065  }
  • trunk/sources/HeuristicLab.Core/3.3/OperatorBase.cs

    r2526 r2653  
    2424using System.Text;
    2525using System.Xml;
     26using System.Drawing;
    2627using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2728using HeuristicLab.Common;
     29using HeuristicLab.Collections;
    2830
    2931namespace HeuristicLab.Core {
     
    3133  /// The base class for all operators.
    3234  /// </summary>
    33   public abstract class OperatorBase : ItemBase, IOperator {
     35  [Item("OperatorBase", "Base class for operators.")]
     36  public abstract class OperatorBase : NamedItemBase, IOperator {
     37    public override Image ItemImage {
     38      get { return HeuristicLab.Common.Resources.VS2008ImageLibrary.Method; }
     39    }
    3440
     41    private ParameterCollection parameters;
    3542    [Storable]
    36     private string myName;
    37     /// <summary>
    38     /// Gets or sets the name of the operator.
    39     /// </summary>
    40     /// <remarks>Calls <see cref="OnNameChanged"/> in the setter.</remarks>
    41     public string Name {
    42       get { return myName; }
    43       set {
    44         if (myName != value) {
    45           myName = value;
    46           OnNameChanged();
    47         }
     43    protected ParameterCollection Parameters {
     44      get { return parameters;}
     45      private set {
     46        if (parameters != null) parameters.Changed -= new ChangedEventHandler(Parameters_Changed);
     47        parameters = value;
     48        readOnlyParameters = null;
     49        if (parameters != null) parameters.Changed += new ChangedEventHandler(Parameters_Changed);
    4850      }
    4951    }
    50     /// <summary>
    51     /// Gets the description of the current operator.
    52     /// </summary>
    53     /// <remarks>Returns "No operator description available" if the method is not overriden.</remarks>
    54     public virtual string Description {
    55       get { return "No operator description available."; }
     52    private ReadOnlyObservableKeyedCollection<string, IParameter> readOnlyParameters;
     53    IObservableKeyedCollection<string, IParameter> IOperator.Parameters {
     54      get {
     55        if (readOnlyParameters == null) readOnlyParameters = parameters.AsReadOnly();
     56        return readOnlyParameters;
     57      }
    5658    }
     59
    5760    /// <summary>
    5861    /// Flag whether the current instance has been canceled.
    5962    /// </summary>
    60     protected bool myCanceled;
     63    private bool canceled;
    6164    /// <inheritdoc/>
    62     public bool Canceled {
    63       get { return myCanceled; }
     65    protected bool Canceled {
     66      get { return canceled; }
    6467    }
    6568
    6669    [Storable]
    67     private bool myBreakpoint;
     70    private bool breakpoint;
    6871    /// <inheritdoc/>
    6972    /// <remarks>Calls <see cref="OnBreakpointChanged"/> in the setter.</remarks>
    7073    public bool Breakpoint {
    71       get { return myBreakpoint; }
     74      get { return breakpoint; }
    7275      set {
    73         if (value != myBreakpoint) {
    74           myBreakpoint = value;
     76        if (value != breakpoint) {
     77          breakpoint = value;
    7578          OnBreakpointChanged();
    76         }
    77       }
    78     }
    79 
    80     [Storable]
    81     private List<IOperator> mySubOperators;
    82     /// <summary>
    83     /// Gets a list of all suboperators.
    84     /// <note type="caution"> Returns the suboperators read-only!</note>
    85     /// </summary>
    86     public virtual IList<IOperator> SubOperators {
    87       get { return mySubOperators.AsReadOnly(); }
    88     }
    89 
    90     [Storable]
    91     private Dictionary<string, IVariableInfo> myVariableInfos;
    92     /// <inheritdoc/>
    93     public virtual ICollection<IVariableInfo> VariableInfos {
    94       get { return myVariableInfos.Values; }
    95     }
    96    
    97     private Dictionary<string, IVariable> myVariables;
    98     /// <inheritdoc/>   
    99     public virtual ICollection<IVariable> Variables {
    100       get { return myVariables.Values; }
    101     }
    102 
    103     [Storable(Name="Variables")]
    104     private List<IVariable> VariablePersistence {
    105       get { return new List<IVariable>(myVariables.Values); }
    106       set {
    107         myVariables.Clear();
    108         foreach (IVariable var in value) {
    109           AddVariable(var);
    11079        }
    11180      }
     
    11786    /// </summary>
    11887    protected OperatorBase() {
    119       myName = this.GetType().Name;
    120       myCanceled = false;
    121       myBreakpoint = false;
    122       mySubOperators = new List<IOperator>();
    123       myVariableInfos = new Dictionary<string, IVariableInfo>();
    124       myVariables = new Dictionary<string, IVariable>();
     88      name = ItemName;
     89      Parameters = new ParameterCollection();
     90      readOnlyParameters = null;
     91      canceled = false;
     92      breakpoint = false;
    12593    }
    12694
     
    13199    /// <param name="clonedObjects">Dictionary of all already cloned objects. (Needed to avoid cycles.)</param>
    132100    /// <returns>The cloned object as <see cref="OperatorBase"/>.</returns>
    133     public override IItem Clone(ICloner cloner) {
     101    public override IDeepCloneable Clone(Cloner cloner) {
    134102      OperatorBase clone = (OperatorBase)base.Clone(cloner);
    135       clone.myName = Name;
    136       clone.mySubOperators.Clear();
    137       for (int i = 0; i < SubOperators.Count; i++)
    138         clone.AddSubOperator((IOperator)cloner.Clone(SubOperators[i]));
    139       clone.myVariableInfos.Clear();
    140       foreach (IVariableInfo variableInfo in myVariableInfos.Values)
    141         clone.AddVariableInfo((IVariableInfo)cloner.Clone(variableInfo));
    142       clone.myVariables.Clear();
    143       foreach (IVariable variable in myVariables.Values)
    144         clone.AddVariable((IVariable)cloner.Clone(variable));
     103      clone.Parameters = (ParameterCollection)cloner.Clone(parameters);
     104      clone.canceled = canceled;
     105      clone.breakpoint = breakpoint;
    145106      return clone;
    146107    }
    147108
    148     #region SubOperator Methods
    149     /// <inheritdoc cref="HeuristicLab.Core.IOperator.AddSubOperator(HeuristicLab.Core.IOperator)"/>
    150     /// <param name="subOperator">The sub operator to add.</param>
    151     /// <remarks>Calls <see cref="OnSubOperatorAdded"/>.</remarks>
    152     public virtual void AddSubOperator(IOperator subOperator) {
    153       mySubOperators.Add(subOperator);
    154       OnSubOperatorAdded(subOperator, mySubOperators.Count - 1);
    155     }
    156     /// <inheritdoc cref="HeuristicLab.Core.IOperator.AddSubOperator(HeuristicLab.Core.IOperator, int)"/>
    157     /// <param name="subOperator">The sub operator to add.</param>
    158     /// <remarks>Calls <see cref="OnSubOperatorAdded"/>.</remarks>
    159     public virtual void AddSubOperator(IOperator subOperator, int index) {
    160       mySubOperators.Insert(index, subOperator);
    161       OnSubOperatorAdded(subOperator, index);
    162     }
    163109    /// <inheritdoc/>
    164     /// <remarks>Calls <see cref="OnSubOperatorRemoved"/>.</remarks>
    165     public virtual void RemoveSubOperator(int index) {
    166       IOperator op = mySubOperators[index];
    167       mySubOperators.RemoveAt(index);
    168       OnSubOperatorRemoved(op, index);
    169     }
    170     #endregion
    171 
    172     #region VariableInfo Methods
    173     /// <inheritdoc/>
    174     public virtual IVariableInfo GetVariableInfo(string formalName) {
    175       IVariableInfo info;
    176       if (myVariableInfos.TryGetValue(formalName, out info))
    177         return info;
    178       else
    179         return null;
    180     }
    181     /// <inheritdoc/>
    182     /// <remarks>Calls <see cref="OnVariableInfoAdded"/>.</remarks>
    183     public virtual void AddVariableInfo(IVariableInfo variableInfo) {
    184       myVariableInfos.Add(variableInfo.FormalName, variableInfo);
    185       OnVariableInfoAdded(variableInfo);
    186     }
    187     /// <inheritdoc/>
    188     /// <remarks>Calls <see cref="OnVariableInfoRemoved"/>.</remarks>
    189     public virtual void RemoveVariableInfo(string formalName) {
    190       IVariableInfo variableInfo;
    191       if (myVariableInfos.TryGetValue(formalName, out variableInfo)) {
    192         myVariableInfos.Remove(formalName);
    193         OnVariableInfoRemoved(variableInfo);
    194       }
    195     }
    196     #endregion
    197 
    198     #region Variable Methods
    199     /// <inheritdoc/>
    200     public virtual IVariable GetVariable(string name) {
    201       IVariable variable;
    202       if (myVariables.TryGetValue(name, out variable))
    203         return variable;
    204       else
    205         return null;
    206     }
    207     /// <inheritdoc/>
    208     /// <remarks>Calls <see cref="OnVariableAdded"/> and adds <c>NameChanging</c> and <c>NameChanged</c>
    209     /// event handlers.</remarks>
    210     public virtual void AddVariable(IVariable variable) {
    211       myVariables.Add(variable.Name, variable);
    212       variable.NameChanging += new EventHandler<CancelEventArgs<string>>(Variable_NameChanging);
    213       variable.NameChanged += new EventHandler(Variable_NameChanged);
    214       OnVariableAdded(variable);
    215     }
    216     /// <inheritdoc/>
    217     /// <remarks>Calls <see cref="OnVariableRemoved"/> and removes <c>NameChanging</c> and <c>NameChanged</c>
    218     /// event handlers.</remarks>
    219     public virtual void RemoveVariable(string name) {
    220       IVariable variable;
    221       if (myVariables.TryGetValue(name, out variable)) {
    222         variable.NameChanging -= new EventHandler<CancelEventArgs<string>>(Variable_NameChanging);
    223         variable.NameChanged -= new EventHandler(Variable_NameChanged);
    224         myVariables.Remove(name);
    225         OnVariableRemoved(variable);
    226       }
    227     }
    228     private void Variable_NameChanging(object sender, CancelEventArgs<string> e) {
    229       e.Cancel = myVariables.ContainsKey(e.Value);
    230     }
    231     private void Variable_NameChanged(object sender, EventArgs e) {
    232       IVariable variable = (IVariable)sender;
    233       string oldName = null;
    234       foreach (KeyValuePair<string, IVariable> element in myVariables) {
    235         if (element.Value == variable)
    236           oldName = element.Key;
    237       }
    238       myVariables.Remove(oldName);
    239       myVariables.Add(variable.Name, variable);
    240     }
    241     /// <inheritdoc cref="IOperator.GetVariableValue&lt;T&gt;(string, HeuristicLab.Core.IScope, bool)"/>
    242     ///  <remarks>Calls <see cref="GetVariableValue&lt;T&gt;(string, HeuristicLab.Core.IScope, bool, bool)"/>
    243     /// with <c>throwOnError</c> set to <c>false</c>.</remarks>
    244     public T GetVariableValue<T>(string formalName, IScope scope, bool recursiveLookup) where T : class, IItem {
    245       return GetVariableValue<T>(formalName, scope, recursiveLookup, true);
    246     }
    247     /// <inheritdoc cref="IOperator.GetVariableValue&lt;T&gt;(string, HeuristicLab.Core.IScope, bool, bool)"/>
    248     /// <remarks>Calls
    249     /// <see cref="GetVariableValue(string, HeuristicLab.Core.IScope, bool, bool)"/>.</remarks>
    250     public T GetVariableValue<T>(string formalName, IScope scope, bool recursiveLookup, bool throwOnError) where T : class, IItem {
    251       return (T)GetVariableValue(formalName, scope, recursiveLookup, throwOnError);
    252     }
    253     /// <inheritdoc cref="IOperator.GetVariableValue(string, HeuristicLab.Core.IScope, bool)"/>
    254     /// <remarks>Calls <see cref="GetVariableValue(string, HeuristicLab.Core.IScope, bool, bool)"/>
    255     /// with <c>throwOnError</c> set to <c>false</c>.</remarks>
    256     public IItem GetVariableValue(string formalName, IScope scope, bool recursiveLookup) {
    257       return GetVariableValue(formalName, scope, recursiveLookup, true);
    258     }
    259     /// <inheritdoc cref="IOperator.GetVariableValue(string, HeuristicLab.Core.IScope, bool, bool)"/>
    260     public virtual IItem GetVariableValue(string formalName, IScope scope, bool recursiveLookup, bool throwOnError) {
    261       IVariableInfo info = GetVariableInfo(formalName);
    262       if (info.Local) {
    263         IVariable variable;
    264         if (myVariables.TryGetValue(info.ActualName, out variable))
    265           return variable.Value;
    266         else {
    267           if (throwOnError)
    268             throw new ArgumentException("Variable " + info.ActualName + " not found");
    269           else
    270             return null;
    271         }
    272       } else {
    273         return scope.GetVariableValue(formalName, recursiveLookup, throwOnError);
    274       }
    275     }
    276     #endregion
    277     /// <inheritdoc/>
    278     public virtual IOperation Execute(IScope scope) {
    279       myCanceled = false;
    280 
    281       foreach (IVariableInfo variableInfo in VariableInfos)
    282         scope.AddAlias(variableInfo.FormalName, variableInfo.ActualName);
    283 
    284       IOperation next = Apply(scope);
    285 
    286       foreach (IVariableInfo variableInfo in VariableInfos)
    287         scope.RemoveAlias(variableInfo.FormalName);
    288 
     110    public virtual ExecutionContextCollection Execute(ExecutionContext context) {
     111      canceled = false;
     112      ExecutionContextCollection next = Apply(context);
    289113      OnExecuted();
    290114      return next;
     
    293117    /// <remarks>Sets property <see cref="Canceled"/> to <c>true</c>.</remarks>
    294118    public virtual void Abort() {
    295       myCanceled = true;
     119      canceled = true;
    296120    }
    297121    /// <summary>
     
    300124    /// <param name="scope">The scope where to execute the operator</param>
    301125    /// <returns><c>null</c>.</returns>
    302     public virtual IOperation Apply(IScope scope) {
    303       return null;
     126    public virtual ExecutionContextCollection Apply(ExecutionContext context) {
     127      return new ExecutionContextCollection();
    304128    }
    305     /// <inheritdoc/>
    306     public event EventHandler NameChanged;
    307     /// <summary>
    308     /// Fires a new <c>NameChanged</c> event.
    309     /// </summary>
    310     protected virtual void OnNameChanged() {
    311       if (NameChanged != null) {
    312         NameChanged(this, new EventArgs());
    313       }
    314     }
     129
    315130    /// <inheritdoc/>
    316131    public event EventHandler BreakpointChanged;
     
    322137        BreakpointChanged(this, new EventArgs());
    323138      }
    324     }
    325     /// <inheritdoc/>
    326     public event EventHandler<EventArgs<IOperator, int>> SubOperatorAdded;
    327     /// <summary>
    328     /// Fires a new <c>SubOperatorAdded</c> event.
    329     /// </summary>
    330     /// <param name="subOperator">The sub operator that has been added.</param>
    331     /// <param name="index">The position where the operator has been added.</param>
    332     protected virtual void OnSubOperatorAdded(IOperator subOperator, int index) {
    333       if (SubOperatorAdded != null)
    334         SubOperatorAdded(this, new EventArgs<IOperator, int>(subOperator, index));
    335     }
    336     /// <inheritdoc/>
    337     public event EventHandler<EventArgs<IOperator, int>> SubOperatorRemoved;
    338     /// <summary>
    339     /// Fires a new <c>SubOperatorRemoved</c> event.
    340     /// </summary>
    341     /// <param name="subOperator">The sub operator that has been removed.</param>
    342     /// <param name="index">The position where the operator has been removed.</param>
    343     protected virtual void OnSubOperatorRemoved(IOperator subOperator, int index) {
    344       if (SubOperatorRemoved != null)
    345         SubOperatorRemoved(this, new EventArgs<IOperator, int>(subOperator, index));
    346     }
    347     /// <inheritdoc/>
    348     public event EventHandler<EventArgs<IVariableInfo>> VariableInfoAdded;
    349     /// <summary>
    350     /// Fires a new <c>VariableInfoAdded</c> event.
    351     /// </summary>
    352     /// <param name="variableInfo">The variable info that has been added.</param>
    353     protected virtual void OnVariableInfoAdded(IVariableInfo variableInfo) {
    354       if (VariableInfoAdded != null)
    355         VariableInfoAdded(this, new EventArgs<IVariableInfo>(variableInfo));
    356     }
    357     /// <inheritdoc/>
    358     public event EventHandler<EventArgs<IVariableInfo>> VariableInfoRemoved;
    359     /// <summary>
    360     /// Fires a new <c>VariableInfoRemoved</c> event.
    361     /// </summary>
    362     /// <param name="variableInfo">The variable info that has been removed.</param>
    363     protected virtual void OnVariableInfoRemoved(IVariableInfo variableInfo) {
    364       if (VariableInfoRemoved != null)
    365         VariableInfoRemoved(this, new EventArgs<IVariableInfo>(variableInfo));
    366     }
    367     /// <inheritdoc/>
    368     public event EventHandler<EventArgs<IVariable>> VariableAdded;
    369     /// <summary>
    370     /// Fires a new <c>VariableAdded</c> event.
    371     /// </summary>
    372     /// <param name="variable">The variable that has been added.</param>
    373     protected virtual void OnVariableAdded(IVariable variable) {
    374       if (VariableAdded != null)
    375         VariableAdded(this, new EventArgs<IVariable>(variable));
    376     }
    377     /// <inheritdoc/>
    378     public event EventHandler<EventArgs<IVariable>> VariableRemoved;
    379     /// <summary>
    380     /// Fires a new <c>VariableRemoved</c> event.
    381     /// </summary>
    382     /// <param name="variable">The variable that has been removed</param>
    383     protected virtual void OnVariableRemoved(IVariable variable) {
    384       if (VariableRemoved != null)
    385         VariableRemoved(this, new EventArgs<IVariable>(variable));
     139      OnChanged();
    386140    }
    387141    /// <inheritdoc/>
     
    395149      }
    396150    }
     151
     152    private void Parameters_Changed(object sender, ChangedEventArgs e) {
     153      OnChanged(e);
     154    }
    397155  }
    398156}
  • trunk/sources/HeuristicLab.Core/3.3/OperatorGraph.cs

    r2526 r2653  
    2424using System.Text;
    2525using System.Xml;
     26using System.Linq;
    2627using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    2728using HeuristicLab.Common;
     29using HeuristicLab.Collections;
    2830
    2931namespace HeuristicLab.Core {
     
    3133  /// Represents a graph of operators.
    3234  /// </summary>
    33   public class OperatorGraph : ItemBase, IOperatorGraph {
    34 
     35  [Item("OperatorGraph", "Represents a graph of operators.")]
     36  [Creatable("Test")]
     37  public class OperatorGraph : ItemBase {
     38    private OperatorSet operators;
     39    /// <summary>
     40    /// Gets all operators of the current instance.
     41    /// </summary>
    3542    [Storable]
    36     private IDictionary<IOperator, IOperator> myOperators;
    37     /// <summary>
    38     /// Gets all operators of the current instance.
    39     /// </summary>
    40     public ICollection<IOperator> Operators {
    41       get { return myOperators.Values; }
     43    public OperatorSet Operators {
     44      get { return operators; }
     45      private set {
     46        DeregisterOperatorsEvents();
     47        operators = value;
     48        RegisterOperatorsEvents();
     49      }
    4250    }
    4351
    4452    [Storable]
    45     private IOperator myInitialOperator;
     53    private IOperator initialOperator;
    4654    /// <summary>
    4755    /// Gets or sets the initial operator (the starting one).
     
    4957    /// <remarks>Calls <see cref="OnInitialOperatorChanged"/> in the setter.</remarks>
    5058    public IOperator InitialOperator {
    51       get { return myInitialOperator; }
     59      get { return initialOperator; }
    5260      set {
    53         if (myInitialOperator != value) {
    54           myInitialOperator = value;
     61        if (initialOperator != value) {
     62          if (value != null) Operators.Add(value);
     63          initialOperator = value;
    5564          OnInitialOperatorChanged();
    5665        }
     
    6271    /// </summary>
    6372    public OperatorGraph() {
    64       myOperators = new Dictionary<IOperator, IOperator>();
     73      Operators = new OperatorSet();
     74      initialOperator = null;
    6575    }
    6676
     
    7282    /// <param name="clonedObjects">Dictionary of all already cloned objects. (Needed to avoid cycles.)</param>
    7383    /// <returns>The cloned object as <see cref="OperatorGraph"/>.</returns>
    74     public override IItem Clone(ICloner cloner) {
     84    public override IDeepCloneable Clone(Cloner cloner) {
    7585      OperatorGraph clone = new OperatorGraph();
    7686      cloner.RegisterClonedObject(this, clone);
    77       foreach (IOperator op in Operators)
    78         clone.AddOperator((IOperator)cloner.Clone(op));
    79       if (InitialOperator != null)
    80         clone.myInitialOperator = (IOperator)cloner.Clone(InitialOperator);
     87      clone.Operators = (OperatorSet)cloner.Clone(operators);
     88      clone.initialOperator = (IOperator)cloner.Clone(initialOperator);
    8189      return clone;
    8290    }
    8391
    84     /// <inheritdoc/>
    85     /// <remarks>Calls <see cref="OnOperatorAdded"/>.</remarks>
    86     public void AddOperator(IOperator op) {
    87       if (!myOperators.ContainsKey(op)) {
    88         myOperators.Add(op, op);
    89         OnOperatorAdded(op);
    90 
    91         foreach (IOperator subOperator in op.SubOperators)
    92           AddOperator(subOperator);
    93       }
    94     }
    95     /// <inheritdoc/>
    96     /// <remarks>Calls <see cref="OnOperatorRemoved"/>.</remarks>
    97     public void RemoveOperator(IOperator op) {
    98       if (myOperators.ContainsKey(op)) {
    99         foreach (IOperator o in Operators) {
    100           int i = 0;
    101           while (i < o.SubOperators.Count) {
    102             if (o.SubOperators[i] == op)
    103               o.RemoveSubOperator(i);
    104             else
    105               i++;
    106           }
    107         }
    108         if (InitialOperator == op)
    109           InitialOperator = null;
    110         myOperators.Remove(op);
    111         OnOperatorRemoved(op);
    112       }
    113     }
    114     /// <inheritdoc/>
    115     public void Clear() {
    116       IOperator[] ops = new IOperator[Operators.Count];
    117       int i = 0;
    118       foreach (IOperator op in Operators) {
    119         ops[i] = op;
    120         i++;
    121       }
    122       for (int j = 0; j < ops.Length; j++)
    123         RemoveOperator(ops[j]);
    124     }
    125 
    126     /// <inheritdoc/>
    127     public event EventHandler<EventArgs<IOperator>> OperatorAdded;
    128     /// <summary>
    129     /// Fires a new <c>OperatorAdded</c> event.
    130     /// </summary>
    131     /// <param name="op">The operator that has been added.</param>
    132     protected virtual void OnOperatorAdded(IOperator op) {
    133       if (OperatorAdded != null)
    134         OperatorAdded(this, new EventArgs<IOperator>(op));
    135     }
    136     /// <inheritdoc/>
    137     public event EventHandler<EventArgs<IOperator>> OperatorRemoved;
    138     /// <summary>
    139     /// Fires a new <c>OperatorRemoved</c> event.
    140     /// </summary>
    141     /// <param name="op">The operator that has been removed.</param>
    142     protected virtual void OnOperatorRemoved(IOperator op) {
    143       if (OperatorRemoved != null)
    144         OperatorRemoved(this, new EventArgs<IOperator>(op));
    145     }
    14692    /// <inheritdoc/>
    14793    public event EventHandler InitialOperatorChanged;
     
    15298      if (InitialOperatorChanged != null)
    15399        InitialOperatorChanged(this, new EventArgs());
    154     }
     100      OnChanged();
     101    }
     102
     103    #region Operators Events
     104    private void AddOperator(IOperator op) {
     105      RegisterOperatorEvents(op);
     106      foreach (IParameter param in op.Parameters)
     107        AddParameter(param);
     108    }
     109    private void RemoveOperator(IOperator op) {
     110      foreach (IParameter param in op.Parameters)
     111        RemoveParameter(param);
     112      DeregisterOperatorEvents(op);
     113
     114      // remove edges to removed operator
     115      var opParams = from o in Operators
     116                     from p in o.Parameters
     117                     where p is IOperatorParameter
     118                     where (((IOperatorParameter)p).Value != null) && (((IOperatorParameter)p).Value == op)
     119                     select (IOperatorParameter)p;
     120      foreach (IOperatorParameter opParam in opParams)
     121        opParam.Value = null;
     122    }
     123    private void AddParameter(IParameter param) {
     124      IOperatorParameter opParam = param as IOperatorParameter;
     125      if (opParam != null) {
     126        RegisterOperatorParameterEvents(opParam);
     127        if (opParam.Value != null) Operators.Add(opParam.Value);
     128      }
     129    }
     130    private void RemoveParameter(IParameter param) {
     131      IOperatorParameter opParam = param as IOperatorParameter;
     132      if (opParam != null) {
     133        DeregisterOperatorParameterEvents(opParam);
     134      }
     135    }
     136
     137    private void RegisterOperatorsEvents() {
     138      if (operators != null) {
     139        operators.Changed += new ChangedEventHandler(Operators_Changed);
     140        operators.ItemsAdded += new CollectionItemsChangedEventHandler<IOperator>(Operators_ItemsAdded);
     141        operators.ItemsRemoved += new CollectionItemsChangedEventHandler<IOperator>(Operators_ItemsRemoved);
     142        operators.CollectionReset += new CollectionItemsChangedEventHandler<IOperator>(Operators_CollectionReset);
     143      }
     144    }
     145    private void DeregisterOperatorsEvents() {
     146      if (operators != null) {
     147        operators.Changed -= new ChangedEventHandler(Operators_Changed);
     148        operators.ItemsAdded -= new CollectionItemsChangedEventHandler<IOperator>(Operators_ItemsAdded);
     149        operators.ItemsRemoved -= new CollectionItemsChangedEventHandler<IOperator>(Operators_ItemsRemoved);
     150        operators.CollectionReset -= new CollectionItemsChangedEventHandler<IOperator>(Operators_CollectionReset);
     151      }
     152    }
     153    private void RegisterOperatorEvents(IOperator op) {
     154      op.Parameters.ItemsAdded += new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsAdded);
     155      op.Parameters.ItemsRemoved += new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsRemoved);
     156      op.Parameters.ItemsReplaced += new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsReplaced);
     157      op.Parameters.CollectionReset += new CollectionItemsChangedEventHandler<IParameter>(Parameters_CollectionReset);
     158    }
     159    private void DeregisterOperatorEvents(IOperator op) {
     160      op.Parameters.ItemsAdded -= new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsAdded);
     161      op.Parameters.ItemsRemoved -= new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsRemoved);
     162      op.Parameters.ItemsReplaced -= new CollectionItemsChangedEventHandler<IParameter>(Parameters_ItemsReplaced);
     163      op.Parameters.CollectionReset -= new CollectionItemsChangedEventHandler<IParameter>(Parameters_CollectionReset);
     164    }
     165    private void RegisterOperatorParameterEvents(IOperatorParameter opParam) {
     166      opParam.ValueChanged += new EventHandler(opParam_ValueChanged);
     167    }
     168    private void DeregisterOperatorParameterEvents(IOperatorParameter opParam) {
     169      opParam.ValueChanged -= new EventHandler(opParam_ValueChanged);
     170    }
     171
     172    private void Operators_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IOperator> e) {
     173      foreach (IOperator op in e.Items)
     174        AddOperator(op);
     175    }
     176    private void Operators_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IOperator> e) {
     177      foreach (IOperator op in e.Items)
     178        RemoveOperator(op);
     179      if (!Operators.Contains(InitialOperator)) InitialOperator = null;
     180    }
     181    private void Operators_CollectionReset(object sender, CollectionItemsChangedEventArgs<IOperator> e) {
     182      foreach (IOperator op in e.OldItems)
     183        RemoveOperator(op);
     184      foreach (IOperator op in e.Items)
     185        AddOperator(op);
     186      if (!Operators.Contains(InitialOperator)) InitialOperator = null;
     187    }
     188    private void Parameters_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IParameter> e) {
     189      foreach (IParameter param in e.Items)
     190        AddParameter(param);
     191    }
     192    private void Parameters_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IParameter> e) {
     193      foreach (IParameter param in e.Items)
     194        RemoveParameter(param);
     195    }
     196    private void Parameters_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IParameter> e) {
     197      foreach (IParameter param in e.OldItems)
     198        RemoveParameter(param);
     199      foreach (IParameter param in e.Items)
     200        AddParameter(param);
     201    }
     202    private void Parameters_CollectionReset(object sender, CollectionItemsChangedEventArgs<IParameter> e) {
     203      foreach (IParameter param in e.OldItems)
     204        RemoveParameter(param);
     205      foreach (IParameter param in e.Items)
     206        AddParameter(param);
     207    }
     208    private void opParam_ValueChanged(object sender, EventArgs e) {
     209      IOperatorParameter opParam = (IOperatorParameter)sender;
     210      if (opParam.Value != null) Operators.Add(opParam.Value);
     211    }
     212    private void Operators_Changed(object sender, ChangedEventArgs e) {
     213      OnChanged(e);
     214    }
     215    #endregion
    155216  }
    156217}
  • trunk/sources/HeuristicLab.Core/3.3/Scope.cs

    r2526 r2653  
    2525using System.Xml;
    2626using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    27 using HeuristicLab.Common;
     27using HeuristicLab.Collections;
    2828
    2929namespace HeuristicLab.Core {
     
    3131  /// Hierarchical container of variables (and of subscopes).
    3232  /// </summary>
    33   public class Scope : ItemBase, IScope {
     33  [Item("Scope", "A scope which contains variables and sub-scopes.")]
     34  [Creatable("Test")]
     35  public class Scope : NamedItemBase {
     36    [Storable]
     37    private Scope parent;
    3438
     39    private VariableCollection variables;
    3540    [Storable]
    36     private IScope parent;
    37 
    38     [Storable]
    39     private string myName;
    40     /// <summary>
    41     /// Gets the name of the current scope.
    42     /// </summary>
    43     public string Name {
    44       get { return myName; }
    45     }
    46    
    47     private IDictionary<string, IVariable> myVariables;
    48     /// <inheritdoc/>   
    49     public ICollection<IVariable> Variables {
    50       get { return myVariables.Values; }
     41    public VariableCollection Variables {
     42      get { return variables; }
     43      private set {
     44        if (variables != null) variables.Changed -= new ChangedEventHandler(Variables_Changed);
     45        variables = value;
     46        if (variables != null) variables.Changed += new ChangedEventHandler(Variables_Changed);
     47      }
    5148    }
    5249
    53     [Storable(Name="Variables")]
    54     private List<IVariable> VariablePersistence {
    55       get { return new List<IVariable>(myVariables.Values); }
    56       set {
    57         myVariables.Clear();
    58         foreach (IVariable var in value) {
    59           AddVariable(var);
    60         }
     50    private ScopeList subScopes;
     51    [Storable]
     52    public ScopeList SubScopes {
     53      get { return subScopes; }
     54      private set {
     55        DeregisterSubScopesEvents();
     56        subScopes = value;
     57        RegisterSubScopesEvents();
    6158      }
    62     }
    63    
    64     [Storable]
    65     private IDictionary<string, string> myAliases;
    66     /// <inheritdoc/>
    67     public IEnumerable<KeyValuePair<string, string>> Aliases {
    68       get { return myAliases; }
    69     }
    70 
    71     [Storable]
    72     private List<IScope> mySubScopes;
    73     /// <summary>
    74     /// Gets all subscopes of the current instance.
    75     /// <note type="caution"> The subscopes are returned as read-only.</note>
    76     /// </summary>
    77     public IList<IScope> SubScopes {
    78       get { return mySubScopes.AsReadOnly(); }
    7959    }
    8060
     
    8262    /// Initializes a new instance of <see cref="Scope"/> having "Anonymous" as default name.
    8363    /// </summary>
    84     public Scope() {
    85       myName = "Anonymous";
    86       myVariables = new Dictionary<string, IVariable>();
    87       myAliases = new Dictionary<string, string>();
    88       mySubScopes = new List<IScope>();
     64    public Scope()
     65      : base("Anonymous") {
     66      parent = null;
     67      Variables = new VariableCollection();
     68      SubScopes = new ScopeList();
    8969    }
    9070    /// <summary>
     
    9373    /// <param name="name">The name of the scope.</param>
    9474    public Scope(string name)
    95       : this() {
    96       if (name != null) myName = name;
     75      : base(name) {
     76      parent = null;
     77      Variables = new VariableCollection();
     78      SubScopes = new ScopeList();
    9779    }
    9880
    99     /// <inheritdoc/>
    100     public void SetParent(IScope scope) {
    101       parent = scope;
     81    public Variable Lookup(string name, bool recursive) {
     82      return Lookup(name, recursive, true);
    10283    }
     84    public Variable Lookup(string name, bool recursive, bool throwOnError) {
     85      Variable variable;
    10386
    104     /// <inheritdoc/>
    105     public IVariable GetVariable(string name) {
    106       IVariable variable;
    107       if (myVariables.TryGetValue(name, out variable))
     87      if (this.variables.TryGetValue(name, out variable)) {
    10888        return variable;
     89      } else if (recursive) {
     90        Scope scope = this.parent;
     91        while (scope != null) {
     92          if (scope.variables.TryGetValue(name, out variable))
     93            return variable;
     94          scope = scope.parent;
     95        }
     96      }
     97      if (throwOnError)
     98        throw new ArgumentException("Variable " + name + " not found");
    10999      else
    110100        return null;
    111     }
    112     /// <inheritdoc/>
    113     public void AddVariable(IVariable variable) {
    114       myVariables.Add(variable.Name, variable);
    115       variable.NameChanging += new EventHandler<CancelEventArgs<string>>(Variable_NameChanging);
    116       variable.NameChanged += new EventHandler(Variable_NameChanged);
    117       OnVariableAdded(variable);
    118     }
    119 
    120     /// <inheritdoc/>
    121     public void RemoveVariable(string name) {
    122       IVariable variable;
    123       if (myVariables.TryGetValue(name, out variable)) {
    124         variable.NameChanging -= new EventHandler<CancelEventArgs<string>>(Variable_NameChanging);
    125         variable.NameChanged -= new EventHandler(Variable_NameChanged);
    126         myVariables.Remove(name);
    127         OnVariableRemoved(variable);
    128       }
    129     }
    130     private void Variable_NameChanging(object sender, CancelEventArgs<string> e) {
    131       e.Cancel = myVariables.ContainsKey(e.Value);
    132     }
    133     private void Variable_NameChanged(object sender, EventArgs e) {
    134       IVariable variable = (IVariable)sender;
    135       string oldName = null;
    136       foreach (KeyValuePair<string, IVariable> element in myVariables) {
    137         if (element.Value == variable)
    138           oldName = element.Key;
    139       }
    140       myVariables.Remove(oldName);
    141       myVariables.Add(variable.Name, variable);
    142     }
    143     /// <inheritdoc cref="IScope.GetVariableValue&lt;T&gt;(string, bool)"/>
    144     public T GetVariableValue<T>(string name, bool recursiveLookup) where T : class, IItem {
    145       return GetVariableValue<T>(name, recursiveLookup, true);
    146     }
    147     /// <inheritdoc cref="IScope.GetVariableValue&lt;T&gt;(string, bool, bool)"/>
    148     public T GetVariableValue<T>(string name, bool recursiveLookup, bool throwOnError) where T : class, IItem {
    149       return (T)GetVariableValue(name, recursiveLookup, throwOnError);
    150     }
    151     /// <inheritdoc cref="IScope.GetVariableValue(string, bool)"/>
    152     public IItem GetVariableValue(string name, bool recursiveLookup) {
    153       return GetVariableValue(name, recursiveLookup, true);
    154     }
    155     /// <inheritdoc cref="IScope.GetVariableValue(string, bool, bool)"/>
    156     public IItem GetVariableValue(string name, bool recursiveLookup, bool throwOnError) {
    157       IVariable variable;
    158       name = TranslateName(name);
    159       if (myVariables.TryGetValue(name, out variable)) {
    160         return variable.Value;
    161       } else {
    162         if (recursiveLookup && (parent != null))
    163           return parent.GetVariableValue(name, recursiveLookup, throwOnError);
    164         else {
    165           if (throwOnError)
    166             throw new ArgumentException("Variable " + name + " not found");
    167           else
    168             return null;
    169         }
    170       }
    171     }
    172     /// <inheritdoc/>
    173     public string TranslateName(string name) {
    174       while (myAliases.ContainsKey(name))
    175         name = myAliases[name];
    176       if (parent != null)
    177         name = parent.TranslateName(name);
    178       return name;
    179     }
    180     /// <inheritdoc/>
    181     public void AddAlias(string alias, string name) {
    182       RemoveAlias(alias);
    183       if (alias != name) {
    184         myAliases.Add(alias, name);
    185         OnAliasAdded(alias);
    186       }
    187     }
    188     /// <inheritdoc/>
    189     public void RemoveAlias(string alias) {
    190       if (myAliases.ContainsKey(alias)) {
    191         myAliases.Remove(alias);
    192         OnAliasRemoved(alias);
    193       }
    194     }
    195 
    196     /// <inheritdoc/>
    197     public void AddSubScope(IScope scope) {
    198       scope.SetParent(this);
    199       mySubScopes.Add(scope);
    200       OnSubScopeAdded(scope, mySubScopes.Count - 1);
    201     }
    202     /// <inheritdoc/>
    203     public void RemoveSubScope(IScope scope) {
    204       int index = mySubScopes.IndexOf(scope);
    205       if (mySubScopes.Remove(scope)) {
    206         scope.SetParent(null);
    207         OnSubScopeRemoved(scope, index);
    208       }
    209     }
    210     /// <inheritdoc/>
    211     public void ReorderSubScopes(int[] sequence) {
    212       IScope[] scopes = mySubScopes.ToArray();
    213       mySubScopes.Clear();
    214       for (int i = 0; i < scopes.Length; i++)
    215         mySubScopes.Add(scopes[sequence[i]]);
    216       OnSubScopesReordered();
    217     }
    218     /// <inheritdoc/>
    219     public IScope GetScope(string name) {
    220       if (Name == name) return this;
    221       else {
    222         for (int i = 0; i < mySubScopes.Count; i++) {
    223           IScope s = mySubScopes[i].GetScope(name);
    224           if (s != null) return s;
    225         }
    226       }
    227       return null;
    228101    }
    229102
    230103    /// <inheritdoc/>
    231104    public void Clear() {
    232       string[] variableNames = new string[Variables.Count];
    233       int i = 0;
    234       foreach (IVariable variable in Variables) {
    235         variableNames[i] = variable.Name;
    236         i++;
    237       }
    238       for (int j = 0; j < variableNames.Length; j++)
    239         RemoveVariable(variableNames[j]);
    240 
    241       KeyValuePair<string, string>[] aliases = new KeyValuePair<string, string>[myAliases.Count];
    242       myAliases.CopyTo(aliases, 0);
    243       for (int j = 0; j < aliases.Length; j++)
    244         RemoveAlias(aliases[j].Key);
    245 
    246       while (SubScopes.Count > 0)
    247         RemoveSubScope(SubScopes[0]);
     105      variables.Clear();
     106      subScopes.Clear();
    248107    }
    249108
    250109    /// <inheritdoc/>
    251     public override IItem Clone(ICloner cloner) {
     110    public override IDeepCloneable Clone(Cloner cloner) {
    252111      Scope clone = (Scope)base.Clone(cloner);
    253       clone.myName = Name;
    254 
    255       foreach (IVariable variable in myVariables.Values)
    256         clone.AddVariable((IVariable)cloner.Clone(variable));
    257       foreach (KeyValuePair<string, string> alias in myAliases)
    258         clone.AddAlias(alias.Key, alias.Value);
    259       for (int i = 0; i < SubScopes.Count; i++)
    260         clone.AddSubScope((IScope)cloner.Clone(SubScopes[i]));
    261 
     112      clone.parent = (Scope)cloner.Clone(parent);
     113      clone.Variables = (VariableCollection)cloner.Clone(variables);
     114      clone.SubScopes = (ScopeList)cloner.Clone(subScopes);
    262115      return clone;
    263116    }
    264117
    265     /// <inheritdoc />
    266     public event EventHandler<EventArgs<IVariable>> VariableAdded;
    267     /// <summary>
    268     /// Fires a new <c>VariableAdded</c> event.
    269     /// </summary>
    270     /// <param name="variable">The variable that has been added.</param>
    271     protected virtual void OnVariableAdded(IVariable variable) {
    272       if (VariableAdded != null)
    273         VariableAdded(this, new EventArgs<IVariable>(variable));
     118    #region SubScopes Events
     119    private void RegisterSubScopesEvents() {
     120      if (subScopes != null) {
     121        subScopes.ItemsAdded += new CollectionItemsChangedEventHandler<IndexedItem<Scope>>(SubScopes_ItemsAdded);
     122        subScopes.ItemsRemoved += new CollectionItemsChangedEventHandler<IndexedItem<Scope>>(SubScopes_ItemsRemoved);
     123        subScopes.ItemsReplaced += new CollectionItemsChangedEventHandler<IndexedItem<Scope>>(SubScopes_ItemsReplaced);
     124        subScopes.CollectionReset += new CollectionItemsChangedEventHandler<IndexedItem<Scope>>(SubScopes_CollectionReset);
     125        subScopes.Changed += new ChangedEventHandler(SubScopes_Changed);
     126      }
    274127    }
    275     /// <inheritdoc />
    276     public event EventHandler<EventArgs<IVariable>> VariableRemoved;
    277     /// <summary>
    278     /// Fires a new <c>VariableRemoved</c>.
    279     /// </summary>
    280     /// <param name="variable">The variable that has been deleted.</param>
    281     protected virtual void OnVariableRemoved(IVariable variable) {
    282       if (VariableRemoved != null)
    283         VariableRemoved(this, new EventArgs<IVariable>(variable));
     128    private void DeregisterSubScopesEvents() {
     129      if (subScopes != null) {
     130        subScopes.ItemsAdded -= new CollectionItemsChangedEventHandler<IndexedItem<Scope>>(SubScopes_ItemsAdded);
     131        subScopes.ItemsRemoved -= new CollectionItemsChangedEventHandler<IndexedItem<Scope>>(SubScopes_ItemsRemoved);
     132        subScopes.ItemsReplaced -= new CollectionItemsChangedEventHandler<IndexedItem<Scope>>(SubScopes_ItemsReplaced);
     133        subScopes.CollectionReset -= new CollectionItemsChangedEventHandler<IndexedItem<Scope>>(SubScopes_CollectionReset);
     134        subScopes.Changed -= new ChangedEventHandler(SubScopes_Changed);
     135      }
    284136    }
    285     /// <inheritdoc />
    286     public event EventHandler<EventArgs<string>> AliasAdded;
    287     /// <summary>
    288     /// Fires a new <c>AliasAdded</c> event.
    289     /// </summary>
    290     /// <param name="alias">The alias that has been added.</param>
    291     protected virtual void OnAliasAdded(string alias) {
    292       if (AliasAdded != null)
    293         AliasAdded(this, new EventArgs<string>(alias));
     137    private void SubScopes_ItemsAdded(object sender, CollectionItemsChangedEventArgs<IndexedItem<Scope>> e) {
     138      foreach (IndexedItem<Scope> item in e.Items)
     139        item.Value.parent = this;
    294140    }
    295     /// <inheritdoc/>
    296     public event EventHandler<EventArgs<string>> AliasRemoved;
    297     /// <summary>
    298     /// Fires a new <c>AliasRemoved</c> event.
    299     /// </summary>
    300     /// <param name="alias">The alias that has been deleted.</param>
    301     protected virtual void OnAliasRemoved(string alias) {
    302       if (AliasRemoved != null)
    303         AliasRemoved(this, new EventArgs<string>(alias));
     141    private void SubScopes_ItemsRemoved(object sender, CollectionItemsChangedEventArgs<IndexedItem<Scope>> e) {
     142      foreach (IndexedItem<Scope> item in e.Items)
     143        item.Value.parent = null;
    304144    }
    305     /// <inheritdoc/>
    306     public event EventHandler<EventArgs<IScope, int>> SubScopeAdded;
    307     /// <summary>
    308     /// Fires a new <c>SubScopeAdded</c> event.
    309     /// </summary>
    310     /// <param name="scope">The sub scope that has been added.</param>
    311     /// <param name="index">The index where the scope has been added.</param>
    312     protected virtual void OnSubScopeAdded(IScope scope, int index) {
    313       if (SubScopeAdded != null)
    314         SubScopeAdded(this, new EventArgs<IScope, int>(scope, index));
     145    private void SubScopes_ItemsReplaced(object sender, CollectionItemsChangedEventArgs<IndexedItem<Scope>> e) {
     146      foreach (IndexedItem<Scope> oldItem in e.OldItems)
     147        oldItem.Value.parent = null;
     148      foreach (IndexedItem<Scope> item in e.Items)
     149        item.Value.parent = this;
    315150    }
    316     /// <inheritdoc/>
    317     public event EventHandler<EventArgs<IScope, int>> SubScopeRemoved;
    318     /// <summary>
    319     /// Fires a new <c>SubScopeRemoved</c> event.
    320     /// </summary>
    321     /// <param name="scope">The sub scope that has been deleted.</param>
    322     /// <param name="index">The position of the sub scope.</param>
    323     protected virtual void OnSubScopeRemoved(IScope scope, int index) {
    324       if (SubScopeRemoved != null)
    325         SubScopeRemoved(this, new EventArgs<IScope, int>(scope, index));
     151    private void SubScopes_CollectionReset(object sender, CollectionItemsChangedEventArgs<IndexedItem<Scope>> e) {
     152      foreach (IndexedItem<Scope> oldItem in e.OldItems)
     153        oldItem.Value.parent = null;
     154      foreach (IndexedItem<Scope> item in e.Items)
     155        item.Value.parent = this;
    326156    }
    327     /// <inheritdoc />
    328     public event EventHandler SubScopesReordered;
    329     /// <summary>
    330     /// Fires a new <c>SubScopesReordered</c> event
    331     /// </summary>
    332     protected virtual void OnSubScopesReordered() {
    333       if (SubScopesReordered != null)
    334         SubScopesReordered(this, new EventArgs());
     157    private void SubScopes_Changed(object sender, ChangedEventArgs e) {
     158      OnChanged(e);
    335159    }
     160    #endregion
     161
     162    #region Variables Events
     163    private void Variables_Changed(object sender, ChangedEventArgs e) {
     164      OnChanged(e);
     165    }
     166    #endregion
    336167  }
    337168}
  • trunk/sources/HeuristicLab.Core/3.3/Variable.cs

    r2526 r2653  
    2929namespace HeuristicLab.Core {
    3030  /// <summary>
    31   /// Represents a variable of an operator having a name and a value.
     31  /// Represents a variable which has a name and holds an IItem.
    3232  /// </summary>
    33   public class Variable : ItemBase, IVariable {
    34 
    35     [Storable]
    36     private string myName;
    37     /// <inheritdoc/>
    38     /// <remarks>Calls <see cref="OnNameChanging"/> and also <see cref="OnNameChanged"/>
    39     /// eventually in the setter.</remarks>
    40     public string Name {
    41       get { return myName; }
    42       set {
    43         if (!myName.Equals(value)) {
    44           CancelEventArgs<string> e = new CancelEventArgs<string>(value);
    45           OnNameChanging(e);
    46           if (!e.Cancel) {
    47             myName = value;
    48             OnNameChanged();
    49           }
    50         }
    51       }
    52     }
    53 
    54     [Storable]
    55     private IItem myValue;
     33  [Item("Variable", "A variable which has a name and holds an IItem.")]
     34  [Creatable("Test")]
     35  public sealed class Variable : NamedItemBase {
     36    private IItem value;
    5637    /// <inheritdoc/>
    5738    /// <remarks>Calls <see cref="OnValueChanged"/> in the setter.</remarks>
     39    [Storable]
    5840    public IItem Value {
    59       get { return myValue; }
     41      get { return value; }
    6042      set {
    61         if (myValue != value) {
    62           myValue = value;
     43        if (this.value != value) {
     44          if (this.value != null) this.value.Changed -= new ChangedEventHandler(Value_Changed);
     45          this.value = value;
     46          if (this.value != null) this.value.Changed += new ChangedEventHandler(Value_Changed);
    6347          OnValueChanged();
    6448        }
     
    7054    /// and value <c>null</c>.
    7155    /// </summary>
    72     public Variable() {
    73       myName = "Anonymous";
    74       myValue = null;
     56    public Variable()
     57      : base("Anonymous") {
     58      Value = null;
    7559    }
    7660    /// <summary>
     
    8064    /// <param name="name">The name of the current instance.</param>
    8165    /// <param name="value">The value of the current instance.</param>
    82     public Variable(string name, IItem value) {
    83       myName = name;
    84       myValue = value;
     66    public Variable(string name, IItem value)
     67      : base(name) {
     68      Value = value;
    8569    }
    8670
     
    9579    /// <param name="clonedObjects">Dictionary of all already cloned objects. (Needed to avoid cycles.)</param>
    9680    /// <returns>The cloned object as <see cref="Variable"/>.</returns>
    97     public override IItem Clone(ICloner cloner) {
     81    public override IDeepCloneable Clone(Cloner cloner) {
    9882      Variable clone = new Variable();
    9983      cloner.RegisterClonedObject(this, clone);
    100       clone.myName = Name;
    101       if (Value != null)
    102         clone.myValue = (IItem)cloner.Clone(Value);
     84      clone.name = name;
     85      clone.description = description;
     86      clone.Value = (IItem)cloner.Clone(value);
    10387      return clone;
    10488    }
     
    10993    /// <returns>The current instance as a string.</returns>
    11094    public override string ToString() {
    111       return Name + ": " + ((Value == null) ? ("null") : (Value.ToString()));
     95      if (Value == null)
     96        return string.Format("{0}: null", Name);
     97      else
     98        return string.Format("{0}: {1} ({2})", Name, Value.ToString(), Value.GetType().Name);
    11299    }
    113100
    114     /// <inheritdoc/>
    115     public event EventHandler<CancelEventArgs<string>> NameChanging;
    116     /// <summary>
    117     /// Fires a new <c>NameChanging</c> event.
    118     /// </summary>
    119     /// <param name="e">The event arguments of the changing.</param>
    120     protected virtual void OnNameChanging(CancelEventArgs<string> e) {
    121       if (NameChanging != null)
    122         NameChanging(this, e);
    123     }
    124     /// <inheritdoc/>
    125     public event EventHandler NameChanged;
    126     /// <summary>
    127     /// Fires a new <c>NameChanged</c> event.
    128     /// </summary>
    129     /// <remarks>Calls <see cref="ItemBase.OnChanged"/>.</remarks>
    130     protected virtual void OnNameChanged() {
    131       if (NameChanged != null)
    132         NameChanged(this, new EventArgs());
    133       OnChanged();
    134     }
    135101    /// <inheritdoc/>
    136102    public event EventHandler ValueChanged;
     
    138104    /// Fires a new <c>ValueChanged</c> even.
    139105    /// </summary>
    140     protected virtual void OnValueChanged() {
     106    private void OnValueChanged() {
    141107      if (ValueChanged != null)
    142108        ValueChanged(this, new EventArgs());
    143109      OnChanged();
    144110    }
     111
     112    private void Value_Changed(object sender, ChangedEventArgs e) {
     113      OnChanged(e);
     114    }
    145115  }
    146116}
Note: See TracChangeset for help on using the changeset viewer.