{"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
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 = \"