MatchCake

matchcake.devices package

Subpackages

Submodules

matchcake.devices.device_utils module

matchcake.devices.device_utils.circuit_or_fop_matmul(first_matrix: Any, second_matrix: Any, *, fop_direction: MatmulDirectionType = MatmulDirectionType.RL, circuit_direction: MatmulDirectionType = MatmulDirectionType.LR, operator: Literal['einsum', 'matmul', '@'] = '@')

Matmul two operators together. The direction of the matmul will depend on the type of the operators. If both operators are MatchgateOperations, the direction of the matmul will be determined by the circuit_direction parameter. If both operators are SingleParticleTransitionMatrixOperations, the direction of the matmul will be determined by the fop_direction parameter. If one operator is a MatchgateOperation and the other is a SingleParticleTransitionMatrixOperation, the MatchgateOperation will be converted to a SingleParticleTransitionMatrixOperation and the matmul will be performed in the direction of the SingleParticleTransitionMatrixOperation.

If the type of the operator is not recognized, a ValueError will be raised.

matchcake.devices.nif_device module

class matchcake.devices.nif_device.NonInteractingFermionicDevice(wires: int | Wires | List[int] = 2, *, r_dtype=torch.float64, c_dtype=torch.complex128, analytic=None, shots: int | None = None, **kwargs)

Bases: QubitDevice

The Non-Interacting Fermionic Simulator device.

Parameters:
  • wires (Union[int, Wires, List[int]]) – The number of wires of the device

  • r_dtype (np.dtype) – The data type for the real part of the state vector

  • c_dtype (np.dtype) – The data type for the complex part of the state vector

Kwargs:

Additional keyword arguments

Keyword Arguments:
  • prob_strategy – The strategy to compute the probabilities. Can be either “lookup_table” or “explicit_sum”. Defaults to “lookup_table”.

  • majorana_getter – The Majorana getter to use. Defaults to a new instance of MajoranaGetter.

  • contraction_method – The contraction method to use. Can be either None or “neighbours”. Defaults to None.

  • pfaffian_method – The method to compute the Pfaffian. Can be either “det” or “P”. Defaults to “det”.

  • n_workers – The number of workers to use for multiprocessing. Defaults to 0.

  • star_state_finding_strategy – The strategy to find the star state.

Variables:
  • prob_strategy (str) – The strategy to compute the probabilities

  • majorana_getter (MajoranaGetter) – The Majorana getter to use

  • contraction_method (Optional[str]) – The contraction method to use

  • pfaffian_method (str) – The method to compute the Pfaffian

  • n_workers (int) – The number of workers to use for multiprocessing

  • basis_state_index (int) – The index of the basis state

  • sparse_state (sparse.coo_array) – The sparse state of the device

  • state (np.ndarray) – The state of the device

  • is_state_initialized (bool) – Whether the state is initialized

  • transition_matrix (np.ndarray) – The transition matrix of the device

  • lookup_table (NonInteractingFermionicLookupTable) – The lookup table of the device

  • memory_usage (int) – The memory usage of the device

Note:

This device is a simulator for non-interacting fermions. It is based on the default.qubit device.

Note:

This device supports batch execution.

Note:

This device is in development, and its API is subject to change.

DEFAULT_CONTRACTION_METHOD = 'neighbours'
DEFAULT_PFAFFIAN_METHOD = 'det'
DEFAULT_PROB_STRATEGY = 'LookupTable'
DEFAULT_SAMPLING_STRATEGY = '2QubitBy2QubitSampling'
DEFAULT_STAR_STATE_FINDING_STRATEGY = 'FromSampling'
__init__(wires: int | Wires | List[int] = 2, *, r_dtype=torch.float64, c_dtype=torch.complex128, analytic=None, shots: int | None = None, **kwargs)
analytic_probability(wires=None)

Return the (marginal) probability of each computational basis state from the last run of the device.

PennyLane uses the convention \(|q_0,q_1,\dots,q_{N-1}\rangle\) where \(q_0\) is the most significant bit.

If no wires are specified, then all the basis states representable by the device are considered and no marginalization takes place.

Note

marginal_prob() may be used as a utility method to calculate the marginal probability distribution.

Parameters:

wires (Iterable[Number, str], Number, str, Wires) – wires to return marginal probabilities for. Wires not provided are traced out of the system.

Returns:

list of the probabilities

Return type:

array[float]

apply(operations, rotations=None, **kwargs)

This method applies a list of operations to the device. It will update the _transition_matrix attribute of the device.

Note:

if the number of workers is different from 0, this method will use multiprocessing method apply_mp() to apply the operations.

