Module qisjob.qisjob

qisjob.pyx

Load from OpenQASM source or Qiskit QuantumCircuit source and run job with reporting. Many utility operations to examine provider, backends, and jobs are also provided.

The main repository is https://github.com/jwoehr/qisjob

Copyright 2019 Jack Woehr jwoehr@softwoehr.com PO Box 51, Golden, CO 80402-0051

Apache License, Version 2.0 – See LICENSE which you should have received with this code.

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.

The class to instance in a program is QisJob.

1. Instance a QisJob with appropriate kwargs.
2. Call the member function do_it()

Optionally, wrapper the do_it() in try - except.

The qisjob script is for command-line usage which instances a QisJob and calls do_it(). The script provides a --help switch which will explain all the optional arguments.

The qisjob script will be mentioned in the QisJob documentation. To better understand the documentation, we recommended that the reader execute

qisjob --help

and examine the output.

Note that many functions which are really private are exposed and documented here to make it easier to understand what QisJob does in its do_it() method.

Classes

class QisJob (filepaths=None, qasm_src=None, provider_name='IBMQ', hub='ibm-q', group='open', project='main', providers=False, backend_name=None, token=None, url=None, nuqasm2=None, num_qubits=5, shots=1024, max_credits=3, outfile_path=None, one_job=False, qasm=False, use_aer=False, use_qasm_simulator=False, use_unitary_simulator=False, use_statevector_gpu=False, use_unitary_gpu=False, use_density_matrix_gpu=False, use_sim=False, qvm=False, qvm_as=False, qc_name=None, xpile=False, showsched=False, circuit_layout=False, optimization_level=1, print_job=False, memory=False, show_result=False, jobs_status=None, job_id=None, job_result=None, show_backends=False, show_configuration=False, show_properties=False, show_statuses=False, date_time=None, print_histogram=False, print_state_city=0, figure_basename='figout', show_q_version=False, verbose=0, show_qisjob_version=False, use_job_monitor=False, job_monitor_filepath=None, job_monitor_line='\r', noisy_sim=False)

Embody preparation, execution, display, and management of Qiskit job or jobs.

A QisJob instance can also fetch information about provider backends.

A QisJob is instanced with all the member variables governing its behavior and then the do_it() member function is called. After that, generally, the instance is discarded.

QisJob's initializer instances QisJob member data which control the instance's behavior when QisJob's main function do_it() is called.

In the parameter discussion below, actions are described as being taken by QisJob. Typically, these actions are actually taken when the do_it() method is called, not when member variables are instanced at __init__ time.

Parameters

filepaths : str

The default is None.

Corresponding qisjob script argument: Any and all undecorated arguments following the -- decorated switch arguments are taken to be files to add to the filepaths kwarg.

List of fully qualified or relative filepaths for experiments.

If filepaths is None source is read from stdin.

If qasm_src is set, this kwarg is ignored.

qasm_src : str

The default is None.

Corresponding qisjob script argument: none

A string of OpenQASM experiment source.

If qasm_src is set, it takes precedence and filepaths is ignored.

provider_name : str

The default is "IBMQ".

Corresponding qisjob script argument: --api_provider

The name of the backend provider. Currently supported are

* IBMQ
* QI
* Forest
* JKU
hub : str

The default is 'ibm-q'.

Corresponding qisjob script argument: --hub

Provider hub. For instance, IBMQ accounts have 3 attributes, the names and defaults for which are

hub='ibm-q', group='open', project='main'
group : str

The default is 'open'.

Corresponding qisjob script argument: --group

Provider group. For instance, IBMQ accounts have 3 attributes, the names and defaults for which are

hub='ibm-q', group='open', project='main'
project : str

The default is 'main'.

Corresponding qisjob script argument: --project

Provider project. For instance, IBMQ accounts have 3 attributes, the names and defaults for which are

hub='ibm-q', group='open', project='main'
providers : bool

The default is False.

Corresponding qisjob script argument: --providers

List providers for IBM Q and return.

backend_name : str

The default is None.

Corresponding qisjob script argument: -b, --backend

Name of chosen backend for given provider.

If provider is IBMQ and backend_name is None, QisJob will search for least_busy().

token : str

The default is None.

Corresponding qisjob script argument: --token

Login token for provider. This is a string even if it looks like a giant hexadecimal number.

If provided, then url must also be provided.

If not provided, QisJob will either attempt the supported provider's automatic load of login credentials or simply attempt the connection without credentials.

