pyfunctionhood 0.2.1__tar.gz → 0.3.1__tar.gz

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.
Files changed (27) hide show
  1. pyfunctionhood-0.3.1/.github/workflows/python-publish.yml +47 -0
  2. pyfunctionhood-0.3.1/.gitignore +9 -0
  3. pyfunctionhood-0.3.1/MANIFEST.in +3 -0
  4. {pyfunctionhood-0.2.1/src/pyfunctionhood.egg-info → pyfunctionhood-0.3.1}/PKG-INFO +27 -9
  5. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/README.md +26 -8
  6. pyfunctionhood-0.3.1/img/pyfunctionhood.png +0 -0
  7. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/pyproject.toml +6 -2
  8. pyfunctionhood-0.3.1/requirements.txt +2 -0
  9. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/src/pyfunctionhood/hassediagram.py +7 -6
  10. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/src/pyfunctionhood/main.py +92 -34
  11. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1/src/pyfunctionhood.egg-info}/PKG-INFO +27 -9
  12. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/src/pyfunctionhood.egg-info/SOURCES.txt +11 -1
  13. pyfunctionhood-0.3.1/src/pyfunctionhood.egg-info/scm_file_list.json +109 -0
  14. pyfunctionhood-0.3.1/src/pyfunctionhood.egg-info/scm_version.json +8 -0
  15. pyfunctionhood-0.3.1/tests/test_check_rules.py +110 -0
  16. pyfunctionhood-0.3.1/tests/test_check_sign_changes.py +130 -0
  17. pyfunctionhood-0.3.1/tests/test_rule_categorization.py +117 -0
  18. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/LICENSE +0 -0
  19. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/setup.cfg +0 -0
  20. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/src/pyfunctionhood/__init__.py +0 -0
  21. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/src/pyfunctionhood/clause.py +0 -0
  22. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/src/pyfunctionhood/function.py +0 -0
  23. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/src/pyfunctionhood/powerset.py +0 -0
  24. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/src/pyfunctionhood.egg-info/dependency_links.txt +0 -0
  25. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/src/pyfunctionhood.egg-info/entry_points.txt +0 -0
  26. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/src/pyfunctionhood.egg-info/requires.txt +0 -0
  27. {pyfunctionhood-0.2.1 → pyfunctionhood-0.3.1}/src/pyfunctionhood.egg-info/top_level.txt +0 -0
