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, the dyce.evaluation package provides the expandable decorator, which is useful for substitutions, explosions, and modeling arbitrarily complex computations with dependent terms. It also provides foreach and explode as convenient shorthands. The dyce.r package provides scalars, histograms, pools, operators, etc. for assembling reusable roller trees.

H

Bases: _MappingT

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.

The initializer takes a single parameter, items. In its most explicit form, items 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})

An iterable of pairs can also be used (similar to dict).

1
2
>>> d6 == H(((1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1)))
True

Two shorthands are provided. If items is an iterable of numbers, counts of 1 are assumed.

1
2
>>> d6 == H((1, 2, 3, 4, 5, 6))
True

Repeated items are accumulated, as one would expect.

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

If items is an integer, it is shorthand for creating a sequential range \([{1} .. {items}]\) (or \([{items} .. {-1}]\) if items is negative).

1
2
>>> d6 == H(6)
True

Histograms are maps, so we can test equivalence against other maps.

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

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

1
2
>>> H((2, 3, 3, 4, 4, 5))[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
>>> d6 + 4
H({5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1})
1
2
3
4
5
6
>>> 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, combinations are computed. 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())
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

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
>>> 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())
avg |    0.83
std |    0.37
var |    0.14
  0 |  16.67% |########
  1 |  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())
