#region License Information /* HeuristicLab * Copyright (C) 2002-2014 Heuristic and Evolutionary Algorithms Laboratory (HEAL) * * This file is part of HeuristicLab. * * HeuristicLab is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * HeuristicLab is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with HeuristicLab. If not, see . */ #endregion using System; using System.Collections.Generic; using System.Linq; using System.Threading; using HeuristicLab.Common; using HeuristicLab.Core; using HeuristicLab.Core.Networks; using HeuristicLab.Operators; using HeuristicLab.Optimization; using HeuristicLab.Persistence.Default.CompositeSerializers.Storable; namespace HeuristicLab.Networks { [Item("AlgorithmNode", "A node of a network which contains a HeuristicLab algorithm.")] [StorableClass] public class AlgorithmNode : Node, IAlgorithmNode { protected object locker = new object(); new public PortCollection Ports { get { return base.Ports; } } [Storable] private IAlgorithm algorithm; public IAlgorithm Algorithm { get { return algorithm; } set { if (value != algorithm) { algorithm = value; OnAlgorithmChanged(); } } } [Storable] private RunCollection runs; public RunCollection Runs { get { return runs; } } [Storable] private IItemCollection startedAlgorithms; public IItemCollection StartedAlgorithms { get { return startedAlgorithms; } } [StorableConstructor] protected AlgorithmNode(bool deserializing) : base(deserializing) { } protected AlgorithmNode(AlgorithmNode original, Cloner cloner) : base(original, cloner) { algorithm = cloner.Clone(original.algorithm); runs = cloner.Clone(original.runs); startedAlgorithms = cloner.Clone(original.startedAlgorithms); RegisterStartedAlgorithmsEvents(); } public AlgorithmNode() : base("AlgorithmNode") { runs = new RunCollection(); startedAlgorithms = new ItemCollection(); RegisterStartedAlgorithmsEvents(); } public AlgorithmNode(string name) : base(name) { runs = new RunCollection(); startedAlgorithms = new ItemCollection(); RegisterStartedAlgorithmsEvents(); } public AlgorithmNode(string name, string description) : base(name, description) { runs = new RunCollection(); startedAlgorithms = new ItemCollection(); RegisterStartedAlgorithmsEvents(); } public override IDeepCloneable Clone(Cloner cloner) { return new AlgorithmNode(this, cloner); } [StorableHook(HookType.AfterDeserialization)] private void AfterDeserialization() { RegisterStartedAlgorithmsEvents(); } protected virtual void RegisterStartedAlgorithmsEvents() { startedAlgorithms.ItemsAdded += StartedAlgorithms_ItemsChanged; startedAlgorithms.ItemsRemoved += StartedAlgorithms_ItemsChanged; } private void StartedAlgorithms_ItemsChanged(object sender, Collections.CollectionItemsChangedEventArgs e) { OnStartedAlgorithmsChanged(); } protected virtual void Configure(IConfigurationPort port, IMessage message, CancellationToken token) { // set algorithm and problem parameters lock (locker) { if (algorithm != null) { foreach (var v in message.Values) { IParameter param = null; if (Algorithm.Parameters.TryGetValue(v.Name, out param)) { var vp = param as IValueParameter; if (vp != null) vp.Value = v.Value; } if (Algorithm.Problem.Parameters.TryGetValue(v.Name, out param)) { var vp = param as IValueParameter; if (vp != null) vp.Value = v.Value; } } } } } protected virtual void Execute(IExecutionPort port, IMessage message, CancellationToken token) { if (Algorithm == null) throw new InvalidOperationException("Algorithm is null"); IAlgorithm algorithm; lock (locker) { // prevent cloning of ports in hook operators var cloner = new Cloner(); foreach (var hook in Algorithm.GetObjectGraphObjects(new HashSet() { Algorithm.Results, Algorithm.Runs }).OfType()) { cloner.RegisterClonedObject(hook.Port, hook.Port); } algorithm = (IAlgorithm)Algorithm.Clone(cloner); } // set parameters foreach (var v in message.Values) { IParameter param = null; if (algorithm.Parameters.TryGetValue(v.Name, out param)) { var vp = param as IValueParameter; if (vp != null) vp.Value = v.Value; } if (algorithm.Problem.Parameters.TryGetValue(v.Name, out param)) { var vp = param as IValueParameter; if (vp != null) vp.Value = v.Value; } } token.ThrowIfCancellationRequested(); Exception exception = null; using (var started = new AutoResetEvent(false)) using (var stopped = new AutoResetEvent(false)) using (var ctr = token.Register(() => { started.WaitOne(); try { algorithm.Stop(); } catch (InvalidOperationException) { // NOTE: // After the algorithm's engine is stopped, all stateful items in the algorithm are cleared before the execution state of the algorithm is set to stopped. // When algorithm.Stop() is called during that operation, an InvalidOperationException is thrown because Stop is called on the engine but the engine is already stopped. // This exception can be ignored, as the algorithm will stop immediately after the clearing of its stateful items is finished. } })) { algorithm.StoreAlgorithmInEachRun = false; algorithm.Prepare(true); algorithm.ExceptionOccurred += (sender, args) => { exception = args.Value; }; algorithm.Started += (sender, args) => { started.Set(); startedAlgorithms.Add((IAlgorithm)sender); }; algorithm.Stopped += (sender, args) => { stopped.Set(); startedAlgorithms.Remove((IAlgorithm)sender); }; algorithm.Start(); stopped.WaitOne(); } if (exception != null) throw exception; token.ThrowIfCancellationRequested(); // retrieve results var run = algorithm.Runs.First(); foreach (var v in message.Values) { IItem result = null; if (run.Results.TryGetValue(v.Name, out result)) { v.Value = result; } } lock (locker) { Runs.Add(run); } } public event EventHandler AlgorithmChanged; protected virtual void OnAlgorithmChanged() { var handler = AlgorithmChanged; if (handler != null) handler(this, EventArgs.Empty); } public event EventHandler StartedAlgorithmsChanged; protected virtual void OnStartedAlgorithmsChanged() { var handler = StartedAlgorithmsChanged; if (handler != null) handler(this, EventArgs.Empty); } #region Ports Events protected override void RegisterPortsEvents() { base.RegisterPortsEvents(); foreach (var p in Ports) RegisterPortEvents(p); } protected override void Ports_ItemsAdded(object sender, Collections.CollectionItemsChangedEventArgs e) { base.Ports_ItemsAdded(sender, e); foreach (var p in e.Items) RegisterPortEvents(p); } protected override void Ports_ItemsRemoved(object sender, Collections.CollectionItemsChangedEventArgs e) { base.Ports_ItemsRemoved(sender, e); foreach (var p in e.Items) DeregisterPortEvents(p); } protected override void Ports_ItemsReplaced(object sender, Collections.CollectionItemsChangedEventArgs e) { base.Ports_ItemsReplaced(sender, e); foreach (var p in e.OldItems) DeregisterPortEvents(p); foreach (var p in e.Items) RegisterPortEvents(p); } protected override void Ports_CollectionReset(object sender, Collections.CollectionItemsChangedEventArgs e) { base.Ports_CollectionReset(sender, e); foreach (var p in e.OldItems) DeregisterPortEvents(p); foreach (var p in e.Items) RegisterPortEvents(p); } #endregion #region Port Events private void RegisterPortEvents(IPort port) { IConfigurationPort c = port as IConfigurationPort; if (c != null) { c.MessageReceived += ConfigurationPort_MessageReceived; } IExecutionPort e = port as IExecutionPort; if (e != null) { e.MessageReceived += ExecutionPort_MessageReceived; } } private void DeregisterPortEvents(IPort port) { IConfigurationPort c = port as IConfigurationPort; if (c != null) { c.MessageReceived -= ConfigurationPort_MessageReceived; } IExecutionPort e = port as IExecutionPort; if (e != null) { e.MessageReceived -= ExecutionPort_MessageReceived; } } protected virtual void ConfigurationPort_MessageReceived(object sender, EventArgs e) { Configure((IConfigurationPort)sender, e.Value, e.Value2); } protected virtual void ExecutionPort_MessageReceived(object sender, EventArgs e) { Execute((IExecutionPort)sender, e.Value, e.Value2); } #endregion } }