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

619

620

621

622

623

624

625

626

627

628

629

630

631

632

633

634

635

636

637

638

639

640

641

642

643

644

645

646

647

648

649

650

651

652

653

654

655

656

657

658

659

660

661

662

663

664

665

666

667

668

669

670

671

672

673

674

675

676

677

678

679

680

681

682

683

684

685

686

687

688

689

690

691

692

693

694

695

696

697

698

699

700

701

702

703

704

705

706

707

708

709

710

711

712

713

714

715

716

717

718

719

720

721

722

723

724

725

726

727

728

729

730

731

732

733

734

735

736

737

738

739

740

741

742

743

744

745

746

747

748

749

750

751

752

753

754

755

756

757

758

759

760

761

762

763

764

765

766

767

768

769

770

771

772

773

774

775

776

777

778

779

780

781

782

783

784

785

786

787

788

789

790

791

792

793

794

795

796

797

798

799

800

801

802

803

804

805

806

807

808

809

810

811

812

813

814

815

816

817

818

819

820

821

822

823

824

825

826

827

828

829

830

831

832

833

834

835

836

837

838

839

840

841

842

843

844

845

846

847

848

849

850

851

852

853

854

855

856

857

858

859

860

861

862

863

864

865

866

867

868

869

870

871

872

873

874

875

876

877

878

879

880

881

882

883

884

885

886

887

888

889

890

891

892

893

894

895

896

897

898

899

900

901

902

903

904

905

906

907

908

909

910

911

912

913

914

915

916

917

918

919

920

921

922

923

924

925

926

927

928

929

930

931

932

933

934

935

936

937

938

939

940

941

942

943

944

945

946

947

948

949

950

951

952

953

954

955

956

957

958

959

960

961

962

963

964

965

966

967

968

969

970

971

972

973

974

975

976

977

978

979

980

981

982

983

984

985

986

987

988

989

990

991

992

993

994

995

996

997

998

999

1000

1001

1002

1003

1004

1005

1006

1007

1008

1009

1010

1011

1012

1013

1014

1015

1016

1017

1018

1019

1020

1021

1022

1023

1024

1025

1026

1027

1028

1029

1030

1031

1032

1033

1034

1035

1036

1037

1038

1039

1040

1041

1042

1043

1044

1045

1046

1047

1048

1049

1050

1051

1052

1053

1054

1055

1056

1057

1058

1059

1060

1061

1062

1063

1064

1065

1066

1067

1068

1069

1070

1071

1072

1073

1074

1075

1076

1077

1078

1079

1080

1081

1082

1083

1084

1085

1086

1087

1088

1089

1090

1091

1092

1093

1094

1095

1096

1097

1098

1099

1100

1101

1102

1103

1104

1105

1106

1107

1108

1109

1110

1111

1112

1113

1114

1115

1116

1117

1118

1119

1120

1121

1122

1123

1124

1125

1126

1127

1128

1129

1130

1131

1132

1133

1134

1135

1136

1137

1138

1139

1140

1141

1142

1143

1144

1145

1146

1147

1148

1149

1150

1151

1152

1153

1154

1155

1156

1157

1158

1159

1160

1161

1162

1163

1164

1165

1166

1167

1168

1169

1170

1171

1172

1173

1174

1175

1176

1177

1178

1179

1180

1181

1182

1183

1184

1185

1186

1187

1188

1189

1190

1191

1192

1193

1194

1195

1196

1197

1198

1199

1200

1201

1202

1203

1204

1205

1206

1207

1208

1209

1210

1211

1212

1213

1214

1215

1216

1217

1218

1219

1220

1221

1222

1223

1224

1225

1226

1227

1228

1229

1230

1231

1232

1233

1234

1235

1236

1237

1238

1239

1240

1241

1242

1243

1244

1245

1246

1247

1248

1249

1250

1251

1252

1253

1254

1255

1256

1257

1258

1259

1260

1261

1262

1263

1264

1265

1266

1267

1268

1269

1270

1271

1272

1273

1274

1275

1276

1277

1278

1279

1280

1281

1282

1283

1284

1285

1286

1287

1288

1289

1290

1291

1292

1293

1294

1295

1296

1297

1298

1299

1300

1301

1302

1303

1304

1305

1306

1307

1308

1309

1310

1311

1312

1313

1314

1315

1316

1317

1318

1319

1320

1321

1322

1323

1324

1325

1326

1327

1328

1329

1330

1331

1332

1333

1334

1335

1336

1337

1338

1339

1340

1341

1342

1343

1344

1345

1346

1347

1348

1349

1350

1351

1352

1353

1354

1355

1356

1357

1358

1359

1360

1361

1362

1363

1364

1365

1366

1367

1368

1369

1370

1371

1372

1373

1374

1375

1376

1377

1378

1379

1380

1381

1382

1383

1384

1385

1386

1387

1388

1389

1390

1391

1392

1393

1394

1395

1396

1397

1398

1399

1400

1401

1402

1403

1404

1405

1406

1407

1408

1409

1410

1411

1412

1413

1414

1415

1416

1417

1418

1419

1420

1421

1422

1423

1424

1425

1426

1427

1428

1429

1430

1431

1432

1433

1434

1435

1436

1437

1438

1439

1440

1441

1442

1443

1444

1445

1446

1447

1448

1449

1450

1451

1452

1453

1454

1455

1456

1457

1458

1459

1460

1461

1462

1463

1464

1465

1466

1467

1468

1469

1470

1471

1472

1473

1474

1475

1476

1477

1478

1479

1480

1481

1482

1483

1484

1485

1486

1487

1488

1489

1490

1491

1492

1493

1494

1495

1496

1497

1498

1499

1500

1501

1502

1503

1504

1505

1506

1507

1508

1509

1510

1511

1512

1513

1514

1515

1516

1517

1518

1519

1520

1521

1522

1523

1524

1525

1526

1527

1528

1529

1530

1531

1532

1533

1534

1535

1536

1537

1538

1539

1540

1541

1542

1543

1544

1545

1546

1547

1548

1549

1550

1551

1552

1553

1554

1555

1556

1557

1558

1559

1560

1561

1562

1563

1564

1565

1566

1567

1568

1569

1570

1571

1572

1573

1574

1575

1576

1577

1578

1579

1580

1581

1582

1583

1584

1585

1586

1587

1588

1589

1590

1591

1592

1593

1594

1595

1596

1597

1598

1599

1600

1601

1602

1603

1604

1605

1606

1607

1608

1609

1610

1611

1612

1613

1614

1615

1616

1617

1618

1619

1620

1621

1622

1623

1624

1625

1626

1627

1628

1629

1630

1631

1632

1633

1634

1635

1636

1637

1638

1639

1640

1641

1642

1643

1644

1645

1646

1647

1648

1649

1650

1651

1652

1653

1654

1655

1656

1657

1658

1659

1660

1661

1662

1663

1664

1665

1666

1667

1668

1669

1670

1671

1672

1673

1674

1675

1676

1677

1678

1679

1680

1681

1682

1683

1684

1685

1686

1687

1688

1689

1690

1691

1692

1693

1694

1695

1696

1697

1698

1699

1700

1701

1702

1703

1704

1705

1706

1707

1708

1709

1710

1711

1712

1713

1714

1715

1716

1717

1718

1719

1720

1721

1722

1723

1724

1725

1726

1727

1728

1729

1730

1731

1732

1733

1734

1735

1736

1737

1738

1739

1740

1741

1742

1743

1744

