Skip to content

quantumcircuit ¤

This module contains the QuantumCircuit class, which offers an intuitive interface for designing, visualizing, and converting quantum circuits in various formats such as OpenQASM 2.0 and qlisp.

Classes:

Name Description
QuantumCircuit

A class used to build and manipulate a quantum circuit.

Functions:

Name Description
generate_ghz_state

Produce a GHZ state on n qubits.

QuantumCircuit(*args) ¤

A class used to build and manipulate a quantum circuit.

This class allows you to create quantum circuits with a specified number of quantum and classical bits. The circuit can be customized using various quantum gates, and additional features (such as simulation support, circuit summary, and more) will be added in future versions.

Attributes:

Name Type Description
nqubits int or None

Number of quantum bits in the circuit.

ncbits int or None

Number of classical bits in the circuit.

Initialize a QuantumCircuit object.

The constructor supports three different initialization modes: 1. QuantumCircuit(): Creates a circuit with nqubits and ncbits both set to None. 2. QuantumCircuit(nqubits): Creates a circuit with the specified number of quantum bits (nqubits), and classical bits (ncbits) set to the same value as nqubits. 3. QuantumCircuit(nqubits, ncbits): Creates a circuit with the specified number of quantum bits (nqubits) and classical bits (ncbits).

Parameters:

Name Type Description Default
*args

Variable length argument list used to specify the number of qubits and classical bits.

()

Raises:

Type Description
ValueError

If more than two arguments are provided, or if the arguments are not in one of the specified valid forms.

Methods:

Name Description
from_openqasm2

Initializes the QuantumCircuit object based on the given OpenQASM 2.0 string.

from_qlisp

Initializes the QuantumCircuit object based on the given qlisp list.

id

Add a Identity gate.

x

Add a X gate.

y

Add a Y gate.

z

Add a Z gate.

s

Add a S gate.

sdg

Add a S dagger gate.

sx

Add a Sqrt(X) gate.

sxdg

Add a Sqrt(X) dagger gate.

t

Add a T gate.

tdg

Add a T dagger gate.

h

Add a H gate.

swap

Add a SWAP gate.

iswap

Add a ISWAP gate.

cx

Add a CX gate.

cnot

Add a CNOT gate.

cy

Add a CY gate.

cz

Add a CZ gate.

ccz

Add CCZ gate.

ccx

Add CCX gate.

cswap

Add CSWAP gate.

p

Add a Phase gate.

r

Add a R gate.

u

Add a U3 gate.

u3

Add a U3 gate.

rx

Add a RX gate.

ry

Add a RY gate.

rz

Add a RZ gate.

rxx

Add a RXX gate.

ryy

Add a RYY gate.

rzz

Add a RZZ gate.

cp

Add a Cphase gate.

mapping_to_others

Map current qubit indices to new indices.

u3_for_unitary

Decomposes a 2x2 unitary matrix into a U3 gate and applies it to a specified qubit.

zyz_for_unitary

Decomposes a 2x2 unitary matrix into Rz-Ry-Rz gate sequence and applies it to a specified qubit.

kak_for_unitary

Decomposes a 4 x 4 unitary matrix into a sequence of CZ and U3 gates using KAK decomposition and applies them to the specified qubits.

reset

Add reset to qubit.

delay

Adds delay to qubits, the unit is s.

barrier

Adds barrier to qubits.

remove_barrier

Remove all barrier gates from the quantum circuit.

remove_gate

Remove specified gates from the circuit.

count_gate

Count target gates in this QuantumCircuit.

measure

Adds measurement to qubits.

measure_all

Adds measurement to all qubits.

draw

Draw the quantum circuit.

draw_simply

Draw a simplified quantum circuit diagram.

Source code in quark/circuit/quantumcircuit.py
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
def __init__(self, *args):
    r"""
    Initialize a QuantumCircuit object.

    The constructor supports three different initialization modes:
    1. `QuantumCircuit()`: Creates a circuit with `nqubits` and `ncbits` both set to `None`.
    2. `QuantumCircuit(nqubits)`: Creates a circuit with the specified number of quantum bits (`nqubits`), 
    and classical bits (`ncbits`) set to the same value as `nqubits`.
    3. `QuantumCircuit(nqubits, ncbits)`: Creates a circuit with the specified number of quantum bits (`nqubits`) 
    and classical bits (`ncbits`).

    Args:
        *args: Variable length argument list used to specify the number of qubits and classical bits.

    Raises:
        ValueError: If more than two arguments are provided, or if the arguments are not in one of the specified valid forms.
    """
    if len(args) == 0:
        self.nqubits = None
        self.ncbits = self.nqubits
    elif len(args) == 1:
        self.nqubits = args[0]
        self.ncbits = self.nqubits
    elif len(args) == 2:
        self.nqubits = args[0]
        self.ncbits = args[1]
    else:
        raise ValueError("Support only QuantumCircuit(), QuantumCircuit(nqubits) or QuantumCircuit(nqubits,ncbits).")

    self.qubits = []
    self.gates = []
    self.params_value = {}

to_openqasm2: str property ¤

Export the quantum circuit to an OpenQASM 2 program in a string.

Returns:

Name Type Description
str str

An OpenQASM 2 string representing the circuit.

to_qlisp: list property ¤

Export the quantum circuit to qlisp list.

Returns:

Name Type Description
list list

qlisp list

depth: int property ¤

Count QuantumCircuit depth.

Returns:

Name Type Description
int int

QuantumCircuit depth.

ncz: int property ¤

Count all two-qubit gates in this QuantumCircuit.

Returns:

Name Type Description
int int

The number of two-qubit gates.

from_openqasm2(openqasm2_str: str) -> QuantumCircuit ¤

Initializes the QuantumCircuit object based on the given OpenQASM 2.0 string.

Parameters:

Name Type Description Default
openqasm2_str str

A string representing a quantum circuit in OpenQASM 2.0 format.

