diff --git "a/chunk_128.jsonl" "b/chunk_128.jsonl"
new file mode 100644--- /dev/null
+++ "b/chunk_128.jsonl"
@@ -0,0 +1,3000 @@
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nreport on GitHub that the branch is failing to build at the specified commit.", "response": "def report(self, branch, commit, infourl=None):\n \"\"\"Report on GitHub that the specified branch is failing to build at\n the specified commit. The method will open an issue indicating that\n the branch is failing. If there is an issue already open, it will add a\n comment avoiding to report twice about the same failure.\n\n Args:\n branch (str): branch name to report about.\n commit (str): commit hash at which the build fails.\n infourl (str): URL with extra info about the failure such as the\n build logs.\n \"\"\"\n issue_number = self._get_report_issue_number()\n if issue_number:\n self._report_as_comment(issue_number, branch, commit, infourl)\n else:\n self._report_as_issue(branch, commit, infourl)"}
+{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef iplot_state_paulivec(rho, figsize=None, slider=False, show_legend=False):\n\n # HTML\n html_template = Template(\"\"\"\n
\n
\n \n \"\"\")\n\n # JavaScript\n javascript_template = Template(\"\"\"\n \n \"\"\")\n rho = _validate_input_state(rho)\n # set default figure size if none given\n if figsize is None:\n figsize = (7, 5)\n\n options = {'width': figsize[0], 'height': figsize[1],\n 'slider': int(slider), 'show_legend': int(show_legend)}\n\n # Process data and execute\n div_number = str(time.time())\n div_number = re.sub('[.]', '', div_number)\n\n data_to_plot = []\n rho_data = process_data(rho)\n data_to_plot.append(dict(\n data=rho_data\n ))\n\n html = html_template.substitute({\n 'divNumber': div_number\n })\n\n javascript = javascript_template.substitute({\n 'divNumber': div_number,\n 'executions': data_to_plot,\n 'options': options\n })\n\n display(HTML(html + javascript))", "response": "Create a paulivec representation of the state vector or density matrix."}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nplot the state vector or density matrix of a quantum state.", "response": "def iplot_state(quantum_state, method='city', figsize=None):\n \"\"\"Plot the quantum state.\n\n Args:\n quantum_state (ndarray): statevector or density matrix\n representation of a quantum state.\n method (str): Plotting method to use.\n figsize (tuple): Figure size in pixels.\n\n Raises:\n VisualizationError: if the input is not a statevector or density\n matrix, or if the state is not an multi-qubit quantum state.\n \"\"\"\n warnings.warn(\"iplot_state is deprecated, and will be removed in \\\n the 0.9 release. Use the iplot_state_ * functions \\\n instead.\",\n DeprecationWarning)\n rho = _validate_input_state(quantum_state)\n if method == \"city\":\n iplot_state_city(rho, figsize=figsize)\n elif method == \"paulivec\":\n iplot_state_paulivec(rho, figsize=figsize)\n elif method == \"qsphere\":\n iplot_state_qsphere(rho, figsize=figsize)\n elif method == \"bloch\":\n iplot_bloch_multivector(rho, figsize=figsize)\n elif method == \"hinton\":\n iplot_state_hinton(rho, figsize=figsize)\n else:\n raise VisualizationError('Invalid plot state method.')"}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\napplies RZZ to circuit.", "response": "def rzz(self, theta, qubit1, qubit2):\n \"\"\"Apply RZZ to circuit.\"\"\"\n return self.append(RZZGate(theta), [qubit1, qubit2], [])"}
+{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\napply Fredkin to circuit.", "response": "def cswap(self, ctl, tgt1, tgt2):\n \"\"\"Apply Fredkin to circuit.\"\"\"\n return self.append(FredkinGate(), [ctl, tgt1, tgt2], [])"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ndefining the internal state of the object.", "response": "def _define(self):\n \"\"\"\n gate cswap a,b,c\n { cx c,b;\n ccx a,b,c;\n cx c,b;\n }\n \"\"\"\n definition = []\n q = QuantumRegister(3, \"q\")\n rule = [\n (CnotGate(), [q[2], q[1]], []),\n (ToffoliGate(), [q[0], q[1], q[2]], []),\n (CnotGate(), [q[2], q[1]], [])\n ]\n for inst in rule:\n definition.append(inst)\n self.definition = definition"}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _initialize_backend_prop(self):\n backend_prop = self.backend_prop\n for ginfo in backend_prop.gates:\n if ginfo.gate == 'cx':\n for item in ginfo.parameters:\n if item.name == 'gate_error':\n g_reliab = 1.0 - item.value\n break\n else:\n g_reliab = 1.0\n swap_reliab = -math.log(pow(g_reliab, 3))\n self.swap_graph.add_edge(ginfo.qubits[0], ginfo.qubits[1], weight=swap_reliab)\n self.swap_graph.add_edge(ginfo.qubits[1], ginfo.qubits[0], weight=swap_reliab)\n self.cx_errors[(ginfo.qubits[0], ginfo.qubits[1])] = g_reliab\n self.gate_list.append((ginfo.qubits[0], ginfo.qubits[1]))\n idx = 0\n for q in backend_prop.qubits:\n for nduv in q:\n if nduv.name == 'readout_error':\n self.readout_errors[idx] = 1.0 - nduv.value\n self.available_hw_qubits.append(idx)\n idx += 1\n for edge in self.cx_errors:\n self.gate_cost[edge] = self.cx_errors[edge] * self.readout_errors[edge[0]] *\\\n self.readout_errors[edge[1]]\n self.swap_paths, swap_costs_temp = nx.algorithms.shortest_paths.dense.\\\n floyd_warshall_predecessor_and_distance(self.swap_graph, weight='weight')\n for i in swap_costs_temp:\n self.swap_costs[i] = {}\n for j in swap_costs_temp[i]:\n if (i, j) in self.cx_errors:\n self.swap_costs[i][j] = self.cx_errors[(i, j)]\n elif (j, i) in self.cx_errors:\n self.swap_costs[i][j] = self.cx_errors[(j, i)]\n else:\n best_reliab = 0.0\n for n in self.swap_graph.neighbors(j):\n if (n, j) in self.cx_errors:\n reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(n, j)]\n else:\n reliab = math.exp(-swap_costs_temp[i][n])*self.cx_errors[(j, n)]\n if reliab > best_reliab:\n best_reliab = reliab\n self.swap_costs[i][j] = best_reliab", "response": "Initialize the internal state of the backend properties."}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _create_program_graph(self, dag):\n idx = 0\n for q in dag.qubits():\n self.qarg_to_id[q[0].name + str(q[1])] = idx\n idx += 1\n for gate in dag.twoQ_gates():\n qid1 = self._qarg_to_id(gate.qargs[0])\n qid2 = self._qarg_to_id(gate.qargs[1])\n min_q = min(qid1, qid2)\n max_q = max(qid1, qid2)\n edge_weight = 1\n if self.prog_graph.has_edge(min_q, max_q):\n edge_weight = self.prog_graph[min_q][max_q]['weight'] + 1\n self.prog_graph.add_edge(min_q, max_q, weight=edge_weight)\n return idx", "response": "Create the program graph for the given dag."}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _select_next_edge(self):\n for edge in self.pending_program_edges:\n q1_mapped = edge[0] in self.prog2hw\n q2_mapped = edge[1] in self.prog2hw\n assert not (q1_mapped and q2_mapped)\n if q1_mapped or q2_mapped:\n return edge\n return self.pending_program_edges[0]", "response": "Select next edge in the list of pending program edges."}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _select_best_remaining_cx(self):\n candidates = []\n for gate in self.gate_list:\n chk1 = gate[0] in self.available_hw_qubits\n chk2 = gate[1] in self.available_hw_qubits\n if chk1 and chk2:\n candidates.append(gate)\n best_reliab = 0\n best_item = None\n for item in candidates:\n if self.gate_cost[item] > best_reliab:\n best_reliab = self.gate_cost[item]\n best_item = item\n return best_item", "response": "Select the best remaining CNOT in the hardware for the next program edge."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nselect the best available hardware qubit for the next program qubit.", "response": "def _select_best_remaining_qubit(self, prog_qubit):\n \"\"\"\n Select the best remaining hardware qubit for the next program qubit.\n \"\"\"\n reliab_store = {}\n for hw_qubit in self.available_hw_qubits:\n reliab = 1\n for n in self.prog_graph.neighbors(prog_qubit):\n if n in self.prog2hw:\n reliab *= self.swap_costs[self.prog2hw[n]][hw_qubit]\n reliab *= self.readout_errors[hw_qubit]\n reliab_store[hw_qubit] = reliab\n max_reliab = 0\n best_hw_qubit = None\n for hw_qubit in reliab_store:\n if reliab_store[hw_qubit] > max_reliab:\n max_reliab = reliab_store[hw_qubit]\n best_hw_qubit = hw_qubit\n return best_hw_qubit"}
+{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef run(self, dag):\n self._initialize_backend_prop()\n num_qubits = self._create_program_graph(dag)\n if num_qubits > len(self.swap_graph):\n raise TranspilerError('Number of qubits greater than device.')\n for end1, end2, _ in sorted(self.prog_graph.edges(data=True),\n key=lambda x: x[2]['weight'], reverse=True):\n self.pending_program_edges.append((end1, end2))\n while self.pending_program_edges:\n edge = self._select_next_edge()\n q1_mapped = edge[0] in self.prog2hw\n q2_mapped = edge[1] in self.prog2hw\n if (not q1_mapped) and (not q2_mapped):\n best_hw_edge = self._select_best_remaining_cx()\n self.prog2hw[edge[0]] = best_hw_edge[0]\n self.prog2hw[edge[1]] = best_hw_edge[1]\n self.available_hw_qubits.remove(best_hw_edge[0])\n self.available_hw_qubits.remove(best_hw_edge[1])\n elif not q1_mapped:\n best_hw_qubit = self._select_best_remaining_qubit(edge[0])\n self.prog2hw[edge[0]] = best_hw_qubit\n self.available_hw_qubits.remove(best_hw_qubit)\n else:\n best_hw_qubit = self._select_best_remaining_qubit(edge[1])\n self.prog2hw[edge[1]] = best_hw_qubit\n self.available_hw_qubits.remove(best_hw_qubit)\n new_edges = [x for x in self.pending_program_edges\n if not (x[0] in self.prog2hw and x[1] in self.prog2hw)]\n self.pending_program_edges = new_edges\n for qid in self.qarg_to_id.values():\n if qid not in self.prog2hw:\n self.prog2hw[qid] = self.available_hw_qubits[0]\n self.available_hw_qubits.remove(self.prog2hw[qid])\n layout = Layout()\n for q in dag.qubits():\n pid = self._qarg_to_id(q)\n hwid = self.prog2hw[pid]\n layout[(q[0], q[1])] = hwid\n self.property_set['layout'] = layout", "response": "Main method for the noise adaptive layout."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef instruction_list(self):\n instruction_list = []\n for instruction in self.data:\n if isinstance(instruction, CompositeGate):\n instruction_list.extend(instruction.instruction_list())\n else:\n instruction_list.append(instruction)\n return instruction_list", "response": "Return a list of instructions for this CompositeGate."}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nadding controls to this gate.", "response": "def q_if(self, *qregs):\n \"\"\"Add controls to this gate.\"\"\"\n self.data = [gate.q_if(qregs) for gate in self.data]\n return self"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef c_if(self, classical, val):\n self.data = [gate.c_if(classical, val) for gate in self.data]\n return self", "response": "Add classical control register."}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef is_unitary(self, atol=None, rtol=None):\n if atol is None:\n atol = self._atol\n if rtol is None:\n rtol = self._rtol\n return is_unitary_matrix(self._data, rtol=rtol, atol=atol)", "response": "Return True if operator is a unitary matrix."}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef conjugate(self):\n return Operator(\n np.conj(self.data), self.input_dims(), self.output_dims())", "response": "Return the conjugate of the operator."}
+{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn the transpose of the operator.", "response": "def transpose(self):\n \"\"\"Return the transpose of the operator.\"\"\"\n return Operator(\n np.transpose(self.data), self.input_dims(), self.output_dims())"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef power(self, n):\n if not isinstance(n, int):\n raise QiskitError(\"Can only take integer powers of Operator.\")\n if self.input_dims() != self.output_dims():\n raise QiskitError(\"Can only power with input_dims = output_dims.\")\n # Override base class power so we can implement more efficiently\n # using Numpy.matrix_power\n return Operator(\n np.linalg.matrix_power(self.data, n), self.input_dims(),\n self.output_dims())", "response": "Return the matrix power of the operator."}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef add(self, other):\n if not isinstance(other, Operator):\n other = Operator(other)\n if self.dim != other.dim:\n raise QiskitError(\"other operator has different dimensions.\")\n return Operator(self.data + other.data, self.input_dims(),\n self.output_dims())", "response": "Returns the operator self + other."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef multiply(self, other):\n if not isinstance(other, Number):\n raise QiskitError(\"other is not a number\")\n return Operator(other * self.data, self.input_dims(),\n self.output_dims())", "response": "Returns the operator self + other."}
+{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn the tensor shape of the matrix operator", "response": "def _shape(self):\n \"\"\"Return the tensor shape of the matrix operator\"\"\"\n return tuple(reversed(self.output_dims())) + tuple(\n reversed(self.input_dims()))"}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nevolve a state by the operator.", "response": "def _evolve(self, state, qargs=None):\n \"\"\"Evolve a quantum state by the operator.\n\n Args:\n state (QuantumState): The input statevector or density matrix.\n qargs (list): a list of QuantumState subsystem positions to apply\n the operator on.\n\n Returns:\n QuantumState: the output quantum state.\n\n Raises:\n QiskitError: if the operator dimension does not match the\n specified QuantumState subsystem dimensions.\n \"\"\"\n state = self._format_state(state)\n if qargs is None:\n if state.shape[0] != self._input_dim:\n raise QiskitError(\n \"Operator input dimension is not equal to state dimension.\"\n )\n if state.ndim == 1:\n # Return evolved statevector\n return np.dot(self.data, state)\n # Return evolved density matrix\n return np.dot(\n np.dot(self.data, state), np.transpose(np.conj(self.data)))\n # Subsystem evolution\n return self._evolve_subsystem(state, qargs)"}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nevolve a state by the operator on the subsystem.", "response": "def _evolve_subsystem(self, state, qargs):\n \"\"\"Evolve a quantum state by the operator.\n\n Args:\n state (QuantumState): The input statevector or density matrix.\n qargs (list): a list of QuantumState subsystem positions to apply\n the operator on.\n\n Returns:\n QuantumState: the output quantum state.\n\n Raises:\n QiskitError: if the operator dimension does not match the\n specified QuantumState subsystem dimensions.\n \"\"\"\n mat = np.reshape(self.data, self._shape)\n # Hack to assume state is a N-qubit state until a proper class for states\n # is in place\n state_size = len(state)\n state_dims = self._automatic_dims(None, state_size)\n if self.input_dims() != len(qargs) * (2,):\n raise QiskitError(\n \"Operator input dimensions are not compatible with state subsystem dimensions.\"\n )\n if state.ndim == 1:\n # Return evolved statevector\n tensor = np.reshape(state, state_dims)\n indices = [len(state_dims) - 1 - qubit for qubit in qargs]\n tensor = self._einsum_matmul(tensor, mat, indices)\n return np.reshape(tensor, state_size)\n # Return evolved density matrix\n tensor = np.reshape(state, 2 * state_dims)\n indices = [len(state_dims) - 1 - qubit for qubit in qargs]\n right_shift = len(state_dims)\n # Left multiply by operator\n tensor = self._einsum_matmul(tensor, mat, indices)\n # Right multiply by adjoint operator\n # We implement the transpose by doing left multiplication instead of right\n # in the _einsum_matmul function\n tensor = self._einsum_matmul(\n tensor, np.conj(mat), indices, shift=right_shift)\n return np.reshape(tensor, [state_size, state_size])"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nformatting input state so it is statevector or density matrix", "response": "def _format_state(self, state):\n \"\"\"Format input state so it is statevector or density matrix\"\"\"\n state = np.array(state)\n shape = state.shape\n ndim = state.ndim\n if ndim > 2:\n raise QiskitError('Input state is not a vector or matrix.')\n # Flatten column-vector to vector\n if ndim == 2:\n if shape[1] != 1 and shape[1] != shape[0]:\n raise QiskitError('Input state is not a vector or matrix.')\n if shape[1] == 1:\n # flatten colum-vector to vector\n state = np.reshape(state, shape[0])\n return state"}
+{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nconverts a QuantumCircuit or Instruction to an Operator.", "response": "def _instruction_to_operator(cls, instruction):\n \"\"\"Convert a QuantumCircuit or Instruction to an Operator.\"\"\"\n # Convert circuit to an instruction\n if isinstance(instruction, QuantumCircuit):\n instruction = instruction.to_instruction()\n # Initialize an identity operator of the correct size of the circuit\n op = Operator(np.eye(2 ** instruction.num_qubits))\n op._append_instruction(instruction)\n return op"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef _append_instruction(self, obj, qargs=None):\n if isinstance(obj, Instruction):\n mat = None\n if hasattr(obj, 'to_matrix'):\n # If instruction is a gate first we see if it has a\n # `to_matrix` definition and if so use that.\n try:\n mat = obj.to_matrix()\n except QiskitError:\n pass\n if mat is not None:\n # Perform the composition and inplace update the current state\n # of the operator\n op = self.compose(mat, qargs=qargs)\n self._data = op.data\n else:\n # If the instruction doesn't have a matrix defined we use its\n # circuit decomposition definition if it exists, otherwise we\n # cannot compose this gate and raise an error.\n if obj.definition is None:\n raise QiskitError('Cannot apply Instruction: {}'.format(obj.name))\n for instr, qregs, cregs in obj.definition:\n if cregs:\n raise QiskitError(\n 'Cannot apply instruction with classical registers: {}'.format(\n instr.name))\n # Get the integer position of the flat register\n new_qargs = [tup[1] for tup in qregs]\n self._append_instruction(instr, qargs=new_qargs)\n else:\n raise QiskitError('Input is not an instruction.')", "response": "Update the current Operator by apply an instruction."}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nmapping a DAGCircuit onto a CouplingGraph using swap gates.", "response": "def run(self, dag):\n \"\"\"Map a DAGCircuit onto a CouplingGraph using swap gates.\n\n Args:\n dag (DAGCircuit): input DAG circuit\n\n Returns:\n DAGCircuit: object containing a circuit equivalent to\n circuit_graph that respects couplings in coupling_map, and\n a layout dict mapping qubits of circuit_graph into qubits\n of coupling_map. The layout may differ from the initial_layout\n if the first layer of gates cannot be executed on the\n initial_layout.\n\n Raises:\n TranspilerError: if there was any error during the mapping or with the\n parameters.\n \"\"\"\n if dag.width() > self.coupling_map.size():\n raise TranspilerError(\"Not enough qubits in CouplingGraph\")\n\n # Schedule the input circuit\n layerlist = list(dag.layers())\n\n if self.initial_layout is None and self.property_set[\"layout\"]:\n self.initial_layout = self.property_set[\"layout\"]\n\n if self.initial_layout is not None:\n # update initial_layout from a user given dict{(regname,idx): (regname,idx)}\n # to an expected dict{(reg,idx): (reg,idx)}\n\n virtual_qubits = self.initial_layout.get_virtual_bits()\n self.initial_layout = {(v[0].name, v[1]): ('q', self.initial_layout[v]) for v in\n virtual_qubits}\n\n device_register = QuantumRegister(self.coupling_map.size(), 'q')\n initial_layout = {(dag.qregs[k[0]], k[1]): (device_register, v[1])\n for k, v in self.initial_layout.items()}\n # Check the input layout\n circ_qubits = dag.qubits()\n coup_qubits = [(QuantumRegister(self.coupling_map.size(), 'q'), wire) for wire in\n self.coupling_map.physical_qubits]\n qubit_subset = []\n for k, v in initial_layout.items():\n qubit_subset.append(v)\n if k not in circ_qubits:\n raise TranspilerError(\"initial_layout qubit %s[%d] not in input \"\n \"DAGCircuit\" % (k[0].name, k[1]))\n if v not in coup_qubits:\n raise TranspilerError(\"initial_layout qubit %s[%d] not in input \"\n \"CouplingGraph\" % (v[0].name, v[1]))\n else:\n # Supply a default layout\n qubit_subset = [(QuantumRegister(self.coupling_map.size(), 'q'), wire) for wire in\n self.coupling_map.physical_qubits]\n qubit_subset = qubit_subset[0:dag.width()]\n initial_layout = {a: b for a, b in zip(dag.qubits(), qubit_subset)}\n\n # Find swap circuit to preceed to each layer of input circuit\n layout = initial_layout.copy()\n\n # Construct an empty DAGCircuit with one qreg \"q\"\n # and the same set of cregs as the input circuit\n dagcircuit_output = DAGCircuit()\n dagcircuit_output.name = dag.name\n dagcircuit_output.add_qreg(QuantumRegister(self.coupling_map.size(), \"q\"))\n for creg in dag.cregs.values():\n dagcircuit_output.add_creg(creg)\n\n # Make a trivial wire mapping between the subcircuits\n # returned by swap_mapper_layer_update and the circuit\n # we are building\n identity_wire_map = {}\n q = QuantumRegister(self.coupling_map.size(), 'q')\n for j in range(self.coupling_map.size()):\n identity_wire_map[(q, j)] = (q, j)\n for creg in dag.cregs.values():\n for j in range(creg.size):\n identity_wire_map[(creg, j)] = (creg, j)\n\n first_layer = True # True until first layer is output\n\n # Iterate over layers\n for i, layer in enumerate(layerlist):\n\n # Attempt to find a permutation for this layer\n success_flag, best_circ, best_d, best_layout, trivial_flag \\\n = self.layer_permutation(layer[\"partition\"], layout, qubit_subset)\n\n # If this fails, try one gate at a time in this layer\n if not success_flag:\n serial_layerlist = list(layer[\"graph\"].serial_layers())\n\n # Go through each gate in the layer\n for j, serial_layer in enumerate(serial_layerlist):\n\n success_flag, best_circ, best_d, best_layout, trivial_flag \\\n = self.layer_permutation(serial_layer[\"partition\"], layout, qubit_subset)\n\n # Give up if we fail again\n if not success_flag:\n raise TranspilerError(\"swap_mapper failed: \" +\n \"layer %d, sublayer %d\" % (i, j))\n\n # If this layer is only single-qubit gates,\n # and we have yet to see multi-qubit gates,\n # continue to the next inner iteration\n if trivial_flag and first_layer:\n continue\n\n # Update the record of qubit positions for each inner iteration\n layout = best_layout\n # Update the QASM\n dagcircuit_output.compose_back(\n self.swap_mapper_layer_update(j,\n first_layer,\n best_layout,\n best_d,\n best_circ,\n serial_layerlist),\n identity_wire_map)\n # Update initial layout\n if first_layer:\n initial_layout = layout\n first_layer = False\n\n else:\n # Update the record of qubit positions for each iteration\n layout = best_layout\n\n # Update the QASM\n dagcircuit_output.compose_back(\n self.swap_mapper_layer_update(i,\n first_layer,\n best_layout,\n best_d,\n best_circ,\n layerlist),\n identity_wire_map)\n # Update initial layout\n if first_layer:\n initial_layout = layout\n first_layer = False\n\n # If first_layer is still set, the circuit only has single-qubit gates\n # so we can use the initial layout to output the entire circuit\n if first_layer:\n layout = initial_layout\n for i, layer in enumerate(layerlist):\n dagcircuit_output.compose_back(layer[\"graph\"], layout)\n\n return dagcircuit_output"}
+{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nfinds a swap circuit that implements a permutation for this layer.", "response": "def layer_permutation(self, layer_partition, layout, qubit_subset):\n \"\"\"Find a swap circuit that implements a permutation for this layer.\n\n The goal is to swap qubits such that qubits in the same two-qubit gates\n are adjacent.\n\n Based on Sergey Bravyi's algorithm.\n\n The layer_partition is a list of (qu)bit lists and each qubit is a\n tuple (qreg, index).\n The layout is a dict mapping qubits in the circuit to qubits in the\n coupling graph and represents the current positions of the data.\n The qubit_subset is the subset of qubits in the coupling graph that\n we have chosen to map into.\n The coupling is a CouplingGraph.\n TRIALS is the number of attempts the randomized algorithm makes.\n\n Returns: success_flag, best_circ, best_d, best_layout, trivial_flag\n\n If success_flag is True, then best_circ contains a DAGCircuit with\n the swap circuit, best_d contains the depth of the swap circuit, and\n best_layout contains the new positions of the data qubits after the\n swap circuit has been applied. The trivial_flag is set if the layer\n has no multi-qubit gates.\n \"\"\"\n if self.seed is None:\n self.seed = np.random.randint(0, np.iinfo(np.int32).max)\n rng = np.random.RandomState(self.seed)\n rev_layout = {b: a for a, b in layout.items()}\n gates = []\n for layer in layer_partition:\n if len(layer) > 2:\n raise TranspilerError(\"Layer contains >2 qubit gates\")\n elif len(layer) == 2:\n gates.append(tuple(layer))\n\n # Can we already apply the gates?\n dist = sum([self.coupling_map.distance(layout[g[0]][1], layout[g[1]][1]) for g in gates])\n if dist == len(gates):\n circ = DAGCircuit()\n circ.add_qreg(QuantumRegister(self.coupling_map.size(), \"q\"))\n return True, circ, 0, layout, bool(gates)\n\n # Begin loop over trials of randomized algorithm\n n = self.coupling_map.size()\n best_d = sys.maxsize # initialize best depth\n best_circ = None # initialize best swap circuit\n best_layout = None # initialize best final layout\n QR = QuantumRegister(self.coupling_map.size(), \"q\")\n for _ in range(self.trials):\n\n trial_layout = layout.copy()\n rev_trial_layout = rev_layout.copy()\n # SWAP circuit constructed this trial\n trial_circ = DAGCircuit()\n trial_circ.add_qreg(QR)\n\n # Compute Sergey's randomized distance\n xi = {}\n for i in self.coupling_map.physical_qubits:\n xi[(QR, i)] = {}\n for i in self.coupling_map.physical_qubits:\n i = (QR, i)\n for j in self.coupling_map.physical_qubits:\n j = (QR, j)\n scale = 1 + rng.normal(0, 1 / n)\n xi[i][j] = scale * self.coupling_map.distance(i[1], j[1]) ** 2\n xi[j][i] = xi[i][j]\n\n # Loop over depths d up to a max depth of 2n+1\n d = 1\n # Circuit for this swap slice\n circ = DAGCircuit()\n circ.add_qreg(QR)\n\n # Identity wire-map for composing the circuits\n identity_wire_map = {(QR, j): (QR, j) for j in range(n)}\n\n while d < 2 * n + 1:\n # Set of available qubits\n qubit_set = set(qubit_subset)\n # While there are still qubits available\n while qubit_set:\n # Compute the objective function\n min_cost = sum([xi[trial_layout[g[0]]][trial_layout[g[1]]]\n for g in gates])\n # Try to decrease objective function\n progress_made = False\n # Loop over edges of coupling graph\n for e in self.coupling_map.get_edges():\n e = [(QR, edge) for edge in e]\n # Are the qubits available?\n if e[0] in qubit_set and e[1] in qubit_set:\n # Try this edge to reduce the cost\n new_layout = trial_layout.copy()\n new_layout[rev_trial_layout[e[0]]] = e[1]\n new_layout[rev_trial_layout[e[1]]] = e[0]\n rev_new_layout = rev_trial_layout.copy()\n rev_new_layout[e[0]] = rev_trial_layout[e[1]]\n rev_new_layout[e[1]] = rev_trial_layout[e[0]]\n # Compute the objective function\n new_cost = sum([xi[new_layout[g[0]]][new_layout[g[1]]]\n for g in gates])\n # Record progress if we succceed\n if new_cost < min_cost:\n progress_made = True\n min_cost = new_cost\n opt_layout = new_layout\n rev_opt_layout = rev_new_layout\n opt_edge = e\n\n # Were there any good choices?\n if progress_made:\n qubit_set.remove(opt_edge[0])\n qubit_set.remove(opt_edge[1])\n trial_layout = opt_layout\n rev_trial_layout = rev_opt_layout\n circ.apply_operation_back(\n SwapGate(),\n [(opt_edge[0][0], opt_edge[0][1]), (opt_edge[1][0], opt_edge[1][1])],\n [])\n else:\n break\n\n # We have either run out of qubits or failed to improve\n # Compute the coupling graph distance_qubits\n dist = sum([self.coupling_map.distance(trial_layout[g[0]][1],\n trial_layout[g[1]][1]) for g in gates])\n # If all gates can be applied now, we are finished\n # Otherwise we need to consider a deeper swap circuit\n if dist == len(gates):\n trial_circ.compose_back(circ, identity_wire_map)\n break\n\n # Increment the depth\n d += 1\n\n # Either we have succeeded at some depth d < dmax or failed\n dist = sum([self.coupling_map.distance(trial_layout[g[0]][1],\n trial_layout[g[1]][1]) for g in gates])\n if dist == len(gates):\n if d < best_d:\n best_circ = trial_circ\n best_layout = trial_layout\n best_d = min(best_d, d)\n\n if best_circ is None:\n return False, None, None, None, False\n\n return True, best_circ, best_d, best_layout, False"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef swap_mapper_layer_update(self, i, first_layer, best_layout, best_d,\n best_circ, layer_list):\n \"\"\"Update the QASM string for an iteration of swap_mapper.\n\n i = layer number\n first_layer = True if this is the first layer with multi-qubit gates\n best_layout = layout returned from swap algorithm\n best_d = depth returned from swap algorithm\n best_circ = swap circuit returned from swap algorithm\n layer_list = list of circuit objects for each layer\n\n Return DAGCircuit object to append to the output DAGCircuit.\n \"\"\"\n layout = best_layout\n dagcircuit_output = DAGCircuit()\n QR = QuantumRegister(self.coupling_map.size(), 'q')\n dagcircuit_output.add_qreg(QR)\n # Identity wire-map for composing the circuits\n identity_wire_map = {(QR, j): (QR, j) for j in range(self.coupling_map.size())}\n\n # If this is the first layer with multi-qubit gates,\n # output all layers up to this point and ignore any\n # swap gates. Set the initial layout.\n if first_layer:\n # Output all layers up to this point\n for j in range(i + 1):\n dagcircuit_output.compose_back(layer_list[j][\"graph\"], layout)\n # Otherwise, we output the current layer and the associated swap gates.\n else:\n # Output any swaps\n if best_d > 0:\n dagcircuit_output.compose_back(best_circ, identity_wire_map)\n\n # Output this layer\n dagcircuit_output.compose_back(layer_list[i][\"graph\"], layout)\n return dagcircuit_output", "response": "Update the QASM string for an iteration of swap_mapper."}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef real(self, nested_scope=None):\n operation = self.children[0].operation()\n expr = self.children[1].real(nested_scope)\n return operation(expr)", "response": "Return the correspond floating point number."}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning the correspond symbolic number.", "response": "def sym(self, nested_scope=None):\n \"\"\"Return the correspond symbolic number.\"\"\"\n operation = self.children[0].operation()\n expr = self.children[1].sym(nested_scope)\n return operation(expr)"}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nseparating a bitstring according to the registers defined in the result header.", "response": "def _separate_bitstring(bitstring, creg_sizes):\n \"\"\"Separate a bitstring according to the registers defined in the result header.\"\"\"\n substrings = []\n running_index = 0\n for _, size in reversed(creg_sizes):\n substrings.append(bitstring[running_index: running_index + size])\n running_index += size\n return ' '.join(substrings)"}
+{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef format_counts_memory(shot_memory, header=None):\n if shot_memory.startswith('0x'):\n shot_memory = _hex_to_bin(shot_memory)\n if header:\n creg_sizes = header.get('creg_sizes', None)\n memory_slots = header.get('memory_slots', None)\n if memory_slots:\n shot_memory = _pad_zeros(shot_memory, memory_slots)\n if creg_sizes and memory_slots:\n shot_memory = _separate_bitstring(shot_memory, creg_sizes)\n return shot_memory", "response": "Formats a single bitstring from a single shot experiment."}
+{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nconvert nested list of shape (... 2 to complex numpy array with shape (... 2 )", "response": "def _list_to_complex_array(complex_list):\n \"\"\"Convert nested list of shape (..., 2) to complex numpy array with shape (...)\n\n Args:\n complex_list (list): List to convert.\n\n Returns:\n np.ndarray: Complex numpy aray\n\n Raises:\n QiskitError: If inner most array of input nested list is not of length 2.\n \"\"\"\n arr = np.asarray(complex_list, dtype=np.complex_)\n if not arr.shape[-1] == 2:\n raise QiskitError('Inner most nested list is not of length 2.')\n\n return arr[..., 0] + 1j*arr[..., 1]"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef format_level_0_memory(memory):\n formatted_memory = _list_to_complex_array(memory)\n # infer meas_return from shape of returned data.\n if not 2 <= len(formatted_memory.shape) <= 3:\n raise QiskitError('Level zero memory is not of correct shape.')\n return formatted_memory", "response": "Formats an experiment result memory object for measurement level 0."}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef format_level_1_memory(memory):\n formatted_memory = _list_to_complex_array(memory)\n # infer meas_return from shape of returned data.\n if not 1 <= len(formatted_memory.shape) <= 2:\n raise QiskitError('Level one memory is not of correct shape.')\n return formatted_memory", "response": "Formats an experiment result memory object for measurement level 1."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nformat an experiment result memory object for measurement level 2.", "response": "def format_level_2_memory(memory, header=None):\n \"\"\" Format an experiment result memory object for measurement level 2.\n\n Args:\n memory (list): Memory from experiment with `meas_level==2` and `memory==True`.\n header (dict): the experiment header dictionary containing\n useful information for postprocessing.\n\n Returns:\n list[str]: List of bitstrings\n \"\"\"\n memory_list = []\n for shot_memory in memory:\n memory_list.append(format_counts_memory(shot_memory, header))\n return memory_list"}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nformatting a single experiment result coming from backend to present to the Qiskit user.", "response": "def format_counts(counts, header=None):\n \"\"\"Format a single experiment result coming from backend to present\n to the Qiskit user.\n\n Args:\n counts (dict): counts histogram of multiple shots\n header (dict): the experiment header dictionary containing\n useful information for postprocessing.\n\n Returns:\n dict: a formatted counts\n \"\"\"\n counts_dict = {}\n for key, val in counts.items():\n key = format_counts_memory(key, header)\n counts_dict[key] = val\n return counts_dict"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef format_statevector(vec, decimals=None):\n num_basis = len(vec)\n vec_complex = np.zeros(num_basis, dtype=complex)\n for i in range(num_basis):\n vec_complex[i] = vec[i][0] + 1j * vec[i][1]\n if decimals:\n vec_complex = np.around(vec_complex, decimals=decimals)\n return vec_complex", "response": "Formats the statevector coming from the backend to present to the Qiskit user."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef format_unitary(mat, decimals=None):\n num_basis = len(mat)\n mat_complex = np.zeros((num_basis, num_basis), dtype=complex)\n for i, vec in enumerate(mat):\n mat_complex[i] = format_statevector(vec, decimals)\n return mat_complex", "response": "Format the unitary coming from the backend to present to the Qiskit user."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nsubmitting the job to the backend.", "response": "def submit(self):\n \"\"\"Submit the job to the backend for execution.\n\n Raises:\n QobjValidationError: if the JSON serialization of the Qobj passed\n during construction does not validate against the Qobj schema.\n\n JobError: if trying to re-submit the job.\n \"\"\"\n if self._future is not None:\n raise JobError(\"We have already submitted the job!\")\n\n validate_qobj_against_schema(self._qobj)\n self._future = self._executor.submit(self._fn, self._job_id, self._qobj)"}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\ngetting the status of the current job by querying the Python s future .", "response": "def status(self):\n \"\"\"Gets the status of the job by querying the Python's future\n\n Returns:\n qiskit.providers.JobStatus: The current JobStatus\n\n Raises:\n JobError: If the future is in unexpected state\n concurrent.futures.TimeoutError: if timeout occurred.\n \"\"\"\n # The order is important here\n if self._future.running():\n _status = JobStatus.RUNNING\n elif self._future.cancelled():\n _status = JobStatus.CANCELLED\n elif self._future.done():\n _status = JobStatus.DONE if self._future.exception() is None else JobStatus.ERROR\n else:\n # Note: There is an undocumented Future state: PENDING, that seems to show up when\n # the job is enqueued, waiting for someone to pick it up. We need to deal with this\n # state but there's no public API for it, so we are assuming that if the job is not\n # in any of the previous states, is PENDING, ergo INITIALIZING for us.\n _status = JobStatus.INITIALIZING\n\n return _status"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef iplot_bloch_multivector(rho, figsize=None):\n\n # HTML\n html_template = Template(\"\"\"\n \n
\n \n \"\"\")\n\n # JavaScript\n javascript_template = Template(\"\"\"\n \n \"\"\")\n rho = _validate_input_state(rho)\n if figsize is None:\n options = {}\n else:\n options = {'width': figsize[0], 'height': figsize[1]}\n\n # Process data and execute\n num = int(np.log2(len(rho)))\n\n bloch_data = []\n for i in range(num):\n pauli_singles = [Pauli.pauli_single(num, i, 'X'), Pauli.pauli_single(num, i, 'Y'),\n Pauli.pauli_single(num, i, 'Z')]\n bloch_state = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),\n pauli_singles))\n bloch_data.append(bloch_state)\n\n div_number = str(time.time())\n div_number = re.sub('[.]', '', div_number)\n\n html = html_template.substitute({\n 'divNumber': div_number\n })\n\n javascript = javascript_template.substitute({\n 'data': bloch_data,\n 'divNumber': div_number,\n 'options': options\n })\n\n display(HTML(html + javascript))", "response": "Create a bloch sphere representation of the input array using as much bloch spheres as qubit."}
+{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nparallel execution of a mapping of `values` to the function `task`. This is functionally equivalent to:: result = [task(value, *task_args, **task_kwargs) for value in values] On Windows this function defaults to a serial implementation to avoid the overhead from spawning processes in Windows. Args: task (func): Function that is to be called for each value in ``values``. values (array_like): List or array of values for which the ``task`` function is to be evaluated. task_args (list): Optional additional arguments to the ``task`` function. task_kwargs (dict): Optional additional keyword argument to the ``task`` function. num_processes (int): Number of processes to spawn. Returns: result: The result list contains the value of ``task(value, *task_args, **task_kwargs)`` for each value in ``values``. Raises: QiskitError: If user interrupts via keyboard. Events: terra.parallel.start: The collection of parallel tasks are about to start. terra.parallel.update: One of the parallel task has finished. terra.parallel.finish: All the parallel tasks have finished.", "response": "def parallel_map(task, values, task_args=tuple(), task_kwargs={}, # pylint: disable=W0102\n num_processes=CPU_COUNT):\n \"\"\"\n Parallel execution of a mapping of `values` to the function `task`. This\n is functionally equivalent to::\n\n result = [task(value, *task_args, **task_kwargs) for value in values]\n\n On Windows this function defaults to a serial implementation to avoid the\n overhead from spawning processes in Windows.\n\n Args:\n task (func): Function that is to be called for each value in ``values``.\n values (array_like): List or array of values for which the ``task``\n function is to be evaluated.\n task_args (list): Optional additional arguments to the ``task`` function.\n task_kwargs (dict): Optional additional keyword argument to the ``task`` function.\n num_processes (int): Number of processes to spawn.\n\n Returns:\n result: The result list contains the value of\n ``task(value, *task_args, **task_kwargs)`` for\n each value in ``values``.\n\n Raises:\n QiskitError: If user interrupts via keyboard.\n\n Events:\n terra.parallel.start: The collection of parallel tasks are about to start.\n terra.parallel.update: One of the parallel task has finished.\n terra.parallel.finish: All the parallel tasks have finished.\n \"\"\"\n if len(values) == 1:\n return [task(values[0], *task_args, **task_kwargs)]\n\n Publisher().publish(\"terra.parallel.start\", len(values))\n nfinished = [0]\n\n def _callback(_):\n nfinished[0] += 1\n Publisher().publish(\"terra.parallel.done\", nfinished[0])\n\n # Run in parallel if not Win and not in parallel already\n if platform.system() != 'Windows' and num_processes > 1 \\\n and os.getenv('QISKIT_IN_PARALLEL') == 'FALSE':\n os.environ['QISKIT_IN_PARALLEL'] = 'TRUE'\n try:\n pool = Pool(processes=num_processes)\n\n async_res = [pool.apply_async(task, (value,) + task_args, task_kwargs,\n _callback) for value in values]\n\n while not all([item.ready() for item in async_res]):\n for item in async_res:\n item.wait(timeout=0.1)\n\n pool.terminate()\n pool.join()\n\n except KeyboardInterrupt:\n pool.terminate()\n pool.join()\n Publisher().publish(\"terra.parallel.finish\")\n raise QiskitError('Keyboard interrupt in parallel_map.')\n\n Publisher().publish(\"terra.parallel.finish\")\n os.environ['QISKIT_IN_PARALLEL'] = 'FALSE'\n return [ar.get() for ar in async_res]\n\n # Cannot do parallel on Windows , if another parallel_map is running in parallel,\n # or len(values) == 1.\n results = []\n for _, value in enumerate(values):\n result = task(value, *task_args, **task_kwargs)\n results.append(result)\n _callback(0)\n Publisher().publish(\"terra.parallel.finish\")\n return results"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef get_qubit_los(self, user_lo_config):\n try:\n _q_los = self.default_qubit_los.copy()\n except KeyError:\n raise PulseError('Qubit default frequencies not exist.')\n\n for channel, lo_freq in user_lo_config.qubit_lo_dict().items():\n _q_los[channel.index] = lo_freq\n\n if _q_los == self.default_qubit_los:\n return None\n return _q_los", "response": "Embed default qubit LO frequencies from backend and format them to list object."}
+{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef get_meas_los(self, user_lo_config):\n try:\n _m_los = self.default_meas_los.copy()\n except KeyError:\n raise PulseError('Default measurement frequencies not exist.')\n\n for channel, lo_freq in user_lo_config.meas_lo_dict().items():\n _m_los[channel.index] = lo_freq\n\n if _m_los == self.default_meas_los:\n return None\n return _m_los", "response": "Embed default meas LO frequencies from backend and format them to list object."}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef run(self, dag):\n # Walk through the DAG and expand each non-basis node\n for node in dag.op_nodes():\n basic_insts = ['measure', 'reset', 'barrier', 'snapshot']\n if node.name in basic_insts:\n # TODO: this is legacy behavior.Basis_insts should be removed that these\n # instructions should be part of the device-reported basis. Currently, no\n # backend reports \"measure\", for example.\n continue\n if node.name in self.basis: # If already a base, ignore.\n continue\n\n # TODO: allow choosing other possible decompositions\n rule = node.op.definition\n if not rule:\n raise QiskitError(\"Cannot unroll the circuit to the given basis, %s. \"\n \"No rule to expand instruction %s.\" %\n (str(self.basis), node.op.name))\n\n # hacky way to build a dag on the same register as the rule is defined\n # TODO: need anonymous rules to address wires by index\n decomposition = DAGCircuit()\n decomposition.add_qreg(rule[0][1][0][0])\n for inst in rule:\n decomposition.apply_operation_back(*inst)\n\n unrolled_dag = self.run(decomposition) # recursively unroll ops\n dag.substitute_node_with_dag(node, unrolled_dag)\n return dag", "response": "Expand all op nodes to the given basis."}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef iplot_state_qsphere(rho, figsize=None):\n\n # HTML\n html_template = Template(\"\"\"\n \n
\n \n \"\"\")\n\n # JavaScript\n javascript_template = Template(\"\"\"\n \n\n \"\"\")\n rho = _validate_input_state(rho)\n if figsize is None:\n options = {}\n else:\n options = {'width': figsize[0], 'height': figsize[1]}\n\n qspheres_data = []\n # Process data and execute\n num = int(np.log2(len(rho)))\n\n # get the eigenvectors and eigenvalues\n weig, stateall = linalg.eigh(rho)\n\n for _ in range(2**num):\n # start with the max\n probmix = weig.max()\n prob_location = weig.argmax()\n if probmix > 0.001:\n # print(\"The \" + str(k) + \"th eigenvalue = \" + str(probmix))\n # get the max eigenvalue\n state = stateall[:, prob_location]\n loc = np.absolute(state).argmax()\n # get the element location closes to lowest bin representation.\n for j in range(2**num):\n test = np.absolute(np.absolute(state[j]) -\n np.absolute(state[loc]))\n if test < 0.001:\n loc = j\n break\n # remove the global phase\n angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)\n angleset = np.exp(-1j*angles)\n state = angleset*state\n state.flatten()\n\n spherepoints = []\n for i in range(2**num):\n # get x,y,z points\n\n element = bin(i)[2:].zfill(num)\n weight = element.count(\"1\")\n\n number_of_divisions = n_choose_k(num, weight)\n weight_order = bit_string_index(element)\n\n angle = weight_order * 2 * np.pi / number_of_divisions\n\n zvalue = -2 * weight / num + 1\n xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)\n yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)\n\n # get prob and angle - prob will be shade and angle color\n prob = np.real(np.dot(state[i], state[i].conj()))\n angles = (np.angle(state[i]) + 2 * np.pi) % (2 * np.pi)\n qpoint = {\n 'x': xvalue,\n 'y': yvalue,\n 'z': zvalue,\n 'prob': prob,\n 'phase': angles\n }\n spherepoints.append(qpoint)\n\n # Associate all points to one sphere\n sphere = {\n 'points': spherepoints,\n 'eigenvalue': probmix\n }\n\n # Add sphere to the spheres array\n qspheres_data.append(sphere)\n weig[prob_location] = 0\n\n div_number = str(time.time())\n div_number = re.sub('[.]', '', div_number)\n\n html = html_template.substitute({\n 'divNumber': div_number\n })\n\n javascript = javascript_template.substitute({\n 'data': qspheres_data,\n 'divNumber': div_number,\n 'options': options\n })\n\n display(HTML(html + javascript))", "response": "Create a Q sphere representation of the input array using a Q sphere visualization."}
+{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nreturns the number of combinations for n choose k.", "response": "def n_choose_k(n, k):\n \"\"\"Return the number of combinations for n choose k.\n\n Args:\n n (int): the total number of options .\n k (int): The number of elements.\n\n Returns:\n int: returns the binomial coefficient\n \"\"\"\n if n == 0:\n return 0\n return reduce(lambda x, y: x * y[0] / y[1],\n zip(range(n - k + 1, n + 1),\n range(1, k + 1)), 1)"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef bit_string_index(text):\n n = len(text)\n k = text.count(\"1\")\n if text.count(\"0\") != n - k:\n raise VisualizationError(\"s must be a string of 0 and 1\")\n ones = [pos for pos, char in enumerate(text) if char == \"1\"]\n return lex_index(n, k, ones)", "response": "Return the index of a string of 0s and 1s."}
+{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns the index of a combination of n and k.", "response": "def lex_index(n, k, lst):\n \"\"\"Return the lex index of a combination..\n\n Args:\n n (int): the total number of options .\n k (int): The number of elements.\n lst (list): list\n\n Returns:\n int: returns int index for lex order\n\n Raises:\n VisualizationError: if length of list is not equal to k\n \"\"\"\n if len(lst) != k:\n raise VisualizationError(\"list should have length k\")\n comb = list(map(lambda x: n - 1 - x, lst))\n dualm = sum([n_choose_k(comb[k - 1 - i], i + 1) for i in range(k)])\n return int(dualm)"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef plot_state_hinton(rho, title='', figsize=None):\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed.')\n rho = _validate_input_state(rho)\n if figsize is None:\n figsize = (8, 5)\n num = int(np.log2(len(rho)))\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=figsize)\n max_weight = 2 ** np.ceil(np.log(np.abs(rho).max()) / np.log(2))\n datareal = np.real(rho)\n dataimag = np.imag(rho)\n column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]\n row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]\n lx = len(datareal[0]) # Work out matrix dimensions\n ly = len(datareal[:, 0])\n # Real\n ax1.patch.set_facecolor('gray')\n ax1.set_aspect('equal', 'box')\n ax1.xaxis.set_major_locator(plt.NullLocator())\n ax1.yaxis.set_major_locator(plt.NullLocator())\n\n for (x, y), w in np.ndenumerate(datareal):\n color = 'white' if w > 0 else 'black'\n size = np.sqrt(np.abs(w) / max_weight)\n rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,\n facecolor=color, edgecolor=color)\n ax1.add_patch(rect)\n\n ax1.set_xticks(np.arange(0, lx+0.5, 1))\n ax1.set_yticks(np.arange(0, ly+0.5, 1))\n ax1.set_yticklabels(row_names, fontsize=14)\n ax1.set_xticklabels(column_names, fontsize=14, rotation=90)\n ax1.autoscale_view()\n ax1.invert_yaxis()\n ax1.set_title('Real[rho]', fontsize=14)\n # Imaginary\n ax2.patch.set_facecolor('gray')\n ax2.set_aspect('equal', 'box')\n ax2.xaxis.set_major_locator(plt.NullLocator())\n ax2.yaxis.set_major_locator(plt.NullLocator())\n\n for (x, y), w in np.ndenumerate(dataimag):\n color = 'white' if w > 0 else 'black'\n size = np.sqrt(np.abs(w) / max_weight)\n rect = plt.Rectangle([x - size / 2, y - size / 2], size, size,\n facecolor=color, edgecolor=color)\n ax2.add_patch(rect)\n if np.any(dataimag != 0):\n ax2.set_xticks(np.arange(0, lx+0.5, 1))\n ax2.set_yticks(np.arange(0, ly+0.5, 1))\n ax2.set_yticklabels(row_names, fontsize=14)\n ax2.set_xticklabels(column_names, fontsize=14, rotation=90)\n ax2.autoscale_view()\n ax2.invert_yaxis()\n ax2.set_title('Imag[rho]', fontsize=14)\n if title:\n fig.suptitle(title, fontsize=16)\n plt.tight_layout()\n plt.close(fig)\n return fig", "response": "Plots a hinton diagram for the quanum state vector or density matrix."}
+{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nplots the Bloch vector.", "response": "def plot_bloch_vector(bloch, title=\"\", ax=None, figsize=None):\n \"\"\"Plot the Bloch sphere.\n\n Plot a sphere, axes, the Bloch vector, and its projections onto each axis.\n\n Args:\n bloch (list[double]): array of three elements where [, , ]\n title (str): a string that represents the plot title\n ax (matplotlib.Axes): An Axes to use for rendering the bloch sphere\n figsize (tuple): Figure size in inches. Has no effect is passing `ax`.\n\n Returns:\n Figure: A matplotlib figure instance if `ax = None`.\n\n Raises:\n ImportError: Requires matplotlib.\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed.')\n if figsize is None:\n figsize = (5, 5)\n B = Bloch(axes=ax)\n B.add_vectors(bloch)\n B.render(title=title)\n if ax is None:\n fig = B.fig\n fig.set_size_inches(figsize[0], figsize[1])\n plt.close(fig)\n return fig\n return None"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef plot_bloch_multivector(rho, title='', figsize=None):\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed.')\n rho = _validate_input_state(rho)\n num = int(np.log2(len(rho)))\n width, height = plt.figaspect(1/num)\n fig = plt.figure(figsize=(width, height))\n for i in range(num):\n ax = fig.add_subplot(1, num, i + 1, projection='3d')\n pauli_singles = [\n Pauli.pauli_single(num, i, 'X'),\n Pauli.pauli_single(num, i, 'Y'),\n Pauli.pauli_single(num, i, 'Z')\n ]\n bloch_state = list(\n map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),\n pauli_singles))\n plot_bloch_vector(bloch_state, \"qubit \" + str(i), ax=ax,\n figsize=figsize)\n fig.suptitle(title, fontsize=16)\n plt.close(fig)\n return fig", "response": "Plot the Bloch sphere."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef plot_state_city(rho, title=\"\", figsize=None, color=None,\n alpha=1):\n \"\"\"Plot the cityscape of quantum state.\n\n Plot two 3d bar graphs (two dimensional) of the real and imaginary\n part of the density matrix rho.\n\n Args:\n rho (ndarray): Numpy array for state vector or density matrix.\n title (str): a string that represents the plot title\n figsize (tuple): Figure size in inches.\n color (list): A list of len=2 giving colors for real and\n imaginary components of matrix elements.\n alpha (float): Transparency value for bars\n Returns:\n matplotlib.Figure: The matplotlib.Figure of the visualization\n\n Raises:\n ImportError: Requires matplotlib.\n ValueError: When 'color' is not a list of len=2.\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed.')\n rho = _validate_input_state(rho)\n\n num = int(np.log2(len(rho)))\n # get the real and imag parts of rho\n datareal = np.real(rho)\n dataimag = np.imag(rho)\n\n # get the labels\n column_names = [bin(i)[2:].zfill(num) for i in range(2**num)]\n row_names = [bin(i)[2:].zfill(num) for i in range(2**num)]\n\n lx = len(datareal[0]) # Work out matrix dimensions\n ly = len(datareal[:, 0])\n xpos = np.arange(0, lx, 1) # Set up a mesh of positions\n ypos = np.arange(0, ly, 1)\n xpos, ypos = np.meshgrid(xpos+0.25, ypos+0.25)\n\n xpos = xpos.flatten()\n ypos = ypos.flatten()\n zpos = np.zeros(lx*ly)\n\n dx = 0.5 * np.ones_like(zpos) # width of bars\n dy = dx.copy()\n dzr = datareal.flatten()\n dzi = dataimag.flatten()\n\n if color is None:\n color = [\"#648fff\", \"#648fff\"]\n else:\n if len(color) != 2:\n raise ValueError(\"'color' must be a list of len=2.\")\n if color[0] is None:\n color[0] = \"#648fff\"\n if color[1] is None:\n color[1] = \"#648fff\"\n\n # set default figure size\n if figsize is None:\n figsize = (15, 5)\n\n fig = plt.figure(figsize=figsize)\n ax1 = fig.add_subplot(1, 2, 1, projection='3d')\n\n x = [0, max(xpos)+0.5, max(xpos)+0.5, 0]\n y = [0, 0, max(ypos)+0.5, max(ypos)+0.5]\n z = [0, 0, 0, 0]\n verts = [list(zip(x, y, z))]\n\n fc1 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzr, color[0])\n for idx, cur_zpos in enumerate(zpos):\n if dzr[idx] > 0:\n zorder = 2\n else:\n zorder = 0\n b1 = ax1.bar3d(xpos[idx], ypos[idx], cur_zpos,\n dx[idx], dy[idx], dzr[idx],\n alpha=alpha, zorder=zorder)\n b1.set_facecolors(fc1[6*idx:6*idx+6])\n\n pc1 = Poly3DCollection(verts, alpha=0.15, facecolor='k',\n linewidths=1, zorder=1)\n\n if min(dzr) < 0 < max(dzr):\n ax1.add_collection3d(pc1)\n\n ax2 = fig.add_subplot(1, 2, 2, projection='3d')\n fc2 = generate_facecolors(xpos, ypos, zpos, dx, dy, dzi, color[1])\n for idx, cur_zpos in enumerate(zpos):\n if dzi[idx] > 0:\n zorder = 2\n else:\n zorder = 0\n b2 = ax2.bar3d(xpos[idx], ypos[idx], cur_zpos,\n dx[idx], dy[idx], dzi[idx],\n alpha=alpha, zorder=zorder)\n b2.set_facecolors(fc2[6*idx:6*idx+6])\n\n pc2 = Poly3DCollection(verts, alpha=0.2, facecolor='k',\n linewidths=1, zorder=1)\n\n if min(dzi) < 0 < max(dzi):\n ax2.add_collection3d(pc2)\n ax1.set_xticks(np.arange(0.5, lx+0.5, 1))\n ax1.set_yticks(np.arange(0.5, ly+0.5, 1))\n max_dzr = max(dzr)\n min_dzr = min(dzr)\n if max_dzr != min_dzr:\n ax1.axes.set_zlim3d(np.min(dzr), np.max(dzr)+1e-9)\n else:\n if min_dzr == 0:\n ax1.axes.set_zlim3d(np.min(dzr), np.max(dzr)+1e-9)\n else:\n ax1.axes.set_zlim3d(auto=True)\n ax1.zaxis.set_major_locator(MaxNLocator(5))\n ax1.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45)\n ax1.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5)\n ax1.set_zlabel(\"Real[rho]\", fontsize=14)\n for tick in ax1.zaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n\n ax2.set_xticks(np.arange(0.5, lx+0.5, 1))\n ax2.set_yticks(np.arange(0.5, ly+0.5, 1))\n min_dzi = np.min(dzi)\n max_dzi = np.max(dzi)\n if min_dzi != max_dzi:\n eps = 0\n ax2.zaxis.set_major_locator(MaxNLocator(5))\n ax2.axes.set_zlim3d(np.min(dzi), np.max(dzi)+eps)\n else:\n if min_dzi == 0:\n ax2.set_zticks([0])\n eps = 1e-9\n ax2.axes.set_zlim3d(np.min(dzi), np.max(dzi)+eps)\n else:\n ax2.axes.set_zlim3d(auto=True)\n ax2.w_xaxis.set_ticklabels(row_names, fontsize=14, rotation=45)\n ax2.w_yaxis.set_ticklabels(column_names, fontsize=14, rotation=-22.5)\n ax2.set_zlabel(\"Imag[rho]\", fontsize=14)\n for tick in ax2.zaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n plt.suptitle(title, fontsize=16)\n plt.tight_layout()\n plt.close(fig)\n return fig", "response": "Plots the cityscape of quantum state."}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nplots the paulivec representation of a mixed state vector or density matrix.", "response": "def plot_state_paulivec(rho, title=\"\", figsize=None, color=None):\n \"\"\"Plot the paulivec representation of a quantum state.\n\n Plot a bargraph of the mixed state rho over the pauli matrices\n\n Args:\n rho (ndarray): Numpy array for state vector or density matrix\n title (str): a string that represents the plot title\n figsize (tuple): Figure size in inches.\n color (list or str): Color of the expectation value bars.\n Returns:\n matplotlib.Figure: The matplotlib.Figure of the visualization\n Raises:\n ImportError: Requires matplotlib.\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed.')\n rho = _validate_input_state(rho)\n if figsize is None:\n figsize = (7, 5)\n num = int(np.log2(len(rho)))\n labels = list(map(lambda x: x.to_label(), pauli_group(num)))\n values = list(map(lambda x: np.real(np.trace(np.dot(x.to_matrix(), rho))),\n pauli_group(num)))\n numelem = len(values)\n if color is None:\n color = \"#648fff\"\n\n ind = np.arange(numelem) # the x locations for the groups\n width = 0.5 # the width of the bars\n fig, ax = plt.subplots(figsize=figsize)\n ax.grid(zorder=0, linewidth=1, linestyle='--')\n ax.bar(ind, values, width, color=color, zorder=2)\n ax.axhline(linewidth=1, color='k')\n # add some text for labels, title, and axes ticks\n ax.set_ylabel('Expectation value', fontsize=14)\n ax.set_xticks(ind)\n ax.set_yticks([-1, -0.5, 0, 0.5, 1])\n ax.set_xticklabels(labels, fontsize=14, rotation=70)\n ax.set_xlabel('Pauli', fontsize=14)\n ax.set_ylim([-1, 1])\n ax.set_facecolor('#eeeeee')\n for tick in ax.xaxis.get_major_ticks()+ax.yaxis.get_major_ticks():\n tick.label.set_fontsize(14)\n ax.set_title(title, fontsize=16)\n plt.close(fig)\n return fig"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn the index of a string of 0 and 1s.", "response": "def bit_string_index(s):\n \"\"\"Return the index of a string of 0s and 1s.\"\"\"\n n = len(s)\n k = s.count(\"1\")\n if s.count(\"0\") != n - k:\n raise VisualizationError(\"s must be a string of 0 and 1\")\n ones = [pos for pos, char in enumerate(s) if char == \"1\"]\n return lex_index(n, k, ones)"}
+{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef phase_to_color_wheel(complex_number):\n angles = np.angle(complex_number)\n angle_round = int(((angles + 2 * np.pi) % (2 * np.pi))/np.pi*6)\n color_map = {\n 0: (0, 0, 1), # blue,\n 1: (0.5, 0, 1), # blue-violet\n 2: (1, 0, 1), # violet\n 3: (1, 0, 0.5), # red-violet,\n 4: (1, 0, 0), # red\n 5: (1, 0.5, 0), # red-oranage,\n 6: (1, 1, 0), # orange\n 7: (0.5, 1, 0), # orange-yellow\n 8: (0, 1, 0), # yellow,\n 9: (0, 1, 0.5), # yellow-green,\n 10: (0, 1, 1), # green,\n 11: (0, 0.5, 1) # green-blue,\n }\n return color_map[angle_round]", "response": "Map a phase of a complexnumber to a color wheel."}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nplots the qsphere representation of a state vector or density matrix representation.", "response": "def plot_state_qsphere(rho, figsize=None):\n \"\"\"Plot the qsphere representation of a quantum state.\n\n Args:\n rho (ndarray): State vector or density matrix representation.\n of quantum state.\n figsize (tuple): Figure size in inches.\n\n Returns:\n Figure: A matplotlib figure instance.\n\n Raises:\n ImportError: Requires matplotlib.\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed.')\n rho = _validate_input_state(rho)\n if figsize is None:\n figsize = (7, 7)\n num = int(np.log2(len(rho)))\n # get the eigenvectors and eigenvalues\n we, stateall = linalg.eigh(rho)\n for _ in range(2**num):\n # start with the max\n probmix = we.max()\n prob_location = we.argmax()\n if probmix > 0.001:\n # get the max eigenvalue\n state = stateall[:, prob_location]\n loc = np.absolute(state).argmax()\n # get the element location closes to lowest bin representation.\n for j in range(2**num):\n test = np.absolute(np.absolute(state[j]) -\n np.absolute(state[loc]))\n if test < 0.001:\n loc = j\n break\n # remove the global phase\n angles = (np.angle(state[loc]) + 2 * np.pi) % (2 * np.pi)\n angleset = np.exp(-1j*angles)\n # print(state)\n # print(angles)\n state = angleset*state\n # print(state)\n state.flatten()\n # start the plotting\n fig = plt.figure(figsize=figsize)\n ax = fig.add_subplot(111, projection='3d')\n ax.axes.set_xlim3d(-1.0, 1.0)\n ax.axes.set_ylim3d(-1.0, 1.0)\n ax.axes.set_zlim3d(-1.0, 1.0)\n ax.set_aspect(\"equal\")\n ax.axes.grid(False)\n # Plot semi-transparent sphere\n u = np.linspace(0, 2 * np.pi, 25)\n v = np.linspace(0, np.pi, 25)\n x = np.outer(np.cos(u), np.sin(v))\n y = np.outer(np.sin(u), np.sin(v))\n z = np.outer(np.ones(np.size(u)), np.cos(v))\n ax.plot_surface(x, y, z, rstride=1, cstride=1, color='k',\n alpha=0.05, linewidth=0)\n # wireframe\n # Get rid of the panes\n ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 0.0))\n\n # Get rid of the spines\n ax.w_xaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n ax.w_yaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n ax.w_zaxis.line.set_color((1.0, 1.0, 1.0, 0.0))\n # Get rid of the ticks\n ax.set_xticks([])\n ax.set_yticks([])\n ax.set_zticks([])\n\n d = num\n for i in range(2**num):\n # get x,y,z points\n element = bin(i)[2:].zfill(num)\n weight = element.count(\"1\")\n zvalue = -2 * weight / d + 1\n number_of_divisions = n_choose_k(d, weight)\n weight_order = bit_string_index(element)\n # if weight_order >= number_of_divisions / 2:\n # com_key = compliment(element)\n # weight_order_temp = bit_string_index(com_key)\n # weight_order = np.floor(\n # number_of_divisions / 2) + weight_order_temp + 1\n angle = weight_order * 2 * np.pi / number_of_divisions\n xvalue = np.sqrt(1 - zvalue**2) * np.cos(angle)\n yvalue = np.sqrt(1 - zvalue**2) * np.sin(angle)\n ax.plot([xvalue], [yvalue], [zvalue],\n markerfacecolor=(.5, .5, .5),\n markeredgecolor=(.5, .5, .5),\n marker='o', markersize=10, alpha=1)\n # get prob and angle - prob will be shade and angle color\n prob = np.real(np.dot(state[i], state[i].conj()))\n colorstate = phase_to_color_wheel(state[i])\n a = Arrow3D([0, xvalue], [0, yvalue], [0, zvalue],\n mutation_scale=20, alpha=prob, arrowstyle=\"-\",\n color=colorstate, lw=10)\n ax.add_artist(a)\n # add weight lines\n for weight in range(d + 1):\n theta = np.linspace(-2 * np.pi, 2 * np.pi, 100)\n z = -2 * weight / d + 1\n r = np.sqrt(1 - z**2)\n x = r * np.cos(theta)\n y = r * np.sin(theta)\n ax.plot(x, y, z, color=(.5, .5, .5))\n # add center point\n ax.plot([0], [0], [0], markerfacecolor=(.5, .5, .5),\n markeredgecolor=(.5, .5, .5), marker='o', markersize=10,\n alpha=1)\n we[prob_location] = 0\n else:\n break\n plt.tight_layout()\n plt.close(fig)\n return fig"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nplot the state of a multi - qubit state.", "response": "def plot_state(quantum_state, method='city', figsize=None):\n \"\"\"Plot the quantum state.\n\n Args:\n quantum_state (ndarray): statevector or density matrix\n representation of a quantum state.\n method (str): Plotting method to use.\n figsize (tuple): Figure size in inches,\n\n Returns:\n matplotlib.Figure: The matplotlib.Figure of the visualization\n Raises:\n ImportError: Requires matplotlib.\n VisualizationError: if the input is not a statevector or density\n matrix, or if the state is not an multi-qubit quantum state.\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed.')\n warnings.warn(\"plot_state is deprecated, and will be removed in \\\n the 0.9 release. Use the plot_state_ * functions \\\n instead.\",\n DeprecationWarning)\n # Check if input is a statevector, and convert to density matrix\n rho = _validate_input_state(quantum_state)\n fig = None\n if method == 'city':\n fig = plot_state_city(rho, figsize=figsize)\n elif method == \"paulivec\":\n fig = plot_state_paulivec(rho, figsize=figsize)\n elif method == \"qsphere\":\n fig = plot_state_qsphere(rho, figsize=figsize)\n elif method == \"bloch\":\n plot_bloch_multivector(rho, figsize=figsize)\n elif method == \"hinton\":\n fig = plot_state_hinton(rho, figsize=figsize)\n return fig"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ngenerating a list of shaded facecolors for the given set of points.", "response": "def generate_facecolors(x, y, z, dx, dy, dz, color):\n \"\"\"Generates shaded facecolors for shaded bars.\n This is here to work around a Matplotlib bug\n where alpha does not work in Bar3D.\n Args:\n x (array_like): The x- coordinates of the anchor point of the bars.\n y (array_like): The y- coordinates of the anchor point of the bars.\n z (array_like): The z- coordinates of the anchor point of the bars.\n dx (array_like): Width of bars.\n dy (array_like): Depth of bars.\n dz (array_like): Height of bars.\n color (array_like): sequence of valid color specifications, optional\n Returns:\n list: Shaded colors for bars.\n \"\"\"\n cuboid = np.array([\n # -z\n (\n (0, 0, 0),\n (0, 1, 0),\n (1, 1, 0),\n (1, 0, 0),\n ),\n # +z\n (\n (0, 0, 1),\n (1, 0, 1),\n (1, 1, 1),\n (0, 1, 1),\n ),\n # -y\n (\n (0, 0, 0),\n (1, 0, 0),\n (1, 0, 1),\n (0, 0, 1),\n ),\n # +y\n (\n (0, 1, 0),\n (0, 1, 1),\n (1, 1, 1),\n (1, 1, 0),\n ),\n # -x\n (\n (0, 0, 0),\n (0, 0, 1),\n (0, 1, 1),\n (0, 1, 0),\n ),\n # +x\n (\n (1, 0, 0),\n (1, 1, 0),\n (1, 1, 1),\n (1, 0, 1),\n ),\n ])\n\n # indexed by [bar, face, vertex, coord]\n polys = np.empty(x.shape + cuboid.shape)\n # handle each coordinate separately\n for i, p, dp in [(0, x, dx), (1, y, dy), (2, z, dz)]:\n p = p[..., np.newaxis, np.newaxis]\n dp = dp[..., np.newaxis, np.newaxis]\n polys[..., i] = p + dp * cuboid[..., i]\n\n # collapse the first two axes\n polys = polys.reshape((-1,) + polys.shape[2:])\n\n facecolors = []\n if len(color) == len(x):\n # bar colors specified, need to expand to number of faces\n for c in color:\n facecolors.extend([c] * 6)\n else:\n # a single color specified, or face colors specified explicitly\n facecolors = list(mcolors.to_rgba_array(color))\n if len(facecolors) < len(x):\n facecolors *= (6 * len(x))\n\n normals = _generate_normals(polys)\n return _shade_colors(facecolors, normals)"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\ngenerate the array of the normals for the given list of polygons.", "response": "def _generate_normals(polygons):\n \"\"\"\n Takes a list of polygons and return an array of their normals.\n Normals point towards the viewer for a face with its vertices in\n counterclockwise order, following the right hand rule.\n Uses three points equally spaced around the polygon.\n This normal of course might not make sense for polygons with more than\n three points not lying in a plane, but it's a plausible and fast\n approximation.\n Args:\n polygons (list): list of (M_i, 3) array_like, or (..., M, 3) array_like\n A sequence of polygons to compute normals for, which can have\n varying numbers of vertices. If the polygons all have the same\n number of vertices and array is passed, then the operation will\n be vectorized.\n Returns:\n normals: (..., 3) array_like\n A normal vector estimated for the polygon.\n \"\"\"\n if isinstance(polygons, np.ndarray):\n # optimization: polygons all have the same number of points, so can\n # vectorize\n n = polygons.shape[-2]\n i1, i2, i3 = 0, n//3, 2*n//3\n v1 = polygons[..., i1, :] - polygons[..., i2, :]\n v2 = polygons[..., i2, :] - polygons[..., i3, :]\n else:\n # The subtraction doesn't vectorize because polygons is jagged.\n v1 = np.empty((len(polygons), 3))\n v2 = np.empty((len(polygons), 3))\n for poly_i, ps in enumerate(polygons):\n n = len(ps)\n i1, i2, i3 = 0, n//3, 2*n//3\n v1[poly_i, :] = ps[i1, :] - ps[i2, :]\n v2[poly_i, :] = ps[i2, :] - ps[i3, :]\n\n return np.cross(v1, v2)"}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _shade_colors(color, normals, lightsource=None):\n if lightsource is None:\n # chosen for backwards-compatibility\n lightsource = LightSource(azdeg=225, altdeg=19.4712)\n\n shade = np.array([np.dot(n / proj3d.mod(n), lightsource.direction)\n if proj3d.mod(n) else np.nan\n for n in normals])\n mask = ~np.isnan(shade)\n\n if mask.any():\n norm = Normalize(min(shade[mask]), max(shade[mask]))\n shade[~mask] = min(shade[mask])\n color = mcolors.to_rgba_array(color)\n # shape of color should be (M, 4) (where M is number of faces)\n # shape of shade should be (M,)\n # colors should have final shape of (M, 4)\n alpha = color[:, 3]\n colors = (0.5 + norm(shade)[:, np.newaxis] * 0.5) * color\n colors[:, 3] = alpha\n else:\n colors = np.asanyarray(color).copy()\n\n return colors", "response": "Shade colors using normal vectors given by normals."}
+{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef get_unique_backends():\n backends = IBMQ.backends()\n unique_hardware_backends = []\n unique_names = []\n for back in backends:\n if back.name() not in unique_names and not back.configuration().simulator:\n unique_hardware_backends.append(back)\n unique_names.append(back.name())\n if not unique_hardware_backends:\n raise QiskitError('No backends available.')\n return unique_hardware_backends", "response": "Gets the unique backends that are available."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef backend_monitor(backend):\n if not isinstance(backend, IBMQBackend):\n raise QiskitError('Input variable is not of type IBMQBackend.')\n config = backend.configuration().to_dict()\n status = backend.status().to_dict()\n config_dict = {**status, **config}\n if not config['simulator']:\n props = backend.properties().to_dict()\n\n print(backend.name())\n print('='*len(backend.name()))\n print('Configuration')\n print('-'*13)\n offset = ' '\n\n upper_list = ['n_qubits', 'operational',\n 'status_msg', 'pending_jobs',\n 'basis_gates', 'local', 'simulator']\n\n lower_list = list(set(config_dict.keys()).difference(upper_list))\n # Remove gates because they are in a different tab\n lower_list.remove('gates')\n for item in upper_list+lower_list:\n print(offset+item+':', config_dict[item])\n\n # Stop here if simulator\n if config['simulator']:\n return\n\n print()\n qubit_header = 'Qubits [Name / Freq / T1 / T2 / U1 err / U2 err / U3 err / Readout err]'\n print(qubit_header)\n print('-'*len(qubit_header))\n\n sep = ' / '\n for qub in range(len(props['qubits'])):\n name = 'Q%s' % qub\n qubit_data = props['qubits'][qub]\n gate_data = props['gates'][3*qub:3*qub+3]\n t1_info = qubit_data[0]\n t2_info = qubit_data[1]\n freq_info = qubit_data[2]\n readout_info = qubit_data[3]\n\n freq = str(round(freq_info['value'], 5))+' '+freq_info['unit']\n T1 = str(round(t1_info['value'], # pylint: disable=invalid-name\n 5))+' ' + t1_info['unit']\n T2 = str(round(t2_info['value'], # pylint: disable=invalid-name\n 5))+' ' + t2_info['unit']\n # pylint: disable=invalid-name\n U1 = str(round(gate_data[0]['parameters'][0]['value'], 5))\n # pylint: disable=invalid-name\n U2 = str(round(gate_data[1]['parameters'][0]['value'], 5))\n # pylint: disable=invalid-name\n U3 = str(round(gate_data[2]['parameters'][0]['value'], 5))\n\n readout_error = str(round(readout_info['value'], 5))\n\n qstr = sep.join([name, freq, T1, T2, U1, U2, U3, readout_error])\n print(offset+qstr)\n\n print()\n multi_qubit_gates = props['gates'][3*config['n_qubits']:]\n multi_header = 'Multi-Qubit Gates [Name / Type / Gate Error]'\n print(multi_header)\n print('-'*len(multi_header))\n\n for gate in multi_qubit_gates:\n name = gate['name']\n ttype = gate['gate']\n error = str(round(gate['parameters'][0]['value'], 5))\n mstr = sep.join([name, ttype, error])\n print(offset+mstr)", "response": "Monitor a single IBMQ backend."}
+{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ngive overview information on all the IBMQ alues that are available.", "response": "def backend_overview():\n \"\"\"Gives overview information on all the IBMQ\n backends that are available.\n \"\"\"\n unique_hardware_backends = get_unique_backends()\n _backends = []\n # Sort backends by operational or not\n for idx, back in enumerate(unique_hardware_backends):\n if back.status().operational:\n _backends = [back] + _backends\n else:\n _backends = _backends + [back]\n\n stati = [back.status() for back in _backends]\n idx = list(range(len(_backends)))\n pending = [s.pending_jobs for s in stati]\n _, least_idx = zip(*sorted(zip(pending, idx)))\n\n # Make sure least pending is operational\n for ind in least_idx:\n if stati[ind].operational:\n least_pending_idx = ind\n break\n\n num_rows = math.ceil(len(_backends)/3)\n\n count = 0\n num_backends = len(_backends)\n for _ in range(num_rows):\n max_len = 0\n str_list = ['']*8\n for idx in range(3):\n offset = ' ' * 10 if idx else ''\n config = _backends[count].configuration().to_dict()\n props = _backends[count].properties().to_dict()\n n_qubits = config['n_qubits']\n str_list[0] += (' '*(max_len-len(str_list[0]))+offset)\n str_list[0] += _backends[count].name()\n\n str_list[1] += (' '*(max_len-len(str_list[1]))+offset)\n str_list[1] += '-'*len(_backends[count].name())\n\n str_list[2] += (' '*(max_len-len(str_list[2]))+offset)\n str_list[2] += 'Num. Qubits: %s' % config['n_qubits']\n\n str_list[3] += (' '*(max_len-len(str_list[3]))+offset)\n str_list[3] += 'Pending Jobs: %s' % stati[count].pending_jobs\n\n str_list[4] += (' '*(max_len-len(str_list[4]))+offset)\n str_list[4] += 'Least busy: %s' % (count == least_pending_idx)\n\n str_list[5] += (' '*(max_len-len(str_list[5]))+offset)\n str_list[5] += 'Operational: %s' % stati[count].operational\n\n str_list[6] += (' '*(max_len-len(str_list[6]))+offset)\n str_list[6] += 'Avg. T1: %s' % round(sum([q[0]['value']\n for q in props['qubits']])/n_qubits, 1)\n str_list[7] += (' '*(max_len-len(str_list[7]))+offset)\n str_list[7] += 'Avg. T2: %s' % round(sum([q[1]['value']\n for q in props['qubits']])/n_qubits, 1)\n count += 1\n if count == num_backends:\n break\n max_len = max([len(s) for s in str_list])\n\n print(\"\\n\".join(str_list))\n print('\\n'*2)"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef op(self):\n if 'type' not in self.data_dict or self.data_dict['type'] != 'op':\n raise QiskitError(\"The node %s is not an op node\" % (str(self)))\n return self.data_dict.get('op')", "response": "Returns the Instruction object corresponding to the op for the node else None"}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef wire(self):\n if self.data_dict['type'] not in ['in', 'out']:\n raise QiskitError('The node %s is not an input/output node' % str(self))\n return self.data_dict.get('wire')", "response": "Returns the wire register of the node."}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nchecking if two nodes are considered equivalent.", "response": "def semantic_eq(node1, node2):\n \"\"\"\n Check if DAG nodes are considered equivalent, e.g. as a node_match for nx.is_isomorphic.\n\n Args:\n node1 (DAGNode): A node to compare.\n node2 (DAGNode): The other node to compare.\n\n Return:\n Bool: If node1 == node2\n \"\"\"\n # For barriers, qarg order is not significant so compare as sets\n if 'barrier' == node1.name == node2.name:\n return set(node1.qargs) == set(node2.qargs)\n return node1.data_dict == node2.data_dict"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef constant(duration: int, amp: complex, name: str = None) -> SamplePulse:\n return _sampled_constant_pulse(duration, amp, name=name)", "response": "Generates a constant - sampled sample - pulse."}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngenerates a zero - sampled version of the current object.", "response": "def zero(duration: int, name: str = None) -> SamplePulse:\n \"\"\"Generates zero-sampled `SamplePulse`.\n\n Args:\n duration: Duration of pulse. Must be greater than zero.\n name: Name of pulse.\n \"\"\"\n return _sampled_zero_pulse(duration, name=name)"}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngenerates a square wave.", "response": "def square(duration: int, amp: complex, period: float = None,\n phase: float = 0, name: str = None) -> SamplePulse:\n \"\"\"Generates square wave `SamplePulse`.\n\n Applies `left` sampling strategy to generate discrete pulse from continuous function.\n\n Args:\n duration: Duration of pulse. Must be greater than zero.\n amp: Pulse amplitude. Wave range is [-amp, amp].\n period: Pulse period, units of dt. If `None` defaults to single cycle.\n phase: Pulse phase.\n name: Name of pulse.\n \"\"\"\n if period is None:\n period = duration\n\n return _sampled_square_pulse(duration, amp, period, phase=phase, name=name)"}
+{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef sawtooth(duration: int, amp: complex, period: float = None,\n phase: float = 0, name: str = None) -> SamplePulse:\n \"\"\"Generates sawtooth wave `SamplePulse`.\n\n Args:\n duration: Duration of pulse. Must be greater than zero.\n amp: Pulse amplitude. Wave range is [-amp, amp].\n period: Pulse period, units of dt. If `None` defaults to single cycle.\n phase: Pulse phase.\n name: Name of pulse.\n \"\"\"\n if period is None:\n period = duration\n\n return _sampled_sawtooth_pulse(duration, amp, period, phase=phase, name=name)", "response": "Generates a sawtooth wave."}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngenerating a continuous triangle wave.", "response": "def triangle(duration: int, amp: complex, period: float = None,\n phase: float = 0, name: str = None) -> SamplePulse:\n \"\"\"Generates triangle wave `SamplePulse`.\n\n Applies `left` sampling strategy to generate discrete pulse from continuous function.\n\n Args:\n duration: Duration of pulse. Must be greater than zero.\n amp: Pulse amplitude. Wave range is [-amp, amp].\n period: Pulse period, units of dt. If `None` defaults to single cycle.\n phase: Pulse phase.\n name: Name of pulse.\n \"\"\"\n if period is None:\n period = duration\n\n return _sampled_triangle_pulse(duration, amp, period, phase=phase, name=name)"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef cos(duration: int, amp: complex, freq: float = None,\n phase: float = 0, name: str = None) -> SamplePulse:\n \"\"\"Generates cosine wave `SamplePulse`.\n\n Applies `left` sampling strategy to generate discrete pulse from continuous function.\n\n Args:\n duration: Duration of pulse. Must be greater than zero.\n amp: Pulse amplitude.\n freq: Pulse frequency, units of 1/dt. If `None` defaults to single cycle.\n phase: Pulse phase.\n name: Name of pulse.\n \"\"\"\n if freq is None:\n freq = 1/duration\n\n return _sampled_cos_pulse(duration, amp, freq, phase=phase, name=name)", "response": "Generates a cosine wave from continuous function."}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef sin(duration: int, amp: complex, freq: float = None,\n phase: float = 0, name: str = None) -> SamplePulse:\n \"\"\"Generates sine wave `SamplePulse`.\n\n Args:\n duration: Duration of pulse. Must be greater than zero.\n amp: Pulse amplitude.\n freq: Pulse frequency, units of 1/dt. If `None` defaults to single cycle.\n phase: Pulse phase.\n name: Name of pulse.\n \"\"\"\n if freq is None:\n freq = 1/duration\n\n return _sampled_sin_pulse(duration, amp, freq, phase=phase, name=name)", "response": "Generates a sine wave."}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ngenerating a gaussian square pulse.", "response": "def gaussian_square(duration: int, amp: complex, sigma: float,\n risefall: int, name: str = None) -> SamplePulse:\n \"\"\"Generates gaussian square `SamplePulse`.\n\n Centered at `duration/2` and zeroed at `t=-1` and `t=duration+1` to prevent\n large initial/final discontinuities.\n\n Applies `left` sampling strategy to generate discrete pulse from continuous function.\n\n Args:\n duration: Duration of pulse. Must be greater than zero.\n amp: Pulse amplitude.\n sigma: Width (standard deviation) of gaussian rise/fall portion of the pulse.\n risefall: Number of samples over which pulse rise and fall happen. Width of\n square portion of pulse will be `duration-2*risefall`.\n name: Name of pulse.\n \"\"\"\n center = duration/2\n width = duration-2*risefall\n zeroed_width = duration + 2\n return _sampled_gaussian_square_pulse(duration, amp, center, width, sigma,\n zeroed_width=zeroed_width, name=name)"}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef run(self, dag):\n diagonal_1q_gates = (RZGate, ZGate, TGate, SGate, TdgGate, SdgGate, U1Gate)\n diagonal_2q_gates = (CzGate, CrzGate, Cu1Gate, RZZGate)\n\n nodes_to_remove = set()\n for measure in dag.op_nodes(Measure):\n predecessor = dag.quantum_predecessors(measure)[0]\n\n if predecessor.type == 'op' and isinstance(predecessor.op, diagonal_1q_gates):\n nodes_to_remove.add(predecessor)\n\n if predecessor.type == 'op' and isinstance(predecessor.op, diagonal_2q_gates):\n successors = dag.quantum_successors(predecessor)\n if all([s.type == 'op' and isinstance(s.op, Measure) for s in successors]):\n nodes_to_remove.add(predecessor)\n\n for node_to_remove in nodes_to_remove:\n dag.remove_op_node(node_to_remove)\n\n return dag", "response": "Return a new circuit that has been optimized."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nplotting the gate map of a device.", "response": "def plot_gate_map(backend, figsize=None,\n plot_directed=False,\n label_qubits=True,\n qubit_size=24,\n line_width=4,\n font_size=12,\n qubit_color=None,\n line_color=None,\n font_color='w'):\n \"\"\"Plots the gate map of a device.\n\n Args:\n backend (BaseBackend): A backend instance,\n figsize (tuple): Output figure size (wxh) in inches.\n plot_directed (bool): Plot directed coupling map.\n label_qubits (bool): Label the qubits.\n qubit_size (float): Size of qubit marker.\n line_width (float): Width of lines.\n font_size (int): Font size of qubit labels.\n qubit_color (list): A list of colors for the qubits\n line_color (list): A list of colors for each line from coupling_map.\n font_color (str): The font color for the qubit labels.\n\n Returns:\n Figure: A Matplotlib figure instance.\n\n Raises:\n QiskitError: if tried to pass a simulator.\n ImportError: if matplotlib not installed.\n \"\"\"\n if not HAS_MATPLOTLIB:\n raise ImportError('Must have Matplotlib installed.')\n\n if backend.configuration().simulator:\n raise QiskitError('Requires a device backend, not simulator.')\n\n mpl_data = {}\n\n mpl_data['ibmq_20_tokyo'] = [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4],\n [1, 0], [1, 1], [1, 2], [1, 3], [1, 4],\n [2, 0], [2, 1], [2, 2], [2, 3], [2, 4],\n [3, 0], [3, 1], [3, 2], [3, 3], [3, 4]]\n\n mpl_data['ibmq_poughkeepsie'] = mpl_data['ibmq_20_tokyo']\n\n mpl_data['ibmq_16_melbourne'] = [[0, 0], [0, 1], [0, 2], [0, 3], [0, 4],\n [0, 5], [0, 6], [1, 7], [1, 6], [1, 5],\n [1, 4], [1, 3], [1, 2], [1, 1]]\n\n mpl_data['ibmq_16_rueschlikon'] = [[1, 0], [0, 0], [0, 1], [0, 2], [0, 3],\n [0, 4], [0, 5], [0, 6], [0, 7], [1, 7],\n [1, 6], [1, 5], [1, 4], [1, 3], [1, 2], [1, 1]]\n\n mpl_data['ibmq_5_tenerife'] = [[1, 0], [0, 1], [1, 1], [1, 2], [2, 1]]\n\n mpl_data['ibmq_5_yorktown'] = mpl_data['ibmq_5_tenerife']\n\n config = backend.configuration()\n name = config.backend_name\n cmap = config.coupling_map\n\n dep_names = {'ibmqx5': 'ibmq_16_rueschlikon',\n 'ibmqx4': 'ibmq_5_tenerife',\n 'ibmqx2': 'ibmq_5_yorktown'}\n\n if name in dep_names.keys():\n name = dep_names[name]\n\n if name in mpl_data.keys():\n grid_data = mpl_data[name]\n else:\n fig, ax = plt.subplots(figsize=(5, 5)) # pylint: disable=invalid-name\n ax.axis('off')\n return fig\n\n x_max = max([d[1] for d in grid_data])\n y_max = max([d[0] for d in grid_data])\n max_dim = max(x_max, y_max)\n\n if figsize is None:\n if x_max/max_dim > 0.33 and y_max/max_dim > 0.33:\n figsize = (5, 5)\n else:\n figsize = (9, 3)\n\n fig, ax = plt.subplots(figsize=figsize) # pylint: disable=invalid-name\n ax.axis('off')\n fig.tight_layout()\n\n # set coloring\n if qubit_color is None:\n qubit_color = ['#648fff']*config.n_qubits\n if line_color is None:\n line_color = ['#648fff']*len(cmap)\n\n # Add lines for couplings\n for ind, edge in enumerate(cmap):\n is_symmetric = False\n if edge[::-1] in cmap:\n is_symmetric = True\n y_start = grid_data[edge[0]][0]\n x_start = grid_data[edge[0]][1]\n y_end = grid_data[edge[1]][0]\n x_end = grid_data[edge[1]][1]\n\n if is_symmetric:\n if y_start == y_end:\n x_end = (x_end - x_start)/2+x_start\n\n elif x_start == x_end:\n y_end = (y_end - y_start)/2+y_start\n\n else:\n x_end = (x_end - x_start)/2+x_start\n y_end = (y_end - y_start)/2+y_start\n ax.add_artist(plt.Line2D([x_start, x_end], [-y_start, -y_end],\n color=line_color[ind], linewidth=line_width,\n zorder=0))\n if plot_directed:\n dx = x_end-x_start # pylint: disable=invalid-name\n dy = y_end-y_start # pylint: disable=invalid-name\n if is_symmetric:\n x_arrow = x_start+dx*0.95\n y_arrow = -y_start-dy*0.95\n dx_arrow = dx*0.01\n dy_arrow = -dy*0.01\n head_width = 0.15\n else:\n x_arrow = x_start+dx*0.5\n y_arrow = -y_start-dy*0.5\n dx_arrow = dx*0.2\n dy_arrow = -dy*0.2\n head_width = 0.2\n ax.add_patch(mpatches.FancyArrow(x_arrow,\n y_arrow,\n dx_arrow,\n dy_arrow,\n head_width=head_width,\n length_includes_head=True,\n edgecolor=None,\n linewidth=0,\n facecolor=line_color[ind],\n zorder=1))\n\n # Add circles for qubits\n for var, idx in enumerate(grid_data):\n _idx = [idx[1], -idx[0]]\n width = _GraphDist(qubit_size, ax, True)\n height = _GraphDist(qubit_size, ax, False)\n ax.add_artist(mpatches.Ellipse(\n _idx, width, height, color=qubit_color[var], zorder=1))\n if label_qubits:\n ax.text(*_idx, s=str(var),\n horizontalalignment='center',\n verticalalignment='center',\n color=font_color, size=font_size, weight='bold')\n ax.set_xlim([-1, x_max+1])\n ax.set_ylim([-(y_max+1), 1])\n plt.close(fig)\n return fig"}
+{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ndistances abs of the current time series", "response": "def dist_abs(self):\n \"\"\"Distance abs\n \"\"\"\n bounds = self.ax.get_xlim() if self.x else self.ax.get_ylim()\n return bounds[0] - bounds[1]"}
+{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nprints the node data with indent.", "response": "def to_string(self, indent):\n \"\"\"Print the node data, with indent.\"\"\"\n ind = indent * ' '\n print(ind, 'qreg')\n self.children[0].to_string(indent + 3)"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef _verify_backends(self):\n ret = OrderedDict()\n for backend_cls in SIMULATORS:\n try:\n backend_instance = self._get_backend_instance(backend_cls)\n backend_name = backend_instance.name()\n ret[backend_name] = backend_instance\n except QiskitError as err:\n # Ignore backends that could not be initialized.\n logger.info('Basic Aer backend %s is not available: %s',\n backend_cls, str(err))\n return ret", "response": "Verify that all Basic Aer backends are available."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning an instance of a backend from its class.", "response": "def _get_backend_instance(self, backend_cls):\n \"\"\"\n Return an instance of a backend from its class.\n\n Args:\n backend_cls (class): Backend class.\n Returns:\n BaseBackend: a backend instance.\n Raises:\n QiskitError: if the backend could not be instantiated.\n \"\"\"\n # Verify that the backend can be instantiated.\n try:\n backend_instance = backend_cls(provider=self)\n except Exception as err:\n raise QiskitError('Backend %s could not be instantiated: %s' %\n (backend_cls, err))\n\n return backend_instance"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning a list of qubits as ( QuantumRegister index ) pairs.", "response": "def qubits(self):\n \"\"\"Return a list of qubits as (QuantumRegister, index) pairs.\"\"\"\n return [(v, i) for k, v in self.qregs.items() for i in range(v.size)]"}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns a list of bits as ( ClassicalRegister index ) pairs.", "response": "def clbits(self):\n \"\"\"Return a list of bits as (ClassicalRegister, index) pairs.\"\"\"\n return [(v, i) for k, v in self.cregs.items() for i in range(v.size)]"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nrenaming a classical or quantum register throughout the circuit.", "response": "def rename_register(self, regname, newname):\n \"\"\"Rename a classical or quantum register throughout the circuit.\n\n regname = existing register name string\n newname = replacement register name string\n \"\"\"\n if regname == newname:\n return\n if newname in self.qregs or newname in self.cregs:\n raise DAGCircuitError(\"duplicate register name %s\" % newname)\n if regname not in self.qregs and regname not in self.cregs:\n raise DAGCircuitError(\"no register named %s\" % regname)\n if regname in self.qregs:\n reg = self.qregs[regname]\n reg.name = newname\n self.qregs[newname] = reg\n self.qregs.pop(regname, None)\n if regname in self.cregs:\n reg = self.cregs[regname]\n reg.name = newname\n self.qregs[newname] = reg\n self.qregs.pop(regname, None)\n\n for node in self._multi_graph.nodes():\n if node.type == \"in\" or node.type == \"out\":\n if node.name and regname in node.name:\n node.name = newname\n elif node.type == \"op\":\n qa = []\n for a in node.qargs:\n if a[0] == regname:\n a = (newname, a[1])\n qa.append(a)\n node.qargs = qa\n ca = []\n for a in node.cargs:\n if a[0] == regname:\n a = (newname, a[1])\n ca.append(a)\n node.cargs = ca\n if node.condition is not None:\n if node.condition[0] == regname:\n node.condition = (newname, node.condition[1])\n # eX = edge, d= data\n for _, _, edge_data in self._multi_graph.edges(data=True):\n if regname in edge_data['name']:\n edge_data['name'] = re.sub(regname, newname, edge_data['name'])"}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nremove all operations with the given name.", "response": "def remove_all_ops_named(self, opname):\n \"\"\"Remove all operation nodes with the given name.\"\"\"\n for n in self.named_nodes(opname):\n self.remove_op_node(n)"}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nadds all wires in a quantum register.", "response": "def add_qreg(self, qreg):\n \"\"\"Add all wires in a quantum register.\"\"\"\n if not isinstance(qreg, QuantumRegister):\n raise DAGCircuitError(\"not a QuantumRegister instance.\")\n if qreg.name in self.qregs:\n raise DAGCircuitError(\"duplicate register %s\" % qreg.name)\n self.qregs[qreg.name] = qreg\n for j in range(qreg.size):\n self._add_wire((qreg, j))"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nadding all wires in a classical register.", "response": "def add_creg(self, creg):\n \"\"\"Add all wires in a classical register.\"\"\"\n if not isinstance(creg, ClassicalRegister):\n raise DAGCircuitError(\"not a ClassicalRegister instance.\")\n if creg.name in self.cregs:\n raise DAGCircuitError(\"duplicate register %s\" % creg.name)\n self.cregs[creg.name] = creg\n for j in range(creg.size):\n self._add_wire((creg, j))"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nadd a wire to the circuit.", "response": "def _add_wire(self, wire):\n \"\"\"Add a qubit or bit to the circuit.\n\n Args:\n wire (tuple): (Register,int) containing a register instance and index\n This adds a pair of in and out nodes connected by an edge.\n\n Raises:\n DAGCircuitError: if trying to add duplicate wire\n \"\"\"\n if wire not in self.wires:\n self.wires.append(wire)\n self._max_node_id += 1\n input_map_wire = self.input_map[wire] = self._max_node_id\n\n self._max_node_id += 1\n output_map_wire = self._max_node_id\n\n wire_name = \"%s[%s]\" % (wire[0].name, wire[1])\n\n inp_node = DAGNode(data_dict={'type': 'in', 'name': wire_name, 'wire': wire},\n nid=input_map_wire)\n outp_node = DAGNode(data_dict={'type': 'out', 'name': wire_name, 'wire': wire},\n nid=output_map_wire)\n self._id_to_node[input_map_wire] = inp_node\n self._id_to_node[output_map_wire] = outp_node\n\n self.input_map[wire] = inp_node\n self.output_map[wire] = outp_node\n\n self._multi_graph.add_node(inp_node)\n self._multi_graph.add_node(outp_node)\n\n self._multi_graph.add_edge(inp_node,\n outp_node)\n\n self._multi_graph.adj[inp_node][outp_node][0][\"name\"] \\\n = \"%s[%s]\" % (wire[0].name, wire[1])\n self._multi_graph.adj[inp_node][outp_node][0][\"wire\"] \\\n = wire\n else:\n raise DAGCircuitError(\"duplicate wire %s\" % (wire,))"}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef _check_condition(self, name, condition):\n # Verify creg exists\n if condition is not None and condition[0].name not in self.cregs:\n raise DAGCircuitError(\"invalid creg in condition for %s\" % name)", "response": "Verify that the condition is valid."}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _check_bits(self, args, amap):\n # Check for each wire\n for wire in args:\n if wire not in amap:\n raise DAGCircuitError(\"(qu)bit %s[%d] not found\" %\n (wire[0].name, wire[1]))", "response": "Check the values of a list of ( qu ) bit arguments."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nreturning a list of bits in the given condition.", "response": "def _bits_in_condition(self, cond):\n \"\"\"Return a list of bits in the given condition.\n\n Args:\n cond (tuple or None): optional condition (ClassicalRegister, int)\n\n Returns:\n list[(ClassicalRegister, idx)]: list of bits\n \"\"\"\n all_bits = []\n if cond is not None:\n all_bits.extend([(cond[0], j) for j in range(self.cregs[cond[0].name].size)])\n return all_bits"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nadding a new operation node to the multi - graph and assign properties.", "response": "def _add_op_node(self, op, qargs, cargs, condition=None):\n \"\"\"Add a new operation node to the graph and assign properties.\n\n Args:\n op (Instruction): the operation associated with the DAG node\n qargs (list): list of quantum wires to attach to.\n cargs (list): list of classical wires to attach to.\n condition (tuple or None): optional condition (ClassicalRegister, int)\n \"\"\"\n node_properties = {\n \"type\": \"op\",\n \"op\": op,\n \"name\": op.name,\n \"qargs\": qargs,\n \"cargs\": cargs,\n \"condition\": condition\n }\n\n # Add a new operation node to the graph\n self._max_node_id += 1\n new_node = DAGNode(data_dict=node_properties, nid=self._max_node_id)\n self._multi_graph.add_node(new_node)\n self._id_to_node[self._max_node_id] = new_node"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\napply an operation to the output of the circuit.", "response": "def apply_operation_back(self, op, qargs=None, cargs=None, condition=None):\n \"\"\"Apply an operation to the output of the circuit.\n\n Args:\n op (Instruction): the operation associated with the DAG node\n qargs (list[tuple]): qubits that op will be applied to\n cargs (list[tuple]): cbits that op will be applied to\n condition (tuple or None): optional condition (ClassicalRegister, int)\n\n Returns:\n DAGNode: the current max node\n\n Raises:\n DAGCircuitError: if a leaf node is connected to multiple outputs\n\n \"\"\"\n qargs = qargs or []\n cargs = cargs or []\n\n all_cbits = self._bits_in_condition(condition)\n all_cbits.extend(cargs)\n\n self._check_condition(op.name, condition)\n self._check_bits(qargs, self.output_map)\n self._check_bits(all_cbits, self.output_map)\n\n self._add_op_node(op, qargs, cargs, condition)\n\n # Add new in-edges from predecessors of the output nodes to the\n # operation node while deleting the old in-edges of the output nodes\n # and adding new edges from the operation node to each output node\n al = [qargs, all_cbits]\n for q in itertools.chain(*al):\n ie = list(self._multi_graph.predecessors(self.output_map[q]))\n\n if len(ie) != 1:\n raise DAGCircuitError(\"output node has multiple in-edges\")\n\n self._multi_graph.add_edge(ie[0], self._id_to_node[self._max_node_id],\n name=\"%s[%s]\" % (q[0].name, q[1]), wire=q)\n self._multi_graph.remove_edge(ie[0], self.output_map[q])\n self._multi_graph.add_edge(self._id_to_node[self._max_node_id], self.output_map[q],\n name=\"%s[%s]\" % (q[0].name, q[1]), wire=q)\n\n return self._id_to_node[self._max_node_id]"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _check_edgemap_registers(self, edge_map, keyregs, valregs, valreg=True):\n # FIXME: some mixing of objects and strings here are awkward (due to\n # self.qregs/self.cregs still keying on string.\n add_regs = set()\n reg_frag_chk = {}\n for v in keyregs.values():\n reg_frag_chk[v] = {j: False for j in range(len(v))}\n for k in edge_map.keys():\n if k[0].name in keyregs:\n reg_frag_chk[k[0]][k[1]] = True\n for k, v in reg_frag_chk.items():\n s = set(v.values())\n if len(s) == 2:\n raise DAGCircuitError(\"edge_map fragments reg %s\" % k)\n elif s == set([False]):\n if k in self.qregs.values() or k in self.cregs.values():\n raise DAGCircuitError(\"unmapped duplicate reg %s\" % k)\n else:\n # Add registers that appear only in keyregs\n add_regs.add(k)\n else:\n if valreg:\n # If mapping to a register not in valregs, add it.\n # (k,0) exists in edge_map because edge_map doesn't\n # fragment k\n if not edge_map[(k, 0)][0].name in valregs:\n size = max(map(lambda x: x[1],\n filter(lambda x: x[0] == edge_map[(k, 0)][0],\n edge_map.values())))\n qreg = QuantumRegister(size + 1, edge_map[(k, 0)][0].name)\n add_regs.add(qreg)\n return add_regs", "response": "Check that the wiremap does not leave duplicate registers."}
+{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nchecks that the wire_map is consistent.", "response": "def _check_wiremap_validity(self, wire_map, keymap, valmap):\n \"\"\"Check that the wiremap is consistent.\n\n Check that the wiremap refers to valid wires and that\n those wires have consistent types.\n\n Args:\n wire_map (dict): map from (register,idx) in keymap to\n (register,idx) in valmap\n keymap (dict): a map whose keys are wire_map keys\n valmap (dict): a map whose keys are wire_map values\n\n Raises:\n DAGCircuitError: if wire_map not valid\n \"\"\"\n for k, v in wire_map.items():\n kname = \"%s[%d]\" % (k[0].name, k[1])\n vname = \"%s[%d]\" % (v[0].name, v[1])\n if k not in keymap:\n raise DAGCircuitError(\"invalid wire mapping key %s\" % kname)\n if v not in valmap:\n raise DAGCircuitError(\"invalid wire mapping value %s\" % vname)\n if type(k) is not type(v):\n raise DAGCircuitError(\"inconsistent wire_map at (%s,%s)\" %\n (kname, vname))"}
+{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nmaps the condition tuple to the new condition tuple.", "response": "def _map_condition(self, wire_map, condition):\n \"\"\"Use the wire_map dict to change the condition tuple's creg name.\n\n Args:\n wire_map (dict): a map from wires to wires\n condition (tuple): (ClassicalRegister,int)\n Returns:\n tuple(ClassicalRegister,int): new condition\n \"\"\"\n if condition is None:\n new_condition = None\n else:\n # Map the register name, using fact that registers must not be\n # fragmented by the wire_map (this must have been checked\n # elsewhere)\n bit0 = (condition[0], 0)\n new_condition = (wire_map.get(bit0, bit0)[0], condition[1])\n return new_condition"}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef extend_back(self, dag, edge_map=None):\n edge_map = edge_map or {}\n for qreg in dag.qregs.values():\n if qreg.name not in self.qregs:\n self.add_qreg(QuantumRegister(qreg.size, qreg.name))\n edge_map.update([(qbit, qbit) for qbit in qreg if qbit not in edge_map])\n\n for creg in dag.cregs.values():\n if creg.name not in self.cregs:\n self.add_creg(ClassicalRegister(creg.size, creg.name))\n edge_map.update([(cbit, cbit) for cbit in creg if cbit not in edge_map])\n\n self.compose_back(dag, edge_map)", "response": "Add dag at the end of self using edge_map."}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef compose_back(self, input_circuit, edge_map=None):\n edge_map = edge_map or {}\n\n # Check the wire map for duplicate values\n if len(set(edge_map.values())) != len(edge_map):\n raise DAGCircuitError(\"duplicates in wire_map\")\n\n add_qregs = self._check_edgemap_registers(edge_map,\n input_circuit.qregs,\n self.qregs)\n for qreg in add_qregs:\n self.add_qreg(qreg)\n\n add_cregs = self._check_edgemap_registers(edge_map,\n input_circuit.cregs,\n self.cregs)\n for creg in add_cregs:\n self.add_creg(creg)\n\n self._check_wiremap_validity(edge_map, input_circuit.input_map,\n self.output_map)\n\n # Compose\n for nd in input_circuit.topological_nodes():\n if nd.type == \"in\":\n # if in wire_map, get new name, else use existing name\n m_wire = edge_map.get(nd.wire, nd.wire)\n # the mapped wire should already exist\n if m_wire not in self.output_map:\n raise DAGCircuitError(\"wire %s[%d] not in self\" % (m_wire[0].name, m_wire[1]))\n\n if nd.wire not in input_circuit.wires:\n raise DAGCircuitError(\"inconsistent wire type for %s[%d] in input_circuit\"\n % (nd.wire[0].name, nd.wire[1]))\n\n elif nd.type == \"out\":\n # ignore output nodes\n pass\n elif nd.type == \"op\":\n condition = self._map_condition(edge_map, nd.condition)\n self._check_condition(nd.name, condition)\n m_qargs = list(map(lambda x: edge_map.get(x, x), nd.qargs))\n m_cargs = list(map(lambda x: edge_map.get(x, x), nd.cargs))\n self.apply_operation_back(nd.op, m_qargs, m_cargs, condition)\n else:\n raise DAGCircuitError(\"bad node type %s\" % nd.type)", "response": "Apply the input circuit to the output of this circuit."}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef depth(self):\n if not nx.is_directed_acyclic_graph(self._multi_graph):\n raise DAGCircuitError(\"not a DAG\")\n\n depth = nx.dag_longest_path_length(self._multi_graph) - 1\n return depth if depth != -1 else 0", "response": "Return the depth of the current node in the DAG."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncheck that a list of wires is compatible with a node.", "response": "def _check_wires_list(self, wires, node):\n \"\"\"Check that a list of wires is compatible with a node to be replaced.\n\n - no duplicate names\n - correct length for operation\n Raise an exception otherwise.\n\n Args:\n wires (list[register, index]): gives an order for (qu)bits\n in the input circuit that is replacing the node.\n node (DAGNode): a node in the dag\n\n Raises:\n DAGCircuitError: if check doesn't pass.\n \"\"\"\n if len(set(wires)) != len(wires):\n raise DAGCircuitError(\"duplicate wires\")\n\n wire_tot = len(node.qargs) + len(node.cargs)\n if node.condition is not None:\n wire_tot += node.condition[0].size\n\n if len(wires) != wire_tot:\n raise DAGCircuitError(\"expected %d wires, got %d\"\n % (wire_tot, len(wires)))"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn predecessor and successor dictionaries.", "response": "def _make_pred_succ_maps(self, node):\n \"\"\"Return predecessor and successor dictionaries.\n\n Args:\n node (DAGNode): reference to multi_graph node\n\n Returns:\n tuple(dict): tuple(predecessor_map, successor_map)\n These map from wire (Register, int) to predecessor (successor)\n nodes of n.\n \"\"\"\n\n pred_map = {e[2]['wire']: e[0] for e in\n self._multi_graph.in_edges(nbunch=node, data=True)}\n succ_map = {e[2]['wire']: e[1] for e in\n self._multi_graph.out_edges(nbunch=node, data=True)}\n return pred_map, succ_map"}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _full_pred_succ_maps(self, pred_map, succ_map, input_circuit,\n wire_map):\n \"\"\"Map all wires of the input circuit.\n\n Map all wires of the input circuit to predecessor and\n successor nodes in self, keyed on wires in self.\n\n Args:\n pred_map (dict): comes from _make_pred_succ_maps\n succ_map (dict): comes from _make_pred_succ_maps\n input_circuit (DAGCircuit): the input circuit\n wire_map (dict): the map from wires of input_circuit to wires of self\n\n Returns:\n tuple: full_pred_map, full_succ_map (dict, dict)\n\n Raises:\n DAGCircuitError: if more than one predecessor for output nodes\n \"\"\"\n full_pred_map = {}\n full_succ_map = {}\n for w in input_circuit.input_map:\n # If w is wire mapped, find the corresponding predecessor\n # of the node\n if w in wire_map:\n full_pred_map[wire_map[w]] = pred_map[wire_map[w]]\n full_succ_map[wire_map[w]] = succ_map[wire_map[w]]\n else:\n # Otherwise, use the corresponding output nodes of self\n # and compute the predecessor.\n full_succ_map[w] = self.output_map[w]\n full_pred_map[w] = self._multi_graph.predecessors(\n self.output_map[w])[0]\n if len(list(self._multi_graph.predecessors(self.output_map[w]))) != 1:\n raise DAGCircuitError(\"too many predecessors for %s[%d] \"\n \"output node\" % (w[0], w[1]))\n\n return full_pred_map, full_succ_map", "response": "Map all wires of the input circuit to predecessor and successor nodes in self and compute the full predecessors of the output nodes."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef topological_nodes(self):\n return nx.lexicographical_topological_sort(self._multi_graph,\n key=lambda x: str(x.qargs))", "response": "Yield nodes in topological order."}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nsubstitutes one node with a dag.", "response": "def substitute_node_with_dag(self, node, input_dag, wires=None):\n \"\"\"Replace one node with dag.\n\n Args:\n node (DAGNode): node to substitute\n input_dag (DAGCircuit): circuit that will substitute the node\n wires (list[(Register, index)]): gives an order for (qu)bits\n in the input circuit. This order gets matched to the node wires\n by qargs first, then cargs, then conditions.\n\n Raises:\n DAGCircuitError: if met with unexpected predecessor/successors\n \"\"\"\n if isinstance(node, int):\n warnings.warn('Calling substitute_node_with_dag() with a node id is deprecated,'\n ' use a DAGNode instead',\n DeprecationWarning, 2)\n\n node = self._id_to_node[node]\n\n condition = node.condition\n # the dag must be ammended if used in a\n # conditional context. delete the op nodes and replay\n # them with the condition.\n if condition:\n input_dag.add_creg(condition[0])\n to_replay = []\n for sorted_node in input_dag.topological_nodes():\n if sorted_node.type == \"op\":\n sorted_node.op.control = condition\n to_replay.append(sorted_node)\n for input_node in input_dag.op_nodes():\n input_dag.remove_op_node(input_node)\n for replay_node in to_replay:\n input_dag.apply_operation_back(replay_node.op, replay_node.qargs,\n replay_node.cargs, condition=condition)\n\n if wires is None:\n qwires = [w for w in input_dag.wires if isinstance(w[0], QuantumRegister)]\n cwires = [w for w in input_dag.wires if isinstance(w[0], ClassicalRegister)]\n wires = qwires + cwires\n\n self._check_wires_list(wires, node)\n\n # Create a proxy wire_map to identify fragments and duplicates\n # and determine what registers need to be added to self\n proxy_map = {w: QuantumRegister(1, 'proxy') for w in wires}\n add_qregs = self._check_edgemap_registers(proxy_map,\n input_dag.qregs,\n {}, False)\n for qreg in add_qregs:\n self.add_qreg(qreg)\n\n add_cregs = self._check_edgemap_registers(proxy_map,\n input_dag.cregs,\n {}, False)\n for creg in add_cregs:\n self.add_creg(creg)\n\n # Replace the node by iterating through the input_circuit.\n # Constructing and checking the validity of the wire_map.\n # If a gate is conditioned, we expect the replacement subcircuit\n # to depend on those control bits as well.\n if node.type != \"op\":\n raise DAGCircuitError(\"expected node type \\\"op\\\", got %s\"\n % node.type)\n\n condition_bit_list = self._bits_in_condition(node.condition)\n\n wire_map = {k: v for k, v in zip(wires,\n [i for s in [node.qargs,\n node.cargs,\n condition_bit_list]\n for i in s])}\n self._check_wiremap_validity(wire_map, wires, self.input_map)\n pred_map, succ_map = self._make_pred_succ_maps(node)\n full_pred_map, full_succ_map = self._full_pred_succ_maps(pred_map, succ_map,\n input_dag, wire_map)\n # Now that we know the connections, delete node\n self._multi_graph.remove_node(node)\n\n # Iterate over nodes of input_circuit\n for sorted_node in input_dag.topological_op_nodes():\n # Insert a new node\n condition = self._map_condition(wire_map, sorted_node.condition)\n m_qargs = list(map(lambda x: wire_map.get(x, x),\n sorted_node.qargs))\n m_cargs = list(map(lambda x: wire_map.get(x, x),\n sorted_node.cargs))\n self._add_op_node(sorted_node.op, m_qargs, m_cargs, condition)\n # Add edges from predecessor nodes to new node\n # and update predecessor nodes that change\n all_cbits = self._bits_in_condition(condition)\n all_cbits.extend(m_cargs)\n al = [m_qargs, all_cbits]\n for q in itertools.chain(*al):\n self._multi_graph.add_edge(full_pred_map[q],\n self._id_to_node[self._max_node_id],\n name=\"%s[%s]\" % (q[0].name, q[1]),\n wire=q)\n full_pred_map[q] = self._id_to_node[self._max_node_id]\n\n # Connect all predecessors and successors, and remove\n # residual edges between input and output nodes\n for w in full_pred_map:\n self._multi_graph.add_edge(full_pred_map[w],\n full_succ_map[w],\n name=\"%s[%s]\" % (w[0].name, w[1]),\n wire=w)\n o_pred = list(self._multi_graph.predecessors(self.output_map[w]))\n if len(o_pred) > 1:\n if len(o_pred) != 2:\n raise DAGCircuitError(\"expected 2 predecessors here\")\n\n p = [x for x in o_pred if x != full_pred_map[w]]\n if len(p) != 1:\n raise DAGCircuitError(\"expected 1 predecessor to pass filter\")\n\n self._multi_graph.remove_edge(p[0], self.output_map[w])"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef edges(self, nodes=None):\n for source_node, dest_node, edge_data in self._multi_graph.edges(nodes, data=True):\n yield source_node, dest_node, edge_data", "response": "Iterate over edges of the node values."}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef op_nodes(self, op=None):\n nodes = []\n for node in self._multi_graph.nodes():\n if node.type == \"op\":\n if op is None or isinstance(node.op, op):\n nodes.append(node)\n return nodes", "response": "Returns the list of op nodes in the dag."}
+{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\ngets the list of gate nodes in the dag.", "response": "def gate_nodes(self):\n \"\"\"Get the list of gate nodes in the dag.\n\n Returns:\n list: the list of node ids that represent gates.\n \"\"\"\n nodes = []\n for node in self.op_nodes():\n if isinstance(node.op, Gate):\n nodes.append(node)\n return nodes"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get_named_nodes(self, *names):\n warnings.warn('The method get_named_nodes() is being replaced by named_nodes()',\n 'Returning a list of node_ids is also deprecated, named_nodes() '\n 'returns a list of DAGNodes ',\n DeprecationWarning, 2)\n\n named_nodes = []\n for node in self._multi_graph.nodes():\n if node.type == 'op' and node.op.name in names:\n named_nodes.append(node._node_id)\n return named_nodes", "response": "Deprecated. Use named_nodes instead."}
+{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\ngets the set of op nodes with the given name.", "response": "def named_nodes(self, *names):\n \"\"\"Get the set of \"op\" nodes with the given name.\"\"\"\n named_nodes = []\n for node in self._multi_graph.nodes():\n if node.type == 'op' and node.op.name in names:\n named_nodes.append(node)\n return named_nodes"}
+{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef get_2q_nodes(self):\n warnings.warn('The method get_2q_nodes() is being replaced by twoQ_gates()',\n 'Returning a list of data_dicts is also deprecated, twoQ_gates() '\n 'returns a list of DAGNodes.',\n DeprecationWarning, 2)\n\n two_q_nodes = []\n for node in self._multi_graph.nodes():\n if node.type == 'op' and len(node.qargs) == 2:\n two_q_nodes.append(node.data_dict)\n\n return two_q_nodes", "response": "Deprecated. Use twoQ_gates() to get a list of data_dicts."}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef twoQ_gates(self):\n two_q_gates = []\n for node in self.gate_nodes():\n if len(node.qargs) == 2:\n two_q_gates.append(node)\n return two_q_gates", "response": "Get list of 2 - qubit gates. Ignore snapshot barriers and the like."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nget list of 3 - or - more - qubit gates.", "response": "def threeQ_or_more_gates(self):\n \"\"\"Get list of 3-or-more-qubit gates: (id, data).\"\"\"\n three_q_gates = []\n for node in self.gate_nodes():\n if len(node.qargs) >= 3:\n three_q_gates.append(node)\n return three_q_gates"}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef predecessors(self, node):\n if isinstance(node, int):\n warnings.warn('Calling predecessors() with a node id is deprecated,'\n ' use a DAGNode instead',\n DeprecationWarning, 2)\n node = self._id_to_node[node]\n\n return self._multi_graph.predecessors(node)", "response": "Returns the list of predecessors of a node as DAGNodes."}
+{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef quantum_predecessors(self, node):\n\n predecessors = []\n for predecessor in self.predecessors(node):\n if isinstance(self._multi_graph.get_edge_data(predecessor, node, key=0)['wire'][0],\n QuantumRegister):\n predecessors.append(predecessor)\n return predecessors", "response": "Returns the list of predecessors of a node that are connected by a quantum edge as DAGNodes."}
+{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef ancestors(self, node):\n if isinstance(node, int):\n warnings.warn('Calling ancestors() with a node id is deprecated,'\n ' use a DAGNode instead',\n DeprecationWarning, 2)\n node = self._id_to_node[node]\n\n return nx.ancestors(self._multi_graph, node)", "response": "Returns the set of ancestors of a node as DAGNodes."}
+{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nreturns the list of successors of a node that are connected by a quantum edge as DAGNodes.", "response": "def quantum_successors(self, node):\n \"\"\"Returns list of the successors of a node that are\n connected by a quantum edge as DAGNodes.\"\"\"\n if isinstance(node, int):\n warnings.warn('Calling quantum_successors() with a node id is deprecated,'\n ' use a DAGNode instead',\n DeprecationWarning, 2)\n node = self._id_to_node[node]\n\n successors = []\n for successor in self.successors(node):\n if isinstance(self._multi_graph.get_edge_data(\n node, successor, key=0)['wire'][0],\n QuantumRegister):\n successors.append(successor)\n return successors"}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef remove_op_node(self, node):\n if isinstance(node, int):\n warnings.warn('Calling remove_op_node() with a node id is deprecated,'\n ' use a DAGNode instead',\n DeprecationWarning, 2)\n node = self._id_to_node[node]\n\n if node.type != 'op':\n raise DAGCircuitError('The method remove_op_node only works on op node types. An \"%s\" '\n 'node type was wrongly provided.' % node.type)\n\n pred_map, succ_map = self._make_pred_succ_maps(node)\n\n # remove from graph and map\n self._multi_graph.remove_node(node)\n\n for w in pred_map.keys():\n self._multi_graph.add_edge(pred_map[w], succ_map[w],\n name=\"%s[%s]\" % (w[0].name, w[1]), wire=w)", "response": "Remove an operation node n."}
+{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef remove_ancestors_of(self, node):\n if isinstance(node, int):\n warnings.warn('Calling remove_ancestors_of() with a node id is deprecated,'\n ' use a DAGNode instead',\n DeprecationWarning, 2)\n node = self._id_to_node[node]\n\n anc = nx.ancestors(self._multi_graph, node)\n # TODO: probably better to do all at once using\n # multi_graph.remove_nodes_from; same for related functions ...\n for anc_node in anc:\n if anc_node.type == \"op\":\n self.remove_op_node(anc_node)", "response": "Remove all of the ancestor operation nodes of node."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef remove_descendants_of(self, node):\n if isinstance(node, int):\n warnings.warn('Calling remove_descendants_of() with a node id is deprecated,'\n ' use a DAGNode instead',\n DeprecationWarning, 2)\n node = self._id_to_node[node]\n\n desc = nx.descendants(self._multi_graph, node)\n for desc_node in desc:\n if desc_node.type == \"op\":\n self.remove_op_node(desc_node)", "response": "Remove all of the descendant operation nodes of node."}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef remove_nonancestors_of(self, node):\n if isinstance(node, int):\n warnings.warn('Calling remove_nonancestors_of() with a node id is deprecated,'\n ' use a DAGNode instead',\n DeprecationWarning, 2)\n node = self._id_to_node[node]\n\n anc = nx.ancestors(self._multi_graph, node)\n comp = list(set(self._multi_graph.nodes()) - set(anc))\n for n in comp:\n if n.type == \"op\":\n self.remove_op_node(n)", "response": "Remove all of the non - ancestors operation nodes of node."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nremoving all of the non - descendant operation nodes of node.", "response": "def remove_nondescendants_of(self, node):\n \"\"\"Remove all of the non-descendants operation nodes of node.\"\"\"\n if isinstance(node, int):\n warnings.warn('Calling remove_nondescendants_of() with a node id is deprecated,'\n ' use a DAGNode instead',\n DeprecationWarning, 2)\n node = self._id_to_node[node]\n\n dec = nx.descendants(self._multi_graph, node)\n comp = list(set(self._multi_graph.nodes()) - set(dec))\n for n in comp:\n if n.type == \"op\":\n self.remove_op_node(n)"}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef layers(self):\n graph_layers = self.multigraph_layers()\n try:\n next(graph_layers) # Remove input nodes\n except StopIteration:\n return\n\n def add_nodes_from(layer, nodes):\n \"\"\" Convert DAGNodes into a format that can be added to a\n multigraph and then add to graph\"\"\"\n layer._multi_graph.add_nodes_from(nodes)\n\n for graph_layer in graph_layers:\n\n # Get the op nodes from the layer, removing any input and output nodes.\n op_nodes = [node for node in graph_layer if node.type == \"op\"]\n\n # Stop yielding once there are no more op_nodes in a layer.\n if not op_nodes:\n return\n\n # Construct a shallow copy of self\n new_layer = DAGCircuit()\n new_layer.name = self.name\n\n for creg in self.cregs.values():\n new_layer.add_creg(creg)\n for qreg in self.qregs.values():\n new_layer.add_qreg(qreg)\n\n add_nodes_from(new_layer, self.input_map.values())\n add_nodes_from(new_layer, self.output_map.values())\n add_nodes_from(new_layer, op_nodes)\n\n # The quantum registers that have an operation in this layer.\n support_list = [\n op_node.qargs\n for op_node in op_nodes\n if op_node.name not in {\"barrier\", \"snapshot\", \"save\", \"load\", \"noise\"}\n ]\n\n # Now add the edges to the multi_graph\n # By default we just wire inputs to the outputs.\n wires = {self.input_map[wire]: self.output_map[wire]\n for wire in self.wires}\n # Wire inputs to op nodes, and op nodes to outputs.\n for op_node in op_nodes:\n args = self._bits_in_condition(op_node.condition) \\\n + op_node.cargs + op_node.qargs\n arg_ids = (self.input_map[(arg[0], arg[1])] for arg in args)\n for arg_id in arg_ids:\n wires[arg_id], wires[op_node] = op_node, wires[arg_id]\n\n # Add wiring to/from the operations and between unused inputs & outputs.\n new_layer._multi_graph.add_edges_from(wires.items())\n yield {\"graph\": new_layer, \"partition\": support_list}", "response": "Yields a shallow view on all d layers of this circuit."}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef serial_layers(self):\n for next_node in self.topological_op_nodes():\n new_layer = DAGCircuit()\n for qreg in self.qregs.values():\n new_layer.add_qreg(qreg)\n for creg in self.cregs.values():\n new_layer.add_creg(creg)\n # Save the support of the operation we add to the layer\n support_list = []\n # Operation data\n op = copy.copy(next_node.op)\n qa = copy.copy(next_node.qargs)\n ca = copy.copy(next_node.cargs)\n co = copy.copy(next_node.condition)\n _ = self._bits_in_condition(co)\n\n # Add node to new_layer\n new_layer.apply_operation_back(op, qa, ca, co)\n # Add operation to partition\n if next_node.name not in [\"barrier\",\n \"snapshot\", \"save\", \"load\", \"noise\"]:\n support_list.append(list(qa))\n l_dict = {\"graph\": new_layer, \"partition\": support_list}\n yield l_dict", "response": "Yields a list of all serial layers for all gates of this circuit."}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef multigraph_layers(self):\n predecessor_count = dict() # Dict[node, predecessors not visited]\n cur_layer = [node for node in self.input_map.values()]\n yield cur_layer\n next_layer = []\n while cur_layer:\n for node in cur_layer:\n # Count multiedges with multiplicity.\n for successor in self._multi_graph.successors(node):\n multiplicity = self._multi_graph.number_of_edges(node, successor)\n if successor in predecessor_count:\n predecessor_count[successor] -= multiplicity\n else:\n predecessor_count[successor] = \\\n self._multi_graph.in_degree(successor) - multiplicity\n\n if predecessor_count[successor] == 0:\n next_layer.append(successor)\n del predecessor_count[successor]\n\n yield next_layer\n cur_layer = next_layer\n next_layer = []", "response": "Yields all layers of the multigraph."}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef collect_runs(self, namelist):\n group_list = []\n\n # Iterate through the nodes of self in topological order\n # and form tuples containing sequences of gates\n # on the same qubit(s).\n topo_ops = list(self.topological_op_nodes())\n nodes_seen = dict(zip(topo_ops, [False] * len(topo_ops)))\n for node in topo_ops:\n if node.name in namelist and node.condition is None \\\n and not nodes_seen[node]:\n group = [node]\n nodes_seen[node] = True\n s = list(self._multi_graph.successors(node))\n while len(s) == 1 and \\\n s[0].type == \"op\" and \\\n s[0].name in namelist:\n group.append(s[0])\n nodes_seen[s[0]] = True\n s = list(self._multi_graph.successors(s[0]))\n if len(group) >= 1:\n group_list.append(tuple(group))\n return set(group_list)", "response": "Return a set of non - conditional runs of op nodes with the given names."}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef nodes_on_wire(self, wire, only_ops=False):\n current_node = self.input_map.get(wire, None)\n\n if not current_node:\n raise DAGCircuitError('The given wire %s is not present in the circuit'\n % str(wire))\n\n more_nodes = True\n while more_nodes:\n more_nodes = False\n # allow user to just get ops on the wire - not the input/output nodes\n if current_node.type == 'op' or not only_ops:\n yield current_node\n\n # find the adjacent node that takes the wire being looked at as input\n for node, edges in self._multi_graph.adj[current_node].items():\n if any(wire == edge['wire'] for edge in edges.values()):\n current_node = node\n more_nodes = True\n break", "response": "Iterator for nodes that affect a given wire."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef count_ops(self):\n op_dict = {}\n for node in self.topological_op_nodes():\n name = node.name\n if name not in op_dict:\n op_dict[name] = 1\n else:\n op_dict[name] += 1\n return op_dict", "response": "Count the occurrences of operation names."}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef properties(self):\n summary = {\"size\": self.size(),\n \"depth\": self.depth(),\n \"width\": self.width(),\n \"bits\": self.num_cbits(),\n \"factors\": self.num_tensor_factors(),\n \"operations\": self.count_ops()}\n return summary", "response": "Return a dictionary of circuit properties."}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef tomography_basis(basis, prep_fun=None, meas_fun=None):\n ret = TomographyBasis(basis)\n ret.prep_fun = prep_fun\n ret.meas_fun = meas_fun\n return ret", "response": "Generates a TomographyBasis object from a list of functions."}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef __pauli_prep_gates(circuit, qreg, op):\n bas, proj = op\n if bas not in ['X', 'Y', 'Z']:\n raise QiskitError(\"There's no X, Y or Z basis for this Pauli \"\n \"preparation\")\n\n if bas == \"X\":\n if proj == 1:\n circuit.u2(np.pi, np.pi, qreg) # H.X\n else:\n circuit.u2(0., np.pi, qreg) # H\n elif bas == \"Y\":\n if proj == 1:\n circuit.u2(-0.5 * np.pi, np.pi, qreg) # S.H.X\n else:\n circuit.u2(0.5 * np.pi, np.pi, qreg) # S.H\n elif bas == \"Z\" and proj == 1:\n circuit.u3(np.pi, 0., np.pi, qreg)", "response": "Add state preparation gates to a circuit."}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef __pauli_meas_gates(circuit, qreg, op):\n if op not in ['X', 'Y', 'Z']:\n raise QiskitError(\"There's no X, Y or Z basis for this Pauli \"\n \"measurement\")\n\n if op == \"X\":\n circuit.u2(0., np.pi, qreg) # H\n elif op == \"Y\":\n circuit.u2(0., 0.5 * np.pi, qreg)", "response": "Add state measurement gates to a circuit."}
+{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nadd state preparation gates to a SIC.", "response": "def __sic_prep_gates(circuit, qreg, op):\n \"\"\"\n Add state preparation gates to a circuit.\n \"\"\"\n bas, proj = op\n\n if bas != 'S':\n raise QiskitError('Not in SIC basis!')\n\n theta = -2 * np.arctan(np.sqrt(2))\n if proj == 1:\n circuit.u3(theta, np.pi, 0.0, qreg)\n elif proj == 2:\n circuit.u3(theta, np.pi / 3, 0.0, qreg)\n elif proj == 3:\n circuit.u3(theta, -np.pi / 3, 0.0, qreg)"}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ngenerates a dictionary of process tomography experiment configurations. This returns a data structure that is used by other tomography functions to generate state and process tomography circuits, and extract tomography data from results after execution on a backend. A quantum process tomography set is created by specifying a preparation basis along with a measurement basis. The preparation basis may be a user defined `tomography_basis`, or one of the two built in basis 'SIC' or 'Pauli'. - SIC: Is a minimal symmetric informationally complete preparation basis for 4 states for each qubit (4 ^ number of qubits total preparation states). These correspond to the |0> state and the 3 other vertices of a tetrahedron on the Bloch-sphere. - Pauli: Is a tomographically overcomplete preparation basis of the six eigenstates of the 3 Pauli operators (6 ^ number of qubits total preparation states). Args: meas_qubits (list): The qubits being measured. meas_basis (tomography_basis or str): The qubit measurement basis. The default value is 'Pauli'. prep_qubits (list or None): The qubits being prepared. If None then meas_qubits will be used for process tomography experiments. prep_basis (tomography_basis or str): The qubit preparation basis. The default value is 'SIC'. Returns: dict: A dict of tomography configurations that can be parsed by `create_tomography_circuits` and `tomography_data` functions for implementing quantum tomography experiments. This output contains fields \"qubits\", \"meas_basis\", \"prep_basus\", circuits\". ``` { 'qubits': qubits (list[ints]), 'meas_basis': meas_basis (tomography_basis), 'prep_basis': prep_basis (tomography_basis), 'circuit_labels': (list[string]), 'circuits': (list[dict]) # prep and meas configurations } ```", "response": "def process_tomography_set(meas_qubits, meas_basis='Pauli',\n prep_qubits=None, prep_basis='SIC'):\n \"\"\"\n Generate a dictionary of process tomography experiment configurations.\n\n This returns a data structure that is used by other tomography functions\n to generate state and process tomography circuits, and extract tomography\n data from results after execution on a backend.\n\n A quantum process tomography set is created by specifying a preparation\n basis along with a measurement basis. The preparation basis may be a\n user defined `tomography_basis`, or one of the two built in basis 'SIC'\n or 'Pauli'.\n - SIC: Is a minimal symmetric informationally complete preparation\n basis for 4 states for each qubit (4 ^ number of qubits total\n preparation states). These correspond to the |0> state and the 3\n other vertices of a tetrahedron on the Bloch-sphere.\n - Pauli: Is a tomographically overcomplete preparation basis of the six\n eigenstates of the 3 Pauli operators (6 ^ number of qubits\n total preparation states).\n\n Args:\n meas_qubits (list): The qubits being measured.\n meas_basis (tomography_basis or str): The qubit measurement basis.\n The default value is 'Pauli'.\n prep_qubits (list or None): The qubits being prepared. If None then\n meas_qubits will be used for process tomography experiments.\n prep_basis (tomography_basis or str): The qubit preparation basis.\n The default value is 'SIC'.\n\n Returns:\n dict: A dict of tomography configurations that can be parsed by\n `create_tomography_circuits` and `tomography_data` functions\n for implementing quantum tomography experiments. This output contains\n fields \"qubits\", \"meas_basis\", \"prep_basus\", circuits\".\n ```\n {\n 'qubits': qubits (list[ints]),\n 'meas_basis': meas_basis (tomography_basis),\n 'prep_basis': prep_basis (tomography_basis),\n 'circuit_labels': (list[string]),\n 'circuits': (list[dict]) # prep and meas configurations\n }\n ```\n \"\"\"\n return tomography_set(meas_qubits, meas_basis=meas_basis,\n prep_qubits=prep_qubits, prep_basis=prep_basis)"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nadd tomography measurement circuits to a QuantumProgram. The quantum program must contain a circuit 'name', which is treated as a state preparation circuit for state tomography, or as teh circuit being measured for process tomography. This function then appends the circuit with a set of measurements specified by the input `tomography_set`, optionally it also prepends the circuit with state preparation circuits if they are specified in the `tomography_set`. For n-qubit tomography with a tomographically complete set of preparations and measurements this results in $4^n 3^n$ circuits being added to the quantum program. Args: circuit (QuantumCircuit): The circuit to be appended with tomography state preparation and/or measurements. qreg (QuantumRegister): the quantum register containing qubits to be measured. creg (ClassicalRegister): the classical register containing bits to store measurement outcomes. tomoset (tomography_set): the dict of tomography configurations. Returns: list: A list of quantum tomography circuits for the input circuit. Raises: QiskitError: if circuit is not a valid QuantumCircuit Example: For a tomography set specifying state tomography of qubit-0 prepared by a circuit 'circ' this would return: ``` ['circ_meas_X(0)', 'circ_meas_Y(0)', 'circ_meas_Z(0)'] ``` For process tomography of the same circuit with preparation in the SIC-POVM basis it would return: ``` [ 'circ_prep_S0(0)_meas_X(0)', 'circ_prep_S0(0)_meas_Y(0)', 'circ_prep_S0(0)_meas_Z(0)', 'circ_prep_S1(0)_meas_X(0)', 'circ_prep_S1(0)_meas_Y(0)', 'circ_prep_S1(0)_meas_Z(0)', 'circ_prep_S2(0)_meas_X(0)', 'circ_prep_S2(0)_meas_Y(0)', 'circ_prep_S2(0)_meas_Z(0)', 'circ_prep_S3(0)_meas_X(0)', 'circ_prep_S3(0)_meas_Y(0)', 'circ_prep_S3(0)_meas_Z(0)' ] ```", "response": "def create_tomography_circuits(circuit, qreg, creg, tomoset):\n \"\"\"\n Add tomography measurement circuits to a QuantumProgram.\n\n The quantum program must contain a circuit 'name', which is treated as a\n state preparation circuit for state tomography, or as teh circuit being\n measured for process tomography. This function then appends the circuit\n with a set of measurements specified by the input `tomography_set`,\n optionally it also prepends the circuit with state preparation circuits if\n they are specified in the `tomography_set`.\n\n For n-qubit tomography with a tomographically complete set of preparations\n and measurements this results in $4^n 3^n$ circuits being added to the\n quantum program.\n\n Args:\n circuit (QuantumCircuit): The circuit to be appended with tomography\n state preparation and/or measurements.\n qreg (QuantumRegister): the quantum register containing qubits to be\n measured.\n creg (ClassicalRegister): the classical register containing bits to\n store measurement outcomes.\n tomoset (tomography_set): the dict of tomography configurations.\n\n Returns:\n list: A list of quantum tomography circuits for the input circuit.\n\n Raises:\n QiskitError: if circuit is not a valid QuantumCircuit\n\n Example:\n For a tomography set specifying state tomography of qubit-0 prepared\n by a circuit 'circ' this would return:\n ```\n ['circ_meas_X(0)', 'circ_meas_Y(0)', 'circ_meas_Z(0)']\n ```\n For process tomography of the same circuit with preparation in the\n SIC-POVM basis it would return:\n ```\n [\n 'circ_prep_S0(0)_meas_X(0)', 'circ_prep_S0(0)_meas_Y(0)',\n 'circ_prep_S0(0)_meas_Z(0)', 'circ_prep_S1(0)_meas_X(0)',\n 'circ_prep_S1(0)_meas_Y(0)', 'circ_prep_S1(0)_meas_Z(0)',\n 'circ_prep_S2(0)_meas_X(0)', 'circ_prep_S2(0)_meas_Y(0)',\n 'circ_prep_S2(0)_meas_Z(0)', 'circ_prep_S3(0)_meas_X(0)',\n 'circ_prep_S3(0)_meas_Y(0)', 'circ_prep_S3(0)_meas_Z(0)'\n ]\n ```\n \"\"\"\n\n if not isinstance(circuit, QuantumCircuit):\n raise QiskitError('Input circuit must be a QuantumCircuit object')\n\n dics = tomoset['circuits']\n labels = tomography_circuit_names(tomoset, circuit.name)\n tomography_circuits = []\n for label, conf in zip(labels, dics):\n tmp = circuit\n # Add prep circuits\n if 'prep' in conf:\n prep = QuantumCircuit(qreg, creg, name='tmp_prep')\n for qubit, op in conf['prep'].items():\n tomoset['prep_basis'].prep_gate(prep, qreg[qubit], op)\n prep.barrier(qreg[qubit])\n tmp = prep + tmp\n # Add measurement circuits\n meas = QuantumCircuit(qreg, creg, name='tmp_meas')\n for qubit, op in conf['meas'].items():\n meas.barrier(qreg[qubit])\n tomoset['meas_basis'].meas_gate(meas, qreg[qubit], op)\n meas.measure(qreg[qubit], creg[qubit])\n tmp = tmp + meas\n # Add label to the circuit\n tmp.name = label\n tomography_circuits.append(tmp)\n\n logger.info('>> created tomography circuits for \"%s\"', circuit.name)\n return tomography_circuits"}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns a dictionary for a state or process tomography experiment.", "response": "def tomography_data(results, name, tomoset):\n \"\"\"\n Return a results dict for a state or process tomography experiment.\n\n Args:\n results (Result): Results from execution of a process tomography\n circuits on a backend.\n name (string): The name of the circuit being reconstructed.\n tomoset (tomography_set): the dict of tomography configurations.\n\n Returns:\n list: A list of dicts for the outcome of each process tomography\n measurement circuit.\n \"\"\"\n\n labels = tomography_circuit_names(tomoset, name)\n circuits = tomoset['circuits']\n data = []\n prep = None\n for j, _ in enumerate(labels):\n counts = marginal_counts(results.get_counts(labels[j]),\n tomoset['qubits'])\n shots = sum(counts.values())\n meas = circuits[j]['meas']\n prep = circuits[j].get('prep', None)\n meas_qubits = sorted(meas.keys())\n if prep:\n prep_qubits = sorted(prep.keys())\n circuit = {}\n for c in counts.keys():\n circuit[c] = {}\n circuit[c]['meas'] = [(meas[meas_qubits[k]], int(c[-1 - k]))\n for k in range(len(meas_qubits))]\n if prep:\n circuit[c]['prep'] = [prep[prep_qubits[k]]\n for k in range(len(prep_qubits))]\n data.append({'counts': counts, 'shots': shots, 'circuit': circuit})\n\n ret = {'data': data, 'meas_basis': tomoset['meas_basis']}\n if prep:\n ret['prep_basis'] = tomoset['prep_basis']\n return ret"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\ncomputing the marginal counts for a subset of measured qubits.", "response": "def marginal_counts(counts, meas_qubits):\n \"\"\"\n Compute the marginal counts for a subset of measured qubits.\n\n Args:\n counts (dict): the counts returned from a backend ({str: int}).\n meas_qubits (list[int]): the qubits to return the marginal\n counts distribution for.\n\n Returns:\n dict: A counts dict for the meas_qubits.abs\n Example: if `counts = {'00': 10, '01': 5}`\n `marginal_counts(counts, [0])` returns `{'0': 15, '1': 0}`.\n `marginal_counts(counts, [0])` returns `{'0': 10, '1': 5}`.\n \"\"\"\n # pylint: disable=cell-var-from-loop\n # Extract total number of qubits from count keys\n num_of_qubits = len(list(counts.keys())[0])\n\n # keys for measured qubits only\n qs = sorted(meas_qubits, reverse=True)\n\n meas_keys = count_keys(len(qs))\n\n # get regex match strings for summing outcomes of other qubits\n rgx = [\n reduce(lambda x, y: (key[qs.index(y)] if y in qs else '\\\\d') + x,\n range(num_of_qubits), '') for key in meas_keys\n ]\n\n # build the return list\n meas_counts = []\n for m in rgx:\n c = 0\n for key, val in counts.items():\n if match(m, key):\n c += val\n meas_counts.append(c)\n\n # return as counts dict on measured qubits only\n return dict(zip(meas_keys, meas_counts))"}
+{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nfits a Choi - matrix or process - matrix from tomography measurement data.", "response": "def fit_tomography_data(tomo_data, method='wizard', options=None):\n \"\"\"\n Reconstruct a density matrix or process-matrix from tomography data.\n\n If the input data is state_tomography_data the returned operator will\n be a density matrix. If the input data is process_tomography_data the\n returned operator will be a Choi-matrix in the column-vectorization\n convention.\n\n Args:\n tomo_data (dict): process tomography measurement data.\n method (str): the fitting method to use.\n Available methods:\n - 'wizard' (default)\n - 'leastsq'\n options (dict or None): additional options for fitting method.\n\n Returns:\n numpy.array: The fitted operator.\n\n Available methods:\n - 'wizard' (Default): The returned operator will be constrained to be\n positive-semidefinite.\n Options:\n - 'trace': the trace of the returned operator.\n The default value is 1.\n - 'beta': hedging parameter for computing frequencies from\n zero-count data. The default value is 0.50922.\n - 'epsilon: threshold for truncating small eigenvalues to zero.\n The default value is 0\n - 'leastsq': Fitting without positive-semidefinite constraint.\n Options:\n - 'trace': Same as for 'wizard' method.\n - 'beta': Same as for 'wizard' method.\n Raises:\n Exception: if the `method` parameter is not valid.\n \"\"\"\n\n if isinstance(method, str) and method.lower() in ['wizard', 'leastsq']:\n # get options\n trace = __get_option('trace', options)\n beta = __get_option('beta', options)\n # fit state\n rho = __leastsq_fit(tomo_data, trace=trace, beta=beta)\n if method == 'wizard':\n # Use wizard method to constrain positivity\n epsilon = __get_option('epsilon', options)\n rho = __wizard(rho, epsilon=epsilon)\n return rho\n else:\n raise Exception('Invalid reconstruction method \"%s\"' % method)"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef __leastsq_fit(tomo_data, weights=None, trace=None, beta=None):\n if trace is None:\n trace = 1. # default to unit trace\n\n data = tomo_data['data']\n keys = data[0]['circuit'].keys()\n\n # Get counts and shots\n counts = []\n shots = []\n ops = []\n for dat in data:\n for key in keys:\n counts.append(dat['counts'][key])\n shots.append(dat['shots'])\n projectors = dat['circuit'][key]\n op = __projector(projectors['meas'], tomo_data['meas_basis'])\n if 'prep' in projectors:\n op_prep = __projector(projectors['prep'],\n tomo_data['prep_basis'])\n op = np.kron(op_prep.conj(), op)\n ops.append(op)\n\n # Convert counts to frequencies\n counts = np.array(counts)\n shots = np.array(shots)\n freqs = counts / shots\n\n # Use hedged frequencies to calculate least squares fitting weights\n if weights is None:\n if beta is None:\n beta = 0.50922\n K = len(keys)\n freqs_hedged = (counts + beta) / (shots + K * beta)\n weights = np.sqrt(shots / (freqs_hedged * (1 - freqs_hedged)))\n\n return __tomo_linear_inv(freqs, ops, weights, trace=trace)", "response": "Reconstruct a state from unconstrained least - squares fitting."}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef __tomo_linear_inv(freqs, ops, weights=None, trace=None):\n # get weights matrix\n if weights is not None:\n W = np.array(weights)\n if W.ndim == 1:\n W = np.diag(W)\n\n # Get basis S matrix\n S = np.array([vectorize(m).conj()\n for m in ops]).reshape(len(ops), ops[0].size)\n if weights is not None:\n S = np.dot(W, S) # W.S\n\n # get frequencies vec\n v = np.array(freqs) # |f>\n if weights is not None:\n v = np.dot(W, freqs) # W.|f>\n Sdg = S.T.conj() # S^*.W^*\n inv = np.linalg.pinv(np.dot(Sdg, S)) # (S^*.W^*.W.S)^-1\n\n # linear inversion of freqs\n ret = devectorize(np.dot(inv, np.dot(Sdg, v)))\n # renormalize to input trace value\n if trace is not None:\n ret = trace * ret / np.trace(ret)\n return ret", "response": "Reconstruct a matrix through linear inversion of the given freqs and ops."}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nreturning the nearest positive semidefinite operator to an operator. This method is based on reference [1]. It constrains positivity by setting negative eigenvalues to zero and rescaling the positive eigenvalues. Args: rho (array_like): the input operator. epsilon(float or None): threshold (>=0) for truncating small eigenvalues values to zero. Returns: numpy.array: A positive semidefinite numpy array.", "response": "def __wizard(rho, epsilon=None):\n \"\"\"\n Returns the nearest positive semidefinite operator to an operator.\n\n This method is based on reference [1]. It constrains positivity\n by setting negative eigenvalues to zero and rescaling the positive\n eigenvalues.\n\n Args:\n rho (array_like): the input operator.\n epsilon(float or None): threshold (>=0) for truncating small\n eigenvalues values to zero.\n\n Returns:\n numpy.array: A positive semidefinite numpy array.\n \"\"\"\n if epsilon is None:\n epsilon = 0. # default value\n\n dim = len(rho)\n rho_wizard = np.zeros([dim, dim])\n v, w = np.linalg.eigh(rho) # v eigenvecrors v[0] < v[1] <...\n for j in range(dim):\n if v[j] < epsilon:\n tmp = v[j]\n v[j] = 0.\n # redistribute loop\n x = 0.\n for k in range(j + 1, dim):\n x += tmp / (dim - (j + 1))\n v[k] = v[k] + tmp / (dim - (j + 1))\n for j in range(dim):\n rho_wizard = rho_wizard + v[j] * outer(w[:, j])\n return rho_wizard"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nbuild the list of circuits to rotate to points in phase space.", "response": "def build_wigner_circuits(circuit, phis, thetas, qubits,\n qreg, creg):\n \"\"\"Create the circuits to rotate to points in phase space\n Args:\n circuit (QuantumCircuit): The circuit to be appended with tomography\n state preparation and/or measurements.\n phis (np.matrix[[complex]]): phis\n thetas (np.matrix[[complex]]): thetas\n qubits (list[int]): a list of the qubit indexes of qreg to be measured.\n qreg (QuantumRegister): the quantum register containing qubits to be\n measured.\n creg (ClassicalRegister): the classical register containing bits to\n store measurement outcomes.\n\n Returns:\n list: A list of names of the added wigner function circuits.\n\n Raises:\n QiskitError: if circuit is not a valid QuantumCircuit.\n \"\"\"\n\n if not isinstance(circuit, QuantumCircuit):\n raise QiskitError('Input circuit must be a QuantumCircuit object')\n\n tomography_circuits = []\n points = len(phis[0])\n for point in range(points):\n label = '_wigner_phase_point'\n label += str(point)\n tmp_circ = QuantumCircuit(qreg, creg, name=label)\n for qubit, _ in enumerate(qubits):\n tmp_circ.u3(thetas[qubit][point], 0,\n phis[qubit][point], qreg[qubits[qubit]])\n tmp_circ.measure(qreg[qubits[qubit]], creg[qubits[qubit]])\n # Add to original circuit\n tmp_circ = circuit + tmp_circ\n tmp_circ.name = circuit.name + label\n tomography_circuits.append(tmp_circ)\n\n logger.info('>> Created Wigner function circuits for \"%s\"', circuit.name)\n return tomography_circuits"}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nget the value of the Wigner function at measured points in the state tomography.", "response": "def wigner_data(q_result, meas_qubits, labels, shots=None):\n \"\"\"Get the value of the Wigner function from measurement results.\n\n Args:\n q_result (Result): Results from execution of a state tomography\n circuits on a backend.\n meas_qubits (list[int]): a list of the qubit indexes measured.\n labels (list[str]): a list of names of the circuits\n shots (int): number of shots\n\n Returns:\n list: The values of the Wigner function at measured points in\n phase space\n \"\"\"\n num = len(meas_qubits)\n\n dim = 2**num\n p = [0.5 + 0.5 * np.sqrt(3), 0.5 - 0.5 * np.sqrt(3)]\n parity = 1\n\n for i in range(num):\n parity = np.kron(parity, p)\n\n w = [0] * len(labels)\n wpt = 0\n counts = [marginal_counts(q_result.get_counts(circ), meas_qubits)\n for circ in labels]\n for entry in counts:\n x = [0] * dim\n\n for i in range(dim):\n if bin(i)[2:].zfill(num) in entry:\n x[i] = float(entry[bin(i)[2:].zfill(num)])\n\n if shots is None:\n shots = np.sum(x)\n\n for i in range(dim):\n w[wpt] = w[wpt] + (x[i] / shots) * parity[i]\n wpt += 1\n\n return w"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nadd state preparation gates to a circuit.", "response": "def prep_gate(self, circuit, qreg, op):\n \"\"\"\n Add state preparation gates to a circuit.\n\n Args:\n circuit (QuantumCircuit): circuit to add a preparation to.\n qreg (tuple(QuantumRegister,int)): quantum register to apply\n preparation to.\n op (tuple(str, int)): the basis label and index for the\n preparation op.\n \"\"\"\n if self.prep_fun is None:\n pass\n else:\n self.prep_fun(circuit, qreg, op)"}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef meas_gate(self, circuit, qreg, op):\n if self.meas_fun is None:\n pass\n else:\n self.meas_fun(circuit, qreg, op)", "response": "Add measurement gates to a circuit."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _text_checker(job, interval, _interval_set=False, quiet=False, output=sys.stdout):\n status = job.status()\n msg = status.value\n prev_msg = msg\n msg_len = len(msg)\n\n if not quiet:\n print('\\r%s: %s' % ('Job Status', msg), end='', file=output)\n while status.name not in ['DONE', 'CANCELLED', 'ERROR']:\n time.sleep(interval)\n status = job.status()\n msg = status.value\n\n if status.name == 'QUEUED':\n msg += ' (%s)' % job.queue_position()\n if not _interval_set:\n interval = max(job.queue_position(), 2)\n else:\n if not _interval_set:\n interval = 2\n\n # Adjust length of message so there are no artifacts\n if len(msg) < msg_len:\n msg += ' ' * (msg_len - len(msg))\n elif len(msg) > msg_len:\n msg_len = len(msg)\n\n if msg != prev_msg and not quiet:\n print('\\r%s: %s' % ('Job Status', msg), end='', file=output)\n prev_msg = msg\n if not quiet:\n print('', file=output)", "response": "A text - based job status checker."}
+{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nmonitor the status of a Jupyter notebook.", "response": "def job_monitor(job, interval=None, monitor_async=False, quiet=False, output=sys.stdout):\n \"\"\"Monitor the status of a IBMQJob instance.\n\n Args:\n job (BaseJob): Job to monitor.\n interval (int): Time interval between status queries.\n monitor_async (bool): Monitor asyncronously (in Jupyter only).\n quiet (bool): If True, do not print status messages.\n output (file): The file like object to write status messages to.\n By default this is sys.stdout.\n\n Raises:\n QiskitError: When trying to run async outside of Jupyter\n ImportError: ipywidgets not available for notebook.\n \"\"\"\n if interval is None:\n _interval_set = False\n interval = 2\n else:\n _interval_set = True\n if _NOTEBOOK_ENV:\n if monitor_async:\n try:\n import ipywidgets as widgets # pylint: disable=import-error\n except ImportError:\n raise ImportError('These functions need ipywidgets. '\n 'Run \"pip install ipywidgets\" before.')\n from qiskit.tools.jupyter.jupyter_magics import _html_checker # pylint: disable=C0412\n\n style = \"font-size:16px;\"\n header = \"Job Status: %s
\".format(\n style=style)\n status = widgets.HTML(value=header % job.status().value)\n display(status)\n\n thread = threading.Thread(target=_html_checker, args=(job, interval,\n status, header))\n thread.start()\n else:\n _text_checker(job, interval, _interval_set,\n quiet=quiet, output=output)\n\n else:\n if monitor_async:\n raise QiskitError(\n 'monitor_async only available in Jupyter notebooks.')\n _text_checker(job, interval, _interval_set, quiet=quiet, output=output)"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\ncompute the Euler angles for a single - qubit gate.", "response": "def euler_angles_1q(unitary_matrix):\n \"\"\"Compute Euler angles for a single-qubit gate.\n\n Find angles (theta, phi, lambda) such that\n unitary_matrix = phase * Rz(phi) * Ry(theta) * Rz(lambda)\n\n Args:\n unitary_matrix (ndarray): 2x2 unitary matrix\n\n Returns:\n tuple: (theta, phi, lambda) Euler angles of SU(2)\n\n Raises:\n QiskitError: if unitary_matrix not 2x2, or failure\n \"\"\"\n if unitary_matrix.shape != (2, 2):\n raise QiskitError(\"euler_angles_1q: expected 2x2 matrix\")\n phase = la.det(unitary_matrix)**(-1.0/2.0)\n U = phase * unitary_matrix # U in SU(2)\n # OpenQASM SU(2) parameterization:\n # U[0, 0] = exp(-i(phi+lambda)/2) * cos(theta/2)\n # U[0, 1] = -exp(-i(phi-lambda)/2) * sin(theta/2)\n # U[1, 0] = exp(i(phi-lambda)/2) * sin(theta/2)\n # U[1, 1] = exp(i(phi+lambda)/2) * cos(theta/2)\n # Find theta\n if abs(U[0, 0]) > _CUTOFF_PRECISION:\n theta = 2 * math.acos(abs(U[0, 0]))\n else:\n theta = 2 * math.asin(abs(U[1, 0]))\n # Find phi and lambda\n phase11 = 0.0\n phase10 = 0.0\n if abs(math.cos(theta/2.0)) > _CUTOFF_PRECISION:\n phase11 = U[1, 1] / math.cos(theta/2.0)\n if abs(math.sin(theta/2.0)) > _CUTOFF_PRECISION:\n phase10 = U[1, 0] / math.sin(theta/2.0)\n phiplambda = 2 * math.atan2(np.imag(phase11), np.real(phase11))\n phimlambda = 2 * math.atan2(np.imag(phase10), np.real(phase10))\n phi = 0.0\n if abs(U[0, 0]) > _CUTOFF_PRECISION and abs(U[1, 0]) > _CUTOFF_PRECISION:\n phi = (phiplambda + phimlambda) / 2.0\n lamb = (phiplambda - phimlambda) / 2.0\n else:\n if abs(U[0, 0]) < _CUTOFF_PRECISION:\n lamb = -phimlambda\n else:\n lamb = phiplambda\n # Check the solution\n Rzphi = np.array([[np.exp(-1j*phi/2.0), 0],\n [0, np.exp(1j*phi/2.0)]], dtype=complex)\n Rytheta = np.array([[np.cos(theta/2.0), -np.sin(theta/2.0)],\n [np.sin(theta/2.0), np.cos(theta/2.0)]], dtype=complex)\n Rzlambda = np.array([[np.exp(-1j*lamb/2.0), 0],\n [0, np.exp(1j*lamb/2.0)]], dtype=complex)\n V = np.dot(Rzphi, np.dot(Rytheta, Rzlambda))\n if la.norm(V - U) > _CUTOFF_PRECISION:\n raise QiskitError(\"euler_angles_1q: incorrect result\")\n return theta, phi, lamb"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nsimplify a general U gate.", "response": "def simplify_U(theta, phi, lam):\n \"\"\"Return the gate u1, u2, or u3 implementing U with the fewest pulses.\n\n The returned gate implements U exactly, not up to a global phase.\n\n Args:\n theta, phi, lam: input Euler rotation angles for a general U gate\n\n Returns:\n Gate: one of IdGate, U1Gate, U2Gate, U3Gate.\n \"\"\"\n gate = U3Gate(theta, phi, lam)\n # Y rotation is 0 mod 2*pi, so the gate is a u1\n if abs(gate.params[0] % (2.0 * math.pi)) < _CUTOFF_PRECISION:\n gate = U1Gate(gate.params[0] + gate.params[1] + gate.params[2])\n # Y rotation is pi/2 or -pi/2 mod 2*pi, so the gate is a u2\n if isinstance(gate, U3Gate):\n # theta = pi/2 + 2*k*pi\n if abs((gate.params[0] - math.pi / 2) % (2.0 * math.pi)) < _CUTOFF_PRECISION:\n gate = U2Gate(gate.params[1],\n gate.params[2] + (gate.params[0] - math.pi / 2))\n # theta = -pi/2 + 2*k*pi\n if abs((gate.params[0] + math.pi / 2) % (2.0 * math.pi)) < _CUTOFF_PRECISION:\n gate = U2Gate(gate.params[1] + math.pi,\n gate.params[2] - math.pi + (gate.params[0] + math.pi / 2))\n # u1 and lambda is 0 mod 4*pi so gate is nop\n if isinstance(gate, U1Gate) and abs(gate.params[0] % (4.0 * math.pi)) < _CUTOFF_PRECISION:\n gate = IdGate()\n return gate"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef two_qubit_kak(unitary):\n if hasattr(unitary, 'to_operator'):\n # If input is a BaseOperator subclass this attempts to convert\n # the object to an Operator so that we can extract the underlying\n # numpy matrix from `Operator.data`.\n unitary = unitary.to_operator().data\n if hasattr(unitary, 'to_matrix'):\n # If input is Gate subclass or some other class object that has\n # a to_matrix method this will call that method.\n unitary = unitary.to_matrix()\n # Convert to numpy array incase not already an array\n unitary_matrix = np.array(unitary, dtype=complex)\n # Check input is a 2-qubit unitary\n if unitary_matrix.shape != (4, 4):\n raise QiskitError(\"two_qubit_kak: Expected 4x4 matrix\")\n if not is_unitary_matrix(unitary_matrix):\n raise QiskitError(\"Input matrix is not unitary.\")\n phase = la.det(unitary_matrix)**(-1.0/4.0)\n # Make it in SU(4), correct phase at the end\n U = phase * unitary_matrix\n # B changes to the Bell basis\n B = (1.0/math.sqrt(2)) * np.array([[1, 1j, 0, 0],\n [0, 0, 1j, 1],\n [0, 0, 1j, -1],\n [1, -1j, 0, 0]], dtype=complex)\n\n # We also need B.conj().T below\n Bdag = B.conj().T\n # U' = Bdag . U . B\n Uprime = Bdag.dot(U.dot(B))\n # M^2 = trans(U') . U'\n M2 = Uprime.T.dot(Uprime)\n\n # Diagonalize M2\n # Must use diagonalization routine which finds a real orthogonal matrix P\n # when M2 is real.\n D, P = la.eig(M2)\n D = np.diag(D)\n # If det(P) == -1 then in O(4), apply a swap to make P in SO(4)\n if abs(la.det(P)+1) < 1e-5:\n swap = np.array([[1, 0, 0, 0],\n [0, 0, 1, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 1]], dtype=complex)\n P = P.dot(swap)\n D = swap.dot(D.dot(swap))\n\n Q = np.sqrt(D) # array from elementwise sqrt\n # Want to take square root so that Q has determinant 1\n if abs(la.det(Q)+1) < 1e-5:\n Q[0, 0] = -Q[0, 0]\n\n # Q^-1*P.T = P' -> QP' = P.T (solve for P' using Ax=b)\n Pprime = la.solve(Q, P.T)\n # K' now just U' * P * P'\n Kprime = Uprime.dot(P.dot(Pprime))\n\n K1 = B.dot(Kprime.dot(P.dot(Bdag)))\n A = B.dot(Q.dot(Bdag))\n K2 = B.dot(P.T.dot(Bdag))\n # KAK = K1 * A * K2\n KAK = K1.dot(A.dot(K2))\n\n # Verify decomp matches input unitary.\n if la.norm(KAK - U) > 1e-6:\n raise QiskitError(\"two_qubit_kak: KAK decomposition \" +\n \"does not return input unitary.\")\n\n # Compute parameters alpha, beta, gamma so that\n # A = exp(i * (alpha * XX + beta * YY + gamma * ZZ))\n xx = np.array([[0, 0, 0, 1],\n [0, 0, 1, 0],\n [0, 1, 0, 0],\n [1, 0, 0, 0]], dtype=complex)\n\n yy = np.array([[0, 0, 0, -1],\n [0, 0, 1, 0],\n [0, 1, 0, 0],\n [-1, 0, 0, 0]], dtype=complex)\n\n zz = np.array([[1, 0, 0, 0],\n [0, -1, 0, 0],\n [0, 0, -1, 0],\n [0, 0, 0, 1]], dtype=complex)\n\n A_real_tr = A.real.trace()\n alpha = math.atan2(A.dot(xx).imag.trace(), A_real_tr)\n beta = math.atan2(A.dot(yy).imag.trace(), A_real_tr)\n gamma = math.atan2(A.dot(zz).imag.trace(), A_real_tr)\n\n # K1 = kron(U1, U2) and K2 = kron(V1, V2)\n # Find the matrices U1, U2, V1, V2\n\n # Find a block in K1 where U1_ij * [U2] is not zero\n L = K1[0:2, 0:2]\n if la.norm(L) < 1e-9:\n L = K1[0:2, 2:4]\n if la.norm(L) < 1e-9:\n L = K1[2:4, 2:4]\n # Remove the U1_ij prefactor\n Q = L.dot(L.conj().T)\n U2 = L / math.sqrt(Q[0, 0].real)\n\n # Now grab U1 given we know U2\n R = K1.dot(np.kron(np.identity(2), U2.conj().T))\n U1 = np.zeros((2, 2), dtype=complex)\n U1[0, 0] = R[0, 0]\n U1[0, 1] = R[0, 2]\n U1[1, 0] = R[2, 0]\n U1[1, 1] = R[2, 2]\n\n # Repeat K1 routine for K2\n L = K2[0:2, 0:2]\n if la.norm(L) < 1e-9:\n L = K2[0:2, 2:4]\n if la.norm(L) < 1e-9:\n L = K2[2:4, 2:4]\n Q = np.dot(L, np.transpose(L.conjugate()))\n V2 = L / np.sqrt(Q[0, 0])\n R = np.dot(K2, np.kron(np.identity(2), np.transpose(V2.conjugate())))\n\n V1 = np.zeros_like(U1)\n V1[0, 0] = R[0, 0]\n V1[0, 1] = R[0, 2]\n V1[1, 0] = R[2, 0]\n V1[1, 1] = R[2, 2]\n\n if la.norm(np.kron(U1, U2) - K1) > 1e-4:\n raise QiskitError(\"two_qubit_kak: K1 != U1 x U2\")\n if la.norm(np.kron(V1, V2) - K2) > 1e-4:\n raise QiskitError(\"two_qubit_kak: K2 != V1 x V2\")\n\n test = la.expm(1j*(alpha * xx + beta * yy + gamma * zz))\n if la.norm(A - test) > 1e-4:\n raise QiskitError(\"two_qubit_kak: \" +\n \"Matrix A does not match xx,yy,zz decomposition.\")\n\n # Circuit that implements K1 * A * K2 (up to phase), using\n # Vatan and Williams Fig. 6 of quant-ph/0308006v3\n # Include prefix and suffix single-qubit gates into U2, V1 respectively.\n\n V2 = np.array([[np.exp(1j*np.pi/4), 0],\n [0, np.exp(-1j*np.pi/4)]], dtype=complex).dot(V2)\n U1 = U1.dot(np.array([[np.exp(-1j*np.pi/4), 0],\n [0, np.exp(1j*np.pi/4)]], dtype=complex))\n\n # Corrects global phase: exp(ipi/4)*phase'\n U1 = U1.dot(np.array([[np.exp(1j*np.pi/4), 0],\n [0, np.exp(1j*np.pi/4)]], dtype=complex))\n U1 = phase.conjugate() * U1\n\n # Test\n g1 = np.kron(V1, V2)\n g2 = np.array([[1, 0, 0, 0],\n [0, 0, 0, 1],\n [0, 0, 1, 0],\n [0, 1, 0, 0]], dtype=complex)\n\n theta = 2*gamma - np.pi/2\n\n Ztheta = np.array([[np.exp(1j*theta/2), 0],\n [0, np.exp(-1j*theta/2)]], dtype=complex)\n\n kappa = np.pi/2 - 2*alpha\n Ykappa = np.array([[math.cos(kappa/2), math.sin(kappa/2)],\n [-math.sin(kappa/2), math.cos(kappa/2)]], dtype=complex)\n g3 = np.kron(Ztheta, Ykappa)\n g4 = np.array([[1, 0, 0, 0],\n [0, 1, 0, 0],\n [0, 0, 0, 1],\n [0, 0, 1, 0]], dtype=complex)\n\n zeta = 2*beta - np.pi/2\n Yzeta = np.array([[math.cos(zeta/2), math.sin(zeta/2)],\n [-math.sin(zeta/2), math.cos(zeta/2)]], dtype=complex)\n g5 = np.kron(np.identity(2), Yzeta)\n g6 = g2\n g7 = np.kron(U1, U2)\n\n V = g2.dot(g1)\n V = g3.dot(V)\n V = g4.dot(V)\n V = g5.dot(V)\n V = g6.dot(V)\n V = g7.dot(V)\n\n if la.norm(V - U*phase.conjugate()) > 1e-6:\n raise QiskitError(\"two_qubit_kak: \" +\n \"sequence incorrect, unknown error\")\n\n v1_param = euler_angles_1q(V1)\n v2_param = euler_angles_1q(V2)\n u1_param = euler_angles_1q(U1)\n u2_param = euler_angles_1q(U2)\n\n v1_gate = U3Gate(v1_param[0], v1_param[1], v1_param[2])\n v2_gate = U3Gate(v2_param[0], v2_param[1], v2_param[2])\n u1_gate = U3Gate(u1_param[0], u1_param[1], u1_param[2])\n u2_gate = U3Gate(u2_param[0], u2_param[1], u2_param[2])\n\n q = QuantumRegister(2)\n return_circuit = QuantumCircuit(q)\n\n return_circuit.append(v1_gate, [q[1]])\n\n return_circuit.append(v2_gate, [q[0]])\n\n return_circuit.append(CnotGate(), [q[0], q[1]])\n\n gate = U3Gate(0.0, 0.0, -2.0*gamma + np.pi/2.0)\n return_circuit.append(gate, [q[1]])\n\n gate = U3Gate(-np.pi/2.0 + 2.0*alpha, 0.0, 0.0)\n return_circuit.append(gate, [q[0]])\n\n return_circuit.append(CnotGate(), [q[1], q[0]])\n\n gate = U3Gate(-2.0*beta + np.pi/2.0, 0.0, 0.0)\n return_circuit.append(gate, [q[0]])\n\n return_circuit.append(CnotGate(), [q[0], q[1]])\n\n return_circuit.append(u1_gate, [q[1]])\n\n return_circuit.append(u2_gate, [q[0]])\n\n return return_circuit", "response": "Decomposes a two - qubit gate over SU ( 2 + CNOT using the KAK decomposition."}
+{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nextend a DAG with virtual qubits that are not in the circuit yet.", "response": "def run(self, dag):\n \"\"\"\n Extends dag with virtual qubits that are in layout but not in the circuit yet.\n\n Args:\n dag (DAGCircuit): DAG to extend.\n\n Returns:\n DAGCircuit: An extended DAG.\n\n Raises:\n TranspilerError: If there is not layout in the property set or not set at init time.\n \"\"\"\n self.layout = self.layout or self.property_set['layout']\n\n if self.layout is None:\n raise TranspilerError(\"EnlargeWithAncilla requires property_set[\\\"layout\\\"] or\"\n \" \\\"layout\\\" parameter to run\")\n\n layout_virtual_qubits = self.layout.get_virtual_bits().keys()\n new_qregs = set(virtual_qubit[0] for virtual_qubit in layout_virtual_qubits\n if virtual_qubit not in dag.wires)\n\n for qreg in new_qregs:\n dag.add_qreg(qreg)\n\n return dag"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\ndefining the class entry.", "response": "def _define(self):\n \"\"\"\n gate ch a,b {\n h b;\n sdg b;\n cx a,b;\n h b;\n t b;\n cx a,b;\n t b;\n h b;\n s b;\n x b;\n s a;}\n \"\"\"\n definition = []\n q = QuantumRegister(2, \"q\")\n rule = [\n (HGate(), [q[1]], []),\n (SdgGate(), [q[1]], []),\n (CnotGate(), [q[0], q[1]], []),\n (HGate(), [q[1]], []),\n (TGate(), [q[1]], []),\n (CnotGate(), [q[0], q[1]], []),\n (TGate(), [q[1]], []),\n (HGate(), [q[1]], []),\n (SGate(), [q[1]], []),\n (XGate(), [q[1]], []),\n (SGate(), [q[0]], [])\n ]\n for inst in rule:\n definition.append(inst)\n self.definition = definition"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef config_tab(backend):\n status = backend.status().to_dict()\n config = backend.configuration().to_dict()\n\n config_dict = {**status, **config}\n\n upper_list = ['n_qubits', 'operational',\n 'status_msg', 'pending_jobs',\n 'basis_gates', 'local', 'simulator']\n\n lower_list = list(set(config_dict.keys()).difference(upper_list))\n # Remove gates because they are in a different tab\n lower_list.remove('gates')\n upper_str = \"\"\n upper_str += \"\"\"\"\"\"\n\n footer = \"
\"\n\n # Upper HBox widget data\n\n upper_str += \"| Property | Value |
\"\n for key in upper_list:\n upper_str += \"| %s | %s |
\" % (\n key, config_dict[key])\n upper_str += footer\n\n upper_table = widgets.HTML(\n value=upper_str, layout=widgets.Layout(width='100%', grid_area='left'))\n\n image_widget = widgets.Output(\n layout=widgets.Layout(display='flex-inline', grid_area='right',\n padding='10px 10px 10px 10px',\n width='auto', max_height='300px',\n align_items='center'))\n\n if not config['simulator']:\n with image_widget:\n gate_map = plot_gate_map(backend)\n display(gate_map)\n plt.close(gate_map)\n\n lower_str = \"\"\n lower_str += \"\"\"\"\"\"\n lower_str += \" | |
\"\n for key in lower_list:\n if key != 'name':\n lower_str += \"| %s | %s |
\" % (\n key, config_dict[key])\n lower_str += footer\n\n lower_table = widgets.HTML(value=lower_str,\n layout=widgets.Layout(\n width='auto',\n grid_area='bottom'))\n\n grid = widgets.GridBox(children=[upper_table, image_widget, lower_table],\n layout=widgets.Layout(\n grid_template_rows='auto auto',\n grid_template_columns='25% 25% 25% 25%',\n grid_template_areas='''\n \"left right right right\"\n \"bottom bottom bottom bottom\"\n ''',\n grid_gap='0px 0px'))\n\n return grid", "response": "A function that creates a new configuration tab."}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ndisplay a detailed noise map for a particular backend.", "response": "def detailed_map(backend):\n \"\"\"Widget for displaying detailed noise map.\n\n Args:\n backend (IBMQbackend): The backend.\n\n Returns:\n GridBox: Widget holding noise map images.\n \"\"\"\n props = backend.properties().to_dict()\n config = backend.configuration().to_dict()\n single_gate_errors = [q['parameters'][0]['value']\n for q in props['gates'][2:3*config['n_qubits']:3]]\n single_norm = matplotlib.colors.Normalize(\n vmin=min(single_gate_errors), vmax=max(single_gate_errors))\n q_colors = [cm.viridis(single_norm(err)) for err in single_gate_errors]\n\n cmap = config['coupling_map']\n\n cx_errors = []\n for line in cmap:\n for item in props['gates'][3*config['n_qubits']:]:\n if item['qubits'] == line:\n cx_errors.append(item['parameters'][0]['value'])\n break\n else:\n continue\n\n cx_norm = matplotlib.colors.Normalize(\n vmin=min(cx_errors), vmax=max(cx_errors))\n line_colors = [cm.viridis(cx_norm(err)) for err in cx_errors]\n\n single_widget = widgets.Output(layout=widgets.Layout(display='flex-inline', grid_area='left',\n align_items='center'))\n\n cmap_widget = widgets.Output(layout=widgets.Layout(display='flex-inline', grid_area='top',\n width='auto', height='auto',\n align_items='center'))\n\n cx_widget = widgets.Output(layout=widgets.Layout(display='flex-inline', grid_area='right',\n align_items='center'))\n\n tick_locator = mpl.ticker.MaxNLocator(nbins=5)\n with cmap_widget:\n noise_map = plot_gate_map(backend, qubit_color=q_colors,\n line_color=line_colors,\n qubit_size=28,\n plot_directed=True)\n width, height = noise_map.get_size_inches()\n\n noise_map.set_size_inches(1.25*width, 1.25*height)\n\n display(noise_map)\n plt.close(noise_map)\n\n with single_widget:\n cbl_fig = plt.figure(figsize=(3, 1))\n ax1 = cbl_fig.add_axes([0.05, 0.80, 0.9, 0.15])\n single_cb = mpl.colorbar.ColorbarBase(ax1, cmap=cm.viridis,\n norm=single_norm,\n orientation='horizontal')\n single_cb.locator = tick_locator\n single_cb.update_ticks()\n ax1.set_title('Single-qubit U3 error rate')\n display(cbl_fig)\n plt.close(cbl_fig)\n\n with cx_widget:\n cx_fig = plt.figure(figsize=(3, 1))\n ax2 = cx_fig.add_axes([0.05, 0.80, 0.9, 0.15])\n cx_cb = mpl.colorbar.ColorbarBase(ax2, cmap=cm.viridis,\n norm=cx_norm,\n orientation='horizontal')\n cx_cb.locator = tick_locator\n cx_cb.update_ticks()\n ax2.set_title('CNOT error rate')\n display(cx_fig)\n plt.close(cx_fig)\n\n out_box = widgets.GridBox([single_widget, cmap_widget, cx_widget],\n layout=widgets.Layout(\n grid_template_rows='auto auto',\n grid_template_columns='33% 33% 33%',\n grid_template_areas='''\n \"top top top\"\n \"left . right\"\n ''',\n grid_gap='0px 0px'))\n return out_box"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef job_history(backend):\n year = widgets.Output(layout=widgets.Layout(display='flex-inline',\n align_items='center',\n min_height='400px'))\n\n month = widgets.Output(layout=widgets.Layout(display='flex-inline',\n align_items='center',\n min_height='400px'))\n\n week = widgets.Output(layout=widgets.Layout(display='flex-inline',\n align_items='center',\n min_height='400px'))\n\n tabs = widgets.Tab(layout=widgets.Layout(max_height='620px'))\n tabs.children = [year, month, week]\n tabs.set_title(0, 'Year')\n tabs.set_title(1, 'Month')\n tabs.set_title(2, 'Week')\n tabs.selected_index = 1\n\n _build_job_history(tabs, backend)\n return tabs", "response": "A tab widget for displaying job history images."}
+{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nplot the job history of the user from the given list of jobs.", "response": "def plot_job_history(jobs, interval='year'):\n \"\"\"Plots the job history of the user from the given list of jobs.\n\n Args:\n jobs (list): A list of jobs with type IBMQjob.\n interval (str): Interval over which to examine.\n\n Returns:\n fig: A Matplotlib figure instance.\n \"\"\"\n def get_date(job):\n \"\"\"Returns a datetime object from a IBMQJob instance.\n\n Args:\n job (IBMQJob): A job.\n\n Returns:\n dt: A datetime object.\n \"\"\"\n return datetime.datetime.strptime(job.creation_date(),\n '%Y-%m-%dT%H:%M:%S.%fZ')\n\n current_time = datetime.datetime.now()\n\n if interval == 'year':\n bins = [(current_time - datetime.timedelta(days=k*365/12))\n for k in range(12)]\n elif interval == 'month':\n bins = [(current_time - datetime.timedelta(days=k)) for k in range(30)]\n elif interval == 'week':\n bins = [(current_time - datetime.timedelta(days=k)) for k in range(7)]\n\n binned_jobs = [0]*len(bins)\n\n if interval == 'year':\n for job in jobs:\n for ind, dat in enumerate(bins):\n date = get_date(job)\n if date.month == dat.month:\n binned_jobs[ind] += 1\n break\n else:\n continue\n else:\n for job in jobs:\n for ind, dat in enumerate(bins):\n date = get_date(job)\n if date.day == dat.day and date.month == dat.month:\n binned_jobs[ind] += 1\n break\n else:\n continue\n\n nz_bins = []\n nz_idx = []\n for ind, val in enumerate(binned_jobs):\n if val != 0:\n nz_idx.append(ind)\n nz_bins.append(val)\n\n total_jobs = sum(binned_jobs)\n\n colors = ['#003f5c', '#ffa600', '#374c80', '#ff764a',\n '#7a5195', '#ef5675', '#bc5090']\n\n if interval == 'year':\n labels = ['{}-{}'.format(str(bins[b].year)[2:], bins[b].month) for b in nz_idx]\n else:\n labels = ['{}-{}'.format(bins[b].month, bins[b].day) for b in nz_idx]\n fig, ax = plt.subplots(1, 1, figsize=(5, 5)) # pylint: disable=invalid-name\n ax.pie(nz_bins[::-1], labels=labels, colors=colors, textprops={'fontsize': 14},\n rotatelabels=True, counterclock=False)\n ax.add_artist(Circle((0, 0), 0.7, color='white', zorder=1))\n ax.text(0, 0, total_jobs, horizontalalignment='center',\n verticalalignment='center', fontsize=26)\n fig.tight_layout()\n return fig"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef run(self, dag):\n resets = dag.op_nodes(Reset)\n for reset in resets:\n predecessor = next(dag.predecessors(reset))\n if predecessor.type == 'in':\n dag.remove_op_node(reset)\n return dag", "response": "Return a new circuit that has been optimized."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nplot the interpolated envelope of pulse.", "response": "def draw(self, **kwargs):\n \"\"\"Plot the interpolated envelope of pulse.\n\n Keyword Args:\n dt (float): Time interval of samples.\n interp_method (str): Method of interpolation\n (set `None` for turn off the interpolation).\n filename (str): Name required to save pulse image.\n interactive (bool): When set true show the circuit in a new window\n (this depends on the matplotlib backend being used supporting this).\n dpi (int): Resolution of saved image.\n nop (int): Data points for interpolation.\n size (tuple): Size of figure.\n \"\"\"\n from qiskit.tools.visualization import pulse_drawer\n\n return pulse_drawer(self._samples, self.duration, **kwargs)"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef cu3(self, theta, phi, lam, ctl, tgt):\n return self.append(Cu3Gate(theta, phi, lam), [ctl, tgt], [])", "response": "Apply cu3 to tgt with angle theta phi lam."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _define(self):\n definition = []\n q = QuantumRegister(2, \"q\")\n rule = [\n (U1Gate((self.params[2] - self.params[1]) / 2), [q[1]], []),\n (CnotGate(), [q[0], q[1]], []),\n (U3Gate(-self.params[0] / 2, 0, -(self.params[1] + self.params[2]) / 2), [q[1]], []),\n (CnotGate(), [q[0], q[1]], []),\n (U3Gate(self.params[0] / 2, self.params[1], 0), [q[1]], [])\n ]\n for inst in rule:\n definition.append(inst)\n self.definition = definition", "response": "Define the related class."}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef build_bell_circuit():\n q = QuantumRegister(2)\n c = ClassicalRegister(2)\n qc = QuantumCircuit(q, c)\n qc.h(q[0])\n qc.cx(q[0], q[1])\n qc.measure(q, c)\n return qc", "response": "Builds a Bell circuit."}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef _transpile_circuit(circuit_config_tuple):\n circuit, transpile_config = circuit_config_tuple\n\n # if the pass manager is not already selected, choose an appropriate one.\n if transpile_config.pass_manager:\n pass_manager = transpile_config.pass_manager\n\n elif transpile_config.coupling_map:\n pass_manager = default_pass_manager(transpile_config.basis_gates,\n transpile_config.coupling_map,\n transpile_config.initial_layout,\n transpile_config.seed_transpiler)\n else:\n pass_manager = default_pass_manager_simulator(transpile_config.basis_gates)\n\n return pass_manager.run(circuit)", "response": "Select a PassManager and run a single circuit through it."}
+{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\nreturns a list of TranspileConfig objects for each argument in the list of circuits.", "response": "def _parse_transpile_args(circuits, backend,\n basis_gates, coupling_map, backend_properties,\n initial_layout, seed_transpiler, optimization_level,\n pass_manager):\n \"\"\"Resolve the various types of args allowed to the transpile() function through\n duck typing, overriding args, etc. Refer to the transpile() docstring for details on\n what types of inputs are allowed.\n\n Here the args are resolved by converting them to standard instances, and prioritizing\n them in case a transpile option is passed through multiple args (explicitly setting an\n arg has more priority than the arg set by backend)\n\n Returns:\n list[TranspileConfig]: a transpile config for each circuit, which is a standardized\n object that configures the transpiler and determines the pass manager to use.\n \"\"\"\n # Each arg could be single or a list. If list, it must be the same size as\n # number of circuits. If single, duplicate to create a list of that size.\n num_circuits = len(circuits)\n\n basis_gates = _parse_basis_gates(basis_gates, backend, circuits)\n\n coupling_map = _parse_coupling_map(coupling_map, backend, num_circuits)\n\n backend_properties = _parse_backend_properties(backend_properties, backend, num_circuits)\n\n initial_layout = _parse_initial_layout(initial_layout, circuits)\n\n seed_transpiler = _parse_seed_transpiler(seed_transpiler, num_circuits)\n\n optimization_level = _parse_optimization_level(optimization_level, num_circuits)\n\n pass_manager = _parse_pass_manager(pass_manager, num_circuits)\n\n transpile_configs = []\n for args in zip(basis_gates, coupling_map, backend_properties, initial_layout,\n seed_transpiler, optimization_level, pass_manager):\n transpile_config = TranspileConfig(basis_gates=args[0],\n coupling_map=args[1],\n backend_properties=args[2],\n initial_layout=args[3],\n seed_transpiler=args[4],\n optimization_level=args[5],\n pass_manager=args[6])\n transpile_configs.append(transpile_config)\n\n return transpile_configs"}
+{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef execute(experiments, backend,\n basis_gates=None, coupling_map=None, # circuit transpile options\n backend_properties=None, initial_layout=None,\n seed_transpiler=None, optimization_level=None, pass_manager=None,\n qobj_id=None, qobj_header=None, shots=1024, # common run options\n memory=False, max_credits=10, seed_simulator=None,\n default_qubit_los=None, default_meas_los=None, # schedule run options\n schedule_los=None, meas_level=2, meas_return='avg',\n memory_slots=None, memory_slot_size=100, rep_time=None, parameter_binds=None,\n seed=None, seed_mapper=None, # deprecated\n config=None, circuits=None,\n **run_config):\n \"\"\"Execute a list of circuits or pulse schedules on a backend.\n\n The execution is asynchronous, and a handle to a job instance is returned.\n\n Args:\n experiments (QuantumCircuit or list[QuantumCircuit] or Schedule or list[Schedule]):\n Circuit(s) or pulse schedule(s) to execute\n\n backend (BaseBackend):\n Backend to execute circuits on.\n Transpiler options are automatically grabbed from\n backend.configuration() and backend.properties().\n If any other option is explicitly set (e.g. coupling_map), it\n will override the backend's.\n\n basis_gates (list[str]):\n List of basis gate names to unroll to.\n e.g:\n ['u1', 'u2', 'u3', 'cx']\n If None, do not unroll.\n\n coupling_map (CouplingMap or list):\n Coupling map (perhaps custom) to target in mapping.\n Multiple formats are supported:\n a. CouplingMap instance\n\n b. list\n Must be given as an adjacency matrix, where each entry\n specifies all two-qubit interactions supported by backend\n e.g:\n [[0, 1], [0, 3], [1, 2], [1, 5], [2, 5], [4, 1], [5, 3]]\n\n backend_properties (BackendProperties):\n Properties returned by a backend, including information on gate\n errors, readout errors, qubit coherence times, etc. For a backend\n that provides this information, it can be obtained with:\n ``backend.properties()``\n\n initial_layout (Layout or dict or list):\n Initial position of virtual qubits on physical qubits.\n If this layout makes the circuit compatible with the coupling_map\n constraints, it will be used.\n The final layout is not guaranteed to be the same, as the transpiler\n may permute qubits through swaps or other means.\n\n Multiple formats are supported:\n a. Layout instance\n\n b. dict\n virtual to physical:\n {qr[0]: 0,\n qr[1]: 3,\n qr[2]: 5}\n\n physical to virtual:\n {0: qr[0],\n 3: qr[1],\n 5: qr[2]}\n\n c. list\n virtual to physical:\n [0, 3, 5] # virtual qubits are ordered (in addition to named)\n\n physical to virtual:\n [qr[0], None, None, qr[1], None, qr[2]]\n\n seed_transpiler (int):\n Sets random seed for the stochastic parts of the transpiler\n\n optimization_level (int):\n How much optimization to perform on the circuits.\n Higher levels generate more optimized circuits,\n at the expense of longer transpilation time.\n 0: no optimization\n 1: light optimization\n 2: heavy optimization\n\n pass_manager (PassManager):\n The pass manager to use during transpilation. If this arg is present,\n auto-selection of pass manager based on the transpile options will be\n turned off and this pass manager will be used directly.\n\n qobj_id (str):\n String identifier to annotate the Qobj\n\n qobj_header (QobjHeader or dict):\n User input that will be inserted in Qobj header, and will also be\n copied to the corresponding Result header. Headers do not affect the run.\n\n shots (int):\n Number of repetitions of each circuit, for sampling. Default: 2014\n\n memory (bool):\n If True, per-shot measurement bitstrings are returned as well\n (provided the backend supports it). For OpenPulse jobs, only\n measurement level 2 supports this option. Default: False\n\n max_credits (int):\n Maximum credits to spend on job. Default: 10\n\n seed_simulator (int):\n Random seed to control sampling, for when backend is a simulator\n\n default_qubit_los (list):\n List of default qubit lo frequencies\n\n default_meas_los (list):\n List of default meas lo frequencies\n\n schedule_los (None or list[Union[Dict[PulseChannel, float], LoConfig]] or\n Union[Dict[PulseChannel, float], LoConfig]):\n Experiment LO configurations\n\n meas_level (int):\n Set the appropriate level of the measurement output for pulse experiments.\n\n meas_return (str):\n Level of measurement data for the backend to return\n For `meas_level` 0 and 1:\n \"single\" returns information from every shot.\n \"avg\" returns average measurement output (averaged over number of shots).\n\n memory_slots (int):\n Number of classical memory slots used in this job.\n\n memory_slot_size (int):\n Size of each memory slot if the output is Level 0.\n\n rep_time (int): repetition time of the experiment in \u03bcs.\n The delay between experiments will be rep_time.\n Must be from the list provided by the device.\n\n parameter_binds (list[dict{Parameter: Value}]):\n List of Parameter bindings over which the set of experiments will be\n executed. Each list element (bind) should be of the form\n {Parameter1: value1, Parameter2: value2, ...}. All binds will be\n executed across all experiments, e.g. if parameter_binds is a\n length-n list, and there are m experiments, a total of m x n\n experiments will be run (one for each experiment/bind pair).\n\n seed (int):\n DEPRECATED in 0.8: use ``seed_simulator`` kwarg instead\n\n seed_mapper (int):\n DEPRECATED in 0.8: use ``seed_transpiler`` kwarg instead\n\n config (dict):\n DEPRECATED in 0.8: use run_config instead\n\n circuits (QuantumCircuit or list[QuantumCircuit]):\n DEPRECATED in 0.8: use ``experiments`` kwarg instead.\n\n run_config (dict):\n Extra arguments used to configure the run (e.g. for Aer configurable backends)\n Refer to the backend documentation for details on these arguments\n Note: for now, these keyword arguments will both be copied to the\n Qobj config, and passed to backend.run()\n\n Returns:\n BaseJob: returns job instance derived from BaseJob\n\n Raises:\n QiskitError: if the execution cannot be interpreted as either circuits or schedules\n \"\"\"\n if circuits is not None:\n experiments = circuits\n warnings.warn(\"the `circuits` arg in `execute()` has been deprecated. \"\n \"please use `experiments`, which can handle both circuit \"\n \"and pulse Schedules\", DeprecationWarning)\n\n # transpiling the circuits using given transpile options\n experiments = transpile(experiments,\n basis_gates=basis_gates,\n coupling_map=coupling_map,\n backend_properties=backend_properties,\n initial_layout=initial_layout,\n seed_transpiler=seed_transpiler,\n optimization_level=optimization_level,\n backend=backend,\n pass_manager=pass_manager,\n seed_mapper=seed_mapper, # deprecated\n )\n\n # assembling the circuits into a qobj to be run on the backend\n qobj = assemble(experiments,\n qobj_id=qobj_id,\n qobj_header=qobj_header,\n shots=shots,\n memory=memory,\n max_credits=max_credits,\n seed_simulator=seed_simulator,\n default_qubit_los=default_qubit_los,\n default_meas_los=default_meas_los,\n schedule_los=schedule_los,\n meas_level=meas_level,\n meas_return=meas_return,\n memory_slots=memory_slots,\n memory_slot_size=memory_slot_size,\n rep_time=rep_time,\n parameter_binds=parameter_binds,\n backend=backend,\n config=config, # deprecated\n seed=seed, # deprecated\n run_config=run_config\n )\n\n # executing the circuits on the backend and returning the job\n return backend.run(qobj, **run_config)", "response": "Execute a list of circuits or pulse schedules on a backend."}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nreturns the primary drive channel of this qubit.", "response": "def drive(self) -> DriveChannel:\n \"\"\"Return the primary drive channel of this qubit.\"\"\"\n if self._drives:\n return self._drives[0]\n else:\n raise PulseError(\"No drive channels in q[%d]\" % self._index)"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nreturn the primary control channel of this qubit.", "response": "def control(self) -> ControlChannel:\n \"\"\"Return the primary control channel of this qubit.\"\"\"\n if self._controls:\n return self._controls[0]\n else:\n raise PulseError(\"No control channels in q[%d]\" % self._index)"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn the primary measure channel of this qubit.", "response": "def measure(self) -> MeasureChannel:\n \"\"\"Return the primary measure channel of this qubit.\"\"\"\n if self._measures:\n return self._measures[0]\n else:\n raise PulseError(\"No measurement channels in q[%d]\" % self._index)"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nreturning the primary acquire channel of this qubit.", "response": "def acquire(self) -> AcquireChannel:\n \"\"\"Return the primary acquire channel of this qubit.\"\"\"\n if self._acquires:\n return self._acquires[0]\n else:\n raise PulseError(\"No acquire channels in q[%d]\" % self._index)"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef assemble_circuits(circuits, qobj_id=None, qobj_header=None, run_config=None):\n qobj_config = QasmQobjConfig()\n if run_config:\n qobj_config = QasmQobjConfig(**run_config.to_dict())\n\n # Pack everything into the Qobj\n experiments = []\n max_n_qubits = 0\n max_memory_slots = 0\n for circuit in circuits:\n # header stuff\n n_qubits = 0\n memory_slots = 0\n qubit_labels = []\n clbit_labels = []\n\n qreg_sizes = []\n creg_sizes = []\n for qreg in circuit.qregs:\n qreg_sizes.append([qreg.name, qreg.size])\n for j in range(qreg.size):\n qubit_labels.append([qreg.name, j])\n n_qubits += qreg.size\n for creg in circuit.cregs:\n creg_sizes.append([creg.name, creg.size])\n for j in range(creg.size):\n clbit_labels.append([creg.name, j])\n memory_slots += creg.size\n\n # TODO: why do we need creq_sizes and qreg_sizes in header\n # TODO: we need to rethink memory_slots as they are tied to classical bit\n experimentheader = QobjExperimentHeader(qubit_labels=qubit_labels,\n n_qubits=n_qubits,\n qreg_sizes=qreg_sizes,\n clbit_labels=clbit_labels,\n memory_slots=memory_slots,\n creg_sizes=creg_sizes,\n name=circuit.name)\n # TODO: why do we need n_qubits and memory_slots in both the header and the config\n experimentconfig = QasmQobjExperimentConfig(n_qubits=n_qubits, memory_slots=memory_slots)\n\n # Convert conditionals from QASM-style (creg ?= int) to qobj-style\n # (register_bit ?= 1), by assuming device has unlimited register slots\n # (supported only for simulators). Map all measures to a register matching\n # their clbit_index, create a new register slot for every conditional gate\n # and add a bfunc to map the creg=val mask onto the gating register bit.\n\n is_conditional_experiment = any(op.control for (op, qargs, cargs) in circuit.data)\n max_conditional_idx = 0\n\n instructions = []\n for op_context in circuit.data:\n instruction = op_context[0].assemble()\n\n # Add register attributes to the instruction\n qargs = op_context[1]\n cargs = op_context[2]\n if qargs:\n qubit_indices = [qubit_labels.index([qubit[0].name, qubit[1]])\n for qubit in qargs]\n instruction.qubits = qubit_indices\n if cargs:\n clbit_indices = [clbit_labels.index([clbit[0].name, clbit[1]])\n for clbit in cargs]\n instruction.memory = clbit_indices\n # If the experiment has conditional instructions, assume every\n # measurement result may be needed for a conditional gate.\n if instruction.name == \"measure\" and is_conditional_experiment:\n instruction.register = clbit_indices\n\n # To convert to a qobj-style conditional, insert a bfunc prior\n # to the conditional instruction to map the creg ?= val condition\n # onto a gating register bit.\n if hasattr(instruction, '_control'):\n ctrl_reg, ctrl_val = instruction._control\n mask = 0\n val = 0\n for clbit in clbit_labels:\n if clbit[0] == ctrl_reg.name:\n mask |= (1 << clbit_labels.index(clbit))\n val |= (((ctrl_val >> clbit[1]) & 1) << clbit_labels.index(clbit))\n\n conditional_reg_idx = memory_slots + max_conditional_idx\n conversion_bfunc = QasmQobjInstruction(name='bfunc',\n mask=\"0x%X\" % mask,\n relation='==',\n val=\"0x%X\" % val,\n register=conditional_reg_idx)\n instructions.append(conversion_bfunc)\n instruction.conditional = conditional_reg_idx\n max_conditional_idx += 1\n # Delete control attribute now that we have replaced it with\n # the conditional and bfuc\n del instruction._control\n\n instructions.append(instruction)\n\n experiments.append(QasmQobjExperiment(instructions=instructions, header=experimentheader,\n config=experimentconfig))\n if n_qubits > max_n_qubits:\n max_n_qubits = n_qubits\n if memory_slots > max_memory_slots:\n max_memory_slots = memory_slots\n\n qobj_config.memory_slots = max_memory_slots\n qobj_config.n_qubits = max_n_qubits\n\n return QasmQobj(qobj_id=qobj_id,\n config=qobj_config,\n experiments=experiments,\n header=qobj_header)", "response": "Assembles a list of circuits into a single Qobj which can be run on the backend."}
+{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nassembles a list of schedules into a single Qobj which can be run on the backend.", "response": "def assemble_schedules(schedules, qobj_id=None, qobj_header=None, run_config=None):\n \"\"\"Assembles a list of schedules into a qobj which can be run on the backend.\n Args:\n schedules (list[Schedule]): schedules to assemble\n qobj_id (int): identifier for the generated qobj\n qobj_header (QobjHeader): header to pass to the results\n run_config (RunConfig): configuration of the runtime environment\n Returns:\n PulseQobj: the Qobj to be run on the backends\n Raises:\n QiskitError: when invalid schedules or configs are provided\n \"\"\"\n qobj_config = QasmQobjConfig()\n if run_config:\n qobj_config = QasmQobjConfig(**run_config.to_dict())\n\n # Get appropriate convertors\n instruction_converter = PulseQobjConverter\n instruction_converter = instruction_converter(PulseQobjInstruction, **run_config.to_dict())\n lo_converter = LoConfigConverter(PulseQobjExperimentConfig, run_config.qubit_lo_freq,\n run_config.meas_lo_freq, **run_config.to_dict())\n\n # Pack everything into the Qobj\n qobj_schedules = []\n user_pulselib = set()\n for idx, schedule in enumerate(schedules):\n # instructions\n qobj_instructions = []\n # Instructions are returned as tuple of shifted time and instruction\n for shift, instruction in schedule.instructions:\n # TODO: support conditional gate\n qobj_instructions.append(instruction_converter(shift, instruction))\n if isinstance(instruction, PulseInstruction):\n # add samples to pulse library\n user_pulselib.add(instruction.command)\n # experiment header\n qobj_experiment_header = QobjExperimentHeader(\n name=schedule.name or 'Experiment-%d' % idx\n )\n\n qobj_schedules.append({\n 'header': qobj_experiment_header,\n 'instructions': qobj_instructions\n })\n\n # setup pulse_library\n run_config.pulse_library = [QobjPulseLibrary(name=pulse.name, samples=pulse.samples)\n for pulse in user_pulselib]\n\n # create qob experiment field\n experiments = []\n if len(run_config.schedule_los) == 1:\n lo_dict = run_config.schedule_los.pop()\n # update global config\n q_los = lo_converter.get_qubit_los(lo_dict)\n if q_los:\n run_config.qubit_lo_freq = q_los\n m_los = lo_converter.get_meas_los(lo_dict)\n if m_los:\n run_config.meas_lo_freq = m_los\n\n if run_config.schedule_los:\n # multiple frequency setups\n if len(qobj_schedules) == 1:\n # frequency sweep\n for lo_dict in run_config.schedule_los:\n experiments.append(PulseQobjExperiment(\n instructions=qobj_schedules[0]['instructions'],\n experimentheader=qobj_schedules[0]['header'],\n experimentconfig=lo_converter(lo_dict)\n ))\n elif len(qobj_schedules) == len(run_config.schedule_los):\n # n:n setup\n for lo_dict, schedule in zip(run_config.schedule_los, qobj_schedules):\n experiments.append(PulseQobjExperiment(\n instructions=schedule['instructions'],\n experimentheader=schedule['header'],\n experimentconfig=lo_converter(lo_dict)\n ))\n else:\n raise QiskitError('Invalid LO setting is specified. '\n 'The LO should be configured for each schedule, or '\n 'single setup for all schedules (unique), or '\n 'multiple setups for a single schedule (frequency sweep),'\n 'or no LO configured at all.')\n else:\n # unique frequency setup\n for schedule in qobj_schedules:\n experiments.append(PulseQobjExperiment(\n instructions=schedule['instructions'],\n experimentheader=schedule['header'],\n ))\n\n qobj_config = PulseQobjConfig(**run_config.to_dict())\n\n return PulseQobj(qobj_id=qobj_id,\n config=qobj_config,\n experiments=experiments,\n header=qobj_header)"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef assemble(experiments,\n backend=None,\n qobj_id=None, qobj_header=None, # common run options\n shots=1024, memory=False, max_credits=None, seed_simulator=None,\n default_qubit_los=None, default_meas_los=None, # schedule run options\n schedule_los=None, meas_level=2, meas_return='avg',\n memory_slots=None, memory_slot_size=100, rep_time=None, parameter_binds=None,\n config=None, seed=None, # deprecated\n **run_config):\n \"\"\"Assemble a list of circuits or pulse schedules into a Qobj.\n\n This function serializes the payloads, which could be either circuits or schedules,\n to create Qobj \"experiments\". It further annotates the experiment payload with\n header and configurations.\n\n Args:\n experiments (QuantumCircuit or list[QuantumCircuit] or Schedule or list[Schedule]):\n Circuit(s) or pulse schedule(s) to execute\n\n backend (BaseBackend):\n If set, some runtime options are automatically grabbed from\n backend.configuration() and backend.defaults().\n If any other option is explicitly set (e.g. rep_rate), it\n will override the backend's.\n If any other options is set in the run_config, it will\n also override the backend's.\n\n qobj_id (str):\n String identifier to annotate the Qobj\n\n qobj_header (QobjHeader or dict):\n User input that will be inserted in Qobj header, and will also be\n copied to the corresponding Result header. Headers do not affect the run.\n\n shots (int):\n Number of repetitions of each circuit, for sampling. Default: 2014\n\n memory (bool):\n If True, per-shot measurement bitstrings are returned as well\n (provided the backend supports it). For OpenPulse jobs, only\n measurement level 2 supports this option. Default: False\n\n max_credits (int):\n Maximum credits to spend on job. Default: 10\n\n seed_simulator (int):\n Random seed to control sampling, for when backend is a simulator\n\n default_qubit_los (list):\n List of default qubit lo frequencies\n\n default_meas_los (list):\n List of default meas lo frequencies\n\n schedule_los (None or list[Union[Dict[PulseChannel, float], LoConfig]] or\n Union[Dict[PulseChannel, float], LoConfig]):\n Experiment LO configurations\n\n meas_level (int):\n Set the appropriate level of the measurement output for pulse experiments.\n\n meas_return (str):\n Level of measurement data for the backend to return\n For `meas_level` 0 and 1:\n \"single\" returns information from every shot.\n \"avg\" returns average measurement output (averaged over number of shots).\n\n memory_slots (int):\n Number of classical memory slots used in this job.\n\n memory_slot_size (int):\n Size of each memory slot if the output is Level 0.\n\n rep_time (int): repetition time of the experiment in \u03bcs.\n The delay between experiments will be rep_time.\n Must be from the list provided by the device.\n\n parameter_binds (list[dict{Parameter: Value}]):\n List of Parameter bindings over which the set of experiments will be\n executed. Each list element (bind) should be of the form\n {Parameter1: value1, Parameter2: value2, ...}. All binds will be\n executed across all experiments, e.g. if parameter_binds is a\n length-n list, and there are m experiments, a total of m x n\n experiments will be run (one for each experiment/bind pair).\n\n seed (int):\n DEPRECATED in 0.8: use ``seed_simulator`` kwarg instead\n\n config (dict):\n DEPRECATED in 0.8: use run_config instead\n\n run_config (dict):\n extra arguments used to configure the run (e.g. for Aer configurable backends)\n Refer to the backend documentation for details on these arguments\n\n Returns:\n Qobj: a qobj which can be run on a backend. Depending on the type of input,\n this will be either a QasmQobj or a PulseQobj.\n\n Raises:\n QiskitError: if the input cannot be interpreted as either circuits or schedules\n \"\"\"\n # deprecation matter\n if config:\n warnings.warn('config is not used anymore. Set all configs in '\n 'run_config.', DeprecationWarning)\n run_config = run_config or config\n if seed:\n warnings.warn('seed is deprecated in favor of seed_simulator.', DeprecationWarning)\n seed_simulator = seed_simulator or seed\n\n # Get RunConfig(s) that will be inserted in Qobj to configure the run\n experiments = experiments if isinstance(experiments, list) else [experiments]\n qobj_id, qobj_header, run_config = _parse_run_args(backend, qobj_id, qobj_header,\n shots, memory, max_credits, seed_simulator,\n default_qubit_los, default_meas_los,\n schedule_los, meas_level, meas_return,\n memory_slots, memory_slot_size, rep_time,\n parameter_binds, **run_config)\n\n # assemble either circuits or schedules\n if all(isinstance(exp, QuantumCircuit) for exp in experiments):\n # If circuits are parameterized, bind parameters and remove from run_config\n bound_experiments, run_config = _expand_parameters(circuits=experiments,\n run_config=run_config)\n return assemble_circuits(circuits=bound_experiments, qobj_id=qobj_id,\n qobj_header=qobj_header, run_config=run_config)\n\n elif all(isinstance(exp, Schedule) for exp in experiments):\n return assemble_schedules(schedules=experiments, qobj_id=qobj_id,\n qobj_header=qobj_header, run_config=run_config)\n\n else:\n raise QiskitError(\"bad input to assemble() function; \"\n \"must be either circuits or schedules\")", "response": "Assemble a list of circuits or schedules into a single Qobj."}
+{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nparse the args for the assemble function.", "response": "def _parse_run_args(backend, qobj_id, qobj_header,\n shots, memory, max_credits, seed_simulator,\n default_qubit_los, default_meas_los,\n schedule_los, meas_level, meas_return,\n memory_slots, memory_slot_size, rep_time,\n parameter_binds, **run_config):\n \"\"\"Resolve the various types of args allowed to the assemble() function through\n duck typing, overriding args, etc. Refer to the assemble() docstring for details on\n what types of inputs are allowed.\n\n Here the args are resolved by converting them to standard instances, and prioritizing\n them in case a run option is passed through multiple args (explicitly setting an arg\n has more priority than the arg set by backend)\n\n Returns:\n RunConfig: a run config, which is a standardized object that configures the qobj\n and determines the runtime environment.\n \"\"\"\n # grab relevant info from backend if it exists\n backend_config = None\n backend_default = None\n if backend:\n backend_config = backend.configuration()\n # TODO : Remove usage of config.defaults when backend.defaults() is updated.\n try:\n backend_default = backend.defaults()\n except (ModelValidationError, AttributeError):\n from collections import namedtuple\n backend_config_defaults = getattr(backend_config, 'defaults', {})\n BackendDefault = namedtuple('BackendDefault', ('qubit_freq_est', 'meas_freq_est'))\n backend_default = BackendDefault(\n qubit_freq_est=backend_config_defaults.get('qubit_freq_est'),\n meas_freq_est=backend_config_defaults.get('meas_freq_est')\n )\n\n memory_slots = memory_slots or getattr(backend_config, 'memory_slots', None)\n rep_time = rep_time or getattr(backend_config, 'rep_times', None)\n if isinstance(rep_time, list):\n rep_time = rep_time[-1]\n\n parameter_binds = parameter_binds or []\n\n # add default empty lo config\n schedule_los = schedule_los or []\n if isinstance(schedule_los, (LoConfig, dict)):\n schedule_los = [schedule_los]\n\n # Convert to LoConfig if lo configuration supplied as dictionary\n schedule_los = [lo_config if isinstance(lo_config, LoConfig) else LoConfig(lo_config)\n for lo_config in schedule_los]\n\n qubit_lo_freq = default_qubit_los or getattr(backend_default, 'qubit_freq_est', [])\n meas_lo_freq = default_meas_los or getattr(backend_default, 'meas_freq_est', [])\n\n # an identifier for the Qobj\n qobj_id = qobj_id or str(uuid.uuid4())\n\n # The header that goes at the top of the Qobj (and later Result)\n # we process it as dict, then write entries that are not None to a QobjHeader object\n qobj_header = qobj_header or {}\n if isinstance(qobj_header, QobjHeader):\n qobj_header = qobj_header.to_dict()\n backend_name = getattr(backend_config, 'backend_name', None)\n backend_version = getattr(backend_config, 'backend_version', None)\n qobj_header = {**dict(backend_name=backend_name, backend_version=backend_version),\n **qobj_header}\n qobj_header = QobjHeader(**{k: v for k, v in qobj_header.items() if v is not None})\n\n # create run configuration and populate\n run_config_dict = dict(shots=shots,\n memory=memory,\n max_credits=max_credits,\n seed_simulator=seed_simulator,\n seed=seed_simulator, # deprecated\n qubit_lo_freq=qubit_lo_freq,\n meas_lo_freq=meas_lo_freq,\n schedule_los=schedule_los,\n meas_level=meas_level,\n meas_return=meas_return,\n memory_slots=memory_slots,\n memory_slot_size=memory_slot_size,\n rep_time=rep_time,\n parameter_binds=parameter_binds,\n **run_config)\n run_config = RunConfig(**{k: v for k, v in run_config_dict.items() if v is not None})\n\n return qobj_id, qobj_header, run_config"}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\nexpand all parameters in the input circuits and run_config.", "response": "def _expand_parameters(circuits, run_config):\n \"\"\"Verifies that there is a single common set of parameters shared between\n all circuits and all parameter binds in the run_config. Returns an expanded\n list of circuits (if parameterized) with all parameters bound, and a copy of\n the run_config with parameter_binds cleared.\n\n If neither the circuits nor the run_config specify parameters, the two are\n returned unmodified.\n\n Raises:\n QiskitError: if run_config parameters are not compatible with circuit parameters\n\n Returns:\n Tuple(List[QuantumCircuit], RunConfig):\n - List of input circuits expanded and with parameters bound\n - RunConfig with parameter_binds removed\n \"\"\"\n\n parameter_binds = run_config.parameter_binds\n if parameter_binds or \\\n any(circuit.parameters for circuit in circuits):\n\n all_bind_parameters = [bind.keys()\n for bind in parameter_binds]\n all_circuit_parameters = [circuit.parameters for circuit in circuits]\n\n # Collect set of all unique parameters across all circuits and binds\n unique_parameters = set(param\n for param_list in all_bind_parameters + all_circuit_parameters\n for param in param_list)\n\n # Check that all parameters are common to all circuits and binds\n if not all_bind_parameters \\\n or not all_circuit_parameters \\\n or any(unique_parameters != bind_params for bind_params in all_bind_parameters) \\\n or any(unique_parameters != parameters for parameters in all_circuit_parameters):\n raise QiskitError(\n ('Mismatch between run_config.parameter_binds and all circuit parameters. ' +\n 'Parameter binds: {} ' +\n 'Circuit parameters: {}').format(all_bind_parameters, all_circuit_parameters))\n\n circuits = [circuit.bind_parameters(binds)\n for circuit in circuits\n for binds in parameter_binds]\n\n # All parameters have been expanded and bound, so remove from run_config\n run_config = copy.deepcopy(run_config)\n run_config.parameter_binds = []\n\n return circuits, run_config"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef unset_qiskit_logger():\n qiskit_logger = logging.getLogger('qiskit')\n for handler in qiskit_logger.handlers:\n qiskit_logger.removeHandler(handler)", "response": "Remove the handlers for the qiskit logger."}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef iplot_state_hinton(rho, figsize=None):\n\n # HTML\n html_template = Template(\"\"\"\n \n
\n \n \"\"\")\n\n # JavaScript\n javascript_template = Template(\"\"\"\n \n \"\"\")\n rho = _validate_input_state(rho)\n if figsize is None:\n options = {}\n else:\n options = {'width': figsize[0], 'height': figsize[1]}\n\n # Process data and execute\n div_number = str(time.time())\n div_number = re.sub('[.]', '', div_number)\n\n # Process data and execute\n real = []\n imag = []\n for xvalue in rho:\n row_real = []\n col_imag = []\n\n for value_real in xvalue.real:\n row_real.append(float(value_real))\n real.append(row_real)\n\n for value_imag in xvalue.imag:\n col_imag.append(float(value_imag))\n imag.append(col_imag)\n\n html = html_template.substitute({\n 'divNumber': div_number\n })\n\n javascript = javascript_template.substitute({\n 'divNumber': div_number,\n 'executions': [{'data': real}, {'data': imag}],\n 'options': options\n })\n\n display(HTML(html + javascript))", "response": "Creates a 2D city style hinton representation of the input array."}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef process_fidelity(channel1, channel2, require_cptp=True):\n # First we must determine if input is to be interpreted as a unitary matrix\n # or as a channel.\n # If input is a raw numpy array we will interpret it as a unitary matrix.\n is_cptp1 = None\n is_cptp2 = None\n if isinstance(channel1, (list, np.ndarray)):\n channel1 = Operator(channel1)\n if require_cptp:\n is_cptp1 = channel1.is_unitary()\n if isinstance(channel2, (list, np.ndarray)):\n channel2 = Operator(channel2)\n if require_cptp:\n is_cptp2 = channel2.is_unitary()\n\n # Next we convert inputs SuperOp objects\n # This works for objects that also have a `to_operator` or `to_channel` method\n s1 = SuperOp(channel1)\n s2 = SuperOp(channel2)\n\n # Check inputs are CPTP\n if require_cptp:\n # Only check SuperOp if we didn't already check unitary inputs\n if is_cptp1 is None:\n is_cptp1 = s1.is_cptp()\n if not is_cptp1:\n raise QiskitError('channel1 is not CPTP')\n if is_cptp2 is None:\n is_cptp2 = s2.is_cptp()\n if not is_cptp2:\n raise QiskitError('channel2 is not CPTP')\n\n # Check dimensions match\n input_dim1, output_dim1 = s1.dim\n input_dim2, output_dim2 = s2.dim\n if input_dim1 != output_dim1 or input_dim2 != output_dim2:\n raise QiskitError('Input channels must have same size input and output dimensions.')\n if input_dim1 != input_dim2:\n raise QiskitError('Input channels have different dimensions.')\n\n # Compute process fidelity\n fidelity = np.trace(s1.compose(s2.adjoint()).data) / (input_dim1 ** 2)\n return fidelity", "response": "This function returns the process fidelity between two quantum channels."}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef input(self, data):\n self.data = data\n self.lexer.input(data)", "response": "Set the input text data."}
+{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef pop(self):\n self.lexer = self.stack.pop()\n self.filename = self.lexer.qasm_file\n self.lineno = self.lexer.qasm_line", "response": "Pop a PLY lexer off the stack."}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\npushing a PLY lexer on the stack to parse filename.", "response": "def push(self, filename):\n \"\"\"Push a PLY lexer on the stack to parse filename.\"\"\"\n self.lexer.qasm_file = self.filename\n self.lexer.qasm_line = self.lineno\n self.stack.append(self.lexer)\n self.__mklexer__(filename)"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nparsing include file and return the next token.", "response": "def t_INCLUDE(self, t):\n 'include'\n #\n # Now eat up the next two tokens which must be\n # 1 - the name of the include file, and\n # 2 - a terminating semicolon\n #\n # Then push the current lexer onto the stack, create a new one from\n # the include file, and push it onto the stack.\n #\n # When we hit eof (the t_eof) rule, we pop.\n next_token = self.lexer.token()\n lineno = next_token.lineno\n # print('NEXT', next, \"next.value\", next.value, type(next))\n if isinstance(next_token.value, str):\n incfile = next_token.value.strip('\"')\n else:\n raise QasmError(\"Invalid include: must be a quoted string.\")\n\n if incfile in CORE_LIBS:\n incfile = os.path.join(CORE_LIBS_PATH, incfile)\n\n next_token = self.lexer.token()\n if next_token is None or next_token.value != ';':\n raise QasmError('Invalid syntax, missing \";\" at line', str(lineno))\n\n if not os.path.exists(incfile):\n raise QasmError(\n 'Include file %s cannot be found, line %s, file %s' %\n (incfile, str(next_token.lineno), self.filename))\n self.push(incfile)\n return self.lexer.token()"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef t_ID(self, t):\n r'[a-z][a-zA-Z0-9_]*'\n\n t.type = self.reserved.get(t.value, 'ID')\n if t.type == 'ID':\n t.value = node.Id(t.value, self.lineno, self.filename)\n return t", "response": "r A type can be used to set the ID attribute of a resource."}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef create_from(cls, backend):\n backend_config = backend.configuration()\n\n # TODO : Remove usage of config.defaults when backend.defaults() is updated.\n try:\n backend_default = backend.defaults()\n except ModelValidationError:\n from collections import namedtuple\n BackendDefault = namedtuple('BackendDefault', ('qubit_freq_est', 'meas_freq_est'))\n\n backend_default = BackendDefault(\n qubit_freq_est=backend_config.defaults['qubit_freq_est'],\n meas_freq_est=backend_config.defaults['meas_freq_est']\n )\n\n # system size\n n_qubits = backend_config.n_qubits\n n_registers = backend_config.n_registers\n n_uchannels = backend_config.n_uchannels\n\n if n_uchannels > 0 and n_uchannels != n_qubits:\n raise PulseError(\"This version assumes no U-channels or #U-cannels==#qubits.\")\n\n # frequency information\n qubit_lo_freqs = backend_default.qubit_freq_est\n qubit_lo_ranges = backend_config.qubit_lo_range\n meas_lo_freqs = backend_default.meas_freq_est\n meas_lo_ranges = backend_config.meas_lo_range\n\n # generate channels with assuming their numberings are aligned with qubits\n drives = [\n DriveChannel(i, qubit_lo_freqs[i], tuple(qubit_lo_ranges[i]))\n for i in range(n_qubits)\n ]\n measures = [\n MeasureChannel(i, meas_lo_freqs[i], tuple(meas_lo_ranges[i]))\n for i in range(n_qubits)\n ]\n acquires = [AcquireChannel(i) for i in range(n_qubits)]\n controls = [ControlChannel(i) for i in range(n_uchannels)]\n\n qubits = []\n for i in range(n_qubits):\n # TODO: get qubits <-> channels relationship from backend\n qubit = Qubit(i,\n drive_channels=[drives[i]],\n control_channels=None if n_uchannels == 0 else controls[i],\n measure_channels=[measures[i]],\n acquire_channels=[acquires[i]])\n qubits.append(qubit)\n\n registers = [RegisterSlot(i) for i in range(n_registers)]\n # TODO: get #mem_slots from backend\n mem_slots = [MemorySlot(i) for i in range(len(qubits))]\n\n return DeviceSpecification(qubits, registers, mem_slots)", "response": "Create a new instance of the object based on the given backend."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef run(self, dag):\n new_dag = DAGCircuit()\n for qreg in dag.qregs.values():\n new_dag.add_qreg(qreg)\n for creg in dag.cregs.values():\n new_dag.add_creg(creg)\n\n # compute ordered indices for the global circuit wires\n global_index_map = {}\n for wire in dag.wires:\n if not isinstance(wire[0], QuantumRegister):\n continue\n global_qregs = list(dag.qregs.values())\n global_index_map[wire] = global_qregs.index(wire[0]) + wire[1]\n\n blocks = self.property_set['block_list']\n nodes_seen = set()\n\n for node in dag.topological_op_nodes():\n # skip already-visited nodes or input/output nodes\n if node in nodes_seen or node.type == 'in' or node.type == 'out':\n continue\n # check if the node belongs to the next block\n if blocks and node in blocks[0]:\n block = blocks[0]\n # find the qubits involved in this block\n block_qargs = set()\n for nd in block:\n block_qargs |= set(nd.qargs)\n # convert block to a sub-circuit, then simulate unitary and add\n block_width = len(block_qargs)\n q = QuantumRegister(block_width)\n subcirc = QuantumCircuit(q)\n block_index_map = self._block_qargs_to_indices(block_qargs,\n global_index_map)\n for nd in block:\n nodes_seen.add(nd)\n subcirc.append(nd.op, [q[block_index_map[i]] for i in nd.qargs])\n unitary = UnitaryGate(Operator(subcirc)) # simulates the circuit\n new_dag.apply_operation_back(\n unitary, sorted(block_qargs, key=lambda x: block_index_map[x]))\n del blocks[0]\n else:\n # the node could belong to some future block, but in that case\n # we simply skip it. It is guaranteed that we will revisit that\n # future block, via its other nodes\n for block in blocks[1:]:\n if node in block:\n break\n # freestanding nodes can just be added\n else:\n nodes_seen.add(node)\n new_dag.apply_operation_back(node.op, node.qargs, node.cargs)\n\n return new_dag", "response": "iterate over each block and replace it with an equivalent UnitaryGate on the same wires."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nmap each qubit in block_qargs to its wire position among the block s wires.", "response": "def _block_qargs_to_indices(self, block_qargs, global_index_map):\n \"\"\"\n Map each qubit in block_qargs to its wire position among the block's wires.\n Args:\n block_qargs (list): list of qubits that a block acts on\n global_index_map (dict): mapping from each qubit in the\n circuit to its wire position within that circuit\n Returns:\n dict: mapping from qarg to position in block\n \"\"\"\n block_indices = [global_index_map[q] for q in block_qargs]\n ordered_block_indices = sorted(block_indices)\n block_positions = {q: ordered_block_indices.index(global_index_map[q])\n for q in block_qargs}\n return block_positions"}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef get_bound_method(self, instruction):\n try:\n return self._bound_instructions[type(instruction)]\n except KeyError:\n raise PulseError('Qobj conversion method for %s is not found.' % instruction)", "response": "Get conversion method for instruction."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nconverting an acquire instruction to a new version of the QOBJ model.", "response": "def convert_acquire(self, shift, instruction):\n \"\"\"Return converted `AcquireInstruction`.\n\n Args:\n shift(int): Offset time.\n instruction (AcquireInstruction): acquire instruction.\n Returns:\n dict: Dictionary of required parameters.\n \"\"\"\n meas_level = self._run_config.get('meas_level', 2)\n\n command_dict = {\n 'name': 'acquire',\n 't0': shift+instruction.start_time,\n 'duration': instruction.duration,\n 'qubits': [q.index for q in instruction.acquires],\n 'memory_slot': [m.index for m in instruction.mem_slots]\n }\n if meas_level == 2:\n # setup discriminators\n if instruction.command.discriminator:\n command_dict.update({\n 'discriminators': [\n QobjMeasurementOption(\n name=instruction.command.discriminator.name,\n params=instruction.command.discriminator.params)\n ]\n })\n # setup register_slots\n command_dict.update({\n 'register_slot': [regs.index for regs in instruction.reg_slots]\n })\n if meas_level >= 1:\n # setup kernels\n if instruction.command.kernel:\n command_dict.update({\n 'kernels': [\n QobjMeasurementOption(\n name=instruction.command.kernel.name,\n params=instruction.command.kernel.params)\n ]\n })\n return self._qobj_model(**command_dict)"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nreturn converted frame change instruction.", "response": "def convert_frame_change(self, shift, instruction):\n \"\"\"Return converted `FrameChangeInstruction`.\n\n Args:\n shift(int): Offset time.\n instruction (FrameChangeInstruction): frame change instruction.\n Returns:\n dict: Dictionary of required parameters.\n \"\"\"\n command_dict = {\n 'name': 'fc',\n 't0': shift+instruction.start_time,\n 'ch': instruction.channels[0].name,\n 'phase': instruction.command.phase\n }\n return self._qobj_model(**command_dict)"}
+{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\nreturn converted persistent value instruction.", "response": "def convert_persistent_value(self, shift, instruction):\n \"\"\"Return converted `PersistentValueInstruction`.\n\n Args:\n shift(int): Offset time.\n instruction (PersistentValueInstruction): persistent value instruction.\n Returns:\n dict: Dictionary of required parameters.\n \"\"\"\n command_dict = {\n 'name': 'pv',\n 't0': shift+instruction.start_time,\n 'ch': instruction.channels[0].name,\n 'val': instruction.command.value\n }\n return self._qobj_model(**command_dict)"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn converted drive command.", "response": "def convert_drive(self, shift, instruction):\n \"\"\"Return converted `PulseInstruction`.\n\n Args:\n shift(int): Offset time.\n instruction (PulseInstruction): drive instruction.\n Returns:\n dict: Dictionary of required parameters.\n \"\"\"\n command_dict = {\n 'name': instruction.command.name,\n 't0': shift+instruction.start_time,\n 'ch': instruction.channels[0].name\n }\n return self._qobj_model(**command_dict)"}
+{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef convert_snapshot(self, shift, instruction):\n command_dict = {\n 'name': 'snapshot',\n 't0': shift+instruction.start_time,\n 'label': instruction.name,\n 'type': instruction.type\n }\n return self._qobj_model(**command_dict)", "response": "Return converted `Snapshot`.\n\n Args:\n shift(int): Offset time.\n instruction (Snapshot): snapshot instruction.\n Returns:\n dict: Dictionary of required parameters."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef _update_annotations(discretized_pulse: Callable) -> Callable:\n undecorated_annotations = list(discretized_pulse.__annotations__.items())\n decorated_annotations = undecorated_annotations[1:]\n decorated_annotations.insert(0, ('duration', int))\n discretized_pulse.__annotations__ = dict(decorated_annotations)\n return discretized_pulse", "response": "Update annotations of discretized continuous pulse function with duration."}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef _update_docstring(discretized_pulse: Callable, sampler_inst: Callable) -> Callable:\n wrapped_docstring = pydoc.render_doc(discretized_pulse, '%s')\n header, body = wrapped_docstring.split('\\n', 1)\n body = textwrap.indent(body, ' ')\n wrapped_docstring = header+body\n updated_ds = \"\"\"\n Discretized continuous pulse function: `{continuous_name}` using\n sampler: `{sampler_name}`.\n\n The first argument (time) of the continuous pulse function has been replaced with\n a discretized `duration` of type (int).\n\n Args:\n duration (int)\n *args: Remaining arguments of continuous pulse function.\n See continuous pulse function documentation below.\n **kwargs: Remaining kwargs of continuous pulse function.\n See continuous pulse function documentation below.\n\n Sampled continuous function:\n\n {continuous_doc}\n \"\"\".format(continuous_name=discretized_pulse.__name__,\n sampler_name=sampler_inst.__name__,\n continuous_doc=wrapped_docstring)\n\n discretized_pulse.__doc__ = updated_ds\n return discretized_pulse", "response": "Update the docstring of a continuous pulse function."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef sampler(sample_function: Callable) -> Callable:\n\n def generate_sampler(continuous_pulse: Callable) -> Callable:\n \"\"\"Return a decorated sampler function.\"\"\"\n\n @functools.wraps(continuous_pulse)\n def call_sampler(duration: int, *args, **kwargs) -> commands.SamplePulse:\n \"\"\"Replace the call to the continuous function with a call to the sampler applied\n to the anlytic pulse function.\"\"\"\n sampled_pulse = sample_function(continuous_pulse, duration, *args, **kwargs)\n return np.asarray(sampled_pulse, dtype=np.complex_)\n\n # Update type annotations for wrapped continuous function to be discrete\n call_sampler = _update_annotations(call_sampler)\n # Update docstring with that of the sampler and include sampled function documentation.\n call_sampler = _update_docstring(call_sampler, sample_function)\n # Unset wrapped to return base sampler signature\n # but still get rest of benefits of wraps\n # such as __name__, __qualname__\n call_sampler.__dict__.pop('__wrapped__')\n # wrap with functional pulse\n return commands.functional_pulse(call_sampler)\n\n return generate_sampler", "response": "Decorator for generating a sampler function."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nfiltering the list of backends by their configuration or status attributes or from a boolean callable.", "response": "def filter_backends(backends, filters=None, **kwargs):\n \"\"\"Return the backends matching the specified filtering.\n\n Filter the `backends` list by their `configuration` or `status`\n attributes, or from a boolean callable. The criteria for filtering can\n be specified via `**kwargs` or as a callable via `filters`, and the\n backends must fulfill all specified conditions.\n\n Args:\n backends (list[BaseBackend]): list of backends.\n filters (callable): filtering conditions as a callable.\n **kwargs (dict): dict of criteria.\n\n Returns:\n list[BaseBackend]: a list of backend instances matching the\n conditions.\n \"\"\"\n def _match_all(obj, criteria):\n \"\"\"Return True if all items in criteria matches items in obj.\"\"\"\n return all(getattr(obj, key_, None) == value_ for\n key_, value_ in criteria.items())\n\n # Inspect the backends to decide which filters belong to\n # backend.configuration and which ones to backend.status, as it does\n # not involve querying the API.\n configuration_filters = {}\n status_filters = {}\n for key, value in kwargs.items():\n if all(key in backend.configuration() for backend in backends):\n configuration_filters[key] = value\n else:\n status_filters[key] = value\n\n # 1. Apply backend.configuration filtering.\n if configuration_filters:\n backends = [b for b in backends if\n _match_all(b.configuration(), configuration_filters)]\n\n # 2. Apply backend.status filtering (it involves one API call for\n # each backend).\n if status_filters:\n backends = [b for b in backends if\n _match_all(b.status(), status_filters)]\n\n # 3. Apply acceptor filter.\n backends = list(filter(filters, backends))\n\n return backends"}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef resolve_backend_name(name, backends, deprecated, aliased):\n available = [backend.name() for backend in backends]\n\n resolved_name = deprecated.get(name, aliased.get(name, name))\n if isinstance(resolved_name, list):\n resolved_name = next((b for b in resolved_name if b in available), \"\")\n\n if resolved_name not in available:\n raise LookupError(\"backend '{}' not found.\".format(name))\n\n if name in deprecated:\n logger.warning(\"WARNING: '%s' is deprecated. Use '%s'.\", name, resolved_name)\n\n return resolved_name", "response": "Resolve backend name from a deprecated name or an aliased name."}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef dag_to_circuit(dag):\n qregs = collections.OrderedDict()\n for qreg in dag.qregs.values():\n qreg_tmp = QuantumRegister(qreg.size, name=qreg.name)\n qregs[qreg.name] = qreg_tmp\n cregs = collections.OrderedDict()\n for creg in dag.cregs.values():\n creg_tmp = ClassicalRegister(creg.size, name=creg.name)\n cregs[creg.name] = creg_tmp\n\n name = dag.name or None\n circuit = QuantumCircuit(*qregs.values(), *cregs.values(), name=name)\n\n for node in dag.topological_op_nodes():\n qubits = []\n for qubit in node.qargs:\n qubits.append(qregs[qubit[0].name][qubit[1]])\n\n clbits = []\n for clbit in node.cargs:\n clbits.append(cregs[clbit[0].name][clbit[1]])\n\n # Get arguments for classical control (if any)\n if node.condition is None:\n control = None\n else:\n control = (node.condition[0], node.condition[1])\n\n inst = node.op.copy()\n inst.control = control\n circuit.append(inst, qubits, clbits)\n return circuit", "response": "Return a QuantumCircuit object from a DAGCircuit."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nconvert an observable in matrix form to dictionary form.", "response": "def make_dict_observable(matrix_observable):\n \"\"\"Convert an observable in matrix form to dictionary form.\n\n Takes in a diagonal observable as a matrix and converts it to a dictionary\n form. Can also handle a list sorted of the diagonal elements.\n\n Args:\n matrix_observable (list): The observable to be converted to dictionary\n form. Can be a matrix or just an ordered list of observed values\n\n Returns:\n Dict: A dictionary with all observable states as keys, and corresponding\n values being the observed value for that state\n \"\"\"\n dict_observable = {}\n observable = np.array(matrix_observable)\n observable_size = len(observable)\n observable_bits = int(np.ceil(np.log2(observable_size)))\n binary_formater = '0{}b'.format(observable_bits)\n if observable.ndim == 2:\n observable = observable.diagonal()\n for state_no in range(observable_size):\n state_str = format(state_no, binary_formater)\n dict_observable[state_str] = observable[state_no]\n return dict_observable"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nupdate a node in the symbol table.", "response": "def update_symtab(self, obj):\n \"\"\"Update a node in the symbol table.\n\n Everything in the symtab must be a node with these attributes:\n name - the string name of the object\n type - the string type of the object\n line - the source line where the type was first found\n file - the source file where the type was first found\n \"\"\"\n if obj.name in self.current_symtab:\n prev = self.current_symtab[obj.name]\n raise QasmError(\"Duplicate declaration for\", obj.type + \" '\"\n + obj.name + \"' at line\", str(obj.line)\n + ', file', obj.file\n + '.\\nPrevious occurrence at line',\n str(prev.line) + ', file', prev.file)\n self.current_symtab[obj.name] = obj"}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef verify_declared_bit(self, obj):\n # We are verifying gate args against the formal parameters of a\n # gate prototype.\n if obj.name not in self.current_symtab:\n raise QasmError(\"Cannot find symbol '\" + obj.name\n + \"' in argument list for gate, line\",\n str(obj.line), 'file', obj.file)\n\n # This insures the thing is from the bitlist and not from the\n # argument list.\n sym = self.current_symtab[obj.name]\n if not (sym.type == 'id' and sym.is_bit):\n raise QasmError(\"Bit\", obj.name,\n 'is not declared as a bit in the gate.')", "response": "Verify a qubit id against the gate prototype."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef verify_exp_list(self, obj):\n # A tad harder. This is a list of expressions each of which could be\n # the head of a tree. We need to recursively walk each of these and\n # ensure that any Id elements resolve to the current stack.\n #\n # I believe we only have to look at the current symtab.\n if obj.children is not None:\n for children in obj.children:\n if isinstance(children, node.Id):\n if children.name in self.external_functions:\n continue\n\n if children.name not in self.current_symtab:\n raise QasmError(\"Argument '\" + children.name\n + \"' in expression cannot be \"\n + \"found, line\", str(children.line),\n \"file\", children.file)\n else:\n if hasattr(children, \"children\"):\n self.verify_exp_list(children)", "response": "Verify each expression in a list."}
+{"SOURCE": "codesearchnet", "instruction": "How would you implement a function in Python 3 that\nverifies a user defined gate call.", "response": "def verify_as_gate(self, obj, bitlist, arglist=None):\n \"\"\"Verify a user defined gate call.\"\"\"\n if obj.name not in self.global_symtab:\n raise QasmError(\"Cannot find gate definition for '\" + obj.name\n + \"', line\", str(obj.line), 'file', obj.file)\n g_sym = self.global_symtab[obj.name]\n if not (g_sym.type == 'gate' or g_sym.type == 'opaque'):\n raise QasmError(\"'\" + obj.name + \"' is used as a gate \"\n + \"or opaque call but the symbol is neither;\"\n + \" it is a '\" + g_sym.type + \"' line\",\n str(obj.line), 'file', obj.file)\n\n if g_sym.n_bits() != bitlist.size():\n raise QasmError(\"Gate or opaque call to '\" + obj.name\n + \"' uses\", str(bitlist.size()),\n \"qubits but is declared for\",\n str(g_sym.n_bits()), \"qubits\", \"line\",\n str(obj.line), 'file', obj.file)\n\n if arglist:\n if g_sym.n_args() != arglist.size():\n raise QasmError(\"Gate or opaque call to '\" + obj.name\n + \"' uses\", str(arglist.size()),\n \"qubits but is declared for\",\n str(g_sym.n_args()), \"qubits\", \"line\",\n str(obj.line), 'file', obj.file)\n else:\n if g_sym.n_args() > 0:\n raise QasmError(\"Gate or opaque call to '\" + obj.name\n + \"' has no arguments but is declared for\",\n str(g_sym.n_args()), \"qubits\", \"line\",\n str(obj.line), 'file', obj.file)"}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef verify_reg_list(self, obj, object_type):\n # We expect the object to be a bitlist or an idlist, we don't care.\n # We will iterate it and ensure everything in it is declared as a bit,\n # and throw if not.\n for children in obj.children:\n self.verify_reg(children, object_type)", "response": "Verify a list of registers."}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nreturning a list of tuples for this id node.", "response": "def id_tuple_list(self, id_node):\n \"\"\"Return a list of (name, index) tuples for this id node.\"\"\"\n if id_node.type != \"id\":\n raise QasmError(\"internal error, id_tuple_list\")\n bit_list = []\n try:\n g_sym = self.current_symtab[id_node.name]\n except KeyError:\n g_sym = self.global_symtab[id_node.name]\n if g_sym.type == \"qreg\" or g_sym.type == \"creg\":\n # Return list of (name, idx) for reg ids\n for idx in range(g_sym.index):\n bit_list.append((id_node.name, idx))\n else:\n # Return (name, -1) for other ids\n bit_list.append((id_node.name, -1))\n return bit_list"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef verify_distinct(self, list_of_nodes):\n bit_list = []\n line_number = -1\n filename = \"\"\n for node_ in list_of_nodes:\n # id node: add all bits in register or (name, -1) for id\n if node_.type == \"id\":\n bit_list.extend(self.id_tuple_list(node_))\n line_number = node_.line\n filename = node_.file\n # indexed_id: add the bit\n elif node_.type == \"indexed_id\":\n bit_list.append((node_.name, node_.index))\n line_number = node_.line\n filename = node_.file\n # primary_list: for each id or indexed_id child, add\n elif node_.type == \"primary_list\":\n for child in node_.children:\n if child.type == \"id\":\n bit_list.extend(self.id_tuple_list(child))\n else:\n bit_list.append((child.name, child.index))\n line_number = child.line\n filename = child.file\n # id_list: for each id, add\n elif node_.type == \"id_list\":\n for child in node_.children:\n bit_list.extend(self.id_tuple_list(child))\n line_number = child.line\n filename = child.file\n else:\n raise QasmError(\"internal error, verify_distinct\")\n if len(bit_list) != len(set(bit_list)):\n raise QasmError(\"duplicate identifiers at line %d file %s\"\n % (line_number, filename))", "response": "Verify that the objects in list_of_nodes represent distinct bits."}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nprocessing a single statement.", "response": "def p_statement(self, program):\n \"\"\"\n statement : decl\n | quantum_op ';'\n | format ';'\n | ignore\n | quantum_op error\n | format error\n \"\"\"\n if len(program) > 2:\n if program[2] != ';':\n raise QasmError(\"Missing ';' at end of statement; \"\n + \"received\", str(program[2].value))\n program[0] = program[1]"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script to\nparse indexed ID program.", "response": "def p_indexed_id(self, program):\n \"\"\"\n indexed_id : id '[' NNINTEGER ']'\n | id '[' NNINTEGER error\n | id '[' error\n \"\"\"\n if len(program) == 4:\n raise QasmError(\"Expecting an integer index; received\",\n str(program[3].value))\n if program[4] != ']':\n raise QasmError(\"Missing ']' in indexed ID; received\",\n str(program[4].value))\n program[0] = node.IndexedId([program[1], node.Int(program[3])])"}
+{"SOURCE": "codesearchnet", "instruction": "How would you explain what the following Python 3 function does\ndef p_gate_id_list_0(self, program):\n program[0] = node.IdList([program[1]])\n self.update_symtab(program[1])", "response": "Update the symtab with the list of gate IDs."}
+{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef p_bit_list_0(self, program):\n program[0] = node.IdList([program[1]])\n program[1].is_bit = True\n self.update_symtab(program[1])", "response": "Set the bit list to 0"}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function for\nprocessing bit list 1.", "response": "def p_bit_list_1(self, program):\n \"\"\"\n bit_list : bit_list ',' id\n \"\"\"\n program[0] = program[1]\n program[0].add_child(program[3])\n program[3].is_bit = True\n self.update_symtab(program[3])"}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef p_decl(self, program):\n if len(program) > 2:\n if program[2] != ';':\n raise QasmError(\"Missing ';' in qreg or creg declaration.\"\n \" Instead received '\" + program[2].value + \"'\")\n program[0] = program[1]", "response": "Process the declaration of a set of keys."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nprocessing a QREG declaration.", "response": "def p_qreg_decl(self, program):\n \"\"\"\n qreg_decl : QREG indexed_id\n \"\"\"\n program[0] = node.Qreg([program[2]])\n if program[2].name in self.external_functions:\n raise QasmError(\"QREG names cannot be reserved words. \"\n + \"Received '\" + program[2].name + \"'\")\n if program[2].index == 0:\n raise QasmError(\"QREG size must be positive\")\n self.update_symtab(program[0])"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nprocessing a CREG declaration program.", "response": "def p_creg_decl(self, program):\n \"\"\"\n creg_decl : CREG indexed_id\n \"\"\"\n program[0] = node.Creg([program[2]])\n if program[2].name in self.external_functions:\n raise QasmError(\"CREG names cannot be reserved words. \"\n + \"Received '\" + program[2].name + \"'\")\n if program[2].index == 0:\n raise QasmError(\"CREG size must be positive\")\n self.update_symtab(program[0])"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nparsing the gate body.", "response": "def p_gate_body_0(self, program):\n \"\"\"\n gate_body : '{' '}'\n \"\"\"\n if program[2] != '}':\n raise QasmError(\"Missing '}' in gate definition; received'\"\n + str(program[2].value) + \"'\")\n program[0] = node.GateBody(None)"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef p_unitary_op_0(self, program):\n program[0] = node.UniversalUnitary([program[3], program[5]])\n self.verify_reg(program[5], 'qreg')\n self.verify_exp_list(program[3])", "response": "P_unitary_op_0 is the unitary operation that is used in the code."}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef p_unitary_op_1(self, program):\n program[0] = node.Cnot([program[2], program[4]])\n self.verify_reg(program[2], 'qreg')\n self.verify_reg(program[4], 'qreg')\n self.verify_distinct([program[2], program[4]])", "response": "P 1. 2. 6. 1. 1."}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef p_unitary_op_2(self, program):\n program[0] = node.CustomUnitary([program[1], program[2]])\n self.verify_as_gate(program[1], program[2])\n self.verify_reg_list(program[2], 'qreg')\n self.verify_distinct([program[2]])", "response": "Verify that unitary_op is 2."}
+{"SOURCE": "codesearchnet", "instruction": "Create a Python 3 function to\ncheck that the unitary op is 3.", "response": "def p_unitary_op_3(self, program):\n \"\"\"\n unitary_op : id '(' ')' primary_list\n \"\"\"\n program[0] = node.CustomUnitary([program[1], program[4]])\n self.verify_as_gate(program[1], program[4])\n self.verify_reg_list(program[4], 'qreg')\n self.verify_distinct([program[4]])"}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nhandles the 4 - level unitary operation.", "response": "def p_unitary_op_4(self, program):\n \"\"\"\n unitary_op : id '(' exp_list ')' primary_list\n \"\"\"\n program[0] = node.CustomUnitary([program[1], program[3], program[5]])\n self.verify_as_gate(program[1], program[5], arglist=program[3])\n self.verify_reg_list(program[5], 'qreg')\n self.verify_exp_list(program[3])\n self.verify_distinct([program[5]])"}
+{"SOURCE": "codesearchnet", "instruction": "Explain what the following Python 3 code does\ndef p_gate_op_1(self, program):\n program[0] = node.Cnot([program[2], program[4]])\n self.verify_declared_bit(program[2])\n self.verify_declared_bit(program[4])\n self.verify_distinct([program[2], program[4]])", "response": "P gate op 1"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef p_gate_op_2(self, program):\n program[0] = node.CustomUnitary([program[1], program[2]])\n # To verify:\n # 1. id is declared as a gate in global scope\n # 2. everything in the id_list is declared as a bit in local scope\n self.verify_as_gate(program[1], program[2])\n self.verify_bit_list(program[2])\n self.verify_distinct([program[2]])", "response": "Check that gate_op is 2."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nhandle gate op 3.", "response": "def p_gate_op_3(self, program):\n \"\"\"\n gate_op : id '(' ')' id_list ';'\n \"\"\"\n program[0] = node.CustomUnitary([program[1], program[4]])\n self.verify_as_gate(program[1], program[4])\n self.verify_bit_list(program[4])\n self.verify_distinct([program[4]])"}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef p_gate_op_4(self, program):\n program[0] = node.CustomUnitary([program[1], program[3], program[5]])\n self.verify_as_gate(program[1], program[5], arglist=program[3])\n self.verify_bit_list(program[5])\n self.verify_exp_list(program[3])\n self.verify_distinct([program[5]])", "response": "Handle gate op 4."}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\nhandles the gate operation 5.", "response": "def p_gate_op_5(self, program):\n \"\"\"\n gate_op : BARRIER id_list ';'\n \"\"\"\n program[0] = node.Barrier([program[2]])\n self.verify_bit_list(program[2])\n self.verify_distinct([program[2]])"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function that can\nopaque : OPAQUE id gate_scope bit_list", "response": "def p_opaque_0(self, program):\n \"\"\"\n opaque : OPAQUE id gate_scope bit_list\n \"\"\"\n # TODO: Review Opaque function\n program[0] = node.Opaque([program[2], program[4]])\n if program[2].name in self.external_functions:\n raise QasmError(\"OPAQUE names cannot be reserved words. \"\n + \"Received '\" + program[2].name + \"'\")\n self.pop_scope()\n self.update_symtab(program[0])"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nopaquing : OPAQUE id gate_scope '(' ')' bit_list", "response": "def p_opaque_1(self, program):\n \"\"\"\n opaque : OPAQUE id gate_scope '(' ')' bit_list\n \"\"\"\n program[0] = node.Opaque([program[2], program[6]])\n self.pop_scope()\n self.update_symtab(program[0])"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef p_measure(self, program):\n program[0] = node.Measure([program[2], program[4]])\n self.verify_reg(program[2], 'qreg')\n self.verify_reg(program[4], 'creg')", "response": "P_MEASURE is a basic operation on the COORDINATES section."}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 function for\nresetting the entry point.", "response": "def p_reset(self, program):\n \"\"\"\n reset : RESET primary\n \"\"\"\n program[0] = node.Reset([program[2]])\n self.verify_reg(program[2], 'qreg')"}
+{"SOURCE": "codesearchnet", "instruction": "Here you have a function in Python 3, explain what it does\ndef p_if(self, program):\n if len(program) == 3:\n raise QasmError(\"Ill-formed IF statement. Perhaps a\"\n + \" missing '('?\")\n if len(program) == 5:\n raise QasmError(\"Ill-formed IF statement. Expected '==', \"\n + \"received '\" + str(program[4].value))\n if len(program) == 6:\n raise QasmError(\"Ill-formed IF statement. Expected a number, \"\n + \"received '\" + str(program[5].value))\n if len(program) == 7:\n raise QasmError(\"Ill-formed IF statement, unmatched '('\")\n\n if program[7].type == 'if':\n raise QasmError(\"Nested IF statements not allowed\")\n if program[7].type == 'barrier':\n raise QasmError(\"barrier not permitted in IF statement\")\n\n program[0] = node.If([program[3], node.Int(program[5]), program[7]])", "response": "P - IF statement."}
+{"SOURCE": "codesearchnet", "instruction": "Make a summary of the following Python 3 code\ndef p_expression_1(self, program):\n program[0] = node.Prefix([node.UnaryOperator(program[1]), program[2]])", "response": "expression : '-' expression %prec negative\n | '+' expression %prec positive"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate a brief explanation for the following Python 3 code\ndef p_expression_0(self, program):\n program[0] = node.BinaryOp([node.BinaryOperator(program[2]),\n program[1], program[3]])", "response": "expression : expression '*' expression\n | expression '/' expression\n | expression '+' expression\n | expression '-' expression\n | expression '^' expression"}
+{"SOURCE": "codesearchnet", "instruction": "How would you code a function in Python 3 to\ncompute the column in the input text string.", "response": "def find_column(self, input_, token):\n \"\"\"Compute the column.\n\n Input is the input text string.\n token is a token instance.\n \"\"\"\n if token is None:\n return 0\n last_cr = input_.rfind('\\n', 0, token.lexpos)\n if last_cr < 0:\n last_cr = 0\n column = (token.lexpos - last_cr) + 1\n return column"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef get_tokens(self):\n try:\n while True:\n token = self.lexer.token()\n\n if not token:\n break\n\n yield token\n except QasmError as e:\n print('Exception tokenizing qasm file:', e.msg)", "response": "Returns a generator of the tokens."}
+{"SOURCE": "codesearchnet", "instruction": "Can you write a function in Python 3 where it\nsets the parse_deb field.", "response": "def parse_debug(self, val):\n \"\"\"Set the parse_deb field.\"\"\"\n if val is True:\n self.parse_deb = True\n elif val is False:\n self.parse_deb = False\n else:\n raise QasmError(\"Illegal debug value '\" + str(val)\n + \"' must be True or False.\")"}
+{"SOURCE": "codesearchnet", "instruction": "Write a Python 3 script for\nparsing the data and return the result.", "response": "def run(self, data):\n \"\"\"Parser runner.\n\n To use this module stand-alone.\n \"\"\"\n ast = self.parser.parse(data, debug=True)\n self.parser.parse(data, debug=True)\n ast.to_string(0)"}
+{"SOURCE": "codesearchnet", "instruction": "Implement a function in Python 3 to\nreturn a generator of the tokens.", "response": "def get_tokens(self):\n \"\"\"Returns a generator of the tokens.\"\"\"\n if self._filename:\n with open(self._filename) as ifile:\n self._data = ifile.read()\n\n with QasmParser(self._filename) as qasm_p:\n return qasm_p.get_tokens()"}
+{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\napplies crz from ctl to tgt with angle theta.", "response": "def crz(self, theta, ctl, tgt):\n \"\"\"Apply crz from ctl to tgt with angle theta.\"\"\"\n return self.append(CrzGate(theta), [ctl, tgt], [])"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef basis_state(str_state, num):\n n = int(str_state, 2)\n if num >= len(str_state):\n state = np.zeros(1 << num, dtype=complex)\n state[n] = 1\n return state\n else:\n raise QiskitError('size of bitstring is greater than num.')", "response": "Return a basis state ndarray."}
+{"SOURCE": "codesearchnet", "instruction": "Given the following Python 3 function, write the documentation\ndef projector(state, flatten=False):\n density_matrix = np.outer(state.conjugate(), state)\n if flatten:\n return density_matrix.flatten(order='F')\n return density_matrix", "response": "Maps a pure state matrix to a state matrix of column workitems."}
+{"SOURCE": "codesearchnet", "instruction": "Can you implement a function in Python 3 that\ncalculates the purity of a quantum state.", "response": "def purity(state):\n \"\"\"Calculate the purity of a quantum state.\n\n Args:\n state (ndarray): a quantum state\n Returns:\n float: purity.\n \"\"\"\n rho = np.array(state)\n if rho.ndim == 1:\n return 1.0\n return np.real(np.trace(rho.dot(rho)))"}
+{"SOURCE": "codesearchnet", "instruction": "Can you generate the documentation for the following Python 3 function\ndef qasm(self, prec=15):\n string = \"gate \" + self.name\n if self.arguments is not None:\n string += \"(\" + self.arguments.qasm(prec) + \")\"\n string += \" \" + self.bitlist.qasm(prec) + \"\\n\"\n string += \"{\\n\" + self.body.qasm(prec) + \"}\"\n return string", "response": "Return the corresponding OPENQASM string."}
+{"SOURCE": "codesearchnet", "instruction": "Implement a Python 3 function for\nrunning the pass on the DAG and write the discovered commutation relations to the property_set.", "response": "def run(self, dag):\n \"\"\"\n Run the pass on the DAG, and write the discovered commutation relations\n into the property_set.\n \"\"\"\n # Initiate the commutation set\n self.property_set['commutation_set'] = defaultdict(list)\n\n # Build a dictionary to keep track of the gates on each qubit\n for wire in dag.wires:\n wire_name = \"{0}[{1}]\".format(str(wire[0].name), str(wire[1]))\n self.property_set['commutation_set'][wire_name] = []\n\n # Add edges to the dictionary for each qubit\n for node in dag.topological_op_nodes():\n for (_, _, edge_data) in dag.edges(node):\n\n edge_name = edge_data['name']\n self.property_set['commutation_set'][(node, edge_name)] = -1\n\n for wire in dag.wires:\n wire_name = \"{0}[{1}]\".format(str(wire[0].name), str(wire[1]))\n\n for current_gate in dag.nodes_on_wire(wire):\n\n current_comm_set = self.property_set['commutation_set'][wire_name]\n if not current_comm_set:\n current_comm_set.append([current_gate])\n\n if current_gate not in current_comm_set[-1]:\n prev_gate = current_comm_set[-1][-1]\n if _commute(current_gate, prev_gate):\n current_comm_set[-1].append(current_gate)\n\n else:\n current_comm_set.append([current_gate])\n\n temp_len = len(current_comm_set)\n self.property_set['commutation_set'][(current_gate, wire_name)] = temp_len - 1"}
+{"SOURCE": "codesearchnet", "instruction": "Can you create a Python 3 function that\ncreates a backend widget.", "response": "def backend_widget(backend):\n \"\"\"Creates a backend widget.\n \"\"\"\n config = backend.configuration().to_dict()\n props = backend.properties().to_dict()\n\n name = widgets.HTML(value=\"{name}
\".format(name=backend.name()),\n layout=widgets.Layout())\n\n n_qubits = config['n_qubits']\n\n qubit_count = widgets.HTML(value=\"{qubits}
\".format(qubits=n_qubits),\n layout=widgets.Layout(justify_content='center'))\n\n cmap = widgets.Output(layout=widgets.Layout(min_width='250px', max_width='250px',\n max_height='250px',\n min_height='250px',\n justify_content='center',\n align_items='center',\n margin='0px 0px 0px 0px'))\n\n with cmap:\n _cmap_fig = plot_gate_map(backend,\n plot_directed=False,\n label_qubits=False)\n if _cmap_fig is not None:\n display(_cmap_fig)\n # Prevents plot from showing up twice.\n plt.close(_cmap_fig)\n\n pending = generate_jobs_pending_widget()\n\n is_oper = widgets.HTML(value=\"\",\n layout=widgets.Layout(justify_content='center'))\n\n least_busy = widgets.HTML(value=\"\",\n layout=widgets.Layout(justify_content='center'))\n\n t1_units = props['qubits'][0][0]['unit']\n avg_t1 = round(sum([q[0]['value'] for q in props['qubits']])/n_qubits, 1)\n t1_widget = widgets.HTML(value=\"{t1} {units}
\".format(t1=avg_t1, units=t1_units),\n layout=widgets.Layout())\n\n t2_units = props['qubits'][0][1]['unit']\n avg_t2 = round(sum([q[1]['value'] for q in props['qubits']])/n_qubits, 1)\n t2_widget = widgets.HTML(value=\"{t2} {units}
\".format(t2=avg_t2, units=t2_units),\n layout=widgets.Layout())\n\n out = widgets.VBox([name, cmap, qubit_count, pending,\n least_busy, is_oper, t1_widget, t2_widget],\n layout=widgets.Layout(display='inline-flex',\n flex_flow='column',\n align_items='center'))\n\n out._is_alive = True\n return out"}
+{"SOURCE": "codesearchnet", "instruction": "Can you tell what is the following Python 3 function doing\ndef update_backend_info(self, interval=60):\n my_thread = threading.currentThread()\n current_interval = 0\n started = False\n all_dead = False\n stati = [None]*len(self._backends)\n while getattr(my_thread, \"do_run\", True) and not all_dead:\n if current_interval == interval or started is False:\n for ind, back in enumerate(self._backends):\n _value = self.children[ind].children[2].value\n _head = _value.split('')[0]\n try:\n _status = back.status()\n stati[ind] = _status\n except Exception: # pylint: disable=W0703\n self.children[ind].children[2].value = _value.replace(\n _head, \"