We are currently solving the following issue within our repository. Here is the issue text:
--- BEGIN ISSUE ---
Default circuit names are not zero-based
<!-- ⚠️ If you do not respect this template, your issue will be closed -->
<!-- ⚠️ Make sure to browse the opened and closed issues -->

### Informations

- **Qiskit Terra version**: latest
- **Python version**: 3.7
- **Operating system**: OSX

### What is the current behavior?
When creating a quantum circuit with no name, the default name is set to `circuitX`.  Currently, `X` starts from `1` rather than `0`, and can cause some confusion when trying to index circuits by name.


### Steps to reproduce the problem
```python
from qiskit import *
q = QuantumRegister(2, "q")
c = ClassicalRegister(2, "c")
# Create measurement subcircuit
qc = QuantumCircuit(q,c)
qc.name
```
gives `'circuit1'` for the initial circuit created.  It should be `'circuit0'` to coincide with the the indexing in Python.

### What is the expected behavior?



### Suggested solutions




--- END ISSUE ---

Below are some code segments, each from a relevant file. One or more of these files may contain bugs.
--- BEGIN FILES ---
Path: `qiskit/_quantumcircuit.py`
Content:
```
1 # -*- coding: utf-8 -*-
2 
3 # Copyright 2017, IBM.
4 #
5 # This source code is licensed under the Apache License, Version 2.0 found in
6 # the LICENSE.txt file in the root directory of this source tree.
7 
8 """
9 Quantum circuit object.
10 """
11 import itertools
12 from collections import OrderedDict
13 from ._qiskiterror import QISKitError
14 from ._register import Register
15 from ._quantumregister import QuantumRegister
16 from ._classicalregister import ClassicalRegister
17 from ._measure import Measure
18 from ._reset import Reset
19 from ._instructionset import InstructionSet
20 
21 
22 class QuantumCircuit(object):
23     """Quantum circuit."""
24     instances = 0
25     prefix = 'circuit'
26 
27     # Class variable OPENQASM header
28     header = "OPENQASM 2.0;"
29 
30     # Class variable with gate definitions
31     # This is a dict whose values are dicts with the
32     # following keys:
33     #   "print" = True or False
34     #   "opaque" = True or False
35     #   "n_args" = number of real parameters
36     #   "n_bits" = number of qubits
37     #   "args"   = list of parameter names
38     #   "bits"   = list of qubit names
39     #   "body"   = GateBody AST node
40     definitions = OrderedDict()
41 
42     def __init__(self, *regs, name=None):
43         """Create a new circuit.
44 
45         Args:
46             *regs (Registers): registers to include in the circuit.
47             name (str or None): the name of the quantum circuit. If
48                 None, an automatically generated identifier will be
49                 assigned.
50 
51         Raises:
52             QISKitError: if the circuit name, if given, is not valid.
53         """
54         self._increment_instances()
55         if name is None:
56             name = self.cls_prefix() + str(self.cls_instances())
57 
58         if not isinstance(name, str):
59             raise QISKitError("The circuit name should be a string "
60                               "(or None for autogenerate a name).")
61 
62         self.name = name
63         # Data contains a list of instructions in the order they were applied.
64         self.data = []
65         # This is a map of registers bound to this circuit, by name.
66         self.regs = OrderedDict()
67         self.add(*regs)
68 
69     @classmethod
70     def _increment_instances(cls):
71         cls.instances += 1
72 
73     @classmethod
74     def cls_instances(cls):
75         """Return the current number of instances of this class,
76         useful for auto naming."""
77         return cls.instances
78 
79     @classmethod
80     def cls_prefix(cls):
81         """Return the prefix to use for auto naming."""
82         return cls.prefix
83 
84     def has_register(self, register):
85         """
86         Test if this circuit has the register r.
87 
88         Return True or False.
89         """
90         if register.name in self.regs:
91             registers = self.regs[register.name]
92             if registers.size == register.size:
93                 if ((isinstance(register, QuantumRegister) and
94                      isinstance(registers, QuantumRegister)) or
95                         (isinstance(register, ClassicalRegister) and
96                          isinstance(registers, ClassicalRegister))):
97                     return True
98         return False
99 
100     def get_qregs(self):
101         """Get the qregs from the registers."""
102         qregs = OrderedDict()
103         for name, register in self.regs.items():
104             if isinstance(register, QuantumRegister):
105                 qregs[name] = register
106         return qregs
107 
108     def get_cregs(self):
109         """Get the cregs from the registers."""
110         cregs = OrderedDict()
111         for name, register in self.regs.items():
112             if isinstance(register, ClassicalRegister):
113                 cregs[name] = register
114         return cregs
115 
116     def combine(self, rhs):
117         """
118         Append rhs to self if self contains compatible registers.
119 
120         Two circuits are compatible if they contain the same registers
121         or if they contain different registers with unique names. The
122         returned circuit will contain all unique registers between both
123         circuits.
124 
125         Return self + rhs as a new object.
126         """
127         combined_registers = []
128         # Check registers in LHS are compatible with RHS
129         for name, register in self.regs.items():
130             if name in rhs.regs and register != rhs.regs[name]:
131                 raise QISKitError("circuits are not compatible")
132             else:
133                 combined_registers.append(register)
134         # Add registers in RHS not in LHS
135         complement_registers = set(rhs.regs) - set(self.regs)
136         for name in complement_registers:
137             combined_registers.append(rhs.regs[name])
138         # Make new circuit with combined registers
139         circuit = QuantumCircuit(*combined_registers)
140         for gate in itertools.chain(self.data, rhs.data):
141             gate.reapply(circuit)
142         return circuit
143 
144     def extend(self, rhs):
145         """
146         Append rhs to self if self if it contains compatible registers.
147 
148         Two circuits are compatible if they contain the same registers
149         or if they contain different registers with unique names. The
150         returned circuit will contain all unique registers between both
151         circuits.
152 
153         Modify and return self.
154         """
155         # Check compatibility and add new registers
156         for name, register in rhs.regs.items():
157             if name not in self.regs:
158                 self.add(register)
159             elif name in self.regs and register != self.regs[name]:
160                 raise QISKitError("circuits are not compatible")
161 
162         # Add new gates
163         for gate in rhs.data:
164             gate.reapply(self)
165         return self
166 
167     def __add__(self, rhs):
168         """Overload + to implement self.concatenate."""
169         return self.combine(rhs)
170 
171     def __iadd__(self, rhs):
172         """Overload += to implement self.extend."""
173         return self.extend(rhs)
174 
175     def __len__(self):
176         """Return number of operations in circuit."""
177         return len(self.data)
178 
179     def __getitem__(self, item):
180         """Return indexed operation."""
181         return self.data[item]
182 
183     def _attach(self, gate):
184         """Attach a gate."""
185         self.data.append(gate)
186         return gate
187 
188     def add(self, *regs):
189         """Add registers."""
190         for register in regs:
191             if not isinstance(register, Register):
192                 raise QISKitError("expected a register")
193             if register.name not in self.regs:
194                 self.regs[register.name] = register
195             else:
196                 raise QISKitError("register name \"%s\" already exists"
197                                   % register.name)
198 
199     def _check_qreg(self, register):
200         """Raise exception if r is not in this circuit or not qreg."""
201         if not isinstance(register, QuantumRegister):
202             raise QISKitError("expected quantum register")
203         if not self.has_register(register):
204             raise QISKitError(
205                 "register '%s' not in this circuit" %
206                 register.name)
207 
208     def _check_qubit(self, qubit):
209         """Raise exception if qubit is not in this circuit or bad format."""
210         if not isinstance(qubit, tuple):
211             raise QISKitError("%s is not a tuple."
212                               "A qubit should be formated as a tuple." % str(qubit))
213         if not len(qubit) == 2:
214             raise QISKitError("%s is not a tuple with two elements, but %i instead" % len(qubit))
215         if not isinstance(qubit[1], int):
216             raise QISKitError("The second element of a tuple defining a qubit should be an int:"
217                               "%s was found instead" % type(qubit[1]).__name__)
218         self._check_qreg(qubit[0])
219         qubit[0].check_range(qubit[1])
220 
221     def _check_creg(self, register):
222         """Raise exception if r is not in this circuit or not creg."""
223         if not isinstance(register, ClassicalRegister):
224             raise QISKitError("expected classical register")
225         if not self.has_register(register):
226             raise QISKitError(
227                 "register '%s' not in this circuit" %
228                 register.name)
229 
230     def _check_dups(self, qubits):
231         """Raise exception if list of qubits contains duplicates."""
232         squbits = set(qubits)
233         if len(squbits) != len(qubits):
234             raise QISKitError("duplicate qubit arguments")
235 
236     def _gate_string(self, name):
237         """Return a QASM string for the named gate."""
238         out = ""
239         if self.definitions[name]["opaque"]:
240             out = "opaque " + name
241         else:
242             out = "gate " + name
243         if self.definitions[name]["n_args"] > 0:
244             out += "(" + ",".join(self.definitions[name]["args"]) + ")"
245         out += " " + ",".join(self.definitions[name]["bits"])
246         if self.definitions[name]["opaque"]:
247             out += ";"
248         else:
249             out += "\n{\n" + self.definitions[name]["body"].qasm() + "}\n"
250         return out
251 
252     def qasm(self):
253         """Return OPENQASM string."""
254         string_temp = self.header + "\n"
255         for gate_name in self.definitions:
256             if self.definitions[gate_name]["print"]:
257                 string_temp += self._gate_string(gate_name)
258         for register in self.regs.values():
259             string_temp += register.qasm() + "\n"
260         for instruction in self.data:
261             string_temp += instruction.qasm() + "\n"
262         return string_temp
263 
264     def measure(self, qubit, cbit):
265         """Measure quantum bit into classical bit (tuples).
266 
267         Returns:
268             qiskit.Gate: the attached measure gate.
269 
270         Raises:
271             QISKitError: if qubit is not in this circuit or bad format;
272                 if cbit is not in this circuit or not creg.
273         """
274         if isinstance(qubit, QuantumRegister) and \
275            isinstance(cbit, ClassicalRegister) and len(qubit) == len(cbit):
276             instructions = InstructionSet()
277             for i in range(qubit.size):
278                 instructions.add(self.measure((qubit, i), (cbit, i)))
279             return instructions
280 
281         self._check_qubit(qubit)
282         self._check_creg(cbit[0])
283         cbit[0].check_range(cbit[1])
284         return self._attach(Measure(qubit, cbit, self))
285 
286     def reset(self, quantum_register):
287         """Reset q."""
288         if isinstance(quantum_register, QuantumRegister):
289             instructions = InstructionSet()
290             for sizes in range(quantum_register.size):
291                 instructions.add(self.reset((quantum_register, sizes)))
292             return instructions
293         self._check_qubit(quantum_register)
294         return self._attach(Reset(quantum_register, self))
295
```
--- END FILES ---

