cryptominisat 5.8.0

Rust bindings for CryptoMiniSat, a boolean satisfiability solver
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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
/*****************************************************************************
MiniSat -- Copyright (c) 2003-2006, Niklas Een, Niklas Sorensson
CryptoMiniSat -- Copyright (C) 2009-2020 Authors of CryptoMiniSat, see AUTHORS file

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
******************************************************************************/

#ifndef DIMACSPARSER_H
#define DIMACSPARSER_H

#include <string.h>
#include "streambuffer.h"
#include <cstdlib>
#include <cmath>

using namespace CMSat;
using std::vector;

template <class C, class S>
class DimacsParser
{
    public:
        DimacsParser(S* solver, const std::string* debugLib, unsigned _verbosity);

        template <class T> bool parse_DIMACS(
            T input_stream,
            const bool strict_header,
            uint32_t offset_vars = 0);
        uint64_t max_var = std::numeric_limits<uint64_t>::max();
        vector<uint32_t> sampling_vars;
        vector<double> weights;
        const std::string dimacs_spec = "http://www.satcompetition.org/2009/format-benchmarks2009.html";
        const std::string please_read_dimacs = "\nPlease read DIMACS specification at http://www.satcompetition.org/2009/format-benchmarks2009.html";

    private:
        bool parse_DIMACS_main(C& in);
        bool readClause(C& in);
        bool parse_and_add_clause(C& in);
        bool parse_and_add_xor_clause(C& in);
        bool match(C& in, const char* str);
        bool parse_header(C& in);
        bool parseComments(C& in, const std::string& str);
        std::string stringify(uint32_t x) const;

        #ifdef DEBUG_DIMACSPARSER_CMS
        bool parseWeight(C& in);
        bool parse_solve_simp_comment(C& in, const bool solve);
        void write_solution_to_debuglib_file(const lbool ret) const;
        #endif

        bool parseIndependentSet(C& in);
        std::string get_debuglib_fname() const;


        S* solver;
        std::string debugLib;
        unsigned verbosity;
        bool pcnf = false;
        unsigned num_vp = 0; //how many vp's have we seen

        //Stat
        size_t lineNum;

        //Printing partial solutions to debugLibPart1..N.output when "debugLib" is set to TRUE
        uint32_t debugLibPart = 1;

        //check header strictly
        bool strict_header = false;
        bool header_found = false;
        int num_header_vars = 0;
        int num_header_cls = 0;
        uint32_t offset_vars = 0;

        //Reduce temp overhead
        vector<Lit> lits;
        vector<uint32_t> vars;

        size_t norm_clauses_added = 0;
        size_t xor_clauses_added = 0;
};

#include <sstream>
#include <iostream>
#include <iomanip>
#include <vector>
#include <fstream>
#include <complex>
#include <cassert>

using std::vector;
using std::cout;
using std::endl;

template<class C, class S>
DimacsParser<C, S>::DimacsParser(
    S* _solver
    , const std::string* _debugLib
    , unsigned _verbosity
):
    solver(_solver)
    , verbosity(_verbosity)
    , lineNum(0)
{
    if (_debugLib) {
        debugLib = *_debugLib;
    }
}

template<class C, class S>
std::string DimacsParser<C, S>::stringify(uint32_t x) const
{
    std::ostringstream o;
    o << x;
    return o.str();
}