1745

1746

1747

1748

1749

1750

1751

1752

1753

1754

1755

1756

1757

1758

1759

1760

1761

1762

1763

1764

1765

1766

1767

1768

1769

1770

1771

1772

1773

1774

1775

1776

1777

1778

1779

1780

1781

1782

1783

1784

1785

1786

1787

1788

1789

1790

1791

1792

1793

1794

1795

1796

1797

1798

1799

1800

1801

1802

1803

1804

1805

1806

1807

1808

1809

1810

1811

1812

1813

1814

1815

1816

1817

1818

1819

1820

1821

1822

1823

1824

1825

1826

1827

1828

1829

1830

1831

1832

1833

1834

1835

1836

1837

1838

1839

1840

1841

1842

1843

1844

1845

1846

1847

1848

1849

1850

1851

1852

1853

1854

1855

1856

1857

1858

1859

1860

1861

1862

1863

1864

""" 

Boolean algebra module for SymPy 

""" 

from __future__ import print_function, division 

 

from collections import defaultdict 

from itertools import combinations, product 

 

from sympy.core.basic import Basic 

from sympy.core.cache import cacheit 

from sympy.core.numbers import Number 

from sympy.core.operations import LatticeOp 

from sympy.core.function import Application, Derivative 

from sympy.core.compatibility import ordered, range, with_metaclass, as_int 

from sympy.core.sympify import converter, _sympify, sympify 

from sympy.core.singleton import Singleton, S 

 

 

class Boolean(Basic): 

"""A boolean object is an object for which logic operations make sense.""" 

 

__slots__ = [] 

 

def __and__(self, other): 

"""Overloading for & operator""" 

return And(self, other) 

 

__rand__ = __and__ 

 

def __or__(self, other): 

"""Overloading for |""" 

return Or(self, other) 

 

__ror__ = __or__ 

 

def __invert__(self): 

"""Overloading for ~""" 

return Not(self) 

 

def __rshift__(self, other): 

"""Overloading for >>""" 

return Implies(self, other) 

 

def __lshift__(self, other): 

"""Overloading for <<""" 

return Implies(other, self) 

 

__rrshift__ = __lshift__ 

__rlshift__ = __rshift__ 

 

def __xor__(self, other): 

return Xor(self, other) 

 

__rxor__ = __xor__ 

 

def equals(self, other): 

""" 

Returns True if the given formulas have the same truth table. 

For two formulas to be equal they must have the same literals. 

 

Examples 

======== 

 

>>> from sympy.abc import A, B, C 

>>> from sympy.logic.boolalg import And, Or, Not 

>>> (A >> B).equals(~B >> ~A) 

True 

>>> Not(And(A, B, C)).equals(And(Not(A), Not(B), Not(C))) 

False 

>>> Not(And(A, Not(A))).equals(Or(B, Not(B))) 

False 

""" 

from sympy.logic.inference import satisfiable 

from sympy.core.relational import Relational 

 

if self.has(Relational) or other.has(Relational): 

raise NotImplementedError('handling of relationals') 

return self.atoms() == other.atoms() and \ 

not satisfiable(Not(Equivalent(self, other))) 

 

 

class BooleanAtom(Boolean): 

""" 

Base class of BooleanTrue and BooleanFalse. 

""" 

is_Boolean = True 

_op_priority = 11 # higher than Expr 

 

@property 

def canonical(self): 

return self 

 

def _noop(self, other=None): 

raise TypeError('BooleanAtom not allowed in this context.') 

 

__add__ = _noop 

__radd__ = _noop 

__sub__ = _noop 

__rsub__ = _noop 

__mul__ = _noop 

__rmul__ = _noop 

__pow__ = _noop 

__rpow__ = _noop 

__rdiv__ = _noop 

__truediv__ = _noop 

__div__ = _noop 

__rtruediv__ = _noop 

__mod__ = _noop 

__rmod__ = _noop 

_eval_power = _noop 

 

 

class BooleanTrue(with_metaclass(Singleton, BooleanAtom)): 

""" 

SymPy version of True, a singleton that can be accessed via S.true. 

 

This is the SymPy version of True, for use in the logic module. The 

primary advantage of using true instead of True is that shorthand boolean 

operations like ~ and >> will work as expected on this class, whereas with 

True they act bitwise on 1. Functions in the logic module will return this 

class when they evaluate to true. 

 

Notes 

===== 

 

There is liable to be some confusion as to when ``True`` should 

be used and when ``S.true`` should be used in various contexts 

throughout SymPy. An important thing to remember is that 

``sympify(True)`` returns ``S.true``. This means that for the most 

part, you can just use ``True`` and it will automatically be converted 

to ``S.true`` when necessary, similar to how you can generally use 1 

instead of ``S.One``. 

 

The rule of thumb is: 

 

"If the boolean in question can be replaced by an arbitrary symbolic 

``Boolean``, like ``Or(x, y)`` or ``x > 1``, use ``S.true``. 

Otherwise, use ``True``" 

 

In other words, use ``S.true`` only on those contexts where the 

boolean is being used as a symbolic representation of truth. 

For example, if the object ends up in the ``.args`` of any expression, 

then it must necessarily be ``S.true`` instead of ``True``, as 

elements of ``.args`` must be ``Basic``. On the other hand, 

``==`` is not a symbolic operation in SymPy, since it always returns 

``True`` or ``False``, and does so in terms of structural equality 

rather than mathematical, so it should return ``True``. The assumptions 

system should use ``True`` and ``False``. Aside from not satisfying 

the above rule of thumb, the 

assumptions system uses a three-valued logic (``True``, ``False``, ``None``), 

whereas ``S.true`` and ``S.false`` represent a two-valued logic. When in 

doubt, use ``True``. 

 

"``S.true == True is True``." 

 

While "``S.true is True``" is ``False``, "``S.true == True``" 

is ``True``, so if there is any doubt over whether a function or 

expression will return ``S.true`` or ``True``, just use ``==`` 

instead of ``is`` to do the comparison, and it will work in either 

case. Finally, for boolean flags, it's better to just use ``if x`` 

instead of ``if x is True``. To quote PEP 8: 

 

Don't compare boolean values to ``True`` or ``False`` 

using ``==``. 

 

* Yes: ``if greeting:`` 

* No: ``if greeting == True:`` 

* Worse: ``if greeting is True:`` 

 

Examples 

======== 

 

>>> from sympy import sympify, true, Or 

>>> sympify(True) 

True 

>>> ~true 

False 

>>> ~True 

-2 

>>> Or(True, False) 

True 

 

See Also 

======== 

sympy.logic.boolalg.BooleanFalse 

 

""" 

def __nonzero__(self): 

return True 

 

__bool__ = __nonzero__ 

 

def __hash__(self): 

return hash(True) 

 

def as_set(self): 

""" 

Rewrite logic operators and relationals in terms of real sets. 

 

Examples 

======== 

 

>>> from sympy import true 

>>> true.as_set() 

UniversalSet() 

""" 

return S.UniversalSet 

 

 

class BooleanFalse(with_metaclass(Singleton, BooleanAtom)): 

""" 

SymPy version of False, a singleton that can be accessed via S.false. 

 

This is the SymPy version of False, for use in the logic module. The 

primary advantage of using false instead of False is that shorthand boolean 

operations like ~ and >> will work as expected on this class, whereas with 

False they act bitwise on 0. Functions in the logic module will return this 

class when they evaluate to false. 

 

Notes 

====== 

See note in :py:class`sympy.logic.boolalg.BooleanTrue` 

 

Examples 

======== 

 

>>> from sympy import sympify, false, Or, true 

>>> sympify(False) 

False 

>>> false >> false 

True 

>>> False >> False 

0 

>>> Or(True, False) 

True 

 

See Also 

======== 

sympy.logic.boolalg.BooleanTrue 

 

""" 

