symprog 0.1.0a1__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 (64) hide show
  1. symprog-0.1.0a1/.gitignore +32 -0
  2. symprog-0.1.0a1/LICENSE +202 -0
  3. symprog-0.1.0a1/PKG-INFO +348 -0
  4. symprog-0.1.0a1/README.md +303 -0
  5. symprog-0.1.0a1/pyproject.toml +59 -0
  6. symprog-0.1.0a1/symprog/__init__.py +7 -0
  7. symprog-0.1.0a1/symprog/__main__.py +0 -0
  8. symprog-0.1.0a1/symprog/base.py +30 -0
  9. symprog-0.1.0a1/symprog/config.py +243 -0
  10. symprog-0.1.0a1/symprog/lang/__init__.py +2 -0
  11. symprog-0.1.0a1/symprog/lang/language.py +489 -0
  12. symprog-0.1.0a1/symprog/lang/languages/__init__.py +2 -0
  13. symprog-0.1.0a1/symprog/lang/languages/constraint.py +685 -0
  14. symprog-0.1.0a1/symprog/lang/languages/plp.py +1487 -0
  15. symprog-0.1.0a1/symprog/lang/languages/utils.py +212 -0
  16. symprog-0.1.0a1/symprog/registry.py +124 -0
  17. symprog-0.1.0a1/symprog/solvers/__init__.py +2 -0
  18. symprog-0.1.0a1/symprog/solvers/factory.py +46 -0
  19. symprog-0.1.0a1/symprog/solvers/klay_interface.py +161 -0
  20. symprog-0.1.0a1/symprog/solvers/mapper.py +283 -0
  21. symprog-0.1.0a1/symprog/solvers/numerical.py +612 -0
  22. symprog-0.1.0a1/symprog/solvers/numerical_interfaces/__init__.py +4 -0
  23. symprog-0.1.0a1/symprog/solvers/numerical_interfaces/jax.py +186 -0
  24. symprog-0.1.0a1/symprog/solvers/numerical_interfaces/python.py +175 -0
  25. symprog-0.1.0a1/symprog/solvers/numerical_interfaces/pytorch.py +377 -0
  26. symprog-0.1.0a1/symprog/solvers/numerical_interfaces/symbolic.py +494 -0
  27. symprog-0.1.0a1/symprog/solvers/semiring.py +470 -0
  28. symprog-0.1.0a1/symprog/solvers/semirings/__init__.py +6 -0
  29. symprog-0.1.0a1/symprog/solvers/semirings/common.py +306 -0
  30. symprog-0.1.0a1/symprog/solvers/semirings/count.py +76 -0
  31. symprog-0.1.0a1/symprog/solvers/semirings/entropy.py +118 -0
  32. symprog-0.1.0a1/symprog/solvers/semirings/formula.py +41 -0
  33. symprog-0.1.0a1/symprog/solvers/semirings/fuzzy.py +63 -0
  34. symprog-0.1.0a1/symprog/solvers/semirings/prob.py +114 -0
  35. symprog-0.1.0a1/symprog/solvers/semirings/viterbi.py +167 -0
  36. symprog-0.1.0a1/symprog/solvers/solver.py +1231 -0
  37. symprog-0.1.0a1/symprog/solvers/solver_interfaces/__init__.py +6 -0
  38. symprog-0.1.0a1/symprog/solvers/solver_interfaces/bdd.py +327 -0
  39. symprog-0.1.0a1/symprog/solvers/solver_interfaces/pysat.py +263 -0
  40. symprog-0.1.0a1/symprog/solvers/solver_interfaces/sdd.py +484 -0
  41. symprog-0.1.0a1/symprog/solvers/solver_interfaces/sympy.py +139 -0
  42. symprog-0.1.0a1/symprog/solvers/solver_interfaces/utils.py +6 -0
  43. symprog-0.1.0a1/symprog/solvers/solver_interfaces/z3.py +180 -0
  44. symprog-0.1.0a1/symprog/solvers/solver_utils.py +193 -0
  45. symprog-0.1.0a1/symprog/solvers/tensorization.py +411 -0
  46. symprog-0.1.0a1/symprog/version.py +1 -0
  47. symprog-0.1.0a1/tests/__init__.py +0 -0
  48. symprog-0.1.0a1/tests/reference.py +100 -0
  49. symprog-0.1.0a1/tests/test_backends.py +193 -0
  50. symprog-0.1.0a1/tests/test_constraint_lang.py +342 -0
  51. symprog-0.1.0a1/tests/test_gradients.py +355 -0
  52. symprog-0.1.0a1/tests/test_language_api.py +69 -0
  53. symprog-0.1.0a1/tests/test_plp.py +276 -0
  54. symprog-0.1.0a1/tests/test_plp_problog.py +1074 -0
  55. symprog-0.1.0a1/tests/test_python_numerics.py +59 -0
  56. symprog-0.1.0a1/tests/test_pytorch_numerics.py +70 -0
  57. symprog-0.1.0a1/tests/test_semirings.py +298 -0
  58. symprog-0.1.0a1/tests/test_solver.py +463 -0
  59. symprog-0.1.0a1/tests/test_solver_inference.py +131 -0
  60. symprog-0.1.0a1/tests/test_solver_interfaces.py +106 -0
  61. symprog-0.1.0a1/tests/test_solver_tensorization.py +303 -0
  62. symprog-0.1.0a1/tests/test_symbolic_numerics.py +79 -0
  63. symprog-0.1.0a1/tests/test_tensorization.py +359 -0
  64. symprog-0.1.0a1/tests/test_trace.py +43 -0
