lemon/dimacs.h
author Peter Kovacs <kpeter@inf.elte.hu>
Fri, 08 Sep 2017 17:02:03 +0200
changeset 1005 f37f0845cf32
parent 561 6e0525ec5355
child 1006 332627dd249e
permissions -rw-r--r--
Bug fix in DIMACS reader (#607)
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@440
     5
 * Copyright (C) 2003-2009
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@561
    25
#include <limits>
alpar@385
    26
#include <lemon/maps.h>
alpar@387
    27
#include <lemon/error.h>
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
  /// \addtogroup dimacs_group
alpar@385
    35
  /// @{
alpar@385
    36
alpar@387
    37
  /// DIMACS file type descriptor.
alpar@387
    38
  struct DimacsDescriptor
alpar@387
    39
  {
alpar@387
    40
    ///File type enum
alpar@387
    41
    enum Type
alpar@387
    42
      {
alpar@387
    43
        NONE, MIN, MAX, SP, MAT
alpar@387
    44
      };
alpar@387
    45
    ///The file type
alpar@387
    46
    Type type;
kpeter@388
    47
    ///The number of nodes in the graph
alpar@387
    48
    int nodeNum;
kpeter@388
    49
    ///The number of edges in the graph
alpar@387
    50
    int edgeNum;
alpar@387
    51
    int lineShift;
alpar@387
    52
    /// Constructor. Sets the type to NONE.
alpar@387
    53
    DimacsDescriptor() : type(NONE) {}
alpar@387
    54
  };
alpar@387
    55
alpar@387
    56
  ///Discover the type of a DIMACS file
alpar@387
    57
alpar@561
    58
  ///It starts seeking the beginning of the file for the problem type
kpeter@388
    59
  ///and size info. The found data is returned in a special struct
alpar@387
    60
  ///that can be evaluated and passed to the appropriate reader
alpar@387
    61
  ///function.
alpar@387
    62
  DimacsDescriptor dimacsType(std::istream& is)
alpar@387
    63
  {
alpar@387
    64
    DimacsDescriptor r;
alpar@387
    65
    std::string problem,str;
alpar@387
    66
    char c;
alpar@387
    67
    r.lineShift=0;
alpar@387
    68
    while (is >> c)
alpar@387
    69
      switch(c)
alpar@387
    70
        {
alpar@387
    71
        case 'p':
alpar@387
    72
          if(is >> problem >> r.nodeNum >> r.edgeNum)
alpar@387
    73
            {
alpar@387
    74
              getline(is, str);
alpar@387
    75
              r.lineShift++;
alpar@387
    76
              if(problem=="min") r.type=DimacsDescriptor::MIN;
alpar@387
    77
              else if(problem=="max") r.type=DimacsDescriptor::MAX;
alpar@387
    78
              else if(problem=="sp") r.type=DimacsDescriptor::SP;
alpar@387
    79
              else if(problem=="mat") r.type=DimacsDescriptor::MAT;
alpar@387
    80
              else throw FormatError("Unknown problem type");
alpar@387
    81
              return r;
alpar@387
    82
            }
alpar@387
    83
          else
alpar@387
    84
            {
alpar@387
    85
              throw FormatError("Missing or wrong problem type declaration.");
alpar@387
    86
            }
alpar@387
    87
          break;
alpar@387
    88
        case 'c':
alpar@387
    89
          getline(is, str);
alpar@387
    90
          r.lineShift++;
alpar@387
    91
          break;
alpar@387
    92
        default:
alpar@387
    93
          throw FormatError("Unknown DIMACS declaration.");
alpar@387
    94
        }
alpar@387
    95
    throw FormatError("Missing problem type declaration.");
alpar@387
    96
  }
alpar@387
    97
alpar@387
    98
alpar@387
    99
kpeter@388
   100
  /// DIMACS minimum cost flow reader function.
alpar@385
   101
  ///
kpeter@388
   102
  /// This function reads a minimum cost flow instance from DIMACS format,
kpeter@388
   103
  /// i.e. from a DIMACS file having a line starting with
alpar@385
   104
  /// \code
alpar@385
   105
  ///   p min
alpar@385
   106
  /// \endcode
alpar@387
   107
  /// At the beginning, \c g is cleared by \c g.clear(). The supply
alpar@561
   108
  /// amount of the nodes are written to the \c supply node map
alpar@561
   109
  /// (they are signed values). The lower bounds, capacities and costs
alpar@561
   110
  /// of the arcs are written to the \c lower, \c capacity and \c cost
alpar@561
   111
  /// arc maps.
alpar@561
   112
  ///
alpar@561
   113
  /// If the capacity of an arc is less than the lower bound, it will
alpar@561
   114
  /// be set to "infinite" instead. The actual value of "infinite" is
alpar@561
   115
  /// contolled by the \c infty parameter. If it is 0 (the default value),
alpar@561
   116
  /// \c std::numeric_limits<Capacity>::infinity() will be used if available,
alpar@561
   117
  /// \c std::numeric_limits<Capacity>::max() otherwise. If \c infty is set to
alpar@561
   118
  /// a non-zero value, that value will be used as "infinite".
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@561
   131
                     typename CapacityMap::Value infty = 0,
alpar@387
   132
                     DimacsDescriptor desc=DimacsDescriptor())
