File size: 297,106 Bytes
2f203f5 | 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 3554 3555 3556 3557 3558 3559 3560 3561 3562 3563 3564 3565 3566 3567 3568 3569 3570 3571 3572 3573 3574 3575 3576 3577 3578 3579 3580 3581 3582 3583 3584 3585 3586 3587 3588 3589 3590 3591 3592 3593 3594 3595 3596 3597 3598 3599 3600 3601 3602 3603 3604 3605 3606 3607 3608 3609 3610 3611 3612 3613 3614 3615 3616 3617 3618 3619 3620 3621 3622 3623 3624 3625 3626 3627 3628 3629 3630 3631 3632 3633 3634 3635 3636 3637 3638 3639 3640 3641 3642 3643 3644 3645 3646 3647 3648 3649 3650 3651 3652 3653 3654 3655 3656 3657 3658 3659 3660 3661 3662 3663 3664 3665 3666 3667 3668 3669 3670 3671 3672 3673 3674 3675 3676 3677 3678 3679 3680 3681 3682 3683 3684 3685 3686 3687 3688 3689 3690 3691 3692 3693 3694 3695 3696 3697 3698 3699 3700 3701 3702 3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776 3777 3778 3779 3780 3781 3782 3783 3784 3785 3786 3787 3788 3789 3790 3791 3792 3793 3794 3795 3796 3797 3798 3799 3800 3801 3802 3803 3804 3805 3806 3807 3808 3809 3810 3811 3812 3813 3814 3815 3816 3817 3818 3819 3820 3821 3822 3823 3824 3825 3826 3827 3828 3829 3830 3831 3832 3833 3834 3835 3836 3837 3838 3839 3840 3841 3842 3843 3844 3845 3846 3847 3848 3849 3850 3851 3852 3853 3854 3855 3856 3857 3858 3859 3860 3861 3862 3863 3864 3865 3866 3867 3868 3869 3870 3871 3872 3873 3874 3875 3876 3877 3878 3879 3880 3881 3882 3883 3884 3885 3886 3887 3888 3889 3890 3891 3892 3893 3894 3895 3896 3897 3898 3899 3900 3901 3902 3903 3904 3905 3906 3907 3908 3909 3910 3911 3912 3913 3914 3915 3916 3917 3918 3919 3920 3921 3922 3923 3924 3925 3926 3927 3928 3929 3930 3931 3932 3933 3934 3935 3936 3937 3938 3939 3940 3941 3942 3943 3944 3945 3946 3947 3948 3949 3950 3951 3952 3953 3954 3955 3956 3957 3958 3959 3960 3961 3962 3963 3964 3965 3966 3967 3968 3969 3970 3971 3972 3973 3974 3975 3976 3977 3978 3979 3980 3981 3982 3983 3984 3985 3986 3987 3988 3989 3990 3991 3992 3993 3994 3995 3996 3997 3998 3999 4000 4001 4002 4003 4004 4005 4006 4007 4008 4009 4010 4011 4012 4013 4014 4015 4016 4017 4018 4019 4020 4021 4022 4023 4024 4025 4026 4027 4028 4029 4030 4031 4032 4033 4034 4035 4036 4037 4038 4039 4040 4041 4042 4043 4044 4045 4046 4047 4048 4049 4050 4051 4052 4053 4054 4055 4056 4057 4058 4059 4060 4061 4062 4063 4064 4065 4066 4067 4068 4069 4070 4071 4072 4073 4074 4075 4076 4077 4078 4079 4080 4081 4082 4083 4084 4085 4086 4087 4088 4089 4090 4091 4092 4093 4094 4095 4096 4097 4098 4099 4100 4101 4102 4103 4104 4105 4106 4107 4108 4109 4110 4111 4112 4113 4114 4115 4116 4117 4118 4119 4120 4121 4122 4123 4124 4125 4126 4127 4128 4129 4130 4131 4132 4133 4134 4135 4136 4137 4138 4139 4140 4141 4142 4143 4144 4145 4146 4147 4148 4149 4150 4151 4152 4153 4154 4155 4156 4157 4158 4159 4160 4161 4162 4163 4164 4165 4166 4167 4168 4169 4170 4171 4172 4173 4174 4175 4176 4177 4178 4179 4180 4181 4182 4183 4184 4185 4186 4187 4188 4189 4190 4191 4192 4193 4194 4195 4196 4197 4198 4199 4200 4201 4202 4203 4204 4205 4206 4207 4208 4209 4210 4211 4212 4213 4214 4215 4216 4217 4218 4219 4220 4221 4222 4223 4224 4225 4226 4227 4228 4229 4230 4231 4232 4233 4234 4235 4236 4237 4238 4239 4240 4241 4242 4243 4244 4245 4246 4247 4248 4249 4250 4251 4252 4253 4254 4255 4256 4257 4258 4259 4260 4261 4262 4263 4264 4265 4266 4267 4268 4269 4270 4271 4272 4273 4274 4275 4276 4277 4278 4279 4280 4281 4282 4283 4284 4285 4286 4287 4288 4289 4290 4291 4292 4293 4294 4295 4296 4297 4298 4299 4300 4301 4302 4303 4304 4305 4306 4307 4308 4309 4310 4311 4312 4313 4314 4315 4316 4317 4318 4319 4320 4321 4322 4323 4324 4325 4326 4327 4328 4329 4330 4331 4332 4333 4334 4335 4336 4337 4338 4339 4340 4341 4342 4343 4344 4345 4346 4347 4348 4349 4350 4351 4352 4353 4354 4355 4356 4357 4358 4359 4360 4361 4362 4363 4364 4365 4366 4367 4368 4369 4370 4371 4372 4373 4374 4375 4376 4377 4378 4379 4380 4381 4382 4383 4384 4385 4386 4387 4388 4389 4390 4391 4392 4393 4394 4395 4396 4397 4398 4399 4400 4401 4402 4403 4404 4405 4406 4407 4408 4409 4410 4411 4412 4413 4414 4415 4416 4417 4418 4419 4420 4421 4422 4423 4424 4425 4426 4427 4428 4429 4430 4431 4432 4433 4434 4435 4436 4437 4438 4439 4440 4441 4442 4443 4444 4445 4446 4447 4448 4449 4450 4451 4452 4453 4454 4455 4456 4457 4458 4459 4460 4461 4462 4463 4464 4465 4466 4467 4468 4469 4470 4471 4472 4473 4474 4475 4476 4477 4478 4479 4480 4481 4482 4483 4484 4485 4486 4487 4488 4489 4490 4491 4492 4493 4494 4495 4496 4497 4498 4499 4500 4501 4502 4503 4504 4505 4506 4507 4508 4509 4510 4511 4512 4513 4514 4515 4516 4517 4518 4519 4520 4521 4522 4523 4524 4525 4526 4527 4528 4529 4530 4531 4532 4533 4534 4535 4536 4537 4538 4539 4540 4541 4542 4543 4544 4545 4546 4547 4548 4549 4550 4551 4552 4553 4554 4555 4556 4557 4558 4559 4560 4561 4562 4563 4564 4565 4566 4567 4568 4569 4570 4571 4572 4573 4574 4575 4576 4577 4578 4579 4580 4581 4582 4583 4584 4585 4586 4587 4588 4589 4590 4591 4592 4593 4594 4595 4596 4597 4598 4599 4600 4601 4602 4603 4604 4605 4606 4607 4608 4609 4610 4611 4612 4613 4614 4615 4616 4617 4618 4619 4620 4621 4622 4623 4624 4625 4626 4627 4628 4629 4630 4631 4632 4633 4634 4635 4636 4637 4638 4639 4640 4641 4642 4643 4644 4645 4646 4647 4648 4649 4650 4651 4652 4653 4654 4655 4656 4657 4658 4659 4660 4661 4662 4663 4664 4665 4666 4667 4668 4669 4670 4671 4672 4673 4674 4675 4676 4677 4678 4679 4680 4681 4682 4683 4684 4685 4686 4687 4688 4689 4690 4691 4692 4693 4694 4695 4696 4697 4698 4699 4700 4701 4702 4703 4704 4705 4706 4707 4708 4709 4710 4711 4712 4713 4714 4715 4716 4717 4718 4719 4720 4721 4722 4723 4724 4725 4726 4727 4728 4729 4730 4731 4732 4733 4734 4735 4736 4737 4738 4739 4740 4741 4742 4743 4744 4745 4746 4747 4748 4749 4750 4751 4752 4753 4754 4755 4756 4757 4758 4759 4760 4761 4762 4763 4764 4765 4766 4767 4768 4769 4770 4771 4772 4773 4774 4775 4776 4777 4778 4779 4780 4781 4782 4783 4784 4785 4786 4787 4788 4789 4790 4791 4792 4793 4794 4795 4796 4797 4798 4799 4800 4801 4802 4803 4804 4805 4806 4807 4808 4809 4810 4811 4812 4813 4814 4815 4816 4817 4818 4819 4820 4821 4822 4823 4824 4825 4826 4827 4828 4829 4830 4831 4832 4833 4834 4835 4836 4837 4838 4839 4840 4841 4842 4843 4844 4845 4846 4847 4848 4849 4850 4851 4852 4853 4854 4855 4856 4857 4858 4859 4860 4861 4862 4863 4864 4865 4866 4867 4868 4869 4870 4871 4872 4873 4874 4875 4876 4877 4878 4879 4880 4881 4882 4883 4884 4885 4886 4887 4888 4889 4890 4891 4892 4893 4894 4895 4896 4897 4898 4899 4900 4901 4902 4903 4904 4905 4906 4907 4908 4909 4910 4911 4912 4913 4914 4915 4916 4917 4918 4919 4920 4921 4922 4923 4924 4925 4926 4927 4928 4929 4930 4931 4932 4933 4934 4935 4936 4937 4938 4939 4940 4941 4942 4943 4944 4945 4946 4947 4948 4949 4950 4951 4952 4953 4954 4955 4956 4957 4958 4959 4960 4961 4962 4963 4964 4965 4966 4967 4968 4969 4970 4971 4972 4973 4974 4975 4976 4977 4978 4979 4980 4981 4982 4983 4984 4985 4986 4987 4988 4989 4990 4991 4992 4993 4994 4995 4996 4997 4998 4999 5000 5001 5002 5003 5004 5005 5006 5007 5008 5009 5010 5011 5012 5013 5014 5015 5016 5017 5018 5019 5020 5021 5022 5023 5024 5025 5026 5027 5028 5029 5030 5031 5032 5033 5034 5035 5036 5037 5038 5039 5040 5041 5042 5043 5044 5045 5046 5047 5048 5049 5050 5051 5052 5053 5054 5055 5056 5057 5058 5059 5060 5061 5062 5063 5064 5065 5066 5067 5068 5069 5070 5071 5072 5073 5074 5075 5076 5077 5078 5079 5080 5081 5082 5083 5084 5085 5086 5087 5088 5089 5090 5091 5092 5093 5094 5095 5096 5097 5098 5099 5100 5101 5102 5103 5104 5105 5106 5107 5108 5109 5110 5111 5112 5113 5114 5115 5116 5117 5118 5119 5120 5121 5122 5123 5124 5125 5126 5127 5128 5129 5130 5131 5132 5133 5134 5135 5136 5137 5138 5139 5140 5141 5142 5143 5144 5145 5146 5147 5148 5149 5150 5151 5152 5153 5154 5155 5156 5157 5158 5159 5160 5161 5162 5163 5164 5165 5166 5167 5168 5169 5170 5171 5172 5173 5174 5175 5176 5177 5178 5179 5180 5181 5182 5183 5184 5185 5186 5187 5188 5189 5190 5191 5192 5193 5194 5195 5196 5197 5198 5199 5200 5201 5202 5203 5204 5205 5206 5207 5208 5209 5210 5211 5212 5213 5214 5215 5216 5217 5218 5219 5220 5221 5222 5223 5224 5225 5226 5227 5228 5229 5230 5231 5232 5233 5234 5235 5236 5237 5238 5239 5240 5241 5242 5243 5244 5245 5246 5247 5248 5249 5250 5251 5252 5253 5254 5255 5256 5257 5258 5259 5260 5261 5262 5263 5264 5265 5266 5267 5268 5269 5270 5271 5272 5273 5274 5275 5276 5277 5278 5279 5280 5281 5282 5283 5284 5285 5286 5287 5288 5289 5290 5291 5292 5293 5294 5295 5296 5297 5298 5299 5300 5301 5302 5303 5304 5305 5306 5307 5308 5309 5310 5311 5312 5313 5314 5315 5316 5317 5318 5319 5320 5321 5322 5323 5324 5325 5326 5327 5328 5329 5330 5331 5332 5333 5334 5335 5336 5337 5338 5339 5340 5341 5342 5343 5344 5345 5346 5347 5348 5349 5350 5351 5352 5353 5354 5355 5356 5357 5358 5359 5360 5361 5362 5363 5364 5365 5366 5367 5368 5369 5370 5371 5372 5373 5374 5375 5376 5377 5378 5379 5380 5381 5382 5383 5384 5385 5386 5387 5388 5389 5390 5391 5392 5393 5394 5395 5396 5397 5398 5399 5400 5401 5402 5403 5404 5405 5406 5407 5408 5409 5410 5411 5412 5413 5414 5415 5416 5417 5418 5419 5420 5421 5422 5423 5424 5425 5426 5427 5428 5429 5430 5431 5432 5433 5434 5435 5436 5437 5438 5439 5440 5441 5442 5443 5444 5445 5446 5447 5448 5449 5450 5451 5452 5453 5454 5455 5456 5457 5458 5459 5460 5461 5462 5463 5464 5465 5466 5467 5468 5469 5470 5471 5472 5473 5474 5475 5476 5477 5478 5479 5480 5481 5482 5483 5484 5485 5486 5487 5488 5489 5490 5491 5492 5493 5494 5495 5496 5497 5498 5499 5500 5501 5502 5503 5504 5505 5506 5507 5508 5509 5510 5511 5512 5513 5514 5515 5516 5517 5518 5519 5520 5521 5522 5523 5524 5525 5526 5527 5528 5529 5530 5531 5532 5533 5534 5535 5536 5537 5538 5539 5540 5541 5542 5543 5544 5545 5546 5547 5548 5549 5550 5551 5552 5553 5554 5555 5556 5557 5558 5559 5560 5561 5562 5563 5564 5565 5566 5567 5568 5569 5570 5571 5572 5573 5574 5575 5576 5577 5578 5579 5580 5581 5582 5583 5584 5585 5586 5587 5588 5589 5590 5591 5592 5593 5594 5595 5596 5597 5598 5599 5600 5601 5602 5603 5604 5605 5606 5607 5608 5609 5610 5611 5612 5613 5614 5615 5616 5617 5618 5619 5620 5621 5622 5623 5624 5625 5626 5627 5628 5629 5630 5631 5632 5633 5634 5635 5636 5637 5638 5639 5640 5641 5642 5643 5644 5645 5646 5647 5648 5649 5650 5651 5652 5653 5654 5655 5656 5657 5658 5659 5660 5661 5662 5663 5664 5665 5666 5667 5668 5669 5670 5671 5672 5673 5674 5675 5676 5677 5678 5679 5680 5681 5682 5683 5684 5685 5686 5687 5688 5689 5690 5691 5692 5693 5694 5695 5696 5697 5698 5699 5700 5701 5702 5703 5704 5705 5706 5707 5708 5709 5710 5711 5712 5713 5714 5715 5716 5717 5718 5719 5720 5721 5722 5723 5724 5725 5726 5727 5728 5729 5730 5731 5732 5733 5734 5735 5736 5737 5738 5739 5740 5741 5742 5743 5744 5745 5746 5747 5748 5749 5750 5751 5752 5753 5754 5755 5756 5757 5758 5759 5760 5761 5762 5763 5764 5765 5766 5767 5768 5769 5770 5771 5772 5773 5774 5775 5776 5777 5778 5779 5780 5781 5782 5783 5784 5785 5786 5787 5788 5789 5790 5791 5792 5793 5794 5795 5796 5797 5798 5799 5800 5801 5802 5803 5804 5805 5806 5807 5808 5809 5810 5811 5812 5813 5814 5815 5816 5817 5818 5819 5820 5821 5822 5823 5824 5825 5826 5827 5828 5829 5830 5831 5832 5833 5834 5835 5836 5837 5838 5839 5840 5841 5842 5843 5844 5845 5846 5847 5848 5849 5850 5851 5852 5853 5854 5855 5856 5857 5858 5859 5860 5861 5862 5863 5864 5865 5866 5867 5868 5869 5870 5871 5872 5873 5874 5875 5876 5877 5878 5879 5880 5881 5882 5883 5884 5885 5886 5887 5888 5889 5890 5891 5892 5893 5894 5895 5896 5897 5898 5899 5900 5901 5902 5903 5904 5905 5906 5907 5908 5909 5910 5911 5912 5913 5914 5915 5916 5917 5918 5919 5920 5921 5922 5923 5924 5925 5926 5927 5928 5929 5930 5931 5932 5933 5934 5935 5936 5937 5938 5939 5940 5941 5942 5943 5944 5945 5946 5947 5948 5949 5950 5951 5952 5953 5954 5955 5956 5957 5958 5959 5960 5961 5962 5963 5964 5965 5966 5967 5968 5969 5970 5971 5972 5973 5974 5975 5976 5977 5978 5979 5980 5981 5982 5983 5984 5985 5986 5987 5988 5989 5990 5991 5992 5993 5994 5995 5996 5997 5998 5999 6000 6001 6002 6003 6004 6005 6006 6007 6008 6009 6010 6011 6012 6013 6014 6015 6016 6017 6018 6019 6020 6021 6022 6023 6024 6025 6026 6027 6028 6029 6030 6031 6032 6033 6034 6035 6036 6037 6038 6039 6040 6041 6042 6043 6044 6045 6046 6047 6048 6049 6050 6051 6052 6053 6054 6055 6056 6057 6058 6059 6060 6061 6062 6063 6064 6065 6066 6067 6068 6069 6070 6071 6072 6073 6074 6075 6076 6077 6078 6079 6080 6081 6082 6083 6084 6085 6086 6087 6088 6089 6090 6091 6092 6093 6094 6095 6096 6097 6098 6099 6100 6101 6102 6103 6104 6105 6106 6107 6108 6109 6110 6111 6112 6113 6114 6115 6116 6117 6118 6119 6120 6121 6122 6123 6124 6125 6126 6127 6128 6129 6130 6131 6132 6133 6134 6135 6136 6137 6138 6139 6140 6141 6142 6143 6144 6145 6146 6147 6148 6149 6150 6151 6152 6153 6154 6155 6156 6157 6158 6159 6160 6161 6162 6163 6164 6165 6166 6167 6168 6169 6170 6171 6172 6173 6174 6175 6176 6177 6178 6179 6180 6181 6182 6183 6184 6185 6186 6187 6188 6189 6190 6191 6192 6193 6194 6195 6196 6197 6198 6199 6200 6201 6202 6203 6204 6205 6206 6207 6208 6209 6210 6211 6212 6213 6214 6215 6216 6217 6218 6219 6220 6221 6222 6223 6224 6225 6226 6227 6228 6229 6230 6231 6232 6233 6234 6235 6236 6237 6238 6239 6240 6241 6242 6243 6244 6245 6246 6247 6248 6249 6250 6251 6252 6253 6254 6255 6256 6257 6258 6259 6260 6261 6262 6263 6264 6265 6266 6267 6268 6269 6270 6271 6272 6273 6274 6275 6276 6277 6278 6279 6280 6281 6282 6283 6284 6285 6286 6287 6288 6289 6290 6291 6292 6293 6294 6295 6296 6297 6298 6299 6300 6301 6302 6303 6304 6305 6306 6307 6308 6309 6310 6311 6312 6313 6314 6315 6316 6317 6318 6319 6320 6321 6322 6323 6324 6325 6326 6327 6328 6329 6330 6331 6332 6333 6334 6335 6336 6337 6338 6339 6340 6341 6342 6343 6344 6345 6346 6347 6348 6349 6350 6351 6352 6353 6354 6355 6356 6357 6358 6359 6360 6361 6362 6363 6364 6365 6366 6367 6368 6369 6370 6371 6372 6373 6374 6375 6376 6377 6378 6379 6380 6381 6382 6383 6384 6385 6386 6387 6388 6389 6390 6391 6392 6393 6394 6395 6396 6397 6398 6399 6400 6401 6402 6403 6404 6405 6406 6407 6408 6409 6410 6411 6412 6413 6414 6415 6416 6417 6418 6419 6420 6421 6422 6423 6424 6425 6426 6427 6428 6429 6430 6431 6432 6433 6434 6435 6436 6437 6438 6439 6440 6441 6442 6443 6444 6445 6446 6447 6448 6449 6450 6451 6452 6453 6454 6455 6456 6457 6458 6459 6460 6461 6462 6463 6464 6465 6466 6467 6468 6469 6470 6471 6472 6473 6474 6475 6476 6477 6478 6479 6480 6481 6482 6483 6484 6485 6486 6487 6488 6489 6490 6491 6492 6493 6494 6495 6496 6497 6498 6499 6500 6501 6502 6503 6504 6505 6506 6507 6508 6509 6510 6511 6512 6513 6514 6515 6516 6517 6518 6519 6520 6521 6522 6523 6524 6525 6526 6527 6528 6529 6530 6531 6532 6533 6534 6535 6536 6537 6538 6539 6540 6541 6542 6543 6544 6545 6546 6547 6548 6549 6550 6551 6552 6553 6554 6555 6556 6557 6558 6559 6560 6561 6562 6563 6564 6565 6566 6567 6568 6569 6570 6571 6572 6573 6574 6575 6576 6577 6578 6579 6580 6581 6582 6583 6584 6585 6586 6587 6588 6589 6590 6591 6592 6593 6594 6595 6596 6597 6598 6599 6600 6601 6602 6603 6604 6605 6606 6607 6608 6609 6610 6611 6612 6613 6614 6615 6616 6617 6618 6619 6620 6621 6622 6623 6624 6625 6626 6627 6628 6629 6630 6631 6632 6633 6634 6635 6636 6637 6638 6639 6640 6641 6642 6643 6644 6645 6646 6647 6648 6649 6650 6651 6652 6653 6654 6655 6656 6657 6658 6659 6660 6661 6662 6663 6664 6665 6666 6667 6668 6669 6670 6671 6672 6673 6674 6675 6676 6677 6678 6679 6680 6681 6682 6683 6684 6685 6686 6687 6688 6689 6690 6691 6692 6693 6694 6695 6696 6697 6698 6699 6700 6701 6702 6703 6704 6705 6706 6707 6708 6709 6710 6711 6712 6713 6714 6715 6716 6717 6718 6719 6720 6721 6722 6723 6724 6725 6726 6727 6728 6729 6730 6731 6732 6733 6734 6735 6736 6737 6738 6739 6740 6741 6742 6743 6744 6745 6746 6747 6748 6749 6750 6751 6752 6753 6754 6755 6756 6757 6758 6759 6760 6761 6762 6763 6764 6765 6766 6767 6768 6769 6770 6771 6772 6773 6774 6775 6776 6777 6778 6779 6780 6781 6782 6783 6784 6785 6786 6787 6788 6789 6790 6791 6792 6793 6794 6795 6796 6797 6798 6799 6800 6801 6802 6803 6804 6805 6806 6807 6808 6809 6810 6811 6812 6813 6814 6815 6816 6817 6818 6819 6820 6821 6822 6823 6824 6825 6826 6827 6828 6829 6830 6831 6832 6833 6834 6835 6836 6837 6838 6839 6840 6841 6842 6843 6844 6845 6846 6847 6848 6849 6850 6851 6852 6853 6854 6855 6856 6857 6858 6859 6860 6861 6862 6863 6864 6865 6866 6867 6868 6869 6870 6871 6872 6873 6874 6875 6876 6877 6878 6879 6880 6881 6882 6883 6884 6885 6886 6887 6888 6889 6890 6891 6892 6893 6894 6895 6896 6897 6898 6899 6900 6901 6902 6903 6904 6905 6906 6907 6908 6909 6910 6911 6912 6913 6914 6915 6916 6917 6918 6919 6920 6921 6922 6923 6924 6925 6926 6927 6928 6929 6930 6931 6932 6933 6934 6935 6936 6937 6938 6939 6940 6941 6942 6943 6944 6945 6946 6947 6948 6949 6950 6951 6952 6953 6954 6955 6956 6957 6958 6959 6960 6961 6962 6963 6964 6965 6966 6967 6968 6969 6970 6971 6972 6973 6974 6975 6976 6977 6978 6979 6980 6981 6982 6983 6984 6985 6986 6987 6988 6989 6990 6991 6992 6993 6994 6995 6996 6997 6998 6999 7000 7001 7002 7003 7004 7005 7006 7007 7008 7009 7010 7011 7012 7013 7014 7015 7016 7017 7018 7019 7020 7021 7022 7023 7024 7025 7026 7027 7028 7029 7030 7031 7032 7033 7034 7035 7036 7037 7038 7039 7040 7041 7042 7043 7044 7045 7046 7047 7048 7049 7050 7051 7052 7053 7054 7055 7056 7057 7058 7059 7060 7061 7062 7063 7064 7065 7066 7067 7068 7069 7070 7071 7072 7073 7074 7075 7076 7077 7078 7079 7080 7081 7082 7083 7084 7085 7086 7087 7088 7089 7090 7091 7092 7093 7094 7095 7096 7097 7098 7099 7100 7101 7102 7103 7104 7105 7106 7107 7108 7109 7110 7111 7112 7113 7114 7115 7116 7117 7118 7119 7120 7121 7122 7123 7124 7125 7126 7127 7128 7129 7130 7131 7132 7133 7134 7135 7136 7137 7138 7139 7140 7141 7142 7143 7144 7145 7146 7147 7148 7149 7150 7151 7152 7153 7154 7155 7156 7157 7158 7159 7160 7161 7162 7163 7164 7165 7166 7167 7168 7169 7170 7171 7172 7173 7174 7175 7176 7177 7178 7179 7180 7181 7182 7183 7184 7185 7186 7187 7188 7189 7190 7191 7192 7193 7194 7195 7196 7197 7198 7199 7200 7201 7202 7203 7204 7205 7206 7207 7208 7209 7210 7211 7212 7213 7214 7215 7216 7217 7218 7219 7220 7221 7222 7223 7224 7225 7226 7227 7228 7229 7230 7231 7232 7233 7234 7235 7236 7237 7238 7239 7240 7241 7242 7243 7244 7245 7246 7247 7248 7249 7250 7251 7252 7253 7254 7255 7256 7257 7258 7259 7260 7261 7262 7263 7264 7265 7266 7267 7268 7269 7270 7271 7272 7273 7274 7275 7276 7277 7278 7279 7280 7281 7282 7283 7284 7285 7286 7287 7288 7289 7290 7291 7292 7293 7294 7295 7296 7297 7298 7299 7300 7301 7302 7303 7304 7305 7306 7307 7308 7309 7310 7311 7312 7313 7314 7315 7316 7317 7318 7319 7320 7321 7322 7323 7324 7325 7326 7327 7328 7329 7330 7331 7332 7333 7334 7335 7336 7337 7338 7339 7340 7341 7342 7343 7344 7345 7346 7347 7348 7349 7350 7351 7352 7353 7354 7355 7356 7357 7358 7359 7360 7361 7362 7363 7364 7365 7366 7367 7368 7369 7370 7371 7372 7373 7374 7375 7376 7377 7378 7379 7380 7381 7382 7383 7384 7385 7386 7387 7388 7389 7390 7391 7392 7393 7394 7395 7396 7397 7398 7399 7400 7401 7402 7403 7404 7405 7406 7407 7408 7409 7410 7411 7412 7413 7414 7415 7416 7417 7418 7419 7420 7421 7422 7423 7424 7425 7426 7427 7428 7429 7430 7431 7432 7433 7434 7435 7436 7437 7438 7439 7440 7441 7442 7443 7444 7445 7446 7447 7448 7449 7450 7451 7452 7453 7454 7455 7456 7457 7458 7459 7460 7461 7462 7463 7464 7465 7466 7467 | """
Visualization Configuration Module
Centralizes all rules, strategies, spec builders, and style tokens for the
Data360 visualization system.
Design principles:
- World Bank Data Visualization Style Guide (colors, typography, grid)
- FT Visual Vocabulary (chart-type selection by data relationship)
- All functions here are pure (no async, no I/O) β fully unit-testable
"""
from __future__ import annotations
import re
from collections import defaultdict
from dataclasses import dataclass, field
from enum import Enum
from numbers import Integral
from typing import Any, Literal
import pandas as pd
# Temporal frequency detected from TIME_PERIOD column values.
# Governs how the year column is formatted and how x-axis timeUnit/format
# is set in Vega-Lite.
TemporalFreq = Literal["annual", "quarterly", "monthly", "daily"]
# ============================================================================
# WORLD BANK COLOR PALETTE
# Source: https://worldbank.github.io/data-visualization-style-guide/colors
# ============================================================================
WB_CAT_COLORS: list[str] = [
"#34A7F2", # cat1 β blue
"#FF9800", # cat2 β orange
"#664AB6", # cat3 β purple
"#4EC2C0", # cat4 β teal
"#F3578E", # cat5 β pink
"#081079", # cat6 β navy
"#0C7C68", # cat7 β dark green
"#AA0000", # cat8 β red
"#DDDA21", # cat9 β yellow
]
WB_REGION_COLORS: dict[str, str] = {
"NAC": "#34A7F2",
"SSF": "#FF9800",
"MEA": "#664AB6",
"SAS": "#4EC2C0",
"EAS": "#F3578E",
"LCN": "#0C7C68",
"ECS": "#AA0000",
"AFW": "#DDDA21",
"AFE": "#FF9800",
"WLD": "#081079",
}
WB_GENDER_COLORS: dict[str, str] = {
"F": "#FF9800",
"M": "#664AB6",
"_T": "#4EC2C0",
"female": "#FF9800",
"male": "#664AB6",
}
WB_INCOME_COLORS: dict[str, str] = {
"HIC": "#016B6C",
"UMC": "#73AF48",
"LMC": "#DB95D7",
"LIC": "#3B4DA6",
}
WB_SEQ_GOOD: list[str] = ["#FDF6DB", "#A1CBCF", "#5D99C2", "#2868A0", "#023B6F"]
WB_SEQ_BAD: list[str] = ["#E3F6FD", "#91C5F0", "#8B8AC0", "#88506E", "#691B15"]
WB_SEQ_BLUE: list[str] = ["#E3F6FD", "#75CCEC", "#089BD4", "#0169A1", "#023B6F"]
WB_DIV_DEFAULT: list[str] = [
"#920000",
"#BD6126",
"#E3A763",
"#EFEFEF",
"#80BDE7",
"#3587C3",
"#025288",
]
WB_TEXT = "#111111"
WB_TEXT_SUBTLE = "#666666"
WB_GRID_COLOR = "#CED4DE"
WB_ZERO_COLOR = "#8A969F"
WB_REFERENCE = "#8A969F"
WB_NO_DATA = "#CED4DE"
WB_WHITE = "#FFFFFF"
WB_BACKGROUND = "#FFFFFF"
WB_FONT_FAMILY = "Noto Sans, Arial, sans-serif"
# ============================================================================
# ORDINAL SORT ORDERS FOR HIGH-DIMENSIONAL INDICATORS
# ============================================================================
KNOWN_ORDINAL_SORT_ORDERS: dict[str, list[str]] = {
"sex": ["female", "male", "_T"],
"gender": ["female", "male", "total"],
"ipc_phase": ["Minimal", "Stressed", "Crisis", "Emergency", "Famine"],
"income_group": ["Low income", "Lower middle income", "Upper middle income", "High income"],
"development_stage": ["Pre-transition", "Transition", "Post-transition"],
"age": [
"80 years old and over", "80+", "80-84", "85-89", "90-94", "95-99", "100+",
"75 to 79 years old", "75-79",
"70 to 74 years old", "70-74",
"65 to 69 years old", "65-69",
"60 to 64 years old", "60-64",
"55 to 59 years old", "55-59",
"50 to 54 years old", "50-54",
"45 to 49 years old", "45-49",
"40 to 44 years old", "40-44",
"35 to 39 years old", "35-39",
"30 to 34 years old", "30-34",
"25 to 29 years old", "25-29",
"20 to 24 years old", "20-24",
"15 to 19 years old", "15-19",
"10 to 14 years old", "10-14",
"5 to 9 years old", "5-9",
"under 5 years old", "0-4",
"under 15 years old", "15 to 64 years old", "65 years old and over"
]
}
def _get_dimension_sort_order(field_name: str, values: list[str]) -> list[str] | None:
"""Return an explicit sorting list if the field or values match a known ordinal dimension."""
normalized_field = (field_name or "").strip().lower()
if normalized_field in KNOWN_ORDINAL_SORT_ORDERS:
return KNOWN_ORDINAL_SORT_ORDERS[normalized_field]
# Check value-based matching (e.g. if the values contain IPC phases or income groups)
val_set = {str(v).strip().lower() for v in values}
for key, order in KNOWN_ORDINAL_SORT_ORDERS.items():
order_set = {str(o).strip().lower() for o in order}
if val_set.intersection(order_set) and len(val_set.intersection(order_set)) >= 2:
sorted_avail = []
for o in order:
o_norm = o.strip().lower()
matched_val = None
for val in values:
if str(val).strip().lower() == o_norm:
matched_val = val
break
if matched_val is not None:
sorted_avail.append(matched_val)
return sorted_avail
return None
# ============================================================================
# WB ALTAIR THEME CONFIG
# ============================================================================
def wb_altair_config() -> dict:
"""Return World Bank style config dict for injection into Vega-Lite specs."""
return {
"background": WB_BACKGROUND,
"font": WB_FONT_FAMILY,
"title": {
"fontSize": 16,
"fontWeight": "bold",
"color": WB_TEXT,
# AntVis component guideline: use absolute px line-height for predictable wrapping.
# ratio (1.2) causes tight stacking when title wraps to 2 lines.
"lineHeight": 22,
"anchor": "start",
"offset": 8,
"subtitleFontSize": 12,
"subtitleColor": WB_TEXT_SUBTLE,
"subtitleFontWeight": "normal",
"subtitlePadding": 4,
# Breathing room between each subtitle part (geography / unit / breakdown note).
"subtitleLineHeight": 18,
},
"axis": {
"grid": False,
"labelColor": WB_TEXT_SUBTLE,
"labelFontSize": 12,
"labelFont": WB_FONT_FAMILY,
"titleColor": WB_TEXT,
"titleFontSize": 12,
"titleFont": WB_FONT_FAMILY,
"titleFontWeight": "bold",
"gridColor": WB_GRID_COLOR,
"gridDash": [4, 2],
"gridWidth": 1,
"domainColor": WB_GRID_COLOR,
"tickColor": WB_GRID_COLOR,
"tickCount": 5,
"labelOverlap": "greedy",
},
"legend": {
"labelColor": WB_TEXT,
"labelFont": WB_FONT_FAMILY,
"labelFontSize": 12,
"labelFontWeight": "bold",
"labelLimit": 300,
"titleColor": WB_TEXT,
"titleFont": WB_FONT_FAMILY,
"titleFontSize": 12,
"orient": "top",
"direction": "horizontal",
},
"range": {"category": WB_CAT_COLORS},
"view": {"stroke": "transparent"},
"line": {"strokeWidth": 3, "strokeCap": "round"},
"point": {"size": 60, "stroke": WB_WHITE, "strokeWidth": 1},
"bar": {"cornerRadiusTopLeft": 2, "cornerRadiusTopRight": 2},
}
def _suppress_redundant_legends(node):
if isinstance(node, dict):
if "encoding" in node:
enc = node["encoding"]
if isinstance(enc, dict):
color_enc = enc.get("color")
if isinstance(color_enc, dict) and "field" in color_enc:
color_field = color_enc.get("field")
if color_field:
x_field = enc.get("x", {}).get("field") if isinstance(enc.get("x"), dict) else None
y_field = enc.get("y", {}).get("field") if isinstance(enc.get("y"), dict) else None
if color_field in (x_field, y_field):
color_enc["legend"] = None
for k, v in node.items():
_suppress_redundant_legends(v)
elif isinstance(node, list):
for item in node:
_suppress_redundant_legends(item)
def inject_wb_config(vl_spec: dict) -> dict:
"""Merge WB style config into a Vega-Lite spec without overwriting user settings."""
_suppress_redundant_legends(vl_spec)
wb_cfg = wb_altair_config()
if "config" not in vl_spec:
vl_spec["config"] = wb_cfg
else:
for section, props in wb_cfg.items():
if section not in vl_spec["config"]:
vl_spec["config"][section] = props
elif isinstance(props, dict) and isinstance(
vl_spec["config"].get(section), dict
):
for k, v in props.items():
vl_spec["config"][section].setdefault(k, v)
return vl_spec
# ============================================================================
# STRUCTURED TOOLTIPS
# ============================================================================
# ``year`` / ``time_period`` are built in ``build_structured_tooltips`` from ``viz_data``:
# marking them ``temporal`` when values are plain strings like "2018" makes Vega-Lite parse
# the field as dates for all encodings, so an ordinal x-axis shows epoch milliseconds.
_TOOLTIP_SPECS: dict[str, dict] = {
"value": {"title": "Value", "format": ",.2f", "type": "quantitative"},
"country": {"title": "Economy", "type": "nominal"},
"sex": {"title": "Sex", "type": "nominal"},
"age": {"title": "Age Group", "type": "nominal"},
"urbanisation": {"title": "Urbanisation", "type": "nominal"},
"residence": {"title": "Residence", "type": "nominal"},
"comp_breakdown_1": {"title": "Dimension 1", "type": "nominal"},
"comp_breakdown_2": {"title": "Dimension 2", "type": "nominal"},
"comp_breakdown_3": {"title": "Dimension 3", "type": "nominal"},
"time_period": {"title": "Period", "type": "temporal"},
"obs_value": {"title": "Value", "format": ",.2f", "type": "quantitative"},
"ref_area": {"title": "Economy", "type": "nominal"},
"region": {"title": "Region", "type": "nominal"},
}
_TOOLTIP_PRIORITY = [
"year",
"time_period",
"value",
"obs_value",
"country",
"ref_area",
"region",
"sex",
"age",
"urbanisation",
"residence",
"comp_breakdown_1",
"comp_breakdown_2",
]
_VOWELS = {"a", "e", "i", "o", "u"}
def _year_range_label(year_series: pd.Series) -> str | None:
"""Minβmax year label, e.g. ``1990-2024`` or ``2020`` when only one year."""
if year_series.empty:
return None
try:
if pd.api.types.is_datetime64_any_dtype(year_series):
ynum = year_series.dt.year
else:
ynum = pd.to_numeric(year_series, errors="coerce")
yvalid = ynum.dropna()
if yvalid.empty:
return None
y0, y1 = int(yvalid.min()), int(yvalid.max())
return f"{y0}-{y1}" if y0 != y1 else str(y0)
except (TypeError, ValueError):
return None
def format_chart_context_subtitle(df: pd.DataFrame) -> str | None:
"""Build geography list + year range for chart subtitle (product-style).
Example: ``\"Philippines, Belgium, 1990-2024\"``. Long geography lists are truncated.
"""
parts: list[str] = []
if "country" in df.columns:
vals = sorted(
{str(v).strip() for v in df["country"].dropna() if str(v).strip()},
key=str.casefold,
)
if vals:
if len(vals) <= 3:
parts.append(", ".join(vals))
year_lbl = None
if "year" in df.columns:
year_lbl = _year_range_label(df["year"])
if year_lbl:
parts.append(year_lbl)
if not parts:
return None
return ", ".join(parts)
def build_chart_title_with_context(
main_title: str | list[str] | dict,
unit_subtitle: str | None,
df: pd.DataFrame,
) -> str | dict | list:
"""Vega-Lite title: main text plus subtitle lines (geography + years, unit).
Subtitle is returned as a **list of strings** so Vega-Lite v5 renders each
part on its own line. This prevents the single-line overflow that occurs
when country names, year ranges, units, and trim notes are concatenated.
"""
if isinstance(main_title, str) and main_title.strip().startswith("{"):
try:
import json
main_title = json.loads(main_title)
except Exception:
pass
if isinstance(main_title, dict):
return main_title
ctx = format_chart_context_subtitle(df)
subtitle_parts: list[str] = []
if ctx:
subtitle_parts.append(ctx)
if unit_subtitle and str(unit_subtitle).strip():
subtitle_parts.append(str(unit_subtitle).strip())
if not subtitle_parts:
return main_title
return {"text": main_title, "subtitle": subtitle_parts}
def _clean_label_generic(label: str) -> str:
"""Generically cleans long indicator/dimension labels by stripping trailing parentheticals."""
if not label or not isinstance(label, str):
return label
s = label.strip()
# Strip up to 2 trailing parentheticals if they contain metadata or unit info
for _ in range(2):
if s.endswith(")"):
idx = s.rfind("(")
if idx != -1:
content = s[idx+1:-1].lower()
# Strip if it contains common metadata/unit keywords or is long
strip_keywords = {"estimate", "modeled", "ilo", "gdp", "%", "percent", "constant", "current", "low to", "base", "index"}
if any(kw in content for kw in strip_keywords) or len(content) > 10:
s = s[:idx].strip()
else:
break
else:
break
else:
break
return s
def _clean_unit_label(label: str) -> str:
"""Returns a short, clean unit label suitable for axis titles."""
if not label:
return "Value"
l = label.lower()
if "(" in label or "per" in l or "/" in label:
return label.strip()
if "percent" in l or "percentage" in l or "%" in l:
if "gdp" in l:
return "% of GDP"
return "%" if label == "%" else "Percentage"
if "index" in l or "score" in l:
return "Index"
if "usd" in l or "us$" in l or "dollar" in l:
if "constant" in l or "current" in l:
return label.strip()
return "USD"
if "share" in l or "proportion" in l or "ratio" in l:
return "Share"
if "estimate" in l:
return "Estimate"
if "co2" in l or "greenhouse" in l:
return "Tonnes CO2-eq"
return label.strip()
# Dimension codes that are custom breakdowns (not standard demographic dims).
_CUSTOM_BREAKDOWN_DIMS = {"comp_breakdown_1", "comp_breakdown_2", "comp_breakdown_3"}
def _generate_color_shades(hex_color: str, n: int) -> list[str]:
"""Return n shades of hex_color spread from dark to light (HSL lightness).
n=1 β returns the base color unchanged.
n=2 β [dark, base] (darker shade + original).
n=3 β [dark, base, light].
n>3 β evenly distributed from 0.28 L to 0.75 L.
"""
import colorsys
if n <= 0:
return []
if n == 1:
return [hex_color]
h_str = hex_color.lstrip("#")
r, g, b = (int(h_str[i : i + 2], 16) / 255.0 for i in (0, 2, 4))
h, _l, s = colorsys.rgb_to_hls(r, g, b)
shades: list[str] = []
for i in range(n):
factor = i / (n - 1)
new_l = 0.28 + factor * 0.47 # 0.28 (dark) β 0.75 (light)
nr, ng, nb = colorsys.hls_to_rgb(h, new_l, min(s, 0.90))
shades.append(f"#{int(nr * 255):02x}{int(ng * 255):02x}{int(nb * 255):02x}")
return shades
def _compute_legend_layout(labels: list[str], chart_width: int = 680) -> dict:
"""Compute Vega-Lite legend config (orient/direction/columns/labelLimit) from data.
Uses the number of items, their rendered pixel width, and the chart width to
determine whether the legend fits in one horizontal row, needs multiple rows
(grid), or must fall back to a vertical list.
Approximate rendered width per item at 11 px font:
6.5 px/char Γ label_length + symbol (20 px) + padding (16 px)
"""
import math
n = len(labels)
if n == 0:
return {"orient": "bottom", "labelFontSize": 11, "symbolSize": 80}
max_lbl = max(len(l) for l in labels)
item_px = int(max_lbl * 6.5 + 36) # estimated rendered width per item
items_per_row = max(1, chart_width // item_px)
base = {"labelFontSize": 11, "symbolSize": 80}
if n <= items_per_row:
# Everything fits in one row β horizontal, single row
return {**base, "orient": "bottom", "direction": "horizontal",
"labelLimit": max(150, item_px - 36)}
if items_per_row >= 2:
# Multi-row grid β aim for β€3 rows to keep legend compact
cols = min(items_per_row, max(2, math.ceil(n / 3)))
return {**base, "orient": "bottom", "direction": "horizontal",
"columns": cols, "labelLimit": max(150, item_px - 36)}
# Labels too long for horizontal β vertical list
return {**base, "orient": "bottom", "direction": "vertical", "labelLimit": 0}
def _estimate_legend_height(
n_items: int,
layout: dict,
has_title: bool = True,
) -> int:
"""Estimate legend pixel height from the layout dict returned by _compute_legend_layout.
Used to shrink panel heights so the total figure height stays within budget.
"""
import math
direction = layout.get("direction", "vertical")
columns = layout.get("columns", 0)
row_px = 22 # height per legend row (symbol + label + vertical gap)
title_px = 20 if has_title else 0
padding = 16 # top + bottom padding inside the legend box
if direction == "horizontal" and columns:
rows = math.ceil(n_items / columns)
elif direction == "horizontal":
rows = 1
else:
rows = n_items
return title_px + rows * row_px + padding
def _detect_scale_incompatibility(
df: pd.DataFrame,
breakdown_dim: str,
magnitude_threshold: float = 1.5,
) -> bool:
"""Return True when breakdown series have incompatible Y-axis scales.
Computes the order of magnitude (log10 of max |value|) for each
breakdown series. If the spread between the largest and smallest
magnitudes exceeds *magnitude_threshold*, the series cannot share a
Y-axis without visually compressing the small-magnitude series.
A threshold of 1.5 corresponds to roughly a 30Γ difference between
the dominant series and the smallest (e.g., a WGI percentile rank
peaking at ~65 vs. a standard error peaking at ~0.2).
Only meaningful for *_CUSTOM_BREAKDOWN_DIMS*; standard demographic
dims (sex, age) almost always share a unit and should never fire.
Returns False when:
- breakdown_dim is not in df.columns or 'value' is missing
- fewer than 2 unique breakdown values are present
- all series are zero or NaN (no meaningful magnitudes to compare)
Examples::
WGI: EST max|val|β0.6 (magβ-0.22), SC max|val|β65 (magβ1.81)
spread = 1.81 β (β0.22) = 2.03 β True (exceeds 1.5)
IPC phases: all person counts, max|val|β[1000, 5000]
mags β [3.0, 3.5, 3.7], spread = 0.7 β False
"""
import math
if breakdown_dim not in df.columns or "value" not in df.columns:
return False
bd_vals = df[breakdown_dim].dropna().unique()
if len(bd_vals) < 2:
return False
mags: list[float] = []
for v in bd_vals:
series_vals = df.loc[df[breakdown_dim] == v, "value"].dropna()
if series_vals.empty:
continue
max_abs = float(series_vals.abs().max())
if max_abs == 0:
mags.append(0.0)
else:
mags.append(math.log10(max_abs))
if len(mags) < 2:
return False
return (max(mags) - min(mags)) >= magnitude_threshold
def _format_breakdown_subtitle(df: pd.DataFrame, color_dim: str | None) -> str | None:
"""Return a compact subtitle note when color_dim is a heterogeneous custom breakdown.
Appended to chart subtitles so end users can see which series are present
and understand they may carry different units or scales.
Returns None when:
- color_dim is a standard dimension (country, sex, age, β¦)
- there is only one unique breakdown value
- series share a compatible scale (log10 magnitude spread β€ 1.5) β the
unit warning is suppressed because _detect_scale_incompatibility returns
False. This correctly handles summary-measure breakdowns such as
"Arithmetic mean" vs "Median" which share the same currency unit.
"""
if color_dim not in _CUSTOM_BREAKDOWN_DIMS:
return None
if color_dim not in df.columns:
return None
vals = sorted(str(v) for v in df[color_dim].dropna().unique())
if len(vals) <= 1:
return None
series_list = ", ".join(vals)
# Use the quantitative check (log10 magnitude spread) instead of the
# trailing-digit string heuristic. This avoids false positives for
# human-readable labels that happen not to end in a digit.
if _detect_scale_incompatibility(df, color_dim):
return f"Series: {series_list} β series may have different units/scales"
return f"Series: {series_list}"
def _append_breakdown_note(
title: str | dict,
df: pd.DataFrame,
color_dim: str | None,
) -> str | dict:
"""Inject breakdown note into a Vega-Lite title dict's subtitle.
When subtitle is a list (Vega-Lite multi-line form), the note is appended
as a new line. When subtitle is a string, it is appended with ' Β· '.
"""
note = _format_breakdown_subtitle(df, color_dim)
if not note:
return title
if isinstance(title, dict):
existing = title.get("subtitle", "")
if isinstance(existing, list):
return {**title, "subtitle": existing + [note]}
new_sub = f"{existing} Β· {note}" if existing else note
return {**title, "subtitle": new_sub}
# Plain string title β upgrade to single-line dict.
return {"text": title, "subtitle": note}
def _cap_cardinality(
df: pd.DataFrame,
dim: str,
max_n: int,
) -> tuple[pd.DataFrame, int | None]:
"""Cap the number of unique values for *dim* to *max_n*.
Shared utility called by every spec builder that renders one visual element
per dim value (facet panels, bar rows, color lines). This is standard
chart best practice: beyond ~8β12 elements embedded charts overflow the
chatbot UI and individual items become unreadable.
Selection strategy: top-N by most-recent data point, ties broken by row
count (more data = more informative panel). Rows outside the top-N are
dropped from the returned DataFrame.
Args:
df: Input DataFrame. Must have a ``year`` column for recency sort.
dim: Dimension column whose cardinality to cap (e.g. ``country``).
max_n: Maximum number of unique values to retain.
Returns:
(trimmed_df, original_n) where *original_n* is the pre-trim count, or
*None* when no trimming was needed (df is returned unchanged).
"""
if dim not in df.columns:
return df, None
n_total = df[dim].nunique()
if n_total <= max_n:
return df, None
if "year" in df.columns:
latest = df.groupby(dim)["year"].max()
else:
latest = pd.Series(dtype="object", index=df[dim].unique())
count = df.groupby(dim).size()
rank = pd.DataFrame(
{"latest": latest.reindex(count.index).fillna(pd.Timestamp.min), "count": count}
)
top = (
rank.sort_values(["latest", "count"], ascending=False)
.head(max_n)
.index.tolist()
)
return df[df[dim].isin(top)].copy(), n_total
def _append_trim_note(
title: str | dict,
dim_label: str,
shown: int,
original: int | None,
) -> str | dict:
"""Inject a 'Showing N of M' note into the chart subtitle when cardinality
was capped by :func:`_cap_cardinality`.
No-op when *original* is None (no trimming occurred).
When subtitle is a list (Vega-Lite multi-line form), the note is appended
as a new line. When subtitle is a string, it is appended with ' Β· '.
"""
if original is None:
return title
dim_title = (
_TOOLTIP_SPECS.get(dim_label, {}).get("title")
or dim_label.replace("_", " ")
).strip().lower()
# comp_breakdown_* fields use generic "Dimension N" labels in _TOOLTIP_SPECS;
# for trim notes, the user-facing term should be "breakdown" instead.
if dim_label.startswith("comp_breakdown_"):
dim_title = "breakdown"
# Simple English pluralization for subtitle notes.
if dim_title.endswith("y") and len(dim_title) > 2 and dim_title[-2] not in _VOWELS:
dim_plural = f"{dim_title[:-1]}ies"
elif dim_title.endswith(("s", "x", "z", "ch", "sh")):
dim_plural = f"{dim_title}es"
else:
dim_plural = f"{dim_title}s"
note = (
f"Showing {shown} of {original} {dim_plural} by most recent data β "
"specify a subset for the full view"
)
if isinstance(title, dict):
existing = title.get("subtitle", "")
if isinstance(existing, list):
return {**title, "subtitle": existing + [note]}
return {**title, "subtitle": f"{existing} Β· {note}" if existing else note}
return {"text": title, "subtitle": note}
# Shared dimensions for multi-indicator line layers: one value column per layerβs tooltip.
_MULTI_IND_TOOLTIP_DIMS: tuple[str, ...] = (
"year",
"time_period",
"country",
"ref_area",
"region",
"sex",
"age",
"urbanisation",
"residence",
)
# Visible points widen the Vega hit target for line tooltips without a spec API change.
_LINE_HOVER_POINT: dict[str, object] = {"filled": True, "size": 56}
def _multi_indicator_tooltip_columns(
df_columns: list[str], value_col: str
) -> list[str]:
colset = set(df_columns)
out: list[str] = []
for c in _MULTI_IND_TOOLTIP_DIMS:
if c in colset:
out.append(c)
if value_col in colset and value_col not in out:
out.append(value_col)
return out
def _tooltip_spec_for_time_dim(
col: str,
viz_data: pd.DataFrame | None,
temporal_freq: TemporalFreq | None = None,
) -> dict:
"""Return a Vega-Lite tooltip spec for year/time_period columns.
When a temporal frequency is known (or can be detected from the values),
the spec uses ``type: temporal`` with the correct timeUnit + format so that
Vega-Lite formats the internally-parsed epoch timestamp correctly. Without
this, charts with a temporal X-axis display the raw millisecond number
(e.g. 1596240000000) instead of a human-readable date string.
"""
title = "Year" if col == "year" else "Period"
# Mapping that mirrors _TEMPORAL_X_ENCODING so tooltip labels match axis labels.
_FREQ_TOOLTIP: dict[str, dict] = {
"annual": {"timeUnit": "utcyear", "format": "%Y"},
"monthly": {"timeUnit": "utcyearmonth", "format": "%b %Y"},
"quarterly": {"timeUnit": "utcyearquarter", "format": "Q%q %Y"},
"daily": {"timeUnit": "utcyearmonthdate", "format": "%Y-%m-%d"},
}
# If the time column contains only 1 unique value, return nominal type
# to prevent Vega-Lite from auto-parsing the field as a Date object.
if viz_data is not None and col in viz_data.columns and viz_data[col].nunique() <= 1:
return {"field": col, "title": title, "type": "nominal"}
freq: TemporalFreq | None = temporal_freq
if freq is None and viz_data is not None and col in viz_data.columns:
# Infer from the formatted string values already in the frame.
freq = _detect_temporal_frequency(viz_data[col])
if freq is not None:
cfg = _FREQ_TOOLTIP.get(freq, _FREQ_TOOLTIP["annual"])
return {
"field": col,
"title": title,
"type": "temporal",
"timeUnit": cfg["timeUnit"],
"format": cfg["format"],
}
return {"field": col, "title": title, "type": "nominal"}
def build_structured_tooltips(
columns: list[str],
mark_type: str,
indicator_labels: dict[str, str] | None = None,
value_format: str = ",.2f",
viz_data: pd.DataFrame | None = None,
temporal_freq: TemporalFreq | None = None,
dim_name_labels: dict[str, str] | None = None,
indicator_name: str | None = None,
) -> list[dict]:
"""Build typed, labelled tooltip list for a Vega-Lite encoding.
indicator_labels: optional {col_name: human_label} for indicator value columns
in multi-indicator charts (e.g. {"gdp_per_capita": "GDP per capita (USD)"}).
value_format: D3 format string for quantitative value fields.
viz_data: when set, ``year`` / ``time_period`` frequency is detected from the
column values to produce correctly formatted temporal tooltip labels.
temporal_freq: explicit temporal frequency; overrides auto-detection from
viz_data. Pass ``result.temporal_frequency`` from temporal chart builders
so the tooltip date format matches the X-axis format exactly.
dim_name_labels: optional {col_name: human_label} for comp_breakdown_* columns
sourced from the disaggregation API. Overrides the generic "Dimension N"
fallback in ``_TOOLTIP_SPECS`` for those fields.
indicator_name: human-readable indicator title. When provided, appended as a
constant tooltip entry (``{"value": indicator_name, "title": "Indicator"}``)
so hovering always shows which indicator is displayed.
"""
ordered = [c for c in _TOOLTIP_PRIORITY if c in columns]
ordered += [c for c in columns if c not in _TOOLTIP_PRIORITY and not c.startswith("_")]
tooltips = []
for col in ordered:
if col in ("year", "time_period"):
tooltips.append(_tooltip_spec_for_time_dim(col, viz_data, temporal_freq))
continue
if dim_name_labels and col in dim_name_labels:
title = dim_name_labels[col]
col_type = "quantitative" if "value" in col.lower() else "nominal"
tip = {"field": col, "title": title, "type": col_type}
if col_type == "quantitative":
tip["format"] = value_format
elif indicator_labels and col in indicator_labels:
tip = {
"field": col,
"title": indicator_labels[col],
"format": value_format,
"type": "quantitative",
}
elif col in _TOOLTIP_SPECS:
spec = _TOOLTIP_SPECS[col]
# Use the API-sourced dimension name when available, otherwise the
# generic "Dimension N" fallback from _TOOLTIP_SPECS.
title = (
dim_name_labels.get(col)
if (dim_name_labels and col in dim_name_labels)
else spec["title"]
)
tip = {"field": col, "title": title, "type": spec["type"]}
if "format" in spec:
# Use value_format for quantitative value fields
if col in ("value", "obs_value"):
tip["format"] = value_format
else:
tip["format"] = spec["format"]
else:
tip = {"field": col, "title": col.replace("_", " ").title()}
tooltips.append(tip)
# Append the indicator name as a constant tooltip entry when provided.
# Vega-Lite supports {"value": <literal>} in the tooltip array to display
# static text alongside dynamic field values.
if indicator_name:
tooltips.append({"value": indicator_name, "title": "Indicator"})
return tooltips
def apply_structured_tooltips(
vl_spec: dict,
columns: list[str],
mark_type: str,
indicator_labels: dict[str, str] | None = None,
viz_data: pd.DataFrame | None = None,
) -> dict:
tips = build_structured_tooltips(
columns, mark_type, indicator_labels, viz_data=viz_data
)
vl_spec.setdefault("encoding", {})["tooltip"] = tips
return vl_spec
# ============================================================================
# CHART STRATEGY ROUTER (FT Visual Vocabulary aligned)
# ============================================================================
class ChartStrategy(str, Enum):
"""Named chart strategies mapped to FT Visual Vocabulary categories."""
TEMPORAL_SINGLE = "temporal_single" # 1 indicator, β€8 countries, multi-year β lines
TEMPORAL_MULTI_IND = (
"temporal_multi_indicator" # 2-4 indicators β layered lines (dual Y + offsets)
)
CORRELATION = "correlation" # 2 indicators, multi-country, 1 year β scatter
CORRELATION_TEMPORAL = "correlation_temporal" # 2 indicators, multi-country, multi-year β connected scatter
CROSS_SECTIONAL = (
"cross_sectional" # 1 indicator, β€8 countries, 1 year β horizontal bar
)
DISTRIBUTION = "distribution" # 1 indicator, >8 countries, 1 year β strip/beeswarm
BREAKDOWN_COMPARISON = (
"breakdown_comparison" # 1 indicator, 1 disagg, 2-4 values β grouped bar
)
SMALL_MULTIPLES = (
"small_multiples" # 1 indicator, 2+ disagg or >4 cntry+breakdown β facet
)
HEATMAP = "heatmap" # dense country x year matrix
STACKED_AREA = "stacked_area" # part-to-whole over time
STACKED_BAR = "stacked_bar" # part-to-whole snapshot/bar
CHOROPLETH = "choropleth" # geographic map
FALLBACK_LINE = "fallback_line" # anything else
@dataclass
class StrategyResult:
strategy: ChartStrategy
reason: str
# Enriched context the spec builder needs
indicator_cols: list[str] = field(
default_factory=list
) # value columns for multi-indicator
color_dim: str | None = None
facet_dim: str | None = None
# Secondary color dimension for 3-way combo encoding:
# When both color_dim and secondary_color_dim are set, the spec builder
# creates a combo color field = color_dim_value + ' / ' + secondary_color_dim_value
# using shade families (e.g. IPC phases Γ countries: 5 shades per country).
secondary_color_dim: str | None = None
x_dim: str | None = None
y_dim: str | None = None
scale_incompatible: bool = False # breakdown series need independent Y-axes
temporal_frequency: TemporalFreq = "annual" # detected from time_period values
# Multi-indicator scale compatibility computed from real data
scale_compatibility: dict | None = None
# Human-readable names for comp_breakdown_* columns sourced from the
# disaggregation API label_name field; used for legend/tooltip titles.
dim_name_labels: dict[str, str] = field(default_factory=dict)
# Carries the user's mark preference ("bar", "line", etc.) from select_strategy
# to the spec builder, so builders can switch mark type without re-routing.
mark_hint: str | None = None
scale_type: str | None = None
unit_mult: int = 0
raw_hint: str | None = None
# Full data profile computed before routing; returned in tool responses
data_profile: dict | None = None
refusal_reason: str | None = None
from typing import Protocol
@dataclass
class RoutingContext:
df: pd.DataFrame
n_indicators: int
hint: str | None
raw_hint: str | None
ind_cols: list[str]
# Pre-computed metrics
year_count: int
country_count: int
breakdown_counts: dict[str, int]
n_breakdowns: int
max_years_per_country: int = 1
avg_years_per_country: float = 0.0
scale_type: str | None = None
unit_mult: int = 0
skewness: float = 0.0
# Per-indicator value ranges computed from real data (multi-indicator only)
indicator_value_ranges: dict[str, dict[str, float]] = field(default_factory=dict)
# Coverage quality signals from data profile (set when data_profile is passed to select_strategy)
sparse_country_count: int = 0
completeness_pct: float = 100.0
same_unit: bool = True
can_share_axis: bool = True
refusal_reason: str | None = None
def register_refusal(self, hint: str, reason: str):
self.refusal_reason = f"Cannot honor requested '{hint}': {reason}"
@classmethod
def build(
cls,
df: pd.DataFrame,
n_indicators: int,
chart_type_hint: str | None,
indicator_cols: list[str] | None,
raw_unit: str | None = None,
raw_unit_mult: int = 0,
) -> RoutingContext:
hint = parse_chart_type_hint(chart_type_hint)
cols = set(df.columns)
year_count = df["year"].nunique() if "year" in cols else 0
country_count = df["country"].nunique() if "country" in cols else 0
max_years_per_country = 1
avg_years_per_country = 0.0
if country_count > 0 and "country" in cols and "year" in cols and not df.empty:
try:
max_years_per_country = int(df.groupby("country")["year"].nunique().max())
avg_years_per_country = float(df.groupby("country")["year"].nunique().mean())
except Exception:
pass
sex_count = df["sex"].nunique() if "sex" in cols else 0
age_count = df["age"].nunique() if "age" in cols else 0
urban_count = df["urbanisation"].nunique() if "urbanisation" in cols else 0
residence_count = df["residence"].nunique() if "residence" in cols else 0
cb1_count = df["comp_breakdown_1"].nunique() if "comp_breakdown_1" in cols else 0
cb2_count = df["comp_breakdown_2"].nunique() if "comp_breakdown_2" in cols else 0
cb3_count = df["comp_breakdown_3"].nunique() if "comp_breakdown_3" in cols else 0
unit_count = df["unit_measure"].nunique() if "unit_measure" in cols else 0
# Identify statistical error band breakdowns to exclude them from routing disaggregation counts
# BUT only if country_count <= 1. If we have multiple countries, we route to small multiples
# to avoid overlapping confidence interval bands in a single plot.
err_band_dims = set()
if country_count <= 1:
for col_name in ("comp_breakdown_1", "comp_breakdown_2", "comp_breakdown_3"):
if col_name in cols:
unique_vals = [str(x).lower().strip() for x in df[col_name].dropna().unique()]
if unique_vals:
is_err = True
for val in unique_vals:
is_val_err = False
if "estimate" in val:
is_val_err = True
elif val == "est" or val.startswith("est ") or val.endswith(" est") or " est " in val:
is_val_err = True
elif "standard error" in val or "std error" in val or "std. error" in val:
is_val_err = True
elif val in ("stderr", "std_err", "std.err", "std. err", "s.e."):
is_val_err = True
elif val == "se" or val.startswith("se ") or val.endswith(" se") or " se " in val:
is_val_err = True
if not is_val_err:
is_err = False
break
if is_err:
err_band_dims.add(col_name)
breakdown_counts = {
k: v
for k, v in [
("sex", sex_count),
("age", age_count),
("urbanisation", urban_count),
("residence", residence_count),
("comp_breakdown_1", cb1_count if "comp_breakdown_1" not in err_band_dims else 0),
("comp_breakdown_2", cb2_count if "comp_breakdown_2" not in err_band_dims else 0),
("comp_breakdown_3", cb3_count if "comp_breakdown_3" not in err_band_dims else 0),
("unit_measure", unit_count),
]
if v > 1
}
# Derive scale type
normalized = (raw_unit or "").upper().strip()
if "$" in normalized or "USD" in normalized or "CURRENCY" in normalized or "DOLLARS" in normalized:
scale_type = "currency"
elif normalized == "PS" or "PEOPLE" in normalized or "PERSONS" in normalized or "COUNT" in normalized or "HEADCOUNT" in normalized or "PERSON" in normalized:
scale_type = "persons"
elif "%" in normalized or "PERCENT" in normalized or "RATE" in normalized or "SHARE" in normalized or "PROPORTION" in normalized:
scale_type = "percentage"
else:
scale_type = "index"
# Multiplier
unit_mult = raw_unit_mult
if "unit_mult" in df.columns:
_mults = df["unit_mult"].dropna().unique()
if len(_mults) == 1:
try:
unit_mult = int(_mults[0])
except (ValueError, TypeError):
pass
# Skewness
skewness = 0.0
if "value" in df.columns:
val_series = pd.to_numeric(df["value"], errors="coerce").dropna()
if not val_series.empty:
skew = val_series.skew()
skewness = float(skew) if not pd.isna(skew) else 0.0
# Per-indicator value ranges from real wide-format columns
indicator_value_ranges: dict[str, dict[str, float]] = {}
if indicator_cols:
for col in indicator_cols:
if col in df.columns:
series = pd.to_numeric(df[col], errors="coerce").dropna()
if not series.empty:
indicator_value_ranges[col] = {
"min": float(series.min()),
"max": float(series.max()),
}
return cls(
df=df,
n_indicators=n_indicators,
hint=hint,
raw_hint=chart_type_hint,
ind_cols=indicator_cols or [],
year_count=year_count,
country_count=country_count,
max_years_per_country=max_years_per_country,
avg_years_per_country=avg_years_per_country,
breakdown_counts=breakdown_counts,
n_breakdowns=len(breakdown_counts),
scale_type=scale_type,
unit_mult=unit_mult,
skewness=skewness,
indicator_value_ranges=indicator_value_ranges,
)
class RoutingRule(Protocol):
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None: ...
class ExplicitScatterRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.hint in ("point", "scatter", "connected_scatter") and ctx.n_indicators == 2 and len(ctx.ind_cols) == 2:
if ctx.year_count > 1:
return StrategyResult(
ChartStrategy.CORRELATION_TEMPORAL,
"User requested scatter; 2 indicators, multi-year β connected scatter",
indicator_cols=ctx.ind_cols,
color_dim="country" if ctx.country_count > 0 else None,
)
return StrategyResult(
ChartStrategy.CORRELATION,
"User requested scatter; 2 indicators, single year β scatterplot",
indicator_cols=ctx.ind_cols,
color_dim="country" if ctx.country_count > 0 else None,
)
return None
class ExplicitStackedAreaMultiIndicatorRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.hint in ("area", "stacked_area") and ctx.n_indicators >= 2 and len(ctx.ind_cols) >= 2:
if not (ctx.same_unit and ctx.can_share_axis):
ctx.register_refusal(ctx.hint, "Indicators represent different units or incompatible scales")
return None
if ctx.year_count <= 1:
ctx.register_refusal(ctx.hint, "Area charts require multiple years of data")
return None
return StrategyResult(
ChartStrategy.STACKED_AREA,
f"User requested stacked area; {ctx.n_indicators} indicators, {ctx.year_count} years β stacked area chart",
indicator_cols=ctx.ind_cols,
color_dim="indicator",
)
return None
class ExplicitStackedBarRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.hint in ("stacked_bar", "bar"):
if ctx.n_indicators >= 2 and len(ctx.ind_cols) >= 2:
if not (ctx.same_unit and ctx.can_share_axis):
ctx.register_refusal(ctx.hint, "Indicators represent different units or incompatible scales")
return None
return StrategyResult(
ChartStrategy.STACKED_BAR,
f"User requested stacked bar; {ctx.n_indicators} indicators β stacked bar chart",
indicator_cols=ctx.ind_cols,
color_dim="indicator",
)
elif ctx.n_breakdowns == 1:
color_dim = list(ctx.breakdown_counts.keys())[0]
return StrategyResult(
ChartStrategy.STACKED_BAR,
f"User requested stacked bar; 1 breakdown ({color_dim}) β stacked bar chart",
color_dim=color_dim,
)
elif ctx.country_count > 1:
# "bar" hint + multi-year + multi-country = stacked bar over time,
# color=country. Single-year bar requests fall through to
# ExplicitBarCrossSectionalRule which produces a ranking bar.
if ctx.hint == "stacked_bar" or ctx.year_count > 1:
return StrategyResult(
ChartStrategy.STACKED_BAR,
f"User requested bar; {ctx.country_count} economies, {ctx.year_count} years β stacked bar chart (color=country)",
color_dim="country",
)
return None
class ExplicitMapRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.hint in ("map", "choropleth", "geoshape"):
if ctx.country_count > 0:
return StrategyResult(
ChartStrategy.CHOROPLETH,
f"User requested map; {ctx.country_count} economies β choropleth map",
indicator_cols=ctx.ind_cols,
)
return None
class ExplicitDistributionRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.hint in ("strip", "beeswarm", "tick", "distribution"):
# Require β₯10 countries: strip/tick charts only have visual density
# with many data points. Below 10, fall through to CrossSectionalRule
# which produces a proper solid horizontal bar β far more readable.
if ctx.country_count >= 10 and ctx.year_count <= 1:
return StrategyResult(
ChartStrategy.DISTRIBUTION,
f"User requested distribution; {ctx.country_count} economies, single year β strip/beeswarm",
color_dim="country",
)
return None
class ExplicitSmallMultiplesRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.hint in ("facet", "small_multiples"):
facet_dim = None
color_dim = None
if ctx.n_breakdowns >= 1:
facet_dim = list(ctx.breakdown_counts.keys())[0]
if ctx.n_breakdowns >= 2:
color_dim = list(ctx.breakdown_counts.keys())[1]
elif ctx.country_count > 1:
facet_dim = "country"
elif ctx.year_count > 1:
facet_dim = "year"
if facet_dim:
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
f"User requested small multiples; faceting by {facet_dim}",
facet_dim=facet_dim,
color_dim=color_dim,
)
return None
def _axes_are_incompatible(df: "pd.DataFrame", ind_cols: list, scale_type: str | None = None) -> bool:
"""Return True when indicators cannot meaningfully share a single Y-axis.
Three complementary tests β all data-driven and domain-agnostic:
1. **Magnitude ratio β₯ 10Γ** (1.0 logββ unit).
Standard dataviz threshold at which the smaller series becomes visually
compressed against the larger one.
2. **Sign-domain mismatch** β one indicator's *median* is negative while
another's is non-negative.
Growth rates, balances, and returns cross zero; levels and counts do not.
Placing them on a shared axis creates a misleading zero-reference.
3. **Range non-overlap** β the full [min, max] interval of one indicator
does not intersect the interval of another.
This catches cases where magnitude ratios are similar but the scales are
completely disjoint (e.g. GDP growth [-6, 14] vs life expectancy [51, 67]:
ratio is only ~5Γ, no negative medians, but the ranges are entirely
separate and combining them on one axis is meaningless).
"""
import math as _m
mags: list[float] = []
medians: list[float] = []
ranges: list[tuple] = []
for col in ind_cols:
if col not in df.columns:
continue
s = pd.to_numeric(df[col], errors="coerce").dropna()
if s.empty:
continue
lo, hi = float(s.min()), float(s.max())
ranges.append((lo, hi))
medians.append(float(s.median()))
max_abs = float(s.abs().max())
if max_abs > 0:
mags.append(_m.log10(max_abs))
# Test 1: any pair exceeds magnitude ratio threshold
valid_cols = [col for col in ind_cols if col in df.columns and not pd.to_numeric(df[col], errors="coerce").dropna().empty]
for i in range(len(mags)):
for j in range(i + 1, len(mags)):
col_i, col_j = valid_cols[i], valid_cols[j]
s_i = pd.to_numeric(df[col_i], errors="coerce").dropna()
s_j = pd.to_numeric(df[col_j], errors="coerce").dropna()
is_pct_i = any(x in col_i.lower() for x in ["%", "percent", "pct", "proportion", "share", "rate"]) and s_i.max() <= 100.0 and s_i.min() >= 0.0
is_pct_j = any(x in col_j.lower() for x in ["%", "percent", "pct", "proportion", "share", "rate"]) and s_j.max() <= 100.0 and s_j.min() >= 0.0
same_numeric_scale = not ((s_i.max() <= 1.0) ^ (s_j.max() <= 1.0))
is_pct = (scale_type == "percentage") or (is_pct_i and is_pct_j and same_numeric_scale)
thresh = float("inf") if is_pct else 1.0
if abs(mags[i] - mags[j]) >= thresh:
return True
# Test 2: sign-domain mismatch β some medians negative, some non-negative
if len(medians) >= 2:
if any(m < 0 for m in medians) and any(m >= 0 for m in medians):
return True
# Test 3: range non-overlap β any pair of indicators has disjoint [min, max]
# Two ranges [a,b] and [c,d] overlap iff b >= c AND d >= a.
# Percentage-based indicators share the same bounded [0, 100] scale, so range non-overlap is bypassed.
is_pct_scale = (scale_type == "percentage")
if not is_pct_scale:
for i in range(len(ranges)):
for j in range(i + 1, len(ranges)):
a, b = ranges[i]
c, d = ranges[j]
if b < c or d < a: # ranges are disjoint
return True
return False
class TwoIndicatorRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.n_indicators == 2 and len(ctx.ind_cols) == 2:
if ctx.year_count <= 1 and ctx.country_count > 1:
if ctx.hint == "bar":
return StrategyResult(
ChartStrategy.BREAKDOWN_COMPARISON,
f"User requested bar; 2 indicators, {ctx.country_count} economies, single year β grouped bar",
indicator_cols=ctx.ind_cols,
color_dim="indicator",
)
return StrategyResult(
ChartStrategy.CORRELATION,
f"2 indicators, {ctx.country_count} economies, single year β scatterplot",
indicator_cols=ctx.ind_cols,
color_dim="country",
x_dim=ctx.ind_cols[0],
y_dim=ctx.ind_cols[1],
)
if ctx.year_count > 1 and ctx.country_count > 1:
# Phase 8: connected scatter reveals relationship evolution.
# Only use connected scatter if explicitly requested (hint is "point" i.e. scatter/dot/correlation).
# Otherwise, small multiples is much more standard and readable for trend comparison.
is_scatter_hint = ctx.hint == "point"
if (
is_scatter_hint
and ctx.country_count <= CORRELATION_TEMPORAL_AUTO_MAX_COUNTRIES
and ctx.year_count <= CORRELATION_TEMPORAL_AUTO_MAX_YEARS
):
return StrategyResult(
ChartStrategy.CORRELATION_TEMPORAL,
(
f"2 indicators, {ctx.country_count} economies, "
f"{ctx.year_count} years β connected scatter "
f"(β€{CORRELATION_TEMPORAL_AUTO_MAX_COUNTRIES} countries "
f"Γ β€{CORRELATION_TEMPORAL_AUTO_MAX_YEARS} years threshold)"
),
indicator_cols=ctx.ind_cols,
color_dim="country",
)
try:
is_incompatible = _axes_are_incompatible(ctx.df, ctx.ind_cols, ctx.scale_type)
except Exception:
is_incompatible = False
if is_incompatible:
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
f"2 indicators (scale-incompatible), {ctx.country_count} economies, {ctx.year_count} years β small multiples (facet=indicator, color=country)",
indicator_cols=ctx.ind_cols,
color_dim="country",
facet_dim="indicator",
scale_incompatible=True,
)
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
(
f"2 indicators (scale-compatible), "
f"{ctx.country_count} economies, {ctx.year_count} years β small multiples (facet=indicator, color=country)"
),
indicator_cols=ctx.ind_cols,
color_dim="country",
facet_dim="indicator",
)
if ctx.year_count <= 1:
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
"2 indicators, 1 country, single year β small multiples (facet=indicator, color=indicator)",
indicator_cols=ctx.ind_cols,
color_dim="indicator",
facet_dim="indicator",
)
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
f"2 indicators, 1 country, {ctx.year_count} years β small multiples (facet=indicator, color=indicator)",
indicator_cols=ctx.ind_cols,
color_dim="indicator",
facet_dim="indicator",
)
return None
class ThreePlusIndicatorRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.n_indicators >= 2 and len(ctx.ind_cols) >= 2:
mark_hint = "bar" if ctx.year_count <= 1 else "line"
# Scale-incompatibility check: if any pair of indicators differs by
# β₯1.5 orders of magnitude, small_multiples keeps them readable on
# independent Y-axes (one panel per indicator, color=country).
if ctx.year_count > 1 and ctx.country_count >= 1:
try:
is_incompatible = _axes_are_incompatible(ctx.df, ctx.ind_cols, ctx.scale_type)
except Exception:
is_incompatible = False
if is_incompatible:
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
(
f"{ctx.n_indicators} indicators (scale-incompatible), "
f"{ctx.country_count} economies, {ctx.year_count} years "
f"β small multiples (facet=indicator, color=country)"
),
indicator_cols=ctx.ind_cols,
color_dim="country",
facet_dim="indicator",
scale_incompatible=True,
)
elif ctx.country_count > 1:
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
(
f"{ctx.n_indicators} indicators, "
f"{ctx.country_count} economies, {ctx.year_count} years "
f"β small multiples (facet=indicator, color=country)"
),
indicator_cols=ctx.ind_cols,
color_dim="country",
facet_dim="indicator",
)
if ctx.country_count > 1:
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
(
f"{ctx.n_indicators} indicators, "
f"{ctx.country_count} economies β "
f"small multiples (facet=indicator, color=country)"
),
indicator_cols=ctx.ind_cols,
color_dim="country",
facet_dim="indicator",
)
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
f"{ctx.n_indicators} indicators, 1 country β small multiples (facet=indicator, color=indicator)",
indicator_cols=ctx.ind_cols,
color_dim="indicator",
facet_dim="indicator",
)
return None
class StackedAreaRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.hint in ("area", "stacked_area") and "unit_measure" not in ctx.breakdown_counts:
if ctx.n_indicators >= 2:
if not (ctx.same_unit and ctx.can_share_axis):
ctx.register_refusal(ctx.hint, "Indicators represent different units or incompatible scales")
return None
if ctx.year_count <= 1:
ctx.register_refusal(ctx.hint, "Area charts require multiple years of data")
return None
if ctx.year_count > 1:
color_dim = None
if ctx.breakdown_counts:
color_dim = list(ctx.breakdown_counts.keys())[0]
elif ctx.country_count > 1:
color_dim = "country"
return StrategyResult(
ChartStrategy.STACKED_AREA,
f"User requested area; {ctx.year_count} years β stacked area chart",
color_dim=color_dim,
)
return None
class ExplicitHeatmapRule:
"""Honour an explicit ``heatmap`` hint from the caller.
Requires multiple time periods so there is a meaningful country-x-year
matrix. Single-year requests fall through to the auto-routing rules
(usually CrossSectional / BreakdownComparison).
"""
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.hint == "heatmap" and ctx.year_count > 1 and ctx.country_count > 1:
return StrategyResult(
ChartStrategy.HEATMAP,
f"User requested heatmap; {ctx.country_count} economies, {ctx.year_count} years β heatmap",
color_dim="value",
)
return None
class HeatmapRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.country_count >= HIGH_CARDINALITY_THRESHOLDS["heatmap_threshold"] and ctx.year_count > 1:
if ctx.n_breakdowns == 0:
return StrategyResult(
ChartStrategy.HEATMAP,
f"{ctx.country_count} economies, {ctx.year_count} years β heatmap",
color_dim="value",
)
return None
class ExplicitBarBreakdownRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.hint == "bar" and ctx.n_breakdowns == 1 and 0 < ctx.country_count <= 4:
color_dim = list(ctx.breakdown_counts.keys())[0]
return StrategyResult(
ChartStrategy.BREAKDOWN_COMPARISON,
f"User requested bar; 1 breakdown ({color_dim}), {ctx.country_count} economies β grouped bar",
color_dim=color_dim,
)
return None
class IncompatibleUnitsRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if "unit_measure" in ctx.breakdown_counts:
facet_dim = "unit_measure"
other_breakdowns = [k for k in ctx.breakdown_counts if k != "unit_measure"]
color_dim = other_breakdowns[0] if other_breakdowns else None
secondary_color_dim = "country" if ctx.country_count > 1 else None
n_other = len(other_breakdowns)
unit_count = ctx.breakdown_counts["unit_measure"]
reason_detail = (
f"unit_measure ({unit_count} units)"
+ (f" + {n_other} other breakdown(s)" if n_other else "")
+ f", {ctx.country_count} econom{'y' if ctx.country_count == 1 else 'ies'}"
+ (" + country combo" if secondary_color_dim else "")
+ " β faceted by unit (independent Y-axes)"
)
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
reason_detail,
color_dim=color_dim,
facet_dim=facet_dim,
secondary_color_dim=secondary_color_dim,
scale_incompatible=True,
)
return None
class IncompatibleCustomBreakdownRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.n_breakdowns == 1 and ctx.country_count > 1:
bd_dim = list(ctx.breakdown_counts.keys())[0]
if bd_dim in _CUSTOM_BREAKDOWN_DIMS and _detect_scale_incompatibility(ctx.df, bd_dim):
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
f"1 breakdown ({bd_dim}), {ctx.country_count} economies, scale-incompatible "
f"β scale-split panels (color=economy)",
color_dim="country",
facet_dim=bd_dim,
scale_incompatible=True,
)
return None
class GenericSmallMultiplesRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.n_breakdowns >= 2 or (ctx.n_breakdowns >= 1 and ctx.country_count > 1):
if ctx.country_count > 1:
facet_dim = "country"
color_dim = list(ctx.breakdown_counts.keys())[0] if ctx.breakdown_counts else None
elif ctx.n_breakdowns >= 2:
bd_keys = list(ctx.breakdown_counts.keys())
facet_dim = bd_keys[0]
color_dim = bd_keys[1] if len(bd_keys) >= 2 else None
else:
facet_dim = list(ctx.breakdown_counts.keys())[0]
color_dim = None
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
f"{ctx.n_breakdowns} breakdowns, {ctx.country_count} econom{'y' if ctx.country_count == 1 else 'ies'} "
f"β small multiples (facet={facet_dim}, color={color_dim})",
color_dim=color_dim,
facet_dim=facet_dim,
)
return None
class TemporalBreakdownRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.n_breakdowns == 1 and ctx.year_count > 1:
color_dim = list(ctx.breakdown_counts.keys())[0]
if color_dim in _CUSTOM_BREAKDOWN_DIMS and _detect_scale_incompatibility(ctx.df, color_dim):
return StrategyResult(
ChartStrategy.SMALL_MULTIPLES,
f"1 breakdown ({color_dim}), {ctx.year_count} years, scale-incompatible "
f"β faceted (independent Y-axes)",
color_dim=None,
facet_dim=color_dim,
scale_incompatible=True,
)
return StrategyResult(
ChartStrategy.TEMPORAL_SINGLE,
f"1 breakdown ({color_dim}), {ctx.year_count} years β multi-series line chart",
color_dim=color_dim,
)
return None
class BreakdownComparisonGroupedBarRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.n_breakdowns == 1 and ctx.country_count <= 4 and ctx.year_count <= 1:
color_dim = list(ctx.breakdown_counts.keys())[0]
return StrategyResult(
ChartStrategy.BREAKDOWN_COMPARISON,
f"1 breakdown ({color_dim}), {ctx.breakdown_counts[color_dim]} values, single year β grouped bar",
color_dim=color_dim,
)
return None
class ExplicitBarCrossSectionalRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.hint == "bar" and ctx.year_count <= 1 and ctx.country_count > 0:
return StrategyResult(
ChartStrategy.CROSS_SECTIONAL,
f"User requested bar; {ctx.country_count} economies, single year β horizontal bar",
color_dim="country",
)
return None
class HighCardinalityCrossSectionalRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.country_count > HIGH_CARDINALITY_THRESHOLDS["beeswarm_threshold"] and ctx.year_count <= 1:
if ctx.hint in ("strip", "beeswarm", "tick", "distribution"):
return StrategyResult(
ChartStrategy.DISTRIBUTION,
f"User requested strip/beeswarm; {ctx.country_count} economies, single year β strip/beeswarm",
color_dim="country",
)
return StrategyResult(
ChartStrategy.CHOROPLETH,
f"{ctx.country_count} economies, single year β default to choropleth map",
)
return None
class CrossSectionalRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if (ctx.year_count <= 1 or ctx.avg_years_per_country < 1.7) and ctx.country_count > 0:
return StrategyResult(
ChartStrategy.CROSS_SECTIONAL,
f"{ctx.country_count} economies, sparse or single year (avg {ctx.avg_years_per_country:.2f} yrs) β horizontal bar",
color_dim="country",
)
return None
class TemporalSingleRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult | None:
if ctx.year_count > 1 and ctx.avg_years_per_country >= 1.7:
phrase = chart_type_phrase_for_reason(ctx.hint)
return StrategyResult(
ChartStrategy.TEMPORAL_SINGLE,
f"Single indicator, {ctx.year_count} years, {ctx.country_count} economies β {phrase}",
color_dim="country" if ctx.country_count > 0 else None,
mark_hint=ctx.hint if ctx.hint in ("bar", "line") else None,
)
return None
class FallbackRule:
def evaluate(self, ctx: RoutingContext) -> StrategyResult:
return StrategyResult(
ChartStrategy.FALLBACK_LINE,
f"Default fallback β {chart_type_phrase_for_reason(ctx.hint)}",
color_dim="country" if ctx.country_count > 0 else None,
)
ROUTING_RULES: list[RoutingRule] = [
ExplicitScatterRule(),
ExplicitStackedAreaMultiIndicatorRule(),
ExplicitStackedBarRule(),
ExplicitMapRule(),
ExplicitSmallMultiplesRule(),
ExplicitHeatmapRule(),
ExplicitDistributionRule(),
TwoIndicatorRule(),
ThreePlusIndicatorRule(),
StackedAreaRule(),
HeatmapRule(),
ExplicitBarBreakdownRule(),
IncompatibleUnitsRule(),
IncompatibleCustomBreakdownRule(),
GenericSmallMultiplesRule(),
TemporalBreakdownRule(),
BreakdownComparisonGroupedBarRule(),
ExplicitBarCrossSectionalRule(),
HighCardinalityCrossSectionalRule(),
CrossSectionalRule(),
TemporalSingleRule(),
]
def select_strategy(
df: pd.DataFrame,
n_indicators: int = 1,
chart_type_hint: str | None = None,
indicator_cols: list[str] | None = None,
raw_unit: str | None = None,
raw_unit_mult: int = 0,
data_profile: dict | None = None,
strategy_override: str | None = None,
) -> StrategyResult:
"""
Applies the Rule Engine to select the correct ChartStrategy.
Parameters
----------
data_profile : dict | None
Pre-computed data profile from ``_build_data_profile``. When provided,
coverage quality signals (sparse country count, completeness %) are
injected into the ``RoutingContext`` so routing rules can use real
sparsity data rather than structural heuristics alone.
strategy_override : str | None
Explicit ChartStrategy value or name (e.g. "stacked_bar", "vconcat_panels").
If provided and valid, bypasses the rule engine and directly forces
the requested strategy, using the routing context to configure sensible
color and facet defaults.
"""
ctx = RoutingContext.build(
df,
n_indicators,
chart_type_hint,
indicator_cols,
raw_unit=raw_unit,
raw_unit_mult=raw_unit_mult
)
# Inject coverage signals from data_profile into RoutingContext
if data_profile:
cq = data_profile.get("coverage_quality", {})
ctx.sparse_country_count = len(cq.get("sparse_countries", []))
ctx.completeness_pct = cq.get("completeness_pct", 100.0)
scale_comp = data_profile.get("scale_compatibility", {})
ctx.same_unit = scale_comp.get("same_unit", True)
ctx.can_share_axis = scale_comp.get("can_share_axis", True)
inds = data_profile.get("indicators", [])
if inds and all(ind.get("scale_type") == "percentage" for ind in inds):
ctx.scale_type = "percentage"
res: StrategyResult | None = None
# Handle explicit strategy override
if strategy_override:
matched_strategy = None
for s in ChartStrategy:
if s.value.lower() == strategy_override.lower() or s.name.lower() == strategy_override.lower():
matched_strategy = s
break
if matched_strategy:
res = _build_overridden_strategy(matched_strategy, ctx)
# Fall back to Rule Engine if no override or invalid override
if res is None:
for rule in ROUTING_RULES:
res = rule.evaluate(ctx)
if res is not None:
break
if res is None:
res = FallbackRule().evaluate(ctx)
res.scale_type = ctx.scale_type
res.unit_mult = ctx.unit_mult
res.raw_hint = ctx.raw_hint
res.refusal_reason = ctx.refusal_reason
# Attach the full data profile to the result so it travels with the strategy
if data_profile is not None:
res.data_profile = data_profile
# Compute scale compatibility from real data for multi-indicator charts
if ctx.indicator_value_ranges and len(ctx.indicator_value_ranges) >= 2:
maxes = [r["max"] for r in ctx.indicator_value_ranges.values() if r["max"] > 0]
mins_nz = [r["min"] for r in ctx.indicator_value_ranges.values() if r["min"] > 0]
if maxes and mins_nz:
ratio = max(maxes) / min(mins_nz)
can_share = ratio <= 10.0
res.scale_compatibility = {
"max_min_ratio": round(ratio, 2),
"can_share_axis": can_share,
"reason": (
f"Value ratio {ratio:.1f}x β "
+ ("within" if can_share else "exceeds")
+ " 10x threshold"
),
}
return res
def _build_overridden_strategy(strategy: ChartStrategy, ctx: RoutingContext) -> StrategyResult:
"""Build a StrategyResult for a user/LLM overridden strategy, populating sensible defaults."""
color_dim = None
facet_dim = None
indicator_cols = ctx.ind_cols
if strategy in (ChartStrategy.STACKED_AREA, ChartStrategy.STACKED_BAR):
if len(indicator_cols) >= 2:
color_dim = "indicator"
elif ctx.n_breakdowns == 1:
color_dim = list(ctx.breakdown_counts.keys())[0]
elif ctx.country_count > 1:
color_dim = "country"
elif strategy == ChartStrategy.TEMPORAL_SINGLE:
if ctx.n_breakdowns == 1:
color_dim = list(ctx.breakdown_counts.keys())[0]
elif ctx.country_count > 1:
color_dim = "country"
elif strategy == ChartStrategy.SMALL_MULTIPLES:
if len(indicator_cols) >= 2:
facet_dim = "indicator"
color_dim = "indicator"
elif ctx.country_count > 1:
facet_dim = "country"
if ctx.n_breakdowns == 1:
color_dim = list(ctx.breakdown_counts.keys())[0]
elif strategy == ChartStrategy.BREAKDOWN_COMPARISON:
if len(indicator_cols) >= 2:
color_dim = "indicator"
elif ctx.n_breakdowns == 1:
color_dim = list(ctx.breakdown_counts.keys())[0]
elif strategy in (ChartStrategy.CORRELATION, ChartStrategy.CORRELATION_TEMPORAL):
if ctx.country_count > 0:
color_dim = "country"
return StrategyResult(
strategy=strategy,
reason=f"Forced via strategy_override: {strategy.value}",
indicator_cols=indicator_cols,
color_dim=color_dim,
facet_dim=facet_dim,
)
def explain_chart_routing(
n_indicators: int,
country_count: int,
year_count: int,
avg_years_per_country: float,
breakdown_dims: list[str] | None = None,
chart_type_hint: str | None = None,
scale_type: str | None = None,
indicator_scales: list[dict] | None = None,
) -> dict:
"""Explain which chart strategy the routing engine would select for the given data shape.
Synthesises a minimal DataFrame from the structural descriptors, runs the full
rule waterfall, checks multi-indicator scale compatibility, and returns a
structured explanation the LLM can use to decide *which* viz tool to call and
*how* to configure it β before committing to a potentially expensive data fetch.
Args:
n_indicators: Number of distinct indicators (1, 2, or 3+).
country_count: Number of unique countries in the data.
year_count: Total number of unique time periods in the data.
avg_years_per_country: Mean unique years per country
(use year_count for single-country data; lower if countries have sparse coverage).
breakdown_dims: Disaggregation dimensions present in the data
(e.g. ["sex"], ["age", "urbanisation"]). Omit or pass [] for none.
chart_type_hint: Optional explicit chart type requested by the user
(e.g. "heatmap", "bar", "scatter"). Pass None to use auto-routing.
scale_type: Shared unit type for single-indicator data
(e.g. "percentage", "currency", "persons", "index").
indicator_scales: Per-indicator scale info for multi-indicator data.
Each entry: {"label": str, "scale_type": str, "approx_max": float}.
Used to determine whether indicators can share a Y-axis (ratio <= 10x).
Returns:
dict with keys:
strategy : ChartStrategy value string (e.g. "temporal_single")
layout : "single_panel" | "vconcat_panels" (multi-indicator only)
reason : Human-readable explanation of why this strategy was chosen
recommended_viz_tool : "data360_get_viz_spec" | "data360_get_multi_indicator_viz_spec"
chart_type_hint : Suggested chart_type argument value, or null
scale_notes : Notes on scale compatibility for multi-indicator data
routing_inputs : Echo of the structural inputs used for reproducibility
"""
import numpy as np
# ββ Build a synthetic DataFrame matching the described data shape ββββββββββ
countries = [f"C{i}" for i in range(max(country_count, 1))]
years = list(range(2020, 2020 + max(year_count, 1)))
# Main value column for single-indicator routing
rows = []
for c in countries:
c_years = years[:max(1, round(avg_years_per_country))]
for y in c_years:
row: dict = {"country": c, "year": y, "value": float(np.random.uniform(10, 100))}
for dim in (breakdown_dims or []):
row[dim] = f"{dim}_val"
rows.append(row)
df = pd.DataFrame(rows) if rows else pd.DataFrame({"country": ["C0"], "year": [2020], "value": [50.0]})
# Add wide-format indicator columns for multi-indicator routing
ind_cols: list[str] | None = None
if n_indicators >= 2 and indicator_scales:
ind_cols = []
for i, ind in enumerate(indicator_scales[:n_indicators]):
col_name = f"IND_{i}"
approx_max = float(ind.get("approx_max", 100.0))
df[col_name] = [float(np.random.uniform(approx_max * 0.5, approx_max)) for _ in range(len(df))]
ind_cols.append(col_name)
# ββ Run routing engine βββββββββββββββββββββββββββββββββββββββββββββββββββββ
raw_unit = scale_type or ""
result = select_strategy(
df,
n_indicators=n_indicators,
chart_type_hint=chart_type_hint,
indicator_cols=ind_cols,
raw_unit=raw_unit,
)
strategy_value = result.strategy.value
# ββ Multi-indicator layout check βββββββββββββββββββββββββββββββββββββββββββ
layout = "single_panel"
scale_notes = ""
if n_indicators >= 2 and indicator_scales and ind_cols:
try:
max_vals = [float(ind.get("approx_max", 100.0)) for ind in indicator_scales[:n_indicators]]
if max_vals and min(max_vals) > 0:
ratio = max(max_vals) / min(max_vals)
if ratio <= 10.0:
layout = "single_panel"
scale_notes = (
f"Indicators are scale-compatible (max ratio {ratio:.1f}x β€ 10x). "
f"They will share a single Y-axis in one panel."
)
else:
layout = "vconcat_panels"
scale_notes = (
f"Indicators differ in scale by {ratio:.0f}x (> 10x threshold). "
f"They will be split into stacked panels with independent Y-axes."
)
else:
layout = "vconcat_panels"
scale_notes = "Could not determine scale ratio β defaulting to stacked panels."
except Exception:
layout = "vconcat_panels"
scale_notes = "Scale check failed β defaulting to stacked panels."
elif strategy_value == "temporal_multi_indicator":
scale_notes = (
"No per-indicator scale info provided. Pass indicator_scales to determine "
"whether indicators can share a Y-axis."
)
# ββ Recommended viz tool βββββββββββββββββββββββββββββββββββββββββββββββββββ
recommended_tool = (
"data360_get_multi_indicator_viz_spec"
if n_indicators >= 2
else "data360_get_viz_spec"
)
# ββ Suggested chart_type argument ββββββββββββββββββββββββββββββββββββββββββ
suggested_hint: str | None = chart_type_hint # keep explicit hints as-is
if not chart_type_hint:
# Provide a helpful hint only when auto-routing might be ambiguous
hint_map = {
"cross_sectional": "bar",
"heatmap": "heatmap",
"distribution": "strip",
"correlation": "scatter",
"correlation_temporal": "connected_scatter",
"stacked_area": "stacked_area",
}
suggested_hint = hint_map.get(strategy_value) # None = let auto-routing decide
return {
"strategy": strategy_value,
"layout": layout,
"reason": result.reason,
"recommended_viz_tool": recommended_tool,
"chart_type_hint": suggested_hint,
"scale_notes": scale_notes,
"routing_inputs": {
"n_indicators": n_indicators,
"country_count": country_count,
"year_count": year_count,
"avg_years_per_country": avg_years_per_country,
"breakdown_dims": breakdown_dims or [],
"chart_type_hint": chart_type_hint,
"scale_type": scale_type,
"indicator_scales": indicator_scales or [],
},
}
# ============================================================================
# SPEC BUILDERS β one per strategy, pure functions returning raw VL dicts
# ============================================================================
def _vl_schema() -> str:
return "https://vega.github.io/schema/vega-lite/v5.json"
def _axis_style(title: str | None = None, temporal: bool = False) -> dict:
ax: dict = {
"grid": False,
"gridColor": WB_GRID_COLOR,
"gridDash": [4, 2],
"labelColor": WB_TEXT_SUBTLE,
"titleColor": WB_TEXT,
"titleFontWeight": "bold",
"tickCount": 5,
}
if temporal:
ax["title"] = None
ax["format"] = "%Y"
ax["tickCount"] = 5
ax["labelAngle"] = 0
elif title is not None:
ax["title"] = title
return ax
def _resolve_axis_title(
y_label: str | None,
indicator_name: str | None,
) -> str | None:
"""Return the best available axis title for a value axis, using only the short unit of measure."""
_GENERIC = {"value", ""}
unit_ok = y_label is not None and y_label.lower() not in _GENERIC
if unit_ok:
return _clean_unit_label(y_label)
if indicator_name:
return indicator_name
return None
def _detect_temporal_frequency(series: pd.Series) -> TemporalFreq:
"""Infer temporal frequency from raw TIME_PERIOD values.
Handles all formats the Data360 API produces:
- Annual: "2019", "2020"
- Monthly: "2019-09", "2019-09-01", "2019M09"
- Quarterly: "2019-Q1", "2019Q1", "2019-q1"
- Daily: "2019-09-15"
Logic:
- Parse unique values as datetime. If all land on Jan-1 (or are bare
4-digit integers), treat as annual.
- If distinct parsed periods show > 1 period per year β sub-annual.
Distinguish quarterly (avg ~4/year) vs monthly (avg ~12/year).
- Fall back to annual on any parse error or empty series.
"""
values = series.dropna().astype(str).unique()
if len(values) == 0:
return "annual"
# Fast path: all values are bare 4-digit years (most common case)
if all(v.strip().isdigit() and len(v.strip()) == 4 for v in values):
return "annual"
# Check for explicit quarter markers before parsing as datetime
q_pattern = re.compile(r"\d{4}[-\s]?[Qq]\d", re.IGNORECASE)
if any(q_pattern.search(v) for v in values):
return "quarterly"
# Parse as datetime
try:
parsed = pd.to_datetime(pd.Series(values), errors="coerce").dropna()
except Exception:
return "annual"
if parsed.empty:
return "annual"
# If every date is Jan-1 β effectively annual
if (parsed.dt.month == 1).all() and (parsed.dt.day == 1).all():
return "annual"
n_years = max(parsed.dt.year.nunique(), 1)
# Count distinct year-month combos to correctly classify monthly data
# where dates span calendar-year boundaries (e.g. Sep 2019 β Aug 2020).
n_year_months = parsed.dt.to_period("M").nunique()
avg_months_per_year = n_year_months / n_years
# Quarterly data has at most 4 year-months per year.
# Monthly data has >= 5 (even sparse datasets).
if avg_months_per_year >= 5:
return "monthly"
if avg_months_per_year >= 3:
return "quarterly"
# Fewer than 3 distinct months per year on average β annual (e.g. IPC biannual)
return "annual"
def _format_time_period_series(
series: pd.Series, freq: TemporalFreq
) -> pd.Series:
"""Convert raw TIME_PERIOD strings to the correct format for a given frequency.
Annual β "2019" (4-digit year string; Vega-Lite ordinal)
Monthly β "2019-09" (ISO yearmonth; Vega-Lite temporal + timeUnit yearmonth)
Quarterlyβ "2019-Q1" (ISO yearquarter; Vega-Lite temporal + timeUnit yearquarter)
Daily β "2019-09-15" (ISO date; Vega-Lite temporal)
Values that fail parsing are left as-is (graceful fallback).
"""
try:
parsed = pd.to_datetime(series.astype(str), errors="coerce")
except Exception:
return series
if freq == "annual":
return parsed.dt.year.astype("Int64").astype(str).where(parsed.notna(), series)
elif freq == "monthly":
return parsed.dt.to_period("M").astype(str).where(parsed.notna(), series)
elif freq == "quarterly":
return parsed.dt.to_period("Q").astype(str).where(parsed.notna(), series)
else: # daily
return parsed.dt.strftime("%Y-%m-%d").where(parsed.notna(), series)
# Vega-Lite x-axis configuration per temporal frequency.
# Using a separate dict per frequency so builder functions have a single
# call site (_x_temporal_encoding) rather than hardcoded copies.
_TEMPORAL_X_ENCODING: dict[TemporalFreq, dict] = {
"annual": {
"field": "year",
"type": "temporal",
"timeUnit": "utcyear",
"axis": {
"title": None,
"format": "%Y",
"tickCount": 5,
"labelAngle": 0,
"grid": False,
"gridColor": WB_GRID_COLOR,
"gridDash": [4, 2],
"labelColor": WB_TEXT_SUBTLE,
"titleColor": WB_TEXT,
"titleFontWeight": "bold",
},
},
"monthly": {
"field": "year",
"type": "temporal",
"timeUnit": "utcyearmonth",
"axis": {
"title": None,
"format": "%b %Y",
"tickCount": 8,
"labelAngle": -45,
"grid": False,
"gridColor": WB_GRID_COLOR,
"gridDash": [4, 2],
"labelColor": WB_TEXT_SUBTLE,
"titleColor": WB_TEXT,
"titleFontWeight": "bold",
},
},
"quarterly": {
"field": "year",
"type": "temporal",
"timeUnit": "utcyearquarter",
"axis": {
"title": None,
"format": "Q%q %Y",
"tickCount": 6,
"labelAngle": -45,
"grid": False,
"gridColor": WB_GRID_COLOR,
"gridDash": [4, 2],
"labelColor": WB_TEXT_SUBTLE,
"titleColor": WB_TEXT,
"titleFontWeight": "bold",
},
},
"daily": {
"field": "year",
"type": "temporal",
"timeUnit": "utcyearmonthdate",
"axis": {
"title": None,
"format": "%d %b %Y",
"tickCount": 6,
"labelAngle": -45,
"grid": False,
"gridColor": WB_GRID_COLOR,
"gridDash": [4, 2],
"labelColor": WB_TEXT_SUBTLE,
"titleColor": WB_TEXT,
"titleFontWeight": "bold",
},
},
}
def _x_temporal_encoding(freq: TemporalFreq = "annual") -> dict:
"""Return the correct Vega-Lite x encoding for the given temporal frequency.
Returns a deep copy so callers can mutate axis overrides (e.g. labels=False
for non-bottom panels) without affecting subsequent calls.
"""
import copy
return copy.deepcopy(_TEMPORAL_X_ENCODING.get(freq, _TEMPORAL_X_ENCODING["annual"]))
def _is_proportion_indicator(df, unit_measure=None, scale_type=None):
"""Check if the indicator unit, scale_type, or name suggests it's a proportion/rate/share."""
normalized_unit = (unit_measure or "").upper()
if scale_type == "percentage" or (("%" in normalized_unit or "PERCENT" in normalized_unit) and "PERSON" not in normalized_unit):
return True
keywords = {"PROPORTION", "SHARE", "RATE", "RATIO", "FRACTION"}
if any(k in normalized_unit for k in keywords):
return True
if df is not None and "indicator" in df.columns:
ind_names = df["indicator"].dropna().unique()
for name in ind_names:
name_upper = str(name).upper()
if any(k in name_upper for k in keywords) or "PERCENT" in name_upper or "%" in name_upper:
return True
return False
def _value_label_expr(unit_measure: str | None = None, scale_type: str | None = None) -> str:
"""Vega expression for custom k/m/b/t axis label formatting."""
normalized = (unit_measure or "").upper().strip()
if scale_type == "proportion":
return "format(datum.value, '.0%')"
is_currency = scale_type == "currency" or "$" in normalized or "USD" in normalized
prefix = "$" if is_currency else ""
is_percentage = scale_type == "percentage" or (("%" in normalized or "PERCENT" in normalized) and "PERSON" not in normalized)
if is_percentage:
return "format(datum.value, '.1~f') + '%'"
if unit_measure == "T":
tiers = [("1e12", "Gt"), ("1e9", "Mt"), ("1e6", "Kt")]
elif unit_measure == "W_POP":
tiers = [("1e12", "Gw"), ("1e9", "Mw"), ("1e6", "Kw")]
elif unit_measure in ("BITS", "BIT_S_IU"):
tiers = [("1e12", "Gb"), ("1e9", "Mb"), ("1e6", "Kb")]
else:
tiers = [("1e12", "t"), ("1e9", "b"), ("1e6", "m"), ("1e3", "k")]
parts = [
f"abs(datum.value)>={t} ? '{prefix}'+format(datum.value/{t},'.1~f')+'{s}'"
for t, s in tiers
]
tail = (
f" : abs(datum.value)>=10 ? '{prefix}'+format(datum.value,',.1~f')"
f" : abs(datum.value)>=1 ? '{prefix}'+format(datum.value,'.1~f')"
f" : '{prefix}'+format(datum.value,'.2~f')"
)
return " : ".join(parts) + tail
def _compute_tooltip_format(
max_abs: float | None = None, unit_measure: str | None = None
) -> str:
"""Returns D3 format string for tooltip quantitative fields.
Avoids D3's SI-prefix format (~s) which uses G/M/k (giga/mega/kilo) β
these conflict with our axis labelExpr which uses b/m/k (billion/million/thousand).
Large values are formatted as plain integers with comma separators instead.
"""
normalized = (unit_measure or "").upper().strip()
if ("PROPORTION" in normalized or "SHARE" in normalized) and max_abs is not None and 0.0 < max_abs <= 1.0:
return ".1%"
if unit_measure == "%" or "%" in normalized or "PERCENT" in normalized:
return ".1f"
if "$" in normalized or "USD" in normalized:
return "$,.2f"
if max_abs is None or max_abs < 1:
return ".2f"
if max_abs < 10:
return ".1f"
if max_abs < 1000:
return ",.1f"
# Use comma-separated integers for large numbers (population, GDP, etc.)
# ",.0f" β "1,400,000,000" β unambiguous, no SI prefix conflict.
return ",.0f"
def _color_encoding(
field: str,
domain: list | None = None,
mark_type: str = "point",
n_items: int = 0,
legend_title: str | None = None,
domain_labels: list[str] | None = None,
) -> dict:
"""Build a Vega-Lite color encoding channel.
Legend title resolves in this priority order:
1. Caller-supplied ``legend_title``
2. Human-readable label from ``_TOOLTIP_SPECS`` (e.g. "Dimension 1")
3. Title-cased field name (e.g. "Comp Breakdown 2")
Legend orientation is chosen dynamically:
- When the longest label in ``domain_labels`` exceeds 40 chars the legend
switches to ``orient: bottom`` / ``direction: vertical`` so labels are not
truncated and are not clipped in narrow containers (e.g. chatbot panels).
- Otherwise ``orient: top`` / ``direction: horizontal`` is used.
"""
resolved_title = (
legend_title
or _TOOLTIP_SPECS.get(field, {}).get("title")
or field.replace("_", " ").title()
)
scale = {"range": WB_CAT_COLORS}
if domain:
sort_order = _get_dimension_sort_order(field, [str(d) for d in domain])
if sort_order:
domain = sorted(domain, key=lambda x: sort_order.index(str(x)) if str(x) in sort_order else len(sort_order))
scale["domain"] = domain
# Keep a legend for geography even with one series (product expectation).
if n_items == 1 and field != "country":
legend = None
else:
_LONG_LABEL_THRESHOLD = 40
max_label_len = (
max((len(lbl) for lbl in domain_labels), default=0)
if domain_labels
else 0
)
if max_label_len > _LONG_LABEL_THRESHOLD:
legend: dict | None = {
"orient": "right",
"direction": "vertical",
"title": resolved_title,
"labelLimit": 1000,
}
else:
legend = {
"orient": "right",
"direction": "vertical",
"title": resolved_title,
"labelLimit": 250,
}
if mark_type == "line":
legend["symbolType"] = "stroke"
return {
"field": field,
"type": "nominal",
"scale": scale,
"legend": legend,
}
def _adjust_end_label_y(df: pd.DataFrame, color_dim: str) -> pd.DataFrame:
"""Compute a '_label_y' column in df to prevent direct end labels from overlapping.
Uses a 1D relaxation (spring/force) algorithm on the final year's data values.
"""
if df.empty or "value" not in df.columns or "year" not in df.columns or not color_dim or color_dim not in df.columns:
return df
# Create copy and initialize _label_y to value
df = df.copy()
df["_label_y"] = df["value"]
try:
# Reset index to guarantee row matching is safe and non-duplicate
df = df.reset_index(drop=True)
# Get the rows representing the last point for each series
last_indices = df.groupby(color_dim)["year"].idxmax()
last_rows = df.loc[last_indices]
if len(last_rows) < 2:
return df
y_min = df["value"].min()
y_max = df["value"].max()
y_range = y_max - y_min if y_max != y_min else 1.0
if y_range <= 0:
return df
threshold = 0.04 * y_range
last_points = []
for idx, row in last_rows.iterrows():
last_points.append({
"idx": idx,
"val": float(row["value"])
})
last_points.sort(key=lambda x: x["val"])
# Spring relaxation pass
for _ in range(10):
for i in range(len(last_points) - 1):
p1 = last_points[i]
p2 = last_points[i+1]
diff = p2["val"] - p1["val"]
if diff < threshold:
overlap = threshold - diff
p1["val"] -= overlap / 2.0
p2["val"] += overlap / 2.0
for p in last_points:
df.at[p["idx"], "_label_y"] = p["val"]
except Exception as e:
import logging
logging.getLogger(__name__).warning(f"Failed to adjust end labels: {e}")
return df
def build_temporal_single_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
y_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Line or grouped-bar chart: 1 indicator, multi-year, β€8 countries.
When result.mark_hint == "bar", renders a grouped bar chart with:
- x = year as temporal (same encoding as line chart, timeUnit+format ensures correct display)
- xOffset = country (side-by-side bars within each year band)
- mark = bar with rounded top corners
"""
color_dim = result.color_dim
original_n = None
if color_dim and color_dim in df.columns:
df, original_n = _cap_cardinality(df, color_dim, HIGH_CARDINALITY_THRESHOLDS["line_max_series"])
# Determine if we need direct end labels and adjust y-positions to avoid overlaps
is_bar = result.mark_hint == "bar"
n_series = df[color_dim].nunique() if (color_dim and color_dim in df.columns) else 0
needs_end_labels = (
not is_bar
and color_dim
and 2 <= n_series <= MAX_END_LABEL_SERIES
and "year" in df.columns
)
if needs_end_labels:
df = _adjust_end_label_y(df, color_dim)
rows = df.to_dict(orient="records")
max_abs = float(df["value"].abs().max()) if "value" in df.columns else None
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
is_bar = result.mark_hint == "bar"
y_title = _resolve_axis_title(y_label, indicator_name)
y_ax = {
**_axis_style(),
"title": y_title,
"labelExpr": _value_label_expr(unit_measure),
}
# Both bar and line use the same temporal encoding β timeUnit+format handles
# date parsing and display (e.g. "%Y" for annual). Ordinal type was wrong
# because it doesn't parse dates, causing epoch-ms to render as raw numbers.
x_enc = _x_temporal_encoding(result.temporal_frequency)
encoding: dict = {
"x": x_enc,
"y": {
"field": "value",
"type": "quantitative",
"axis": y_ax,
"scale": {"zero": is_bar},
},
"tooltip": build_structured_tooltips(
list(df.columns),
"bar" if is_bar else "line",
indicator_labels,
value_format=tt_fmt,
viz_data=df,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
indicator_name=indicator_name,
),
}
if result.color_dim:
n_items = (
df[result.color_dim].nunique() if result.color_dim in df.columns else 0
)
domain_labels = (
list(df[result.color_dim].unique()) if result.color_dim in df.columns else None
)
legend_title = result.dim_name_labels.get(result.color_dim)
encoding["color"] = _color_encoding(
result.color_dim,
mark_type="bar" if is_bar else "line",
n_items=n_items,
legend_title=legend_title,
domain_labels=domain_labels,
)
if is_bar and result.color_dim in df.columns:
encoding["xOffset"] = {"field": result.color_dim, "type": "nominal"}
# Annotate subtitle with breakdown series names when color_dim is a custom breakdown.
annotated_title = _append_breakdown_note(title, df, result.color_dim)
annotated_title = _append_trim_note(annotated_title, color_dim, df[color_dim].nunique() if color_dim in df.columns else 0, original_n)
if is_bar:
mark_spec: dict = {
"type": "bar",
"opacity": 0.85,
"cornerRadiusTopLeft": 2,
"cornerRadiusTopRight": 2,
}
else:
mark_spec = {
"type": "line",
"strokeWidth": 3,
"strokeCap": "round",
"point": _LINE_HOVER_POINT,
}
spec: dict = {
"$schema": _vl_schema(),
"title": annotated_title,
"data": {"values": rows},
"mark": mark_spec,
"encoding": encoding,
"width": 600,
"height": 350,
}
# ------------------------------------------------------------------
# Phase 6 β Zero reference line for signed-value line/area charts.
# When the value domain spans negative and positive (e.g. GDP growth,
# inflation, current account balance) add a thin gray rule at y=0 so
# the growth/contraction boundary is always visible.
# ------------------------------------------------------------------
needs_zero_line = (
not is_bar
and "value" in df.columns
and df["value"].min() < 0 < df["value"].max()
)
# ------------------------------------------------------------------
# Phase 7 β Direct end labels for 2βMAX_END_LABEL_SERIES series.
# Eliminates legend look-away on multi-country line charts.
# Not applied to bar charts (bars are already labeled on the axis).
# ------------------------------------------------------------------
color_dim = result.color_dim
n_series = df[color_dim].nunique() if (color_dim and color_dim in df.columns) else 0
needs_end_labels = (
not is_bar
and color_dim
and 2 <= n_series <= MAX_END_LABEL_SERIES
and "year" in df.columns
)
if needs_zero_line or needs_end_labels:
# Convert flat spec to a layered spec. The main mark layer inherits
# the top-level $schema, title, data, width, and height from the
# outer container; the individual layers only need mark + encoding.
main_layer: dict = {"mark": spec.pop("mark"), "encoding": spec.pop("encoding")}
if needs_end_labels:
if "color" in main_layer["encoding"] and isinstance(main_layer["encoding"]["color"], dict):
main_layer["encoding"]["color"]["legend"] = None
layers: list[dict] = [main_layer]
if needs_zero_line:
zero_layer: dict = {
"mark": {
"type": "rule",
"color": "#999999",
"strokeWidth": 1.0,
"strokeDash": [4, 3],
"opacity": 0.8,
"tooltip": False,
},
"encoding": {"y": {"datum": 0}},
}
layers.append(zero_layer)
if needs_end_labels:
# Identify last year per series via argmax transform.
# This produces exactly one row per series β the point with the
# maximum year value β to anchor the label.
year_type = "temporal" if df["year"].dtype == "datetime64[ns]" else "ordinal"
end_label_layer: dict = {
"transform": [
{
"aggregate": [
{"op": "argmax", "field": "year", "as": "_last"}
],
"groupby": [color_dim],
},
{
"calculate": "datum._last._label_y",
"as": "_end_value",
},
{
"calculate": f"datum._last.year",
"as": "_end_year",
},
],
"mark": {
"type": "text",
"align": "left",
"dx": 5,
"fontSize": 10,
"fontWeight": "normal",
"tooltip": False,
},
"encoding": {
"x": {"field": "_end_year", "type": year_type},
"y": {"field": "_end_value", "type": "quantitative"},
"text": {"field": color_dim, "type": "nominal"},
"color": encoding.get("color", {}),
},
}
layers.append(end_label_layer)
spec["layer"] = layers
return inject_wb_config(spec)
def build_cross_sectional_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
x_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Horizontal bar: 1 indicator, single year.
Rows are capped at HIGH_CARDINALITY_THRESHOLDS["cross_sectional_max_items"]
and sorted descending by value (highest performing country at top).
"""
bar_dim = result.color_dim or "country"
df, original_n = _cap_cardinality(
df.sort_values("value", ascending=False),
bar_dim,
HIGH_CARDINALITY_THRESHOLDS["cross_sectional_max_items"],
)
title = _append_trim_note(title, bar_dim, df[bar_dim].nunique() if bar_dim in df.columns else 0, original_n)
rows = df.to_dict(orient="records")
max_abs = float(df["value"].abs().max()) if "value" in df.columns else None
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
color_enc = (
_color_encoding(result.color_dim)
if result.color_dim
else {"value": WB_CAT_COLORS[0]}
)
# The Y-axis already labels the rows; the legend is purely redundant.
if isinstance(color_enc, dict) and "field" in color_enc:
color_enc["legend"] = None
x_title = _resolve_axis_title(x_label, indicator_name)
x_ax = {
**_axis_style(),
"title": x_title,
"labelExpr": _value_label_expr(unit_measure),
}
spec: dict = {
"$schema": _vl_schema(),
"title": title,
"data": {"values": rows},
"mark": {
"type": "bar",
"cornerRadiusTopRight": 3,
"cornerRadiusBottomRight": 3,
},
"encoding": {
"y": {
"field": "country",
"type": "nominal",
"sort": "-x",
"axis": {
"title": None,
"labelColor": WB_TEXT,
"labelFontWeight": "bold",
"labelLimit": 150,
},
},
"x": {
"field": "value",
"type": "quantitative",
"axis": x_ax,
"scale": {"zero": True},
},
"color": color_enc,
"tooltip": build_structured_tooltips(
list(df.columns),
"bar",
indicator_labels,
value_format=tt_fmt,
indicator_name=indicator_name,
),
},
"width": 500,
"height": max(180, len(df) * 28),
}
return inject_wb_config(spec)
def build_distribution_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
x_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Strip/beeswarm: 1 indicator, >8 countries, single year."""
df, original_n = _cap_cardinality(
df.sort_values("value", ascending=False),
"country",
HIGH_CARDINALITY_THRESHOLDS["top_n_series"],
)
title = _append_trim_note(title, "country", df["country"].nunique() if "country" in df.columns else 0, original_n)
rows = df.to_dict(orient="records")
max_abs = float(df["value"].abs().max()) if "value" in df.columns else None
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
spec: dict = {
"$schema": _vl_schema(),
"title": title,
"data": {"values": rows},
"mark": {"type": "bar", "cornerRadiusEnd": 3},
"encoding": {
"x": {
"field": "value",
"type": "quantitative",
"axis": {
**_axis_style(),
"title": x_label,
"labelExpr": _value_label_expr(unit_measure),
},
},
"y": {
"field": "country",
"type": "nominal",
"sort": "-x",
"axis": {
"title": None,
"labelColor": WB_TEXT,
"labelFontWeight": "bold",
"labelLimit": 160,
},
},
# No color encoding: position encodes rank clearly without a
# 15-20-entry legend that clutters the chart and confuses the reader.
"tooltip": build_structured_tooltips(
list(df.columns),
"bar",
indicator_labels,
value_format=tt_fmt,
indicator_name=indicator_name,
),
},
"width": 500,
"height": max(250, len(df) * 22),
}
return inject_wb_config(spec)
def build_breakdown_comparison_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
y_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Grouped bar: 1 indicator, 1 breakdown (sex/age/urban), 2-4 values, β€4 countries."""
rows = df.to_dict(orient="records")
color_dim = result.color_dim or "sex"
max_abs = float(df["value"].abs().max()) if "value" in df.columns else None
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
if color_dim == "sex":
domain = [k for k in WB_GENDER_COLORS if k in df[color_dim].unique()]
color_range = [WB_GENDER_COLORS[k] for k in domain]
color_scale = {"domain": domain, "range": color_range}
else:
color_scale = {"range": WB_CAT_COLORS}
x_field = "country" if df.get("country", pd.Series()).nunique() > 1 else "year"
if x_field == "year" and df.get("year", pd.Series()).nunique() <= 1:
x_field = color_dim
x_enc: dict
if x_field == "year":
x_enc = _x_temporal_encoding(result.temporal_frequency)
else:
x_enc = {
"field": x_field,
"type": "nominal",
"axis": {"title": None, "labelFontWeight": "bold"},
}
y_ax = {
**_axis_style(),
"title": None,
"labelExpr": _value_label_expr(unit_measure),
}
# Resolve a friendly legend title: prefer _TOOLTIP_SPECS label, fall back to title-cased field.
legend_title = _TOOLTIP_SPECS.get(color_dim, {}).get("title") or color_dim.replace("_", " ").title()
n_categories = df[x_field].nunique() if x_field in df.columns else 1
mark_spec: dict = {"type": "bar"}
if n_categories == 1:
mark_spec["size"] = 30
elif n_categories == 2:
mark_spec["size"] = 35
spec: dict = {
"$schema": _vl_schema(),
"title": title,
"data": {"values": rows},
"mark": mark_spec,
"encoding": {
"x": x_enc,
"y": {
"field": "value",
"type": "quantitative",
"axis": y_ax,
"scale": {"zero": True},
},
"color": {
"field": color_dim,
"type": "nominal",
"scale": color_scale,
"legend": {
"orient": "top",
"title": legend_title,
"labelLimit": 100,
"columns": 3,
},
},
"tooltip": build_structured_tooltips(
list(df.columns),
"bar",
indicator_labels,
value_format=tt_fmt,
),
},
"width": max(300, df[x_field].nunique() * 80),
"height": 320,
}
if x_field != color_dim:
spec["encoding"]["xOffset"] = {"field": color_dim, "type": "nominal"}
return inject_wb_config(spec)
def _group_breakdowns_by_scale(
df: pd.DataFrame,
breakdown_dim: str,
grouping_threshold: float = 0.75,
) -> list[list[str]]:
"""Cluster breakdown values into scale-compatible groups.
Groups breakdown series so that all members within a group can share a
Y-axis without any one series visually dominating the others. Series in
different groups will be rendered as separate panels.
Algorithm
---------
1. Compute ``log10(max |value|)`` for each breakdown value.
2. Sort breakdown values by this magnitude.
3. Greedily build groups: add the next value to the current group if the
group's magnitude span (max_mag β min_mag) stays within
*grouping_threshold*. Otherwise start a new group.
The default *grouping_threshold* of **0.75** (β5.6Γ difference max within
a group) is intentionally tighter than the detection threshold of 1.5
(β30Γ) used by :func:`_detect_scale_incompatibility`. This ensures that
within-group series are visually comparable on a shared Y-axis.
This function is **purely data-driven**: it does not use any hardcoded
dimension names, indicator codes, or external metadata. It works for any
indicator and any number of breakdown values.
Args:
df: DataFrame containing *breakdown_dim* and ``value`` columns.
breakdown_dim: Column containing breakdown series identifiers.
grouping_threshold: Maximum log10 span within a group. Default
``0.75`` β 5.6Γ β half the detection threshold.
Returns:
Ordered list of groups; each group is an ordered list of breakdown
value strings. Every unique non-null breakdown value appears in
exactly one group. Falls back to one singleton group per value if
computation fails.
"""
import math
bd_vals = sorted(
str(v) for v in df[breakdown_dim].dropna().unique()
) if breakdown_dim in df.columns else []
if len(bd_vals) <= 1:
return [bd_vals] if bd_vals else []
if "value" not in df.columns:
return [[v] for v in bd_vals]
# Compute log10(max|value|) for each breakdown value.
mags: dict[str, float] = {}
for v in bd_vals:
series = df.loc[df[breakdown_dim] == v, "value"].dropna()
if series.empty:
mags[v] = 0.0
continue
max_abs = float(series.abs().max())
mags[v] = math.log10(max_abs) if max_abs > 0 else 0.0
# Sort by magnitude then build groups greedily.
sorted_vals = sorted(bd_vals, key=lambda v: mags[v])
groups: list[list[str]] = []
current_group: list[str] = []
group_min_mag: float = 0.0
group_max_mag: float = 0.0
for v in sorted_vals:
mag = mags[v]
if not current_group:
current_group = [v]
group_min_mag = group_max_mag = mag
else:
new_min = min(group_min_mag, mag)
new_max = max(group_max_mag, mag)
if new_max - new_min <= grouping_threshold:
current_group.append(v)
group_min_mag = new_min
group_max_mag = new_max
else:
groups.append(current_group)
current_group = [v]
group_min_mag = group_max_mag = mag
if current_group:
groups.append(current_group)
return groups
def _get_label_differentiators(labels: list[str]) -> dict[str, str]:
"""Given a list of labels, extracts the unique differentiators by stripping common prefix/suffix."""
if not labels:
return {}
if len(labels) == 1:
return {labels[0]: labels[0]}
# Filter out non-strings or empty strings
valid_labels = [l for l in labels if isinstance(l, str) and l.strip()]
if len(valid_labels) <= 1:
return {l: l for l in labels}
# 1. Find longest common prefix
first = valid_labels[0]
prefix = ""
for i in range(1, len(first) + 1):
candidate = first[:i]
if all(l.startswith(candidate) for l in valid_labels):
prefix = candidate
else:
break
# Adjust prefix to end at a word boundary
if prefix:
ends_at_boundary = all(
l[len(prefix):].startswith((" ", ",", "-", "(", ")", "/", "[", "]", "{", "}")) or
prefix.endswith((" ", ",", "-", "(", ")", "/", "[", "]", "{", "}"))
for l in valid_labels
)
if not ends_at_boundary:
while prefix and not prefix[-1].isspace() and prefix[-1] not in (",", "-", "(", ")", "/", "[", "]", "{", "}"):
prefix = prefix[:-1]
# 2. Find longest common suffix
reversed_first = first[::-1]
suffix = ""
for i in range(1, len(reversed_first) + 1):
candidate = reversed_first[:i][::-1]
if all(l.endswith(candidate) for l in valid_labels):
suffix = candidate
else:
break
# Adjust suffix to start at a word boundary
if suffix:
starts_at_boundary = all(
l[:-len(suffix)].endswith((" ", ",", "-", "(", ")", "/", "[", "]", "{", "}")) or
suffix.startswith((" ", ",", "-", "(", ")", "/", "[", "]", "{", "}"))
for l in valid_labels
)
if not starts_at_boundary:
while suffix and not suffix[0].isspace() and suffix[0] not in (",", "-", "(", ")", "/", "[", "]", "{", "}"):
suffix = suffix[1:]
# Construct the differentiator mapping
mapping = {}
for l in labels:
if not isinstance(l, str):
mapping[l] = l
continue
shortened = l
if prefix:
shortened = shortened[len(prefix):]
if suffix:
shortened = shortened[:-len(suffix)]
# Clean up leading/trailing punctuation and whitespace
shortened = shortened.strip(",;.:-()[]{} ")
# If the differentiator is too short (or empty), fall back to original
if len(shortened) < 2:
mapping[l] = l
else:
# Capitalize first letter if it was lowercase
if shortened[0].islower():
shortened = shortened[0].upper() + shortened[1:]
mapping[l] = shortened
return mapping
def _truncate_panel_title(title_text: str | list[str], max_len: int = 35) -> str | list[str]:
if isinstance(title_text, list):
return [_truncate_panel_title(t, max_len) for t in title_text]
if not isinstance(title_text, str):
return title_text
if len(title_text) > max_len:
return title_text[:max_len-1].strip() + "\u2026"
return title_text
def _determine_small_multiples_columns(n_panels: int, year_count: int) -> int | None:
if n_panels <= 1:
return None
# Maximum of 2 columns. If year count is large (>10), we need wider panels. Keep columns to 1 or 2.
if year_count > 10:
return 1 if n_panels <= 3 else 2
return 2
def _build_scale_split_vconcat(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
y_label: str = "Value",
unit_measure: str | None = None,
grouping_threshold: float = 0.75,
force_separate_panels: bool = False,
indicator_name: str | None = None,
) -> dict:
"""Vconcat layout for scale-incompatible custom breakdowns.
Produces one full-width panel per **scale-compatible group** of breakdown
values. Groups are discovered automatically by
:func:`_group_breakdowns_by_scale` (data-driven, no hard-coded metadata).
Panel layout
------------
- **Single-member group** (680Γ140): one fixed-color line, panel title =
series label. Identical to the pre-grouping behaviour.
- **Multi-member group** (680Γ180): layered multi-series lines with Vega-Lite
``color`` encoding, a right-side legend, and a panel title listing the
member labels (truncated at 80 characters).
All panels share the X (year) axis via ``resolve.scale.x = 'shared'``.
X-axis labels are suppressed on all but the bottom panel.
The default *grouping_threshold* of 0.75 (β5.6Γ) is tighter than the
detection threshold of 1.5 (β30Γ), so within-group series are always
visually comparable on a shared Y-axis.
"""
facet_dim = result.facet_dim or "comp_breakdown_1"
lab = indicator_labels or {}
# Cap using the same threshold as regular small multiples.
df, original_n = _cap_cardinality(
df, facet_dim, HIGH_CARDINALITY_THRESHOLDS["small_multiples_max_facets"]
)
breakdown_vals = sorted(df[facet_dim].dropna().unique(), key=str)
# Extract unique differentiators for the breakdown/facet values to clean titles/legends (skip for countries)
if facet_dim != "country":
raw_bd_labels = [lab.get(v, v) for v in breakdown_vals]
diff_map = _get_label_differentiators(raw_bd_labels)
for v in breakdown_vals:
orig = lab.get(v, v)
if orig in diff_map:
lab[v] = diff_map[orig]
rows = df.to_dict(orient="records")
label_expr = _value_label_expr(unit_measure)
# Rebuild the context subtitle so it only names the countries actually shown,
# not the full pre-cap list that build_chart_title_with_context built earlier.
if original_n is not None and facet_dim == "country" and isinstance(title, dict):
existing_sub = title.get("subtitle", "")
if isinstance(existing_sub, str):
existing_sub = [p.strip() for p in existing_sub.split(" Β· ") if p.strip()]
shown_countries = sorted(df["country"].unique().tolist(), key=str.casefold)
# _year_range_label expects a Series. It's imported in viz_config.
from data360.viz_config import _year_range_label
year_lbl = _year_range_label(df["year"]) if "year" in df.columns else None
new_geo = ", ".join(shown_countries)
if year_lbl:
new_geo = f"{new_geo}, {year_lbl}"
title = {**title, "subtitle": [new_geo] + existing_sub[1:]}
annotated_title = _append_trim_note(
title, facet_dim,
len(breakdown_vals),
original_n,
)
# Discover scale-compatible groups from the data β no hard-coded logic.
if force_separate_panels:
# One panel per facet value, sorted alphabetically (standard facet behavior)
groups = [[v] for v in breakdown_vals]
else:
# Check if values are bounded percentages using unit measure / axis label declaration
is_pct_unit = False
if unit_measure and any(x in str(unit_measure).lower() for x in ["percent", "pct", "%"]):
is_pct_unit = True
elif y_label and any(x in str(y_label).lower() for x in ["percent", "pct", "%"]):
is_pct_unit = True
val_series = pd.to_numeric(df["value"], errors="coerce").dropna()
is_pct = is_pct_unit and not val_series.empty and val_series.max() <= 100.0 and val_series.min() >= 0.0
# Check if there is a fraction vs percent mismatch in the breakdown values:
same_numeric_scale = True
if is_pct:
maxes = []
for v in breakdown_vals:
s = pd.to_numeric(df.loc[df[facet_dim] == v, "value"], errors="coerce").dropna()
if not s.empty:
maxes.append(s.max())
if maxes:
any_gt_1 = any(m > 1.0 for m in maxes)
all_lte_1 = all(m <= 1.0 for m in maxes)
same_numeric_scale = any_gt_1 or all_lte_1
actual_threshold = float("inf") if (is_pct and same_numeric_scale) else grouping_threshold
groups = _group_breakdowns_by_scale(df, facet_dim, actual_threshold)
# GoG: when the color channel encodes a variable DIFFERENT from the facet variable
# (e.g. IPC phases within unit panels, or countries within WGI breakdown panels),
# the color mapping is identical in every panel β share the scale so Vega-Lite
# renders exactly one legend. When color and facet are the same variable (original
# single-country WGI) each panel has its own color domain β keep independent.
#
# For the cross-dim multi-member case (multi-country + multi-breakdown per panel),
# each panel gets its own combo-color domain (country shades Γ breakdowns in that
# group), so resolve must be "independent" there. We track this and override below.
color_resolve = (
"shared"
if result.color_dim and result.color_dim != facet_dim
else "independent"
)
# Pre-compute a globally sorted domain for the color dimension so that
# color assignments are deterministic and consistent across all panels.
# Without a pinned domain, Vega-Lite assigns colors by first-encounter order
# in the data, which depends on fetch ordering and can vary between runs.
_color_dim_domain: list[str] | None = (
sorted(df[result.color_dim].dropna().unique().tolist())
if result.color_dim and result.color_dim in df.columns
else None
)
# ββ Pre-compute legend layout and dynamic panel height ββββββββββββββββββββ
# Build the worst-case combo label list (most items any panel will show) so
# the layout helper can pick orient/direction/columns once for the whole spec.
_n_panels = len(groups)
if _n_panels == 1:
group = groups[0]
is_bar_chart = (df["year"].nunique() <= 1 if "year" in df.columns else True)
x_enc = _x_temporal_encoding(result.temporal_frequency)
if is_bar_chart:
x_enc["type"] = "nominal"
if "timeUnit" in x_enc:
del x_enc["timeUnit"]
if "axis" in x_enc and "format" in x_enc["axis"]:
del x_enc["axis"]["format"]
if len(group) == 1:
if result.color_dim and result.color_dim in df.columns:
x_enc["field"] = result.color_dim
else:
x_enc["field"] = facet_dim
if "axis" not in x_enc or x_enc["axis"] is None:
x_enc["axis"] = {}
x_enc["axis"].update({
"labelAngle": -45,
"labelAlign": "right",
"labelBaseline": "middle",
"labelLimit": 150,
"labelOverlap": False,
})
y_title = _resolve_axis_title(y_label, indicator_name)
y_axis = {
**_axis_style(),
"title": y_title,
"labelExpr": label_expr,
}
df_filtered = df[df[facet_dim].isin(group)].copy()
if len(group) == 1:
bd_val = group[0]
bd_label = lab.get(bd_val, bd_val)
bd_data = df_filtered[df_filtered[facet_dim] == bd_val]
max_abs = (
float(bd_data["value"].abs().max())
if "value" in bd_data.columns and not bd_data.empty
else None
)
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
if is_bar_chart:
mark_spec = {
"type": "bar",
"cornerRadiusTopRight": 2,
"cornerRadiusTopLeft": 2,
"size": 40,
}
else:
mark_spec = {
"type": "line",
"strokeWidth": 3,
"strokeCap": "round",
"point": _LINE_HOVER_POINT,
}
encoding = {
"x": x_enc,
"y": {
"field": "value",
"type": "quantitative",
"axis": y_axis,
"scale": {"zero": is_bar_chart},
},
"tooltip": build_structured_tooltips(
list(bd_data.columns),
"bar" if is_bar_chart else "line",
indicator_labels={**lab, "value": bd_label},
value_format=tt_fmt,
viz_data=bd_data,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
),
}
extra_transforms = []
if result.color_dim and result.secondary_color_dim:
_sec = result.secondary_color_dim
_pri = result.color_dim
sorted_secondary = sorted(df[_sec].dropna().unique().tolist()) if _sec in df.columns else []
sorted_primary = sorted(bd_data[_pri].dropna().unique().tolist()) if _pri in bd_data.columns else []
_s_combo_domain = [
f"{s} | {lab.get(p, p)}"
for s in sorted_secondary
for p in sorted_primary
]
_s_combo_range = []
for si, _country in enumerate(sorted_secondary):
base_color = WB_CAT_COLORS[si % len(WB_CAT_COLORS)]
_s_combo_range.extend(_generate_color_shades(base_color, len(sorted_primary)))
_s_combo_field = "_s_combo_label"
_s_combo_calc = {
"calculate": f"datum['{_sec}'] + ' | ' + datum['{_pri}']",
"as": _s_combo_field,
}
extra_transforms.append(_s_combo_calc)
_pri_title = result.dim_name_labels.get(_pri) or _pri.replace("_", " ").title()
_sec_title = result.dim_name_labels.get(_sec) or _sec.replace("_", " ").title()
_all_combo_labels = _s_combo_domain
_legend_layout = _compute_legend_layout(_all_combo_labels)
encoding["color"] = {
"field": _s_combo_field,
"type": "nominal",
"scale": {"domain": _s_combo_domain, "range": _s_combo_range},
"legend": {**_legend_layout, "title": f"{_sec_title} | {_pri_title}"},
}
elif result.color_dim:
n_items = bd_data[result.color_dim].nunique() if result.color_dim in bd_data.columns else 0
domain_labels = list(bd_data[result.color_dim].unique()) if result.color_dim in bd_data.columns else None
legend_title = result.dim_name_labels.get(result.color_dim)
encoding["color"] = _color_encoding(
result.color_dim,
mark_type="bar" if is_bar_chart else "line",
n_items=n_items,
legend_title=legend_title,
domain_labels=domain_labels,
domain=_color_dim_domain,
)
else:
mark_spec["color"] = WB_CAT_COLORS[0]
else:
group_labels = [lab.get(v, v) for v in group]
max_abs = (
float(df_filtered["value"].abs().max())
if "value" in df_filtered.columns and not df_filtered.empty
else None
)
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
mark_spec = {
"type": "bar" if is_bar_chart else "line",
**(
{"cornerRadiusTopRight": 2, "cornerRadiusTopLeft": 2, "size": 40}
if is_bar_chart
else {"strokeWidth": 3, "strokeCap": "round", "point": _LINE_HOVER_POINT}
)
}
extra_transforms = []
if is_bar_chart and result.color_dim:
n_items = df_filtered[result.color_dim].nunique() if result.color_dim in df_filtered.columns else 0
domain_labels = list(df_filtered[result.color_dim].unique()) if result.color_dim in df_filtered.columns else None
legend_title = result.dim_name_labels.get(result.color_dim)
encoding = {
"x": x_enc,
"y": {
"field": "value",
"type": "quantitative",
"axis": y_axis,
"scale": {"zero": is_bar_chart},
},
"color": _color_encoding(
result.color_dim,
mark_type="bar",
n_items=n_items,
legend_title=legend_title,
domain_labels=domain_labels,
domain=_color_dim_domain,
),
"tooltip": build_structured_tooltips(
list(df_filtered.columns),
"bar",
indicator_labels=lab,
value_format=tt_fmt,
viz_data=df_filtered,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
),
}
elif result.color_dim and result.color_dim != facet_dim:
sorted_countries = sorted(df[result.color_dim].dropna().unique().tolist())
combo_domain = [
f"{c} | {lab.get(bd, bd)}"
for c in sorted_countries
for bd in group
]
combo_range = []
for ci, country in enumerate(sorted_countries):
base_color = WB_CAT_COLORS[ci % len(WB_CAT_COLORS)]
combo_range.extend(_generate_color_shades(base_color, len(group)))
_combo_field = "_combo_label"
_combo_calc = {
"calculate": f"datum['{result.color_dim}'] + ' | ' + datum['{facet_dim}']",
"as": _combo_field,
}
extra_transforms.append(_combo_calc)
_country_title = result.dim_name_labels.get(result.color_dim) or result.color_dim.title()
_bd_title = result.dim_name_labels.get(facet_dim) or facet_dim.title()
_all_combo_labels = combo_domain
_legend_layout = _compute_legend_layout(_all_combo_labels)
encoding = {
"x": x_enc,
"y": {
"field": "value",
"type": "quantitative",
"axis": y_axis,
"scale": {"zero": is_bar_chart},
},
"color": {
"field": _combo_field,
"type": "nominal",
"scale": {"domain": combo_domain, "range": combo_range},
"legend": {**_legend_layout, "title": f"{_country_title} | {_bd_title}"},
},
"tooltip": build_structured_tooltips(
list(df_filtered.columns),
"bar" if is_bar_chart else "line",
indicator_labels=lab,
value_format=tt_fmt,
viz_data=df_filtered,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
),
}
else:
group_colors = [
WB_CAT_COLORS[j % len(WB_CAT_COLORS)]
for j in range(len(group))
]
encoding = {
"x": x_enc,
"y": {
"field": "value",
"type": "quantitative",
"axis": y_axis,
"scale": {"zero": is_bar_chart},
},
"color": {
"field": facet_dim,
"type": "nominal",
"scale": {
"domain": group,
"range": group_colors,
},
"legend": {
"orient": "bottom" if max((len(lbl) for lbl in group_labels), default=0) > 40 else "right",
"labelFontSize": 11,
"symbolSize": 80,
**(
{"labelLimit": 0, "direction": "vertical"}
if max((len(lbl) for lbl in group_labels), default=0) > 40
else {"labelLimit": 200}
),
},
},
"tooltip": build_structured_tooltips(
list(df_filtered.columns),
"bar" if is_bar_chart else "line",
indicator_labels=lab,
value_format=tt_fmt,
viz_data=df_filtered,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
),
}
effective_color_dim = facet_dim if len(group) > 1 else result.color_dim
n_series = df_filtered[effective_color_dim].nunique() if (effective_color_dim and effective_color_dim in df_filtered.columns) else 0
needs_end_labels = (
not is_bar_chart
and effective_color_dim
and 2 <= n_series <= MAX_END_LABEL_SERIES
and "year" in df_filtered.columns
)
if needs_end_labels:
df_filtered = _adjust_end_label_y(df_filtered, effective_color_dim)
rows = df_filtered.to_dict(orient="records")
spec = {
"$schema": _vl_schema(),
"title": annotated_title,
"data": {"values": rows},
"mark": mark_spec,
"encoding": encoding,
"width": 600,
"height": 350,
}
if extra_transforms:
spec["transform"] = extra_transforms
needs_zero_line = (
not is_bar_chart
and "value" in df_filtered.columns
and df_filtered["value"].min() < 0 < df_filtered["value"].max()
)
# If bar offset is needed
if is_bar_chart and result.color_dim and result.color_dim in df_filtered.columns:
if encoding.get("x", {}).get("field") != result.color_dim:
encoding["xOffset"] = {"field": result.color_dim, "type": "nominal"}
if needs_zero_line or needs_end_labels:
main_layer = {"mark": spec.pop("mark"), "encoding": spec.pop("encoding")}
if needs_end_labels:
if "color" in main_layer["encoding"] and isinstance(main_layer["encoding"]["color"], dict):
main_layer["encoding"]["color"]["legend"] = None
layers = [main_layer]
if needs_zero_line:
zero_layer = {
"mark": {
"type": "rule",
"color": "#999999",
"strokeWidth": 1.0,
"strokeDash": [4, 3],
"opacity": 0.8,
"tooltip": False,
},
"encoding": {"y": {"datum": 0}},
}
layers.append(zero_layer)
if needs_end_labels:
year_type = "temporal" if df_filtered["year"].dtype == "datetime64[ns]" else "ordinal"
end_label_layer = {
"transform": [
{
"aggregate": [
{"op": "argmax", "field": "year", "as": "_last"}
],
"groupby": [effective_color_dim],
},
{
"calculate": "datum._last._label_y",
"as": "_end_value",
},
{
"calculate": "datum._last.year",
"as": "_end_year",
},
],
"mark": {
"type": "text",
"align": "left",
"dx": 5,
"fontSize": 10,
"fontWeight": "normal",
"tooltip": False,
},
"encoding": {
"x": {"field": "_end_year", "type": year_type},
"y": {"field": "_end_value", "type": "quantitative"},
"text": {"field": effective_color_dim, "type": "nominal"},
"color": encoding.get("color", {}),
},
}
layers.append(end_label_layer)
spec["layer"] = layers
return inject_wb_config(spec)
_legend_target_total_px = 850 # desired total figure height in pixels
_base_single_px = 240 # default single-member panel height
_base_multi_px = 300 # default multi-member panel height
if result.color_dim and (result.color_dim != facet_dim or result.secondary_color_dim):
# Combo path (Case B / secondary_color_dim): compute worst-case labels.
_sec_dim = result.secondary_color_dim # e.g. "country" or None
_pri_dim = result.color_dim # e.g. "comp_breakdown_2" or country
if _sec_dim:
# secondary_color_dim path: country | breakdown
_sorted_sec = sorted(df[_sec_dim].dropna().unique().tolist())
_sorted_pri = sorted(df[_pri_dim].dropna().unique().tolist())
_all_combo_labels = [
f"{s} | {lab.get(p, p)}"
for s in _sorted_sec
for p in _sorted_pri
]
else:
# Case B multi-member: country | breakdown per panel β largest group
_sorted_countries = sorted(df[_pri_dim].dropna().unique().tolist())
_max_group = max(groups, key=len) if groups else []
_all_combo_labels = [
f"{c} | {lab.get(bd, bd)}"
for c in _sorted_countries
for bd in _max_group
]
_legend_layout = _compute_legend_layout(_all_combo_labels)
_legend_h = _estimate_legend_height(len(_all_combo_labels), _legend_layout, has_title=True)
_panel_h_single = max(80, (_legend_target_total_px - _legend_h) // _n_panels)
_panel_h_multi = max(100, (_legend_target_total_px - _legend_h) // _n_panels)
else:
# No combo: use a small legend and default panel heights.
_legend_layout = _compute_legend_layout([])
_legend_h = 0
_panel_h_single = _base_single_px
_panel_h_multi = _base_multi_px
is_multi_panel = len(groups) > 1
panel_width = 280 if is_multi_panel else 680
if is_multi_panel:
_panel_h_single = 200
_panel_h_multi = 220
is_bar_chart = (df["year"].nunique() <= 1 if "year" in df.columns else True)
charts: list[dict] = []
color_offset = 0 # global color index so adjacent panels never share a colour
for g_idx, group in enumerate(groups):
is_last_panel = g_idx == len(groups) - 1
x_enc = _x_temporal_encoding(result.temporal_frequency)
if is_bar_chart:
x_enc["type"] = "nominal"
if "timeUnit" in x_enc:
del x_enc["timeUnit"]
if "axis" in x_enc and "format" in x_enc["axis"]:
del x_enc["axis"]["format"]
# Map single-year snapshot charts to use a categorical/varying dimension as the x-axis field
if len(group) == 1:
if result.color_dim and result.color_dim in df.columns:
x_enc["field"] = result.color_dim
else:
x_enc["field"] = facet_dim
if "axis" not in x_enc or x_enc["axis"] is None:
x_enc["axis"] = {}
x_enc["axis"].update({
"labelAngle": -45,
"labelAlign": "right",
"labelBaseline": "middle",
"labelLimit": 150,
"labelOverlap": False,
})
if not is_last_panel and not is_multi_panel:
x_enc = {**x_enc, "axis": {**x_enc.get("axis", {}), "labels": False, "title": None}}
y_axis = {**_axis_style(), "title": None, "labelExpr": label_expr}
if len(group) == 1:
# ----------------------------------------------------------------
# Single-member group β identical to pre-grouping behaviour.
# ----------------------------------------------------------------
bd_val = group[0]
color = WB_CAT_COLORS[color_offset % len(WB_CAT_COLORS)]
color_offset += 1
bd_label = lab.get(bd_val, bd_val)
bd_data = df[df[facet_dim] == bd_val]
max_abs = (
float(bd_data["value"].abs().max())
if "value" in bd_data.columns and not bd_data.empty
else None
)
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
if is_bar_chart:
mark_spec = {
"type": "bar",
"cornerRadiusTopRight": 2,
"cornerRadiusTopLeft": 2,
"size": 40,
}
else:
mark_spec = {
"type": "line",
"strokeWidth": 3,
"strokeCap": "round",
"point": _LINE_HOVER_POINT,
}
chart_enc = {
"x": x_enc,
"y": {
"field": "value",
"type": "quantitative",
"axis": y_axis,
"scale": {"zero": False},
},
"tooltip": build_structured_tooltips(
list(bd_data.columns),
"line",
indicator_labels={**lab, "value": bd_label},
value_format=tt_fmt,
viz_data=bd_data,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
),
}
if result.color_dim and result.secondary_color_dim:
# 3-way encoding: facet_dim=unit_measure, color_dim=breakdown,
# secondary_color_dim=country β combo shade families per panel.
# Format: "{country} | {breakdown}" β country is primary (base color),
# breakdown is secondary (shade within country family).
_sec = result.secondary_color_dim # country
_pri = result.color_dim # comp_breakdown_2
sorted_secondary = sorted(
df[_sec].dropna().unique().tolist()
) if _sec in df.columns else []
sorted_primary = sorted(
bd_data[_pri].dropna().unique().tolist()
) if _pri in bd_data.columns else []
# Domain: grouped by country first, then breakdown within each country.
_s_combo_domain: list[str] = [
f"{s} | {lab.get(p, p)}"
for s in sorted_secondary # country = outer loop
for p in sorted_primary # breakdown = inner loop
]
# Color: each country gets a base color, breakdowns get shades.
_s_combo_range: list[str] = []
for si, _country in enumerate(sorted_secondary):
base_color = WB_CAT_COLORS[si % len(WB_CAT_COLORS)]
_s_combo_range.extend(_generate_color_shades(base_color, len(sorted_primary)))
_s_combo_field = "_s_combo_label"
_s_combo_calc = {
"calculate": f"datum['{_sec}'] + ' | ' + datum['{_pri}']",
"as": _s_combo_field,
}
_pri_title = result.dim_name_labels.get(_pri) or _pri.replace("_", " ").title()
_sec_title = result.dim_name_labels.get(_sec) or _sec.replace("_", " ").title()
# Show legend only on the last panel so it appears once at the bottom.
_s_legend: dict | None = (
{**_legend_layout, "title": f"{_sec_title} | {_pri_title}"}
if is_last_panel
else None
)
chart_enc["color"] = {
"field": _s_combo_field,
"type": "nominal",
"scale": {"domain": _s_combo_domain, "range": _s_combo_range},
"legend": _s_legend,
}
charts.append({
"title": {
"text": _truncate_panel_title(bd_label),
"fontSize": 12,
"fontWeight": "bold",
"anchor": "start",
"offset": 4,
},
"width": panel_width,
"height": _panel_h_single,
"transform": [
_s_combo_calc,
{"filter": {"field": facet_dim, "equal": bd_val}},
],
"mark": mark_spec,
"encoding": chart_enc,
})
continue # skip the generic charts.append below
elif result.color_dim:
n_items = (
bd_data[result.color_dim].nunique()
if result.color_dim in bd_data.columns
else 0
)
domain_labels_for_group = (
list(bd_data[result.color_dim].unique())
if result.color_dim and result.color_dim in bd_data.columns
else None
)
legend_title_for_group = result.dim_name_labels.get(result.color_dim) if result.color_dim else None
chart_enc["color"] = _color_encoding(
result.color_dim,
mark_type="line",
n_items=n_items,
legend_title=legend_title_for_group,
domain_labels=domain_labels_for_group,
domain=_color_dim_domain,
)
# Previously we suppressed legend on non-first panels when color_resolve
# == "shared" to reduce visual repetition. This breaks in chat embed
# contexts where panels scroll independently: users cannot scroll back to
# panel 0's legend when reading panel 2. Every panel must carry its own
# legend. The domain is pinned globally so colors are consistent.
else:
mark_spec["color"] = color
charts.append({
"title": {
"text": _truncate_panel_title(bd_label),
"color": color if not result.color_dim else None,
"fontSize": 12,
"fontWeight": "bold",
"anchor": "start",
"offset": 4,
},
"width": panel_width,
"height": _panel_h_single,
"transform": [{"filter": {"field": facet_dim, "equal": bd_val}}],
"mark": mark_spec,
"encoding": chart_enc,
})
else:
# ----------------------------------------------------------------
# Multi-member group β layered lines, shared Y-axis, color legend.
# ----------------------------------------------------------------
group_labels = [lab.get(v, v) for v in group]
import textwrap as _textwrap
joined = ", ".join(group_labels)
wrapped = _textwrap.wrap(joined, width=100)
if len(wrapped) > 2:
wrapped = wrapped[:2]
wrapped[-1] = wrapped[-1].rstrip(",") + "\u2026"
panel_title: str | list[str] = wrapped if len(wrapped) > 1 else (wrapped[0] if wrapped else joined)
group_data = df[df[facet_dim].isin(group)]
max_abs = (
float(group_data["value"].abs().max())
if "value" in group_data.columns and not group_data.empty
else None
)
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
# Two rendering modes for multi-member groups:
# A. color_dim IS the facet_dim (or color_dim is None):
# Original WGI single-country case β color by breakdown value within panel.
# B. color_dim != facet_dim (e.g. multi-country WGI, color=country):
# Cross-dimension case β shade families per country.
# Georgia gets N shades of blue (darkβlight per breakdown),
# UK gets N shades of orange. A single color channel encodes
# both dimensions; strokeDash is dropped entirely.
_panel_extra_transforms: list[dict] = [] # e.g. calculate for combo field
if result.color_dim and result.color_dim != facet_dim:
# Case B: combo color families β format "{country} | {breakdown}".
# Country (color_dim) is the primary grouping (base color family).
# Breakdown values (facet_dim items in this group) are shades.
sorted_countries = sorted(
df[result.color_dim].dropna().unique().tolist()
)
# Domain: all countryΓbreakdown combos, grouped by country first.
combo_domain: list[str] = [
f"{c} | {lab.get(bd, bd)}"
for c in sorted_countries
for bd in group
]
# Range: each country gets N shades (darkβlight per breakdown).
combo_range: list[str] = []
for ci, country in enumerate(sorted_countries):
base_color = WB_CAT_COLORS[ci % len(WB_CAT_COLORS)]
combo_range.extend(_generate_color_shades(base_color, len(group)))
# Vega-Lite calculate: "{country} | {breakdown_value}".
_combo_field = "_combo_label"
_combo_calc = {
"calculate": (
f"datum['{result.color_dim}'] + ' | ' + datum['{facet_dim}']"
),
"as": _combo_field,
}
_country_title = (
result.dim_name_labels.get(result.color_dim, result.color_dim.title())
)
_bd_title = (
result.dim_name_labels.get(facet_dim, facet_dim.title())
)
# Show legend only on the last panel.
combo_legend: dict | None = (
{**_legend_layout, "title": f"{_country_title} | {_bd_title}"}
if is_last_panel
else None
)
panel_encoding: dict = {
"x": x_enc,
"y": {
"field": "value",
"type": "quantitative",
"axis": y_axis,
"scale": {"zero": False},
},
"color": {
"field": _combo_field,
"type": "nominal",
"scale": {"domain": combo_domain, "range": combo_range},
"legend": combo_legend,
},
"tooltip": build_structured_tooltips(
list(group_data.columns),
"line",
indicator_labels=lab,
value_format=tt_fmt,
viz_data=group_data,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
),
}
# Add the combo calculate to this panel's transforms.
_panel_extra_transforms = [_combo_calc]
else:
# Case A: original β color by the breakdown value within the panel.
group_colors = [
WB_CAT_COLORS[(color_offset + j) % len(WB_CAT_COLORS)]
for j in range(len(group))
]
color_offset += len(group)
panel_encoding = {
"x": x_enc,
"y": {
"field": "value",
"type": "quantitative",
"axis": y_axis,
"scale": {"zero": False},
},
"color": {
"field": facet_dim,
"type": "nominal",
"scale": {
"domain": group,
"range": group_colors,
},
"legend": {
"orient": "bottom" if max((len(lbl) for lbl in group_labels), default=0) > 40 else "right",
"labelFontSize": 11,
"symbolSize": 80,
**(
{"labelLimit": 0, "direction": "vertical"}
if max((len(lbl) for lbl in group_labels), default=0) > 40
else {"labelLimit": 200}
),
},
},
"tooltip": build_structured_tooltips(
list(group_data.columns),
"bar" if is_bar_chart else "line",
indicator_labels=lab,
value_format=tt_fmt,
viz_data=group_data,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
),
}
charts.append({
"title": {
"text": _truncate_panel_title(panel_title),
"fontSize": 12,
"fontWeight": "bold",
"anchor": "start",
"offset": 4,
},
"width": panel_width,
"height": _panel_h_multi,
# Extra transforms (e.g. calculate for combo field) must come
# BEFORE the filter so the calculated field is available.
"transform": _panel_extra_transforms + [{"filter": {"field": facet_dim, "oneOf": group}}],
"mark": {
"type": "bar" if is_bar_chart else "line",
**(
{"cornerRadiusTopRight": 2, "cornerRadiusTopLeft": 2, "size": 40}
if is_bar_chart
else {"strokeWidth": 3, "strokeCap": "round", "point": _LINE_HOVER_POINT}
)
},
"encoding": panel_encoding,
})
x_resolve = "independent" if is_bar_chart else "shared"
spec: dict = {
"$schema": _vl_schema(),
"title": annotated_title,
"data": {"values": rows},
"resolve": {"scale": {"x": x_resolve, "color": color_resolve}},
"autosize": {"type": "fit", "contains": "padding"},
}
if is_bar_chart:
spec["padding"] = {"top": 10, "left": 10, "bottom": 110, "right": 10}
# Always use concat to avoid Vega-Lite layout bugs in vertical concatenation (vconcat)
# where rotated labels on the bottom-most panel get clipped.
spec["concat"] = charts
if is_multi_panel:
year_cnt = df["year"].nunique() if "year" in df.columns else 1
spec["columns"] = _determine_small_multiples_columns(len(groups), year_cnt)
# Optimize shared legend positioning and layout for high cardinality
color_dim = result.color_dim
if color_dim and color_dim in df.columns:
n_items = df[color_dim].nunique()
if n_items > 4:
cols = min(5, (n_items + 1) // 2)
spec["config"] = {
"legend": {
"orient": "bottom",
"direction": "horizontal",
"columns": cols,
"title": result.dim_name_labels.get(color_dim, color_dim.replace("_", " ").title()) if result.dim_name_labels else color_dim.replace("_", " ").title(),
"labelLimit": 200,
}
}
else:
spec["columns"] = 1
return inject_wb_config(spec)
def build_small_multiples_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
y_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Faceted small multiples: 1 indicator, 2+ breakdowns or breakdown+many countries.
Facet panels are capped at HIGH_CARDINALITY_THRESHOLDS["small_multiples_max_facets"]
via the shared :func:`_cap_cardinality` utility. When trimmed, the top-N facet
values by most-recent data point are retained and a subtitle note is injected via
:func:`_append_trim_note` β the same logic used by build_cross_sectional_spec.
When ``result.scale_incompatible`` is True, delegates to
:func:`_build_scale_split_vconcat` which produces one full-width vertically
stacked panel per breakdown value, each with an independent Y-axis. This
prevents scale-dominant series from compressing smaller ones on a shared axis.
"""
facet_dim = result.facet_dim or "comp_breakdown_1"
color_dim = result.color_dim
# Redirect exactly 2 scale-incompatible indicators for a single country to the dual-axis line chart
indicator_cols = result.indicator_cols or []
unique_inds = df["indicator"].dropna().unique().tolist() if "indicator" in df.columns else []
if not indicator_cols and len(unique_inds) == 2:
indicator_cols = unique_inds
country_cnt = df["country"].nunique() if "country" in df.columns else 0
is_bar = (result.mark_hint == "bar") or (df["year"].nunique() <= 1 if "year" in df.columns else True)
if len(indicator_cols) == 2 and country_cnt <= 1 and not is_bar:
try:
clean_labels = {}
if indicator_labels:
clean_labels = {
_clean_label_generic(k): _clean_label_generic(v)
for k, v in indicator_labels.items()
}
maxes = {}
for ind in indicator_cols:
clean_ind = _clean_label_generic(ind)
pretty_val = clean_labels.get(clean_ind, clean_ind)
if ind in df.columns:
vals = df[ind].dropna().abs()
elif pretty_val in df.columns:
vals = df[pretty_val].dropna().abs()
elif "indicator" in df.columns:
vals = df[df["indicator"].map(lambda x: _clean_label_generic(x) if isinstance(x, str) else x).isin([clean_ind, pretty_val])]["value"].dropna().abs()
else:
vals = pd.Series(dtype=float)
maxes[ind] = vals.max() if not vals.empty else 0.0
nz_maxes = [m for m in maxes.values() if m > 0]
is_incompatible = False
if len(nz_maxes) == 2:
ratio = max(nz_maxes) / min(nz_maxes)
if ratio > 10.0:
is_incompatible = True
except Exception:
is_incompatible = False
if is_incompatible:
if "indicator" in df.columns and "value" in df.columns:
index_cols = [c for c in df.columns if c not in ("indicator", "value")]
wide_df = df.pivot_table(index=index_cols, columns="indicator", values="value", aggfunc="mean").reset_index()
wide_df.columns.name = None
temp_indicator_cols = [c for c in wide_df.columns if c not in index_cols]
else:
wide_df = df
temp_indicator_cols = indicator_cols
from data360.viz_config import build_temporal_multi_indicator_spec, StrategyResult, ChartStrategy
temp_result = StrategyResult(
strategy=ChartStrategy.TEMPORAL_MULTI_IND,
reason=result.reason,
indicator_cols=temp_indicator_cols,
color_dim=result.color_dim,
facet_dim=result.facet_dim,
mark_hint=result.mark_hint,
scale_incompatible=result.scale_incompatible,
)
return build_temporal_multi_indicator_spec(
wide_df,
title,
temp_result,
indicator_labels=indicator_labels,
y_label=y_label,
unit_measure=unit_measure,
indicator_name=indicator_name,
)
# Auto-melt if called directly with a wide dataframe (e.g. in tests or simple API calls)
if (facet_dim == "indicator" or color_dim == "indicator") and "indicator" not in df.columns:
if result.indicator_cols:
df = df.copy()
id_cols = [c for c in df.columns if c not in result.indicator_cols]
df = df.melt(
id_vars=id_cols,
value_vars=result.indicator_cols,
var_name="indicator",
value_name="value",
)
# Map column names to pretty labels if indicator_labels is provided
if indicator_labels:
df["indicator"] = df["indicator"].map(lambda x: indicator_labels.get(x, x))
df = df.dropna(subset=["value"])
if facet_dim in df.columns:
df = df.copy()
df[facet_dim] = df[facet_dim].map(lambda x: _clean_label_generic(x) if isinstance(x, str) else x)
if indicator_labels:
indicator_labels = {
_clean_label_generic(k): _clean_label_generic(v)
for k, v in indicator_labels.items()
}
force_sep = result.scale_incompatible
# Force separation if faceting by indicator and coloring by another dimension (e.g. country)
if facet_dim == "indicator" and color_dim != "indicator" and not is_bar:
force_sep = True
# Force separation if faceting by country (never group countries into a single panel in small multiples)
elif facet_dim == "country":
force_sep = True
return _build_scale_split_vconcat(
df, title, result, indicator_labels, y_label, unit_measure,
force_separate_panels=force_sep,
indicator_name=indicator_name
)
def build_heatmap_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
y_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Heatmap chart: >8 countries, multi-year matrix."""
df, original_n = _cap_cardinality(df, "country", 50)
title = _append_trim_note(title, "country", df["country"].nunique() if "country" in df.columns else 0, original_n)
rows = df.to_dict(orient="records")
tt_fmt = _compute_tooltip_format(float(df["value"].abs().max()) if "value" in df.columns else None, unit_measure)
# Determine scheme based on values: divergent for mixed signs, sequential otherwise
has_negative = df["value"].min() < 0 if "value" in df.columns else False
scheme = "redblue" if has_negative else "yellowgreenblue"
# Compute explicit domain so Vega-Lite cannot infer a discrete/ordinal scale
# from the data shape. Without this, symbol legend entries are rendered for
# each unique float value instead of a continuous gradient.
val_series = pd.to_numeric(df["value"], errors="coerce").dropna() if "value" in df.columns else pd.Series(dtype=float)
if not val_series.empty:
val_min = float(val_series.min())
val_max = float(val_series.max())
if has_negative:
# Symmetric domain for diverging schemes so the midpoint is always 0.
abs_max = max(abs(val_min), abs(val_max))
color_domain = [-abs_max, abs_max]
else:
color_domain = [val_min, val_max]
else:
color_domain = [0, 1]
y_enc = {
"field": "country",
"type": "nominal",
"axis": {"title": None, "labelFontWeight": "bold"}
}
x_enc = _x_temporal_encoding(result.temporal_frequency)
color_enc = {
"field": "value",
"type": "quantitative",
# Explicit domain forces a continuous quantitative scale; without it
# Vega-Lite may fall back to an ordinal scale and render symbol swatches.
"scale": {"scheme": scheme, "domain": color_domain},
"legend": {
"type": "gradient",
"title": _resolve_axis_title(y_label, indicator_name),
"orient": "top",
"direction": "horizontal",
"gradientLength": 200,
# Explicit gradient stops mirror the domain so the legend
# colour bar matches the cell colours exactly.
"gradientThickness": 12,
"labelFontSize": 10,
},
}
spec: dict = {
"$schema": _vl_schema(),
"title": title,
"data": {"values": rows},
"mark": {"type": "rect", "tooltip": True},
"encoding": {
"x": x_enc,
"y": y_enc,
"color": color_enc,
"tooltip": build_structured_tooltips(
list(df.columns),
"rect",
indicator_labels,
value_format=tt_fmt,
viz_data=df,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
indicator_name=indicator_name,
)
},
"width": 600,
"height": {"step": 15},
# Override the global config.legend for heatmaps: the WB theme default
# does not include symbolType/gradientLength, causing Vega-Lite to
# render a symbol swatch legend when the global config is merged in.
"config": {
"legend": {
"symbolType": "square",
}
},
}
if result.facet_dim:
spec["facet"] = {
"field": result.facet_dim,
"type": "nominal",
"columns": 2,
"header": {"title": None, "labelFontWeight": "bold"}
}
spec["spec"] = {
"mark": {"type": "rect", "tooltip": True},
"encoding": spec.pop("encoding"),
"width": 250,
"height": {"step": 15}
}
del spec["mark"]
del spec["width"]
del spec["height"]
return inject_wb_config(spec)
def build_choropleth_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
y_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Choropleth map chart: single indicator, geographic display."""
# Maps display a single point in time. If data is multi-year, filter to the latest year.
year_count = df["year"].nunique() if "year" in df.columns else 0
if year_count > 1:
latest_year = df["year"].max()
df = df[df["year"] == latest_year].copy()
# Ensure title dict structure
if isinstance(title, str):
title = {"text": title}
subs = title.get("subtitle", [])
if isinstance(subs, str):
subs = [subs]
subs.append(f"Note: Map displays data for the most recent year ({latest_year})")
title["subtitle"] = subs
# Map World Bank country names to World Atlas TopoJSON names.
# The TopoJSON uses English common names that differ from WB official names.
# Entries here prevent lookup misses that leave countries uncolored.
if "country" in df.columns:
_WORLD_ATLAS_NAME_MAP = {
# Americas
"United States": "United States of America",
"Venezuela, RB": "Venezuela",
"Bolivia": "Bolivia",
"Trinidad and Tobago": "Trinidad and Tobago",
"Bahamas, The": "Bahamas",
"Gambia, The": "Gambia",
# Europe & Central Asia
"Russian Federation": "Russia",
"Slovak Republic": "Slovakia",
"Czech Republic": "Czechia",
"Kyrgyz Republic": "Kyrgyzstan",
"Turkiye": "Turkey",
"North Macedonia": "Macedonia",
"Bosnia and Herzegovina": "Bosnia and Herz.",
"Serbia": "Serbia",
"Kosovo": "Kosovo",
# Middle East & North Africa
"Egypt, Arab Rep.": "Egypt",
"Iran, Islamic Rep.": "Iran",
"Yemen, Rep.": "Yemen",
"West Bank and Gaza": "Palestine",
"Syrian Arab Republic": "Syria",
# East Asia & Pacific
"Korea, Rep.": "South Korea",
"Korea, Dem. People's Rep.": "North Korea",
"Viet Nam": "Vietnam",
"Lao PDR": "Laos",
"Brunei Darussalam": "Brunei",
"Timor-Leste": "East Timor",
"Micronesia, Fed. Sts.": "Micronesia",
"Solomon Islands": "Solomon Islands",
# Sub-Saharan Africa
"Congo, Dem. Rep.": "Dem. Rep. Congo",
"Congo, Rep.": "Congo",
"Cote d'Ivoire": "CΓ΄te d'Ivoire",
"Eswatini": "eSwatini",
"Tanzania": "United Republic of Tanzania",
"Cabo Verde": "Cape Verde",
"Sao Tome and Principe": "Sao Tome and Principe",
# South Asia
"Sri Lanka": "Sri Lanka",
}
df = df.copy()
df["country"] = df["country"].map(lambda x: _WORLD_ATLAS_NAME_MAP.get(x, x))
# Add a subtitle clarifying that gray areas are outside the selected set.
# This prevents the LLM judge from misinterpreting gray = missing/broken data.
if isinstance(title, str):
title = {"text": title, "subtitle": []}
subs = title.get("subtitle", [])
if isinstance(subs, str):
subs = [subs]
if not any("Gray" in s for s in subs):
subs.append("Gray: countries not in selected set or no data for this year.")
title["subtitle"] = subs
rows = df.to_dict(orient="records")
max_abs = float(df["value"].abs().max()) if "value" in df.columns else None
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
has_negative = df["value"].min() < 0 if "value" in df.columns else False
scheme = "redblue" if has_negative else "blues"
# Use TopoJSON as the main data so countries without data are still drawn (in gray)
spec: dict = {
"$schema": _vl_schema(),
"title": title,
"width": 800,
"height": 450,
"data": {
"url": "https://unpkg.com/world-atlas@2.0.2/countries-110m.json",
"format": {"type": "topojson", "feature": "countries"}
},
"transform": [
{
"lookup": "properties.name",
"from": {
"data": {"values": rows},
"key": "country",
"fields": list(df.columns)
}
}
],
"projection": {"type": "equalEarth"},
"layer": [
{
# Base layer: draw all countries in light gray
"mark": {"type": "geoshape", "fill": "#eee", "stroke": "white", "strokeWidth": 0.5}
},
{
# Data layer: color countries that have values
"mark": {"type": "geoshape", "stroke": "white", "strokeWidth": 0.5},
"transform": [{"filter": "isValid(datum.value)"}],
"encoding": {
"color": {
"field": "value",
"type": "quantitative",
"scale": {"scheme": scheme},
"legend": {
"title": _resolve_axis_title(y_label, indicator_name),
"orient": "bottom",
"direction": "horizontal",
"gradientLength": 300
}
},
"tooltip": build_structured_tooltips(
list(df.columns),
"geoshape",
indicator_labels,
value_format=tt_fmt,
dim_name_labels=result.dim_name_labels,
indicator_name=indicator_name,
)
}
}
]
}
return inject_wb_config(spec)
def build_stacked_area_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
y_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Stacked Area chart: multi-year, multiple series (part-to-whole)."""
color_dim = result.color_dim or "country"
# Fallback if mixed signs, as stacked area expects same-sign data
has_negative = df["value"].min() < 0 if "value" in df.columns else False
if has_negative:
return build_temporal_single_spec(df, title, result, indicator_labels, y_label, unit_measure)
df, original_n = _cap_cardinality(df, color_dim, HIGH_CARDINALITY_THRESHOLDS["line_max_series"])
annotated_title = _append_breakdown_note(title, df, color_dim)
annotated_title = _append_trim_note(annotated_title, color_dim, df[color_dim].nunique() if color_dim in df.columns else 0, original_n)
rows = df.to_dict(orient="records")
tt_fmt = _compute_tooltip_format(float(df["value"].abs().max()) if "value" in df.columns else None, unit_measure)
legend_title = _TOOLTIP_SPECS.get(color_dim, {}).get("title") or color_dim.replace("_", " ").title()
domain = sorted(df[color_dim].dropna().unique().tolist(), key=str) if color_dim in df.columns else None
spec: dict = {
"$schema": _vl_schema(),
"title": annotated_title,
"data": {"values": rows},
"mark": {"type": "area", "tooltip": True, "line": True, "opacity": 0.8},
"encoding": {
"x": _x_temporal_encoding(result.temporal_frequency),
"y": {
"field": "value",
"type": "quantitative",
"stack": "zero",
"axis": {**_axis_style(), "title": _resolve_axis_title(y_label, indicator_name), "labelExpr": _value_label_expr(unit_measure)}
},
"color": _color_encoding(color_dim, domain=domain, mark_type="area", legend_title=legend_title),
"tooltip": build_structured_tooltips(
list(df.columns),
"area",
indicator_labels,
value_format=tt_fmt,
viz_data=df,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
indicator_name=indicator_name,
)
},
"width": 600,
"height": 350
}
return inject_wb_config(spec)
def build_stacked_bar_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
y_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Stacked Bar chart (part-to-whole / snapshot comparisons)."""
color_dim = result.color_dim or "sex"
# For part-to-whole stacked bars (color_dim != "country"), all segments must be
# same-sign so the stack is readable. Redirect to grouped bar when values are mixed.
# For temporal stacked bars (color_dim == "country", x=year), negative values are
# valid β growth rates, balances, and returns commonly cross zero and Vega-Lite
# handles diverging stacks correctly.
has_negative = df["value"].min() < 0 if "value" in df.columns else False
if has_negative and color_dim != "country":
return build_breakdown_comparison_spec(df, title, result, indicator_labels, y_label, unit_measure, indicator_name)
df, original_n = _cap_cardinality(df, color_dim, HIGH_CARDINALITY_THRESHOLDS["line_max_series"])
annotated_title = _append_breakdown_note(title, df, color_dim)
annotated_title = _append_trim_note(annotated_title, color_dim, df[color_dim].nunique() if color_dim in df.columns else 0, original_n)
rows = df.to_dict(orient="records")
tt_fmt = _compute_tooltip_format(float(df["value"].abs().max()) if "value" in df.columns else None, unit_measure)
legend_title = _TOOLTIP_SPECS.get(color_dim, {}).get("title") or color_dim.replace("_", " ").title()
domain = sorted(df[color_dim].dropna().unique().tolist(), key=str) if color_dim in df.columns else None
if color_dim == "sex":
domain_colors = [k for k in WB_GENDER_COLORS if k in df[color_dim].unique()]
color_range = [WB_GENDER_COLORS[k] for k in domain_colors]
color_scale = {"domain": domain_colors, "range": color_range}
else:
color_scale = {"range": WB_CAT_COLORS}
if domain:
color_scale["domain"] = domain
# Determine x-axis field: it must differ from color_dim.
# color_dim encodes the stacking dimension (e.g. "country", "sex", "indicator").
# x encodes the primary categorical axis β typically "year" for temporal stacked bars
# or "country" for snapshot/breakdown comparisons.
#
# Rule: if color_dim == "country", x = "year" (temporal stacked bar, countries stacked).
# if color_dim == "year", x = "country" (shouldn't happen but guard it).
# otherwise, prefer "country" when multiple countries exist, else "year".
if df.get("year", pd.Series()).nunique() <= 1 and df.get("country", pd.Series()).nunique() <= 1:
x_field = color_dim
elif color_dim == "country":
x_field = "year" if df.get("year", pd.Series()).nunique() > 1 else "country"
elif color_dim == "year":
x_field = "country"
else:
x_field = "country" if df.get("country", pd.Series()).nunique() > 1 else "year"
if x_field == "year" and df.get("year", pd.Series()).nunique() <= 1:
x_field = "country"
x_enc: dict
if x_field == "year":
x_enc = _x_temporal_encoding(result.temporal_frequency)
else:
x_enc = {
"field": x_field,
"type": "nominal",
"axis": {"title": None, "labelFontWeight": "bold"},
}
n_categories = df[x_field].nunique() if x_field in df.columns else 1
mark_spec: dict = {"type": "bar", "tooltip": True}
if n_categories == 1:
mark_spec["size"] = 40
elif n_categories == 2:
mark_spec["size"] = 45
spec: dict = {
"$schema": _vl_schema(),
"title": annotated_title,
"data": {"values": rows},
"mark": mark_spec,
"encoding": {
"x": x_enc,
"y": {
"field": "value",
"type": "quantitative",
"stack": "zero",
"axis": {**_axis_style(), "title": _resolve_axis_title(y_label, indicator_name), "labelExpr": _value_label_expr(unit_measure)}
},
"color": {
"field": color_dim,
"type": "nominal",
"scale": color_scale,
"legend": {
"orient": "top",
"title": legend_title,
"labelLimit": 100,
"columns": 3,
},
},
"tooltip": build_structured_tooltips(
list(df.columns),
"bar",
indicator_labels,
value_format=tt_fmt,
viz_data=df,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
indicator_name=indicator_name,
)
},
"width": max(300, df[x_field].nunique() * 80),
"height": 320
}
return inject_wb_config(spec)
def build_correlation_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
indicator_name: str | None = None,
) -> dict:
"""Scatterplot: 2 indicators, single year, multi-country."""
ind_cols = result.indicator_cols
if len(ind_cols) < 2:
raise ValueError("correlation spec requires exactly 2 indicator columns")
x_col, y_col = ind_cols[0], ind_cols[1]
lab = indicator_labels or {}
x_label = lab.get(x_col, x_col.replace("_", " ").title())
y_label = lab.get(y_col, y_col.replace("_", " ").title())
df_clean = df.dropna(subset=[x_col, y_col]).copy()
if not df_clean.empty:
x_min, x_max = df_clean[x_col].min(), df_clean[x_col].max()
y_min, y_max = df_clean[y_col].min(), df_clean[y_col].max()
x_range = x_max - x_min if x_max != x_min else 1.0
y_range = y_max - y_min if y_max != y_min else 1.0
df_clean["_x_norm"] = (df_clean[x_col] - x_min) / x_range
df_clean["_y_norm"] = (df_clean[y_col] - y_min) / y_range
# Priority metric: distance from center (0.5, 0.5) to prioritize outliers/boundary points
df_clean["_dist_from_center"] = (df_clean["_x_norm"] - 0.5) ** 2 + (df_clean["_y_norm"] - 0.5) ** 2
# Sort descending by distance from center so outliers are labeled first
df_sorted = df_clean.sort_values(by="_dist_from_center", ascending=False)
labeled_points = []
show_labels = {}
# Collision thresholds: 6% horizontal width, 4% vertical height
EPSILON_X = 0.06
EPSILON_Y = 0.04
for idx, row in df_sorted.iterrows():
x_n = row["_x_norm"]
y_n = row["_y_norm"]
collision = False
for lx, ly in labeled_points:
if abs(x_n - lx) < EPSILON_X and abs(y_n - ly) < EPSILON_Y:
collision = True
break
if not collision:
show_labels[idx] = True
labeled_points.append((x_n, y_n))
else:
show_labels[idx] = False
df_clean["_show_label"] = df_clean.index.map(show_labels)
else:
df_clean["_show_label"] = True
rows = df_clean.to_dict(orient="records")
color_dim = result.color_dim or "country"
color_enc = _color_encoding(color_dim)
# The legend is 100% redundant now because every dot has a direct text label.
# Direct labeling is superior in GoG as it prevents saccadic eye movement.
if isinstance(color_enc, dict) and "legend" in color_enc:
color_enc["legend"] = None
spec: dict = {
"$schema": _vl_schema(),
"title": title,
"data": {"values": rows},
"layer": [
{
"mark": {
"type": "circle",
"opacity": 0.85,
"stroke": WB_WHITE,
"strokeWidth": 1,
"size": 70
},
"encoding": {
"x": {
"field": x_col,
"type": "quantitative",
"axis": _axis_style(x_label),
"scale": {"zero": False},
},
"y": {
"field": y_col,
"type": "quantitative",
"axis": _axis_style(_resolve_axis_title(y_label, indicator_name)),
"scale": {"zero": False},
},
"color": color_enc,
"tooltip": build_structured_tooltips(
list(df.columns), "point", lab, viz_data=df
),
}
},
{
"mark": {
"type": "text",
"dy": -10,
"fontSize": 10,
"fontWeight": "bold"
},
"encoding": {
"x": {
"field": x_col,
"type": "quantitative"
},
"y": {
"field": y_col,
"type": "quantitative"
},
"text": {
"field": color_dim,
"type": "nominal"
},
"color": color_enc,
"opacity": {
"condition": {"test": "datum._show_label", "value": 1},
"value": 0
}
}
}
],
"width": 600,
"height": 450,
}
return inject_wb_config(spec)
def build_correlation_temporal_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
indicator_name: str | None = None,
) -> dict:
"""Connected scatterplot: 2 indicators, multi-country, multi-year."""
ind_cols = result.indicator_cols
if len(ind_cols) < 2:
raise ValueError("correlation_temporal spec requires 2 indicator columns")
x_col, y_col = ind_cols[0], ind_cols[1]
lab = indicator_labels or {}
x_label = lab.get(x_col, x_col.replace("_", " ").title())
y_label = lab.get(y_col, y_col.replace("_", " ").title())
rows = df.dropna(subset=[x_col, y_col]).to_dict(orient="records")
color_dim = result.color_dim or "country"
# Layer: lines + points
base_enc: dict = {
"x": {
"field": x_col,
"type": "quantitative",
"axis": _axis_style(x_label),
"scale": {"zero": False},
},
"y": {
"field": y_col,
"type": "quantitative",
"axis": _axis_style(y_label),
"scale": {"zero": False},
},
"color": _color_encoding(color_dim),
"order": {"field": "year", "type": "temporal"},
"tooltip": build_structured_tooltips(
list(df.columns), "line", lab, viz_data=df
),
}
spec: dict = {
"$schema": _vl_schema(),
"title": title,
"data": {"values": rows},
"layer": [
{
"mark": {"type": "line", "strokeWidth": 2, "opacity": 0.6},
"encoding": {k: v for k, v in base_enc.items() if k != "tooltip"},
},
{
"mark": {"type": "circle", "size": 40, "opacity": 0.9},
"encoding": base_enc,
},
],
"width": 550,
"height": 450,
}
return inject_wb_config(spec)
def build_temporal_multi_indicator_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
y_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Faceted (Small Multiples) multi-axis line chart: 2-4 indicators, multi-year.
Complies with Grammar of Graphics by strictly avoiding dual-axis overlapping.
Uses Vega-Lite `vconcat` to create vertically stacked charts that share a
common X-axis (time), giving each indicator its own isolated Y-axis plane.
"""
ind_cols = result.indicator_cols
if not ind_cols:
raise ValueError("temporal_multi_indicator spec requires indicator_cols")
lab = indicator_labels or {}
df_copy = df.copy()
# Determine if we should layer the indicators in a single panel instead of using vconcat
should_layer = False
fold_cols = [col for col in ind_cols if col in df_copy.columns]
if len(fold_cols) >= 2:
try:
max_vals = []
for col in fold_cols:
max_vals.append(df_copy[col].abs().max())
if len(max_vals) == len(fold_cols) and all(v is not None and not pd.isna(v) for v in max_vals):
max_val = max(max_vals)
min_val = min(max_vals)
# If both are valid positive values and scale difference is within 10x, layer them
if min_val > 0 and (max_val / min_val) <= 10.0:
should_layer = True
except Exception:
pass
if should_layer:
# Extract clean legend labels by stripping common prefix and suffix
raw_titles = [lab.get(col, col) for col in fold_cols]
col_to_legend = dict(zip(fold_cols, raw_titles))
if len(raw_titles) >= 2:
try:
import os
common_pref = os.path.commonprefix(raw_titles)
common_pref_stripped = common_pref.strip()
while common_pref_stripped and common_pref_stripped[-1] in (",", "-", " ", "|", ":", ";", "("):
common_pref_stripped = common_pref_stripped[:-1].strip()
temp_cleaned = []
for t in raw_titles:
part = t[len(common_pref):].strip()
while part and part[0] in (",", "-", " ", "|", ":", ";", "("):
part = part[1:].strip()
first_segment = part
for sep in (",", "(", " - ", " | "):
if sep in part:
candidate = part.split(sep)[0].strip()
if len(candidate) >= 3:
first_segment = candidate
break
temp_cleaned.append(first_segment.title())
if len(set(temp_cleaned)) == len(temp_cleaned) and all(len(x) >= 2 for x in temp_cleaned):
col_to_legend = dict(zip(fold_cols, temp_cleaned))
except Exception:
pass
# Determine y-axis title: if generic or defaults, try to use common prefix
final_y_label = y_label
if final_y_label in ("Value", "obs_value", None) or len(final_y_label) > 60:
try:
import os
common_pref = os.path.commonprefix(raw_titles)
common_pref_stripped = common_pref.strip()
while common_pref_stripped and common_pref_stripped[-1] in (",", "-", " ", "|", ":", ";", "("):
common_pref_stripped = common_pref_stripped[:-1].strip()
if len(common_pref_stripped) >= 8:
is_pct = any("%" in u.lower() or "percent" in u.lower() or "rate" in u.lower() or "share" in u.lower() for u in (unit_measure or "", *raw_titles))
if is_pct and not common_pref_stripped.endswith("(%)") and "%" not in common_pref_stripped:
final_y_label = f"{common_pref_stripped} (%)"
else:
final_y_label = common_pref_stripped
except Exception:
pass
# Melt to long format for single-panel multi-series visualization
melted_df = df_copy.melt(
id_vars=[c for c in df_copy.columns if c not in fold_cols],
value_vars=fold_cols,
var_name="indicator_name_melted",
value_name="indicator_value_melted",
)
# Apply friendly legend labels
melted_df["indicator_name_melted"] = melted_df["indicator_name_melted"].map(col_to_legend)
# Cast year to clean string
if "year" in melted_df.columns:
try:
parsed_years = pd.to_datetime(melted_df["year"].astype(str), errors="coerce")
if parsed_years.notna().any():
if result.temporal_frequency == "monthly":
melted_df["year"] = parsed_years.dt.strftime("%Y-%m")
else:
melted_df["year"] = parsed_years.dt.strftime("%Y")
else:
melted_df["year"] = melted_df["year"].astype(str)
except Exception:
melted_df["year"] = melted_df["year"].astype(str)
rows = melted_df.to_dict(orient="records")
label_expr = _value_label_expr(unit_measure)
x_enc = _x_temporal_encoding(result.temporal_frequency)
max_abs = float(melted_df["indicator_value_melted"].abs().max())
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
color_scale_range = WB_CAT_COLORS[:len(fold_cols)]
y_axis = {
**_axis_style(),
"title": final_y_label or "Value",
"labelExpr": label_expr,
}
tooltip_cols = ["year", "indicator_name_melted", "indicator_value_melted"]
if "country" in melted_df.columns:
tooltip_cols.append("country")
encoding = {
"x": x_enc,
"y": {
"field": "indicator_value_melted",
"type": "quantitative",
"axis": y_axis,
"scale": {"zero": False},
},
"color": {
"field": "indicator_name_melted",
"type": "nominal",
"scale": {
"range": color_scale_range
},
"legend": {
"title": None,
"orient": "bottom",
"offset": 12,
}
},
"tooltip": build_structured_tooltips(
tooltip_cols, "line", lab, value_format=tt_fmt, viz_data=melted_df,
temporal_freq=result.temporal_frequency,
dim_name_labels={
"indicator_name_melted": "Indicator",
"indicator_value_melted": "Value",
},
),
}
mark_spec = {
"type": "line",
"strokeWidth": 3,
"strokeCap": "round",
"point": _LINE_HOVER_POINT,
"tooltip": True
}
data_spec = {"values": rows}
if melted_df["year"].nunique() <= 1 if "year" in melted_df.columns else True:
data_spec["format"] = {"parse": {"year": "string"}}
# If there are multiple countries, facet/vconcat by country to prevent vertical zigzagging lines
if "country" in melted_df.columns and melted_df["country"].nunique() > 1:
countries = sorted(melted_df["country"].dropna().unique().tolist())
panels = []
for i, c in enumerate(countries):
# Clean x encoding: hide labels on top panels to avoid clutter
x_enc_panel = x_enc.copy()
if i < len(countries) - 1:
x_enc_panel = {**x_enc_panel, "axis": {**x_enc_panel.get("axis", {}), "labels": False, "title": None}}
panel = {
"title": {
"text": str(c),
"fontSize": 12,
"fontWeight": "bold",
"anchor": "start",
},
"transform": [{"filter": f"datum.country == '{c}'"}],
"width": 680,
"height": 180,
"mark": mark_spec,
"encoding": {
**encoding,
"x": x_enc_panel,
}
}
panels.append(panel)
spec = {
"$schema": _vl_schema(),
"title": title,
"data": data_spec,
"vconcat": panels,
"resolve": {
"scale": {"x": "shared"},
"axis": {"x": "independent"}
}
}
return inject_wb_config(spec)
return {
"$schema": _vl_schema(),
"title": title,
"data": data_spec,
"width": 680,
"height": 350,
"mark": mark_spec,
"encoding": encoding,
}
# Cast year to clean string format if present to avoid millisecond/integer formatting on nominal axes.
# We parse using pd.to_datetime first since the parent pipeline's JSON sanitizer
# converts datetime columns to ISO strings (like "2022-01-01T00:00:00") which need formatting.
if "year" in df_copy.columns:
try:
parsed_years = pd.to_datetime(df_copy["year"].astype(str), errors="coerce")
if parsed_years.notna().any():
if result.temporal_frequency == "monthly":
df_copy["year"] = parsed_years.dt.strftime("%Y-%m")
else:
df_copy["year"] = parsed_years.dt.strftime("%Y")
else:
df_copy["year"] = df_copy["year"].astype(str)
except Exception:
df_copy["year"] = df_copy["year"].astype(str)
rows = df_copy.to_dict(orient="records")
label_expr = _value_label_expr(unit_measure)
is_bar_chart = (result.mark_hint == "bar") or (df_copy["year"].nunique() <= 1 if "year" in df_copy.columns else True)
# If exactly 2 scale-incompatible indicators for a single country, use dual-axis layering
country_cnt = df_copy["country"].nunique() if "country" in df_copy.columns else 0
if len(ind_cols) == 2 and not should_layer and country_cnt <= 1 and not is_bar_chart:
chart0_color = WB_CAT_COLORS[0]
chart1_color = WB_CAT_COLORS[1]
col0 = ind_cols[0]
col1 = ind_cols[1]
col0_label = lab.get(col0, col0.replace("_", " ").title())
col1_label = lab.get(col1, col1.replace("_", " ").title())
max_abs0 = float(df_copy[col0].abs().max()) if col0 in df_copy.columns else None
max_abs1 = float(df_copy[col1].abs().max()) if col1 in df_copy.columns else None
tt_fmt0 = _compute_tooltip_format(max_abs0, unit_measure)
tt_fmt1 = _compute_tooltip_format(max_abs1, unit_measure)
if df_copy["year"].nunique() <= 1 if "year" in df_copy.columns else True:
x_enc = {
"field": "year" if "year" in df_copy.columns else "TIME_PERIOD",
"type": "nominal",
"axis": {"title": None}
}
else:
x_enc = _x_temporal_encoding(result.temporal_frequency)
layer0 = {
"mark": {
"type": "line",
"strokeWidth": 3,
"strokeCap": "round",
"point": _LINE_HOVER_POINT,
"color": chart0_color,
"tooltip": True
},
"encoding": {
"x": x_enc,
"y": {
"field": col0,
"type": "quantitative",
"axis": {
**_axis_style(),
"title": col0_label,
"titleColor": chart0_color,
"labelColor": chart0_color,
"labelExpr": label_expr,
},
"scale": {"zero": False}
},
"tooltip": build_structured_tooltips(
_multi_indicator_tooltip_columns(list(df_copy.columns), col0),
"line", lab, value_format=tt_fmt0, viz_data=df_copy,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
)
}
}
layer1 = {
"mark": {
"type": "line",
"strokeWidth": 3,
"strokeCap": "round",
"point": _LINE_HOVER_POINT,
"color": chart1_color,
"tooltip": True
},
"encoding": {
"x": x_enc,
"y": {
"field": col1,
"type": "quantitative",
"axis": {
**_axis_style(),
"title": col1_label,
"titleColor": chart1_color,
"labelColor": chart1_color,
"labelExpr": label_expr,
},
"scale": {"zero": False}
},
"tooltip": build_structured_tooltips(
_multi_indicator_tooltip_columns(list(df_copy.columns), col1),
"line", lab, value_format=tt_fmt1, viz_data=df_copy,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
)
}
}
data_spec = {"values": rows}
if df_copy["year"].nunique() <= 1 if "year" in df_copy.columns else True:
data_spec["format"] = {"parse": {"year": "string"}}
spec = {
"$schema": _vl_schema(),
"title": title,
"data": data_spec,
"width": 680,
"height": 350,
"layer": [layer0, layer1],
"resolve": {
"scale": {"y": "independent"}
}
}
return inject_wb_config(spec)
charts = []
for i, col in enumerate(ind_cols):
color = WB_CAT_COLORS[i % len(WB_CAT_COLORS)]
col_label = lab.get(col, col.replace("_", " ").title())
max_abs = float(df_copy[col].abs().max()) if col in df_copy.columns else None
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
y_axis = {
**_axis_style(),
"title": None, # Remove vertical Y-axis title
"labelExpr": label_expr,
}
# Handle X encoding: nominal for single-year to center label, temporal for multi-year trends
if df_copy["year"].nunique() <= 1 if "year" in df_copy.columns else True:
if df_copy["country"].nunique() > 1 if "country" in df_copy.columns else False:
x_enc = {
"field": "country",
"type": "nominal",
"axis": {"title": "Country"}
}
else:
x_enc = {
"field": "year" if "year" in df_copy.columns else "TIME_PERIOD",
"type": "nominal",
"axis": {"title": None}
}
else:
x_enc = _x_temporal_encoding(result.temporal_frequency)
# Only show X-axis labels on the bottom-most chart to reduce clutter
if i < len(ind_cols) - 1:
x_enc = {**x_enc, "axis": {**x_enc.get("axis", {}), "labels": False, "title": None}}
tooltip_cols = _multi_indicator_tooltip_columns(list(df_copy.columns), col)
# Color by country if there are multiple countries to draw distinct lines per country
if not is_bar_chart and "country" in df_copy.columns and df_copy["country"].nunique() > 1:
color_enc = {
"field": "country",
"type": "nominal",
"scale": {"range": WB_CAT_COLORS},
"legend": {
"title": None,
"orient": "bottom",
"offset": 12
} if i == len(ind_cols) - 1 else None # Only show legend on bottom-most chart
}
else:
color_enc = {"value": color}
layer_enc: dict = {
"x": x_enc,
"y": {
"field": col,
"type": "quantitative",
"axis": y_axis,
"scale": {"zero": is_bar_chart}, # Bars should zero-align
},
"color": color_enc,
"tooltip": build_structured_tooltips(
tooltip_cols, "bar" if is_bar_chart else "line", lab, value_format=tt_fmt, viz_data=df_copy,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
),
}
# Build clean mark dict depending on type
if is_bar_chart:
mark_spec = {
"type": "bar",
"color": color,
"size": 40, # Fixed width so bar doesn't stretch to fill full chart width
"tooltip": True
}
else:
mark_spec = {
"type": "line",
"strokeWidth": 3,
"strokeCap": "round",
"point": _LINE_HOVER_POINT,
"tooltip": True
}
# Only set constant color if not coloring by country
if not ("country" in df_copy.columns and df_copy["country"].nunique() > 1):
mark_spec["color"] = color
charts.append(
{
"title": {
"text": col_label,
"color": color,
"fontSize": 12,
"fontWeight": "bold",
"anchor": "start",
"offset": 4
},
"width": 680,
"height": 140, # Fixed height per small multiple
"mark": mark_spec,
"encoding": layer_enc,
}
)
data_spec: dict = {"values": rows}
if df_copy["year"].nunique() <= 1 if "year" in df_copy.columns else True:
data_spec["format"] = {"parse": {"year": "string"}}
spec: dict = {
"$schema": _vl_schema(),
"title": title,
"data": data_spec,
"vconcat": charts,
"resolve": {
"scale": {"x": "shared"},
"axis": {"x": "independent"}
},
}
return inject_wb_config(spec)
def build_fallback_line_spec(
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
y_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Fallback: best-effort line chart for unclassified data shapes."""
cols = set(df.columns)
x_col = (
"year"
if "year" in cols
else ("time_period" if "time_period" in cols else df.columns[0])
)
y_col = (
"value"
if "value" in cols
else ("obs_value" if "obs_value" in cols else df.columns[-1])
)
max_abs = float(df[y_col].abs().max()) if y_col in df.columns else None
tt_fmt = _compute_tooltip_format(max_abs, unit_measure)
y_ax = {
**_axis_style(),
"title": None,
"labelExpr": _value_label_expr(unit_measure),
}
encoding: dict = {
"x": _x_temporal_encoding(result.temporal_frequency) if "year" in x_col else {
"field": x_col,
"type": "ordinal",
"axis": _axis_style(),
},
"y": {"field": y_col, "type": "quantitative", "axis": y_ax},
"tooltip": build_structured_tooltips(
list(df.columns),
"line",
indicator_labels,
value_format=tt_fmt,
viz_data=df,
temporal_freq=result.temporal_frequency,
dim_name_labels=result.dim_name_labels,
),
}
if result.color_dim and result.color_dim in cols:
n_items = df[result.color_dim].nunique()
_domain_labels = list(df[result.color_dim].unique())
encoding["color"] = _color_encoding(
result.color_dim,
mark_type="line",
n_items=n_items,
legend_title=result.dim_name_labels.get(result.color_dim),
domain_labels=_domain_labels,
)
spec: dict = {
"$schema": _vl_schema(),
"title": title,
"data": {"values": df.to_dict(orient="records")},
"mark": {
"type": "line",
"strokeWidth": 3,
"strokeCap": "round",
"point": _LINE_HOVER_POINT,
},
"encoding": encoding,
"width": 600,
"height": 350,
}
return inject_wb_config(spec)
STRATEGY_BUILDERS: dict[ChartStrategy, callable] = {
ChartStrategy.TEMPORAL_SINGLE: build_temporal_single_spec,
ChartStrategy.CROSS_SECTIONAL: build_cross_sectional_spec,
ChartStrategy.DISTRIBUTION: build_distribution_spec,
ChartStrategy.BREAKDOWN_COMPARISON: build_breakdown_comparison_spec,
ChartStrategy.SMALL_MULTIPLES: build_small_multiples_spec,
ChartStrategy.HEATMAP: build_heatmap_spec,
ChartStrategy.STACKED_AREA: build_stacked_area_spec,
ChartStrategy.STACKED_BAR: build_stacked_bar_spec,
ChartStrategy.CHOROPLETH: build_choropleth_spec,
ChartStrategy.CORRELATION: build_correlation_spec,
ChartStrategy.CORRELATION_TEMPORAL: build_correlation_temporal_spec,
ChartStrategy.TEMPORAL_MULTI_IND: build_temporal_multi_indicator_spec,
ChartStrategy.FALLBACK_LINE: build_fallback_line_spec,
}
def resolve_unmapped_disaggregations(df: pd.DataFrame, result: StrategyResult) -> pd.DataFrame:
"""Filter or collapse disaggregation dimensions that are not mapped in the strategy."""
if df.empty:
return df
mapped_dims = {
"year",
"value",
"country",
result.color_dim,
result.facet_dim,
result.secondary_color_dim,
result.x_dim,
result.y_dim,
}
# Identify unmapped disaggregation dimensions present in df
disagg_dims = [
"sex",
"age",
"urbanisation",
"residence",
"comp_breakdown_1",
"comp_breakdown_2",
"comp_breakdown_3",
"unit_measure",
]
unmapped_dims = [
c for c in df.columns if c in disagg_dims and c not in mapped_dims
]
if not unmapped_dims:
return df
import logging
logger = logging.getLogger("data360.viz_config")
df_resolved = df.copy()
key_cols = [c for c in df_resolved.columns if c not in unmapped_dims and c != "value"]
for dim in unmapped_dims:
if df_resolved[dim].nunique() <= 1:
continue
# Try to filter by total/aggregate sentinels first
sentinels = {
"_t",
"_z",
"total",
"all",
"overall",
"u",
"not applicable",
"not_applicable",
"notapplicable",
}
unique_vals = df_resolved[dim].dropna().unique()
sentinel_found = None
for val in unique_vals:
val_str = str(val).strip().lower()
if val_str in sentinels:
sentinel_found = val
break
if sentinel_found is not None:
df_resolved = df_resolved[df_resolved[dim] == sentinel_found]
logger.info("Filtered unmapped dimension '%s' to sentinel '%s'", dim, sentinel_found)
# After filtering, check if duplicates still exist
if df_resolved.duplicated(subset=key_cols).any():
n_before = len(df_resolved)
df_resolved = (
df_resolved.groupby(key_cols, sort=False)["value"].mean().reset_index()
)
n_collapsed = n_before - len(df_resolved)
logger.warning(
"Collapsed %d duplicate rows on unmapped dimensions %s",
n_collapsed,
unmapped_dims,
)
return df_resolved
def dispatch_spec(
strategy: ChartStrategy,
df: pd.DataFrame,
title: str | dict,
result: StrategyResult,
indicator_labels: dict[str, str] | None = None,
y_label: str = "Value",
x_label: str = "Value",
unit_measure: str | None = None,
indicator_name: str | None = None,
) -> dict:
"""Call the right spec builder for the given strategy."""
df = resolve_unmapped_disaggregations(df, result)
builder = STRATEGY_BUILDERS[strategy]
if strategy in (
ChartStrategy.TEMPORAL_SINGLE,
ChartStrategy.TEMPORAL_MULTI_IND,
ChartStrategy.BREAKDOWN_COMPARISON,
ChartStrategy.SMALL_MULTIPLES,
ChartStrategy.STACKED_AREA,
ChartStrategy.STACKED_BAR,
ChartStrategy.CHOROPLETH,
ChartStrategy.FALLBACK_LINE,
ChartStrategy.HEATMAP,
):
return builder(df, title, result, indicator_labels, y_label, unit_measure, indicator_name=indicator_name)
elif strategy in (ChartStrategy.CROSS_SECTIONAL, ChartStrategy.DISTRIBUTION):
return builder(df, title, result, indicator_labels, x_label, unit_measure, indicator_name=indicator_name)
else:
return builder(df, title, result, indicator_labels, indicator_name=indicator_name)
# ============================================================================
# HIGH-CARDINALITY THRESHOLDS
# ============================================================================
HIGH_CARDINALITY_THRESHOLDS: dict[str, int] = {
# Maximum color series in a TEMPORAL_SINGLE line chart.
# Strategy routing enforces this before the builder is called.
"line_max_series": 12,
# Minimum country count to switch from line to strip (beeswarm) in single-year views.
"beeswarm_threshold": 20,
# Minimum breakdown count to prefer SMALL_MULTIPLES over BREAKDOWN_COMPARISON.
"facet_threshold": 4,
# Maximum color series in any context where the strategy router canβt pre-filter.
"top_n_series": 12,
# Maximum facet panels in SMALL_MULTIPLES.
# Chatbot UIs embed charts at fixed widths; beyond this panels become unreadably
# small and the page overflows vertically.
"small_multiples_max_facets": 6,
# Maximum bar rows in CROSS_SECTIONAL horizontal bar charts.
# Beyond this, bars become hair-thin and labels collide.
"cross_sectional_max_items": 20,
# Minimum country count to automatically route to a heatmap when multi-year data is present.
"heatmap_threshold": 12,
}
# Keep the standalone constant as a typed alias for backward compat with existing tests.
SMALL_MULTIPLES_MAX_FACETS: int = HIGH_CARDINALITY_THRESHOLDS["small_multiples_max_facets"]
# Maximum series count for direct end labels on multi-series line charts.
# At 680px width, 8 labels of ~10px font fit without overlap when series are spread.
# Above this threshold the color legend is cleaner than cramped end labels.
MAX_END_LABEL_SERIES: int = 10
# Auto-routing threshold for CORRELATION_TEMPORAL (connected scatter).
# When 2 indicators are present with β€ these many countries and years,
# a connected scatter reveals relationship evolution better than SMALL_MULTIPLES.
# Beyond these thresholds, SMALL_MULTIPLES remains the better choice (panels
# become unreadable and the dot paths overlap catastrophically).
CORRELATION_TEMPORAL_AUTO_MAX_COUNTRIES: int = 8
CORRELATION_TEMPORAL_AUTO_MAX_YEARS: int = 8
# Keep legacy aliases for backward compat with existing tests
def should_use_beeswarm(
viz_data: pd.DataFrame,
chart_type: str | None = None,
color_dim: str | None = None,
) -> bool:
if color_dim is None or color_dim not in viz_data.columns:
return False
if chart_type and chart_type not in (None, "line", "area"):
return False
series_count = viz_data[color_dim].nunique()
year_count = viz_data["year"].nunique() if "year" in viz_data.columns else 0
return (
series_count > HIGH_CARDINALITY_THRESHOLDS["beeswarm_threshold"]
and year_count <= 1
)
def build_beeswarm_spec(
viz_data: pd.DataFrame,
title: str,
value_col: str = "value",
color_col: str = "country",
) -> dict:
"""Legacy alias β delegates to build_distribution_spec."""
r = StrategyResult(ChartStrategy.DISTRIBUTION, "beeswarm", color_dim=color_col)
# rename value_col if needed
df = viz_data.copy()
if value_col != "value" and value_col in df.columns:
df = df.rename(columns={value_col: "value"})
return build_distribution_spec(df, title, r)
# ============================================================================
# FREQUENCY / CHART TYPE MAPPINGS (unchanged from original)
# ============================================================================
FREQUENCY_TO_TIMEUNIT: dict[str, str] = {
"A": "utcyear",
"M": "utcyearmonth",
"Q": "utcyearquarter",
}
PERIODICITY_KEYWORDS: dict[str, list[str]] = {
"A": ["annual", "yearly"],
"M": ["month", "monthly"],
"Q": ["quarter", "quarterly"],
}
CHART_TYPE_KEYWORDS: dict[str, list[str]] = {
"line": ["line", "trend", "time series", "over time"],
"stacked_bar": ["stacked_bar", "stacked_column", "stacked bar", "stacked column"],
"bar": ["bar", "column", "ranking", "compare", "histogram"],
"point": ["scatter", "point", "dot", "correlation", "bubble"],
"area": ["area", "filled", "cumulative", "stacked"],
"tick": ["tick", "strip", "beeswarm", "distribution"],
# NOTE: "heatmap" must be evaluated before "map" because the substring "map"
# appears inside "heatmap" and "heat map". Insertion order is significant.
"heatmap": ["heatmap", "heat map", "heat"],
"map": ["map", "choropleth", "geoshape", "geographic"],
"small_multiples": ["facet", "small multiples", "small_multiples", "grid"],
}
DEFAULT_CHART_TYPE: str = "line"
def parse_chart_type_hint(chart_type: str | None) -> str:
if not chart_type:
return DEFAULT_CHART_TYPE
hint = chart_type.lower().strip()
for mark_type, keywords in CHART_TYPE_KEYWORDS.items():
if any(keyword in hint for keyword in keywords):
return mark_type
return DEFAULT_CHART_TYPE
_REASON_CHART_PHRASES: dict[str, str] = {
"line": "line chart",
"bar": "bar chart",
"stacked_bar": "stacked bar chart",
"area": "area chart",
"point": "point chart",
"tick": "strip chart",
}
def chart_type_phrase_for_reason(mark_type: str | None) -> str:
"""Human phrase for strategy / tool ``reason`` (aligned with mark type hint or render)."""
if not mark_type:
return _REASON_CHART_PHRASES["line"]
normalized = mark_type.lower().strip()
return _REASON_CHART_PHRASES.get(normalized, f"{normalized} chart")
def patch_strategy_reason_chart_phrase(reason: str, mark_type: str) -> str:
"""Replace the trailing ``β β¦`` segment so it reflects the given mark type."""
sep = " β "
if sep not in reason:
return reason
prefix, _old = reason.rsplit(sep, 1)
return f"{prefix}{sep}{chart_type_phrase_for_reason(mark_type)}"
def extract_top_level_mark_type(vl_spec: dict) -> str | None:
"""Best-effort mark ``type`` from a single-view Vega-Lite spec."""
mark = vl_spec.get("mark")
if isinstance(mark, str):
return mark
if isinstance(mark, dict):
t = mark.get("type")
return t if isinstance(t, str) else None
return None
def get_main_data_layer(spec: dict) -> dict:
"""Return the primary data-bearing layer from a flat or layered Vega-Lite spec.
Phase 6 and Phase 7 may convert a flat ``{mark, encoding}`` spec into a
layered spec ``{layer: [{mark, encoding}, ...]}`` by appending a zero-line
rule and/or a text end-label layer. Tests and post-processing code that
inspect ``spec["mark"]`` or ``spec["encoding"]`` must call this helper to
get the correct sub-spec regardless of whether the wrapping occurred.
Convention: the first layer ``layer[0]`` is always the primary data mark.
Decoration layers (rule, text) are appended after it.
"""
if "layer" in spec:
layers = spec["layer"]
if layers:
return layers[0]
return spec
def infer_frequency_from_periodicity(periodicity: str) -> str | None:
pl = periodicity.lower()
for code, kws in PERIODICITY_KEYWORDS.items():
if any(kw in pl for kw in kws):
return code
return None
def should_use_temporal_x_axis(
viz_data: pd.DataFrame, chart_type: str | None, available_dimensions: list[str]
) -> tuple[bool, str | None]:
if "year" not in available_dimensions:
return False, _select_categorical_dimension(available_dimensions)
year_count = viz_data["year"].nunique() if "year" in viz_data.columns else 0
if year_count > 1:
return True, None
mark_type = parse_chart_type_hint(chart_type) if chart_type else "line"
pref = {"tick": 1.0, "point": 0.7, "bar": 0.5, "line": 0.2, "area": 0.1}
cat_field = _select_categorical_dimension(available_dimensions)
if cat_field is None:
return True, None
if pref.get(mark_type, 0.5) >= 0.5:
return False, cat_field
return True, None
def _select_categorical_dimension(available_dimensions: list[str]) -> str | None:
for dim in ["country", "sex", "age", "urbanisation", "residence", "education", "income_group"]:
if dim in available_dimensions:
return dim
for dim in available_dimensions:
if dim not in ["year", "value", "time_period", "obs_value"]:
return dim
return None
# ============================================================================
# DATA PREPARATION RULES (unchanged)
# ============================================================================
@dataclass
class DataPreparationRule:
chart_type: str
frequency: str | None
action: Literal["year_strings", "datetime"]
description: str
DATA_PREPARATION_RULES: list[DataPreparationRule] = [
DataPreparationRule(
"bar", "A", "year_strings", "Bar charts with annual data use year strings"
),
DataPreparationRule(
"bar",
None,
"year_strings",
"Bar charts when API frequency is unknown β assume annual WDI-style years",
),
DataPreparationRule("*", "*", "datetime", "Default: datetime"),
]
def get_data_preparation_action(
chart_type: str, frequency: str | None
) -> Literal["year_strings", "datetime"]:
for rule in DATA_PREPARATION_RULES:
if (rule.chart_type == "*" or rule.chart_type == chart_type) and (
rule.frequency == "*" or rule.frequency == frequency
):
return rule.action
return "datetime"
_YEAR_GAP_FILL_MAX_SPAN = 400
def frequency_allows_annual_year_gap_fill(data_frequency: str | None) -> bool:
"""True when data are treated as annual so missing calendar years can be inserted."""
if data_frequency is None or not str(data_frequency).strip():
return True
code = str(data_frequency).strip().upper()
if code in FREQUENCY_TO_TIMEUNIT and code != "A":
return False
return code in ("A", "ANNUAL", "Y", "YEAR", "YA")
def _clone_year_field(y_int: int, sample: Any) -> Any:
"""Match ``year`` dtype/shape used in the source group (string, datetime, int)."""
if isinstance(sample, str):
stripped = sample.strip()
if len(stripped) == 4 and stripped.isdigit():
return str(y_int)
return pd.Timestamp(year=y_int, month=1, day=1)
if isinstance(sample, pd.Timestamp):
return pd.Timestamp(year=y_int, month=1, day=1)
if isinstance(sample, Integral) and not isinstance(sample, bool):
return int(y_int)
if isinstance(sample, float) and not pd.isna(sample) and sample == int(sample):
return int(y_int)
return pd.Timestamp(year=y_int, month=1, day=1)
def _coerce_year_column_to_int(series: pd.Series) -> pd.Series:
if pd.api.types.is_datetime64_any_dtype(series):
return series.dt.year.astype("Int64")
parsed = pd.to_datetime(series.astype(str), errors="coerce")
if parsed.notna().mean() >= 0.99 and parsed.notna().any():
return parsed.dt.year.astype("Int64")
num = pd.to_numeric(series, errors="coerce")
return num.round().astype("Int64")
def fill_missing_calendar_years_annual(
df: pd.DataFrame,
data_frequency: str | None,
) -> pd.DataFrame:
"""Insert NaN rows for missing integer calendar years within each series' span.
Each *series* is defined by every column except ``year`` and ``value`` (e.g. one
country). For that series, all calendar years from min(year) to max(year) appear
exactly once; gaps in the source (e.g. no 2010) become explicit rows with null
``value``. Skipped when frequency is not annual, years cannot be coerced, any
(series, year) duplicates exist, or the span exceeds ``_YEAR_GAP_FILL_MAX_SPAN``.
"""
if df.empty or "year" not in df.columns or "value" not in df.columns:
return df
if not frequency_allows_annual_year_gap_fill(data_frequency):
return df
y_int = _coerce_year_column_to_int(df["year"])
if y_int.isna().all():
return df
work = df.copy()
work["_yi"] = y_int
work = work.loc[~work["_yi"].isna()].copy()
work["_yi"] = work["_yi"].astype(int)
gcols = [c for c in work.columns if c not in ("year", "value", "_yi")]
dup_check = work.groupby(gcols + ["_yi"], dropna=False).size()
if (dup_check > 1).any():
return df
out_rows: list[pd.Series] = []
grouped = (
work.groupby(gcols, dropna=False)
if gcols
else [(tuple(), work)]
)
for _gkey, g in grouped:
lo = int(g["_yi"].min())
hi = int(g["_yi"].max())
if hi - lo > _YEAR_GAP_FILL_MAX_SPAN:
return df
sample_year = g["year"].iloc[0]
existing = set(int(x) for x in g["_yi"].tolist())
for yi in range(lo, hi + 1):
match = g[g["_yi"] == yi]
if len(match) > 0:
out_rows.append(match.iloc[0].drop(labels=["_yi"]))
else:
proto = g.iloc[0].drop(labels=["_yi"]).to_dict()
proto["year"] = _clone_year_field(yi, sample_year)
proto["value"] = float("nan")
out_rows.append(pd.Series(proto))
out = pd.DataFrame(out_rows)
out = out.reindex(columns=df.columns)
meta_cols = [c for c in df.columns if c not in ("year", "value")]
out["_sy"] = _coerce_year_column_to_int(out["year"])
sort_keys = [k for k in (*meta_cols, "_sy") if k in out.columns]
out = out.sort_values(by=sort_keys, na_position="last").drop(columns=["_sy"])
return out
def should_prepare_as_datetime(
viz_data: pd.DataFrame, chart_type: str, frequency: str | None
) -> bool:
return get_data_preparation_action(chart_type, frequency) == "datetime"
# ============================================================================
# POST-PROCESSING RULES (kept for backward compat with existing Draco path)
# ============================================================================
@dataclass
class PostProcessingRule:
name: str
applies_to_mark_types: list[str]
description: str
def should_apply(self, mark_type: str, encoding: dict, data: dict) -> bool:
raise NotImplementedError
def apply(
self,
spec: dict,
data_frequency: str | None = None,
unit_measure: str | None = None,
) -> dict:
raise NotImplementedError
def _first_non_null_dataset_value(dataset: list, field: str) -> object:
for row in dataset:
if field in row:
v = row[field]
if v is not None:
return v
return None
# Ordinal ``year`` values at or above this magnitude are treated as epoch milliseconds
# (typical Altair / Vega-Lite JSON for datetimes), not calendar years.
_YEAR_ORDINAL_EPOCH_MS_THRESHOLD = 1e12
def _year_ordinal_value_needs_temporal_encoding(value: object) -> bool:
"""True when x is ordinal but values are ISO datetimes or epoch ms (Vega-Lite)."""
if value is None or isinstance(value, bool):
return False
if isinstance(value, str):
return "T" in value
if isinstance(value, (int, float)):
fv = float(value)
# Altair often serializes datetimes as milliseconds in embedded datasets
return abs(fv) >= _YEAR_ORDINAL_EPOCH_MS_THRESHOLD
return False
def _extract_spec_dataset_rows(spec: dict) -> list[dict] | None:
"""Return embedded chart rows from ``data.values`` or ``datasets[name]``."""
data = spec.get("data")
if isinstance(data, dict) and "values" in data:
v = data.get("values")
return v if isinstance(v, list) else None
ds_name = data.get("name") if isinstance(data, dict) else None
if ds_name and isinstance(spec.get("datasets"), dict):
rows = spec["datasets"].get(ds_name)
return rows if isinstance(rows, list) else None
return None
def _single_obs_year_to_int(value: object) -> int | None:
"""Parse one observation's year field to a calendar year, or None."""
if value is None or (isinstance(value, float) and pd.isna(value)):
return None
if isinstance(value, bool):
return None
if isinstance(value, Integral):
return int(value)
if isinstance(value, float) and value == int(value):
return int(value)
if isinstance(value, str):
s = value.strip()
if len(s) >= 4 and s[:4].isdigit():
return int(s[:4])
ts = pd.to_datetime(s, errors="coerce")
if pd.notna(ts):
return int(ts.year)
return None
if isinstance(value, pd.Timestamp):
return int(value.year)
return None
class ContiguousCalendarYearDomainRule(PostProcessingRule):
"""Ordinal/nominal ``year`` / ``time_period`` on x: full calendar year range on the scale.
Applies to marks that commonly use a discrete year axis (bar, line, area, point, tick).
Does **not** apply when ``x`` is ``temporal`` (handled separately; continuous time β discrete domain).
"""
def __init__(self):
super().__init__(
"contiguous_calendar_year_domain",
["bar", "line", "area", "point", "tick"],
"Ordinal/nominal year x: explicit scale.domain for every calendar year in minβmax span",
)
def apply(self, spec, data_frequency=None, unit_measure=None):
if not frequency_allows_annual_year_gap_fill(data_frequency):
return spec
if "encoding" not in spec or "x" not in spec["encoding"]:
return spec
mark_type = (
spec.get("mark", {}).get("type")
if isinstance(spec.get("mark"), dict)
else spec.get("mark")
)
if mark_type not in self.applies_to_mark_types:
return spec
x = spec["encoding"]["x"]
xf = x.get("field")
if xf not in ("year", "time_period"):
return spec
if x.get("type") not in ("ordinal", "nominal"):
return spec
if x.get("scale", {}).get("domain") is not None:
return spec
rows = _extract_spec_dataset_rows(spec)
if not rows or len(rows) < 2:
return spec
years: list[int] = []
template: object | None = None
for row in rows:
if not isinstance(row, dict) or xf not in row:
continue
raw = row.get(xf)
if raw is None:
continue
if template is None:
template = raw
yi = _single_obs_year_to_int(raw)
if yi is not None:
years.append(yi)
if len(years) < 2:
return spec
lo, hi = min(years), max(years)
if hi - lo > _YEAR_GAP_FILL_MAX_SPAN:
return spec
if template is None:
return spec
domain = [_clone_year_field(y, template) for y in range(lo, hi + 1)]
x.setdefault("scale", {})["domain"] = domain
# Explicit sort matches domain order (helps Vega-Lite / Vega compile stability).
x["sort"] = domain
return spec
class OrdinalToTemporalRule(PostProcessingRule):
def __init__(self):
super().__init__(
"ordinal_to_temporal",
["line", "area", "point", "tick", "bar"],
"Fix ordinalβtemporal for time fields (ISO or epoch ms), including bars",
)
def should_apply(self, mark_type, x_enc, dataset):
if mark_type not in self.applies_to_mark_types:
return False
if x_enc.get("type") != "ordinal":
return False
x_field = x_enc.get("field")
if x_field not in ["year", "time_period"]:
return False
if not dataset:
return False
sample = _first_non_null_dataset_value(dataset, x_field)
return _year_ordinal_value_needs_temporal_encoding(sample)
def apply(self, spec, data_frequency=None, unit_measure=None):
mark_type = (
spec.get("mark", {}).get("type")
if isinstance(spec.get("mark"), dict)
else spec.get("mark")
)
if "encoding" not in spec or "x" not in spec["encoding"]:
return spec
x_enc = spec["encoding"]["x"]
ds_name = spec.get("data", {}).get("name")
if not ds_name or "datasets" not in spec:
return spec
dataset = spec["datasets"].get(ds_name, [])
if self.should_apply(mark_type, x_enc, dataset):
x_enc["type"] = "temporal"
return spec
class ApplyTimeUnitRule(PostProcessingRule):
def __init__(self):
super().__init__(
"apply_timeunit",
["line", "area", "point", "tick"],
"Add timeUnit from frequency",
)
def should_apply(self, x_enc, freq):
return freq in FREQUENCY_TO_TIMEUNIT and x_enc.get("type") == "temporal"
def apply(self, spec, data_frequency=None, unit_measure=None):
if "encoding" not in spec or "x" not in spec["encoding"]:
return spec
x_enc = spec["encoding"]["x"]
if self.should_apply(x_enc, data_frequency):
x_enc["timeUnit"] = FREQUENCY_TO_TIMEUNIT[data_frequency]
return spec
class FixValueAxisEncodingRule(PostProcessingRule):
"""Altair can infer ordinal for `value` after Draco strips types; fix for line/area/point."""
def __init__(self):
super().__init__(
"fix_value_axis_encodings",
["point", "line", "area"],
"Fix ordinal y on value for line/area/point; point-only size cleanup",
)
def should_apply(self, spec, data_frequency=None):
mark_type = (
spec.get("mark", {}).get("type")
if isinstance(spec.get("mark"), dict)
else spec.get("mark")
)
return mark_type in self.applies_to_mark_types
def apply(self, spec, data_frequency=None, unit_measure=None):
if not self.should_apply(spec, data_frequency):
return spec
if "encoding" not in spec:
return spec
mark_type = (
spec.get("mark", {}).get("type")
if isinstance(spec.get("mark"), dict)
else spec.get("mark")
)
y = spec["encoding"].get("y", {})
if y.get("type") == "ordinal" and y.get("field") == "value":
y["type"] = "quantitative"
y.setdefault("scale", {})["type"] = "linear"
if mark_type == "point":
sz = spec["encoding"].get("size", {})
if sz.get("aggregate") == "count" and "field" not in sz:
del spec["encoding"]["size"]
return spec
class TemporalAxisCleanupRule(PostProcessingRule):
def __init__(self):
super().__init__(
"temporal_axis_cleanup",
["line", "area", "point", "bar"],
"Remove title from temporal x-axis",
)
def should_apply(self, spec, data_frequency=None):
mark_type = (
spec.get("mark", {}).get("type")
if isinstance(spec.get("mark"), dict)
else spec.get("mark")
)
if mark_type not in self.applies_to_mark_types:
return False
return spec.get("encoding", {}).get("x", {}).get("type") == "temporal"
def apply(self, spec, data_frequency=None, unit_measure=None):
if not self.should_apply(spec):
return spec
x = spec["encoding"]["x"]
x.setdefault("axis", {})
x["axis"]["title"] = None
x["axis"]["labelAngle"] = 0
x["axis"].setdefault("format", "%Y")
x["axis"].setdefault("tickCount", 5)
return spec
class DiscreteYearBarXAxisRule(PostProcessingRule):
"""Vega-Lite defaults often rotate discrete x labels on bars; force horizontal years."""
def __init__(self):
super().__init__(
"discrete_year_bar_x_axis",
["bar"],
"Horizontal labels for ordinal/nominal year on column/bar x-axis",
)
def should_apply(self, spec, data_frequency=None):
mark_type = (
spec.get("mark", {}).get("type")
if isinstance(spec.get("mark"), dict)
else spec.get("mark")
)
if mark_type not in self.applies_to_mark_types:
return False
x = spec.get("encoding", {}).get("x", {})
if x.get("field") not in ("year", "time_period"):
return False
return x.get("type") in ("ordinal", "nominal")
def apply(self, spec, data_frequency=None, unit_measure=None):
if not self.should_apply(spec):
return spec
x = spec["encoding"]["x"]
x.setdefault("axis", {})
x["axis"]["labelAngle"] = 0
return spec
class ValueAxisLabelFormatRule(PostProcessingRule):
def __init__(self):
super().__init__(
"value_axis_label_format",
["bar", "line", "area", "point", "tick"],
"Apply compact/value-aware y-axis label formatting",
)
def should_apply(self, spec, data_frequency=None):
mark_type = (
spec.get("mark", {}).get("type")
if isinstance(spec.get("mark"), dict)
else spec.get("mark")
)
if mark_type not in self.applies_to_mark_types:
return False
y = spec.get("encoding", {}).get("y", {})
return y.get("type") == "quantitative" and y.get("field") in {
"value",
"obs_value",
}
def apply(self, spec, data_frequency=None, unit_measure=None, scale_type=None, df=None, **kwargs):
if not self.should_apply(spec, data_frequency):
return spec
resolved_scale_type = scale_type
if df is not None and "value" in df.columns:
import pandas as pd
vals = df["value"].dropna()
if not vals.empty:
max_val = float(vals.abs().max())
if max_val <= 1.0 and _is_proportion_indicator(df, unit_measure, scale_type):
resolved_scale_type = "proportion"
y = spec["encoding"]["y"]
y.setdefault("axis", {})
y["axis"]["labelExpr"] = _value_label_expr(unit_measure, scale_type=resolved_scale_type)
return spec
# Internal columns for year-gap dashed line segments (unlikely to collide with WDI columns).
_LINE_GAP_SEG_DETAIL = "_d360_lseg"
_LINE_GAP_STROKE_FLAG = "_d360_ygap"
class LineYearGapStrokeDashRule(PostProcessingRule):
"""Temporal / discrete-year line charts: dashed stroke across multi-year gaps.
Vega-Lite draws one continuous polyline per color series. We split each
consecutive observation pair into its own ``detail`` group and use
``strokeDash`` so segments that skip one or more calendar years render dashed.
"""
def __init__(self):
super().__init__(
"line_year_gap_stroke_dash",
["line"],
"Dashed line segments where consecutive points differ by >1 calendar year",
)
def apply(self, spec, data_frequency=None, unit_measure=None, is_composite=False, **kwargs):
if not isinstance(spec, dict):
return spec
if "layer" in spec and isinstance(spec["layer"], list):
self._apply_to_layer_root(spec, is_composite=is_composite)
return spec
if "spec" in spec and isinstance(spec.get("spec"), dict):
inner = spec["spec"]
# Facet + inner layer (e.g. line + point from interactive) β data often on facet root
if "layer" in inner and isinstance(inner["layer"], list):
self._apply_to_layer_root(inner, data_root=spec, is_composite=is_composite)
return spec
if self._is_candidate_line_spec(inner):
self._maybe_transform_line_spec(inner, spec, is_composite=is_composite)
return spec
if self._is_candidate_line_spec(spec):
self._maybe_transform_line_spec(spec, spec, is_composite=is_composite)
return spec
def _apply_to_layer_root(
self, layer_parent: dict, data_root: dict | None = None, is_composite: bool = False
) -> None:
root = data_root if data_root is not None else layer_parent
line_layers = [
layer
for layer in layer_parent["layer"]
if isinstance(layer, dict) and self._is_candidate_line_spec(layer)
]
if len(line_layers) != 1:
return
self._maybe_transform_line_spec(line_layers[0], root, is_composite=is_composite)
def _mark_type(self, enc_spec: dict) -> str | None:
m = enc_spec.get("mark")
if isinstance(m, str):
return m
if isinstance(m, dict):
return m.get("type")
return None
def _is_candidate_line_spec(self, enc_spec: dict) -> bool:
mt = self._mark_type(enc_spec)
enc = enc_spec.get("encoding")
if mt != "line":
return False
if not isinstance(enc, dict):
return False
x = enc.get("x", {})
if not isinstance(x, dict):
return False
xf = x.get("field")
if xf not in ("year", "time_period"):
return False
# ApplyTimeUnitRule sets ``timeUnit: "year"`` for annual (A) data; still one value
# per calendar year β allow dashed segments across missing years. Reject finer
# units (month, quarter) where calendar-year gap logic does not apply.
if not self._x_timeunit_allows_year_gap_segments(x):
return False
if x.get("type") not in ("temporal", "ordinal", "nominal"):
return False
y = enc.get("y", {})
if not isinstance(y, dict) or y.get("type") != "quantitative":
return False
if not y.get("field"):
return False
if enc.get("detail") is not None:
return False
if enc.get("strokeDash") is not None:
return False
return True
@staticmethod
def _x_timeunit_allows_year_gap_segments(x: dict) -> bool:
tu = x.get("timeUnit")
if tu is None:
return True
if isinstance(tu, str):
return tu in ("year", "utcyear")
if isinstance(tu, dict):
return tu.get("unit") in ("year", "utcyear")
return False
def _find_inline_values_holder(self, line_spec: dict, data_root: dict) -> dict | None:
for candidate in (line_spec, data_root):
data = candidate.get("data")
if isinstance(data, dict) and isinstance(data.get("values"), list):
return candidate
return None
def _write_inline_values(self, holder: dict, rows: list[dict]) -> None:
data = holder.get("data")
if isinstance(data, dict) and "values" in data:
data["values"] = rows
def _named_dataset_rows(
self, line_spec: dict, data_root: dict
) -> tuple[str, list] | None:
for candidate in (line_spec, data_root):
data = candidate.get("data")
if not isinstance(data, dict):
continue
name = data.get("name")
if (
isinstance(name, str)
and isinstance(data_root.get("datasets"), dict)
and isinstance(data_root["datasets"].get(name), list)
):
return name, data_root["datasets"][name]
return None
def _set_named_dataset_rows(self, data_root: dict, name: str, rows: list[dict]) -> None:
data_root.setdefault("datasets", {})[name] = rows
def _series_keys(self, encoding: dict) -> list[str]:
c = encoding.get("color")
if isinstance(c, dict) and isinstance(c.get("field"), str):
return [c["field"]]
return []
def _facet_field_keys(self, data_root: dict) -> list[str]:
"""Facet / row / column fields so multi-panel specs split series per panel."""
keys: list[str] = []
for name in ("facet", "row", "column"):
node = data_root.get(name)
if not isinstance(node, dict):
continue
f = node.get("field")
if isinstance(f, str):
keys.append(f)
return keys
def _dedupe_sort_group(
self, rows: list[dict], x_field: str
) -> list[tuple[int, dict]]:
by_year: dict[int, dict] = {}
order: list[int] = []
for row in rows:
if not isinstance(row, dict):
continue
yi = _single_obs_year_to_int(row.get(x_field))
if yi is None:
continue
if yi not in by_year:
order.append(yi)
by_year[yi] = dict(row)
order.sort()
return [(y, by_year[y]) for y in order]
def _group_rows_by_series(
self, rows: list[dict], series_keys: list[str]
) -> dict[tuple, list[dict]]:
groups: defaultdict[tuple, list[dict]] = defaultdict(list)
for row in rows:
if not isinstance(row, dict):
continue
key = tuple(row.get(k) for k in series_keys) if series_keys else (None,)
groups[key].append(dict(row))
return dict(groups)
def _any_calendar_year_gap(
self, groups: dict[tuple, list[dict]], x_field: str
) -> bool:
for grp_rows in groups.values():
chain = self._dedupe_sort_group(grp_rows, x_field)
if len(chain) < 2:
continue
for i in range(len(chain) - 1):
y0 = chain[i][0]
y1 = chain[i + 1][0]
if y1 - y0 > 1:
return True
return False
def _build_segment_rows(
self, groups: dict[tuple, list[dict]], x_field: str, series_keys: list[str]
) -> list[dict]:
out: list[dict] = []
seg_i = 0
for key, grp_rows in groups.items():
chain = self._dedupe_sort_group(grp_rows, x_field)
n = len(chain)
if n < 2:
# 0 or 1 point: just add them with default segment info
prefix = "_".join("" if v is None else str(v) for v in key)
sid = f"{prefix}_{seg_i}" if prefix else str(seg_i)
seg_i += 1
for _, r in chain:
out.append({**r, _LINE_GAP_SEG_DETAIL: sid, _LINE_GAP_STROKE_FLAG: 0})
continue
prefix = "_".join("" if v is None else str(v) for v in key)
i = 0
while i < n:
# Start a consecutive block (difference of exactly 1 year)
block = [chain[i]]
j = i + 1
while j < n and (chain[j][0] - chain[j - 1][0]) == 1:
block.append(chain[j])
j += 1
# Only output this block as a solid segment if it has at least 2 points
# (a 1-point block does not draw a line and will connect to a gap segment anyway)
if len(block) >= 2:
sid = f"{prefix}_{seg_i}" if prefix else str(seg_i)
seg_i += 1
for _, r in block:
out.append({**r, _LINE_GAP_SEG_DETAIL: sid, _LINE_GAP_STROKE_FLAG: 0})
# If there is a next block, there is a gap (>1 year) between block[-1] and chain[j]
if j < n:
gap_sid = f"{prefix}_{seg_i}" if prefix else str(seg_i)
seg_i += 1
_, r0 = block[-1]
_, r1 = chain[j]
out.append({**r0, _LINE_GAP_SEG_DETAIL: gap_sid, _LINE_GAP_STROKE_FLAG: 1})
out.append({**r1, _LINE_GAP_SEG_DETAIL: gap_sid, _LINE_GAP_STROKE_FLAG: 1})
i = j
return out
def _strip_internal_tooltip_channels(self, encoding: dict) -> None:
tips = encoding.get("tooltip")
if not isinstance(tips, list):
return
internal = {_LINE_GAP_SEG_DETAIL, _LINE_GAP_STROKE_FLAG}
encoding["tooltip"] = [
t
for t in tips
if not (isinstance(t, dict) and t.get("field") in internal)
]
def _maybe_transform_line_spec(self, line_spec: dict, data_root: dict, is_composite: bool = False) -> None:
# If the chart is a composite/multi-panel view (indicated by is_composite=True),
# modifying the shared top-level data values array will corrupt/delete data
# for other panels. Localize the data values to this panel to preserve data integrity.
if is_composite or "vconcat" in data_root or "hconcat" in data_root or "concat" in data_root:
holder = self._find_inline_values_holder(line_spec, data_root)
rows: list[dict] | None = None
if holder is not None:
v = holder["data"]["values"]
rows = v if isinstance(v, list) else None
else:
named = self._named_dataset_rows(line_spec, data_root)
if named is not None:
_, rows_list = named
rows = rows_list if isinstance(rows_list, list) else None
if not rows or len(rows) < 2:
return
# Apply any filters from data_root or line_spec to obtain only this panel's subset
# (e.g. filter by country/breakdown)
filters = []
for candidate in (data_root, line_spec):
if "transform" in candidate and isinstance(candidate["transform"], list):
for t in candidate["transform"]:
if isinstance(t, dict) and "filter" in t:
filters.append(t["filter"])
panel_rows = list(rows)
for filt in filters:
if isinstance(filt, dict):
field = filt.get("field")
equal_val = filt.get("equal")
one_of_val = filt.get("oneOf")
if field:
if equal_val is not None:
panel_rows = [r for r in panel_rows if r.get(field) == equal_val]
elif isinstance(one_of_val, list):
panel_rows = [r for r in panel_rows if r.get(field) in one_of_val]
enc = line_spec.get("encoding")
if not isinstance(enc, dict):
return
x = enc.get("x", {})
x_field = x.get("field") if isinstance(x, dict) else None
if x_field not in ("year", "time_period"):
return
facet_keys = self._facet_field_keys(data_root)
series_keys = list(
dict.fromkeys([*self._series_keys(enc), *facet_keys]),
)
groups = self._group_rows_by_series(panel_rows, series_keys)
if not self._any_calendar_year_gap(groups, x_field):
return
new_rows = self._build_segment_rows(groups, x_field, series_keys)
if len(new_rows) < 2:
return
# Localize dataset to line_spec so we don't modify shared parent data
line_spec["data"] = {"values": new_rows}
enc["detail"] = {"field": _LINE_GAP_SEG_DETAIL, "type": "nominal"}
enc["strokeDash"] = {
"condition": {
"test": f"datum.{_LINE_GAP_STROKE_FLAG} == 1",
"value": [6, 4],
},
"value": [],
}
self._strip_internal_tooltip_channels(enc)
return
enc = line_spec.get("encoding")
if not isinstance(enc, dict):
return
x = enc.get("x", {})
x_field = x.get("field") if isinstance(x, dict) else None
if x_field not in ("year", "time_period"):
return
holder = self._find_inline_values_holder(line_spec, data_root)
rows: list[dict] | None = None
if holder is not None:
v = holder["data"]["values"]
rows = v if isinstance(v, list) else None
else:
named = self._named_dataset_rows(line_spec, data_root)
if named is not None:
_, rows_list = named
rows = rows_list if isinstance(rows_list, list) else None
if not rows or len(rows) < 2:
return
facet_keys = self._facet_field_keys(data_root)
series_keys = list(
dict.fromkeys([*self._series_keys(enc), *facet_keys]),
)
groups = self._group_rows_by_series(rows, series_keys)
if not self._any_calendar_year_gap(groups, x_field):
return
new_rows = self._build_segment_rows(groups, x_field, series_keys)
if len(new_rows) < 2:
return
if holder is not None:
self._write_inline_values(holder, new_rows)
else:
named = self._named_dataset_rows(line_spec, data_root)
if named is None:
return
name, _ = named
self._set_named_dataset_rows(data_root, name, new_rows)
enc["detail"] = {"field": _LINE_GAP_SEG_DETAIL, "type": "nominal"}
enc["strokeDash"] = {
"condition": {
"test": f"datum.{_LINE_GAP_STROKE_FLAG} == 1",
"value": [6, 4],
},
"value": [],
}
self._strip_internal_tooltip_channels(enc)
class LineChartPointHoverRule(PostProcessingRule):
"""Add / enlarge line points so tooltips are easier to trigger (thin line geometry)."""
def __init__(self):
super().__init__(
"line_chart_point_hover",
["line"],
"Widen line tooltip hit target with point marks",
)
def should_apply(self, spec, data_frequency=None, unit_measure=None):
m = spec.get("mark")
if isinstance(m, str):
return m == "line"
if isinstance(m, dict):
return m.get("type") == "line"
return False
def apply(self, spec, data_frequency=None, unit_measure=None):
if not self.should_apply(spec):
return spec
m = spec["mark"]
if isinstance(m, str):
spec["mark"] = {
"type": "line",
"point": _LINE_HOVER_POINT,
}
return spec
pt = m.get("point")
if pt is False or pt is None or pt is True:
m["point"] = dict(_LINE_HOVER_POINT)
elif isinstance(pt, dict):
sz = pt.get("size", 0)
if not isinstance(sz, (int, float)) or sz < 40:
m["point"] = {**pt, **_LINE_HOVER_POINT}
return spec
class ZeroLineRule(PostProcessingRule):
def __init__(self):
super().__init__(
"zero_line", ["bar", "line", "area"], "Bar charts start at zero"
)
def should_apply(self, spec, data_frequency=None):
mark_type = (
spec.get("mark", {}).get("type")
if isinstance(spec.get("mark"), dict)
else spec.get("mark")
)
return mark_type in self.applies_to_mark_types
def apply(self, spec, data_frequency=None, unit_measure=None):
if not self.should_apply(spec):
return spec
y = spec.get("encoding", {}).get("y", {})
if y.get("type") == "quantitative":
y.setdefault("scale", {})
mark_type = (
spec.get("mark", {}).get("type")
if isinstance(spec.get("mark"), dict)
else spec.get("mark")
)
if mark_type == "bar":
y["scale"]["zero"] = True
return spec
class SkewnessLogScaleRule(PostProcessingRule):
def __init__(self):
super().__init__(
"skewness_log_scale",
["line", "bar", "point", "area", "circle", "text"],
"Automatically apply log scale if values are highly positive skewed and positive"
)
def should_apply(self, spec, data_frequency=None, df=None, raw_hint=None, **kwargs):
return True
def apply(self, spec, data_frequency=None, unit_measure=None, df=None, raw_hint=None, **kwargs):
def _apply_log_scale_to_spec(subspec):
if not isinstance(subspec, dict):
return subspec
# Recurse into sub-specs
if "spec" in subspec:
_apply_log_scale_to_spec(subspec["spec"])
if "layer" in subspec and isinstance(subspec["layer"], list):
for child in subspec["layer"]:
_apply_log_scale_to_spec(child)
if "vconcat" in subspec and isinstance(subspec["vconcat"], list):
for child in subspec["vconcat"]:
_apply_log_scale_to_spec(child)
if "hconcat" in subspec and isinstance(subspec["hconcat"], list):
for child in subspec["hconcat"]:
_apply_log_scale_to_spec(child)
# Apply to the current spec's encodings
enc = subspec.get("encoding", {})
if not isinstance(enc, dict):
return subspec
applied_log = False
for channel in ("x", "y"):
ch_enc = enc.get(channel)
if not isinstance(ch_enc, dict) or ch_enc.get("type") != "quantitative":
continue
if "stack" in ch_enc:
continue
field_name = ch_enc.get("field")
if not field_name or df is None or field_name not in df.columns:
continue
# Check explicit request or skewness condition
hint_str = (raw_hint or "").lower().strip()
is_explicit = "log" in hint_str or "logarithmic" in hint_str
# Compute metrics
val_series = pd.to_numeric(df[field_name], errors="coerce").dropna()
if val_series.empty or val_series.min() <= 0:
continue
should_log = False
if is_explicit:
should_log = True
else:
# Check if the data represents percentages, proportions, indices or ratios
is_percentage = False
unit_str = str(unit_measure or "").upper().strip()
if any(x in unit_str for x in ["%", "PERCENT", "PROP", "SHARE", "RATIO", "INDEX"]):
is_percentage = True
if not is_percentage and df is not None:
if "unit_measure" in df.columns:
units = df["unit_measure"].dropna().astype(str).str.upper().unique()
if any(any(x in u for x in ["%", "PERCENT", "PROP", "SHARE", "RATIO", "INDEX"]) for u in units):
is_percentage = True
if not is_percentage and val_series.min() >= 0 and val_series.max() <= 1.0:
is_percentage = True
if not is_percentage:
skewness = val_series.skew()
if not pd.isna(skewness):
median = val_series.median()
val_max = val_series.max()
val_min = val_series.min()
ratio = val_max / (median or 1)
min_max_ratio = val_max / (val_min or 1)
# Apply log scale if highly skewed or dynamic range is wide (> 30x)
if (skewness > 0.5 and ratio > 7.5) or min_max_ratio > 50.0: # raised 50% from original 5x/30x
should_log = True
if should_log:
ch_enc.setdefault("scale", {})
ch_enc["scale"]["type"] = "log"
ch_enc["scale"]["zero"] = False
if not val_series.empty and val_series.min() > 0:
min_val = float(val_series.min())
domain_min = 1.0 if min_val > 1.0 else float(min_val * 0.9)
ch_enc["scale"]["domain"] = [domain_min, float(val_series.max() * 1.1)]
applied_log = True
if applied_log:
# Vega-Lite bar marks on a log scale REQUIRE an explicit x2 baseline.
# Without it, the bar tries to extend from log(0) = -β and renders blank.
# We set x2 to the domain minimum (the leftmost tick) so bars have a
# valid positive anchor and render as proper proportional bars.
mark = subspec.get("mark")
is_bar = (isinstance(mark, dict) and mark.get("type") == "bar") or mark == "bar"
if is_bar and val_series is not None and not val_series.empty and val_series.min() > 0:
min_val = float(val_series.min())
domain_min = 1.0 if min_val > 1.0 else float(min_val * 0.9)
enc = subspec.setdefault("encoding", {})
# Determine which axis has the log scale applied (the quantitative axis)
# and add an explicit baseline encoding using datum (data coordinate,
# not pixel). This anchors the bar's trailing edge at the domain minimum.
if "x" in enc and enc["x"].get("field") == "value":
enc["x2"] = {"datum": domain_min}
elif "y" in enc and enc["y"].get("field") == "value":
enc["y2"] = {"datum": domain_min}
if applied_log:
has_log[0] = True
return subspec
has_log = [False]
_apply_log_scale_to_spec(spec)
if has_log[0]:
title_obj = spec.get("title")
if isinstance(title_obj, dict):
subtitle = title_obj.get("subtitle", [])
if isinstance(subtitle, str):
subtitle = [subtitle]
elif not isinstance(subtitle, list):
subtitle = []
note_str = "Note: Value axis is on a logarithmic scale due to wide dynamic range."
if note_str not in subtitle:
subtitle.append(note_str)
title_obj["subtitle"] = subtitle
elif isinstance(title_obj, str):
spec["title"] = {
"text": title_obj,
"subtitle": ["Note: Value axis is on a logarithmic scale due to wide dynamic range."]
}
return spec
class PercentageBoundaryClampingRule(PostProcessingRule):
def __init__(self):
super().__init__(
"percentage_boundary_clamping",
["line", "bar", "area"],
"Clamps percentage axes to 0-100 or 0-1 standard bounds"
)
def should_apply(self, spec, scale_type=None, df=None, unit_measure=None, **kwargs):
import pandas as pd
if df is not None and "value" in df.columns:
vals = df["value"].dropna()
if not vals.empty:
max_val = float(vals.max())
min_val = float(vals.min())
if min_val < 0:
return False
if max_val > 100:
return False
# Exclude unbounded growth, inflation, or interest rates from clamping
normalized_unit = (unit_measure or "").upper()
unbounded_keywords = {"GROWTH", "INFLATION", "INTEREST", "YIELD", "INDEX"}
if any(k in normalized_unit for k in unbounded_keywords):
return False
if "indicator" in df.columns:
ind_names = df["indicator"].dropna().unique()
for name in ind_names:
name_upper = str(name).upper()
if any(k in name_upper for k in unbounded_keywords):
return False
# Exclude indicators concentrated far from zero to allow natural trend zooming
is_proportion = max_val <= 1.0 and _is_proportion_indicator(df, unit_measure, scale_type)
if is_proportion and min_val > 0.3:
return False
if not is_proportion and min_val > 30:
return False
if scale_type == "percentage":
return True
# Also apply for proportion indicators even if scale_type is not percentage
if df is not None and "value" in df.columns:
import pandas as pd
vals = df["value"].dropna()
if not vals.empty:
max_val = float(vals.abs().max())
if max_val <= 1.0 and _is_proportion_indicator(df, unit_measure, scale_type):
return True
return False
def apply(self, spec, data_frequency=None, unit_measure=None, scale_type=None, df=None, **kwargs):
if not self.should_apply(spec, scale_type=scale_type, df=df, unit_measure=unit_measure):
return spec
# Check if the data represents raw proportions (value max <= 1) rather than 0-100 percentages.
is_proportion = False
max_val = 100.0
if df is not None and "value" in df.columns:
import pandas as pd
vals = df["value"].dropna()
if not vals.empty:
max_abs = float(vals.abs().max())
max_val = float(vals.max())
if max_abs <= 1.0 and _is_proportion_indicator(df, unit_measure, scale_type):
is_proportion = True
# Determine dynamic upper bound for domain to avoid squishing
if is_proportion:
if max_val <= 0.05:
upper = 0.05
elif max_val <= 0.10:
upper = 0.10
elif max_val <= 0.25:
upper = 0.25
elif max_val <= 0.50:
upper = 0.50
else:
upper = 1.0
domain = [0, upper]
else:
if max_val <= 5:
upper = 5
elif max_val <= 10:
upper = 10
elif max_val <= 25:
upper = 25
elif max_val <= 50:
upper = 50
else:
upper = 100
domain = [0, upper]
enc = spec.get("encoding", {})
for channel in ("x", "y"):
ch_enc = enc.get(channel)
if isinstance(ch_enc, dict) and ch_enc.get("type") == "quantitative":
ch_enc.setdefault("scale", {})
if ch_enc["scale"].get("type") == "log":
continue
ch_enc["scale"]["domain"] = domain
# Format axis label correctly if it's a proportion percentage
if is_proportion:
axis_spec = ch_enc.setdefault("axis", {})
if "labelExpr" in axis_spec:
expr = axis_spec["labelExpr"]
if "datum.value" in expr and "* 100" not in expr and "%" in expr:
axis_spec["labelExpr"] = expr.replace("datum.value", "datum.value * 100")
if "spec" in spec:
self.apply(spec["spec"], data_frequency, unit_measure, scale_type=scale_type, df=df, **kwargs)
if "layer" in spec:
for subspec in spec["layer"]:
self.apply(subspec, data_frequency, unit_measure, scale_type=scale_type, df=df, **kwargs)
return spec
def _filter_df_for_error_band(df: pd.DataFrame) -> pd.DataFrame:
"""Pre-filters the dataframe to keep only the best errorband triplet/pair if present."""
if "comp_breakdown_1" not in df.columns or "value" not in df.columns:
return df
cb1_vals = df["comp_breakdown_1"].dropna().unique().tolist()
# Classify each unique category value
lower_keywords = {"lower", "lb", "min", "minimum", "low"}
upper_keywords = {"upper", "ub", "max", "maximum", "high"}
se_keywords = {"se", "std_err", "stderr", "error"}
est_keywords = {"estimate", "score", "value", "val", "est"}
classified = {}
for v in cb1_vals:
v_lower = str(v).lower().strip()
parts = set(v_lower.replace("-", "_").replace(" ", "_").split("_"))
if parts.intersection(lower_keywords):
classified[v] = "lower"
elif parts.intersection(upper_keywords):
classified[v] = "upper"
elif parts.intersection(se_keywords) or "standard error" in v_lower:
classified[v] = "se"
elif parts.intersection(est_keywords):
classified[v] = "est"
# Try to find a matching triplet (est, lower, upper)
lower_vals = [k for k, val in classified.items() if val == "lower"]
upper_vals = [k for k, val in classified.items() if val == "upper"]
est_vals = [k for k, val in classified.items() if val == "est"]
se_vals = [k for k, val in classified.items() if val == "se"]
best_triplet = None
for est in est_vals:
# Strip parentheses and their contents to handle mapped labels like "Governance score (0-100)"
est_clean = re.sub(r'\(.*?\)', '', str(est))
est_base = est_clean.lower().replace("_sc", "").replace("_est", "").strip()
matching_lower = []
for l in lower_vals:
l_clean = re.sub(r'\(.*?\)', '', str(l)).lower()
if est_base in l_clean or est_base == l_clean.replace("_lb", "").replace("_lower", "").strip():
matching_lower.append(l)
matching_upper = []
for u in upper_vals:
u_clean = re.sub(r'\(.*?\)', '', str(u)).lower()
if est_base in u_clean or est_base == u_clean.replace("_ub", "").replace("_upper", "").strip():
matching_upper.append(u)
if matching_lower and matching_upper:
best_triplet = (est, matching_lower[0], matching_upper[0])
break
if best_triplet:
return df[df["comp_breakdown_1"].isin(best_triplet)].copy()
# Try to find a matching estimate + se pair
best_pair = None
for est in est_vals:
est_clean = re.sub(r'\(.*?\)', '', str(est))
est_base = est_clean.lower().replace("_est", "").strip()
matching_se = []
for s in se_vals:
s_clean = re.sub(r'\(.*?\)', '', str(s)).lower()
# Strict matching: est_base must be in the se label, or the se label must be generic (e.g. "se", "standard error")
is_generic = s_clean.strip() in ("se", "standard error", "std_err", "stderr", "std error", "error")
if est_base in s_clean or is_generic:
matching_se.append(s)
if matching_se:
best_pair = (est, matching_se[0])
break
if best_pair:
return df[df["comp_breakdown_1"].isin(best_pair)].copy()
# Fallback to any triplet or pair if no prefix-matching succeeded
if est_vals and lower_vals and upper_vals:
return df[df["comp_breakdown_1"].isin([est_vals[0], lower_vals[0], upper_vals[0]])].copy()
if est_vals and se_vals:
return df[df["comp_breakdown_1"].isin([est_vals[0], se_vals[0]])].copy()
return df
class GeneralErrorBandRule(PostProcessingRule):
def __init__(self):
super().__init__(
"general_error_band",
["line"],
"Layer estimate lines with lower/upper bound area error bands when confidence intervals or standard errors are detected"
)
def _classify_values(self, unique_vals: list[str]) -> tuple[dict[str, str], set[str]]:
"""Maps each unique category label to a normalized key: 'est', 'lower', 'upper', or 'se'."""
mapping = {}
unclassified = []
lower_keywords = {"lower", "lb", "min", "minimum", "low"}
upper_keywords = {"upper", "ub", "max", "maximum", "high"}
se_keywords = {"se", "std_err", "stderr", "error"}
est_keywords = {"estimate", "score", "value", "val", "est"}
for v in unique_vals:
v_lower = str(v).lower().strip()
parts = set(v_lower.replace("-", "_").replace(" ", "_").split("_"))
# Lower bound check
if parts.intersection(lower_keywords):
mapping[v] = "lower"
# Upper bound check
elif parts.intersection(upper_keywords):
mapping[v] = "upper"
# Standard error check
elif parts.intersection(se_keywords) or "standard error" in v_lower:
mapping[v] = "se"
# Explicit estimate check
elif parts.intersection(est_keywords):
mapping[v] = "est"
else:
unclassified.append(v)
# Resolve unclassified value if it's the third-wheel in a triplet or pair
classified_keys = set(mapping.values())
if len(unclassified) == 1:
if "lower" in classified_keys and "upper" in classified_keys and "est" not in classified_keys:
mapping[unclassified[0]] = "est"
elif "se" in classified_keys and "est" not in classified_keys:
mapping[unclassified[0]] = "est"
return mapping, set(mapping.values())
def should_apply(self, spec, df=None, **kwargs):
if df is None or "comp_breakdown_1" not in df.columns or "value" not in df.columns:
return False
cb1_vals = df["comp_breakdown_1"].dropna().unique().tolist()
_, mapped_keys = self._classify_values(cb1_vals)
has_triplet = {"est", "lower", "upper"}.issubset(mapped_keys)
has_pair = {"est", "se"}.issubset(mapped_keys)
return has_triplet or has_pair
def apply(self, spec, data_frequency=None, unit_measure=None, df=None, **kwargs):
if not self.should_apply(spec, df=df):
return spec
df_copy = df.copy()
cb1_vals = df_copy["comp_breakdown_1"].dropna().unique().tolist()
mapping, _ = self._classify_values(cb1_vals)
# Map values to the normalized keys
df_copy["comp_breakdown_1"] = df_copy["comp_breakdown_1"].map(mapping).fillna(df_copy["comp_breakdown_1"])
unique_vals = set(df_copy["comp_breakdown_1"].dropna().unique())
groupby_cols = [c for c in ["year", "time_period", "country", "ref_area", "ref_area_name"] if c in df_copy.columns]
if {"est", "lower", "upper"}.issubset(unique_vals):
transforms = [
{
"pivot": "comp_breakdown_1",
"value": "value",
"groupby": groupby_cols
}
]
lb_field = "lower"
ub_field = "upper"
elif {"est", "se"}.issubset(unique_vals):
transforms = [
{
"pivot": "comp_breakdown_1",
"value": "value",
"groupby": groupby_cols
},
{
"calculate": "datum.est - 1.645 * datum.se",
"as": "lower"
},
{
"calculate": "datum.est + 1.645 * datum.se",
"as": "upper"
}
]
lb_field = "lower"
ub_field = "upper"
else:
return spec
is_layered = "layer" in spec
is_vconcat = ("vconcat" in spec or "concat" in spec) and not is_layered
concat_key = "concat" if "concat" in spec else "vconcat"
# ββ vconcat/concat case: each panel is a per-country or per-indicator flat spec β
# We need to transform each panel individually, preserving its scoping
# filter transform (country OR indicator) while replacing the
# color-by-breakdown encoding with a layered errorband + estimate line approach.
if is_vconcat:
new_panels = []
for panel in spec[concat_key]:
panel_enc = panel.get("encoding", {})
if not panel_enc or "y" not in panel_enc:
new_panels.append(panel)
continue
color_enc = panel_enc.get("color")
keep_color = False
if isinstance(color_enc, dict):
color_field = color_enc.get("field")
if color_field and color_field != "comp_breakdown_1":
keep_color = True
# Extract the per-country filter transform (e.g. filter country==Argentina).
# Also capture per-indicator filters: in multi-indicator WGI small-multiples
# each panel is scoped to one indicator value, not a country.
country_filter_transforms = [
t for t in panel.get("transform", [])
if "filter" in t and isinstance(t["filter"], dict) and t["filter"].get("field") == "country"
]
indicator_filter_transforms = [
t for t in panel.get("transform", [])
if "filter" in t and isinstance(t["filter"], dict) and t["filter"].get("field") == "indicator"
]
panel_x_enc = panel_enc.get("x", {})
panel_y_enc = panel_enc.get("y", {})
panel_mark = panel.get("mark", {"type": "line", "strokeWidth": 3})
panel_title = panel.get("title")
panel_width = panel.get("width", spec.get("width", 600))
panel_height = panel.get("height", spec.get("height", 200))
# Build the full transform chain: scoping filters β pivot β calculate bounds.
# Scoping filters = country filter (single-indicator multi-country) OR indicator
# filter (multi-indicator WGI). Both are prepended so the pivot only sees the
# rows belonging to this panel's dimension value.
scoping_filters = country_filter_transforms + indicator_filter_transforms
full_transforms = scoping_filters + transforms
is_nominal_x = panel_x_enc.get("type") == "nominal"
is_nominal_y = panel_y_enc.get("type") == "nominal"
if is_nominal_x or is_nominal_y:
errorband_mark = {"type": "rule", "color": "#666666", "strokeWidth": 1.5}
else:
errorband_mark = {"type": "area", "opacity": 0.2}
if not keep_color:
errorband_mark["color"] = "#34A7F2"
if is_nominal_y:
errorband_encoding = {
"y": panel_y_enc,
"x": {
"field": lb_field,
"type": "quantitative",
"scale": {"zero": False}
},
"x2": {
"field": ub_field
}
}
if "yOffset" in panel_enc:
errorband_encoding["yOffset"] = panel_enc["yOffset"]
else:
errorband_encoding = {
"x": panel_x_enc,
"y": {
"field": lb_field,
"type": "quantitative",
"scale": {"zero": False}
},
"y2": {
"field": ub_field
}
}
if "xOffset" in panel_enc:
errorband_encoding["xOffset"] = panel_enc["xOffset"]
if keep_color:
errorband_encoding["color"] = color_enc
errorband = {
"transform": full_transforms,
"mark": errorband_mark,
"encoding": errorband_encoding
}
# Build line encoding
if keep_color:
line_enc = panel_enc
else:
line_enc = {k: v for k, v in panel_enc.items() if k != "color"}
line = {
"transform": scoping_filters + [
{"filter": "datum.comp_breakdown_1 == 'est'"}
],
"mark": panel_mark,
"encoding": line_enc
}
new_panel = {
"title": panel_title,
"width": panel_width,
"height": panel_height,
"layer": [errorband, line]
}
new_panels.append(new_panel)
spec[concat_key] = new_panels
spec["data"] = {"values": df_copy.to_dict(orient="records")}
return spec
if is_layered:
# Find the main layer (usually the first one with encoding and color/line)
main_layer = None
for layer in spec["layer"]:
if "encoding" in layer and "y" in layer["encoding"]:
main_layer = layer
break
if main_layer is None:
return spec
enc = main_layer["encoding"]
mark_spec = main_layer.get("mark", "line")
else:
enc = spec.get("encoding", {})
mark_spec = spec.get("mark", "line")
if not enc:
return spec
x_enc = enc.get("x", {})
y_enc = enc.get("y", {})
color_enc = enc.get("color", {})
keep_color = False
if isinstance(color_enc, dict):
color_field = color_enc.get("field")
if color_field and color_field != "comp_breakdown_1":
keep_color = True
is_nominal_x = x_enc.get("type") == "nominal"
is_nominal_y = y_enc.get("type") == "nominal"
if is_nominal_x or is_nominal_y:
errorband_mark = {"type": "rule", "color": "#666666", "strokeWidth": 1.5}
else:
errorband_mark = {"type": "area", "opacity": 0.2}
if not keep_color:
errorband_mark["color"] = "#34A7F2"
if is_nominal_y:
errorband_encoding = {
"y": y_enc,
"x": {
"field": lb_field,
"type": "quantitative",
"scale": {"zero": False}
},
"x2": {
"field": ub_field
}
}
if "yOffset" in enc:
errorband_encoding["yOffset"] = enc["yOffset"]
else:
errorband_encoding = {
"x": x_enc,
"y": {
"field": lb_field,
"type": "quantitative",
"scale": {"zero": False}
},
"y2": {
"field": ub_field
}
}
if "xOffset" in enc:
errorband_encoding["xOffset"] = enc["xOffset"]
if keep_color:
errorband_encoding["color"] = color_enc
errorband_layer = {
"transform": transforms,
"mark": errorband_mark,
"encoding": errorband_encoding
}
# Clean up line encoding to only filter and draw the 'est' line
line_enc = enc.copy()
if not keep_color:
if "color" in line_enc:
del line_enc["color"]
line_layer = {
"transform": [
{
"filter": "datum.comp_breakdown_1 == 'est'"
}
],
"mark": mark_spec,
"encoding": line_enc
}
if is_layered:
new_layers = [errorband_layer]
for layer in spec["layer"]:
# Suppress the end label layer for comp_breakdown_1 in confidence interval charts
is_text = False
mark = layer.get("mark", {})
mark_type = mark.get("type") if isinstance(mark, dict) else mark
if mark_type == "text":
is_text = True
if layer is main_layer:
new_layers.append(line_layer)
elif is_text:
continue
else:
new_layers.append(layer)
spec["layer"] = new_layers
spec["data"] = {"values": df_copy.to_dict(orient="records")}
return spec
else:
layered_spec = {
"$schema": spec.get("$schema", "https://vega.github.io/schema/vega-lite/v5.json"),
"title": spec.get("title"),
"width": spec.get("width", 600),
"height": spec.get("height", 350),
"config": spec.get("config", {}),
"data": {"values": df_copy.to_dict(orient="records")},
"layer": [errorband_layer, line_layer]
}
return layered_spec
class PopulationPyramidRule(PostProcessingRule):
def __init__(self):
super().__init__(
"population_pyramid",
["*"],
"Transform bar chart into a diverging population pyramid when age and sex dimensions are present"
)
def should_apply(self, spec, df=None, raw_hint=None, **kwargs):
if df is None:
return False
cols = {c.lower() for c in df.columns}
has_dims = "sex" in cols and "age" in cols
if not has_dims:
return False
hint_str = (raw_hint or "").lower().strip()
is_pyramid_hint = "pyramid" in hint_str or "population_pyramid" in hint_str
if is_pyramid_hint:
return True
# Auto-trigger if single country, single year, and both age/sex columns are present
year_count = df["year"].nunique() if "year" in df.columns else 0
country_count = df["country"].nunique() if "country" in df.columns else 0
if year_count == 1 and country_count == 1:
return True
return False
def apply(self, spec, data_frequency=None, unit_measure=None, df=None, raw_hint=None, **kwargs):
if not self.should_apply(spec, df=df, raw_hint=raw_hint):
return spec
sex_col = [c for c in df.columns if c.lower() == "sex"][0]
age_col = [c for c in df.columns if c.lower() == "age"][0]
unique_ages = df[age_col].dropna().unique().tolist()
sort_order = _get_dimension_sort_order(age_col, unique_ages)
y_enc = {
"field": age_col,
"type": "nominal",
"axis": {
"title": "Age Group",
"grid": False
}
}
if sort_order:
y_enc["sort"] = sort_order
unique_sexes = df[sex_col].dropna().unique().tolist()
domain = [s for s in ["Male", "Female", "M", "F"] if s in unique_sexes]
range_colors = []
for s in domain:
if s in ("Male", "M"):
range_colors.append("#34A7F2")
else:
range_colors.append("#F3578E")
pyramid_spec = {
"$schema": spec.get("$schema", "https://vega.github.io/schema/vega-lite/v5.json"),
"title": spec.get("title"),
"width": spec.get("width", 600),
"height": spec.get("height", 350),
"config": spec.get("config", {}),
"data": spec.get("data", {}),
"transform": [
{
"calculate": f"datum.{sex_col} == 'Male' || datum.{sex_col} == 'M' ? -datum.value : datum.value",
"as": "signed_value"
}
],
"mark": {
"type": "bar",
"tooltip": True
},
"encoding": {
"y": y_enc,
"x": {
"field": "signed_value",
"type": "quantitative",
"axis": {
"title": "Population",
"labelExpr": "abs(datum.value)"
}
},
"color": {
"field": sex_col,
"type": "nominal",
"scale": {
"domain": domain,
"range": range_colors
},
"legend": {
"title": "Sex"
}
}
}
}
return pyramid_spec
class ApplyWBStyleRule(PostProcessingRule):
def __init__(self):
super().__init__("apply_wb_style", ["*"], "Inject WB style config")
def should_apply(self, spec, data_frequency=None):
return True
def apply(self, spec, data_frequency=None, unit_measure=None, **kwargs):
return inject_wb_config(spec)
POST_PROCESSING_RULES: list[PostProcessingRule] = [
OrdinalToTemporalRule(),
ApplyTimeUnitRule(),
FixValueAxisEncodingRule(),
ContiguousCalendarYearDomainRule(),
TemporalAxisCleanupRule(),
DiscreteYearBarXAxisRule(),
SkewnessLogScaleRule(),
PercentageBoundaryClampingRule(),
ValueAxisLabelFormatRule(),
LineYearGapStrokeDashRule(),
LineChartPointHoverRule(),
GeneralErrorBandRule(),
PopulationPyramidRule(),
ZeroLineRule(),
ApplyWBStyleRule(),
]
# ============================================================================
# DRACO CONSTRAINT CONFIG (unchanged)
# ============================================================================
@dataclass
class DracoConstraintConfig:
base_constraints: list[str]
nominal_color_fields: list[str]
color_dimension_priority: list[str]
def __init__(self):
self.base_constraints = ["entity(view,root,view).", "entity(mark,view,m)."]
self.nominal_color_fields = ["country", "sex", "urbanisation", "residence", "ref_area"]
self.color_dimension_priority = ["country", "sex", "age", "urbanisation", "residence"]
DEFAULT_DRACO_CONFIG = DracoConstraintConfig()
|