-
Notifications
You must be signed in to change notification settings - Fork 12
/
PulseSequencer.py
240 lines (197 loc) · 8 KB
/
PulseSequencer.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
# coding: utf-8
'''
Quantum Gate Language Module
Copyright 2013 Raytheon BBN Technologies
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
'''
from __future__ import unicode_literals
from copy import copy
import json
import numpy as np
import operator
from collections import OrderedDict
from functools import reduce
from builtins import str
from . import ChannelLibrary, PulseShapes
from collections import namedtuple
class Pulse(namedtuple("Pulse", ["label", "channel", "length", "amp", "phase", "frequency",
"frameChange", "shapeParams", "isTimeAmp",
"isZero", "ignoredStrParams"])):
__slots__ = ()
def __new__(cls, label, channel, shapeParams, amp=1.0, phase=0, frameChange=0, ignoredStrParams=[]):
if hasattr(channel, 'frequency'):
frequency = channel.frequency
else:
frequency = 0
requiredParams = ['length', 'shapeFun']
for param in requiredParams:
if param not in shapeParams.keys():
raise NameError("shapeParams must include {0}".format(param))
isTimeAmp = (shapeParams['shapeFun'] == PulseShapes.constant)
isZero = (amp == 0)
return super(cls, Pulse).__new__(cls, label, channel, shapeParams['length'], amp, phase, frequency, frameChange, shapeParams, isTimeAmp, isZero, ignoredStrParams)
def __str__(self):
kwvals = []
# object parameters outside of shapeParams
for param in ["amp", "phase", "frameChange"]:
if param not in self.ignoredStrParams:
kwvals.append("{0}={1}".format(param, getattr(self, param)))
# parameters inside shapeParams
for n, v in self.shapeParams.items():
if (n not in self.ignoredStrParams and
n in self.channel.pulseParams and
self.channel.pulseParams[n] != v):
kwvals.append("{0}={1}".format(n, v))
if kwvals:
kwstr = ", " + ", ".join(kwvals)
else:
kwstr = ""
return '{0}({1}{2})'.format(self.label, self.channel.label, kwstr)
def _repr_pretty_(self, p, cycle):
p.text(str(self))
def hashshape(self):
return hash(frozenset(self.shapeParams.items()))
def __add__(self, other):
if self.channel != other.channel:
raise NameError(
"Can only concatenate pulses acting on the same channel")
return CompositePulse("", [self, other])
# unary negation inverts the pulse amplitude and frame change
def __neg__(self):
return Pulse(self.label, self.channel, copy(self.shapeParams),
-self.amp, self.phase, -self.frameChange)
def __mul__(self, other):
""" Overload multiplication of Pulses as a "tensor" operator"""
return self.promote() * other.promote()
def promote(self):
# promote a Pulse to a PulseBlock
return PulseBlock(self)
@property
def shape(self):
params = copy(self.shapeParams)
params['samplingRate'] = self.channel.physChan.samplingRate
params.pop('shapeFun')
return self.shapeParams['shapeFun'](**params)
def TAPulse(label,
channel,
length,
amp,
phase=0,
frameChange=0,
ignoredStrParams=None):
"""
Creates a time/amplitude pulse with the given pulse length and amplitude
"""
params = {'length': length, 'shapeFun': PulseShapes.constant}
if ignoredStrParams:
ignoredStrParams.append('shapeFun')
else:
ignoredStrParams = ['shapeFun']
return Pulse(label, channel, params, amp, phase, frameChange, ignoredStrParams)
class CompositePulse(namedtuple("CompositePulse", ["label", "pulses"])):
'''
A sequential series of pulses that reside within one time bin of a pulse block
'''
__slots__ = ()
def __str__(self):
if self.label != "":
return self.label
else:
return "+".join([str(p) for p in self.pulses])
def _repr_pretty_(self, p, cycle):
p.text(str(self))
def __add__(self, other):
if self.channel != other.channel:
raise NameError(
"Can only concatenate pulses acting on the same channel")
if hasattr(other, 'pulses'):
return CompositePulse("", self.pulses + other.pulses)
else:
return CompositePulse("", self.pulses + [other])
def __mul__(self, other):
return self.promote() * other.promote()
def promote(self):
# promote a CompositePulse to a PulseBlock
return PulseBlock(self)
@property
def channel(self):
# Assume that the first pulse in the composite contains the channel information
return self.pulses[0].channel
@property
def length(self):
return sum(p.length for p in self.pulses)
@property
def frameChange(self):
return sum(p.frameChange for p in self.pulses)
@property
def isZero(self):
return all(p.isZero for p in self.pulses)
class PulseBlock(object):
'''
The basic building block for pulse sequences. This is what we can concatenate together to make sequences.
We overload the * operator so that we can combine pulse blocks on different channels.
We overload the + operator to concatenate pulses on the same channel.
'''
def __init__(self, *pulses):
self.alignment = 'left'
self.pulses = OrderedDict([(pulse.channel, pulse) for pulse in pulses])
# The maximum length for any channel on this block
self.length = max(p.length for p in self.pulses.values())
self.label = None
def __repr__(self):
return "Pulses " + ";".join([
str(pulse) for pulse in self.pulses.values()
]) + " alignment: {0}".format(self.alignment)
def __str__(self):
labelPart = "{0}: ".format(self.label) if self.label else ""
return labelPart + "*".join(
[str(pulse) for pulse in self.pulses.values()])
def _repr_pretty_(self, p, cycle):
labelPart = "{0}: ".format(self.label) if self.label else ""
p.text(labelPart + "⊗ ".join([str(pulse)
for pulse in self.pulses.values()]))
# Overload the multiplication operator to combine pulse blocks
def __mul__(self, rhs):
# make sure RHS is a PulseBlock
rhs = rhs.promote()
# copy PulseBlock so we don't modify other references
result = copy(self)
result.pulses = copy(self.pulses)
for (k, v) in rhs.pulses.items():
if k in result.pulses.keys():
raise NameError(
"Attempted to multiply pulses acting on the same space")
else:
result.pulses[k] = v
result.length = max(self.length, rhs.length)
return result
def __eq__(self, other):
if isinstance(other, self.__class__):
# ignore label in equality testing
mydict = self.__dict__.copy()
otherdict = other.__dict__.copy()
mydict.pop('label')
otherdict.pop('label')
return mydict == otherdict
return False
def __ne__(self, other):
return not self == other
# PulseBlocks don't need to be promoted, so just return self
def promote(self):
return self
@property
def channel(self):
return self.pulses.keys()
def align(pulseBlock, mode="center"):
# make sure we have a PulseBlock
pulseBlock = pulseBlock.promote()
pulseBlock.alignment = mode
return pulseBlock