Skip to content

dyce package reference

  • H represents possible outcomes and their weights as integer counts. A fair, six-sided die can be represented as H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), or the shorthand H((1, 2, 3, 4, 5, 6)), or simply H(6). The sum of three six-sided dice can be represented as 3 @ H(6).
  • P represents an ordered sequence of histograms. A pool of three separate six-sided dice can be represented as 3 @ P(H(6)), or the shorthand 3 @ P(6). Ps keep each die separate, so you can select any die or group of dice and calculate the distribution of their summed results.
  • P.survey and expand are experimental interfaces useful for modeling mechanics where the outcome of one die affects how others are rolled. Examples include: exploding dice, conditional re-rolls, or damage that depends on whether an attack hits.
    • explode_n is provided as a convenient shorthand.

H

Bases: Mapping[_T_co, int], Iterable[_T_co], HableT[_T_co]

An immutable mapping for use as a histogram which supports arithmetic operations. This is useful for modeling discrete outcomes, like individual dice. H objects encode finite discrete probability distributions as integer counts without any denominator.

Info

The lack of an explicit denominator is intentional and has two benefits. First, a denominator is redundant. Without it, one never has to worry about probabilities summing to one (e.g., via miscalculation, floating point error, etc.). Second (and perhaps more importantly), sometimes one wants to have an insight into non-reduced counts, not just probabilities. If needed, probabilities can always be derived, as shown below. While a rational abstraction (e.g., fractions.Fraction) could have been used, ints typically perform better under most circumstances.

The initializer takes a single argument, init_val. In its most explicit form, init_val maps outcome values to counts.

Modeling a single six-sided die (1d6) can be expressed as:

1
2
>>> from dyce import H
>>> d6 = H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})

Two shorthands are provided. If init_val is an operable of numbers, counts of 1 are assumed and outcomes are sorted.

1
2
>>> H(range(6, 0, -1))
H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})

Repeated items are accumulated, as one would expect.

1
2
3
>>> lo_var_d6 = H((5, 4, 4, 3, 3, 2))
>>> lo_var_d6
H({2: 1, 3: 2, 4: 2, 5: 1})

If init_val is an int (and only an int), it is shorthand for creating a sequential range \(\left[ {1} .. {init\_val} \right]\) (or \(\left[ {init\_val} .. {-1} \right]\) if init_val is negative).

1
2
3
4
5
6
7
8
>>> H(8)
H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1})
>>> H(0)
H({})
>>> H(-4.0)  # type: ignore[call-overload]
Traceback (most recent call last):
  ...
TypeError: scalar init_val must be int; use explicit Mapping or Iterable for 'float' outcomes

A work-around

You can usually find a way to coerce the shorthand into the correct type, if needed:

1
2
3
>>> import sympy.abc
>>> (H(-4) + 0.0) * sympy.abc.x
H({-1.0*x: 1, -2.0*x: 1, -3.0*x: 1, -4.0*x: 1})

Histograms are maps, so they can interact with other map types.

1
2
3
4
5
6
7
>>> lo_var_d6 == {2: 1, 3: 2, 4: 2, 5: 1}
True
>>> lo_var_d6 != {}
True
>>> from collections import Counter
>>> lo_var_d6 == Counter(lo_var_d6)
True

Simple indices can be used to look up an outcome’s count.

1
2
>>> lo_var_d6[3]
2

Most arithmetic operators are supported and do what one would expect. If the operand is a number, the operator applies to the outcomes.

1
2
3
4
5
6
7
8
9
>>> d6 + 4
H({5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1})

>>> d6 * -1
H({-6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1})
>>> d6 * -1 == -d6
True
>>> d6 * -1 == H(-6)
True

If the operand is another histogram, the operator applies to the Cartesian product of the outcomes in each histogram, and respective counts are multiplied. Modeling the sum of two six-sided dice (2d6) can be expressed as:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
>>> d6 + d6
H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})
>>> print((d6 + d6).format(width=65))
avg |    7.00
std |    2.42
  2 |   2.78% |#
  3 |   5.56% |##
  4 |   8.33% |####
  5 |  11.11% |#####
  6 |  13.89% |######
  7 |  16.67% |########
  8 |  13.89% |######
  9 |  11.11% |#####
 10 |   8.33% |####
 11 |   5.56% |##
 12 |   2.78% |#

To sum \({n}\) identical histograms, the matrix multiplication operator (@) provides a shorthand.

1
2
>>> 3 @ d6 == d6 + d6 + d6
True

Unary operators are also supported:

1
2
3
4
>>> ~d6
H({-7: 1, -6: 1, -5: 1, -4: 1, -3: 1, -2: 1})
>>> abs(-d6) == d6
True

The len built-in function can be used to show the number of distinct outcomes.

1
2
>>> len(2 @ d6)
11

The total property can be used to compute the total number of combinations and each outcome’s probability.

1
2
3
4
5
6
7
8
>>> from fractions import Fraction
>>> (2 @ d6).total
36
>>> [
...     (outcome, Fraction(count, (2 @ d6).total))
...     for outcome, count in (2 @ d6).items()
... ]
[(2, Fraction(1, 36)), (3, Fraction(1, 18)), (4, Fraction(1, 12)), (5, Fraction(1, 9)), (6, Fraction(5, 36)), (7, Fraction(1, 6)), ..., (12, Fraction(1, 36))]

Histograms provide common comparators (e.g., eq ne, etc.). One way to count how often a first six-sided die shows a different face than a second is:

1
2
3
4
5
6
7
>>> d6.ne(d6)
H({False: 6, True: 30})
>>> print(d6.ne(d6).format(width=65))
  avg |    0.83
  std |    0.37
False |  16.67% |########
 True |  83.33% |########################################

Or, how often a first six-sided die shows a face less than a second is:

1
2
3
4
5
6
7
>>> d6.lt(d6)
H({False: 21, True: 15})
>>> print(d6.lt(d6).format(width=65))
  avg |    0.42
  std |    0.49
False |  58.33% |############################
 True |  41.67% |####################

Or how often at least one 2 will show when rolling four six-sided dice:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> d6_eq2 = d6.eq(2)
>>> d6_eq2  # how often a 2 shows on a single six-sided die
H({False: 5, True: 1})
>>> 4 @ d6_eq2  # number of 2s showing among 4d6
H({0: 625, 1: 500, 2: 150, 3: 20, 4: 1})
>>> (4 @ d6_eq2).ge(1)  # how often at least one 2 shows on 4d6
H({False: 625, True: 671})
>>> print((4 @ d6_eq2).ge(1).format(width=65))
  avg |    0.52
  std |    0.50
False |  48.23% |#######################
 True |  51.77% |########################

Mind your parentheses

Parentheses are often necessary to enforce the desired order of operations. This is most often an issue with the @ operator, because it behaves differently than the d operator in most dedicated grammars. More specifically, in Python, @ has a lower precedence than . and […].

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
>>> 2 @ d6[7]  # type: ignore
Traceback (most recent call last):
  ...
KeyError: 7
>>> 2 @ d6.le(7)  # probably not what was intended
H({2: 36})
>>> 2 @ d6.le(7) == 2 @ (d6.le(7))
True

>>> (2 @ d6)[7]
6
>>> (2 @ d6).le(7)
H({False: 15, True: 21})
>>> 2 @ d6.le(7) == (2 @ d6).le(7)
False

Counts are generally accumulated without reduction. To reduce, call the lowest_terms method.

1
2
3
4
>>> d6.ge(4)
H({False: 3, True: 3})
>>> d6.ge(4).lowest_terms()
H({False: 1, True: 1})

Testing equivalence implicitly performs reductions of operands.

1
2
>>> d6.ge(4) == d6.ge(4).lowest_terms()
True
Source code in dyce/h.py
 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