def __nonzero__(self): 

return False 

 

__bool__ = __nonzero__ 

 

def __hash__(self): 

return hash(False) 

 

def as_set(self): 

""" 

Rewrite logic operators and relationals in terms of real sets. 

 

Examples 

======== 

 

>>> from sympy import false 

>>> false.as_set() 

EmptySet() 

""" 

from sympy.sets.sets import EmptySet 

return EmptySet() 

 

true = BooleanTrue() 

false = BooleanFalse() 

# We want S.true and S.false to work, rather than S.BooleanTrue and 

# S.BooleanFalse, but making the class and instance names the same causes some 

# major issues (like the inability to import the class directly from this 

# file). 

S.true = true 

S.false = false 

 

converter[bool] = lambda x: S.true if x else S.false 

 

class BooleanFunction(Application, Boolean): 

"""Boolean function is a function that lives in a boolean space 

It is used as base class for And, Or, Not, etc. 

""" 

is_Boolean = True 

 

def _eval_simplify(self, ratio, measure): 

return simplify_logic(self) 

 

def to_nnf(self, simplify=True): 

return self._to_nnf(*self.args, simplify=simplify) 

 

@classmethod 

def _to_nnf(cls, *args, **kwargs): 

simplify = kwargs.get('simplify', True) 

argset = set([]) 

for arg in args: 

if not is_literal(arg): 

arg = arg.to_nnf(simplify) 

if simplify: 

if isinstance(arg, cls): 

arg = arg.args 

else: 

arg = (arg,) 

for a in arg: 

if Not(a) in argset: 

return cls.zero 

argset.add(a) 

else: 

argset.add(arg) 

return cls(*argset) 

 

 

class And(LatticeOp, BooleanFunction): 

""" 

Logical AND function. 

 

It evaluates its arguments in order, giving False immediately 

if any of them are False, and True if they are all True. 

 

Examples 

======== 

 

>>> from sympy.core import symbols 

>>> from sympy.abc import x, y 

>>> from sympy.logic.boolalg import And 

>>> x & y 

And(x, y) 

 

Notes 

===== 

 

The ``&`` operator is provided as a convenience, but note that its use 

here is different from its normal use in Python, which is bitwise 

and. Hence, ``And(a, b)`` and ``a & b`` will return different things if 

``a`` and ``b`` are integers. 

 

>>> And(x, y).subs(x, 1) 

y 

 

""" 

zero = false 

identity = true 

 

nargs = None 

 

@classmethod 

def _new_args_filter(cls, args): 

newargs = [] 

rel = [] 

for x in reversed(list(args)): 

if isinstance(x, Number) or x in (0, 1): 

newargs.append(True if x else False) 

continue 

if x.is_Relational: 

c = x.canonical 

if c in rel: 

continue 

nc = (~c).canonical 

if any(r == nc for r in rel): 

return [S.false] 

rel.append(c) 

newargs.append(x) 

return LatticeOp._new_args_filter(newargs, And) 

 

def as_set(self): 

""" 

Rewrite logic operators and relationals in terms of real sets. 

 

Examples 

======== 

 

>>> from sympy import And, Symbol 

>>> x = Symbol('x', real=True) 

>>> And(x<2, x>-2).as_set() 

(-2, 2) 

""" 

from sympy.sets.sets import Intersection 

if len(self.free_symbols) == 1: 

return Intersection(*[arg.as_set() for arg in self.args]) 

else: 

raise NotImplementedError("Sorry, And.as_set has not yet been" 

" implemented for multivariate" 

" expressions") 

 

 

class Or(LatticeOp, BooleanFunction): 

""" 

Logical OR function 

 

It evaluates its arguments in order, giving True immediately 

if any of them are True, and False if they are all False. 

 

Examples 

======== 

 

>>> from sympy.core import symbols 

>>> from sympy.abc import x, y 

>>> from sympy.logic.boolalg import Or 

>>> x | y 

Or(x, y) 

 

Notes 

===== 

 

The ``|`` operator is provided as a convenience, but note that its use 

here is different from its normal use in Python, which is bitwise 

or. Hence, ``Or(a, b)`` and ``a | b`` will return different things if 

``a`` and ``b`` are integers. 

 

>>> Or(x, y).subs(x, 0) 

y 

 

""" 

zero = true 

identity = false 

 

@classmethod 

def _new_args_filter(cls, args): 

newargs = [] 

rel = [] 

for x in args: 

if isinstance(x, Number) or x in (0, 1): 

newargs.append(True if x else False) 

continue 

if x.is_Relational: 

c = x.canonical 

if c in rel: 

continue 

nc = (~c).canonical 

if any(r == nc for r in rel): 

return [S.true] 

rel.append(c) 

newargs.append(x) 

return LatticeOp._new_args_filter(newargs, Or) 

 

def as_set(self): 

""" 

Rewrite logic operators and relationals in terms of real sets. 

 

Examples 

======== 

 

>>> from sympy import Or, Symbol 

>>> x = Symbol('x', real=True) 

>>> Or(x>2, x<-2).as_set() 

(-oo, -2) U (2, oo) 

""" 

from sympy.sets.sets import Union 

if len(self.free_symbols) == 1: 

return Union(*[arg.as_set() for arg in self.args]) 

else: 

raise NotImplementedError("Sorry, Or.as_set has not yet been" 

" implemented for multivariate" 

" expressions") 

 

 

class Not(BooleanFunction): 

""" 

Logical Not function (negation) 

 

 

Returns True if the statement is False 

Returns False if the statement is True 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import Not, And, Or 

>>> from sympy.abc import x, A, B 

>>> Not(True) 

False 

>>> Not(False) 

True 

>>> Not(And(True, False)) 

True 

>>> Not(Or(True, False)) 

False 

>>> Not(And(And(True, x), Or(x, False))) 

Not(x) 

>>> ~x 

Not(x) 

>>> Not(And(Or(A, B), Or(~A, ~B))) 

Not(And(Or(A, B), Or(Not(A), Not(B)))) 

 

Notes 

===== 

 

- The ``~`` operator is provided as a convenience, but note that its use 

here is different from its normal use in Python, which is bitwise 

not. In particular, ``~a`` and ``Not(a)`` will be different if ``a`` is 

an integer. Furthermore, since bools in Python subclass from ``int``, 

``~True`` is the same as ``~1`` which is ``-2``, which has a boolean 

value of True. To avoid this issue, use the SymPy boolean types 

``true`` and ``false``. 

 

>>> from sympy import true 

>>> ~True 

-2 

>>> ~true 

False 

 

""" 

 

is_Not = True 

 

@classmethod 

def eval(cls, arg): 

from sympy import ( 

Equality, GreaterThan, LessThan, 

StrictGreaterThan, StrictLessThan, Unequality) 

if isinstance(arg, Number) or arg in (True, False): 

return false if arg else true 

if arg.is_Not: 

return arg.args[0] 

# Simplify Relational objects. 

if isinstance(arg, Equality): 

return Unequality(*arg.args) 

if isinstance(arg, Unequality): 

return Equality(*arg.args) 

if isinstance(arg, StrictLessThan): 

