agentic-mcp-solver 4.2.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,79 @@
1
+ """MaxSAT helper library: hard cardinality constraints that mutate a WCNF.
2
+
3
+ Unlike the clause-returning helpers in :mod:`mcp_solver.helpers.pysat`, these
4
+ functions append HARD clauses directly to a ``WCNF`` in place (weight ``None``
5
+ in pysat terms), so they express constraints that must hold in every model. For
6
+ weighted SOFT versions, use the ``soft_*`` helpers in the pysat module.
7
+
8
+ Example:
9
+ >>> from pysat.formula import WCNF
10
+ >>> wcnf = WCNF()
11
+ >>> exactly_k(wcnf, [1, 2, 3], 1)
12
+ >>> wcnf.append([1], weight=1) # a soft preference
13
+ """
14
+
15
+ import itertools
16
+
17
+ from pysat.formula import WCNF
18
+
19
+
20
+ def at_most_k(wcnf: WCNF, variables: list[int], k: int) -> None:
21
+ """Append hard clauses so at most ``k`` of ``variables`` are true.
22
+
23
+ Uses a direct pairwise encoding (no auxiliary variables): each (k+1)-subset
24
+ gets a clause requiring at least one false member. ``k < 0`` forces every
25
+ variable false; ``k >= len(variables)`` adds nothing.
26
+
27
+ Args:
28
+ wcnf: WCNF to mutate in place.
29
+ variables: Signed variable IDs.
30
+ k: Upper bound.
31
+ """
32
+ if k >= len(variables):
33
+ return
34
+
35
+ if k < 0:
36
+ for var in variables:
37
+ wcnf.append([-var])
38
+ return
39
+
40
+ for subset in itertools.combinations(variables, k + 1):
41
+ wcnf.append([-var for var in subset])
42
+
43
+
44
+ def at_least_k(wcnf: WCNF, variables: list[int], k: int) -> None:
45
+ """Append hard clauses so at least ``k`` of ``variables`` are true.
46
+
47
+ Each (n-k+1)-subset gets a clause requiring at least one true member.
48
+ ``k <= 0`` adds nothing; an impossible ``k > len(variables)`` appends a
49
+ single empty clause, making the WCNF unsatisfiable.
50
+
51
+ Args:
52
+ wcnf: WCNF to mutate in place.
53
+ variables: Signed variable IDs.
54
+ k: Lower bound.
55
+ """
56
+ if k <= 0:
57
+ return
58
+
59
+ n = len(variables)
60
+ if k > n:
61
+ wcnf.append([])
62
+ return
63
+
64
+ for subset in itertools.combinations(range(n), n - k + 1):
65
+ wcnf.append([variables[i] for i in subset])
66
+
67
+
68
+ def exactly_k(wcnf: WCNF, variables: list[int], k: int) -> None:
69
+ """Append hard clauses so exactly ``k`` of ``variables`` are true.
70
+
71
+ Combines :func:`at_least_k` and :func:`at_most_k`.
72
+
73
+ Args:
74
+ wcnf: WCNF to mutate in place.
75
+ variables: Signed variable IDs.
76
+ k: Exact count required.
77
+ """
78
+ at_least_k(wcnf, variables, k)
79
+ at_most_k(wcnf, variables, k)
@@ -0,0 +1,346 @@
1
+ """PySAT helper library: variable mapping, clause builders, cardinality
2
+ constraints, and MaxSAT soft-clause helpers.
3
+
4
+ All cardinality helpers return plain clause lists (``list[list[int]]``) that
5
+ you can feed straight to a solver or append to a ``CNF``/``WCNF``. Literals are
6
+ DIMACS-style signed integers: ``v`` means "variable v true", ``-v`` means
7
+ "variable v false".
8
+
9
+ Example:
10
+ >>> from pysat.solvers import Glucose3
11
+ >>> vm = VariableMap()
12
+ >>> a, b, c = (vm.get_id(n) for n in ("a", "b", "c"))
13
+ >>> solver = Glucose3()
14
+ >>> for clause in exactly_one([a, b, c]):
15
+ ... solver.add_clause(clause)
16
+ >>> solver.solve()
17
+ True
18
+ >>> vm.interpret_model(solver.get_model()) # doctest: +SKIP
19
+ {'a': True, 'b': False, 'c': False}
20
+ """
21
+
22
+ import itertools
23
+
24
+ from pysat.card import CardEnc, EncType
25
+ from pysat.formula import WCNF
26
+
27
+ # Threshold below which at_most_k uses a direct pairwise encoding instead of
28
+ # pysat's CardEnc. Pairwise adds no auxiliary variables and behaves identically
29
+ # across pysat versions, at the cost of O(n^(k+1)) clauses.
30
+ _PAIRWISE_MAX_VARS = 20
31
+
32
+ # Threshold below which at_least_k reduces to at_most_k via De Morgan rather
33
+ # than calling CardEnc directly.
34
+ _DE_MORGAN_MAX_VARS = 100
35
+
36
+
37
+ class VariableMap:
38
+ """Bidirectional mapping between meaningful names and SAT variable IDs.
39
+
40
+ IDs are assigned sequentially from 1 as names are first requested, matching
41
+ the DIMACS convention (variable 0 is reserved). Use :meth:`interpret_model`
42
+ to turn a solver model back into ``{name: bool}``: a positive literal in the
43
+ model means the variable is true.
44
+
45
+ Example:
46
+ >>> vm = VariableMap()
47
+ >>> vm.get_id("x")
48
+ 1
49
+ >>> vm.get_id("y")
50
+ 2
51
+ >>> vm.get_id("x") # stable
52
+ 1
53
+ >>> vm.interpret_model([1, -2])
54
+ {'x': True, 'y': False}
55
+ """
56
+
57
+ def __init__(self) -> None:
58
+ self.var_to_id: dict[str, int] = {}
59
+ self.id_to_var: dict[int, str] = {}
60
+ self.next_id: int = 1
61
+
62
+ def get_id(self, var_name: str) -> int:
63
+ """Return the ID for ``var_name``, allocating a fresh one if new."""
64
+ if var_name not in self.var_to_id:
65
+ self.var_to_id[var_name] = self.next_id
66
+ self.id_to_var[self.next_id] = var_name
67
+ self.next_id += 1
68
+ return self.var_to_id[var_name]
69
+
70
+ def get_name(self, var_id: int) -> str:
71
+ """Return the name for ``var_id`` (sign ignored).
72
+
73
+ Unknown IDs yield ``"unknown_<id>"`` rather than raising.
74
+ """
75
+ return self.id_to_var.get(abs(var_id), f"unknown_{abs(var_id)}")
76
+
77
+ def interpret_model(self, model: list[int]) -> dict[str, bool]:
78
+ """Convert a SAT model (list of signed literals) to ``{name: bool}``.
79
+
80
+ Only variables known to this map appear in the result; auxiliary IDs
81
+ introduced by cardinality encodings are skipped.
82
+ """
83
+ result: dict[str, bool] = {}
84
+ for lit in model:
85
+ var_id = abs(lit)
86
+ if var_id in self.id_to_var:
87
+ result[self.id_to_var[var_id]] = lit > 0
88
+ return result
89
+
90
+ def get_mapping(self) -> dict[str, int]:
91
+ """Return a copy of the current name-to-ID mapping."""
92
+ return self.var_to_id.copy()
93
+
94
+
95
+ # ---------------------------------------------------------------------------
96
+ # Cardinality constraints (return clause lists)
97
+ # ---------------------------------------------------------------------------
98
+
99
+
100
+ def at_most_k(
101
+ variables: list[int],
102
+ k: int,
103
+ *,
104
+ encoding: int = EncType.seqcounter,
105
+ top_id: int | None = None,
106
+ ) -> list[list[int]]:
107
+ """Clauses enforcing that at most ``k`` of ``variables`` are true.
108
+
109
+ For up to ``_PAIRWISE_MAX_VARS`` (20) variables a direct pairwise encoding
110
+ is used: it introduces no auxiliary variables and is identical across pysat
111
+ versions. For larger sets pysat's ``CardEnc.atmost`` is used (falling back
112
+ to pairwise if it raises), which allocates auxiliary variable IDs above
113
+ ``max(abs(v))`` unless you pass ``top_id`` to reserve a higher starting
114
+ point.
115
+
116
+ Args:
117
+ variables: Signed variable IDs (usually all positive).
118
+ k: Upper bound, ``k >= 0``.
119
+ encoding: pysat ``EncType`` used only on the CardEnc path.
120
+ top_id: Highest variable ID already in use, so CardEnc allocates
121
+ auxiliary variables above it (CardEnc path only).
122
+
123
+ Returns:
124
+ A list of clauses; empty if the constraint is trivially satisfied
125
+ (``k >= len(variables)``).
126
+ """
127
+ if k >= len(variables):
128
+ return []
129
+
130
+ if len(variables) <= _PAIRWISE_MAX_VARS:
131
+ return _pairwise_at_most(variables, k)
132
+
133
+ try:
134
+ return CardEnc.atmost(variables, k, encoding=encoding, top_id=top_id).clauses
135
+ except Exception:
136
+ return _pairwise_at_most(variables, k)
137
+
138
+
139
+ def _pairwise_at_most(variables: list[int], k: int) -> list[list[int]]:
140
+ """Direct pairwise at-most-k: each (k+1)-subset has a false member."""
141
+ return [[-v for v in combo] for combo in itertools.combinations(variables, k + 1)]
142
+
143
+
144
+ def at_least_k(
145
+ variables: list[int],
146
+ k: int,
147
+ *,
148
+ encoding: int = EncType.seqcounter,
149
+ top_id: int | None = None,
150
+ ) -> list[list[int]]:
151
+ """Clauses enforcing that at least ``k`` of ``variables`` are true.
152
+
153
+ Uses De Morgan's law for up to ``_DE_MORGAN_MAX_VARS`` (100) variables:
154
+ "at least k true" == "at most (n - k) of the negated variables true", which
155
+ routes through :func:`at_most_k` and its pairwise encoding. Larger sets try
156
+ ``CardEnc.atleast`` first, falling back to the De Morgan reduction.
157
+
158
+ Args:
159
+ variables: Signed variable IDs.
160
+ k: Lower bound.
161
+ encoding: pysat ``EncType`` used only on the CardEnc path.
162
+ top_id: Passed through to the CardEnc auxiliary-variable allocation.
163
+
164
+ Returns:
165
+ A list of clauses.
166
+ """
167
+ n = len(variables)
168
+ if n <= _DE_MORGAN_MAX_VARS:
169
+ neg_vars = [-v for v in variables]
170
+ return at_most_k(neg_vars, n - k, encoding=encoding, top_id=top_id)
171
+
172
+ try:
173
+ return CardEnc.atleast(variables, k, encoding=encoding, top_id=top_id).clauses
174
+ except Exception:
175
+ neg_vars = [-v for v in variables]
176
+ return at_most_k(neg_vars, n - k, encoding=encoding, top_id=top_id)
177
+
178
+
179
+ def exactly_k(
180
+ variables: list[int],
181
+ k: int,
182
+ *,
183
+ encoding: int = EncType.seqcounter,
184
+ top_id: int | None = None,
185
+ ) -> list[list[int]]:
186
+ """Clauses enforcing that exactly ``k`` of ``variables`` are true.
187
+
188
+ ``k == 0`` forbids every variable and ``k == 1`` combines a single
189
+ at-least-one clause with pairwise at-most-one (both auxiliary-free). The
190
+ general case is :func:`at_most_k` plus :func:`at_least_k`; above the
191
+ pairwise threshold those allocate CardEnc auxiliary variables, with the
192
+ IDs threaded so the two encodings never collide with each other or with
193
+ ``variables``. Pass ``top_id`` when your formula already uses IDs above
194
+ ``max(variables)``. An impossible request (``k < 0`` or
195
+ ``k > len(variables)``) returns ``[[]]`` (a single empty clause), which
196
+ any solver reads as UNSAT.
197
+
198
+ Args:
199
+ variables: Signed variable IDs.
200
+ k: Exact count required.
201
+ encoding: pysat ``EncType`` used only on the CardEnc path.
202
+ top_id: Highest variable ID already in use, so CardEnc allocates
203
+ auxiliary variables above it (CardEnc path only).
204
+
205
+ Returns:
206
+ A list of clauses.
207
+ """
208
+ if k > len(variables) or k < 0:
209
+ return [[]]
210
+
211
+ if k == 0:
212
+ return [[-v] for v in variables]
213
+
214
+ if k == 1:
215
+ at_least = [variables.copy()]
216
+ at_most = [
217
+ [-variables[i], -variables[j]]
218
+ for i in range(len(variables))
219
+ for j in range(i + 1, len(variables))
220
+ ]
221
+ return at_least + at_most
222
+
223
+ at_most = at_most_k(variables, k, encoding=encoding, top_id=top_id)
224
+ used = max(
225
+ (abs(lit) for clause in at_most for lit in clause),
226
+ default=0,
227
+ )
228
+ used = max(used, max(abs(v) for v in variables), top_id or 0)
229
+ return at_most + at_least_k(variables, k, encoding=encoding, top_id=used)
230
+
231
+
232
+ def at_most_one(variables: list[int]) -> list[list[int]]:
233
+ """Clauses enforcing that at most one of ``variables`` is true (pairwise)."""
234
+ return at_most_k(variables, 1)
235
+
236
+
237
+ def exactly_one(variables: list[int]) -> list[list[int]]:
238
+ """Clauses enforcing that exactly one of ``variables`` is true."""
239
+ return exactly_k(variables, 1)
240
+
241
+
242
+ def one_hot_encoding(variables: list[int]) -> list[list[int]]:
243
+ """Clauses for a one-hot encoding (exactly one variable true).
244
+
245
+ Semantically identical to :func:`exactly_one`; kept as a named alias for
246
+ readability in models that speak of one-hot vectors.
247
+ """
248
+ return exactly_one(variables)
249
+
250
+
251
+ def mutually_exclusive(variables: list[int]) -> list[list[int]]:
252
+ """Clauses ensuring at most one of ``variables`` is true (alias)."""
253
+ return at_most_one(variables)
254
+
255
+
256
+ def implies(a: int, b: int) -> list[list[int]]:
257
+ """Clauses for the implication ``a -> b`` (equivalently ``!a OR b``)."""
258
+ return [[-a, b]]
259
+
260
+
261
+ def if_then_else(condition: int, then_var: int, else_var: int) -> list[list[int]]:
262
+ """Clauses for ``if condition then then_var else else_var``.
263
+
264
+ Enforces ``condition -> then_var`` and ``!condition -> else_var``.
265
+ """
266
+ return [
267
+ [-condition, then_var],
268
+ [condition, else_var],
269
+ ]
270
+
271
+
272
+ # ---------------------------------------------------------------------------
273
+ # MaxSAT soft-clause helpers (return (clause, weight) pairs)
274
+ # ---------------------------------------------------------------------------
275
+
276
+
277
+ def soft_clause(literals: int | list[int], weight: int = 1) -> tuple[list[int], int]:
278
+ """Build a single soft clause ``(clause, weight)`` for a WCNF.
279
+
280
+ A soft clause may be violated at a cost equal to ``weight``. A bare int is
281
+ wrapped into a unit clause.
282
+ """
283
+ if isinstance(literals, int):
284
+ literals = [literals]
285
+ return (literals, weight)
286
+
287
+
288
+ def soft_at_most_k(
289
+ variables: list[int], k: int, weight: int = 1
290
+ ) -> list[tuple[list[int], int]]:
291
+ """Soft at-most-k as weighted pairwise clauses for a WCNF.
292
+
293
+ Each (k+1)-subset contributes a soft clause "at least one is false"; each
294
+ violated clause costs ``weight``. Returns ``[]`` when trivially satisfied.
295
+ """
296
+ if k >= len(variables):
297
+ return []
298
+ return [
299
+ ([-var for var in combo], weight)
300
+ for combo in itertools.combinations(variables, k + 1)
301
+ ]
302
+
303
+
304
+ def soft_at_least_k(
305
+ variables: list[int], k: int, weight: int = 1
306
+ ) -> list[tuple[list[int], int]]:
307
+ """Soft at-least-k as weighted clauses for a WCNF.
308
+
309
+ Built by De Morgan over the negated variables. Returns ``[]`` when
310
+ ``k <= 0`` (trivially satisfied).
311
+ """
312
+ if k <= 0:
313
+ return []
314
+ negated_vars = [-var for var in variables]
315
+ return [
316
+ ([-lit for lit in combo], weight)
317
+ for combo in itertools.combinations(negated_vars, len(variables) - k + 1)
318
+ ]
319
+
320
+
321
+ def soft_exactly_k(
322
+ variables: list[int], k: int, weight: int = 1
323
+ ) -> list[tuple[list[int], int]]:
324
+ """Soft exactly-k: the union of soft at-most-k and soft at-least-k."""
325
+ return soft_at_most_k(variables, k, weight) + soft_at_least_k(variables, k, weight)
326
+
327
+
328
+ def soft_implies(a: int, b: int, weight: int = 1) -> list[tuple[list[int], int]]:
329
+ """Soft implication ``a -> b`` as a single weighted clause."""
330
+ return [([-a, b], weight)]
331
+
332
+
333
+ def soft_if_then_else(
334
+ condition: int, then_var: int, else_var: int, weight: int = 1
335
+ ) -> list[tuple[list[int], int]]:
336
+ """Soft if-then-else as two weighted clauses."""
337
+ return [
338
+ ([-condition, then_var], weight),
339
+ ([condition, else_var], weight),
340
+ ]
341
+
342
+
343
+ def add_soft_clauses_to_wcnf(wcnf: WCNF, clauses: list[tuple[list[int], int]]) -> None:
344
+ """Append ``(clause, weight)`` pairs to ``wcnf`` in place."""
345
+ for clause, weight in clauses:
346
+ wcnf.append(clause, weight=weight)
@@ -0,0 +1,213 @@
1
+ """Z3 helper library: array/function properties, pseudo-Boolean cardinality
2
+ constraints, and optimal-subset search.
3
+
4
+ The array and function helpers return Z3 ``BoolRef`` constraints (typically
5
+ quantified) that you add to a ``Solver``/``Optimize``. Arrays are modelled as
6
+ Z3 ``Array(Int, ...)`` values with an explicit ``size``; quantified helpers
7
+ range over indices ``0 <= i < size``. Reserved index names ``_i``/``_j`` are
8
+ used internally, so avoid those names in your own model.
9
+
10
+ Example:
11
+ >>> import z3
12
+ >>> arr = z3.Array("a", z3.IntSort(), z3.IntSort())
13
+ >>> s = z3.Solver()
14
+ >>> s.add(array_is_sorted(arr, 3, strict=True))
15
+ >>> s.add(arr[0] == 5, arr[1] == 1)
16
+ >>> s.check()
17
+ unsat
18
+ """
19
+
20
+ from collections.abc import Callable
21
+ from itertools import combinations
22
+ from typing import Any, TypeVar
23
+
24
+ from z3 import (
25
+ And,
26
+ ArrayRef,
27
+ BoolRef,
28
+ Exists,
29
+ ExprRef,
30
+ ForAll,
31
+ Implies,
32
+ Int,
33
+ Ints,
34
+ PbEq,
35
+ PbGe,
36
+ PbLe,
37
+ )
38
+
39
+ T = TypeVar("T")
40
+
41
+
42
+ # ---------------------------------------------------------------------------
43
+ # Array and sequence properties
44
+ # ---------------------------------------------------------------------------
45
+
46
+
47
+ def array_is_sorted(
48
+ arr: ArrayRef, size: int | ExprRef, strict: bool = False
49
+ ) -> BoolRef:
50
+ """Constraint that ``arr[0:size]`` is sorted in ascending order.
51
+
52
+ Args:
53
+ arr: Z3 array (index sort Int).
54
+ size: Number of leading elements considered (int or Z3 expression).
55
+ strict: If True require strictly increasing (``<``), else ``<=``.
56
+
57
+ Returns:
58
+ A quantified Z3 ``BoolRef``.
59
+ """
60
+ i, j = Ints("_i _j")
61
+ guard = And(i >= 0, i < j, j < size)
62
+ if strict:
63
+ return ForAll([i, j], Implies(guard, arr[i] < arr[j]))
64
+ return ForAll([i, j], Implies(guard, arr[i] <= arr[j]))
65
+
66
+
67
+ def all_distinct(arr: ArrayRef, size: int | ExprRef) -> BoolRef:
68
+ """Constraint that all elements of ``arr[0:size]`` are pairwise distinct."""
69
+ i, j = Ints("_i _j")
70
+ return ForAll([i, j], Implies(And(i >= 0, i < j, j < size), arr[i] != arr[j]))
71
+
72
+
73
+ def array_contains(arr: ArrayRef, size: int | ExprRef, value: Any) -> BoolRef:
74
+ """Constraint that ``value`` occurs somewhere in ``arr[0:size]``."""
75
+ i = Int("_i")
76
+ return Exists([i], And(i >= 0, i < size, arr[i] == value))
77
+
78
+
79
+ # ---------------------------------------------------------------------------
80
+ # Cardinality constraints (pseudo-Boolean)
81
+ # ---------------------------------------------------------------------------
82
+
83
+
84
+ def exactly_k(bool_vars: list[BoolRef], k: int | ExprRef) -> BoolRef:
85
+ """Constraint that exactly ``k`` of ``bool_vars`` are true (``PbEq``)."""
86
+ return PbEq([(v, 1) for v in bool_vars], k)
87
+
88
+
89
+ def at_most_k(bool_vars: list[BoolRef], k: int | ExprRef) -> BoolRef:
90
+ """Constraint that at most ``k`` of ``bool_vars`` are true (``PbLe``)."""
91
+ return PbLe([(v, 1) for v in bool_vars], k)
92
+
93
+
94
+ def at_least_k(bool_vars: list[BoolRef], k: int | ExprRef) -> BoolRef:
95
+ """Constraint that at least ``k`` of ``bool_vars`` are true (``PbGe``)."""
96
+ return PbGe([(v, 1) for v in bool_vars], k)
97
+
98
+
99
+ # ---------------------------------------------------------------------------
100
+ # Functional properties
101
+ # ---------------------------------------------------------------------------
102
+
103
+
104
+ def function_is_injective(
105
+ func: ArrayRef,
106
+ domain_size: int | ExprRef,
107
+ range_size: int | ExprRef | None = None,
108
+ ) -> BoolRef:
109
+ """Constraint that ``func`` restricted to ``[0, domain_size)`` is injective.
110
+
111
+ Args:
112
+ func: Z3 array modelling the function.
113
+ domain_size: Size of the domain considered.
114
+ range_size: Unused; accepted for symmetry with
115
+ :func:`function_is_surjective`.
116
+
117
+ Returns:
118
+ A quantified Z3 ``BoolRef``.
119
+ """
120
+ i, j = Ints("_i _j")
121
+ return ForAll(
122
+ [i, j],
123
+ Implies(
124
+ And(i >= 0, i < domain_size, j >= 0, j < domain_size, i != j),
125
+ func[i] != func[j],
126
+ ),
127
+ )
128
+
129
+
130
+ def function_is_surjective(
131
+ func: ArrayRef, domain_size: int | ExprRef, range_size: int | ExprRef
132
+ ) -> BoolRef:
133
+ """Constraint that ``func`` maps ``[0, domain_size)`` onto ``[0, range_size)``.
134
+
135
+ Every target ``j`` in ``[0, range_size)`` has some ``i`` in
136
+ ``[0, domain_size)`` with ``func[i] == j``.
137
+ """
138
+ j = Int("_j")
139
+ i = Int("_i")
140
+ return ForAll(
141
+ [j],
142
+ Implies(
143
+ And(j >= 0, j < range_size),
144
+ Exists([i], And(i >= 0, i < domain_size, func[i] == j)),
145
+ ),
146
+ )
147
+
148
+
149
+ # ---------------------------------------------------------------------------
150
+ # Optimal subset search
151
+ # ---------------------------------------------------------------------------
152
+
153
+
154
+ def smallest_subset_with_property(
155
+ items: list[T],
156
+ property_check_func: Callable[[list[T]], bool],
157
+ min_size: int = 1,
158
+ max_size: int | None = None,
159
+ ) -> list[T] | None:
160
+ """Find a smallest subset of ``items`` for which the property holds.
161
+
162
+ Enumerates subsets by increasing size and returns the first one for which
163
+ ``property_check_func`` returns True. Because sizes are tried smallest
164
+ first, the returned subset has minimum cardinality. This is a generic
165
+ driver: ``property_check_func`` typically builds and checks a Z3 model, but
166
+ any boolean predicate over a subset works.
167
+
168
+ If ``property_check_func`` carries a ``candidate_subsets`` attribute, those
169
+ candidates are tried first and, on a hit, locally minimized via element
170
+ removal before returning.
171
+
172
+ Args:
173
+ items: Items to draw subsets from.
174
+ property_check_func: Predicate on a subset (e.g. returns
175
+ ``solver.check() == unsat``).
176
+ min_size: Smallest subset size to consider.
177
+ max_size: Largest subset size to consider (default ``len(items)``).
178
+
179
+ Returns:
180
+ A smallest satisfying subset, or None if none exists in range.
181
+
182
+ Example:
183
+ >>> nums = [1, 2, 3, 4]
184
+ >>> smallest_subset_with_property(nums, lambda s: sum(s) >= 5, min_size=1)
185
+ [1, 4]
186
+ """
187
+ if max_size is None:
188
+ max_size = len(items)
189
+
190
+ if hasattr(property_check_func, "candidate_subsets"):
191
+ for subset in property_check_func.candidate_subsets:
192
+ if min_size <= len(subset) <= max_size and property_check_func(subset):
193
+ return _minimize_subset(subset, property_check_func)
194
+
195
+ for size in range(min_size, max_size + 1):
196
+ for subset in combinations(items, size):
197
+ subset = list(subset)
198
+ if property_check_func(subset):
199
+ return subset
200
+
201
+ return None
202
+
203
+
204
+ def _minimize_subset(
205
+ subset: list[T], property_check_func: Callable[[list[T]], bool]
206
+ ) -> list[T]:
207
+ """Greedily drop elements while the property is preserved."""
208
+ minimal = subset.copy()
209
+ for item in subset:
210
+ smaller = [x for x in minimal if x != item]
211
+ if smaller and property_check_func(smaller):
212
+ return _minimize_subset(smaller, property_check_func)
213
+ return minimal
@@ -0,0 +1,22 @@
1
+ """Solver project templates (markdown), shipped as package data."""
2
+
3
+ from importlib.resources import files
4
+ from pathlib import Path
5
+
6
+ SOLVERS = ("pysat", "maxsat", "z3", "cpmpy", "clingo", "didp")
7
+
8
+
9
+ def get_template(solver: str, root: str | None = None) -> str:
10
+ """Return the project template text for a solver.
11
+
12
+ When *root* is given (dev mode), read the template from that source
13
+ checkout at ``<root>/src/mcp_solver/templates/<solver>.md`` if it exists;
14
+ otherwise fall back to the packaged resource.
15
+ """
16
+ if solver not in SOLVERS:
17
+ raise ValueError(f"Unknown solver {solver!r}; expected one of {SOLVERS}")
18
+ if root is not None:
19
+ override = Path(root) / "src" / "mcp_solver" / "templates" / f"{solver}.md"
20
+ if override.is_file():
21
+ return override.read_text(encoding="utf-8")
22
+ return (files(__package__) / f"{solver}.md").read_text(encoding="utf-8")