alpar@385
   133
  {
alpar@385
   134
    g.clear();
alpar@385
   135
    std::vector<typename Digraph::Node> nodes;
alpar@385
   136
    typename Digraph::Arc e;
alpar@385
   137
    std::string problem, str;
alpar@385
   138
    char c;
alpar@385
   139
    int i, j;
alpar@387
   140
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
alpar@387
   141
    if(desc.type!=DimacsDescriptor::MIN)
alpar@387
   142
      throw FormatError("Problem type mismatch");
alpar@387
   143
alpar@387
   144
    nodes.resize(desc.nodeNum + 1);
alpar@387
   145
    for (int k = 1; k <= desc.nodeNum; ++k) {
alpar@387
   146
      nodes[k] = g.addNode();
alpar@387
   147
      supply.set(nodes[k], 0);
alpar@387
   148
    }
alpar@387
   149
alpar@385
   150
    typename SupplyMap::Value sup;
alpar@385
   151
    typename CapacityMap::Value low;
alpar@385
   152
    typename CapacityMap::Value cap;
alpar@385
   153
    typename CostMap::Value co;
alpar@561
   154
    typedef typename CapacityMap::Value Capacity;
alpar@561
   155
    if(infty==0)
alpar@561
   156
      infty = std::numeric_limits<Capacity>::has_infinity ?
alpar@561
   157
        std::numeric_limits<Capacity>::infinity() :
alpar@561
   158
        std::numeric_limits<Capacity>::max();
alpar@561
   159
alpar@385
   160
    while (is >> c) {
alpar@385
   161
      switch (c) {
alpar@385
   162
      case 'c': // comment line
alpar@385
   163
        getline(is, str);
alpar@385
   164
        break;
alpar@385
   165
      case 'n': // node definition line
alpar@385
   166
        is >> i >> sup;
alpar@385
   167
        getline(is, str);
alpar@385
   168
        supply.set(nodes[i], sup);
alpar@385
   169
        break;
alpar@561
   170
      case 'a': // arc definition line
alpar@385
   171
        is >> i >> j >> low >> cap >> co;
alpar@385
   172
        getline(is, str);
alpar@385
   173
        e = g.addArc(nodes[i], nodes[j]);
alpar@385
   174
        lower.set(e, low);
alpar@561
   175
        if (cap >= low)
alpar@385
   176
          capacity.set(e, cap);
alpar@385
   177
        else
alpar@561
   178
          capacity.set(e, infty);
alpar@385
   179
        cost.set(e, co);
alpar@385
   180
        break;
alpar@385
   181
      }
alpar@385
   182
    }
alpar@385
   183
  }
alpar@385
   184
alpar@385
   185
  template<typename Digraph, typename CapacityMap>