template<class C, class S>
bool DimacsParser<C, S>::readClause(C& in)
{
    int32_t parsed_lit;
    uint32_t var;
    for (;;) {
        if (!in.parseInt(parsed_lit, lineNum)) {
            return false;
        }
        if (parsed_lit == 0) {
            break;
        }

        var = std::abs(parsed_lit)-1;
        var += offset_vars;

        if (var > max_var) {
            std::cerr
            << "ERROR! "
            << "Variable requested is too large for DIMACS parser parameter: "
            << var << endl
            << "--> At line " << lineNum+1
            << please_read_dimacs
            << endl;
            return false;
        }

        if (var >= (1ULL<<28)) {
            std::cerr
            << "ERROR! "
            << "Variable requested is far too large: " << var + 1 << endl
            << "--> At line " << lineNum+1
            << please_read_dimacs
            << endl;
            return false;
        }

        if (strict_header && !header_found) {
            std::cerr
            << "ERROR! "
            << "DIMACS header ('p cnf vars cls') never found!" << endl;
            return false;
        }

        if ((int)var >= num_header_vars && strict_header) {
            std::cerr
            << "ERROR! "
            << "Variable requested is larger than the header told us." << endl
            << " -> var is : " << var + 1 << endl
            << " -> header told us maximum will be : " << num_header_vars << endl
            << " -> At line " << lineNum+1
            << endl;
            return false;
        }

        if (var >= solver->nVars()) {
            assert(!strict_header);
            solver->new_vars(var - solver->nVars() +1);
        }

        lits.push_back( (parsed_lit > 0) ? Lit(var, false) : Lit(var, true) );
        if (*in != ' ') {
            std::cerr
            << "ERROR! "
            << "After last element on the line must be 0" << endl
            << "--> At line " << lineNum+1
            << please_read_dimacs
            << endl
            << endl;
            return false;
        }
    }

    return true;
}

template<class C, class S>
bool DimacsParser<C, S>::match(C& in, const char* str)
{
    for (; *str != 0; ++str, ++in)
        if (*str != *in)
            return false;
    return true;
}

#ifdef DEBUG_DIMACSPARSER_CMS
template<class C, class S>
bool DimacsParser<C, S>::parseWeight(C& in)
{
    if (match(in, "w ")) {
        int32_t slit;
        double weight;
        if (in.parseInt(slit, lineNum)
            && in.parseDouble(weight, lineNum)
        ) {
            if (slit == 0) {
                cout << "ERROR: Cannot define weight of literal 0!" << endl;
                exit(-1);
            }
            uint32_t var = std::abs(slit)-1;
            bool sign = slit < 0;
            Lit lit = Lit(var, sign);
            solver->set_var_weight(lit, weight);
            //cout << "lit: " << lit << " weight: " << std::setprecision(12) << weight << endl;
            if (weight < 0) {
                cout << "ERROR: while definint weight, variable " << var+1 << " has is negative weight: " << weight << " -- line " << lineNum << endl;
                exit(-1);
            }
            return true;
        } else {
            cout << "ERROR: weight is incorrect on line " << lineNum << endl;
            exit(-1);
        }
    } else {
        cout << "ERROR: weight is not given on line " << lineNum << endl;
        exit(-1);
    }
    return true;
}
#endif

template<class C, class S>
bool DimacsParser<C, S>::parse_header(C& in)
{
    ++in;
    in.skipWhitespace();
    std::string str;
    in.parseString(str);
    if (str == "cnf" || str == "pcnf") {
        pcnf = (str == "pcnf");
        if (pcnf && verbosity) {
            cout << "c parsing pcnf" << endl;
        }
        if (header_found && strict_header) {
            std::cerr << "ERROR: CNF header ('p cnf vars cls') found twice in file! Exiting." << endl;
            exit(-1);
        }
        header_found = true;

        if (!in.parseInt(num_header_vars, lineNum)
            || !in.parseInt(num_header_cls, lineNum)
        ) {
            return false;
        }
        if (verbosity) {
            cout << "c -- header says num vars:   " << std::setw(12) << num_header_vars << endl;
            cout << "c -- header says num clauses:" <<  std::setw(12) << num_header_cls << endl;
        }
        if (num_header_vars < 0) {
            std::cerr << "ERROR: Number of variables in header cannot be less than 0" << endl;
            return false;
        }
        if (num_header_cls < 0) {
            std::cerr << "ERROR: Number of clauses in header cannot be less than 0" << endl;
            return false;
        }
        num_header_vars += offset_vars;

        if (solver->nVars() < (size_t)num_header_vars) {
            solver->new_vars(num_header_vars-solver->nVars());
        }
    } else {
        std::cerr
        << "PARSE ERROR! Unexpected char (hex: " << std::hex
        << std::setw(2)
        << std::setfill('0')
        << "0x" << *in
        << std::setfill(' ')
        << std::dec
        << ")"
        << " At line " << lineNum+1
        << "' in the header"
        << please_read_dimacs
        << endl;
        return false;
    }

    return true;
}

