-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
n_local.py
1071 lines (890 loc) · 42.5 KB
/
n_local.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2020.
#
# This code is licensed under the Apache License, Version 2.0. You may
# obtain a copy of this license in the LICENSE.txt file in the root directory
# of this source tree or at http://www.apache.org/licenses/LICENSE-2.0.
#
# Any modifications or derivative works of this code must retain this
# copyright notice, and modified files need to carry a notice indicating
# that they have been altered from the originals.
"""The n-local circuit class."""
from __future__ import annotations
import collections
import itertools
import typing
from collections.abc import Callable, Mapping, Sequence
import numpy
from qiskit.circuit.quantumcircuit import QuantumCircuit
from qiskit.circuit.quantumregister import QuantumRegister
from qiskit.circuit import (
Instruction,
Parameter,
ParameterVector,
ParameterExpression,
CircuitInstruction,
)
from qiskit.exceptions import QiskitError
from qiskit.circuit.library.standard_gates import get_standard_gate_name_mapping
from qiskit._accelerate.circuit_library import get_entangler_map as fast_entangler_map
from ..blueprintcircuit import BlueprintCircuit
if typing.TYPE_CHECKING:
import qiskit # pylint: disable=cyclic-import
class NLocal(BlueprintCircuit):
"""The n-local circuit class.
The structure of the n-local circuit are alternating rotation and entanglement layers.
In both layers, parameterized circuit-blocks act on the circuit in a defined way.
In the rotation layer, the blocks are applied stacked on top of each other, while in the
entanglement layer according to the ``entanglement`` strategy.
The circuit blocks can have arbitrary sizes (smaller equal to the number of qubits in the
circuit). Each layer is repeated ``reps`` times, and by default a final rotation layer is
appended.
For instance, a rotation block on 2 qubits and an entanglement block on 4 qubits using
``'linear'`` entanglement yields the following circuit.
.. parsed-literal::
┌──────┐ ░ ┌──────┐ ░ ┌──────┐
┤0 ├─░─┤0 ├──────────────── ... ─░─┤0 ├
│ Rot │ ░ │ │┌──────┐ ░ │ Rot │
┤1 ├─░─┤1 ├┤0 ├──────── ... ─░─┤1 ├
├──────┤ ░ │ Ent ││ │┌──────┐ ░ ├──────┤
┤0 ├─░─┤2 ├┤1 ├┤0 ├ ... ─░─┤0 ├
│ Rot │ ░ │ ││ Ent ││ │ ░ │ Rot │
┤1 ├─░─┤3 ├┤2 ├┤1 ├ ... ─░─┤1 ├
├──────┤ ░ └──────┘│ ││ Ent │ ░ ├──────┤
┤0 ├─░─────────┤3 ├┤2 ├ ... ─░─┤0 ├
│ Rot │ ░ └──────┘│ │ ░ │ Rot │
┤1 ├─░─────────────────┤3 ├ ... ─░─┤1 ├
└──────┘ ░ └──────┘ ░ └──────┘
| |
+---------------------------------+
repeated reps times
If specified, barriers can be inserted in between every block.
If an initial state object is provided, it is added in front of the NLocal.
"""
def __init__(
self,
num_qubits: int | None = None,
rotation_blocks: (
QuantumCircuit
| list[QuantumCircuit]
| qiskit.circuit.Instruction
| list[qiskit.circuit.Instruction]
| None
) = None,
entanglement_blocks: (
QuantumCircuit
| list[QuantumCircuit]
| qiskit.circuit.Instruction
| list[qiskit.circuit.Instruction]
| None
) = None,
entanglement: list[int] | list[list[int]] | None = None,
reps: int = 1,
insert_barriers: bool = False,
parameter_prefix: str = "θ",
overwrite_block_parameters: bool | list[list[Parameter]] = True,
skip_final_rotation_layer: bool = False,
skip_unentangled_qubits: bool = False,
initial_state: QuantumCircuit | None = None,
name: str | None = "nlocal",
flatten: bool | None = None,
) -> None:
"""
Args:
num_qubits: The number of qubits of the circuit.
rotation_blocks: The blocks used in the rotation layers. If multiple are passed,
these will be applied one after another (like new sub-layers).
entanglement_blocks: The blocks used in the entanglement layers. If multiple are passed,
these will be applied one after another. To use different entanglements for
the sub-layers, see :meth:`get_entangler_map`.
entanglement: The indices specifying on which qubits the input blocks act. If ``None``, the
entanglement blocks are applied at the top of the circuit.
reps: Specifies how often the rotation blocks and entanglement blocks are repeated.
insert_barriers: If ``True``, barriers are inserted in between each layer. If ``False``,
no barriers are inserted.
parameter_prefix: The prefix used if default parameters are generated.
overwrite_block_parameters: If the parameters in the added blocks should be overwritten.
If ``False``, the parameters in the blocks are not changed.
skip_final_rotation_layer: Whether a final rotation layer is added to the circuit.
skip_unentangled_qubits: If ``True``, the rotation gates act only on qubits that
are entangled. If ``False``, the rotation gates act on all qubits.
initial_state: A :class:`.QuantumCircuit` object which can be used to describe an initial
state prepended to the NLocal circuit.
name: The name of the circuit.
flatten: Set this to ``True`` to output a flat circuit instead of nesting it inside multiple
layers of gate objects. By default currently the contents of
the output circuit will be wrapped in nested objects for
cleaner visualization. However, if you're using this circuit
for anything besides visualization its **strongly** recommended
to set this flag to ``True`` to avoid a large performance
overhead for parameter binding.
Raises:
ValueError: If ``reps`` parameter is less than or equal to 0.
TypeError: If ``reps`` parameter is not an int value.
"""
super().__init__(name=name)
self._num_qubits: int | None = None
self._insert_barriers = insert_barriers
self._reps = reps
self._entanglement_blocks: list[QuantumCircuit] = []
self._rotation_blocks: list[QuantumCircuit] = []
self._prepended_blocks: list[QuantumCircuit] = []
self._prepended_entanglement: list[list[list[int]] | str] = []
self._appended_blocks: list[QuantumCircuit] = []
self._appended_entanglement: list[list[list[int]] | str] = []
self._entanglement = None
self._entangler_maps = None
self._ordered_parameters: ParameterVector | list[Parameter] = ParameterVector(
name=parameter_prefix
)
self._overwrite_block_parameters = overwrite_block_parameters
self._skip_final_rotation_layer = skip_final_rotation_layer
self._skip_unentangled_qubits = skip_unentangled_qubits
self._initial_state: QuantumCircuit | None = None
self._initial_state_circuit: QuantumCircuit | None = None
self._bounds: list[tuple[float | None, float | None]] | None = None
self._flatten = flatten
# During the build, if a subclass hasn't overridden our parametrization methods, we can use
# a newer fast-path method to parametrise the rotation and entanglement blocks if internally
# those are just simple stdlib gates that have been promoted to circuits. We don't
# precalculate the fast-path layers themselves because there's far too much that can be
# overridden between object construction and build, and far too many subclasses of `NLocal`
# that override bits and bobs of the internal private methods, so it'd be too hard to keep
# everything in sync.
self._allow_fast_path_parametrization = (
getattr(self._parameter_generator, "__func__", None) is NLocal._parameter_generator
)
if int(reps) != reps:
raise TypeError("The value of reps should be int")
if reps < 0:
raise ValueError("The value of reps should be larger than or equal to 0")
if num_qubits is not None:
self.num_qubits = num_qubits
if entanglement_blocks is not None:
self.entanglement_blocks = entanglement_blocks
if rotation_blocks is not None:
self.rotation_blocks = rotation_blocks
if entanglement is not None:
self.entanglement = entanglement
if initial_state is not None:
self.initial_state = initial_state
@property
def num_qubits(self) -> int:
"""Returns the number of qubits in this circuit.
Returns:
The number of qubits.
"""
return self._num_qubits if self._num_qubits is not None else 0
@num_qubits.setter
def num_qubits(self, num_qubits: int) -> None:
"""Set the number of qubits for the n-local circuit.
Args:
The new number of qubits.
"""
if self._num_qubits != num_qubits:
# invalidate the circuit
self._invalidate()
self._num_qubits = num_qubits
self.qregs = [QuantumRegister(num_qubits, name="q")]
@property
def flatten(self) -> bool:
"""Returns whether the circuit is wrapped in nested gates/instructions or flattened."""
return bool(self._flatten)
@flatten.setter
def flatten(self, flatten: bool) -> None:
self._invalidate()
self._flatten = flatten
def _convert_to_block(self, layer: typing.Any) -> QuantumCircuit:
"""Try to convert ``layer`` to a QuantumCircuit.
Args:
layer: The object to be converted to an NLocal block / Instruction.
Returns:
The layer converted to a circuit.
Raises:
TypeError: If the input cannot be converted to a circuit.
"""
if isinstance(layer, QuantumCircuit):
return layer
if isinstance(layer, Instruction):
circuit = QuantumCircuit(layer.num_qubits)
circuit.append(layer, list(range(layer.num_qubits)))
return circuit
try:
circuit = QuantumCircuit(layer.num_qubits)
circuit.append(layer.to_instruction(), list(range(layer.num_qubits)))
return circuit
except AttributeError:
pass
raise TypeError(f"Adding a {type(layer)} to an NLocal is not supported.")
@property
def rotation_blocks(self) -> list[QuantumCircuit]:
"""The blocks in the rotation layers.
Returns:
The blocks in the rotation layers.
"""
return self._rotation_blocks
@rotation_blocks.setter
def rotation_blocks(
self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction]
) -> None:
"""Set the blocks in the rotation layers.
Args:
blocks: The new blocks for the rotation layers.
"""
# cannot check for the attribute ``'__len__'`` because a circuit also has this attribute
if not isinstance(blocks, (list, numpy.ndarray)):
blocks = [blocks]
self._invalidate()
self._rotation_blocks = [self._convert_to_block(block) for block in blocks]
@property
def entanglement_blocks(self) -> list[QuantumCircuit]:
"""The blocks in the entanglement layers.
Returns:
The blocks in the entanglement layers.
"""
return self._entanglement_blocks
@entanglement_blocks.setter
def entanglement_blocks(
self, blocks: QuantumCircuit | list[QuantumCircuit] | Instruction | list[Instruction]
) -> None:
"""Set the blocks in the entanglement layers.
Args:
blocks: The new blocks for the entanglement layers.
"""
# cannot check for the attribute ``'__len__'`` because a circuit also has this attribute
if not isinstance(blocks, (list, numpy.ndarray)):
blocks = [blocks]
self._invalidate()
self._entanglement_blocks = [self._convert_to_block(block) for block in blocks]
@property
def entanglement(
self,
) -> (
str
| list[str]
| list[list[str]]
| list[int]
| list[list[int]]
| list[list[list[int]]]
| list[list[list[list[int]]]]
| Callable[[int], str]
| Callable[[int], list[list[int]]]
):
"""Get the entanglement strategy.
Returns:
The entanglement strategy, see :meth:`get_entangler_map` for more detail on how the
format is interpreted.
"""
return self._entanglement
@entanglement.setter
def entanglement(
self,
entanglement: (
str
| list[str]
| list[list[str]]
| list[int]
| list[list[int]]
| list[list[list[int]]]
| list[list[list[list[int]]]]
| Callable[[int], str]
| Callable[[int], list[list[int]]]
| None
),
) -> None:
"""Set the entanglement strategy.
Args:
entanglement: The entanglement strategy. See :meth:`get_entangler_map` for more detail
on the supported formats.
"""
self._invalidate()
self._entanglement = entanglement
@property
def num_layers(self) -> int:
"""Return the number of layers in the n-local circuit.
Returns:
The number of layers in the circuit.
"""
return 2 * self._reps + int(not self._skip_final_rotation_layer)
def _check_configuration(self, raise_on_failure: bool = True) -> bool:
"""Check if the configuration of the NLocal class is valid.
Args:
raise_on_failure: Whether to raise on failure.
Returns:
True, if the configuration is valid and the circuit can be constructed. Otherwise
an ValueError is raised.
Raises:
ValueError: If the blocks are not set.
ValueError: If the number of repetitions is not set.
ValueError: If the qubit indices are not set.
ValueError: If the number of qubit indices does not match the number of blocks.
ValueError: If an index in the repetitions list exceeds the number of blocks.
ValueError: If the number of repetitions does not match the number of block-wise
parameters.
ValueError: If a specified qubit index is larger than the (manually set) number of
qubits.
"""
valid = True
if self.num_qubits is None:
valid = False
if raise_on_failure:
raise ValueError("No number of qubits specified.")
# check no needed parameters are None
if self.entanglement_blocks is None and self.rotation_blocks is None:
valid = False
if raise_on_failure:
raise ValueError("The blocks are not set.")
return valid
@property
def ordered_parameters(self) -> list[Parameter]:
"""The parameters used in the underlying circuit.
This includes float values and duplicates.
Examples:
>>> # prepare circuit ...
>>> print(nlocal)
┌───────┐┌──────────┐┌──────────┐┌──────────┐
q_0: ┤ Ry(1) ├┤ Ry(θ[1]) ├┤ Ry(θ[1]) ├┤ Ry(θ[3]) ├
└───────┘└──────────┘└──────────┘└──────────┘
>>> nlocal.parameters
{Parameter(θ[1]), Parameter(θ[3])}
>>> nlocal.ordered_parameters
[1, Parameter(θ[1]), Parameter(θ[1]), Parameter(θ[3])]
Returns:
The parameters objects used in the circuit.
"""
if isinstance(self._ordered_parameters, ParameterVector):
self._ordered_parameters.resize(self.num_parameters_settable)
return list(self._ordered_parameters)
return self._ordered_parameters
@ordered_parameters.setter
def ordered_parameters(self, parameters: ParameterVector | list[Parameter]) -> None:
"""Set the parameters used in the underlying circuit.
Args:
The parameters to be used in the underlying circuit.
Raises:
ValueError: If the length of ordered parameters does not match the number of
parameters in the circuit and they are not a ``ParameterVector`` (which could
be resized to fit the number of parameters).
"""
if (
not isinstance(parameters, ParameterVector)
and len(parameters) != self.num_parameters_settable
):
raise ValueError(
"The length of ordered parameters must be equal to the number of "
f"settable parameters in the circuit ({self.num_parameters_settable}),"
f" but is {len(parameters)}"
)
self._ordered_parameters = parameters
self._invalidate()
@property
def insert_barriers(self) -> bool:
"""If barriers are inserted in between the layers or not.
Returns:
``True``, if barriers are inserted in between the layers, ``False`` if not.
"""
return self._insert_barriers
@insert_barriers.setter
def insert_barriers(self, insert_barriers: bool) -> None:
"""Specify whether barriers should be inserted in between the layers or not.
Args:
insert_barriers: If True, barriers are inserted, if False not.
"""
# if insert_barriers changes, we have to invalidate the circuit definition,
# if it is the same as before we can leave the NLocal instance as it is
if insert_barriers is not self._insert_barriers:
self._invalidate()
self._insert_barriers = insert_barriers
def get_unentangled_qubits(self) -> set[int]:
"""Get the indices of unentangled qubits in a set.
Returns:
The unentangled qubits.
"""
entangled_qubits = set()
for i in range(self._reps):
for j, block in enumerate(self.entanglement_blocks):
entangler_map = self.get_entangler_map(i, j, block.num_qubits)
entangled_qubits.update([idx for indices in entangler_map for idx in indices])
unentangled_qubits = set(range(self.num_qubits)) - entangled_qubits
return unentangled_qubits
@property
def num_parameters_settable(self) -> int:
"""The number of total parameters that can be set to distinct values.
This does not change when the parameters are bound or exchanged for same parameters,
and therefore is different from ``num_parameters`` which counts the number of unique
:class:`~qiskit.circuit.Parameter` objects currently in the circuit.
Returns:
The number of parameters originally available in the circuit.
Note:
This quantity does not require the circuit to be built yet.
"""
num = 0
for i in range(self._reps):
for j, block in enumerate(self.entanglement_blocks):
entangler_map = self.get_entangler_map(i, j, block.num_qubits)
num += len(entangler_map) * len(get_parameters(block))
if self._skip_unentangled_qubits:
unentangled_qubits = self.get_unentangled_qubits()
num_rot = 0
for block in self.rotation_blocks:
block_indices = [
list(range(j * block.num_qubits, (j + 1) * block.num_qubits))
for j in range(self.num_qubits // block.num_qubits)
]
if self._skip_unentangled_qubits:
block_indices = [
indices
for indices in block_indices
if set(indices).isdisjoint(unentangled_qubits)
]
num_rot += len(block_indices) * len(get_parameters(block))
num += num_rot * (self._reps + int(not self._skip_final_rotation_layer))
return num
@property
def reps(self) -> int:
"""The number of times rotation and entanglement block are repeated.
Returns:
The number of repetitions.
"""
return self._reps
@reps.setter
def reps(self, repetitions: int) -> None:
"""Set the repetitions.
If the repetitions are `0`, only one rotation layer with no entanglement
layers is applied (unless ``self.skip_final_rotation_layer`` is set to ``True``).
Args:
repetitions: The new repetitions.
Raises:
ValueError: If reps setter has parameter repetitions < 0.
"""
if repetitions < 0:
raise ValueError("The repetitions should be larger than or equal to 0")
if repetitions != self._reps:
self._invalidate()
self._reps = repetitions
def print_settings(self) -> str:
"""Returns information about the setting.
Returns:
The class name and the attributes/parameters of the instance as ``str``.
"""
ret = f"NLocal: {self.__class__.__name__}\n"
params = ""
for key, value in self.__dict__.items():
if key[0] == "_":
params += f"-- {key[1:]}: {value}\n"
ret += f"{params}"
return ret
@property
def preferred_init_points(self) -> list[float] | None:
"""The initial points for the parameters. Can be stored as initial guess in optimization.
Returns:
The initial values for the parameters, or None, if none have been set.
"""
return None
# pylint: disable=too-many-return-statements
def get_entangler_map(
self, rep_num: int, block_num: int, num_block_qubits: int
) -> Sequence[Sequence[int]]:
"""Get the entangler map for in the repetition ``rep_num`` and the block ``block_num``.
The entangler map for the current block is derived from the value of ``self.entanglement``.
Below the different cases are listed, where ``i`` and ``j`` denote the repetition number
and the block number, respectively, and ``n`` the number of qubits in the block.
=================================== ========================================================
entanglement type entangler map
=================================== ========================================================
``None`` ``[[0, ..., n - 1]]``
``str`` (e.g ``'full'``) the specified connectivity on ``n`` qubits
``List[int]`` [``entanglement``]
``List[List[int]]`` ``entanglement``
``List[List[List[int]]]`` ``entanglement[i]``
``List[List[List[List[int]]]]`` ``entanglement[i][j]``
``List[str]`` the connectivity specified in ``entanglement[i]``
``List[List[str]]`` the connectivity specified in ``entanglement[i][j]``
``Callable[int, str]`` same as ``List[str]``
``Callable[int, List[List[int]]]`` same as ``List[List[List[int]]]``
=================================== ========================================================
Note that all indices are to be taken modulo the length of the array they act on, i.e.
no out-of-bounds index error will be raised but we re-iterate from the beginning of the
list.
Args:
rep_num: The current repetition we are in.
block_num: The block number within the entanglement layers.
num_block_qubits: The number of qubits in the block.
Returns:
The entangler map for the current block in the current repetition.
Raises:
ValueError: If the value of ``entanglement`` could not be cast to a corresponding
entangler map.
"""
i, j, n = rep_num, block_num, num_block_qubits
entanglement = self._entanglement
# entanglement is None
if entanglement is None:
return [list(range(n))]
# entanglement is callable
if callable(entanglement):
entanglement = entanglement(i)
# entanglement is str
if isinstance(entanglement, str):
return get_entangler_map(n, self.num_qubits, entanglement, offset=i)
# check if entanglement is list of something
if not isinstance(entanglement, (tuple, list)):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
num_i = len(entanglement)
# entanglement is List[str]
if all(isinstance(en, str) for en in entanglement):
return get_entangler_map(n, self.num_qubits, entanglement[i % num_i], offset=i)
# entanglement is List[int]
if all(isinstance(en, (int, numpy.integer)) for en in entanglement):
return [[int(en) for en in entanglement]]
# check if entanglement is List[List]
if not all(isinstance(en, (tuple, list)) for en in entanglement):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
num_j = len(entanglement[i % num_i])
# entanglement is List[List[str]]
if all(isinstance(e2, str) for en in entanglement for e2 in en):
return get_entangler_map(
n, self.num_qubits, entanglement[i % num_i][j % num_j], offset=i
)
# entanglement is List[List[int]]
if all(isinstance(e2, (int, numpy.int32, numpy.int64)) for en in entanglement for e2 in en):
for ind, en in enumerate(entanglement):
entanglement[ind] = tuple(map(int, en))
return entanglement
# check if entanglement is List[List[List]]
if not all(isinstance(e2, (tuple, list)) for en in entanglement for e2 in en):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
# entanglement is List[List[List[int]]]
if all(
isinstance(e3, (int, numpy.int32, numpy.int64))
for en in entanglement
for e2 in en
for e3 in e2
):
for en in entanglement:
for ind, e2 in enumerate(en):
en[ind] = tuple(map(int, e2))
return entanglement[i % num_i]
# check if entanglement is List[List[List[List]]]
if not all(isinstance(e3, (tuple, list)) for en in entanglement for e2 in en for e3 in e2):
raise ValueError(f"Invalid value of entanglement: {entanglement}")
# entanglement is List[List[List[List[int]]]]
if all(
isinstance(e4, (int, numpy.int32, numpy.int64))
for en in entanglement
for e2 in en
for e3 in e2
for e4 in e3
):
for en in entanglement:
for e2 in en:
for ind, e3 in enumerate(e2):
e2[ind] = tuple(map(int, e3))
return entanglement[i % num_i][j % num_j]
raise ValueError(f"Invalid value of entanglement: {entanglement}")
@property
def initial_state(self) -> QuantumCircuit:
"""Return the initial state that is added in front of the n-local circuit.
Returns:
The initial state.
"""
return self._initial_state
@initial_state.setter
def initial_state(self, initial_state: QuantumCircuit) -> None:
"""Set the initial state.
Args:
initial_state: The new initial state.
Raises:
ValueError: If the number of qubits has been set before and the initial state
does not match the number of qubits.
"""
self._initial_state = initial_state
self._invalidate()
@property
def parameter_bounds(self) -> list[tuple[float, float]] | None:
"""The parameter bounds for the unbound parameters in the circuit.
Returns:
A list of pairs indicating the bounds, as (lower, upper). None indicates an unbounded
parameter in the corresponding direction. If ``None`` is returned, problem is fully
unbounded.
"""
if not self._is_built:
self._build()
return self._bounds
@parameter_bounds.setter
def parameter_bounds(self, bounds: list[tuple[float, float]]) -> None:
"""Set the parameter bounds.
Args:
bounds: The new parameter bounds.
"""
self._bounds = bounds
def add_layer(
self,
other: QuantumCircuit | qiskit.circuit.Instruction,
entanglement: list[int] | str | list[list[int]] | None = None,
front: bool = False,
) -> "NLocal":
"""Append another layer to the NLocal.
Args:
other: The layer to compose, can be another NLocal, an Instruction or Gate,
or a QuantumCircuit.
entanglement: The entanglement or qubit indices.
front: If True, ``other`` is appended to the front, else to the back.
Returns:
self, such that chained composes are possible.
Raises:
TypeError: If `other` is not compatible, i.e. is no Instruction and does not have a
`to_instruction` method.
"""
block = self._convert_to_block(other)
if entanglement is None:
entanglement = [list(range(block.num_qubits))]
elif isinstance(entanglement, list) and not isinstance(entanglement[0], list):
entanglement = [entanglement]
if front:
self._prepended_blocks += [block]
self._prepended_entanglement += [entanglement]
else:
self._appended_blocks += [block]
self._appended_entanglement += [entanglement]
if isinstance(entanglement, list):
num_qubits = 1 + max(max(indices) for indices in entanglement)
if num_qubits > self.num_qubits:
self._invalidate() # rebuild circuit
self.num_qubits = num_qubits
# modify the circuit accordingly
if front is False and self._is_built:
if self._insert_barriers and len(self.data) > 0:
self.barrier()
if isinstance(entanglement, str):
entangler_map: Sequence[Sequence[int]] = get_entangler_map(
block.num_qubits, self.num_qubits, entanglement
)
else:
entangler_map = entanglement
for i in entangler_map:
params = self.ordered_parameters[-len(get_parameters(block)) :]
parameterized_block = self._parameterize_block(block, params=params)
self.compose(parameterized_block, i, inplace=True, copy=False)
else:
# cannot prepend a block currently, just rebuild
self._invalidate()
return self
def assign_parameters(
self,
parameters: (
Mapping[Parameter, ParameterExpression | float] | Sequence[ParameterExpression | float]
),
inplace: bool = False,
**kwargs,
) -> QuantumCircuit | None:
"""Assign parameters to the n-local circuit.
This method also supports passing a list instead of a dictionary. If a list
is passed, the list must have the same length as the number of unbound parameters in
the circuit. The parameters are assigned in the order of the parameters in
:meth:`ordered_parameters`.
Returns:
A copy of the NLocal circuit with the specified parameters.
Raises:
AttributeError: If the parameters are given as list and do not match the number
of parameters.
"""
if parameters is None or len(parameters) == 0:
return self
if not self._is_built:
self._build()
return super().assign_parameters(parameters, inplace=inplace, **kwargs)
def _parameterize_block(
self, block, param_iter=None, rep_num=None, block_num=None, indices=None, params=None
):
"""Convert ``block`` to a circuit of correct width and parameterized using the iterator."""
if self._overwrite_block_parameters:
# check if special parameters should be used
# pylint: disable=assignment-from-none
if params is None:
params = self._parameter_generator(rep_num, block_num, indices)
if params is None:
params = [next(param_iter) for _ in range(len(get_parameters(block)))]
update = dict(zip(block.parameters, params))
return block.assign_parameters(update)
return block.copy()
def _build_rotation_layer(self, circuit, param_iter, i):
"""Build a rotation layer."""
# if the unentangled qubits are skipped, compute the set of qubits that are not entangled
if self._skip_unentangled_qubits:
skipped_qubits = self.get_unentangled_qubits()
else:
skipped_qubits = set()
target_qubits = circuit.qubits
# iterate over all rotation blocks
for j, block in enumerate(self.rotation_blocks):
skipped_blocks = {qubit // block.num_qubits for qubit in skipped_qubits}
if (
self._allow_fast_path_parametrization
and (simple_block := _stdlib_gate_from_simple_block(block)) is not None
):
all_qubits = (
tuple(target_qubits[k * block.num_qubits : (k + 1) * block.num_qubits])
for k in range(self.num_qubits // block.num_qubits)
if k not in skipped_blocks
)
for qubits in all_qubits:
instr = CircuitInstruction(
simple_block.gate(*itertools.islice(param_iter, simple_block.num_params)),
qubits,
)
circuit._append(instr)
else:
block_indices = [
list(range(k * block.num_qubits, (k + 1) * block.num_qubits))
for k in range(self.num_qubits // block.num_qubits)
if k not in skipped_blocks
]
# apply the operations in the layer
for indices in block_indices:
parameterized_block = self._parameterize_block(block, param_iter, i, j, indices)
circuit.compose(parameterized_block, indices, inplace=True, copy=False)
def _build_entanglement_layer(self, circuit, param_iter, i):
"""Build an entanglement layer."""
# iterate over all entanglement blocks
target_qubits = circuit.qubits
for j, block in enumerate(self.entanglement_blocks):
entangler_map = self.get_entangler_map(i, j, block.num_qubits)
if (
self._allow_fast_path_parametrization
and (simple_block := _stdlib_gate_from_simple_block(block)) is not None
):
for indices in entangler_map:
# It's actually nontrivially faster to use a listcomp and pass that to `tuple`
# than to pass a generator expression directly.
# pylint: disable=consider-using-generator
instr = CircuitInstruction(
simple_block.gate(*itertools.islice(param_iter, simple_block.num_params)),
tuple([target_qubits[i] for i in indices]),
)
circuit._append(instr)
else:
# apply the operations in the layer
for indices in entangler_map:
parameterized_block = self._parameterize_block(block, param_iter, i, j, indices)
circuit.compose(parameterized_block, indices, inplace=True, copy=False)
def _build_additional_layers(self, circuit, which):
if which == "appended":
blocks = self._appended_blocks
entanglements = self._appended_entanglement
elif which == "prepended":
blocks = reversed(self._prepended_blocks)
entanglements = reversed(self._prepended_entanglement)
else:
raise ValueError("`which` must be either `appended` or `prepended`.")
for block, ent in zip(blocks, entanglements):
if isinstance(ent, str):
ent = get_entangler_map(block.num_qubits, self.num_qubits, ent)
for indices in ent:
circuit.compose(block, indices, inplace=True, copy=False)
def _build(self) -> None:
"""If not already built, build the circuit."""
if self._is_built:
return
super()._build()
if self.num_qubits == 0:
return
if not self._flatten:
circuit = QuantumCircuit(*self.qregs, name=self.name)
else:
circuit = self
# use the initial state as starting circuit, if it is set
if self.initial_state:
circuit.compose(self.initial_state.copy(), inplace=True, copy=False)
param_iter = iter(self.ordered_parameters)
# build the prepended layers
self._build_additional_layers(circuit, "prepended")
# main loop to build the entanglement and rotation layers
for i in range(self.reps):
# insert barrier if specified and there is a preceding layer
if self._insert_barriers and (i > 0 or len(self._prepended_blocks) > 0):
circuit.barrier()
# build the rotation layer
self._build_rotation_layer(circuit, param_iter, i)
# barrier in between rotation and entanglement layer
if self._insert_barriers and len(self._rotation_blocks) > 0:
circuit.barrier()
# build the entanglement layer
self._build_entanglement_layer(circuit, param_iter, i)
# add the final rotation layer
if not self._skip_final_rotation_layer:
if self.insert_barriers and self.reps > 0:
circuit.barrier()
self._build_rotation_layer(circuit, param_iter, self.reps)
# add the appended layers
self._build_additional_layers(circuit, "appended")
# cast global phase to float if it has no free parameters
if isinstance(circuit.global_phase, ParameterExpression):
try:
circuit.global_phase = float(circuit.global_phase)
except TypeError:
# expression contains free parameters
pass
if not self._flatten:
try:
block = circuit.to_gate()
except QiskitError:
block = circuit.to_instruction()