class H(Mapping[_T_co, int], Iterable[_T_co], HableT[_T_co]):  # type: ignore[type-var] # ty: ignore[invalid-generic-class]
    r"""
    <!-- BEGIN MONKEY PATCH --
    For typing.

        >>> import sympy.abc  # type: ignore[import-untyped]

      -- END MONKEY PATCH -->

    An immutable mapping for use as a histogram which supports arithmetic operations.
    This is useful for modeling discrete outcomes, like individual dice.
    `H` objects encode finite discrete probability distributions as integer counts without any denominator.

    !!! info

        The lack of an explicit denominator is intentional and has two benefits.
        First, a denominator is redundant.
        Without it, one never has to worry about probabilities summing to one (e.g., via miscalculation, floating point error, etc.).
        Second (and perhaps more importantly), sometimes one wants to have an insight into non-reduced counts, not just probabilities.
        If needed, probabilities can always be derived, as shown below.
        While a rational abstraction (e.g., `fractions.Fraction`) could have been used, `int`s typically perform better under most circumstances.

    The [initializer][dyce.H.__init__] takes a single argument, *init_val*.
    In its most explicit form, *init_val* maps outcome values to counts.

    Modeling a single six-sided die (`1d6`) can be expressed as:

        >>> from dyce import H
        >>> d6 = H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})

    Two shorthands are provided.
    If *init_val* is an operable of numbers, counts of 1 are assumed and outcomes are sorted.

        >>> H(range(6, 0, -1))
        H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})

    Repeated items are accumulated, as one would expect.

        >>> lo_var_d6 = H((5, 4, 4, 3, 3, 2))
        >>> lo_var_d6
        H({2: 1, 3: 2, 4: 2, 5: 1})

    If *init_val* is an `int` (and ***only*** an `int`), it is shorthand for creating a sequential range `#!math \left[ {1} .. {init\_val} \right]` (or `#!math \left[ {init\_val} .. {-1} \right]` if *init_val* is negative).

        >>> H(8)
        H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1})
        >>> H(0)
        H({})
        >>> H(-4.0)  # type: ignore[call-overload]
        Traceback (most recent call last):
          ...
        TypeError: scalar init_val must be int; use explicit Mapping or Iterable for 'float' outcomes

    !!! note "A work-around"

        You can usually find a way to coerce the shorthand into the correct type, if needed:

            >>> import sympy.abc
            >>> (H(-4) + 0.0) * sympy.abc.x
            H({-1.0*x: 1, -2.0*x: 1, -3.0*x: 1, -4.0*x: 1})

    Histograms are maps, so they can interact with other map types.

        >>> lo_var_d6 == {2: 1, 3: 2, 4: 2, 5: 1}
        True
        >>> lo_var_d6 != {}
        True
        >>> from collections import Counter
        >>> lo_var_d6 == Counter(lo_var_d6)
        True

    Simple indices can be used to look up an outcome’s count.

        >>> lo_var_d6[3]
        2

    Most arithmetic operators are supported and do what one would expect.
    If the operand is a number, the operator applies to the outcomes.

        >>> d6 + 4
        H({5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1})

        >>> d6 * -1
        H({-6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1})
        >>> d6 * -1 == -d6
        True
        >>> d6 * -1 == H(-6)
        True

    If the operand is another histogram, the operator applies to the Cartesian product of the outcomes in each histogram, and respective counts are multiplied.
    Modeling the sum of two six-sided dice (`2d6`) can be expressed as:

        >>> d6 + d6
        H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})
        >>> print((d6 + d6).format(width=65))
        avg |    7.00
        std |    2.42
          2 |   2.78% |#
          3 |   5.56% |##
          4 |   8.33% |####
          5 |  11.11% |#####
          6 |  13.89% |######
          7 |  16.67% |########
          8 |  13.89% |######
          9 |  11.11% |#####
         10 |   8.33% |####
         11 |   5.56% |##
         12 |   2.78% |#

    To sum `#!math {n}` identical histograms, the matrix multiplication operator (`@`) provides a shorthand.

        >>> 3 @ d6 == d6 + d6 + d6
        True

    Unary operators are also supported:

        >>> ~d6
        H({-7: 1, -6: 1, -5: 1, -4: 1, -3: 1, -2: 1})
        >>> abs(-d6) == d6
        True

    The `len` built-in function can be used to show the number of distinct outcomes.

        >>> len(2 @ d6)
        11

    The [`total` property][dyce.H.total] can be used to compute the total number of combinations and each outcome’s probability.

        >>> from fractions import Fraction
        >>> (2 @ d6).total
        36
        >>> [
        ...     (outcome, Fraction(count, (2 @ d6).total))
        ...     for outcome, count in (2 @ d6).items()
        ... ]
        [(2, Fraction(1, 36)), (3, Fraction(1, 18)), (4, Fraction(1, 12)), (5, Fraction(1, 9)), (6, Fraction(5, 36)), (7, Fraction(1, 6)), ..., (12, Fraction(1, 36))]

    Histograms provide common comparators (e.g., [`eq`][dyce.H.eq] [`ne`][dyce.H.ne], etc.).
    One way to count how often a first six-sided die shows a different face than a second is:

        >>> d6.ne(d6)
        H({False: 6, True: 30})
        >>> print(d6.ne(d6).format(width=65))
          avg |    0.83
          std |    0.37
        False |  16.67% |########
         True |  83.33% |########################################

    Or, how often a first six-sided die shows a face less than a second is:

        >>> d6.lt(d6)
        H({False: 21, True: 15})
        >>> print(d6.lt(d6).format(width=65))
          avg |    0.42
          std |    0.49
        False |  58.33% |############################
         True |  41.67% |####################

    Or how often at least one `2` will show when rolling four six-sided dice:

        >>> d6_eq2 = d6.eq(2)
        >>> d6_eq2  # how often a 2 shows on a single six-sided die
        H({False: 5, True: 1})
        >>> 4 @ d6_eq2  # number of 2s showing among 4d6
        H({0: 625, 1: 500, 2: 150, 3: 20, 4: 1})
        >>> (4 @ d6_eq2).ge(1)  # how often at least one 2 shows on 4d6
        H({False: 625, True: 671})
        >>> print((4 @ d6_eq2).ge(1).format(width=65))
          avg |    0.52
          std |    0.50
        False |  48.23% |#######################
         True |  51.77% |########################

    !!! bug "Mind your parentheses"

        Parentheses are often necessary to enforce the desired order of operations.
        This is most often an issue with the `@` operator, because it behaves differently than the `d` operator in most dedicated grammars.
        More specifically, in Python, `@` has a [lower precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence) than `.` and `[…]`.

            >>> 2 @ d6[7]  # type: ignore
            Traceback (most recent call last):
              ...
            KeyError: 7
            >>> 2 @ d6.le(7)  # probably not what was intended
            H({2: 36})
            >>> 2 @ d6.le(7) == 2 @ (d6.le(7))
            True

            >>> (2 @ d6)[7]
            6
            >>> (2 @ d6).le(7)
            H({False: 15, True: 21})
            >>> 2 @ d6.le(7) == (2 @ d6).le(7)
            False

    Counts are generally accumulated without reduction.
    To reduce, call the [`lowest_terms` method][dyce.H.lowest_terms].

        >>> d6.ge(4)
        H({False: 3, True: 3})
        >>> d6.ge(4).lowest_terms()
        H({False: 1, True: 1})

    Testing equivalence implicitly performs reductions of operands.

        >>> d6.ge(4) == d6.ge(4).lowest_terms()
        True
    """

    __slots__ = (
        "_h",
        "_hash",
        "_order_stat_funcs_by_n",
        "_total",
    )

    @overload
    def __init__(
        self: "H[Never]", init_val: Mapping[Never, SupportsInt], /
    ) -> None: ...
    @overload
    def __init__(self: "H[_T]", init_val: Mapping[_T, SupportsInt], /) -> None: ...
    @overload
    def __init__(self: "H[Never]", init_val: Iterable[Never], /) -> None: ...
    @overload
    def __init__(self: "H[_T]", init_val: Iterable[_T], /) -> None: ...
    @overload
    def __init__(self: "H[Never]", init_val: Literal[0, False], /) -> None: ...
    @overload
    def __init__(self: "H[int]", init_val: int, /) -> None: ...
    def __init__(self, init_val: Any, /) -> None:  # ruff: ignore[complex-structure]
        r"""
        Constructs an [`H`][dyce.H] from *init_val*, which can be a mapping, iterable, or an integer shorthand.
        """
        self._h: dict[_T_co, int]
        self._hash: int | None = None
        self._order_stat_funcs_by_n: dict[int, Callable[[int], H[Any]]] = {}
        self._total: int | None = None

        @nobeartype  # not decoratable by beartype (avoids warning)
        def _sorted_items_iter(
            items: Sequence[tuple[Any, SupportsInt]],
        ) -> Iterator[tuple[Any, int]]:
            sorted_items = [(k, lossless_int(v)) for k, v in items]
            try:
                sorted_items.sort()
            except TypeError:
                sorted_items.sort(key=lambda item: natural_key(item[0]))
            for outcome, count in sorted_items:
                if count < 0:
                    raise ValueError(f"count for {outcome} cannot be negative")
                yield (outcome, count)

        if isinstance(init_val, Iterable):
            if isinstance(init_val, Mapping):
                self._h = dict(_sorted_items_iter(list(init_val.items())))
            else:
                c: Counter[_T_co] = Counter(init_val)
                self._h = dict(_sorted_items_iter(list(c.items())))
        elif isinstance(init_val, int):
            n = abs(init_val)
            if init_val > 0:
                self._h = dict(_sorted_items_iter([(i, 1) for i in range(1, n + 1)]))
            elif init_val < 0:
                self._h = dict(_sorted_items_iter([(i, 1) for i in range(-n, 0)]))
            else:
                self._h = {}
        else:
            raise TypeError(
                f"scalar init_val must be int; use explicit Mapping or Iterable "
                f"for {type(init_val).__qualname__!r} outcomes"
            )
        cur_ctxt = _quantize_ctxt.get()
        if cur_ctxt.bit_width:
            self._h = cast(
                "dict[_T_co, int]",
                _quantize_counts(
                    self._h,
                    cur_ctxt.bit_width,
                    preserve_zero_counts=cur_ctxt.preserve_zero_counts,
                ),
            )

    # ---- Class methods ---------------------------------------------------------------

    @classmethod
    def from_counts(
        cls,
        *sources: Mapping[_T, SupportsInt] | Iterable[tuple[_T, SupportsInt]],
        preserve_zero_counts: bool = False,
    ) -> "H[_T]":
        r"""
        Constructs an [`H`][dyce.H] by accumulating counts from one or more *sources*.

        Each source may be a mapping of outcomes to counts, or an iterable of `(outcome, count)` pairs.
        Counts for the same outcome across all sources are summed.

            >>> H.from_counts([(1, 3), (2, 2), (1, 1)])
            H({1: 4, 2: 2})
            >>> H.from_counts({1: 2, 2: 3}, [(1, 1), (3, 4)])
            H({1: 3, 2: 3, 3: 4})

        With a single mapping source this is equivalent to [`H`][dyce.H] construction, but multiple sources are accumulated rather than raising on duplicate keys.

            >>> H.from_counts(H(6), H(6))
            H({1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 2})

        If *preserve_zero_counts* is `True`, entries with zero counts make it into the final `H` object.
        Otherwise, they are omitted.

            >>> H.from_counts([(2, 2), (1, 1), (3, 0)], H({1: 0, 64: 0}))
            H({1: 1, 2: 2})
            >>> H.from_counts(
            ...     [(2, 2), (1, 1), (3, 0)],
            ...     {1: 0, 64: 0},
            ...     preserve_zero_counts=True,
            ... )
            H({1: 1, 2: 2, 3: 0, 64: 0})
        """
        c: Counter[_T] = Counter()
        for source in sources:
            if isinstance(source, Mapping):
                # The cast is necessary because isinstance only narrows on Mapping, but
                # Iterable[tuple[_T, SupportsInt]] > Mapping[tuple[_T, SupportsInt],
                # Any], so type checkers rightly include that as the inferred return
                # type for source.items()
                source = cast("ItemsView[_T, SupportsInt]", source.items())  # ruff: ignore[redefined-loop-name]
            for outcome, count in source:
                if count or preserve_zero_counts:
                    c[outcome] += lossless_int(count)
        return cast("H[_T]", cls(c))  # pyright: ignore[reportArgumentType,reportCallIssue]

    # ---- Overrides -------------------------------------------------------------------

    def __hash__(self) -> int:
        if self._hash is None:
            self._hash = hash((type(self), *self.lowest_terms().items()))
        return self._hash

    def __repr__(self) -> str:
        return f"{type(self).__name__}({self._h!r})"

    def __eq__(self, other: object) -> bool:
        if isinstance(other, H):
            return bool(self.lowest_terms()._h == other.lowest_terms()._h)
        if isinstance(other, HableOpsMixin):
            return self.__eq__(other.h())
        return super().__eq__(other)

    # ---- Mapping abstract methods ----------------------------------------------------

    def __bool__(self) -> bool:
        return bool(self.total)

    def __getitem__(self, key: object, /) -> int:
        return self._h[key]  # type: ignore[index] # ty: ignore[invalid-argument-type]

    def __iter__(self) -> Iterator[_T_co]:
        return iter(self._h)

    def __len__(self) -> int:
        return len(self._h)

    def counts(self) -> ValuesView[int]:
        r"""A more descriptive synonym for the `values` mapping method."""
        return self._h.values()

    def outcomes(self: "H[_T]") -> KeysView[_T]:
        r"""A more descriptive synonym for the `keys` mapping method."""
        return self._h.keys()

    # ---- HableT abstract methods -----------------------------------------------------

    def h(self: "H[_T]") -> "H[_T]":
        r"""Returns `self`."""
        return self

    # ---- Forward operators -----------------------------------------------------------

    @overload
    def __matmul__(self: "H[Never]", rhs: SupportsInt) -> "H[Never]": ...
    @overload
    def __matmul__(self: "H[Any]", rhs: Literal[0]) -> "H[Never]": ...
    @overload
    # See <https://github.com/jorenham/optype/discussions/574>
    def __matmul__(self: "H[ot.CanAdd[int, int]]", rhs: SupportsInt) -> "H[int]": ...
    @overload
    def __matmul__(self: "H[_CanAddSameT]", rhs: SupportsInt) -> "H[_CanAddSameT]": ...
    # Keep the narrower Literal[1] case first so all type checkers preserve the
    # concrete HableOpsMixin subtype.
    @overload
    def __matmul__(
        self: "H[_HableOpsMixinT]", rhs: Literal[1]
    ) -> "H[_HableOpsMixinT]": ...
    @overload
    def __matmul__(
        self: "H[HableOpsMixin[_CanAddSameT]]", rhs: SupportsInt
    ) -> "H[HableOpsMixin[_CanAddSameT] | H[_CanAddSameT]]": ...
    @overload
    def __matmul__(self: "H[_T]", rhs: Literal[1]) -> "H[_T]": ...
    def __matmul__(self: "H[Any]", rhs: SupportsInt) -> "H[Any]":
        n = lossless_int_or_not_implemented(rhs)
        if n is NotImplemented:
            return NotImplemented
        if n < 0:
            raise ValueError(
                f"{type(self).__name__} requires non-negative operand for @ operator (found {n!r})"
            )
        result = _convolve(self._h, n)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __add__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanRAddHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __add__(
        self: "H[HableOpsMixin[ot.CanAdd[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __add__(self: "H[int]", rhs: "H[int]") -> "H[int]": ...
    @overload
    # See <https://github.com/astral-sh/ty/issues/3234>.
    def __add__(self: "H[float]", rhs: "H[float]") -> "H[float]": ...
    @overload
    def __add__(
        self: "H[ot.CanAdd[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __add__(
        self: "H[ot.CanAdd[_OtherT, _ResultT]]", rhs: "HableOpsMixin[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __add__(
        self: "H[ot.CanAdd[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __add__(self: "H[_T]", rhs: "H[ot.CanAdd[_T, _ResultT]]") -> "H[_ResultT]": ...
    @overload
    def __add__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanAdd[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __add__(self: "H[_T]", rhs: ot.CanAdd[_T, _ResultT]) -> "H[_ResultT]": ...
    def __add__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(lhs, "__add__", "__radd__", rhs),
            )
        else:
            result = _map_opname_fwd(self._h, "__add__", "__radd__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __sub__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanRSubHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __sub__(
        self: "H[HableOpsMixin[ot.CanSub[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __sub__(self: "H[int]", rhs: "H[int]") -> "H[int]": ...
    @overload
    # See <https://github.com/astral-sh/ty/issues/3234>.
    def __sub__(self: "H[float]", rhs: "H[float]") -> "H[float]": ...
    @overload
    def __sub__(
        self: "H[ot.CanSub[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __sub__(
        self: "H[ot.CanSub[_OtherT, _ResultT]]", rhs: "HableOpsMixin[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __sub__(
        self: "H[ot.CanSub[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __sub__(self: "H[_T]", rhs: "H[ot.CanSub[_T, _ResultT]]") -> "H[_ResultT]": ...
    @overload
    def __sub__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanSub[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __sub__(self: "H[_T]", rhs: ot.CanSub[_T, _ResultT]) -> "H[_ResultT]": ...
    def __sub__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(lhs, "__sub__", "__rsub__", rhs),
            )
        else:
            result = _map_opname_fwd(self._h, "__sub__", "__rsub__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __mul__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanRMulHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __mul__(
        self: "H[HableOpsMixin[ot.CanMul[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __mul__(
        self: "H[ot.CanMul[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __mul__(
        self: "H[ot.CanMul[_OtherT, _ResultT]]", rhs: "HableOpsMixin[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __mul__(
        self: "H[ot.CanMul[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __mul__(self: "H[_T]", rhs: "H[ot.CanMul[_T, _ResultT]]") -> "H[_ResultT]": ...
    @overload
    def __mul__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanMul[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __mul__(self: "H[_T]", rhs: ot.CanMul[_T, _ResultT]) -> "H[_ResultT]": ...
    def __mul__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(lhs, "__mul__", "__rmul__", rhs),
            )
        else:
            result = _map_opname_fwd(self._h, "__mul__", "__rmul__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __truediv__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanRTruedivHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __truediv__(
        self: "H[HableOpsMixin[ot.CanTruediv[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __truediv__(
        self: "H[ot.CanTruediv[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __truediv__(
        self: "H[ot.CanTruediv[_OtherT, _ResultT]]",
        rhs: "HableOpsMixin[_OtherT]",
    ) -> "H[_ResultT]": ...
    @overload
    def __truediv__(
        self: "H[ot.CanTruediv[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __truediv__(
        self: "H[_T]", rhs: "H[ot.CanTruediv[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __truediv__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanTruediv[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __truediv__(
        self: "H[_T]", rhs: ot.CanTruediv[_T, _ResultT]
    ) -> "H[_ResultT]": ...
    def __truediv__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(lhs, "__truediv__", "__rtruediv__", rhs),
            )
        else:
            result = _map_opname_fwd(self._h, "__truediv__", "__rtruediv__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __floordiv__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanRFloordivHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __floordiv__(
        self: "H[HableOpsMixin[ot.CanFloordiv[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __floordiv__(
        self: "H[ot.CanFloordiv[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __floordiv__(
        self: "H[ot.CanFloordiv[_OtherT, _ResultT]]",
        rhs: "HableOpsMixin[_OtherT]",
    ) -> "H[_ResultT]": ...
    @overload
    def __floordiv__(
        self: "H[ot.CanFloordiv[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __floordiv__(
        self: "H[_T]", rhs: "H[ot.CanFloordiv[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __floordiv__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanFloordiv[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __floordiv__(
        self: "H[_T]", rhs: ot.CanFloordiv[_T, _ResultT]
    ) -> "H[_ResultT]": ...
    def __floordiv__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(
                    lhs, "__floordiv__", "__rfloordiv__", rhs
                ),
            )
        else:
            result = _map_opname_fwd(self._h, "__floordiv__", "__rfloordiv__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __mod__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanRModHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __mod__(
        self: "H[HableOpsMixin[ot.CanMod[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __mod__(
        self: "H[ot.CanMod[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __mod__(
        self: "H[ot.CanMod[_OtherT, _ResultT]]", rhs: "HableOpsMixin[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __mod__(
        self: "H[ot.CanMod[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __mod__(self: "H[_T]", rhs: "H[ot.CanMod[_T, _ResultT]]") -> "H[_ResultT]": ...
    @overload
    def __mod__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanMod[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __mod__(self: "H[_T]", rhs: ot.CanMod[_T, _ResultT]) -> "H[_ResultT]": ...
    def __mod__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(lhs, "__mod__", "__rmod__", rhs),
            )
        else:
            result = _map_opname_fwd(self._h, "__mod__", "__rmod__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __pow__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanRPowHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __pow__(
        self: "H[HableOpsMixin[ot.CanPow2[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __pow__(
        self: "H[ot.CanPow2[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __pow__(
        self: "H[ot.CanPow2[_OtherT, _ResultT]]", rhs: "HableOpsMixin[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __pow__(
        self: "H[ot.CanPow2[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __pow__(self: "H[_T]", rhs: "H[ot.CanPow2[_T, _ResultT]]") -> "H[_ResultT]": ...
    @overload
    def __pow__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanPow2[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __pow__(self: "H[_T]", rhs: ot.CanPow2[_T, _ResultT]) -> "H[_ResultT]": ...
    def __pow__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(lhs, "__pow__", "__rpow__", rhs),
            )
        else:
            result = _map_opname_fwd(self._h, "__pow__", "__rpow__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __lshift__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanRLshiftHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __lshift__(
        self: "H[HableOpsMixin[ot.CanLshift[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __lshift__(
        self: "H[ot.CanLshift[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __lshift__(
        self: "H[ot.CanLshift[_OtherT, _ResultT]]", rhs: "HableOpsMixin[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __lshift__(
        self: "H[ot.CanLshift[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __lshift__(
        self: "H[_T]", rhs: "H[ot.CanLshift[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __lshift__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanLshift[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __lshift__(self: "H[_T]", rhs: ot.CanLshift[_T, _ResultT]) -> "H[_ResultT]": ...
    def __lshift__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(lhs, "__lshift__", "__rlshift__", rhs),
            )
        else:
            result = _map_opname_fwd(self._h, "__lshift__", "__rlshift__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __rshift__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanRRshiftHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __rshift__(
        self: "H[HableOpsMixin[ot.CanRshift[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __rshift__(
        self: "H[ot.CanRshift[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __rshift__(
        self: "H[ot.CanRshift[_OtherT, _ResultT]]", rhs: "HableOpsMixin[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __rshift__(
        self: "H[ot.CanRshift[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __rshift__(
        self: "H[_T]", rhs: "H[ot.CanRshift[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __rshift__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanRshift[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __rshift__(self: "H[_T]", rhs: ot.CanRshift[_T, _ResultT]) -> "H[_ResultT]": ...
    def __rshift__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(lhs, "__rshift__", "__rrshift__", rhs),
            )
        else:
            result = _map_opname_fwd(self._h, "__rshift__", "__rrshift__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __and__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanRAndHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __and__(
        self: "H[HableOpsMixin[ot.CanAnd[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __and__(
        self: "H[ot.CanAnd[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __and__(
        self: "H[ot.CanAnd[_OtherT, _ResultT]]", rhs: "HableOpsMixin[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __and__(
        self: "H[ot.CanAnd[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __and__(self: "H[_T]", rhs: "H[ot.CanAnd[_T, _ResultT]]") -> "H[_ResultT]": ...
    @overload
    def __and__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanAnd[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __and__(self: "H[_T]", rhs: ot.CanAnd[_T, _ResultT]) -> "H[_ResultT]": ...
    def __and__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(lhs, "__and__", "__rand__", rhs),
            )
        else:
            result = _map_opname_fwd(self._h, "__and__", "__rand__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __or__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanROrHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __or__(
        self: "H[HableOpsMixin[ot.CanOr[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __or__(
        self: "H[ot.CanOr[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __or__(
        self: "H[ot.CanOr[_OtherT, _ResultT]]", rhs: "HableOpsMixin[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __or__(
        self: "H[ot.CanOr[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __or__(self: "H[_T]", rhs: "H[ot.CanOr[_T, _ResultT]]") -> "H[_ResultT]": ...
    @overload
    def __or__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanOr[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __or__(self: "H[_T]", rhs: ot.CanOr[_T, _ResultT]) -> "H[_ResultT]": ...
    def __or__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(lhs, "__or__", "__ror__", rhs),
            )
        else:
            result = _map_opname_fwd(self._h, "__or__", "__ror__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __xor__(  # type: ignore[overload-overlap]
        self: "H[_T]", rhs: _CanRXorHableOpsOptOut["H[_T]", _ResultT]
    ) -> _ResultT: ...
    @overload
    def __xor__(
        self: "H[HableOpsMixin[ot.CanXor[_OtherT, _ResultT]]]",
        rhs: "H[HableOpsMixin[_OtherT]]",
    ) -> "H[H[_ResultT]]": ...
    @overload
    def __xor__(
        self: "H[ot.CanXor[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __xor__(
        self: "H[ot.CanXor[_OtherT, _ResultT]]", rhs: "HableOpsMixin[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __xor__(
        self: "H[ot.CanXor[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __xor__(self: "H[_T]", rhs: "H[ot.CanXor[_T, _ResultT]]") -> "H[_ResultT]": ...
    @overload
    def __xor__(
        self: "H[_T]", rhs: "HableOpsMixin[ot.CanXor[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __xor__(self: "H[_T]", rhs: ot.CanXor[_T, _ResultT]) -> "H[_ResultT]": ...
    def __xor__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        rhs = _flatten_to_h(rhs)
        if isinstance(rhs, H):
            result = _h_binary_callable(
                self._h,
                rhs._h,
                lambda lhs, rhs: _apply_opname(lhs, "__xor__", "__rxor__", rhs),
            )
        else:
            result = _map_opname_fwd(self._h, "__xor__", "__rxor__", rhs)
        return NotImplemented if result is NotImplemented else H(result)

    # ---- Reflected operators ---------------------------------------------------------

    @overload
    def __rmatmul__(self: "H[Never]", lhs: SupportsInt) -> "H[Never]": ...
    @overload
    def __rmatmul__(self: "H[Any]", lhs: Literal[0]) -> "H[Never]": ...
    @overload
    # See <https://github.com/jorenham/optype/discussions/574>
    def __rmatmul__(self: "H[ot.CanAdd[int, int]]", lhs: SupportsInt) -> "H[int]": ...
    @overload
    def __rmatmul__(self: "H[_CanAddSameT]", lhs: SupportsInt) -> "H[_CanAddSameT]": ...
    # Keep the narrower Literal[1] case first so all type checkers preserve the
    # concrete HableOpsMixin subtype.
    @overload
    def __rmatmul__(
        self: "H[_HableOpsMixinT]", lhs: Literal[1]
    ) -> "H[_HableOpsMixinT]": ...
    @overload
    def __rmatmul__(
        self: "H[HableOpsMixin[_CanAddSameT]]", lhs: SupportsInt
    ) -> "H[HableOpsMixin[_CanAddSameT] | H[_CanAddSameT]]": ...
    @overload
    def __rmatmul__(self: "H[_T]", lhs: Literal[1]) -> "H[_T]": ...
    def __rmatmul__(self: "H[Any]", lhs: SupportsInt) -> "H[Any]":
        return self.__matmul__(lhs)

    @overload
    def __radd__(
        self: "H[ot.CanRAdd[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __radd__(self: "H[_T]", lhs: ot.CanRAdd[_T, _ResultT]) -> "H[_ResultT]": ...
    def __radd__(self, lhs: object) -> object:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__add__", "__radd__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __rsub__(
        self: "H[ot.CanRSub[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __rsub__(self: "H[_T]", lhs: ot.CanRSub[_T, _ResultT]) -> "H[_ResultT]": ...
    def __rsub__(self, lhs: object) -> "H[object]":
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__sub__", "__rsub__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __rmul__(
        self: "H[ot.CanRMul[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __rmul__(self: "H[_T]", lhs: ot.CanRMul[_T, _ResultT]) -> "H[_ResultT]": ...
    def __rmul__(self, lhs: object) -> "H[object]":
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__mul__", "__rmul__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __rtruediv__(
        self: "H[ot.CanRTruediv[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __rtruediv__(
        self: "H[_T]", lhs: ot.CanRTruediv[_T, _ResultT]
    ) -> "H[_ResultT]": ...
    def __rtruediv__(self, lhs: object) -> "H[object]":
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__truediv__", "__rtruediv__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __rfloordiv__(
        self: "H[ot.CanRFloordiv[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __rfloordiv__(
        self: "H[_T]", lhs: ot.CanRFloordiv[_T, _ResultT]
    ) -> "H[_ResultT]": ...
    def __rfloordiv__(self, lhs: object) -> "H[object]":
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__floordiv__", "__rfloordiv__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __rmod__(
        self: "H[ot.CanRMod[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __rmod__(self: "H[_T]", lhs: ot.CanRMod[_T, _ResultT]) -> "H[_ResultT]": ...
    def __rmod__(self, lhs: object) -> "H[object]":
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__mod__", "__rmod__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __rpow__(
        self: "H[ot.CanRPow[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __rpow__(self: "H[_T]", lhs: ot.CanRPow[_T, _ResultT]) -> "H[_ResultT]": ...
    def __rpow__(self, lhs: object) -> "H[object]":
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__pow__", "__rpow__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __rlshift__(
        self: "H[ot.CanRLshift[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __rlshift__(
        self: "H[_T]", lhs: ot.CanRLshift[_T, _ResultT]
    ) -> "H[_ResultT]": ...
    def __rlshift__(self, lhs: object) -> "H[object]":
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__lshift__", "__rlshift__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __rrshift__(
        self: "H[ot.CanRRshift[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __rrshift__(
        self: "H[_T]", lhs: ot.CanRRshift[_T, _ResultT]
    ) -> "H[_ResultT]": ...
    def __rrshift__(self, lhs: object) -> "H[object]":
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__rshift__", "__rrshift__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __rand__(
        self: "H[ot.CanRAnd[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __rand__(self: "H[_T]", lhs: ot.CanRAnd[_T, _ResultT]) -> "H[_ResultT]": ...
    def __rand__(self, lhs: object) -> "H[object]":
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__and__", "__rand__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __ror__(
        self: "H[ot.CanROr[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __ror__(self: "H[_T]", lhs: ot.CanROr[_T, _ResultT]) -> "H[_ResultT]": ...
    def __ror__(self, lhs: object) -> "H[object]":
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__or__", "__ror__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def __rxor__(
        self: "H[ot.CanRXor[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> "H[_ResultT]": ...
    @overload
    def __rxor__(self: "H[_T]", lhs: ot.CanRXor[_T, _ResultT]) -> "H[_ResultT]": ...
    def __rxor__(self, lhs: object) -> "H[object]":
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        result = _map_opname_ref(self._h, "__xor__", "__rxor__", lhs)
        return NotImplemented if result is NotImplemented else H(result)

    @overload
    def lt(self: "H[ot.CanLt[_OtherT, bool]]", rhs: "H[_OtherT]") -> "H[bool]": ...
    @overload
    def lt(self: "H[ot.CanLt[_OtherT, bool]]", rhs: _OtherT) -> "H[bool]": ...
    def lt(self, rhs: "H[object] | object") -> "H[bool]":
        r"""
        Shorthand for `self.apply(optype.do_lt, rhs)`.

            >>> H(20).lt(10)
            H({False: 11, True: 9})
            >>> H(6).lt(H(10)).lowest_terms()
            H({False: 7, True: 13})
        """
        return self.apply(ot.do_lt, rhs)  # pyright: ignore[reportArgumentType,reportCallIssue] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def le(self: "H[ot.CanLe[_OtherT, bool]]", rhs: "H[_OtherT]") -> "H[bool]": ...
    @overload
    def le(self: "H[ot.CanLe[_OtherT, bool]]", rhs: _OtherT) -> "H[bool]": ...
    def le(self, rhs: "H[object] | object") -> "H[bool]":
        r"""
        Shorthand for `self.apply(optype.do_le, rhs)`.

            >>> H(20).le(10)
            H({False: 10, True: 10})
            >>> H(6).le(H(10)).lowest_terms()
            H({False: 1, True: 3})
        """
        return self.apply(ot.do_le, rhs)  # pyright: ignore[reportArgumentType,reportCallIssue] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def eq(self: "H[ot.CanEq[_OtherT, bool]]", rhs: "H[_OtherT]") -> "H[bool]": ...
    @overload
    def eq(self: "H[ot.CanEq[_OtherT, bool]]", rhs: _OtherT) -> "H[bool]": ...
    def eq(self, rhs: "H[object] | object") -> "H[bool]":
        r"""
        Shorthand for `self.apply(optype.do_eq, rhs)`.

            >>> H(20).eq(10)
            H({False: 19, True: 1})
            >>> H(6).eq(H(10)).lowest_terms()
            H({False: 9, True: 1})
        """
        return self.apply(ot.do_eq, rhs)

    @overload
    def ne(self: "H[ot.CanNe[_OtherT, bool]]", rhs: "H[_OtherT]") -> "H[bool]": ...
    @overload
    def ne(self: "H[ot.CanNe[_OtherT, bool]]", rhs: _OtherT) -> "H[bool]": ...
    def ne(self, rhs: "H[object] | object") -> "H[bool]":
        r"""
        Shorthand for `self.apply(optype.do_ne, rhs)`.

            >>> H(20).ne(10)
            H({False: 1, True: 19})
            >>> H(6).ne(H(10)).lowest_terms()
            H({False: 1, True: 9})
        """
        return self.apply(ot.do_ne, rhs)

    @overload
    def ge(self: "H[ot.CanGe[_OtherT, bool]]", rhs: "H[_OtherT]") -> "H[bool]": ...
    @overload
    def ge(self: "H[ot.CanGe[_OtherT, bool]]", rhs: _OtherT) -> "H[bool]": ...
    def ge(self, rhs: "H[object] | object") -> "H[bool]":
        r"""
        Shorthand for `self.apply(optype.do_ge, rhs)`.

            >>> H(20).ge(10)
            H({False: 9, True: 11})
            >>> H(6).ge(H(10)).lowest_terms()
            H({False: 13, True: 7})
        """
        return self.apply(ot.do_ge, rhs)  # pyright: ignore[reportArgumentType,reportCallIssue] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def gt(self: "H[ot.CanGt[_OtherT, bool]]", rhs: "H[_OtherT]") -> "H[bool]": ...
    @overload
    def gt(self: "H[ot.CanGt[_OtherT, bool]]", rhs: _OtherT) -> "H[bool]": ...
    def gt(self, rhs: "H[object] | object") -> "H[bool]":
        r"""
        Shorthand for `self.apply(optype.do_gt, rhs)`.

            >>> H(20).gt(10)
            H({False: 10, True: 10})
            >>> H(6).gt(H(10)).lowest_terms()
            H({False: 3, True: 1})
        """
        return self.apply(ot.do_gt, rhs)  # pyright: ignore[reportArgumentType,reportCallIssue] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    # ---- Unary operators -------------------------------------------------------------

    def __neg__(self: "H[ot.CanNeg[_ResultT]]") -> "H[_ResultT]":
        result = _h_unary_opname(self._h, "__neg__")
        if result is NotImplemented:
            raise TypeError(
                f"bad operand type for unary -: {type(next(iter(self._h))).__qualname__!r}"
            )
        return H(result)

    def __pos__(self: "H[ot.CanPos[_ResultT]]") -> "H[_ResultT]":
        result = _h_unary_opname(self._h, "__pos__")
        if result is NotImplemented:
            raise TypeError(
                f"bad operand type for unary +: {type(next(iter(self._h))).__qualname__!r}"
            )
        return H(result)

    def __abs__(self: "H[ot.CanAbs[_ResultT]]") -> "H[_ResultT]":
        result = _h_unary_opname(self._h, "__abs__")
        if result is NotImplemented:
            raise TypeError(
                f"bad operand type for abs(): {type(next(iter(self._h))).__qualname__!r}"
            )
        return H(result)

    def __invert__(self: "H[ot.CanInvert[_ResultT]]") -> "H[_ResultT]":
        result = _h_unary_opname(self._h, "__invert__")
        if result is NotImplemented:
            raise TypeError(
                f"bad operand type for unary ~: {type(next(iter(self._h))).__qualname__!r}"
            )
        return H(result)

    # ---- Properties ------------------------------------------------------------------

    @property
    def total(self) -> int:
        r"""
        Equivalent to `sum(self.counts())`.

        The result is cached to avoid redundant computation with multiple accesses.

            >>> H({4: 2, 5: 3, 6: 1}).total
            6
            >>> H({}).total
            0
        """
        if self._total is None:
            self._total = sum(self._h.values())
        return self._total

    # ---- Methods ---------------------------------------------------------------------

    @overload
    def apply(
        self: "H[_T]",
        func: Callable[[_T], _ResultT],
    ) -> "H[_ResultT]": ...
    @overload
    def apply(
        self: "H[_T]",
        func: Callable[[_T, _OtherT], _ResultT],
        other: "H[_OtherT]",
    ) -> "H[_ResultT]": ...
    @overload
    def apply(
        self: "H[_T]",
        func: Callable[[_T, _OtherT], _ResultT],
        other: _OtherT,
    ) -> "H[_ResultT]": ...
    def apply(
        self: "H[_T]",
        func: Callable[[_T], _ResultT] | Callable[[_T, _OtherT], _ResultT],
        other: "H[_OtherT] | _OtherT | SentinelT" = Sentinel,
    ) -> "H[_ResultT]":
        r"""
        Returns a new [`H`][dyce.H] by applying *func* to outcomes.

        If *other* is provided, *func* should have two parameters, otherwise it should have one.
        If *other* is an [`H`][dyce.H], take the Cartesian product of both histograms’ items: call `func(h_outcome, other_outcome)` for each pair and accumulate `h_count * other_count`.
        If *other* is a scalar, call `func(outcome, other)` for each outcome, passing counts through unchanged.

        Resulting counts for duplicate outcomes are summed.

            >>> import operator
            >>> H({10: 1, 20: 1}).apply(operator.sub, 10)
            H({0: 1, 10: 1})
            >>> H({10: 1, 20: 1}).apply(operator.sub, H({1: 1, 2: 1}))
            H({8: 1, 9: 1, 18: 1, 19: 1})

            >>> # optype provides reflected operator functions as do_r*
            >>> import optype as ot

            >>> H({10: 1, 20: 1}).apply(ot.do_rsub, 10)
            H({-10: 1, 0: 1})

            >>> H({10: 1, 20: 1}).apply(ot.do_rsub, H({1: 1, 2: 1}))
            H({-19: 1, -18: 1, -9: 1, -8: 1})

        One way to compute how often a six-sided die “beats” an eight-sided die rolled together:

            >>> from enum import IntEnum

            >>> class Versus(IntEnum):
            ...     LOSS = -1
            ...     DRAW = 0
            ...     WIN = 1

            >>> d6 = H(6)
            >>> d8 = H(8)
            >>> vs = lambda h_outcome, other_outcome: (
            ...     Versus.LOSS
            ...     if h_outcome < other_outcome
            ...     else Versus.WIN
            ...     if h_outcome > other_outcome
            ...     else Versus.DRAW
            ... )
            >>> d6.apply(vs, d8)
            H({<Versus.LOSS: -1>: 27, <Versus.DRAW: 0>: 6, <Versus.WIN: 1>: 15})

        Omitting *other* allows examination of just the histogram.
        One way to determine *Apocalypse World* mechanic outcomes with a modifier:

            >>> class PBTA(IntEnum):
            ...     MISS = 0
            ...     WEAK_HIT = 1
            ...     STRONG_HIT = 2

            >>> mod = +1
            >>> pbta_result = (2 @ H(6) + mod).apply(
            ...     lambda outcome: (
            ...         PBTA.MISS
            ...         if outcome <= 6
            ...         else PBTA.WEAK_HIT
            ...         if 7 <= outcome <= 9
            ...         else PBTA.STRONG_HIT
            ...     )
            ... )
            >>> pbta_result
            H({<PBTA.MISS: 0>: 10, <PBTA.WEAK_HIT: 1>: 16, <PBTA.STRONG_HIT: 2>: 10})

        One way to count how often summing outcomes comes out even on 2d3:

            >>> d3_2 = 2 @ H(3)
            >>> d3_2
            H({2: 1, 3: 2, 4: 3, 5: 2, 6: 1})
            >>> d3_2_is_even = d3_2.apply(lambda outcome: outcome % 2 == 0)
            >>> d3_2_is_even
            H({False: 4, True: 5})
            >>> (d3_2 % 2).eq(0) == d3_2_is_even
            True
            >>> ((d3_2 + 1) % 2) == d3_2_is_even
            True
        """
        if other is Sentinel:
            result: dict[_ResultT, int] = {}
            func = cast("Callable[[_T], _ResultT]", func)
            for outcome, count in self._h.items():
                new_outcome = func(outcome)
                result[new_outcome] = result.get(new_outcome, 0) + count
            return H(result)

        func = cast("Callable[[_T, _OtherT], _ResultT]", func)
        if isinstance(other, H):
            return H(
                cast("dict[_ResultT, int]", _h_binary_callable(self._h, other._h, func))  # ruff: ignore[private-member-access]
            )
        else:
            return H(
                cast(
                    "dict[_ResultT, int]", _h_binary_callable(self._h, {other: 1}, func)
                )
            )

    @experimental
    def exactly_k_times_in_n(
        self: "H[_T]",
        outcome: _T,
        n: SupportsInt,
        k: SupportsInt,
    ) -> int:
        r"""
        Computes and returns (in constant time) the number of ways *outcome* appears exactly *k* times among *n* like histograms.

        Uses the binomial coefficient as a more efficient alternative to `(n @ self.eq(outcome))[k]`.

            >>> H(6).exactly_k_times_in_n(outcome=5, n=4, k=2)
            150
            >>> H((2, 3, 3, 4, 4, 5)).exactly_k_times_in_n(outcome=2, n=3, k=3)
            1
            >>> H((2, 3, 3, 4, 4, 5)).exactly_k_times_in_n(outcome=4, n=3, k=3)
            8

        !!! note "Counts, not probabilities"

            This returns a *count* of ways, not a probability, and may not be in lowest terms.
            (See [`lowest_terms`][dyce.H.lowest_terms].)
            Divide by `self.total ** n` to get a probability.
            (See [`total`][dyce.H.total].)

                >>> from fractions import Fraction
                >>> h = H((2, 3, 3, 4, 4, 5))
                >>> n, k = 3, 2
                >>> (n @ h).total == h.total**n
                True
                >>> Fraction(h.exactly_k_times_in_n(outcome=3, n=n, k=k), h.total**n)
                Fraction(2, 9)
                >>> h_not_lowest_terms = H.from_counts(h, h)
                >>> h == h_not_lowest_terms
                True
                >>> h_not_lowest_terms
                H({2: 2, 3: 4, 4: 4, 5: 2})
                >>> h_not_lowest_terms.exactly_k_times_in_n(outcome=3, n=n, k=k)
                384
                >>> Fraction(
                ...     h_not_lowest_terms.exactly_k_times_in_n(outcome=3, n=n, k=k),
                ...     h_not_lowest_terms.total**n,
                ... )
                Fraction(2, 9)
        """
        n = lossless_int(n)
        k = lossless_int(k)

        if k > n:
            raise ValueError(f"k ({k!r}) must be less than or equal to n ({n!r})")

        c_outcome = self.get(outcome, 0)
        return math.comb(n, k) * c_outcome**k * (self.total - c_outcome) ** (n - k)  # type: ignore[no-any-return]

    def format(
        self,
        *,
        precision: int = DEFAULT_PRECISION,
        scaled: bool = False,
        tick: str = "#",
        width: int = _ROW_WIDTH,
    ) -> str:
        r"""
        Returns a formatted string representation of the histogram.

        *precision* is the number of decimal places to use and defaults to `2`.
        *tick* is used as the bar character and defaults to `"#"`.
        *width* must be positive and is the maximum width of the horizontal bar ASCII graph.

            >>> print(
            ...     H.from_counts(
            ...         (2 @ H(6)),
            ...         dict.fromkeys(range(1, 21), 0),
            ...         preserve_zero_counts=True,
            ...     ).format(precision=4, tick="@", width=65)
            ... )
            avg |    7.0000
            std |    2.4152
              1 |   0.0000% |
              2 |   2.7778% |@
              3 |   5.5556% |@@
              4 |   8.3333% |@@@@
              5 |  11.1111% |@@@@@
              6 |  13.8889% |@@@@@@
              7 |  16.6667% |@@@@@@@@
              8 |  13.8889% |@@@@@@
              9 |  11.1111% |@@@@@
             10 |   8.3333% |@@@@
             11 |   5.5556% |@@
             12 |   2.7778% |@
             13 |   0.0000% |
             14 |   0.0000% |
             15 |   0.0000% |
             16 |   0.0000% |
             17 |   0.0000% |
             18 |   0.0000% |
             19 |   0.0000% |
             20 |   0.0000% |

        If *scaled* is `True`, horizontal bars are scaled to *width*.

            >>> h_ge = (2 @ H(6)).ge(7)
            >>> print(f"{' 65 chars wide -->|':->65}")
            ---------------------------------------------- 65 chars wide -->|
            >>> print(H(1).format(scaled=False, width=65))
            avg |    1.00
            std |    0.00
              1 | 100.00% |##################################################
            >>> print(h_ge.format(scaled=False, width=65))
              avg |    0.58
              std |    0.49
            False |  41.67% |####################
             True |  58.33% |############################
            >>> print(h_ge.format(scaled=True, width=65))
              avg |    0.58
              std |    0.49
            False |  41.67% |##################################
             True |  58.33% |################################################
        """
        # Get the length of the fixed-width column " | {<var>:7.2%} |" for computing the
        # available tick space
        prob_width = 5 + precision
        prob_len = len(f" | {0.0:{prob_width}.{precision}%} |")
        try:
            mu: float | None = self.mean()  # type: ignore[misc] # ty: ignore[invalid-argument-type]
            std: float | None = self.stdev()  # type: ignore[misc] # ty: ignore[invalid-argument-type]
        except Exception as exc:  # ruff: ignore[blind-except]
            # Broad catch is intentional: format() is a display method that should
            # always produce output. Any failure to compute statistics (including from
            # runtime type checkers like beartype) is treated as "stats not available"
            # rather than an error.
            warnings.warn(f"{exc!s}", stacklevel=2)
            mu = None
            std = None

        def _lines() -> Iterator[str]:
            # First pass: collect (outcome_str, probability) pairs and find the widest
            # outcome representation. We need max_outcome_len before we can emit
            # anything, because the stats header must align with it.
            pairs: list[tuple[str, Fraction]] = []
            max_outcome_len = 3  # minimum column width
            for outcome, probability in self.probability_items():
                outcome_str = repr(outcome)
                max_outcome_len = max(max_outcome_len, len(outcome_str))
                pairs.append((outcome_str, probability))

            # Stats header (emitted before outcome rows)
            if mu is not None:
                yield f"{'avg': >{max_outcome_len}} | {mu:{prob_width}.{precision}f}"
            if std is not None:
                yield f"{'std': >{max_outcome_len}} | {std:{prob_width}.{precision}f}"

            if pairs:
                tick_scale = max(self.counts()) / self.total if scaled else 1.0
                max_num_ticks = (width - max_outcome_len - prob_len) // len(tick)
                for outcome_str, probability in pairs:
                    ticks = tick * int(max_num_ticks * float(probability) / tick_scale)
                    yield f"{outcome_str: >{max_outcome_len}} | {float(probability):{prob_width}.{precision}%} |{ticks}"

        return os.linesep.join(_lines())

    def format_short(
        self,
        *,
        include_avg: bool = True,
        precision: int = DEFAULT_PRECISION,
    ) -> str:
        r"""
        Returns a short-form formatted string representation of the histogram.

            >>> print(H(6).format_short())
            {avg: 3.50, 1: 16.67%, 2: 16.67%, 3: 16.67%, 4: 16.67%, 5: 16.67%, 6: 16.67%}
            >>> print(
            ...     H(6).format_short(
            ...         include_avg=False,
            ...         precision=3,  # decimal places
            ...     )
            ... )
            {1: 16.667%, 2: 16.667%, 3: 16.667%, 4: 16.667%, 5: 16.667%, 6: 16.667%}
        """
        prob_width = 5 + precision
        mu: float | None = None
        if include_avg:
            try:
                mu = self.mean()  # type: ignore[misc] # ty: ignore[invalid-argument-type]
            except Exception as exc:  # ruff: ignore[blind-except]
                # See format() for rationale
                warnings.warn(f"{exc!s}", stacklevel=2)

        def _parts() -> Iterator[str]:
            if mu is not None:
                yield f"avg: {mu:.2f}"
            yield from (
                f"{outcome!r}:{float(probability):{prob_width}.{precision}%}"
                for outcome, probability in self.probability_items()
            )

        return f"{{{', '.join(_parts())}}}"

    def lowest_terms(self: "H[_T]", *, preserve_zero_counts: bool = False) -> "H[_T]":
        r"""
        Returns a new [`H`][dyce.H] with zero-count outcomes removed and all counts divided by their GCD.

            >>> H({1: 2, 2: 4, 3: 6, 4: 0}).lowest_terms()
            H({1: 1, 2: 2, 3: 3})
            >>> H({1: 3, 2: 0, 3: 6}).lowest_terms()
            H({1: 1, 3: 2})
            >>> H({}).lowest_terms()
            H({})

        If *preserve_zero_counts* is `True`, counts are reduced, but zero counts are kept.

            >>> H({1: 2, 2: 4, 3: 6, 4: 0}).lowest_terms(preserve_zero_counts=True)
            H({1: 1, 2: 2, 3: 3, 4: 0})
        """
        counts = tuple(count for count in self._h.values() if count)
        if not counts:
            return H({})
        g = math.gcd(*counts)
        return H(
            {
                outcome: count // g
                for outcome, count in self._h.items()
                if count or preserve_zero_counts
            }
        )

    def mean(self: "H[SupportsFloat]") -> float:
        r"""
        Returns the mean (expected value) of the weighted outcomes.

        Raises `ValueError` if the histogram is empty.

            >>> H(6).mean()
            3.5
            >>> H({1: 1, 3: 1}).mean()
            2.0
        """
        if not self._h:
            raise ValueError("mean of empty histogram is undefined")
        weighted_outcomes = (
            outcome * count  # type: ignore[operator] # ty: ignore[unsupported-operator]
            for outcome, count in self.items()
        )
        return float(reduce(operator.add, weighted_outcomes) / self.total)

    def merge(
        self: "H[_T]", other: "H[_T] | Mapping[_T, SupportsInt] | Iterable[_T]"
    ) -> "H[_T]":
        r"""
        Merges counts.

            >>> H(4).merge(H(6))
            H({1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1})
        """
        result: dict[_T, int] = dict(self)
        other_h = other if isinstance(other, H) else H(other)
        for outcome, count in other_h.items():
            result[outcome] = result.get(outcome, 0) + count
        return H(result)

    @experimental
    def order_stat_for_n_at_pos(
        self: "H[_T]",
        n: SupportsInt,
        pos: SupportsInt,
    ) -> "H[_T]":
        r"""
        Computes the probability distribution for each outcome appearing at *pos* among *n* like histograms sorted least-to-greatest.

        *pos* is a zero-based index analogous to `#!math k` in the `#!math k`th order statistic this method implements.

            >>> d6avg = H((2, 3, 3, 4, 4, 5))
            >>> d6avg.order_stat_for_n_at_pos(5, 3)
            H({2: 26, 3: 1432, 4: 4792, 5: 1526})

        The results show that, when rolling five averaging dice and sorting each roll, there are 26 ways where `2` appears at the fourth (index `3`) position, 1,432 ways where `3` appears at the fourth position, etc.

        Negative values for *pos* follow Python index semantics:

            >>> d6 = H(6)
            >>> d6.order_stat_for_n_at_pos(6, 0) == d6.order_stat_for_n_at_pos(6, -6)
            True
            >>> d6.order_stat_for_n_at_pos(6, 5) == d6.order_stat_for_n_at_pos(6, -1)
            True

        This method caches the beta values for *n* so they can be reused for varying values of *pos* in subsequent calls.
        """
        n = lossless_int(n)
        pos = lossless_int(pos)
        if not (-n <= pos < n):
            raise ValueError(f"pos ({pos!r}) must be in range [{-n}, {n})")

        if n not in self._order_stat_funcs_by_n:
            self._order_stat_funcs_by_n[n] = self._order_stat_func_for_n(n)
        if pos < 0:
            pos = n + pos
        return self._order_stat_funcs_by_n[n](pos)

    @overload
    def probability_items(
        self: "H[_T]", rational_t: None = ...
    ) -> Iterator[tuple[_T, Fraction]]: ...
    @overload
    def probability_items(
        self: "H[_T]", rational_t: Callable[[int, int], _OtherT]
    ) -> Iterator[tuple[_T, _OtherT]]: ...
    def probability_items(
        self: "H[_T]", rational_t: Callable[[int, int], _OtherT] | None = None
    ) -> Iterator[tuple[_T, _OtherT]]:
        r"""
        Yields `(outcome, probability)` pairs where each probability is computed as `rational_t(count, total)`.

        *rational_t* defaults to `fractions.Fraction`, giving exact rational probabilities.
        Pass any two-argument callable to get a different representation (e.g. `float` division via `lambda n, d: n / d`).

        Yields nothing if the histogram is empty (total is zero).

            >>> list(H({1: 1, 2: 2, 3: 1}).probability_items())
            [(1, Fraction(1, 4)), (2, Fraction(1, 2)), (3, Fraction(1, 4))]
            >>> from operator import truediv
            >>> list(H({1: 1, 2: 2, 3: 1}).probability_items(truediv))
            [(1, 0.25), (2, 0.5), (3, 0.25)]
            >>> list(H({}).probability_items())
            []
        """
        if rational_t is None:
            rational_t = cast("Callable[[int, int], _OtherT]", Fraction)
        t = self.total
        if not t:
            return
        for outcome, count in self._h.items():
            yield outcome, rational_t(count, t)

    @experimental
    def quantile(self: "H[_T]", numerator: SupportsInt, denominator: SupportsInt) -> _T:
        r"""
        Returns the smallest outcome whose cumulative probability (i.e., including all smaller weighted outcomes) is at least *numerator* / *denominator*.

        It matches NumPy's [`numpy.quantile(outcomes, numerator / denominator, weights=counts, method="inverted_cdf")`](https://numpy.org/doc/stable/reference/generated/numpy.quantile.html) (the step-function quantile appropriate to a discrete distribution), but stays integer-exact rather than rounding through `float`.
        Raises `ValueError` if the histogram is empty, if *denominator* is not positive, or if *numerator* / *denominator* lies outside the closed interval $\left[ 0, 1 \right]$.

            >>> (2 @ H(10)).quantile(1, 3)
            9
            >>> H(6).quantile(0, 1)
            1
            >>> H(6).quantile(1, 2)
            3
            >>> H(6).quantile(1, 1)
            6
        """
        if not self._h:
            raise ValueError("quantile of empty histogram is undefined")
        numerator = lossless_int(numerator)
        denominator = lossless_int(denominator)
        if denominator <= 0:
            raise ValueError(f"denominator ({denominator!r}) must be positive")
        if not 0 <= numerator <= denominator:
            raise ValueError(
                f"numerator / denominator ({numerator}/{denominator}) must be in the interval [0, 1]"
            )
        # `cumulative / total >= numerator / denominator` cross-multiplies to
        # `cumulative * denominator >= numerator * total` for `denominator > 0 and total
        # > 0` (i.e., no sign flip)
        scaled_target = numerator * self.total
        cumulative = 0
        for outcome, count in self.items():
            cumulative += count
            if cumulative * denominator >= scaled_target:
                return outcome
        raise AssertionError(
            "unreachable: cumulative reaches total"
        )  # pragma: no cover

    @overload
    def quantize_counts(
        self: "H[Never]",
        bit_width: int = ...,
        *,
        preserve_zero_counts: bool = False,
    ) -> "H[Never]": ...
    @overload
    def quantize_counts(
        self: "H[_T]",
        bit_width: int = ...,
        *,
        preserve_zero_counts: bool = False,
    ) -> "H[_T]": ...
    @experimental
    def quantize_counts(
        self,
        bit_width: int = DEFAULT_QUANTIZATION_BIT_WIDTH,
        *,
        preserve_zero_counts: bool = False,
    ) -> "H[Any]":
        r"""
        Constructs an [`H`][dyce.H] by “quantizing” its counts such that no count occupies more than *bit_width* bits.

        Proportions are approximated.
        If *preserve_zero_counts* is `True`, outcomes are retained even if their counts are reduced to `0`.

            >>> H.quantize_counts(
            ...     H({1: 0x100, 2: 0x400, 3: 0x200, 4: 0x80, 5: 0xFFFF, 6: 0x7F}),
            ...     bit_width=8,
            ... )
            H({1: 1, 2: 4, 3: 2, 4: 1, 5: 255})
            >>> H.quantize_counts(
            ...     H({1: 0x400, 2: 0x1000, 3: 0xF, 4: 0x10, 5: 0}),
            ...     bit_width=8,
            ...     preserve_zero_counts=True,
            ... )
            H({1: 32, 2: 128, 3: 0, 4: 1, 5: 0})
        """
        quantized = _quantize_counts(
            self, bit_width, preserve_zero_counts=preserve_zero_counts
        )
        return self if quantized is self else type(self)(quantized)

    @experimental
    def sample(self: "H[_T]") -> _T:
        r"""
        <!-- BEGIN MONKEY PATCH --
        For deterministic outcomes.

        >>> import random
        >>> from dyce import rng
        >>> rng.RNG = random.Random(1774583876)

          -- END MONKEY PATCH -->

        Returns a (weighted) random outcome.

            >>> d6 = H(6)
            >>> [d6.sample() for _ in range(10)]
            [2, 6, 1, 2, 4, 5, 1, 4, 2, 5]
        """
        from . import rng

        if not self:
            raise ValueError("no outcomes in an empty histogram")
        return rng.RNG.choices(
            population=tuple(self.outcomes()),
            weights=tuple(self.counts()),
            k=1,
        )[0]

    def stdev(self: "H[SupportsFloat]") -> float:
        r"""
        Returns the standard deviation of the weighted outcomes as a `float`.

        Raises `ValueError` if the histogram is empty.

            >>> H(6).stdev()
            1.707825...
            >>> H({1: 1, 3: 1}).stdev()
            1.0
        """
        return math.sqrt(self.variance())

    def variance(self: "H[SupportsFloat]") -> float:
        r"""
        Returns the variance of the weighted outcomes as a `float`.

        Raises `ValueError` if the histogram is empty.

            >>> H(6).variance()
            2.916666...
            >>> H({1: 1, 3: 1}).variance()
            1.0
        """
        return (
            sum(
                (
                    count / self.total * float(outcome) ** 2
                    for outcome, count in self._h.items()
                ),
                start=0.0,
            )
            - self.mean() ** 2
        )

    def _order_stat_func_for_n(self: "H[_T]", n: int) -> "Callable[[int], H[_T]]":
        cumulative = 0
        betas: list[tuple[_T, int, int]] = []
        total = self.total
        for outcome, count in self.items():
            c_lt = cumulative
            c_le = cumulative + count
            betas.append((outcome, c_lt, c_le))
            cumulative = c_le

        def _order_stat_at_pos(pos: int) -> "H[_T]":
            # Two endpoint fast paths reduce the inner binomial sum to a single
            # closed-form term per outcome. Both also carry `prev_term` across
            # iterations so each outcome does ONE pow operation rather than two.
            #
            # pos == n - 1 (max): only k == n contributes; the sum is just `c_le^n`.
            # Difference between adjacent outcomes is `cur_term - prev_term`.
            #
            # pos == 0 (min): the n-term sum from k == 1 to k == n collapses via the
            # binomial theorem -- `(c + (T-c))^n` minus the k == 0 term `(T-c)^n` -- to
            # `T^n - (T-c)^n`. Two adjacent outcomes' difference is `(T-c_lt)^n -
            # (T-c_le)^n`. Empirically this is ~280x faster than the general path for `n
            # == 100`, `num_outcomes == 100`.
            if pos == n - 1:
                # k_range -> range(n, n+1) -> (n,)
                # math.comb(n, n)  # -> 1  # ruff: ignore[commented-out-code]
                # * c_le**n
                # * (total - c_le) ** (n-n)  # -> 1  # ruff: ignore[commented-out-code]
                counts: dict[_T, int] = {}
                prev_term = 0  # 0^n == 0 for n >= 1
                for outcome, _c_lt, c_le in betas:
                    cur_term = c_le**n
                    counts[outcome] = cur_term - prev_term
                    prev_term = cur_term
                return H(counts)
            elif pos == 0:
                # k_range -> range(1) -> (0,)
                # math.comb(n, 0)  # -> 1  # ruff: ignore[commented-out-code]
                # * c_le**0  # -> 1
                # * (total - c_le) ** (n-0)  # ruff: ignore[commented-out-code]
                counts = {}
                prev_term = total**n  # (T-0)^n
                for outcome, _c_lt, c_le in betas:
                    cur_term = (total - c_le) ** n
                    counts[outcome] = prev_term - cur_term
                    prev_term = cur_term
                return H(counts)
            # General middle-position fallback. Two equivalent formulations differ only
            # in which side of the binomial sum gets evaluated:
            #
            #   direct (n - pos terms):     Σ_{k=pos+1}^{n} C(n,k) c^k (T-c)^(n-k)
            #
            #   complement (pos + 1 terms): T^n - Σ_{k=0}^{pos} C(n,k) c^k (T-c)^(n-k)
            #
            # The `T^n` cancels in the c_le-vs-c_lt subtraction, so the complement form
            # just swaps which sum is subtracted from which. Pick whichever has fewer
            # terms.
            elif pos + 1 < n - pos:
                k_range = range(pos + 1)
                return H(
                    {
                        # For each outcome-beta
                        outcome: (
                            # This first sum (with c_lt^k * (T-c_lt)^(n-k)): counts the
                            # n-tuples where AT MOST pos of the n rolls are strictly
                            # less than outcome x.
                            #
                            # Each term C(n,k) * c_lt^k * (T-c_lt)^(n-k) is: "choose
                            # which k positions hold a roll < x (there are c_lt ways per
                            # position), and the remaining n-k positions hold rolls ≥ x
                            # (there are T - c_lt ways per position)." Sum over k from 0
                            # to pos.
                            sum(
                                # The number of ways to choose k items from a set of n
                                # items (n choose k)
                                math.comb(n, k)
                                # The cumulative count of outcomes less than this one to
                                # the kth power
                                * c_lt**k
                                # The remaining counts taken to the power of the
                                # remaining positions
                                * (total - c_lt) ** (n - k)
                                # Summed for all positions [0, k]
                                for k in k_range
                            )
                            -
                            # This second sum (with c_le^k * (total - c_le)^(n-k)):
                            # counts n-tuples where AT MOST pos of the rolls are less
                            # than or equal to x.
                            sum(
                                # n choose k (computed again)
                                math.comb(n, k)
                                # The cumulative count of outcomes including this one to
                                # the kth power
                                * c_le**k
                                # The remaining counts taken to the power of the
                                # remaining positions
                                * (total - c_le) ** (n - k)
                                # Summed for all positions [0, k]
                                for k in k_range
                            )
                            # This difference captures "x is at position pos" precisely
                            # because:
                            #
                            # - "x is at position pos in the sorted list" is the joint
                            #   event:
                            #   - At MOST pos rolls are strictly less than x (otherwise
                            #     something < x would push x to a later position), AND
                            #   - At LEAST pos + 1 rolls are less than or equal to x
                            #     (otherwise x couldn't even be present at position
                            #     pos).
                            # - "At most pos rolls < x" MINUS "at most pos rolls ≤ x" =
                            #   "at most pos rolls < x AND more than pos rolls ≤ x" =
                            #   exactly the joint event above. The rolls that are ≤ x
                            #   but not < x are rolls equal to x — so the difference
                            #   counts configurations where enough rolls equal x to push
                            #   x into position pos.
                        )
                        for outcome, c_lt, c_le in betas
                    }
                )
            else:  # pos + 1 >= n - pos
                k_range = range(pos + 1, n + 1)
                return H(
                    {
                        outcome: (
                            sum(
                                math.comb(n, k) * c_le**k * (total - c_le) ** (n - k)
                                for k in k_range
                            )
                            - sum(
                                math.comb(n, k) * c_lt**k * (total - c_lt) ** (n - k)
                                for k in k_range
                            )
                        )
                        for outcome, c_lt, c_le in betas
                    }
                )

        return _order_stat_at_pos

total: int property

Equivalent to sum(self.counts()).

The result is cached to avoid redundant computation with multiple accesses.

1
2
3
4
>>> H({4: 2, 5: 3, 6: 1}).total
6
>>> H({}).total
0

__init__(init_val: Any) -> None

__init__(init_val: Mapping[Never, SupportsInt]) -> None
__init__(init_val: Mapping[_T, SupportsInt]) -> None
__init__(init_val: Iterable[Never]) -> None
__init__(init_val: Iterable[_T]) -> None
__init__(init_val: Literal[0, False]) -> None
__init__(init_val: int) -> None

Constructs an H from init_val, which can be a mapping, iterable, or an integer shorthand.

Source code in dyce/h.py
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
def __init__(self, init_val: Any, /) -> None:  # ruff: ignore[complex-structure]
    r"""
    Constructs an [`H`][dyce.H] from *init_val*, which can be a mapping, iterable, or an integer shorthand.
    """
    self._h: dict[_T_co, int]
    self._hash: int | None = None
    self._order_stat_funcs_by_n: dict[int, Callable[[int], H[Any]]] = {}
    self._total: int | None = None

    @nobeartype  # not decoratable by beartype (avoids warning)
    def _sorted_items_iter(
        items: Sequence[tuple[Any, SupportsInt]],
    ) -> Iterator[tuple[Any, int]]:
        sorted_items = [(k, lossless_int(v)) for k, v in items]
        try:
            sorted_items.sort()
        except TypeError:
            sorted_items.sort(key=lambda item: natural_key(item[0]))
        for outcome, count in sorted_items:
            if count < 0:
                raise ValueError(f"count for {outcome} cannot be negative")
            yield (outcome, count)

    if isinstance(init_val, Iterable):
        if isinstance(init_val, Mapping):
            self._h = dict(_sorted_items_iter(list(init_val.items())))
        else:
            c: Counter[_T_co] = Counter(init_val)
            self._h = dict(_sorted_items_iter(list(c.items())))
    elif isinstance(init_val, int):
        n = abs(init_val)
        if init_val > 0:
            self._h = dict(_sorted_items_iter([(i, 1) for i in range(1, n + 1)]))
        elif init_val < 0:
            self._h = dict(_sorted_items_iter([(i, 1) for i in range(-n, 0)]))
        else:
            self._h = {}
    else:
        raise TypeError(
            f"scalar init_val must be int; use explicit Mapping or Iterable "
            f"for {type(init_val).__qualname__!r} outcomes"
        )
    cur_ctxt = _quantize_ctxt.get()
    if cur_ctxt.bit_width:
        self._h = cast(
            "dict[_T_co, int]",
            _quantize_counts(
                self._h,
                cur_ctxt.bit_width,
                preserve_zero_counts=cur_ctxt.preserve_zero_counts,
            ),
        )

apply(func: Callable[[_T], _ResultT] | Callable[[_T, _OtherT], _ResultT], other: H[_OtherT] | _OtherT | SentinelT = Sentinel) -> H[_ResultT]

apply(func: Callable[[_T], _ResultT]) -> H[_ResultT]
apply(func: Callable[[_T, _OtherT], _ResultT], other: H[_OtherT]) -> H[_ResultT]
apply(func: Callable[[_T, _OtherT], _ResultT], other: _OtherT) -> H[_ResultT]

Returns a new H by applying func to outcomes.

If other is provided, func should have two parameters, otherwise it should have one. If other is an H, take the Cartesian product of both histograms’ items: call func(h_outcome, other_outcome) for each pair and accumulate h_count * other_count. If other is a scalar, call func(outcome, other) for each outcome, passing counts through unchanged.

Resulting counts for duplicate outcomes are summed.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
>>> import operator
>>> H({10: 1, 20: 1}).apply(operator.sub, 10)
H({0: 1, 10: 1})
>>> H({10: 1, 20: 1}).apply(operator.sub, H({1: 1, 2: 1}))
H({8: 1, 9: 1, 18: 1, 19: 1})

>>> # optype provides reflected operator functions as do_r*
>>> import optype as ot

>>> H({10: 1, 20: 1}).apply(ot.do_rsub, 10)
H({-10: 1, 0: 1})

>>> H({10: 1, 20: 1}).apply(ot.do_rsub, H({1: 1, 2: 1}))
H({-19: 1, -18: 1, -9: 1, -8: 1})

One way to compute how often a six-sided die “beats” an eight-sided die rolled together:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
>>> from enum import IntEnum

>>> class Versus(IntEnum):
...     LOSS = -1
...     DRAW = 0
...     WIN = 1

>>> d6 = H(6)
>>> d8 = H(8)
>>> vs = lambda h_outcome, other_outcome: (
...     Versus.LOSS
...     if h_outcome < other_outcome
...     else Versus.WIN
...     if h_outcome > other_outcome
...     else Versus.DRAW
... )
>>> d6.apply(vs, d8)
H({<Versus.LOSS: -1>: 27, <Versus.DRAW: 0>: 6, <Versus.WIN: 1>: 15})

Omitting other allows examination of just the histogram. One way to determine Apocalypse World mechanic outcomes with a modifier:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
>>> class PBTA(IntEnum):
...     MISS = 0
...     WEAK_HIT = 1
...     STRONG_HIT = 2

>>> mod = +1
>>> pbta_result = (2 @ H(6) + mod).apply(
...     lambda outcome: (
...         PBTA.MISS
...         if outcome <= 6
...         else PBTA.WEAK_HIT
...         if 7 <= outcome <= 9
...         else PBTA.STRONG_HIT
...     )
... )
>>> pbta_result
H({<PBTA.MISS: 0>: 10, <PBTA.WEAK_HIT: 1>: 16, <PBTA.STRONG_HIT: 2>: 10})

One way to count how often summing outcomes comes out even on 2d3:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> d3_2 = 2 @ H(3)
>>> d3_2
H({2: 1, 3: 2, 4: 3, 5: 2, 6: 1})
>>> d3_2_is_even = d3_2.apply(lambda outcome: outcome % 2 == 0)
>>> d3_2_is_even
H({False: 4, True: 5})
>>> (d3_2 % 2).eq(0) == d3_2_is_even
True
>>> ((d3_2 + 1) % 2) == d3_2_is_even
True
Source code in dyce/h.py
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
def apply(
    self: "H[_T]",
    func: Callable[[_T], _ResultT] | Callable[[_T, _OtherT], _ResultT],
    other: "H[_OtherT] | _OtherT | SentinelT" = Sentinel,
) -> "H[_ResultT]":
    r"""
    Returns a new [`H`][dyce.H] by applying *func* to outcomes.

    If *other* is provided, *func* should have two parameters, otherwise it should have one.
    If *other* is an [`H`][dyce.H], take the Cartesian product of both histograms’ items: call `func(h_outcome, other_outcome)` for each pair and accumulate `h_count * other_count`.
    If *other* is a scalar, call `func(outcome, other)` for each outcome, passing counts through unchanged.

    Resulting counts for duplicate outcomes are summed.

        >>> import operator
        >>> H({10: 1, 20: 1}).apply(operator.sub, 10)
        H({0: 1, 10: 1})
        >>> H({10: 1, 20: 1}).apply(operator.sub, H({1: 1, 2: 1}))
        H({8: 1, 9: 1, 18: 1, 19: 1})

        >>> # optype provides reflected operator functions as do_r*
        >>> import optype as ot

        >>> H({10: 1, 20: 1}).apply(ot.do_rsub, 10)
        H({-10: 1, 0: 1})

        >>> H({10: 1, 20: 1}).apply(ot.do_rsub, H({1: 1, 2: 1}))
        H({-19: 1, -18: 1, -9: 1, -8: 1})

    One way to compute how often a six-sided die “beats” an eight-sided die rolled together:

        >>> from enum import IntEnum

        >>> class Versus(IntEnum):
        ...     LOSS = -1
        ...     DRAW = 0
        ...     WIN = 1

        >>> d6 = H(6)
        >>> d8 = H(8)
        >>> vs = lambda h_outcome, other_outcome: (
        ...     Versus.LOSS
        ...     if h_outcome < other_outcome
        ...     else Versus.WIN
        ...     if h_outcome > other_outcome
        ...     else Versus.DRAW
        ... )
        >>> d6.apply(vs, d8)
        H({<Versus.LOSS: -1>: 27, <Versus.DRAW: 0>: 6, <Versus.WIN: 1>: 15})

    Omitting *other* allows examination of just the histogram.
    One way to determine *Apocalypse World* mechanic outcomes with a modifier:

        >>> class PBTA(IntEnum):
        ...     MISS = 0
        ...     WEAK_HIT = 1
        ...     STRONG_HIT = 2

        >>> mod = +1
        >>> pbta_result = (2 @ H(6) + mod).apply(
        ...     lambda outcome: (
        ...         PBTA.MISS
        ...         if outcome <= 6
        ...         else PBTA.WEAK_HIT
        ...         if 7 <= outcome <= 9
        ...         else PBTA.STRONG_HIT
        ...     )
        ... )
        >>> pbta_result
        H({<PBTA.MISS: 0>: 10, <PBTA.WEAK_HIT: 1>: 16, <PBTA.STRONG_HIT: 2>: 10})

    One way to count how often summing outcomes comes out even on 2d3:

        >>> d3_2 = 2 @ H(3)
        >>> d3_2
        H({2: 1, 3: 2, 4: 3, 5: 2, 6: 1})
        >>> d3_2_is_even = d3_2.apply(lambda outcome: outcome % 2 == 0)
        >>> d3_2_is_even
        H({False: 4, True: 5})
        >>> (d3_2 % 2).eq(0) == d3_2_is_even
        True
        >>> ((d3_2 + 1) % 2) == d3_2_is_even
        True
    """
    if other is Sentinel:
        result: dict[_ResultT, int] = {}
        func = cast("Callable[[_T], _ResultT]", func)
        for outcome, count in self._h.items():
            new_outcome = func(outcome)
            result[new_outcome] = result.get(new_outcome, 0) + count
        return H(result)

    func = cast("Callable[[_T, _OtherT], _ResultT]", func)
    if isinstance(other, H):
        return H(
            cast("dict[_ResultT, int]", _h_binary_callable(self._h, other._h, func))  # ruff: ignore[private-member-access]
        )
    else:
        return H(
            cast(
                "dict[_ResultT, int]", _h_binary_callable(self._h, {other: 1}, func)
            )
        )

counts() -> ValuesView[int]

A more descriptive synonym for the values mapping method.

Source code in dyce/h.py
584
585
586
def counts(self) -> ValuesView[int]:
    r"""A more descriptive synonym for the `values` mapping method."""
    return self._h.values()

eq(rhs: H[object] | object) -> H[bool]

eq(rhs: H[_OtherT]) -> H[bool]
eq(rhs: _OtherT) -> H[bool]

Shorthand for self.apply(optype.do_eq, rhs).

1
2
3
4
>>> H(20).eq(10)
H({False: 19, True: 1})
>>> H(6).eq(H(10)).lowest_terms()
H({False: 9, True: 1})
Source code in dyce/h.py
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
def eq(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `self.apply(optype.do_eq, rhs)`.

        >>> H(20).eq(10)
        H({False: 19, True: 1})
        >>> H(6).eq(H(10)).lowest_terms()
        H({False: 9, True: 1})
    """
    return self.apply(ot.do_eq, rhs)

exactly_k_times_in_n(outcome: _T, n: SupportsInt, k: SupportsInt) -> int

Experimental

dyce.h.H.exactly_k_times_in_n is experimental; its interface may change or it may be removed in a future release.

Computes and returns (in constant time) the number of ways outcome appears exactly k times among n like histograms.

Uses the binomial coefficient as a more efficient alternative to (n @ self.eq(outcome))[k].

1
2
3
4
5
6
>>> H(6).exactly_k_times_in_n(outcome=5, n=4, k=2)
150
>>> H((2, 3, 3, 4, 4, 5)).exactly_k_times_in_n(outcome=2, n=3, k=3)
1
>>> H((2, 3, 3, 4, 4, 5)).exactly_k_times_in_n(outcome=4, n=3, k=3)
8

Counts, not probabilities

This returns a count of ways, not a probability, and may not be in lowest terms. (See lowest_terms.) Divide by self.total ** n to get a probability. (See total.)

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
>>> from fractions import Fraction
>>> h = H((2, 3, 3, 4, 4, 5))
>>> n, k = 3, 2
>>> (n @ h).total == h.total**n
True
>>> Fraction(h.exactly_k_times_in_n(outcome=3, n=n, k=k), h.total**n)
Fraction(2, 9)
>>> h_not_lowest_terms = H.from_counts(h, h)
>>> h == h_not_lowest_terms
True
>>> h_not_lowest_terms
H({2: 2, 3: 4, 4: 4, 5: 2})
>>> h_not_lowest_terms.exactly_k_times_in_n(outcome=3, n=n, k=k)
384
>>> Fraction(
...     h_not_lowest_terms.exactly_k_times_in_n(outcome=3, n=n, k=k),
...     h_not_lowest_terms.total**n,
... )
Fraction(2, 9)
Source code in dyce/h.py
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
@experimental
def exactly_k_times_in_n(
    self: "H[_T]",
    outcome: _T,
    n: SupportsInt,
    k: SupportsInt,
) -> int:
    r"""
    Computes and returns (in constant time) the number of ways *outcome* appears exactly *k* times among *n* like histograms.

    Uses the binomial coefficient as a more efficient alternative to `(n @ self.eq(outcome))[k]`.

        >>> H(6).exactly_k_times_in_n(outcome=5, n=4, k=2)
        150
        >>> H((2, 3, 3, 4, 4, 5)).exactly_k_times_in_n(outcome=2, n=3, k=3)
        1
        >>> H((2, 3, 3, 4, 4, 5)).exactly_k_times_in_n(outcome=4, n=3, k=3)
        8

    !!! note "Counts, not probabilities"

        This returns a *count* of ways, not a probability, and may not be in lowest terms.
        (See [`lowest_terms`][dyce.H.lowest_terms].)
        Divide by `self.total ** n` to get a probability.
        (See [`total`][dyce.H.total].)

            >>> from fractions import Fraction
            >>> h = H((2, 3, 3, 4, 4, 5))
            >>> n, k = 3, 2
            >>> (n @ h).total == h.total**n
            True
            >>> Fraction(h.exactly_k_times_in_n(outcome=3, n=n, k=k), h.total**n)
            Fraction(2, 9)
            >>> h_not_lowest_terms = H.from_counts(h, h)
            >>> h == h_not_lowest_terms
            True
            >>> h_not_lowest_terms
            H({2: 2, 3: 4, 4: 4, 5: 2})
            >>> h_not_lowest_terms.exactly_k_times_in_n(outcome=3, n=n, k=k)
            384
            >>> Fraction(
            ...     h_not_lowest_terms.exactly_k_times_in_n(outcome=3, n=n, k=k),
            ...     h_not_lowest_terms.total**n,
            ... )
            Fraction(2, 9)
    """
    n = lossless_int(n)
    k = lossless_int(k)

    if k > n:
        raise ValueError(f"k ({k!r}) must be less than or equal to n ({n!r})")

    c_outcome = self.get(outcome, 0)
    return math.comb(n, k) * c_outcome**k * (self.total - c_outcome) ** (n - k)  # type: ignore[no-any-return]

format(*, precision: int = DEFAULT_PRECISION, scaled: bool = False, tick: str = '#', width: int = _ROW_WIDTH) -> str

Returns a formatted string representation of the histogram.

precision is the number of decimal places to use and defaults to 2. tick is used as the bar character and defaults to "#". width must be positive and is the maximum width of the horizontal bar ASCII graph.

 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
>>> print(
...     H.from_counts(
...         (2 @ H(6)),
...         dict.fromkeys(range(1, 21), 0),
...         preserve_zero_counts=True,
...     ).format(precision=4, tick="@", width=65)
... )
avg |    7.0000
std |    2.4152
  1 |   0.0000% |
  2 |   2.7778% |@
  3 |   5.5556% |@@
  4 |   8.3333% |@@@@
  5 |  11.1111% |@@@@@
  6 |  13.8889% |@@@@@@
  7 |  16.6667% |@@@@@@@@
  8 |  13.8889% |@@@@@@
  9 |  11.1111% |@@@@@
 10 |   8.3333% |@@@@
 11 |   5.5556% |@@
 12 |   2.7778% |@
 13 |   0.0000% |
 14 |   0.0000% |
 15 |   0.0000% |
 16 |   0.0000% |
 17 |   0.0000% |
 18 |   0.0000% |
 19 |   0.0000% |
 20 |   0.0000% |

If scaled is True, horizontal bars are scaled to width.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
>>> h_ge = (2 @ H(6)).ge(7)
>>> print(f"{' 65 chars wide -->|':->65}")
---------------------------------------------- 65 chars wide -->|
>>> print(H(1).format(scaled=False, width=65))
avg |    1.00
std |    0.00
  1 | 100.00% |##################################################
>>> print(h_ge.format(scaled=False, width=65))
  avg |    0.58
  std |    0.49
False |  41.67% |####################
 True |  58.33% |############################
>>> print(h_ge.format(scaled=True, width=65))
  avg |    0.58
  std |    0.49
False |  41.67% |##################################
 True |  58.33% |################################################
Source code in dyce/h.py
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
def format(
    self,
    *,
    precision: int = DEFAULT_PRECISION,
    scaled: bool = False,
    tick: str = "#",
    width: int = _ROW_WIDTH,
) -> str:
    r"""
    Returns a formatted string representation of the histogram.

    *precision* is the number of decimal places to use and defaults to `2`.
    *tick* is used as the bar character and defaults to `"#"`.
    *width* must be positive and is the maximum width of the horizontal bar ASCII graph.

        >>> print(
        ...     H.from_counts(
        ...         (2 @ H(6)),
        ...         dict.fromkeys(range(1, 21), 0),
        ...         preserve_zero_counts=True,
        ...     ).format(precision=4, tick="@", width=65)
        ... )
        avg |    7.0000
        std |    2.4152
          1 |   0.0000% |
          2 |   2.7778% |@
          3 |   5.5556% |@@
          4 |   8.3333% |@@@@
          5 |  11.1111% |@@@@@
          6 |  13.8889% |@@@@@@
          7 |  16.6667% |@@@@@@@@
          8 |  13.8889% |@@@@@@
          9 |  11.1111% |@@@@@
         10 |   8.3333% |@@@@
         11 |   5.5556% |@@
         12 |   2.7778% |@
         13 |   0.0000% |
         14 |   0.0000% |
         15 |   0.0000% |
         16 |   0.0000% |
         17 |   0.0000% |
         18 |   0.0000% |
         19 |   0.0000% |
         20 |   0.0000% |

    If *scaled* is `True`, horizontal bars are scaled to *width*.

        >>> h_ge = (2 @ H(6)).ge(7)
        >>> print(f"{' 65 chars wide -->|':->65}")
        ---------------------------------------------- 65 chars wide -->|
        >>> print(H(1).format(scaled=False, width=65))
        avg |    1.00
        std |    0.00
          1 | 100.00% |##################################################
        >>> print(h_ge.format(scaled=False, width=65))
          avg |    0.58
          std |    0.49
        False |  41.67% |####################
         True |  58.33% |############################
        >>> print(h_ge.format(scaled=True, width=65))
          avg |    0.58
          std |    0.49
        False |  41.67% |##################################
         True |  58.33% |################################################
    """
    # Get the length of the fixed-width column " | {<var>:7.2%} |" for computing the
    # available tick space
    prob_width = 5 + precision
    prob_len = len(f" | {0.0:{prob_width}.{precision}%} |")
    try:
        mu: float | None = self.mean()  # type: ignore[misc] # ty: ignore[invalid-argument-type]
        std: float | None = self.stdev()  # type: ignore[misc] # ty: ignore[invalid-argument-type]
    except Exception as exc:  # ruff: ignore[blind-except]
        # Broad catch is intentional: format() is a display method that should
        # always produce output. Any failure to compute statistics (including from
        # runtime type checkers like beartype) is treated as "stats not available"
        # rather than an error.
        warnings.warn(f"{exc!s}", stacklevel=2)
        mu = None
        std = None

    def _lines() -> Iterator[str]:
        # First pass: collect (outcome_str, probability) pairs and find the widest
        # outcome representation. We need max_outcome_len before we can emit
        # anything, because the stats header must align with it.
        pairs: list[tuple[str, Fraction]] = []
        max_outcome_len = 3  # minimum column width
        for outcome, probability in self.probability_items():
            outcome_str = repr(outcome)
            max_outcome_len = max(max_outcome_len, len(outcome_str))
            pairs.append((outcome_str, probability))

        # Stats header (emitted before outcome rows)
        if mu is not None:
            yield f"{'avg': >{max_outcome_len}} | {mu:{prob_width}.{precision}f}"
        if std is not None:
            yield f"{'std': >{max_outcome_len}} | {std:{prob_width}.{precision}f}"

        if pairs:
            tick_scale = max(self.counts()) / self.total if scaled else 1.0
            max_num_ticks = (width - max_outcome_len - prob_len) // len(tick)
            for outcome_str, probability in pairs:
                ticks = tick * int(max_num_ticks * float(probability) / tick_scale)
                yield f"{outcome_str: >{max_outcome_len}} | {float(probability):{prob_width}.{precision}%} |{ticks}"

    return os.linesep.join(_lines())

format_short(*, include_avg: bool = True, precision: int = DEFAULT_PRECISION) -> str

Returns a short-form formatted string representation of the histogram.

1
2
3
4
5
6
7
8
9
>>> print(H(6).format_short())
{avg: 3.50, 1: 16.67%, 2: 16.67%, 3: 16.67%, 4: 16.67%, 5: 16.67%, 6: 16.67%}
>>> print(
...     H(6).format_short(
...         include_avg=False,
...         precision=3,  # decimal places
...     )
... )
{1: 16.667%, 2: 16.667%, 3: 16.667%, 4: 16.667%, 5: 16.667%, 6: 16.667%}
Source code in dyce/h.py
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
def format_short(
    self,
    *,
    include_avg: bool = True,
    precision: int = DEFAULT_PRECISION,
) -> str:
    r"""
    Returns a short-form formatted string representation of the histogram.

        >>> print(H(6).format_short())
        {avg: 3.50, 1: 16.67%, 2: 16.67%, 3: 16.67%, 4: 16.67%, 5: 16.67%, 6: 16.67%}
        >>> print(
        ...     H(6).format_short(
        ...         include_avg=False,
        ...         precision=3,  # decimal places
        ...     )
        ... )
        {1: 16.667%, 2: 16.667%, 3: 16.667%, 4: 16.667%, 5: 16.667%, 6: 16.667%}
    """
    prob_width = 5 + precision
    mu: float | None = None
    if include_avg:
        try:
            mu = self.mean()  # type: ignore[misc] # ty: ignore[invalid-argument-type]
        except Exception as exc:  # ruff: ignore[blind-except]
            # See format() for rationale
            warnings.warn(f"{exc!s}", stacklevel=2)

    def _parts() -> Iterator[str]:
        if mu is not None:
            yield f"avg: {mu:.2f}"
        yield from (
            f"{outcome!r}:{float(probability):{prob_width}.{precision}%}"
            for outcome, probability in self.probability_items()
        )

    return f"{{{', '.join(_parts())}}}"

from_counts(*sources: Mapping[_T, SupportsInt] | Iterable[tuple[_T, SupportsInt]], preserve_zero_counts: bool = False) -> H[_T] classmethod

Constructs an H by accumulating counts from one or more sources.

Each source may be a mapping of outcomes to counts, or an iterable of (outcome, count) pairs. Counts for the same outcome across all sources are summed.

1
2
3
4
>>> H.from_counts([(1, 3), (2, 2), (1, 1)])
H({1: 4, 2: 2})
>>> H.from_counts({1: 2, 2: 3}, [(1, 1), (3, 4)])
H({1: 3, 2: 3, 3: 4})

With a single mapping source this is equivalent to H construction, but multiple sources are accumulated rather than raising on duplicate keys.

1
2
>>> H.from_counts(H(6), H(6))
H({1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 2})

If preserve_zero_counts is True, entries with zero counts make it into the final H object. Otherwise, they are omitted.

1
2
3
4
5
6
7
8
>>> H.from_counts([(2, 2), (1, 1), (3, 0)], H({1: 0, 64: 0}))
H({1: 1, 2: 2})
>>> H.from_counts(
...     [(2, 2), (1, 1), (3, 0)],
...     {1: 0, 64: 0},
...     preserve_zero_counts=True,
... )
H({1: 1, 2: 2, 3: 0, 64: 0})
Source code in dyce/h.py
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
@classmethod
def from_counts(
    cls,
    *sources: Mapping[_T, SupportsInt] | Iterable[tuple[_T, SupportsInt]],
    preserve_zero_counts: bool = False,
) -> "H[_T]":
    r"""
    Constructs an [`H`][dyce.H] by accumulating counts from one or more *sources*.

    Each source may be a mapping of outcomes to counts, or an iterable of `(outcome, count)` pairs.
    Counts for the same outcome across all sources are summed.

        >>> H.from_counts([(1, 3), (2, 2), (1, 1)])
        H({1: 4, 2: 2})
        >>> H.from_counts({1: 2, 2: 3}, [(1, 1), (3, 4)])
        H({1: 3, 2: 3, 3: 4})

    With a single mapping source this is equivalent to [`H`][dyce.H] construction, but multiple sources are accumulated rather than raising on duplicate keys.

        >>> H.from_counts(H(6), H(6))
        H({1: 2, 2: 2, 3: 2, 4: 2, 5: 2, 6: 2})

    If *preserve_zero_counts* is `True`, entries with zero counts make it into the final `H` object.
    Otherwise, they are omitted.

        >>> H.from_counts([(2, 2), (1, 1), (3, 0)], H({1: 0, 64: 0}))
        H({1: 1, 2: 2})
        >>> H.from_counts(
        ...     [(2, 2), (1, 1), (3, 0)],
        ...     {1: 0, 64: 0},
        ...     preserve_zero_counts=True,
        ... )
        H({1: 1, 2: 2, 3: 0, 64: 0})
    """
    c: Counter[_T] = Counter()
    for source in sources:
        if isinstance(source, Mapping):
            # The cast is necessary because isinstance only narrows on Mapping, but
            # Iterable[tuple[_T, SupportsInt]] > Mapping[tuple[_T, SupportsInt],
            # Any], so type checkers rightly include that as the inferred return
            # type for source.items()
            source = cast("ItemsView[_T, SupportsInt]", source.items())  # ruff: ignore[redefined-loop-name]
        for outcome, count in source:
            if count or preserve_zero_counts:
                c[outcome] += lossless_int(count)
    return cast("H[_T]", cls(c))  # pyright: ignore[reportArgumentType,reportCallIssue]

ge(rhs: H[object] | object) -> H[bool]

ge(rhs: H[_OtherT]) -> H[bool]
ge(rhs: _OtherT) -> H[bool]

Shorthand for self.apply(optype.do_ge, rhs).

1
2
3
4
>>> H(20).ge(10)
H({False: 9, True: 11})
>>> H(6).ge(H(10)).lowest_terms()
H({False: 13, True: 7})
Source code in dyce/h.py
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
def ge(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `self.apply(optype.do_ge, rhs)`.

        >>> H(20).ge(10)
        H({False: 9, True: 11})
        >>> H(6).ge(H(10)).lowest_terms()
        H({False: 13, True: 7})
    """
    return self.apply(ot.do_ge, rhs)  # pyright: ignore[reportArgumentType,reportCallIssue] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

gt(rhs: H[object] | object) -> H[bool]

gt(rhs: H[_OtherT]) -> H[bool]
gt(rhs: _OtherT) -> H[bool]

Shorthand for self.apply(optype.do_gt, rhs).

1
2
3
4
>>> H(20).gt(10)
H({False: 10, True: 10})
>>> H(6).gt(H(10)).lowest_terms()
H({False: 3, True: 1})
Source code in dyce/h.py
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
def gt(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `self.apply(optype.do_gt, rhs)`.

        >>> H(20).gt(10)
        H({False: 10, True: 10})
        >>> H(6).gt(H(10)).lowest_terms()
        H({False: 3, True: 1})
    """
    return self.apply(ot.do_gt, rhs)  # pyright: ignore[reportArgumentType,reportCallIssue] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

h() -> H[_T]

Returns self.

Source code in dyce/h.py
594
595
596
def h(self: "H[_T]") -> "H[_T]":
    r"""Returns `self`."""
    return self

le(rhs: H[object] | object) -> H[bool]

le(rhs: H[_OtherT]) -> H[bool]
le(rhs: _OtherT) -> H[bool]

Shorthand for self.apply(optype.do_le, rhs).

1
2
3
4
>>> H(20).le(10)
H({False: 10, True: 10})
>>> H(6).le(H(10)).lowest_terms()
H({False: 1, True: 3})
Source code in dyce/h.py
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
def le(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `self.apply(optype.do_le, rhs)`.

        >>> H(20).le(10)
        H({False: 10, True: 10})
        >>> H(6).le(H(10)).lowest_terms()
        H({False: 1, True: 3})
    """
    return self.apply(ot.do_le, rhs)  # pyright: ignore[reportArgumentType,reportCallIssue] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

lowest_terms(*, preserve_zero_counts: bool = False) -> H[_T]

Returns a new H with zero-count outcomes removed and all counts divided by their GCD.

1
2
3
4
5
6
>>> H({1: 2, 2: 4, 3: 6, 4: 0}).lowest_terms()
H({1: 1, 2: 2, 3: 3})
>>> H({1: 3, 2: 0, 3: 6}).lowest_terms()
H({1: 1, 3: 2})
>>> H({}).lowest_terms()
H({})

If preserve_zero_counts is True, counts are reduced, but zero counts are kept.

1
2
>>> H({1: 2, 2: 4, 3: 6, 4: 0}).lowest_terms(preserve_zero_counts=True)
H({1: 1, 2: 2, 3: 3, 4: 0})
Source code in dyce/h.py
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
def lowest_terms(self: "H[_T]", *, preserve_zero_counts: bool = False) -> "H[_T]":
    r"""
    Returns a new [`H`][dyce.H] with zero-count outcomes removed and all counts divided by their GCD.

        >>> H({1: 2, 2: 4, 3: 6, 4: 0}).lowest_terms()
        H({1: 1, 2: 2, 3: 3})
        >>> H({1: 3, 2: 0, 3: 6}).lowest_terms()
        H({1: 1, 3: 2})
        >>> H({}).lowest_terms()
        H({})

    If *preserve_zero_counts* is `True`, counts are reduced, but zero counts are kept.

        >>> H({1: 2, 2: 4, 3: 6, 4: 0}).lowest_terms(preserve_zero_counts=True)
        H({1: 1, 2: 2, 3: 3, 4: 0})
    """
    counts = tuple(count for count in self._h.values() if count)
    if not counts:
        return H({})
    g = math.gcd(*counts)
    return H(
        {
            outcome: count // g
            for outcome, count in self._h.items()
            if count or preserve_zero_counts
        }
    )

lt(rhs: H[object] | object) -> H[bool]

lt(rhs: H[_OtherT]) -> H[bool]
lt(rhs: _OtherT) -> H[bool]

Shorthand for self.apply(optype.do_lt, rhs).

1
2
3
4
>>> H(20).lt(10)
H({False: 11, True: 9})
>>> H(6).lt(H(10)).lowest_terms()
H({False: 7, True: 13})
Source code in dyce/h.py
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
def lt(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `self.apply(optype.do_lt, rhs)`.

        >>> H(20).lt(10)
        H({False: 11, True: 9})
        >>> H(6).lt(H(10)).lowest_terms()
        H({False: 7, True: 13})
    """
    return self.apply(ot.do_lt, rhs)  # pyright: ignore[reportArgumentType,reportCallIssue] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

mean() -> float

Returns the mean (expected value) of the weighted outcomes.

Raises ValueError if the histogram is empty.

1
2
3
4
>>> H(6).mean()
3.5
>>> H({1: 1, 3: 1}).mean()
2.0
Source code in dyce/h.py
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
def mean(self: "H[SupportsFloat]") -> float:
    r"""
    Returns the mean (expected value) of the weighted outcomes.

    Raises `ValueError` if the histogram is empty.

        >>> H(6).mean()
        3.5
        >>> H({1: 1, 3: 1}).mean()
        2.0
    """
    if not self._h:
        raise ValueError("mean of empty histogram is undefined")
    weighted_outcomes = (
        outcome * count  # type: ignore[operator] # ty: ignore[unsupported-operator]
        for outcome, count in self.items()
    )
    return float(reduce(operator.add, weighted_outcomes) / self.total)

merge(other: H[_T] | Mapping[_T, SupportsInt] | Iterable[_T]) -> H[_T]

Merges counts.

1
2
>>> H(4).merge(H(6))
H({1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1})
Source code in dyce/h.py
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
def merge(
    self: "H[_T]", other: "H[_T] | Mapping[_T, SupportsInt] | Iterable[_T]"
) -> "H[_T]":
    r"""
    Merges counts.

        >>> H(4).merge(H(6))
        H({1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1})
    """
    result: dict[_T, int] = dict(self)
    other_h = other if isinstance(other, H) else H(other)
    for outcome, count in other_h.items():
        result[outcome] = result.get(outcome, 0) + count
    return H(result)

ne(rhs: H[object] | object) -> H[bool]

ne(rhs: H[_OtherT]) -> H[bool]
ne(rhs: _OtherT) -> H[bool]

Shorthand for self.apply(optype.do_ne, rhs).

1
2
3
4
>>> H(20).ne(10)
H({False: 1, True: 19})
>>> H(6).ne(H(10)).lowest_terms()
H({False: 1, True: 9})
Source code in dyce/h.py
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
def ne(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `self.apply(optype.do_ne, rhs)`.

        >>> H(20).ne(10)
        H({False: 1, True: 19})
        >>> H(6).ne(H(10)).lowest_terms()
        H({False: 1, True: 9})
    """
    return self.apply(ot.do_ne, rhs)

order_stat_for_n_at_pos(n: SupportsInt, pos: SupportsInt) -> H[_T]

Experimental

dyce.h.H.order_stat_for_n_at_pos is experimental; its interface may change or it may be removed in a future release.

Computes the probability distribution for each outcome appearing at pos among n like histograms sorted least-to-greatest.

pos is a zero-based index analogous to \(k\) in the \(k\)th order statistic this method implements.

1
2
3
>>> d6avg = H((2, 3, 3, 4, 4, 5))
>>> d6avg.order_stat_for_n_at_pos(5, 3)
H({2: 26, 3: 1432, 4: 4792, 5: 1526})

The results show that, when rolling five averaging dice and sorting each roll, there are 26 ways where 2 appears at the fourth (index 3) position, 1,432 ways where 3 appears at the fourth position, etc.

Negative values for pos follow Python index semantics:

1
2
3
4
5
>>> d6 = H(6)
>>> d6.order_stat_for_n_at_pos(6, 0) == d6.order_stat_for_n_at_pos(6, -6)
True
>>> d6.order_stat_for_n_at_pos(6, 5) == d6.order_stat_for_n_at_pos(6, -1)
True

This method caches the beta values for n so they can be reused for varying values of pos in subsequent calls.

Source code in dyce/h.py
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
@experimental
def order_stat_for_n_at_pos(
    self: "H[_T]",
    n: SupportsInt,
    pos: SupportsInt,
) -> "H[_T]":
    r"""
    Computes the probability distribution for each outcome appearing at *pos* among *n* like histograms sorted least-to-greatest.

    *pos* is a zero-based index analogous to `#!math k` in the `#!math k`th order statistic this method implements.

        >>> d6avg = H((2, 3, 3, 4, 4, 5))
        >>> d6avg.order_stat_for_n_at_pos(5, 3)
        H({2: 26, 3: 1432, 4: 4792, 5: 1526})

    The results show that, when rolling five averaging dice and sorting each roll, there are 26 ways where `2` appears at the fourth (index `3`) position, 1,432 ways where `3` appears at the fourth position, etc.

    Negative values for *pos* follow Python index semantics:

        >>> d6 = H(6)
        >>> d6.order_stat_for_n_at_pos(6, 0) == d6.order_stat_for_n_at_pos(6, -6)
        True
        >>> d6.order_stat_for_n_at_pos(6, 5) == d6.order_stat_for_n_at_pos(6, -1)
        True

    This method caches the beta values for *n* so they can be reused for varying values of *pos* in subsequent calls.
    """
    n = lossless_int(n)
    pos = lossless_int(pos)
    if not (-n <= pos < n):
        raise ValueError(f"pos ({pos!r}) must be in range [{-n}, {n})")

    if n not in self._order_stat_funcs_by_n:
        self._order_stat_funcs_by_n[n] = self._order_stat_func_for_n(n)
    if pos < 0:
        pos = n + pos
    return self._order_stat_funcs_by_n[n](pos)

outcomes() -> KeysView[_T]

A more descriptive synonym for the keys mapping method.

Source code in dyce/h.py
588
589
590
def outcomes(self: "H[_T]") -> KeysView[_T]:
    r"""A more descriptive synonym for the `keys` mapping method."""
    return self._h.keys()

probability_items(rational_t: Callable[[int, int], _OtherT] | None = None) -> Iterator[tuple[_T, _OtherT]]

probability_items(rational_t: None = ...) -> Iterator[tuple[_T, Fraction]]
probability_items(rational_t: Callable[[int, int], _OtherT]) -> Iterator[tuple[_T, _OtherT]]

Yields (outcome, probability) pairs where each probability is computed as rational_t(count, total).

rational_t defaults to fractions.Fraction, giving exact rational probabilities. Pass any two-argument callable to get a different representation (e.g. float division via lambda n, d: n / d).

Yields nothing if the histogram is empty (total is zero).

1
2
3
4
5
6
7
>>> list(H({1: 1, 2: 2, 3: 1}).probability_items())
[(1, Fraction(1, 4)), (2, Fraction(1, 2)), (3, Fraction(1, 4))]
>>> from operator import truediv
>>> list(H({1: 1, 2: 2, 3: 1}).probability_items(truediv))
[(1, 0.25), (2, 0.5), (3, 0.25)]
>>> list(H({}).probability_items())
[]
Source code in dyce/h.py
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
def probability_items(
    self: "H[_T]", rational_t: Callable[[int, int], _OtherT] | None = None
) -> Iterator[tuple[_T, _OtherT]]:
    r"""
    Yields `(outcome, probability)` pairs where each probability is computed as `rational_t(count, total)`.

    *rational_t* defaults to `fractions.Fraction`, giving exact rational probabilities.
    Pass any two-argument callable to get a different representation (e.g. `float` division via `lambda n, d: n / d`).

    Yields nothing if the histogram is empty (total is zero).

        >>> list(H({1: 1, 2: 2, 3: 1}).probability_items())
        [(1, Fraction(1, 4)), (2, Fraction(1, 2)), (3, Fraction(1, 4))]
        >>> from operator import truediv
        >>> list(H({1: 1, 2: 2, 3: 1}).probability_items(truediv))
        [(1, 0.25), (2, 0.5), (3, 0.25)]
        >>> list(H({}).probability_items())
        []
    """
    if rational_t is None:
        rational_t = cast("Callable[[int, int], _OtherT]", Fraction)
    t = self.total
    if not t:
        return
    for outcome, count in self._h.items():
        yield outcome, rational_t(count, t)

quantile(numerator: SupportsInt, denominator: SupportsInt) -> _T

Experimental

dyce.h.H.quantile is experimental; its interface may change or it may be removed in a future release.

Returns the smallest outcome whose cumulative probability (i.e., including all smaller weighted outcomes) is at least numerator / denominator.

It matches NumPy's numpy.quantile(outcomes, numerator / denominator, weights=counts, method="inverted_cdf") (the step-function quantile appropriate to a discrete distribution), but stays integer-exact rather than rounding through float. Raises ValueError if the histogram is empty, if denominator is not positive, or if numerator / denominator lies outside the closed interval \(\left[ 0, 1 \right]\).

1
2
3
4
5
6
7
8
>>> (2 @ H(10)).quantile(1, 3)
9
>>> H(6).quantile(0, 1)
1
>>> H(6).quantile(1, 2)
3
>>> H(6).quantile(1, 1)
6
Source code in dyce/h.py
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
@experimental
def quantile(self: "H[_T]", numerator: SupportsInt, denominator: SupportsInt) -> _T:
    r"""
    Returns the smallest outcome whose cumulative probability (i.e., including all smaller weighted outcomes) is at least *numerator* / *denominator*.

    It matches NumPy's [`numpy.quantile(outcomes, numerator / denominator, weights=counts, method="inverted_cdf")`](https://numpy.org/doc/stable/reference/generated/numpy.quantile.html) (the step-function quantile appropriate to a discrete distribution), but stays integer-exact rather than rounding through `float`.
    Raises `ValueError` if the histogram is empty, if *denominator* is not positive, or if *numerator* / *denominator* lies outside the closed interval $\left[ 0, 1 \right]$.

        >>> (2 @ H(10)).quantile(1, 3)
        9
        >>> H(6).quantile(0, 1)
        1
        >>> H(6).quantile(1, 2)
        3
        >>> H(6).quantile(1, 1)
        6
    """
    if not self._h:
        raise ValueError("quantile of empty histogram is undefined")
    numerator = lossless_int(numerator)
    denominator = lossless_int(denominator)
    if denominator <= 0:
        raise ValueError(f"denominator ({denominator!r}) must be positive")
    if not 0 <= numerator <= denominator:
        raise ValueError(
            f"numerator / denominator ({numerator}/{denominator}) must be in the interval [0, 1]"
        )
    # `cumulative / total >= numerator / denominator` cross-multiplies to
    # `cumulative * denominator >= numerator * total` for `denominator > 0 and total
    # > 0` (i.e., no sign flip)
    scaled_target = numerator * self.total
    cumulative = 0
    for outcome, count in self.items():
        cumulative += count
        if cumulative * denominator >= scaled_target:
            return outcome
    raise AssertionError(
        "unreachable: cumulative reaches total"
    )  # pragma: no cover

quantize_counts(bit_width: int = DEFAULT_QUANTIZATION_BIT_WIDTH, *, preserve_zero_counts: bool = False) -> H[Any]

quantize_counts(bit_width: int = ..., *, preserve_zero_counts: bool = False) -> H[Never]
quantize_counts(bit_width: int = ..., *, preserve_zero_counts: bool = False) -> H[_T]

Experimental

dyce.h.H.quantize_counts is experimental; its interface may change or it may be removed in a future release.

Constructs an H by “quantizing” its counts such that no count occupies more than bit_width bits.

Proportions are approximated. If preserve_zero_counts is True, outcomes are retained even if their counts are reduced to 0.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
>>> H.quantize_counts(
...     H({1: 0x100, 2: 0x400, 3: 0x200, 4: 0x80, 5: 0xFFFF, 6: 0x7F}),
...     bit_width=8,
... )
H({1: 1, 2: 4, 3: 2, 4: 1, 5: 255})
>>> H.quantize_counts(
...     H({1: 0x400, 2: 0x1000, 3: 0xF, 4: 0x10, 5: 0}),
...     bit_width=8,
...     preserve_zero_counts=True,
... )
H({1: 32, 2: 128, 3: 0, 4: 1, 5: 0})
Source code in dyce/h.py
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
@experimental
def quantize_counts(
    self,
    bit_width: int = DEFAULT_QUANTIZATION_BIT_WIDTH,
    *,
    preserve_zero_counts: bool = False,
) -> "H[Any]":
    r"""
    Constructs an [`H`][dyce.H] by “quantizing” its counts such that no count occupies more than *bit_width* bits.

    Proportions are approximated.
    If *preserve_zero_counts* is `True`, outcomes are retained even if their counts are reduced to `0`.

        >>> H.quantize_counts(
        ...     H({1: 0x100, 2: 0x400, 3: 0x200, 4: 0x80, 5: 0xFFFF, 6: 0x7F}),
        ...     bit_width=8,
        ... )
        H({1: 1, 2: 4, 3: 2, 4: 1, 5: 255})
        >>> H.quantize_counts(
        ...     H({1: 0x400, 2: 0x1000, 3: 0xF, 4: 0x10, 5: 0}),
        ...     bit_width=8,
        ...     preserve_zero_counts=True,
        ... )
        H({1: 32, 2: 128, 3: 0, 4: 1, 5: 0})
    """
    quantized = _quantize_counts(
        self, bit_width, preserve_zero_counts=preserve_zero_counts
    )
    return self if quantized is self else type(self)(quantized)

sample() -> _T

Experimental

dyce.h.H.sample is experimental; its interface may change or it may be removed in a future release.

Returns a (weighted) random outcome.

1
2
3
>>> d6 = H(6)
>>> [d6.sample() for _ in range(10)]
[2, 6, 1, 2, 4, 5, 1, 4, 2, 5]
Source code in dyce/h.py
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
@experimental
def sample(self: "H[_T]") -> _T:
    r"""
    <!-- BEGIN MONKEY PATCH --
    For deterministic outcomes.

    >>> import random
    >>> from dyce import rng
    >>> rng.RNG = random.Random(1774583876)

      -- END MONKEY PATCH -->

    Returns a (weighted) random outcome.

        >>> d6 = H(6)
        >>> [d6.sample() for _ in range(10)]
        [2, 6, 1, 2, 4, 5, 1, 4, 2, 5]
    """
    from . import rng

    if not self:
        raise ValueError("no outcomes in an empty histogram")
    return rng.RNG.choices(
        population=tuple(self.outcomes()),
        weights=tuple(self.counts()),
        k=1,
    )[0]

stdev() -> float

Returns the standard deviation of the weighted outcomes as a float.

Raises ValueError if the histogram is empty.

1
2
3
4
>>> H(6).stdev()
1.707825...
>>> H({1: 1, 3: 1}).stdev()
1.0
Source code in dyce/h.py
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
def stdev(self: "H[SupportsFloat]") -> float:
    r"""
    Returns the standard deviation of the weighted outcomes as a `float`.

    Raises `ValueError` if the histogram is empty.

        >>> H(6).stdev()
        1.707825...
        >>> H({1: 1, 3: 1}).stdev()
        1.0
    """
    return math.sqrt(self.variance())

variance() -> float

Returns the variance of the weighted outcomes as a float.

Raises ValueError if the histogram is empty.

1
2
3
4
>>> H(6).variance()
2.916666...
>>> H({1: 1, 3: 1}).variance()
1.0
Source code in dyce/h.py
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
def variance(self: "H[SupportsFloat]") -> float:
    r"""
    Returns the variance of the weighted outcomes as a `float`.

    Raises `ValueError` if the histogram is empty.

        >>> H(6).variance()
        2.916666...
        >>> H({1: 1, 3: 1}).variance()
        1.0
    """
    return (
        sum(
            (
                count / self.total * float(outcome) ** 2
                for outcome, count in self._h.items()
            ),
            start=0.0,
        )
        - self.mean() ** 2
    )

HResult

Bases: NamedTuple, Generic[_T_co]

Container passed to an expand callback when the corresponding source is an H object.

Source code in dyce/evaluation.py
50
51
52
53
54
55
56
class HResult(NamedTuple, Generic[_T_co]):
    r"""
    Container passed to an [`expand`][dyce.expand] callback when the corresponding source is an [`H`][dyce.H] object.
    """

    h: H[_T_co]
    outcome: _T_co

HableOpsMixin

Bases: HableT[_T_co]

An abstract mixin that provides H math operators to its subclasses.

Each operator delegates to the H object returned by subclass-defined h().

Source code in dyce/h.py
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
class HableOpsMixin(HableT[_T_co]):
    r"""
    An abstract mixin that provides [`H`][dyce.H] math operators to its subclasses.

    Each operator delegates to the [`H`][dyce.H] object returned by subclass-defined [`h()`][dyce.HableT.h].
    """

    __slots__ = ()

    # ---- Forward operators -----------------------------------------------------------

    @overload
    def __add__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanRAddHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __add__(
        self: "HableOpsMixin[ot.CanAdd[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __add__(
        self: "HableOpsMixin[ot.CanAdd[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __add__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanAdd[_T, _ResultT]] | HableOpsMixin[ot.CanAdd[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __add__(
        self: "HableOpsMixin[_T]", rhs: ot.CanAdd[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __add__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__add__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    @overload
    def __sub__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanRSubHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __sub__(
        self: "HableOpsMixin[ot.CanSub[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __sub__(
        self: "HableOpsMixin[ot.CanSub[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __sub__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanSub[_T, _ResultT]] | HableOpsMixin[ot.CanSub[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __sub__(
        self: "HableOpsMixin[_T]", rhs: ot.CanSub[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __sub__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__sub__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    @overload
    def __mul__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanRMulHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __mul__(
        self: "HableOpsMixin[ot.CanMul[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __mul__(
        self: "HableOpsMixin[ot.CanMul[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __mul__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanMul[_T, _ResultT]] | HableOpsMixin[ot.CanMul[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __mul__(
        self: "HableOpsMixin[_T]", rhs: ot.CanMul[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __mul__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__mul__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    @overload
    def __truediv__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanRTruedivHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __truediv__(
        self: "HableOpsMixin[ot.CanTruediv[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __truediv__(
        self: "HableOpsMixin[ot.CanTruediv[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __truediv__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanTruediv[_T, _ResultT]] | HableOpsMixin[ot.CanTruediv[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __truediv__(
        self: "HableOpsMixin[_T]", rhs: ot.CanTruediv[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __truediv__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__truediv__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    @overload
    def __floordiv__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanRFloordivHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __floordiv__(
        self: "HableOpsMixin[ot.CanFloordiv[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __floordiv__(
        self: "HableOpsMixin[ot.CanFloordiv[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __floordiv__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanFloordiv[_T, _ResultT]] | HableOpsMixin[ot.CanFloordiv[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __floordiv__(
        self: "HableOpsMixin[_T]", rhs: ot.CanFloordiv[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __floordiv__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__floordiv__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    @overload
    def __mod__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanRModHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __mod__(
        self: "HableOpsMixin[ot.CanMod[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __mod__(
        self: "HableOpsMixin[ot.CanMod[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __mod__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanMod[_T, _ResultT]] | HableOpsMixin[ot.CanMod[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __mod__(
        self: "HableOpsMixin[_T]", rhs: ot.CanMod[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __mod__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__mod__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    @overload
    def __pow__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanRPowHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __pow__(
        self: "HableOpsMixin[ot.CanPow2[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __pow__(
        self: "HableOpsMixin[ot.CanPow2[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __pow__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanPow2[_T, _ResultT]] | HableOpsMixin[ot.CanPow2[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __pow__(
        self: "HableOpsMixin[_T]", rhs: ot.CanPow2[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __pow__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__pow__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    @overload
    def __lshift__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanRLshiftHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __lshift__(
        self: "HableOpsMixin[ot.CanLshift[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __lshift__(
        self: "HableOpsMixin[ot.CanLshift[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __lshift__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanLshift[_T, _ResultT]] | HableOpsMixin[ot.CanLshift[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __lshift__(
        self: "HableOpsMixin[_T]", rhs: ot.CanLshift[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __lshift__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__lshift__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    @overload
    def __rshift__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanRRshiftHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __rshift__(
        self: "HableOpsMixin[ot.CanRshift[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __rshift__(
        self: "HableOpsMixin[ot.CanRshift[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rshift__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanRshift[_T, _ResultT]] | HableOpsMixin[ot.CanRshift[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __rshift__(
        self: "HableOpsMixin[_T]", rhs: ot.CanRshift[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rshift__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__rshift__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    @overload
    def __and__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanRAndHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __and__(
        self: "HableOpsMixin[ot.CanAnd[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __and__(
        self: "HableOpsMixin[ot.CanAnd[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __and__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanAnd[_T, _ResultT]] | HableOpsMixin[ot.CanAnd[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __and__(
        self: "HableOpsMixin[_T]", rhs: ot.CanAnd[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __and__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__and__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    @overload
    def __or__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanROrHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __or__(
        self: "HableOpsMixin[ot.CanOr[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __or__(
        self: "HableOpsMixin[ot.CanOr[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __or__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanOr[_T, _ResultT]] | HableOpsMixin[ot.CanOr[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __or__(
        self: "HableOpsMixin[_T]", rhs: ot.CanOr[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __or__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__or__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    @overload
    def __xor__(  # type: ignore[overload-overlap]
        self: "HableOpsMixin[_T]",
        rhs: _CanRXorHableOpsOptOut["HableOpsMixin[_T]", _ResultT],
    ) -> _ResultT: ...
    @overload
    def __xor__(
        self: "HableOpsMixin[ot.CanXor[_OtherT, _ResultT]]",
        rhs: "H[_OtherT] | HableOpsMixin[_OtherT]",
    ) -> H[_ResultT]: ...
    @overload
    def __xor__(
        self: "HableOpsMixin[ot.CanXor[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __xor__(
        self: "HableOpsMixin[_T]",
        rhs: "H[ot.CanXor[_T, _ResultT]] | HableOpsMixin[ot.CanXor[_T, _ResultT]]",
    ) -> H[_ResultT]: ...
    @overload
    def __xor__(
        self: "HableOpsMixin[_T]", rhs: ot.CanXor[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __xor__(self, rhs: object) -> object:
        if _should_defer_hable_operator(rhs):
            return NotImplemented
        return self.h().__xor__(_flatten_to_h(rhs))  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[call-overload]

    # ---- Reflected operators ---------------------------------------------------------

    @overload
    def __radd__(
        self: "HableOpsMixin[ot.CanRAdd[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __radd__(
        self: "HableOpsMixin[_T]", lhs: ot.CanRAdd[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __radd__(self, lhs: object) -> object:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__radd__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def __rsub__(
        self: "HableOpsMixin[ot.CanRSub[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rsub__(
        self: "HableOpsMixin[_T]", lhs: ot.CanRSub[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rsub__(self, lhs: object) -> H[object]:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__rsub__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def __rmul__(
        self: "HableOpsMixin[ot.CanRMul[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rmul__(
        self: "HableOpsMixin[_T]", lhs: ot.CanRMul[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rmul__(self, lhs: object) -> H[object]:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__rmul__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def __rtruediv__(
        self: "HableOpsMixin[ot.CanRTruediv[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rtruediv__(
        self: "HableOpsMixin[_T]", lhs: ot.CanRTruediv[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rtruediv__(self, lhs: object) -> H[object]:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__rtruediv__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def __rfloordiv__(
        self: "HableOpsMixin[ot.CanRFloordiv[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rfloordiv__(
        self: "HableOpsMixin[_T]", lhs: ot.CanRFloordiv[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rfloordiv__(self, lhs: object) -> H[object]:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__rfloordiv__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def __rmod__(
        self: "HableOpsMixin[ot.CanRMod[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rmod__(
        self: "HableOpsMixin[_T]", lhs: ot.CanRMod[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rmod__(self, lhs: object) -> H[object]:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__rmod__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def __rpow__(
        self: "HableOpsMixin[ot.CanRPow[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rpow__(
        self: "HableOpsMixin[_T]", lhs: ot.CanRPow[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rpow__(self, lhs: object) -> H[object]:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__rpow__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def __rlshift__(
        self: "HableOpsMixin[ot.CanRLshift[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rlshift__(
        self: "HableOpsMixin[_T]", lhs: ot.CanRLshift[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rlshift__(self, lhs: object) -> H[object]:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__rlshift__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def __rrshift__(
        self: "HableOpsMixin[ot.CanRRshift[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rrshift__(
        self: "HableOpsMixin[_T]", lhs: ot.CanRRshift[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rrshift__(self, lhs: object) -> H[object]:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__rrshift__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def __rand__(
        self: "HableOpsMixin[ot.CanRAnd[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rand__(
        self: "HableOpsMixin[_T]", lhs: ot.CanRAnd[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rand__(self, lhs: object) -> H[object]:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__rand__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def __ror__(
        self: "HableOpsMixin[ot.CanROr[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __ror__(
        self: "HableOpsMixin[_T]", lhs: ot.CanROr[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __ror__(self, lhs: object) -> H[object]:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__ror__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    @overload
    def __rxor__(
        self: "HableOpsMixin[ot.CanRXor[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rxor__(
        self: "HableOpsMixin[_T]", lhs: ot.CanRXor[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rxor__(self, lhs: object) -> H[object]:
        if _should_defer_hable_operator(lhs):
            return NotImplemented
        return self.h().__rxor__(lhs)  # type: ignore[operator] # ty: ignore[no-matching-overload] # zuban: ignore[arg-type]

    # ---- Unary operators -------------------------------------------------------------

    def __neg__(self: "HableOpsMixin[ot.CanNeg[_ResultT]]") -> H[_ResultT]:
        return self.h().__neg__()

    def __pos__(self: "HableOpsMixin[ot.CanPos[_ResultT]]") -> H[_ResultT]:
        return self.h().__pos__()

    def __abs__(self: "HableOpsMixin[ot.CanAbs[_ResultT]]") -> H[_ResultT]:
        return self.h().__abs__()

    def __invert__(self: "HableOpsMixin[ot.CanInvert[_ResultT]]") -> H[_ResultT]:
        return self.h().__invert__()

HableT

Bases: ABC, Generic[_T_co]

An abstract base whose implementer can be expressed as (or reduced to) an H object by calling its h method.

Info

The intended pronunciation of Hable is AYCH-uh-BUL1 (i.e., H-able). Yes, that is a clumsy attempt at verbing. (You could totally H that, dude!) However, if you prefer something else (e.g. HAY-bul or AYCH-AY-bul), no one is going to judge you. (Well, they might, but they shouldn’t.) We all know what you mean.


  1. World Book Online (WBO) style pronunciation respelling. ↩

Source code in dyce/h.py
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
class HableT(ABC, Generic[_T_co]):
    r"""
    An abstract base whose implementer can be expressed as (or reduced to) an [`H` object][dyce.H] by calling its [`h` method][dyce.HableT.h].

    !!! info

        The intended pronunciation of `Hable` is *AYCH-uh-BUL*[^1] (i.e., [`H`][dyce.H]-able).
        Yes, that is a clumsy attempt at [verbing](https://www.gocomics.com/calvinandhobbes/1993/01/25).
        (You could *totally* [`H`][dyce.H] that, dude!)
        However, if you prefer something else (e.g. *HAY-bul* or *AYCH-AY-bul*), no one is going to judge you.
        (Well, they *might*, but they *shouldn’t*.)
        We all know what you mean.

    [^1]:

        World Book Online (WBO) style [pronunciation respelling](https://en.wikipedia.org/wiki/Pronunciation_respelling_for_English#Traditional_respelling_systems).
    """

    __slots__ = ()

    @abstractmethod
    def h(self: "HableT[_T]") -> "H[_T]":
        r"""Expresses its implementer as an [`H` object][dyce.H]."""

h() -> H[_T] abstractmethod

Expresses its implementer as an H object.

Source code in dyce/h.py
214
215
216
@abstractmethod
def h(self: "HableT[_T]") -> "H[_T]":
    r"""Expresses its implementer as an [`H` object][dyce.H]."""

P

Bases: Sequence[H[_T_co]], HableOpsMixin[_T_co]

An immutable pool (ordered sequence) supporting group operations for zero or more H objects (provided or created from the initializer’s args parameter).

1
2
3
4
>>> from dyce import H, P
>>> p_d6 = P(6)  # shorthand for P(H(6))
>>> p_d6
P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))
1
2
3
4
5
6
>>> P(p_d6, p_d6)  # 2d6
2@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))
>>> 2 @ p_d6  # also 2d6
2@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))
>>> 2 @ (2 @ p_d6) == 4 @ p_d6
True
1
2
3
>>> p = P(4, P(6, P(8, P(10, P(12, P(20))))))
>>> p == P(4, 6, 8, 10, 12, 20)
True

This class derives from HableT through HableOpsMixin, which means it can be “flattened” into a single histogram, either explicitly via the h method, or implicitly by using arithmetic operations.

1
2
>>> -p_d6
H({-6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1})
1
2
>>> p_d6 + p_d6
H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})
1
2
>>> 2 * P(8) - 1
H({1: 1, 3: 1, 5: 1, 7: 1, 9: 1, 11: 1, 13: 1, 15: 1})

To perform arithmetic on individual H objects in a pool without flattening, use the apply_to_each_h method.

1
2
3
>>> import operator
>>> P(4, 6, 8).apply_to_each_h(operator.neg)
P(H({-8: 1, -7: 1, -6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1}), H({-6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1}), H({-4: 1, -3: 1, -2: 1, -1: 1}))
1
2
>>> P(4, 6).apply_to_each_h(operator.pow, 2)
P(H({1: 1, 4: 1, 9: 1, 16: 1}), H({1: 1, 4: 1, 9: 1, 16: 1, 25: 1, 36: 1}))
1
2
3
4
5
6
7
8
9
>>> P(4, 6).apply_to_each_h(
...     lambda h_outcome, other_outcome: (
...         operator.pow(  # zuban: ignore[no-untyped-call]
...             other_outcome, h_outcome
...         )
...     ),
...     2,
... )
P(H({2: 1, 4: 1, 8: 1, 16: 1}), H({2: 1, 4: 1, 8: 1, 16: 1, 32: 1, 64: 1}))

Comparisons with H objects work as expected.

1
2
>>> 3 @ p_d6 == H(6) + H(6) + H(6)
True

Indexing selects a contained histogram.

1
2
>>> P(4, 6, 8)[0]
H({1: 1, 2: 1, 3: 1, 4: 1})

Note that pools are opinionated about ordering.

1
2
3
4
>>> P(8, 6, 4)
P(H({1: 1, 2: 1, 3: 1, 4: 1}), H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1}))
>>> P(8, 6, 4)[0] == P(8, 4, 6)[0] == H(4)
True
Source code in dyce/p.py
 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
class P(Sequence[H[_T_co]], HableOpsMixin[_T_co]):
    r"""
    An immutable pool (ordered sequence) supporting group operations for zero or more [`H` objects][dyce.H] (provided or created from the [initializer][dyce.P.__init__]’s *args* parameter).

        >>> from dyce import H, P
        >>> p_d6 = P(6)  # shorthand for P(H(6))
        >>> p_d6
        P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))

    <!-- -->

        >>> P(p_d6, p_d6)  # 2d6
        2@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))
        >>> 2 @ p_d6  # also 2d6
        2@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))
        >>> 2 @ (2 @ p_d6) == 4 @ p_d6
        True

    <!-- -->

        >>> p = P(4, P(6, P(8, P(10, P(12, P(20))))))
        >>> p == P(4, 6, 8, 10, 12, 20)
        True

    This class derives from [`HableT`][dyce.HableT] through [`HableOpsMixin`][dyce.HableOpsMixin], which means it can be “flattened” into a single histogram, either explicitly via the [`h` method][dyce.P.h], or implicitly by using arithmetic operations.

        >>> -p_d6
        H({-6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1})

    <!-- -->

        >>> p_d6 + p_d6
        H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})

    <!-- -->

        >>> 2 * P(8) - 1
        H({1: 1, 3: 1, 5: 1, 7: 1, 9: 1, 11: 1, 13: 1, 15: 1})

    To perform arithmetic on individual [`H` objects][dyce.H] in a pool without flattening, use the [`apply_to_each_h`][dyce.P.apply_to_each_h] method.

        >>> import operator
        >>> P(4, 6, 8).apply_to_each_h(operator.neg)
        P(H({-8: 1, -7: 1, -6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1}), H({-6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1}), H({-4: 1, -3: 1, -2: 1, -1: 1}))

    <!-- -->

        >>> P(4, 6).apply_to_each_h(operator.pow, 2)
        P(H({1: 1, 4: 1, 9: 1, 16: 1}), H({1: 1, 4: 1, 9: 1, 16: 1, 25: 1, 36: 1}))

    <!-- -->

        >>> P(4, 6).apply_to_each_h(
        ...     lambda h_outcome, other_outcome: (
        ...         operator.pow(  # zuban: ignore[no-untyped-call]
        ...             other_outcome, h_outcome
        ...         )
        ...     ),
        ...     2,
        ... )
        P(H({2: 1, 4: 1, 8: 1, 16: 1}), H({2: 1, 4: 1, 8: 1, 16: 1, 32: 1, 64: 1}))

    Comparisons with [`H` objects][dyce.H] work as expected.

        >>> 3 @ p_d6 == H(6) + H(6) + H(6)
        True

    Indexing selects a contained histogram.

        >>> P(4, 6, 8)[0]
        H({1: 1, 2: 1, 3: 1, 4: 1})

    Note that pools are opinionated about ordering.

        >>> P(8, 6, 4)
        P(H({1: 1, 2: 1, 3: 1, 4: 1}), H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1}))
        >>> P(8, 6, 4)[0] == P(8, 4, 6)[0] == H(4)
        True
    """

    __slots__ = (
        "_h_groups",
        "_hash",
        "_len",
        "_total",
    )

    # ---- Initializer -----------------------------------------------------------------

    @overload
    def __init__(self: "P[Never]", *init_vals: Never) -> None: ...
    @overload
    def __init__(self: "P[int]", *init_vals: int) -> None: ...
    @overload
    def __init__(self: "P[_T]", *init_vals: "P[_T] | H[_T]") -> None: ...
    @overload
    def __init__(self: "P[int | _T]", *init_vals: "P[_T] | H[_T] | int") -> None: ...
    def __init__(
        self,
        *init_vals: Any,
    ) -> None:
        r"""
        Constructs a [`P`][dyce.P] from zero or more *init_vals*, each of which can be a histogram, pool, or initializer shorthand value.
        """
        super().__init__()
        self._h_groups: dict[H[_T_co], int]
        h_counts: Counter[H[_T_co]] = Counter()

        for init_val in init_vals:
            if isinstance(init_val, H):
                h_counts[init_val] += 1
            elif isinstance(init_val, P):
                h_counts.update(dict(init_val._h_groups.items()))  # ruff: ignore[private-member-access]
            else:
                h_counts[H(init_val)] += 1

        try:
            self._h_groups = {
                h: h_counts[h]
                for h in sorted(h_counts, key=lambda h: tuple(h.items()))
                if h
            }
        except TypeError:
            # For Hs whose outcomes don't support direct comparisons (e.g. symbolic
            # types)
            self._h_groups = {
                h: h_counts[h]
                for h in sorted(h_counts, key=lambda h: natural_key(h.items()))
                if h
            }
        self._hash: int | None = None
        self._len = sum(self._h_groups.values())
        self._total: int | None = None

    # ---- Overrides -------------------------------------------------------------------

    def __hash__(self) -> int:
        if self._hash is None:
            self._hash = hash((type(self), *self._h_groups.items()))
        return self._hash

    def __repr__(self) -> str:
        def _n_at(h: H[_T_co], n: int) -> str:
            return repr(h) if n == 1 else f"{n}@{type(self).__name__}({h!r})"

        if len(self._h_groups) == 1:
            h, hn = next(iter(self._h_groups.items()))
            return f"{type(self).__name__}({_n_at(h, 1)})" if hn == 1 else _n_at(h, hn)
        else:
            inner = ", ".join(starmap(_n_at, self._h_groups.items()))
            return f"{type(self).__name__}({inner})"

    def __eq__(self, other: object) -> bool:
        if isinstance(other, P):
            return self._h_groups == other._h_groups
        return NotImplemented

    # ---- Sequence abstract methods ---------------------------------------------------

    @overload
    def __getitem__(self: "P[_T]", key: SupportsIndex) -> H[_T]: ...
    @overload
    def __getitem__(self: "P[_T]", key: slice) -> "P[_T]": ...
    def __getitem__(self: "P[_T]", key: SupportsIndex | slice) -> "P[_T] | H[_T]":

        def _selected_hs(*indices: int) -> Iterator[H[_T]]:
            offsets: list[int] = []
            hs: list[H[_T]] = []
            cum = 0
            for h, n in self._h_groups.items():
                offsets.append(cum)
                hs.append(h)
                cum += n
            for i in indices:
                g = bisect_right(offsets, i) - 1
                yield hs[g]

        if isinstance(key, slice):
            return P(*_selected_hs(*range(*key.indices(len(self)))))
        i = operator.index(key)
        if i >= len(self) or i < -len(self):
            raise IndexError("P index out of range")
        return next(_selected_hs(len(self) + i if i < 0 else i))

    def __iter__(self: "P[_T]") -> Iterator[H[_T]]:
        for h, hn in self._h_groups.items():
            yield from (h for _ in range(hn))

    def __len__(self) -> int:
        return self._len

    # ---- Operators -------------------------------------------------------------------

    @overload
    def __matmul__(self: "P[Any]", lhs: Literal[0]) -> "P[Never]": ...
    @overload
    def __matmul__(self: "P[_T]", lhs: SupportsInt) -> "P[_T]": ...
    def __matmul__(self: "P[Any]", lhs: SupportsInt) -> "P[Any]":
        try:
            n = lossless_int(lhs)
        except (TypeError, ValueError):
            return NotImplemented
        if n < 0:
            raise ValueError(
                f"{type(self).__name__} requires non-negative operand for @ operator (found {n!r})"
            )
        # TODO(@posita): # ruff: ignore[missing-todo-link] - Put initialization logic in
        # an _init helper method and have both this and __init__ use that helper method
        # The slow and safe way
        # return P(*chain.from_iterable(repeat(self, n)))  # ruff: ignore[commented-out-code]
        # The dangerous and fast way (needs to know about __init__, __slots__,
        # initialization, etc.)
        p = P()
        if n:
            p._h_groups = {h: hn * n for h, hn in self._h_groups.items()}
            p._len = len(self) * n
            assert p._hash is None
            assert p._total is None
        return p

    @overload
    def __rmatmul__(self: "P[Any]", rhs: Literal[0]) -> "P[Never]": ...
    @overload
    def __rmatmul__(self: "P[_T]", rhs: SupportsInt) -> "P[_T]": ...
    def __rmatmul__(self: "P[Any]", rhs: SupportsInt) -> "P[Any]":
        return self.__matmul__(rhs)

    # ---- Properties ------------------------------------------------------------------

    @property
    def is_homogeneous(self) -> int:
        r"""
        `True` if the number of distinct histograms in this pool is less than or equal to one.
        """
        return len(self._h_groups) <= 1

    @property
    def total(self) -> int:
        r"""
        Equivalent to `prod(h.total for h in self)`.

        Consistent with the empty product, this is `1` for an empty pool.
        The result is cached to avoid redundant computation with multiple accesses.
        """
        if self._total is None:
            self._total = prod(h.total**hn for h, hn in self._h_groups.items())
        return self._total

    # ---- Methods ---------------------------------------------------------------------

    @overload
    def apply_to_each_h(
        self: "P[_T]",
        func: Callable[[_T], _ResultT],
        *,
        apply_to_each: bool = ...,
    ) -> "P[_ResultT]": ...
    @overload
    def apply_to_each_h(
        self: "P[_T]",
        func: Callable[[_T, _OtherT], _ResultT],
        other: "H[_OtherT]",
        *,
        apply_to_each: bool = ...,
    ) -> "P[_ResultT]": ...
    @overload
    def apply_to_each_h(
        self: "P[_T]",
        func: Callable[[_T, _OtherT], _ResultT],
        other: _OtherT,
        *,
        apply_to_each: bool = ...,
    ) -> "P[_ResultT]": ...
    def apply_to_each_h(
        self: "P[_T]",
        func: Callable[[_T], _ResultT] | Callable[[_T, _OtherT], _ResultT],
        other: "H[_OtherT] | _OtherT | SentinelT" = Sentinel,
        *,
        apply_to_each: bool = False,
    ) -> "P[_ResultT]":
        r"""
        Returns a new [`P`][dyce.P] by applying *func* to each histogram via its [`H.apply`][dyce.H.apply] method.

        If *other* is provided, *func* should have two parameters, otherwise it should have one.

        *func* is assumed to be idempotent, meaning that for each distinct histogram `h`, calling `h.apply(func, other)` should return the same result regardless of context.
        This allows for *func* to be applied only once for each distinct `H` in `P`, and the result reused.
        If this is not desired, provide `True` for *apply_to_each* to ensure that *func* is actually run on each individual histogram.
        """

        def _h_counts_by_group() -> Iterator[tuple[H[_T], int]]:
            yield from self._h_groups.items()

        def _each_h_count_in_self() -> Iterator[tuple[H[_T], int]]:
            yield from ((h, 1) for h in self)

        def _applied_hs() -> Iterator[H[_ResultT]]:
            for h, count in (
                _each_h_count_in_self() if apply_to_each else _h_counts_by_group()
            ):
                new_h = h.apply(func, other)  # type: ignore[arg-type] # ty: ignore[no-matching-overload]
                yield from (new_h for _ in range(count))

        return P(*_applied_hs())

    @overload
    def at(self: "P[Never]", which: GetItemT, *more: GetItemT) -> H[Never]: ...
    @overload
    # See <https://github.com/jorenham/optype/discussions/574>
    def at(
        self: "P[ot.CanAddSame[int, int]]", which: GetItemT, *more: GetItemT
    ) -> H[int]: ...
    @overload
    def at(
        self: "P[_AddableSameT]", which: GetItemT, *more: GetItemT
    ) -> H[_AddableSameT]: ...
    @overload
    def at(self: "P[_T]", which: int) -> H[_T]: ...
    def at(self: "P[Any]", which: GetItemT, *more: GetItemT) -> H[Any]:
        r"""
        Returns a histogram representing the sum of the outcomes at the selected positions for each possible roll.

        This is roughly equivalent to `H((sum(roll), count) for roll, count in self.rolls_with_counts(which, *more))` with optimizations.
        Identifiers can be `int`s or `slice`s, and can be mixed.

        Taking the greatest of two six-sided dice can be modeled as:

            >>> p_2d6 = 2 @ P(6)
            >>> p_2d6.at(-1)
            H({1: 1, 2: 3, 3: 5, 4: 7, 5: 9, 6: 11})
            >>> print(p_2d6.at(-1).format(width=65))
            avg |    4.47
            std |    1.40
              1 |   2.78% |#
              2 |   8.33% |####
              3 |  13.89% |######
              4 |  19.44% |#########
              5 |  25.00% |############
              6 |  30.56% |###############

        Taking the greatest two and least two faces of ten four-sided dice (`10d4`) can be modeled as:

            >>> p_10d4 = 10 @ P(4)
            >>> p_10d4.at(slice(2), slice(-2, None))
            H({4: 1, 5: 10, 6: 1012, 7: 5030, 8: 51973, 9: 168760, 10: 595004, 11: 168760, 12: 51973, 13: 5030, 14: 1012, 15: 10, 16: 1})
            >>> print(
            ...     p_10d4.at(slice(2), slice(-2, None)).format(scaled=True, width=65)
            ... )
            avg |   10.00
            std |    0.91
              4 |   0.00% |
              5 |   0.00% |
              6 |   0.10% |
              7 |   0.48% |
              8 |   4.96% |####
              9 |  16.09% |##############
             10 |  56.74% |##################################################
             11 |  16.09% |##############
             12 |   4.96% |####
             13 |   0.48% |
             14 |   0.10% |
             15 |   0.00% |
             16 |   0.00% |

        Taking all outcomes exactly once is equivalent to summing the histograms in the pool.

            >>> d6 = H(6)
            >>> d6avg = H((2, 3, 3, 4, 4, 5))
            >>> p = 2 @ P(d6, d6avg)
            >>> p.at(slice(None)) == p.h() == d6 + d6 + d6avg + d6avg
            True

        !!! note "On selection ordering"

            As an optimization, selected outcomes are summed in the order in which they appear in sorted rolls, regardless of the order they appear in *which*.
            Where addition over the outcomes’ type is commutative, equivalence holds as expected:

                >>> p_c = P(2, 3, 4)
                >>> p_c.at(
                ...     slice(None),  # select everything once
                ...     slice(None),  # then select everything again
                ... ) == 2 * p_c.h()
                True

            Where outcomes define `__add__` as non-commutative (e.g., strings, sequences, etc.), ordering can affect construction under certain circumstances:

                >>> p_nc = P(H(((1,), (2,))), H(((3,), (4,))), H(((5,), (6,))))
                >>> p_nc.at(
                ...     slice(None),  # select everything once, then again, like above
                ...     slice(None),  # pyright: ignore[reportCallIssue]
                ... )
                H({(1, 1, 3, 3, 5, 5): 1, (1, 1, 3, 3, 6, 6): 1, ..., (2, 2, 4, 4, 5, 5): 1, (2, 2, 4, 4, 6, 6): 1})
                >>> 2 * p_nc.h()  # type: ignore[operator]
                H({(1, 3, 5, 1, 3, 5): 1, (1, 3, 6, 1, 3, 6): 1, ..., (2, 4, 5, 2, 4, 5): 1, (2, 4, 6, 2, 4, 6): 1})
        """
        n = len(self)
        indices = tuple(range(n))
        selected = tuple(getitems(indices, (which, *more)))
        if not selected:
            return H({})
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ExperimentalWarning)
            if len(selected) == 1 and len(self._h_groups) == 1:
                h, count = next(iter(self._h_groups.items()))
                return h.order_stat_for_n_at_pos(count, selected[0])
            # Reducing each repeated group to its extreme strictly shrinks the pool,
            # so recursion terminates once every remaining group has count one.
            if (
                len(selected) == 1
                and selected[0] in (0, n - 1)
                and any(count > 1 for count in self._h_groups.values())
            ):
                from_right = selected[0] == n - 1
                reduced = P(
                    *(
                        h.order_stat_for_n_at_pos(count, count - 1 if from_right else 0)
                        for h, count in self._h_groups.items()
                    )
                )
                return reduced.at(-1 if from_right else 0)
            # Unlike rolls_with_counts, at can fold large selections directly without
            # materializing rolls, which becomes faster beyond roughly half the pool.
            if 1 < len(selected) <= n // 2:
                h_groups = tuple(self._h_groups.items())
                if selected == tuple(range(len(selected))):
                    return H.from_counts(
                        (reduce(operator.add, roll), weight)
                        for roll, weight in _rwc_heterogeneous_one_end(
                            h_groups, len(selected), from_right=False
                        )
                    )
                if selected == tuple(range(n - len(selected), n)):
                    return H.from_counts(
                        (reduce(operator.add, roll), weight)
                        for roll, weight in _rwc_heterogeneous_one_end(
                            h_groups, len(selected), from_right=True
                        )
                    )
            return self.survey(_WhichHSurveyor(self, selected))

    @overload
    def h(self: "P[Never]") -> H[Never]: ...
    @overload
    # See <https://github.com/jorenham/optype/discussions/574>
    def h(self: "P[ot.CanAddSame[int, int]]") -> H[int]: ...
    @overload
    def h(self: "P[_AddableSameT]") -> H[_AddableSameT]: ...
    @overload
    def h(self: "P[_T]") -> H[_T]: ...
    def h(self: "P[Any]") -> H[Any]:
        r"""
        Combines (or “flattens”) all contained histograms into a single [`H`][dyce.H] in accordance with the [`HableT` abstract base][dyce.HableT].

            >>> (2 @ P(6)).h()
            H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})
        """
        if len(self._h_groups) == 0:
            return H({})
        if self._len == 1:
            return next(iter(self._h_groups))
        return sum_h(self)

    @experimental
    def sample(self: "P[_T]") -> RollT[_T]:
        r"""
        Returns (weighted) random outcomes from contained histograms.

        !!! note "On ordering"

            This method “works” (i.e., falls back to a “natural” ordering of string representations) for outcomes whose relative values cannot be known (e.g., symbolic expressions).
            This is deliberate to allow random roll functionality where symbolic resolution is not needed or will happen later.
        """
        if not self:
            raise ValueError("no outcomes from an empty pool")
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ExperimentalWarning)
            roll = [h.sample() for h in self]
        try:
            roll.sort()  # pyright: ignore[reportCallIssue] # zuban: ignore[call-arg]
        except TypeError:
            roll.sort(key=natural_key)
        return tuple(roll)

    def rolls_with_counts(self: "P[_T]", *which: GetItemT) -> Iterator[RollCountT[_T]]:
        r"""
        Returns an iterator yielding `(roll, count)` pairs that collectively enumerate all distinct rolls of the pool.

        Each *roll* is a sorted tuple of outcomes (least to greatest); *count* is the number of ways that roll occurs.

        If one or more *which* arguments are provided (as `SupportsIndex` or `slice` values), each roll is filtered to the selected positions before yielding.

            >>> from dyce import H, P
            >>> p_2d6 = 2 @ P(6)
            >>> H.from_counts(
            ...     (sum(roll), count) for roll, count in p_2d6.rolls_with_counts()
            ... ) == p_2d6.h()
            True

        *which* selects by sorted position.
        An inefficient way to take the highest outcome from 3d6:

            >>> p_3d6 = 3 @ P(6)
            >>> H.from_counts(
            ...     (roll[0], count) for roll, count in p_3d6.rolls_with_counts(-1)
            ... )
            H({1: 1, 2: 7, 3: 19, 4: 37, 5: 61, 6: 91})

        Multiple *which* arguments are aggregated:

            >>> lo_hi_from_all_3d6_rolls = sorted(
            ...     p_3d6.rolls_with_counts(0, -1)  # selects lowest and highest of 3d6
            ... )
            >>> lo_hi_from_all_3d6_rolls
            [((1, 1), 1), ((1, 2), 6), ((1, 3), 12), ..., ((5, 5), 1), ((5, 6), 6), ((6, 6), 1)]
            >>> H.from_counts(lo_hi_from_all_3d6_rolls) == H.from_counts(
            ...     ((r[0], r[-1]), c) for r, c in p_3d6.rolls_with_counts()
            ... )
            True

        Collectively selecting everything with no overlaps is the same as the default.

            >>> p_2df = 2 @ P(H((-1, 0, 1)))
            >>> p_2df_rolls = sorted(p_2df.rolls_with_counts())
            >>> p_2df_rolls
            [((-1, -1), 1), ((-1, 0), 2), ((-1, 1), 2), ((0, 0), 1), ((0, 1), 2), ((1, 1), 1)]
            >>> sorted(p_2df.rolls_with_counts(0, 1)) == p_2df_rolls
            True
            >>> sorted(
            ...     p_2df.rolls_with_counts(slice(None, 1), slice(1, None))
            ... ) == p_2df_rolls
            True

        This method may yield the same roll more than once under certain conditions (e.g., non-contiguous *which* selections, where heterogeneous pools produce similar rolls for each group ordering):

            >>> sorted((3 @ P(H(2))).rolls_with_counts(0, -1))
            [((1, 1), 1), ((1, 2), 6), ((2, 2), 1)]
            >>> sorted(P(H(2), H(3)).rolls_with_counts())
            [((1, 1), 1), ((1, 2), 2), ((1, 3), 1), ((2, 2), 1), ((2, 3), 1)]

        No rolls will be produced with empty `P` objects or where *which* selects no positions.

            >>> sorted(P(6).rolls_with_counts(slice(6, 7)))
            []
            >>> sorted(P().rolls_with_counts())
            []
        """
        n = len(self)
        indices = tuple(range(n))
        selected = tuple(getitems(indices, which or indices))
        if len(selected) == 1 and len(self._h_groups) == 1:
            h, count = next(iter(self._h_groups.items()))
            with warnings.catch_warnings():
                warnings.simplefilter("ignore", ExperimentalWarning)
                order_stat_h = h.order_stat_for_n_at_pos(count, selected[0])
            yield from (
                ((outcome,), weight) for outcome, weight in order_stat_h.items()
            )
            return
        if len(selected) == 1 and len(self._h_groups) > 1 and selected[0] in (0, n - 1):
            extreme_h = self.at(-1 if selected[0] == n - 1 else 0)
            yield from (((outcome,), weight) for outcome, weight in extreme_h.items())
            return
        if 1 < len(selected) < n and (
            len(self._h_groups) == 1 or len(selected) <= n // 2
        ):
            h_groups = tuple(self._h_groups.items())
            if selected == tuple(range(len(selected))):
                yield from _rwc_heterogeneous_one_end(
                    h_groups, len(selected), from_right=False
                )
                return
            if selected == tuple(range(n - len(selected), n)):
                yield from _rwc_heterogeneous_one_end(
                    h_groups, len(selected), from_right=True
                )
                return
        yield from (
            self._survey_raw(_WhichRollSurveyor(self, selected)) if selected else ()
        )

    @overload
    def survey(
        self: "P[_T]",
        surveyor: SurveyorBase[_T, _StateT, _ResultT],
    ) -> H[_ResultT]: ...
    @overload
    def survey(
        self: "P[_T]",
        *,
        accumulate: Callable[[_StateT | None, _T, int], _StateT],
        initial: _StateT | None = ...,
        order: Callable[[Iterable[_T]], Iterable[_T]],
        settle: None = ...,
    ) -> H[_StateT]: ...
    @overload
    def survey(
        self: "P[_T]",
        *,
        accumulate: Callable[[_StateT | None, _T, int], _StateT],
        initial: _StateT | None = ...,
        order: Callable[[Iterable[_T]], Iterable[_T]],
        settle: Callable[[_StateT], _ResultT],
    ) -> H[_ResultT]: ...
    @experimental
    def survey(
        self: "P[_T]",
        surveyor: SurveyorBase[_T, _StateT, _ResultT] | None = None,
        *,
        accumulate: Callable[[_StateT | None, _T, int], _StateT] | None = None,
        initial: _StateT | None = None,
        order: Callable[[Iterable[_T]], Iterable[_T]] | None = None,
        settle: Callable[[_StateT], _ResultT] | None = None,
    ) -> H[_StateT | _ResultT]:
        r"""
        Returns a new [`H`][dyce.H] by folding a transition function defined by *surveyor* over the pool one outcome at a time.

        This implements a state-collapsing dynamic algorithm similar to Albert Julius Liu’s [`icepool`](https://github.com/HighDiceRoller/icepool).
        Rather than enumerating every distinct roll, it sweeps the shared outcome axis once, and branches on how many dice show each distinct outcome.
        Equivalent partial rolls that reach the same state are merged, so the cost scales with the number of reachable states rather than the number of rolls.

        If provided, *surveyor* bundles the *accumulate*, *order*, and *settle* methods as well as the *initial* property.
        Otherwise, each may be provided separately.
        *accumulate* and *order* are required.
        *initial* and *settle* are optional.

        *accumulate* is called as `accumulate(state, outcome, count)` and returns the successor state.
        On the first (seed) call, *state* is `surveyor.initial`.
        *count* is the number of dice showing *outcome*, aggregated across all of the pool’s (possibly heterogeneous) histograms, and is always at least `1`.
        *state* must be hashable, since equal states are merged.
        *order* selects the sweep order over the shared outcome set.

        !!! note "Only present outcomes are accumulated"

            *accumulate* is invoked only for outcomes that at least one die shows, never for absent ones.
            A mechanic that must reason about gaps in a sequence (e.g. the longest run of consecutive values) should therefore compare neighboring *outcome* values rather than expecting to be notified of the absent ones.


        If provided, *settle* maps each terminal state to the outcome recorded in the resulting [`H`][dyce.H].
        Otherwise, *accumulate*’s terminal states are themselves the outcomes.

        Summing three six-sided dice, cross-checked against [`h`][dyce.P.h] (note that *count* scales each outcome’s contribution):

            >>> from dyce import P
            >>> from dyce.p import survey_outcome_order_ascending
            >>> def running_sum(state: int | None, outcome: int, count: int) -> int:
            ...     return outcome * count if state is None else state + outcome * count
            >>> p_3d6 = 3 @ P(6)
            >>> p_3d6.survey(
            ...     accumulate=running_sum, order=survey_outcome_order_ascending
            ... ) == p_3d6.h()
            True

        Keeping the greatest two of four six-sided dice is order-sensitive, so it sweeps descending and uses *settle* to project the accumulated sum:

            >>> from dyce.p import survey_outcome_order_descending
            >>> def keep_highest_two(
            ...     state: tuple[int, int] | None, outcome: int, count: int
            ... ) -> tuple[int, int]:
            ...     kept, total = (0, 0) if state is None else state
            ...     take = min(count, 2 - kept)
            ...     return kept + take, total + outcome * take
            >>> p_4d6 = 4 @ P(6)
            >>> keep = p_4d6.survey(
            ...     accumulate=keep_highest_two,
            ...     order=survey_outcome_order_descending,
            ...     settle=lambda s: s[1],
            ... )
            >>> keep == p_4d6.at(slice(-2, None))
            True
        """
        if surveyor is None:
            if accumulate is None or order is None:
                raise ValueError("must provide a surveyor or an accumulate and order")
            survey_raw_iter = (
                # Without the convoluted ... if settle is None else ... structure below,
                # Mypy is confused whether the return type is H[_StateT] or H[_ResultT]
                self._survey_raw(
                    # settle is None, return type is H[_StateT]
                    ParameterizedSurveyor(
                        accumulate,
                        order,
                        initial=initial,
                    )
                )
                if settle is None
                else self._survey_raw(
                    # settle is not None, return type is H[_ResultT]
                    ParameterizedSurveyor(
                        accumulate,
                        order,
                        initial=initial,
                        settle=settle,
                    )
                )
            )
            return aggregate_weighted(survey_raw_iter)  # zuban: ignore[no-any-return]
        else:
            if (
                accumulate is not None
                or initial is not None
                or order is not None
                or settle is not None
            ):
                raise ValueError(
                    "must not provide an accumulate and order with a surveyor"
                )
            return aggregate_weighted(self._survey_raw(surveyor))

    def _survey_raw(  # ruff: ignore[complex-structure]
        self: "P[_T]",
        surveyor: SurveyorBase[_T, _StateT, _ResultT],
    ) -> Iterator[tuple[_ResultT, int]]:
        uniq_outcomes = list(
            surveyor.order(set().union(*(set(h) for h in self._h_groups)))
        )
        if not uniq_outcomes:
            return

        group_items = tuple(self._h_groups.items())
        n_groups = len(group_items)
        group_weights = tuple(
            tuple(h.get(outcome, 0) for outcome in uniq_outcomes)
            for h, _ in group_items
        )
        memo: dict[
            tuple[  # key
                int,  # current unique outcome index; outcomes[uniq_outcome_idx]
                tuple[int, ...],  # remaining split counts for outcome (one per group)
            ],
            dict[  # value
                _StateT,
                int,  # weight
            ],
        ] = {}

        def _solve(  # ruff: ignore[complex-structure]
            uniq_outcome_idx: int, group_split_counts: tuple[int, ...]
        ) -> dict[_StateT, int]:
            key = (uniq_outcome_idx, group_split_counts)
            if key in memo:
                return memo[key]
            outcome = uniq_outcomes[uniq_outcome_idx]
            result: dict[
                _StateT,
                int,  # weight
            ] = defaultdict(int)
            if uniq_outcome_idx == 0:
                # Base case: every remaining die must show the first outcome (lowest for
                # ascending, highest for descending)
                scale = prod(
                    group_weights[g][0] ** group_split_counts[g]
                    for g in range(n_groups)
                )
                if scale:
                    count = sum(group_split_counts)
                    seed = (
                        surveyor.accumulate(surveyor.initial, outcome, count)
                        if count
                        else cast("_StateT", surveyor.initial)
                    )
                    result[seed] += scale
            else:
                # For a heterogeneous pool, an outcome can come from different groups
                # ("splits"). accumulate only cares about the total, not which group
                # supplied them. So the code sums the weight of all splits sharing a
                # total into by_count first, then calls accumulate(state, outcome,
                # count) once instead of calling it redundantly for each split.
                state_weights_by_count: dict[
                    int,  # count of dice showing uniq_outcomes[uniq_outcome_idx]
                    dict[
                        _StateT,
                        int,  # weight
                    ],
                ] = defaultdict(lambda: defaultdict(int))
                # For each group g, establish a range of 0..group_split_counts[g] (0 up
                # to all its remaining dice). Then take the Cartesian product across
                # those group ranges, so split is a tuple (k_0, k_1, ...), one count per
                # group. For example, take 2 groups with the respective counts (2, 1).
                # This produces splits of (0,0), (0,1), (1,0), (1,1), (2,0), (2,1). Each
                # is one candidate allocation of dice to this outcome. The loop body
                # then weights it and recurses on the leftover.
                for split in product(
                    *(range(group_split_counts[g] + 1) for g in range(n_groups))
                ):
                    scale = 1
                    for g in range(n_groups):
                        scale *= (
                            comb(group_split_counts[g], split[g])
                            * group_weights[g][uniq_outcome_idx] ** split[g]
                        )
                    if scale == 0:
                        # This group has no such outcome (e.g., trying to role a 6 on a
                        # d4)
                        continue
                    remaining = tuple(
                        group_split_counts[g] - split[g] for g in range(n_groups)
                    )
                    for state, weight in _solve(
                        uniq_outcome_idx - 1, remaining
                    ).items():
                        state_weights_by_count[sum(split)][state] += weight * scale
                for count, states in state_weights_by_count.items():
                    if count:
                        for state, weight in states.items():
                            result[surveyor.accumulate(state, outcome, count)] += weight
                    else:
                        # States pass through unchanged
                        for state, weight in states.items():
                            result[state] += weight
            memo[key] = dict(result)
            return memo[key]

        final_states = _solve(len(uniq_outcomes) - 1, tuple(n for _, n in group_items))

        yield from (
            (surveyor.settle(state), weight) for state, weight in final_states.items()
        )

is_homogeneous: int property

True if the number of distinct histograms in this pool is less than or equal to one.

total: int property

Equivalent to prod(h.total for h in self).

Consistent with the empty product, this is 1 for an empty pool. The result is cached to avoid redundant computation with multiple accesses.

__init__(*init_vals: Any) -> None

__init__(*init_vals: Never) -> None
__init__(*init_vals: int) -> None
__init__(*init_vals: P[_T] | H[_T]) -> None
__init__(*init_vals: P[_T] | H[_T] | int) -> None

Constructs a P from zero or more init_vals, each of which can be a histogram, pool, or initializer shorthand value.

Source code in dyce/p.py
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
def __init__(
    self,
    *init_vals: Any,
) -> None:
    r"""
    Constructs a [`P`][dyce.P] from zero or more *init_vals*, each of which can be a histogram, pool, or initializer shorthand value.
    """
    super().__init__()
    self._h_groups: dict[H[_T_co], int]
    h_counts: Counter[H[_T_co]] = Counter()

    for init_val in init_vals:
        if isinstance(init_val, H):
            h_counts[init_val] += 1
        elif isinstance(init_val, P):
            h_counts.update(dict(init_val._h_groups.items()))  # ruff: ignore[private-member-access]
        else:
            h_counts[H(init_val)] += 1

    try:
        self._h_groups = {
            h: h_counts[h]
            for h in sorted(h_counts, key=lambda h: tuple(h.items()))
            if h
        }
    except TypeError:
        # For Hs whose outcomes don't support direct comparisons (e.g. symbolic
        # types)
        self._h_groups = {
            h: h_counts[h]
            for h in sorted(h_counts, key=lambda h: natural_key(h.items()))
            if h
        }
    self._hash: int | None = None
    self._len = sum(self._h_groups.values())
    self._total: int | None = None

apply_to_each_h(func: Callable[[_T], _ResultT] | Callable[[_T, _OtherT], _ResultT], other: H[_OtherT] | _OtherT | SentinelT = Sentinel, *, apply_to_each: bool = False) -> P[_ResultT]

apply_to_each_h(func: Callable[[_T], _ResultT], *, apply_to_each: bool = ...) -> P[_ResultT]
apply_to_each_h(func: Callable[[_T, _OtherT], _ResultT], other: H[_OtherT], *, apply_to_each: bool = ...) -> P[_ResultT]
apply_to_each_h(func: Callable[[_T, _OtherT], _ResultT], other: _OtherT, *, apply_to_each: bool = ...) -> P[_ResultT]

Returns a new P by applying func to each histogram via its H.apply method.

If other is provided, func should have two parameters, otherwise it should have one.

func is assumed to be idempotent, meaning that for each distinct histogram h, calling h.apply(func, other) should return the same result regardless of context. This allows for func to be applied only once for each distinct H in P, and the result reused. If this is not desired, provide True for apply_to_each to ensure that func is actually run on each individual histogram.

Source code in dyce/p.py
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
def apply_to_each_h(
    self: "P[_T]",
    func: Callable[[_T], _ResultT] | Callable[[_T, _OtherT], _ResultT],
    other: "H[_OtherT] | _OtherT | SentinelT" = Sentinel,
    *,
    apply_to_each: bool = False,
) -> "P[_ResultT]":
    r"""
    Returns a new [`P`][dyce.P] by applying *func* to each histogram via its [`H.apply`][dyce.H.apply] method.

    If *other* is provided, *func* should have two parameters, otherwise it should have one.

    *func* is assumed to be idempotent, meaning that for each distinct histogram `h`, calling `h.apply(func, other)` should return the same result regardless of context.
    This allows for *func* to be applied only once for each distinct `H` in `P`, and the result reused.
    If this is not desired, provide `True` for *apply_to_each* to ensure that *func* is actually run on each individual histogram.
    """

    def _h_counts_by_group() -> Iterator[tuple[H[_T], int]]:
        yield from self._h_groups.items()

    def _each_h_count_in_self() -> Iterator[tuple[H[_T], int]]:
        yield from ((h, 1) for h in self)

    def _applied_hs() -> Iterator[H[_ResultT]]:
        for h, count in (
            _each_h_count_in_self() if apply_to_each else _h_counts_by_group()
        ):
            new_h = h.apply(func, other)  # type: ignore[arg-type] # ty: ignore[no-matching-overload]
            yield from (new_h for _ in range(count))

    return P(*_applied_hs())

at(which: GetItemT, *more: GetItemT) -> H[Any]

at(which: GetItemT, *more: GetItemT) -> H[Never]
at(which: GetItemT, *more: GetItemT) -> H[int]
at(which: GetItemT, *more: GetItemT) -> H[_AddableSameT]
at(which: int) -> H[_T]

Returns a histogram representing the sum of the outcomes at the selected positions for each possible roll.

This is roughly equivalent to H((sum(roll), count) for roll, count in self.rolls_with_counts(which, *more)) with optimizations. Identifiers can be ints or slices, and can be mixed.

Taking the greatest of two six-sided dice can be modeled as:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> p_2d6 = 2 @ P(6)
>>> p_2d6.at(-1)
H({1: 1, 2: 3, 3: 5, 4: 7, 5: 9, 6: 11})
>>> print(p_2d6.at(-1).format(width=65))
avg |    4.47
std |    1.40
  1 |   2.78% |#
  2 |   8.33% |####
  3 |  13.89% |######
  4 |  19.44% |#########
  5 |  25.00% |############
  6 |  30.56% |###############

Taking the greatest two and least two faces of ten four-sided dice (10d4) can be modeled as:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
>>> p_10d4 = 10 @ P(4)
>>> p_10d4.at(slice(2), slice(-2, None))
H({4: 1, 5: 10, 6: 1012, 7: 5030, 8: 51973, 9: 168760, 10: 595004, 11: 168760, 12: 51973, 13: 5030, 14: 1012, 15: 10, 16: 1})
>>> print(
...     p_10d4.at(slice(2), slice(-2, None)).format(scaled=True, width=65)
... )
avg |   10.00
std |    0.91
  4 |   0.00% |
  5 |   0.00% |
  6 |   0.10% |
  7 |   0.48% |
  8 |   4.96% |####
  9 |  16.09% |##############
 10 |  56.74% |##################################################
 11 |  16.09% |##############
 12 |   4.96% |####
 13 |   0.48% |
 14 |   0.10% |
 15 |   0.00% |
 16 |   0.00% |

Taking all outcomes exactly once is equivalent to summing the histograms in the pool.

1
2
3
4
5
>>> d6 = H(6)
>>> d6avg = H((2, 3, 3, 4, 4, 5))
>>> p = 2 @ P(d6, d6avg)
>>> p.at(slice(None)) == p.h() == d6 + d6 + d6avg + d6avg
True

On selection ordering

As an optimization, selected outcomes are summed in the order in which they appear in sorted rolls, regardless of the order they appear in which. Where addition over the outcomes’ type is commutative, equivalence holds as expected:

1
2
3
4
5
6
>>> p_c = P(2, 3, 4)
>>> p_c.at(
...     slice(None),  # select everything once
...     slice(None),  # then select everything again
... ) == 2 * p_c.h()
True

Where outcomes define __add__ as non-commutative (e.g., strings, sequences, etc.), ordering can affect construction under certain circumstances:

1
2
3
4
5
6
7
8
>>> p_nc = P(H(((1,), (2,))), H(((3,), (4,))), H(((5,), (6,))))
>>> p_nc.at(
...     slice(None),  # select everything once, then again, like above
...     slice(None),  # pyright: ignore[reportCallIssue]
... )
H({(1, 1, 3, 3, 5, 5): 1, (1, 1, 3, 3, 6, 6): 1, ..., (2, 2, 4, 4, 5, 5): 1, (2, 2, 4, 4, 6, 6): 1})
>>> 2 * p_nc.h()  # type: ignore[operator]
H({(1, 3, 5, 1, 3, 5): 1, (1, 3, 6, 1, 3, 6): 1, ..., (2, 4, 5, 2, 4, 5): 1, (2, 4, 6, 2, 4, 6): 1})
Source code in dyce/p.py
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
def at(self: "P[Any]", which: GetItemT, *more: GetItemT) -> H[Any]:
    r"""
    Returns a histogram representing the sum of the outcomes at the selected positions for each possible roll.

    This is roughly equivalent to `H((sum(roll), count) for roll, count in self.rolls_with_counts(which, *more))` with optimizations.
    Identifiers can be `int`s or `slice`s, and can be mixed.

    Taking the greatest of two six-sided dice can be modeled as:

        >>> p_2d6 = 2 @ P(6)
        >>> p_2d6.at(-1)
        H({1: 1, 2: 3, 3: 5, 4: 7, 5: 9, 6: 11})
        >>> print(p_2d6.at(-1).format(width=65))
        avg |    4.47
        std |    1.40
          1 |   2.78% |#
          2 |   8.33% |####
          3 |  13.89% |######
          4 |  19.44% |#########
          5 |  25.00% |############
          6 |  30.56% |###############

    Taking the greatest two and least two faces of ten four-sided dice (`10d4`) can be modeled as:

        >>> p_10d4 = 10 @ P(4)
        >>> p_10d4.at(slice(2), slice(-2, None))
        H({4: 1, 5: 10, 6: 1012, 7: 5030, 8: 51973, 9: 168760, 10: 595004, 11: 168760, 12: 51973, 13: 5030, 14: 1012, 15: 10, 16: 1})
        >>> print(
        ...     p_10d4.at(slice(2), slice(-2, None)).format(scaled=True, width=65)
        ... )
        avg |   10.00
        std |    0.91
          4 |   0.00% |
          5 |   0.00% |
          6 |   0.10% |
          7 |   0.48% |
          8 |   4.96% |####
          9 |  16.09% |##############
         10 |  56.74% |##################################################
         11 |  16.09% |##############
         12 |   4.96% |####
         13 |   0.48% |
         14 |   0.10% |
         15 |   0.00% |
         16 |   0.00% |

    Taking all outcomes exactly once is equivalent to summing the histograms in the pool.

        >>> d6 = H(6)
        >>> d6avg = H((2, 3, 3, 4, 4, 5))
        >>> p = 2 @ P(d6, d6avg)
        >>> p.at(slice(None)) == p.h() == d6 + d6 + d6avg + d6avg
        True

    !!! note "On selection ordering"

        As an optimization, selected outcomes are summed in the order in which they appear in sorted rolls, regardless of the order they appear in *which*.
        Where addition over the outcomes’ type is commutative, equivalence holds as expected:

            >>> p_c = P(2, 3, 4)
            >>> p_c.at(
            ...     slice(None),  # select everything once
            ...     slice(None),  # then select everything again
            ... ) == 2 * p_c.h()
            True

        Where outcomes define `__add__` as non-commutative (e.g., strings, sequences, etc.), ordering can affect construction under certain circumstances:

            >>> p_nc = P(H(((1,), (2,))), H(((3,), (4,))), H(((5,), (6,))))
            >>> p_nc.at(
            ...     slice(None),  # select everything once, then again, like above
            ...     slice(None),  # pyright: ignore[reportCallIssue]
            ... )
            H({(1, 1, 3, 3, 5, 5): 1, (1, 1, 3, 3, 6, 6): 1, ..., (2, 2, 4, 4, 5, 5): 1, (2, 2, 4, 4, 6, 6): 1})
            >>> 2 * p_nc.h()  # type: ignore[operator]
            H({(1, 3, 5, 1, 3, 5): 1, (1, 3, 6, 1, 3, 6): 1, ..., (2, 4, 5, 2, 4, 5): 1, (2, 4, 6, 2, 4, 6): 1})
    """
    n = len(self)
    indices = tuple(range(n))
    selected = tuple(getitems(indices, (which, *more)))
    if not selected:
        return H({})
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", ExperimentalWarning)
        if len(selected) == 1 and len(self._h_groups) == 1:
            h, count = next(iter(self._h_groups.items()))
            return h.order_stat_for_n_at_pos(count, selected[0])
        # Reducing each repeated group to its extreme strictly shrinks the pool,
        # so recursion terminates once every remaining group has count one.
        if (
            len(selected) == 1
            and selected[0] in (0, n - 1)
            and any(count > 1 for count in self._h_groups.values())
        ):
            from_right = selected[0] == n - 1
            reduced = P(
                *(
                    h.order_stat_for_n_at_pos(count, count - 1 if from_right else 0)
                    for h, count in self._h_groups.items()
                )
            )
            return reduced.at(-1 if from_right else 0)
        # Unlike rolls_with_counts, at can fold large selections directly without
        # materializing rolls, which becomes faster beyond roughly half the pool.
        if 1 < len(selected) <= n // 2:
            h_groups = tuple(self._h_groups.items())
            if selected == tuple(range(len(selected))):
                return H.from_counts(
                    (reduce(operator.add, roll), weight)
                    for roll, weight in _rwc_heterogeneous_one_end(
                        h_groups, len(selected), from_right=False
                    )
                )
            if selected == tuple(range(n - len(selected), n)):
                return H.from_counts(
                    (reduce(operator.add, roll), weight)
                    for roll, weight in _rwc_heterogeneous_one_end(
                        h_groups, len(selected), from_right=True
                    )
                )
        return self.survey(_WhichHSurveyor(self, selected))

h() -> H[Any]

h() -> H[Never]
h() -> H[int]
h() -> H[_AddableSameT]
h() -> H[_T]

Combines (or “flattens”) all contained histograms into a single H in accordance with the HableT abstract base.

1
2
>>> (2 @ P(6)).h()
H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})
Source code in dyce/p.py
718
719
720
721
722
723
724
725
726
727
728
729
def h(self: "P[Any]") -> H[Any]:
    r"""
    Combines (or “flattens”) all contained histograms into a single [`H`][dyce.H] in accordance with the [`HableT` abstract base][dyce.HableT].

        >>> (2 @ P(6)).h()
        H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})
    """
    if len(self._h_groups) == 0:
        return H({})
    if self._len == 1:
        return next(iter(self._h_groups))
    return sum_h(self)

rolls_with_counts(*which: GetItemT) -> Iterator[RollCountT[_T]]

Returns an iterator yielding (roll, count) pairs that collectively enumerate all distinct rolls of the pool.

Each roll is a sorted tuple of outcomes (least to greatest); count is the number of ways that roll occurs.

If one or more which arguments are provided (as SupportsIndex or slice values), each roll is filtered to the selected positions before yielding.

1
2
3
4
5
6
>>> from dyce import H, P
>>> p_2d6 = 2 @ P(6)
>>> H.from_counts(
...     (sum(roll), count) for roll, count in p_2d6.rolls_with_counts()
... ) == p_2d6.h()
True

which selects by sorted position. An inefficient way to take the highest outcome from 3d6:

1
2
3
4
5
>>> p_3d6 = 3 @ P(6)
>>> H.from_counts(
...     (roll[0], count) for roll, count in p_3d6.rolls_with_counts(-1)
... )
H({1: 1, 2: 7, 3: 19, 4: 37, 5: 61, 6: 91})

Multiple which arguments are aggregated:

1
2
3
4
5
6
7
8
9
>>> lo_hi_from_all_3d6_rolls = sorted(
...     p_3d6.rolls_with_counts(0, -1)  # selects lowest and highest of 3d6
... )
>>> lo_hi_from_all_3d6_rolls
[((1, 1), 1), ((1, 2), 6), ((1, 3), 12), ..., ((5, 5), 1), ((5, 6), 6), ((6, 6), 1)]
>>> H.from_counts(lo_hi_from_all_3d6_rolls) == H.from_counts(
...     ((r[0], r[-1]), c) for r, c in p_3d6.rolls_with_counts()
... )
True

Collectively selecting everything with no overlaps is the same as the default.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> p_2df = 2 @ P(H((-1, 0, 1)))
>>> p_2df_rolls = sorted(p_2df.rolls_with_counts())
>>> p_2df_rolls
[((-1, -1), 1), ((-1, 0), 2), ((-1, 1), 2), ((0, 0), 1), ((0, 1), 2), ((1, 1), 1)]
>>> sorted(p_2df.rolls_with_counts(0, 1)) == p_2df_rolls
True
>>> sorted(
...     p_2df.rolls_with_counts(slice(None, 1), slice(1, None))
... ) == p_2df_rolls
True

This method may yield the same roll more than once under certain conditions (e.g., non-contiguous which selections, where heterogeneous pools produce similar rolls for each group ordering):

1
2
3
4
>>> sorted((3 @ P(H(2))).rolls_with_counts(0, -1))
[((1, 1), 1), ((1, 2), 6), ((2, 2), 1)]
>>> sorted(P(H(2), H(3)).rolls_with_counts())
[((1, 1), 1), ((1, 2), 2), ((1, 3), 1), ((2, 2), 1), ((2, 3), 1)]

No rolls will be produced with empty P objects or where which selects no positions.

1
2
3
4
>>> sorted(P(6).rolls_with_counts(slice(6, 7)))
[]
>>> sorted(P().rolls_with_counts())
[]
Source code in dyce/p.py
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
def rolls_with_counts(self: "P[_T]", *which: GetItemT) -> Iterator[RollCountT[_T]]:
    r"""
    Returns an iterator yielding `(roll, count)` pairs that collectively enumerate all distinct rolls of the pool.

    Each *roll* is a sorted tuple of outcomes (least to greatest); *count* is the number of ways that roll occurs.

    If one or more *which* arguments are provided (as `SupportsIndex` or `slice` values), each roll is filtered to the selected positions before yielding.

        >>> from dyce import H, P
        >>> p_2d6 = 2 @ P(6)
        >>> H.from_counts(
        ...     (sum(roll), count) for roll, count in p_2d6.rolls_with_counts()
        ... ) == p_2d6.h()
        True

    *which* selects by sorted position.
    An inefficient way to take the highest outcome from 3d6:

        >>> p_3d6 = 3 @ P(6)
        >>> H.from_counts(
        ...     (roll[0], count) for roll, count in p_3d6.rolls_with_counts(-1)
        ... )
        H({1: 1, 2: 7, 3: 19, 4: 37, 5: 61, 6: 91})

    Multiple *which* arguments are aggregated:

        >>> lo_hi_from_all_3d6_rolls = sorted(
        ...     p_3d6.rolls_with_counts(0, -1)  # selects lowest and highest of 3d6
        ... )
        >>> lo_hi_from_all_3d6_rolls
        [((1, 1), 1), ((1, 2), 6), ((1, 3), 12), ..., ((5, 5), 1), ((5, 6), 6), ((6, 6), 1)]
        >>> H.from_counts(lo_hi_from_all_3d6_rolls) == H.from_counts(
        ...     ((r[0], r[-1]), c) for r, c in p_3d6.rolls_with_counts()
        ... )
        True

    Collectively selecting everything with no overlaps is the same as the default.

        >>> p_2df = 2 @ P(H((-1, 0, 1)))
        >>> p_2df_rolls = sorted(p_2df.rolls_with_counts())
        >>> p_2df_rolls
        [((-1, -1), 1), ((-1, 0), 2), ((-1, 1), 2), ((0, 0), 1), ((0, 1), 2), ((1, 1), 1)]
        >>> sorted(p_2df.rolls_with_counts(0, 1)) == p_2df_rolls
        True
        >>> sorted(
        ...     p_2df.rolls_with_counts(slice(None, 1), slice(1, None))
        ... ) == p_2df_rolls
        True

    This method may yield the same roll more than once under certain conditions (e.g., non-contiguous *which* selections, where heterogeneous pools produce similar rolls for each group ordering):

        >>> sorted((3 @ P(H(2))).rolls_with_counts(0, -1))
        [((1, 1), 1), ((1, 2), 6), ((2, 2), 1)]
        >>> sorted(P(H(2), H(3)).rolls_with_counts())
        [((1, 1), 1), ((1, 2), 2), ((1, 3), 1), ((2, 2), 1), ((2, 3), 1)]

    No rolls will be produced with empty `P` objects or where *which* selects no positions.

        >>> sorted(P(6).rolls_with_counts(slice(6, 7)))
        []
        >>> sorted(P().rolls_with_counts())
        []
    """
    n = len(self)
    indices = tuple(range(n))
    selected = tuple(getitems(indices, which or indices))
    if len(selected) == 1 and len(self._h_groups) == 1:
        h, count = next(iter(self._h_groups.items()))
        with warnings.catch_warnings():
            warnings.simplefilter("ignore", ExperimentalWarning)
            order_stat_h = h.order_stat_for_n_at_pos(count, selected[0])
        yield from (
            ((outcome,), weight) for outcome, weight in order_stat_h.items()
        )
        return
    if len(selected) == 1 and len(self._h_groups) > 1 and selected[0] in (0, n - 1):
        extreme_h = self.at(-1 if selected[0] == n - 1 else 0)
        yield from (((outcome,), weight) for outcome, weight in extreme_h.items())
        return
    if 1 < len(selected) < n and (
        len(self._h_groups) == 1 or len(selected) <= n // 2
    ):
        h_groups = tuple(self._h_groups.items())
        if selected == tuple(range(len(selected))):
            yield from _rwc_heterogeneous_one_end(
                h_groups, len(selected), from_right=False
            )
            return
        if selected == tuple(range(n - len(selected), n)):
            yield from _rwc_heterogeneous_one_end(
                h_groups, len(selected), from_right=True
            )
            return
    yield from (
        self._survey_raw(_WhichRollSurveyor(self, selected)) if selected else ()
    )

sample() -> RollT[_T]

Experimental

dyce.p.P.sample is experimental; its interface may change or it may be removed in a future release.

Returns (weighted) random outcomes from contained histograms.

On ordering

This method “works” (i.e., falls back to a “natural” ordering of string representations) for outcomes whose relative values cannot be known (e.g., symbolic expressions). This is deliberate to allow random roll functionality where symbolic resolution is not needed or will happen later.

Source code in dyce/p.py
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
@experimental
def sample(self: "P[_T]") -> RollT[_T]:
    r"""
    Returns (weighted) random outcomes from contained histograms.

    !!! note "On ordering"

        This method “works” (i.e., falls back to a “natural” ordering of string representations) for outcomes whose relative values cannot be known (e.g., symbolic expressions).
        This is deliberate to allow random roll functionality where symbolic resolution is not needed or will happen later.
    """
    if not self:
        raise ValueError("no outcomes from an empty pool")
    with warnings.catch_warnings():
        warnings.simplefilter("ignore", ExperimentalWarning)
        roll = [h.sample() for h in self]
    try:
        roll.sort()  # pyright: ignore[reportCallIssue] # zuban: ignore[call-arg]
    except TypeError:
        roll.sort(key=natural_key)
    return tuple(roll)

survey(surveyor: SurveyorBase[_T, _StateT, _ResultT] | None = None, *, accumulate: Callable[[_StateT | None, _T, int], _StateT] | None = None, initial: _StateT | None = None, order: Callable[[Iterable[_T]], Iterable[_T]] | None = None, settle: Callable[[_StateT], _ResultT] | None = None) -> H[_StateT | _ResultT]

survey(surveyor: SurveyorBase[_T, _StateT, _ResultT]) -> H[_ResultT]
survey(*, accumulate: Callable[[_StateT | None, _T, int], _StateT], initial: _StateT | None = ..., order: Callable[[Iterable[_T]], Iterable[_T]], settle: None = ...) -> H[_StateT]
survey(*, accumulate: Callable[[_StateT | None, _T, int], _StateT], initial: _StateT | None = ..., order: Callable[[Iterable[_T]], Iterable[_T]], settle: Callable[[_StateT], _ResultT]) -> H[_ResultT]

Experimental

dyce.p.P.survey is experimental; its interface may change or it may be removed in a future release.

Returns a new H by folding a transition function defined by surveyor over the pool one outcome at a time.

This implements a state-collapsing dynamic algorithm similar to Albert Julius Liu’s icepool. Rather than enumerating every distinct roll, it sweeps the shared outcome axis once, and branches on how many dice show each distinct outcome. Equivalent partial rolls that reach the same state are merged, so the cost scales with the number of reachable states rather than the number of rolls.

If provided, surveyor bundles the accumulate, order, and settle methods as well as the initial property. Otherwise, each may be provided separately. accumulate and order are required. initial and settle are optional.

accumulate is called as accumulate(state, outcome, count) and returns the successor state. On the first (seed) call, state is surveyor.initial. count is the number of dice showing outcome, aggregated across all of the pool’s (possibly heterogeneous) histograms, and is always at least 1. state must be hashable, since equal states are merged. order selects the sweep order over the shared outcome set.

Only present outcomes are accumulated

accumulate is invoked only for outcomes that at least one die shows, never for absent ones. A mechanic that must reason about gaps in a sequence (e.g. the longest run of consecutive values) should therefore compare neighboring outcome values rather than expecting to be notified of the absent ones.

If provided, settle maps each terminal state to the outcome recorded in the resulting H. Otherwise, accumulate’s terminal states are themselves the outcomes.

Summing three six-sided dice, cross-checked against h (note that count scales each outcome’s contribution):

1
2
3
4
5
6
7
8
9
>>> from dyce import P
>>> from dyce.p import survey_outcome_order_ascending
>>> def running_sum(state: int | None, outcome: int, count: int) -> int:
...     return outcome * count if state is None else state + outcome * count
>>> p_3d6 = 3 @ P(6)
>>> p_3d6.survey(
...     accumulate=running_sum, order=survey_outcome_order_ascending
... ) == p_3d6.h()
True

Keeping the greatest two of four six-sided dice is order-sensitive, so it sweeps descending and uses settle to project the accumulated sum:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
>>> from dyce.p import survey_outcome_order_descending
>>> def keep_highest_two(
...     state: tuple[int, int] | None, outcome: int, count: int
... ) -> tuple[int, int]:
...     kept, total = (0, 0) if state is None else state
...     take = min(count, 2 - kept)
...     return kept + take, total + outcome * take
>>> p_4d6 = 4 @ P(6)
>>> keep = p_4d6.survey(
...     accumulate=keep_highest_two,
...     order=survey_outcome_order_descending,
...     settle=lambda s: s[1],
... )
>>> keep == p_4d6.at(slice(-2, None))
True
Source code in dyce/p.py
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
@experimental
def survey(
    self: "P[_T]",
    surveyor: SurveyorBase[_T, _StateT, _ResultT] | None = None,
    *,
    accumulate: Callable[[_StateT | None, _T, int], _StateT] | None = None,
    initial: _StateT | None = None,
    order: Callable[[Iterable[_T]], Iterable[_T]] | None = None,
    settle: Callable[[_StateT], _ResultT] | None = None,
) -> H[_StateT | _ResultT]:
    r"""
    Returns a new [`H`][dyce.H] by folding a transition function defined by *surveyor* over the pool one outcome at a time.

    This implements a state-collapsing dynamic algorithm similar to Albert Julius Liu’s [`icepool`](https://github.com/HighDiceRoller/icepool).
    Rather than enumerating every distinct roll, it sweeps the shared outcome axis once, and branches on how many dice show each distinct outcome.
    Equivalent partial rolls that reach the same state are merged, so the cost scales with the number of reachable states rather than the number of rolls.

    If provided, *surveyor* bundles the *accumulate*, *order*, and *settle* methods as well as the *initial* property.
    Otherwise, each may be provided separately.
    *accumulate* and *order* are required.
    *initial* and *settle* are optional.

    *accumulate* is called as `accumulate(state, outcome, count)` and returns the successor state.
    On the first (seed) call, *state* is `surveyor.initial`.
    *count* is the number of dice showing *outcome*, aggregated across all of the pool’s (possibly heterogeneous) histograms, and is always at least `1`.
    *state* must be hashable, since equal states are merged.
    *order* selects the sweep order over the shared outcome set.

    !!! note "Only present outcomes are accumulated"

        *accumulate* is invoked only for outcomes that at least one die shows, never for absent ones.
        A mechanic that must reason about gaps in a sequence (e.g. the longest run of consecutive values) should therefore compare neighboring *outcome* values rather than expecting to be notified of the absent ones.


    If provided, *settle* maps each terminal state to the outcome recorded in the resulting [`H`][dyce.H].
    Otherwise, *accumulate*’s terminal states are themselves the outcomes.

    Summing three six-sided dice, cross-checked against [`h`][dyce.P.h] (note that *count* scales each outcome’s contribution):

        >>> from dyce import P
        >>> from dyce.p import survey_outcome_order_ascending
        >>> def running_sum(state: int | None, outcome: int, count: int) -> int:
        ...     return outcome * count if state is None else state + outcome * count
        >>> p_3d6 = 3 @ P(6)
        >>> p_3d6.survey(
        ...     accumulate=running_sum, order=survey_outcome_order_ascending
        ... ) == p_3d6.h()
        True

    Keeping the greatest two of four six-sided dice is order-sensitive, so it sweeps descending and uses *settle* to project the accumulated sum:

        >>> from dyce.p import survey_outcome_order_descending
        >>> def keep_highest_two(
        ...     state: tuple[int, int] | None, outcome: int, count: int
        ... ) -> tuple[int, int]:
        ...     kept, total = (0, 0) if state is None else state
        ...     take = min(count, 2 - kept)
        ...     return kept + take, total + outcome * take
        >>> p_4d6 = 4 @ P(6)
        >>> keep = p_4d6.survey(
        ...     accumulate=keep_highest_two,
        ...     order=survey_outcome_order_descending,
        ...     settle=lambda s: s[1],
        ... )
        >>> keep == p_4d6.at(slice(-2, None))
        True
    """
    if surveyor is None:
        if accumulate is None or order is None:
            raise ValueError("must provide a surveyor or an accumulate and order")
        survey_raw_iter = (
            # Without the convoluted ... if settle is None else ... structure below,
            # Mypy is confused whether the return type is H[_StateT] or H[_ResultT]
            self._survey_raw(
                # settle is None, return type is H[_StateT]
                ParameterizedSurveyor(
                    accumulate,
                    order,
                    initial=initial,
                )
            )
            if settle is None
            else self._survey_raw(
                # settle is not None, return type is H[_ResultT]
                ParameterizedSurveyor(
                    accumulate,
                    order,
                    initial=initial,
                    settle=settle,
                )
            )
        )
        return aggregate_weighted(survey_raw_iter)  # zuban: ignore[no-any-return]
    else:
        if (
            accumulate is not None
            or initial is not None
            or order is not None
            or settle is not None
        ):
            raise ValueError(
                "must not provide an accumulate and order with a surveyor"
            )
        return aggregate_weighted(self._survey_raw(surveyor))

PResult

Bases: NamedTuple, Generic[_T_co]

Container passed to an expand callback when the corresponding source is a P object.

Source code in dyce/evaluation.py
59
60
61
62
63
64
65
class PResult(NamedTuple, Generic[_T_co]):
    r"""
    Container passed to an [`expand`][dyce.expand] callback when the corresponding source is a [`P`][dyce.P] object.
    """

    p: P[_T_co]
    roll: tuple[_T_co, ...]

TruncationWarning

Bases: UserWarning

Issued when results are truncated from expand for whatever reason.

Source code in dyce/evaluation.py
44
45
46
47
class TruncationWarning(UserWarning):
    r"""
    Issued when results are truncated from [`expand`][dyce.expand] for whatever reason.
    """

expand(callback: Callable[..., Any], *sources: H[Any] | P[Any], min_path_probability: Fraction | None = None, reset_path_probability: bool = False, **state: Any) -> H[Any]

expand(callback: Callable[[HResult[_T]], H[_ResultT] | _ResultT], source: H[_T], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[PResult[_T]], H[_ResultT] | _ResultT], source: P[_T], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[HResult[_T1], HResult[_T2]], H[_ResultT] | _ResultT], source1: H[_T1], source2: H[_T2], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[HResult[_T1], PResult[_T2]], H[_ResultT] | _ResultT], source1: H[_T1], source2: P[_T2], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[PResult[_T1], HResult[_T2]], H[_ResultT] | _ResultT], source1: P[_T1], source2: H[_T2], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[PResult[_T1], PResult[_T2]], H[_ResultT] | _ResultT], source1: P[_T1], source2: P[_T2], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[HResult[_T1], HResult[_T2], HResult[_T3]], H[_ResultT] | _ResultT], source1: H[_T1], source2: H[_T2], source3: H[_T3], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[HResult[_T1], HResult[_T2], PResult[_T3]], H[_ResultT] | _ResultT], source1: H[_T1], source2: H[_T2], source3: P[_T3], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[HResult[_T1], PResult[_T2], HResult[_T3]], H[_ResultT] | _ResultT], source1: H[_T1], source2: P[_T2], source3: H[_T3], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[HResult[_T1], PResult[_T2], PResult[_T3]], H[_ResultT] | _ResultT], source1: H[_T1], source2: P[_T2], source3: P[_T3], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[PResult[_T1], HResult[_T2], HResult[_T3]], H[_ResultT] | _ResultT], source1: P[_T1], source2: H[_T2], source3: H[_T3], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[PResult[_T1], HResult[_T2], PResult[_T3]], H[_ResultT] | _ResultT], source1: P[_T1], source2: H[_T2], source3: P[_T3], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[PResult[_T1], PResult[_T2], HResult[_T3]], H[_ResultT] | _ResultT], source1: P[_T1], source2: P[_T2], source3: H[_T3], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[[PResult[_T1], PResult[_T2], PResult[_T3]], H[_ResultT] | _ResultT], source1: P[_T1], source2: P[_T2], source3: P[_T3], *, min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[_ResultT]
expand(callback: Callable[..., Any], *sources: H[Any] | P[Any], min_path_probability: Fraction | None = ..., reset_path_probability: bool = ..., **state: Any) -> H[Any]

Experimental

expand is experimental; its interface may change or it may be removed in a future release.

Evaluates callback over the Cartesian product of all sources, accumulating the results into an H object.

For each combination of outcomes drawn from sources, callback is called with one positional HResult or PResult argument per H or P source, respectively, plus any provided keyword arguments. The return value controls how the branch contributes to the accumulation:

  • Scalar - The outcome is recorded directly.
  • H - The histogram is expanded in place, meaning its outcomes are merged into the accumulation with their counts scaled to preserve the correct proportions.
  • H({}) (the empty histogram) - The branch is eliminated, meaning it contributes nothing to the accumulation and is silently discarded. This is the designated mechanism for signaling that an outcome is impossible or should be excluded from the result.

This is useful for modeling mechanics where the outcome of one die affects how others are rolled. Examples include: exploding dice, conditional re-rolls, or damage that depends on whether an attack hits.

Re-roll an initial 1:

1
2
3
4
5
6
>>> from dyce import H
>>> from dyce.evaluation import HResult, expand
>>> def reroll_first_one(result: HResult[int]) -> H[int] | int:
...     return result.h if result.outcome == 1 else result.outcome
>>> expand(reroll_first_one, H(6))
H({1: 1, 2: 7, 3: 7, 4: 7, 5: 7, 6: 7})

Returning an H expands the branch in place, with counts scaled to preserve proportions relative to the whole. Substituting a d00 for a 1 on a d6:

1
2
3
4
5
6
7
8
9
>>> from fractions import Fraction
>>> d00 = (H(10) - 1) * 10
>>> set(H(6)) & set(d00)  # no outcomes in common
set()
>>> def roll_d00_on_one(result: HResult[int]) -> H[int] | int:
...     return d00 if result.outcome == 1 else result.outcome
>>> d6_d00 = expand(roll_d00_on_one, H(6))
>>> d6_d00
H({0: 1, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10, 10: 1, 20: 1, 30: 1, 40: 1, 50: 1, 60: 1, 70: 1, 80: 1, 90: 1})

The ten d00 outcomes together make up the same proportion of the total as the original 1 did in the d6:

1
2
3
4
5
6
7
>>> Fraction(
...     sum(count for outcome, count in d6_d00.items() if outcome in d00),
...     d6_d00.total,
... )
Fraction(1, 6)
>>> Fraction(H(6)[1], H(6).total)
Fraction(1, 6)

When the intent is that a whole path be eliminated (not merely approximated), returning H({}) from a recursive call propagates naturally through arithmetic (H({}) + outcome is H({})), and no special check is needed.

Re-roll all 1s:

1
2
3
4
>>> def always_reroll_on_one(result: HResult[int]) -> H[int] | int:
...     return H({}) if result.outcome == 1 else result.outcome
>>> expand(always_reroll_on_one, H(6))
H({2: 1, 3: 1, 4: 1, 5: 1, 6: 1})

Path probability and recursion limiting

The min_path_probability parameter controls when recursive expansion is truncated automatically. It represents the minimum path probability (the probability of reaching a branch) below which the callback is not invoked. Additionally, any branch that exceeds Python’s recursion limit is also truncated. In both cases, the branch is eliminated exactly as if the callback had explicitly returned H({}). A TruncationWarning is emitted when any branch is dropped this way, distinguishing resource-limit elimination from intentional callback-driven elimination.

When min_path_probability is None, nested calls inherit the enclosing call's min_path_probability. At the top level, its default value is Fraction(1, 0x7FFFFF). An explicit fraction sets min_path_probability for this call. Nested calls inherit that value unless they override it. Zero disables probability-based truncation, but path probability is still tracked.

When reset_path_probability is True, this call starts with path probability one. When reset_path_probability is True and min_path_probability is None, this call uses the default value for min_path_probability. The enclosing context is restored after the call.

Independent calls and min_path_probability overrides can increase computation

A nested call can disable probability-based truncation by setting min_path_probability to zero. Repeated calls with reset_path_probability set to True can prevent path probability from decreasing across recursion. Neither choice restores branches already discarded by an enclosing call.

The same min_path_probability can produce different recursion depths depending on the probability of the exploding face. A more probable exploding face keeps path probability at or above min_path_probability for more recursive calls:

 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
>>> from dyce import TruncationWarning
>>> import warnings
>>> def explode_on_max(result: HResult[int]) -> H[int] | int:
...     if result.outcome == max(result.h):
...         inner = expand(explode_on_max, result.h)
...         return (inner + result.outcome) if inner else result.outcome
...     return result.outcome
>>> with warnings.catch_warnings(record=True) as caught:
...     warnings.simplefilter("always", category=TruncationWarning)
...     expand(
...         explode_on_max,
...         H({1: 1, 2: 3}),
...         min_path_probability=Fraction(1, 16),
...     )
H({1: 256, 3: 192, 5: 144, 7: 108, 9: 81, 18: 243})
>>> caught and all(w.category is TruncationWarning for w in caught)
True
>>> with warnings.catch_warnings(record=True) as caught:
...     warnings.simplefilter("always", category=TruncationWarning)
...     expand(
...         explode_on_max,
...         H({1: 3, 2: 1}),
...         min_path_probability=Fraction(1, 16),
...     )
H({1: 12, 3: 3, 4: 1})
>>> caught and all(w.category is TruncationWarning for w in caught)
True

Arbitrary state threading

Any keyword arguments beyond min_path_probability and reset_path_probability are forwarded verbatim to callback as keyword-only arguments. To pass updated state into recursive calls, include it explicitly:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
>>> def explode_on_max_up_to_n_times(
...     result: HResult[int], *, n: int
... ) -> H[int] | int:
...     if n > 0 and result.outcome == max(result.h):
...         inner = expand(explode_on_max_up_to_n_times, result.h, n=n - 1)
...         if inner:
...             return inner + result.outcome
...     return result.outcome
>>> expand(
...     explode_on_max_up_to_n_times,
...     H(10),
...     n=0,  # just the first roll with zero explosions
... ) == H(10)
True
>>> expand(
...     explode_on_max_up_to_n_times,
...     H(10),
...     n=4,  # up to four explosions (five total rolls)
... )
H({1: 10000, ..., 9: 10000, 11: 1000, ..., 19: 1000, 21: 100, ..., 29: 100, 31: 10, ..., 39: 10, 41: 1, ..., 49: 1, 50: 1})

Multiple sources

When multiple sources are provided, callback receives one positional argument per source. Counting how often a d6 beats each outcome of a 2d10 pool:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> from dyce import P
>>> from dyce.evaluation import PResult
>>> p2d10 = 2 @ P(10)
>>> def times_d6_beats_two_d10s(
...     d6_result: HResult[int],
...     p2d10_result: PResult[int],
... ) -> int:
...     return sum(
...         1 for outcome in p2d10_result.roll if outcome < d6_result.outcome
...     )
>>> expand(times_d6_beats_two_d10s, H(6), p2d10)
H({0: 71, 1: 38, 2: 11})
Source code in dyce/evaluation.py
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
def expand(  # ruff: ignore[complex-structure]
    callback: Callable[..., Any],
    *sources: H[Any] | P[Any],
    min_path_probability: Fraction | None = None,
    reset_path_probability: bool = False,
    **state: Any,
) -> H[Any]:
    r"""
    !!! warning "Experimental"

        `expand` is experimental; its interface may change or it may be removed in a future release.

    Evaluates *callback* over the Cartesian product of all *sources*, accumulating the results into an [`H`][dyce.H] object.

    For each combination of outcomes drawn from *sources*, *callback* is called with one positional [`HResult`][dyce.HResult] or [`PResult`][dyce.PResult] argument per [`H`][dyce.H] or [`P`][dyce.P] source, respectively, plus any provided keyword arguments.
    The return value controls how the branch contributes to the accumulation:

    - **Scalar** - The outcome is recorded directly.
    - **[`H`][dyce.H]** - The histogram is expanded in place, meaning its outcomes are merged into the accumulation with their counts scaled to preserve the correct proportions.
    - **`H({})` (the empty histogram)** - The branch is *eliminated*, meaning it contributes nothing to the accumulation and is silently discarded.
      This is the designated mechanism for signaling that an outcome is impossible or should be excluded from the result.

    This is useful for modeling mechanics where the outcome of one die affects how others are rolled.
    Examples include: exploding dice, conditional re-rolls, or damage that depends on whether an attack hits.

    Re-roll an initial 1:

        >>> from dyce import H
        >>> from dyce.evaluation import HResult, expand
        >>> def reroll_first_one(result: HResult[int]) -> H[int] | int:
        ...     return result.h if result.outcome == 1 else result.outcome
        >>> expand(reroll_first_one, H(6))
        H({1: 1, 2: 7, 3: 7, 4: 7, 5: 7, 6: 7})

    Returning an [`H`][dyce.H] expands the branch in place, with counts scaled to preserve proportions relative to the whole.
    Substituting a d00 for a 1 on a d6:

        >>> from fractions import Fraction
        >>> d00 = (H(10) - 1) * 10
        >>> set(H(6)) & set(d00)  # no outcomes in common
        set()
        >>> def roll_d00_on_one(result: HResult[int]) -> H[int] | int:
        ...     return d00 if result.outcome == 1 else result.outcome
        >>> d6_d00 = expand(roll_d00_on_one, H(6))
        >>> d6_d00
        H({0: 1, 2: 10, 3: 10, 4: 10, 5: 10, 6: 10, 10: 1, 20: 1, 30: 1, 40: 1, 50: 1, 60: 1, 70: 1, 80: 1, 90: 1})

    The ten d00 outcomes together make up the same proportion of the total as the original 1 did in the d6:

        >>> Fraction(
        ...     sum(count for outcome, count in d6_d00.items() if outcome in d00),
        ...     d6_d00.total,
        ... )
        Fraction(1, 6)
        >>> Fraction(H(6)[1], H(6).total)
        Fraction(1, 6)

    When the intent is that a whole path be *eliminated* (not merely approximated), returning `H({})` from a recursive call propagates naturally through arithmetic (`H({}) + outcome` is `H({})`), and no special check is needed.

    Re-roll *all* 1s:

        >>> def always_reroll_on_one(result: HResult[int]) -> H[int] | int:
        ...     return H({}) if result.outcome == 1 else result.outcome
        >>> expand(always_reroll_on_one, H(6))
        H({2: 1, 3: 1, 4: 1, 5: 1, 6: 1})

    **Path probability and recursion limiting**

    The *min_path_probability* parameter controls when recursive expansion is truncated automatically.
    It represents the minimum path probability (the probability of reaching a branch) below which the callback is not invoked.
    Additionally, any branch that exceeds Python’s recursion limit is also truncated.
    In both cases, the branch is eliminated exactly as if the callback had explicitly returned `H({})`.
    A [`TruncationWarning`][dyce.TruncationWarning] is emitted when any branch is dropped this way, distinguishing resource-limit elimination from intentional callback-driven elimination.

    When *min_path_probability* is `None`, nested calls inherit the enclosing call's *min_path_probability*.
    At the top level, its default value is `Fraction(1, 0x7FFFFF)`.
    An explicit fraction sets *min_path_probability* for this call.
    Nested calls inherit that value unless they override it.
    Zero disables probability-based truncation, but path probability is still tracked.

    When *reset_path_probability* is `True`, this call starts with path probability one.
    When *reset_path_probability* is `True` and *min_path_probability* is `None`, this call uses the default value for *min_path_probability*.
    The enclosing context is restored after the call.

    !!! warning "Independent calls and min_path_probability overrides can increase computation"

        A nested call can disable probability-based truncation by setting *min_path_probability* to zero.
        Repeated calls with *reset_path_probability* set to `True` can prevent path probability from decreasing across recursion.
        Neither choice restores branches already discarded by an enclosing call.

    The same *min_path_probability* can produce different recursion depths depending on the probability of the exploding face.
    A more probable exploding face keeps path probability at or above *min_path_probability* for more recursive calls:

        >>> from dyce import TruncationWarning
        >>> import warnings
        >>> def explode_on_max(result: HResult[int]) -> H[int] | int:
        ...     if result.outcome == max(result.h):
        ...         inner = expand(explode_on_max, result.h)
        ...         return (inner + result.outcome) if inner else result.outcome
        ...     return result.outcome
        >>> with warnings.catch_warnings(record=True) as caught:
        ...     warnings.simplefilter("always", category=TruncationWarning)
        ...     expand(
        ...         explode_on_max,
        ...         H({1: 1, 2: 3}),
        ...         min_path_probability=Fraction(1, 16),
        ...     )
        H({1: 256, 3: 192, 5: 144, 7: 108, 9: 81, 18: 243})
        >>> caught and all(w.category is TruncationWarning for w in caught)
        True
        >>> with warnings.catch_warnings(record=True) as caught:
        ...     warnings.simplefilter("always", category=TruncationWarning)
        ...     expand(
        ...         explode_on_max,
        ...         H({1: 3, 2: 1}),
        ...         min_path_probability=Fraction(1, 16),
        ...     )
        H({1: 12, 3: 3, 4: 1})
        >>> caught and all(w.category is TruncationWarning for w in caught)
        True

    **Arbitrary state threading**

    Any keyword arguments beyond *min_path_probability* and *reset_path_probability* are forwarded verbatim to *callback* as keyword-only arguments.
    To pass updated state into recursive calls, include it explicitly:

        >>> def explode_on_max_up_to_n_times(
        ...     result: HResult[int], *, n: int
        ... ) -> H[int] | int:
        ...     if n > 0 and result.outcome == max(result.h):
        ...         inner = expand(explode_on_max_up_to_n_times, result.h, n=n - 1)
        ...         if inner:
        ...             return inner + result.outcome
        ...     return result.outcome
        >>> expand(
        ...     explode_on_max_up_to_n_times,
        ...     H(10),
        ...     n=0,  # just the first roll with zero explosions
        ... ) == H(10)
        True
        >>> expand(
        ...     explode_on_max_up_to_n_times,
        ...     H(10),
        ...     n=4,  # up to four explosions (five total rolls)
        ... )
        H({1: 10000, ..., 9: 10000, 11: 1000, ..., 19: 1000, 21: 100, ..., 29: 100, 31: 10, ..., 39: 10, 41: 1, ..., 49: 1, 50: 1})

    **Multiple sources**

    When multiple sources are provided, *callback* receives one positional argument per source.
    Counting how often a d6 beats each outcome of a 2d10 pool:

        >>> from dyce import P
        >>> from dyce.evaluation import PResult
        >>> p2d10 = 2 @ P(10)
        >>> def times_d6_beats_two_d10s(
        ...     d6_result: HResult[int],
        ...     p2d10_result: PResult[int],
        ... ) -> int:
        ...     return sum(
        ...         1 for outcome in p2d10_result.roll if outcome < d6_result.outcome
        ...     )
        >>> expand(times_d6_beats_two_d10s, H(6), p2d10)
        H({0: 71, 1: 38, 2: 11})
    """
    if min_path_probability is not None and not (0 <= min_path_probability <= 1):
        raise ValueError(
            f"if set, min_path_probability ({min_path_probability}) must be between zero and one, inclusive"
        )
    if not sources:
        raise ValueError("expand requires at least one source")
    try:
        cur_ctxt = _expand_ctxt.get()
    except LookupError:
        # TODO(@posita): <https://github.com/astral-sh/ty/issues/2278> - Try the
        # @experimental decorator instead once that issue is fixed
        warnings.warn(experimental_msg % "expand", ExperimentalWarning, stacklevel=2)
        # We're at the top level, so create a new context
        cur_ctxt = _ExpandContext(
            path_probability=Fraction(1),
            min_path_probability=(
                _DEFAULT_MIN_PATH_PROBABILITY
                if min_path_probability is None
                else min_path_probability
            ),
        )

    current_path_prob = (
        Fraction(1) if reset_path_probability else cur_ctxt.path_probability
    )
    effective_min_path_probability = (
        min_path_probability
        if min_path_probability is not None
        else _DEFAULT_MIN_PATH_PROBABILITY
        if reset_path_probability
        else cur_ctxt.min_path_probability
    )
    total_product = prod(s.total for s in sources)
    truncation_reasons: set[_TruncationReason] = set()

    @nobeartype  # not decoratable by beartype (avoids warning)
    def _result_counts() -> Iterator[tuple[Any, int]]:
        for result_counts in iproduct(
            *(_source_to_result_iterable(s) for s in sources)
        ):
            results, counts = zip(*result_counts, strict=True)
            combined_count = prod(counts)
            branch_path_prob = current_path_prob * Fraction(
                combined_count, total_product
            )
            if branch_path_prob < effective_min_path_probability:
                truncation_reasons.add(_TruncationReason.PROB_BDGT_EXHAUSTED)
                continue
            new_ctxt = _ExpandContext(
                path_probability=branch_path_prob,
                min_path_probability=effective_min_path_probability,
            )
            token = _expand_ctxt.set(new_ctxt)
            try:
                result = callback(*results, **state)
            except RecursionError:
                truncation_reasons.add(_TruncationReason.RCRS_LMT_EXCEEDED)
                continue
            finally:
                _expand_ctxt.reset(token)
            yield result, combined_count

    h = aggregate_weighted(_result_counts())
    if _TruncationReason.PROB_BDGT_EXHAUSTED in truncation_reasons:
        warnings.warn(
            f"expand: some branches with path probability < {effective_min_path_probability!r} "
            f"were truncated",
            TruncationWarning,
            stacklevel=2,
        )
    if _TruncationReason.RCRS_LMT_EXCEEDED in truncation_reasons:
        warnings.warn(
            f"expand: some branches whose recursion depth exceeded "
            f"{sys.getrecursionlimit()} were truncated",
            TruncationWarning,
            stacklevel=2,
        )

    if current_path_prob == Fraction(1):
        return h.lowest_terms(preserve_zero_counts=True)  # zuban: ignore[no-any-return]
    return h  # zuban: ignore[no-any-return]

explode_n(source: H[ot.CanAdd[_OtherT, _ResultT]], *, n: int = 1, min_path_probability: Fraction = Fraction(0), resolver: Callable[[HResult[_ResultT], int, int], H[_ResultT] | _ResultT] = _explode_on_max) -> H[_ResultT]

Experimental

dyce.evaluation.explode_n is experimental; its interface may change or it may be removed in a future release.

Convenience wrapper around expand for exploding dice.

The resolver callback takes an HResult for the current roll being resolved and two ints. The first int is how many explosions we have left before explode_n terminates all further exploration (i.e., our remaining depth). The second int is how many explosions we’ve performed so far (i.e., our current depth). Together, they should always sum to the value of n originally passed to explode_n. The resolver callback can return either a histogram to indicate the next die to be rolled and accumulated or a single outcome. The default resolver explodes on the maximum face.

1
2
3
4
>>> from dyce import H, HResult, explode_n
>>> d6 = H(6)
>>> explode_n(d6, n=2)
H({1: 36, 2: 36, 3: 36, 4: 36, 5: 36, 7: 6, 8: 6, 9: 6, 10: 6, 11: 6, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1})
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
>>> import sympy
>>> x = sympy.sympify("x")
>>> dx = H({x: 1})
>>> # Zero explosions is the starting roll
>>> explode_n(
...     dx,  # zuban: ignore[arg-type] # pyright: ignore[reportArgumentType]
...     n=0,
... ) == dx
True
>>> # Starting roll with up to two explosions
>>> explode_n(
...     dx,  # zuban: ignore[arg-type] # pyright: ignore[reportArgumentType]
...     n=2,
... )
H({3*x: 1})

min_path_probability is forwarded to expand and defaults to zero. A TruncationWarning is emitted when a branch's path probability falls below min_path_probability or a branch exceeds Python's recursion limit.

 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
>>> from dyce import TruncationWarning
>>> import sys, warnings
>>> from fractions import Fraction
>>> with warnings.catch_warnings(record=True) as caught:
...     warnings.simplefilter("always", TruncationWarning)
...     explode_n(
...         d6,
...         n=sys.maxsize,
...         min_path_probability=Fraction(1, 6**3),
...     )
H({1: 36, 2: 36, 3: 36, 4: 36, 5: 36, 7: 6, 8: 6, 9: 6, 10: 6, 11: 6, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1})
>>> caught and all(w.category is TruncationWarning for w in caught)
True
>>> def explode_on_even_resolver(
...     result: HResult[int], n_left: int, n_done: int
... ) -> H[int] | int:
...     return result.h if result.outcome % 2 == 0 else result.outcome
>>> with warnings.catch_warnings(record=True) as caught:
...     warnings.simplefilter("always", TruncationWarning)
...     explode_n(
...         d6,
...         n=sys.maxsize,
...         min_path_probability=Fraction(1, 6**3),
...         resolver=explode_on_even_resolver,
...     )
H({1: 36, 3: 42, 5: 49, 6: 1, 7: 21, 8: 3, 9: 18, 10: 6, 11: 13, 12: 7, 13: 6, 14: 6, 15: 3, 16: 3, 17: 1, 18: 1})
>>> caught and all(w.category is TruncationWarning for w in caught)
True
Source code in dyce/evaluation.py
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
@experimental
def explode_n(
    source: H[ot.CanAdd[_OtherT, _ResultT]],
    *,
    n: int = 1,
    min_path_probability: Fraction = Fraction(0),
    resolver: Callable[
        [HResult[_ResultT], int, int], H[_ResultT] | _ResultT
    ] = _explode_on_max,
) -> H[_ResultT]:
    r"""
    <!-- BEGIN MONKEY PATCH --
    >>> import sympy  # type: ignore[import-untyped]

       -- END MONKEY PATCH -->

    Convenience wrapper around [`expand`][dyce.expand] for exploding dice.

    The *resolver* callback takes an [`HResult`][dyce.HResult] for the current roll being resolved and two `int`s.
    The first `int` is how many explosions we have left before `explode_n` terminates all further exploration (i.e., our remaining depth).
    The second `int` is how many explosions we’ve performed so far (i.e., our current depth).
    Together, they should always sum to the value of *n* originally passed to `explode_n`.
    The *resolver* callback can return either a histogram to indicate the next die to be rolled and accumulated or a single outcome.
    The default *resolver* explodes on the maximum face.

        >>> from dyce import H, HResult, explode_n
        >>> d6 = H(6)
        >>> explode_n(d6, n=2)
        H({1: 36, 2: 36, 3: 36, 4: 36, 5: 36, 7: 6, 8: 6, 9: 6, 10: 6, 11: 6, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1})

    <!-- -->

        >>> import sympy
        >>> x = sympy.sympify("x")
        >>> dx = H({x: 1})
        >>> # Zero explosions is the starting roll
        >>> explode_n(
        ...     dx,  # zuban: ignore[arg-type] # pyright: ignore[reportArgumentType]
        ...     n=0,
        ... ) == dx
        True
        >>> # Starting roll with up to two explosions
        >>> explode_n(
        ...     dx,  # zuban: ignore[arg-type] # pyright: ignore[reportArgumentType]
        ...     n=2,
        ... )
        H({3*x: 1})

    *min_path_probability* is forwarded to [`expand`][dyce.expand] and defaults to zero.
    A [`TruncationWarning`][dyce.TruncationWarning] is emitted when a branch's path probability falls below *min_path_probability* or a branch exceeds Python's recursion limit.

        >>> from dyce import TruncationWarning
        >>> import sys, warnings
        >>> from fractions import Fraction
        >>> with warnings.catch_warnings(record=True) as caught:
        ...     warnings.simplefilter("always", TruncationWarning)
        ...     explode_n(
        ...         d6,
        ...         n=sys.maxsize,
        ...         min_path_probability=Fraction(1, 6**3),
        ...     )
        H({1: 36, 2: 36, 3: 36, 4: 36, 5: 36, 7: 6, 8: 6, 9: 6, 10: 6, 11: 6, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1})
        >>> caught and all(w.category is TruncationWarning for w in caught)
        True
        >>> def explode_on_even_resolver(
        ...     result: HResult[int], n_left: int, n_done: int
        ... ) -> H[int] | int:
        ...     return result.h if result.outcome % 2 == 0 else result.outcome
        >>> with warnings.catch_warnings(record=True) as caught:
        ...     warnings.simplefilter("always", TruncationWarning)
        ...     explode_n(
        ...         d6,
        ...         n=sys.maxsize,
        ...         min_path_probability=Fraction(1, 6**3),
        ...         resolver=explode_on_even_resolver,
        ...     )
        H({1: 36, 3: 42, 5: 49, 6: 1, 7: 21, 8: 3, 9: 18, 10: 6, 11: 13, 12: 7, 13: 6, 14: 6, 15: 3, 16: 3, 17: 1, 18: 1})
        >>> caught and all(w.category is TruncationWarning for w in caught)
        True
    """

    @nobeartype  # not decoratable by beartype (avoids warning)
    def _callback(result: HResult[_ResultT], *, n_left: int) -> H[_ResultT] | _ResultT:
        if n_left <= 0:
            return result.outcome
        next_h_or_outcome = resolver(result, n_left, n - n_left)
        if isinstance(next_h_or_outcome, H):
            inner: H[_ResultT] = expand(_callback, next_h_or_outcome, n_left=n_left - 1)
            return (
                cast("H[_ResultT]", inner + result.outcome)  # type: ignore[operator] # ty: ignore[unsupported-operator]
                if inner
                else result.outcome
            )
        return next_h_or_outcome

    return expand(
        _callback, source, n_left=n, min_path_probability=min_path_probability
    )

quantize_hs(*, bit_width: int = DEFAULT_QUANTIZATION_BIT_WIDTH, preserve_zero_counts: bool = True) -> Any

Experimental

dyce.h.quantize_hs is experimental; its interface may change or it may be removed in a future release.

Context manager to quantize H counts to a maximal bit width on construction.

If nested, the innermost context controls.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
>>> from dyce import H, quantize_hs
>>> from dyce.d import d20
>>> h20d20_full = 20 @ d20
>>> h20d20_full
H({20: 1, 21: 20, 22: 210, ..., 200: 1496580006525694242666523, ..., 398: 210, 399: 20, 400: 1})
>>> with quantize_hs(bit_width=16):
...     h20d20_16bit = 20 @ d20
>>> h20d20_16bit
H({20: 0, 21: 0, 22: 0, ..., 199: 39947, 200: 40565, 201: 41131, ..., 398: 0, 399: 0, 400: 0})
>>> with quantize_hs(bit_width=8):
...     h20d20_8bit = 20 @ d20
>>> h20d20_8bit
H({20: 0, 21: 0, 22: 0, ..., 199: 156, 200: 158, 201: 161, ..., 398: 0, 399: 0, 400: 0})
>>> with quantize_hs(bit_width=8):
...     with quantize_hs(bit_width=16):
...         assert 20 @ d20 == h20d20_16bit
...     assert 20 @ d20 == h20d20_8bit
Source code in dyce/h.py
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
@experimental
@contextmanager
# The type of the return of the undecorated function is Generator, but after the
# @contextmanager decorator is applied, it's AbstractContextManager. By refusing to
# commit, we don't confuse beartype who will otherwise complain because
# issubclass(AbstractContextManager, Generator) is False. I'm not quite sure why
# beartype is confused because
# https://github.com/python/typeshed/blob/main/stdlib/contextlib.pyi provides a hint
# that the contextmanager-wrapped function should return a Callable[_P,
# _GeneratorContextManager[_T_co]].
def quantize_hs(
    *,
    bit_width: int = DEFAULT_QUANTIZATION_BIT_WIDTH,
    preserve_zero_counts: bool = True,
) -> Any:  # ruff: ignore[any-type]
    r"""
    Context manager to quantize [`H`][dyce.H] counts to a maximal bit width on construction.

    If nested, the innermost context controls.

        >>> from dyce import H, quantize_hs
        >>> from dyce.d import d20
        >>> h20d20_full = 20 @ d20
        >>> h20d20_full
        H({20: 1, 21: 20, 22: 210, ..., 200: 1496580006525694242666523, ..., 398: 210, 399: 20, 400: 1})
        >>> with quantize_hs(bit_width=16):
        ...     h20d20_16bit = 20 @ d20
        >>> h20d20_16bit
        H({20: 0, 21: 0, 22: 0, ..., 199: 39947, 200: 40565, 201: 41131, ..., 398: 0, 399: 0, 400: 0})
        >>> with quantize_hs(bit_width=8):
        ...     h20d20_8bit = 20 @ d20
        >>> h20d20_8bit
        H({20: 0, 21: 0, 22: 0, ..., 199: 156, 200: 158, 201: 161, ..., 398: 0, 399: 0, 400: 0})
        >>> with quantize_hs(bit_width=8):
        ...     with quantize_hs(bit_width=16):
        ...         assert 20 @ d20 == h20d20_16bit
        ...     assert 20 @ d20 == h20d20_8bit
    """
    token = _quantize_ctxt.set(
        _QuantizeContext(bit_width=bit_width, preserve_zero_counts=preserve_zero_counts)
    )
    try:
        yield
    finally:
        _quantize_ctxt.reset(token)