avg |    0.42
std |    0.49
var |    0.24
  0 |  58.33% |#############################
  1 |  41.67% |####################

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

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

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

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

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

    ```

    An iterable of pairs can also be used (similar to ``#!python dict``).

    ``` python
    >>> d6 == H(((1, 1), (2, 1), (3, 1), (4, 1), (5, 1), (6, 1)))
    True

    ```

    Two shorthands are provided. If *items* is an iterable of numbers, counts of 1 are
    assumed.

    ``` python
    >>> d6 == H((1, 2, 3, 4, 5, 6))
    True

    ```

    Repeated items are accumulated, as one would expect.

    ``` python
    >>> H((2, 3, 3, 4, 4, 5))
    H({2: 1, 3: 2, 4: 2, 5: 1})

    ```

    If *items* is an integer, it is shorthand for creating a sequential range $[{1} ..
    {items}]$ (or $[{items} .. {-1}]$ if *items* is negative).

    ``` python
    >>> d6 == H(6)
    True

    ```

    Histograms are maps, so we can test equivalence against other maps.

    ``` python
    >>> H(6) == {1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}
    True

    ```

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

    ``` python
    >>> H((2, 3, 3, 4, 4, 5))[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.

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

    ```

    ``` python
    >>> 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, combinations are computed. Modeling the sum of
    two six-sided dice (``2d6``) can be expressed as:

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

    ``` python
    >>> 3@d6 == d6 + d6 + d6
    True

    ```

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

    ``` python
    >>> len(2@d6)
    11

    ```

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

    ``` python
    >>> 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.H.eq]
    [``ne``][dyce.h.H.ne], etc.). One way to count how often a first six-sided die
    shows a different face than a second is:

    ``` python
    >>> d6.ne(d6)
    H({False: 6, True: 30})
    >>> print(d6.ne(d6).format())
    avg |    0.83
    std |    0.37
    var |    0.14
      0 |  16.67% |########
      1 |  83.33% |#########################################

    ```

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

    ``` python
    >>> d6.lt(d6)
    H({False: 21, True: 15})
    >>> print(d6.lt(d6).format())
    avg |    0.42
    std |    0.49
    var |    0.24
      0 |  58.33% |#############################
      1 |  41.67% |####################

    ```

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

    ``` python
    >>> 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  # count of 2s showing on 4d6
    H({0: 625, 1: 500, 2: 150, 3: 20, 4: 1})
    >>> (4@d6_eq2).ge(1)  # how often that count is at least one
    H({False: 625, True: 671})
    >>> print((4@d6_eq2).ge(1).format())
    avg |    0.52
    std |    0.50
    var |    0.25
      0 |  48.23% |########################
      1 |  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 […]``.

        ``` python
        >>> 2@d6[7]  # type: ignore [operator]
        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

        ```

        ``` python
        >>> (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.H.lowest_terms].

    ``` python
    >>> 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.

    ``` python
    >>> d6.ge(4) == d6.ge(4).lowest_terms()
    True

    ```
    """
    __slots__: Any = (
        "_h",
        "_hash",
        "_lowest_terms",
        "_order_stat_funcs_by_n",
        "_total",
    )

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

    @beartype
    def __init__(self, items: _SourceT) -> None:
        r"Initializer."
        super().__init__()
        self._h: _MappingT

        if isinstance(items, H):
            self._h = items._h
        elif isinstance(items, SupportsInt):
            if items == 0:
                self._h = {}
            else:
                simple_init = as_int(items)
                outcome_range = range(
                    simple_init if simple_init < 0 else 1,
                    0 if simple_init < 0 else simple_init + 1,
                )

                # if isinstance(items, RealLike):
                #     outcome_type = type(items)
                #     self._h = {outcome_type(i): 1 for i in outcome_range}
                # else:
                #     self._h = {i: 1 for i in outcome_range}
                assert isinstance(items, RealLike)
                outcome_type = type(items)
                self._h = {outcome_type(i): 1 for i in outcome_range}
        elif isinstance(items, HableT):
            self._h = items.h()._h
        elif isinstance(items, IterableC):
            if isinstance(items, Mapping):
                items = items.items()

            # items is either an Iterable[RealLike] or an Iterable[tuple[RealLike,
            # SupportsInt]] (although this technically supports Iterable[RealLike |
            # tuple[RealLike, SupportsInt]])
            self._h = {}
            sorted_items = list(items)

            try:
                sorted_items.sort()
            except TypeError:
                sorted_items.sort(key=natural_key)

            # As of Python 3.7, insertion order of keys is preserved
            for item in sorted_items:
                if isinstance(item, tuple):
                    outcome, count = item
                    count = as_int(count)
                else:
                    outcome = item
                    count = 1

                if count < 0:
                    raise ValueError(f"count for {outcome} cannot be negative")

                if outcome not in self._h:
                    self._h[outcome] = 0

                self._h[outcome] += count
        else:
            raise TypeError(f"unrecognized initializer type {items!r}")

        # We can't use something like functools.lru_cache for these values because those
        # mechanisms call this object's __hash__ method which relies on both of these
        # and we don't want a circular dependency when computing this object's hash.
        self._hash: Optional[int] = None
        self._total: int = sum(self._h.values())
        self._lowest_terms: Optional[H] = None

        # We don't use functools' caching mechanisms generally because they don't
        # present a good mechanism for scoping the cache to object instances such that
        # the cache will be purged when the object is deleted. functools.cached_property
        # is an exception, but it requires that objects have proper __dict__ values,
        # which Hs do not. So we basically do what functools.cached_property does, but
        # without a __dict__.
        self._order_stat_funcs_by_n: dict[int, Callable[[int], H]] = {}

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

    @beartype
    def __repr__(self) -> str:
        return f"{type(self).__name__}({dict.__repr__(self._h)})"

    @beartype
    def __eq__(self, other) -> bool:
        if isinstance(other, HableT):
            return __eq__(self, other.h())
        elif isinstance(other, H):
            return __eq__(self.lowest_terms()._h, other.lowest_terms()._h)
        else:
            return super().__eq__(other)

    @beartype
    def __ne__(self, other) -> bool:
        if isinstance(other, HableT):
            return __ne__(self, other.h())
        elif isinstance(other, H):
            return not __eq__(self, other)
        else:
            return super().__ne__(other)

    @beartype
    def __hash__(self) -> int:
        if self._hash is None:
            self._hash = hash(frozenset(self.lowest_terms().items()))

        return self._hash

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

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

    @beartype
    def __getitem__(self, key: RealLike) -> int:
        return __getitem__(self._h, key)

    @beartype
    def __iter__(self) -> Iterator[RealLike]:
        return iter(self._h)

    @beartype
    def __reversed__(self) -> Iterator[RealLike]:
        return reversed(self._h)

    @beartype
    def __contains__(self, key: RealLike) -> bool:  # type: ignore [override]
        return key in self._h

    @beartype
    def __add__(self, other: _OperandT) -> "H":
        try:
            return self.map(__add__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __radd__(self, other: RealLike) -> "H":
        try:
            return self.rmap(other, __add__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __sub__(self, other: _OperandT) -> "H":
        try:
            return self.map(__sub__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rsub__(self, other: RealLike) -> "H":
        try:
            return self.rmap(other, __sub__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __mul__(self, other: _OperandT) -> "H":
        try:
            return self.map(__mul__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rmul__(self, other: RealLike) -> "H":
        try:
            return self.rmap(other, __mul__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __matmul__(self, other: SupportsInt) -> "H":
        try:
            other = as_int(other)
        except TypeError:
            return NotImplemented

        if other < 0:
            raise ValueError("argument cannot be negative")
        else:
            return sum_h(repeat(self, other))

    @beartype
    def __rmatmul__(self, other: SupportsInt) -> "H":
        return self.__matmul__(other)

    @beartype
    def __truediv__(self, other: _OperandT) -> "H":
        try:
            return self.map(__truediv__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rtruediv__(self, other: RealLike) -> "H":
        try:
            return self.rmap(other, __truediv__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __floordiv__(self, other: _OperandT) -> "H":
        try:
            return self.map(__floordiv__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rfloordiv__(self, other: RealLike) -> "H":
        try:
            return self.rmap(other, __floordiv__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __mod__(self, other: _OperandT) -> "H":
        try:
            return self.map(__mod__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rmod__(self, other: RealLike) -> "H":
        try:
            return self.rmap(other, __mod__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __pow__(self, other: _OperandT) -> "H":
        try:
            return self.map(__pow__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rpow__(self, other: RealLike) -> "H":
        try:
            return self.rmap(other, __pow__)
        except NotImplementedError:
            return NotImplemented

    @beartype
    # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
    def __and__(self, other: Union[SupportsInt, "H", "HableT"]) -> "H":
        try:
            if isinstance(other, SupportsInt):
                other = as_int(other)

            return self.map(__and__, other)
        except (NotImplementedError, TypeError):
            return NotImplemented

    @beartype
    def __rand__(self, other: SupportsInt) -> "H":
        try:
            return self.rmap(as_int(other), __and__)
        except (NotImplementedError, TypeError):
            return NotImplemented

    @beartype
    # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
    def __xor__(self, other: Union[SupportsInt, "H", "HableT"]) -> "H":
        try:
            if isinstance(other, SupportsInt):
                other = as_int(other)

            return self.map(__xor__, other)
        except NotImplementedError:
            return NotImplemented

    @beartype
    def __rxor__(self, other: SupportsInt) -> "H":
        try:
            return self.rmap(as_int(other), __xor__)
        except (NotImplementedError, TypeError):
            return NotImplemented

    @beartype
    # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
    def __or__(self, other: Union[SupportsInt, "H", "HableT"]) -> "H":
        try:
            if isinstance(other, SupportsInt):
                other = as_int(other)

            return self.map(__or__, other)
        except (NotImplementedError, TypeError):
            return NotImplemented

    @beartype
    def __ror__(self, other: SupportsInt) -> "H":
        try:
            return self.rmap(as_int(other), __or__)
        except (NotImplementedError, TypeError):
            return NotImplemented

    @beartype
    def __neg__(self) -> "H":
        return self.umap(__neg__)

    @beartype
    def __pos__(self) -> "H":
        return self.umap(__pos__)

    @beartype
    def __abs__(self) -> "H":
        return self.umap(__abs__)

    @beartype
    def __invert__(self) -> "H":
        return self.umap(__invert__)

    @beartype
    def counts(self) -> ValuesView[int]:
        r"""
        More descriptive synonym for the [``values`` method][dyce.h.H.values].
        """
        return self._h.values()

    @beartype
    def items(self) -> ItemsView[RealLike, int]:
        return self._h.items()

    @beartype
    def keys(self) -> KeysView[RealLike]:
        return self.outcomes()

    @beartype
    def outcomes(self) -> KeysView[RealLike]:
        r"""
        More descriptive synonym for the [``keys`` method][dyce.h.H.keys].
        """
        return self._h.keys()

    @beartype
    def reversed(self) -> Iterator[RealLike]:
        return reversed(self)

    @beartype
    def values(self) -> ValuesView[int]:
        return self.counts()

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

    @property
    def total(self) -> int:
        r"""
        !!! warning "Experimental"

            This property should be considered experimental and may change or disappear
            in future versions.

        Equivalent to ``#!python sum(self.counts())``.
        """
        return self._total

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

    @classmethod
    @deprecated
    @beartype
    def foreach(
        cls,
        dependent_term: Callable[..., HOrOutcomeT],
        **independent_sources: _SourceT,
    ) -> "H":
        r"""
        !!! warning "Deprecated"

            This method has been deprecated and will be removed in a future release. See
            the [``expandable`` decorator][dyce.evaluation.expandable] and
            [``foreach`` function][dyce.evaluation.foreach] for more flexible
            alternatives.

        Calls ``#!python dependent_term`` for each set of outcomes from the product of
        ``independent_sources`` and accumulates the results. This is useful for
        resolving dependent probabilities. Returned histograms are always reduced to
        their lowest terms.

        For example rolling a d20, re-rolling a ``#!python 1`` if it comes up, and
        keeping the result might be expressed as[^1]:

        [^1]:

            This is primarily for illustration. [``H.substitute``][dyce.h.H.substitute]
            is often better suited to cases involving re-rolling a single independent
            term such as this one.

        ``` python
        >>> d20 = H(20)

        >>> def reroll_one_dependent_term(d20_outcome):
        ...   if d20_outcome == 1:
        ...     return d20
        ...   else:
        ...     return d20_outcome

        >>> H.foreach(reroll_one_dependent_term, d20_outcome=d20)
        H({1: 1, 2: 21, 3: 21, ..., 19: 21, 20: 21})

        ```

        The ``#!python foreach`` class method merely wraps *dependent_term* and calls
        [``P.foreach``][dyce.p.P.foreach]. In doing so, it imposes a very modest
        overhead that is negligible in most cases.

        ``` python
        --8<-- "docs/assets/perf_foreach.txt"
        ```

        <details>
        <summary>Source: <a href="https://github.com/posita/dyce/blob/latest/docs/assets/perf_foreach.ipy"><code>perf_foreach.ipy</code></a></summary>

        ``` python
        --8<-- "docs/assets/perf_foreach.ipy"
        ```
        </details>
        """
        from dyce import P

        def _dependent_term(**roll_kw):
            outcome_kw: dict[str, RealLike] = {}

            for key, roll in roll_kw.items():
                assert isinstance(roll, tuple)
                assert len(roll) == 1
                outcome_kw[key] = roll[0]

            return dependent_term(**outcome_kw)

        return P.foreach(_dependent_term, **independent_sources)

    @beartype
    def map(self, bin_op: _BinaryOperatorT, right_operand: _OperandT) -> "H":
        r"""
        Applies *bin_op* to each outcome of the histogram as the left operand and
        *right_operand* as the right. Shorthands exist for many arithmetic operators and
        comparators.

        ``` python
        >>> import operator
        >>> d6 = H(6)
        >>> d6.map(operator.__add__, d6)
        H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})
        >>> d6.map(operator.__add__, d6) == d6 + d6
        True

        ```

        ``` python
        >>> d6.map(operator.__pow__, 2)
        H({1: 1, 4: 1, 9: 1, 16: 1, 25: 1, 36: 1})
        >>> d6.map(operator.__pow__, 2) == d6 ** 2
        True

        ```

        ``` python
        >>> d6.map(operator.__gt__, 3)
        H({False: 3, True: 3})
        >>> d6.map(operator.__gt__, 3) == d6.gt(3)
        True

        ```
        """
        if isinstance(right_operand, HableT):
            right_operand = right_operand.h()

        if isinstance(right_operand, H):
            return type(self)(
                (bin_op(s, o), self[s] * right_operand[o])
                for s, o in product(self, right_operand)
            )
        else:
            return type(self)(
                (bin_op(outcome, right_operand), count)
                for outcome, count in self.items()
            )

    @beartype
    def rmap(self, left_operand: RealLike, bin_op: _BinaryOperatorT) -> "H":
        r"""
        Analogous to the [``map`` method][dyce.h.H.map], but where the caller supplies
        *left_operand*.

        ``` python
        >>> import operator
        >>> d6 = H(6)
        >>> d6.rmap(2, operator.__pow__)
        H({2: 1, 4: 1, 8: 1, 16: 1, 32: 1, 64: 1})
        >>> d6.rmap(2, operator.__pow__) == 2 ** d6
        True

        ```

        !!! note

            The positions of *left_operand* and *bin_op* are different from
            [``map`` method][dyce.h.H.map]. This is intentional and serves as a reminder
            of operand ordering.
        """
        return type(self)(
            (bin_op(left_operand, outcome), count) for outcome, count in self.items()
        )

    @beartype
    def umap(self, un_op: _UnaryOperatorT) -> "H":
        r"""
        Applies *un_op* to each outcome of the histogram.

        ``` python
        >>> import operator
        >>> H(6).umap(operator.__neg__)
        H({-6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1})

        ```

        ``` python
        >>> H(4).umap(lambda outcome: (-outcome) ** outcome)
        H({-27: 1, -1: 1, 4: 1, 256: 1})

        ```
        """
        return type(self)((un_op(outcome), count) for outcome, count in self.items())

    @beartype
    def lt(self, other: _OperandT) -> "H":
        r"""
        Shorthand for ``#!python self.map(operator.__lt__, other).umap(bool)``.

        ``` python
        >>> H(6).lt(3)
        H({False: 4, True: 2})

        ```

        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
        """
        return self.map(__lt__, other).umap(bool)

    @beartype
    def le(self, other: _OperandT) -> "H":
        r"""
        Shorthand for ``#!python self.map(operator.__le__, other).umap(bool)``.

        ``` python
        >>> H(6).le(3)
        H({False: 3, True: 3})

        ```

        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
        """
        return self.map(__le__, other).umap(bool)

    @beartype
    def eq(self, other: _OperandT) -> "H":
        r"""
        Shorthand for ``#!python self.map(operator.__eq__, other).umap(bool)``.

        ``` python
        >>> H(6).eq(3)
        H({False: 5, True: 1})

        ```

        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
        """
        return self.map(__eq__, other).umap(bool)

    @beartype
    def ne(self, other: _OperandT) -> "H":
        r"""
        Shorthand for ``#!python self.map(operator.__ne__, other).umap(bool)``.

        ``` python
        >>> H(6).ne(3)
        H({False: 1, True: 5})

        ```

        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
        """
        return self.map(__ne__, other).umap(bool)

    @beartype
    def gt(self, other: _OperandT) -> "H":
        r"""
        Shorthand for ``#!python self.map(operator.__gt__, other).umap(bool)``.

        ``` python
        >>> H(6).gt(3)
        H({False: 3, True: 3})

        ```

        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
        """
        return self.map(__gt__, other).umap(bool)

    @beartype
    def ge(self, other: _OperandT) -> "H":
        r"""
        Shorthand for ``#!python self.map(operator.__ge__, other).umap(bool)``.

        ``` python
        >>> H(6).ge(3)
        H({False: 2, True: 4})

        ```

        See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
        """
        return self.map(__ge__, other).umap(bool)

    @beartype
    def is_even(self) -> "H":
        r"""
        Equivalent to ``#!python self.umap(dyce.types.is_even)``.

        ``` python
        >>> H((-4, -2, 0, 1, 2, 3)).is_even()
        H({False: 2, True: 4})

        ```

        See the [``umap`` method][dyce.h.H.umap].
        """
        return self.umap(is_even)

    @beartype
    def is_odd(self) -> "H":
        r"""
        Equivalent to ``#!python self.umap(dyce.types.is_odd)``.

        ``` python
        >>> H((-4, -2, 0, 1, 2, 3)).is_odd()
        H({False: 4, True: 2})

        ```

        See the [``umap`` method][dyce.h.H.umap].
        """
        return self.umap(is_odd)

    @beartype
    def accumulate(self, other: _SourceT) -> "H":
        r"""
        Accumulates counts.

        ``` python
        >>> H(4).accumulate(H(6))
        H({1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1})

        ```
        """
        if not isinstance(other, H):
            other = H(other)

        return type(self)(cast(_SourceT, chain(self.items(), other.items())))

    @beartype
    def draw(
        self,
        outcomes: Optional[Union[RealLike, Iterable[RealLike], _MappingT]] = None,
    ) -> "H":
        r"""
        !!! warning "Experimental"

            This property should be considered experimental and may change or disappear
            in future versions.

        Returns a new [``H`` object][dyce.h.H] where the counts associated with
        *outcomes* has been updated. This may be useful for using histograms to model
        decks of cards (rather than dice). If *outcome* is ``#!python None``, this is
        equivalent to ``#!python self.draw(self.roll())``.

        If *outcomes* is a single value, that value’s count is decremented by one. If
        *outcomes* is an iterable of values, those values’ outcomes are decremented by
        one for each time that outcome appears. If *outcomes* is a mapping of outcomes
        to counts, those outcomes are decremented by the respective counts.

        Counts are not reduced and zero counts are preserved. To reduce, call the
        [``lowest_terms`` method][dyce.h.H.lowest_terms].

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

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

          -- END MONKEY PATCH -->

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

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

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

        >>> h = H(6).accumulate(H(4)) ; h
        H({1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1})
        >>> h.draw({1: 2, 4: 1, 6: 1})
        H({1: 0, 2: 2, 3: 2, 4: 1, 5: 1, 6: 0})

        ```

        !!! tip "Negative counts can be used to increase counts"

            Where *outcomes* is a mapping of outcomes to counts, negative counts can be
            used to *increase* or “add” outcomes’ counts.

            ``` python
            >>> H(4).draw({5: -1})
            H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1})

            ```
        """
        if outcomes is None:
            return self.draw(self.roll())

        if isinstance(outcomes, RealLike):
            outcomes = (outcomes,)

        to_draw_outcome_counts = Counter(outcomes)
        self_outcome_counts = Counter(self)
        # This approach is necessary because Counter.__sub__ does not preserve negative
        # counts and Counter.subtract modifies the counter in-place
        new_outcome_counts = Counter(self_outcome_counts)
        new_outcome_counts.subtract(to_draw_outcome_counts)
        would_go_negative = set(+to_draw_outcome_counts) - set(+self_outcome_counts)

        if would_go_negative:
            raise ValueError(f"outcomes to be drawn {would_go_negative} not in {self}")

        zeros = set(self_outcome_counts) - set(new_outcome_counts)

        for outcome in zeros:
            new_outcome_counts[outcome] = 0

        return type(self)(new_outcome_counts)

    @experimental
    @beartype
    def exactly_k_times_in_n(
        self,
        outcome: RealLike,
        n: SupportsInt,
        k: SupportsInt,
    ) -> int:
        r"""
        !!! warning "Experimental"

            This method should be considered experimental and may change or disappear in
            future versions.

        Computes (in constant time) and returns the number of times *outcome* appears
        exactly *k* times among ``#!python n@self``. This is a more efficient
        alternative to ``#!python (n@(self.eq(outcome)))[k]``.

        ``` python
        >>> 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

        ```
        """
        n = as_int(n)
        k = as_int(k)
        assert k <= n
        c_outcome = self.get(outcome, 0)

        return comb(n, k) * c_outcome**k * (self.total - c_outcome) ** (n - k)

    @overload
    def explode(
        self,
        max_depth: IntegralLike,
        precision_limit: None = None,
    ) -> "H":
        ...

    @overload
    def explode(
        self,
        max_depth: None,
        precision_limit: Union[RationalLikeMixedU, RealLike],
    ) -> "H":
        ...

    @overload
    def explode(
        self,
        max_depth: None = None,
        *,
        precision_limit: Union[RationalLikeMixedU, RealLike],
    ) -> "H":
        ...

    @overload
    def explode(
        self,
        max_depth: None = None,
        precision_limit: None = None,
    ) -> "H":
        ...

    @deprecated
    @beartype
    def explode(
        self,
        max_depth: Optional[IntegralLike] = None,
        precision_limit: Optional[Union[RationalLikeMixedU, RealLike]] = None,
    ) -> "H":
        r"""
        !!! warning "Deprecated"

            This method has been deprecated and will be removed in a future release. See
            the [``explode`` function][dyce.evaluation.explode] for a more flexible
            alternative.

        Shorthand for ``#!python self.substitute(lambda h, outcome: outcome if len(h) == 1
        else h if outcome == max(h) else outcome, operator.__add__, max_depth,
        precision_limit)``.

        ``` python
        >>> H(6).explode(max_depth=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})

        ```

        This method guards against excessive recursion by returning ``#!python outcome``
        if the passed histogram has only one face. See the [``substitute``
        method][dyce.h.H.substitute].
        """

        def _explode(h: H, outcome: RealLike) -> HOrOutcomeT:
            return outcome if len(h) == 1 else h if outcome == max(h) else outcome

        if max_depth is not None and precision_limit is not None:
            raise ValueError("only one of max_depth and precision_limit is allowed")
        elif max_depth is not None:
            return self.substitute(_explode, __add__, max_depth)
        elif precision_limit is not None:
            return self.substitute(_explode, __add__, precision_limit=precision_limit)
        else:
            return self.substitute(_explode, __add__)

    @beartype
    def lowest_terms(self) -> "H":
        r"""
        Computes and returns a histogram whose nonzero counts share a greatest
        common divisor of 1.

        ``` python
        >>> df_obscured = H({-2: 0, -1: 2, 0: 2, 1: 2, 2: 0})
        >>> df_obscured.lowest_terms()
        H({-1: 1, 0: 1, 1: 1})

        ```
        """
        if self._lowest_terms is None:
            counts_gcd = gcd(*self.counts())

            if counts_gcd in (0, 1) and 0 not in self.counts():
                self._lowest_terms = self
            else:
                self._lowest_terms = type(self)(
                    (outcome, count // counts_gcd)
                    for outcome, count in self.items()
                    if count != 0
                )

        return self._lowest_terms

    @experimental
    @beartype
    def order_stat_for_n_at_pos(self, n: SupportsInt, pos: SupportsInt) -> "H":
        r"""
        !!! warning "Experimental"

            This method should be considered experimental and may change or disappear in
            future versions.

        Computes the probability distribution for each outcome appearing in at *pos* for
        *n* histograms. *pos* is a zero-based index.

        ``` python
        >>> d6avg = H((2, 3, 3, 4, 4, 5))
        >>> d6avg.order_stat_for_n_at_pos(5, 3)  # counts where outcome appears in the fourth of five positions
        H({2: 26, 3: 1432, 4: 4792, 5: 1526})

        ```

        The results show that, when rolling five six-sided “averaging” dice and sorting
        each roll, there are 26 ways where ``#!python 2`` appears at the fourth (index
        ``#!python 3``) position, 1432 ways where ``#!python 3`` appears at the fourth
        position, etc. This can be verified independently using the computationally
        expensive method of enumerating rolls and counting those that meet the criteria.

        ``` python
        >>> from dyce import P
        >>> p_5d6avg = 5@P(d6avg)
        >>> sum(count for roll, count in p_5d6avg.rolls_with_counts() if roll[3] == 5)
        1526

        ```

        Negative values for *pos* follow Python index semantics:

        ``` python
        >>> 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 computing the betas for *n* so they can be reused for varying
        values of *pos* in subsequent calls.
        """
        # See <https://math.stackexchange.com/q/4173084/226394> for motivation
        n = as_int(n)
        pos = as_int(pos)

        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)

    @beartype
    def remove(self, outcome: RealLike) -> "H":
        if outcome not in self:
            return self

        return type(self)(
            (orig_outcome, count)
            for orig_outcome, count in self.items()
            if orig_outcome != outcome
        )

    @overload
    def substitute(
        self,
        expand: _SubstituteExpandCallbackT,
        coalesce: _SubstituteCoalesceCallbackT = coalesce_replace,
    ) -> "H":
        ...

    @overload
    def substitute(
        self,
        expand: _SubstituteExpandCallbackT,
        coalesce: _SubstituteCoalesceCallbackT = coalesce_replace,
        *,
        max_depth: IntegralLike,
        precision_limit: None = None,
    ) -> "H":
        ...

    @overload
    def substitute(
        self,
        expand: _SubstituteExpandCallbackT,
        coalesce: _SubstituteCoalesceCallbackT,
        max_depth: IntegralLike,
        precision_limit: None = None,
    ) -> "H":
        ...

    @overload
    def substitute(
        self,
        expand: _SubstituteExpandCallbackT,
        coalesce: _SubstituteCoalesceCallbackT = coalesce_replace,
        *,
        max_depth: None,
        precision_limit: Union[RationalLikeMixedU, RealLike],
    ) -> "H":
        ...

    @overload
    def substitute(
        self,
        expand: _SubstituteExpandCallbackT,
        coalesce: _SubstituteCoalesceCallbackT,
        max_depth: None,
        precision_limit: Union[RationalLikeMixedU, RealLike],
    ) -> "H":
        ...

    @overload
    def substitute(
        self,
        expand: _SubstituteExpandCallbackT,
        coalesce: _SubstituteCoalesceCallbackT = coalesce_replace,
        max_depth: None = None,
        *,
        precision_limit: Union[RationalLikeMixedU, RealLike],
    ) -> "H":
        ...

    @overload
    def substitute(
        self,
        expand: _SubstituteExpandCallbackT,
        coalesce: _SubstituteCoalesceCallbackT = coalesce_replace,
        max_depth: None = None,
        precision_limit: None = None,
    ) -> "H":
        ...

    @deprecated
    @beartype
    def substitute(
        self,
        expand: _SubstituteExpandCallbackT,
        coalesce: _SubstituteCoalesceCallbackT = coalesce_replace,
        max_depth: Optional[IntegralLike] = None,
        precision_limit: Optional[Union[RationalLikeMixedU, RealLike]] = None,
    ) -> "H":
        r"""
        !!! warning "Deprecated"

            This method has been deprecated and will be removed in a future release. See
            the [``expandable`` decorator][dyce.evaluation.expandable] and
            [``foreach`` function][dyce.evaluation.foreach] for more flexible
            alternatives.

        Calls *expand* on each outcome. If *expand* returns a single outcome, it
        replaces the existing outcome. If it returns an [``H`` object][dyce.h.H],
        evaluation is performed again (recursively) on that object until a limit (either
        *max_depth* or *precision_limit*) is exhausted. *coalesce* is called on the
        original outcome and the expanded histogram or outcome and the returned
        histogram is “folded” into result. The default behavior for *coalesce* is to
        replace the outcome with the expanded histogram. Returned histograms are always
        reduced to their lowest terms.

        !!! note "*coalesce* is not called unless *expand* returns a histogram"

            If *expand* returns a single outcome, it *always* replaces the existing
            outcome. This is intentional. To return a single outcome, but trigger
            *coalesce*, characterize that outcome as a single-sided die (e.g.,
            ``#!python H({outcome: 1})``.

        See the [``coalesce_replace``][dyce.h.coalesce_replace] and
        [``lowest_terms``][dyce.h.H.lowest_terms] methods.

        !!! tip "Precision limits"

            The *max_depth* parameter is similar to an
            [``expandable``][dyce.evaluation.expandable]-decorated function’s limit
            argument when given a whole number. The *precision_limit* parameter is
            similar to an [``expandable``][dyce.evaluation.expandable]-decorated
            function’s limit argument being provided a fractional value. It is an error
            to provide values for both *max_depth* and *precision_limit*.
        """
        from .evaluation import HResult, LimitT, expandable

        if max_depth is not None and precision_limit is not None:
            raise ValueError("only one of max_depth and precision_limit is allowed")

        limit: Optional[LimitT] = (
            max_depth if precision_limit is None else precision_limit
        )

        @expandable(sentinel=self)
        def _expand(result: HResult) -> HOrOutcomeT:
            res = expand(result.h, result.outcome)

            return coalesce(_expand(res), result.outcome) if isinstance(res, H) else res

        return _expand(self, limit=limit)

    @beartype
    def vs(self, other: _OperandT) -> "H":
        r"""
        Compares the histogram with *other*. -1 represents where *other* is greater. 0
        represents where they are equal. 1 represents where *other* is less.

        Shorthand for ``#!python self.within(0, 0, other)``.

        ``` python
        >>> H(6).vs(H(4))
        H({-1: 6, 0: 4, 1: 14})
        >>> H(6).vs(H(4)) == H(6).within(0, 0, H(4))
        True

        ```

        See the [``within`` method][dyce.h.H.within].
        """
        return self.within(0, 0, other)

    @beartype
    def within(self, lo: RealLike, hi: RealLike, other: _OperandT = 0) -> "H":
        r"""
        Computes the difference between the histogram and *other*. -1 represents where that
        difference is less than *lo*. 0 represents where that difference between *lo*
        and *hi* (inclusive). 1 represents where that difference is greater than *hi*.

        ``` python
        >>> d6_2 = 2@H(6)
        >>> d6_2.within(7, 9)
        H({-1: 15, 0: 15, 1: 6})
        >>> print(d6_2.within(7, 9).format())
        avg |   -0.25
        std |    0.72
        var |    0.52
         -1 |  41.67% |####################
          0 |  41.67% |####################
          1 |  16.67% |########

        ```

        ``` python
        >>> d6_3, d8_2 = 3@H(6), 2@H(8)
        >>> d6_3.within(-1, 1, d8_2)  # 3d6 w/in 1 of 2d8
        H({-1: 3500, 0: 3412, 1: 6912})
        >>> print(d6_3.within(-1, 1, d8_2).format())
        avg |    0.25
        std |    0.83
        var |    0.69
         -1 |  25.32% |############
          0 |  24.68% |############
          1 |  50.00% |#########################

        ```
        """
        return self.map(_within(lo, hi), other)

    @beartype
    def zero_fill(self, outcomes: Iterable[RealLike]) -> "H":
        r"""
        Shorthand for ``#!python self.accumulate({outcome: 0 for outcome in
        outcomes})``.

        ``` python
        >>> 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.accumulate({outcome: 0 for outcome in outcomes})

    @overload
    def distribution(
        self,
    ) -> Iterator[tuple[RealLike, Fraction]]:
        ...

    @overload
    def distribution(
        self,
        rational_t: Callable[[int, int], _T],
    ) -> Iterator[tuple[RealLike, _T]]:
        ...

    @experimental
    @beartype
    def distribution(
        self,
        rational_t: Optional[Callable[[int, int], _T]] = None,
    ) -> Iterator[tuple[RealLike, _T]]:
        r"""
        Presentation helper function returning an iterator for each outcome/count or
        outcome/probability pair.

        ``` python
        >>> h = H((1, 2, 3, 3, 4, 4, 5, 6))
        >>> list(h.distribution())
        [(1, Fraction(1, 8)), (2, Fraction(1, 8)), (3, Fraction(1, 4)), (4, Fraction(1, 4)), (5, Fraction(1, 8)), (6, Fraction(1, 8))]
        >>> list(h.ge(3).distribution())
        [(False, Fraction(1, 4)), (True, Fraction(3, 4))]

        ```

        !!! warning "Experimental"

            The *rational_t* argument to this method should be considered experimental
            and may change or disappear in future versions.

        If provided, *rational_t* must be a callable that takes two ``#!python int``s (a
        numerator and denominator) and returns an instance of a desired (but otherwise
        arbitrary) type.

        ``` python
        >>> list(h.distribution(rational_t=lambda n, d: f"{n}/{d}"))
        [(1, '1/8'), (2, '1/8'), (3, '2/8'), (4, '2/8'), (5, '1/8'), (6, '1/8')]

        ```

        ``` python
        >>> import sympy
        >>> list(h.distribution(rational_t=sympy.Rational))
        [(1, 1/8), (2, 1/8), (3, 1/4), (4, 1/4), (5, 1/8), (6, 1/8)]

        ```

        ``` python
        >>> import sage.rings.rational  # doctest: +SKIP
        >>> list(h.distribution(rational_t=lambda n, d: sage.rings.rational.Rational((n, d))))  # doctest: +SKIP
        [(1, 1/8), (2, 1/8), (3, 1/4), (4, 1/4), (5, 1/8), (6, 1/8)]

        ```

        !!! note

            The arguments passed to *rational_t* are not reduced to the lowest terms.

        The *rational_t* argument is a convenience. Iteration or comprehension can be
        used to accomplish something similar.

        ``` python
        >>> [(outcome, f"{probability.numerator}/{probability.denominator}") for outcome, probability in (h).distribution()]
        [(1, '1/8'), (2, '1/8'), (3, '1/4'), (4, '1/4'), (5, '1/8'), (6, '1/8')]

        ```

        Many number implementations can convert directly from ``#!python
        fractions.Fraction``s.

        ``` python
        >>> import sympy.abc
        >>> [(outcome, sympy.Rational(probability)) for outcome, probability in (h + sympy.abc.x).distribution()]
        [(x + 1, 1/8), (x + 2, 1/8), (x + 3, 1/4), (x + 4, 1/4), (x + 5, 1/8), (x + 6, 1/8)]

        ```

        ``` python
        >>> import sage.rings.rational  # doctest: +SKIP
        >>> [(outcome, sage.rings.rational.Rational(probability)) for outcome, probability in h.distribution()]  # doctest: +SKIP
        [(1, 1/6), (2, 1/6), (3, 1/3), (4, 1/3), (5, 1/6), (6, 1/6)]

        ```
        """
        if rational_t is None:
            # TODO(posita): See <https://github.com/python/mypy/issues/10854#issuecomment-1663057450>
            rational_t = Fraction  # type: ignore [assignment]
            assert rational_t is not None

        total = sum(self.values()) or 1

        return (
            (outcome, rational_t(self[outcome], total))
            for outcome in sorted_outcomes(self)
        )

    @beartype
    def distribution_xy(
        self,
    ) -> tuple[tuple[RealLike, ...], tuple[float, ...]]:
        r"""
        Presentation helper function returning an iterator for a “zipped” arrangement of the
        output from the [``distribution`` method][dyce.h.H.distribution] and ensures the
        values are ``#!python float``s.

        ``` python
        >>> list(H(6).distribution())
        [(1, Fraction(1, 6)), (2, Fraction(1, 6)), (3, Fraction(1, 6)), (4, Fraction(1, 6)), (5, Fraction(1, 6)), (6, Fraction(1, 6))]
        >>> H(6).distribution_xy()
        ((1, 2, 3, 4, 5, 6), (0.16666666, 0.16666666, 0.16666666, 0.16666666, 0.16666666, 0.16666666))

        ```
        """
        # TODO(posita): See <https://github.com/python/typing/issues/193>
        return tuple(  # type: ignore [return-value]
            zip(
                *(
                    (outcome, float(probability))
                    for outcome, probability in self.distribution()
                )
            )
        )

    @beartype
    def format(
        self,
        width: SupportsInt = _ROW_WIDTH,
        scaled: bool = False,
        tick: str = "#",
        sep: str = os.linesep,
    ) -> str:
        r"""
        Returns a formatted string representation of the histogram. If *width* is
        greater than zero, a horizontal bar ASCII graph is printed using *tick* and
        *sep* (which are otherwise ignored if *width* is zero or less).

        ``` python
        >>> print(H(6).format(width=0))
        {avg: 3.50, 1: 16.67%, 2: 16.67%, 3: 16.67%, 4: 16.67%, 5: 16.67%, 6: 16.67%}

        ```

        ``` python
        >>> print((2@H(6)).zero_fill(range(1, 21)).format(tick="@"))
        avg |    7.00
        std |    2.42
        var |    5.83
          1 |   0.00% |
          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% |@
         13 |   0.00% |
         14 |   0.00% |
         15 |   0.00% |
         16 |   0.00% |
         17 |   0.00% |
         18 |   0.00% |
         19 |   0.00% |
         20 |   0.00% |

        ```

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

        ``` python
        >>> h = (2@H(6)).ge(7)
        >>> print(f"{' 65 chars wide -->|':->65}")
        ---------------------------------------------- 65 chars wide -->|
        >>> print(H(1).format(scaled=False))
        avg |    1.00
        std |    0.00
        var |    0.00
          1 | 100.00% |##################################################
        >>> print(h.format(scaled=False))
        avg |    0.58
        std |    0.49
        var |    0.24
          0 |  41.67% |####################
          1 |  58.33% |#############################
        >>> print(h.format(scaled=True))
        avg |    0.58
        std |    0.49
        var |    0.24
          0 |  41.67% |###################################
          1 |  58.33% |##################################################

        ```
        """
        width = as_int(width)

        # We convert various values herein to native ints and floats because number
        # tower implementations sometimes neglect to implement __format__ properly (or
        # at all). (I'm looking at you, sage.rings.…!)
        try:
            mu: RealLike = float(self.mean())
        except (OverflowError, TypeError):
            mu = self.mean()

        if width <= 0:

            def _parts() -> Iterator[str]:
                yield f"avg: {mu:.2f}"

                for (
                    outcome,
                    probability,
                ) in self.distribution():
                    probability_f = float(probability)
                    yield f"{outcome}:{probability_f:7.2%}"

            return "{" + ", ".join(_parts()) + "}"
        else:
            w = width - 15

            def _lines() -> Iterator[str]:
                try:
                    yield f"avg | {mu:7.2f}"
                    std = float(self.stdev(mu))
                    var = float(self.variance(mu))
                    yield f"std | {std:7.2f}"
                    yield f"var | {var:7.2f}"
                except (OverflowError, TypeError) as exc:
                    warnings.warn(f"{str(exc)}; mu: {mu}")

                if self:
                    outcomes, probabilities = self.distribution_xy()
                    tick_scale = max(probabilities) if scaled else 1.0

                    for outcome, probability in zip(outcomes, probabilities):
                        try:
                            outcome_str = f"{outcome: 3}"
                        except (TypeError, ValueError):
                            outcome_str = str(outcome)
                            outcome_str = f"{outcome_str: >3}"

                        ticks = tick * int(w * probability / tick_scale)
                        probability_f = float(probability)
                        yield f"{outcome_str} | {probability_f:7.2%} |{ticks}"

            return sep.join(_lines())

    @beartype
    def mean(self) -> RealLike:
        r"""
        Returns the mean of the weighted outcomes (or 0.0 if there are no outcomes).
        """
        numerator: float
        denominator: float
        numerator = denominator = 0

        for outcome, count in self.items():
            numerator += outcome * count
            denominator += count

        return numerator / (denominator or 1)

    @beartype
    def stdev(self, mu: Optional[RealLike] = None) -> RealLike:
        r"""
        Shorthand for ``#!python math.sqrt(self.variance(mu))``.
        """
        return sqrt(self.variance(mu))

    @beartype
    def variance(self, mu: Optional[RealLike] = None) -> RealLike:
        r"""
        Returns the variance of the weighted outcomes. If provided, *mu* is used as the mean
        (to avoid duplicate computation).
        """
        mu = mu if mu else self.mean()
        numerator: float
        denominator: float
        numerator = denominator = 0

        for outcome, count in self.items():
            numerator += outcome**2 * count
            denominator += count

        # While floating point overflow is impossible to eliminate, we avoid it under
        # some circumstances by exploiting the equivalence of E[(X - E[X])**2] and the
        # more efficient E[X**2] - E[X]**2. See
        # <https://dlsun.github.io/probability/variance.html>.
        return numerator / (denominator or 1) - mu**2

    @beartype
    def roll(self) -> RealLike:
        r"""
        Returns a (weighted) random outcome.
        """
        return (
            rng.RNG.choices(
                population=tuple(self.outcomes()),
                weights=tuple(self.counts()),
                k=1,
            )[0]
            if self
            else 0
        )

    def _order_stat_func_for_n(self, n: int) -> Callable[[int], "H"]:
        betas_by_outcome: dict[RealLike, tuple[H, H]] = {}

        for outcome in self.outcomes():
            betas_by_outcome[outcome] = (
                n @ self.le(outcome),
                n @ self.lt(outcome),
            )

        def _gen_h_items_at_pos(pos: int) -> Iterator[_OutcomeCountT]:
            for outcome, (h_le, h_lt) in betas_by_outcome.items():
                yield (
                    outcome,
                    h_le.gt(pos).get(True, 0) - h_lt.gt(pos).get(True, 0),
                )

        @beartype
        def order_stat_for_n_at_pos(pos: int) -> "H":
            return type(self)(_gen_h_items_at_pos(pos))

        return order_stat_for_n_at_pos

__slots__: Any = ('_h', '_hash', '_lowest_terms', '_order_stat_funcs_by_n', '_total') class-attribute instance-attribute

total: int property

Experimental

This property should be considered experimental and may change or disappear in future versions.

Equivalent to sum(self.counts()).

__abs__() -> H

Source code in dyce/h.py
691
692
693
@beartype
def __abs__(self) -> "H":
    return self.umap(__abs__)

__add__(other: _OperandT) -> H

Source code in dyce/h.py
515
516
517
518
519
520
@beartype
def __add__(self, other: _OperandT) -> "H":
    try:
        return self.map(__add__, other)
    except NotImplementedError:
        return NotImplemented

__and__(other: Union[SupportsInt, H, HableT]) -> H

Source code in dyce/h.py
629
630
631
632
633
634
635
636
637
638
@beartype
# TODO(posita): See <https://github.com/beartype/beartype/issues/152>
def __and__(self, other: Union[SupportsInt, "H", "HableT"]) -> "H":
    try:
        if isinstance(other, SupportsInt):
            other = as_int(other)

        return self.map(__and__, other)
    except (NotImplementedError, TypeError):
        return NotImplemented

__bool__() -> int

Source code in dyce/h.py
491
492
493
@beartype
def __bool__(self) -> int:
    return bool(self.total)

__contains__(key: RealLike) -> bool

Source code in dyce/h.py
511
512
513
@beartype
def __contains__(self, key: RealLike) -> bool:  # type: ignore [override]
    return key in self._h

__eq__(other) -> bool

Source code in dyce/h.py
466
467
468
469
470
471
472
473
@beartype
def __eq__(self, other) -> bool:
    if isinstance(other, HableT):
        return __eq__(self, other.h())
    elif isinstance(other, H):
        return __eq__(self.lowest_terms()._h, other.lowest_terms()._h)
    else:
        return super().__eq__(other)

__floordiv__(other: _OperandT) -> H

Source code in dyce/h.py
587
588
589
590
591
592
@beartype
def __floordiv__(self, other: _OperandT) -> "H":
    try:
        return self.map(__floordiv__, other)
    except NotImplementedError:
        return NotImplemented

__getitem__(key: RealLike) -> int

Source code in dyce/h.py
499
500
501
@beartype
def __getitem__(self, key: RealLike) -> int:
    return __getitem__(self._h, key)

__hash__() -> int

Source code in dyce/h.py
484
485
486
487
488
489
@beartype
def __hash__(self) -> int:
    if self._hash is None:
        self._hash = hash(frozenset(self.lowest_terms().items()))

    return self._hash

__init__(items: _SourceT) -> None

Initializer.

Source code in dyce/h.py
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
@beartype
def __init__(self, items: _SourceT) -> None:
    r"Initializer."
    super().__init__()
    self._h: _MappingT

    if isinstance(items, H):
        self._h = items._h
    elif isinstance(items, SupportsInt):
        if items == 0:
            self._h = {}
        else:
            simple_init = as_int(items)
            outcome_range = range(
                simple_init if simple_init < 0 else 1,
                0 if simple_init < 0 else simple_init + 1,
            )

            # if isinstance(items, RealLike):
            #     outcome_type = type(items)
            #     self._h = {outcome_type(i): 1 for i in outcome_range}
            # else:
            #     self._h = {i: 1 for i in outcome_range}
            assert isinstance(items, RealLike)
            outcome_type = type(items)
            self._h = {outcome_type(i): 1 for i in outcome_range}
    elif isinstance(items, HableT):
        self._h = items.h()._h
    elif isinstance(items, IterableC):
        if isinstance(items, Mapping):
            items = items.items()

        # items is either an Iterable[RealLike] or an Iterable[tuple[RealLike,
        # SupportsInt]] (although this technically supports Iterable[RealLike |
        # tuple[RealLike, SupportsInt]])
        self._h = {}
        sorted_items = list(items)

        try:
            sorted_items.sort()
        except TypeError:
            sorted_items.sort(key=natural_key)

        # As of Python 3.7, insertion order of keys is preserved
        for item in sorted_items:
            if isinstance(item, tuple):
                outcome, count = item
                count = as_int(count)
            else:
                outcome = item
                count = 1

            if count < 0:
                raise ValueError(f"count for {outcome} cannot be negative")

            if outcome not in self._h:
                self._h[outcome] = 0

            self._h[outcome] += count
    else:
        raise TypeError(f"unrecognized initializer type {items!r}")

    # We can't use something like functools.lru_cache for these values because those
    # mechanisms call this object's __hash__ method which relies on both of these
    # and we don't want a circular dependency when computing this object's hash.
    self._hash: Optional[int] = None
    self._total: int = sum(self._h.values())
    self._lowest_terms: Optional[H] = None

    # We don't use functools' caching mechanisms generally because they don't
    # present a good mechanism for scoping the cache to object instances such that
    # the cache will be purged when the object is deleted. functools.cached_property
    # is an exception, but it requires that objects have proper __dict__ values,
    # which Hs do not. So we basically do what functools.cached_property does, but
    # without a __dict__.
    self._order_stat_funcs_by_n: dict[int, Callable[[int], H]] = {}

__invert__() -> H

Source code in dyce/h.py
695
696
697
@beartype
def __invert__(self) -> "H":
    return self.umap(__invert__)

__iter__() -> Iterator[RealLike]

Source code in dyce/h.py
503
504
505
@beartype
def __iter__(self) -> Iterator[RealLike]:
    return iter(self._h)

__len__() -> int

Source code in dyce/h.py
495
496
497
@beartype
def __len__(self) -> int:
    return len(self._h)

__matmul__(other: SupportsInt) -> H

Source code in dyce/h.py
557
558
559
560
561
562
563
564
565
566
567
@beartype
def __matmul__(self, other: SupportsInt) -> "H":
    try:
        other = as_int(other)
    except TypeError:
        return NotImplemented

    if other < 0:
        raise ValueError("argument cannot be negative")
    else:
        return sum_h(repeat(self, other))

__mod__(other: _OperandT) -> H

Source code in dyce/h.py
601
602
603
604
605
606
@beartype
def __mod__(self, other: _OperandT) -> "H":
    try:
        return self.map(__mod__, other)
    except NotImplementedError:
        return NotImplemented

__mul__(other: _OperandT) -> H

Source code in dyce/h.py
543
544
545
546
547
548
@beartype
def __mul__(self, other: _OperandT) -> "H":
    try:
        return self.map(__mul__, other)
    except NotImplementedError:
        return NotImplemented

__ne__(other) -> bool

Source code in dyce/h.py
475
476
477
478
479
480
481
482
@beartype
def __ne__(self, other) -> bool:
    if isinstance(other, HableT):
        return __ne__(self, other.h())
    elif isinstance(other, H):
        return not __eq__(self, other)
    else:
        return super().__ne__(other)

__neg__() -> H

Source code in dyce/h.py
683
684
685
@beartype
def __neg__(self) -> "H":
    return self.umap(__neg__)

__or__(other: Union[SupportsInt, H, HableT]) -> H

Source code in dyce/h.py
665
666
667
668
669
670
671
672
673
674
@beartype
# TODO(posita): See <https://github.com/beartype/beartype/issues/152>
def __or__(self, other: Union[SupportsInt, "H", "HableT"]) -> "H":
    try:
        if isinstance(other, SupportsInt):
            other = as_int(other)

        return self.map(__or__, other)
    except (NotImplementedError, TypeError):
        return NotImplemented

__pos__() -> H

Source code in dyce/h.py
687
688
689
@beartype
def __pos__(self) -> "H":
    return self.umap(__pos__)

__pow__(other: _OperandT) -> H

Source code in dyce/h.py
615
616
617
618
619
620
@beartype
def __pow__(self, other: _OperandT) -> "H":
    try:
        return self.map(__pow__, other)
    except NotImplementedError:
        return NotImplemented

__radd__(other: RealLike) -> H

Source code in dyce/h.py
522
523
524
525
526
527
@beartype
def __radd__(self, other: RealLike) -> "H":
    try:
        return self.rmap(other, __add__)
    except NotImplementedError:
        return NotImplemented

__rand__(other: SupportsInt) -> H

Source code in dyce/h.py
640
641
642
643
644
645
@beartype
def __rand__(self, other: SupportsInt) -> "H":
    try:
        return self.rmap(as_int(other), __and__)
    except (NotImplementedError, TypeError):
        return NotImplemented

__repr__() -> str

Source code in dyce/h.py
462
463
464
@beartype
def __repr__(self) -> str:
    return f"{type(self).__name__}({dict.__repr__(self._h)})"

__reversed__() -> Iterator[RealLike]

Source code in dyce/h.py
507
508
509
@beartype
def __reversed__(self) -> Iterator[RealLike]:
    return reversed(self._h)

__rfloordiv__(other: RealLike) -> H

Source code in dyce/h.py
594
595
596
597
598
599
@beartype
def __rfloordiv__(self, other: RealLike) -> "H":
    try:
        return self.rmap(other, __floordiv__)
    except NotImplementedError:
        return NotImplemented

__rmatmul__(other: SupportsInt) -> H

Source code in dyce/h.py
569
570
571
@beartype
def __rmatmul__(self, other: SupportsInt) -> "H":
    return self.__matmul__(other)

__rmod__(other: RealLike) -> H

Source code in dyce/h.py
608
609
610
611
612
613
@beartype
def __rmod__(self, other: RealLike) -> "H":
    try:
        return self.rmap(other, __mod__)
    except NotImplementedError:
        return NotImplemented

__rmul__(other: RealLike) -> H

Source code in dyce/h.py
550
551
552
553
554
555
@beartype
def __rmul__(self, other: RealLike) -> "H":
    try:
        return self.rmap(other, __mul__)
    except NotImplementedError:
        return NotImplemented

__ror__(other: SupportsInt) -> H

Source code in dyce/h.py
676
677
678
679
680
681
@beartype
def __ror__(self, other: SupportsInt) -> "H":
    try:
        return self.rmap(as_int(other), __or__)
    except (NotImplementedError, TypeError):
        return NotImplemented

__rpow__(other: RealLike) -> H

Source code in dyce/h.py
622
623
624
625
626
627
@beartype
def __rpow__(self, other: RealLike) -> "H":
    try:
        return self.rmap(other, __pow__)
    except NotImplementedError:
        return NotImplemented

__rsub__(other: RealLike) -> H

Source code in dyce/h.py
536
537
538
539
540
541
@beartype
def __rsub__(self, other: RealLike) -> "H":
    try:
        return self.rmap(other, __sub__)
    except NotImplementedError:
        return NotImplemented

__rtruediv__(other: RealLike) -> H

Source code in dyce/h.py
580
581
582
583
584
585
@beartype
def __rtruediv__(self, other: RealLike) -> "H":
    try:
        return self.rmap(other, __truediv__)
    except NotImplementedError:
        return NotImplemented

__rxor__(other: SupportsInt) -> H

Source code in dyce/h.py
658
659
660
661
662
663
@beartype
def __rxor__(self, other: SupportsInt) -> "H":
    try:
        return self.rmap(as_int(other), __xor__)
    except (NotImplementedError, TypeError):
        return NotImplemented

__sub__(other: _OperandT) -> H

Source code in dyce/h.py
529
530
531
532
533
534
@beartype
def __sub__(self, other: _OperandT) -> "H":
    try:
        return self.map(__sub__, other)
    except NotImplementedError:
        return NotImplemented

__truediv__(other: _OperandT) -> H

Source code in dyce/h.py
573
574
575
576
577
578
@beartype
def __truediv__(self, other: _OperandT) -> "H":
    try:
        return self.map(__truediv__, other)
    except NotImplementedError:
        return NotImplemented

__xor__(other: Union[SupportsInt, H, HableT]) -> H

Source code in dyce/h.py
647
648
649
650
651
652
653
654
655
656
@beartype
# TODO(posita): See <https://github.com/beartype/beartype/issues/152>
def __xor__(self, other: Union[SupportsInt, "H", "HableT"]) -> "H":
    try:
        if isinstance(other, SupportsInt):
            other = as_int(other)

        return self.map(__xor__, other)
    except NotImplementedError:
        return NotImplemented

accumulate(other: _SourceT) -> H

Accumulates counts.

1
2
>>> H(4).accumulate(H(6))
H({1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1})
Source code in dyce/h.py
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
@beartype
def accumulate(self, other: _SourceT) -> "H":
    r"""
    Accumulates counts.

    ``` python
    >>> H(4).accumulate(H(6))
    H({1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1})

    ```
    """
    if not isinstance(other, H):
        other = H(other)

    return type(self)(cast(_SourceT, chain(self.items(), other.items())))

counts() -> ValuesView[int]

More descriptive synonym for the values method.

Source code in dyce/h.py
699
700
701
702
703
704
@beartype
def counts(self) -> ValuesView[int]:
    r"""
    More descriptive synonym for the [``values`` method][dyce.h.H.values].
    """
    return self._h.values()

distribution(rational_t: Optional[Callable[[int, int], _T]] = None) -> Iterator[tuple[RealLike, _T]]

Presentation helper function returning an iterator for each outcome/count or outcome/probability pair.

1
2
3
4
5
>>> h = H((1, 2, 3, 3, 4, 4, 5, 6))
>>> list(h.distribution())
[(1, Fraction(1, 8)), (2, Fraction(1, 8)), (3, Fraction(1, 4)), (4, Fraction(1, 4)), (5, Fraction(1, 8)), (6, Fraction(1, 8))]
>>> list(h.ge(3).distribution())
[(False, Fraction(1, 4)), (True, Fraction(3, 4))]

Experimental

The rational_t argument to this method should be considered experimental and may change or disappear in future versions.

If provided, rational_t must be a callable that takes two ints (a numerator and denominator) and returns an instance of a desired (but otherwise arbitrary) type.

1
2
>>> list(h.distribution(rational_t=lambda n, d: f"{n}/{d}"))
[(1, '1/8'), (2, '1/8'), (3, '2/8'), (4, '2/8'), (5, '1/8'), (6, '1/8')]
1
2
3
>>> import sympy
>>> list(h.distribution(rational_t=sympy.Rational))
[(1, 1/8), (2, 1/8), (3, 1/4), (4, 1/4), (5, 1/8), (6, 1/8)]
1
2
3
>>> import sage.rings.rational  # doctest: +SKIP
>>> list(h.distribution(rational_t=lambda n, d: sage.rings.rational.Rational((n, d))))  # doctest: +SKIP
[(1, 1/8), (2, 1/8), (3, 1/4), (4, 1/4), (5, 1/8), (6, 1/8)]

Note

The arguments passed to rational_t are not reduced to the lowest terms.

The rational_t argument is a convenience. Iteration or comprehension can be used to accomplish something similar.

1
2
>>> [(outcome, f"{probability.numerator}/{probability.denominator}") for outcome, probability in (h).distribution()]
[(1, '1/8'), (2, '1/8'), (3, '1/4'), (4, '1/4'), (5, '1/8'), (6, '1/8')]

Many number implementations can convert directly from fractions.Fractions.

1
2
3
>>> import sympy.abc
>>> [(outcome, sympy.Rational(probability)) for outcome, probability in (h + sympy.abc.x).distribution()]
[(x + 1, 1/8), (x + 2, 1/8), (x + 3, 1/4), (x + 4, 1/4), (x + 5, 1/8), (x + 6, 1/8)]
1
2
3
>>> import sage.rings.rational  # doctest: +SKIP
>>> [(outcome, sage.rings.rational.Rational(probability)) for outcome, probability in h.distribution()]  # doctest: +SKIP
[(1, 1/6), (2, 1/6), (3, 1/3), (4, 1/3), (5, 1/6), (6, 1/6)]
Source code in dyce/h.py
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
@experimental
@beartype
def distribution(
    self,
    rational_t: Optional[Callable[[int, int], _T]] = None,
) -> Iterator[tuple[RealLike, _T]]:
    r"""
    Presentation helper function returning an iterator for each outcome/count or
    outcome/probability pair.

    ``` python
    >>> h = H((1, 2, 3, 3, 4, 4, 5, 6))
    >>> list(h.distribution())
    [(1, Fraction(1, 8)), (2, Fraction(1, 8)), (3, Fraction(1, 4)), (4, Fraction(1, 4)), (5, Fraction(1, 8)), (6, Fraction(1, 8))]
    >>> list(h.ge(3).distribution())
    [(False, Fraction(1, 4)), (True, Fraction(3, 4))]

    ```

    !!! warning "Experimental"

        The *rational_t* argument to this method should be considered experimental
        and may change or disappear in future versions.

    If provided, *rational_t* must be a callable that takes two ``#!python int``s (a
    numerator and denominator) and returns an instance of a desired (but otherwise
    arbitrary) type.

    ``` python
    >>> list(h.distribution(rational_t=lambda n, d: f"{n}/{d}"))
    [(1, '1/8'), (2, '1/8'), (3, '2/8'), (4, '2/8'), (5, '1/8'), (6, '1/8')]

    ```

    ``` python
    >>> import sympy
    >>> list(h.distribution(rational_t=sympy.Rational))
    [(1, 1/8), (2, 1/8), (3, 1/4), (4, 1/4), (5, 1/8), (6, 1/8)]

    ```

    ``` python
    >>> import sage.rings.rational  # doctest: +SKIP
    >>> list(h.distribution(rational_t=lambda n, d: sage.rings.rational.Rational((n, d))))  # doctest: +SKIP
    [(1, 1/8), (2, 1/8), (3, 1/4), (4, 1/4), (5, 1/8), (6, 1/8)]

    ```

    !!! note

        The arguments passed to *rational_t* are not reduced to the lowest terms.

    The *rational_t* argument is a convenience. Iteration or comprehension can be
    used to accomplish something similar.

    ``` python
    >>> [(outcome, f"{probability.numerator}/{probability.denominator}") for outcome, probability in (h).distribution()]
    [(1, '1/8'), (2, '1/8'), (3, '1/4'), (4, '1/4'), (5, '1/8'), (6, '1/8')]

    ```

    Many number implementations can convert directly from ``#!python
    fractions.Fraction``s.

    ``` python
    >>> import sympy.abc
    >>> [(outcome, sympy.Rational(probability)) for outcome, probability in (h + sympy.abc.x).distribution()]
    [(x + 1, 1/8), (x + 2, 1/8), (x + 3, 1/4), (x + 4, 1/4), (x + 5, 1/8), (x + 6, 1/8)]

    ```

    ``` python
    >>> import sage.rings.rational  # doctest: +SKIP
    >>> [(outcome, sage.rings.rational.Rational(probability)) for outcome, probability in h.distribution()]  # doctest: +SKIP
    [(1, 1/6), (2, 1/6), (3, 1/3), (4, 1/3), (5, 1/6), (6, 1/6)]

    ```
    """
    if rational_t is None:
        # TODO(posita): See <https://github.com/python/mypy/issues/10854#issuecomment-1663057450>
        rational_t = Fraction  # type: ignore [assignment]
        assert rational_t is not None

    total = sum(self.values()) or 1

    return (
        (outcome, rational_t(self[outcome], total))
        for outcome in sorted_outcomes(self)
    )

distribution_xy() -> tuple[tuple[RealLike, ...], tuple[float, ...]]

Presentation helper function returning an iterator for a “zipped” arrangement of the output from the distribution method and ensures the values are floats.

1
2
3
4
>>> list(H(6).distribution())
[(1, Fraction(1, 6)), (2, Fraction(1, 6)), (3, Fraction(1, 6)), (4, Fraction(1, 6)), (5, Fraction(1, 6)), (6, Fraction(1, 6))]
>>> H(6).distribution_xy()
((1, 2, 3, 4, 5, 6), (0.16666666, 0.16666666, 0.16666666, 0.16666666, 0.16666666, 0.16666666))
Source code in dyce/h.py
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
@beartype
def distribution_xy(
    self,
) -> tuple[tuple[RealLike, ...], tuple[float, ...]]:
    r"""
    Presentation helper function returning an iterator for a “zipped” arrangement of the
    output from the [``distribution`` method][dyce.h.H.distribution] and ensures the
    values are ``#!python float``s.

    ``` python
    >>> list(H(6).distribution())
    [(1, Fraction(1, 6)), (2, Fraction(1, 6)), (3, Fraction(1, 6)), (4, Fraction(1, 6)), (5, Fraction(1, 6)), (6, Fraction(1, 6))]
    >>> H(6).distribution_xy()
    ((1, 2, 3, 4, 5, 6), (0.16666666, 0.16666666, 0.16666666, 0.16666666, 0.16666666, 0.16666666))

    ```
    """
    # TODO(posita): See <https://github.com/python/typing/issues/193>
    return tuple(  # type: ignore [return-value]
        zip(
            *(
                (outcome, float(probability))
                for outcome, probability in self.distribution()
            )
        )
    )

draw(outcomes: Optional[Union[RealLike, Iterable[RealLike], _MappingT]] = None) -> H

Experimental

This property should be considered experimental and may change or disappear in future versions.

Returns a new H object where the counts associated with outcomes has been updated. This may be useful for using histograms to model decks of cards (rather than dice). If outcome is None, this is equivalent to self.draw(self.roll()).

If outcomes is a single value, that value’s count is decremented by one. If outcomes is an iterable of values, those values’ outcomes are decremented by one for each time that outcome appears. If outcomes is a mapping of outcomes to counts, those outcomes are decremented by the respective counts.

Counts are not reduced and zero counts are preserved. To reduce, call the lowest_terms method.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> H(6).draw()
H({1: 1, 2: 1, 3: 1, 4: 0, 5: 1, 6: 1})

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

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

>>> h = H(6).accumulate(H(4)) ; h
H({1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1})
>>> h.draw({1: 2, 4: 1, 6: 1})
H({1: 0, 2: 2, 3: 2, 4: 1, 5: 1, 6: 0})

Negative counts can be used to increase counts

Where outcomes is a mapping of outcomes to counts, negative counts can be used to increase or “add” outcomes’ counts.

1
2
>>> H(4).draw({5: -1})
H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1})
Source code in dyce/h.py
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
@beartype
def draw(
    self,
    outcomes: Optional[Union[RealLike, Iterable[RealLike], _MappingT]] = None,
) -> "H":
    r"""
    !!! warning "Experimental"

        This property should be considered experimental and may change or disappear
        in future versions.

    Returns a new [``H`` object][dyce.h.H] where the counts associated with
    *outcomes* has been updated. This may be useful for using histograms to model
    decks of cards (rather than dice). If *outcome* is ``#!python None``, this is
    equivalent to ``#!python self.draw(self.roll())``.

    If *outcomes* is a single value, that value’s count is decremented by one. If
    *outcomes* is an iterable of values, those values’ outcomes are decremented by
    one for each time that outcome appears. If *outcomes* is a mapping of outcomes
    to counts, those outcomes are decremented by the respective counts.

    Counts are not reduced and zero counts are preserved. To reduce, call the
    [``lowest_terms`` method][dyce.h.H.lowest_terms].

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

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

      -- END MONKEY PATCH -->

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

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

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

    >>> h = H(6).accumulate(H(4)) ; h
    H({1: 2, 2: 2, 3: 2, 4: 2, 5: 1, 6: 1})
    >>> h.draw({1: 2, 4: 1, 6: 1})
    H({1: 0, 2: 2, 3: 2, 4: 1, 5: 1, 6: 0})

    ```

    !!! tip "Negative counts can be used to increase counts"

        Where *outcomes* is a mapping of outcomes to counts, negative counts can be
        used to *increase* or “add” outcomes’ counts.

        ``` python
        >>> H(4).draw({5: -1})
        H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1})

        ```
    """
    if outcomes is None:
        return self.draw(self.roll())

    if isinstance(outcomes, RealLike):
        outcomes = (outcomes,)

    to_draw_outcome_counts = Counter(outcomes)
    self_outcome_counts = Counter(self)
    # This approach is necessary because Counter.__sub__ does not preserve negative
    # counts and Counter.subtract modifies the counter in-place
    new_outcome_counts = Counter(self_outcome_counts)
    new_outcome_counts.subtract(to_draw_outcome_counts)
    would_go_negative = set(+to_draw_outcome_counts) - set(+self_outcome_counts)

    if would_go_negative:
        raise ValueError(f"outcomes to be drawn {would_go_negative} not in {self}")

    zeros = set(self_outcome_counts) - set(new_outcome_counts)

    for outcome in zeros:
        new_outcome_counts[outcome] = 0

    return type(self)(new_outcome_counts)

eq(other: _OperandT) -> H

Shorthand for self.map(operator.__eq__, other).umap(bool).

1
2
>>> H(6).eq(3)
H({False: 5, True: 1})

See the map and umap methods.

Source code in dyce/h.py
942
943
944
945
946
947
948
949
950
951
952
953
954
955
@beartype
def eq(self, other: _OperandT) -> "H":
    r"""
    Shorthand for ``#!python self.map(operator.__eq__, other).umap(bool)``.

    ``` python
    >>> H(6).eq(3)
    H({False: 5, True: 1})

    ```

    See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
    """
    return self.map(__eq__, other).umap(bool)

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

Experimental

This method should be considered experimental and may change or disappear in future versions.

Computes (in constant time) and returns the number of times outcome appears exactly k times among n@self. This is 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
Source code in dyce/h.py
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
@experimental
@beartype
def exactly_k_times_in_n(
    self,
    outcome: RealLike,
    n: SupportsInt,
    k: SupportsInt,
) -> int:
    r"""
    !!! warning "Experimental"

        This method should be considered experimental and may change or disappear in
        future versions.

    Computes (in constant time) and returns the number of times *outcome* appears
    exactly *k* times among ``#!python n@self``. This is a more efficient
    alternative to ``#!python (n@(self.eq(outcome)))[k]``.

    ``` python
    >>> 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

    ```
    """
    n = as_int(n)
    k = as_int(k)
    assert k <= n
    c_outcome = self.get(outcome, 0)

    return comb(n, k) * c_outcome**k * (self.total - c_outcome) ** (n - k)

explode(max_depth: Optional[IntegralLike] = None, precision_limit: Optional[Union[RationalLikeMixedU, RealLike]] = None) -> H

Deprecated

This method has been deprecated and will be removed in a future release. See the explode function for a more flexible alternative.

Shorthand for self.substitute(lambda h, outcome: outcome if len(h) == 1else h if outcome == max(h) else outcome, operator.__add__, max_depth,precision_limit).

1
2
>>> H(6).explode(max_depth=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})

This method guards against excessive recursion by returning outcome if the passed histogram has only one face. See the substitute method.

Source code in dyce/h.py
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
@deprecated
@beartype
def explode(
    self,
    max_depth: Optional[IntegralLike] = None,
    precision_limit: Optional[Union[RationalLikeMixedU, RealLike]] = None,
) -> "H":
    r"""
    !!! warning "Deprecated"

        This method has been deprecated and will be removed in a future release. See
        the [``explode`` function][dyce.evaluation.explode] for a more flexible
        alternative.

    Shorthand for ``#!python self.substitute(lambda h, outcome: outcome if len(h) == 1
    else h if outcome == max(h) else outcome, operator.__add__, max_depth,
    precision_limit)``.

    ``` python
    >>> H(6).explode(max_depth=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})

    ```

    This method guards against excessive recursion by returning ``#!python outcome``
    if the passed histogram has only one face. See the [``substitute``
    method][dyce.h.H.substitute].
    """

    def _explode(h: H, outcome: RealLike) -> HOrOutcomeT:
        return outcome if len(h) == 1 else h if outcome == max(h) else outcome

    if max_depth is not None and precision_limit is not None:
        raise ValueError("only one of max_depth and precision_limit is allowed")
    elif max_depth is not None:
        return self.substitute(_explode, __add__, max_depth)
    elif precision_limit is not None:
        return self.substitute(_explode, __add__, precision_limit=precision_limit)
    else:
        return self.substitute(_explode, __add__)

foreach(dependent_term: Callable[..., HOrOutcomeT], **independent_sources: _SourceT) -> H classmethod

Deprecated

This method has been deprecated and will be removed in a future release. See the expandable decorator and foreach function for more flexible alternatives.

Calls dependent_term for each set of outcomes from the product of independent_sources and accumulates the results. This is useful for resolving dependent probabilities. Returned histograms are always reduced to their lowest terms.

For example rolling a d20, re-rolling a 1 if it comes up, and keeping the result might be expressed as1:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> d20 = H(20)

>>> def reroll_one_dependent_term(d20_outcome):
...   if d20_outcome == 1:
...     return d20
...   else:
...     return d20_outcome

>>> H.foreach(reroll_one_dependent_term, d20_outcome=d20)
H({1: 1, 2: 21, 3: 21, ..., 19: 21, 20: 21})

The foreach class method merely wraps dependent_term and calls P.foreach. In doing so, it imposes a very modest overhead that is negligible in most cases.

1
2
3
4
5
%timeit P.foreach(dependent_term_p, roll_1=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), roll_2=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1}), roll_3=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1}), roll_n=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1}))
101 ms ± 223 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

%timeit H.foreach(dependent_term_h, outcome_1=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}), outcome_2=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1}), outcome_3=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1}), outcome_n=H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1}))
107 ms ± 173 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
Source: perf_foreach.ipy
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from dyce import H, P

def dependent_term(
  val_1,
  val_2,
  val_3,
  val_n,
):
  import math ; math.gcd(456**123, 123**456)  # emulate an expensive calculation
  return (
    (val_1 == val_2) +
    (val_2 == val_3) +
    (val_1 == val_3) +
    (
      val_n > val_1
      and val_n > val_2
      and val_n > val_3
    )
  )

def dependent_term_h(
  outcome_1,
  outcome_2,
  outcome_3,
  outcome_n,
):
  return dependent_term(outcome_1, outcome_2, outcome_3, outcome_n)

def dependent_term_p(
  roll_1,
  roll_2,
  roll_3,
  roll_n,
):
  return dependent_term(roll_1, roll_2, roll_3, roll_n)

source_1 = H(6)
source_2 = H(8)
source_3 = H(10)
source_n = H(20)

print(f"%timeit P.foreach({dependent_term_p.__name__}, roll_1={source_1}, roll_2={source_2}, roll_3={source_3}, roll_n={source_n})")
%timeit P.foreach(dependent_term_p, roll_1=source_1, roll_2=source_2, roll_3=source_3, roll_n=source_n)
print()

print(f"%timeit H.foreach({dependent_term_h.__name__}, outcome_1={source_1}, outcome_2={source_2}, outcome_3={source_3}, outcome_n={source_n})")
%timeit H.foreach(dependent_term_h, outcome_1=source_1, outcome_2=source_2, outcome_3=source_3, outcome_n=source_n)
print()

  1. This is primarily for illustration. H.substitute is often better suited to cases involving re-rolling a single independent term such as this one. 

Source code in dyce/h.py
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
@classmethod
@deprecated
@beartype
def foreach(
    cls,
    dependent_term: Callable[..., HOrOutcomeT],
    **independent_sources: _SourceT,
) -> "H":
    r"""
    !!! warning "Deprecated"

        This method has been deprecated and will be removed in a future release. See
        the [``expandable`` decorator][dyce.evaluation.expandable] and
        [``foreach`` function][dyce.evaluation.foreach] for more flexible
        alternatives.

    Calls ``#!python dependent_term`` for each set of outcomes from the product of
    ``independent_sources`` and accumulates the results. This is useful for
    resolving dependent probabilities. Returned histograms are always reduced to
    their lowest terms.

    For example rolling a d20, re-rolling a ``#!python 1`` if it comes up, and
    keeping the result might be expressed as[^1]:

    [^1]:

        This is primarily for illustration. [``H.substitute``][dyce.h.H.substitute]
        is often better suited to cases involving re-rolling a single independent
        term such as this one.

    ``` python
    >>> d20 = H(20)

    >>> def reroll_one_dependent_term(d20_outcome):
    ...   if d20_outcome == 1:
    ...     return d20
    ...   else:
    ...     return d20_outcome

    >>> H.foreach(reroll_one_dependent_term, d20_outcome=d20)
    H({1: 1, 2: 21, 3: 21, ..., 19: 21, 20: 21})

    ```

    The ``#!python foreach`` class method merely wraps *dependent_term* and calls
    [``P.foreach``][dyce.p.P.foreach]. In doing so, it imposes a very modest
    overhead that is negligible in most cases.

    ``` python
    --8<-- "docs/assets/perf_foreach.txt"
    ```

    <details>
    <summary>Source: <a href="https://github.com/posita/dyce/blob/latest/docs/assets/perf_foreach.ipy"><code>perf_foreach.ipy</code></a></summary>

    ``` python
    --8<-- "docs/assets/perf_foreach.ipy"
    ```
    </details>
    """
    from dyce import P

    def _dependent_term(**roll_kw):
        outcome_kw: dict[str, RealLike] = {}

        for key, roll in roll_kw.items():
            assert isinstance(roll, tuple)
            assert len(roll) == 1
            outcome_kw[key] = roll[0]

        return dependent_term(**outcome_kw)

    return P.foreach(_dependent_term, **independent_sources)

format(width: SupportsInt = _ROW_WIDTH, scaled: bool = False, tick: str = '#', sep: str = os.linesep) -> str

Returns a formatted string representation of the histogram. If width is greater than zero, a horizontal bar ASCII graph is printed using tick and sep (which are otherwise ignored if width is zero or less).

1
2
>>> print(H(6).format(width=0))
{avg: 3.50, 1: 16.67%, 2: 16.67%, 3: 16.67%, 4: 16.67%, 5: 16.67%, 6: 16.67%}
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
>>> print((2@H(6)).zero_fill(range(1, 21)).format(tick="@"))
avg |    7.00
std |    2.42
var |    5.83
  1 |   0.00% |
  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% |@
 13 |   0.00% |
 14 |   0.00% |
 15 |   0.00% |
 16 |   0.00% |
 17 |   0.00% |
 18 |   0.00% |
 19 |   0.00% |
 20 |   0.00% |

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 = (2@H(6)).ge(7)
>>> print(f"{' 65 chars wide -->|':->65}")
---------------------------------------------- 65 chars wide -->|
>>> print(H(1).format(scaled=False))
avg |    1.00
std |    0.00
var |    0.00
  1 | 100.00% |##################################################
>>> print(h.format(scaled=False))
avg |    0.58
std |    0.49
var |    0.24
  0 |  41.67% |####################
  1 |  58.33% |#############################
>>> print(h.format(scaled=True))
avg |    0.58
std |    0.49
var |    0.24
  0 |  41.67% |###################################
  1 |  58.33% |##################################################
Source code in dyce/h.py
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
@beartype
def format(
    self,
    width: SupportsInt = _ROW_WIDTH,
    scaled: bool = False,
    tick: str = "#",
    sep: str = os.linesep,
) -> str:
    r"""
    Returns a formatted string representation of the histogram. If *width* is
    greater than zero, a horizontal bar ASCII graph is printed using *tick* and
    *sep* (which are otherwise ignored if *width* is zero or less).

    ``` python
    >>> print(H(6).format(width=0))
    {avg: 3.50, 1: 16.67%, 2: 16.67%, 3: 16.67%, 4: 16.67%, 5: 16.67%, 6: 16.67%}

    ```

    ``` python
    >>> print((2@H(6)).zero_fill(range(1, 21)).format(tick="@"))
    avg |    7.00
    std |    2.42
    var |    5.83
      1 |   0.00% |
      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% |@
     13 |   0.00% |
     14 |   0.00% |
     15 |   0.00% |
     16 |   0.00% |
     17 |   0.00% |
     18 |   0.00% |
     19 |   0.00% |
     20 |   0.00% |

    ```

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

    ``` python
    >>> h = (2@H(6)).ge(7)
    >>> print(f"{' 65 chars wide -->|':->65}")
    ---------------------------------------------- 65 chars wide -->|
    >>> print(H(1).format(scaled=False))
    avg |    1.00
    std |    0.00
    var |    0.00
      1 | 100.00% |##################################################
    >>> print(h.format(scaled=False))
    avg |    0.58
    std |    0.49
    var |    0.24
      0 |  41.67% |####################
      1 |  58.33% |#############################
    >>> print(h.format(scaled=True))
    avg |    0.58
    std |    0.49
    var |    0.24
      0 |  41.67% |###################################
      1 |  58.33% |##################################################

    ```
    """
    width = as_int(width)

    # We convert various values herein to native ints and floats because number
    # tower implementations sometimes neglect to implement __format__ properly (or
    # at all). (I'm looking at you, sage.rings.…!)
    try:
        mu: RealLike = float(self.mean())
    except (OverflowError, TypeError):
        mu = self.mean()

    if width <= 0:

        def _parts() -> Iterator[str]:
            yield f"avg: {mu:.2f}"

            for (
                outcome,
                probability,
            ) in self.distribution():
                probability_f = float(probability)
                yield f"{outcome}:{probability_f:7.2%}"

        return "{" + ", ".join(_parts()) + "}"
    else:
        w = width - 15

        def _lines() -> Iterator[str]:
            try:
                yield f"avg | {mu:7.2f}"
                std = float(self.stdev(mu))
                var = float(self.variance(mu))
                yield f"std | {std:7.2f}"
                yield f"var | {var:7.2f}"
            except (OverflowError, TypeError) as exc:
                warnings.warn(f"{str(exc)}; mu: {mu}")

            if self:
                outcomes, probabilities = self.distribution_xy()
                tick_scale = max(probabilities) if scaled else 1.0

                for outcome, probability in zip(outcomes, probabilities):
                    try:
                        outcome_str = f"{outcome: 3}"
                    except (TypeError, ValueError):
                        outcome_str = str(outcome)
                        outcome_str = f"{outcome_str: >3}"

                    ticks = tick * int(w * probability / tick_scale)
                    probability_f = float(probability)
                    yield f"{outcome_str} | {probability_f:7.2%} |{ticks}"

        return sep.join(_lines())

ge(other: _OperandT) -> H

Shorthand for self.map(operator.__ge__, other).umap(bool).

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

See the map and umap methods.

Source code in dyce/h.py
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
@beartype
def ge(self, other: _OperandT) -> "H":
    r"""
    Shorthand for ``#!python self.map(operator.__ge__, other).umap(bool)``.

    ``` python
    >>> H(6).ge(3)
    H({False: 2, True: 4})

    ```

    See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
    """
    return self.map(__ge__, other).umap(bool)

gt(other: _OperandT) -> H

Shorthand for self.map(operator.__gt__, other).umap(bool).

1
2
>>> H(6).gt(3)
H({False: 3, True: 3})

See the map and umap methods.

Source code in dyce/h.py
972
973
974
975
976
977
978
979
980
981
982
983
984
985
@beartype
def gt(self, other: _OperandT) -> "H":
    r"""
    Shorthand for ``#!python self.map(operator.__gt__, other).umap(bool)``.

    ``` python
    >>> H(6).gt(3)
    H({False: 3, True: 3})

    ```

    See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
    """
    return self.map(__gt__, other).umap(bool)

is_even() -> H

Equivalent to self.umap(dyce.types.is_even).

1
2
>>> H((-4, -2, 0, 1, 2, 3)).is_even()
H({False: 2, True: 4})

See the umap method.

Source code in dyce/h.py
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
@beartype
def is_even(self) -> "H":
    r"""
    Equivalent to ``#!python self.umap(dyce.types.is_even)``.

    ``` python
    >>> H((-4, -2, 0, 1, 2, 3)).is_even()
    H({False: 2, True: 4})

    ```

    See the [``umap`` method][dyce.h.H.umap].
    """
    return self.umap(is_even)

is_odd() -> H

Equivalent to self.umap(dyce.types.is_odd).

1
2
>>> H((-4, -2, 0, 1, 2, 3)).is_odd()
H({False: 4, True: 2})

See the umap method.

Source code in dyce/h.py
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
@beartype
def is_odd(self) -> "H":
    r"""
    Equivalent to ``#!python self.umap(dyce.types.is_odd)``.

    ``` python
    >>> H((-4, -2, 0, 1, 2, 3)).is_odd()
    H({False: 4, True: 2})

    ```

    See the [``umap`` method][dyce.h.H.umap].
    """
    return self.umap(is_odd)

items() -> ItemsView[RealLike, int]

Source code in dyce/h.py
706
707
708
@beartype
def items(self) -> ItemsView[RealLike, int]:
    return self._h.items()

keys() -> KeysView[RealLike]

Source code in dyce/h.py
710
711
712
@beartype
def keys(self) -> KeysView[RealLike]:
    return self.outcomes()

le(other: _OperandT) -> H

Shorthand for self.map(operator.__le__, other).umap(bool).

1
2
>>> H(6).le(3)
H({False: 3, True: 3})

See the map and umap methods.

Source code in dyce/h.py
927
928
929
930
931
932
933
934
935
936
937
938
939
940
@beartype
def le(self, other: _OperandT) -> "H":
    r"""
    Shorthand for ``#!python self.map(operator.__le__, other).umap(bool)``.

    ``` python
    >>> H(6).le(3)
    H({False: 3, True: 3})

    ```

    See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
    """
    return self.map(__le__, other).umap(bool)

lowest_terms() -> H

Computes and returns a histogram whose nonzero counts share a greatest common divisor of 1.

1
2
3
>>> df_obscured = H({-2: 0, -1: 2, 0: 2, 1: 2, 2: 0})
>>> df_obscured.lowest_terms()
H({-1: 1, 0: 1, 1: 1})
Source code in dyce/h.py
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
@beartype
def lowest_terms(self) -> "H":
    r"""
    Computes and returns a histogram whose nonzero counts share a greatest
    common divisor of 1.

    ``` python
    >>> df_obscured = H({-2: 0, -1: 2, 0: 2, 1: 2, 2: 0})
    >>> df_obscured.lowest_terms()
    H({-1: 1, 0: 1, 1: 1})

    ```
    """
    if self._lowest_terms is None:
        counts_gcd = gcd(*self.counts())

        if counts_gcd in (0, 1) and 0 not in self.counts():
            self._lowest_terms = self
        else:
            self._lowest_terms = type(self)(
                (outcome, count // counts_gcd)
                for outcome, count in self.items()
                if count != 0
            )

    return self._lowest_terms

lt(other: _OperandT) -> H

Shorthand for self.map(operator.__lt__, other).umap(bool).

1
2
>>> H(6).lt(3)
H({False: 4, True: 2})

See the map and umap methods.

Source code in dyce/h.py
912
913
914
915
916
917
918
919
920
921
922
923
924
925
@beartype
def lt(self, other: _OperandT) -> "H":
    r"""
    Shorthand for ``#!python self.map(operator.__lt__, other).umap(bool)``.

    ``` python
    >>> H(6).lt(3)
    H({False: 4, True: 2})

    ```

    See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
    """
    return self.map(__lt__, other).umap(bool)

map(bin_op: _BinaryOperatorT, right_operand: _OperandT) -> H

Applies bin_op to each outcome of the histogram as the left operand and right_operand as the right. Shorthands exist for many arithmetic operators and comparators.

1
2
3
4
5
6
>>> import operator
>>> d6 = H(6)
>>> d6.map(operator.__add__, d6)
H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})
>>> d6.map(operator.__add__, d6) == d6 + d6
True
1
2
3
4
>>> d6.map(operator.__pow__, 2)
H({1: 1, 4: 1, 9: 1, 16: 1, 25: 1, 36: 1})
>>> d6.map(operator.__pow__, 2) == d6 ** 2
True
1
2
3
4
>>> d6.map(operator.__gt__, 3)
H({False: 3, True: 3})
>>> d6.map(operator.__gt__, 3) == d6.gt(3)
True
Source code in dyce/h.py
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
@beartype
def map(self, bin_op: _BinaryOperatorT, right_operand: _OperandT) -> "H":
    r"""
    Applies *bin_op* to each outcome of the histogram as the left operand and
    *right_operand* as the right. Shorthands exist for many arithmetic operators and
    comparators.

    ``` python
    >>> import operator
    >>> d6 = H(6)
    >>> d6.map(operator.__add__, d6)
    H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})
    >>> d6.map(operator.__add__, d6) == d6 + d6
    True

    ```

    ``` python
    >>> d6.map(operator.__pow__, 2)
    H({1: 1, 4: 1, 9: 1, 16: 1, 25: 1, 36: 1})
    >>> d6.map(operator.__pow__, 2) == d6 ** 2
    True

    ```

    ``` python
    >>> d6.map(operator.__gt__, 3)
    H({False: 3, True: 3})
    >>> d6.map(operator.__gt__, 3) == d6.gt(3)
    True

    ```
    """
    if isinstance(right_operand, HableT):
        right_operand = right_operand.h()

    if isinstance(right_operand, H):
        return type(self)(
            (bin_op(s, o), self[s] * right_operand[o])
            for s, o in product(self, right_operand)
        )
    else:
        return type(self)(
            (bin_op(outcome, right_operand), count)
            for outcome, count in self.items()
        )

mean() -> RealLike

Returns the mean of the weighted outcomes (or 0.0 if there are no outcomes).

Source code in dyce/h.py
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
@beartype
def mean(self) -> RealLike:
    r"""
    Returns the mean of the weighted outcomes (or 0.0 if there are no outcomes).
    """
    numerator: float
    denominator: float
    numerator = denominator = 0

    for outcome, count in self.items():
        numerator += outcome * count
        denominator += count

    return numerator / (denominator or 1)

ne(other: _OperandT) -> H

Shorthand for self.map(operator.__ne__, other).umap(bool).

1
2
>>> H(6).ne(3)
H({False: 1, True: 5})

See the map and umap methods.

Source code in dyce/h.py
957
958
959
960
961
962
963
964
965
966
967
968
969
970
@beartype
def ne(self, other: _OperandT) -> "H":
    r"""
    Shorthand for ``#!python self.map(operator.__ne__, other).umap(bool)``.

    ``` python
    >>> H(6).ne(3)
    H({False: 1, True: 5})

    ```

    See the [``map``][dyce.h.H.map] and [``umap``][dyce.h.H.umap] methods.
    """
    return self.map(__ne__, other).umap(bool)

order_stat_for_n_at_pos(n: SupportsInt, pos: SupportsInt) -> H

Experimental

This method should be considered experimental and may change or disappear in future versions.

Computes the probability distribution for each outcome appearing in at pos for n histograms. 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)  # counts where outcome appears in the fourth of five positions
H({2: 26, 3: 1432, 4: 4792, 5: 1526})

The results show that, when rolling five six-sided “averaging” dice and sorting each roll, there are 26 ways where 2 appears at the fourth (index 3) position, 1432 ways where 3 appears at the fourth position, etc. This can be verified independently using the computationally expensive method of enumerating rolls and counting those that meet the criteria.

1
2
3
4
>>> from dyce import P
>>> p_5d6avg = 5@P(d6avg)
>>> sum(count for roll, count in p_5d6avg.rolls_with_counts() if roll[3] == 5)
1526

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 computing the betas for n so they can be reused for varying values of pos in subsequent calls.

Source code in dyce/h.py
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
@experimental
@beartype
def order_stat_for_n_at_pos(self, n: SupportsInt, pos: SupportsInt) -> "H":
    r"""
    !!! warning "Experimental"

        This method should be considered experimental and may change or disappear in
        future versions.

    Computes the probability distribution for each outcome appearing in at *pos* for
    *n* histograms. *pos* is a zero-based index.

    ``` python
    >>> d6avg = H((2, 3, 3, 4, 4, 5))
    >>> d6avg.order_stat_for_n_at_pos(5, 3)  # counts where outcome appears in the fourth of five positions
    H({2: 26, 3: 1432, 4: 4792, 5: 1526})

    ```

    The results show that, when rolling five six-sided “averaging” dice and sorting
    each roll, there are 26 ways where ``#!python 2`` appears at the fourth (index
    ``#!python 3``) position, 1432 ways where ``#!python 3`` appears at the fourth
    position, etc. This can be verified independently using the computationally
    expensive method of enumerating rolls and counting those that meet the criteria.

    ``` python
    >>> from dyce import P
    >>> p_5d6avg = 5@P(d6avg)
    >>> sum(count for roll, count in p_5d6avg.rolls_with_counts() if roll[3] == 5)
    1526

    ```

    Negative values for *pos* follow Python index semantics:

    ``` python
    >>> 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 computing the betas for *n* so they can be reused for varying
    values of *pos* in subsequent calls.
    """
    # See <https://math.stackexchange.com/q/4173084/226394> for motivation
    n = as_int(n)
    pos = as_int(pos)

    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[RealLike]

More descriptive synonym for the keys method.

Source code in dyce/h.py
714
715
716
717
718
719
@beartype
def outcomes(self) -> KeysView[RealLike]:
    r"""
    More descriptive synonym for the [``keys`` method][dyce.h.H.keys].
    """
    return self._h.keys()

remove(outcome: RealLike) -> H

Source code in dyce/h.py
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
@beartype
def remove(self, outcome: RealLike) -> "H":
    if outcome not in self:
        return self

    return type(self)(
        (orig_outcome, count)
        for orig_outcome, count in self.items()
        if orig_outcome != outcome
    )

reversed() -> Iterator[RealLike]

Source code in dyce/h.py
721
722
723
@beartype
def reversed(self) -> Iterator[RealLike]:
    return reversed(self)

rmap(left_operand: RealLike, bin_op: _BinaryOperatorT) -> H

Analogous to the map method, but where the caller supplies left_operand.

1
2
3
4
5
6
>>> import operator
>>> d6 = H(6)
>>> d6.rmap(2, operator.__pow__)
H({2: 1, 4: 1, 8: 1, 16: 1, 32: 1, 64: 1})
>>> d6.rmap(2, operator.__pow__) == 2 ** d6
True

Note

The positions of left_operand and bin_op are different from map method. This is intentional and serves as a reminder of operand ordering.

Source code in dyce/h.py
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
@beartype
def rmap(self, left_operand: RealLike, bin_op: _BinaryOperatorT) -> "H":
    r"""
    Analogous to the [``map`` method][dyce.h.H.map], but where the caller supplies
    *left_operand*.

    ``` python
    >>> import operator
    >>> d6 = H(6)
    >>> d6.rmap(2, operator.__pow__)
    H({2: 1, 4: 1, 8: 1, 16: 1, 32: 1, 64: 1})
    >>> d6.rmap(2, operator.__pow__) == 2 ** d6
    True

    ```

    !!! note

        The positions of *left_operand* and *bin_op* are different from
        [``map`` method][dyce.h.H.map]. This is intentional and serves as a reminder
        of operand ordering.
    """
    return type(self)(
        (bin_op(left_operand, outcome), count) for outcome, count in self.items()
    )

roll() -> RealLike

Returns a (weighted) random outcome.

Source code in dyce/h.py
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
@beartype
def roll(self) -> RealLike:
    r"""
    Returns a (weighted) random outcome.
    """
    return (
        rng.RNG.choices(
            population=tuple(self.outcomes()),
            weights=tuple(self.counts()),
            k=1,
        )[0]
        if self
        else 0
    )

stdev(mu: Optional[RealLike] = None) -> RealLike

Shorthand for math.sqrt(self.variance(mu)).

Source code in dyce/h.py
1814
1815
1816
1817
1818
1819
@beartype
def stdev(self, mu: Optional[RealLike] = None) -> RealLike:
    r"""
    Shorthand for ``#!python math.sqrt(self.variance(mu))``.
    """
    return sqrt(self.variance(mu))

substitute(expand: _SubstituteExpandCallbackT, coalesce: _SubstituteCoalesceCallbackT = coalesce_replace, max_depth: Optional[IntegralLike] = None, precision_limit: Optional[Union[RationalLikeMixedU, RealLike]] = None) -> H

Deprecated

This method has been deprecated and will be removed in a future release. See the expandable decorator and foreach function for more flexible alternatives.

Calls expand on each outcome. If expand returns a single outcome, it replaces the existing outcome. If it returns an H object, evaluation is performed again (recursively) on that object until a limit (either max_depth or precision_limit) is exhausted. coalesce is called on the original outcome and the expanded histogram or outcome and the returned histogram is “folded” into result. The default behavior for coalesce is to replace the outcome with the expanded histogram. Returned histograms are always reduced to their lowest terms.

coalesce is not called unless expand returns a histogram

If expand returns a single outcome, it always replaces the existing outcome. This is intentional. To return a single outcome, but trigger coalesce, characterize that outcome as a single-sided die (e.g., H({outcome: 1}).

See the coalesce_replace and lowest_terms methods.

Precision limits

The max_depth parameter is similar to an expandable-decorated function’s limit argument when given a whole number. The precision_limit parameter is similar to an expandable-decorated function’s limit argument being provided a fractional value. It is an error to provide values for both max_depth and precision_limit.

Source code in dyce/h.py
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
@deprecated
@beartype
def substitute(
    self,
    expand: _SubstituteExpandCallbackT,
    coalesce: _SubstituteCoalesceCallbackT = coalesce_replace,
    max_depth: Optional[IntegralLike] = None,
    precision_limit: Optional[Union[RationalLikeMixedU, RealLike]] = None,
) -> "H":
    r"""
    !!! warning "Deprecated"

        This method has been deprecated and will be removed in a future release. See
        the [``expandable`` decorator][dyce.evaluation.expandable] and
        [``foreach`` function][dyce.evaluation.foreach] for more flexible
        alternatives.

    Calls *expand* on each outcome. If *expand* returns a single outcome, it
    replaces the existing outcome. If it returns an [``H`` object][dyce.h.H],
    evaluation is performed again (recursively) on that object until a limit (either
    *max_depth* or *precision_limit*) is exhausted. *coalesce* is called on the
    original outcome and the expanded histogram or outcome and the returned
    histogram is “folded” into result. The default behavior for *coalesce* is to
    replace the outcome with the expanded histogram. Returned histograms are always
    reduced to their lowest terms.

    !!! note "*coalesce* is not called unless *expand* returns a histogram"

        If *expand* returns a single outcome, it *always* replaces the existing
        outcome. This is intentional. To return a single outcome, but trigger
        *coalesce*, characterize that outcome as a single-sided die (e.g.,
        ``#!python H({outcome: 1})``.

    See the [``coalesce_replace``][dyce.h.coalesce_replace] and
    [``lowest_terms``][dyce.h.H.lowest_terms] methods.

    !!! tip "Precision limits"

        The *max_depth* parameter is similar to an
        [``expandable``][dyce.evaluation.expandable]-decorated function’s limit
        argument when given a whole number. The *precision_limit* parameter is
        similar to an [``expandable``][dyce.evaluation.expandable]-decorated
        function’s limit argument being provided a fractional value. It is an error
        to provide values for both *max_depth* and *precision_limit*.
    """
    from .evaluation import HResult, LimitT, expandable

    if max_depth is not None and precision_limit is not None:
        raise ValueError("only one of max_depth and precision_limit is allowed")

    limit: Optional[LimitT] = (
        max_depth if precision_limit is None else precision_limit
    )

    @expandable(sentinel=self)
    def _expand(result: HResult) -> HOrOutcomeT:
        res = expand(result.h, result.outcome)

        return coalesce(_expand(res), result.outcome) if isinstance(res, H) else res

    return _expand(self, limit=limit)

umap(un_op: _UnaryOperatorT) -> H

Applies un_op to each outcome of the histogram.

1
2
3
>>> import operator
>>> H(6).umap(operator.__neg__)
H({-6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1})
1
2
>>> H(4).umap(lambda outcome: (-outcome) ** outcome)
H({-27: 1, -1: 1, 4: 1, 256: 1})
Source code in dyce/h.py
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
@beartype
def umap(self, un_op: _UnaryOperatorT) -> "H":
    r"""
    Applies *un_op* to each outcome of the histogram.

    ``` python
    >>> import operator
    >>> H(6).umap(operator.__neg__)
    H({-6: 1, -5: 1, -4: 1, -3: 1, -2: 1, -1: 1})

    ```

    ``` python
    >>> H(4).umap(lambda outcome: (-outcome) ** outcome)
    H({-27: 1, -1: 1, 4: 1, 256: 1})

    ```
    """
    return type(self)((un_op(outcome), count) for outcome, count in self.items())

values() -> ValuesView[int]

Source code in dyce/h.py
725
726
727
@beartype
def values(self) -> ValuesView[int]:
    return self.counts()

variance(mu: Optional[RealLike] = None) -> RealLike

Returns the variance of the weighted outcomes. If provided, mu is used as the mean (to avoid duplicate computation).

Source code in dyce/h.py
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
@beartype
def variance(self, mu: Optional[RealLike] = None) -> RealLike:
    r"""
    Returns the variance of the weighted outcomes. If provided, *mu* is used as the mean
    (to avoid duplicate computation).
    """
    mu = mu if mu else self.mean()
    numerator: float
    denominator: float
    numerator = denominator = 0

    for outcome, count in self.items():
        numerator += outcome**2 * count
        denominator += count

    # While floating point overflow is impossible to eliminate, we avoid it under
    # some circumstances by exploiting the equivalence of E[(X - E[X])**2] and the
    # more efficient E[X**2] - E[X]**2. See
    # <https://dlsun.github.io/probability/variance.html>.
    return numerator / (denominator or 1) - mu**2

vs(other: _OperandT) -> H

Compares the histogram with other. -1 represents where other is greater. 0 represents where they are equal. 1 represents where other is less.

Shorthand for self.within(0, 0, other).

1
2
3
4
>>> H(6).vs(H(4))
H({-1: 6, 0: 4, 1: 14})
>>> H(6).vs(H(4)) == H(6).within(0, 0, H(4))
True

See the within method.

Source code in dyce/h.py
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
@beartype
def vs(self, other: _OperandT) -> "H":
    r"""
    Compares the histogram with *other*. -1 represents where *other* is greater. 0
    represents where they are equal. 1 represents where *other* is less.

    Shorthand for ``#!python self.within(0, 0, other)``.

    ``` python
    >>> H(6).vs(H(4))
    H({-1: 6, 0: 4, 1: 14})
    >>> H(6).vs(H(4)) == H(6).within(0, 0, H(4))
    True

    ```

    See the [``within`` method][dyce.h.H.within].
    """
    return self.within(0, 0, other)

within(lo: RealLike, hi: RealLike, other: _OperandT = 0) -> H

Computes the difference between the histogram and other. -1 represents where that difference is less than lo. 0 represents where that difference between lo and hi (inclusive). 1 represents where that difference is greater than hi.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> d6_2 = 2@H(6)
>>> d6_2.within(7, 9)
H({-1: 15, 0: 15, 1: 6})
>>> print(d6_2.within(7, 9).format())
avg |   -0.25
std |    0.72
var |    0.52
 -1 |  41.67% |####################
  0 |  41.67% |####################
  1 |  16.67% |########
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
>>> d6_3, d8_2 = 3@H(6), 2@H(8)
>>> d6_3.within(-1, 1, d8_2)  # 3d6 w/in 1 of 2d8
H({-1: 3500, 0: 3412, 1: 6912})
>>> print(d6_3.within(-1, 1, d8_2).format())
avg |    0.25
std |    0.83
var |    0.69
 -1 |  25.32% |############
  0 |  24.68% |############
  1 |  50.00% |#########################
Source code in dyce/h.py
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
@beartype
def within(self, lo: RealLike, hi: RealLike, other: _OperandT = 0) -> "H":
    r"""
    Computes the difference between the histogram and *other*. -1 represents where that
    difference is less than *lo*. 0 represents where that difference between *lo*
    and *hi* (inclusive). 1 represents where that difference is greater than *hi*.

    ``` python
    >>> d6_2 = 2@H(6)
    >>> d6_2.within(7, 9)
    H({-1: 15, 0: 15, 1: 6})
    >>> print(d6_2.within(7, 9).format())
    avg |   -0.25
    std |    0.72
    var |    0.52
     -1 |  41.67% |####################
      0 |  41.67% |####################
      1 |  16.67% |########

    ```

    ``` python
    >>> d6_3, d8_2 = 3@H(6), 2@H(8)
    >>> d6_3.within(-1, 1, d8_2)  # 3d6 w/in 1 of 2d8
    H({-1: 3500, 0: 3412, 1: 6912})
    >>> print(d6_3.within(-1, 1, d8_2).format())
    avg |    0.25
    std |    0.83
    var |    0.69
     -1 |  25.32% |############
      0 |  24.68% |############
      1 |  50.00% |#########################

    ```
    """
    return self.map(_within(lo, hi), other)

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

Shorthand for self.accumulate({outcome: 0 for outcome inoutcomes}).

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
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
@beartype
def zero_fill(self, outcomes: Iterable[RealLike]) -> "H":
    r"""
    Shorthand for ``#!python self.accumulate({outcome: 0 for outcome in
    outcomes})``.

    ``` python
    >>> 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.accumulate({outcome: 0 for outcome in outcomes})

P

Bases: Sequence[H], HableOpsMixin

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
>>> from dyce import P
>>> p_d6 = P(6) ; p_d6  # shorthand for P(H(6))
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
4
>>> p = P(4, P(6, P(8, P(10, P(12, P(20)))))) ; p
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}), H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1}), H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1}), H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1}))
>>> sum(p.roll()) in p.h()
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 map, rmap, and umap methods.

1
2
3
>>> import operator
>>> P(4, 6, 8).umap(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).map(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
>>> P(4, 6).rmap(2, operator.__pow__)
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
>>> from dyce import H
>>> 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

In an extension to (departure from) the HableT protocol, the h method’s implementation also affords subsets of outcomes to be “taken” (selected) by passing in selection criteria. Values are indexed from least to greatest. Negative indexes are supported and retain their idiomatic meaning. Modeling the sum of the greatest two faces of three six-sided dice (3d6) can be expressed as:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
>>> p_3d6 = 3@p_d6
>>> p_3d6.h(-2, -1)
H({2: 1, 3: 3, 4: 7, 5: 12, 6: 19, 7: 27, 8: 34, 9: 36, 10: 34, 11: 27, 12: 16})
>>> print(p_3d6.h(-2, -1).format())
avg |    8.46
std |    2.21
var |    4.91
  2 |   0.46% |
  3 |   1.39% |
  4 |   3.24% |#
  5 |   5.56% |##
  6 |   8.80% |####
  7 |  12.50% |######
  8 |  15.74% |#######
  9 |  16.67% |########
 10 |  15.74% |#######
 11 |  12.50% |######
 12 |   7.41% |###
Source code in dyce/p.py
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
class P(Sequence[H], HableOpsMixin):
    r"""
    An immutable pool (ordered sequence) supporting group operations for zero or more
    [``H`` objects][dyce.h.H] (provided or created from the
    [initializer][dyce.p.P.__init__]’s *args* parameter).

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

    ```

    ``` python
    >>> 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

    ```

    ``` python
    >>> p = P(4, P(6, P(8, P(10, P(12, P(20)))))) ; p
    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}), H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1}), H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1}), H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1, 7: 1, 8: 1, 9: 1, 10: 1, 11: 1, 12: 1, 13: 1, 14: 1, 15: 1, 16: 1, 17: 1, 18: 1, 19: 1, 20: 1}))
    >>> sum(p.roll()) in p.h()
    True

    ```

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

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

    ```

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

    ```

    ``` python
    >>> 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.H] in a pool without
    flattening, use the [``map``][dyce.p.P.map], [``rmap``][dyce.p.P.rmap], and
    [``umap``][dyce.p.P.umap] methods.

    ``` python
    >>> import operator
    >>> P(4, 6, 8).umap(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}))

    ```

    ``` python
    >>> P(4, 6).map(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}))

    ```

    ``` python
    >>> P(4, 6).rmap(2, operator.__pow__)
    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.H] work as expected.

    ``` python
    >>> from dyce import H
    >>> 3@p_d6 == H(6) + H(6) + H(6)
    True

    ```

    Indexing selects a contained histogram.

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

    ```

    Note that pools are opinionated about ordering.

    ``` python
    >>> 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

    ```

    In an extension to (departure from) the [``HableT`` protocol][dyce.h.HableT], the
    [``h`` method][dyce.p.P.h]’s implementation also affords subsets of outcomes to be
    “taken” (selected) by passing in selection criteria. Values are indexed from least
    to greatest. Negative indexes are supported and retain their idiomatic meaning.
    Modeling the sum of the greatest two faces of three six-sided dice (``3d6``) can be
    expressed as:

    ``` python
    >>> p_3d6 = 3@p_d6
    >>> p_3d6.h(-2, -1)
    H({2: 1, 3: 3, 4: 7, 5: 12, 6: 19, 7: 27, 8: 34, 9: 36, 10: 34, 11: 27, 12: 16})
    >>> print(p_3d6.h(-2, -1).format())
    avg |    8.46
    std |    2.21
    var |    4.91
      2 |   0.46% |
      3 |   1.39% |
      4 |   3.24% |#
      5 |   5.56% |##
      6 |   8.80% |####
      7 |  12.50% |######
      8 |  15.74% |#######
      9 |  16.67% |########
     10 |  15.74% |#######
     11 |  12.50% |######
     12 |   7.41% |###

    ```
    """
    __slots__: Any = (
        "_hs",
        "_total",
    )

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

    @beartype
    # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
    def __init__(self, *args: Union[SupportsInt, "P", H]) -> None:
        r"Initializer."
        super().__init__()

        def _gen_hs() -> Iterator[H]:
            for a in args:
                if isinstance(a, H):
                    yield a
                elif isinstance(a, P):
                    for h in a._hs:
                        yield h
                elif isinstance(a, SupportsInt):
                    yield H(a)
                else:
                    raise TypeError(f"unrecognized initializer type {a!r}")

        hs = list(h for h in _gen_hs() if h)

        try:
            hs.sort(key=lambda h: tuple(h.items()))
        except TypeError:
            # This is for outcomes that don't support direct comparisons, like symbolic
            # representations
            hs.sort(key=lambda h: str(tuple(h.items())))

        self._hs = tuple(hs)
        self._total: int = prod(h.total for h in self._hs)

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

    @property
    def total(self) -> int:
        r"""
        !!! warning "Experimental"

            This method should be considered experimental and may change or disappear in
            future versions.

        Equivalent to ``#!python prod(h.total for h in self)``. Note that—consistent
        with the empty product—this is ``#!python 1`` for an empty pool.
        """
        return self._total

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

    @beartype
    def __repr__(self) -> str:
        group_counters: dict[H, int] = {}

        for h, hs in groupby(self):
            n = sum(1 for _ in hs)
            group_counters[h] = n

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

        if len(group_counters) == 1:
            h = next(iter(group_counters))

            if group_counters[h] == 1:
                return f"{type(self).__name__}({_n_at(h, 1)})"
            else:
                return _n_at(h, group_counters[h])
        else:
            args = ", ".join(_n_at(h, n) for h, n in group_counters.items())

            return f"{type(self).__name__}({args})"

    @beartype
    def __eq__(self, other) -> bool:
        if isinstance(other, P):
            return __eq__(self._hs, other._hs)
        else:
            return NotImplemented

    @beartype
    def __ne__(self, other) -> bool:
        if isinstance(other, P):
            return __ne__(self._hs, other._hs)
        else:
            return NotImplemented

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

    @overload
    def __getitem__(self, key: SupportsIndex) -> H:
        ...

    @overload
    def __getitem__(self, key: slice) -> "P":
        ...

    @beartype
    def __getitem__(self, key: _GetItemT) -> Union[H, "P"]:
        if isinstance(key, slice):
            return P(*self._hs[key])
        else:
            return self._hs[__index__(key)]

    @beartype
    def __iter__(self) -> Iterator[H]:
        return iter(self._hs)

    @beartype
    def __matmul__(self, other: SupportsInt) -> "P":
        try:
            other = as_int(other)
        except TypeError:
            return NotImplemented

        if other < 0:
            raise ValueError("argument cannot be negative")
        else:
            return P(*chain.from_iterable(repeat(self, other)))

    @beartype
    def __rmatmul__(self, other: SupportsInt) -> "P":
        return self.__matmul__(other)

    @beartype
    def h(self, *which: _GetItemT) -> H:
        r"""
        Roughly equivalent to ``#!python H((sum(roll), count) for roll, count in
        self.rolls_with_counts(*which))`` with some short-circuit optimizations.

        When provided no arguments, ``#!python h`` combines (or “flattens”) contained
        histograms in accordance with the [``HableT`` protocol][dyce.h.HableT].

        ``` python
        >>> (2@P(6)).h()
        H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})

        ```

        If one or more arguments are provided, this method sums subsets of outcomes
        those arguments identify for each roll. Outcomes are ordered from least (index
        ``#!python 0``) to greatest (index ``#!python -1`` or ``#!python len(self) -
        1``). 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:

        ``` python
        >>> 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())
        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:

        ``` python
        >>> 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(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.

        ``` python
        >>> 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 which:
            n = len(self)
            i = _analyze_selection(n, which)

            if i and i >= n:
                # The caller selected all dice in the pool exactly i // n times, so we
                # can short-circuit roll enumeration
                assert i % n == 0

                return self.h() * (i // n)
            else:
                return H(
                    (sum(roll), count) for roll, count in self.rolls_with_counts(*which)
                )
        else:
            # The caller offered no selection
            return sum_h(self)

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

    @classmethod
    @deprecated
    @beartype
    def foreach(
        cls,
        dependent_term: Callable[..., Union[H, RealLike]],
        # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
        **independent_sources: Union["P", H, HableT, _SourceT],
    ) -> H:
        r"""
        !!! warning "Deprecated"

            This method has been deprecated and will be removed in a future release. See
            the [``expandable`` decorator][dyce.evaluation.expandable] and
            [``foreach`` function][dyce.evaluation.foreach] for more flexible
            alternatives.

        Calls ``#!python dependent_term`` for each unique set of rolls from the product
        of ``independent_sources`` and accumulates the results. This is useful for
        resolving dependent probabilities. Rolls are sorted least to greatest. Returned
        histograms are always reduced to their lowest terms.

        ``` python
        >>> from dyce.p import RollT

        >>> def three_way_vs(first: RollT, second: RollT, third: RollT):
        ...   first_reversed = first[::-1]
        ...   second_reversed = second[::-1]
        ...   third_reversed = third[::-1]
        ...   if first_reversed > second_reversed and first_reversed > third_reversed:
        ...     return 1  # first is the clear winner
        ...   elif second_reversed > first_reversed and second_reversed > third_reversed:
        ...     return 2  # second is the clear winner
        ...   elif third_reversed > first_reversed and third_reversed > second_reversed:
        ...     return 3  # third is the clear winner
        ...   else:
        ...     return 0  # there was a tie somewhere

        >>> P.foreach(
        ...   three_way_vs,
        ...   first=P(6, 6),  # first has pool of two d6s
        ...   second=P(6, 6),  # second has pool of two d6s
        ...   third=P(4, 8),  # third has pool of one d4 and one d8
        ... )
        H({0: 1103, 1: 5783, 2: 5783, 3: 8067})

        ```

        When all of ``#!python foreach``’s arguments are [``P`` objects][dyce.p.P] of
        size 1 or anything other than a ``P`` object, this function behaves similarly to
        [``H.foreach``][dyce.h.H] (although the signature of the *dependent_term*
        callback function differs slightly between the two interfaces).

        ``` python
        >>> from itertools import chain
        >>> P.foreach(
        ...   lambda **kw: sum(chain(*kw.values())),  # receives single-element rolls
        ...   src1=P(6),  # pool of size 1
        ...   src2=H(6),  # histogram
        ...   src3=range(6, 0, -1),  # histogram source
        ... ) == H.foreach(
        ...   lambda **kw: sum(kw.values()),  # receives outcomes
        ...   src1=P(6).h(),  # histogram
        ...   src2=H(6),  # histogram
        ...   src3={1, 2, 3, 4, 5, 6},  # histogram source
        ... )
        True

        ```

        The ``#!python foreach`` class method is equivalent to nesting loops iterating
        over [``P.rolls_with_counts``][dyce.p.P.rolls_with_counts] for each independent
        term and then aggregating the results.

        ``` python
        >>> def dependent_term(
        ...   *,
        ...   roll_1,
        ...   roll_2,
        ...   # ...
        ...   roll_n,
        ... ):
        ...   return (
        ...     (roll_2[-1] > roll_1[-1])
        ...     + (roll_n[-1] > roll_2[-1])
        ...     # ...
        ...   )

        >>> source_1 = P(8)
        >>> source_2 = P(6, 6)
        >>> # ...
        >>> source_n = P(4, 4, 4)

        >>> h = P.foreach(
        ...   dependent_term,
        ...   roll_1=source_1,
        ...   roll_2=source_2,
        ...   # ...
        ...   roll_n=source_n,
        ... ) ; h
        H({0: 3821, 1: 5126, 2: 269})

        >>> def resolve():
        ...   for roll_1, count_1 in source_1.rolls_with_counts():
        ...     for roll_2, count_2 in source_2.rolls_with_counts():
        ...       # ...
        ...       for roll_n, count_n in source_n.rolls_with_counts():
        ...         # ...
        ...           yield dependent_term(
        ...             roll_1=roll_1,
        ...             roll_2=roll_2,
        ...             # ...
        ...             roll_n=roll_n,
        ...         ), (
        ...           count_1
        ...           * count_2
        ...           # * ...
        ...           * count_n
        ...         )

        >>> from dyce.evaluation import aggregate_weighted
        >>> aggregate_weighted(resolve()) == h
        True

        ```
        """
        from dyce.evaluation import aggregate_weighted

        pools_by_kw: dict[str, P] = {}

        for source_name, source in independent_sources.items():
            if isinstance(source, H):
                pools_by_kw[source_name] = P(source)
            elif isinstance(source, P):
                pools_by_kw[source_name] = source
            elif isinstance(source, HableT):
                pools_by_kw[source_name] = P(source.h())
            else:
                pools_by_kw[source_name] = P(H(source))

        def _kw_roll_count_tuples(
            pool_name: str,
        ) -> Iterator[tuple[str, RollT, int]]:
            for roll, count in pools_by_kw[pool_name].rolls_with_counts():
                yield pool_name, roll, count

        def _resolve_dependent_term_for_rolls() -> (
            Iterator[tuple[Union[H, RealLike], int]]
        ):
            for kw_roll_count_tuples in product(
                *(_kw_roll_count_tuples(pool_name) for pool_name in pools_by_kw)
            ):
                combined_count = prod(count for _, _, count in kw_roll_count_tuples)
                rolls_by_name = {name: roll for name, roll, _ in kw_roll_count_tuples}
                yield dependent_term(**rolls_by_name), combined_count

        return aggregate_weighted(_resolve_dependent_term_for_rolls()).lowest_terms()

    @experimental
    @beartype
    def is_homogeneous(self) -> bool:
        r"""
        !!! warning "Experimental"

            This property should be considered experimental and may change or disappear
            in future versions.

        Returns whether the pool’s population of histograms is homogeneous.

        ``` python
        >>> P(6, 6).is_homogeneous()
        True
        >>> P(4, 6, 8).is_homogeneous()
        False

        ```
        """
        return len(set(self._hs)) <= 1

    @experimental
    @beartype
    def appearances_in_rolls(self, outcome: RealLike) -> H:
        r"""
        !!! warning "Experimental"

            This method should be considered experimental and may change or disappear in
            future versions. While it does provide a performance improvement over other
            techniques, it is not significant for most applications, and rarely
            justifies the corresponding reduction in readability.

        Returns a histogram where the outcomes (keys) are the number of times *outcome*
        appears, and the counts are the number of rolls where *outcome* appears
        precisely that number of times. Equivalent to ``#!python H((sum(1 for v in roll
        if v == outcome), count) for roll, count in self.rolls_with_counts())``, but
        much more efficient.

        ``` python
        >>> p_2d6 = P(6, 6)
        >>> sorted(p_2d6.rolls_with_counts())
        [((1, 1), 1), ((1, 2), 2), ((1, 3), 2), ((1, 4), 2), ((1, 5), 2), ((1, 6), 2), ...]
        >>> p_2d6.appearances_in_rolls(1)
        H({0: 25, 1: 10, 2: 1})

        ```

        ``` python
        >>> # Least efficient, by far
        >>> d4, d6 = H(4), H(6)
        >>> p_3d4_2d6 = P(d4, d4, d4, d6, d6)
        >>> H((sum(1 for v in roll if v == 3), count) for roll, count in p_3d4_2d6.rolls_with_counts())
        H({0: 675, 1: 945, 2: 522, 3: 142, 4: 19, 5: 1})

        ```

        ``` python
        >>> # Pretty darned efficient, generalizable to other boolean inquiries, and
        >>> # arguably the most readable
        >>> d4_eq3, d6_eq3 = d4.eq(3), d6.eq(3)
        >>> 3@d4_eq3 + 2@d6_eq3
        H({0: 675, 1: 945, 2: 522, 3: 142, 4: 19, 5: 1})

        ```

        ``` python
        >>> # Most efficient for large sets of dice
        >>> p_3d4_2d6.appearances_in_rolls(3)
        H({0: 675, 1: 945, 2: 522, 3: 142, 4: 19, 5: 1})

        ```

        Based on some rudimentary testing, this method appears to converge on being
        about twice as fast as the boolean accumulation technique for larger sets.

        ``` python
        --8<-- "docs/assets/perf_appearances_in_rolls.txt"
        ```

        <details>
        <summary>Source: <a href="https://github.com/posita/dyce/blob/latest/docs/assets/perf_appearances_in_rolls.ipy"><code>perf_appearances_in_rolls.ipy</code></a></summary>

        ``` python
        --8<-- "docs/assets/perf_appearances_in_rolls.ipy"
        ```
        </details>
        """
        group_counters: list[Counter[RealLike]] = []

        for h, hs in groupby(self):
            group_counter: Counter[RealLike] = Counter()
            n = sum(1 for _ in hs)

            for k in range(0, n + 1):
                group_counter[k] = h.exactly_k_times_in_n(outcome, n, k) * (
                    group_counter[k] if group_counter[k] else 1
                )

            group_counters.append(group_counter)

        return sum_h(H(group_counter) for group_counter in group_counters)

    @beartype
    def roll(self) -> RollT:
        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.
        """
        return tuple(sorted_outcomes(h.roll() for h in self))

    @beartype
    def rolls_with_counts(self, *which: _GetItemT) -> Iterator[_RollCountT]:
        r"""
        Returns an iterator yielding two-tuples (pairs) that, collectively, enumerate all
        possible outcomes for the pool. The first item in the two-tuple is a sorted
        sequence of the outcomes for a distinct roll. The second is the count for that
        roll. Outcomes in each roll are ordered least to greatest.

        If one or more arguments are provided, this methods selects subsets of outcomes
        for each roll. Outcomes in each roll are ordered from least (index ``#!python
        0``) to greatest (index ``#!python -1`` or ``#!python len(self) - 1``).
        Identifiers can be ``#!python int``s or ``#!python slice``s, and can be mixed
        for more flexible selections.

        ``` python
        >>> from collections import Counter

        >>> def accumulate_roll_counts(counter, roll_counts):
        ...   for roll, count in roll_counts:
        ...     counter[roll] += count
        ...   return counter

        >>> p_6d6 = 6@P(6)
        >>> every_other_d6 = accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(slice(None, None, -2))) ; every_other_d6
        Counter({(6, 4, 2): 4110, (6, 5, 3): 3390, (6, 4, 3): 3330, ..., (3, 3, 3): 13, (2, 2, 2): 7, (1, 1, 1): 1})
        >>> accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(5, 3, 1)) == every_other_d6
        True
        >>> accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(*range(5, 0, -2))) == every_other_d6
        True
        >>> accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(*(i for i in range(6, 0, -1) if i % 2 == 1))) == every_other_d6
        True

        ```

        One way to model the likelihood of achieving a “Yhatzee” (i.e., where five
        six-sided dice show the same face) on a single roll by checking rolls for where
        the least and greatest outcomes are the same.

        ``` python
        >>> p_5d6 = 5@P(6)
        >>> yhatzee_on_single_roll = H(
        ...   (1 if roll[0] == roll[-1] else 0, count)
        ...   for roll, count
        ...   in p_5d6.rolls_with_counts()
        ... )
        >>> print(yhatzee_on_single_roll.format(width=0))
        {..., 0: 99.92%, 1:  0.08%}

        ```

        !!! note "In the general case, rolls may appear more than once."

            ``` python
            >>> 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)]

            ```

            In the above, ``#!python (1, 2)`` appears a total of two times, each with
            counts of one.

            However, if the pool is homogeneous (meaning it only contains identical
            histograms), rolls (before selection) are not repeated. (See the note on
            implementation below.)

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

            ```

            Either way, by summing and counting all rolls, we can confirm identity.

            ``` python
            >>> d6 = H(6)
            >>> d6avg = H((2, 3, 3, 4, 4, 5))
            >>> p = 2@P(d6, d6avg)
            >>> H((sum(roll), count) for roll, count in p.rolls_with_counts()) == p.h() == d6 + d6 + d6avg + d6avg
            True

            ```

        This method does not try to outsmart callers by (mis)interpreting selection
        arguments. It honors selection identifier order and any redundancy.

        ``` python
        >>> p_d3_d4 = P(H(3), H(4))
        >>> # Select the second, first, then second (again) elements
        >>> sorted(p_d3_d4.rolls_with_counts(-1, 0, 1))
        [((1, 1, 1), 1), ((2, 1, 2), 1), ((2, 1, 2), 1), ..., ((4, 1, 4), 1), ((4, 2, 4), 1), ((4, 3, 4), 1)]

        ```

        Selecting the same outcomes, but in a different order is not immediately
        comparable.

        ``` python
        >>> select_0_1 = sorted(p_d3_d4.rolls_with_counts(0, 1))
        >>> select_1_0 = sorted(p_d3_d4.rolls_with_counts(1, 0))
        >>> select_0_1 == select_1_0
        False

        ```

        Equivalence can be tested when selected outcomes are sorted.

        ``` python
        >>> sorted_0_1 = sorted((sorted(roll), count) for roll, count in select_0_1)
        >>> sorted_1_0 = sorted((sorted(roll), count) for roll, count in select_1_0)
        >>> sorted_0_1 == sorted_1_0
        True

        ```

        They can also be summed and counted which is equivalent to calling the
        [``h`` method][dyce.p.P.h] with identical selection arguments.

        ``` python
        >>> summed_0_1 = H((sum(roll), count) for roll, count in select_0_1)
        >>> summed_1_0 = H((sum(roll), count) for roll, count in select_1_0)
        >>> summed_0_1 == summed_1_0 == p_d3_d4.h(0, 1) == p_d3_d4.h(1, 0)
        True

        ```

        !!! info "About the implementation"

            Enumeration is substantially more efficient for homogeneous pools than
            heterogeneous ones, because we are able to avoid the expensive enumeration
            of the Cartesian product using several techniques.

            Taking $k$ outcomes, where $k$ selects fewer than all $n$ outcomes a
            homogeneous pool benefits from [Ilmari Karonen’s
            optimization](https://rpg.stackexchange.com/a/166663/71245), which appears
            to scale geometrically with $k$ times some factor of $n$ (e.g., $\log n$,
            but I haven’t bothered to figure that out yet), such that—in observed
            testing, at least—it is generally the fastest approach for $k < n$.

            Where $k = n$, we leverage the [*multinomial
            coefficient*](https://en.wikipedia.org/wiki/Permutation#Permutations_of_multisets),
            which appears to scale generally with $n$.

            $$
            {{n} \choose {{{k}_{1}},{{k}_{2}},\ldots,{{k}_{m}}}}
            = {\frac {{n}!} {{{k}_{1}}! {{k}_{2}}! \cdots {{k}_{m}}!}}
            $$

            We enumerate combinations with replacements, and then the compute the number
            of permutations with repetitions for each combination. Consider ``#!python
            n@P(H(m))``. Enumerating combinations with replacements would yield all
            unique rolls.

            ``#!python ((1, 1, …, 1), (1, 1, …, 2), …, (1, 1, …, m), …, (m - 1, m, …,
            m), (m, m, …, m))``

            To determine the count for a particular roll ``#!python (a, b, …, n)``, we
            compute the multinomial coefficient for that roll and multiply by the scalar
            ``#!python H(m)[a] * H(m)[b] * … * H(m)[n]``. (See
            [this](https://www.lucamoroni.it/the-dice-roll-sum-problem/) for an in-depth
            exploration of the topic.)

            Further, this implementation attempts to optimize heterogeneous pools by
            breaking them into homogeneous groups before computing the Cartesian product
            of those sub-results. This approach allows homogeneous pools to be ordered
            without duplicates, where heterogeneous ones offer no such guarantees.

            As expected, this optimization allows the performance of arbitrary selection
            from mixed pools to sit between that of purely homogeneous and purely
            heterogeneous ones. Note, however, that all three appear to scale
            geometrically in some way.

            ``` python
            --8<-- "docs/assets/perf_rolls_with_counts.txt"
            ```

            <details>
            <summary>Source: <a href="https://github.com/posita/dyce/blob/latest/docs/assets/perf_rolls_with_counts.ipy"><code>perf_rolls_with_counts.ipy</code></a></summary>

            ``` python
            --8<-- "docs/assets/perf_rolls_with_counts.ipy"
            ```
            </details>
        """
        n = len(self)

        if not which:
            i: Optional[int] = n
        else:
            i = _analyze_selection(n, which)

        if i == 0 or n == 0:
            rolls_with_counts_iter: Iterable[_RollCountT] = iter(())
        else:
            groups = tuple((h, sum(1 for _ in hs)) for h, hs in groupby(self))

            if len(groups) == 1:
                # Based on cursory performance analysis, calling the homogeneous
                # implementation directly provides about a 15% performance savings over
                # merely falling through to _rwc_heterogeneous_h_groups. Maybe
                # itertools.product adds significant overhead?
                h, hn = groups[0]
                assert hn == n

                # Still in search of a better (i.e., more efficient) way:
                # <https://math.stackexchange.com/questions/4173084/probability-distribution-of-k-1-k-2-cdots-k-m-selections-of-arbitrary-posi>
                if i and abs(i) < n:
                    rolls_with_counts_iter = _rwc_homogeneous_n_h_using_partial_selection(
                        n,
                        h,
                        i,
                        # This is just padding to allow for consistent indexing. They
                        # are deselected (i.e., not returned) below.
                        fill=0,
                    )
                else:
                    rolls_with_counts_iter = (
                        _rwc_homogeneous_n_h_using_partial_selection(n, h, n)
                    )
            else:
                rolls_with_counts_iter = _rwc_heterogeneous_h_groups(groups, i)

        for sorted_outcomes_for_roll, roll_count in rolls_with_counts_iter:
            if which:
                taken_outcomes = tuple(getitems(sorted_outcomes_for_roll, which))
            else:
                taken_outcomes = sorted_outcomes_for_roll

            yield taken_outcomes, roll_count

    @beartype
    def map(self, op: _BinaryOperatorT, right_operand: _OperandT) -> "P":
        r"""
        Shorthand for ``#!python P(*(h.map(op, right_operand) for h in self))``. See the
        [``H.map`` method][dyce.h.H.map].

        ``` python
        >>> import operator
        >>> p_3d6 = 3@P(H((-3, -1, 2, 4)))
        >>> p_3d6.map(operator.__mul__, -1)
        3@P(H({-4: 1, -2: 1, 1: 1, 3: 1}))

        ```
        """
        return P(*(h.map(op, right_operand) for h in self))

    @beartype
    def rmap(self, left_operand: RealLike, op: _BinaryOperatorT) -> "P":
        r"""
        Shorthand for ``#!python P(*(h.rmap(left_operand, op) for h in self))``. See the
        [``H.rmap`` method][dyce.h.H.rmap].

        ``` python
        >>> import operator
        >>> from fractions import Fraction
        >>> p_3d6 = 2@P(H((-3, -1, 2, 4)))
        >>> p_3d6.umap(Fraction).rmap(1, operator.__truediv__)
        2@P(H({Fraction(-1, 1): 1, Fraction(-1, 3): 1, Fraction(1, 4): 1, Fraction(1, 2): 1}))

        ```
        """
        return P(*(h.rmap(left_operand, op) for h in self))

    @beartype
    def umap(self, op: _UnaryOperatorT) -> "P":
        r"""
        Shorthand for ``#!python P(*(h.umap(op) for h in self))``. See the
        [``H.umap`` method][dyce.h.H.umap].

        ``` python
        >>> import operator
        >>> p_3d6 = 3@P(H((-3, -1, 2, 4)))
        >>> p_3d6.umap(operator.__neg__)
        3@P(H({-4: 1, -2: 1, 1: 1, 3: 1}))
        >>> p_3d6.umap(operator.__abs__)
        3@P(H({1: 1, 2: 1, 3: 1, 4: 1}))

        ```
        """
        return P(*(h.umap(op) for h in self))

__slots__: Any = ('_hs', '_total') class-attribute instance-attribute

total: int property

Experimental

This method should be considered experimental and may change or disappear in future versions.

Equivalent to prod(h.total for h in self). Note that—consistent with the empty product—this is 1 for an empty pool.

__eq__(other) -> bool

Source code in dyce/p.py
270
271
272
273
274
275
@beartype
def __eq__(self, other) -> bool:
    if isinstance(other, P):
        return __eq__(self._hs, other._hs)
    else:
        return NotImplemented

__getitem__(key: _GetItemT) -> Union[H, P]

Source code in dyce/p.py
296
297
298
299
300
301
@beartype
def __getitem__(self, key: _GetItemT) -> Union[H, "P"]:
    if isinstance(key, slice):
        return P(*self._hs[key])
    else:
        return self._hs[__index__(key)]

__init__(*args: Union[SupportsInt, P, H]) -> None

Initializer.

Source code in dyce/p.py
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
@beartype
# TODO(posita): See <https://github.com/beartype/beartype/issues/152>
def __init__(self, *args: Union[SupportsInt, "P", H]) -> None:
    r"Initializer."
    super().__init__()

    def _gen_hs() -> Iterator[H]:
        for a in args:
            if isinstance(a, H):
                yield a
            elif isinstance(a, P):
                for h in a._hs:
                    yield h
            elif isinstance(a, SupportsInt):
                yield H(a)
            else:
                raise TypeError(f"unrecognized initializer type {a!r}")

    hs = list(h for h in _gen_hs() if h)

    try:
        hs.sort(key=lambda h: tuple(h.items()))
    except TypeError:
        # This is for outcomes that don't support direct comparisons, like symbolic
        # representations
        hs.sort(key=lambda h: str(tuple(h.items())))

    self._hs = tuple(hs)
    self._total: int = prod(h.total for h in self._hs)

__iter__() -> Iterator[H]

Source code in dyce/p.py
303
304
305
@beartype
def __iter__(self) -> Iterator[H]:
    return iter(self._hs)

__len__() -> int

Source code in dyce/p.py
284
285
286
@beartype
def __len__(self) -> int:
    return len(self._hs)

__matmul__(other: SupportsInt) -> P

Source code in dyce/p.py
307
308
309
310
311
312
313
314
315
316
317
@beartype
def __matmul__(self, other: SupportsInt) -> "P":
    try:
        other = as_int(other)
    except TypeError:
        return NotImplemented

    if other < 0:
        raise ValueError("argument cannot be negative")
    else:
        return P(*chain.from_iterable(repeat(self, other)))

__ne__(other) -> bool

Source code in dyce/p.py
277
278
279
280
281
282
@beartype
def __ne__(self, other) -> bool:
    if isinstance(other, P):
        return __ne__(self._hs, other._hs)
    else:
        return NotImplemented

__repr__() -> str

Source code in dyce/p.py
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
@beartype
def __repr__(self) -> str:
    group_counters: dict[H, int] = {}

    for h, hs in groupby(self):
        n = sum(1 for _ in hs)
        group_counters[h] = n

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

    if len(group_counters) == 1:
        h = next(iter(group_counters))

        if group_counters[h] == 1:
            return f"{type(self).__name__}({_n_at(h, 1)})"
        else:
            return _n_at(h, group_counters[h])
    else:
        args = ", ".join(_n_at(h, n) for h, n in group_counters.items())

        return f"{type(self).__name__}({args})"

