1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
// Copyright (c) 2015, 2016, 2017 Frank Fischer <frank-fischer@shadow-soft.de>
//
// This program 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.
//
// This program 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 this program.  If not, see  <http://www.gnu.org/licenses/>
//

//! This module implements a read function for the famous DIMACS max
//! flow format. A DIMACS file must look as follows.
//!
//! 1. empty lines are allowed and ignored
//! 2. a line starting with `c` is a comment line and is ignored
//! 3. the first non-comment line must have the form `p max <n> <m>`,
//!    where `<n>` is an integer > 0 denoting the number of nodes and
//!    `<m>` an integer > 0 denoting the number of arcs.
//! 4. after the problem line there must follow exactly two node lines
//!    of the form `n <node> <type>` where `<node>` is the node number
//!    between `1..n` and `<type>` is either `s` (if this is the source
//!    node) or `t` (if this is the sink node).
//! 5. after the node lines there must be exactly `m` arc lines `a <u>
//!    <v> <c>` denoting the source and sink nodes of an arc as well as
//!    the arcs capacity `<c>` (an integer >= 0).

use crate::builder::{Buildable, Builder};
use crate::traits::IndexGraph;

use super::{read_dimacs, DimacsError};

use crate::num::traits::FromPrimitive;

use std::fs;
use std::io;

/// A maxflow instance.
pub struct Instance<G, F, N>
where
    G: for<'a> IndexGraph<'a, Node = N>,
{
    /// The graph.
    pub graph: G,
    /// The source node.
    pub src: N,
    /// The sink node.
    pub snk: N,
    /// The upper bounds.
    pub upper: Vec<F>,
}