template<class C, class S>
std::string DimacsParser<C, S>::get_debuglib_fname() const
{
    std::string sol_fname = debugLib + "-debugLibPart" + stringify(debugLibPart) +".output";
    return sol_fname;
}

#ifdef DEBUG_DIMACSPARSER_CMS
template<class C, class S>
bool DimacsParser<C, S>::parse_solve_simp_comment(C& in, const bool solve)
{
    vector<Lit> assumps;
    in.skipWhitespace();
    while(*in != ')') {
        int lit;
        if (!in.parseInt(lit, lineNum)) {
            return false;
        }
        assumps.push_back(Lit(std::abs(lit)-1, lit < 0));
        in.skipWhitespace();
    }

    if (verbosity) {
        cout
        << "c -----------> Solver::"
        << (solve ? "solve" : "simplify")
        <<" called (number: "
        << std::setw(3) << debugLibPart << ") with assumps :";
        for(Lit lit: assumps) {
            cout << lit << " ";
        }
        cout << "<-----------" << endl;
    }

    lbool ret;
    if (solve) {
        if (verbosity) {
            cout << "c Solution will be written to: "
            << get_debuglib_fname() << endl;
        }
        ret = solver->solve(&assumps);
        write_solution_to_debuglib_file(ret);
        debugLibPart++;
    } else {
        ret = solver->simplify(&assumps);
    }

    if (verbosity >= 6) {
        cout << "c Parsed Solver::"
        << (solve ? "solve" : "simplify")
        << endl;
    }
    return true;
}

template<class C, class S>
void DimacsParser<C, S>::write_solution_to_debuglib_file(const lbool ret) const
{
    //Open file for writing
    std::string s = get_debuglib_fname();
    std::ofstream partFile;
    partFile.open(s.c_str());
    if (!partFile) {
        std::cerr << "ERROR: Cannot open part file '" << s << "'";
        std::exit(-1);
    }

    //Output to part file the result
    if (ret == l_True) {
        partFile << "s SATISFIABLE\n";
        partFile << "v ";
        for (uint32_t i = 0; i != solver->nVars(); i++) {
            if (solver->get_model()[i] != l_Undef)
                partFile
                << ((solver->get_model()[i]==l_True) ? "" : "-")
                << (i+1) <<  " ";
        }
        partFile << "0\n";
    } else if (ret == l_False) {
        partFile << "conflict ";
        for (Lit lit: solver->get_conflict()) {
            partFile << lit << " ";
        }
        partFile
        << "\ns UNSAT\n";
    } else if (ret == l_Undef) {
        cout << "c timeout, exiting" << endl;
        std::exit(15);
    } else {
        assert(false);
    }
    partFile.close();
}
#endif

template<class C, class S>
bool DimacsParser<C, S>::parseComments(C& in, const std::string& str)
{
    #ifdef DEBUG_DIMACSPARSER_CMS
    if (!debugLib.empty() && str.substr(0, 13) == "Solver::solve") {
        if (!parse_solve_simp_comment(in, true)) {
            return false;
        }
    } else if (!debugLib.empty() && str.substr(0, 16) == "Solver::simplify") {
        if (!parse_solve_simp_comment(in, false)) {
            return false;
        }
    } else
    #endif
    if (!debugLib.empty() && str == "Solver::new_var()") {
        solver->new_var();

        if (verbosity >= 6) {
            cout << "c Parsed Solver::new_var()" << endl;
        }
    } else if (!debugLib.empty() && str == "Solver::new_vars(") {
        in.skipWhitespace();
        int n;
        if (!in.parseInt(n, lineNum)) {
            return false;
        }
        solver->new_vars(n);

        if (verbosity >= 6) {
            cout << "c Parsed Solver::new_vars( " << n << " )" << endl;
        }
    } else if (str == "ind") {
        if (pcnf) {
            //nothing
        } else {
            if (!parseIndependentSet(in)) {
                return false;
            }
        }
    } else {
        if (verbosity >= 6) {
            cout
            << "didn't understand in CNF file comment line:"
            << "'c " << str << "'"
            << endl;
        }
    }
    in.skipLine();
    lineNum++;
    return true;
}

