Free cookie consent management tool by TermsFeed Policy Generator

source: branches/QAP/HeuristicLab.Problems.QuadraticAssignment/3.3/Parsers/QAPLIBSolutionParser.cs @ 5648

Last change on this file since 5648 was 5648, checked in by abeham, 12 years ago

#1330

  • Unified QAP visualization in solution and problem view
  • Fixed bug in gradient-descent gradient calculation when performing multidimensional scaling
  • Extended QAPLIB parsers to cover some file format variations
  • Added unit tests to check if all QAPLIB instances import without error
  • Changed BestKnownSolution to be an OptionalValueParameter
File size: 2.0 KB
Line 
1using System;
2using System.IO;
3
4namespace HeuristicLab.Problems.QuadraticAssignment {
5  public class QAPLIBSolutionParser {
6    public int Size { get; private set; }
7    public int[] Assignment { get; private set; }
8    public double Qualiy { get; private set; }
9    public Exception Error { get; private set; }
10
11    public QAPLIBSolutionParser() {
12      Reset();
13    }
14
15    public void Reset() {
16      Size = 0;
17      Assignment = null;
18      Qualiy = double.NaN;
19      Error = null;
20    }
21
22    public bool Parse(string file) {
23      using (Stream stream = new FileStream(file, FileMode.Open, FileAccess.Read)) {
24        return Parse(stream);
25      }
26    }
27
28    /// <summary>
29    /// Reads from the given stream data which is expected to be in the QAPLIB format.
30    /// </summary>
31    /// <remarks>
32    /// The stream is not closed or disposed. The caller has to take care of that.
33    /// </remarks>
34    /// <param name="stream">The stream to read data from.</param>
35    /// <returns>True if the file was successfully read or false otherwise.</returns>
36    public bool Parse(Stream stream) {
37      Error = null;
38      try {
39        StreamReader reader = new StreamReader(stream);
40        char[] delim = new char[] { ' ', ',' }; // comma is added for nug30.sln which is the only file that separates the permutation with commas
41        string[] firstline = reader.ReadLine().Split(delim, StringSplitOptions.RemoveEmptyEntries);
42        Size = int.Parse(firstline[0]);
43        Qualiy = double.Parse(firstline[1]);
44        Assignment = new int[Size];
45        int read = 0;
46        while (!reader.EndOfStream) {
47          string valLine = reader.ReadLine();
48          string[] vals = valLine.Split(delim, StringSplitOptions.RemoveEmptyEntries);
49          for (int j = 0; j < vals.Length; j++) {
50            Assignment[read++] = int.Parse(vals[j]);
51          }
52        }
53        return true;
54      } catch (Exception e) {
55        Error = e;
56        return false;
57      }
58    }
59  }
60}
Note: See TracBrowser for help on using the repository browser.