oxidd_core/function.rs
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 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885
//! Function traits
use std::fmt::Display;
use std::hash::{BuildHasher, Hash};
use nanorand::Rng;
use crate::util::num::F64;
use crate::util::{
AllocResult, Borrowed, EdgeDropGuard, NodeSet, OptBool, SatCountCache, SatCountNumber,
Substitution,
};
use crate::{DiagramRules, Edge, InnerNode, LevelNo, Manager, ManagerRef, Node};
/// Shorthand to get the [`Edge`] type associated with a [`Function`]
pub type EdgeOfFunc<'id, F> = <<F as Function>::Manager<'id> as Manager>::Edge;
/// Shorthand to get the edge tag type associated with a [`Function`]
pub type ETagOfFunc<'id, F> = <<F as Function>::Manager<'id> as Manager>::EdgeTag;
/// Shorthand to get the [`InnerNode`] type associated with a [`Function`]
pub type INodeOfFunc<'id, F> = <<F as Function>::Manager<'id> as Manager>::InnerNode;
/// Function in a decision diagram
///
/// A function is some kind of external reference to a node as opposed to
/// [`Edge`]s, which are diagram internal. A function also includes a reference
/// to the diagram's manager. So one may view a function as an [`Edge`] plus a
/// [`ManagerRef`].
///
/// Functions are what the library's user mostly works with. There may be
/// subtraits such as `BooleanFunction` in the `oxidd-rules-bdd` crate which
/// provide more functionality, in this case applying connectives of boolean
/// logic to other functions.
///
/// For some methods of this trait, there are notes on locking behavior. In a
/// concurrent setting, a manager has some kind of read/write lock, and
/// [`Self::with_manager_shared()`] / [`Self::with_manager_exclusive()`] acquire
/// this lock accordingly. In a sequential implementation, a
/// [`RefCell`][std::cell::RefCell] or the like may be used instead of lock.
///
/// # Safety
///
/// An implementation must ensure that the "[`Edge`] part" of the function
/// points to a node that is stored in the manager referenced by the
/// "[`ManagerRef`] part" of the function. All functions of this trait must
/// maintain this link accordingly. In particular, [`Self::as_edge()`] and
/// [`Self::into_edge()`] must panic as specified there.
pub unsafe trait Function: Clone + Ord + Hash {
/// Type of the associated manager
///
/// This type is generic over a lifetime `'id` to permit the "lifetime
/// trick" used, e.g., in [`GhostCell`][GhostCell]: The idea is to make the
/// [`Manager`], [`Edge`] and [`InnerNode`] types [invariant][variance] over
/// `'id`. Any call to one of the
/// [`with_manager_shared()`][Function::with_manager_shared] /
/// [`with_manager_exclusive()`][Function::with_manager_exclusive] functions
/// of the [`Function`] or [`ManagerRef`] trait, which "generate" a fresh
/// lifetime `'id`. Now the type system ensures that every edge or node with
/// `'id` comes belongs to the manager from the `with_manager_*()` call.
/// This means that we can reduce the amount of runtime checks needed to
/// uphold the invariant that the children of a node stored in [`Manager`] M
/// are stored in M as well.
///
/// Note that [`Function`] and [`ManagerRef`] are (typically) outside the
/// scope of this lifetime trick to make the library more flexible.
///
/// [GhostCell]: https://plv.mpi-sws.org/rustbelt/ghostcell/
/// [variance]: https://doc.rust-lang.org/reference/subtyping.html
type Manager<'id>: Manager;
/// [Manager references][ManagerRef] for [`Self::Manager`]
type ManagerRef: for<'id> ManagerRef<Manager<'id> = Self::Manager<'id>>;
/// Create a new function from a manager reference and an edge
fn from_edge<'id>(manager: &Self::Manager<'id>, edge: EdgeOfFunc<'id, Self>) -> Self;
/// Create a new function from a manager reference and an edge reference
#[inline(always)]
fn from_edge_ref<'id>(manager: &Self::Manager<'id>, edge: &EdgeOfFunc<'id, Self>) -> Self {
Self::from_edge(manager, manager.clone_edge(edge))
}
/// Converts this function into the underlying edge (as reference), checking
/// that it belongs to the given `manager`
///
/// Panics if the function does not belong to `manager`.
fn as_edge<'id>(&self, manager: &Self::Manager<'id>) -> &EdgeOfFunc<'id, Self>;
/// Converts this function into the underlying edge, checking that it
/// belongs to the given `manager`
///
/// Panics if the function does not belong to `manager`.
fn into_edge<'id>(self, manager: &Self::Manager<'id>) -> EdgeOfFunc<'id, Self>;
/// Clone the [`ManagerRef`] part
fn manager_ref(&self) -> Self::ManagerRef;
/// Obtain a shared manager reference as well as the underlying edge
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// # Example
///
/// ```
/// # use oxidd_core::function::Function;
/// fn my_eq<F: Function>(f: &F, g: &F) -> bool {
/// f.with_manager_shared(|manager, f_edge| {
/// // Do something meaningful with `manager` and `edge` (the following
/// // is better done using `f == g` without `with_manager_shared()`)
/// let g_edge = g.as_edge(manager);
/// f_edge == g_edge
/// })
/// }
/// ```
fn with_manager_shared<F, T>(&self, f: F) -> T
where
F: for<'id> FnOnce(&Self::Manager<'id>, &EdgeOfFunc<'id, Self>) -> T;
/// Obtain an exclusive manager reference as well as the underlying edge
///
/// Locking behavior: acquires the manager's lock for exclusive access.
///
/// # Example
///
/// ```
/// # use oxidd_core::{*, function::Function, util::AllocResult};
/// /// Adds a binary node on a new level with children `f` and `g`
/// fn foo<F: Function>(f: &F, g: &F) -> AllocResult<F> {
/// f.with_manager_exclusive(|manager, f_edge| {
/// let fe = manager.clone_edge(f_edge);
/// let ge = manager.clone_edge(g.as_edge(manager));
/// let he = manager.add_level(|level| InnerNode::new(level, [fe, ge]))?;
/// Ok(F::from_edge(manager, he))
/// })
/// }
/// ```
fn with_manager_exclusive<F, T>(&self, f: F) -> T
where
F: for<'id> FnOnce(&mut Self::Manager<'id>, &EdgeOfFunc<'id, Self>) -> T;
/// Count the number of nodes in this function, including terminal nodes
///
/// Locking behavior: acquires the manager's lock for shared access.
fn node_count(&self) -> usize {
fn inner<M: Manager>(manager: &M, e: &M::Edge, set: &mut M::NodeSet) {
if set.insert(e) {
if let Node::Inner(node) = manager.get_node(e) {
for e in node.children() {
inner(manager, &*e, set)
}
}
}
}
self.with_manager_shared(|manager, edge| {
let mut set = Default::default();
inner(manager, edge, &mut set);
set.len()
})
}
}
/// Substitution extension for [`Function`]
pub trait FunctionSubst: Function {
/// Substitute variables in `self` according to `substitution`
///
/// The substitution is performed in a parallel fashion, e.g.:
/// `(¬x ∧ ¬y)[x ↦ ¬x ∧ ¬y, y ↦ ⊥] = ¬(¬x ∧ ¬y) ∧ ¬⊥ = x ∨ y`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and the function in `substitution` don't belong to the
/// same manager.
fn substitute<'a>(
&'a self,
substitution: impl Substitution<Var = &'a Self, Replacement = &'a Self>,
) -> AllocResult<Self> {
if substitution.pairs().len() == 0 {
return Ok(self.clone());
}
self.with_manager_shared(|manager, edge| {
Ok(Self::from_edge(
manager,
Self::substitute_edge(
manager,
edge,
substitution.map(|(v, r)| {
(v.as_edge(manager).borrowed(), r.as_edge(manager).borrowed())
}),
)?,
))
})
}
/// `Edge` version of [`Self::substitute()`]
#[must_use]
fn substitute_edge<'id, 'a>(
manager: &'a Self::Manager<'id>,
edge: &'a EdgeOfFunc<'id, Self>,
substitution: impl Substitution<
Var = Borrowed<'a, EdgeOfFunc<'id, Self>>,
Replacement = Borrowed<'a, EdgeOfFunc<'id, Self>>,
>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
}
/// Boolean functions 𝔹ⁿ → 𝔹
///
/// As a user of this trait, you are probably most interested in methods like
/// [`Self::not()`], [`Self::and()`], and [`Self::or()`]. As an implementor, it
/// suffices to implement the functions operating on edges.
pub trait BooleanFunction: Function {
/// Get the always false function `⊥`
fn f<'id>(manager: &Self::Manager<'id>) -> Self {
Self::from_edge(manager, Self::f_edge(manager))
}
/// Get the always true function `⊤`
fn t<'id>(manager: &Self::Manager<'id>) -> Self {
Self::from_edge(manager, Self::t_edge(manager))
}
/// Get a fresh variable, i.e., a function that is true if and only if the
/// variable is true. This adds a new level to a decision diagram.
fn new_var<'id>(manager: &mut Self::Manager<'id>) -> AllocResult<Self>;
/// Get the cofactors `(f_true, f_false)` of `self`
///
/// Let f(x₀, …, xₙ) be represented by `self`, where x₀ is (currently) the
/// top-most variable. Then f<sub>true</sub>(x₁, …, xₙ) = f(⊤, x₁, …, xₙ)
/// and f<sub>false</sub>(x₁, …, xₙ) = f(⊥, x₁, …, xₙ).
///
/// Note that the domain of f is 𝔹ⁿ⁺¹ while the domain of f<sub>true</sub>
/// and f<sub>false</sub> is 𝔹ⁿ. This is irrelevant in case of BDDs and
/// BCDDs, but not for ZBDDs: For instance, g(x₀) = x₀ and g'(x₀, x₁) = x₀
/// have the same representation as BDDs or BCDDs, but different
/// representations as ZBDDs.
///
/// Structurally, the cofactors are simply the children in case of BDDs and
/// ZBDDs. (For BCDDs, the edge tags are adjusted accordingly.) On these
/// representations, runtime is thus in O(1).
///
/// Returns `None` iff `self` references a terminal node. If you only need
/// `f_true` or `f_false`, [`Self::cofactor_true`] or
/// [`Self::cofactor_false`] are slightly more efficient.
///
/// Locking behavior: acquires the manager's lock for shared access.
fn cofactors(&self) -> Option<(Self, Self)> {
self.with_manager_shared(|manager, f| {
let (ft, ff) = Self::cofactors_edge(manager, f)?;
Some((
Self::from_edge_ref(manager, &ft),
Self::from_edge_ref(manager, &ff),
))
})
}
/// Get the cofactor `f_true` of `self`
///
/// This method is slightly more efficient than [`Self::cofactors`] in case
/// `f_false` is not needed.
///
/// For a more detailed description, see [`Self::cofactors`].
///
/// Returns `None` iff `self` references a terminal node.
///
/// Locking behavior: acquires the manager's lock for shared access.
fn cofactor_true(&self) -> Option<Self> {
self.with_manager_shared(|manager, f| {
let (ft, _) = Self::cofactors_edge(manager, f)?;
Some(Self::from_edge_ref(manager, &ft))
})
}
/// Get the cofactor `f_false` of `self`
///
/// This method is slightly more efficient than [`Self::cofactors`] in case
/// `f_true` is not needed.
///
/// For a more detailed description, see [`Self::cofactors`].
///
/// Returns `None` iff `self` references a terminal node.
///
/// Locking behavior: acquires the manager's lock for shared access.
fn cofactor_false(&self) -> Option<Self> {
self.with_manager_shared(|manager, f| {
let (_, ff) = Self::cofactors_edge(manager, f)?;
Some(Self::from_edge_ref(manager, &ff))
})
}
/// Compute the negation `¬self`
///
/// Locking behavior: acquires the manager's lock for shared access.
fn not(&self) -> AllocResult<Self> {
self.with_manager_shared(|manager, edge| {
Ok(Self::from_edge(manager, Self::not_edge(manager, edge)?))
})
}
/// Compute the negation `¬self`, owned version
///
/// Compared to [`Self::not()`], this method does not need to clone the
/// function, so when the implementation is using (e.g.) complemented edges,
/// this might be a little bit faster than [`Self::not()`].
///
/// Locking behavior: acquires the manager's lock for shared access.
fn not_owned(self) -> AllocResult<Self> {
self.not()
}
/// Compute the conjunction `self ∧ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn and(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::and_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the disjunction `self ∨ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn or(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::or_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the negated conjunction `self ⊼ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn nand(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::nand_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the negated disjunction `self ⊽ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn nor(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::nor_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the exclusive disjunction `self ⊕ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn xor(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::xor_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the equivalence `self ↔ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn equiv(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::equiv_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the implication `self → rhs` (or `self ≤ rhs`)
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn imp(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::imp_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the strict implication `self < rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn imp_strict(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::imp_strict_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Get the always false function `⊥` as edge
fn f_edge<'id>(manager: &Self::Manager<'id>) -> EdgeOfFunc<'id, Self>;
/// Get the always true function `⊤` as edge
fn t_edge<'id>(manager: &Self::Manager<'id>) -> EdgeOfFunc<'id, Self>;
/// Get the cofactors `(f_true, f_false)` of `f`, edge version
///
/// Returns `None` iff `f` references a terminal node. For more details on
/// the semantics of `f_true` and `f_false`, see [`Self::cofactors`].
#[inline]
#[allow(clippy::type_complexity)]
fn cofactors_edge<'a, 'id>(
manager: &'a Self::Manager<'id>,
f: &'a EdgeOfFunc<'id, Self>,
) -> Option<(
Borrowed<'a, EdgeOfFunc<'id, Self>>,
Borrowed<'a, EdgeOfFunc<'id, Self>>,
)> {
if let Node::Inner(node) = manager.get_node(f) {
Some(Self::cofactors_node(f.tag(), node))
} else {
None
}
}
/// Get the cofactors `(f_true, f_false)` of `node`, assuming an incoming
/// edge with `EdgeTag`
///
/// Returns `None` iff `f` references a terminal node. For more details on
/// the semantics of `f_true` and `f_false`, see [`Self::cofactors`].
///
/// Implementation note: The default implementation assumes that
/// [cofactor 0][DiagramRules::cofactor] corresponds to `f_true` and
/// [cofactor 1][DiagramRules::cofactor] corresponds to `f_false`.
#[inline]
fn cofactors_node<'a, 'id>(
tag: ETagOfFunc<'id, Self>,
node: &'a INodeOfFunc<'id, Self>,
) -> (
Borrowed<'a, EdgeOfFunc<'id, Self>>,
Borrowed<'a, EdgeOfFunc<'id, Self>>,
) {
let cofactor = <<Self::Manager<'id> as Manager>::Rules as DiagramRules<_, _, _>>::cofactor;
(cofactor(tag, node, 0), cofactor(tag, node, 1))
}
/// Compute the negation `¬edge`, edge version
#[must_use]
fn not_edge<'id>(
manager: &Self::Manager<'id>,
edge: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the negation `¬edge`, owned edge version
///
/// Compared to [`Self::not_edge()`], this method does not need to clone the
/// edge, so when the implementation is using (e.g.) complemented edges,
/// this might be a little bit faster than [`Self::not_edge()`].
#[must_use]
fn not_edge_owned<'id>(
manager: &Self::Manager<'id>,
edge: EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>> {
Self::not_edge(manager, &edge)
}
/// Compute the conjunction `lhs ∧ rhs`, edge version
#[must_use]
fn and_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the disjunction `lhs ∨ rhs`, edge version
#[must_use]
fn or_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the negated conjunction `lhs ⊼ rhs`, edge version
#[must_use]
fn nand_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the negated disjunction `lhs ⊽ rhs`, edge version
#[must_use]
fn nor_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the exclusive disjunction `lhs ⊕ rhs`, edge version
#[must_use]
fn xor_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the equivalence `lhs ↔ rhs`, edge version
#[must_use]
fn equiv_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the implication `lhs → rhs`, edge version
#[must_use]
fn imp_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the strict implication `lhs < rhs`, edge version
#[must_use]
fn imp_strict_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Returns `true` iff `self` is satisfiable, i.e. is not `⊥`
///
/// Locking behavior: acquires the manager's lock for shared access.
fn satisfiable(&self) -> bool {
self.with_manager_shared(|manager, edge| {
let f = EdgeDropGuard::new(manager, Self::f_edge(manager));
edge != &*f
})
}
/// Returns `true` iff `self` is valid, i.e. is `⊤`
///
/// Locking behavior: acquires the manager's lock for shared access.
fn valid(&self) -> bool {
self.with_manager_shared(|manager, edge| {
let t = EdgeDropGuard::new(manager, Self::t_edge(manager));
edge == &*t
})
}
/// Compute `if self { then_case } else { else_case }`
///
/// This is equivalent to `(self ∧ then_case) ∨ (¬self ∧ else_case)` but
/// possibly more efficient than computing all the
/// conjunctions/disjunctions.
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self`, `then_case`, and `else_case` don't belong to the same
/// manager.
fn ite(&self, then_case: &Self, else_case: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, if_edge| {
let then_edge = then_case.as_edge(manager);
let else_edge = else_case.as_edge(manager);
let res = Self::ite_edge(manager, if_edge, then_edge, else_edge)?;
Ok(Self::from_edge(manager, res))
})
}
/// Compute `if if_edge { then_edge } else { else_edge }` (edge version)
///
/// This is equivalent to `(self ∧ then_case) ∨ (¬self ∧ else_case)` but
/// possibly more efficient than computing all the
/// conjunctions/disjunctions.
#[must_use]
fn ite_edge<'id>(
manager: &Self::Manager<'id>,
if_edge: &EdgeOfFunc<'id, Self>,
then_edge: &EdgeOfFunc<'id, Self>,
else_edge: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>> {
let f = EdgeDropGuard::new(manager, Self::and_edge(manager, if_edge, then_edge)?);
let g = EdgeDropGuard::new(manager, Self::imp_strict_edge(manager, if_edge, else_edge)?);
Self::or_edge(manager, &*f, &*g)
}
/// Count the number of satisfying assignments, assuming `vars` input
/// variables
///
/// The `cache` can be used to speed up multiple model counting operations
/// for functions in the same decision diagram. If the model counts of just
/// one function are of interest, one may simply pass an empty
/// [`SatCountCache`] (using `&mut SatCountCache::default()`). The cache
/// will automatically be invalidated in case there have been reordering
/// operations or `vars` changed since the last query (see
/// [`SatCountCache::clear_if_invalid()`]). Still, it is the caller's
/// responsibility to not use the cache for different managers.
///
/// Locking behavior: acquires the manager's lock for shared access.
fn sat_count<N: SatCountNumber, S: std::hash::BuildHasher>(
&self,
vars: LevelNo,
cache: &mut SatCountCache<N, S>,
) -> N {
self.with_manager_shared(|manager, edge| Self::sat_count_edge(manager, edge, vars, cache))
}
/// `Edge` version of [`Self::sat_count()`]
fn sat_count_edge<'id, N: SatCountNumber, S: std::hash::BuildHasher>(
manager: &Self::Manager<'id>,
edge: &EdgeOfFunc<'id, Self>,
vars: LevelNo,
cache: &mut SatCountCache<N, S>,
) -> N;
/// Pick a cube of this function
///
/// A cube `c` of a function `f` is a satisfying assignment, i.e., `c → f`
/// holds, and can be represented as a conjunction of literals. It does
/// not necessarily define all variables in the function's domain (it is
/// not necessarily a canonical minterm). For most (if not all) kinds of
/// decision diagrams, cubes have at most one node per level.
///
/// `order` is a list of variables. If it is non-empty, it must contain as
/// many variables as there are levels.
///
/// Returns `None` if the function is false. Otherwise, this method returns
/// a vector where the i-th entry indicates if the i-th variable of `order`
/// (or the variable currently at the i-th level in case `order` is empty)
/// is true, false, or "don't care".
///
/// Whenever a value for a variable needs to be chosen (i.e., it cannot be
/// left as a don't care), `choice` is called to determine the valuation for
/// this variable. The argument of type [`LevelNo`] is the level
/// corresponding to that variable. It is guaranteed that `choice` will
/// only be called at most once for each level. The [`Edge`] argument is
/// guaranteed to point to an inner node at the respective level. (We
/// pass an [`Edge`] and not an [`InnerNode`] reference since [`Edge`]s
/// provide more information, e.g., the [`NodeID`][Edge::node_id()].)
///
/// Locking behavior: acquires the manager's lock for shared access.
fn pick_cube<'a, I: ExactSizeIterator<Item = &'a Self>>(
&'a self,
order: impl IntoIterator<IntoIter = I>,
choice: impl for<'id> FnMut(&Self::Manager<'id>, &EdgeOfFunc<'id, Self>, LevelNo) -> bool,
) -> Option<Vec<OptBool>> {
self.with_manager_shared(|manager, edge| {
Self::pick_cube_edge(
manager,
edge,
order.into_iter().map(|f| f.as_edge(manager)),
choice,
)
})
}
/// Pick a symbolic cube of this function, i.e., as decision diagram
///
/// A cube `c` of a function `f` is a satisfying assignment, i.e., `c → f`
/// holds, and can be represented as a conjunction of literals. It does
/// not necessarily define all variables in the function's domain (it is
/// not necessarily a canonical minterm). For most (if not all) kinds of
/// decision diagrams, cubes have at most one node per level.
///
/// Whenever a value for a variable needs to be chosen (i.e., it cannot be
/// left as a don't care), `choice` is called to determine the valuation for
/// this variable. The argument of type [`LevelNo`] is the level
/// corresponding to that variable. It is guaranteed that `choice` will
/// only be called at most once for each level. The [`Edge`] argument is
/// guaranteed to point to an inner node at the respective level. (We
/// pass an [`Edge`] and not an [`InnerNode`] reference since [`Edge`]s
/// provide more information, e.g., the [`NodeID`][Edge::node_id()].)
///
/// If `self` is `⊥`, then the return value will be `⊥`.
///
/// Locking behavior: acquires the manager's lock for shared access.
fn pick_cube_dd(
&self,
choice: impl for<'id> FnMut(&Self::Manager<'id>, &EdgeOfFunc<'id, Self>, LevelNo) -> bool,
) -> AllocResult<Self> {
self.with_manager_shared(|manager, edge| {
let res = Self::pick_cube_dd_edge(manager, edge, choice)?;
Ok(Self::from_edge(manager, res))
})
}
/// Pick a symbolic cube of this function, i.e., as decision diagram, using
/// the literals in `literal_set` if there is a choice
///
/// A cube `c` of a function `f` is a satisfying assignment, i.e., `c → f`
/// holds, and can be represented as a conjunction of literals. It does
/// not necessarily define all variables in the function's domain (it is
/// not necessarily a canonical minterm). For most (if not all) kinds of
/// decision diagrams, cubes have at most one node per level.
///
/// `literal_set` is represented as a conjunction of literals. Whenever
/// there is a choice for a variable, it will be set to true if the variable
/// has a positive occurrence in `literal_set`, and set to false if it
/// occurs negated in `literal_set`. If the variable does not occur in
/// `literal_set`, then it will be left as don't care if possible, otherwise
/// an arbitrary (not necessarily random) choice will be performed.
///
/// If `self` is `⊥`, then the return value will be `⊥`.
///
/// Locking behavior: acquires the manager's lock for shared access.
fn pick_cube_dd_set(&self, literal_set: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, edge| {
let res = Self::pick_cube_dd_set_edge(manager, edge, literal_set.as_edge(manager))?;
Ok(Self::from_edge(manager, res))
})
}
/// `Edge` version of [`Self::pick_cube()`]
fn pick_cube_edge<'id, 'a, I>(
manager: &'a Self::Manager<'id>,
edge: &'a EdgeOfFunc<'id, Self>,
order: impl IntoIterator<IntoIter = I>,
choice: impl FnMut(&Self::Manager<'id>, &EdgeOfFunc<'id, Self>, LevelNo) -> bool,
) -> Option<Vec<OptBool>>
where
I: ExactSizeIterator<Item = &'a EdgeOfFunc<'id, Self>>;
/// `Edge` version of [`Self::pick_cube_dd()`]
fn pick_cube_dd_edge<'id>(
manager: &Self::Manager<'id>,
edge: &EdgeOfFunc<'id, Self>,
choice: impl FnMut(&Self::Manager<'id>, &EdgeOfFunc<'id, Self>, LevelNo) -> bool,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// `Edge` version of [`Self::pick_cube_dd_set()`]
fn pick_cube_dd_set_edge<'id>(
manager: &Self::Manager<'id>,
edge: &EdgeOfFunc<'id, Self>,
literal_set: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Pick a random cube of this function, where each cube has the same
/// probability of being chosen
///
/// `order` is a list of variables. If it is non-empty, it must contain as
/// many variables as there are levels.
///
/// Returns `None` if the function is false. Otherwise, this method returns
/// a vector where the i-th entry indicates if the i-th variable of `order`
/// (or the variable currently at the i-th level in case `order` is empty)
/// is true, false, or "don't care". To obtain a total valuation from this
/// partial valuation, it suffices to pick true or false with probability ½.
/// (Note that this function returns a partial valuation with n "don't
/// cares" with a probability that is 2<sup>n</sup> as high as the
/// probability of any total valuation.)
///
/// Locking behavior: acquires the manager's lock for shared access.
fn pick_cube_uniform<'a, I: ExactSizeIterator<Item = &'a Self>, S: BuildHasher>(
&'a self,
order: impl IntoIterator<IntoIter = I>,
cache: &mut SatCountCache<F64, S>,
rng: &mut crate::util::Rng,
) -> Option<Vec<OptBool>> {
self.with_manager_shared(|manager, edge| {
Self::pick_cube_uniform_edge(
manager,
edge,
order.into_iter().map(|f| f.as_edge(manager)),
cache,
rng,
)
})
}
/// `Edge` version of [`Self::pick_cube_uniform()`]
fn pick_cube_uniform_edge<'id, 'a, I, S>(
manager: &'a Self::Manager<'id>,
edge: &'a EdgeOfFunc<'id, Self>,
order: impl IntoIterator<IntoIter = I>,
cache: &mut SatCountCache<F64, S>,
rng: &mut crate::util::Rng,
) -> Option<Vec<OptBool>>
where
I: ExactSizeIterator<Item = &'a EdgeOfFunc<'id, Self>>,
S: BuildHasher,
{
let vars = manager.num_levels();
Self::pick_cube_edge(manager, edge, order, |manager, edge, _| {
let tag = edge.tag();
// `edge` is guaranteed to point to an inner node
let node = manager.get_node(edge).unwrap_inner();
let (t, e) = Self::cofactors_node(tag, node);
let t_count = Self::sat_count_edge(manager, &*t, vars, cache).0;
let e_count = Self::sat_count_edge(manager, &*e, vars, cache).0;
rng.generate::<f64>() < t_count / (t_count + e_count)
})
}
/// Evaluate this Boolean function
///
/// `args` determines the valuation for all variables. Missing values are
/// assumed to be false. However, note that the arguments may also determine
/// the domain, e.g., in case of ZBDDs. If values are specified multiple
/// times, the last one counts. Panics if any function in `args` refers to a
/// terminal node.
///
/// Locking behavior: acquires the manager's lock for shared access.
fn eval<'a>(&'a self, args: impl IntoIterator<Item = (&'a Self, bool)>) -> bool {
self.with_manager_shared(|manager, edge| {
Self::eval_edge(
manager,
edge,
args.into_iter()
.map(|(f, b)| (f.as_edge(manager).borrowed(), b)),
)
})
}
/// `Edge` version of [`Self::eval()`]
fn eval_edge<'id, 'a>(
manager: &'a Self::Manager<'id>,
edge: &'a EdgeOfFunc<'id, Self>,
args: impl IntoIterator<Item = (Borrowed<'a, EdgeOfFunc<'id, Self>>, bool)>,
) -> bool;
}
// The `cfg_attr` below is used such that cbindgen does not output the
// Rust-specific documentation.
/// Binary operators on Boolean functions
#[cfg_attr(
all(),
doc = "
The operators are used by the combined apply and quantification operations of
the [`BooleanFunctionQuant`] trait. The operators themselves correspond to the
ones defined in [`BooleanFunction`]."
)]
#[derive(Copy, Clone, PartialEq, Eq, PartialOrd, Ord, Hash, Debug)]
#[repr(u8)]
pub enum BooleanOperator {
/// Conjunction `lhs ∧ rhs`
And,
/// Disjunction `lhs ∨ rhs`
Or,
/// Exclusive disjunction `lhs ⊕ rhs`
Xor,
/// Equivalence `lhs ↔ rhs`
Equiv,
/// Negated conjunction `lhs ⊼ rhs`
Nand,
/// Negated disjunction `lhs ⊽ rhs`
Nor,
/// Implication `lhs → rhs`
Imp,
/// Strict implication `lhs < rhs`
ImpStrict,
}
/// cbindgen:ignore
unsafe impl crate::Countable for BooleanOperator {
const MAX_VALUE: usize = BooleanOperator::ImpStrict as usize;
fn as_usize(self) -> usize {
self as usize
}
fn from_usize(value: usize) -> Self {
use BooleanOperator::*;
match () {
_ if value == And as usize => And,
_ if value == Or as usize => Or,
_ if value == Xor as usize => Xor,
_ if value == Equiv as usize => Equiv,
_ if value == Nand as usize => Nand,
_ if value == Nor as usize => Nor,
_ if value == Imp as usize => Imp,
_ if value == ImpStrict as usize => ImpStrict,
_ => panic!("{value} does not correspond to a Boolean operator"),
}
}
}
/// cbindgen:ignore
impl Display for BooleanOperator {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
use BooleanOperator::*;
match self {
And => write!(f, "∧"),
Or => write!(f, "∨"),
Xor => write!(f, "⊕"),
Equiv => write!(f, "↔"),
Nand => write!(f, "⊼"),
Nor => write!(f, "⊽"),
Imp => write!(f, "→"),
ImpStrict => write!(f, "<"),
}
}
}
/// Quantification extension for [`BooleanFunction`]
pub trait BooleanFunctionQuant: BooleanFunction {
/// Restrict a set of `vars` to constant values
///
/// `vars` conceptually is a partial assignment, represented as the
/// conjunction of positive or negative literals, depending on whether the
/// variable should be mapped to true or false.
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `vars` don't belong to the same manager.
fn restrict(&self, vars: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, root| {
let e = Self::restrict_edge(manager, root, vars.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the universal quantification over `vars`
///
/// `vars` is a set of variables, which in turn is just the conjunction of
/// the variables. This operation removes all occurrences of the variables
/// by universal quantification. Universal quantification `∀x. f(…, x, …)`
/// of a boolean function `f(…, x, …)` over a single variable `x` is
/// `f(…, 0, …) ∧ f(…, 1, …)`.
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `vars` don't belong to the same manager.
fn forall(&self, vars: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, root| {
let e = Self::forall_edge(manager, root, vars.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the existential quantification over `vars`
///
/// `vars` is a set of variables, which in turn is just the conjunction of
/// the variables. This operation removes all occurrences of the variables
/// by existential quantification. Existential quantification
/// `∃x. f(…, x, …)` of a boolean function `f(…, x, …)` over a single
/// variable `x` is `f(…, 0, …) ∨ f(…, 1, …)`.
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `vars` don't belong to the same manager.
fn exist(&self, vars: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, root| {
let e = Self::exist_edge(manager, root, vars.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the unique quantification over `vars`
///
/// `vars` is a set of variables, which in turn is just the conjunction of
/// the variables. This operation removes all occurrences of the variables
/// by unique quantification. Unique quantification `∃!x. f(…, x, …)` of a
/// boolean function `f(…, x, …)` over a single variable `x` is
/// `f(…, 0, …) ⊕ f(…, 1, …)`.
///
/// Unique quantification is also known as the
/// [Boolean difference](https://en.wikipedia.org/wiki/Boole%27s_expansion_theorem#Operations_with_cofactors)
/// or
/// [Boolean derivative](https://en.wikipedia.org/wiki/Boolean_differential_calculus).
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `vars` don't belong to the same manager.
fn unique(&self, vars: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, root| {
let e = Self::unique_edge(manager, root, vars.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Combined application of `op` and quantification `∀x. self <op> rhs`,
/// where `<op>` is any of the operations from [`BooleanOperator`]
///
/// See also [`Self::forall()`] and the trait [`BooleanFunction`] for more
/// details.
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` and `vars` don't belong to the same manager.
fn apply_forall(&self, op: BooleanOperator, rhs: &Self, vars: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, root| {
let e = Self::apply_forall_edge(
manager,
op,
root,
rhs.as_edge(manager),
vars.as_edge(manager),
)?;
Ok(Self::from_edge(manager, e))
})
}
/// Combined application of `op` and quantification `∃x. self <op> rhs`,
/// where `<op>` is any of the operations from [`BooleanOperator`]
///
/// See also [`Self::exist()`] and the trait [`BooleanFunction`] for more
/// details.
///
/// Panics if `self` and `rhs` and `vars` don't belong to the same manager.
fn apply_exist(&self, op: BooleanOperator, rhs: &Self, vars: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, root| {
let e = Self::apply_exist_edge(
manager,
op,
root,
rhs.as_edge(manager),
vars.as_edge(manager),
)?;
Ok(Self::from_edge(manager, e))
})
}
/// Combined application of `op` and quantification `∃!x. self <op> rhs`,
/// where `<op>` is any of the operations from [`BooleanOperator`]
///
/// See also [`Self::unique()`] and the trait [`BooleanFunction`] for more
/// details.
///
/// Panics if `self` and `rhs` and `vars` don't belong to the same manager.
fn apply_unique(&self, op: BooleanOperator, rhs: &Self, vars: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, root| {
let e = Self::apply_unique_edge(
manager,
op,
root,
rhs.as_edge(manager),
vars.as_edge(manager),
)?;
Ok(Self::from_edge(manager, e))
})
}
/// Restrict a set of `vars` to constant values, edge version
///
/// See [`Self::restrict()`] for more details.
#[must_use]
fn restrict_edge<'id>(
manager: &Self::Manager<'id>,
root: &EdgeOfFunc<'id, Self>,
vars: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the universal quantification of `root` over `vars`, edge
/// version
///
/// See [`Self::forall()`] for more details.
#[must_use]
fn forall_edge<'id>(
manager: &Self::Manager<'id>,
root: &EdgeOfFunc<'id, Self>,
vars: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the existential quantification of `root` over `vars`, edge
/// version
///
/// See [`Self::exist()`] for more details.
#[must_use]
fn exist_edge<'id>(
manager: &Self::Manager<'id>,
root: &EdgeOfFunc<'id, Self>,
vars: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the unique quantification of `root` over `vars`, edge version
///
/// See [`Self::unique()`] for more details.
#[must_use]
fn unique_edge<'id>(
manager: &Self::Manager<'id>,
root: &EdgeOfFunc<'id, Self>,
vars: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Combined application of `op` and forall quantification, edge version
///
/// See [`Self::apply_forall()`] for more details.
#[must_use]
fn apply_forall_edge<'id>(
manager: &Self::Manager<'id>,
op: BooleanOperator,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
vars: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>> {
// Naive default implementation
use BooleanOperator::*;
let inner = EdgeDropGuard::new(
manager,
match op {
And => Self::and_edge(manager, lhs, rhs),
Or => Self::or_edge(manager, lhs, rhs),
Xor => Self::xor_edge(manager, lhs, rhs),
Equiv => Self::equiv_edge(manager, lhs, rhs),
Nand => Self::nand_edge(manager, lhs, rhs),
Nor => Self::nor_edge(manager, lhs, rhs),
Imp => Self::imp_edge(manager, lhs, rhs),
ImpStrict => Self::imp_strict_edge(manager, lhs, rhs),
}?,
);
Self::forall_edge(manager, &inner, vars)
}
/// Combined application of `op` and existential quantification, edge
/// version
///
/// See [`Self::apply_exist()`] for more details.
#[must_use]
fn apply_exist_edge<'id>(
manager: &Self::Manager<'id>,
op: BooleanOperator,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
vars: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>> {
// Naive default implementation
use BooleanOperator::*;
let inner = EdgeDropGuard::new(
manager,
match op {
And => Self::and_edge(manager, lhs, rhs),
Or => Self::or_edge(manager, lhs, rhs),
Xor => Self::xor_edge(manager, lhs, rhs),
Equiv => Self::equiv_edge(manager, lhs, rhs),
Nand => Self::nand_edge(manager, lhs, rhs),
Nor => Self::nor_edge(manager, lhs, rhs),
Imp => Self::imp_edge(manager, lhs, rhs),
ImpStrict => Self::imp_strict_edge(manager, lhs, rhs),
}?,
);
Self::exist_edge(manager, &inner, vars)
}
/// Combined application of `op` and unique quantification, edge version
///
/// See [`Self::apply_unique()`] for more details.
#[must_use]
fn apply_unique_edge<'id>(
manager: &Self::Manager<'id>,
op: BooleanOperator,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
vars: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>> {
// Naive default implementation
use BooleanOperator::*;
let inner = EdgeDropGuard::new(
manager,
match op {
And => Self::and_edge(manager, lhs, rhs),
Or => Self::or_edge(manager, lhs, rhs),
Xor => Self::xor_edge(manager, lhs, rhs),
Equiv => Self::equiv_edge(manager, lhs, rhs),
Nand => Self::nand_edge(manager, lhs, rhs),
Nor => Self::nor_edge(manager, lhs, rhs),
Imp => Self::imp_edge(manager, lhs, rhs),
ImpStrict => Self::imp_strict_edge(manager, lhs, rhs),
}?,
);
Self::unique_edge(manager, &inner, vars)
}
}
/// Set of Boolean vectors
///
/// A Boolean function f: 𝔹ⁿ → 𝔹 may also be regarded as a set S ∈ 𝒫(𝔹ⁿ), where
/// S = {v ∈ 𝔹ⁿ | f(v) = 1}. f is also called the characteristic function of S.
/// We can even view a Boolean vector as a subset of some "Universe" U, so we
/// also have S ∈ 𝒫(𝒫(U)). For example, let U = {a, b, c}. The function a is
/// the set of all sets containing a, {a, ab, abc, ac} (for the sake of
/// readability, we write ab for the set {a, b}). Conversely, the set {a} is the
/// function a ∧ ¬b ∧ ¬c.
///
/// Counting the number of elements in a `BoolVecSet` is equivalent to counting
/// the number of satisfying assignments of its characteristic function. Hence,
/// you may use [`BooleanFunction::sat_count()`] for this task.
///
/// The functions of this trait can be implemented efficiently for ZBDDs.
///
/// As a user of this trait, you are probably most interested in methods like
/// [`Self::union()`], [`Self::intsec()`], and [`Self::diff()`]. As an
/// implementor, it suffices to implement the functions operating on edges.
pub trait BooleanVecSet: Function {
/// Add a new variable to the manager and get the corresponding singleton
/// set
///
/// This adds a new level to the decision diagram.
fn new_singleton<'id>(manager: &mut Self::Manager<'id>) -> AllocResult<Self>;
/// Get the empty set ∅
///
/// This corresponds to the Boolean function ⊥.
fn empty<'id>(manager: &Self::Manager<'id>) -> Self {
Self::from_edge(manager, Self::empty_edge(manager))
}
/// Get the set {∅}
///
/// This corresponds to the Boolean function ¬x₁ ∧ … ∧ ¬xₙ
fn base<'id>(manager: &Self::Manager<'id>) -> Self {
Self::from_edge(manager, Self::base_edge(manager))
}
/// Get the set of subsets of `self` not containing `var`, formally
/// `{s ∈ self | var ∉ s}`
///
/// `var` must be a singleton set, otherwise the result is unspecified.
/// Ideally, the implementation panics.
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `var` do not belong to the same manager.
fn subset0(&self, var: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, set| {
let e = Self::subset0_edge(manager, set, var.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Get the set of subsets of `self` containing `var`, formally
/// `{s ∈ self | var ∈ s}`
///
/// `var` must be a singleton set, otherwise the result is unspecified.
/// Ideally, the implementation panics.
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `var` do not belong to the same manager.
fn subset1(&self, var: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, set| {
let e = Self::subset1_edge(manager, set, var.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Get the set of subsets derived from `self` by adding `var` to the
/// subsets that do not contain `var`, and removing `var` from the subsets
/// that contain `var`, formally
/// `{s ∪ {var} | s ∈ self ∧ var ∉ s} ∪ {s ∖ {var} | s ∈ self ∧ var ∈ s}`
///
/// `var` must be a singleton set, otherwise the result is unspecified.
/// Ideally, the implementation panics.
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `var` do not belong to the same manager.
fn change(&self, var: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, set| {
let e = Self::change_edge(manager, set, var.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the union `self ∪ rhs`
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `rhs` do not belong to the same manager.
fn union(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::union_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the intersection `self ∩ rhs`
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `rhs` do not belong to the same manager.
fn intsec(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::intsec_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the set difference `self ∖ rhs`
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `rhs` do not belong to the same manager.
fn diff(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::diff_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Edge version of [`Self::empty()`]
fn empty_edge<'id>(manager: &Self::Manager<'id>) -> EdgeOfFunc<'id, Self>;
/// Edge version of [`Self::base()`]
fn base_edge<'id>(manager: &Self::Manager<'id>) -> EdgeOfFunc<'id, Self>;
/// Edge version of [`Self::subset0()`]
fn subset0_edge<'id>(
manager: &Self::Manager<'id>,
set: &EdgeOfFunc<'id, Self>,
var: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Edge version of [`Self::subset1()`]
fn subset1_edge<'id>(
manager: &Self::Manager<'id>,
set: &EdgeOfFunc<'id, Self>,
var: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Edge version of [`Self::change()`]
fn change_edge<'id>(
manager: &Self::Manager<'id>,
set: &EdgeOfFunc<'id, Self>,
var: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the union `lhs ∪ rhs`, edge version
fn union_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the intersection `lhs ∩ rhs`, edge version
fn intsec_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the set difference `lhs ∖ rhs`, edge version
fn diff_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
}
/// Basic trait for numbers
///
/// [`zero()`][Self::zero], [`one()`][Self::one], and [`nan()`][Self::nan] are
/// implemented as functions because depending on the number underlying type,
/// it can be hard/impossible to obtain a `const` for these values.
/// This trait also includes basic arithmetic methods. This is to avoid cloning
/// of big integers. We could also require `&Self: Add<&Self, Output = Self>`
/// etc., but this would lead to ugly trait bounds.
///
/// Used by [`PseudoBooleanFunction::Number`]
pub trait NumberBase: Clone + Eq + Hash + PartialOrd {
/// Get the value 0
fn zero() -> Self;
/// Get the value 1
fn one() -> Self;
/// Get the value "not a number," e.g. the result of a division 0/0.
///
/// `Self::nan() == Self::nan()` should evaluate to `true`.
fn nan() -> Self;
/// Returns `true` iff `self == Self::zero()`
fn is_zero(&self) -> bool {
self == &Self::zero()
}
/// Returns `true` iff `self == Self::one()`
fn is_one(&self) -> bool {
self == &Self::one()
}
/// Returns `true` iff `self == Self::nan()`
fn is_nan(&self) -> bool {
self == &Self::nan()
}
/// Compute `self + rhs`
fn add(&self, rhs: &Self) -> Self;
/// Compute `self - rhs`
fn sub(&self, rhs: &Self) -> Self;
/// Compute `self * rhs`
fn mul(&self, rhs: &Self) -> Self;
/// Compute `self / rhs`
fn div(&self, rhs: &Self) -> Self;
}
/// Pseudo-Boolean function 𝔹ⁿ → ℝ
pub trait PseudoBooleanFunction: Function {
/// The number type used for the functions' target set.
type Number: NumberBase;
/// Get the constant `value`
fn constant<'id>(manager: &Self::Manager<'id>, value: Self::Number) -> AllocResult<Self> {
Ok(Self::from_edge(
manager,
Self::constant_edge(manager, value)?,
))
}
/// Get a fresh variable, i.e. a function that is 1 if the variable is true
/// and 0 otherwise. This adds a new level to a decision diagram.
fn new_var<'id>(manager: &mut Self::Manager<'id>) -> AllocResult<Self>;
/// Point-wise addition `self + rhs`
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `rhs` do not belong to the same manager.
fn add(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::add_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Point-wise subtraction `self - rhs`
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `rhs` do not belong to the same manager.
fn sub(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::sub_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Point-wise multiplication `self * rhs`
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `rhs` do not belong to the same manager.
fn mul(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::mul_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Point-wise division `self / rhs`
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `rhs` do not belong to the same manager.
fn div(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::div_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Point-wise minimum `min(self, rhs)`
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `rhs` do not belong to the same manager.
fn min(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::min_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Point-wise maximum `max(self, rhs)`
///
/// Locking behavior: acquires a shared manager lock
///
/// Panics if `self` and `rhs` do not belong to the same manager.
fn max(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::max_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Get the constant `value`, edge version
fn constant_edge<'id>(
manager: &Self::Manager<'id>,
value: Self::Number,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Point-wise addition `self + rhs`, edge version
fn add_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Point-wise subtraction `self - rhs`, edge version
fn sub_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Point-wise multiplication `self * rhs`, edge version
fn mul_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Point-wise division `self / rhs`, edge version
fn div_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Point-wise minimum `min(self, rhs)`, edge version
fn min_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Point-wise maximum `max(self, rhs)`, edge version
fn max_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
}
/// Function of three valued logic
pub trait TVLFunction: Function {
/// Get the always false function `⊥`
fn f<'id>(manager: &Self::Manager<'id>) -> Self {
Self::from_edge(manager, Self::f_edge(manager))
}
/// Get the always true function `⊤`
fn t<'id>(manager: &Self::Manager<'id>) -> Self {
Self::from_edge(manager, Self::t_edge(manager))
}
/// Get the "unknown" function `U`
fn u<'id>(manager: &Self::Manager<'id>) -> Self {
Self::from_edge(manager, Self::t_edge(manager))
}
/// Get the cofactors `(f_true, f_unknown, f_false)` of `self`
///
/// Let f(x₀, …, xₙ) be represented by `self`, where x₀ is (currently) the
/// top-most variable. Then f<sub>true</sub>(x₁, …, xₙ) = f(⊤, x₁, …, xₙ)
/// and f<sub>false</sub>(x₁, …, xₙ) = f(⊥, x₁, …, xₙ).
///
/// Note that the domain of f is 𝔹ⁿ⁺¹ while the domain of f<sub>true</sub>
/// and f<sub>false</sub> is 𝔹ⁿ.
///
/// Returns `None` iff `self` references a terminal node. If you only need
/// `f_true`, `f_unknown`, or `f_false`, [`Self::cofactor_true`],
/// [`Self::cofactor_unknown`], or [`Self::cofactor_false`] are slightly
/// more efficient.
///
/// Locking behavior: acquires the manager's lock for shared access.
fn cofactors(&self) -> Option<(Self, Self, Self)> {
self.with_manager_shared(|manager, f| {
let (ft, fu, ff) = Self::cofactors_edge(manager, f)?;
Some((
Self::from_edge_ref(manager, &ft),
Self::from_edge_ref(manager, &fu),
Self::from_edge_ref(manager, &ff),
))
})
}
/// Get the cofactor `f_true` of `self`
///
/// This method is slightly more efficient than [`Self::cofactors`] in case
/// `f_unknown` and `f_false` are not needed.
///
/// For a more detailed description, see [`Self::cofactors`].
///
/// Returns `None` iff `self` references a terminal node.
///
/// Locking behavior: acquires the manager's lock for shared access.
fn cofactor_true(&self) -> Option<Self> {
self.with_manager_shared(|manager, f| {
let (ft, _, _) = Self::cofactors_edge(manager, f)?;
Some(Self::from_edge_ref(manager, &ft))
})
}
/// Get the cofactor `f_unknown` of `self`
///
/// This method is slightly more efficient than [`Self::cofactors`] in case
/// `f_true` and `f_false` are not needed.
///
/// For a more detailed description, see [`Self::cofactors`].
///
/// Returns `None` iff `self` references a terminal node.
///
/// Locking behavior: acquires the manager's lock for shared access.
fn cofactor_unknown(&self) -> Option<Self> {
self.with_manager_shared(|manager, f| {
let (_, fu, _) = Self::cofactors_edge(manager, f)?;
Some(Self::from_edge_ref(manager, &fu))
})
}
/// Get the cofactor `f_false` of `self`
///
/// This method is slightly more efficient than [`Self::cofactors`] in case
/// `f_true` and `f_unknown` are not needed.
///
/// For a more detailed description, see [`Self::cofactors`].
///
/// Returns `None` iff `self` references a terminal node.
///
/// Locking behavior: acquires the manager's lock for shared access.
fn cofactor_false(&self) -> Option<Self> {
self.with_manager_shared(|manager, f| {
let (_, _, ff) = Self::cofactors_edge(manager, f)?;
Some(Self::from_edge_ref(manager, &ff))
})
}
/// Get a fresh variable, i.e. a function that is true if the variable is
/// true, false if the variable is false, and undefined otherwise. This adds
/// a new level to a decision diagram.
fn new_var<'id>(manager: &mut Self::Manager<'id>) -> AllocResult<Self>;
/// Compute the negation `¬self`
///
/// Locking behavior: acquires the manager's lock for shared access.
fn not(&self) -> AllocResult<Self> {
self.with_manager_shared(|manager, edge| {
Ok(Self::from_edge(manager, Self::not_edge(manager, edge)?))
})
}
/// Compute the negation `¬self`, owned version
///
/// Compared to [`Self::not()`], this method does not need to clone the
/// function, so when the implementation is using (e.g.) complemented edges,
/// this might be a little bit faster than [`Self::not()`].
///
/// Locking behavior: acquires the manager's lock for shared access.
fn not_owned(self) -> AllocResult<Self> {
self.not()
}
/// Compute the conjunction `self ∧ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn and(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::and_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the disjunction `self ∨ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn or(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::or_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the negated conjunction `self ⊼ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn nand(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::nand_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the negated disjunction `self ⊽ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn nor(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::nor_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the exclusive disjunction `self ⊕ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn xor(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::xor_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the equivalence `self ↔ rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn equiv(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::equiv_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the implication `self → rhs` (or `self ≤ rhs`)
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn imp(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::imp_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Compute the strict implication `self < rhs`
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self` and `rhs` don't belong to the same manager.
fn imp_strict(&self, rhs: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, lhs| {
let e = Self::imp_strict_edge(manager, lhs, rhs.as_edge(manager))?;
Ok(Self::from_edge(manager, e))
})
}
/// Get the always false function `⊥` as edge
fn f_edge<'id>(manager: &Self::Manager<'id>) -> EdgeOfFunc<'id, Self>;
/// Get the always true function `⊤` as edge
fn t_edge<'id>(manager: &Self::Manager<'id>) -> EdgeOfFunc<'id, Self>;
/// Get the "unknown" function `U` as edge
fn u_edge<'id>(manager: &Self::Manager<'id>) -> EdgeOfFunc<'id, Self>;
/// Get the cofactors `(f_true, f_unknown, f_false)` of `f`, edge version
///
/// Returns `None` iff `f` references a terminal node. For more details on
/// the semantics of `f_true` and `f_false`, see [`Self::cofactors`].
#[inline]
#[allow(clippy::type_complexity)]
fn cofactors_edge<'a, 'id>(
manager: &'a Self::Manager<'id>,
f: &'a EdgeOfFunc<'id, Self>,
) -> Option<(
Borrowed<'a, EdgeOfFunc<'id, Self>>,
Borrowed<'a, EdgeOfFunc<'id, Self>>,
Borrowed<'a, EdgeOfFunc<'id, Self>>,
)> {
if let Node::Inner(node) = manager.get_node(f) {
Some(Self::cofactors_node(f.tag(), node))
} else {
None
}
}
/// Get the cofactors `(f_true, f_unknown, f_false)` of `node`, assuming an
/// incoming edge with `EdgeTag`
///
/// Returns `None` iff `f` references a terminal node. For more details on
/// the semantics of `f_true` and `f_false`, see [`Self::cofactors`].
///
/// Implementation note: The default implementation assumes that
/// [cofactor 0][DiagramRules::cofactor] corresponds to `f_true`,
/// [cofactor 1][DiagramRules::cofactor] corresponds to `f_unknown`, and
/// [cofactor 2][DiagramRules::cofactor] corresponds to `f_false`.
#[inline]
#[allow(clippy::type_complexity)]
fn cofactors_node<'a, 'id>(
tag: ETagOfFunc<'id, Self>,
node: &'a INodeOfFunc<'id, Self>,
) -> (
Borrowed<'a, EdgeOfFunc<'id, Self>>,
Borrowed<'a, EdgeOfFunc<'id, Self>>,
Borrowed<'a, EdgeOfFunc<'id, Self>>,
) {
let cofactor = <<Self::Manager<'id> as Manager>::Rules as DiagramRules<_, _, _>>::cofactor;
(
cofactor(tag, node, 0),
cofactor(tag, node, 1),
cofactor(tag, node, 2),
)
}
/// Compute the negation `¬edge`, edge version
#[must_use]
fn not_edge<'id>(
manager: &Self::Manager<'id>,
edge: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the negation `¬edge`, owned edge version
///
/// Compared to [`Self::not_edge()`], this method does not need to clone the
/// edge, so when the implementation is using (e.g.) complemented edges,
/// this might be a little bit faster than [`Self::not_edge()`].
#[must_use]
fn not_edge_owned<'id>(
manager: &Self::Manager<'id>,
edge: EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>> {
Self::not_edge(manager, &edge)
}
/// Compute the conjunction `lhs ∧ rhs`, edge version
#[must_use]
fn and_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the disjunction `lhs ∨ rhs`, edge version
#[must_use]
fn or_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the negated conjunction `lhs ⊼ rhs`, edge version
#[must_use]
fn nand_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the negated disjunction `lhs ⊽ rhs`, edge version
#[must_use]
fn nor_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the exclusive disjunction `lhs ⊕ rhs`, edge version
#[must_use]
fn xor_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the equivalence `lhs ↔ rhs`, edge version
#[must_use]
fn equiv_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the implication `lhs → rhs`, edge version
#[must_use]
fn imp_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute the strict implication `lhs < rhs`, edge version
#[must_use]
fn imp_strict_edge<'id>(
manager: &Self::Manager<'id>,
lhs: &EdgeOfFunc<'id, Self>,
rhs: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>>;
/// Compute `if self { then_case } else { else_case }`
///
/// This is equivalent to `(self ∧ then_case) ∨ (¬self ∧ else_case)` but
/// possibly more efficient than computing all the
/// conjunctions/disjunctions.
///
/// Locking behavior: acquires the manager's lock for shared access.
///
/// Panics if `self`, `then_case`, and `else_case` don't belong to the same
/// manager.
fn ite(&self, then_case: &Self, else_case: &Self) -> AllocResult<Self> {
self.with_manager_shared(|manager, if_edge| {
let then_edge = then_case.as_edge(manager);
let else_edge = else_case.as_edge(manager);
let res = Self::ite_edge(manager, if_edge, then_edge, else_edge)?;
Ok(Self::from_edge(manager, res))
})
}
/// Compute `if if_edge { then_edge } else { else_edge }` (edge version)
///
/// This is equivalent to `(self ∧ then_case) ∨ (¬self ∧ else_case)` but
/// possibly more efficient than computing all the
/// conjunctions/disjunctions.
#[must_use]
fn ite_edge<'id>(
manager: &Self::Manager<'id>,
if_edge: &EdgeOfFunc<'id, Self>,
then_edge: &EdgeOfFunc<'id, Self>,
else_edge: &EdgeOfFunc<'id, Self>,
) -> AllocResult<EdgeOfFunc<'id, Self>> {
let f = EdgeDropGuard::new(manager, Self::and_edge(manager, if_edge, then_edge)?);
let g = EdgeDropGuard::new(manager, Self::imp_strict_edge(manager, if_edge, else_edge)?);
Self::or_edge(manager, &*f, &*g)
}
}