url : str

The default is None.

Corresponding qisjob script argument: --url

URL of backend provider gateway

If provided, then token must also be provided.

If not provided, QisJob will assume the default URL for the supported provider's backend.

nuqasm2 : str

The default is None.

Corresponding qisjob script argument: --nuqasm2

This is a "double purpose" switch. Its target is an include path for OpenQASM include files, which, if present, serves to indicate that nuqasm2 should be used as the OpenQASM compiler.

num_qubits : int

The default is 5.

Corresponding qisjob script argument: -q, --qubits

Number of qubits required for any and all experiment(s).

shots : int

The default is 1024.

Corresponding qisjob script argument: -t, --shots

Number of shots performed for any and all experiment(s). Subject to limitation of the provider backend.

max_credits : int

The default is 3.

Corresponding qisjob script argument: -c, --credits

Max credits to expend on each job, default is 3. If provider has no credit scheme enabled, max_credits has no effect.

outfile_path : str

The default is stdout.

Corresponding qisjob script argument: -o, --outfile

Write CSV output of experiment(s) to the target argument.

one_job : bool

The default is False.

Corresponding qisjob script argument: -1, --one_job

Run all experiments provided via the filepaths member in one job.

The default is to submit one job per experiment.

qasm : bool

The default is False.

Corresponding qisjob script argument: --qasm

If True, print each qasm file to stdout before running job.

use_aer : bool

The default is False.

Corresponding qisjob script argument: -a, --aer

If True use QISKit Aer simulator.

The default Aer simulator is the Aer statevector simulator. In conjunction with this kwarg:

* Set use_qasm_simulator True for Aer qasm simulator.
* Set use_unitary_simulator True for Aer unitary simulator.

It is an error to set both qasm_simulator and unitary_simulator True.

use_qasm_simulator : bool

The default is False.

Corresponding qisjob script argument: --qasm_simulator

In conjunction with use_aer, use Aer's qasm simulator.

use_unitary_simulator : bool

The default is False.

Corresponding qisjob script argument: --unitary-simulator

In conjunction with use_aer, use Aer's unitary simulator.

use_statevector_gpu : bool

The default is False.

Corresponding qisjob script argument: --statevector_gpu

If True and use_aer is True and use_qasm_simulator is True, use gpu statevector simulator.

use_unitary_gpu : bool

The default is False.

Corresponding qisjob script argument: --unitary_gpu

If True and use_aer is True and use_qasm_simulator is True, use gpu unitary simulator.

use_density_matrix_gpu : bool

The default is False.

Corresponding qisjob script argument: --density_matrix_gpu

If True and use_aer is True and use_qasm_simulator is True, use gpu density matrix simulator.

use_sim : bool

The default is False.

Corresponding qisjob script argument: -s, --sim

If True, use IBMQ online qasm simulator

qvm : bool

The default is False.

Corresponding qisjob script argument: --qvm

If True. use Forest local qvm simulator described by backend_name, generally one of qasm_simulator or statevector_simulator. Use qvm_as to instruct the simulator to emulate a specific Rigetti QPU.

qvm_as : bool

The default is False.

Corresponding qisjob script argument: --qvm_as

If True. use Forest local qvm simulator to emulate the specific Rigetti QPU described by -b backend. Use –qvm to run the Forest local qvm simulator described by -b backend

qc_name : str

The default is None.

Corresponding qisjob script argument: --qc

If set, indicates the name of a variable instanced to a Python-coded QuantumCircuit to be run. If set, each and every file (or input from stdin) must contain valid Python code containing such an instance.

Do not include any Qiskit job control in the file. All that needs to be included or imported is the circuit itself.

Warning QisJob uses Python exec() to run your included circuit file. No sanitization is performed. The code will be executed as-is.

xpile : bool

The default is False.

Corresponding qisjob script argument: -x, --transpile

If True, test-transpile the circuit for chosen backend into a new circuit and print the new circuit to stdout before jobbing the original circuit.

The level of transpilation is that indicated by the kwarg optimization_level.

showsched : bool

The default is False.

Corresponding qisjob script argument: --showsched

If True, in conjuction with xpile, show schedule for the test- transpiled circuit to stdout before jobbing the original circuit.

circuit_layout

The default is False.

Corresponding qisjob script argument: -circuit_layout

If True, and if xpile is also set, write image file of circuit layout to the fully qualified filepath specified by the figure_basename kwarg concatenated with an algorithmically added filename extension indicating the type of output and time.

