lemon/dimacs.h
author Alpar Juttner <alpar@cs.elte.hu>
Fri, 28 Nov 2008 06:38:20 +0000
changeset 387 24a2c6ee6cb0
parent 386 9d1faab5e0f1
child 388 0a3ec097a76c
permissions -rw-r--r--
Refactoring of DIMACS tools
alpar@385
     1
/* -*- mode: C++; indent-tabs-mode: nil; -*-
alpar@385
     2
 *
alpar@385
     3
 * This file is a part of LEMON, a generic C++ optimization library.
alpar@385
     4
 *
alpar@385
     5
 * Copyright (C) 2003-2008
alpar@385
     6
 * Egervary Jeno Kombinatorikus Optimalizalasi Kutatocsoport
alpar@385
     7
 * (Egervary Research Group on Combinatorial Optimization, EGRES).
alpar@385
     8
 *
alpar@385
     9
 * Permission to use, modify and distribute this software is granted
alpar@385
    10
 * provided that this copyright notice appears in all copies. For
alpar@385
    11
 * precise terms see the accompanying LICENSE file.
alpar@385
    12
 *
alpar@385
    13
 * This software is provided "AS IS" with no warranty of any kind,
alpar@385
    14
 * express or implied, and with no claim as to its suitability for any
alpar@385
    15
 * purpose.
alpar@385
    16
 *
alpar@385
    17
 */
alpar@385
    18
alpar@385
    19
#ifndef LEMON_DIMACS_H
alpar@385
    20
#define LEMON_DIMACS_H
alpar@385
    21
alpar@385
    22
#include <iostream>
alpar@385
    23
#include <string>
alpar@385
    24
#include <vector>
alpar@385
    25
#include <lemon/maps.h>
alpar@387
    26
#include <lemon/error.h>
alpar@385
    27
alpar@385
    28
/// \ingroup dimacs_group
alpar@385
    29
/// \file
alpar@385
    30
/// \brief DIMACS file format reader.
alpar@385
    31
alpar@385
    32