alpar@387
   186
  void _readDimacs(std::istream& is,
alpar@387
   187
                   Digraph &g,
alpar@387
   188
                   CapacityMap& capacity,
alpar@387
   189
                   typename Digraph::Node &s,
alpar@387
   190
                   typename Digraph::Node &t,
alpar@561
   191
                   typename CapacityMap::Value infty = 0,
alpar@387
   192
                   DimacsDescriptor desc=DimacsDescriptor()) {
alpar@385
   193
    g.clear();
alpar@387
   194
    s=t=INVALID;
alpar@385
   195
    std::vector<typename Digraph::Node> nodes;
alpar@385
   196
    typename Digraph::Arc e;
alpar@385
   197
    char c, d;
alpar@385
   198
    int i, j;
alpar@385
   199
    typename CapacityMap::Value _cap;
alpar@385
   200
    std::string str;
alpar@387
   201
    nodes.resize(desc.nodeNum + 1);
alpar@387
   202
    for (int k = 1; k <= desc.nodeNum; ++k) {
alpar@387
   203
      nodes[k] = g.addNode();
alpar@387
   204
    }
alpar@561
   205
    typedef typename CapacityMap::Value Capacity;
alpar@387
   206
alpar@561
   207
    if(infty==0)
alpar@561
   208
      infty = std::numeric_limits<Capacity>::has_infinity ?
alpar@561
   209
        std::numeric_limits<Capacity>::infinity() :
alpar@561
   210
        std::numeric_limits<Capacity>::max();
alpar@561
   211
 
alpar@385
   212
    while (is >> c) {
alpar@385
   213
      switch (c) {
alpar@385
   214
      case 'c': // comment line
alpar@385
   215
        getline(is, str);
alpar@385
   216
        break;
alpar@385
   217
      case 'n': // node definition line
alpar@387
   218
        if (desc.type==DimacsDescriptor::SP) { // shortest path problem
alpar@385
   219
          is >> i;
alpar@385
   220
          getline(is, str);
alpar@385
   221
          s = nodes[i];
alpar@385
   222
        }
alpar@387
   223
        if (desc.type==DimacsDescriptor::MAX) { // max flow problem
alpar@385
   224
          is >> i >> d;
alpar@385
   225
          getline(is, str);
alpar@385
   226
          if (d == 's') s = nodes[i];
alpar@385
   227
          if (d == 't') t = nodes[i];
alpar@385
   228
        }
alpar@385
   229
        break;
alpar@561
   230
      case 'a': // arc definition line
alpar@561
   231
        if (desc.type==DimacsDescriptor::SP) {
alpar@385
   232
          is >> i >> j >> _cap;
alpar@385
   233
          getline(is, str);
alpar@385
   234
          e = g.addArc(nodes[i], nodes[j]);
alpar@385
   235
          capacity.set(e, _cap);
alpar@561
   236
        } 
alpar@561
   237
        else if (desc.type==DimacsDescriptor::MAX) {
alpar@561
   238
          is >> i >> j >> _cap;
alpar@561
   239
          getline(is, str);
alpar@561
   240
          e = g.addArc(nodes[i], nodes[j]);
alpar@561
   241
          if (_cap >= 0)
alpar@561
   242
            capacity.set(e, _cap);
alpar@561
   243
          else
alpar@561
   244
            capacity.set(e, infty);
alpar@561
   245
        }
alpar@561
   246
        else {
alpar@385
   247
          is >> i >> j;
alpar@385
   248
          getline(is, str);
alpar@385
   249
          g.addArc(nodes[i], nodes[j]);
alpar@385
   250
        }
alpar@385
   251
        break;
alpar@385
   252
      }
alpar@385
   253
    }
alpar@385
   254
  }
alpar@385
   255
kpeter@388
   256
  /// DIMACS maximum flow reader function.
alpar@387
   257
  ///
kpeter@388
   258
  /// This function reads a maximum flow instance from DIMACS format,
kpeter@388
   259
  /// i.e. from a DIMACS file having a line starting with
alpar@387
   260
  /// \code
alpar@387
   261
  ///   p max
alpar@387
   262
  /// \endcode
alpar@387
   263
  /// At the beginning, \c g is cleared by \c g.clear(). The arc
alpar@561
   264
  /// capacities are written to the \c capacity arc map and \c s and
alpar@561
   265
  /// \c t are set to the source and the target nodes.
alpar@561
   266
  ///
alpar@561
   267
  /// If the capacity of an arc is negative, it will
alpar@561
   268
  /// be set to "infinite" instead. The actual value of "infinite" is
alpar@561
   269
  /// contolled by the \c infty parameter. If it is 0 (the default value),
alpar@561
   270
  /// \c std::numeric_limits<Capacity>::infinity() will be used if available,
alpar@561
   271
  /// \c std::numeric_limits<Capacity>::max() otherwise. If \c infty is set to
alpar@561
   272
  /// a non-zero value, that value will be used as "infinite".
alpar@387
   273
  ///
alpar@387
   274
  /// If the file type was previously evaluated by dimacsType(), then
alpar@387
   275
  /// the descriptor struct should be given by the \c dest parameter.
alpar@387
   276
  template<typename Digraph, typename CapacityMap>
alpar@387
   277
  void readDimacsMax(std::istream& is,
alpar@387
   278
                     Digraph &g,
alpar@387
   279
                     CapacityMap& capacity,
alpar@387
   280
                     typename Digraph::Node &s,
alpar@387
   281
                     typename Digraph::Node &t,
alpar@561
   282
                     typename CapacityMap::Value infty = 0,
alpar@387
   283
                     DimacsDescriptor desc=DimacsDescriptor()) {
alpar@387
   284
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
alpar@387
   285
    if(desc.type!=DimacsDescriptor::MAX)
alpar@387
   286
      throw FormatError("Problem type mismatch");
alpar@561
   287
    _readDimacs(is,g,capacity,s,t,infty,desc);
alpar@387
   288
  }
