tequila-basic 1.9.8__py3-none-any.whl → 1.9.10__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. tequila/__init__.py +29 -14
  2. tequila/apps/__init__.py +14 -5
  3. tequila/apps/_unary_state_prep_impl.py +145 -112
  4. tequila/apps/adapt/__init__.py +9 -1
  5. tequila/apps/adapt/adapt.py +154 -113
  6. tequila/apps/krylov/__init__.py +1 -1
  7. tequila/apps/krylov/krylov.py +23 -21
  8. tequila/apps/robustness/helpers.py +10 -6
  9. tequila/apps/robustness/interval.py +238 -156
  10. tequila/apps/unary_state_prep.py +29 -23
  11. tequila/autograd_imports.py +8 -5
  12. tequila/circuit/__init__.py +2 -1
  13. tequila/circuit/_gates_impl.py +135 -67
  14. tequila/circuit/circuit.py +177 -88
  15. tequila/circuit/compiler.py +114 -105
  16. tequila/circuit/gates.py +288 -120
  17. tequila/circuit/gradient.py +35 -23
  18. tequila/circuit/noise.py +83 -74
  19. tequila/circuit/postselection.py +120 -0
  20. tequila/circuit/pyzx.py +10 -6
  21. tequila/circuit/qasm.py +201 -83
  22. tequila/circuit/qpic.py +63 -61
  23. tequila/grouping/binary_rep.py +148 -146
  24. tequila/grouping/binary_utils.py +84 -75
  25. tequila/grouping/compile_groups.py +334 -230
  26. tequila/grouping/ev_utils.py +77 -41
  27. tequila/grouping/fermionic_functions.py +383 -308
  28. tequila/grouping/fermionic_methods.py +170 -123
  29. tequila/grouping/overlapping_methods.py +69 -52
  30. tequila/hamiltonian/paulis.py +12 -13
  31. tequila/hamiltonian/paulistring.py +1 -1
  32. tequila/hamiltonian/qubit_hamiltonian.py +45 -35
  33. tequila/ml/__init__.py +1 -0
  34. tequila/ml/interface_torch.py +19 -16
  35. tequila/ml/ml_api.py +11 -10
  36. tequila/ml/utils_ml.py +12 -11
  37. tequila/objective/__init__.py +8 -3
  38. tequila/objective/braket.py +55 -47
  39. tequila/objective/objective.py +91 -56
  40. tequila/objective/qtensor.py +36 -27
  41. tequila/optimizers/__init__.py +31 -23
  42. tequila/optimizers/_containers.py +11 -7
  43. tequila/optimizers/optimizer_base.py +111 -83
  44. tequila/optimizers/optimizer_gd.py +258 -231
  45. tequila/optimizers/optimizer_gpyopt.py +56 -42
  46. tequila/optimizers/optimizer_scipy.py +157 -112
  47. tequila/quantumchemistry/__init__.py +66 -38
  48. tequila/quantumchemistry/chemistry_tools.py +394 -203
  49. tequila/quantumchemistry/encodings.py +121 -13
  50. tequila/quantumchemistry/madness_interface.py +170 -96
  51. tequila/quantumchemistry/orbital_optimizer.py +86 -40
  52. tequila/quantumchemistry/psi4_interface.py +166 -97
  53. tequila/quantumchemistry/pyscf_interface.py +70 -23
  54. tequila/quantumchemistry/qc_base.py +866 -414
  55. tequila/simulators/__init__.py +0 -3
  56. tequila/simulators/simulator_api.py +258 -106
  57. tequila/simulators/simulator_aqt.py +102 -0
  58. tequila/simulators/simulator_base.py +156 -55
  59. tequila/simulators/simulator_cirq.py +58 -42
  60. tequila/simulators/simulator_cudaq.py +600 -0
  61. tequila/simulators/simulator_ddsim.py +390 -0
  62. tequila/simulators/simulator_mqp.py +30 -0
  63. tequila/simulators/simulator_pyquil.py +190 -171
  64. tequila/simulators/simulator_qibo.py +95 -87
  65. tequila/simulators/simulator_qiskit.py +124 -114
  66. tequila/simulators/simulator_qlm.py +52 -26
  67. tequila/simulators/simulator_qulacs.py +85 -59
  68. tequila/simulators/simulator_spex.py +464 -0
  69. tequila/simulators/simulator_symbolic.py +6 -5
  70. tequila/simulators/test_spex_simulator.py +208 -0
  71. tequila/tools/convenience.py +4 -4
  72. tequila/tools/qng.py +72 -64
  73. tequila/tools/random_generators.py +38 -34
  74. tequila/utils/bitstrings.py +13 -7
  75. tequila/utils/exceptions.py +19 -5
  76. tequila/utils/joined_transformation.py +8 -10
  77. tequila/utils/keymap.py +0 -5
  78. tequila/utils/misc.py +6 -4
  79. tequila/version.py +1 -1
  80. tequila/wavefunction/qubit_wavefunction.py +52 -30
  81. {tequila_basic-1.9.8.dist-info → tequila_basic-1.9.10.dist-info}/METADATA +23 -17
  82. tequila_basic-1.9.10.dist-info/RECORD +93 -0
  83. {tequila_basic-1.9.8.dist-info → tequila_basic-1.9.10.dist-info}/WHEEL +1 -1
  84. tequila_basic-1.9.8.dist-info/RECORD +0 -86
  85. {tequila_basic-1.9.8.dist-info → tequila_basic-1.9.10.dist-info/licenses}/LICENSE +0 -0
  86. {tequila_basic-1.9.8.dist-info → tequila_basic-1.9.10.dist-info}/top_level.txt +0 -0