return GreaterThan(*arg.args) 

if isinstance(arg, StrictGreaterThan): 

return LessThan(*arg.args) 

if isinstance(arg, LessThan): 

return StrictGreaterThan(*arg.args) 

if isinstance(arg, GreaterThan): 

return StrictLessThan(*arg.args) 

 

def as_set(self): 

""" 

Rewrite logic operators and relationals in terms of real sets. 

 

Examples 

======== 

 

>>> from sympy import Not, Symbol 

>>> x = Symbol('x', real=True) 

>>> Not(x>0).as_set() 

(-oo, 0] 

""" 

if len(self.free_symbols) == 1: 

return self.args[0].as_set().complement(S.Reals) 

else: 

raise NotImplementedError("Sorry, Not.as_set has not yet been" 

" implemented for mutivariate" 

" expressions") 

 

def to_nnf(self, simplify=True): 

if is_literal(self): 

return self 

 

expr = self.args[0] 

 

func, args = expr.func, expr.args 

 

if func == And: 

return Or._to_nnf(*[~arg for arg in args], simplify=simplify) 

 

if func == Or: 

return And._to_nnf(*[~arg for arg in args], simplify=simplify) 

 

if func == Implies: 

a, b = args 

return And._to_nnf(a, ~b, simplify=simplify) 

 

if func == Equivalent: 

return And._to_nnf(Or(*args), Or(*[~arg for arg in args]), simplify=simplify) 

 

if func == Xor: 

result = [] 

for i in range(1, len(args)+1, 2): 

for neg in combinations(args, i): 

clause = [~s if s in neg else s for s in args] 

result.append(Or(*clause)) 

return And._to_nnf(*result, simplify=simplify) 

 

if func == ITE: 

a, b, c = args 

return And._to_nnf(Or(a, ~c), Or(~a, ~b), simplify=simplify) 

 

raise ValueError("Illegal operator %s in expression" % func) 

 

 

class Xor(BooleanFunction): 

""" 

Logical XOR (exclusive OR) function. 

 

 

Returns True if an odd number of the arguments are True and the rest are 

False. 

 

Returns False if an even number of the arguments are True and the rest are 

False. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import Xor 

>>> from sympy import symbols 

>>> x, y = symbols('x y') 

>>> Xor(True, False) 

True 

>>> Xor(True, True) 

False 

>>> Xor(True, False, True, True, False) 

True 

>>> Xor(True, False, True, False) 

False 

>>> x ^ y 

Xor(x, y) 

 

Notes 

===== 

 

The ``^`` operator is provided as a convenience, but note that its use 

here is different from its normal use in Python, which is bitwise xor. In 

particular, ``a ^ b`` and ``Xor(a, b)`` will be different if ``a`` and 

``b`` are integers. 

 

>>> Xor(x, y).subs(y, 0) 

x 

 

""" 

def __new__(cls, *args, **kwargs): 

argset = set([]) 

obj = super(Xor, cls).__new__(cls, *args, **kwargs) 

for arg in obj._args: 

if isinstance(arg, Number) or arg in (True, False): 

if arg: 

arg = true 

else: 

continue 

if isinstance(arg, Xor): 

for a in arg.args: 

argset.remove(a) if a in argset else argset.add(a) 

elif arg in argset: 

argset.remove(arg) 

else: 

argset.add(arg) 

rel = [(r, r.canonical, (~r).canonical) for r in argset if r.is_Relational] 

odd = False # is number of complimentary pairs odd? start 0 -> False 

remove = [] 

for i, (r, c, nc) in enumerate(rel): 

for j in range(i + 1, len(rel)): 

rj, cj = rel[j][:2] 

if cj == nc: 

odd = ~odd 

break 

elif cj == c: 

break 

else: 

continue 

remove.append((r, rj)) 

if odd: 

argset.remove(true) if true in argset else argset.add(true) 

for a, b in remove: 

argset.remove(a) 

argset.remove(b) 

if len(argset) == 0: 

return false 

elif len(argset) == 1: 

return argset.pop() 

elif True in argset: 

argset.remove(True) 

return Not(Xor(*argset)) 

else: 

obj._args = tuple(ordered(argset)) 

obj._argset = frozenset(argset) 

return obj 

 

@property 

@cacheit 

def args(self): 

return tuple(ordered(self._argset)) 

 

def to_nnf(self, simplify=True): 

args = [] 

for i in range(0, len(self.args)+1, 2): 

for neg in combinations(self.args, i): 

clause = [~s if s in neg else s for s in self.args] 

args.append(Or(*clause)) 

return And._to_nnf(*args, simplify=simplify) 

 

 

class Nand(BooleanFunction): 

""" 

Logical NAND function. 

 

It evaluates its arguments in order, giving True immediately if any 

of them are False, and False if they are all True. 

 

Returns True if any of the arguments are False 

Returns False if all arguments are True 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import Nand 

>>> from sympy import symbols 

>>> x, y = symbols('x y') 

>>> Nand(False, True) 

True 

>>> Nand(True, True) 

False 

>>> Nand(x, y) 

Not(And(x, y)) 

 

""" 

@classmethod 

def eval(cls, *args): 

return Not(And(*args)) 

 

 

class Nor(BooleanFunction): 

""" 

Logical NOR function. 

 

It evaluates its arguments in order, giving False immediately if any 

of them are True, and True if they are all False. 

 

Returns False if any argument is True 

Returns True if all arguments are False 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import Nor 

>>> from sympy import symbols 

>>> x, y = symbols('x y') 

 

>>> Nor(True, False) 

False 

>>> Nor(True, True) 

False 

>>> Nor(False, True) 

False 

>>> Nor(False, False) 

True 

>>> Nor(x, y) 

Not(Or(x, y)) 

 

""" 

@classmethod 

def eval(cls, *args): 

return Not(Or(*args)) 

 

 

class Implies(BooleanFunction): 

""" 

Logical implication. 

 

A implies B is equivalent to !A v B 

 

Accepts two Boolean arguments; A and B. 

Returns False if A is True and B is False 

Returns True otherwise. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import Implies 

>>> from sympy import symbols 

>>> x, y = symbols('x y') 

 

>>> Implies(True, False) 

False 

>>> Implies(False, False) 

True 

>>> Implies(True, True) 

True 

>>> Implies(False, True) 

True 

>>> x >> y 

Implies(x, y) 

>>> y << x 

Implies(x, y) 

 

Notes 

===== 

 

The ``>>`` and ``<<`` operators are provided as a convenience, but note 

that their use here is different from their normal use in Python, which is 

bit shifts. Hence, ``Implies(a, b)`` and ``a >> b`` will return different 

things if ``a`` and ``b`` are integers. In particular, since Python 

considers ``True`` and ``False`` to be integers, ``True >> True`` will be 

the same as ``1 >> 1``, i.e., 0, which has a truth value of False. To 

avoid this issue, use the SymPy objects ``true`` and ``false``. 

 

>>> from sympy import true, false 

>>> True >> False 

1 

>>> true >> false 

False 

 

""" 

@classmethod 

def eval(cls, *args): 

try: 

newargs = [] 

for x in args: 

if isinstance(x, Number) or x in (0, 1): 

newargs.append(True if x else False) 

else: 

newargs.append(x) 

A, B = newargs 

except ValueError: 

raise ValueError( 

"%d operand(s) used for an Implies " 

"(pairs are required): %s" % (len(args), str(args))) 

if A == True or A == False or B == True or B == False: 

return Or(Not(A), B) 

