pyfunctionhood 0.0.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 +180 -0
- pyfunctionhood/main.py +227 -0
- pyfunctionhood/powerset.py +82 -0
- pyfunctionhood-0.0.0.dist-info/METADATA +182 -0
- pyfunctionhood-0.0.0.dist-info/RECORD +12 -0
- pyfunctionhood-0.0.0.dist-info/WHEEL +5 -0
- pyfunctionhood-0.0.0.dist-info/entry_points.txt +2 -0
- pyfunctionhood-0.0.0.dist-info/licenses/LICENSE +661 -0
- pyfunctionhood-0.0.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,180 @@
|
|
|
1
|
+
from .clause import Clause
|
|
2
|
+
from .function import Function
|
|
3
|
+
from .powerset import PowerSet
|
|
4
|
+
from bitarray import bitarray
|
|
5
|
+
from typing import Tuple, Set
|
|
6
|
+
|
|
7
|
+
class HasseDiagram:
|
|
8
|
+
# Dedeking number: number of monotone Boolean functions of n variables:
|
|
9
|
+
# https://oeis.org/A000372
|
|
10
|
+
# Number of monotone non-degenerate Boolean functions of n variables:
|
|
11
|
+
# n=2 -> 2 functions
|
|
12
|
+
# n=3 -> 9 functions
|
|
13
|
+
# n=4 -> 114 functions
|
|
14
|
+
# n=5 -> 6 894 functions
|
|
15
|
+
# n=6 -> 7 785 062 functions
|
|
16
|
+
# n=7 -> 2 414 627 396 434 functions
|
|
17
|
+
# n=8 -> 56 130 437 209 370 320 359 966 functions
|
|
18
|
+
# n=9 -> 286 386 577 668 298 410 623 295 216 696 338 374 471 993 functions
|
|
19
|
+
|
|
20
|
+
def __init__(self, nvars: int) -> None:
|
|
21
|
+
self.nvars = nvars
|
|
22
|
+
self.powerset = PowerSet(nvars)
|
|
23
|
+
|
|
24
|
+
def get_infimum(self) -> 'Function':
|
|
25
|
+
""" Returns the infimum of the set of functions. """
|
|
26
|
+
return Function(self.nvars, { Clause('1'*self.nvars) })
|
|
27
|
+
|
|
28
|
+
def get_supremum(self) -> 'Function':
|
|
29
|
+
""" Returns the supremum of the set of functions. """
|
|
30
|
+
return Function(self.nvars,
|
|
31
|
+
{ Clause('0'*i + '1' + '0'*(self.nvars - 1 - i))
|
|
32
|
+
for i in range(self.nvars) } )
|
|
33
|
+
|
|
34
|
+
def get_size(self) -> int:
|
|
35
|
+
""" Returns the number of variables of the Hasse diagram. """
|
|
36
|
+
return self.nvars
|
|
37
|
+
|
|
38
|
+
def get_f_parents(self, f: 'Function') -> Tuple[Set['Function'], Set['Function'], Set['Function']]:
|
|
39
|
+
""" Returns the set of immediate parents of f. """
|
|
40
|
+
s1Parents, s2Parents, s3Parents = set(), set(), set()
|
|
41
|
+
|
|
42
|
+
# Get maximal independent clauses
|
|
43
|
+
sC = self.powerset.get_maximal(self.powerset.get_independent(f.clauses))
|
|
44
|
+
|
|
45
|
+
# Add all parents from the 1st rule
|
|
46
|
+
s1Parents = { f.clone_rm_add(set(), { c }) for c in sC }
|
|
47
|
+
|
|
48
|
+
# Get maximal dominated clauses
|
|
49
|
+
lD = [d for d in self.powerset.get_maximal( \
|
|
50
|
+
self.powerset.get_dominated_directly(f.clauses))\
|
|
51
|
+
if not any([(d<=s) for s in sC])]
|
|
52
|
+
|
|
53
|
+
# Add all parents from the 2nd rule
|
|
54
|
+
sDnotUsed = {}
|
|
55
|
+
for d in lD:
|
|
56
|
+
sContained = d.get_containing(f.clauses)
|
|
57
|
+
fp = f.clone_rm_add(sContained, {d})
|
|
58
|
+
if fp.is_consistent():
|
|
59
|
+
s2Parents.add(fp)
|
|
60
|
+
#print(' fp:',fp,'R2')
|
|
61
|
+
else:
|
|
62
|
+
for s in sContained:
|
|
63
|
+
if s not in sDnotUsed: sDnotUsed[s] = set()
|
|
64
|
+
sDnotUsed[s].add(d)
|
|
65
|
+
|
|
66
|
+
# Add all parents from the 3rd rule
|
|
67
|
+
for s in sDnotUsed:
|
|
68
|
+
lSigmas = list(sDnotUsed[s])
|
|
69
|
+
if len(lSigmas) < 2: # needs at least 2 clauses to be combined
|
|
70
|
+
continue
|
|
71
|
+
for i in range(len(lSigmas)-1):
|
|
72
|
+
for j in range(i + 1, len(lSigmas)):
|
|
73
|
+
# by def only s contains both sigma_i and sigma_j
|
|
74
|
+
fp = f.clone_rm_add({s}, {lSigmas[i],lSigmas[j]})
|
|
75
|
+
# by def no need to test if isCover(fp)
|
|
76
|
+
s3Parents.add(fp)
|
|
77
|
+
#print(' fp:',fp, 'R3')
|
|
78
|
+
|
|
79
|
+
return s1Parents, s2Parents, s3Parents
|
|
80
|
+
|
|
81
|
+
def get_f_children(self, f: 'Function') -> Tuple[Set['Function'], Set['Function'], Set['Function']]:
|
|
82
|
+
""" Returns the set of immediate children of f. """
|
|
83
|
+
s1Children, s2Children, s3Children = set(), set(), set()
|
|
84
|
+
dmergeable = {}
|
|
85
|
+
|
|
86
|
+
# Add all children of the 1st form
|
|
87
|
+
for s in f.clauses:
|
|
88
|
+
bToMerge, bExtendable = False, False
|
|
89
|
+
# Child function to be extended with: s \cup {l_i}
|
|
90
|
+
fs = f.clone_rm_add({s},set())
|
|
91
|
+
for l in s.get_off_literals():
|
|
92
|
+
sl = s.clone_add(l)
|
|
93
|
+
sAbsorbed = sl.get_contained(f.clauses)
|
|
94
|
+
if len(sAbsorbed) == 1:
|
|
95
|
+
bExtendable = True
|
|
96
|
+
fs = fs.clone_rm_add(set(), {sl})
|
|
97
|
+
elif len(sAbsorbed) == 2:
|
|
98
|
+
bToMerge = True
|
|
99
|
+
|
|
100
|
+
if bExtendable:
|
|
101
|
+
s2Children.add(fs)
|
|
102
|
+
#print('fc:',fs, 'R2')
|
|
103
|
+
elif fs.is_consistent():
|
|
104
|
+
s1Children.add(fs)
|
|
105
|
+
#print('fc:',fs, 'R1')
|
|
106
|
+
elif bToMerge:
|
|
107
|
+
# Clauses are only (potentially) mergeable with others of their own size
|
|
108
|
+
sz = s.get_order()
|
|
109
|
+
if sz not in dmergeable: dmergeable[sz] = []
|
|
110
|
+
dmergeable[sz].append(s)
|
|
111
|
+
|
|
112
|
+
for sz in dmergeable:
|
|
113
|
+
lmergeable = dmergeable[sz]
|
|
114
|
+
while lmergeable:
|
|
115
|
+
c = lmergeable[-1]
|
|
116
|
+
fMergeable = Function(f.get_size(), set(lmergeable))
|
|
117
|
+
for l in c.get_off_literals():
|
|
118
|
+
cl = c.clone_add(l)
|
|
119
|
+
sAbsorbed = cl.get_contained(fMergeable.clauses)
|
|
120
|
+
if len(sAbsorbed) == 2:
|
|
121
|
+
fc = f.clone_rm_add(sAbsorbed, {cl})
|
|
122
|
+
s3Children.add(fc)
|
|
123
|
+
#print('fc:',fc, 'R3')
|
|
124
|
+
lmergeable.pop()
|
|
125
|
+
|
|
126
|
+
return s1Children, s2Children, s3Children
|
|
127
|
+
|
|
128
|
+
def get_f_parents_with_sign_changes(self, f: 'Function', changed_signs: bitarray) -> Tuple[Set['Function'], Set['Function'], Set['Function']]:
|
|
129
|
+
""" Returns the set of immediate parents of f when the variables/regulators
|
|
130
|
+
flagged in changed_signs have switched sign (0->1 or 1->0). """
|
|
131
|
+
if changed_signs.count() == 0:
|
|
132
|
+
raise ValueError('changed_signs must flag at least one variable!')
|
|
133
|
+
if len(changed_signs) != self.nvars:
|
|
134
|
+
raise ValueError('changed_signs must have size ' + str(self.nvars) + '!')
|
|
135
|
+
|
|
136
|
+
# S_bullet: clauses of f with all sign-changed literals removed
|
|
137
|
+
sBullet = set()
|
|
138
|
+
for c in f.clauses:
|
|
139
|
+
signature = c.get_signature() & ~changed_signs
|
|
140
|
+
if signature.count() == 0:
|
|
141
|
+
# Existence criterion: no f' exists once a clause becomes empty
|
|
142
|
+
return set(), set(), set()
|
|
143
|
+
sBullet.add(Clause(signature))
|
|
144
|
+
|
|
145
|
+
# Keep only the smallest clauses, dropping any that are supersets of another
|
|
146
|
+
sBullet = self.powerset.get_minimal(sBullet)
|
|
147
|
+
|
|
148
|
+
# S' = S_bullet union each maximal independent clause of f
|
|
149
|
+
sC = self.powerset.get_maximal(self.powerset.get_independent(sBullet))
|
|
150
|
+
sParents = { Function(self.nvars, sBullet | { c }) for c in sC }
|
|
151
|
+
|
|
152
|
+
return sParents, set(), set() # between signature changes only R1 parents are possible
|
|
153
|
+
|
|
154
|
+
def get_f_children_with_sign_changes(self, f: 'Function', changed_signs: bitarray) -> Tuple[Set['Function'], Set['Function'], Set['Function']]:
|
|
155
|
+
""" Returns the set of immediate children of f when the variables/regulators
|
|
156
|
+
flagged in changed_signs have switched sign (0->1 or 1->0). """
|
|
157
|
+
if changed_signs.count() == 0:
|
|
158
|
+
raise ValueError('changed_signs must flag at least one variable!')
|
|
159
|
+
if len(changed_signs) != self.nvars:
|
|
160
|
+
raise ValueError('changed_signs must have size ' + str(self.nvars) + '!')
|
|
161
|
+
|
|
162
|
+
# Existence criterion: f' exists only if some clause is made up exclusively of unchanged variables
|
|
163
|
+
invariants = { c for c in f.clauses if (c.get_signature() & changed_signs).count() == 0 }
|
|
164
|
+
if not invariants:
|
|
165
|
+
return set(), set(), set()
|
|
166
|
+
|
|
167
|
+
# One f' per clause s in invariants: f' = (Inv \ {s}) U { s U {l} : l in ext(s) },
|
|
168
|
+
# where ext(s) is every literal l not in s such that s U {l} is independent of Inv \ {s}.
|
|
169
|
+
# (ext(s) always contains every changed variable, so f' is a cover.)
|
|
170
|
+
sChildren = set()
|
|
171
|
+
for s in invariants:
|
|
172
|
+
sRest = invariants - { s }
|
|
173
|
+
sExt = set()
|
|
174
|
+
for l in s.get_off_literals():
|
|
175
|
+
candidate = s.clone_add(l)
|
|
176
|
+
if all(candidate.is_independent(c) for c in sRest):
|
|
177
|
+
sExt.add(candidate)
|
|
178
|
+
sChildren.add(Function(self.nvars, sRest | sExt))
|
|
179
|
+
|
|
180
|
+
return sChildren, set(), set() # between signature changes only R1 children are possible
|
pyfunctionhood/main.py
ADDED
|
@@ -0,0 +1,227 @@
|
|
|
1
|
+
import sys
|
|
2
|
+
|
|
3
|
+
from bitarray import bitarray
|
|
4
|
+
from .hassediagram import HasseDiagram
|
|
5
|
+
from .function import Function
|
|
6
|
+
|
|
7
|
+
def GUI_mode():
|
|
8
|
+
try:
|
|
9
|
+
import tkinter as tk
|
|
10
|
+
except ImportError:
|
|
11
|
+
print("ERROR: tkinter module is not available. GUI mode cannot be started.")
|
|
12
|
+
print("Please install tkinter or run in command line mode.")
|
|
13
|
+
sys.exit(1)
|
|
14
|
+
|
|
15
|
+
def get_changed_signs(idim):
|
|
16
|
+
""" Returns None if no sign changed, otherwise the corresponding bitarray. """
|
|
17
|
+
strSigns = varChangedSigns.get().strip()
|
|
18
|
+
if not strSigns:
|
|
19
|
+
return None
|
|
20
|
+
if len(strSigns) != idim or any(c not in ('0', '1') for c in strSigns):
|
|
21
|
+
raise ValueError('changed signs must be a string of ' + str(idim) + ' bits (0/1)!')
|
|
22
|
+
changed_signs = bitarray(strSigns)
|
|
23
|
+
return changed_signs if changed_signs.count() else None
|
|
24
|
+
|
|
25
|
+
def get_parents():
|
|
26
|
+
try:
|
|
27
|
+
idim = int(varDimension.get())
|
|
28
|
+
hd = HasseDiagram(idim)
|
|
29
|
+
f = Function.fromString(idim, varFunction.get())
|
|
30
|
+
changed_signs = get_changed_signs(idim)
|
|
31
|
+
if changed_signs is None:
|
|
32
|
+
s1Parents, s2Parents, s3Parents = hd.get_f_parents(f)
|
|
33
|
+
else:
|
|
34
|
+
s1Parents, s2Parents, s3Parents = hd.get_f_parents_with_sign_changes(f, changed_signs)
|
|
35
|
+
lParents = ['R1 ' + str(f) for f in s1Parents]\
|
|
36
|
+
+ ['R2 ' + str(f) for f in s2Parents]\
|
|
37
|
+
+ ['R3 ' + str(f) for f in s3Parents]
|
|
38
|
+
output = '** Parents(f) ***\n' + '\n'.join(lParents)
|
|
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 get_children():
|
|
45
|
+
try:
|
|
46
|
+
idim = int(varDimension.get())
|
|
47
|
+
hd = HasseDiagram(idim)
|
|
48
|
+
f = Function.fromString(idim, varFunction.get())
|
|
49
|
+
changed_signs = get_changed_signs(idim)
|
|
50
|
+
if changed_signs is None:
|
|
51
|
+
s1Children, s2Children, s3Children = hd.get_f_children(f)
|
|
52
|
+
else:
|
|
53
|
+
s1Children, s2Children, s3Children = hd.get_f_children_with_sign_changes(f, changed_signs)
|
|
54
|
+
lChildren = ['R1 ' + str(f) for f in s1Children]\
|
|
55
|
+
+ ['R2 ' + str(f) for f in s2Children]\
|
|
56
|
+
+ ['R3 ' + str(f) for f in s3Children]
|
|
57
|
+
output = '** Children(f) ***\n' + '\n'.join(lChildren)
|
|
58
|
+
except ValueError as e:
|
|
59
|
+
output = "ERROR! " + str(e)
|
|
60
|
+
outputText.delete(1.0, "end") # Clear previous output
|
|
61
|
+
outputText.insert(1.0, output)
|
|
62
|
+
|
|
63
|
+
def default_values():
|
|
64
|
+
varFunction.set('{{1,2,3},{1,3,4},{2,3,4}}')
|
|
65
|
+
varDimension.set(4)
|
|
66
|
+
varChangedSigns.set('')
|
|
67
|
+
outputText.delete(1.0, "end") # Clear previous output
|
|
68
|
+
outputText.insert(1.0, '')
|
|
69
|
+
|
|
70
|
+
def set_infimum():
|
|
71
|
+
try:
|
|
72
|
+
idim = int(varDimension.get())
|
|
73
|
+
hd = HasseDiagram(idim)
|
|
74
|
+
f = hd.get_infimum()
|
|
75
|
+
varFunction.set(str(f))
|
|
76
|
+
except ValueError as e:
|
|
77
|
+
output = "ERROR! " + str(e)
|
|
78
|
+
|
|
79
|
+
def set_supremum():
|
|
80
|
+
try:
|
|
81
|
+
idim = int(varDimension.get())
|
|
82
|
+
hd = HasseDiagram(idim)
|
|
83
|
+
f = hd.get_supremum()
|
|
84
|
+
varFunction.set(str(f))
|
|
85
|
+
except ValueError as e:
|
|
86
|
+
output = "ERROR! " + str(e)
|
|
87
|
+
|
|
88
|
+
def close_window():
|
|
89
|
+
"""
|
|
90
|
+
Close the main window (exits the interface).
|
|
91
|
+
"""
|
|
92
|
+
root.destroy()
|
|
93
|
+
|
|
94
|
+
# Create the main window
|
|
95
|
+
root = tk.Tk()
|
|
96
|
+
root.title("pyFunctionHood GUI")
|
|
97
|
+
|
|
98
|
+
root.grid_columnconfigure(0, minsize=1, weight=0)
|
|
99
|
+
root.grid_columnconfigure(1, minsize=1, weight=1)
|
|
100
|
+
root.grid_columnconfigure(2, minsize=1, weight=1)
|
|
101
|
+
|
|
102
|
+
row = 0
|
|
103
|
+
# Entry field for user function
|
|
104
|
+
labelDimension = tk.Label(root, text="Dimension")
|
|
105
|
+
labelDimension.grid(row=row, column=0, sticky='w')
|
|
106
|
+
labelFunction = tk.Label(root, text="Monotone Boolean Function")
|
|
107
|
+
labelFunction.grid(row=row, column=1, columnspan=2)
|
|
108
|
+
|
|
109
|
+
row += 1
|
|
110
|
+
# Spinbox with Dimension
|
|
111
|
+
varDimension = tk.IntVar(value=4) # default dimension
|
|
112
|
+
spinboxDimension = tk.Spinbox(root, from_=2, to=14, textvariable=varDimension, width=6)
|
|
113
|
+
spinboxDimension.grid(row=row, column=0, sticky='w')
|
|
114
|
+
varFunction = tk.StringVar(value='{{1,2,3},{1,3,4},{2,3,4}}')
|
|
115
|
+
entryFunction = tk.Entry(root, textvariable=varFunction, width=48)
|
|
116
|
+
entryFunction.grid(row=row, column=1, columnspan=2)
|
|
117
|
+
|
|
118
|
+
row += 1
|
|
119
|
+
labelChangedSigns = tk.Label(root, text="Changed Signs")
|
|
120
|
+
labelChangedSigns.grid(row=row, column=0, sticky='w')
|
|
121
|
+
varChangedSigns = tk.StringVar(value='') # empty means no sign changed
|
|
122
|
+
entryChangedSigns = tk.Entry(root, textvariable=varChangedSigns, width=48)
|
|
123
|
+
entryChangedSigns.grid(row=row, column=1, columnspan=2)
|
|
124
|
+
|
|
125
|
+
row += 1
|
|
126
|
+
bottomFrame = tk.Frame(root, padx=5, pady=5)
|
|
127
|
+
bottomFrame.grid(row=row, columnspan=2)
|
|
128
|
+
|
|
129
|
+
row = 0
|
|
130
|
+
# Buttons for Infimum/Supremum
|
|
131
|
+
buttonInfimum = tk.Button(bottomFrame, text="Set Infimum", command=set_infimum)
|
|
132
|
+
buttonInfimum.grid(row=row, column=0)
|
|
133
|
+
buttonSupremum = tk.Button(bottomFrame, text="Set Supremum", command=set_supremum)
|
|
134
|
+
buttonSupremum.grid(row=row, column=1)
|
|
135
|
+
|
|
136
|
+
row += 1
|
|
137
|
+
canvas = tk.Canvas(bottomFrame, height=2, bg="darkgray") # Adjust height and color
|
|
138
|
+
canvas.grid(row=row, columnspan=3, sticky="ew", pady=10)
|
|
139
|
+
|
|
140
|
+
row += 1
|
|
141
|
+
# Buttons to call parents/children methods
|
|
142
|
+
buttonParents = tk.Button(bottomFrame, text="Generate Parents", command=get_parents)
|
|
143
|
+
buttonParents.grid(row=row, column=0)
|
|
144
|
+
buttonChildren = tk.Button(bottomFrame, text="Generate Children", command=get_children)
|
|
145
|
+
buttonChildren.grid(row=row, column=1)
|
|
146
|
+
|
|
147
|
+
row += 1
|
|
148
|
+
# Text area with grid placement and set state to disabled
|
|
149
|
+
outputText = tk.Text(bottomFrame, width=60, height=10)#, state="disabled")
|
|
150
|
+
outputText.grid(row=row, columnspan=2) # Span across two columns
|
|
151
|
+
|
|
152
|
+
row += 1
|
|
153
|
+
# Default values
|
|
154
|
+
buttonDefault = tk.Button(bottomFrame, text="Default values", command=default_values)
|
|
155
|
+
buttonDefault.grid(row=row, column=0)
|
|
156
|
+
# Close button
|
|
157
|
+
buttonClose = tk.Button(bottomFrame, text="Close", command=close_window)
|
|
158
|
+
buttonClose.grid(row=row, column=1)
|
|
159
|
+
|
|
160
|
+
# Run the main loop
|
|
161
|
+
root.mainloop()
|
|
162
|
+
|
|
163
|
+
#--------------------------------------------------------------------
|
|
164
|
+
|
|
165
|
+
def usage():
|
|
166
|
+
print('\nFor graphical mode, run without arguments: python', sys.argv[0])
|
|
167
|
+
print('\nFor command line mode, use the following arguments:')
|
|
168
|
+
print('Usage example:', sys.argv[0], '<type>', '<dimension>', '<function>', '[<changed_signs>]')
|
|
169
|
+
print(' <type>: [p]arents or [c]hildren')
|
|
170
|
+
print(' <dimension>: 4')
|
|
171
|
+
print(' <function>: "{{1,2,3},{1,3,4},{2,3,4}}"')
|
|
172
|
+
print(' <changed_signs>: optional, e.g. "0100" (bit i=1 means variable i switched sign)')
|
|
173
|
+
sys.exit(1)
|
|
174
|
+
|
|
175
|
+
def command_line_mode():
|
|
176
|
+
if len(sys.argv) not in (4, 5):
|
|
177
|
+
print('ERROR: invalid number of arguments!')
|
|
178
|
+
usage()
|
|
179
|
+
if sys.argv[1] not in ('p','parents','c','children'):
|
|
180
|
+
print('ERROR: invalid <type>')
|
|
181
|
+
usage()
|
|
182
|
+
|
|
183
|
+
ndim = int(sys.argv[2])
|
|
184
|
+
hd = HasseDiagram(ndim)
|
|
185
|
+
f = Function.fromString(ndim, sys.argv[3])
|
|
186
|
+
|
|
187
|
+
changed_signs = None
|
|
188
|
+
if len(sys.argv) == 5:
|
|
189
|
+
strSigns = sys.argv[4]
|
|
190
|
+
if len(strSigns) != ndim or any(c not in ('0', '1') for c in strSigns):
|
|
191
|
+
print('ERROR: invalid <changed_signs>')
|
|
192
|
+
usage()
|
|
193
|
+
changed_signs = bitarray(strSigns)
|
|
194
|
+
if changed_signs.count() == 0:
|
|
195
|
+
changed_signs = None
|
|
196
|
+
|
|
197
|
+
if sys.argv[1] in ('p','parents'):
|
|
198
|
+
if changed_signs is None:
|
|
199
|
+
s1Parents, s2Parents, s3Parents = hd.get_f_parents(f)
|
|
200
|
+
else:
|
|
201
|
+
s1Parents, s2Parents, s3Parents = hd.get_f_parents_with_sign_changes(f, changed_signs)
|
|
202
|
+
lParents = ['R1 ' + str(f) for f in s1Parents]\
|
|
203
|
+
+ ['R2 ' + str(f) for f in s2Parents]\
|
|
204
|
+
+ ['R3 ' + str(f) for f in s3Parents]
|
|
205
|
+
print('\n'.join(lParents))
|
|
206
|
+
else:
|
|
207
|
+
if changed_signs is None:
|
|
208
|
+
s1Children, s2Children, s3Children = hd.get_f_children(f)
|
|
209
|
+
else:
|
|
210
|
+
s1Children, s2Children, s3Children = hd.get_f_children_with_sign_changes(f, changed_signs)
|
|
211
|
+
lChildren = ['R1 ' + str(f) for f in s1Children]\
|
|
212
|
+
+ ['R2 ' + str(f) for f in s2Children]\
|
|
213
|
+
+ ['R3 ' + str(f) for f in s3Children]
|
|
214
|
+
print('\n'.join(lChildren))
|
|
215
|
+
|
|
216
|
+
|
|
217
|
+
|
|
218
|
+
|
|
219
|
+
#--------------------------------------------------------------------
|
|
220
|
+
def main():
|
|
221
|
+
if len(sys.argv) == 1:
|
|
222
|
+
GUI_mode()
|
|
223
|
+
else:
|
|
224
|
+
command_line_mode()
|
|
225
|
+
|
|
226
|
+
if __name__ == '__main__':
|
|
227
|
+
main()
|