@@ -1,4 +1 @@
1
1
 
2
-
3
-
4
-
@@ -1,22 +1,43 @@
1
1
  from collections import namedtuple
2
- import typing, warnings, numpy
2
+ import typing
3
+ import warnings
4
+ import numpy
3
5
  from numbers import Real as RealNumber
4
6
  from typing import Dict, Union, Hashable
5
7
  import pkg_resources
6
8
  from pkg_resources import DistributionNotFound
7
-
8
9
  from tequila.objective import Objective, Variable, assign_variable, format_variable_dictionary, QTensor
9
10
  from tequila.utils.exceptions import TequilaException, TequilaWarning
10
11
  from tequila.simulators.simulator_base import BackendCircuit, BackendExpectationValue
11
12
  from tequila.circuit.noise import NoiseModel
12
13
  from tequila.wavefunction.qubit_wavefunction import QubitWaveFunction
14
+ from tequila.simulators.simulator_symbolic import BackendCircuitSymbolic, BackendExpectationValueSymbolic
13
15
 
14
- SUPPORTED_BACKENDS = ["qulacs", "qulacs_gpu", "qibo", "qiskit", "qiskit_gpu", "cirq", "pyquil", "symbolic", "qlm"]
15
- SUPPORTED_NOISE_BACKENDS = ["qiskit", "qiskit_gpu", "cirq", "pyquil"] # qulacs removed in v.1.9
16
- BackendTypes = namedtuple('BackendTypes', 'CircType ExpValueType')
16
+ SUPPORTED_BACKENDS = [
17
+ "qulacs",
18
+ "qulacs_gpu",
19
+ "qibo",
20
+ "qiskit",
21
+ "qiskit_gpu",
22
+ "cirq",
23
+ "pyquil",
24
+ "symbolic",
25
+ "qlm",
26
+ "spex",
27
+ "aqt",
28
+ "mqp",
29
+ "ddsim",
30
+ "cudaq",
31
+ ]
32
+
33
+ # TODO: Reenable noise for Qiskit
34
+ SUPPORTED_NOISE_BACKENDS = ["cirq", "pyquil"] # qulacs removed in v.1.9
35
+
36
+ BackendTypes = namedtuple("BackendTypes", "CircType ExpValueType")
17
37
  INSTALLED_SIMULATORS = {}
18
38
  INSTALLED_SAMPLERS = {}
19
39
 
40
+
20
41
  HAS_QULACS = True
21
42
  INSTALLED_NOISE_SAMPLERS = {}
22
43
  if typing.TYPE_CHECKING:
@@ -29,14 +50,51 @@ Check which simulators are installed
29
50
  We are distinguishing two classes of simulators: Samplers and full wavefunction simulators