optimization_level : int

The default is 1.

Corresponding qisjob script argument: --optimization_level

Set optimization level for transpilation before run. Valid values are 0-3, default is 1.

This affects not only the actual circuit, but alsothe test transpile, if the latter is invoked by the xpile kwarg.

print_job : bool

The default is False.

Corresponding qisjob script argument: -j, --job

If True, print the Job dictionary to stdout before and after run.

memory : bool

The default is False.

Corresponding qisjob script argument: -m, --memory

If True, print individual results of each multishot experiment to stdout.

show_result : bool

The default is False.

Corresponding qisjob script argument: -r, --result

If True, print each Job's result to stdout.

jobs_status : int

The default is None.

Corresponding qisjob script argument: --jobs

If instanced, print that number of most recent jobs and status for the selected backend to stdout and return.

See do_it() for the precedence of this kwarg.

job_id : int

The default is None.

Corresponding qisjob script argument: --job_id

If instanced, print that job number (job id) for the chosen backend to stdout and return.

See do_it() for the precedence of this kwarg.

job_result : int

The default is None.

Corresponding qisjob script argument: --job_result

If instanced, print the result for that (completed) job number (job id) to stdout and return.

See do_it() for the precedence of this kwarg.

show_backends : bool

The default is False.

Corresponding qisjob script argument: --backends

If True, print list of backends for chosen provider to stdout and return.

See do_it() for the precedence of this kwarg.

show_configuration : bool

The default is False.

Corresponding qisjob script argument: -g, --configuration

If True, print configuration for backend specified by -b to stdout and return.

See do_it() for the precedence of this kwarg.

show_properties : bool

The default is False.

Corresponding qisjob script argument: p, --properties

If True, print properties for backend specified by -b to stdout and return.

For historical properties, also set the date_time kwarg.

See do_it() for the precedence of this kwarg.

show_statuses : bool

The default is False.

Corresponding qisjob script argument: –status

If True, print status for chosen backend to stdout and return. If no backend chosen, print statuses for all of the chosen provider's backends.

See do_it() for the precedence of this kwarg.

date_time : str

The default is None.

Corresponding qisjob script argument: -d, --datetime

Datetime year,month,day[,hour,min,sec] for showing properties of a backend in conjunction with the show_properties kwarg.

print_histogram : bool

The default is False.

Corresponding qisjob script argument: --histogram

If True, write image file of histogram of experiment results to the fully qualified filepath specified by the figure_basename kwarg concatenated with an algorithmically added filename extension indicating the type of output and time.

print_state_city : int

The default is 0.

Corresponding qisjob script argument: --plot_state_city

If non-zero, write image file of state city plot of statevector to the number of decimal points indicated by the int value to the fully qualified filepath specified by the figure_basename kwarg concatenated with an algorithmically added filename extension indicating the type of output and time.

figure_basename : str

The default is 'figout'.

Corresponding qisjob script argument: --figure_basename

Basename including path (if any) for figure output, in conjunction with kwargs print_histogram and print_state_city. The backend name, figure type, and timestamp will be concatenated to form the full filename.

show_q_version : bool

The default is False.

Corresponding qisjob script argument: -qiskit_version

If True, do_it() print Qiskit version to stdout and returns.

See do_it() for the precedence of this kwarg.

verbose : int

The default is 0.

Corresponding qisjob script argument: -v, --verbose

Set the verbosity level of miscellaneous informational messages emitted to stderr by do_it().

The general range is 0-3. If set precisely to 4, do_it() will print the QisJob instance's data dictionary and return.

show_qisjob_version : bool

The default is False.

Corresponding qisjob script argument: --version

If True, do_it() print QisJob version to stdout and returns.

See do_it() for the precedence of this kwarg.

use_job_monitor : bool

The default is False.

Corresponding qisjob script argument: --use_job_monitor

If True, display the periodically updated job monitor output instead of just blocking waiting for job result to return.

job_monitor_filepath : str

The default is None.

Corresponding qisjob script argument: --job_monitor_filepath

In conjunction with use_job_monitor, set an output filepath for job monitor output instead of the default outstream of stdout.

job_monitor_line : str

The default is a string consisting solely of carriage-return 0x0d.

Corresponding qisjob script argument: --job_monitor_line

Sets the string emitted at the head of every line of job monitor output. The default causes the cursor to jump back to the head of the line on typical terminals so as to overwrite the previous output and update the user interactively without scrolling the screen. For program usage, a different string can be set.

