XanaduAI / strawberryfields

Strawberry Fields is a full-stack Python library for designing, simulating, and optimizing continuous variable (CV) quantum optical circuits.
https://strawberryfields.ai
Apache License 2.0
748 stars 187 forks source link

Add `results.counts()` method to allow easy counting of sampling data #157

Open josh146 opened 5 years ago

josh146 commented 5 years ago

Something that would be nice to have, as a convenience to the user, is a results.counts() method, that analyzes the sampled data and returns counts. I.e.,

>>> results.counts()
{'0,0,0,0': 46,
 '0,1,0,0': 10,
 '1,0,1,0': 1,
 '1,0,0,0': 4,
 '0,0,1,0': 9,
 '2,0,0,3': 1,
 '0,0,0,1': 9,
 '0,1,1,0': 5,
 '0,0,1,1': 3,
 '2,0,1,1': 1,
 '0,1,0,1': 2,
 '0,0,0,2': 2,
 '0,1,1,1': 1,
 '0,2,0,0': 1,
 '0,2,1,1': 1,
 '0,0,2,0': 2,
 '1,0,0,1': 1,
 '1,0,0,2': 1}

This is relatively easy to do, so should be a small PR:

from collections import Counter

def count(self):
    # convert a single shot of samples into a bitstring,
    # for example [0, 1, 0, 2] -> "0102"
    bitstrings = [",".join([str(j) for j in i]) for i in self.samples.T]
    # count the number of times each bitstring occurs
    return {k:v for k, v in Counter(bitstrings).items()}
josh146 commented 5 years ago

(Note that this really only makes sense for measurements that return integer results, such as MeasureFock() or MeasureThreshold()).

co9olguy commented 5 years ago

seems like something that should be packaged as a method of the Results class. Might make sense to make both results.samples and results.counts lazy-loading?

josh146 commented 5 years ago

Might make sense to make both results.samples and results.counts lazy-loading?

Definitely would be nice! Especially to reduce network load.

felipeoyarce commented 2 years ago

Hi @josh146 and @co9olguy 😄 I would like to work in this issue, what do you think?

co9olguy commented 2 years ago

Hi @felipeoyarce, thanks for your interest.

This is quite an old issue, but I think it's still applicable, so if you want to take a chance at it, go for it :slightly_smiling_face: