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)
python类binary_repr()的实例源码
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 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 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
test_regression.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 38
收藏 0
点赞 0
评论 0
def test_binary_repr_0(self,level=rlevel):
# Ticket #151
assert_equal('0', np.binary_repr(0))
test_regression.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 42
收藏 0
点赞 0
评论 0
def test_binary_repr_0_width(self, level=rlevel):
assert_equal(np.binary_repr(0, width=3), '000')
test_numeric.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 52
收藏 0
点赞 0
评论 0
def test_zero(self):
assert_equal(np.binary_repr(0), '0')
test_numeric.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 31
收藏 0
点赞 0
评论 0
def test_large(self):
assert_equal(np.binary_repr(10736848), '101000111101010011010000')
test_numeric.py 文件源码
项目:PyDataLondon29-EmbarrassinglyParallelDAWithAWSLambda
作者: SignalMedia
项目源码
文件源码
阅读 39
收藏 0
点赞 0
评论 0
def test_negative(self):
assert_equal(np.binary_repr(-1), '-1')
assert_equal(np.binary_repr(-1, width=8), '11111111')
def test_binary_repr_0(self,level=rlevel):
# Ticket #151
assert_equal('0', np.binary_repr(0))