Please first localize the bug based on the issue statement, and then generate a patch according to the `git diff` format fenced by three backticks.

Here is an example:

```diff
diff --git a/examples/server_async.py b/examples/server_async.py
--- a/examples/server_async.py
+++ b/examples/server_async.py
@@ -313,4 +313,4 @@
 
 
 if __name__ == "__main__":
-    asyncio.run(run_async_server("."), debug=True)
+    asyncio.run(run_async_server(), debug=True)
diff --git a/examples/server_sync.py b/examples/server_sync.py
--- a/examples/server_sync.py
+++ b/examples/server_sync.py
@@ -313,5 +313,5 @@
 
 
 if __name__ == "__main__":
-    server = run_sync_server(".")
+    server = run_sync_server()
     server.shutdown()

```

diff --git a/qiskit/_quantumcircuit.py b/qiskit/_quantumcircuit.py
--- a/qiskit/_quantumcircuit.py
+++ b/qiskit/_quantumcircuit.py
@@ -51,9 +51,9 @@
         Raises:
             QISKitError: if the circuit name, if given, is not valid.
         """
-        self._increment_instances()
         if name is None:
             name = self.cls_prefix() + str(self.cls_instances())
+        self._increment_instances()
 
         if not isinstance(name, str):
             raise QISKitError("The circuit name should be a string "

{"golden_diff": "diff --git a/qiskit/_quantumcircuit.py b/qiskit/_quantumcircuit.py\n--- a/qiskit/_quantumcircuit.py\n+++ b/qiskit/_quantumcircuit.py\n@@ -51,9 +51,9 @@\n         Raises:\n             QISKitError: if the circuit name, if given, is not valid.\n         \"\"\"\n-        self._increment_instances()\n         if name is None:\n             name = self.cls_prefix() + str(self.cls_instances())\n+        self._increment_instances()\n \n         if not isinstance(name, str):\n             raise QISKitError(\"The circuit name should be a string \"\n", "issue": "Default circuit names are not zero-based\n<!-- \u26a0\ufe0f If you do not respect this template, your issue will be closed -->\r\n<!-- \u26a0\ufe0f Make sure to browse the opened and closed issues -->\r\n\r\n### Informations\r\n\r\n- **Qiskit Terra version**: latest\r\n- **Python version**: 3.7\r\n- **Operating system**: OSX\r\n\r\n### What is the current behavior?\r\nWhen creating a quantum circuit with no name, the default name is set to `circuitX`.  Currently, `X` starts from `1` rather than `0`, and can cause some confusion when trying to index circuits by name.\r\n\r\n\r\n### Steps to reproduce the problem\r\n```python\r\nfrom qiskit import *\r\nq = QuantumRegister(2, \"q\")\r\nc = ClassicalRegister(2, \"c\")\r\n# Create measurement subcircuit\r\nqc = QuantumCircuit(q,c)\r\nqc.name\r\n```\r\ngives `'circuit1'` for the initial circuit created.  It should be `'circuit0'` to coincide with the the indexing in Python.\r\n\r\n### What is the expected behavior?\r\n\r\n\r\n\r\n### Suggested solutions\r\n\r\n\r\n\n", "before_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright 2017, IBM.\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n\"\"\"\nQuantum circuit object.\n\"\"\"\nimport itertools\nfrom collections import OrderedDict\nfrom ._qiskiterror import QISKitError\nfrom ._register import Register\nfrom ._quantumregister import QuantumRegister\nfrom ._classicalregister import ClassicalRegister\nfrom ._measure import Measure\nfrom ._reset import Reset\nfrom ._instructionset import InstructionSet\n\n\nclass QuantumCircuit(object):\n    \"\"\"Quantum circuit.\"\"\"\n    instances = 0\n    prefix = 'circuit'\n\n    # Class variable OPENQASM header\n    header = \"OPENQASM 2.0;\"\n\n    # Class variable with gate definitions\n    # This is a dict whose values are dicts with the\n    # following keys:\n    #   \"print\" = True or False\n    #   \"opaque\" = True or False\n    #   \"n_args\" = number of real parameters\n    #   \"n_bits\" = number of qubits\n    #   \"args\"   = list of parameter names\n    #   \"bits\"   = list of qubit names\n    #   \"body\"   = GateBody AST node\n    definitions = OrderedDict()\n\n    def __init__(self, *regs, name=None):\n        \"\"\"Create a new circuit.\n\n        Args:\n            *regs (Registers): registers to include in the circuit.\n            name (str or None): the name of the quantum circuit. If\n                None, an automatically generated identifier will be\n                assigned.\n\n        Raises:\n            QISKitError: if the circuit name, if given, is not valid.\n        \"\"\"\n        self._increment_instances()\n        if name is None:\n            name = self.cls_prefix() + str(self.cls_instances())\n\n        if not isinstance(name, str):\n            raise QISKitError(\"The circuit name should be a string \"\n                              \"(or None for autogenerate a name).\")\n\n        self.name = name\n        # Data contains a list of instructions in the order they were applied.\n        self.data = []\n        # This is a map of registers bound to this circuit, by name.\n        self.regs = OrderedDict()\n        self.add(*regs)\n\n    @classmethod\n    def _increment_instances(cls):\n        cls.instances += 1\n\n    @classmethod\n    def cls_instances(cls):\n        \"\"\"Return the current number of instances of this class,\n        useful for auto naming.\"\"\"\n        return cls.instances\n\n    @classmethod\n    def cls_prefix(cls):\n        \"\"\"Return the prefix to use for auto naming.\"\"\"\n        return cls.prefix\n\n    def has_register(self, register):\n        \"\"\"\n        Test if this circuit has the register r.\n\n        Return True or False.\n        \"\"\"\n        if register.name in self.regs:\n            registers = self.regs[register.name]\n            if registers.size == register.size:\n                if ((isinstance(register, QuantumRegister) and\n                     isinstance(registers, QuantumRegister)) or\n                        (isinstance(register, ClassicalRegister) and\n                         isinstance(registers, ClassicalRegister))):\n                    return True\n        return False\n\n    def get_qregs(self):\n        \"\"\"Get the qregs from the registers.\"\"\"\n        qregs = OrderedDict()\n        for name, register in self.regs.items():\n            if isinstance(register, QuantumRegister):\n                qregs[name] = register\n        return qregs\n\n    def get_cregs(self):\n        \"\"\"Get the cregs from the registers.\"\"\"\n        cregs = OrderedDict()\n        for name, register in self.regs.items():\n            if isinstance(register, ClassicalRegister):\n                cregs[name] = register\n        return cregs\n\n    def combine(self, rhs):\n        \"\"\"\n        Append rhs to self if self contains compatible registers.\n\n        Two circuits are compatible if they contain the same registers\n        or if they contain different registers with unique names. The\n        returned circuit will contain all unique registers between both\n        circuits.\n\n        Return self + rhs as a new object.\n        \"\"\"\n        combined_registers = []\n        # Check registers in LHS are compatible with RHS\n        for name, register in self.regs.items():\n            if name in rhs.regs and register != rhs.regs[name]:\n                raise QISKitError(\"circuits are not compatible\")\n            else:\n                combined_registers.append(register)\n        # Add registers in RHS not in LHS\n        complement_registers = set(rhs.regs) - set(self.regs)\n        for name in complement_registers:\n            combined_registers.append(rhs.regs[name])\n        # Make new circuit with combined registers\n        circuit = QuantumCircuit(*combined_registers)\n        for gate in itertools.chain(self.data, rhs.data):\n            gate.reapply(circuit)\n        return circuit\n\n    def extend(self, rhs):\n        \"\"\"\n        Append rhs to self if self if it contains compatible registers.\n\n        Two circuits are compatible if they contain the same registers\n        or if they contain different registers with unique names. The\n        returned circuit will contain all unique registers between both\n        circuits.\n\n        Modify and return self.\n        \"\"\"\n        # Check compatibility and add new registers\n        for name, register in rhs.regs.items():\n            if name not in self.regs:\n                self.add(register)\n            elif name in self.regs and register != self.regs[name]:\n                raise QISKitError(\"circuits are not compatible\")\n\n        # Add new gates\n        for gate in rhs.data:\n            gate.reapply(self)\n        return self\n\n    def __add__(self, rhs):\n        \"\"\"Overload + to implement self.concatenate.\"\"\"\n        return self.combine(rhs)\n\n    def __iadd__(self, rhs):\n        \"\"\"Overload += to implement self.extend.\"\"\"\n        return self.extend(rhs)\n\n    def __len__(self):\n        \"\"\"Return number of operations in circuit.\"\"\"\n        return len(self.data)\n\n    def __getitem__(self, item):\n        \"\"\"Return indexed operation.\"\"\"\n        return self.data[item]\n\n    def _attach(self, gate):\n        \"\"\"Attach a gate.\"\"\"\n        self.data.append(gate)\n        return gate\n\n    def add(self, *regs):\n        \"\"\"Add registers.\"\"\"\n        for register in regs:\n            if not isinstance(register, Register):\n                raise QISKitError(\"expected a register\")\n            if register.name not in self.regs:\n                self.regs[register.name] = register\n            else:\n                raise QISKitError(\"register name \\\"%s\\\" already exists\"\n                                  % register.name)\n\n    def _check_qreg(self, register):\n        \"\"\"Raise exception if r is not in this circuit or not qreg.\"\"\"\n        if not isinstance(register, QuantumRegister):\n            raise QISKitError(\"expected quantum register\")\n        if not self.has_register(register):\n            raise QISKitError(\n                \"register '%s' not in this circuit\" %\n                register.name)\n\n    def _check_qubit(self, qubit):\n        \"\"\"Raise exception if qubit is not in this circuit or bad format.\"\"\"\n        if not isinstance(qubit, tuple):\n            raise QISKitError(\"%s is not a tuple.\"\n                              \"A qubit should be formated as a tuple.\" % str(qubit))\n        if not len(qubit) == 2:\n            raise QISKitError(\"%s is not a tuple with two elements, but %i instead\" % len(qubit))\n        if not isinstance(qubit[1], int):\n            raise QISKitError(\"The second element of a tuple defining a qubit should be an int:\"\n                              \"%s was found instead\" % type(qubit[1]).__name__)\n        self._check_qreg(qubit[0])\n        qubit[0].check_range(qubit[1])\n\n    def _check_creg(self, register):\n        \"\"\"Raise exception if r is not in this circuit or not creg.\"\"\"\n        if not isinstance(register, ClassicalRegister):\n            raise QISKitError(\"expected classical register\")\n        if not self.has_register(register):\n            raise QISKitError(\n                \"register '%s' not in this circuit\" %\n                register.name)\n\n    def _check_dups(self, qubits):\n        \"\"\"Raise exception if list of qubits contains duplicates.\"\"\"\n        squbits = set(qubits)\n        if len(squbits) != len(qubits):\n            raise QISKitError(\"duplicate qubit arguments\")\n\n    def _gate_string(self, name):\n        \"\"\"Return a QASM string for the named gate.\"\"\"\n        out = \"\"\n        if self.definitions[name][\"opaque\"]:\n            out = \"opaque \" + name\n        else:\n            out = \"gate \" + name\n        if self.definitions[name][\"n_args\"] > 0:\n            out += \"(\" + \",\".join(self.definitions[name][\"args\"]) + \")\"\n        out += \" \" + \",\".join(self.definitions[name][\"bits\"])\n        if self.definitions[name][\"opaque\"]:\n            out += \";\"\n        else:\n            out += \"\\n{\\n\" + self.definitions[name][\"body\"].qasm() + \"}\\n\"\n        return out\n\n    def qasm(self):\n        \"\"\"Return OPENQASM string.\"\"\"\n        string_temp = self.header + \"\\n\"\n        for gate_name in self.definitions:\n            if self.definitions[gate_name][\"print\"]:\n                string_temp += self._gate_string(gate_name)\n        for register in self.regs.values():\n            string_temp += register.qasm() + \"\\n\"\n        for instruction in self.data:\n            string_temp += instruction.qasm() + \"\\n\"\n        return string_temp\n\n    def measure(self, qubit, cbit):\n        \"\"\"Measure quantum bit into classical bit (tuples).\n\n        Returns:\n            qiskit.Gate: the attached measure gate.\n\n        Raises:\n            QISKitError: if qubit is not in this circuit or bad format;\n                if cbit is not in this circuit or not creg.\n        \"\"\"\n        if isinstance(qubit, QuantumRegister) and \\\n           isinstance(cbit, ClassicalRegister) and len(qubit) == len(cbit):\n            instructions = InstructionSet()\n            for i in range(qubit.size):\n                instructions.add(self.measure((qubit, i), (cbit, i)))\n            return instructions\n\n        self._check_qubit(qubit)\n        self._check_creg(cbit[0])\n        cbit[0].check_range(cbit[1])\n        return self._attach(Measure(qubit, cbit, self))\n\n    def reset(self, quantum_register):\n        \"\"\"Reset q.\"\"\"\n        if isinstance(quantum_register, QuantumRegister):\n            instructions = InstructionSet()\n            for sizes in range(quantum_register.size):\n                instructions.add(self.reset((quantum_register, sizes)))\n            return instructions\n        self._check_qubit(quantum_register)\n        return self._attach(Reset(quantum_register, self))\n", "path": "qiskit/_quantumcircuit.py"}], "after_files": [{"content": "# -*- coding: utf-8 -*-\n\n# Copyright 2017, IBM.\n#\n# This source code is licensed under the Apache License, Version 2.0 found in\n# the LICENSE.txt file in the root directory of this source tree.\n\n\"\"\"\nQuantum circuit object.\n\"\"\"\nimport itertools\nfrom collections import OrderedDict\nfrom ._qiskiterror import QISKitError\nfrom ._register import Register\nfrom ._quantumregister import QuantumRegister\nfrom ._classicalregister import ClassicalRegister\nfrom ._measure import Measure\nfrom ._reset import Reset\nfrom ._instructionset import InstructionSet\n\n\nclass QuantumCircuit(object):\n    \"\"\"Quantum circuit.\"\"\"\n    instances = 0\n    prefix = 'circuit'\n\n    # Class variable OPENQASM header\n    header = \"OPENQASM 2.0;\"\n\n    # Class variable with gate definitions\n    # This is a dict whose values are dicts with the\n    # following keys:\n    #   \"print\" = True or False\n    #   \"opaque\" = True or False\n    #   \"n_args\" = number of real parameters\n    #   \"n_bits\" = number of qubits\n    #   \"args\"   = list of parameter names\n    #   \"bits\"   = list of qubit names\n    #   \"body\"   = GateBody AST node\n    definitions = OrderedDict()\n\n    def __init__(self, *regs, name=None):\n        \"\"\"Create a new circuit.\n\n        Args:\n            *regs (Registers): registers to include in the circuit.\n            name (str or None): the name of the quantum circuit. If\n                None, an automatically generated identifier will be\n                assigned.\n\n        Raises:\n            QISKitError: if the circuit name, if given, is not valid.\n        \"\"\"\n        if name is None:\n            name = self.cls_prefix() + str(self.cls_instances())\n        self._increment_instances()\n\n        if not isinstance(name, str):\n            raise QISKitError(\"The circuit name should be a string \"\n                              \"(or None for autogenerate a name).\")\n\n        self.name = name\n        # Data contains a list of instructions in the order they were applied.\n        self.data = []\n        # This is a map of registers bound to this circuit, by name.\n        self.regs = OrderedDict()\n        self.add(*regs)\n\n    @classmethod\n    def _increment_instances(cls):\n        cls.instances += 1\n\n    @classmethod\n    def cls_instances(cls):\n        \"\"\"Return the current number of instances of this class,\n        useful for auto naming.\"\"\"\n        return cls.instances\n\n    @classmethod\n    def cls_prefix(cls):\n        \"\"\"Return the prefix to use for auto naming.\"\"\"\n        return cls.prefix\n\n    def has_register(self, register):\n        \"\"\"\n        Test if this circuit has the register r.\n\n        Return True or False.\n        \"\"\"\n        if register.name in self.regs:\n            registers = self.regs[register.name]\n            if registers.size == register.size:\n                if ((isinstance(register, QuantumRegister) and\n                     isinstance(registers, QuantumRegister)) or\n                        (isinstance(register, ClassicalRegister) and\n                         isinstance(registers, ClassicalRegister))):\n                    return True\n        return False\n\n    def get_qregs(self):\n        \"\"\"Get the qregs from the registers.\"\"\"\n        qregs = OrderedDict()\n        for name, register in self.regs.items():\n            if isinstance(register, QuantumRegister):\n                qregs[name] = register\n        return qregs\n\n    def get_cregs(self):\n        \"\"\"Get the cregs from the registers.\"\"\"\n        cregs = OrderedDict()\n        for name, register in self.regs.items():\n            if isinstance(register, ClassicalRegister):\n                cregs[name] = register\n        return cregs\n\n    def combine(self, rhs):\n        \"\"\"\n        Append rhs to self if self contains compatible registers.\n\n        Two circuits are compatible if they contain the same registers\n        or if they contain different registers with unique names. The\n        returned circuit will contain all unique registers between both\n        circuits.\n\n        Return self + rhs as a new object.\n        \"\"\"\n        combined_registers = []\n        # Check registers in LHS are compatible with RHS\n        for name, register in self.regs.items():\n            if name in rhs.regs and register != rhs.regs[name]:\n                raise QISKitError(\"circuits are not compatible\")\n            else:\n                combined_registers.append(register)\n        # Add registers in RHS not in LHS\n        complement_registers = set(rhs.regs) - set(self.regs)\n        for name in complement_registers:\n            combined_registers.append(rhs.regs[name])\n        # Make new circuit with combined registers\n        circuit = QuantumCircuit(*combined_registers)\n        for gate in itertools.chain(self.data, rhs.data):\n            gate.reapply(circuit)\n        return circuit\n\n    def extend(self, rhs):\n        \"\"\"\n        Append rhs to self if self if it contains compatible registers.\n\n        Two circuits are compatible if they contain the same registers\n        or if they contain different registers with unique names. The\n        returned circuit will contain all unique registers between both\n        circuits.\n\n        Modify and return self.\n        \"\"\"\n        # Check compatibility and add new registers\n        for name, register in rhs.regs.items():\n            if name not in self.regs:\n                self.add(register)\n            elif name in self.regs and register != self.regs[name]:\n                raise QISKitError(\"circuits are not compatible\")\n\n        # Add new gates\n        for gate in rhs.data:\n            gate.reapply(self)\n        return self\n\n    def __add__(self, rhs):\n        \"\"\"Overload + to implement self.concatenate.\"\"\"\n        return self.combine(rhs)\n\n    def __iadd__(self, rhs):\n        \"\"\"Overload += to implement self.extend.\"\"\"\n        return self.extend(rhs)\n\n    def __len__(self):\n        \"\"\"Return number of operations in circuit.\"\"\"\n        return len(self.data)\n\n    def __getitem__(self, item):\n        \"\"\"Return indexed operation.\"\"\"\n        return self.data[item]\n\n    def _attach(self, gate):\n        \"\"\"Attach a gate.\"\"\"\n        self.data.append(gate)\n        return gate\n\n    def add(self, *regs):\n        \"\"\"Add registers.\"\"\"\n        for register in regs:\n            if not isinstance(register, Register):\n                raise QISKitError(\"expected a register\")\n            if register.name not in self.regs:\n                self.regs[register.name] = register\n            else:\n                raise QISKitError(\"register name \\\"%s\\\" already exists\"\n                                  % register.name)\n\n    def _check_qreg(self, register):\n        \"\"\"Raise exception if r is not in this circuit or not qreg.\"\"\"\n        if not isinstance(register, QuantumRegister):\n            raise QISKitError(\"expected quantum register\")\n        if not self.has_register(register):\n            raise QISKitError(\n                \"register '%s' not in this circuit\" %\n                register.name)\n\n    def _check_qubit(self, qubit):\n        \"\"\"Raise exception if qubit is not in this circuit or bad format.\"\"\"\n        if not isinstance(qubit, tuple):\n            raise QISKitError(\"%s is not a tuple.\"\n                              \"A qubit should be formated as a tuple.\" % str(qubit))\n        if not len(qubit) == 2:\n            raise QISKitError(\"%s is not a tuple with two elements, but %i instead\" % len(qubit))\n        if not isinstance(qubit[1], int):\n            raise QISKitError(\"The second element of a tuple defining a qubit should be an int:\"\n                              \"%s was found instead\" % type(qubit[1]).__name__)\n        self._check_qreg(qubit[0])\n        qubit[0].check_range(qubit[1])\n\n    def _check_creg(self, register):\n        \"\"\"Raise exception if r is not in this circuit or not creg.\"\"\"\n        if not isinstance(register, ClassicalRegister):\n            raise QISKitError(\"expected classical register\")\n        if not self.has_register(register):\n            raise QISKitError(\n                \"register '%s' not in this circuit\" %\n                register.name)\n\n    def _check_dups(self, qubits):\n        \"\"\"Raise exception if list of qubits contains duplicates.\"\"\"\n        squbits = set(qubits)\n        if len(squbits) != len(qubits):\n            raise QISKitError(\"duplicate qubit arguments\")\n\n    def _gate_string(self, name):\n        \"\"\"Return a QASM string for the named gate.\"\"\"\n        out = \"\"\n        if self.definitions[name][\"opaque\"]:\n            out = \"opaque \" + name\n        else:\n            out = \"gate \" + name\n        if self.definitions[name][\"n_args\"] > 0:\n            out += \"(\" + \",\".join(self.definitions[name][\"args\"]) + \")\"\n        out += \" \" + \",\".join(self.definitions[name][\"bits\"])\n        if self.definitions[name][\"opaque\"]:\n            out += \";\"\n        else:\n            out += \"\\n{\\n\" + self.definitions[name][\"body\"].qasm() + \"}\\n\"\n        return out\n\n    def qasm(self):\n        \"\"\"Return OPENQASM string.\"\"\"\n        string_temp = self.header + \"\\n\"\n        for gate_name in self.definitions:\n            if self.definitions[gate_name][\"print\"]:\n                string_temp += self._gate_string(gate_name)\n        for register in self.regs.values():\n            string_temp += register.qasm() + \"\\n\"\n        for instruction in self.data:\n            string_temp += instruction.qasm() + \"\\n\"\n        return string_temp\n\n    def measure(self, qubit, cbit):\n        \"\"\"Measure quantum bit into classical bit (tuples).\n\n        Returns:\n            qiskit.Gate: the attached measure gate.\n\n        Raises:\n            QISKitError: if qubit is not in this circuit or bad format;\n                if cbit is not in this circuit or not creg.\n        \"\"\"\n        if isinstance(qubit, QuantumRegister) and \\\n           isinstance(cbit, ClassicalRegister) and len(qubit) == len(cbit):\n            instructions = InstructionSet()\n            for i in range(qubit.size):\n                instructions.add(self.measure((qubit, i), (cbit, i)))\n            return instructions\n\n        self._check_qubit(qubit)\n        self._check_creg(cbit[0])\n        cbit[0].check_range(cbit[1])\n        return self._attach(Measure(qubit, cbit, self))\n\n    def reset(self, quantum_register):\n        \"\"\"Reset q.\"\"\"\n        if isinstance(quantum_register, QuantumRegister):\n            instructions = InstructionSet()\n            for sizes in range(quantum_register.size):\n                instructions.add(self.reset((quantum_register, sizes)))\n            return instructions\n        self._check_qubit(quantum_register)\n        return self._attach(Reset(quantum_register, self))\n", "path": "qiskit/_quantumcircuit.py"}]}