required
Source code in quark/circuit/quantumcircuit.py
155
156
157
158
159
160
161
162
163
164
165
166
167
168
def from_openqasm2(self,openqasm2_str: str) -> 'QuantumCircuit':
    r"""
    Initializes the QuantumCircuit object based on the given OpenQASM 2.0 string.

    Args:
        openqasm2_str (str): A string representing a quantum circuit in OpenQASM 2.0 format.
    """
    assert('OPENQASM 2.0' in openqasm2_str)
    new_gates,qubit_used,cbit_used = parse_openqasm2_to_gates(openqasm2_str)
    self.nqubits = max(qubit_used, default=0) + 1 
    self.ncbits = max(cbit_used, default=0) + 1
    self.qubits = list(qubit_used) #[i for i in range(self.nqubits)]
    self.gates = new_gates
    return self

from_qlisp(qlisp: list | str) -> QuantumCircuit ¤

Initializes the QuantumCircuit object based on the given qlisp list.

Parameters:

Name Type Description Default
qlisp list

A list representing a quantum circuit in qlisp format.

required
Source code in quark/circuit/quantumcircuit.py
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
def from_qlisp(self, qlisp: list|str) -> 'QuantumCircuit':
    r"""
    Initializes the QuantumCircuit object based on the given qlisp list.

    Args:
        qlisp (list): A list representing a quantum circuit in qlisp format.
    """
    if isinstance(qlisp, str):
        import ast
        qlisp = ast.literal_eval(qlisp)
    new_gates, qubit_used,cbit_used = parse_qlisp_to_gates(qlisp)
    self.nqubits = max(qubit_used, default=0) + 1 
    self.ncbits = max(cbit_used, default=0) + 1
    self.qubits = list(qubit_used) #[i for i in range(self.nqubits)]
    self.gates = new_gates
    return self

id(qubit: int) -> QuantumCircuit ¤