elif A == B: 

return S.true 

elif A.is_Relational and B.is_Relational: 

if A.canonical == B.canonical: 

return S.true 

if (~A).canonical == B.canonical: 

return B 

else: 

return Basic.__new__(cls, *args) 

 

def to_nnf(self, simplify=True): 

a, b = self.args 

return Or._to_nnf(~a, b, simplify=simplify) 

 

 

class Equivalent(BooleanFunction): 

""" 

Equivalence relation. 

 

Equivalent(A, B) is True iff A and B are both True or both False 

 

Returns True if all of the arguments are logically equivalent. 

Returns False otherwise. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import Equivalent, And 

>>> from sympy.abc import x, y 

>>> Equivalent(False, False, False) 

True 

>>> Equivalent(True, False, False) 

False 

>>> Equivalent(x, And(x, True)) 

True 

""" 

def __new__(cls, *args, **options): 

from sympy.core.relational import Relational 

args = [_sympify(arg) for arg in args] 

 

argset = set(args) 

for x in args: 

if isinstance(x, Number) or x in [True, False]: # Includes 0, 1 

argset.discard(x) 

argset.add(True if x else False) 

rel = [] 

for r in argset: 

if isinstance(r, Relational): 

rel.append((r, r.canonical, (~r).canonical)) 

remove = [] 

for i, (r, c, nc) in enumerate(rel): 

for j in range(i + 1, len(rel)): 

rj, cj = rel[j][:2] 

if cj == nc: 

return false 

elif cj == c: 

remove.append((r, rj)) 

break 

for a, b in remove: 

argset.remove(a) 

argset.remove(b) 

argset.add(True) 

if len(argset) <= 1: 

return true 

if True in argset: 

argset.discard(True) 

return And(*argset) 

if False in argset: 

argset.discard(False) 

return And(*[~arg for arg in argset]) 

_args = frozenset(argset) 

obj = super(Equivalent, cls).__new__(cls, _args) 

obj._argset = _args 

return obj 

 

@property 

@cacheit 

def args(self): 

return tuple(ordered(self._argset)) 

 

def to_nnf(self, simplify=True): 

args = [] 

for a, b in zip(self.args, self.args[1:]): 

args.append(Or(~a, b)) 

args.append(Or(~self.args[-1], self.args[0])) 

return And._to_nnf(*args, simplify=simplify) 

 

 

class ITE(BooleanFunction): 

""" 

If then else clause. 

 

ITE(A, B, C) evaluates and returns the result of B if A is true 

else it returns the result of C 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import ITE, And, Xor, Or 

>>> from sympy.abc import x, y, z 

>>> ITE(True, False, True) 

False 

>>> ITE(Or(True, False), And(True, True), Xor(True, True)) 

True 

>>> ITE(x, y, z) 

ITE(x, y, z) 

>>> ITE(True, x, y) 

x 

>>> ITE(False, x, y) 

y 

>>> ITE(x, y, y) 

y 

""" 

@classmethod 

def eval(cls, *args): 

try: 

a, b, c = args 

except ValueError: 

raise ValueError("ITE expects exactly 3 arguments") 

if a == True: 

return b 

if a == False: 

return c 

if b == c: 

return b 

 

def to_nnf(self, simplify=True): 

a, b, c = self.args 

return And._to_nnf(Or(~a, b), Or(a, c), simplify=simplify) 

 

def _eval_derivative(self, x): 

return self.func(self.args[0], *[a.diff(x) for a in self.args[1:]]) 

 

# the diff method below is copied from Expr class 

def diff(self, *symbols, **assumptions): 

new_symbols = list(map(sympify, symbols)) # e.g. x, 2, y, z 

assumptions.setdefault("evaluate", True) 

return Derivative(self, *new_symbols, **assumptions) 

 

 

### end class definitions. Some useful methods 

 

 

def conjuncts(expr): 

"""Return a list of the conjuncts in the expr s. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import conjuncts 

>>> from sympy.abc import A, B 

>>> conjuncts(A & B) 

frozenset([A, B]) 

>>> conjuncts(A | B) 

frozenset([Or(A, B)]) 

 

""" 

return And.make_args(expr) 

 

 

def disjuncts(expr): 

"""Return a list of the disjuncts in the sentence s. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import disjuncts 

>>> from sympy.abc import A, B 

>>> disjuncts(A | B) 

frozenset([A, B]) 

>>> disjuncts(A & B) 

frozenset([And(A, B)]) 

 

""" 

return Or.make_args(expr) 

 

 

def distribute_and_over_or(expr): 

""" 

Given a sentence s consisting of conjunctions and disjunctions 

of literals, return an equivalent sentence in CNF. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import distribute_and_over_or, And, Or, Not 

>>> from sympy.abc import A, B, C 

>>> distribute_and_over_or(Or(A, And(Not(B), Not(C)))) 

And(Or(A, Not(B)), Or(A, Not(C))) 

""" 

return _distribute((expr, And, Or)) 

 

 

def distribute_or_over_and(expr): 

""" 

Given a sentence s consisting of conjunctions and disjunctions 

of literals, return an equivalent sentence in DNF. 

 

Note that the output is NOT simplified. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import distribute_or_over_and, And, Or, Not 

>>> from sympy.abc import A, B, C 

>>> distribute_or_over_and(And(Or(Not(A), B), C)) 

Or(And(B, C), And(C, Not(A))) 

""" 

return _distribute((expr, Or, And)) 

 

 

def _distribute(info): 

""" 

Distributes info[1] over info[2] with respect to info[0]. 

""" 

if info[0].func is info[2]: 

for arg in info[0].args: 

if arg.func is info[1]: 

conj = arg 

break 

else: 

return info[0] 

rest = info[2](*[a for a in info[0].args if a is not conj]) 

return info[1](*list(map(_distribute, 

[(info[2](c, rest), info[1], info[2]) for c in conj.args]))) 

elif info[0].func is info[1]: 

return info[1](*list(map(_distribute, 

[(x, info[1], info[2]) for x in info[0].args]))) 

else: 

return info[0] 

 

 

def to_nnf(expr, simplify=True): 

""" 

Converts expr to Negation Normal Form. 

A logical expression is in Negation Normal Form (NNF) if it 

contains only And, Or and Not, and Not is applied only to literals. 

If simpify is True, the result contains no redundant clauses. 

 

Examples 

======== 

 

>>> from sympy.abc import A, B, C, D 

>>> from sympy.logic.boolalg import Not, Equivalent, to_nnf 

>>> to_nnf(Not((~A & ~B) | (C & D))) 

And(Or(A, B), Or(Not(C), Not(D))) 

>>> to_nnf(Equivalent(A >> B, B >> A)) 

And(Or(A, And(A, Not(B)), Not(B)), Or(And(B, Not(A)), B, Not(A))) 

""" 

if is_nnf(expr, simplify): 

return expr 

return expr.to_nnf(simplify) 

 

 

def to_cnf(expr, simplify=False): 

""" 

Convert a propositional logical sentence s to conjunctive normal form. 

That is, of the form ((A | ~B | ...) & (B | C | ...) & ...) 

If simplify is True, the expr is evaluated to its simplest CNF form. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import to_cnf 

>>> from sympy.abc import A, B, D 

>>> to_cnf(~(A | B) | D) 

And(Or(D, Not(A)), Or(D, Not(B))) 

>>> to_cnf((A | B) & (A | ~A), True) 

Or(A, B) 

 

""" 

expr = sympify(expr) 

