Hide keyboard shortcuts

Hot-keys on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

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

""" 

An ANF to CNF Converter using a Dense/Sparse Strategy 

 

This converter is based on two converters. The first one, by Martin Albrecht, was based on [CB2007]_, 

this is the basis of the "dense" part of the converter. It was later improved by Mate Soos. The 

second one, by Michael Brickenstein, uses a reduced truth table based approach and forms the 

"sparse" part of the converter. 

 

AUTHORS: 

 

- Martin Albrecht - (2008-09) initial version of 'anf2cnf.py' 

- Michael Brickenstein - (2009) 'cnf.py' for PolyBoRi 

- Mate Soos - (2010) improved version of 'anf2cnf.py' 

- Martin Albrecht - (2012) unified and added to Sage 

 

Classes and Methods 

------------------- 

""" 

 

############################################################################## 

# Copyright (C) 2008-2009 Martin Albrecht <martinralbrecht@googlemail.com> 

# Copyright (C) 2009 Michael Brickenstein <brickenstein@mfo.de> 

# Copyright (C) 2010 Mate Soos 

# Copyright (C) 2012 Martin Albrecht <martinralbrecht@googlemail.com> 

# Distributed under the terms of the GNU General Public License (GPL) 

# The full text of the GPL is available at: 

# http://www.gnu.org/licenses/ 

############################################################################## 

 

from random import Random 

from sage.rings.polynomial.pbori import if_then_else as ite 

from sage.rings.integer_ring import ZZ 

from sage.functions.other import ceil 

from sage.misc.cachefunc import cached_method, cached_function 

from sage.combinat.permutation import Permutations 

from sage.sat.converters import ANF2CNFConverter 

 

import six 

 

 

class CNFEncoder(ANF2CNFConverter): 

""" 

ANF to CNF Converter using a Dense/Sparse Strategy. This converter distinguishes two classes of 

polynomials. 

 

1. Sparse polynomials are those with at most ``max_vars_sparse`` variables. Those are converted 

using reduced truth-tables based on PolyBoRi's internal representation. 

 

2. Polynomials with more variables are converted by introducing new variables for monomials and 

by converting these linearised polynomials. 

 

Linearised polynomials are converted either by splitting XOR chains -- into chunks of length 

``cutting_number`` -- or by constructing XOR clauses if the underlying solver supports it. This 

behaviour is disabled by passing ``use_xor_clauses=False``. 

 

.. automethod:: __init__ 

.. automethod:: __call__ 

""" 

def __init__(self, solver, ring, max_vars_sparse=6, use_xor_clauses=None, cutting_number=6, random_seed=16): 

""" 

Construct ANF to CNF converter over ``ring`` passing clauses to ``solver``. 

 

INPUT: 

 

- ``solver`` - a SAT-solver instance 

 

- ``ring`` - a :class:`sage.rings.polynomial.pbori.BooleanPolynomialRing` 

 

- ``max_vars_sparse`` - maximum number of variables for direct conversion 

 

- ``use_xor_clauses`` - use XOR clauses; if ``None`` use if 

``solver`` supports it. (default: ``None``) 

 

- ``cutting_number`` - maximum length of XOR chains after 

splitting if XOR clauses are not supported (default: 6) 

 

- ``random_seed`` - the direct conversion method uses 

randomness, this sets the seed (default: 16) 

 

EXAMPLES: 

 

We compare the sparse and the dense strategies, sparse first:: 

 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: fn = tmp_filename() 

sage: solver = DIMACS(filename=fn) 

sage: e = CNFEncoder(solver, B) 

sage: e.clauses_sparse(a*b + a + 1) 

sage: _ = solver.write() 

sage: print(open(fn).read()) 

p cnf 3 2 

1 0 

-2 0 

sage: e.phi 

[None, a, b, c] 

 

Now, we convert using the dense strategy:: 

 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: fn = tmp_filename() 

sage: solver = DIMACS(filename=fn) 

sage: e = CNFEncoder(solver, B) 

sage: e.clauses_dense(a*b + a + 1) 

sage: _ = solver.write() 

sage: print(open(fn).read()) 

p cnf 4 5 

1 -4 0 

2 -4 0 

4 -1 -2 0 

-4 -1 0 

4 1 0 

sage: e.phi 

[None, a, b, c, a*b] 

 

.. NOTE:: 

 

This constructor generates SAT variables for each Boolean polynomial variable. 

""" 

self.random_generator = Random(random_seed) 

self.one_set = ring.one().set() 

self.empty_set = ring.zero().set() 

 

self.solver = solver 

self.max_vars_sparse = max_vars_sparse 