Parameters:
  • operations – The operations to apply

  • rotations – The rotations to apply

  • kwargs – Additional keyword arguments. The keyword arguments are passed to the apply_mp() method.

Returns:

None

apply_generator(op_iterator: Iterable[Operation], **kwargs) NonInteractingFermionicDevice

Apply a generator of gates to the device.

Parameters:
  • op_iterator (Iterable[qml.operation.Operation]) – The generator of operations to apply

  • kwargs – Additional keyword arguments

Returns:

None

apply_mp(operations, rotations=None, **kwargs)

Apply a list of operations to the device using multiprocessing. This method will update the _transition_matrix attribute of the device.

Parameters:
  • operations – The operations to apply

  • rotations – The rotations to apply

  • kwargs – Additional keyword arguments

Returns:

None

apply_op(op: Operation) SingleParticleTransitionMatrixOperation
apply_state_prep(operation, **kwargs) bool

Apply a state preparation operation to the device. Will set the internal state of the device only if the operation is a state preparation operation and then return True. Otherwise, it will return False.

Parameters:
  • operation – The operation to apply

  • kwargs – Additional keyword arguments

Returns:

True if the operation was applied, False otherwise

Return type:

bool

author = 'Jérémie Gince'
property basis_state_index: int
batch_transform(circuit: QuantumTape)

Apply a differentiable batch transform for preprocessing a circuit prior to execution. This method is called directly by the QNode, and should be overwritten if the device requires a transform that generates multiple circuits prior to execution.

By default, this method contains logic for generating multiple circuits, one per term, of a circuit that terminates in expval(H), if the underlying device does not support Hamiltonian expectation values, or if the device requires finite shots.

Warning

This method will be tracked by autodifferentiation libraries, such as Autograd, JAX, TensorFlow, and Torch. Please make sure to use qml.math for autodiff-agnostic tensor processing if required.

Parameters:

circuit (.QuantumTape) – the circuit to preprocess

Returns:

Returns a tuple containing the sequence of circuits to be executed, and a post-processing function to be applied to the list of evaluated circuit results.

Return type:

tuple[Sequence[.QuantumTape], callable]

property binary_state: ndarray
classmethod capabilities()

Get the capabilities of this device class.

Inheriting classes that change or add capabilities must override this method, for example via

@classmethod
def capabilities(cls):
    capabilities = super().capabilities().copy()
    capabilities.update(
        supports_a_new_capability=True,
    )
    return capabilities
Returns:

results

Return type:

dict[str->*]

casting_priorities = ['numpy', 'autograd', 'jax', 'tf', 'torch']
close_p_bar()
compute_star_state(**kwargs)

Compute the star state of the device. The star state is the state that has the highest probability.

Parameters:

kwargs – Additional keyword arguments

Returns:

The star state and its probability

exact_expval(observable)
execute_generator(op_iterator: Iterable[Operation], observable: Optional = None, output_type: Literal['samples', 'expval', 'probs', 'star_state', '*state'] | None = None, **kwargs)

Execute a generator of operations on the device and return the result in the specified output type.

Parameters:
  • op_iterator (Iterable[qml.operation.Operation]) – A generator of operations to execute

  • observable (Optional) – The observable to measure

  • output_type (Optional[Literal["samples", "expval", "probs"]]) – The type of output to return. Supported types are “samples”, “expval”, and “probs”

  • kwargs – Additional keyword arguments

Keyword Arguments:
  • reset – Whether to reset the device before applying the operations. Default is False.

  • apply – Whether to apply the operations. Where “auto” will apply the operations if the transition matrix is None which means that no operations have been applied yet. Default is “auto”.

  • wires – The wires to measure the observable on. Default is None.

  • shot_range – The range of shots to measure the observable on. Default is None.

  • bin_size – The size of the bins to measure the observable on. Default is None.

Returns:

The result of the execution in the specified output type

execute_output(observable: Optional = None, output_type: Literal['samples', 'expval', 'probs', 'star_state', '*state'] | None = None, **kwargs)

Return the result of the execution in the specified output type.

Parameters:
  • observable (Optional) – The observable to measure

  • output_type (Optional[Literal["samples", "expval", "probs"]]) – The type of output to return. Supported types are “samples”, “expval”, and “probs”

  • kwargs – Additional keyword arguments

Keyword Arguments:
  • reset – Whether to reset the device before applying the operations. Default is False.

  • apply – Whether to apply the operations. Where “auto” will apply the operations if the transition matrix is None which means that no operations have been applied yet. Default is “auto”.

  • wires – The wires to measure the observable on. Default is None.

  • shot_range – The range of shots to measure the observable on. Default is None.

  • bin_size – The size of the bins to measure the observable on. Default is None.

