Skip to content

quantumcircuit_helpers ¤

The module contains some tools for quantumcircuit.

Functions:

Name Description
is_multiple_of_pi

Determines if a given number is approximately a multiple of π (pi) within a given tolerance.

parse_openqasm2_to_gates

Parse gate information from an input OpenQASM 2.0 string, and update gates, supporting multiple registers.

parse_openqasm2_to_gates_dump

Parse gate information from an input OpenQASM 2.0 string, and update gates

parse_qlisp_to_gates

Parse gate information from an input qlisp list.

initialize_lines

Initialize a blank circuit.

generate_gates_layerd

Assign gates to their respective layers loosely.

format_gates_layerd

Unify the width of each layer's gate strings

add_gates_to_lines

Add gates to lines.

is_multiple_of_pi(n, tolerance: float = 1e-09) -> str ¤

Determines if a given number is approximately a multiple of π (pi) within a given tolerance.

Parameters:

Name Type Description Default
n float

The number to be checked.

required
tolerance float

The allowable difference between the number and a multiple of π. Defaults to 1e-9.

1e-09

Returns:

Name Type Description
str str

A string representation of the result. If the number is close to a multiple of π, it returns a string in the form of "kπ" where k is a rounded multiplier (e.g., "2π" for 2 x π). If n is approximately 0, it returns "0.0". Otherwise, it returns a string representation of the number rounded to three decimal places.

Source code in quark/circuit/quantumcircuit_helpers.py
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
def is_multiple_of_pi(n, tolerance: float = 1e-9) -> str:
    r"""
    Determines if a given number is approximately a multiple of π (pi) within a given tolerance.

    Args:
        n (float): The number to be checked.
        tolerance (float, optional): The allowable difference between the number and a multiple of π. Defaults to 1e-9.

    Returns:
        str: A string representation of the result. If the number is close to a multiple of π, 
             it returns a string in the form of "kπ" where k is a rounded multiplier (e.g., "2π" for 2 x π).
             If n is approximately 0, it returns "0.0".
             Otherwise, it returns a string representation of the number rounded to three decimal places.
    """
    result = n / np.pi
    aprox = round(result,2)
    if abs(result - aprox) < tolerance:
        if np.allclose(aprox, 0.0):
            return str(0.0)
        else:
            expression = f'{aprox}π'
            return expression
    else:
        return str(round(n,3))

parse_openqasm2_to_gates(openqasm2_str) -> None ¤

Parse gate information from an input OpenQASM 2.0 string, and update gates, supporting multiple registers.

