qlazy package

Subpackages

Submodules

qlazy.Backend module

Backend device of quantum computing

class qlazy.Backend.Backend(product=None, device=None)[source]

Bases: object

Backend device of quantum computing

product

product name of the backend (‘qlazy’ or ‘qulacs’ or ‘ibmq’)

Type

str

device

device name of the product

Type

str

config_braket

config for amazon braket backend {‘backet_name’: str, ‘poll_timeout_seconds’: int}

Type

dict

Notes

If you use amazon braket backend (braket_local, braket_aws, braket_ionq, braket_rigetti, braket_oqc), you must have config.ini file in your ‘~/.qlazy/’ directory, and discribe like following example …

Example

>>> bk = Backend(product='qlazy', device='stabilizer_simulator')
>>> bk = Backend(product='qulacs', device='gpu_simulator')
>>> bk = Backend(product='ibmq', device='least_busy')
>>> bk = Backend(product='braket_rigetti', device='aspen_11') # read ~/.qlazy/config.ini
...
$ cat ~/.qlazy/config.ini
[backend_braket]
backet_name = amazon-braket-xxxx # set your s3 backet name
...
$ cat ~/.qlazy/config.ini
[backend_braket]
backet_name = amazon-braket-xxxx # set your s3 backet name
poll_timeout_seconds = 86400  # set 1-day (default: 5-days)
classmethod devices(product)[source]

get devices list for the product

expect(qcirc=None, observable=None, shots=None, precise=False, init=None)[source]

run the quantum circuit.

Parameters
  • qcirc (instance of QCirc) – quantum circuit.

  • observable (instance of Observable) – obserbable considerd.

  • shots (int, default - None) – number of measurements for estimating the expectation value.

  • precise (bool, default - False) – precise calculation (only qlazy and qulacs) or estimation by measurements.

  • init (instance of QState, MPState) – initial quantum state

Returns

expval – expectation value

Return type

complex

Examples

>>> # simple example
>>> from qlazy import QCirc, Backend
>>> from qlazy.Observable import X,Y,Z
>>> bk = Backend(product='qlazy', device='qstate_simulator')
>>> ob = Z(0)*X(1)
>>> qc = QCirc().h(0).cx(0,1)
>>> exp = bk.expect(qcirc=qc, shots=10000, observable=ob)
>>> print(exp.real)
>>> 0.0074
classmethod ibmq_devices()[source]

get ibmq’s devices list

classmethod products()[source]

get products list

classmethod qlazy_devices()[source]

get qlazy’s devices list

classmethod qulacs_devices()[source]

get qulacs’s devices list

run(qcirc=None, shots=1, cid=None, out_state=False, init=None, **kwargs)[source]

run the quantum circuit.

Parameters
  • qcirc (instance of QCirc) – quantum circuit.

  • shots (int, default 1) – number of measurements.

  • cid (list, default None) – classical register id list to count frequency.

  • out_state (bool, default False) – output classical and quantum information after execting circuit. (only for qlazy’s qstate and stabilizer simulator)

  • init (instance of QState, Stabilizer, MPState) – initial quantum state

Returns

result – measurement result.

Return type

incetance of Result

Examples

>>> # simple example
>>> from qlazy import QCirc, Backend
>>> bk = Backend(product='qlazy', device='qstate_simulator')
>>> qc = QCirc().h(0).cx(0,1).measure(qid=[0,1], cid=[0,1])
>>> result = bk.run(qcirc=qc, shots=100)
>>> print(result.frequency)
Counter({'00': 51, '11': 49})
>>> ...
>>> # control quantum gate by measured results
>>> from qlazy import QCirc, Backend
>>> bk = Backend(product='qlazy', device='qstate_simulator')
>>> qc = QCirc.h(0)
>>> qc.cx(0,1).measure(qid=[0],cid=[0])
>>> qc.x(0, ctrl=0).x(1, ctrl=0).measure(qid=[0,1], cid=[0,1])
>>> result = bk.run(qcirc=qc, shots=100)
>>> print(result.frequency)
Counter({'00': 100})

qlazy.CMem module

Classical Memory

class qlazy.CMem.CMem(cmem_num, **kwargs)[source]

Bases: Structure

Classical Memory

cmem_num

number of the classical register (classical memory size).

Type

int

bit_array

bit array of classical memory.

Type

list (int)

bit_array

Structure/Union member

property bits

bit list of classical memory.

clone()[source]

get the copy of the classical memory.

Parameters

None

Returns

cmem – copy of the original classical memory.

Return type

instance of CMem

cmem_num

Structure/Union member

get_bits()[source]

get bit list of the classical memory.

Parameters

None

Returns

bits – bits array of the classical memory

Return type

numpy.ndarray (int)

set_bits(bits)[source]

set bit list to the classical memory.

Parameters

bits (list) – bits array of the classical memory

Return type

None

qlazy.DensOp module

Density Operator

class qlazy.DensOp.DensOp(qubit_num=0, qstate=None, prob=None, matrix=None, **kwargs)[source]

Bases: Structure, QObject

Density Operator

row

dimension of density operator (= 2**qubit_num).

Type

int

col

dimension of density operator (= 2**qubit_num).

Type

int

element

matrix elements of density operator.

Type

list of list of complex

add(densop=None)[source]

add the density operator.

Parameters

densop (instance of DensOp) – density operator to add.

Returns

self

Return type

instance of DensOp

Notes

This method change the original density operator.

classmethod add_method(method)[source]

add method (custum gate).

Parameters

method (func) – method (custum gate) to add.

Examples

>>> def bell(self, q0, q1):
>>>     self.h(q0).cx(q0,q1)
>>> ...
>>> DensOp.add_method(bell)
>>> qs = DensOp(qubit_num=2)
>>> qs.bell(0,1)
>>> ...
classmethod add_methods(*methods)[source]

add methods (custum gates).

Parameters

methods (func, func, ...) – arguments of methods (custum gates) to add.

Examples

>>> def bell(self, q0, q1):
>>>     self.h(q0).cx(q0,q1)
>>>     return self
>>> ...
>>> def flip(self, q0, q1):
>>>     self.x(q0).x(q1)
>>>     return self
>>> ...
>>> DensOp.add_methods(bell, flip, ...)
>>> de = DensOp(qubit=2)
>>> de.bell(0,1)
>>> de.flip(0,1)
>>> ...
amp_dump(q, prob=0.0)[source]

execute the quantum channel of amplitude dumping.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probability of the quantum channel.

Returns

self

Return type

instance of DensOp

apply(matrix=None, qid=None, dire='both')[source]

apply the matrix to density operator. (= [matrix] * [self] * [dagger of matrix])

Parameters

matrix (list of list) – matrix to apply.

Return type

None

Notes

If ‘qid’ isn’t set, dimension of the matrix must be equal to dimension of the density operator. If ‘qid’ is set, dimension of the matrix must be equal to the 2 power of ‘qid’ length.

bit_flip(q, prob=0.0)[source]

execute the quantum channel of bit flip.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probabillity of the quantum channel.

Returns

self

Return type

instance of DensOp

bit_phase_flip(q, prob=0.0)[source]

execute the quantum channel of bit and phase flip.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probability of the quantum channel.

Returns

self

Return type

instance of DensOp

buf_id

Structure/Union member

buffer_0

Structure/Union member

buffer_1

Structure/Union member

clone()[source]

get the copy of density operator.

Parameters

None

Returns

densop – copy of the original density operator.

Return type

instance of DensOp

col

Structure/Union member

composite(num=0)[source]

get the composite density operator of same density operators.

Parameters

num (int) – number of density operators..

Returns

de – composite density operator.

Return type

instance of DensOp

cond_entropy(qid_0=None, qid_1=None)[source]

get the conditional entropy.

Parameters
  • qid_0 (list of int) – qubit id’s list (sub-system) to calculate the entropy.

  • qid_1 (list of int) – qubit id’s list (sub-system) to calculate the entropy.

Returns

ent – conditianal entropy (S(qid_0|qid_1)).

Return type

float

classmethod create_register(num)[source]

create registers (qubit id’s list) and initialize zero.

Parameters

num (int) – qubit number you want to use.

Returns

qid – qubit id’s list.

Return type

list of int

Examples

>>> qid = DensOp.create_register(3)
>>> print(qid)
[0,0,0]
classmethod del_all(*densops)[source]

free memory of the all density operators.

Parameters

densops (instance of DensOp,instance of DensOp,...) – set of DensOp instances

Return type

None

depolarize(q, prob=0.0)[source]

execute the quantum channel of depolarize.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probability of the quantum channel.

Returns

self

Return type

instance of DensOp

distance(densop=None, qid=None)[source]

get the trace distance with the density operator.

