/
__init__.py
402 lines (339 loc) · 11.8 KB
/
__init__.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
"""Implementations of a text parser for reading GST input files."""
#***************************************************************************************************
# Copyright 2015, 2019 National Technology & Engineering Solutions of Sandia, LLC (NTESS).
# Under the terms of Contract DE-NA0003525 with NTESS, the U.S. Government retains certain rights
# in this software.
# 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 or in the LICENSE file in the root pyGSTi directory.
#***************************************************************************************************
"""
Encapsulates a text parser for reading GST input files.
** Grammar **
expop :: '^'
multop :: '*'
integer :: '0'..'9'+
real :: ['+'|'-'] integer [ '.' integer [ 'e' ['+'|'-'] integer ] ]
reflbl :: (alpha | digit | '_')+
nop :: '{}'
opname :: 'G' [ lowercase | digit | '_' ]+
instrmtnm :: 'I' [ lowercase | digit | '_' ]+
povmnm :: 'M' [ lowercase | digit | '_' ]+
prepnm :: 'rho' [ lowercase | digit | '_' ]+
gate :: opname [':' integer ]*
instrmt :: instrmt [':' integer ]*
povm :: povmnm [':' integer ]*
prep :: prepnm [':' integer ]*
strref :: 'S' '<' reflbl '>'
slcref :: strref [ '[' integer ':' integer ']' ]
subcircuit:: '[' layer ']' | '(' string ')'
layerable :: gate | instrmt | subcircuit [ expop integer ]*
layer :: layerable [ [ multop ] layerable ]*
expable :: gate | instrmt | '[' layer ']' | slcref | '(' string ')' | nop
expdstr :: expable [ expop integer ]*
string :: expdstr [ [ multop ] expdstr ]*
pstring :: [ prep ] string
ppstring :: pstring [ povm ]
"""
warn_msg = """
An optimized Cython-based implementation of `{module}` is available as
an extension, but couldn't be imported. This might happen if the
extension has not been built. `pip install cython`, then reinstall
pyGSTi to build Cython extensions. Alternatively, setting the
environment variable `PYGSTI_NO_CYTHON_WARNING` will suppress this
message.
""".format(module=__name__)
try:
# Import cython implementation if it's been built...
from .fastcircuitparser import *
except ImportError:
# ... If not, fall back to the python implementation, with a warning.
import os as _os
import warnings as _warnings
if 'PYGSTI_NO_CYTHON_WARNING' not in _os.environ:
_warnings.warn(warn_msg)
from .slowcircuitparser import *
import warnings as _warnings
from ply import lex, yacc
from ...objects import label as _lbl
class CircuitLexer:
""" Lexer for matching and interpreting text-format operation sequences """
# List of token names. This is always required
tokens = (
'EXPOP',
'MULTOP',
'INTEGER',
'NOP',
'GATE',
'INSTRMT',
'PREP',
'POVM',
'REFLBL',
'OPENBR',
'CLOSEBR',
'LPAREN',
'COLON',
'SEMICOLON',
'EXCLAM',
'RPAREN',
'STRINGIND'
)
@staticmethod
def makeLabel(s):
if '!' in s:
s, time = s.split('!') # must be only two parts (only 1 exclamation pt)
time = float(time)
else:
time = 0.0
if ';' in s:
parts = s.split(';')
parts2 = parts[-1].split(':')
nm = parts[0]
args = parts[1:-1] + [parts2[0]]
sslbls = parts2[1:]
else:
parts = s.split(':')
nm = parts[0]
args = None
sslbls = parts[1:]
if len(sslbls) == 0:
sslbls = None
return _lbl.Label(nm, sslbls, time, args)
@staticmethod
def t_GATE(t):
r'G[a-z0-9_]+(;[a-zQ0-9_\./]+)*(:[a-zQ0-9_]+)*(![0-9\.]+)?'
#Note: Q is only capital letter allowed in qubit label
#Note: don't need to convert parts[1],etc, to integers (if possible) as Label automatically does this
lbl = CircuitLexer.makeLabel(t.value)
t.value = lbl, # make it a tuple
return t
@staticmethod
def t_INSTRMT(t):
r'I[a-z0-9_]+(![0-9\.]+)?'
#Note: don't need to convert parts[1],etc, to integers (if possible) as Label automatically does this
lbl = CircuitLexer.makeLabel(t.value)
t.value = lbl, # make it a tuple
return t
@staticmethod
def t_PREP(t):
r'rho[a-z0-9_]+(![0-9\.]+)?'
#Note: don't need to convert parts[1],etc, to integers (if possible) as Label automatically does this
lbl = CircuitLexer.makeLabel(t.value)
t.value = lbl, # make it a tuple
return t
@staticmethod
def t_POVM(t):
r'M[a-z0-9_]+(![0-9\.]+)?'
#Note: don't need to convert parts[1],etc, to integers (if possible) as Label automatically does this
lbl = CircuitLexer.makeLabel(t.value)
t.value = lbl, # make it a tuple
return t
@staticmethod
def t_STRINGIND(t):
r'S(?=\s*\<)'
return t
@staticmethod
def t_REFLBL(t):
r'<\s*[a-zA-Z0-9_]+\s*>'
t.value = t.value[1:-1].strip()
return t
# Regular expression rules for simple tokens
t_EXPOP = r'\^'
t_MULTOP = r'\*'
t_OPENBR = r'\['
t_CLOSEBR = r'\]'
t_LPAREN = r'\('
t_RPAREN = r'\)'
t_COLON = r'\:'
t_SEMICOLON = r'\;'
t_EXCLAM = r'\!'
@staticmethod
def t_NOP(t):
r'\{\}'
t.value = tuple()
return t
@staticmethod
def t_INTEGER(t):
r'\d+'
t.value = int(t.value)
return t
# A string containing ignored characters (spaces and tabs)
t_ignore = ' \t'
# Error handling rule
@staticmethod
def t_error(t):
if t is not None:
raise ValueError("Illegal character '{}' at position {} of string '{}'".format(
t.value[0], t.lexpos, t.lexer.lexdata))
raise ValueError("Lexer error") # pragma: no cover
class CircuitParser(object):
""" Parser for text-format operation sequences """
tokens = CircuitLexer.tokens
mode = "simple"
def __init__(self, lexer_object=None, lookup={}):
if self.mode == "ply":
self._lookup = lookup
self._lexer = lex.lex(object=lexer_object if lexer_object else CircuitLexer())
self._parser = yacc.yacc(module=self, start="ppstring", debug=False,
tabmodule='pygsti.io.parsetab_string')
self.parse = self.ply_parse
else:
self.parse = self._parse
def _parse(self, code, create_subcircuits=True, integerize_sslbls=True):
""" Parse a circuit string
This method will dispatch to the optimized Cython
implementation, if available. Otherwise, the slower native
python implementation will be used.
"""
return parse_circuit(code, create_subcircuits, integerize_sslbls)
@property
def lookup(self):
""" The lookup dictionary for expanding references """
return self._lookup
@lookup.setter
def lookup(self, newdict):
""" The lookup dictionary for expanding references """
self._lookup = newdict
def p_strref(self, p):
'''strref : STRINGIND REFLBL'''
match = self._lookup.get(str(p[2]))
if match is None:
raise ValueError("Lookup, key '{}' not found".format(str(p[2])))
p[0] = tuple(match)
@staticmethod
def p_slcref_slice(p):
'''slcref : strref OPENBR INTEGER COLON INTEGER CLOSEBR'''
_, ref, _, lower, _, upper, _ = p
p[0] = ref[lower:upper]
@staticmethod
def p_slcref(p):
'''slcref : strref'''
p[0] = p[1]
@staticmethod
def p_subcircuit_singlelayer(p):
'''subcircuit : OPENBR layer CLOSEBR'''
p[0] = p[2], # subcircuit should be a tuple of layers - and p[2] is a *single* layer
@staticmethod
def p_subcircuit_string(p):
'''subcircuit : LPAREN layer RPAREN'''
p[0] = p[2]
@staticmethod
def p_layerable(p):
'''layerable : GATE
| INSTRMT '''
p[0] = p[1]
@staticmethod
def p_layerable_subcircuit(p):
'''layerable : subcircuit '''
plbl = _lbl.Label((p[1],)) # just for total sslbls
p[0] = _lbl.CircuitLabel('', p[1], plbl.sslbls, 1),
@staticmethod
def p_layerable_subcircuit_expop(p):
'''layerable : subcircuit EXPOP INTEGER'''
plbl = _lbl.Label(p[1]) # just for total sslbls
p[0] = _lbl.CircuitLabel('', p[1], plbl.sslbls, p[3]),
@staticmethod
def p_layer_layerable(p):
'''layer : layerable'''
p[0] = p[1]
@staticmethod
def p_layer_str(p):
'''layer : layer layerable'''
p[0] = p[1] + p[2] # tuple concatenation
@staticmethod
def p_layer(p):
'''layer : layer MULTOP layerable'''
p[0] = p[1] + p[3] # tuple concatenation
@staticmethod
def p_expable_paren(p):
'''expable : LPAREN string RPAREN'''
p[0] = p[2]
@staticmethod
def p_expable_layer(p):
'''expable : OPENBR layer CLOSEBR'''
p[0] = p[2], # -> tuple
@staticmethod
def p_expable_empty_layer(p):
'''expable : OPENBR CLOSEBR'''
p[0] = ((),) # -> empty layer tuple
@staticmethod
def p_expable_single(p):
'''expable : GATE
| INSTRMT
| NOP '''
p[0] = p[1]
@staticmethod
def p_expable(p):
'''expable : slcref'''
p[0] = p[1]
@staticmethod
def p_expdstr_expop(p):
'''expdstr : expable EXPOP INTEGER'''
plbl = _lbl.Label(p[1]) # just for total sslbls
if len(p[1]) > 0:
p[0] = _lbl.CircuitLabel('', p[1], plbl.sslbls, p[3]),
else:
p[0] = () # special case of {}^power => remain empty
#OLD (before subcircuits) p[0] = p[1] * p[3] # tuple repetition
@staticmethod
def p_expdstr(p):
'''expdstr : expable'''
p[0] = p[1]
@staticmethod
def p_string_expdstr(p):
'''string : expdstr'''
p[0] = p[1]
@staticmethod
def p_string_str(p):
'''string : string expdstr'''
p[0] = p[1] + p[2] # tuple concatenation
@staticmethod
def p_string(p):
'''string : string MULTOP expdstr'''
p[0] = p[1] + p[3] # tuple concatenation
@staticmethod
def p_pstring(p):
'''pstring : string'''
p[0] = p[1]
@staticmethod
def p_pstring_prep(p):
'''pstring : PREP string'''
p[0] = p[1] + p[2]
@staticmethod
def p_ppstring(p):
'''ppstring : pstring'''
p[0] = p[1]
@staticmethod
def p_ppstring_povm(p):
'''ppstring : pstring POVM'''
p[0] = p[1] + p[2]
@staticmethod
def p_error(p):
message = "Syntax error"
if p is not None:
message += " at pos {} of input {}".format(p.lexpos, p.lexer.lexdata)
raise ValueError(message)
def ply_parse(self, code, create_subcircuits=True):
"""
Perform lexing and parsing of `code`.
Parameters
----------
code : str
A circuit encoded as a single-line string
Returns
-------
layer_labels : tuple
A tuple of the layer-labels of the circuit
line_labels : tuple
A tuple of the line labels of the circuit.
"""
if '@' in code: # format: <string>@<line_labels>
code, labels = code.split('@')
labels = labels.strip("( )") # remove opening and closing parenthesis
def process(x): return int(x) if x.strip().isdigit() else x.strip()
labels = tuple(map(process, labels.split(',')))
else:
labels = None
self._lexer.input(code)
result = self._parser.parse(lexer=self._lexer)
return result, labels