noisy_sim : bool

The default is False.

Corresponding qisjob script argument: --noisy_sim

Performs an Aer sim noise model using the designated backend (see –backend) as the model backend.

Static methods

def basic_noise_sim(circuit: qiskit.circuit.quantumcircuit.QuantumCircuit, model_backend: qiskit.providers.basebackend.BaseBackend) ‑> qiskit.providers.basejob.BaseJob

Execute a simulator job with a basic noise model from a known backend.

Parameters

model_backend : BaseBackend
The BaseBackend instance whose noise model is to be used
circuit : QuantumCircuit
The QuantumCircuit instance to execute

Returns

BaseJob
The job which is executing the circuit
def csv_str(description: unicode, sort_keys: list, sort_counts: list) ‑> list

Generate a CSV as a list of two strings from sorted keys and sorted counts.

Parameters

description : str
Text description of CSV
sort_keys : list
List of keys (classical bit patterns)
sort_counts : list
List of counts

Returns

list
Two strings representing the key row and count row.
def do_histogram(result_exp: qiskit.result.result.Result, circ: qiskit.circuit.quantumcircuit.QuantumCircuit, figure_basename: unicode, backend: qiskit.providers.basebackend.BaseBackend)

Plot histogram-style the result to file. Filename algorithmically generated from figure_basename plus concatenated type and timestamp.

Parameters

result_exp : Result
experiment result
circ : QuantumCircuit
the circuit
figure_basename : str
base file name of output.
backend : BaseBackend
backend experiment was run on.

Returns

None.

def fig_name_str(filepath: unicode, backend: qiskit.providers.basebackend.BaseBackend) ‑> unicode

Create filename consisting of filepath, backend and timestamp.

Parameters

filepath : str
base filepath fqp.
backend : BaseBackend
backend ostensibly one that experiment was run on.

Returns

str
the algorithmically generated filename.
def gen_datetime(datetime_comma_string: unicode) ‑> datetime.datetime

Convert comma-separated date elements to datetime.

Parameters

datetime_comma_string : str
String of comma-separated date elements year,month,day[,hour,min,sec]

Returns

datetime.datetime
Python datetime object
def ibmqjob_to_dict(job: qiskit.providers.ibmq.job.ibmqjob.IBMQJob) ‑> dict

Create a dict containing job factors for which there are methods. Acts as a to_dict().

Parameters

job : IBMQJob
An instance of qiskit.providers.ibmq.job.IBMQJob

Returns

dict

Return a dict containing IBMQ Provider Job info as if qiskit.providers.ibmq.job.IBMQJob had a to_dict() method.

Actually, currently there is such a method, but it is deprecated and will be removed in the next release.

The members should correspond to the methods documented in the Qiskit IBM Quantum Provider documentation

Not all members are present on all platforms, so we try/except each one.

def save_fig(figure: matplotlib.figure.Figure, filepath: unicode, backend: qiskit.providers.basebackend.BaseBackend, tail: unicode)

Write a figure to an algorithmically named destination file

Parameters

figure : Figure
The matplotlib Figure.
filepath : str
base filepath fqp
backend : BaseBackend
Ostensibly the Backend the experiment was run on.
tail : str
uniquifying string to append to filename.

Returns

None.

def state_city_plot(result_exp: qiskit.result.result.Result, circ: qiskit.circuit.quantumcircuit.QuantumCircuit, figure_basename: unicode, backend: qiskit.providers.basebackend.BaseBackend, decimals: int = 3)

Plot state_city-style the output state to file. Filename algorithmically generated from figure_basename plus concatenated type and timestamp.

result_exp - experiment result circ - the circuit figure_basename - base file name of output backend - backend run on decimals - how many decimal places

Parameters

result_exp : Result
experiment result.
circ : QuantumCircuit
DESCRIPTION.
figure_basename : str
the circuit.
backend : BaseBackend
backend run on.
decimals : int, optional
how many decimal places. The default is 3.

Returns

None.

Methods

def account_fu(self)

Load account from correct API provider and instance self with provider

def choose_backend(self)

Instance self with backend selected by user if account will activate and allow.

def do_it(self)

Run the program specified by ctor args/kwargs, usally instanced from the driver script. Afterwards, the QisJob instance is usually discarded, or the members can be carefully edited and the instance reused.

