WendingGao commited on
Commit
0dd0bac
·
verified ·
1 Parent(s): b213012

Add files using upload-large-folder tool

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +1 -0
  2. .gitignore +5 -0
  3. README.md +250 -0
  4. annotations/dev.json +0 -0
  5. annotations/samples.json +1009 -0
  6. annotations/test.json +0 -0
  7. annotations/train.json +0 -0
  8. create_samples.py +71 -0
  9. data/dev_en.json +0 -0
  10. data/test_en.json +0 -0
  11. data/train_en.json +0 -0
  12. requirements.txt +48 -0
  13. results/.DS_Store +0 -0
  14. results/dev/.DS_Store +0 -0
  15. results/dev/parabola/problem_0025.png +3 -0
  16. results/dev/parabola/problem_0145.png +3 -0
  17. results/dev/parabola/problem_0150.png +3 -0
  18. results/dev/parabola/problem_0151.png +3 -0
  19. results/dev/parabola/problem_0179.png +3 -0
  20. results/dev/parabola/problem_0186.png +3 -0
  21. results/dev/parabola/problem_0409.png +3 -0
  22. results/dev/parabola/problem_0541.png +3 -0
  23. results/dev/parabola/problem_0569.png +3 -0
  24. results/dev/parabola/problem_0596.png +3 -0
  25. results/dev/parabola/problem_0637.png +3 -0
  26. results/dev/parabola/problem_0743.png +3 -0
  27. results/dev/parabola/problem_0794.png +3 -0
  28. results/dev/parabola/problem_0804.png +3 -0
  29. results/dev/parabola/problem_0958.png +3 -0
  30. results/dev/summary.json +0 -0
  31. results/test/.DS_Store +0 -0
  32. results/test/summary.json +0 -0
  33. results/train/.DS_Store +0 -0
  34. results/train/summary.json +0 -0
  35. src/__pycache__/sdf_geo_solver.cpython-313.pyc +3 -0
  36. src/main.py +68 -0
  37. src/sdf_geo/__init__.py +51 -0
  38. src/sdf_geo/__pycache__/__init__.cpython-313.pyc +0 -0
  39. src/sdf_geo/__pycache__/constraints.cpython-313.pyc +0 -0
  40. src/sdf_geo/__pycache__/optimizer.cpython-313.pyc +0 -0
  41. src/sdf_geo/__pycache__/parser.cpython-313.pyc +0 -0
  42. src/sdf_geo/__pycache__/primitives.cpython-313.pyc +0 -0
  43. src/sdf_geo/__pycache__/processor.cpython-313.pyc +0 -0
  44. src/sdf_geo/__pycache__/renderer.cpython-313.pyc +0 -0
  45. src/sdf_geo/constraints.py +82 -0
  46. src/sdf_geo/optimizer.py +81 -0
  47. src/sdf_geo/parser.py +1184 -0
  48. src/sdf_geo/primitives.py +354 -0
  49. src/sdf_geo/processor.py +1218 -0
  50. src/sdf_geo/renderer.py +98 -0
.gitattributes CHANGED
@@ -58,3 +58,4 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
58
  # Video files - compressed
59
  *.mp4 filter=lfs diff=lfs merge=lfs -text
60
  *.webm filter=lfs diff=lfs merge=lfs -text
61
+ src/__pycache__/sdf_geo_solver.cpython-313.pyc filter=lfs diff=lfs merge=lfs -text
.gitignore ADDED
@@ -0,0 +1,5 @@
 
 
 
 
 
 
1
+ .DS_Store
2
+ __pycache__/
3
+ *.pyc
4
+ *.egg-info/
5
+ .env
README.md ADDED
@@ -0,0 +1,250 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Image_SDF
2
+
3
+ **Automatic Diagram Generation for Analytic Geometry Problems using Signed Distance Fields**
4
+
5
+ <p align="center">
6
+ <img src="results/test/ellipse/problem_2063.png" width="600" alt="Example Output">
7
+ </p>
8
+
9
+ <p align="center">
10
+ <img src="https://img.shields.io/badge/Python-3.9%2B-blue.svg" alt="Python">
11
+ <img src="https://img.shields.io/badge/PyTorch-2.0%2B-ee4c2c.svg" alt="PyTorch">
12
+ <img src="https://img.shields.io/badge/Accuracy-96.7%25-brightgreen.svg" alt="Accuracy">
13
+ <img src="https://img.shields.io/badge/Problems-10,861-orange.svg" alt="Problems">
14
+ <img src="https://img.shields.io/badge/License-MIT-green.svg" alt="License">
15
+ </p>
16
+
17
+ ---
18
+
19
+ ## Introduction
20
+
21
+ **Image_SDF** is an automatic system that converts mathematical geometry problem text into accurate visualizations. By leveraging **Signed Distance Fields (SDF)** combined with differentiable optimization, the system can automatically generate precise conic section diagrams from symbolic geometric expressions.
22
+
23
+ Traditional geometry diagram generation often relies on manual drawing or rule-based methods. This system takes a different approach: it models geometric constraints as differentiable loss functions and uses gradient-based optimization to find curve parameters that satisfy all constraints, ultimately rendering high-quality geometric diagrams.
24
+
25
+ ### Key Features
26
+
27
+ - **Fully Automated**: Generate PNG diagrams directly from JSON-formatted geometry problems without manual intervention
28
+ - **High Accuracy**: Achieves **96.7%** validation pass rate on parseable problems
29
+ - **Large-Scale Validation**: Tested on **10,861** geometry problems across 3 datasets
30
+ - **Rigorous Verification**: Multi-dimensional geometric property validation including focus position, eccentricity, and asymptote slope
31
+
32
+ ---
33
+
34
+ ## Supported Curve Types
35
+
36
+ The system supports four classical conic sections, each with complete SDF representation and constraint validation:
37
+
38
+ | Curve Type | Standard Form | Validated Properties |
39
+ |------------|---------------|---------------------|
40
+ | **Ellipse** | x²/a² + y²/b² = 1 | Focus distance c²=a²-b², eccentricity, points on curve |
41
+ | **Hyperbola** | x²/a² - y²/b² = 1 | Focus distance c²=a²+b², asymptote slope, eccentricity |
42
+ | **Parabola** | y² = 4px | Focus position, directrix equation, points on curve |
43
+ | **Circle** | (x-h)² + (y-k)² = r² | Center position, radius, points on curve |
44
+
45
+ ---
46
+
47
+ ## How It Works
48
+
49
+ The system follows a four-stage pipeline:
50
+
51
+ ```
52
+ Text Parsing → SDF Construction → Constraint Optimization → Diagram Rendering
53
+ ```
54
+
55
+ ### 1. Text Parsing
56
+
57
+ Extract geometric parameters from mathematical expressions. For example:
58
+
59
+ ```
60
+ Input: "ellipse x²/4 + y²/9 = 1"
61
+ Output: Ellipse(a=2, b=3, center=(0,0))
62
+ ```
63
+
64
+ The parser supports various expression formats including fractions, radicals, and LaTeX-formatted mathematical expressions.
65
+
66
+ ### 2. SDF Construction
67
+
68
+ Build a signed distance field function for each curve type. The SDF value represents the signed distance from any point in space to the curve boundary:
69
+ - Positive: point is outside the curve
70
+ - Negative: point is inside the curve
71
+ - Zero: point is exactly on the curve
72
+
73
+ ### 3. Constraint Optimization
74
+
75
+ Optimize curve parameters via gradient descent to satisfy all geometric constraints:
76
+
77
+ ```python
78
+ # Total loss = point constraint + focus constraint + eccentricity constraint + crowd penalty
79
+ L_total = λ₁·L_point + λ₂·L_focus + λ₃·L_ecc + λ₄·L_crowd
80
+ ```
81
+
82
+ Using the AdamW optimizer, convergence typically occurs within 100-200 iterations.
83
+
84
+ ### 4. Diagram Rendering
85
+
86
+ Extract the zero-level set of the SDF (i.e., the curve itself) and render in Chinese Gaokao (高考) analytic geometry style: white background, black curves, arrow axes through origin with O/x/y labels, feature point annotations (foci, vertices), and auxiliary elements (asymptotes, directrix) as dashed lines. No problem text, grid, or legend is included in the output.
87
+
88
+ ---
89
+
90
+ ## Datasets and Results
91
+
92
+ The system has been fully tested on three datasets:
93
+
94
+ | Dataset | Total Problems | Parseable | Successful | Parseable Accuracy |
95
+ |---------|----------------|-----------|------------|-------------------|
96
+ | dev | 1,035 | 809 | 788 | **97.4%** |
97
+ | test | 2,069 | 1,649 | 1,596 | **96.8%** |
98
+ | train | 7,757 | 6,052 | 5,849 | **96.6%** |
99
+ | **Total** | **10,861** | **8,510** | **8,233** | **96.7%** |
100
+
101
+ > **Note**: "Parseable" refers to problems with explicit geometric expressions (e.g., x²/4 + y²/9 = 1) rather than implicit or parametric forms. Approximately 22% of problems cannot be parsed due to overly complex or incomplete expressions.
102
+
103
+ ### Curve Type Distribution
104
+
105
+ | Type | Dev | Test | Train | Total |
106
+ |------|-----|------|-------|-------|
107
+ | Ellipse | 220 | 467 | 1,734 | 2,421 |
108
+ | Hyperbola | 293 | 565 | 2,025 | 2,883 |
109
+ | Parabola | 262 | 532 | 2,000 | 2,794 |
110
+ | Circle | 13 | 32 | 90 | 135 |
111
+
112
+ ---
113
+
114
+ ## Installation and Usage
115
+
116
+ ### Requirements
117
+
118
+ - Python >= 3.9
119
+ - PyTorch >= 2.0.0
120
+ - NumPy >= 1.24.0
121
+ - Matplotlib >= 3.7.0
122
+ - tqdm >= 4.65.0
123
+
124
+ ### Install Dependencies
125
+
126
+ ```bash
127
+ pip install -r requirements.txt
128
+ ```
129
+
130
+ ### Running Examples
131
+
132
+ ```bash
133
+ # Process test dataset
134
+ python src/main.py --input data/test_en.json --output results/test/
135
+
136
+ # Process dev dataset
137
+ python src/main.py --input data/dev_en.json --output results/dev/
138
+
139
+ # Process train dataset (~30 minutes)
140
+ python src/main.py --input data/train_en.json --output results/train/
141
+
142
+ # Process only first 100 problems with verbose output
143
+ python src/main.py -i data/test_en.json -o results/test/ -m 100 -v
144
+ ```
145
+
146
+ ### Command Line Arguments
147
+
148
+ | Argument | Description | Default |
149
+ |----------|-------------|---------|
150
+ | `-i, --input` | Input JSON file path | `data/test_en.json` |
151
+ | `-o, --output` | Output directory | `results/` |
152
+ | `-m, --max` | Maximum number of problems to process | All |
153
+ | `-v, --verbose` | Enable verbose output | False |
154
+
155
+ ### Python API
156
+
157
+ ```python
158
+ from src.sdf_geo import SDFBatchProcessor
159
+
160
+ # Create processor
161
+ processor = SDFBatchProcessor(output_dir='results/')
162
+
163
+ # Batch processing
164
+ results = processor.process_batch('data/test_en.json', max_problems=100)
165
+
166
+ # Calculate success rate
167
+ success_rate = sum(r['success'] for r in results) / len(results)
168
+ print(f"Success rate: {success_rate:.1%}")
169
+ ```
170
+
171
+ ---
172
+
173
+ ## Project Structure
174
+
175
+ ```
176
+ Image_SDF/
177
+ ├── data/
178
+ │ ├── dev_en.json # Dev set (1,035 problems)
179
+ │ ├── test_en.json # Test set (2,069 problems)
180
+ │ └── train_en.json # Train set (7,757 problems)
181
+ ├── results/
182
+ │ ├── dev/ # Dev set results
183
+ │ ├── test/ # Test set results
184
+ │ └── train/ # Train set results
185
+ ├── samples/ # Sample images (3 per curve type per dataset)
186
+ ├── src/
187
+ │ ├── main.py # CLI entry point
188
+ │ └── sdf_geo/ # Core modules
189
+ │ ├── primitives.py # SDF geometric primitives
190
+ │ ├── constraints.py # Differentiable constraint functions
191
+ │ ├── parser.py # Expression parser
192
+ │ ├── optimizer.py # Gradient optimizer
193
+ │ ├── processor.py # Batch processing, validation & visualization
194
+ │ └── renderer.py # SDF field evaluation & curve rendering
195
+ ├── create_samples.py # Generate sample images from results
196
+ ├── requirements.txt
197
+ └── README.md
198
+ ```
199
+
200
+ ---
201
+
202
+ ## Output Format
203
+
204
+ Each problem generates a PNG image in Chinese Gaokao (高考) analytic geometry style, containing:
205
+
206
+ - **Geometric Curve**: Black curve rendered from the SDF zero-level set on white background
207
+ - **Feature Point Annotations**: Foci (F₁, F₂), vertices, center, marked as small black dots with labels
208
+ - **Coordinate System**: Arrow axes through origin with O, x, y labels (no grid)
209
+ - **Auxiliary Elements**: Asymptotes and directrix rendered as dashed lines
210
+
211
+ Results are organized by curve type:
212
+
213
+ ```
214
+ results/test/
215
+ ├── summary.json # Statistics summary
216
+ ├── circle/ # Circle diagrams
217
+ ├── ellipse/ # Ellipse diagrams
218
+ ├── hyperbola/ # Hyperbola diagrams
219
+ └── parabola/ # Parabola diagrams
220
+ ```
221
+
222
+ ---
223
+
224
+ ## Validation Standards
225
+
226
+ The system employs multi-dimensional geometric property validation to ensure mathematical correctness of generated diagrams:
227
+
228
+ | Validation Item | Tolerance | Description |
229
+ |-----------------|-----------|-------------|
230
+ | Point on curve | 0.03 | SDF(p) ≈ 0 |
231
+ | Eccentricity | 0.05 | \|e_calculated - e_target\| < tol |
232
+ | Focus position | 0.05 | \|c_calculated - c_given\| < tol |
233
+ | Asymptote slope | 0.05 | \|b/a - slope\| < tol |
234
+
235
+ ---
236
+
237
+ ## Methodology
238
+
239
+ This implementation is based on the methodology described in:
240
+
241
+ > **GeoSDF: Plane Geometry Diagram Synthesis via Signed Distance Field**
242
+ > arXiv:2506.13492
243
+
244
+ The core ideas of using signed distance fields for geometric representation and differentiable optimization for constraint satisfaction are derived from this work.
245
+
246
+ ---
247
+
248
+ ## License
249
+
250
+ MIT License
annotations/dev.json ADDED
The diff for this file is too large to render. See raw diff
 
