当前位置: 首页>>代码示例>>Python>>正文


Python QuantumCircuit.add方法代码示例

本文整理汇总了Python中qiskit.QuantumCircuit.add方法的典型用法代码示例。如果您正苦于以下问题:Python QuantumCircuit.add方法的具体用法?Python QuantumCircuit.add怎么用?Python QuantumCircuit.add使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在qiskit.QuantumCircuit的用法示例。


在下文中一共展示了QuantumCircuit.add方法的3个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: add_circuits

# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import add [as 别名]
    def add_circuits(self, n_circuits, do_measure=True, basis=None,
                     basis_weights=None):
        """Adds circuits to program.

        Generates a circuit with a random number of operations in `basis`.
        Also adds a random number of measurements in
        [1,nQubits] to end of circuit.

        Args:
            n_circuits (int): Number of circuits to add.
            do_measure (bool): Whether to add measurements.
            basis (list(str) or None): List of op names. If None, basis
                is randomly chosen with unique ops in (2,7)
            basis_weights (list(float) or None): List of weights
                corresponding to indices in `basis`.
        Raises:
            AttributeError: if operation is not recognized.
        """
        if basis is None:
            basis = list(random.sample(self.op_signature.keys(),
                                       random.randint(2, 7)))
            basis_weights = [1./len(basis)] * len(basis)
        if basis_weights is not None:
            assert len(basis) == len(basis_weights)
        uop_basis = basis[:]
        if basis_weights:
            uop_basis_weights = basis_weights[:]
        else:
            uop_basis_weights = None
        # remove barrier from uop basis if it is specified
        if 'barrier' in uop_basis:
            ind = uop_basis.index('barrier')
            del uop_basis[ind]
            if uop_basis_weights:
                del uop_basis_weights[ind]
        # remove measure from uop basis if it is specified
        if 'measure' in uop_basis:
            ind = uop_basis.index('measure')
            del uop_basis[ind]
            if uop_basis_weights:
                del uop_basis_weights[ind]
        # self.basis_gates = uop_basis
        self.basis_gates = basis
        self.circuit_name_list = []
        # TODO: replace choices with random.choices() when python 3.6 is
        # required.
        self.n_qubit_list = choices(
            range(self.min_qubits, self.max_qubits + 1), k=n_circuits)
        self.depth_list = choices(
            range(self.min_depth, self.max_depth + 1), k=n_circuits)
        for i_circuit in range(n_circuits):
            n_qubits = self.n_qubit_list[i_circuit]
            if self.min_regs_exceeds_nqubits(uop_basis, n_qubits):
                # no gate operation from this circuit can fit in the available
                # number of qubits.
                continue
            depth_cnt = self.depth_list[i_circuit]
            reg_pop = numpy.arange(1, n_qubits+1)
            register_weights = reg_pop[::-1].astype(float)
            register_weights /= register_weights.sum()
            max_registers = numpy.random.choice(reg_pop, p=register_weights)
            reg_weight = numpy.ones(max_registers) / float(max_registers)
            reg_sizes = rand_register_sizes(n_qubits, reg_weight)
            n_registers = len(reg_sizes)
            circuit = QuantumCircuit()
            for i_size, size in enumerate(reg_sizes):
                cr_name = 'cr' + str(i_size)
                qr_name = 'qr' + str(i_size)
                creg = ClassicalRegister(size, cr_name)
                qreg = QuantumRegister(size, qr_name)
                circuit.add(qreg, creg)
            while depth_cnt > 0:
                # TODO: replace choices with random.choices() when python 3.6
                # is required.
                op_name = choices(basis, weights=basis_weights)[0]
                if hasattr(circuit, op_name):
                    operator = getattr(circuit, op_name)
                else:
                    raise AttributeError('operation \"{0}\"'
                                         ' not recognized'.format(op_name))
                n_regs = self.op_signature[op_name]['nregs']
                n_params = self.op_signature[op_name]['nparams']
                if n_regs == 0:  # this is a barrier or measure
                    n_regs = random.randint(1, n_qubits)
                if n_qubits >= n_regs:
                    # warning: assumes op function signature specifies
                    # op parameters before qubits
                    op_args = []
                    if n_params:
                        op_args = [random.random() for _ in range(n_params)]
                    if op_name == 'measure':
                        # if measure occurs here, assume it's to do a conditional
                        # randomly select a register to measure
                        ireg = random.randint(0, n_registers-1)
                        qr_name = 'qr' + str(ireg)
                        cr_name = 'cr' + str(ireg)
                        qreg = circuit.regs[qr_name]
                        creg = circuit.regs[cr_name]
                        for qind in range(qreg.size):
                            operator(qreg[qind], creg[qind])
#.........这里部分代码省略.........
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:103,代码来源:_random_circuit_generator.py

示例2: add_circuits

# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import add [as 别名]
    def add_circuits(self, nCircuits, doMeasure=True, basis=['u3', 'cx'],
                     basis_weights=None):
        """Adds circuits to program.

        Generates a circuit with a random number of operations in `basis`.
        Also adds a random number of measurements in
        [1,nQubits] to end of circuit.

        Args:
            nCircuits (int): Number of circuits to add.
            doMeasure (bool): Whether to add measurements.
            basis (list of str): List of op names.
            basis_weights (list of float or None): List of weights
                corresponding to indices in `basis`.
        """
        uop_basis = basis[:]
        if basis_weights:
            uop_basis_weights = basis_weights[:]
        else:
            uop_basis_weights = None
        # remove barrier from uop basis if it is specified
        if 'barrier' in uop_basis:
            ind = uop_basis.index('barrier')
            del uop_basis[ind]
            if uop_basis_weights:
                del uop_basis_weights[ind]
        # remove measure from uop basis if it is specified
        if 'measure' in uop_basis:
            ind = uop_basis.index('measure')
            del uop_basis[ind]
            if uop_basis_weights:
                del uop_basis_weights[ind]
        # self.basis_gates = uop_basis
        self.basis_gates = basis
        self.circuitNameList = []
        # TODO: replace choices with random.choices() when python 3.6 is
        # required.
        self.nQubit_list = choices(
            range(self.minQubits, self.maxQubits+1), k=nCircuits)
        self.depth_list = choices(
            range(self.minDepth, self.maxDepth+1), k=nCircuits)
        for iCircuit in range(nCircuits):
            nQubits = self.nQubit_list[iCircuit]
            depthCnt = self.depth_list[iCircuit]
            regpop = numpy.arange(1, nQubits+1)
            registerWeights = regpop[::-1].astype(float)
            registerWeights /= registerWeights.sum()
            maxRegisters = numpy.random.choice(regpop, p=registerWeights)
            regWeight = numpy.ones(maxRegisters) / float(maxRegisters)
            regSizes = rand_register_sizes(nQubits, regWeight)
            nRegisters = len(regSizes)
            circuit = QuantumCircuit()
            for isize, size in enumerate(regSizes):
                cr_name = 'cr' + str(isize)
                qr_name = 'qr' + str(isize)
                cr = ClassicalRegister(cr_name, size)
                qr = QuantumRegister(qr_name, size)
                circuit.add(qr, cr)
            while depthCnt > 0:
                # TODO: replace choices with random.choices() when python 3.6
                # is required.
                opName = choices(basis, weights=basis_weights)[0]
                if hasattr(circuit, opName):
                    op = getattr(circuit, opName)
                else:
                    raise AttributeError('operation \"{0}\"'
                                         ' not recognized'.format(opName))
                nregs = self.opSignature[opName]['nregs']
                nparams = self.opSignature[opName]['nparams']
                if nregs == 0:  # this is a barrier or measure
                    nregs = random.randint(1, nQubits)
                if nQubits >= nregs:
                    # warning: assumes op function signature specifies
                    # op parameters before qubits
                    op_args = []
                    if nparams:
                        op_args = [random.random() for p in range(nparams)]
                    if opName is 'measure':
                        # if measure occurs here, assume it's to do a conditional
                        # randomly select a register to measure
                        ireg = random.randint(0, nRegisters-1)
                        qr_name = 'qr' + str(ireg)
                        cr_name = 'cr' + str(ireg)
                        qreg = circuit.regs[qr_name]
                        creg = circuit.regs[cr_name]
                        for qind in range(qreg.size):
                            op(qreg[qind], creg[qind])
                        ifval = random.randint(0, (1 << qreg.size) - 1)
                        # TODO: replace choices with random.choices() when
                        # python 3.6 is required.
                        uopName = choices(uop_basis, weights=uop_basis_weights)[0]
                        if hasattr(circuit, uopName):
                            uop = getattr(circuit, uopName)
                        else:
                            raise AttributeError('operation \"{0}\"'
                                                 ' not recognized'.format(uopName))
                        unregs = self.opSignature[uopName]['nregs']
                        unparams = self.opSignature[uopName]['nparams']
                        if unregs == 0: # this is a barrier or measure
                            unregs = random.randint(1, nQubits)