self.cutting_number = cutting_number 

 

if use_xor_clauses is None: 

use_xor_clauses = hasattr(solver,"add_xor_clause") 

self.use_xor_clauses = use_xor_clauses 

 

self.ring = ring 

 

# If you change this, make sure we are calling m.index() 

# below, as this relies on phi being sorted like this. 

self._phi = [None] 

for x in sorted([x.lm() for x in self.ring.gens()], key=lambda x: x.index()): 

self.var(x) 

 

def var(self, m=None, decision=None): 

""" 

Return a *new* variable. 

 

This is a thin wrapper around the SAT-solvers function where 

we keep track of which SAT variable corresponds to which 

monomial. 

 

INPUT: 

 

- ``m`` - something the new variables maps to, usually a monomial 

- ``decision`` - is this variable a decision variable? 

 

EXAMPLES:: 

 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: ce = CNFEncoder(DIMACS(), B) 

sage: ce.var() 

4 

""" 

self._phi.append(m) 

return self.solver.var(decision=decision) 

 

@property 

def phi(self): 

""" 

Map SAT variables to polynomial variables. 

 

EXAMPLES:: 

 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: ce = CNFEncoder(DIMACS(), B) 

sage: ce.var() 

4 

sage: ce.phi 

[None, a, b, c, None] 

""" 

return list(self._phi) 

 

################################################## 

# Encoding based on polynomial roots 

################################################## 

 

def zero_blocks(self, f): 

""" 

Divides the zero set of ``f`` into blocks. 

 

EXAMPLES:: 

 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: e = CNFEncoder(DIMACS(), B) 

sage: sorted(e.zero_blocks(a*b*c)) 

[{c: 0}, {b: 0}, {a: 0}] 

 

.. note:: 

 

This function is randomised. 

""" 

variables = f.vars_as_monomial() 

 

space = variables.divisors() 

variables = list(variables.variables()) 

zeros = f.zeros_in(space) 

rest = zeros 

res = list() 

 

def choose(s): 

indices = [] 

assert not s.empty() 

nav = s.navigation() 

while not nav.constant(): 

e = nav.else_branch() 

t = nav.then_branch() 

if e.constant() and not e.terminal_one(): 

indices.append(nav.value()) 

nav = t 

else: 

if self.random_generator.randint(0,1): 

indices.append(nav.value()) 

nav = t 

 

else: 

nav = e 

assert nav.terminal_one() 

res = self.one_set 

for i in reversed(indices): 

res = ite(i, res, self.empty_set) 

return next(iter(res)) 

 

while not rest.empty(): 

l = choose(rest) 

l_variables = set(l.variables()) 

block_dict = dict([(v, 1 if v in l_variables else 0) for v in variables]) 

l = l.set() 

self.random_generator.shuffle(variables) 

for v in variables: 

candidate = l.change(v.index()) 

if candidate.diff(zeros).empty(): 

l = l.union(candidate) 

del block_dict[v] 

rest = rest.diff(l) 

res.append(block_dict) 

return res 

 

def clauses_sparse(self, f): 

""" 

Convert ``f`` using the sparse strategy. 

 

INPUT: 

 

- ``f`` - a :class:`sage.rings.polynomial.pbori.BooleanPolynomial` 

 

 

EXAMPLES:: 

 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: fn = tmp_filename() 

sage: solver = DIMACS(filename=fn) 

sage: e = CNFEncoder(solver, B) 

sage: e.clauses_sparse(a*b + a + 1) 

sage: _ = solver.write() 

sage: print(open(fn).read()) 

p cnf 3 2 

1 0 

-2 0 

sage: e.phi 

[None, a, b, c] 

""" 

# we form an expression for a var configuration *not* lying in 

# the block it is evaluated to 0 by f, iff it is not lying in 

# any zero block of f+1 

 

blocks = self.zero_blocks(f+1) 

C = [dict([(variable, 1-value) for (variable, value) in six.iteritems(b)]) for b in blocks ] 

 

def to_dimacs_index(v): 

return v.index()+1 

 

def clause(c): 

return [to_dimacs_index(variable) if value == 1 else -to_dimacs_index(variable) for (variable, value) in six.iteritems(c)] 

 

for c in C: 

self.solver.add_clause(clause(c)) 

 

################################################### 

# Indirect conversion, may add new variables 

################################################### 

 

def clauses_dense(self, f): 

