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