Add a Identity gate.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def id(self, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a Identity gate.

    Args:
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('id', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

x(qubit: int) -> QuantumCircuit ¤

Add a X gate.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
def x(self, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a X gate.

    Args:
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('x', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

y(qubit: int) -> QuantumCircuit ¤

Add a Y gate.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
def y(self, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a Y gate.

    Args:
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('y', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

z(qubit: int) -> QuantumCircuit ¤

Add a Z gate.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
def z(self, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a Z gate.

    Args:
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('z', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

s(qubit: int) -> QuantumCircuit ¤

Add a S gate.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
def s(self, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a S gate.

    Args:
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('s', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

sdg(qubit: int) -> QuantumCircuit ¤

Add a S dagger gate.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
def sdg(self, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a S dagger gate.

    Args:
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('sdg', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

sx(qubit: int) -> QuantumCircuit ¤

Add a Sqrt(X) gate.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
def sx(self, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a Sqrt(X) gate.

    Args:
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('sx', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

sxdg(qubit: int) -> QuantumCircuit ¤

Add a Sqrt(X) dagger gate.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
def sxdg(self, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a Sqrt(X) dagger gate.

    Args:
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('sxdg', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

t(qubit: int) -> QuantumCircuit ¤

Add a T gate.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
def t(self, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a T gate.

    Args:
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('t', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

tdg(qubit: int) -> QuantumCircuit ¤

Add a T dagger gate.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
331
332
333
334
335
336
337
338
339
340
341
342
343
344
def tdg(self, qubit: int) -> 'QuantumCircuit':
    r"""Add a T dagger gate.

    Args:
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('tdg', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

h(qubit: int) -> QuantumCircuit ¤

Add a H gate.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
def h(self, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a H gate.

    Args:
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('h', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

swap(qubit1: int, qubit2: int) -> QuantumCircuit ¤

Add a SWAP gate.

Parameters:

Name Type Description Default
qubit1 int

The first qubit to apply the gate to.

required
qubit2 int

The second qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
def swap(self, qubit1: int, qubit2: int) -> 'QuantumCircuit':
    r"""
    Add a SWAP gate.

    Args:
        qubit1 (int): The first qubit to apply the gate to.
        qubit2 (int): The second qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if max(qubit1,qubit2) < self.nqubits:
        if qubit1 != qubit2:
            self.gates.append(('swap', qubit1,qubit2))
            self._add_qubits(qubit1,qubit2)
        else:
            raise ValueError(f"Qubit index conflict: qubit1 and qubit2 are both {qubit1}")
    else:
        raise ValueError("Qubit index out of range")

iswap(qubit1: int, qubit2: int) -> QuantumCircuit ¤

Add a ISWAP gate.

Parameters:

Name Type Description Default
qubit1 int

The first qubit to apply the gate to.

required
qubit2 int

The second qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def iswap(self, qubit1: int, qubit2: int) -> 'QuantumCircuit':
    r"""
    Add a ISWAP gate.

    Args:
        qubit1 (int): The first qubit to apply the gate to.
        qubit2 (int): The second qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if max(qubit1, qubit2) < self.nqubits:
        if qubit1 != qubit2:
            self.gates.append(('iswap', qubit1,qubit2))
            self._add_qubits(qubit1,qubit2)
        else:
            raise ValueError(f"Qubit index conflict: qubit1 and qubit2 are both {qubit1}")
    else:
        raise ValueError("Qubit index out of range")

cx(control_qubit: int, target_qubit: int) -> QuantumCircuit ¤

Add a CX gate.

Parameters:

Name Type Description Default
control_qubit int

The qubit used as control.

required
target_qubit int

The qubit targeted by the gate.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
def cx(self, control_qubit: int, target_qubit: int) -> 'QuantumCircuit':
    r"""
    Add a CX gate.

    Args:
        control_qubit (int): The qubit used as control.
        target_qubit (int): The qubit targeted by the gate.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if max(control_qubit,target_qubit) < self.nqubits:
        if control_qubit != target_qubit:
            self.gates.append(('cx', control_qubit,target_qubit))
            self._add_qubits(control_qubit,target_qubit)
        else:
            raise ValueError(f"Qubit index conflict: control_qubit and target_qubit are both {control_qubit}")
    else:
        raise ValueError("Qubit index out of range")

cnot(control_qubit: int, target_qubit: int) -> QuantumCircuit ¤

Add a CNOT gate.

Parameters:

Name Type Description Default
control_qubit int

The qubit used as control.

required
target_qubit int

The qubit targeted by the gate.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
def cnot(self, control_qubit: int, target_qubit: int) -> 'QuantumCircuit':
    r"""
    Add a CNOT gate.

    Args:
        control_qubit (int): The qubit used as control.
        target_qubit (int): The qubit targeted by the gate.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if max(control_qubit,target_qubit) < self.nqubits:
        if control_qubit != target_qubit:
            self.cx(control_qubit, target_qubit)
            self._add_qubits(control_qubit,target_qubit)
        else:
            raise ValueError(f"Qubit index conflict: control_qubit and target_qubit are both {control_qubit}")
    else:
        raise ValueError("Qubit index out of range")

cy(control_qubit: int, target_qubit: int) -> QuantumCircuit ¤

Add a CY gate.

Parameters:

Name Type Description Default
control_qubit int

The qubit used as control.

required
target_qubit int

The qubit targeted by the gate.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
def cy(self, control_qubit: int, target_qubit: int) -> 'QuantumCircuit':
    r"""
    Add a CY gate.

    Args:
        control_qubit (int): The qubit used as control.
        target_qubit (int): The qubit targeted by the gate.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if max(control_qubit,target_qubit) < self.nqubits:
        if control_qubit != target_qubit:
            self.gates.append(('cy', control_qubit,target_qubit))
            self._add_qubits(control_qubit,target_qubit)
        else:
            raise ValueError(f"Qubit index conflict: control_qubit and target_qubit are both {control_qubit}")
    else:
        raise ValueError("Qubit index out of range")

cz(control_qubit: int, target_qubit: int) -> QuantumCircuit ¤

Add a CZ gate.

Parameters:

Name Type Description Default
control_qubit int

The qubit used as control.

required
target_qubit int

The qubit targeted by the gate.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
def cz(self, control_qubit: int, target_qubit: int) -> 'QuantumCircuit':
    r"""
    Add a CZ gate.

    Args:
        control_qubit (int): The qubit used as control.
        target_qubit (int): The qubit targeted by the gate.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if max(control_qubit,target_qubit) < self.nqubits:
        if control_qubit != target_qubit:
            self.gates.append(('cz', control_qubit, target_qubit))
            self._add_qubits(control_qubit,target_qubit)
        else:
            raise ValueError(f"Qubit index conflict: control_qubit and target_qubit are both {control_qubit}")
    else:
        raise ValueError("Qubit index out of range")

ccz(control_qubit1: int, control_qubit2: int, target_qubit: int) -> QuantumCircuit ¤

Add CCZ gate.

Parameters:

Name Type Description Default
control_qubit1 int

The qubit used as the first control.

required
control_qubit2 int

The qubit used as the second control.

required
target_qubit int

The qubit targeted by the gate.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
def ccz(self,control_qubit1:int,control_qubit2:int,target_qubit:int) -> 'QuantumCircuit':
    """Add CCZ gate.

    Args:
        control_qubit1 (int): The qubit used as the first control.
        control_qubit2 (int): The qubit used as the second control.
        target_qubit (int): The qubit targeted by the gate.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    qubits0 = [control_qubit1,control_qubit2,target_qubit]
    if max(qubits0) < self.nqubits:
        if len(set(qubits0)) == 3:
            self.gates.append(('ccz',control_qubit1,control_qubit2,target_qubit))
            self._add_qubits(*qubits0)
        else:
            raise ValueError(f"Qubit index conflict: control_qubit1 {control_qubit1} control_qubit2 {control_qubit2} target_qubit {target_qubit}")
    else:
        raise ValueError("Qubit index out of range")

ccx(control_qubit1: int, control_qubit2: int, target_qubit: int) -> QuantumCircuit ¤

Add CCX gate.

Parameters:

Name Type Description Default
control_qubit1 int

The qubit used as the first control.

required
control_qubit2 int

The qubit used as the second control.

required
target_qubit int

The qubit targeted by the gate.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
def ccx(self,control_qubit1:int,control_qubit2:int,target_qubit:int) -> 'QuantumCircuit':
    """Add CCX gate.

    Args:
        control_qubit1 (int): The qubit used as the first control.
        control_qubit2 (int): The qubit used as the second control.
        target_qubit (int): The qubit targeted by the gate.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    qubits0 = [control_qubit1,control_qubit2,target_qubit]
    if max(qubits0) < self.nqubits:
        if len(set(qubits0)) == 3:
            self.gates.append(('ccx',control_qubit1,control_qubit2,target_qubit))
            self._add_qubits(*qubits0)
        else:
            raise ValueError(f"Qubit index conflict: control_qubit1 {control_qubit1} control_qubit2 {control_qubit2} target_qubit {target_qubit}")
    else:
        raise ValueError("Qubit index out of range")

cswap(control_qubit: int, target_qubit1: int, target_qubit2: int) -> QuantumCircuit ¤

Add CSWAP gate.

Parameters:

Name Type Description Default
control_qubit int

The qubit used as control.

required
target_qubit1 int

The qubit targeted by the gate.

required
target_qubit2 int

The qubit targeted by the gate.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
def cswap(self,control_qubit:int,target_qubit1:int,target_qubit2:int) -> 'QuantumCircuit':
    """Add CSWAP gate.

    Args:
        control_qubit (int): The qubit used as control.
        target_qubit1 (int): The qubit targeted by the gate.
        target_qubit2 (int): The qubit targeted by the gate.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    qubits0 = [control_qubit,target_qubit1,target_qubit2]
    if max(qubits0) < self.nqubits:
        if len(set(qubits0)) == 3:
            self.gates.append(('cswap',control_qubit,target_qubit1,target_qubit2))
            self._add_qubits(*qubits0)
        else:
            raise ValueError(f"Qubit index conflict: control_qubit1 {control_qubit} control_qubit2 {target_qubit1} target_qubit {target_qubit2}")
    else:
        raise ValueError("Qubit index out of range")

p(theta: float, qubit: int) -> QuantumCircuit ¤

Add a Phase gate.

Parameters:

Name Type Description Default
theta float

The rotation angle of the gate.

required
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
def p(self, theta: float, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a Phase gate.

    Args:
        theta (float): The rotation angle of the gate.
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('p', theta, qubit))
        self._add_qubits(qubit)
        if isinstance(theta,str):
            self.params_value[theta] = theta
    else:
        raise ValueError("Qubit index out of range")

r(theta: float, phi: float, qubit: int) -> QuantumCircuit ¤

Add a R gate.

\[ R(\theta,\phi) = e^{-i\frac{\theta}{2}(\cos{\phi x}+\sin{\phi y})} = \begin{bmatrix} \cos(\frac{\theta}{2}) & -i e^{-i\phi}\sin(\frac{\theta}{2}) \\ -i e^{i\phi}\sin(\frac{\theta}{2}) & \cos(\frac{\theta}{2}) \end{bmatrix} \]

Parameters:

Name Type Description Default
theta float

The rotation angle of the gate.

required
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
def r(self, theta: float, phi:float, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a R gate.

    $$
    R(\theta,\phi) = e^{-i\frac{\theta}{2}(\cos{\phi x}+\sin{\phi y})} = \begin{bmatrix}
     \cos(\frac{\theta}{2})             & -i e^{-i\phi}\sin(\frac{\theta}{2}) \\
     -i e^{i\phi}\sin(\frac{\theta}{2}) & \cos(\frac{\theta}{2})      
    \end{bmatrix}
    $$

    Args:
        theta (float): The rotation angle of the gate.
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('r', theta, phi, qubit))
        self._add_qubits(qubit)
        if isinstance(theta,str):
            self.params_value[theta] = theta
        if isinstance(phi,str):
            self.params_value[phi] = phi
    else:
        raise ValueError("Qubit index out of range")

u(theta: float, phi: float, lamda: float, qubit: int) -> QuantumCircuit ¤

Add a U3 gate.

The U3 gate is a single-qubit gate with the following matrix representation:

\[ U3(\theta, \phi, \lambda) = \begin{bmatrix} \cos(\theta/2) & -e^{i\lambda} \sin(\theta/2) \\ e^{i\phi} \sin(\theta/2) & e^{i(\phi + \lambda)} \cos(\theta/2) \end{bmatrix} \]

Parameters:

Name Type Description Default
theta float

The rotation angle of the gate.

required
phi float

The rotation angle of the gate.

required
lamda float

The rotation angle of the gate.

required
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
def u(self, theta: float, phi: float, lamda: float, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a U3 gate.

    The U3 gate is a single-qubit gate with the following matrix representation:

    $$
    U3(\theta, \phi, \lambda) = \begin{bmatrix}
        \cos(\theta/2) & -e^{i\lambda} \sin(\theta/2) \\
        e^{i\phi} \sin(\theta/2) & e^{i(\phi + \lambda)} \cos(\theta/2)
        \end{bmatrix}
    $$

    Args:
        theta (float): The rotation angle of the gate.
        phi (float): The rotation angle of the gate.
        lamda (float): The rotation angle of the gate.
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('u', theta, phi, lamda, qubit))
        self._add_qubits(qubit)
        if isinstance(theta,str):
            self.params_value[theta] = theta
        if isinstance(phi,str):
            self.params_value[phi] = phi
        if isinstance(lamda,str):
            self.params_value[lamda] = lamda
    else:
        raise ValueError("Qubit index out of range")

u3(theta: float, phi: float, lamda: float, qubit: int) -> QuantumCircuit ¤

Add a U3 gate.

The U3 gate is a single-qubit gate with the following matrix representation:

\[ U3(\theta, \phi, \lambda) = \begin{bmatrix} \cos(\theta/2) & -e^{i\lambda} \sin(\theta/2) \\ e^{i\phi} \sin(\theta/2) & e^{i(\phi + \lambda)} \cos(\theta/2) \end{bmatrix} \]

Parameters:

Name Type Description Default
theta float

The rotation angle of the gate.

required
phi float

The rotation angle of the gate.

required
lamda float

The rotation angle of the gate.

required
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
def u3(self, theta: float, phi: float, lamda: float, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a U3 gate.

    The U3 gate is a single-qubit gate with the following matrix representation:

    $$
    U3(\theta, \phi, \lambda) = \begin{bmatrix}
        \cos(\theta/2) & -e^{i\lambda} \sin(\theta/2) \\
        e^{i\phi} \sin(\theta/2) & e^{i(\phi + \lambda)} \cos(\theta/2)
        \end{bmatrix}
    $$

    Args:
        theta (float): The rotation angle of the gate.
        phi (float): The rotation angle of the gate.
        lamda (float): The rotation angle of the gate.
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.u(theta, phi, lamda, qubit)
        self._add_qubits(qubit)
        if isinstance(theta,str):
            self.params_value[theta] = theta
        if isinstance(phi,str):
            self.params_value[phi] = phi
        if isinstance(lamda,str):
            self.params_value[lamda] = lamda
    else:
        raise ValueError("Qubit index out of range")   

rx(theta: float, qubit: int) -> QuantumCircuit ¤

Add a RX gate.

Parameters:

Name Type Description Default
theta float

The rotation angle of the gate.

required
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
def rx(self, theta: float, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a RX gate.

    Args:
        theta (float): The rotation angle of the gate.
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('rx', theta, qubit))
        self._add_qubits(qubit)
        if isinstance(theta,str):
            self.params_value[theta] = theta
    else:
        raise ValueError("Qubit index out of range")

ry(theta: float, qubit: int) -> QuantumCircuit ¤

Add a RY gate.

Parameters:

Name Type Description Default
theta (float

The rotation angle of the gate.

required
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
def ry(self, theta: float, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a RY gate.

    Args:
        theta (float: The rotation angle of the gate.
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('ry', theta, qubit))
        self._add_qubits(qubit)
        if isinstance(theta,str):
            self.params_value[theta] = theta
    else:
        raise ValueError("Qubit index out of range")

rz(theta: float, qubit: int) -> QuantumCircuit ¤

Add a RZ gate.

Parameters:

Name Type Description Default
theta float

The rotation angle of the gate.

required
qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
def rz(self, theta: float, qubit: int) -> 'QuantumCircuit':
    r"""
    Add a RZ gate.

    Args:
        theta (float): The rotation angle of the gate.
        qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('rz', theta, qubit))
        self._add_qubits(qubit)
        if isinstance(theta,str):
            self.params_value[theta] = theta
    else:
        raise ValueError("Qubit index out of range")

rxx(theta: float, qubit1: int, qubit2: int) -> QuantumCircuit ¤

Add a RXX gate.

\[ Rxx(\theta) = e^{-i\frac{\theta}{2}X\otimes X} = \begin{bmatrix} \cos(\frac{\theta}{2}) & 0 & 0 & -i\sin(\frac{\theta}{2}) \\ 0 & \cos(\frac{\theta}{2}) & -i\sin(\frac{\theta}{2}) & 0 \\ 0 & -i\sin(\frac{\theta}{2}) & \cos(\frac{\theta}{2}) & 0 \\ -i\sin(\frac{\theta}{2}) & 0 & 0 & \cos(\frac{\theta}{2}) \end{bmatrix}. \]

Parameters:

Name Type Description Default
theta float

The rotation angle of the gate.

required
qubit1 int

The qubit to apply the gate to.

required
qubit2 int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
def rxx(self, theta: float, qubit1: int, qubit2:int) -> 'QuantumCircuit':
    r"""
    Add a RXX gate.

    $$
    Rxx(\theta) = e^{-i\frac{\theta}{2}X\otimes X} = 
    \begin{bmatrix}
     \cos(\frac{\theta}{2})  & 0 & 0 & -i\sin(\frac{\theta}{2}) \\
     0 & \cos(\frac{\theta}{2}) & -i\sin(\frac{\theta}{2}) & 0 \\
     0 & -i\sin(\frac{\theta}{2}) & \cos(\frac{\theta}{2}) & 0 \\
     -i\sin(\frac{\theta}{2}) & 0 & 0 & \cos(\frac{\theta}{2})
    \end{bmatrix}.
    $$

    Args:
        theta (float): The rotation angle of the gate.
        qubit1 (int): The qubit to apply the gate to.
        qubit2 (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if max(qubit1, qubit2) < self.nqubits:
        if qubit1 != qubit2:
            self.gates.append(('rxx', theta, qubit1, qubit2))
            self._add_qubits(qubit1,qubit2)
            if isinstance(theta,str):
                self.params_value[theta] = theta
        else:
            raise ValueError(f"Qubit index conflict: qubit1 and qubit2 are both {qubit1}")
    else:
        raise ValueError("Qubit index out of range")

ryy(theta: float, qubit1: int, qubit2: int) -> QuantumCircuit ¤

Add a RYY gate.

\[ Ryy(\theta) = e^{-i\frac{\theta}{2}Y\otimes Y} = \begin{bmatrix} \cos(\frac{\theta}{2}) & 0 & 0 & i\sin(\frac{\theta}{2}) \\ 0 & \cos(\frac{\theta}{2}) & -i\sin(\frac{\theta}{2}) & 0 \\ 0 & -i\sin(\frac{\theta}{2}) & \cos(\frac{\theta}{2}) & 0 \\ i\sin(\frac{\theta}{2}) & 0 & 0 & \cos(\frac{\theta}{2}) \end{bmatrix}. \]

Parameters:

Name Type Description Default
theta float

The rotation angle of the gate.

required
qubit1 int

The qubit to apply the gate to.

required
qubit2 int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
def ryy(self, theta: float, qubit1: int, qubit2:int) -> 'QuantumCircuit':
    r"""
    Add a RYY gate.

    $$
    Ryy(\theta) = e^{-i\frac{\theta}{2}Y\otimes Y} = 
    \begin{bmatrix}
     \cos(\frac{\theta}{2})  & 0 & 0 & i\sin(\frac{\theta}{2}) \\
     0 & \cos(\frac{\theta}{2}) & -i\sin(\frac{\theta}{2}) & 0 \\
     0 & -i\sin(\frac{\theta}{2}) & \cos(\frac{\theta}{2}) & 0 \\
     i\sin(\frac{\theta}{2}) & 0 & 0 & \cos(\frac{\theta}{2})
    \end{bmatrix}.
    $$

    Args:
        theta (float): The rotation angle of the gate.
        qubit1 (int): The qubit to apply the gate to.
        qubit2 (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if max(qubit1, qubit2) < self.nqubits:
        if qubit1 != qubit2:
            self.gates.append(('ryy', theta, qubit1, qubit2))
            self._add_qubits(qubit1, qubit2)
            if isinstance(theta, str):
                self.params_value[theta] = theta
        else:
            raise ValueError(f"Qubit index conflict: qubit1 and qubit2 are both {qubit1}")
    else:
        raise ValueError("Qubit index out of range")

rzz(theta: float, qubit1: int, qubit2: int) -> QuantumCircuit ¤

Add a RZZ gate.

\[ Rzz(\theta) = e^{-i\frac{\theta}{2}Z\otimes Z} = \begin{bmatrix} e^{-i\frac{\theta}{2}} & 0 & 0 & 0 \\ 0 & e^{i\frac{\theta}{2}} & 0 & 0 \\ 0 & 0 & e^{i\frac{\theta}{2}} & 0 \\ 0 & 0 & 0 & e^{-i\frac{\theta}{2}} \end{bmatrix}. \]

Parameters:

Name Type Description Default
theta float

The rotation angle of the gate.

required
qubit1 int

The qubit to apply the gate to.

required
qubit2 int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
def rzz(self, theta: float, qubit1: int, qubit2:int) -> 'QuantumCircuit':
    r"""
    Add a RZZ gate.

    $$
    Rzz(\theta) = e^{-i\frac{\theta}{2}Z\otimes Z} = 
    \begin{bmatrix}
     e^{-i\frac{\theta}{2}}  & 0 & 0 & 0 \\
     0 & e^{i\frac{\theta}{2}} & 0 & 0 \\
     0 & 0 & e^{i\frac{\theta}{2}} & 0 \\
     0 & 0 & 0 & e^{-i\frac{\theta}{2}}
    \end{bmatrix}.
    $$

    Args:
        theta (float): The rotation angle of the gate.
        qubit1 (int): The qubit to apply the gate to.
        qubit2 (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if max(qubit1, qubit2) < self.nqubits:
        if qubit1 != qubit2:
            self.gates.append(('rzz', theta, qubit1, qubit2))
            self._add_qubits(qubit1,qubit2)
            if isinstance(theta,str):
                self.params_value[theta] = theta
        else:
            raise ValueError(f"Qubit index conflict: qubit1 and qubit2 are both {qubit1}")
    else:
        raise ValueError("Qubit index out of range")

cp(theta: float, control_qubit: int, target_qubit: int) -> QuantumCircuit ¤

Add a Cphase gate.

\[ Rzz(\theta) = I \otimes |0\rangle\langle 0| + P \otimes |1\rangle\langle 1| = \begin{bmatrix} 1 & 0 & 0 & 0 \\ 0 & 1 & 0 & 0 \\ 0 & 0 & 1 & 0 \\ 0 & 0 & 0 & e^{i\theta} \end{bmatrix}. \]

Parameters:

Name Type Description Default
theta float

The rotation angle of the gate.

required
control_qubit int

The qubit to apply the gate to.

required
target_qubit int

The qubit to apply the gate to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
def cp(self, theta: float, control_qubit: int, target_qubit:int) -> 'QuantumCircuit':
    r"""
    Add a Cphase gate.

    $$
    Rzz(\theta) = I \otimes |0\rangle\langle 0| + P \otimes |1\rangle\langle 1| = 
    \begin{bmatrix}
     1  & 0 & 0 & 0 \\
     0 & 1 & 0 & 0 \\
     0 & 0 & 1 & 0 \\
     0 & 0 & 0 & e^{i\theta}
    \end{bmatrix}.
    $$

    Args:
        theta (float): The rotation angle of the gate.
        control_qubit (int): The qubit to apply the gate to.
        target_qubit (int): The qubit to apply the gate to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if max(control_qubit, target_qubit) < self.nqubits:
        if control_qubit != target_qubit:
            self.gates.append(('cp', theta, control_qubit, target_qubit))
            self._add_qubits(control_qubit, target_qubit)
            if isinstance(theta,str):
                self.params_value[theta] = theta
        else:
            raise ValueError(f"Qubit index conflict: qubit1 and qubit2 are both {control_qubit}")
    else:
        raise ValueError("Qubit index out of range")

mapping_to_others(mapping: dict) -> QuantumCircuit ¤

Map current qubit indices to new indices.

Parameters:

Name Type Description Default
mapping dict

A dictionary specifying the mapping from current qubit indices to target indices.

required

Returns:

Name Type Description
dict QuantumCircuit

A dictionary with updated qubit index mapping.

Source code in quark/circuit/quantumcircuit.py
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
def mapping_to_others(self,mapping:dict) -> 'QuantumCircuit':
    """Map current qubit indices to new indices.

    Args:
        mapping (dict): A dictionary specifying the mapping from current qubit indices to target indices.

    Returns:
        dict: A dictionary with updated qubit index mapping.
    """
    assert(len(self.qubits) == len(mapping))
    new = []
    for gate_info in self.gates:
        gate = gate_info[0]
        if gate in one_qubit_gates_available.keys():
            new.append((gate,mapping[gate_info[1]]))
        elif gate in two_qubit_gates_available.keys():
            new.append((gate,*[mapping[q] for q in gate_info[1:]]))
        elif gate in one_qubit_parameter_gates_available.keys():
            new.append((gate,*gate_info[1:-1],mapping[gate_info[-1]]))
        elif gate in two_qubit_parameter_gates_available.keys():
            new.append((gate,gate_info[1],*[mapping[q] for q in gate_info[2:]]))
        elif gate in three_qubit_gates_available.keys():
            new.append((gate,*[mapping[q] for q in gate_info[1:]]))
        elif gate in functional_gates_available.keys():
            if gate == 'measure':
                qubitlst = [mapping[q] for q in gate_info[1]]
                cbitlst = gate_info[2]
                new.append((gate,qubitlst,cbitlst))
            elif gate == 'barrier':
                qubitlst = [mapping[q] for q in gate_info[1] if q in mapping] 
                new.append((gate,tuple(qubitlst)))
            elif gate == 'delay':
                qubitlst = [mapping[q] for q in gate_info[-1]]
                new.append((gate,gate_info[1],tuple(qubitlst)))
            elif gate == 'reset':
                qubit0 = mapping[gate_info[1]]
                new.append((gate,qubit0))
    self.nqubits = max(mapping.values())+1
    self.qubits = list(sorted(mapping.values()))
    self.gates = new
    return self

u3_for_unitary(unitary: np.ndarray, qubit: int) ¤

Decomposes a 2x2 unitary matrix into a U3 gate and applies it to a specified qubit.

Parameters:

Name Type Description Default
unitary ndarray

A 2x2 unitary matrix.

required
qubit int

The qubit to apply the gate to.

required
Source code in quark/circuit/quantumcircuit.py
926
927
928
929
930
931
932
933
934
935
936
937
938
def u3_for_unitary(self, unitary: np.ndarray, qubit: int):
    r"""
    Decomposes a 2x2 unitary matrix into a U3 gate and applies it to a specified qubit.

    Args:
        unitary (np.ndarray): A 2x2 unitary matrix.
        qubit (int): The qubit to apply the gate to.
    """
    assert(unitary.shape == (2,2))
    assert(qubit < self.nqubits)
    theta,phi,lamda,phase = u3_decompose(unitary)
    self.gates.append(('u', theta, phi, lamda, qubit))
    self._add_qubits(qubit)

zyz_for_unitary(unitary: np.ndarray, qubit: int) -> QuantumCircuit ¤

Decomposes a 2x2 unitary matrix into Rz-Ry-Rz gate sequence and applies it to a specified qubit.

Parameters:

Name Type Description Default
unitary ndarray

A 2x2 unitary matrix.

required
qubit int

The qubit to apply the gate sequence to.

required
Source code in quark/circuit/quantumcircuit.py
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
def zyz_for_unitary(self, unitary: np.ndarray, qubit:int) -> 'QuantumCircuit':
    r"""
    Decomposes a 2x2 unitary matrix into Rz-Ry-Rz gate sequence and applies it to a specified qubit.

    Args:
        unitary (np.ndarray): A 2x2 unitary matrix.
        qubit (int): The qubit to apply the gate sequence to.
    """
    assert(unitary.shape == (2,2))
    assert(qubit < self.nqubits)
    theta, phi, lamda, alpha = zyz_decompose(unitary)
    self.gates.append(('rz', lamda, qubit))
    self.gates.append(('ry', theta, qubit))
    self.gates.append(('rz', phi, qubit))
    self._add_qubits(qubit)

kak_for_unitary(unitary: np.ndarray, qubit1: int, qubit2: int) -> QuantumCircuit ¤

Decomposes a 4 x 4 unitary matrix into a sequence of CZ and U3 gates using KAK decomposition and applies them to the specified qubits.

Parameters:

Name Type Description Default
unitary ndarray

A 4 x 4 unitary matrix.

required
qubit1 int

The first qubit to apply the gates to.

required
qubit2 int

The second qubit to apply the gates to.

required
Source code in quark/circuit/quantumcircuit.py
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
def kak_for_unitary(self, unitary: np.ndarray, qubit1: int, qubit2: int) -> 'QuantumCircuit':
    r"""
    Decomposes a 4 x 4 unitary matrix into a sequence of CZ and U3 gates using KAK decomposition and applies them to the specified qubits.

    Args:
        unitary (np.ndarray): A 4 x 4 unitary matrix.
        qubit1 (int): The first qubit to apply the gates to.
        qubit2 (int): The second qubit to apply the gates to.
    """
    assert(unitary.shape == (4,4))
    assert(qubit1 != qubit2)
    rots1, rots2 = kak_decompose(unitary)
    self.u3_for_unitary(rots1[0], qubit1)
    self.u3_for_unitary(h_mat @ rots2[0], qubit2)
    self.gates.append(('cz', qubit1, qubit2))
    self.u3_for_unitary(rots1[1], qubit1)
    self.u3_for_unitary(h_mat @ rots2[1] @ h_mat, qubit2)
    self.gates.append(('cz', qubit1, qubit2))
    self.u3_for_unitary(rots1[2], qubit1)
    self.u3_for_unitary(h_mat @ rots2[2] @ h_mat, qubit2)
    self.gates.append(('cz', qubit1, qubit2))        
    self.u3_for_unitary(rots1[3], qubit1)
    self.u3_for_unitary(rots2[3] @ h_mat, qubit2)
    self._add_qubits(qubit1,qubit2)

reset(qubit: int) -> QuantumCircuit ¤

Add reset to qubit.

Parameters:

Name Type Description Default
qubit int

The qubit to apply the instruction to.

required

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
def reset(self, qubit: int) -> 'QuantumCircuit':
    r"""
    Add reset to qubit.

    Args:
        qubit (int): The qubit to apply the instruction to.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if qubit < self.nqubits:
        self.gates.append(('reset', qubit))
        self._add_qubits(qubit)
    else:
        raise ValueError("Qubit index out of range")

delay(duration: int | float, *qubits: tuple[int], unit='s') -> QuantumCircuit ¤

Adds delay to qubits, the unit is s.

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
def delay(self,duration:int|float, *qubits:tuple[int],unit='s') -> 'QuantumCircuit':
    r"""
    Adds delay to qubits, the unit is s.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    # convert 'ns' 'ms' 'us' to 's
    if unit == 'ns':
        duration = duration * 1e-9
    elif unit == 'us':
        duration = duration * 1e-6
    elif unit =='ms':
        duration = duration * 1e-3

    if not qubits: # it will add barrier for all qubits
        self.gates.append(('delay', duration, tuple(self.qubits)))
    else:
        if max(qubits) < self.nqubits:
            self.gates.append(('delay', duration, qubits))
            self._add_qubits(*qubits)
        else:
            raise ValueError("Qubit index out of range")

barrier(*qubits: tuple[int]) -> QuantumCircuit ¤

Adds barrier to qubits.

Raises:

Type Description
ValueError

If qubit out of circuit range.

Source code in quark/circuit/quantumcircuit.py
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
def barrier(self,*qubits: tuple[int]) -> 'QuantumCircuit':
    r"""
    Adds barrier to qubits.

    Raises:
        ValueError: If qubit out of circuit range.
    """
    if not qubits: # it will add barrier for all qubits
        self.gates.append(('barrier', tuple(self.qubits)))
    else:
        if max(qubits) < self.nqubits:
            if len(set(qubits)) == len(qubits):
                self.gates.append(('barrier', qubits))
            else:
                raise(ValueError(f'Qubit index conflict. {qubits}'))
        else:
            raise ValueError("Qubit index out of range")

remove_barrier() -> QuantumCircuit ¤

Remove all barrier gates from the quantum circuit.

Returns:

Name Type Description
QuantumCircuit QuantumCircuit

The updated quantum circuit with all barrier gates removed.

Source code in quark/circuit/quantumcircuit.py
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
def remove_barrier(self) -> 'QuantumCircuit':
    r"""
    Remove all barrier gates from the quantum circuit.

    Returns:
        QuantumCircuit: The updated quantum circuit with all barrier gates removed.
    """
    new = []
    for gate_info in self.gates:
        gate  = gate_info[0]
        if gate != 'barrier':
            new.append(gate_info)
    self.gates = new
    return self

remove_gate(gate_name: str) ¤

Remove specified gates from the circuit.

Returns:

Name Type Description
QuantumCircuit

The updated quantum circuit with specified gates removed.

Source code in quark/circuit/quantumcircuit.py
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
def remove_gate(self,gate_name:str):
    r"""
    Remove specified gates from the circuit.

    Returns:
        QuantumCircuit: The updated quantum circuit with specified gates removed.

    """
    new = []
    for gate_info in self.gates:
        gate  = gate_info[0]
        if gate != gate_name:
            new.append(gate_info)
    self.gates = new
    return self

count_gate(gate_name: str) -> int ¤

Count target gates in this QuantumCircuit.

Returns:

Name Type Description
int int

The number of gates.

Source code in quark/circuit/quantumcircuit.py
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
def count_gate(self,gate_name:str) -> int:
    r"""Count target gates in this QuantumCircuit.

    Returns:
        int: The number of gates.
    """
    num = 0
    for gate_info in self.gates:
        gate  = gate_info[0]
        if gate == gate_name:
            num += 1
        else:
            continue
    return num

measure(qubitlst: int | Iterable[int], cbitlst: int | Iterable[int]) -> QuantumCircuit ¤

Adds measurement to qubits.

Parameters:

Name Type Description Default
qubitlst int | list

Qubit(s) to measure.

required
cbitlst int | list

Classical bit(s) to place the measure results in.

required
Source code in quark/circuit/quantumcircuit.py
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
def measure(self,qubitlst: int | Iterable[int], cbitlst: int | Iterable[int]) -> 'QuantumCircuit':
    r"""Adds measurement to qubits.

    Args:
        qubitlst (int | list): Qubit(s) to measure.
        cbitlst (int | list): Classical bit(s) to place the measure results in.
    """
    if isinstance(qubitlst,Iterable):
        qubitlst = list(qubitlst)
        cbitlst = list(cbitlst)
        if (len(set(qubitlst)) == len(qubitlst) and 
            len(set(cbitlst)) == len(cbitlst) and 
            len(qubitlst) == len(cbitlst)):
            self.gates.append(('measure', qubitlst,cbitlst))
            self._add_qubits(*qubitlst)
        else:
            raise(ValueError(f'Qubit or Cbits index conflict. {qubitlst} {cbitlst}'))
    elif isinstance(qubitlst,int):
        if qubitlst < self.nqubits:
            self.gates.append(('measure', [qubitlst], [cbitlst]))
            self._add_qubits(qubitlst)
        else:
            raise ValueError("Qubit index out of range")
    else:
        raise(ValueError(''))

measure_all() -> QuantumCircuit ¤

Adds measurement to all qubits.

Source code in quark/circuit/quantumcircuit.py
1111
1112
1113
1114
1115
1116
1117
def measure_all(self) -> 'QuantumCircuit':
    r"""
    Adds measurement to all qubits.
    """
    qubitlst = [i for i in self.qubits]
    cbitlst = [i for i in range(len(qubitlst))]
    self.gates.append(('measure', qubitlst,cbitlst))

draw(width: int = 4) -> None ¤

Draw the quantum circuit.

Parameters:

Name Type Description Default
width int

The width between gates. Defaults to 4.

4
Source code in quark/circuit/quantumcircuit.py
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
def draw(self, width: int = 4) -> None:
    r"""
    Draw the quantum circuit.

    Args:
        width (int, optional): The width between gates. Defaults to 4.
    """
    lines1,lines_use = add_gates_to_lines(self.nqubits,self.ncbits,self.gates,self.params_value, width = width)
    fline = str()
    for line in lines1:
        fline += '\n'
        fline += line

    formatted_string = fline.replace("\n", "<br>").replace(" ", "&nbsp;")
    html_content = f'<div style="overflow-x: auto; white-space: nowrap; font-family: consolas;">{formatted_string}</div>'
    display(HTML(html_content))

draw_simply(width: int = 4) -> None ¤

Draw a simplified quantum circuit diagram.

This method visualizes the quantum circuit by displaying only the qubits that have gates applied to them, omitting any qubits without active gates. The result is a cleaner, more concise circuit diagram.

Parameters:

Name Type Description Default
width int

The width between gates. Defaults to 4.

4
Source code in quark/circuit/quantumcircuit.py
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
def draw_simply(self, width: int = 4) -> None:
    r"""
    Draw a simplified quantum circuit diagram.

    This method visualizes the quantum circuit by displaying only the qubits that have gates applied to them,
    omitting any qubits without active gates. The result is a cleaner, more concise circuit diagram.

    Args:
        width (int, optional): The width between gates. Defaults to 4.
    """
    lines1,lines_use = add_gates_to_lines(self.nqubits,self.ncbits,self.gates,self.params_value, width=width)
    fline = str()
    for idx in range(2 * self.nqubits):
        if idx in lines_use:
            fline += '\n'
            fline += lines1[idx]
    for idx in range(2 * self.nqubits, len(lines1)):
        fline += '\n'
        fline += lines1[idx]

    formatted_string = fline.replace("\n", "<br>").replace(" ", "&nbsp;")
    html_content = f'<div style="overflow-x: auto; white-space: nowrap; font-family: consolas;">{formatted_string}</div>'
    display(HTML(html_content))

generate_ghz_state(nqubits: int) -> QuantumCircuit ¤

Produce a GHZ state on n qubits.

Parameters:

Name Type Description Default
nqubits int

The number of qubits. Must be >= 2.

required

Returns:

Name Type Description
QuantumCircuit QuantumCircuit

A quantum circuit representing the GHZ state.

Source code in quark/circuit/quantumcircuit.py
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def generate_ghz_state(nqubits: int) -> 'QuantumCircuit':
    r"""
    Produce a GHZ state on n qubits.

    Args:
        nqubits (int): The number of qubits. Must be >= 2.

    Returns:
        QuantumCircuit: A quantum circuit representing the GHZ state.
    """
    cir =  QuantumCircuit(nqubits)
    cir.h(0)
    for i in range(1,nqubits):
        cir.cx(0,i)
    return cir