1 | using System;
|
---|
2 | using System.IO;
|
---|
3 |
|
---|
4 | namespace 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 | }
|
---|