pyfunctionhood 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pyfunctionhood/__init__.py +9 -0
- pyfunctionhood/clause.py +113 -0
- pyfunctionhood/function.py +101 -0
- pyfunctionhood/hassediagram.py +125 -0
- pyfunctionhood/main.py +182 -0
- pyfunctionhood/powerset.py +82 -0
- pyfunctionhood-0.1.0.dist-info/METADATA +146 -0
- pyfunctionhood-0.1.0.dist-info/RECORD +12 -0
- pyfunctionhood-0.1.0.dist-info/WHEEL +5 -0
- pyfunctionhood-0.1.0.dist-info/entry_points.txt +2 -0
- pyfunctionhood-0.1.0.dist-info/licenses/LICENSE +661 -0
- pyfunctionhood-0.1.0.dist-info/top_level.txt +1 -0
pyfunctionhood/clause.py
ADDED
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
from typing import Set
|
|
2
|
+
from bitarray import bitarray
|
|
3
|
+
|
|
4
|
+
class Clause:
|
|
5
|
+
def __init__(self, signature, size=None) -> None:
|
|
6
|
+
if not signature:
|
|
7
|
+
raise ValueError('Invalid signature!')
|
|
8
|
+
if isinstance(signature, str):
|
|
9
|
+
if any(c not in ('0','1') for c in signature) or \
|
|
10
|
+
(size and size != len(signature)):
|
|
11
|
+
raise ValueError('Invalid signature!')
|
|
12
|
+
self.cardinality = len(signature)
|
|
13
|
+
self.signature = bitarray(signature)
|
|
14
|
+
elif isinstance(signature, bitarray):
|
|
15
|
+
if size and size != len(signature):
|
|
16
|
+
raise ValueError('Invalid signature!')
|
|
17
|
+
self.cardinality = len(signature)
|
|
18
|
+
self.signature = signature.copy()
|
|
19
|
+
elif isinstance(signature, list):
|
|
20
|
+
if not size or not isinstance(size, int) or size < 1 or \
|
|
21
|
+
any((i < 1 or i > size) for i in signature):
|
|
22
|
+
raise ValueError('Invalid signature!')
|
|
23
|
+
self.cardinality = size
|
|
24
|
+
self.signature = bitarray('0' * size)
|
|
25
|
+
for i in signature:
|
|
26
|
+
self.signature[i - 1] = True
|
|
27
|
+
|
|
28
|
+
def clone_add(self, lit: int) -> 'Clause':
|
|
29
|
+
c = Clause(self.signature)
|
|
30
|
+
c.signature[lit] = True
|
|
31
|
+
return c
|
|
32
|
+
|
|
33
|
+
def clone_rm(self, lit: int) -> 'Clause':
|
|
34
|
+
c = Clause(self.signature)
|
|
35
|
+
c.signature[lit] = False
|
|
36
|
+
return c
|
|
37
|
+
|
|
38
|
+
def get_size(self) -> int:
|
|
39
|
+
return self.cardinality
|
|
40
|
+
|
|
41
|
+
def get_signature(self) -> bitarray:
|
|
42
|
+
return self.signature
|
|
43
|
+
|
|
44
|
+
def get_order(self) -> int:
|
|
45
|
+
return self.signature.count()
|
|
46
|
+
|
|
47
|
+
def get_off_literals(self) -> list[int]:
|
|
48
|
+
return [i for i in range(self.cardinality) if not self.signature[i]]
|
|
49
|
+
|
|
50
|
+
def get_on_literals(self) -> list[int]:
|
|
51
|
+
return [i for i in range(self.cardinality) if self.signature[i]]
|
|
52
|
+
|
|
53
|
+
def __hash__(self) -> int:
|
|
54
|
+
""" Hash function for Clause using the signature bit """
|
|
55
|
+
return hash(self.signature.tobytes())
|
|
56
|
+
|
|
57
|
+
def get_containing(self, sClauses: Set['Clause']) -> Set['Clause']:
|
|
58
|
+
return { s for s in sClauses if self <= s }
|
|
59
|
+
|
|
60
|
+
def get_contained(self, sClauses: Set['Clause']) -> Set['Clause']:
|
|
61
|
+
return { s for s in sClauses if s < self }
|
|
62
|
+
|
|
63
|
+
def __eq__(self, other) -> bool:
|
|
64
|
+
return isinstance(other, Clause) and \
|
|
65
|
+
self.cardinality == other.cardinality and \
|
|
66
|
+
self.signature == other.signature
|
|
67
|
+
|
|
68
|
+
def __ne__(self, other) -> bool:
|
|
69
|
+
return not self == other
|
|
70
|
+
|
|
71
|
+
def __ge__(self, c: 'Clause') -> bool:
|
|
72
|
+
if self.cardinality != c.cardinality:
|
|
73
|
+
raise ValueError("Clauses must have the same cardinality!")
|
|
74
|
+
# with list comprehension
|
|
75
|
+
return (~self.signature & c.signature).count() == 0
|
|
76
|
+
|
|
77
|
+
def __gt__(self, c: 'Clause') -> bool:
|
|
78
|
+
if self.cardinality != c.cardinality:
|
|
79
|
+
raise ValueError("Clauses must have the same cardinality!")
|
|
80
|
+
return self >= c and self != c
|
|
81
|
+
|
|
82
|
+
def __le__(self, c: 'Clause') -> bool:
|
|
83
|
+
if self.cardinality != c.cardinality:
|
|
84
|
+
raise ValueError("Clauses must have the same cardinality!")
|
|
85
|
+
return (~c.signature & self.signature).count() == 0
|
|
86
|
+
|
|
87
|
+
def __lt__(self, c: 'Clause') -> bool:
|
|
88
|
+
if self.cardinality != c.cardinality:
|
|
89
|
+
raise ValueError("Clauses must have the same cardinality!")
|
|
90
|
+
return self <= c and self != c
|
|
91
|
+
|
|
92
|
+
def is_independent(self, c: 'Clause') -> bool:
|
|
93
|
+
if self.cardinality != c.cardinality:
|
|
94
|
+
raise ValueError("Clauses must have the same cardinality!")
|
|
95
|
+
return not self>=c and not self<=c
|
|
96
|
+
|
|
97
|
+
def get_subsets(self) -> Set['Clause']:
|
|
98
|
+
return { self.clone_rm(l) for l in self.get_on_literals() }
|
|
99
|
+
|
|
100
|
+
def get_supersets(self) -> Set['Clause']:
|
|
101
|
+
return { self.clone_add(l) for l in self.get_off_literals() }
|
|
102
|
+
|
|
103
|
+
def __str__(self) -> str:
|
|
104
|
+
return "{" + ",".join(str(i + 1) for i in range(self.cardinality) if self.signature[i]) + "}"
|
|
105
|
+
|
|
106
|
+
def __repr__(self) -> str:
|
|
107
|
+
return str(self)
|
|
108
|
+
|
|
109
|
+
def evaluate(self, signs: bitarray, values: bitarray) -> bool:
|
|
110
|
+
# (signs XAND values) AND clause
|
|
111
|
+
# number of 1's must be equal to the number of literals in clause
|
|
112
|
+
return ((~(signs ^ values)) & self.signature).count() == self.signature.count()
|
|
113
|
+
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
from .clause import Clause
|
|
2
|
+
from bitarray import bitarray
|
|
3
|
+
from typing import Set
|
|
4
|
+
|
|
5
|
+
class Function:
|
|
6
|
+
def __init__(self, nvars:int, clauses: Set['Clause']) -> None:
|
|
7
|
+
if not clauses:
|
|
8
|
+
raise ValueError('Empty set of clauses!')
|
|
9
|
+
if nvars <= 0 or any(c.get_size() != nvars for c in clauses):
|
|
10
|
+
raise ValueError('One clause has size !=' + str(nvars)+'!')
|
|
11
|
+
self.nvars = nvars
|
|
12
|
+
self.clauses = clauses
|
|
13
|
+
self.update_consistency()
|
|
14
|
+
|
|
15
|
+
@staticmethod
|
|
16
|
+
def fromString(nvars: int, strClauses: str) -> 'Function':
|
|
17
|
+
strClauses = strClauses.replace(' ', '')
|
|
18
|
+
if not strClauses:
|
|
19
|
+
raise ValueError('Empty function string!')
|
|
20
|
+
clauses = set()
|
|
21
|
+
for strc in strClauses[2:-2].split('},{'):
|
|
22
|
+
if not strc:
|
|
23
|
+
raise ValueError('Empty clause!')
|
|
24
|
+
tmp = '0'*nvars
|
|
25
|
+
for l in strc.split(','):
|
|
26
|
+
tmp = tmp[:int(l)-1] + '1' + tmp[int(l):]
|
|
27
|
+
clauses.add(Clause(tmp))
|
|
28
|
+
return Function(nvars, clauses)
|
|
29
|
+
|
|
30
|
+
def clone_rm_add(self, scRm: Set['Clause'], scAdd: Set['Clause']) -> 'Function':
|
|
31
|
+
f = Function(self.nvars, self.clauses.copy())
|
|
32
|
+
for c in scRm: f.clauses.remove(c)
|
|
33
|
+
for c in scAdd: f.clauses.add(c)
|
|
34
|
+
f.update_consistency()
|
|
35
|
+
return f
|
|
36
|
+
|
|
37
|
+
def add_clause(self, c: 'Clause') -> None:
|
|
38
|
+
self.clauses.add(c)
|
|
39
|
+
self.update_consistency()
|
|
40
|
+
|
|
41
|
+
def get_size(self) -> int:
|
|
42
|
+
""" Returns the number of variables of the function. """
|
|
43
|
+
return self.nvars
|
|
44
|
+
|
|
45
|
+
def get_clauses(self) -> Set['Clause']:
|
|
46
|
+
""" Returns the set of clauses of the function without a copy. """
|
|
47
|
+
return self.clauses
|
|
48
|
+
|
|
49
|
+
def is_consistent(self) -> bool:
|
|
50
|
+
""" Returns True if the function is consistent, False otherwise. """
|
|
51
|
+
return self.consistent
|
|
52
|
+
|
|
53
|
+
def update_consistency(self) -> None:
|
|
54
|
+
self.consistent = self.is_independent() and self.is_cover()
|
|
55
|
+
|
|
56
|
+
def is_independent(self) -> bool:
|
|
57
|
+
return all(c1.is_independent(c2) for c1 in self.clauses for c2 in self.clauses if c1 != c2)
|
|
58
|
+
|
|
59
|
+
def is_cover(self) -> bool:
|
|
60
|
+
bcover = bitarray('0'*self.nvars)
|
|
61
|
+
for c in self.clauses:
|
|
62
|
+
bcover |= c.get_signature()
|
|
63
|
+
return bcover.all()
|
|
64
|
+
|
|
65
|
+
def __eq__(self, other) -> bool:
|
|
66
|
+
return isinstance(other, Function) and \
|
|
67
|
+
self.nvars == other.nvars and \
|
|
68
|
+
self.clauses == other.clauses
|
|
69
|
+
|
|
70
|
+
def __hash__(self) -> int:
|
|
71
|
+
# Combine the hashes of the elements using XOR
|
|
72
|
+
hash_value = 0
|
|
73
|
+
for c in self.clauses:
|
|
74
|
+
hash_value ^= hash(c)
|
|
75
|
+
return hash_value
|
|
76
|
+
|
|
77
|
+
def __str__(self) -> str:
|
|
78
|
+
return '{' + ','.join(sorted([str(c) for c in self.clauses])) + '}'
|
|
79
|
+
|
|
80
|
+
def __repr__(self) -> str:
|
|
81
|
+
return str(self)
|
|
82
|
+
|
|
83
|
+
def evaluate(self, signs: bitarray, values: bitarray) -> bool:
|
|
84
|
+
return any(c.evaluate(signs, values) for c in self.clauses)
|
|
85
|
+
|
|
86
|
+
def get_level(self) -> list[int]:
|
|
87
|
+
return sorted([(self.nvars - c.get_order()) for c in self.clauses], reverse=True)
|
|
88
|
+
|
|
89
|
+
def level_cmp(self, other: 'Function') -> int:
|
|
90
|
+
lself, lother = self.get_level(), other.get_level()
|
|
91
|
+
szself, szother = len(lself), len(lother)
|
|
92
|
+
|
|
93
|
+
# Compare element by element
|
|
94
|
+
for i in range(min(szself, szother)):
|
|
95
|
+
if lself[i] > lother[i]: return 1
|
|
96
|
+
elif lself[i] < lother[i]: return -1
|
|
97
|
+
|
|
98
|
+
if szself < szother: return -1
|
|
99
|
+
elif szself == szother: return 0
|
|
100
|
+
else: return 1
|
|
101
|
+
|
|
@@ -0,0 +1,125 @@
|
|
|
1
|
+
from .clause import Clause
|
|
2
|
+
from .function import Function
|
|
3
|
+
from .powerset import PowerSet
|
|
4
|
+
from typing import Tuple, Set
|
|
5
|
+
|
|
6
|
+
class HasseDiagram:
|
|
7
|
+
# Dedeking number: number of monotone Boolean functions of n variables:
|
|
8
|
+
# https://oeis.org/A000372
|
|
9
|
+
# Number of monotone non-degenerate Boolean functions of n variables:
|
|
10
|
+
# n=2 -> 2 functions
|
|
11
|
+
# n=3 -> 9 functions
|
|
12
|
+
# n=4 -> 114 functions
|
|
13
|
+
# n=5 -> 6 894 functions
|
|
14
|
+
# n=6 -> 7 785 062 functions
|
|
15
|
+
# n=7 -> 2 414 627 396 434 functions
|
|
16
|
+
# n=8 -> 56 130 437 209 370 320 359 966 functions
|
|
17
|
+
# n=9 -> 286 386 577 668 298 410 623 295 216 696 338 374 471 993 functions
|
|
18
|
+
|
|
19
|
+
def __init__(self, nvars: int) -> None:
|
|
20
|
+
self.nvars = nvars
|
|
21
|
+
self.powerset = PowerSet(nvars)
|
|
22
|
+
|
|
23
|
+
def get_infimum(self) -> 'Function':
|
|
24
|
+
""" Returns the infimum of the set of functions. """
|
|
25
|
+
return Function(self.nvars, { Clause('1'*self.nvars) })
|
|
26
|
+
|
|
27
|
+
def get_supremum(self) -> 'Function':
|
|
28
|
+
""" Returns the supremum of the set of functions. """
|
|
29
|
+
return Function(self.nvars,
|
|
30
|
+
{ Clause('0'*i + '1' + '0'*(self.nvars - 1 - i))
|
|
31
|
+
for i in range(self.nvars) } )
|
|
32
|
+
|
|
33
|
+
def get_size(self) -> int:
|
|
34
|
+
""" Returns the number of variables of the Hasse diagram. """
|
|
35
|
+
return self.nvars
|
|
36
|
+
|
|
37
|
+
def get_f_parents(self, f: 'Function') -> Tuple[Set['Function'], Set['Function'], Set['Function']]:
|
|
38
|
+
""" Returns the set of immediate parents of f. """
|
|
39
|
+
s1Parents, s2Parents, s3Parents = set(), set(), set()
|
|
40
|
+
|
|
41
|
+
# Get maximal independent clauses
|
|
42
|
+
sC = self.powerset.get_maximal(self.powerset.get_independent(f.clauses))
|
|
43
|
+
|
|
44
|
+
# Add all parents from the 1st rule
|
|
45
|
+
s1Parents = { f.clone_rm_add(set(), { c }) for c in sC }
|
|
46
|
+
|
|
47
|
+
# Get maximal dominated clauses
|
|
48
|
+
lD = [d for d in self.powerset.get_maximal( \
|
|
49
|
+
self.powerset.get_dominated_directly(f.clauses))\
|
|
50
|
+
if not any([(d<=s) for s in sC])]
|
|
51
|
+
|
|
52
|
+
# Add all parents from the 2nd rule
|
|
53
|
+
sDnotUsed = {}
|
|
54
|
+
for d in lD:
|
|
55
|
+
sContained = d.get_containing(f.clauses)
|
|
56
|
+
fp = f.clone_rm_add(sContained, {d})
|
|
57
|
+
if fp.is_consistent():
|
|
58
|
+
s2Parents.add(fp)
|
|
59
|
+
#print(' fp:',fp,'R2')
|
|
60
|
+
else:
|
|
61
|
+
for s in sContained:
|
|
62
|
+
if s not in sDnotUsed: sDnotUsed[s] = set()
|
|
63
|
+
sDnotUsed[s].add(d)
|
|
64
|
+
|
|
65
|
+
# Add all parents from the 3rd rule
|
|
66
|
+
for s in sDnotUsed:
|
|
67
|
+
lSigmas = list(sDnotUsed[s])
|
|
68
|
+
if len(lSigmas) < 2: # needs at least 2 clauses to be combined
|
|
69
|
+
continue
|
|
70
|
+
for i in range(len(lSigmas)-1):
|
|
71
|
+
for j in range(i + 1, len(lSigmas)):
|
|
72
|
+
# by def only s contains both sigma_i and sigma_j
|
|
73
|
+
fp = f.clone_rm_add({s}, {lSigmas[i],lSigmas[j]})
|
|
74
|
+
# by def no need to test if isCover(fp)
|
|
75
|
+
s3Parents.add(fp)
|
|
76
|
+
#print(' fp:',fp, 'R3')
|
|
77
|
+
|
|
78
|
+
return s1Parents, s2Parents, s3Parents
|
|
79
|
+
|
|
80
|
+
def get_f_children(self, f: 'Function') -> Tuple[Set['Function'], Set['Function'], Set['Function']]:
|
|
81
|
+
""" Returns the set of immediate children of f. """
|
|
82
|
+
s1Children, s2Children, s3Children = set(), set(), set()
|
|
83
|
+
dmergeable = {}
|
|
84
|
+
|
|
85
|
+
# Add all children of the 1st form
|
|
86
|
+
for s in f.clauses:
|
|
87
|
+
bToMerge, bExtendable = False, False
|
|
88
|
+
# Child function to be extended with: s \cup {l_i}
|
|
89
|
+
fs = f.clone_rm_add({s},set())
|
|
90
|
+
for l in s.get_off_literals():
|
|
91
|
+
sl = s.clone_add(l)
|
|
92
|
+
sAbsorbed = sl.get_contained(f.clauses)
|
|
93
|
+
if len(sAbsorbed) == 1:
|
|
94
|
+
bExtendable = True
|
|
95
|
+
fs = fs.clone_rm_add(set(), {sl})
|
|
96
|
+
elif len(sAbsorbed) == 2:
|
|
97
|
+
bToMerge = True
|
|
98
|
+
|
|
99
|
+
if bExtendable:
|
|
100
|
+
s2Children.add(fs)
|
|
101
|
+
#print('fc:',fs, 'R2')
|
|
102
|
+
elif fs.is_consistent():
|
|
103
|
+
s1Children.add(fs)
|
|
104
|
+
#print('fc:',fs, 'R1')
|
|
105
|
+
elif bToMerge:
|
|
106
|
+
# Clauses are only (potentially) mergeable with others of their own size
|
|
107
|
+
sz = s.get_order()
|
|
108
|
+
if sz not in dmergeable: dmergeable[sz] = []
|
|
109
|
+
dmergeable[sz].append(s)
|
|
110
|
+
|
|
111
|
+
for sz in dmergeable:
|
|
112
|
+
lmergeable = dmergeable[sz]
|
|
113
|
+
while lmergeable:
|
|
114
|
+
c = lmergeable[-1]
|
|
115
|
+
fMergeable = Function(f.get_size(), set(lmergeable))
|
|
116
|
+
for l in c.get_off_literals():
|
|
117
|
+
cl = c.clone_add(l)
|
|
118
|
+
sAbsorbed = cl.get_contained(fMergeable.clauses)
|
|
119
|
+
if len(sAbsorbed) == 2:
|
|
120
|
+
fc = f.clone_rm_add(sAbsorbed, {cl})
|
|
121
|
+
s3Children.add(fc)
|
|
122
|
+
#print('fc:',fc, 'R3')
|
|
123
|
+
lmergeable.pop()
|
|
124
|
+
|
|
125
|
+
return s1Children, s2Children, s3Children
|
pyfunctionhood/main.py
ADDED
|
@@ -0,0 +1,182 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
|
|
3
|
+
from .hassediagram import HasseDiagram
|
|
4
|
+
from .function import Function
|
|
5
|
+
|
|
6
|
+
def GUI_mode():
|
|
7
|
+
try:
|
|
8
|
+
import tkinter as tk
|
|
9
|
+
except ImportError:
|
|
10
|
+
print("ERROR: tkinter module is not available. GUI mode cannot be started.")
|
|
11
|
+
print("Please install tkinter or run in command line mode.")
|
|
12
|
+
sys.exit(1)
|
|
13
|
+
|
|
14
|
+
def get_parents():
|
|
15
|
+
try:
|
|
16
|
+
idim = int(varDimension.get())
|
|
17
|
+
hd = HasseDiagram(idim)
|
|
18
|
+
f = Function.fromString(idim, varFunction.get())
|
|
19
|
+
s1Parents, s2Parents, s3Parents = hd.get_f_parents(f)
|
|
20
|
+
lParents = ['R1 ' + str(f) for f in s1Parents]\
|
|
21
|
+
+ ['R2 ' + str(f) for f in s2Parents]\
|
|
22
|
+
+ ['R3 ' + str(f) for f in s3Parents]
|
|
23
|
+
output = '** Parents(f) ***\n' + '\n'.join(lParents)
|
|
24
|
+
except ValueError as e:
|
|
25
|
+
output = "ERROR! " + str(e)
|
|
26
|
+
outputText.delete(1.0, "end") # Clear previous output
|
|
27
|
+
outputText.insert(1.0, output)
|
|
28
|
+
|
|
29
|
+
def get_children():
|
|
30
|
+
try:
|
|
31
|
+
idim = int(varDimension.get())
|
|
32
|
+
hd = HasseDiagram(idim)
|
|
33
|
+
f = Function.fromString(idim, varFunction.get())
|
|
34
|
+
s1Children, s2Children, s3Children = hd.get_f_children(f)
|
|
35
|
+
lChildren = ['R1 ' + str(f) for f in s1Children]\
|
|
36
|
+
+ ['R2 ' + str(f) for f in s2Children]\
|
|
37
|
+
+ ['R3 ' + str(f) for f in s3Children]
|
|
38
|
+
output = '** Children(f) ***\n' + '\n'.join(lChildren)
|
|
39
|
+
except ValueError as e:
|
|
40
|
+
output = "ERROR! " + str(e)
|
|
41
|
+
outputText.delete(1.0, "end") # Clear previous output
|
|
42
|
+
outputText.insert(1.0, output)
|
|
43
|
+
|
|
44
|
+
def default_values():
|
|
45
|
+
varFunction.set('{{1,2,3},{1,3,4},{2,3,4}}')
|
|
46
|
+
varDimension.set(4)
|
|
47
|
+
outputText.delete(1.0, "end") # Clear previous output
|
|
48
|
+
outputText.insert(1.0, '')
|
|
49
|
+
|
|
50
|
+
def set_infimum():
|
|
51
|
+
try:
|
|
52
|
+
idim = int(varDimension.get())
|
|
53
|
+
hd = HasseDiagram(idim)
|
|
54
|
+
f = hd.get_infimum()
|
|
55
|
+
varFunction.set(str(f))
|
|
56
|
+
except ValueError as e:
|
|
57
|
+
output = "ERROR! " + str(e)
|
|
58
|
+
|
|
59
|
+
def set_supremum():
|
|
60
|
+
try:
|
|
61
|
+
idim = int(varDimension.get())
|
|
62
|
+
hd = HasseDiagram(idim)
|
|
63
|
+
f = hd.get_supremum()
|
|
64
|
+
varFunction.set(str(f))
|
|
65
|
+
except ValueError as e:
|
|
66
|
+
output = "ERROR! " + str(e)
|
|
67
|
+
|
|
68
|
+
def close_window():
|
|
69
|
+
"""
|
|
70
|
+
Close the main window (exits the interface).
|
|
71
|
+
"""
|
|
72
|
+
root.destroy()
|
|
73
|
+
|
|
74
|
+
# Create the main window
|
|
75
|
+
root = tk.Tk()
|
|
76
|
+
root.title("pyFunctionHood GUI")
|
|
77
|
+
|
|
78
|
+
root.grid_columnconfigure(0, minsize=1, weight=0)
|
|
79
|
+
root.grid_columnconfigure(1, minsize=1, weight=1)
|
|
80
|
+
root.grid_columnconfigure(2, minsize=1, weight=1)
|
|
81
|
+
|
|
82
|
+
row = 0
|
|
83
|
+
# Entry field for user function
|
|
84
|
+
labelDimension = tk.Label(root, text="Dimension")
|
|
85
|
+
labelDimension.grid(row=row, column=0, sticky='w')
|
|
86
|
+
labelFunction = tk.Label(root, text="Monotone Boolean Function")
|
|
87
|
+
labelFunction.grid(row=row, column=1, columnspan=2)
|
|
88
|
+
|
|
89
|
+
row += 1
|
|
90
|
+
# Spinbox with Dimension
|
|
91
|
+
varDimension = tk.IntVar(value=4) # default dimension
|
|
92
|
+
spinboxDimension = tk.Spinbox(root, from_=2, to=14, textvariable=varDimension, width=6)
|
|
93
|
+
spinboxDimension.grid(row=row, column=0, sticky='w')
|
|
94
|
+
varFunction = tk.StringVar(value='{{1,2,3},{1,3,4},{2,3,4}}')
|
|
95
|
+
entryFunction = tk.Entry(root, textvariable=varFunction, width=48)
|
|
96
|
+
entryFunction.grid(row=row, column=1, columnspan=2)
|
|
97
|
+
|
|
98
|
+
row += 1
|
|
99
|
+
bottomFrame = tk.Frame(root, padx=5, pady=5)
|
|
100
|
+
bottomFrame.grid(row=row, columnspan=2)
|
|
101
|
+
|
|
102
|
+
row = 0
|
|
103
|
+
# Buttons for Infimum/Supremum
|
|
104
|
+
buttonInfimum = tk.Button(bottomFrame, text="Set Infimum", command=set_infimum)
|
|
105
|
+
buttonInfimum.grid(row=row, column=0)
|
|
106
|
+
buttonSupremum = tk.Button(bottomFrame, text="Set Supremum", command=set_supremum)
|
|
107
|
+
buttonSupremum.grid(row=row, column=1)
|
|
108
|
+
|
|
109
|
+
row += 1
|
|
110
|
+
canvas = tk.Canvas(bottomFrame, height=2, bg="darkgray") # Adjust height and color
|
|
111
|
+
canvas.grid(row=row, columnspan=3, sticky="ew", pady=10)
|
|
112
|
+
|
|
113
|
+
row += 1
|
|
114
|
+
# Buttons to call parents/children methods
|
|
115
|
+
buttonParents = tk.Button(bottomFrame, text="Generate Parents", command=get_parents)
|
|
116
|
+
buttonParents.grid(row=row, column=0)
|
|
117
|
+
buttonChildren = tk.Button(bottomFrame, text="Generate Children", command=get_children)
|
|
118
|
+
buttonChildren.grid(row=row, column=1)
|
|
119
|
+
|
|
120
|
+
row += 1
|
|
121
|
+
# Text area with grid placement and set state to disabled
|
|
122
|
+
outputText = tk.Text(bottomFrame, width=60, height=10)#, state="disabled")
|
|
123
|
+
outputText.grid(row=row, columnspan=2) # Span across two columns
|
|
124
|
+
|
|
125
|
+
row += 1
|
|
126
|
+
# Default values
|
|
127
|
+
buttonDefault = tk.Button(bottomFrame, text="Default values", command=default_values)
|
|
128
|
+
buttonDefault.grid(row=row, column=0)
|
|
129
|
+
# Close button
|
|
130
|
+
buttonClose = tk.Button(bottomFrame, text="Close", command=close_window)
|
|
131
|
+
buttonClose.grid(row=row, column=1)
|
|
132
|
+
|
|
133
|
+
# Run the main loop
|
|
134
|
+
root.mainloop()
|
|
135
|
+
|
|
136
|
+
#--------------------------------------------------------------------
|
|
137
|
+
|
|
138
|
+
def usage():
|
|
139
|
+
print('\nFor graphical mode, run without arguments: python', sys.argv[0])
|
|
140
|
+
print('\nFor command line mode, use the following arguments:')
|
|
141
|
+
print('Usage example:', sys.argv[0], '<type>', '<dimension>', '<function>')
|
|
142
|
+
print(' <type>: [p]arents or [c]hildren')
|
|
143
|
+
print(' <dimension>: 4')
|
|
144
|
+
print(' <function>: "{{1,2,3},{1,3,4},{2,3,4}}"')
|
|
145
|
+
sys.exit(1)
|
|
146
|
+
|
|
147
|
+
def command_line_mode():
|
|
148
|
+
if len(sys.argv) != 4:
|
|
149
|
+
print('ERROR: invalid number of arguments!')
|
|
150
|
+
usage()
|
|
151
|
+
if sys.argv[1] not in ('p','parents','c','children'):
|
|
152
|
+
print('ERROR: invalid <type>')
|
|
153
|
+
usage()
|
|
154
|
+
|
|
155
|
+
ndim = int(sys.argv[2])
|
|
156
|
+
hd = HasseDiagram(ndim)
|
|
157
|
+
f = Function.fromString(ndim, sys.argv[3])
|
|
158
|
+
if sys.argv[1] in ('p','parents'):
|
|
159
|
+
s1Parents, s2Parents, s3Parents = hd.get_f_parents(f)
|
|
160
|
+
lParents = ['R1 ' + str(f) for f in s1Parents]\
|
|
161
|
+
+ ['R2 ' + str(f) for f in s2Parents]\
|
|
162
|
+
+ ['R3 ' + str(f) for f in s3Parents]
|
|
163
|
+
print('\n'.join(lParents))
|
|
164
|
+
else:
|
|
165
|
+
s1Children, s2Children, s3Children = hd.get_f_children(f)
|
|
166
|
+
lChildren = ['R1 ' + str(f) for f in s1Children]\
|
|
167
|
+
+ ['R2 ' + str(f) for f in s2Children]\
|
|
168
|
+
+ ['R3 ' + str(f) for f in s3Children]
|
|
169
|
+
print('\n'.join(lChildren))
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
|
|
174
|
+
#--------------------------------------------------------------------
|
|
175
|
+
def main():
|
|
176
|
+
if len(sys.argv) == 1:
|
|
177
|
+
GUI_mode()
|
|
178
|
+
else:
|
|
179
|
+
command_line_mode()
|
|
180
|
+
|
|
181
|
+
if __name__ == '__main__':
|
|
182
|
+
main()
|
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
from .clause import Clause
|
|
2
|
+
from typing import Set
|
|
3
|
+
from collections import defaultdict
|
|
4
|
+
|
|
5
|
+
class PowerSet:
|
|
6
|
+
def __init__(self, nvars: int) -> None:
|
|
7
|
+
self.nvars = nvars
|
|
8
|
+
self.subset_clauses = defaultdict(set)
|
|
9
|
+
self.superset_clauses = defaultdict(set)
|
|
10
|
+
# useful to compute the independent clauses
|
|
11
|
+
self.all = set()
|
|
12
|
+
# initialize the graph with the most specific clause
|
|
13
|
+
c = Clause('1'*nvars)
|
|
14
|
+
self.superset_clauses[c] = set()
|
|
15
|
+
self.build_graph(c)
|
|
16
|
+
|
|
17
|
+
def build_graph(self, c_superset: 'Clause') -> None:
|
|
18
|
+
if c_superset not in self.subset_clauses:
|
|
19
|
+
self.subset_clauses[c_superset] = set()
|
|
20
|
+
if c_superset in self.all:
|
|
21
|
+
return
|
|
22
|
+
self.all.add(c_superset)
|
|
23
|
+
if c_superset.get_order() <= 1:
|
|
24
|
+
return
|
|
25
|
+
for c_subset in c_superset.get_subsets():
|
|
26
|
+
if c_subset not in self.superset_clauses:
|
|
27
|
+
self.superset_clauses[c_subset] = set()
|
|
28
|
+
s_tmp = self.subset_clauses[c_superset]
|
|
29
|
+
s_tmp.add(c_subset)
|
|
30
|
+
self.subset_clauses[c_superset] = s_tmp
|
|
31
|
+
s_tmp = self.superset_clauses[c_subset]
|
|
32
|
+
s_tmp.add(c_superset)
|
|
33
|
+
self.superset_clauses[c_subset] = s_tmp
|
|
34
|
+
self.build_graph(c_subset)
|
|
35
|
+
|
|
36
|
+
def get_dominated_directly(self, s_clauses: Set['Clause']) -> Set['Clause']:
|
|
37
|
+
s_dominated = set()
|
|
38
|
+
for c in s_clauses:
|
|
39
|
+
s_dominated.update(self.subset_clauses.get(c, set()))
|
|
40
|
+
return s_dominated
|
|
41
|
+
|
|
42
|
+
def get_dominant_directly(self, s_clauses: Set['Clause']) -> Set['Clause']:
|
|
43
|
+
s_dominant = set()
|
|
44
|
+
for c in s_clauses:
|
|
45
|
+
s_dominant.update(self.superset_clauses.get(c, set()))
|
|
46
|
+
return s_dominant
|
|
47
|
+
|
|
48
|
+
def get_dominated_recursively(self, c: 'Clause', s_seen: Set['Clause']) -> Set['Clause']:
|
|
49
|
+
for c_subset in self.subset_clauses.get(c, set()):
|
|
50
|
+
if c_subset not in s_seen:
|
|
51
|
+
s_seen.add(c_subset)
|
|
52
|
+
s_seen.update(self.get_dominated_recursively(c_subset, s_seen))
|
|
53
|
+
return s_seen
|
|
54
|
+
|
|
55
|
+
def get_dominant_recursively(self, c: 'Clause', s_seen: Set['Clause']) -> Set['Clause']:
|
|
56
|
+
for c_superset in self.superset_clauses.get(c, set()):
|
|
57
|
+
if c_superset not in s_seen:
|
|
58
|
+
s_seen.add(c_superset)
|
|
59
|
+
s_seen.update(self.get_dominant_recursively(c_superset, s_seen))
|
|
60
|
+
return s_seen
|
|
61
|
+
|
|
62
|
+
def get_independent(self, clauses: Set['Clause']) -> Set['Clause']:
|
|
63
|
+
if not clauses: # If the set is empty
|
|
64
|
+
return { Clause('1'*self.nvars) } # return the maximal clause
|
|
65
|
+
dep_set = set()
|
|
66
|
+
for c in clauses:
|
|
67
|
+
dep_set.update(self.get_dominated_recursively(c, dep_set))
|
|
68
|
+
dep_set.update(self.get_dominant_recursively(c, dep_set))
|
|
69
|
+
s_diff = self.all - clauses - dep_set
|
|
70
|
+
return s_diff
|
|
71
|
+
|
|
72
|
+
def get_minimal(self, s_clauses: Set['Clause']) -> Set['Clause']:
|
|
73
|
+
return { s1 for s1 in s_clauses if not any( s1 != s2 and s2 <= s1 for s2 in s_clauses) }
|
|
74
|
+
|
|
75
|
+
def get_maximal(self, s_clauses: Set['Clause']) -> Set['Clause']:
|
|
76
|
+
return { s1 for s1 in s_clauses if not any( s1 != s2 and s2 >= s1 for s2 in s_clauses) }
|
|
77
|
+
|
|
78
|
+
def __str__(self) -> str:
|
|
79
|
+
s = ""
|
|
80
|
+
for c in self.all:
|
|
81
|
+
s += f"{c}\tSuper: {self.superset_clauses.get(c, set())}\tSub: {self.subset_clauses.get(c, set())}\n"
|
|
82
|
+
return s
|