do_it() has many logical branches depending on the request made as represented at instancing. Below, in order of branching, are the main branches.

The best information on QisJob logic in QisJob.do_it() is the source code itself; the following is a lite summary.

1. If show_qisjob_version print QisJob version and return.
2. If show_q_version Qiskit version shown and return.
3. If providers show IBM Q providers and return.
4. If show_configuration print config for -b backend and return.
5. If show_properties print properties for -b backend and return.
6. If show_backends print list of backends for provider and return.
7. If show_statuses print status or statuses for -b backend
    or if no backend specified, for all backends for provider
    and return.
8. If jobs_status print status for n jobs and return.
9. If job_id then print job dict for that job and return.
10. If job_result then print job result for that job and return.

Otherwise, proceed to job experiments provided in kwargs as follows:

1. If qasm_src job and return.
2. If filepaths read, job, and return.
3. Else read stdin for qasm src. On EOF, job and return.

Returns

None.

Raises

QisJobException -+
                 |
                 + QisJobArgumentException
                 |
                 + QisJobRuntimeException

Note: Applications should wrap do_it() in try-except QiskitError as miscellaneous instances can be raised in ways the code does not anticipate.

See the qisjob script for an example of this pattern.

def forest_account_fu(self)

Load Rigetti Forest account appropriately and instance self with provider

def formulate_result(self, result_exp: qiskit.result.result.Result, circ: qiskit.circuit.quantumcircuit.QuantumCircuit, ofh: _io.TextIOWrapper) ‑> list

Formulate the result result_exp of one circuit circ returning output as string optionally also writing this same output to a file.

Optionally also write the qasm for the circuit if the qasm kwarg was True when the QisJob was instanced. This is written to ofh but not added to the method return.

Parameters

result_exp : dict
The dict result of an experiment
circ : QuantumCircuit
The circuit for the experiment
ofh : TextIOWrapper
Output file handle to which output is written. May be None.

Returns

list
The output list representing the result in csv form. It is also written to ofh if that handle is instanced.
def get_statuses(self) ‑> list

Return backend status tuple(s)

Returns

list
Backend status tuple(s)
def ibmq_account_fu(self)

Load IBMQ account appropriately and instance self with provider

def jku_account_fu(self)

Load qiskit-jku-provider and instance self with provider

def multi_exps(self)

Load qasms and run all as one the job, print csvs and other selected output

def one_exp(self, filepath_name: unicode = None)

Load experiment source (OpenQASM or Python QuantumCircuit source) and run the job. print csv and other selected output.

Parameters

filepath_name : str, optional
Filepath to experiment source. The default is None. If None, read from stdin.

Returns

None.

Raises

QisJobRuntimeException
 
def process_result(self, result_exp: qiskit.result.result.Result, circ: qiskit.circuit.quantumcircuit.QuantumCircuit, ofh: _io.TextIOWrapper)

Process the result of one QuantumCircuit circ experiment from its Result result_exp printing to output file handle ofh and pass original qasm filepath to figure output.

Parameters

result_exp : Result
Result of experiment.
circ : QuantumCircuit
Circuit subject of experiment.
ofh : TextIOWrapper
Output file handle, possibly (typically) stdout.

Returns

None.

def qasm_exp(self) ‑> list

Given qasm source, run the job and return list of string csv and other selected output.

Returns

list
The output list representing the result in csv form. It is also written to ofh if that handle is instanced.

Raises

QisJobRuntimeException
def qi_account_fu(self)

Load Quantum Inspire account appropriately and instance self with provider

def qisjob_version(self) ‑> unicode

Return version of QisJob

Returns

str
version string for QisJob.
def verbosity(self, printable: Any, count: int)

Print some printable item to stdout if count exceeds verbose level.

Parameters

printable : str
Item to print.
count : int
Level that self.verbose must equal or exceed to print message.

Returns

None.

class QisJobArgumentException (message: unicode)

Argument passed to QisJob ctor is invalid.

Parameters

message : str
programmer-supplied message

Returns

None.

Ancestors

class QisJobException (message: unicode, retval: int)

Base class for QisJob exceptions

Parameters

message : str
programmer-supplied message
retval : int
suggested return val for an encapsulating function or script

Returns

None.

Ancestors

  • builtins.Exception
  • builtins.BaseException

Subclasses

class QisJobRuntimeException (message: unicode)

QisJob encountered an unrecoverable runtime error.

Parameters

message : str
programmer-supplied message

Returns

None.

Ancestors