mimiqcircuits.remote¶
Remote connection and execution utilities.
Classes
|
Connection to the MIMIQ cloud services. |
|
Connection to the MIMIQ services through the PlanQK gateway. |
|
Base class for connections to the MIMIQ remote services. |
- class MimiqConnection(url=None, auth_url=None)[source]¶
Bases:
RemoteConnectionConnection to the MIMIQ cloud services.
Wraps a
mimiqlink.MimiqConnection, or amimiqlink.QhiveConnectionfor Quantum Hive deployments, and adds the circuit execution API described inRemoteConnection. The object is created unauthenticated: callconnect(orloadtoken) before submitting anything.Examples
Connect to the default MIMIQ cloud. Without arguments
connectopens a login page in the browser.>>> from mimiqcircuits import * >>> conn = MimiqConnection() >>> conn.connect()
Save the session token to reuse it later without logging in again.
>>> conn.savetoken("qperfect.json") >>> conn = MimiqConnection().loadtoken("qperfect.json")
Submit a circuit and wait for its results.
>>> c = Circuit() >>> c.push(GateH(), 0) 1-qubit circuit with 1 instruction: └── H @ q[0] >>> c.push(Measure(), 0, 0) 1-qubit, 1-bit circuit with 2 instructions: ├── H @ q[0] └── M @ q[0], c[0] >>> job = conn.submit(c, nsamples=100) >>> res = conn.get_result(job)
List past executions and close the session.
>>> conn.requests() >>> conn.close()
- __init__(url=None, auth_url=None)[source]¶
Create an unauthenticated connection.
- Parameters:
url (str, optional) – The URL of the MIMIQ service. Defaults to None (
mimiqlink.QPERFECT_CLOUD, ormimiqlink.QPERFECT_CLOUD_V2whenauth_urlis given).auth_url (str, optional) – The URL of the authentication server. Giving one, or giving
mimiqlink.QPERFECT_CLOUD_V2ormimiqlink.QPERFECT_DEVasurl, connects to Quantum Hive, which authenticates through Keycloak. The known URLs pick their own authentication server, soauth_urlis only needed for other deployments. Defaults to None.
- Warns:
FutureWarning – When connecting to the current MIMIQ web service, which will be deprecated in favour of MIMIQ V2. Set the
MIMIQ_V2_WARNINGenvironment variable tooff,false,noor0to silence it.
- class PlanqkConnection(url=None, consumer_key=None, consumer_secret=None)[source]¶
Bases:
RemoteConnectionConnection to the MIMIQ services through the PlanQK gateway.
Wraps a
mimiqlink.PlanqkConnectionand adds the circuit execution API described inRemoteConnection. Callconnectbefore submitting anything.Examples
Connect with explicit credentials. Without arguments,
connectreadsPLANQK_CONSUMER_KEYandPLANQK_CONSUMER_SECRETfrom the environment.>>> from mimiqcircuits import * >>> from mimiqcircuits.remote import PlanqkConnection >>> conn = PlanqkConnection() >>> conn.connect("my_consumer_key", "my_consumer_secret")
Submit and retrieve results as with
MimiqConnection.>>> c = Circuit() >>> c.push(GateX(), 0) 1-qubit circuit with 1 instruction: └── X @ q[0] >>> c.push(Measure(), 0, 0) 1-qubit, 1-bit circuit with 2 instructions: ├── X @ q[0] └── M @ q[0], c[0] >>> job = conn.submit(c) >>> res = conn.get_result(job)
- class RemoteConnection(connection)[source]¶
Bases:
objectBase class for connections to the MIMIQ remote services.
It wraps a
mimiqlinkconnection and adds the circuit execution API:submit(),optimize(),check_equivalence(), and theget_result/get_results/get_input/get_inputsretrieval methods. Any other attribute or method (connect,close,loadtoken,savetoken,requests,stopExecution, …) is forwarded to the wrapped connection. Forwarded methods that return the wrapped connection return this object instead, so calls such asconn.connect()can be chained.Use
MimiqConnectionorPlanqkConnectionrather than this class directly.- __init__(connection)[source]¶
Wrap an existing
mimiqlinkconnection.- Parameters:
connection (mimiqlink.AbstractConnection) – A
mimiqlinkconnection object, such asmimiqlink.MimiqConnection,mimiqlink.QhiveConnectionormimiqlink.PlanqkConnection.
- submit(circuits, label='pyapi_v0.33.0', algorithm='auto', nsamples=1000, bitstrings=None, timelimit=None, bonddim=None, entdim=None, mpscutoff=None, remove_swaps=None, canonicaldecompose=None, fuse=None, reorderqubits=None, reorderqubits_seed=None, seed=None, qasmincludes=None, force=False, mpsmethod=None, mpotraversal=None, noisemodel=None, streaming=None)[source]¶
Submit one or more circuits for execution on the remote service.
The call uploads the circuits and returns at once, without waiting for the execution to finish. Pass the returned identifier to
get_resultorget_resultsto wait for and download the results.Circuits are sent in protobuf format. File paths are uploaded as they are and must point to an OpenQASM 2.0 file (its first non-comment line is
OPENQASM 2.0;) or a STIM file. AnEquivalenceExperimentis turned into its test circuit withbuild_circuit()and submitted.- Parameters:
circuits (Circuit | str | EquivalenceExperiment | list) – A circuit, a path to an OpenQASM 2.0 or STIM file, an equivalence experiment, or a list of circuits and file paths.
label (str) – A label to identify the execution. Defaults to
"pyapi_v"followed by the package version.algorithm (str) – The simulator to use:
"auto","mps"or"statevector"."auto"lets the service choose and accepts a single circuit only. Defaults to"auto".nsamples (int) – The number of measurement samples to collect. At most
MAX_SAMPLES(65536). Defaults to 1000.bitstrings (list of BitString, optional) – Bitstrings whose amplitudes are computed. When
circuitsis a singleCircuit, each must have one bit per qubit. Defaults to None (no amplitudes).timelimit (int, optional) – The maximum execution time in minutes. Defaults to None, which uses the largest time limit allowed for the account (30 minutes if the service sets none).
bonddim (int, optional) – The MPS bond dimension, between 1 and 4096. Defaults to None, which means 256 for the
"auto"and"mps"algorithms.entdim (int, optional) – The MPS entanglement dimension, at least 4. Defaults to None, which means 16 for the
"auto"and"mps"algorithms.mpscutoff (float, optional) – Singular value truncation cutoff for MPS simulation. Smaller values give higher accuracy at higher cost. Must be non-negative. Defaults to None (the service decides).
remove_swaps (bool, optional) – Whether to remove SWAP gates by relabeling qubits. Defaults to None (the service decides).
canonicaldecompose (bool, optional) – Whether to decompose the circuit into
GateUandGateCX. Defaults to None (the service decides).fuse (bool, optional) – Whether to fuse gates. Defaults to None (the service decides).
reorderqubits (bool or str, optional) – Whether to reorder qubits, or the name of the reordering method (for example
"greedy","spectral","rcm","sa_warm_start","sa_only","memetic","multilevel","grasp","hybrid"). Defaults to None (the service decides).reorderqubits_seed (int, optional) – Seed for the qubit reordering, independent of
seed. Defaults to None (derived fromseed).seed (int, optional) – Seed for the simulation’s random number generator. Defaults to None (a random seed).
qasmincludes (list of str, optional) – Accepted for compatibility and not used.
force (bool) – If True, allow
entdimbelow 4 and print a warning instead of raising. Defaults to False.mpsmethod (str, optional) – How MPOs are applied in MPS simulation:
"vmpoa"or"vmpob"(variational) or"dmpo"(direct). Defaults to None (the service decides).mpotraversal (str, optional) – How the circuit is traversed when compressing it into MPOs:
"sequential","bfs"(breadth-first search) or"frontierpack"(packs independent ready gates into the open MPO, good for brickwork circuits). Defaults to None (the service decides).noisemodel (NoiseModel, optional) – A noise model applied to every
Circuitbefore upload. It cannot be applied to file paths. Defaults to None.streaming (bool, optional) – Whether to use the streaming simulator. Defaults to None (the service decides).
- Returns:
The identifier of the execution on the remote service.
- Return type:
- Raises:
ValueError – If
nsamples,timelimit,bonddim,entdim,mpscutoff,mpsmethodormpotraversalis out of range; if a bitstring has the wrong length; if the list of circuits is empty, contains an empty circuit, a circuit with unevaluated symbolic parameters, or a path that does not exist or is neither OpenQASM 2.0 nor STIM; ifalgorithmis"auto"with more than one circuit; or ifnoisemodelis given with a file path.TypeError – If an item of
circuitsis not a circuit or a path, ifnoisemodelis not aNoiseModel, or if a preparation flag has the wrong type.mimiqlink.MimiqConnectionError – If the connection is not authenticated or the upload fails.
Examples
>>> from mimiqcircuits import * >>> conn = MimiqConnection() >>> conn.connect()
Build a Bell-state circuit and measure both qubits.
>>> c = Circuit() >>> c.push(GateH(), 0) 1-qubit circuit with 1 instruction: └── H @ q[0] >>> c.push(GateCX(), 0, 1) 2-qubit circuit with 2 instructions: ├── H @ q[0] └── CX @ q[0], q[1] >>> c.push(Measure(), range(2), range(2)) 2-qubit, 2-bit circuit with 4 instructions: ├── H @ q[0] ├── CX @ q[0], q[1] ├── M @ q[0], c[0] └── M @ q[1], c[1]
Submit it: the call returns an identifier straight away.
>>> job = conn.submit(c, nsamples=1000, algorithm="statevector")
Wait for the execution to finish and download its results.
>>> res = conn.get_result(job) >>> res.histogram()
- execute(*args, **kwargs)[source]¶
Submit circuits for execution. Deprecated: use
submit().Takes the same arguments as
submit(), emits aDeprecationWarning, and returns the execution identifier without waiting for the execution to finish.
- check_equivalence(experiment, **kwargs)[source]¶
Run an equivalence experiment remotely and return its score.
Submits
experimentwithsubmit(), waits for the results and passes the first one toexperiment.interpret_results.- Parameters:
experiment (EquivalenceExperiment) – The experiment to run.
**kwargs – Keyword arguments passed to
submit().
- Returns:
The verification score (probability of the all-zero state).
- Return type:
- Raises:
RuntimeError – If the remote job fails or is canceled.
- optimize(experiments, label='pyapi_v0.33.0', algorithm='auto', nsamples=1000, timelimit=None, bonddim=None, entdim=None, mpscutoff=None, remove_swaps=None, canonicaldecompose=None, fuse=None, reorderqubits=None, reorderqubits_seed=None, seed=None, history=False, force=False, debug=False, mpsmethod=None, mpotraversal=None, streaming=None)[source]¶
Submit one or more optimization experiments to the remote service.
The call uploads the experiments and returns at once. Pass the returned identifier to
get_resultorget_resultsto wait for the execution and obtainOptimizationResults.- Parameters:
experiments (OptimizationExperiment or list) – An experiment or a list of experiments.
label (str) – A label to identify the execution. Defaults to
"pyapi_v"followed by the package version.algorithm (str) – The simulator to use:
"auto","mps"or"statevector"."auto"accepts a single experiment only. Defaults to"auto".nsamples (int) – The number of samples used to estimate expectation values. At most 65536. Defaults to 1000.
timelimit (int, optional) – The maximum execution time in minutes. Defaults to None (the largest limit allowed for the account).
bonddim (int, optional) – The MPS bond dimension. Defaults to None (256 for
"auto"and"mps").entdim (int, optional) – The MPS entanglement dimension. Defaults to None (16 for
"auto"and"mps").mpscutoff (float, optional) – Singular value truncation cutoff for MPS simulation. Defaults to None (the service decides).
remove_swaps (bool, optional) – Whether to remove SWAP gates. Defaults to None (the service decides).
canonicaldecompose (bool, optional) – Whether to decompose into
GateUandGateCX. Defaults to None (the service decides).fuse (bool, optional) – Whether to fuse gates. Defaults to None (the service decides).
reorderqubits (bool or str, optional) – Whether to reorder qubits, or the reordering method. Defaults to None (the service decides).
reorderqubits_seed (int, optional) – Seed for the qubit reordering. Defaults to None (derived from
seed).seed (int, optional) – Seed for the random number generator. Defaults to None (a random seed).
history (bool) – If True, record every evaluation of the optimization. Defaults to False.
force (bool) – If True, allow
entdimbelow 4 with a warning. Defaults to False.debug (bool) – If True, keep the temporary upload directory. Defaults to False.
mpsmethod (str, optional) –
"vmpoa","vmpob"or"dmpo". Defaults to None (the service decides).mpotraversal (str, optional) –
"sequential","bfs"or"frontierpack". Defaults to None (the service decides).streaming (bool, optional) – Whether to use the streaming simulator. Defaults to None (the service decides).
- Returns:
The identifier of the execution on the remote service.
- Return type:
- Raises:
ValueError – If a parameter is out of range, no experiment is given, or
algorithmis"auto"with more than one experiment.TypeError – If an item is not an
OptimizationExperiment, or a preparation flag has the wrong type.
Examples
>>> from mimiqcircuits import * >>> conn = MimiqConnection() >>> conn.connect()
Build a one-parameter circuit and the quantity to minimise.
>>> from symengine import symbols >>> x = symbols("x") >>> c = Circuit() >>> c.push(GateRX(x), 0) 1-qubit circuit with 1 instruction: └── RX(x) @ q[0] >>> c.push(ExpectationValue(GateZ()), 0, 0) 1-qubit, 1-zvar circuit with 2 instructions: ├── RX(x) @ q[0] └── ⟨Z⟩ @ q[0], z[0]
Minimise z[0] starting from x = 0.5, then fetch the best value.
>>> ex = OptimizationExperiment(c, {x: 0.5}, zregister=0) >>> job = conn.optimize(ex) >>> res = conn.get_result(job) >>> res.get_best()
- get_input(execution)¶
Download the inputs of a remote job and return the first one with the parameters.
Available as a method of the connection:
conn.get_input(job). If the job has more than one input, a warning is printed and only the first is returned.- Parameters:
execution (str) – The job identifier returned by
submit.- Returns:
(input, parameters), withinputthe first entry of the listget_inputs()returns.- Return type:
- Raises:
RuntimeError – As for
get_inputs().
- get_inputs(execution)¶
Download the inputs of a remote job: its circuits and its parameters.
Available as a method of the connection:
conn.get_inputs(job). The names of the downloaded files are printed.- Parameters:
execution (str) – The job identifier returned by
submit.- Returns:
(inputs, parameters).inputsis a list with oneCircuitper circuit job entry (or the path of a downloaded file for circuits submitted as QASM or Stim; the files are left in a new temporary directory, which is not removed), or oneOptimizationExperimentper experiment of an optimization job.parametersis the dict of job parameters.- Return type:
- Raises:
RuntimeError – If the job files are not a valid circuit or optimization job.
ValueError – If a circuit file has an unsupported type.
- get_result(execution, **kwargs)¶
Wait for a remote job to finish and return its first result.
Available as a method of the connection:
conn.get_result(job). Use it for jobs with a single circuit; if the job has more, a warning is printed and only the first result is returned.- Parameters:
execution (str) – The job identifier returned by
submit.**kwargs – Passed to
get_results(), such asinterval.
- Returns:
The first result, or an
OptimizationResultsor aQCSError, as forget_results().- Return type:
- Raises:
RuntimeError – As for
get_results().
- get_results(execution, interval=1)¶
Wait for a remote job to finish and return its results.
Available as a method of the connection:
conn.get_results(job). The call blocks, checking the job status everyintervalseconds, then downloads the results.- Parameters:
- Returns:
One entry per circuit or experiment of the job, in order: a
QCSResults, anOptimizationResultsfor optimization jobs, or aQCSErrorfor a circuit that failed.- Return type:
- Raises:
RuntimeError – If the whole job failed or was canceled, or its result files are missing.
Examples
>>> from mimiqcircuits import * >>> conn = MimiqConnection() >>> conn.connect() >>> c = Circuit().push(GateH(), 0).push(Measure(), 0, 0) >>> job = conn.submit(c, nsamples=100) >>> results = conn.get_results(job)