msg290003 - (view) |
Author: Niklas Fiekas (niklasf) * |
Date: 2017-03-22 17:30 |
An efficient popcount (something equivalent to bin(a).count("1")) would
be useful for numerics, parsing binary formats, scientific applications
and others.
DESIGN DECISIONS
* Is a popcount method useful enough?
* How to handle negative values?
* How should the method be named?
SURVEY
gmpy calls the operation popcount and returns -1/None for negative values:
>>> import gmpy2
>>> gmpy2.popcount(-10)
-1
>>> import gmpy
>>> gmpy.popcount(-10)
From the documentation [1]:
> If x < 0, the number of bits with value 1 is infinite
> so -1 is returned in that case.
(I am not a fan of the arbitrary return value).
The bitarray module has a count(value=True) method:
>>> from bitarray import bitarray
>>> bitarray(bin(123456789).strip("0b")).count()
16
Bitsets [2] exposes __len__.
There is an SSE4 POPCNT instruction. C compilers call the corresponding
intrinsic popcnt or popcount (with some prefix and suffix) and they
accept unsigned arguments.
Rust calls the operation count_ones [3]. Ones are counted in the binary
representation of the *absolute* value. (I propose to do the same).
Introducing popcount was previously considered here but closed for lack
of a PEP or patch: http://bugs.python.org/issue722647
Sensible names could be bit_count along the lines of the existing
bit_length or popcount for gmpy compability and to distinguish it more.
PERFORMANCE
$ ./python -m timeit "bin(123456789).count('1')" # equivalent
1000000 loops, best of 5: 286 nsec per loop
$ ./python -m timeit "(123456789).bit_count()" # fallback
5000000 loops, best of 5: 46.3 nsec per loop
[1] https://gmpy2.readthedocs.io/en/latest/mpz.html#mpz-functions
[2] https://pypi.python.org/pypi/bitsets/0.7.9
[3] https://doc.rust-lang.org/std/primitive.i64.html#method.count_ones
|
msg290013 - (view) |
Author: Mark Dickinson (mark.dickinson) * |
Date: 2017-03-22 20:22 |
Can you give some examples of concrete use-cases? I've spent the last six years or so writing scientific applications and parsing all sorts of odd binary formats, and haven't needed or wanted a popcount yet.
> (I am not a fan of the arbitrary return value).
Agreed: if this were implemented, I think raising ValueError would be the most appropriate thing to do for negative inputs.
|
msg290014 - (view) |
Author: Niklas Fiekas (niklasf) * |
Date: 2017-03-22 21:38 |
Searching popcount in Python files on GitHub yields
a considerable number of examples:
https://github.com/search?utf8=%E2%9C%93&q=popcount+extension%3Apy&type=Code
Perhaps intresting:
* In CPython itself: See count_set_bits in
Modules/mathmodule.c
* Domain specific applications: Bitboards in Chess,
fairly shuffling cards in Poker, comparing molecules
* Size of bitsets (see bitarray and bitsets I listed above).
Probably for this reason also as a first class citizen
in Redis: https://redis.io/commands/bitcount.
Probably most important:
* As the Hamming Distance:
https://en.wikipedia.org/wiki/Hamming_distance#History_and_applications
---
Btw. not a concrete application. I just stumbled upon this.
popcnt was considered important enough to be included in the
rather limited WebAssembly instruction set:
https://github.com/WebAssembly/spec/raw/master/papers/pldi2017.pdf
|
msg290015 - (view) |
Author: Mark Dickinson (mark.dickinson) * |
Date: 2017-03-22 21:45 |
Many of those applications are really for bitstrings (chess bitboards, hamming distance), which aren't really the same thing as integers.
Nice find for the mathmodule.c case. I'd forgotten about that one (though according to git blame, apparently I'm responsible for checking it in). It's a fairly obscure corner case, though.
Overall, I'm -1 on adding this: I don't think it meets the bar of being useful enough to justify the extra method. I'd suggest that people needing this kind of efficient bitstring operation use a 3rd-party bitstring library instead.
|
msg290016 - (view) |
Author: Serhiy Storchaka (serhiy.storchaka) * |
Date: 2017-03-22 21:49 |
I think that adding bitarray or bitset (or both) in the stdlib would better satisfy the needs. There are open issues for adding ability to read or set selected bits or range of bits in int or for bitwise operations on bytes. I think that bitarray and bitset would provide better interface for these operations.
|
msg290017 - (view) |
Author: Tim Peters (tim.peters) * |
Date: 2017-03-22 22:00 |
See also:
https://en.wikipedia.org/wiki/Hamming_weight
As that says, there are a number of languages and processors with first class support for a popcount function. I've frequently implemented it in Python when using integers as integer bitsets (`i` is in the set if and only if bit `2**i` is set in the integer), which often - except for finding the cardinality - runs much faster than using general Python sets.
|
msg290073 - (view) |
Author: Case Van Horsen (casevh) |
Date: 2017-03-24 01:54 |
I like the name bit_count and I'll gladly add it to gmpy2 with the appropriate changes to exceptions, etc.
|
msg344215 - (view) |
Author: Raymond Hettinger (rhettinger) * |
Date: 2019-06-01 20:13 |
Is everyone comfortable with how negative numbers are handled by this patch? It might be better to limit the domain and raise a ValueError rather than make a presumption about what the user intends.
|
msg344216 - (view) |
Author: Serhiy Storchaka (serhiy.storchaka) * |
Date: 2019-06-01 20:16 |
I am going to add the imath module. If we decide to add popcount(), it may be better to add it in this module instead of int class.
|
msg344223 - (view) |
Author: Mark Dickinson (mark.dickinson) * |
Date: 2019-06-01 20:34 |
> Is everyone comfortable with how negative numbers are handled by this patch?
Not entirely, but it's not terribly wrong and it's consistent with how `int.bit_length` works. (I'm also a bit uncomfortable about `int.bit_length`s behaviour on negative numbers, but it is the way it is.)
|
msg344224 - (view) |
Author: Tim Peters (tim.peters) * |
Date: 2019-06-01 20:35 |
I prefer that a negative int raise ValueError, but am OK with it using the absolute value instead (i.e., what it does now).
|
msg344225 - (view) |
Author: Mark Dickinson (mark.dickinson) * |
Date: 2019-06-01 20:35 |
> I am going to add the imath module.
Aimed at 3.8, or 3.9? This seems somewhat rushed for 3.8.
|
msg369860 - (view) |
Author: Mark Dickinson (mark.dickinson) * |
Date: 2020-05-25 08:24 |
I'm re-reviewing this discussion three years on. I'd be happy for this to go into 3.10. Are there other strong opinions? It would be good to either update and merge the PR, or close as rejected.
|
msg369878 - (view) |
Author: Tim Peters (tim.peters) * |
Date: 2020-05-25 14:16 |
I see I never explicitly said +1, so I will now: +1 on merging this :-)
|
msg369879 - (view) |
Author: STINNER Victor (vstinner) * |
Date: 2020-05-25 14:46 |
Adding a function to a new hypothetical imath module sounds reasonable.
I'm less comfortable with adding a new method to int type: it would mean that any int subtype "should" implement it.
For example, should numpy.int64 get this method as well?
What is the effect on https://docs.python.org/3.9/library/numbers.html?
Does it make sense to call (True).popcount()?
|
msg369881 - (view) |
Author: STINNER Victor (vstinner) * |
Date: 2020-05-25 14:53 |
> In CPython itself: See count_set_bits in Modules/mathmodule.c
Python/hamt.c contains an optimized function:
static inline uint32_t
hamt_bitcount(uint32_t i)
{
/* We could use native popcount instruction but that would
require to either add configure flags to enable SSE4.2
support or to detect it dynamically. Otherwise, we have
a risk of CPython not working properly on older hardware.
In practice, there's no observable difference in
performance between using a popcount instruction or the
following fallback code.
The algorithm is copied from:
https://graphics.stanford.edu/~seander/bithacks.html
*/
i = i - ((i >> 1) & 0x55555555);
i = (i & 0x33333333) + ((i >> 2) & 0x33333333);
return (((i + (i >> 4)) & 0xF0F0F0F) * 0x1010101) >> 24;
}
Python/pymath.c provides a "unsigned int _Py_bit_length(unsigned long d)" function used by math.factorial, _PyLong_NumBits(), int.__format__(), long / long, _PyLong_Frexp() and PyLong_AsDouble(), etc.
Maybe we could add a _Py_bit_count().
See also bpo-29782: "Use __builtin_clzl for bits_in_digit if available" which proposes to micro-optimize _Py_bit_length().
--
In the meanwhile, I also added pycore_byteswap.h *internal* header which provides static inline function which *do* use builtin functions like __builtin_bswap32().
|
msg369887 - (view) |
Author: Mark Dickinson (mark.dickinson) * |
Date: 2020-05-25 15:04 |
> For example, should numpy.int64 get this method as well?
That's for the NumPy folks to decide (and I've added Nathaniel Smith to the nosy in case he wants to comment), but I don't see any particularly strong reason that NumPy would need to add it. It looks as though the NumPy integer types have survived happily without a bit_length method, for example - I don't even see any issues in the NumPy tracker suggesting that anyone missed it. (Though perhaps that's because in the case of a NumPy int one always has at least an upper bound on the bit_length available.)
> What is the effect on https://docs.python.org/3.9/library/numbers.html?
No effect, just as int.bit_length has no effect.
> Does it make sense to call (True).popcount()?
It would be spelled `True.bit_count()` if the PR goes in as-is, but sure, why not. :-)
|
msg369966 - (view) |
Author: Mark Dickinson (mark.dickinson) * |
Date: 2020-05-26 10:15 |
PR is updated and mergeable.
|
msg370323 - (view) |
Author: Mark Dickinson (mark.dickinson) * |
Date: 2020-05-29 16:28 |
New changeset 8bd216dfede9cb2d5bedb67f20a30c99844dbfb8 by Niklas Fiekas in branch 'master':
bpo-29882: Add an efficient popcount method for integers (#771)
https://github.com/python/cpython/commit/8bd216dfede9cb2d5bedb67f20a30c99844dbfb8
|
msg370423 - (view) |
Author: Mark Shannon (Mark.Shannon) * |
Date: 2020-05-31 11:02 |
Why are calling a population count method "bit_count()"?
That seems likely to cause confusion with "bit_length()".
I might reasonable expect that 0b1000.bit_count() be 4, not 1. It does have 4 bits.
Whereas 0b1000.population_count() is clearly 1.
I have no objection to adding this method, just the choice of name.
|
msg370447 - (view) |
Author: Mark Dickinson (mark.dickinson) * |
Date: 2020-05-31 13:27 |
> Why are calling a population count method "bit_count()"?
Naming things is hard, but I don't think this is an unreasonable name, and it's not without precedent. Java similarly has Integer.bitCount and BigInteger.bitCount. MySQL has BIT_COUNT.
|
msg370456 - (view) |
Author: Mark Dickinson (mark.dickinson) * |
Date: 2020-05-31 13:46 |
A couple of other data points:
- Swift has nonzeroBitCount: https://developer.apple.com/documentation/swift/int/2886050-nonzerobitcount
- Rust has count_ones: https://doc.rust-lang.org/std/primitive.u64.html
- Go's math/bits package has OnesCount
- The closest thing in Mathematica appears to be DigitCount, which isn't base-specific.
@Mark Shannon: what name would you suggest, and why? The term "population count" feels too non-obvious and specialist to me, and anything involving "Hamming" likewise.
"count_ones" isn't obviously a bit operation.
"count_set_bits"?
|
msg370987 - (view) |
Author: STINNER Victor (vstinner) * |
Date: 2020-06-08 14:30 |
New changeset c6b292cdeee689f0bfac6c1e2c2d4e4e01fa8d9e by Victor Stinner in branch 'master':
bpo-29882: Add _Py_popcount32() function (GH-20518)
https://github.com/python/cpython/commit/c6b292cdeee689f0bfac6c1e2c2d4e4e01fa8d9e
|
msg372497 - (view) |
Author: Vedran Čačić (veky) * |
Date: 2020-06-28 06:43 |
Well, bit_sum is what it really is. But I agree it's a terrible name. :-)
|
msg411211 - (view) |
Author: STINNER Victor (vstinner) * |
Date: 2022-01-21 23:54 |
New changeset cd8de40b3b10311de2db7b90abdf80af9e35535f by Victor Stinner in branch 'main':
bpo-29882: _Py_popcount32() doesn't need 64x64 multiply (GH-30774)
https://github.com/python/cpython/commit/cd8de40b3b10311de2db7b90abdf80af9e35535f
|
msg411357 - (view) |
Author: Mark Dickinson (mark.dickinson) * |
Date: 2022-01-23 09:59 |
New changeset 83a0ef2162aa379071e243f1b696aa6814edcd2a by Mark Dickinson in branch 'main':
bpo-29882: Fix portability bug introduced in GH-30774 (#30794)
https://github.com/python/cpython/commit/83a0ef2162aa379071e243f1b696aa6814edcd2a
|
|
Date |
User |
Action |
Args |
2022-04-11 14:58:44 | admin | set | github: 74068 |
2022-01-23 09:59:43 | mark.dickinson | set | messages:
+ msg411357 |
2022-01-22 15:25:59 | mark.dickinson | set | pull_requests:
+ pull_request28979 |
2022-01-21 23:54:52 | vstinner | set | messages:
+ msg411211 |
2022-01-21 22:56:11 | vstinner | set | pull_requests:
+ pull_request28959 |
2020-06-28 06:43:47 | veky | set | nosy:
+ veky messages:
+ msg372497
|
2020-06-08 14:30:37 | vstinner | set | messages:
+ msg370987 |
2020-05-31 13:46:50 | mark.dickinson | set | messages:
+ msg370456 |
2020-05-31 13:27:43 | mark.dickinson | set | messages:
+ msg370447 |
2020-05-31 11:02:30 | Mark.Shannon | set | nosy:
+ Mark.Shannon messages:
+ msg370423
|
2020-05-29 17:14:17 | vstinner | set | pull_requests:
+ pull_request19762 |
2020-05-29 16:28:39 | mark.dickinson | set | status: open -> closed stage: resolved resolution: fixed versions:
+ Python 3.10, - Python 3.7 |
2020-05-29 16:28:08 | mark.dickinson | set | messages:
+ msg370323 |
2020-05-26 10:15:46 | mark.dickinson | set | messages:
+ msg369966 |
2020-05-25 15:04:48 | mark.dickinson | set | nosy:
+ njs messages:
+ msg369887
|
2020-05-25 14:53:08 | vstinner | set | messages:
+ msg369881 |
2020-05-25 14:46:52 | vstinner | set | nosy:
+ vstinner messages:
+ msg369879
|
2020-05-25 14:16:31 | tim.peters | set | messages:
+ msg369878 |
2020-05-25 08:24:05 | mark.dickinson | set | messages:
+ msg369860 |
2019-06-01 20:35:34 | mark.dickinson | set | messages:
+ msg344225 |
2019-06-01 20:35:32 | tim.peters | set | messages:
+ msg344224 |
2019-06-01 20:34:42 | mark.dickinson | set | messages:
+ msg344223 |
2019-06-01 20:16:20 | serhiy.storchaka | set | messages:
+ msg344216 |
2019-06-01 20:13:40 | rhettinger | set | nosy:
+ rhettinger messages:
+ msg344215
|
2018-01-30 17:19:37 | gbtami | set | nosy:
+ gbtami
|
2017-03-24 01:54:25 | casevh | set | nosy:
+ casevh messages:
+ msg290073
|
2017-03-22 22:00:38 | tim.peters | set | nosy:
+ tim.peters messages:
+ msg290017
|
2017-03-22 21:49:42 | serhiy.storchaka | set | nosy:
+ serhiy.storchaka messages:
+ msg290016
|
2017-03-22 21:45:13 | mark.dickinson | set | messages:
+ msg290015 |
2017-03-22 21:38:05 | niklasf | set | messages:
+ msg290014 |
2017-03-22 20:22:28 | mark.dickinson | set | messages:
+ msg290013 |
2017-03-22 17:47:33 | Jim Fasarakis-Hilliard | set | nosy:
+ Jim Fasarakis-Hilliard
|
2017-03-22 17:32:02 | niklasf | set | pull_requests:
+ pull_request678 |
2017-03-22 17:30:42 | niklasf | create | |