def circuit_from_qasm_string(qasm_string,
                             name=None,
                             basis_gates="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,"
                             "rx,ry,rz,cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,"
                             "cswap"):
    """Construct a quantum circuit from a qasm representation (string).

    Args:
        qasm_string (str): a string of qasm, or a filename containing qasm.
        basis_gates (str): basis gates for the quantum circuit.
        name (str or None): the name of the quantum circuit after loading
            qasm text into it. If no name given, assign automatically.
    Returns:
        QuantumCircuit: circuit constructed from qasm.
    Raises:
        QISKitError: if the string is not valid QASM
    """

    node_circuit = Qasm(data=qasm_string).parse()
    unrolled_circuit = Unroller(node_circuit,
                                CircuitBackend(basis_gates.split(",")))
    circuit_unrolled = unrolled_circuit.execute()
    if name:
        circuit_unrolled.name = name
    return circuit_unrolled
def load_unroll_qasm_file(filename, basis_gates='u1,u2,u3,cx,id'):
    """Load qasm file and return unrolled circuit

    Args:
        filename (str): a string for the filename including its location.
        basis_gates (str): basis to unroll circuit to.
    Returns:
        object: Returns a unrolled QuantumCircuit object
    """
    # create Program object Node (AST)
    node_circuit = qasm.Qasm(filename=filename).parse()
    node_unroller = Unroller(node_circuit, CircuitBackend(basis_gates.split(",")))
    circuit_unrolled = node_unroller.execute()
    return circuit_unrolled
Beispiel #3
0
    def test_execute(self):
        ast = qasm.Qasm(
            filename=self._get_resource_path('qasm/example.qasm')).parse()
        dag_circuit = Unroller(ast, DAGBackend()).execute()
        dag_unroller = DagUnroller(dag_circuit, DAGBackend())
        unroller_dag_circuit = dag_unroller.execute()
        expected_result = """\
OPENQASM 2.0;
qreg q[3];
qreg r[3];
creg c[3];
creg d[3];
U(0.5*pi,0,pi) q[2];
CX q[2],r[2];
measure r[2] -> d[2];
U(0.5*pi,0,pi) q[1];
CX q[1],r[1];
measure r[1] -> d[1];
U(0.5*pi,0,pi) q[0];
CX q[0],r[0];
measure r[0] -> d[0];
barrier q[0],q[1],q[2];
measure q[2] -> c[2];
measure q[1] -> c[1];
measure q[0] -> c[0];
"""
        self.assertEqual(unroller_dag_circuit.qasm(), expected_result)
    def setUp(self):
        qasm_filename = self._get_resource_path('qasm/example.qasm')
        qasm_ast = Qasm(filename=qasm_filename).parse()
        qasm_dag = Unroller(qasm_ast, DAGBackend()).execute()
        qasm_json = DagUnroller(qasm_dag,
                                JsonBackend(qasm_dag.basis)).execute()

        qr = QuantumRegister(2, 'q')
        cr = ClassicalRegister(2, 'c')
        qc = QuantumCircuit(qr, cr)
        qc.h(qr[0])
        qc.measure(qr[0], cr[0])
        qc_dag = DAGCircuit.fromQuantumCircuit(qc)
        qc_json = DagUnroller(qc_dag, JsonBackend(qc_dag.basis)).execute()

        # create qobj
        compiled_circuit1 = QobjExperiment.from_dict(qc_json)
        compiled_circuit2 = QobjExperiment.from_dict(qasm_json)

        self.qobj = Qobj(qobj_id='test_qobj',
                         config=QobjConfig(shots=2000,
                                           memory_slots=1,
                                           max_credits=3,
                                           seed=1111),
                         experiments=[compiled_circuit1, compiled_circuit2],
                         header=QobjHeader(backend_name='qasm_simulator'))
        self.qobj.experiments[0].header.name = 'test_circuit1'
        self.qobj.experiments[1].header.name = 'test_circuit2'
        self.backend = QasmSimulator()
