Special Topics¶
This page provides detailed information on specialized functionalities in MIMIQ.
BitString¶
The BitString class represents the state of bits and can be used
to represent classical registers with specified values for each bit (0 or 1). At its core,
it is simply a vector of booleans. BitString allows direct bit manipulation, bitwise operations, and conversion to other data formats like integers. It’s designed for flexibility in binary manipulation tasks within quantum computations.
Using BitString in MIMIQ Operations¶
In MIMIQ, several operations use BitString as a direct input for conditional logic
or specific quantum operations, such as IfStatement
and Amplitude. See non-unitary operations
and statistical operations pages. Here are some examples:
>>> if_statement = IfStatement(GateX(), BitString("01011"))
>>> if_statement
IF (c==01011) X
# Amplitude Operation
>>> Amplitude(BitString("001"))
Amplitude(bs"001")
Constructors¶
BitString objects can be constructed in different ways.
From a String: Use
BitString("binary_string")to initialize a BitString by parsing a string in binary format.>>> BitString("1101") bs"1101"
From bit locations: Use
BitString(numbits, bit_indices)to initialize a BitString ofnumbits, setting specific bits to 1.# Initializing with Specific Bits >>> BitString(8, [2, 4, 6]) bs"00101010"
From a function: Use
BitString(f, numbits)to initialize a BitString withnumbits, where each bit is set based on the functionf.# Initialize an 8-bit BitString where bits are set based on even indices >>> BitString.fromfunction(8, lambda i: i % 2 == 0) bs"10101010"
Accessing and Modifying Bits¶
Each bit in a BitString can be accessed or modified individually in the same way as vectors,
making it easy to retrieve or set specific bit values.
# Accessing a Bit
>>> bs = BitString(4, [1, 3])
>>> bs
bs"0101"
>>> bs[2]
0
>>> # Modifying a Bit
>>> bs[2] = True
>>> bs
bs"0111"
A useful function is nonzeros(), which returns the indices of non-zero bits in a BitString.
>>> bs = BitString(6, [1, 3, 5])
>>> bs.nonzeros()
[1, 3, 5]
Conversion and Manipulation Methods¶
The BitString class includes functionality for
conversion to integer representations, indexing, and other methods for
retrieving and manipulating bit values:
BitString to Integer: Use
tointeger()to convert aBitStringinto its integer representation,
By default it uses a big-endian order.
>>> bs = BitString("101010") >>> bs bs"101010" # Convert BitString to Integer (big-endian by default) >>> bs.tointeger() 21 # Convert BitString to Integer (little-endian) >>> bs.tointeger(endianess='little') 42
Alternatively, you can use the function toindex(), which converts a BitString to an index for
purposes like vector indexing, checking bounds, and compatibility with 64-bit indexing constraints. It’s
essentially the same as tointeger().
>>> bs.toindex() 21
BitString to String: Use
to01().# Convert BitString to String of "0"s and "1"s (big-endian (default)) >>> bs.to01() '101010' # Convert BitString to String of "0"s and "1"s (little-endian) >>> bs.to01(endianess='little') '010101'
Bitwise Operators¶
BitString supports bitwise operations such as NOT, AND, OR, XOR,
as well as bitwise shifts:
NOT (~):
>>> bs = BitString("1011") >>> ~bs bs"0100"
AND (&), OR (|):
>>> bs1 = BitString("1100") >>> bs2 = BitString("0110") # Bitwise AND >>> bs1 & bs2 bs"0100" # Bitwise OR >>> bs1 | bs2 bs"1110"
XOR (^):
# Bitwise XOR >>> bs1 ^ bs2 bs"1010"
Left Shift (<<) and Right Shift (>>):
# Left Shift >>> bs << 1 bs"0110" # Right Shift >>> bs >> 1 bs"0101"
Concatenation and Repetition¶
BitString supports concatenation and repetition, allowing you to combine or extend bitstrings efficiently:
Concatenation (+) Use
+perator to combines twoBitStringobjects by appending the bits ofrhstolhs.>>> bs1 = BitString("1010") >>> bs2 = BitString("0101") >>> bs1 + bs2 bs"10100101"
Repetition (*) Use
*perator to repeat aBitStringto a specified number of times, creating a newBitStringwith the pattern repeated.>>> bs = BitString("1010") >>> bs * 2 bs"10101010"
Reference¶
- class BitString(arg, indices=None)[source]
Bases:
objectA sequence of bits, one per qubit or classical bit.
A
BitStringrepresents a computational basis state of a register, such as a measurement outcome. Sampled results inQCSResultsare stored asBitStringobjects, and thebitstringsargument ofsubmittakes them to request amplitudes. Bitiof the string is qubit (or classical bit)i, and the printed formbs"..."lists bit 0 first.A
BitStringis hashable, so it can be a dictionary key. Indexing returns a bit; slicing returns a newBitString. Assigning a bit withbs[i] = 1changes 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"
- __init__(arg, indices=None)[source]
Create a BitString.
- Parameters:
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 abitarray.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
indicesis outsiderange(arg), or the bits contain values other than 0 and 1.TypeError – If
arghas 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"
- property bits
The bits as a read-only
frozenbitarray.
- static fromnonzeros(num_qubits, nonzeros)[source]
Create a BitString with the given bits set to 1.
- Parameters:
- Returns:
The new string.
- Return type:
- Raises:
ValueError – If an index is outside
range(num_qubits).
Examples
>>> BitString.fromnonzeros(4, [1, 3]) bs"0101"
- static fromfunction(num_qubits, f)[source]
Create a BitString by evaluating a function on each index.
- Parameters:
- Returns:
The new string.
- Return type:
Examples
>>> BitString.fromfunction(6, lambda i: i % 3 == 0) bs"100100"
- static fromstring(bitstring)[source]
Create a BitString from a string of
"0"and"1".Same as
BitString(bitstring).
- static fromint(num_qubits, integer, endianess='big')[source]
Create a BitString from the binary digits of an integer.
- Parameters:
num_qubits (int) – The number of bits.
integer (int) – A non-negative integer that fits in
num_qubitsbits.endianess (str) –
"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 oftointeger()with the sameendianess.
- Returns:
The new string.
- Return type:
- Raises:
ValueError – If
integerneeds more thannum_qubitsbits, orendianessis neither"big"nor"little".
Examples
>>> BitString.fromint(4, 1) bs"1000" >>> BitString.fromint(4, 1, "little") bs"0001" >>> BitString.fromint(4, 6).tointeger() 6
- num_qubits()[source]
Return the number of bits, the same as
len(bs).
- nonzeros()[source]
Return the indices of the bits set to 1, as a list of
int.
- zeros()[source]
Return the indices of the bits set to 0, as a list of
int.
- tointeger(endianess='big')[source]
Return the integer whose binary digits are the bits.
- Parameters:
endianess (str) –
"big"reads bit 0 as the least significant binary digit;"little"reads it as the most significant. Defaults to"big".- Returns:
The integer value.
- Return type:
- Raises:
ValueError – If the string is empty, or
endianessis neither"big"nor"little".
Examples
>>> BitString("1000").tointeger() 1 >>> BitString("1000").tointeger("little") 8
- to01(endianess='big')[source]
Return the bits as a string of
"0"and"1".- Parameters:
endianess (str) –
"big"lists bit 0 first, as the printed form does;"little"lists it last. Defaults to"big".- Returns:
The bits as text.
- Return type:
- Raises:
ValueError – If
endianessis neither"big"nor"little".
Examples
>>> BitString("110").to01() '110' >>> BitString("110").to01("little") '011'
- toindex(endianess='big')[source]
Return the index of the basis state, as in a state vector.
Indices start at 0, so this is the same value as
tointeger().- Parameters:
endianess (str) – See
tointeger(). Defaults to"big".- Returns:
The index.
- Return type:
- Raises:
ValueError – If the string is empty, or
endianessis neither"big"nor"little".
- __setitem__(index, value)[source]
Set a specific bit by creating a new frozenbitarray.
The buffer stays frozen because
__hash__is defined over it andQCSResults.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.