if not isinstance(expr, BooleanFunction): 

return expr 

 

if simplify: 

return simplify_logic(expr, 'cnf', True) 

 

# Don't convert unless we have to 

if is_cnf(expr): 

return expr 

 

expr = eliminate_implications(expr) 

return distribute_and_over_or(expr) 

 

 

def to_dnf(expr, simplify=False): 

""" 

Convert a propositional logical sentence s to disjunctive normal form. 

That is, of the form ((A & ~B & ...) | (B & C & ...) | ...) 

If simplify is True, the expr is evaluated to its simplest DNF form. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import to_dnf 

>>> from sympy.abc import A, B, C 

>>> to_dnf(B & (A | C)) 

Or(And(A, B), And(B, C)) 

>>> to_dnf((A & B) | (A & ~B) | (B & C) | (~B & C), True) 

Or(A, C) 

 

""" 

expr = sympify(expr) 

if not isinstance(expr, BooleanFunction): 

return expr 

 

if simplify: 

return simplify_logic(expr, 'dnf', True) 

 

# Don't convert unless we have to 

if is_dnf(expr): 

return expr 

 

expr = eliminate_implications(expr) 

return distribute_or_over_and(expr) 

 

 

def is_nnf(expr, simplified=True): 

""" 

Checks if expr is in Negation Normal Form. 

A logical expression is in Negation Normal Form (NNF) if it 

contains only And, Or and Not, and Not is applied only to literals. 

If simpified is True, checks if result contains no redundant clauses. 

 

Examples 

======== 

 

>>> from sympy.abc import A, B, C 

>>> from sympy.logic.boolalg import Not, is_nnf 

>>> is_nnf(A & B | ~C) 

True 

>>> is_nnf((A | ~A) & (B | C)) 

False 

>>> is_nnf((A | ~A) & (B | C), False) 

True 

>>> is_nnf(Not(A & B) | C) 

False 

>>> is_nnf((A >> B) & (B >> A)) 

False 

""" 

 

expr = sympify(expr) 

if is_literal(expr): 

return True 

 

stack = [expr] 

 

while stack: 

expr = stack.pop() 

if expr.func in (And, Or): 

if simplified: 

args = expr.args 

for arg in args: 

if Not(arg) in args: 

return False 

stack.extend(expr.args) 

 

elif not is_literal(expr): 

return False 

 

return True 

 

 

def is_cnf(expr): 

""" 

Test whether or not an expression is in conjunctive normal form. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import is_cnf 

>>> from sympy.abc import A, B, C 

>>> is_cnf(A | B | C) 

True 

>>> is_cnf(A & B & C) 

True 

>>> is_cnf((A & B) | C) 

False 

 

""" 

return _is_form(expr, And, Or) 

 

 

def is_dnf(expr): 

""" 

Test whether or not an expression is in disjunctive normal form. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import is_dnf 

>>> from sympy.abc import A, B, C 

>>> is_dnf(A | B | C) 

True 

>>> is_dnf(A & B & C) 

True 

>>> is_dnf((A & B) | C) 

True 

>>> is_dnf(A & (B | C)) 

False 

 

""" 

return _is_form(expr, Or, And) 

 

 

def _is_form(expr, function1, function2): 

""" 

Test whether or not an expression is of the required form. 

 

""" 

expr = sympify(expr) 

 

# Special case of an Atom 

if expr.is_Atom: 

return True 

 

# Special case of a single expression of function2 

if expr.func is function2: 

for lit in expr.args: 

if lit.func is Not: 

if not lit.args[0].is_Atom: 

return False 

else: 

if not lit.is_Atom: 

return False 

return True 

 

# Special case of a single negation 

if expr.func is Not: 

if not expr.args[0].is_Atom: 

return False 

 

if expr.func is not function1: 

return False 

 

for cls in expr.args: 

if cls.is_Atom: 

continue 

if cls.func is Not: 

if not cls.args[0].is_Atom: 

return False 

elif cls.func is not function2: 

return False 

for lit in cls.args: 

if lit.func is Not: 

if not lit.args[0].is_Atom: 

return False 

else: 

if not lit.is_Atom: 

return False 

 

return True 

 

 

def eliminate_implications(expr): 

""" 

Change >>, <<, and Equivalent into &, |, and ~. That is, return an 

expression that is equivalent to s, but has only &, |, and ~ as logical 

operators. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import Implies, Equivalent, \ 

eliminate_implications 

>>> from sympy.abc import A, B, C 

>>> eliminate_implications(Implies(A, B)) 

Or(B, Not(A)) 

>>> eliminate_implications(Equivalent(A, B)) 

And(Or(A, Not(B)), Or(B, Not(A))) 

>>> eliminate_implications(Equivalent(A, B, C)) 

And(Or(A, Not(C)), Or(B, Not(A)), Or(C, Not(B))) 

""" 

return to_nnf(expr) 

 

 

def is_literal(expr): 

""" 

Returns True if expr is a literal, else False. 

 

Examples 

======== 

 

>>> from sympy import Or, Q 

>>> from sympy.abc import A, B 

>>> from sympy.logic.boolalg import is_literal 

>>> is_literal(A) 

True 

>>> is_literal(~A) 

True 

>>> is_literal(Q.zero(A)) 

True 

>>> is_literal(A + B) 

True 

>>> is_literal(Or(A, B)) 

False 

""" 

if isinstance(expr, Not): 

return not isinstance(expr.args[0], BooleanFunction) 

else: 

return not isinstance(expr, BooleanFunction) 

 

 

def to_int_repr(clauses, symbols): 

""" 

Takes clauses in CNF format and puts them into an integer representation. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import to_int_repr 

>>> from sympy.abc import x, y 

>>> to_int_repr([x | y, y], [x, y]) == [set([1, 2]), set([2])] 

True 

 

""" 

 

# Convert the symbol list into a dict 

symbols = dict(list(zip(symbols, list(range(1, len(symbols) + 1))))) 

 

def append_symbol(arg, symbols): 

if arg.func is Not: 

return -symbols[arg.args[0]] 

else: 

return symbols[arg] 

 

return [set(append_symbol(arg, symbols) for arg in Or.make_args(c)) 

for c in clauses] 

 

 

def term_to_integer(term): 

""" 

Return an integer corresponding to the base-2 digits given by ``term``. 

 

Parameters 

========== 

 

term : a string or list of ones and zeros 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import term_to_integer 

>>> term_to_integer([1, 0, 0]) 

4 

>>> term_to_integer('100') 

4 

 

""" 

 

return int(''.join(list(map(str, list(term)))), 2) 

 

 

def integer_to_term(k, n_bits=None): 

""" 

Return a list of the base-2 digits in the integer, ``k``. 

 

Parameters 

========== 

 

k : int 

n_bits : int 

If ``n_bits`` is given and the number of digits in the binary 

representation of ``k`` is smaller than ``n_bits`` then left-pad the 

list with 0s. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import integer_to_term 

>>> integer_to_term(4) 

[1, 0, 0] 

>>> integer_to_term(4, 6) 

[0, 0, 0, 1, 0, 0] 

""" 

 

s = '{0:0{1}b}'.format(abs(as_int(k)), as_int(abs(n_bits or 0))) 

return list(map(int, s)) 

 

 

def truth_table(expr, variables, input=True): 