Beispiel #5
0
    def test_dag_to_dag_expand_gates_default_basis(self):
        """Test DagUnroller.expand_gates()"""
        ast = qasm.Qasm(filename=self._get_resource_path('qasm/example.qasm')).parse()
        dag_circuit = Unroller(ast, DAGBackend()).execute()
        dag_unroller = DagUnroller(dag_circuit, DAGBackend())
        expanded_dag_circuit = dag_unroller.expand_gates()
        expected_result = """\
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
qreg r[3];
creg c[3];
creg d[3];
U(pi/2,0,pi) q[2];
CX q[2],r[2];
measure r[2] -> d[2];
U(pi/2,0,pi) q[1];
CX q[1],r[1];
measure r[1] -> d[1];
U(pi/2,0,pi) q[0];
CX q[0],r[0];
barrier q[0],q[1],q[2];
measure q[0] -> c[0];
measure q[1] -> c[1];
measure q[2] -> c[2];
measure r[0] -> d[0];
"""
        expected_dag = circuit_to_dag(QuantumCircuit.from_qasm_str(expected_result))
        self.assertEqual(expanded_dag_circuit, expected_dag)
Beispiel #6
0
    def test_dag_to_json(self):
        """Test DagUnroller with JSON backend."""
        ast = qasm.Qasm(filename=self._get_resource_path('qasm/example.qasm')).parse()
        dag_circuit = Unroller(ast, DAGBackend()).execute()
        dag_unroller = DagUnroller(dag_circuit, JsonBackend())
        json_circuit = dag_unroller.execute()
        expected_result = {
            'operations':
                [
                    {'qubits': [5], 'texparams': ['0.5 \\pi', '0', '\\pi'],
                     'name': 'U', 'params': [1.5707963267948966, 0.0, 3.141592653589793]},
                    {'name': 'CX', 'qubits': [5, 2]},
                    {'clbits': [2], 'name': 'measure', 'qubits': [2]},
                    {'qubits': [4], 'texparams': ['0.5 \\pi', '0', '\\pi'], 'name': 'U',
                     'params': [1.5707963267948966, 0.0, 3.141592653589793]},
                    {'name': 'CX', 'qubits': [4, 1]},
                    {'clbits': [1], 'name': 'measure', 'qubits': [1]},
                    {'qubits': [3], 'texparams': ['0.5 \\pi', '0', '\\pi'], 'name': 'U',
                     'params': [1.5707963267948966, 0.0, 3.141592653589793]},
                    {'name': 'CX', 'qubits': [3, 0]},
                    {'name': 'barrier', 'qubits': [3, 4, 5]},
                    {'clbits': [5], 'name': 'measure', 'qubits': [5]},
                    {'clbits': [4], 'name': 'measure', 'qubits': [4]},
                    {'clbits': [3], 'name': 'measure', 'qubits': [3]},
                    {'clbits': [0], 'name': 'measure', 'qubits': [0]}
                ],
            'header':
                {
                    'memory_slots': 6,
                    'qubit_labels': [['r', 0], ['r', 1], ['r', 2], ['q', 0], ['q', 1], ['q', 2]],
                    'n_qubits': 6, 'clbit_labels': [['d', 3], ['c', 3]]
                }
        }

        self.assertEqual(json_circuit, expected_result)
Beispiel #7
0
 def test_from_dag_to_json_with_basis(self):
     ast = qasm.Qasm(
         filename=self._get_resource_path('qasm/example.qasm')).parse()
     dag_circuit = Unroller(ast, DAGBackend(["cx", "u1", "u2",
                                             "u3"])).execute()
     dag_unroller = DagUnroller(dag_circuit,
                                JsonBackend(["cx", "u1", "u2", "u3"]))
     json_circuit = dag_unroller.execute()
     expected_result = \
         {'operations':
             [{'qubits': [5], 'texparams': ['0', '\\pi'], 'params': [0.0, 3.141592653589793],
               'name': 'u2'},
              {'qubits': [5, 2], 'texparams': [], 'params': [], 'name': 'cx'},
              {'qubits': [2], 'clbits': [2], 'name': 'measure'},
              {'qubits': [4], 'texparams': ['0', '\\pi'], 'params': [0.0, 3.141592653589793],
               'name': 'u2'},
              {'qubits': [4, 1], 'texparams': [], 'params': [], 'name': 'cx'},
              {'qubits': [1], 'clbits': [1], 'name': 'measure'},
              {'qubits': [3], 'texparams': ['0', '\\pi'], 'params': [0.0, 3.141592653589793],
               'name': 'u2'},
              {'qubits': [3, 0], 'texparams': [], 'params': [], 'name': 'cx'},
              {'qubits': [3, 4, 5], 'name': 'barrier'},
              {'qubits': [5], 'clbits': [5], 'name': 'measure'},
              {'qubits': [4], 'clbits': [4], 'name': 'measure'},
              {'qubits': [3], 'clbits': [3], 'name': 'measure'},
              {'qubits': [0], 'clbits': [0], 'name': 'measure'}],
          'header':
              {'clbit_labels': [['d', 3], ['c', 3]],
               'number_of_qubits': 6,
               'qubit_labels': [['r', 0], ['r', 1], ['r', 2], ['q', 0], ['q', 1], ['q', 2]],
               'number_of_clbits': 6
               }
          }
     self.assertEqual(json_circuit, expected_result)
Beispiel #8
0
def _circuit_from_qasm(qasm):
    from qiskit.unroll import Unroller
    from qiskit.unroll import DAGBackend
    from qiskit.converters import dag_to_circuit
    ast = qasm.parse()
    dag = Unroller(ast, DAGBackend()).execute()
    return dag_to_circuit(dag)
Beispiel #9
0
    def test_from_ast_to_dag(self):
        """Test Unroller.execute()"""
        ast = qasm.Qasm(
            filename=self._get_resource_path('qasm/example.qasm')).parse()
        dag_circuit = Unroller(ast, DAGBackend()).execute()
        expected_result = """\
OPENQASM 2.0;
include "qelib1.inc";
qreg q[3];
qreg r[3];
creg c[3];
creg d[3];
h q[0];
h q[1];
h q[2];
cx q[0],r[0];
cx q[1],r[1];
cx q[2],r[2];
barrier q[0],q[1],q[2];
measure q[0] -> c[0];
measure q[1] -> c[1];
measure q[2] -> c[2];
measure r[0] -> d[0];
measure r[1] -> d[1];
measure r[2] -> d[2];
"""
        expected_dag = DAGCircuit.fromQuantumCircuit(
            QuantumCircuit.from_qasm_str(expected_result))
        self.assertEqual(dag_circuit, expected_dag)
Beispiel #10
0
def load_qasm_string(qasm_string, name=None,
                     basis_gates="id,u0,u1,u2,u3,x,y,z,h,s,sdg,t,tdg,rx,ry,rz,"
                                 "cx,cy,cz,ch,crz,cu1,cu3,swap,ccx,cswap"):
    """Construct a quantum circuit from a qasm representation (string).

    Args:
        qasm_string (str): a string of qasm, or a filename containing qasm.
        basis_gates (str): basis gates for the quantum circuit.
        name (str or None): the name of the quantum circuit after loading qasm
            text into it. If no name given, assign automatically.
    Returns:
        QuantumCircuit: circuit constructed from qasm.
    Raises:
        QISKitError: if the string is not valid QASM
    """
    node_circuit = Qasm(data=qasm_string).parse()
    unrolled_circuit = Unroller(node_circuit, CircuitBackend(basis_gates.split(",")))
    circuit_unrolled = unrolled_circuit.execute()
    if name:
        circuit_unrolled.name = name
    return circuit_unrolled
    def _build_subcircuit(self, gatedefs, basis, gate_name, gate_params,
                          gate_args, gate_condition):
        """Build DAGCircuit for a given user-defined gate node.

        gatedefs = dictionary of Gate AST nodes for user-defined gates
        gate_name = name of gate to expand to target_basis (nd["name"])
        gate_params = list of gate parameters (nd["params"])
        gate_args = list of gate arguments (nd["qargs"])
        gate_condition = None or tuple (string, int) (nd["condition"])

        Returns (subcircuit, wires) where subcircuit is the DAGCircuit
        corresponding to the user-defined gate node expanded to target_basis
        and wires is the list of input wires to the subcircuit in order
        corresponding to the gate's arguments.
        """

        children = [Id(gate_name, 0, "")]
        if gate_params:
            children.append(ExpressionList(list(map(Real, gate_params))))
        new_wires = [("q", j) for j in range(len(gate_args))]
        children.append(
            PrimaryList(
                list(
                    map(lambda x: IndexedId([Id(x[0], 0, ""),
                                             Int(x[1])]), new_wires))))
        gate_node = CustomUnitary(children)
        id_int = [Id("q", 0, ""), Int(len(gate_args))]
        # Make a list of register declaration nodes
        reg_nodes = [Qreg([IndexedId(id_int)])]
        # Add an If node when there is a condition present
        if gate_condition:
            gate_node = If([
                Id(gate_condition[0], 0, ""),
                Int(gate_condition[1]), gate_node
            ])
            new_wires += [
                (gate_condition[0], j)
                for j in range(self.dag_circuit.cregs[gate_condition[0]])
            ]
            reg_nodes.append(
                Creg([
                    IndexedId([
                        Id(gate_condition[0], 0, ""),
                        Int(self.dag_circuit.cregs[gate_condition[0]])
                    ])
                ]))

        # Build the whole program's AST
        sub_ast = Program(gatedefs + reg_nodes + [gate_node])
        # Interpret the AST to give a new DAGCircuit over backend basis
        sub_circuit = Unroller(sub_ast, DAGBackend(basis)).execute()
        return sub_circuit, new_wires
Beispiel #12
0
def qasm_to_dag_circuit(qasm_string, basis_gates='u1,u2,u3,cx,id'):
    """
    Convert an OPENQASM text string to a DAGCircuit.

    Args:
        qasm_string (str): OPENQASM2.0 circuit string.
        basis_gates (str): QASM gates to unroll circuit to.

    Returns:
        A DAGCircuit object of the unrolled QASM circuit.
    """
    program_node_circuit = qiskit.qasm.Qasm(data=qasm_string).parse()
    dag_circuit = Unroller(program_node_circuit,
                           DAGBackend(basis_gates.split(","))).execute()
    return dag_circuit
Beispiel #13
0
    def test_dag_to_dag_expand_gates_custom_basis(self):
        """Test DagUnroller.expand_gates() to a gate basis."""
        ast = qasm.Qasm(
            filename=self._get_resource_path('qasm/example.qasm')).parse()
        dag_circuit = Unroller(ast, DAGBackend()).execute()
        dag_unroller = DagUnroller(dag_circuit, DAGBackend())
        expanded_dag_circuit = dag_unroller.expand_gates(
            basis=["cx", "u1", "u2", "u3"])
        expected_result = """\
OPENQASM 2.0;
qreg q[3];
qreg r[3];
creg c[3];
creg d[3];
gate u2(phi,lambda) q
{
  U((pi/2),phi,lambda) q;
}
gate h a
{
  u2(0,pi) a;
}
gate cx c,t
{
  CX c,t;
}
u2(0,pi) q[2];
cx q[2],r[2];
measure r[2] -> d[2];
u2(0,pi) q[1];
cx q[1],r[1];
measure r[1] -> d[1];
u2(0,pi) q[0];
cx q[0],r[0];
barrier q[0],q[1],q[2];
measure q[0] -> c[0];
measure q[1] -> c[1];
measure q[2] -> c[2];
measure r[0] -> d[0];
"""
        self.assertEqual(expanded_dag_circuit.qasm(), expected_result)
Beispiel #14
0
    def setUp(self):
        self.seed = 88
        self.backend = QasmSimulatorPy()
        backend_basis = self.backend.configuration().basis_gates
        qasm_filename = self._get_resource_path('qasm/example.qasm')
        qasm_ast = Qasm(filename=qasm_filename).parse()
        qasm_dag = Unroller(qasm_ast, DAGBackend()).execute()
        qasm_dag = DagUnroller(qasm_dag, DAGBackend(backend_basis)).expand_gates()
        qasm_json = DagUnroller(qasm_dag, JsonBackend(qasm_dag.basis)).execute()
        compiled_circuit = QobjExperiment.from_dict(qasm_json)
        compiled_circuit.header.name = 'test'

        self.qobj = Qobj(
            qobj_id='test_sim_single_shot',
            config=QobjConfig(
                shots=1024, memory_slots=6,
                max_credits=3, seed=self.seed
            ),
            experiments=[compiled_circuit],
            header=QobjHeader(backend_name='qasm_simulator_py')
        )
def _circuit_from_qasm(qasm):
    from qiskit.unroll import Unroller
    from qiskit.unroll import DAGBackend
    ast = qasm.parse()
    dag = Unroller(ast, DAGBackend()).execute()

    circuit = QuantumCircuit()
    for qreg in dag.qregs.values():
        circuit.add_register(qreg)
    for creg in dag.cregs.values():
        circuit.add_register(creg)
    graph = dag.multi_graph
    for node in nx.topological_sort(graph):
        n = graph.nodes[node]
        if n['type'] == 'op':
            n['op'].circuit = circuit
            if 'condition' in n and n['condition']:
                circuit._attach(n['op'].c_if(*n['condition']))
            else:
                circuit._attach(n['op'])

    return circuit