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,1071 @@
1
+ # Vendored from sircuitenum/singular_interface.py (GPL-3.0), sircuitenum commit b2c57e8.
2
+ __doc__ = "singular_interface.py: Interface to Singular for solving underdetermined polynomial systems using Groebner Covers."
3
+ __author__ = "Eli Weissler"
4
+ __version__ = "0.1.0"
5
+
6
+
7
+ __all__ = [
8
+ "solve_with_singular", "is_compatible", "extract_mappings", "get_groebner_basis"
9
+ ]
10
+
11
+ import shutil
12
+ import subprocess
13
+ import os
14
+ import signal
15
+ import time
16
+ import sys
17
+ import select
18
+
19
+ import sympy as sym
20
+ import numpy as np
21
+ from sympy import S
22
+ import re
23
+ import itertools, functools
24
+ from pathlib import Path
25
+ from typing import List, Dict, Any, Optional, Union, Iterable
26
+
27
+ # Singular Interface -- Initialize once per process.
28
+ # circuit_quantization: SageMath was only used to locate the binary and for one
29
+ # lex Groebner basis (get_groebner_basis below); both are done without it.
30
+ SINGULAR_PATH = (shutil.which("Singular")
31
+ or shutil.which("Singular", path=os.path.dirname(sys.executable)))
32
+ if SINGULAR_PATH is None:
33
+ raise ImportError("circuit_quantization.optimize needs the Singular binary on PATH "
34
+ "(conda install -c conda-forge singular)")
35
+ WORKER_SINGULAR = None
36
+ GROEBNER_SINGULAR = None # separate process for get_groebner_basis
37
+
38
+ # Sircuitenum
39
+ from .rational_check import has_at_least_one_clean_root, get_clean_roots, _has_rational_coeffs
40
+ from . import _utils as utils
41
+
42
+
43
+
44
+ def get_groebner_basis(sympy_eqs, sympy_vars):
45
+ """
46
+ Calculates the reduced lex Groebner Basis over QQ with Singular, with monic
47
+ polynomials as SageMath (Singular backend) returns them, from and to SymPy objects.
48
+
49
+ circuit_quantization: replaces sircuitenum's get_sage_groebner_basis without Sage.
50
+ A reduced Groebner basis is unique for a given ordering, so this matches Sage's
51
+ result; polynomials are listed by decreasing leading monomial, as Sage lists them.
52
+ It uses its own Singular process (GROEBNER_SINGULAR), killed on any interruption,
53
+ because callers run it under run_with_timeout. groebner() picks the algorithm (FGLM for
54
+ zero-dimensional lex), matching Sage's speed. SymPy is not a substitute: a dense quadratic
55
+ system in 4 variables takes Singular 0.06 s and SymPy over a minute (0.16 s via FGLM, but
56
+ 6 s at 5 variables, where Singular takes 0.2 s).
57
+
58
+ Args:
59
+ sympy_eqs: List of SymPy equations or expressions (assumed = 0)
60
+ sympy_vars: List of SymPy symbols
61
+
62
+ Returns:
63
+ List of SymPy expressions representing the Groebner Basis
64
+ """
65
+ global GROEBNER_SINGULAR
66
+ exprs = [eq.lhs - eq.rhs if isinstance(eq, sym.Eq) else eq for eq in sympy_eqs]
67
+ # Integer coefficients for Singular; scaling a generator does not change the ideal.
68
+ polys = [sym.Poly(e, *sympy_vars, domain=sym.QQ).clear_denoms()[1].as_expr() for e in exprs]
69
+ singular_name = {v: sym.Symbol(f"x({k + 1})") for k, v in enumerate(sympy_vars)}
70
+ generators = ",".join(str(p.subs(singular_name, simultaneous=True)).replace("**", "^") or "0" for p in polys)
71
+ cmd = (f"if (defined(GB_RING)) {{kill GB_RING;}}\n"
72
+ f"ring GB_RING = 0, (x(1..{len(sympy_vars)})), lp; short = 0; option(redSB);\n"
73
+ f"ideal GB_I = {generators or '0'};\n"
74
+ f"\"|||GB|||\"; string(simplify(groebner(GB_I), 1));")
75
+ if GROEBNER_SINGULAR is None:
76
+ GROEBNER_SINGULAR = SafeSingular(binary_path=SINGULAR_PATH, timeout=100)
77
+ try:
78
+ out = GROEBNER_SINGULAR.eval(cmd)
79
+ except BaseException:
80
+ GROEBNER_SINGULAR.kill() # a half-read reply would corrupt the next call
81
+ raise
82
+ # string(...) prints the whole basis on the one line after the marker.
83
+ after = clean_singular_string(out).split("|||GB|||", 1)[1]
84
+ text = next(line for line in after.splitlines() if line.strip())
85
+ sympy_name = {f"x({k + 1})": str(v) for k, v in enumerate(sympy_vars)}
86
+ text = re.sub(r"x\((\d+)\)", lambda m: f"({sympy_name[m.group(0)]})", text).replace("^", "**")
87
+ local = {str(v): v for v in sympy_vars}
88
+ basis = [sym.sympify(term, locals=local) for term in text.split(",") if term.strip()]
89
+ basis = [b for b in basis if b != 0] or [sym.Integer(0)]
90
+ # Sage lists the reduced basis by decreasing leading monomial in lex order.
91
+ lead = lambda b: sym.Poly(b, *sympy_vars).monoms(order="lex")[0] if b.free_symbols else (0,) * len(sympy_vars)
92
+ return sorted(basis, key=lead, reverse=True)
93
+
94
+
95
+ def solve_0D_backsub(sympy_eqs, sympy_vars, sympy_params=None, rational_only=False, debug=False) -> List[Dict[str, Any]]:
96
+ """
97
+ Finds ALL rational solutions for a system with parameters.
98
+ Includes a final substitution pass to ensure all variables are fully numeric.
99
+ """
100
+ if debug:
101
+ print("Solving 0D system via back-substitution:")
102
+ print("Equations:")
103
+ for eq in sympy_eqs:
104
+ print("-----\n", eq)
105
+ print("Variables:", sympy_vars)
106
+ print("Parameters:", sympy_params)
107
+ print("Rational Only:", rational_only)
108
+
109
+ if sympy_params is None: sympy_params = []
110
+
111
+ # Get triangular groebner basis (lex)
112
+ # Order: vars > params (lex is mandatory for triangular form)
113
+ all_vars = sympy_vars + sympy_params
114
+ gb = get_groebner_basis(sympy_eqs, all_vars)
115
+ # Inconsistent system
116
+ if len(gb) == 1 and gb[0] == 1:
117
+ return []
118
+ # Identify any variables that don't actually appear
119
+ sympy_vars =[v for v in sympy_vars if any(v in eq.free_symbols for eq in gb)]
120
+ if len(sympy_vars) == 0:
121
+ raise ValueError(f"Unconstrained variables: {sympy_vars}")
122
+
123
+ if debug:
124
+ print("Groebner Basis (Triangular Form):")
125
+ for eq in gb:
126
+ print("-----\n", eq)
127
+ print("variables after filtering:", sympy_vars)
128
+
129
+ # Backsubstitute, with branching for multiple roots
130
+ solve_order = sympy_vars[::-1]
131
+ current_branches = [{}]
132
+ param_set = set(sympy_params)
133
+ for target_var in solve_order:
134
+ next_branches = []
135
+ for partial_sol in current_branches:
136
+ # 1. Substitute knowns
137
+ specialized_basis = [poly.subs(partial_sol) for poly in gb]
138
+
139
+ # 2. Select Polynomial that contains only target_var + params
140
+ # Pick the one with the lowest degree in target_var
141
+ candidate_polys = []
142
+ allowed_symbols = param_set | {target_var}
143
+ for poly in specialized_basis:
144
+ if poly == 0:
145
+ continue
146
+ if target_var not in poly.free_symbols:
147
+ continue
148
+ if poly.free_symbols.issubset(allowed_symbols):
149
+ candidate_polys.append(poly)
150
+ if not candidate_polys:
151
+ raise ValueError(f"Unconstrained variable: {target_var}")
152
+ degrees = [sym.degree(p, target_var) for p in candidate_polys]
153
+ poly_to_solve = candidate_polys[np.argmin(degrees)].as_poly(target_var)
154
+ # 3. Find roots via factorization -> solve
155
+ roots = []
156
+ if rational_only:
157
+ if has_at_least_one_clean_root(poly_to_solve):
158
+ for root in get_clean_roots(poly_to_solve):
159
+ if _has_rational_coeffs(root, sympy_params):
160
+ roots.append({target_var: root})
161
+ else:
162
+ coeff, factors = sym.factor_list(poly_to_solve)
163
+ for factor, exp in factors:
164
+ sols = sym.solve(factor, target_var, dict=True, simplify=True)
165
+ print("sols", sols)
166
+ roots.extend(sols)
167
+
168
+ # 4. Create new branches from roots
169
+ for r in roots:
170
+ new_branch = partial_sol.copy() | r
171
+ next_branches.append(new_branch)
172
+
173
+ current_branches = next_branches
174
+ if not current_branches:
175
+ return []
176
+
177
+ # Final Simplify Pass
178
+ final_results = []
179
+ for sol in current_branches:
180
+ clean_sol = {k: sym.simplify(v) for k, v in sol.items()}
181
+ final_results.append(clean_sol)
182
+
183
+ return final_results
184
+
185
+
186
+ def is_compatible(equations: Iterable[Union[sym.Expr, sym.Equality]], check_fraction: bool = True, timeout=None, debug: bool = False) -> bool:
187
+ """
188
+ Checks if a system of SymPy equations is mathematically consistent (has at least one solution).
189
+
190
+ This function performs a series of checks ranging from trivial inconsistency detection
191
+ (e.g., :math:`1 = 0`) to complex ideal membership tests using the Singular algebra system.
192
+
193
+ :param equations: A collection of SymPy expressions or equalities. If expressions are provided,
194
+ they are assumed to be equal to zero.
195
+ :type equations: Iterable[Union[sym.Expr, sym.Equality]]
196
+ :param check_fraction: If ``True``, detects fractions in the equations. It clears denominators
197
+ and applies the Rabinowitsch trick (adding :math:`1 - z \\cdot denom = 0`)
198
+ to enforce that denominators cannot be zero. Defaults to ``True``.
199
+ :type check_fraction: bool, optional If True, detects fractions in the equations. It clears denominators
200
+
201
+ :return: ``True`` if the system is potentially solvable (compatible), ``False`` if it is
202
+ proven inconsistent.
203
+ :rtype: bool
204
+
205
+ .. note::
206
+ This function uses an external interface to **Singular**. It constructs a Groebner basis
207
+ computation to determine if the ideal generated by the equations is the whole ring (1).
208
+ """
209
+
210
+ equations = list(equations)
211
+ if not equations:
212
+ return True # Empty system is trivially compatible
213
+
214
+ # Convert equations to SymPy expressions if needed
215
+ if isinstance(list(equations)[0], sym.Equality):
216
+ equations = [eq.lhs - eq.rhs for eq in equations]
217
+
218
+ # Quick inconsistency check: if any equation is a non-zero constant, system is inconsistent
219
+ for eq in equations:
220
+ if eq.is_Number and eq != 0:
221
+ return False
222
+
223
+ # Verify fractions are not present and adjust if needed
224
+ if check_fraction:
225
+ new_eqs = []
226
+ denoms = []
227
+ for eq in equations:
228
+ numer, denom = _eq_as_numer_denom(eq)
229
+ if denom != 1:
230
+ denoms.append(denom)
231
+ new_eqs.append(numer)
232
+ equations = new_eqs
233
+ # Rabinowitsch Trick to enforce nonzero conditions
234
+ nz_term = []
235
+ if len(denoms) > 0:
236
+ nz_eq = sym.sympify(1)
237
+ for d in denoms:
238
+ nz_eq *= d
239
+ nz_var = sym.symbols('denomNZVar')
240
+ nz_term = [1 - nz_var * nz_eq]
241
+ equations += nz_term
242
+
243
+ # Collect all symbols from equations
244
+ all_symbols = set()
245
+ for eq in equations:
246
+ all_symbols.update(str(s) for s in eq.free_symbols)
247
+
248
+ # No variables in the system
249
+ if not all_symbols:
250
+ if all(sym.simplify(eq) == 0 for eq in equations):
251
+ # All equations are 0 = 0, trivially satisfied
252
+ return []
253
+
254
+ # Not obviously true or false, use Singular to check
255
+
256
+ dummy_map, _ = make_dummy_map(all_symbols)
257
+
258
+ # Build input strings for the Singular proc (no spaces)
259
+ str_vars = ",".join(dummy_map[str(v)] for v in all_symbols)
260
+ str_eqs = ",".join(str(sym.nsimplify(eq)).replace("**", "^") for eq in equations)
261
+ for orig in sorted(dummy_map.keys(), key=lambda x: (-len(x), str(x))):
262
+ str_eqs = str_eqs.replace(orig, dummy_map[orig])
263
+
264
+ # 1. Enforce the ring context FIRST
265
+ # 2. Then define the ideal and call the proc
266
+ cmd = f"setring SUPER_RING; check_solvability(ideal({str_eqs}));"
267
+
268
+ return _cached_compatible(cmd, timeout, debug=debug)
269
+
270
+
271
+ @functools.cache
272
+ def _cached_compatible(cmd: str, timeout: Optional[float] = None, debug: bool = False) -> bool:
273
+ if WORKER_SINGULAR is None:
274
+ initialize_singular()
275
+ cleaned = clean_singular_string(WORKER_SINGULAR.eval(cmd, timeout))
276
+ return "1" in cleaned
277
+
278
+
279
+ def solve_with_singular(equations: list[sym.Expr], solve_vars=None, check_solvability=True,
280
+ check_fraction: bool = True, rational_only: bool = False, debug: bool = False,
281
+ get_all_sols: bool = True, branch_timeout=1) -> List[Dict[str, Any]]:
282
+ """
283
+ Solves a system of SymPy equations using the Groebner Cover algorithm via Singular.
284
+
285
+ This approach utilizes a pipeline of ``facstd`` (factorized Groebner Basis) ->
286
+ ``minAssGTZ`` (minimal associated primes) -> ``indepSet`` (independent sets) ->
287
+ ``grobcov`` (Groebner Cover) to provably find all solution branches, including singular
288
+ and degenerate cases where parameters take specific values.
289
+
290
+ :param equations: A list of SymPy expressions or equalities to solve.
291
+ :type equations: List[Union[sym.Expr, sym.Equality]]
292
+ :param solve_vars: A specific list of symbols to treat as dependent variables (unknowns).
293
+ Symbols present in ``equations`` but not in ``solve_vars`` are treated
294
+ as free parameters (constants) for the solving process.
295
+ If ``None``, the algorithm auto-discovers the independent versus
296
+ dependent variables for each component.
297
+ :type solve_vars: Iterable[sym.Symbol], optional
298
+ :param check_solvability: If ``True``, runs a quick :func:`is_compatible` check before
299
+ attempting the full Groebner Cover. Defaults to ``True``.
300
+ :type check_solvability: bool, optional
301
+ :param check_fraction: If ``True``, processes equations to clear denominators and enforce
302
+ non-zero conditions on them. Defaults to ``True``.
303
+ :param rational_only: If ``True``, only allows for solutions that contain rational numbers
304
+ :type check_fraction: bool, optional
305
+
306
+ :return: A list of solution branches. Each branch is a dictionary containing:
307
+
308
+ * **id** (*int*): Unique branch identifier.
309
+ * **component** (*int*): Leading polynomial powers of the Groebner Basis.
310
+ * **params** (*list[str]*): Names of independent variables (free parameters).
311
+ * **vars** (*list[str]*): Names of dependent variables (solved unknowns).
312
+ * **constraints** (*list[sym.Expr]*): Conditions on parameters for this branch to be valid.
313
+ * **constraint_basis** (*list[sym.Expr]*): A Groebner basis for the constraints if there are finite solutions.
314
+ * **nonnull** (*list[sym.Expr]*): Expressions that must not be zero.
315
+ * **basis** (*list*): The Groebner basis for this specific segment.
316
+ * **mapping** (*dict*): A dictionary mapping variable names to their solution expressions
317
+ or the string "Free Parameter".
318
+ :rtype: List[Dict[str, Any]]
319
+ """
320
+
321
+ # Verify fractions are not present and adjust if needed
322
+ denoms = []
323
+ if check_fraction:
324
+ new_eqs = []
325
+ for eq in equations:
326
+ numer, denom = _eq_as_numer_denom(eq)
327
+ if denom != 1:
328
+ denoms.append(denom)
329
+ new_eqs.append(numer)
330
+ equations = new_eqs
331
+
332
+ if not isinstance(equations, list):
333
+ equations = list(equations)
334
+
335
+ all_symbols = set()
336
+ for eq in equations:
337
+ all_symbols.update(str(s) for s in eq.free_symbols)
338
+
339
+ # Quick compatibility check
340
+ if not equations or not all_symbols:
341
+ print("Trivially no branches (no equations or no variables).")
342
+ return [] # No equations or no variables means no branches
343
+ # Convert equations to SymPy expressions if needed
344
+ if isinstance(equations[0], sym.Equality):
345
+ equations = [eq.lhs - eq.rhs for eq in equations]
346
+ if check_solvability:
347
+ if not is_compatible(equations, debug=debug):
348
+ print("System is incompatible, no solutions.")
349
+ return []
350
+
351
+ # Determine Fixed vs Potential variables
352
+ if solve_vars is not None:
353
+ solve_vars_set = set(str(s) for s in solve_vars)
354
+ fixed_params = sorted(all_symbols - solve_vars_set)
355
+ potential_vars = sorted(set(solve_vars_set & all_symbols))
356
+ else:
357
+ fixed_params = []
358
+ potential_vars = sorted(set(str(s) for s in all_symbols))
359
+
360
+ dummy_map, inv_dummy_map = make_dummy_map(fixed_params + potential_vars)
361
+
362
+
363
+ # Build input strings for the Singular proc (no spaces)
364
+ str_fixed_params = ",".join(dummy_map[str(p)] for p in fixed_params)
365
+ str_potential_vars = ",".join(dummy_map[str(v)] for v in potential_vars)
366
+ str_eqs = ",".join(str(sym.nsimplify(eq)).replace("**", "^") for eq in equations)
367
+ for orig in sorted(dummy_map.keys(), key=lambda x: (-len(x), str(x))):
368
+ str_eqs = str_eqs.replace(orig, dummy_map[orig])
369
+
370
+ # Run Singular
371
+ singular_call = f'solve_cover("{str_fixed_params}", "{str_potential_vars}", "{str_eqs}", {int(rational_only)}, {int(debug)});'
372
+ if debug:
373
+ print("singular call", singular_call)
374
+ raw_output = _cached_solve(singular_call, debug=debug)
375
+ if debug:
376
+ print("raw singular output", raw_output)
377
+
378
+ # 1. Parse Raw Output
379
+ all_var_names = list(dummy_map.values())
380
+ raw_branches = parse_singular_output(raw_output, all_var_names, inv_dummy_map=inv_dummy_map)
381
+ if debug:
382
+ print(f"Singular returned {len(raw_branches)} raw branches.")
383
+ final_branches = []
384
+ # 2. Resolve Each Branch (Logic moved "inside solve")
385
+ # Sort branches by number of constraints (heuristic: more constraints = more likely to be easily resolved)
386
+ raw_branches.sort(key=lambda b: -len(b['constraints']))
387
+ for raw_br in raw_branches:
388
+
389
+ if raw_br['basis'] == [1]: continue # Inconsistent
390
+
391
+ # Resolve (Handles recursion, filtering, refinement)
392
+ resolved_list = resolve_branch_logic(raw_br, equations, rational_only=rational_only,
393
+ branch_timeout=branch_timeout, debug=debug)
394
+
395
+ final_branches.extend(resolved_list)
396
+
397
+ # If we only want one solution, take the first resolved branch
398
+ if (not get_all_sols) and (len(final_branches) > 0):
399
+ if (check_branch_validity(final_branches[0], equations) and
400
+ all(_robust_substitute(denom, final_branches[0]['mapping']) != 0 for denom in denoms)):
401
+ break
402
+
403
+ if debug:
404
+ print(f"After resolution, {len(final_branches)} total branches.")
405
+ # 3. Final Validity Check
406
+ valid_branches = []
407
+ for br in final_branches:
408
+ if (check_branch_validity(br, equations) and
409
+ all(_robust_substitute(denom, br['mapping']) != 0 for denom in denoms)):
410
+ valid_branches.append(br)
411
+ if debug:
412
+ print(f"After validity checking, {len(valid_branches)} valid branches.")
413
+ # 4. Filter Redundant Branches
414
+ valid_branches = filter_redundant_branches(valid_branches)
415
+
416
+ if debug:
417
+ print(f"After redundancy filtering, {len(valid_branches)} unique branches.")
418
+ print("first branch", valid_branches[0]["mapping"] if valid_branches else "N/A")
419
+
420
+ return valid_branches
421
+
422
+ @functools.cache
423
+ def _cached_solve(singular_call: str, debug: bool = False) -> str:
424
+ if WORKER_SINGULAR is None:
425
+ initialize_singular()
426
+ out = WORKER_SINGULAR.eval(singular_call, debug=debug)
427
+ return out
428
+
429
+ def extract_mappings(branches: List[Dict[str, Any]], real_only: bool = False) -> List[Dict[str, Any]]:
430
+ """
431
+ Extracts and simplifies variable mappings from the complex branch structure returned by the solver.
432
+
433
+ :param branches: The list of branch dictionaries returned by :func:`solve_with_singular`.
434
+ :type branches: List[Dict[str, Any]]
435
+ :param real_only: If ``True``, filters out any mappings where the solution explicitly
436
+ contains the imaginary unit :math:`i` (SymPy's ``I``). Defaults to ``False``.
437
+ :type real_only: bool, optional
438
+
439
+ :return: A list of simplified dictionaries, where each dictionary maps variables to their
440
+ SymPy expressions representing the solutions. Can be used in expr.subs(mapping).
441
+ :rtype: List[Dict[str, Any]]
442
+ """
443
+
444
+ simplified_mappings = []
445
+ for br in branches:
446
+ mapping = br['mapping']
447
+ if real_only:
448
+ # Check if mapping has an explicit imaginary part
449
+ if all(not sym.sympify(val).has(sym.I) for val in mapping.values()):
450
+ simplified_mappings.append(mapping)
451
+ else:
452
+ simplified_mappings.append(mapping)
453
+ return simplified_mappings
454
+
455
+
456
+ # Helper to convert Singular power notation back to SymPy
457
+ # (e.g. x2 -> x**2)
458
+ def fix_powers(text, var_names):
459
+ new_text = ""
460
+ i = 0
461
+ n_chars = len(text)
462
+ while i < n_chars:
463
+ this_char = text[i]
464
+ if this_char in var_names:
465
+ # Check for following digits
466
+ j = i + 1
467
+ power_str = ""
468
+ while j < n_chars and text[j].isdigit():
469
+ power_str += text[j]
470
+ j += 1
471
+ if power_str:
472
+ new_text += this_char + "**" + power_str
473
+ i = j
474
+ else:
475
+ new_text += this_char
476
+ i += 1
477
+ else:
478
+ new_text += this_char
479
+ i += 1
480
+ return new_text
481
+
482
+
483
+ def clean_singular_string(raw_output):
484
+ """
485
+ Removes Singular list markers ([1]:) and comments (//)
486
+ so the output looks exactly like the old string format.
487
+ """
488
+ lines = raw_output.splitlines()
489
+ clean_lines = []
490
+ # Regex to match "[123]: " at the start of a line
491
+ marker_re = re.compile(r'^\s*\[\d+\]:\s*')
492
+ for line in lines:
493
+ # 1. Drop warning/comment lines
494
+ if line.strip().startswith("//"):
495
+ continue
496
+ # 2. Remove the "[N]:" marker, keeping the rest of the line
497
+ # e.g. "[1]: |||START|||" --> "|||START|||"
498
+ # e.g. "[9]: (a)" --> "(a)"
499
+ cleaned = marker_re.sub('', line)
500
+ # 3. Keep non-empty lines
501
+ if cleaned.strip():
502
+ clean_lines.append(cleaned)
503
+ # Join back into the single block of text your parser expects
504
+ return "\n".join(clean_lines)
505
+
506
+
507
+ def _robust_substitute(expr, subs_dict):
508
+ val = expr
509
+ while any(val.has(var) for var in subs_dict.keys()):
510
+ for var, sub_val in subs_dict.items():
511
+ val = val.subs(var, sub_val)
512
+ return sym.simplify(val)
513
+
514
+ def parse_singular_output(raw_output: str,
515
+ all_var_names: list[str],
516
+ inv_dummy_map: dict[str, str]) -> List[Dict[str, Any]]:
517
+ """
518
+ Parses Singular output string into a list of raw dictionaries with SymPy expressions.
519
+ Does NOT perform any solving, recursion, or filtering.
520
+ """
521
+ if "[1]:" in raw_output:
522
+ raw_output = clean_singular_string(raw_output)
523
+
524
+ if "|||START|||" not in raw_output:
525
+ # print("ERROR: Singular script did not produce expected output markers")
526
+ return []
527
+
528
+ content = raw_output.split("|||START|||")[1].split("|||END|||")[0]
529
+ raw_branches = content.split("|||BRANCH|||")[1:]
530
+
531
+ parsed_raw_branches = []
532
+
533
+ for b_text in raw_branches:
534
+ lines = b_text.strip().split("\n")
535
+ branch_data = {
536
+ 'id': int(lines[0]),
537
+ 'component': [],
538
+ 'params': [],
539
+ 'vars': [],
540
+ 'constraints': [],
541
+ 'constraint_basis': [],
542
+ 'nonnull': [],
543
+ 'basis': [],
544
+ 'num_solutions': -1, # Default to infinite if missing
545
+ 'num_constraint_solutions': -1
546
+ }
547
+
548
+ mode = None
549
+
550
+ for line in lines[1:]:
551
+ line = line.strip()
552
+ if not line: continue
553
+
554
+ # --- METADATA PARSING ---
555
+ if "|||PARAMS|||" in line:
556
+ params_str = line.replace("|||PARAMS|||", "").strip()
557
+ params = [inv_dummy_map.get(v.strip(), v.strip()) for v in params_str.split(",") if v.strip()]
558
+ branch_data['params'] = [sym.sympify(p) for p in params]
559
+ continue
560
+ if "|||VARS|||" in line:
561
+ vars_str = line.replace("|||VARS|||", "").strip()
562
+ vars = [inv_dummy_map.get(v.strip(), v.strip()) for v in vars_str.split(",") if v.strip()]
563
+ branch_data['vars'] = [sym.sympify(v) for v in vars]
564
+ continue
565
+ if "|||NUM_SOLUTIONS|||" in line:
566
+ val = line.replace("|||NUM_SOLUTIONS|||", "").strip()
567
+ if val: branch_data['num_solutions'] = int(val)
568
+ continue
569
+ if "|||NUM_CONSTRAINT_SOLUTIONS|||" in line:
570
+ val = line.replace("|||NUM_CONSTRAINT_SOLUTIONS|||", "").strip()
571
+ if val: branch_data['num_constraint_solutions'] = int(val)
572
+ continue
573
+
574
+ # --- MODE SWITCHING ---
575
+ if "|||CONSTRAINTS|||" in line: mode = "constraints"; continue
576
+ if "|||CONSTRAINT_BASIS|||" in line: mode = "constraint_basis"; continue
577
+ if "|||NONNULL|||" in line: mode = "nonnull"; continue
578
+ if "|||BASIS|||" in line: mode = "basis"; continue
579
+ if "|||COMPONENT|||" in line: mode = "component"; continue # Already handled
580
+
581
+ # --- EXPRESSION PARSING ---
582
+ # 1. Fix Powers (^ -> **)
583
+ clean_line = fix_powers(line, all_var_names)
584
+ # 2. Fix variable spacing (ac -> a*c)
585
+ # (Assumes fix_powers logic is similar or you can use your existing fix_powers)
586
+ sym_line = ""
587
+ for i in range(len(clean_line)):
588
+ ch = clean_line[i]
589
+ sym_line += inv_dummy_map.get(ch, ch)
590
+ # Check for implicit multiplication necessity
591
+ if ch in all_var_names or ch.isnumeric():
592
+ if i + 1 < len(clean_line):
593
+ next_ch = clean_line[i + 1]
594
+ if next_ch in all_var_names or next_ch == '(':
595
+ sym_line += '*'
596
+
597
+ try:
598
+ expr = sym.simplify(sym.sympify(sym_line))
599
+ if expr != 0:
600
+ branch_data[mode].append(expr)
601
+ except:
602
+ pass # logging error
603
+
604
+ parsed_raw_branches.append(branch_data)
605
+
606
+ return parsed_raw_branches
607
+
608
+
609
+ def resolve_branch_logic(branch_data: dict, original_equations: list, rational_only=False, branch_timeout=1, debug=False) -> List[Dict]:
610
+ """
611
+ Takes a raw branch dict, handles ghost constraints, solves sub-systems
612
+ (finitely or recursively), and merges the results into fully resolved branches.
613
+ """
614
+
615
+ # ---------------------------------------------------------------------
616
+ # 1. GHOST CONSTRAINT SEPARATION
617
+ # ---------------------------------------------------------------------
618
+ dep_vars_set = set(branch_data['vars'])
619
+ basis_eqs = branch_data['basis']
620
+
621
+ true_dep_eqs = []
622
+ ghost_constraints = []
623
+
624
+ for eq in basis_eqs:
625
+ # If eq involves Dependent Vars, it stays in the Basis.
626
+ if eq.free_symbols.intersection(dep_vars_set):
627
+ true_dep_eqs.append(eq)
628
+ # Otherwise, it's a constraint on the Parameters (Ghost).
629
+ else:
630
+ ghost_constraints.append(eq)
631
+
632
+ # Update the branch data to reflect this separation
633
+ branch_data['basis'] = true_dep_eqs
634
+ # Append ghosts to existing constraints list
635
+ active_constraints = branch_data['constraints'] + ghost_constraints
636
+
637
+ # ---------------------------------------------------------------------
638
+ # 2. SOLVE CONSTRAINTS (Recursive & Filtered)
639
+ # ---------------------------------------------------------------------
640
+ # We will store results as "Branch Objects" to preserve metadata
641
+ # (constraints, basis) from recursive calls.
642
+ param_branches = []
643
+
644
+ # A. Trivial Case (No constraints)
645
+ if not active_constraints:
646
+ # Returns one "empty" branch context
647
+ param_branches = [{'mapping': {}, 'constraints': [], 'basis': []}]
648
+
649
+ # B. Finite Case (SymPy Solve)
650
+ elif branch_data.get('num_constraint_solutions', -1) > 0:
651
+ eqs_to_solve = branch_data['constraint_basis']
652
+ # Identify which parameters are actually involved
653
+ vars_to_solve = [v for v in branch_data['params']
654
+ if any(v in eq.free_symbols for eq in eqs_to_solve)]
655
+
656
+
657
+ # Convert s to m for timeout
658
+ raw_sols = utils.run_with_timeout(solve_0D_backsub,
659
+ (eqs_to_solve, vars_to_solve, None, rational_only, debug), timeout=branch_timeout/60)
660
+ if raw_sols is None:
661
+ print(f"Warning: Constraint solving timed out after {branch_timeout} seconds. Skipping this branch.")
662
+ return []
663
+
664
+ # NONNULL FILTER
665
+ nonnull_exprs = branch_data.get('nonnull', [])
666
+ for sol in raw_sols:
667
+ is_valid = True
668
+ for nk in nonnull_exprs:
669
+ if nk.subs(sol).simplify() == 0:
670
+ is_valid = False
671
+ break
672
+ if is_valid:
673
+ # Wrap the mapping in a standardized Branch Object
674
+ param_branches.append({
675
+ 'mapping': sol,
676
+ 'constraints': branch_data["constraints"],
677
+ 'basis': []
678
+ })
679
+
680
+ # C. Infinite Case (Recursive Singular Call)
681
+ else:
682
+ # Recursively solve the constraint system.
683
+ # This returns a list of full branch dictionaries.
684
+ # We pass 'params' as the variables to solve for.
685
+ param_branches = solve_with_singular(active_constraints, solve_vars=branch_data['params'],
686
+ check_fraction=False, rational_only=rational_only, debug=debug)
687
+
688
+ # ---------------------------------------------------------------------
689
+ # 3. SOLVE DEPENDENT VARIABLES (Triangular)
690
+ # ---------------------------------------------------------------------
691
+ dep_branches = []
692
+ dep_eqs = branch_data['basis']
693
+ dep_vars = branch_data['vars']
694
+
695
+ if not dep_eqs:
696
+ dep_branches = [{'mapping': {}, 'constraints': [], 'basis': []}]
697
+ else:
698
+ # B. Finite Case
699
+ if branch_data['num_solutions'] != -1:
700
+ raw_dep_sols = utils.run_with_timeout(solve_0D_backsub,
701
+ (dep_eqs, dep_vars, branch_data["params"], rational_only, debug), timeout=branch_timeout/60)
702
+ if raw_dep_sols is None:
703
+ print(f"Warning: Dependent variable solving timed out after {branch_timeout} seconds. Skipping this branch.")
704
+ return []
705
+ for sol in raw_dep_sols:
706
+ dep_branches.append({
707
+ 'mapping': sol,
708
+ 'constraints': [],
709
+ 'basis': dep_eqs
710
+ })
711
+
712
+ # C. Infinite Case (Recursive Singular Call)
713
+ else:
714
+ # Recursively solve the dependent system.
715
+ dep_branches = solve_with_singular(dep_eqs, solve_vars=dep_vars, check_fraction=False,
716
+ rational_only=rational_only, debug=debug)
717
+
718
+ # ---------------------------------------------------------------------
719
+ # 4. COMBINE and MERGE BRANCHES
720
+ # ---------------------------------------------------------------------
721
+ resolved_branches = []
722
+
723
+ # Cartesian Product of Parameter Branches * Dependent Branches
724
+ # Now we are merging Objects, not just mappings.
725
+ count = 0
726
+ for p_br, d_br in itertools.product(param_branches, dep_branches):
727
+
728
+ # A. Merge Mappings
729
+ combined_mapping = {**p_br.get('mapping', {}), **d_br.get('mapping', {})}
730
+
731
+ # B. Merge Constraints
732
+ # We accumulate any 'residue' constraints returned by the recursive calls
733
+ combined_constraints = (
734
+ p_br.get('constraints', []) +
735
+ d_br.get('constraints', [])
736
+ )
737
+
738
+ # C. Merge Basis
739
+ combined_basis = (
740
+ p_br.get('basis', []) +
741
+ d_br.get('basis', [])
742
+ )
743
+
744
+ new_br = branch_data.copy()
745
+
746
+ new_br['id'] = f"{branch_data['id']}.{count}"
747
+ count += 1
748
+ new_br['mapping'] = combined_mapping
749
+ new_br['constraints'] = combined_constraints # Preserve recursive constraints
750
+ new_br['basis'] = combined_basis
751
+
752
+ # Recalculate Free Vars/Params based on what ended up in the mapping
753
+ new_br['free_vars'] = [v for v in dep_vars if v not in combined_mapping]
754
+ new_br['free_params'] = [v for v in branch_data['params'] if v not in combined_mapping]
755
+
756
+ resolved_branches.append(new_br)
757
+
758
+ return resolved_branches
759
+
760
+
761
+ def make_dummy_map(var_list: List[sym.Symbol]):
762
+ # Sort variables by name to ensure consistent mapping
763
+ var_list = sorted(var_list, key=lambda x: str(x))
764
+ dummy_map = {}
765
+ inv_dummy_map = {}
766
+ # Identify any variables that are single lowercase letters or uppercase letters
767
+ for s in var_list:
768
+ if re.fullmatch(r'[a-z]', str(s)):
769
+ dummy_map[str(s)] = str(s)
770
+ inv_dummy_map[str(s)] = str(s)
771
+ elif re.fullmatch(r'[A-Z]', str(s)):
772
+ dummy_map[str(s)] = str(s)
773
+ inv_dummy_map[str(s)] = str(s)
774
+ # Dummy substitutions to avoid Singular parsing issues
775
+ ord_val = 97 # ASCII 'a'
776
+ for s in var_list:
777
+ if str(s) in dummy_map:
778
+ continue # Already assigned
779
+ # skip e
780
+ if chr(ord_val) in ['e', 'i', 'E', 'I']:
781
+ ord_val += 1
782
+ if ord_val > 122: # ASCII 'z'
783
+ ord_val = 65 # ASCII 'A'
784
+ if ord_val == 91: # One past 'Z'
785
+ print("ERROR: Too many variables for dummy substitution")
786
+ print(len(var_list), "variables provided.\n", var_list)
787
+ print(dummy_map)
788
+ raise ValueError("Too many variables for dummy substitution (max 48)")
789
+ dummy_map[str(s)] = chr(ord_val)
790
+ inv_dummy_map[chr(ord_val)] = str(s)
791
+ ord_val += 1
792
+ return dummy_map, inv_dummy_map
793
+
794
+
795
+ def check_branch_validity(branch, original_eqs, eps=1e-12):
796
+ # Simple check to ensure we don't return garbage
797
+ mapping = branch['mapping']
798
+ for eq in original_eqs:
799
+ val = sym.simplify(_robust_substitute(eq, mapping))
800
+ failed = True
801
+ if len(val.free_symbols) == 0:
802
+ if abs(val) < eps:
803
+ failed = False
804
+ if failed:
805
+ print(f"Branch {branch['id']} failed validity check on equation {eq} with mapping {mapping}")
806
+ print(f"Result: {_robust_substitute(eq, mapping)}")
807
+ return False
808
+ return True
809
+
810
+
811
+ def filter_redundant_branches(branches, verbose=False):
812
+ """
813
+ Filters branches assuming they have been flattened (1 mapping per branch).
814
+ """
815
+
816
+ def is_subset(branch_spec, branch_gen):
817
+ # 1. SETUP MAP
818
+ if 'mapping' not in branch_spec: return False
819
+ spec_map = branch_spec['mapping'].copy()
820
+
821
+ # Augment with basis
822
+ for eq in branch_spec.get('basis', []):
823
+ if isinstance(eq, sym.Symbol): spec_map[eq] = 0
824
+
825
+ # 2. BASIS CHECK
826
+ for eq in branch_gen.get('basis', []):
827
+ if eq.subs(spec_map).simplify() != 0: return False
828
+
829
+ # 3. HOLE CHECK
830
+ for constr in branch_gen.get('nonnull', []):
831
+ if constr == 1: continue
832
+ if constr.subs(spec_map).simplify() == 0: return False
833
+
834
+ # 4. MAPPING CHECK
835
+ if branch_gen.get('mapping'):
836
+ gen_map = branch_gen['mapping']
837
+ for lhs, rhs in gen_map.items():
838
+ if (lhs - rhs).subs(spec_map).simplify() != 0:
839
+ return False
840
+ return True
841
+
842
+ to_remove_ids = set()
843
+ for i, b_spec in enumerate(branches):
844
+ if b_spec['id'] in to_remove_ids: continue
845
+ for j, b_gen in enumerate(branches):
846
+ if i == j: continue
847
+ if b_gen['id'] in to_remove_ids: continue
848
+
849
+ if is_subset(b_spec, b_gen):
850
+ if verbose: print(f"Removing {b_spec['id']} (Subset of {b_gen['id']})")
851
+ to_remove_ids.add(b_spec['id'])
852
+ break
853
+
854
+ to_keep = [b for b in branches if b['id'] not in to_remove_ids]
855
+ # sort by ID
856
+ to_keep.sort(key=lambda b: float(b['id']))
857
+ return to_keep
858
+
859
+
860
+ # =========================================
861
+ # EXAMPLE USAGE
862
+ # =========================================
863
+ if __name__ == "__main__":
864
+ a, b, x, y = sym.symbols('a b x y')
865
+
866
+ # Test 1: Auto-discover structure (no solve_vars specified)
867
+ print("=== Test 1: ax = b (auto-discover) ===")
868
+ eqs = [a*x - b]
869
+ branches = solve_with_singular(eqs)
870
+ print(f"Found {len(branches)} Branches:")
871
+ for br in branches:
872
+ print(br)
873
+ # Test 2: Explicitly specify solve_vars (a, b are parameters)
874
+ print("\n=== Test 2: ax = b (solve for x, treat a,b as params) ===")
875
+ eqs = [a*x - b]
876
+ branches = solve_with_singular(eqs, solve_vars=[x])
877
+ print(f"Found {len(branches)} Branches:")
878
+ for br in branches:
879
+ print(br)
880
+ # Test 3: Two equations with explicit solve_vars
881
+ print("\n=== Test 3: x^2 + y = a, a*x = b (solve for x,y) ===")
882
+ eqs = [x**2 + y - a, a*x - b]
883
+ branches = solve_with_singular(eqs, solve_vars=[x, y])
884
+ print(f"Found {len(branches)} Branches:")
885
+ for br in branches:
886
+ print(br)
887
+
888
+
889
+ def _eq_as_numer_denom(eq: Union[sym.Eq, sym.Expr]):
890
+ """Extract numerator and denominator from equation or expression.
891
+
892
+ Parameters
893
+ ----------
894
+ eq : sym.Eq or sym.Expr
895
+ Equation or expression to decompose.
896
+
897
+ Returns
898
+ -------
899
+ tuple[sym.Expr, sym.Expr]
900
+ Numerator and denominator after combining fractions.
901
+ """
902
+ if isinstance(eq, sym.Eq):
903
+ eq = (eq.lhs - eq.rhs)
904
+ if isinstance(eq, int) or isinstance(eq, float):
905
+ eq = sym.sympify(eq)
906
+ # Combine fractions -- quick
907
+ numer, denom = eq.as_numer_denom()
908
+ if numer.as_numer_denom()[1] != 1 and denom.as_numer_denom()[1] != 1:
909
+ # More complex fractions present
910
+ eq_new = sym.expand(eq).together(deep=True)
911
+ numer, denom = eq_new.as_numer_denom()
912
+ return numer, denom
913
+
914
+
915
+ def initialize_singular():
916
+ """
917
+ Called once per worker to initialize a fresh singular interface
918
+ """
919
+ # Sage's process spawner tries to flush stdout, but multiprocessing
920
+ # workers on macOS often have sys.stdout set to None.
921
+ # Assign it to /dev/null to prevent an AttributeError.
922
+ # if sys.stdout is None:
923
+ # sys.stdout = open(os.devnull, 'w')
924
+ # if sys.stderr is None:
925
+ # sys.stderr = open(os.devnull, 'w')
926
+ lib_path = Path(__file__).with_name("poly_solver.sing")
927
+ startup_code = ""
928
+ startup_code += f'LIB "{str(lib_path)}";\n'
929
+ startup_code += "ring SUPER_RING = 0, (a,b,c,d,f,g,h,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,F,G,H,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z), dp;\n"
930
+ # startup_code += "option(prot);"
931
+ global WORKER_SINGULAR
932
+ WORKER_SINGULAR = SafeSingular(startup_code=startup_code, binary_path=SINGULAR_PATH, timeout=100)
933
+
934
+
935
+
936
+ class SafeSingular:
937
+ def __init__(self, startup_code="", binary_path=SINGULAR_PATH, timeout=100):
938
+ self.binary_path = binary_path
939
+ self.startup_code = startup_code
940
+ self.timeout = timeout
941
+ self.process = None
942
+
943
+ def start(self):
944
+ """Launches process and runs startup code."""
945
+ self.process = subprocess.Popen(
946
+ [self.binary_path, "--no-tty", "--quiet"],
947
+ stdin=subprocess.PIPE,
948
+ stdout=subprocess.PIPE,
949
+ stderr=subprocess.PIPE,
950
+ text=True,
951
+ start_new_session=True, # Critical for killing process tree
952
+ bufsize=1
953
+ )
954
+
955
+ # Immediately run the startup code if it exists
956
+ if self.startup_code:
957
+ try:
958
+ self.eval(self.startup_code)
959
+ except (TimeoutError, RuntimeError):
960
+ print("Startup code failed! Killing process.")
961
+ self.kill()
962
+ raise
963
+
964
+ def eval(self, cmd, timeout=None, debug=False):
965
+ """
966
+ Public method: Ensures process exists, then runs command.
967
+ """
968
+ # Auto-restart if dead
969
+ if self.process is None:
970
+ self.start()
971
+ # if debug:
972
+ # print("Executing Singular Command:", cmd)
973
+ out = self._execute_raw(cmd, timeout)
974
+ # if debug:
975
+ # print("done.\n", out)
976
+ if "error" in out.lower():
977
+ raise RuntimeError(f"Singular Error:\n{out}")
978
+ return out
979
+
980
+ def _execute_raw(self, cmd, timeout):
981
+
982
+
983
+ if timeout is None:
984
+ timeout = self.timeout
985
+ # Unique sentinel to mark end of command
986
+ sentinel = "___CMD_DONE___"
987
+
988
+ # Ensure command ends with newline and forces a flush
989
+ if not cmd.strip().endswith(";"):
990
+ cmd += ";"
991
+ full_cmd = f"{cmd};\nprint('{sentinel}');\nprint('');\n"
992
+
993
+ if self.process.poll() is not None:
994
+ self.process = None
995
+ raise RuntimeError("Singular process is dead.")
996
+
997
+ # Write command
998
+ try:
999
+ self.process.stdin.write(full_cmd)
1000
+ self.process.stdin.flush()
1001
+ except (BrokenPipeError, AttributeError):
1002
+ self.kill()
1003
+ raise RuntimeError("Singular process died unexpectedly.")
1004
+
1005
+ output_buffer = ""
1006
+ start_time = time.time()
1007
+
1008
+ # Get file descriptor for low-level read
1009
+ fd = self.process.stdout.fileno()
1010
+
1011
+ while True:
1012
+ # Calculate timeout
1013
+ if timeout:
1014
+ remaining = timeout - (time.time() - start_time)
1015
+ if remaining <= 0:
1016
+ self.kill()
1017
+ raise TimeoutError(f"Singular timed out after {timeout} seconds")
1018
+ else:
1019
+ remaining = None
1020
+
1021
+ # Select waits for DATA, not LINES.
1022
+ ready, _, _ = select.select([self.process.stdout], [], [], remaining)
1023
+
1024
+ if ready:
1025
+ # RAW READ: Read up to 1024 bytes.
1026
+ # This returns '1' or '.' immediately without waiting for \n
1027
+ chunk = os.read(fd, 1024).decode('utf-8', errors='replace')
1028
+
1029
+ if not chunk: # EOF
1030
+ self.kill()
1031
+ raise RuntimeError("Singular process closed connection.")
1032
+
1033
+ output_buffer += chunk
1034
+
1035
+ # Check for Soft Errors
1036
+ if "?" in chunk and "error" in chunk.lower():
1037
+ # Simple heuristic: if we see "? ... error", abort
1038
+ pass
1039
+
1040
+ # Check for sentinel
1041
+ if sentinel in output_buffer:
1042
+ break
1043
+ else:
1044
+ self.kill()
1045
+ raise TimeoutError("Singular timed out")
1046
+
1047
+ return output_buffer.replace(sentinel, "").strip()
1048
+
1049
+ def _wait_for_prompt(self, timeout):
1050
+ """Consumes initial banner/prompt output."""
1051
+ start = time.time()
1052
+ fd = self.process.stdout.fileno()
1053
+ buf = ""
1054
+ while (time.time() - start) < timeout:
1055
+ r, _, _ = select.select([self.process.stdout], [], [], 0.1)
1056
+ if r:
1057
+ chunk = os.read(fd, 1024).decode('utf-8')
1058
+ buf += chunk
1059
+ # Singular prompt is usually ">"
1060
+ if ">" in buf:
1061
+ return
1062
+ # If we time out, we assume it's silent and ready
1063
+ return
1064
+
1065
+ def kill(self):
1066
+ """Force kills the process group and resets state."""
1067
+ if self.process:
1068
+ pgid = os.getpgid(self.process.pid)
1069
+ os.killpg(pgid, signal.SIGKILL)
1070
+ self.process.wait()
1071
+ self.process = None