Python numpy.binary_repr() Examples
The following are 30
code examples of numpy.binary_repr().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: decimal_to_binary.py From qiskit-aqua with Apache License 2.0 | 6 votes |
def decimal_to_binary(decimal_val, max_num_digits=20, fractional_part_only=False): """ decimal to binary """ decimal_val_fractional_part = abs(decimal_val - int(decimal_val)) current_binary_position_val = 1 / 2 binary_fractional_part_digits = [] while decimal_val_fractional_part >= 0 and len(binary_fractional_part_digits) < max_num_digits: if decimal_val_fractional_part >= current_binary_position_val: binary_fractional_part_digits.append('1') decimal_val_fractional_part -= current_binary_position_val else: binary_fractional_part_digits.append('0') current_binary_position_val /= 2 binary_repr_fractional_part = ''.join(binary_fractional_part_digits) if fractional_part_only: return binary_repr_fractional_part else: return binary_repr(int(decimal_val)) + '.' + binary_repr_fractional_part
Example #2
Source File: grover.py From grove with Apache License 2.0 | 6 votes |
def _compute_grover_oracle_matrix(bitstring_map: Dict[str, int]) -> np.ndarray: """ Computes the unitary matrix that encodes the oracle function for Grover's algorithm :param bitstring_map: dict with string keys corresponding to bitstrings, and integer values corresponding to the desired phase on the output state. :return: a numpy array corresponding to the unitary matrix for oracle for the given bitstring_map """ n_bits = len(list(bitstring_map.keys())[0]) oracle_matrix = np.zeros(shape=(2 ** n_bits, 2 ** n_bits)) for b in range(2 ** n_bits): pad_str = np.binary_repr(b, n_bits) phase_factor = bitstring_map[pad_str] oracle_matrix[b, b] = phase_factor return oracle_matrix
Example #3
Source File: test_set_packing.py From qiskit-aqua with Apache License 2.0 | 6 votes |
def _brute_force(self): # brute-force way: try every possible assignment! def bitfield(n, length): result = np.binary_repr(n, length) return [int(digit) for digit in result] # [2:] to chop off the "0b" part subsets = len(self.list_of_subsets) maximum = 2 ** subsets max_v = -np.inf for i in range(maximum): cur = bitfield(i, subsets) cur_v = set_packing.check_disjoint(cur, self.list_of_subsets) if cur_v: if np.count_nonzero(cur) > max_v: max_v = np.count_nonzero(cur) return max_v
Example #4
Source File: test_graph_partition.py From qiskit-aqua with Apache License 2.0 | 6 votes |
def _brute_force(self): # use the brute-force way to generate the oracle def bitfield(n, length): result = np.binary_repr(n, length) return [int(digit) for digit in result] # [2:] to chop off the "0b" part nodes = self.num_nodes maximum = 2 ** nodes minimal_v = np.inf for i in range(maximum): cur = bitfield(i, nodes) how_many_nonzero = np.count_nonzero(cur) if how_many_nonzero * 2 != nodes: # not balanced continue cur_v = graph_partition.objective_value(np.array(cur), self.w) if cur_v < minimal_v: minimal_v = cur_v return minimal_v
Example #5
Source File: test_vertex_cover.py From qiskit-aqua with Apache License 2.0 | 6 votes |
def _brute_force(self): # brute-force way def bitfield(n, length): result = np.binary_repr(n, length) return [int(digit) for digit in result] # [2:] to chop off the "0b" part nodes = self.num_nodes maximum = 2 ** nodes minimal_v = np.inf for i in range(maximum): cur = bitfield(i, nodes) cur_v = vertex_cover.check_full_edge_coverage(np.array(cur), self.w) if cur_v: nonzerocount = np.count_nonzero(cur) if nonzerocount < minimal_v: minimal_v = nonzerocount return minimal_v
Example #6
Source File: test_exact_cover.py From qiskit-aqua with Apache License 2.0 | 6 votes |
def _brute_force(self): # brute-force way: try every possible assignment! has_sol = False def bitfield(n, length): result = np.binary_repr(n, length) return [int(digit) for digit in result] # [2:] to chop off the "0b" part subsets = len(self.list_of_subsets) maximum = 2 ** subsets for i in range(maximum): cur = bitfield(i, subsets) cur_v = exact_cover.check_solution_satisfiability(cur, self.list_of_subsets) if cur_v: has_sol = True break return has_sol
Example #7
Source File: test_simon.py From qiskit-aqua with Apache License 2.0 | 6 votes |
def test_simon(self, simon_input, mct_mode, optimization, simulator): """ Simon test """ # find the two keys that have matching values nbits = int(math.log(len(simon_input[0]), 2)) vals = list(zip(*simon_input))[::-1] def find_pair(): for i, val in enumerate(vals): for j in range(i + 1, len(vals)): if val == vals[j]: return i, j return 0, 0 k_1, k_2 = find_pair() hidden = np.binary_repr(k_1 ^ k_2, nbits) backend = BasicAer.get_backend(simulator) oracle = TruthTableOracle(simon_input, optimization=optimization, mct_mode=mct_mode) algorithm = Simon(oracle) quantum_instance = QuantumInstance(backend) result = algorithm.run(quantum_instance=quantum_instance) # print(result['circuit'].draw(line_length=10000)) self.assertEqual(result['result'], hidden)
Example #8
Source File: simon.py From qiskit-aqua with Apache License 2.0 | 6 votes |
def _run(self): if self._quantum_instance.is_statevector: qc = self.construct_circuit(measurement=False) result = self._quantum_instance.execute(qc) complete_state_vec = result.get_statevector(qc) variable_register_density_matrix = get_subsystem_density_matrix( complete_state_vec, range(len(self._oracle.variable_register), qc.width()) ) variable_register_density_matrix_diag = np.diag(variable_register_density_matrix) measurements = { np.binary_repr(idx, width=len(self._oracle.variable_register)): abs(variable_register_density_matrix_diag[idx]) ** 2 for idx in range(len(variable_register_density_matrix_diag)) if not variable_register_density_matrix_diag[idx] == 0 } else: qc = self.construct_circuit(measurement=True) measurements = self._quantum_instance.execute(qc).get_counts(qc) self._ret['result'] = self._interpret_measurement(measurements) return self._ret
Example #9
Source File: test_numeric.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def test_zero(self): assert_equal(np.binary_repr(0), '0')
Example #10
Source File: test_regression.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def test_binary_repr_0(self): # Ticket #151 assert_equal('0', np.binary_repr(0))
Example #11
Source File: test_numeric.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def test_positive(self): assert_equal(np.binary_repr(10), '1010') assert_equal(np.binary_repr(12522), '11000011101010') assert_equal(np.binary_repr(10736848), '101000111101010011010000')
Example #12
Source File: deutsch_jozsa.py From qiskit-aqua with Apache License 2.0 | 5 votes |
def _run(self): if self._quantum_instance.is_statevector: qc = self.construct_circuit(measurement=False) result = self._quantum_instance.execute(qc) complete_state_vec = result.get_statevector(qc) variable_register_density_matrix = get_subsystem_density_matrix( complete_state_vec, range(len(self._oracle.variable_register), qc.width()) ) variable_register_density_matrix_diag = np.diag(variable_register_density_matrix) max_amplitude = max( variable_register_density_matrix_diag.min(), variable_register_density_matrix_diag.max(), key=abs ) max_amplitude_idx = \ np.where(variable_register_density_matrix_diag == max_amplitude)[0][0] top_measurement = np.binary_repr(max_amplitude_idx, len(self._oracle.variable_register)) else: qc = self.construct_circuit(measurement=True) measurement = self._quantum_instance.execute(qc).get_counts(qc) self._ret['measurement'] = measurement top_measurement = max(measurement.items(), key=operator.itemgetter(1))[0] self._ret['result'] = 'constant' if int(top_measurement) == 0 else 'balanced' return self._ret
Example #13
Source File: test_numeric.py From pySINDy with MIT License | 5 votes |
def test_positive(self): assert_equal(np.binary_repr(10), '1010') assert_equal(np.binary_repr(12522), '11000011101010') assert_equal(np.binary_repr(10736848), '101000111101010011010000')
Example #14
Source File: test_numeric.py From pySINDy with MIT License | 5 votes |
def test_zero(self): assert_equal(np.binary_repr(0), '0')
Example #15
Source File: test_deprecations.py From pySINDy with MIT License | 5 votes |
def test_insufficient_width_negative(self): args = (-5,) kwargs = {'width': 2} self.message = ("Insufficient bit width provided. This behavior " "will raise an error in the future.") self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
Example #16
Source File: test_deprecations.py From pySINDy with MIT License | 5 votes |
def test_insufficient_width_positive(self): args = (10,) kwargs = {'width': 2} self.message = ("Insufficient bit width provided. This behavior " "will raise an error in the future.") self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
Example #17
Source File: __init__.py From cupy with MIT License | 5 votes |
def binary_repr(num, width=None): """Return the binary representation of the input number as a string. .. seealso:: :func:`numpy.binary_repr` """ return numpy.binary_repr(num, width) # ----------------------------------------------------------------------------- # Data type routines (borrowed from NumPy) # -----------------------------------------------------------------------------
Example #18
Source File: bernstein_vazirani.py From qiskit-aqua with Apache License 2.0 | 5 votes |
def _run(self): if self._quantum_instance.is_statevector: qc = self.construct_circuit(measurement=False) result = self._quantum_instance.execute(qc) complete_state_vec = result.get_statevector(qc) variable_register_density_matrix = get_subsystem_density_matrix( complete_state_vec, range(len(self._oracle.variable_register), qc.width()) ) variable_register_density_matrix_diag = np.diag(variable_register_density_matrix) max_amplitude = max( variable_register_density_matrix_diag.min(), variable_register_density_matrix_diag.max(), key=abs ) max_amplitude_idx = \ np.where(variable_register_density_matrix_diag == max_amplitude)[0][0] top_measurement = np.binary_repr(max_amplitude_idx, len(self._oracle.variable_register)) else: qc = self.construct_circuit(measurement=True) measurement = self._quantum_instance.execute(qc).get_counts(qc) self._ret['measurement'] = measurement top_measurement = max(measurement.items(), key=operator.itemgetter(1))[0] self._ret['result'] = top_measurement return self._ret
Example #19
Source File: test_regression.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def test_binary_repr_0_width(self): assert_equal(np.binary_repr(0, width=3), '000')
Example #20
Source File: test_deprecations.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def test_insufficient_width_negative(self): args = (-5,) kwargs = {'width': 2} self.message = ("Insufficient bit width provided. This behavior " "will raise an error in the future.") self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
Example #21
Source File: test_deprecations.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def test_insufficient_width_positive(self): args = (10,) kwargs = {'width': 2} self.message = ("Insufficient bit width provided. This behavior " "will raise an error in the future.") self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
Example #22
Source File: amplitude_measurement.py From grove with Apache License 2.0 | 5 votes |
def measure_wf_coefficients(prep_program, coeff_list, reference_state, quantum_resource, variance_bound=1.0E-6): """ Measure a set of coefficients with a phase relative to the reference_state :param prep_program: pyQuil program to prepare the state :param coeff_list: list of integers labeling amplitudes to measure :param reference_state: Integer of the computational basis state to use as a reference :param quantum_resource: An instance of a quantum abstract machine :param variance_bound: Default 1.0E-6. variance of the monte carlo estimator for the non-hermitian operator :return: returns a list of reference_state amplitude + coeff_list amplitudes """ num_qubits = len(prep_program.get_qubits()) normalizer_ops = projector_generator(reference_state, reference_state) c0_coeff, _, _ = estimate_locally_commuting_operator( prep_program, normalizer_ops, variance_bound=variance_bound, quantum_resource=quantum_resource) c0_coeff = np.sqrt(c0_coeff) amplitudes = [] for ii in coeff_list: if ii == reference_state: amplitudes.append(c0_coeff) else: bra = list(map(int, np.binary_repr(ii, width=num_qubits))) c_ii_op = projector_generator(reference_state, bra) result = estimate_locally_commuting_operator( prep_program, c_ii_op, variance_bound=variance_bound, quantum_resource=quantum_resource) amplitudes.append(result[0] / c0_coeff) return amplitudes
Example #23
Source File: bernstein_vazirani.py From grove with Apache License 2.0 | 5 votes |
def create_bv_bitmap(dot_product_vector: str, dot_product_bias: str) -> Dict[str, str]: """ This function creates a map from bitstring to function value for a boolean formula :math:`f` with a dot product vector :math:`a` and a dot product bias :math:`b` .. math:: f:\\{0,1\\}^n\\rightarrow \\{0,1\\} \\mathbf{x}\\rightarrow \\mathbf{a}\\cdot\\mathbf{x}+b\\pmod{2} (\\mathbf{a}\\in\\{0,1\\}^n, b\\in\\{0,1\\}) :param dot_product_vector: a string of 0's and 1's that represents the dot-product partner in :math:`f` :param dot_product_bias: 0 or 1 as a string representing the bias term in :math:`f` :return: A dictionary containing all possible bitstring of length equal to :math:`a` and the function value :math:`f` """ n_bits = len(dot_product_vector) bit_map = {} for bit_val in range(2 ** n_bits): bit_map[np.binary_repr(bit_val, width=n_bits)] = str( (int(utils.bitwise_dot_product(np.binary_repr(bit_val, width=n_bits), dot_product_vector)) + int(dot_product_bias, 2)) % 2 ) return bit_map
Example #24
Source File: test_regression.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_binary_repr_0_width(self): assert_equal(np.binary_repr(0, width=3), '000')
Example #25
Source File: test_regression.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_binary_repr_0(self): # Ticket #151 assert_equal('0', np.binary_repr(0))
Example #26
Source File: test_numeric.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_neg_width_boundaries(self): # see gh-8670 # Ensure that the example in the issue does not # break before proceeding to a more thorough test. assert_equal(np.binary_repr(-128, width=8), '10000000') for width in range(1, 11): num = -2**(width - 1) exp = '1' + (width - 1) * '0' assert_equal(np.binary_repr(num, width=width), exp)
Example #27
Source File: test_numeric.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_sufficient_width(self): assert_equal(np.binary_repr(0, width=5), '00000') assert_equal(np.binary_repr(10, width=7), '0001010') assert_equal(np.binary_repr(-5, width=7), '1111011')
Example #28
Source File: test_numeric.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_zero(self): assert_equal(np.binary_repr(0), '0')
Example #29
Source File: test_deprecations.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_insufficient_width_negative(self): args = (-5,) kwargs = {'width': 2} self.message = ("Insufficient bit width provided. This behavior " "will raise an error in the future.") self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)
Example #30
Source File: test_deprecations.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def test_insufficient_width_positive(self): args = (10,) kwargs = {'width': 2} self.message = ("Insufficient bit width provided. This behavior " "will raise an error in the future.") self.assert_deprecated(np.binary_repr, args=args, kwargs=kwargs)