#
# Copyright © 2022-2024 University of Strasbourg. All Rights Reserved.
# Copyright © 2023-2025 QPerfect. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
#
from bitarray import bitarray, frozenbitarray
def _helper_bitvec_to_int(arr):
res = 0
for bit in arr:
res = (res << 1) | bit
return res
# Function to convert a bitarray to an integer
def bitvec_to_int(arr):
# `frozenbitarray` subclasses `bitarray`, so one isinstance covers both.
if not isinstance(arr, bitarray):
raise TypeError("Input must be a bitarray or BitVector.")
num_bits = len(arr)
if num_bits > 0:
return _helper_bitvec_to_int(arr)
else:
raise ValueError("Input array is empty.")
[docs]
class BitString:
"""A sequence of bits, one per qubit or classical bit.
A :class:`BitString` represents a computational basis state of a register,
such as a measurement outcome. Sampled results in
:class:`~mimiqcircuits.QCSResults` are stored as :class:`BitString`
objects, and the ``bitstrings`` argument of ``submit`` takes them to
request amplitudes. Bit ``i`` of the string is qubit (or classical bit)
``i``, and the printed form ``bs"..."`` lists bit 0 first.
A :class:`BitString` is hashable, so it can be a dictionary key. Indexing
returns a bit; slicing returns a new :class:`BitString`. Assigning a bit
with ``bs[i] = 1`` changes the string, and with it its hash, so do not
assign bits of a string that is used as a dictionary key.
Examples:
Create one from a number of bits (all zero), a string, a sequence of
0 and 1, or a ``bitarray``:
>>> from mimiqcircuits import *
>>> from bitarray import bitarray
>>> BitString(16) # number of qubits
bs"0000000000000000"
>>> BitString('10101') # binary string
bs"10101"
>>> BitString([1,0,0,0,1]) # binary string
bs"10001"
>>> BitString((1,0,0,0,1)) # binary string
bs"10001"
>>> BitString(bitarray('101010')) # bitarray
bs"101010"
Other constructors:
>>> BitString.fromnonzeros(16, [1, 3, 5, 7, 9, 11, 13, 15])
bs"0101010101010101"
>>> BitString.fromfunction(16, lambda i: i % 2 == 1)
bs"0101010101010101"
>>> BitString.fromstring('10101')
bs"10101"
>>> BitString.fromint(16, 21)
bs"1010100000000000"
>>> BitString.fromint(16, 21, 'little')
bs"0000000000010101"
Accessing the bits:
>>> bs = BitString('0110')
>>> bs[1] # get bit 1
1
>>> bs[0:2] # get the first 2 bits
bs"01"
>>> bs.nonzeros() # indices of the bits set to 1
[1, 2]
>>> BitString('1100').tointeger() # bit 0 is the least significant
3
Bitwise operations:
>>> bs1 = BitString('10101')
>>> bs2 = BitString('11100')
>>> bs1 | bs2 # OR
bs"11101"
>>> bs1 & bs2 # AND
bs"10100"
>>> bs1 ^ bs2 # XOR
bs"01001"
>>> ~bs1 # NOT
bs"01010"
>>> bs1 << 2 # left shift
bs"10100"
>>> bs1 >> 2 # right shift
bs"00101"
Other operations:
>>> bs1 + bs2 # concatenation
bs"1010111100"
>>> bs1 * 2 # repetition
bs"1010110101"
"""
_bits = bitarray(0)
[docs]
def __init__(self, arg, indices=None):
"""Create a BitString.
Args:
arg (int, str, list, tuple, bitarray or frozenbitarray): Either the
number of bits, which gives the all-zero string (or the string
with ones at ``indices``), or the bits themselves as a string
of ``"0"`` and ``"1"``, a sequence of 0 and 1, or a
``bitarray``.
indices (list of int, optional): With an integer ``arg``, the
indices of the bits set to 1. Ignored otherwise.
Raises:
ValueError: If an index in ``indices`` is outside
``range(arg)``, or the bits contain values other than 0 and 1.
TypeError: If ``arg`` has another type.
Examples:
>>> BitString(16) # number of qubits
bs"0000000000000000"
>>> BitString(4, [0, 2]) # number of qubits and the bits set to 1
bs"1010"
>>> BitString('10101') # binary string
bs"10101"
>>> BitString(bitarray('101010')) # bitarray
bs"101010"
"""
# A frozenbitarray is already the stored representation and is
# immutable, so it can be shared rather than copied. This is the
# path every bulk producer of BitStrings takes.
#
# The buffer's bit order is kept as given, which is what the copying
# path did too: `frozenbitarray(x)` preserves `x.endian`. So a
# BitString can hold either order, `to01` and indexing read the same
# bits from both, and only `tobytes` differs. Anything reading the
# raw buffer has to check `.endian` rather than assume.
if indices is None and type(arg) is frozenbitarray:
self._bits = arg
return
if isinstance(arg, int):
if indices is None:
bitstring = arg * "0"
else:
if not all(0 <= i < arg for i in indices):
raise ValueError(
"Index out of range for the given number of qubits."
)
bitstring = "".join("1" if i in indices else "0" for i in range(arg))
elif isinstance(arg, (str, bitarray, frozenbitarray, list, tuple)):
bitstring = arg
else:
raise TypeError(
"Invalid input type. Expected 'str', 'int', 'bitarray', 'list', 'tuple', 'frozenbitarray'"
)
self._bits = frozenbitarray(bitstring)
@property
def bits(self):
"""The bits as a read-only ``frozenbitarray``."""
return self._bits
@bits.setter
def bits(self, bits):
raise AttributeError("Cannot set the bits of a BitString.")
[docs]
@staticmethod
def fromnonzeros(num_qubits: int, nonzeros: list):
"""Create a BitString with the given bits set to 1.
Args:
num_qubits: The number of bits.
nonzeros: The indices of the bits set to 1.
Returns:
BitString: The new string.
Raises:
ValueError: If an index is outside ``range(num_qubits)``.
Examples:
>>> BitString.fromnonzeros(4, [1, 3])
bs"0101"
"""
bitstring = ""
if not all(0 <= i < num_qubits for i in nonzeros):
raise ValueError("Invalid nonzero index.")
for i in range(num_qubits):
bitstring += "1" if i in nonzeros else "0"
return BitString(bitstring)
[docs]
@staticmethod
def fromfunction(num_qubits: int, f: type[lambda: None]):
"""Create a BitString by evaluating a function on each index.
Args:
num_qubits: The number of bits.
f: A function called with each index ``i``; bit ``i`` is 1 when
the result is true.
Returns:
BitString: The new string.
Examples:
>>> BitString.fromfunction(6, lambda i: i % 3 == 0)
bs"100100"
"""
bitstring = ""
for i in range(num_qubits):
bitstring += "1" if f(i) else "0"
return BitString(bitstring)
[docs]
@staticmethod
def fromstring(bitstring: str):
"""Create a BitString from a string of ``"0"`` and ``"1"``.
Same as ``BitString(bitstring)``.
Args:
bitstring: The bits, bit 0 first.
Returns:
BitString: The new string.
"""
return BitString(bitstring)
[docs]
@staticmethod
def fromint(num_qubits: int, integer: int, endianess: str = "big"):
"""Create a BitString from the binary digits of an integer.
Args:
num_qubits: The number of bits.
integer: A non-negative integer that fits in ``num_qubits`` bits.
endianess: ``"big"`` puts the least significant binary digit in
bit 0; ``"little"`` puts the most significant digit in bit 0.
Defaults to ``"big"``. This is the inverse of
:meth:`tointeger` with the same ``endianess``.
Returns:
BitString: The new string.
Raises:
ValueError: If ``integer`` needs more than ``num_qubits`` bits, or
``endianess`` is neither ``"big"`` nor ``"little"``.
Examples:
>>> BitString.fromint(4, 1)
bs"1000"
>>> BitString.fromint(4, 1, "little")
bs"0001"
>>> BitString.fromint(4, 6).tointeger()
6
"""
if len(bin(integer)[2:]) > num_qubits:
raise ValueError("Integer is too large for the given number of qubits.")
if endianess == "little":
bitstring = bin(integer)[2:].zfill(num_qubits)[::-1]
elif endianess == "big":
bitstring = bin(integer)[2:].zfill(num_qubits)
else:
raise ValueError("endian must be either 'big' or 'little'")
return BitString(bitstring[::-1])
[docs]
def num_qubits(self):
"""Return the number of bits, the same as ``len(bs)``."""
return len(self.bits)
[docs]
def nonzeros(self):
"""Return the indices of the bits set to 1, as a list of ``int``."""
return [i for i, bit in enumerate(self.bits) if bit]
[docs]
def zeros(self):
"""Return the indices of the bits set to 0, as a list of ``int``."""
return [i for i, bit in enumerate(self.bits) if not bit]
[docs]
def tointeger(self, endianess: str = "big"):
"""Return the integer whose binary digits are the bits.
Args:
endianess: ``"big"`` reads bit 0 as the least significant binary
digit; ``"little"`` reads it as the most significant.
Defaults to ``"big"``.
Returns:
int: The integer value.
Raises:
ValueError: If the string is empty, or ``endianess`` is neither
``"big"`` nor ``"little"``.
Examples:
>>> BitString("1000").tointeger()
1
>>> BitString("1000").tointeger("little")
8
"""
if endianess == "big":
return bitvec_to_int(self.bits[::-1])
elif endianess == "little":
return bitvec_to_int(self.bits)
else:
raise ValueError("Invalid endianess. Must be 'big' or 'little'.")
[docs]
def to01(self, endianess="big"):
"""Return the bits as a string of ``"0"`` and ``"1"``.
Args:
endianess (str): ``"big"`` lists bit 0 first, as the printed form
does; ``"little"`` lists it last. Defaults to ``"big"``.
Returns:
str: The bits as text.
Raises:
ValueError: If ``endianess`` is neither ``"big"`` nor
``"little"``.
Examples:
>>> BitString("110").to01()
'110'
>>> BitString("110").to01("little")
'011'
"""
if endianess == "big":
return "".join(map(str, self.bits))
elif endianess == "little":
return "".join(map(str, reversed(self.bits)))
else:
raise ValueError("Invalid endianess. Must be 'big' or 'little'.")
[docs]
def toindex(self, endianess: str = "big"):
"""Return the index of the basis state, as in a state vector.
Indices start at 0, so this is the same value as :meth:`tointeger`.
Args:
endianess: See :meth:`tointeger`. Defaults to ``"big"``.
Returns:
int: The index.
Raises:
ValueError: If the string is empty, or ``endianess`` is neither
``"big"`` nor ``"little"``.
"""
if endianess == "big":
return bitvec_to_int(self.bits[::-1])
elif endianess == "little":
return bitvec_to_int(self.bits)
else:
raise ValueError("endian must be either 'big' or 'little'")
def __eq__(self, other):
if not isinstance(other, BitString):
return False
return self.bits == other.bits
def __str__(self):
s = f"{len(self.bits)}-qubit BitString"
nz = self.nonzeros()
if len(nz) != 0:
s += f" with {len(nz)} non-zero qubits:\n"
s += f"├── |{self.bits.to01()}⟩\n"
s += f"└── non-zero qubits: {nz}"
else:
s += f":\n└── |{self.bits.to01()}⟩"
return s
def __repr__(self):
return "bs" + '"' + self.to01() + '"'
def __len__(self):
return len(self.bits)
def __hash__(self):
return hash(self.bits.to01())
def __iter__(self):
return iter(self.bits)
def __getitem__(self, index):
if type(index) is slice:
return BitString(self.bits[index])
return self.bits[index]
[docs]
def __setitem__(self, index, value):
"""Set a specific bit by creating a new frozenbitarray.
The buffer stays frozen because `__hash__` is defined over it and
`QCSResults.histogram()` uses BitStrings as dictionary keys, so a
freely mutable buffer would break the key contract. Copying it as a
bitarray rather than through a Python list of ints is what keeps a
single-bit write from costing two conversions of the whole string.
"""
if not isinstance(value, (bool, int)) or value not in (0, 1):
raise ValueError("Value must be a boolean or an integer (0 or 1).")
temp = bitarray(self._bits)
temp[index] = value
self._bits = frozenbitarray(temp)
def __or__(self, other):
if not isinstance(other, BitString):
raise TypeError("BitString can only be ORed with another BitString.")
return BitString(self.bits | other.bits)
def __and__(self, other):
if not isinstance(other, BitString):
raise TypeError("BitString can only be ANDed with another BitString.")
return BitString(self.bits & other.bits)
def __xor__(self, other):
if not isinstance(other, BitString):
raise TypeError("BitString can only be XORed with another BitString.")
return BitString(self.bits ^ other.bits)
def __invert__(self):
return BitString(~self.bits)
def __lshift__(self, other):
if not isinstance(other, int):
raise TypeError("BitString can only be left shifted by an integer.")
return BitString(self.bits << other)
def __rshift__(self, other):
if not isinstance(other, int):
raise TypeError("BitString can only be right shifted by an integer.")
return BitString(self.bits >> other)
def __add__(self, other):
if not isinstance(other, BitString):
raise TypeError("BitString can only be added with another BitString.")
return BitString(self.bits + other.bits)
def __mul__(self, other):
if not isinstance(other, int):
raise TypeError("BitString can only be multiplied by an integer.")
return BitString(self.bits * other)
__all__ = ["BitString"]