__rmatmul__(other: SupportsInt) -> P

Source code in dyce/p.py
319
320
321
@beartype
def __rmatmul__(self, other: SupportsInt) -> "P":
    return self.__matmul__(other)

appearances_in_rolls(outcome: RealLike) -> H

Experimental

This method should be considered experimental and may change or disappear in future versions. While it does provide a performance improvement over other techniques, it is not significant for most applications, and rarely justifies the corresponding reduction in readability.

Returns a histogram where the outcomes (keys) are the number of times outcome appears, and the counts are the number of rolls where outcome appears precisely that number of times. Equivalent to H((sum(1 for v in rollif v == outcome), count) for roll, count in self.rolls_with_counts()), but much more efficient.

1
2
3
4
5
>>> p_2d6 = P(6, 6)
>>> sorted(p_2d6.rolls_with_counts())
[((1, 1), 1), ((1, 2), 2), ((1, 3), 2), ((1, 4), 2), ((1, 5), 2), ((1, 6), 2), ...]
>>> p_2d6.appearances_in_rolls(1)
H({0: 25, 1: 10, 2: 1})
1
2
3
4
5
>>> # Least efficient, by far
>>> d4, d6 = H(4), H(6)
>>> p_3d4_2d6 = P(d4, d4, d4, d6, d6)
>>> H((sum(1 for v in roll if v == 3), count) for roll, count in p_3d4_2d6.rolls_with_counts())
H({0: 675, 1: 945, 2: 522, 3: 142, 4: 19, 5: 1})
1
2
3
4
5
>>> # Pretty darned efficient, generalizable to other boolean inquiries, and
>>> # arguably the most readable
>>> d4_eq3, d6_eq3 = d4.eq(3), d6.eq(3)
>>> 3@d4_eq3 + 2@d6_eq3
H({0: 675, 1: 945, 2: 522, 3: 142, 4: 19, 5: 1})
1
2
3
>>> # Most efficient for large sets of dice
>>> p_3d4_2d6.appearances_in_rolls(3)
H({0: 675, 1: 945, 2: 522, 3: 142, 4: 19, 5: 1})