""" 

Return a generator of all possible configurations of the input variables, 

and the result of the boolean expression for those values. 

 

Parameters 

========== 

 

expr : string or boolean expression 

variables : list of variables 

input : boolean (default True) 

indicates whether to return the input combinations. 

 

Examples 

======== 

 

>>> from sympy.logic.boolalg import truth_table 

>>> from sympy.abc import x,y 

>>> table = truth_table(x >> y, [x, y]) 

>>> for t in table: 

... print('{0} -> {1}'.format(*t)) 

[0, 0] -> True 

[0, 1] -> True 

[1, 0] -> False 

[1, 1] -> True 

 

>>> table = truth_table(x | y, [x, y]) 

>>> list(table) 

[([0, 0], False), ([0, 1], True), ([1, 0], True), ([1, 1], True)] 

 

If input is false, truth_table returns only a list of truth values. 

In this case, the corresponding input values of variables can be 

deduced from the index of a given output. 

 

>>> from sympy.logic.boolalg import integer_to_term 

>>> vars = [y, x] 

>>> values = truth_table(x >> y, vars, input=False) 

>>> values = list(values) 

>>> values 

[True, False, True, True] 

 

>>> for i, value in enumerate(values): 

... print('{0} -> {1}'.format(list(zip( 

... vars, integer_to_term(i, len(vars)))), value)) 

[(y, 0), (x, 0)] -> True 

[(y, 0), (x, 1)] -> False 

[(y, 1), (x, 0)] -> True 

[(y, 1), (x, 1)] -> True 

 

""" 

variables = [sympify(v) for v in variables] 

 

expr = sympify(expr) 

if not isinstance(expr, BooleanFunction) and not is_literal(expr): 

return 

 

table = product([0, 1], repeat=len(variables)) 

for term in table: 

term = list(term) 

value = expr.xreplace(dict(zip(variables, term))) 

 

if input: 

yield term, value 

else: 

yield value 

 

 

def _check_pair(minterm1, minterm2): 

""" 

Checks if a pair of minterms differs by only one bit. If yes, returns 

index, else returns -1. 

""" 

index = -1 

for x, (i, j) in enumerate(zip(minterm1, minterm2)): 

if i != j: 

if index == -1: 

index = x 

else: 

return -1 

return index 

 

 

def _convert_to_varsSOP(minterm, variables): 

""" 

Converts a term in the expansion of a function from binary to it's 

variable form (for SOP). 

""" 

temp = [] 

for i, m in enumerate(minterm): 

if m == 0: 

temp.append(Not(variables[i])) 

elif m == 1: 

temp.append(variables[i]) 

else: 

pass # ignore the 3s 

return And(*temp) 

 

 

def _convert_to_varsPOS(maxterm, variables): 

""" 

Converts a term in the expansion of a function from binary to it's 

variable form (for POS). 

""" 

temp = [] 

for i, m in enumerate(maxterm): 

if m == 1: 

temp.append(Not(variables[i])) 

elif m == 0: 

temp.append(variables[i]) 

else: 

pass # ignore the 3s 

return Or(*temp) 

 

 

def _simplified_pairs(terms): 

""" 

Reduces a set of minterms, if possible, to a simplified set of minterms 

with one less variable in the terms using QM method. 

""" 

simplified_terms = [] 

todo = list(range(len(terms))) 

for i, ti in enumerate(terms[:-1]): 

for j_i, tj in enumerate(terms[(i + 1):]): 

index = _check_pair(ti, tj) 

if index != -1: 

todo[i] = todo[j_i + i + 1] = None 

newterm = ti[:] 

newterm[index] = 3 

if newterm not in simplified_terms: 

simplified_terms.append(newterm) 

simplified_terms.extend( 

[terms[i] for i in [_ for _ in todo if _ is not None]]) 

return simplified_terms 

 

 

def _compare_term(minterm, term): 

""" 

Return True if a binary term is satisfied by the given term. Used 

for recognizing prime implicants. 

""" 

for i, x in enumerate(term): 

if x != 3 and x != minterm[i]: 

return False 

return True 

 

 

def _rem_redundancy(l1, terms): 

""" 

After the truth table has been sufficiently simplified, use the prime 

implicant table method to recognize and eliminate redundant pairs, 

and return the essential arguments. 

""" 

essential = [] 

for x in terms: 

temporary = [] 

for y in l1: 

if _compare_term(x, y): 

temporary.append(y) 

if len(temporary) == 1: 

if temporary[0] not in essential: 

essential.append(temporary[0]) 

for x in terms: 

for y in essential: 

if _compare_term(x, y): 

break 

else: 

for z in l1: 

if _compare_term(x, z): 

if z not in essential: 

essential.append(z) 

break 

 

return essential 

 

 

def SOPform(variables, minterms, dontcares=None): 

""" 

The SOPform function uses simplified_pairs and a redundant group- 

eliminating algorithm to convert the list of all input combos that 

generate '1' (the minterms) into the smallest Sum of Products form. 

 

The variables must be given as the first argument. 

 

Return a logical Or function (i.e., the "sum of products" or "SOP" 

form) that gives the desired outcome. If there are inputs that can 

be ignored, pass them as a list, too. 

 

The result will be one of the (perhaps many) functions that satisfy 

the conditions. 

 

Examples 

======== 

 

>>> from sympy.logic import SOPform 

>>> from sympy import symbols 

>>> w, x, y, z = symbols('w x y z') 

>>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], 

... [0, 1, 1, 1], [1, 0, 1, 1], [1, 1, 1, 1]] 

>>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] 

>>> SOPform([w, x, y, z], minterms, dontcares) 

Or(And(Not(w), z), And(y, z)) 

 

References 

========== 

 

.. [1] en.wikipedia.org/wiki/Quine-McCluskey_algorithm 

 

""" 

variables = [sympify(v) for v in variables] 

if minterms == []: 

return false 

 

minterms = [list(i) for i in minterms] 

dontcares = [list(i) for i in (dontcares or [])] 

for d in dontcares: 

if d in minterms: 

raise ValueError('%s in minterms is also in dontcares' % d) 

 

old = None 

new = minterms + dontcares 

while new != old: 

old = new 

new = _simplified_pairs(old) 

essential = _rem_redundancy(new, minterms) 

return Or(*[_convert_to_varsSOP(x, variables) for x in essential]) 

 

 

def POSform(variables, minterms, dontcares=None): 

""" 

The POSform function uses simplified_pairs and a redundant-group 

eliminating algorithm to convert the list of all input combinations 

that generate '1' (the minterms) into the smallest Product of Sums form. 

 

The variables must be given as the first argument. 

 

Return a logical And function (i.e., the "product of sums" or "POS" 

form) that gives the desired outcome. If there are inputs that can 

be ignored, pass them as a list, too. 

 

The result will be one of the (perhaps many) functions that satisfy 

the conditions. 

 

Examples 

======== 

 

>>> from sympy.logic import POSform 

>>> from sympy import symbols 

>>> w, x, y, z = symbols('w x y z') 

>>> minterms = [[0, 0, 0, 1], [0, 0, 1, 1], [0, 1, 1, 1], 

... [1, 0, 1, 1], [1, 1, 1, 1]] 

>>> dontcares = [[0, 0, 0, 0], [0, 0, 1, 0], [0, 1, 0, 1]] 

>>> POSform([w, x, y, z], minterms, dontcares) 

And(Or(Not(w), y), z) 

 

References 

========== 

 

.. [1] en.wikipedia.org/wiki/Quine-McCluskey_algorithm 

 

""" 

variables = [sympify(v) for v in variables] 

if minterms == []: 

return false 

 

minterms = [list(i) for i in minterms] 

