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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
"""
Batch Processor Module
Processes geometry problems and generates visualizations.
"""

import torch
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import json
import re
from pathlib import Path
from typing import Dict, List, Tuple, Optional
from tqdm import tqdm

from .primitives import (
    CircleSDF, EllipseSDF, HyperbolaSDF, ParabolaSDF
)
from .constraints import GeometricConstraints
from .parser import ProblemParser
from .optimizer import GeometryOptimizer
from .renderer import SDFRenderer


class SDFBatchProcessor:
    """
    Process problems using the SDF methodology.
    """
    
    def __init__(self, output_dir: str = 'sdf_output'):
        self.output_dir = Path(output_dir)
        self.output_dir.mkdir(exist_ok=True, parents=True)
        
        self.parser = ProblemParser()
        self.optimizer = GeometryOptimizer()
        
        # Create subdirectories
        for subdir in ['ellipse', 'hyperbola', 'parabola', 'circle']:
            (self.output_dir / subdir).mkdir(exist_ok=True)
    
    def process_problem(self, problem: Dict, idx: int, verbose: bool = False) -> Dict:
        """Process a single problem using SDF methodology."""
        result = {
            'index': idx,
            'success': False,
            'error': None
        }
        
        try:
            fact_expr = problem.get('fact_expressions', '')
            text = problem.get('text', '')
            query_expr = problem.get('query_expressions', '')
            
            # Determine the primary shape to visualize based on query
            # If query is about Expression(G), find what G is
            primary_shape = None
            query_match = re.search(r'Expression\((\w+)\)', query_expr)
            if query_match:
                shape_name = query_match.group(1)
                # Find what type this shape is
                type_match = re.search(rf'{shape_name}:\s*(\w+)', fact_expr)
                if type_match:
                    primary_shape = type_match.group(1).lower()
            
            # Detect main conic names for each type
            main_hyperbola_name = self._detect_main_conic_name(fact_expr, 'hyperbola')
            main_ellipse_name = self._detect_main_conic_name(fact_expr, 'ellipse')
            main_parabola_name = self._detect_main_conic_name(fact_expr, 'parabola')
            main_circle_name = self._detect_main_conic_name(fact_expr, 'circle')
            
            # Try to parse as different conic types, using main conic names
            ellipse_params = self.parser.parse_ellipse(fact_expr)
            hyperbola_params = self.parser.parse_hyperbola(fact_expr, main_hyperbola_name)
            parabola_params = self.parser.parse_parabola(fact_expr)
            circle_params = self.parser.parse_circle(fact_expr)
            
            # Additional constraints
            coords = self.parser.parse_coordinates(fact_expr)
            eccentricity = self.parser.parse_eccentricity(fact_expr)
            asymptote = self.parser.parse_asymptote_slope(fact_expr)
            
            # Special case: moving circle locus (externally tangent to fixed circle, passes through a fixed point)
            moving_circle = self._detect_moving_circle_locus(fact_expr, coords)
            if moving_circle:
                params_hyp = moving_circle
                return self._process_hyperbola(problem, idx, params_hyp, coords, eccentricity=None, asymptote=None, verbose=verbose)
            
            # Process based on primary shape (if determined) or first available
            if primary_shape == 'hyperbola' and hyperbola_params:
                result = self._process_hyperbola(problem, idx, hyperbola_params, coords, eccentricity, asymptote, verbose)
            elif primary_shape == 'ellipse' and ellipse_params:
                result = self._process_ellipse(problem, idx, ellipse_params, coords, eccentricity, verbose)
            elif primary_shape == 'parabola' and parabola_params:
                result = self._process_parabola(problem, idx, parabola_params, coords, verbose)
            elif primary_shape == 'circle' and circle_params:
                result = self._process_circle(problem, idx, circle_params, coords, verbose)
            # Fallback to order of detection, but prioritize hyperbola over ellipse 
            # (many problems have both, with hyperbola as the main subject)
            elif hyperbola_params:
                result = self._process_hyperbola(problem, idx, hyperbola_params, coords, eccentricity, asymptote, verbose)
            elif ellipse_params:
                result = self._process_ellipse(problem, idx, ellipse_params, coords, eccentricity, verbose)
            elif parabola_params:
                result = self._process_parabola(problem, idx, parabola_params, coords, verbose)
            elif circle_params:
                result = self._process_circle(problem, idx, circle_params, coords, verbose)
            else:
                result['error'] = 'Unsupported or unparseable expression'
                return result
            
            # Validation step
            result = self._validate_result(result, problem)
            return result
                
        except Exception as e:
            result['error'] = str(e)
            return result
    
    def _validate_result(self, result: Dict, problem: Dict) -> Dict:
        """
        Rigorous validation following paper-quality standards.
        Validates all explicit geometric constraints from the problem.
        
        Validation includes:
        - Parameter positivity (a, b, p, r > 0)
        - Eccentricity matching (e_calc vs e_target)
        - Asymptote slope matching (b/a vs target slope)
        - Focus position verification (c² = a² ± b²)
        - Point-on-curve verification for constrained points
        - Directrix position verification (parabola)
        """
        if not result.get('success'):
            return result
        
        conic_type = result.get('conic_type')
        fact_expr = result.get('fact_expr', problem.get('fact_expressions', ''))
        coords = result.get('coords', {})
        reasons = []
        
        # Tolerance settings (paper-quality)
        tol_point = 3e-2      # Point on curve tolerance
        tol_param = 0.05      # Parameter matching tolerance (e, slope)
        tol_focus = 0.05      # Focus position tolerance
        
        # Dynamically detect the main conic name from fact_expr
        main_conic = self._detect_main_conic_name(fact_expr, conic_type)
        
        # Get only points that are explicitly on the MAIN conic
        points_on_main = self._points_on_main_conic(fact_expr, coords, main_conic)
        
        # Helper: extract focus coordinates from fact_expr
        def get_focus_coords() -> List[Tuple[float, float]]:
            """Extract focus point coordinates."""
            foci = []
            for name, coord in coords.items():
                # Check if this point is declared as a focus
                if re.search(rf'Focus\s*\(\s*{main_conic}\s*\)\s*=\s*\{{\s*{name}', fact_expr) or \
                   re.search(rf'Focus\s*\(\s*{main_conic}\s*\)\s*=\s*{name}', fact_expr) or \
                   (name in ['F', 'F1', 'F2'] and re.search(rf'Focus\s*\(\s*{main_conic}\s*\)', fact_expr)):
                    foci.append(coord)
            return foci
        
        # Helper: check if point is on curve constraint
        def has_point_constraint(name: str) -> bool:
            return name in points_on_main
        
        if conic_type == 'ellipse':
            params = result.get('params', {})
            if 'a' not in params or 'b' not in params:
                return result  # Skip validation if params incomplete
            a = params['a']
            b = params['b']
            
            # 1. Parameter positivity
            if a <= 0 or b <= 0:
                reasons.append('ellipse_nonpositive_axes')
            
            # 2. Eccentricity verification
            ecc_target = self.parser.parse_eccentricity(fact_expr)
            if ecc_target and 0 < ecc_target < 1:
                a_major, b_minor = max(a, b), min(a, b)
                ecc_calc = np.sqrt(1 - (b_minor / a_major)**2)
                if abs(ecc_calc - ecc_target) > tol_param:
                    reasons.append('ellipse_ecc_mismatch')
            
            # 3. Focus position verification (c² = a² - b² for ellipse)
            foci = get_focus_coords()
            if foci:
                a_major, b_minor = max(a, b), min(a, b)
                c_calc = np.sqrt(max(0, a_major**2 - b_minor**2))
                for fx, fy in foci:
                    # Focus should be at (±c, 0) or (0, ±c) from center
                    c_given = np.sqrt(fx**2 + fy**2)  # Assuming center at origin
                    if abs(c_calc - c_given) > tol_focus:
                        reasons.append('ellipse_focus_mismatch')
                        break
            
            # 4. Point-on-curve verification
            for name, (px, py) in coords.items():
                if has_point_constraint(name):
                    major_axis = params.get('major_axis', 'x')
                    if major_axis == 'x':
                        val = (px**2) / (a**2) + (py**2) / (b**2) - 1
                    else:
                        val = (px**2) / (b**2) + (py**2) / (a**2) - 1
                    if abs(val) > tol_point:
                        reasons.append('ellipse_point_off_curve')
                        break
        
        elif conic_type == 'hyperbola':
            params = result.get('params', {})
            if 'a' not in params or 'b' not in params:
                return result  # Skip validation if params incomplete
            a = params['a']
            b = params['b']
            orientation = params.get('orientation', 'horizontal')
            
            # 1. Parameter positivity
            if a <= 0 or b <= 0:
                reasons.append('hyperbola_nonpositive_axes')
            
            # 2. Asymptote slope verification (b/a for horizontal)
            asym = self.parser.parse_asymptote_slope(fact_expr)
            if asym:
                slope_calc = b / a if orientation == 'horizontal' else a / b
                if abs(slope_calc - asym) > tol_param:
                    reasons.append('hyperbola_asymptote_mismatch')
            
            # 3. Eccentricity verification (e = c/a = sqrt(1 + b²/a²))
            ecc_target = self.parser.parse_eccentricity(fact_expr)
            if ecc_target and ecc_target > 1:
                ecc_calc = np.sqrt(1 + (b / a)**2)
                if abs(ecc_calc - ecc_target) > tol_param:
                    reasons.append('hyperbola_ecc_mismatch')
            
            # 4. Focus position verification (c² = a² + b² for hyperbola)
            foci = get_focus_coords()
            if foci:
                c_calc = np.sqrt(a**2 + b**2)
                for fx, fy in foci:
                    # Focus should be at (±c, 0) or (0, ±c) from center
                    c_given = np.sqrt(fx**2 + fy**2)  # Assuming center at origin
                    if abs(c_calc - c_given) > tol_focus:
                        reasons.append('hyperbola_focus_mismatch')
                        break
            
            # 5. Point-on-curve verification
            for name, (px, py) in coords.items():
                if has_point_constraint(name):
                    if orientation == 'vertical':
                        val = (py**2) / (a**2) - (px**2) / (b**2) - 1
                    else:
                        val = (px**2) / (a**2) - (py**2) / (b**2) - 1
                    if abs(val) > tol_point:
                        reasons.append('hyperbola_point_off_curve')
                        break
        
        elif conic_type == 'parabola':
            params = result.get('params', {})
            p = params.get('p', 0)
            direction = params.get('direction', 'right')
            
            # 1. Parameter positivity
            if p <= 0:
                reasons.append('parabola_nonpositive_p')
            
            # 2. Focus position verification
            # Focus at (p, 0) for y² = 4px (right-opening)
            foci = get_focus_coords()
            if foci:
                for fx, fy in foci:
                    if direction == 'right':
                        focus_expected = (p, 0)
                    elif direction == 'left':
                        focus_expected = (-p, 0)
                    elif direction == 'up':
                        focus_expected = (0, p)
                    else:  # down
                        focus_expected = (0, -p)
                    
                    dist = np.sqrt((fx - focus_expected[0])**2 + (fy - focus_expected[1])**2)
                    if dist > tol_focus:
                        reasons.append('parabola_focus_mismatch')
                        break
            
            # 3. Directrix verification (if specified)
            # Directrix at x = -p for y² = 4px
            directrix_match = re.search(r'Directrix\s*\(\s*\w+\s*\)\s*=\s*\(x\s*=\s*(-?\d+\.?\d*)\)', fact_expr)
            if directrix_match:
                directrix_given = float(directrix_match.group(1))
                if direction == 'right':
                    directrix_expected = -p
                elif direction == 'left':
                    directrix_expected = p
                else:
                    directrix_expected = None  # y-directrix for up/down
                
                if directrix_expected is not None:
                    if abs(directrix_given - directrix_expected) > tol_focus:
                        reasons.append('parabola_directrix_mismatch')
            
            # 4. Point-on-curve verification
            for name, (px, py) in coords.items():
                if has_point_constraint(name):
                    if direction == 'right':
                        val = py**2 - 4 * p * px
                    elif direction == 'left':
                        val = py**2 + 4 * p * px
                    elif direction == 'up':
                        val = px**2 - 4 * p * py
                    else:
                        val = px**2 + 4 * p * py
                    if abs(val) > tol_point:
                        reasons.append('parabola_point_off_curve')
                        break
        
        elif conic_type == 'circle':
            params = result.get('params', {})
            r = params.get('radius', 0)
            cx, cy = params.get('center', (0, 0))
            
            # 1. Parameter positivity
            if r <= 0:
                reasons.append('circle_nonpositive_radius')
            
            # 2. Center verification (if specified)
            center_match = re.search(r'Center\s*\(\s*\w+\s*\)\s*=\s*\(([^,]+),\s*([^)]+)\)', fact_expr)
            if center_match:
                try:
                    cx_given = float(center_match.group(1))
                    cy_given = float(center_match.group(2))
                    if abs(cx - cx_given) > tol_focus or abs(cy - cy_given) > tol_focus:
                        reasons.append('circle_center_mismatch')
                except:
                    pass
            
            # 3. Radius verification (if specified)
            radius_match = re.search(r'Radius\s*\(\s*\w+\s*\)\s*=\s*(\d+\.?\d*)', fact_expr)
            if radius_match:
                r_given = float(radius_match.group(1))
                if abs(r - r_given) > tol_focus:
                    reasons.append('circle_radius_mismatch')
            
            # 4. Point-on-curve verification
            for name, (px, py) in coords.items():
                if has_point_constraint(name):
                    val = (px - cx)**2 + (py - cy)**2 - r**2
                    if abs(val) > tol_point:
                        reasons.append('circle_point_off_curve')
                        break
        
        if reasons:
            result['success'] = False
            result['error'] = 'validation: ' + ';'.join(reasons)
            result['validation_reasons'] = reasons
        return result

    def _point_constraint_names(self, fact_expr: str, coords: Dict, conic_type: str = 'parabola') -> set:
        """
        Collect point names that are explicitly constrained on the main curve.
        Uses _detect_main_conic_name to find the actual conic variable name.
        """
        main_conic = self._detect_main_conic_name(fact_expr, conic_type)
        return self._points_on_main_conic(fact_expr, coords, main_conic)
    
    def _detect_main_conic_name(self, fact_expr: str, conic_type: str) -> str:
        """
        Detect the actual name of the main conic from fact_expr.
        
        Patterns like 'G: Ellipse', 'C: Parabola', 'C: Hyperbola', etc.
        Returns the variable name (e.g., 'G' or 'C').
        """
        # Map conic_type to the type name in fact_expr
        type_map = {
            'ellipse': 'Ellipse',
            'hyperbola': 'Hyperbola',
            'parabola': 'Parabola',
            'circle': 'Circle'
        }
        type_name = type_map.get(conic_type, '')
        
        if type_name:
            # Pattern: variable_name: TypeName (e.g., "G: Ellipse" or "C: Parabola")
            pattern = rf'(\w+)\s*:\s*{type_name}'
            match = re.search(pattern, fact_expr)
            if match:
                return match.group(1)
        
        # Fallback to defaults
        return 'C' if conic_type == 'circle' else 'G'
    
    def _points_on_main_conic(self, fact_expr: str, coords: Dict, conic_name: str = 'G') -> set:
        """
        Collect point names that are EXPLICITLY on the MAIN conic (e.g., G or C).
        
        Includes:
        - PointOnCurve(<name>, G) where G is the main conic
        - Intersection(*, G) = {A, B} where G is the main conic
        
        Excludes:
        - PointOnCurve(<name>, H) where H is a line
        - PointOnCurve(<name>, Asymptote(G)) - on asymptote, not curve
        - PointOnCurve(<name>, Directrix(G)) - on directrix, not curve
        - PointOnCurve(<name>, G1) where G1 is a different curve
        - MidPoint constraints (midpoints of chords are not on the curve)
        """
        names = set()
        
        # Match PointOnCurve(name, G) exactly - second argument must be exactly the conic name
        # Avoid matching things like Asymptote(G), Directrix(G), G1, etc.
        for name in coords.keys():
            # Pattern: PointOnCurve(name, G) - spaces allowed, second arg must be exactly conic_name
            # Use word boundary to avoid matching G1 when looking for G
            pattern = rf'PointOnCurve\(\s*{re.escape(name)}\s*,\s*{re.escape(conic_name)}\s*\)'
            if re.search(pattern, fact_expr):
                names.add(name)
        
        # Match Intersection(*, G) = {A, B} or Intersection(G, *) = {A, B}
        # Only if one of the arguments is exactly the main conic
        inter_pattern = r'Intersection\(\s*([^,)]+)\s*,\s*([^)]+)\s*\)\s*=\s*\{([^}]+)\}'
        for m in re.finditer(inter_pattern, fact_expr):
            arg1 = m.group(1).strip()
            arg2 = m.group(2).strip()
            points_str = m.group(3)
            
            # Check if either argument is exactly the main conic name
            if arg1 == conic_name or arg2 == conic_name:
                for p in points_str.split(','):
                    p = p.strip()
                    if p in coords:
                        names.add(p)
        
        return names

    def _detect_moving_circle_locus(self, fact_expr: str, coords: Dict) -> Optional[Dict]:
        """
        Detect pattern: moving circle through fixed point A, externally tangent to fixed circle C.
        If foci on x-axis, convert to hyperbola params: |PC| - |PA| = R -> 2a = R.
        Returns hyperbola params dict or None.
        """
        if "IsOutTangent" not in fact_expr:
            return None
        # Parse fixed circle C explicitly from its expression (two common orderings)
        patterns = [
            r'Expression\(C\)\s*=\s*\(y\^2\s*\+\s*\(x\s*([+-])\s*(\d+\.?\d*)\)\^2\s*=\s*(\d+\.?\d*)\)',
            r'Expression\(C\)\s*=\s*\(\(x\s*([+-])\s*(\d+\.?\d*)\)\^2\s*\+\s*y\^2\s*=\s*(\d+\.?\d*)\)'
        ]
        cx = cy = R = None
        for pat in patterns:
            m = re.search(pat, fact_expr)
            if m:
                sign = m.group(1)
                val = float(m.group(2))
                cx = -val if sign == '+' else val
                cy = 0.0
                R = np.sqrt(float(m.group(3)))
                break
        if R is None or R <= 0:
            return None
        # pick A if present, else first point
        if 'A' in coords:
            ax, ay = coords['A']
        elif coords:
            ax, ay = next(iter(coords.values()))
        else:
            return None
        # Only handle foci on x-axis for now
        if abs(ay) > 1e-6 or abs(cy) > 1e-6:
            return None
        c = abs(cx - ax) / 2
        if c <= 0:
            return None
        a = R / 2
        if a <= 0 or c <= a:
            return None
        b_sq = c * c - a * a
        b = np.sqrt(b_sq)
        return {'a': a, 'b': b}
    
    def _process_ellipse(self, problem: Dict, idx: int, params: Dict,
                        coords: Dict, eccentricity: Optional[float], verbose: bool) -> Dict:
        """Process ellipse problem with SDF optimization."""
        
        fact_expr = problem.get('fact_expressions', '')
        point_names = self._point_constraint_names(fact_expr, coords, 'ellipse')
        # Create SDF with initial parameters
        center = torch.tensor([0.0, 0.0])
        # Ensure params has 'a' and 'b' keys
        if 'a' not in params or 'b' not in params:
            return {
                'index': idx,
                'success': False,
                'error': f"Ellipse params missing 'a' or 'b': {list(params.keys())}"
            }
        a = torch.tensor([params['a']])
        b = torch.tensor([params['b']])
        
        sdf = EllipseSDF(center, a, b)
        
        # Check if we have explicit numeric coefficients (not symbolic)
        has_explicit_coeffs = not params.get('symbolic', False) and not params.get('from_constraints', False)
        
        # Only apply optimization if we don't have explicit coefficients
        # or if constraints are compatible
        should_optimize = False
        constraints = []
        weights = []
        
        if not has_explicit_coeffs:
            # If we have eccentricity constraint for ellipse (must be < 1)
            if eccentricity and eccentricity < 1:
                constraints.append(lambda: GeometricConstraints.eccentricity_ellipse(
                    sdf.a, sdf.b, eccentricity
                ))
                weights.append(10.0)
                should_optimize = True
            
            # Collect positions for crowd penalty
            all_positions = [sdf.center]
            
            # Point on curve constraints
            for name, (px, py) in coords.items():
                if name in point_names and name not in ['F1', 'F2', 'F', 'O']:
                    point = torch.tensor([px, py])
                    constraints.append(lambda p=point: GeometricConstraints.point_on_curve(sdf, p))
                    weights.append(5.0)
                    should_optimize = True
                    all_positions.append(point)
            
            # Crowd regularization (Paper Section 3.3, Equation 2)
            # Prevents geometric elements from collapsing
            if len(all_positions) > 1:
                constraints.append(lambda pos=all_positions: GeometricConstraints.crowd_penalty(pos, min_dist=0.5))
                weights.append(3.0)  # λ_crowd = 3.0 (paper default)
            
            # Positive constraints
            constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.a))
            constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.b))
            weights.extend([1.0, 1.0])
        
        # Optimize only if needed and constraints are valid
        if should_optimize and len(constraints) > 2:
            opt_result = self.optimizer.optimize(sdf, constraints, weights, verbose)
            
            # Check if optimization produced valid result
            with torch.no_grad():
                a_opt = abs(sdf.a.item())
                b_opt = abs(sdf.b.item())
            
            # If optimization produced degenerate result, revert to original params
            if b_opt < 0.1 or a_opt < 0.1:
                sdf.a.data = torch.tensor([params['a']])
                sdf.b.data = torch.tensor([params['b']])
                opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'reverted to explicit params'}
        else:
            opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'using explicit params'}
        
        # Extract final parameters
        with torch.no_grad():
            a_final = abs(sdf.a.item())
            b_final = abs(sdf.b.item())
        
        # Determine major axis based on original coefficients
        major_axis = params.get('major_axis', 'x')
        
        # Visualize
        output_path = self.output_dir / 'ellipse' / f'problem_{idx:04d}.png'
        self._visualize_ellipse(sdf, problem, params, output_path, major_axis)
        
        return {
            'index': idx,
            'success': True,
            'conic_type': 'ellipse',
            'error': None,
            'params': {
                'a': a_final,
                'b': b_final,
                'major_axis': major_axis,
                'x_coef': params['x_coef'],
                'y_coef': params['y_coef']
            },
            'optimization': opt_result,
            'output_path': str(output_path),
            'answer': problem.get('answer_expressions', ''),
            'fact_expr': fact_expr,
            'coords': coords
        }
    
    def _process_hyperbola(self, problem: Dict, idx: int, params: Dict,
                          coords: Dict, eccentricity: Optional[float],
                          asymptote: Optional[float], verbose: bool) -> Dict:
        """Process hyperbola problem with SDF optimization."""
        
        fact_expr = problem.get('fact_expressions', '')
        point_names = self._point_constraint_names(fact_expr, coords, 'hyperbola')
        
        # Check if foci come from an ellipse (Focus(G) = Focus(H) where H is Ellipse)
        c_from_ellipse = None
        if 'Focus(G) = Focus(H)' in fact_expr or 'Focus(H) = Focus(G)' in fact_expr:
            # Find the ellipse expression
            ellipse_match = re.search(r'Expression\(\w+\)\s*=\s*\(x\^2/(\d+)\s*\+\s*y\^2/(\d+)\s*=\s*1\)', fact_expr)
            if ellipse_match:
                x_coef = float(ellipse_match.group(1))
                y_coef = float(ellipse_match.group(2))
                a_ell = np.sqrt(max(x_coef, y_coef))
                b_ell = np.sqrt(min(x_coef, y_coef))
                c_from_ellipse = np.sqrt(a_ell**2 - b_ell**2)
        
        # If we have eccentricity and c from ellipse, calculate a and b directly
        if eccentricity and eccentricity > 1 and c_from_ellipse:
            # For hyperbola: e = c/a, so a = c/e
            a_val = c_from_ellipse / eccentricity
            # c² = a² + b², so b² = c² - a²
            b_squared = c_from_ellipse**2 - a_val**2
            if b_squared > 0:
                b_val = np.sqrt(b_squared)
                params['a'] = a_val
                params['b'] = b_val
                params['a_squared'] = a_val**2
                params['b_squared'] = b_squared
        
        center = torch.tensor([0.0, 0.0])
        # Ensure params has 'a' and 'b' keys
        if 'a' not in params or 'b' not in params:
            return {
                'index': idx,
                'success': False,
                'error': f"Hyperbola params missing 'a' or 'b': {list(params.keys())}"
            }
        a = torch.tensor([params['a']])
        b = torch.tensor([params['b']])
        
        sdf = HyperbolaSDF(center, a, b)
        
        # Check if we already have explicit params from the above calculation
        has_explicit_params = c_from_ellipse is not None and eccentricity and eccentricity > 1
        
        constraints = []
        weights = []
        
        if not has_explicit_params:
            # Collect positions for crowd penalty
            all_positions = [sdf.center]
            
            # Eccentricity constraint
            if eccentricity and eccentricity > 1:
                constraints.append(lambda: GeometricConstraints.eccentricity_hyperbola(
                    sdf.a, sdf.b, eccentricity
                ))
                weights.append(10.0)
            
            # Asymptote slope constraint
            if asymptote:
                constraints.append(lambda: GeometricConstraints.asymptote_slope(
                    sdf.a, sdf.b, asymptote
                ))
                weights.append(10.0)
            
            # Focus constraint from coordinates
            focus_coords = [(n, c) for n, c in coords.items() if 'F' in n]
            if len(focus_coords) >= 2:
                f1 = focus_coords[0][1]
                f2 = focus_coords[1][1]
                c_target = abs(f1[0] - f2[0]) / 2 if f1[1] == f2[1] == 0 else None
                if c_target:
                    constraints.append(lambda ct=c_target: GeometricConstraints.focus_constraint_hyperbola(
                        sdf.a, sdf.b, ct
                    ))
                    weights.append(10.0)
            
            # Add extra points to crowd penalty
            for name, (px, py) in coords.items():
                if name in point_names and name not in ['F1', 'F2', 'F', 'O']:
                    all_positions.append(torch.tensor([px, py]))
            
            # Crowd regularization (Paper Section 3.3, Equation 2)
            if len(all_positions) > 1:
                constraints.append(lambda pos=all_positions: GeometricConstraints.crowd_penalty(pos, min_dist=0.5))
                weights.append(3.0)  # λ_crowd = 3.0
            
            # Positive constraints
            constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.a))
            constraints.append(lambda: GeometricConstraints.positive_constraint(sdf.b))
            weights.extend([1.0, 1.0])
        
        if len(constraints) > 2:
            opt_result = self.optimizer.optimize(sdf, constraints, weights, verbose)
        else:
            opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'using explicit params'}
        
        with torch.no_grad():
            a_final = abs(sdf.a.item())
            b_final = abs(sdf.b.item())
        
        output_path = self.output_dir / 'hyperbola' / f'problem_{idx:04d}.png'
        self._visualize_hyperbola(sdf, problem, params, output_path)
        
        return {
            'index': idx,
            'success': True,
            'conic_type': 'hyperbola',
            'error': None,
            'params': {
                'a': a_final,
                'b': b_final,
                'orientation': params.get('orientation', 'horizontal')
            },
            'optimization': opt_result,
            'output_path': str(output_path),
            'answer': problem.get('answer_expressions', ''),
            'fact_expr': fact_expr,
            'coords': coords
        }
    
    def _process_parabola(self, problem: Dict, idx: int, params: Dict,
                         coords: Dict, verbose: bool) -> Dict:
        """Process parabola problem with SDF optimization."""
        
        fact_expr = problem.get('fact_expressions', '')
        point_names = self._point_constraint_names(fact_expr, coords, 'parabola')
        vertex = torch.tensor([0.0, 0.0])
        p = torch.tensor([params['p']])
        direction = params.get('direction', 'right')
        
        sdf = ParabolaSDF(vertex, p, direction)
        # Keep vertex fixed at origin to avoid unintended translation during optimization
        sdf.vertex.requires_grad_(False)
        
        # 如果题目给出了显式的抛物线方程(非符号/约束推导),直接使用,不做优化
        has_explicit_params = not params.get('symbolic', False) and not params.get('from_constraints', False)
        
        if has_explicit_params:
            opt_result = {'final_loss': 0.0, 'converged': True, 'note': 'using explicit params'}
        else:
            # Collect positions for crowd penalty
            all_positions = [sdf.vertex]
            
            constraints = [
                lambda: GeometricConstraints.positive_constraint(sdf.p)
            ]
            weights = [1.0]
            
            # Point on curve constraints
            for name, (px, py) in coords.items():
                if name in point_names and name not in ['F', 'O']:
                    point = torch.tensor([px, py])
                    constraints.append(lambda pt=point: GeometricConstraints.point_on_curve(sdf, pt))
                    weights.append(5.0)
                    all_positions.append(point)
            
            # Crowd regularization (Paper Section 3.3, Equation 2)
            if len(all_positions) > 1:
                constraints.append(lambda pos=all_positions: GeometricConstraints.crowd_penalty(pos, min_dist=0.5))
                weights.append(3.0)  # λ_crowd = 3.0
            
            if len(constraints) > 1:
                opt_result = self.optimizer.optimize(sdf, constraints, weights, verbose)
            else:
                opt_result = {'final_loss': 0.0, 'converged': True}
        
        with torch.no_grad():
            p_final = abs(sdf.p.item())
        
        output_path = self.output_dir / 'parabola' / f'problem_{idx:04d}.png'
        self._visualize_parabola(sdf, problem, params, output_path)
        
        return {
            'index': idx,
            'success': True,
            'conic_type': 'parabola',
            'error': None,
            'params': {'p': p_final, 'direction': direction},
            'optimization': opt_result,
            'output_path': str(output_path),
            'answer': problem.get('answer_expressions', ''),
            'fact_expr': fact_expr,
            'coords': coords
        }
    
    def _process_circle(self, problem: Dict, idx: int, params: Dict,
                        coords: Dict, verbose: bool) -> Dict:
        """Process circle problem with SDF."""
        
        fact_expr = problem.get('fact_expressions', '')
        point_names = self._point_constraint_names(fact_expr, coords, 'circle')
        # Get center and radius
        if params.get('from_diameter'):
            # Compute circle from diameter endpoints
            # Pattern: IsDiameter(LineSegmentOf(A, B), C) where C is the circle
            fact_expr = problem.get('fact_expressions', '')
            coords = self.parser.parse_coordinates(fact_expr)
            
            # Find the two points that form the diameter
            diameter_match = re.search(r'IsDiameter\(LineSegmentOf\((\w+),\s*(\w+)\)', fact_expr)
            if diameter_match:
                pt1_name = diameter_match.group(1)
                pt2_name = diameter_match.group(2)
                if pt1_name in coords and pt2_name in coords:
                    x1, y1 = coords[pt1_name]
                    x2, y2 = coords[pt2_name]
                    # Center = midpoint, radius = half of distance
                    params['center'] = ((x1 + x2) / 2, (y1 + y2) / 2)
                    params['radius'] = np.sqrt((x2 - x1)**2 + (y2 - y1)**2) / 2
                else:
                    result = {
                        'index': idx,
                        'success': False,
                        'error': 'Circle from diameter: missing point coordinates'
                    }
                    return result
            else:
                result = {
                    'index': idx,
                    'success': False,
                    'error': 'Circle from diameter: cannot parse diameter pattern'
                }
                return result
        
        center = torch.tensor(list(params.get('center', (0.0, 0.0))))
        radius = torch.tensor([params.get('radius', 1.0)])
        
        sdf = CircleSDF(center, radius)
        
        # No optimization needed for explicit circles
        opt_result = {'final_loss': 0.0, 'converged': True}
        
        with torch.no_grad():
            cx = sdf.center[0].item()
            cy = sdf.center[1].item()
            r = abs(sdf.radius.item())
        
        output_path = self.output_dir / 'circle' / f'problem_{idx:04d}.png'
        self._visualize_circle(sdf, problem, params, output_path)
        
        return {
            'index': idx,
            'success': True,
            'conic_type': 'circle',
            'error': None,
            'params': {'center': (cx, cy), 'radius': r},
            'optimization': opt_result,
            'output_path': str(output_path),
            'answer': problem.get('answer_expressions', ''),
            'fact_expr': fact_expr,
            'coords': {k:v for k,v in coords.items() if k in point_names}
        }
    
    def _visualize_circle(self, sdf: CircleSDF, problem: Dict, params: Dict,
                         output_path: Path):
        """Visualize circle using SDF zero-level set."""
        
        with torch.no_grad():
            cx = sdf.center[0].item()
            cy = sdf.center[1].item()
            r = abs(sdf.radius.item())
        
        # Set up plot range
        margin = r + 2
        xlim = (cx - margin, cx + margin)
        ylim = (cy - margin, cy + margin)
        
        # Create renderer
        renderer = SDFRenderer(resolution=400, xlim=xlim, ylim=ylim)
        
        # Create figure with info panel
        fig, (ax, ax_info) = plt.subplots(2, 1, figsize=(10, 12),
                                          gridspec_kw={'height_ratios': [0.6, 0.4]})
        
        # Render SDF field and zero-level set
        renderer.render_sdf_field(sdf, ax, show_field=True, field_alpha=0.15)
        
        # Mark center
        ax.plot(cx, cy, 'ro', markersize=10, label='Center')
        ax.annotate('C', (cx, cy), textcoords="offset points", xytext=(10, 10), fontsize=12)
        
        # Draw radius line
        ax.plot([cx, cx + r], [cy, cy], 'g--', linewidth=2, label=f'r = {r:.2f}')
        
        # Plot any additional points from constraints
        for name, (px, py) in params.get('coords', {}).items():
            ax.plot(px, py, 'go', markersize=8)
            ax.annotate(name, (px, py), textcoords="offset points", xytext=(5, 5), fontsize=10)
        
        ax.set_xlabel('x')
        ax.set_ylabel('y')
        ax.set_title('Circle - SDF Zero-Level Set')
        ax.legend(loc='upper right')
        ax.set_aspect('equal')
        ax.grid(True, alpha=0.3)
        
        # Info panel
        ax_info.axis('off')
        
        text = problem.get('text', '')
        wrapped_text = self._wrap_text(text, width=60)
        
        info_text = f"""PROBLEM
{'─' * 50}
{wrapped_text}

EQUATION (SDF Zero-Level Set)
{'─' * 50}
(x - {cx:.2f})² + (y - {cy:.2f})² = {r**2:.2f}

SDF PARAMETERS
{'─' * 50}
center: ({cx:.4f}, {cy:.4f})
radius: {r:.4f}

EXPECTED ANSWER: {problem.get('answer_expressions', 'N/A')}
QUERY: {problem.get('query_expressions', 'N/A')}"""
        
        ax_info.text(0, 1, info_text, transform=ax_info.transAxes,
                    fontsize=10, verticalalignment='top', fontfamily='monospace',
                    wrap=True)
        
        plt.tight_layout()
        output_path.parent.mkdir(parents=True, exist_ok=True)
        plt.savefig(output_path, dpi=150, bbox_inches='tight', facecolor='white')
        plt.close()
    
    def _wrap_text(self, text: str, width: int = 50) -> str:
        """Wrap text to specified width."""
        words = text.split()
        lines = []
        current_line = []
        current_len = 0
        
        for word in words:
            if current_len + len(word) + 1 <= width:
                current_line.append(word)
                current_len += len(word) + 1
            else:
                if current_line:
                    lines.append(' '.join(current_line))
                current_line = [word]
                current_len = len(word)
        
        if current_line:
            lines.append(' '.join(current_line))
        
        return '\n'.join(lines)
    
    def _visualize_ellipse(self, sdf: EllipseSDF, problem: Dict, params: Dict,
                          output_path: Path, major_axis: str):
        """Visualize ellipse using SDF zero-level set, including related shapes."""
        
        with torch.no_grad():
            a = abs(sdf.a.item())
            b = abs(sdf.b.item())
        
        # Ensure minimum b value for visualization
        b_viz = max(b, 0.1)
        
        fact_expr = problem.get('fact_expressions', '')
        
        # Check if there's also a hyperbola in the problem
        hyperbola_params = self.parser.parse_hyperbola(fact_expr)
        has_hyperbola = hyperbola_params is not None and 'a' in hyperbola_params and 'b' in hyperbola_params
        
        # Determine plot limits - ensure all curves visible
        if has_hyperbola:
            a_hyp = hyperbola_params['a']
            b_hyp = hyperbola_params['b']
            max_dim = max(a, b_viz, a_hyp, b_hyp) * 1.8 + 1
        else:
            max_dim = max(a, b_viz) * 1.3
        
        # Use vertical layout: plot on top, info below
        fig = plt.figure(figsize=(10, 14), dpi=120)
        
        # Main plot takes up top 60%
        ax_main = fig.add_axes([0.1, 0.4, 0.8, 0.55])
        
        # Create renderer with appropriate limits
        renderer = SDFRenderer(
            resolution=500,
            xlim=(-max_dim, max_dim),
            ylim=(-max_dim, max_dim)
        )
        
        # Render SDF field and zero-level set
        renderer.render_sdf_field(sdf, ax_main, show_field=True)
        
        # If there's a hyperbola, also draw it
        if has_hyperbola:
            center = torch.tensor([0.0, 0.0])
            a_hyp_t = torch.tensor([hyperbola_params['a']])
            b_hyp_t = torch.tensor([hyperbola_params['b']])
            hyp_sdf = HyperbolaSDF(center, a_hyp_t, b_hyp_t)
            
            # Draw hyperbola zero-level set in a different color
            with torch.no_grad():
                grid_flat = renderer.grid.reshape(-1, 2)
                hyp_distances = hyp_sdf(grid_flat).reshape(renderer.resolution, renderer.resolution)
                hyp_distances_np = hyp_distances.cpu().numpy()
            
            ax_main.contour(renderer.xx.numpy(), renderer.yy.numpy(), hyp_distances_np,
                           levels=[0], colors=['#E74C3C'], linewidths=2.5, linestyles='-')
            
            # Asymptotes for hyperbola
            slope_hyp = hyperbola_params['b'] / hyperbola_params['a']
            x_asym = np.linspace(-max_dim, max_dim, 100)
            ax_main.plot(x_asym, slope_hyp * x_asym, '--', color='#C73E1D', linewidth=1.5, alpha=0.5)
            ax_main.plot(x_asym, -slope_hyp * x_asym, '--', color='#C73E1D', linewidth=1.5, alpha=0.5)
            
            # Add to legend
            ellipse_line = Line2D([0], [0], color='#2E86AB', linewidth=2.5, 
                                  label=f'Ellipse (x²/{params["x_coef"]:.0f} + y²/{params["y_coef"]:.0f} = 1)')
            hyperbola_line = Line2D([0], [0], color='#E74C3C', linewidth=2.5, 
                                    label=f'Hyperbola (x²/{hyperbola_params["a"]:.2f}² - y²/{hyperbola_params["b"]:.2f}² = 1)')
        
        # Calculate and plot foci
        c = np.sqrt(abs(a**2 - b**2)) if a > b else np.sqrt(abs(b**2 - a**2))
        if major_axis == 'x':
            ax_main.plot([c, -c], [0, 0], 'ro', markersize=12, 
                        label='Shared Foci' if has_hyperbola else 'Foci', zorder=5)
            ax_main.annotate('$F_1$', (-c, 0), xytext=(-c-0.4, 0.4), fontsize=14, fontweight='bold')
            ax_main.annotate('$F_2$', (c, 0), xytext=(c+0.2, 0.4), fontsize=14, fontweight='bold')
        else:
            ax_main.plot([0, 0], [c, -c], 'ro', markersize=12, 
                        label='Shared Foci' if has_hyperbola else 'Foci', zorder=5)
            ax_main.annotate('$F_1$', (0, -c), xytext=(0.3, -c-0.4), fontsize=14, fontweight='bold')
            ax_main.annotate('$F_2$', (0, c), xytext=(0.3, c+0.2), fontsize=14, fontweight='bold')
        
        # Plot additional points
        coords = self.parser.parse_coordinates(problem.get('fact_expressions', ''))
        for name, (px, py) in coords.items():
            if name not in ['F1', 'F2', 'F', 'O']:
                ax_main.plot(px, py, 'go', markersize=10, zorder=6)
                ax_main.annotate(f'${name}$', (px, py), xytext=(px+0.3, py+0.3), fontsize=13, fontweight='bold')
        
        # Styling
        ax_main.axhline(y=0, color='black', linewidth=0.8, alpha=0.6)
        ax_main.axvline(x=0, color='black', linewidth=0.8, alpha=0.6)
        ax_main.grid(True, alpha=0.3, linestyle='--')
        ax_main.set_xlim(-max_dim, max_dim)
        ax_main.set_ylim(-max_dim, max_dim)
        ax_main.set_xlabel('x', fontsize=14)
        ax_main.set_ylabel('y', fontsize=14)
        
        if has_hyperbola:
            ax_main.set_title('Ellipse & Hyperbola - SDF Zero-Level Sets', fontsize=16, fontweight='bold', pad=10)
            handles, labels = ax_main.get_legend_handles_labels()
            handles.extend([ellipse_line, hyperbola_line])
            ax_main.legend(handles=handles, loc='upper right', fontsize=10)
        else:
            ax_main.set_title('Ellipse - SDF Zero-Level Set', fontsize=16, fontweight='bold', pad=10)
            ax_main.legend(loc='upper right', fontsize=11)
        
        ax_main.set_aspect('equal')
        ax_main.tick_params(labelsize=11)
        
        # Info panel at bottom
        ax_info = fig.add_axes([0.05, 0.02, 0.9, 0.35])
        ax_info.axis('off')
        
        x_coef = params['x_coef']
        y_coef = params['y_coef']
        
        # Wrap problem text
        problem_text = self._wrap_text(problem.get('text', ''), width=70)
        
        if has_hyperbola:
            equations_text = f"""Ellipse: x²/{np.sqrt(x_coef):.2f}² + y²/{np.sqrt(y_coef):.2f}² = 1  (Blue)
Hyperbola: x²/{hyperbola_params['a']:.2f}² - y²/{hyperbola_params['b']:.2f}² = 1  (Red)"""
        else:
            equations_text = f"x²/{np.sqrt(x_coef):.2f}² + y²/{np.sqrt(y_coef):.2f}² = 1"
        
        info_text = f"""PROBLEM
{'─'*70}
{problem_text}

EQUATIONS (SDF Zero-Level Sets)
{'─'*70}
{equations_text}

SDF PARAMETERS (Ellipse)
{'─'*70}
a (semi-major): {a:.4f}    b (semi-minor): {b:.4f}    c (focal dist): {c:.4f}
eccentricity: {c/max(a,b):.4f}    major_axis: {major_axis}

EXPECTED ANSWER: {problem.get('answer_expressions', '')}
QUERY: {problem.get('query_expressions', '')}
"""
        
        ax_info.text(0.0, 1.0, info_text, transform=ax_info.transAxes,
                    fontsize=10, verticalalignment='top', family='monospace',
                    bbox=dict(boxstyle='round,pad=0.5', facecolor='#E8F4F8', alpha=0.9, edgecolor='#CCCCCC'))
        
        plt.savefig(output_path, bbox_inches='tight', dpi=120, facecolor='white')
        plt.close(fig)
    
    def _visualize_hyperbola(self, sdf: HyperbolaSDF, problem: Dict, params: Dict,
                            output_path: Path):
        """Visualize hyperbola using SDF zero-level set, including related shapes."""
        
        with torch.no_grad():
            a = abs(sdf.a.item())
            b = abs(sdf.b.item())
        
        fact_expr = problem.get('fact_expressions', '')
        
        # Check if there are other shapes in the problem
        ellipse_params = self.parser.parse_ellipse(fact_expr)
        line_params = self.parser.parse_line(fact_expr)
        has_ellipse = ellipse_params is not None and 'a' in ellipse_params and 'b' in ellipse_params
        has_line = line_params is not None and (line_params.get('a') is not None or line_params.get('slope') is not None)
        
        # If line has slope but no explicit equation, try to construct it
        if has_line and line_params.get('slope') is not None and line_params.get('a') is None:
            # Check if line passes through a focus
            slope = line_params['slope']
            # Find focus coordinates
            if 'LeftFocus' in fact_expr or 'RightFocus' in fact_expr:
                # Line passes through focus
                c_hyp = np.sqrt(a**2 + b**2)
                if 'LeftFocus' in fact_expr:
                    focus_x = -c_hyp
                else:
                    focus_x = c_hyp
                # Line: y - 0 = slope * (x - focus_x) => slope*x - y - slope*focus_x = 0
                line_params['a'] = slope
                line_params['b'] = -1.0
                line_params['c'] = -slope * focus_x
                line_params['equation'] = f'y = {slope:.2f}(x - {focus_x:.2f})'
        
        # Determine plot limits
        if has_ellipse:
            a_ell = ellipse_params['a']
            b_ell = ellipse_params['b']
            max_dim = max(a, b, a_ell, b_ell) * 1.5 + 1
        else:
            max_dim = max(a, b) * 2.5 + 2
        
        # Use vertical layout
        fig = plt.figure(figsize=(10, 14), dpi=120)
        ax_main = fig.add_axes([0.1, 0.4, 0.8, 0.55])
        
        renderer = SDFRenderer(
            resolution=500,
            xlim=(-max_dim, max_dim),
            ylim=(-max_dim, max_dim)
        )
        
        # Render hyperbola SDF field
        renderer.render_sdf_field(sdf, ax_main, show_field=True)
        
        # If there's an ellipse, also draw it
        if has_ellipse:
            center = torch.tensor([0.0, 0.0])
            a_ell_t = torch.tensor([ellipse_params['a']])
            b_ell_t = torch.tensor([ellipse_params['b']])
            ellipse_sdf = EllipseSDF(center, a_ell_t, b_ell_t)
            
            # Draw ellipse zero-level set in a different color
            with torch.no_grad():
                grid_flat = renderer.grid.reshape(-1, 2)
                ell_distances = ellipse_sdf(grid_flat).reshape(renderer.resolution, renderer.resolution)
                ell_distances_np = ell_distances.cpu().numpy()
            
            ax_main.contour(renderer.xx.numpy(), renderer.yy.numpy(), ell_distances_np,
                           levels=[0], colors=['#27AE60'], linewidths=2.5, linestyles='-')
            
            # Add ellipse to legend
            ellipse_line = Line2D([0], [0], color='#27AE60', linewidth=2.5, label=f'Ellipse (x²/{ellipse_params["x_coef"]:.0f} + y²/{ellipse_params["y_coef"]:.0f} = 1)')
            hyperbola_line = Line2D([0], [0], color='#2E86AB', linewidth=2.5, label=f'Hyperbola (x²/{a:.2f}² - y²/{b:.2f}² = 1)')
        
        # Draw line if present (only if we have complete line equation)
        if has_line and line_params.get('a') is not None and line_params.get('b') is not None:
            line_a = line_params['a']
            line_b = line_params['b']
            line_c = line_params.get('c', 0)
            
            # Line: ax + by + c = 0 => y = (-ax - c) / b or x = (-by - c) / a
            x_line = np.linspace(-max_dim, max_dim, 100)
            if abs(line_b) > 1e-6:
                y_line = (-line_a * x_line - line_c) / line_b
                ax_main.plot(x_line, y_line, '-', color='#9B59B6', linewidth=2.5, 
                            label=f'Line ({line_params["equation"]} = 0)', zorder=4)
            else:
                # Vertical line
                x_val = -line_c / line_a if abs(line_a) > 1e-6 else 0
                ax_main.axvline(x=x_val, color='#9B59B6', linewidth=2.5,
                               label=f'Line (x = {x_val:.2f})', zorder=4)
        
        # Foci (shared between hyperbola and ellipse if Focus(G) = Focus(H))
        c = np.sqrt(a**2 + b**2)
        ax_main.plot([c, -c], [0, 0], 'ro', markersize=12, label='Shared Foci' if has_ellipse else 'Foci', zorder=5)
        ax_main.annotate('$F_1$', (-c, 0), xytext=(-c-0.4, 0.6), fontsize=14, fontweight='bold')
        ax_main.annotate('$F_2$', (c, 0), xytext=(c+0.2, 0.6), fontsize=14, fontweight='bold')
        
        # Asymptotes
        slope = b / a
        x_asym = np.linspace(-max_dim, max_dim, 100)
        ax_main.plot(x_asym, slope * x_asym, '--', color='#C73E1D', linewidth=2, 
                    alpha=0.7, label='Asymptotes')
        ax_main.plot(x_asym, -slope * x_asym, '--', color='#C73E1D', linewidth=2, alpha=0.7)
        
        # Plot additional points
        coords = self.parser.parse_coordinates(problem.get('fact_expressions', ''))
        for name, (px, py) in coords.items():
            if name not in ['F1', 'F2', 'F', 'O']:
                ax_main.plot(px, py, 'go', markersize=10, zorder=6)
                ax_main.annotate(f'${name}$', (px, py), xytext=(px+0.3, py+0.3), fontsize=13, fontweight='bold')
        
        ax_main.axhline(y=0, color='black', linewidth=0.8, alpha=0.6)
        ax_main.axvline(x=0, color='black', linewidth=0.8, alpha=0.6)
        ax_main.grid(True, alpha=0.3, linestyle='--')
        ax_main.set_xlim(-max_dim, max_dim)
        ax_main.set_ylim(-max_dim, max_dim)
        ax_main.set_xlabel('x', fontsize=14)
        ax_main.set_ylabel('y', fontsize=14)
        
        # Set title based on what shapes are present
        title_parts = ['Hyperbola']
        if has_ellipse:
            title_parts.append('Ellipse')
        if has_line:
            title_parts.append('Line')
        
        if len(title_parts) > 1:
            ax_main.set_title(' & '.join(title_parts) + ' - SDF Zero-Level Sets', fontsize=16, fontweight='bold', pad=10)
            handles, labels = ax_main.get_legend_handles_labels()
            if has_ellipse:
                handles.extend([ellipse_line, hyperbola_line])
            ax_main.legend(handles=handles, loc='upper right', fontsize=10)
        else:
            ax_main.set_title('Hyperbola - SDF Zero-Level Set', fontsize=16, fontweight='bold', pad=10)
            ax_main.legend(loc='upper right', fontsize=11)
        
        ax_main.set_aspect('equal')
        ax_main.tick_params(labelsize=11)
        
        # Info panel at bottom
        ax_info = fig.add_axes([0.05, 0.02, 0.9, 0.35])
        ax_info.axis('off')
        
        problem_text = self._wrap_text(problem.get('text', ''), width=70)
        
        equations_parts = [f"Hyperbola: x²/{a:.2f}² - y²/{b:.2f}² = 1  (Blue)"]
        if has_ellipse:
            equations_parts.append(f"Ellipse: x²/{ellipse_params['x_coef']:.0f} + y²/{ellipse_params['y_coef']:.0f} = 1  (Green)")
        if has_line:
            equations_parts.append(f"Line: {line_params.get('equation', 'slope defined')} = 0  (Purple)")
        
        equations_text = '\n'.join(equations_parts)
        
        info_text = f"""PROBLEM
{'─'*70}
{problem_text}

EQUATIONS (SDF Zero-Level Sets)
{'─'*70}
{equations_text}

SDF PARAMETERS (Hyperbola)
{'─'*70}
a: {a:.4f}    b: {b:.4f}    c: {c:.4f}
eccentricity: {c/a:.4f}    asymptote slope: ±{slope:.4f}

EXPECTED ANSWER: {problem.get('answer_expressions', '')}
QUERY: {problem.get('query_expressions', '')}
"""
        
        ax_info.text(0.0, 1.0, info_text, transform=ax_info.transAxes,
                    fontsize=10, verticalalignment='top', family='monospace',
                    bbox=dict(boxstyle='round,pad=0.5', facecolor='#E8F4F8', alpha=0.9, edgecolor='#CCCCCC'))
        
        plt.savefig(output_path, bbox_inches='tight', dpi=120, facecolor='white')
        plt.close(fig)
    
    def _visualize_parabola(self, sdf: ParabolaSDF, problem: Dict, params: Dict,
                           output_path: Path):
        """Visualize parabola using SDF zero-level set."""
        
        with torch.no_grad():
            p = abs(sdf.p.item())
        
        direction = params.get('direction', 'right')
        
        # Adjust limits based on direction and p value
        extent = max(p * 8, 6)
        if direction == 'right':
            xlim = (-p * 2, extent)
            ylim = (-extent * 0.8, extent * 0.8)
        elif direction == 'left':
            xlim = (-extent, p * 2)
            ylim = (-extent * 0.8, extent * 0.8)
        else:  # up
            xlim = (-extent * 0.8, extent * 0.8)
            ylim = (-p * 2, extent)
        
        # Use vertical layout
        fig = plt.figure(figsize=(10, 14), dpi=120)
        ax_main = fig.add_axes([0.1, 0.4, 0.8, 0.55])
        
        # Increase resolution slightly to sharpen zero-level near the vertex
        renderer = SDFRenderer(resolution=600, xlim=xlim, ylim=ylim)
        renderer.render_sdf_field(sdf, ax_main, show_field=True)
        
        # Focus and directrix
        if direction == 'right':
            focus = (p, 0)
            ax_main.plot(p, 0, 'ro', markersize=12, label='Focus', zorder=5)
            ax_main.annotate('$F$', (p, 0), xytext=(p+0.4, 0.4), fontsize=14, fontweight='bold')
            ax_main.axvline(x=-p, color='#2ECC71', linestyle='--', linewidth=2, 
                           alpha=0.8, label='Directrix')
            equation = f"y² = {4*p:.2f}x"
        elif direction == 'left':
            focus = (-p, 0)
            ax_main.plot(-p, 0, 'ro', markersize=12, label='Focus', zorder=5)
            ax_main.annotate('$F$', (-p, 0), xytext=(-p-0.6, 0.4), fontsize=14, fontweight='bold')
            ax_main.axvline(x=p, color='#2ECC71', linestyle='--', linewidth=2,
                           alpha=0.8, label='Directrix')
            equation = f"y² = -{4*p:.2f}x"
        else:  # up
            focus = (0, p)
            ax_main.plot(0, p, 'ro', markersize=12, label='Focus', zorder=5)
            ax_main.annotate('$F$', (0, p), xytext=(0.4, p+0.4), fontsize=14, fontweight='bold')
            ax_main.axhline(y=-p, color='#2ECC71', linestyle='--', linewidth=2,
                           alpha=0.8, label='Directrix')
            equation = f"x² = {4*p:.2f}y"
        
        # Plot additional points with staggered labels to reduce overlaps
        coords = self.parser.parse_coordinates(problem.get('fact_expressions', ''))
        for idx, (name, (px, py)) in enumerate(coords.items()):
            if name not in ['F', 'O']:
                ax_main.plot(px, py, 'go', markersize=10, zorder=6)
                offset_y = 0.3 + 0.25 * idx
                ax_main.annotate(f'${name}$', (px, py), xytext=(px + 0.3, py + offset_y),
                                 fontsize=13, fontweight='bold')
        
        ax_main.axhline(y=0, color='black', linewidth=0.8, alpha=0.6)
        ax_main.axvline(x=0, color='black', linewidth=0.8, alpha=0.6)
        ax_main.grid(True, alpha=0.3, linestyle='--')
        ax_main.set_xlim(xlim)
        ax_main.set_ylim(ylim)
        ax_main.set_xlabel('x', fontsize=14)
        ax_main.set_ylabel('y', fontsize=14)
        ax_main.set_title('Parabola - SDF Zero-Level Set', fontsize=16, fontweight='bold', pad=10)
        ax_main.set_aspect('equal')
        ax_main.legend(loc='upper right', fontsize=11)
        ax_main.tick_params(labelsize=11)
        
        # Info panel at bottom
        ax_info = fig.add_axes([0.05, 0.02, 0.9, 0.35])
        ax_info.axis('off')
        
        problem_text = self._wrap_text(problem.get('text', ''), width=70)
        
        info_text = f"""PROBLEM
{'─'*70}
{problem_text}

EQUATION (SDF Zero-Level Set)
{'─'*70}
{equation}

SDF PARAMETERS
{'─'*70}
p (focal param): {p:.4f}    focus: {focus}
directrix: {'x = ' + f'{-p:.2f}' if direction in ['right', 'left'] else 'y = ' + f'{-p:.2f}'}
direction: {direction}

EXPECTED ANSWER: {problem.get('answer_expressions', '')}
QUERY: {problem.get('query_expressions', '')}
"""
        
        ax_info.text(0.0, 1.0, info_text, transform=ax_info.transAxes,
                    fontsize=10, verticalalignment='top', family='monospace',
                    bbox=dict(boxstyle='round,pad=0.5', facecolor='#E8F4F8', alpha=0.9, edgecolor='#CCCCCC'))
        
        plt.savefig(output_path, bbox_inches='tight', dpi=120, facecolor='white')
        plt.close(fig)
    
    def process_batch(self, problems_input, max_problems: int = None,
                     verbose: bool = False) -> List[Dict]:
        """Process a batch of problems.
        
        Args:
            problems_input: Either a list of problem dicts or a path to JSON file
            max_problems: Maximum number of problems to process
            verbose: Whether to print verbose output
        """
        # Handle both list and file path inputs
        if isinstance(problems_input, str):
            with open(problems_input, 'r', encoding='utf-8') as f:
                problems = json.load(f)
        else:
            problems = problems_input
            
        if max_problems:
            problems = problems[:max_problems]
        
        results = []
        stats = {'total': len(problems), 'success': 0, 'failed': 0}
        type_stats = {'ellipse': 0, 'hyperbola': 0, 'parabola': 0, 'circle': 0}
        reason_counts: Dict[str, int] = {}
        
        print(f"\n{'='*60}")
        print(f"SDF-Based Processing: {len(problems)} problems")
        print(f"{'='*60}\n")
        
        for idx, problem in enumerate(tqdm(problems, desc="Processing")):
            result = self.process_problem(problem, idx, verbose)
            results.append(result)
            
            if result['success']:
                stats['success'] += 1
                ctype = result.get('conic_type')
                if ctype in type_stats:
                    type_stats[ctype] += 1
            else:
                stats['failed'] += 1
                for reason in result.get('validation_reasons', []):
                    reason_counts[reason] = reason_counts.get(reason, 0) + 1
        
        # Save summary
        summary = {
            'stats': stats,
            'type_stats': type_stats,
            'reason_counts': reason_counts,
            'results': results
        }
        with open(self.output_dir / 'summary.json', 'w') as f:
            json.dump(summary, f, indent=2, default=str)
        
        print(f"\n{'='*60}")
        print("PROCESSING COMPLETE")
        print(f"{'='*60}")
        print(f"Success: {stats['success']} / {stats['total']} ({100*stats['success']/stats['total']:.1f}%)")
        print(f"By type: {type_stats}")
        print(f"Output: {self.output_dir}")
        
        return results