Source code for qibolab._core.instruments.qrng.qrng
fromtypingimportList,Optional,Sequence,Unionimportnumpyasnpimportnumpy.typingasnptfromserialimportSerialfrom..abstractimportInstrumentfrom.extractorsimportExtractor,ShaExtractor__all__=["QRNG"]defread(port:Serial,n:int=1,nbytes:int=4)->List[int]:"""Read raw samples from the QRNG device serial output. In the entropy mode of the device, these typically follow a normal distribution. Args: n: Number of samples to retrieve. nbytes: Number of bytes to read from serial port to generate one raw sample. """samples=[]whilelen(samples)<n:num_str=""whilelen(num_str)<nbytes:sample=port.read(1)ifsample==b" ":breaknum_str+=sample.decode("utf-8")try:samples.append(int(num_str))exceptValueError:passreturnsamples
[docs]classQRNG(Instrument):"""Driver to sample numbers from a Quantum Random Number Generator (QRNG). See :ref:`qrng` for example usage. """address:strbaudrate:int=115200extractor:Extractor=ShaExtractor()port:Optional[Serial]=Nonebytes_per_number:int=4"""Number of bytes to read from serial port to generate one raw sample."""
[docs]defread(self,n:int)->List[int]:"""Read raw samples from the QRNG device serial output. In the entropy mode of the device, these typically follow a normal distribution. Args: n: Number of samples to retrieve. """returnread(self.port,n,self.bytes_per_number)
[docs]defrandom(self,size:Optional[Union[int,Sequence[int]]]=None)->npt.NDArray:"""Returns random floats following uniform distribution in [0, 1]. Args: size: Shape of the returned array (to behave similarly to ``np.random.random``). """n=np.prod(size)nraw=self.extractor.num_raw_samples(n)raw=self.read(nraw)extracted=self.extractor.extract(raw)[:n]returnnp.reshape(extracted,size)