annotations/samples.json ADDED
@@ -0,0 +1,1009 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ [
2
+ {
3
+ "dataset": "dev",
4
+ "index": 6,
5
+ "conic_type": "circle",
6
+ "image_path": "samples/dev/circle/problem_0006.png",
7
+ "problem": {
8
+ "text": "Given the circle $(x+1)^{2}+y^{2}=36$ with center $M$, let $A$ be any point on the circle, and let $N(1 , 0)$. The perpendicular bisector of segment $AN$ intersects $MA$ at point $P$. Then the trajectory equation of the moving point $P$ is?",
9
+ "fact_expressions": "G: Circle;Expression(G) = (y^2 + (x + 1)^2 = 36);Center(G) = M;M: Point;A: Point;PointOnCurve(A, G);N: Point;Coordinate(N) = (1, 0);Intersection(PerpendicularBisector(LineSegmentOf(A,N)),LineSegmentOf(M,A)) = P;P: Point",
10
+ "query_expressions": "LocusEquation(P)",
11
+ "answer_expressions": "x^2/9+y^2/8=1",
12
+ "process": "Since the circle $(x+2)^{2}+y^{2}=36$ has center $M(-1,0)$ and radius $r=6$, let point $P(x,y)$. Since the perpendicular bisector of segment $AN$ intersects $MA$ at point $P$, we have $|PN|=|PA|$. Therefore, $|PM|+|PN|=|PM|+|PA|=|MA|=6>|MN|=2$. Hence, the trajectory of point $P$ is an ellipse with foci at $M(-1,0)$ and $N(1,0)$, and major axis length $2a=6$, so $b=\\sqrt{a^{2}-c^{2}}=\\sqrt{9-1}=2\\sqrt{2}$. Thus, the equation of the trajectory of moving point $P$ is $\\frac{x^{2}}{9}+\\frac{y^{2}}{8}=1$."
13
+ },
14
+ "sdf_annotation": {
15
+ "params": {
16
+ "center": [
17
+ 1.0,
18
+ 0.0
19
+ ],
20
+ "radius": 6.0
21
+ },
22
+ "optimization": {
23
+ "final_loss": 0.0,
24
+ "converged": true
25
+ },
26
+ "coords": {}
27
+ }
28
+ },
29
+ {
30
+ "dataset": "dev",
31
+ "index": 441,
32
+ "conic_type": "circle",
33
+ "image_path": "samples/dev/circle/problem_0441.png",
34
+ "problem": {
35
+ "text": "A moving circle is externally tangent to the circle $Q_{1}$: $(x+3)^{2}+y^{2}=1$ and internally tangent to the circle $Q_{2}$: $(x-3)^{2}+y^{2}=81$. Then, the trajectory equation of the center of this moving circle is?",
36
+ "fact_expressions": "G: Circle;IsOutTangent(G,Q1) = True;Q1: Circle;Expression(Q1) = ((x+3)^2+y^2=1);Q2: Circle;Expression(Q2) = ((x-3)^2+y^2=81);IsInTangent(G,Q2) = True",
37
+ "query_expressions": "LocusEquation(Center(G))",
38
+ "answer_expressions": "x^2/25+y^2/16=1",
39
+ "process": "Let the center of the moving circle be Q(x, y), with radius R. Since the moving circle is externally tangent to the circle Q_{1}:(x+3)^{2}+y^{2}=1 and internally tangent to the circle Q_{2}:(x-3)^{2}+y^{2}=81, we have |QQ_{1}| = R + 1, |QQ_{2}| = 9 - R. Therefore, |QQ_{1}| + |QQ_{2}| = 10 > 6 = |Q_{1}Q_{2}|. Thus, the locus of the center of the moving circle is an ellipse with foci at Q_{1} and Q_{2}. Hence, 2a = 10, a = 5, c = 3, b^{2} = 16. Therefore, the equation of the locus of the center of the moving circle is \\frac{x^{2}}{25}+\\frac{y^{2}}{16}=1."
40
+ },
41
+ "sdf_annotation": {
42
+ "params": {
43
+ "center": [
44
+ -3.0,
45
+ 0.0
46
+ ],
47
+ "radius": 1.0
48
+ },
49
+ "optimization": {
50
+ "final_loss": 0.0,
51
+ "converged": true
52
+ },
53
+ "coords": {}
54
+ }
55
+ },
56
+ {
57
+ "dataset": "dev",
58
+ "index": 669,
59
+ "conic_type": "circle",
60
+ "image_path": "samples/dev/circle/problem_0669.png",
61
+ "problem": {
62
+ "text": "Given the circle $C$: $x^{2}+y^{2}=25$, draw a line $l$ through point $M(-2,3)$ intersecting the circle $C$ at points $A$ and $B$. Tangents to the circle are drawn at points $A$ and $B$, respectively. When the two tangents intersect at point $N$, what is the trajectory equation of point $N$?",
63
+ "fact_expressions": "C: Circle;Expression(C) = (x^2 + y^2 = 25);M: Point;l: Line;Coordinate(M) = (-2, 3);PointOnCurve(M, l);A: Point;B: Point;Intersection(l, C) = {A, B};L1: Line;L2: Line;TangentOnPoint(A,C)=L1;TangentOnPoint(B,C)=L2;N: Point;Intersection(L1, L2) = N",
64
+ "query_expressions": "LocusEquation(N)",
65
+ "answer_expressions": "2*x-3*y+25=0",
66
+ "process": "Consider the following problem: Given a circle $ C: x^{2} + y^{2} = r^{2} $ ($ r > 0 $) and a point $ P(a, b) $. If point $ P $ lies inside $ C $, draw a line $ l $ through $ P $ intersecting $ C $ at points $ A $ and $ B $. Tangents to $ C $ are drawn at points $ A $ and $ B $ respectively. When these two tangents intersect at point $ Q $, find the locus equation of point $ Q $. The center of circle $ C: x^{2} + y^{2} = r^{2} $ is $ (0, 0) $. Let $ A(x_{1}, y_{1}) $, $ B(x_{2}, y_{2}) $, $ Q(x_{0}, y_{0}) $. Since $ AQ $ is tangent to circle $ C $, we have $ AQ \\perp CA $. Therefore, $ (x_{1} - x_{0})(x_{1} - 0) + (y_{1} - y_{0})(y_{1} - 0) = 0 $, that is, $ x^{2}_{1} - x_{0}x_{1} + y^{2}_{1} - y_{0}y_{1} = 0 $. Since $ x^{2} + y^{2} = r^{2} $, it follows that $ x_{0}x_{1} + y_{0}y_{1} = r^{2} $. Similarly, $ x_{0}x_{2} + y_{0}y_{2} = r^{2} $. Hence, the equation of the line passing through points $ A $ and $ B $ is $ xx_{0} + yy_{0} = r^{2} $. Since line $ AB $ passes through point $ (a, b) $, substituting gives $ ax_{0} + by_{0} = r^{2} $. Therefore, the locus equation of point $ Q $ is: $ ax + by = r^{2} $. According to the problem, the locus equation of point $ N $ is $ 2x - 3y + 25 = 0 $."
67
+ },
68
+ "sdf_annotation": {
69
+ "params": {
70
+ "center": [
71
+ 0.0,
72
+ 0.0
73
+ ],
74
+ "radius": 5.0
75
+ },
76
+ "optimization": {
77
+ "final_loss": 0.0,
78
+ "converged": true
79
+ },
80
+ "coords": {}
81
+ }
82
+ },
83
+ {
84
+ "dataset": "dev",
85
+ "index": 1,
86
+ "conic_type": "ellipse",
87
+ "image_path": "samples/dev/ellipse/problem_0001.png",
88
+ "problem": {
89
+ "text": "Given the ellipse $\\frac{x^{2}}{4}+y^{2}=1$ with left and right foci $F_{1}$, $F_{2}$, point $P$ is a moving point on the ellipse. Then the range of values of $\\overrightarrow{P F_{1}} \\cdot \\overrightarrow{P F_{2}}$ is?",
90
+ "fact_expressions": "G: Ellipse;P: Point;F1: Point;F2: Point;Expression(G) = (x^2/4 + y^2 = 1);LeftFocus(G) = F1;RightFocus(G) = F2;PointOnCurve(P, G)",
91
+ "query_expressions": "Range(DotProduct(VectorOf(P, F1), VectorOf(P, F2)))",
92
+ "answer_expressions": "[-2, 1]",
93
+ "process": "Let P(x,y) be an arbitrary point on the ellipse, then \\overrightarrow{PF_{1}}=(-\\sqrt{3}-x,-y), \\overrightarrow{PF_{2}}=(\\sqrt{3}-x,-y). Therefore, \\overrightarrow{PF_{1}}\\cdot\\overrightarrow{PF_{2}}=(-\\sqrt{3}-x,-y)\\cdot(\\sqrt{3}-x,-y)=x^{2}+y^{2}-3=x^{2}+1-\\frac{x^{2}}{4}=\\frac{3}{4}x^{2}-2. Since P lies on the ellipse, -2\\leqslant x \\leqslant 2, so -2\\leqslant \\frac{3}{4}x^{2}-2 \\leqslant 1, that is, the range of \\overrightarrow{PF_{1}}\\cdot\\overrightarrow{PF_{2}} is [-2,1]."
94
+ },
95
+ "sdf_annotation": {
96
+ "params": {
97
+ "a": 2.0,
98
+ "b": 1.0,
99
+ "major_axis": "x",
100
+ "x_coef": 4.0,
101
+ "y_coef": 1.0
102
+ },
103
+ "optimization": {
104
+ "final_loss": 0.0,
105
+ "converged": true,
106
+ "note": "using explicit params"
107
+ },
108
+ "coords": {}
109
+ }
110
+ },
111
+ {
112
+ "dataset": "dev",
113
+ "index": 524,
114
+ "conic_type": "ellipse",
115
+ "image_path": "samples/dev/ellipse/problem_0524.png",
116
+ "problem": {
117
+ "text": "Point $P$ lies on the ellipse $\\frac{x^{2}}{16}+\\frac{y^{2}}{9}=1$. What are the maximum and minimum distances from point $P$ to the line $3x-4y=24$?",
118
+ "fact_expressions": "G: Ellipse;H: Line;P: Point;Expression(G) = (x^2/16 + y^2/9 = 1);Expression(H) = (3*x - 4*y = 24);PointOnCurve(P, G)",
119
+ "query_expressions": "Max(Distance(P,H));Min(Distance(P,H))",
120
+ "answer_expressions": "12*(2+sqrt(2))/5\n12*(2-sqrt(2))/5",
121
+ "process": "Let the coordinates of point P be (4\\cos\\theta,3\\sin\\theta). The distance d from point P to the line 3x-4y=24 reaches its maximum when \\cos(\\theta+\\frac{\\pi}{4})=-1, and reaches its minimum when \\cos(\\theta+\\frac{\\pi}{4})=1, with the minimum value being \\frac{12(2-}{"
122
+ },
123
+ "sdf_annotation": {
124
+ "params": {
125
+ "a": 4.0,
126
+ "b": 3.0,
127
+ "major_axis": "x",
128
+ "x_coef": 16.0,
129
+ "y_coef": 9.0
130
+ },
131
+ "optimization": {
132
+ "final_loss": 0.0,
133
+ "converged": true,
134
+ "note": "using explicit params"
135
+ },
136
+ "coords": {}
137
+ }
138
+ },
139
+ {
140
+ "dataset": "dev",
141
+ "index": 1034,
142
+ "conic_type": "ellipse",
143
+ "image_path": "samples/dev/ellipse/problem_1034.png",
144
+ "problem": {
145
+ "text": "Given the ellipse $\\frac{x^{2}}{25}+\\frac{y^{2}}{9}=1$, the left and right foci are denoted as $F_{1}$ and $F_{2}$ respectively. A line passing through $F_{1}$ and perpendicular to the major axis intersects the ellipse at points $A$ and $B$. Find the radius of the incircle of triangle $ABF_{2}$.",
146
+ "fact_expressions": "G: Ellipse;H:Line;A: Point;B: Point;F1: Point;F2: Point;Expression(G) = (x^2/25 + y^2/9 = 1);LeftFocus(G)=F1;RightFocus(G)=F2;PointOnCurve(F1,H);IsPerpendicular(H,MajorAxis(G));Intersection(H,G) = {A, B}",
147
+ "query_expressions": "Radius(InscribedCircle(TriangleOf(A,B,F2)))",
148
+ "answer_expressions": "36/25",
149
+ "process": "According to the problem, let the inradius of $\\triangle ABF_{2}$ be $r$, and the perimeter of the triangle be $4a$. Then, derive the expression for the area of the triangle, use $AF_{1}, BF_{1}$ to find the area of $\\triangle ABF_{2}$, and then determine the inradius. [Detailed Solution] According to the problem, let the inradius of $\\triangle ABF_{2}$ be $r$; the equation of the ellipse is $\\frac{x^{2}}{25}+\\frac{y^{2}}{9}=1$, and the perimeter of the triangle is $20$. Hence, $S=\\frac{1}{2}\\times20\\times r=10r$. The line passing through $F_1$ and perpendicular to the major axis intersects the ellipse at points $A$ and $B$. Then, $AB=2\\sqrt{9(1-\\frac{16}{25})}=\\frac{18}{5}$. Therefore, $S=\\frac{1}{2}\\times8\\times\\frac{18}{5}=\\frac{72}{5}$. Thus, $10r=\\frac{72}{5}$, solving gives $r=\\frac{36}{25}$. Therefore, the inradius is $\\frac{36}{25}$."
150
+ },
151
+ "sdf_annotation": {
152
+ "params": {
153
+ "a": 5.0,
154
+ "b": 3.0,
155
+ "major_axis": "x",
156
+ "x_coef": 25.0,
157
+ "y_coef": 9.0
158
+ },
159
+ "optimization": {
160
+ "final_loss": 0.0,
161
+ "converged": true,
162
+ "note": "using explicit params"
163
+ },
164
+ "coords": {}
165
+ }
166
+ },
167
+ {
168
+ "dataset": "dev",
169
+ "index": 0,
170
+ "conic_type": "hyperbola",
171
+ "image_path": "samples/dev/hyperbola/problem_0000.png",
172
+ "problem": {
173
+ "text": "From the left focus $F_{1}$ of the hyperbola $\\frac{x^{2}}{16}-\\frac{y^{2}}{25}=1$, draw a tangent to the circle $x^{2}+y^{2}=16$, with the point of tangency $T$. Extend $F_{1} T$ to intersect the right branch of the hyperbola at point $P$. Let $M$ be the midpoint of segment $F_{1} P$, and let $O$ be the origin. Then $|M O|-|M T|$=?",
174
+ "fact_expressions": "G: Hyperbola;H: Circle;F1: Point;Z: Line;T: Point;P: Point;M: Point;Expression(G) = (x^2/16 - y^2/25 = 1);LeftFocus(G) = F1;Expression(H) = (x^2 + y^2 = 16);TangentOfPoint(F1, H) = Z;TangentPoint(Z, H) = T;Intersection(OverlappingLine(LineSegmentOf(F1, T)), RightPart(G)) = P;MidPoint(LineSegmentOf(F1, P)) = M;O: Origin",
175
+ "query_expressions": "Abs(LineSegmentOf(M, O)) - Abs(LineSegmentOf(M, T))",
176
+ "answer_expressions": "1",
177
+ "process": "Let F' be the right focus of the hyperbola, connect PF'. Since M and O are the midpoints of F_{1}P and F_{1}F' respectively, then |MO| = \\frac{1}{2}|PF'|. By the definition of the hyperbola, |F_{1}P| - |PF'| = 8. Hence, |MO| - |MT| = \\frac{1}{2}|PF| - |MF_{1}| + |F_{1}T| = \\frac{1}{2}(|PF'| - |F_{1}P|) + |F_{1}T| = -4 + 5 = 1"
178
+ },
179
+ "sdf_annotation": {
180
+ "params": {
181
+ "a": 4.0,
182
+ "b": 5.0,
183
+ "orientation": "horizontal"
184
+ },
185
+ "optimization": {
186
+ "final_loss": 0.0,
187
+ "converged": true,
188
+ "note": "using explicit params"
189
+ },
190
+ "coords": {}
191
+ }
192
+ },
193
+ {
194
+ "dataset": "dev",
195
+ "index": 537,
196
+ "conic_type": "hyperbola",
197
+ "image_path": "samples/dev/hyperbola/problem_0537.png",
198
+ "problem": {
199
+ "text": "Given fixed points $A(-5,0)$, $B(5,4)$, and point $P$ being any point on the right branch of the hyperbola $C$: $\\frac{x^{2}}{16}-\\frac{y^{2}}{9}=1$, then the maximum value of $|PB|-|PA|$ is?",
200
+ "fact_expressions": "C: Hyperbola;A: Point;B: Point;P: Point;Expression(C) = (x^2/16 - y^2/9 = 1);Coordinate(A) = (-5, 0);Coordinate(B) = (5, 4);PointOnCurve(P, RightPart(C))",
201
+ "query_expressions": "Max(-Abs(LineSegmentOf(P, A)) + Abs(LineSegmentOf(P, B)))",
202
+ "answer_expressions": "-4",
203
+ "process": "According to the given conditions, a=4, b=3, so c=\\sqrt{a^{2}+b^{2}}=5; therefore, A(-5,0) is the left focus of the hyperbola, and let the right focus be F(5,0). Thus, |PB|-|PA|=|PB|-(|PF|+2a)=|PB|-|PF|-8\\leqslant|BF|-8=4-8=-4, with equality if and only if points P, F, and B are collinear."
204
+ },
205
+ "sdf_annotation": {
206
+ "params": {
207
+ "a": 4.0,
208
+ "b": 3.0,
209
+ "orientation": "horizontal"
210
+ },
211
+ "optimization": {
212
+ "final_loss": 0.0,
213
+ "converged": true,
214
+ "note": "using explicit params"
215
+ },
216
+ "coords": {
217
+ "A": [
218
+ -5.0,
219
+ 0.0
220
+ ],
221
+ "B": [
222
+ 5.0,
223
+ 4.0
224
+ ]
225
+ }
226
+ }
227
+ },
228
+ {
229
+ "dataset": "dev",
230
+ "index": 1033,
231
+ "conic_type": "hyperbola",
232
+ "image_path": "samples/dev/hyperbola/problem_1033.png",
233
+ "problem": {
234
+ "text": "Given that line $l$ passes through point $P(2, 1)$ and intersects the hyperbola $x^{2}-\\frac{y^{2}}{4}=1$ at points $A$ and $B$, if $P$ is the midpoint of $AB$, then what is the equation of line $l$?",
235
+ "fact_expressions": "l: Line;P: Point;Coordinate(P) = (2, 1);PointOnCurve(P, l);G: Hyperbola;Expression(G) = (x^2 - y^2/4 = 1);Intersection(l, G) = {A, B};A: Point;B: Point;MidPoint(LineSegmentOf(A, B)) = P",
236
+ "query_expressions": "Expression(l)",
237
+ "answer_expressions": "8*x-y-15=0",
238
+ "process": ""
239
+ },
240
+ "sdf_annotation": {
241
+ "params": {
242
+ "a": 1.0,
243
+ "b": 2.0,
244
+ "orientation": "horizontal"
245
+ },
246
+ "optimization": {
247
+ "final_loss": 0.0,
248
+ "converged": true,
249
+ "note": "using explicit params"
250
+ },
251
+ "coords": {
252
+ "P": [
253
+ 2.0,
254
+ 1.0
255
+ ]
256
+ }
257
+ }
258
+ },
259
+ {
260
+ "dataset": "dev",
261
+ "index": 2,
262
+ "conic_type": "parabola",
263
+ "image_path": "samples/dev/parabola/problem_0002.png",
264
+ "problem": {
265
+ "text": "The coordinates of the focus of the parabola $y^{2}=4 x$ are?",
266
+ "fact_expressions": "G: Parabola;Expression(G) = (y^2 = 4*x)",
267
+ "query_expressions": "Coordinate(Focus(G))",
268
+ "answer_expressions": "(1, 0)",
269
+ "process": "The focus of the parabola y^{2}=4x lies on the x-axis, and p=2, \\therefore\\frac{p}{2}=1, so the focus coordinates of the parabola y^{2}=4x are (1,0)."
270
+ },
271
+ "sdf_annotation": {
272
+ "params": {
273
+ "p": 1.0,
274
+ "direction": "right"
275
+ },
276
+ "optimization": {
277
+ "final_loss": 0.0,
278
+ "converged": true,
279
+ "note": "using explicit params"
280
+ },
281
+ "coords": {}
282
+ }
283
+ },
284
+ {
285
+ "dataset": "dev",
286
+ "index": 508,
287
+ "conic_type": "parabola",
288
+ "image_path": "samples/dev/parabola/problem_0508.png",
289
+ "problem": {
290
+ "text": "Given the parabola $y^{2}=4x$ with focus $F$, $A(-1,0)$, and point $P$ being a moving point on the parabola, when the value of $|PF|$ is minimized, $|PF|=$?",
291
+ "fact_expressions": "G: Parabola;A: Point;P: Point;F: Point;Expression(G) = (y^2 = 4*x);Coordinate(A) = (-1, 0);Focus(G) = F;PointOnCurve(P, G);WhenMin(Abs(LineSegmentOf(P, F)))",
292
+ "query_expressions": "Abs(LineSegmentOf(P, F))",
293
+ "answer_expressions": "2",
294
+ "process": "The equation of the directrix of the parabola is x = -1. Let the distance from P to the directrix be |PQ|, then |PQ| = |PF|, \\therefore \\frac{|PF|}{|PA|} = \\frac{|PQ|}{|PA|} = \\sin\\angle PAQ. Therefore, when PA is tangent to the parabola y^{2} = 4x, \\angle PAQ is minimized, i.e., \\frac{|PF|}{|PA|} reaches its minimum value. Suppose the line passing through point A, y = kx + k, is tangent to the parabola (k \\neq 0). Substituting into the parabola equation gives k^{2}x^{2} + (2k^{2} - 4)x + k^{2} = 0. \\therefore \\Delta = (2k^{2} - 4)^{2} - 4k^{4} = 0. Solving yields k = \\pm 1. Then we have x^{2} - 2x + 1 = 0, solving gives x = 1. Substituting x = 1 into y^{2} = 4x gives y = \\pm 2. \\therefore P(1,2) or P(1,-2), \\therefore |PF| = 2."
295
+ },
296
+ "sdf_annotation": {
297
+ "params": {
298
+ "p": 1.0,
299
+ "direction": "right"
300
+ },
301
+ "optimization": {
302
+ "final_loss": 0.0,
303
+ "converged": true,
304
+ "note": "using explicit params"
305
+ },
306
+ "coords": {
307
+ "A": [
308
+ -1.0,
309
+ 0.0
310
+ ]
311
+ }
312
+ }
313
+ },
314
+ {
315
+ "dataset": "dev",
316
+ "index": 1030,
317
+ "conic_type": "parabola",
318
+ "image_path": "samples/dev/parabola/problem_1030.png",
319
+ "problem": {
320
+ "text": "Given point $P(1,-1)$ and parabola $C$: $y=\\frac{1}{4} x^{2}$, a line passing through the focus of parabola $C$ with slope $k$ intersects parabola $C$ at points $A$ and $B$. If $\\overrightarrow{P A} \\cdot \\overrightarrow{P B}=0$, then $k=?$",
321
+ "fact_expressions": "P: Point;Coordinate(P) = (1, -1);C: Parabola;Expression(C) = (y = x^2/4);G: Line;PointOnCurve(Focus(C), G);k: Number;Slope(G) = k;A: Point;B: Point;Intersection(G, C) = {A, B};DotProduct(VectorOf(P, A), VectorOf(P, B)) = 0",
322
+ "query_expressions": "k",
323
+ "answer_expressions": "1/2",
324
+ "process": "Let the parabola C: y = \\frac{1}{4}x^{2} have focus F; then the coordinates of F are (0,1). Thus, the equation of line AB is y = kx + 1. Let points A(x_{1},y_{1}) and B(x_{2},y_{2}). Substituting the equation of line AB into the equation of parabola C and simplifying yields x^{2} - 4kx - 4 = 0. Then x_{1} + x_{2} = 4k, x_{1}x_{2} = -4. From \\overrightarrow{PA} \\cdot \\overrightarrow{PB} = 0, we obtain (x_{1}-1)(x_{2}-1) + (y_{1}+1)(y_{2}+1) = 0, that is, (x_{1}-1)(x_{2}-1) + (kx_{1}+2)(kx_{2}+2) = 0, which simplifies to (k^{2}+1)x_{1}x_{2} + (2k-1)(x_{1}+x_{2}) + 5 = 0. Therefore, -4(k^{2}+1) + 4k(2k-1) + 5 = (2k-1)^{2} = 0. Solving gives k = \\frac{1}{2}."
325
+ },
326
+ "sdf_annotation": {
327
+ "params": {
328
+ "p": 1.0,
329
+ "direction": "up"
330
+ },
331
+ "optimization": {
332
+ "final_loss": 0.0,
333
+ "converged": true,
334
+ "note": "using explicit params"
335
+ },
336
+ "coords": {
337
+ "P": [
338
+ 1.0,
339
+ -1.0
340
+ ]
341
+ }
342
+ }
343
+ },
344
+ {
345
+ "dataset": "test",
346
+ "index": 4,
347
+ "conic_type": "circle",
348
+ "image_path": "samples/test/circle/problem_0004.png",
349
+ "problem": {
350
+ "text": "The product of the slopes of the lines connecting a moving point $P$ to fixed points $A(-1,0)$ and $B(1,0)$ is $-1$. Then, what is the trajectory equation of point $P$?",
351
+ "fact_expressions": "P: Point;Slope(LineSegmentOf(P, A))*Slope(LineSegmentOf(P, B)) = -1;A: Point;Coordinate(A) = (-1, 0);B: Point;Coordinate(B) = (1, 0)",
352
+ "query_expressions": "LocusEquation(P)",
353
+ "answer_expressions": "(x^2+y^2=1)&Negation(x=pm*1)",
354
+ "process": "Let P(x,y), then k_{PA}=\\frac{y-0}{x+1}, k_{PB}=\\frac{y-0}{x-1}. Since the product of the slopes of the lines joining the moving point P and the fixed points A(-1,0), B(1,0) is -1, \\therefore k_{PA} \\cdot k_{PB} = -1, \\therefore \\frac{y^{2}}{x^{2}-1} = -1, that is, x^{2} + y^{2} = 1, and x \\neq \\pm 1. In conclusion, the trajectory equation of point P is x^{2} + y^{2} = 1 (x \\neq \\pm 1)."
355
+ },
356
+ "sdf_annotation": {
357
+ "params": {
358
+ "center": [
359
+ 0.0,
360
+ 0.0
361
+ ],
362
+ "radius": 1.0
363
+ },
364
+ "optimization": {
365
+ "final_loss": 0.0,
366
+ "converged": true
367
+ },
368
+ "coords": {}
369
+ }
370
+ },
371
+ {
372
+ "dataset": "test",
373
+ "index": 1202,
374
+ "conic_type": "circle",
375
+ "image_path": "samples/test/circle/problem_1202.png",
376
+ "problem": {
377
+ "text": "Given a line $ l $ with slope $ 1 $ and positive $ y $-intercept $ b $ that intersects the circle $ C: x^{2} + y^{2} = 4 $ at points $ A $ and $ B $, and $ O $ is the origin. If the area of $ \\triangle AOB $ is $ \\sqrt{3} $, then $ b = $?",
378
+ "fact_expressions": "l: Line;C: Circle;A: Point;O: Origin;B: Point;b: Number;Expression(C) = (x^2 + y^2 = 4);Slope(l)=1;b>0;Intercept(l,yAxis)=b;Intersection(l, C) = {A, B};Area(TriangleOf(A, O, B)) = sqrt(3)",
379
+ "query_expressions": "b",
380
+ "answer_expressions": "{sqrt(6),sqrt(2)}",
381
+ "process": "According to the problem, the equation of line $ l $ is $ y = x + b $, the center of circle $ C $ is $ C(0,0) $, and the radius is $ r = 2 $. Using the point-to-line distance formula, $ \\frac{1}{2} \\cdot 2\\sqrt{4 - \\frac{b^{2}}{2}} \\cdot \\frac{|b|}{\\sqrt{3}} = \\sqrt{3} $. Given $ b > 0 $, solving yields $ b = \\sqrt{6} $ or $ \\sqrt{2} $."
382
+ },
383
+ "sdf_annotation": {
384
+ "params": {
385
+ "center": [
386
+ 0.0,
387
+ 0.0
388
+ ],
389
+ "radius": 2.0
390
+ },
391
+ "optimization": {
392
+ "final_loss": 0.0,
393
+ "converged": true
394
+ },
395
+ "coords": {}
396
+ }
397
+ },
398
+ {
399
+ "dataset": "test",
400
+ "index": 1992,
401
+ "conic_type": "circle",
402
+ "image_path": "samples/test/circle/problem_1992.png",
403
+ "problem": {
404
+ "text": "Given that the moving circle $P$ is externally tangent to the fixed circle $C$: $(x+2)^{2}+y^{2}=1$, and also tangent to the line $x=1$, what is the equation of the locus of the center $P$ of the moving circle?",
405
+ "fact_expressions": "P: Circle;G: Line;C:Circle;P1:Point;Expression(C)=((x+2)^2+y^2=1);Expression(G) = (x = 1);IsOutTangent(P,C);IsTangent(P,G);Center(P)=P1",
406
+ "query_expressions": "LocusEquation(P1)",
407
+ "answer_expressions": "y^2=-8*x",
408
+ "process": "Let the distance from the center P of a circle to the line x=1 be equal to r, and let P(x,y). According to the given condition, we have PC = 1 + r, that is, \\sqrt{(x+2)^{2}+y^{2}} = 1 + r. Simplifying yields y^{2} = -8x."
409
+ },
410
+ "sdf_annotation": {
411
+ "params": {
412
+ "center": [
413
+ -2.0,
414
+ 0.0
415
+ ],
416
+ "radius": 1.0
417
+ },
418
+ "optimization": {
419
+ "final_loss": 0.0,
420
+ "converged": true
421
+ },
422
+ "coords": {}
423
+ }
424
+ },
425
+ {
426
+ "dataset": "test",
427
+ "index": 1,
428
+ "conic_type": "ellipse",
429
+ "image_path": "samples/test/ellipse/problem_0001.png",
430
+ "problem": {
431
+ "text": "An ellipse $\\frac{x^{2}}{k^{2}}+y^{2}=1$ $(k>0)$ has a focus at $(3 , 0)$, then $k=$?",
432
+ "fact_expressions": "G: Ellipse;Expression(G) = (y^2 + x^2/k^2 = 1);k: Number;k>0;Coordinate(OneOf(Focus(G))) = (3,0)",
433
+ "query_expressions": "k",
434
+ "answer_expressions": "sqrt(10)",
435
+ "process": ""
436
+ },
437
+ "sdf_annotation": {
438
+ "params": {
439
+ "a": 2.0,
440
+ "b": 1.0,
441
+ "major_axis": "x",
442
+ "x_coef": 4.0,
443
+ "y_coef": 1.0
444
+ },
445
+ "optimization": {
446
+ "final_loss": 0.0,
447
+ "converged": true,
448
+ "note": "using explicit params"
449
+ },
450
+ "coords": {}
451
+ }
452
+ },
453
+ {
454
+ "dataset": "test",
455
+ "index": 1083,
456
+ "conic_type": "ellipse",
457
+ "image_path": "samples/test/ellipse/problem_1083.png",
458
+ "problem": {
459
+ "text": "The equation of a hyperbola that shares the same foci with the ellipse $x^{2}+4 y^{2}=16$ and has an asymptote given by $x+ \\sqrt {3} y=0$ is?",
460
+ "fact_expressions": "G: Hyperbola;H: Ellipse;Expression(H)=(x^2 + 4*y^2 = 16);Focus(H) = Focus(G);Expression(OneOf(Asymptote(G))) = (x + sqrt(3)*y = 0)",
461
+ "query_expressions": "Expression(G)",
462
+ "answer_expressions": "x^2/9-y^2/3=1",
463
+ "process": ""
464
+ },
465
+ "sdf_annotation": {
466
+ "params": {
467
+ "a": 4.0,
468
+ "b": 2.0,
469
+ "major_axis": "x",
470
+ "x_coef": 16.0,
471
+ "y_coef": 4.0
472
+ },
473
+ "optimization": {
474
+ "final_loss": 0.0,
475
+ "converged": true,
476
+ "note": "using explicit params"
477
+ },
478
+ "coords": {}
479
+ }
480
+ },
481
+ {
482
+ "dataset": "test",
483
+ "index": 2067,
484
+ "conic_type": "ellipse",
485
+ "image_path": "samples/test/ellipse/problem_2067.png",
486
+ "problem": {
487
+ "text": "Given that the foci of the ellipse $\\frac{x^{2}}{9}+\\frac{y^{2}}{2}=1$ are $F_{1}$ and $F_{2}$ respectively, and point $P$ lies on the ellipse. If $|P F_{1}|=4$, then the area of triangle $F_{1} P F_{2}$ is?",
488
+ "fact_expressions": "G: Ellipse;Expression(G) = (x^2/9 + y^2/2 = 1);F1: Point;F2: Point;Focus(G) = {F1, F2};P: Point;PointOnCurve(P, G);Abs(LineSegmentOf(P, F1)) = 4",
489
+ "query_expressions": "Area(TriangleOf(F1, P, F2))",
490
+ "answer_expressions": "2*sqrt(3)",
491
+ "process": ""
492
+ },
493
+ "sdf_annotation": {
494
+ "params": {
495
+ "a": 3.0,
496
+ "b": 1.4142135623730951,
497
+ "major_axis": "x",
498
+ "x_coef": 9.0,
499
+ "y_coef": 2.0
500
+ },
501
+ "optimization": {
502
+ "final_loss": 0.0,
503
+ "converged": true,
504
+ "note": "using explicit params"
505
+ },
506
+ "coords": {}
507
+ }
508
+ },
509
+ {
510
+ "dataset": "test",
511
+ "index": 0,
512
+ "conic_type": "hyperbola",
513
+ "image_path": "samples/test/hyperbola/problem_0000.png",
514
+ "problem": {
515
+ "text": "If the two foci of a hyperbola are $F_{1}(-3,0)$, $F_{2}(3,0)$, and one asymptote has equation $y=\\sqrt{2} x$, then the equation of this hyperbola is?",
516
+ "fact_expressions": "G: Hyperbola;F1: Point;F2: Point;Coordinate(F1) = (-3, 0);Coordinate(F2) = (3, 0);Focus(G)={F1,F2};Expression(OneOf(Asymptote(G))) = (y = sqrt(2)*x)",
517
+ "query_expressions": "Expression(G)",
518
+ "answer_expressions": "x^2/3-y^2/6=1",
519
+ "process": ""
520
+ },
521
+ "sdf_annotation": {
522
+ "params": {
523
+ "a": 1.732385540716972,
524
+ "b": 2.4497476064802375,
525
+ "orientation": "horizontal"
526
+ },
527
+ "optimization": {
528
+ "final_loss": 2.601017381791051e-06,
529
+ "converged": true,
530
+ "iterations": 91
531
+ },
532
+ "coords": {
533
+ "F1": [
534
+ -3.0,
535
+ 0.0
536
+ ],
537
+ "F2": [
538
+ 3.0,
539
+ 0.0
540
+ ]
541
+ }
542
+ }
543
+ },
544
+ {
545
+ "dataset": "test",
546
+ "index": 969,
547
+ "conic_type": "hyperbola",
548
+ "image_path": "samples/test/hyperbola/problem_0969.png",
549
+ "problem": {
550
+ "text": "Given that $P$ is an intersection point of the ellipse $\\frac{x^{2}}{a_{1}^{2}}+\\frac{y^{2}}{b_{1}^{2}}=1$ $(a_{1}>b_{1}>0)$ and the hyperbola $\\frac{x^{2}}{a_{2}^{2}}-\\frac{y^{2}}{b_{2}^{2}}=1$ $(a_{2}>0, b_{2}>0)$, $F_{1}$, $F_{2}$ are the common foci of the ellipse and the hyperbola, $e_{1}$, $e_{2}$ are the eccentricities of the ellipse and the hyperbola respectively, and if $\\angle F_{1} P F_{2}=\\frac{\\pi}{3}$, then the minimum value of $e_{1} \\cdot e_{2}$ is?",
551
+ "fact_expressions": "G: Hyperbola;H: Ellipse;a2: Number;b2: Number;a1: Number;b1: Number;F1: Point;P: Point;F2: Point;a2>0;b2>0;Expression(G) = (-y^2/b2^2 + x^2/a2^2 = 1);a1>b1;b1>0;Expression(H) = (y^2/b1^2 + x^2/a1^2 = 1);OneOf(Intersection(H, G)) = P;Focus(G) = {F1, F2};Focus(H) = {F1, F2};Focus(G) = Focus(H);e1: Number;e2: Number;Eccentricity(H) = e1;Eccentricity(G) = e2;AngleOf(F1, P, F2) = pi/3",
552
+ "query_expressions": "Min(e1*e2)",
553
+ "answer_expressions": "sqrt(3)/2",
554
+ "process": "By the symmetry of the ellipse and hyperbola, assume without loss of generality that point P lies in the first quadrant, so |PF_{1}| > |PF_{2}|. Since the ellipse and hyperbola share common foci, let the semi-focal length of the ellipse and hyperbola be c. By the definitions of the ellipse and hyperbola, we have: |PF_{1}| + |PF_{2}| = 2a_{1}, |PF_{1}| - |PF_{2}| = 2a_{2}. Solving gives |PF_{1}| = a_{1} + a_{2}, |PF_{2}| = a_{1} - a_{2}. In triangle F_{1}PF_{2}, by the law of cosines, we obtain: |F_{1}F_{2}|^{2} = |PF_{1}|^{2} + |PF_{2}|^{2} - 2|PF_{1}||PF_{2}|\\cos\\frac{\\pi}{3}, that is, 4c^{2} = (a_{1}+a_{2})^{2} + (a_{1}-a_{2})^{2} - (a_{1}+a_{2})(a_{1}-a_{2}). Simplifying yields 4c^{2} = a_{1}^{2} + 3a_{2}^{2}, so \\frac{1}{e_{1}^{2}} + 3\\frac{1}{e_{2}^{2}} = 4. Also, \\frac{1}{e_{1}^{2}} + 3\\frac{1}{e_{2}^{2}} \\geqslant \\frac{2\\sqrt{3}}{e_{1}e_{2}}, therefore e_{1}e_{2} \\geqslant \\frac{\\sqrt{3}}{2}."
555
+ },
556
+ "sdf_annotation": {
557
+ "params": {
558
+ "a": 2.0,
559
+ "b": 1.5,
560
+ "orientation": "horizontal"
561
+ },
562
+ "optimization": {
563
+ "final_loss": 0.0,
564
+ "converged": true,
565
+ "note": "using explicit params"
566
+ },
567
+ "coords": {}
568
+ }
569
+ },
570
+ {
571
+ "dataset": "test",
572
+ "index": 2065,
573
+ "conic_type": "hyperbola",
574
+ "image_path": "samples/test/hyperbola/problem_2065.png",
575
+ "problem": {
576
+ "text": "Through the right focus $F$ of the hyperbola $\\frac{x^{2}}{a^{2}}-\\frac{y^{2}}{b^{2}}=1$ $(a>0, b>0)$, draw a perpendicular line to the asymptote $y=\\frac{b}{a}x$, with foot of perpendicular at $M$. This line intersects the left and right branches of the hyperbola at points $A$ and $B$ respectively. Find the range of values for the eccentricity of the hyperbola?",
577
+ "fact_expressions": "G: Hyperbola;b: Number;a: Number;F: Point;A: Point;B: Point;M:Point;a>0;b>0;Expression(G) = (-y^2/b^2 + x^2/a^2 = 1);RightFocus(G) = F;L:Line;OneOf(Asymptote(G))=L;Expression(L)=(y=(b/a)*x);L1:Line;IsPerpendicular(L,L1);FootPoint(L,L1)=M;PointOnCurve(F, L1);Intersection(L1,LeftPart(G)) = A;Intersection(L1,RightPart(G)) = B",
578
+ "query_expressions": "Range(Eccentricity(G))",
579
+ "answer_expressions": "(sqrt(2),+oo)",
580
+ "process": "Since line AB intersects both the left and right branches of the hyperbola, line AB must intersect the asymptote y=-\\frac{b}{a}x in the second quadrant. Therefore, the slope of line AB must be greater than the slope of the asymptote y=-\\frac{b}{a}x, that is, -\\frac{a}{b}>-\\frac{b}{a}, which implies b^{2}>a^{2}. Since b^{2}=c^{2}-a^{2}, it follows that c^{2}>2a^{2}. The eccentricity of the hyperbola e=\\frac{c}{a}>\\sqrt{2}. Therefore, the range of values for the eccentricity of the hyperbola is (\\sqrt{2},+\\infty)."
581
+ },
582
+ "sdf_annotation": {
583
+ "params": {
584
+ "a": 2.0,
585
+ "b": 1.5,
586
+ "orientation": "horizontal"
587
+ },
588
+ "optimization": {
589
+ "final_loss": 0.0,
590
+ "converged": true,
591
+ "note": "using explicit params"
592
+ },
593
+ "coords": {}
594
+ }
595
+ },
596
+ {
597
+ "dataset": "test",
598
+ "index": 2,
599
+ "conic_type": "parabola",
600
+ "image_path": "samples/test/parabola/problem_0002.png",
601
+ "problem": {
602
+ "text": "Given any point $P$ on the parabola $y^{2}=4 x$, let $d$ be the distance from point $P$ to the $y$-axis. For a given point $A(4,5)$, what is the minimum value of $|P A|+d$?",
603
+ "fact_expressions": "G: Parabola;A: Point;P: Point;Expression(G) = (y^2 = 4*x);Coordinate(A) = (4, 5);PointOnCurve(P,G);Distance(P, yAxis) = d;d:Number",
604
+ "query_expressions": "Min(d + Abs(LineSegmentOf(P, A)))",
605
+ "answer_expressions": "sqrt(34)-1",
606
+ "process": "The directrix of the parabola is x = -1. Extending the distance from P to the y-axis one unit further to the left gives the distance from P to the directrix. According to the definition of a parabola, the distance from P to the directrix equals the distance from P to the focus F(1,0). Therefore, |PA| + d = |PA| + |PF| - 1. Since A lies outside the parabola, the minimum value occurs when A, P, and F are collinear (i.e., P is the intersection point of segment AF and the parabola). The minimum value is |AF| - 1 = \\sqrt{(9+25)} - 1 = \\sqrt{34} - 1^{n}"
607
+ },
608
+ "sdf_annotation": {
609
+ "params": {
610
+ "p": 1.0,
611
+ "direction": "right"
612
+ },
613
+ "optimization": {
614
+ "final_loss": 0.0,
615
+ "converged": true,
616
+ "note": "using explicit params"
617
+ },
618
+ "coords": {
619
+ "A": [
620
+ 4.0,
621
+ 5.0
622
+ ]
623
+ }
624
+ }
625
+ },
626
+ {
627
+ "dataset": "test",
628
+ "index": 1025,
629
+ "conic_type": "parabola",
630
+ "image_path": "samples/test/parabola/problem_1025.png",
631
+ "problem": {
632
+ "text": "The focus of the parabola $y^{2}=2 x$ is $F$. If $P(2, y)$ lies on the parabola, then $|PF|=$?",
633
+ "fact_expressions": "G: Parabola;F: Point;P: Point;y1: Number;Expression(G) = (y^2 = 2*x);Coordinate(P) = (2, y1);Focus(G) = F;PointOnCurve(P, G)",
634
+ "query_expressions": "Abs(LineSegmentOf(P, F))",
635
+ "answer_expressions": "5/2",
636
+ "process": ""
637
+ },
638
+ "sdf_annotation": {
639
+ "params": {
640
+ "p": 0.5,
641
+ "direction": "right"
642
+ },
643
+ "optimization": {
644
+ "final_loss": 0.0,
645
+ "converged": true,
646
+ "note": "using explicit params"
647
+ },
648
+ "coords": {}
649
+ }
650
+ },
651
+ {
652
+ "dataset": "test",
653
+ "index": 2068,
654
+ "conic_type": "parabola",
655
+ "image_path": "samples/test/parabola/problem_2068.png",
656
+ "problem": {
657
+ "text": "Let $F$ be the focus of the parabola $C$: $y^{2}=8 x$. A line passing through $F$ with an inclination angle of $30^{\\circ}$ intersects $C$ at points $A$ and $B$. Then $|A B|$=?",
658
+ "fact_expressions": "C: Parabola;Expression(C) = (y^2 = 8*x);F: Point;Focus(C) = F;G: Line;PointOnCurve(F, G);Inclination(G) = ApplyUnit(30, degree);A: Point;B: Point;Intersection(G, C) = {A, B}",
659
+ "query_expressions": "Abs(LineSegmentOf(A, B))",
660
+ "answer_expressions": "32",
661
+ "process": "From $ y^{2} = 8x $, we get $ 2p = 8 $, $ p = 4 $, then $ F(2,0) $. Therefore, the equation of the line passing through $ A $ and $ B $ is $ y = \\frac{\\sqrt{3}}{3}(x - 2) $. Solving the system \n\\[\n\\begin{cases}\ny^{2} = 8x \\\\\ny = \\frac{\\sqrt{3}}{3}(x - 2)\n\\end{cases}\n\\]\nyields $ x^{2} - 28x + 4 = 0 $. Let $ A(x_{1}, y_{1}) $, $ B(x_{2}, y_{2}) $, then $ x_{1} + x_{2} = 28 $, and since $ |AB| = x_{1} + x_{2} + p = 28 + 4 = 32 $."
662
+ },
663
+ "sdf_annotation": {
664
+ "params": {
665
+ "p": 2.0,
666
+ "direction": "right"
667
+ },
668
+ "optimization": {
669
+ "final_loss": 0.0,
670
+ "converged": true,
671
+ "note": "using explicit params"
672
+ },
673
+ "coords": {}
674
+ }
675
+ },
676
+ {
677
+ "dataset": "train",
678
+ "index": 85,
679
+ "conic_type": "circle",
680
+ "image_path": "samples/train/circle/problem_0085.png",
681
+ "problem": {
682
+ "text": "The two foci of the ellipse $x^{2}+k y^{2}=1$ lie on the circle $x^{2}+y^{2}=4$. Then the real number $k$=?",
683
+ "fact_expressions": "G: Ellipse;k: Real;H: Circle;Expression(G) = (k*y^2 + x^2 = 1);Expression(H) = (x^2 + y^2 = 4);PointOnCurve(Focus(G), H)",
684
+ "query_expressions": "k",
685
+ "answer_expressions": "1/5",
686
+ "process": "Since the two foci of the ellipse $x^{2}+ky^{2}=1$ lie on the circle $x^{2}+y^{2}=4$, we have $c=2$. Because $x^{2}+\\frac{y^{2}}{\\frac{1}{k}}=1$, when $0<k<1$, $a^{2}=\\frac{1}{k}$, $b^{2}=1$, and from $a^{2}=b^{2}+c^{2}$ we obtain $k=\\frac{1}{5}$. When $k>1$, $b^{2}=\\frac{1}{k}$, $a^{2}=1$, which does not hold. Therefore, $k=\\frac{1}{5}$."
687
+ },
688
+ "sdf_annotation": {
689
+ "params": {
690
+ "center": [
691
+ 0.0,
692
+ 0.0
693
+ ],
694
+ "radius": 2.0
695
+ },
696
+ "optimization": {
697
+ "final_loss": 0.0,
698
+ "converged": true
699
+ },
700
+ "coords": {}
701
+ }
702
+ },
703
+ {
704
+ "dataset": "train",
705
+ "index": 4027,
706
+ "conic_type": "circle",
707
+ "image_path": "samples/train/circle/problem_4027.png",
708
+ "problem": {
709
+ "text": "Given the circle $(x+2)^{2}+y^{2}=64$ with center $M$, let $A$ be any point on the circle, and let $N(2,0)$. The perpendicular bisector of segment $AN$ intersects $MA$ at point $P$. What is the equation of the locus of the moving point $P$?",
710
+ "fact_expressions": "G: Circle;Expression(G) = (y^2 + (x + 2)^2 = 64);M: Point;Center(G) = M;A: Point;PointOnCurve(A, G);N: Point;Coordinate(N) = (2, 0);P: Point;Intersection(PerpendicularBisector(LineSegmentOf(A, N)), LineSegmentOf(M, A)) = P",
711
+ "query_expressions": "LocusEquation(P)",
712
+ "answer_expressions": "x^2/16+y^2/12=1",
713
+ "process": "According to the problem, the circle $(x+2)^{2}+y^{2}=64$ has center $M(-2,0)$, and point $N(2,0)$. The perpendicular bisector of segment $AN$ intersects $MA$ at point $P$. Therefore, $P$ lies on the perpendicular bisector of $AN$, so $PA=PN$. Also, since $|AM|=8$, the point $P$ satisfies $|PM|+|PN|=8>4$. According to the definition of an ellipse, the locus of point $P$ is an ellipse with foci $M$ and $N$, where $2a=8$, $2c=4$, giving $a=4$, $c=2$, so $b=\\sqrt{a^{2}-c^{2}}=\\sqrt{12}$. Thus, the equation of the ellipse is $\\frac{x^{2}}{16}+\\frac{y^{2}}{12}=1$."
714
+ },
715
+ "sdf_annotation": {
716
+ "params": {
717
+ "center": [
718
+ 2.0,
719
+ 0.0
720
+ ],
721
+ "radius": 8.0
722
+ },
723
+ "optimization": {
724
+ "final_loss": 0.0,
725
+ "converged": true
726
+ },
727
+ "coords": {}
728
+ }
729
+ },
730
+ {
731
+ "dataset": "train",
732
+ "index": 7579,
733
+ "conic_type": "circle",
734
+ "image_path": "samples/train/circle/problem_7579.png",
735
+ "problem": {
736
+ "text": "If from any point $P$ on the circle $x^{2}+y^{2}=1$, a perpendicular line segment is drawn to the $y$-axis, then the trajectory equation of the midpoint $M$ of this line segment is?",
737
+ "fact_expressions": "G: Circle;H: LineSegment;Expression(G) = (x^2 + y^2 = 1);PointOnCurve(P,G);IsPerpendicular(H,yAxis);M:Point;MidPoint(H)=M;P:Point",
738
+ "query_expressions": "LocusEquation(M)",
739
+ "answer_expressions": "4*x^2+y^2=1",
740
+ "process": "Let the coordinates of point M be (x, y) and the coordinates of point P be (x_{0}, y_{0}). Then from the given conditions, we have x = \\frac{x_{0}}{2}, y = y_{0}. Since P(x_{0}, y_{0}) lies on the circle x^{2} + y^{2} = 1, it follows that x_{0}^{2} + y_{0}^{2} = 1. Substituting x_{0} = 2x, y_{0} = y into the equation x_{0}^{2} + y_{0}^{2} = 1, we obtain 4x^{2} + y^{2} = 1. Therefore, the trajectory equation of point M is 4x^{2} + y^{2} = 1."
741
+ },
742
+ "sdf_annotation": {
743
+ "params": {
744
+ "center": [
745
+ 0.0,
746
+ 0.0
747
+ ],
748
+ "radius": 1.0
749
+ },
750
+ "optimization": {
751
+ "final_loss": 0.0,
752
+ "converged": true
753
+ },
754
+ "coords": {}
755
+ }
756
+ },
757
+ {
758
+ "dataset": "train",
759
+ "index": 0,
760
+ "conic_type": "ellipse",
761
+ "image_path": "samples/train/ellipse/problem_0000.png",
762
+ "problem": {
763
+ "text": "The eccentricity of the ellipse $\\frac{x^{2}}{2}+\\frac{y^{2}}{3}=1$ is?",
764
+ "fact_expressions": "G: Ellipse;Expression(G) = (x^2/2 + y^2/3 = 1)",
765
+ "query_expressions": "Eccentricity(G)",
766
+ "answer_expressions": "sqrt(3)/3",
767
+ "process": ""
768
+ },
769
+ "sdf_annotation": {
770
+ "params": {
771
+ "a": 1.7320508075688772,
772
+ "b": 1.4142135623730951,
773
+ "major_axis": "y",
774
+ "x_coef": 2.0,
775
+ "y_coef": 3.0
776
+ },
777
+ "optimization": {
778
+ "final_loss": 0.0,
779
+ "converged": true,
780
+ "note": "using explicit params"
781
+ },
782
+ "coords": {}
783
+ }
784
+ },
785
+ {
786
+ "dataset": "train",
787
+ "index": 3849,
788
+ "conic_type": "ellipse",
789
+ "image_path": "samples/train/ellipse/problem_3849.png",
790
+ "problem": {
791
+ "text": "Given the parabola $C_{1}$: $y=a x^{2} (a>0)$, the focus $F$ of which is also a focus of the ellipse $C_{2}$: $\\frac{y^{2}}{4}+\\frac{x^{2}}{b^{2}}=1 (b>0)$. Points $M$ and $P(\\frac{3}{2}, 1)$ are on curves $C_{1}$ and $C_{2}$ respectively. Then the minimum value of $|M P|+|M F|$ is?",
792
+ "fact_expressions": "C1: Parabola;Expression(C1) = (y = a*x^2);a: Number;a>0;F: Point;Focus(C1) = F;C2: Ellipse;Expression(C2) = (y^2/4 + x^2/b^2 = 1);b: Number;b>0;OneOf(Focus(C2)) = F;M: Point;PointOnCurve(M, C1);P: Point;Coordinate(P) = (3/2, 1);PointOnCurve(P, C2)",
793
+ "query_expressions": "Min(Abs(LineSegmentOf(M, F)) + Abs(LineSegmentOf(M, P)))",
794
+ "answer_expressions": "2",
795
+ "process": "Since point $ P\\left(\\frac{3}{2},1\\right) $ lies on the ellipse $ C_{2} $, and $ b>0 $, we have $ \\frac{1}{4}+\\frac{\\left(\\frac{3}{2}\\right)^{2}}{b^{2}}=1 \\Rightarrow b=\\sqrt{3} $, so the coordinates of focus $ F $ are $ (0,1) $. Also, from the equation of parabola $ C_{1} $, we get $ F\\left(0,\\frac{1}{4a}\\right) $, so $ \\frac{1}{4a}=1 \\Rightarrow a=\\frac{1}{4} $, then $ c_{1}: y=\\frac{1}{4}x^{2} $. By the definition of the parabola, $ |MF| $ equals the distance $ d $ from point $ M $ to its directrix $ l: y=-1 $. Draw a perpendicular line $ l': x=\\frac{3}{2} $ from point $ P $ to the directrix $ l: y=-1 $. Then the intersection point of the perpendicular line $ l': x=\\frac{3}{2} $ and the parabola $ C_{1}: y=\\frac{1}{4}x^{2} $ is the desired point $ M $. Therefore, the minimum value of $ |MP|+|MF|=|MP|+d $ is $ 1-(-1)=2 $."
796
+ },
797
+ "sdf_annotation": {
798
+ "params": {
799
+ "a": 1.8537487983703613,
800
+ "b": 1.6118527266061986,
801
+ "major_axis": "x",
802
+ "x_coef": 4.0,
803
+ "y_coef": 3.0
804
+ },
805
+ "optimization": {
806
+ "final_loss": 1.4665974334810584e-06,
807
+ "converged": true,
808
+ "iterations": 90
809
+ },
810
+ "coords": {
811
+ "P": [
812
+ 1.5,
813
+ 1.0
814
+ ]
815
+ }
816
+ }
817
+ },
818
+ {
819
+ "dataset": "train",
820
+ "index": 7753,
821
+ "conic_type": "ellipse",
822
+ "image_path": "samples/train/ellipse/problem_7753.png",
823
+ "problem": {
824
+ "text": "The eccentricity of the ellipse $\\frac{y^{2}}{3}+x^{2}=1$ is?",
825
+ "fact_expressions": "G: Ellipse;Expression(G) = (x^2 + y^2/3 = 1)",
826
+ "query_expressions": "Eccentricity(G)",
827
+ "answer_expressions": "sqrt(6)/3",
828
+ "process": "Find the values of a, b, and c, then determine the eccentricity of the ellipse \\frac{y^{2}}{3}+x^{2}=1. In the ellipse \\frac{y^{2}}{3}+x^{2}=1, a=\\sqrt{3}, b=1, c=\\sqrt{a^{2}-b^{2}}=\\sqrt{2}. Therefore, the eccentricity of the ellipse \\frac{y^{2}}{3}+x^{2}=1 is e=\\frac{c}{a}=\\frac{\\sqrt{2}}{\\sqrt{3}}=\\frac{\\sqrt{6}}{3}"
829
+ },
830
+ "sdf_annotation": {
831
+ "params": {
832
+ "a": 2.0,
833
+ "b": 1.0,
834
+ "major_axis": "y",
835
+ "x_coef": 1.0,
836
+ "y_coef": 4.0
837
+ },
838
+ "optimization": {
839
+ "final_loss": 0.0,
840
+ "converged": true,
841
+ "note": "using explicit params"
842
+ },
843
+ "coords": {}
844
+ }
845
+ },
846
+ {
847
+ "dataset": "train",
848
+ "index": 1,
849
+ "conic_type": "hyperbola",
850
+ "image_path": "samples/train/hyperbola/problem_0001.png",
851
+ "problem": {
852
+ "text": "Given that one asymptote of the hyperbola $\\frac{x^{2}}{4}-\\frac{y^{2}}{m^{2}}=1$ $(m>0)$ is $5 x-2 y=0$, then $m=$?",
853
+ "fact_expressions": "G: Hyperbola;m: Number;m>0;Expression(G) = (x^2/4 - y^2/m^2 = 1);Expression(OneOf(Asymptote(G))) = (5*x - 2*y = 0)",
854
+ "query_expressions": "m",
855
+ "answer_expressions": "5",
856
+ "process": "The asymptotes of the hyperbola $\\frac{x^{2}}{4}-\\frac{y^{2}}{m^{2}}=1$ $(m>0)$ are given by $y=\\pm\\frac{m}{2}x$. The equation of the line $5x-2y=0$ can be rewritten as $y=\\frac{5}{2}x$, so $m=5$."
857
+ },
858
+ "sdf_annotation": {
859
+ "params": {
860
+ "a": 2.0,
861
+ "b": 1.5,
862
+ "orientation": "horizontal"
863
+ },
864
+ "optimization": {
865
+ "final_loss": 0.0,
866
+ "converged": true,
867
+ "note": "using explicit params"
868
+ },
869
+ "coords": {}
870
+ }
871
+ },
872
+ {
873
+ "dataset": "train",
874
+ "index": 3822,
875
+ "conic_type": "hyperbola",
876
+ "image_path": "samples/train/hyperbola/problem_3822.png",
877
+ "problem": {
878
+ "text": "The distance from the focus of the hyperbola $\\frac{x^{2}}{4}-\\frac{y^{2}}{12}=1$ to its asymptote is?",
879
+ "fact_expressions": "G: Hyperbola;Expression(G) = (x^2/4 - y^2/12 = 1)",
880
+ "query_expressions": "Distance(Focus(G), Asymptote(G))",
881
+ "answer_expressions": "Preserve all mathematical expressions exactly (including LaTeX format, symbols, and numbers). \nDo not add explanations.",
882
+ "process": ""
883
+ },
884
+ "sdf_annotation": {
885
+ "params": {
886
+ "a": 2.0,
887
+ "b": 3.4641016151377544,
888
+ "orientation": "horizontal"
889
+ },
890
+ "optimization": {
891
+ "final_loss": 0.0,
892
+ "converged": true,
893
+ "note": "using explicit params"
894
+ },
895
+ "coords": {}
896
+ }
897
+ },
898
+ {
899
+ "dataset": "train",
900
+ "index": 7756,
901
+ "conic_type": "hyperbola",
902
+ "image_path": "samples/train/hyperbola/problem_7756.png",
903
+ "problem": {
904
+ "text": "Given the hyperbola $\\frac{x^{2}}{3}-y^{2}=1$, the left and right foci are $F_{1}$ and $F_{2}$ respectively, $P$ is a point on the right branch of the hyperbola, and the coordinates of point $Q$ are $(-2,3)$. Then the minimum value of $|P Q|+|P F_{1}|$ is?",
905
+ "fact_expressions": "G: Hyperbola;Expression(G) = (x^2/3 - y^2 = 1);F1: Point;F2: Point;LeftFocus(G) = F1;RightFocus(G) = F2;P: Point;PointOnCurve(P, RightPart(G));Q: Point;Coordinate(Q) = (-2, 3)",
906
+ "query_expressions": "Min(Abs(LineSegmentOf(P, F1)) + Abs(LineSegmentOf(P, Q)))",
907
+ "answer_expressions": "5+2*sqrt(3)",
908
+ "process": ""
909
+ },
910
+ "sdf_annotation": {
911
+ "params": {
912
+ "a": 1.7320508075688772,
913
+ "b": 1.0,
914
+ "orientation": "horizontal"
915
+ },
916
+ "optimization": {
917
+ "final_loss": 0.0,
918
+ "converged": true,
919
+ "note": "using explicit params"
920
+ },
921
+ "coords": {
922
+ "Q": [
923
+ -2.0,
924
+ 3.0
925
+ ]
926
+ }
927
+ }
928
+ },
929
+ {
930
+ "dataset": "train",
931
+ "index": 4,
932
+ "conic_type": "parabola",
933
+ "image_path": "samples/train/parabola/problem_0004.png",
934
+ "problem": {
935
+ "text": "The parabola $x^{2}=a y$ passes through the point $A(1, \\frac{1}{4})$, then the distance from point $A$ to the focus of this parabola is?",
936
+ "fact_expressions": "G: Parabola;Expression(G) = (x^2 = a*y);a: Number;A: Point;Coordinate(A) = (1, 1/4);PointOnCurve(A, G)",
937
+ "query_expressions": "Distance(A, Focus(G))",
938
+ "answer_expressions": "5/4",
939
+ "process": "\\because the parabola x^{2}=ay passes through point A(1,\\frac{1}{4}), \\therefore 1^{2}=a\\times\\frac{1}{4}, solving gives a=4. Therefore, the equation of the parabola is x^{2}=4y, yielding its focus at F(0,1) and directrix equation y=-1. \\because the distance from any point on the parabola to the focus equals the distance from that point to the directrix of the parabola, \\therefore the distance from point A to the focus of this parabola is y_{4}-(-1)=\\frac{1}{4}+1=\\frac{5}{4}"
940
+ },
941
+ "sdf_annotation": {
942
+ "params": {
943
+ "p": 0.9959803819656372,
944
+ "direction": "up"
945
+ },
946
+ "optimization": {
947
+ "final_loss": 3.6780886603082763e-07,
948
+ "converged": true,
949
+ "iterations": 56
950
+ },
951
+ "coords": {
952
+ "A": [
953
+ 1.0,
954
+ 0.25
955
+ ]
956
+ }
957
+ }
958
+ },
959
+ {
960
+ "dataset": "train",
961
+ "index": 3812,
962
+ "conic_type": "parabola",
963
+ "image_path": "samples/train/parabola/problem_3812.png",
964
+ "problem": {
965
+ "text": "A point $M$ on the parabola $y=4 x^{2}$ is at a distance of $1$ from the focus. What is the ordinate of point $M$?",
966
+ "fact_expressions": "G: Parabola;Expression(G) = (y = 4*x^2);M: Point;PointOnCurve(M, G);Distance(M, Focus(G)) = 1",
967
+ "query_expressions": "YCoordinate(M)",
968
+ "answer_expressions": "15/16",
969
+ "process": "From $ y = 4x^{2} $, we obtain $ x^{2} = \\frac{1}{4}y $, so the focus of the parabola is $ F(0, \\frac{1}{16}) $, and the equation of the directrix is $ y = -\\frac{1}{16} $. Let $ M(x_{M}, y_{M}) $. By the definition of the parabola, we have $ MF = y_{M} + \\frac{1}{16} = 1 $, so $ y_{M} = \\frac{15}{16} $."
970
+ },
971
+ "sdf_annotation": {
972
+ "params": {
973
+ "p": 0.0625,
974
+ "direction": "up"
975
+ },
976
+ "optimization": {
977
+ "final_loss": 0.0,
978
+ "converged": true,
979
+ "note": "using explicit params"
980
+ },
981
+ "coords": {}
982
+ }
983
+ },
984
+ {
985
+ "dataset": "train",
986
+ "index": 7755,
987
+ "conic_type": "parabola",
988
+ "image_path": "samples/train/parabola/problem_7755.png",
989
+ "problem": {
990
+ "text": "If the distance from point $P$ on the parabola $x^{2}=8y$ to the focus is $12$, then what is the distance from $P$ to the $x$-axis?",
991
+ "fact_expressions": "G: Parabola;P: Point;Expression(G) = (x^2 = 8*y);PointOnCurve(P, G);Distance(P, Focus(G)) = 12",
992
+ "query_expressions": "Distance(P, xAxis)",
993
+ "answer_expressions": "10",
994
+ "process": "Since the parabola is $x^{2}=8y$, the focus coordinates are $(0,2)$, and the directrix equation is $y=-2$. Because the distance from point $P$ to the focus is $12$, according to the definition of a parabola, the distance from $P$ to the directrix is also $12$. Therefore, the distance from point $P$ to the $x$-axis is $10$."
995
+ },
996
+ "sdf_annotation": {
997
+ "params": {
998
+ "p": 2.0,
999
+ "direction": "up"
1000
+ },
1001
+ "optimization": {
1002
+ "final_loss": 0.0,
1003
+ "converged": true,
1004
+ "note": "using explicit params"
1005
+ },
1006
+ "coords": {}
1007
+ }
1008
+ }
1009
+ ]
annotations/test.json ADDED
The diff for this file is too large to render. See raw diff
 