alpar@387
   289
alpar@385
   290
  /// DIMACS shortest path reader function.
alpar@385
   291
  ///
alpar@385
   292
  /// This function reads a shortest path instance from DIMACS format,
kpeter@388
   293
  /// i.e. from a DIMACS file having a line starting with
alpar@385
   294
  /// \code
alpar@385
   295
  ///   p sp
alpar@385
   296
  /// \endcode
alpar@387
   297
  /// At the beginning, \c g is cleared by \c g.clear(). The arc
alpar@561
   298
  /// lengths are written to the \c length arc map and \c s is set to the
alpar@385
   299
  /// source node.
alpar@387
   300
  ///
alpar@387
   301
  /// If the file type was previously evaluated by dimacsType(), then
alpar@387
   302
  /// the descriptor struct should be given by the \c dest parameter.
alpar@387
   303
  template<typename Digraph, typename LengthMap>
alpar@387
   304
  void readDimacsSp(std::istream& is,
alpar@387
   305
                    Digraph &g,
alpar@387
   306
                    LengthMap& length,
alpar@387
   307
                    typename Digraph::Node &s,
alpar@387
   308
                    DimacsDescriptor desc=DimacsDescriptor()) {
alpar@386
   309
    typename Digraph::Node t;
alpar@387
   310
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
alpar@387
   311
    if(desc.type!=DimacsDescriptor::SP)
alpar@387
   312
      throw FormatError("Problem type mismatch");
alpar@561
   313
    _readDimacs(is, g, length, s, t, 0, desc);
alpar@385
   314
  }
alpar@385
   315
alpar@385
   316
  /// DIMACS capacitated digraph reader function.
alpar@385
   317
  ///
alpar@385
   318
  /// This function reads an arc capacitated digraph instance from
alpar@561
   319
  /// DIMACS 'max' or 'sp' format.
alpar@387
   320
  /// At the beginning, \c g is cleared by \c g.clear()
alpar@561
   321
  /// and the arc capacities/lengths are written to the \c capacity
alpar@561
   322
  /// arc map.
alpar@561
   323
  ///
alpar@561
   324
  /// In case of the 'max' format, if the capacity of an arc is negative,
alpar@561
   325
  /// it will
alpar@561
   326
  /// be set to "infinite" instead. The actual value of "infinite" is
alpar@561
   327
  /// contolled by the \c infty parameter. If it is 0 (the default value),
alpar@561
   328
  /// \c std::numeric_limits<Capacity>::infinity() will be used if available,
alpar@561
   329
  /// \c std::numeric_limits<Capacity>::max() otherwise. If \c infty is set to
alpar@561
   330
  /// a non-zero value, that value will be used as "infinite".
alpar@387
   331
  ///
alpar@387
   332
  /// If the file type was previously evaluated by dimacsType(), then
alpar@387
   333
  /// the descriptor struct should be given by the \c dest parameter.
alpar@385
   334
  template<typename Digraph, typename CapacityMap>
alpar@387
   335
  void readDimacsCap(std::istream& is,
alpar@387
   336
                     Digraph &g,
alpar@387
   337
                     CapacityMap& capacity,
alpar@561
   338
                     typename CapacityMap::Value infty = 0,
alpar@387
   339
                     DimacsDescriptor desc=DimacsDescriptor()) {
alpar@386
   340
    typename Digraph::Node u,v;
alpar@387
   341
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
kpeter@1005
   342
    if(desc.type!=DimacsDescriptor::MAX && desc.type!=DimacsDescriptor::SP)
alpar@387
   343
      throw FormatError("Problem type mismatch");
alpar@561
   344
    _readDimacs(is, g, capacity, u, v, infty, desc);
alpar@385
   345
  }
alpar@385
   346
alpar@525
   347
  template<typename Graph>
alpar@525
   348
  typename enable_if<lemon::UndirectedTagIndicator<Graph>,void>::type
alpar@525
   349
  _addArcEdge(Graph &g, typename Graph::Node s, typename Graph::Node t,
alpar@525
   350
              dummy<0> = 0)
alpar@525
   351
  {
alpar@525
   352
    g.addEdge(s,t);
alpar@525
   353
  }
alpar@525
   354
  template<typename Graph>
alpar@525
   355
  typename disable_if<lemon::UndirectedTagIndicator<Graph>,void>::type
alpar@525
   356
  _addArcEdge(Graph &g, typename Graph::Node s, typename Graph::Node t,
alpar@525
   357
              dummy<1> = 1)
