Coverage for qml_essentials/coefficients.py: 93%
14 statements
« prev ^ index » next coverage.py v7.6.5, created at 2024-11-15 11:13 +0000
« prev ^ index » next coverage.py v7.6.5, created at 2024-11-15 11:13 +0000
1from qml_essentials.model import Model
2from functools import partial
3from pennylane.fourier import coefficients
4import numpy as np
7class Coefficients:
9 @staticmethod
10 def sample_coefficients(model: Model, **kwargs) -> np.ndarray:
11 """
12 Sample the Fourier coefficients of a given model
13 using Pennylane fourier.coefficients function.
15 Note that the coefficients are complex numbers, but the imaginary part
16 of the coefficients should be very close to zero, since the expectation
17 values of the Pauli operators are real numbers.
19 Args:
20 model (Model): The model to sample.
21 kwargs (Any): Additional keyword arguments for the model function.
23 Returns:
24 np.ndarray: The sampled Fourier coefficients.
25 """
26 kwargs.setdefault("force_mean", True)
27 kwargs.setdefault("execution_type", "expval")
29 partial_circuit = partial(model, model.params, **kwargs)
30 coeffs = coefficients(partial_circuit, 1, model.degree)
32 if not np.isclose(np.sum(coeffs).imag, 0.0, rtol=1.0e-5):
33 raise ValueError(
34 f"Spectrum is not real. Imaginary part of coefficients is:\
35 {np.sum(coeffs).imag}"
36 )
38 return coeffs