circuit-quantization 0.1.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,794 @@
1
+ # Vendored from sircuitenum/z3_interface.py (GPL-3.0), sircuitenum commit b2c57e8.
2
+ __doc__ = "z3_interface.py: Interface to Z3 SMT solver for finding rational variable assignments satisfying integer constraints."
3
+ __author__ = "Eli Weissler"
4
+ __version__ = "0.1.0"
5
+
6
+
7
+ __all__ = [
8
+ "find_rational_vars_integer_results",
9
+ ]
10
+
11
+ import itertools
12
+ import sympy as sym
13
+ from z3 import Solver, Real, RealVal, Int, Sum, If, sat, unsat
14
+ from z3 import unknown, Optimize, Or, IsInt, set_param, Abs
15
+ from z3 import Tactic, Then
16
+
17
+ from .singular_interface import _eq_as_numer_denom
18
+
19
+
20
+ def _check_or_timeout(solver):
21
+ """Run a Z3 check and turn ``unknown`` into an explicit timeout error."""
22
+ result = solver.check()
23
+ if result == unknown:
24
+ raise TimeoutError(f"Z3 returned unknown: {solver.reason_unknown()}")
25
+ return result
26
+
27
+
28
+ def _normalize_known_solutions(solutions, integer_constraints, expected_cost):
29
+ """Reconstruct and validate complete result vectors for known witnesses."""
30
+ normalized = []
31
+ seen = set()
32
+ for solution in solutions:
33
+ variables = solution["variables"]
34
+ values = []
35
+ valid = True
36
+ for expression in integer_constraints:
37
+ value = sym.simplify(expression.subs(variables))
38
+ if value.free_symbols or not value.is_integer:
39
+ valid = False
40
+ break
41
+ values.append(int(value))
42
+ if not valid or sum(abs(value) for value in values) != expected_cost:
43
+ continue
44
+ key = (
45
+ tuple(values),
46
+ tuple(sorted((str(var), str(value)) for var, value in variables.items())),
47
+ )
48
+ if key not in seen:
49
+ seen.add(key)
50
+ normalized.append({"results": values, "variables": variables})
51
+
52
+ normalized.sort(
53
+ key=lambda solution: (
54
+ sum(abs(x) for x in solution["results"]),
55
+ tuple(-x for x in solution["results"]),
56
+ tuple(sorted((str(k), str(v)) for k, v in solution["variables"].items())),
57
+ )
58
+ )
59
+ return normalized
60
+
61
+
62
+ def find_rational_vars_integer_results(integer_constraints, nonzero_constraints, zero_constraints,
63
+ variables, max_result_range=5, timeout_ms=int(1e06),
64
+ heuristic_upper=True, apriori_sol=None,
65
+ symmetry_map=lambda x: [x, [-i for i in x]],
66
+ enumerate_sols=True, debug=False,
67
+ proven_lower_bound=None,
68
+ accept_heuristic_optimum=False):
69
+ """
70
+ Find rational variable assignments such that integer constraints evaluate to integers
71
+ with minimal L1 norm.
72
+
73
+ Uses the Z3 SMT solver to find rational values for the given variables such that:
74
+
75
+ 1. All expressions in ``integer_constraints`` evaluate to integers within
76
+ ``[-max_result_range, max_result_range]``.
77
+ 2. All expressions in ``nonzero_constraints`` evaluate to non-zero values.
78
+ 3. All expressions in ``zero_constraints`` evaluate to zero.
79
+ 4. The L1 norm (sum of absolute values) of the ``integer_constraints`` results
80
+ is minimized.
81
+
82
+ The algorithm uses a "Linear Cost Sweep" strategy:
83
+
84
+ 1. Compute a lower bound on the cost by minimizing individual integer constraints independently.
85
+ 2. Optionally use a heuristic to find an upper bound by greedily setting variables to zero.
86
+ 3. Sweep through possible costs to find the minimum achievable cost.
87
+ 4. Enumerate all solutions at that minimum cost.
88
+
89
+ :param integer_constraints: Expressions that must evaluate to integer values.
90
+ :type integer_constraints: list[sympy.Expr]
91
+ :param nonzero_constraints: Expressions that must evaluate to non-zero values.
92
+ :type nonzero_constraints: list[sympy.Expr]
93
+ :param zero_constraints: Expressions that must evaluate to zero.
94
+ :type zero_constraints: list[sympy.Expr]
95
+ :param variables: Symbols representing the unknowns to solve for.
96
+ :type variables: list[sympy.Symbol]
97
+ :param max_result_range: Maximum absolute value allowed for integer constraint results.
98
+ Defaults to 5.
99
+ :type max_result_range: int
100
+ :param timeout_ms: Timeout in milliseconds for each solver operation.
101
+ Defaults to 1,000,000.
102
+ :type timeout_ms: int
103
+ :param heuristic_upper: Whether to use heuristic search to find an upper bound
104
+ on the optimal cost. Defaults to True.
105
+ :type heuristic_upper: bool
106
+ :param apriori_sol: Known upper bound on the cost from a previous solution.
107
+ If provided, only searches for solutions with cost <= this value.
108
+ Defaults to None.
109
+ :type apriori_sol: int | None
110
+ :param symmetry_map: Function mapping a result vector to equivalent vectors under
111
+ symmetry. Used to block symmetric solutions during enumeration.
112
+ Defaults to identity and negation.
113
+ :type symmetry_map: Callable[[list[int]], list[list[int]]]
114
+ :param enumerate_sols: Whether to enumerate all solutions at the minimum cost,
115
+ or just return one. Defaults to True.
116
+ :type enumerate_sols: bool
117
+ :param debug: Whether to print solver progress and bound information.
118
+ Defaults to False.
119
+ :type debug: bool
120
+ :param proven_lower_bound: Optional caller-supplied, mathematically proven
121
+ lower bound on the L1 cost. This is added as a solver constraint; it
122
+ must not be an estimate. Defaults to None.
123
+ :type proven_lower_bound: int | None
124
+ :param accept_heuristic_optimum: Whether a validated heuristic witness may
125
+ be returned when its cost equals ``proven_lower_bound``. Callers must
126
+ use this only when all optima are known to form one canonical orbit.
127
+ Defaults to False.
128
+ :type accept_heuristic_optimum: bool
129
+
130
+ :returns: List of solutions at the globally minimal cost. Each solution is a
131
+ dictionary with keys:
132
+
133
+ - ``'results'`` (*list[int]*): Integer values of the ``integer_constraints``.
134
+ - ``'variables'`` (*dict[sympy.Symbol, sympy.Rational]*): Variable assignments.
135
+
136
+ Returns an empty list if no solution exists.
137
+ :rtype: list[dict]
138
+
139
+ :raises ValueError: If an invalid minimum is found or constraints are inconsistent.
140
+ :raises TimeoutError: If the solver times out during critical operations.
141
+
142
+ Example
143
+ -------
144
+ >>> Z1, Z2 = sym.symbols('Z1 Z2')
145
+ >>> solutions = find_rational_vars_integer_results(
146
+ ... integer_constraints=[Z1/2, Z2/3],
147
+ ... nonzero_constraints=[Z1 * Z2],
148
+ ... zero_constraints=[],
149
+ ... variables=[Z1, Z2]
150
+ ... )
151
+ """
152
+
153
+ # Set random seed for reproducibility
154
+ set_param('smt.random_seed', 7)
155
+ set_param('sat.random_seed', 7)
156
+
157
+ # Consider individual terms for lower bound
158
+ lower_bound, solv, cost_terms, z3_vars, cost = _calc_min_cost(integer_constraints, nonzero_constraints,
159
+ zero_constraints, variables, max_result_range)
160
+ if proven_lower_bound is not None:
161
+ proven_lower_bound = int(proven_lower_bound)
162
+ if proven_lower_bound < 0:
163
+ raise ValueError("A proven lower bound must be non-negative")
164
+ lower_bound = max(lower_bound, proven_lower_bound)
165
+ # Besides skipping weaker objective values, give the nonlinear solver
166
+ # the certificate as a lemma. This can turn an expensive global
167
+ # optimality proof into immediate propagation.
168
+ solv.add(cost >= lower_bound)
169
+ solv.set("rlimit", 0)
170
+ solv.set("timeout", timeout_ms)
171
+ solv.set(logic='QF_NIA')
172
+
173
+ # If we have an apriori solution that we need to beat, check it now
174
+ upper_bound = len(cost_terms) * max_result_range
175
+ if not apriori_sol is None:
176
+ solv.push()
177
+ # If apriori solution is already lower than lower bound, give up
178
+ if apriori_sol < lower_bound:
179
+ return []
180
+ try:
181
+ if debug:
182
+ print(f" > Using apriori solution cost = {apriori_sol} to limit search.")
183
+ solv.add(cost <= apriori_sol)
184
+ check_result = _check_or_timeout(solv)
185
+ if debug:
186
+ print(f" > Check result: {check_result}")
187
+ # Nothing can achieve the apriori lower bound
188
+ if check_result == unsat:
189
+ return []
190
+ elif check_result == sat:
191
+ upper_bound = apriori_sol
192
+ # Don't use apriori if it times out
193
+ # switch to heuristic upper bound search
194
+ except TimeoutError:
195
+ apriori_sol = None
196
+ heuristic_upper = True
197
+ solv.pop()
198
+
199
+ # Check whether the lower bound is achievable. When a caller has both a
200
+ # structural lower-bound certificate and a unique canonical optimum orbit,
201
+ # defer this check until after the cheap heuristic witness search; equality
202
+ # itself can be a difficult nonlinear query.
203
+ if not (proven_lower_bound is not None and accept_heuristic_optimum):
204
+ solv.push()
205
+ try:
206
+ if debug:
207
+ print(f" > Checking if lower bound cost = {lower_bound} is achievable...")
208
+ solv.add(cost == lower_bound)
209
+ check_result = _check_or_timeout(solv)
210
+ if debug:
211
+ print(f" > Check result: {check_result}")
212
+ if check_result == sat:
213
+ if enumerate_sols:
214
+ return _enumerate_solutions(solv, cost_terms, z3_vars,
215
+ symmetry_map=symmetry_map)
216
+ else:
217
+ return _enumerate_solutions(solv, cost_terms, z3_vars,
218
+ max_solutions=1)
219
+ except TimeoutError:
220
+ pass
221
+ solv.pop()
222
+
223
+ # Get a heuristic upper bound by setting the maximum number of variables to zero
224
+ if any(nz == 0 for nz in nonzero_constraints):
225
+ raise ValueError("Provided Already Zero Nonzero Constraint")
226
+ nonzero_constraints = [nz for nz in nonzero_constraints if len(nz.free_symbols) > 0]
227
+ # Are there any variables we could freely set to zero?
228
+ heuristic_solutions = []
229
+ if nonzero_constraints and heuristic_upper:
230
+ try:
231
+ upper_other, heuristic_solutions = _heuristic_upper_bound(integer_constraints, nonzero_constraints,
232
+ zero_constraints,
233
+ variables, max_result_range=max_result_range,
234
+ timeout_ms=timeout_ms)
235
+ upper_bound = min(upper_bound, upper_other)
236
+
237
+ # Don't use heuristic upper if it times out
238
+ except TimeoutError:
239
+ heuristic_upper = False
240
+ # Do we have an upper bound already?
241
+ # If so search downwards from it
242
+ if heuristic_upper or upper_bound < len(cost_terms) * max_result_range:
243
+ target_costs = list(range(upper_bound, lower_bound-1,-1))
244
+ iteration_order = "down"
245
+
246
+ # Some callers can prove both the lower bound and uniqueness of the
247
+ # canonical optimum orbit from problem structure. In that case the
248
+ # heuristic witness is already an exact optimum, and enumerating every
249
+ # minimum-cost model is redundant (and can be dramatically harder than
250
+ # finding the witness).
251
+ if (accept_heuristic_optimum and upper_bound == lower_bound
252
+ and heuristic_solutions):
253
+ exact_solutions = _normalize_known_solutions(
254
+ heuristic_solutions, integer_constraints, upper_bound
255
+ )
256
+ if exact_solutions:
257
+ return exact_solutions
258
+
259
+ # Check to see if we're already done
260
+ done = False
261
+ if upper_bound == lower_bound:
262
+ done = True
263
+ else:
264
+ try:
265
+ solv.push()
266
+ solv.add(cost < upper_bound)
267
+ check_result = _check_or_timeout(solv)
268
+ solv.pop()
269
+ if check_result == unsat:
270
+ done = True
271
+ except TimeoutError:
272
+ pass
273
+ if done:
274
+ solv.push()
275
+ solv.add(cost == upper_bound)
276
+ check_result = _check_or_timeout(solv)
277
+ if enumerate_sols:
278
+ solutions = _enumerate_solutions(solv, cost_terms, z3_vars,
279
+ symmetry_map=symmetry_map)
280
+ else:
281
+ solutions = _enumerate_solutions(solv, cost_terms, z3_vars,
282
+ symmetry_map=symmetry_map, max_solutions=1)
283
+ # If no solutions found, check if it's because lower==upper but system is infeasible
284
+ if not solutions:
285
+ if check_result == unsat:
286
+ print("Warning: Lower and Upper Bound Equal but System Infeasible")
287
+ else:
288
+ raise ValueError("Lower and Upper Bound Equal but No Solutions Found")
289
+ return solutions
290
+ else:
291
+ target_costs = list(range(lower_bound, upper_bound+1))
292
+ iteration_order = "up"
293
+
294
+ for target_cost in target_costs:
295
+
296
+ if debug:
297
+ print(f" > Trying Cost = {target_cost}...")
298
+
299
+ # Push a temporary context to check "Can Cost == k?"
300
+ solv.push()
301
+ solv.add(cost == target_cost)
302
+ check_result = _check_or_timeout(solv)
303
+
304
+ if check_result == sat:
305
+ # Verify
306
+ solv.pop()
307
+ solv.push()
308
+ solv.add(cost < target_cost)
309
+ check_result = _check_or_timeout(solv)
310
+ solv.pop()
311
+ if check_result != unsat and iteration_order == "down":
312
+ continue
313
+ elif check_result != unsat and iteration_order == "up":
314
+ raise ValueError("Invalid Min Found")
315
+ # SUCCESS! We found the lowest possible cost.
316
+ # No verification loop needed because we checked 0, 1, 2... in order.
317
+ solv.add(cost == target_cost)
318
+ if enumerate_sols:
319
+ solutions = _enumerate_solutions(solv, cost_terms, z3_vars,
320
+ symmetry_map=symmetry_map)
321
+ else:
322
+ solutions = _enumerate_solutions(solv, cost_terms, z3_vars,
323
+ max_solutions=1)
324
+ return solutions
325
+
326
+ elif check_result == unknown:
327
+ raise TimeoutError(f" > Z3 gave up! Reason: {solv.reason_unknown()}")
328
+
329
+ solv.pop()
330
+
331
+ if not apriori_sol is None and target_cost >= apriori_sol:
332
+ # We've already established nothing can beat apriori_sol
333
+ break
334
+
335
+
336
+ return []
337
+
338
+
339
+
340
+
341
+ def _calc_min_cost(integer_constraints, nonzero_constraints, zero_constraints,
342
+ variables, max_result_range=5, timeout_ms=200):
343
+ """
344
+ Calculate a lower bound on the L1 cost and initialize the Z3 solver.
345
+
346
+ Sets up the Z3 solver with all constraints and computes a theoretical minimum
347
+ cost by minimizing each integer constraint independently, subject to the nonzero
348
+ and zero constraints.
349
+
350
+ :param integer_constraints: Expressions that must evaluate to integer values.
351
+ :type integer_constraints: list[sympy.Expr]
352
+ :param nonzero_constraints: Expressions that must evaluate to non-zero values.
353
+ :type nonzero_constraints: list[sympy.Expr]
354
+ :param zero_constraints: Expressions that must evaluate to zero.
355
+ :type zero_constraints: list[sympy.Expr]
356
+ :param variables: Symbols representing the unknowns to solve for.
357
+ :type variables: list[sympy.Symbol]
358
+ :param max_result_range: Maximum absolute value allowed for integer constraint
359
+ results. Defaults to 4.
360
+ :type max_result_range: int
361
+ :param timeout_ms: Timeout in milliseconds for individual satisfiability checks
362
+ during lower bound computation. Defaults to 200.
363
+ :type timeout_ms: int
364
+
365
+ :returns: A tuple containing:
366
+
367
+ - ``min_possible_cost`` (*int*): Lower bound on the achievable L1 cost.
368
+ - ``solv`` (*z3.Solver*): Configured Z3 solver with all constraints added.
369
+ - ``cost_terms`` (*list*): Z3 expressions for each integer constraint result.
370
+ - ``z3_vars`` (*dict[sympy.Symbol, z3.Real]*): Mapping from SymPy symbols
371
+ to Z3 variables.
372
+ - ``cost`` (*z3.Int*): Z3 integer variable representing the total L1 cost.
373
+
374
+ :rtype: tuple[int, z3.Solver, list, dict, z3.Int]
375
+
376
+ :raises ValueError: If the computed lower bound is incorrect (sanity check fails).
377
+ """
378
+
379
+ # --- STEP 1: PRE-COMPILATION ---
380
+ z3_vars = {var: Real(str(var)) for var in variables}
381
+ solver_strategy = Then('simplify', 'propagate-values', 'smt')
382
+ solv = solver_strategy.solver()
383
+ solv.set("timeout", timeout_ms)
384
+
385
+ # 1a. Expressions that are zero
386
+ zero_factors = set()
387
+ for expr in zero_constraints:
388
+ num, den = _eq_as_numer_denom(sym.nsimplify(expr, rational=True))
389
+ if (num, den) not in zero_factors:
390
+ solv.add(num == 0)
391
+ if len(den.free_symbols) > 0:
392
+ solv.add(den != 0)
393
+
394
+ # 1b. Nonzero Constraints
395
+ # Consider numerator and denominator seperately
396
+ nz_factors = set()
397
+ for expr in nonzero_constraints:
398
+ num, den = _eq_as_numer_denom(sym.nsimplify(expr, rational=True))
399
+ all_expr = [num]
400
+ if den != 1:
401
+ all_expr.append(den)
402
+ for nz_expr in all_expr:
403
+ factored_expr = sym.factor(nz_expr)
404
+ if factored_expr.is_Mul:
405
+ factors = factored_expr.args
406
+ else:
407
+ factors = [factored_expr]
408
+ for sub_expr in factors:
409
+ if sub_expr not in nz_factors:
410
+ if len(sub_expr.free_symbols) == 0 and expr != 0:
411
+ continue
412
+ z_expr = _sympy_to_z3(sub_expr, z3_vars)
413
+ solv.add(z_expr != 0)
414
+ nz_factors.add(z_expr)
415
+
416
+ # 1c. Integer Constraints
417
+ # We simplify ONCE here to avoid overhead inside loops.
418
+ cost_terms = []
419
+ integer_expr = {}
420
+ for expr in integer_constraints:
421
+ rat_expr = sym.simplify(expr, rational=True)
422
+ num, den = _eq_as_numer_denom(rat_expr)
423
+ if (num, den) in integer_expr:
424
+ cost_terms.append(integer_expr[(num, den)])
425
+ continue
426
+ # Simple linear/poly constraint: Z01, Z02-Z22, etc.
427
+ # Or one with rational coefficients: Z01/2 etc.
428
+ # Bound it directly
429
+ if len(den.free_symbols) == 0:
430
+ z = _sympy_to_z3(sym.simplify(num/den), z3_vars)
431
+ if not isinstance(z, int):
432
+ solv.add(IsInt(z))
433
+ integer_expr[(num, den)] = z
434
+ cost_terms.append(z)
435
+ # Rational constraint: N/D
436
+ # Transform: N == k * D
437
+ # with auxiliary variable k
438
+ # (bound k)
439
+ else:
440
+ k = Int(f"aux_{len(cost_terms)}")
441
+ z_num = _sympy_to_z3(num, z3_vars)
442
+ z_den = _sympy_to_z3(den, z3_vars)
443
+ solv.add(z_num == k * z_den)
444
+ solv.add(k >= -max_result_range)
445
+ solv.add(k <= max_result_range)
446
+ integer_expr[(num, den)] = k
447
+ cost_terms.append(k)
448
+ # Add nonzero constraints for denominator
449
+ factored_den = sym.factor(den)
450
+ if factored_den.is_Mul:
451
+ factors = factored_den.args
452
+ else:
453
+ factors = [factored_den]
454
+ for sub_expr in factors:
455
+ if sub_expr not in nz_factors:
456
+ if len(sub_expr.free_symbols) == 0 and expr != 0:
457
+ continue
458
+ z_expr = _sympy_to_z3(sub_expr, z3_vars)
459
+ solv.add(z_expr != 0)
460
+ nz_factors.add(z_expr)
461
+ # 1c. Cost Function (Sum of Absolute Values)
462
+ cost = Int('cost')
463
+
464
+ # Theoretical Min Cost = sum(min cost per term)
465
+ min_possible_cost = 0
466
+ cost_term_dict = {}
467
+ total_cost = None
468
+ for term in cost_terms:
469
+ if total_cost is None:
470
+ total_cost = Abs(term)
471
+ else:
472
+ total_cost += Abs(term)
473
+ if term in cost_term_dict:
474
+ min_possible_cost += cost_term_dict[term]
475
+ continue
476
+ min_val = 0
477
+ for val in range(0, max_result_range + 1):
478
+ # Thorough Estimate -- is it possible
479
+ # to be this value, considering all
480
+ # integer conditions?
481
+ solv.push()
482
+ solv.add(term == val)
483
+ result = solv.check()
484
+ solv.pop()
485
+ # Unknown is conservative here: treating the value as attainable
486
+ # can only weaken this preliminary lower bound. Critical checks
487
+ # below use _check_or_timeout instead.
488
+ if result != unsat:
489
+ break
490
+ if val < max_result_range:
491
+ min_val += 1
492
+ min_possible_cost += min_val
493
+ cost_term_dict[term] = min_val
494
+ solv.add(cost == total_cost)
495
+
496
+ # Add bounds on cost
497
+ for z in integer_expr.values():
498
+ solv.add(z >= -max_result_range)
499
+ solv.add(z <= max_result_range)
500
+
501
+
502
+ # Verify
503
+ solv.push()
504
+ solv.add(cost < min_possible_cost)
505
+ check_result = _check_or_timeout(solv)
506
+ if check_result == sat:
507
+ raise ValueError("Bad minimum value")
508
+ solv.pop()
509
+
510
+ return min_possible_cost, solv, cost_terms, z3_vars, cost
511
+
512
+
513
+ def _enumerate_solutions(solver_with_state, tracked_exprs, z3_vars, max_solutions=1000, symmetry_map=lambda x: [x],
514
+ verify_same_cost=True):
515
+ """
516
+ Enumerate all unique solutions for the current solver state.
517
+
518
+ Iteratively finds satisfying assignments, extracts the solution, blocks it
519
+ (along with symmetric equivalents), and repeats until no more solutions exist
520
+ or the maximum is reached.
521
+
522
+ The solver must already have appropriate cost constraints added before calling
523
+ this function. Solutions are blocked by adding constraints that exclude the
524
+ found result vector and all its symmetric equivalents.
525
+
526
+ :param solver_with_state: Z3 solver with constraints already configured,
527
+ including any cost equality constraints.
528
+ :type solver_with_state: z3.Solver
529
+ :param tracked_exprs: Z3 expressions whose values define a solution
530
+ (typically the integer constraint terms).
531
+ :type tracked_exprs: list[z3.ExprRef]
532
+ :param z3_vars: Mapping from SymPy symbols to their corresponding Z3 variables.
533
+ :type z3_vars: dict[sympy.Symbol, z3.Real]
534
+ :param max_solutions: Maximum number of solutions to enumerate. Defaults to 1000.
535
+ :type max_solutions: int
536
+ :param symmetry_map: Function mapping a result vector to all equivalent vectors
537
+ under symmetry. All symmetric equivalents are blocked together.
538
+ Defaults to identity only.
539
+ :type symmetry_map: Callable[[list[int]], list[list[int]]]
540
+ :param verify_same_cost: Whether to verify that all enumerated solutions have
541
+ the same cost. Defaults to True.
542
+ :type verify_same_cost: bool
543
+
544
+ :returns: List of solutions, sorted deterministically. Each solution is a
545
+ dictionary with keys:
546
+
547
+ - ``'results'`` (*list[int]*): Integer values of the tracked expressions.
548
+ - ``'variables'`` (*dict[sympy.Symbol, sympy.Rational]*): Variable assignments.
549
+
550
+ :rtype: list[dict]
551
+
552
+ .. note::
553
+ This function modifies the solver state by adding blocking clauses.
554
+ The solver should not be reused for other purposes after calling this.
555
+ """
556
+ results = []
557
+ n_res = 0
558
+
559
+ # We iterate while the solver remains satisfiable. A Z3 timeout is
560
+ # reported as ``unknown``, not as a Python exception, so translate it
561
+ # explicitly rather than silently treating a timed-out enumeration as
562
+ # complete.
563
+ while _check_or_timeout(solver_with_state) == sat:
564
+ m = solver_with_state.model()
565
+
566
+ # 1. Extract Results
567
+ res_vals = [m.eval(e).as_long() for e in tracked_exprs]
568
+
569
+ # 2. Extract Variables (as SymPy Rationals)
570
+ var_vals = {}
571
+ for var, z_var in z3_vars.items():
572
+ val = m[z_var]
573
+ # val not present
574
+ if val is None:
575
+ continue
576
+ if hasattr(val, 'numerator_as_long'):
577
+ val_sym = sym.Rational(val.numerator_as_long(), val.denominator_as_long())
578
+ else:
579
+ val_sym = sym.Integer(val.as_long())
580
+ var_vals[var] = val_sym
581
+
582
+ results.append({"results": res_vals, "variables": var_vals})
583
+ n_res += 1
584
+ if n_res >= max_solutions:
585
+ if max_solutions != 1:
586
+ print(f" > Reached max solutions limit of {max_solutions}, stopping enumeration.")
587
+ break
588
+
589
+ # 3. Block this specific result vector, as well as any equivalents under symmetry
590
+ n_expr = len(tracked_exprs)
591
+ for res_perm in symmetry_map(res_vals):
592
+ block_clause = [tracked_exprs[i] != res_perm[i] for i in range(n_expr)]
593
+ solver_with_state.add(Or(block_clause))
594
+
595
+ # Sort results deterministically to ensure consistent ordering across runs
596
+ # Sort by: results tuple first, then by variable assignments
597
+ def _sort_key(sol):
598
+ res_val = sum(abs(x) for x in sol["results"])
599
+ res_key = tuple([-x for x in sol["results"]])
600
+ var_key = tuple(sorted((str(k), str(v)) for k, v in sol["variables"].items()))
601
+ return (res_val, res_key, var_key)
602
+ results.sort(key=_sort_key)
603
+
604
+ # Verify that all results have the same cost
605
+ if len(results) > 1 and verify_same_cost:
606
+ first_cost = sum(abs(x) for x in results[0]["results"])
607
+ for i,r in enumerate(results[1:]):
608
+ this_cost = sum(abs(x) for x in r["results"])
609
+ if this_cost != first_cost:
610
+ raise ValueError(
611
+ f"Inconsistent costs in enumerated solutions: "
612
+ f"solution 0 has cost {first_cost} with results {results[0]['results']}, "
613
+ f"but solution {i+1} has cost {this_cost} with results {r['results']}"
614
+ )
615
+
616
+ return results
617
+
618
+ def _zero_subs_for_nonzero(nonzero_constraints, variables, n_terms=1):
619
+ """
620
+ Generate substitutions that set all variables not involved in the given nonzero constraints to zero.
621
+ """
622
+
623
+ # Heuristic solver for upper bound -- assume maximal number of variables are zero
624
+ nz_prod = sym.sympify(1)
625
+ # We want to consider the nonzero constraints together,
626
+ # so we take their product and consider the factors of that.
627
+ nonzero_constraints_no_frac = []
628
+ for nz in nonzero_constraints:
629
+ nz_numer, nz_denom = _eq_as_numer_denom(nz)
630
+ nonzero_constraints_no_frac.append(nz_numer)
631
+ if len(nz_denom.free_symbols) > 0:
632
+ nonzero_constraints_no_frac.append(nz_denom)
633
+ for nz in nonzero_constraints_no_frac:
634
+ nz_prod *= nz
635
+ nz_numer, nz_denom = _eq_as_numer_denom(nz_prod)
636
+ nz_numer = sym.expand(nz_numer)
637
+ if isinstance(nz_numer, sym.Add):
638
+ nz_terms = nz_numer.args
639
+ else:
640
+ nz_terms = [nz_numer]
641
+ unique_subs = set()
642
+ unique_subs_dict = []
643
+ for nz_terms in itertools.combinations(sorted(nz_terms, key=lambda x: (len(x.free_symbols), str(x))), n_terms):
644
+ zero_subs = {}
645
+ for var in variables:
646
+ if all(var not in nz_term.free_symbols for nz_term in nz_terms):
647
+ zero_subs[var] = 0
648
+ unique_subs_key = tuple(sorted(zero_subs.items(), key=lambda x: str(x[0])))
649
+ if unique_subs_key in unique_subs or nz_denom.subs(zero_subs) == 0:
650
+ continue
651
+ unique_subs.add(unique_subs_key)
652
+ unique_subs_dict.append(zero_subs)
653
+ return unique_subs_dict, nz_terms
654
+
655
+ def _heuristic_upper_bound(integer_constraints, nonzero_constraints, zero_constraints, variables, max_result_range=5,
656
+ timeout_ms=int(1e03), return_first_only=False, debug=False):
657
+ """
658
+ Find a heuristic upper bound on the optimal cost by maximizing zero variables.
659
+
660
+ Attempts to find a valid solution by setting as many variables to zero as
661
+ possible while still satisfying the nonzero constraints. This provides an
662
+ upper bound that can speed up the main optimization by allowing a top-down
663
+ search strategy.
664
+
665
+ The algorithm:
666
+
667
+ 1. Expands the product of all nonzero constraints into terms.
668
+ 2. For each term, identifies which variables must be nonzero for that term.
669
+ 3. Sets all other variables to zero and solves the reduced problem.
670
+ 4. Returns the best (lowest cost) solution found.
671
+
672
+ :param integer_constraints: Expressions that must evaluate to integer values.
673
+ :type integer_constraints: list[sympy.Expr]
674
+ :param nonzero_constraints: Expressions that must evaluate to non-zero values.
675
+ :type nonzero_constraints: list[sympy.Expr]
676
+ :param zero_constraints: Expressions that must evaluate to zero.
677
+ :type zero_constraints: list[sympy.Expr]
678
+ :param variables: Symbols representing the unknowns to solve for.
679
+ :type variables: list[sympy.Symbol]
680
+ :param max_result_range: Maximum absolute value allowed for integer constraint
681
+ results. Defaults to 4.
682
+ :type max_result_range: int
683
+ :param timeout_ms: Timeout in milliseconds for each sub-problem. Defaults to 1000.
684
+ :type timeout_ms: int
685
+
686
+ :returns: A tuple containing:
687
+
688
+ - ``best_val`` (*int*): The lowest cost found (upper bound on optimal).
689
+ - ``res`` (*list[dict]*): Solutions achieving the best cost, with zero
690
+ substitutions included in the variable assignments.
691
+
692
+ :rtype: tuple[int, list[dict]]
693
+
694
+ :raises TimeoutError: If solver times out on a sub-problem (propagated from
695
+ recursive call to :func:`find_rational_vars_integer_results`).
696
+ """
697
+ all_zero_subs, nz_terms = _zero_subs_for_nonzero(nonzero_constraints, variables)
698
+ best_val = len(integer_constraints)*max_result_range
699
+ res = []
700
+ if debug:
701
+ print(f" > Heuristic upper bound search over {len(nz_terms)} nonzero terms...")
702
+ print(f" > Nonzero terms: {nz_terms}")
703
+
704
+ for zero_subs in all_zero_subs:
705
+
706
+ new_constraints = [c.subs(zero_subs) for c in integer_constraints if c.subs(zero_subs) != 0]
707
+ new_nonzero_constraints = [c.subs(zero_subs) for c in nonzero_constraints if c.subs(zero_subs) != 0]
708
+ new_zero_constraints = [c.subs(zero_subs) for c in zero_constraints if c.subs(zero_subs) != 0]
709
+
710
+ # Make sure to only include variables that remain finite
711
+ if any(c.has(sym.core.numbers.ComplexInfinity) or c.has(sym.core.numbers.Infinity) for c in new_constraints+new_zero_constraints+new_nonzero_constraints):
712
+ continue
713
+
714
+ new_variables = sorted(set(itertools.chain.from_iterable(c.free_symbols for c in new_constraints+new_nonzero_constraints+new_zero_constraints)), key=str)
715
+ this_res = find_rational_vars_integer_results(new_constraints, nonzero_constraints=new_nonzero_constraints,
716
+ zero_constraints=new_zero_constraints,
717
+ variables=new_variables,
718
+ max_result_range=max_result_range,
719
+ timeout_ms=timeout_ms, heuristic_upper=False,
720
+ apriori_sol=best_val, enumerate_sols=False, debug=debug)
721
+ if this_res:
722
+ val = sum(abs(x) for x in this_res[0]["results"])
723
+ if val <= best_val:
724
+ this_res_proc = []
725
+ for r in this_res:
726
+ this_res_proc.append({"results": r["results"], "variables": r["variables"] | zero_subs})
727
+ if val < best_val:
728
+ res = this_res_proc
729
+ best_val = val
730
+ elif val == best_val:
731
+ # Explicitly add the zero substitutions to the results
732
+ res.extend(this_res_proc)
733
+ if return_first_only and res:
734
+ break
735
+
736
+ return best_val, res
737
+
738
+
739
+ def _sympy_to_z3(e, z3_vars):
740
+ e = sym.sympify(e)
741
+ if e.is_Integer:
742
+ return int(e)
743
+ if e.is_Symbol:
744
+ return z3_vars[e]
745
+ if e.is_Add:
746
+ return Sum([_sympy_to_z3(arg, z3_vars) for arg in e.args])
747
+ if e.is_Mul:
748
+ res = 1
749
+ for arg in e.args:
750
+ res = res * _sympy_to_z3(arg, z3_vars)
751
+ return res
752
+ if e.is_Pow:
753
+ base, exp = e.args
754
+ return _sympy_to_z3(base, z3_vars) ** int(exp)
755
+ if e.is_Rational:
756
+ return RealVal(e.p) / RealVal(e.q)
757
+ raise ValueError(f"Unsupported expression type: {type(e)}")
758
+
759
+
760
+ if __name__ == "__main__":
761
+
762
+ # --- Example Usage ---
763
+ Z1, Z2 = sym.symbols('Z1 Z2')
764
+
765
+ # We want these expressions to be integers:
766
+ # 1. Z1/2
767
+ # 2. Z2/3
768
+ # 3. Z1 + Z2
769
+
770
+ integer_exprs = [
771
+ Z1 / 2,
772
+ Z2 / 3,
773
+ Z1 + Z2
774
+ ]
775
+
776
+ # Example Nonzero Constraint:
777
+ # The product Z1*Z2 must not be zero (implies neither is zero)
778
+ nonzero_exprs = [
779
+ Z1 * Z2
780
+ ]
781
+
782
+ print("Solving...")
783
+ all_sols = find_rational_vars_integer_results(
784
+ integer_constraints=integer_exprs,
785
+ nonzero_constraints=nonzero_exprs,
786
+ variables=[Z1, Z2],
787
+ max_result_range=5
788
+ )
789
+
790
+ print(f"Found {len(all_sols)} unique integer profiles.")
791
+ for i, s in enumerate(all_sols):
792
+ print(f"Solution {i+1}:")
793
+ print(f" Integer Results: {s['results']}")
794
+ print(f" Variable Ex: {s['variables']}")