@@ -0,0 +1,47 @@
1
+ name: Publish Python Package
2
+
3
+ on:
4
+ push:
5
+ tags:
6
+ - 'v*' # Trigger workflow on tags that start with "v" (e.g., v1.0.0)
7
+ workflow_dispatch: # Allow manual runs from the Actions tab
8
+
9
+ jobs:
10
+ build-and-publish:
11
+ name: Build and publish to PyPI
12
+ runs-on: ubuntu-latest
13
+
14
+ # Required for trusted publishing to PyPI
15
+ permissions:
16
+ id-token: write
17
+ contents: write # Elevated from 'read' to allow Release creation
18
+
19
+ steps:
20
+ - name: Checkout Code
21
+ uses: actions/checkout@v6
22
+ with:
23
+ fetch-depth: 0
24
+
25
+ - name: Set up Python
26
+ uses: actions/setup-python@v6
27
+ with:
28
+ python-version: "3.x"
29
+
30
+ - name: Install build dependencies
31
+ run: python -m pip install --upgrade pip build setuptools_scm[toml]
32
+
33
+ - name: Build sdist and wheel
34
+ run: python -m build
35
+
36
+ - name: Publish to PyPI
37
+ uses: pypa/gh-action-pypi-publish@release/v1
38
+
39
+ - name: Create GitHub Release
40
+ if: startsWith(github.ref, 'refs/tags/')
41
+ uses: softprops/action-gh-release@v2
42
+ with:
43
+ # This will include the .tar.gz and .whl files in the GitHub Release assets
44
+ files: dist/*
45
+ generate_release_notes: true
46
+ env:
47
+ GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
@@ -0,0 +1,9 @@
1
+ *~
2
+ venv/
3
+ *.bak
4
+ .vscode
5
+ __pycache__/
6
+ *.pdf
7
+ build/
8
+ dist/
9
+ *.egg-info/
@@ -0,0 +1,3 @@
1
+ # The experiments (scripts, raw data and figures of the paper) live in the GitHub
2
+ # repository only; they are not shipped in the source distribution on PyPI.
3
+ prune experiments
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyfunctionhood
3
- Version: 0.2.1
3
+ Version: 0.3.1
4
4
  Summary: Local computation of immediate neighbours of a given monotone non-degenerate Boolean function
5
5
  Author-email: "Pedro T. Monteiro" <Pedro.Tiago.Monteiro@tecnico.ulisboa.pt>
6
6
  License: AGPL-3.0
@@ -45,11 +45,11 @@ Given a reference monotone Boolean function, this library can be used in three d
45
45
  Usage - command line
46
46
  --------------------
47
47
  ```
48
- Usage example: python main.py <type> <dimension> <function> [<changed_signs>]
48
+ Usage example: python main.py <type> <dimension> <function> [<signature>]
49
49
  <type>: [p]arents or [c]hildren
50
50
  <dimension>: 4
51
51
  <function>: "{{1,2,3},{1,3,4},{2,3,4}}"
52
- <changed_signs>: optional, e.g. "0100" (bit i=1 means variable i switched sign)
52
+ <signature>: optional target signature, e.g. "1011" (bit i: 1 = positive, 0 = negative variable i)
53
53
  ```
54
54
 
55
55
  **Parents**
@@ -76,12 +76,12 @@ R1 {{1,2,3},{2,3,4}}
76
76
 
77
77
  **Sign changes**
78
78
 
79
- Commands accept an optional trailing `<changed_signs>` argument: a bitstring of the same length as `<dimension>`, where bit `i=1` means variable/regulator `i` switched sign (0->1 or 1->0) with respect to the reference topology. When provided (and not all zeros), parents/children are computed considering that change of signs instead of the default fixed-topology rules:
79
+ Commands accept an optional trailing `<signature>` argument: the target signature, a bitstring of the same length as `<dimension>`, where bit `i` is `1` if variable/regulator `i` is positive and `0` if it is negative. The function is given in the all-positive signature (all 1's). When a signature with some `0` is provided, the closest parents/children in that signature are computed instead of the default fixed-topology rules:
80
80
  ```
81
- python main.py p 4 "{{1,2,3},{1,3,4},{2,3,4}}" 0100
82
- python main.py c 4 "{{1,2,3},{1,3,4},{2,3,4}}" 0100
81
+ python main.py p 4 "{{1,2,3},{1,3,4},{2,3,4}}" 1011
82
+ python main.py c 4 "{{1,2,3},{1,3,4},{2,3,4}}" 1011
83
83
  ```
84
- When omitted (or all zeros), the behaviour is unchanged from above, i.e. fixed-topology.
84
+ When omitted (or all 1's), the behaviour is unchanged from above, i.e. fixed-topology. In the output, `~i` denotes the negated variable `i`: for instance, `python main.py p 3 "{{1,2},{3}}" 101` yields `R1 {{1},{~2},{3}}`.
85
85
 
86
86
  ---
87
87
 
@@ -94,7 +94,7 @@ There is also a graphical interface using Tkinter where the user can define the
94
94
 
95
95
  The interface has a button to automatically write the Infimum function of the chosen dimension, and another for the Supremum function.
96
96
 
97
- A **Changed signs** text box is also available to optionally specify a bitstring of the same length as the dimension, where bit `i=1` means variable/regulator `i` switched sign. Leaving it empty (the default) keeps the fixed-topology behaviour.
97
+ A **Signature** text box is also available to optionally specify the target signature, a bitstring of the same length as the dimension, where bit `i` is `1` if variable/regulator `i` is positive and `0` if it is negative. It is set to all 1's (the default, i.e. the fixed-topology behaviour) and goes back to all 1's whenever the dimension changes. Hovering over it shows a short explanation.
98
98
 
99
99
  The user has two buttons to generate the immediate neighbouring functions: **Generate Parents** to generate the list of parent functions, and **Generate Children** to generate the list of children functions.
100
100
 
@@ -144,12 +144,30 @@ changed_signs = bitarray('0100')
144
144
  s1, s2, s3 = hd.get_f_parents_with_sign_changes(f, changed_signs)
145
145
  ```
146
146
 
147
+ This is the complement of the `<signature>` used by the command line and the GUI: `changed_signs = ~bitarray(signature)`.
148
+
149
+ ---
150
+
151
+ Testing
152
+ -------
153
+
154
+ The library includes a comprehensive pytest suite to validate correctness of the core algorithms:
155
+
156
+ ```bash
157
+ pytest tests/ -v
158
+ ```
159
+
160
+ This runs 22 tests covering:
161
+ - **Sign changes computation** (test_check_sign_changes.py): Validates `get_f_parents/children_with_sign_changes()` by exhaustive checking for small dimensions and random sampling for larger ones
162
+ - **Random walk consistency** (test_check_rules.py): Performs random walks on the Hasse diagram to verify parent-child relationships are consistent
163
+ - **Rule categorization** (test_rule_categorization.py): Validates that parent and children are correctly partitioned into S1, S2, and S3 rules
164
+
147
165
  ---
148
166
 
149
167
  License
150
168
  -------
151
169
 
152
- This code is available under GPL-3.0.
170
+ This code is available under the GNU Affero General Public License v3.0 (AGPL-3.0). See the `LICENSE` file.
153
171
 
154
172
  Cite
155
173
  ----
@@ -19,11 +19,11 @@ Given a reference monotone Boolean function, this library can be used in three d
19
19
  Usage - command line
20
20
  --------------------
21
21
  ```
22
- Usage example: python main.py <type> <dimension> <function> [<changed_signs>]
22
+ Usage example: python main.py <type> <dimension> <function> [<signature>]
23
23
  <type>: [p]arents or [c]hildren
24
24
  <dimension>: 4
25
25
  <function>: "{{1,2,3},{1,3,4},{2,3,4}}"
26
- <changed_signs>: optional, e.g. "0100" (bit i=1 means variable i switched sign)
26
+ <signature>: optional target signature, e.g. "1011" (bit i: 1 = positive, 0 = negative variable i)
27
27
  ```
28
28
 
29
29
  **Parents**
@@ -50,12 +50,12 @@ R1 {{1,2,3},{2,3,4}}
50
50
 
51
51
  **Sign changes**
52
52
 
53
- Commands accept an optional trailing `<changed_signs>` argument: a bitstring of the same length as `<dimension>`, where bit `i=1` means variable/regulator `i` switched sign (0->1 or 1->0) with respect to the reference topology. When provided (and not all zeros), parents/children are computed considering that change of signs instead of the default fixed-topology rules:
53
+ Commands accept an optional trailing `<signature>` argument: the target signature, a bitstring of the same length as `<dimension>`, where bit `i` is `1` if variable/regulator `i` is positive and `0` if it is negative. The function is given in the all-positive signature (all 1's). When a signature with some `0` is provided, the closest parents/children in that signature are computed instead of the default fixed-topology rules:
54
54
  ```
55
- python main.py p 4 "{{1,2,3},{1,3,4},{2,3,4}}" 0100
56
- python main.py c 4 "{{1,2,3},{1,3,4},{2,3,4}}" 0100
55
+ python main.py p 4 "{{1,2,3},{1,3,4},{2,3,4}}" 1011
56
+ python main.py c 4 "{{1,2,3},{1,3,4},{2,3,4}}" 1011
57
57
  ```
58
- When omitted (or all zeros), the behaviour is unchanged from above, i.e. fixed-topology.
58
+ When omitted (or all 1's), the behaviour is unchanged from above, i.e. fixed-topology. In the output, `~i` denotes the negated variable `i`: for instance, `python main.py p 3 "{{1,2},{3}}" 101` yields `R1 {{1},{~2},{3}}`.
59
59
 
60
60
  ---
61
61
 
@@ -68,7 +68,7 @@ There is also a graphical interface using Tkinter where the user can define the
68
68
 
69
69
  The interface has a button to automatically write the Infimum function of the chosen dimension, and another for the Supremum function.
70
70
 
71
- A **Changed signs** text box is also available to optionally specify a bitstring of the same length as the dimension, where bit `i=1` means variable/regulator `i` switched sign. Leaving it empty (the default) keeps the fixed-topology behaviour.
71
+ A **Signature** text box is also available to optionally specify the target signature, a bitstring of the same length as the dimension, where bit `i` is `1` if variable/regulator `i` is positive and `0` if it is negative. It is set to all 1's (the default, i.e. the fixed-topology behaviour) and goes back to all 1's whenever the dimension changes. Hovering over it shows a short explanation.
72
72
 
73
73
  The user has two buttons to generate the immediate neighbouring functions: **Generate Parents** to generate the list of parent functions, and **Generate Children** to generate the list of children functions.
74
74
 
@@ -118,12 +118,30 @@ changed_signs = bitarray('0100')
118
118
  s1, s2, s3 = hd.get_f_parents_with_sign_changes(f, changed_signs)
119
119
  ```
120
120
 
121
+ This is the complement of the `<signature>` used by the command line and the GUI: `changed_signs = ~bitarray(signature)`.
122
+
123
+ ---
124
+
125
+ Testing
126
+ -------
127
+
128
+ The library includes a comprehensive pytest suite to validate correctness of the core algorithms:
129
+
130
+ ```bash
131
+ pytest tests/ -v
132
+ ```
133
+
134
+ This runs 22 tests covering:
135
+ - **Sign changes computation** (test_check_sign_changes.py): Validates `get_f_parents/children_with_sign_changes()` by exhaustive checking for small dimensions and random sampling for larger ones
136
+ - **Random walk consistency** (test_check_rules.py): Performs random walks on the Hasse diagram to verify parent-child relationships are consistent
137
+ - **Rule categorization** (test_rule_categorization.py): Validates that parent and children are correctly partitioned into S1, S2, and S3 rules
138
+
121
139
  ---
122
140
 
123
141
  License
124
142
  -------
125
143
 
126
- This code is available under GPL-3.0.
144
+ This code is available under the GNU Affero General Public License v3.0 (AGPL-3.0). See the `LICENSE` file.
127
145
 
128
146
  Cite
129
147
  ----
@@ -1,10 +1,10 @@
1
1
  [build-system]
2
- requires = ["setuptools>=61.0", "wheel"]
2
+ requires = ["setuptools>=61.0", "wheel", "setuptools_scm[toml]>=8"]
3
3
  build-backend = "setuptools.build_meta"
4
4
 
5
5
  [project]
6
6
  name = "pyfunctionhood"
7
- version = "0.2.1"
7
+ dynamic = ["version"]
8
8
  description = "Local computation of immediate neighbours of a given monotone non-degenerate Boolean function"
9
9
  readme = "README.md"
10
10
  requires-python = ">=3.9"
@@ -36,3 +36,7 @@ Repository = "https://github.com/ptgm/pyfunctionhood"
36
36
 
37
37
  [project.scripts]
38
38
  pyfunctionhood = "pyfunctionhood.main:main"
39
+
40
+ [tool.setuptools_scm]
41
+ tag_regex = "^v(?P<version>\\d+\\.\\d+\\.\\d+)$"
42
+ local_scheme = "no-local-version"
@@ -0,0 +1,2 @@
1
+ bitarray
2
+ pytest
@@ -164,16 +164,17 @@ class HasseDiagram:
164
164
  if not invariants:
165
165
  return set(), set(), set()
166
166
 
167
- # One f' per clause s in invariants: f' = sRest union ext(s)
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.)
168
170
  sChildren = set()
169
171
  for s in invariants:
170
172
  sRest = invariants - { s }
171
- s_ext = s
173
+ sExt = set()
172
174
  for l in s.get_off_literals():
173
- candidate = s_ext.clone_add(l)
175
+ candidate = s.clone_add(l)
174
176
  if all(candidate.is_independent(c) for c in sRest):
175
- s_ext = candidate
176
- if s_ext != s: # s unextended would just recreate f, not a child
177
- sChildren.add(Function(self.nvars, sRest | { s_ext }))
177
+ sExt.add(candidate)
178
+ sChildren.add(Function(self.nvars, sRest | sExt))
178
179
 
179
180
  return sChildren, set(), set() # between signature changes only R1 children are possible
@@ -3,6 +3,26 @@ import sys
3
3
  from bitarray import bitarray
4
4
  from .hassediagram import HasseDiagram
5
5
  from .function import Function
6
+ import re
7
+
8
+ def signature_to_changed_signs(signature, ndim):
9
+ """ Converts a target signature (a string of ndim bits, 1 = positive and 0 = negative regulator,
10
+ relative to the all-positive reference) into the bitarray of changed signs expected by the
11
+ get_f_*_with_sign_changes methods. Returns None if no sign changes (empty or all 1's).
12
+ Raises ValueError if the signature is invalid. """
13
+ signature = signature.strip()
14
+ if not signature:
15
+ return None
16
+ if len(signature) != ndim or any(c not in ('0', '1') for c in signature):
17
+ raise ValueError('signature must be a string of ' + str(ndim) + ' bits (0/1)!')
18
+ changed_signs = ~bitarray(signature)
19
+ return changed_signs if changed_signs.count() else None
20
+
21
+ def format_function(f, changed_signs=None):
22
+ """ String of function f, writing variable i as ~i whenever its sign changed. """
23
+ if changed_signs is None:
24
+ return str(f)
25
+ return re.sub(r'\d+', lambda m: ('~' if changed_signs[int(m.group(0)) - 1] else '') + m.group(0), str(f))
6
26
 
7
27
  def GUI_mode():
8
28
  try:
@@ -12,15 +32,33 @@ def GUI_mode():
12
32
  print("Please install tkinter or run in command line mode.")
13
33
  sys.exit(1)
14
34
 
35
+ class ToolTip:
36
+ """Small tooltip shown while the mouse is over a widget."""
37
+ def __init__(self, widget, text):
38
+ self.widget, self.text, self.tip = widget, text, None
39
+ widget.bind('<Enter>', self.show)
40
+ widget.bind('<Leave>', self.hide)
41
+ widget.bind('<ButtonPress>', self.hide)
42
+
43
+ def show(self, event=None):
44
+ if self.tip is not None:
45
+ return
46
+ x = self.widget.winfo_rootx() + 20
47
+ y = self.widget.winfo_rooty() + self.widget.winfo_height() + 4
48
+ self.tip = tk.Toplevel(self.widget)
49
+ self.tip.wm_overrideredirect(True)
50
+ self.tip.wm_geometry('+%d+%d' % (x, y))
51
+ tk.Label(self.tip, text=self.text, justify='left', background='#ffffe0',
52
+ relief='solid', borderwidth=1, padx=6, pady=4).pack()
53
+
54
+ def hide(self, event=None):
55
+ if self.tip is not None:
56
+ self.tip.destroy()
57
+ self.tip = None
58
+
15
59
  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
60
+ """ Returns None if no sign changed, otherwise the bitarray of changed signs. """
61
+ return signature_to_changed_signs(varSignature.get(), idim)
24
62
 
25
63
  def get_parents():
26
64
  try:
@@ -32,9 +70,9 @@ def GUI_mode():
32
70
  s1Parents, s2Parents, s3Parents = hd.get_f_parents(f)
33
71
  else:
34
72
  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]
73
+ lParents = ['R1 ' + format_function(f, changed_signs) for f in s1Parents]\
74
+ + ['R2 ' + format_function(f, changed_signs) for f in s2Parents]\
75
+ + ['R3 ' + format_function(f, changed_signs) for f in s3Parents]
38
76
  output = '** Parents(f) ***\n' + '\n'.join(lParents)
39
77
  except ValueError as e:
40
78
  output = "ERROR! " + str(e)
@@ -51,9 +89,9 @@ def GUI_mode():
51
89
  s1Children, s2Children, s3Children = hd.get_f_children(f)
52
90
  else:
53
91
  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]
92
+ lChildren = ['R1 ' + format_function(f, changed_signs) for f in s1Children]\
93
+ + ['R2 ' + format_function(f, changed_signs) for f in s2Children]\
94
+ + ['R3 ' + format_function(f, changed_signs) for f in s3Children]
57
95
  output = '** Children(f) ***\n' + '\n'.join(lChildren)
58
96
  except ValueError as e:
59
97
  output = "ERROR! " + str(e)
@@ -63,7 +101,7 @@ def GUI_mode():
63
101
  def default_values():
64
102
  varFunction.set('{{1,2,3},{1,3,4},{2,3,4}}')
65
103
  varDimension.set(4)
66
- varChangedSigns.set('')
104
+ varSignature.set('1' * 4)
67
105
  outputText.delete(1.0, "end") # Clear previous output
68
106
  outputText.insert(1.0, '')
69
107
 
@@ -116,11 +154,32 @@ def GUI_mode():
116
154
  entryFunction.grid(row=row, column=1, columnspan=2)
117
155
 
118
156
  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)
157
+ labelSignature = tk.Label(root, text="Signature")
158
+ labelSignature.grid(row=row, column=0, sticky='w')
159
+ varSignature = tk.StringVar(value='1' * varDimension.get()) # all 1's: no sign change
160
+ entrySignature = tk.Entry(root, textvariable=varSignature, width=48)
161
+ entrySignature.grid(row=row, column=1, columnspan=2)
162
+
163
+ def reset_signature(*args):
164
+ """ Whenever the dimension changes, the signature goes back to all 1's. """
165
+ try:
166
+ varSignature.set('1' * int(varDimension.get()))
167
+ except (ValueError, tk.TclError): # dimension field empty or not (yet) a number
168
+ pass
169
+ varDimension.trace_add('write', reset_signature)
170
+
171
+ signatureHelp = ("Target signature: one bit per variable, 1 = positive and 0 = negative regulator.\n"
172
+ "All 1's (the default): no sign change. Set a bit to 0 to flip that variable.\n"
173
+ "\n"
174
+ "For instance, with 3 variables:\n"
175
+ " 101 -> variable 2 is negative\n"
176
+ " 110 -> variable 3 is negative\n"
177
+ "\n"
178
+ "The function is given in the all-positive signature. In the output,\n"
179
+ "~i denotes the negated variable i. The signature is reset to all 1's\n"
180
+ "when the dimension changes.")
181
+ ToolTip(labelSignature, signatureHelp)
182
+ ToolTip(entrySignature, signatureHelp)
124
183
 
125
184
  row += 1
126
185
  bottomFrame = tk.Frame(root, padx=5, pady=5)
@@ -165,11 +224,12 @@ def GUI_mode():
165
224
  def usage():
166
225
  print('\nFor graphical mode, run without arguments: python', sys.argv[0])
167
226
  print('\nFor command line mode, use the following arguments:')
168
- print('Usage example:', sys.argv[0], '<type>', '<dimension>', '<function>', '[<changed_signs>]')
227
+ print('Usage example:', sys.argv[0], '<type>', '<dimension>', '<function>', '[<signature>]')
169
228
  print(' <type>: [p]arents or [c]hildren')
170
229
  print(' <dimension>: 4')
171
230
  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)')
231
+ print(' <signature>: optional target signature, e.g. "1011" (bit i: 1 = positive, 0 = negative variable i;')
232
+ print(' all 1\'s or omitted: no sign change). In the output, ~i denotes the negated variable i')
173
233
  sys.exit(1)
174
234
 
175
235
  def command_line_mode():
@@ -186,31 +246,29 @@ def command_line_mode():
186
246
 
187
247
  changed_signs = None
188
248
  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>')
249
+ try:
250
+ changed_signs = signature_to_changed_signs(sys.argv[4], ndim)
251
+ except ValueError:
252
+ print('ERROR: invalid <signature>')
192
253
  usage()
193
- changed_signs = bitarray(strSigns)
194
- if changed_signs.count() == 0:
195
- changed_signs = None
196
254
 
197
255
  if sys.argv[1] in ('p','parents'):
198
256
  if changed_signs is None:
199
257
  s1Parents, s2Parents, s3Parents = hd.get_f_parents(f)
200
258
  else:
201
259
  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]
260
+ lParents = ['R1 ' + format_function(f, changed_signs) for f in s1Parents]\
261
+ + ['R2 ' + format_function(f, changed_signs) for f in s2Parents]\
262
+ + ['R3 ' + format_function(f, changed_signs) for f in s3Parents]
205
263
  print('\n'.join(lParents))
206
264
  else:
207
265
  if changed_signs is None:
208
266
  s1Children, s2Children, s3Children = hd.get_f_children(f)
209
267
  else:
210
268
  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]
269
+ lChildren = ['R1 ' + format_function(f, changed_signs) for f in s1Children]\
270
+ + ['R2 ' + format_function(f, changed_signs) for f in s2Children]\
271
+ + ['R3 ' + format_function(f, changed_signs) for f in s3Children]
214
272
  print('\n'.join(lChildren))
215
273
 
216
274
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: pyfunctionhood
3
- Version: 0.2.1
3
+ Version: 0.3.1
4
4
  Summary: Local computation of immediate neighbours of a given monotone non-degenerate Boolean function
5
5
  Author-email: "Pedro T. Monteiro" <Pedro.Tiago.Monteiro@tecnico.ulisboa.pt>
6
6
  License: AGPL-3.0
@@ -45,11 +45,11 @@ Given a reference monotone Boolean function, this library can be used in three d
45
45
  Usage - command line
46
46
  --------------------
47
47
  ```
48
- Usage example: python main.py <type> <dimension> <function> [<changed_signs>]
48
+ Usage example: python main.py <type> <dimension> <function> [<signature>]
49
49
  <type>: [p]arents or [c]hildren
50
50
  <dimension>: 4
51
51
  <function>: "{{1,2,3},{1,3,4},{2,3,4}}"
52
- <changed_signs>: optional, e.g. "0100" (bit i=1 means variable i switched sign)
52
+ <signature>: optional target signature, e.g. "1011" (bit i: 1 = positive, 0 = negative variable i)
53
53
  ```
54
54
 
55
55
  **Parents**
@@ -76,12 +76,12 @@ R1 {{1,2,3},{2,3,4}}
76
76
 
77
77
  **Sign changes**
78
78
 
79
- Commands accept an optional trailing `<changed_signs>` argument: a bitstring of the same length as `<dimension>`, where bit `i=1` means variable/regulator `i` switched sign (0->1 or 1->0) with respect to the reference topology. When provided (and not all zeros), parents/children are computed considering that change of signs instead of the default fixed-topology rules:
79
+ Commands accept an optional trailing `<signature>` argument: the target signature, a bitstring of the same length as `<dimension>`, where bit `i` is `1` if variable/regulator `i` is positive and `0` if it is negative. The function is given in the all-positive signature (all 1's). When a signature with some `0` is provided, the closest parents/children in that signature are computed instead of the default fixed-topology rules:
80
80
  ```
81
- python main.py p 4 "{{1,2,3},{1,3,4},{2,3,4}}" 0100
82
- python main.py c 4 "{{1,2,3},{1,3,4},{2,3,4}}" 0100
81
+ python main.py p 4 "{{1,2,3},{1,3,4},{2,3,4}}" 1011
82
+ python main.py c 4 "{{1,2,3},{1,3,4},{2,3,4}}" 1011
83
83
  ```
84
- When omitted (or all zeros), the behaviour is unchanged from above, i.e. fixed-topology.
84
+ When omitted (or all 1's), the behaviour is unchanged from above, i.e. fixed-topology. In the output, `~i` denotes the negated variable `i`: for instance, `python main.py p 3 "{{1,2},{3}}" 101` yields `R1 {{1},{~2},{3}}`.
85
85
 
86
86
  ---
87
87
 
@@ -94,7 +94,7 @@ There is also a graphical interface using Tkinter where the user can define the
94
94
 
95
95
  The interface has a button to automatically write the Infimum function of the chosen dimension, and another for the Supremum function.
96
96
 
97
- A **Changed signs** text box is also available to optionally specify a bitstring of the same length as the dimension, where bit `i=1` means variable/regulator `i` switched sign. Leaving it empty (the default) keeps the fixed-topology behaviour.
97
+ A **Signature** text box is also available to optionally specify the target signature, a bitstring of the same length as the dimension, where bit `i` is `1` if variable/regulator `i` is positive and `0` if it is negative. It is set to all 1's (the default, i.e. the fixed-topology behaviour) and goes back to all 1's whenever the dimension changes. Hovering over it shows a short explanation.
98
98
 
99
99
  The user has two buttons to generate the immediate neighbouring functions: **Generate Parents** to generate the list of parent functions, and **Generate Children** to generate the list of children functions.
100
100
 
@@ -144,12 +144,30 @@ changed_signs = bitarray('0100')
144
144
  s1, s2, s3 = hd.get_f_parents_with_sign_changes(f, changed_signs)
145
145
  ```
146
146
 
147
+ This is the complement of the `<signature>` used by the command line and the GUI: `changed_signs = ~bitarray(signature)`.
148
+
149
+ ---
150
+
151
+ Testing
152
+ -------
153
+
154
+ The library includes a comprehensive pytest suite to validate correctness of the core algorithms:
155
+
156
+ ```bash
157
+ pytest tests/ -v
158
+ ```
159
+
160
+ This runs 22 tests covering:
161
+ - **Sign changes computation** (test_check_sign_changes.py): Validates `get_f_parents/children_with_sign_changes()` by exhaustive checking for small dimensions and random sampling for larger ones
162
+ - **Random walk consistency** (test_check_rules.py): Performs random walks on the Hasse diagram to verify parent-child relationships are consistent
163
+ - **Rule categorization** (test_rule_categorization.py): Validates that parent and children are correctly partitioned into S1, S2, and S3 rules
164
+
147
165
  ---
148
166
 
149
167
  License
150
168
  -------
151
169
 
152
- This code is available under GPL-3.0.
170
+ This code is available under the GNU Affero General Public License v3.0 (AGPL-3.0). See the `LICENSE` file.
153
171
 
154
172
  Cite
155
173
  ----
@@ -1,6 +1,11 @@
1
+ .gitignore
1
2
  LICENSE
3
+ MANIFEST.in
2
4
  README.md
3
5
  pyproject.toml
6
+ requirements.txt
7
+ .github/workflows/python-publish.yml
8
+ img/pyfunctionhood.png
4
9
  src/pyfunctionhood/__init__.py
5
10
  src/pyfunctionhood/clause.py
6
11
  src/pyfunctionhood/function.py
@@ -12,4 +17,9 @@ src/pyfunctionhood.egg-info/SOURCES.txt
12
17
  src/pyfunctionhood.egg-info/dependency_links.txt
13
18
  src/pyfunctionhood.egg-info/entry_points.txt
14
19
  src/pyfunctionhood.egg-info/requires.txt
15
- src/pyfunctionhood.egg-info/top_level.txt
20
+ src/pyfunctionhood.egg-info/scm_file_list.json
21
+ src/pyfunctionhood.egg-info/scm_version.json
22
+ src/pyfunctionhood.egg-info/top_level.txt
23
+ tests/test_check_rules.py
24
+ tests/test_check_sign_changes.py
25
+ tests/test_rule_categorization.py
@@ -0,0 +1,109 @@
1
+ {
2
+ "files": [
3
+ ".github/workflows/python-publish.yml",
4
+ ".gitignore",
5
+ "LICENSE",
6
+ "MANIFEST.in",
7
+ "README.md",
8
+ "experiments/README.md",
9
+ "experiments/fig_sc_cost.py",
10
+ "experiments/fig_sc_neighbourhood.py",
11
+ "experiments/requirements.txt",
12
+ "experiments/results/n2_k0_s10_r10_b10.txt",
13
+ "experiments/results/n2_k1_s10_r10_b10.txt",
14
+ "experiments/results/n2_k2_s10_r10_b10.txt",
15
+ "experiments/results/n3_k0_s10_r10_b10.txt",
16
+ "experiments/results/n3_k1_s10_r10_b10.txt",
17
+ "experiments/results/n3_k2_s10_r10_b10.txt",
18
+ "experiments/results/n3_k3_s10_r10_b10.txt",
19
+ "experiments/results/n4_k0_s10_r10_b10.txt",
20
+ "experiments/results/n4_k1_s10_r10_b10.txt",
21
+ "experiments/results/n4_k2_s10_r10_b10.txt",
22
+ "experiments/results/n4_k3_s10_r10_b10.txt",
23
+ "experiments/results/n4_k4_s10_r10_b10.txt",
24
+ "experiments/results/n5_k0_s10_r10_b10.txt",
25
+ "experiments/results/n5_k1_s10_r10_b10.txt",
26
+ "experiments/results/n5_k2_s10_r10_b10.txt",
27
+ "experiments/results/n5_k3_s10_r10_b10.txt",
28
+ "experiments/results/n5_k4_s10_r10_b10.txt",
29
+ "experiments/results/n5_k5_s10_r10_b10.txt",
30
+ "experiments/results/n6_k0_s10_r10_b10.txt",
31
+ "experiments/results/n6_k1_s10_r10_b10.txt",
32
+ "experiments/results/n6_k2_s10_r10_b10.txt",
33
+ "experiments/results/n6_k3_s10_r10_b10.txt",
34
+ "experiments/results/n6_k4_s10_r10_b10.txt",
35
+ "experiments/results/n6_k5_s10_r10_b10.txt",
36
+ "experiments/results/n6_k6_s10_r10_b10.txt",
37
+ "experiments/results/n7_k0_s10_r10_b10.txt",
38
+ "experiments/results/n7_k1_s10_r10_b10.txt",
39
+ "experiments/results/n7_k2_s10_r10_b10.txt",
40
+ "experiments/results/n7_k3_s10_r10_b10.txt",
41
+ "experiments/results/n7_k4_s10_r10_b10.txt",
42
+ "experiments/results/n7_k5_s10_r10_b10.txt",
43
+ "experiments/results/n7_k6_s10_r10_b10.txt",
44
+ "experiments/results/n7_k7_s10_r10_b10.txt",
45
+ "experiments/results/n8_k0_s10_r10_b10.txt",
46
+ "experiments/results/n8_k1_s10_r10_b10.txt",
47
+ "experiments/results/n8_k2_s10_r10_b10.txt",
48
+ "experiments/results/n8_k3_s10_r10_b10.txt",
49
+ "experiments/results/n8_k4_s10_r10_b10.txt",
50
+ "experiments/results/n8_k5_s10_r10_b10.txt",
51
+ "experiments/results/n8_k6_s10_r10_b10.txt",
52
+ "experiments/results/n8_k7_s10_r10_b10.txt",
53
+ "experiments/results/n8_k8_s10_r10_b10.txt",
54
+ "experiments/results/neigh_n2_k0_s100.txt",
55
+ "experiments/results/neigh_n2_k1_s100.txt",
56
+ "experiments/results/neigh_n2_k2_s100.txt",
57
+ "experiments/results/neigh_n3_k0_s100.txt",
58
+ "experiments/results/neigh_n3_k1_s100.txt",
59
+ "experiments/results/neigh_n3_k2_s100.txt",
60
+ "experiments/results/neigh_n3_k3_s100.txt",
61
+ "experiments/results/neigh_n4_k0_s100.txt",
62
+ "experiments/results/neigh_n4_k1_s100.txt",
63
+ "experiments/results/neigh_n4_k2_s100.txt",
64
+ "experiments/results/neigh_n4_k3_s100.txt",
65
+ "experiments/results/neigh_n4_k4_s100.txt",
66
+ "experiments/results/neigh_n5_k0_s100.txt",
67
+ "experiments/results/neigh_n5_k1_s100.txt",
68
+ "experiments/results/neigh_n5_k2_s100.txt",
69
+ "experiments/results/neigh_n5_k3_s100.txt",
70
+ "experiments/results/neigh_n5_k4_s100.txt",
71
+ "experiments/results/neigh_n5_k5_s100.txt",
72
+ "experiments/results/neigh_n6_k0_s100.txt",
73
+ "experiments/results/neigh_n6_k1_s100.txt",
74
+ "experiments/results/neigh_n6_k2_s100.txt",
75
+ "experiments/results/neigh_n6_k3_s100.txt",
76
+ "experiments/results/neigh_n6_k4_s100.txt",
77
+ "experiments/results/neigh_n6_k5_s100.txt",
78
+ "experiments/results/neigh_n6_k6_s100.txt",
79
+ "experiments/results/neigh_n7_k0_s40.txt",
80
+ "experiments/results/neigh_n7_k1_s40.txt",
81
+ "experiments/results/neigh_n7_k2_s40.txt",
82
+ "experiments/results/neigh_n7_k3_s40.txt",
83
+ "experiments/results/neigh_n7_k4_s40.txt",
84
+ "experiments/results/neigh_n7_k5_s40.txt",
85
+ "experiments/results/neigh_n7_k6_s40.txt",
86
+ "experiments/results/neigh_n7_k7_s40.txt",
87
+ "experiments/results/neigh_n8_k0_s20.txt",
88
+ "experiments/results/neigh_n8_k1_s20.txt",
89
+ "experiments/results/neigh_n8_k2_s20.txt",
90
+ "experiments/results/neigh_n8_k3_s20.txt",
91
+ "experiments/results/neigh_n8_k4_s20.txt",
92
+ "experiments/results/neigh_n8_k5_s20.txt",
93
+ "experiments/results/neigh_n8_k6_s20.txt",
94
+ "experiments/results/neigh_n8_k7_s20.txt",
95
+ "experiments/results/neigh_n8_k8_s20.txt",
96
+ "img/pyfunctionhood.png",
97
+ "pyproject.toml",
98
+ "requirements.txt",
99
+ "src/pyfunctionhood/__init__.py",
100
+ "src/pyfunctionhood/clause.py",
101
+ "src/pyfunctionhood/function.py",
102
+ "src/pyfunctionhood/hassediagram.py",
103
+ "src/pyfunctionhood/main.py",
104
+ "src/pyfunctionhood/powerset.py",
105
+ "tests/test_check_rules.py",
106
+ "tests/test_check_sign_changes.py",
107
+ "tests/test_rule_categorization.py"
108
+ ]
109
+ }
@@ -0,0 +1,8 @@
1
+ {
2
+ "tag": "0.3.1",
3
+ "distance": 0,
4
+ "node": "g210892b6f9476129011d38c3cc0d273f5912c464",
5
+ "dirty": false,
6
+ "branch": "HEAD",
7
+ "node_date": "2026-11-23"
8
+ }
@@ -0,0 +1,110 @@
1
+ """Pytest for consistency of parent-child relationships in Hasse diagrams.
2
+
3
+ This module contains tests that verify parent-child relationships are
4
+ consistent by performing random walks on the Hasse diagram, both from
5
+ infimum to supremum and from supremum to infimum.
6
+ """
7
+ import pytest
8
+ import random
9
+ from pyfunctionhood import HasseDiagram
10
+
11
+
12
+ def random_walk_infimum_to_supremum(hd, num_walks=10):
13
+ """Perform random walks from infimum to supremum.
14
+
15
+ For each walk, verify that at every step, the previous function
16
+ is indeed a child of the randomly chosen parent.
17
+
18
+ Args:
19
+ hd: HasseDiagram instance
20
+ num_walks: number of independent random walks to perform
21
+
22
+ Returns:
23
+ Tuple of (failed, total_steps) where failed is True if any walk failed
24
+ """
25
+ finf = hd.get_infimum()
26
+ fsup = hd.get_supremum()
27
+
28
+ for walk in range(num_walks):
29
+ f = finf
30
+ while f != fsup:
31
+ s1Parents, s2Parents, s3Parents = hd.get_f_parents(f)
32
+ lParents = list(s1Parents) + list(s2Parents) + list(s3Parents)
33
+
34
+ # Randomly choose a parent
35
+ parent = lParents[random.randint(0, len(lParents) - 1)]
36
+
37
+ # Verify that f is indeed a child of parent
38
+ s1Children, s2Children, s3Children = hd.get_f_children(parent)
39
+ if not (f in s1Children or f in s2Children or f in s3Children):
40
+ return True, walk, f, parent # Failed
41
+
42
+ f = parent
43
+
44
+ return False, num_walks, None, None # Success
45
+
46
+
47
+ def random_walk_supremum_to_infimum(hd, num_walks=10):
48
+ """Perform random walks from supremum to infimum.
49
+
50
+ For each walk, verify that at every step, the previous function
51
+ is indeed a parent of the randomly chosen child.
52
+
53
+ Args:
54
+ hd: HasseDiagram instance
55
+ num_walks: number of independent random walks to perform
56
+
57
+ Returns:
58
+ Tuple of (failed, total_steps) where failed is True if any walk failed
59
+ """
60
+ finf = hd.get_infimum()
61
+ fsup = hd.get_supremum()
62
+
63
+ for walk in range(num_walks):
64
+ f = fsup
65
+ while f != finf:
66
+ s1Children, s2Children, s3Children = hd.get_f_children(f)
67
+ lChildren = list(s1Children) + list(s2Children) + list(s3Children)
68
+
69
+ # Randomly choose a child
70
+ child = lChildren[random.randint(0, len(lChildren) - 1)]
71
+
72
+ # Verify that f is indeed a parent of child
73
+ s1Parents, s2Parents, s3Parents = hd.get_f_parents(child)
74
+ if not (f in s1Parents or f in s2Parents or f in s3Parents):
75
+ return True, walk, f, child # Failed
76
+
77
+ f = child
78
+
79
+ return False, num_walks, None, None # Success
80
+
81
+
82
+ @pytest.mark.parametrize("n", [2, 3, 4, 5, 6])
83
+ def test_hasse_diagram_rules_infimum_to_supremum(n):
84
+ """Test parent-child consistency with random walks from infimum to supremum.
85
+
86
+ Performs 10 independent random walks from the infimum (0) to supremum (1)
87
+ on the Hasse diagram, verifying that at each step, the previous function
88
+ is indeed a child of the randomly chosen parent.
89
+ """
90
+ hd = HasseDiagram(n)
91
+ failed, walk, f, parent = random_walk_infimum_to_supremum(hd, num_walks=10)
92
+ assert not failed, f"Walk failed at walk {walk} for n={n}: f={f} is not a child of parent={parent}"
93
+
94
+
95
+ @pytest.mark.parametrize("n", [2, 3, 4, 5, 6])
96
+ def test_hasse_diagram_rules_supremum_to_infimum(n):
97
+ """Test parent-child consistency with random walks from supremum to infimum.
98
+
99
+ Performs 10 independent random walks from the supremum (1) to infimum (0)
100
+ on the Hasse diagram, verifying that at each step, the previous function
101
+ is indeed a parent of the randomly chosen child.
102
+ """
103
+ hd = HasseDiagram(n)
104
+ failed, walk, f, child = random_walk_supremum_to_infimum(hd, num_walks=10)
105
+ assert not failed, f"Walk failed at walk {walk} for n={n}: f={f} is not a parent of child={child}"
106
+
107
+
108
+ if __name__ == "__main__":
109
+ # Allow running directly with: python -m pytest tests/test_check_rules.py
110
+ pytest.main([__file__, "-v"])
@@ -0,0 +1,130 @@
1
+ """Pytest for sign changes validation using checkSignChanges.
2
+
3
+ This module contains parameterized tests that validate the correctness of
4
+ get_f_parents/children_with_sign_changes by checking against brute-force
5
+ exhaustive or sampled (f, K) pairs.
6
+ """
7
+ #A test case is a pair (f, K): f a non-degenerate monotone function
8
+ #over n variables and K a non-empty set of variables whose sign changes.
9
+ #Number of pairs = #functions * (2^n - 1):
10
+ #
11
+ # n #functions #K = 2^n - 1 #pairs (f, K)
12
+ # 2 2 3 6
13
+ # 3 9 7 63
14
+ # 4 114 15 1,710
15
+ # 5 6,894 31 213,714 - tested below for 100 random pairs
16
+ # 6 7,785,062 63 ~4.9 * 10^8
17
+ # 7 ~2.4 * 10^12 127 ~3.1 * 10^14
18
+ # 8 ~5.6 * 10^22 255 ~1.4 * 10^25
19
+
20
+ import pytest
21
+ import sys
22
+ import random
23
+ from bitarray import bitarray
24
+ from pyfunctionhood import HasseDiagram, Function, Clause
25
+
26
+
27
+ def all_functions(n):
28
+ """Generate all non-degenerate monotone functions over n variables."""
29
+ full = (1 << n) - 1
30
+ subsets = sorted(range(1, full + 1), key=lambda s: (bin(s).count('1'), s))
31
+ res = []
32
+ def rec(i, cur):
33
+ if i == len(subsets):
34
+ u = 0
35
+ for c in cur: u |= c
36
+ if u == full: res.append(frozenset(cur))
37
+ return
38
+ rec(i + 1, cur)
39
+ s = subsets[i]
40
+ if all((s & c) != c and (s & c) != s for c in cur):
41
+ cur.append(s); rec(i + 1, cur); cur.pop()
42
+ rec(0, [])
43
+ return res
44
+
45
+
46
+ def true_set(fn, n, K):
47
+ """Compute the true set of a function with sign changes in variables K.
48
+
49
+ Variables in K are negative: a literal is true iff x_i == 0.
50
+ """
51
+ return frozenset(x for x in range(1 << n) if any(((x ^ K) & s) == s for s in fn))
52
+
53
+
54
+ def to_fn(n, masks):
55
+ """Convert from mask representation to Function object."""
56
+ return Function(n, {Clause(bitarray(''.join('1' if (m >> i) & 1 else '0' for i in range(n)))) for m in masks})
57
+
58
+
59
+ def from_fn(f):
60
+ """Convert from Function object to mask representation."""
61
+ return frozenset(sum(1 << i for i in c.get_on_literals()) for c in f.get_clauses())
62
+
63
+
64
+ def check_dimension(n, sample=None):
65
+ """Check all (f, K) pairs for dimension n.
66
+
67
+ Args:
68
+ n: number of variables
69
+ sample: if None, do exhaustive check; otherwise randomly sample this many pairs
70
+
71
+ Returns:
72
+ Tuple of (mismatches, total_pairs_checked)
73
+ """
74
+ hd = HasseDiagram(n)
75
+ bad = tot = 0
76
+
77
+ if sample is None: # exhaustive: need all functions
78
+ funcs = all_functions(n)
79
+ Tpos = {f: true_set(f, n, 0) for f in funcs}
80
+ pairs = {K: funcs for K in range(1, 1 << n)}
81
+ else: # random (f,K) pairs: only generate functions as needed
82
+ funcs = all_functions(n) # Still need all for comparison, but cache results
83
+ Tpos = {f: true_set(f, n, 0) for f in funcs}
84
+ pairs = {}
85
+ for _ in range(sample):
86
+ pairs.setdefault(random.randrange(1, 1 << n), []).append(random.choice(funcs))
87
+
88
+ for K, fs in pairs.items():
89
+ Tk = {f: true_set(f, n, K) for f in funcs}
90
+ Kb = bitarray(''.join('1' if (K >> i) & 1 else '0' for i in range(n)))
91
+ for f in fs:
92
+ up = [g for g in funcs if Tpos[f] <= Tk[g]]
93
+ down = [g for g in funcs if Tk[g] <= Tpos[f]]
94
+ mn = {g for g in up if not any(Tk[h] < Tk[g] for h in up)}
95
+ mx = {g for g in down if not any(Tk[g] < Tk[h] for h in down)}
96
+ P, _, _ = hd.get_f_parents_with_sign_changes(to_fn(n, f), Kb)
97
+ C, _, _ = hd.get_f_children_with_sign_changes(to_fn(n, f), Kb)
98
+ tot += 1
99
+ if {from_fn(g) for g in P} != mn or {from_fn(g) for g in C} != mx:
100
+ bad += 1
101
+
102
+ return bad, tot
103
+
104
+
105
+ @pytest.mark.parametrize("n", [2, 3, 4])
106
+ def test_sign_changes_exhaustive(n):
107
+ """Test sign changes with exhaustive checking for n=2,3,4.
108
+
109
+ For small dimensions (n <= 4), all (f, K) pairs are checked.
110
+ """
111
+ mismatches, total = check_dimension(n, sample=None)
112
+ assert mismatches == 0, f"Found {mismatches} mismatches in {total} (f, K) pairs for n={n}"
113
+
114
+
115
+ @pytest.mark.parametrize("n,sample", [(5, 100)])
116
+ def test_sign_changes_sampled(n, sample):
117
+ """Test sign changes with random sampling for larger dimensions.
118
+
119
+ For n=5 with 100 random (f, K) pairs sampled.
120
+ Note: n=6 would require generating 7.7M functions just to check 1 pair,
121
+ so it's not practical for routine testing.
122
+ """
123
+ mismatches, total = check_dimension(n, sample=sample)
124
+ assert mismatches == 0, f"Found {mismatches} mismatches in {total} sampled (f, K) pairs for n={n} (sample={sample})"
125
+
126
+
127
+
128
+ if __name__ == "__main__":
129
+ # Allow running directly with: python -m pytest tests/test_check_sign_changes.py
130
+ pytest.main([__file__, "-v"])
@@ -0,0 +1,117 @@
1
+ """Pytest for rule categorization (S1, S2, S3) in parent-child relationships.
2
+
3
+ This module validates that parents and children are correctly categorized
4
+ into S1, S2, and S3 rules, and that the categorization is exhaustive and
5
+ consistent.
6
+ """
7
+ import pytest
8
+ from pyfunctionhood import HasseDiagram
9
+
10
+
11
+ def test_rule_categorization_completeness(n=4):
12
+ """Verify that all parents/children are categorized into exactly one rule.
13
+
14
+ Every parent must belong to exactly one of S1, S2, or S3.
15
+ Every child must belong to exactly one of S1, S2, or S3.
16
+ """
17
+ hd = HasseDiagram(n)
18
+ finf = hd.get_infimum()
19
+
20
+ # Sample some functions at different levels
21
+ s1Parents, s2Parents, s3Parents = hd.get_f_parents(finf)
22
+
23
+ # Check partition properties: sets should be disjoint
24
+ assert len(s1Parents & s2Parents) == 0, "S1 and S2 parents overlap"
25
+ assert len(s2Parents & s3Parents) == 0, "S2 and S3 parents overlap"
26
+ assert len(s1Parents & s3Parents) == 0, "S1 and S3 parents overlap"
27
+
28
+ # Check that union equals total (optional, but good for exhaustiveness)
29
+ all_parents = s1Parents | s2Parents | s3Parents
30
+ assert len(all_parents) > 0, "No parents found"
31
+
32
+
33
+ @pytest.mark.parametrize("n", [2, 3, 4])
34
+ def test_rule_categorization_consistency(n):
35
+ """Test that rule categorization is consistent across multiple queries.
36
+
37
+ For several functions, verify that:
38
+ 1. Each parent/child belongs to exactly one rule category
39
+ 2. Getting the same parent/child again yields the same categorization
40
+ """
41
+ hd = HasseDiagram(n)
42
+ finf = hd.get_infimum()
43
+ fsup = hd.get_supremum()
44
+
45
+ # Test parents of infimum
46
+ s1P, s2P, s3P = hd.get_f_parents(finf)
47
+
48
+ # Verify partition
49
+ assert len(s1P & s2P) == 0 and len(s2P & s3P) == 0 and len(s1P & s3P) == 0, \
50
+ f"n={n}: Parents not properly partitioned into disjoint sets"
51
+
52
+ # Verify at least one rule is non-empty
53
+ assert len(s1P) + len(s2P) + len(s3P) > 0, \
54
+ f"n={n}: No parents found for infimum"
55
+
56
+ # Test children of supremum
57
+ s1C, s2C, s3C = hd.get_f_children(fsup)
58
+
59
+ # Verify partition
60
+ assert len(s1C & s2C) == 0 and len(s2C & s3C) == 0 and len(s1C & s3C) == 0, \
61
+ f"n={n}: Children not properly partitioned into disjoint sets"
62
+
63
+ # Verify at least one rule is non-empty
64
+ assert len(s1C) + len(s2C) + len(s3C) > 0, \
65
+ f"n={n}: No children found for supremum"
66
+
67
+
68
+ @pytest.mark.parametrize("n", [2, 3, 4])
69
+ def test_rule_coverage_across_dimensions(n):
70
+ """Verify that rules are non-empty in the Hasse diagram.
71
+
72
+ For small to medium dimensions, at least S3 should appear
73
+ (S1 and S2 may require intermediate functions).
74
+ """
75
+ hd = HasseDiagram(n)
76
+ finf = hd.get_infimum()
77
+ fsup = hd.get_supremum()
78
+
79
+ # Infimum should have S3 parents
80
+ s1P, s2P, s3P = hd.get_f_parents(finf)
81
+ assert len(s3P) > 0, f"n={n}: Infimum should have S3 parents"
82
+
83
+ # Supremum should have S3 children
84
+ s1C, s2C, s3C = hd.get_f_children(fsup)
85
+ assert len(s3C) > 0, f"n={n}: Supremum should have S3 children"
86
+
87
+
88
+ def test_infimum_supremum_duality(n=4):
89
+ """Test duality: infimum and supremum should have complementary properties.
90
+
91
+ The infimum has only parents (no parents of parents...).
92
+ The supremum has only children (no children of children...).
93
+ """
94
+ hd = HasseDiagram(n)
95
+ finf = hd.get_infimum()
96
+ fsup = hd.get_supremum()
97
+
98
+ # Infimum has parents but no children
99
+ s1P, s2P, s3P = hd.get_f_parents(finf)
100
+ s1C, s2C, s3C = hd.get_f_children(finf)
101
+
102
+ assert len(s1P) + len(s2P) + len(s3P) > 0, f"Infimum has no parents (n={n})"
103
+ assert len(s1C) == 0 and len(s2C) == 0 and len(s3C) == 0, \
104
+ f"Infimum should have no children (n={n})"
105
+
106
+ # Supremum has children but no parents
107
+ s1P, s2P, s3P = hd.get_f_parents(fsup)
108
+ s1C, s2C, s3C = hd.get_f_children(fsup)
109
+
110
+ assert len(s1C) + len(s2C) + len(s3C) > 0, f"Supremum has no children (n={n})"
111
+ assert len(s1P) == 0 and len(s2P) == 0 and len(s3P) == 0, \
112
+ f"Supremum should have no parents (n={n})"
113
+
114
+
115
+ if __name__ == "__main__":
116
+ # Allow running directly with: python -m pytest tests/test_rule_categorization.py
117
+ pytest.main([__file__, "-v"])
File without changes
File without changes