template<class C, class S>
bool DimacsParser<C, S>::parse_and_add_clause(C& in)
{
    lits.clear();
    if (!readClause(in)) {
        return false;
    }
    in.skipWhitespace();
    if (!in.skipEOL(lineNum)) {
        return false;
    }
    lineNum++;
    solver->add_clause(lits);
    norm_clauses_added++;
    return true;
}

template<class C, class S>
bool DimacsParser<C, S>::parse_and_add_xor_clause(C& in)
{
    lits.clear();
    if (!readClause(in)) {
        return false;
    }
    if (!in.skipEOL(lineNum)) {
        return false;
    }
    lineNum++;
    if (lits.empty())
        return true;

    bool rhs = true;
    vars.clear();
    for(Lit& lit: lits) {
        vars.push_back(lit.var());
        if (lit.sign()) {
            rhs ^= true;
        }
    }
    solver->add_xor_clause(vars, rhs);
    xor_clauses_added++;
    return true;
}

template<class C, class S>
bool DimacsParser<C, S>::parse_DIMACS_main(C& in)
{
    std::string str;

    for (;;) {
        in.skipWhitespace();
        switch (*in) {
        case EOF:
            return true;
        case 'p':
            if (!parse_header(in)) {
                return false;
            }
            in.skipLine();
            lineNum++;
            break;
        case 'v':
            in.parseString(str);
            assert(str == "vp");
            if (!pcnf) {
                in.skipLine();
            } else {
                if (num_vp == 0) {
                    sampling_vars.clear();
                }
                num_vp++;
                if (!parseIndependentSet(in)) {
                    return false;
                }
            }
            break;

        #ifdef DEBUG_DIMACSPARSER_CMS
        case 'w':
            if (!parseWeight(in)) {
                return false;
            }
            in.skipLine();
            lineNum++;
            break;
        #endif
        case 'c':
            ++in;
            in.parseString(str);
            if (!parseComments(in, str)) {
                return false;
            }
            break;
        case 'x':
            ++in;
            if (!parse_and_add_xor_clause(in)) {
                return false;
            }
            break;
        case '\n':
            if (verbosity) {
                std::cout
                << "c WARNING: Empty line at line number " << lineNum+1
                << " -- this is not part of the DIMACS specifications ("
                << dimacs_spec << "). Ignoring."
                << endl;
            }
            in.skipLine();
            lineNum++;
            break;
        default:
            if (!parse_and_add_clause(in)) {
                return false;
            }
            break;
        }
    }

    return true;
}

template <class C, class S>
template <class T>
bool DimacsParser<C, S>::parse_DIMACS(
    T input_stream,
    const bool _strict_header,
    uint32_t _offset_vars)
{
    debugLibPart = 1;
    strict_header = _strict_header;
    offset_vars = _offset_vars;
    const uint32_t origNumVars = solver->nVars();

    C in(input_stream);
    if ( !parse_DIMACS_main(in)) {
        return false;
    }

    if (verbosity) {
        cout
        << "c -- clauses added: " << norm_clauses_added << endl
        << "c -- xor clauses added: " << xor_clauses_added << endl
        << "c -- vars added " << (solver->nVars() - origNumVars)
        << endl;
    }

    return true;
}

template <class C, class S>
bool DimacsParser<C, S>::parseIndependentSet(C& in)
{
    int32_t parsed_lit;
    for (;;) {
        if (!in.parseInt(parsed_lit, lineNum)) {
            return false;
        }
        if (parsed_lit == 0) {
            break;
        }
        uint32_t var = std::abs(parsed_lit) - 1;
        sampling_vars.push_back(var);
    }
    return true;
}

#endif //DIMACSPARSER_H