我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用numpy.binary_repr()。
def set_value(self, value: int) -> None: value = self.bounds(value) # automatically performs 2s comp if needed binary = np.binary_repr(value, width=8) self.values = np.array(list(binary), dtype=np.uint8)
def calc_sent_loss(sent): # Create a computation graph dy.renew_cg() W_c = dy.parameter(W_c_p) # Get embeddings for the sentence emb = [W_w_p[x] for x in sent] # Step through the sentence and calculate binary prediction losses all_losses = [] for i, my_emb in enumerate(emb): scores = dy.logistic(W_c * my_emb) pos_words = ([sent[x] if x >= 0 else S for x in range(i-N,i)] + [sent[x] if x < len(sent) else S for x in range(i+1,i+N+1)]) word_repr = [[float(y) for y in np.binary_repr(x).zfill(nbits)] for x in pos_words] word_repr = [dy.inputVector(x) for x in word_repr] all_losses.extend([dy.binary_log_loss(scores, x) for x in word_repr]) return dy.esum(all_losses)
def _compute_grover_oracle_matrix(bitstring_map): """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. :type bitstring_map: Dict[String, Int] :return: a numpy array corresponding to the unitary matrix for oracle for the given bitstring_map :rtype: numpy.ndarray """ 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
def get_key_bounds(self, level, cell_iarr): """ Get index keys for index file supplied. level: int Requested level cell_iarr: array-like, length 3 Requested cell from given level. Returns: lmax_lk, lmax_rk """ shift = self.level-level level_buff = 0 level_lk = self.get_key(cell_iarr + level_buff) level_rk = self.get_key(cell_iarr + level_buff) + 1 lmax_lk = (level_lk << shift*3) lmax_rk = (((level_rk) << shift*3) -1) #print "Level ", level, np.binary_repr(level_lk, width=self.level*3), np.binary_repr(level_rk, width=self.level*3) #print "Level ", self.level, np.binary_repr(lmax_lk, width=self.level*3), np.binary_repr(lmax_rk, width=self.level*3) return lmax_lk, lmax_rk
def find_all_subsets(s): """ find all subsets of a set, except for the empty set :param s: a set represented by a list :return: a list of subsets """ subsets = [] N = np.power(2,len(s)) for n in range(N-1): # each number represent a subset set = [] # the subset corresponding to n binary_ind = np.binary_repr(n+1) # binary for idx in range(1,len(binary_ind)+1): # each bit of the binary number if binary_ind[-idx] == '1': # '1' means to add the element corresponding to that bit set.append(s[-idx]) subsets.append(set) return subsets
def main(): import numpy.random as random from trace import trace import sys if len(sys.argv) == 1: sys.exit("{} [directory]".format(sys.argv[0])) directory = sys.argv[1] directory_ad = "{}_ad/".format(directory) discriminator = Discriminator(directory_ad).load() name = "generated_actions.csv" N = discriminator.net.input_shape[1] lowbit = 20 highbit = N - lowbit print("batch size: {}".format(2**lowbit)) xs = (((np.arange(2**lowbit )[:,None] & (1 << np.arange(N)))) > 0).astype(int) # xs_h = (((np.arange(2**highbit)[:,None] & (1 << np.arange(highbit)))) > 0).astype(int) try: print(discriminator.local(name)) with open(discriminator.local(name), 'wb') as f: for i in range(2**highbit): print("Iteration {}/{} base: {}".format(i,2**highbit,i*(2**lowbit)), end=' ') # h = np.binary_repr(i*(2**lowbit), width=N) # print(h) # xs_h = np.unpackbits(np.array([i*(2**lowbit)],dtype=int)) xs_h = (((np.array([i])[:,None] & (1 << np.arange(highbit)))) > 0).astype(int) xs[:,lowbit:] = xs_h # print(xs_h) # print(xs[:10]) ys = discriminator.discriminate(xs,batch_size=100000) ind = np.where(ys > 0.5) valid_xs = xs[ind] print(len(valid_xs)) np.savetxt(f,valid_xs,"%d") except KeyboardInterrupt: print("dump stopped")
def test_binary_repr_0(self,level=rlevel): # Ticket #151 assert_equal('0', np.binary_repr(0))
def test_binary_repr_0_width(self, level=rlevel): assert_equal(np.binary_repr(0, width=3), '000')
def test_zero(self): assert_equal(np.binary_repr(0), '0')
def test_large(self): assert_equal(np.binary_repr(10736848), '101000111101010011010000')
def test_negative(self): assert_equal(np.binary_repr(-1), '-1') assert_equal(np.binary_repr(-1, width=8), '11111111')
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) # -----------------------------------------------------------------------------
def create_bv_bitmap(dot_product_vector, dot_product_bias): """ 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 String dot_product_vector: a string of 0's and 1's that represents the dot-product partner in :math:`f` :param String 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` :rtype: Dict[String, String] """ 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
def _compute_unitary_oracle_matrix(bitstring_map): """ Computes the unitary matrix that encodes the orcale function for Simon's algorithm :param Dict[String, String] bitstring_map: truth-table of the input bitstring map in dictionary format :return: a dense matrix containing the permutation of the bit strings and a dictionary containing the indices of the non-zero elements of the computed permutation matrix as key-value-pairs :rtype: Tuple[2darray, Dict[String, String]] """ n_bits = len(list(bitstring_map.keys())[0]) # We instantiate an empty matrix of size 2 * n_bits to encode the mapping from n qubits # to n ancillas, which explains the factor 2 overhead. # To construct the matrix we go through all possible state transitions and pad the index # according to all possible states the ancilla-subsystem could be in ufunc = np.zeros(shape=(2 ** (2 * n_bits), 2 ** (2 * n_bits))) index_mapping_dct = defaultdict(dict) for b in range(2**n_bits): # padding according to ancilla state pad_str = np.binary_repr(b, n_bits) for k, v in bitstring_map.items(): # add mapping from initial state to the state in the ancilla system. # pad_str corresponds to the initial state of the ancilla system. index_mapping_dct[pad_str + k] = utils.bitwise_xor(pad_str, v) + k # calculate matrix indices that correspond to the transition-matrix-element # of the oracle unitary i, j = int(pad_str+k, 2), int(utils.bitwise_xor(pad_str, v) + k, 2) ufunc[i, j] = 1 return ufunc, index_mapping_dct
def index_2_bit(state_index, num_bits): """Returns bit string corresponding to quantum state index Args: state_index : basis index of a quantum state num_bits : the number of bits in the returned string Returns: A integer array with the binary representation of state_index """ return np.array([int(c) for c in np.binary_repr(state_index, num_bits)[::-1]], dtype=np.uint8)
def get_node(self, nodeid): path = np.binary_repr(nodeid) depth = 1 temp = self.tree.trunk for depth in range(1, len(path)): if path[depth] == '0': temp = temp.left else: temp = temp.right assert(temp is not None) return temp
def get_key_slow(self, iarr, level=None): if level is None: level = self.level i1, i2, i3 = iarr rep1 = np.binary_repr(i1, width=self.level) rep2 = np.binary_repr(i2, width=self.level) rep3 = np.binary_repr(i3, width=self.level) inter = np.zeros(self.level*3, dtype='c') inter[self.dim_slices[0]] = rep1 inter[self.dim_slices[1]] = rep2 inter[self.dim_slices[2]] = rep3 return int(inter.tostring(), 2)
def get_slice_key(self, ind, dim='r'): slb = np.binary_repr(ind, width=self.level) expanded = np.array([0]*self.level*3, dtype='c') expanded[self.dim_slices[dim]] = slb return int(expanded.tostring(), 2)
def get_ind_from_key(self, key, dim='r'): ind = [0,0,0] br = np.binary_repr(key, width=self.level*3) for dim in range(3): ind[dim] = int(br[self.dim_slices[dim]],2) return ind
def Bin(a,N): a_bin = np.binary_repr(a) while len(a_bin) < N: a_bin = '0'+a_bin return a_bin
def test_binary_repr_0(self, level=rlevel): # Ticket #151 assert_equal('0', np.binary_repr(0))
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')
def test_negative(self): assert_equal(np.binary_repr(-1), '-1') assert_equal(np.binary_repr(-10), '-1010') assert_equal(np.binary_repr(-12522), '-11000011101010') assert_equal(np.binary_repr(-10736848), '-101000111101010011010000')
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)
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)
def _getAllowedShapes(self, shape): ''' Return set of allowed shapes that can be squeezed into given shape. Examples -------- >>> PB = ParamBag() # fixing K,D doesn't matter >>> PB._getAllowedShapes(()) set([()]) >>> PB._getAllowedShapes((1,)) set([(), (1,)]) >>> aSet = PB._getAllowedShapes((23,)) >>> sorted(aSet) [(23,)] >>> sorted(PB._getAllowedShapes((3,1))) [(3,), (3, 1)] >>> sorted(PB._getAllowedShapes((1,1))) [(), (1,), (1, 1)] ''' assert isinstance(shape, tuple) allowedShapes = set() if len(shape) == 0: allowedShapes.add(tuple()) return allowedShapes shapeVec = np.asarray(shape, dtype=np.int32) onesMask = shapeVec == 1 keepMask = np.logical_not(onesMask) nOnes = sum(onesMask) for b in range(2**nOnes): bStr = np.binary_repr(b) bStr = '0' * (nOnes - len(bStr)) + bStr keepMask[onesMask] = np.asarray([int(x) > 0 for x in bStr]) curShape = shapeVec[keepMask] allowedShapes.add(tuple(curShape)) return allowedShapes
def _get_contrast_indices(effect_idx, n_factors): """Henson's factor coding, see num2binvec""" binrepr = np.binary_repr(effect_idx, n_factors) return np.array([int(i) for i in binrepr], dtype=int)
def activate_network(self, num_activations=1): """Activates the Markov Network Parameters ---------- num_activations: int (default: 1) The number of times the Markov Network should be activated Returns ------- None """ original_input_values = np.copy(self.states[:self.num_input_states]) for _ in range(num_activations): for markov_gate, mg_input_ids, mg_output_ids in zip(self.markov_gates, self.markov_gate_input_ids, self.markov_gate_output_ids): # Determine the input values for this Markov Gate mg_input_values = self.states[mg_input_ids] mg_input_index = int(''.join([str(int(val)) for val in mg_input_values]), base=2) # Determine the corresponding output values for this Markov Gate roll = np.random.uniform() mg_output_index = np.where(markov_gate[mg_input_index, :] >= roll)[0][0] mg_output_values = np.array(list(np.binary_repr(mg_output_index, width=len(mg_output_ids))), dtype=np.uint8) self.states[mg_output_ids] = np.bitwise_or(self.states[mg_output_ids], mg_output_values) self.states[:self.num_input_states] = original_input_values