impl<G, F, N> Instance<G, F, N>
where
    G: for<'a> IndexGraph<'a, Node = N> + Buildable,
    F: FromPrimitive,
    N: Copy + Eq,
{
    /// Read DIMACS file and return instance.
    ///
    /// - `fname` is the name of the file to be read
    pub fn read(fname: &str) -> Result<Self, DimacsError> {
        let f = fs::File::open(fname)?;
        Instance::read_from_buf(&mut io::BufReader::new(f))
    }

    /// Read DIMACS file from a buffered reader and return instance.
    ///
    /// - `buf` the buffer with the file content
    pub fn read_from_buf<R>(buf: &mut R) -> Result<Self, DimacsError>
    where
        R: io::BufRead,
    {
        let mut graph = G::Builder::new();
        let mut nnodes = 0;
        let mut nedges = 0;
        let mut src = None;
        let mut snk = None;
        let mut upper = vec![];

        enum State {
            Prob,
            SrcSnk,
            Arcs,
        };
        let mut state = State::Prob;
        let mut nodes = vec![];

        read_dimacs(buf, &mut |d, toks| match state {
            State::Prob => {
                if d != 'p' {
                    return Err(DimacsError::Format {
                        line: toks.line,
                        msg: format!("expected problem line starting with 'p', got: {}", d),
                    });
                }
                let max = toks.next().unwrap_or("end of line");
                if max != "max" {
                    return Err(DimacsError::Format {
                        line: toks.line,
                        msg: format!("expected 'max' in p line, got: {}", max),
                    });
                }
                nnodes = toks.number()?;
                nedges = toks.number()?;
                toks.end()?;

                nodes = graph.add_nodes(nnodes);
                upper.extend((0..nedges).map(|_| F::from_usize(0).unwrap()));

                state = State::SrcSnk;
                Ok(())
            }
            State::SrcSnk => {
                if d != 'n' {
                    return Err(DimacsError::Format {
                        line: toks.line,
                        msg: format!("expected node line starting with 'n', got: {}", d),
                    });
                }

                let u: usize = toks.number()?;
                let what = toks.str()?;
                toks.end()?;

                if u < 1 || u > nnodes {
                    return Err(DimacsError::Data {
                        line: toks.line,
                        msg: format!("invalid node id {} (must be <= {})", u, nnodes),
                    });
                }

                match what {
                    "s" => {
                        if src.is_some() {
                            return Err(DimacsError::Format {
                                line: toks.line,
                                msg: "duplicate source node".to_string(),
                            });
                        }
                        src = Some(u);
                    }
                    "t" => {
                        if snk.is_some() {
                            return Err(DimacsError::Format {
                                line: toks.line,
                                msg: "duplicate sink node".to_string(),
                            });
                        }
                        snk = Some(u);
                    }
                    _ => {
                        return Err(DimacsError::Format {
                            line: toks.line,
                            msg: format!("invalid node type, must be 's' or 't', got: {}", what),
                        });
                    }
                }

                if src.is_some() && snk.is_some() {
                    state = State::Arcs;
                }
                Ok(())
            }
            State::Arcs => {
                if d != 'a' {
                    return Err(DimacsError::Format {
                        line: toks.line,
                        msg: format!("expected arc line starting with 'a', got: {}", d),
                    });
                }
                let u: usize = toks.number()?;
                let v: usize = toks.number()?;
                let c: usize = toks.number()?;
                if u < 1 || u > nnodes {
                    return Err(DimacsError::Data {
                        line: toks.line,
                        msg: format!("invalid source node id {} (must be <= {})", u, nnodes),
                    });
                }
                if v < 1 || v > nnodes {
                    return Err(DimacsError::Data {
                        line: toks.line,
                        msg: format!("invalid sink node id {} (must be <= {})", v, nnodes),
                    });
                }
                if u == v {
                    return Err(DimacsError::Data {
                        line: toks.line,
                        msg: format!("invalid loop ({},{}) in edge", u, u),
                    });
                }
                let e = graph.add_edge(nodes[u - 1], nodes[v - 1]);
                upper[graph.edge2id(e)] = F::from_usize(c).unwrap();
                Ok(())
            }
        })?;

        let src = graph.node2id(src.map(|s| nodes[s - 1]).ok_or_else(|| DimacsError::Format {
            line: 0,
            msg: "missing source node".to_string(),
        })?);
        let snk = graph.node2id(snk.map(|t| nodes[t - 1]).ok_or_else(|| DimacsError::Format {
            line: 0,
            msg: "missing sink node".to_string(),
        })?);

        let graph = graph.to_graph();
        let src = graph.id2node(src);
        let snk = graph.id2node(snk);

        Ok(Instance { graph, src, snk, upper })
    }
}

#[cfg(test)]
mod tests {

    use crate::dimacs::maxflow::Instance;
    use crate::{traits::*, LinkedListGraph};
    use std::io;

    #[test]
    fn parse_file_test() {
        let file = "c this is a test file

p max 6 9
n 5 s
n 6 t

c there might be empty lines

a 5 1 10
a 5 2 10
a 1 2 2
a 1 3 4
a 1 4 8
a 2 4 9
a 3 6 10
a 4 3 6
a 4 6 10

c end of the file
";
        let instance = Instance::read_from_buf(&mut io::Cursor::new(file)).unwrap();

        let g: LinkedListGraph = instance.graph;
        let src = instance.src;
        let snk = instance.snk;
        let upper = instance.upper;

        assert_eq!(g.num_nodes(), 6);
        assert_eq!(g.num_edges(), 9);
        assert_eq!(g.node_id(src), 4);
        assert_eq!(g.node_id(snk), 5);

        let mut arcs: Vec<_> = g
            .edges()
            .map(|e| (g.node_id(g.src(e)) + 1, g.node_id(g.snk(e)) + 1, upper[g.edge_id(e)]))
            .collect();

        arcs.sort();

        assert_eq!(
            arcs,
            vec![
                (1, 2, 2),
                (1, 3, 4),
                (1, 4, 8),
                (2, 4, 9),
                (3, 6, 10),
                (4, 3, 6),
                (4, 6, 10),
                (5, 1, 10),
                (5, 2, 10),
            ]
        );
    }

}