flamapy-sharpsat 2.6.0.dev5__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 (20) hide show
  1. flamapy_sharpsat-2.6.0.dev5/LICENSE +165 -0
  2. flamapy_sharpsat-2.6.0.dev5/PKG-INFO +79 -0
  3. flamapy_sharpsat-2.6.0.dev5/README.md +57 -0
  4. flamapy_sharpsat-2.6.0.dev5/flamapy/metamodels/sharpsat_metamodel/__init__.py +0 -0
  5. flamapy_sharpsat-2.6.0.dev5/flamapy/metamodels/sharpsat_metamodel/models/__init__.py +4 -0
  6. flamapy_sharpsat-2.6.0.dev5/flamapy/metamodels/sharpsat_metamodel/models/sharpsat_model.py +28 -0
  7. flamapy_sharpsat-2.6.0.dev5/flamapy/metamodels/sharpsat_metamodel/operations/__init__.py +8 -0
  8. flamapy_sharpsat-2.6.0.dev5/flamapy/metamodels/sharpsat_metamodel/operations/sharpsat_configurations_number.py +43 -0
  9. flamapy_sharpsat-2.6.0.dev5/flamapy/metamodels/sharpsat_metamodel/operations/sharpsat_sampling.py +79 -0
  10. flamapy_sharpsat-2.6.0.dev5/flamapy/metamodels/sharpsat_metamodel/transformations/__init__.py +4 -0
  11. flamapy_sharpsat-2.6.0.dev5/flamapy/metamodels/sharpsat_metamodel/transformations/fm_to_sharpsat.py +41 -0
  12. flamapy_sharpsat-2.6.0.dev5/flamapy_sharpsat.egg-info/PKG-INFO +79 -0
  13. flamapy_sharpsat-2.6.0.dev5/flamapy_sharpsat.egg-info/SOURCES.txt +18 -0
  14. flamapy_sharpsat-2.6.0.dev5/flamapy_sharpsat.egg-info/dependency_links.txt +1 -0
  15. flamapy_sharpsat-2.6.0.dev5/flamapy_sharpsat.egg-info/requires.txt +11 -0
  16. flamapy_sharpsat-2.6.0.dev5/flamapy_sharpsat.egg-info/top_level.txt +1 -0
  17. flamapy_sharpsat-2.6.0.dev5/pyproject.toml +86 -0
  18. flamapy_sharpsat-2.6.0.dev5/setup.cfg +4 -0
  19. flamapy_sharpsat-2.6.0.dev5/setup.py +3 -0
  20. flamapy_sharpsat-2.6.0.dev5/tests/test_sharpsat.py +140 -0