Returns:

The result of the execution in the specified output type

expval(observable, shot_range=None, bin_size=None)

Returns the expectation value of observable on specified wires.

Note: all arguments accept _lists_, which indicate a tensor product of observables.

Parameters:
  • observable (str or list[str]) – name of the observable(s)

  • wires (Wires) – wires the observable(s) are to be measured on

  • par (tuple or list[tuple]]) – parameters for the observable(s)

Returns:

expectation value \(\expect{A} = \bra{\psi}A\ket{\psi}\)

Return type:

float

gather_single_particle_transition_matrices(operations) list

Gather the single particle transition matrices of a list of operations.

Parameters:

operations – The operations to gather the single particle transition matrices from

Returns:

The single particle transition matrices of the operations

gather_single_particle_transition_matrices_mp(operations) list

Gather the single particle transition matrices of a list of operations. Will use multiprocessing if the number of workers is different from 0.

Parameters:

operations – The operations to gather the single particle transition matrices from

Returns:

The single particle transition matrices of the operations

gather_single_particle_transition_matrix(operation)

Gather the single particle transition matrix of a given operation.

Parameters:

operation – The operation to gather the single particle transition matrix from

Returns:

The single particle transition matrix of the operation

generate_samples()

Returns the computational basis samples generated for all wires.

Note that PennyLane uses the convention \(|q_0,q_1,\dots,q_{N-1}\rangle\) where \(q_0\) is the most significant bit.

Warning

This method should be overwritten on devices that generate their own computational basis samples, with the resulting computational basis samples stored as self._samples.

Returns:

array of samples in the shape (dev.shots, dev.num_wires)

Return type:

array[complex]

get_sparse_or_dense_state() int | coo_array | ndarray | TensorLike
get_state_probability(target_binary_state: TensorLike, wires: Wires | None = None)
get_states_probability(target_binary_states: TensorLike, batch_wires: Wires | None = None, **kwargs)
property global_sptm: SingleParticleTransitionMatrixOperation | None
initialize_p_bar(*args, **kwargs)
property is_state_initialized: bool
property lookup_table
property memory_usage
name = 'Non-Interacting Fermionic Simulator'
observables = {'BatchHamiltonian', 'Hadamard', 'Hermitian', 'Identity', 'PauliX', 'PauliY', 'PauliZ', 'Prod', 'Projector', 'Sprod', 'Sum'}
operations = {'BasisEmbedding', 'BasisState', 'FermionicPauli', 'FermionicRotation', 'IZ', 'MatchgateOperation', 'Rxx', 'Rzz', 'SingleParticleTransitionMatrixOperation', 'Snapshot', 'SptmFHH', 'SptmFSwap', 'SptmFSwapHH', 'SptmFSwapRzRz', 'SptmFermionicSuperposition', 'SptmIdentity', 'SptmRyRy', 'SptmRzRz', 'SptmfRxRx', 'StatePrep', 'ZI', 'fH', 'fRXX', 'fRYY', 'fRZZ', 'fSWAP', 'fXX', 'fYY', 'fZZ'}
p_bar_set_n(n: int)
p_bar_set_postfix(*args, **kwargs)
p_bar_set_postfix_str(*args, **kwargs)
p_bar_set_total(total: int)
pennylane_requires = '==0.39'
pfaffian_methods = {'PfaffianFDBPf', 'bH', 'bLTL', 'cuda_det', 'det'}
classmethod prod_single_particle_transition_matrices(first, sptm_list)

Compute the product of the single particle transition matrices of a list of single particle transition matrix.

Parameters:
  • first – The first single particle transition matrix

  • sptm_list – The list of single particle transition matrices

Returns:

The product of the single particle transition matrices with the first one

prod_single_particle_transition_matrices_mp(sptm_list)

Compute the product of the single particle transition matrices of a list of single particle transition matrix using multiprocessing.

Parameters:

sptm_list – The list of single particle transition matrices

Returns:

The product of the single particle transition matrices

reset()

Reset the device

property samples
short_name = 'nif.qubit'
property sparse_state: coo_array
property star_probability
property star_state
property state: ndarray

Return the state of the device.

Returns:

state vector of the device

Return type:

array[complex]

Note:

This function comes from the default.qubit device.

property transition_matrix
update_p_bar(*args, **kwargs)
classmethod update_single_particle_transition_matrix(old_sptm, new_sptm)

Update the old single particle transition matrix by performing a matrix multiplication with the new single particle transition matrix. :param old_sptm: The old single particle transition matrix :param new_sptm: The new single particle transition matrix

Returns:

The updated single particle transition matrix.

version = '0.0.2'

Module contents