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

1from qml_essentials.model import Model 

2from functools import partial 

3from pennylane.fourier import coefficients 

4import numpy as np 

5 

6 

7class Coefficients: 

8 

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. 

14 

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. 

18 

19 Args: 

20 model (Model): The model to sample. 

21 kwargs (Any): Additional keyword arguments for the model function. 

22 

23 Returns: 

24 np.ndarray: The sampled Fourier coefficients. 

25 """ 

26 kwargs.setdefault("force_mean", True) 

27 kwargs.setdefault("execution_type", "expval") 

28 

29 partial_circuit = partial(model, model.params, **kwargs) 

30 coeffs = coefficients(partial_circuit, 1, model.degree) 

31 

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 ) 

37 

38 return coeffs