File size: 143,641 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 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 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926 1927 1928 1929 1930 1931 1932 1933 1934 1935 1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954 1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985 1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069 2070 2071 2072 2073 2074 2075 2076 2077 2078 2079 2080 2081 2082 2083 2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095 2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125 2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165 2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200 2201 2202 2203 2204 2205 2206 2207 2208 2209 2210 2211 2212 2213 2214 2215 2216 2217 2218 2219 2220 2221 2222 2223 2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235 2236 2237 2238 2239 2240 2241 2242 2243 2244 2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379 2380 2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398 2399 2400 2401 2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414 2415 2416 2417 2418 2419 2420 2421 2422 2423 2424 2425 2426 2427 2428 2429 2430 2431 2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442 2443 2444 2445 2446 2447 2448 2449 2450 2451 2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464 2465 2466 2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481 2482 2483 2484 2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540 2541 2542 2543 2544 2545 2546 2547 2548 2549 2550 2551 2552 2553 2554 2555 2556 2557 2558 2559 2560 2561 2562 2563 2564 2565 2566 2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606 2607 2608 2609 2610 2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703 2704 2705 2706 2707 2708 2709 2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723 2724 2725 2726 2727 2728 2729 2730 2731 2732 2733 2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751 2752 2753 2754 2755 2756 2757 2758 2759 2760 2761 2762 2763 2764 2765 2766 2767 2768 2769 2770 2771 2772 2773 2774 2775 2776 2777 2778 2779 2780 2781 2782 2783 2784 2785 2786 2787 2788 2789 2790 2791 2792 2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803 2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825 2826 2827 2828 2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861 2862 2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880 2881 2882 2883 2884 2885 2886 2887 2888 2889 2890 2891 2892 2893 2894 2895 2896 2897 2898 2899 2900 2901 2902 2903 2904 2905 2906 2907 2908 2909 2910 2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923 2924 2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948 2949 2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981 2982 2983 2984 2985 2986 2987 2988 2989 2990 2991 2992 2993 2994 2995 2996 2997 2998 2999 3000 3001 3002 3003 3004 3005 3006 3007 3008 3009 3010 3011 3012 3013 3014 3015 3016 3017 3018 3019 3020 3021 3022 3023 3024 3025 3026 3027 3028 3029 3030 3031 3032 3033 3034 3035 3036 3037 3038 3039 3040 3041 3042 3043 3044 3045 3046 3047 3048 3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098 3099 3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122 3123 3124 3125 3126 3127 3128 3129 3130 3131 3132 3133 3134 3135 3136 3137 3138 3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149 3150 3151 3152 3153 3154 3155 3156 3157 3158 3159 3160 3161 3162 3163 3164 3165 3166 3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200 3201 3202 3203 3204 3205 3206 3207 3208 3209 3210 3211 3212 3213 3214 3215 3216 3217 3218 3219 3220 3221 3222 3223 3224 3225 3226 3227 3228 3229 3230 3231 3232 3233 3234 3235 3236 3237 3238 3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249 3250 3251 3252 3253 3254 3255 3256 3257 3258 3259 3260 3261 3262 3263 3264 3265 3266 3267 3268 3269 3270 3271 3272 3273 3274 3275 3276 3277 3278 3279 3280 3281 3282 3283 3284 3285 3286 3287 3288 3289 3290 3291 3292 3293 3294 3295 3296 3297 3298 3299 3300 3301 3302 3303 3304 3305 3306 3307 3308 3309 3310 3311 3312 3313 3314 3315 3316 3317 3318 3319 3320 3321 3322 3323 3324 3325 3326 3327 3328 3329 3330 3331 3332 3333 3334 3335 3336 3337 3338 3339 3340 3341 3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353 3354 3355 3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375 3376 3377 3378 3379 3380 3381 3382 3383 3384 3385 3386 3387 3388 3389 3390 3391 3392 3393 3394 3395 3396 3397 3398 3399 3400 3401 3402 3403 3404 3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418 3419 3420 3421 3422 3423 3424 3425 3426 3427 3428 3429 3430 3431 3432 3433 3434 3435 3436 3437 3438 3439 3440 3441 3442 3443 3444 3445 3446 3447 3448 3449 3450 3451 3452 3453 3454 3455 3456 3457 3458 3459 3460 3461 3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472 3473 3474 3475 3476 3477 3478 3479 3480 3481 3482 3483 3484 3485 3486 3487 3488 3489 3490 3491 3492 3493 3494 3495 3496 3497 3498 3499 3500 3501 3502 3503 3504 3505 3506 3507 3508 3509 3510 3511 3512 3513 3514 3515 3516 3517 3518 3519 3520 3521 3522 3523 3524 3525 3526 3527 3528 3529 3530 3531 3532 3533 3534 3535 3536 3537 3538 3539 3540 3541 3542 3543 3544 3545 3546 3547 3548 3549 3550 3551 3552 3553 |
"""
SDF-Based Analytic Geometry Solver
Strictly following the GeoSDF paper methodology
Core Principles:
1. True Signed Distance Field representations for all geometric primitives
2. Constraint-based optimization using differentiable loss functions
3. Zero-level set visualization (SDF = 0 defines the curve)
4. Gradient-based optimization with Adam/AdamW
Reference: GeoSDF - Plane Geometry Diagram Synthesis via Signed Distance Field
"""
import torch
import torch.nn as nn
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import json
import re
from pathlib import Path
from typing import Dict, List, Tuple, Optional, Any, Union
from dataclasses import dataclass, field
from enum import Enum
import warnings
from tqdm import tqdm
import argparse
warnings.filterwarnings('ignore')
plt.switch_backend('Agg')
# Device configuration
DEVICE = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
# =============================================================================
# Quartic Solver Utilities (Following Paper Appendix B)
# Fully vectorized for batch SDF computation
# =============================================================================
def solve_cubic_one_real_batch(a: torch.Tensor, b: torch.Tensor, c: torch.Tensor,
d: torch.Tensor) -> torch.Tensor:
"""
Find one real root of cubic equation: ax³ + bx² + cx + d = 0
Using Cardano's formula. Fully vectorized for batch inputs.
Args:
a, b, c, d: Coefficient tensors of same shape [...]
Returns:
Tensor of same shape with one real root per element
"""
# Normalize to x³ + px² + qx + r = 0
a_safe = a + 1e-10 * torch.sign(a + 1e-20)
p = b / a_safe
q = c / a_safe
r = d / a_safe
# Substitute x = t - p/3 to get depressed cubic: t³ + αt + β = 0
alpha = q - p**2 / 3
beta = 2 * p**3 / 27 - p * q / 3 + r
# Cardano's discriminant
discriminant = (beta / 2)**2 + (alpha / 3)**3
# For numerical stability, use safe sqrt
sqrt_disc = torch.sqrt(torch.clamp(discriminant, min=0) + 1e-12)
# Cardano's formula: t = ∛(-β/2 + √Δ) + ∛(-β/2 - √Δ)
term1 = -beta / 2 + sqrt_disc
term2 = -beta / 2 - sqrt_disc
# Safe cube root preserving sign
def safe_cbrt(x):
return torch.sign(x) * torch.pow(torch.abs(x) + 1e-12, 1/3)
u = safe_cbrt(term1)
v = safe_cbrt(term2)
t = u + v
x = t - p / 3
return x
def hyperbola_distance_quartic(px: torch.Tensor, py: torch.Tensor,
a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
"""
Compute exact distance from point (px, py) to hyperbola x²/a² - y²/b² = 1
using the quartic equation approach from Paper Appendix B.
For hyperbola in standard form, transform to xy = k form:
The closest point problem leads to: t⁴ - px·t³ - k·py·t + k² = 0
where k = ab (for the transformed hyperbola).
This is a vectorized implementation for batch processing.
Args:
px, py: Query point coordinates (batched tensors of same shape)
a, b: Hyperbola parameters (scalar tensors)
Returns:
Distance tensor of same shape as px, py
"""
# Use absolute values due to symmetry
px_abs = torch.abs(px)
py_abs = torch.abs(py)
# For hyperbola x²/a² - y²/b² = 1, parametric form: (a·cosh(t), b·sinh(t))
# The distance minimization leads to a quartic in t (or in the parameter)
# Alternative approach: Use the fact that the closest point satisfies
# the normal from (px, py) passing through the hyperbola point
# This gives: (px - a·cosh(t))·a·sinh(t) = (py - b·sinh(t))·b·cosh(t)
# For numerical stability, we use Newton-Raphson with good initial guess
# combined with the quartic structure for refinement
# Initial guess from asymptotic behavior
t = torch.asinh(py_abs / (b + 1e-8))
t = torch.clamp(t, 0.01, 10.0)
# Newton-Raphson iterations (the quartic solver is used for validation)
for _ in range(15):
cosh_t = torch.cosh(t)
sinh_t = torch.sinh(t)
# Point on hyperbola
hx = a * cosh_t
hy = b * sinh_t
# Distance squared: f(t) = (px - hx)² + (py - hy)²
dx = px_abs - hx
dy = py_abs - hy
# Gradient: f'(t) = -2[(px - hx)·a·sinh(t) + (py - hy)·b·cosh(t)]
grad = -2 * (dx * a * sinh_t + dy * b * cosh_t)
# Hessian: f''(t) = 2[a²sinh² + b²cosh² - dx·a·cosh - dy·b·sinh]
hess = 2 * (a**2 * sinh_t**2 + b**2 * cosh_t**2
- dx * a * cosh_t - dy * b * sinh_t)
hess = hess + 1e-6 # Regularization
# Newton step with damping
step = grad / torch.abs(hess)
t = t - torch.clamp(step, -0.3, 0.3)
t = torch.clamp(t, 0.001, 20.0)
# Final distance computation
cosh_t = torch.cosh(t)
sinh_t = torch.sinh(t)
closest_x = a * cosh_t
closest_y = b * sinh_t
dist = torch.sqrt((px_abs - closest_x)**2 + (py_abs - closest_y)**2 + 1e-10)
return dist
def ellipse_distance_quartic(px: torch.Tensor, py: torch.Tensor,
a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
"""
Compute exact distance from point (px, py) to ellipse x²/a² + y²/b² = 1
using the quartic equation approach from Paper Appendix B.
The closest point on ellipse to (px, py) satisfies a quartic equation.
Reference: "Computing the Distance from a Point to an Ellipse" (Eberly)
This is a vectorized implementation for batch processing.
Args:
px, py: Query point coordinates (batched tensors of same shape)
a, b: Ellipse semi-axes (scalar tensors), assumes a >= b
Returns:
Distance tensor of same shape as px, py
"""
# Use absolute values due to symmetry
px_abs = torch.abs(px)
py_abs = torch.abs(py)
# Ensure a >= b for the algorithm
a_use = torch.max(a, b)
b_use = torch.min(a, b)
# Swap coordinates if needed
needs_swap = a < b
if needs_swap:
px_use, py_use = py_abs, px_abs
else:
px_use, py_use = px_abs, py_abs
# Handle special cases
# Case 1: Point at origin
at_origin = (px_use < 1e-10) & (py_use < 1e-10)
# Case 2: Point on x-axis (py = 0)
on_x_axis = py_use < 1e-10
# Case 3: Point on y-axis (px = 0)
on_y_axis = px_use < 1e-10
# General case: Use Newton iteration on the parametric form
# Ellipse: (a·cos(θ), b·sin(θ))
# Minimize: (px - a·cos(θ))² + (py - b·sin(θ))²
# Initial guess
theta = torch.atan2(a_use * py_use, b_use * px_use)
for _ in range(12):
cos_t = torch.cos(theta)
sin_t = torch.sin(theta)
# Point on ellipse
ex = a_use * cos_t
ey = b_use * sin_t
# Residuals
dx = px_use - ex
dy = py_use - ey
# Gradient: d/dθ [(px - a·cos)² + (py - b·sin)²]
# = 2(px - a·cos)(a·sin) + 2(py - b·sin)(-b·cos)
grad = 2 * (dx * a_use * sin_t - dy * b_use * cos_t)
# Hessian
hess = 2 * (a_use**2 * sin_t**2 + b_use**2 * cos_t**2
+ dx * a_use * cos_t + dy * b_use * sin_t)
hess = hess + 1e-6
# Newton step
step = grad / torch.abs(hess)
theta = theta - torch.clamp(step, -0.3, 0.3)
# Final distance
cos_t = torch.cos(theta)
sin_t = torch.sin(theta)
closest_x = a_use * cos_t
closest_y = b_use * sin_t
dist = torch.sqrt((px_use - closest_x)**2 + (py_use - closest_y)**2 + 1e-10)
# Handle special cases
# At origin: distance to closest point on ellipse (the minor axis endpoint)
dist_origin = b_use
dist = torch.where(at_origin, dist_origin, dist)
# On x-axis: distance is |px - a| if px > a, else 0 (on ellipse) or distance to (a,0)
dist_x_axis = torch.where(px_use > a_use, px_use - a_use,
torch.sqrt((px_use - a_use)**2 + 1e-10))
dist = torch.where(on_x_axis & ~at_origin, dist_x_axis, dist)
# On y-axis: distance to (0, b)
dist_y_axis = torch.abs(py_use - b_use)
dist = torch.where(on_y_axis & ~at_origin, dist_y_axis, dist)
return dist
# =============================================================================
# SDF Primitives (Following Paper Section 2 & 3)
# =============================================================================
class SDFPrimitive(nn.Module):
"""Base class for SDF primitives - all shapes represented as distance functions"""
def forward(self, p: torch.Tensor) -> torch.Tensor:
"""
Compute signed distance from points p to the shape boundary.
Args:
p: Points tensor of shape [N, 2] or [H, W, 2]
Returns:
Signed distance tensor, negative inside, positive outside
"""
raise NotImplementedError
class PointSDF(SDFPrimitive):
"""SDF for a point: f(p; c) = ||p - c||₂"""
def __init__(self, center: torch.Tensor):
super().__init__()
self.center = nn.Parameter(center.clone())
def forward(self, p: torch.Tensor) -> torch.Tensor:
return torch.norm(p - self.center, dim=-1)
class CircleSDF(SDFPrimitive):
"""
SDF for circle: f(p; c, r) = ||p - c||₂ - r
Sign convention:
- Negative inside the circle
- Positive outside the circle
- Zero on the boundary
"""
def __init__(self, center: torch.Tensor, radius: torch.Tensor):
super().__init__()
self.center = nn.Parameter(center.clone())
self.radius = nn.Parameter(radius.clone())
def forward(self, p: torch.Tensor) -> torch.Tensor:
dist_to_center = torch.norm(p - self.center, dim=-1)
return dist_to_center - self.radius
class EllipseSDF(SDFPrimitive):
"""
SDF for ellipse: x²/a² + y²/b² = 1
Uses quartic-based Newton iteration for accurate distance computation.
Reference: Paper Appendix B, "Computing Distance from Point to Ellipse"
Sign Convention:
- NEGATIVE: Point is INSIDE the ellipse
- POSITIVE: Point is OUTSIDE the ellipse
- ZERO: Point is on the ellipse boundary
Parameters:
center: [cx, cy] - center of ellipse
a: semi-axis along x
b: semi-axis along y
"""
def __init__(self, center: torch.Tensor, a: torch.Tensor, b: torch.Tensor):
super().__init__()
self.center = nn.Parameter(center.clone())
self.a = nn.Parameter(a.clone())
self.b = nn.Parameter(b.clone())
def forward(self, p: torch.Tensor) -> torch.Tensor:
# Translate to ellipse-centered coordinates
p_local = p - self.center
px = p_local[..., 0]
py = p_local[..., 1]
a = torch.abs(self.a) + 1e-8
b = torch.abs(self.b) + 1e-8
# Use the optimized quartic-based distance function
dist = ellipse_distance_quartic(px, py, a, b)
# Sign: inside if x²/a² + y²/b² < 1
ellipse_val = px**2 / (a**2) + py**2 / (b**2)
inside = ellipse_val < 1
return torch.where(inside, -dist, dist)
class EllipseSDF_Legacy(SDFPrimitive):
"""
Legacy EllipseSDF implementation using simple Newton iteration.
Kept for backward compatibility and comparison.
"""
def __init__(self, center: torch.Tensor, a: torch.Tensor, b: torch.Tensor):
super().__init__()
self.center = nn.Parameter(center.clone())
self.a = nn.Parameter(a.clone())
self.b = nn.Parameter(b.clone())
def forward(self, p: torch.Tensor) -> torch.Tensor:
p_local = p - self.center
px = torch.abs(p_local[..., 0])
py = torch.abs(p_local[..., 1])
a = torch.abs(self.a)
b = torch.abs(self.b)
# Swap if needed
swap_mask = a < b
if swap_mask.any():
px, py = torch.where(swap_mask, py, px), torch.where(swap_mask, px, py)
a, b = torch.where(swap_mask, b, a), torch.where(swap_mask, a, b)
# Newton iteration
t = torch.atan2(a * py, b * px)
# Newton iterations
for _ in range(5):
cos_t = torch.cos(t)
sin_t = torch.sin(t)
# Point on ellipse
ex = a * cos_t
ey = b * sin_t
# Distance squared
dx = px - ex
dy = py - ey
# Derivatives
# d/dt ||p - e(t)||² = 2 * (p - e(t)) · (-e'(t))
# e'(t) = (-a*sin(t), b*cos(t))
dex = -a * sin_t
dey = b * cos_t
# Gradient
grad = dx * (-dex) + dy * (-dey)
# Second derivative for Newton step
ddex = -a * cos_t
ddey = -b * sin_t
hess = dex * dex + dey * dey + dx * (-ddex) + dy * (-ddey)
# Newton update with damping
step = grad / (hess + 1e-8)
t = t - 0.8 * step
# Final closest point
cos_t = torch.cos(t)
sin_t = torch.sin(t)
closest_x = a * cos_t
closest_y = b * sin_t
# Distance to closest point
dist = torch.sqrt((px - closest_x)**2 + (py - closest_y)**2)
# Sign: inside if x²/a² + y²/b² < 1
inside = (px**2 / (a**2 + 1e-8) + py**2 / (b**2 + 1e-8)) < 1
return torch.where(inside, -dist, dist)
class HyperbolaSDF(SDFPrimitive):
"""
SDF for hyperbola: x²/a² - y²/b² = 1
Uses quartic-based Newton iteration for accurate distance computation.
Reference: Paper Appendix B - Hyperbola distance computation.
Sign Convention (following standard SDF):
- NEGATIVE: Point is BETWEEN the two branches (where x²/a² - y²/b² < 1)
- POSITIVE: Point is OUTSIDE the branches (on the "open" side)
- ZERO: Point is exactly on the hyperbola boundary
The "interior" of a hyperbola is defined as the region between the two
branches - geometrically, the region where you cannot reach the curve
without crossing the other branch.
Parameters:
center: [cx, cy] - center of hyperbola
a: semi-transverse axis (distance from center to vertex)
b: semi-conjugate axis
"""
def __init__(self, center: torch.Tensor, a: torch.Tensor, b: torch.Tensor):
super().__init__()
self.center = nn.Parameter(center.clone())
self.a = nn.Parameter(a.clone())
self.b = nn.Parameter(b.clone())
def forward(self, p: torch.Tensor) -> torch.Tensor:
# Translate to hyperbola-centered coordinates
p_local = p - self.center
px = p_local[..., 0]
py = p_local[..., 1]
a = torch.abs(self.a) + 1e-8
b = torch.abs(self.b) + 1e-8
# Use the optimized quartic-based distance function
# This uses Newton iteration informed by the quartic structure
dist = hyperbola_distance_quartic(px, py, a, b)
# Sign convention:
# "Between branches" = where x²/a² - y²/b² < 1
# This is the INTERIOR (negative SDF)
# "Outside branches" = where x²/a² - y²/b² > 1
# This is the EXTERIOR (positive SDF)
hyperbola_val = px**2 / (a**2) - py**2 / (b**2)
is_between_branches = hyperbola_val < 1
# Return: negative inside (between branches), positive outside
return torch.where(is_between_branches, -dist, dist)
class ParabolaSDF(SDFPrimitive):
"""
SDF for parabola: y² = 4px (rightward opening)
or x² = 4py (upward opening)
Sign Convention for Unbounded Curve:
For right-opening parabola y² = 4px:
- NEGATIVE: Point is on the CONCAVE side (where focus is, x > 0 and y² < 4px)
This is the "interior" - the region bounded by the parabola
- POSITIVE: Point is on the CONVEX side (x < 0, or x > 0 but y² > 4px)
This is the "exterior"
- ZERO: Point is on the parabola boundary
The "interior" is defined as the concave region containing the focus.
This provides a consistent and geometrically meaningful sign convention.
Parameters:
vertex: [vx, vy] - vertex position
p: focal parameter (distance from vertex to focus)
direction: 'right', 'left', 'up', 'down'
"""
def __init__(self, vertex: torch.Tensor, p: torch.Tensor, direction: str = 'right'):
super().__init__()
self.vertex = nn.Parameter(vertex.clone())
self.p = nn.Parameter(p.clone())
self.direction = direction
def forward(self, pts: torch.Tensor) -> torch.Tensor:
# Translate to parabola-centered coordinates
p_local = pts - self.vertex
px = p_local[..., 0]
py = p_local[..., 1]
p_param = torch.abs(self.p) + 1e-6
if self.direction == 'right':
# y² = 4px, parametric: (t²/(4p), t)
return self._compute_distance_right(px, py, p_param, flip_sign=False)
elif self.direction == 'left':
# y² = -4px (flip x)
return self._compute_distance_right(-px, py, p_param, flip_sign=False)
elif self.direction == 'up':
# x² = 4py, parametric: (t, t²/(4p))
return self._compute_distance_right(py, px, p_param, flip_sign=False)
elif self.direction == 'down':
# x² = -4py
return self._compute_distance_right(-py, px, p_param, flip_sign=False)
else:
return self._compute_distance_right(px, py, p_param, flip_sign=False)
def _compute_distance_right(self, px: torch.Tensor, py: torch.Tensor,
p: torch.Tensor, flip_sign: bool = False) -> torch.Tensor:
"""
Compute signed distance to parabola y² = 4px
Sign convention:
- Negative on concave side (where y² < 4px AND x >= 0)
- Positive elsewhere
"""
# Newton iteration to find closest point
t = py.clone()
for _ in range(12): # More iterations for stability
para_x = t**2 / (4 * p)
para_y = t
dx = px - para_x
dy = py - para_y
dpara_x = t / (2 * p)
dpara_y = torch.ones_like(t)
grad = -2 * (dx * dpara_x + dy * dpara_y)
ddpara_x = 1 / (2 * p)
hess = 2 * (dpara_x**2 + dpara_y**2 - dx * ddpara_x) + 1e-8
step = grad / torch.abs(hess)
t = t - torch.clamp(step, -1.0, 1.0)
# Final closest point and distance
para_x = t**2 / (4 * p)
para_y = t
dist = torch.sqrt((px - para_x)**2 + (py - para_y)**2 + 1e-10)
# Treat the vertex as exactly on-curve to avoid tiny positive offsets
at_vertex = (torch.abs(px) < 1e-6) & (torch.abs(py) < 1e-6)
dist = torch.where(at_vertex, torch.zeros_like(dist), dist)
# Sign convention: concave side (interior) is negative
# For y² = 4px:
# - Concave side: x >= 0 AND y² < 4px (region bounded by parabola)
# - Convex side: x < 0 OR y² > 4px
on_concave_side = (px >= 0) & (py**2 < 4 * p * px)
return torch.where(on_concave_side, -dist, dist)
class LineSDF(SDFPrimitive):
"""
SDF for infinite line passing through point with direction.
f(p) = signed distance to line
"""
def __init__(self, point: torch.Tensor, direction: torch.Tensor):
super().__init__()
self.point = nn.Parameter(point.clone())
# Normalize direction
self.direction = nn.Parameter(direction / (torch.norm(direction) + 1e-8))
def forward(self, p: torch.Tensor) -> torch.Tensor:
# Vector from line point to query point
v = p - self.point
# Normal direction (perpendicular to line direction)
normal = torch.tensor([-self.direction[1], self.direction[0]], device=p.device)
# Signed distance is dot product with normal
return (v * normal).sum(dim=-1)
class LineSegmentSDF(SDFPrimitive):
"""
SDF for line segment from point a to point b.
Following paper Section 2.3
"""
def __init__(self, a: torch.Tensor, b: torch.Tensor):
super().__init__()
self.a = nn.Parameter(a.clone())
self.b = nn.Parameter(b.clone())
def forward(self, p: torch.Tensor) -> torch.Tensor:
# Direction vector
v_ab = self.b - self.a
# Vector from a to query point
v_ap = p - self.a
# Normalized projection parameter
h = (v_ap * v_ab).sum(dim=-1) / (torch.norm(v_ab)**2 + 1e-8)
# Clamp to segment bounds [0, 1]
h_clamped = torch.clamp(h, 0, 1)
# Closest point on segment
closest = self.a + h_clamped.unsqueeze(-1) * v_ab
# Distance
return torch.norm(p - closest, dim=-1)
class TriangleEdgesSDF(SDFPrimitive):
"""
SDF for triangle edges (boundary only) - union of three line segments.
Pure SDF implementation for triangle boundaries.
"""
def __init__(self, v0: torch.Tensor, v1: torch.Tensor, v2: torch.Tensor,
line_thickness: float = 0.02):
super().__init__()
self.edge0 = LineSegmentSDF(v0, v1)
self.edge1 = LineSegmentSDF(v1, v2)
self.edge2 = LineSegmentSDF(v2, v0)
self.thickness = line_thickness
def forward(self, p: torch.Tensor) -> torch.Tensor:
# Union of three edges (min of distances)
d0 = self.edge0(p)
d1 = self.edge1(p)
d2 = self.edge2(p)
return torch.min(torch.min(d0, d1), d2) - self.thickness
class TriangleFillSDF(SDFPrimitive):
"""
SDF for filled triangle region.
Negative inside, positive outside.
Pure SDF implementation for triangle fill.
"""
def __init__(self, v0: torch.Tensor, v1: torch.Tensor, v2: torch.Tensor):
super().__init__()
self.v0 = nn.Parameter(v0.clone())
self.v1 = nn.Parameter(v1.clone())
self.v2 = nn.Parameter(v2.clone())
self.edge0 = LineSegmentSDF(v0, v1)
self.edge1 = LineSegmentSDF(v1, v2)
self.edge2 = LineSegmentSDF(v2, v0)
def _sign(self, p: torch.Tensor, a: torch.Tensor, b: torch.Tensor) -> torch.Tensor:
"""Compute signed area for point-in-triangle test"""
return (p[..., 0] - a[0]) * (b[1] - a[1]) - (b[0] - a[0]) * (p[..., 1] - a[1])
def forward(self, p: torch.Tensor) -> torch.Tensor:
# Distance to boundary
d0 = self.edge0(p)
d1 = self.edge1(p)
d2 = self.edge2(p)
dist = torch.min(torch.min(d0, d1), d2)
# Inside/outside test using signed areas
s0 = self._sign(p, self.v0, self.v1)
s1 = self._sign(p, self.v1, self.v2)
s2 = self._sign(p, self.v2, self.v0)
# Inside if all same sign
inside = ((s0 >= 0) & (s1 >= 0) & (s2 >= 0)) | ((s0 <= 0) & (s1 <= 0) & (s2 <= 0))
return torch.where(inside, -dist, dist)
class RightAngleSDF(SDFPrimitive):
"""
SDF for right angle marker (two perpendicular line segments).
Pure SDF implementation for geometric annotations.
"""
def __init__(self, vertex: torch.Tensor, dir1: torch.Tensor, dir2: torch.Tensor,
size: float = 0.25, thickness: float = 0.015):
super().__init__()
# Normalize directions
dir1_norm = dir1 / (torch.norm(dir1) + 1e-8)
dir2_norm = dir2 / (torch.norm(dir2) + 1e-8)
# Corner points
p1 = vertex + dir1_norm * size
p2 = vertex + dir2_norm * size
p3 = vertex + dir1_norm * size + dir2_norm * size
self.seg1 = LineSegmentSDF(p1, p3)
self.seg2 = LineSegmentSDF(p2, p3)
self.thickness = thickness
def forward(self, p: torch.Tensor) -> torch.Tensor:
d1 = self.seg1(p)
d2 = self.seg2(p)
return torch.min(d1, d2) - self.thickness
# =============================================================================
# Constraint Functions (Following Paper Section 5)
# =============================================================================
class GeometricConstraints:
"""
Differentiable constraint functions for geometric relationships.
All constraints return a loss value that should be minimized to 0.
"""
@staticmethod
def point_on_curve(sdf: SDFPrimitive, point: torch.Tensor) -> torch.Tensor:
"""Point lies on curve: |SDF(point)| = 0"""
return torch.abs(sdf(point.unsqueeze(0))).squeeze()
@staticmethod
def distance_constraint(p1: torch.Tensor, p2: torch.Tensor, target_dist: float) -> torch.Tensor:
"""Distance between two points equals target"""
actual_dist = torch.norm(p1 - p2)
return (actual_dist - target_dist)**2
@staticmethod
def focus_constraint_ellipse(a: torch.Tensor, b: torch.Tensor, c_target: float) -> torch.Tensor:
"""Ellipse focus constraint: c = sqrt(a² - b²) for a > b"""
a_val = torch.max(a, b)
b_val = torch.min(a, b)
c_computed = torch.sqrt(torch.relu(a_val**2 - b_val**2) + 1e-8)
return (c_computed - c_target)**2
@staticmethod
def focus_constraint_hyperbola(a: torch.Tensor, b: torch.Tensor, c_target: float) -> torch.Tensor:
"""Hyperbola focus constraint: c = sqrt(a² + b²)"""
c_computed = torch.sqrt(a**2 + b**2)
return (c_computed - c_target)**2
@staticmethod
def eccentricity_ellipse(a: torch.Tensor, b: torch.Tensor, e_target: float) -> torch.Tensor:
"""Ellipse eccentricity: e = c/a = sqrt(1 - b²/a²)"""
a_val = torch.max(a, b)
b_val = torch.min(a, b)
e_computed = torch.sqrt(torch.relu(1 - (b_val/a_val)**2) + 1e-8)
return (e_computed - e_target)**2
@staticmethod
def eccentricity_hyperbola(a: torch.Tensor, b: torch.Tensor, e_target: float) -> torch.Tensor:
"""Hyperbola eccentricity: e = c/a = sqrt(1 + b²/a²)"""
e_computed = torch.sqrt(1 + (b/a)**2)
return (e_computed - e_target)**2
@staticmethod
def asymptote_slope(a: torch.Tensor, b: torch.Tensor, slope_target: float) -> torch.Tensor:
"""Hyperbola asymptote slope: y = ±(b/a)x"""
slope_computed = b / (a + 1e-8)
return (slope_computed - slope_target)**2
@staticmethod
def positive_constraint(val: torch.Tensor) -> torch.Tensor:
"""Ensure value is positive"""
return torch.relu(-val + 0.01)**2
@staticmethod
def crowd_penalty(positions: List[torch.Tensor], tau: float = 0.5) -> torch.Tensor:
"""
Prevent element collapse (Paper Section 5.3)
L_crowd = Σ_{i<j} [max(0, τ - ||x_i - x_j||)]²
"""
loss = torch.tensor(0.0, device=positions[0].device)
for i in range(len(positions)):
for j in range(i + 1, len(positions)):
dist = torch.norm(positions[i] - positions[j])
loss = loss + torch.relu(tau - dist)**2
return loss
# =============================================================================
# SDF Renderer (Following Paper Section: Zero-Level Set Visualization)
# =============================================================================
class SDFRenderer:
"""
Render geometric shapes by visualizing the zero-level set of SDFs.
The boundary of each shape is where SDF = 0.
"""
def __init__(self, resolution: int = 500, xlim: Tuple[float, float] = (-5, 5),
ylim: Tuple[float, float] = (-5, 5)):
self.resolution = resolution
self.xlim = xlim
self.ylim = ylim
# Create grid
x = torch.linspace(xlim[0], xlim[1], resolution)
y = torch.linspace(ylim[0], ylim[1], resolution)
self.xx, self.yy = torch.meshgrid(x, y, indexing='xy')
self.grid = torch.stack([self.xx, self.yy], dim=-1) # [H, W, 2]
def render_sdf_field(self, sdf: SDFPrimitive, ax, cmap='RdBu', show_field: bool = True,
field_alpha: float = 0.15):
"""
Render the SDF field and its zero-level set.
Args:
sdf: The SDF primitive to render
ax: Matplotlib axis
cmap: Colormap for the distance field
show_field: Whether to show the distance field background
field_alpha: Transparency of the field (0=invisible, 1=opaque). Default 0.15
"""
with torch.no_grad():
grid_flat = self.grid.reshape(-1, 2)
distances = sdf(grid_flat).reshape(self.resolution, self.resolution)
distances_np = distances.cpu().numpy()
if show_field and field_alpha > 0:
# Show distance field as background with reduced opacity
vmax = max(abs(distances_np.min()), abs(distances_np.max()))
vmax = min(vmax, 5) # Clamp for visualization
im = ax.imshow(distances_np.T, extent=[*self.xlim, *self.ylim],
origin='lower', cmap=cmap, vmin=-vmax, vmax=vmax, alpha=field_alpha)
# Extract zero-level set (the curve boundary)
# Note: must use .T to match imshow orientation with indexing='xy'
ax.contour(self.xx.numpy().T, self.yy.numpy().T, distances_np.T,
levels=[0], colors=['#2E86AB'], linewidths=2.5)
def render_multiple(self, sdfs: List[Tuple[SDFPrimitive, str, str]], ax,
show_field: bool = False):
"""
Render multiple SDFs with different colors.
Args:
sdfs: List of (sdf, color, label) tuples
"""
for sdf, color, label in sdfs:
with torch.no_grad():
grid_flat = self.grid.reshape(-1, 2)
distances = sdf(grid_flat).reshape(self.resolution, self.resolution)
distances_np = distances.cpu().numpy()
# Zero-level set (use .T to match grid orientation)
cs = ax.contour(self.xx.numpy().T, self.yy.numpy().T, distances_np.T,
levels=[0], colors=[color], linewidths=2.5)
def render_line_segment(self, p1: torch.Tensor, p2: torch.Tensor, ax,
color: str = '#E74C3C', thickness: float = 0.025,
label: str = None):
"""
Render a line segment using pure SDF (LineSegmentSDF).
Uses contourf to fill the region where SDF < thickness, avoiding double lines.
Args:
p1, p2: Endpoint tensors
ax: Matplotlib axis
color: Line color
thickness: Line thickness (SDF threshold)
label: Optional label for legend
"""
segment_sdf = LineSegmentSDF(p1, p2)
with torch.no_grad():
grid_flat = self.grid.reshape(-1, 2)
distances = segment_sdf(grid_flat).reshape(self.resolution, self.resolution)
distances_np = distances.cpu().numpy()
# Use contourf to fill region where distance < thickness
# This creates a single solid line instead of two parallel contour lines
# Note: use .T to match grid orientation with indexing='xy'
ax.contourf(self.xx.numpy().T, self.yy.numpy().T, distances_np.T,
levels=[-1e10, thickness], colors=[color], alpha=1.0)
if label:
ax.plot([], [], color=color, lw=3, label=label)
def render_triangle(self, v0: torch.Tensor, v1: torch.Tensor, v2: torch.Tensor, ax,
edge_color: str = '#E74C3C', fill_color: str = '#FFD700',
fill_alpha: float = 0.3, edge_thickness: float = 0.025,
edge_labels: List[str] = None):
"""
Render a triangle using pure SDF.
Edges are rendered using LineSegmentSDF (contourf), fill using TriangleFillSDF.
Args:
v0, v1, v2: Vertex tensors
ax: Matplotlib axis
edge_color: Color for all edges (or list of 3 colors)
fill_color: Fill color
fill_alpha: Fill transparency
edge_thickness: Edge line thickness (SDF threshold)
edge_labels: Optional list of 3 labels for edges
"""
# Render fill using TriangleFillSDF
fill_sdf = TriangleFillSDF(v0, v1, v2)
with torch.no_grad():
grid_flat = self.grid.reshape(-1, 2)
fill_dist = fill_sdf(grid_flat).reshape(self.resolution, self.resolution)
fill_np = fill_dist.cpu().numpy()
ax.contourf(self.xx.numpy().T, self.yy.numpy().T, fill_np.T,
levels=[-1e10, 0], colors=[fill_color], alpha=fill_alpha)
# Render edges using LineSegmentSDF (contourf for single line)
edges = [(v0, v1), (v1, v2), (v2, v0)]
colors = [edge_color] * 3 if isinstance(edge_color, str) else edge_color
labels = edge_labels if edge_labels else [None, None, None]
for (p1, p2), c, lbl in zip(edges, colors, labels):
self.render_line_segment(p1, p2, ax, color=c, thickness=edge_thickness, label=lbl)
def render_sdf_filled(self, sdf: SDFPrimitive, ax, color: str = '#FFD700',
alpha: float = 0.3):
"""
Render the interior region of an SDF (where SDF < 0).
Args:
sdf: The SDF primitive
ax: Matplotlib axis
color: Fill color
alpha: Fill transparency
"""
with torch.no_grad():
grid_flat = self.grid.reshape(-1, 2)
distances = sdf(grid_flat).reshape(self.resolution, self.resolution)
distances_np = distances.cpu().numpy()
ax.contourf(self.xx.numpy().T, self.yy.numpy().T, distances_np.T,
levels=[-1e10, 0], colors=[color], alpha=alpha)
def render_sdf_zero_level(self, sdf: SDFPrimitive, ax, color: str = '#2E86AB',
linewidth: float = 2.5, linestyle: str = '-',
label: str = None):
"""
Render only the zero-level set (SDF = 0) of an SDF.
Args:
sdf: The SDF primitive
ax: Matplotlib axis
color: Contour color
linewidth: Line width
linestyle: Line style
label: Optional label for legend
"""
with torch.no_grad():
grid_flat = self.grid.reshape(-1, 2)
distances = sdf(grid_flat).reshape(self.resolution, self.resolution)
distances_np = distances.cpu().numpy()
ax.contour(self.xx.numpy().T, self.yy.numpy().T, distances_np.T,
levels=[0], colors=[color], linewidths=linewidth, linestyles=linestyle)
if label:
ax.plot([], [], color=color, lw=linewidth, ls=linestyle, label=label)
# =============================================================================
# Geometry Optimizer (Following Paper Section 5.2)
# =============================================================================
class GeometryOptimizer:
"""
Optimize geometric parameters to satisfy constraints.
Uses gradient-based optimization with Adam.
"""
def __init__(self, lr: float = 0.05, max_steps: int = 2000,
convergence_threshold: float = 0.001):
self.lr = lr
self.max_steps = max_steps
self.threshold = convergence_threshold
def optimize(self, sdf: SDFPrimitive, constraints: List[callable],
weights: List[float] = None, verbose: bool = False) -> Dict:
"""
Optimize SDF parameters to satisfy constraints.
Args:
sdf: The SDF primitive with learnable parameters
constraints: List of constraint functions that return loss values
weights: Optional weights for each constraint
verbose: Print optimization progress
Returns:
Dictionary with optimization results
"""
if weights is None:
weights = [1.0] * len(constraints)
optimizer = torch.optim.AdamW(sdf.parameters(), lr=self.lr)
scheduler = torch.optim.lr_scheduler.CosineAnnealingLR(
optimizer, T_max=self.max_steps, eta_min=1e-6
)
history = []
for step in range(self.max_steps):
optimizer.zero_grad()
# Compute total loss
total_loss = torch.tensor(0.0)
constraint_losses = []
for constraint, weight in zip(constraints, weights):
c_loss = constraint()
constraint_losses.append(c_loss.item())
total_loss = total_loss + weight * c_loss
history.append(total_loss.item())
# Check convergence
if total_loss.item() < self.threshold:
if verbose:
print(f" Converged at step {step}, loss={total_loss.item():.6f}")
break
# Backprop and update
total_loss.backward()
# Gradient clipping for stability
torch.nn.utils.clip_grad_norm_(sdf.parameters(), max_norm=1.0)
optimizer.step()
scheduler.step()
if verbose and step % 500 == 0:
print(f" Step {step}: loss={total_loss.item():.6f}")
return {
'final_loss': total_loss.item(),
'steps': step + 1,
'converged': total_loss.item() < self.threshold,
'history': history
}
# =============================================================================
# Problem Parser
# =============================================================================
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
# =============================================================================
# Main Batch Processor
# =============================================================================
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:
"""
Lightweight validation to catch obvious incorrect outputs.
Adds validation_reasons when failed and flips success=False.
"""
if not result.get('success'):
return result
conic_type = result.get('conic_type')
fact_expr = result.get('fact_expr', problem.get('fact_expressions', ''))
coords = result.get('coords', {})
reasons = []
tol = 3e-2
# 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)
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']
if a <= 0 or b <= 0:
reasons.append('ellipse_nonpositive_axes')
ecc_target = self.parser.parse_eccentricity(fact_expr)
if ecc_target and ecc_target < 1:
ecc_calc = np.sqrt(max(0.0, 1 - (min(a, b) / max(a, b))**2))
if abs(ecc_calc - ecc_target) > 0.05:
reasons.append('ellipse_ecc_mismatch')
# Point-on-curve checks
for name, (px, py) in coords.items():
if has_point_constraint(name):
val = (px**2) / (a**2) + (py**2) / (b**2) - 1
if abs(val) > tol:
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')
if a <= 0 or b <= 0:
reasons.append('hyperbola_nonpositive_axes')
asym = self.parser.parse_asymptote_slope(fact_expr)
if asym:
if abs(b / a - asym) > 0.05:
reasons.append('hyperbola_asymptote_mismatch')
ecc_target = self.parser.parse_eccentricity(fact_expr)
if ecc_target and ecc_target > 1:
ecc_calc = np.sqrt(1 + (b / a) ** 2)
if abs(ecc_calc - ecc_target) > 0.05:
reasons.append('hyperbola_ecc_mismatch')
for name, (px, py) in coords.items():
if has_point_constraint(name):
# Use correct formula based on orientation
if orientation == 'vertical':
# y²/a² - x²/b² = 1
val = (py**2) / (a**2) - (px**2) / (b**2) - 1
else:
# x²/a² - y²/b² = 1 (horizontal, default)
val = (px**2) / (a**2) - (py**2) / (b**2) - 1
if abs(val) > tol:
reasons.append('hyperbola_point_off_curve')
break
elif conic_type == 'parabola':
p = result['params']['p']
direction = result['params'].get('direction', 'right')
if p <= 0:
reasons.append('parabola_nonpositive_p')
# value at origin should be zero for standard placement
if direction == 'right':
base_val = 0 - 4 * p * 0
elif direction == 'left':
base_val = 0 + 4 * p * 0
elif direction == 'up':
base_val = 0 - 4 * p * 0
else: # down
base_val = 0 + 4 * p * 0
if abs(base_val) > tol:
reasons.append('parabola_origin_offset')
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:
reasons.append('parabola_point_off_curve')
break
elif conic_type == 'circle':
r = result['params']['radius']
cx, cy = result['params']['center']
if r <= 0:
reasons.append('circle_nonpositive_radius')
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:
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').
"""
import re
# 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)
"""
import re
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
import re
# 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, tau=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, tau=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, tau=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
from matplotlib.lines import Line2D
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
from matplotlib.lines import Line2D
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:
from matplotlib.lines import Line2D
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: List[Dict], max_problems: int = None,
verbose: bool = False) -> List[Dict]:
"""Process a batch of problems."""
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
def main():
parser = argparse.ArgumentParser(description='SDF-Based Geometry Solver')
parser.add_argument('--input', '-i', type=str, default='test_en.json')
parser.add_argument('--output', '-o', type=str, default='sdf_output')
parser.add_argument('--max', '-m', type=int, default=None)
parser.add_argument('--verbose', '-v', action='store_true')
args = parser.parse_args()
with open(args.input, 'r', encoding='utf-8') as f:
problems = json.load(f)
print(f"Loaded {len(problems)} problems")
processor = SDFBatchProcessor(output_dir=args.output)
processor.process_batch(problems, max_problems=args.max, verbose=args.verbose)
if __name__ == "__main__":
main()
|