Image_SDF / src /sdf_geo /parser.py
WendingGao's picture
Upload 22 files
fdb3169 verified
"""
Problem Parser Module
Extracts geometric parameters from problem expressions.
"""
import re
import numpy as np
from typing import Dict, List, Tuple, Optional
class ProblemParser:
"""Parse problem expressions into geometric constraints and SDFs."""
def __init__(self):
pass
def parse_line(self, fact_expr: str) -> Optional[Dict]:
"""Parse line expression."""
# Expression(G) = (x + y - 1 = 0) or similar
match = re.search(r'Expression\(\w+\)\s*=\s*\(([^)]+)\s*=\s*0\)', fact_expr)
if match:
expr = match.group(1)
# Parse ax + by + c = 0 format
# Try to extract coefficients
a, b, c = 0.0, 0.0, 0.0
# Match patterns like "x + y - 1" or "2*x - 3*y + 5"
x_match = re.search(r'([+-]?\s*\d*\.?\d*)\s*\*?\s*x', expr)
y_match = re.search(r'([+-]?\s*\d*\.?\d*)\s*\*?\s*y', expr)
if x_match:
coef = x_match.group(1).replace(' ', '')
if coef in ['', '+']:
a = 1.0
elif coef == '-':
a = -1.0
else:
try:
a = float(coef)
except:
a = 1.0
if y_match:
coef = y_match.group(1).replace(' ', '')
if coef in ['', '+']:
b = 1.0
elif coef == '-':
b = -1.0
else:
try:
b = float(coef)
except:
b = 1.0
# Find constant term
const_match = re.search(r'([+-]\s*\d+\.?\d*)\s*(?:=|$)', expr)
if const_match:
try:
c = float(const_match.group(1).replace(' ', ''))
except:
c = 0.0
if a != 0 or b != 0:
return {
'type': 'line',
'a': a,
'b': b,
'c': c,
'equation': expr
}
# Check for Slope constraint - sqrt format
slope_match = re.search(r'Slope\(\w+\)\s*=\s*sqrt\((\d+)\)', fact_expr)
if slope_match:
slope = np.sqrt(float(slope_match.group(1)))
return {
'type': 'line',
'slope': slope,
'symbolic': True
}
# Check for Slope constraint - numeric format
slope_match = re.search(r'Slope\(\w+\)\s*=\s*([\d.]+)', fact_expr)
if slope_match:
return {
'type': 'line',
'slope': float(slope_match.group(1)),
'symbolic': True
}
return None
def parse_circle(self, fact_expr: str) -> Optional[Dict]:
"""Parse circle expression."""
# Format 1: (x-a)^2 + (y-b)^2 = r^2
match = re.search(r'Expression\(\w+\)\s*=\s*\(\(x-([^)]+)\)\^2\s*\+\s*\(y-([^)]+)\)\^2\s*=\s*(\d+)\)', fact_expr)
if match:
return {
'type': 'circle',
'center': (float(match.group(1)), float(match.group(2))),
'radius': np.sqrt(float(match.group(3)))
}
# Format 2: x^2 + (y-a)^2 = r (center at origin or on axis)
match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*\+\s*\(([+-]?\s*\d*\.?\d*)\s*[+-]\s*y\)\^2\s*=\s*(\d+)\)', fact_expr)
if match:
cy = -float(match.group(1).replace(' ', '')) if match.group(1) else 0.0
return {
'type': 'circle',
'center': (0.0, cy),
'radius': np.sqrt(float(match.group(2)))
}
# Format 3: y^2 + (x-a)^2 = r or y^2 + (x+a)^2 = r
match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*\+\s*\(x\s*([+-])\s*(\d+\.?\d*)\)\^2\s*=\s*(\d+\.?\d*)\)', fact_expr)
if match:
sign = -1 if match.group(1) == '-' else 1
cx = sign * float(match.group(2))
return {
'type': 'circle',
'center': (cx, 0.0),
'radius': np.sqrt(float(match.group(3)))
}
# Format 4: x^2 + y^2 = r (center at origin)
match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*\+\s*y\^2\s*=\s*(\d+\.?\d*)\)', fact_expr)
if match:
return {
'type': 'circle',
'center': (0.0, 0.0),
'radius': np.sqrt(float(match.group(1)))
}
# Format 5: Check if it's explicitly declared as Circle type
if re.search(r'\w+:\s*Circle', fact_expr):
# Try more general patterns
# (x + a)^2 + (y - b)^2 = r
match = re.search(r'\(x\s*([+-])\s*(\d+\.?\d*)\)\^2\s*\+\s*\(y\s*([+-])\s*(\d+\.?\d*)\)\^2\s*=\s*(\d+\.?\d*)', fact_expr)
if match:
cx = float(match.group(2)) * (-1 if match.group(1) == '+' else 1)
cy = float(match.group(4)) * (-1 if match.group(3) == '+' else 1)
return {
'type': 'circle',
'center': (cx, cy),
'radius': np.sqrt(float(match.group(5)))
}
# Check for circle defined by diameter
if 'IsDiameter' in fact_expr:
return {
'type': 'circle',
'from_diameter': True
}
# Check for circle defined by slope product = -1 (perpendicular)
# Pattern: Slope(LineSegmentOf(P, A)) * Slope(LineSegmentOf(P, B)) = -1
# This means angle APB = 90°, so P lies on circle with diameter AB
slope_match = re.search(r'Slope\(LineSegmentOf\(\w+,\s*(\w+)\)\)\s*\*\s*Slope\(LineSegmentOf\(\w+,\s*(\w+)\)\)\s*=\s*-1', fact_expr)
if slope_match:
pt1_name = slope_match.group(1)
pt2_name = slope_match.group(2)
coords = self.parse_coordinates(fact_expr)
if pt1_name in coords and pt2_name in coords:
x1, y1 = coords[pt1_name]
x2, y2 = coords[pt2_name]
# Circle with diameter AB: center = midpoint, radius = |AB|/2
cx = (x1 + x2) / 2
cy = (y1 + y2) / 2
radius = np.sqrt((x2 - x1)**2 + (y2 - y1)**2) / 2
return {
'type': 'circle',
'center': (cx, cy),
'radius': radius,
'from_constraints': True
}
# General circle equation: x^2 + y^2 + Dx + Ey + F = 0
# Center: (-D/2, -E/2), Radius: sqrt(D²/4 + E²/4 - F)
# Pattern: ax^2 + by^2 + Dx + Ey + F = 0 where coefficients can vary
general_match = re.search(r'Expression\(\w+\)\s*=\s*\(([^)]+x\^2[^)]+y\^2[^)]+)\s*=\s*0\)', fact_expr)
if general_match and 'Circle' in fact_expr:
expr = general_match.group(1)
# Parse coefficients: D*x, E*y, F (constant)
D = E = F = 0.0
# Find coefficient of x (not x^2)
d_match = re.search(r'([+-]?\s*\d*\.?\d*)\s*\*?\s*x(?!\^)', expr)
if d_match:
d_str = d_match.group(1).replace(' ', '')
D = float(d_str) if d_str and d_str not in ['+', '-'] else (1.0 if d_str == '+' or d_str == '' else -1.0)
# Find coefficient of y (not y^2)
e_match = re.search(r'([+-]?\s*\d*\.?\d*)\s*\*?\s*y(?!\^)', expr)
if e_match:
e_str = e_match.group(1).replace(' ', '')
E = float(e_str) if e_str and e_str not in ['+', '-'] else (1.0 if e_str == '+' or e_str == '' else -1.0)
# Find constant term
const_match = re.search(r'([+-]\s*\d+\.?\d*)\s*(?:=|$)', expr)
if const_match:
f_str = const_match.group(1).replace(' ', '')
F = float(f_str)
cx = -D / 2
cy = -E / 2
r_sq = D**2 / 4 + E**2 / 4 - F
if r_sq > 0:
return {
'type': 'circle',
'center': (cx, cy),
'radius': np.sqrt(r_sq),
'from_constraints': True
}
# Shifted center circle: (x+h)^2 + y^2 = r^2 or (x-h)^2 + y^2 = r^2
shifted_match = re.search(r'Expression\(\w+\)\s*=\s*\(\(x([+-])(\d+\.?\d*)\)\^2\s*\+\s*y\^2\s*=\s*(\d+\.?\d*)\)', fact_expr)
if shifted_match:
sign = shifted_match.group(1)
h = float(shifted_match.group(2))
r_sq = float(shifted_match.group(3))
cx = -h if sign == '+' else h
return {
'type': 'circle',
'center': (cx, 0.0),
'radius': np.sqrt(r_sq),
}
# (x±h)^2 + (y±k)^2 = r^2
shifted_match2 = re.search(r'Expression\(\w+\)\s*=\s*\(\(x([+-])(\d+\.?\d*)\)\^2\s*\+\s*\(y([+-])(\d+\.?\d*)\)\^2\s*=\s*(\d+\.?\d*)\)', fact_expr)
if shifted_match2:
sign_x = shifted_match2.group(1)
h = float(shifted_match2.group(2))
sign_y = shifted_match2.group(3)
k = float(shifted_match2.group(4))
r_sq = float(shifted_match2.group(5))
cx = -h if sign_x == '+' else h
cy = -k if sign_y == '+' else k
return {
'type': 'circle',
'center': (cx, cy),
'radius': np.sqrt(r_sq),
}
return None
def parse_ellipse(self, fact_expr: str) -> Optional[Dict]:
"""Parse ellipse expression and return parameters."""
# x^2/a + y^2/b = 1
match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2/(\d+)\s*\+\s*y\^2/(\d+)\s*=\s*1\)', fact_expr)
if match:
x_coef = float(match.group(1))
y_coef = float(match.group(2))
return {
'type': 'ellipse',
'x_coef': x_coef,
'y_coef': y_coef,
'a': np.sqrt(max(x_coef, y_coef)),
'b': np.sqrt(min(x_coef, y_coef)),
'major_axis': 'x' if x_coef > y_coef else 'y'
}
# y^2/b + x^2/a = 1
match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2/(\d+)\s*\+\s*x\^2/(\d+)\s*=\s*1\)', fact_expr)
if match:
y_coef = float(match.group(1))
x_coef = float(match.group(2))
return {
'type': 'ellipse',
'x_coef': x_coef,
'y_coef': y_coef,
'a': np.sqrt(max(x_coef, y_coef)),
'b': np.sqrt(min(x_coef, y_coef)),
'major_axis': 'x' if x_coef > y_coef else 'y'
}
# x^2/a + y^2 = 1 (y has coefficient 1, x has numeric denominator)
match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2/(\d+)\s*\+\s*y\^2\s*=\s*1\)', fact_expr)
if match:
x_coef = float(match.group(1))
y_coef = 1.0
return {
'type': 'ellipse',
'x_coef': x_coef,
'y_coef': y_coef,
'a': np.sqrt(x_coef), # a > b since x_coef > 1
'b': 1.0,
'major_axis': 'x'
}
# y^2/a + x^2 = 1 (x has coefficient 1, y has numeric denominator)
match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2/(\d+)\s*\+\s*x\^2\s*=\s*1\)', fact_expr)
if match:
y_coef = float(match.group(1))
x_coef = 1.0
return {
'type': 'ellipse',
'x_coef': x_coef,
'y_coef': y_coef,
'a': np.sqrt(y_coef), # a > b since y_coef > 1
'b': 1.0,
'major_axis': 'y'
}
# y^2 + x^2/k^2 = 1 (y has coefficient 1)
match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*\+\s*x\^2/\w+\^?2?\s*=\s*1\)', fact_expr)
if match:
return {
'type': 'ellipse',
'x_coef': 4.0, # default
'y_coef': 1.0,
'a': 2.0,
'b': 1.0,
'major_axis': 'x',
'symbolic': True
}
# x^2 + y^2/k^2 = 1
match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*\+\s*y\^2/\w+\^?2?\s*=\s*1\)', fact_expr)
if match:
return {
'type': 'ellipse',
'x_coef': 1.0,
'y_coef': 4.0, # default
'a': 2.0,
'b': 1.0,
'major_axis': 'y',
'symbolic': True
}
# Ellipse with symbolic: y^2/b^2 + x^2/a^2 = 1 or x^2/a^2 + y^2/b^2 = 1
if re.search(r'Expression\(\w+\)\s*=\s*\([xy]\^2/\w+\^?2?\s*\+\s*[xy]\^2/\w+\^?2?\s*=\s*1\)', fact_expr):
return {
'type': 'ellipse',
'x_coef': 4.0,
'y_coef': 3.0,
'a': 2.0,
'b': np.sqrt(3),
'major_axis': 'x',
'symbolic': True
}
# x^2 + N*y^2 = M (ellipse: x²/M + y²/(M/N) = 1)
match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*\+\s*(\d+)\*y\^2\s*=\s*(\d+)\)', fact_expr)
if match:
n = float(match.group(1))
m = float(match.group(2))
a_sq = m # x coefficient
b_sq = m / n # y coefficient
a = np.sqrt(max(a_sq, b_sq))
b = np.sqrt(min(a_sq, b_sq))
return {
'type': 'ellipse',
'x_coef': a_sq,
'y_coef': b_sq,
'a': a,
'b': b,
'major_axis': 'x' if a_sq >= b_sq else 'y'
}
# N*x^2 + y^2 = M (ellipse: x²/(M/N) + y²/M = 1)
match = re.search(r'Expression\(\w+\)\s*=\s*\((\d+)\*x\^2\s*\+\s*y\^2\s*=\s*(\d+)\)', fact_expr)
if match:
n = float(match.group(1))
m = float(match.group(2))
a_sq = m / n # x coefficient
b_sq = m # y coefficient
a = np.sqrt(max(a_sq, b_sq))
b = np.sqrt(min(a_sq, b_sq))
return {
'type': 'ellipse',
'x_coef': a_sq,
'y_coef': b_sq,
'a': a,
'b': b,
'major_axis': 'x' if a_sq >= b_sq else 'y'
}
# Check for Ellipse with geometric constraints (no explicit expression)
if 'Ellipse' in fact_expr:
coords = self.parse_coordinates(fact_expr)
eccentricity = self.parse_eccentricity(fact_expr)
c = None
major_axis = 'x' # default
# Try to find focus coordinate from various patterns
# Pattern 1: Coordinate(F) = (c, 0); RightFocus(G) = F
for name, (fx, fy) in coords.items():
if f'RightFocus(' in fact_expr and f') = {name}' in fact_expr:
c = abs(fx)
major_axis = 'x'
break
elif f'LeftFocus(' in fact_expr and f') = {name}' in fact_expr:
c = abs(fx)
major_axis = 'x'
break
elif f'UpperFocus(' in fact_expr and f') = {name}' in fact_expr:
c = abs(fy)
major_axis = 'y'
break
elif f'LowerFocus(' in fact_expr and f') = {name}' in fact_expr:
c = abs(fy)
major_axis = 'y'
break
# Pattern 2: Coordinate(OneOf(Focus(...)))
if c is None:
focus_match = re.search(r'Coordinate\(OneOf\(Focus\(\w+\)\)\)\s*=\s*\(([^,]+),\s*([^)]+)\)', fact_expr)
if focus_match:
try:
fx = float(focus_match.group(1).strip())
fy = float(focus_match.group(2).strip())
c = abs(fx) if abs(fy) < 0.01 else abs(fy)
major_axis = 'x' if abs(fy) < 0.01 else 'y'
except:
pass
# Pattern 2b: Two foci with explicit coordinates: Focus(G) = {F1, F2}
if c is None:
foci_match = re.search(r'Focus\(\w+\)\s*=\s*\{(\w+),\s*(\w+)\}', fact_expr)
if foci_match:
f1_name = foci_match.group(1)
f2_name = foci_match.group(2)
if f1_name in coords and f2_name in coords:
fx1, fy1 = coords[f1_name]
fx2, fy2 = coords[f2_name]
# c = half the distance between foci
c = np.sqrt((fx2 - fx1)**2 + (fy2 - fy1)**2) / 2
major_axis = 'x' if abs(fy1) < 0.01 else 'y'
# Pattern 3: PointOnCurve(Focus(G), xAxis) - focus on x-axis
if c is None and 'PointOnCurve(Focus(' in fact_expr:
if 'xAxis' in fact_expr:
major_axis = 'x'
elif 'yAxis' in fact_expr:
major_axis = 'y'
# Pattern 4: Length(MajorAxis(G)) = k * Length(MinorAxis(G))
axis_ratio = None
ratio_match = re.search(r'Length\(MajorAxis\(\w+\)\)\s*=\s*(\d+)\s*\*\s*Length\(MinorAxis', fact_expr)
if ratio_match:
axis_ratio = float(ratio_match.group(1))
# Pattern 5: Length(MinorAxis(G)) = N or Length(MinorAxis(G)) = 2*sqrt(N)
minor_axis_len = None
match = re.search(r'Length\(MinorAxis\(\w+\)\)\s*=\s*2\*sqrt\((\d+)\)', fact_expr)
if match:
minor_axis_len = 2 * np.sqrt(float(match.group(1)))
else:
match = re.search(r'Length\(MinorAxis\(\w+\)\)\s*=\s*(\d+)', fact_expr)
if match:
minor_axis_len = float(match.group(1))
# Pattern 6: Length(MajorAxis(G)) = N
major_axis_len = None
match = re.search(r'Length\(MajorAxis\(\w+\)\)\s*=\s*2\*sqrt\((\d+)\)', fact_expr)
if match:
major_axis_len = 2 * np.sqrt(float(match.group(1)))
else:
match = re.search(r'Length\(MajorAxis\(\w+\)\)\s*=\s*(\d+)', fact_expr)
if match:
major_axis_len = float(match.group(1))
# Pattern 7: FocalLength(G) = N or 2*c = N
focal_length = None
match = re.search(r'FocalLength\(\w+\)\s*=\s*(\d+)', fact_expr)
if match:
focal_length = float(match.group(1))
else:
match = re.search(r'2\*c\s*=\s*(\d+)', fact_expr)
if match:
focal_length = float(match.group(1))
# Case: c from FocalLength + b from MinorAxis
if c is None and focal_length:
c = focal_length / 2
# Case: b from MinorAxis length
if minor_axis_len:
b_from_minor = minor_axis_len / 2
if c is not None:
a = np.sqrt(c**2 + b_from_minor**2)
b = b_from_minor
# Case: a from MajorAxis length
if major_axis_len:
a_from_major = major_axis_len / 2
if c is not None:
a = a_from_major
b = np.sqrt(a**2 - c**2) if a > c else None
# Compute a, b from constraints
a, b = None, None
# Case 1: c and eccentricity known → a = c/e, b = sqrt(a² - c²)
if c is not None and eccentricity and 0 < eccentricity < 1:
a = c / eccentricity
b = np.sqrt(a**2 - c**2)
# Case 2: eccentricity known + axis ratio → solve for a, b
elif eccentricity and 0 < eccentricity < 1 and axis_ratio:
# a/b = axis_ratio, e = sqrt(1 - b²/a²) = sqrt(1 - 1/ratio²)
# This gives us the ratio, need another constraint for absolute size
a = 2.0 * axis_ratio # default size
b = 2.0
# Case 3: axis ratio + point on curve
elif axis_ratio:
# Find a point on curve and solve
for name, (px, py) in coords.items():
if f'PointOnCurve({name}' in fact_expr:
# x²/a² + y²/b² = 1, a = ratio * b
# x²/(ratio*b)² + y²/b² = 1
# x²/ratio² + y² = b²
b_sq = px**2 / axis_ratio**2 + py**2
if b_sq > 0:
b = np.sqrt(b_sq)
a = axis_ratio * b
break
# Case 4: Two points on ellipse → solve for a, b
if a is None:
points_on_curve = []
for name, (px, py) in coords.items():
if f'PointOnCurve({name}' in fact_expr and name not in ['F', 'F1', 'F2']:
points_on_curve.append((px, py))
if len(points_on_curve) >= 2:
# x1²/a² + y1²/b² = 1
# x2²/a² + y2²/b² = 1
p1, p2 = points_on_curve[0], points_on_curve[1]
x1, y1 = p1
x2, y2 = p2
# Solve: let u = 1/a², v = 1/b²
# x1²u + y1²v = 1
# x2²u + y2²v = 1
det = x1**2 * y2**2 - x2**2 * y1**2
if abs(det) > 1e-10:
u = (y2**2 - y1**2) / det
v = (x1**2 - x2**2) / det
if u > 0 and v > 0:
a_sq = 1 / u
b_sq = 1 / v
a = np.sqrt(max(a_sq, b_sq))
b = np.sqrt(min(a_sq, b_sq))
major_axis = 'x' if a_sq >= b_sq else 'y'
# Return if we have valid a, b
if a is not None and b is not None and a > 0 and b > 0:
return {
'type': 'ellipse',
'x_coef': a**2 if major_axis == 'x' else b**2,
'y_coef': b**2 if major_axis == 'x' else a**2,
'a': a,
'b': b,
'major_axis': major_axis,
'from_constraints': True
}
return None
def parse_hyperbola(self, fact_expr: str, main_conic_name: str = None) -> Optional[Dict]:
"""Parse hyperbola expression.
Args:
fact_expr: The fact expression string
main_conic_name: If provided, only match Expression(main_conic_name) = ...
This avoids matching secondary hyperbola expressions.
"""
# Build regex prefix based on main_conic_name
if main_conic_name:
expr_prefix = rf'Expression\({re.escape(main_conic_name)}\)\s*=\s*\('
else:
expr_prefix = r'Expression\(\w+\)\s*=\s*\('
# Horizontal: x^2/a - y^2/b = 1
match = re.search(expr_prefix + r'x\^2/(\d+)\s*-\s*y\^2/(\d+)\s*=\s*1\)', fact_expr)
if match:
a_sq = float(match.group(1))
b_sq = float(match.group(2))
return {
'type': 'hyperbola',
'a': np.sqrt(a_sq),
'b': np.sqrt(b_sq),
'a_squared': a_sq,
'b_squared': b_sq,
'orientation': 'horizontal'
}
# Vertical: y^2/a - x^2/b = 1
match = re.search(expr_prefix + r'y\^2/(\d+)\s*-\s*x\^2/(\d+)\s*=\s*1\)', fact_expr)
if match:
a_sq = float(match.group(1))
b_sq = float(match.group(2))
return {
'type': 'hyperbola',
'a': np.sqrt(a_sq),
'b': np.sqrt(b_sq),
'a_squared': a_sq,
'b_squared': b_sq,
'orientation': 'vertical'
}
# Horizontal: x^2/a - y^2 = 1 (b=1)
match = re.search(expr_prefix + r'x\^2/(\d+)\s*-\s*y\^2\s*=\s*1\)', fact_expr)
if match:
a_sq = float(match.group(1))
return {
'type': 'hyperbola',
'a': np.sqrt(a_sq),
'b': 1.0,
'a_squared': a_sq,
'b_squared': 1.0,
'orientation': 'horizontal'
}
# x^2 - y^2 = 1
if re.search(expr_prefix + r'x\^2\s*-\s*y\^2\s*=\s*1\)', fact_expr):
return {
'type': 'hyperbola',
'a': 1.0,
'b': 1.0,
'a_squared': 1.0,
'b_squared': 1.0,
'orientation': 'horizontal'
}
# Horizontal: x^2 - y^2/b = 1 (a=1, b^2 = b_val)
match = re.search(expr_prefix + r'x\^2\s*-\s*y\^2/(\d+)\s*=\s*1\)', fact_expr)
if match:
b_sq = float(match.group(1))
return {
'type': 'hyperbola',
'a': 1.0,
'b': np.sqrt(b_sq),
'a_squared': 1.0,
'b_squared': b_sq,
'orientation': 'horizontal'
}
# x^2 - y^2 = N (divide by N to normalize: x²/N - y²/N = 1)
match = re.search(expr_prefix + r'x\^2\s*-\s*y\^2\s*=\s*(\d+)\)', fact_expr)
if match:
n = float(match.group(1))
a = np.sqrt(n)
return {
'type': 'hyperbola',
'a': a,
'b': a,
'a_squared': n,
'b_squared': n,
'orientation': 'horizontal'
}
# x^2 - N*y^2 = M (x²/M - y²/(M/N) = 1)
match = re.search(expr_prefix + r'x\^2\s*-\s*(\d+)\*y\^2\s*=\s*(\d+)\)', fact_expr)
if match:
n = float(match.group(1))
m = float(match.group(2))
a_sq = m
b_sq = m / n
return {
'type': 'hyperbola',
'a': np.sqrt(a_sq),
'b': np.sqrt(b_sq),
'a_squared': a_sq,
'b_squared': b_sq,
'orientation': 'horizontal'
}
# N*x^2 - M*y^2 = K (x²/(K/N) - y²/(K/M) = 1)
match = re.search(expr_prefix + r'(\d+)\*x\^2\s*-\s*(\d+)\*y\^2\s*=\s*(\d+)\)', fact_expr)
if match:
n = float(match.group(1))
m = float(match.group(2))
k = float(match.group(3))
a_sq = k / n
b_sq = k / m
return {
'type': 'hyperbola',
'a': np.sqrt(a_sq),
'b': np.sqrt(b_sq),
'a_squared': a_sq,
'b_squared': b_sq,
'orientation': 'horizontal'
}
# x^2/a - y^2/b = -1 → y^2/b - x^2/a = 1 (vertical hyperbola)
match = re.search(expr_prefix + r'x\^2/(\d+)\s*-\s*y\^2/(\d+)\s*=\s*-1\)', fact_expr)
if match:
a_sq = float(match.group(1)) # becomes b² for vertical
b_sq = float(match.group(2)) # becomes a² for vertical
return {
'type': 'hyperbola',
'a': np.sqrt(b_sq),
'b': np.sqrt(a_sq),
'a_squared': b_sq,
'b_squared': a_sq,
'orientation': 'vertical'
}
# x^2-y^2/N=1 (no spaces) - horizontal
match = re.search(expr_prefix + r'x\^2-y\^2/(\d+)=1\)', fact_expr)
if match:
b_sq = float(match.group(1))
return {
'type': 'hyperbola',
'a': 1.0,
'b': np.sqrt(b_sq),
'a_squared': 1.0,
'b_squared': b_sq,
'orientation': 'horizontal'
}
# Vertical: y^2 - x^2/a = 1 (b=1 in standard form, here y² term positive)
match = re.search(expr_prefix + r'y\^2\s*-\s*x\^2/(\d+)\s*=\s*1\)', fact_expr)
if match:
b_sq = float(match.group(1))
return {
'type': 'hyperbola',
'a': 1.0, # For vertical hyperbola y²/a² - x²/b² = 1, a=1
'b': np.sqrt(b_sq),
'a_squared': 1.0,
'b_squared': b_sq,
'orientation': 'vertical'
}
# y^2 - x^2 = 1 (vertical hyperbola, a=1, b=1)
if re.search(expr_prefix + r'y\^2\s*-\s*x\^2\s*=\s*1\)', fact_expr):
return {
'type': 'hyperbola',
'a': 1.0,
'b': 1.0,
'a_squared': 1.0,
'b_squared': 1.0,
'orientation': 'vertical'
}
# Vertical symbolic: -x^2/b^2 + y^2/a^2 = 1
if re.search(expr_prefix + r'-x\^2/\w+\^?2?\s*\+\s*y\^2/\w+\^?2?\s*=\s*1\)', fact_expr):
return {
'type': 'hyperbola',
'a': 2.0, # default
'b': 1.5, # default
'a_squared': 4.0,
'b_squared': 2.25,
'symbolic': True,
'orientation': 'vertical'
}
# Vertical symbolic: y^2/a^2 - x^2/b^2 = 1
if re.search(expr_prefix + r'y\^2/\w+\^?2?\s*-\s*x\^2/\w+\^?2?\s*=\s*1\)', fact_expr):
return {
'type': 'hyperbola',
'a': 2.0, # default
'b': 1.5, # default
'a_squared': 4.0,
'b_squared': 2.25,
'symbolic': True,
'orientation': 'vertical'
}
# Horizontal symbolic: x^2/a^2 - y^2/b^2 = 1
if re.search(expr_prefix + r'x\^2/\w+\^?2?\s*-\s*y\^2/\w+\^?2?\s*=\s*1\)', fact_expr):
return {
'type': 'hyperbola',
'a': 2.0, # default
'b': 1.5, # default
'a_squared': 4.0,
'b_squared': 2.25,
'symbolic': True,
'orientation': 'horizontal'
}
# Horizontal symbolic: -y^2/b^2 + x^2/a^2 = 1
if re.search(expr_prefix + r'-y\^2/\w+\^?2?\s*\+\s*x\^2/\w+\^?2?\s*=\s*1\)', fact_expr):
return {
'type': 'hyperbola',
'a': 2.0, # default
'b': 1.5, # default
'a_squared': 4.0,
'b_squared': 2.25,
'symbolic': True,
'orientation': 'horizontal'
}
# Check for hyperbola type with asymptote/focus constraints (no explicit expression)
if 'Hyperbola' in fact_expr:
# Extract constraints
asymptote = self.parse_asymptote_slope(fact_expr)
coords = self.parse_coordinates(fact_expr)
focus_coords = [(n, c) for n, c in coords.items() if 'F' in n]
if asymptote or len(focus_coords) >= 2:
# Calculate a and b from constraints
if len(focus_coords) >= 2:
f1, f2 = focus_coords[0][1], focus_coords[1][1]
c = abs(f1[0] - f2[0]) / 2 if f1[1] == f2[1] == 0 else 3.0
else:
c = 3.0
if asymptote:
# b/a = asymptote, c² = a² + b²
# Let a be found from c and asymptote
# c² = a² + (a*slope)² = a²(1 + slope²)
a = c / np.sqrt(1 + asymptote**2)
b = a * asymptote
else:
a = c / np.sqrt(2)
b = a
return {
'type': 'hyperbola',
'a': a,
'b': b,
'a_squared': a**2,
'b_squared': b**2,
'from_constraints': True,
'orientation': 'horizontal' # Default, focus on x-axis
}
return None
def parse_parabola(self, fact_expr: str) -> Optional[Dict]:
"""Parse parabola expression."""
# y^2 = 4x, y^2 = 2*p*x, etc.
match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*(\d+)\*x\)', fact_expr)
if match:
coef = float(match.group(1))
return {
'type': 'parabola',
'p': coef / 4, # 4p = coef
'direction': 'right'
}
# x^2 = 4y, x^2 = 2*p*y
match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*(\d+)\*y\)', fact_expr)
if match:
coef = float(match.group(1))
return {
'type': 'parabola',
'p': coef / 4,
'direction': 'up'
}
# x^2 = -Ny (downward opening)
match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*-(\d+)\*y\)', fact_expr)
if match:
coef = float(match.group(1))
return {
'type': 'parabola',
'p': coef / 4,
'direction': 'down'
}
# x^2 = y/N (small opening upward)
match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*y/(\d+)\)', fact_expr)
if match:
divisor = float(match.group(1))
return {
'type': 'parabola',
'p': 1 / (4 * divisor),
'direction': 'up'
}
# y = -x^2/N (downward parabola in vertex form)
match = re.search(r'Expression\(\w+\)\s*=\s*\(y\s*=\s*-x\^2/(\d+)\)', fact_expr)
if match:
divisor = float(match.group(1))
# y = -x²/N → x² = -Ny → 4p = N → p = N/4
return {
'type': 'parabola',
'p': divisor / 4,
'direction': 'down'
}
# y = x^2/N (upward parabola in vertex form)
match = re.search(r'Expression\(\w+\)\s*=\s*\(y\s*=\s*x\^2/(\d+)\)', fact_expr)
if match:
divisor = float(match.group(1))
# y = x²/N → x² = Ny → 4p = N → p = N/4
return {
'type': 'parabola',
'p': divisor / 4,
'direction': 'up'
}
# y^2 = p*x (symbolic p, single coefficient)
if re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*\w+\*x\)', fact_expr):
return {
'type': 'parabola',
'p': 1.0, # Default, will be optimized
'direction': 'right',
'symbolic': True
}
# x^2 = p*y (symbolic p, single coefficient)
if re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*\w+\*y\)', fact_expr):
return {
'type': 'parabola',
'p': 1.0,
'direction': 'up',
'symbolic': True
}
# y^2 = 2*(p*x)
if re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*2\*\(\w+\*x\)\)', fact_expr):
return {
'type': 'parabola',
'p': 1.0, # Default, will be optimized
'direction': 'right',
'symbolic': True
}
# x^2 = 2*(p*y)
if re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*2\*\(\w+\*y\)\)', fact_expr):
return {
'type': 'parabola',
'p': 1.0,
'direction': 'up',
'symbolic': True
}
# y = 2*x^2 or y = a*x^2 (vertex form)
match = re.search(r'Expression\(\w+\)\s*=\s*\(y\s*=\s*(\d*)\*?x\^2\)', fact_expr)
if match:
coef = match.group(1)
a = float(coef) if coef else 1.0
return {
'type': 'parabola',
'p': 1 / (4 * a),
'direction': 'up'
}
# y = x^2/8 (division form)
match = re.search(r'Expression\(\w+\)\s*=\s*\(y\s*=\s*x\^2/(\d+)\)', fact_expr)
if match:
divisor = float(match.group(1))
return {
'type': 'parabola',
'p': divisor / 4,
'direction': 'up'
}
# y^2 = -8*x (left opening)
match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*-(\d+)\*x\)', fact_expr)
if match:
coef = float(match.group(1))
return {
'type': 'parabola',
'p': coef / 4,
'direction': 'left'
}
# y^2 = 2*p*x (symbolic p) - parabola opening right
if re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*2\*p\*x\)', fact_expr):
return {
'type': 'parabola',
'p': 1.0, # Default, will be optimized
'direction': 'right',
'symbolic': True
}
# x^2 = 2*p*y (symbolic p) - parabola opening up
if re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*2\*p\*y\)', fact_expr):
return {
'type': 'parabola',
'p': 1.0, # Default, will be optimized
'direction': 'up',
'symbolic': True
}
# y^2 = x (p = 1/4, so 4p = 1) - parabola opening right
if re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*x\)', fact_expr):
return {
'type': 'parabola',
'p': 0.25, # y^2 = 4px, so 4p = 1, p = 0.25
'direction': 'right'
}
# x^2 = y (p = 1/4) - parabola opening up
if re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*y\)', fact_expr):
return {
'type': 'parabola',
'p': 0.25,
'direction': 'up'
}
# Check for Parabola type with geometric constraints
if 'Parabola' in fact_expr:
coords = self.parse_coordinates(fact_expr)
# Determine direction from constraints
direction = None
if 'PointOnCurve(Focus(' in fact_expr:
if 'xAxis' in fact_expr:
direction = 'right' # Focus on x-axis → horizontal parabola
elif 'yAxis' in fact_expr:
direction = 'up' # Focus on y-axis → vertical parabola
# Check for vertex at origin
vertex_at_origin = 'Vertex(' in fact_expr and 'Origin' in fact_expr
# Try to find p from point on curve + distance to focus
# Pattern: Distance(P, Focus(G)) = d
dist_match = re.search(r'Distance\((\w+),\s*Focus\(\w+\)\)\s*=\s*(\d+)', fact_expr)
if dist_match and vertex_at_origin:
pt_name = dist_match.group(1)
dist_val = float(dist_match.group(2))
if pt_name in coords:
px, py = coords[pt_name]
# For parabola y² = 4px with vertex at origin:
# Distance from point to focus = |x + p|
# For right-opening: focus at (p, 0), dist = sqrt((x-p)² + y²)
# We can solve for p
if direction == 'right':
# dist² = (px - p)² + py²
# y² = 4px → py² = 4p*px
# Substitute: dist² = (px - p)² + 4p*px
# dist² = px² - 2*px*p + p² + 4p*px = px² + 2*px*p + p² = (px + p)²
# So dist = |px + p|, p = dist - px (assuming px > 0)
p = (dist_val - px) if px >= 0 else (dist_val + px)
if p > 0:
return {
'type': 'parabola',
'p': p,
'direction': 'right',
'from_constraints': True
}
elif direction == 'up':
p = (dist_val - py) if py >= 0 else (dist_val + py)
if p > 0:
return {
'type': 'parabola',
'p': p,
'direction': 'up',
'from_constraints': True
}
# Look for focus coordinate in coords
for name, (px, py) in coords.items():
# If this is a focus (F in name) or explicitly marked as focus
if 'F' in name and (f'Focus(' in fact_expr):
if abs(py) < 0.01: # Focus on x-axis
return {
'type': 'parabola',
'p': abs(px), # Focus at (p, 0)
'direction': 'right' if px > 0 else 'left',
'from_constraints': True
}
elif abs(px) < 0.01: # Focus on y-axis
return {
'type': 'parabola',
'p': abs(py),
'direction': 'up' if py > 0 else 'down',
'from_constraints': True
}
# Default: parabola with vertex at origin, direction from constraints
if vertex_at_origin and direction:
return {
'type': 'parabola',
'p': 1.0, # Default, will be optimized
'direction': direction,
'symbolic': True
}
return None
def parse_coordinates(self, fact_expr: str) -> Dict[str, Tuple[float, float]]:
"""Extract point coordinates."""
coords = {}
# Use a more robust pattern that handles nested parentheses
# Match: Coordinate(Name) = (x_expr, y_expr)
# Find all Coordinate(...) = (...) patterns
coord_pattern = r'Coordinate\((\w+)\)\s*=\s*\(([^;]+)\)'
for match in re.finditer(coord_pattern, fact_expr):
name = match.group(1)
coord_str = match.group(2)
# Split by comma, but handle nested parentheses
depth = 0
parts = []
current = ""
for char in coord_str:
if char == '(':
depth += 1
current += char
elif char == ')':
depth -= 1
current += char
elif char == ',' and depth == 0:
parts.append(current.strip())
current = ""
else:
current += char
parts.append(current.strip())
if len(parts) >= 2:
try:
x = parts[0].replace('sqrt', 'np.sqrt').replace('^', '**')
y = parts[1].replace('sqrt', 'np.sqrt').replace('^', '**')
x_val = float(eval(x, {"np": np, "__builtins__": {}}))
y_val = float(eval(y, {"np": np, "__builtins__": {}}))
coords[name] = (x_val, y_val)
except:
pass
return coords
def parse_eccentricity(self, fact_expr: str) -> Optional[float]:
"""Extract eccentricity constraint."""
# sqrt pattern
match = re.search(r'Eccentricity\(\w+\)\s*=\s*sqrt\((\d+)\)', fact_expr)
if match:
return np.sqrt(float(match.group(1)))
# Fraction pattern (MUST be checked BEFORE decimal pattern!)
match = re.search(r'Eccentricity\(\w+\)\s*=\s*(\d+)/(\d+)', fact_expr)
if match:
return float(match.group(1)) / float(match.group(2))
# Simple decimal pattern
match = re.search(r'Eccentricity\(\w+\)\s*=\s*([\d.]+)', fact_expr)
if match:
return float(match.group(1))
return None
def parse_asymptote_slope(self, fact_expr: str) -> Optional[float]:
"""Extract asymptote slope for hyperbola.
Supports patterns like:
- y = sqrt(2)*x
- y = pm*sqrt(2)*x
- y = pm*(sqrt(2)/2)*x or y = pm*(sqrt(2)/2)*X
- y = 4/3*x
- y = pm*3*x
- y = pm*(sqrt(2)*x)
"""
# Pattern: y = sqrt(N)*x
match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*sqrt\((\d+)\)\*[xX]\)', fact_expr)
if match:
return np.sqrt(float(match.group(1)))
# Pattern: y = pm*sqrt(N)*x or y = pm*(sqrt(N)*x)
match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*pm\*\(?sqrt\((\d+)\)\*?[xX]\)?', fact_expr)
if match:
return np.sqrt(float(match.group(1)))
# Pattern: y = pm*(sqrt(N)/M)*x (e.g., sqrt(2)/2)
match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*pm\*\(sqrt\((\d+)\)/(\d+)\)\*[xX]\)', fact_expr)
if match:
return np.sqrt(float(match.group(1))) / float(match.group(2))
# Pattern: y = A/B*x (fraction slope)
match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*(\d+)/(\d+)\*[xX]\)', fact_expr)
if match:
return float(match.group(1)) / float(match.group(2))
# Pattern: y = pm*N*x (integer slope)
match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*pm\*(\d+)\*[xX]\)', fact_expr)
if match:
return float(match.group(1))
# Pattern: y = N*x (simple integer slope)
match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*(\d+)\*[xX]\)', fact_expr)
if match:
return float(match.group(1))
# Pattern: pm*A*y+B*x=0 → y = ±(B/A)*x, slope = B/A
match = re.search(r'Asymptote.*?=\s*\(pm\*(\d+)\*y\+(\d+)\*x=0\)', fact_expr)
if match:
a = float(match.group(1))
b = float(match.group(2))
return b / a
# Pattern: pm*(A/B)*x or y = pm*(A/B)*x
match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*pm\*\((\d+)/(\d+)\)\*[xX]\)', fact_expr)
if match:
return float(match.group(1)) / float(match.group(2))
return None