Source code in quark/circuit/quantumcircuit_helpers.py
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
def parse_openqasm2_to_gates(openqasm2_str) -> None:
    r"""
    Parse gate information from an input OpenQASM 2.0 string, and update gates, supporting multiple registers.
    """
    qregs_used,cregs_used,openqasm2_str = parse_openqasm2_regs(openqasm2_str)
    if len(qregs_used) >1 or len(cregs_used)>1:
        print('Multiple registers detected. For subsequent compilation, the program will merge them. The mapping is as follows:')
    qreg_map = generate_reg_map(qregs_used,'Qubit')
    creg_map = generate_reg_map(cregs_used,'Cbit')

    custom_gates,openqasm2_str = parse_openqasm2_custom_gates(openqasm2_str)

    new = []
    qubit_used = []
    cbit_used = []
    clean_qasm = openqasm2_str.strip() 
    for line in clean_qasm.splitlines():
        if line == '':
            continue
        elif set(line) == {'\t'}: # check tab
            continue
        line_clear = line.split('//')[0].strip()
        gate,params_str,qregs_str = sparse_gate_params_qregs(line_clear)
        #print(gate,params_str,qregs_str)
        if params_str is not None:
            params = [parse_expression(p) for p in params_str.split(',')]
        else:
            params = []
        positions = get_positions_list(gate,qregs_str,qreg_map,creg_map)
        if gate in one_qubit_gates_available.keys():
            qubits = [p for pp in positions for p in pp]
            for q in qubits:
                new.append((gate,q))
                qubit_used.append(q)
        elif gate in two_qubit_gates_available.keys():
            if len(positions) != 2:
                raise ValueError(f'{gate} takes 2 quantum arguments, but got {len(positions)}.')
            if len(positions[0]) != len(positions[1]):
                raise ValueError(f'{gate} takes 2 different quantum arguments length.')
            for idx in range(len(positions[0])):
                new.append((gate,positions[0][idx],positions[1][idx]))
                qubit_used.append(positions[0][idx])
                qubit_used.append(positions[1][idx])
        elif gate in three_qubit_gates_available.keys():
            if len(positions) != 3:
                raise ValueError(f'{gate} takes 3 quantum arguments, but got {len(positions)}.')
            if len(positions[0]) != len(positions[1]) or len(positions[0]) != len(positions[2]):
                raise ValueError(f'{gate} takes 3 different quantum arguments length.')
            for idx in range(len(positions[0])):
                new.append((gate,positions[0][idx],positions[1][idx],positions[2][idx]))
                qubit_used.append(positions[0][idx])
                qubit_used.append(positions[1][idx])
                qubit_used.append(positions[2][idx])        
        elif gate in one_qubit_parameter_gates_available.keys():
            qubits = [p for pp in positions for p in pp]
            if gate == 'u' or gate == 'u3':
                for q in qubits:
                    new.append(('u', params[0], params[1], params[2], q))
                    qubit_used.append(q)
            elif gate == 'r':
                for q in qubits:
                    new.append((gate, params[0], params[1], q))
                    qubit_used.append(q)
            else:
                for q in qubits:
                    new.append((gate, *params, q))
                    qubit_used.append(q)
        elif gate in ['u1','u2']:
            qubits = [p for pp in positions for p in pp]
            if gate == 'u1':
                for q in qubits:
                    new.append(('u', 0, 0, params[0], q))
                    qubit_used.append(q)
            elif gate == 'u2':
                for q in qubits:
                    new.append(('u', np.pi/2, params[0], params[1], q))
                    qubit_used.append(q)
        elif gate in two_qubit_parameter_gates_available.keys():
            if len(positions) != 2:
                raise ValueError(f'{gate} takes 2 quantum arguments, but got {len(positions)}.')
            if len(positions[0]) != len(positions[1]):
                raise ValueError(f'{gate} takes 2 different quantum arguments length.') 
            for idx in range(len(positions[0])):
                new.append((gate, *params, positions[0][idx], positions[1][idx]))
                qubit_used.append(positions[0][idx])
                qubit_used.append(positions[1][idx])
        elif gate in ['cu1']:
            if len(positions) != 2:
                raise ValueError(f'{gate} takes 2 quantum arguments, but got {len(positions)}.')
            if len(positions[0]) != len(positions[1]):
                raise ValueError(f'{gate} takes 2 different quantum arguments length.') 
            for idx in range(len(positions[0])):
                new.append(('cp', *params, positions[0][idx], positions[1][idx]))
                qubit_used.append(positions[0][idx])
                qubit_used.append(positions[1][idx])
        elif gate in ['delay']:
            qubits = [p for pp in positions for p in pp]
            for q in qubits:
                new.append((gate,*params,(q,)))
                qubit_used.append(q)
        elif gate in ['reset']:
            qubits = [p for pp in positions for p in pp]
            for q in qubits:
                new.append((gate,q))
                qubit_used.append(q)
        elif gate in ['barrier']:
            qubits = [p for pp in positions for p in pp]
            new.append((gate, tuple(qubits)))
            #qubit_used += list(qubits)
        elif gate in ['measure']:
            if len(positions[0]) != len(positions[1]):
                raise ValueError(f'{gate} takes 2 different quantum arguments length.') 
            for idx in range(len(positions[0])):
                new.append((gate, [positions[0][idx]], [positions[1][idx]])) 
                qubit_used.append(positions[0][idx])
                cbit_used.append(positions[1][idx])
        elif gate in ['OPENQASM','include','opaque','gate','qreg','creg','//']:
            continue
        elif gate in custom_gates.keys():
            positions_lengths = [len(position) for position in positions]
            if len(set(positions_lengths)) > 1:
                raise ValueError(f'custom gate {gate} sparse failer!' )
            for idx in range(len(positions[0])):
                qubits = [position[idx] for position in positions]
                params_qreg_dic = dict(zip(custom_gates[gate]['params_and_qregs'],params+qubits))
                new0 = []
                for gate0_info in custom_gates[gate]['definition']:
                    cc = []
                    for key in gate0_info[1:]:
                        if key in params_qreg_dic.keys():
                            cc.append(params_qreg_dic[key])
                        else:
                            if key.isdigit():
                                cc.append(int(key))
                            else:
                                cc.append(parse_expression(key))
                    new0.append(tuple([gate0_info[0]]+cc))
                new += new0
        elif gate is None:
            pass
        else:
            raise(ValueError(f"Sorry, an unrecognized OpenQASM 2.0 syntax {gate} was detected by quarkcircuit. Please contact the developer for assistance."))

    if cbit_used == []:
        cbit_used = [i for i in range(len(set(qubit_used)))]

    new_new = []
    for gate_info in new:
        if gate_info[0] == 'barrier':
            qubits = [q for q in gate_info[1] if q in qubit_used]
            if len(qubits) > 0:
                barrier_info = ('barrier',tuple(qubits))
                new_new.append(barrier_info)
        else:
            new_new.append(gate_info)
    return new_new,set(qubit_used),set(cbit_used)

parse_openqasm2_to_gates_dump(openqasm2_str) -> None ¤

Parse gate information from an input OpenQASM 2.0 string, and update gates