@@ -0,0 +1,32 @@
1
+ # Python
2
+ __pycache__/
3
+ *.py[cod]
4
+ *.so
5
+
6
+ # Packaging
7
+ build/
8
+ dist/
9
+ *.egg-info/
10
+ *.egg
11
+
12
+ # Virtual environments
13
+ .venv/
14
+ venv*/
15
+ env*/
16
+
17
+ # Tests and coverage
18
+ .pytest_cache/
19
+ .coverage
20
+ .coverage.*
21
+ htmlcov/
22
+ .tox/
23
+
24
+ # Notebooks
25
+ .ipynb_checkpoints/
26
+
27
+ # Editors and OS files
28
+ .vscode/
29
+ .idea/
30
+ *.swp
31
+ *~
32
+ .DS_Store
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,348 @@
1
+ Metadata-Version: 2.5
2
+ Name: symprog
3
+ Version: 0.1.0a1
4
+ Summary: A lightweight toolkit for prototyping discrete and probabilistic symbolic programs in Python.
5
+ Project-URL: Homepage, https://github.com/TuLLI-AI/symprog
6
+ Project-URL: Issues, https://github.com/TuLLI-AI/symprog/issues
7
+ Author: Kyle Richardson
8
+ License-Expression: Apache-2.0
9
+ License-File: LICENSE
10
+ Keywords: knowledge compilation,neuro-symbolic,probabilistic logic programming,symbolic programming,weighted model counting
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Education
13
+ Classifier: Intended Audience :: Science/Research
14
+ Classifier: Programming Language :: Python :: 3
15
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
16
+ Requires-Python: >=3.10
17
+ Requires-Dist: dd
18
+ Requires-Dist: dill
19
+ Requires-Dist: numpy
20
+ Requires-Dist: pydantic>=2
21
+ Requires-Dist: pysdd
22
+ Requires-Dist: python-sat
23
+ Requires-Dist: symengine
24
+ Requires-Dist: sympy>=1.12
25
+ Requires-Dist: torch>=2.1
26
+ Requires-Dist: z3-solver
27
+ Provides-Extra: console
28
+ Requires-Dist: pandas; extra == 'console'
29
+ Requires-Dist: streamlit; extra == 'console'
30
+ Requires-Dist: streamlit-code-editor; extra == 'console'
31
+ Provides-Extra: dev
32
+ Requires-Dist: build; extra == 'dev'
33
+ Requires-Dist: ipykernel; extra == 'dev'
34
+ Requires-Dist: nbmake; extra == 'dev'
35
+ Requires-Dist: pytest; extra == 'dev'
36
+ Requires-Dist: twine; extra == 'dev'
37
+ Provides-Extra: jax
38
+ Requires-Dist: jax; extra == 'jax'
39
+ Provides-Extra: klay
40
+ Requires-Dist: klaycircuits>=0.1.2; (python_version >= '3.11') and extra == 'klay'
41
+ Provides-Extra: notebooks
42
+ Requires-Dist: graphviz; extra == 'notebooks'
43
+ Requires-Dist: jupyter; extra == 'notebooks'
44
+ Description-Content-Type: text/markdown
45
+
46
+ # symprog
47
+
48
+ **Symbolic programming in Python: a fast prototyping toolkit for
49
+ working with weighted Boolean formulas and discrete (probabilistic) programs.**
50
+
51
+ > ⚠️ **Work in progress.** `symprog` is under active development. APIs may
52
+ > change between releases, and some features are experimental. Feedback, bug
53
+ > reports and contributions are very welcome. Please open an
54
+ > [issue](https://github.com/TuLLI-AI/symprog/issues).
55
+
56
+ `symprog` lets you write small symbolic programs (Boolean constraints,
57
+ probabilistic logic programs, weighted formulas) directly inside Python. You can
58
+ then reason about them on the fly: count models, compute exact probabilities,
59
+ find the most likely assignment, take gradients, or look at the underlying
60
+ symbolic equations.
61
+
62
+ It is designed with two uses in mind:
63
+
64
+ - **Rapid prototyping.** Sketch a new modeling idea involving weighed
65
+ Boolean formulas or discrete programming in a few lines of Python. Then switch the reasoning backend (SDDs, BDDs, SAT, SMT) and the
66
+ numerical backend (PyTorch, symbolic algebra) without rewriting your program.
67
+ - **Teaching.** The library stays small and readable. Each piece (languages,
68
+ solvers, semirings, knowledge compilers) matches a concept from logic,
69
+ probabilistic reasoning and automated reasoning, and the
70
+ [notebooks](notebooks/) walk through them step by step.
71
+
72
+ ## Installation
73
+
74
+ `symprog` requires Python 3.10 or newer.
75
+
76
+ ```bash
77
+ pip install symprog
78
+ ```
79
+
80
+ To get the latest development version from GitHub:
81
+
82
+ ```bash
83
+ pip install "git+https://github.com/TuLLI-AI/symprog.git"
84
+ ```
85
+
86
+ Optional extras:
87
+
88
+ ```bash
89
+ pip install "symprog[console]" # interactive Streamlit console
90
+ pip install "symprog[notebooks]" # Jupyter and graphviz for the tutorials
91
+ pip install "symprog[jax]" # experimental JAX backend
92
+ pip install "symprog[klay]" # klay tensorizaiton backend (https://github.com/ML-KULeuven/klay)
93
+ ```
94
+
95
+ For development, clone the repository and install it in editable mode:
96
+
97
+ ```bash
98
+ git clone https://github.com/TuLLI-AI/symprog.git
99
+ cd symprog
100
+ pip install -e ".[dev,notebooks,console]"
101
+ pytest
102
+ ```
103
+
104
+ ## Quick tour
105
+
106
+ ### Languages
107
+
108
+ `symprog` can embed small probabilistic programming languages *inline* in
109
+ Python, with on-the-fly inference and differentiable computation.
110
+
111
+ Below is a small program in probabilistic logic. It has a set of constraints
112
+ over weighted variables:
113
+
114
+ ```python
115
+ from symprog import Parser
116
+
117
+ @Parser(language="constraint")
118
+ def prog():
119
+ ## variable weights
120
+ a: 0.9; b: 0.7; c: 0.65
121
+
122
+ ## Boolean constraints
123
+ (not a) or b
124
+ c or b
125
+ (not b) or c
126
+
127
+ ## conditioning
128
+ condition: a
129
+ ```
130
+
131
+ You can then query the exact probability that the formula is satisfied:
132
+
133
+ ```python
134
+ prog.inference(mode="Prob").inference
135
+ ```
136
+
137
+ The next example uses a small probabilistic logic programming language, inspired
138
+ by [ProbLog](https://dtai.cs.kuleuven.be/problog/):
139
+
140
+ ```python
141
+ from symprog import Parser
142
+
143
+ @Parser(language="plp")
144
+ def inh():
145
+ ## probabilistic facts
146
+ c1: 0.5; c2: 0.5
147
+
148
+ ## weighted clauses
149
+ e1[0.3] :- c1
150
+ e1[0.2, False] :- c2
151
+
152
+ e2[0.4] :- c2
153
+ e2[0.2, False] :- c1
154
+
155
+ e :- e1
156
+ e :- e2
157
+
158
+ ## evidence or conditions
159
+ evidence(c1, True)
160
+ evidence(c2, True)
161
+
162
+ ## queries
163
+ query(e)
164
+ ```
165
+
166
+ The same kinds of inference work here. For more examples see
167
+ [`notebooks/languages.ipynb`](notebooks/languages.ipynb).
168
+
169
+ ### Interactive console
170
+
171
+ To try programs interactively, launch the console from a clone of the
172
+ repository (it requires the `console` extra):
173
+
174
+ ```bash
175
+ streamlit run console.py
176
+ ```
177
+
178
+ The console comes with example programs in both languages (graph coloring,
179
+ fault diagnosis, Monty Hall, a hidden Markov model and more). Besides running,
180
+ sampling and exact inference, it can show:
181
+
182
+ - the program's models, with a brute-force check of the solver's results;
183
+ - the compiled circuit, with the value of each node in a chosen semiring, and
184
+ the files to download it;
185
+ - each program as inline Python code, ready to copy.
186
+
187
+ ### Solvers
188
+
189
+ Inference is driven by `Solver`s. A `Solver` gives you one simple interface to
190
+ several reasoning tools, such as
191
+ [pysdd](https://pysdd.readthedocs.io/en/latest/),
192
+ [z3](https://ericpony.github.io/z3py-tutorial/guide-examples.htm) and
193
+ [python-sat](https://pysathq.github.io/), and to tensor libraries such as
194
+ [PyTorch](https://pytorch.org/). With these it performs exact inference over
195
+ (weighted) Boolean formulas.
196
+
197
+ ```python
198
+ from symprog import Solver
199
+
200
+ solver = Solver()
201
+
202
+ ## add propositional formulas and variable weights
203
+ solver.add([
204
+ "Implies(a, b)",
205
+ "And(Or(a, b), Implies(a, c))",
206
+ ])
207
+ solver.add_weights({"a": 0.9, "b": 0.64, "c": 0.34})
208
+
209
+ ## probabilistic inference (weighted model counting)
210
+ print(solver.query())
211
+ # => SolverOut(inference_type=Prob, inference=0.2598400115966797)
212
+ ```
213
+
214
+ Solvers support many kinds of inference through an extensible *algebraic*
215
+ (semiring) interface. See
216
+ [`notebooks/solver_tutorial.ipynb`](notebooks/solver_tutorial.ipynb) for details:
217
+
218
+ ```python
219
+ ## Viterbi-style inference (most likely assignment of variables)
220
+ solver.query(mode="Viterbi").inference
221
+ solver.query(mode="ViterbiAssignment").variables
222
+ # => {'c': True, 'b': True, 'a': True}
223
+ solver.query(mode="LogViterbi").inference
224
+
225
+ ## semantic entropy (entropy of interpretations given the formulas)
226
+ solver.query(mode="Entropy").inference
227
+
228
+ ## probability and log probability (more numerically stable)
229
+ solver.query(mode="Prob").inference
230
+ solver.query(mode="LogProb").inference
231
+
232
+ ## fuzzy inference
233
+ solver.query(mode="Fuzzy").inference
234
+
235
+ ## satisfiability testing (SAT)
236
+ solver.query(mode="SAT").inference
237
+ ```
238
+
239
+ Conditioning on evidence:
240
+
241
+ ```python
242
+ solver.query(mode="ViterbiAssignment", evidence="~a").variables
243
+ # => {'c': False, 'a': False, 'b': True}
244
+ ```
245
+
246
+ Gradients with respect to the weights:
247
+
248
+ ```python
249
+ solver.gradient(mode="Viterbi", key="weights")
250
+ # => tensor([0.2176, 0.3060, 0.5760])
251
+ ```
252
+
253
+ Model enumeration:
254
+
255
+ ```python
256
+ for model in solver.models():
257
+ print(model)
258
+ # {'a': True, 'c': True, 'b': True}
259
+ # {'a': False, 'c': False, 'b': True}
260
+ # {'a': False, 'c': True, 'b': True}
261
+ ```
262
+
263
+ ### Backend support
264
+
265
+ Not every backend supports every feature yet:
266
+
267
+ | Backend | SAT / model counting / model enumeration | Weighted inference (`Prob`, `Viterbi`, …) | Gradients |
268
+ | --- | --- | --- | --- |
269
+ | `sdd` solver (default) | ✅ | ✅ | ✅ |
270
+ | `bdd`, `z3`, `sympy`, `pysat` solvers | ✅ | ❌ not yet implemented | n/a |
271
+ | `pytorch` weights (default) | | ✅ | ✅ |
272
+ | `python` weights | | ✅ | ❌ |
273
+ | `sympy` / `symengine` symbolic weights | | ✅ | ✅ (symbolic) |
274
+ | `jax` weights (**experimental**, `pip install "symprog[jax]"`) | | ✅ | ✅ |
275
+
276
+ With the JAX backend, `Solver.as_function` returns inference as a pure function
277
+ of the weight vector (ordered as in `solver.weight_names`). You can then
278
+ transform it with `jax.grad`, `jax.jit` and `jax.vmap`, for example to compute
279
+ batched gradients for many weight settings at once:
280
+
281
+ ```python
282
+ import jax, jax.numpy as jnp
283
+
284
+ solver.add_weights({"a": 0.9, "b": 0.64, "c": 0.34}, container_type="jax")
285
+ f = solver.as_function(mode="LogProb", evidence="c")
286
+ batched_grads = jax.jit(jax.vmap(jax.grad(f)))(jnp.array([[0.9, 0.64, 0.34],
287
+ [0.2, 0.50, 0.70]]))
288
+ ```
289
+
290
+ The `Product` inference mode (product t-norm with probabilistic sum) is also
291
+ **experimental**. It is not a true semiring, so its results depend on the
292
+ structure of the compiled circuit.
293
+
294
+ **Tensorization** (`solver.tensorize`), which compiles an inference into a
295
+ PyTorch module for fast batched evaluation, is **experimental** as well. It has
296
+ two backends: `fx` (default), which supports all inference modes, evidence,
297
+ queries and conditionals, and `klay`, which uses
298
+ [KLay](https://github.com/ML-KULeuven/klay) to evaluate circuits layer by layer
299
+ and supports `Prob`, `LogProb`, `Viterbi`, `LogViterbi` and `Fuzzy`, without
300
+ evidence or conditioning (`pip install "symprog[klay]"`, Python ≥ 3.11).
301
+
302
+ Experimental features emit a `symprog.ExperimentalWarning`, which can be
303
+ silenced with:
304
+
305
+ ```python
306
+ import warnings, symprog
307
+ warnings.filterwarnings("ignore", category=symprog.ExperimentalWarning)
308
+ ```
309
+
310
+ ### Symbolic equations
311
+
312
+ Solvers also connect to computer algebra systems
313
+ ([SymPy](https://www.sympy.org/),
314
+ [SymEngine](https://github.com/symengine/symengine.py)). You can produce and
315
+ manipulate the exact symbolic equations behind any of the inferences above:
316
+
317
+ ```python
318
+ ## the symbolic polynomial behind the entropy computation
319
+ solver.query(mode="Entropy", symbolic=True).inference
320
+ # => log(a*b*c + b*(1 - a)) - (a*b*c*log(a) + a*(b*c*log(b) + b*c*log(c)) + ...
321
+
322
+ ## its symbolic gradient vector
323
+ solver.gradient(mode="Entropy", symbolic=True, key="weights")
324
+ ```
325
+
326
+ ## Tutorials
327
+
328
+ The [`notebooks/`](notebooks/) directory contains step-by-step tutorials, in
329
+ suggested reading order:
330
+
331
+ | Notebook | Topic |
332
+ | --- | --- |
333
+ | [`solver_tutorial.ipynb`](notebooks/solver_tutorial.ipynb) | **Start here:** formulas, weighted model counting, conditioning, and the algebraic (semiring) view of inference |
334
+ | [`languages.ipynb`](notebooks/languages.ipynb) | Writing inline constraint programs and probabilistic logic programs (ProbLog-style) |
335
+ | [`symbolic_and_gradients.ipynb`](notebooks/symbolic_and_gradients.ipynb) | Symbolic expressions, numerical/symbolic/Boolean gradients, and learning weights |
336
+ | [`tensorization_and_jax.ipynb`](notebooks/tensorization_and_jax.ipynb) | Fast batched inference: compiling to PyTorch modules, and JAX (`jit`, `vmap`, `grad`) |
337
+ | [`solver_interfaces.ipynb`](notebooks/solver_interfaces.ipynb) | The solver backends (SDD, BDD, z3, sympy, PySAT) |
338
+ | [`weight_interface.ipynb`](notebooks/weight_interface.ipynb) | The weight backends (PyTorch, Python, symbolic, JAX) |
339
+
340
+ ## Contributing
341
+
342
+ `symprog` is meant to grow with its users. Bug reports, examples, new languages
343
+ and new solver backends are all welcome. Please open an issue to discuss larger
344
+ changes before submitting a pull request.
345
+
346
+ ## License
347
+
348
+ `symprog` is released under the [Apache License 2.0](LICENSE).