Free cookie consent management tool by TermsFeed Policy Generator

Ignore:
Timestamp:
03/15/12 09:11:17 (13 years ago)
Author:
gkronber
Message:

#1081 merged r7462:7609 from trunk into time series branch

Location:
branches/HeuristicLab.TimeSeries
Files:
3 edited

Legend:

Unmodified
Added
Removed
  • branches/HeuristicLab.TimeSeries

  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.QuadraticAssignment

  • branches/HeuristicLab.TimeSeries/HeuristicLab.Problems.QuadraticAssignment/3.3/QuadraticAssignmentProblem.cs

    r7460 r7615  
    2121
    2222using System;
    23 using System.Collections.Generic;
    2423using System.Drawing;
    25 using System.IO;
    2624using System.Linq;
    27 using System.Reflection;
    2825using HeuristicLab.Common;
    2926using HeuristicLab.Core;
     
    3431using HeuristicLab.Persistence.Default.CompositeSerializers.Storable;
    3532using HeuristicLab.PluginInfrastructure;
     33using HeuristicLab.Problems.Instances;
    3634
    3735namespace HeuristicLab.Problems.QuadraticAssignment {
     
    3937  [Creatable("Problems")]
    4038  [StorableClass]
    41   public sealed class QuadraticAssignmentProblem : SingleObjectiveHeuristicOptimizationProblem<IQAPEvaluator, IPermutationCreator>, IStorableContent {
    42     private static string InstancePrefix = "HeuristicLab.Problems.QuadraticAssignment.Data.";
    43 
     39  public sealed class QuadraticAssignmentProblem : SingleObjectiveHeuristicOptimizationProblem<IQAPEvaluator, IPermutationCreator>, IStorableContent,
     40    IProblemInstanceConsumer<QAPData>,
     41    IProblemInstanceConsumer<TSPData> {
    4442    public string Filename { get; set; }
    4543
     
    9189    private QAPPopulationDiversityAnalyzer QAPPopulationDiversityAnalyzer {
    9290      get { return Operators.OfType<QAPPopulationDiversityAnalyzer>().FirstOrDefault(); }
    93     }
    94 
    95     public IEnumerable<string> Instances {
    96       get {
    97         return Assembly.GetExecutingAssembly()
    98           .GetManifestResourceNames()
    99           .Where(x => x.EndsWith(".dat"))
    100           .OrderBy(x => x)
    101           .Select(x => x.Replace(".dat", String.Empty))
    102           .Select(x => x.Replace(InstancePrefix, String.Empty));
    103       }
    10491    }
    10592    #endregion
     
    365352    #endregion
    366353
    367     public void LoadInstanceFromFile(string filename) {
    368       QAPLIBParser parser = new QAPLIBParser();
    369       parser.Parse(filename);
    370       if (parser.Error != null) throw parser.Error;
    371       Distances = new DoubleMatrix(parser.Distances);
    372       Weights = new DoubleMatrix(parser.Weights);
    373       Name = "Quadratic Assignment Problem (imported from " + Path.GetFileNameWithoutExtension(filename) + ")";
    374       Description = "Imported problem data using QAPLIBParser " + Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).Cast<AssemblyFileVersionAttribute>().FirstOrDefault().Version + ".";
     354    public void Load(QAPData data) {
     355      var weights = new DoubleMatrix(data.Weights);
     356      var distances = new DoubleMatrix(data.Distances);
     357      Load(weights, distances);
     358      EvaluateAndLoadAssignment(data.BestKnownAssignment);
     359      OnReset();
     360    }
     361
     362    public void Load(TSPData data) {
     363      if (data.Dimension > 1000)
     364        throw new System.IO.InvalidDataException("Instances with more than 1000 customers are not supported by the QAP.");
     365      var weights = new DoubleMatrix(data.Dimension, data.Dimension);
     366      for (int i = 0; i < data.Dimension; i++)
     367        weights[i, (i + 1) % data.Dimension] = 1;
     368      var distances = new DoubleMatrix(data.GetDistanceMatrix());
     369      Load(weights, distances);
     370      EvaluateAndLoadAssignment(data.BestKnownTour);
     371      OnReset();
     372    }
     373
     374    public void Load(DoubleMatrix weights, DoubleMatrix distances) {
     375      if (weights == null || weights.Rows == 0)
     376        throw new System.IO.InvalidDataException("The given instance does not contain weights!");
     377      if (weights.Rows != weights.Columns)
     378        throw new System.IO.InvalidDataException("The weights matrix is not a square matrix!");
     379      if (distances == null || distances.Rows == 0)
     380        throw new System.IO.InvalidDataException("The given instance does not contain distances!");
     381      if (distances.Rows != distances.Columns)
     382        throw new System.IO.InvalidDataException("The distances matrix is not a square matrix!");
     383      if (weights.Rows != distances.Columns)
     384        throw new System.IO.InvalidDataException("The weights matrix and the distance matrix are not of equal size!");
     385
     386      Weights = weights;
     387      Distances = distances;
     388
    375389      BestKnownQuality = null;
    376390      BestKnownSolution = null;
    377391      BestKnownSolutions = null;
    378       OnReset();
    379     }
    380 
    381     public void LoadInstanceFromFile(string datFilename, string slnFilename) {
    382       QAPLIBParser datParser = new QAPLIBParser();
    383       datParser.Parse(datFilename);
    384       if (datParser.Error != null) throw datParser.Error;
    385       Distances = new DoubleMatrix(datParser.Distances);
    386       Weights = new DoubleMatrix(datParser.Weights);
    387       Name = "Quadratic Assignment Problem (imported from " + Path.GetFileNameWithoutExtension(datFilename) + ")";
    388       Description = "Imported problem data using QAPLIBParser " + Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).Cast<AssemblyFileVersionAttribute>().FirstOrDefault().Version + ".";
    389 
    390       QAPLIBSolutionParser slnParser = new QAPLIBSolutionParser();
    391       slnParser.Parse(slnFilename, true);
    392       if (slnParser.Error != null) throw slnParser.Error;
    393 
    394       BestKnownQuality = new DoubleValue(slnParser.Quality);
    395       BestKnownSolution = new Permutation(PermutationTypes.Absolute, slnParser.Assignment);
    396       BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
    397       BestKnownSolutions.Add((Permutation)BestKnownSolution.Clone());
    398 
    399       if (!BestKnownQuality.Value.IsAlmost(QAPEvaluator.Apply(BestKnownSolution, Weights, Distances))) {
    400         // the solution doesn't result in the given quality, maybe indices and values are inverted
    401         // try parsing again, this time inverting them
    402         slnParser.Reset();
    403         slnParser.Parse(slnFilename, false);
    404         if (slnParser.Error != null) throw slnParser.Error;
    405 
    406         BestKnownQuality = new DoubleValue(slnParser.Quality);
    407         BestKnownSolution = new Permutation(PermutationTypes.Absolute, slnParser.Assignment);
    408         BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
    409         BestKnownSolutions.Add((Permutation)BestKnownSolution.Clone());
    410 
    411         if (!BestKnownQuality.Value.IsAlmost(QAPEvaluator.Apply(BestKnownSolution, Weights, Distances))) {
    412           // if the solution still doesn't result in the given quality, remove it and only take the quality
    413           BestKnownSolution = null;
    414           BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
    415         }
    416       }
    417       OnReset();
    418     }
    419 
    420     public void LoadInstanceFromEmbeddedResource(string instance) {
    421       using (Stream stream = Assembly.GetExecutingAssembly()
    422         .GetManifestResourceStream(InstancePrefix + instance + ".dat")) {
    423         QAPLIBParser datParser = new QAPLIBParser();
    424         datParser.Parse(stream);
    425         if (datParser.Error != null) throw datParser.Error;
    426         Distances = new DoubleMatrix(datParser.Distances);
    427         Weights = new DoubleMatrix(datParser.Weights);
    428         Name = instance;
    429         Description = "Loaded embedded instance " + instance + " of plugin version " + Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(AssemblyFileVersionAttribute), true).Cast<AssemblyFileVersionAttribute>().FirstOrDefault().Version + ".";
    430 
    431         bool solutionExists = Assembly.GetExecutingAssembly()
    432           .GetManifestResourceNames()
    433           .Where(x => x.EndsWith(instance + ".sln"))
    434           .Any();
    435 
    436         if (solutionExists) {
    437           using (Stream solStream = Assembly.GetExecutingAssembly()
    438             .GetManifestResourceStream(InstancePrefix + instance + ".sln")) {
    439             QAPLIBSolutionParser slnParser = new QAPLIBSolutionParser();
    440             slnParser.Parse(solStream, true);
    441             if (slnParser.Error != null) throw slnParser.Error;
    442 
    443             BestKnownQuality = new DoubleValue(slnParser.Quality);
    444             BestKnownSolution = new Permutation(PermutationTypes.Absolute, slnParser.Assignment);
    445             BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
    446             BestKnownSolutions.Add((Permutation)BestKnownSolution.Clone());
    447 
    448             if (!BestKnownQuality.Value.IsAlmost(QAPEvaluator.Apply(BestKnownSolution, Weights, Distances))) {
    449               // the solution doesn't result in the given quality, maybe indices and values are inverted
    450               // try parsing again, this time inverting them
    451               solStream.Seek(0, SeekOrigin.Begin);
    452               slnParser.Reset();
    453               slnParser.Parse(solStream, false);
    454               if (slnParser.Error != null) throw slnParser.Error;
    455 
    456               BestKnownQuality = new DoubleValue(slnParser.Quality);
    457               BestKnownSolution = new Permutation(PermutationTypes.Absolute, slnParser.Assignment);
    458               BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
    459               BestKnownSolutions.Add((Permutation)BestKnownSolution.Clone());
    460 
    461               if (!BestKnownQuality.Value.IsAlmost(QAPEvaluator.Apply(BestKnownSolution, Weights, Distances))) {
    462                 // if the solution still doesn't result in the given quality, remove it and only take the quality
    463                 BestKnownSolution = null;
    464                 BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
    465               }
    466             }
    467           }
    468         } else {  // no solution exists
    469           BestKnownSolution = null;
    470           BestKnownSolutions = new ItemSet<Permutation>(new PermutationEqualityComparer());
    471           BestKnownQuality = null;
    472         }
    473       }
    474       OnReset();
     392    }
     393
     394    public void EvaluateAndLoadAssignment(int[] assignment) {
     395      if (assignment == null || assignment.Length == 0) return;
     396      var vector = new Permutation(PermutationTypes.Absolute, assignment);
     397      var result = QAPEvaluator.Apply(vector, Weights, Distances);
     398      BestKnownQuality = new DoubleValue(result);
     399      BestKnownSolution = vector;
     400      BestKnownSolutions = new ItemSet<Permutation>();
     401      BestKnownSolutions.Add((Permutation)vector.Clone());
    475402    }
    476403  }
Note: See TracChangeset for help on using the changeset viewer.