| """ |
| Batch Processor Module |
| Processes geometry problems and generates visualizations. |
| """ |
|
|
| import torch |
| import numpy as np |
| import matplotlib.pyplot as plt |
| from matplotlib.lines import Line2D |
| import json |
| import re |
| from pathlib import Path |
| from typing import Dict, List, Tuple, Optional |
| from tqdm import tqdm |
|
|
| from .primitives import ( |
| CircleSDF, EllipseSDF, HyperbolaSDF, ParabolaSDF |
| ) |
| from .constraints import GeometricConstraints |
| from .parser import ProblemParser |
| from .optimizer import GeometryOptimizer |
| from .renderer import SDFRenderer |
|
|
|
|
| class SDFBatchProcessor: |
| """ |
| Process problems using the SDF methodology. |
| """ |
| |
| def __init__(self, output_dir: str = 'sdf_output'): |
| self.output_dir = Path(output_dir) |
| self.output_dir.mkdir(exist_ok=True, parents=True) |
| |
| self.parser = ProblemParser() |
| self.optimizer = GeometryOptimizer() |
| |
| |
| for subdir in ['ellipse', 'hyperbola', 'parabola', 'circle']: |
| (self.output_dir / subdir).mkdir(exist_ok=True) |
| |
| def process_problem(self, problem: Dict, idx: int, verbose: bool = False) -> Dict: |
| """Process a single problem using SDF methodology.""" |
| result = { |
| 'index': idx, |
| 'success': False, |
| 'error': None |
| } |
| |
| try: |
| fact_expr = problem.get('fact_expressions', '') |
| text = problem.get('text', '') |
| query_expr = problem.get('query_expressions', '') |
| |
| |
| |
| primary_shape = None |
| query_match = re.search(r'Expression\((\w+)\)', query_expr) |
| if query_match: |
| shape_name = query_match.group(1) |
| |
| type_match = re.search(rf'{shape_name}:\s*(\w+)', fact_expr) |
| if type_match: |
| primary_shape = type_match.group(1).lower() |
| |
| |
| main_hyperbola_name = self._detect_main_conic_name(fact_expr, 'hyperbola') |
| main_ellipse_name = self._detect_main_conic_name(fact_expr, 'ellipse') |
| main_parabola_name = self._detect_main_conic_name(fact_expr, 'parabola') |
| main_circle_name = self._detect_main_conic_name(fact_expr, 'circle') |
| |
| |
| ellipse_params = self.parser.parse_ellipse(fact_expr) |
| hyperbola_params = self.parser.parse_hyperbola(fact_expr, main_hyperbola_name) |
| parabola_params = self.parser.parse_parabola(fact_expr) |
| circle_params = self.parser.parse_circle(fact_expr) |
| |
| |
| coords = self.parser.parse_coordinates(fact_expr) |
| eccentricity = self.parser.parse_eccentricity(fact_expr) |
| asymptote = self.parser.parse_asymptote_slope(fact_expr) |
| |
| |
| moving_circle = self._detect_moving_circle_locus(fact_expr, coords) |
| if moving_circle: |
| params_hyp = moving_circle |
| return self._process_hyperbola(problem, idx, params_hyp, coords, eccentricity=None, asymptote=None, verbose=verbose) |
| |
| |
| if primary_shape == 'hyperbola' and hyperbola_params: |
| result = self._process_hyperbola(problem, idx, hyperbola_params, coords, eccentricity, asymptote, verbose) |
| elif primary_shape == 'ellipse' and ellipse_params: |
| result = self._process_ellipse(problem, idx, ellipse_params, coords, eccentricity, verbose) |
| elif primary_shape == 'parabola' and parabola_params: |
| result = self._process_parabola(problem, idx, parabola_params, coords, verbose) |
| elif primary_shape == 'circle' and circle_params: |
| result = self._process_circle(problem, idx, circle_params, coords, verbose) |
| |
| |
| elif hyperbola_params: |
| result = self._process_hyperbola(problem, idx, hyperbola_params, coords, eccentricity, asymptote, verbose) |
| elif ellipse_params: |
| result = self._process_ellipse(problem, idx, ellipse_params, coords, eccentricity, verbose) |
| elif parabola_params: |
| result = self._process_parabola(problem, idx, parabola_params, coords, verbose) |
| elif circle_params: |
| result = self._process_circle(problem, idx, circle_params, coords, verbose) |
| else: |
| result['error'] = 'Unsupported or unparseable expression' |
| return result |
| |
| |
| result = self._validate_result(result, problem) |
| return result |
| |
| except Exception as e: |
| result['error'] = str(e) |
| return result |
| |
| def _validate_result(self, result: Dict, problem: Dict) -> Dict: |
| """ |
| Rigorous validation following paper-quality standards. |
| Validates all explicit geometric constraints from the problem. |
| |
| Validation includes: |
| - Parameter positivity (a, b, p, r > 0) |
| - Eccentricity matching (e_calc vs e_target) |
| - Asymptote slope matching (b/a vs target slope) |
| - Focus position verification (c² = a² ± b²) |
| - Point-on-curve verification for constrained points |
| - Directrix position verification (parabola) |
| """ |
| if not result.get('success'): |
| return result |
| |
| conic_type = result.get('conic_type') |
| fact_expr = result.get('fact_expr', problem.get('fact_expressions', '')) |
| coords = result.get('coords', {}) |
| reasons = [] |
| |
| |
| tol_point = 3e-2 |
| tol_param = 0.05 |
| tol_focus = 0.05 |
| |
| |
| main_conic = self._detect_main_conic_name(fact_expr, conic_type) |
| |
| |
| points_on_main = self._points_on_main_conic(fact_expr, coords, main_conic) |
| |
| |
| def get_focus_coords() -> List[Tuple[float, float]]: |
| """Extract focus point coordinates.""" |
| foci = [] |
| for name, coord in coords.items(): |
| |
| if re.search(rf'Focus\s*\(\s*{main_conic}\s*\)\s*=\s*\{{\s*{name}', fact_expr) or \ |
| re.search(rf'Focus\s*\(\s*{main_conic}\s*\)\s*=\s*{name}', fact_expr) or \ |
| (name in ['F', 'F1', 'F2'] and re.search(rf'Focus\s*\(\s*{main_conic}\s*\)', fact_expr)): |
| foci.append(coord) |
| return foci |
| |
| |
| def has_point_constraint(name: str) -> bool: |
| return name in points_on_main |
| |
| if conic_type == 'ellipse': |
| params = result.get('params', {}) |
| if 'a' not in params or 'b' not in params: |
| return result |
| a = params['a'] |
| b = params['b'] |
| |
| |
| if a <= 0 or b <= 0: |
| reasons.append('ellipse_nonpositive_axes') |
| |
| |
| ecc_target = self.parser.parse_eccentricity(fact_expr) |
| if ecc_target and 0 < ecc_target < 1: |
| a_major, b_minor = max(a, b), min(a, b) |
| ecc_calc = np.sqrt(1 - (b_minor / a_major)**2) |
| if abs(ecc_calc - ecc_target) > tol_param: |
| reasons.append('ellipse_ecc_mismatch') |
| |
| |
| foci = get_focus_coords() |
| if foci: |
| a_major, b_minor = max(a, b), min(a, b) |
| c_calc = np.sqrt(max(0, a_major**2 - b_minor**2)) |
| for fx, fy in foci: |
| |
| c_given = np.sqrt(fx**2 + fy**2) |
| if abs(c_calc - c_given) > tol_focus: |
| reasons.append('ellipse_focus_mismatch') |
| break |
| |
| |
| for name, (px, py) in coords.items(): |
| if has_point_constraint(name): |
| major_axis = params.get('major_axis', 'x') |
| if major_axis == 'x': |
| val = (px**2) / (a**2) + (py**2) / (b**2) - 1 |
| else: |
| val = (px**2) / (b**2) + (py**2) / (a**2) - 1 |
| if abs(val) > tol_point: |
| reasons.append('ellipse_point_off_curve') |
| break |
| |
| elif conic_type == 'hyperbola': |
| params = result.get('params', {}) |
| if 'a' not in params or 'b' not in params: |
| return result |
| a = params['a'] |
| b = params['b'] |
| orientation = params.get('orientation', 'horizontal') |
| |
| |
| if a <= 0 or b <= 0: |
| reasons.append('hyperbola_nonpositive_axes') |
| |
| |
| asym = self.parser.parse_asymptote_slope(fact_expr) |
| if asym: |
| slope_calc = b / a if orientation == 'horizontal' else a / b |
| if abs(slope_calc - asym) > tol_param: |
| reasons.append('hyperbola_asymptote_mismatch') |
| |
| |
| ecc_target = self.parser.parse_eccentricity(fact_expr) |
| if ecc_target and ecc_target > 1: |
| ecc_calc = np.sqrt(1 + (b / a)**2) |
| if abs(ecc_calc - ecc_target) > tol_param: |
| reasons.append('hyperbola_ecc_mismatch') |
| |
| |
| foci = get_focus_coords() |
| if foci: |
| c_calc = np.sqrt(a**2 + b**2) |
| for fx, fy in foci: |
| |
| c_given = np.sqrt(fx**2 + fy**2) |
| if abs(c_calc - c_given) > tol_focus: |
| reasons.append('hyperbola_focus_mismatch') |
| break |
| |
| |
| for name, (px, py) in coords.items(): |
| if has_point_constraint(name): |
| if orientation == 'vertical': |
| val = (py**2) / (a**2) - (px**2) / (b**2) - 1 |
| else: |
| val = (px**2) / (a**2) - (py**2) / (b**2) - 1 |
| if abs(val) > tol_point: |
| reasons.append('hyperbola_point_off_curve') |
| break |
| |
| elif conic_type == 'parabola': |
| params = result.get('params', {}) |
| p = params.get('p', 0) |
| direction = params.get('direction', 'right') |
| |
| |
| if p <= 0: |
| reasons.append('parabola_nonpositive_p') |
| |
| |
| |
| foci = get_focus_coords() |
| if foci: |
| for fx, fy in foci: |
| if direction == 'right': |
| focus_expected = (p, 0) |
| elif direction == 'left': |
| focus_expected = (-p, 0) |
| elif direction == 'up': |
| focus_expected = (0, p) |
| else: |
| focus_expected = (0, -p) |
| |
| dist = np.sqrt((fx - focus_expected[0])**2 + (fy - focus_expected[1])**2) |
| if dist > tol_focus: |
| reasons.append('parabola_focus_mismatch') |
| break |
| |
| |
| |
| directrix_match = re.search(r'Directrix\s*\(\s*\w+\s*\)\s*=\s*\(x\s*=\s*(-?\d+\.?\d*)\)', fact_expr) |
| if directrix_match: |
| directrix_given = float(directrix_match.group(1)) |
| if direction == 'right': |
| directrix_expected = -p |
| elif direction == 'left': |
| directrix_expected = p |
| else: |
| directrix_expected = None |
| |
| if directrix_expected is not None: |
| if abs(directrix_given - directrix_expected) > tol_focus: |
| reasons.append('parabola_directrix_mismatch') |
| |
| |
| for name, (px, py) in coords.items(): |
| if has_point_constraint(name): |
| if direction == 'right': |
| val = py**2 - 4 * p * px |
| elif direction == 'left': |
| val = py**2 + 4 * p * px |
| elif direction == 'up': |
| val = px**2 - 4 * p * py |
| else: |
| val = px**2 + 4 * p * py |
| if abs(val) > tol_point: |
| reasons.append('parabola_point_off_curve') |
| break |
| |
| elif conic_type == 'circle': |
| params = result.get('params', {}) |
| r = params.get('radius', 0) |
| cx, cy = params.get('center', (0, 0)) |
| |
| |
| if r <= 0: |
| reasons.append('circle_nonpositive_radius') |
| |
| |
| center_match = re.search(r'Center\s*\(\s*\w+\s*\)\s*=\s*\(([^,]+),\s*([^)]+)\)', fact_expr) |
| if center_match: |
| try: |
| cx_given = float(center_match.group(1)) |
| cy_given = float(center_match.group(2)) |
| if abs(cx - cx_given) > tol_focus or abs(cy - cy_given) > tol_focus: |
| reasons.append('circle_center_mismatch') |
| except: |
| pass |
| |
| |
| radius_match = re.search(r'Radius\s*\(\s*\w+\s*\)\s*=\s*(\d+\.?\d*)', fact_expr) |
| if radius_match: |
| r_given = float(radius_match.group(1)) |
| if abs(r - r_given) > tol_focus: |
| reasons.append('circle_radius_mismatch') |
| |
| |
| for name, (px, py) in coords.items(): |
| if has_point_constraint(name): |
| val = (px - cx)**2 + (py - cy)**2 - r**2 |
| if abs(val) > tol_point: |
| reasons.append('circle_point_off_curve') |
| break |
| |
| if reasons: |
| result['success'] = False |
| result['error'] = 'validation: ' + ';'.join(reasons) |
| result['validation_reasons'] = reasons |
| return result |
|
|
| def _point_constraint_names(self, fact_expr: str, coords: Dict, conic_type: str = 'parabola') -> set: |
| """ |
| Collect point names that are explicitly constrained on the main curve. |
| Uses _detect_main_conic_name to find the actual conic variable name. |
| """ |
| main_conic = self._detect_main_conic_name(fact_expr, conic_type) |
| return self._points_on_main_conic(fact_expr, coords, main_conic) |
| |
| def _detect_main_conic_name(self, fact_expr: str, conic_type: str) -> str: |
| """ |
| Detect the actual name of the main conic from fact_expr. |
| |
| Patterns like 'G: Ellipse', 'C: Parabola', 'C: Hyperbola', etc. |
| Returns the variable name (e.g., 'G' or 'C'). |
| """ |
| |
| type_map = { |
| 'ellipse': 'Ellipse', |
| 'hyperbola': 'Hyperbola', |
| 'parabola': 'Parabola', |
| 'circle': 'Circle' |
| } |
| type_name = type_map.get(conic_type, '') |
| |
| if type_name: |
| |
| pattern = rf'(\w+)\s*:\s*{type_name}' |
| match = re.search(pattern, fact_expr) |
| if match: |
| return match.group(1) |
| |
| |
| return 'C' if conic_type == 'circle' else 'G' |
| |
| def _points_on_main_conic(self, fact_expr: str, coords: Dict, conic_name: str = 'G') -> set: |
| """ |
| Collect point names that are EXPLICITLY on the MAIN conic (e.g., G or C). |
| |
| Includes: |
| - PointOnCurve(<name>, G) where G is the main conic |
| - Intersection(*, G) = {A, B} where G is the main conic |
| |
| Excludes: |
| - PointOnCurve(<name>, H) where H is a line |
| - PointOnCurve(<name>, Asymptote(G)) - on asymptote, not curve |
| - PointOnCurve(<name>, Directrix(G)) - on directrix, not curve |
| - PointOnCurve(<name>, G1) where G1 is a different curve |
| - MidPoint constraints (midpoints of chords are not on the curve) |
| """ |
| names = set() |
| |
| |
| |
| for name in coords.keys(): |
| |
| |
| pattern = rf'PointOnCurve\(\s*{re.escape(name)}\s*,\s*{re.escape(conic_name)}\s*\)' |
| if re.search(pattern, fact_expr): |
| names.add(name) |
| |
| |
| |
| inter_pattern = r'Intersection\(\s*([^,)]+)\s*,\s*([^)]+)\s*\)\s*=\s*\{([^}]+)\}' |
| for m in re.finditer(inter_pattern, fact_expr): |
| arg1 = m.group(1).strip() |
| arg2 = m.group(2).strip() |
| points_str = m.group(3) |
| |
| |
| if arg1 == conic_name or arg2 == conic_name: |
| for p in points_str.split(','): |
| p = p.strip() |
| if p in coords: |
| names.add(p) |
| |
| return names |
|
|
| def _detect_moving_circle_locus(self, fact_expr: str, coords: Dict) -> Optional[Dict]: |
| """ |
| Detect pattern: moving circle through fixed point A, externally tangent to fixed circle C. |
| If foci on x-axis, convert to hyperbola params: |PC| - |PA| = R -> 2a = R. |
| Returns hyperbola params dict or None. |
| """ |
| if "IsOutTangent" not in fact_expr: |
| return None |
| |
| patterns = [ |
| r'Expression\(C\)\s*=\s*\(y\^2\s*\+\s*\(x\s*([+-])\s*(\d+\.?\d*)\)\^2\s*=\s*(\d+\.?\d*)\)', |
| r'Expression\(C\)\s*=\s*\(\(x\s*([+-])\s*(\d+\.?\d*)\)\^2\s*\+\s*y\^2\s*=\s*(\d+\.?\d*)\)' |
| ] |
| cx = cy = R = None |
| for pat in patterns: |
| m = re.search(pat, fact_expr) |
| if m: |
| sign = m.group(1) |
| val = float(m.group(2)) |
| cx = -val if sign == '+' else val |
| cy = 0.0 |
| R = np.sqrt(float(m.group(3))) |
| break |
| if R is None or R <= 0: |
| return None |
| |
| if 'A' in coords: |
| ax, ay = coords['A'] |
| elif coords: |
| ax, ay = next(iter(coords.values())) |
| else: |
| return None |
| |
| if abs(ay) > 1e-6 or abs(cy) > 1e-6: |
| return None |
| c = abs(cx - ax) / 2 |
| if c <= 0: |
| return None |
| a = R / 2 |
| if a <= 0 or c <= a: |
| return None |
| b_sq = c * c - a * a |
| b = np.sqrt(b_sq) |
| return {'a': a, 'b': b} |
| |
| def _process_ellipse(self, problem: Dict, idx: int, params: Dict, |
| coords: Dict, eccentricity: Optional[float], verbose: bool) -> Dict: |
| """Process ellipse problem with SDF optimization.""" |
| |
| fact_expr = problem.get('fact_expressions', '') |
| point_names = self._point_constraint_names(fact_expr, coords, 'ellipse') |
| |
| center = torch.tensor([0.0, 0.0]) |
| |
| if 'a' not in params or 'b' not in params: |
| return { |
| 'index': idx, |
| 'success': False, |
| 'error': f"Ellipse params missing 'a' or 'b': {list(params.keys())}" |
| } |
| a = torch.tensor([params['a']]) |
| b = torch.tensor([params['b']]) |
| |
| sdf = EllipseSDF(center, a, b) |
| |
| |
| has_explicit_coeffs = not params.get('symbolic', False) and not params.get('from_constraints', False) |
| |
| |
| |
| should_optimize = False |
| constraints = [] |
| weights = [] |
| |
| if not has_explicit_coeffs: |
| |
| if eccentricity and eccentricity < 1: |
| constraints.append(lambda: GeometricConstraints.eccentricity_ellipse( |
| sdf.a, sdf.b, eccentricity |
| )) |
| weights.append(10.0) |
| should_optimize = True |
| |
| |
| all_positions = [sdf.center] |
| |
| |
| for name, (px, py) in coords.items(): |
| if name in point_names and name not in ['F1', 'F2', 'F', 'O']: |
| point = torch.tensor([px, py]) |
| constraints.append(lambda p=point: GeometricConstraints.point_on_curve(sdf, p)) |
| weights.append(5.0) |
| should_optimize = True |
| all_positions.append(point) |
| |
| |
| |
| if len(all_positions) > 1: |
| constraints.append(lambda pos=all_positions: GeometricConstraints.crowd_penalty(pos, min_dist=0.5)) |
| weights.append(3.0) |
| |
| |
| constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.a)) |
| constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.b)) |
| weights.extend([1.0, 1.0]) |
| |
| |
| if should_optimize and len(constraints) > 2: |
| opt_result = self.optimizer.optimize(sdf, constraints, weights, verbose) |
| |
| |
| with torch.no_grad(): |
| a_opt = abs(sdf.a.item()) |
| b_opt = abs(sdf.b.item()) |
| |
| |
| if b_opt < 0.1 or a_opt < 0.1: |
| sdf.a.data = torch.tensor([params['a']]) |
| sdf.b.data = torch.tensor([params['b']]) |
| opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'reverted to explicit params'} |
| else: |
| opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'using explicit params'} |
| |
| |
| with torch.no_grad(): |
| a_final = abs(sdf.a.item()) |
| b_final = abs(sdf.b.item()) |
| |
| |
| major_axis = params.get('major_axis', 'x') |
| |
| |
| output_path = self.output_dir / 'ellipse' / f'problem_{idx:04d}.png' |
| self._visualize_ellipse(sdf, problem, params, output_path, major_axis) |
| |
| return { |
| 'index': idx, |
| 'success': True, |
| 'conic_type': 'ellipse', |
| 'error': None, |
| 'params': { |
| 'a': a_final, |
| 'b': b_final, |
| 'major_axis': major_axis, |
| 'x_coef': params['x_coef'], |
| 'y_coef': params['y_coef'] |
| }, |
| 'optimization': opt_result, |
| 'output_path': str(output_path), |
| 'answer': problem.get('answer_expressions', ''), |
| 'fact_expr': fact_expr, |
| 'coords': coords |
| } |
| |
| def _process_hyperbola(self, problem: Dict, idx: int, params: Dict, |
| coords: Dict, eccentricity: Optional[float], |
| asymptote: Optional[float], verbose: bool) -> Dict: |
| """Process hyperbola problem with SDF optimization.""" |
| |
| fact_expr = problem.get('fact_expressions', '') |
| point_names = self._point_constraint_names(fact_expr, coords, 'hyperbola') |
| |
| |
| c_from_ellipse = None |
| if 'Focus(G) = Focus(H)' in fact_expr or 'Focus(H) = Focus(G)' in fact_expr: |
| |
| ellipse_match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2/(\d+)\s*\+\s*y\^2/(\d+)\s*=\s*1\)', fact_expr) |
| if ellipse_match: |
| x_coef = float(ellipse_match.group(1)) |
| y_coef = float(ellipse_match.group(2)) |
| a_ell = np.sqrt(max(x_coef, y_coef)) |
| b_ell = np.sqrt(min(x_coef, y_coef)) |
| c_from_ellipse = np.sqrt(a_ell**2 - b_ell**2) |
| |
| |
| if eccentricity and eccentricity > 1 and c_from_ellipse: |
| |
| a_val = c_from_ellipse / eccentricity |
| |
| b_squared = c_from_ellipse**2 - a_val**2 |
| if b_squared > 0: |
| b_val = np.sqrt(b_squared) |
| params['a'] = a_val |
| params['b'] = b_val |
| params['a_squared'] = a_val**2 |
| params['b_squared'] = b_squared |
| |
| center = torch.tensor([0.0, 0.0]) |
| |
| if 'a' not in params or 'b' not in params: |
| return { |
| 'index': idx, |
| 'success': False, |
| 'error': f"Hyperbola params missing 'a' or 'b': {list(params.keys())}" |
| } |
| a = torch.tensor([params['a']]) |
| b = torch.tensor([params['b']]) |
| |
| sdf = HyperbolaSDF(center, a, b) |
| |
| |
| has_explicit_params = c_from_ellipse is not None and eccentricity and eccentricity > 1 |
| |
| constraints = [] |
| weights = [] |
| |
| if not has_explicit_params: |
| |
| all_positions = [sdf.center] |
| |
| |
| if eccentricity and eccentricity > 1: |
| constraints.append(lambda: GeometricConstraints.eccentricity_hyperbola( |
| sdf.a, sdf.b, eccentricity |
| )) |
| weights.append(10.0) |
| |
| |
| if asymptote: |
| constraints.append(lambda: GeometricConstraints.asymptote_slope( |
| sdf.a, sdf.b, asymptote |
| )) |
| weights.append(10.0) |
| |
| |
| focus_coords = [(n, c) for n, c in coords.items() if 'F' in n] |
| if len(focus_coords) >= 2: |
| f1 = focus_coords[0][1] |
| f2 = focus_coords[1][1] |
| c_target = abs(f1[0] - f2[0]) / 2 if f1[1] == f2[1] == 0 else None |
| if c_target: |
| constraints.append(lambda ct=c_target: GeometricConstraints.focus_constraint_hyperbola( |
| sdf.a, sdf.b, ct |
| )) |
| weights.append(10.0) |
| |
| |
| for name, (px, py) in coords.items(): |
| if name in point_names and name not in ['F1', 'F2', 'F', 'O']: |
| all_positions.append(torch.tensor([px, py])) |
| |
| |
| if len(all_positions) > 1: |
| constraints.append(lambda pos=all_positions: GeometricConstraints.crowd_penalty(pos, min_dist=0.5)) |
| weights.append(3.0) |
| |
| |
| constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.a)) |
| constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.b)) |
| weights.extend([1.0, 1.0]) |
| |
| if len(constraints) > 2: |
| opt_result = self.optimizer.optimize(sdf, constraints, weights, verbose) |
| else: |
| opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'using explicit params'} |
| |
| with torch.no_grad(): |
| a_final = abs(sdf.a.item()) |
| b_final = abs(sdf.b.item()) |
| |
| output_path = self.output_dir / 'hyperbola' / f'problem_{idx:04d}.png' |
| self._visualize_hyperbola(sdf, problem, params, output_path) |
| |
| return { |
| 'index': idx, |
| 'success': True, |
| 'conic_type': 'hyperbola', |
| 'error': None, |
| 'params': { |
| 'a': a_final, |
| 'b': b_final, |
| 'orientation': params.get('orientation', 'horizontal') |
| }, |
| 'optimization': opt_result, |
| 'output_path': str(output_path), |
| 'answer': problem.get('answer_expressions', ''), |
| 'fact_expr': fact_expr, |
| 'coords': coords |
| } |
| |
| def _process_parabola(self, problem: Dict, idx: int, params: Dict, |
| coords: Dict, verbose: bool) -> Dict: |
| """Process parabola problem with SDF optimization.""" |
| |
| fact_expr = problem.get('fact_expressions', '') |
| point_names = self._point_constraint_names(fact_expr, coords, 'parabola') |
| vertex = torch.tensor([0.0, 0.0]) |
| p = torch.tensor([params['p']]) |
| direction = params.get('direction', 'right') |
| |
| sdf = ParabolaSDF(vertex, p, direction) |
| |
| sdf.vertex.requires_grad_(False) |
| |
| |
| has_explicit_params = not params.get('symbolic', False) and not params.get('from_constraints', False) |
| |
| if has_explicit_params: |
| opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'using explicit params'} |
| else: |
| |
| all_positions = [sdf.vertex] |
| |
| constraints = [ |
| lambda: GeometricConstraints.positive_constraint(sdf.p) |
| ] |
| weights = [1.0] |
| |
| |
| for name, (px, py) in coords.items(): |
| if name in point_names and name not in ['F', 'O']: |
| point = torch.tensor([px, py]) |
| constraints.append(lambda pt=point: GeometricConstraints.point_on_curve(sdf, pt)) |
| weights.append(5.0) |
| all_positions.append(point) |
| |
| |
| if len(all_positions) > 1: |
| constraints.append(lambda pos=all_positions: GeometricConstraints.crowd_penalty(pos, min_dist=0.5)) |
| weights.append(3.0) |
| |
| if len(constraints) > 1: |
| opt_result = self.optimizer.optimize(sdf, constraints, weights, verbose) |
| else: |
| opt_result = {'final_loss': 0.0, 'converged': True} |
| |
| with torch.no_grad(): |
| p_final = abs(sdf.p.item()) |
| |
| output_path = self.output_dir / 'parabola' / f'problem_{idx:04d}.png' |
| self._visualize_parabola(sdf, problem, params, output_path) |
| |
| return { |
| 'index': idx, |
| 'success': True, |
| 'conic_type': 'parabola', |
| 'error': None, |
| 'params': {'p': p_final, 'direction': direction}, |
| 'optimization': opt_result, |
| 'output_path': str(output_path), |
| 'answer': problem.get('answer_expressions', ''), |
| 'fact_expr': fact_expr, |
| 'coords': coords |
| } |
| |
| def _process_circle(self, problem: Dict, idx: int, params: Dict, |
| coords: Dict, verbose: bool) -> Dict: |
| """Process circle problem with SDF.""" |
| |
| fact_expr = problem.get('fact_expressions', '') |
| point_names = self._point_constraint_names(fact_expr, coords, 'circle') |
| |
| if params.get('from_diameter'): |
| |
| |
| fact_expr = problem.get('fact_expressions', '') |
| coords = self.parser.parse_coordinates(fact_expr) |
| |
| |
| diameter_match = re.search(r'IsDiameter\(LineSegmentOf\((\w+),\s*(\w+)\)', fact_expr) |
| if diameter_match: |
| pt1_name = diameter_match.group(1) |
| pt2_name = diameter_match.group(2) |
| if pt1_name in coords and pt2_name in coords: |
| x1, y1 = coords[pt1_name] |
| x2, y2 = coords[pt2_name] |
| |
| params['center'] = ((x1 + x2) / 2, (y1 + y2) / 2) |
| params['radius'] = np.sqrt((x2 - x1)**2 + (y2 - y1)**2) / 2 |
| else: |
| result = { |
| 'index': idx, |
| 'success': False, |
| 'error': 'Circle from diameter: missing point coordinates' |
| } |
| return result |
| else: |
| result = { |
| 'index': idx, |
| 'success': False, |
| 'error': 'Circle from diameter: cannot parse diameter pattern' |
| } |
| return result |
| |
| center = torch.tensor(list(params.get('center', (0.0, 0.0)))) |
| radius = torch.tensor([params.get('radius', 1.0)]) |
| |
| sdf = CircleSDF(center, radius) |
| |
| |
| opt_result = {'final_loss': 0.0, 'converged': True} |
| |
| with torch.no_grad(): |
| cx = sdf.center[0].item() |
| cy = sdf.center[1].item() |
| r = abs(sdf.radius.item()) |
| |
| output_path = self.output_dir / 'circle' / f'problem_{idx:04d}.png' |
| self._visualize_circle(sdf, problem, params, output_path) |
| |
| return { |
| 'index': idx, |
| 'success': True, |
| 'conic_type': 'circle', |
| 'error': None, |
| 'params': {'center': (cx, cy), 'radius': r}, |
| 'optimization': opt_result, |
| 'output_path': str(output_path), |
| 'answer': problem.get('answer_expressions', ''), |
| 'fact_expr': fact_expr, |
| 'coords': {k:v for k,v in coords.items() if k in point_names} |
| } |
| |
| def _setup_gaokao_axes(self, ax, xlim, ylim): |
| """Setup coordinate axes in Chinese Gaokao analytic geometry style.""" |
| ax.set_facecolor('white') |
| for spine in ax.spines.values(): |
| spine.set_visible(False) |
| ax.set_xticks([]) |
| ax.set_yticks([]) |
|
|
| |
| arrow_kw = dict(arrowstyle='->', color='black', lw=1.0) |
| ax.annotate('', xy=(xlim[1], 0), xytext=(xlim[0], 0), arrowprops=arrow_kw) |
| ax.annotate('', xy=(0, ylim[1]), xytext=(0, ylim[0]), arrowprops=arrow_kw) |
|
|
| |
| r = max(xlim[1] - xlim[0], ylim[1] - ylim[0]) |
| d = r * 0.025 |
|
|
| ax.text(xlim[1] - d, -d * 2, '$x$', fontsize=14, ha='right', va='top') |
| ax.text(d * 0.5, ylim[1] - d * 0.5, '$y$', fontsize=14, ha='left', va='top') |
| ax.text(-d * 1.5, -d * 2, '$O$', fontsize=14, ha='right', va='top') |
|
|
| ax.set_xlim(xlim) |
| ax.set_ylim(ylim) |
| ax.set_aspect('equal') |
|
|
| def _visualize_circle(self, sdf: CircleSDF, problem: Dict, params: Dict, |
| output_path: Path): |
| """Visualize circle in Gaokao style.""" |
|
|
| with torch.no_grad(): |
| cx = sdf.center[0].item() |
| cy = sdf.center[1].item() |
| r = abs(sdf.radius.item()) |
|
|
| margin = r + 1.5 |
| xlim = (min(cx - margin, -0.5), max(cx + margin, 0.5)) |
| ylim = (min(cy - margin, -0.5), max(cy + margin, 0.5)) |
|
|
| fig, ax = plt.subplots(figsize=(8, 8)) |
| fig.patch.set_facecolor('white') |
|
|
| renderer = SDFRenderer(resolution=400, xlim=xlim, ylim=ylim) |
| renderer.render_curve_only(sdf, ax, color='black', linewidth=1.5) |
|
|
| |
| d = max(xlim[1] - xlim[0], ylim[1] - ylim[0]) * 0.02 |
| ax.plot(cx, cy, 'k.', markersize=4) |
| ax.text(cx + d, cy + d * 2, '$C$', fontsize=13, ha='left', va='bottom') |
|
|
| |
| for name, (px, py) in params.get('coords', {}).items(): |
| ax.plot(px, py, 'k.', markersize=4) |
| ax.text(px + d, py + d * 2, f'${name}$', fontsize=13, ha='left', va='bottom') |
|
|
| self._setup_gaokao_axes(ax, xlim, ylim) |
|
|
| output_path.parent.mkdir(parents=True, exist_ok=True) |
| plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white') |
| plt.close(fig) |
| |
| def _wrap_text(self, text: str, width: int = 50) -> str: |
| """Wrap text to specified width.""" |
| words = text.split() |
| lines = [] |
| current_line = [] |
| current_len = 0 |
| |
| for word in words: |
| if current_len + len(word) + 1 <= width: |
| current_line.append(word) |
| current_len += len(word) + 1 |
| else: |
| if current_line: |
| lines.append(' '.join(current_line)) |
| current_line = [word] |
| current_len = len(word) |
| |
| if current_line: |
| lines.append(' '.join(current_line)) |
| |
| return '\n'.join(lines) |
| |
| def _visualize_ellipse(self, sdf: EllipseSDF, problem: Dict, params: Dict, |
| output_path: Path, major_axis: str): |
| """Visualize ellipse in Gaokao style.""" |
|
|
| with torch.no_grad(): |
| a = abs(sdf.a.item()) |
| b = abs(sdf.b.item()) |
|
|
| b_viz = max(b, 0.1) |
| fact_expr = problem.get('fact_expressions', '') |
|
|
| |
| hyperbola_params = self.parser.parse_hyperbola(fact_expr) |
| has_hyperbola = hyperbola_params is not None and 'a' in hyperbola_params and 'b' in hyperbola_params |
|
|
| if has_hyperbola: |
| a_hyp = hyperbola_params['a'] |
| b_hyp = hyperbola_params['b'] |
| max_dim = max(a, b_viz, a_hyp, b_hyp) * 1.8 + 1 |
| else: |
| max_dim = max(a, b_viz) * 1.5 + 0.5 |
|
|
| xlim = (-max_dim, max_dim) |
| ylim = (-max_dim, max_dim) |
|
|
| fig, ax = plt.subplots(figsize=(8, 8)) |
| fig.patch.set_facecolor('white') |
|
|
| renderer = SDFRenderer(resolution=500, xlim=xlim, ylim=ylim) |
| renderer.render_curve_only(sdf, ax, color='black', linewidth=1.5) |
|
|
| |
| if has_hyperbola: |
| center = torch.tensor([0.0, 0.0]) |
| a_hyp_t = torch.tensor([hyperbola_params['a']]) |
| b_hyp_t = torch.tensor([hyperbola_params['b']]) |
| hyp_sdf = HyperbolaSDF(center, a_hyp_t, b_hyp_t) |
| renderer.render_curve_only(hyp_sdf, ax, color='black', linewidth=1.5) |
|
|
| |
| slope_hyp = hyperbola_params['b'] / hyperbola_params['a'] |
| x_asym = np.linspace(-max_dim, max_dim, 100) |
| ax.plot(x_asym, slope_hyp * x_asym, 'k--', linewidth=0.8, alpha=0.5) |
| ax.plot(x_asym, -slope_hyp * x_asym, 'k--', linewidth=0.8, alpha=0.5) |
|
|
| |
| c = np.sqrt(abs(a**2 - b**2)) if a > b else np.sqrt(abs(b**2 - a**2)) |
| d = max_dim * 0.025 |
| if major_axis == 'x': |
| ax.plot(c, 0, 'k.', markersize=5) |
| ax.plot(-c, 0, 'k.', markersize=5) |
| ax.text(-c, d * 2, '$F_1$', fontsize=13, ha='center', va='bottom') |
| ax.text(c, d * 2, '$F_2$', fontsize=13, ha='center', va='bottom') |
| else: |
| ax.plot(0, c, 'k.', markersize=5) |
| ax.plot(0, -c, 'k.', markersize=5) |
| ax.text(d * 2, -c, '$F_1$', fontsize=13, ha='left', va='center') |
| ax.text(d * 2, c, '$F_2$', fontsize=13, ha='left', va='center') |
|
|
| |
| coords = self.parser.parse_coordinates(problem.get('fact_expressions', '')) |
| for name, (px, py) in coords.items(): |
| if name not in ['F1', 'F2', 'F', 'O']: |
| ax.plot(px, py, 'k.', markersize=5) |
| ax.text(px + d, py + d * 2, f'${name}$', fontsize=13) |
|
|
| self._setup_gaokao_axes(ax, xlim, ylim) |
|
|
| plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white') |
| plt.close(fig) |
| |
| def _visualize_hyperbola(self, sdf: HyperbolaSDF, problem: Dict, params: Dict, |
| output_path: Path): |
| """Visualize hyperbola in Gaokao style.""" |
|
|
| with torch.no_grad(): |
| a = abs(sdf.a.item()) |
| b = abs(sdf.b.item()) |
|
|
| fact_expr = problem.get('fact_expressions', '') |
|
|
| |
| ellipse_params = self.parser.parse_ellipse(fact_expr) |
| line_params = self.parser.parse_line(fact_expr) |
| has_ellipse = ellipse_params is not None and 'a' in ellipse_params and 'b' in ellipse_params |
| has_line = line_params is not None and (line_params.get('a') is not None or line_params.get('slope') is not None) |
|
|
| |
| if has_line and line_params.get('slope') is not None and line_params.get('a') is None: |
| slope = line_params['slope'] |
| if 'LeftFocus' in fact_expr or 'RightFocus' in fact_expr: |
| c_hyp = np.sqrt(a**2 + b**2) |
| focus_x = -c_hyp if 'LeftFocus' in fact_expr else c_hyp |
| line_params['a'] = slope |
| line_params['b'] = -1.0 |
| line_params['c'] = -slope * focus_x |
|
|
| |
| if has_ellipse: |
| a_ell = ellipse_params['a'] |
| b_ell = ellipse_params['b'] |
| max_dim = max(a, b, a_ell, b_ell) * 1.5 + 1 |
| else: |
| max_dim = max(a, b) * 2.5 + 2 |
|
|
| xlim = (-max_dim, max_dim) |
| ylim = (-max_dim, max_dim) |
|
|
| fig, ax = plt.subplots(figsize=(8, 8)) |
| fig.patch.set_facecolor('white') |
|
|
| renderer = SDFRenderer(resolution=500, xlim=xlim, ylim=ylim) |
| renderer.render_curve_only(sdf, ax, color='black', linewidth=1.5) |
|
|
| |
| if has_ellipse: |
| center = torch.tensor([0.0, 0.0]) |
| a_ell_t = torch.tensor([ellipse_params['a']]) |
| b_ell_t = torch.tensor([ellipse_params['b']]) |
| ellipse_sdf = EllipseSDF(center, a_ell_t, b_ell_t) |
| renderer.render_curve_only(ellipse_sdf, ax, color='black', linewidth=1.5) |
|
|
| |
| if has_line and line_params.get('a') is not None and line_params.get('b') is not None: |
| line_a = line_params['a'] |
| line_b = line_params['b'] |
| line_c = line_params.get('c', 0) |
| x_line = np.linspace(-max_dim, max_dim, 100) |
| if abs(line_b) > 1e-6: |
| y_line = (-line_a * x_line - line_c) / line_b |
| mask = (y_line >= ylim[0]) & (y_line <= ylim[1]) |
| ax.plot(x_line[mask], y_line[mask], 'k-', linewidth=1.0) |
| else: |
| x_val = -line_c / line_a if abs(line_a) > 1e-6 else 0 |
| ax.axvline(x=x_val, color='black', linewidth=1.0) |
|
|
| |
| slope = b / a |
| x_asym = np.linspace(-max_dim, max_dim, 100) |
| ax.plot(x_asym, slope * x_asym, 'k--', linewidth=0.8, alpha=0.5) |
| ax.plot(x_asym, -slope * x_asym, 'k--', linewidth=0.8, alpha=0.5) |
|
|
| |
| c = np.sqrt(a**2 + b**2) |
| d = max_dim * 0.025 |
| ax.plot(c, 0, 'k.', markersize=5) |
| ax.plot(-c, 0, 'k.', markersize=5) |
| ax.text(-c, d * 2, '$F_1$', fontsize=13, ha='center', va='bottom') |
| ax.text(c, d * 2, '$F_2$', fontsize=13, ha='center', va='bottom') |
|
|
| |
| coords = self.parser.parse_coordinates(fact_expr) |
| for name, (px, py) in coords.items(): |
| if name not in ['F1', 'F2', 'F', 'O']: |
| ax.plot(px, py, 'k.', markersize=5) |
| ax.text(px + d, py + d * 2, f'${name}$', fontsize=13) |
|
|
| self._setup_gaokao_axes(ax, xlim, ylim) |
|
|
| plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white') |
| plt.close(fig) |
| |
| def _visualize_parabola(self, sdf: ParabolaSDF, problem: Dict, params: Dict, |
| output_path: Path): |
| """Visualize parabola in Gaokao style.""" |
|
|
| with torch.no_grad(): |
| p = abs(sdf.p.item()) |
|
|
| direction = params.get('direction', 'right') |
|
|
| |
| extent = max(p * 8, 6) |
| if direction == 'right': |
| xlim = (-p * 3, extent) |
| ylim = (-extent * 0.8, extent * 0.8) |
| elif direction == 'left': |
| xlim = (-extent, p * 3) |
| ylim = (-extent * 0.8, extent * 0.8) |
| elif direction == 'up': |
| xlim = (-extent * 0.8, extent * 0.8) |
| ylim = (-p * 3, extent) |
| else: |
| xlim = (-extent * 0.8, extent * 0.8) |
| ylim = (-extent, p * 3) |
|
|
| |
| xlim = (min(xlim[0], -0.5), max(xlim[1], 0.5)) |
| ylim = (min(ylim[0], -0.5), max(ylim[1], 0.5)) |
|
|
| fig, ax = plt.subplots(figsize=(8, 8)) |
| fig.patch.set_facecolor('white') |
|
|
| renderer = SDFRenderer(resolution=600, xlim=xlim, ylim=ylim) |
| renderer.render_curve_only(sdf, ax, color='black', linewidth=1.5) |
|
|
| d = max(xlim[1] - xlim[0], ylim[1] - ylim[0]) * 0.02 |
|
|
| |
| if direction == 'right': |
| ax.plot(p, 0, 'k.', markersize=5) |
| ax.text(p + d, d * 2, '$F$', fontsize=13, ha='left', va='bottom') |
| ax.plot([-p, -p], [ylim[0], ylim[1]], 'k--', linewidth=0.8, alpha=0.5) |
| elif direction == 'left': |
| ax.plot(-p, 0, 'k.', markersize=5) |
| ax.text(-p - d, d * 2, '$F$', fontsize=13, ha='right', va='bottom') |
| ax.plot([p, p], [ylim[0], ylim[1]], 'k--', linewidth=0.8, alpha=0.5) |
| elif direction == 'up': |
| ax.plot(0, p, 'k.', markersize=5) |
| ax.text(d * 2, p + d, '$F$', fontsize=13, ha='left', va='bottom') |
| ax.plot([xlim[0], xlim[1]], [-p, -p], 'k--', linewidth=0.8, alpha=0.5) |
| else: |
| ax.plot(0, -p, 'k.', markersize=5) |
| ax.text(d * 2, -p - d, '$F$', fontsize=13, ha='left', va='top') |
| ax.plot([xlim[0], xlim[1]], [p, p], 'k--', linewidth=0.8, alpha=0.5) |
|
|
| |
| coords = self.parser.parse_coordinates(problem.get('fact_expressions', '')) |
| for idx, (name, (px, py)) in enumerate(coords.items()): |
| if name not in ['F', 'O']: |
| ax.plot(px, py, 'k.', markersize=5) |
| offset_y = d * 2 + d * idx |
| ax.text(px + d, py + offset_y, f'${name}$', fontsize=13) |
|
|
| self._setup_gaokao_axes(ax, xlim, ylim) |
|
|
| plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white') |
| plt.close(fig) |
| |
| def process_batch(self, problems_input, max_problems: int = None, |
| verbose: bool = False) -> List[Dict]: |
| """Process a batch of problems. |
| |
| Args: |
| problems_input: Either a list of problem dicts or a path to JSON file |
| max_problems: Maximum number of problems to process |
| verbose: Whether to print verbose output |
| """ |
| |
| if isinstance(problems_input, str): |
| with open(problems_input, 'r', encoding='utf-8') as f: |
| problems = json.load(f) |
| else: |
| problems = problems_input |
| |
| if max_problems: |
| problems = problems[:max_problems] |
| |
| results = [] |
| stats = {'total': len(problems), 'success': 0, 'failed': 0} |
| type_stats = {'ellipse': 0, 'hyperbola': 0, 'parabola': 0, 'circle': 0} |
| reason_counts: Dict[str, int] = {} |
| |
| print(f"\n{'='*60}") |
| print(f"SDF-Based Processing: {len(problems)} problems") |
| print(f"{'='*60}\n") |
| |
| for idx, problem in enumerate(tqdm(problems, desc="Processing")): |
| result = self.process_problem(problem, idx, verbose) |
| results.append(result) |
| |
| if result['success']: |
| stats['success'] += 1 |
| ctype = result.get('conic_type') |
| if ctype in type_stats: |
| type_stats[ctype] += 1 |
| else: |
| stats['failed'] += 1 |
| for reason in result.get('validation_reasons', []): |
| reason_counts[reason] = reason_counts.get(reason, 0) + 1 |
| |
| |
| summary = { |
| 'stats': stats, |
| 'type_stats': type_stats, |
| 'reason_counts': reason_counts, |
| 'results': results |
| } |
| with open(self.output_dir / 'summary.json', 'w') as f: |
| json.dump(summary, f, indent=2, default=str) |
| |
| print(f"\n{'='*60}") |
| print("PROCESSING COMPLETE") |
| print(f"{'='*60}") |
| print(f"Success: {stats['success']} / {stats['total']} ({100*stats['success']/stats['total']:.1f}%)") |
| print(f"By type: {type_stats}") |
| print(f"Output: {self.output_dir}") |
| |
| return results |
|
|