qadence 1.7.4__py3-none-any.whl → 1.7.6__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -59,9 +59,13 @@ class AddressingPattern:
59
59
  ) -> dict:
60
60
  # augment weight dict if needed
61
61
  weights = {
62
- i: Parameter(0.0)
63
- if i not in weights
64
- else (Parameter(weights[i]) if not isinstance(weights[i], Parameter) else weights[i])
62
+ i: (
63
+ Parameter(0.0)
64
+ if i not in weights
65
+ else (
66
+ Parameter(weights[i]) if not isinstance(weights[i], Parameter) else weights[i]
67
+ )
68
+ )
65
69
  for i in range(self.n_qubits)
66
70
  }
67
71
 
qadence/backends/api.py CHANGED
@@ -3,6 +3,9 @@ from __future__ import annotations
3
3
  from qadence.backend import Backend, BackendConfiguration
4
4
  from qadence.engines.differentiable_backend import DifferentiableBackend
5
5
  from qadence.extensions import (
6
+ BackendNotFoundError,
7
+ ConfigNotFoundError,
8
+ EngineNotFoundError,
6
9
  import_backend,
7
10
  import_config,
8
11
  import_engine,
@@ -49,12 +52,9 @@ def backend_factory(
49
52
  diff_backend_cls = import_engine(backend_inst.engine)
50
53
  backend_inst = diff_backend_cls(backend=backend_inst, diff_mode=DiffMode(diff_mode)) # type: ignore[operator]
51
54
  return backend_inst
52
- except Exception as e:
53
- msg = f"The requested backend '{backend}' is either not installed\
54
- or could not be imported due to {e}."
55
- logger.error(msg)
56
- raise Exception(msg)
57
- # Set backend configurations which depend on the differentiation mode
55
+ except (BackendNotFoundError, EngineNotFoundError, ConfigNotFoundError) as e:
56
+ logger.error(e.msg)
57
+ raise e
58
58
 
59
59
 
60
60
  def config_factory(backend_name: BackendName | str, config: dict) -> BackendConfiguration:
@@ -62,6 +62,7 @@ def config_factory(backend_name: BackendName | str, config: dict) -> BackendConf
62
62
  try:
63
63
  BackendConfigCls = import_config(backend_name)
64
64
  cfg = BackendConfigCls(**config) # type: ignore[operator]
65
- except Exception as e:
66
- logger.debug(f"Unable to import config for backend {backend_name} due to {e}.")
65
+ except ConfigNotFoundError as e:
66
+ logger.error(e.msg)
67
+ raise e
67
68
  return cfg
qadence/backends/gpsr.py CHANGED
@@ -11,13 +11,29 @@ from qadence.utils import _round_complex
11
11
 
12
12
 
13
13
  def general_psr(spectrum: Tensor, n_eqs: int | None = None, shift_prefac: float = 0.5) -> Callable:
14
+ """Define whether single_gap_psr or multi_gap_psr is used.
15
+
16
+ Args:
17
+ spectrum (Tensor): Spectrum of the operation we apply PSR onto.
18
+ n_eqs (int | None, optional): Number of equations. Defaults to None.
19
+ If provided, we keep the n_eqs higher spectral gaps.
20
+ shift_prefac (float, optional): Shift prefactor. Defaults to 0.5.
21
+
22
+ Returns:
23
+ Callable: single_gap_psr or multi_gap_psr function for
24
+ concerned operation.
25
+ """
14
26
  diffs = _round_complex(spectrum - spectrum.reshape(-1, 1))
15
27
  sorted_unique_spectral_gaps = torch.unique(torch.abs(torch.tril(diffs)))
16
28
 
17
29
  # We have to filter out zeros
18
30
  sorted_unique_spectral_gaps = sorted_unique_spectral_gaps[sorted_unique_spectral_gaps > 0]
19
- n_eqs = len(sorted_unique_spectral_gaps)
20
- sorted_unique_spectral_gaps = torch.tensor(list(sorted_unique_spectral_gaps))
31
+ n_eqs = (
32
+ len(sorted_unique_spectral_gaps)
33
+ if n_eqs is None
34
+ else min(n_eqs, len(sorted_unique_spectral_gaps))
35
+ )
36
+ sorted_unique_spectral_gaps = torch.tensor(list(sorted_unique_spectral_gaps)[:n_eqs])
21
37
 
22
38
  if n_eqs == 1:
23
39
  return single_gap_psr
@@ -7,11 +7,11 @@ from operator import add
7
7
  from typing import Any, Callable, Dict
8
8
 
9
9
  import jax.numpy as jnp
10
- from horqrux.abstract import Primitive as Gate
11
10
  from horqrux.analog import _HamiltonianEvolution as NativeHorqHEvo
12
11
  from horqrux.apply import apply_gate
13
12
  from horqrux.parametric import RX, RY, RZ
14
13
  from horqrux.primitive import NOT, SWAP, H, I, X, Y, Z
14
+ from horqrux.primitive import Primitive as Gate
15
15
  from horqrux.utils import inner
16
16
  from jax import Array
17
17
  from jax.scipy.linalg import expm
@@ -71,19 +71,16 @@ class Backend(BackendInterface):
71
71
  def observable(self, observable: AbstractBlock, n_qubits: int) -> ConvertedObservable:
72
72
  # make sure only leaves, i.e. primitive blocks are scaled
73
73
  transpilations = [
74
- lambda block: chain_single_qubit_ops(block)
75
- if self.config.use_single_qubit_composition
76
- else flatten(block),
74
+ lambda block: (
75
+ chain_single_qubit_ops(block)
76
+ if self.config.use_single_qubit_composition
77
+ else flatten(block)
78
+ ),
77
79
  scale_primitive_blocks_only,
78
80
  ]
79
81
  block = transpile(*transpilations)(observable) # type: ignore[call-overload]
80
82
  operations = convert_block(block, n_qubits, self.config)
81
- obs_cls = (
82
- pyq.DiagonalObservable
83
- if block._is_diag_pauli and not block.is_parametric
84
- else pyq.Observable
85
- )
86
- native = obs_cls(n_qubits=n_qubits, operations=operations)
83
+ native = pyq.Observable(operations=operations)
87
84
  return ConvertedObservable(native=native, abstract=block, original=observable)
88
85
 
89
86
  def run(
@@ -140,7 +137,7 @@ class Backend(BackendInterface):
140
137
  )
141
138
  observable = observable if isinstance(observable, list) else [observable]
142
139
  _expectation = torch.hstack(
143
- [obs.native(state, param_values).reshape(-1, 1) for obs in observable]
140
+ [obs.native.expectation(state, param_values).reshape(-1, 1) for obs in observable]
144
141
  )
145
142
  return _expectation
146
143
 
@@ -169,7 +166,7 @@ class Backend(BackendInterface):
169
166
  observables = observable if isinstance(observable, list) else [observable]
170
167
  for vals in to_list_of_dicts(param_values):
171
168
  wf = self.run(circuit, vals, state, endianness, pyqify_state=True, unpyqify_state=False)
172
- exs = torch.cat([obs.native(wf, vals) for obs in observables], 0)
169
+ exs = torch.cat([obs.native.expectation(wf, vals) for obs in observables], 0)
173
170
  list_expvals.append(exs)
174
171
 
175
172
  batch_expvals = torch.vstack(list_expvals)
@@ -7,7 +7,6 @@ from typing import Any, Sequence, Tuple
7
7
  import pyqtorch as pyq
8
8
  import sympy
9
9
  import torch
10
- from pyqtorch.apply import apply_operator
11
10
  from pyqtorch.embed import Embedding
12
11
  from pyqtorch.matrices import _dagger
13
12
  from pyqtorch.time_dependent.sesolve import sesolve
@@ -45,7 +44,6 @@ from qadence.blocks import (
45
44
  )
46
45
  from qadence.blocks.block_to_tensor import (
47
46
  _block_to_tensor_embedded,
48
- block_to_tensor,
49
47
  )
50
48
  from qadence.blocks.primitive import ProjectorBlock
51
49
  from qadence.blocks.utils import parameters
@@ -78,6 +76,14 @@ def is_single_qubit_chain(block: AbstractBlock) -> bool:
78
76
  )
79
77
 
80
78
 
79
+ def extract_parameter(block: ScaleBlock | ParametricBlock, config: Configuration) -> str | Tensor:
80
+ return (
81
+ tensor([block.parameters.parameter], dtype=float64)
82
+ if not block.is_parametric
83
+ else config.get_param_name(block)[0]
84
+ )
85
+
86
+
81
87
  def convert_block(
82
88
  block: AbstractBlock, n_qubits: int = None, config: Configuration = None
83
89
  ) -> Sequence[Module | Tensor | str | sympy.Expr]:
@@ -94,31 +100,45 @@ def convert_block(
94
100
 
95
101
  if isinstance(block, ScaleBlock):
96
102
  scaled_ops = convert_block(block.block, n_qubits, config)
97
- scale = (
98
- tensor([block.parameters.parameter], dtype=float64)
99
- if not block.is_parametric
100
- else config.get_param_name(block)[0]
101
- )
103
+ scale = extract_parameter(block, config)
102
104
  return [pyq.Scale(pyq.Sequence(scaled_ops), scale)]
103
105
 
104
106
  elif isinstance(block, TimeEvolutionBlock):
105
- # TODO add native pyq hamevo
106
- # generator = convert_block(block.generator, n_qubits, config)[0] # type: ignore[arg-type]
107
- # time_param = config.get_param_name(block)[0]
108
- # is_parametric = (
109
- # block.generator.is_parametric if isinstance(block.generator, AbstractBlock) else False
110
- # )
111
- # return [
112
- # pyq.HamiltonianEvolution(
113
- # qubit_support=qubit_support,
114
- # generator=generator,
115
- # time=time_param,
116
- # generator_parametric=is_parametric, # type: ignore[union-attr]
117
- # )
118
- # ]
119
- return [PyQHamiltonianEvolution(qubit_support, n_qubits, block, config)]
107
+ if getattr(block.generator, "is_time_dependent", False):
108
+ return [PyQTimeDependentEvolution(qubit_support, n_qubits, block, config)]
109
+ else:
110
+ if isinstance(block.generator, sympy.Basic):
111
+ generator = config.get_param_name(block)[1]
112
+ elif isinstance(block.generator, Tensor):
113
+ m = block.generator.to(dtype=cdouble)
114
+ generator = convert_block(
115
+ MatrixBlock(
116
+ m,
117
+ qubit_support=qubit_support,
118
+ check_unitary=False,
119
+ check_hermitian=True,
120
+ )
121
+ )[0]
122
+ else:
123
+ generator = convert_block(block.generator, n_qubits, config)[0] # type: ignore[arg-type]
124
+ time_param = config.get_param_name(block)[0]
125
+ is_parametric = (
126
+ block.generator.is_parametric
127
+ if isinstance(block.generator, AbstractBlock)
128
+ else False
129
+ )
130
+ return [
131
+ pyq.HamiltonianEvolution(
132
+ qubit_support=qubit_support,
133
+ generator=generator,
134
+ time=time_param,
135
+ generator_parametric=is_parametric, # type: ignore[union-attr]
136
+ cache_length=0,
137
+ )
138
+ ]
139
+
120
140
  elif isinstance(block, MatrixBlock):
121
- return [pyq.primitive.Primitive(block.matrix, block.qubit_support)]
141
+ return [pyq.primitives.Primitive(block.matrix, block.qubit_support)]
122
142
  elif isinstance(block, CompositeBlock):
123
143
  ops = list(flatten(*(convert_block(b, n_qubits, config) for b in block.blocks)))
124
144
  if isinstance(block, AddBlock):
@@ -142,14 +162,14 @@ def convert_block(
142
162
  if isinstance(block, U):
143
163
  op = pyq_cls(qubit_support[0], *config.get_param_name(block))
144
164
  else:
145
- op = pyq_cls(qubit_support[0], config.get_param_name(block)[0])
165
+ op = pyq_cls(qubit_support[0], extract_parameter(block, config))
146
166
  else:
147
167
  op = pyq_cls(qubit_support[0])
148
168
  return [op]
149
169
  elif isinstance(block, tuple(two_qubit_gateset)):
150
170
  pyq_cls = getattr(pyq, block.name)
151
171
  if isinstance(block, ParametricBlock):
152
- op = pyq_cls(qubit_support[0], qubit_support[1], config.get_param_name(block)[0])
172
+ op = pyq_cls(qubit_support[0], qubit_support[1], extract_parameter(block, config))
153
173
  else:
154
174
  op = pyq_cls(qubit_support[0], qubit_support[1])
155
175
  return [op]
@@ -157,7 +177,7 @@ def convert_block(
157
177
  block_name = block.name[1:] if block.name.startswith("M") else block.name
158
178
  pyq_cls = getattr(pyq, block_name)
159
179
  if isinstance(block, ParametricBlock):
160
- op = pyq_cls(qubit_support[:-1], qubit_support[-1], config.get_param_name(block)[0])
180
+ op = pyq_cls(qubit_support[:-1], qubit_support[-1], extract_parameter(block, config))
161
181
  else:
162
182
  if "CSWAP" in block_name:
163
183
  op = pyq_cls(qubit_support[:-2], qubit_support[-2:])
@@ -172,7 +192,7 @@ def convert_block(
172
192
  )
173
193
 
174
194
 
175
- class PyQHamiltonianEvolution(Module):
195
+ class PyQTimeDependentEvolution(Module):
176
196
  def __init__(
177
197
  self,
178
198
  qubit_support: Tuple[int, ...],
@@ -188,50 +208,17 @@ class PyQHamiltonianEvolution(Module):
188
208
  self.hmat: Tensor
189
209
  self.config = config
190
210
 
191
- if isinstance(block.generator, AbstractBlock) and not block.generator.is_parametric:
192
- hmat = block_to_tensor(
193
- block.generator,
194
- qubit_support=self.qubit_support,
195
- use_full_support=False,
196
- )
197
- hmat = hmat.permute(1, 2, 0)
198
- self.register_buffer("hmat", hmat)
199
- self._hamiltonian = lambda self, values: self.hmat
200
-
201
- elif isinstance(block.generator, Tensor):
202
- m = block.generator.to(dtype=cdouble)
203
- hmat = block_to_tensor(
204
- MatrixBlock(
205
- m,
206
- qubit_support=block.qubit_support,
207
- check_unitary=False,
208
- check_hermitian=True,
209
- ),
211
+ def _hamiltonian(self: PyQTimeDependentEvolution, values: dict[str, Tensor]) -> Tensor:
212
+ hmat = _block_to_tensor_embedded(
213
+ block.generator, # type: ignore[arg-type]
214
+ values=values,
210
215
  qubit_support=self.qubit_support,
211
216
  use_full_support=False,
217
+ device=self.device,
212
218
  )
213
- hmat = hmat.permute(1, 2, 0)
214
- self.register_buffer("hmat", hmat)
215
- self._hamiltonian = lambda self, values: self.hmat
216
-
217
- elif isinstance(block.generator, sympy.Basic):
218
- self._hamiltonian = (
219
- lambda self, values: values[self.param_names[1]].squeeze(3).permute(1, 2, 0)
220
- )
221
- # FIXME Why are we squeezing
222
- else:
223
-
224
- def _hamiltonian(self: PyQHamiltonianEvolution, values: dict[str, Tensor]) -> Tensor:
225
- hmat = _block_to_tensor_embedded(
226
- block.generator, # type: ignore[arg-type]
227
- values=values,
228
- qubit_support=self.qubit_support,
229
- use_full_support=False,
230
- device=self.device,
231
- )
232
- return hmat.permute(1, 2, 0)
219
+ return hmat.permute(1, 2, 0)
233
220
 
234
- self._hamiltonian = _hamiltonian
221
+ self._hamiltonian = _hamiltonian
235
222
 
236
223
  self._time_evolution = lambda values: values[self.param_names[0]]
237
224
  self._device: torch_device = (
@@ -322,61 +309,51 @@ class PyQHamiltonianEvolution(Module):
322
309
  values: dict[str, Tensor] | ParameterDict = dict(),
323
310
  embedding: Embedding | None = None,
324
311
  ) -> Tensor:
325
- if getattr(self.block.generator, "is_time_dependent", False): # type: ignore [union-attr]
326
-
327
- def Ht(t: Tensor | float) -> Tensor:
328
- # values dict has to change with new value of t
329
- # initial value of a feature parameter inside generator block
330
- # has to be inferred here
331
- new_vals = dict()
332
- for str_expr, val in values.items():
333
- expr = sympy.sympify(str_expr)
334
- t_symb = sympy.Symbol(self._get_time_parameter())
335
- free_symbols = expr.free_symbols
336
- if t_symb in free_symbols:
337
- # create substitution list for time and feature params
338
- subs_list = [(t_symb, t)]
339
-
340
- if len(free_symbols) > 1:
341
- # get feature param symbols
342
- feat_symbols = free_symbols.difference(set([t_symb]))
343
-
344
- # get feature param values
345
- feat_vals = values["orig_param_values"]
346
-
347
- # update substitution list with feature param values
348
- for fs in feat_symbols:
349
- subs_list.append((fs, feat_vals[str(fs)]))
350
-
351
- # evaluate expression with new time param value
352
- new_vals[str_expr] = torch.tensor(float(expr.subs(subs_list)))
353
- else:
354
- # expression doesn't contain time parameter - copy it as is
355
- new_vals[str_expr] = val
356
-
357
- # get matrix form of generator
358
- hmat = _block_to_tensor_embedded(
359
- self.block.generator, # type: ignore[arg-type]
360
- values=new_vals,
361
- qubit_support=self.qubit_support,
362
- use_full_support=False,
363
- device=self.device,
364
- ).squeeze(0)
365
-
366
- return hmat
367
-
368
- tsave = torch.linspace(0, self.block.duration, self.config.n_steps_hevo) # type: ignore [attr-defined]
369
- result = pyqify(
370
- sesolve(Ht, unpyqify(state).T[:, 0:1], tsave, self.config.ode_solver).states[-1].T
371
- )
372
- else:
373
- result = apply_operator(
374
- state,
375
- self.unitary(values),
376
- self.qubit_support,
377
- self.n_qubits,
378
- self.batch_size,
379
- )
312
+ def Ht(t: Tensor | float) -> Tensor:
313
+ # values dict has to change with new value of t
314
+ # initial value of a feature parameter inside generator block
315
+ # has to be inferred here
316
+ new_vals = dict()
317
+ for str_expr, val in values.items():
318
+ expr = sympy.sympify(str_expr)
319
+ t_symb = sympy.Symbol(self._get_time_parameter())
320
+ free_symbols = expr.free_symbols
321
+ if t_symb in free_symbols:
322
+ # create substitution list for time and feature params
323
+ subs_list = [(t_symb, t)]
324
+
325
+ if len(free_symbols) > 1:
326
+ # get feature param symbols
327
+ feat_symbols = free_symbols.difference(set([t_symb]))
328
+
329
+ # get feature param values
330
+ feat_vals = values["orig_param_values"]
331
+
332
+ # update substitution list with feature param values
333
+ for fs in feat_symbols:
334
+ subs_list.append((fs, feat_vals[str(fs)]))
335
+
336
+ # evaluate expression with new time param value
337
+ new_vals[str_expr] = torch.tensor(float(expr.subs(subs_list)))
338
+ else:
339
+ # expression doesn't contain time parameter - copy it as is
340
+ new_vals[str_expr] = val
341
+
342
+ # get matrix form of generator
343
+ hmat = _block_to_tensor_embedded(
344
+ self.block.generator, # type: ignore[arg-type]
345
+ values=new_vals,
346
+ qubit_support=self.qubit_support,
347
+ use_full_support=False,
348
+ device=self.device,
349
+ ).squeeze(0)
350
+
351
+ return hmat
352
+
353
+ tsave = torch.linspace(0, self.block.duration, self.config.n_steps_hevo) # type: ignore [attr-defined]
354
+ result = pyqify(
355
+ sesolve(Ht, unpyqify(state).T[:, 0:1], tsave, self.config.ode_solver).states[-1].T
356
+ )
380
357
 
381
358
  return result
382
359
 
@@ -388,7 +365,7 @@ class PyQHamiltonianEvolution(Module):
388
365
  def dtype(self) -> torch_dtype:
389
366
  return self._dtype
390
367
 
391
- def to(self, *args: Any, **kwargs: Any) -> PyQHamiltonianEvolution:
368
+ def to(self, *args: Any, **kwargs: Any) -> PyQTimeDependentEvolution:
392
369
  if hasattr(self, "hmat"):
393
370
  self.hmat = self.hmat.to(*args, **kwargs)
394
371
  self._device = self.hmat.device
qadence/backends/utils.py CHANGED
@@ -9,7 +9,7 @@ import pyqtorch as pyq
9
9
  import torch
10
10
  from numpy.typing import ArrayLike
11
11
  from pyqtorch.apply import apply_operator
12
- from pyqtorch.parametric import Parametric as PyQParametric
12
+ from pyqtorch.primitives import Parametric as PyQParametric
13
13
  from torch import (
14
14
  Tensor,
15
15
  cat,
@@ -129,9 +129,11 @@ class CompositeBlock(AbstractBlock):
129
129
  from qadence.blocks.utils import _construct, tag
130
130
 
131
131
  blocks = [
132
- getattr(operations, b["type"])._from_dict(b)
133
- if hasattr(operations, b["type"])
134
- else getattr(qadenceblocks, b["type"])._from_dict(b)
132
+ (
133
+ getattr(operations, b["type"])._from_dict(b)
134
+ if hasattr(operations, b["type"])
135
+ else getattr(qadenceblocks, b["type"])._from_dict(b)
136
+ )
135
137
  for b in d["blocks"]
136
138
  ]
137
139
  block = _construct(cls, blocks) # type: ignore[arg-type]
qadence/blocks/utils.py CHANGED
@@ -263,11 +263,29 @@ def expression_to_uuids(block: AbstractBlock) -> dict[Expr, list[str]]:
263
263
  return expr_to_uuid
264
264
 
265
265
 
266
- def uuid_to_eigen(block: AbstractBlock) -> dict[str, Tensor]:
266
+ def uuid_to_eigen(
267
+ block: AbstractBlock, rescale_eigenvals_timeevo: bool = False
268
+ ) -> dict[str, Tensor]:
267
269
  """Creates a mapping between a parametric block's param_id and its' eigenvalues.
268
270
 
269
271
  This method is needed for constructing the PSR rules for a given block.
270
272
 
273
+ A PSR shift factor is also added in the mapping for dealing
274
+ with the time evolution case as it requires rescaling.
275
+
276
+ Args:
277
+ block (AbstractBlock): Block input
278
+ rescale_eigenvals_timeevo (bool, optional): If True, rescale
279
+ eigenvalues and shift factor
280
+ by 2 times spectral gap
281
+ for the TimeEvolutionBlock case to allow
282
+ differientiating with Hamevo.
283
+ Defaults to False.
284
+
285
+ Returns:
286
+ dict[str, Tensor]: Mapping between block's param_id, eigenvalues and
287
+ PSR shift.
288
+
271
289
  !!! warn
272
290
  Will ignore eigenvalues of AnalogBlocks that are not yet computed.
273
291
  """
@@ -276,7 +294,23 @@ def uuid_to_eigen(block: AbstractBlock) -> dict[str, Tensor]:
276
294
  for uuid, b in uuid_to_block(block).items():
277
295
  if b.eigenvalues_generator is not None:
278
296
  if b.eigenvalues_generator.numel() > 0:
279
- result[uuid] = b.eigenvalues_generator
297
+ # GPSR assumes a factor 0.5 for differentiation
298
+ # so need rescaling
299
+ if isinstance(b, TimeEvolutionBlock) and rescale_eigenvals_timeevo:
300
+ if b.eigenvalues_generator.numel() > 1:
301
+ result[uuid] = (
302
+ b.eigenvalues_generator * 2.0,
303
+ 0.5,
304
+ )
305
+ else:
306
+ result[uuid] = (
307
+ b.eigenvalues_generator * 2.0,
308
+ 1.0 / (b.eigenvalues_generator.item() * 2.0)
309
+ if len(b.eigenvalues_generator) == 1
310
+ else 1.0,
311
+ )
312
+ else:
313
+ result[uuid] = (b.eigenvalues_generator, 1.0)
280
314
 
281
315
  # leave only angle parameter uuid with eigenvals for ConstantAnalogRotation block
282
316
  if isinstance(block, ConstantAnalogRotation):
@@ -7,61 +7,59 @@ import sympy
7
7
  from qadence.blocks import KronBlock, kron
8
8
  from qadence.operations import RY
9
9
  from qadence.parameters import FeatureParameter, Parameter
10
- from qadence.types import PI
10
+ from qadence.types import PI, BasisSet, MultivariateStrategy, ReuploadScaling
11
11
 
12
12
 
13
- def generator_prefactor(spectrum: str, qubit_index: int) -> float | int:
13
+ def generator_prefactor(reupload_scaling: ReuploadScaling, qubit_index: int) -> float | int:
14
14
  """Converts a spectrum string, e.g. tower or exponential.
15
15
 
16
16
  The result is the correct generator prefactor.
17
17
  """
18
- spectrum = spectrum.lower()
19
18
  conversion_dict: dict[str, float | int] = {
20
- "simple": 1,
21
- "tower": qubit_index + 1,
22
- "exponential": 2 * PI / (2 ** (qubit_index + 1)),
19
+ ReuploadScaling.CONSTANT: 1,
20
+ ReuploadScaling.TOWER: qubit_index + 1,
21
+ ReuploadScaling.EXP: 2 * PI / (2 ** (qubit_index + 1)),
23
22
  }
24
- return conversion_dict[spectrum]
23
+ return conversion_dict[reupload_scaling]
25
24
 
26
25
 
27
- def basis_func(basis: str, x: Parameter) -> Parameter | sympy.Expr:
28
- basis = basis.lower()
26
+ def basis_func(basis: BasisSet, x: Parameter) -> Parameter | sympy.Expr:
29
27
  conversion_dict: dict[str, Parameter | sympy.Expr] = {
30
- "fourier": x,
31
- "chebyshev": 2 * sympy.acos(x),
28
+ BasisSet.FOURIER: x,
29
+ BasisSet.CHEBYSHEV: 2 * sympy.acos(x),
32
30
  }
33
31
  return conversion_dict[basis]
34
32
 
35
33
 
36
34
  def build_idx_fms(
37
- basis: str,
35
+ basis: BasisSet,
38
36
  fm_pauli: Type[RY],
39
- fm_strategy: str,
37
+ multivariate_strategy: MultivariateStrategy,
40
38
  n_features: int,
41
39
  n_qubits: int,
42
- spectrum: str,
40
+ reupload_scaling: ReuploadScaling,
43
41
  ) -> list[KronBlock]:
44
42
  """Builds the index feature maps based on the given parameters.
45
43
 
46
44
  Args:
47
- basis (str): Type of basis chosen for the feature map.
45
+ basis (BasisSet): Type of basis chosen for the feature map.
48
46
  fm_pauli (PrimitiveBlock type): The chosen Pauli rotation type.
49
- fm_strategy (str): The feature map strategy to be used. Possible values are
50
- 'parallel' or 'serial'.
47
+ multivariate_strategy (MultivariateStrategy): The strategy used for encoding
48
+ the multivariate feature map.
51
49
  n_features (int): The number of features.
52
50
  n_qubits (int): The number of qubits.
53
- spectrum (str): The chosen spectrum.
51
+ reupload_scaling (ReuploadScaling): The chosen scaling for the reupload.
54
52
 
55
53
  Returns:
56
54
  List[KronBlock]: The list of index feature maps.
57
55
  """
58
56
  idx_fms = []
59
57
  for i in range(n_features):
60
- target_qubits = get_fm_qubits(fm_strategy, i, n_qubits, n_features)
58
+ target_qubits = get_fm_qubits(multivariate_strategy, i, n_qubits, n_features)
61
59
  param = FeatureParameter(f"x{i}")
62
60
  block = kron(
63
61
  *[
64
- fm_pauli(qubit, generator_prefactor(spectrum, j) * basis_func(basis, param))
62
+ fm_pauli(qubit, generator_prefactor(reupload_scaling, j) * basis_func(basis, param))
65
63
  for j, qubit in enumerate(target_qubits)
66
64
  ]
67
65
  )
@@ -70,12 +68,14 @@ def build_idx_fms(
70
68
  return idx_fms
71
69
 
72
70
 
73
- def get_fm_qubits(fm_strategy: str, i: int, n_qubits: int, n_features: int) -> Iterable:
71
+ def get_fm_qubits(
72
+ multivariate_strategy: MultivariateStrategy, i: int, n_qubits: int, n_features: int
73
+ ) -> Iterable:
74
74
  """Returns the list of target qubits for the given feature map strategy and feature index.
75
75
 
76
76
  Args:
77
- fm_strategy (str): The feature map strategy to be used. Possible values
78
- are 'parallel' or 'serial'.
77
+ multivariate_strategy (MultivariateStrategy): The strategy used for encoding
78
+ the multivariate feature map.
79
79
  i (int): The feature index.
80
80
  n_qubits (int): The number of qubits.
81
81
  n_features (int): The number of features.
@@ -86,11 +86,11 @@ def get_fm_qubits(fm_strategy: str, i: int, n_qubits: int, n_features: int) -> I
86
86
  Raises:
87
87
  ValueError: If the feature map strategy is not implemented.
88
88
  """
89
- if fm_strategy == "parallel":
89
+ if multivariate_strategy == MultivariateStrategy.PARALLEL:
90
90
  n_qubits_per_feature = int(n_qubits / n_features)
91
91
  target_qubits = range(i * n_qubits_per_feature, (i + 1) * n_qubits_per_feature)
92
- elif fm_strategy == "serial":
92
+ elif multivariate_strategy == MultivariateStrategy.SERIES:
93
93
  target_qubits = range(0, n_qubits)
94
94
  else:
95
- raise ValueError(f"Feature map strategy {fm_strategy} not implemented.")
95
+ raise ValueError(f"Multivariate strategy {multivariate_strategy} not implemented.")
96
96
  return target_qubits
@@ -52,7 +52,7 @@ class DifferentiableExpectation:
52
52
  return expectation_fn(state, values, psr_params)
53
53
 
54
54
  uuid_to_eigs = {
55
- k: tensor_to_jnp(v) for k, v in uuid_to_eigen(self.circuit.abstract.block).items()
55
+ k: tensor_to_jnp(v[0]) for k, v in uuid_to_eigen(self.circuit.abstract.block).items()
56
56
  }
57
57
  self.psr_params = {
58
58
  k: self.param_values[k] for k in uuid_to_eigs.keys()