namespace lemon {
alpar@385
    33
alpar@385
    34
  ///@defgroup dimacs_group DIMACS format
alpar@385
    35
  ///\brief Read and write files in DIMACS format
alpar@385
    36
  ///
alpar@385
    37
  ///Tools to read a digraph from or write it to a file in DIMACS format
alpar@385
    38
  ///data
alpar@385
    39
  ///\ingroup io_group
alpar@385
    40
alpar@385
    41
  /// \addtogroup dimacs_group
alpar@385
    42
  /// @{
alpar@385
    43
alpar@387
    44
alpar@387
    45
  /// DIMACS file type descriptor.
alpar@387
    46
  struct DimacsDescriptor
alpar@387
    47
  {
alpar@387
    48
    ///File type enum
alpar@387
    49
    enum Type
alpar@387
    50
      {
alpar@387
    51
        NONE, MIN, MAX, SP, MAT
alpar@387
    52
      };
alpar@387
    53
    ///The file type
alpar@387
    54
    Type type;
alpar@387
    55
    ///The number of nodes on the graph
alpar@387
    56
    int nodeNum;
alpar@387
    57
    ///The number of edges on the graph
alpar@387
    58
    int edgeNum;
alpar@387
    59
    int lineShift;
alpar@387
    60
    /// Constructor. Sets the type to NONE.
alpar@387
    61
    DimacsDescriptor() : type(NONE) {}
alpar@387
    62
  };
alpar@387
    63
alpar@387
    64
  ///Discover the type of a DIMACS file
alpar@387
    65
alpar@387
    66
  ///It starts seeking the begining of the file for the problem type
alpar@387
    67
  ///and size info. The found date is returned in a special struct
alpar@387
    68
  ///that can be evaluated and passed to the appropriate reader
alpar@387
    69
  ///function.
alpar@387
    70
  DimacsDescriptor dimacsType(std::istream& is)
alpar@387
    71
  {
alpar@387
    72
    DimacsDescriptor r;
alpar@387
    73
    std::string problem,str;
alpar@387
    74
    char c;
alpar@387
    75
    r.lineShift=0;
alpar@387
    76
    while (is >> c)
alpar@387
    77
      switch(c)
alpar@387
    78
        {
alpar@387
    79
        case 'p':
alpar@387
    80
          if(is >> problem >> r.nodeNum >> r.edgeNum)
alpar@387
    81
            {
alpar@387
    82
              getline(is, str);
alpar@387
    83
              r.lineShift++;
alpar@387
    84
              if(problem=="min") r.type=DimacsDescriptor::MIN;
alpar@387
    85
              else if(problem=="max") r.type=DimacsDescriptor::MAX;
alpar@387
    86
              else if(problem=="sp") r.type=DimacsDescriptor::SP;
alpar@387
    87
              else if(problem=="mat") r.type=DimacsDescriptor::MAT;
alpar@387
    88
              else throw FormatError("Unknown problem type");
alpar@387
    89
              return r;
alpar@387
    90
            }
alpar@387
    91
          else
alpar@387
    92
            {
alpar@387
    93
              throw FormatError("Missing or wrong problem type declaration.");
alpar@387
    94
            }
alpar@387
    95
          break;
alpar@387
    96
        case 'c':
alpar@387
    97
          getline(is, str);
alpar@387
    98
          r.lineShift++;
alpar@387
    99
          break;
alpar@387
   100
        default:
alpar@387
   101
          throw FormatError("Unknown DIMACS declaration.");
alpar@387
   102
        }
alpar@387
   103
    throw FormatError("Missing problem type declaration.");
alpar@387
   104
  }
alpar@387
   105
alpar@387
   106
alpar@387
   107
alpar@385
   108
  /// DIMACS min cost flow reader function.
alpar@385
   109
  ///
alpar@385
   110
  /// This function reads a min cost flow instance from DIMACS format,
alpar@385
   111
  /// i.e. from DIMACS files having a line starting with
alpar@385
   112
  /// \code
alpar@385
   113
  ///   p min
alpar@385
   114
  /// \endcode
alpar@387
   115
  /// At the beginning, \c g is cleared by \c g.clear(). The supply
alpar@385
   116
  /// amount of the nodes are written to \c supply (signed). The
alpar@385
   117
  /// lower bounds, capacities and costs of the arcs are written to
alpar@385
   118
  /// \c lower, \c capacity and \c cost.
alpar@387
   119
  ///
alpar@387
   120
  /// If the file type was previously evaluated by dimacsType(), then
alpar@387
   121
  /// the descriptor struct should be given by the \c dest parameter.
alpar@385
   122
  template <typename Digraph, typename LowerMap,
alpar@387
   123
            typename CapacityMap, typename CostMap,
alpar@387
   124
            typename SupplyMap>
alpar@387
   125
  void readDimacsMin(std::istream& is,
alpar@387
   126
                     Digraph &g,
alpar@387
   127
                     LowerMap& lower,
alpar@387
   128
                     CapacityMap& capacity,
alpar@387
   129
                     CostMap& cost,
alpar@387
   130
                     SupplyMap& supply,
alpar@387
   131
                     DimacsDescriptor desc=DimacsDescriptor())
alpar@385
   132
  {
alpar@385
   133
    g.clear();
alpar@385
   134
    std::vector<typename Digraph::Node> nodes;
alpar@385
   135
    typename Digraph::Arc e;
alpar@385
   136
    std::string problem, str;
alpar@385
   137
    char c;
alpar@385
   138
    int i, j;
alpar@387
   139
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
alpar@387
   140
    if(desc.type!=DimacsDescriptor::MIN)
alpar@387
   141
      throw FormatError("Problem type mismatch");
alpar@387
   142
alpar@387
   143
    nodes.resize(desc.nodeNum + 1);
alpar@387
   144
    for (int k = 1; k <= desc.nodeNum; ++k) {
alpar@387
   145
      nodes[k] = g.addNode();
alpar@387
   146
      supply.set(nodes[k], 0);
alpar@387
   147
    }
alpar@387
   148
alpar@385
   149
    typename SupplyMap::Value sup;
alpar@385
   150
    typename CapacityMap::Value low;
alpar@385
   151
    typename CapacityMap::Value cap;
alpar@385
   152
    typename CostMap::Value co;
alpar@385
   153
    while (is >> c) {
alpar@385
   154
      switch (c) {
alpar@385
   155
      case 'c': // comment line
alpar@385
   156
        getline(is, str);
alpar@385
   157
        break;
alpar@385
   158
      case 'n': // node definition line
alpar@385
   159
        is >> i >> sup;
alpar@385
   160
        getline(is, str);
alpar@385
   161
        supply.set(nodes[i], sup);
alpar@385
   162
        break;
alpar@385
   163
      case 'a': // arc (arc) definition line
alpar@385
   164
        is >> i >> j >> low >> cap >> co;
alpar@385
   165
        getline(is, str);
alpar@385
   166
        e = g.addArc(nodes[i], nodes[j]);
alpar@385
   167
        lower.set(e, low);
alpar@385
   168
        if (cap >= 0)
alpar@385
   169
          capacity.set(e, cap);
alpar@385
   170
        else
alpar@385
   171
          capacity.set(e, -1);
alpar@385
   172
        cost.set(e, co);
alpar@385
   173
        break;
alpar@385
   174
      }
alpar@385
   175
    }
alpar@385
   176
  }
alpar@385
   177
alpar@385
   178
  template<typename Digraph, typename CapacityMap>
alpar@387
   179
  void _readDimacs(std::istream& is,
alpar@387
   180
                   Digraph &g,
alpar@387
   181
                   CapacityMap& capacity,
alpar@387
   182
                   typename Digraph::Node &s,
alpar@387
   183
                   typename Digraph::Node &t,
alpar@387
   184
                   DimacsDescriptor desc=DimacsDescriptor()) {
alpar@385
   185
    g.clear();
alpar@387
   186
    s=t=INVALID;
alpar@385
   187
    std::vector<typename Digraph::Node> nodes;
alpar@385
   188
    typename Digraph::Arc e;
alpar@385
   189
    char c, d;
alpar@385
   190
    int i, j;
alpar@385
   191
    typename CapacityMap::Value _cap;
alpar@385
   192
    std::string str;
alpar@387
   193
    nodes.resize(desc.nodeNum + 1);
alpar@387
   194
    for (int k = 1; k <= desc.nodeNum; ++k) {
alpar@387
   195
      nodes[k] = g.addNode();
alpar@387
   196
    }
alpar@387
   197
alpar@385
   198
    while (is >> c) {
alpar@385
   199
      switch (c) {
alpar@385
   200
      case 'c': // comment line
alpar@385
   201
        getline(is, str);
alpar@385
   202
        break;
alpar@385
   203
      case 'n': // node definition line
alpar@387
   204
        if (desc.type==DimacsDescriptor::SP) { // shortest path problem
alpar@385
   205
          is >> i;
alpar@385
   206
          getline(is, str);
alpar@385
   207
          s = nodes[i];
alpar@385
   208
        }
alpar@387
   209
        if (desc.type==DimacsDescriptor::MAX) { // max flow problem
alpar@385
   210
          is >> i >> d;
alpar@385
   211
          getline(is, str);
alpar@385
   212
          if (d == 's') s = nodes[i];
alpar@385
   213
          if (d == 't') t = nodes[i];
alpar@385
   214
        }
alpar@385
   215
        break;
alpar@385
   216
      case 'a': // arc (arc) definition line
alpar@387
   217
        if (desc.type==DimacsDescriptor::SP ||
alpar@387
   218
            desc.type==DimacsDescriptor::MAX) {
alpar@385
   219
          is >> i >> j >> _cap;
alpar@385
   220
          getline(is, str);
alpar@385
   221
          e = g.addArc(nodes[i], nodes[j]);
alpar@385
   222
          capacity.set(e, _cap);
alpar@385
   223
        } else {
alpar@385
   224
          is >> i >> j;
alpar@385
   225
          getline(is, str);
alpar@385
   226
          g.addArc(nodes[i], nodes[j]);
alpar@385
   227
        }
alpar@385
   228
        break;
alpar@385
   229
      }
alpar@385
   230
    }
alpar@385
   231
  }
alpar@385
   232
alpar@387
   233
  /// DIMACS max flow reader function.
alpar@387
   234
  ///
alpar@387
   235
  /// This function reads a max flow instance from DIMACS format,
alpar@387
   236
  /// i.e. from DIMACS files having a line starting with
alpar@387
   237
  /// \code
alpar@387
   238
  ///   p max
alpar@387
   239
  /// \endcode
alpar@387
   240
  /// At the beginning, \c g is cleared by \c g.clear(). The arc
alpar@387
   241
  /// capacities are written to \c capacity and \c s and \c t are
alpar@387
   242
  /// set to the source and the target nodes.
alpar@387
   243
  ///
alpar@387
   244
  /// If the file type was previously evaluated by dimacsType(), then
alpar@387
   245
  /// the descriptor struct should be given by the \c dest parameter.
alpar@387
   246
  template<typename Digraph, typename CapacityMap>
alpar@387
   247
  void readDimacsMax(std::istream& is,
alpar@387
   248
                     Digraph &g,
alpar@387
   249
                     CapacityMap& capacity,
alpar@387
   250
                     typename Digraph::Node &s,
alpar@387
   251
                     typename Digraph::Node &t,
alpar@387
   252
                     DimacsDescriptor desc=DimacsDescriptor()) {
alpar@387
   253
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
alpar@387
   254
    if(desc.type!=DimacsDescriptor::MAX)
alpar@387
   255
      throw FormatError("Problem type mismatch");
alpar@387
   256
    _readDimacs(is,g,capacity,s,t,desc);
alpar@387
   257
  }
alpar@387
   258
alpar@385
   259
  /// DIMACS shortest path reader function.
alpar@385
   260
  ///
alpar@385
   261
  /// This function reads a shortest path instance from DIMACS format,
alpar@385
   262
  /// i.e. from DIMACS files having a line starting with
alpar@385
   263
  /// \code
alpar@385
   264
  ///   p sp
alpar@385
   265
  /// \endcode
alpar@387
   266
  /// At the beginning, \c g is cleared by \c g.clear(). The arc
alpar@387
   267
  /// lengths are written to \c lenght and \c s is set to the
alpar@385
   268
  /// source node.
alpar@387
   269
  ///
alpar@387
   270
  /// If the file type was previously evaluated by dimacsType(), then
alpar@387
   271
  /// the descriptor struct should be given by the \c dest parameter.
alpar@387
   272
  template<typename Digraph, typename LengthMap>
alpar@387
   273
  void readDimacsSp(std::istream& is,
alpar@387
   274
                    Digraph &g,
alpar@387
   275
                    LengthMap& length,
alpar@387
   276
                    typename Digraph::Node &s,
alpar@387
   277
                    DimacsDescriptor desc=DimacsDescriptor()) {
alpar@386
   278
    typename Digraph::Node t;
alpar@387
   279
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
alpar@387
   280
    if(desc.type!=DimacsDescriptor::SP)
alpar@387
   281
      throw FormatError("Problem type mismatch");
alpar@387
   282
    _readDimacs(is, g, length, s, t,desc);
alpar@385
   283
  }
alpar@385
   284
alpar@385
   285
  /// DIMACS capacitated digraph reader function.
alpar@385
   286
  ///
alpar@385
   287
  /// This function reads an arc capacitated digraph instance from
alpar@387
   288
  /// DIMACS 'mat' or 'sp' format.
alpar@387
   289
  /// At the beginning, \c g is cleared by \c g.clear()
alpar@387
   290
  /// and the arc capacities/lengths are written to \c capacity.
alpar@387
   291
  ///
alpar@387
   292
  /// If the file type was previously evaluated by dimacsType(), then
alpar@387
   293
  /// the descriptor struct should be given by the \c dest parameter.
alpar@385
   294
  template<typename Digraph, typename CapacityMap>
alpar@387
   295
  void readDimacsCap(std::istream& is,
alpar@387
   296
                     Digraph &g,
alpar@387
   297
                     CapacityMap& capacity,
alpar@387
   298
                     DimacsDescriptor desc=DimacsDescriptor()) {
alpar@386
   299
    typename Digraph::Node u,v;
alpar@387
   300
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
alpar@387
   301
    if(desc.type!=DimacsDescriptor::MAX || desc.type!=DimacsDescriptor::SP)
alpar@387
   302
      throw FormatError("Problem type mismatch");
alpar@387
   303
    _readDimacs(is, g, capacity, u, v, desc);
alpar@385
   304
  }
alpar@385
   305
alpar@385
   306
  /// DIMACS plain digraph reader function.
alpar@385
   307
  ///
alpar@385
   308
  /// This function reads a digraph without any designated nodes and
alpar@385
   309
  /// maps from DIMACS format, i.e. from DIMACS files having a line
alpar@385
   310
  /// starting with
alpar@385
   311
  /// \code
alpar@385
   312
  ///   p mat
alpar@385
   313
  /// \endcode
alpar@387
   314
  /// At the beginning, \c g is cleared by \c g.clear().
alpar@387
   315
  ///
alpar@387
   316
  /// If the file type was previously evaluated by dimacsType(), then
alpar@387
   317
  /// the descriptor struct should be given by the \c dest parameter.
alpar@385
   318
  template<typename Digraph>
alpar@387
   319
  void readDimacsMat(std::istream& is, Digraph &g,
alpar@387
   320
                     DimacsDescriptor desc=DimacsDescriptor()) {
alpar@386
   321
    typename Digraph::Node u,v;
alpar@385
   322
    NullMap<typename Digraph::Arc, int> n;
alpar@387
   323
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
alpar@387
   324
    if(desc.type!=DimacsDescriptor::MAT)
alpar@387
   325
      throw FormatError("Problem type mismatch");
alpar@387
   326
    _readDimacs(is, g, n, u, v, desc);
alpar@385
   327
  }
alpar@385
   328
alpar@385
   329
  /// DIMACS plain digraph writer function.
alpar@385
   330
  ///
alpar@385
   331
  /// This function writes a digraph without any designated nodes and
alpar@385
   332
  /// maps into DIMACS format, i.e. into DIMACS file having a line
alpar@385
   333
  /// starting with
alpar@385
   334
  /// \code
alpar@385
   335
  ///   p mat
alpar@385
   336
  /// \endcode
alpar@387
   337
  /// If \c comment is not empty, then it will be printed in the first line
alpar@387
   338
  /// prefixed by 'c'.
alpar@385
   339
  template<typename Digraph>
alpar@387
   340
  void writeDimacsMat(std::ostream& os, const Digraph &g,
alpar@387
   341
                      std::string comment="") {
alpar@385
   342
    typedef typename Digraph::NodeIt NodeIt;
alpar@385
   343
    typedef typename Digraph::ArcIt ArcIt;
alpar@385
   344
alpar@387
   345
    if(!comment.empty()) 
alpar@387
   346
      os << "c " << comment << std::endl;
alpar@385
   347
    os << "p mat " << g.nodeNum() << " " << g.arcNum() << std::endl;
alpar@385
   348
alpar@385
   349
    typename Digraph::template NodeMap<int> nodes(g);
alpar@385
   350
    int i = 1;
alpar@385
   351
    for(NodeIt v(g); v != INVALID; ++v) {
alpar@385
   352
      nodes.set(v, i);
alpar@385
   353
      ++i;
alpar@385
   354
    }
alpar@385
   355
    for(ArcIt e(g); e != INVALID; ++e) {
alpar@385
   356
      os << "a " << nodes[g.source(e)] << " " << nodes[g.target(e)]
alpar@385
   357
         << std::endl;
alpar@385
   358
    }
alpar@385
   359
  }
alpar@385
   360
alpar@385
   361
  /// @}
alpar@385
   362
alpar@385
   363
} //namespace lemon
alpar@385
   364
alpar@385
   365
#endif //LEMON_DIMACS_H