Based on some rudimentary testing, this method appears to converge on being about twice as fast as the boolean accumulation technique for larger sets.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
%timeit 3@d4_eq3 + 2@d6_eq3
30 µs ± 111 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

%timeit P(3@P(4), 2@P(6)).appearances_in_rolls(3)
64.7 µs ± 570 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

%timeit 9@d4_eq3 + 6@d6_eq3
134 µs ± 2.24 µs per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

%timeit P(9@P(4), 6@P(6)).appearances_in_rolls(3)
120 µs ± 670 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)

%timeit 27@d4_eq3 + 18@d6_eq3
803 µs ± 2.62 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

%timeit P(27@P(4), 18@P(6)).appearances_in_rolls(3)
426 µs ± 1.8 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

%timeit 81@d4_eq3 + 54@d6_eq3
6.36 ms ± 20 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

%timeit P(81@P(4), 54@P(6)).appearances_in_rolls(3)
2.61 ms ± 5.41 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
Source: perf_appearances_in_rolls.ipy
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
from dyce import H, P

p_2d6 = P(6, 6)
d4, d6 = H(4), H(6)
p_3d4_2d6 = P(d4, d4, d4, d6, d6)
d4_eq3, d6_eq3 = d4.eq(2), d6.eq(2)

print(f"%timeit 3@d4_eq3 + 2@d6_eq3")
%timeit 3@d4_eq3 + 2@d6_eq3
print()

print(f"%timeit P(3@P(4), 2@P(6)).appearances_in_rolls(3)")
%timeit P(3@P(4), 2@P(6)).appearances_in_rolls(3)
print()

print(f"%timeit 9@d4_eq3 + 6@d6_eq3")
%timeit 9@d4_eq3 + 6@d6_eq3
print()

print(f"%timeit P(9@P(4), 6@P(6)).appearances_in_rolls(3)")
%timeit P(9@P(4), 6@P(6)).appearances_in_rolls(3)
print()

print(f"%timeit 27@d4_eq3 + 18@d6_eq3")
%timeit 27@d4_eq3 + 18@d6_eq3
print()

print(f"%timeit P(27@P(4), 18@P(6)).appearances_in_rolls(3)")
%timeit P(27@P(4), 18@P(6)).appearances_in_rolls(3)
print()

print(f"%timeit 81@d4_eq3 + 54@d6_eq3")
%timeit 81@d4_eq3 + 54@d6_eq3
print()

print(f"%timeit P(81@P(4), 54@P(6)).appearances_in_rolls(3)")
%timeit P(81@P(4), 54@P(6)).appearances_in_rolls(3)
print()
Source code in dyce/p.py
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
@experimental
@beartype
def appearances_in_rolls(self, outcome: RealLike) -> H:
    r"""
    !!! warning "Experimental"

        This method should be considered experimental and may change or disappear in
        future versions. While it does provide a performance improvement over other
        techniques, it is not significant for most applications, and rarely
        justifies the corresponding reduction in readability.

    Returns a histogram where the outcomes (keys) are the number of times *outcome*
    appears, and the counts are the number of rolls where *outcome* appears
    precisely that number of times. Equivalent to ``#!python H((sum(1 for v in roll
    if v == outcome), count) for roll, count in self.rolls_with_counts())``, but
    much more efficient.

    ``` python
    >>> p_2d6 = P(6, 6)
    >>> sorted(p_2d6.rolls_with_counts())
    [((1, 1), 1), ((1, 2), 2), ((1, 3), 2), ((1, 4), 2), ((1, 5), 2), ((1, 6), 2), ...]
    >>> p_2d6.appearances_in_rolls(1)
    H({0: 25, 1: 10, 2: 1})

    ```

    ``` python
    >>> # Least efficient, by far
    >>> d4, d6 = H(4), H(6)
    >>> p_3d4_2d6 = P(d4, d4, d4, d6, d6)
    >>> H((sum(1 for v in roll if v == 3), count) for roll, count in p_3d4_2d6.rolls_with_counts())
    H({0: 675, 1: 945, 2: 522, 3: 142, 4: 19, 5: 1})

    ```

    ``` python
    >>> # Pretty darned efficient, generalizable to other boolean inquiries, and
    >>> # arguably the most readable
    >>> d4_eq3, d6_eq3 = d4.eq(3), d6.eq(3)
    >>> 3@d4_eq3 + 2@d6_eq3
    H({0: 675, 1: 945, 2: 522, 3: 142, 4: 19, 5: 1})

    ```

    ``` python
    >>> # Most efficient for large sets of dice
    >>> p_3d4_2d6.appearances_in_rolls(3)
    H({0: 675, 1: 945, 2: 522, 3: 142, 4: 19, 5: 1})

    ```

    Based on some rudimentary testing, this method appears to converge on being
    about twice as fast as the boolean accumulation technique for larger sets.

    ``` python
    --8<-- "docs/assets/perf_appearances_in_rolls.txt"
    ```

    <details>
    <summary>Source: <a href="https://github.com/posita/dyce/blob/latest/docs/assets/perf_appearances_in_rolls.ipy"><code>perf_appearances_in_rolls.ipy</code></a></summary>

    ``` python
    --8<-- "docs/assets/perf_appearances_in_rolls.ipy"
    ```
    </details>
    """
    group_counters: list[Counter[RealLike]] = []

    for h, hs in groupby(self):
        group_counter: Counter[RealLike] = Counter()
        n = sum(1 for _ in hs)

        for k in range(0, n + 1):
            group_counter[k] = h.exactly_k_times_in_n(outcome, n, k) * (
                group_counter[k] if group_counter[k] else 1
            )

        group_counters.append(group_counter)

    return sum_h(H(group_counter) for group_counter in group_counters)

foreach(dependent_term: Callable[..., Union[H, RealLike]], **independent_sources: Union[P, H, HableT, _SourceT]) -> H classmethod

Deprecated

This method has been deprecated and will be removed in a future release. See the expandable decorator and foreach function for more flexible alternatives.

Calls dependent_term for each unique set of rolls from the product of independent_sources and accumulates the results. This is useful for resolving dependent probabilities. Rolls are sorted least to greatest. Returned histograms are always reduced to their lowest terms.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
>>> from dyce.p import RollT

>>> def three_way_vs(first: RollT, second: RollT, third: RollT):
...   first_reversed = first[::-1]
...   second_reversed = second[::-1]
...   third_reversed = third[::-1]
...   if first_reversed > second_reversed and first_reversed > third_reversed:
...     return 1  # first is the clear winner
...   elif second_reversed > first_reversed and second_reversed > third_reversed:
...     return 2  # second is the clear winner
...   elif third_reversed > first_reversed and third_reversed > second_reversed:
...     return 3  # third is the clear winner
...   else:
...     return 0  # there was a tie somewhere

>>> P.foreach(
...   three_way_vs,
...   first=P(6, 6),  # first has pool of two d6s
...   second=P(6, 6),  # second has pool of two d6s
...   third=P(4, 8),  # third has pool of one d4 and one d8
... )
H({0: 1103, 1: 5783, 2: 5783, 3: 8067})

When all of foreach’s arguments are P objects of size 1 or anything other than a P object, this function behaves similarly to H.foreach (although the signature of the dependent_term callback function differs slightly between the two interfaces).

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
>>> from itertools import chain
>>> P.foreach(
...   lambda **kw: sum(chain(*kw.values())),  # receives single-element rolls
...   src1=P(6),  # pool of size 1
...   src2=H(6),  # histogram
...   src3=range(6, 0, -1),  # histogram source
... ) == H.foreach(
...   lambda **kw: sum(kw.values()),  # receives outcomes
...   src1=P(6).h(),  # histogram
...   src2=H(6),  # histogram
...   src3={1, 2, 3, 4, 5, 6},  # histogram source
... )
True

The foreach class method is equivalent to nesting loops iterating over P.rolls_with_counts for each independent term and then aggregating the results.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
>>> def dependent_term(
...   *,
...   roll_1,
...   roll_2,
...   # ...
...   roll_n,
... ):
...   return (
...     (roll_2[-1] > roll_1[-1])
...     + (roll_n[-1] > roll_2[-1])
...     # ...
...   )

>>> source_1 = P(8)
>>> source_2 = P(6, 6)
>>> # ...
>>> source_n = P(4, 4, 4)

>>> h = P.foreach(
...   dependent_term,
...   roll_1=source_1,
...   roll_2=source_2,
...   # ...
...   roll_n=source_n,
... ) ; h
H({0: 3821, 1: 5126, 2: 269})

>>> def resolve():
...   for roll_1, count_1 in source_1.rolls_with_counts():
...     for roll_2, count_2 in source_2.rolls_with_counts():
...       # ...
...       for roll_n, count_n in source_n.rolls_with_counts():
...         # ...
...           yield dependent_term(
...             roll_1=roll_1,
...             roll_2=roll_2,
...             # ...
...             roll_n=roll_n,
...         ), (
...           count_1
...           * count_2
...           # * ...
...           * count_n
...         )

>>> from dyce.evaluation import aggregate_weighted
>>> aggregate_weighted(resolve()) == h
True
Source code in dyce/p.py
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
@classmethod
@deprecated
@beartype
def foreach(
    cls,
    dependent_term: Callable[..., Union[H, RealLike]],
    # TODO(posita): See <https://github.com/beartype/beartype/issues/152>
    **independent_sources: Union["P", H, HableT, _SourceT],
) -> H:
    r"""
    !!! warning "Deprecated"

        This method has been deprecated and will be removed in a future release. See
        the [``expandable`` decorator][dyce.evaluation.expandable] and
        [``foreach`` function][dyce.evaluation.foreach] for more flexible
        alternatives.

    Calls ``#!python dependent_term`` for each unique set of rolls from the product
    of ``independent_sources`` and accumulates the results. This is useful for
    resolving dependent probabilities. Rolls are sorted least to greatest. Returned
    histograms are always reduced to their lowest terms.

    ``` python
    >>> from dyce.p import RollT

    >>> def three_way_vs(first: RollT, second: RollT, third: RollT):
    ...   first_reversed = first[::-1]
    ...   second_reversed = second[::-1]
    ...   third_reversed = third[::-1]
    ...   if first_reversed > second_reversed and first_reversed > third_reversed:
    ...     return 1  # first is the clear winner
    ...   elif second_reversed > first_reversed and second_reversed > third_reversed:
    ...     return 2  # second is the clear winner
    ...   elif third_reversed > first_reversed and third_reversed > second_reversed:
    ...     return 3  # third is the clear winner
    ...   else:
    ...     return 0  # there was a tie somewhere

    >>> P.foreach(
    ...   three_way_vs,
    ...   first=P(6, 6),  # first has pool of two d6s
    ...   second=P(6, 6),  # second has pool of two d6s
    ...   third=P(4, 8),  # third has pool of one d4 and one d8
    ... )
    H({0: 1103, 1: 5783, 2: 5783, 3: 8067})

    ```

    When all of ``#!python foreach``’s arguments are [``P`` objects][dyce.p.P] of
    size 1 or anything other than a ``P`` object, this function behaves similarly to
    [``H.foreach``][dyce.h.H] (although the signature of the *dependent_term*
    callback function differs slightly between the two interfaces).

    ``` python
    >>> from itertools import chain
    >>> P.foreach(
    ...   lambda **kw: sum(chain(*kw.values())),  # receives single-element rolls
    ...   src1=P(6),  # pool of size 1
    ...   src2=H(6),  # histogram
    ...   src3=range(6, 0, -1),  # histogram source
    ... ) == H.foreach(
    ...   lambda **kw: sum(kw.values()),  # receives outcomes
    ...   src1=P(6).h(),  # histogram
    ...   src2=H(6),  # histogram
    ...   src3={1, 2, 3, 4, 5, 6},  # histogram source
    ... )
    True

    ```

    The ``#!python foreach`` class method is equivalent to nesting loops iterating
    over [``P.rolls_with_counts``][dyce.p.P.rolls_with_counts] for each independent
    term and then aggregating the results.

    ``` python
    >>> def dependent_term(
    ...   *,
    ...   roll_1,
    ...   roll_2,
    ...   # ...
    ...   roll_n,
    ... ):
    ...   return (
    ...     (roll_2[-1] > roll_1[-1])
    ...     + (roll_n[-1] > roll_2[-1])
    ...     # ...
    ...   )

    >>> source_1 = P(8)
    >>> source_2 = P(6, 6)
    >>> # ...
    >>> source_n = P(4, 4, 4)

    >>> h = P.foreach(
    ...   dependent_term,
    ...   roll_1=source_1,
    ...   roll_2=source_2,
    ...   # ...
    ...   roll_n=source_n,
    ... ) ; h
    H({0: 3821, 1: 5126, 2: 269})

    >>> def resolve():
    ...   for roll_1, count_1 in source_1.rolls_with_counts():
    ...     for roll_2, count_2 in source_2.rolls_with_counts():
    ...       # ...
    ...       for roll_n, count_n in source_n.rolls_with_counts():
    ...         # ...
    ...           yield dependent_term(
    ...             roll_1=roll_1,
    ...             roll_2=roll_2,
    ...             # ...
    ...             roll_n=roll_n,
    ...         ), (
    ...           count_1
    ...           * count_2
    ...           # * ...
    ...           * count_n
    ...         )

    >>> from dyce.evaluation import aggregate_weighted
    >>> aggregate_weighted(resolve()) == h
    True

    ```
    """
    from dyce.evaluation import aggregate_weighted

    pools_by_kw: dict[str, P] = {}

    for source_name, source in independent_sources.items():
        if isinstance(source, H):
            pools_by_kw[source_name] = P(source)
        elif isinstance(source, P):
            pools_by_kw[source_name] = source
        elif isinstance(source, HableT):
            pools_by_kw[source_name] = P(source.h())
        else:
            pools_by_kw[source_name] = P(H(source))

    def _kw_roll_count_tuples(
        pool_name: str,
    ) -> Iterator[tuple[str, RollT, int]]:
        for roll, count in pools_by_kw[pool_name].rolls_with_counts():
            yield pool_name, roll, count

    def _resolve_dependent_term_for_rolls() -> (
        Iterator[tuple[Union[H, RealLike], int]]
    ):
        for kw_roll_count_tuples in product(
            *(_kw_roll_count_tuples(pool_name) for pool_name in pools_by_kw)
        ):
            combined_count = prod(count for _, _, count in kw_roll_count_tuples)
            rolls_by_name = {name: roll for name, roll, _ in kw_roll_count_tuples}
            yield dependent_term(**rolls_by_name), combined_count

    return aggregate_weighted(_resolve_dependent_term_for_rolls()).lowest_terms()

h(*which: _GetItemT) -> H

Roughly equivalent to H((sum(roll), count) for roll, count inself.rolls_with_counts(*which)) with some short-circuit optimizations.

When provided no arguments, h combines (or “flattens”) contained histograms 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})

