mimiqcircuits.remote

Remote connection and execution utilities.

Classes

MimiqConnection([url, auth_url])

Connection to the MIMIQ cloud services.

PlanqkConnection([url, consumer_key, ...])

Connection to the MIMIQ services through the PlanQK gateway.

RemoteConnection(connection)

Base class for connections to the MIMIQ remote services.

class MimiqConnection(url=None, auth_url=None)[source]

Bases: RemoteConnection

Connection to the MIMIQ cloud services.

Wraps a mimiqlink.MimiqConnection, or a mimiqlink.QhiveConnection for Quantum Hive deployments, and adds the circuit execution API described in RemoteConnection. The object is created unauthenticated: call connect (or loadtoken) before submitting anything.

Examples

Connect to the default MIMIQ cloud. Without arguments connect opens 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, or mimiqlink.QPERFECT_CLOUD_V2 when auth_url is given).

  • auth_url (str, optional) – The URL of the authentication server. Giving one, or giving mimiqlink.QPERFECT_CLOUD_V2 or mimiqlink.QPERFECT_DEV as url, connects to Quantum Hive, which authenticates through Keycloak. The known URLs pick their own authentication server, so auth_url is 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_WARNING environment variable to off, false, no or 0 to silence it.

class PlanqkConnection(url=None, consumer_key=None, consumer_secret=None)[source]

Bases: RemoteConnection

Connection to the MIMIQ services through the PlanQK gateway.

Wraps a mimiqlink.PlanqkConnection and adds the circuit execution API described in RemoteConnection. Call connect before submitting anything.

Examples

Connect with explicit credentials. Without arguments, connect reads PLANQK_CONSUMER_KEY and PLANQK_CONSUMER_SECRET from 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)  
__init__(url=None, consumer_key=None, consumer_secret=None)[source]

Create an unauthenticated PlanQK connection.

Parameters:
  • url (str, optional) – The URL of the PlanQK gateway. Defaults to None (mimiqlink.PLANQK_API).

  • consumer_key (str, optional) – The PlanQK consumer key. Defaults to None.

  • consumer_secret (str, optional) – The PlanQK consumer secret. Defaults to None.

class RemoteConnection(connection)[source]

Bases: object

Base class for connections to the MIMIQ remote services.

It wraps a mimiqlink connection and adds the circuit execution API: submit(), optimize(), check_equivalence(), and the get_result/get_results/get_input/get_inputs retrieval 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 as conn.connect() can be chained.

Use MimiqConnection or PlanqkConnection rather than this class directly.

__init__(connection)[source]

Wrap an existing mimiqlink connection.

Parameters:

connection (mimiqlink.AbstractConnection) – A mimiqlink connection object, such as mimiqlink.MimiqConnection, mimiqlink.QhiveConnection or mimiqlink.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_result or get_results to 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. An EquivalenceExperiment is turned into its test circuit with build_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 circuits is a single Circuit, 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 GateU and GateCX. 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 from seed).

  • 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 entdim below 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 Circuit before 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:

str

Raises:
  • ValueError – If nsamples, timelimit, bonddim, entdim, mpscutoff, mpsmethod or mpotraversal is 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; if algorithm is "auto" with more than one circuit; or if noisemodel is given with a file path.

  • TypeError – If an item of circuits is not a circuit or a path, if noisemodel is not a NoiseModel, 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 a DeprecationWarning, 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 experiment with submit(), waits for the results and passes the first one to experiment.interpret_results.

Parameters:
Returns:

The verification score (probability of the all-zero state).

Return type:

float

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_result or get_results to wait for the execution and obtain OptimizationResults.

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 GateU and GateCX. 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 entdim below 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:

str

Raises:
  • ValueError – If a parameter is out of range, no experiment is given, or algorithm is "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()  
__repr__()[source]

Return a string representation of the connection.

__str__()[source]

Return a string representation of the connection.

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), with input the first entry of the list get_inputs() returns.

Return type:

tuple

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). inputs is a list with one Circuit per 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 one OptimizationExperiment per experiment of an optimization job. parameters is the dict of job parameters.

Return type:

tuple

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 as interval.

Returns:

The first result, or an OptimizationResults or a QCSError, as for get_results().

Return type:

QCSResults

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 every interval seconds, then downloads the results.

Parameters:
  • execution (str) – The job identifier returned by submit.

  • interval (float) – Seconds between status checks. Defaults to 1.

Returns:

One entry per circuit or experiment of the job, in order: a QCSResults, an OptimizationResults for optimization jobs, or a QCSError for a circuit that failed.

Return type:

list

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)