Source code in quark/circuit/quantumcircuit_helpers.py
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
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
591
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
625
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
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
def parse_openqasm2_to_gates_dump(openqasm2_str) -> None:
    r"""
    Parse gate information from an input OpenQASM 2.0 string, and update gates
    """
    qregs,cregs,_ = parse_openqasm2_regs(openqasm2_str)
    if len(qregs) >1 or len(cregs)>1:
        raise(ValueError(f"Sorry, currently only one quantum or classical register definition is supported"))

    custom_gates,openqasm2_str = parse_openqasm2_custom_gates(openqasm2_str)
    new = []
    qubit_used = []
    cbit_used = []
    clean_qasm = openqasm2_str.strip() 
    for line in clean_qasm.splitlines():
        if line == '':
            continue
        elif set(line) == {'\t'}: # check tab
            continue
        gate = line.split()[0].split('(')[0]
        position = [int(num) for num in re.findall(r"\[(\d+)\]", line)] 
        if gate in one_qubit_gates_available.keys():
            new.append((gate,position[0]))
            qubit_used.append(position[0])
        elif gate in two_qubit_gates_available.keys():
            new.append((gate,position[0],position[1]))
            qubit_used.append(position[0])
            qubit_used.append(position[1])
        elif gate in three_qubit_gates_available.keys():
            new.append((gate,position[0],position[1],position[2]))
            qubit_used.append(position[0])
            qubit_used.append(position[1])
            qubit_used.append(position[2])            
        elif gate in one_qubit_parameter_gates_available.keys():
            if gate == 'u' or gate == 'u3':
                params_str = re.search(r'\(([^)]+)\)', line).group(1).split(',')
                params = [parse_expression(i) for i in params_str]
                new.append(('u', params[0], params[1], params[2], position[-1]))
                qubit_used.append(position[-1])
            elif gate == 'r':
                params_str = re.search(r'\(([^)]+)\)', line).group(1).split(',')
                params = [parse_expression(i) for i in params_str]
                new.append((gate, params[0], params[1], position[-1]))
                qubit_used.append(position[-1])
            else:
                param_str = re.search(r'\(([^)]+)\)', line).group(1)
                param = parse_expression(param_str)
                new.append((gate, param, position[-1]))
                qubit_used.append(position[-1])   
        elif gate in ['u1','u2']:
            if gate == 'u1':
                params_str = re.search(r'\(([^)]+)\)', line).group(1).split(',')
                params = [parse_expression(i) for i in params_str]
                new.append(('u', 0, 0, params[0], position[-1]))
                qubit_used.append(position[-1])
            elif gate == 'u2':
                params_str = re.search(r'\(([^)]+)\)', line).group(1).split(',')
                params = [parse_expression(i) for i in params_str]
                new.append(('u', np.pi/2, params[0], params[1], position[-1]))
                qubit_used.append(position[-1])
        elif gate in two_qubit_parameter_gates_available.keys():
            param_str = re.search(r'\(([^)]+)\)', line).group(1)
            param = parse_expression(param_str)
            new.append((gate, param, position[-2], position[-1]))
            qubit_used.append(position[-2])
            qubit_used.append(position[-1])
        elif gate in ['cu1']:
            param_str = re.search(r'\(([^)]+)\)', line).group(1)
            param = parse_expression(param_str)
            new.append(('cp', param, position[-2], position[-1]))
            qubit_used.append(position[-2])
            qubit_used.append(position[-1])
        elif gate in ['delay']:
            param = float(re.search(r'\(([^)]+)\)', line).group(1))
            new.append((gate,param,(position[-1],)))
            qubit_used.append(position[-1])
        elif gate in ['reset']:
            new.append((gate,position[0]))
            qubit_used.append(position[0])
        elif gate in ['barrier']:
            if position == []:
                line0 = line.strip().rstrip(';')
                pattern = r"barrier\s+(.+?)"
                match = re.match(pattern, line0)
                q_name = match.groups()[0]
                if q_name == qregs[0][0]:
                    new.append((gate, tuple([i for i in range(qregs[0][1])]))) 
                else:
                    raise(ValueError(f"Sorry, an unrecognized OpenQASM 2.0 syntax {line} was detected by quarkcircuit."))
            else:
                new.append((gate, tuple(position)))
            #qubit_used += list(position)
        elif gate in ['measure']:
            if position == []:
                line0 = line.strip().rstrip(';')
                pattern = r"measure\s+(.+?)\s*->\s*(.+)"
                match = re.match(pattern, line0)
                left, right = match.groups()
                q_name = left.strip()
                c_name = right.strip()
                if q_name == qregs[0][0] and c_name == cregs[0][0] and qregs[0][1]==cregs[0][1]:
                    for q in range(qregs[0][1]):
                        new.append(('measure', [q], [q])) 
                else:
                    raise(ValueError(f"check qreg name {qregs[0][0]} and parse q_name {q_name} is consistent, \
                    \ncheck creg name {cregs[0][0]} and parse c_name {c_name} is consistent, \
                    \ncheck qregs size {qregs[0][1]} and cregs size {cregs[0][1]} is equal."))
            else:
                new.append((gate, [position[0]], [position[1]])) 
                qubit_used.append(position[0])
                cbit_used.append(position[1])
        elif gate in ['OPENQASM','include','opaque','gate','qreg','creg','//']:
            continue
        elif gate in custom_gates.keys():
            try:
                params_str = re.search(r'\(([^)]+)\)', line).group(1).split(',')
                params = [parse_expression(i) for i in params_str]
            except:
                params = []
            params_qreg_dic = dict(zip(custom_gates[gate]['params_and_qregs'],params+position))
            new0 = []
            for gate0_info in custom_gates[gate]['definition']:
                cc = []
                for key in gate0_info[1:]:
                    if key in params_qreg_dic.keys():
                        cc.append(params_qreg_dic[key])
                    else:
                        if key.isdigit():
                            cc.append(int(key))
                        else:
                            cc.append(parse_expression(key))
                new0.append(tuple([gate0_info[0]]+cc))
            new += new0
        else:
            raise(ValueError(f"Sorry, an unrecognized OpenQASM 2.0 syntax {gate} was detected by quarkcircuit. Please contact the developer for assistance."))

    if cbit_used == []:
        cbit_used = [i for i in range(len(set(qubit_used)))]
    return new,set(qubit_used),set(cbit_used)

