inquanto.core
Parameters Classes
- class SymbolDict(initializer=None, **kwargs)
Bases:
SymbolTypeKeyDictWrapper
Holds an ordered map of
sympy.Symbol
s to values.Provides a general way to keep track of the symbols in a quantum expression. When a string is used as a key, it is converted to a
Symbol
object.- Parameters:
Examples
>>> SymbolDict(a=1,b=2) SymbolDict({a: 1, b: 2}) >>> SymbolDict({"c": 0.1, "d": 0.2}) SymbolDict({c: 0.1, d: 0.2}) >>> SymbolDict([("sym0", 10), ("sym1", 20)]) SymbolDict({sym0: 10, sym1: 20})
- copy()
Performs a deep copy.
- Returns:
Union
[SymbolTypeKeyDictWrapper
,SymbolDict
,SymbolSet
] – A deep copy of this object.
Examples
>>> symbols = SymbolSet(["a", "b", "c"]) >>> other = symbols.copy() >>> symbols == other True >>> symbols is other False >>> symbols.add("d") d >>> symbols == other False
- df()
Returns a
pandas.DataFrame
containingSymbolDict
data.- Return type:
DataFrame
- discard(*symbols)
Discard symbols in-place.
- from_array(array)
Sets symbol values from an input
numpy.ndarray
.The array must have at least as many elements as there are symbols in the
SymbolDict
.- Parameters:
- Returns:
SymbolDict
– Updated instance ofSymbolDict
.
- classmethod from_circuit(circuit)
Instantiate from a pytket circuit.
- Parameters:
circuit (
Circuit
) – Input circuit from which symbols are extracted.- Return type:
Union
[SymbolTypeKeyDictWrapper
,SymbolDict
,SymbolSet
]
- generate_report()
Generates a report on the symbol order and values in
.json
format.
- items()
Returns an iterator over symbol-value pairs.
- make_hashable()
Returns a hashable object corresponding to the
SymbolDict
.- Return type:
- print_report()
Prints the
SymbolDict
.- Return type:
- set(symbol, value=None)
Adds or updates a symbol-value pair.
- to_array()
Returns
SymbolDict
values as anumpy.ndarray
.- Return type:
ndarray
- update(other)
Update the symbol values based on another
SymbolDict
.The order is defined by the symbols first appearance.
- Parameters:
other (
Union
[SymbolDict
,dict
[Symbol
,Union
[float
,complex
,Expr
,None
]]]) – Symbol-to-value map from which to update.- Returns:
SymbolDict
– Updated instance ofSymbolDict
.
- class SymbolSet(iterable=None)
Bases:
SymbolTypeKeyDictWrapper
Holds an ordered set of
sympy.Symbol
s.It can be converted to a
SymbolDict
by assigned values to the symbols, using provided class methods.Examples
>>> SymbolSet(["a", "b", "c"]) SymbolSet([a, b, c]) >>> SymbolSet(["a", Symbol("b"), "c"]) SymbolSet([a, b, c])
- add(symbol)
Adds a symbol to the end of the ordered symbols.
- Parameters:
symbol (
Union
[str
,Symbol
]) – The symbol to be added. If it already exists in theSymbolSet
, the set remains unchanged.- Returns:
Symbol
– The added symbol.
Examples
>>> symbols = SymbolSet(["a", "b", "c"]) >>> symbols.add("b") b >>> symbols SymbolSet([a, b, c]) >>> symbols.add("a1") a1 >>> symbols SymbolSet([a, b, c, a1])
- construct_from_array(array)
Constructs a
SymbolDict
object given an array of values.The new
SymbolDict
object is constructed from the originalSymbolSet
instance and the input array. Values from the input array are assigned to symbols according to the order of theSymbolSet
.- Parameters:
array (
Union
[ndarray
,list
]) – Array containing values to be assigned.- Returns:
SymbolDict
– NewSymbolDict
instance.- Raises:
AssertionError – When the input array and
SymbolSet
have different lengths.
- construct_from_dict(other)
Constructs a
SymbolDict
object given a symbol-to-value map.The new
SymbolDict
contains all the symbols from the originalSymbolSet
instance, with values assigned according toother
.- Parameters:
other (
Union
[SymbolDict
,dict
]) – A symbol-to-value map.- Returns:
SymbolDict
– A newSymbolDict
instance.- Raises:
RuntimeError – When
other
does not contain any of the symbols from theSymbolSet
instance.
Examples
>>> sd = SymbolDict(a=1, b=2, c=3) >>> ss = SymbolSet(['a', 'b']) >>> ss.construct_from_dict(sd) SymbolDict({a: 1, b: 2}) >>> sd = {Symbol("b"): 2, Symbol("a"): 1, Symbol("c"): 3} >>> ss.construct_from_dict(sd) SymbolDict({a: 1, b: 2})
- construct_random(seed=0, mu=0.0, sigma=1.0)
Constructs a
SymbolDict
object with random values.The new
SymbolDict
object contains all symbols from the originalSymbolSet
, with values drawn randomly from a Gaussian distribution.- Parameters:
seed (default:
0
) – Seed for random number generation.mu (default:
0.0
) – Mean of the distribution.sigma (default:
1.0
) – Standard deviation of the distribution.
- Returns:
SymbolDict
– NewSymbolDict
instance.
- construct_zeros()
Constructs a
SymbolDict
object with all values set to zero.The new
SymbolDict
object contains all symbols from the originalSymbolSet
, with values set to zero.- Returns:
SymbolDict
– NewSymbolDict
instance.
- copy()
Performs a deep copy.
- Returns:
Union
[SymbolTypeKeyDictWrapper
,SymbolDict
,SymbolSet
] – A deep copy of this object.
Examples
>>> symbols = SymbolSet(["a", "b", "c"]) >>> other = symbols.copy() >>> symbols == other True >>> symbols is other False >>> symbols.add("d") d >>> symbols == other False
- discard(*symbols)
Discard symbols in-place.
- classmethod from_circuit(circuit)
Instantiate from a pytket circuit.
- Parameters:
circuit (
Circuit
) – Input circuit from which symbols are extracted.- Return type:
Union
[SymbolTypeKeyDictWrapper
,SymbolDict
,SymbolSet
]
- renamed(name_function=None, prefix='new_')
Returns a new set with the same order but renamed.
- Parameters:
- Returns:
Examples
>>> SymbolSet(["a", "b", "c"]).renamed() SymbolSet([new_a, new_b, new_c]) >>> SymbolSet(["a", "b", "c"]).renamed(lambda s: f"renamed_{s}") SymbolSet([renamed_a, renamed_b, renamed_c])
Cache
- class Cache(level=CacheLevels.LIFETIME, max_mem_size=None, size_unit=CacheSizeUnit.MB, key_generator=None)
Bases:
object
Implements general cache handling.
- Parameters:
level (
CacheLevels
, default:CacheLevels.LIFETIME
) – Cache level (CacheLevels.NONE
: nothing is cached, orCacheLevels.LIFETIME
: cache is not cleared during lifetime of the object, using it (unless memory used exceedsmax_mem_size
parameter value).max_mem_size (
Optional
[int
], default:None
) – Maximum memory size that cache is allowed to occupy. Not checked if set toNone
.size_unit (
CacheSizeUnit
, default:CacheSizeUnit.MB
) – Memory size unit (used to process input and output).key_generator (
Optional
[Callable
[...
,Hashable
]], default:None
) – Function to generate a key from the input objects.
- Raises:
ValueError – When
max_mem_size
parameter has negative value.
- property check_mem: bool
Returns whether the size of memory occupied by cache is to be checked at runtime.
Notes
Currently the
Cache
class does not check for memory size itself (except for the report). Such checks are supposed to be done by a handler (e.g. a caching decorator).
- hashkey(*args, **kwargs)
Creates a hashable key from input arguments.
Optionally uses a key generator function if passed at the class instance construction.
- property level: CacheLevels
Returns the cache level.
- property mem_size: float
Calculates size of memory occupied by cache.
Currently uses implementation given here and converts result (in bytes) to the set memory size units.
- report()
Returns a pandas
DataFrame
object containing a report of the current state of cache.- Return type:
DataFrame
- property size_unit: CacheSizeUnit
Returns the memory size unit as used by the class instance.
- class CacheLevels(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
IntEnum
Enum class containing possible cache levels.
- LIFETIME = 3
- NONE = 1
- RUNTIME = 2
- as_integer_ratio()
Return integer ratio.
Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.
>>> (10).as_integer_ratio() (10, 1) >>> (-10).as_integer_ratio() (-10, 1) >>> (0).as_integer_ratio() (0, 1)
- bit_count()
Number of ones in the binary representation of the absolute value of self.
Also known as the population count.
>>> bin(13) '0b1101' >>> (13).bit_count() 3
- bit_length()
Number of bits necessary to represent self in binary.
>>> bin(37) '0b100101' >>> (37).bit_length() 6
- conjugate()
Returns self, the complex conjugate of any int.
- denominator
the denominator of a rational number in lowest terms
- from_bytes(byteorder='big', *, signed=False)
Return the integer represented by the given array of bytes.
- bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.
- signed
Indicates whether two’s complement is used to represent the integer.
- imag
the imaginary part of a complex number
- numerator
the numerator of a rational number in lowest terms
- real
the real part of a complex number
- to_bytes(length=1, byteorder='big', *, signed=False)
Return an array of bytes representing an integer.
- length
Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.
- signed
Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
- class CacheSizeUnit(value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)
Bases:
IntEnum
Enum class containing possible memory units.
- BYTES = 1
- GB = 4
- KB = 2
- MB = 3
- as_integer_ratio()
Return integer ratio.
Return a pair of integers, whose ratio is exactly equal to the original int and with a positive denominator.
>>> (10).as_integer_ratio() (10, 1) >>> (-10).as_integer_ratio() (-10, 1) >>> (0).as_integer_ratio() (0, 1)
- bit_count()
Number of ones in the binary representation of the absolute value of self.
Also known as the population count.
>>> bin(13) '0b1101' >>> (13).bit_count() 3
- bit_length()
Number of bits necessary to represent self in binary.
>>> bin(37) '0b100101' >>> (37).bit_length() 6
- conjugate()
Returns self, the complex conjugate of any int.
- denominator
the denominator of a rational number in lowest terms
- from_bytes(byteorder='big', *, signed=False)
Return the integer represented by the given array of bytes.
- bytes
Holds the array of bytes to convert. The argument must either support the buffer protocol or be an iterable object producing bytes. Bytes and bytearray are examples of built-in objects that support the buffer protocol.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.
- signed
Indicates whether two’s complement is used to represent the integer.
- imag
the imaginary part of a complex number
- numerator
the numerator of a rational number in lowest terms
- real
the real part of a complex number
- to_bytes(length=1, byteorder='big', *, signed=False)
Return an array of bytes representing an integer.
- length
Length of bytes object to use. An OverflowError is raised if the integer is not representable with the given number of bytes. Default is length 1.
- byteorder
The byte order used to represent the integer. If byteorder is ‘big’, the most significant byte is at the beginning of the byte array. If byteorder is ‘little’, the most significant byte is at the end of the byte array. To request the native byte order of the host system, use `sys.byteorder’ as the byte order value. Default is to use ‘big’.
- signed
Determines whether two’s complement is used to represent the integer. If signed is False and a negative integer is given, an OverflowError is raised.
Logging and Timing
- class TimerWith(name=None, process=False)
Bases:
object
Basic timer context manager.
- Parameters:
Examples
>>> with TimerWith(): ... for i in range(1000000): ... a = i ** 2 #... #... >>> with TimerWith("OUTER"): ... for i in range(1000000): ... a = i ** 2 ... with TimerWith("INNER"): ... for i in range(1000000): ... a = i ** 2 #... #... #... #...
- block_counter = 0
Methods
InQuanto’s core module containing utility methods and classes useful in multiple submodules.
- dict_to_matrix(ordered_symbols, symbol_pair_to_value)
Return a matrix of values with specified order.
- dict_to_vector(ordered_symbols, symbol_to_value)
Return an array of values with specified order.
- matrix_to_dict(ordered_symbols, matrix)
Converts a matrix of values to a map of symbol-pairs to values.
- pd_safe_eigh(h, s, lindep=1e-14)
Solves the generalized eigenvalue problem \(HC = SCE\).
\(H\) and \(S\) are square matrices, and \(C\) is a matrix of eigenvectors. The matrices \(H\) and \(S\) are usually Hermitian (or symmetric if real) and \(S\) is positive definite.
- Parameters:
h (
ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]]) – Hermitian matrix.s (
ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]]) – Hermitian matrix.lindep (
float
, default:1e-14
) – Tolerance to determine linear dependency. Diagonalizing \(S\) identifies eigenvectors as linearly dependent subsets when their corresponding eigenvalues fall below the specified threshold.
- Returns:
tuple
[ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]],ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]],ndarray
[Any
,dtype
[TypeVar
(_ScalarType_co
, bound=generic
, covariant=True)]]] – Eigenvalues \(E\) in the linearly independent subspace, matrix of eigenvectors \(C\), and eigenvalues of \(S\).
- vector_to_dict(ordered_symbols, vector)
Converts a vector of values to a symbol-value map.