inquanto.core

Parameters Classes

class SymbolDict(initializer=None, **kwargs)

Bases: SymbolTypeKeyDictWrapper

Holds an ordered map of sympy.Symbols 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})
clear()

Remove all symbols.

Return type:

None

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 containing SymbolDict data.

Return type:

DataFrame

discard(*symbols)

Discard symbols in-place.

Parameters:

symbols (Union[str, Symbol]) – Symbols to be discarded.

Returns:

SymbolTypeKeyDictWrapper – Updated instance.

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:

array (Union[ndarray, list]) – Array of numeric values.

Returns:

SymbolDict – Updated instance of SymbolDict.

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.

Return type:

list[dict]

items()

Returns an iterator over symbol-value pairs.

Return type:

ItemsView[Symbol, Union[float, complex, Expr, None]]

keys()

Returns an iterator over the symbols.

Return type:

KeysView[Symbol]

make_hashable()

Returns a hashable object corresponding to the SymbolDict.

Return type:

str

print_report()

Prints the SymbolDict.

Return type:

None

set(symbol, value=None)

Adds or updates a symbol-value pair.

Parameters:
Return type:

None

property symbols: list[Symbol]

Returns a list of all symbols.

to_array()

Returns SymbolDict values as a numpy.ndarray.

Return type:

ndarray

to_dict()

Returns the underlying Python dict.

Return type:

dict[Symbol, Union[float, complex, Expr, None]]

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 of SymbolDict.

values()

Returns an iterator over the values.

Return type:

ValuesView[Union[float, complex, Expr, None]]

class SymbolSet(iterable=None)

Bases: SymbolTypeKeyDictWrapper

Holds an ordered set of sympy.Symbols.

It can be converted to a SymbolDict by assigned values to the symbols, using provided class methods.

Parameters:

iterable (Optional[Iterable[Union[str, Symbol]]], default: None) – Iterable of symbols.

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 the SymbolSet, 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])
clear()

Remove all symbols.

Return type:

None

construct_from_array(array)

Constructs a SymbolDict object given an array of values.

The new SymbolDict object is constructed from the original SymbolSet instance and the input array. Values from the input array are assigned to symbols according to the order of the SymbolSet.

Parameters:

array (Union[ndarray, list]) – Array containing values to be assigned.

Returns:

SymbolDict – New SymbolDict 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 original SymbolSet instance, with values assigned according to other.

Parameters:

other (Union[SymbolDict, dict]) – A symbol-to-value map.

Returns:

SymbolDict – A new SymbolDict instance.

Raises:

RuntimeError – When other does not contain any of the symbols from the SymbolSet 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 original SymbolSet, 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 – New SymbolDict instance.

construct_zeros()

Constructs a SymbolDict object with all values set to zero.

The new SymbolDict object contains all symbols from the original SymbolSet, with values set to zero.

Returns:

SymbolDict – New SymbolDict 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
df()

Returns a pandas.DataFrame containing SymbolSet data.

Return type:

DataFrame

discard(*symbols)

Discard symbols in-place.

Parameters:

symbols (Union[str, Symbol]) – Symbols to be discarded.

Returns:

SymbolTypeKeyDictWrapper – Updated instance.

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]

make_hashable()

Returns a hashable object corresponding to the SymbolSet.

Return type:

str

renamed(name_function=None, prefix='new_')

Returns a new set with the same order but renamed.

Parameters:
  • name_function (Optional[Callable[[str], str]], default: None) – Function to rename symbols.

  • prefix (str, default: "new_") – If name_function is not provided, prefix is added in front of every symbol.

Returns:

SymbolSet – A new SymbolSet object.

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])
property symbols: list[Symbol]

Returns a list of all symbols.

update(other)

Update the SymbolSet based on another iterable of symbols.

The order is defined by a symbol’s first appearance.

Parameters:

other (Iterable[Union[str, Symbol]]) – Symbols from which to update.

Returns:

SymbolSet – Updated instance of SymbolSet.

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, or CacheLevels.LIFETIME: cache is not cleared during lifetime of the object, using it (unless memory used exceeds max_mem_size parameter value).

  • max_mem_size (Optional[int], default: None) – Maximum memory size that cache is allowed to occupy. Not checked if set to None.

  • 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 cache: Dict[Any, Any]

Returns the internal dict, storing cache.

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).

clear()

Clears cache.

Return type:

None

hashkey(*args, **kwargs)

Creates a hashable key from input arguments.

Optionally uses a key generator function if passed at the class instance construction.

Parameters:
  • args (Any) – Arguments to be made hashable.

  • kwargs (Any) – Keyword arguments, which values are to be made hashable.

Returns:

Tuple[Any, ...] – A list of hashable objects, to be used as a cache dict key.

Raises:

RuntimeError – If created key is not hashable.

property level: CacheLevels

Returns the cache level.

property max_mem_size: int | None

Returns the maximum allowed memory size for cache.

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.

property num_entries: int

Returns the number of entries currently stored in cache.

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 Timer

Bases: object

Simple Timer.

start()

Starts timer.

Return type:

None

stop()

Stops timer.

Return type:

None

class TimerWith(name=None, process=False)

Bases: object

Basic timer context manager.

Parameters:
  • name (Optional[str], default: None) – Name for the context.

  • process (bool, default: False) – Whether to use process timing.

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
class InQuantoContext(job_name, working_file_name=None, file_only=False)

Bases: object

Context to log into a file during a calculation.

Parameters:
  • job_name (str) – Name of the job (this will be part of the file name).

  • working_file_name (Optional[str], default: None) – Name of this file, for example "__file__".

  • file_only (bool, default: False) – Whether to suppress std outputs.

property base: str

Filename base.

property prefix: str

Filename prefix.

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.

Parameters:
  • ordered_symbols (Sequence[Symbol]) – Sequence of symbols defining output order.

  • symbol_pair_to_value (dict[tuple[Symbol, Symbol], float]) – Map of symbol-pairs to values.

Returns:

ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]] – Matrix of values with axes ordered according to ordered_symbols.

dict_to_vector(ordered_symbols, symbol_to_value)

Return an array of values with specified order.

Parameters:
  • ordered_symbols (Sequence[Symbol]) – Sequence of symbols defining output order.

  • symbol_to_value (dict[Symbol, float]) – Map of symbols to values.

Returns:

ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]] – Values ordered according to ordered_symbols.

matrix_to_dict(ordered_symbols, matrix)

Converts a matrix of values to a map of symbol-pairs to values.

Parameters:
  • ordered_symbols (Sequence[Symbol]) – Sequence of symbols defining output order.

  • matrix (ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]]) – Matrix of values to be assigned to symbol-pairs.

Returns:

dict[tuple[Symbol, Symbol], float] – 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.

Parameters:
  • ordered_symbols (Sequence[Symbol]) – Sequence of symbols defining output order.

  • vector (ndarray[Any, dtype[TypeVar(_ScalarType_co, bound= generic, covariant=True)]]) – Values to be assigned to symbols.

Returns:

dict[Symbol, float] – Map of symbols to values.