Skip to content

dyce package reference

dyce revolves around two core primitives. H objects are histograms (outcomes or individual dice). P objects are collections of histograms (pools).

Additionally, dyce provides expand, which is useful for substitutions, explosions, and modeling arbitrarily complex computations with dependent terms. It also provides explode_n as a convenient shorthand.

H

Bases: Mapping[_T_co, int], Iterable[_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] # ty: ignore[no-matching-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 indexes 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
17
>>> 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
var |    5.83
  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
8
>>> d6.ne(d6)
H({False: 6, True: 30})
>>> print(d6.ne(d6).format(width=65))
  avg |    0.83
  std |    0.37
  var |    0.14
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
8
>>> d6.lt(d6)
H({False: 21, True: 15})
>>> print(d6.lt(d6).format(width=65))
  avg |    0.42
  std |    0.49
  var |    0.24
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
13
>>> 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
  var |    0.25
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
  76
  77
  78
  79
  80
  81
  82
  83
  84
  85
  86
  87
  88
  89
  90
  91
  92
  93
  94
  95
  96
  97
  98
  99
 100
 101
 102
 103
 104
 105
 106
 107
 108
 109
 110
 111
 112
 113
 114
 115
 116
 117
 118
 119
 120
 121
 122
 123
 124
 125
 126
 127
 128
 129
 130
 131
 132
 133
 134
 135
 136
 137
 138
 139
 140
 141
 142
 143
 144
 145
 146
 147
 148
 149
 150
 151
 152
 153
 154
 155
 156
 157
 158
 159
 160
 161
 162
 163
 164
 165
 166
 167
 168
 169
 170
 171
 172
 173
 174
 175
 176
 177
 178
 179
 180
 181
 182
 183
 184
 185
 186
 187
 188
 189
 190
 191
 192
 193
 194
 195
 196
 197
 198
 199
 200
 201
 202
 203
 204
 205
 206
 207
 208
 209
 210
 211
 212
 213
 214
 215
 216
 217
 218
 219
 220
 221
 222
 223
 224
 225
 226
 227
 228
 229
 230
 231
 232
 233
 234
 235
 236
 237
 238
 239
 240
 241
 242
 243
 244
 245
 246
 247
 248
 249
 250
 251
 252
 253
 254
 255
 256
 257
 258
 259
 260
 261
 262
 263
 264
 265
 266
 267
 268
 269
 270
 271
 272
 273
 274
 275
 276
 277
 278
 279
 280
 281
 282
 283
 284
 285
 286
 287
 288
 289
 290
 291
 292
 293
 294
 295
 296
 297
 298
 299
 300
 301
 302
 303
 304
 305
 306
 307
 308
 309
 310
 311
 312
 313
 314
 315
 316
 317
 318
 319
 320
 321
 322
 323
 324
 325
 326
 327
 328
 329
 330
 331
 332
 333
 334
 335
 336
 337
 338
 339
 340
 341
 342
 343
 344
 345
 346
 347
 348
 349
 350
 351
 352
 353
 354
 355
 356
 357
 358
 359
 360
 361
 362
 363
 364
 365
 366
 367
 368
 369
 370
 371
 372
 373
 374
 375
 376
 377
 378
 379
 380
 381
 382
 383
 384
 385
 386
 387
 388
 389
 390
 391
 392
 393
 394
 395
 396
 397
 398
 399
 400
 401
 402
 403
 404
 405
 406
 407
 408
 409
 410
 411
 412
 413
 414
 415
 416
 417
 418
 419
 420
 421
 422
 423
 424
 425
 426
 427
 428
 429
 430
 431
 432
 433
 434
 435
 436
 437
 438
 439
 440
 441
 442
 443
 444
 445
 446
 447
 448
 449
 450
 451
 452
 453
 454
 455
 456
 457
 458
 459
 460
 461
 462
 463
 464
 465
 466
 467
 468
 469
 470
 471
 472
 473
 474
 475
 476
 477
 478
 479
 480
 481
 482
 483
 484
 485
 486
 487
 488
 489
 490
 491
 492
 493
 494
 495
 496
 497
 498
 499
 500
 501
 502
 503
 504
 505
 506
 507
 508
 509
 510
 511
 512
 513
 514
 515
 516
 517
 518
 519
 520
 521
 522
 523
 524
 525
 526
 527
 528
 529
 530
 531
 532
 533
 534
 535
 536
 537
 538
 539
 540
 541
 542
 543
 544
 545
 546
 547
 548
 549
 550
 551
 552
 553
 554
 555
 556
 557
 558
 559
 560
 561
 562
 563
 564
 565
 566
 567
 568
 569
 570
 571
 572
 573
 574
 575
 576
 577
 578
 579
 580
 581
 582
 583
 584
 585
 586
 587
 588
 589
 590
 591
 592
 593
 594
 595
 596
 597
 598
 599
 600
 601
 602
 603
 604
 605
 606
 607
 608
 609
 610
 611
 612
 613
 614
 615
 616
 617
 618
 619
 620
 621
 622
 623
 624
 625
 626
 627
 628
 629
 630
 631
 632
 633
 634
 635
 636
 637
 638
 639
 640
 641
 642
 643
 644
 645
 646
 647
 648
 649
 650
 651
 652
 653
 654
 655
 656
 657
 658
 659
 660
 661
 662
 663
 664
 665
 666
 667
 668
 669
 670
 671
 672
 673
 674
 675
 676
 677
 678
 679
 680
 681
 682
 683
 684
 685
 686
 687
 688
 689
 690
 691
 692
 693
 694
 695
 696
 697
 698
 699
 700
 701
 702
 703
 704
 705
 706
 707
 708
 709
 710
 711
 712
 713
 714
 715
 716
 717
 718
 719
 720
 721
 722
 723
 724
 725
 726
 727
 728
 729
 730
 731
 732
 733
 734
 735
 736
 737
 738
 739
 740
 741
 742
 743
 744
 745
 746
 747
 748
 749
 750
 751
 752
 753
 754
 755
 756
 757
 758
 759
 760
 761
 762
 763
 764
 765
 766
 767
 768
 769
 770
 771
 772
 773
 774
 775
 776
 777
 778
 779
 780
 781
 782
 783
 784
 785
 786
 787
 788
 789
 790
 791
 792
 793
 794
 795
 796
 797
 798
 799
 800
 801
 802
 803
 804
 805
 806
 807
 808
 809
 810
 811
 812
 813
 814
 815
 816
 817
 818
 819
 820
 821
 822
 823
 824
 825
 826
 827
 828
 829
 830
 831
 832
 833
 834
 835
 836
 837
 838
 839
 840
 841
 842
 843
 844
 845
 846
 847
 848
 849
 850
 851
 852
 853
 854
 855
 856
 857
 858
 859
 860
 861
 862
 863
 864
 865
 866
 867
 868
 869
 870
 871
 872
 873
 874
 875
 876
 877
 878
 879
 880
 881
 882
 883
 884
 885
 886
 887
 888
 889
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
class H(Mapping[_T_co, int], Iterable[_T_co]):  # type: ignore[type-var]
    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.
    `#!python 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., `#!python fractions.Fraction`) could have been used, `#!python 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 `#!python int` (and ***only*** an `#!python 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] # ty: ignore[no-matching-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 indexes 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
        var |    5.83
          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 `#!python 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
          var |    0.14
        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
          var |    0.24
        False |  58.33% |############################
         True |  41.67% |####################

    Or how often at least one `#!python 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
          var |    0.25
        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 `#!python @` operator, because it behaves differently than the `d` operator in most dedicated grammars.
        More specifically, in Python, `#!python @` has a [lower precedence](https://docs.python.org/3/reference/expressions.html#operator-precedence) than `#!python .` and `#!python […]`.

            >>> 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:
        r"""Constructor."""
        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

        def _sorted_items_iter(
            items: Sequence[tuple[Any, SupportsInt]],
        ) -> Iterable[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())))  # ty: ignore[invalid-argument-type]
            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"
            )

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

    @classmethod
    def from_counts(
        cls,
        *sources: Mapping[_T, SupportsInt] | Iterable[tuple[_T, SupportsInt]],
    ) -> Self:
        r"""
        Construct a [`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
        `#!python (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})

        """
        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())  # noqa: PLW2901
            for outcome, count in source:
                c[outcome] += lossless_int(count)
        return 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, HableT):
            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"""
        More descriptive synonym for the `#!python values` mapping method.
        """
        return self._h.values()

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

    # ---- 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[_ConvolvableT]", rhs: SupportsInt
    ) -> "H[_ConvolvableT]": ...
    @overload
    def __matmul__(self: "H[_T]", rhs: Literal[1]) -> "H[_T]": ...
    def __matmul__(self: "H", rhs: SupportsInt) -> "H":
        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__(
        self: "H[ot.CanAdd[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __add__(
        self: "H[ot.CanAdd[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanAdd[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __add__(self: "H[_T]", rhs: ot.CanAdd[_T, _ResultT]) -> "H[_ResultT]": ...
    def __add__(self, rhs: object) -> "H[object]":
        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__(
        self: "H[ot.CanSub[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __sub__(
        self: "H[ot.CanSub[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanSub[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __sub__(self: "H[_T]", rhs: ot.CanSub[_T, _ResultT]) -> "H[_ResultT]": ...
    def __sub__(self, rhs: object) -> "H[object]":
        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__(
        self: "H[ot.CanMul[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __mul__(
        self: "H[ot.CanMul[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanMul[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __mul__(self: "H[_T]", rhs: ot.CanMul[_T, _ResultT]) -> "H[_ResultT]": ...
    def __mul__(self, rhs: object) -> "H[object]":
        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__(
        self: "H[ot.CanTruediv[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __truediv__(
        self: "H[ot.CanTruediv[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanTruediv[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __truediv__(
        self: "H[_T]", rhs: ot.CanTruediv[_T, _ResultT]
    ) -> "H[_ResultT]": ...
    def __truediv__(self, rhs: object) -> "H[object]":
        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__(
        self: "H[ot.CanFloordiv[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __floordiv__(
        self: "H[ot.CanFloordiv[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanFloordiv[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __floordiv__(
        self: "H[_T]", rhs: ot.CanFloordiv[_T, _ResultT]
    ) -> "H[_ResultT]": ...
    def __floordiv__(self, rhs: object) -> "H[object]":
        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__(
        self: "H[ot.CanMod[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __mod__(
        self: "H[ot.CanMod[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanMod[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __mod__(self: "H[_T]", rhs: ot.CanMod[_T, _ResultT]) -> "H[_ResultT]": ...
    def __mod__(self, rhs: object) -> "H[object]":
        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__(
        self: "H[ot.CanPow2[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __pow__(
        self: "H[ot.CanPow2[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanPow2[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __pow__(self: "H[_T]", rhs: ot.CanPow2[_T, _ResultT]) -> "H[_ResultT]": ...
    def __pow__(self, rhs: object) -> "H[object]":
        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__(
        self: "H[ot.CanLshift[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __lshift__(
        self: "H[ot.CanLshift[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanLshift[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __lshift__(self: "H[_T]", rhs: ot.CanLshift[_T, _ResultT]) -> "H[_ResultT]": ...
    def __lshift__(self, rhs: object) -> "H[object]":
        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__(
        self: "H[ot.CanRshift[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __rshift__(
        self: "H[ot.CanRshift[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanRshift[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __rshift__(self: "H[_T]", rhs: ot.CanRshift[_T, _ResultT]) -> "H[_ResultT]": ...
    def __rshift__(self, rhs: object) -> "H[object]":
        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__(
        self: "H[ot.CanAnd[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __and__(
        self: "H[ot.CanAnd[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanAnd[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __and__(self: "H[_T]", rhs: ot.CanAnd[_T, _ResultT]) -> "H[_ResultT]": ...
    def __and__(self, rhs: object) -> "H[object]":
        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__(
        self: "H[ot.CanOr[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __or__(
        self: "H[ot.CanOr[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanOr[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __or__(self: "H[_T]", rhs: ot.CanOr[_T, _ResultT]) -> "H[_ResultT]": ...
    def __or__(self, rhs: object) -> "H[object]":
        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__(
        self: "H[ot.CanXor[_OtherT, _ResultT]]", rhs: "H[_OtherT]"
    ) -> "H[_ResultT]": ...
    @overload
    def __xor__(
        self: "H[ot.CanXor[_OtherT, _ResultT]]", rhs: "HableT[_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: "HableT[ot.CanXor[_T, _ResultT]]"
    ) -> "H[_ResultT]": ...
    @overload
    def __xor__(self: "H[_T]", rhs: ot.CanXor[_T, _ResultT]) -> "H[_ResultT]": ...
    def __xor__(self, rhs: object) -> "H[object]":
        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[_ConvolvableT]", lhs: SupportsInt
    ) -> "H[_ConvolvableT]": ...
    @overload
    def __rmatmul__(self: "H[_T]", lhs: Literal[1]) -> "H[_T]": ...
    def __rmatmul__(self: "H", lhs: SupportsInt) -> "H":
        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) -> "H[object]":
        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]":
        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]":
        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]":
        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]":
        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]":
        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]":
        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]":
        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]":
        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]":
        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]":
        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]":
        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 `#!python 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)  # type: 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 `#!python 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)  # type: 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 `#!python 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 `#!python 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 `#!python 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)  # type: 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 `#!python 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)  # type: 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 `#!python 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 ---------------------------------------------------------------------

    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  # ty: ignore[invalid-assignment,no-matching-overload]
        return H(result)

    @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"""
        Return a new [`H`][dyce.H] by applying *func* to outcomes.
        If *operand* is provided, *func* should have two parameters, otherwise it should have one.

        If *operand* is an [`H`][dyce.H], take the Cartesian product of both histograms’ items: call `#!python func(h_outcome, other_outcome)` for each pair and accumulate `#!python h_count * other_count`.

        If *operand* is a scalar, call `#!python func(outcome, operand)` 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 *operand* allows examination of just the histogram.
        One way to determine Apocalypse World 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))  # noqa: SLF001
            )
        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"""
        <!-- BEGIN MONKEY PATCH --
        >>> import warnings
        >>> from dyce.lifecycle import ExperimentalWarning
        >>> warnings.filterwarnings("ignore", category=ExperimentalWarning)

           -- END MONKEY PATCH -->

        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 `#!python (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 `#!python 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.merge(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)

        <!-- BEGIN MONKEY PATCH --
        >>> warnings.resetwarnings()

           -- END MONKEY PATCH -->
        """
        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)

    def format(
        self,
        *,
        precision: int = 2,
        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 `#!python 2`.
        *tick* is used as the bar character and defaults to `#!python "#"`.
        *width* must be positive and is the maximum width of the horizontal bar ASCII graph.

            >>> print(
            ...     (2 @ H(6))
            ...     .zero_fill(range(1, 21))
            ...     .format(precision=4, tick="@", width=65)
            ... )
            avg |    7.0000
            std |    2.4152
            var |    5.8333
              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 `#!python 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
            var |    0.00
              1 | 100.00% |##################################################
            >>> print(h_ge.format(scaled=False, width=65))
              avg |    0.58
              std |    0.49
              var |    0.24
            False |  41.67% |####################
             True |  58.33% |############################
            >>> print(h_ge.format(scaled=True, width=65))
              avg |    0.58
              std |    0.49
              var |    0.24
            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]
            var: float | None = self.variance()  # type: ignore[misc] # ty: ignore[invalid-argument-type]
        except Exception as exc:  # noqa: BLE001
            # 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
            var = None

        def _lines() -> Iterable[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 var is not None:
                yield f"{'var': >{max_outcome_len}} | {var:{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,
        *,
        precision: int = 2,
    ) -> 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(precision=3))  # decimal places
            {avg: 3.500, 1: 16.667%, 2: 16.667%, 3: 16.667%, 4: 16.667%, 5: 16.667%, 6: 16.667%}
        """
        prob_width = 5 + precision
        try:
            mu: float | None = self.mean()  # type: ignore[misc] # ty: ignore[invalid-argument-type]
        except Exception as exc:  # noqa: BLE001
            # See format() for rationale
            warnings.warn(f"{exc!s}", stacklevel=2)
            mu = None

        def _parts() -> Iterable[str]:
            if mu is not None:
                yield f"avg: {mu:.2f}"
            yield from (
                f"{outcome}:{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"""
        Return 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 `#!python 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 cast("H[_T]", 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"""
        Return the mean (expected value) of the weighted outcomes.
        Raises `#!python 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")
        return float(
            sum(outcome * count for outcome, count in self.items()) / self.total  # type: ignore[misc,operator]  # ty: ignore[unsupported-operator]
        )

    @experimental
    def order_stat_for_n_at_pos(
        self: "H[_T]",
        n: SupportsInt,
        pos: SupportsInt,
    ) -> "H[_T]":
        r"""
        <!-- BEGIN MONKEY PATCH --
        >>> import warnings
        >>> from dyce.lifecycle import ExperimentalWarning
        >>> warnings.filterwarnings("ignore", category=ExperimentalWarning)

           -- END MONKEY PATCH -->

        Computes the probability distribution for each outcome appearing at *pos* among *n* like histograms sorted least-to-greatest.
        *pos* is a zero-based index.

            >>> 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 `#!python 2` appears at the fourth (index `#!python 3`) position, 1,432 ways where `#!python 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.

        <!-- BEGIN MONKEY PATCH --
        >>> warnings.resetwarnings()

           -- END MONKEY PATCH -->
        """
        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 = None
    ) -> Iterable[tuple[_T, Fraction]]: ...
    @overload
    def probability_items(
        self: "H[_T]", rational_t: Callable[[int, int], _OtherT]
    ) -> Iterable[tuple[_T, _OtherT]]: ...
    def probability_items(
        self: "H[_T]", rational_t: Callable[[int, int], _OtherT] | None = None
    ) -> Iterable[tuple[_T, _OtherT]]:
        r"""
        Yield `#!python (outcome, probability)` pairs where each probability is computed as `#!python rational_t(count, total)`.

        *rational_t* defaults to `#!python fractions.Fraction`, giving exact rational probabilities.
        Pass any two-argument callable to get a different representation (e.g. `#!python float` division via `#!python 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 replace(self: "H[_T]", existing_outcome: _T, repl: "H[_T] | _T") -> "H[_T]":
        r"""
        <!-- BEGIN MONKEY PATCH --
        >>> import warnings
        >>> from dyce.lifecycle import ExperimentalWarning
        >>> warnings.filterwarnings("ignore", category=ExperimentalWarning)

           -- END MONKEY PATCH -->

        Returns a new histogram with a possibly substituted outcome.
        If *repl* is a single outcome, it will replace *existing_outcome* directly (if *existing_outcome* exists in the original histogram).
        If *repl* is a histogram, its outcomes will be “folded in”, together making up the same proportion of the total as the replaced outcome.

            >>> d6 = H(6)
            >>> d6.replace(6, 1_000)
            H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 1000: 1})
            >>> d6.replace(7, "never used") == d6  # type: ignore[arg-type]
            True

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

            >>> once_exploded_d6 = d6.replace(6, d6 + 6)
            >>> once_exploded_d6
            H({1: 6, 2: 6, 3: 6, 4: 6, 5: 6, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1})

        One way to “explode” a die `#!math n` times:

            >>> def explode_n_by_replacement(h: H[int], n: int) -> H[int]:
            ...     max_h = max(h)
            ...     exploded_h = h
            ...     for _ in range(n):
            ...         exploded_h = h.replace(max_h, exploded_h + max_h)
            ...     return exploded_h  # ty: ignore[invalid-return-type]

            >>> explode_n_by_replacement(d6, 0) == d6
            True
            >>> explode_n_by_replacement(d6, 1) == once_exploded_d6
            True
            >>> explode_n_by_replacement(d6, 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})
            >>> explode_n_by_replacement(d6, 15)
            H({1: 470184984576, 2: 470184984576, 3: 470184984576, ..., 94: 1, 95: 1, 96: 1})

        <!-- BEGIN MONKEY PATCH --
        >>> warnings.resetwarnings()

           -- END MONKEY PATCH -->
        """
        if existing_outcome not in self:
            return self
        existing_outcome_count = self[existing_outcome]
        d: dict[_T, int]
        if isinstance(repl, H):
            repl_total = repl.total
            d = {
                outcome: count * repl_total
                for outcome, count in self.items()
                if outcome != existing_outcome
            }
            for repl_outcome, repl_count in repl.items():
                d[repl_outcome] = (  # ty: ignore[invalid-assignment]
                    d.get(repl_outcome, 0)  # ty: ignore[no-matching-overload]
                    + repl_count * existing_outcome_count
                )
        else:
            d = {
                outcome: count
                for outcome, count in self.items()
                if outcome != existing_outcome
            }
            d[repl] = d.get(repl, 0) + existing_outcome_count
        return H(d)

    def roll(self: "H[_T]") -> _T:
        r"""
        Returns a (weighted) random outcome.

        <!-- BEGIN MONKEY PATCH --
        For deterministic outcomes.

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

          -- END MONKEY PATCH -->

            >>> d6 = H(6)
            >>> [d6.roll() for _ in range(10)]
            [2, 6, 1, 2, 4, 5, 1, 4, 2, 5]
        """
        if not self:
            raise ValueError("no outcomes from which to select in empty histogram")
        return rng.RNG.choices(
            population=tuple(self.outcomes()),
            weights=tuple(self.counts()),
            k=1,
        )[0]

    def stdev(self: "H[SupportsFloat]") -> float:
        r"""
        Return the standard deviation of the weighted outcomes as a `#!python float`.
        Raises `#!python 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"""
        Return the variance of the weighted outcomes as a `#!python float`.
        Raises `#!python 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()
            )
            - self.mean() ** 2
        )

    def zero_fill(self: "H[_T]", outcomes: Iterable[_T]) -> "H[_T]":
        r"""
        Shorthand for `#!python self.merge(dict.fromkeys(outcomes, 0))`.

            >>> H(4).zero_fill(H(8).outcomes())
            H({1: 1, 2: 1, 3: 1, 4: 1, 5: 0, 6: 0, 7: 0, 8: 0})
        """
        return self.merge(dict.fromkeys(outcomes, 0))

    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 op 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:
                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:
                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(
                    {
                        outcome: (
                            sum(
                                math.comb(n, k) * c_lt**k * (total - c_lt) ** (n - k)
                                for k in k_range
                            )
                            - sum(
                                math.comb(n, k) * c_le**k * (total - c_le) ** (n - k)
                                for k in k_range
                            )
                        )
                        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

Constructor.

Source code in dyce/h.py
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
def __init__(self, init_val: Any, /) -> None:
    r"""Constructor."""
    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

    def _sorted_items_iter(
        items: Sequence[tuple[Any, SupportsInt]],
    ) -> Iterable[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())))  # ty: ignore[invalid-argument-type]
        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"
        )

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]

Return a new H by applying func to outcomes. If operand is provided, func should have two parameters, otherwise it should have one.

If operand 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 operand is a scalar, call func(outcome, operand) 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 operand allows examination of just the histogram. One way to determine Apocalypse World 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
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
def apply(
    self: "H[_T]",
    func: Callable[[_T], _ResultT] | Callable[[_T, _OtherT], _ResultT],
    other: "H[_OtherT] | _OtherT | SentinelT" = Sentinel,
) -> "H[_ResultT]":
    r"""
    Return a new [`H`][dyce.H] by applying *func* to outcomes.
    If *operand* is provided, *func* should have two parameters, otherwise it should have one.

    If *operand* is an [`H`][dyce.H], take the Cartesian product of both histograms’ items: call `#!python func(h_outcome, other_outcome)` for each pair and accumulate `#!python h_count * other_count`.

    If *operand* is a scalar, call `#!python func(outcome, operand)` 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 *operand* allows examination of just the histogram.
    One way to determine Apocalypse World 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))  # noqa: SLF001
        )
    else:
        return H(
            cast(
                "dict[_ResultT, int]", _h_binary_callable(self._h, {other: 1}, func)
            )
        )