@@ -0,0 +1,165 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: flamapy-sharpsat
3
+ Version: 2.6.0.dev5
4
+ Summary: flamapy-sharpsat is a plugin to flamapy providing approximate model counting and almost-uniform sampling
5
+ Author-email: Flamapy <flamapy@us.es>
6
+ License-Expression: GPL-3.0-or-later
7
+ Project-URL: Homepage, https://github.com/flamapy/sharpsat_metamodel
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: flamapy-fw~=2.6.0.dev5
12
+ Requires-Dist: flamapy-fm~=2.6.0.dev5
13
+ Requires-Dist: flamapy-sat~=2.6.0.dev5
14
+ Requires-Dist: pyunigen~=2.5
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest; extra == "dev"
17
+ Requires-Dist: pytest-mock; extra == "dev"
18
+ Requires-Dist: prospector; extra == "dev"
19
+ Requires-Dist: mypy; extra == "dev"
20
+ Requires-Dist: coverage; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ # flamapy-sharpsat
24
+
25
+ `flamapy-sharpsat` is a [flamapy](https://flamapy.github.io) plugin that adds **scalable
26
+ approximate model counting** and **almost-uniform sampling** of feature-model configurations,
27
+ on top of the CNF produced by the SAT metamodel.
28
+
29
+ It complements the existing backends:
30
+
31
+ - The SAT (`flamapy-sat`) and Z3 backends count configurations by full enumeration, which does
32
+ not scale; the BDD backend counts exactly but the diagram can blow up on large models.
33
+ - `flamapy-sharpsat` uses [ApproxMC](https://github.com/meelgroup/approxmc) for an
34
+ (epsilon, delta) **approximate** count and [UniGen](https://github.com/meelgroup/unigen) for
35
+ **almost-uniform** sampling — both hashing-based tools from the CryptoMiniSat family that
36
+ scale to far larger models.
37
+
38
+ ## Installation
39
+
40
+ ```
41
+ pip install flamapy-sharpsat
42
+ ```
43
+
44
+ This pulls in `pyunigen` (which bundles ApproxMC), and the flamapy core/FM/SAT plugins.
45
+
46
+ ## Operations
47
+
48
+ | Operation | Class |
49
+ |---|---|
50
+ | Approximate number of configurations | `SharpSATConfigurationsNumber` |
51
+ | Almost-uniform sampling | `SharpSATSampling` |
52
+
53
+ ## Usage
54
+
55
+ ```python
56
+ from flamapy.metamodels.fm_metamodel.transformations import UVLReader
57
+ from flamapy.metamodels.sharpsat_metamodel.transformations import FmToSharpSAT
58
+ from flamapy.metamodels.sharpsat_metamodel.operations import (
59
+ SharpSATConfigurationsNumber,
60
+ SharpSATSampling,
61
+ )
62
+
63
+ fm = UVLReader('model.uvl').transform()
64
+ model = FmToSharpSAT(fm).transform()
65
+
66
+ count = SharpSATConfigurationsNumber().execute(model).get_result()
67
+
68
+ sampler = SharpSATSampling()
69
+ sampler.set_sample_size(10)
70
+ sample = sampler.execute(model).get_sample()
71
+ ```
72
+
73
+ Counting and sampling are projected onto the feature variables, so auxiliary variables
74
+ (such as the ones introduced by the optional Tseytin CNF encoding, available through
75
+ `FmToSharpSAT(fm, cnf_method='tseytin')`) never distort the results.
76
+
77
+ ## License
78
+
79
+ GPL-3.0-or-later.
@@ -0,0 +1,57 @@
1
+ # flamapy-sharpsat
2
+
3
+ `flamapy-sharpsat` is a [flamapy](https://flamapy.github.io) plugin that adds **scalable
4
+ approximate model counting** and **almost-uniform sampling** of feature-model configurations,
5
+ on top of the CNF produced by the SAT metamodel.
6
+
7
+ It complements the existing backends:
8
+
9
+ - The SAT (`flamapy-sat`) and Z3 backends count configurations by full enumeration, which does
10
+ not scale; the BDD backend counts exactly but the diagram can blow up on large models.
11
+ - `flamapy-sharpsat` uses [ApproxMC](https://github.com/meelgroup/approxmc) for an
12
+ (epsilon, delta) **approximate** count and [UniGen](https://github.com/meelgroup/unigen) for
13
+ **almost-uniform** sampling — both hashing-based tools from the CryptoMiniSat family that
14
+ scale to far larger models.
15
+
16
+ ## Installation
17
+
18
+ ```
19
+ pip install flamapy-sharpsat
20
+ ```
21
+
22
+ This pulls in `pyunigen` (which bundles ApproxMC), and the flamapy core/FM/SAT plugins.
23
+
24
+ ## Operations
25
+
26
+ | Operation | Class |
27
+ |---|---|
28
+ | Approximate number of configurations | `SharpSATConfigurationsNumber` |
29
+ | Almost-uniform sampling | `SharpSATSampling` |
30
+
31
+ ## Usage
32
+
33
+ ```python
34
+ from flamapy.metamodels.fm_metamodel.transformations import UVLReader
35
+ from flamapy.metamodels.sharpsat_metamodel.transformations import FmToSharpSAT
36
+ from flamapy.metamodels.sharpsat_metamodel.operations import (
37
+ SharpSATConfigurationsNumber,
38
+ SharpSATSampling,
39
+ )
40
+
41
+ fm = UVLReader('model.uvl').transform()
42
+ model = FmToSharpSAT(fm).transform()
43
+
44
+ count = SharpSATConfigurationsNumber().execute(model).get_result()
45
+
46
+ sampler = SharpSATSampling()
47
+ sampler.set_sample_size(10)
48
+ sample = sampler.execute(model).get_sample()
49
+ ```
50
+
51
+ Counting and sampling are projected onto the feature variables, so auxiliary variables
52
+ (such as the ones introduced by the optional Tseytin CNF encoding, available through
53
+ `FmToSharpSAT(fm, cnf_method='tseytin')`) never distort the results.
54
+
55
+ ## License
56
+
57
+ GPL-3.0-or-later.
@@ -0,0 +1,4 @@
1
+ from .sharpsat_model import SharpSATModel
2
+
3
+
4
+ __all__ = ['SharpSATModel']
@@ -0,0 +1,28 @@
1
+ from typing import Optional
2
+
3
+ from flamapy.core.models import VariabilityModel
4
+
5
+
6
+ class SharpSATModel(VariabilityModel):
7
+ """A CNF model for approximate model counting and almost-uniform sampling.
8
+
9
+ It mirrors the variable/feature bookkeeping of the SAT metamodel: ``clauses`` is the
10
+ CNF, ``variables`` maps a feature name to its SAT variable id and ``features`` the
11
+ reverse, while ``auxiliary_variables`` holds ids that are not features (e.g. Tseytin
12
+ gates) and must be projected out when counting or sampling configurations.
13
+ """
14
+
15
+ @staticmethod
16
+ def get_extension() -> str:
17
+ return 'sharpsat'
18
+
19
+ def __init__(self) -> None:
20
+ self.clauses: list[list[int]] = []
21
+ self.variables: dict[str, int] = {} # feature name -> id
22
+ self.features: dict[int, str] = {} # id -> feature name
23
+ self.auxiliary_variables: set[int] = set()
24
+ self.original_model: Optional[VariabilityModel] = None
25
+
26
+ def feature_variables(self) -> list[int]:
27
+ """SAT variable ids that correspond to features (auxiliary ids excluded)."""
28
+ return list(self.features.keys())
@@ -0,0 +1,8 @@
1
+ from .sharpsat_configurations_number import SharpSATConfigurationsNumber
2
+ from .sharpsat_sampling import SharpSATSampling
3
+
4
+
5
+ __all__ = [
6
+ 'SharpSATConfigurationsNumber',
7
+ 'SharpSATSampling',
8
+ ]
@@ -0,0 +1,43 @@
1
+ from typing import cast
2
+
3
+ import pyunigen
4
+
5
+ from flamapy.core.models import VariabilityModel
6
+ from flamapy.core.operations import ConfigurationsNumber
7
+ from flamapy.metamodels.sharpsat_metamodel.models import SharpSATModel
8
+
9
+
10
+ class SharpSATConfigurationsNumber(ConfigurationsNumber):
11
+ """Approximate the number of valid configurations with ApproxMC.
12
+
13
+ Counting is projected onto the feature variables, so auxiliary variables (e.g. Tseytin
14
+ gates) do not inflate the result. ApproxMC gives an (epsilon, delta) probabilistic
15
+ approximation that scales far better than exact enumeration.
16
+
17
+ The count is obtained through UniGen's binding (``pyunigen`` with ``num=0``, which runs
18
+ ApproxMC's projected count without drawing samples). The standalone ``pyapproxmc`` binding
19
+ mis-configures ApproxMC's projected counting on feature-model CNFs with implied variables
20
+ (the root and mandatory-relation unit clauses), undercounting by a factor of two; UniGen's
21
+ ApproxMC invocation does not have that problem.
22
+ """
23
+
24
+ def __init__(self, seed: int = 1) -> None:
25
+ self._result = 0
26
+ self._seed = seed
27
+
28
+ def get_configurations_number(self) -> int:
29
+ return self._result
30
+
31
+ def get_result(self) -> int:
32
+ return self._result
33
+
34
+ def execute(self, model: VariabilityModel) -> 'SharpSATConfigurationsNumber':
35
+ sharpsat_model = cast(SharpSATModel, model)
36
+ counter = pyunigen.Sampler(seed=self._seed)
37
+ for clause in sharpsat_model.clauses:
38
+ counter.add_clause(clause)
39
+ cell_count, hash_count, _samples = counter.sample(
40
+ num=0, sampling_set=sharpsat_model.feature_variables()
41
+ )
42
+ self._result = cell_count * (2 ** hash_count)
43
+ return self
@@ -0,0 +1,79 @@
1
+ from typing import Any, Optional, cast
2
+
3
+ import pyunigen
4
+
5
+ from flamapy.core.models import VariabilityModel
6
+ from flamapy.core.operations import Sampling
7
+ from flamapy.metamodels.configuration_metamodel.models.configuration import Configuration
8
+ from flamapy.metamodels.sharpsat_metamodel.models import SharpSATModel
9
+
10
+
11
+ class SharpSATSampling(Sampling):
12
+ """Almost-uniform sampling of valid configurations with UniGen.
13
+
14
+ Unlike an enumerate-first-N sampler, UniGen draws configurations almost uniformly at
15
+ random. Sampling is projected onto the feature variables, and an optional partial
16
+ configuration fixes features as assumptions.
17
+ """
18
+
19
+ def __init__(self, seed: int = 1) -> None:
20
+ self._sample_size = 1
21
+ self._with_replacement = False
22
+ self._partial_configuration: Optional[Configuration] = None
23
+ self._result: list[Configuration] = []
24
+ self._seed = seed
25
+
26
+ def set_sample_size(self, sample_size: int) -> None:
27
+ self._sample_size = sample_size
28
+
29
+ def set_with_replacement(self, with_replacement: bool) -> None:
30
+ self._with_replacement = with_replacement
31
+
32
+ def set_partial_configuration(self, partial_configuration: Configuration) -> None:
33
+ self._partial_configuration = partial_configuration
34
+
35
+ def get_sample(self) -> list[Configuration]:
36
+ return self._result
37
+
38
+ def get_result(self) -> list[Configuration]:
39
+ return self._result
40
+
41
+ def execute(self, model: VariabilityModel) -> 'SharpSATSampling':
42
+ sharpsat_model = cast(SharpSATModel, model)
43
+ sampler = pyunigen.Sampler(seed=self._seed)
44
+ for clause in sharpsat_model.clauses:
45
+ sampler.add_clause(clause)
46
+ if self._partial_configuration is not None:
47
+ for name, value in self._partial_configuration.elements.items():
48
+ variable = sharpsat_model.variables.get(name)
49
+ if variable is not None:
50
+ sampler.add_clause([variable if value else -variable])
51
+
52
+ _cells, _hashes, samples = sampler.sample(
53
+ num=self._sample_size, sampling_set=sharpsat_model.feature_variables()
54
+ )
55
+
56
+ configurations = [self._to_configuration(sharpsat_model, sample) for sample in samples]
57
+ self._result = configurations if self._with_replacement else _dedupe(configurations)
58
+ return self
59
+
60
+ @staticmethod
61
+ def _to_configuration(model: SharpSATModel, sample: list[int]) -> Configuration:
62
+ elements: dict[Any, Any] = {}
63
+ for literal in sample:
64
+ if literal > 0:
65
+ name = model.features.get(literal)
66
+ if name is not None:
67
+ elements[name] = True
68
+ return Configuration(elements)
69
+
70
+
71
+ def _dedupe(configurations: list[Configuration]) -> list[Configuration]:
72
+ seen: set[frozenset[Any]] = set()
73
+ unique: list[Configuration] = []
74
+ for configuration in configurations:
75
+ key = frozenset(name for name, value in configuration.elements.items() if value)
76
+ if key not in seen:
77
+ seen.add(key)
78
+ unique.append(configuration)
79
+ return unique
@@ -0,0 +1,4 @@
1
+ from .fm_to_sharpsat import FmToSharpSAT
2
+
3
+
4
+ __all__ = ['FmToSharpSAT']
@@ -0,0 +1,41 @@
1
+ from flamapy.core.transformations import ModelToModel
2
+ from flamapy.metamodels.fm_metamodel.models import FeatureModel
3
+ from flamapy.metamodels.pysat_metamodel.transformations import FmToPysat
4
+ from flamapy.metamodels.sharpsat_metamodel.models import SharpSATModel
5
+
6
+
7
+ class FmToSharpSAT(ModelToModel):
8
+ """Transform a feature model into a SharpSAT (CNF) model.
9
+
10
+ The CNF is produced by reusing the SAT metamodel's ``FmToPysat`` transformation, so
11
+ the same constraint encoding (and the optional Tseytin encoding via ``cnf_method``) is
12
+ available here.
13
+ """
14
+
15
+ @staticmethod
16
+ def get_source_extension() -> str:
17
+ return 'fm'
18
+
19
+ @staticmethod
20
+ def get_destination_extension() -> str:
21
+ return 'sharpsat'
22
+
23
+ def __init__(self, source_model: FeatureModel, cnf_method: str = 'distributive') -> None:
24
+ self.source_model = source_model
25
+ self.cnf_method = cnf_method
26
+ self.destination_model = SharpSATModel()
27
+
28
+ def transform(self) -> SharpSATModel:
29
+ # Only pass cnf_method when a non-default encoding is requested, so the plugin also
30
+ # works against releases of flamapy-sat that predate the Tseytin cnf_method option.
31
+ if self.cnf_method == 'distributive':
32
+ sat_model = FmToPysat(self.source_model).transform()
33
+ else:
34
+ sat_model = FmToPysat(self.source_model, cnf_method=self.cnf_method).transform()
35
+ model = self.destination_model
36
+ model.clauses = [list(clause) for clause in sat_model.get_all_clauses().clauses]
37
+ model.variables = dict(sat_model.variables)
38
+ model.features = dict(sat_model.features)
39
+ model.auxiliary_variables = set(sat_model.auxiliary_variables)
40
+ model.original_model = self.source_model
41
+ return model
@@ -0,0 +1,79 @@
1
+ Metadata-Version: 2.4
2
+ Name: flamapy-sharpsat
3
+ Version: 2.6.0.dev5
4
+ Summary: flamapy-sharpsat is a plugin to flamapy providing approximate model counting and almost-uniform sampling
5
+ Author-email: Flamapy <flamapy@us.es>
6
+ License-Expression: GPL-3.0-or-later
7
+ Project-URL: Homepage, https://github.com/flamapy/sharpsat_metamodel
8
+ Requires-Python: >=3.11
9
+ Description-Content-Type: text/markdown
10
+ License-File: LICENSE
11
+ Requires-Dist: flamapy-fw~=2.6.0.dev5
12
+ Requires-Dist: flamapy-fm~=2.6.0.dev5
13
+ Requires-Dist: flamapy-sat~=2.6.0.dev5
14
+ Requires-Dist: pyunigen~=2.5
15
+ Provides-Extra: dev
16
+ Requires-Dist: pytest; extra == "dev"
17
+ Requires-Dist: pytest-mock; extra == "dev"
18
+ Requires-Dist: prospector; extra == "dev"
19
+ Requires-Dist: mypy; extra == "dev"
20
+ Requires-Dist: coverage; extra == "dev"
21
+ Dynamic: license-file
22
+
23
+ # flamapy-sharpsat
24
+
25
+ `flamapy-sharpsat` is a [flamapy](https://flamapy.github.io) plugin that adds **scalable
26
+ approximate model counting** and **almost-uniform sampling** of feature-model configurations,
27
+ on top of the CNF produced by the SAT metamodel.
28
+
29
+ It complements the existing backends:
30
+
31
+ - The SAT (`flamapy-sat`) and Z3 backends count configurations by full enumeration, which does
32
+ not scale; the BDD backend counts exactly but the diagram can blow up on large models.
33
+ - `flamapy-sharpsat` uses [ApproxMC](https://github.com/meelgroup/approxmc) for an
34
+ (epsilon, delta) **approximate** count and [UniGen](https://github.com/meelgroup/unigen) for
35
+ **almost-uniform** sampling — both hashing-based tools from the CryptoMiniSat family that
36
+ scale to far larger models.
37
+
38
+ ## Installation
39
+
40
+ ```
41
+ pip install flamapy-sharpsat
42
+ ```
43
+
44
+ This pulls in `pyunigen` (which bundles ApproxMC), and the flamapy core/FM/SAT plugins.
45
+
46
+ ## Operations
47
+
48
+ | Operation | Class |
49
+ |---|---|
50
+ | Approximate number of configurations | `SharpSATConfigurationsNumber` |
51
+ | Almost-uniform sampling | `SharpSATSampling` |
52
+
53
+ ## Usage
54
+
55
+ ```python
56
+ from flamapy.metamodels.fm_metamodel.transformations import UVLReader
57
+ from flamapy.metamodels.sharpsat_metamodel.transformations import FmToSharpSAT
58
+ from flamapy.metamodels.sharpsat_metamodel.operations import (
59
+ SharpSATConfigurationsNumber,
60
+ SharpSATSampling,
61
+ )
62
+
63
+ fm = UVLReader('model.uvl').transform()
64
+ model = FmToSharpSAT(fm).transform()
65
+
66
+ count = SharpSATConfigurationsNumber().execute(model).get_result()
67
+
68
+ sampler = SharpSATSampling()
69
+ sampler.set_sample_size(10)
70
+ sample = sampler.execute(model).get_sample()
71
+ ```
72
+
73
+ Counting and sampling are projected onto the feature variables, so auxiliary variables
74
+ (such as the ones introduced by the optional Tseytin CNF encoding, available through
75
+ `FmToSharpSAT(fm, cnf_method='tseytin')`) never distort the results.
76
+
77
+ ## License
78
+
79
+ GPL-3.0-or-later.
@@ -0,0 +1,18 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ setup.py
5
+ flamapy/metamodels/sharpsat_metamodel/__init__.py
6
+ flamapy/metamodels/sharpsat_metamodel/models/__init__.py
7
+ flamapy/metamodels/sharpsat_metamodel/models/sharpsat_model.py
8
+ flamapy/metamodels/sharpsat_metamodel/operations/__init__.py
9
+ flamapy/metamodels/sharpsat_metamodel/operations/sharpsat_configurations_number.py
10
+ flamapy/metamodels/sharpsat_metamodel/operations/sharpsat_sampling.py
11
+ flamapy/metamodels/sharpsat_metamodel/transformations/__init__.py
12
+ flamapy/metamodels/sharpsat_metamodel/transformations/fm_to_sharpsat.py
13
+ flamapy_sharpsat.egg-info/PKG-INFO
14
+ flamapy_sharpsat.egg-info/SOURCES.txt
15
+ flamapy_sharpsat.egg-info/dependency_links.txt
16
+ flamapy_sharpsat.egg-info/requires.txt
17
+ flamapy_sharpsat.egg-info/top_level.txt
18
+ tests/test_sharpsat.py
@@ -0,0 +1,11 @@
1
+ flamapy-fw~=2.6.0.dev5
2
+ flamapy-fm~=2.6.0.dev5
3
+ flamapy-sat~=2.6.0.dev5
4
+ pyunigen~=2.5
5
+
6
+ [dev]
7
+ pytest
8
+ pytest-mock
9
+ prospector
10
+ mypy
11
+ coverage
@@ -0,0 +1,86 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "flamapy-sharpsat"
7
+ version = "2.6.0.dev5"
8
+ description = "flamapy-sharpsat is a plugin to flamapy providing approximate model counting and almost-uniform sampling"
9
+ readme = "README.md"
10
+ license = "GPL-3.0-or-later"
11
+ authors = [{ name = "Flamapy", email = "flamapy@us.es" }]
12
+ requires-python = ">=3.11"
13
+ dependencies = [
14
+ "flamapy-fw~=2.6.0.dev5",
15
+ "flamapy-fm~=2.6.0.dev5",
16
+ "flamapy-sat~=2.6.0.dev5",
17
+ "pyunigen~=2.5",
18
+ ]
19
+
20
+ [project.optional-dependencies]
21
+ dev = [
22
+ "pytest",
23
+ "pytest-mock",
24
+ "prospector",
25
+ "mypy",
26
+ "coverage",
27
+ ]
28
+
29
+ [project.urls]
30
+ Homepage = "https://github.com/flamapy/sharpsat_metamodel"
31
+
32
+ [tool.setuptools.packages.find]
33
+ include = ["flamapy.*"]
34
+
35
+ [tool.ruff]
36
+ line-length = 100 # Matches max-line-length from pycodestyle
37
+ target-version = "py311"
38
+
39
+ [tool.ruff.lint]
40
+ select = ["E", "W", "F", "C", "PL", "RUF"] # Includes pycodestyle, pylint, and McCabe complexity
41
+ ignore = [
42
+ "RUF012", # Equivalent to Pylint's super-init-not-called
43
+ "RUF002", # Weird symbols on docstring
44
+ "RUF001", # Weird symbols string
45
+ ]
46
+
47
+ [tool.ruff.lint.mccabe]
48
+ max-complexity = 10 # Equivalent to enabling mccabe in Prospector
49
+
50
+ [tool.ruff.lint.per-file-ignores]
51
+ "tests/*" = ["ALL"] # Ignore all test files
52
+ "build/*" = ["ALL"]
53
+ "resources/*" = ["ALL"]
54
+ ".mypy_cache/*" = ["ALL"]
55
+ "venv/*" = ["ALL"]
56
+ ".venv/*" = ["ALL"]
57
+ "env/*" = ["ALL"]
58
+ "flamapy_sharpsat.egg-info/*" = ["ALL"]
59
+ "__pycache__/*" = ["ALL"]
60
+
61
+ [tool.ruff.lint.pycodestyle]
62
+ max-line-length = 100 # Matches your existing pycodestyle setting
63
+
64
+ # MYPY CONFIGURATION
65
+ [tool.mypy]
66
+ scripts_are_modules = true
67
+ show_traceback = true
68
+
69
+ # Strict checking
70
+ check_untyped_defs = true
71
+ disallow_untyped_defs = true
72
+ disallow_any_generics = true
73
+ warn_no_return = true
74
+ strict_optional = true
75
+ no_implicit_optional = true
76
+ warn_redundant_casts = true
77
+ warn_unused_ignores = true
78
+
79
+ # Show error codes for type: ignore comments
80
+ show_error_codes = true
81
+
82
+ # Suppress missing imports errors
83
+ ignore_missing_imports = true
84
+
85
+ # Warn about unreachable or redundant code
86
+ warn_unreachable = true
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,3 @@
1
+ from setuptools import setup
2
+
3
+ setup()
@@ -0,0 +1,140 @@
1
+ """Tests for the sharpsat metamodel: approximate counting and almost-uniform sampling."""
2
+ import os
3
+ import tempfile
4
+
5
+ import pytest
6
+
7
+ from flamapy.metamodels.fm_metamodel.transformations import UVLReader
8
+ from flamapy.metamodels.fm_metamodel.models import FeatureModel
9
+ from flamapy.metamodels.sharpsat_metamodel.transformations import FmToSharpSAT
10
+ from flamapy.metamodels.sharpsat_metamodel.operations import (
11
+ SharpSATConfigurationsNumber,
12
+ SharpSATSampling,
13
+ )
14
+
15
+ # Exact oracle and validity oracle via SAT (a declared dependency, unlike BDD).
16
+ from flamapy.metamodels.pysat_metamodel.transformations import FmToPysat
17
+ from flamapy.metamodels.pysat_metamodel.operations.pysat_configurations_number import (
18
+ PySATConfigurationsNumber,
19
+ )
20
+ from flamapy.metamodels.pysat_metamodel.operations.pysat_satisfiable_configuration import (
21
+ PySATSatisfiableConfiguration,
22
+ )
23
+ from flamapy.metamodels.configuration_metamodel.models.configuration import Configuration
24
+
25
+
26
+ _UVL = """features
27
+ Root {abstract}
28
+ optional
29
+ A
30
+ B
31
+ C
32
+ D
33
+ constraints
34
+ (A | B) => (C <=> D)
35
+ A => !B
36
+ """
37
+
38
+
39
+ def _fm() -> FeatureModel:
40
+ handle, path = tempfile.mkstemp(suffix='.uvl')
41
+ try:
42
+ with os.fdopen(handle, 'w') as file:
43
+ file.write(_UVL)
44
+ return UVLReader(path).transform()
45
+ finally:
46
+ os.remove(path)
47
+
48
+
49
+ def _all_feature_names(fm: FeatureModel) -> list[str]:
50
+ return [feature.name for feature in fm.get_features()]
51
+
52
+
53
+ def _is_valid(fm: FeatureModel, selected: set) -> bool:
54
+ sat_model = FmToPysat(fm).transform()
55
+ elements = {name: (name in selected) for name in _all_feature_names(fm)}
56
+ configuration = Configuration(elements)
57
+ configuration.set_full(True)
58
+ op = PySATSatisfiableConfiguration()
59
+ op.set_configuration(configuration)
60
+ return op.execute(sat_model).get_result()
61
+
62
+
63
+ _IMPLIED_VARS_UVL = """features
64
+ Root {abstract}
65
+ mandatory
66
+ Base
67
+ mandatory
68
+ Core
69
+ optional
70
+ A
71
+ B
72
+ C
73
+ constraints
74
+ A => B
75
+ """
76
+
77
+
78
+ def _fm_from(uvl):
79
+ handle, path = tempfile.mkstemp(suffix='.uvl')
80
+ try:
81
+ with os.fdopen(handle, 'w') as file:
82
+ file.write(uvl)
83
+ return UVLReader(path).transform()
84
+ finally:
85
+ os.remove(path)
86
+
87
+
88
+ def test_approximate_count_matches_exact_on_small_model():
89
+ fm = _fm()
90
+ exact = PySATConfigurationsNumber().execute(FmToPysat(fm).transform()).get_result()
91
+ approx = SharpSATConfigurationsNumber().execute(FmToSharpSAT(fm).transform()).get_result()
92
+ # ApproxMC's default (epsilon, delta) is exact on a model this small.
93
+ assert approx == exact
94
+
95
+
96
+ def test_count_is_correct_with_implied_variables():
97
+ # Regression guard: models with implied variables (mandatory chains, root unit clause)
98
+ # must not be undercounted. The standalone pyapproxmc binding halved these; the UniGen
99
+ # ApproxMC invocation used by the counter does not.
100
+ fm = _fm_from(_IMPLIED_VARS_UVL)
101
+ exact = PySATConfigurationsNumber().execute(FmToPysat(fm).transform()).get_result()
102
+ approx = SharpSATConfigurationsNumber().execute(FmToSharpSAT(fm).transform()).get_result()
103
+ assert approx == exact
104
+
105
+
106
+ def test_sampling_returns_valid_configurations():
107
+ fm = _fm()
108
+ model = FmToSharpSAT(fm).transform()
109
+ op = SharpSATSampling()
110
+ op.set_sample_size(6)
111
+ op.set_with_replacement(True)
112
+ sample = op.execute(model).get_sample()
113
+ assert len(sample) == 6
114
+ for configuration in sample:
115
+ selected = {name for name, value in configuration.elements.items() if value}
116
+ assert _is_valid(fm, selected), f"invalid configuration sampled: {selected}"
117
+
118
+
119
+ def test_sampling_respects_partial_configuration():
120
+ fm = _fm()
121
+ model = FmToSharpSAT(fm).transform()
122
+ op = SharpSATSampling()
123
+ op.set_sample_size(5)
124
+ op.set_with_replacement(True)
125
+ op.set_partial_configuration(Configuration({'A': True}))
126
+ for configuration in op.execute(model).get_sample():
127
+ selected = {name for name, value in configuration.elements.items() if value}
128
+ assert 'A' in selected # the fixed feature is always present
129
+ assert 'B' not in selected # A => !B forces B out
130
+
131
+
132
+ def test_without_replacement_deduplicates():
133
+ fm = _fm()
134
+ model = FmToSharpSAT(fm).transform()
135
+ op = SharpSATSampling()
136
+ op.set_sample_size(20)
137
+ op.set_with_replacement(False)
138
+ sample = op.execute(model).get_sample()
139
+ keys = [frozenset(n for n, v in c.elements.items() if v) for c in sample]
140
+ assert len(keys) == len(set(keys)) # no duplicates