alpar@525
   358
  {
alpar@525
   359
    g.addArc(s,t);
alpar@525
   360
  }
alpar@525
   361
  
alpar@525
   362
  /// DIMACS plain (di)graph reader function.
alpar@385
   363
  ///
alpar@525
   364
  /// This function reads a (di)graph without any designated nodes and
alpar@385
   365
  /// maps from DIMACS format, i.e. from DIMACS files having a line
alpar@385
   366
  /// starting with
alpar@385
   367
  /// \code
alpar@385
   368
  ///   p mat
alpar@385
   369
  /// \endcode
alpar@387
   370
  /// At the beginning, \c g is cleared by \c g.clear().
alpar@387
   371
  ///
alpar@387
   372
  /// If the file type was previously evaluated by dimacsType(), then
alpar@387
   373
  /// the descriptor struct should be given by the \c dest parameter.
alpar@525
   374
  template<typename Graph>
alpar@525
   375
  void readDimacsMat(std::istream& is, Graph &g,
alpar@525
   376
                     DimacsDescriptor desc=DimacsDescriptor())
alpar@525
   377
  {
alpar@387
   378
    if(desc.type==DimacsDescriptor::NONE) desc=dimacsType(is);
alpar@387
   379
    if(desc.type!=DimacsDescriptor::MAT)
alpar@387
   380
      throw FormatError("Problem type mismatch");
alpar@525
   381
alpar@525
   382
    g.clear();
alpar@525
   383
    std::vector<typename Graph::Node> nodes;
alpar@525
   384
    char c;
alpar@525
   385
    int i, j;
alpar@525
   386
    std::string str;
alpar@525
   387
    nodes.resize(desc.nodeNum + 1);
alpar@525
   388
    for (int k = 1; k <= desc.nodeNum; ++k) {
alpar@525
   389
      nodes[k] = g.addNode();
alpar@525
   390
    }
alpar@525
   391
    
alpar@525
   392
    while (is >> c) {
alpar@525
   393
      switch (c) {
alpar@525
   394
      case 'c': // comment line
alpar@525
   395
        getline(is, str);
alpar@525
   396
        break;
alpar@525
   397
      case 'n': // node definition line
alpar@525
   398
        break;
alpar@561
   399
      case 'a': // arc definition line
alpar@525
   400
        is >> i >> j;
alpar@525
   401
        getline(is, str);
alpar@525
   402
        _addArcEdge(g,nodes[i], nodes[j]);
alpar@525
   403
        break;
alpar@525
   404
      }
alpar@525
   405
    }
alpar@385
   406
  }
alpar@385
   407
alpar@385
   408
  /// DIMACS plain digraph writer function.
alpar@385
   409
  ///
alpar@385
   410
  /// This function writes a digraph without any designated nodes and
alpar@385
   411
  /// maps into DIMACS format, i.e. into DIMACS file having a line
alpar@385
   412
  /// starting with
alpar@385
   413
  /// \code
alpar@385
   414
  ///   p mat
alpar@385
   415
  /// \endcode
alpar@387
   416
  /// If \c comment is not empty, then it will be printed in the first line
alpar@387
   417
  /// prefixed by 'c'.
alpar@385
   418
  template<typename Digraph>
alpar@387
   419
  void writeDimacsMat(std::ostream& os, const Digraph &g,
alpar@387
   420
                      std::string comment="") {
alpar@385
   421
    typedef typename Digraph::NodeIt NodeIt;
alpar@385
   422
    typedef typename Digraph::ArcIt ArcIt;
alpar@385
   423
alpar@440
   424
    if(!comment.empty())
alpar@387
   425
      os << "c " << comment << std::endl;
alpar@385
   426
    os << "p mat " << g.nodeNum() << " " << g.arcNum() << std::endl;
alpar@385
   427
alpar@385
   428
    typename Digraph::template NodeMap<int> nodes(g);
alpar@385
   429
    int i = 1;
alpar@385
   430
    for(NodeIt v(g); v != INVALID; ++v) {
alpar@385
   431
      nodes.set(v, i);
alpar@385
   432
      ++i;
alpar@385
   433
    }
alpar@385
   434
    for(ArcIt e(g); e != INVALID; ++e) {
alpar@385
   435
      os << "a " << nodes[g.source(e)] << " " << nodes[g.target(e)]
alpar@385
   436
         << std::endl;
alpar@385
   437
    }
alpar@385
   438
  }
alpar@385
   439
alpar@385
   440
  /// @}
alpar@385
   441
alpar@385
   442
} //namespace lemon
alpar@385
   443
alpar@385
   444
#endif //LEMON_DIMACS_H