parse_qlisp_to_gates(qlisp: list) -> tuple[list, list, list] ¤

Parse gate information from an input qlisp list.

Args: qlisp (list): qlisp

Returns: tuple[list, list, list]: A tuple containing: An gate information list. An qubit information list. An cbit information list.

Source code in quark/circuit/quantumcircuit_helpers.py
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
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
749
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
782
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 parse_qlisp_to_gates(qlisp: list) -> tuple[list, list, list]:
    r"""
    Parse gate information from an input qlisp list.

     Args:
        qlisp (list): qlisp

     Returns:
        tuple[list, list, list]: A tuple containing:
            An gate information list.
            An qubit information list.
            An cbit information list.
    """
    new = []
    qubit_used = []
    cbit_used = []
    for gate_info in qlisp:
        gate = gate_info[0]
        if gate in ['X', 'Y', 'Z', 'S', 'T', 'H']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append((gate.lower(), qubit0))
            qubit_used.append(qubit0)
        elif gate in ['I']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append(('id', qubit0))
            qubit_used.append(qubit0)
        elif gate in ['-S','-T']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append((gate[1].lower() + 'dg', qubit0))
            qubit_used.append(qubit0)
        elif gate in ['Z/2']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append(('s', qubit0))
            qubit_used.append(qubit0)
        elif gate in ['-Z/2']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append(('sdg', qubit0))
            qubit_used.append(qubit0)
        elif gate in ['X/2']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append(('rx',np.pi/2,qubit0))
            qubit_used.append(qubit0)
        elif gate in ['-X/2']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append(('rx',-np.pi/2,qubit0))
            qubit_used.append(qubit0)
        elif gate in ['Y/2']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append(('ry',np.pi/2,qubit0))
            qubit_used.append(qubit0)
        elif gate in ['-Y/2']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append(('ry',-np.pi/2, qubit0))
            qubit_used.append(qubit0)
        elif gate[0] in ['u3','U']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append(('u', gate[1], gate[2], gate[3], qubit0))
            qubit_used.append(qubit0)
        elif gate[0] in ['u1']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append(('p', gate[1], qubit0))  
            qubit_used.append(qubit0)      
        elif gate[0] in ['u2']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append(('u',np.pi/2, gate[1], gate[2],qubit0))  
            qubit_used.append(qubit0)
        elif gate[0] in ['R']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append(('r',np.pi/2, gate[1], qubit0))
            qubit_used.append(qubit0)
        #elif gate[0] in ['rfUnitary']:
        #    qubit0 = int(gate_info[1].split('Q')[1])
        #    new.append(('r', gate[1], gate[2], qubit0))
        elif gate[0] in ['CU']:
            qubit1 = int(gate_info[1][0].split('Q')[1])
            qubit2 = int(gate_info[1][1].split('Q')[1])
            new.append((gate[0].lower(),gate[1],qubit1,qubit2))
            qubit_used.append(qubit1)
            qubit_used.append(qubit2)
        elif gate in ['Cnot']:
            qubit1 = int(gate_info[1][0].split('Q')[1])
            qubit2 = int(gate_info[1][1].split('Q')[1])
            new.append(('cx', qubit1, qubit2))
            qubit_used.append(qubit1)
            qubit_used.append(qubit2)
        elif gate in ['CX','CY', 'CZ', 'SWAP']:
            qubit1 = int(gate_info[1][0].split('Q')[1])
            qubit2 = int(gate_info[1][1].split('Q')[1])
            new.append((gate.lower(), qubit1, qubit2))
            qubit_used.append(qubit1)
            qubit_used.append(qubit2)
        elif gate in ['CCZ','CCX','CSWAP']:
            qubit1 = int(gate_info[1][0].split('Q')[1])
            qubit2 = int(gate_info[1][1].split('Q')[1])
            qubit3 = int(gate_info[1][2].split('Q')[1])
            new.append((gate.lower(), qubit1, qubit2, qubit3))
            qubit_used.append(qubit1)
            qubit_used.append(qubit2) 
            qubit_used.append(qubit3)            
        elif gate in ['iSWAP']:
            qubit1 = int(gate_info[1][0].split('Q')[1])
            qubit2 = int(gate_info[1][1].split('Q')[1])
            new.append(('iswap', qubit1, qubit2))
            qubit_used.append(qubit1)
            qubit_used.append(qubit2)
        elif gate[0] in ['Rx', 'Ry', 'Rz', 'P']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append((gate[0].lower(), gate[1], qubit0))
            qubit_used.append(qubit0)
        elif gate in ['Reset']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append((gate.lower(), qubit0))
            qubit_used.append(qubit0)
        elif gate in ['Barrier']:
            qubitn = [int(istr.split('Q')[1]) for istr in gate_info[1]]
            new.append((gate.lower(), tuple(qubitn)))
            #qubit_used += qubitn
        elif gate[0] in ['Delay']:
            qubit0 = int(gate_info[1].split('Q')[1])
            new.append((gate[0].lower(), gate[1],(qubit0,)))
            qubit_used += [qubit0]
        elif gate[0] in ['Measure']:
            qubit0 = int(gate_info[1].split('Q')[1])
            cbit0 = gate[1]
            new.append((gate[0].lower(), [qubit0] ,[cbit0]))
            qubit_used += [qubit0]
            cbit_used += [cbit0]
        else:
            raise(ValueError(f'Sorry, an unrecognized qlisp syntax was detected by quarkcircuit. Please contact the developer for assistance. {gate[0]}'))

    return new, set(qubit_used), set(cbit_used)