""" 

Convert ``f`` using the dense strategy. 

 

INPUT: 

 

- ``f`` - a :class:`sage.rings.polynomial.pbori.BooleanPolynomial` 

 

EXAMPLES:: 

 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: fn = tmp_filename() 

sage: solver = DIMACS(filename=fn) 

sage: e = CNFEncoder(solver, B) 

sage: e.clauses_dense(a*b + a + 1) 

sage: _ = solver.write() 

sage: print(open(fn).read()) 

p cnf 4 5 

1 -4 0 

2 -4 0 

4 -1 -2 0 

-4 -1 0 

4 1 0 

sage: e.phi 

[None, a, b, c, a*b] 

""" 

equal_zero = not bool(f.constant_coefficient()) 

 

f = (f - f.constant_coefficient()) 

f = [self.monomial(m) for m in f] 

 

if self.use_xor_clauses: 

self.solver.add_xor_clause(f, rhs=not equal_zero) 

elif f > self.cutting_number: 

for fpart, this_equal_zero in self.split_xor(f, equal_zero): 

ll = len(fpart) 

for p in self.permutations(ll, this_equal_zero): 

self.solver.add_clause([ p[i]*fpart[i] for i in range(ll) ]) 

else: 

ll = len(f) 

for p in self.permutations(ll, equal_zero): 

self.solver.add_clause([ p[i]*f[i] for i in range(ll) ]) 

 

@cached_method 

def monomial(self, m): 

""" 

Return SAT variable for ``m`` 

 

INPUT: 

 

- ``m`` - a monomial. 

 

OUTPUT: An index for a SAT variable corresponding to ``m``. 

 

EXAMPLES:: 

 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: fn = tmp_filename() 

sage: solver = DIMACS(filename=fn) 

sage: e = CNFEncoder(solver, B) 

sage: e.clauses_dense(a*b + a + 1) 

sage: e.phi 

[None, a, b, c, a*b] 

 

If monomial is called on a new monomial, a new variable is created:: 

 

sage: e.monomial(a*b*c) 

5 

sage: e.phi 

[None, a, b, c, a*b, a*b*c] 

 

If monomial is called on a monomial that was queried before, 

the index of the old variable is returned and no new variable 

is created:: 

 

sage: e.monomial(a*b) 

4 

sage: e.phi 

[None, a, b, c, a*b, a*b*c] 

 

.. note:: 

 

For correctness, this function is cached. 

""" 

if m.deg() == 1: 

return m.index()+1 

else: 

# we need to encode the relationship between the monomial 

# and its variables 

variables = [self.monomial(v) for v in m.variables()] 

monomial = self.var(m) 

 

# (a | -w) & (b | -w) & (w | -a | -b) <=> w == a*b 

for v in variables: 

self.solver.add_clause( (v, -monomial) ) 

self.solver.add_clause( tuple([monomial] + [-v for v in variables]) ) 

 

return monomial 

 

@cached_function 

def permutations(length, equal_zero): 

""" 

Return permutations of length ``length`` which are equal to 

zero if ``equal_zero`` and equal to one otherwise. 

 

A variable is false if the integer in its position is smaller 

than zero and true otherwise. 

 

INPUT: 

 

- ``length`` - the number of variables 

- ``equal_zero`` - should the sum be equal to zero? 

 

EXAMPLES:: 

 

 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: ce = CNFEncoder(DIMACS(), B) 

sage: ce.permutations(3, True) 

[[-1, -1, -1], [1, 1, -1], [1, -1, 1], [-1, 1, 1]] 

 

sage: ce.permutations(3, False) 

[[1, -1, -1], [-1, 1, -1], [-1, -1, 1], [1, 1, 1]] 

""" 

E = [] 

for num_negated in range(0, length+1) : 

if (((num_negated % 2) ^ ((length+1) % 2)) == equal_zero) : 

continue 

start = [] 

for i in range(num_negated) : 

start.append(1) 

for i in range(length - num_negated) : 

start.append(-1) 

E.extend(Permutations(start)) 

return E 

 

def split_xor(self, monomial_list, equal_zero): 

""" 

Split XOR chains into subchains. 

 

INPUT: 

 

- ``monomial_list`` - a list of monomials 

- ``equal_zero`` - is the constant coefficient zero? 

 

EXAMPLES:: 

 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: B.<a,b,c,d,e,f> = BooleanPolynomialRing() 

sage: ce = CNFEncoder(DIMACS(), B, cutting_number=3) 

sage: ce.split_xor([1,2,3,4,5,6], False) 

[[[1, 7], False], [[7, 2, 8], True], [[8, 3, 9], True], [[9, 4, 10], True], [[10, 5, 11], True], [[11, 6], True]] 

 

sage: ce = CNFEncoder(DIMACS(), B, cutting_number=4) 

sage: ce.split_xor([1,2,3,4,5,6], False) 

[[[1, 2, 7], False], [[7, 3, 4, 8], True], [[8, 5, 6], True]] 

 

sage: ce = CNFEncoder(DIMACS(), B, cutting_number=5) 

sage: ce.split_xor([1,2,3,4,5,6], False) 

[[[1, 2, 3, 7], False], [[7, 4, 5, 6], True]] 

""" 

