-
Notifications
You must be signed in to change notification settings - Fork 7
/
estimator.py
333 lines (271 loc) · 10.6 KB
/
estimator.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
# 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 collections.abc import Collection, Iterable, Sequence
from typing import TYPE_CHECKING, Any, Callable, NamedTuple, Optional
import juliacall
import numpy as np
from juliacall import Main as jl
from typing_extensions import TypeAlias
from quri_parts.core.estimator import (
ConcurrentParametricQuantumEstimator,
ConcurrentQuantumEstimator,
Estimatable,
Estimate,
ParametricQuantumEstimator,
QuantumEstimator,
create_parametric_estimator,
)
from quri_parts.core.operator import zero
from quri_parts.core.state import CircuitQuantumState, ParametricCircuitQuantumState
from quri_parts.core.utils.concurrent import execute_concurrently
from quri_parts.itensor.load_itensor import ensure_itensor_loaded
from .circuit import convert_circuit
from .operator import convert_operator
if TYPE_CHECKING:
from concurrent.futures import Executor
class _Estimate(NamedTuple):
value: complex
error: float = np.nan
#: A type alias for state classes supported by ITensor estimators.
#: ITensor estimators support circuit states.
ITensorStateT: TypeAlias = CircuitQuantumState
#: A type alias for parametric state classes supported by ITensor estimators.
#: ITensor estimators support circuit states.
ITensorParametricStateT: TypeAlias = ParametricCircuitQuantumState
def _estimate(
operator: Estimatable, state: ITensorStateT, **kwargs: Any
) -> Estimate[complex]:
if operator == zero():
return _Estimate(value=0.0, error=0.0)
qubits = state.qubit_count
s: juliacall.VectorValue = jl.siteinds("Qubit", qubits)
psi: juliacall.AnyValue = jl.init_state(s, qubits)
# create ITensor circuit
circuit = convert_circuit(state.circuit, s)
# create ITensor operator
op = convert_operator(operator, s)
# apply circuit
psi = jl.apply(circuit, psi, **kwargs)
# calculate expectation value
error = 0.0
if any(k in kwargs for k in ["mindim", "maxdim", "cutoff"]):
# See https://github.com/QunaSys/quri-parts/pull/203#discussion_r1329458816
error = np.nan
psi = jl.normalize(psi)
exp: float = jl.expectation(psi, op)
return _Estimate(value=exp, error=error)
def create_itensor_mps_estimator(
*,
maxdim: Optional[int] = None,
cutoff: Optional[float] = None,
**kwargs: Any,
) -> QuantumEstimator[ITensorStateT]:
"""Returns a :class:`~QuantumEstimator` that uses ITensor MPS simulator to
calculate expectation values.
The following parameters including keyword
arguments `**kwargs` are passed to `ITensors.apply
<https://itensor.github.io/ITensors.jl/dev/MPSandMPO.html#ITensors.product-Tuple{ITensor,%20ITensors.AbstractMPS}>`_.
Args:
maxdim: The maximum number of singular values.
cutoff: Singular value truncation cutoff.
"""
ensure_itensor_loaded()
def estimator(operator: Estimatable, state: ITensorStateT) -> Estimate[complex]:
if maxdim is not None:
kwargs["maxdim"] = maxdim
if cutoff is not None:
kwargs["cutoff"] = cutoff
return _estimate(operator, state, **kwargs)
return estimator
def _sequential_estimate_single_state(
state: ITensorStateT,
operators: Sequence[Estimatable],
**kwargs: Any,
) -> Sequence[Estimate[complex]]:
qubits = state.qubit_count
s: juliacall.VectorValue = jl.siteinds("Qubit", qubits)
psi: juliacall.AnyValue = jl.init_state(s, qubits)
circuit = convert_circuit(state.circuit, s)
psi = jl.apply(circuit, psi, **kwargs)
if any(k in kwargs for k in ["mindim", "maxdim", "cutoff"]):
psi = jl.normalize(psi)
results = []
for op in operators:
if op == zero():
results.append(_Estimate(value=0.0, error=0.0))
continue
itensor_op = convert_operator(op, s)
# See https://github.com/QunaSys/quri-parts/pull/203#discussion_r1329458816
error = 0.0
if any(k in kwargs for k in ["mindim", "maxdim", "cutoff"]):
error = np.nan
results.append(_Estimate(value=jl.expectation(psi, itensor_op), error=error))
return results
def _concurrent_estimate(
_sequential_estimate: Callable[
[Any, Sequence[tuple[Estimatable, ITensorStateT]]], Sequence[Estimate[complex]]
],
_sequential_estimate_single_state: Callable[
[ITensorStateT, Sequence[Estimatable]], Sequence[Estimate[complex]]
],
operators: Collection[Estimatable],
states: Collection[ITensorStateT],
executor: Optional["Executor"],
concurrency: int = 1,
) -> Sequence[Estimate[complex]]:
num_ops = len(operators)
num_states = len(states)
if num_ops == 0:
raise ValueError("No operator specified.")
if num_states == 0:
raise ValueError("No state specified.")
if num_ops > 1 and num_states > 1 and num_ops != num_states:
raise ValueError(
f"Number of operators ({num_ops}) does not match"
f"number of states ({num_states})."
)
if num_states == 1:
return execute_concurrently(
_sequential_estimate_single_state,
next(iter(states)),
operators,
executor,
concurrency,
)
else:
if num_ops == 1:
operators = [next(iter(operators))] * num_states
return execute_concurrently(
_sequential_estimate, None, zip(operators, states), executor, concurrency
)
def create_itensor_mps_concurrent_estimator(
executor: Optional["Executor"] = None,
concurrency: int = 1,
*,
maxdim: Optional[int] = None,
cutoff: Optional[float] = None,
**kwargs: Any,
) -> ConcurrentQuantumEstimator[ITensorStateT]:
"""Returns a :class:`~ConcurrentQuantumEstimator` that uses ITensor MPS
simulator to calculate expectation values.
For now, this function works when the executor is defined like below
Examples:
>>> with ProcessPoolExecutor(
max_workers=2, mp_context=get_context("spawn")
) as executor:
The following parameters including
keyword arguments `**kwargs` are passed to `ITensors.apply
<https://itensor.github.io/ITensors.jl/dev/MPSandMPO.html#ITensors.product-Tuple{ITensor,%20ITensors.AbstractMPS}>`_.
Args:
maxdim: The maximum number of singular values.
cutoff: Singular value truncation cutoff.
"""
ensure_itensor_loaded()
if maxdim is not None:
kwargs["maxdim"] = maxdim
if cutoff is not None:
kwargs["cutoff"] = cutoff
mps_estimator = create_itensor_mps_estimator(**kwargs)
def _estimate_sequentially(
_: Any, op_state_tuples: Sequence[tuple[Estimatable, ITensorStateT]]
) -> Sequence[Estimate[complex]]:
return [mps_estimator(operator, state) for operator, state in op_state_tuples]
def _estimate_single_state_sequentially(
state: ITensorStateT, operators: Sequence[Estimatable]
) -> Sequence[Estimate[complex]]:
return _sequential_estimate_single_state(state, operators, **kwargs)
def estimator(
operators: Collection[Estimatable],
states: Collection[ITensorStateT],
) -> Iterable[Estimate[complex]]:
return _concurrent_estimate(
_estimate_sequentially,
_estimate_single_state_sequentially,
operators,
states,
executor,
concurrency,
)
return estimator
def _sequential_parametric_estimate(
op_state: tuple[Estimatable, ITensorParametricStateT],
params: Sequence[Sequence[float]],
**kwargs: Any,
) -> Sequence[Estimate[complex]]:
operator, state = op_state
estimates = []
estimator = create_itensor_mps_parametric_estimator(**kwargs)
for param in params:
estimates.append(estimator(operator, state, param))
return estimates
def create_itensor_mps_parametric_estimator(
*,
maxdim: Optional[int] = None,
cutoff: Optional[float] = None,
**kwargs: Any,
) -> ParametricQuantumEstimator[ITensorParametricStateT]:
"""Creates parametric estimator that uses ITensor MPS simulator to
calculate expectation values.
The following parameters including
keyword arguments `**kwargs` are passed to `ITensors.apply
<https://itensor.github.io/ITensors.jl/dev/MPSandMPO.html#ITensors.product-Tuple{ITensor,%20ITensors.AbstractMPS}>`_.
Args:
maxdim: The maximum number of singular values.
cutoff: Singular value truncation cutoff.
"""
ensure_itensor_loaded()
if maxdim is not None:
kwargs["maxdim"] = maxdim
if cutoff is not None:
kwargs["cutoff"] = cutoff
return create_parametric_estimator(create_itensor_mps_estimator(**kwargs))
def create_itensor_mps_concurrent_parametric_estimator(
executor: Optional["Executor"] = None,
concurrency: int = 1,
*,
maxdim: Optional[int] = None,
cutoff: Optional[float] = None,
**kwargs: Any,
) -> ConcurrentParametricQuantumEstimator[ITensorParametricStateT]:
"""Creates concurrent parametric estimator from parametric estimator.
The following parameters including
keyword arguments `**kwargs` are passed to `ITensors.apply
<https://itensor.github.io/ITensors.jl/dev/MPSandMPO.html#ITensors.product-Tuple{ITensor,%20ITensors.AbstractMPS}>`_.
Args:
maxdim: The maximum number of singular values.
cutoff: Singular value truncation cutoff.
"""
ensure_itensor_loaded()
if maxdim is not None:
kwargs["maxdim"] = maxdim
if cutoff is not None:
kwargs["cutoff"] = cutoff
def _estimate_sequentially(
op_state: tuple[Estimatable, ITensorParametricStateT],
params: Sequence[Sequence[float]],
) -> Sequence[Estimate[complex]]:
return _sequential_parametric_estimate(
op_state,
params,
**kwargs,
)
def estimator(
operator: Estimatable,
state: ITensorParametricStateT,
params: Sequence[Sequence[float]],
) -> Sequence[Estimate[complex]]:
return execute_concurrently(
_estimate_sequentially,
(operator, state),
params,
executor,
concurrency,
)
return estimator