dontcares = [list(i) for i in (dontcares or [])] 

for d in dontcares: 

if d in minterms: 

raise ValueError('%s in minterms is also in dontcares' % d) 

 

maxterms = [] 

for t in product([0, 1], repeat=len(variables)): 

t = list(t) 

if (t not in minterms) and (t not in dontcares): 

maxterms.append(t) 

old = None 

new = maxterms + dontcares 

while new != old: 

old = new 

new = _simplified_pairs(old) 

essential = _rem_redundancy(new, maxterms) 

return And(*[_convert_to_varsPOS(x, variables) for x in essential]) 

 

 

def _find_predicates(expr): 

"""Helper to find logical predicates in BooleanFunctions. 

 

A logical predicate is defined here as anything within a BooleanFunction 

that is not a BooleanFunction itself. 

 

""" 

if not isinstance(expr, BooleanFunction): 

return {expr} 

return set().union(*(_find_predicates(i) for i in expr.args)) 

 

 

def simplify_logic(expr, form=None, deep=True): 

""" 

This function simplifies a boolean function to its simplified version 

in SOP or POS form. The return type is an Or or And object in SymPy. 

 

Parameters 

========== 

 

expr : string or boolean expression 

form : string ('cnf' or 'dnf') or None (default). 

If 'cnf' or 'dnf', the simplest expression in the corresponding 

normal form is returned; if None, the answer is returned 

according to the form with fewest args (in CNF by default). 

deep : boolean (default True) 

indicates whether to recursively simplify any 

non-boolean functions contained within the input. 

 

Examples 

======== 

 

>>> from sympy.logic import simplify_logic 

>>> from sympy.abc import x, y, z 

>>> from sympy import S 

>>> b = (~x & ~y & ~z) | ( ~x & ~y & z) 

>>> simplify_logic(b) 

And(Not(x), Not(y)) 

 

>>> S(b) 

Or(And(Not(x), Not(y), Not(z)), And(Not(x), Not(y), z)) 

>>> simplify_logic(_) 

And(Not(x), Not(y)) 

 

""" 

 

if form == 'cnf' or form == 'dnf' or form is None: 

expr = sympify(expr) 

if not isinstance(expr, BooleanFunction): 

return expr 

variables = _find_predicates(expr) 

truthtable = [] 

for t in product([0, 1], repeat=len(variables)): 

t = list(t) 

if expr.xreplace(dict(zip(variables, t))) == True: 

truthtable.append(t) 

if deep: 

from sympy.simplify.simplify import simplify 

variables = [simplify(v) for v in variables] 

if form == 'dnf' or \ 

(form is None and len(truthtable) >= (2 ** (len(variables) - 1))): 

return SOPform(variables, truthtable) 

elif form == 'cnf' or form is None: 

return POSform(variables, truthtable) 

else: 

raise ValueError("form can be cnf or dnf only") 

 

 

def _finger(eq): 

""" 

Assign a 5-item fingerprint to each symbol in the equation: 

[ 

# of times it appeared as a Symbol, 

# of times it appeared as a Not(symbol), 

# of times it appeared as a Symbol in an And or Or, 

# of times it appeared as a Not(Symbol) in an And or Or, 

sum of the number of arguments with which it appeared, 

counting Symbol as 1 and Not(Symbol) as 2 

] 

 

>>> from sympy.logic.boolalg import _finger as finger 

>>> from sympy import And, Or, Not 

>>> from sympy.abc import a, b, x, y 

>>> eq = Or(And(Not(y), a), And(Not(y), b), And(x, y)) 

>>> dict(finger(eq)) 

{(0, 0, 1, 0, 2): [x], (0, 0, 1, 0, 3): [a, b], (0, 0, 1, 2, 8): [y]} 

 

So y and x have unique fingerprints, but a and b do not. 

""" 

f = eq.free_symbols 

d = dict(list(zip(f, [[0] * 5 for fi in f]))) 

for a in eq.args: 

if a.is_Symbol: 

d[a][0] += 1 

elif a.is_Not: 

d[a.args[0]][1] += 1 

else: 

o = len(a.args) + sum(ai.func is Not for ai in a.args) 

for ai in a.args: 

if ai.is_Symbol: 

d[ai][2] += 1 

d[ai][-1] += o 

else: 

d[ai.args[0]][3] += 1 

d[ai.args[0]][-1] += o 

inv = defaultdict(list) 

for k, v in ordered(iter(d.items())): 

inv[tuple(v)].append(k) 

return inv 

 

 

def bool_map(bool1, bool2): 

""" 

Return the simplified version of bool1, and the mapping of variables 

that makes the two expressions bool1 and bool2 represent the same 

logical behaviour for some correspondence between the variables 

of each. 

If more than one mappings of this sort exist, one of them 

is returned. 

For example, And(x, y) is logically equivalent to And(a, b) for 

the mapping {x: a, y:b} or {x: b, y:a}. 

If no such mapping exists, return False. 

 

Examples 

======== 

 

>>> from sympy import SOPform, bool_map, Or, And, Not, Xor 

>>> from sympy.abc import w, x, y, z, a, b, c, d 

>>> function1 = SOPform([x, z, y],[[1, 0, 1], [0, 0, 1]]) 

>>> function2 = SOPform([a, b, c],[[1, 0, 1], [1, 0, 0]]) 

>>> bool_map(function1, function2) 

(And(Not(z), y), {y: a, z: b}) 

 

The results are not necessarily unique, but they are canonical. Here, 

``(w, z)`` could be ``(a, d)`` or ``(d, a)``: 

 

>>> eq = Or(And(Not(y), w), And(Not(y), z), And(x, y)) 

>>> eq2 = Or(And(Not(c), a), And(Not(c), d), And(b, c)) 

>>> bool_map(eq, eq2) 

(Or(And(Not(y), w), And(Not(y), z), And(x, y)), {w: a, x: b, y: c, z: d}) 

>>> eq = And(Xor(a, b), c, And(c,d)) 

>>> bool_map(eq, eq.subs(c, x)) 

(And(Or(Not(a), Not(b)), Or(a, b), c, d), {a: a, b: b, c: d, d: x}) 

 

""" 

 

def match(function1, function2): 

"""Return the mapping that equates variables between two 

simplified boolean expressions if possible. 

 

By "simplified" we mean that a function has been denested 

and is either an And (or an Or) whose arguments are either 

symbols (x), negated symbols (Not(x)), or Or (or an And) whose 

arguments are only symbols or negated symbols. For example, 

And(x, Not(y), Or(w, Not(z))). 

 

Basic.match is not robust enough (see issue 4835) so this is 

a workaround that is valid for simplified boolean expressions 

""" 

 

# do some quick checks 

if function1.__class__ != function2.__class__: 

return None 

if len(function1.args) != len(function2.args): 

return None 

if function1.is_Symbol: 

return {function1: function2} 

 

# get the fingerprint dictionaries 

f1 = _finger(function1) 

f2 = _finger(function2) 

 

# more quick checks 

if len(f1) != len(f2): 

return False 

 

# assemble the match dictionary if possible 

matchdict = {} 

for k in f1.keys(): 

if k not in f2: 

return False 

if len(f1[k]) != len(f2[k]): 

return False 

for i, x in enumerate(f1[k]): 

matchdict[x] = f2[k][i] 

return matchdict 

 

a = simplify_logic(bool1) 

b = simplify_logic(bool2) 

m = match(a, b) 

if m: 

return a, m 

return m is not None