#.........这里部分代码省略.........
开发者ID:LuisCarlosEiras,项目名称:qiskit-sdk-py,代码行数:103,代码来源:_random_circuit_generator.py

示例3: CircuitBackend

# 需要导入模块: from qiskit import QuantumCircuit [as 别名]
# 或者: from qiskit.QuantumCircuit import add [as 别名]
class CircuitBackend(UnrollerBackend):
    """Backend for the unroller that produces a QuantumCircuit.

    By default, basis gates are the QX gates.
    """

    def __init__(self, basis=None):
        """Setup this backend.

        basis is a list of operation name strings.
        """
        super().__init__(basis)
        self.creg = None
        self.cval = None
        if basis:
            self.basis = basis
        else:
            self.basis = ["cx", "u1", "u2", "u3"]
        self.gates = {}
        self.listen = True
        self.in_gate = ""
        self.circuit = QuantumCircuit()

    def set_basis(self, basis):
        """Declare the set of user-defined gates to emit.

        basis is a list of operation name strings.
        """
        self.basis = basis

    def version(self, version):
        """Ignore the version string.

        v is a version number.
        """
        pass

    def new_qreg(self, name, size):
        """Create a new quantum register.

        name = name of the register
        sz = size of the register
        """
        assert size >= 0, "invalid qreg size"
        q_register = QuantumRegister(size, name)
        self.circuit.add(q_register)

    def new_creg(self, name, size):
        """Create a new classical register.

        name = name of the register
        sz = size of the register
        """
        assert size >= 0, "invalid creg size"
        c_register = ClassicalRegister(size, name)
        self.circuit.add(c_register)

    def define_gate(self, name, gatedata):
        """Define a new quantum gate.

        We don't check that the definition and name agree.

        name is a string.
        gatedata is the AST node for the gate.
        """
        self.gates[name] = gatedata

    def _map_qubit(self, qubit):
        """Map qubit tuple (regname, index) to (QuantumRegister, index)."""
        qregs = self.circuit.get_qregs()
        if qubit[0] not in qregs:
            raise BackendError("qreg %s does not exist" % qubit[0])
        return (qregs[qubit[0]], qubit[1])

    def _map_bit(self, bit):
        """Map bit tuple (regname, index) to (ClassicalRegister, index)."""
        cregs = self.circuit.get_cregs()
        if bit[0] not in cregs:
            raise BackendError("creg %s does not exist" % bit[0])
        return (cregs[bit[0]], bit[1])

    def _map_creg(self, creg):
        """Map creg name to ClassicalRegister."""
        cregs = self.circuit.get_cregs()
        if creg not in cregs:
            raise BackendError("creg %s does not exist" % creg)
        return cregs[creg]

    def u(self, arg, qubit, nested_scope=None):
        """Fundamental single qubit gate.

        arg is 3-tuple of Node expression objects.
        qubit is (regname,idx) tuple.
        nested_scope is a list of dictionaries mapping expression variables
        to Node expression objects in order of increasing nesting depth.
        """
        if self.listen:
            if "U" not in self.basis:
                self.basis.append("U")

#.........这里部分代码省略.........
开发者ID:christians94,项目名称:qiskit-sdk-py,代码行数:103,代码来源:_circuitbackend.py


注:本文中的qiskit.QuantumCircuit.add方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。