def put(a, ind, v, mode='raise'):
"""
Replaces specified elements of an array with given values.
The indexing works on the flattened target array. `put` is roughly
equivalent to:
::
a.flat[ind] = v
Parameters
----------
a : ndarray
Target array.
ind : array_like
Target indices, interpreted as integers.
v : array_like
Values to place in `a` at target indices. If `v` is shorter than
`ind` it will be repeated as necessary.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
* 'raise' -- raise an error (default)
* 'wrap' -- wrap around
* 'clip' -- clip to the range
'clip' mode means that all indices that are too large are replaced
by the index that addresses the last element along that axis. Note
that this disables indexing with negative numbers.
See Also
--------
putmask, place
Examples
--------
>>> a = np.arange(5)
>>> np.put(a, [0, 2], [-44, -55])
>>> a
array([-44, 1, -55, 3, 4])
>>> a = np.arange(5)
>>> np.put(a, 22, -5, mode='clip')
>>> a
array([ 0, 1, 2, 3, -5])
"""
return a.put(ind, v, mode)
python类put()的实例源码
def get_dataset(self, key, info=None, out=None, xslice=None, yslice=None):
"""Load a dataset
"""
if key in self.cache:
return self.cache[key]
# Type dictionary
typedict = {"af": "flash_accumulation",
"afa": "accumulated_flash_area",
"afr": "flash_radiance",
"lgr": "radiance",
"lef": "radiance",
"lfl": "radiance"}
# Get lightning data out of NetCDF container
logger.debug("Key: {}".format(key.name))
# Create reference grid
grid = np.full((self.nlines, self.ncols), np.NaN)
# Set slices to full disc extent
if xslice is None:
xslice = slice(0, self.ncols, None)
if yslice is None:
yslice = slice(0, self.nlines, None)
logger.debug("Slices - x: {}, y: {}".format(xslice, yslice))
# Get product values
values = self.nc[typedict[key.name]]
rows = self.nc['row']
cols = self.nc['column']
logger.debug('[ Number of values ] : {}'.format((len(values))))
logger.debug('[Min/Max] : <{}> / <{}>'.format(np.min(values),
np.max(values)))
# Convert xy coordinates to flatten indices
ids = np.ravel_multi_index([rows, cols], grid.shape)
# Replace NaN values with data
np.put(grid, ids, values)
# Correct for bottom left origin in LI row/column indices.
rotgrid = np.flipud(grid)
logger.debug('Data shape: {}, {}'.format(yslice, xslice))
# Rotate the grid by 90 degree clockwise
rotgrid = np.rot90(rotgrid, 3)
logger.warning("LI data has been rotated to fit to reference grid. \
Works only for test dataset")
# Slice the gridded lighting data
slicegrid = rotgrid[yslice, xslice]
# Mask invalid values
ds = np.ma.masked_where(np.isnan(slicegrid), slicegrid)
# Create dataset object
out.data[:] = np.ma.getdata(ds)
out.mask[:] = np.ma.getmask(ds)
out.info.update(key.to_dict())
return(out)
def get_stochastic_network_move(session, input_layer, output_layer, board_state, side,
valid_only=False, game_spec=None):
"""Choose a move for the given board_state using a stocastic policy. A move is selected using the values from the
output_layer as a categorical probability distribution to select a single move
Args:
session (tf.Session): Session used to run this network
input_layer (tf.Placeholder): Placeholder to the network used to feed in the board_state
output_layer (tf.Tensor): Tensor that will output the probabilities of the moves, we expect this to be of
dimesensions (None, board_squares) and the sum of values across the board_squares to be 1.
board_state: The board_state we want to get the move for.
side: The side that is making the move.
Returns:
(np.array) It's shape is (board_squares), and it is a 1 hot encoding for the move the network has chosen.
"""
np_board_state = np.array(board_state)
if side == -1:
np_board_state = -np_board_state
np_board_state = np_board_state.reshape(1, *input_layer.get_shape().as_list()[1:])
probability_of_actions = session.run(output_layer,
feed_dict={input_layer: np_board_state})[0]
if valid_only:
available_moves = list(game_spec.available_moves(board_state))
if len(available_moves) == 1:
move = np.zeros(game_spec.board_squares())
np.put(move, game_spec.tuple_move_to_flat(available_moves[0]), 1)
return move
available_moves_flat = [game_spec.tuple_move_to_flat(x) for x in available_moves]
for i in range(game_spec.board_squares()):
if i not in available_moves_flat:
probability_of_actions[i] = 0.
prob_mag = sum(probability_of_actions)
if prob_mag != 0.:
probability_of_actions /= sum(probability_of_actions)
try:
move = np.random.multinomial(1, probability_of_actions)
except ValueError:
# sometimes because of rounding errors we end up with probability_of_actions summing to greater than 1.
# so need to reduce slightly to be a valid value
move = np.random.multinomial(1, probability_of_actions / (1. + 1e-6))
return move
def put(a, ind, v, mode='raise'):
"""
Replaces specified elements of an array with given values.
The indexing works on the flattened target array. `put` is roughly
equivalent to:
::
a.flat[ind] = v
Parameters
----------
a : ndarray
Target array.
ind : array_like
Target indices, interpreted as integers.
v : array_like
Values to place in `a` at target indices. If `v` is shorter than
`ind` it will be repeated as necessary.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
* 'raise' -- raise an error (default)
* 'wrap' -- wrap around
* 'clip' -- clip to the range
'clip' mode means that all indices that are too large are replaced
by the index that addresses the last element along that axis. Note
that this disables indexing with negative numbers.
See Also
--------
putmask, place
Examples
--------
>>> a = np.arange(5)
>>> np.put(a, [0, 2], [-44, -55])
>>> a
array([-44, 1, -55, 3, 4])
>>> a = np.arange(5)
>>> np.put(a, 22, -5, mode='clip')
>>> a
array([ 0, 1, 2, 3, -5])
"""
try:
put = a.put
except AttributeError:
raise TypeError("argument 1 must be numpy.ndarray, "
"not {name}".format(name=type(a).__name__))
return put(ind, v, mode)
def put(a, ind, v, mode='raise'):
"""
Replaces specified elements of an array with given values.
The indexing works on the flattened target array. `put` is roughly
equivalent to:
::
a.flat[ind] = v
Parameters
----------
a : ndarray
Target array.
ind : array_like
Target indices, interpreted as integers.
v : array_like
Values to place in `a` at target indices. If `v` is shorter than
`ind` it will be repeated as necessary.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
* 'raise' -- raise an error (default)
* 'wrap' -- wrap around
* 'clip' -- clip to the range
'clip' mode means that all indices that are too large are replaced
by the index that addresses the last element along that axis. Note
that this disables indexing with negative numbers.
See Also
--------
putmask, place
Examples
--------
>>> a = np.arange(5)
>>> np.put(a, [0, 2], [-44, -55])
>>> a
array([-44, 1, -55, 3, 4])
>>> a = np.arange(5)
>>> np.put(a, 22, -5, mode='clip')
>>> a
array([ 0, 1, 2, 3, -5])
"""
try:
put = a.put
except AttributeError:
raise TypeError("argument 1 must be numpy.ndarray, "
"not {name}".format(name=type(a).__name__))
return put(ind, v, mode=mode)
def handle(self):
data = self.request[0].strip()
data_length = len(data)
# check packet start byte 0x9C
if not data_length >= 8 and data[0] == 0x9c:
return
packet_type = data[1]
frame_size = (data[2] << 8) + data[3]
# check consistency of length and proper frame ending
if not (data_length - 7 == frame_size) and data[-1] == 0x36:
return
packet_number = data[4]
number_of_packets = data[5]
if packet_type == 0xDA: # data frame
# tell ribbapi that tpm2_net data is received
self.server.ribbapi.receiving_data.set()
self.server.update_time()
if packet_number == 0:
self.server.misbehaving = True
if packet_number == (1 if not self.server.misbehaving else 0):
self.server.tmp_buffer_index = 0
upper = min(self.server.tmp_buffer.size,
self.server.tmp_buffer_index + frame_size)
arange = np.arange(self.server.tmp_buffer_index,
upper)
np.put(self.server.tmp_buffer, arange, list(data[6:-1]))
self.server.tmp_buffer_index = self.server.tmp_buffer_index + frame_size
if packet_number == (number_of_packets if not self.server.misbehaving else number_of_packets - 1):
if not self.server.ribbapi.current_animation:
self.server.ribbapi.frame_queue.put(self.server.tmp_buffer.copy())
elif data[1] == 0xC0: # command
# NOT IMPLEMENTED
return
elif data[1] == 0xAA: # request response
# NOT IMPLEMENTED
return
else: # no valid tmp2 packet type
return
def put(a, ind, v, mode='raise'):
"""
Replaces specified elements of an array with given values.
The indexing works on the flattened target array. `put` is roughly
equivalent to:
::
a.flat[ind] = v
Parameters
----------
a : ndarray
Target array.
ind : array_like
Target indices, interpreted as integers.
v : array_like
Values to place in `a` at target indices. If `v` is shorter than
`ind` it will be repeated as necessary.
mode : {'raise', 'wrap', 'clip'}, optional
Specifies how out-of-bounds indices will behave.
* 'raise' -- raise an error (default)
* 'wrap' -- wrap around
* 'clip' -- clip to the range
'clip' mode means that all indices that are too large are replaced
by the index that addresses the last element along that axis. Note
that this disables indexing with negative numbers.
See Also
--------
putmask, place
Examples
--------
>>> a = np.arange(5)
>>> np.put(a, [0, 2], [-44, -55])
>>> a
array([-44, 1, -55, 3, 4])
>>> a = np.arange(5)
>>> np.put(a, 22, -5, mode='clip')
>>> a
array([ 0, 1, 2, 3, -5])
"""
try:
put = a.put
except AttributeError:
raise TypeError("argument 1 must be numpy.ndarray, "
"not {name}".format(name=type(a).__name__))
return put(ind, v, mode)