Changeset 17253


Ignore:
Timestamp:
09/16/19 16:12:21 (2 years ago)
Author:
abeham
Message:

#2521: worked on refactoring PTSP

Location:
branches/2521_ProblemRefactoring
Files:
1 added
4 deleted
49 edited

Legend:

Unmodified
Added
Removed
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/BoolArray.cs

    r17226 r17253  
    2121
    2222using System.Text;
     23using HEAL.Attic;
    2324using HeuristicLab.Common;
    2425using HeuristicLab.Core;
    25 using HEAL.Attic;
    2626
    2727namespace HeuristicLab.Data {
     
    3636    public BoolArray() : base() { }
    3737    public BoolArray(int length) : base(length) { }
    38     public BoolArray(bool[] elements) : base(elements) { }
     38    public BoolArray(bool[] elements, bool @readonly = false) : base(elements, @readonly) { }
    3939
    4040    public override IDeepCloneable Clone(Cloner cloner) {
     
    6767      }
    6868    }
     69
     70    public new BoolArray AsReadOnly() {
     71      return (BoolArray)base.AsReadOnly();
     72    }
    6973  }
    7074}
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/BoolMatrix.cs

    r17226 r17253  
    2222using System.Collections.Generic;
    2323using System.Text;
     24using HEAL.Attic;
    2425using HeuristicLab.Common;
    2526using HeuristicLab.Core;
    26 using HEAL.Attic;
    2727
    2828namespace HeuristicLab.Data {
     
    3939    public BoolMatrix(int rows, int columns, IEnumerable<string> columnNames) : base(rows, columns, columnNames) { }
    4040    public BoolMatrix(int rows, int columns, IEnumerable<string> columnNames, IEnumerable<string> rowNames) : base(rows, columns, columnNames, rowNames) { }
    41     public BoolMatrix(bool[,] elements) : base(elements) { }
    42     public BoolMatrix(bool[,] elements, IEnumerable<string> columnNames) : base(elements, columnNames) { }
    43     public BoolMatrix(bool[,] elements, IEnumerable<string> columnNames, IEnumerable<string> rowNames) : base(elements, columnNames, rowNames) { }
     41    public BoolMatrix(bool[,] elements, bool @readonly = false) : base(elements, @readonly) { }
     42    public BoolMatrix(bool[,] elements, IEnumerable<string> columnNames, bool @readonly = false) : base(elements, columnNames, @readonly) { }
     43    public BoolMatrix(bool[,] elements, IEnumerable<string> columnNames, IEnumerable<string> rowNames, bool @readonly = false) : base(elements, columnNames, rowNames, @readonly) { }
    4444
    4545    public override IDeepCloneable Clone(Cloner cloner) {
     
    7373    }
    7474
     75    public new BoolMatrix AsReadOnly() {
     76      return (BoolMatrix)base.AsReadOnly();
     77    }
     78
    7579    #region IStringConvertibleMatrix Members
    7680    int IStringConvertibleMatrix.Rows {
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/BoolValue.cs

    r17226 r17253  
    2323using System.Drawing;
    2424using System.Text;
     25using HEAL.Attic;
    2526using HeuristicLab.Common;
    2627using HeuristicLab.Core;
    27 using HEAL.Attic;
    2828
    2929namespace HeuristicLab.Data {
     
    4141    }
    4242    public BoolValue() : base() { }
    43     public BoolValue(bool value) : base(value) { }
     43    public BoolValue(bool value, bool @readonly = false) : base(value, @readonly) { }
    4444
    4545    public override IDeepCloneable Clone(Cloner cloner) {
     
    8181    }
    8282
     83    public new BoolValue AsReadOnly() {
     84      return (BoolValue)base.AsReadOnly();
     85    }
     86
    8387    #region IStringConvertibleValue Members
    8488    bool IStringConvertibleValue.Validate(string value, out string errorMessage) {
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/DoubleArray.cs

    r17226 r17253  
    2121
    2222using System.Text;
     23using HEAL.Attic;
    2324using HeuristicLab.Common;
    2425using HeuristicLab.Core;
    25 using HEAL.Attic;
    2626
    2727namespace HeuristicLab.Data {
     
    3636    public DoubleArray() : base() { }
    3737    public DoubleArray(int length) : base(length) { }
    38     public DoubleArray(double[] elements) : base(elements) { }
     38    public DoubleArray(double[] elements, bool @readonly = false) : base(elements, @readonly) { }
    3939
    4040    public override IDeepCloneable Clone(Cloner cloner) {
     
    6767      }
    6868    }
     69
     70    public new DoubleArray AsReadOnly() {
     71      return (DoubleArray)base.AsReadOnly();
     72    }
    6973  }
    7074}
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/DoubleMatrix.cs

    r17248 r17253  
    7373    }
    7474
     75    public new DoubleMatrix AsReadOnly() {
     76      return (DoubleMatrix)base.AsReadOnly();
     77    }
     78
    7579    #region IStringConvertibleMatrix Members
    7680    int IStringConvertibleMatrix.Rows {
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/DoubleValue.cs

    r17226 r17253  
    2323using System.Drawing;
    2424using System.Text;
     25using HEAL.Attic;
    2526using HeuristicLab.Common;
    2627using HeuristicLab.Core;
    27 using HEAL.Attic;
    2828
    2929namespace HeuristicLab.Data {
     
    4141    }
    4242    public DoubleValue() : base() { }
    43     public DoubleValue(double value) : base(value) { }
     43    public DoubleValue(double value, bool @readonly = false) : base(value, @readonly) { }
    4444
    4545    public override IDeepCloneable Clone(Cloner cloner) {
     
    8585    }
    8686
     87    public new DoubleValue AsReadOnly() {
     88      return (DoubleValue)base.AsReadOnly();
     89    }
     90
    8791    #region IStringConvertibleValue Members
    8892    bool IStringConvertibleValue.Validate(string value, out string errorMessage) {
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/EnumValue.cs

    r17226 r17253  
    2222using System;
    2323using System.Drawing;
     24using HEAL.Attic;
    2425using HeuristicLab.Common;
    2526using HeuristicLab.Core;
    26 using HEAL.Attic;
    2727
    2828namespace HeuristicLab.Data {
     
    3939    }
    4040
    41     public EnumValue() {
    42       this.value = default(T);
    43       this.readOnly = false;
    44     }
    45     public EnumValue(T value) {
    46       this.value = value;
    47       this.readOnly = false;
    48     }
     41    public EnumValue() : base(default(T)) { }
     42    public EnumValue(T value, bool @readonly = false) : base(value, @readonly) { }
    4943
    5044    [StorableConstructor]
     
    6155      return Value.CompareTo(other.Value);
    6256    }
     57
     58    public new EnumValue<T> AsReadOnly() {
     59      return (EnumValue<T>)base.AsReadOnly();
     60    }
    6361  }
    6462}
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/IntArray.cs

    r17226 r17253  
    2121
    2222using System.Text;
     23using HEAL.Attic;
    2324using HeuristicLab.Common;
    2425using HeuristicLab.Core;
    25 using HEAL.Attic;
    2626
    2727namespace HeuristicLab.Data {
     
    3636    public IntArray() : base() { }
    3737    public IntArray(int length) : base(length) { }
    38     public IntArray(int[] elements) : base(elements) { }
     38    public IntArray(int[] elements, bool @readonly = false) : base(elements, @readonly) { }
    3939
    4040    public override IDeepCloneable Clone(Cloner cloner) {
     
    6767      }
    6868    }
     69
     70    public new IntArray AsReadOnly() {
     71      return (IntArray)base.AsReadOnly();
     72    }
    6973  }
    7074}
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/IntMatrix.cs

    r17226 r17253  
    2222using System.Collections.Generic;
    2323using System.Text;
     24using HEAL.Attic;
    2425using HeuristicLab.Common;
    2526using HeuristicLab.Core;
    26 using HEAL.Attic;
    2727
    2828namespace HeuristicLab.Data {
     
    3939    public IntMatrix(int rows, int columns, IEnumerable<string> columnNames) : base(rows, columns, columnNames) { }
    4040    public IntMatrix(int rows, int columns, IEnumerable<string> columnNames,IEnumerable<string> rowNames) : base(rows, columns, columnNames,rowNames) { }
    41     public IntMatrix(int[,] elements) : base(elements) { }
    42     public IntMatrix(int[,] elements, IEnumerable<string> columnNames) : base(elements,columnNames) { }
    43     public IntMatrix(int[,] elements, IEnumerable<string> columnNames, IEnumerable<string> rowNames) : base(elements,columnNames,rowNames) { }
     41    public IntMatrix(int[,] elements, bool @readonly = false) : base(elements, @readonly) { }
     42    public IntMatrix(int[,] elements, IEnumerable<string> columnNames, bool @readonly = false) : base(elements, columnNames, @readonly) { }
     43    public IntMatrix(int[,] elements, IEnumerable<string> columnNames, IEnumerable<string> rowNames, bool @readonly = false) : base(elements, columnNames, rowNames, @readonly) { }
    4444
    4545    public override IDeepCloneable Clone(Cloner cloner) {
     
    7373    }
    7474
     75    public new IntMatrix AsReadOnly() {
     76      return (IntMatrix)base.AsReadOnly();
     77    }
     78
    7579    #region IStringConvertibleMatrix Members
    7680    int IStringConvertibleMatrix.Rows {
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/IntValue.cs

    r17226 r17253  
    2323using System.Drawing;
    2424using System.Text;
     25using HEAL.Attic;
    2526using HeuristicLab.Common;
    2627using HeuristicLab.Core;
    27 using HEAL.Attic;
    2828
    2929namespace HeuristicLab.Data {
     
    4141    }
    4242    public IntValue() : base() { }
    43     public IntValue(int value) : base(value) { }
     43    public IntValue(int value, bool @readonly = false) : base(value, @readonly) { }
    4444
    4545    public override IDeepCloneable Clone(Cloner cloner) {
     
    8181    }
    8282
     83    public new IntValue AsReadOnly() {
     84      return (IntValue)base.AsReadOnly();
     85    }
     86
    8387    #region IStringConvertibleValue Members
    8488    bool IStringConvertibleValue.Validate(string value, out string errorMessage) {
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/PercentArray.cs

    r17226 r17253  
    2121
    2222using System.Text;
     23using HEAL.Attic;
    2324using HeuristicLab.Common;
    2425using HeuristicLab.Core;
    25 using HEAL.Attic;
    2626
    2727namespace HeuristicLab.Data {
     
    3636    public PercentArray() : base() { }
    3737    public PercentArray(int length) : base(length) { }
    38     public PercentArray(double[] elements) : base(elements) { }
     38    public PercentArray(double[] elements, bool @readonly = false) : base(elements, @readonly) { }
    3939
    4040    public override IDeepCloneable Clone(Cloner cloner) {
     
    7777      }
    7878    }
     79
     80    public new PercentArray AsReadOnly() {
     81      return (PercentArray)base.AsReadOnly();
     82    }
    7983  }
    8084}
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/PercentMatrix.cs

    r17226 r17253  
    2222using System.Collections.Generic;
    2323using System.Text;
     24using HEAL.Attic;
    2425using HeuristicLab.Common;
    2526using HeuristicLab.Core;
    26 using HEAL.Attic;
    2727
    2828namespace HeuristicLab.Data {
     
    3939    public PercentMatrix(int rows, int columns, IEnumerable<string> columnNames) : base(rows, columns, columnNames) { }
    4040    public PercentMatrix(int rows, int columns, IEnumerable<string> columnNames, IEnumerable<string> rowNames) : base(rows, columns, columnNames, rowNames) { }
    41     public PercentMatrix(double[,] elements) : base(elements) { }
    42     public PercentMatrix(double[,] elements, IEnumerable<string> columnNames) : base(elements, columnNames) { }
    43     public PercentMatrix(double[,] elements, IEnumerable<string> columnNames, IEnumerable<string> rowNames) : base(elements, columnNames, rowNames) { }
     41    public PercentMatrix(double[,] elements, bool @readonly = false) : base(elements, @readonly) { }
     42    public PercentMatrix(double[,] elements, IEnumerable<string> columnNames, bool @readonly = false) : base(elements, columnNames, @readonly) { }
     43    public PercentMatrix(double[,] elements, IEnumerable<string> columnNames, IEnumerable<string> rowNames, bool @readonly = false) : base(elements, columnNames, rowNames, @readonly) { }
    4444
    4545    public override IDeepCloneable Clone(Cloner cloner) {
     
    8585      }
    8686    }
     87
     88    public new PercentMatrix AsReadOnly() {
     89      return (PercentMatrix)base.AsReadOnly();
     90    }
    8791  }
    8892}
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/PercentValue.cs

    r17226 r17253  
    2121
    2222using System;
     23using HEAL.Attic;
    2324using HeuristicLab.Common;
    2425using HeuristicLab.Core;
    25 using HEAL.Attic;
    2626
    2727namespace HeuristicLab.Data {
     
    5151    }
    5252    public PercentValue() : base() { }
    53     public PercentValue(double value) : base(value) { }
    54 
    55     public PercentValue(double value, bool restrictToUnitInterval)
     53    public PercentValue(double value, bool @readonly = false) : base(value, @readonly) { }
     54    // TODO: suggest to remove the following constructor [ABE]
     55    public PercentValue(double value, bool restrictToUnitInterval, bool @readonly = false)
    5656      : base() {
    5757      this.restrictToUnitInterval = restrictToUnitInterval;
     
    5959        throw new ArgumentException("Value must lie in the interval [0,1].");
    6060      this.value = value;
     61      this.readOnly = @readonly;
    6162    }
    6263
     
    101102      }
    102103    }
     104
     105    public new PercentValue AsReadOnly() {
     106      return (PercentValue)base.AsReadOnly();
     107    }
    103108  }
    104109}
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/StringArray.cs

    r17226 r17253  
    2626using System.Linq;
    2727using System.Text;
     28using HEAL.Attic;
    2829using HeuristicLab.Common;
    2930using HeuristicLab.Core;
    30 using HEAL.Attic;
    3131
    3232namespace HeuristicLab.Data {
     
    131131      elementNames = new List<string>();
    132132    }
    133     public StringArray(string[] elements) {
     133    public StringArray(string[] elements, bool @readonly = false) {
    134134      if (elements == null) throw new ArgumentNullException();
    135135      array = new string[elements.Length];
    136136      for (int i = 0; i < array.Length; i++)
    137137        array[i] = elements[i] == null ? string.Empty : elements[i];
    138       readOnly = false;
     138      readOnly = @readonly;
    139139      resizable = true;
    140140      elementNames = new List<string>();
     
    146146
    147147    public virtual StringArray AsReadOnly() {
    148       StringArray readOnlyStringArray = (StringArray)this.Clone();
    149       readOnlyStringArray.readOnly = true;
    150       return readOnlyStringArray;
     148      if (ReadOnly) return this;
     149      var clone = (StringArray)this.Clone();
     150      clone.readOnly = true;
     151      return clone;
    151152    }
    152153    IValueTypeArray IValueTypeArray.AsReadOnly() {
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/StringConvertibleArray.cs

    r17226 r17253  
    2222#endregion
    2323
     24using HEAL.Attic;
    2425using HeuristicLab.Common;
    2526using HeuristicLab.Core;
    26 using HEAL.Attic;
    2727
    2828namespace HeuristicLab.Data {
     
    3737    protected StringConvertibleArray() : base() { }
    3838    protected StringConvertibleArray(int length) : base(length) { }
    39     protected StringConvertibleArray(T[] elements) : base(elements) { }
     39    protected StringConvertibleArray(T[] elements, bool @readonly = false) : base(elements, @readonly) { }
    4040
    4141    protected abstract bool Validate(string value, out string errorMessage);
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/StringMatrix.cs

    r17226 r17253  
    2626using System.Linq;
    2727using System.Text;
     28using HEAL.Attic;
    2829using HeuristicLab.Common;
    2930using HeuristicLab.Core;
    30 using HEAL.Attic;
    3131
    3232namespace HeuristicLab.Data {
     
    178178      RowNames = rowNames;
    179179    }
    180     public StringMatrix(string[,] elements) {
     180    public StringMatrix(string[,] elements, bool @readonly = false) {
    181181      if (elements == null) throw new ArgumentNullException();
    182182      matrix = new string[elements.GetLength(0), elements.GetLength(1)];
     
    188188      rowNames = new List<string>();
    189189      sortableView = false;
    190       readOnly = false;
    191     }
    192     protected StringMatrix(string[,] elements, IEnumerable<string> columnNames)
    193       : this(elements) {
     190      readOnly = @readonly;
     191    }
     192    protected StringMatrix(string[,] elements, IEnumerable<string> columnNames, bool @readonly = false)
     193      : this(elements, @readonly) {
    194194      ColumnNames = columnNames;
    195195    }
    196     protected StringMatrix(string[,] elements, IEnumerable<string> columnNames, IEnumerable<string> rowNames)
    197       : this(elements, columnNames) {
     196    protected StringMatrix(string[,] elements, IEnumerable<string> columnNames, IEnumerable<string> rowNames, bool @readonly = false)
     197      : this(elements, columnNames, @readonly ) {
    198198      RowNames = rowNames;
    199199    }
     
    204204
    205205    public virtual StringMatrix AsReadOnly() {
    206       StringMatrix readOnlyStringMatrix = (StringMatrix)this.Clone();
    207       readOnlyStringMatrix.readOnly = true;
    208       return readOnlyStringMatrix;
     206      if (ReadOnly) return this;
     207      var clone = (StringMatrix)this.Clone();
     208      clone.readOnly = true;
     209      return clone;
    209210    }
    210211
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/StringValue.cs

    r17226 r17253  
    2222using System;
    2323using System.Drawing;
     24using HEAL.Attic;
    2425using HeuristicLab.Common;
    2526using HeuristicLab.Core;
    26 using HEAL.Attic;
    2727
    2828namespace HeuristicLab.Data {
     
    6666      this.readOnly = false;
    6767    }
    68     public StringValue(string value) {
     68    public StringValue(string value, bool @readonly = false) {
    6969      this.value = value != null ? value : string.Empty;
    70       this.readOnly = false;
     70      this.readOnly = @readonly;
    7171    }
    7272
     
    7676
    7777    public virtual StringValue AsReadOnly() {
    78       StringValue readOnlyStringValue = (StringValue)this.Clone();
    79       readOnlyStringValue.readOnly = true;
    80       return readOnlyStringValue;
     78      if (ReadOnly) return this;
     79      var clone = (StringValue)this.Clone();
     80      clone.readOnly = true;
     81      return clone;
    8182    }
    8283
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/TextValue.cs

    r17226 r17253  
    2020#endregion
    2121
     22using HEAL.Attic;
    2223using HeuristicLab.Common;
    2324using HeuristicLab.Core;
    24 using HEAL.Attic;
    2525
    2626namespace HeuristicLab.Data {
     
    2929  public class TextValue : StringValue, ITextValue {
    3030
    31     public TextValue() {
    32       this.value = string.Empty;
    33       this.readOnly = false;
    34     }
    35 
    36     public TextValue(string value) {
    37       this.value = value ?? string.Empty;
    38       this.readOnly = false;
    39     }
     31    public TextValue() : base() { }
     32    public TextValue(string value, bool @readonly = false) : base(value ?? string.Empty, @readonly) { }
    4033
    4134    [StorableConstructor]
    4235    protected TextValue(StorableConstructorFlag _) : base(_) { }
    4336
    44     protected TextValue(TextValue original, Cloner cloner)
    45       : base(original, cloner) {
    46       this.value = original.value ?? string.Empty;
    47       this.readOnly = original.readOnly;
    48     }
     37    protected TextValue(TextValue original, Cloner cloner) : base(original, cloner) { }
    4938
    5039    public override IDeepCloneable Clone(Cloner cloner) {
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/TimeSpanValue.cs

    r17226 r17253  
    2323using System.Globalization;
    2424using System.Text;
     25using HEAL.Attic;
    2526using HeuristicLab.Common;
    2627using HeuristicLab.Core;
    27 using HEAL.Attic;
    2828
    2929namespace HeuristicLab.Data {
     
    3737    }
    3838    public TimeSpanValue() : base() { }
    39     public TimeSpanValue(TimeSpan value) : base(value) { }
     39    public TimeSpanValue(TimeSpan value, bool @readonly = false) : base(value, @readonly) { }
    4040
    4141    public override IDeepCloneable Clone(Cloner cloner) {
     
    8080    }
    8181
     82    public new TimeSpanValue AsReadOnly() {
     83      return (TimeSpanValue)base.AsReadOnly();
     84    }
     85
    8286    #region IStringConvertibleValue Members
    8387    bool IStringConvertibleValue.Validate(string value, out string errorMessage) {
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/ValueTypeArray.cs

    r17226 r17253  
    2626using System.Linq;
    2727using System.Text;
     28using HEAL.Attic;
    2829using HeuristicLab.Common;
    2930using HeuristicLab.Core;
    30 using HEAL.Attic;
    3131
    3232namespace HeuristicLab.Data {
     
    137137      elementNames = new List<string>();
    138138    }
    139     protected ValueTypeArray(T[] elements) {
     139    protected ValueTypeArray(T[] elements, bool @readonly = false) {
    140140      if (elements == null) throw new ArgumentNullException();
    141141      array = (T[])elements.Clone();
    142       readOnly = false;
     142      readOnly = @readonly;
    143143      resizable = true;
    144144      elementNames = new List<string>();
     
    146146
    147147    public virtual IValueTypeArray AsReadOnly() {
    148       ValueTypeArray<T> readOnlyValueTypeArray = (ValueTypeArray<T>)this.Clone();
    149       readOnlyValueTypeArray.readOnly = true;
    150       return readOnlyValueTypeArray;
     148      if (ReadOnly) return this;
     149      var clone = (ValueTypeArray<T>)this.Clone();
     150      clone.readOnly = true;
     151      return clone;
    151152    }
    152153
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/ValueTypeMatrix.cs

    r17251 r17253  
    190190
    191191    public virtual ValueTypeMatrix<T> AsReadOnly() {
    192       if (readOnly) return this;
    193       var readOnlyValueTypeMatrix = (ValueTypeMatrix<T>)this.Clone();
    194       readOnlyValueTypeMatrix.readOnly = true;
    195       return readOnlyValueTypeMatrix;
     192      if (ReadOnly) return this;
     193      var clone = (ValueTypeMatrix<T>)this.Clone();
     194      clone.readOnly = true;
     195      return clone;
    196196    }
    197197
  • branches/2521_ProblemRefactoring/HeuristicLab.Data/3.3/ValueTypeValue.cs

    r17226 r17253  
    2222using System;
    2323using System.Drawing;
     24using HEAL.Attic;
    2425using HeuristicLab.Common;
    2526using HeuristicLab.Core;
    26 using HEAL.Attic;
    2727
    2828namespace HeuristicLab.Data {
     
    6464      this.readOnly = false;
    6565    }
    66     protected ValueTypeValue(T value) {
     66    protected ValueTypeValue(T value, bool @readonly = false) {
    6767      this.value = value;
    68       this.readOnly = false;
     68      this.readOnly = @readonly;
    6969    }
    7070
    7171    public virtual ValueTypeValue<T> AsReadOnly() {
    72       ValueTypeValue<T> readOnlyValueTypeValue = (ValueTypeValue<T>)this.Clone();
    73       readOnlyValueTypeValue.readOnly = true;
    74       return readOnlyValueTypeValue;
     72      if (ReadOnly) return this;
     73      var clone = (ValueTypeValue<T>)this.Clone();
     74      clone.readOnly = true;
     75      return clone;
    7576    }
    7677
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.Instances/3.3/Types/DistanceHelper.cs

    r17226 r17253  
    9090    }
    9191
    92     private static double AttDistance(double x1, double y1, double x2, double y2) {
     92    public static double AttDistance(double x1, double y1, double x2, double y2) {
    9393      return Math.Ceiling(Math.Sqrt(((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2)) / 10.0));
    9494    }
    9595
    96     private static double EuclideanDistance(double x1, double y1, double x2, double y2) {
     96    public static double EuclideanDistance(double x1, double y1, double x2, double y2) {
    9797      return Math.Sqrt((x1 - x2) * (x1 - x2) + (y1 - y2) * (y1 - y2));
    9898    }
     
    100100    private const double PI = 3.141592;
    101101    private const double RADIUS = 6378.388;
    102     private static double GeoDistance(double x1, double y1, double x2, double y2) {
     102    public static double GeoDistance(double x1, double y1, double x2, double y2) {
    103103      double latitude1, longitude1, latitude2, longitude2;
    104104      double q1, q2, q3;
     
    122122    }
    123123
    124     private static double ManhattanDistance(double x1, double y1, double x2, double y2) {
     124    public static double ManhattanDistance(double x1, double y1, double x2, double y2) {
    125125      return Math.Round(Math.Abs(x1 - x2) + Math.Abs(y1 - y2), MidpointRounding.AwayFromZero);
    126126    }
    127127
    128     private static double MaximumDistance(double x1, double y1, double x2, double y2) {
     128    public static double MaximumDistance(double x1, double y1, double x2, double y2) {
    129129      return Math.Max(Math.Round(Math.Abs(x1 - x2), MidpointRounding.AwayFromZero), Math.Round(Math.Abs(y1 - y2), MidpointRounding.AwayFromZero));
    130130    }
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/AnalyticalPTSP.cs

    r17226 r17253  
    2020#endregion
    2121
    22 using System;
    2322using System.Linq;
     23using HEAL.Attic;
    2424using HeuristicLab.Common;
    2525using HeuristicLab.Core;
    26 using HeuristicLab.Data;
    2726using HeuristicLab.Encodings.PermutationEncoding;
    28 using HeuristicLab.Optimization;
    29 using HEAL.Attic;
    3027
    3128namespace HeuristicLab.Problems.PTSP {
    32   [Item("Analytical Probabilistic Traveling Salesman Problem (PTSP)", "Represents a probabilistic traveling salesman problem where the expected tour length is calculated exactly.")]
     29  [Item("Analytical Probabilistic TSP (p-TSP)", "Represents a probabilistic traveling salesman problem where the expected tour length is calculated exactly.")]
    3330  [Creatable(CreatableAttribute.Categories.CombinatorialProblems)]
    3431  [StorableType("509B6AB5-F4DE-4144-A031-43EEBAD02CA6")]
    35   public sealed class AnalyticalProbabilisticTravelingSalesmanProblem : ProbabilisticTravelingSalesmanProblem {
     32  public sealed class AnalyticalPTSP : ProbabilisticTSP {
    3633
    3734    [StorableConstructor]
    38     private AnalyticalProbabilisticTravelingSalesmanProblem(StorableConstructorFlag _) : base(_) { }
    39     private AnalyticalProbabilisticTravelingSalesmanProblem(AnalyticalProbabilisticTravelingSalesmanProblem original, Cloner cloner) : base(original, cloner) { }
    40     public AnalyticalProbabilisticTravelingSalesmanProblem() {
    41       Operators.Add(new BestPTSPSolutionAnalyzer());
    42 
     35    private AnalyticalPTSP(StorableConstructorFlag _) : base(_) { }
     36    private AnalyticalPTSP(AnalyticalPTSP original, Cloner cloner) : base(original, cloner) { }
     37    public AnalyticalPTSP() {
    4338      Operators.Add(new PTSPAnalyticalInversionMoveEvaluator());
    4439      Operators.Add(new PTSPAnalyticalInsertionMoveEvaluator());
     
    5348      Operators.Add(new PTSPAnalyticalTwoPointFiveMoveEvaluator());
    5449
    55       Operators.RemoveAll(x => x is SingleObjectiveMoveGenerator);
    56       Operators.RemoveAll(x => x is SingleObjectiveMoveMaker);
    57       Operators.RemoveAll(x => x is SingleObjectiveMoveEvaluator);
    58 
    5950      Encoding.ConfigureOperators(Operators.OfType<IOperator>());
    6051      foreach (var twopointfiveMoveOperator in Operators.OfType<ITwoPointFiveMoveOperator>()) {
     
    6455
    6556    public override IDeepCloneable Clone(Cloner cloner) {
    66       return new AnalyticalProbabilisticTravelingSalesmanProblem(this, cloner);
     57      return new AnalyticalPTSP(this, cloner);
    6758    }
    6859
    6960    public override double Evaluate(Permutation tour, IRandom random) {
    70       // abeham: Cache in local variable for performance reasons
    71       var distanceMatrix = DistanceMatrix;
    72       return Evaluate(tour, (a, b) => distanceMatrix[a, b], Probabilities);
     61      return Evaluate(tour, ProbabilisticTSPData);
    7362    }
    7463
    75     public static double Evaluate(Permutation tour, Func<int, int, double> distance, DoubleArray probabilities) {
     64    public static double Evaluate(Permutation tour, IProbabilisticTSPData data) {
    7665      // Analytical evaluation
    7766      var firstSum = 0.0;
    7867      for (var i = 0; i < tour.Length - 1; i++) {
    7968        for (var j = i + 1; j < tour.Length; j++) {
    80           var prod1 = distance(tour[i], tour[j]) * probabilities[tour[i]] * probabilities[tour[j]];
     69          var prod1 = data.GetDistance(tour[i], tour[j]) * data.GetProbability(tour[i]) * data.GetProbability(tour[j]);
    8170          for (var k = i + 1; k < j; k++) {
    82             prod1 = prod1 * (1 - probabilities[tour[k]]);
     71            prod1 *= (1 - data.GetProbability(tour[k]));
    8372          }
    8473          firstSum += prod1;
     
    8877      for (var j = 0; j < tour.Length; j++) {
    8978        for (var i = 0; i < j; i++) {
    90           var prod2 = distance(tour[j], tour[i]) * probabilities[tour[i]] * probabilities[tour[j]];
     79          var prod2 = data.GetDistance(tour[j], tour[i]) * data.GetProbability(tour[i]) * data.GetProbability(tour[j]);
    9180          for (var k = j + 1; k < tour.Length; k++) {
    92             prod2 = prod2 * (1 - probabilities[tour[k]]);
     81            prod2 *= (1 - data.GetProbability(tour[k]));
    9382          }
    9483          for (var k = 0; k < i; k++) {
    95             prod2 = prod2 * (1 - probabilities[tour[k]]);
     84            prod2 *= (1 - data.GetProbability(tour[k]));
    9685          }
    9786          secondSum += prod2;
     
    10089      return firstSum + secondSum;
    10190    }
    102 
    103     public static double Evaluate(Permutation tour, DistanceMatrix distanceMatrix, DoubleArray probabilities) {
    104       return Evaluate(tour, (a, b) => distanceMatrix[a, b], probabilities);
    105     }
    10691  }
    10792}
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/EstimatedPTSP.cs

    r17226 r17253  
    2121
    2222using System;
     23using System.Collections.Generic;
    2324using System.Linq;
     25using HEAL.Attic;
    2426using HeuristicLab.Common;
    2527using HeuristicLab.Core;
    2628using HeuristicLab.Data;
    2729using HeuristicLab.Encodings.PermutationEncoding;
    28 using HeuristicLab.Optimization;
    2930using HeuristicLab.Parameters;
    30 using HEAL.Attic;
    31 using HeuristicLab.Problems.Instances;
    3231using HeuristicLab.Random;
    3332
    3433namespace HeuristicLab.Problems.PTSP {
    35   [Item("Estimated Probabilistic Traveling Salesman Problem (PTSP)", "Represents a probabilistic traveling salesman problem where the expected tour length is estimated by averaging over the length of tours on a number of, so called, realizations.")]
     34  [Item("Estimated Probabilistic TSP (p-TSP)", "Represents a probabilistic traveling salesman problem where the expected tour length is estimated by averaging over the length of tours on a number of, so called, realizations.")]
    3635  [Creatable(CreatableAttribute.Categories.CombinatorialProblems)]
    37   [StorableType("D1F1DE71-54E3-40B6-856F-685CD71D97F9")]
    38   public sealed class EstimatedProbabilisticTravelingSalesmanProblem : ProbabilisticTravelingSalesmanProblem {
     36  [StorableType("d1b4149b-8ab9-4314-8d96-9ea04a4d5b8b")]
     37  public sealed class EstimatedPTSP : ProbabilisticTSP {
    3938
    4039    #region Parameter Properties
    41     public IValueParameter<ItemList<BoolArray>> RealizationsParameter {
    42       get { return (IValueParameter<ItemList<BoolArray>>)Parameters["Realizations"]; }
    43     }
    44     public IFixedValueParameter<IntValue> RealizationsSizeParameter {
    45       get { return (IFixedValueParameter<IntValue>)Parameters["RealizationsSize"]; }
    46     }
     40    [Storable] public IFixedValueParameter<IntValue> RealizationsSeedParameter { get; private set; }
     41    [Storable] public IFixedValueParameter<IntValue> RealizationsParameter { get; private set; }
     42    [Storable] private IValueParameter<ReadOnlyItemList<BoolArray>> RealizationDataParameter { get; set; }
    4743    #endregion
    4844
    4945    #region Properties
    50     public ItemList<BoolArray> Realizations {
    51       get { return RealizationsParameter.Value; }
    52       set { RealizationsParameter.Value = value; }
    53     }
    54 
    55     public int RealizationsSize {
    56       get { return RealizationsSizeParameter.Value.Value; }
    57       set { RealizationsSizeParameter.Value.Value = value; }
     46
     47    public int RealizationsSeed {
     48      get { return RealizationsSeedParameter.Value.Value; }
     49      set { RealizationsSeedParameter.Value.Value = value; }
     50    }
     51
     52    public int Realizations {
     53      get { return RealizationsParameter.Value.Value; }
     54      set { RealizationsParameter.Value.Value = value; }
     55    }
     56   
     57    private ReadOnlyItemList<BoolArray> RealizationData {
     58      get { return RealizationDataParameter.Value; }
     59      set { RealizationDataParameter.Value = value; }
    5860    }
    5961    #endregion
    6062
    6163    [StorableConstructor]
    62     private EstimatedProbabilisticTravelingSalesmanProblem(StorableConstructorFlag _) : base(_) { }
    63     private EstimatedProbabilisticTravelingSalesmanProblem(EstimatedProbabilisticTravelingSalesmanProblem original, Cloner cloner)
     64    private EstimatedPTSP(StorableConstructorFlag _) : base(_) { }
     65    private EstimatedPTSP(EstimatedPTSP original, Cloner cloner)
    6466      : base(original, cloner) {
     67      RealizationsSeedParameter = cloner.Clone(original.RealizationsSeedParameter);
     68      RealizationsParameter = cloner.Clone(original.RealizationsParameter);
     69      RealizationDataParameter = cloner.Clone(original.RealizationDataParameter);
    6570      RegisterEventHandlers();
    6671    }
    67     public EstimatedProbabilisticTravelingSalesmanProblem() {
    68       Parameters.Add(new FixedValueParameter<IntValue>("RealizationsSize", "Size of the sample for the estimation-based evaluation", new IntValue(100)));
    69       Parameters.Add(new ValueParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances.", new ItemList<BoolArray>()));
    70 
    71       Operators.Add(new BestPTSPSolutionAnalyzer());
     72    public EstimatedPTSP() {
     73      Parameters.Add(RealizationsSeedParameter = new FixedValueParameter<IntValue>("RealizationsSeed", "The starting seed of the RNG from which realizations should be drawn.", new IntValue(1)));
     74      Parameters.Add(RealizationsParameter = new FixedValueParameter<IntValue>("Realizations", "The number of realizations that should be made.", new IntValue(100)));
     75      Parameters.Add(RealizationDataParameter = new ValueParameter<ReadOnlyItemList<BoolArray>>("RealizationData", "The actual realizations.") { Hidden = true, GetsCollected = false });
    7276
    7377      Operators.Add(new PTSPEstimatedInversionMoveEvaluator());
     
    8387      Operators.Add(new PTSPEstimatedTwoPointFiveMoveEvaluator());
    8488
    85       Operators.RemoveAll(x => x is SingleObjectiveMoveGenerator);
    86       Operators.RemoveAll(x => x is SingleObjectiveMoveMaker);
    87       Operators.RemoveAll(x => x is SingleObjectiveMoveEvaluator);
    88 
    8989      Encoding.ConfigureOperators(Operators.OfType<IOperator>());
    9090      foreach (var twopointfiveMoveOperator in Operators.OfType<ITwoPointFiveMoveOperator>()) {
     
    9797
    9898    public override IDeepCloneable Clone(Cloner cloner) {
    99       return new EstimatedProbabilisticTravelingSalesmanProblem(this, cloner);
     99      return new EstimatedPTSP(this, cloner);
     100    }
     101
     102    public override double Evaluate(Permutation tour, IRandom random) {
     103      return Evaluate(tour, ProbabilisticTSPData, RealizationData);
    100104    }
    101105
     
    105109    }
    106110
    107     private void RegisterEventHandlers() {
    108       RealizationsSizeParameter.Value.ValueChanged += RealizationsSizeParameter_ValueChanged;
    109     }
    110 
    111     private void RealizationsSizeParameter_ValueChanged(object sender, EventArgs e) {
    112       UpdateRealizations();
    113     }
    114 
    115     public override double Evaluate(Permutation tour, IRandom random) {
    116       // abeham: Cache parameters in local variables for performance reasons
    117       var realizations = Realizations;
    118       var realizationsSize = RealizationsSize;
    119       var useDistanceMatrix = UseDistanceMatrix;
    120       var distanceMatrix = DistanceMatrix;
    121       var distanceCalculator = DistanceCalculator;
    122       var coordinates = Coordinates;
    123 
     111    public static double Evaluate(Permutation tour, IProbabilisticTSPData data, IEnumerable<BoolArray> realizations) {
    124112      // Estimation-based evaluation, here without calculating variance for faster evaluation
    125113      var estimatedSum = 0.0;
    126       for (var i = 0; i < realizations.Count; i++) {
     114      var count = 0;
     115      foreach (var r in realizations) {
    127116        int singleRealization = -1, firstNode = -1;
    128         for (var j = 0; j < realizations[i].Length; j++) {
    129           if (realizations[i][tour[j]]) {
     117        for (var j = 0; j < data.Cities; j++) {
     118          if (r[tour[j]]) {
    130119            if (singleRealization != -1) {
    131               estimatedSum += useDistanceMatrix ? distanceMatrix[singleRealization, tour[j]] : distanceCalculator.Calculate(singleRealization, tour[j], coordinates);
     120              estimatedSum += data.GetDistance(singleRealization, tour[j]);
    132121            } else {
    133122              firstNode = tour[j];
     
    136125          }
    137126        }
    138         if (singleRealization != -1) {
    139           estimatedSum += useDistanceMatrix ? distanceMatrix[singleRealization, firstNode] : distanceCalculator.Calculate(singleRealization, firstNode, coordinates);
    140         }
    141       }
    142       return estimatedSum / realizationsSize;
     127        if (singleRealization != -1)
     128          estimatedSum += data.GetDistance(singleRealization, firstNode);
     129        count++;
     130      }
     131      return estimatedSum / count;
    143132    }
    144133
     
    147136    /// </summary>
    148137    /// <param name="tour">The tour between all cities.</param>
    149     /// <param name="distanceMatrix">The distances between the cities.</param>
    150     /// <param name="realizations">A sample of realizations of the stochastic instance</param>
     138    /// <param name="data">The main parameters of the p-TSP.</param>
     139    /// <param name="realizations">How many realizations to achieve.</param>
     140    /// <param name="seed">The starting seed of generating the realizations.</param>
    151141    /// <param name="variance">The estimated variance will be returned in addition to the mean.</param>
    152142    /// <returns>A vector with length two containing mean and variance.</returns>
    153     public static double Evaluate(Permutation tour, DistanceMatrix distanceMatrix, ItemList<BoolArray> realizations, out double variance) {
    154       return Evaluate(tour, (a, b) => distanceMatrix[a, b], realizations, out variance);
    155     }
    156 
    157     /// <summary>
    158     /// An evaluate method that can be used if mean as well as variance should be calculated
    159     /// </summary>
    160     /// <param name="tour">The tour between all cities.</param>
    161     /// <param name="distance">A func that accepts the index of two cities and returns the distance as a double.</param>
    162     /// <param name="realizations">A sample of realizations of the stochastic instance</param>
    163     /// <param name="variance">The estimated variance will be returned in addition to the mean.</param>
    164     /// <returns>A vector with length two containing mean and variance.</returns>
    165     public static double Evaluate(Permutation tour, Func<int, int, double> distance, ItemList<BoolArray> realizations, out double variance) {
     143    public static double Evaluate(Permutation tour, IProbabilisticTSPData data, IEnumerable<BoolArray> realizations, out double variance) {
    166144      // Estimation-based evaluation
    167145      var estimatedSum = 0.0;
    168       var partialSums = new double[realizations.Count];
    169       for (var i = 0; i < realizations.Count; i++) {
    170         partialSums[i] = 0;
     146      var partialSums = new List<double>();
     147      var count = 0;
     148      foreach (var r in realizations) {
     149        var pSum = 0.0;
    171150        int singleRealization = -1, firstNode = -1;
    172         for (var j = 0; j < realizations[i].Length; j++) {
    173           if (realizations[i][tour[j]]) {
     151        for (var j = 0; j < data.Cities; j++) {
     152          if (r[tour[j]]) {
    174153            if (singleRealization != -1) {
    175               partialSums[i] += distance(singleRealization, tour[j]);
     154              pSum += data.GetDistance(singleRealization, tour[j]);
    176155            } else {
    177156              firstNode = tour[j];
     
    181160        }
    182161        if (singleRealization != -1) {
    183           partialSums[i] += distance(singleRealization, firstNode);
    184         }
    185         estimatedSum += partialSums[i];
    186       }
    187       var mean = estimatedSum / realizations.Count;
     162          pSum += data.GetDistance(singleRealization, firstNode);
     163        }
     164        estimatedSum += pSum;
     165        partialSums.Add(pSum);
     166        count++;
     167      }
     168      var mean = estimatedSum / count;
    188169      variance = 0.0;
    189       for (var i = 0; i < realizations.Count; i++) {
     170      for (var i = 0; i < count; i++) {
    190171        variance += Math.Pow((partialSums[i] - mean), 2);
    191172      }
    192       variance = variance / realizations.Count;
     173      variance = variance / count;
    193174      return mean;
    194175    }
    195176
    196     public override void Load(PTSPData data) {
    197       base.Load(data);
     177    private void RegisterEventHandlers() {
     178      RealizationsParameter.Value.ValueChanged += RealizationsOnChanged;
     179      RealizationsSeedParameter.Value.ValueChanged += RealizationsSeedOnChanged;
     180    }
     181
     182    private void RealizationsSeedOnChanged(object sender, EventArgs e) {
    198183      UpdateRealizations();
    199 
    200       foreach (var op in Operators.OfType<IEstimatedPTSPOperator>()) {
    201         op.RealizationsParameter.ActualName = RealizationsParameter.Name;
    202       }
     184    }
     185
     186    private void RealizationsOnChanged(object sender, EventArgs e) {
     187      if (Realizations <= 0) Realizations = 1;
     188      else UpdateRealizations();
    203189    }
    204190
    205191    private void UpdateRealizations() {
    206       var realizations = new ItemList<BoolArray>(RealizationsSize);
    207       var rand = new MersenneTwister();
    208       for (var i = 0; i < RealizationsSize; i++) {
    209         var newRealization = new BoolArray(Probabilities.Length);
    210         var countOnes = 0;
    211         do {
    212           countOnes = 0;
    213           for (var j = 0; j < Probabilities.Length; j++) {
    214             newRealization[j] = Probabilities[j] < rand.NextDouble();
    215             if (newRealization[j]) countOnes++;
     192      var data = new List<BoolArray>(Realizations);
     193      var rng = new FastRandom(RealizationsSeed);
     194      for (var i = 0; i < Realizations; i++) {
     195        var cities = 0;
     196        var r = new bool[ProbabilisticTSPData.Cities];
     197        for (var j = 0; j < ProbabilisticTSPData.Cities; j++) {
     198          if (rng.NextDouble() < ProbabilisticTSPData.GetProbability(j)) {
     199            r[j] = true;
     200            cities++;
    216201          }
    217           // only generate realizations with at least 4 cities visited
    218         } while (countOnes < 4 && Probabilities.Length > 3);
    219         realizations.Add(newRealization);
    220       }
    221       Realizations = realizations;
     202        }
     203        if (cities > 0) {
     204          data.Add(new BoolArray(r, @readonly: true));
     205        }
     206      }
     207      RealizationData = (new ItemList<BoolArray>(data)).AsReadOnly();
    222208    }
    223209  }
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/HeuristicLab.Problems.PTSP-3.3.csproj

    r16723 r17253  
    144144      <Private>False</Private>
    145145    </ProjectReference>
     146    <ProjectReference Include="..\..\HeuristicLab.Problems.TravelingSalesman\3.3\HeuristicLab.Problems.TravelingSalesman-3.3.csproj">
     147      <Project>{d767c38d-8014-46b0-9a32-03a3aecce34a}</Project>
     148      <Name>HeuristicLab.Problems.TravelingSalesman-3.3</Name>
     149      <Private>False</Private>
     150    </ProjectReference>
    146151    <ProjectReference Include="..\..\HeuristicLab.Random\3.3\HeuristicLab.Random-3.3.csproj">
    147152      <Project>{F4539FB6-4708-40C9-BE64-0A1390AEA197}</Project>
     
    160165  </ItemGroup>
    161166  <ItemGroup>
     167    <Compile Include="PTSPData.cs" />
    162168    <None Include="Properties\AssemblyInfo.cs.frame" />
    163169    <None Include="Plugin.cs.frame" />
    164170    <Compile Include="AnalyticalPTSP.cs" />
    165     <Compile Include="Analyzers\BestPTSPSolutionAnalyzer.cs" />
    166     <Compile Include="DistanceCalculators\MaximumDistance.cs" />
    167     <Compile Include="DistanceCalculators\ManhattanDistance.cs" />
    168     <Compile Include="DistanceCalculators\GeoDistance.cs" />
    169     <Compile Include="DistanceCalculators\DistanceCalculator.cs" />
    170     <Compile Include="DistanceCalculators\AttDistance.cs" />
    171     <Compile Include="DistanceCalculators\UpperEuclideanDistance.cs" />
    172     <Compile Include="DistanceCalculators\RoundedEuclideanDistance.cs" />
    173     <Compile Include="DistanceCalculators\EuclideanDistance.cs" />
    174     <Compile Include="DistanceMatrix.cs" />
    175171    <Compile Include="EstimatedPTSP.cs" />
    176172    <Compile Include="Improvers\PTSPAnalyticalInsertionLocalImprovement.cs" />
     
    199195    <Compile Include="Moves\TwoPointFiveOpt\TwoPointFiveMoveMaker.cs" />
    200196    <Compile Include="Moves\TwoPointFiveOpt\TwoPointFiveMove.cs" />
    201     <Compile Include="PathPTSPTour.cs" />
    202197    <Compile Include="PTSP.cs" />
    203198    <Compile Include="Plugin.cs" />
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPAnalyticalInsertionLocalImprovement.cs

    r17226 r17253  
    2222using System;
    2323using System.Threading;
     24using HEAL.Attic;
    2425using HeuristicLab.Common;
    2526using HeuristicLab.Core;
     
    2930using HeuristicLab.Optimization;
    3031using HeuristicLab.Parameters;
    31 using HEAL.Attic;
    3232
    3333namespace HeuristicLab.Problems.PTSP {
     
    3939  /// </remarks>
    4040  [Item("PTSP Analytical Insertion Local Improvement", "An operator that improves probabilistic traveling salesman solutions. The operator tries to improve the probabilistic traveling salesman solution by swapping two randomly chosen edges for a certain number of times.")]
    41   [StorableType("D63C6CB3-A5EF-4270-A252-2F5EBF1ED163")]
     41  [StorableType("5adca9d8-02b2-4937-9f79-a24d8ea8ea19")]
    4242  public sealed class PTSPAnalyticalInsertionLocalImprovement : SingleSuccessorOperator, IAnalyticalPTSPOperator, ILocalImprovementOperator {
    4343
     
    7070    }
    7171
    72     public ILookupParameter<DistanceMatrix> DistanceMatrixParameter {
    73       get { return (ILookupParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
    74     }
    75 
    76     public ILookupParameter<DoubleArray> ProbabilitiesParameter {
    77       get { return (ILookupParameter<DoubleArray>)Parameters["Probabilities"]; }
     72    public ILookupParameter<IProbabilisticTSPData> ProbabilisticTSPDataParameter {
     73      get { return (ILookupParameter<IProbabilisticTSPData>)Parameters["PTSP Data"]; }
    7874    }
    7975
     
    9086      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality value of the assignment."));
    9187      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem should be maximized or minimized."));
    92       Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
    93       Parameters.Add(new LookupParameter<DoubleArray>("Probabilities", "The list of probabilities of the cities to appear."));
     88      Parameters.Add(new LookupParameter<IProbabilisticTSPData>("PTSP Data", "The main parameters of the p-TSP."));
    9489    }
    9590
     
    9893    }
    9994
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, DoubleArray probabilities, CancellationToken cancellation) {
    101       var distanceM = (DistanceMatrix)distances;
    102       Func<int, int, double> distance = (a, b) => distanceM[a, b];
     95    public static void Improve(Permutation assignment, IProbabilisticTSPData data, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation) {
    10396      for (var i = localIterations.Value; i < maxIterations; i++) {
    10497        TranslocationMove bestMove = null;
     
    10699        var evaluations = 0.0;
    107100        foreach (var move in ExhaustiveInsertionMoveGenerator.Generate(assignment)) {
    108           var moveQuality = PTSPAnalyticalInsertionMoveEvaluator.EvaluateMove(assignment, move, distance, probabilities);
     101          var moveQuality = PTSPAnalyticalInsertionMoveEvaluator.EvaluateMove(assignment, move, data);
    109102          evaluations++;
    110103          if (maximization && moveQuality > bestQuality
     
    127120      var assignment = PermutationParameter.ActualValue;
    128121      var maximization = MaximizationParameter.ActualValue.Value;
    129       var distances = DistanceMatrixParameter.ActualValue;
    130122      var quality = QualityParameter.ActualValue;
    131123      var localIterations = LocalIterationsParameter.ActualValue;
    132124      var evaluations = EvaluatedSolutionsParameter.ActualValue;
    133       var probabilities = ProbabilitiesParameter.ActualValue;
     125      var data = ProbabilisticTSPDataParameter.ActualValue;
    134126      if (localIterations == null) {
    135127        localIterations = new IntValue(0);
     
    137129      }
    138130
    139       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, probabilities, CancellationToken);
     131      Improve(assignment, data, quality, localIterations, evaluations, maximization, maxIterations, CancellationToken);
    140132
    141133      localIterations.Value = 0;
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPAnalyticalInversionLocalImprovement.cs

    r17226 r17253  
    2222using System;
    2323using System.Threading;
     24using HEAL.Attic;
    2425using HeuristicLab.Common;
    2526using HeuristicLab.Core;
     
    2930using HeuristicLab.Optimization;
    3031using HeuristicLab.Parameters;
    31 using HEAL.Attic;
    3232
    3333namespace HeuristicLab.Problems.PTSP {
     
    3939  /// </remarks>
    4040  [Item("PTSP Analytical Inversion Local Improvement", "An operator that improves probabilistic traveling salesman solutions. The operator tries to improve the probabilistic traveling salesman solution by swapping two randomly chosen edges for a certain number of times.")]
    41   [StorableType("1594EB4E-A874-485A-B1D5-E622F9FF3FD8")]
     41  [StorableType("88147d6a-e843-4f65-8058-421453b5206a")]
    4242  public sealed class PTSPAnalyticalInversionLocalImprovement : SingleSuccessorOperator, IAnalyticalPTSPOperator, ILocalImprovementOperator {
    4343
     
    7070    }
    7171
    72     public ILookupParameter<DistanceMatrix> DistanceMatrixParameter {
    73       get { return (ILookupParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
    74     }
    75 
    76     public ILookupParameter<DoubleArray> ProbabilitiesParameter {
    77       get { return (ILookupParameter<DoubleArray>)Parameters["Probabilities"]; }
     72    public ILookupParameter<IProbabilisticTSPData> ProbabilisticTSPDataParameter {
     73      get { return (ILookupParameter<IProbabilisticTSPData>)Parameters["PTSP Data"]; }
    7874    }
    7975
     
    9086      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality value of the assignment."));
    9187      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem should be maximized or minimized."));
    92       Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
    93       Parameters.Add(new LookupParameter<DoubleArray>("Probabilities", "The list of probabilities of the cities to appear."));
     88      Parameters.Add(new LookupParameter<IProbabilisticTSPData>("PTSP Data", "The main parameters of the p-TSP."));
    9489    }
    9590
     
    9893    }
    9994
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, DoubleArray probabilities, CancellationToken cancellation) {
    101       var distanceM = (DistanceMatrix)distances;
    102       Func<int, int, double> distance = (a, b) => distanceM[a, b];
     95    public static void Improve(Permutation assignment, IProbabilisticTSPData data, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation) {
    10396      for (var i = localIterations.Value; i < maxIterations; i++) {
    10497        InversionMove bestMove = null;
     
    10699        var evaluations = 0.0;
    107100        foreach (var move in ExhaustiveInversionMoveGenerator.Generate(assignment)) {
    108           var moveQuality = PTSPAnalyticalInversionMoveEvaluator.EvaluateMove(assignment, move, distance, probabilities);
     101          var moveQuality = PTSPAnalyticalInversionMoveEvaluator.EvaluateMove(assignment, move, data);
    109102          evaluations++;
    110103          if (maximization && moveQuality > bestQuality
     
    127120      var assignment = PermutationParameter.ActualValue;
    128121      var maximization = MaximizationParameter.ActualValue.Value;
    129       var distances = DistanceMatrixParameter.ActualValue;
    130122      var quality = QualityParameter.ActualValue;
    131123      var localIterations = LocalIterationsParameter.ActualValue;
    132124      var evaluations = EvaluatedSolutionsParameter.ActualValue;
    133       var probabilities = ProbabilitiesParameter.ActualValue;
     125      var data = ProbabilisticTSPDataParameter.ActualValue;
    134126      if (localIterations == null) {
    135127        localIterations = new IntValue(0);
     
    137129      }
    138130
    139       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, probabilities, CancellationToken);
     131      Improve(assignment, data, quality, localIterations, evaluations, maximization, maxIterations, CancellationToken);
    140132
    141133      localIterations.Value = 0;
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPAnalyticalTwoPointFiveLocalImprovement.cs

    r17226 r17253  
    2222using System;
    2323using System.Threading;
     24using HEAL.Attic;
    2425using HeuristicLab.Common;
    2526using HeuristicLab.Core;
     
    2930using HeuristicLab.Optimization;
    3031using HeuristicLab.Parameters;
    31 using HEAL.Attic;
    3232
    3333namespace HeuristicLab.Problems.PTSP {
     
    3939  /// </remarks>
    4040  [Item("PTSP Analytical 2.5 Local Improvement", "An operator that improves probabilistic traveling salesman solutions. The operator tries to improve the probabilistic traveling salesman solution by swapping two randomly chosen edges for a certain number of times.")]
    41   [StorableType("C139639F-D6DD-4756-8482-24F12A78C8E9")]
     41  [StorableType("6e07195e-0da7-45ea-9385-0c66594127db")]
    4242  public sealed class PTSPAnalyticalTwoPointFiveLocalImprovement : SingleSuccessorOperator, IAnalyticalPTSPOperator, ILocalImprovementOperator {
    4343
     
    7070    }
    7171
    72     public ILookupParameter<DistanceMatrix> DistanceMatrixParameter {
    73       get { return (ILookupParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
    74     }
    75 
    76     public ILookupParameter<DoubleArray> ProbabilitiesParameter {
    77       get { return (ILookupParameter<DoubleArray>)Parameters["Probabilities"]; }
     72    public ILookupParameter<IProbabilisticTSPData> ProbabilisticTSPDataParameter {
     73      get { return (ILookupParameter<IProbabilisticTSPData>)Parameters["PTSP Data"]; }
    7874    }
    7975
     
    9086      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality value of the assignment."));
    9187      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem should be maximized or minimized."));
    92       Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
    93       Parameters.Add(new LookupParameter<DoubleArray>("Probabilities", "The list of probabilities of the cities to appear."));
     88      Parameters.Add(new LookupParameter<IProbabilisticTSPData>("PTSP Data", "The main parameters of the p-TSP."));
    9489    }
    9590
     
    9893    }
    9994
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, DoubleArray probabilities, CancellationToken cancellation) {
    101       var distanceM = (DistanceMatrix)distances;
    102       Func<int, int, double> distance = (a, b) => distanceM[a, b];
     95    public static void Improve(Permutation assignment, IProbabilisticTSPData data, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, CancellationToken cancellation) {
    10396      for (var i = localIterations.Value; i < maxIterations; i++) {
    10497        TwoPointFiveMove bestMove = null;
     
    10699        var evaluations = 0.0;
    107100        foreach (var move in ExhaustiveTwoPointFiveMoveGenerator.Generate(assignment)) {
    108           var moveQuality = PTSPAnalyticalTwoPointFiveMoveEvaluator.EvaluateMove(assignment, move, distance, probabilities);
     101          var moveQuality = PTSPAnalyticalTwoPointFiveMoveEvaluator.EvaluateMove(assignment, move, data);
    109102          evaluations++;
    110103          if (maximization && moveQuality > bestQuality
     
    127120      var assignment = PermutationParameter.ActualValue;
    128121      var maximization = MaximizationParameter.ActualValue.Value;
    129       var distances = DistanceMatrixParameter.ActualValue;
    130122      var quality = QualityParameter.ActualValue;
    131123      var localIterations = LocalIterationsParameter.ActualValue;
    132124      var evaluations = EvaluatedSolutionsParameter.ActualValue;
    133       var probabilities = ProbabilitiesParameter.ActualValue;
     125      var data = ProbabilisticTSPDataParameter.ActualValue;
    134126      if (localIterations == null) {
    135127        localIterations = new IntValue(0);
     
    137129      }
    138130
    139       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, probabilities, CancellationToken);
     131      Improve(assignment, data, quality, localIterations, evaluations, maximization, maxIterations, CancellationToken);
    140132
    141133      localIterations.Value = 0;
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPEstimatedInsertionLocalImprovement.cs

    r17226 r17253  
    2121
    2222using System;
     23using System.Collections.Generic;
     24using System.Linq;
    2325using System.Threading;
     26using HEAL.Attic;
    2427using HeuristicLab.Common;
    2528using HeuristicLab.Core;
     
    2932using HeuristicLab.Optimization;
    3033using HeuristicLab.Parameters;
    31 using HEAL.Attic;
    3234
    3335namespace HeuristicLab.Problems.PTSP {
     
    7072    }
    7173
    72     public ILookupParameter<DistanceMatrix> DistanceMatrixParameter {
    73       get { return (ILookupParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
     74    public ILookupParameter<IProbabilisticTSPData> ProbabilisticTSPDataParameter {
     75      get { return (ILookupParameter<IProbabilisticTSPData>)Parameters["PTSP Data"]; }
    7476    }
    7577
    76     public ILookupParameter<ItemList<BoolArray>> RealizationsParameter {
    77       get { return (ILookupParameter<ItemList<BoolArray>>)Parameters["Realizations"]; }
     78    public ILookupParameter<ReadOnlyItemList<BoolArray>> RealizationsParameter {
     79      get { return (ILookupParameter<ReadOnlyItemList<BoolArray>>)Parameters["Realizations"]; }
    7880    }
    7981
     
    9092      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality value of the assignment."));
    9193      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem should be maximized or minimized."));
    92       Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
     94      Parameters.Add(new LookupParameter<IProbabilisticTSPData>("PTSP Data", "The main parameters of the p-TSP."));
    9395      Parameters.Add(new LookupParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances."));
    9496    }
     
    98100    }
    99101
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, ItemList<BoolArray> realizations, CancellationToken cancellation) {
    101       var distanceM = (DistanceMatrix)distances;
    102       Func<int, int, double> distance = (a, b) => distanceM[a, b];
     102    public static void Improve(Permutation assignment, IProbabilisticTSPData data, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, IEnumerable<BoolArray> realizations, CancellationToken cancellation) {
    103103      for (var i = localIterations.Value; i < maxIterations; i++) {
    104104        TranslocationMove bestMove = null;
     
    106106        double evaluations = 0.0;
    107107        foreach (var move in ExhaustiveInsertionMoveGenerator.Generate(assignment)) {
    108           double moveQuality = PTSPEstimatedInsertionMoveEvaluator.EvaluateMove(assignment, move, distance, realizations);
    109           evaluations += realizations.Count * 6.0 / (assignment.Length * assignment.Length);
     108          double moveQuality = PTSPEstimatedInsertionMoveEvaluator.EvaluateMove(assignment, move, data, realizations);
     109          evaluations += realizations.Count() * 6.0 / (assignment.Length * assignment.Length);
    110110          if (maximization && moveQuality > bestQuality
    111111            || !maximization && moveQuality < bestQuality) {
     
    127127      var assignment = PermutationParameter.ActualValue;
    128128      var maximization = MaximizationParameter.ActualValue.Value;
    129       var distances = DistanceMatrixParameter.ActualValue;
    130129      var quality = QualityParameter.ActualValue;
    131130      var localIterations = LocalIterationsParameter.ActualValue;
    132131      var evaluations = EvaluatedSolutionsParameter.ActualValue;
     132      var data = ProbabilisticTSPDataParameter.ActualValue;
    133133      var realizations = RealizationsParameter.ActualValue;
    134134      if (localIterations == null) {
     
    137137      }
    138138
    139       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, realizations, CancellationToken);
     139      Improve(assignment, data, quality, localIterations, evaluations, maximization, maxIterations, realizations, CancellationToken);
    140140
    141141      localIterations.Value = 0;
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPEstimatedInversionLocalImprovement.cs

    r17226 r17253  
    2121
    2222using System;
     23using System.Collections.Generic;
     24using System.Linq;
    2325using System.Threading;
     26using HEAL.Attic;
    2427using HeuristicLab.Common;
    2528using HeuristicLab.Core;
     
    2932using HeuristicLab.Optimization;
    3033using HeuristicLab.Parameters;
    31 using HEAL.Attic;
    3234
    3335namespace HeuristicLab.Problems.PTSP {
     
    7072    }
    7173
    72     public ILookupParameter<DistanceMatrix> DistanceMatrixParameter {
    73       get { return (ILookupParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
     74    public ILookupParameter<IProbabilisticTSPData> ProbabilisticTSPDataParameter {
     75      get { return (ILookupParameter<IProbabilisticTSPData>)Parameters["PTSP Data"]; }
    7476    }
    7577
    76     public ILookupParameter<ItemList<BoolArray>> RealizationsParameter {
    77       get { return (ILookupParameter<ItemList<BoolArray>>)Parameters["Realizations"]; }
     78    public ILookupParameter<ReadOnlyItemList<BoolArray>> RealizationsParameter {
     79      get { return (ILookupParameter<ReadOnlyItemList<BoolArray>>)Parameters["Realizations"]; }
    7880    }
    7981
     
    9092      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality value of the assignment."));
    9193      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem should be maximized or minimized."));
    92       Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
     94      Parameters.Add(new LookupParameter<IProbabilisticTSPData>("PTSP Data", "The main parameters of the p-TSP."));
    9395      Parameters.Add(new LookupParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances."));
    9496    }
     
    98100    }
    99101
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, ItemList<BoolArray> realizations, CancellationToken cancellation) {
    101       var distanceM = (DistanceMatrix)distances;
    102       Func<int, int, double> distance = (a, b) => distanceM[a, b];
     102    public static void Improve(Permutation assignment, IProbabilisticTSPData data, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, IEnumerable<BoolArray> realizations, CancellationToken cancellation) {
    103103      for (var i = localIterations.Value; i < maxIterations; i++) {
    104104        InversionMove bestMove = null;
     
    106106        double evaluations = 0.0;
    107107        foreach (var move in ExhaustiveInversionMoveGenerator.Generate(assignment)) {
    108           double moveQuality = PTSPEstimatedInversionMoveEvaluator.EvaluateMove(assignment, move, distance, realizations);
    109           evaluations += realizations.Count * 4.0 / (assignment.Length * assignment.Length);
     108          double moveQuality = PTSPEstimatedInversionMoveEvaluator.EvaluateMove(assignment, move, data, realizations);
     109          evaluations += realizations.Count() * 4.0 / (assignment.Length * assignment.Length);
    110110          if (maximization && moveQuality > bestQuality
    111111            || !maximization && moveQuality < bestQuality) {
     
    127127      var assignment = PermutationParameter.ActualValue;
    128128      var maximization = MaximizationParameter.ActualValue.Value;
    129       var distances = DistanceMatrixParameter.ActualValue;
    130129      var quality = QualityParameter.ActualValue;
    131130      var localIterations = LocalIterationsParameter.ActualValue;
    132131      var evaluations = EvaluatedSolutionsParameter.ActualValue;
     132      var data = ProbabilisticTSPDataParameter.ActualValue;
    133133      var realizations = RealizationsParameter.ActualValue;
    134134      if (localIterations == null) {
     
    137137      }
    138138
    139       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, realizations, CancellationToken);
     139      Improve(assignment, data, quality, localIterations, evaluations, maximization, maxIterations, realizations, CancellationToken);
    140140
    141141      localIterations.Value = 0;
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Improvers/PTSPEstimatedTwoPointFiveLocalImprovement.cs

    r17226 r17253  
    2121
    2222using System;
     23using System.Collections.Generic;
     24using System.Linq;
    2325using System.Threading;
     26using HEAL.Attic;
    2427using HeuristicLab.Common;
    2528using HeuristicLab.Core;
     
    2932using HeuristicLab.Optimization;
    3033using HeuristicLab.Parameters;
    31 using HEAL.Attic;
    3234
    3335namespace HeuristicLab.Problems.PTSP {
     
    7072    }
    7173
    72     public ILookupParameter<DistanceMatrix> DistanceMatrixParameter {
    73       get { return (ILookupParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
     74    public ILookupParameter<IProbabilisticTSPData> ProbabilisticTSPDataParameter {
     75      get { return (ILookupParameter<IProbabilisticTSPData>)Parameters["PTSP Data"]; }
    7476    }
    75 
    76     public ILookupParameter<ItemList<BoolArray>> RealizationsParameter {
    77       get { return (ILookupParameter<ItemList<BoolArray>>)Parameters["Realizations"]; }
     77    public ILookupParameter<ReadOnlyItemList<BoolArray>> RealizationsParameter {
     78      get { return (ILookupParameter<ReadOnlyItemList<BoolArray>>)Parameters["Realizations"]; }
    7879    }
    7980
     
    9091      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality value of the assignment."));
    9192      Parameters.Add(new LookupParameter<BoolValue>("Maximization", "True if the problem should be maximized or minimized."));
    92       Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
    93       Parameters.Add(new LookupParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances."));
     93      Parameters.Add(new LookupParameter<IProbabilisticTSPData>("PTSP Data", "The main parameters of the p-TSP."));
     94      Parameters.Add(new LookupParameter<ReadOnlyItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances."));
    9495    }
    9596
     
    9899    }
    99100
    100     public static void Improve(Permutation assignment, DoubleMatrix distances, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, ItemList<BoolArray> realizations, CancellationToken cancellation) {
    101       var distanceM = (DistanceMatrix)distances;
    102       Func<int, int, double> distance = (a, b) => distanceM[a, b];
     101    public static void Improve(Permutation assignment, IProbabilisticTSPData data, DoubleValue quality, IntValue localIterations, IntValue evaluatedSolutions, bool maximization, int maxIterations, IEnumerable<BoolArray> realizations, CancellationToken cancellation) {
    103102      for (var i = localIterations.Value; i < maxIterations; i++) {
    104103        TwoPointFiveMove bestMove = null;
     
    106105        var evaluations = 0.0;
    107106        foreach (var move in ExhaustiveTwoPointFiveMoveGenerator.Generate(assignment)) {
    108           var moveQuality = PTSPEstimatedTwoPointFiveMoveEvaluator.EvaluateMove(assignment, move, distance, realizations);
    109           if (move.IsInvert) evaluations += realizations.Count * 4.0 / (assignment.Length * assignment.Length);
    110           else evaluations += realizations.Count * 6.0 / (assignment.Length * assignment.Length);
     107          var moveQuality = PTSPEstimatedTwoPointFiveMoveEvaluator.EvaluateMove(assignment, move, data, realizations);
     108          if (move.IsInvert) evaluations += realizations.Count() * 4.0 / (assignment.Length * assignment.Length);
     109          else evaluations += realizations.Count() * 6.0 / (assignment.Length * assignment.Length);
    111110          if (maximization && moveQuality > bestQuality
    112111            || !maximization && moveQuality < bestQuality) {
     
    128127      var assignment = PermutationParameter.ActualValue;
    129128      var maximization = MaximizationParameter.ActualValue.Value;
    130       var distances = DistanceMatrixParameter.ActualValue;
    131129      var quality = QualityParameter.ActualValue;
    132130      var localIterations = LocalIterationsParameter.ActualValue;
    133131      var evaluations = EvaluatedSolutionsParameter.ActualValue;
     132      var data = ProbabilisticTSPDataParameter.ActualValue;
    134133      var realizations = RealizationsParameter.ActualValue;
    135134      if (localIterations == null) {
     
    138137      }
    139138
    140       Improve(assignment, distances, quality, localIterations, evaluations, maximization, maxIterations, realizations, CancellationToken);
     139      Improve(assignment, data, quality, localIterations, evaluations, maximization, maxIterations, realizations, CancellationToken);
    141140
    142141      localIterations.Value = 0;
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Interfaces/IAnalyticalPTSPMoveEvaluator.cs

    r17226 r17253  
    2020#endregion
    2121
    22 using HeuristicLab.Core;
    23 using HeuristicLab.Data;
     22using HEAL.Attic;
    2423using HeuristicLab.Encodings.PermutationEncoding;
    2524using HeuristicLab.Optimization;
    26 using HEAL.Attic;
    2725
    2826namespace HeuristicLab.Problems.PTSP {
    29   [StorableType("D503E92D-9A85-46AC-ADAA-8A454B9E9C79")]
     27  [StorableType("dea758f7-136a-469f-a486-ef6569fa0c74")]
    3028  public interface IAnalyticalPTSPMoveEvaluator : IAnalyticalPTSPOperator, ISingleObjectiveMoveEvaluator, IPermutationMoveOperator {
    31     ILookupParameter<DoubleMatrix> CoordinatesParameter { get; }
    32     ILookupParameter<DistanceCalculator> DistanceCalculatorParameter { get; }
    33     ILookupParameter<DistanceMatrix> DistanceMatrixParameter { get; }
    34     ILookupParameter<BoolValue> UseDistanceMatrixParameter { get; }
    3529  }
    3630}
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Interfaces/IAnalyticalPTSPOperator.cs

    r17226 r17253  
    2020#endregion
    2121
     22using HEAL.Attic;
    2223using HeuristicLab.Core;
    23 using HeuristicLab.Data;
    24 using HEAL.Attic;
    2524
    2625namespace HeuristicLab.Problems.PTSP {
    27   [StorableType("1BB8344B-894B-48E9-9805-49938AE3F83F")]
     26  [StorableType("2b0bd347-7bb6-449a-bbcf-24aa452abc0a")]
    2827  public interface IAnalyticalPTSPOperator : IItem {
    29     ILookupParameter<DoubleArray> ProbabilitiesParameter { get; }
     28    ILookupParameter<IProbabilisticTSPData> ProbabilisticTSPDataParameter { get; }
    3029  }
    3130}
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Interfaces/IEstimatedPTSPMoveEvaluator.cs

    r17226 r17253  
    2020#endregion
    2121
    22 using HeuristicLab.Core;
    23 using HeuristicLab.Data;
     22using HEAL.Attic;
    2423using HeuristicLab.Encodings.PermutationEncoding;
    2524using HeuristicLab.Optimization;
    26 using HEAL.Attic;
    2725
    2826namespace HeuristicLab.Problems.PTSP {
    29   [StorableType("FECFFE5C-64EE-4615-A9FC-786F2B37143A")]
     27  [StorableType("96103e8b-bfc4-4e42-a579-074bfdd8d589")]
    3028  public interface IEstimatedPTSPMoveEvaluator : IEstimatedPTSPOperator, ISingleObjectiveMoveEvaluator, IPermutationMoveOperator {
    31     ILookupParameter<DoubleMatrix> CoordinatesParameter { get; }
    32     ILookupParameter<DistanceCalculator> DistanceCalculatorParameter { get; }
    33     ILookupParameter<DistanceMatrix> DistanceMatrixParameter { get; }
    34     ILookupParameter<BoolValue> UseDistanceMatrixParameter { get; }
    3529  }
    3630}
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Interfaces/IEstimatedPTSPOperator.cs

    r17226 r17253  
    2020#endregion
    2121
     22using HEAL.Attic;
    2223using HeuristicLab.Core;
    2324using HeuristicLab.Data;
    24 using HEAL.Attic;
    2525
    2626namespace HeuristicLab.Problems.PTSP {
    27   [StorableType("1998604C-41FF-4388-B413-8BD658D073E5")]
     27  [StorableType("5bcc1ef1-b865-42be-8a63-e5f810c52d01")]
    2828  public interface IEstimatedPTSPOperator : IItem {
    29     ILookupParameter<ItemList<BoolArray>> RealizationsParameter { get; }
     29    ILookupParameter<IProbabilisticTSPData> ProbabilisticTSPDataParameter { get; }
     30    ILookupParameter<ReadOnlyItemList<BoolArray>> RealizationsParameter { get; }
    3031  }
    3132}
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Moves/AnalyticalPTSPMoveEvaluator.cs

    r17226 r17253  
    2020#endregion
    2121
    22 using System;
     22using HEAL.Attic;
    2323using HeuristicLab.Common;
    2424using HeuristicLab.Core;
     
    2727using HeuristicLab.Operators;
    2828using HeuristicLab.Parameters;
    29 using HEAL.Attic;
    3029
    3130namespace HeuristicLab.Problems.PTSP {
     
    4140      get { return (ILookupParameter<Permutation>)Parameters["Permutation"]; }
    4241    }
    43     public ILookupParameter<DoubleMatrix> CoordinatesParameter {
    44       get { return (ILookupParameter<DoubleMatrix>)Parameters["Coordinates"]; }
    45     }
    46     public ILookupParameter<DistanceMatrix> DistanceMatrixParameter {
    47       get { return (ILookupParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
    48     }
    49     public ILookupParameter<BoolValue> UseDistanceMatrixParameter {
    50       get { return (ILookupParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }
    51     }
    52     public ILookupParameter<DoubleArray> ProbabilitiesParameter {
    53       get { return (ILookupParameter<DoubleArray>)Parameters["Probabilities"]; }
    54     }
    5542    public ILookupParameter<DoubleValue> QualityParameter {
    5643      get { return (ILookupParameter<DoubleValue>)Parameters["Quality"]; }
     
    5946      get { return (ILookupParameter<DoubleValue>)Parameters["MoveQuality"]; }
    6047    }
    61     public ILookupParameter<DistanceCalculator> DistanceCalculatorParameter {
    62       get { return (ILookupParameter<DistanceCalculator>)Parameters["DistanceCalculator"]; }
     48    public ILookupParameter<IProbabilisticTSPData> ProbabilisticTSPDataParameter {
     49      get { return (ILookupParameter<IProbabilisticTSPData>)Parameters["PTSP Data"]; }
    6350    }
    6451
     
    6956      : base() {
    7057      Parameters.Add(new LookupParameter<Permutation>("Permutation", "The solution as permutation."));
    71       Parameters.Add(new LookupParameter<DoubleMatrix>("Coordinates", "The city's coordinates."));
    72       Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
    73       Parameters.Add(new LookupParameter<BoolValue>("UseDistanceMatrix", "True if a distance matrix should be calculated (if it does not exist already) and used for evaluation, otherwise false."));
    74       Parameters.Add(new LookupParameter<DoubleArray>("Probabilities", "The list of probabilities for each city to appear."));
    7558      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality of a TSP solution."));
    7659      Parameters.Add(new LookupParameter<DoubleValue>("MoveQuality", "The evaluated quality of a move on a TSP solution."));
    77       Parameters.Add(new LookupParameter<DistanceCalculator>("DistanceCalculator", "The class that can compute distances between coordinates."));
     60      Parameters.Add(new LookupParameter<IProbabilisticTSPData>("PTSP Data", "The main parameters of the p-TSP."));
    7861    }
    7962
    8063    public override IOperation Apply() {
    8164      var permutation = PermutationParameter.ActualValue;
    82       var coordinates = CoordinatesParameter.ActualValue;
    83       var probabilities = ProbabilitiesParameter.ActualValue;
    84       Func<int, int, double> distance = null;
    85       if (UseDistanceMatrixParameter.ActualValue.Value) {
    86         var distanceMatrix = DistanceMatrixParameter.ActualValue;
    87         if (distanceMatrix == null) throw new InvalidOperationException("The distance matrix has not been calculated.");
    88         distance = (a, b) => distanceMatrix[a, b];
    89       } else {
    90         if (coordinates == null) throw new InvalidOperationException("No coordinates were given.");
    91         var distanceCalculator = DistanceCalculatorParameter.ActualValue;
    92         if (distanceCalculator == null) throw new InvalidOperationException("Distance calculator is null!");
    93         distance = (a, b) => distanceCalculator.Calculate(a, b, coordinates);
    94       }
     65      var data = ProbabilisticTSPDataParameter.ActualValue;
     66
    9567      // here moves are not delta-evaluated
    96       var newQuality = EvaluateMove(permutation, distance, probabilities);
     68      var newQuality = EvaluateMove(permutation, data);
    9769      var moveQuality = MoveQualityParameter.ActualValue;
    9870      if (moveQuality == null) MoveQualityParameter.ActualValue = new DoubleValue(newQuality);
     
    10274    }
    10375
    104     protected abstract double EvaluateMove(Permutation permutation, Func<int, int, double> distance, DoubleArray probabilities);
     76    protected abstract double EvaluateMove(Permutation tour, IProbabilisticTSPData data);
    10577  }
    10678}
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Moves/EstimatedPTSPMoveEvaluator.cs

    r17226 r17253  
    2020#endregion
    2121
    22 using System;
     22using HEAL.Attic;
    2323using HeuristicLab.Common;
    2424using HeuristicLab.Core;
     
    2727using HeuristicLab.Operators;
    2828using HeuristicLab.Parameters;
    29 using HEAL.Attic;
    3029
    3130namespace HeuristicLab.Problems.PTSP {
     
    4140      get { return (ILookupParameter<Permutation>)Parameters["Permutation"]; }
    4241    }
    43     public ILookupParameter<DoubleMatrix> CoordinatesParameter {
    44       get { return (ILookupParameter<DoubleMatrix>)Parameters["Coordinates"]; }
     42    public ILookupParameter<IProbabilisticTSPData> ProbabilisticTSPDataParameter {
     43      get { return (ILookupParameter<IProbabilisticTSPData>)Parameters["PTSP Data"]; }
    4544    }
    46     public ILookupParameter<DistanceMatrix> DistanceMatrixParameter {
    47       get { return (ILookupParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
    48     }
    49     public ILookupParameter<BoolValue> UseDistanceMatrixParameter {
    50       get { return (ILookupParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }
    51     }
    52     public ILookupParameter<ItemList<BoolArray>> RealizationsParameter {
    53       get { return (ILookupParameter<ItemList<BoolArray>>)Parameters["Realizations"]; }
     45    public ILookupParameter<ReadOnlyItemList<BoolArray>> RealizationsParameter {
     46      get { return (ILookupParameter<ReadOnlyItemList<BoolArray>>)Parameters["Realizations"]; }
    5447    }
    5548    public ILookupParameter<DoubleValue> QualityParameter {
     
    5851    public ILookupParameter<DoubleValue> MoveQualityParameter {
    5952      get { return (ILookupParameter<DoubleValue>)Parameters["MoveQuality"]; }
    60     }
    61     public ILookupParameter<DistanceCalculator> DistanceCalculatorParameter {
    62       get { return (ILookupParameter<DistanceCalculator>)Parameters["DistanceCalculator"]; }
    6353    }
    6454
     
    6959      : base() {
    7060      Parameters.Add(new LookupParameter<Permutation>("Permutation", "The solution as permutation."));
    71       Parameters.Add(new LookupParameter<DoubleMatrix>("Coordinates", "The city's coordinates."));
    72       Parameters.Add(new LookupParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
    73       Parameters.Add(new LookupParameter<BoolValue>("UseDistanceMatrix", "True if a distance matrix should be calculated (if it does not exist already) and used for evaluation, otherwise false."));
    74       Parameters.Add(new LookupParameter<ItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances."));
     61      Parameters.Add(new LookupParameter<IProbabilisticTSPData>("PTSP Data", "The main parameters of the p-TSP."));
     62      Parameters.Add(new LookupParameter<ReadOnlyItemList<BoolArray>>("Realizations", "The list of samples drawn from all possible stochastic instances."));
    7563      Parameters.Add(new LookupParameter<DoubleValue>("Quality", "The quality of a TSP solution."));
    7664      Parameters.Add(new LookupParameter<DoubleValue>("MoveQuality", "The evaluated quality of a move on a TSP solution."));
    77       Parameters.Add(new LookupParameter<DistanceCalculator>("DistanceCalculator", "The class that can compute distances between coordinates."));
    7865    }
    7966
    8067    public override IOperation Apply() {
    8168      var permutation = PermutationParameter.ActualValue;
    82       var coordinates = CoordinatesParameter.ActualValue;
    8369      var realizations = RealizationsParameter.ActualValue;
    84       Func<int, int, double> distance = null;
    85       if (UseDistanceMatrixParameter.ActualValue.Value) {
    86         var distanceMatrix = DistanceMatrixParameter.ActualValue;
    87         if (distanceMatrix == null) throw new InvalidOperationException("The distance matrix has not been calculated.");
    88         distance = (a, b) => distanceMatrix[a, b];
    89       } else {
    90         if (coordinates == null) throw new InvalidOperationException("No coordinates were given.");
    91         var distanceCalculator = DistanceCalculatorParameter.ActualValue;
    92         if (distanceCalculator == null) throw new InvalidOperationException("Distance calculator is null!");
    93         distance = (a, b) => distanceCalculator.Calculate(a, b, coordinates);
    94       }
    95       var relativeQualityDifference = EvaluateMove(permutation, distance, realizations);
     70      var data = ProbabilisticTSPDataParameter.ActualValue;
     71      var relativeQualityDifference = EvaluateMove(permutation, data, realizations);
    9672      var moveQuality = MoveQualityParameter.ActualValue;
    9773      if (moveQuality == null) MoveQualityParameter.ActualValue = new DoubleValue(QualityParameter.ActualValue.Value + relativeQualityDifference);
     
    10076    }
    10177
    102     protected abstract double EvaluateMove(Permutation permutation, Func<int, int, double> distance, ItemList<BoolArray> realizations);
     78    protected abstract double EvaluateMove(Permutation tour, IProbabilisticTSPData data, ReadOnlyItemList<BoolArray> realizations);
    10379  }
    10480}
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Moves/OneShift/PTSPAnalyticalInsertionMoveEvaluator.cs

    r17226 r17253  
    2020#endregion
    2121
    22 using System;
     22using HEAL.Attic;
    2323using HeuristicLab.Common;
    2424using HeuristicLab.Core;
    25 using HeuristicLab.Data;
    2625using HeuristicLab.Encodings.PermutationEncoding;
    2726using HeuristicLab.Parameters;
    28 using HEAL.Attic;
    2927
    3028namespace HeuristicLab.Problems.PTSP {
     
    4947    }
    5048
    51     public static double EvaluateMove(Permutation tour, TranslocationMove move, Func<int, int, double> distance, DoubleArray probabilities) {
     49    public static double EvaluateMove(Permutation tour, TranslocationMove move, IProbabilisticTSPData data) {
    5250      var afterMove = (Permutation)tour.Clone();
    5351      TranslocationManipulator.Apply(afterMove, move.Index1, move.Index1, move.Index3);
    54       return AnalyticalProbabilisticTravelingSalesmanProblem.Evaluate(afterMove, distance, probabilities);
     52      return AnalyticalPTSP.Evaluate(afterMove, data);
    5553    }
    5654
    57     protected override double EvaluateMove(Permutation tour, Func<int, int, double> distance, DoubleArray probabilities) {
    58       return EvaluateMove(tour, TranslocationMoveParameter.ActualValue, distance, probabilities);
     55    protected override double EvaluateMove(Permutation tour, IProbabilisticTSPData data) {
     56      return EvaluateMove(tour, TranslocationMoveParameter.ActualValue, data);
    5957    }
    6058  }
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Moves/OneShift/PTSPEstimatedInsertionMoveEvaluator.cs

    r17226 r17253  
    2121
    2222using System;
     23using System.Collections.Generic;
     24using HEAL.Attic;
    2325using HeuristicLab.Common;
    2426using HeuristicLab.Core;
     
    2628using HeuristicLab.Encodings.PermutationEncoding;
    2729using HeuristicLab.Parameters;
    28 using HEAL.Attic;
    2930
    3031namespace HeuristicLab.Problems.PTSP {
     
    4950    }
    5051
    51     public static double EvaluateMove(Permutation tour, TranslocationMove move, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
     52    public static double EvaluateMove(Permutation tour, TranslocationMove move, IProbabilisticTSPData data, IEnumerable<BoolArray> realizations) {
    5253      var afterMove = (Permutation)tour.Clone();
    5354      TranslocationManipulator.Apply(afterMove, move.Index1, move.Index1, move.Index3);
     
    9394      }
    9495      int[] aPosteriori = new int[12];
     96      var count = 0;
    9597      foreach (var realization in realizations) {
    9698        for (int i = 0; i < edges.Length; i++) {
     
    124126          !(aPosteriori[2] == aPosteriori[4] && aPosteriori[3] == aPosteriori[5])) {
    125127          // compute cost difference between the two a posteriori solutions
    126           moveQuality = moveQuality + distance(aPosteriori[6], aPosteriori[7]) + distance(aPosteriori[8], aPosteriori[9]) + distance(aPosteriori[10], aPosteriori[11]);
    127           moveQuality = moveQuality - distance(aPosteriori[0], aPosteriori[1]) - distance(aPosteriori[2], aPosteriori[3]) - distance(aPosteriori[4], aPosteriori[5]);
     128          moveQuality = moveQuality + data.GetDistance(aPosteriori[6], aPosteriori[7]) + data.GetDistance(aPosteriori[8], aPosteriori[9]) + data.GetDistance(aPosteriori[10], aPosteriori[11]);
     129          moveQuality = moveQuality - data.GetDistance(aPosteriori[0], aPosteriori[1]) - data.GetDistance(aPosteriori[2], aPosteriori[3]) - data.GetDistance(aPosteriori[4], aPosteriori[5]);
    128130        }
    129131        Array.Clear(aPosteriori, 0, aPosteriori.Length);
     132        count++;
    130133      }
    131134      // return average of cost differences
    132       return moveQuality / realizations.Count;
     135      return moveQuality / count;
    133136    }
    134137
     
    149152    }
    150153
    151     protected override double EvaluateMove(Permutation tour, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
    152       return EvaluateMove(tour, TranslocationMoveParameter.ActualValue, distance, realizations);
     154    protected override double EvaluateMove(Permutation tour, IProbabilisticTSPData data, ReadOnlyItemList<BoolArray> realizations) {
     155      return EvaluateMove(tour, TranslocationMoveParameter.ActualValue, data, realizations);
    153156    }
    154157  }
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Moves/TwoOpt/PTSPAnalyticalInversionMoveEvaluator.cs

    r17226 r17253  
    2020#endregion
    2121
    22 using System;
     22using HEAL.Attic;
    2323using HeuristicLab.Common;
    2424using HeuristicLab.Core;
    25 using HeuristicLab.Data;
    2625using HeuristicLab.Encodings.PermutationEncoding;
    2726using HeuristicLab.Parameters;
    28 using HEAL.Attic;
    2927
    3028namespace HeuristicLab.Problems.PTSP {
     
    4947    }
    5048
    51     public static double EvaluateMove(Permutation tour, InversionMove move, Func<int, int, double> distance, DoubleArray probabilities) {
     49    public static double EvaluateMove(Permutation tour, InversionMove move, IProbabilisticTSPData data) {
    5250      var afterMove = (Permutation)tour.Clone();
    5351      InversionManipulator.Apply(afterMove, move.Index1, move.Index2);
    54       return AnalyticalProbabilisticTravelingSalesmanProblem.Evaluate(afterMove, distance, probabilities);
     52      return AnalyticalPTSP.Evaluate(afterMove, data);
    5553    }
    5654
    57     protected override double EvaluateMove(Permutation tour, Func<int, int, double> distance, DoubleArray probabilities) {
    58       return EvaluateMove(tour, InversionMoveParameter.ActualValue, distance, probabilities);
     55    protected override double EvaluateMove(Permutation tour, IProbabilisticTSPData data) {
     56      return EvaluateMove(tour, InversionMoveParameter.ActualValue, data);
    5957    }
    6058  }
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Moves/TwoOpt/PTSPEstimatedInversionMoveEvaluator.cs

    r17226 r17253  
    2121
    2222using System;
     23using System.Collections.Generic;
     24using HEAL.Attic;
    2325using HeuristicLab.Common;
    2426using HeuristicLab.Core;
     
    2628using HeuristicLab.Encodings.PermutationEncoding;
    2729using HeuristicLab.Parameters;
    28 using HEAL.Attic;
    2930
    3031namespace HeuristicLab.Problems.PTSP {
     
    4950    }
    5051
    51     public static double EvaluateMove(Permutation tour, InversionMove move, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
     52    public static double EvaluateMove(Permutation tour, InversionMove move, IProbabilisticTSPData data, IEnumerable<BoolArray> realizations) {
    5253      double moveQuality = 0;
    5354      var edges = new int[4];
     
    6465      if (indices[3] == tour.Length + 1) indices[3] = 0;
    6566      var aPosteriori = new int[4];
     67      var count = 0;
    6668      foreach (var realization in realizations) {
    6769        for (var i = 0; i < edges.Length; i++) {
     
    8789        // compute cost difference between the two a posteriori solutions
    8890        if (!(aPosteriori[0] == aPosteriori[2] && aPosteriori[1] == aPosteriori[3])) {
    89           moveQuality = moveQuality + distance(aPosteriori[0], aPosteriori[2]) + distance(aPosteriori[1], aPosteriori[3])
    90             - distance(aPosteriori[0], aPosteriori[1]) - distance(aPosteriori[2], aPosteriori[3]);
     91          moveQuality = moveQuality + data.GetDistance(aPosteriori[0], aPosteriori[2]) + data.GetDistance(aPosteriori[1], aPosteriori[3])
     92            - data.GetDistance(aPosteriori[0], aPosteriori[1]) - data.GetDistance(aPosteriori[2], aPosteriori[3]);
    9193        }
    9294        Array.Clear(aPosteriori, 0, aPosteriori.Length);
     95        count++;
    9396      }
    9497      // return average of cost differences
    95       return moveQuality / realizations.Count;
     98      return moveQuality / count;
    9699    }
    97100
    98     protected override double EvaluateMove(Permutation tour, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
    99       return EvaluateMove(tour, InversionMoveParameter.ActualValue, distance, realizations);
     101    protected override double EvaluateMove(Permutation tour, IProbabilisticTSPData data, ReadOnlyItemList<BoolArray> realizations) {
     102      return EvaluateMove(tour, InversionMoveParameter.ActualValue, data, realizations);
    100103    }
    101104  }
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/PTSPAnalyticalTwoPointFiveMoveEvaluator.cs

    r17226 r17253  
    2020#endregion
    2121
    22 using System;
     22using HEAL.Attic;
    2323using HeuristicLab.Common;
    2424using HeuristicLab.Core;
    25 using HeuristicLab.Data;
    2625using HeuristicLab.Encodings.PermutationEncoding;
    2726using HeuristicLab.Parameters;
    28 using HEAL.Attic;
    2927
    3028namespace HeuristicLab.Problems.PTSP {
     
    4947    }
    5048
    51     protected override double EvaluateMove(Permutation permutation, Func<int, int, double> distance, DoubleArray probabilities) {
    52       return EvaluateMove(permutation, TwoPointFiveMoveParameter.ActualValue, distance, probabilities);
     49    protected override double EvaluateMove(Permutation permutation, IProbabilisticTSPData data) {
     50      return EvaluateMove(permutation, TwoPointFiveMoveParameter.ActualValue, data);
    5351    }
    5452
    55     public static double EvaluateMove(Permutation permutation, TwoPointFiveMove move, Func<int, int, double> distance, DoubleArray probabilities) {
     53    public static double EvaluateMove(Permutation permutation, TwoPointFiveMove move, IProbabilisticTSPData data) {
    5654      if (move.IsInvert) {
    5755        return PTSPAnalyticalInversionMoveEvaluator.EvaluateMove(permutation,
    58           new InversionMove(move.Index1, move.Index2, move.Permutation), distance, probabilities);
     56          new InversionMove(move.Index1, move.Index2, move.Permutation), data);
    5957      } else {
    6058        return PTSPAnalyticalInsertionMoveEvaluator.EvaluateMove(permutation,
    61           new TranslocationMove(move.Index1, move.Index1, move.Index2), distance, probabilities);
     59          new TranslocationMove(move.Index1, move.Index1, move.Index2), data);
    6260      }
    6361    }
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Moves/TwoPointFiveOpt/PTSPEstimatedTwoPointFiveMoveEvaluator.cs

    r17226 r17253  
    2020#endregion
    2121
    22 using System;
     22using System.Collections.Generic;
     23using HEAL.Attic;
    2324using HeuristicLab.Common;
    2425using HeuristicLab.Core;
     
    2627using HeuristicLab.Encodings.PermutationEncoding;
    2728using HeuristicLab.Parameters;
    28 using HEAL.Attic;
    2929
    3030namespace HeuristicLab.Problems.PTSP {
     
    4949    }
    5050
    51     protected override double EvaluateMove(Permutation permutation, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
    52       return EvaluateMove(permutation, TwoPointFiveMoveParameter.ActualValue, distance, realizations);
     51    protected override double EvaluateMove(Permutation permutation, IProbabilisticTSPData data, ReadOnlyItemList<BoolArray> realizations) {
     52      return EvaluateMove(permutation, TwoPointFiveMoveParameter.ActualValue, data, realizations);
    5353    }
    5454
    55     public static double EvaluateMove(Permutation permutation, TwoPointFiveMove move, Func<int, int, double> distance, ItemList<BoolArray> realizations) {
     55    public static double EvaluateMove(Permutation permutation, TwoPointFiveMove move, IProbabilisticTSPData data, IEnumerable<BoolArray> realizations) {
    5656      if (move.IsInvert) {
    5757        return PTSPEstimatedInversionMoveEvaluator.EvaluateMove(permutation,
    58           new InversionMove(move.Index1, move.Index2, move.Permutation), distance, realizations);
     58          new InversionMove(move.Index1, move.Index2, move.Permutation), data, realizations);
    5959      } else {
    6060        return PTSPEstimatedInsertionMoveEvaluator.EvaluateMove(permutation,
    61           new TranslocationMove(move.Index1, move.Index1, move.Index2), distance, realizations);
     61          new TranslocationMove(move.Index1, move.Index1, move.Index2), data, realizations);
    6262      }
    6363    }
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/PTSP.cs

    r17226 r17253  
    2222using System;
    2323using System.Linq;
    24 using HeuristicLab.Analysis;
     24using HEAL.Attic;
    2525using HeuristicLab.Common;
    2626using HeuristicLab.Core;
     
    2828using HeuristicLab.Encodings.PermutationEncoding;
    2929using HeuristicLab.Optimization;
    30 using HeuristicLab.Optimization.Operators;
    3130using HeuristicLab.Parameters;
    32 using HEAL.Attic;
    3331using HeuristicLab.Problems.Instances;
     32using HeuristicLab.Problems.TravelingSalesman;
     33using HeuristicLab.Random;
    3434
    3535namespace HeuristicLab.Problems.PTSP {
    36   [Item("Probabilistic Traveling Salesman Problem (PTSP)", "Represents a Probabilistic Traveling Salesman Problem.")]
    37   [StorableType("4CB8ACF3-C3D4-4CC6-BB1F-986BDE16B30A")]
    38   public abstract class ProbabilisticTravelingSalesmanProblem : SingleObjectiveBasicProblem<PermutationEncoding>,
    39   IProblemInstanceConsumer<PTSPData> {
     36  [Item("Probabilistic TSP (p-TSP)", "Represents a Probabilistic Traveling Salesman Problem.")]
     37  [StorableType("86041a8c-14e6-46e1-b20f-566892c871f6")]
     38  public abstract class ProbabilisticTSP : PermutationProblem,
     39      IProblemInstanceConsumer<PTSPData> {
    4040    protected bool SuppressEvents { get; set; }
    4141
    42     private static readonly int DistanceMatrixSizeLimit = 1000;
     42    public static int DistanceMatrixSizeLimit = 1000;
    4343
    4444    #region Parameter Properties
    45     public OptionalValueParameter<DoubleMatrix> CoordinatesParameter {
    46       get { return (OptionalValueParameter<DoubleMatrix>)Parameters["Coordinates"]; }
    47     }
    48     public OptionalValueParameter<DistanceCalculator> DistanceCalculatorParameter {
    49       get { return (OptionalValueParameter<DistanceCalculator>)Parameters["DistanceCalculator"]; }
    50     }
    51     public OptionalValueParameter<DistanceMatrix> DistanceMatrixParameter {
    52       get { return (OptionalValueParameter<DistanceMatrix>)Parameters["DistanceMatrix"]; }
    53     }
    54     public IFixedValueParameter<BoolValue> UseDistanceMatrixParameter {
    55       get { return (IFixedValueParameter<BoolValue>)Parameters["UseDistanceMatrix"]; }
    56     }
    57     public OptionalValueParameter<Permutation> BestKnownSolutionParameter {
    58       get { return (OptionalValueParameter<Permutation>)Parameters["BestKnownSolution"]; }
    59     }
    60     public IValueParameter<DoubleArray> ProbabilitiesParameter {
    61       get { return (IValueParameter<DoubleArray>)Parameters["Probabilities"]; }
    62     }
     45    [Storable] public ValueParameter<IProbabilisticTSPData> PTSPDataParameter { get; private set; }
     46    [Storable] public OptionalValueParameter<ITSPSolution> BestKnownSolutionParameter { get; private set; }
    6347    #endregion
    6448
    6549    #region Properties
    66     public DoubleMatrix Coordinates {
    67       get { return CoordinatesParameter.Value; }
    68       set { CoordinatesParameter.Value = value; }
     50    public IProbabilisticTSPData ProbabilisticTSPData {
     51      get { return PTSPDataParameter.Value; }
     52      set { PTSPDataParameter.Value = value; }
    6953    }
    70     public DistanceCalculator DistanceCalculator {
    71       get { return DistanceCalculatorParameter.Value; }
    72       set { DistanceCalculatorParameter.Value = value; }
    73     }
    74     public DistanceMatrix DistanceMatrix {
    75       get { return DistanceMatrixParameter.Value; }
    76       set { DistanceMatrixParameter.Value = value; }
    77     }
    78     public bool UseDistanceMatrix {
    79       get { return UseDistanceMatrixParameter.Value.Value; }
    80       set { UseDistanceMatrixParameter.Value.Value = value; }
    81     }
    82     public Permutation BestKnownSolution {
     54    public ITSPSolution BestKnownSolution {
    8355      get { return BestKnownSolutionParameter.Value; }
    8456      set { BestKnownSolutionParameter.Value = value; }
    8557    }
    86     public DoubleArray Probabilities {
    87       get { return ProbabilitiesParameter.Value; }
    88       set { ProbabilitiesParameter.Value = value; }
    89     }
    90 
    9158    #endregion
    9259
     
    9663
    9764    [StorableConstructor]
    98     protected ProbabilisticTravelingSalesmanProblem(StorableConstructorFlag _) : base(_) { }
    99     protected ProbabilisticTravelingSalesmanProblem(ProbabilisticTravelingSalesmanProblem original, Cloner cloner)
     65    protected ProbabilisticTSP(StorableConstructorFlag _) : base(_) { }
     66    protected ProbabilisticTSP(ProbabilisticTSP original, Cloner cloner)
    10067      : base(original, cloner) {
    101       RegisterEventHandlers();
     68      PTSPDataParameter = cloner.Clone(original.PTSPDataParameter);
     69      BestKnownSolutionParameter = cloner.Clone(original.BestKnownSolutionParameter);
    10270    }
    103     protected ProbabilisticTravelingSalesmanProblem() {
    104       Parameters.Add(new OptionalValueParameter<DoubleMatrix>("Coordinates", "The x- and y-Coordinates of the cities."));
    105       Parameters.Add(new OptionalValueParameter<DistanceCalculator>("DistanceCalculator", "Calculates the distance between two rows in the coordinates matrix."));
    106       Parameters.Add(new OptionalValueParameter<DistanceMatrix>("DistanceMatrix", "The matrix which contains the distances between the cities."));
    107       Parameters.Add(new FixedValueParameter<BoolValue>("UseDistanceMatrix", "True if the coordinates based evaluators should calculate the distance matrix from the coordinates and use it for evaluation similar to the distance matrix evaluator, otherwise false.", new BoolValue(true)));
    108       Parameters.Add(new OptionalValueParameter<Permutation>("BestKnownSolution", "The best known solution of this TSP instance."));
    109       Parameters.Add(new ValueParameter<DoubleArray>("Probabilities", "This list describes for each city the probability of appearing in a realized instance."));
     71    protected ProbabilisticTSP() {
     72      Parameters.Add(PTSPDataParameter = new ValueParameter<IProbabilisticTSPData>("PTSP Data", "The main parameters for the p-TSP."));
     73      Parameters.Add(BestKnownSolutionParameter = new OptionalValueParameter<ITSPSolution>("BestKnownSolution", "The best known solution of this p-TSP instance."));
    11074
    111       var coordinates = new DoubleMatrix(new double[,] {
    112         { 100, 100 }, { 100, 200 }, { 100, 300 }, { 100, 400 },
    113         { 200, 100 }, { 200, 200 }, { 200, 300 }, { 200, 400 },
    114         { 300, 100 }, { 300, 200 }, { 300, 300 }, { 300, 400 },
    115         { 400, 100 }, { 400, 200 }, { 400, 300 }, { 400, 400 }
    116       });
    117       Coordinates = coordinates;
    118       Encoding.Length = coordinates.Rows;
    119       DistanceCalculator = new EuclideanDistance();
    120       DistanceMatrix = new DistanceMatrix(CalculateDistances());
    121       Probabilities = new DoubleArray(Enumerable.Range(0, coordinates.Rows).Select(x => 0.5).ToArray());
    122 
    123       InitializeOperators();
    124       Parameterize();
    125       RegisterEventHandlers();
    126     }
    127 
    128     private void InitializeOperators() {
    129       Operators.Add(new HammingSimilarityCalculator());
    130       Operators.Add(new QualitySimilarityCalculator());
    131       Operators.Add(new PopulationSimilarityAnalyzer(Operators.OfType<ISolutionSimilarityCalculator>()));
    132     }
    133 
    134     [StorableHook(HookType.AfterDeserialization)]
    135     private void AfterDeserialization() {
    136       RegisterEventHandlers();
     75      ProbabilisticTSPData = new MatrixProbabilisticTSPData();
     76      Encoding.Length = ProbabilisticTSPData.Cities;
    13777    }
    13878
    13979    protected override void OnEncodingChanged() {
    14080      base.OnEncodingChanged();
    141       Encoding.Length = Coordinates.Rows;
    142       Parameterize();
     81      Encoding.Length = ProbabilisticTSPData.Cities;
    14382    }
    14483
    145     private void RegisterEventHandlers() {
    146       CoordinatesParameter.ValueChanged += CoordinatesParameterOnValueChanged;
    147       if (Coordinates != null) {
    148         Coordinates.RowsChanged += CoordinatesOnChanged;
    149         Coordinates.ItemChanged += CoordinatesOnChanged;
     84    public override void Analyze(Permutation[] solutions, double[] qualities, ResultCollection results, IRandom random) {
     85      base.Analyze(solutions, qualities, results, random);
     86      var max = Maximization;
     87
     88      var i = !max ? qualities.Select((x, index) => new { index, x }).OrderBy(x => x).First().index
     89                   : qualities.Select((x, index) => new { index, x }).OrderByDescending(x => x).First().index;
     90
     91      if (double.IsNaN(BestKnownQuality) ||
     92          max && qualities[i] > BestKnownQuality ||
     93          !max && qualities[i] < BestKnownQuality) {
     94        BestKnownQuality = qualities[i];
     95        BestKnownSolution = ProbabilisticTSPData.GetSolution((Permutation)solutions[i].Clone(), qualities[i]);
    15096      }
    151       UseDistanceMatrixParameter.Value.ValueChanged += UseDistanceMatrixValueChanged;
    152       DistanceCalculatorParameter.ValueChanged += DistanceCalculatorParameterOnValueChanged;
    153     }
    15497
    155     private void CoordinatesParameterOnValueChanged(object sender, EventArgs eventArgs) {
    156       if (Coordinates != null) {
    157         Coordinates.RowsChanged += CoordinatesOnChanged;
    158         Coordinates.ItemChanged += CoordinatesOnChanged;
    159       }
    160       if (SuppressEvents) return;
    161       UpdateInstance();
    162     }
    163 
    164     private void CoordinatesOnChanged(object sender, EventArgs eventArgs) {
    165       if (SuppressEvents) return;
    166       UpdateInstance();
    167     }
    168 
    169     private void UseDistanceMatrixValueChanged(object sender, EventArgs eventArgs) {
    170       if (SuppressEvents) return;
    171       UpdateInstance();
    172     }
    173 
    174     private void DistanceCalculatorParameterOnValueChanged(object sender, EventArgs eventArgs) {
    175       if (SuppressEvents) return;
    176       UpdateInstance();
    177     }
    178 
    179     public override double Evaluate(Individual individual, IRandom random) {
    180       return Evaluate(individual.Permutation(), random);
    181     }
    182 
    183     public abstract double Evaluate(Permutation tour, IRandom random);
    184 
    185     public double[,] CalculateDistances() {
    186       var coords = Coordinates;
    187       var len = coords.Rows;
    188       var dist = DistanceCalculator;
    189 
    190       var matrix = new double[len, len];
    191       for (var i = 0; i < len - 1; i++)
    192         for (var j = i + 1; j < len; j++)
    193           matrix[i, j] = matrix[j, i] = dist.Calculate(i, j, coords);
    194 
    195       return matrix;
     98      IResult bestSolutionResult;
     99      if (results.TryGetValue("Best p-TSP Solution", out bestSolutionResult)) {
     100        var bestSolution = bestSolutionResult.Value as ITSPSolution;
     101        if (bestSolution == null || Maximization && bestSolution.TourLength.Value < qualities[i]
     102          || !Maximization && bestSolution.TourLength.Value > qualities[i]) {
     103          bestSolutionResult.Value = ProbabilisticTSPData.GetSolution(solutions[i], qualities[i]);
     104        }
     105      } else results.Add(new Result("Best p-TSP Solution", ProbabilisticTSPData.GetSolution(solutions[i], qualities[i])));
    196106    }
    197107
    198108    public virtual void Load(PTSPData data) {
    199       try {
    200         SuppressEvents = true;
    201         if (data.Coordinates == null && data.Distances == null)
    202           throw new System.IO.InvalidDataException("The given instance specifies neither coordinates nor distances!");
    203         if (data.Dimension > DistanceMatrixSizeLimit && (data.Coordinates == null || data.Coordinates.GetLength(0) != data.Dimension || data.Coordinates.GetLength(1) != 2))
    204           throw new System.IO.InvalidDataException("The given instance is too large for using a distance matrix and there is a problem with the coordinates.");
    205         if (data.Coordinates != null && (data.Coordinates.GetLength(0) != data.Dimension || data.Coordinates.GetLength(1) != 2))
    206           throw new System.IO.InvalidDataException("The coordinates of the given instance are not in the right format, there need to be one row for each customer and two columns for the x and y coordinates respectively.");
     109      if (data.Coordinates == null && data.Distances == null)
     110        throw new System.IO.InvalidDataException("The given instance specifies neither coordinates nor distances!");
     111      if (data.Dimension > DistanceMatrixSizeLimit && (data.DistanceMeasure == DistanceMeasure.Att
     112        || data.DistanceMeasure == DistanceMeasure.Manhattan
     113        || data.DistanceMeasure == DistanceMeasure.Maximum))
     114        throw new System.IO.InvalidDataException("The given instance uses an unsupported distance measure and is too large for using a distance matrix.");
     115      if (data.Coordinates != null && data.Coordinates.GetLength(1) != 2)
     116        throw new System.IO.InvalidDataException("The coordinates of the given instance are not in the right format, there need to be one row for each customer and two columns for the x and y coordinates.");
    207117
     118      Encoding.Length = data.Dimension;
     119      Name = data.Name;
     120      Description = data.Description;
     121
     122      if (data.Dimension <= DistanceMatrixSizeLimit) {
     123        ProbabilisticTSPData = new MatrixProbabilisticTSPData(data.Name, data.GetDistanceMatrix(), data.Probabilities, data.Coordinates) { Description = data.Description };
     124      } else if (data.DistanceMeasure == DistanceMeasure.Direct && data.Distances != null) {
     125        ProbabilisticTSPData = new MatrixProbabilisticTSPData(data.Name, data.Distances, data.Probabilities, data.Coordinates) { Description = data.Description };
     126      } else {
    208127        switch (data.DistanceMeasure) {
    209           case DistanceMeasure.Direct:
    210             DistanceCalculator = null;
    211             if (data.Dimension > DistanceMatrixSizeLimit && Coordinates != null) {
    212               DistanceCalculator = new EuclideanDistance();
    213               UseDistanceMatrix = false;
    214             } else UseDistanceMatrix = true;
     128          case DistanceMeasure.Att:
     129            ProbabilisticTSPData = new AttPTSPData(data.Name, data.Coordinates, data.Probabilities) { Description = data.Description };
    215130            break;
    216           case DistanceMeasure.Att: DistanceCalculator = new AttDistance(); break;
    217           case DistanceMeasure.Euclidean: DistanceCalculator = new EuclideanDistance(); break;
    218           case DistanceMeasure.Geo: DistanceCalculator = new GeoDistance(); break;
    219           case DistanceMeasure.Manhattan: DistanceCalculator = new ManhattanDistance(); break;
    220           case DistanceMeasure.Maximum: DistanceCalculator = new MaximumDistance(); break;
    221           case DistanceMeasure.RoundedEuclidean: DistanceCalculator = new RoundedEuclideanDistance(); break;
    222           case DistanceMeasure.UpperEuclidean: DistanceCalculator = new UpperEuclideanDistance(); break;
    223           default: throw new ArgumentException("Distance measure is unknown");
     131          case DistanceMeasure.Euclidean:
     132            ProbabilisticTSPData = new EuclideanPTSPData(data.Name, data.Coordinates, data.Probabilities, EuclideanTSPData.DistanceRounding.None) { Description = data.Description };
     133            break;
     134          case DistanceMeasure.RoundedEuclidean:
     135            ProbabilisticTSPData = new EuclideanPTSPData(data.Name, data.Coordinates, data.Probabilities, EuclideanTSPData.DistanceRounding.Midpoint) { Description = data.Description };
     136            break;
     137          case DistanceMeasure.UpperEuclidean:
     138            ProbabilisticTSPData = new EuclideanPTSPData(data.Name, data.Coordinates, data.Probabilities, EuclideanTSPData.DistanceRounding.Ceiling) { Description = data.Description };
     139            break;
     140          case DistanceMeasure.Geo:
     141            ProbabilisticTSPData = new GeoPTSPData(data.Name, data.Coordinates, data.Probabilities) { Description = data.Description };
     142            break;
     143          case DistanceMeasure.Manhattan:
     144            ProbabilisticTSPData = new ManhattanPTSPData(data.Name, data.Coordinates, data.Probabilities) { Description = data.Description };
     145            break;
     146          case DistanceMeasure.Maximum:
     147            ProbabilisticTSPData = new MaximumPTSPData(data.Name, data.Coordinates, data.Probabilities) { Description = data.Description };
     148            break;
     149          default:
     150            throw new System.IO.InvalidDataException("An unknown distance measure is given in the instance!");
    224151        }
     152      }
     153      BestKnownSolution = null;
     154      BestKnownQuality = double.NaN;
    225155
    226         Name = data.Name;
    227         Description = data.Description;
    228 
    229         Probabilities = new DoubleArray(data.Probabilities);
    230         BestKnownSolution = data.BestKnownTour != null ? new Permutation(PermutationTypes.RelativeUndirected, data.BestKnownTour) : null;
    231         Coordinates = data.Coordinates != null && data.Coordinates.GetLength(0) > 0 ? new DoubleMatrix(data.Coordinates) : null;
    232         DistanceMatrix = data.Dimension <= DistanceMatrixSizeLimit && UseDistanceMatrix ? new DistanceMatrix(data.GetDistanceMatrix()) : null;
    233 
    234         Encoding.Length = data.Dimension;
    235       } finally { SuppressEvents = false; }
     156      if (data.BestKnownTour != null) {
     157        try {
     158          var tour = new Permutation(PermutationTypes.RelativeUndirected, data.BestKnownTour);
     159          var tourLength = Evaluate(tour, new FastRandom(1));
     160          BestKnownSolution = new TSPSolution(data.Coordinates != null ? new DoubleMatrix(data.Coordinates) : null, tour, new DoubleValue(tourLength));
     161          BestKnownQuality = tourLength;
     162        } catch (InvalidOperationException) {
     163          if (data.BestKnownQuality.HasValue)
     164            BestKnownQuality = data.BestKnownQuality.Value;
     165        }
     166      } else if (data.BestKnownQuality.HasValue) {
     167        BestKnownQuality = data.BestKnownQuality.Value;
     168      }
    236169      OnReset();
    237     }
    238 
    239     private void UpdateInstance() {
    240       var len = GetProblemDimension();
    241       if (Coordinates != null && Coordinates.Rows <= DistanceMatrixSizeLimit
    242         && DistanceCalculator != null && UseDistanceMatrix)
    243         DistanceMatrix = new DistanceMatrix(CalculateDistances());
    244       if (!UseDistanceMatrix) DistanceMatrix = null;
    245       Encoding.Length = len;
    246 
    247       OnReset();
    248     }
    249 
    250     private int GetProblemDimension() {
    251       if (Coordinates == null && DistanceMatrix == null) throw new InvalidOperationException("Both coordinates and distance matrix are null, please specify at least one of them.");
    252       return Coordinates != null ? Coordinates.Rows : DistanceMatrix.Rows;
    253     }
    254 
    255     private void Parameterize() {
    256       foreach (var similarityCalculator in Operators.OfType<ISolutionSimilarityCalculator>()) {
    257         similarityCalculator.SolutionVariableName = Encoding.SolutionCreator.PermutationParameter.ActualName;
    258         similarityCalculator.QualityVariableName = Evaluator.QualityParameter.ActualName;
    259       }
    260170    }
    261171  }
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.PTSP/3.3/Plugin.cs.frame

    r17226 r17253  
    3838  [PluginDependency("HeuristicLab.Attic", "1.0")]
    3939  [PluginDependency("HeuristicLab.Problems.Instances", "3.3")]
     40  [PluginDependency("HeuristicLab.Problems.TravelingSalesman", "3.3")]
    4041  [PluginDependency("HeuristicLab.Random", "3.3")]
    4142  public class HeuristicLabProblemsPTSPPlugin : PluginBase {
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.QuadraticAssignment/3.3/QuadraticAssignmentProblem.cs

    r17252 r17253  
    177177    protected override void OnEncodingChanged() {
    178178      base.OnEncodingChanged();
     179      Encoding.Length = Weights.Rows;
    179180      Parameterize();
    180181    }
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.TravelingSalesman/3.3/TSP.cs

    r17251 r17253  
    7272
    7373      TSPData = new EuclideanTSPData();
     74      Encoding.Length = TSPData.Cities;
    7475
    7576      InitializeOperators();
    7677    }
     78
     79    // TODO: encoding length should not be changeable
    7780
    7881    public override IDeepCloneable Clone(Cloner cloner) {
     
    99102        i = qualities.Select((x, index) => new { index, Fitness = x }).OrderBy(x => x.Fitness).First().index;
    100103      else i = qualities.Select((x, index) => new { index, Fitness = x }).OrderByDescending(x => x.Fitness).First().index;
    101       var solution = TSPData.GetSolution(solutions[i], qualities[i]);
    102104
    103105      if (double.IsNaN(BestKnownQuality) ||
    104106          Maximization && qualities[i] > BestKnownQuality ||
    105107          !Maximization && qualities[i] < BestKnownQuality) {
     108        var bestKnown = TSPData.GetSolution(solutions[i], qualities[i]);
    106109        BestKnownQualityParameter.Value = new DoubleValue(qualities[i]);
    107         BestKnownSolutionParameter.Value = solution;
    108       }
    109       results.AddOrUpdateResult("Best TSP Solution", solution);
     110        BestKnownSolutionParameter.Value = bestKnown;
     111      }
     112
     113      IResult bestSolutionResult;
     114      if (results.TryGetValue("Best TSP Solution", out bestSolutionResult)) {
     115        var bestSolution = bestSolutionResult.Value as ITSPSolution;
     116        if (bestSolution == null || Maximization && bestSolution.TourLength.Value < qualities[i]
     117          || !Maximization && bestSolution.TourLength.Value > qualities[i]) {
     118          bestSolutionResult.Value = TSPData.GetSolution(solutions[i], qualities[i]);
     119        }
     120      } else results.Add(new Result("Best TSP Solution", TSPData.GetSolution(solutions[i], qualities[i])));
    110121    }
    111122
     
    132143      Description = data.Description;
    133144
    134       if (data.DistanceMeasure == DistanceMeasure.Att
    135         || data.DistanceMeasure == DistanceMeasure.Manhattan
    136         || data.DistanceMeasure == DistanceMeasure.Maximum
    137         || data.Dimension <= DistanceMatrixSizeLimit) {
     145      if (data.Dimension <= DistanceMatrixSizeLimit) {
    138146        TSPData = new MatrixTSPData(data.Name, data.GetDistanceMatrix(), data.Coordinates) { Description = data.Description };
    139147      } else if (data.DistanceMeasure == DistanceMeasure.Direct && data.Distances != null) {
     
    141149      } else {
    142150        switch (data.DistanceMeasure) {
     151          case DistanceMeasure.Att:
     152            TSPData = new AttTSPData(data.Name, data.Coordinates) { Description = data.Description };
     153            break;
    143154          case DistanceMeasure.Euclidean:
    144155            TSPData = new EuclideanTSPData(data.Name, data.Coordinates, EuclideanTSPData.DistanceRounding.None) { Description = data.Description };
     
    152163          case DistanceMeasure.Geo:
    153164            TSPData = new GeoTSPData(data.Name, data.Coordinates) { Description = data.Description };
     165            break;
     166          case DistanceMeasure.Manhattan:
     167            TSPData = new ManhattanTSPData(data.Name, data.Coordinates) { Description = data.Description };
     168            break;
     169          case DistanceMeasure.Maximum:
     170            TSPData = new MaximumTSPData(data.Name, data.Coordinates) { Description = data.Description };
    154171            break;
    155172          default:
     
    185202    }
    186203
     204
    187205    protected override void OnEncodingChanged() {
    188206      base.OnEncodingChanged();
     207      Encoding.Length = TSPData.Cities;
    189208      ParameterizeOperators();
    190209    }
  • branches/2521_ProblemRefactoring/HeuristicLab.Problems.TravelingSalesman/3.3/TSPData.cs

    r17251 r17253  
    3131  [StorableType("1a9bf60c-b6a6-4c95-8e99-5a2dec0ee892")]
    3232  public interface ITSPData : INamedItem {
     33    int Cities { get; }
     34
    3335    double GetDistance(int fromCity, int toCity);
    3436    ITSPSolution GetSolution(Permutation tspTour, double tourLength);
     
    3840  [Item("Matrix-based TSP Data", "TSP that is representd by a distance matrix.")]
    3941  [StorableType("4df58a35-679d-4414-b815-9450ae100823")]
    40   public sealed class MatrixTSPData : NamedItem, ITSPData {
    41     [Storable] public DoubleMatrix Matrix { get; private set; }
    42     [Storable] public DoubleMatrix DisplayCoordinates { get; private set; }
    43 
    44     [StorableConstructor]
    45     private MatrixTSPData(StorableConstructorFlag _) : base(_) { }
    46     private MatrixTSPData(MatrixTSPData original, Cloner cloner) : base(original, cloner) {
     42  public class MatrixTSPData : NamedItem, ITSPData {
     43    [Storable] public DoubleMatrix Matrix { get; protected set; }
     44    [Storable] public DoubleMatrix DisplayCoordinates { get; protected set; }
     45
     46    public int Cities => Matrix.Rows;
     47
     48    [StorableConstructor]
     49    protected  MatrixTSPData(StorableConstructorFlag _) : base(_) { }
     50    protected MatrixTSPData(MatrixTSPData original, Cloner cloner) : base(original, cloner) {
    4751      Matrix = original.Matrix;
    4852      DisplayCoordinates = original.DisplayCoordinates;
     
    6872        throw new ArgumentException("Unequal number of rows in " + nameof(matrix) + " and " + nameof(coordinates) + ".");
    6973      Name = name;
    70       Matrix = (DoubleMatrix)matrix.AsReadOnly();
    71       DisplayCoordinates = (DoubleMatrix)coordinates?.AsReadOnly();
    72     }
    73 
    74     public ITSPSolution GetSolution(Permutation tour, double tourLength) {
     74      Matrix = matrix.AsReadOnly();
     75      DisplayCoordinates = coordinates?.AsReadOnly();
     76    }
     77
     78    public virtual ITSPSolution GetSolution(Permutation tour, double tourLength) {
    7579      return new TSPSolution(DisplayCoordinates, tour, new DoubleValue(tourLength));
    7680    }
     
    97101  [StorableType("3955d07a-d43c-4a01-9505-d2effb1ea865")]
    98102  public abstract class CoordinatesTSPData : NamedItem, ITSPData {
    99     [Storable] public DoubleMatrix Coordinates { get; private set; }
     103    [Storable] public DoubleMatrix Coordinates { get; protected set; }
     104
     105    public int Cities => Coordinates.Rows;
    100106
    101107    [StorableConstructor]
     
    118124      if (coordinates.Columns != 2) throw new ArgumentException("Argument must have exactly two columns.", nameof(coordinates));
    119125      Name = name;
    120       Coordinates = (DoubleMatrix)coordinates.AsReadOnly();
     126      Coordinates = coordinates.AsReadOnly();
    121127    }
    122128
     
    128134    public abstract double GetDistance(double fromX, double fromY, double toX, double toY);
    129135
    130     public ITSPSolution GetSolution(Permutation tour, double tourLength) {
     136    public virtual ITSPSolution GetSolution(Permutation tour, double tourLength) {
    131137      return new TSPSolution(Coordinates, tour, new DoubleValue(tourLength));
    132138    }
     
    137143  [Item("Euclidean TSP Data", "TSP that is represented by coordinates in an Euclidean plane.")]
    138144  [StorableType("4bf58348-cd98-46c5-a4c0-55f486ca88b4")]
    139   public sealed class EuclideanTSPData : CoordinatesTSPData {
     145  public class EuclideanTSPData : CoordinatesTSPData {
    140146    public enum DistanceRounding { None, Midpoint, Ceiling }
    141147
    142148    [Storable]
    143     public DistanceRounding Rounding { get; private set; }
    144 
    145     [StorableConstructor]
    146     private EuclideanTSPData(StorableConstructorFlag _) : base(_) { }
    147     private EuclideanTSPData(EuclideanTSPData original, Cloner cloner) : base(original, cloner) {
     149    public DistanceRounding Rounding { get; protected set; }
     150
     151    [StorableConstructor]
     152    protected EuclideanTSPData(StorableConstructorFlag _) : base(_) { }
     153    protected EuclideanTSPData(EuclideanTSPData original, Cloner cloner) : base(original, cloner) {
    148154      Rounding = original.Rounding;
    149155    }
     
    166172
    167173    public override double GetDistance(double fromX, double fromY, double toX, double toY) {
    168       var dist = Math.Sqrt((fromX - toX) * (fromX - toX) + (fromY - toY) * (fromY - toY));
     174      var dist = DistanceHelper.EuclideanDistance(fromX, fromY, toX, toY);
    169175      switch (Rounding) {
    170176        case DistanceRounding.None: return dist;
     
    193199  [Item("Geo TSP Data", "TSP that is represented by geo coordinates.")]
    194200  [StorableType("4bf58348-cd98-46c5-a4c0-55f486ca88b4")]
    195   public sealed class GeoTSPData : CoordinatesTSPData {
    196     public const double PI = 3.141592;
    197     public const double RADIUS = 6378.388;
    198 
    199     [StorableConstructor]
    200     private GeoTSPData(StorableConstructorFlag _) : base(_) { }
    201     private GeoTSPData(GeoTSPData original, Cloner cloner) : base(original, cloner) { }
     201  public class GeoTSPData : CoordinatesTSPData {
     202    [StorableConstructor]
     203    protected GeoTSPData(StorableConstructorFlag _) : base(_) { }
     204    protected GeoTSPData(GeoTSPData original, Cloner cloner) : base(original, cloner) { }
    202205    public GeoTSPData() : base() { }
    203206    public GeoTSPData(string name, double[,] coordinates) : base(name, coordinates) { }
     
    209212
    210213    public override double GetDistance(double fromX, double fromY, double toX, double toY) {
    211       double latitude1, longitude1, latitude2, longitude2;
    212       double q1, q2, q3;
    213       double length;
    214 
    215       latitude1 = ConvertToRadian(fromX);
    216       longitude1 = ConvertToRadian(fromY);
    217       latitude2 = ConvertToRadian(toX);
    218       longitude2 = ConvertToRadian(toY);
    219 
    220       q1 = Math.Cos(longitude1 - longitude2);
    221       q2 = Math.Cos(latitude1 - latitude2);
    222       q3 = Math.Cos(latitude1 + latitude2);
    223 
    224       length = (int)(RADIUS * Math.Acos(0.5 * ((1.0 + q1) * q2 - (1.0 - q1) * q3)) + 1.0);
    225       return (length);
    226     }
    227 
    228     private double ConvertToRadian(double x) {
    229       return PI * (Math.Truncate(x) + 5.0 * (x - Math.Truncate(x)) / 3.0) / 180.0;
     214      return DistanceHelper.GeoDistance(fromX, fromY, toX, toY);
    230215    }
    231216
     
    237222        Dimension = Coordinates.Rows,
    238223        DistanceMeasure = DistanceMeasure.Geo
     224      };
     225    }
     226  }
     227
     228  [Item("ATT TSP Data", "TSP that is represented by ATT coordinates.")]
     229  [StorableType("d7a0add3-6ec1-42e0-b1d7-b6454694d485")]
     230  public class AttTSPData : CoordinatesTSPData {
     231    [StorableConstructor]
     232    protected AttTSPData(StorableConstructorFlag _) : base(_) { }
     233    protected AttTSPData(AttTSPData original, Cloner cloner) : base(original, cloner) { }
     234    public AttTSPData() : base() { }
     235    public AttTSPData(string name, double[,] coordinates) : base(name, coordinates) { }
     236    public AttTSPData(string name, DoubleMatrix coordinates) : base(name, coordinates) { }
     237
     238    public override IDeepCloneable Clone(Cloner cloner) {
     239      return new AttTSPData(this, cloner);
     240    }
     241
     242    public override double GetDistance(double fromX, double fromY, double toX, double toY) {
     243      return DistanceHelper.AttDistance(fromX, fromY, toX, toY);
     244    }
     245
     246    public override TSPData Export() {
     247      return new TSPData() {
     248        Name = name,
     249        Description = description,
     250        Coordinates = Coordinates.CloneAsMatrix(),
     251        Dimension = Coordinates.Rows,
     252        DistanceMeasure = DistanceMeasure.Att
     253      };
     254    }
     255  }
     256
     257  [Item("Manhattan TSP Data", "TSP that is represented by Manhattan coordinates.")]
     258  [StorableType("5f1ef9e2-cbd1-400e-8f87-6855f091fc9e")]
     259  public class ManhattanTSPData : CoordinatesTSPData {
     260    [StorableConstructor]
     261    protected ManhattanTSPData(StorableConstructorFlag _) : base(_) { }
     262    protected ManhattanTSPData(ManhattanTSPData original, Cloner cloner) : base(original, cloner) { }
     263    public ManhattanTSPData() : base() { }
     264    public ManhattanTSPData(string name, double[,] coordinates) : base(name, coordinates) { }
     265    public ManhattanTSPData(string name, DoubleMatrix coordinates) : base(name, coordinates) { }
     266
     267    public override IDeepCloneable Clone(Cloner cloner) {
     268      return new ManhattanTSPData(this, cloner);
     269    }
     270
     271    public override double GetDistance(double fromX, double fromY, double toX, double toY) {
     272      return DistanceHelper.ManhattanDistance(fromX, fromY, toX, toY);
     273    }
     274
     275    public override TSPData Export() {
     276      return new TSPData() {
     277        Name = name,
     278        Description = description,
     279        Coordinates = Coordinates.CloneAsMatrix(),
     280        Dimension = Coordinates.Rows,
     281        DistanceMeasure = DistanceMeasure.Manhattan
     282      };
     283    }
     284  }
     285
     286  [Item("Manhattan TSP Data", "TSP that is represented by the maximum absolute distance in either x or y coordinates.")]
     287  [StorableType("c6294a6c-fe62-4906-9765-4bc306d3e4a8")]
     288  public class MaximumTSPData : CoordinatesTSPData {
     289    [StorableConstructor]
     290    protected MaximumTSPData(StorableConstructorFlag _) : base(_) { }
     291    protected MaximumTSPData(MaximumTSPData original, Cloner cloner) : base(original, cloner) { }
     292    public MaximumTSPData() : base() { }
     293    public MaximumTSPData(string name, double[,] coordinates) : base(name, coordinates) { }
     294    public MaximumTSPData(string name, DoubleMatrix coordinates) : base(name, coordinates) { }
     295
     296    public override IDeepCloneable Clone(Cloner cloner) {
     297      return new MaximumTSPData(this, cloner);
     298    }
     299
     300    public override double GetDistance(double fromX, double fromY, double toX, double toY) {
     301      return DistanceHelper.MaximumDistance(fromX, fromY, toX, toY);
     302    }
     303
     304    public override TSPData Export() {
     305      return new TSPData() {
     306        Name = name,
     307        Description = description,
     308        Coordinates = Coordinates.CloneAsMatrix(),
     309        Dimension = Coordinates.Rows,
     310        DistanceMeasure = DistanceMeasure.Maximum
    239311      };
    240312    }
Note: See TracChangeset for help on using the changeset viewer.