initialize_lines(nqubits: int, ncbits: int, gates: list) -> tuple[list, list] ¤

Initialize a blank circuit.

Returns:

Type Description
tuple[list, list]

tuple[list,list]: A tuple containing: - A list of fake gates element. - A list of fake gates element list.

Source code in quark/circuit/quantumcircuit_helpers.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
848
849
850
851
def initialize_lines(nqubits:int,ncbits:int,gates:list) -> tuple[list, list]:
    r"""
    Initialize a blank circuit.

    Returns:
        tuple[list,list]: A tuple containing:
            - A list of fake gates element.
            - A list of fake gates element list.
    """
    nlines = 2 * nqubits + 1 + len(str(ncbits))
    gates_element = list('─ ' * nqubits) + ['═'] + [' '] * len(str(ncbits))
    gates_initial = copy.deepcopy(gates_element)
    qubits_expression = 'q'
    for i in range(nlines):
        if i in range(0, 2 * nqubits, 2):
            qi = i // 2
            if len(str(qi)) == 1:
                qn = qubits_expression + f'[{qi:<1}]  '
            elif len(str(qi)) == 2:
                qn = qubits_expression + f'[{qi:<2}] '
            elif len(str(qi)) == 3:
                qn = qubits_expression + f'[{qi:<3}]'
            gates_initial[i] = qn
        elif i in [2 * nqubits]:
            if len(str(ncbits)) == 1:
                c = f'c:  {ncbits}/'
            elif len(str(ncbits)) == 2:
                c = f'c: {ncbits}/'
            elif len(str(ncbits)) == 3:
                c = f'c:{ncbits}/'
            gates_initial[i] = c
        else:
            gates_initial[i] = ' ' * 6   
    n = len(gates) + nqubits
    gates_layerd = [gates_initial] + [copy.deepcopy(gates_element) for _ in range(n)]
    return gates_element,gates_layerd

generate_gates_layerd(nqubits: int, ncbits: int, gates: list, params_value: dict) -> list ¤

Assign gates to their respective layers loosely.

Returns:

Name Type Description
list list

A list of gates element list.

Source code in quark/circuit/quantumcircuit_helpers.py
 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
 890
 891
 892
 893
 894
 895
 896
 897
 898
 899
 900
 901
 902
 903
 904
 905
 906
 907
 908
 909
 910
 911
 912
 913
 914
 915
 916
 917
 918
 919
 920
 921
 922
 923
 924
 925
 926
 927
 928
 929
 930
 931
 932
 933
 934
 935
 936
 937
 938
 939
 940
 941
 942
 943
 944
 945
 946
 947
 948
 949
 950
 951
 952
 953
 954
 955
 956
 957
 958
 959
 960
 961
 962
 963
 964
 965
 966
 967
 968
 969
 970
 971
 972
 973
 974
 975
 976
 977
 978
 979
 980
 981
 982
 983
 984
 985
 986
 987
 988
 989
 990
 991
 992
 993
 994
 995
 996
 997
 998
 999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
