Coverage for qml_essentials / coefficients.py: 97%
759 statements
« prev ^ index » next coverage.py v7.13.4, created at 2026-11-26 07:51 +0000
« prev ^ index » next coverage.py v7.13.4, created at 2026-11-26 07:51 +0000
1from __future__ import annotations
2import sys
3import math
4import warnings
5import itertools
6from collections import defaultdict
7import jax.numpy as jnp
8from jax import random
9import numpy as np
10from scipy.stats import rankdata
11from functools import reduce, lru_cache
12from typing import List, Tuple, Optional, Any, Dict, Union
14from qml_essentials.model import Model
15from qml_essentials.pauli import PauliCircuit
16from jaqsi.paulis import PauliWord
18import logging
20log = logging.getLogger(__name__)
23class Coefficients:
24 @classmethod
25 def get_spectrum(
26 cls,
27 model: Model,
28 mfs: Union[int, List[int]] = 1,
29 mts: int = 1,
30 shift=False,
31 trim=False,
32 numerical_cap: Optional[float] = -1,
33 **kwargs,
34 ) -> Tuple[jnp.ndarray, Union[jnp.ndarray, List[jnp.ndarray]]]:
35 """
36 Extracts the coefficients of a given model using a FFT (jnp-fft).
38 Note that the coefficients are complex numbers, but the imaginary part
39 of the coefficients should be very close to zero, since the expectation
40 values of the Pauli operators are real numbers.
42 It can perform oversampling in both the frequency and time domain
43 using the `mfs` and `mts` arguments.
45 Args:
46 model (Model): The model to sample.
47 mfs (Union[int, List[int]]): Multiplicator for the highest
48 frequency. Either a single factor applied to every input
49 feature, or one factor per input feature. Default is 1.
50 mts (int): Multiplicator for the number of time samples. Default is 1.
51 shift (bool): Whether to apply jnp-fftshift. Default is False.
52 trim (bool): Whether to remove the Nyquist frequency if spectrum is even.
53 Default is False.
54 numerical_cap (Optional[float]): Numerical cap for the coefficients.
55 If positive, coefficients with magnitude below the cap are
56 zeroed and, for a single input feature, frequencies that
57 vanish entirely are removed from both `coeffs` and `freqs`.
58 kwargs (Any): Additional keyword arguments for the model function.
60 Returns:
61 Tuple[jnp.ndarray, Union[jnp.ndarray, List[jnp.ndarray]]]: The
62 coefficients, with one leading axis per input feature, and the
63 frequencies. For multiple input features, the frequencies are a
64 list with one vector per input feature, independent of `shift`;
65 for a single input feature, they are a single vector.
67 Note:
68 The FFT grid is built from the nominal `model.degree`, which does
69 not account for frequency scaling via `enc_params` or
70 `enc_pulse_params`. For a model whose effective frequencies exceed
71 the nominal degree by a factor $s > 1$, choose `mfs` at least
72 $\\lceil s \\rceil$ (e.g. `mfs=2` covers scalings up to 2),
73 otherwise the scaled components alias.
75 Multi-feature input (d >= 2) is supported for per-axis frequency
76 vectors of different lengths (the generic case, since per-axis
77 degrees need not coincide). The grid and the returned frequency
78 labels follow the ij/C-order convention (meshgrid
79 ``indexing="ij"``, flattened row-major, first input feature
80 slowest). `trim` removes the Nyquist entry of each even-length axis
81 at that axis's own position.
82 """
83 kwargs.setdefault("force_mean", True)
84 kwargs.setdefault("execution_type", "expval")
86 coeffs, freqs = cls._fourier_transform(model, mfs=mfs, mts=mts, **kwargs)
88 if not jnp.isclose(jnp.sum(coeffs).imag, 0.0, atol=1.0e-6):
89 raise ValueError(
90 f"Spectrum is not real. Imaginary part of coefficients is:\
91 {jnp.sum(coeffs).imag}"
92 )
94 if trim:
95 # Per-axis Nyquist removal: each frequency axis is trimmed at
96 # its own length.
97 for ax in range(model.n_input_feat):
98 if coeffs.shape[ax] % 2 == 0:
99 nyquist = coeffs.shape[ax] // 2
100 coeffs = np.delete(coeffs, nyquist, axis=ax)
101 freqs[ax] = np.delete(freqs[ax], nyquist)
103 if shift:
104 coeffs = jnp.fft.fftshift(coeffs, axes=list(range(model.n_input_feat)))
105 # per-axis shift: a global fftshift on the ragged list of
106 # per-axis frequency vectors fails for multi-dim input
107 freqs = [np.fft.fftshift(f) for f in freqs]
109 if numerical_cap > 0:
110 # set coeffs below threshold to zero
111 coeffs = jnp.where(
112 jnp.abs(coeffs) < numerical_cap,
113 jnp.zeros_like(coeffs),
114 coeffs,
115 )
117 # Drop frequencies whose coefficients vanish entirely after
118 # capping, so the returned spectrum reflects only the surviving
119 # frequencies. Well-defined only for a single (1-D) frequency
120 # axis; for multi-dim input the rectangular grid is left intact.
121 if model.n_input_feat == 1:
122 if coeffs.ndim == 1:
123 surviving = coeffs != 0
124 else:
125 surviving = jnp.any(coeffs != 0, axis=tuple(range(1, coeffs.ndim)))
126 coeffs = coeffs[surviving]
127 freqs = [freqs[0][surviving]]
129 if len(freqs) == 1:
130 freqs = freqs[0]
132 return coeffs, freqs
134 @classmethod
135 def _fourier_transform(
136 cls, model: Model, mfs: Union[int, List[int]], mts: int, **kwargs: Any
137 ) -> Tuple[jnp.ndarray, List]:
138 # Per-axis oversampling: mfs may be a single integer factor (applied to
139 # every axis) or one per input feature.
140 mfs_axis = np.asarray(mfs)
141 if not np.issubdtype(mfs_axis.dtype, np.integer):
142 raise TypeError(f"mfs factors must be integers, got {mfs}")
143 if mfs_axis.ndim == 0:
144 mfs_axis = np.full(model.n_input_feat, mfs_axis)
145 elif mfs_axis.shape != (model.n_input_feat,):
146 raise ValueError(
147 f"mfs must be an int or one factor per input feature "
148 f"({model.n_input_feat}), got {mfs}"
149 )
151 # Create a frequency vector with as many frequencies as model degrees,
152 # oversampled by mfs
153 n_freqs: jnp.ndarray = jnp.array(
154 [mfs_axis[i] * model.degree[i] for i in range(model.n_input_feat)]
155 )
157 start, stop, step = 0, 2 * mts * jnp.pi, 2 * jnp.pi / n_freqs
158 # Stretch according to the number of frequencies
159 inputs: List = [
160 jnp.arange(start, stop, step[i]) for i in range(model.n_input_feat)
161 ]
163 # Grid in ij/C order: meshgrid(indexing="ij") stacked on the last axis
164 # and flattened row-major, so the first input feature is the slowest
165 # and the last the fastest. This keeps the flat ordering aligned with
166 # the coefficient reshape, the frequency labels and the FFT axes, and
167 # supports per-axis vectors of different lengths (the generic
168 # multi-feature case).
169 nd_inputs = jnp.stack(jnp.meshgrid(*inputs, indexing="ij"), axis=-1).reshape(
170 -1, model.n_input_feat
171 )
173 # Output vector is not necessarily the same length as input.
174 # The leading axes are the flattened frequency grid: reshape to the
175 # per-axis sizes and drop the trailing axis if it has size 1 (e.g. a
176 # single observable). A bare .squeeze() would also collapse size-1
177 # frequency axes and misalign the FFT axes for degree-1 features.
178 outputs = model(inputs=nd_inputs, **kwargs)
179 outputs = outputs.reshape(
180 *[inputs[i].shape[0] for i in range(model.n_input_feat)], -1
181 )
182 if outputs.shape[-1] == 1:
183 outputs = outputs.squeeze(axis=-1)
185 coeffs = jnp.fft.fftn(outputs, axes=list(range(model.n_input_feat)))
187 freqs = [
188 jnp.fft.fftfreq(int(mts * n_freqs[i]), 1 / n_freqs[i])
189 for i in range(model.n_input_feat)
190 ]
192 # Normalize by the frequency-grid size (the batch axis, if any, is
193 # not part of the grid).
194 return (
195 coeffs / math.prod(outputs.shape[0 : model.n_input_feat]),
196 freqs,
197 )
199 @classmethod
200 def get_psd(cls, coeffs: jnp.ndarray) -> jnp.ndarray:
201 """
202 Calculates the power spectral density (PSD) from given Fourier coefficients.
204 Args:
205 coeffs (jnp.ndarray): The Fourier coefficients.
207 Returns:
208 jnp.ndarray: The power spectral density.
209 """
210 # TODO: if we apply trim=True in advance, this will be slightly wrong..
212 def abs2(x):
213 return x.real**2 + x.imag**2
215 scale = 2.0 / (len(coeffs) ** 2)
216 return scale * abs2(coeffs)
218 @classmethod
219 def evaluate_Fourier_series(
220 cls,
221 coefficients: jnp.ndarray,
222 frequencies: jnp.ndarray,
223 inputs: Union[jnp.ndarray, list, float],
224 ) -> float:
225 """
226 Evaluate the function value of a Fourier series at one point.
228 Args:
229 coefficients (jnp.ndarray): Coefficients of the Fourier series.
230 frequencies (jnp.ndarray): Corresponding frequencies.
231 inputs (jnp.ndarray): Point at which to evaluate the function.
232 Returns:
233 float: The function value at the input point.
234 """
235 coefficients = jnp.asarray(coefficients)
237 def flatten_grid(freq_axes):
238 freq_axes = [jnp.asarray(freq) for freq in freq_axes]
239 freq_grid = jnp.stack(jnp.meshgrid(*freq_axes, indexing="ij"), axis=-1)
240 flat_frequencies = freq_grid.reshape(-1, len(freq_axes))
241 flat_coefficients = coefficients.reshape(
242 flat_frequencies.shape[0], *coefficients.shape[len(freq_axes) :]
243 )
244 return flat_coefficients, flat_frequencies
246 if isinstance(frequencies, list):
247 flat_coefficients, flat_frequencies = flatten_grid(frequencies)
248 else:
249 frequencies = jnp.asarray(frequencies)
250 if frequencies.ndim == 1:
251 flat_frequencies = frequencies[:, jnp.newaxis]
252 flat_coefficients = coefficients.reshape(
253 flat_frequencies.shape[0], *coefficients.shape[1:]
254 )
255 else:
256 n_features, n_axis_freqs = frequencies.shape
257 is_axis_frequencies = (
258 coefficients.shape[:n_features] == (n_axis_freqs,) * n_features
259 )
261 if is_axis_frequencies:
262 flat_coefficients, flat_frequencies = flatten_grid(frequencies)
263 else:
264 flat_frequencies = frequencies
265 flat_coefficients = coefficients.reshape(
266 flat_frequencies.shape[0], *coefficients.shape[1:]
267 )
269 inputs = jnp.asarray(inputs)
270 if inputs.ndim == 0:
271 inputs = inputs.reshape(1, 1)
272 elif inputs.ndim == 1:
273 if flat_frequencies.shape[1] == 1:
274 inputs = inputs[:, jnp.newaxis]
275 elif inputs.shape[0] == flat_frequencies.shape[1]:
276 inputs = inputs[jnp.newaxis, :]
277 else:
278 inputs = jnp.repeat(
279 inputs[:, jnp.newaxis], flat_frequencies.shape[1], axis=1
280 )
281 exponents = jnp.exp(1j * (inputs @ flat_frequencies.T))
282 exp = jnp.tensordot(exponents, flat_coefficients, axes=([1], [0]))
284 return jnp.squeeze(jnp.real(exp))
287class FourierTree:
288 """
289 Sine-cosine tree representation for the algorithm by Nemkov et al.
291 Computes the analytical Fourier coefficients/frequencies of a Pauli-Clifford
292 circuit. The symbolic structure of the tree (which Pauli rotations
293 contribute sine/cosine factors to which leaf, and the leaf observables) is
294 built once in NumPy; the parameter-dependent coefficients are then obtained
295 with a small number of vectorised JAX operations, so the result remains
296 jittable / differentiable with respect to the model parameters.
298 The resulting spectrum is the d-dimensional set of frequency vectors,
299 where $d$ is the input dimensionality.
301 **Usage**:
302 ```
303 model = Model(...)
304 tree = FourierTree(model)
305 exp = tree() # expectation value
306 coeff_list, freq_list = tree.get_spectrum()
307 ```
308 """
310 def __init__(self, model: Model):
311 """
312 Tree initialisation, based on the Pauli-Clifford representation of a
313 model.
315 Args:
316 model (Model): The Model, for which to build the tree.
317 """
318 self.model = model
319 self.n_qubits = model.n_qubits
321 # A single (de-batched) parameter set drives the whole tree.
322 self._params = self._single_param_set(model.params)
324 # Canonical Pauli-Clifford structure, recorded once at a fixed base
325 # input. The base value is irrelevant to the structure (it only sets
326 # the rotation angles, not which Pauli words appear).
327 base_inputs = np.ones(model.n_input_feat)
328 operations, observables = self._build_canonical_tape(self._params, base_inputs)
330 self.parameters = [
331 jnp.squeeze(p) for p in PauliCircuit.get_parameters(operations)
332 ]
333 self.n_params = len(self.parameters)
335 # Pauli generators of the (canonical) rotations, as symbolic words.
336 self.pauli_words: List[PauliWord] = [
337 PauliWord.from_operation(op, self.n_qubits) for op in operations
338 ]
340 # Cumulative X/Y support of the rotations[0..k] (for light-cone early
341 # stopping). cumulative_xy[k] is True on every qubit touched by an X/Y
342 # generator in any rotation up to index k.
343 self.cumulative_xy: List[np.ndarray] = []
344 running = np.zeros(self.n_qubits, dtype=bool)
345 for pw in self.pauli_words:
346 running = np.logical_or(running, pw.xy_mask)
347 self.cumulative_xy.append(running.copy())
349 # Observable Pauli words (one tree root each).
350 self.observable_words: List[PauliWord] = [
351 PauliWord.from_operation(obs, self.n_qubits) for obs in observables
352 ]
354 # Identify the input-encoding columns, their feature, and integer
355 # frequency scaling directly from the tape (no per-gate tagging). Sets
356 # ``input_indices``, ``all_input_indices``, ``input_scaling``,
357 # ``var_positions`` and ``features``.
358 self._detect_inputs(base_inputs)
360 # The explicit leaf structure is built lazily: for deep circuits the
361 # number of tree paths explodes combinatorially, while the canonical
362 # form above (and the merged-state support DP) remain cheap.
363 self._structure_built = False
365 def _ensure_structure(self) -> None:
366 """Build the explicit leaf/spectrum structure on first use."""
367 if not self._structure_built:
368 # Symbolic structure: per root (S, C, terms) leaf arrays ...
369 self._build_leaf_arrays()
370 # ... and the parameter-independent frequency/weight structure.
371 self._build_spectrum_structure()
372 self._structure_built = True
374 def _single_param_set(self, params) -> jnp.ndarray:
375 """De-batch the model parameters to the single set the tree describes.
377 Models can carry batched parameters (e.g. after FCC sampling); the tree
378 is defined for one set, so fall back to the first and warn.
379 """
380 params = jnp.asarray(params)
381 if params.ndim > 2 and params.shape[0] > 1:
382 warnings.warn(
383 f"FourierTree supports a single parameter set; using the first "
384 f"of {params.shape[0]} batched parameter sets.",
385 UserWarning,
386 )
387 params = params[0]
388 return params
390 def _build_canonical_tape(self, params, inputs):
391 """Record the circuit and transform it to Pauli-Clifford normal form.
393 Returns the ``(operations, observables)`` of the canonical circuit
394 (see :meth:`PauliCircuit.from_parameterised_circuit`).
395 """
396 params = self._single_param_set(params)
397 inputs = self.model._inputs_validation(inputs)
398 raw_tape = self.model.script.record(params=params, inputs=inputs)
399 _, obs_list = self.model._build_obs()
400 return PauliCircuit.from_parameterised_circuit(
401 raw_tape, observables=obs_list, n_qubits=self.n_qubits
402 )
404 def _canonical_parameters(self, inputs) -> np.ndarray:
405 """Recorded canonical rotation angles (1-D float array) for ``inputs``."""
406 operations, _ = self._build_canonical_tape(self._params, inputs)
407 return np.array(
408 [float(jnp.squeeze(p)) for p in PauliCircuit.get_parameters(operations)]
409 )
411 def _detect_inputs(self, base_inputs: np.ndarray) -> None:
412 r"""Infer the input-encoding columns directly from the tape (tag-free).
414 Each encoding rotation applies an angle :math:`\omega_k\,x_f` that is
415 linear in a single input feature :math:`x_f`, and Clifford commutation
416 only multiplies a rotation generator by :math:`\pm 1`. Every canonical
417 rotation angle is therefore an affine function of the inputs, so
418 perturbing one feature at a time and differencing the recorded angles
419 isolates exactly the columns that depend on it, together with the
420 signed scaling :math:`\omega_k` (rational for diagonal-Hamiltonian
421 encodings such as Golomb).
423 Sets :attr:`input_indices` (``{feature: [columns]}``),
424 :attr:`all_input_indices`, :attr:`input_scaling` (per column, ``1`` for
425 variational columns), :attr:`var_positions`, and :attr:`features`.
427 Raises:
428 NotImplementedError: If a rotation depends on more than one feature
429 (the tree requires single-feature encodings).
430 """
431 tol = 1e-6
432 d = self.model.n_input_feat
433 base = np.asarray(base_inputs, dtype=float)
434 p_base = np.array([float(p) for p in self.parameters])
436 # response[f, k] = d(angle_k) / d(x_f), the linear response of column k.
437 response = np.zeros((d, self.n_params))
438 for f in range(d):
439 step = base.copy()
440 step[f] += 1.0
441 response[f] = self._canonical_parameters(step) - p_base
443 input_indices: Dict[int, list] = defaultdict(list)
444 all_input_indices: List[int] = []
445 scaling = np.ones(self.n_params, dtype=np.float64)
446 for k in range(self.n_params):
447 feats = np.flatnonzero(np.abs(response[:, k]) > tol)
448 if feats.size == 0:
449 continue # variational column
450 if feats.size > 1:
451 raise NotImplementedError(
452 f"Rotation {k} depends on multiple input features "
453 f"{feats.tolist()}; the Fourier tree requires each encoding "
454 "rotation to be linear in a single feature."
455 )
456 f = int(feats[0])
457 omega = float(response[f, k])
458 # Scalings may be rational (e.g. diagonal-Hamiltonian / Golomb
459 # encodings, whose per-Pauli-string scalings are dyadic rationals);
460 # the integer-frequency model spectrum is recovered downstream.
461 input_indices[f].append(k)
462 all_input_indices.append(k)
463 scaling[k] = omega
465 self.input_indices = input_indices
466 self.all_input_indices = all_input_indices
467 self.input_scaling = scaling
468 input_set = set(all_input_indices)
469 self.var_positions = np.array(
470 [i for i in range(self.n_params) if i not in input_set], dtype=np.int64
471 )
472 # Ordered list of input feature keys (d-dimensional spectrum).
473 self.features = sorted(input_indices.keys())
475 # Symbolic tree construction (NumPy)
476 def _build_leaf_arrays(self) -> None:
477 """Collect the tree leaves for every root into integer count matrices.
479 For each root (observable) this produces:
480 - ``S``: (n_leaves, n_params) sine-factor counts per parameter,
481 - ``C``: (n_leaves, n_params) cosine-factor counts per parameter,
482 - ``terms``: (n_leaves,) complex leaf constants ``<0|O_leaf|0>``.
483 """
484 self.leaf_arrays: List[Tuple[np.ndarray, np.ndarray, np.ndarray]] = []
485 for obs_word in self.observable_words:
486 leaves: List[Tuple[np.ndarray, np.ndarray, complex]] = []
487 zeros = np.zeros(self.n_params, dtype=np.int64)
488 self._collect_leaves(
489 obs_word, self.n_params - 1, zeros.copy(), zeros.copy(), leaves
490 )
491 if leaves:
492 S = np.stack([leaf[0] for leaf in leaves])
493 C = np.stack([leaf[1] for leaf in leaves])
494 terms = np.array([leaf[2] for leaf in leaves], dtype=np.complex128)
495 else:
496 S = np.zeros((0, self.n_params), dtype=np.int64)
497 C = np.zeros((0, self.n_params), dtype=np.int64)
498 terms = np.zeros(0, dtype=np.complex128)
499 self.leaf_arrays.append((S, C, terms))
501 def _collect_leaves(
502 self,
503 observable: PauliWord,
504 pauli_idx: int,
505 sin_counts: np.ndarray,
506 cos_counts: np.ndarray,
507 leaves: List[Tuple[np.ndarray, np.ndarray, complex]],
508 ) -> None:
509 """Recursively enumerate the leaves of the coefficient tree.
511 The incoming sine/cosine factor (from the parent edge) is already
512 accumulated into ``sin_counts``/``cos_counts``. This fuses the tree
513 construction and leaf traversal of the original implementation into a
514 single NumPy pass (no per-node JAX scatter updates).
515 """
516 if self._early_stopping_possible(pauli_idx, observable):
517 return
519 # Skip trailing Pauli rotations that commute with the observable.
520 while pauli_idx >= 0:
521 last = self.pauli_words[pauli_idx]
522 if not observable.commutes_with(last):
523 break
524 pauli_idx -= 1
525 else: # leaf reached
526 term = observable.zero_expectation()
527 if term != 0:
528 leaves.append((sin_counts, cos_counts, term))
529 return
531 last = self.pauli_words[pauli_idx]
533 # Left child: cosine factor for this parameter, same observable.
534 cos_left = cos_counts.copy()
535 cos_left[pauli_idx] += 1
536 self._collect_leaves(
537 observable, pauli_idx - 1, sin_counts.copy(), cos_left, leaves
538 )
540 # Right child: sine factor, observable becomes P . O.
541 sin_right = sin_counts.copy()
542 sin_right[pauli_idx] += 1
543 self._collect_leaves(
544 last.compose(observable),
545 pauli_idx - 1,
546 sin_right,
547 cos_counts.copy(),
548 leaves,
549 )
551 def _early_stopping_possible(self, pauli_idx: int, observable: PauliWord) -> bool:
552 """Whether a node can be discarded (all reachable expectations vanish).
554 Mirrors the criterion of Nemkov et al. (light cone): a qubit on which
555 the observable carries an X/Y must be covered by an X/Y generator of
556 some remaining rotation (rotations[0..pauli_idx]); otherwise that X/Y can
557 never be rotated into a diagonal term and the whole node contributes
558 zero. Equivalently, the node survives iff every qubit is either I/Z in
559 the observable or covered by the cumulative rotation X/Y support.
560 """
561 obs_iz = np.logical_not(observable.xy_mask)
562 combined = np.logical_or(obs_iz, self.cumulative_xy[pauli_idx]).all()
563 return not bool(combined)
565 # Frequency / weight structure (NumPy, parameter independent)
566 def _build_spectrum_structure(self) -> None:
567 """Build, per root, the frequency vectors and the (n_freq, n_leaves)
568 weight matrix ``W`` such that ``coeffs = W @ (terms * variational)``.
569 """
570 self.freqs_per_root: List[np.ndarray] = []
571 self.weights_per_root: List[np.ndarray] = []
572 d = len(self.features)
574 for S, C, _ in self.leaf_arrays:
575 n_leaves = S.shape[0]
576 freq_to_col: Dict[tuple, np.ndarray] = defaultdict(
577 lambda: np.zeros(n_leaves, dtype=np.complex128)
578 )
579 for leaf in range(n_leaves):
580 # One expansion factor per *active* input column, each carrying
581 # its feature axis and integer frequency scaling. Per leaf a
582 # column contributes at most one sin/cos factor (square-free),
583 # but different columns of the same feature may carry different
584 # scalings, so they are expanded individually and convolved
585 # rather than aggregating counts (which would assume a common
586 # unit scaling).
587 col_factors: List[List[Tuple[int, float, float]]] = []
588 half_exp = 0
589 for axis, feat in enumerate(self.features):
590 for k in self.input_indices[feat]:
591 s = int(S[leaf, k])
592 c = int(C[leaf, k])
593 if s == 0 and c == 0:
594 continue
595 half_exp += s + c
596 w_k = float(self.input_scaling[k])
597 col_factors.append(
598 [
599 (axis, o * w_k, wt)
600 for o, wt in self._binomial_terms(s, c)
601 ]
602 )
603 half = 0.5**half_exp
605 if d == 0:
606 freq_to_col[(0,)][leaf] += half
607 continue
609 if not col_factors:
610 freq_to_col[(0,) * d][leaf] += half
611 continue
613 for combo in itertools.product(*col_factors):
614 omega = [0.0] * d
615 weight = half
616 for axis, o, wt in combo:
617 omega[axis] += o
618 weight *= wt
619 # Snap to a tolerance so dyadic-rational contributions that
620 # are numerically equal share a single frequency key.
621 key = tuple(round(v, 9) for v in omega)
622 freq_to_col[key][leaf] += weight
624 if freq_to_col:
625 omegas = sorted(freq_to_col.keys())
626 W = np.stack([freq_to_col[o] for o in omegas]) # (n_freq, n_leaves)
627 freqs = np.array(omegas, dtype=float) # (n_freq, d)
628 # Diagonal-Hamiltonian (Golomb) encodings produce rational
629 # per-rotation scalings but integer model frequencies; snap to
630 # int64 when every entry is integral so integer-encoding
631 # consumers are unchanged, otherwise keep the rational floats.
632 rounded = np.rint(freqs)
633 if np.all(np.abs(freqs - rounded) < 1e-6):
634 freqs = rounded.astype(np.int64)
635 else:
636 freqs = np.zeros((1, max(d, 1)), dtype=np.int64)
637 W = np.zeros((1, n_leaves), dtype=np.complex128)
639 # Collapse to 1-D frequency array for the single-feature case.
640 if freqs.shape[1] == 1:
641 freqs = freqs[:, 0]
642 self.freqs_per_root.append(freqs)
643 # Keep W in NumPy complex128: its entries are dyadic rationals
644 # (binomial weights x 0.5^k x i^m), which are exact in float64 --
645 # this allows exact symbolic zero-tests in get_exact_support.
646 self.weights_per_root.append(W)
648 @staticmethod
649 def _binomial_terms(s: int, c: int) -> List[Tuple[int, float]]:
650 """Expand ``cos^c (i sin)^s`` in ``e^{i omega x}`` (without the 0.5 factor).
652 Returns a list of ``(omega, weight)`` with
653 ``omega = 2a + 2b - s - c`` and ``weight = C(s,a) C(c,b) (-1)^{s-a}``.
654 """
655 terms = []
656 for a in range(s + 1):
657 for b in range(c + 1):
658 weight = math.comb(s, a) * math.comb(c, b) * (-1) ** (s - a)
659 terms.append((2 * a + 2 * b - s - c, float(weight)))
660 return terms
662 # Vectorised numeric evaluation (JAX)
663 @staticmethod
664 def _safe_pow(base: jnp.ndarray, exp: jnp.ndarray) -> jnp.ndarray:
665 """Elementwise ``base ** exp`` for real base and non-negative integer
666 exponents, correct for negative bases (avoids ``log`` of negatives).
668 Args:
669 base: real array of shape ``(n,)``.
670 exp: integer array of shape ``(n_leaves, n)``.
671 """
672 mag = jnp.abs(base)[None, :] ** exp
673 sign = jnp.where(exp % 2 == 0, 1.0, jnp.sign(base)[None, :])
674 return sign * mag
676 _I_POW = None # set lazily to jnp.array([1, 1j, -1, -1j])
678 def _leaf_factors(
679 self, S: np.ndarray, C: np.ndarray, columns: np.ndarray
680 ) -> jnp.ndarray:
681 """Per-leaf product ``prod_i cos(theta_i)^{C} (i sin(theta_i))^{S}`` over
682 the given parameter ``columns`` (vectorised over leaves).
683 """
684 if FourierTree._I_POW is None:
685 FourierTree._I_POW = jnp.array([1, 1j, -1, -1j])
687 if S.shape[0] == 0:
688 return jnp.zeros(0, dtype=jnp.complex64)
690 theta = jnp.stack([self.parameters[i] for i in columns])
691 S_sub = jnp.asarray(S[:, columns])
692 C_sub = jnp.asarray(C[:, columns])
694 cos_part = self._safe_pow(jnp.cos(theta), C_sub)
695 sin_mag = self._safe_pow(jnp.sin(theta), S_sub)
696 i_part = FourierTree._I_POW[S_sub % 4]
697 return jnp.prod(cos_part * sin_mag * i_part, axis=1)
699 def __call__(
700 self,
701 params: Optional[jnp.ndarray] = None,
702 inputs: Optional[jnp.ndarray] = None,
703 **kwargs,
704 ) -> jnp.ndarray:
705 """
706 Evaluate the expectation value(s) of the model's observables via the
707 sine-cosine tree (equivalent to the circuit expectation).
709 Args:
710 params (Optional[jnp.ndarray]): Model parameters. Defaults to the
711 model's parameters.
712 inputs (Optional[jnp.ndarray]): Inputs to the circuit. Defaults to 1.
714 Returns:
715 jnp.ndarray: Expectation value per observable (or their mean if
716 ``force_mean`` is set).
718 Raises:
719 NotImplementedError: For execution types other than "expval" or when
720 noise is requested.
721 """
722 params = (
723 self.model._params_validation(params)
724 if params is not None
725 else self.model.params
726 )
727 inputs = (
728 self.model._inputs_validation(inputs)
729 if inputs is not None
730 else self.model._inputs_validation(1.0)
731 )
733 if kwargs.get("execution_type", "expval") != "expval":
734 raise NotImplementedError(
735 f'Currently, only "expval" execution type is supported when '
736 f"building FourierTree. Got {kwargs.get('execution_type', 'expval')}."
737 )
738 if kwargs.get("noise_params", None) is not None:
739 raise NotImplementedError(
740 "Currently, noise is not supported when building FourierTree."
741 )
743 # Re-derive the (canonical) parameter values for the requested inputs;
744 # the tree structure (leaf arrays) is unchanged.
745 operations, _ = self._build_canonical_tape(params, inputs)
746 self.parameters = [
747 jnp.squeeze(p) for p in PauliCircuit.get_parameters(operations)
748 ]
750 self._ensure_structure()
751 all_columns = np.arange(self.n_params, dtype=np.int64)
752 results = []
753 for S, C, terms in self.leaf_arrays:
754 factors = self._leaf_factors(S, C, all_columns)
755 results.append(jnp.real(jnp.sum(jnp.asarray(terms) * factors)))
756 results = jnp.array(results)
758 if kwargs.get("force_mean", False):
759 return jnp.mean(results)
760 return results
762 def get_spectrum(
763 self, force_mean: bool = False
764 ) -> Tuple[List[jnp.ndarray], List[jnp.ndarray]]:
765 """
766 Compute the Fourier spectrum (coefficients and frequencies) of the tree.
768 Args:
769 force_mean (bool, optional): Average the coefficients over all
770 observables (roots). Defaults to False.
772 Returns:
773 Tuple[List[jnp.ndarray], List[jnp.ndarray]]:
774 - List of coefficients, one entry per observable (root).
775 - List of corresponding frequencies, one entry per root.
776 When ``force_mean`` is set, both lists have a single entry.
777 """
778 self._ensure_structure()
779 per_root_coeffs: List[jnp.ndarray] = []
780 for (S, C, terms), W in zip(self.leaf_arrays, self.weights_per_root):
781 leaf_const = jnp.asarray(terms) * self._leaf_factors(
782 S, C, self.var_positions
783 )
784 per_root_coeffs.append(jnp.asarray(W) @ leaf_const)
786 return self._combine_roots(per_root_coeffs, self.freqs_per_root, force_mean)
788 def get_exact_support(self, method: str = "tree") -> List[np.ndarray]:
789 r"""Symbolically derive the exact frequency support (no sampling).
791 A frequency :math:`\omega` belongs to the exact spectrum iff its
792 coefficient :math:`c_\omega(\theta) = \sum_l W_{\omega l}\,
793 \text{term}_l\, v_l(\theta)` is not identically zero in the
794 variational parameters :math:`\theta`.
796 Two methods are available:
798 - ``"tree"`` (default, fully exact): enumerates the explicit tree
799 leaves. Because the branch index strictly decreases along every tree
800 path, each parameter contributes **at most one** sine *or* cosine
801 factor per leaf (:math:`S_{li}, C_{li} \in \{0, 1\}`). Every
802 variational leaf factor :math:`v_l` is therefore a *square-free*
803 monomial over :math:`\{1, \cos\theta_i, i\sin\theta_i\}`, and
804 monomials with distinct signatures are linearly independent functions
805 (no :math:`\cos^2 + \sin^2` identities can arise without squares).
806 Hence
808 .. math::
809 c_\omega \equiv 0 \iff \sum_{l \in g} W_{\omega l}\,\text{term}_l
810 = 0 \quad \text{for every signature group } g.
812 Since all involved quantities are dyadic rationals times
813 :math:`\{\pm 1, \pm i\}`, the group sums are exact in float64 and the
814 zero-test is exact. The number of leaves can however grow
815 exponentially with circuit depth.
817 - ``"dp"`` (scalable): merges tree nodes with identical
818 ``(rotation index, observable)`` — at most ``n_params * 4^n_qubits``
819 states — and tracks, per state, the achievable per-feature sine/cosine
820 count vectors ``(s_f, c_f)`` as a mixed-radix bitmask. Each feature's
821 support is the union of the (exact) expansion supports of
822 :math:`\cos^{c_f} x_f\, (i \sin x_f)^{s_f}`, and the model support is
823 their Cartesian product across features. This is exact per tree path
824 (including interior zero coefficients of the expansions), but unlike
825 ``"tree"`` it cannot detect coefficients that cancel identically
826 *across* paths with identical variational signatures (e.g. directly
827 repeated encodings). It therefore yields a tight superset in such
828 corner cases. Supports any number of input features, but requires
829 unit-magnitude input scaling: per-gate :math:`|\omega| \neq 1`
830 scalings (e.g. Golomb encodings) are rejected — use ``"tree"``.
832 Args:
833 method (str): ``"tree"`` (fully exact) or ``"dp"`` (scalable).
835 Returns:
836 List[np.ndarray]: For each observable (root), the frequency vectors
837 with not-identically-zero coefficient — shape ``(n_freq,)`` for a
838 single input feature, ``(n_freq, n_features)`` otherwise.
839 """
840 if method == "dp":
841 return self._support_dp()
842 if method != "tree":
843 raise ValueError(f"Unknown method '{method}'. Use 'tree' or 'dp'.")
845 self._ensure_structure()
846 supports = []
847 for (S, C, terms), W, freqs in zip(
848 self.leaf_arrays, self.weights_per_root, self.freqs_per_root
849 ):
850 freqs = np.asarray(freqs)
851 n_leaves = S.shape[0]
852 if n_leaves == 0:
853 supports.append(freqs[:0])
854 continue
856 # Group leaves by their variational sine/cosine signature.
857 signature = np.hstack([S[:, self.var_positions], C[:, self.var_positions]])
858 _, groups = np.unique(signature, axis=0, return_inverse=True)
859 n_groups = int(groups.max()) + 1
861 # Per-group sums of W[omega, l] * term_l, accumulated exactly.
862 contrib = (W * terms[None, :]).T # (n_leaves, n_freq)
863 group_sums = np.zeros((n_groups, W.shape[0]), dtype=np.complex128)
864 np.add.at(group_sums, groups, contrib)
866 mask = (np.abs(group_sums) > 1e-12).any(axis=0) # (n_freq,)
867 supports.append(freqs[mask])
868 return supports
870 def _support_dp(self) -> List[np.ndarray]:
871 """Merged-state dynamic program for the frequency support.
873 Instead of enumerating all (worst-case exponentially many) tree paths,
874 nodes are merged on ``(rotation index, bare observable)``. Each state
875 stores the set of achievable per-axis count vectors
876 ``(c_0, s_0, ..., c_{d-1}, s_{d-1})`` as a mixed-radix bitmask (one
877 digit per feature sine/cosine count), so transitions are O(1) big-int
878 operations. See :meth:`get_exact_support` for semantics and
879 limitations.
880 """
881 # Count aggregation is valid as long as every input rotation has
882 # unit-magnitude scaling. A Clifford-commutation sign flip (scaling -1)
883 # leaves the frequency support unchanged -- cos is even and sin odd, so
884 # the sign only flips the coefficient, which the support ignores -- but a
885 # genuine per-gate scaling (|omega| != 1, e.g. Golomb / heterogeneous
886 # frequencies) cannot be represented by sin/cos counts.
887 if self.all_input_indices and np.any(
888 np.abs(self.input_scaling[self.all_input_indices]) != 1
889 ):
890 raise NotImplementedError(
891 "The 'dp' support method does not support non-unit input "
892 "frequency scaling (it aggregates sin/cos counts and cannot "
893 "represent per-gate scalings); use method='tree'."
894 )
896 n = self.n_qubits
897 d = len(self.features)
898 # Pack the achievable per-axis sine/cosine counts into one big-int as a
899 # mixed-radix bitmask over (c_0, s_0, ..., c_{d-1}, s_{d-1}). Axis a's
900 # counts range 0..n_a (n_a input rotations encode feature a), so each
901 # digit has radix n_a + 1; a left-shift by a digit's place value
902 # increments that count, OR is set-union. (For d == 1 this reduces to
903 # shift_c = 1, shift_s = n_inp + 1, i.e. the flat (s, c) layout.)
904 ranges = [len(self.input_indices[self.features[a]]) + 1 for a in range(d)]
905 shift_c = [0] * d
906 shift_s = [0] * d
907 place = 1
908 for a in range(d):
909 shift_c[a] = place
910 place *= ranges[a]
911 shift_s[a] = place
912 place *= ranges[a]
913 # Feature axis of each input rotation (-1 if variational), in the same
914 # enumerate(self.features) order the tree method uses for its axes.
915 axis_of_col = np.full(self.n_params, -1, dtype=np.int64)
916 for a in range(d):
917 for k in self.input_indices[self.features[a]]:
918 axis_of_col[k] = a
920 def encode(word: PauliWord) -> Tuple[int, int]:
921 x = z = 0
922 for q in range(n):
923 x |= int(word.x[q]) << q
924 z |= int(word.z[q]) << q
925 return x, z
927 paulis = [encode(w) for w in self.pauli_words]
928 cum_xy = []
929 running = 0
930 for xp, _ in paulis:
931 running |= xp
932 cum_xy.append(running)
934 def parity(v: int) -> int:
935 return bin(v).count("1") & 1
937 def dp(idx: int, xo: int, zo: int, memo: dict) -> int:
938 # Light-cone early stopping (cf. _early_stopping_possible).
939 if idx >= 0 and (xo & ~cum_xy[idx]):
940 return 0
941 # Skip trailing rotations that commute with the observable.
942 while idx >= 0:
943 xp, zp = paulis[idx]
944 if parity(xo & zp) ^ parity(zo & xp):
945 break
946 idx -= 1
947 else: # leaf: counts (s=0, c=0) iff the observable is diagonal
948 return 1 if xo == 0 else 0
949 key = (idx, xo, zo)
950 hit = memo.get(key)
951 if hit is not None:
952 return hit
953 xp, zp = paulis[idx]
954 cos_child = dp(idx - 1, xo, zo, memo)
955 sin_child = dp(idx - 1, xo ^ xp, zo ^ zp, memo)
956 a = int(axis_of_col[idx])
957 if a >= 0:
958 # Active input gate: cosine increments c_a, sine increments s_a.
959 val = (cos_child << shift_c[a]) | (sin_child << shift_s[a])
960 else:
961 val = cos_child | sin_child
962 memo[key] = val
963 return val
965 # Recursion depth is bounded by the number of rotations.
966 old_limit = sys.getrecursionlimit()
967 sys.setrecursionlimit(max(old_limit, self.n_params + 1000))
968 try:
969 supports = []
970 for obs in self.observable_words:
971 memo: dict = {}
972 xo, zo = encode(obs)
973 mask = dp(self.n_params - 1, xo, zo, memo)
974 supports.append(self._dp_mask_to_support(mask, d, ranges))
975 finally:
976 sys.setrecursionlimit(old_limit)
977 return supports
979 def _dp_mask_to_support(self, mask: int, d: int, ranges: List[int]) -> np.ndarray:
980 """Decode a count bitmask (see :meth:`_support_dp`) into a frequency
981 support. Each set bit is a per-axis count vector ``(c_a, s_a)``; the
982 per-axis expansion supports are combined across axes (Cartesian
983 product) and unioned over all bits.
985 Returns an ``(n_freq, d)`` array, collapsed to 1-D for ``d <= 1`` to
986 match :meth:`get_exact_support` with ``method="tree"`` (``d == 0`` keeps
987 only the DC term).
988 """
989 tupleset: set = set()
990 while mask:
991 bit = mask & -mask
992 i = bit.bit_length() - 1
993 rem = i
994 axis_freqs = []
995 for a in range(d):
996 c_a = rem % ranges[a]
997 rem //= ranges[a]
998 s_a = rem % ranges[a]
999 rem //= ranges[a]
1000 axis_freqs.append(sorted(self._expansion_support(s_a, c_a)))
1001 tupleset.update(itertools.product(*axis_freqs))
1002 mask ^= bit
1004 if d >= 2:
1005 if not tupleset:
1006 return np.empty((0, d), dtype=np.int64)
1007 return np.array(sorted(tupleset), dtype=np.int64)
1008 # d in {0, 1}: collapse to a 1-D frequency array.
1009 flat = sorted(t[0] for t in tupleset) if d == 1 else ([0] if tupleset else [])
1010 return np.array(flat, dtype=np.int64)
1012 @staticmethod
1013 @lru_cache(maxsize=None)
1014 def _expansion_support(s: int, c: int) -> frozenset:
1015 r"""Frequencies with non-zero coefficient in :math:`\cos^c x (i\sin x)^s`.
1017 Computed exactly with integer arithmetic via the polynomial
1018 :math:`(t - 1)^s (t + 1)^c` (with :math:`t = e^{2ix}` up to a shift);
1019 interior coefficients can vanish, e.g. :math:`\cos x \sin x` only
1020 contains :math:`\pm 2`.
1021 """
1022 coeffs = [1]
1023 for _ in range(s): # multiply by (t - 1)
1024 new = [0] * (len(coeffs) + 1)
1025 for i, a in enumerate(coeffs):
1026 new[i + 1] += a
1027 new[i] -= a
1028 coeffs = new
1029 for _ in range(c): # multiply by (t + 1)
1030 new = [0] * (len(coeffs) + 1)
1031 for i, a in enumerate(coeffs):
1032 new[i + 1] += a
1033 new[i] += a
1034 coeffs = new
1035 m = s + c
1036 return frozenset(2 * k - m for k, a in enumerate(coeffs) if a != 0)
1038 def _combine_roots(
1039 self,
1040 per_root_coeffs: List[jnp.ndarray],
1041 per_root_freqs: List[np.ndarray],
1042 force_mean: bool,
1043 ) -> Tuple[List[jnp.ndarray], List[jnp.ndarray]]:
1044 """Assemble the per-root spectra, optionally averaging over roots."""
1045 if not force_mean:
1046 coefficients = [jnp.asarray(c) for c in per_root_coeffs]
1047 frequencies = [jnp.asarray(f) for f in per_root_freqs]
1048 return coefficients, frequencies
1050 # Average over roots on the union of all frequency vectors. Keys are
1051 # snapped to a tolerance so rational frequencies dedup robustly.
1052 accum: Dict[tuple, complex] = defaultdict(complex)
1053 for coeffs, freqs in zip(per_root_coeffs, per_root_freqs):
1054 freqs_np = np.asarray(freqs)
1055 for k in range(freqs_np.shape[0]):
1056 key = (
1057 (round(float(freqs_np[k]), 9),)
1058 if freqs_np.ndim == 1
1059 else tuple(round(float(v), 9) for v in freqs_np[k])
1060 )
1061 accum[key] += complex(coeffs[k])
1062 n_roots = max(len(per_root_coeffs), 1)
1063 keys = sorted(accum.keys())
1064 mean_coeffs = jnp.array([accum[k] / n_roots for k in keys])
1065 freq_arr = np.array(keys, dtype=float)
1066 rounded = np.rint(freq_arr)
1067 if np.all(np.abs(freq_arr - rounded) < 1e-6):
1068 freq_arr = rounded.astype(np.int64)
1069 if freq_arr.shape[1] == 1:
1070 freq_arr = freq_arr[:, 0]
1071 return [mean_coeffs], [jnp.asarray(freq_arr)]
1074class FCC:
1075 @classmethod
1076 def get_fcc(
1077 cls,
1078 model: Model,
1079 n_samples: int,
1080 random_key: Optional[random.PRNGKey] = None,
1081 method: Optional[str] = "pearson",
1082 scale: Optional[bool] = False,
1083 weight: Optional[bool] = False,
1084 trim_redundant: Optional[bool] = True,
1085 **kwargs,
1086 ) -> float:
1087 """
1088 Shortcut method to get just the FCC.
1089 This includes
1090 1. What is done in `get_fourier_fingerprint`:
1091 1. Calculating the coefficients (using `n_samples`)
1092 2. Correlating the result from 1) using `method`
1093 3. Weighting the correlation matrix (if `weight` is True)
1094 4. Remove redundancies
1095 2. What is done in `calculate_fcc`:
1096 1. Absolute of the fingerprint
1097 2. Average
1099 Args:
1100 model (Model): The QFM model
1101 n_samples (int): Number of samples to calculate average of coefficients
1102 random_key (Optional[random.PRNGKey]): JAX random key for parameter
1103 initialization. If None, uses the model's internal random key.
1104 method (Optional[str], optional): Correlation method. Supported values are
1105 "pearson", "complex_pearson", "spearman", and "covariance".
1106 Defaults to "pearson".
1107 scale (Optional[bool], optional): Whether to scale the number of samples.
1108 Defaults to False.
1109 weight (Optional[bool], optional): Whether to weight the correlation matrix.
1110 Defaults to False.
1111 trim_redundant (Optional[bool], optional): Whether to remove redundant
1112 correlations. Defaults to False.
1113 **kwargs (Any): Additional keyword arguments for the model function.
1115 Returns:
1116 float: The FCC
1117 """
1119 # Memory-efficient fast path
1120 if trim_redundant and not weight:
1121 _, coeffs, freqs = cls._calculate_coefficients(
1122 model, n_samples, random_key, scale, **kwargs
1123 )
1124 pos_idx = cls._calculate_mask(freqs)
1125 coeffs_flat = coeffs.reshape(-1, coeffs.shape[-1])
1126 coeffs_sub = coeffs_flat[pos_idx]
1128 fp = cls._correlate(coeffs_sub.transpose(), method=method)
1129 abs_fp = jnp.abs(fp)
1130 diag = jnp.abs(jnp.diagonal(fp))
1132 total_sum = jnp.nansum(abs_fp)
1133 total_count = jnp.sum(jnp.isfinite(abs_fp))
1134 diag_sum = jnp.nansum(diag)
1135 diag_count = jnp.sum(jnp.isfinite(diag))
1137 lower_sum = (total_sum - diag_sum) / 2.0
1138 lower_count = (total_count - diag_count) / 2.0
1139 return lower_sum / lower_count
1141 fourier_fingerprint, _, _ = cls.get_fourier_fingerprint(
1142 model,
1143 n_samples,
1144 random_key,
1145 method,
1146 scale,
1147 weight,
1148 trim_redundant=trim_redundant,
1149 **kwargs,
1150 )
1152 return cls.calculate_fcc(fourier_fingerprint)
1154 @classmethod
1155 def get_fourier_fingerprint(
1156 cls,
1157 model: Model,
1158 n_samples: int,
1159 random_key: Optional[random.PRNGKey] = None,
1160 method: Optional[str] = "pearson",
1161 scale: Optional[bool] = False,
1162 weight: Optional[bool] = False,
1163 trim_redundant: Optional[bool] = True,
1164 nan_to_one: Optional[bool] = False,
1165 **kwargs: Any,
1166 ) -> Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]:
1167 """
1168 Shortcut method to get just the fourier fingerprint.
1169 This includes
1170 1. Calculating the coefficients (using `n_samples`)
1171 2. Correlating the result from 1) using `method`
1172 3. Weighting the correlation matrix (if `weight` is True)
1173 4. Remove redundancies (if `trim_redundant` is True)
1175 Args:
1176 model (Model): The QFM model
1177 n_samples (int): Number of samples to calculate average of coefficients
1178 random_key (Optional[random.PRNGKey]): JAX random key for parameter
1179 initialization. If None, uses the model's internal random key.
1180 method (Optional[str], optional): Correlation method. Supported values are
1181 "pearson", "complex_pearson", "spearman", and "covariance".
1182 Defaults to "pearson".
1183 scale (Optional[bool], optional): Whether to scale the number of samples.
1184 Defaults to False.
1185 weight (Optional[bool], optional): Whether to weight the correlation matrix.
1186 Defaults to False.
1187 trim_redundant (Optional[bool], optional): Whether to remove redundant
1188 correlations. Defaults to True.
1189 nan_to_one (Optional[bool], optional): Whether to set nan to 1.
1190 Defaults to False.
1191 **kwargs: Additional keyword arguments for the model function.
1193 Returns:
1194 Tuple[jnp.ndarray, jnp.ndarray, jnp.ndarray]: The fourier
1195 fingerprint, the corresponding frequency indices and the
1196 corresponding coefficients. If `trim_redundant` is True the
1197 frequencies are returned as a `(row_freqs, col_freqs)` tuple that
1198 labels the two (redundancy-trimmed) matrix axes and the
1199 coefficients as a matching `(row_coeffs, col_coeffs)` tuple whose
1200 rows align with those frequencies; otherwise the frequencies as
1201 given by `Coefficients.get_spectrum` (a 1-D vector for one input
1202 feature, a list of per-axis vectors otherwise) and the full
1203 coefficient array are returned.
1204 """
1205 _, coeffs, freqs = cls._calculate_coefficients(
1206 model, n_samples, random_key, scale, **kwargs
1207 )
1209 # Memory-efficient fast path
1210 if trim_redundant and not weight:
1211 pos_idx = cls._calculate_mask(freqs)
1212 pos_freqs = cls._flat_frequencies(freqs)[pos_idx]
1214 # Flatten all frequency axes; the last axis is the sample
1215 # axis. `_calculate_mask` returns flat indices in C order,
1216 # matching this reshape.
1217 coeffs_flat = coeffs.reshape(-1, coeffs.shape[-1])
1218 coeffs_sub = coeffs_flat[pos_idx]
1220 fourier_fingerprint = cls._correlate(coeffs_sub.transpose(), method=method)
1222 if nan_to_one:
1223 fourier_fingerprint = jnp.where(
1224 jnp.isnan(fourier_fingerprint), 1.0, fourier_fingerprint
1225 )
1227 M = fourier_fingerprint.shape[0]
1228 lower_tri_mask = jnp.tri(M, k=-1, dtype=bool)
1229 fourier_fingerprint = jnp.where(
1230 lower_tri_mask, fourier_fingerprint, jnp.nan
1231 )
1233 row_mask = jnp.any(jnp.isfinite(fourier_fingerprint), axis=1)
1234 col_mask = jnp.any(jnp.isfinite(fourier_fingerprint), axis=0)
1235 fourier_fingerprint = fourier_fingerprint[row_mask][:, col_mask]
1237 return (
1238 fourier_fingerprint,
1239 (pos_freqs[row_mask], pos_freqs[col_mask]),
1240 (coeffs_sub[row_mask], coeffs_sub[col_mask]),
1241 )
1243 # Flatten in C order, like the fast path, so `_calculate_mask` indices
1244 # address the matching rows/cols.
1245 fourier_fingerprint = cls._correlate(
1246 coeffs.reshape(-1, coeffs.shape[-1]).transpose(), method=method
1247 )
1249 if nan_to_one:
1250 # set nan to 1
1251 fourier_fingerprint[jnp.isnan(fourier_fingerprint)] = 1.0
1253 # perform weighting if requested
1254 fourier_fingerprint = (
1255 cls._weighting_mean(fourier_fingerprint, coeffs)
1256 if weight
1257 else fourier_fingerprint
1258 )
1260 if trim_redundant:
1261 pos_idx = cls._calculate_mask(freqs)
1262 pos_freqs = cls._flat_frequencies(freqs)[pos_idx]
1263 coeffs_sub = coeffs.reshape(-1, coeffs.shape[-1])[pos_idx]
1265 # restrict to the positive-frequency sub-block (M x M with
1266 # M = number of non-negative flat-frequencies) instead of
1267 # building a full N x N mask. This avoids the O(N^2) float
1268 fourier_fingerprint = fourier_fingerprint[pos_idx][:, pos_idx]
1270 # keep only the strict lower triangle; the rest -> nan
1271 M = fourier_fingerprint.shape[0]
1272 lower_tri_mask = jnp.tri(M, k=-1, dtype=bool)
1273 fourier_fingerprint = jnp.where(
1274 lower_tri_mask, fourier_fingerprint, jnp.nan
1275 )
1277 row_mask = jnp.any(jnp.isfinite(fourier_fingerprint), axis=1)
1278 col_mask = jnp.any(jnp.isfinite(fourier_fingerprint), axis=0)
1280 fourier_fingerprint = fourier_fingerprint[row_mask][:, col_mask]
1282 return (
1283 fourier_fingerprint,
1284 (pos_freqs[row_mask], pos_freqs[col_mask]),
1285 (coeffs_sub[row_mask], coeffs_sub[col_mask]),
1286 )
1288 return fourier_fingerprint, freqs, coeffs
1290 @classmethod
1291 def calculate_fcc(
1292 cls,
1293 fourier_fingerprint: jnp.ndarray,
1294 ) -> float:
1295 """
1296 Method to calculate the FCC based on an existing correlation matrix.
1297 Calculate absolute and then the average over this matrix.
1298 The Fingerprint can be obtained via `get_fourier_fingerprint`
1300 Args:
1301 fourier_fingerprint (jnp.ndarray): Correlation matrix of coefficients
1302 Returns:
1303 float: The FCC
1304 """
1305 # apply the mask on the fingerprint
1306 return jnp.nanmean(jnp.abs(fourier_fingerprint))
1308 @staticmethod
1309 def _per_axis_frequencies(
1310 freqs: Union[jnp.ndarray, List[jnp.ndarray]],
1311 ) -> List[jnp.ndarray]:
1312 """
1313 Normalize a frequency container into a list of per-axis frequency
1314 vectors.
1316 Accepts a ragged list/tuple of per-axis vectors (the generic
1317 multi-feature case, where axis lengths differ), a 1-D vector
1318 (single input feature, also as a plain list of scalars), or a
1319 ``(n_input_feat, K)`` stack of equal length vectors.
1321 Args:
1322 freqs (Union[jnp.ndarray, List[jnp.ndarray]]): Frequency
1323 container as described above.
1325 Returns:
1326 List[jnp.ndarray]: One frequency vector per input feature.
1327 """
1328 if isinstance(freqs, (list, tuple)) and np.ndim(freqs[0]) > 0:
1329 # Ragged per-axis frequency vectors: a global jnp.asarray fails
1330 # on unequal axis lengths, so consume the per-axis list directly.
1331 # A plain list of scalars is a single axis and falls through.
1332 return [jnp.asarray(f) for f in freqs]
1333 fa = jnp.asarray(freqs)
1334 if fa.ndim == 1:
1335 return [fa]
1336 return [fa[i] for i in range(fa.shape[0])]
1338 @classmethod
1339 def _calculate_mask(
1340 cls, freqs: Union[jnp.ndarray, List[jnp.ndarray]]
1341 ) -> jnp.ndarray:
1342 """
1343 Determine the flat indices of the Fourier correlation matrix
1344 that lie on a non-negative-frequency row/column. Together with
1345 the strict-lower-triangle condition (handled by the caller),
1346 these indices select the entries of the correlation matrix
1347 that survive the redundancy filter applied in
1348 `get_fourier_fingerprint`:
1350 - rows/columns whose flat frequency component is negative are
1351 discarded (they are the complex-conjugate redundancies of
1352 their positive counterparts);
1353 - of the remaining positive-frequency sub-block, only the
1354 strict lower triangle is kept (the upper triangle, including
1355 the diagonal, contains either duplicates from symmetry or
1356 self-correlations).
1358 Args:
1359 freqs (Union[jnp.ndarray, List[jnp.ndarray]]): Frequencies.
1360 Either a 1-D vector (single input feature), a
1361 ``(n_input_feat, K)`` stack or a ragged list whose rows are
1362 the per-axis frequency vectors (multi-dim input).
1364 Returns:
1365 jnp.ndarray: 1-D int array of flat indices selecting the
1366 non-negative-frequency rows/cols of the fingerprint.
1367 """
1368 axes = cls._per_axis_frequencies(freqs)
1370 if len(axes) == 1:
1371 pos_flat = axes[0] >= 0
1372 else:
1373 # Multi-axis case: build the per-axis non-negativity masks and
1374 # combine them via meshgrid (no float `jnp.outer`!), then
1375 # flatten row-major to match the C-order flattening used by
1376 # the coefficient/correlation pipeline.
1377 grids = jnp.meshgrid(*[axis >= 0 for axis in axes], indexing="ij")
1378 nd_pos = reduce(jnp.logical_and, grids)
1379 pos_flat = nd_pos.flatten()
1381 return jnp.where(pos_flat)[0]
1383 @classmethod
1384 def _flat_frequencies(
1385 cls, freqs: Union[jnp.ndarray, List[jnp.ndarray]]
1386 ) -> jnp.ndarray:
1387 """
1388 Build the per-coefficient flat frequency labels in the same
1389 C-order used to flatten the coefficient/correlation pipeline, so
1390 they can be indexed by the flat indices from `_calculate_mask`.
1392 Args:
1393 freqs (Union[jnp.ndarray, List[jnp.ndarray]]): Either a 1-D
1394 vector (single input feature) or a ``(n_input_feat, K)``
1395 stack / ragged list of per-axis frequency vectors
1396 (multi-dim input).
1398 Returns:
1399 jnp.ndarray: 1-D frequency vector (single input feature) or a
1400 ``(N, n_input_feat)`` array of per-coefficient frequency
1401 tuples (multi-dim input).
1402 """
1403 axes = cls._per_axis_frequencies(freqs)
1404 if len(axes) == 1:
1405 return axes[0]
1406 # Multi-dim: per-axis vectors -> flat grid of frequency tuples in the
1407 # same C-order used by `_calculate_mask` and the coefficient reshape.
1408 grids = jnp.meshgrid(*axes, indexing="ij")
1409 return jnp.stack(grids, axis=-1).reshape(-1, len(axes))
1411 @classmethod
1412 def _calculate_coefficients(
1413 cls,
1414 model: Model,
1415 n_samples: int,
1416 random_key: Optional[random.PRNGKey] = None,
1417 scale: bool = False,
1418 **kwargs: Any,
1419 ) -> Tuple[jnp.ndarray, jnp.ndarray]:
1420 """
1421 Calculates the Fourier coefficients of a given model
1422 using `n_samples`.
1423 Optionally, `noise_params` can be passed to perform noisy simulation.
1425 Args:
1426 model (Model): The QFM model
1427 n_samples (int): Number of samples to calculate average of coefficients
1428 random_key (Optional[random.PRNGKey]): JAX random key for parameter
1429 initialization. If None, uses the model's internal random key.
1430 scale (bool, optional): Whether to scale the number of samples.
1431 Defaults to False.
1432 **kwargs: Additional keyword arguments for the model function.
1434 Returns:
1435 Tuple[jnp.ndarray, jnp.ndarray]: Parameters and Coefficients of size NxK
1436 """
1437 if n_samples > 0:
1438 if scale:
1439 total_samples = int(
1440 jnp.power(2, model.n_qubits) * n_samples * model.n_input_feat
1441 )
1442 log.info(f"Using {total_samples} samples.")
1443 else:
1444 total_samples = n_samples
1445 model.initialize_params(random_key, repeat=total_samples)
1446 else:
1447 total_samples = 1
1449 coeffs, freqs = Coefficients.get_spectrum(
1450 model, shift=True, trim=True, **kwargs
1451 )
1453 return model.params, coeffs, freqs
1455 @classmethod
1456 def _correlate(cls, mat: jnp.ndarray, method: str = "pearson") -> jnp.ndarray:
1457 """
1458 Correlates two arrays using `method`.
1459 Currently, `pearson`, `complex_pearson`, `spearman`, and `covariance`
1460 are supported.
1462 Args:
1463 mat (jnp.ndarray): Array of shape (N, K)
1464 method (str, optional): Correlation method. Defaults to "pearson".
1466 Raises:
1467 ValueError: If the method is not supported.
1469 Returns:
1470 jnp.ndarray: Correlation matrix of `a` and `b`.
1471 """
1472 assert len(mat.shape) >= 2, "Input matrix must have at least 2 dimensions"
1474 # The first axis is the sample axis; any remaining axes are flattened
1475 # in C order. Callers pass coefficients already flattened in C order
1476 # (first input feature slowest), the order that `_calculate_mask`
1477 # and `_flat_frequencies` index into.
1478 if method == "pearson":
1479 result = cls._pearson(mat.reshape(mat.shape[0], -1))
1480 # result = cls._pearson(mat.reshape(mat.shape[-1], -1, order="F"))
1481 elif method == "complex_pearson":
1482 result = cls._complex_pearson(mat.reshape(mat.shape[0], -1))
1483 elif method == "spearman":
1484 result = cls._spearman(mat.reshape(mat.shape[0], -1))
1485 # result = cls._spearman(mat.reshape(mat.shape[-1], -1, order="F"))
1486 elif method == "covariance":
1487 result = cls._covariance(mat.reshape(mat.shape[0], -1))
1488 else:
1489 raise ValueError(
1490 f"Unknown correlation method: {method}. Must be 'pearson', \
1491 'complex_pearson', 'spearman' or 'covariance'."
1492 )
1494 return result
1496 @classmethod
1497 def _covariance(cls, mat: jnp.ndarray, minp: Optional[int] = 1) -> jnp.ndarray:
1498 """
1499 Compute the Hermitian sample covariance between columns of `mat`,
1500 permitting missing values (NaN or ±Inf).
1502 For each pair (i, j) the covariance is computed over the rows that are
1503 finite in both columns, as
1504 sum(conj(x_i - mean_i) * (x_j - mean_j)) / (nobs - 1),
1505 so it computes `X.conj().T @ X`.
1506 Real input collapses to the ordinary real sample covariance; complex
1507 input yields a complex matrix whose magnitude and angle carry the
1508 covariance strength and relative phase.
1511 Args:
1512 mat : array_like, shape (N, K)
1513 Input data.
1514 minp : int, optional
1515 Minimum number of paired observations required to form a
1516 covariance. If the number of valid pairs for (i, j) is < minp,
1517 the result is NaN.
1519 Returns:
1520 cov : ndarray, shape (K, K)
1521 Sample covariance matrix.
1522 """
1523 mat = jnp.asarray(mat)
1524 real_dtype = jnp.asarray(mat.real).dtype
1526 mask = jnp.isfinite(mat)
1527 fmask = mask.astype(real_dtype)
1528 safe = jnp.where(mask, mat, 0.0)
1530 nobs = fmask.T @ fmask
1531 nobs_safe = jnp.where(nobs > 0, nobs, 1.0)
1533 sum_x = safe.T @ fmask
1534 sum_y = fmask.T @ safe
1536 masked = safe * fmask
1537 sum_conj_xy = jnp.conj(masked).T @ masked
1539 sxy = sum_conj_xy - (jnp.conj(sum_x) * sum_y) / nobs_safe
1541 denom = jnp.where(nobs > 1, nobs - 1, jnp.nan)
1542 result = sxy / denom
1544 result = jnp.where(nobs < minp, jnp.nan, result)
1546 return result
1548 @classmethod
1549 def _complex_pearson(cls, mat: jnp.ndarray, minp: Optional[int] = 1) -> jnp.ndarray:
1550 """
1551 Compute the complex Pearson correlation between columns of `mat`,
1552 permitting missing values (NaN or ±Inf).
1554 This uses the Hermitian normalized covariance
1555 sum(conj(x_i - mean_i) * (x_j - mean_j)) /
1556 sqrt(sum(abs(x_i - mean_i)**2) * sum(abs(x_j - mean_j)**2)).
1557 Consequently, if column j is exp(1j * phi) times column i, then
1558 abs(corr[i, j]) is 1 and angle(corr[i, j]) is phi.
1560 Args:
1561 mat : array_like, shape (N, K)
1562 Input data.
1563 minp : int, optional
1564 Minimum number of paired observations required to form a correlation.
1565 If the number of valid pairs for (i, j) is < minp, the result is NaN.
1567 Returns:
1568 corr : ndarray, shape (K, K)
1569 Complex Pearson correlation matrix.
1570 """
1571 mat = jnp.asarray(mat)
1572 real_dtype = jnp.asarray(mat.real).dtype
1574 mask = jnp.isfinite(mat)
1575 fmask = mask.astype(real_dtype)
1576 safe = jnp.where(mask, mat, 0.0)
1578 nobs = fmask.T @ fmask
1579 nobs_safe = jnp.where(nobs > 0, nobs, 1.0)
1581 sum_x = safe.T @ fmask
1582 sum_y = fmask.T @ safe
1584 masked = safe * fmask
1585 sum_conj_xy = jnp.conj(masked).T @ masked
1587 safe_abs_sq = jnp.abs(safe) ** 2
1588 sum_abs_x2 = safe_abs_sq.T @ fmask
1589 sum_abs_y2 = fmask.T @ safe_abs_sq
1591 ssx = sum_abs_x2 - jnp.abs(sum_x) ** 2 / nobs_safe
1592 ssy = sum_abs_y2 - jnp.abs(sum_y) ** 2 / nobs_safe
1593 sxy = sum_conj_xy - (jnp.conj(sum_x) * sum_y) / nobs_safe
1595 denom = jnp.sqrt(ssx * ssy)
1596 result = jnp.where(denom > 0, sxy / denom, jnp.nan)
1597 magnitude = jnp.abs(result)
1598 result = jnp.where(magnitude > 1.0, result / magnitude, result)
1600 result = jnp.where(nobs < minp, jnp.nan, result)
1602 return result
1604 @classmethod
1605 def _pearson(cls, mat: jnp.ndarray, minp: Optional[int] = 1) -> jnp.ndarray:
1606 """
1607 Compute Pearson correlation between columns of `mat`,
1608 permitting missing values (NaN or ±Inf).
1610 The Pearson correlation is the normalized covariance,
1611 corr[i, j] = cov[i, j] / sqrt(cov[i, i] * cov[j, j]),
1612 so it is obtained by normalizing `_covariance` by the per-column
1613 standard deviations.
1615 If the input is complex, real and imaginary parts are stacked along
1616 the sample axis so that both components contribute to the correlation
1617 without discarding information.
1619 Args:
1620 mat : array_like, shape (N, K)
1621 Input data.
1622 minp : int, optional
1623 Minimum number of paired observations required to form a correlation.
1624 If the number of valid pairs for (i, j) is < minp, the result is NaN.
1626 Returns:
1627 corr : ndarray, shape (K, K)
1628 Pearson correlation matrix.
1629 """
1630 # Preserve complex information by splitting into real / imag samples.
1631 # After stacking the data is real, so the Hermitian `_covariance`
1632 # reduces to the ordinary real sample covariance.
1633 if jnp.iscomplexobj(mat):
1634 mat = jnp.concatenate([mat.real, mat.imag], axis=0)
1636 cov = cls._covariance(mat, minp=minp)
1638 # corr[i, j] = cov[i, j] / (std_i * std_j) with std_i = sqrt(cov[i, i])
1639 std = jnp.sqrt(jnp.diagonal(cov))
1640 denom = std[:, None] * std[None, :]
1641 result = jnp.where(denom > 0, cov / denom, jnp.nan)
1643 # clip numerical drift to [-1, 1]
1644 result = jnp.clip(jnp.real(result), -1.0, 1.0)
1646 return result
1648 @classmethod
1649 def _spearman(cls, mat: jnp.ndarray, minp: Optional[int] = 1) -> jnp.ndarray:
1650 """
1651 Based on Pandas correlation method as implemented here:
1652 https://github.com/pandas-dev/pandas/blob/main/pandas/_libs/algos.pyx
1654 Compute Spearman correlation between columns of `mat`,
1655 permitting missing values (NaN or ±Inf).
1657 If the input is complex, real and imaginary parts are stacked along
1658 the sample axis so that both components contribute to the correlation
1659 without discarding information.
1661 Args:
1662 mat : array_like, shape (N, K)
1663 Input data.
1664 minp : int, optional
1665 Minimum number of paired observations required to form a correlation.
1666 If the number of valid pairs for (i, j) is < minp, the result is NaN.
1668 Returns:
1669 corr : ndarray, shape (K, K)
1670 Spearman correlation matrix.
1671 """
1672 # Preserve complex information by splitting into real / imag samples
1673 if jnp.iscomplexobj(mat):
1674 mat = jnp.concatenate([mat.real, mat.imag], axis=0)
1676 mat = jnp.asarray(mat)
1677 N, K = mat.shape
1679 # trivial all-NaN answer if too few rows
1680 if N < minp:
1681 return jnp.full((K, K), jnp.nan)
1683 # mask of finite entries
1684 mask = jnp.isfinite(mat) # shape (N, K), dtype=bool
1686 # precompute ranks column-wise ignoring NaNs
1687 ranks = np.full((N, K), np.nan)
1688 for j in range(K):
1689 valid = mask[:, j]
1690 if valid.any():
1691 ranks[valid, j] = rankdata(mat[valid, j], method="average")
1693 ranks = jnp.asarray(ranks)
1695 # Vectorised Pearson on the ranks
1696 # Replace NaN ranks with 0; use mask to track validity.
1697 rank_mask = jnp.isfinite(ranks)
1698 safe_ranks = jnp.where(rank_mask, ranks, 0.0)
1700 # Pairwise valid-observation counts (K, K)
1701 fmask = rank_mask.astype(ranks.dtype)
1702 nobs = fmask.T @ fmask
1704 # Pairwise sums over mutually-valid rows
1705 sum_x = safe_ranks.T @ fmask # (K, K)
1706 sum_y = fmask.T @ safe_ranks # (K, K)
1708 # Pairwise products
1709 masked_ranks = safe_ranks * fmask # same as safe_ranks
1710 sum_xy = masked_ranks.T @ masked_ranks # (K, K)
1712 safe_sq = safe_ranks**2
1713 sum_x2 = safe_sq.T @ fmask # (K, K)
1714 sum_y2 = fmask.T @ safe_sq # (K, K)
1716 nobs_safe = jnp.where(nobs > 0, nobs, 1.0)
1717 ssx = sum_x2 - sum_x**2 / nobs_safe
1718 ssy = sum_y2 - sum_y**2 / nobs_safe
1719 sxy = sum_xy - (sum_x * sum_y) / nobs_safe
1721 denom = jnp.sqrt(ssx * ssy)
1722 result = jnp.where(denom > 0, sxy / denom, jnp.nan)
1723 result = jnp.clip(result, -1.0, 1.0)
1725 # Enforce minp
1726 result = jnp.where(nobs < minp, jnp.nan, result)
1728 return result
1730 @classmethod
1731 def _weighting_linear(cls, fourier_fingerprint: jnp.ndarray) -> jnp.ndarray:
1732 """
1733 Performs weighting on the given correlation matrix.
1734 Here, low-frequent coefficients are weighted more heavily.
1736 Args:
1737 fourier_fingerprint (jnp.ndarray): Correlation matrix
1738 """
1739 assert (
1740 fourier_fingerprint.shape[0] % 2 != 0
1741 and fourier_fingerprint.shape[1] % 2 != 0
1742 ), (
1743 "Correlation matrix must have odd dimensions. \
1744 Hint: use `trim` argument when calling `get_spectrum`."
1745 )
1746 assert fourier_fingerprint.shape[0] == fourier_fingerprint.shape[1], (
1747 "Correlation matrix must be square."
1748 )
1750 # The weight matrix produced by the previous quadrant-mirror
1751 # construction has a closed form: it is a "tent" sum along the
1752 # two axes. Concretely, with N = fourier_fingerprint.shape[0]
1753 # (odd) and center = N // 2,
1754 # W[i, j] = u[i] + u[j]
1755 # where u[k] = (center - |k - center|) / (2 * center)
1756 # is a triangular weighting peaking at the centre (the zero
1757 # frequency) and decaying linearly to 0 at the spectrum edges.
1758 N = fourier_fingerprint.shape[0]
1759 center = N // 2
1760 k = jnp.arange(N)
1761 u = (center - jnp.abs(k - center)) / (2 * center)
1763 return fourier_fingerprint * (u[:, None] + u[None, :])
1765 @classmethod
1766 def _weighting_mean(
1767 cls, fourier_fingerprint: jnp.ndarray, coeffs: jnp.ndarray
1768 ) -> jnp.ndarray:
1769 """
1770 Performs weighting on the given correlation matrix.
1771 Here, we use the product of the mean of the coefficients as weights.
1772 This suppresses correlations where the mean of the coefficients is near zero.
1774 Args:
1775 fourier_fingerprint (jnp.ndarray): Correlation matrix
1776 coeffs (jnp.ndarray): Fourier coefficients
1777 """
1778 assert fourier_fingerprint.shape[0] == fourier_fingerprint.shape[1], (
1779 "Correlation matrix must be square."
1780 )
1781 assert len(coeffs.shape) >= 2, (
1782 "Coefficient matrix must contain coefficient axes and a sample axis."
1783 )
1785 coefficient_means = jnp.abs(jnp.mean(coeffs, axis=-1))
1786 # C order, matching the flattening of the correlated coefficients
1787 coefficient_means = coefficient_means.reshape(-1)
1789 assert fourier_fingerprint.shape[0] == coefficient_means.shape[0], (
1790 "Correlation matrix size must match the number of Fourier coefficients."
1791 )
1793 # Apply the rank-1 weight w[i] * w[j] via broadcasting instead
1794 # of materialising an explicit `jnp.outer` N x N intermediate.
1795 return (
1796 fourier_fingerprint
1797 * coefficient_means[:, None]
1798 * coefficient_means[None, :]
1799 )
1802class Datasets:
1803 @classmethod
1804 def generate_fourier_series(
1805 cls,
1806 random_key: random.PRNGKey,
1807 model: Model,
1808 coefficients_min: float = 0.0,
1809 coefficients_max: float = 1.0,
1810 zero_centered: bool = False,
1811 ) -> jnp.ndarray:
1812 """
1813 Generates the Fourier series representation of a function.
1814 It uses the `model.frequencies` property to retrieve the frequency
1815 information. This ensures that the resulting Fourier series is
1816 compatible with the model.
1818 This function is capable of generating $D$-dimensional Fourier series
1819 (again defined by `model.n_input_feat`).
1820 The highest frequency $N$ is retrieved per dimension.
1822 Samples of the Fourier coefficients are drawn from a uniform circle.
1824 Args:
1825 random_key (random.PRNGKey): Random number key for JAX.
1826 model (Model): The quantum circuit model.
1827 coefficients_min (float, optional): Minimum value for the coefficients.
1828 Defaults to 0.0.
1829 coefficients_max (float, optional): Maximum value for the coefficients.
1830 Defaults to 1.0.
1831 zero_centered (bool, optional): Whether to zero-center the coefficients.
1832 Defaults to False.
1834 Returns:
1835 jnp.ndarray: Input domain samples with shape ((N,)*D, D)
1836 jnp.ndarray: Fourier series values with shape ((N,)*D)
1837 jnp.ndarray: Fourier coefficients with shape ((N,)*D)
1839 """
1840 # TODO: the following code can be considered to
1841 # capturing a truly random spectrum.
1842 # add some constraints on the spectrum, i.e. not fully
1844 # Note: one key observation for understanding the following code is,
1845 # that instead of wrapping your head around symmetries in multi-
1846 # dimensional coefficient matrices, one can simply look at the flattened
1847 # version of such a matrix and reshape later. It just works out.
1848 domain_samples_per_input_dim = cls.construct_domain_samples(model)
1850 frequencies = cls.construct_frequencies(model)
1852 coefficients = cls.construct_coefficients(
1853 random_key, model, coefficients_min, coefficients_max, zero_centered
1854 )
1856 values = cls.calculate_values(
1857 domain_samples_per_input_dim, frequencies, coefficients
1858 )
1860 # return all the information we have
1861 return [
1862 domain_samples_per_input_dim.reshape(*model.degree, -1),
1863 values.reshape(model.degree),
1864 coefficients.reshape(model.degree),
1865 ]
1867 @classmethod
1868 def construct_domain_samples(
1869 cls, model: Model, mts: int = 1, mfs: int = 1
1870 ) -> jnp.ndarray:
1871 """
1872 Builds the input-domain sample grid for the model spectrum.
1874 Going from $[0, 2 \\pi \\, \\mathrm{mts}]$ with the resolution required
1875 for the highest frequency, permuted with the input dimensionality to get
1876 an n-d grid of domain samples (a "coordinate system").
1878 The grid follows the same convention as
1879 `Coefficients._fourier_transform`, so a dataset built here lands on the
1880 bins that `Coefficients.get_spectrum` analyses with the same `mts` and
1881 `mfs`. A target component at $k + j/r$ has period $2 \\pi r$, hence
1882 `mts` should be at least $r$ to cover a full period.
1884 Args:
1885 model (Model): The quantum circuit model.
1886 mts (int, optional): Domain oversampling, i.e. the number of
1887 periods covered. Defaults to 1.
1888 mfs (int, optional): Frequency oversampling, i.e. the sample
1889 density per period. Defaults to 1.
1891 Returns:
1892 jnp.ndarray: Domain samples with shape
1893 (mts $\\cdot$ mfs $\\cdot$ $\\prod$ degree, n_input_feat).
1894 """
1895 return jnp.stack(
1896 jnp.meshgrid(
1897 *[
1898 jnp.arange(0, 2 * mts * jnp.pi, 2 * jnp.pi / (mfs * d))
1899 for d in model.degree
1900 ],
1901 indexing="ij",
1902 ),
1903 axis=-1,
1904 ).reshape(-1, model.n_input_feat)
1906 @classmethod
1907 def construct_frequencies(
1908 cls,
1909 model: Model,
1910 random_key: Optional[random.PRNGKey] = None,
1911 offgrid_mode: str = "none",
1912 offgrid_prob: float = 0.0,
1913 offgrid_resolution: int = 2,
1914 ) -> jnp.ndarray:
1915 """
1916 Builds the frequency-index grid for the model spectrum.
1918 This has the same shape as the domain samples returned by
1919 `construct_domain_samples`.
1921 By default the grid is the model's own comb, so the dataset is exactly
1922 representable. The off-grid modes move a controllable fraction of the
1923 components off that comb.
1924 Offsets are always multiples of $1/r$ for the given resolution $r$.
1926 Args:
1927 model (Model): The quantum circuit model.
1928 random_key (Optional[random.PRNGKey]): Random number key for JAX.
1929 Required unless `offgrid_mode` is "none".
1930 offgrid_mode (str, optional): How to displace components off the
1931 model comb. "none" keeps the model comb. "index" perturbs each
1932 frequency independently, which spans arbitrary combs that are
1933 in general not exactly reachable. "generator" perturbs the
1934 per-gate generator frequencies and rebuilds the comb as their
1935 Minkowski sum, which stays exactly reachable by an encoding
1936 pulse configuration. Defaults to "none".
1937 offgrid_prob (float, optional): Probability that a single component
1938 ("index") or generator ("generator") is displaced. Defaults to
1939 0.0, which reproduces the model comb in every mode. Note that
1940 this is the fraction of components that end up off the comb
1941 only in "index" mode: a sum of displaced generators can land
1942 back on an integer, so "generator" mode displaces noticeably
1943 fewer components than asked for and saturates well below one.
1944 offgrid_resolution (int, optional): Denominator $r$ of the offset
1945 grid, i.e. offsets are drawn from $\\{\\pm j/r\\}$ with
1946 $j = 1 \\dots r-1$. Defaults to 2, giving half-integer offsets.
1948 Returns:
1949 jnp.ndarray: Frequency indices with shape
1950 ($\\prod$ degree, n_input_feat).
1951 """
1952 if offgrid_mode == "none":
1953 frequencies = model.frequencies
1954 else:
1955 if random_key is None:
1956 raise ValueError(f"offgrid_mode={offgrid_mode!r} requires a random_key")
1957 if offgrid_resolution < 2:
1958 raise ValueError(
1959 f"offgrid_resolution must be at least 2, "
1960 f"got {offgrid_resolution}. There is no non-integer offset "
1961 "on a grid of resolution 1."
1962 )
1963 if offgrid_mode == "index":
1964 displace = cls._displace_indices
1965 elif offgrid_mode == "generator":
1966 displace = cls._displace_generators
1967 else:
1968 raise ValueError(
1969 f"Unknown offgrid_mode: {offgrid_mode!r}. Use one of "
1970 "'none', 'index', 'generator'."
1971 )
1973 frequencies = []
1974 for i in range(model.n_input_feat):
1975 random_key, sub_key = random.split(random_key)
1976 frequencies.append(
1977 displace(model, i, sub_key, offgrid_prob, offgrid_resolution)
1978 )
1980 return jnp.stack(jnp.meshgrid(*frequencies, indexing="ij"), axis=-1).reshape(
1981 -1, model.n_input_feat
1982 )
1984 @classmethod
1985 def _offsets(
1986 cls,
1987 random_key: random.PRNGKey,
1988 shape: Tuple[int, ...],
1989 prob: float,
1990 resolution: int,
1991 ) -> jnp.ndarray:
1992 """
1993 Draws signed offsets on the $1/r$ grid, zero where not displaced.
1995 Args:
1996 random_key (random.PRNGKey): Random number key for JAX.
1997 shape (Tuple[int, ...]): Shape of the offset array.
1998 prob (float): Probability that an entry is displaced.
1999 resolution (int): Denominator $r$ of the offset grid.
2001 Returns:
2002 jnp.ndarray: Offsets drawn from $\\{0\\} \\cup \\{\\pm j/r\\}$ with
2003 $j = 1 \\dots r-1$.
2004 """
2005 move_key, magnitude_key, sign_key = random.split(random_key, 3)
2006 magnitude = random.randint(magnitude_key, shape, 1, resolution) / resolution
2007 return (
2008 random.bernoulli(move_key, prob, shape)
2009 * random.rademacher(sign_key, shape)
2010 * magnitude
2011 )
2013 @classmethod
2014 def _displace_indices(
2015 cls,
2016 model: Model,
2017 feature: int,
2018 random_key: random.PRNGKey,
2019 prob: float,
2020 resolution: int,
2021 ) -> jnp.ndarray:
2022 """
2023 Displaces individual frequencies of one input feature off the comb.
2025 Each positive frequency is displaced independently, the result is
2026 re-sorted and mirrored so that the comb stays antisymmetric. This is
2027 what `construct_coefficients` relies on to enforce conjugate symmetry,
2028 and in turn what keeps the series real-valued. The comb never leaves
2029 the model's frequency range: an offset that would push a component past
2030 the highest frequency has its sign flipped rather than being clipped,
2031 which would put the component back on the comb.
2033 Args:
2034 model (Model): The quantum circuit model.
2035 feature (int): Index of the input feature.
2036 random_key (random.PRNGKey): Random number key for JAX.
2037 prob (float): Probability that a component is displaced.
2038 resolution (int): Denominator $r$ of the offset grid.
2040 Returns:
2041 jnp.ndarray: Displaced comb, same size as the model comb.
2042 """
2043 nominal = jnp.asarray(model.frequencies[feature])
2044 positive = nominal[nominal > 0]
2045 limit = positive[-1]
2047 offsets = cls._offsets(random_key, positive.shape, prob, resolution)
2048 # the smallest positive frequency is 1 and offsets are below 1, so only
2049 # the upper end of the range can be overshot
2050 offsets = jnp.where(positive + offsets > limit, -offsets, offsets)
2052 # ponytail: two components can collide (1 + 0.5 and 2 - 0.5), in which
2053 # case their coefficients simply add. Deduplicating would change the
2054 # number of components, which is the one thing the study holds fixed.
2055 positive = jnp.sort(positive + offsets)
2057 return jnp.concatenate([-jnp.flip(positive), jnp.zeros(1), positive])
2059 @classmethod
2060 def _displace_generators(
2061 cls,
2062 model: Model,
2063 feature: int,
2064 random_key: random.PRNGKey,
2065 prob: float,
2066 resolution: int,
2067 ) -> jnp.ndarray:
2068 """
2069 Displaces the generator frequencies of one input feature off the comb.
2071 Mirrors `Encoding.get_spectrum`, but scales each encoding gate's
2072 generator by a displaced $\\eta$ before taking the Minkowski sum, which
2073 is exactly what an encoding pulse scaler does to the gate it drives.
2074 The reachable comb then grows past the model degree in both count and
2075 range, so each model frequency claims the closest reachable one that is
2076 still inside the model's range. Staying in range matters: a component
2077 beyond the highest model frequency would be unreachable.
2078 Two model frequencies may end up claiming the same
2079 reachable one, as in `_displace_indices`.
2081 Args:
2082 model (Model): The quantum circuit model.
2083 feature (int): Index of the input feature.
2084 random_key (random.PRNGKey): Random number key for JAX.
2085 prob (float): Probability that a generator is displaced.
2086 resolution (int): Denominator $r$ of the offset grid.
2088 Returns:
2089 jnp.ndarray: Displaced comb, same size as the model comb.
2090 """
2091 # the offset draw and in-range flip live in _generator_etas, so the
2092 # scalers exposed by generator_etas cannot desync from this comb
2093 eta = cls._generator_etas(model, feature, random_key, prob, resolution)
2095 base = {"hamming": 1, "binary": 2, "ternary": 3}[model._enc._strategy]
2096 nominal = np.asarray(model.frequencies[feature])
2097 limit = nominal.max()
2098 mask = np.asarray(model.data_reupload[..., feature], dtype=bool)
2099 scale = base ** np.arange(mask.shape[1])
2101 # Minkowski sum over the displaced per-gate generators. Rounded before
2102 # deduplication, which is exact for a power-of-two resolution.
2103 reach = {0.0}
2104 for layer, qubit in zip(*np.nonzero(mask)):
2105 generator = scale[qubit] * eta[layer, qubit]
2106 reach = {
2107 round(a + s * generator, 9) for a in reach for s in (-1.0, 0.0, 1.0)
2108 }
2109 reachable = sorted(v for v in reach if 0 < v <= limit)
2111 # claim the closest reachable frequency, so the displaced comb tracks
2112 # the original one
2113 positive = jnp.sort(
2114 jnp.asarray(
2115 [
2116 min(reachable, key=lambda v: abs(v - frequency))
2117 for frequency in nominal[nominal > 0]
2118 ],
2119 dtype=float,
2120 )
2121 )
2123 return jnp.concatenate([-jnp.flip(positive), jnp.zeros(1), positive])
2125 @classmethod
2126 def _generator_etas(
2127 cls,
2128 model: Model,
2129 feature: int,
2130 random_key: random.PRNGKey,
2131 prob: float,
2132 resolution: int,
2133 ) -> np.ndarray:
2134 """
2135 The per-gate scalers $\\eta = 1 + \\text{offset}$ applied to the
2136 encoding generators of one input feature in `offgrid_mode='generator'`.
2138 This is the offset draw and in-range flip shared with
2139 `_displace_generators`; the returned array has the shape of the
2140 data-reupload mask ($n_\\text{layers}, n_\\text{qubits}$) and holds
2141 exactly the encoding pulse amplitude scalers that make the generator
2142 comb reachable.
2144 Args:
2145 model (Model): The quantum circuit model.
2146 feature (int): Index of the input feature.
2147 random_key (random.PRNGKey): Random number key for JAX.
2148 prob (float): Probability that a generator is displaced.
2149 resolution (int): Denominator $r$ of the offset grid.
2151 Returns:
2152 np.ndarray: Amplitude scalers $\\eta$, shape
2153 ($n_\\text{layers}, n_\\text{qubits}$).
2154 """
2155 base = {"hamming": 1, "binary": 2, "ternary": 3}.get(model._enc._strategy)
2156 if base is None:
2157 raise ValueError(
2158 f"offgrid_mode='generator' does not support the "
2159 f"{model._enc._strategy!r} encoding strategy, which has no "
2160 "per-gate pulse parametrization to displace."
2161 )
2163 nominal = np.asarray(model.frequencies[feature])
2164 limit = nominal.max()
2165 mask = np.asarray(model.data_reupload[..., feature], dtype=bool)
2166 scale = base ** np.arange(mask.shape[1])
2167 offsets = np.asarray(cls._offsets(random_key, mask.shape, prob, resolution))
2168 offsets = np.where(scale * (1.0 + offsets) > limit, -offsets, offsets)
2169 return 1.0 + offsets
2171 @classmethod
2172 def generator_etas(
2173 cls,
2174 model: Model,
2175 random_key: random.PRNGKey,
2176 offgrid_prob: float,
2177 offgrid_resolution: int,
2178 ) -> List[np.ndarray]:
2179 """
2180 The encoding pulse amplitude scalers `construct_frequencies` applies in
2181 `offgrid_mode='generator'`, one ($n_\\text{layers}, n_\\text{qubits}$)
2182 array per input feature.
2184 Call with the same `random_key` passed to `construct_frequencies` to
2185 recover the encoding pulse configuration that makes the off-grid target
2186 reachable, e.g. to oracle-initialize or score trained scalers against
2187 it. The per-feature key split mirrors `construct_frequencies`.
2189 Args:
2190 model (Model): The quantum circuit model.
2191 random_key (random.PRNGKey): The key passed to
2192 `construct_frequencies`.
2193 offgrid_prob (float): Probability that a generator is displaced.
2194 offgrid_resolution (int): Denominator $r$ of the offset grid.
2196 Returns:
2197 List[np.ndarray]: Amplitude scalers $\\eta$ per input feature.
2198 """
2199 etas = []
2200 for i in range(model.n_input_feat):
2201 random_key, sub_key = random.split(random_key)
2202 etas.append(
2203 cls._generator_etas(model, i, sub_key, offgrid_prob, offgrid_resolution)
2204 )
2205 return etas
2207 @classmethod
2208 def construct_coefficients(
2209 cls,
2210 random_key: random.PRNGKey,
2211 model: Model,
2212 coefficients_min: float = 0.0,
2213 coefficients_max: float = 1.0,
2214 zero_centered: bool = False,
2215 ) -> jnp.ndarray:
2216 """
2217 Samples the conjugate-symmetric Fourier coefficient vector.
2219 Coefficients are drawn from a uniform circle (see `uniform_circle`).
2220 The offset coefficient (first entry) is either zeroed or made real,
2221 then the spectrum is mirrored to enforce conjugate symmetry.
2223 Args:
2224 random_key (random.PRNGKey): Random number key for JAX.
2225 model (Model): The quantum circuit model.
2226 coefficients_min (float, optional): Minimum value for the
2227 coefficients. Defaults to 0.0.
2228 coefficients_max (float, optional): Maximum value for the
2229 coefficients. Defaults to 1.0.
2230 zero_centered (bool, optional): Whether to zero-center the
2231 coefficients. Defaults to False.
2233 Returns:
2234 jnp.ndarray: Conjugate-symmetric coefficient vector of size
2235 $\\prod$ degree.
2236 """
2237 coefficients = cls.uniform_circle(
2238 random_key,
2239 low=coefficients_min,
2240 high=coefficients_max,
2241 size=math.prod(model.degree) // 2 + 1,
2242 )
2244 # zero center (first coeff = 0)
2245 # we can assume the first coeff is the offset, because we're dealing
2246 # with a non-symmetric spectrum here
2247 if zero_centered:
2248 coefficients = coefficients.at[0].set(0.0)
2249 else:
2250 coefficients = coefficients.at[0].set(coefficients[0].real)
2252 # ensure symmetry (here, non_negative_ is removed!),
2253 # giving us the full coefficients vector
2254 return jnp.concat(
2255 [
2256 jnp.flip(coefficients[..., 1:]).conjugate(),
2257 coefficients,
2258 ],
2259 axis=-1,
2260 )
2262 @classmethod
2263 def calculate_values(
2264 cls,
2265 domain_samples: jnp.ndarray,
2266 frequencies: jnp.ndarray,
2267 coefficients: jnp.ndarray,
2268 ) -> jnp.ndarray:
2269 """
2270 Evaluates the real-valued Fourier series on the domain grid.
2272 Vectorized version of
2273 $f(x) = \\sum_{n=0}^{N-1} c_n e^{i \\omega_n x}$ that takes the input
2274 dimension into account, normalized by the number of coefficients.
2276 Args:
2277 domain_samples (jnp.ndarray): Domain samples with shape
2278 (n_points, n_input_feat).
2279 frequencies (jnp.ndarray): Frequency indices with shape
2280 (n_freqs, n_input_feat).
2281 coefficients (jnp.ndarray): Fourier coefficients with shape
2282 (n_freqs,).
2284 Returns:
2285 jnp.ndarray: Real-valued Fourier series samples with shape
2286 (n_points,).
2287 """
2288 return jnp.real(
2289 (jnp.exp(1j * (domain_samples @ frequencies.T)) * coefficients).sum(axis=1)
2290 / coefficients.size
2291 )
2293 @classmethod
2294 def uniform_circle(
2295 cls,
2296 random_key: random.PRNGKey,
2297 size: Union[jnp.ndarray, List, int],
2298 low=0.0,
2299 high=1.0,
2300 ):
2301 """
2302 Random number generator for complex numbers sampled inside the unit circle
2304 Args:
2305 random_key (random.PRNGKey): Random number key for JAX.
2306 size (Union[jnp.ndarray, int]): Number of samples. If a 2D array is passed,
2307 the first dimension will be the number of dimensions.
2308 low (float, optional): Minimum Radius. Defaults to 0.0.
2309 high (float, optional): Maximum Radius. Defaults to 1.0.
2311 Returns
2312 jnp.ndarray: Array of complex numbers with shape of `size`
2313 """
2315 if isinstance(size, int):
2316 size = jnp.array([size])
2318 random_key, random_key1 = random.split(random_key)
2319 return jnp.sqrt(
2320 random.uniform(random_key, size, minval=low, maxval=high)
2321 ) * jnp.exp(2j * jnp.pi * random.uniform(random_key1, size))