30
51
  """
31
52
 
53
+ # a check block for cudaq
54
+ HAS_CUDAQ = True
55
+ try:
56
+ from tequila.simulators.simulator_cudaq import BackendCircuitCudaq, BackendExpectationValueCudaq
57
+
58
+ INSTALLED_SIMULATORS["cudaq"] = BackendTypes(BackendCircuitCudaq, BackendExpectationValueCudaq)
59
+ except ImportError:
60
+ HAS_CUDAQ = False
61
+
62
+
63
+ HAS_SPEX = True
64
+ try:
65
+ from tequila.simulators.simulator_spex import BackendCircuitSpex, BackendExpectationValueSpex
66
+
67
+ INSTALLED_SIMULATORS["spex"] = BackendTypes(BackendCircuitSpex, BackendExpectationValueSpex)
68
+ except ImportError:
69
+ HAS_SPEX = False
70
+
71
+ # mqp and aqt are samplers, not simulators
72
+ HAS_AQT = True
73
+ try:
74
+ from tequila.simulators.simulator_aqt import BackendCircuitAQT, BackendExpectationValueAQT
75
+
76
+ INSTALLED_SAMPLERS["aqt"] = BackendTypes(BackendCircuitAQT, BackendExpectationValueAQT)
77
+ except ImportError:
78
+ HAS_AQT = False
79
+
80
+ HAS_MQP = True
81
+ try:
82
+ from tequila.simulators.simulator_mqp import BackendCircuitMQP, BackendExpectationValueMQP
83
+
84
+ INSTALLED_SAMPLERS["mqp"] = BackendTypes(BackendCircuitMQP, BackendExpectationValueMQP)
85
+ except ImportError:
86
+ HAS_MQP = False
87
+
32
88
 
33
89
  HAS_QISKIT = True
34
90
  try:
35
91
  from tequila.simulators.simulator_qiskit import BackendCircuitQiskit, BackendExpectationValueQiskit
92
+
36
93
  HAS_QISKIT = True
37
94
  INSTALLED_SIMULATORS["qiskit"] = BackendTypes(BackendCircuitQiskit, BackendExpectationValueQiskit)
38
95
  INSTALLED_SAMPLERS["qiskit"] = BackendTypes(BackendCircuitQiskit, BackendExpectationValueQiskit)
39
96
  from tequila.simulators.simulator_qiskit import HAS_NOISE as HAS_QISKIT_NOISE
97
+
40
98
  if HAS_QISKIT_NOISE:
41
99
  INSTALLED_NOISE_SAMPLERS["qiskit"] = BackendTypes(BackendCircuitQiskit, BackendExpectationValueQiskit)
42
100
  except ImportError:
@@ -46,10 +104,12 @@ except ImportError:
46
104
  try:
47
105
  pkg_resources.require("qiskit-aer-gpu")
48
106
  from tequila.simulators.simulator_qiskit_gpu import BackendCircuitQiskitGpu, BackendExpectationValueQiskitGpu
107
+
49
108
  HAS_QISKIT_GPU = True
50
109
  INSTALLED_SIMULATORS["qiskit_gpu"] = BackendTypes(BackendCircuitQiskitGpu, BackendExpectationValueQiskitGpu)
51
110
  INSTALLED_SAMPLERS["qiskit_gpu"] = BackendTypes(BackendCircuitQiskitGpu, BackendExpectationValueQiskitGpu)
52
111
  from tequila.simulators.simulator_qiskit import HAS_NOISE as HAS_QISKIT_GPU_NOISE
112
+
53
113
  if HAS_QISKIT_GPU_NOISE:
54
114
  INSTALLED_NOISE_SAMPLERS["qiskit_gpu"] = BackendTypes(BackendCircuitQiskitGpu, BackendExpectationValueQiskitGpu)
55
115
  except (ImportError, DistributionNotFound):
@@ -59,6 +119,7 @@ except (ImportError, DistributionNotFound):
59
119
  HAS_QIBO = True
60
120
  try:
61
121
  from tequila.simulators.simulator_qibo import BackendCircuitQibo, BackendExpectationValueQibo
122
+
62
123
  HAS_QIBO = True
63
124
  INSTALLED_SIMULATORS["qibo"] = BackendTypes(BackendCircuitQibo, BackendExpectationValueQibo)
64
125
  INSTALLED_SAMPLERS["qibo"] = BackendTypes(BackendCircuitQibo, BackendExpectationValueQibo)
@@ -73,8 +134,9 @@ try:
73
134
  HAS_CIRQ = True
74
135
  INSTALLED_SIMULATORS["cirq"] = BackendTypes(CircType=BackendCircuitCirq, ExpValueType=BackendExpectationValueCirq)
75
136
  INSTALLED_SAMPLERS["cirq"] = BackendTypes(CircType=BackendCircuitCirq, ExpValueType=BackendExpectationValueCirq)
76
- INSTALLED_NOISE_SAMPLERS["cirq"] = BackendTypes(CircType=BackendCircuitCirq,
77
- ExpValueType=BackendExpectationValueCirq)
137
+ INSTALLED_NOISE_SAMPLERS["cirq"] = BackendTypes(
138
+ CircType=BackendCircuitCirq, ExpValueType=BackendExpectationValueCirq
139
+ )
78
140
 
79
141
  except ImportError:
80
142
  HAS_CIRQ = False
@@ -85,12 +147,15 @@ try:
85
147
  from tequila.simulators.simulator_qulacs import BackendCircuitQulacs, BackendExpectationValueQulacs
86
148
 
87
149
  HAS_QULACS = True
88
- INSTALLED_SIMULATORS["qulacs"] = BackendTypes(CircType=BackendCircuitQulacs,
89
- ExpValueType=BackendExpectationValueQulacs)
90
- INSTALLED_SAMPLERS["qulacs"] = BackendTypes(CircType=BackendCircuitQulacs,
91
- ExpValueType=BackendExpectationValueQulacs)
92
- INSTALLED_NOISE_SAMPLERS["qulacs"] = BackendTypes(CircType=BackendCircuitQulacs,
93
- ExpValueType=BackendExpectationValueQulacs)
150
+ INSTALLED_SIMULATORS["qulacs"] = BackendTypes(
151
+ CircType=BackendCircuitQulacs, ExpValueType=BackendExpectationValueQulacs
152
+ )
153
+ INSTALLED_SAMPLERS["qulacs"] = BackendTypes(
154
+ CircType=BackendCircuitQulacs, ExpValueType=BackendExpectationValueQulacs
155
+ )
156
+ INSTALLED_NOISE_SAMPLERS["qulacs"] = BackendTypes(
157
+ CircType=BackendCircuitQulacs, ExpValueType=BackendExpectationValueQulacs
158
+ )
94
159
  except (ImportError, DistributionNotFound):
95
160
  HAS_QULACS = False
96
161
 
@@ -100,12 +165,15 @@ try:
100
165
  from tequila.simulators.simulator_qulacs_gpu import BackendCircuitQulacsGpu, BackendExpectationValueQulacsGpu
101
166
 
102
167
  HAS_QULACS_GPU = True
103
- INSTALLED_SIMULATORS["qulacs_gpu"] = BackendTypes(CircType=BackendCircuitQulacsGpu,
104
- ExpValueType=BackendExpectationValueQulacsGpu)
105
- INSTALLED_SAMPLERS["qulacs_gpu"] = BackendTypes(CircType=BackendCircuitQulacsGpu,
106
- ExpValueType=BackendExpectationValueQulacsGpu)
107
- INSTALLED_NOISE_SAMPLERS["qulacs_gpu"] = BackendTypes(CircType=BackendCircuitQulacsGpu,
108
- ExpValueType=BackendExpectationValueQulacsGpu)
168
+ INSTALLED_SIMULATORS["qulacs_gpu"] = BackendTypes(
169
+ CircType=BackendCircuitQulacsGpu, ExpValueType=BackendExpectationValueQulacsGpu
170
+ )
171
+ INSTALLED_SAMPLERS["qulacs_gpu"] = BackendTypes(
172
+ CircType=BackendCircuitQulacsGpu, ExpValueType=BackendExpectationValueQulacsGpu
173
+ )
174
+ INSTALLED_NOISE_SAMPLERS["qulacs_gpu"] = BackendTypes(
175
+ CircType=BackendCircuitQulacsGpu, ExpValueType=BackendExpectationValueQulacsGpu
176
+ )
109
177
  except (ImportError, DistributionNotFound):
110
178
  HAS_QULACS_GPU = False
111
179
 
@@ -132,30 +200,42 @@ try:
132
200
  except ImportError:
133
201
  HAS_QLM = False
134
202
 
135
- from tequila.simulators.simulator_symbolic import BackendCircuitSymbolic, BackendExpectationValueSymbolic
136
-
137
- INSTALLED_SIMULATORS["symbolic"] = BackendTypes(CircType=BackendCircuitSymbolic,
138
- ExpValueType=BackendExpectationValueSymbolic)
203
+ INSTALLED_SIMULATORS["symbolic"] = BackendTypes(
204
+ CircType=BackendCircuitSymbolic, ExpValueType=BackendExpectationValueSymbolic
205
+ )
139
206
  HAS_SYMBOLIC = True
140
207
 
208
+ HAS_DDSIM = True
209
+ try:
210
+ from tequila.simulators.simulator_ddsim import BackendCircuitDDSim, BackendExpectationValueDDSim
211
+
212
+ INSTALLED_SIMULATORS["ddsim"] = BackendTypes(BackendCircuitDDSim, BackendExpectationValueDDSim)
213
+ INSTALLED_SAMPLERS["ddsim"] = BackendTypes(BackendCircuitDDSim, BackendExpectationValueDDSim)
214
+ except ImportError:
215
+ HAS_DDSIM = False
216
+
141
217
 
142
218
  def show_available_simulators():
143
219
  """ """
144
220
  print("{:15} | {:10} | {:10} | {:10} | {:10}".format("backend", "wfn", "sampling", "noise", "installed"))
145
221
  print("--------------------------------------------------------------------")
146
222
  for k in SUPPORTED_BACKENDS:
147
- print("{:15} | {:10} | {:10} | {:10} | {:10}".format(k,
148
- str(k in INSTALLED_SIMULATORS),
149
- str(k in INSTALLED_SAMPLERS),
150
- str(k in INSTALLED_NOISE_SAMPLERS),
151
- str(k in INSTALLED_BACKENDS)))
223
+ print(
224
+ "{:15} | {:10} | {:10} | {:10} | {:10}".format(
225
+ k,
226
+ str(k in INSTALLED_SIMULATORS),
227
+ str(k in INSTALLED_SAMPLERS),
228
+ str(k in INSTALLED_NOISE_SAMPLERS),
229
+ str(k in INSTALLED_BACKENDS),
230
+ )
231
+ )
152
232
  if HAS_QISKIT and not HAS_QISKIT_NOISE:
153
233
  print("missing qiskit_aer: no noisy simulation")
154
234
 
155
235
 
156
- def pick_backend(backend: str = None, samples: int = None, noise: NoiseModel = None, device=None,
157
- exclude_symbolic: bool = True) -> str:
158
-
236
+ def pick_backend(
237
+ backend: str = None, samples: int = None, noise: NoiseModel = None, device=None, exclude_symbolic: bool = True
238
+ ) -> str:
159
239
  """
