File size: 47,289 Bytes
fdb3169
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
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
"""
Problem Parser Module
Extracts geometric parameters from problem expressions.
"""

import re
import numpy as np
from typing import Dict, List, Tuple, Optional


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