-
Notifications
You must be signed in to change notification settings - Fork 60
/
dynamics_backend.py
1044 lines (887 loc) · 42.7 KB
/
dynamics_backend.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
# -*- coding: utf-8 -*-
# This code is part of Qiskit.
#
# (C) Copyright IBM 2022.
#
# 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.
# pylint: disable=invalid-name
"""
Pulse-enabled simulator backend.
"""
import datetime
import uuid
from typing import List, Optional, Union, Dict, Tuple
import copy
import numpy as np
from scipy.integrate._ivp.ivp import OdeResult # pylint: disable=unused-import
from qiskit import pulse
from qiskit.qobj.utils import MeasLevel, MeasReturnType
from qiskit.qobj.common import QobjHeader
from qiskit.transpiler import Target, InstructionProperties
from qiskit.circuit.library import Measure
from qiskit.pulse import Schedule, ScheduleBlock
from qiskit.pulse.transforms.canonicalization import block_to_schedule
from qiskit.providers.options import Options
from qiskit.providers.backend import BackendV1, BackendV2
from qiskit.providers.models.pulsedefaults import PulseDefaults
from qiskit.providers.models.backendconfiguration import PulseBackendConfiguration
from qiskit.result import Result
from qiskit.result.models import ExperimentResult, ExperimentResultData
from qiskit import QiskitError, QuantumCircuit
from qiskit import schedule as build_schedule
from qiskit.quantum_info import Statevector, DensityMatrix
from qiskit_dynamics import RotatingFrame
from qiskit_dynamics.array import Array
from qiskit_dynamics.solvers.solver_classes import Solver
from .dynamics_job import DynamicsJob
from .backend_utils import (
_get_dressed_state_decomposition,
_get_lab_frame_static_hamiltonian,
_get_memory_slot_probabilities,
_sample_probability_dict,
_get_counts_from_samples,
_get_iq_data,
)
from .backend_string_parser import parse_backend_hamiltonian_dict
class DynamicsBackend(BackendV2):
r"""Pulse-level simulator backend.
This class provides a :class:`~qiskit.providers.backend.BackendV2` interface wrapper around a
:class:`.Solver` instance setup to simulate pulse schedules. The backend can be configured to
take advantage of standard transpilation infrastructure to describe pulse-level simulations in
terms of :class:`~qiskit.circuit.QuantumCircuit`\s. Results are returned as
:class:`~qiskit.result.Result` instances.
A minimal :class:`.DynamicsBackend` requires specifying only a :class:`.Solver` instance and a
list of subsystem dimensions, indicating the subsystem decomposition of the model in
:class:`.Solver`. For example, the following code builds a :class:`.DynamicsBackend` around a
:class:`.Solver` and indicates that the system specified by the :class:`.Solver` decomposes as
two ``3`` dimensional subsystems.
.. code-block:: python
backend = DynamicsBackend(
solver=solver, subsystem_dims=[3, 3]
)
Without further configuration, the above ``backend`` can be used to simulate either
:class:`~qiskit.pulse.Schedule` or :class:`~qiskit.pulse.ScheduleBlock` instances.
Pulse-level simulations defined in terms of :class:`~qiskit.circuit.QuantumCircuit` instances
can also be performed if each gate in the circuit has a corresponding pulse-level definition,
either as an attached calibration, or as an instruction contained in ``backend.target``.
Additionally, a :class:`.DynamicsBackend` can be instantiated from an existing backend using the
:meth:`.DynamicsBackend.from_backend` method, utilizing the additional ``subsystem_list``
argument to specify which qubits to include in the model:
.. code-block:: python
backend = DynamicsBackend.from_backend(backend, subsystem_list=[0, 1])
**Supported options**
The behaviour of the backend can be configured via the following options. These can either be
passed as optional keyword arguments at construction, set with the
:meth:`.DynamicsBackend.set_options` method after construction, or passed as runtime arguments
to :meth:`.DynamicsBackend.run`.
* ``shots``: Number of shots per experiment. Defaults to ``1024``.
* ``solver``: The Qiskit Dynamics :class:`.Solver` instance used for simulation.
* ``solver_options``: Dictionary containing optional kwargs for passing to :meth:`Solver.solve`,
indicating solver methods and options. Defaults to the empty dictionary ``{}``.
* ``subsystem_dims``: Dimensions of subsystems making up the system in ``solver``. Defaults to
``[solver.model.dim]``.
* ``subsystem_labels``: Integer labels for subsystems. Defaults to ``[0, ...,
len(subsystem_dims) - 1]``.
* ``meas_map``: Measurement map. Defaults to ``[[idx] for idx in subsystem_labels]``.
* ``control_channel_map``: A dictionary mapping control channel labels to indices, to be used
for control channel index lookup in the :meth:`DynamicsBackend.control_channel` method.
* ``initial_state``: Initial state for simulation, either the string ``"ground_state"``,
indicating that the ground state for the system Hamiltonian should be used, or an arbitrary
``Statevector`` or ``DensityMatrix``. Defaults to ``"ground_state"``.
* ``normalize_states``: Boolean indicating whether to normalize states before computing outcome
probabilities. Defaults to ``True``. Setting to ``False`` can result in errors if the solution
tolerance results in probabilities with significant numerical deviation from a proper
probability distribution.
* ``meas_level``: Form of measurement output. Supported values are ``1`` and ``2``. ``1``
returns IQ points and ``2`` returns counts. Defaults to ``meas_level == 2``.
* ``meas_return``: Level of measurement data to return. For ``meas_level = 1`` ``"single"``
returns output from every shot. ``"avg"`` returns average over shots of measurement output.
Defaults to ``"avg"``.
* ``iq_centers``: Centers for IQ distribution when using ``meas_level==1`` results. Must have
type ``List[List[List[float, float]]]`` formatted as ``iq_centers[subsystem][level] = [I,
Q]``. If ``None``, the ``iq_centers`` are dynamically generated to be equally spaced points on
a unit circle with ground-state at ``(1, 0)``. The default is ``None``.
* ``iq_width``: Standard deviation of IQ distribution around the centers for ``meas_level==1``.
Must be a positive float. Defaults to ``0.2``.
* ``max_outcome_level``: For ``meas_level == 2``, the maximum outcome for each subsystem. Values
will be rounded down to be no larger than ``max_outcome_level``. Must be a positive integer or
``None``. If ``None``, no rounding occurs. Defaults to ``1``.
* ``memory``: Boolean indicating whether to return a list of explicit measurement outcomes for
every experimental shot. Defaults to ``True``.
* ``seed_simulator``: Seed to use in random sampling. Defaults to ``None``.
* ``experiment_result_function``: Function for computing the ``ExperimentResult`` for each
simulated experiment. This option defaults to :func:`default_experiment_result_function`, and
any other function set to this option must have the same signature. Note that the default
utilizes various other options that control results computation, and hence changing it will
impact the meaning of other options.
* ``configuration``: A :class:`PulseBackendConfiguration` instance or ``None``. This option
defaults to ``None``, and is not required for the functioning of this class, but is provided
for compatibility. A set configuration will be returned by
:meth:`DynamicsBackend.configuration()`.
* ``defaults``: A :class:`PulseDefaults` instance or ``None``. This option defaults to ``None``,
and is not required for the functioning of this class, but is provided for compatibility. A
set defaults will be returned by :meth:`DynamicsBackend.defaults()`.
"""
def __init__(
self,
solver: Solver,
target: Optional[Target] = None,
**options,
):
"""Instantiate with a :class:`.Solver` instance and additional options.
Args:
solver: Solver instance configured for pulse simulation.
target: Target object.
options: Additional configuration options for the simulator.
Raises:
QiskitError: If any instantiation arguments fail validation checks.
"""
super().__init__(
name="DynamicsBackend",
description="Pulse enabled simulator backend.",
backend_version="0.1",
)
# Dressed states of solver, will be calculated when solver option is set
self._dressed_evals = None
self._dressed_states = None
self._dressed_states_adjoint = None
# add subsystem_dims to options so set_options validation works
if "subsystem_dims" not in options:
options["subsystem_dims"] = [solver.model.dim]
# Set simulator options
self.set_options(solver=solver, **options)
if self.options.subsystem_labels is None:
labels = list(range(len(self.options.subsystem_dims)))
self.set_options(subsystem_labels=labels)
if self.options.meas_map is None:
meas_map = [[idx] for idx in self.options.subsystem_labels]
self.set_options(meas_map=meas_map)
# self._target = target or Target() doesn't work as bool(target) can be False
if target is None:
target = Target()
else:
target = copy.copy(target)
# add default simulator measure instructions
measure_properties = {}
for qubit in self.options.subsystem_labels:
instruction_schedule_map = target.instruction_schedule_map()
if not instruction_schedule_map.has(instruction="measure", qubits=qubit):
with pulse.build() as meas_sched:
pulse.acquire(
duration=1, qubit_or_channel=qubit, register=pulse.MemorySlot(qubit)
)
measure_properties[(qubit,)] = InstructionProperties(calibration=meas_sched)
target.add_instruction(Measure(), measure_properties)
target.dt = solver._dt
self._target = target
def _default_options(self):
return Options(
shots=1024,
solver=None,
solver_options={},
subsystem_dims=None,
subsystem_labels=None,
meas_map=None,
control_channel_map=None,
normalize_states=True,
initial_state="ground_state",
meas_level=MeasLevel.CLASSIFIED,
meas_return=MeasReturnType.AVERAGE,
iq_centers=None,
iq_width=0.2,
max_outcome_level=1,
memory=True,
seed_simulator=None,
experiment_result_function=default_experiment_result_function,
configuration=None,
defaults=None,
)
def set_options(self, **fields):
"""Set options for DynamicsBackend."""
validate_subsystem_dims = False
validate_iq_centers = False
for key, value in fields.items():
if not hasattr(self._options, key):
raise AttributeError(f"Invalid option {key}")
# validation checks
if key == "initial_state":
if value != "ground_state" and not isinstance(value, (Statevector, DensityMatrix)):
raise QiskitError(
'initial_state must be either "ground_state", or a Statevector or '
"DensityMatrix instance."
)
elif key == "meas_level" and value not in [1, 2]:
raise QiskitError("Only meas_level 1 and 2 are supported by DynamicsBackend.")
elif key == "meas_return" and value not in ["single", "avg"]:
raise QiskitError("meas_return must be either 'single' or 'avg'.")
elif key == "max_outcome_level":
if (value is not None) and (not isinstance(value, int) or (value <= 0)):
raise QiskitError("max_outcome_level must be a positive integer or None.")
elif key == "experiment_result_function" and not callable(value):
raise QiskitError("experiment_result_function must be callable.")
elif key == "configuration" and not isinstance(value, PulseBackendConfiguration):
raise QiskitError(
"configuration option must be an instance of PulseBackendConfiguration."
)
elif key == "defaults" and not isinstance(value, PulseDefaults):
raise QiskitError("defaults option must be an instance of PulseDefaults.")
elif key == "iq_width" and (not isinstance(value, float) or (value <= 0)):
raise QiskitError("iq_width must be a positive float.")
elif key == "iq_centers":
if (value is not None) and not all(
(isinstance(level, List) and len(level) == 2)
for sub_system in value
for level in sub_system
):
raise QiskitError(
"The iq_centers option must be either None or of type "
"List[List[List[int, int]]], where the innermost list is the (I, Q) pair."
)
validate_iq_centers = True
elif key == "subsystem_dims":
validate_subsystem_dims = True
validate_iq_centers = True
elif key == "solver":
validate_subsystem_dims = True
elif key == "control_channel_map":
if value is not None:
if not isinstance(value, dict):
raise QiskitError(
"The control_channel_map option must either be None or a dictionary."
)
if not all(isinstance(x, int) for x in value.values()):
raise QiskitError("The control_channel_map values must be of type int.")
# special setting routines
if key == "solver":
self._set_solver(value)
else:
self._options.update_options(**{key: value})
# perform additional consistency validations if certain options were modified
if (
validate_subsystem_dims
and np.prod(self._options.subsystem_dims) != self._options.solver.model.dim
):
raise QiskitError(
"DynamicsBackend options subsystem_dims and solver.model.dim are inconsistent."
)
if validate_iq_centers and (self._options.iq_centers is not None):
if [
len(sub_system) for sub_system in self._options.iq_centers
] != self._options.subsystem_dims:
raise QiskitError(
"""iq_centers option is not consistent with subsystem_dims. Must be None
or of type List[List[List[int, int]]], where the outermost list is of length equal
to the number of subsystems, and each inner list of length equal to the
corresponding subsystem dimension."""
)
def _set_solver(self, solver):
"""Configure simulator based on provided solver."""
if solver._dt is None:
raise QiskitError(
"Solver passed to DynamicsBackend is not configured for Pulse simulation."
)
self._options.update_options(solver=solver)
# Get dressed states
static_hamiltonian = _get_lab_frame_static_hamiltonian(solver.model)
dressed_evals, dressed_states = _get_dressed_state_decomposition(static_hamiltonian)
self._dressed_evals = dressed_evals
self._dressed_states = dressed_states
self._dressed_states_adjoint = self._dressed_states.conj().transpose()
# pylint: disable=arguments-differ
def run(
self,
run_input: List[Union[QuantumCircuit, Schedule, ScheduleBlock]],
validate: Optional[bool] = True,
**options,
) -> DynamicsJob:
"""Run a list of simulations.
Args:
run_input: A list of simulations, specified by ``QuantumCircuit``, ``Schedule``, or
``ScheduleBlock`` instances.
validate: Whether or not to run validation checks on the input.
**options: Additional run options to temporarily override current backend options.
Returns:
DynamicsJob object containing results and status.
Raises:
QiskitError: If invalid options are set.
"""
if validate:
_validate_run_input(run_input)
# Configure run options for simulation
if options:
backend = copy.deepcopy(self)
backend.set_options(**options)
else:
backend = self
schedules, num_memory_slots_list = _to_schedule_list(run_input, backend=backend)
# get the acquires sample times and subsystem measurement information
(
t_span,
measurement_subsystems_list,
memory_slot_indices_list,
) = _get_acquire_instruction_timings(
schedules, backend.options.subsystem_labels, backend.options.solver._dt
)
# Build and submit job
job_id = str(uuid.uuid4())
dynamics_job = DynamicsJob(
backend=backend,
job_id=job_id,
fn=backend._run,
fn_kwargs={
"t_span": t_span,
"schedules": schedules,
"measurement_subsystems_list": measurement_subsystems_list,
"memory_slot_indices_list": memory_slot_indices_list,
"num_memory_slots_list": num_memory_slots_list,
},
)
dynamics_job.submit()
return dynamics_job
def _run(
self,
job_id,
t_span,
schedules,
measurement_subsystems_list,
memory_slot_indices_list,
num_memory_slots_list,
) -> Result:
"""Simulate a list of schedules."""
# simulate all schedules
y0 = self.options.initial_state
if y0 == "ground_state":
y0 = Statevector(self._dressed_states[:, 0])
solver_results = self.options.solver.solve(
t_span=t_span, y0=y0, signals=schedules, **self.options.solver_options
)
# compute results for each experiment
experiment_names = [schedule.name for schedule in schedules]
experiment_metadatas = [schedule.metadata for schedule in schedules]
rng = np.random.default_rng(self.options.seed_simulator)
experiment_results = []
for (
experiment_name,
solver_result,
measurement_subsystems,
memory_slot_indices,
num_memory_slots,
experiment_metadata,
) in zip(
experiment_names,
solver_results,
measurement_subsystems_list,
memory_slot_indices_list,
num_memory_slots_list,
experiment_metadatas,
):
experiment_results.append(
self.options.experiment_result_function(
experiment_name,
solver_result,
measurement_subsystems,
memory_slot_indices,
num_memory_slots,
self,
seed=rng.integers(low=0, high=9223372036854775807),
metadata=experiment_metadata,
)
)
# Construct full result object
return Result(
backend_name=self.name,
backend_version=self.backend_version,
qobj_id="",
job_id=job_id,
success=True,
results=experiment_results,
date=datetime.datetime.now().isoformat(),
)
@property
def max_circuits(self):
return None
@property
def target(self) -> Target:
return self._target
@property
def meas_map(self) -> List[List[int]]:
return self.options.meas_map
def _get_qubit_channel(
self, qubit: int, ChannelClass: pulse.channels.Channel, method_name: str
):
"""Construct a channel instance for a given qubit."""
if qubit in self.options.subsystem_labels:
return ChannelClass(qubit)
raise QiskitError(
f"{method_name} requested for qubit {qubit} which is not in subsystem_list."
)
def drive_channel(self, qubit: int) -> pulse.DriveChannel:
"""Return the drive channel for a given qubit."""
return self._get_qubit_channel(qubit, pulse.DriveChannel, "drive_channel")
def measure_channel(self, qubit: int) -> pulse.MeasureChannel:
"""Return the measure channel for a given qubit."""
return self._get_qubit_channel(qubit, pulse.MeasureChannel, "measure_channel")
def acquire_channel(self, qubit: int) -> pulse.AcquireChannel:
"""Return the measure channel for a given qubit."""
return self._get_qubit_channel(qubit, pulse.AcquireChannel, "acquire_channel")
def control_channel(
self, qubits: Union[Tuple[int, int], List[Tuple[int, int]]]
) -> List[pulse.ControlChannel]:
"""Return the control channel with a given label specified by qubits.
This method requires the ``control_channel_map`` option is set, and otherwise will raise
a ``NotImplementedError``.
Args:
qubits: The label for the control channel, or a list of labels.
Returns:
A list containing the control channels specified by qubits.
Raises:
NotImplementedError: If the control_channel_map option is not set for this backend.
QiskitError: If a requested channel is not in the control_channel_map.
"""
if self.options.control_channel_map is None:
raise NotImplementedError
if not isinstance(qubits, list):
qubits = [qubits]
control_channels = []
for x in qubits:
if x not in self.options.control_channel_map:
raise QiskitError(f"Key {x} not in control_channel_map.")
control_channels.append(pulse.ControlChannel(self.options.control_channel_map[x]))
return control_channels
def configuration(self) -> PulseBackendConfiguration:
"""Get the backend configuration."""
return self.options.configuration
def defaults(self) -> PulseDefaults:
"""Get the backend defaults."""
return self.options.defaults
@classmethod
def from_backend(
cls,
backend: Union[BackendV1, BackendV2],
subsystem_list: Optional[List[int]] = None,
rotating_frame: Optional[Union[Array, RotatingFrame, str]] = "auto",
evaluation_mode: str = "dense",
rwa_cutoff_freq: Optional[float] = None,
**options,
) -> "DynamicsBackend":
"""Construct a DynamicsBackend instance from an existing Backend instance.
.. warning::
Due to inevitable model inaccuracies, gates calibrated on a real backend will not have
the same performance on the :class:`.DynamicsBackend` instance returned by this method.
As such, gates and calibrations are not be copied into the constructed
:class:`.DynamicsBackend`.
The ``backend`` must contain sufficient information in the ``target``, ``configuration``,
and/or ``defaults`` attributes to be able to run simulations. The following table indicates
which parameters are required, along with their primary and secondary sources:
.. list-table:: Backend parameter locations
:widths: 10 25 25
:header-rows: 1
* - Parameter
- Primary source
- Secondary source
* - ``hamiltonian`` dictionary.
- ``configuration.hamiltonian``
- N/A
* - Control channel frequency specification.
- ``configuration.u_channel_lo``
- N/A
* - Number of qubits in the backend model.
- ``target.num_qubits``
- ``configuration.n_qubits``
* - Pulse schedule sample size ``dt``.
- ``target.dt``
- ``configuration.dt``
* - Drive channel frequencies.
- ``target.qubit_properties``
- ``defaults.qubit_freq_est``
* - Measurement channel frequencies, if measurement channels explicitly appear in the
model.
- ``defaults.meas_freq_est``
- N/A
.. note::
The ``target``, ``configuration``, and ``defaults`` attributes of the original backend
are not copied into the constructed :class:`DynamicsBackend` instance, only the required
data stored within these attributes will be extracted. If necessary, these attributes
can be set and configured by the user.
The optional argument ``subsystem_list`` specifies which subset of qubits to model in the
constructed :class:`DynamicsBackend`. All other qubits are dropped from the model.
Configuration of the underlying :class:`.Solver` is controlled via the ``rotating_frame``,
``evaluation_mode``, and ``rwa_cutoff_freq`` options. In contrast to :class:`.Solver`
initialization, ``rotating_frame`` defaults to the string ``"auto"``, which allows this
method to choose the rotating frame based on ``evaluation_mode``:
* If a dense evaluation mode is chosen, the rotating frame will be set to the
``static_hamiltonian`` indicated by the Hamiltonian in ``backend.configuration()``.
* If a sparse evaluation mode is chosen, the rotating frame will be set to the diagonal of
``static_hamiltonian``.
Otherwise the ``rotating_frame``, ``evaluation_mode``, and ``rwa_cutoff_freq`` are passed
directly to the :class:`.Solver` initialization.
Args:
backend: The ``Backend`` instance to build the :class:`.DynamicsBackend` from.
subsystem_list: The list of qubits in the backend to include in the model.
rotating_frame: Rotating frame argument for the internal :class:`.Solver`. Defaults to
``"auto"``, allowing this method to pick a rotating frame.
evaluation_mode: Evaluation mode argument for the internal :class:`.Solver`.
rwa_cutoff_freq: Rotating wave approximation argument for the internal :class:`.Solver`.
**options: Additional options to be applied in construction of the
:class:`.DynamicsBackend`.
Returns:
DynamicsBackend
Raises:
QiskitError: If any required parameters are missing from the passed backend.
"""
# get available target, config, and defaults objects
backend_target = getattr(backend, "target", None)
if not hasattr(backend, "configuration"):
raise QiskitError(
"DynamicsBackend.from_backend requires that the backend argument has a "
"configuration method."
)
backend_config = backend.configuration()
backend_defaults = None
if hasattr(backend, "defaults"):
backend_defaults = backend.defaults()
# get and parse Hamiltonian string dictionary
if backend_target is not None:
backend_num_qubits = backend_target.num_qubits
else:
backend_num_qubits = backend_config.n_qubits
if subsystem_list is not None:
subsystem_list = sorted(subsystem_list)
if subsystem_list[-1] >= backend_num_qubits:
raise QiskitError(
f"subsystem_list contained {subsystem_list[-1]}, which is out of bounds for "
f"backend with {backend_num_qubits} qubits."
)
else:
subsystem_list = list(range(backend_num_qubits))
if backend_config.hamiltonian is None:
raise QiskitError(
"DynamicsBackend.from_backend requires that backend.configuration() has a "
"hamiltonian."
)
(
static_hamiltonian,
hamiltonian_operators,
hamiltonian_channels,
subsystem_dims,
) = parse_backend_hamiltonian_dict(backend_config.hamiltonian, subsystem_list)
subsystem_dims = [subsystem_dims[idx] for idx in subsystem_list]
# construct model frequencies dictionary from backend
channel_freqs = _get_backend_channel_freqs(
backend_target=backend_target,
backend_config=backend_config,
backend_defaults=backend_defaults,
channels=hamiltonian_channels,
)
# build the solver
if rotating_frame == "auto":
if "dense" in evaluation_mode:
rotating_frame = static_hamiltonian
else:
rotating_frame = np.diag(static_hamiltonian)
# get time step size
if backend_target is not None and backend_target.dt is not None:
dt = backend_target.dt
else:
# config is guaranteed to have a dt
dt = backend_config.dt
solver = Solver(
static_hamiltonian=static_hamiltonian,
hamiltonian_operators=hamiltonian_operators,
hamiltonian_channels=hamiltonian_channels,
channel_carrier_freqs=channel_freqs,
dt=dt,
rotating_frame=rotating_frame,
evaluation_mode=evaluation_mode,
rwa_cutoff_freq=rwa_cutoff_freq,
)
return cls(
solver=solver,
target=Target(dt=dt),
subsystem_labels=subsystem_list,
subsystem_dims=subsystem_dims,
**options,
)
def default_experiment_result_function(
experiment_name: str,
solver_result: OdeResult,
measurement_subsystems: List[int],
memory_slot_indices: List[int],
num_memory_slots: Union[None, int],
backend: DynamicsBackend,
seed: Optional[int] = None,
metadata: Optional[Dict] = None,
) -> ExperimentResult:
"""Default routine for generating ExperimentResult object.
To generate the results for a given experiment, this method takes the following steps:
* The final state is transformed out of the rotating frame and into the lab frame using
``backend.options.solver``.
* If ``backend.options.normalize_states==True``, the final state is normalized.
* Measurement results are computed, in the dressed basis, based on both the measurement-related
options in ``backend.options`` and the measurement specification extracted from the specific
experiment.
Args:
experiment_name: Name of experiment.
solver_result: Result object from :class:`Solver.solve`.
measurement_subsystems: Labels of subsystems in the model being measured.
memory_slot_indices: Indices of memory slots to store the results in for each subsystem.
num_memory_slots: Total number of memory slots in the returned output. If ``None``,
``max(memory_slot_indices)`` will be used.
backend: The backend instance that ran the simulation. Various options and properties
are utilized.
seed: Seed for any random number generation involved (e.g. when computing outcome samples).
metadata: Metadata to add to the header of the
:class:`~qiskit.result.models.ExperimentResult` object.
Returns:
:class:`~qiskit.result.models.ExperimentResult` object containing results.
Raises:
QiskitError: If a specified option is unsupported.
"""
yf = solver_result.y[-1]
tf = solver_result.t[-1]
# Take state out of frame, put in dressed basis, and normalize
if isinstance(yf, Statevector):
yf = np.array(backend.options.solver.model.rotating_frame.state_out_of_frame(t=tf, y=yf))
yf = backend._dressed_states_adjoint @ yf
yf = Statevector(yf, dims=backend.options.subsystem_dims)
if backend.options.normalize_states:
yf = yf / np.linalg.norm(yf.data)
elif isinstance(yf, DensityMatrix):
yf = np.array(
backend.options.solver.model.rotating_frame.operator_out_of_frame(t=tf, operator=yf)
)
yf = backend._dressed_states_adjoint @ yf @ backend._dressed_states
yf = DensityMatrix(yf, dims=backend.options.subsystem_dims)
if backend.options.normalize_states:
yf = yf / np.diag(yf.data).sum()
# compute probabilities for measurement slot values
measurement_subsystems = [
backend.options.subsystem_labels.index(x) for x in measurement_subsystems
]
if backend.options.meas_level == MeasLevel.CLASSIFIED:
memory_slot_probabilities = _get_memory_slot_probabilities(
probability_dict=yf.probabilities_dict(qargs=measurement_subsystems),
memory_slot_indices=memory_slot_indices,
num_memory_slots=num_memory_slots,
max_outcome_value=backend.options.max_outcome_level,
)
# sample
memory_samples = _sample_probability_dict(
memory_slot_probabilities, shots=backend.options.shots, seed=seed
)
counts = _get_counts_from_samples(memory_samples)
# construct results object
exp_data = ExperimentResultData(
counts=counts, memory=memory_samples if backend.options.memory else None
)
return ExperimentResult(
shots=backend.options.shots,
success=True,
data=exp_data,
meas_level=MeasLevel.CLASSIFIED,
seed=seed,
header=QobjHeader(name=experiment_name, metadata=metadata),
)
elif backend.options.meas_level == MeasLevel.KERNELED:
iq_centers = backend.options.iq_centers
if iq_centers is None:
# Default iq_centers
iq_centers = []
for sub_dim in backend.options.subsystem_dims:
theta = 2 * np.pi / sub_dim
iq_centers.append(
[(np.cos(idx * theta), np.sin(idx * theta)) for idx in range(sub_dim)]
)
# generate IQ
measurement_data = _get_iq_data(
yf,
measurement_subsystems=measurement_subsystems,
iq_centers=iq_centers,
iq_width=backend.options.iq_width,
shots=backend.options.shots,
memory_slot_indices=memory_slot_indices,
num_memory_slots=num_memory_slots,
seed=seed,
)
if backend.options.meas_return == MeasReturnType.AVERAGE:
measurement_data = np.average(measurement_data, axis=0)
# construct results object
exp_data = ExperimentResultData(memory=measurement_data)
return ExperimentResult(
shots=backend.options.shots,
success=True,
data=exp_data,
meas_level=MeasLevel.KERNELED,
seed=seed,
header=QobjHeader(name=experiment_name, metadata=metadata),
)
else:
raise QiskitError(f"meas_level=={backend.options.meas_level} not implemented.")
def _validate_run_input(run_input, accept_list=True):
"""Raise errors if the run_input is not one of QuantumCircuit, Schedule, ScheduleBlock, or
a list of these.
"""
if isinstance(run_input, list) and accept_list:
# if list apply recursively, but no longer accept lists
for x in run_input:
_validate_run_input(x, accept_list=False)
elif not isinstance(run_input, (QuantumCircuit, Schedule, ScheduleBlock)):
raise QiskitError(f"Input type {type(run_input)} not supported by DynamicsBackend.run.")
def _get_acquire_instruction_timings(
schedules: List[Schedule], valid_subsystem_labels: List[int], dt: float
) -> Tuple[List[List[float]], List[List[int]], List[List[int]]]:
"""Get the required data from the acquire commands in each schedule.
Additionally validates that each schedule has acquire instructions occurring at one time, at
least one memory slot is being listed, and all measured subsystems exist in
``valid_subsystem_labels``.
Args:
schedules: A list of schedules.
valid_subsystem_labels: Valid acquire channel indices.
dt: The sample size.
Returns:
A tuple of lists containing, for each schedule: the list of integration intervals required
for each schedule (in absolute time, from 0.0 to the beginning of the acquire instructions),
a list of the subsystems being measured, and a list of the memory slots indices in which to
store the results of each subsystem measurement.
Raises:
QiskitError: If a schedule contains no measurement, if a schedule contains measurements at
different times, or if a measurement has an invalid subsystem label.
"""
t_span_list = []
measurement_subsystems_list = []
memory_slot_indices_list = []
for schedule in schedules:
schedule_acquires = []
schedule_acquire_times = []
for start_time, inst in schedule.instructions:
# only track acquires saving in a memory slot
if isinstance(inst, pulse.Acquire) and inst.mem_slot is not None:
schedule_acquires.append(inst)
schedule_acquire_times.append(start_time)
# validate
if len(schedule_acquire_times) == 0:
raise QiskitError(
"At least one measurement saving a a result in a MemorySlot "
"must be present in each schedule."
)
for acquire_time in schedule_acquire_times[1:]:
if acquire_time != schedule_acquire_times[0]:
raise QiskitError("DynamicsBackend.run only supports measurements at one time.")
# use dt to convert acquire start time from sample index to the integration interval
t_span_list.append([0.0, dt * schedule_acquire_times[0]])
measurement_subsystems = []
memory_slot_indices = []
for inst in schedule_acquires:
if inst.channel.index in valid_subsystem_labels:
measurement_subsystems.append(inst.channel.index)
else:
raise QiskitError(
f"Attempted to measure subsystem {inst.channel.index}, but it is not in "
"subsystem_list."
)
memory_slot_indices.append(inst.mem_slot.index)
measurement_subsystems_list.append(measurement_subsystems)
memory_slot_indices_list.append(memory_slot_indices)
return t_span_list, measurement_subsystems_list, memory_slot_indices_list
def _to_schedule_list(
run_input: List[Union[QuantumCircuit, Schedule, ScheduleBlock]], backend: BackendV2
):
"""Convert all inputs to schedules, and store the number of classical registers present
in any circuits.
"""
if not isinstance(run_input, list):
run_input = [run_input]
schedules = []
num_memslots = []
for sched in run_input:
num_memslots.append(None)
if isinstance(sched, ScheduleBlock):
schedules.append(block_to_schedule(sched))
elif isinstance(sched, Schedule):
schedules.append(sched)
elif isinstance(sched, QuantumCircuit):
num_memslots[-1] = sched.cregs[0].size
schedules.append(build_schedule(sched, backend, dt=backend.options.solver._dt))
else:
raise QiskitError(f"Type {type(sched)} cannot be converted to Schedule.")
return schedules, num_memslots
def _get_backend_channel_freqs(
backend_target: Optional[Target],
backend_config: PulseBackendConfiguration,
backend_defaults: Optional[PulseDefaults],
channels: List[str],
) -> Dict[str, float]:
"""Extract frequencies of channels from a backend configuration and defaults.
Args:
backend_target: A backend target object or ``None``.
backend_config: A backend configuration object.
backend_defaults: A backend defaults object or ``None``.
channels: Channel labels given as strings, assumed to be unique.
Returns:
Dict: Mapping of channel labels to frequencies.
Raises:
QiskitError: If the frequency for one of the channels cannot be found.
"""
# partition types of channels
drive_channels = []
meas_channels = []
u_channels = []
for channel in channels:
if channel[0] == "d":
drive_channels.append(channel)
elif channel[0] == "m":
meas_channels.append(channel)
elif channel[0] == "u":
u_channels.append(channel)
else:
raise QiskitError("Unrecognized channel type requested.")
# extract and validate channel frequency parameters
if drive_channels:
# get drive channel frequencies
drive_frequencies = []
if (backend_target is not None) and (backend_target.qubit_properties is not None):
drive_frequencies = [q.frequency for q in backend_target.qubit_properties]
elif backend_defaults is not None:
drive_frequencies = backend_defaults.qubit_freq_est
else: