/
pulsedefaults.py
304 lines (256 loc) · 10.2 KB
/
pulsedefaults.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
# This code is part of Qiskit.
#
# (C) Copyright IBM 2017, 2019.
#
# 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.
"""Model and schema for pulse defaults."""
from typing import Any, Dict, List
from qiskit.pulse.instruction_schedule_map import InstructionScheduleMap, PulseQobjDef
from qiskit.qobj import PulseLibraryItem, PulseQobjInstruction
from qiskit.qobj.converters import QobjToInstructionConverter
class MeasurementKernel:
"""Class representing a Measurement Kernel."""
def __init__(self, name, params):
"""Initialize a MeasurementKernel object
Args:
name (str): The name of the measurement kernel
params: The parameters of the measurement kernel
"""
self.name = name
self.params = params
def to_dict(self):
"""Return a dictionary format representation of the MeasurementKernel.
Returns:
dict: The dictionary form of the MeasurementKernel.
"""
return {"name": self.name, "params": self.params}
@classmethod
def from_dict(cls, data):
"""Create a new MeasurementKernel object from a dictionary.
Args:
data (dict): A dictionary representing the MeasurementKernel
to create. It will be in the same format as output by
:meth:`to_dict`.
Returns:
MeasurementKernel: The MeasurementKernel from the input dictionary.
"""
return cls(**data)
class Discriminator:
"""Class representing a Discriminator."""
def __init__(self, name, params):
"""Initialize a Discriminator object
Args:
name (str): The name of the discriminator
params: The parameters of the discriminator
"""
self.name = name
self.params = params
def to_dict(self):
"""Return a dictionary format representation of the Discriminator.
Returns:
dict: The dictionary form of the Discriminator.
"""
return {"name": self.name, "params": self.params}
@classmethod
def from_dict(cls, data):
"""Create a new Discriminator object from a dictionary.
Args:
data (dict): A dictionary representing the Discriminator
to create. It will be in the same format as output by
:meth:`to_dict`.
Returns:
Discriminator: The Discriminator from the input dictionary.
"""
return cls(**data)
class Command:
"""Class representing a Command.
Attributes:
name: Pulse command name.
"""
_data = {}
def __init__(self, name: str, qubits=None, sequence=None, **kwargs):
"""Initialize a Command object
Args:
name (str): The name of the command
qubits: The qubits for the command
sequence (PulseQobjInstruction): The sequence for the Command
kwargs: Optional additional fields
"""
self._data = {}
self.name = name
if qubits is not None:
self.qubits = qubits
if sequence is not None:
self.sequence = sequence
self._data.update(kwargs)
def __getattr__(self, name):
try:
return self._data[name]
except KeyError as ex:
raise AttributeError(f"Attribute {name} is not defined") from ex
def to_dict(self):
"""Return a dictionary format representation of the Command.
Returns:
dict: The dictionary form of the Command.
"""
out_dict = {"name": self.name}
if hasattr(self, "qubits"):
out_dict["qubits"] = self.qubits
if hasattr(self, "sequence"):
out_dict["sequence"] = [x.to_dict() for x in self.sequence]
out_dict.update(self._data)
return out_dict
@classmethod
def from_dict(cls, data):
"""Create a new Command object from a dictionary.
Args:
data (dict): A dictionary representing the ``Command``
to create. It will be in the same format as output by
:meth:`to_dict`.
Returns:
Command: The ``Command`` from the input dictionary.
"""
# Pulse command data is nested dictionary.
# To avoid deepcopy and avoid mutating the source object, create new dict here.
in_data = {}
for key, value in data.items():
if key == "sequence":
in_data[key] = list(map(PulseQobjInstruction.from_dict, value))
else:
in_data[key] = value
return cls(**in_data)
class PulseDefaults:
"""Description of default settings for Pulse systems. These are instructions or settings that
may be good starting points for the Pulse user. The user may modify these defaults for custom
scheduling.
"""
_data = {}
def __init__(
self,
qubit_freq_est: List[float],
meas_freq_est: List[float],
buffer: int,
pulse_library: List[PulseLibraryItem],
cmd_def: List[Command],
meas_kernel: MeasurementKernel = None,
discriminator: Discriminator = None,
**kwargs: Dict[str, Any],
):
"""
Validate and reformat transport layer inputs to initialize.
Args:
qubit_freq_est: Estimated qubit frequencies in GHz.
meas_freq_est: Estimated measurement cavity frequencies in GHz.
buffer: Default buffer time (in units of dt) between pulses.
pulse_library: Pulse name and sample definitions.
cmd_def: Operation name and definition in terms of Commands.
meas_kernel: The measurement kernels
discriminator: The discriminators
**kwargs: Other attributes for the super class.
"""
self._data = {}
self.buffer = buffer
self.qubit_freq_est = [freq * 1e9 for freq in qubit_freq_est]
"""Qubit frequencies in Hertz."""
self.meas_freq_est = [freq * 1e9 for freq in meas_freq_est]
"""Measurement frequencies in Hertz."""
self.pulse_library = pulse_library
self.cmd_def = cmd_def
self.instruction_schedule_map = InstructionScheduleMap()
self.converter = QobjToInstructionConverter(pulse_library)
for inst in cmd_def:
entry = PulseQobjDef(converter=self.converter, name=inst.name)
entry.define(inst.sequence, user_provided=False)
self.instruction_schedule_map._add(
instruction_name=inst.name,
qubits=tuple(inst.qubits),
entry=entry,
)
if meas_kernel is not None:
self.meas_kernel = meas_kernel
if discriminator is not None:
self.discriminator = discriminator
self._data.update(kwargs)
def __getattr__(self, name):
try:
return self._data[name]
except KeyError as ex:
raise AttributeError(f"Attribute {name} is not defined") from ex
def to_dict(self):
"""Return a dictionary format representation of the PulseDefaults.
Returns:
dict: The dictionary form of the PulseDefaults.
"""
out_dict = {
"qubit_freq_est": self.qubit_freq_est,
"meas_freq_est": self.qubit_freq_est,
"buffer": self.buffer,
"pulse_library": [x.to_dict() for x in self.pulse_library],
"cmd_def": [x.to_dict() for x in self.cmd_def],
}
if hasattr(self, "meas_kernel"):
out_dict["meas_kernel"] = self.meas_kernel.to_dict()
if hasattr(self, "discriminator"):
out_dict["discriminator"] = self.discriminator.to_dict()
for key, value in self.__dict__.items():
if key not in [
"qubit_freq_est",
"meas_freq_est",
"buffer",
"pulse_library",
"cmd_def",
"meas_kernel",
"discriminator",
"converter",
"instruction_schedule_map",
]:
out_dict[key] = value
out_dict.update(self._data)
out_dict["qubit_freq_est"] = [freq * 1e-9 for freq in self.qubit_freq_est]
out_dict["meas_freq_est"] = [freq * 1e-9 for freq in self.meas_freq_est]
return out_dict
@classmethod
def from_dict(cls, data):
"""Create a new PulseDefaults object from a dictionary.
Args:
data (dict): A dictionary representing the PulseDefaults
to create. It will be in the same format as output by
:meth:`to_dict`.
Returns:
PulseDefaults: The PulseDefaults from the input dictionary.
"""
schema = {
"pulse_library": PulseLibraryItem,
"cmd_def": Command,
"meas_kernel": MeasurementKernel,
"discriminator": Discriminator,
}
# Pulse defaults data is nested dictionary.
# To avoid deepcopy and avoid mutating the source object, create new dict here.
in_data = {}
for key, value in data.items():
if key in schema:
if isinstance(value, list):
in_data[key] = list(map(schema[key].from_dict, value))
else:
in_data[key] = schema[key].from_dict(value)
else:
in_data[key] = value
return cls(**in_data)
def __str__(self):
qubit_freqs = [freq / 1e9 for freq in self.qubit_freq_est]
meas_freqs = [freq / 1e9 for freq in self.meas_freq_est]
qfreq = f"Qubit Frequencies [GHz]\n{qubit_freqs}"
mfreq = f"Measurement Frequencies [GHz]\n{meas_freqs} "
return "<{name}({insts}{qfreq}\n{mfreq})>".format(
name=self.__class__.__name__,
insts=str(self.instruction_schedule_map),
qfreq=qfreq,
mfreq=mfreq,
)