counts() -> ValuesView[int]

More descriptive synonym for the values mapping method.

Source code in dyce/h.py
419
420
421
422
423
def counts(self) -> ValuesView[int]:
    r"""
    More descriptive synonym for the `#!python 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
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
def eq(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `#!python 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.merge(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
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
@experimental
def exactly_k_times_in_n(
    self: "H[_T]",
    outcome: _T,
    n: SupportsInt,
    k: SupportsInt,
) -> int:
    r"""
    <!-- BEGIN MONKEY PATCH --
    >>> import warnings
    >>> from dyce.lifecycle import ExperimentalWarning
    >>> warnings.filterwarnings("ignore", category=ExperimentalWarning)

       -- END MONKEY PATCH -->

    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 `#!python (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 `#!python 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.merge(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)

    <!-- BEGIN MONKEY PATCH --
    >>> warnings.resetwarnings()

       -- END MONKEY PATCH -->
    """
    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)

format(*, precision: int = 2, 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
>>> print(
...     (2 @ H(6))
...     .zero_fill(range(1, 21))
...     .format(precision=4, tick="@", width=65)
... )
avg |    7.0000
std |    2.4152
var |    5.8333
  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
18
19
20
>>> 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
var |    0.00
  1 | 100.00% |##################################################
>>> print(h_ge.format(scaled=False, width=65))
  avg |    0.58
  std |    0.49
  var |    0.24
False |  41.67% |####################
 True |  58.33% |############################
>>> print(h_ge.format(scaled=True, width=65))
  avg |    0.58
  std |    0.49
  var |    0.24
False |  41.67% |##################################
 True |  58.33% |################################################
Source code in dyce/h.py
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
def format(
    self,
    *,
    precision: int = 2,
    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 `#!python 2`.
    *tick* is used as the bar character and defaults to `#!python "#"`.
    *width* must be positive and is the maximum width of the horizontal bar ASCII graph.

        >>> print(
        ...     (2 @ H(6))
        ...     .zero_fill(range(1, 21))
        ...     .format(precision=4, tick="@", width=65)
        ... )
        avg |    7.0000
        std |    2.4152
        var |    5.8333
          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 `#!python 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
        var |    0.00
          1 | 100.00% |##################################################
        >>> print(h_ge.format(scaled=False, width=65))
          avg |    0.58
          std |    0.49
          var |    0.24
        False |  41.67% |####################
         True |  58.33% |############################
        >>> print(h_ge.format(scaled=True, width=65))
          avg |    0.58
          std |    0.49
          var |    0.24
        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]
        var: float | None = self.variance()  # type: ignore[misc] # ty: ignore[invalid-argument-type]
    except Exception as exc:  # noqa: BLE001
        # 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
        var = None

    def _lines() -> Iterable[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 var is not None:
            yield f"{'var': >{max_outcome_len}} | {var:{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(*, precision: int = 2) -> str

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

1
2
3
4
>>> 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(precision=3))  # decimal places
{avg: 3.500, 1: 16.667%, 2: 16.667%, 3: 16.667%, 4: 16.667%, 5: 16.667%, 6: 16.667%}
Source code in dyce/h.py
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
def format_short(
    self,
    *,
    precision: int = 2,
) -> 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(precision=3))  # decimal places
        {avg: 3.500, 1: 16.667%, 2: 16.667%, 3: 16.667%, 4: 16.667%, 5: 16.667%, 6: 16.667%}
    """
    prob_width = 5 + precision
    try:
        mu: float | None = self.mean()  # type: ignore[misc] # ty: ignore[invalid-argument-type]
    except Exception as exc:  # noqa: BLE001
        # See format() for rationale
        warnings.warn(f"{exc!s}", stacklevel=2)
        mu = None

    def _parts() -> Iterable[str]:
        if mu is not None:
            yield f"avg: {mu:.2f}"
        yield from (
            f"{outcome}:{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]]) -> Self classmethod

Construct a 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})
Source code in dyce/h.py
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
@classmethod
def from_counts(
    cls,
    *sources: Mapping[_T, SupportsInt] | Iterable[tuple[_T, SupportsInt]],
) -> Self:
    r"""
    Construct a [`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
    `#!python (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})

    """
    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())  # noqa: PLW2901
        for outcome, count in source:
            c[outcome] += lossless_int(count)
    return 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
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
def ge(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `#!python 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)  # type: 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
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
def gt(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `#!python 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)  # type: ignore[arg-type]

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
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
def le(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `#!python 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)  # type: ignore[arg-type]

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

Return 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
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
def lowest_terms(self: "H[_T]", *, preserve_zero_counts: bool = False) -> "H[_T]":
    r"""
    Return 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 `#!python 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 cast("H[_T]", 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
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
def lt(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `#!python 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)  # type: ignore[arg-type]

mean() -> float

Return 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
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
def mean(self: "H[SupportsFloat]") -> float:
    r"""
    Return the mean (expected value) of the weighted outcomes.
    Raises `#!python 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")
    return float(
        sum(outcome * count for outcome, count in self.items()) / self.total  # type: ignore[misc,operator]  # ty: ignore[unsupported-operator]
    )

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
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
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  # ty: ignore[invalid-assignment,no-matching-overload]
    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
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
def ne(self, rhs: "H[object] | object") -> "H[bool]":
    r"""
    Shorthand for `#!python 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.

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
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
@experimental
def order_stat_for_n_at_pos(
    self: "H[_T]",
    n: SupportsInt,
    pos: SupportsInt,
) -> "H[_T]":
    r"""
    <!-- BEGIN MONKEY PATCH --
    >>> import warnings
    >>> from dyce.lifecycle import ExperimentalWarning
    >>> warnings.filterwarnings("ignore", category=ExperimentalWarning)

       -- END MONKEY PATCH -->

    Computes the probability distribution for each outcome appearing at *pos* among *n* like histograms sorted least-to-greatest.
    *pos* is a zero-based index.

        >>> 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 `#!python 2` appears at the fourth (index `#!python 3`) position, 1,432 ways where `#!python 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.

    <!-- BEGIN MONKEY PATCH --
    >>> warnings.resetwarnings()

       -- END MONKEY PATCH -->
    """
    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]

More descriptive synonym for the keys mapping method.

Source code in dyce/h.py
425
426
427
428
429
def outcomes(self: "H[_T]") -> KeysView[_T]:
    r"""
    More descriptive synonym for the `#!python keys` mapping method.
    """
    return self._h.keys()

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

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

Yield (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
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
def probability_items(
    self: "H[_T]", rational_t: Callable[[int, int], _OtherT] | None = None
) -> Iterable[tuple[_T, _OtherT]]:
    r"""
    Yield `#!python (outcome, probability)` pairs where each probability is computed as `#!python rational_t(count, total)`.

    *rational_t* defaults to `#!python fractions.Fraction`, giving exact rational probabilities.
    Pass any two-argument callable to get a different representation (e.g. `#!python float` division via `#!python 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)

replace(existing_outcome: _T, repl: H[_T] | _T) -> H[_T]

Experimental

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

Returns a new histogram with a possibly substituted outcome. If repl is a single outcome, it will replace existing_outcome directly (if existing_outcome exists in the original histogram). If repl is a histogram, its outcomes will be “folded in”, together making up the same proportion of the total as the replaced outcome.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
>>> d6 = H(6)
>>> d6.replace(6, 1_000)
H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 1000: 1})
>>> d6.replace(7, "never used") == d6  # type: ignore[arg-type]
True

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

>>> once_exploded_d6 = d6.replace(6, d6 + 6)
>>> once_exploded_d6
H({1: 6, 2: 6, 3: 6, 4: 6, 5: 6, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1})

One way to “explode” a die \(n\) times:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
>>> def explode_n_by_replacement(h: H[int], n: int) -> H[int]:
...     max_h = max(h)
...     exploded_h = h
...     for _ in range(n):
...         exploded_h = h.replace(max_h, exploded_h + max_h)
...     return exploded_h  # ty: ignore[invalid-return-type]

>>> explode_n_by_replacement(d6, 0) == d6
True
>>> explode_n_by_replacement(d6, 1) == once_exploded_d6
True
>>> explode_n_by_replacement(d6, 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})
>>> explode_n_by_replacement(d6, 15)
H({1: 470184984576, 2: 470184984576, 3: 470184984576, ..., 94: 1, 95: 1, 96: 1})
Source code in dyce/h.py
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
@experimental
def replace(self: "H[_T]", existing_outcome: _T, repl: "H[_T] | _T") -> "H[_T]":
    r"""
    <!-- BEGIN MONKEY PATCH --
    >>> import warnings
    >>> from dyce.lifecycle import ExperimentalWarning
    >>> warnings.filterwarnings("ignore", category=ExperimentalWarning)

       -- END MONKEY PATCH -->

    Returns a new histogram with a possibly substituted outcome.
    If *repl* is a single outcome, it will replace *existing_outcome* directly (if *existing_outcome* exists in the original histogram).
    If *repl* is a histogram, its outcomes will be “folded in”, together making up the same proportion of the total as the replaced outcome.

        >>> d6 = H(6)
        >>> d6.replace(6, 1_000)
        H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 1000: 1})
        >>> d6.replace(7, "never used") == d6  # type: ignore[arg-type]
        True

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

        >>> once_exploded_d6 = d6.replace(6, d6 + 6)
        >>> once_exploded_d6
        H({1: 6, 2: 6, 3: 6, 4: 6, 5: 6, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1})

    One way to “explode” a die `#!math n` times:

        >>> def explode_n_by_replacement(h: H[int], n: int) -> H[int]:
        ...     max_h = max(h)
        ...     exploded_h = h
        ...     for _ in range(n):
        ...         exploded_h = h.replace(max_h, exploded_h + max_h)
        ...     return exploded_h  # ty: ignore[invalid-return-type]

        >>> explode_n_by_replacement(d6, 0) == d6
        True
        >>> explode_n_by_replacement(d6, 1) == once_exploded_d6
        True
        >>> explode_n_by_replacement(d6, 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})
        >>> explode_n_by_replacement(d6, 15)
        H({1: 470184984576, 2: 470184984576, 3: 470184984576, ..., 94: 1, 95: 1, 96: 1})

    <!-- BEGIN MONKEY PATCH --
    >>> warnings.resetwarnings()

       -- END MONKEY PATCH -->
    """
    if existing_outcome not in self:
        return self
    existing_outcome_count = self[existing_outcome]
    d: dict[_T, int]
    if isinstance(repl, H):
        repl_total = repl.total
        d = {
            outcome: count * repl_total
            for outcome, count in self.items()
            if outcome != existing_outcome
        }
        for repl_outcome, repl_count in repl.items():
            d[repl_outcome] = (  # ty: ignore[invalid-assignment]
                d.get(repl_outcome, 0)  # ty: ignore[no-matching-overload]
                + repl_count * existing_outcome_count
            )
    else:
        d = {
            outcome: count
            for outcome, count in self.items()
            if outcome != existing_outcome
        }
        d[repl] = d.get(repl, 0) + existing_outcome_count
    return H(d)

roll() -> _T

Returns a (weighted) random outcome.

1
2
3
>>> d6 = H(6)
>>> [d6.roll() for _ in range(10)]
[2, 6, 1, 2, 4, 5, 1, 4, 2, 5]
Source code in dyce/h.py
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
def roll(self: "H[_T]") -> _T:
    r"""
    Returns a (weighted) random outcome.

    <!-- BEGIN MONKEY PATCH --
    For deterministic outcomes.

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

      -- END MONKEY PATCH -->

        >>> d6 = H(6)
        >>> [d6.roll() for _ in range(10)]
        [2, 6, 1, 2, 4, 5, 1, 4, 2, 5]
    """
    if not self:
        raise ValueError("no outcomes from which to select in empty histogram")
    return rng.RNG.choices(
        population=tuple(self.outcomes()),
        weights=tuple(self.counts()),
        k=1,
    )[0]

stdev() -> float

Return 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
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
def stdev(self: "H[SupportsFloat]") -> float:
    r"""
    Return the standard deviation of the weighted outcomes as a `#!python float`.
    Raises `#!python 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

Return 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
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
def variance(self: "H[SupportsFloat]") -> float:
    r"""
    Return the variance of the weighted outcomes as a `#!python float`.
    Raises `#!python 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()
        )
        - self.mean() ** 2
    )

zero_fill(outcomes: Iterable[_T]) -> H[_T]

Shorthand for self.merge(dict.fromkeys(outcomes, 0)).

1
2
>>> H(4).zero_fill(H(8).outcomes())
H({1: 1, 2: 1, 3: 1, 4: 1, 5: 0, 6: 0, 7: 0, 8: 0})
Source code in dyce/h.py
1748
1749
1750
1751
1752
1753
1754
1755
def zero_fill(self: "H[_T]", outcomes: Iterable[_T]) -> "H[_T]":
    r"""
    Shorthand for `#!python self.merge(dict.fromkeys(outcomes, 0))`.

        >>> H(4).zero_fill(H(8).outcomes())
        H({1: 1, 2: 1, 3: 1, 4: 1, 5: 0, 6: 0, 7: 0, 8: 0})
    """
    return self.merge(dict.fromkeys(outcomes, 0))

HResult

Bases: NamedTuple, Generic[_T]

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

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

    h: H[_T]
    outcome: _T

HableOpsMixin

Bases: HableT[_T_co]

An abstract mixin that provides all H math operators for types implementing the HableT protocol. Each operator delegates to the H object returned by h().

This class also inherits from HableT. Subclasses are required to define h().

Source code in dyce/hable.py
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
class HableOpsMixin(HableT[_T_co]):
    r"""
    An abstract mixin that provides all [`H`][dyce.H] math operators for types implementing the [`HableT`][dyce.HableT] protocol.
    Each operator delegates to the [`H`][dyce.H] object returned by [`h()`][dyce.HableT.h].

    This class also inherits from [`HableT`][dyce.HableT].
    Subclasses are required to define [`h()`][dyce.HableT.h].
    """

    __slots__ = ()

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

    @overload
    def __add__(
        self: "HableOpsMixin[optype.CanAdd[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __add__(
        self: "HableOpsMixin[_T]", rhs: optype.CanAdd[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __add__(self, rhs: object) -> H[object]:
        return self.h().__add__(_flatten_to_h(rhs))  # type: ignore[operator]

    @overload
    def __sub__(
        self: "HableOpsMixin[optype.CanSub[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __sub__(
        self: "HableOpsMixin[_T]", rhs: optype.CanSub[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __sub__(self, rhs: object) -> H[object]:
        return self.h().__sub__(_flatten_to_h(rhs))  # type: ignore[operator]

    @overload
    def __mul__(
        self: "HableOpsMixin[optype.CanMul[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __mul__(
        self: "HableOpsMixin[_T]", rhs: optype.CanMul[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __mul__(self, rhs: object) -> H[object]:
        return self.h().__mul__(_flatten_to_h(rhs))  # type: ignore[operator]

    @overload
    def __truediv__(
        self: "HableOpsMixin[optype.CanTruediv[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __truediv__(
        self: "HableOpsMixin[_T]", rhs: optype.CanTruediv[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __truediv__(self, rhs: object) -> H[object]:
        return self.h().__truediv__(_flatten_to_h(rhs))  # type: ignore[operator]

    @overload
    def __floordiv__(
        self: "HableOpsMixin[optype.CanFloordiv[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __floordiv__(
        self: "HableOpsMixin[_T]", rhs: optype.CanFloordiv[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __floordiv__(self, rhs: object) -> H[object]:
        return self.h().__floordiv__(_flatten_to_h(rhs))  # type: ignore[operator]

    @overload
    def __mod__(
        self: "HableOpsMixin[optype.CanMod[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __mod__(
        self: "HableOpsMixin[_T]", rhs: optype.CanMod[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __mod__(self, rhs: object) -> H[object]:
        return self.h().__mod__(_flatten_to_h(rhs))  # type: ignore[operator]

    @overload
    def __pow__(
        self: "HableOpsMixin[optype.CanPow2[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __pow__(
        self: "HableOpsMixin[_T]", rhs: optype.CanPow2[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __pow__(self, rhs: object) -> H[object]:
        return self.h().__pow__(_flatten_to_h(rhs))  # type: ignore[operator]

    @overload
    def __lshift__(
        self: "HableOpsMixin[optype.CanLshift[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __lshift__(
        self: "HableOpsMixin[_T]", rhs: optype.CanLshift[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __lshift__(self, rhs: object) -> H[object]:
        return self.h().__lshift__(_flatten_to_h(rhs))  # type: ignore[operator]

    @overload
    def __rshift__(
        self: "HableOpsMixin[optype.CanRshift[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rshift__(
        self: "HableOpsMixin[_T]", rhs: optype.CanRshift[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rshift__(self, rhs: object) -> H[object]:
        return self.h().__rshift__(_flatten_to_h(rhs))  # type: ignore[operator]

    @overload
    def __and__(
        self: "HableOpsMixin[optype.CanAnd[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __and__(
        self: "HableOpsMixin[_T]", rhs: optype.CanAnd[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __and__(self, rhs: object) -> H[object]:
        return self.h().__and__(_flatten_to_h(rhs))  # type: ignore[operator]

    @overload
    def __or__(
        self: "HableOpsMixin[optype.CanOr[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __or__(
        self: "HableOpsMixin[_T]", rhs: optype.CanOr[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __or__(self, rhs: object) -> H[object]:
        return self.h().__or__(_flatten_to_h(rhs))  # type: ignore[operator]

    @overload
    def __xor__(
        self: "HableOpsMixin[optype.CanXor[_OtherT, _ResultT]]", rhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __xor__(
        self: "HableOpsMixin[_T]", rhs: optype.CanXor[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __xor__(self, rhs: object) -> H[object]:
        return self.h().__xor__(_flatten_to_h(rhs))  # type: ignore[operator]

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

    @overload
    def __radd__(
        self: "HableOpsMixin[optype.CanRAdd[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __radd__(
        self: "HableOpsMixin[_T]", lhs: optype.CanRAdd[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __radd__(self, lhs: object) -> H[object]:
        return self.h().__radd__(lhs)  # type: ignore[operator]

    @overload
    def __rsub__(
        self: "HableOpsMixin[optype.CanRSub[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rsub__(
        self: "HableOpsMixin[_T]", lhs: optype.CanRSub[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rsub__(self, lhs: object) -> H[object]:
        return self.h().__rsub__(lhs)  # type: ignore[operator]

    @overload
    def __rmul__(
        self: "HableOpsMixin[optype.CanRMul[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rmul__(
        self: "HableOpsMixin[_T]", lhs: optype.CanRMul[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rmul__(self, lhs: object) -> H[object]:
        return self.h().__rmul__(lhs)  # type: ignore[operator]

    @overload
    def __rtruediv__(
        self: "HableOpsMixin[optype.CanRTruediv[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rtruediv__(
        self: "HableOpsMixin[_T]", lhs: optype.CanRTruediv[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rtruediv__(self, lhs: object) -> H[object]:
        return self.h().__rtruediv__(lhs)  # type: ignore[operator]

    @overload
    def __rfloordiv__(
        self: "HableOpsMixin[optype.CanRFloordiv[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rfloordiv__(
        self: "HableOpsMixin[_T]", lhs: optype.CanRFloordiv[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rfloordiv__(self, lhs: object) -> H[object]:
        return self.h().__rfloordiv__(lhs)  # type: ignore[operator]

    @overload
    def __rmod__(
        self: "HableOpsMixin[optype.CanRMod[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rmod__(
        self: "HableOpsMixin[_T]", lhs: optype.CanRMod[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rmod__(self, lhs: object) -> H[object]:
        return self.h().__rmod__(lhs)  # type: ignore[operator]

    @overload
    def __rpow__(
        self: "HableOpsMixin[optype.CanRPow[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rpow__(
        self: "HableOpsMixin[_T]", lhs: optype.CanRPow[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rpow__(self, lhs: object) -> H[object]:
        return self.h().__rpow__(lhs)  # type: ignore[operator]

    @overload
    def __rlshift__(
        self: "HableOpsMixin[optype.CanRLshift[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rlshift__(
        self: "HableOpsMixin[_T]", lhs: optype.CanRLshift[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rlshift__(self, lhs: object) -> H[object]:
        return self.h().__rlshift__(lhs)  # type: ignore[operator]

    @overload
    def __rrshift__(
        self: "HableOpsMixin[optype.CanRRshift[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rrshift__(
        self: "HableOpsMixin[_T]", lhs: optype.CanRRshift[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rrshift__(self, lhs: object) -> H[object]:
        return self.h().__rrshift__(lhs)  # type: ignore[operator]

    @overload
    def __rand__(
        self: "HableOpsMixin[optype.CanRAnd[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rand__(
        self: "HableOpsMixin[_T]", lhs: optype.CanRAnd[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rand__(self, lhs: object) -> H[object]:
        return self.h().__rand__(lhs)  # type: ignore[operator]

    @overload
    def __ror__(
        self: "HableOpsMixin[optype.CanROr[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __ror__(
        self: "HableOpsMixin[_T]", lhs: optype.CanROr[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __ror__(self, lhs: object) -> H[object]:
        return self.h().__ror__(lhs)  # type: ignore[operator]

    @overload
    def __rxor__(
        self: "HableOpsMixin[optype.CanRXor[_OtherT, _ResultT]]", lhs: _OtherT
    ) -> H[_ResultT]: ...
    @overload
    def __rxor__(
        self: "HableOpsMixin[_T]", lhs: optype.CanRXor[_T, _ResultT]
    ) -> H[_ResultT]: ...
    def __rxor__(self, lhs: object) -> H[object]:
        return self.h().__rxor__(lhs)  # type: ignore[operator]

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

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

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

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

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

HableT

Bases: Protocol[_T_co]

A protocol whose implementer can be expressed as (or reduced to) an H object by calling its h method. Currently, no class implements this protocol, but this affords an integration point for.

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
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
@nobeartype  # not decoratable by beartype (avoids warning)
@runtime_checkable
class HableT(Protocol[_T_co]):
    r"""
    A protocol whose implementer can be expressed as (or reduced to) an [`H` object][dyce.H] by calling its [`h` method][dyce.HableT.h].
    Currently, no class implements this protocol, but this affords an integration point for.

    !!! 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"""Express its implementer as an [`H` object][dyce.H]."""

h() -> H[_T] abstractmethod

Express its implementer as an H object.

Source code in dyce/h.py
1867
1868
1869
@abstractmethod
def h(self: "HableT[_T]") -> H[_T]:
    r"""Express 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 implements the HableT protocol and derives from the HableOpsMixin class, 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
>>> P(4, 6).apply_to_each_h(
...     lambda h_outcome, other_outcome: operator.pow(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
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
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 implements the [`HableT` protocol][dyce.HableT] and derives from the [`HableOpsMixin` class][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(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__ = (
        "_hash",
        "_hs",
        "_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"""Constructor."""
        super().__init__()

        def _hs_from_init_vals() -> Iterable[H[_T_co]]:
            for init_val in init_vals:
                if isinstance(init_val, H):
                    yield init_val
                elif isinstance(init_val, P):
                    yield from init_val._hs  # noqa: SLF001
                else:
                    yield H(init_val)

        hs = [h for h in _hs_from_init_vals() if h]
        try:
            hs.sort(key=lambda h: tuple(h.items()))
        except TypeError:
            # For Hs whose outcomes don't support direct comparisons (e.g. symbolic
            # types)
            hs.sort(key=lambda h: natural_key(h.items()))
        self._hs: tuple[H[_T_co], ...] = tuple(hs)
        self._hash: int | None = None
        self._total: int | None = None

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

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

    def __repr__(self) -> str:
        group_counters: dict[H[_T_co], int] = {}
        for h, hs in groupby(self):
            group_counters[h] = sum(1 for _ in hs)

        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(group_counters) == 1:
            h, n = next(iter(group_counters.items()))
            return f"{type(self).__name__}({_n_at(h, 1)})" if n == 1 else _n_at(h, n)
        else:
            inner = ", ".join(starmap(_n_at, group_counters.items()))
            return f"{type(self).__name__}({inner})"

    def __eq__(self, other: object) -> bool:
        if isinstance(other, P):
            return self._hs == other._hs
        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]": ...
    @nobeartype  # TODO(posita): <https://github.com/beartype/beartype/issues/636>
    def __getitem__(self: "P[_T]", key: SupportsIndex | slice) -> "P[_T] | H[_T]":
        if isinstance(key, slice):
            return P(*self._hs[key])
        return self._hs[operator.index(key)]

    def __iter__(self: "P[_T]") -> Iterator[H[_T]]:
        yield from self._hs

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

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

    def __matmul__(self: "P[_T]", other: SupportsInt) -> "P[_T]":
        try:
            n = lossless_int(other)
        except (TypeError, ValueError):
            return NotImplemented
        if n < 0:
            raise ValueError(
                f"{type(self).__name__} requires non-negative operand for @ operator (found {n!r})"
            )
        return P(*chain.from_iterable(repeat(self, n)))

    def __rmatmul__(self: "P[_T]", other: SupportsInt) -> "P[_T]":
        return self.__matmul__(other)

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

    @property
    def total(self) -> int:
        r"""
        Equivalent to `#!python prod(h.total for h in self)`.
        Consistent with the empty product, this is `#!python 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 for h in self._hs)
        return self._total

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

    @overload
    def apply_to_each_h(
        self: "P[_T]",
        func: Callable[[_T], _ResultT],
        *,
        apply_to_each: bool = False,
    ) -> "P[_ResultT]": ...
    @overload
    def apply_to_each_h(
        self: "P[_T]",
        func: Callable[[_T, _OtherT], _ResultT],
        other: "H[_OtherT]",
        *,
        apply_to_each: bool = False,
    ) -> "P[_ResultT]": ...
    @overload
    def apply_to_each_h(
        self: "P[_T]",
        func: Callable[[_T, _OtherT], _ResultT],
        other: _OtherT,
        *,
        apply_to_each: bool = False,
    ) -> "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"""
        Return 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 `#!python h`, calling `#!python h.apply(func, other)` should return the same result regardless of context.
        This allows for *func* to be applied only once for each distinct `#!python H` in `#!python P`, and the result reused.
        If this is not desired, provide `#!python True` for *apply_to_each* to ensure that *func* is actually run on each individual histogram.
        """

        def _h_counts_by_group() -> Iterable[tuple[H[_T], int]]:
            for h, hs in groupby(self):
                yield h, sum(1 for _ in hs)

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

        def _applied_hs() -> Iterable[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())

    @experimental
    def apply_to_each_roll(
        self: "P[_T]",
        func: Callable[[RollT[_T]], H[_ResultT] | _ResultT],
        *which: GetItemT,
    ) -> H[_ResultT]:
        r"""
        TODO(posita): Fill this out.
        """
        return cast(
            "H[_ResultT]",
            aggregate_weighted(
                (func(roll), count) for roll, count in self.rolls_with_counts(*which)
            ),
        )

    # TODO(posita): # noqa: TD003 - Use CanAdd here
    def h(self: "P[_T]", *which: GetItemT) -> H[_T]:  # noqa: C901
        r"""
        Combines (or “flattens”) all contained histograms into a single [`H`][dyce.H] in accordance with the [`HableT` protocol][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})

        When on or more optional *which* identifiers is provided, this is roughly equivalent to `#!python H((sum(roll), count) for roll, count in self.rolls_with_counts(*which))` with some short-circuit optimizations.
        Identifiers can be `#!python int`s or `#!python 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.h(-1)
            H({1: 1, 2: 3, 3: 5, 4: 7, 5: 9, 6: 11})
            >>> print(p_2d6.h(-1).format(width=65))
            avg |    4.47
            std |    1.40
            var |    1.97
              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.h(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.h(slice(2), slice(-2, None)).format(width=65, scaled=True))
            avg |   10.00
            std |    0.91
            var |    0.84
              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.h(slice(None)) == p.h() == d6 + d6 + d6avg + d6avg
            True
        """
        if not which:
            return (
                H({})
                if len(self) == 0
                else self._hs[0]
                if len(self) == 1
                else sum_h(self)
            )
        n = len(self)
        i = _analyze_selection(n, which)
        # Optimization for when each and every position is selected the same number of times
        if n and isinstance(i, _SelectionUniform):
            try:
                # This optimization assumes outcomes support multiplication with native
                # ints while retaining their type ...
                return sum_h(self) * i.times  # type: ignore[operator]
            except TypeError:
                # ... but if we get into trouble, fall through to enumerating via rolls_with_counts
                pass
        # Single-position selection on a homogeneous pool: dispatch directly to
        # `H.order_stat_for_n_at_pos` instead of enumerating rolls. The selection
        # variants that flag this case are:
        #   - `_SelectionSinglePos(pos)` for true-middle positions.
        #   - `_SelectionPrefix(max_index=1)` for the lowest (pos == 0).
        #   - `_SelectionSuffix(min_index=-1)` for the highest (pos == n - 1).
        # Heterogeneous pools and multi-position selections fall through to the existing
        # `rolls_with_counts` path.
        #
        # TODO(posita): # noqa: TD003 - As of *right now*, we prevent selection of the
        # single-prefix or single-suffix fast path with repeated single selections. The
        # fast path can likely support those, but it requires rethinking how we perform
        # and communicate selection analysis. The current approach opts for correctness
        # over a smaller surface. We'll likely revisit with a later deep dive into
        # performance.
        if n:
            pos: int | None = None
            if isinstance(i, _SelectionSinglePos):
                pos = i.pos
            elif (
                isinstance(i, _SelectionPrefix)
                and i.max_index == 1
                and i.is_single_non_repeated
            ):
                pos = 0
            elif (
                isinstance(i, _SelectionSuffix)
                and i.min_index == -1
                and i.is_single_non_repeated
            ):
                pos = n - 1
            if pos is not None:
                # Test for homogeneous: all of `self._hs` are equal. `P`
                # sorts at construction so the test is just first-vs-last.
                if self._hs[0] == self._hs[-1]:
                    h = self._hs[0]
                    # Bypass `order_stat_for_n_at_pos`'s `@experimental` warning
                    # emission by going through the cached internal helper directly,
                    # since both produce the same result
                    if n not in h._order_stat_funcs_by_n:  # noqa: SLF001
                        h._order_stat_funcs_by_n[n] = h._order_stat_func_for_n(n)  # noqa: SLF001
                    return cast(
                        "H[_T]",
                        h._order_stat_funcs_by_n[n](pos),  # noqa: SLF001
                    )
                # Heterogeneous + single-END decomposition. The identity `max(X_1..X_n,
                # Y_1..Y_m) == max(max(X_1..X_n), max(Y_1..Y_m))` (and min
                # symmetrically) lets us reduce each homogeneous sub-group via
                # `order_stat_for_n_at_pos`, then recurse on the smaller reduced pool.
                # Termination: a group of size `n_g > 1` becomes a single H, so each
                # pass strictly decreases `sum(n_g for groups)`. Skip when all groups
                # are size 1 -- decomposition would be a no-op and could otherwise loop.
                if pos == 0 or pos == n - 1:
                    groups_list = [
                        (h_g, sum(1 for _ in g)) for h_g, g in groupby(self._hs)
                    ]
                    if any(n_g > 1 for _, n_g in groups_list):
                        reduced_hs: list[H[_T]] = []
                        for h_g, n_g in groups_list:
                            if n_g == 1:
                                reduced_hs.append(h_g)
                                continue
                            per_group_pos = n_g - 1 if pos == n - 1 else 0
                            if n_g not in h_g._order_stat_funcs_by_n:  # noqa: SLF001
                                h_g._order_stat_funcs_by_n[n_g] = (  # noqa: SLF001
                                    h_g._order_stat_func_for_n(n_g)  # noqa: SLF001
                                )
                            reduced_hs.append(
                                cast(
                                    "H[_T]",
                                    h_g._order_stat_funcs_by_n[n_g](per_group_pos),  # noqa: SLF001
                                )
                            )
                        return P(*reduced_hs).h(0 if pos == 0 else -1)
        return H.from_counts(
            # This slightly esoteric use of sum() is to avoid an attempt to 0 to
            # outcomes, which is sum()'s default behavior. At worst, this results in
            # more accurate error messages where outcomes don't support addition at all.
            (sum(roll[1:], start=roll[0]), count)  # type: ignore[call-overload] # ty: ignore[no-matching-overload]
            for roll, count in self.rolls_with_counts(*which)
        )

    def roll(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.
        """
        roll = [h.roll() for h in self]
        try:
            roll.sort()  # pyrefly: ignore[bad-specialization] # pyright: ignore[reportCallIssue] # ty: ignore[invalid-argument-type]
        except TypeError:
            roll.sort(key=natural_key)
        return tuple(roll)

    def rolls_with_counts(self: "P[_T]", *which: GetItemT) -> Iterable[RollCountT[_T]]:  # noqa: C901
        r"""
        Returns an iterator yielding `#!python (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 `#!python SupportsIndex` or `#!python 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. 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), 3), ((1, 2), 3), ..., ((5, 6), 3), ((5, 6), 3), ((6, 6), 1)]
            >>> lo_hi_from_all_3d6_rolls == sorted(
            ...     ((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), 3), ((1, 2), 3), ((2, 2), 1)]
            >>> sorted(P(H(2), H(3)).rolls_with_counts())
            [((1, 1), 1), ((1, 2), 1), ((1, 2), 1), ((1, 3), 1), ((2, 2), 1), ((2, 3), 1)]

        No rolls will be produced with empty `#!python 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)
        if not which:
            sel: _SelectionResult = _SelectionUniform(times=1)
        else:
            sel = _analyze_selection(n, which)
        rolls_with_counts_iter: Iterable[RollCountT[_T | _MinFill | _MaxFill]]
        # Short-circuit: empty selection or empty pool
        if isinstance(sel, _SelectionEmpty) or n == 0:
            return
        groups = tuple((h, sum(1 for _ in hs)) for h, hs in groupby(self))
        # The fast path inclusion-exclusion algorithm in _rwc_heterogeneous_extremes
        # only supports (lo=1, hi=1). Otherwise, fall through and convert selection to
        # the integer k hint consumed by other lower-level functions:
        #
        # * positive k - take k from left (prefix)
        # * negative k - take k from right (suffix)
        # * None - full enumeration (uniform, extremes fallback, or arbitrary)
        if (
            isinstance(sel, _SelectionExtremes)
            and len(groups) > 1
            and sel.lo == 1
            and sel.hi == 1
        ):
            yield from _rwc_heterogeneous_extremes(groups, sel.lo, sel.hi)
            return

        if isinstance(sel, _SelectionPrefix):
            k: int | None = sel.max_index if sel.max_index >= 0 else n + sel.max_index
        elif isinstance(sel, _SelectionSuffix):
            k = sel.min_index if sel.min_index < 0 else sel.min_index - n
        elif isinstance(sel, _SelectionSinglePos):
            # Pick the side that yields the smaller partial-selection similar to
            # _SelectionPrefix/_SelectionSuffix
            pos = sel.pos
            k = pos + 1 if pos + 1 <= n - pos else pos - n
        else:
            k = None
        if len(groups) == 1:
            h, hn = groups[0]
            assert hn == n
            if k is not None and abs(k) < n:
                rolls_with_counts_iter = _rwc_homogeneous_n_h_using_partial_selection(
                    n, h, k=k, fill=cast("_T", 0)
                )
            else:
                rolls_with_counts_iter = _rwc_homogeneous_n_h_using_partial_selection(
                    n, h, k=n
                )
        else:
            rolls_with_counts_iter = _rwc_heterogeneous_h_groups(groups, k)

        for sorted_outcomes_for_roll, roll_count in rolls_with_counts_iter:
            if which:
                taken_outcomes: RollT[_T] = cast(
                    "RollT[_T]", tuple(getitems(sorted_outcomes_for_roll, which))
                )
            else:
                taken_outcomes = cast("RollT[_T]", sorted_outcomes_for_roll)
            yield taken_outcomes, roll_count

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

Constructor.

Source code in dyce/p.py
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
def __init__(
    self,
    *init_vals: Any,
) -> None:
    r"""Constructor."""
    super().__init__()

    def _hs_from_init_vals() -> Iterable[H[_T_co]]:
        for init_val in init_vals:
            if isinstance(init_val, H):
                yield init_val
            elif isinstance(init_val, P):
                yield from init_val._hs  # noqa: SLF001
            else:
                yield H(init_val)

    hs = [h for h in _hs_from_init_vals() if h]
    try:
        hs.sort(key=lambda h: tuple(h.items()))
    except TypeError:
        # For Hs whose outcomes don't support direct comparisons (e.g. symbolic
        # types)
        hs.sort(key=lambda h: natural_key(h.items()))
    self._hs: tuple[H[_T_co], ...] = tuple(hs)
    self._hash: int | None = None
    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 = False,
) -> P[_ResultT]
apply_to_each_h(
    func: Callable[[_T, _OtherT], _ResultT],
    other: H[_OtherT],
    *,
    apply_to_each: bool = False,
) -> P[_ResultT]
apply_to_each_h(
    func: Callable[[_T, _OtherT], _ResultT],
    other: _OtherT,
    *,
    apply_to_each: bool = False,
) -> P[_ResultT]

Return 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
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
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"""
    Return 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 `#!python h`, calling `#!python h.apply(func, other)` should return the same result regardless of context.
    This allows for *func* to be applied only once for each distinct `#!python H` in `#!python P`, and the result reused.
    If this is not desired, provide `#!python True` for *apply_to_each* to ensure that *func* is actually run on each individual histogram.
    """

    def _h_counts_by_group() -> Iterable[tuple[H[_T], int]]:
        for h, hs in groupby(self):
            yield h, sum(1 for _ in hs)

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

    def _applied_hs() -> Iterable[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())

apply_to_each_roll(func: Callable[[RollT[_T]], H[_ResultT] | _ResultT], *which: GetItemT) -> H[_ResultT]

Experimental

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

TODO(posita): Fill this out.

Source code in dyce/p.py
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
@experimental
def apply_to_each_roll(
    self: "P[_T]",
    func: Callable[[RollT[_T]], H[_ResultT] | _ResultT],
    *which: GetItemT,
) -> H[_ResultT]:
    r"""
    TODO(posita): Fill this out.
    """
    return cast(
        "H[_ResultT]",
        aggregate_weighted(
            (func(roll), count) for roll, count in self.rolls_with_counts(*which)
        ),
    )

h(*which: GetItemT) -> H[_T]

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

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})

When on or more optional which identifiers is provided, this is roughly equivalent to H((sum(roll), count) for roll, count in self.rolls_with_counts(*which)) with some short-circuit 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
13
>>> p_2d6 = 2 @ P(6)
>>> p_2d6.h(-1)
H({1: 1, 2: 3, 3: 5, 4: 7, 5: 9, 6: 11})
>>> print(p_2d6.h(-1).format(width=65))
avg |    4.47
std |    1.40
var |    1.97
  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
>>> p_10d4 = 10 @ P(4)
>>> p_10d4.h(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.h(slice(2), slice(-2, None)).format(width=65, scaled=True))
avg |   10.00
std |    0.91
var |    0.84
  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.h(slice(None)) == p.h() == d6 + d6 + d6avg + d6avg
True
Source code in dyce/p.py
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
def h(self: "P[_T]", *which: GetItemT) -> H[_T]:  # noqa: C901
    r"""
    Combines (or “flattens”) all contained histograms into a single [`H`][dyce.H] in accordance with the [`HableT` protocol][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})

    When on or more optional *which* identifiers is provided, this is roughly equivalent to `#!python H((sum(roll), count) for roll, count in self.rolls_with_counts(*which))` with some short-circuit optimizations.
    Identifiers can be `#!python int`s or `#!python 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.h(-1)
        H({1: 1, 2: 3, 3: 5, 4: 7, 5: 9, 6: 11})
        >>> print(p_2d6.h(-1).format(width=65))
        avg |    4.47
        std |    1.40
        var |    1.97
          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.h(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.h(slice(2), slice(-2, None)).format(width=65, scaled=True))
        avg |   10.00
        std |    0.91
        var |    0.84
          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.h(slice(None)) == p.h() == d6 + d6 + d6avg + d6avg
        True
    """
    if not which:
        return (
            H({})
            if len(self) == 0
            else self._hs[0]
            if len(self) == 1
            else sum_h(self)
        )
    n = len(self)
    i = _analyze_selection(n, which)
    # Optimization for when each and every position is selected the same number of times
    if n and isinstance(i, _SelectionUniform):
        try:
            # This optimization assumes outcomes support multiplication with native
            # ints while retaining their type ...
            return sum_h(self) * i.times  # type: ignore[operator]
        except TypeError:
            # ... but if we get into trouble, fall through to enumerating via rolls_with_counts
            pass
    # Single-position selection on a homogeneous pool: dispatch directly to
    # `H.order_stat_for_n_at_pos` instead of enumerating rolls. The selection
    # variants that flag this case are:
    #   - `_SelectionSinglePos(pos)` for true-middle positions.
    #   - `_SelectionPrefix(max_index=1)` for the lowest (pos == 0).
    #   - `_SelectionSuffix(min_index=-1)` for the highest (pos == n - 1).
    # Heterogeneous pools and multi-position selections fall through to the existing
    # `rolls_with_counts` path.
    #
    # TODO(posita): # noqa: TD003 - As of *right now*, we prevent selection of the
    # single-prefix or single-suffix fast path with repeated single selections. The
    # fast path can likely support those, but it requires rethinking how we perform
    # and communicate selection analysis. The current approach opts for correctness
    # over a smaller surface. We'll likely revisit with a later deep dive into
    # performance.
    if n:
        pos: int | None = None
        if isinstance(i, _SelectionSinglePos):
            pos = i.pos
        elif (
            isinstance(i, _SelectionPrefix)
            and i.max_index == 1
            and i.is_single_non_repeated
        ):
            pos = 0
        elif (
            isinstance(i, _SelectionSuffix)
            and i.min_index == -1
            and i.is_single_non_repeated
        ):
            pos = n - 1
        if pos is not None:
            # Test for homogeneous: all of `self._hs` are equal. `P`
            # sorts at construction so the test is just first-vs-last.
            if self._hs[0] == self._hs[-1]:
                h = self._hs[0]
                # Bypass `order_stat_for_n_at_pos`'s `@experimental` warning
                # emission by going through the cached internal helper directly,
                # since both produce the same result
                if n not in h._order_stat_funcs_by_n:  # noqa: SLF001
                    h._order_stat_funcs_by_n[n] = h._order_stat_func_for_n(n)  # noqa: SLF001
                return cast(
                    "H[_T]",
                    h._order_stat_funcs_by_n[n](pos),  # noqa: SLF001
                )
            # Heterogeneous + single-END decomposition. The identity `max(X_1..X_n,
            # Y_1..Y_m) == max(max(X_1..X_n), max(Y_1..Y_m))` (and min
            # symmetrically) lets us reduce each homogeneous sub-group via
            # `order_stat_for_n_at_pos`, then recurse on the smaller reduced pool.
            # Termination: a group of size `n_g > 1` becomes a single H, so each
            # pass strictly decreases `sum(n_g for groups)`. Skip when all groups
            # are size 1 -- decomposition would be a no-op and could otherwise loop.
            if pos == 0 or pos == n - 1:
                groups_list = [
                    (h_g, sum(1 for _ in g)) for h_g, g in groupby(self._hs)
                ]
                if any(n_g > 1 for _, n_g in groups_list):
                    reduced_hs: list[H[_T]] = []
                    for h_g, n_g in groups_list:
                        if n_g == 1:
                            reduced_hs.append(h_g)
                            continue
                        per_group_pos = n_g - 1 if pos == n - 1 else 0
                        if n_g not in h_g._order_stat_funcs_by_n:  # noqa: SLF001
                            h_g._order_stat_funcs_by_n[n_g] = (  # noqa: SLF001
                                h_g._order_stat_func_for_n(n_g)  # noqa: SLF001
                            )
                        reduced_hs.append(
                            cast(
                                "H[_T]",
                                h_g._order_stat_funcs_by_n[n_g](per_group_pos),  # noqa: SLF001
                            )
                        )
                    return P(*reduced_hs).h(0 if pos == 0 else -1)
    return H.from_counts(
        # This slightly esoteric use of sum() is to avoid an attempt to 0 to
        # outcomes, which is sum()'s default behavior. At worst, this results in
        # more accurate error messages where outcomes don't support addition at all.
        (sum(roll[1:], start=roll[0]), count)  # type: ignore[call-overload] # ty: ignore[no-matching-overload]
        for roll, count in self.rolls_with_counts(*which)
    )

roll() -> RollT[_T]

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
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
def roll(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.
    """
    roll = [h.roll() for h in self]
    try:
        roll.sort()  # pyrefly: ignore[bad-specialization] # pyright: ignore[reportCallIssue] # ty: ignore[invalid-argument-type]
    except TypeError:
        roll.sort(key=natural_key)
    return tuple(roll)

rolls_with_counts(*which: GetItemT) -> Iterable[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. 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), 3), ((1, 2), 3), ..., ((5, 6), 3), ((5, 6), 3), ((6, 6), 1)]
>>> lo_hi_from_all_3d6_rolls == sorted(
...     ((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), 3), ((1, 2), 3), ((2, 2), 1)]
>>> sorted(P(H(2), H(3)).rolls_with_counts())
[((1, 1), 1), ((1, 2), 1), ((1, 2), 1), ((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
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
def rolls_with_counts(self: "P[_T]", *which: GetItemT) -> Iterable[RollCountT[_T]]:  # noqa: C901
    r"""
    Returns an iterator yielding `#!python (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 `#!python SupportsIndex` or `#!python 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. 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), 3), ((1, 2), 3), ..., ((5, 6), 3), ((5, 6), 3), ((6, 6), 1)]
        >>> lo_hi_from_all_3d6_rolls == sorted(
        ...     ((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), 3), ((1, 2), 3), ((2, 2), 1)]
        >>> sorted(P(H(2), H(3)).rolls_with_counts())
        [((1, 1), 1), ((1, 2), 1), ((1, 2), 1), ((1, 3), 1), ((2, 2), 1), ((2, 3), 1)]

    No rolls will be produced with empty `#!python 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)
    if not which:
        sel: _SelectionResult = _SelectionUniform(times=1)
    else:
        sel = _analyze_selection(n, which)
    rolls_with_counts_iter: Iterable[RollCountT[_T | _MinFill | _MaxFill]]
    # Short-circuit: empty selection or empty pool
    if isinstance(sel, _SelectionEmpty) or n == 0:
        return
    groups = tuple((h, sum(1 for _ in hs)) for h, hs in groupby(self))
    # The fast path inclusion-exclusion algorithm in _rwc_heterogeneous_extremes
    # only supports (lo=1, hi=1). Otherwise, fall through and convert selection to
    # the integer k hint consumed by other lower-level functions:
    #
    # * positive k - take k from left (prefix)
    # * negative k - take k from right (suffix)
    # * None - full enumeration (uniform, extremes fallback, or arbitrary)
    if (
        isinstance(sel, _SelectionExtremes)
        and len(groups) > 1
        and sel.lo == 1
        and sel.hi == 1
    ):
        yield from _rwc_heterogeneous_extremes(groups, sel.lo, sel.hi)
        return

    if isinstance(sel, _SelectionPrefix):
        k: int | None = sel.max_index if sel.max_index >= 0 else n + sel.max_index
    elif isinstance(sel, _SelectionSuffix):
        k = sel.min_index if sel.min_index < 0 else sel.min_index - n
    elif isinstance(sel, _SelectionSinglePos):
        # Pick the side that yields the smaller partial-selection similar to
        # _SelectionPrefix/_SelectionSuffix
        pos = sel.pos
        k = pos + 1 if pos + 1 <= n - pos else pos - n
    else:
        k = None
    if len(groups) == 1:
        h, hn = groups[0]
        assert hn == n
        if k is not None and abs(k) < n:
            rolls_with_counts_iter = _rwc_homogeneous_n_h_using_partial_selection(
                n, h, k=k, fill=cast("_T", 0)
            )
        else:
            rolls_with_counts_iter = _rwc_homogeneous_n_h_using_partial_selection(
                n, h, k=n
            )
    else:
        rolls_with_counts_iter = _rwc_heterogeneous_h_groups(groups, k)

    for sorted_outcomes_for_roll, roll_count in rolls_with_counts_iter:
        if which:
            taken_outcomes: RollT[_T] = cast(
                "RollT[_T]", tuple(getitems(sorted_outcomes_for_roll, which))
            )
        else:
            taken_outcomes = cast("RollT[_T]", sorted_outcomes_for_roll)
        yield taken_outcomes, roll_count

PResult

Bases: NamedTuple, Generic[_T]

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

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

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

TruncationWarning

Bases: UserWarning

Issued when results are truncated from expand for whatever reason.

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

expand(callback: Callable, *sources: H | P, precision: Fraction = _DEFAULT_PRECISION, **state: Any) -> H

expand(
    callback: Callable[
        [HResult[_T]], H[_ResultT] | _ResultT
    ],
    source: H[_T],
    *,
    precision: Fraction = ...,
    **state: Any,
) -> H[_ResultT]
expand(
    callback: Callable[
        [PResult[_T]], H[_ResultT] | _ResultT
    ],
    source: P[_T],
    *,
    precision: Fraction = ...,
    **state: Any,
) -> H[_ResultT]
expand(
    callback: Callable[
        [HResult[_T1], HResult[_T2]], H[_ResultT] | _ResultT
    ],
    source1: H[_T1],
    source2: H[_T2],
    *,
    precision: Fraction = ...,
    **state: Any,
) -> H[_ResultT]
expand(
    callback: Callable[
        [HResult[_T1], PResult[_T2]], H[_ResultT] | _ResultT
    ],
    source1: H[_T1],
    source2: P[_T2],
    *,
    precision: Fraction = ...,
    **state: Any,
) -> H[_ResultT]
expand(
    callback: Callable[
        [PResult[_T1], HResult[_T2]], H[_ResultT] | _ResultT
    ],
    source1: P[_T1],
    source2: H[_T2],
    *,
    precision: Fraction = ...,
    **state: Any,
) -> H[_ResultT]
expand(
    callback: Callable[
        [PResult[_T1], PResult[_T2]], H[_ResultT] | _ResultT
    ],
    source1: P[_T1],
    source2: P[_T2],
    *,
    precision: Fraction = ...,
    **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],
    *,
    precision: Fraction = ...,
    **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],
    *,
    precision: Fraction = ...,
    **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],
    *,
    precision: Fraction = ...,
    **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],
    *,
    precision: Fraction = ...,
    **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],
    *,
    precision: Fraction = ...,
    **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],
    *,
    precision: Fraction = ...,
    **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],
    *,
    precision: Fraction = ...,
    **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],
    *,
    precision: Fraction = ...,
    **state: Any,
) -> H[_ResultT]
expand(
    callback: Callable[..., Any],
    *sources: H[Any] | P[Any],
    precision: Fraction = ...,
    **state: Any,
) -> H[Any]

Experimental

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

Evaluate 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 pe 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
7
8
>>> 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
10
11
>>> 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
5
>>> 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})

Precision and recursion limiting

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

precision is set by the outermost expand call and propagated automatically to all recursive calls via a context variable.

precision is not overridden during recursion

Passing precision in a recursive call has no effect. The value from the outermost call is always used.

Because precision is path-probability-based, the same threshold produces different recursion depths depending on how likely the exploding face is. A heavier exploding face keeps branches above the threshold longer:

 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
>>> from dyce import TruncationWarning

>>> 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}),
...         precision=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}),
...         precision=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 precision 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
21
22
>>> def explode_on_max_up_to_n_times(
...     result: HResult, *, 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
13
14
>>> from dyce import P
>>> from dyce.evaluation import PResult
>>> p_2d10 = 2 @ P(10)

>>> def times_d6_beats_two_d10s(
...     d6_result: HResult[int],
...     p_result: PResult[int],
... ) -> int:
...     return sum(
...         1 for outcome in p_result.roll if outcome < d6_result.outcome
...     )

>>> expand(times_d6_beats_two_d10s, H(6), p_2d10)
H({0: 71, 1: 38, 2: 11})
Source code in dyce/evaluation.py
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
def expand(  # noqa: C901
    callback: Callable,
    *sources: H | P,
    precision: Fraction = _DEFAULT_PRECISION,
    **state: Any,
) -> H:
    r"""
    !!! warning "Experimental"

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

    <!-- BEGIN MONKEY PATCH --
    >>> import warnings
    >>> from dyce.lifecycle import ExperimentalWarning
    >>> warnings.filterwarnings("ignore", category=ExperimentalWarning)

       -- END MONKEY PATCH -->

    Evaluate *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 pe [`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.
    - **`#!python 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 `#!python H({})` from a recursive call propagates naturally through arithmetic (`#!python H({}) + outcome` is `#!python 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})

    **Precision and recursion limiting**

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

    *precision* is set by the outermost `expand` call and propagated automatically to all recursive calls via a context variable.

    !!! warning "*precision* is ***not*** overridden during recursion"

        Passing *precision* in a recursive call has no effect.
        The value from the outermost call is *always* used.

    Because *precision* is path-probability-based, the same threshold produces different recursion depths depending on how likely the exploding face is.
    A heavier exploding face keeps branches above the threshold longer:

        >>> from dyce import TruncationWarning

        >>> 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}),
        ...         precision=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}),
        ...         precision=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 *precision* 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, *, 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
        >>> p_2d10 = 2 @ P(10)

        >>> def times_d6_beats_two_d10s(
        ...     d6_result: HResult[int],
        ...     p_result: PResult[int],
        ... ) -> int:
        ...     return sum(
        ...         1 for outcome in p_result.roll if outcome < d6_result.outcome
        ...     )

        >>> expand(times_d6_beats_two_d10s, H(6), p_2d10)
        H({0: 71, 1: 38, 2: 11})

    <!-- BEGIN MONKEY PATCH --
    >>> warnings.resetwarnings()

       -- END MONKEY PATCH -->
    """
    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),
            precision=precision,
        )

    current_path_prob = cur_ctxt.path_probability
    effective_precision = cur_ctxt.precision
    total_product = prod(s.total for s in sources)
    truncation_reasons: set[_TruncationReason] = set()

    def _result_counts() -> Iterable[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_precision:
                truncation_reasons.add(_TruncationReason.PROB_BDGT_EXHAUSTED)
                continue
            new_ctxt = _ExpandContext(
                path_probability=branch_path_prob,
                precision=effective_precision,
            )
            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

    def _result_counts_no_truncate() -> Iterable[tuple[Any, int]]:
        # When precision is 0, the truncation check can never fire, and branch_path_prob
        # would otherwise only feed nested expand's same dead computation since
        # precision is fixed at outermost. Skip the per-branch Fraction construction.
        # The ContextVar still has to be set (so nested calls suppress the
        # outermost-only ExperimentalWarning and inherit precision), but the value is
        # constant across iterations. It is set once around the loop instead of
        # per-iteration.
        shared_ctxt = _ExpandContext(
            path_probability=current_path_prob,
            precision=effective_precision,
        )
        token = _expand_ctxt.set(shared_ctxt)
        try:
            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)
                try:
                    result = callback(*results, **state)
                except RecursionError:
                    truncation_reasons.add(_TruncationReason.RCRS_LMT_EXCEEDED)
                    continue
                yield result, combined_count
        finally:
            _expand_ctxt.reset(token)

    # Warning: _ExpandContext.path_probability is only maintained accurately on the
    # truncating path (precision > 0). The no-truncate fast path skips the per-branch
    # Fraction multiplication, so path_probability stays at its initial value (typically
    # Fraction(1)) at every recursion level. Don't treat it as a meaningful cumulative
    # probability indicator for diagnostics or any other purpose outside the truncation
    # check itself when precision is 0.
    h = aggregate_weighted(
        _result_counts() if effective_precision > 0 else _result_counts_no_truncate()
    )
    if _TruncationReason.PROB_BDGT_EXHAUSTED in truncation_reasons:
        warnings.warn(
            f"expand: some branches with path probability < {effective_precision!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)
    return h

explode_n(source: H[ot.CanAdd[_OtherT, _ResultT]], *, n: int = 1, precision: 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. resolver can return either a histogram to indicate the next die to be rolled and accumulated (up to n times) or an 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
>>> import sympy
>>> x = sympy.sympify("x")
>>> # Zero explosions is the starting roll
>>> explode_n(H({x: 1}), n=0)  # pyright: ignore[reportArgumentType] # ty: ignore[invalid-argument-type]
H({x: 1})
>>> # Starting roll with up to two explosions
>>> explode_n(H({x: 1}), n=2)  # pyright: ignore[reportArgumentType] # ty: ignore[invalid-argument-type]
H({3*x: 1})

precision is forwarded to the outermost expand call. (See that function for details.) With sufficient large values for n, a TruncationWarning will be emitted for branches dropped by exhausting any precision budget.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
>>> from dyce import TruncationWarning
>>> import sys
>>> from fractions import Fraction
>>> with warnings.catch_warnings(record=True) as caught:
...     warnings.simplefilter("always", TruncationWarning)
...     explode_n(
...         d6,
...         n=sys.maxsize,
...         precision=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

>>> from typing import TypeVar
>>> T = TypeVar("T")

>>> def explode_on_even_resolver(
...     result: HResult[T], n_left: int, n_done: int
... ) -> H[T] | T:
...     return result.h if result.outcome % 2 == 0 else result.outcome  # type: ignore[operator] # ty: ignore[unsupported-operator]

>>> with warnings.catch_warnings(record=True) as caught:
...     warnings.simplefilter("always", TruncationWarning)
...     explode_n(
...         d6,
...         n=sys.maxsize,
...         precision=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
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
@experimental
def explode_n(
    source: H[ot.CanAdd[_OtherT, _ResultT]],
    *,
    n: int = 1,
    precision: Fraction = Fraction(0),
    resolver: Callable[
        [HResult[_ResultT], int, int], H[_ResultT] | _ResultT
    ] = _explode_on_max,
) -> H[_ResultT]:
    r"""
    <!-- BEGIN MONKEY PATCH --
    >>> import warnings
    >>> from dyce.lifecycle import ExperimentalWarning
    >>> warnings.filterwarnings("ignore", category=ExperimentalWarning)
    >>> import sympy  # type: ignore[import-untyped]

       -- END MONKEY PATCH -->

    Convenience wrapper around [`expand`][dyce.expand] for exploding dice.
    *resolver* can return either a histogram to indicate the next die to be rolled and accumulated (up to *n* times) or an 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")
        >>> # Zero explosions is the starting roll
        >>> explode_n(H({x: 1}), n=0)  # pyright: ignore[reportArgumentType] # ty: ignore[invalid-argument-type]
        H({x: 1})
        >>> # Starting roll with up to two explosions
        >>> explode_n(H({x: 1}), n=2)  # pyright: ignore[reportArgumentType] # ty: ignore[invalid-argument-type]
        H({3*x: 1})

    *precision* is forwarded to the outermost [`expand`][dyce.expand] call.
    (See that function for details.)
    With sufficient large values for *n*, a [`TruncationWarning`][dyce.TruncationWarning] will be emitted for branches dropped by exhausting any precision budget.

        >>> from dyce import TruncationWarning
        >>> import sys
        >>> from fractions import Fraction
        >>> with warnings.catch_warnings(record=True) as caught:
        ...     warnings.simplefilter("always", TruncationWarning)
        ...     explode_n(
        ...         d6,
        ...         n=sys.maxsize,
        ...         precision=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

        >>> from typing import TypeVar
        >>> T = TypeVar("T")

        >>> def explode_on_even_resolver(
        ...     result: HResult[T], n_left: int, n_done: int
        ... ) -> H[T] | T:
        ...     return result.h if result.outcome % 2 == 0 else result.outcome  # type: ignore[operator] # ty: ignore[unsupported-operator]

        >>> with warnings.catch_warnings(record=True) as caught:
        ...     warnings.simplefilter("always", TruncationWarning)
        ...     explode_n(
        ...         d6,
        ...         n=sys.maxsize,
        ...         precision=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

    <!-- BEGIN MONKEY PATCH --
    >>> warnings.resetwarnings()

       -- END MONKEY PATCH -->
    """

    @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

    with warnings.catch_warnings():
        warnings.filterwarnings("ignore", category=ExperimentalWarning)
        return expand(_callback, source, n_left=n, precision=precision)