If one or more arguments are provided, this method sums subsets of outcomes those arguments identify for each roll. Outcomes are ordered from least (index 0) to greatest (index -1 or len(self) -1). 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())
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(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
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
@beartype
def h(self, *which: _GetItemT) -> H:
    r"""
    Roughly equivalent to ``#!python H((sum(roll), count) for roll, count in
    self.rolls_with_counts(*which))`` with some short-circuit optimizations.

    When provided no arguments, ``#!python h`` combines (or “flattens”) contained
    histograms in accordance with the [``HableT`` protocol][dyce.h.HableT].

    ``` python
    >>> (2@P(6)).h()
    H({2: 1, 3: 2, 4: 3, 5: 4, 6: 5, 7: 6, 8: 5, 9: 4, 10: 3, 11: 2, 12: 1})

    ```

    If one or more arguments are provided, this method sums subsets of outcomes
    those arguments identify for each roll. Outcomes are ordered from least (index
    ``#!python 0``) to greatest (index ``#!python -1`` or ``#!python len(self) -
    1``). 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:

    ``` python
    >>> 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())
    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:

    ``` python
    >>> 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(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.

    ``` python
    >>> 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 which:
        n = len(self)
        i = _analyze_selection(n, which)

        if i and i >= n:
            # The caller selected all dice in the pool exactly i // n times, so we
            # can short-circuit roll enumeration
            assert i % n == 0

            return self.h() * (i // n)
        else:
            return H(
                (sum(roll), count) for roll, count in self.rolls_with_counts(*which)
            )
    else:
        # The caller offered no selection
        return sum_h(self)

is_homogeneous() -> bool

Experimental

This property should be considered experimental and may change or disappear in future versions.

Returns whether the pool’s population of histograms is homogeneous.

1
2
3
4
>>> P(6, 6).is_homogeneous()
True
>>> P(4, 6, 8).is_homogeneous()
False
Source code in dyce/p.py
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
@experimental
@beartype
def is_homogeneous(self) -> bool:
    r"""
    !!! warning "Experimental"

        This property should be considered experimental and may change or disappear
        in future versions.

    Returns whether the pool’s population of histograms is homogeneous.

    ``` python
    >>> P(6, 6).is_homogeneous()
    True
    >>> P(4, 6, 8).is_homogeneous()
    False

    ```
    """
    return len(set(self._hs)) <= 1

map(op: _BinaryOperatorT, right_operand: _OperandT) -> P

Shorthand for P(*(h.map(op, right_operand) for h in self)). See the H.map method.

1
2
3
4
>>> import operator
>>> p_3d6 = 3@P(H((-3, -1, 2, 4)))
>>> p_3d6.map(operator.__mul__, -1)
3@P(H({-4: 1, -2: 1, 1: 1, 3: 1}))
Source code in dyce/p.py
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
@beartype
def map(self, op: _BinaryOperatorT, right_operand: _OperandT) -> "P":
    r"""
    Shorthand for ``#!python P(*(h.map(op, right_operand) for h in self))``. See the
    [``H.map`` method][dyce.h.H.map].

    ``` python
    >>> import operator
    >>> p_3d6 = 3@P(H((-3, -1, 2, 4)))
    >>> p_3d6.map(operator.__mul__, -1)
    3@P(H({-4: 1, -2: 1, 1: 1, 3: 1}))

    ```
    """
    return P(*(h.map(op, right_operand) for h in self))

rmap(left_operand: RealLike, op: _BinaryOperatorT) -> P

Shorthand for P(*(h.rmap(left_operand, op) for h in self)). See the H.rmap method.

1
2
3
4
5
>>> import operator
>>> from fractions import Fraction
>>> p_3d6 = 2@P(H((-3, -1, 2, 4)))
>>> p_3d6.umap(Fraction).rmap(1, operator.__truediv__)
2@P(H({Fraction(-1, 1): 1, Fraction(-1, 3): 1, Fraction(1, 4): 1, Fraction(1, 2): 1}))
Source code in dyce/p.py
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
@beartype
def rmap(self, left_operand: RealLike, op: _BinaryOperatorT) -> "P":
    r"""
    Shorthand for ``#!python P(*(h.rmap(left_operand, op) for h in self))``. See the
    [``H.rmap`` method][dyce.h.H.rmap].

    ``` python
    >>> import operator
    >>> from fractions import Fraction
    >>> p_3d6 = 2@P(H((-3, -1, 2, 4)))
    >>> p_3d6.umap(Fraction).rmap(1, operator.__truediv__)
    2@P(H({Fraction(-1, 1): 1, Fraction(-1, 3): 1, Fraction(1, 4): 1, Fraction(1, 2): 1}))

    ```
    """
    return P(*(h.rmap(left_operand, op) for h in self))

roll() -> RollT

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
682
683
684
685
686
687
688
689
690
691
692
693
694
@beartype
def roll(self) -> RollT:
    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.
    """
    return tuple(sorted_outcomes(h.roll() for h in self))

rolls_with_counts(*which: _GetItemT) -> Iterator[_RollCountT]

Returns an iterator yielding two-tuples (pairs) that, collectively, enumerate all possible outcomes for the pool. The first item in the two-tuple is a sorted sequence of the outcomes for a distinct roll. The second is the count for that roll. Outcomes in each roll are ordered least to greatest.

If one or more arguments are provided, this methods selects subsets of outcomes for each roll. Outcomes in each roll are ordered from least (index 0) to greatest (index -1 or len(self) - 1). Identifiers can be ints or slices, and can be mixed for more flexible selections.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
>>> from collections import Counter

>>> def accumulate_roll_counts(counter, roll_counts):
...   for roll, count in roll_counts:
...     counter[roll] += count
...   return counter

>>> p_6d6 = 6@P(6)
>>> every_other_d6 = accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(slice(None, None, -2))) ; every_other_d6
Counter({(6, 4, 2): 4110, (6, 5, 3): 3390, (6, 4, 3): 3330, ..., (3, 3, 3): 13, (2, 2, 2): 7, (1, 1, 1): 1})
>>> accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(5, 3, 1)) == every_other_d6
True
>>> accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(*range(5, 0, -2))) == every_other_d6
True
>>> accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(*(i for i in range(6, 0, -1) if i % 2 == 1))) == every_other_d6
True

One way to model the likelihood of achieving a “Yhatzee” (i.e., where five six-sided dice show the same face) on a single roll by checking rolls for where the least and greatest outcomes are the same.

1
2
3
4
5
6
7
8
>>> p_5d6 = 5@P(6)
>>> yhatzee_on_single_roll = H(
...   (1 if roll[0] == roll[-1] else 0, count)
...   for roll, count
...   in p_5d6.rolls_with_counts()
... )
>>> print(yhatzee_on_single_roll.format(width=0))
{..., 0: 99.92%, 1:  0.08%}

In the general case, rolls may appear more than once.

1
2
>>> 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)]

In the above, (1, 2) appears a total of two times, each with counts of one.

However, if the pool is homogeneous (meaning it only contains identical histograms), rolls (before selection) are not repeated. (See the note on implementation below.)

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

Either way, by summing and counting all rolls, we can confirm identity.

1
2
3
4
5
>>> d6 = H(6)
>>> d6avg = H((2, 3, 3, 4, 4, 5))
>>> p = 2@P(d6, d6avg)
>>> H((sum(roll), count) for roll, count in p.rolls_with_counts()) == p.h() == d6 + d6 + d6avg + d6avg
True

This method does not try to outsmart callers by (mis)interpreting selection arguments. It honors selection identifier order and any redundancy.

1
2
3
4
>>> p_d3_d4 = P(H(3), H(4))
>>> # Select the second, first, then second (again) elements
>>> sorted(p_d3_d4.rolls_with_counts(-1, 0, 1))
[((1, 1, 1), 1), ((2, 1, 2), 1), ((2, 1, 2), 1), ..., ((4, 1, 4), 1), ((4, 2, 4), 1), ((4, 3, 4), 1)]

Selecting the same outcomes, but in a different order is not immediately comparable.

1
2
3
4
>>> select_0_1 = sorted(p_d3_d4.rolls_with_counts(0, 1))
>>> select_1_0 = sorted(p_d3_d4.rolls_with_counts(1, 0))
>>> select_0_1 == select_1_0
False

Equivalence can be tested when selected outcomes are sorted.

1
2
3
4
>>> sorted_0_1 = sorted((sorted(roll), count) for roll, count in select_0_1)
>>> sorted_1_0 = sorted((sorted(roll), count) for roll, count in select_1_0)
>>> sorted_0_1 == sorted_1_0
True

They can also be summed and counted which is equivalent to calling the h method with identical selection arguments.

1
2
3
4
>>> summed_0_1 = H((sum(roll), count) for roll, count in select_0_1)
>>> summed_1_0 = H((sum(roll), count) for roll, count in select_1_0)
>>> summed_0_1 == summed_1_0 == p_d3_d4.h(0, 1) == p_d3_d4.h(1, 0)
True

About the implementation

Enumeration is substantially more efficient for homogeneous pools than heterogeneous ones, because we are able to avoid the expensive enumeration of the Cartesian product using several techniques.

Taking \(k\) outcomes, where \(k\) selects fewer than all \(n\) outcomes a homogeneous pool benefits from Ilmari Karonen’s optimization, which appears to scale geometrically with \(k\) times some factor of \(n\) (e.g., \(\log n\), but I haven’t bothered to figure that out yet), such that—in observed testing, at least—it is generally the fastest approach for \(k < n\).

Where \(k = n\), we leverage the multinomial coefficient, which appears to scale generally with \(n\).

\[ {{n} \choose {{{k}_{1}},{{k}_{2}},\ldots,{{k}_{m}}}} = {\frac {{n}!} {{{k}_{1}}! {{k}_{2}}! \cdots {{k}_{m}}!}} \]

We enumerate combinations with replacements, and then the compute the number of permutations with repetitions for each combination. Consider n@P(H(m)). Enumerating combinations with replacements would yield all unique rolls.

((1, 1, , 1), (1, 1, , 2), , (1, 1, , m), , (m - 1, m, ,m), (m, m, , m))

To determine the count for a particular roll (a, b, , n), we compute the multinomial coefficient for that roll and multiply by the scalar H(m)[a] * H(m)[b] * * H(m)[n]. (See this for an in-depth exploration of the topic.)

Further, this implementation attempts to optimize heterogeneous pools by breaking them into homogeneous groups before computing the Cartesian product of those sub-results. This approach allows homogeneous pools to be ordered without duplicates, where heterogeneous ones offer no such guarantees.

As expected, this optimization allows the performance of arbitrary selection from mixed pools to sit between that of purely homogeneous and purely heterogeneous ones. Note, however, that all three appear to scale geometrically in some way.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
(4@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))).h(slice(0)):
4.32 µs ± 74.6 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
(4@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))).h(slice(1)):
12.9 µs ± 27.4 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
(4@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))).h(slice(2)):
24.7 µs ± 167 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
(4@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))).h(slice(3)):
53.2 µs ± 187 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
(6@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))).h(slice(2)):
25.9 µs ± 94.9 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
(6@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))).h(slice(3)):
56 µs ± 111 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
(6@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))).h(slice(4)):
117 µs ± 637 ns per loop (mean ± std. dev. of 7 runs, 10,000 loops each)
(6@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1}))).h(slice(5)):
227 µs ± 1.62 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)

(P(H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}), 2@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})))).h(slice(0)):
4.2 µs ± 14 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
(P(H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}), 2@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})))).h(slice(1)):
276 µs ± 3.62 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
(P(H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}), 2@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})))).h(slice(2)):
912 µs ± 4.45 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
(P(H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}), 2@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})))).h(slice(3)):
922 µs ± 3.03 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
(P(H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}), 3@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})))).h(slice(2)):
6.02 ms ± 29.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
(P(H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}), 3@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})))).h(slice(3)):
15.9 ms ± 51.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
(P(H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}), 3@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})))).h(slice(4)):
16 ms ± 39 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
(P(H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}), 3@P(H({1: 1, 2: 1, 3: 1, 4: 1, 5: 1, 6: 1})))).h(slice(5)):
16.2 ms ± 44.7 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

(P(H({-3: 1, -2: 1, -1: 1, 0: 1, 1: 1, 2: 1}), H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))).h(slice(0)):
4.23 µs ± 20.4 ns per loop (mean ± std. dev. of 7 runs, 100,000 loops each)
(P(H({-3: 1, -2: 1, -1: 1, 0: 1, 1: 1, 2: 1}), H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))).h(slice(1)):
1.61 ms ± 3.55 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
(P(H({-3: 1, -2: 1, -1: 1, 0: 1, 1: 1, 2: 1}), H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))).h(slice(2)):
1.64 ms ± 2.83 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
(P(H({-3: 1, -2: 1, -1: 1, 0: 1, 1: 1, 2: 1}), H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))).h(slice(3)):
1.63 ms ± 2.74 µs per loop (mean ± std. dev. of 7 runs, 1,000 loops each)
(P(H({-5: 1, -4: 1, -3: 1, -2: 1, -1: 1, 0: 1}), H({-4: 1, -3: 1, -2: 1, -1: 1, 0: 1, 1: 1}), H({-3: 1, -2: 1, -1: 1, 0: 1, 1: 1, 2: 1}), H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))).h(slice(2)):
61.2 ms ± 122 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
(P(H({-5: 1, -4: 1, -3: 1, -2: 1, -1: 1, 0: 1}), H({-4: 1, -3: 1, -2: 1, -1: 1, 0: 1, 1: 1}), H({-3: 1, -2: 1, -1: 1, 0: 1, 1: 1, 2: 1}), H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))).h(slice(3)):
65.1 ms ± 271 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
(P(H({-5: 1, -4: 1, -3: 1, -2: 1, -1: 1, 0: 1}), H({-4: 1, -3: 1, -2: 1, -1: 1, 0: 1, 1: 1}), H({-3: 1, -2: 1, -1: 1, 0: 1, 1: 1, 2: 1}), H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))).h(slice(4)):
67.2 ms ± 233 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
(P(H({-5: 1, -4: 1, -3: 1, -2: 1, -1: 1, 0: 1}), H({-4: 1, -3: 1, -2: 1, -1: 1, 0: 1, 1: 1}), H({-3: 1, -2: 1, -1: 1, 0: 1, 1: 1, 2: 1}), H({-2: 1, -1: 1, 0: 1, 1: 1, 2: 1, 3: 1}), H({-1: 1, 0: 1, 1: 1, 2: 1, 3: 1, 4: 1}), H({0: 1, 1: 1, 2: 1, 3: 1, 4: 1, 5: 1}))).h(slice(5)):
70.4 ms ± 533 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)

Source: perf_rolls_with_counts.ipy

 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
from dyce import H, P

for n in (4, 6):
  p = n@P(6)
  for i in range(len(p) - 4, len(p)):
    print(f"({p}).h(slice({i})):")
    %timeit p.h(slice(i))

print()

for n in (2, 3):
  p = P(n@P(6), *[H(6) - m for m in range(n, 0, -1)])
  for i in range(len(p) - 4, len(p)):
    print(f"({p}).h(slice({i})):")
    %timeit p.h(slice(i))

print()

for n in (4, 6):
  p = P(*[H(6) - m for m in range(n, 0, -1)])
  for i in range(len(p) - 4, len(p)):
    print(f"({p}).h(slice({i})):")
    %timeit p.h(slice(i))

print()

Source code in dyce/p.py
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
@beartype
def rolls_with_counts(self, *which: _GetItemT) -> Iterator[_RollCountT]:
    r"""
    Returns an iterator yielding two-tuples (pairs) that, collectively, enumerate all
    possible outcomes for the pool. The first item in the two-tuple is a sorted
    sequence of the outcomes for a distinct roll. The second is the count for that
    roll. Outcomes in each roll are ordered least to greatest.

    If one or more arguments are provided, this methods selects subsets of outcomes
    for each roll. Outcomes in each roll are ordered from least (index ``#!python
    0``) to greatest (index ``#!python -1`` or ``#!python len(self) - 1``).
    Identifiers can be ``#!python int``s or ``#!python slice``s, and can be mixed
    for more flexible selections.

    ``` python
    >>> from collections import Counter

    >>> def accumulate_roll_counts(counter, roll_counts):
    ...   for roll, count in roll_counts:
    ...     counter[roll] += count
    ...   return counter

    >>> p_6d6 = 6@P(6)
    >>> every_other_d6 = accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(slice(None, None, -2))) ; every_other_d6
    Counter({(6, 4, 2): 4110, (6, 5, 3): 3390, (6, 4, 3): 3330, ..., (3, 3, 3): 13, (2, 2, 2): 7, (1, 1, 1): 1})
    >>> accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(5, 3, 1)) == every_other_d6
    True
    >>> accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(*range(5, 0, -2))) == every_other_d6
    True
    >>> accumulate_roll_counts(Counter(), p_6d6.rolls_with_counts(*(i for i in range(6, 0, -1) if i % 2 == 1))) == every_other_d6
    True

    ```

    One way to model the likelihood of achieving a “Yhatzee” (i.e., where five
    six-sided dice show the same face) on a single roll by checking rolls for where
    the least and greatest outcomes are the same.

    ``` python
    >>> p_5d6 = 5@P(6)
    >>> yhatzee_on_single_roll = H(
    ...   (1 if roll[0] == roll[-1] else 0, count)
    ...   for roll, count
    ...   in p_5d6.rolls_with_counts()
    ... )
    >>> print(yhatzee_on_single_roll.format(width=0))
    {..., 0: 99.92%, 1:  0.08%}

    ```

    !!! note "In the general case, rolls may appear more than once."

        ``` python
        >>> 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)]

        ```

        In the above, ``#!python (1, 2)`` appears a total of two times, each with
        counts of one.

        However, if the pool is homogeneous (meaning it only contains identical
        histograms), rolls (before selection) are not repeated. (See the note on
        implementation below.)

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

        ```

        Either way, by summing and counting all rolls, we can confirm identity.

        ``` python
        >>> d6 = H(6)
        >>> d6avg = H((2, 3, 3, 4, 4, 5))
        >>> p = 2@P(d6, d6avg)
        >>> H((sum(roll), count) for roll, count in p.rolls_with_counts()) == p.h() == d6 + d6 + d6avg + d6avg
        True

        ```

    This method does not try to outsmart callers by (mis)interpreting selection
    arguments. It honors selection identifier order and any redundancy.

    ``` python
    >>> p_d3_d4 = P(H(3), H(4))
    >>> # Select the second, first, then second (again) elements
    >>> sorted(p_d3_d4.rolls_with_counts(-1, 0, 1))
    [((1, 1, 1), 1), ((2, 1, 2), 1), ((2, 1, 2), 1), ..., ((4, 1, 4), 1), ((4, 2, 4), 1), ((4, 3, 4), 1)]

    ```

    Selecting the same outcomes, but in a different order is not immediately
    comparable.

    ``` python
    >>> select_0_1 = sorted(p_d3_d4.rolls_with_counts(0, 1))
    >>> select_1_0 = sorted(p_d3_d4.rolls_with_counts(1, 0))
    >>> select_0_1 == select_1_0
    False

    ```

    Equivalence can be tested when selected outcomes are sorted.

    ``` python
    >>> sorted_0_1 = sorted((sorted(roll), count) for roll, count in select_0_1)
    >>> sorted_1_0 = sorted((sorted(roll), count) for roll, count in select_1_0)
    >>> sorted_0_1 == sorted_1_0
    True

    ```

    They can also be summed and counted which is equivalent to calling the
    [``h`` method][dyce.p.P.h] with identical selection arguments.

    ``` python
    >>> summed_0_1 = H((sum(roll), count) for roll, count in select_0_1)
    >>> summed_1_0 = H((sum(roll), count) for roll, count in select_1_0)
    >>> summed_0_1 == summed_1_0 == p_d3_d4.h(0, 1) == p_d3_d4.h(1, 0)
    True

    ```

    !!! info "About the implementation"

        Enumeration is substantially more efficient for homogeneous pools than
        heterogeneous ones, because we are able to avoid the expensive enumeration
        of the Cartesian product using several techniques.

        Taking $k$ outcomes, where $k$ selects fewer than all $n$ outcomes a
        homogeneous pool benefits from [Ilmari Karonen’s
        optimization](https://rpg.stackexchange.com/a/166663/71245), which appears
        to scale geometrically with $k$ times some factor of $n$ (e.g., $\log n$,
        but I haven’t bothered to figure that out yet), such that—in observed
        testing, at least—it is generally the fastest approach for $k < n$.

        Where $k = n$, we leverage the [*multinomial
        coefficient*](https://en.wikipedia.org/wiki/Permutation#Permutations_of_multisets),
        which appears to scale generally with $n$.

        $$
        {{n} \choose {{{k}_{1}},{{k}_{2}},\ldots,{{k}_{m}}}}
        = {\frac {{n}!} {{{k}_{1}}! {{k}_{2}}! \cdots {{k}_{m}}!}}
        $$

        We enumerate combinations with replacements, and then the compute the number
        of permutations with repetitions for each combination. Consider ``#!python
        n@P(H(m))``. Enumerating combinations with replacements would yield all
        unique rolls.

        ``#!python ((1, 1, …, 1), (1, 1, …, 2), …, (1, 1, …, m), …, (m - 1, m, …,
        m), (m, m, …, m))``

        To determine the count for a particular roll ``#!python (a, b, …, n)``, we
        compute the multinomial coefficient for that roll and multiply by the scalar
        ``#!python H(m)[a] * H(m)[b] * … * H(m)[n]``. (See
        [this](https://www.lucamoroni.it/the-dice-roll-sum-problem/) for an in-depth
        exploration of the topic.)

        Further, this implementation attempts to optimize heterogeneous pools by
        breaking them into homogeneous groups before computing the Cartesian product
        of those sub-results. This approach allows homogeneous pools to be ordered
        without duplicates, where heterogeneous ones offer no such guarantees.

        As expected, this optimization allows the performance of arbitrary selection
        from mixed pools to sit between that of purely homogeneous and purely
        heterogeneous ones. Note, however, that all three appear to scale
        geometrically in some way.

        ``` python
        --8<-- "docs/assets/perf_rolls_with_counts.txt"
        ```

        <details>
        <summary>Source: <a href="https://github.com/posita/dyce/blob/latest/docs/assets/perf_rolls_with_counts.ipy"><code>perf_rolls_with_counts.ipy</code></a></summary>

        ``` python
        --8<-- "docs/assets/perf_rolls_with_counts.ipy"
        ```
        </details>
    """
    n = len(self)

    if not which:
        i: Optional[int] = n
    else:
        i = _analyze_selection(n, which)

    if i == 0 or n == 0:
        rolls_with_counts_iter: Iterable[_RollCountT] = iter(())
    else:
        groups = tuple((h, sum(1 for _ in hs)) for h, hs in groupby(self))

        if len(groups) == 1:
            # Based on cursory performance analysis, calling the homogeneous
            # implementation directly provides about a 15% performance savings over
            # merely falling through to _rwc_heterogeneous_h_groups. Maybe
            # itertools.product adds significant overhead?
            h, hn = groups[0]
            assert hn == n

            # Still in search of a better (i.e., more efficient) way:
            # <https://math.stackexchange.com/questions/4173084/probability-distribution-of-k-1-k-2-cdots-k-m-selections-of-arbitrary-posi>
            if i and abs(i) < n:
                rolls_with_counts_iter = _rwc_homogeneous_n_h_using_partial_selection(
                    n,
                    h,
                    i,
                    # This is just padding to allow for consistent indexing. They
                    # are deselected (i.e., not returned) below.
                    fill=0,
                )
            else:
                rolls_with_counts_iter = (
                    _rwc_homogeneous_n_h_using_partial_selection(n, h, n)
                )
        else:
            rolls_with_counts_iter = _rwc_heterogeneous_h_groups(groups, i)

    for sorted_outcomes_for_roll, roll_count in rolls_with_counts_iter:
        if which:
            taken_outcomes = tuple(getitems(sorted_outcomes_for_roll, which))
        else:
            taken_outcomes = sorted_outcomes_for_roll

        yield taken_outcomes, roll_count

umap(op: _UnaryOperatorT) -> P

Shorthand for P(*(h.umap(op) for h in self)). See the H.umap method.

1
2
3
4
5
6
>>> import operator
>>> p_3d6 = 3@P(H((-3, -1, 2, 4)))
>>> p_3d6.umap(operator.__neg__)
3@P(H({-4: 1, -2: 1, 1: 1, 3: 1}))
>>> p_3d6.umap(operator.__abs__)
3@P(H({1: 1, 2: 1, 3: 1, 4: 1}))
Source code in dyce/p.py
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
@beartype
def umap(self, op: _UnaryOperatorT) -> "P":
    r"""
    Shorthand for ``#!python P(*(h.umap(op) for h in self))``. See the
    [``H.umap`` method][dyce.h.H.umap].

    ``` python
    >>> import operator
    >>> p_3d6 = 3@P(H((-3, -1, 2, 4)))
    >>> p_3d6.umap(operator.__neg__)
    3@P(H({-4: 1, -2: 1, 1: 1, 3: 1}))
    >>> p_3d6.umap(operator.__abs__)
    3@P(H({1: 1, 2: 1, 3: 1, 4: 1}))

    ```
    """
    return P(*(h.umap(op) for h in self))