pyfunctionhood 0.1.2__tar.gz → 0.3.0__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.
- pyfunctionhood-0.3.0/.github/workflows/python-publish.yml +47 -0
- pyfunctionhood-0.3.0/.gitignore +8 -0
- {pyfunctionhood-0.1.2/src/pyfunctionhood.egg-info → pyfunctionhood-0.3.0}/PKG-INFO +43 -7
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/README.md +42 -5
- pyfunctionhood-0.3.0/img/pyfunctionhood.png +0 -0
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/pyproject.toml +7 -7
- pyfunctionhood-0.3.0/requirements.txt +2 -0
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/src/pyfunctionhood/clause.py +3 -3
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/src/pyfunctionhood/hassediagram.py +55 -0
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/src/pyfunctionhood/main.py +54 -9
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/src/pyfunctionhood/powerset.py +2 -2
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0/src/pyfunctionhood.egg-info}/PKG-INFO +43 -7
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/src/pyfunctionhood.egg-info/SOURCES.txt +10 -1
- pyfunctionhood-0.3.0/src/pyfunctionhood.egg-info/scm_file_list.json +20 -0
- pyfunctionhood-0.3.0/src/pyfunctionhood.egg-info/scm_version.json +8 -0
- pyfunctionhood-0.3.0/tests/test_check_rules.py +110 -0
- pyfunctionhood-0.3.0/tests/test_check_sign_changes.py +130 -0
- pyfunctionhood-0.3.0/tests/test_rule_categorization.py +117 -0
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/LICENSE +0 -0
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/setup.cfg +0 -0
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/src/pyfunctionhood/__init__.py +0 -0
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/src/pyfunctionhood/function.py +0 -0
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/src/pyfunctionhood.egg-info/dependency_links.txt +0 -0
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/src/pyfunctionhood.egg-info/entry_points.txt +0 -0
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/src/pyfunctionhood.egg-info/requires.txt +0 -0
- {pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/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 }}
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyfunctionhood
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Local computation of immediate neighbours of a given monotone non-degenerate Boolean function
|
|
5
|
-
Author: Patrícia Roxo, José E. R. Cury, Vasco Manquinho, Claudine Chaouiya
|
|
6
5
|
Author-email: "Pedro T. Monteiro" <Pedro.Tiago.Monteiro@tecnico.ulisboa.pt>
|
|
7
6
|
License: AGPL-3.0
|
|
8
7
|
Project-URL: Homepage, https://github.com/ptgm/pyfunctionhood
|
|
@@ -34,7 +33,7 @@ Here, immediate neighbours, are the monotone Boolean functions that are immediat
|
|
|
34
33
|
|
|
35
34
|
Monotone non-degenerate Boolean functions are represented as sets of clauses, where each clause is represented by the bitarray data structure, and each bit represents the presence/absence of a given variable/regulator.
|
|
36
35
|
|
|
37
|
-
This work
|
|
36
|
+
This work is developed in Python in [https://github.com/ptgm/pyfunctionhood/](https://github.com/ptgm/pyfunctionhood/), correcting and extending our previous work developed in Java in [https://github.com/ptgm/functionhood/](https://github.com/ptgm/functionhood/) and described in [arxiv:1901.07623](https://arxiv.org/abs/1901.07623).
|
|
38
37
|
|
|
39
38
|
Given a reference monotone Boolean function, this library can be used in three distinct manners:
|
|
40
39
|
- in the command line passing the reference function as an argument
|
|
@@ -46,10 +45,11 @@ Given a reference monotone Boolean function, this library can be used in three d
|
|
|
46
45
|
Usage - command line
|
|
47
46
|
--------------------
|
|
48
47
|
```
|
|
49
|
-
Usage example: python main.py <type> <dimension> <function>
|
|
50
|
-
<type>:
|
|
51
|
-
<dimension>:
|
|
52
|
-
<function>:
|
|
48
|
+
Usage example: python main.py <type> <dimension> <function> [<changed_signs>]
|
|
49
|
+
<type>: [p]arents or [c]hildren
|
|
50
|
+
<dimension>: 4
|
|
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)
|
|
53
53
|
```
|
|
54
54
|
|
|
55
55
|
**Parents**
|
|
@@ -74,6 +74,15 @@ R1 {{1,2,3},{1,3,4}}
|
|
|
74
74
|
R1 {{1,2,3},{2,3,4}}
|
|
75
75
|
```
|
|
76
76
|
|
|
77
|
+
**Sign changes**
|
|
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:
|
|
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
|
|
83
|
+
```
|
|
84
|
+
When omitted (or all zeros), the behaviour is unchanged from above, i.e. fixed-topology.
|
|
85
|
+
|
|
77
86
|
---
|
|
78
87
|
|
|
79
88
|
Usage - Graphical interface
|
|
@@ -85,6 +94,8 @@ There is also a graphical interface using Tkinter where the user can define the
|
|
|
85
94
|
|
|
86
95
|
The interface has a button to automatically write the Infimum function of the chosen dimension, and another for the Supremum function.
|
|
87
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.
|
|
98
|
+
|
|
88
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.
|
|
89
100
|
|
|
90
101
|
In the text area the immediate neighbouring functions are shown, as well as any error if an invalid function is provided.
|
|
@@ -124,6 +135,31 @@ print('\n'.join(['R1 ' + str(f) for f in s1]\
|
|
|
124
135
|
+ ['R3 ' + str(f) for f in s3]))
|
|
125
136
|
```
|
|
126
137
|
|
|
138
|
+
**Sign changes**
|
|
139
|
+
|
|
140
|
+
To compute parents/children considering that some variables/regulators switched sign, use `hd.get_f_parents_with_sign_changes(f, changed_signs)` or `hd.get_f_children_with_sign_changes(f, changed_signs)`, where `changed_signs` is a `bitarray` of the same size as the dimension, with bit `i` set to `True` if variable `i` switched sign:
|
|
141
|
+
```
|
|
142
|
+
from bitarray import bitarray
|
|
143
|
+
changed_signs = bitarray('0100')
|
|
144
|
+
s1, s2, s3 = hd.get_f_parents_with_sign_changes(f, changed_signs)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
Testing
|
|
150
|
+
-------
|
|
151
|
+
|
|
152
|
+
The library includes a comprehensive pytest suite to validate correctness of the core algorithms:
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
pytest tests/ -v
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
This runs 22 tests covering:
|
|
159
|
+
- **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
|
|
160
|
+
- **Random walk consistency** (test_check_rules.py): Performs random walks on the Hasse diagram to verify parent-child relationships are consistent
|
|
161
|
+
- **Rule categorization** (test_rule_categorization.py): Validates that parent and children are correctly partitioned into S1, S2, and S3 rules
|
|
162
|
+
|
|
127
163
|
---
|
|
128
164
|
|
|
129
165
|
License
|
|
@@ -7,7 +7,7 @@ Here, immediate neighbours, are the monotone Boolean functions that are immediat
|
|
|
7
7
|
|
|
8
8
|
Monotone non-degenerate Boolean functions are represented as sets of clauses, where each clause is represented by the bitarray data structure, and each bit represents the presence/absence of a given variable/regulator.
|
|
9
9
|
|
|
10
|
-
This work
|
|
10
|
+
This work is developed in Python in [https://github.com/ptgm/pyfunctionhood/](https://github.com/ptgm/pyfunctionhood/), correcting and extending our previous work developed in Java in [https://github.com/ptgm/functionhood/](https://github.com/ptgm/functionhood/) and described in [arxiv:1901.07623](https://arxiv.org/abs/1901.07623).
|
|
11
11
|
|
|
12
12
|
Given a reference monotone Boolean function, this library can be used in three distinct manners:
|
|
13
13
|
- in the command line passing the reference function as an argument
|
|
@@ -19,10 +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>
|
|
23
|
-
<type>:
|
|
24
|
-
<dimension>:
|
|
25
|
-
<function>:
|
|
22
|
+
Usage example: python main.py <type> <dimension> <function> [<changed_signs>]
|
|
23
|
+
<type>: [p]arents or [c]hildren
|
|
24
|
+
<dimension>: 4
|
|
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
27
|
```
|
|
27
28
|
|
|
28
29
|
**Parents**
|
|
@@ -47,6 +48,15 @@ R1 {{1,2,3},{1,3,4}}
|
|
|
47
48
|
R1 {{1,2,3},{2,3,4}}
|
|
48
49
|
```
|
|
49
50
|
|
|
51
|
+
**Sign changes**
|
|
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:
|
|
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
|
|
57
|
+
```
|
|
58
|
+
When omitted (or all zeros), the behaviour is unchanged from above, i.e. fixed-topology.
|
|
59
|
+
|
|
50
60
|
---
|
|
51
61
|
|
|
52
62
|
Usage - Graphical interface
|
|
@@ -58,6 +68,8 @@ There is also a graphical interface using Tkinter where the user can define the
|
|
|
58
68
|
|
|
59
69
|
The interface has a button to automatically write the Infimum function of the chosen dimension, and another for the Supremum function.
|
|
60
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.
|
|
72
|
+
|
|
61
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.
|
|
62
74
|
|
|
63
75
|
In the text area the immediate neighbouring functions are shown, as well as any error if an invalid function is provided.
|
|
@@ -97,6 +109,31 @@ print('\n'.join(['R1 ' + str(f) for f in s1]\
|
|
|
97
109
|
+ ['R3 ' + str(f) for f in s3]))
|
|
98
110
|
```
|
|
99
111
|
|
|
112
|
+
**Sign changes**
|
|
113
|
+
|
|
114
|
+
To compute parents/children considering that some variables/regulators switched sign, use `hd.get_f_parents_with_sign_changes(f, changed_signs)` or `hd.get_f_children_with_sign_changes(f, changed_signs)`, where `changed_signs` is a `bitarray` of the same size as the dimension, with bit `i` set to `True` if variable `i` switched sign:
|
|
115
|
+
```
|
|
116
|
+
from bitarray import bitarray
|
|
117
|
+
changed_signs = bitarray('0100')
|
|
118
|
+
s1, s2, s3 = hd.get_f_parents_with_sign_changes(f, changed_signs)
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
---
|
|
122
|
+
|
|
123
|
+
Testing
|
|
124
|
+
-------
|
|
125
|
+
|
|
126
|
+
The library includes a comprehensive pytest suite to validate correctness of the core algorithms:
|
|
127
|
+
|
|
128
|
+
```bash
|
|
129
|
+
pytest tests/ -v
|
|
130
|
+
```
|
|
131
|
+
|
|
132
|
+
This runs 22 tests covering:
|
|
133
|
+
- **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
|
|
134
|
+
- **Random walk consistency** (test_check_rules.py): Performs random walks on the Hasse diagram to verify parent-child relationships are consistent
|
|
135
|
+
- **Rule categorization** (test_rule_categorization.py): Validates that parent and children are correctly partitioned into S1, S2, and S3 rules
|
|
136
|
+
|
|
100
137
|
---
|
|
101
138
|
|
|
102
139
|
License
|
|
Binary file
|
|
@@ -1,20 +1,16 @@
|
|
|
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
|
-
|
|
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"
|
|
11
11
|
license = { text = "AGPL-3.0" }
|
|
12
12
|
authors = [
|
|
13
|
-
{ name = "Pedro T. Monteiro", email="Pedro.Tiago.Monteiro@tecnico.ulisboa.pt" }
|
|
14
|
-
{ name = "Patrícia Roxo" },
|
|
15
|
-
{ name = "José E. R. Cury" },
|
|
16
|
-
{ name = "Vasco Manquinho" },
|
|
17
|
-
{ name = "Claudine Chaouiya" }
|
|
13
|
+
{ name = "Pedro T. Monteiro", email="Pedro.Tiago.Monteiro@tecnico.ulisboa.pt" }
|
|
18
14
|
]
|
|
19
15
|
keywords = ["boolean", "monotone", "hasse-diagram", "functions", "bitarray"]
|
|
20
16
|
classifiers = [
|
|
@@ -40,3 +36,7 @@ Repository = "https://github.com/ptgm/pyfunctionhood"
|
|
|
40
36
|
|
|
41
37
|
[project.scripts]
|
|
42
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"
|
|
@@ -77,7 +77,7 @@ class Clause:
|
|
|
77
77
|
def __gt__(self, c: 'Clause') -> bool:
|
|
78
78
|
if self.cardinality != c.cardinality:
|
|
79
79
|
raise ValueError("Clauses must have the same cardinality!")
|
|
80
|
-
return self
|
|
80
|
+
return (self != c) and (self >= c)
|
|
81
81
|
|
|
82
82
|
def __le__(self, c: 'Clause') -> bool:
|
|
83
83
|
if self.cardinality != c.cardinality:
|
|
@@ -87,12 +87,12 @@ class Clause:
|
|
|
87
87
|
def __lt__(self, c: 'Clause') -> bool:
|
|
88
88
|
if self.cardinality != c.cardinality:
|
|
89
89
|
raise ValueError("Clauses must have the same cardinality!")
|
|
90
|
-
return self
|
|
90
|
+
return (self != c) and (self <= c)
|
|
91
91
|
|
|
92
92
|
def is_independent(self, c: 'Clause') -> bool:
|
|
93
93
|
if self.cardinality != c.cardinality:
|
|
94
94
|
raise ValueError("Clauses must have the same cardinality!")
|
|
95
|
-
return not self>=c and not self<=c
|
|
95
|
+
return (not self >= c) and (not self <= c)
|
|
96
96
|
|
|
97
97
|
def get_subsets(self) -> Set['Clause']:
|
|
98
98
|
return { self.clone_rm(l) for l in self.get_on_literals() }
|
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
from .clause import Clause
|
|
2
2
|
from .function import Function
|
|
3
3
|
from .powerset import PowerSet
|
|
4
|
+
from bitarray import bitarray
|
|
4
5
|
from typing import Tuple, Set
|
|
5
6
|
|
|
6
7
|
class HasseDiagram:
|
|
@@ -123,3 +124,57 @@ class HasseDiagram:
|
|
|
123
124
|
lmergeable.pop()
|
|
124
125
|
|
|
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
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import sys
|
|
2
2
|
|
|
3
|
+
from bitarray import bitarray
|
|
3
4
|
from .hassediagram import HasseDiagram
|
|
4
5
|
from .function import Function
|
|
5
6
|
|
|
@@ -11,12 +12,26 @@ def GUI_mode():
|
|
|
11
12
|
print("Please install tkinter or run in command line mode.")
|
|
12
13
|
sys.exit(1)
|
|
13
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
|
+
|
|
14
25
|
def get_parents():
|
|
15
26
|
try:
|
|
16
27
|
idim = int(varDimension.get())
|
|
17
28
|
hd = HasseDiagram(idim)
|
|
18
29
|
f = Function.fromString(idim, varFunction.get())
|
|
19
|
-
|
|
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)
|
|
20
35
|
lParents = ['R1 ' + str(f) for f in s1Parents]\
|
|
21
36
|
+ ['R2 ' + str(f) for f in s2Parents]\
|
|
22
37
|
+ ['R3 ' + str(f) for f in s3Parents]
|
|
@@ -31,7 +46,11 @@ def GUI_mode():
|
|
|
31
46
|
idim = int(varDimension.get())
|
|
32
47
|
hd = HasseDiagram(idim)
|
|
33
48
|
f = Function.fromString(idim, varFunction.get())
|
|
34
|
-
|
|
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)
|
|
35
54
|
lChildren = ['R1 ' + str(f) for f in s1Children]\
|
|
36
55
|
+ ['R2 ' + str(f) for f in s2Children]\
|
|
37
56
|
+ ['R3 ' + str(f) for f in s3Children]
|
|
@@ -44,6 +63,7 @@ def GUI_mode():
|
|
|
44
63
|
def default_values():
|
|
45
64
|
varFunction.set('{{1,2,3},{1,3,4},{2,3,4}}')
|
|
46
65
|
varDimension.set(4)
|
|
66
|
+
varChangedSigns.set('')
|
|
47
67
|
outputText.delete(1.0, "end") # Clear previous output
|
|
48
68
|
outputText.insert(1.0, '')
|
|
49
69
|
|
|
@@ -95,6 +115,13 @@ def GUI_mode():
|
|
|
95
115
|
entryFunction = tk.Entry(root, textvariable=varFunction, width=48)
|
|
96
116
|
entryFunction.grid(row=row, column=1, columnspan=2)
|
|
97
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
|
+
|
|
98
125
|
row += 1
|
|
99
126
|
bottomFrame = tk.Frame(root, padx=5, pady=5)
|
|
100
127
|
bottomFrame.grid(row=row, columnspan=2)
|
|
@@ -138,14 +165,15 @@ def GUI_mode():
|
|
|
138
165
|
def usage():
|
|
139
166
|
print('\nFor graphical mode, run without arguments: python', sys.argv[0])
|
|
140
167
|
print('\nFor command line mode, use the following arguments:')
|
|
141
|
-
print('Usage example:', sys.argv[0], '<type>', '<dimension>', '<function>')
|
|
142
|
-
print(' <type>:
|
|
143
|
-
print(' <dimension>:
|
|
144
|
-
print(' <function>:
|
|
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)')
|
|
145
173
|
sys.exit(1)
|
|
146
174
|
|
|
147
175
|
def command_line_mode():
|
|
148
|
-
if len(sys.argv)
|
|
176
|
+
if len(sys.argv) not in (4, 5):
|
|
149
177
|
print('ERROR: invalid number of arguments!')
|
|
150
178
|
usage()
|
|
151
179
|
if sys.argv[1] not in ('p','parents','c','children'):
|
|
@@ -155,14 +183,31 @@ def command_line_mode():
|
|
|
155
183
|
ndim = int(sys.argv[2])
|
|
156
184
|
hd = HasseDiagram(ndim)
|
|
157
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
|
+
|
|
158
197
|
if sys.argv[1] in ('p','parents'):
|
|
159
|
-
|
|
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)
|
|
160
202
|
lParents = ['R1 ' + str(f) for f in s1Parents]\
|
|
161
203
|
+ ['R2 ' + str(f) for f in s2Parents]\
|
|
162
204
|
+ ['R3 ' + str(f) for f in s3Parents]
|
|
163
205
|
print('\n'.join(lParents))
|
|
164
206
|
else:
|
|
165
|
-
|
|
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)
|
|
166
211
|
lChildren = ['R1 ' + str(f) for f in s1Children]\
|
|
167
212
|
+ ['R2 ' + str(f) for f in s2Children]\
|
|
168
213
|
+ ['R3 ' + str(f) for f in s3Children]
|
|
@@ -70,10 +70,10 @@ class PowerSet:
|
|
|
70
70
|
return s_diff
|
|
71
71
|
|
|
72
72
|
def get_minimal(self, s_clauses: Set['Clause']) -> Set['Clause']:
|
|
73
|
-
return { s1 for s1 in s_clauses if not any(
|
|
73
|
+
return { s1 for s1 in s_clauses if not any(s2 < s1 for s2 in s_clauses) }
|
|
74
74
|
|
|
75
75
|
def get_maximal(self, s_clauses: Set['Clause']) -> Set['Clause']:
|
|
76
|
-
return { s1 for s1 in s_clauses if not any(
|
|
76
|
+
return { s1 for s1 in s_clauses if not any(s2 > s1 for s2 in s_clauses) }
|
|
77
77
|
|
|
78
78
|
def __str__(self) -> str:
|
|
79
79
|
s = ""
|
|
@@ -1,8 +1,7 @@
|
|
|
1
1
|
Metadata-Version: 2.4
|
|
2
2
|
Name: pyfunctionhood
|
|
3
|
-
Version: 0.
|
|
3
|
+
Version: 0.3.0
|
|
4
4
|
Summary: Local computation of immediate neighbours of a given monotone non-degenerate Boolean function
|
|
5
|
-
Author: Patrícia Roxo, José E. R. Cury, Vasco Manquinho, Claudine Chaouiya
|
|
6
5
|
Author-email: "Pedro T. Monteiro" <Pedro.Tiago.Monteiro@tecnico.ulisboa.pt>
|
|
7
6
|
License: AGPL-3.0
|
|
8
7
|
Project-URL: Homepage, https://github.com/ptgm/pyfunctionhood
|
|
@@ -34,7 +33,7 @@ Here, immediate neighbours, are the monotone Boolean functions that are immediat
|
|
|
34
33
|
|
|
35
34
|
Monotone non-degenerate Boolean functions are represented as sets of clauses, where each clause is represented by the bitarray data structure, and each bit represents the presence/absence of a given variable/regulator.
|
|
36
35
|
|
|
37
|
-
This work
|
|
36
|
+
This work is developed in Python in [https://github.com/ptgm/pyfunctionhood/](https://github.com/ptgm/pyfunctionhood/), correcting and extending our previous work developed in Java in [https://github.com/ptgm/functionhood/](https://github.com/ptgm/functionhood/) and described in [arxiv:1901.07623](https://arxiv.org/abs/1901.07623).
|
|
38
37
|
|
|
39
38
|
Given a reference monotone Boolean function, this library can be used in three distinct manners:
|
|
40
39
|
- in the command line passing the reference function as an argument
|
|
@@ -46,10 +45,11 @@ Given a reference monotone Boolean function, this library can be used in three d
|
|
|
46
45
|
Usage - command line
|
|
47
46
|
--------------------
|
|
48
47
|
```
|
|
49
|
-
Usage example: python main.py <type> <dimension> <function>
|
|
50
|
-
<type>:
|
|
51
|
-
<dimension>:
|
|
52
|
-
<function>:
|
|
48
|
+
Usage example: python main.py <type> <dimension> <function> [<changed_signs>]
|
|
49
|
+
<type>: [p]arents or [c]hildren
|
|
50
|
+
<dimension>: 4
|
|
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)
|
|
53
53
|
```
|
|
54
54
|
|
|
55
55
|
**Parents**
|
|
@@ -74,6 +74,15 @@ R1 {{1,2,3},{1,3,4}}
|
|
|
74
74
|
R1 {{1,2,3},{2,3,4}}
|
|
75
75
|
```
|
|
76
76
|
|
|
77
|
+
**Sign changes**
|
|
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:
|
|
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
|
|
83
|
+
```
|
|
84
|
+
When omitted (or all zeros), the behaviour is unchanged from above, i.e. fixed-topology.
|
|
85
|
+
|
|
77
86
|
---
|
|
78
87
|
|
|
79
88
|
Usage - Graphical interface
|
|
@@ -85,6 +94,8 @@ There is also a graphical interface using Tkinter where the user can define the
|
|
|
85
94
|
|
|
86
95
|
The interface has a button to automatically write the Infimum function of the chosen dimension, and another for the Supremum function.
|
|
87
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.
|
|
98
|
+
|
|
88
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.
|
|
89
100
|
|
|
90
101
|
In the text area the immediate neighbouring functions are shown, as well as any error if an invalid function is provided.
|
|
@@ -124,6 +135,31 @@ print('\n'.join(['R1 ' + str(f) for f in s1]\
|
|
|
124
135
|
+ ['R3 ' + str(f) for f in s3]))
|
|
125
136
|
```
|
|
126
137
|
|
|
138
|
+
**Sign changes**
|
|
139
|
+
|
|
140
|
+
To compute parents/children considering that some variables/regulators switched sign, use `hd.get_f_parents_with_sign_changes(f, changed_signs)` or `hd.get_f_children_with_sign_changes(f, changed_signs)`, where `changed_signs` is a `bitarray` of the same size as the dimension, with bit `i` set to `True` if variable `i` switched sign:
|
|
141
|
+
```
|
|
142
|
+
from bitarray import bitarray
|
|
143
|
+
changed_signs = bitarray('0100')
|
|
144
|
+
s1, s2, s3 = hd.get_f_parents_with_sign_changes(f, changed_signs)
|
|
145
|
+
```
|
|
146
|
+
|
|
147
|
+
---
|
|
148
|
+
|
|
149
|
+
Testing
|
|
150
|
+
-------
|
|
151
|
+
|
|
152
|
+
The library includes a comprehensive pytest suite to validate correctness of the core algorithms:
|
|
153
|
+
|
|
154
|
+
```bash
|
|
155
|
+
pytest tests/ -v
|
|
156
|
+
```
|
|
157
|
+
|
|
158
|
+
This runs 22 tests covering:
|
|
159
|
+
- **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
|
|
160
|
+
- **Random walk consistency** (test_check_rules.py): Performs random walks on the Hasse diagram to verify parent-child relationships are consistent
|
|
161
|
+
- **Rule categorization** (test_rule_categorization.py): Validates that parent and children are correctly partitioned into S1, S2, and S3 rules
|
|
162
|
+
|
|
127
163
|
---
|
|
128
164
|
|
|
129
165
|
License
|
|
@@ -1,6 +1,10 @@
|
|
|
1
|
+
.gitignore
|
|
1
2
|
LICENSE
|
|
2
3
|
README.md
|
|
3
4
|
pyproject.toml
|
|
5
|
+
requirements.txt
|
|
6
|
+
.github/workflows/python-publish.yml
|
|
7
|
+
img/pyfunctionhood.png
|
|
4
8
|
src/pyfunctionhood/__init__.py
|
|
5
9
|
src/pyfunctionhood/clause.py
|
|
6
10
|
src/pyfunctionhood/function.py
|
|
@@ -12,4 +16,9 @@ src/pyfunctionhood.egg-info/SOURCES.txt
|
|
|
12
16
|
src/pyfunctionhood.egg-info/dependency_links.txt
|
|
13
17
|
src/pyfunctionhood.egg-info/entry_points.txt
|
|
14
18
|
src/pyfunctionhood.egg-info/requires.txt
|
|
15
|
-
src/pyfunctionhood.egg-info/
|
|
19
|
+
src/pyfunctionhood.egg-info/scm_file_list.json
|
|
20
|
+
src/pyfunctionhood.egg-info/scm_version.json
|
|
21
|
+
src/pyfunctionhood.egg-info/top_level.txt
|
|
22
|
+
tests/test_check_rules.py
|
|
23
|
+
tests/test_check_sign_changes.py
|
|
24
|
+
tests/test_rule_categorization.py
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
{
|
|
2
|
+
"files": [
|
|
3
|
+
".github/workflows/python-publish.yml",
|
|
4
|
+
".gitignore",
|
|
5
|
+
"LICENSE",
|
|
6
|
+
"README.md",
|
|
7
|
+
"img/pyfunctionhood.png",
|
|
8
|
+
"pyproject.toml",
|
|
9
|
+
"requirements.txt",
|
|
10
|
+
"src/pyfunctionhood/__init__.py",
|
|
11
|
+
"src/pyfunctionhood/clause.py",
|
|
12
|
+
"src/pyfunctionhood/function.py",
|
|
13
|
+
"src/pyfunctionhood/hassediagram.py",
|
|
14
|
+
"src/pyfunctionhood/main.py",
|
|
15
|
+
"src/pyfunctionhood/powerset.py",
|
|
16
|
+
"tests/test_check_rules.py",
|
|
17
|
+
"tests/test_check_sign_changes.py",
|
|
18
|
+
"tests/test_rule_categorization.py"
|
|
19
|
+
]
|
|
20
|
+
}
|
|
@@ -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
|
|
File without changes
|
|
File without changes
|
{pyfunctionhood-0.1.2 → pyfunctionhood-0.3.0}/src/pyfunctionhood.egg-info/dependency_links.txt
RENAMED
|
File without changes
|
|
File without changes
|
|
File without changes
|
|
File without changes
|