annotations/train.json ADDED
The diff for this file is too large to render. See raw diff
 
create_samples.py ADDED
@@ -0,0 +1,71 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Create a samples directory with a few examples from each curve type.
4
+ """
5
+ import os
6
+ import shutil
7
+ import json
8
+
9
+ # Configuration
10
+ SAMPLES_PER_TYPE = 3 # Number of samples per curve type per dataset
11
+ SOURCE_DIR = "results"
12
+ TARGET_DIR = "samples"
13
+
14
+ def create_samples():
15
+ # Remove existing samples directory
16
+ if os.path.exists(TARGET_DIR):
17
+ shutil.rmtree(TARGET_DIR)
18
+
19
+ os.makedirs(TARGET_DIR)
20
+
21
+ datasets = ['dev', 'test', 'train']
22
+ curve_types = ['circle', 'ellipse', 'hyperbola', 'parabola']
23
+
24
+ total_copied = 0
25
+
26
+ for dataset in datasets:
27
+ dataset_dir = os.path.join(SOURCE_DIR, dataset)
28
+ if not os.path.exists(dataset_dir):
29
+ continue
30
+
31
+ target_dataset_dir = os.path.join(TARGET_DIR, dataset)
32
+ os.makedirs(target_dataset_dir, exist_ok=True)
33
+
34
+ # Copy summary.json
35
+ summary_src = os.path.join(dataset_dir, 'summary.json')
36
+ if os.path.exists(summary_src):
37
+ shutil.copy(summary_src, target_dataset_dir)
38
+
39
+ for curve_type in curve_types:
40
+ src_type_dir = os.path.join(dataset_dir, curve_type)
41
+ if not os.path.exists(src_type_dir):
42
+ continue
43
+
44
+ target_type_dir = os.path.join(target_dataset_dir, curve_type)
45
+ os.makedirs(target_type_dir, exist_ok=True)
46
+
47
+ # Get PNG files and sort them
48
+ png_files = sorted([f for f in os.listdir(src_type_dir) if f.endswith('.png')])
49
+
50
+ # Select samples (first, middle, last)
51
+ if len(png_files) == 0:
52
+ continue
53
+ elif len(png_files) <= SAMPLES_PER_TYPE:
54
+ selected = png_files
55
+ else:
56
+ indices = [0, len(png_files)//2, len(png_files)-1]
57
+ selected = [png_files[i] for i in indices[:SAMPLES_PER_TYPE]]
58
+
59
+ # Copy selected files
60
+ for filename in selected:
61
+ src = os.path.join(src_type_dir, filename)
62
+ dst = os.path.join(target_type_dir, filename)
63
+ shutil.copy(src, dst)
64
+ total_copied += 1
65
+ print(f" Copied: {dataset}/{curve_type}/{filename}")
66
+
67
+ print(f"\n✓ Created samples directory with {total_copied} files")
68
+ print(f" Location: {os.path.abspath(TARGET_DIR)}")
69
+
70
+ if __name__ == "__main__":
71
+ create_samples()
data/dev_en.json ADDED
The diff for this file is too large to render. See raw diff
 
data/test_en.json ADDED
The diff for this file is too large to render. See raw diff
 
data/train_en.json ADDED
The diff for this file is too large to render. See raw diff
 
requirements.txt ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # =============================================================================
2
+ # Image_SDF: Analytic Geometry Diagram Synthesis
3
+ # =============================================================================
4
+ # Python >= 3.9 required
5
+ # Installation: pip install -r requirements.txt
6
+ # =============================================================================
7
+
8
+ # -----------------------------------------------------------------------------
9
+ # Core Dependencies
10
+ # -----------------------------------------------------------------------------
11
+
12
+ # Deep Learning Framework
13
+ # - Tensor operations and automatic differentiation
14
+ # - AdamW optimizer for constraint satisfaction
15
+ torch>=2.0.0
16
+
17
+ # Numerical Computing
18
+ # - Array operations and linear algebra
19
+ # - Mathematical functions (sqrt, trigonometric)
20
+ numpy>=1.24.0
21
+
22
+ # Visualization
23
+ # - SDF field rendering and zero-level set visualization
24
+ # - Figure generation with annotations
25
+ matplotlib>=3.7.0
26
+
27
+ # Progress Tracking
28
+ # - Batch processing progress bars
29
+ tqdm>=4.65.0
30
+
31
+ # -----------------------------------------------------------------------------
32
+ # Optional Dependencies (uncomment if needed)
33
+ # -----------------------------------------------------------------------------
34
+
35
+ # Enhanced numerical methods
36
+ # scipy>=1.10.0
37
+
38
+ # Image processing utilities
39
+ # pillow>=10.0.0
40
+
41
+ # Better plot styling
42
+ # seaborn>=0.12.0
43
+
44
+ # Type checking (development)
45
+ # mypy>=1.0.0
46
+
47
+ # Testing (development)
48
+ # pytest>=7.0.0
results/.DS_Store ADDED
Binary file (10.2 kB). View file
 
results/dev/.DS_Store ADDED
Binary file (8.2 kB). View file
 
results/dev/parabola/problem_0025.png ADDED

Git LFS Details

  • SHA256: d26136e4dcadd6dbf90ebc9d9a5a99ad836535293f370a2db696688df8b623e1
  • Pointer size: 130 Bytes
  • Size of remote file: 33.9 kB
results/dev/parabola/problem_0145.png ADDED

Git LFS Details

  • SHA256: a03806a2868a160e0e5c3512c105d23263e03890e5ea51be27ad9f062f25a1d8
  • Pointer size: 130 Bytes
  • Size of remote file: 33.9 kB
results/dev/parabola/problem_0150.png ADDED

Git LFS Details

  • SHA256: d26136e4dcadd6dbf90ebc9d9a5a99ad836535293f370a2db696688df8b623e1
  • Pointer size: 130 Bytes
  • Size of remote file: 33.9 kB
results/dev/parabola/problem_0151.png ADDED

Git LFS Details

  • SHA256: 9a3470f30c22a04b86c9ec38722c1a73d39fcbafb9eba13111707beb3a6b937f
  • Pointer size: 130 Bytes
  • Size of remote file: 30.9 kB
results/dev/parabola/problem_0179.png ADDED

Git LFS Details

  • SHA256: b6e17d1eff8a7214131316ede762854cbac795f353b7f421b0749536400480de
  • Pointer size: 130 Bytes
  • Size of remote file: 29.9 kB
results/dev/parabola/problem_0186.png ADDED

Git LFS Details

  • SHA256: 6865760693380c6ff0e8b55541481a6e91af2a068bbf684bf5a831c5674bc43c
  • Pointer size: 130 Bytes
  • Size of remote file: 27.4 kB
results/dev/parabola/problem_0409.png ADDED

Git LFS Details

  • SHA256: a8d059a7ebcc118272841ab9932aa19c110b145c5a539d79e0ba23ca898b41a3
  • Pointer size: 130 Bytes
  • Size of remote file: 34.3 kB
results/dev/parabola/problem_0541.png ADDED

Git LFS Details

  • SHA256: 7106ac7e4927f48f59ef575281d896237b297a95534737f38cc21a245d14e5eb
  • Pointer size: 130 Bytes
  • Size of remote file: 34.5 kB
results/dev/parabola/problem_0569.png ADDED

Git LFS Details

  • SHA256: 75bfba317e0675c775e295613a0a704f62254989862df89927993f46d21a0f88
  • Pointer size: 130 Bytes
  • Size of remote file: 29.9 kB
results/dev/parabola/problem_0596.png ADDED

Git LFS Details

  • SHA256: ef757d9de68e96321c53df002ec1f12ca01c27c8747fe64866ef65b8e123174d
  • Pointer size: 130 Bytes
  • Size of remote file: 33.9 kB
results/dev/parabola/problem_0637.png ADDED

Git LFS Details

  • SHA256: 01fdcd1bd37f7612fa0de34aa49a9336f65bd560f10ffacdec5002f0e65da3b4
  • Pointer size: 130 Bytes
  • Size of remote file: 34.5 kB
results/dev/parabola/problem_0743.png ADDED

Git LFS Details

  • SHA256: ef757d9de68e96321c53df002ec1f12ca01c27c8747fe64866ef65b8e123174d
  • Pointer size: 130 Bytes
  • Size of remote file: 33.9 kB
results/dev/parabola/problem_0794.png ADDED

Git LFS Details

  • SHA256: ef757d9de68e96321c53df002ec1f12ca01c27c8747fe64866ef65b8e123174d
  • Pointer size: 130 Bytes
  • Size of remote file: 33.9 kB
results/dev/parabola/problem_0804.png ADDED

Git LFS Details

  • SHA256: 7cb8b5e86026741d6a24de37bbf2f8b33545fac6bc797ae4c420130df0570211
  • Pointer size: 130 Bytes
  • Size of remote file: 30.4 kB
results/dev/parabola/problem_0958.png ADDED

Git LFS Details

  • SHA256: 4575f8f0520d7e3e0dea11b3dbb2d59ad813a8542f2ce6709dfca3a138fd92d5
  • Pointer size: 130 Bytes
  • Size of remote file: 33.9 kB
results/dev/summary.json ADDED
The diff for this file is too large to render. See raw diff
 
results/test/.DS_Store ADDED
Binary file (8.2 kB). View file
 
results/test/summary.json ADDED
The diff for this file is too large to render. See raw diff
 
results/train/.DS_Store ADDED
Binary file (14.3 kB). View file
 
results/train/summary.json ADDED
The diff for this file is too large to render. See raw diff
 
src/__pycache__/sdf_geo_solver.cpython-313.pyc ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ version https://git-lfs.github.com/spec/v1
2
+ oid sha256:056b7b1420e4c50b338528b19709d35f84ab65b8616f8a7c2fbef17231a78d2b
3
+ size 148145
src/main.py ADDED
@@ -0,0 +1,68 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ SDF-Based Analytic Geometry Solver
4
+ Main entry point for batch processing geometry problems.
5
+ """
6
+
7
+ import argparse
8
+ import sys
9
+ from pathlib import Path
10
+
11
+ # Add src directory to path for module imports
12
+ sys.path.insert(0, str(Path(__file__).parent))
13
+
14
+ from sdf_geo import SDFBatchProcessor
15
+
16
+
17
+ def main():
18
+ parser = argparse.ArgumentParser(
19
+ description='SDF-Based Geometry Solver - Automatic geometry visualization using Signed Distance Fields'
20
+ )
21
+ parser.add_argument(
22
+ '--input', '-i',
23
+ type=str,
24
+ default='data/test_en.json',
25
+ help='Path to input JSON file containing geometry problems'
26
+ )
27
+ parser.add_argument(
28
+ '--output', '-o',
29
+ type=str,
30
+ default='results',
31
+ help='Output directory for generated visualizations'
32
+ )
33
+ parser.add_argument(
34
+ '--max', '-m',
35
+ type=int,
36
+ default=None,
37
+ help='Maximum number of problems to process (default: all)'
38
+ )
39
+ parser.add_argument(
40
+ '--verbose', '-v',
41
+ action='store_true',
42
+ help='Enable verbose output during processing'
43
+ )
44
+
45
+ args = parser.parse_args()
46
+
47
+ # Resolve paths
48
+ input_path = Path(args.input)
49
+ output_path = Path(args.output)
50
+
51
+ # Check input file exists
52
+ if not input_path.exists():
53
+ print(f"Error: Input file not found: {input_path}")
54
+ return 1
55
+
56
+ # Create processor and run
57
+ processor = SDFBatchProcessor(str(output_path))
58
+ processor.process_batch(
59
+ str(input_path),
60
+ max_problems=args.max,
61
+ verbose=args.verbose
62
+ )
63
+
64
+ return 0
65
+
66
+
67
+ if __name__ == '__main__':
68
+ exit(main())
src/sdf_geo/__init__.py ADDED
@@ -0,0 +1,51 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SDF-Based Analytic Geometry Solver Package
3
+
4
+ Core modules for geometric problem solving using Signed Distance Fields.
5
+ """
6
+
7
+ from .primitives import (
8
+ DEVICE,
9
+ SDFPrimitive,
10
+ PointSDF,
11
+ CircleSDF,
12
+ EllipseSDF,
13
+ HyperbolaSDF,
14
+ ParabolaSDF,
15
+ LineSDF,
16
+ LineSegmentSDF,
17
+ TriangleEdgesSDF,
18
+ TriangleFillSDF,
19
+ RightAngleSDF
20
+ )
21
+
22
+ from .constraints import GeometricConstraints
23
+ from .parser import ProblemParser
24
+ from .renderer import SDFRenderer
25
+ from .optimizer import GeometryOptimizer
26
+ from .processor import SDFBatchProcessor
27
+
28
+ __all__ = [
29
+ # Device
30
+ 'DEVICE',
31
+ # Primitives
32
+ 'SDFPrimitive',
33
+ 'PointSDF',
34
+ 'CircleSDF',
35
+ 'EllipseSDF',
36
+ 'HyperbolaSDF',
37
+ 'ParabolaSDF',
38
+ 'LineSDF',
39
+ 'LineSegmentSDF',
40
+ 'TriangleEdgesSDF',
41
+ 'TriangleFillSDF',
42
+ 'RightAngleSDF',
43
+ # Core classes
44
+ 'GeometricConstraints',
45
+ 'ProblemParser',
46
+ 'SDFRenderer',
47
+ 'GeometryOptimizer',
48
+ 'SDFBatchProcessor',
49
+ ]
50
+
51
+ __version__ = '1.0.0'
src/sdf_geo/__pycache__/__init__.cpython-313.pyc ADDED
Binary file (1.01 kB). View file
 
src/sdf_geo/__pycache__/constraints.cpython-313.pyc ADDED
Binary file (5.63 kB). View file
 
src/sdf_geo/__pycache__/optimizer.cpython-313.pyc ADDED
Binary file (3.5 kB). View file
 
src/sdf_geo/__pycache__/parser.cpython-313.pyc ADDED
Binary file (36 kB). View file
 
src/sdf_geo/__pycache__/primitives.cpython-313.pyc ADDED
Binary file (24.2 kB). View file
 
src/sdf_geo/__pycache__/processor.cpython-313.pyc ADDED
Binary file (65.8 kB). View file
 
src/sdf_geo/__pycache__/renderer.cpython-313.pyc ADDED
Binary file (4.89 kB). View file
 
src/sdf_geo/constraints.py ADDED
@@ -0,0 +1,82 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Geometric Constraints - Differentiable constraint functions for optimization.
3
+ Following GeoSDF paper Section 5.
4
+ """
5
+
6
+ import torch
7
+ from typing import Callable
8
+
9
+
10
+ class GeometricConstraints:
11
+ """Collection of differentiable geometric constraint functions."""
12
+
13
+ @staticmethod
14
+ def point_on_curve(sdf: Callable, point: torch.Tensor) -> torch.Tensor:
15
+ """Constraint: point lies on curve (SDF = 0)."""
16
+ return sdf(point.unsqueeze(0))**2
17
+
18
+ @staticmethod
19
+ def distance_constraint(p1: torch.Tensor, p2: torch.Tensor,
20
+ target_dist: float) -> torch.Tensor:
21
+ """Constraint: distance between two points equals target."""
22
+ actual_dist = torch.norm(p1 - p2)
23
+ return (actual_dist - target_dist)**2
24
+
25
+ @staticmethod
26
+ def eccentricity_ellipse(a: torch.Tensor, b: torch.Tensor,
27
+ target_e: float) -> torch.Tensor:
28
+ """Constraint: ellipse eccentricity."""
29
+ c_squared = a**2 - b**2
30
+ c = torch.sqrt(torch.clamp(c_squared, min=1e-8))
31
+ e = c / a
32
+ return (e - target_e)**2
33
+
34
+ @staticmethod
35
+ def eccentricity_hyperbola(a: torch.Tensor, b: torch.Tensor,
36
+ target_e: float) -> torch.Tensor:
37
+ """Constraint: hyperbola eccentricity e = c/a where c² = a² + b²."""
38
+ c_squared = a**2 + b**2
39
+ c = torch.sqrt(c_squared)
40
+ e = c / (a + 1e-8)
41
+ return (e - target_e)**2
42
+
43
+ @staticmethod
44
+ def asymptote_slope(a: torch.Tensor, b: torch.Tensor,
45
+ target_slope: float) -> torch.Tensor:
46
+ """Constraint: hyperbola asymptote slope b/a."""
47
+ actual_slope = b / (a + 1e-8)
48
+ return (actual_slope - target_slope)**2
49
+
50
+ @staticmethod
51
+ def focus_constraint(a: torch.Tensor, b: torch.Tensor,
52
+ focus_coord: float, is_hyperbola: bool = False) -> torch.Tensor:
53
+ """Constraint: focus at specific coordinate."""
54
+ if is_hyperbola:
55
+ c_squared = a**2 + b**2
56
+ else:
57
+ c_squared = a**2 - b**2
58
+ c = torch.sqrt(torch.clamp(c_squared, min=1e-8))
59
+ return (c - abs(focus_coord))**2
60
+
61
+ @staticmethod
62
+ def focus_constraint_hyperbola(a: torch.Tensor, b: torch.Tensor,
63
+ target_c: float) -> torch.Tensor:
64
+ """Constraint: hyperbola focus distance c where c² = a² + b²."""
65
+ c_squared = a**2 + b**2
66
+ c = torch.sqrt(c_squared)
67
+ return (c - target_c)**2
68
+
69
+ @staticmethod
70
+ def positive_constraint(param: torch.Tensor, min_val: float = 0.1) -> torch.Tensor:
71
+ """Soft constraint to keep parameter positive."""
72
+ return torch.relu(min_val - param)**2
73
+
74
+ @staticmethod
75
+ def crowd_penalty(positions: list, min_dist: float = 0.5) -> torch.Tensor:
76
+ """Penalty for elements being too close together."""
77
+ penalty = torch.tensor(0.0)
78
+ for i, p1 in enumerate(positions):
79
+ for p2 in positions[i+1:]:
80
+ dist = torch.norm(p1 - p2)
81
+ penalty = penalty + torch.relu(min_dist - dist)**2
82
+ return penalty
src/sdf_geo/optimizer.py ADDED
@@ -0,0 +1,81 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Geometry Optimizer Module
3
+ Gradient-based optimization for geometric constraints.
4
+ """
5
+
6
+ import torch
7
+ from typing import Dict, List, Callable
8
+
9
+
10
+ class GeometryOptimizer:
11
+ """
12
+ Optimizer for geometric constraints using gradient descent.
13
+ Following GeoSDF paper methodology with AdamW optimizer.
14
+ """
15
+
16
+ def __init__(self, learning_rate: float = 0.1, max_iterations: int = 500,
17
+ convergence_threshold: float = 1e-6):
18
+ self.learning_rate = learning_rate
19
+ self.max_iterations = max_iterations
20
+ self.convergence_threshold = convergence_threshold
21
+
22
+ def optimize(self, sdf, constraints: List[Callable],
23
+ weights: List[float], verbose: bool = False) -> Dict:
24
+ """
25
+ Optimize SDF parameters to satisfy constraints.
26
+
27
+ Args:
28
+ sdf: SDF primitive with learnable parameters
29
+ constraints: List of constraint functions returning loss tensors
30
+ weights: Weight for each constraint
31
+ verbose: Print optimization progress
32
+
33
+ Returns:
34
+ Dictionary with optimization results
35
+ """
36
+ # Get trainable parameters
37
+ params = [p for p in sdf.parameters() if p.requires_grad]
38
+ if not params:
39
+ return {'final_loss': 0.0, 'converged': True, 'iterations': 0}
40
+
41
+ optimizer = torch.optim.AdamW(params, lr=self.learning_rate)
42
+ scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
43
+ optimizer, T_max=self.max_iterations, eta_min=1e-4
44
+ )
45
+
46
+ prev_loss = float('inf')
47
+ converged = False
48
+
49
+ for i in range(self.max_iterations):
50
+ optimizer.zero_grad()
51
+
52
+ # Compute weighted sum of constraint losses
53
+ total_loss = torch.tensor(0.0)
54
+ for constraint, weight in zip(constraints, weights):
55
+ loss = constraint()
56
+ total_loss = total_loss + weight * loss
57
+
58
+ # Backward pass
59
+ total_loss.backward()
60
+
61
+ # Gradient clipping for stability
62
+ torch.nn.utils.clip_grad_norm_(params, max_norm=1.0)
63
+
64
+ optimizer.step()
65
+ scheduler.step()
66
+
67
+ # Check convergence
68
+ current_loss = total_loss.item()
69
+ if abs(prev_loss - current_loss) < self.convergence_threshold:
70
+ converged = True
71
+ break
72
+ prev_loss = current_loss
73
+
74
+ if verbose and i % 100 == 0:
75
+ print(f" Iteration {i}: loss = {current_loss:.6f}")
76
+
77
+ return {
78
+ 'final_loss': current_loss,
79
+ 'converged': converged,
80
+ 'iterations': i + 1
81
+ }
src/sdf_geo/parser.py ADDED
@@ -0,0 +1,1184 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Problem Parser Module
3
+ Extracts geometric parameters from problem expressions.
4
+ """
5
+
6
+ import re
7
+ import numpy as np
8
+ from typing import Dict, List, Tuple, Optional
9
+
10
+
11
+ class ProblemParser:
12
+ """Parse problem expressions into geometric constraints and SDFs."""
13
+
14
+ def __init__(self):
15
+ pass
16
+
17
+ def parse_line(self, fact_expr: str) -> Optional[Dict]:
18
+ """Parse line expression."""
19
+ # Expression(G) = (x + y - 1 = 0) or similar
20
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(([^)]+)\s*=\s*0\)', fact_expr)
21
+ if match:
22
+ expr = match.group(1)
23
+ # Parse ax + by + c = 0 format
24
+ # Try to extract coefficients
25
+ a, b, c = 0.0, 0.0, 0.0
26
+
27
+ # Match patterns like "x + y - 1" or "2*x - 3*y + 5"
28
+ x_match = re.search(r'([+-]?\s*\d*\.?\d*)\s*\*?\s*x', expr)
29
+ y_match = re.search(r'([+-]?\s*\d*\.?\d*)\s*\*?\s*y', expr)
30
+
31
+ if x_match:
32
+ coef = x_match.group(1).replace(' ', '')
33
+ if coef in ['', '+']:
34
+ a = 1.0
35
+ elif coef == '-':
36
+ a = -1.0
37
+ else:
38
+ try:
39
+ a = float(coef)
40
+ except:
41
+ a = 1.0
42
+
43
+ if y_match:
44
+ coef = y_match.group(1).replace(' ', '')
45
+ if coef in ['', '+']:
46
+ b = 1.0
47
+ elif coef == '-':
48
+ b = -1.0
49
+ else:
50
+ try:
51
+ b = float(coef)
52
+ except:
53
+ b = 1.0
54
+
55
+ # Find constant term
56
+ const_match = re.search(r'([+-]\s*\d+\.?\d*)\s*(?:=|$)', expr)
57
+ if const_match:
58
+ try:
59
+ c = float(const_match.group(1).replace(' ', ''))
60
+ except:
61
+ c = 0.0
62
+
63
+ if a != 0 or b != 0:
64
+ return {
65
+ 'type': 'line',
66
+ 'a': a,
67
+ 'b': b,
68
+ 'c': c,
69
+ 'equation': expr
70
+ }
71
+
72
+ # Check for Slope constraint - sqrt format
73
+ slope_match = re.search(r'Slope\(\w+\)\s*=\s*sqrt\((\d+)\)', fact_expr)
74
+ if slope_match:
75
+ slope = np.sqrt(float(slope_match.group(1)))
76
+ return {
77
+ 'type': 'line',
78
+ 'slope': slope,
79
+ 'symbolic': True
80
+ }
81
+
82
+ # Check for Slope constraint - numeric format
83
+ slope_match = re.search(r'Slope\(\w+\)\s*=\s*([\d.]+)', fact_expr)
84
+ if slope_match:
85
+ return {
86
+ 'type': 'line',
87
+ 'slope': float(slope_match.group(1)),
88
+ 'symbolic': True
89
+ }
90
+
91
+ return None
92
+
93
+ def parse_circle(self, fact_expr: str) -> Optional[Dict]:
94
+ """Parse circle expression."""
95
+
96
+ # Format 1: (x-a)^2 + (y-b)^2 = r^2
97
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(\(x-([^)]+)\)\^2\s*\+\s*\(y-([^)]+)\)\^2\s*=\s*(\d+)\)', fact_expr)
98
+ if match:
99
+ return {
100
+ 'type': 'circle',
101
+ 'center': (float(match.group(1)), float(match.group(2))),
102
+ 'radius': np.sqrt(float(match.group(3)))
103
+ }
104
+
105
+ # Format 2: x^2 + (y-a)^2 = r (center at origin or on axis)
106
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*\+\s*\(([+-]?\s*\d*\.?\d*)\s*[+-]\s*y\)\^2\s*=\s*(\d+)\)', fact_expr)
107
+ if match:
108
+ cy = -float(match.group(1).replace(' ', '')) if match.group(1) else 0.0
109
+ return {
110
+ 'type': 'circle',
111
+ 'center': (0.0, cy),
112
+ 'radius': np.sqrt(float(match.group(2)))
113
+ }
114
+
115
+ # Format 3: y^2 + (x-a)^2 = r or y^2 + (x+a)^2 = r
116
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*\+\s*\(x\s*([+-])\s*(\d+\.?\d*)\)\^2\s*=\s*(\d+\.?\d*)\)', fact_expr)
117
+ if match:
118
+ sign = -1 if match.group(1) == '-' else 1
119
+ cx = sign * float(match.group(2))
120
+ return {
121
+ 'type': 'circle',
122
+ 'center': (cx, 0.0),
123
+ 'radius': np.sqrt(float(match.group(3)))
124
+ }
125
+
126
+ # Format 4: x^2 + y^2 = r (center at origin)
127
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*\+\s*y\^2\s*=\s*(\d+\.?\d*)\)', fact_expr)
128
+ if match:
129
+ return {
130
+ 'type': 'circle',
131
+ 'center': (0.0, 0.0),
132
+ 'radius': np.sqrt(float(match.group(1)))
133
+ }
134
+
135
+ # Format 5: Check if it's explicitly declared as Circle type
136
+ if re.search(r'\w+:\s*Circle', fact_expr):
137
+ # Try more general patterns
138
+ # (x + a)^2 + (y - b)^2 = r
139
+ match = re.search(r'\(x\s*([+-])\s*(\d+\.?\d*)\)\^2\s*\+\s*\(y\s*([+-])\s*(\d+\.?\d*)\)\^2\s*=\s*(\d+\.?\d*)', fact_expr)
140
+ if match:
141
+ cx = float(match.group(2)) * (-1 if match.group(1) == '+' else 1)
142
+ cy = float(match.group(4)) * (-1 if match.group(3) == '+' else 1)
143
+ return {
144
+ 'type': 'circle',
145
+ 'center': (cx, cy),
146
+ 'radius': np.sqrt(float(match.group(5)))
147
+ }
148
+
149
+ # Check for circle defined by diameter
150
+ if 'IsDiameter' in fact_expr:
151
+ return {
152
+ 'type': 'circle',
153
+ 'from_diameter': True
154
+ }
155
+
156
+ # Check for circle defined by slope product = -1 (perpendicular)
157
+ # Pattern: Slope(LineSegmentOf(P, A)) * Slope(LineSegmentOf(P, B)) = -1
158
+ # This means angle APB = 90°, so P lies on circle with diameter AB
159
+ slope_match = re.search(r'Slope\(LineSegmentOf\(\w+,\s*(\w+)\)\)\s*\*\s*Slope\(LineSegmentOf\(\w+,\s*(\w+)\)\)\s*=\s*-1', fact_expr)
160
+ if slope_match:
161
+ pt1_name = slope_match.group(1)
162
+ pt2_name = slope_match.group(2)
163
+ coords = self.parse_coordinates(fact_expr)
164
+ if pt1_name in coords and pt2_name in coords:
165
+ x1, y1 = coords[pt1_name]
166
+ x2, y2 = coords[pt2_name]
167
+ # Circle with diameter AB: center = midpoint, radius = |AB|/2
168
+ cx = (x1 + x2) / 2
169
+ cy = (y1 + y2) / 2
170
+ radius = np.sqrt((x2 - x1)**2 + (y2 - y1)**2) / 2
171
+ return {
172
+ 'type': 'circle',
173
+ 'center': (cx, cy),
174
+ 'radius': radius,
175
+ 'from_constraints': True
176
+ }
177
+
178
+ # General circle equation: x^2 + y^2 + Dx + Ey + F = 0
179
+ # Center: (-D/2, -E/2), Radius: sqrt(D²/4 + E²/4 - F)
180
+ # Pattern: ax^2 + by^2 + Dx + Ey + F = 0 where coefficients can vary
181
+ general_match = re.search(r'Expression\(\w+\)\s*=\s*\(([^)]+x\^2[^)]+y\^2[^)]+)\s*=\s*0\)', fact_expr)
182
+ if general_match and 'Circle' in fact_expr:
183
+ expr = general_match.group(1)
184
+ # Parse coefficients: D*x, E*y, F (constant)
185
+ D = E = F = 0.0
186
+
187
+ # Find coefficient of x (not x^2)
188
+ d_match = re.search(r'([+-]?\s*\d*\.?\d*)\s*\*?\s*x(?!\^)', expr)
189
+ if d_match:
190
+ d_str = d_match.group(1).replace(' ', '')
191
+ D = float(d_str) if d_str and d_str not in ['+', '-'] else (1.0 if d_str == '+' or d_str == '' else -1.0)
192
+
193
+ # Find coefficient of y (not y^2)
194
+ e_match = re.search(r'([+-]?\s*\d*\.?\d*)\s*\*?\s*y(?!\^)', expr)
195
+ if e_match:
196
+ e_str = e_match.group(1).replace(' ', '')
197
+ E = float(e_str) if e_str and e_str not in ['+', '-'] else (1.0 if e_str == '+' or e_str == '' else -1.0)
198
+
199
+ # Find constant term
200
+ const_match = re.search(r'([+-]\s*\d+\.?\d*)\s*(?:=|$)', expr)
201
+ if const_match:
202
+ f_str = const_match.group(1).replace(' ', '')
203
+ F = float(f_str)
204
+
205
+ cx = -D / 2
206
+ cy = -E / 2
207
+ r_sq = D**2 / 4 + E**2 / 4 - F
208
+ if r_sq > 0:
209
+ return {
210
+ 'type': 'circle',
211
+ 'center': (cx, cy),
212
+ 'radius': np.sqrt(r_sq),
213
+ 'from_constraints': True
214
+ }
215
+
216
+ # Shifted center circle: (x+h)^2 + y^2 = r^2 or (x-h)^2 + y^2 = r^2
217
+ shifted_match = re.search(r'Expression\(\w+\)\s*=\s*\(\(x([+-])(\d+\.?\d*)\)\^2\s*\+\s*y\^2\s*=\s*(\d+\.?\d*)\)', fact_expr)
218
+ if shifted_match:
219
+ sign = shifted_match.group(1)
220
+ h = float(shifted_match.group(2))
221
+ r_sq = float(shifted_match.group(3))
222
+ cx = -h if sign == '+' else h
223
+ return {
224
+ 'type': 'circle',
225
+ 'center': (cx, 0.0),
226
+ 'radius': np.sqrt(r_sq),
227
+ }
228
+
229
+ # (x±h)^2 + (y±k)^2 = r^2
230
+ 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)
231
+ if shifted_match2:
232
+ sign_x = shifted_match2.group(1)
233
+ h = float(shifted_match2.group(2))
234
+ sign_y = shifted_match2.group(3)
235
+ k = float(shifted_match2.group(4))
236
+ r_sq = float(shifted_match2.group(5))
237
+ cx = -h if sign_x == '+' else h
238
+ cy = -k if sign_y == '+' else k
239
+ return {
240
+ 'type': 'circle',
241
+ 'center': (cx, cy),
242
+ 'radius': np.sqrt(r_sq),
243
+ }
244
+
245
+ return None
246
+
247
+ def parse_ellipse(self, fact_expr: str) -> Optional[Dict]:
248
+ """Parse ellipse expression and return parameters."""
249
+ # x^2/a + y^2/b = 1
250
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2/(\d+)\s*\+\s*y\^2/(\d+)\s*=\s*1\)', fact_expr)
251
+ if match:
252
+ x_coef = float(match.group(1))
253
+ y_coef = float(match.group(2))
254
+ return {
255
+ 'type': 'ellipse',
256
+ 'x_coef': x_coef,
257
+ 'y_coef': y_coef,
258
+ 'a': np.sqrt(max(x_coef, y_coef)),
259
+ 'b': np.sqrt(min(x_coef, y_coef)),
260
+ 'major_axis': 'x' if x_coef > y_coef else 'y'
261
+ }
262
+
263
+ # y^2/b + x^2/a = 1
264
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2/(\d+)\s*\+\s*x\^2/(\d+)\s*=\s*1\)', fact_expr)
265
+ if match:
266
+ y_coef = float(match.group(1))
267
+ x_coef = float(match.group(2))
268
+ return {
269
+ 'type': 'ellipse',
270
+ 'x_coef': x_coef,
271
+ 'y_coef': y_coef,
272
+ 'a': np.sqrt(max(x_coef, y_coef)),
273
+ 'b': np.sqrt(min(x_coef, y_coef)),
274
+ 'major_axis': 'x' if x_coef > y_coef else 'y'
275
+ }
276
+
277
+ # x^2/a + y^2 = 1 (y has coefficient 1, x has numeric denominator)
278
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2/(\d+)\s*\+\s*y\^2\s*=\s*1\)', fact_expr)
279
+ if match:
280
+ x_coef = float(match.group(1))
281
+ y_coef = 1.0
282
+ return {
283
+ 'type': 'ellipse',
284
+ 'x_coef': x_coef,
285
+ 'y_coef': y_coef,
286
+ 'a': np.sqrt(x_coef), # a > b since x_coef > 1
287
+ 'b': 1.0,
288
+ 'major_axis': 'x'
289
+ }
290
+
291
+ # y^2/a + x^2 = 1 (x has coefficient 1, y has numeric denominator)
292
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2/(\d+)\s*\+\s*x\^2\s*=\s*1\)', fact_expr)
293
+ if match:
294
+ y_coef = float(match.group(1))
295
+ x_coef = 1.0
296
+ return {
297
+ 'type': 'ellipse',
298
+ 'x_coef': x_coef,
299
+ 'y_coef': y_coef,
300
+ 'a': np.sqrt(y_coef), # a > b since y_coef > 1
301
+ 'b': 1.0,
302
+ 'major_axis': 'y'
303
+ }
304
+
305
+ # y^2 + x^2/k^2 = 1 (y has coefficient 1)
306
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*\+\s*x\^2/\w+\^?2?\s*=\s*1\)', fact_expr)
307
+ if match:
308
+ return {
309
+ 'type': 'ellipse',
310
+ 'x_coef': 4.0, # default
311
+ 'y_coef': 1.0,
312
+ 'a': 2.0,
313
+ 'b': 1.0,
314
+ 'major_axis': 'x',
315
+ 'symbolic': True
316
+ }
317
+
318
+ # x^2 + y^2/k^2 = 1
319
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*\+\s*y\^2/\w+\^?2?\s*=\s*1\)', fact_expr)
320
+ if match:
321
+ return {
322
+ 'type': 'ellipse',
323
+ 'x_coef': 1.0,
324
+ 'y_coef': 4.0, # default
325
+ 'a': 2.0,
326
+ 'b': 1.0,
327
+ 'major_axis': 'y',
328
+ 'symbolic': True
329
+ }
330
+
331
+ # Ellipse with symbolic: y^2/b^2 + x^2/a^2 = 1 or x^2/a^2 + y^2/b^2 = 1
332
+ if re.search(r'Expression\(\w+\)\s*=\s*\([xy]\^2/\w+\^?2?\s*\+\s*[xy]\^2/\w+\^?2?\s*=\s*1\)', fact_expr):
333
+ return {
334
+ 'type': 'ellipse',
335
+ 'x_coef': 4.0,
336
+ 'y_coef': 3.0,
337
+ 'a': 2.0,
338
+ 'b': np.sqrt(3),
339
+ 'major_axis': 'x',
340
+ 'symbolic': True
341
+ }
342
+
343
+ # x^2 + N*y^2 = M (ellipse: x²/M + y²/(M/N) = 1)
344
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*\+\s*(\d+)\*y\^2\s*=\s*(\d+)\)', fact_expr)
345
+ if match:
346
+ n = float(match.group(1))
347
+ m = float(match.group(2))
348
+ a_sq = m # x coefficient
349
+ b_sq = m / n # y coefficient
350
+ a = np.sqrt(max(a_sq, b_sq))
351
+ b = np.sqrt(min(a_sq, b_sq))
352
+ return {
353
+ 'type': 'ellipse',
354
+ 'x_coef': a_sq,
355
+ 'y_coef': b_sq,
356
+ 'a': a,
357
+ 'b': b,
358
+ 'major_axis': 'x' if a_sq >= b_sq else 'y'
359
+ }
360
+
361
+ # N*x^2 + y^2 = M (ellipse: x²/(M/N) + y²/M = 1)
362
+ match = re.search(r'Expression\(\w+\)\s*=\s*\((\d+)\*x\^2\s*\+\s*y\^2\s*=\s*(\d+)\)', fact_expr)
363
+ if match:
364
+ n = float(match.group(1))
365
+ m = float(match.group(2))
366
+ a_sq = m / n # x coefficient
367
+ b_sq = m # y coefficient
368
+ a = np.sqrt(max(a_sq, b_sq))
369
+ b = np.sqrt(min(a_sq, b_sq))
370
+ return {
371
+ 'type': 'ellipse',
372
+ 'x_coef': a_sq,
373
+ 'y_coef': b_sq,
374
+ 'a': a,
375
+ 'b': b,
376
+ 'major_axis': 'x' if a_sq >= b_sq else 'y'
377
+ }
378
+
379
+ # Check for Ellipse with geometric constraints (no explicit expression)
380
+ if 'Ellipse' in fact_expr:
381
+ coords = self.parse_coordinates(fact_expr)
382
+ eccentricity = self.parse_eccentricity(fact_expr)
383
+
384
+ c = None
385
+ major_axis = 'x' # default
386
+
387
+ # Try to find focus coordinate from various patterns
388
+ # Pattern 1: Coordinate(F) = (c, 0); RightFocus(G) = F
389
+ for name, (fx, fy) in coords.items():
390
+ if f'RightFocus(' in fact_expr and f') = {name}' in fact_expr:
391
+ c = abs(fx)
392
+ major_axis = 'x'
393
+ break
394
+ elif f'LeftFocus(' in fact_expr and f') = {name}' in fact_expr:
395
+ c = abs(fx)
396
+ major_axis = 'x'
397
+ break
398
+ elif f'UpperFocus(' in fact_expr and f') = {name}' in fact_expr:
399
+ c = abs(fy)
400
+ major_axis = 'y'
401
+ break
402
+ elif f'LowerFocus(' in fact_expr and f') = {name}' in fact_expr:
403
+ c = abs(fy)
404
+ major_axis = 'y'
405
+ break
406
+
407
+ # Pattern 2: Coordinate(OneOf(Focus(...)))
408
+ if c is None:
409
+ focus_match = re.search(r'Coordinate\(OneOf\(Focus\(\w+\)\)\)\s*=\s*\(([^,]+),\s*([^)]+)\)', fact_expr)
410
+ if focus_match:
411
+ try:
412
+ fx = float(focus_match.group(1).strip())
413
+ fy = float(focus_match.group(2).strip())
414
+ c = abs(fx) if abs(fy) < 0.01 else abs(fy)
415
+ major_axis = 'x' if abs(fy) < 0.01 else 'y'
416
+ except:
417
+ pass
418
+
419
+ # Pattern 2b: Two foci with explicit coordinates: Focus(G) = {F1, F2}
420
+ if c is None:
421
+ foci_match = re.search(r'Focus\(\w+\)\s*=\s*\{(\w+),\s*(\w+)\}', fact_expr)
422
+ if foci_match:
423
+ f1_name = foci_match.group(1)
424
+ f2_name = foci_match.group(2)
425
+ if f1_name in coords and f2_name in coords:
426
+ fx1, fy1 = coords[f1_name]
427
+ fx2, fy2 = coords[f2_name]
428
+ # c = half the distance between foci
429
+ c = np.sqrt((fx2 - fx1)**2 + (fy2 - fy1)**2) / 2
430
+ major_axis = 'x' if abs(fy1) < 0.01 else 'y'
431
+
432
+ # Pattern 3: PointOnCurve(Focus(G), xAxis) - focus on x-axis
433
+ if c is None and 'PointOnCurve(Focus(' in fact_expr:
434
+ if 'xAxis' in fact_expr:
435
+ major_axis = 'x'
436
+ elif 'yAxis' in fact_expr:
437
+ major_axis = 'y'
438
+
439
+ # Pattern 4: Length(MajorAxis(G)) = k * Length(MinorAxis(G))
440
+ axis_ratio = None
441
+ ratio_match = re.search(r'Length\(MajorAxis\(\w+\)\)\s*=\s*(\d+)\s*\*\s*Length\(MinorAxis', fact_expr)
442
+ if ratio_match:
443
+ axis_ratio = float(ratio_match.group(1))
444
+
445
+ # Pattern 5: Length(MinorAxis(G)) = N or Length(MinorAxis(G)) = 2*sqrt(N)
446
+ minor_axis_len = None
447
+ match = re.search(r'Length\(MinorAxis\(\w+\)\)\s*=\s*2\*sqrt\((\d+)\)', fact_expr)
448
+ if match:
449
+ minor_axis_len = 2 * np.sqrt(float(match.group(1)))
450
+ else:
451
+ match = re.search(r'Length\(MinorAxis\(\w+\)\)\s*=\s*(\d+)', fact_expr)
452
+ if match:
453
+ minor_axis_len = float(match.group(1))
454
+
455
+ # Pattern 6: Length(MajorAxis(G)) = N
456
+ major_axis_len = None
457
+ match = re.search(r'Length\(MajorAxis\(\w+\)\)\s*=\s*2\*sqrt\((\d+)\)', fact_expr)
458
+ if match:
459
+ major_axis_len = 2 * np.sqrt(float(match.group(1)))
460
+ else:
461
+ match = re.search(r'Length\(MajorAxis\(\w+\)\)\s*=\s*(\d+)', fact_expr)
462
+ if match:
463
+ major_axis_len = float(match.group(1))
464
+
465
+ # Pattern 7: FocalLength(G) = N or 2*c = N
466
+ focal_length = None
467
+ match = re.search(r'FocalLength\(\w+\)\s*=\s*(\d+)', fact_expr)
468
+ if match:
469
+ focal_length = float(match.group(1))
470
+ else:
471
+ match = re.search(r'2\*c\s*=\s*(\d+)', fact_expr)
472
+ if match:
473
+ focal_length = float(match.group(1))
474
+
475
+ # Case: c from FocalLength + b from MinorAxis
476
+ if c is None and focal_length:
477
+ c = focal_length / 2
478
+
479
+ # Case: b from MinorAxis length
480
+ if minor_axis_len:
481
+ b_from_minor = minor_axis_len / 2
482
+ if c is not None:
483
+ a = np.sqrt(c**2 + b_from_minor**2)
484
+ b = b_from_minor
485
+
486
+ # Case: a from MajorAxis length
487
+ if major_axis_len:
488
+ a_from_major = major_axis_len / 2
489
+ if c is not None:
490
+ a = a_from_major
491
+ b = np.sqrt(a**2 - c**2) if a > c else None
492
+
493
+ # Compute a, b from constraints
494
+ a, b = None, None
495
+
496
+ # Case 1: c and eccentricity known → a = c/e, b = sqrt(a² - c²)
497
+ if c is not None and eccentricity and 0 < eccentricity < 1:
498
+ a = c / eccentricity
499
+ b = np.sqrt(a**2 - c**2)
500
+
501
+ # Case 2: eccentricity known + axis ratio → solve for a, b
502
+ elif eccentricity and 0 < eccentricity < 1 and axis_ratio:
503
+ # a/b = axis_ratio, e = sqrt(1 - b²/a²) = sqrt(1 - 1/ratio²)
504
+ # This gives us the ratio, need another constraint for absolute size
505
+ a = 2.0 * axis_ratio # default size
506
+ b = 2.0
507
+
508
+ # Case 3: axis ratio + point on curve
509
+ elif axis_ratio:
510
+ # Find a point on curve and solve
511
+ for name, (px, py) in coords.items():
512
+ if f'PointOnCurve({name}' in fact_expr:
513
+ # x²/a² + y²/b² = 1, a = ratio * b
514
+ # x²/(ratio*b)² + y²/b² = 1
515
+ # x²/ratio² + y² = b²
516
+ b_sq = px**2 / axis_ratio**2 + py**2
517
+ if b_sq > 0:
518
+ b = np.sqrt(b_sq)
519
+ a = axis_ratio * b
520
+ break
521
+
522
+ # Case 4: Two points on ellipse → solve for a, b
523
+ if a is None:
524
+ points_on_curve = []
525
+ for name, (px, py) in coords.items():
526
+ if f'PointOnCurve({name}' in fact_expr and name not in ['F', 'F1', 'F2']:
527
+ points_on_curve.append((px, py))
528
+
529
+ if len(points_on_curve) >= 2:
530
+ # x1²/a² + y1²/b² = 1
531
+ # x2²/a² + y2²/b² = 1
532
+ p1, p2 = points_on_curve[0], points_on_curve[1]
533
+ x1, y1 = p1
534
+ x2, y2 = p2
535
+
536
+ # Solve: let u = 1/a², v = 1/b²
537
+ # x1²u + y1²v = 1
538
+ # x2²u + y2²v = 1
539
+ det = x1**2 * y2**2 - x2**2 * y1**2
540
+ if abs(det) > 1e-10:
541
+ u = (y2**2 - y1**2) / det
542
+ v = (x1**2 - x2**2) / det
543
+ if u > 0 and v > 0:
544
+ a_sq = 1 / u
545
+ b_sq = 1 / v
546
+ a = np.sqrt(max(a_sq, b_sq))
547
+ b = np.sqrt(min(a_sq, b_sq))
548
+ major_axis = 'x' if a_sq >= b_sq else 'y'
549
+
550
+ # Return if we have valid a, b
551
+ if a is not None and b is not None and a > 0 and b > 0:
552
+ return {
553
+ 'type': 'ellipse',
554
+ 'x_coef': a**2 if major_axis == 'x' else b**2,
555
+ 'y_coef': b**2 if major_axis == 'x' else a**2,
556
+ 'a': a,
557
+ 'b': b,
558
+ 'major_axis': major_axis,
559
+ 'from_constraints': True
560
+ }
561
+
562
+ return None
563
+
564
+ def parse_hyperbola(self, fact_expr: str, main_conic_name: str = None) -> Optional[Dict]:
565
+ """Parse hyperbola expression.
566
+
567
+ Args:
568
+ fact_expr: The fact expression string
569
+ main_conic_name: If provided, only match Expression(main_conic_name) = ...
570
+ This avoids matching secondary hyperbola expressions.
571
+ """
572
+ # Build regex prefix based on main_conic_name
573
+ if main_conic_name:
574
+ expr_prefix = rf'Expression\({re.escape(main_conic_name)}\)\s*=\s*\('
575
+ else:
576
+ expr_prefix = r'Expression\(\w+\)\s*=\s*\('
577
+
578
+ # Horizontal: x^2/a - y^2/b = 1
579
+ match = re.search(expr_prefix + r'x\^2/(\d+)\s*-\s*y\^2/(\d+)\s*=\s*1\)', fact_expr)
580
+ if match:
581
+ a_sq = float(match.group(1))
582
+ b_sq = float(match.group(2))
583
+ return {
584
+ 'type': 'hyperbola',
585
+ 'a': np.sqrt(a_sq),
586
+ 'b': np.sqrt(b_sq),
587
+ 'a_squared': a_sq,
588
+ 'b_squared': b_sq,
589
+ 'orientation': 'horizontal'
590
+ }
591
+
592
+ # Vertical: y^2/a - x^2/b = 1
593
+ match = re.search(expr_prefix + r'y\^2/(\d+)\s*-\s*x\^2/(\d+)\s*=\s*1\)', fact_expr)
594
+ if match:
595
+ a_sq = float(match.group(1))
596
+ b_sq = float(match.group(2))
597
+ return {
598
+ 'type': 'hyperbola',
599
+ 'a': np.sqrt(a_sq),
600
+ 'b': np.sqrt(b_sq),
601
+ 'a_squared': a_sq,
602
+ 'b_squared': b_sq,
603
+ 'orientation': 'vertical'
604
+ }
605
+
606
+ # Horizontal: x^2/a - y^2 = 1 (b=1)
607
+ match = re.search(expr_prefix + r'x\^2/(\d+)\s*-\s*y\^2\s*=\s*1\)', fact_expr)
608
+ if match:
609
+ a_sq = float(match.group(1))
610
+ return {
611
+ 'type': 'hyperbola',
612
+ 'a': np.sqrt(a_sq),
613
+ 'b': 1.0,
614
+ 'a_squared': a_sq,
615
+ 'b_squared': 1.0,
616
+ 'orientation': 'horizontal'
617
+ }
618
+
619
+ # x^2 - y^2 = 1
620
+ if re.search(expr_prefix + r'x\^2\s*-\s*y\^2\s*=\s*1\)', fact_expr):
621
+ return {
622
+ 'type': 'hyperbola',
623
+ 'a': 1.0,
624
+ 'b': 1.0,
625
+ 'a_squared': 1.0,
626
+ 'b_squared': 1.0,
627
+ 'orientation': 'horizontal'
628
+ }
629
+
630
+ # Horizontal: x^2 - y^2/b = 1 (a=1, b^2 = b_val)
631
+ match = re.search(expr_prefix + r'x\^2\s*-\s*y\^2/(\d+)\s*=\s*1\)', fact_expr)
632
+ if match:
633
+ b_sq = float(match.group(1))
634
+ return {
635
+ 'type': 'hyperbola',
636
+ 'a': 1.0,
637
+ 'b': np.sqrt(b_sq),
638
+ 'a_squared': 1.0,
639
+ 'b_squared': b_sq,
640
+ 'orientation': 'horizontal'
641
+ }
642
+
643
+ # x^2 - y^2 = N (divide by N to normalize: x²/N - y²/N = 1)
644
+ match = re.search(expr_prefix + r'x\^2\s*-\s*y\^2\s*=\s*(\d+)\)', fact_expr)
645
+ if match:
646
+ n = float(match.group(1))
647
+ a = np.sqrt(n)
648
+ return {
649
+ 'type': 'hyperbola',
650
+ 'a': a,
651
+ 'b': a,
652
+ 'a_squared': n,
653
+ 'b_squared': n,
654
+ 'orientation': 'horizontal'
655
+ }
656
+
657
+ # x^2 - N*y^2 = M (x²/M - y²/(M/N) = 1)
658
+ match = re.search(expr_prefix + r'x\^2\s*-\s*(\d+)\*y\^2\s*=\s*(\d+)\)', fact_expr)
659
+ if match:
660
+ n = float(match.group(1))
661
+ m = float(match.group(2))
662
+ a_sq = m
663
+ b_sq = m / n
664
+ return {
665
+ 'type': 'hyperbola',
666
+ 'a': np.sqrt(a_sq),
667
+ 'b': np.sqrt(b_sq),
668
+ 'a_squared': a_sq,
669
+ 'b_squared': b_sq,
670
+ 'orientation': 'horizontal'
671
+ }
672
+
673
+ # N*x^2 - M*y^2 = K (x²/(K/N) - y²/(K/M) = 1)
674
+ match = re.search(expr_prefix + r'(\d+)\*x\^2\s*-\s*(\d+)\*y\^2\s*=\s*(\d+)\)', fact_expr)
675
+ if match:
676
+ n = float(match.group(1))
677
+ m = float(match.group(2))
678
+ k = float(match.group(3))
679
+ a_sq = k / n
680
+ b_sq = k / m
681
+ return {
682
+ 'type': 'hyperbola',
683
+ 'a': np.sqrt(a_sq),
684
+ 'b': np.sqrt(b_sq),
685
+ 'a_squared': a_sq,
686
+ 'b_squared': b_sq,
687
+ 'orientation': 'horizontal'
688
+ }
689
+
690
+ # x^2/a - y^2/b = -1 → y^2/b - x^2/a = 1 (vertical hyperbola)
691
+ match = re.search(expr_prefix + r'x\^2/(\d+)\s*-\s*y\^2/(\d+)\s*=\s*-1\)', fact_expr)
692
+ if match:
693
+ a_sq = float(match.group(1)) # becomes b² for vertical
694
+ b_sq = float(match.group(2)) # becomes a² for vertical
695
+ return {
696
+ 'type': 'hyperbola',
697
+ 'a': np.sqrt(b_sq),
698
+ 'b': np.sqrt(a_sq),
699
+ 'a_squared': b_sq,
700
+ 'b_squared': a_sq,
701
+ 'orientation': 'vertical'
702
+ }
703
+
704
+ # x^2-y^2/N=1 (no spaces) - horizontal
705
+ match = re.search(expr_prefix + r'x\^2-y\^2/(\d+)=1\)', fact_expr)
706
+ if match:
707
+ b_sq = float(match.group(1))
708
+ return {
709
+ 'type': 'hyperbola',
710
+ 'a': 1.0,
711
+ 'b': np.sqrt(b_sq),
712
+ 'a_squared': 1.0,
713
+ 'b_squared': b_sq,
714
+ 'orientation': 'horizontal'
715
+ }
716
+
717
+ # Vertical: y^2 - x^2/a = 1 (b=1 in standard form, here y² term positive)
718
+ match = re.search(expr_prefix + r'y\^2\s*-\s*x\^2/(\d+)\s*=\s*1\)', fact_expr)
719
+ if match:
720
+ b_sq = float(match.group(1))
721
+ return {
722
+ 'type': 'hyperbola',
723
+ 'a': 1.0, # For vertical hyperbola y²/a² - x²/b² = 1, a=1
724
+ 'b': np.sqrt(b_sq),
725
+ 'a_squared': 1.0,
726
+ 'b_squared': b_sq,
727
+ 'orientation': 'vertical'
728
+ }
729
+
730
+ # y^2 - x^2 = 1 (vertical hyperbola, a=1, b=1)
731
+ if re.search(expr_prefix + r'y\^2\s*-\s*x\^2\s*=\s*1\)', fact_expr):
732
+ return {
733
+ 'type': 'hyperbola',
734
+ 'a': 1.0,
735
+ 'b': 1.0,
736
+ 'a_squared': 1.0,
737
+ 'b_squared': 1.0,
738
+ 'orientation': 'vertical'
739
+ }
740
+
741
+ # Vertical symbolic: -x^2/b^2 + y^2/a^2 = 1
742
+ if re.search(expr_prefix + r'-x\^2/\w+\^?2?\s*\+\s*y\^2/\w+\^?2?\s*=\s*1\)', fact_expr):
743
+ return {
744
+ 'type': 'hyperbola',
745
+ 'a': 2.0, # default
746
+ 'b': 1.5, # default
747
+ 'a_squared': 4.0,
748
+ 'b_squared': 2.25,
749
+ 'symbolic': True,
750
+ 'orientation': 'vertical'
751
+ }
752
+
753
+ # Vertical symbolic: y^2/a^2 - x^2/b^2 = 1
754
+ if re.search(expr_prefix + r'y\^2/\w+\^?2?\s*-\s*x\^2/\w+\^?2?\s*=\s*1\)', fact_expr):
755
+ return {
756
+ 'type': 'hyperbola',
757
+ 'a': 2.0, # default
758
+ 'b': 1.5, # default
759
+ 'a_squared': 4.0,
760
+ 'b_squared': 2.25,
761
+ 'symbolic': True,
762
+ 'orientation': 'vertical'
763
+ }
764
+
765
+ # Horizontal symbolic: x^2/a^2 - y^2/b^2 = 1
766
+ if re.search(expr_prefix + r'x\^2/\w+\^?2?\s*-\s*y\^2/\w+\^?2?\s*=\s*1\)', fact_expr):
767
+ return {
768
+ 'type': 'hyperbola',
769
+ 'a': 2.0, # default
770
+ 'b': 1.5, # default
771
+ 'a_squared': 4.0,
772
+ 'b_squared': 2.25,
773
+ 'symbolic': True,
774
+ 'orientation': 'horizontal'
775
+ }
776
+
777
+ # Horizontal symbolic: -y^2/b^2 + x^2/a^2 = 1
778
+ if re.search(expr_prefix + r'-y\^2/\w+\^?2?\s*\+\s*x\^2/\w+\^?2?\s*=\s*1\)', fact_expr):
779
+ return {
780
+ 'type': 'hyperbola',
781
+ 'a': 2.0, # default
782
+ 'b': 1.5, # default
783
+ 'a_squared': 4.0,
784
+ 'b_squared': 2.25,
785
+ 'symbolic': True,
786
+ 'orientation': 'horizontal'
787
+ }
788
+
789
+ # Check for hyperbola type with asymptote/focus constraints (no explicit expression)
790
+ if 'Hyperbola' in fact_expr:
791
+ # Extract constraints
792
+ asymptote = self.parse_asymptote_slope(fact_expr)
793
+ coords = self.parse_coordinates(fact_expr)
794
+ focus_coords = [(n, c) for n, c in coords.items() if 'F' in n]
795
+
796
+ if asymptote or len(focus_coords) >= 2:
797
+ # Calculate a and b from constraints
798
+ if len(focus_coords) >= 2:
799
+ f1, f2 = focus_coords[0][1], focus_coords[1][1]
800
+ c = abs(f1[0] - f2[0]) / 2 if f1[1] == f2[1] == 0 else 3.0
801
+ else:
802
+ c = 3.0
803
+
804
+ if asymptote:
805
+ # b/a = asymptote, c² = a² + b²
806
+ # Let a be found from c and asymptote
807
+ # c² = a² + (a*slope)² = a²(1 + slope²)
808
+ a = c / np.sqrt(1 + asymptote**2)
809
+ b = a * asymptote
810
+ else:
811
+ a = c / np.sqrt(2)
812
+ b = a
813
+
814
+ return {
815
+ 'type': 'hyperbola',
816
+ 'a': a,
817
+ 'b': b,
818
+ 'a_squared': a**2,
819
+ 'b_squared': b**2,
820
+ 'from_constraints': True,
821
+ 'orientation': 'horizontal' # Default, focus on x-axis
822
+ }
823
+
824
+ return None
825
+
826
+ def parse_parabola(self, fact_expr: str) -> Optional[Dict]:
827
+ """Parse parabola expression."""
828
+ # y^2 = 4x, y^2 = 2*p*x, etc.
829
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*(\d+)\*x\)', fact_expr)
830
+ if match:
831
+ coef = float(match.group(1))
832
+ return {
833
+ 'type': 'parabola',
834
+ 'p': coef / 4, # 4p = coef
835
+ 'direction': 'right'
836
+ }
837
+
838
+ # x^2 = 4y, x^2 = 2*p*y
839
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*(\d+)\*y\)', fact_expr)
840
+ if match:
841
+ coef = float(match.group(1))
842
+ return {
843
+ 'type': 'parabola',
844
+ 'p': coef / 4,
845
+ 'direction': 'up'
846
+ }
847
+
848
+ # x^2 = -Ny (downward opening)
849
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*-(\d+)\*y\)', fact_expr)
850
+ if match:
851
+ coef = float(match.group(1))
852
+ return {
853
+ 'type': 'parabola',
854
+ 'p': coef / 4,
855
+ 'direction': 'down'
856
+ }
857
+
858
+ # x^2 = y/N (small opening upward)
859
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*y/(\d+)\)', fact_expr)
860
+ if match:
861
+ divisor = float(match.group(1))
862
+ return {
863
+ 'type': 'parabola',
864
+ 'p': 1 / (4 * divisor),
865
+ 'direction': 'up'
866
+ }
867
+
868
+ # y = -x^2/N (downward parabola in vertex form)
869
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(y\s*=\s*-x\^2/(\d+)\)', fact_expr)
870
+ if match:
871
+ divisor = float(match.group(1))
872
+ # y = -x²/N → x² = -Ny → 4p = N → p = N/4
873
+ return {
874
+ 'type': 'parabola',
875
+ 'p': divisor / 4,
876
+ 'direction': 'down'
877
+ }
878
+
879
+ # y = x^2/N (upward parabola in vertex form)
880
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(y\s*=\s*x\^2/(\d+)\)', fact_expr)
881
+ if match:
882
+ divisor = float(match.group(1))
883
+ # y = x²/N → x² = Ny → 4p = N → p = N/4
884
+ return {
885
+ 'type': 'parabola',
886
+ 'p': divisor / 4,
887
+ 'direction': 'up'
888
+ }
889
+
890
+ # y^2 = p*x (symbolic p, single coefficient)
891
+ if re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*\w+\*x\)', fact_expr):
892
+ return {
893
+ 'type': 'parabola',
894
+ 'p': 1.0, # Default, will be optimized
895
+ 'direction': 'right',
896
+ 'symbolic': True
897
+ }
898
+
899
+ # x^2 = p*y (symbolic p, single coefficient)
900
+ if re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*\w+\*y\)', fact_expr):
901
+ return {
902
+ 'type': 'parabola',
903
+ 'p': 1.0,
904
+ 'direction': 'up',
905
+ 'symbolic': True
906
+ }
907
+
908
+ # y^2 = 2*(p*x)
909
+ if re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*2\*\(\w+\*x\)\)', fact_expr):
910
+ return {
911
+ 'type': 'parabola',
912
+ 'p': 1.0, # Default, will be optimized
913
+ 'direction': 'right',
914
+ 'symbolic': True
915
+ }
916
+
917
+ # x^2 = 2*(p*y)
918
+ if re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*2\*\(\w+\*y\)\)', fact_expr):
919
+ return {
920
+ 'type': 'parabola',
921
+ 'p': 1.0,
922
+ 'direction': 'up',
923
+ 'symbolic': True
924
+ }
925
+
926
+ # y = 2*x^2 or y = a*x^2 (vertex form)
927
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(y\s*=\s*(\d*)\*?x\^2\)', fact_expr)
928
+ if match:
929
+ coef = match.group(1)
930
+ a = float(coef) if coef else 1.0
931
+ return {
932
+ 'type': 'parabola',
933
+ 'p': 1 / (4 * a),
934
+ 'direction': 'up'
935
+ }
936
+
937
+ # y = x^2/8 (division form)
938
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(y\s*=\s*x\^2/(\d+)\)', fact_expr)
939
+ if match:
940
+ divisor = float(match.group(1))
941
+ return {
942
+ 'type': 'parabola',
943
+ 'p': divisor / 4,
944
+ 'direction': 'up'
945
+ }
946
+
947
+ # y^2 = -8*x (left opening)
948
+ match = re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*-(\d+)\*x\)', fact_expr)
949
+ if match:
950
+ coef = float(match.group(1))
951
+ return {
952
+ 'type': 'parabola',
953
+ 'p': coef / 4,
954
+ 'direction': 'left'
955
+ }
956
+
957
+ # y^2 = 2*p*x (symbolic p) - parabola opening right
958
+ if re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*2\*p\*x\)', fact_expr):
959
+ return {
960
+ 'type': 'parabola',
961
+ 'p': 1.0, # Default, will be optimized
962
+ 'direction': 'right',
963
+ 'symbolic': True
964
+ }
965
+
966
+ # x^2 = 2*p*y (symbolic p) - parabola opening up
967
+ if re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*2\*p\*y\)', fact_expr):
968
+ return {
969
+ 'type': 'parabola',
970
+ 'p': 1.0, # Default, will be optimized
971
+ 'direction': 'up',
972
+ 'symbolic': True
973
+ }
974
+
975
+ # y^2 = x (p = 1/4, so 4p = 1) - parabola opening right
976
+ if re.search(r'Expression\(\w+\)\s*=\s*\(y\^2\s*=\s*x\)', fact_expr):
977
+ return {
978
+ 'type': 'parabola',
979
+ 'p': 0.25, # y^2 = 4px, so 4p = 1, p = 0.25
980
+ 'direction': 'right'
981
+ }
982
+
983
+ # x^2 = y (p = 1/4) - parabola opening up
984
+ if re.search(r'Expression\(\w+\)\s*=\s*\(x\^2\s*=\s*y\)', fact_expr):
985
+ return {
986
+ 'type': 'parabola',
987
+ 'p': 0.25,
988
+ 'direction': 'up'
989
+ }
990
+
991
+ # Check for Parabola type with geometric constraints
992
+ if 'Parabola' in fact_expr:
993
+ coords = self.parse_coordinates(fact_expr)
994
+
995
+ # Determine direction from constraints
996
+ direction = None
997
+ if 'PointOnCurve(Focus(' in fact_expr:
998
+ if 'xAxis' in fact_expr:
999
+ direction = 'right' # Focus on x-axis → horizontal parabola
1000
+ elif 'yAxis' in fact_expr:
1001
+ direction = 'up' # Focus on y-axis → vertical parabola
1002
+
1003
+ # Check for vertex at origin
1004
+ vertex_at_origin = 'Vertex(' in fact_expr and 'Origin' in fact_expr
1005
+
1006
+ # Try to find p from point on curve + distance to focus
1007
+ # Pattern: Distance(P, Focus(G)) = d
1008
+ dist_match = re.search(r'Distance\((\w+),\s*Focus\(\w+\)\)\s*=\s*(\d+)', fact_expr)
1009
+ if dist_match and vertex_at_origin:
1010
+ pt_name = dist_match.group(1)
1011
+ dist_val = float(dist_match.group(2))
1012
+ if pt_name in coords:
1013
+ px, py = coords[pt_name]
1014
+ # For parabola y² = 4px with vertex at origin:
1015
+ # Distance from point to focus = |x + p|
1016
+ # For right-opening: focus at (p, 0), dist = sqrt((x-p)² + y²)
1017
+ # We can solve for p
1018
+ if direction == 'right':
1019
+ # dist² = (px - p)² + py²
1020
+ # y² = 4px → py² = 4p*px
1021
+ # Substitute: dist² = (px - p)² + 4p*px
1022
+ # dist² = px² - 2*px*p + p² + 4p*px = px² + 2*px*p + p² = (px + p)²
1023
+ # So dist = |px + p|, p = dist - px (assuming px > 0)
1024
+ p = (dist_val - px) if px >= 0 else (dist_val + px)
1025
+ if p > 0:
1026
+ return {
1027
+ 'type': 'parabola',
1028
+ 'p': p,
1029
+ 'direction': 'right',
1030
+ 'from_constraints': True
1031
+ }
1032
+ elif direction == 'up':
1033
+ p = (dist_val - py) if py >= 0 else (dist_val + py)
1034
+ if p > 0:
1035
+ return {
1036
+ 'type': 'parabola',
1037
+ 'p': p,
1038
+ 'direction': 'up',
1039
+ 'from_constraints': True
1040
+ }
1041
+
1042
+ # Look for focus coordinate in coords
1043
+ for name, (px, py) in coords.items():
1044
+ # If this is a focus (F in name) or explicitly marked as focus
1045
+ if 'F' in name and (f'Focus(' in fact_expr):
1046
+ if abs(py) < 0.01: # Focus on x-axis
1047
+ return {
1048
+ 'type': 'parabola',
1049
+ 'p': abs(px), # Focus at (p, 0)
1050
+ 'direction': 'right' if px > 0 else 'left',
1051
+ 'from_constraints': True
1052
+ }
1053
+ elif abs(px) < 0.01: # Focus on y-axis
1054
+ return {
1055
+ 'type': 'parabola',
1056
+ 'p': abs(py),
1057
+ 'direction': 'up' if py > 0 else 'down',
1058
+ 'from_constraints': True
1059
+ }
1060
+
1061
+ # Default: parabola with vertex at origin, direction from constraints
1062
+ if vertex_at_origin and direction:
1063
+ return {
1064
+ 'type': 'parabola',
1065
+ 'p': 1.0, # Default, will be optimized
1066
+ 'direction': direction,
1067
+ 'symbolic': True
1068
+ }
1069
+
1070
+ return None
1071
+
1072
+ def parse_coordinates(self, fact_expr: str) -> Dict[str, Tuple[float, float]]:
1073
+ """Extract point coordinates."""
1074
+ coords = {}
1075
+ # Use a more robust pattern that handles nested parentheses
1076
+ # Match: Coordinate(Name) = (x_expr, y_expr)
1077
+ # Find all Coordinate(...) = (...) patterns
1078
+ coord_pattern = r'Coordinate\((\w+)\)\s*=\s*\(([^;]+)\)'
1079
+ for match in re.finditer(coord_pattern, fact_expr):
1080
+ name = match.group(1)
1081
+ coord_str = match.group(2)
1082
+
1083
+ # Split by comma, but handle nested parentheses
1084
+ depth = 0
1085
+ parts = []
1086
+ current = ""
1087
+ for char in coord_str:
1088
+ if char == '(':
1089
+ depth += 1
1090
+ current += char
1091
+ elif char == ')':
1092
+ depth -= 1
1093
+ current += char
1094
+ elif char == ',' and depth == 0:
1095
+ parts.append(current.strip())
1096
+ current = ""
1097
+ else:
1098
+ current += char
1099
+ parts.append(current.strip())
1100
+
1101
+ if len(parts) >= 2:
1102
+ try:
1103
+ x = parts[0].replace('sqrt', 'np.sqrt').replace('^', '**')
1104
+ y = parts[1].replace('sqrt', 'np.sqrt').replace('^', '**')
1105
+ x_val = float(eval(x, {"np": np, "__builtins__": {}}))
1106
+ y_val = float(eval(y, {"np": np, "__builtins__": {}}))
1107
+ coords[name] = (x_val, y_val)
1108
+ except:
1109
+ pass
1110
+ return coords
1111
+
1112
+ def parse_eccentricity(self, fact_expr: str) -> Optional[float]:
1113
+ """Extract eccentricity constraint."""
1114
+ # sqrt pattern
1115
+ match = re.search(r'Eccentricity\(\w+\)\s*=\s*sqrt\((\d+)\)', fact_expr)
1116
+ if match:
1117
+ return np.sqrt(float(match.group(1)))
1118
+
1119
+ # Fraction pattern (MUST be checked BEFORE decimal pattern!)
1120
+ match = re.search(r'Eccentricity\(\w+\)\s*=\s*(\d+)/(\d+)', fact_expr)
1121
+ if match:
1122
+ return float(match.group(1)) / float(match.group(2))
1123
+
1124
+ # Simple decimal pattern
1125
+ match = re.search(r'Eccentricity\(\w+\)\s*=\s*([\d.]+)', fact_expr)
1126
+ if match:
1127
+ return float(match.group(1))
1128
+
1129
+ return None
1130
+
1131
+ def parse_asymptote_slope(self, fact_expr: str) -> Optional[float]:
1132
+ """Extract asymptote slope for hyperbola.
1133
+
1134
+ Supports patterns like:
1135
+ - y = sqrt(2)*x
1136
+ - y = pm*sqrt(2)*x
1137
+ - y = pm*(sqrt(2)/2)*x or y = pm*(sqrt(2)/2)*X
1138
+ - y = 4/3*x
1139
+ - y = pm*3*x
1140
+ - y = pm*(sqrt(2)*x)
1141
+ """
1142
+ # Pattern: y = sqrt(N)*x
1143
+ match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*sqrt\((\d+)\)\*[xX]\)', fact_expr)
1144
+ if match:
1145
+ return np.sqrt(float(match.group(1)))
1146
+
1147
+ # Pattern: y = pm*sqrt(N)*x or y = pm*(sqrt(N)*x)
1148
+ match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*pm\*\(?sqrt\((\d+)\)\*?[xX]\)?', fact_expr)
1149
+ if match:
1150
+ return np.sqrt(float(match.group(1)))
1151
+
1152
+ # Pattern: y = pm*(sqrt(N)/M)*x (e.g., sqrt(2)/2)
1153
+ match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*pm\*\(sqrt\((\d+)\)/(\d+)\)\*[xX]\)', fact_expr)
1154
+ if match:
1155
+ return np.sqrt(float(match.group(1))) / float(match.group(2))
1156
+
1157
+ # Pattern: y = A/B*x (fraction slope)
1158
+ match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*(\d+)/(\d+)\*[xX]\)', fact_expr)
1159
+ if match:
1160
+ return float(match.group(1)) / float(match.group(2))
1161
+
1162
+ # Pattern: y = pm*N*x (integer slope)
1163
+ match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*pm\*(\d+)\*[xX]\)', fact_expr)
1164
+ if match:
1165
+ return float(match.group(1))
1166
+
1167
+ # Pattern: y = N*x (simple integer slope)
1168
+ match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*(\d+)\*[xX]\)', fact_expr)
1169
+ if match:
1170
+ return float(match.group(1))
1171
+
1172
+ # Pattern: pm*A*y+B*x=0 → y = ±(B/A)*x, slope = B/A
1173
+ match = re.search(r'Asymptote.*?=\s*\(pm\*(\d+)\*y\+(\d+)\*x=0\)', fact_expr)
1174
+ if match:
1175
+ a = float(match.group(1))
1176
+ b = float(match.group(2))
1177
+ return b / a
1178
+
1179
+ # Pattern: pm*(A/B)*x or y = pm*(A/B)*x
1180
+ match = re.search(r'Asymptote.*?=\s*\(y\s*=\s*pm\*\((\d+)/(\d+)\)\*[xX]\)', fact_expr)
1181
+ if match:
1182
+ return float(match.group(1)) / float(match.group(2))
1183
+
1184
+ return None
src/sdf_geo/primitives.py ADDED
@@ -0,0 +1,354 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SDF Primitives - Core geometric shape representations as Signed Distance Fields.
3
+ Following GeoSDF paper methodology.
4
+
5
+ This module contains:
6
+ - Math utilities for quartic solving (Appendix B)
7
+ - SDF primitive classes (Circle, Ellipse, Hyperbola, Parabola, Line, etc.)
8
+ """
9
+
10
+ import torch
11
+ import torch.nn as nn
12
+ from typing import Tuple
13
+
14
+ # Device configuration
15
+ DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
16
+
17
+
18
+ # =============================================================================
19
+ # Quartic Solver Utilities (Following Paper Appendix B)
20
+ # =============================================================================
21
+
22
+ def solve_cubic_one_real_batch(a: torch.Tensor, b: torch.Tensor, c: torch.Tensor,
23
+ d: torch.Tensor) -> torch.Tensor:
24
+ """Find one real root of cubic equation using Cardano's formula."""
25
+ a_safe = a + 1e-10 * torch.sign(a + 1e-20)
26
+ p = b / a_safe
27
+ q = c / a_safe
28
+ r = d / a_safe
29
+
30
+ alpha = q - p**2 / 3
31
+ beta = 2 * p**3 / 27 - p * q / 3 + r
32
+ discriminant = (beta / 2)**2 + (alpha / 3)**3
33
+ sqrt_disc = torch.sqrt(torch.clamp(discriminant, min=0) + 1e-12)
34
+
35
+ term1 = -beta / 2 + sqrt_disc
36
+ term2 = -beta / 2 - sqrt_disc
37
+
38
+ def safe_cbrt(x):
39
+ return torch.sign(x) * torch.pow(torch.abs(x) + 1e-12, 1/3)
40
+
41
+ u = safe_cbrt(term1)
42
+ v = safe_cbrt(term2)
43
+
44
+ return u + v - p / 3
45
+
46
+
47
+ def hyperbola_distance_quartic(px: torch.Tensor, py: torch.Tensor,
48
+ a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
49
+ """Compute exact distance from point to hyperbola using Newton iteration."""
50
+ px_abs = torch.abs(px)
51
+ py_abs = torch.abs(py)
52
+
53
+ t = torch.asinh(py_abs / (b + 1e-8))
54
+ t = torch.clamp(t, 0.01, 10.0)
55
+
56
+ for _ in range(15):
57
+ cosh_t = torch.cosh(t)
58
+ sinh_t = torch.sinh(t)
59
+ hx = a * cosh_t
60
+ hy = b * sinh_t
61
+ dx = px_abs - hx
62
+ dy = py_abs - hy
63
+
64
+ grad = -2 * (dx * a * sinh_t + dy * b * cosh_t)
65
+ hess = 2 * (a**2 * sinh_t**2 + b**2 * cosh_t**2 - dx * a * cosh_t - dy * b * sinh_t) + 1e-6
66
+
67
+ step = grad / torch.abs(hess)
68
+ t = t - torch.clamp(step, -0.3, 0.3)
69
+ t = torch.clamp(t, 0.001, 20.0)
70
+
71
+ cosh_t = torch.cosh(t)
72
+ sinh_t = torch.sinh(t)
73
+ return torch.sqrt((px_abs - a * cosh_t)**2 + (py_abs - b * sinh_t)**2 + 1e-10)
74
+
75
+
76
+ def ellipse_distance_quartic(px: torch.Tensor, py: torch.Tensor,
77
+ a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
78
+ """Compute exact distance from point to ellipse using Newton iteration."""
79
+ px_abs = torch.abs(px)
80
+ py_abs = torch.abs(py)
81
+
82
+ a_use = torch.max(a, b)
83
+ b_use = torch.min(a, b)
84
+
85
+ needs_swap = a < b
86
+ if needs_swap:
87
+ px_use, py_use = py_abs, px_abs
88
+ else:
89
+ px_use, py_use = px_abs, py_abs
90
+
91
+ at_origin = (px_use < 1e-10) & (py_use < 1e-10)
92
+ on_x_axis = py_use < 1e-10
93
+ on_y_axis = px_use < 1e-10
94
+
95
+ theta = torch.atan2(a_use * py_use, b_use * px_use)
96
+
97
+ for _ in range(12):
98
+ cos_t = torch.cos(theta)
99
+ sin_t = torch.sin(theta)
100
+ ex = a_use * cos_t
101
+ ey = b_use * sin_t
102
+ dx = px_use - ex
103
+ dy = py_use - ey
104
+
105
+ grad = 2 * (dx * a_use * sin_t - dy * b_use * cos_t)
106
+ hess = 2 * (a_use**2 * sin_t**2 + b_use**2 * cos_t**2 + dx * a_use * cos_t + dy * b_use * sin_t) + 1e-6
107
+
108
+ theta = theta - torch.clamp(grad / torch.abs(hess), -0.3, 0.3)
109
+
110
+ cos_t = torch.cos(theta)
111
+ sin_t = torch.sin(theta)
112
+ dist = torch.sqrt((px_use - a_use * cos_t)**2 + (py_use - b_use * sin_t)**2 + 1e-10)
113
+
114
+ dist = torch.where(at_origin, b_use, dist)
115
+ dist = torch.where(on_x_axis & ~at_origin, torch.where(px_use > a_use, px_use - a_use, torch.sqrt((px_use - a_use)**2 + 1e-10)), dist)
116
+ dist = torch.where(on_y_axis & ~at_origin, torch.abs(py_use - b_use), dist)
117
+
118
+ return dist
119
+
120
+
121
+ # =============================================================================
122
+ # SDF Primitives Base Class
123
+ # =============================================================================
124
+
125
+ class SDFPrimitive(nn.Module):
126
+ """Base class for SDF primitives - all shapes represented as distance functions."""
127
+
128
+ def forward(self, p: torch.Tensor) -> torch.Tensor:
129
+ """Compute signed distance from points p to the shape boundary."""
130
+ raise NotImplementedError
131
+
132
+
133
+ class PointSDF(SDFPrimitive):
134
+ """SDF for a point: f(p; c) = ||p - c||₂"""
135
+
136
+ def __init__(self, center: torch.Tensor):
137
+ super().__init__()
138
+ self.center = nn.Parameter(center.clone())
139
+
140
+ def forward(self, p: torch.Tensor) -> torch.Tensor:
141
+ return torch.norm(p - self.center, dim=-1)
142
+
143
+
144
+ class CircleSDF(SDFPrimitive):
145
+ """SDF for circle: f(p; c, r) = ||p - c||₂ - r"""
146
+
147
+ def __init__(self, center: torch.Tensor, radius: torch.Tensor):
148
+ super().__init__()
149
+ self.center = nn.Parameter(center.clone())
150
+ self.radius = nn.Parameter(radius.clone())
151
+
152
+ def forward(self, p: torch.Tensor) -> torch.Tensor:
153
+ dist_to_center = torch.norm(p - self.center, dim=-1)
154
+ return dist_to_center - self.radius
155
+
156
+
157
+ class EllipseSDF(SDFPrimitive):
158
+ """SDF for ellipse: x²/a² + y²/b² = 1"""
159
+
160
+ def __init__(self, center: torch.Tensor, a: torch.Tensor, b: torch.Tensor):
161
+ super().__init__()
162
+ self.center = nn.Parameter(center.clone())
163
+ self.a = nn.Parameter(a.clone())
164
+ self.b = nn.Parameter(b.clone())
165
+
166
+ def forward(self, p: torch.Tensor) -> torch.Tensor:
167
+ p_local = p - self.center
168
+ px = p_local[..., 0]
169
+ py = p_local[..., 1]
170
+
171
+ a = torch.abs(self.a) + 1e-8
172
+ b = torch.abs(self.b) + 1e-8
173
+
174
+ dist = ellipse_distance_quartic(px, py, a, b)
175
+ ellipse_val = px**2 / (a**2) + py**2 / (b**2)
176
+ inside = ellipse_val < 1
177
+
178
+ return torch.where(inside, -dist, dist)
179
+
180
+
181
+ class HyperbolaSDF(SDFPrimitive):
182
+ """SDF for hyperbola: x²/a² - y²/b² = 1"""
183
+
184
+ def __init__(self, center: torch.Tensor, a: torch.Tensor, b: torch.Tensor):
185
+ super().__init__()
186
+ self.center = nn.Parameter(center.clone())
187
+ self.a = nn.Parameter(a.clone())
188
+ self.b = nn.Parameter(b.clone())
189
+
190
+ def forward(self, p: torch.Tensor) -> torch.Tensor:
191
+ p_local = p - self.center
192
+ px = p_local[..., 0]
193
+ py = p_local[..., 1]
194
+
195
+ a = torch.abs(self.a) + 1e-8
196
+ b = torch.abs(self.b) + 1e-8
197
+
198
+ dist = hyperbola_distance_quartic(px, py, a, b)
199
+ hyperbola_val = px**2 / (a**2) - py**2 / (b**2)
200
+ is_between_branches = hyperbola_val < 1
201
+
202
+ return torch.where(is_between_branches, -dist, dist)
203
+
204
+
205
+ class ParabolaSDF(SDFPrimitive):
206
+ """SDF for parabola: y² = 4px (rightward) or x² = 4py (upward)"""
207
+
208
+ def __init__(self, vertex: torch.Tensor, p: torch.Tensor, direction: str = 'right'):
209
+ super().__init__()
210
+ self.vertex = nn.Parameter(vertex.clone())
211
+ self.p = nn.Parameter(p.clone())
212
+ self.direction = direction
213
+
214
+ def forward(self, pts: torch.Tensor) -> torch.Tensor:
215
+ p_local = pts - self.vertex
216
+ px = p_local[..., 0]
217
+ py = p_local[..., 1]
218
+ p_param = torch.abs(self.p) + 1e-6
219
+
220
+ if self.direction == 'right':
221
+ return self._compute_distance_right(px, py, p_param)
222
+ elif self.direction == 'left':
223
+ return self._compute_distance_right(-px, py, p_param)
224
+ elif self.direction == 'up':
225
+ return self._compute_distance_right(py, px, p_param)
226
+ elif self.direction == 'down':
227
+ return self._compute_distance_right(-py, px, p_param)
228
+ return self._compute_distance_right(px, py, p_param)
229
+
230
+ def _compute_distance_right(self, px: torch.Tensor, py: torch.Tensor, p: torch.Tensor) -> torch.Tensor:
231
+ t = py.clone()
232
+
233
+ for _ in range(12):
234
+ para_x = t**2 / (4 * p)
235
+ para_y = t
236
+ dx = px - para_x
237
+ dy = py - para_y
238
+ dpara_x = t / (2 * p)
239
+ dpara_y = torch.ones_like(t)
240
+
241
+ grad = -2 * (dx * dpara_x + dy * dpara_y)
242
+ ddpara_x = 1 / (2 * p)
243
+ hess = 2 * (dpara_x**2 + dpara_y**2 - dx * ddpara_x) + 1e-8
244
+
245
+ t = t - torch.clamp(grad / torch.abs(hess), -1.0, 1.0)
246
+
247
+ para_x = t**2 / (4 * p)
248
+ para_y = t
249
+ dist = torch.sqrt((px - para_x)**2 + (py - para_y)**2 + 1e-10)
250
+
251
+ at_vertex = (torch.abs(px) < 1e-6) & (torch.abs(py) < 1e-6)
252
+ dist = torch.where(at_vertex, torch.zeros_like(dist), dist)
253
+
254
+ on_concave_side = (px >= 0) & (py**2 < 4 * p * px)
255
+ return torch.where(on_concave_side, -dist, dist)
256
+
257
+
258
+ class LineSDF(SDFPrimitive):
259
+ """SDF for infinite line passing through point with direction."""
260
+
261
+ def __init__(self, point: torch.Tensor, direction: torch.Tensor):
262
+ super().__init__()
263
+ self.point = nn.Parameter(point.clone())
264
+ self.direction = nn.Parameter(direction / (torch.norm(direction) + 1e-8))
265
+
266
+ def forward(self, p: torch.Tensor) -> torch.Tensor:
267
+ v = p - self.point
268
+ normal = torch.tensor([-self.direction[1], self.direction[0]], device=p.device)
269
+ return (v * normal).sum(dim=-1)
270
+
271
+
272
+ class LineSegmentSDF(SDFPrimitive):
273
+ """SDF for line segment from point a to point b."""
274
+
275
+ def __init__(self, a: torch.Tensor, b: torch.Tensor):
276
+ super().__init__()
277
+ self.a = nn.Parameter(a.clone())
278
+ self.b = nn.Parameter(b.clone())
279
+
280
+ def forward(self, p: torch.Tensor) -> torch.Tensor:
281
+ v_ab = self.b - self.a
282
+ v_ap = p - self.a
283
+ h = (v_ap * v_ab).sum(dim=-1) / (torch.norm(v_ab)**2 + 1e-8)
284
+ h_clamped = torch.clamp(h, 0, 1)
285
+ closest = self.a + h_clamped.unsqueeze(-1) * v_ab
286
+ return torch.norm(p - closest, dim=-1)
287
+
288
+
289
+ class TriangleEdgesSDF(SDFPrimitive):
290
+ """SDF for triangle edges (boundary only)."""
291
+
292
+ def __init__(self, v0: torch.Tensor, v1: torch.Tensor, v2: torch.Tensor,
293
+ line_thickness: float = 0.02):
294
+ super().__init__()
295
+ self.edge0 = LineSegmentSDF(v0, v1)
296
+ self.edge1 = LineSegmentSDF(v1, v2)
297
+ self.edge2 = LineSegmentSDF(v2, v0)
298
+ self.thickness = line_thickness
299
+
300
+ def forward(self, p: torch.Tensor) -> torch.Tensor:
301
+ d0 = self.edge0(p)
302
+ d1 = self.edge1(p)
303
+ d2 = self.edge2(p)
304
+ return torch.min(torch.min(d0, d1), d2) - self.thickness
305
+
306
+
307
+ class TriangleFillSDF(SDFPrimitive):
308
+ """SDF for filled triangle region."""
309
+
310
+ def __init__(self, v0: torch.Tensor, v1: torch.Tensor, v2: torch.Tensor):
311
+ super().__init__()
312
+ self.v0 = nn.Parameter(v0.clone())
313
+ self.v1 = nn.Parameter(v1.clone())
314
+ self.v2 = nn.Parameter(v2.clone())
315
+ self.edge0 = LineSegmentSDF(v0, v1)
316
+ self.edge1 = LineSegmentSDF(v1, v2)
317
+ self.edge2 = LineSegmentSDF(v2, v0)
318
+
319
+ def _sign(self, p: torch.Tensor, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
320
+ return (p[..., 0] - a[0]) * (b[1] - a[1]) - (b[0] - a[0]) * (p[..., 1] - a[1])
321
+
322
+ def forward(self, p: torch.Tensor) -> torch.Tensor:
323
+ d0 = self.edge0(p)
324
+ d1 = self.edge1(p)
325
+ d2 = self.edge2(p)
326
+ dist = torch.min(torch.min(d0, d1), d2)
327
+
328
+ s0 = self._sign(p, self.v0, self.v1)
329
+ s1 = self._sign(p, self.v1, self.v2)
330
+ s2 = self._sign(p, self.v2, self.v0)
331
+
332
+ inside = ((s0 >= 0) & (s1 >= 0) & (s2 >= 0)) | ((s0 <= 0) & (s1 <= 0) & (s2 <= 0))
333
+ return torch.where(inside, -dist, dist)
334
+
335
+
336
+ class RightAngleSDF(SDFPrimitive):
337
+ """SDF for right angle marker."""
338
+
339
+ def __init__(self, vertex: torch.Tensor, dir1: torch.Tensor, dir2: torch.Tensor,
340
+ size: float = 0.25, thickness: float = 0.015):
341
+ super().__init__()
342
+ dir1_norm = dir1 / (torch.norm(dir1) + 1e-8)
343
+ dir2_norm = dir2 / (torch.norm(dir2) + 1e-8)
344
+
345
+ p1 = vertex + dir1_norm * size
346
+ p2 = vertex + dir2_norm * size
347
+ p3 = vertex + dir1_norm * size + dir2_norm * size
348
+
349
+ self.seg1 = LineSegmentSDF(p1, p3)
350
+ self.seg2 = LineSegmentSDF(p2, p3)
351
+ self.thickness = thickness
352
+
353
+ def forward(self, p: torch.Tensor) -> torch.Tensor:
354
+ return torch.min(self.seg1(p), self.seg2(p)) - self.thickness
src/sdf_geo/processor.py ADDED
@@ -0,0 +1,1218 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ Batch Processor Module
3
+ Processes geometry problems and generates visualizations.
4
+ """
5
+
6
+ import torch
7
+ import numpy as np
8
+ import matplotlib.pyplot as plt
9
+ from matplotlib.lines import Line2D
10
+ import json
11
+ import re
12
+ from pathlib import Path
13
+ from typing import Dict, List, Tuple, Optional
14
+ from tqdm import tqdm
15
+
16
+ from .primitives import (
17
+ CircleSDF, EllipseSDF, HyperbolaSDF, ParabolaSDF
18
+ )
19
+ from .constraints import GeometricConstraints
20
+ from .parser import ProblemParser
21
+ from .optimizer import GeometryOptimizer
22
+ from .renderer import SDFRenderer
23
+
24
+
25
+ class SDFBatchProcessor:
26
+ """
27
+ Process problems using the SDF methodology.
28
+ """
29
+
30
+ def __init__(self, output_dir: str = 'sdf_output'):
31
+ self.output_dir = Path(output_dir)
32
+ self.output_dir.mkdir(exist_ok=True, parents=True)
33
+
34
+ self.parser = ProblemParser()
35
+ self.optimizer = GeometryOptimizer()
36
+
37
+ # Create subdirectories
38
+ for subdir in ['ellipse', 'hyperbola', 'parabola', 'circle']:
39
+ (self.output_dir / subdir).mkdir(exist_ok=True)
40
+
41
+ def process_problem(self, problem: Dict, idx: int, verbose: bool = False) -> Dict:
42
+ """Process a single problem using SDF methodology."""
43
+ result = {
44
+ 'index': idx,
45
+ 'success': False,
46
+ 'error': None
47
+ }
48
+
49
+ try:
50
+ fact_expr = problem.get('fact_expressions', '')
51
+ text = problem.get('text', '')
52
+ query_expr = problem.get('query_expressions', '')
53
+
54
+ # Determine the primary shape to visualize based on query
55
+ # If query is about Expression(G), find what G is
56
+ primary_shape = None
57
+ query_match = re.search(r'Expression\((\w+)\)', query_expr)
58
+ if query_match:
59
+ shape_name = query_match.group(1)
60
+ # Find what type this shape is
61
+ type_match = re.search(rf'{shape_name}:\s*(\w+)', fact_expr)
62
+ if type_match:
63
+ primary_shape = type_match.group(1).lower()
64
+
65
+ # Detect main conic names for each type
66
+ main_hyperbola_name = self._detect_main_conic_name(fact_expr, 'hyperbola')
67
+ main_ellipse_name = self._detect_main_conic_name(fact_expr, 'ellipse')
68
+ main_parabola_name = self._detect_main_conic_name(fact_expr, 'parabola')
69
+ main_circle_name = self._detect_main_conic_name(fact_expr, 'circle')
70
+
71
+ # Try to parse as different conic types, using main conic names
72
+ ellipse_params = self.parser.parse_ellipse(fact_expr)
73
+ hyperbola_params = self.parser.parse_hyperbola(fact_expr, main_hyperbola_name)
74
+ parabola_params = self.parser.parse_parabola(fact_expr)
75
+ circle_params = self.parser.parse_circle(fact_expr)
76
+
77
+ # Additional constraints
78
+ coords = self.parser.parse_coordinates(fact_expr)
79
+ eccentricity = self.parser.parse_eccentricity(fact_expr)
80
+ asymptote = self.parser.parse_asymptote_slope(fact_expr)
81
+
82
+ # Special case: moving circle locus (externally tangent to fixed circle, passes through a fixed point)
83
+ moving_circle = self._detect_moving_circle_locus(fact_expr, coords)
84
+ if moving_circle:
85
+ params_hyp = moving_circle
86
+ return self._process_hyperbola(problem, idx, params_hyp, coords, eccentricity=None, asymptote=None, verbose=verbose)
87
+
88
+ # Process based on primary shape (if determined) or first available
89
+ if primary_shape == 'hyperbola' and hyperbola_params:
90
+ result = self._process_hyperbola(problem, idx, hyperbola_params, coords, eccentricity, asymptote, verbose)
91
+ elif primary_shape == 'ellipse' and ellipse_params:
92
+ result = self._process_ellipse(problem, idx, ellipse_params, coords, eccentricity, verbose)
93
+ elif primary_shape == 'parabola' and parabola_params:
94
+ result = self._process_parabola(problem, idx, parabola_params, coords, verbose)
95
+ elif primary_shape == 'circle' and circle_params:
96
+ result = self._process_circle(problem, idx, circle_params, coords, verbose)
97
+ # Fallback to order of detection, but prioritize hyperbola over ellipse
98
+ # (many problems have both, with hyperbola as the main subject)
99
+ elif hyperbola_params:
100
+ result = self._process_hyperbola(problem, idx, hyperbola_params, coords, eccentricity, asymptote, verbose)
101
+ elif ellipse_params:
102
+ result = self._process_ellipse(problem, idx, ellipse_params, coords, eccentricity, verbose)
103
+ elif parabola_params:
104
+ result = self._process_parabola(problem, idx, parabola_params, coords, verbose)
105
+ elif circle_params:
106
+ result = self._process_circle(problem, idx, circle_params, coords, verbose)
107
+ else:
108
+ result['error'] = 'Unsupported or unparseable expression'
109
+ return result
110
+
111
+ # Validation step
112
+ result = self._validate_result(result, problem)
113
+ return result
114
+
115
+ except Exception as e:
116
+ result['error'] = str(e)
117
+ return result
118
+
119
+ def _validate_result(self, result: Dict, problem: Dict) -> Dict:
120
+ """
121
+ Rigorous validation following paper-quality standards.
122
+ Validates all explicit geometric constraints from the problem.
123
+
124
+ Validation includes:
125
+ - Parameter positivity (a, b, p, r > 0)
126
+ - Eccentricity matching (e_calc vs e_target)
127
+ - Asymptote slope matching (b/a vs target slope)
128
+ - Focus position verification (c² = a² ± b²)
129
+ - Point-on-curve verification for constrained points
130
+ - Directrix position verification (parabola)
131
+ """
132
+ if not result.get('success'):
133
+ return result
134
+
135
+ conic_type = result.get('conic_type')
136
+ fact_expr = result.get('fact_expr', problem.get('fact_expressions', ''))
137
+ coords = result.get('coords', {})
138
+ reasons = []
139
+
140
+ # Tolerance settings (paper-quality)
141
+ tol_point = 3e-2 # Point on curve tolerance
142
+ tol_param = 0.05 # Parameter matching tolerance (e, slope)
143
+ tol_focus = 0.05 # Focus position tolerance
144
+
145
+ # Dynamically detect the main conic name from fact_expr
146
+ main_conic = self._detect_main_conic_name(fact_expr, conic_type)
147
+
148
+ # Get only points that are explicitly on the MAIN conic
149
+ points_on_main = self._points_on_main_conic(fact_expr, coords, main_conic)
150
+
151
+ # Helper: extract focus coordinates from fact_expr
152
+ def get_focus_coords() -> List[Tuple[float, float]]:
153
+ """Extract focus point coordinates."""
154
+ foci = []
155
+ for name, coord in coords.items():
156
+ # Check if this point is declared as a focus
157
+ if re.search(rf'Focus\s*\(\s*{main_conic}\s*\)\s*=\s*\{{\s*{name}', fact_expr) or \
158
+ re.search(rf'Focus\s*\(\s*{main_conic}\s*\)\s*=\s*{name}', fact_expr) or \
159
+ (name in ['F', 'F1', 'F2'] and re.search(rf'Focus\s*\(\s*{main_conic}\s*\)', fact_expr)):
160
+ foci.append(coord)
161
+ return foci
162
+
163
+ # Helper: check if point is on curve constraint
164
+ def has_point_constraint(name: str) -> bool:
165
+ return name in points_on_main
166
+
167
+ if conic_type == 'ellipse':
168
+ params = result.get('params', {})
169
+ if 'a' not in params or 'b' not in params:
170
+ return result # Skip validation if params incomplete
171
+ a = params['a']
172
+ b = params['b']
173
+
174
+ # 1. Parameter positivity
175
+ if a <= 0 or b <= 0:
176
+ reasons.append('ellipse_nonpositive_axes')
177
+
178
+ # 2. Eccentricity verification
179
+ ecc_target = self.parser.parse_eccentricity(fact_expr)
180
+ if ecc_target and 0 < ecc_target < 1:
181
+ a_major, b_minor = max(a, b), min(a, b)
182
+ ecc_calc = np.sqrt(1 - (b_minor / a_major)**2)
183
+ if abs(ecc_calc - ecc_target) > tol_param:
184
+ reasons.append('ellipse_ecc_mismatch')
185
+
186
+ # 3. Focus position verification (c² = a² - b² for ellipse)
187
+ foci = get_focus_coords()
188
+ if foci:
189
+ a_major, b_minor = max(a, b), min(a, b)
190
+ c_calc = np.sqrt(max(0, a_major**2 - b_minor**2))
191
+ for fx, fy in foci:
192
+ # Focus should be at (±c, 0) or (0, ±c) from center
193
+ c_given = np.sqrt(fx**2 + fy**2) # Assuming center at origin
194
+ if abs(c_calc - c_given) > tol_focus:
195
+ reasons.append('ellipse_focus_mismatch')
196
+ break
197
+
198
+ # 4. Point-on-curve verification
199
+ for name, (px, py) in coords.items():
200
+ if has_point_constraint(name):
201
+ major_axis = params.get('major_axis', 'x')
202
+ if major_axis == 'x':
203
+ val = (px**2) / (a**2) + (py**2) / (b**2) - 1
204
+ else:
205
+ val = (px**2) / (b**2) + (py**2) / (a**2) - 1
206
+ if abs(val) > tol_point:
207
+ reasons.append('ellipse_point_off_curve')
208
+ break
209
+
210
+ elif conic_type == 'hyperbola':
211
+ params = result.get('params', {})
212
+ if 'a' not in params or 'b' not in params:
213
+ return result # Skip validation if params incomplete
214
+ a = params['a']
215
+ b = params['b']
216
+ orientation = params.get('orientation', 'horizontal')
217
+
218
+ # 1. Parameter positivity
219
+ if a <= 0 or b <= 0:
220
+ reasons.append('hyperbola_nonpositive_axes')
221
+
222
+ # 2. Asymptote slope verification (b/a for horizontal)
223
+ asym = self.parser.parse_asymptote_slope(fact_expr)
224
+ if asym:
225
+ slope_calc = b / a if orientation == 'horizontal' else a / b
226
+ if abs(slope_calc - asym) > tol_param:
227
+ reasons.append('hyperbola_asymptote_mismatch')
228
+
229
+ # 3. Eccentricity verification (e = c/a = sqrt(1 + b²/a²))
230
+ ecc_target = self.parser.parse_eccentricity(fact_expr)
231
+ if ecc_target and ecc_target > 1:
232
+ ecc_calc = np.sqrt(1 + (b / a)**2)
233
+ if abs(ecc_calc - ecc_target) > tol_param:
234
+ reasons.append('hyperbola_ecc_mismatch')
235
+
236
+ # 4. Focus position verification (c² = a² + b² for hyperbola)
237
+ foci = get_focus_coords()
238
+ if foci:
239
+ c_calc = np.sqrt(a**2 + b**2)
240
+ for fx, fy in foci:
241
+ # Focus should be at (±c, 0) or (0, ±c) from center
242
+ c_given = np.sqrt(fx**2 + fy**2) # Assuming center at origin
243
+ if abs(c_calc - c_given) > tol_focus:
244
+ reasons.append('hyperbola_focus_mismatch')
245
+ break
246
+
247
+ # 5. Point-on-curve verification
248
+ for name, (px, py) in coords.items():
249
+ if has_point_constraint(name):
250
+ if orientation == 'vertical':
251
+ val = (py**2) / (a**2) - (px**2) / (b**2) - 1
252
+ else:
253
+ val = (px**2) / (a**2) - (py**2) / (b**2) - 1
254
+ if abs(val) > tol_point:
255
+ reasons.append('hyperbola_point_off_curve')
256
+ break
257
+
258
+ elif conic_type == 'parabola':
259
+ params = result.get('params', {})
260
+ p = params.get('p', 0)
261
+ direction = params.get('direction', 'right')
262
+
263
+ # 1. Parameter positivity
264
+ if p <= 0:
265
+ reasons.append('parabola_nonpositive_p')
266
+
267
+ # 2. Focus position verification
268
+ # Focus at (p, 0) for y² = 4px (right-opening)
269
+ foci = get_focus_coords()
270
+ if foci:
271
+ for fx, fy in foci:
272
+ if direction == 'right':
273
+ focus_expected = (p, 0)
274
+ elif direction == 'left':
275
+ focus_expected = (-p, 0)
276
+ elif direction == 'up':
277
+ focus_expected = (0, p)
278
+ else: # down
279
+ focus_expected = (0, -p)
280
+
281
+ dist = np.sqrt((fx - focus_expected[0])**2 + (fy - focus_expected[1])**2)
282
+ if dist > tol_focus:
283
+ reasons.append('parabola_focus_mismatch')
284
+ break
285
+
286
+ # 3. Directrix verification (if specified)
287
+ # Directrix at x = -p for y² = 4px
288
+ directrix_match = re.search(r'Directrix\s*\(\s*\w+\s*\)\s*=\s*\(x\s*=\s*(-?\d+\.?\d*)\)', fact_expr)
289
+ if directrix_match:
290
+ directrix_given = float(directrix_match.group(1))
291
+ if direction == 'right':
292
+ directrix_expected = -p
293
+ elif direction == 'left':
294
+ directrix_expected = p
295
+ else:
296
+ directrix_expected = None # y-directrix for up/down
297
+
298
+ if directrix_expected is not None:
299
+ if abs(directrix_given - directrix_expected) > tol_focus:
300
+ reasons.append('parabola_directrix_mismatch')
301
+
302
+ # 4. Point-on-curve verification
303
+ for name, (px, py) in coords.items():
304
+ if has_point_constraint(name):
305
+ if direction == 'right':
306
+ val = py**2 - 4 * p * px
307
+ elif direction == 'left':
308
+ val = py**2 + 4 * p * px
309
+ elif direction == 'up':
310
+ val = px**2 - 4 * p * py
311
+ else:
312
+ val = px**2 + 4 * p * py
313
+ if abs(val) > tol_point:
314
+ reasons.append('parabola_point_off_curve')
315
+ break
316
+
317
+ elif conic_type == 'circle':
318
+ params = result.get('params', {})
319
+ r = params.get('radius', 0)
320
+ cx, cy = params.get('center', (0, 0))
321
+
322
+ # 1. Parameter positivity
323
+ if r <= 0:
324
+ reasons.append('circle_nonpositive_radius')
325
+
326
+ # 2. Center verification (if specified)
327
+ center_match = re.search(r'Center\s*\(\s*\w+\s*\)\s*=\s*\(([^,]+),\s*([^)]+)\)', fact_expr)
328
+ if center_match:
329
+ try:
330
+ cx_given = float(center_match.group(1))
331
+ cy_given = float(center_match.group(2))
332
+ if abs(cx - cx_given) > tol_focus or abs(cy - cy_given) > tol_focus:
333
+ reasons.append('circle_center_mismatch')
334
+ except:
335
+ pass
336
+
337
+ # 3. Radius verification (if specified)
338
+ radius_match = re.search(r'Radius\s*\(\s*\w+\s*\)\s*=\s*(\d+\.?\d*)', fact_expr)
339
+ if radius_match:
340
+ r_given = float(radius_match.group(1))
341
+ if abs(r - r_given) > tol_focus:
342
+ reasons.append('circle_radius_mismatch')
343
+
344
+ # 4. Point-on-curve verification
345
+ for name, (px, py) in coords.items():
346
+ if has_point_constraint(name):
347
+ val = (px - cx)**2 + (py - cy)**2 - r**2
348
+ if abs(val) > tol_point:
349
+ reasons.append('circle_point_off_curve')
350
+ break
351
+
352
+ if reasons:
353
+ result['success'] = False
354
+ result['error'] = 'validation: ' + ';'.join(reasons)
355
+ result['validation_reasons'] = reasons
356
+ return result
357
+
358
+ def _point_constraint_names(self, fact_expr: str, coords: Dict, conic_type: str = 'parabola') -> set:
359
+ """
360
+ Collect point names that are explicitly constrained on the main curve.
361
+ Uses _detect_main_conic_name to find the actual conic variable name.
362
+ """
363
+ main_conic = self._detect_main_conic_name(fact_expr, conic_type)
364
+ return self._points_on_main_conic(fact_expr, coords, main_conic)
365
+
366
+ def _detect_main_conic_name(self, fact_expr: str, conic_type: str) -> str:
367
+ """
368
+ Detect the actual name of the main conic from fact_expr.
369
+
370
+ Patterns like 'G: Ellipse', 'C: Parabola', 'C: Hyperbola', etc.
371
+ Returns the variable name (e.g., 'G' or 'C').
372
+ """
373
+ # Map conic_type to the type name in fact_expr
374
+ type_map = {
375
+ 'ellipse': 'Ellipse',
376
+ 'hyperbola': 'Hyperbola',
377
+ 'parabola': 'Parabola',
378
+ 'circle': 'Circle'
379
+ }
380
+ type_name = type_map.get(conic_type, '')
381
+
382
+ if type_name:
383
+ # Pattern: variable_name: TypeName (e.g., "G: Ellipse" or "C: Parabola")
384
+ pattern = rf'(\w+)\s*:\s*{type_name}'
385
+ match = re.search(pattern, fact_expr)
386
+ if match:
387
+ return match.group(1)
388
+
389
+ # Fallback to defaults
390
+ return 'C' if conic_type == 'circle' else 'G'
391
+
392
+ def _points_on_main_conic(self, fact_expr: str, coords: Dict, conic_name: str = 'G') -> set:
393
+ """
394
+ Collect point names that are EXPLICITLY on the MAIN conic (e.g., G or C).
395
+
396
+ Includes:
397
+ - PointOnCurve(<name>, G) where G is the main conic
398
+ - Intersection(*, G) = {A, B} where G is the main conic
399
+
400
+ Excludes:
401
+ - PointOnCurve(<name>, H) where H is a line
402
+ - PointOnCurve(<name>, Asymptote(G)) - on asymptote, not curve
403
+ - PointOnCurve(<name>, Directrix(G)) - on directrix, not curve
404
+ - PointOnCurve(<name>, G1) where G1 is a different curve
405
+ - MidPoint constraints (midpoints of chords are not on the curve)
406
+ """
407
+ names = set()
408
+
409
+ # Match PointOnCurve(name, G) exactly - second argument must be exactly the conic name
410
+ # Avoid matching things like Asymptote(G), Directrix(G), G1, etc.
411
+ for name in coords.keys():
412
+ # Pattern: PointOnCurve(name, G) - spaces allowed, second arg must be exactly conic_name
413
+ # Use word boundary to avoid matching G1 when looking for G
414
+ pattern = rf'PointOnCurve\(\s*{re.escape(name)}\s*,\s*{re.escape(conic_name)}\s*\)'
415
+ if re.search(pattern, fact_expr):
416
+ names.add(name)
417
+
418
+ # Match Intersection(*, G) = {A, B} or Intersection(G, *) = {A, B}
419
+ # Only if one of the arguments is exactly the main conic
420
+ inter_pattern = r'Intersection\(\s*([^,)]+)\s*,\s*([^)]+)\s*\)\s*=\s*\{([^}]+)\}'
421
+ for m in re.finditer(inter_pattern, fact_expr):
422
+ arg1 = m.group(1).strip()
423
+ arg2 = m.group(2).strip()
424
+ points_str = m.group(3)
425
+
426
+ # Check if either argument is exactly the main conic name
427
+ if arg1 == conic_name or arg2 == conic_name:
428
+ for p in points_str.split(','):
429
+ p = p.strip()
430
+ if p in coords:
431
+ names.add(p)
432
+
433
+ return names
434
+
435
+ def _detect_moving_circle_locus(self, fact_expr: str, coords: Dict) -> Optional[Dict]:
436
+ """
437
+ Detect pattern: moving circle through fixed point A, externally tangent to fixed circle C.
438
+ If foci on x-axis, convert to hyperbola params: |PC| - |PA| = R -> 2a = R.
439
+ Returns hyperbola params dict or None.
440
+ """
441
+ if "IsOutTangent" not in fact_expr:
442
+ return None
443
+ # Parse fixed circle C explicitly from its expression (two common orderings)
444
+ patterns = [
445
+ r'Expression\(C\)\s*=\s*\(y\^2\s*\+\s*\(x\s*([+-])\s*(\d+\.?\d*)\)\^2\s*=\s*(\d+\.?\d*)\)',
446
+ r'Expression\(C\)\s*=\s*\(\(x\s*([+-])\s*(\d+\.?\d*)\)\^2\s*\+\s*y\^2\s*=\s*(\d+\.?\d*)\)'
447
+ ]
448
+ cx = cy = R = None
449
+ for pat in patterns:
450
+ m = re.search(pat, fact_expr)
451
+ if m:
452
+ sign = m.group(1)
453
+ val = float(m.group(2))
454
+ cx = -val if sign == '+' else val
455
+ cy = 0.0
456
+ R = np.sqrt(float(m.group(3)))
457
+ break
458
+ if R is None or R <= 0:
459
+ return None
460
+ # pick A if present, else first point
461
+ if 'A' in coords:
462
+ ax, ay = coords['A']
463
+ elif coords:
464
+ ax, ay = next(iter(coords.values()))
465
+ else:
466
+ return None
467
+ # Only handle foci on x-axis for now
468
+ if abs(ay) > 1e-6 or abs(cy) > 1e-6:
469
+ return None
470
+ c = abs(cx - ax) / 2
471
+ if c <= 0:
472
+ return None
473
+ a = R / 2
474
+ if a <= 0 or c <= a:
475
+ return None
476
+ b_sq = c * c - a * a
477
+ b = np.sqrt(b_sq)
478
+ return {'a': a, 'b': b}
479
+
480
+ def _process_ellipse(self, problem: Dict, idx: int, params: Dict,
481
+ coords: Dict, eccentricity: Optional[float], verbose: bool) -> Dict:
482
+ """Process ellipse problem with SDF optimization."""
483
+
484
+ fact_expr = problem.get('fact_expressions', '')
485
+ point_names = self._point_constraint_names(fact_expr, coords, 'ellipse')
486
+ # Create SDF with initial parameters
487
+ center = torch.tensor([0.0, 0.0])
488
+ # Ensure params has 'a' and 'b' keys
489
+ if 'a' not in params or 'b' not in params:
490
+ return {
491
+ 'index': idx,
492
+ 'success': False,
493
+ 'error': f"Ellipse params missing 'a' or 'b': {list(params.keys())}"
494
+ }
495
+ a = torch.tensor([params['a']])
496
+ b = torch.tensor([params['b']])
497
+
498
+ sdf = EllipseSDF(center, a, b)
499
+
500
+ # Check if we have explicit numeric coefficients (not symbolic)
501
+ has_explicit_coeffs = not params.get('symbolic', False) and not params.get('from_constraints', False)
502
+
503
+ # Only apply optimization if we don't have explicit coefficients
504
+ # or if constraints are compatible
505
+ should_optimize = False
506
+ constraints = []
507
+ weights = []
508
+
509
+ if not has_explicit_coeffs:
510
+ # If we have eccentricity constraint for ellipse (must be < 1)
511
+ if eccentricity and eccentricity < 1:
512
+ constraints.append(lambda: GeometricConstraints.eccentricity_ellipse(
513
+ sdf.a, sdf.b, eccentricity
514
+ ))
515
+ weights.append(10.0)
516
+ should_optimize = True
517
+
518
+ # Collect positions for crowd penalty
519
+ all_positions = [sdf.center]
520
+
521
+ # Point on curve constraints
522
+ for name, (px, py) in coords.items():
523
+ if name in point_names and name not in ['F1', 'F2', 'F', 'O']:
524
+ point = torch.tensor([px, py])
525
+ constraints.append(lambda p=point: GeometricConstraints.point_on_curve(sdf, p))
526
+ weights.append(5.0)
527
+ should_optimize = True
528
+ all_positions.append(point)
529
+
530
+ # Crowd regularization (Paper Section 3.3, Equation 2)
531
+ # Prevents geometric elements from collapsing
532
+ if len(all_positions) > 1:
533
+ constraints.append(lambda pos=all_positions: GeometricConstraints.crowd_penalty(pos, min_dist=0.5))
534
+ weights.append(3.0) # λ_crowd = 3.0 (paper default)
535
+
536
+ # Positive constraints
537
+ constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.a))
538
+ constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.b))
539
+ weights.extend([1.0, 1.0])
540
+
541
+ # Optimize only if needed and constraints are valid
542
+ if should_optimize and len(constraints) > 2:
543
+ opt_result = self.optimizer.optimize(sdf, constraints, weights, verbose)
544
+
545
+ # Check if optimization produced valid result
546
+ with torch.no_grad():
547
+ a_opt = abs(sdf.a.item())
548
+ b_opt = abs(sdf.b.item())
549
+
550
+ # If optimization produced degenerate result, revert to original params
551
+ if b_opt < 0.1 or a_opt < 0.1:
552
+ sdf.a.data = torch.tensor([params['a']])
553
+ sdf.b.data = torch.tensor([params['b']])
554
+ opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'reverted to explicit params'}
555
+ else:
556
+ opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'using explicit params'}
557
+
558
+ # Extract final parameters
559
+ with torch.no_grad():
560
+ a_final = abs(sdf.a.item())
561
+ b_final = abs(sdf.b.item())
562
+
563
+ # Determine major axis based on original coefficients
564
+ major_axis = params.get('major_axis', 'x')
565
+
566
+ # Visualize
567
+ output_path = self.output_dir / 'ellipse' / f'problem_{idx:04d}.png'
568
+ self._visualize_ellipse(sdf, problem, params, output_path, major_axis)
569
+
570
+ return {
571
+ 'index': idx,
572
+ 'success': True,
573
+ 'conic_type': 'ellipse',
574
+ 'error': None,
575
+ 'params': {
576
+ 'a': a_final,
577
+ 'b': b_final,
578
+ 'major_axis': major_axis,
579
+ 'x_coef': params['x_coef'],
580
+ 'y_coef': params['y_coef']
581
+ },
582
+ 'optimization': opt_result,
583
+ 'output_path': str(output_path),
584
+ 'answer': problem.get('answer_expressions', ''),
585
+ 'fact_expr': fact_expr,
586
+ 'coords': coords
587
+ }
588
+
589
+ def _process_hyperbola(self, problem: Dict, idx: int, params: Dict,
590
+ coords: Dict, eccentricity: Optional[float],
591
+ asymptote: Optional[float], verbose: bool) -> Dict:
592
+ """Process hyperbola problem with SDF optimization."""
593
+
594
+ fact_expr = problem.get('fact_expressions', '')
595
+ point_names = self._point_constraint_names(fact_expr, coords, 'hyperbola')
596
+
597
+ # Check if foci come from an ellipse (Focus(G) = Focus(H) where H is Ellipse)
598
+ c_from_ellipse = None
599
+ if 'Focus(G) = Focus(H)' in fact_expr or 'Focus(H) = Focus(G)' in fact_expr:
600
+ # Find the ellipse expression
601
+ ellipse_match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2/(\d+)\s*\+\s*y\^2/(\d+)\s*=\s*1\)', fact_expr)
602
+ if ellipse_match:
603
+ x_coef = float(ellipse_match.group(1))
604
+ y_coef = float(ellipse_match.group(2))
605
+ a_ell = np.sqrt(max(x_coef, y_coef))
606
+ b_ell = np.sqrt(min(x_coef, y_coef))
607
+ c_from_ellipse = np.sqrt(a_ell**2 - b_ell**2)
608
+
609
+ # If we have eccentricity and c from ellipse, calculate a and b directly
610
+ if eccentricity and eccentricity > 1 and c_from_ellipse:
611
+ # For hyperbola: e = c/a, so a = c/e
612
+ a_val = c_from_ellipse / eccentricity
613
+ # c² = a² + b², so b² = c² - a²
614
+ b_squared = c_from_ellipse**2 - a_val**2
615
+ if b_squared > 0:
616
+ b_val = np.sqrt(b_squared)
617
+ params['a'] = a_val
618
+ params['b'] = b_val
619
+ params['a_squared'] = a_val**2
620
+ params['b_squared'] = b_squared
621
+
622
+ center = torch.tensor([0.0, 0.0])
623
+ # Ensure params has 'a' and 'b' keys
624
+ if 'a' not in params or 'b' not in params:
625
+ return {
626
+ 'index': idx,
627
+ 'success': False,
628
+ 'error': f"Hyperbola params missing 'a' or 'b': {list(params.keys())}"
629
+ }
630
+ a = torch.tensor([params['a']])
631
+ b = torch.tensor([params['b']])
632
+
633
+ sdf = HyperbolaSDF(center, a, b)
634
+
635
+ # Check if we already have explicit params from the above calculation
636
+ has_explicit_params = c_from_ellipse is not None and eccentricity and eccentricity > 1
637
+
638
+ constraints = []
639
+ weights = []
640
+
641
+ if not has_explicit_params:
642
+ # Collect positions for crowd penalty
643
+ all_positions = [sdf.center]
644
+
645
+ # Eccentricity constraint
646
+ if eccentricity and eccentricity > 1:
647
+ constraints.append(lambda: GeometricConstraints.eccentricity_hyperbola(
648
+ sdf.a, sdf.b, eccentricity
649
+ ))
650
+ weights.append(10.0)
651
+
652
+ # Asymptote slope constraint
653
+ if asymptote:
654
+ constraints.append(lambda: GeometricConstraints.asymptote_slope(
655
+ sdf.a, sdf.b, asymptote
656
+ ))
657
+ weights.append(10.0)
658
+
659
+ # Focus constraint from coordinates
660
+ focus_coords = [(n, c) for n, c in coords.items() if 'F' in n]
661
+ if len(focus_coords) >= 2:
662
+ f1 = focus_coords[0][1]
663
+ f2 = focus_coords[1][1]
664
+ c_target = abs(f1[0] - f2[0]) / 2 if f1[1] == f2[1] == 0 else None
665
+ if c_target:
666
+ constraints.append(lambda ct=c_target: GeometricConstraints.focus_constraint_hyperbola(
667
+ sdf.a, sdf.b, ct
668
+ ))
669
+ weights.append(10.0)
670
+
671
+ # Add extra points to crowd penalty
672
+ for name, (px, py) in coords.items():
673
+ if name in point_names and name not in ['F1', 'F2', 'F', 'O']:
674
+ all_positions.append(torch.tensor([px, py]))
675
+
676
+ # Crowd regularization (Paper Section 3.3, Equation 2)
677
+ if len(all_positions) > 1:
678
+ constraints.append(lambda pos=all_positions: GeometricConstraints.crowd_penalty(pos, min_dist=0.5))
679
+ weights.append(3.0) # λ_crowd = 3.0
680
+
681
+ # Positive constraints
682
+ constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.a))
683
+ constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.b))
684
+ weights.extend([1.0, 1.0])
685
+
686
+ if len(constraints) > 2:
687
+ opt_result = self.optimizer.optimize(sdf, constraints, weights, verbose)
688
+ else:
689
+ opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'using explicit params'}
690
+
691
+ with torch.no_grad():
692
+ a_final = abs(sdf.a.item())
693
+ b_final = abs(sdf.b.item())
694
+
695
+ output_path = self.output_dir / 'hyperbola' / f'problem_{idx:04d}.png'
696
+ self._visualize_hyperbola(sdf, problem, params, output_path)
697
+
698
+ return {
699
+ 'index': idx,
700
+ 'success': True,
701
+ 'conic_type': 'hyperbola',
702
+ 'error': None,
703
+ 'params': {
704
+ 'a': a_final,
705
+ 'b': b_final,
706
+ 'orientation': params.get('orientation', 'horizontal')
707
+ },
708
+ 'optimization': opt_result,
709
+ 'output_path': str(output_path),
710
+ 'answer': problem.get('answer_expressions', ''),
711
+ 'fact_expr': fact_expr,
712
+ 'coords': coords
713
+ }
714
+
715
+ def _process_parabola(self, problem: Dict, idx: int, params: Dict,
716
+ coords: Dict, verbose: bool) -> Dict:
717
+ """Process parabola problem with SDF optimization."""
718
+
719
+ fact_expr = problem.get('fact_expressions', '')
720
+ point_names = self._point_constraint_names(fact_expr, coords, 'parabola')
721
+ vertex = torch.tensor([0.0, 0.0])
722
+ p = torch.tensor([params['p']])
723
+ direction = params.get('direction', 'right')
724
+
725
+ sdf = ParabolaSDF(vertex, p, direction)
726
+ # Keep vertex fixed at origin to avoid unintended translation during optimization
727
+ sdf.vertex.requires_grad_(False)
728
+
729
+ # 如果题目给出了显式的抛物线方程(非符号/约束推导),直接使用,不做优化
730
+ has_explicit_params = not params.get('symbolic', False) and not params.get('from_constraints', False)
731
+
732
+ if has_explicit_params:
733
+ opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'using explicit params'}
734
+ else:
735
+ # Collect positions for crowd penalty
736
+ all_positions = [sdf.vertex]
737
+
738
+ constraints = [
739
+ lambda: GeometricConstraints.positive_constraint(sdf.p)
740
+ ]
741
+ weights = [1.0]
742
+
743
+ # Point on curve constraints
744
+ for name, (px, py) in coords.items():
745
+ if name in point_names and name not in ['F', 'O']:
746
+ point = torch.tensor([px, py])
747
+ constraints.append(lambda pt=point: GeometricConstraints.point_on_curve(sdf, pt))
748
+ weights.append(5.0)
749
+ all_positions.append(point)
750
+
751
+ # Crowd regularization (Paper Section 3.3, Equation 2)
752
+ if len(all_positions) > 1:
753
+ constraints.append(lambda pos=all_positions: GeometricConstraints.crowd_penalty(pos, min_dist=0.5))
754
+ weights.append(3.0) # λ_crowd = 3.0
755
+
756
+ if len(constraints) > 1:
757
+ opt_result = self.optimizer.optimize(sdf, constraints, weights, verbose)
758
+ else:
759
+ opt_result = {'final_loss': 0.0, 'converged': True}
760
+
761
+ with torch.no_grad():
762
+ p_final = abs(sdf.p.item())
763
+
764
+ output_path = self.output_dir / 'parabola' / f'problem_{idx:04d}.png'
765
+ self._visualize_parabola(sdf, problem, params, output_path)
766
+
767
+ return {
768
+ 'index': idx,
769
+ 'success': True,
770
+ 'conic_type': 'parabola',
771
+ 'error': None,
772
+ 'params': {'p': p_final, 'direction': direction},
773
+ 'optimization': opt_result,
774
+ 'output_path': str(output_path),
775
+ 'answer': problem.get('answer_expressions', ''),
776
+ 'fact_expr': fact_expr,
777
+ 'coords': coords
778
+ }
779
+
780
+ def _process_circle(self, problem: Dict, idx: int, params: Dict,
781
+ coords: Dict, verbose: bool) -> Dict:
782
+ """Process circle problem with SDF."""
783
+
784
+ fact_expr = problem.get('fact_expressions', '')
785
+ point_names = self._point_constraint_names(fact_expr, coords, 'circle')
786
+ # Get center and radius
787
+ if params.get('from_diameter'):
788
+ # Compute circle from diameter endpoints
789
+ # Pattern: IsDiameter(LineSegmentOf(A, B), C) where C is the circle
790
+ fact_expr = problem.get('fact_expressions', '')
791
+ coords = self.parser.parse_coordinates(fact_expr)
792
+
793
+ # Find the two points that form the diameter
794
+ diameter_match = re.search(r'IsDiameter\(LineSegmentOf\((\w+),\s*(\w+)\)', fact_expr)
795
+ if diameter_match:
796
+ pt1_name = diameter_match.group(1)
797
+ pt2_name = diameter_match.group(2)
798
+ if pt1_name in coords and pt2_name in coords:
799
+ x1, y1 = coords[pt1_name]
800
+ x2, y2 = coords[pt2_name]
801
+ # Center = midpoint, radius = half of distance
802
+ params['center'] = ((x1 + x2) / 2, (y1 + y2) / 2)
803
+ params['radius'] = np.sqrt((x2 - x1)**2 + (y2 - y1)**2) / 2
804
+ else:
805
+ result = {
806
+ 'index': idx,
807
+ 'success': False,
808
+ 'error': 'Circle from diameter: missing point coordinates'
809
+ }
810
+ return result
811
+ else:
812
+ result = {
813
+ 'index': idx,
814
+ 'success': False,
815
+ 'error': 'Circle from diameter: cannot parse diameter pattern'
816
+ }
817
+ return result
818
+
819
+ center = torch.tensor(list(params.get('center', (0.0, 0.0))))
820
+ radius = torch.tensor([params.get('radius', 1.0)])
821
+
822
+ sdf = CircleSDF(center, radius)
823
+
824
+ # No optimization needed for explicit circles
825
+ opt_result = {'final_loss': 0.0, 'converged': True}
826
+
827
+ with torch.no_grad():
828
+ cx = sdf.center[0].item()
829
+ cy = sdf.center[1].item()
830
+ r = abs(sdf.radius.item())
831
+
832
+ output_path = self.output_dir / 'circle' / f'problem_{idx:04d}.png'
833
+ self._visualize_circle(sdf, problem, params, output_path)
834
+
835
+ return {
836
+ 'index': idx,
837
+ 'success': True,
838
+ 'conic_type': 'circle',
839
+ 'error': None,
840
+ 'params': {'center': (cx, cy), 'radius': r},
841
+ 'optimization': opt_result,
842
+ 'output_path': str(output_path),
843
+ 'answer': problem.get('answer_expressions', ''),
844
+ 'fact_expr': fact_expr,
845
+ 'coords': {k:v for k,v in coords.items() if k in point_names}
846
+ }
847
+
848
+ def _setup_gaokao_axes(self, ax, xlim, ylim):
849
+ """Setup coordinate axes in Chinese Gaokao analytic geometry style."""
850
+ ax.set_facecolor('white')
851
+ for spine in ax.spines.values():
852
+ spine.set_visible(False)
853
+ ax.set_xticks([])
854
+ ax.set_yticks([])
855
+
856
+ # Draw arrow axes through origin
857
+ arrow_kw = dict(arrowstyle='->', color='black', lw=1.0)
858
+ ax.annotate('', xy=(xlim[1], 0), xytext=(xlim[0], 0), arrowprops=arrow_kw)
859
+ ax.annotate('', xy=(0, ylim[1]), xytext=(0, ylim[0]), arrowprops=arrow_kw)
860
+
861
+ # Label offset proportional to plot range
862
+ r = max(xlim[1] - xlim[0], ylim[1] - ylim[0])
863
+ d = r * 0.025
864
+
865
+ ax.text(xlim[1] - d, -d * 2, '$x$', fontsize=14, ha='right', va='top')
866
+ ax.text(d * 0.5, ylim[1] - d * 0.5, '$y$', fontsize=14, ha='left', va='top')
867
+ ax.text(-d * 1.5, -d * 2, '$O$', fontsize=14, ha='right', va='top')
868
+
869
+ ax.set_xlim(xlim)
870
+ ax.set_ylim(ylim)
871
+ ax.set_aspect('equal')
872
+
873
+ def _visualize_circle(self, sdf: CircleSDF, problem: Dict, params: Dict,
874
+ output_path: Path):
875
+ """Visualize circle in Gaokao style."""
876
+
877
+ with torch.no_grad():
878
+ cx = sdf.center[0].item()
879
+ cy = sdf.center[1].item()
880
+ r = abs(sdf.radius.item())
881
+
882
+ margin = r + 1.5
883
+ xlim = (min(cx - margin, -0.5), max(cx + margin, 0.5))
884
+ ylim = (min(cy - margin, -0.5), max(cy + margin, 0.5))
885
+
886
+ fig, ax = plt.subplots(figsize=(8, 8))
887
+ fig.patch.set_facecolor('white')
888
+
889
+ renderer = SDFRenderer(resolution=400, xlim=xlim, ylim=ylim)
890
+ renderer.render_curve_only(sdf, ax, color='black', linewidth=1.5)
891
+
892
+ # Mark center
893
+ d = max(xlim[1] - xlim[0], ylim[1] - ylim[0]) * 0.02
894
+ ax.plot(cx, cy, 'k.', markersize=4)
895
+ ax.text(cx + d, cy + d * 2, '$C$', fontsize=13, ha='left', va='bottom')
896
+
897
+ # Additional points
898
+ for name, (px, py) in params.get('coords', {}).items():
899
+ ax.plot(px, py, 'k.', markersize=4)
900
+ ax.text(px + d, py + d * 2, f'${name}$', fontsize=13, ha='left', va='bottom')
901
+
902
+ self._setup_gaokao_axes(ax, xlim, ylim)
903
+
904
+ output_path.parent.mkdir(parents=True, exist_ok=True)
905
+ plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white')
906
+ plt.close(fig)
907
+
908
+ def _wrap_text(self, text: str, width: int = 50) -> str:
909
+ """Wrap text to specified width."""
910
+ words = text.split()
911
+ lines = []
912
+ current_line = []
913
+ current_len = 0
914
+
915
+ for word in words:
916
+ if current_len + len(word) + 1 <= width:
917
+ current_line.append(word)
918
+ current_len += len(word) + 1
919
+ else:
920
+ if current_line:
921
+ lines.append(' '.join(current_line))
922
+ current_line = [word]
923
+ current_len = len(word)
924
+
925
+ if current_line:
926
+ lines.append(' '.join(current_line))
927
+
928
+ return '\n'.join(lines)
929
+
930
+ def _visualize_ellipse(self, sdf: EllipseSDF, problem: Dict, params: Dict,
931
+ output_path: Path, major_axis: str):
932
+ """Visualize ellipse in Gaokao style."""
933
+
934
+ with torch.no_grad():
935
+ a = abs(sdf.a.item())
936
+ b = abs(sdf.b.item())
937
+
938
+ b_viz = max(b, 0.1)
939
+ fact_expr = problem.get('fact_expressions', '')
940
+
941
+ # Check if there's also a hyperbola in the problem
942
+ hyperbola_params = self.parser.parse_hyperbola(fact_expr)
943
+ has_hyperbola = hyperbola_params is not None and 'a' in hyperbola_params and 'b' in hyperbola_params
944
+
945
+ if has_hyperbola:
946
+ a_hyp = hyperbola_params['a']
947
+ b_hyp = hyperbola_params['b']
948
+ max_dim = max(a, b_viz, a_hyp, b_hyp) * 1.8 + 1
949
+ else:
950
+ max_dim = max(a, b_viz) * 1.5 + 0.5
951
+
952
+ xlim = (-max_dim, max_dim)
953
+ ylim = (-max_dim, max_dim)
954
+
955
+ fig, ax = plt.subplots(figsize=(8, 8))
956
+ fig.patch.set_facecolor('white')
957
+
958
+ renderer = SDFRenderer(resolution=500, xlim=xlim, ylim=ylim)
959
+ renderer.render_curve_only(sdf, ax, color='black', linewidth=1.5)
960
+
961
+ # Draw secondary hyperbola if present
962
+ if has_hyperbola:
963
+ center = torch.tensor([0.0, 0.0])
964
+ a_hyp_t = torch.tensor([hyperbola_params['a']])
965
+ b_hyp_t = torch.tensor([hyperbola_params['b']])
966
+ hyp_sdf = HyperbolaSDF(center, a_hyp_t, b_hyp_t)
967
+ renderer.render_curve_only(hyp_sdf, ax, color='black', linewidth=1.5)
968
+
969
+ # Asymptotes
970
+ slope_hyp = hyperbola_params['b'] / hyperbola_params['a']
971
+ x_asym = np.linspace(-max_dim, max_dim, 100)
972
+ ax.plot(x_asym, slope_hyp * x_asym, 'k--', linewidth=0.8, alpha=0.5)
973
+ ax.plot(x_asym, -slope_hyp * x_asym, 'k--', linewidth=0.8, alpha=0.5)
974
+
975
+ # Foci
976
+ c = np.sqrt(abs(a**2 - b**2)) if a > b else np.sqrt(abs(b**2 - a**2))
977
+ d = max_dim * 0.025
978
+ if major_axis == 'x':
979
+ ax.plot(c, 0, 'k.', markersize=5)
980
+ ax.plot(-c, 0, 'k.', markersize=5)
981
+ ax.text(-c, d * 2, '$F_1$', fontsize=13, ha='center', va='bottom')
982
+ ax.text(c, d * 2, '$F_2$', fontsize=13, ha='center', va='bottom')
983
+ else:
984
+ ax.plot(0, c, 'k.', markersize=5)
985
+ ax.plot(0, -c, 'k.', markersize=5)
986
+ ax.text(d * 2, -c, '$F_1$', fontsize=13, ha='left', va='center')
987
+ ax.text(d * 2, c, '$F_2$', fontsize=13, ha='left', va='center')
988
+
989
+ # Additional points
990
+ coords = self.parser.parse_coordinates(problem.get('fact_expressions', ''))
991
+ for name, (px, py) in coords.items():
992
+ if name not in ['F1', 'F2', 'F', 'O']:
993
+ ax.plot(px, py, 'k.', markersize=5)
994
+ ax.text(px + d, py + d * 2, f'${name}$', fontsize=13)
995
+
996
+ self._setup_gaokao_axes(ax, xlim, ylim)
997
+
998
+ plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white')
999
+ plt.close(fig)
1000
+
1001
+ def _visualize_hyperbola(self, sdf: HyperbolaSDF, problem: Dict, params: Dict,
1002
+ output_path: Path):
1003
+ """Visualize hyperbola in Gaokao style."""
1004
+
1005
+ with torch.no_grad():
1006
+ a = abs(sdf.a.item())
1007
+ b = abs(sdf.b.item())
1008
+
1009
+ fact_expr = problem.get('fact_expressions', '')
1010
+
1011
+ # Check if there are other shapes in the problem
1012
+ ellipse_params = self.parser.parse_ellipse(fact_expr)
1013
+ line_params = self.parser.parse_line(fact_expr)
1014
+ has_ellipse = ellipse_params is not None and 'a' in ellipse_params and 'b' in ellipse_params
1015
+ has_line = line_params is not None and (line_params.get('a') is not None or line_params.get('slope') is not None)
1016
+
1017
+ # If line has slope but no explicit equation, try to construct it
1018
+ if has_line and line_params.get('slope') is not None and line_params.get('a') is None:
1019
+ slope = line_params['slope']
1020
+ if 'LeftFocus' in fact_expr or 'RightFocus' in fact_expr:
1021
+ c_hyp = np.sqrt(a**2 + b**2)
1022
+ focus_x = -c_hyp if 'LeftFocus' in fact_expr else c_hyp
1023
+ line_params['a'] = slope
1024
+ line_params['b'] = -1.0
1025
+ line_params['c'] = -slope * focus_x
1026
+
1027
+ # Determine plot limits
1028
+ if has_ellipse:
1029
+ a_ell = ellipse_params['a']
1030
+ b_ell = ellipse_params['b']
1031
+ max_dim = max(a, b, a_ell, b_ell) * 1.5 + 1
1032
+ else:
1033
+ max_dim = max(a, b) * 2.5 + 2
1034
+
1035
+ xlim = (-max_dim, max_dim)
1036
+ ylim = (-max_dim, max_dim)
1037
+
1038
+ fig, ax = plt.subplots(figsize=(8, 8))
1039
+ fig.patch.set_facecolor('white')
1040
+
1041
+ renderer = SDFRenderer(resolution=500, xlim=xlim, ylim=ylim)
1042
+ renderer.render_curve_only(sdf, ax, color='black', linewidth=1.5)
1043
+
1044
+ # Draw secondary ellipse if present
1045
+ if has_ellipse:
1046
+ center = torch.tensor([0.0, 0.0])
1047
+ a_ell_t = torch.tensor([ellipse_params['a']])
1048
+ b_ell_t = torch.tensor([ellipse_params['b']])
1049
+ ellipse_sdf = EllipseSDF(center, a_ell_t, b_ell_t)
1050
+ renderer.render_curve_only(ellipse_sdf, ax, color='black', linewidth=1.5)
1051
+
1052
+ # Draw line if present
1053
+ if has_line and line_params.get('a') is not None and line_params.get('b') is not None:
1054
+ line_a = line_params['a']
1055
+ line_b = line_params['b']
1056
+ line_c = line_params.get('c', 0)
1057
+ x_line = np.linspace(-max_dim, max_dim, 100)
1058
+ if abs(line_b) > 1e-6:
1059
+ y_line = (-line_a * x_line - line_c) / line_b
1060
+ mask = (y_line >= ylim[0]) & (y_line <= ylim[1])
1061
+ ax.plot(x_line[mask], y_line[mask], 'k-', linewidth=1.0)
1062
+ else:
1063
+ x_val = -line_c / line_a if abs(line_a) > 1e-6 else 0
1064
+ ax.axvline(x=x_val, color='black', linewidth=1.0)
1065
+
1066
+ # Asymptotes
1067
+ slope = b / a
1068
+ x_asym = np.linspace(-max_dim, max_dim, 100)
1069
+ ax.plot(x_asym, slope * x_asym, 'k--', linewidth=0.8, alpha=0.5)
1070
+ ax.plot(x_asym, -slope * x_asym, 'k--', linewidth=0.8, alpha=0.5)
1071
+
1072
+ # Foci
1073
+ c = np.sqrt(a**2 + b**2)
1074
+ d = max_dim * 0.025
1075
+ ax.plot(c, 0, 'k.', markersize=5)
1076
+ ax.plot(-c, 0, 'k.', markersize=5)
1077
+ ax.text(-c, d * 2, '$F_1$', fontsize=13, ha='center', va='bottom')
1078
+ ax.text(c, d * 2, '$F_2$', fontsize=13, ha='center', va='bottom')
1079
+
1080
+ # Additional points
1081
+ coords = self.parser.parse_coordinates(fact_expr)
1082
+ for name, (px, py) in coords.items():
1083
+ if name not in ['F1', 'F2', 'F', 'O']:
1084
+ ax.plot(px, py, 'k.', markersize=5)
1085
+ ax.text(px + d, py + d * 2, f'${name}$', fontsize=13)
1086
+
1087
+ self._setup_gaokao_axes(ax, xlim, ylim)
1088
+
1089
+ plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white')
1090
+ plt.close(fig)
1091
+
1092
+ def _visualize_parabola(self, sdf: ParabolaSDF, problem: Dict, params: Dict,
1093
+ output_path: Path):
1094
+ """Visualize parabola in Gaokao style."""
1095
+
1096
+ with torch.no_grad():
1097
+ p = abs(sdf.p.item())
1098
+
1099
+ direction = params.get('direction', 'right')
1100
+
1101
+ # Adjust limits based on direction and p value
1102
+ extent = max(p * 8, 6)
1103
+ if direction == 'right':
1104
+ xlim = (-p * 3, extent)
1105
+ ylim = (-extent * 0.8, extent * 0.8)
1106
+ elif direction == 'left':
1107
+ xlim = (-extent, p * 3)
1108
+ ylim = (-extent * 0.8, extent * 0.8)
1109
+ elif direction == 'up':
1110
+ xlim = (-extent * 0.8, extent * 0.8)
1111
+ ylim = (-p * 3, extent)
1112
+ else: # down
1113
+ xlim = (-extent * 0.8, extent * 0.8)
1114
+ ylim = (-extent, p * 3)
1115
+
1116
+ # Ensure origin is visible
1117
+ xlim = (min(xlim[0], -0.5), max(xlim[1], 0.5))
1118
+ ylim = (min(ylim[0], -0.5), max(ylim[1], 0.5))
1119
+
1120
+ fig, ax = plt.subplots(figsize=(8, 8))
1121
+ fig.patch.set_facecolor('white')
1122
+
1123
+ renderer = SDFRenderer(resolution=600, xlim=xlim, ylim=ylim)
1124
+ renderer.render_curve_only(sdf, ax, color='black', linewidth=1.5)
1125
+
1126
+ d = max(xlim[1] - xlim[0], ylim[1] - ylim[0]) * 0.02
1127
+
1128
+ # Focus and directrix
1129
+ if direction == 'right':
1130
+ ax.plot(p, 0, 'k.', markersize=5)
1131
+ ax.text(p + d, d * 2, '$F$', fontsize=13, ha='left', va='bottom')
1132
+ ax.plot([-p, -p], [ylim[0], ylim[1]], 'k--', linewidth=0.8, alpha=0.5)
1133
+ elif direction == 'left':
1134
+ ax.plot(-p, 0, 'k.', markersize=5)
1135
+ ax.text(-p - d, d * 2, '$F$', fontsize=13, ha='right', va='bottom')
1136
+ ax.plot([p, p], [ylim[0], ylim[1]], 'k--', linewidth=0.8, alpha=0.5)
1137
+ elif direction == 'up':
1138
+ ax.plot(0, p, 'k.', markersize=5)
1139
+ ax.text(d * 2, p + d, '$F$', fontsize=13, ha='left', va='bottom')
1140
+ ax.plot([xlim[0], xlim[1]], [-p, -p], 'k--', linewidth=0.8, alpha=0.5)
1141
+ else: # down
1142
+ ax.plot(0, -p, 'k.', markersize=5)
1143
+ ax.text(d * 2, -p - d, '$F$', fontsize=13, ha='left', va='top')
1144
+ ax.plot([xlim[0], xlim[1]], [p, p], 'k--', linewidth=0.8, alpha=0.5)
1145
+
1146
+ # Additional points with staggered labels
1147
+ coords = self.parser.parse_coordinates(problem.get('fact_expressions', ''))
1148
+ for idx, (name, (px, py)) in enumerate(coords.items()):
1149
+ if name not in ['F', 'O']:
1150
+ ax.plot(px, py, 'k.', markersize=5)
1151
+ offset_y = d * 2 + d * idx
1152
+ ax.text(px + d, py + offset_y, f'${name}$', fontsize=13)
1153
+
1154
+ self._setup_gaokao_axes(ax, xlim, ylim)
1155
+
1156
+ plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white')
1157
+ plt.close(fig)
1158
+
1159
+ def process_batch(self, problems_input, max_problems: int = None,
1160
+ verbose: bool = False) -> List[Dict]:
1161
+ """Process a batch of problems.
1162
+
1163
+ Args:
1164
+ problems_input: Either a list of problem dicts or a path to JSON file
1165
+ max_problems: Maximum number of problems to process
1166
+ verbose: Whether to print verbose output
1167
+ """
1168
+ # Handle both list and file path inputs
1169
+ if isinstance(problems_input, str):
1170
+ with open(problems_input, 'r', encoding='utf-8') as f:
1171
+ problems = json.load(f)
1172
+ else:
1173
+ problems = problems_input
1174
+
1175
+ if max_problems:
1176
+ problems = problems[:max_problems]
1177
+
1178
+ results = []
1179
+ stats = {'total': len(problems), 'success': 0, 'failed': 0}
1180
+ type_stats = {'ellipse': 0, 'hyperbola': 0, 'parabola': 0, 'circle': 0}
1181
+ reason_counts: Dict[str, int] = {}
1182
+
1183
+ print(f"\n{'='*60}")
1184
+ print(f"SDF-Based Processing: {len(problems)} problems")
1185
+ print(f"{'='*60}\n")
1186
+
1187
+ for idx, problem in enumerate(tqdm(problems, desc="Processing")):
1188
+ result = self.process_problem(problem, idx, verbose)
1189
+ results.append(result)
1190
+
1191
+ if result['success']:
1192
+ stats['success'] += 1
1193
+ ctype = result.get('conic_type')
1194
+ if ctype in type_stats:
1195
+ type_stats[ctype] += 1
1196
+ else:
1197
+ stats['failed'] += 1
1198
+ for reason in result.get('validation_reasons', []):
1199
+ reason_counts[reason] = reason_counts.get(reason, 0) + 1
1200
+
1201
+ # Save summary
1202
+ summary = {
1203
+ 'stats': stats,
1204
+ 'type_stats': type_stats,
1205
+ 'reason_counts': reason_counts,
1206
+ 'results': results
1207
+ }
1208
+ with open(self.output_dir / 'summary.json', 'w') as f:
1209
+ json.dump(summary, f, indent=2, default=str)
1210
+
1211
+ print(f"\n{'='*60}")
1212
+ print("PROCESSING COMPLETE")
1213
+ print(f"{'='*60}")
1214
+ print(f"Success: {stats['success']} / {stats['total']} ({100*stats['success']/stats['total']:.1f}%)")
1215
+ print(f"By type: {type_stats}")
1216
+ print(f"Output: {self.output_dir}")
1217
+
1218
+ return results
src/sdf_geo/renderer.py ADDED
@@ -0,0 +1,98 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """
2
+ SDF Renderer Module
3
+ Visualization utilities for SDF fields and zero-level sets.
4
+ """
5
+
6
+ import torch
7
+ import numpy as np
8
+ import matplotlib.pyplot as plt
9
+ from matplotlib.colors import LinearSegmentedColormap
10
+ from typing import Tuple, Optional
11
+
12
+
13
+ class SDFRenderer:
14
+ """
15
+ Renderer for SDF fields and zero-level sets.
16
+ Creates visualization grids and renders SDF values.
17
+ """
18
+
19
+ def __init__(self, resolution: int = 512,
20
+ xlim: Tuple[float, float] = (-5, 5),
21
+ ylim: Tuple[float, float] = (-5, 5)):
22
+ self.resolution = resolution
23
+ self.xlim = xlim
24
+ self.ylim = ylim
25
+
26
+ # Create evaluation grid
27
+ x = torch.linspace(xlim[0], xlim[1], resolution)
28
+ y = torch.linspace(ylim[0], ylim[1], resolution)
29
+ self.xx, self.yy = torch.meshgrid(x, y, indexing='xy')
30
+ self.grid = torch.stack([self.xx, self.yy], dim=-1)
31
+
32
+ # Custom colormap for SDF visualization
33
+ self.sdf_cmap = LinearSegmentedColormap.from_list(
34
+ 'sdf', ['#2E86AB', '#FFFFFF', '#E74C3C'], N=256
35
+ )
36
+
37
+ def render_sdf_field(self, sdf, ax: plt.Axes,
38
+ show_field: bool = True,
39
+ field_alpha: float = 0.3) -> np.ndarray:
40
+ """
41
+ Render SDF field and zero-level set.
42
+
43
+ Args:
44
+ sdf: SDF primitive to render
45
+ ax: Matplotlib axes
46
+ show_field: Show background SDF field
47
+ field_alpha: Alpha for background field
48
+
49
+ Returns:
50
+ SDF values as numpy array
51
+ """
52
+ with torch.no_grad():
53
+ # Evaluate SDF on grid
54
+ grid_flat = self.grid.reshape(-1, 2)
55
+ distances = sdf(grid_flat).reshape(self.resolution, self.resolution)
56
+ distances_np = distances.cpu().numpy()
57
+
58
+ # Show SDF field as background
59
+ if show_field:
60
+ max_val = min(np.abs(distances_np).max(), 10)
61
+ ax.contourf(self.xx.numpy(), self.yy.numpy(), distances_np,
62
+ levels=50, cmap=self.sdf_cmap, alpha=field_alpha,
63
+ vmin=-max_val, vmax=max_val)
64
+
65
+ # Draw zero-level set (the curve)
66
+ ax.contour(self.xx.numpy(), self.yy.numpy(), distances_np,
67
+ levels=[0], colors=['#2E86AB'], linewidths=2.5)
68
+
69
+ return distances_np
70
+
71
+ def render_multiple(self, sdfs: list, ax: plt.Axes,
72
+ colors: Optional[list] = None) -> None:
73
+ """Render multiple SDFs on the same axes."""
74
+ if colors is None:
75
+ colors = ['#2E86AB', '#E74C3C', '#27AE60', '#9B59B6', '#F39C12']
76
+
77
+ with torch.no_grad():
78
+ grid_flat = self.grid.reshape(-1, 2)
79
+
80
+ for i, sdf in enumerate(sdfs):
81
+ distances = sdf(grid_flat).reshape(self.resolution, self.resolution)
82
+ distances_np = distances.cpu().numpy()
83
+
84
+ color = colors[i % len(colors)]
85
+ ax.contour(self.xx.numpy(), self.yy.numpy(), distances_np,
86
+ levels=[0], colors=[color], linewidths=2.5)
87
+
88
+ def render_curve_only(self, sdf, ax, color='black', linewidth=1.5, linestyle='-'):
89
+ """Render only the zero-level set (curve) without SDF field background."""
90
+ with torch.no_grad():
91
+ grid_flat = self.grid.reshape(-1, 2)
92
+ distances = sdf(grid_flat).reshape(self.resolution, self.resolution)
93
+ distances_np = distances.cpu().numpy()
94
+
95
+ ax.contour(self.xx.numpy(), self.yy.numpy(), distances_np,
96
+ levels=[0], colors=[color], linewidths=linewidth, linestyles=linestyle)
97
+
98
+ return distances_np