#region License Information
/* HeuristicLab
* Copyright (C) 2002-2012 Heuristic and Evolutionary Algorithms Laboratory (HEAL)
*
* This file is part of HeuristicLab.
*
* HeuristicLab is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* HeuristicLab is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with HeuristicLab. If not, see .
*/
#endregion
using System;
using System.IO;
namespace HeuristicLab.Problems.QuadraticAssignment {
public class QAPLIBParser {
public int Size { get; private set; }
public double[,] Distances { get; private set; }
public double[,] Weights { get; private set; }
public Exception Error { get; private set; }
public QAPLIBParser() {
Reset();
}
public void Reset() {
Size = 0;
Distances = null;
Weights = null;
Error = null;
}
public bool Parse(string file) {
using (Stream stream = new FileStream(file, FileMode.Open, FileAccess.Read)) {
return Parse(stream);
}
}
///
/// Reads from the given stream data which is expected to be in the QAPLIB format.
///
///
/// The stream is not closed or disposed. The caller has to take care of that.
///
/// The stream to read data from.
/// True if the file was successfully read or false otherwise.
public bool Parse(Stream stream) {
Error = null;
try {
StreamReader reader = new StreamReader(stream);
Size = int.Parse(reader.ReadLine());
Distances = new double[Size, Size];
Weights = new double[Size, Size];
string valLine = null;
char[] delim = new char[] { ' ' };
int read = 0;
int k = 0;
while (k < Size) {
if (reader.EndOfStream) throw new InvalidDataException("Reached end of stream while reading first matrix.");
valLine = reader.ReadLine();
while (String.IsNullOrWhiteSpace(valLine)) valLine = reader.ReadLine();
string[] vals = valLine.Split(delim, StringSplitOptions.RemoveEmptyEntries);
foreach (string val in vals) {
Weights[k, read++] = double.Parse(val);
if (read == Size) {
read = 0;
k++;
}
}
}
read = 0;
k = 0;
while (k < Size) {
if (reader.EndOfStream) throw new InvalidDataException("Reached end of stream while reading second matrix.");
valLine = reader.ReadLine();
while (String.IsNullOrWhiteSpace(valLine)) valLine = reader.ReadLine();
string[] vals = valLine.Split(delim, StringSplitOptions.RemoveEmptyEntries);
foreach (string val in vals) {
Distances[k, read++] = double.Parse(val);
if (read == Size) {
read = 0;
k++;
}
}
}
return true;
} catch (Exception e) {
Error = e;
return false;
}
}
}
}