


'''simple docstring'''







import numpy as np
import qiskit


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     str   ,_UpperCAmelCase     :     int  )  ->      qiskit.QuantumCircuit:
       _a   :			Any					 =qiskit.QuantumCircuit(num_qubits + 1  )

       # First, let's deal with the case in which oracle is balanced
       if case == "balanced":
              # First generate a random number that tells us which CNOTs to
              # wrap in X-gates:
              _a   :			Any					 =np.random.randint(1   ,2**num_qubits  )
              # Next, format 'b' as a binary string of length 'n', padded with zeros:
              _a   :			Tuple					 =format(_UpperCAmelCase   ,F"0{num_qubits}b"  )
              # Next, we place the first X-gates. Each digit in our binary string
              # corresponds to a qubit, if the digit is 0, we do nothing, if it's 1
              # we apply an X-gate to that qubit:
              for index, bit in enumerate(_UpperCAmelCase  ):
                     if bit == "1":
                            oracle_qc.x(_UpperCAmelCase  )
        # Do the controlled-NOT gates for each qubit, using the output qubit
        # as the target:
              for index in range(_UpperCAmelCase  ):
                     oracle_qc.cx(_UpperCAmelCase   ,_UpperCAmelCase  )
              # Next, place the final X-gates
              for index, bit in enumerate(_UpperCAmelCase  ):
                     if bit == "1":
                            oracle_qc.x(_UpperCAmelCase  )

    # Case in which oracle is constant
       if case == "constant":
              # First decide what the fixed output of the oracle will be
              # (either always 0 or always 1)
              _a   :			List[Any]					 =np.random.randint(2  )
              if output == 1:
                     oracle_qc.x(_UpperCAmelCase  )

       _a   :			Optional[int]					 =oracle_qc.to_gate()
       _a   :			Optional[Any]					 ="""Oracle"""  # To show when we display the circuit
       return oracle_gate


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     qiskit.QuantumCircuit   ,_UpperCAmelCase     :     int  )  ->      qiskit.QuantumCircuit:
       _a   :			Tuple					 =qiskit.QuantumCircuit(num_qubits + 1   ,_UpperCAmelCase  )
       # Set up the output qubit:
       dj_circuit.x(_UpperCAmelCase  )
       dj_circuit.h(_UpperCAmelCase  )
       # And set up the input register:
       for qubit in range(_UpperCAmelCase  ):
              dj_circuit.h(_UpperCAmelCase  )
       # Let's append the oracle gate to our circuit:
       dj_circuit.append(_UpperCAmelCase   ,range(num_qubits + 1  )  )
       # Finally, perform the H-gates again and measure:
       for qubit in range(_UpperCAmelCase  ):
              dj_circuit.h(_UpperCAmelCase  )

       for i in range(_UpperCAmelCase  ):
              dj_circuit.measure(_UpperCAmelCase   ,_UpperCAmelCase  )

       return dj_circuit


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     str   ,_UpperCAmelCase     :     int  )  ->      qiskit.result.counts.Counts:
       _a   :			Any					 =qiskit.Aer.get_backend("""aer_simulator"""  )

       _a   :			Tuple					 =dj_oracle(_UpperCAmelCase   ,_UpperCAmelCase  )
       _a   :			List[str]					 =dj_algorithm(_UpperCAmelCase   ,_UpperCAmelCase  )

       # Execute the circuit on the simulator
       _a   :			List[Any]					 =qiskit.execute(_UpperCAmelCase   ,_UpperCAmelCase   ,shots=1000  )

       # Return the histogram data of the results of the experiment.
       return job.result().get_counts(_UpperCAmelCase  )


if __name__ == "__main__":
   print(F"Deutsch Jozsa - Constant Oracle: {deutsch_jozsa('constant', 3)}")
   print(F"Deutsch Jozsa - Balanced Oracle: {deutsch_jozsa('balanced', 3)}")






'''simple docstring'''







from typing import Dict, Optional, Tuple

import torch


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor  )  ->      torch.Tensor:
       _a   :			Tuple					 =boundaries[1] - boundaries[0]
       _a   :			Dict					 =boundaries + step / 2
       _a   :			List[Any]					 =torch.cat([bin_centers, (bin_centers[-1] + step).unsqueeze(-1  )]   ,dim=0  )
       return bin_centers


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     torch.Tensor   ,)  ->      Tuple[torch.Tensor, torch.Tensor]:
       _a   :			Any					 =_calculate_bin_centers(_UpperCAmelCase  )
       return (
           torch.sum(aligned_distance_error_probs * bin_centers   ,dim=-1  ),
           bin_centers[-1],
       )


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     int = 31   ,_UpperCAmelCase     :     int = 64   ,**_UpperCAmelCase     :     Dict   ,)  ->      Dict[str, torch.Tensor]:
       _a   :			Dict					 =torch.linspace(0   ,_UpperCAmelCase   ,steps=(no_bins - 1)   ,device=logits.device  )

       _a   :			int					 =torch.nn.functional.softmax(_UpperCAmelCase   ,dim=-1  )
       _a ,   _a   :			List[Any]					 =_calculate_expected_aligned_error(
           alignment_confidence_breaks=_UpperCAmelCase   ,aligned_distance_error_probs=_UpperCAmelCase   ,)

       return {
           "aligned_confidence_probs": aligned_confidence_probs,
           "predicted_aligned_error": predicted_aligned_error,
           "max_predicted_aligned_error": max_predicted_aligned_error,
       }


def      SCREAMING_SNAKE_CASE_ (  _UpperCAmelCase     :     torch.Tensor   ,_UpperCAmelCase     :     Optional[torch.Tensor] = None   ,_UpperCAmelCase     :     int = 31   ,_UpperCAmelCase     :     int = 64   ,_UpperCAmelCase     :     float = 1e-8   ,**_UpperCAmelCase     :     Optional[Any]   ,)  ->      torch.Tensor:
       if residue_weights is None:
              _a   :			Dict					 =logits.new_ones(logits.shape[-2]  )

       _a   :			str					 =torch.linspace(0   ,_UpperCAmelCase   ,steps=(no_bins - 1)   ,device=logits.device  )

       _a   :			Optional[int]					 =_calculate_bin_centers(_UpperCAmelCase  )
       torch.sum(_UpperCAmelCase  )
       _a   :			List[str]					 =logits.shape[-2]
       _a   :			List[Any]					 =max(_UpperCAmelCase   ,19  )

       _a   :			Union[str, Any]					 =1.2_4 * (clipped_n - 15) ** (1.0 / 3) - 1.8

       _a   :			Tuple					 =torch.nn.functional.softmax(_UpperCAmelCase   ,dim=-1  )

       _a   :			Dict					 =1.0 / (1 + (bin_centers**2) / (da**2))
       _a   :			int					 =torch.sum(probs * tm_per_bin   ,dim=-1  )

       _a   :			List[Any]					 =residue_weights / (eps + residue_weights.sum())
       _a   :			List[str]					 =torch.sum(predicted_tm_term * normed_residue_mask   ,dim=-1  )

       _a   :			int					 =per_alignment * residue_weights

       _a   :			List[Any]					 =(weighted == torch.max(_UpperCAmelCase  )).nonzero()[0]
       return per_alignment[tuple(_UpperCAmelCase  )]


