quairkit.loss¶
The module of the pre-provided loss.
-
class quairkit.loss.Measure(measure_op=
None)¶ Compute the probability of the specified measurement result.
- Parameters:¶
- measure_op : str | Tensor | None¶
Specify the basis of the measurement. Defaults to
'computational'.
Note
the allowable input for measure_op are: - None, i.e., a ‘computational’ basis - a string composed of ‘i’, ‘x’, ‘y’, and ‘z’ - a projection-valued measurement (PVM) in torch.Tensor
from quairkit.database import random_state, std_basis # Define measurement basis using a string (e.g., 'xy' denotes eigen-basis of X ⊗ Y) op = Measure("xy") # Define a custom measurement basis using a user-specified PVM tensor pvm_tensor = std_basis(2).density_matrix op = Measure(pvm_tensor) # Use default computational basis op = Measure() state = random_state(num_qubits=2) # Full measurement: probability distribution over all measurement outcomes. result = op(state) print("Probabilities for measuring all qubits:", result) # Measurement on a targeted subsystem (e.g., the first qubit) result = op(state, system_idx=0) print("Probabilities for measuring the first qubit:", result) # Compute probability for a specific full-system outcome ('10') result = op(state, desired_result='10') print("Probability for measuring all qubits with outcome 10:", result) # Compute probabilities for selected outcomes (e.g., outcomes corresponding to indices 0 and 3) result = op(state, desired_result=[0, 3]) print("Probabilities for measuring all qubits with outcomes 00 and 11:", result) # Retrieve both the probability and the post-measurement state. prob, post_state = op(state, keep_state=True) print("Post-measurement state:", post_state) # Batched measurement on multiple states. state_batch = random_state(num_systems=2, size=2) result = op(state_batch) print(f"Probabilities for measuring two states:\n{result}")Probabilities for measuring all qubits: tensor([0.1273, 0.0956, 0.3312, 0.4459]) Probabilities for measuring the first qubit: tensor([0.2229, 0.7771]) Probability for measuring all qubits with outcome 10: tensor([0.3312]) Probabilities for measuring all qubits with outcomes 00 and 11: tensor([0.1273, 0.4459]) Post-measurement state: ----------------------------------------------------- Backend: state_vector System dimension: [2, 2] System sequence: [0, 1] Batch size: [4] # 0: [1.+0.j 0.+0.j 0.+0.j 0.+0.j] # 1: [0.+0.j 1.+0.j 0.+0.j 0.+0.j] # 2: [0.+0.j 0.+0.j 1.+0.j 0.+0.j] # 3: [0.+0.j 0.+0.j 0.+0.j 1.+0.j] ----------------------------------------------------- Probabilities for measuring two states: tensor([[0.2846, 0.1826, 0.2665, 0.2663], [0.1513, 0.4921, 0.1676, 0.1891]])-
forward(state, system_idx=
'full', shots=None, desired_result=None, keep_state=False)¶ Compute the probability of measurement to the input state.
- Parameters:¶
- state : StateSimulator | StateOperator¶
The quantum state to be measured.
- system_idx : Iterable[int] | int | str | None¶
The index of the systems to be measured. Defaults to
'full'which means measure all the qubits.- shots : int | None¶
The number of shots for the measurement. Defaults to None which means the default behavior.
- desired_result : List[int | str] | int | str | None¶
Specify the results of the measurement to return. Defaults to
Nonewhich means return the probability of all the results.- keep_state : bool¶
Whether return the measured state. Defaults to
False.
- Returns:¶
The probability of the measurement.
- Return type:¶
Tensor | Tuple[Tensor, StateSimulator | StateOperator] | Tuple[Dict, StateSimulator | StateOperator]
- class quairkit.loss.ExpecVal(hamiltonian)¶
The class of the loss function to compute the expectation value for an observable.
This interface allows you to use the expectation value of an observable as a loss function for training quantum circuits. The expectation value is defined as \(\langle H \rangle = \text{tr}(\rho H)\).
- Parameters:¶
- hamiltonian : Hamiltonian¶
The input observable (Hamiltonian) to compute the expectation value for.
Note
This class supports batch operations. When input states have batch dimensions, the expectation value is computed element-wise along the batch dimension.
Examples
from quairkit.database import random_hamiltonian_generator, random_state from quairkit.loss import ExpecVal # Create observable and compute expectation value observable = random_hamiltonian_generator(1) print(f'The input observable is:\n{observable}') expec_val = ExpecVal(observable) input_state = random_state(num_systems=1, rank=2) result = expec_val(input_state, decompose=True) print('The expectation value of the observable:', result)The input observable is: -0.28233465254251144 Z0 0.12440505341821817 X0 -0.2854054036807161 Y0 The expectation value of the observable: tensor([-0.1162, 0.0768, -0.0081])# Batch expectation value example input_state_batch = random_state(num_systems=1, size=2) batch_result = expec_val(input_state_batch, decompose=False) print('The expectation value of the observable:', batch_result)The expectation value of the observable: tensor([0.1748, 0.0198])-
forward(state, shots=
None, decompose=False)¶ Compute the expectation value of the observable with respect to the input state.
The value computed by this function can be used as a loss function to optimize quantum circuits.
- Parameters:¶
- state : StateSimulator | StateOperator¶
The input quantum state which will be used to compute the expectation value. Can be a single state or a batch of states.
- shots : int | None¶
The number of shots to measure the observable. Defaults to None, which means exact computation.
- decompose : bool | None¶
If True, returns the expectation value of each term in the observable separately. Defaults to False, which returns the total expectation value.
- Returns:¶
The expectation value of the observable. If
decompose=True, returns a tensor with one value per term. Ifdecompose=False, returns a scalar for single states or a tensor for batched states.- Raises:¶
NotImplementedError – If the backend is wrong or not supported.
- Return type:¶
Tensor
- class quairkit.loss.TraceDistance(target_state)¶
The class of the loss function to compute the trace distance.
This interface allows you to use the trace distance as a loss function for training quantum circuits. The trace distance is defined as \(D(\rho, \sigma) = \frac{1}{2}\text{tr}|\rho-\sigma|\).
- Parameters:¶
- target_state : StateSimulator¶
The target quantum state to be used to compute the trace distance. Can be a single state or a batch of states.
Note
This class supports batch operations. When both target and input states have batch dimensions, the trace distance is computed element-wise along the batch dimension.
Examples
from quairkit.database import one_state, bell_state from quairkit.loss import TraceDistance # Single state example target_state = one_state(1) # Define target input_state = bell_state(1) # Define input trace_distance = TraceDistance(target_state) result = trace_distance(input_state) print('Single state distance:', result)Single state distance: tensor(0.7071)# Batched states example from quairkit.database import random_state target_state_batch = random_state(num_systems=1, size=2) # Batch of 2 targets input_state_batch = random_state(num_systems=1, size=2) # Batch of 2 inputs trace_distance = TraceDistance(target_state_batch) batch_result = trace_distance(input_state_batch) print('Batched distances:', batch_result)Batched distances: tensor([0.7912, 0.7283])- forward(state)¶
Compute the trace distance between the input state and the target state.
The value computed by this function can be used as a loss function to optimize quantum circuits.
- Parameters:¶
- state : StateSimulator¶
The input quantum state which will be used to compute the trace distance with the target state. Can be a single state or a batch of states. Must have the same number of systems as the target state.
- Returns:¶
The trace distance between the input state and the target state. Returns a scalar for single states, or a tensor for batched states.
- Raises:¶
AssertionError – If the number of systems in the input state does not match the target state.
NotImplementedError – If the backend is wrong or not supported.
- Return type:¶
Tensor
- class quairkit.loss.StateFidelity(target_state)¶
The class of the loss function to compute the state fidelity.
This interface allows you to use the state fidelity as a loss function for training quantum circuits. The state fidelity is defined as \(F(\rho, \sigma) = \text{tr}(\sqrt{\sqrt{\rho}\sigma\sqrt{\rho}})\).
- Parameters:¶
- target_state : StateSimulator¶
The target quantum state to be used to compute the state fidelity. Can be a single state or a batch of states.
Note
This class supports batch operations. When both target and input states have batch dimensions, the fidelity is computed element-wise along the batch dimension.
Examples
from quairkit.database import one_state, bell_state from quairkit.loss import StateFidelity # Single state example target_state = one_state(1) # Define target input_state = bell_state(1) # Define input fidelity_calculator = StateFidelity(target_state) result = fidelity_calculator(input_state) print('Single state fidelity:', result)Single state fidelity: tensor(0.7071)# Batched states example from quairkit.database import random_state target_batch = random_state(num_systems=1, size=2) # Batch of 2 targets input_batch = random_state(num_systems=1, size=2) # Batch of 2 inputs fidelity_calculator = StateFidelity(target_batch) batch_result = fidelity_calculator(input_batch) print('Batched fidelities:', batch_result)Batched fidelities: tensor([0.5658, 0.7090])- forward(state)¶
Compute the state fidelity between the input state and the target state.
The value computed by this function can be used as a loss function to optimize quantum circuits.
- Parameters:¶
- state : StateSimulator¶
The input quantum state which will be used to compute the state fidelity with the target state. Can be a single state or a batch of states. Must have the same number of systems as the target state.
- Returns:¶
The state fidelity between the input state and the target state. Returns a scalar for single states, or a tensor for batched states. The fidelity ranges from 0 to 1.
- Raises:¶
AssertionError – If the number of systems in the input state does not match the target state.
NotImplementedError – If the backend is wrong or not supported.
- Return type:¶
Tensor