c = self.cutting_number 

 

nm = len(monomial_list) 

step = ceil((c-2)/ZZ(nm) * nm) 

M = [] 

 

new_variables = [] 

for j in range(0, nm, step): 

m = new_variables + monomial_list[j:j+step] 

if (j + step) < nm: 

new_variables = [self.var(None)] 

m += new_variables 

M.append([m, equal_zero]) 

equal_zero = True 

return M 

 

################################################### 

# Highlevel Functions 

################################################### 

 

def clauses(self, f): 

""" 

Convert ``f`` using the sparse strategy if ``f.nvariables()`` is 

at most ``max_vars_sparse`` and the dense strategy otherwise. 

 

INPUT: 

 

- ``f`` - a :class:`sage.rings.polynomial.pbori.BooleanPolynomial` 

 

EXAMPLES:: 

 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: fn = tmp_filename() 

sage: solver = DIMACS(filename=fn) 

sage: e = CNFEncoder(solver, B, max_vars_sparse=2) 

sage: e.clauses(a*b + a + 1) 

sage: _ = solver.write() 

sage: print(open(fn).read()) 

p cnf 3 2 

1 0 

-2 0 

sage: e.phi 

[None, a, b, c] 

 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: fn = tmp_filename() 

sage: solver = DIMACS(filename=fn) 

sage: e = CNFEncoder(solver, B, max_vars_sparse=2) 

sage: e.clauses(a*b + a + c) 

sage: _ = solver.write() 

sage: print(open(fn).read()) 

p cnf 4 7 

1 -4 0 

2 -4 0 

4 -1 -2 0 

-4 -1 -3 0 

4 1 -3 0 

4 -1 3 0 

-4 1 3 0 

 

sage: e.phi 

[None, a, b, c, a*b] 

""" 

if f.nvariables() <= self.max_vars_sparse: 

self.clauses_sparse(f) 

else: 

self.clauses_dense(f) 

 

def __call__(self, F): 

""" 

Encode the boolean polynomials in ``F`` . 

 

INPUT: 

 

- ``F`` - an iterable of :class:`sage.rings.polynomial.pbori.BooleanPolynomial` 

 

OUTPUT: An inverse map int -> variable 

 

 

EXAMPLES:: 

 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: fn = tmp_filename() 

sage: solver = DIMACS(filename=fn) 

sage: e = CNFEncoder(solver, B, max_vars_sparse=2) 

sage: e([a*b + a + 1, a*b+ a + c]) 

[None, a, b, c, a*b] 

sage: _ = solver.write() 

sage: print(open(fn).read()) 

p cnf 4 9 

1 0 

-2 0 

1 -4 0 

2 -4 0 

4 -1 -2 0 

-4 -1 -3 0 

4 1 -3 0 

4 -1 3 0 

-4 1 3 0 

 

sage: e.phi 

[None, a, b, c, a*b] 

""" 

res = [] 

for f in F: 

self.clauses(f) 

return self.phi 

 

#################################################### 

# Highlevel Functions 

################################################### 

 

def to_polynomial(self, c): 

""" 

Convert clause to :class:`sage.rings.polynomial.pbori.BooleanPolynomial` 

 

INPUT: 

 

- ``c`` - a clause 

 

EXAMPLES:: 

 

sage: B.<a,b,c> = BooleanPolynomialRing() 

sage: from sage.sat.converters.polybori import CNFEncoder 

sage: from sage.sat.solvers.dimacs import DIMACS 

sage: fn = tmp_filename() 

sage: solver = DIMACS(filename=fn) 

sage: e = CNFEncoder(solver, B, max_vars_sparse=2) 

sage: _ = e([a*b + a + 1, a*b+ a + c]) 

sage: e.to_polynomial( (1,-2,3) ) 

a*b*c + a*b + b*c + b 

""" 

def product(l): 

# order of these multiplications for performance 

res = l[0] 

for p in l[1:]: 

res = res*p 

return res 

 

phi = self.phi 

product = self.ring(1) 

for v in c: 

if phi[abs(v)] is None: 

raise ValueError("clause contains an XOR glueing variable") 

product *= phi[abs(v)] + int(v>0) 

return product