def generate_gates_layerd(nqubits:int,ncbits:int,gates:list,params_value:dict) -> list:
    r"""Assign gates to their respective layers loosely.

    Returns:
        list: A list of gates element list.
    """
    lines_use = []
    # according plot layer distributed gates
    gates_element,gates_layerd = initialize_lines(nqubits,ncbits,gates)
    for gate_info in gates:
        gate = gate_info[0]
        if gate in one_qubit_gates_available.keys():
            pos0 = gate_info[1]
            for idx in range(len(gates_layerd)-1,-1,-1):
                if gates_layerd[idx][2*pos0] != '─':
                    gates_layerd[idx+1][2*pos0] = one_qubit_gates_available[gate]
                    lines_use.append(2 * pos0)
                    lines_use.append(2 * pos0 + 1)
                    break
        elif gate in two_qubit_gates_available.keys():
            pos0 = min(gate_info[1],gate_info[2])
            pos1 = max(gate_info[1],gate_info[2])
            for idx in range(len(gates_layerd)-1,-1,-1):
                if gates_layerd[idx][2*pos0:2*pos1+1] != list('─ ')*(pos1-pos0)+['─']:
                    gates_layerd[idx+1][2*gate_info[1]] = two_qubit_gates_available[gate][0]
                    gates_layerd[idx+1][2*gate_info[2]] = two_qubit_gates_available[gate][-1]
                    lines_use.append(2*pos0)
                    lines_use.append(2*pos0+1)
                    lines_use.append(2*pos1)
                    lines_use.append(2*pos1+1)
                    for i in range(2*pos0+1,2*pos1):
                        gates_layerd[idx+1][i] = '│'
                    break
        elif gate in three_qubit_gates_available.keys():
            sorted_qubits = sorted([gate_info[1],gate_info[2],gate_info[3]])
            pos0 = sorted_qubits[0]
            pos1 = sorted_qubits[1]
            pos2 = sorted_qubits[2]
            for idx in range(len(gates_layerd)-1,-1,-1):
                if gates_layerd[idx][2*pos0:2*pos2+1] != list('─ ')*(pos2-pos0)+['─']:
                    gates_layerd[idx+1][2*gate_info[1]] = three_qubit_gates_available[gate][0]
                    gates_layerd[idx+1][2*gate_info[2]] = three_qubit_gates_available[gate][1]
                    gates_layerd[idx+1][2*gate_info[3]] = three_qubit_gates_available[gate][2]
                    lines_use.append(2*pos0)
                    lines_use.append(2*pos0+1)
                    lines_use.append(2*pos1)
                    lines_use.append(2*pos1+1)
                    lines_use.append(2*pos2)
                    lines_use.append(2*pos2+1)
                    for i in range(2*pos0+1,2*pos1):
                        gates_layerd[idx+1][i] = '│'
                    for i in range(2*pos1+1,2*pos2):
                        gates_layerd[idx+1][i] = '│'
                    break
        elif gate in two_qubit_parameter_gates_available.keys():
            if gate in ['cp']:
                pos0 = min(gate_info[2],gate_info[3])
                pos1 = max(gate_info[2],gate_info[3])
                if isinstance(gate_info[1],(float,int)):
                    theta0_str = is_multiple_of_pi(gate_info[1])
                elif isinstance(gate_info[1],str):
                    param = params_value[gate_info[1]]
                    if isinstance(param,(float,int)):
                        theta0_str = is_multiple_of_pi(param)
                    elif isinstance(param,str):
                        theta0_str = param
                gate_express = two_qubit_parameter_gates_available[gate][1]+f'({theta0_str})'
                if len(gate_express) % 2 == 0:
                    gate_express = two_qubit_parameter_gates_available[gate][1]+f'({theta0_str})─'
                for idx in range(len(gates_layerd)-1,-1,-1):
                    if gates_layerd[idx][2*pos0:2*pos1+1] != list('─ ')*(pos1-pos0)+['─']:
                        gates_layerd[idx+1][2*gate_info[2]] = (len(gate_express)//2)*'─' + two_qubit_parameter_gates_available[gate][0] + (len(gate_express)//2)*'─'
                        gates_layerd[idx+1][2*gate_info[3]] = gate_express
                        lines_use.append(2*pos0)
                        lines_use.append(2*pos0+1)
                        lines_use.append(2*pos1)
                        lines_use.append(2*pos1+1)
                        for i in range(2*pos0+1,2*pos1):
                            if i % 2 == 0:
                                gates_layerd[idx+1][i] = (len(gate_express)//2)*'─' + '│' + (len(gate_express)//2)*'─'
                            else:
                                gates_layerd[idx+1][i] = (len(gate_express)//2)*' ' + '│' + (len(gate_express)//2)*' '

                        break

            else:
                pos0 = min(gate_info[2],gate_info[3])
                pos1 = max(gate_info[2],gate_info[3])
                if isinstance(gate_info[1],(float,int)):
                    theta0_str = is_multiple_of_pi(gate_info[1])
                elif isinstance(gate_info[1],str):
                    param = params_value[gate_info[1]]
                    if isinstance(param,(float,int)):
                        theta0_str = is_multiple_of_pi(param)
                    elif isinstance(param,str):
                        theta0_str = param
                gate_express = two_qubit_parameter_gates_available[gate]+f'({theta0_str})'
                if len(gate_express)%2 == 0:
                    gate_express += ' '
                for idx in range(len(gates_layerd)-1,-1,-1):
                    if gates_layerd[idx][2*pos0:2*pos1+1] != list('─ ')*(pos1-pos0)+['─']:
                        dif0 = (len(gate_express) - 1)//2
                        if pos0 == gate_info[2]: 
                            gates_layerd[idx+1][2*pos0] = '┌' + '─'*dif0 +'0'+'─'*dif0 + '┐'
                            gates_layerd[idx+1][2*pos1] = '└' + '─'*dif0 +'1'+'─'*dif0 + '┘'
                            lines_use.append(2*pos0)
                            lines_use.append(2*pos0 + 1)
                            lines_use.append(2*pos1)
                            lines_use.append(2*pos1 + 1)
                        elif pos0 == gate_info[3]:
                            gates_layerd[idx+1][2*pos0] = '┌' + '─'*dif0 +'1'+'─'*dif0 + '┐'
                            gates_layerd[idx+1][2*pos1] = '└' + '─'*dif0 +'0'+'─'*dif0 + '┘'
                            lines_use.append(2*pos0)
                            lines_use.append(2*pos0 + 1)
                            lines_use.append(2*pos1)
                            lines_use.append(2*pos1 + 1)
                        for i in range(2*pos0+1,2*pos1):
                            gates_layerd[idx+1][i] = '│' + ' '*len(gate_express) + '│'
                        gates_layerd[idx+1][2*pos0 + (pos1-pos0)] = '│' + gate_express + '│'
                        break
        elif gate in one_qubit_parameter_gates_available.keys():
            if gate == 'u':
                if isinstance(gate_info[1],(float,int)):
                    theta0_str = is_multiple_of_pi(gate_info[1])
                elif isinstance(gate_info[1],str):
                    param = params_value[gate_info[1]]
                    if isinstance(param,(float,int)):
                        theta0_str = is_multiple_of_pi(param)
                    elif isinstance(param,str):
                        theta0_str = param
                if isinstance(gate_info[2],(float,int)):
                    phi0_str = is_multiple_of_pi(gate_info[2])
                elif isinstance(gate_info[2],str):
                    param = params_value[gate_info[2]]
                    if isinstance(param,(float,int)):
                        phi0_str = is_multiple_of_pi(param)
                    elif isinstance(param,str):
                        phi0_str = param
                if isinstance(gate_info[3],(float,int)):
                    lamda0_str = is_multiple_of_pi(gate_info[3])
                elif isinstance(gate_info[3],str):
                    param = params_value[gate_info[3]]
                    if isinstance(param,(float,int)):
                        lamda0_str = is_multiple_of_pi(param)
                    elif isinstance(param,str):
                        lamda0_str = param
                pos0 = gate_info[-1]
                for idx in range(len(gates_layerd)-1,-1,-1):
                    if gates_layerd[idx][2*pos0] != '─':
                        params_str = '(' + theta0_str + ',' + phi0_str + ',' + lamda0_str + ')'
                        gates_layerd[idx+1][2*pos0] = one_qubit_parameter_gates_available[gate] + params_str
                        lines_use.append(2*pos0)
                        lines_use.append(2*pos0 + 1)
                        break      
            elif gate == 'r':      
                if isinstance(gate_info[1],(float,int)):
                    theta0_str = is_multiple_of_pi(gate_info[1])
                elif isinstance(gate_info[1],str):
                    param = params_value[gate_info[1]]
                    if isinstance(param,(float,int)):
                        theta0_str = is_multiple_of_pi(param)
                    elif isinstance(param,str):
                        theta0_str = param
                if isinstance(gate_info[2],(float,int)):
                    phi0_str = is_multiple_of_pi(gate_info[2])
                elif isinstance(gate_info[2],str):
                    param = params_value[gate_info[2]]
                    if isinstance(param,(float,int)):
                        phi0_str = is_multiple_of_pi(param)
                    elif isinstance(param,str):
                        phi0_str = param       
                pos0 = gate_info[-1]
                for idx in range(len(gates_layerd)-1,-1,-1):
                    if gates_layerd[idx][2*pos0] != '─':
                        params_str = '(' + theta0_str + ',' + phi0_str + ')'
                        gates_layerd[idx+1][2*pos0] = one_qubit_parameter_gates_available[gate] + params_str
                        lines_use.append(2*pos0)
                        lines_use.append(2*pos0 + 1)
                        break    
            else:
                if isinstance(gate_info[1],(float,int)):
                    theta0_str = is_multiple_of_pi(gate_info[1])
                elif isinstance(gate_info[1],str):
                    param = params_value[gate_info[1]]
                    if isinstance(param,(float,int)):
                        theta0_str = is_multiple_of_pi(param)
                    elif isinstance(param,str):
                        theta0_str = param
                #theta0_str = is_multiple_of_pi(gate_info[1])
                pos0 = gate_info[2]
                for idx in range(len(gates_layerd)-1,-1,-1):
                    if gates_layerd[idx][2*pos0] != '─':
                        gates_layerd[idx+1][2*pos0] = one_qubit_parameter_gates_available[gate]+'('+theta0_str+')'
                        lines_use.append(2*pos0)
                        lines_use.append(2*pos0 + 1)
                        break  
        elif gate in ['reset']:
            pos0 = gate_info[1]
            for idx in range(len(gates_layerd)-1,-1,-1):
                if gates_layerd[idx][2*pos0] != '─':
                    gates_layerd[idx+1][2*pos0] = functional_gates_available[gate]
                    lines_use.append(2 * pos0)
                    lines_use.append(2 * pos0 + 1)
                    break
        elif gate in ['barrier']:
            poslst0 = gate_info[1]
            poslst = []
            for j in poslst0:
                if j + 1 in poslst0:
                    poslst.append(2*j)
                    poslst.append(2*j+1)
                else:
                    poslst.append(2*j)
            for idx in range(len(gates_layerd)-1,-1,-1):
                e_ = [gates_layerd[idx][2*i] for i in poslst0]
                if all(e == '─' for e in e_) is False:
                    for i in poslst:
                        gates_layerd[idx+1][i] = functional_gates_available[gate]
                    break
        elif gate in ['delay']:
            poslst0 = gate_info[-1]
            poslst = []
            for j in poslst0:
                if j + 1 in poslst0:
                    poslst.append(2*j)
                else:
                    poslst.append(2*j)
            for idx in range(len(gates_layerd)-1,-1,-1):
                e_ = [gates_layerd[idx][2*i] for i in poslst0]
                if all(e == '─' for e in e_) is False:
                    for i in poslst:
                        gates_layerd[idx+1][i] = functional_gates_available[gate]+f'({gate_info[1]:.1e}s)'
                    break
        elif gate in ['measure']:
            for j in range(len(gate_info[1])):
                pos0 = gate_info[1][j]
                pos1 = gate_info[2][j]
                for idx in range(len(gates_layerd)-1,-1,-1):
                    if gates_layerd[idx][2*pos0:] != gates_element[2*pos0:]:
                        gates_layerd[idx+1][2*pos0] = functional_gates_available[gate]
                        lines_use.append(2*pos0)
                        lines_use.append(2*pos0 + 1)
                        for i in range(2*pos0+1,2*nqubits,1):
                            gates_layerd[idx+1][i] = '│'
                        for i in range(2*nqubits+1, 2*nqubits+1+len(str(pos1))):
                            gates_layerd[idx+1][i] = str(pos1)[i-2*nqubits-1]
                        break
    for idx in range(len(gates_layerd)-1,-1,-1):
        if gates_layerd[idx] != gates_element:
            cut = idx + 1
            break
    return gates_layerd[:cut],lines_use

format_gates_layerd(nqubits: int, ncbits: int, gates: list, params_value: dict) -> list ¤

Unify the width of each layer's gate strings

Returns:

Name Type Description
list list

A new list of gates element list.

Source code in quark/circuit/quantumcircuit_helpers.py
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
def format_gates_layerd(nqubits:int,ncbits:int,gates:list,params_value:dict) -> list:
    r"""Unify the width of each layer's gate strings

     Returns:
        list: A new list of gates element list.
    """
    gates_layerd,lines_use = generate_gates_layerd(nqubits,ncbits,gates,params_value)
    gates_layerd_format = [gates_layerd[0]]
    for lst in gates_layerd[1:]:
        max_length = max(len(item) for item in lst)
        if max_length == 1:
            gates_layerd_format.append(lst)
        else:
            if max_length % 2 == 0:
                max_length += 1
            dif0 = max_length // 2
            for idx in range(len(lst)):
                if len(lst[idx]) == 1:
                    if idx < 2 * nqubits:
                        if idx % 2 == 0:
                            lst[idx] = '─' * dif0 + lst[idx] + '─' * dif0
                        else:
                            lst[idx] = ' ' * dif0 + lst[idx] + ' ' * dif0
                    elif idx == 2 * nqubits:
                        lst[idx] = '═' * dif0 + lst[idx] + '═' * dif0
                    else:
                        lst[idx] = ' ' * dif0 + lst[idx] + ' ' * dif0
                else:
                    dif1 = max_length - len(lst[idx])
                    if idx%2 == 0:
                        lst[idx] = lst[idx] + '─' * dif1
                    else:
                        lst[idx] = lst[idx] + ' ' * dif1
            gates_layerd_format.append(lst)
    return gates_layerd_format,lines_use

add_gates_to_lines(nqubits: int, ncbits: int, gates: list, params_value: dict, width: int = 4) -> list ¤

Add gates to lines. Args: width (int, optional): The width between gates. Defaults to 4. Returns: list: A list of lines.

Source code in quark/circuit/quantumcircuit_helpers.py
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
def add_gates_to_lines(nqubits:int,ncbits:int,gates:list,params_value:dict, width: int = 4) -> list:
    r"""Add gates to lines.
    Args:
        width (int, optional): The width between gates. Defaults to 4.
    Returns:
        list: A list of lines.
    """
    gates_layerd_format,lines_use = format_gates_layerd(nqubits,ncbits,gates,params_value)
    nl = len(gates_layerd_format[0])
    lines1 = [str() for _ in range(nl)]
    for i in range(nl):
        for j in range(len(gates_layerd_format)):
            if i < 2 * nqubits:
                if i % 2 == 0:
                    lines1[i] += gates_layerd_format[j][i] + '─' * width
                else:
                    lines1[i] += gates_layerd_format[j][i] + ' ' * width
            elif i == 2 * nqubits:
                lines1[i] += gates_layerd_format[j][i] + '═' * width
            elif i > 2 * nqubits:
                lines1[i] += gates_layerd_format[j][i] + ' ' * width
    return lines1,lines_use