160
240
  choose, or verify, a backend for the user.
161
241
  Parameters
@@ -178,11 +258,11 @@ def pick_backend(backend: str = None, samples: int = None, noise: NoiseModel = N
178
258
  the name of the chosen (or verified) backend.
179
259
  """
180
260
 
181
- if len(INSTALLED_SIMULATORS) == 0:
261
+ if len(INSTALLED_SIMULATORS) == 0 and len(INSTALLED_SAMPLERS) == 0:
182
262
  raise TequilaException("No simulators installed on your system")
183
263
 
184
264
  if backend is None and device is not None:
185
- raise TequilaException('device use requires backend specification!')
265
+ raise TequilaException("device use requires backend specification!")
186
266
 
187
267
  if backend is None:
188
268
  if noise is None:
@@ -195,30 +275,28 @@ def pick_backend(backend: str = None, samples: int = None, noise: NoiseModel = N
195
275
  return f
196
276
  else:
197
277
  if samples is None:
198
- raise TequilaException(
199
- "Noise requires sampling; please provide a positive, integer value for samples")
278
+ raise TequilaException("Noise requires sampling; please provide a positive, integer value for samples")
200
279
  for f in SUPPORTED_NOISE_BACKENDS:
201
280
  return f
202
- raise TequilaException(
203
- 'Could not find any installed sampler!')
204
-
281
+ raise TequilaException("Could not find any installed sampler!")
205
282
 
206
283
  if hasattr(backend, "lower"):
207
284
  backend = backend.lower()
208
285
 
209
286
  if backend == "random":
210
287
  if device is not None:
211
- raise TequilaException('cannot ask for a random backend and a specific device!')
288
+ raise TequilaException("cannot ask for a random backend and a specific device!")
212
289
  from numpy import random as random
213
290
  import time
214
- state = random.RandomState(int(str(time.process_time()).split('.')[-1]) % 2 ** 32)
291
+
292
+ state = random.RandomState(int(str(time.process_time()).split(".")[-1]) % 2**32)
215
293
  if samples is None:
216
294
  backend = state.choice(list(INSTALLED_SIMULATORS.keys()), 1)[0]
217
295
  else:
218
296
  backend = state.choice(list(INSTALLED_SAMPLERS.keys()), 1)[0]
219
297
 
220
298
  if exclude_symbolic:
221
- while (backend == "symbolic"):
299
+ while backend == "symbolic":
222
300
  backend = state.choice(list(INSTALLED_SIMULATORS.keys()), 1)[0]
223
301
  return backend
224
302
 
@@ -231,19 +309,22 @@ def pick_backend(backend: str = None, samples: int = None, noise: NoiseModel = N
231
309
  raise TequilaException("Backend {backend} not installed or sampling not supported".format(backend=backend))
232
310
  elif noise is not None and samples is not None and backend not in INSTALLED_NOISE_SAMPLERS.keys():
233
311
  raise TequilaException(
234
- "Backend {backend} not installed or else Noise has not been implemented".format(backend=backend))
312
+ "Backend {backend} not installed or else Noise has not been implemented".format(backend=backend)
313
+ )
235
314
 
236
315
  return backend
237
316
 
238
317
 
239
- def compile_objective(objective: typing.Union['Objective'],
240
- variables: typing.Dict['Variable', 'RealNumber'] = None,
241
- backend: str = None,
242
- samples: int = None,
243
- device: str = None,
244
- noise: NoiseModel = None,
245
- *args,
246
- **kwargs) -> Objective:
318
+ def compile_objective(
319
+ objective: typing.Union["Objective"],
320
+ variables: typing.Dict["Variable", "RealNumber"] = None,
321
+ backend: str = None,
322
+ samples: int = None,
323
+ device: str = None,
324
+ noise: NoiseModel = None,
325
+ *args,
326
+ **kwargs,
327
+ ) -> Objective:
247
328
  """
248
329
  compile an objective to render it callable and return it.
249
330
  Parameters
@@ -275,7 +356,10 @@ def compile_objective(objective: typing.Union['Objective'],
275
356
  if variables is None:
276
357
  variables = {k: 0.0 for k in objective.extract_variables()}
277
358
 
278
- ExpValueType = INSTALLED_SIMULATORS[pick_backend(backend=backend)].ExpValueType
359
+ if samples is None:
360
+ ExpValueType = INSTALLED_SIMULATORS[pick_backend(backend=backend)].ExpValueType
361
+ else:
362
+ ExpValueType = INSTALLED_SAMPLERS[pick_backend(backend=backend, samples=samples)].ExpValueType
279
363
  all_compiled = True
280
364
  # check if compiling is necessary
281
365
  for arg in objective.args:
@@ -283,7 +367,10 @@ def compile_objective(objective: typing.Union['Objective'],
283
367
  if not isinstance(arg, ExpValueType):
284
368
  warnings.warn(
285
369
  "Looks like part the objective was already compiled for another backend.\nFound ExpectationValue of type {} and {}\n... proceeding with hybrid\n".format(
286
- type(arg), ExpValueType), TequilaWarning)
370
+ type(arg), ExpValueType
371
+ ),
372
+ TequilaWarning,
373
+ )
287
374
  elif hasattr(arg, "U") and not isinstance(arg, BackendExpectationValue):
288
375
  all_compiled = False
289
376
 
@@ -299,7 +386,9 @@ def compile_objective(objective: typing.Union['Objective'],
299
386
  for arg in argset:
300
387
  if hasattr(arg, "H") and hasattr(arg, "U") and not isinstance(arg, BackendExpectationValue):
301
388
  if arg not in expectationvalues:
302
- compiled_expval = ExpValueType(arg, variables=variables, noise=noise, device=device, *args, **kwargs)
389
+ compiled_expval = ExpValueType(
390
+ arg, variables=variables, noise=noise, device=device, *args, **kwargs
391
+ )
303
392
  expectationvalues[arg] = compiled_expval
304
393
  else:
305
394
  compiled_expval = expectationvalues[arg]
@@ -311,14 +400,16 @@ def compile_objective(objective: typing.Union['Objective'],
311
400
  return type(objective)(args=compiled_sets[0], transformation=objective.transformation)
312
401
 
313
402
 
314
- def compile_circuit(abstract_circuit: 'QCircuit',
315
- variables: typing.Dict['Variable', 'RealNumber'] = None,
316
- backend: str = None,
317
- samples: int = None,
318
- noise: NoiseModel = None,
319
- device: str = None,
320
- *args,
321
- **kwargs) -> BackendCircuit:
403
+ def compile_circuit(
404
+ abstract_circuit: "QCircuit",
405
+ variables: typing.Dict["Variable", "RealNumber"] = None,
406
+ backend: str = None,
407
+ samples: int = None,
408
+ noise: NoiseModel = None,
409
+ device: str = None,
410
+ *args,
411
+ **kwargs,
412
+ ) -> BackendCircuit:
322
413
  """
323
414
  compile a circuit to render it callable and return it.
324
415
  Parameters
@@ -344,8 +435,14 @@ def compile_circuit(abstract_circuit: 'QCircuit',
344
435
  the compiled circuit.
345
436
  """
346
437
 
347
- CircType = INSTALLED_SIMULATORS[
348
- pick_backend(backend=backend, samples=samples, noise=noise, device=device)].CircType
438
+ if samples is None:
439
+ CircType = INSTALLED_SIMULATORS[
440
+ pick_backend(backend=backend, samples=samples, noise=noise, device=device)
441
+ ].CircType
442
+ else:
443
+ CircType = INSTALLED_SAMPLERS[
444
+ pick_backend(backend=backend, samples=samples, noise=noise, device=device)
445
+ ].CircType
349
446
 
350
447
  # dummy variables
351
448
  if variables is None:
@@ -356,22 +453,27 @@ def compile_circuit(abstract_circuit: 'QCircuit',
356
453
  abstract_circuit = abstract_circuit.abstract_circuit
357
454
  warnings.warn(
358
455
  "Looks like the circuit was already compiled for another backend.\nChanging from {} to {}\n".format(
359
- type(abstract_circuit), CircType), TequilaWarning)
456
+ type(abstract_circuit), CircType
457
+ ),
458
+ TequilaWarning,
459
+ )
360
460
  else:
361
461
  return abstract_circuit
362
462
 
363
463
  return CircType(abstract_circuit=abstract_circuit, variables=variables, noise=noise, device=device, *args, **kwargs)
364
464
 
365
465
 
366
- def simulate(objective: typing.Union['Objective', 'QCircuit', 'QTensor'],
367
- variables: Dict[Union[Variable, Hashable], RealNumber] = None,
368
- samples: int = None,
369
- backend: str = None,
370
- noise: NoiseModel = None,
371
- device: str = None,
372
- initial_state: Union[int, QubitWaveFunction] = 0,
373
- *args,
374
- **kwargs) -> Union[RealNumber, QubitWaveFunction]:
466
+ def simulate(
467
+ objective: typing.Union["Objective", "QCircuit", "QTensor"],
468
+ variables: Dict[Union[Variable, Hashable], RealNumber] = None,
469
+ samples: int = None,
470
+ backend: str = None,
471
+ noise: NoiseModel = None,
472
+ device: str = None,
473
+ initial_state: Union[int, QubitWaveFunction] = 0,
474
+ *args,
475
+ **kwargs,
476
+ ) -> Union[RealNumber, QubitWaveFunction]:
375
477
  """Simulate a tequila objective or circuit
376
478
 
377
479
  Parameters
@@ -407,10 +509,20 @@ def simulate(objective: typing.Union['Objective', 'QCircuit', 'QTensor'],
407
509
  if variables is None and not (len(objective.extract_variables()) == 0):
408
510
  raise TequilaException(
409
511
  "You called simulate for a parametrized type but forgot to pass down the variables: {}".format(
410
- objective.extract_variables()))
411
-
412
- compiled_objective = compile(objective=objective, samples=samples, variables=variables, backend=backend,
413
- noise=noise, device=device, *args, **kwargs)
512
+ objective.extract_variables()
513
+ )
514
+ )
515
+
516
+ compiled_objective = compile(
517
+ objective=objective,
518
+ samples=samples,
519
+ variables=variables,
520
+ backend=backend,
521
+ noise=noise,
522
+ device=device,
523
+ *args,
524
+ **kwargs,
525
+ )
414
526
 
415
527
  return compiled_objective(variables=variables, samples=samples, initial_state=initial_state, *args, **kwargs)
416
528
 
@@ -438,6 +550,7 @@ def draw(objective, variables=None, backend: str = None, name=None, *args, **kwa
438
550
 
439
551
  if backend is None:
440
552
  from tequila.circuit.qpic import system_has_qpic
553
+
441
554
  if system_has_qpic:
442
555
  backend = "qpic"
443
556
  elif "cirq" in INSTALLED_SIMULATORS:
@@ -461,7 +574,7 @@ def draw(objective, variables=None, backend: str = None, name=None, *args, **kwa
461
574
  print("total measurements = {}".format(measurements))
462
575
  variables = E.U.extract_variables()
463
576
  print("variables = {}".format(len(variables)))
464
- filename = "{}_{}.png".format(name,i)
577
+ filename = "{}_{}.png".format(name, i)
465
578
  print("circuit = {}".format(filename))
466
579
  draw(E.U, backend=backend, filename=filename)
467
580
  drawn[E] = i
@@ -473,6 +586,7 @@ def draw(objective, variables=None, backend: str = None, name=None, *args, **kwa
473
586
  import IPython
474
587
  import qpic
475
588
  from tequila.circuit.qpic import export_to
589
+
476
590
  if "filename" not in kwargs:
477
591
  kwargs["filename"] = "tmp_{}.png".format(hash(backend))
478
592
 
@@ -483,17 +597,21 @@ def draw(objective, variables=None, backend: str = None, name=None, *args, **kwa
483
597
  circuit = objective.abstract_circuit
484
598
 
485
599
  export_to(circuit=circuit, *args, **kwargs)
486
- width=None # full size
487
- height=200
600
+ width = None # full size
601
+ height = 200
488
602
  if "width" in kwargs:
489
- width=kwargs["width"]
603
+ width = kwargs["width"]
490
604
  if "height" in kwargs:
491
- height=kwargs["height"] # this is buggy in jupyter and will be ignored
492
- image=IPython.display.Image(filename=kwargs["filename"], height=height, width=width)
605
+ height = kwargs["height"] # this is buggy in jupyter and will be ignored
606
+ image = IPython.display.Image(filename=kwargs["filename"], height=height, width=width)
493
607
  IPython.display.display(image)
494
608
 
495
609
  except ImportError as E:
496
- raise Exception("Original Error Message:{}\nYou are missing dependencies for drawing: You need IPython, qpic and pdfatex.\n".format(E))
610
+ raise Exception(
611
+ "Original Error Message:{}\nYou are missing dependencies for drawing: You need IPython, qpic and pdfatex.\n".format(
612
+ E
613
+ )
614
+ )
497
615
  else:
498
616
  compiled = compile_circuit(abstract_circuit=objective, backend=backend)
499
617
  if backend == "qiskit":
@@ -502,14 +620,17 @@ def draw(objective, variables=None, backend: str = None, name=None, *args, **kwa
502
620
  print(compiled.circuit)
503
621
  return ""
504
622
 
505
- def compile(objective: typing.Union['Objective', 'QCircuit', 'QTensor'],
506
- variables: Dict[Union['Variable', Hashable], RealNumber] = None,
507
- samples: int = None,
508
- backend: str = None,
509
- noise: NoiseModel = None,
510
- device: str = None,
511
- *args,
512
- **kwargs) -> typing.Union['BackendCircuit', 'Objective']:
623
+
624
+ def compile(
625
+ objective: typing.Union["Objective", "QCircuit", "QTensor"],
626
+ variables: Dict[Union["Variable", Hashable], RealNumber] = None,
627
+ samples: int = None,
628
+ backend: str = None,
629
+ noise: NoiseModel = None,
630
+ device: str = None,
631
+ *args,
632
+ **kwargs,
633
+ ) -> typing.Union["BackendCircuit", "Objective"]:
513
634
  """Compile a tequila objective or circuit to a backend
514
635
 
515
636
  Parameters
@@ -542,21 +663,50 @@ def compile(objective: typing.Union['Objective', 'QCircuit', 'QTensor'],
542
663
 
543
664
  if isinstance(objective, QTensor):
544
665
  ff = numpy.vectorize(compile_objective)
545
- return ff(objective=objective, samples=samples, variables=variables, backend=backend, noise=noise, device=device, *args, **kwargs)
546
-
666
+ return ff(
667
+ objective=objective,
668
+ samples=samples,
669
+ variables=variables,
670
+ backend=backend,
671
+ noise=noise,
672
+ device=device,
673
+ *args,
674
+ **kwargs,
675
+ )
676
+
547
677
  if isinstance(objective, Objective) or hasattr(objective, "args"):
548
- return compile_objective(objective=objective, samples=samples, variables=variables, backend=backend, noise=noise, device=device, *args, **kwargs)
678
+ return compile_objective(
679
+ objective=objective,
680
+ samples=samples,
681
+ variables=variables,
682
+ backend=backend,
683
+ noise=noise,
684
+ device=device,
685
+ *args,
686
+ **kwargs,
687
+ )
549
688
  elif hasattr(objective, "gates") or hasattr(objective, "abstract_circuit"):
550
- return compile_circuit(abstract_circuit=objective, variables=variables, backend=backend,samples=samples,
551
- noise=noise, device=device, *args, **kwargs)
689
+ return compile_circuit(
690
+ abstract_circuit=objective,
691
+ variables=variables,
692
+ backend=backend,
693
+ samples=samples,
694
+ noise=noise,
695
+ device=device,
696
+ *args,
697
+ **kwargs,
698
+ )
552
699
  else:
553
700
  raise TequilaException(
554
- "Don't know how to compile object of type: {type}, \n{object}".format(type=type(objective),
555
- object=objective))
701
+ "Don't know how to compile object of type: {type}, \n{object}".format(
702
+ type=type(objective), object=objective
703
+ )
704
+ )
556
705
 
557
706
 
558
- def compile_to_function(objective: typing.Union['Objective', 'QCircuit'], *args,
559
- **kwargs) -> typing.Union['BackendCircuit', 'Objective']:
707
+ def compile_to_function(
708
+ objective: typing.Union["Objective", "QCircuit"], *args, **kwargs
709
+ ) -> typing.Union["BackendCircuit", "Objective"]:
560
710
  """
561
711
  Notes
562
712
  ----------
@@ -575,16 +725,18 @@ def compile_to_function(objective: typing.Union['Objective', 'QCircuit'], *args,
575
725
  """
576
726
 
577
727
  compiled_objective = compile(objective, *args, **kwargs)
578
- if 'variables' in kwargs:
579
- varnames = list(kwargs['variables'].keys())
728
+ if "variables" in kwargs:
729
+ varnames = list(kwargs["variables"].keys())
580
730
  else:
581
731
  varnames = objective.extract_variables()
582
732
 
583
733
  def objective_function(*fargs, **fkwargs):
584
734
  if len(fargs) != len(varnames):
585
- raise Exception("Compiled function takes {} variables. You passed down {} arguments."
586
- "Use keywords for samples and other instructions\n"
587
- "like function(a,b,c, samples=10)".format(len(varnames), len(fargs)))
735
+ raise Exception(
736
+ "Compiled function takes {} variables. You passed down {} arguments."
737
+ "Use keywords for samples and other instructions\n"
738
+ "like function(a,b,c, samples=10)".format(len(varnames), len(fargs))
739
+ )
588
740
  vars = {varnames[i]: fargs[i] for i, v in enumerate(fargs)}
589
741
  return compiled_objective(variables=vars, **fkwargs)
590
742