Parameters
  • densop (instance of DensOp) – density operator to get the trace distance.

  • qid (list of int, default - all of the qubit id's list) – qubit id’s list.

Returns

dis – trace distance.

Return type

float

property element

matrix elements of density operator.

elm

Structure/Union member

entropy(qid=None)[source]

get the von neumann entropy (or entanglement entropy).

Parameters

qid (list of int, default - list all of the qubit id) – qubit id’s list (sub-system) to calculate the entropy.

Returns

ent – von neumann entropy.

Return type

float

expect(matrix=None)[source]

get the expectation value of matrix under this density operator.

Parameters

matrix (list of list of complex) – matrix expression of hermitian operator.

Returns

value – expectation value.

Return type

float

Notes

‘matrix’ must be hermitian, and its dimension is equal to the dimension of density operator.

fidelity(densop=None, qid=None)[source]

get the fidelity with density operator.

Parameters
  • densop (instance of DensOp) – density operators to get fidelity.

  • qid (list of int, default - all of the qubit id's list) – qubit id’s list.

Returns

fid – fidelity of two density operators.

Return type

float

gbank

Structure/Union member

get_elm(qid=None)[source]

get the matrix elements of density operator.

Parameters

qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

elm – elements of the density matrix.

Return type

list of complex

Notes

If ‘qid’ is set, matrix elements of specified density operator are got after partial trace for remaining qubits. If no qubits are specified, you get all matrix elements of the density operator.

classmethod init_register(*args)[source]

initialize registers (qubit id’s list).

Parameters

args (list, list,...) – arguments of qubit registers.

Returns

idx – total qubit number.

Return type

int

Examples

>>> qid_0 = DensOp.create_register(3)
>>> qid_1 = DensOp.create_register(2)
>>> print(qid_0, qid_1)
[0,0,0] [0,0]
>>> qnum = DensOp.init_register(qid_0, qid_1)
>>> print(qnum, qid_0, qid_1)
5 [0,1,2] [3,4]
instrument(kraus=None, qid=None, measured_value=None)[source]

instrument to the density operator

Parameters
  • kraus (list of list of comprex) – Kraus operators.

  • qid (list) – qubit id’s list to measure.

  • measured_value (int) – index of measurement (in the case of selective measurement).

Returns

self

Return type

instance of DensOp

Notes

If ‘measured_value’ is set, selective measurement of the index corresponding to ‘measured_value’ is done (but not normalize). If ‘measured_value’ is not set, non-selective measurement is done (only operator sum for the Kraus operators are executed). This method does change the original density operator.

join(de_list)[source]

get tensor product state (density operator) of the density operators’ list.

Parameters

de_list (list (DensOp)) – list of density operators.

Returns

de_out – tensor product state (density operator).

Return type

instance of DensOp

static mat_norm(mat)[source]

norm of the matrix

static mat_spectrum(mat)[source]

spectrum of the hermitian matrix

static mat_sqrt(mat)[source]

square root of the matrix

classmethod mix(densop=None, prob=None)[source]

linear sum of the density operators.

Parameters
  • densop (list of instances of DensOp) – densitiy operators.

  • prob (list of float) – probabilities (coefficients of the linear sum).

mul(factor=1.0)[source]

multiply the density operator by factor.

Parameters

factor (float, default 1.0) – number to multiply.

Returns

self

Return type

instance of DensOp

Notes

This method change the original density operator.

mutual_info(qid_0=None, qid_1=None)[source]

get the mutual information.

Parameters
  • qid_0 (list of int) – qubit id’s list (sub-system) to calculate the mutual information.

  • qid_1 (list of int) – qubit id’s list (sub-system) to calculate the mutual information.

Returns

ent – mutual information (S(qid_0:qid_1)).

Return type

float

operate_gate(kind=None, qid=None, phase=0.0, **kwargs)[source]

operate gate

Parameters
  • kind (int) – kind of the gate

  • qid (list) – quantum id list

  • phase (float) – phase for rotation gate

Returns

self – quantum state

Return type

instance of DensOp

operate_qcirc(qcirc, qctrl=None)[source]

operate quantum circuit

Parameters
  • qcirc (instance of QCirc) – quantum circuit

  • qctrl (int) – control qubit id

Returns

self – quantum state after executing the quantum circuit

Return type

instance of DensOp

Notes

The quantum circut must be unintary.

partial(qid=None)[source]

get the density operator for partial system.

Parameters

qid (list of int) – qubit id’s list to show.

Returns

densop – density operator for partial system (= partial trace for remaining system).

Return type

instance of DensOp

patrace(qid=None)[source]

get the partial trace of density operator.

Parameters

qid (list of int) – qubit id’s list to show.

Returns

densop – density operator after partial trace.

Return type

instance of DensOp

phase_dump(q, prob=0.0)[source]

execute the quantum channel of phase dumping.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probability of the quantum channel.

Returns

self

Return type

instance of DensOp

phase_flip(q, prob=0.0)[source]

execute the quantum channel of phase flip.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probability of the quantum channel.

Returns

self

Return type

instance of DensOp

probability(kraus=None, povm=None, qid=None)[source]

get the probabilities for measuring operators. (Kraus or POVM operators).

Parameters
  • kraus (list of list of comprex) – Kraus operators.

  • povm (list of list of comprex) – POVM operators.

  • qid (list) – qubit id’s list to measure.

Returns

prob – probabilities for measuring operators.

Return type

list of float

Notes

Either ‘kraus’ or ‘povm’ must be set. If ‘qid’ is not set, all of the qubits are measured, the dimention of Kraus or POVM operator must be equal to the dimension of density operator. If ‘qid’ is set, the part of qubits are measured, the dimension of Kraus or POVM operator must be equal to the 2 power of ‘qid’ length. This method does not change the original density operator.

relative_entropy(densop=None)[source]

get the relative entropy.

Parameters

densop (instance of DensOp) – density operator to get the relative entropy.

Returns

ent – relative entropy.

Return type

float

row

Structure/Union member

show(qid=None, nonzero=False)[source]

show the elements of density operator.

Parameters
  • qid (list of int, default - list of all of the qubit id) – qubit id’s list to show.

  • nonzero (bool, default False) – if True, only non-zero elements are printed.

Return type

None

Notes

If ‘qid’ is set, it shows the matrix elements of density operator for partial quantum system specified by ‘qid’. If ‘qid’ isn’t set, it shows the matrix elements of whole quantum system.

Examples

>>> de = DensOp(qubit_num=1)
>>> ...
>>> de.show()
elm[0][0] = +0.5000+0.0000*i : 0.2500 |++++
elm[0][1] = +0.0000+0.0000*i : 0.0000 |
elm[1][0] = +0.0000+0.0000*i : 0.0000 |
elm[1][1] = +0.5000+0.0000*i : 0.2500 |++++
...
>>> de.show(nonzero=True)
elm[0][0] = +0.5000+0.0000*i : 0.2500 |++++
elm[1][1] = +0.5000+0.0000*i : 0.2500 |++++
spectrum()[source]

get the spectrum.

Parameters

None

Returns

  • qstate (list of QState) – list of the quantum state basis.

  • prob (list of float) – list of coefficients for each quantum states basis.

sqtrace()[source]

get the square trace of density operator.

Parameters

None

Returns

sqtrace – square trace of the density operator.

Return type

float

tenspro(densop)[source]

get the tensor product with density operator.

Parameters

densop (instance of DensOp) – density operator to get the tensor product..

Returns

densop_out – tensor produt of ‘self’ and ‘densop’.

Return type

instance of DensOp

trace()[source]

get the trace of density operator.

Parameters

None

Returns

trace – trace of the density operator.

Return type

float

von_neumann_entropy()[source]

get the von neumann entropy (or entanglement entropy).

Parameters

None

Returns

ent – von neumann entropy.

Return type

float

qlazy.MData module

Mesured data

class qlazy.MData.MData(qubit_num=None, shots=1, angle=0.0, phase=0.0, qid=None, **kwargs)[source]

Bases: Structure

Measured data

qubit_num

number of qubits

Type

int

shot_num

number of measureings

Type

int

angle

angle

Type

float

phase

phase

Type

float

qubit_id

list of qubit ids

Type

list of int

freq

list of frequencies

Type

list of float

last_val

last measurement value

Type

int

angle

Structure/Union member

freq

Structure/Union member

property frequency

frequencies of measured value (Counter)

property frq

frequencies of measured value (list)

property last

last measured value (binary string)

last_val

Structure/Union member

property lst

last measured value (integer)

phase

Structure/Union member

qubit_id

Structure/Union member

qubit_num

Structure/Union member

shot_num

Structure/Union member

show()[source]

show the measured data

property state_num

number of states

qlazy.MPState module

Matrix Product State

class qlazy.MPState.MDataMPState(frequency=None, last=None, qid=None, qubit_num=0)[source]

Bases: object

Measured Data for MPState

frequency

frequencies of measured value.

Type

Counter

last

last measured value.

Type

str

qid

qubit id’s list.

Type

list of int

qubit_num

qubit number of the quantum state (= log(state_num)).

Type

int

class qlazy.MPState.MPState(qubit_num=0, bits_str=None, tensors=None, max_truncation_err=1e-06, **kwargs)[source]

Bases: FiniteMPS, QObject

Matrix Product State

qubit_num

number of qubits (number of nodes)

Type

int

bond_dimensions

list of bond dimensions

Type

list (int)

max_truncation_err

maximum of truncation error

Type

float

tensors

list of 3-rank tensors for the matrix product

Type

list (np.ndarray)

property amp

elements of quantum state vector.

clone()[source]

get the copy of the matrix product state.

Parameters

None

Returns

mps – copy of the original matrix product state.

Return type

instance of MPState

classmethod del_all(*mpstates)[source]

free memory of the all matrix product states.

Parameters

mpstates (instance of MPState,instance of MPState,...) – set of MPState instances

Return type

None

expect(observable=None)[source]

get the expectation value for observable under the matrix product state.

Parameters

observable (instance of Observable) – obserbable of the system.

Returns

expect – expect value.

Return type

complex

See also

Obserbable

fidelity(mps, qid=None)[source]

get fidelity with the matrix product state.

Parameters
  • mps (instance of MPState) – one of the two matrix product states.

  • qid (list of int) – qubit id’s list.

Returns

fid – fidelity of the two matrix product states. absolute value of the inner product of two matrix product states.

Return type

float

Notes

If ‘qid’ is set, you can get the fidelity for partial quantum state. If the specified quantum system are entangled with the remaining system, output value is probabilistic, while original quantum states do not change.

get_amp(qid=None)[source]

get the elements of quantum state vector.

Parameters

qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

ret – elements of the quantum state vector.

Return type

numpy.ndarray (complex)

Notes

If ‘qid’ is set, specified qubit state are got after remaining qubits are measured. So if the specified qubits are entangled with the remaining qubits, output quantum state is probabilistic. If no qubits are specified, you get all elements of the quantum state.

inpro(mps, qid=None)[source]

get the inner product with matrix product state.

Parameters
  • mps (instance of MPState) – one of the two matrix product state.

  • qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

inp – inner produt (<self|mps>).

Return type

complex

Notes

If ‘qid’ is set, you can get the inner product for partial quantum state. If the specified quantum system are entangled with the remaining system, output value is probabilistic, while original quantum states do not change.

m(qid=None, shots=1)[source]

measurement in Z-direction

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MDataMPState

See also

MDataMPState

property max_truncation_err
measure(qid=None)[source]

one shot measurement in Z-direction.

Parameters

qid (list of int) – qubit id list to measure.

Returns

mval – measurement value.

Return type

str

Examples

>>> mps = MPState(qubit_num=2).h(0).cx(0,1)
>>> mps.show()
>>> print(mps.measure(qid=[0,1]))
>>> mps.show()
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.7071+0.0000*i : 0.5000 |++++++
00
c[00] = +1.0000+0.0000*i : 1.0000 |+++++++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.0000+0.0000*i : 0.0000 |
operate_1qubit_gate(gate_str, q, para=0.0)[source]

operate 1-qubit gate.

Parameters
  • gate_str (str) – gate stiring (ex. ‘x’,’y’,’z’,’h’,’s’, ..)

  • q0 (int) – qubit id.

  • para (float) – angle for rotation gate (unit of angle is PI radian).

Returns

self

Return type

instance of MPState

operate_2qubit_gate(gate_str, q0, q1, para=0.0)[source]

operate 2-qubit gate.

Parameters
  • gate_str (str) – gate stiring (ex. ‘cx’,’cy’,’cz’,’ch’,’crz’, ..)

  • q0 (int) – qubit id.

  • q1 (int) – qubit id.

  • para (float) – angle for rotation gate (unit of angle is PI radian).

Returns

self

Return type

instance of MPState

operate_gate(kind=None, qid=None, phase=0.0, **kwargs)[source]

operate gate

Parameters
  • kind (int) – kind of the gate

  • qid (list) – quantum id list

  • phase (float) – phase for rotation gate

Returns

self – quantum state

Return type

instance of MPState

operate_qcirc(qcirc, qctrl=None)[source]

operate quantum circuit

Parameters
  • qcirc (instance of QCirc) – quantum circuit

  • qctrl (int) – control qubit id

Returns

self – quantum state after executing the quantum circuit

Return type

instance of MPState

Notes

The quantum circut must be unintary.

property qubit_num
reset_qubits(qid=None)[source]

reset to |00..0> state.

Parameters

qid (list, default - qubit id's list for all of the qubits) – qubit id’s list to reset.

Returns

self – matrix product state.

Return type

instance of MPState

Notes

If ‘qid’ is set, specified qubits are reset after measurement. So if the specified qubits are entangled with the remaining qubits, output quantum state is probabilistic. If no qubits are set, all qubits are zero reset.

show(qid=None, nonzero=False, preal=0)[source]

show the quantum state (elements of the state vector and probabilities).

Parameters
  • qid (list of int, default - list of all of the qubit id) – qubit id’s list to show.

  • nonzero (bool, default False) – if True, only non-zero amplitudes are printed.

  • preal (int, default 0) – state id to make positive real amplitude. (if -1 is set, do not go out the global phase factor)

Return type

None

Notes

If ‘qid’ is set, it shows the elements of quantum state vector for partial quantum system specified by ‘qid’. If the specified quantum system are entangled with the remaining system, output is probabilistic. If no qubits are specified, it shows the whole quantum state. This method does not change the original quantum state.

Examples

>>> mps = MPState(qubit_num=2).h(0).cx(0,1)
>>> mps.show()
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.7071+0.0000*i : 0.5000 |++++++
...
>>> mps.show(qid=[0])
c[0] = +1.0000+0.0000*i : 1.0000 |+++++++++++
c[1] = +0.0000+0.0000*i : 0.0000 |
...
>>> mps.show(nonzero=True)
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[11] = +0.7071+0.0000*i : 0.5000 |++++++

qlazy.Observable module

Obserbavle for quantum many-body spin system.

class qlazy.Observable.Observable(string=None)[source]

Bases: object

Observable for quantum many-body spin system.

base

observable

Type

instance of ObservableBase

string

string of observable description ex) “-2.0+Z_0*Z_1+X_0+X_1” for 2-qubit system

Type

str

weighted_pp_list

weighted pauli product list

Type

list of dict ({‘weight’:weight, ‘pp’:pauli_product})

qubit_num

total qubit number

Type

int

add_wpp(weight=1.0, pp=None)[source]

add the weighted pauli product to the list (self.weighted_pp_list).

Parameters
  • weight (float) – weight value correspond to the pauli product

  • pp (instance of PauliProduct) – pauli product

Returns

self – observable after adding weighted pauli product

Return type

instance of Ovservable

property base
clone()[source]

clone observable.

Parameters

None

Returns

ob – observable

Return type

instance of Observable

get_idx_weight(pp)[source]

get index and weight value correspond to the pauli product.

Parameters

pp (instance of PauliProduct) – pauli product

Returns

  • idx (int) – index number of the list (self.weighted_pp_list) correspond to the pauli product

  • weight (float) – weight value correspond to the pauli product

get_observable_base()[source]

get ObservableBase instance.

Parameters

None

Returns

ob_base – observable

Return type

instance of ObservableBase

get_qubit_num()[source]

get the total qubit number considerd

Parameters

None

Returns

qubit_num – total qubit number considerd by the observable.

Return type

inst

get_string()[source]

get string of observable.

Parameters

None

Returns

s – string of observable

Return type

str

get_weighted_pp_list(string)[source]

get weighted pauli product list.

Parameters

string (str) – string of observable

Returns

weighted_pp_list – weighted pauli product list

Return type

list of dict (weight:pauli_product)

is_hermitian()[source]

hermitian or not

Parameters

None

Returns

ans – is the observable hermitian or not

Return type

bool

property qubit_num
recalc_weight()[source]
recalculate the weights of weighted_pp_list

(weight <= weight * pp.factor, pp.factor <= 1.0)

Parameters

None

Returns

ans – is the observable hermitian or not

Return type

bool

property string
qlazy.Observable.X(q)[source]
Parameters

q (int) – qubit id

Returns

ob – obserbable X(q)

Return type

instance of Observable

qlazy.Observable.Y(q)[source]
Parameters

q (int) – qubit id

Returns

ob – obserbable Y(q)

Return type

instance of Observable

qlazy.Observable.Z(q)[source]
Parameters

q (int) – qubit id

Returns

ob – obserbable X(q)

Return type

instance of Observable

qlazy.ObservableBase module

Obserbavle for quantum many-body spin system.

class qlazy.ObservableBase.ObservableBase(string=None, **kwargs)[source]

Bases: Structure

Observable for quantum many-body spin system.

array_num

Structure/Union member

spin_num

Structure/Union member

spro_array

Structure/Union member

qlazy.PauliProduct module

Pauli Product

class qlazy.PauliProduct.PauliProduct(pauli_str, qid=None, factor=1 + 0j)[source]

Bases: object

Pauli Product

qid

list of qubit id.

Type

list of int

pauli_list

list of pauli operators.

Type

list of str

factor

factor of pauli product.

Type

complex

get_binary_rep(qubit_num=None)[source]

get binary representation of pauli product.

Parameters

qubit_num (int, default - max(self.qid)+1) – qubit number of binary representation.

Returns

binary_rep – output binary representation of the pauli product.

Return type

list of int

Examples

>>> pp = PauliProduct(pauli_str="XYZ", qid=[0,1,2])
>>> print(pp.get_binary_rep())
[1,1,0,0,1,1]
get_qubit_num()[source]

get the total qubit number considerd

Parameters

None

Returns

qubit_num – total qubit number considerd by the pauli product.

Return type

inst

is_commute(pp)[source]

is pauli product commute to other pauli product or not.

Parameters

pp (instance of PauliProduct) – pauli product

Returns

ans – commute (True) or anti-commute (False)

Return type

bool

tenspro(pp)[source]

get tensor product with other pauli product.

Parameters

pp (instance of PauliProduct) – pauli product

Returns

pp_out – output pauli product

Return type

instance of PauliProduct

qlazy.QCirc module

Quantum Circuit

class qlazy.QCirc.QCirc(**kwargs)[source]

Bases: Structure, QObject

Quantum Circuit

qubit_num

qubit number of the quantum state (= log(state_num)).

Type

int

cmem_num

number of the classical register.

Type

int

gate_num

number of gates in the quantum circuit.

Type

int

first

first gate of the quantum circuit.

Type

object

last

last gate of the quantum circuit.

Type

object

tag_table

tag table..

Type

object

add_control(qctrl=None)[source]

add control qubit to quantum circuit

Parameters

qctrl (int) – control qubit id

Returns

qc_out – quantum circuit after adding control qubit

Return type

instance of QCirc

add_gates(gates=None)[source]

add list of gates to the circuit.

Parameters

gates (list of dict) – gates of the quantum circuit gates = [{‘kind’:kind, ‘qid’:qid, ‘phase’:phase, ‘cid’:cid, ‘ctrl’:ctrl}, …] - kind: gate name - qid: qubit id - phase: phase parameter (non-zero only for rotation gates) - cid: classical register id (set only for measurement gate) - ctrl: classical register id for controlling gate operation

Returns

self – circuit after adding gates

Return type

instance of QCirc

Notes

This method changes original quantum circuit.

all_gates_measurement()[source]

gates of the qcirc are all measurement

Parameters

None

Returns

ans – True if all gates are measurement, False if otherwise

Return type

bool

append_gate(kind=None, qid=None, para=None, c=None, ctrl=None, tag=None)[source]

append gate to the end of the circuit.

Parameters
  • kind (int) – kind of gate

  • qid (list (int)) – list of qubit id

  • para (list (float), default None) – list of parameters

  • c (int, default None) – classical register id to store measured data

  • ctrl (int, default None) – classical register id to controll the gate

Return type

None

clone()[source]

clone quantum circuit.

Parameters

None

Returns

qcirc – quantum circuit

Return type

instance of QCirc

cmem_num

Structure/Union member

dump(file_path)[source]

dump the circuit

Parameters

file_path (str) – file path of dump file

Return type

None

equivalent(qc, *args, **kwargs)[source]

two quantum circuits are equivalent or not (using pyzx’s verify_equality method).

Parameters

None

Returns

ans

Return type

bool

Notes

Non-unitary gates: measure, reset are not supported.

first

Structure/Union member

classmethod from_pyzx(zxqc)[source]

get pyzx’s Circuit instance.

Parameters

zxqc (instance of pyzx's Circuit) – quantum circuit

Returns

qc – quantum circuit

Return type

instance of QCirc

Notes

Non-unitary gates: measure, reset are not supported.

classmethod from_qasm(string)[source]

get QCirc instance from OpenQASM 2.0 string.

Parameters

None

Returns

qcirc

Return type

instance of QCirc

Notes

Non-unitary gates (measure, reset) and user customized gates are not supported. Supported gates are ‘x’, ‘y’, ‘z’, ‘h’, ‘s’, ‘sdg’, ‘t’, ‘tdg’, ‘cx’, ‘cz’, ‘ch’, ‘rx’, ‘rz’, ‘crz’.

classmethod from_qasm_file(file_path)[source]

get QCirc instance from OpenQASM 2.0 file.

Parameters

file_path (str) – file path name of OpenQASM 2.0 file

Returns

qcirc

Return type

instance of QCirc

Notes

Non-unitary gates (measure, reset) and user customized gates are not supported. Supported gates are ‘x’, ‘y’, ‘z’, ‘h’, ‘s’, ‘sdg’, ‘t’, ‘tdg’, ‘cx’, ‘cz’, ‘ch’, ‘rx’, ‘rz’, ‘crz’.

gate_num

Structure/Union member

classmethod generate_random_gates(qubit_num=0, gate_num=0, phase=None, prob=None, **kwargs)[source]

generate circuit including random gates.

Parameters
  • qubit_num (int) – number of qubits

  • gate_num (int) – numbner of gates

  • phase (tupple of float) – phases selected randomly

  • prob (dict) –

    {‘x’:prob_x, ‘z’:prob_z, ‘h’:prob_h, ‘s’:prob_s, ‘s_dg’:prob_s_dg,

    ’t’:prob_t, ‘t_dg’:prob_t_dg, ‘rx’:prob_rx, ‘rz’:prob_rz, ‘cx’:prob_cx, ‘cz’:prob_cz, ‘ch’:prob_ch, ‘crz’:prob_crz}

    • prob_x: probability of x

    • prob_z: probability of z

    • prob_h: probability of h

    • prob_s: probability of s

    • prob_s_dg: probability of s_dg

    • prob_t: probability of t

    • prob_t_dg: probability of t_dg

    • prob_rx: probability of rx

    • prob_rz: probability of rz

    • prob_cx: probability of cx

    • prob_cz: probability of cz

    • prob_ch: probability of ch

    • prob_crz: probability of crz

Returns

qcirc – generated circuit

Return type

instance of QCirc

Examples

>>> qc = QCirc.generate_random_gates(qubit_num=5, gate_num=100,
phase_unit=0.25, prob={'h':3, 'cx':7, 'rz':1})

Notes

  • each probability values are normalized so that the sum of the probabilities is 1.0.

  • Phase parameters of rotation gates are selected randomly in the element of ‘phase’.

get_gates()[source]

get list of gates from the circuit.

Parameters

None

Returns

gates – gates of the quantum circuit gates = [{‘kind’:kind, ‘qid’:qid, ‘phase’:phase, ‘cid’:cid, ‘ctrl’:ctrl}, …] - kind: gate name - qid: qubit id - phase: phase parameter (non-zero only for rotation gates) - para: [phase, gphase, factor]

  • gphase means global phase used only when adding control to p gate

  • cid: classical register id (set only for measurement gate)

  • ctrl: classical register id to control gate operation

Return type

list of dict

get_params()[source]

get parameters for each tag

Parameters

None

Returns

params – tag and phase dictionary ex) {‘tag1’: phase1, ‘tag2’: phase2, …}

Return type

dict

Examples

>>> qc = QCirc().h(0).rz(0, tag='foo').rx(0, tag='bar')
>>> qc.set_params(params={'foo': 0.2, 'bar': 0.4})
>>> print(qc.get_params())
{'foo': 0.2, 'bar': 0.4}
get_stats()[source]

get statistics of the circuit.

Parameters

None

Returns

stats – {‘qubit_num’:qubit_num, ‘cmem_num’:cmem_num, ‘gate_num’:gate_num, ‘gate_freq’:gate_freq} - qubit_num: number of qubits - cmem_num: number of classical bits - gate_num: number of gates - gate_freq: frequency of gates (Counter)

Return type

dict

get_tag_phase(tag)[source]

get parameter (= phase) for the tag

Parameters

tag (str) – tag of phase parameter for parametric quantum circuit.

Returns

phase – rotation angle (unit of angle is PI radian) for the tag.

Return type

float

Examples

>>> qc = QCirc().h(0).rz(0, tag='foo').rx(0, tag='bar')
>>> qc.set_params(params={'foo': 0.2, 'bar': 0.4})
>>> print(qc.get_tag_phase('foo'))
0.2
is_clifford()[source]

the quantum circuit is clifford or not

Parameters

None

Returns

ans – True if the quantum circuit unitary, False if otherwise

Return type

bool

is_equal(qc)[source]

eaual or not.

Parameters

qc (instance of QCirc) – quantum circuit (merged)

Returns

qcirc – quantum circuit (result)

Return type

instance of QCirc

is_unitary()[source]

the quantum circuit is unitary or not

Parameters

None

Returns

ans – True if the quantum circuit unitary, False if otherwise

Return type

bool

kind_first()[source]

get kind of first gate of the circuit.

Parameters

None

Returns

kind_list – kind of first quantum gate of quantum circuit

Return type

int

Note

return None if none of gates included

kind_list()[source]

get list of kinds from the circuit.

Parameters

None

Returns

kinds – kinds of the quantum circuit

Return type

list of kind

Note

return None if none of gates included

last

Structure/Union member

classmethod load(file_path)[source]

load the circuit

Parameters

file_path (str) – file path of dump file

Returns

qcirc – loaded circuit

Return type

instance of QCirc

merge(qc)[source]

merge two quantum circuits.

Parameters

qc (instance of QCirc) – quantum circuit (merged)

Returns

qcirc – new quantum circuit (merge result)

Return type

instance of QCirc

merge_mutable(qc)[source]

merge a quantum circuit with another one.

Parameters

qc (instance of QCirc) – quantum circuit (merged)

Returns

self – quantum circuit (merge result)

Return type

instance of QCirc

Notes

This method changes original quantum circuit.

multiple(other)[source]

integer multiple for quantum circuit

Parameters

other (instance of QCirc / int) – quantum circuit / number

Returns

qc – quantum circuit after multiplication

Return type

instance of QCirc

operate_gate(kind=None, qid=None, cid=None, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate gate

Parameters
  • kind (int) – kind of the gate

  • qid (list) – quantum id list

  • cid (list) – classical register (memory) id list

  • phase (float) – phase for rotation gate

  • gphase (float) – global phase for rotation gate

  • fac (float) – factor of phase value

Returns

self – quantum circuit

Return type

instance of QCirc

operate_qcirc(qcirc, qctrl=None)[source]

operate quantum circuit

Parameters
  • qcirc (instance of QCirc) – quantum circuit

  • qctrl (int) – control qubit id

Returns

self – quantum state after executing the quantum circuit

Return type

instance of QState

optimize(*args, **kwargs)[source]

optimize the quantum circuit (using pyzx’s full_optimize method).

Parameters

None

Returns

qc – optimized circuit

Return type

instance of QCirc

Notes

Non-unitary gates: measure, reset are not supported.

pop_gate()[source]

pop first gate of the circuit.

Parameters

None

Returns

gate – tupple of (kind, qid, para, c, ctrl) - kind … kind of gate - qid … qubit id list - para … parameters for rotation - c … classical register ID to store measured data (only for measurement gate) - ctrl … classical register id to controll the gate

Return type

tupple of (int, [int,int], [float,float,float], int, int)

Notes

This method changes original quantum circuit.

qubit_num

Structure/Union member

remap(qid=None, cid=None)[source]

remap qubit id and cmem id of quantum circuit

Parameters
  • qid (list (int)) – list of qubit id (quantum register)

  • cid (list (int)) – list of cmem id (classical memory or classical register)

Returns

qcirc – new quantum circuit after remapping

Return type

instance of QCirc

Examples

>>> qc = QCirc().h(0).cx(0,1).measure(qid=[0,1], cid=[0,1])
>>> qc.show()
q[0] -H-*-M---
q[1] ---X-|-M-
c  =/=====v=v=
2         0 1
>>> qc_new1 = qc.remap(qid=[1,0], cid=[1,0])
>>> qc_new1.show()
q[0] ---X---M-
q[1] -H-*-M-|-
c  =/=====v=v=
2         1 0
>>> qc_new2 = qc.remap(qid=[2,1], cid=[1,0])
>>> qc_new2.show()
q[0] ---------
q[1] ---X---M-
q[2] -H-*-M-|-
c  =/=====v=v=
2         1 0

Notes

Length of the qid must be equal to qubit_num of the original quantum circut. Length of cid must be equal to cmem_num of the original quantum circut. Elements of the qid and the cid must not be duplicated.

save(file_path)[source]

save the circuit

Parameters

file_path (str) – file path of dump file

Return type

None

set_params(params)[source]

set parameters for each tag

Parameters

params (dict) – tag and phase dictionary ex) {‘tag1’: phase1, ‘tag2’: phase2, …}

Return type

None

Examples

>>> qc = QCirc().h(0).rz(0, tag='foo').rx(0, tag='bar')
>>> qc.set_params(params={'foo': 0.2, 'bar': 0.4})
>>> print(qc)
h 0
rz(0.2) 0
rx(0.4) 0
>>> qc.set_params(params={'foo': 0.3, 'bar': 0.5})
>>> print(qc)
h 0
rz(0.3) 0
rx(0.5) 0
show(width=100)[source]

show the circuit

Parameters

width (int, default - 100) – width for line breaks and display long quantum circuit

Return type

None

split_unitary_non_unitary()[source]

split two part of the gate.

Parameters

None

Returns

qc_pair – former part includes only unitary gates and later part includes non-unitary gate (measure or reset) first

Return type

tupple of (QCirc, Qcirc)

tag_table

Structure/Union member

to_pyzx()[source]

get pyzx’s Circuit instance.

Parameters

None

Returns

zxqc – quantum circuit

Return type

instance of pyzx’s Circuit

Notes

Non-unitary gates: measure, reset are not supported.

to_qasm()[source]

get OpenQASM 2.0 string of the circuit.

Parameters

None

Returns

qcirc_str

Return type

str

to_qasm_file(file_path)[source]

write to OpenQASM 2.0 file.

Parameters

file_path (str) – file path name of OpenQASM 2.0 file

Return type

None

to_string()[source]

get string of the circuit (qlazy format).

Parameters

None

Returns

qcirc_str

Return type

str

qlazy.QCirc.append_qc_canvas(qc_canvas, gates, qubit_num, cmem_num)[source]
qlazy.QCirc.init_qc_canvas(qubit_num, cmem_num)[source]
qlazy.QCirc.string_to_args(s)[source]

convert string to args

qlazy.QObject module

Quantum Object

class qlazy.QObject.QObject[source]

Bases: object

ccx(q0, q1, q2, ctrl=None)[source]

operate CCX gate (toffoli gate, controlled controlled X gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (control qubit).

  • q2 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

ch(q0, q1, ctrl=None)[source]

operate CH gate (controlled H gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

cp(q0, q1, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate CP gate (controlled P gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

crx(q0, q1, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate CRX gate (controlled RX gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

  • phase (float) – rotation angle (unit of angle is PI radian).

Returns

self

Return type

instance of QObject

cry(q0, q1, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate CRY gate (controlled RY gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

  • phase (float) – rotation angle (unit of angle is PI radian).

Returns

self

Return type

instance of QObject

crz(q0, q1, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate CRZ gate (controlled RZ gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

  • phase (float) – rotation angle (unit of angle is PI radian).

Returns

self

Return type

instance of QObject

cs(q0, q1, ctrl=None)[source]

operate CS gate (controlled S gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

cs_dg(q0, q1, ctrl=None)[source]

operate CS dagger gate (controlled S dagger gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

csw(q0, q1, q2, ctrl=None)[source]

operate CSW gate (fredkin gate, controlled swap gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (swap qubit).

  • q2 (int) – qubit id (swap qubit).

Returns

self

Return type

instance of QObject

ct(q0, q1, ctrl=None)[source]

operate CT gate (controlled T gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

ct_dg(q0, q1, ctrl=None)[source]

operate CT dagger gate (controlled T dagger gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

cx(q0, q1, ctrl=None)[source]

operate CX gate (controlled X gate, controlled NOT gate, CNOT gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

cxr(q0, q1, ctrl=None)[source]

operate CXR gate (controlled root X gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

cxr_dg(q0, q1, ctrl=None)[source]

operate CXR dagger gate (controlled XR dagger gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

cy(q0, q1, ctrl=None)[source]

operate CY gate (controlled X gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

cz(q0, q1, ctrl=None)[source]

operate CZ gate (controlled Z gate).

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

Returns

self

Return type

instance of QObject

h(q0, ctrl=None)[source]

operate H gate (hadamard gate).

Parameters

q0 (int) – qubit id.

Returns

self

Return type

instance of QObject

iqft(qid)[source]

Inverse Quantum Fourier Transform

Parameters

qid (list of int) – qubit id list

Returns

self

Return type

instance of QObject

mcx(qid=None, ctrl=None)[source]

operate MCX gate (multi-controlled X gate).

Parameters

qid (list of int) – qubit id list [control, control, … , control, target]

Returns

self

Return type

instance of QObject

measure(qid, cid)[source]

add measurement gate (Z-basis).

Parameters
  • qid (list of int) – qubit id list to measure.

  • cid (list of int) – classical register id list to store measured result.

Returns

self – quantum circuit after adding

Return type

instance of QCirc

operate(pp=None, ctrl=None, qctrl=None)[source]

operate pauli product.

operate_pp(pp=None, ctrl=None, qctrl=None)[source]

operate pauli product.

Parameters
  • pp (instance of PauliProduct) – pauli product to operate

  • ctrl (int) – contoroll qubit id for controlled pauli product (this option will be removed near future)

  • qctrl (int) – contoroll qubit id for controlled pauli product

Returns

self – quantum circuit after adding

Return type

instance of QCirc

p(q0, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate P gate (phase shift gate).

Parameters
  • q0 (int) – qubit id.

  • phase (float) – rotation angle (unit of angle is PI radian).

Returns

self

Return type

instance of QObject

Notes

matrix expression is following… | 1.0 0.0 | | 0.0 exp(i*phase*PI) |

qft(qid)[source]

Quantum Fourier Transform

Parameters

qid (list of int) – qubit id list

Returns

self

Return type

instance of QObject

reset(qid=None)[source]

reset to |00..0> state.

Parameters

qid (list, default - qubit id's list for all of the qubits) – qubit id’s list to reset.

Returns

self – quantum state.

Return type

instance of QObject

Notes

If ‘qid’ is set, specified qubits are reset after measurement. So if the specified qubits are entangled with the remaining qubits, output quantum state is probabilistic. If no qubits are set, all qubits are zero reset.

rx(q0, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate RX gate (rotation around X-axis).

Parameters
  • q0 (int) – qubit id.

  • phase (float) – rotation angle (unit of angle is PI radian).

Returns

self

Return type

instance of QObject

rxx(q0, q1, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate Rxx gate.

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

  • phase (float) – rotation angle (unit of angle is PI radian).

Returns

self

Return type

instance of QObject

ry(q0, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate RY gate (rotation around Y-axis).

Parameters
  • q0 (int) – qubit id.

  • phase (float) – rotation angle (unit of angle is PI radian).

Returns

self

Return type

instance of QObject

ryy(q0, q1, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate Ryy gate.

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

  • phase (float) – rotation angle (unit of angle is PI radian).

Returns

self

Return type

instance of QObject

rz(q0, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate RZ gate (rotation around Z-axis).

Parameters
  • q0 (int) – qubit id.

  • phase (float) – rotation angle (unit of angle is PI radian).

Returns

self

Return type

instance of QObject

rzz(q0, q1, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate Rxx gate.

Parameters
  • q0 (int) – qubit id (control qubit).

  • q1 (int) – qubit id (target qubit).

  • phase (float) – rotation angle (unit of angle is PI radian).

Returns

self

Return type

instance of QObject

s(q0, ctrl=None)[source]

operate S gate.

Parameters

q0 (int) – qubit id.

Returns

self

Return type

instance of QObject

s_dg(q0, ctrl=None)[source]

operate S dagger gate (hermitian conjugate of S gate).

Parameters

q0 (int) – qubit id.

Returns

self

Return type

instance of QObject

sw(q0, q1, ctrl=None)[source]

swap gate

Parameters
  • q0 (int) – qubit id

  • q1 (int) – qubit id

Returns

self

Return type

instance of QObject

t(q0, ctrl=None)[source]

operate T gate.

Parameters

q0 (int) – qubit id.

Returns

self

Return type

instance of QObject

t_dg(q0, ctrl=None)[source]

operate T dagger gate (hermitian conjugate of T gate).

Parameters

q0 (int) – qubit id.

Returns

self

Return type

instance of QObject

x(q0, ctrl=None)[source]

operate X gate.

Parameters

q0 (int) – qubit id.

Returns

self

Return type

instance of QObject

xr(q0, ctrl=None)[source]

operate root X gate.

Parameters

q0 (int) – qubit id.

Returns

self

Return type

instance of QObject

xr_dg(q0, ctrl=None)[source]

operate root X dagger gate (hermmitian conjugate of root X gate).

Parameters

q0 (int) – qubit id.

Returns

self

Return type

instance of QObject

y(q0, ctrl=None)[source]

operate Y gate.

Parameters

q0 (int) – qubit id.

Returns

self

Return type

instance of QObject

z(q0, ctrl=None)[source]

operate Z gate.

Parameters

q0 (int) – qubit id.

Returns

self

Return type

instance of QObject

qlazy.QObject.gray_code(n)[source]

gray code generator

qlazy.QState module

Quantum State

class qlazy.QState.QState(qubit_num=0, vector=None, seed=None, use_gpu=False, **kwargs)[source]

Bases: Structure, QObject

Quantum State

qubit_num

qubit number of the quantum state (= log(state_num)).

Type

int

state_num

dimension of the quantum state vector (= 2**qubit_num).

Type

int

amp

elements of the quantum state vector.

Type

list of complex

classmethod add_method(method)[source]

add method (custum gate).

Parameters

method (func) – method (custum gate) to add.

Examples

>>> def bell(self, q0, q1):
>>>     self.h(q0).cx(q0,q1)
>>>     return self
>>> ...
>>> QState.add_method(bell)
>>> qs = QState(qubit_num=2)
>>> qs.bell(0,1)
>>> ...
classmethod add_methods(*methods)[source]

add methods (custum gates).

Parameters

methods (func, func, ...) – arguments of methods (custum gates) to add.

Examples

>>> def bell(self, q0, q1):
>>>     self.h(q0).cx(q0,q1)
>>>     return self
>>> ...
>>> def flip(self, q0, q1):
>>>     self.x(q0).x(q1)
>>>     return self
>>> ...
>>> QState.add_methods(bell, flip, ...)
>>> qs = QState(2)
>>> qs.bell(0,1)
>>> qs.flip(0,1)
>>> ...
property amp

elements of quantum state vector.

apply(matrix=None, qid=None)[source]

apply matrix.

Parameters

matrix (list of list) – matrix to apply.

Returns

self

Return type

instance of QState

Notes

If ‘qid’ isn’t set, dimension of the matrix must be equal to the 2 power of qubit number of the system. If ‘qid’ is set, dimension of the matrix must be equal to the 2 power of ‘qid’ length.

bloch(q=0)[source]

get bloch angles.

Parameters

q (int) – qubit id

Returns

  • theta (float) – bloch angle with Z-axis

  • phi (float) – bloch angle with X-axis

Notes

the unit of angle is PI radian. for example, 0.5 means 0.5*PI (radian).

buf_id

Structure/Union member

buffer_0

Structure/Union member

buffer_1

Structure/Union member

camp

Structure/Union member

clone()[source]

get the copy of the quantum state.

Parameters

None

Returns

qstate – copy of the original quantum state.

Return type

instance of QState

composite(num=1)[source]

get the composite state of same quantum states.

Parameters

num (int) – number of quantum states.

Returns

qs – composite quantum state.

Return type

instance of QState

classmethod create_register(num)[source]

create registers (qubit id’s) and initialize zero.

Parameters

num (int) – qubit number you want to use.

Examples

>>> qid = QState.create_register(3)
>>> print(qid)
[0,0,0]
classmethod del_all(*qstates)[source]

free memory of the all quantum states.

Parameters

qstates (instance of QState,instance of QState,...) – set of QState instances

Return type

None

evolve(observable=None, time=0.0, iteration=0)[source]

evolve the quantum state.

Parameters
  • observable (instance of Observable) – Hamiltonian of the system.

  • time (float) – period of time.

  • iter (int) – number of iteration.

Returns

self

Return type

instance of QState

Notes

The ‘iter’ value should be sufficiently larger than the ‘time’ value. This method change the original state.

See also

Obserbable

expect(observable=None)[source]

get the expectation value for observable under the quantum state.

Parameters

observable (instance of Observable) – obserbable of the system.

Returns

expect – expect value.

Return type

float

See also

Obserbable

fidelity(qstate, qid=None)[source]

get fidelity with the quantum state.

Parameters
  • qstate (instance of QState) – one of the two quantum states.

  • qid (list of int) – qubit id’s list.

Returns

fid – fidelity of two quantum states. absolute value of the inner product of two quantum states.

Return type

float

Notes

If ‘qid’ is set, you can get the fidelity for partial quantum state. If the specified quantum system are entangled with the remaining system, output value is probabilistic, while original quantum states do not change.

gbank

Structure/Union member

get_amp(qid=None)[source]

get the elements of quantum state vector.

Parameters

qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

ret – elements of the quantum state vector.

Return type

numpy.ndarray (complex)

Notes

If ‘qid’ is set, specified qubit state are got after remaining qubits are measured. So if the specified qubits are entangled with the remaining qubits, output quantum state is probabilistic. If no qubits are specified, you get all elements of the quantum state.

get_prob(qid=None)[source]

get the probability list of quantum state vector.

Parameters

qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

prob – key - bits string value - probability ex) {‘00’: 0.52, ‘11’: 0.48}

Return type

dict

classmethod init_register(*args)[source]

initialize registers (qubit id’s).

Parameters

args (list, list,...) – arguments of qubit registers.

Returns

idx – total qubit number.

Return type

int

Examples

>>> qid_0 = QState.create_register(3)
>>> qid_1 = QState.create_register(2)
>>> print(qid_0, qid_1)
[0,0,0] [0,0]
>>> qnum = QState.init_register(qid_0, qid_1)
>>> print(qnum, qid_0, qid_1)
5 [0,1,2] [3,4]
inpro(qstate, qid=None)[source]

get the inner product with quantum state.

Parameters
  • qstate (instance of QState) – one of the two quantum state.

  • qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

inp – inner produt (<self|qstate>).

Return type

complex

Notes

If ‘qid’ is set, you can get the inner product for partial quantum state. If the specified quantum system are entangled with the remaining system, output value is probabilistic, while original quantum states do not change.

join(qs_list)[source]

get tensor product state of the quantum states’ list.

Parameters

qs_list (list (QState)) – list of quantum states.

Returns

qs_out – tensor product state.

Return type

instance of QState

m(qid=None, shots=1, angle=0.0, phase=0.0)[source]

measurement in any direction (default: Z-axis).

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

  • angle (float, default 0.0) – direction of measurement (angle with Z-axis).

  • phase (float, default 0.0) – direction of measurement (phase around Z-axis).

Returns

md – measurement data.

Return type

instance of MData

Examples

>>> qs = QState(2).h(0).cx(0,1)
>>> md = qs.m()
>>> md.show(shots=100)
direction of measurement: z-axis
frq[00] = 52
frq[11] = 48
last state => 11

See also

MData

mb(qid=None, shots=1)[source]

bell measurement

measure(qid=None)[source]

one shot measurement in Z-direction.

Parameters

qid (list of int) – qubit id list to measure.

Returns

mval – measurement value.

Return type

str

Examples

>>> qs = QState(qubit_num=2).h(0).cx(0,1)
>>> qs.show()
>>> print(qs.measure(qid=[0,1]))
>>> qs.show()
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.7071+0.0000*i : 0.5000 |++++++
00
c[00] = +1.0000+0.0000*i : 1.0000 |+++++++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.0000+0.0000*i : 0.0000 |
mx(qid=None, shots=1)[source]

X-axis measurement.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MData

See also

MData

my(qid=None, shots=1)[source]

Y-axis measurement.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MData

See also

MData

mz(qid=None, shots=1)[source]

Z-axis measurement.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MData

See also

MData

operate_gate(kind=None, qid=None, phase=0.0, **kwargs)[source]

operate gate

Parameters
  • kind (int) – kind of the gate

  • qid (list) – quantum id list

  • phase (float) – phase for rotation gate

Returns

self – quantum state

Return type

instance of QState

operate_qcirc(qcirc, qctrl=None)[source]

operate quantum circuit

Parameters
  • qcirc (instance of QCirc) – quantum circuit

  • qctrl (int) – control qubit id

Returns

self – quantum state after executing the quantum circuit

Return type

instance of QState

Notes

The quantum circut must be unintary.

partial(qid=None)[source]

get the partial quantum state.

Parameters

qid (list of int, default - list of all of the qubit id) – qubit id’s list to get as a partial quantum system.

Returns

qs – partial quantum state.

Return type

instance of QState

Notes

If ‘qid’ is set, specified partial quantum system are got after remaining system are measured. So if the specified quantum system are entangled with the remaining system, output quantum state is probabilistic. If no qubits are specified, you get the copy of original quantum state.

prob_array

Structure/Union member

prob_updated

Structure/Union member

qubit_num

Structure/Union member

schmidt_coef(qid_0=None, qid_1=None)[source]

get schmidt coefficients.

Parameters
  • qid_0 (list) – subsystem to decomposite.

  • qid_1 (list) – another subsystem to decomposite.

Returns

coef – schmidt coefficients.

Return type

numpy.ndarray

schmidt_decomp(qid_0=None, qid_1=None)[source]

schmidt decomposition.

Parameters
  • qid_0 (list) – subsystem to decomposite.

  • qid_1 (list) – another subsystem to decomposite.

Returns

  • coef (numpy.ndarray) – schmidt coefficients.

  • qs_0 (list of QState instances) – decomposite quantum state related to ‘qid_0’.

  • qs_1 (list of QState instances) – decomposite quantum state related to ‘qid_1’.

show(qid=None, nonzero=False, preal=0)[source]

show the quantum state (elements of the state vector and probabilities).

Parameters
  • qid (list of int, default - list of all of the qubit id) – qubit id’s list to show.

  • nonzero (bool, default False) – if True, only non-zero amplitudes are printed.

  • preal (int, default 0) – state id to make positive real amplitude. (if -1 is set, do not go out the global phase factor)

Return type

None

Notes

If ‘qid’ is set, it shows the elements of quantum state vector for partial quantum system specified by ‘qid’. If the specified quantum system are entangled with the remaining system, output is probabilistic. If no qubits are specified, it shows the whole quantum state. This method does not change the original quantum state.

Examples

>>> qs = QState(2).h(0).cx(0,1)
>>> qs.show()
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.7071+0.0000*i : 0.5000 |++++++
...
>>> qs.show(qid=[0])
c[0] = +1.0000+0.0000*i : 1.0000 |+++++++++++
c[1] = +0.0000+0.0000*i : 0.0000 |
...
>>> qs.show(nonzero=True)
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[11] = +0.7071+0.0000*i : 0.5000 |++++++
state_num

Structure/Union member

tenspro(qstate)[source]

get the tensor product with quantum state.

Parameters

qstate (instance of QState) – quantum state to get the tensor product.

Returns

qstate_out – tensor produt of ‘self’ and ‘qstate’.

Return type

instance of QState

use_gpu

Structure/Union member

qlazy.Result module

Result of quantum circuit execution

class qlazy.Result.Result[source]

Bases: object

Result of quantum circuit execution

backend

backend device of quantum computing

Type

instance of Backend

qubit_num

number of qubits

Type

int

cmem_num

number of classical bits

Type

int

cid

classical register id list to get frequencys.

Type

list

shots

number of measurements

Type

int

freqency

frequencies of measured value.

Type

instance of Counter

start_time

start time to ececute the quantum circuit.

Type

instance of datetime

end_time

end time to ececute the quantum circuit.

Type

instance of datetime

elapsed_time

elapsed time to ececute the quantum circuit.

Type

float

qstate

quantum state after executing circuit.

Type

instance of QState

stabilizer

stabilizer state after executing circuit.

Type

instance of Stabilizer

cmem

classical memory after executing circuit.

Type

instance of CMem

info

result informations relating to the backend device

Type

dict

backend: Backend = None
cid: list = None
cmem: CMem = None
cmem_num: int = None
elapsed_time: float = None
end_time: datetime = None
frequency: Counter = None
info: dict = None
classmethod load(file_path)[source]

load the result

Parameters

file_path (str) – file path of dump file

Returns

result – loaded circuit

Return type

instance of Result

qstate: QState = None
qubit_num: int = None
save(file_path)[source]

save the result

Parameters

file_path (str) – file path of dump file

Return type

None

shots: int = None
show(verbose=False)[source]

show the result.

Parameters
  • verbose (bool) – verbose output or not

  • None

Return type

None

stabilizer: Stabilizer = None
start_time: datetime = None

qlazy.Stabilizer module

Stabilizer State

class qlazy.Stabilizer.MDataStabilizer(frequency=None, last=None, qid=None, qubit_num=0)[source]

Bases: object

Measured Data for Stabilizer

frequency

frequencies of measured value.

Type

Counter

last

last measured value.

Type

str

qid

qubit id’s list.

Type

list of int

qubit_num

qubit number of the quantum state (= log(state_num)).

Type

int

class qlazy.Stabilizer.Stabilizer(qubit_num=None, gene_num=None, pp_list=None, seed=None, **kwargs)[source]

Bases: Structure, QObject

Stabilizer State

qubit_num

number of qubits.

Type

int

gene_num

number of generators.

Type

int

classmethod add_method(method)[source]

add method (custum gate).

Parameters

method (func) – method (custum gate) to add.

classmethod add_methods(*methods)[source]

add methods (custum gates).

Parameters

methods (func, func, ...) – arguments of methods (custum gates) to add.

check_matrix

Structure/Union member

clone()[source]

get the copy of the quantum state.

Parameters

None

Returns

stab – copy of the original stabilizer.

Return type

instance of Stabilizer

classmethod del_all(*stabs)[source]

free memory of the all stabilizer.

Parameters

stabs (instance of Stabilizer,instance of Stabilizer,...) – set of Stabilizer instances

Return type

None

gene_num

Structure/Union member

get_pauli_fac(gene_id)[source]

get pauli factor of generator (‘+1’,’-1’,’+i’,’-i’).

Parameters

gene_id (int) – generator id to get.

Returns

pauli_fac_complex – complex facto of the generator (1+0j, 1j, -1+0j, -1j)

Return type

complex

get_pauli_op(gene_id, qubit_id)[source]

get pauli operator (‘I’,’X’,’Y’,’Z’).

Parameters
  • gene_id (int) – generator id to get.

  • qubit_id (int) – qubit id to get.

Returns

pauli_op_str – pauli operator (‘I’,’X’,’Y’,’Z’)

Return type

str

get_rank()[source]

get rank of the stabilizer

get_str()[source]

get string of the stabilzer

m(qid=None, shots=1)[source]

measurement in Z-direction.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MDataStabilizer

Examples

>>> sb = Stabilizer(qubit_num=2).set_all('Z').h(0).cx(0,1)
>>> md = qs.m(qid=[0,1], shots=100)
>>> print(md.freauency)
>>> print(md.last)
Counter({'00':55,'11':45})
11

See also

MDataStabilizer

measure(qid=None)[source]

one shot measurement in Z-direction.

Parameters

qid (list of int) – qubit id list to measure.

Returns

mval – measurement value.

Return type

str

Examples

>>> sb = Stabilizer(qubit_num=2).set_all('Z').h(0).cx(0,1)
>>> sb.show()
>>> print(sb.measure(qid=[0,1]))
>>> sb.show()
g[0]:  XX
g[1]:  ZZ
00
g[0]:  ZI
g[1]:  ZZ
mx(qid=None, shots=1)[source]

measurement in X-direction.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MDataStabilizer

my(qid=None, shots=1)[source]

measurement in Y-direction.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MDataStabilizer

mz(qid=None, shots=1)[source]

measurement in Z-direction.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MDataStabilizer

Examples

>>> sb = Stabilizer(2).set_all('Z').h(0).cx(0,1)
>>> md = qs.mz(qid=[0,1], shots=100)
>>> print(md.freauency)
>>> print(md.last)
Counter({'00':55,'11':45})
11

See also

MDataStabilizer

operate(pp=None, ctrl=None, qctrl=None)[source]

operate unitary operator to stabilizer.

Parameters
  • pp (instance of PauliProduct) – pauli product to operate

  • ctrl (int) – contoroll qubit id for controlled pauli product (this option will be removed near future)

  • qctrl (int) – contoroll qubit id for controlled pauli product

Returns

self – stabilizer after operation

Return type

instance of Stabilizer

operate_gate(kind=None, qid=None, **kwargs)[source]

operate gate

Parameters
  • kind (int) – kind of the gate

  • qid (list) – quantum id list

Returns

self – quantum state

Return type

instance of QState

operate_qcirc(qcirc, qctrl=None)[source]

operate quantum circuit

Parameters
  • qcirc (instance of QCirc) – quantum circuit

  • qctrl (int) – control qubit id

Returns

qs – quantum state after executing the quantum circuit

Return type

instance of QState

Notes

The quantum circut must be clifford.

pauli_factor

Structure/Union member

qubit_num

Structure/Union member

set_all(pauli_op_str)[source]

set all of the qubits same pauli operators.

Parameters

pauli_op_str (str) – string of pauli operator (‘X’,’Y’,’Z’).

Returns

self

Return type

instance of Stabilizer

Examples

>>> sb = Stabilizer(qubit_num=3)
>>> sb.set_all('Z')
>>> sb.show()
g[0]:  ZII
g[1]:  IZI
g[2]:  IIZ
set_pauli_fac(gene_id, pauli_fac_str)[source]

set pauli factor of generator (‘+1’,’-1’,’+i’,’-i’).

Parameters

gene_id (int) – generator id to set.

Returns

self

Return type

instance of Stabilizer

set_pauli_op(gene_id, qubit_id, pauli_op_str)[source]

set pauli operator (‘I’,’X’,’Y’,’Z’).

Parameters
  • gene_id (int) – generator id to set.

  • qubit_id (int) – qubit id to set.

Returns

self

Return type

instance of Stabilizer

show()[source]

show the generators of stabilizer.

Parameters

None

Return type

None

qlazy.config module

qlazy.core module

qlazy command

qlazy.core.main()[source]

execute qlazy command

qlazy.error module

exception qlazy.error.QState_Error_AddMethods[source]

Bases: Exception

exception qlazy.error.QState_Error_Apply[source]

Bases: Exception

exception qlazy.error.QState_Error_Bloch[source]

Bases: Exception

exception qlazy.error.QState_Error_Clone[source]

Bases: Exception

exception qlazy.error.QState_Error_Evolve[source]

Bases: Exception

exception qlazy.error.QState_Error_Expect[source]

Bases: Exception

exception qlazy.error.QState_Error_FreeAll[source]

Bases: Exception

exception qlazy.error.QState_Error_GetCmp[source]

Bases: Exception

exception qlazy.error.QState_Error_Initialize[source]

Bases: Exception

exception qlazy.error.QState_Error_InnerProduct[source]

Bases: Exception

exception qlazy.error.QState_Error_OperateQcirc[source]

Bases: Exception

exception qlazy.error.QState_Error_OperateQgate[source]

Bases: Exception

exception qlazy.error.QState_Error_Reset[source]

Bases: Exception

exception qlazy.error.QState_Error_Show[source]

Bases: Exception

exception qlazy.error.QState_Error_TensorProduct[source]

Bases: Exception

exception qlazy.error.QState_NeedMoreArguments[source]

Bases: Exception

exception qlazy.error.QState_OutOfBound[source]

Bases: Exception

exception qlazy.error.QState_SameQubitID[source]

Bases: Exception

exception qlazy.error.QState_TooManyArguments[source]

Bases: Exception

exception qlazy.error.QState_UnknownQgateKind[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_AddMethos[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_Clone[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_FreeAll[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_GetPauliFac[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_GetPauliOp[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_GetRank[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_Initialize[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_Measure[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_OperateQcirc[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_OperateQgate[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_SetPauliFac[source]

Bases: Exception

exception qlazy.error.Stabilizer_Error_SetPauliOp[source]

Bases: Exception

qlazy.gpu module

gpu related functions

qlazy.gpu.gpu_preparation()[source]

memory allocation and free (dummy)

qlazy.gpu.is_gpu_available()[source]

cuda is available or not

qlazy.gpu.is_gpu_supported_lib()[source]

this qlazy library supports cuda executoin or not

qlazy.util module

various kind of utilities

qlazy.util.check_gpu()[source]

NVIDIA GPU is available or not

qlazy.util.densop_check_args(de, kind=None, qid=None)[source]

check arguments for densop

qlazy.util.get_lib_ext()[source]

get library extension (for Mac OS)

qlazy.util.get_qgate_param_num(kind=None)[source]

get parameter number for the quantum gate

qlazy.util.get_qgate_qubit_num(kind=None)[source]

get qubit number for the quantum gate

qlazy.util.is_clifford_gate(kind)[source]

is the gate clifford?

qlazy.util.is_measurement_gate(kind)[source]

is the gate measurement?

qlazy.util.is_non_clifford_gate(kind)[source]

is the gate non-clifford?

qlazy.util.is_num(s)[source]

is this string numeric or not

qlazy.util.is_reset_gate(kind)[source]

is the gate reset?

qlazy.util.is_unitary_gate(kind=None)[source]

is the gate unitary?

qlazy.util.qstate_check_args(qs, kind=None, qid=None)[source]

check arguments for qstate

qlazy.util.read_config_ini(config_ini_path=None)[source]

read config.ini file

qlazy.util.reverse_bit_order(vec_in)[source]

reverse bit order of the state vector

Module contents

class qlazy.Backend(product=None, device=None)[source]

Bases: object

Backend device of quantum computing

product

product name of the backend (‘qlazy’ or ‘qulacs’ or ‘ibmq’)

Type

str

device

device name of the product

Type

str

config_braket

config for amazon braket backend {‘backet_name’: str, ‘poll_timeout_seconds’: int}

Type

dict

Notes

If you use amazon braket backend (braket_local, braket_aws, braket_ionq, braket_rigetti, braket_oqc), you must have config.ini file in your ‘~/.qlazy/’ directory, and discribe like following example …

Example

>>> bk = Backend(product='qlazy', device='stabilizer_simulator')
>>> bk = Backend(product='qulacs', device='gpu_simulator')
>>> bk = Backend(product='ibmq', device='least_busy')
>>> bk = Backend(product='braket_rigetti', device='aspen_11') # read ~/.qlazy/config.ini
...
$ cat ~/.qlazy/config.ini
[backend_braket]
backet_name = amazon-braket-xxxx # set your s3 backet name
...
$ cat ~/.qlazy/config.ini
[backend_braket]
backet_name = amazon-braket-xxxx # set your s3 backet name
poll_timeout_seconds = 86400  # set 1-day (default: 5-days)
classmethod devices(product)[source]

get devices list for the product

expect(qcirc=None, observable=None, shots=None, precise=False, init=None)[source]

run the quantum circuit.

Parameters
  • qcirc (instance of QCirc) – quantum circuit.

  • observable (instance of Observable) – obserbable considerd.

  • shots (int, default - None) – number of measurements for estimating the expectation value.

  • precise (bool, default - False) – precise calculation (only qlazy and qulacs) or estimation by measurements.

  • init (instance of QState, MPState) – initial quantum state

Returns

expval – expectation value

Return type

complex

Examples

>>> # simple example
>>> from qlazy import QCirc, Backend
>>> from qlazy.Observable import X,Y,Z
>>> bk = Backend(product='qlazy', device='qstate_simulator')
>>> ob = Z(0)*X(1)
>>> qc = QCirc().h(0).cx(0,1)
>>> exp = bk.expect(qcirc=qc, shots=10000, observable=ob)
>>> print(exp.real)
>>> 0.0074
classmethod ibmq_devices()[source]

get ibmq’s devices list

classmethod products()[source]

get products list

classmethod qlazy_devices()[source]

get qlazy’s devices list

classmethod qulacs_devices()[source]

get qulacs’s devices list

run(qcirc=None, shots=1, cid=None, out_state=False, init=None, **kwargs)[source]

run the quantum circuit.

Parameters
  • qcirc (instance of QCirc) – quantum circuit.

  • shots (int, default 1) – number of measurements.

  • cid (list, default None) – classical register id list to count frequency.

  • out_state (bool, default False) – output classical and quantum information after execting circuit. (only for qlazy’s qstate and stabilizer simulator)

  • init (instance of QState, Stabilizer, MPState) – initial quantum state

Returns

result – measurement result.

Return type

incetance of Result

Examples

>>> # simple example
>>> from qlazy import QCirc, Backend
>>> bk = Backend(product='qlazy', device='qstate_simulator')
>>> qc = QCirc().h(0).cx(0,1).measure(qid=[0,1], cid=[0,1])
>>> result = bk.run(qcirc=qc, shots=100)
>>> print(result.frequency)
Counter({'00': 51, '11': 49})
>>> ...
>>> # control quantum gate by measured results
>>> from qlazy import QCirc, Backend
>>> bk = Backend(product='qlazy', device='qstate_simulator')
>>> qc = QCirc.h(0)
>>> qc.cx(0,1).measure(qid=[0],cid=[0])
>>> qc.x(0, ctrl=0).x(1, ctrl=0).measure(qid=[0,1], cid=[0,1])
>>> result = bk.run(qcirc=qc, shots=100)
>>> print(result.frequency)
Counter({'00': 100})
class qlazy.CMem(cmem_num, **kwargs)[source]

Bases: Structure

Classical Memory

cmem_num

number of the classical register (classical memory size).

Type

int

bit_array

bit array of classical memory.

Type

list (int)

bit_array

Structure/Union member

property bits

bit list of classical memory.

clone()[source]

get the copy of the classical memory.

Parameters

None

Returns

cmem – copy of the original classical memory.

Return type

instance of CMem

cmem_num

Structure/Union member

get_bits()[source]

get bit list of the classical memory.

Parameters

None

Returns

bits – bits array of the classical memory

Return type

numpy.ndarray (int)

set_bits(bits)[source]

set bit list to the classical memory.

Parameters

bits (list) – bits array of the classical memory

Return type

None

class qlazy.DensOp(qubit_num=0, qstate=None, prob=None, matrix=None, **kwargs)[source]

Bases: Structure, QObject

Density Operator

row

dimension of density operator (= 2**qubit_num).

Type

int

col

dimension of density operator (= 2**qubit_num).

Type

int

element

matrix elements of density operator.

Type

list of list of complex

add(densop=None)[source]

add the density operator.

Parameters

densop (instance of DensOp) – density operator to add.

Returns

self

Return type

instance of DensOp

Notes

This method change the original density operator.

classmethod add_method(method)[source]

add method (custum gate).

Parameters

method (func) – method (custum gate) to add.

Examples

>>> def bell(self, q0, q1):
>>>     self.h(q0).cx(q0,q1)
>>> ...
>>> DensOp.add_method(bell)
>>> qs = DensOp(qubit_num=2)
>>> qs.bell(0,1)
>>> ...
classmethod add_methods(*methods)[source]

add methods (custum gates).

Parameters

methods (func, func, ...) – arguments of methods (custum gates) to add.

Examples

>>> def bell(self, q0, q1):
>>>     self.h(q0).cx(q0,q1)
>>>     return self
>>> ...
>>> def flip(self, q0, q1):
>>>     self.x(q0).x(q1)
>>>     return self
>>> ...
>>> DensOp.add_methods(bell, flip, ...)
>>> de = DensOp(qubit=2)
>>> de.bell(0,1)
>>> de.flip(0,1)
>>> ...
amp_dump(q, prob=0.0)[source]

execute the quantum channel of amplitude dumping.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probability of the quantum channel.

Returns

self

Return type

instance of DensOp

apply(matrix=None, qid=None, dire='both')[source]

apply the matrix to density operator. (= [matrix] * [self] * [dagger of matrix])

Parameters

matrix (list of list) – matrix to apply.

Return type

None

Notes

If ‘qid’ isn’t set, dimension of the matrix must be equal to dimension of the density operator. If ‘qid’ is set, dimension of the matrix must be equal to the 2 power of ‘qid’ length.

bit_flip(q, prob=0.0)[source]

execute the quantum channel of bit flip.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probabillity of the quantum channel.

Returns

self

Return type

instance of DensOp

bit_phase_flip(q, prob=0.0)[source]

execute the quantum channel of bit and phase flip.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probability of the quantum channel.

Returns

self

Return type

instance of DensOp

buf_id

Structure/Union member

buffer_0

Structure/Union member

buffer_1

Structure/Union member

clone()[source]

get the copy of density operator.

Parameters

None

Returns

densop – copy of the original density operator.

Return type

instance of DensOp

col

Structure/Union member

composite(num=0)[source]

get the composite density operator of same density operators.

Parameters

num (int) – number of density operators..

Returns

de – composite density operator.

Return type

instance of DensOp

cond_entropy(qid_0=None, qid_1=None)[source]

get the conditional entropy.

Parameters
  • qid_0 (list of int) – qubit id’s list (sub-system) to calculate the entropy.

  • qid_1 (list of int) – qubit id’s list (sub-system) to calculate the entropy.

Returns

ent – conditianal entropy (S(qid_0|qid_1)).

Return type

float

classmethod create_register(num)[source]

create registers (qubit id’s list) and initialize zero.

Parameters

num (int) – qubit number you want to use.

Returns

qid – qubit id’s list.

Return type

list of int

Examples

>>> qid = DensOp.create_register(3)
>>> print(qid)
[0,0,0]
classmethod del_all(*densops)[source]

free memory of the all density operators.

Parameters

densops (instance of DensOp,instance of DensOp,...) – set of DensOp instances

Return type

None

depolarize(q, prob=0.0)[source]

execute the quantum channel of depolarize.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probability of the quantum channel.

Returns

self

Return type

instance of DensOp

distance(densop=None, qid=None)[source]

get the trace distance with the density operator.

Parameters
  • densop (instance of DensOp) – density operator to get the trace distance.

  • qid (list of int, default - all of the qubit id's list) – qubit id’s list.

Returns

dis – trace distance.

Return type

float

property element

matrix elements of density operator.

elm

Structure/Union member

entropy(qid=None)[source]

get the von neumann entropy (or entanglement entropy).

Parameters

qid (list of int, default - list all of the qubit id) – qubit id’s list (sub-system) to calculate the entropy.

Returns

ent – von neumann entropy.

Return type

float

expect(matrix=None)[source]

get the expectation value of matrix under this density operator.

Parameters

matrix (list of list of complex) – matrix expression of hermitian operator.

Returns

value – expectation value.

Return type

float

Notes

‘matrix’ must be hermitian, and its dimension is equal to the dimension of density operator.

fidelity(densop=None, qid=None)[source]

get the fidelity with density operator.

Parameters
  • densop (instance of DensOp) – density operators to get fidelity.

  • qid (list of int, default - all of the qubit id's list) – qubit id’s list.

Returns

fid – fidelity of two density operators.

Return type

float

gbank

Structure/Union member

get_elm(qid=None)[source]

get the matrix elements of density operator.

Parameters

qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

elm – elements of the density matrix.

Return type

list of complex

Notes

If ‘qid’ is set, matrix elements of specified density operator are got after partial trace for remaining qubits. If no qubits are specified, you get all matrix elements of the density operator.

classmethod init_register(*args)[source]

initialize registers (qubit id’s list).

Parameters

args (list, list,...) – arguments of qubit registers.

Returns

idx – total qubit number.

Return type

int

Examples

>>> qid_0 = DensOp.create_register(3)
>>> qid_1 = DensOp.create_register(2)
>>> print(qid_0, qid_1)
[0,0,0] [0,0]
>>> qnum = DensOp.init_register(qid_0, qid_1)
>>> print(qnum, qid_0, qid_1)
5 [0,1,2] [3,4]
instrument(kraus=None, qid=None, measured_value=None)[source]

instrument to the density operator

Parameters
  • kraus (list of list of comprex) – Kraus operators.

  • qid (list) – qubit id’s list to measure.

  • measured_value (int) – index of measurement (in the case of selective measurement).

Returns

self

Return type

instance of DensOp

Notes

If ‘measured_value’ is set, selective measurement of the index corresponding to ‘measured_value’ is done (but not normalize). If ‘measured_value’ is not set, non-selective measurement is done (only operator sum for the Kraus operators are executed). This method does change the original density operator.

join(de_list)[source]

get tensor product state (density operator) of the density operators’ list.

Parameters

de_list (list (DensOp)) – list of density operators.

Returns

de_out – tensor product state (density operator).

Return type

instance of DensOp

static mat_norm(mat)[source]

norm of the matrix

static mat_spectrum(mat)[source]

spectrum of the hermitian matrix

static mat_sqrt(mat)[source]

square root of the matrix

classmethod mix(densop=None, prob=None)[source]

linear sum of the density operators.

Parameters
  • densop (list of instances of DensOp) – densitiy operators.

  • prob (list of float) – probabilities (coefficients of the linear sum).

mul(factor=1.0)[source]

multiply the density operator by factor.

Parameters

factor (float, default 1.0) – number to multiply.

Returns

self

Return type

instance of DensOp

Notes

This method change the original density operator.

mutual_info(qid_0=None, qid_1=None)[source]

get the mutual information.

Parameters
  • qid_0 (list of int) – qubit id’s list (sub-system) to calculate the mutual information.

  • qid_1 (list of int) – qubit id’s list (sub-system) to calculate the mutual information.

Returns

ent – mutual information (S(qid_0:qid_1)).

Return type

float

operate_gate(kind=None, qid=None, phase=0.0, **kwargs)[source]

operate gate

Parameters
  • kind (int) – kind of the gate

  • qid (list) – quantum id list

  • phase (float) – phase for rotation gate

Returns

self – quantum state

Return type

instance of DensOp

operate_qcirc(qcirc, qctrl=None)[source]

operate quantum circuit

Parameters
  • qcirc (instance of QCirc) – quantum circuit

  • qctrl (int) – control qubit id

Returns

self – quantum state after executing the quantum circuit

Return type

instance of DensOp

Notes

The quantum circut must be unintary.

partial(qid=None)[source]

get the density operator for partial system.

Parameters

qid (list of int) – qubit id’s list to show.

Returns

densop – density operator for partial system (= partial trace for remaining system).

Return type

instance of DensOp

patrace(qid=None)[source]

get the partial trace of density operator.

Parameters

qid (list of int) – qubit id’s list to show.

Returns

densop – density operator after partial trace.

Return type

instance of DensOp

phase_dump(q, prob=0.0)[source]

execute the quantum channel of phase dumping.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probability of the quantum channel.

Returns

self

Return type

instance of DensOp

phase_flip(q, prob=0.0)[source]

execute the quantum channel of phase flip.

Parameters
  • q (int) – qubit id to execute.

  • prob (float) – probability of the quantum channel.

Returns

self

Return type

instance of DensOp

probability(kraus=None, povm=None, qid=None)[source]

get the probabilities for measuring operators. (Kraus or POVM operators).

Parameters
  • kraus (list of list of comprex) – Kraus operators.

  • povm (list of list of comprex) – POVM operators.

  • qid (list) – qubit id’s list to measure.

Returns

prob – probabilities for measuring operators.

Return type

list of float

Notes

Either ‘kraus’ or ‘povm’ must be set. If ‘qid’ is not set, all of the qubits are measured, the dimention of Kraus or POVM operator must be equal to the dimension of density operator. If ‘qid’ is set, the part of qubits are measured, the dimension of Kraus or POVM operator must be equal to the 2 power of ‘qid’ length. This method does not change the original density operator.

relative_entropy(densop=None)[source]

get the relative entropy.

Parameters

densop (instance of DensOp) – density operator to get the relative entropy.

Returns

ent – relative entropy.

Return type

float

row

Structure/Union member

show(qid=None, nonzero=False)[source]

show the elements of density operator.

Parameters
  • qid (list of int, default - list of all of the qubit id) – qubit id’s list to show.

  • nonzero (bool, default False) – if True, only non-zero elements are printed.

Return type

None

Notes

If ‘qid’ is set, it shows the matrix elements of density operator for partial quantum system specified by ‘qid’. If ‘qid’ isn’t set, it shows the matrix elements of whole quantum system.

Examples

>>> de = DensOp(qubit_num=1)
>>> ...
>>> de.show()
elm[0][0] = +0.5000+0.0000*i : 0.2500 |++++
elm[0][1] = +0.0000+0.0000*i : 0.0000 |
elm[1][0] = +0.0000+0.0000*i : 0.0000 |
elm[1][1] = +0.5000+0.0000*i : 0.2500 |++++
...
>>> de.show(nonzero=True)
elm[0][0] = +0.5000+0.0000*i : 0.2500 |++++
elm[1][1] = +0.5000+0.0000*i : 0.2500 |++++
spectrum()[source]

get the spectrum.

Parameters

None

Returns

  • qstate (list of QState) – list of the quantum state basis.

  • prob (list of float) – list of coefficients for each quantum states basis.

sqtrace()[source]

get the square trace of density operator.

Parameters

None

Returns

sqtrace – square trace of the density operator.

Return type

float

tenspro(densop)[source]

get the tensor product with density operator.

Parameters

densop (instance of DensOp) – density operator to get the tensor product..

Returns

densop_out – tensor produt of ‘self’ and ‘densop’.

Return type

instance of DensOp

trace()[source]

get the trace of density operator.

Parameters

None

Returns

trace – trace of the density operator.

Return type

float

von_neumann_entropy()[source]

get the von neumann entropy (or entanglement entropy).

Parameters

None

Returns

ent – von neumann entropy.

Return type

float

class qlazy.MPState(qubit_num=0, bits_str=None, tensors=None, max_truncation_err=1e-06, **kwargs)[source]

Bases: FiniteMPS, QObject

Matrix Product State

qubit_num

number of qubits (number of nodes)

Type

int

bond_dimensions

list of bond dimensions

Type

list (int)

max_truncation_err

maximum of truncation error

Type

float

tensors

list of 3-rank tensors for the matrix product

Type

list (np.ndarray)

property amp

elements of quantum state vector.

clone()[source]

get the copy of the matrix product state.

Parameters

None

Returns

mps – copy of the original matrix product state.

Return type

instance of MPState

classmethod del_all(*mpstates)[source]

free memory of the all matrix product states.

Parameters

mpstates (instance of MPState,instance of MPState,...) – set of MPState instances

Return type

None

expect(observable=None)[source]

get the expectation value for observable under the matrix product state.

Parameters

observable (instance of Observable) – obserbable of the system.

Returns

expect – expect value.

Return type

complex

See also

Obserbable

fidelity(mps, qid=None)[source]

get fidelity with the matrix product state.

Parameters
  • mps (instance of MPState) – one of the two matrix product states.

  • qid (list of int) – qubit id’s list.

Returns

fid – fidelity of the two matrix product states. absolute value of the inner product of two matrix product states.

Return type

float

Notes

If ‘qid’ is set, you can get the fidelity for partial quantum state. If the specified quantum system are entangled with the remaining system, output value is probabilistic, while original quantum states do not change.

get_amp(qid=None)[source]

get the elements of quantum state vector.

Parameters

qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

ret – elements of the quantum state vector.

Return type

numpy.ndarray (complex)

Notes

If ‘qid’ is set, specified qubit state are got after remaining qubits are measured. So if the specified qubits are entangled with the remaining qubits, output quantum state is probabilistic. If no qubits are specified, you get all elements of the quantum state.

inpro(mps, qid=None)[source]

get the inner product with matrix product state.

Parameters
  • mps (instance of MPState) – one of the two matrix product state.

  • qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

inp – inner produt (<self|mps>).

Return type

complex

Notes

If ‘qid’ is set, you can get the inner product for partial quantum state. If the specified quantum system are entangled with the remaining system, output value is probabilistic, while original quantum states do not change.

m(qid=None, shots=1)[source]

measurement in Z-direction

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MDataMPState

See also

MDataMPState

property max_truncation_err
measure(qid=None)[source]

one shot measurement in Z-direction.

Parameters

qid (list of int) – qubit id list to measure.

Returns

mval – measurement value.

Return type

str

Examples

>>> mps = MPState(qubit_num=2).h(0).cx(0,1)
>>> mps.show()
>>> print(mps.measure(qid=[0,1]))
>>> mps.show()
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.7071+0.0000*i : 0.5000 |++++++
00
c[00] = +1.0000+0.0000*i : 1.0000 |+++++++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.0000+0.0000*i : 0.0000 |
operate_1qubit_gate(gate_str, q, para=0.0)[source]

operate 1-qubit gate.

Parameters
  • gate_str (str) – gate stiring (ex. ‘x’,’y’,’z’,’h’,’s’, ..)

  • q0 (int) – qubit id.

  • para (float) – angle for rotation gate (unit of angle is PI radian).

Returns

self

Return type

instance of MPState

operate_2qubit_gate(gate_str, q0, q1, para=0.0)[source]

operate 2-qubit gate.

Parameters
  • gate_str (str) – gate stiring (ex. ‘cx’,’cy’,’cz’,’ch’,’crz’, ..)

  • q0 (int) – qubit id.

  • q1 (int) – qubit id.

  • para (float) – angle for rotation gate (unit of angle is PI radian).

Returns

self

Return type

instance of MPState

operate_gate(kind=None, qid=None, phase=0.0, **kwargs)[source]

operate gate

Parameters
  • kind (int) – kind of the gate

  • qid (list) – quantum id list

  • phase (float) – phase for rotation gate

Returns

self – quantum state

Return type

instance of MPState

operate_qcirc(qcirc, qctrl=None)[source]

operate quantum circuit

Parameters
  • qcirc (instance of QCirc) – quantum circuit

  • qctrl (int) – control qubit id

Returns

self – quantum state after executing the quantum circuit

Return type

instance of MPState

Notes

The quantum circut must be unintary.

property qubit_num
reset_qubits(qid=None)[source]

reset to |00..0> state.

Parameters

qid (list, default - qubit id's list for all of the qubits) – qubit id’s list to reset.

Returns

self – matrix product state.

Return type

instance of MPState

Notes

If ‘qid’ is set, specified qubits are reset after measurement. So if the specified qubits are entangled with the remaining qubits, output quantum state is probabilistic. If no qubits are set, all qubits are zero reset.

show(qid=None, nonzero=False, preal=0)[source]

show the quantum state (elements of the state vector and probabilities).

Parameters
  • qid (list of int, default - list of all of the qubit id) – qubit id’s list to show.

  • nonzero (bool, default False) – if True, only non-zero amplitudes are printed.

  • preal (int, default 0) – state id to make positive real amplitude. (if -1 is set, do not go out the global phase factor)

Return type

None

Notes

If ‘qid’ is set, it shows the elements of quantum state vector for partial quantum system specified by ‘qid’. If the specified quantum system are entangled with the remaining system, output is probabilistic. If no qubits are specified, it shows the whole quantum state. This method does not change the original quantum state.

Examples

>>> mps = MPState(qubit_num=2).h(0).cx(0,1)
>>> mps.show()
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.7071+0.0000*i : 0.5000 |++++++
...
>>> mps.show(qid=[0])
c[0] = +1.0000+0.0000*i : 1.0000 |+++++++++++
c[1] = +0.0000+0.0000*i : 0.0000 |
...
>>> mps.show(nonzero=True)
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[11] = +0.7071+0.0000*i : 0.5000 |++++++
class qlazy.Observable(string=None)[source]

Bases: object

Observable for quantum many-body spin system.

base

observable

Type

instance of ObservableBase

string

string of observable description ex) “-2.0+Z_0*Z_1+X_0+X_1” for 2-qubit system

Type

str

weighted_pp_list

weighted pauli product list

Type

list of dict ({‘weight’:weight, ‘pp’:pauli_product})

qubit_num

total qubit number

Type

int

add_wpp(weight=1.0, pp=None)[source]

add the weighted pauli product to the list (self.weighted_pp_list).

Parameters
  • weight (float) – weight value correspond to the pauli product

  • pp (instance of PauliProduct) – pauli product

Returns

self – observable after adding weighted pauli product

Return type

instance of Ovservable

property base
clone()[source]

clone observable.

Parameters

None

Returns

ob – observable

Return type

instance of Observable

get_idx_weight(pp)[source]

get index and weight value correspond to the pauli product.

Parameters

pp (instance of PauliProduct) – pauli product

Returns

  • idx (int) – index number of the list (self.weighted_pp_list) correspond to the pauli product

  • weight (float) – weight value correspond to the pauli product

get_observable_base()[source]

get ObservableBase instance.

Parameters

None

Returns

ob_base – observable

Return type

instance of ObservableBase

get_qubit_num()[source]

get the total qubit number considerd

Parameters

None

Returns

qubit_num – total qubit number considerd by the observable.

Return type

inst

get_string()[source]

get string of observable.

Parameters

None

Returns

s – string of observable

Return type

str

get_weighted_pp_list(string)[source]

get weighted pauli product list.

Parameters

string (str) – string of observable

Returns

weighted_pp_list – weighted pauli product list

Return type

list of dict (weight:pauli_product)

is_hermitian()[source]

hermitian or not

Parameters

None

Returns

ans – is the observable hermitian or not

Return type

bool

property qubit_num
recalc_weight()[source]
recalculate the weights of weighted_pp_list

(weight <= weight * pp.factor, pp.factor <= 1.0)

Parameters

None

Returns

ans – is the observable hermitian or not

Return type

bool

property string
class qlazy.ObservableBase(string=None, **kwargs)[source]

Bases: Structure

Observable for quantum many-body spin system.

array_num

Structure/Union member

spin_num

Structure/Union member

spro_array

Structure/Union member

class qlazy.PauliProduct(pauli_str, qid=None, factor=1 + 0j)[source]

Bases: object

Pauli Product

qid

list of qubit id.

Type

list of int

pauli_list

list of pauli operators.

Type

list of str

factor

factor of pauli product.

Type

complex

get_binary_rep(qubit_num=None)[source]

get binary representation of pauli product.

Parameters

qubit_num (int, default - max(self.qid)+1) – qubit number of binary representation.

Returns

binary_rep – output binary representation of the pauli product.

Return type

list of int

Examples

>>> pp = PauliProduct(pauli_str="XYZ", qid=[0,1,2])
>>> print(pp.get_binary_rep())
[1,1,0,0,1,1]
get_qubit_num()[source]

get the total qubit number considerd

Parameters

None

Returns

qubit_num – total qubit number considerd by the pauli product.

Return type

inst

is_commute(pp)[source]

is pauli product commute to other pauli product or not.

Parameters

pp (instance of PauliProduct) – pauli product

Returns

ans – commute (True) or anti-commute (False)

Return type

bool

tenspro(pp)[source]

get tensor product with other pauli product.

Parameters

pp (instance of PauliProduct) – pauli product

Returns

pp_out – output pauli product

Return type

instance of PauliProduct

class qlazy.QCirc(**kwargs)[source]

Bases: Structure, QObject

Quantum Circuit

qubit_num

qubit number of the quantum state (= log(state_num)).

Type

int

cmem_num

number of the classical register.

Type

int

gate_num

number of gates in the quantum circuit.

Type

int

first

first gate of the quantum circuit.

Type

object

last

last gate of the quantum circuit.

Type

object

tag_table

tag table..

Type

object

add_control(qctrl=None)[source]

add control qubit to quantum circuit

Parameters

qctrl (int) – control qubit id

Returns

qc_out – quantum circuit after adding control qubit

Return type

instance of QCirc

add_gates(gates=None)[source]

add list of gates to the circuit.

Parameters

gates (list of dict) – gates of the quantum circuit gates = [{‘kind’:kind, ‘qid’:qid, ‘phase’:phase, ‘cid’:cid, ‘ctrl’:ctrl}, …] - kind: gate name - qid: qubit id - phase: phase parameter (non-zero only for rotation gates) - cid: classical register id (set only for measurement gate) - ctrl: classical register id for controlling gate operation

Returns

self – circuit after adding gates

Return type

instance of QCirc

Notes

This method changes original quantum circuit.

all_gates_measurement()[source]

gates of the qcirc are all measurement

Parameters

None

Returns

ans – True if all gates are measurement, False if otherwise

Return type

bool

append_gate(kind=None, qid=None, para=None, c=None, ctrl=None, tag=None)[source]

append gate to the end of the circuit.

Parameters
  • kind (int) – kind of gate

  • qid (list (int)) – list of qubit id

  • para (list (float), default None) – list of parameters

  • c (int, default None) – classical register id to store measured data

  • ctrl (int, default None) – classical register id to controll the gate

Return type

None

clone()[source]

clone quantum circuit.

Parameters

None

Returns

qcirc – quantum circuit

Return type

instance of QCirc

cmem_num

Structure/Union member

dump(file_path)[source]

dump the circuit

Parameters

file_path (str) – file path of dump file

Return type

None

equivalent(qc, *args, **kwargs)[source]

two quantum circuits are equivalent or not (using pyzx’s verify_equality method).

Parameters

None

Returns

ans

Return type

bool

Notes

Non-unitary gates: measure, reset are not supported.

first

Structure/Union member

classmethod from_pyzx(zxqc)[source]

get pyzx’s Circuit instance.

Parameters

zxqc (instance of pyzx's Circuit) – quantum circuit

Returns

qc – quantum circuit

Return type

instance of QCirc

Notes

Non-unitary gates: measure, reset are not supported.

classmethod from_qasm(string)[source]

get QCirc instance from OpenQASM 2.0 string.

Parameters

None

Returns

qcirc

Return type

instance of QCirc

Notes

Non-unitary gates (measure, reset) and user customized gates are not supported. Supported gates are ‘x’, ‘y’, ‘z’, ‘h’, ‘s’, ‘sdg’, ‘t’, ‘tdg’, ‘cx’, ‘cz’, ‘ch’, ‘rx’, ‘rz’, ‘crz’.

classmethod from_qasm_file(file_path)[source]

get QCirc instance from OpenQASM 2.0 file.

Parameters

file_path (str) – file path name of OpenQASM 2.0 file

Returns

qcirc

Return type

instance of QCirc

Notes

Non-unitary gates (measure, reset) and user customized gates are not supported. Supported gates are ‘x’, ‘y’, ‘z’, ‘h’, ‘s’, ‘sdg’, ‘t’, ‘tdg’, ‘cx’, ‘cz’, ‘ch’, ‘rx’, ‘rz’, ‘crz’.

gate_num

Structure/Union member

classmethod generate_random_gates(qubit_num=0, gate_num=0, phase=None, prob=None, **kwargs)[source]

generate circuit including random gates.

Parameters
  • qubit_num (int) – number of qubits

  • gate_num (int) – numbner of gates

  • phase (tupple of float) – phases selected randomly

  • prob (dict) –

    {‘x’:prob_x, ‘z’:prob_z, ‘h’:prob_h, ‘s’:prob_s, ‘s_dg’:prob_s_dg,

    ’t’:prob_t, ‘t_dg’:prob_t_dg, ‘rx’:prob_rx, ‘rz’:prob_rz, ‘cx’:prob_cx, ‘cz’:prob_cz, ‘ch’:prob_ch, ‘crz’:prob_crz}

    • prob_x: probability of x

    • prob_z: probability of z

    • prob_h: probability of h

    • prob_s: probability of s

    • prob_s_dg: probability of s_dg

    • prob_t: probability of t

    • prob_t_dg: probability of t_dg

    • prob_rx: probability of rx

    • prob_rz: probability of rz

    • prob_cx: probability of cx

    • prob_cz: probability of cz

    • prob_ch: probability of ch

    • prob_crz: probability of crz

Returns

qcirc – generated circuit

Return type

instance of QCirc

Examples

>>> qc = QCirc.generate_random_gates(qubit_num=5, gate_num=100,
phase_unit=0.25, prob={'h':3, 'cx':7, 'rz':1})

Notes

  • each probability values are normalized so that the sum of the probabilities is 1.0.

  • Phase parameters of rotation gates are selected randomly in the element of ‘phase’.

get_gates()[source]

get list of gates from the circuit.

Parameters

None

Returns

gates – gates of the quantum circuit gates = [{‘kind’:kind, ‘qid’:qid, ‘phase’:phase, ‘cid’:cid, ‘ctrl’:ctrl}, …] - kind: gate name - qid: qubit id - phase: phase parameter (non-zero only for rotation gates) - para: [phase, gphase, factor]

  • gphase means global phase used only when adding control to p gate

  • cid: classical register id (set only for measurement gate)

  • ctrl: classical register id to control gate operation

Return type

list of dict

get_params()[source]

get parameters for each tag

Parameters

None

Returns

params – tag and phase dictionary ex) {‘tag1’: phase1, ‘tag2’: phase2, …}

Return type

dict

Examples

>>> qc = QCirc().h(0).rz(0, tag='foo').rx(0, tag='bar')
>>> qc.set_params(params={'foo': 0.2, 'bar': 0.4})
>>> print(qc.get_params())
{'foo': 0.2, 'bar': 0.4}
get_stats()[source]

get statistics of the circuit.

Parameters

None

Returns

stats – {‘qubit_num’:qubit_num, ‘cmem_num’:cmem_num, ‘gate_num’:gate_num, ‘gate_freq’:gate_freq} - qubit_num: number of qubits - cmem_num: number of classical bits - gate_num: number of gates - gate_freq: frequency of gates (Counter)

Return type

dict

get_tag_phase(tag)[source]

get parameter (= phase) for the tag

Parameters

tag (str) – tag of phase parameter for parametric quantum circuit.

Returns

phase – rotation angle (unit of angle is PI radian) for the tag.

Return type

float

Examples

>>> qc = QCirc().h(0).rz(0, tag='foo').rx(0, tag='bar')
>>> qc.set_params(params={'foo': 0.2, 'bar': 0.4})
>>> print(qc.get_tag_phase('foo'))
0.2
is_clifford()[source]

the quantum circuit is clifford or not

Parameters

None

Returns

ans – True if the quantum circuit unitary, False if otherwise

Return type

bool

is_equal(qc)[source]

eaual or not.

Parameters

qc (instance of QCirc) – quantum circuit (merged)

Returns

qcirc – quantum circuit (result)

Return type

instance of QCirc

is_unitary()[source]

the quantum circuit is unitary or not

Parameters

None

Returns

ans – True if the quantum circuit unitary, False if otherwise

Return type

bool

kind_first()[source]

get kind of first gate of the circuit.

Parameters

None

Returns

kind_list – kind of first quantum gate of quantum circuit

Return type

int

Note

return None if none of gates included

kind_list()[source]

get list of kinds from the circuit.

Parameters

None

Returns

kinds – kinds of the quantum circuit

Return type

list of kind

Note

return None if none of gates included

last

Structure/Union member

classmethod load(file_path)[source]

load the circuit

Parameters

file_path (str) – file path of dump file

Returns

qcirc – loaded circuit

Return type

instance of QCirc

merge(qc)[source]

merge two quantum circuits.

Parameters

qc (instance of QCirc) – quantum circuit (merged)

Returns

qcirc – new quantum circuit (merge result)

Return type

instance of QCirc

merge_mutable(qc)[source]

merge a quantum circuit with another one.

Parameters

qc (instance of QCirc) – quantum circuit (merged)

Returns

self – quantum circuit (merge result)

Return type

instance of QCirc

Notes

This method changes original quantum circuit.

multiple(other)[source]

integer multiple for quantum circuit

Parameters

other (instance of QCirc / int) – quantum circuit / number

Returns

qc – quantum circuit after multiplication

Return type

instance of QCirc

operate_gate(kind=None, qid=None, cid=None, phase=0.0, gphase=0.0, fac=1.0, tag=None, ctrl=None)[source]

operate gate

Parameters
  • kind (int) – kind of the gate

  • qid (list) – quantum id list

  • cid (list) – classical register (memory) id list

  • phase (float) – phase for rotation gate

  • gphase (float) – global phase for rotation gate

  • fac (float) – factor of phase value

Returns

self – quantum circuit

Return type

instance of QCirc

operate_qcirc(qcirc, qctrl=None)[source]

operate quantum circuit

Parameters
  • qcirc (instance of QCirc) – quantum circuit

  • qctrl (int) – control qubit id

Returns

self – quantum state after executing the quantum circuit

Return type

instance of QState

optimize(*args, **kwargs)[source]

optimize the quantum circuit (using pyzx’s full_optimize method).

Parameters

None

Returns

qc – optimized circuit

Return type

instance of QCirc

Notes

Non-unitary gates: measure, reset are not supported.

pop_gate()[source]

pop first gate of the circuit.

Parameters

None

Returns

gate – tupple of (kind, qid, para, c, ctrl) - kind … kind of gate - qid … qubit id list - para … parameters for rotation - c … classical register ID to store measured data (only for measurement gate) - ctrl … classical register id to controll the gate

Return type

tupple of (int, [int,int], [float,float,float], int, int)

Notes

This method changes original quantum circuit.

qubit_num

Structure/Union member

remap(qid=None, cid=None)[source]

remap qubit id and cmem id of quantum circuit

Parameters
  • qid (list (int)) – list of qubit id (quantum register)

  • cid (list (int)) – list of cmem id (classical memory or classical register)

Returns

qcirc – new quantum circuit after remapping

Return type

instance of QCirc

Examples

>>> qc = QCirc().h(0).cx(0,1).measure(qid=[0,1], cid=[0,1])
>>> qc.show()
q[0] -H-*-M---
q[1] ---X-|-M-
c  =/=====v=v=
2         0 1
>>> qc_new1 = qc.remap(qid=[1,0], cid=[1,0])
>>> qc_new1.show()
q[0] ---X---M-
q[1] -H-*-M-|-
c  =/=====v=v=
2         1 0
>>> qc_new2 = qc.remap(qid=[2,1], cid=[1,0])
>>> qc_new2.show()
q[0] ---------
q[1] ---X---M-
q[2] -H-*-M-|-
c  =/=====v=v=
2         1 0

Notes

Length of the qid must be equal to qubit_num of the original quantum circut. Length of cid must be equal to cmem_num of the original quantum circut. Elements of the qid and the cid must not be duplicated.

save(file_path)[source]

save the circuit

Parameters

file_path (str) – file path of dump file

Return type

None

set_params(params)[source]

set parameters for each tag

Parameters

params (dict) – tag and phase dictionary ex) {‘tag1’: phase1, ‘tag2’: phase2, …}

Return type

None

Examples

>>> qc = QCirc().h(0).rz(0, tag='foo').rx(0, tag='bar')
>>> qc.set_params(params={'foo': 0.2, 'bar': 0.4})
>>> print(qc)
h 0
rz(0.2) 0
rx(0.4) 0
>>> qc.set_params(params={'foo': 0.3, 'bar': 0.5})
>>> print(qc)
h 0
rz(0.3) 0
rx(0.5) 0
show(width=100)[source]

show the circuit

Parameters

width (int, default - 100) – width for line breaks and display long quantum circuit

Return type

None

split_unitary_non_unitary()[source]

split two part of the gate.

Parameters

None

Returns

qc_pair – former part includes only unitary gates and later part includes non-unitary gate (measure or reset) first

Return type

tupple of (QCirc, Qcirc)

tag_table

Structure/Union member

to_pyzx()[source]

get pyzx’s Circuit instance.

Parameters

None

Returns

zxqc – quantum circuit

Return type

instance of pyzx’s Circuit

Notes

Non-unitary gates: measure, reset are not supported.

to_qasm()[source]

get OpenQASM 2.0 string of the circuit.

Parameters

None

Returns

qcirc_str

Return type

str

to_qasm_file(file_path)[source]

write to OpenQASM 2.0 file.

Parameters

file_path (str) – file path name of OpenQASM 2.0 file

Return type

None

to_string()[source]

get string of the circuit (qlazy format).

Parameters

None

Returns

qcirc_str

Return type

str

class qlazy.QState(qubit_num=0, vector=None, seed=None, use_gpu=False, **kwargs)[source]

Bases: Structure, QObject

Quantum State

qubit_num

qubit number of the quantum state (= log(state_num)).

Type

int

state_num

dimension of the quantum state vector (= 2**qubit_num).

Type

int

amp

elements of the quantum state vector.

Type

list of complex

classmethod add_method(method)[source]

add method (custum gate).

Parameters

method (func) – method (custum gate) to add.

Examples

>>> def bell(self, q0, q1):
>>>     self.h(q0).cx(q0,q1)
>>>     return self
>>> ...
>>> QState.add_method(bell)
>>> qs = QState(qubit_num=2)
>>> qs.bell(0,1)
>>> ...
classmethod add_methods(*methods)[source]

add methods (custum gates).

Parameters

methods (func, func, ...) – arguments of methods (custum gates) to add.

Examples

>>> def bell(self, q0, q1):
>>>     self.h(q0).cx(q0,q1)
>>>     return self
>>> ...
>>> def flip(self, q0, q1):
>>>     self.x(q0).x(q1)
>>>     return self
>>> ...
>>> QState.add_methods(bell, flip, ...)
>>> qs = QState(2)
>>> qs.bell(0,1)
>>> qs.flip(0,1)
>>> ...
property amp

elements of quantum state vector.

apply(matrix=None, qid=None)[source]

apply matrix.

Parameters

matrix (list of list) – matrix to apply.

Returns

self

Return type

instance of QState

Notes

If ‘qid’ isn’t set, dimension of the matrix must be equal to the 2 power of qubit number of the system. If ‘qid’ is set, dimension of the matrix must be equal to the 2 power of ‘qid’ length.

bloch(q=0)[source]

get bloch angles.

Parameters

q (int) – qubit id

Returns

  • theta (float) – bloch angle with Z-axis

  • phi (float) – bloch angle with X-axis

Notes

the unit of angle is PI radian. for example, 0.5 means 0.5*PI (radian).

buf_id

Structure/Union member

buffer_0

Structure/Union member

buffer_1

Structure/Union member

camp

Structure/Union member

clone()[source]

get the copy of the quantum state.

Parameters

None

Returns

qstate – copy of the original quantum state.

Return type

instance of QState

composite(num=1)[source]

get the composite state of same quantum states.

Parameters

num (int) – number of quantum states.

Returns

qs – composite quantum state.

Return type

instance of QState

classmethod create_register(num)[source]

create registers (qubit id’s) and initialize zero.

Parameters

num (int) – qubit number you want to use.

Examples

>>> qid = QState.create_register(3)
>>> print(qid)
[0,0,0]
classmethod del_all(*qstates)[source]

free memory of the all quantum states.

Parameters

qstates (instance of QState,instance of QState,...) – set of QState instances

Return type

None

evolve(observable=None, time=0.0, iteration=0)[source]

evolve the quantum state.

Parameters
  • observable (instance of Observable) – Hamiltonian of the system.

  • time (float) – period of time.

  • iter (int) – number of iteration.

Returns

self

Return type

instance of QState

Notes

The ‘iter’ value should be sufficiently larger than the ‘time’ value. This method change the original state.

See also

Obserbable

expect(observable=None)[source]

get the expectation value for observable under the quantum state.

Parameters

observable (instance of Observable) – obserbable of the system.

Returns

expect – expect value.

Return type

float

See also

Obserbable

fidelity(qstate, qid=None)[source]

get fidelity with the quantum state.

Parameters
  • qstate (instance of QState) – one of the two quantum states.

  • qid (list of int) – qubit id’s list.

Returns

fid – fidelity of two quantum states. absolute value of the inner product of two quantum states.

Return type

float

Notes

If ‘qid’ is set, you can get the fidelity for partial quantum state. If the specified quantum system are entangled with the remaining system, output value is probabilistic, while original quantum states do not change.

gbank

Structure/Union member

get_amp(qid=None)[source]

get the elements of quantum state vector.

Parameters

qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

ret – elements of the quantum state vector.

Return type

numpy.ndarray (complex)

Notes

If ‘qid’ is set, specified qubit state are got after remaining qubits are measured. So if the specified qubits are entangled with the remaining qubits, output quantum state is probabilistic. If no qubits are specified, you get all elements of the quantum state.

get_prob(qid=None)[source]

get the probability list of quantum state vector.

Parameters

qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

prob – key - bits string value - probability ex) {‘00’: 0.52, ‘11’: 0.48}

Return type

dict

classmethod init_register(*args)[source]

initialize registers (qubit id’s).

Parameters

args (list, list,...) – arguments of qubit registers.

Returns

idx – total qubit number.

Return type

int

Examples

>>> qid_0 = QState.create_register(3)
>>> qid_1 = QState.create_register(2)
>>> print(qid_0, qid_1)
[0,0,0] [0,0]
>>> qnum = QState.init_register(qid_0, qid_1)
>>> print(qnum, qid_0, qid_1)
5 [0,1,2] [3,4]
inpro(qstate, qid=None)[source]

get the inner product with quantum state.

Parameters
  • qstate (instance of QState) – one of the two quantum state.

  • qid (list of int, default - list of all of the qubit id) – qubit id’s list.

Returns

inp – inner produt (<self|qstate>).

Return type

complex

Notes

If ‘qid’ is set, you can get the inner product for partial quantum state. If the specified quantum system are entangled with the remaining system, output value is probabilistic, while original quantum states do not change.

join(qs_list)[source]

get tensor product state of the quantum states’ list.

Parameters

qs_list (list (QState)) – list of quantum states.

Returns

qs_out – tensor product state.

Return type

instance of QState

m(qid=None, shots=1, angle=0.0, phase=0.0)[source]

measurement in any direction (default: Z-axis).

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

  • angle (float, default 0.0) – direction of measurement (angle with Z-axis).

  • phase (float, default 0.0) – direction of measurement (phase around Z-axis).

Returns

md – measurement data.

Return type

instance of MData

Examples

>>> qs = QState(2).h(0).cx(0,1)
>>> md = qs.m()
>>> md.show(shots=100)
direction of measurement: z-axis
frq[00] = 52
frq[11] = 48
last state => 11

See also

MData

mb(qid=None, shots=1)[source]

bell measurement

measure(qid=None)[source]

one shot measurement in Z-direction.

Parameters

qid (list of int) – qubit id list to measure.

Returns

mval – measurement value.

Return type

str

Examples

>>> qs = QState(qubit_num=2).h(0).cx(0,1)
>>> qs.show()
>>> print(qs.measure(qid=[0,1]))
>>> qs.show()
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.7071+0.0000*i : 0.5000 |++++++
00
c[00] = +1.0000+0.0000*i : 1.0000 |+++++++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.0000+0.0000*i : 0.0000 |
mx(qid=None, shots=1)[source]

X-axis measurement.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MData

See also

MData

my(qid=None, shots=1)[source]

Y-axis measurement.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MData

See also

MData

mz(qid=None, shots=1)[source]

Z-axis measurement.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MData

See also

MData

operate_gate(kind=None, qid=None, phase=0.0, **kwargs)[source]

operate gate

Parameters
  • kind (int) – kind of the gate

  • qid (list) – quantum id list

  • phase (float) – phase for rotation gate

Returns

self – quantum state

Return type

instance of QState

operate_qcirc(qcirc, qctrl=None)[source]

operate quantum circuit

Parameters
  • qcirc (instance of QCirc) – quantum circuit

  • qctrl (int) – control qubit id

Returns

self – quantum state after executing the quantum circuit

Return type

instance of QState

Notes

The quantum circut must be unintary.

partial(qid=None)[source]

get the partial quantum state.

Parameters

qid (list of int, default - list of all of the qubit id) – qubit id’s list to get as a partial quantum system.

Returns

qs – partial quantum state.

Return type

instance of QState

Notes

If ‘qid’ is set, specified partial quantum system are got after remaining system are measured. So if the specified quantum system are entangled with the remaining system, output quantum state is probabilistic. If no qubits are specified, you get the copy of original quantum state.

prob_array

Structure/Union member

prob_updated

Structure/Union member

qubit_num

Structure/Union member

schmidt_coef(qid_0=None, qid_1=None)[source]

get schmidt coefficients.

Parameters
  • qid_0 (list) – subsystem to decomposite.

  • qid_1 (list) – another subsystem to decomposite.

Returns

coef – schmidt coefficients.

Return type

numpy.ndarray

schmidt_decomp(qid_0=None, qid_1=None)[source]

schmidt decomposition.

Parameters
  • qid_0 (list) – subsystem to decomposite.

  • qid_1 (list) – another subsystem to decomposite.

Returns

  • coef (numpy.ndarray) – schmidt coefficients.

  • qs_0 (list of QState instances) – decomposite quantum state related to ‘qid_0’.

  • qs_1 (list of QState instances) – decomposite quantum state related to ‘qid_1’.

show(qid=None, nonzero=False, preal=0)[source]

show the quantum state (elements of the state vector and probabilities).

Parameters
  • qid (list of int, default - list of all of the qubit id) – qubit id’s list to show.

  • nonzero (bool, default False) – if True, only non-zero amplitudes are printed.

  • preal (int, default 0) – state id to make positive real amplitude. (if -1 is set, do not go out the global phase factor)

Return type

None

Notes

If ‘qid’ is set, it shows the elements of quantum state vector for partial quantum system specified by ‘qid’. If the specified quantum system are entangled with the remaining system, output is probabilistic. If no qubits are specified, it shows the whole quantum state. This method does not change the original quantum state.

Examples

>>> qs = QState(2).h(0).cx(0,1)
>>> qs.show()
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[01] = +0.0000+0.0000*i : 0.0000 |
c[10] = +0.0000+0.0000*i : 0.0000 |
c[11] = +0.7071+0.0000*i : 0.5000 |++++++
...
>>> qs.show(qid=[0])
c[0] = +1.0000+0.0000*i : 1.0000 |+++++++++++
c[1] = +0.0000+0.0000*i : 0.0000 |
...
>>> qs.show(nonzero=True)
c[00] = +0.7071+0.0000*i : 0.5000 |++++++
c[11] = +0.7071+0.0000*i : 0.5000 |++++++
state_num

Structure/Union member

tenspro(qstate)[source]

get the tensor product with quantum state.

Parameters

qstate (instance of QState) – quantum state to get the tensor product.

Returns

qstate_out – tensor produt of ‘self’ and ‘qstate’.

Return type

instance of QState

use_gpu

Structure/Union member

class qlazy.Result[source]

Bases: object

Result of quantum circuit execution

backend

backend device of quantum computing

Type

instance of Backend

qubit_num

number of qubits

Type

int

cmem_num

number of classical bits

Type

int

cid

classical register id list to get frequencys.

Type

list

shots

number of measurements

Type

int

freqency

frequencies of measured value.

Type

instance of Counter

start_time

start time to ececute the quantum circuit.

Type

instance of datetime

end_time

end time to ececute the quantum circuit.

Type

instance of datetime

elapsed_time

elapsed time to ececute the quantum circuit.

Type

float

qstate

quantum state after executing circuit.

Type

instance of QState

stabilizer

stabilizer state after executing circuit.

Type

instance of Stabilizer

cmem

classical memory after executing circuit.

Type

instance of CMem

info

result informations relating to the backend device

Type

dict

backend: Backend = None
cid: list = None
cmem: CMem = None
cmem_num: int = None
elapsed_time: float = None
end_time: datetime = None
frequency: Counter = None
info: dict = None
classmethod load(file_path)[source]

load the result

Parameters

file_path (str) – file path of dump file

Returns

result – loaded circuit

Return type

instance of Result

qstate: QState = None
qubit_num: int = None
save(file_path)[source]

save the result

Parameters

file_path (str) – file path of dump file

Return type

None

shots: int = None
show(verbose=False)[source]

show the result.

Parameters
  • verbose (bool) – verbose output or not

  • None

Return type

None

stabilizer: Stabilizer = None
start_time: datetime = None
class qlazy.Stabilizer(qubit_num=None, gene_num=None, pp_list=None, seed=None, **kwargs)[source]

Bases: Structure, QObject

Stabilizer State

qubit_num

number of qubits.

Type

int

gene_num

number of generators.

Type

int

classmethod add_method(method)[source]

add method (custum gate).

Parameters

method (func) – method (custum gate) to add.

classmethod add_methods(*methods)[source]

add methods (custum gates).

Parameters

methods (func, func, ...) – arguments of methods (custum gates) to add.

check_matrix

Structure/Union member

clone()[source]

get the copy of the quantum state.

Parameters

None

Returns

stab – copy of the original stabilizer.

Return type

instance of Stabilizer

classmethod del_all(*stabs)[source]

free memory of the all stabilizer.

Parameters

stabs (instance of Stabilizer,instance of Stabilizer,...) – set of Stabilizer instances

Return type

None

gene_num

Structure/Union member

get_pauli_fac(gene_id)[source]

get pauli factor of generator (‘+1’,’-1’,’+i’,’-i’).

Parameters

gene_id (int) – generator id to get.

Returns

pauli_fac_complex – complex facto of the generator (1+0j, 1j, -1+0j, -1j)

Return type

complex

get_pauli_op(gene_id, qubit_id)[source]

get pauli operator (‘I’,’X’,’Y’,’Z’).

Parameters
  • gene_id (int) – generator id to get.

  • qubit_id (int) – qubit id to get.

Returns

pauli_op_str – pauli operator (‘I’,’X’,’Y’,’Z’)

Return type

str

get_rank()[source]

get rank of the stabilizer

get_str()[source]

get string of the stabilzer

m(qid=None, shots=1)[source]

measurement in Z-direction.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MDataStabilizer

Examples

>>> sb = Stabilizer(qubit_num=2).set_all('Z').h(0).cx(0,1)
>>> md = qs.m(qid=[0,1], shots=100)
>>> print(md.freauency)
>>> print(md.last)
Counter({'00':55,'11':45})
11

See also

MDataStabilizer

measure(qid=None)[source]

one shot measurement in Z-direction.

Parameters

qid (list of int) – qubit id list to measure.

Returns

mval – measurement value.

Return type

str

Examples

>>> sb = Stabilizer(qubit_num=2).set_all('Z').h(0).cx(0,1)
>>> sb.show()
>>> print(sb.measure(qid=[0,1]))
>>> sb.show()
g[0]:  XX
g[1]:  ZZ
00
g[0]:  ZI
g[1]:  ZZ
mx(qid=None, shots=1)[source]

measurement in X-direction.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MDataStabilizer

my(qid=None, shots=1)[source]

measurement in Y-direction.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MDataStabilizer

mz(qid=None, shots=1)[source]

measurement in Z-direction.

Parameters
  • qid (list of int) – qubit id list to measure.

  • shots (int, default 1) – number of measurements.

Returns

md – measurement data.

Return type

instance of MDataStabilizer

Examples

>>> sb = Stabilizer(2).set_all('Z').h(0).cx(0,1)
>>> md = qs.mz(qid=[0,1], shots=100)
>>> print(md.freauency)
>>> print(md.last)
Counter({'00':55,'11':45})
11

See also

MDataStabilizer

operate(pp=None, ctrl=None, qctrl=None)[source]

operate unitary operator to stabilizer.

Parameters
  • pp (instance of PauliProduct) – pauli product to operate

  • ctrl (int) – contoroll qubit id for controlled pauli product (this option will be removed near future)

  • qctrl (int) – contoroll qubit id for controlled pauli product

Returns

self – stabilizer after operation

Return type

instance of Stabilizer

operate_gate(kind=None, qid=None, **kwargs)[source]

operate gate

Parameters
  • kind (int) – kind of the gate

  • qid (list) – quantum id list

Returns

self – quantum state

Return type

instance of QState

operate_qcirc(qcirc, qctrl=None)[source]

operate quantum circuit

Parameters
  • qcirc (instance of QCirc) – quantum circuit

  • qctrl (int) – control qubit id

Returns

qs – quantum state after executing the quantum circuit

Return type

instance of QState

Notes

The quantum circut must be clifford.

pauli_factor

Structure/Union member

qubit_num

Structure/Union member

set_all(pauli_op_str)[source]

set all of the qubits same pauli operators.

Parameters

pauli_op_str (str) – string of pauli operator (‘X’,’Y’,’Z’).

Returns

self

Return type

instance of Stabilizer

Examples

>>> sb = Stabilizer(qubit_num=3)
>>> sb.set_all('Z')
>>> sb.show()
g[0]:  ZII
g[1]:  IZI
g[2]:  IIZ
set_pauli_fac(gene_id, pauli_fac_str)[source]

set pauli factor of generator (‘+1’,’-1’,’+i’,’-i’).

Parameters

gene_id (int) – generator id to set.

Returns

self

Return type

instance of Stabilizer

set_pauli_op(gene_id, qubit_id, pauli_op_str)[source]

set pauli operator (‘I’,’X’,’Y’,’Z’).

Parameters
  • gene_id (int) – generator id to set.

  • qubit_id (int) – qubit id to set.

Returns

self

Return type

instance of Stabilizer

show()[source]

show the generators of stabilizer.

Parameters

None

Return type

None