本文整理匯總了Python中copy.deepcopy方法的典型用法代碼示例。如果您正苦於以下問題:Python copy.deepcopy方法的具體用法?Python copy.deepcopy怎麽用?Python copy.deepcopy使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類copy
的用法示例。
在下文中一共展示了copy.deepcopy方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: money_trader_action
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def money_trader_action(agent):
dic1 = copy.deepcopy(agent["goods"])
ret = seek_a_trade(agent)
dic2 = copy.deepcopy(agent["goods"])
diff = {x: (dic1[x][AMT_AVAIL] - dic2[x][AMT_AVAIL])
for x in dic1 if x in dic2}
for good in diff:
# updated due to change in durability calculation
# decayed_amt = dic1[good][DUR_DECR] * dic1[good][AMT_AVAIL]
# if (diff[good] != decayed_amt and diff[good] != 0):
if diff[good] != 0:
incr_trade_count(good)
# print("TRADE COUNT")
# for good in natures_goods:
# print(good, " is traded ",
# natures_goods[good]["trade_count"], " times")
# good_decay(agent["goods"])
return ret
示例2: create_entr
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def create_entr(name, i, props=None):
"""
Create an agent.
"""
starting_cash = DEF_ENTR_CASH
if props is not None:
starting_cash = get_prop('entr_starting_cash',
DEF_ENTR_CASH)
resources = copy.deepcopy(DEF_CAP_WANTED)
if props is not None:
total_resources = get_prop('entr_want_resource_total',
DEF_TOTAL_RESOURCES_ENTR_WANT)
num_resources = len(resources)
for k in resources.keys():
resources[k] = int((total_resources * 2)
* (random.random() / num_resources))
return Agent(name + str(i), action=entr_action,
attrs={"cash": starting_cash,
"wants": resources,
"have": {}})
示例3: test_MutateAST_visit_read_only
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def test_MutateAST_visit_read_only(binop_file):
"""Read only test to ensure locations are aggregated."""
tree = Genome(binop_file).ast
mast = MutateAST(readonly=True)
testing_tree = deepcopy(tree)
mast.visit(testing_tree)
# four locations from the binary operations in binop_file
assert len(mast.locs) == 4
# tree should be unmodified
assert ast.dump(tree) == ast.dump(testing_tree)
####################################################################################################
# GENERIC TRANSFORMER NODE TESTS
# These represent the basic pattern for visiting a node in the MutateAST class and applying a
# mutation without running the full test suite against the cached files.
####################################################################################################
示例4: test_MutateAST_visit_augassign
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def test_MutateAST_visit_augassign(augassign_file, augassign_expected_locs):
"""Test mutation for AugAssign: +=, -=, /=, *=."""
tree = Genome(augassign_file).ast
test_mutation = "AugAssign_Div"
testing_tree = deepcopy(tree)
mutated_tree = MutateAST(target_idx=augassign_expected_locs[0], mutation=test_mutation).visit(
testing_tree
)
mast = MutateAST(readonly=True)
mast.visit(mutated_tree)
assert len(mast.locs) == 4
for loc in mast.locs:
# spot check on mutation from Add tp Div
if loc.lineno == 1 and loc.col_offset == 4:
assert loc.op_type == test_mutation
# spot check on not-mutated location still being Mult
if loc.lineno == 5 and loc.col_offset == 4:
assert loc.op_type == "AugAssign_Mult"
示例5: test_MutateAST_visit_boolop
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def test_MutateAST_visit_boolop(boolop_file, boolop_expected_loc):
"""Test mutation of AND to OR in the boolop."""
tree = Genome(boolop_file).ast
test_mutation = ast.Or
# apply the mutation to the original tree copy
testing_tree = deepcopy(tree)
mutated_tree = MutateAST(target_idx=boolop_expected_loc, mutation=test_mutation).visit(
testing_tree
)
# revisit in read-only mode to gather the locations of the new nodes
mast = MutateAST(readonly=True)
mast.visit(mutated_tree)
# four locations from the binary operations in binop_file
assert len(mast.locs) == 1
# there will only be one loc, but this still works
# basedon the col and line offset in the fixture for compare_expected_loc
for loc in mast.locs:
if loc.lineno == 2 and loc.col_offset == 11:
assert loc.op_type == test_mutation
示例6: test_MutateAST_visit_compare
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def test_MutateAST_visit_compare(idx, mut_op, lineno, compare_file, compare_expected_locs):
"""Test mutation of the == to != in the compare op."""
tree = Genome(compare_file).ast
# apply the mutation to the original tree copy
testing_tree = deepcopy(tree)
mutated_tree = MutateAST(target_idx=compare_expected_locs[idx], mutation=mut_op).visit(
testing_tree
)
# revisit in read-only mode to gather the locations of the new nodes
mast = MutateAST(readonly=True)
mast.visit(mutated_tree)
assert len(mast.locs) == 3
# check that the lineno marked for mutation is changed, otherwise original ops should
# still be present without modification
for loc in mast.locs:
if loc.lineno == lineno and loc.col_offset == 11:
assert loc.op_type == mut_op
else:
assert loc.op_type in {ast.Eq, ast.Is, ast.In} # based on compare_file fixture
示例7: test_MutateAST_visit_index_neg
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def test_MutateAST_visit_index_neg(
i_order, lineno, col_offset, mut, index_file, index_expected_locs
):
"""Test mutation for Index: i[0], i[1], i[-1]."""
tree = Genome(index_file).ast
test_mutation = mut
testing_tree = deepcopy(tree)
mutated_tree = MutateAST(target_idx=index_expected_locs[i_order], mutation=test_mutation).visit(
testing_tree
)
mast = MutateAST(readonly=True)
mast.visit(mutated_tree)
assert len(mast.locs) == 4
for loc in mast.locs:
# spot check on mutation from Index_NumNeg to Index_NumPos
if loc.lineno == lineno and loc.col_offset == col_offset:
assert loc.op_type == test_mutation
# spot check on not-mutated location still being None
if loc.lineno == 4 and loc.col_offset == 23:
assert loc.op_type == "Index_NumPos"
示例8: test_MutateAST_visit_nameconst
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def test_MutateAST_visit_nameconst(nameconst_file, nameconst_expected_locs):
"""Test mutation for nameconst: True, False, None."""
tree = Genome(nameconst_file).ast
test_mutation = False
testing_tree = deepcopy(tree)
mutated_tree = MutateAST(target_idx=nameconst_expected_locs[0], mutation=test_mutation).visit(
testing_tree
)
mast = MutateAST(readonly=True)
mast.visit(mutated_tree)
# if statement is included with this file that will be picked up
nc_locs = [loc for loc in mast.locs if loc.ast_class == "NameConstant"]
assert len(nc_locs) == 4
for loc in nc_locs:
# spot check on mutation from True to False
if loc.lineno == 1 and loc.col_offset == 14:
assert loc.op_type == test_mutation
# spot check on not-mutated location still being None
if loc.lineno == 7 and loc.col_offset == 22:
assert loc.op_type is None
示例9: __init__
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def __init__(self, args: dict={}):
self.meta = {}
self.args = deepcopy(args)
# since input-patterns can be used in many different kinds of io sources, grab it too.
self.input_patterns = args.get('input-patterns', '**/*')
if isinstance(self.input_patterns, str):
self.input_patterns = self.input_patterns.split(",")
self.samples_dir = args.get('samples-dir', 'samples')
self.cache_dir = args.get('cache-dir', '.cache')
self.random_seed = args.get('random-seed', 42)
self.trainings_dir = args.get('trainings-dir', './trainings')
self._cached_file_state = None
spltype, splval = parse_split(args.get('val-split', '10%'))
self.val_dir = splval if spltype == 'dir' else None
self.val_num = splval if spltype == 'num' else None
self.val_perc = splval if spltype == 'perc' else None
spltype, splval = parse_split(args.get('test-split', '10%'))
self.test_dir = splval if spltype == 'dir' else None
self.test_num = splval if spltype == 'num' else None
self.test_perc = splval if spltype == 'perc' else None
示例10: merge_dicts
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def merge_dicts(child_dict, parent_dict):
if child_dict is None:
return parent_dict
if parent_dict is None:
return child_dict
effective_dict = {}
try:
# Probably should handle non-string keys
use_keys = filter(lambda x: ("!" + x) not in child_dict.keys(),
parent_dict)
for k in use_keys:
effective_dict[k] = deepcopy(parent_dict[k])
use_keys = filter(lambda x: not x.startswith("!"), child_dict)
for k in use_keys:
effective_dict[k] = deepcopy(child_dict[k])
except TypeError:
raise TypeError("Error iterating dict argument")
return effective_dict
示例11: __new__
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def __new__(mcs, name, bases, attrs):
for b in bases:
if not hasattr(b, "_fields"):
continue
for k, v in b.__dict__.items():
if k in attrs:
continue
if isinstance(v, FieldDescriptor):
attrs[k] = copy.deepcopy(v.field)
mcs = super().__new__(mcs, name, bases, attrs)
mcs._fields = {}
for name, field in mcs.__dict__.items():
if isinstance(field, BaseField):
field.add_to_class(mcs, name)
return mcs
示例12: make_model
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def make_model(d_vocab, N, d_model, d_ff=1024, h=4, dropout=0.1):
"""Helper: Construct a model from hyperparameters."""
c = copy.deepcopy
attn = MultiHeadedAttention(h, d_model)
ff = PositionwiseFeedForward(d_model, d_ff, dropout)
position = PositionalEncoding(d_model, dropout)
model = EncoderDecoder(
Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N),
Decoder(DecoderLayer(d_model, c(attn), c(attn), c(ff), dropout), N),
nn.GRU(d_model, d_model, 1),
nn.Sequential(Embeddings(d_model, d_vocab), c(position)),
nn.Sequential(Embeddings(d_model, d_vocab), c(position)),
Generator(d_model, d_vocab),
d_model
)
# This was important from their code.
# Initialize parameters with Glorot / fan_avg.
for p in model.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
return model
示例13: make_model
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def make_model(d_vocab, N, d_model, latent_size, d_ff=1024, h=4, dropout=0.1):
"""Helper: Construct a model from hyperparameters."""
c = copy.deepcopy
attn = MultiHeadedAttention(h, d_model)
ff = PositionwiseFeedForward(d_model, d_ff, dropout)
position = PositionalEncoding(d_model, dropout)
share_embedding = Embeddings(d_model, d_vocab)
model = EncoderDecoder(
Encoder(EncoderLayer(d_model, c(attn), c(ff), dropout), N),
Decoder(DecoderLayer(d_model, c(attn), c(attn), c(ff), dropout), N),
# nn.Sequential(Embeddings(d_model, d_vocab), c(position)),
# nn.Sequential(Embeddings(d_model, d_vocab), c(position)),
nn.Sequential(share_embedding, c(position)),
nn.Sequential(share_embedding, c(position)),
Generator(d_model, d_vocab),
c(position),
d_model,
latent_size,
)
# This was important from their code.
# Initialize parameters with Glorot / fan_avg.
for p in model.parameters():
if p.dim() > 1:
nn.init.xavier_uniform_(p)
return model
示例14: update_generation_losses
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def update_generation_losses(losses, nums, micro, macro, bs, length, loss):
# Update Losses
losses[micro] += \
[copy.deepcopy(losses[micro][-1])]
losses[macro] += \
[copy.deepcopy(losses[macro][-1])]
losses[micro][-1] *= nums[micro]
losses[macro][-1] *= nums[macro]
nums[macro] += bs
if isinstance(length, int):
update_indiv_generation_losses(
losses, nums, micro, macro, bs, length, loss)
else:
update_tensor_generation_losses(
losses, nums, micro, macro, bs, length, loss)
示例15: turn
# 需要導入模塊: import copy [as 別名]
# 或者: from copy import deepcopy [as 別名]
def turn(self):
"""Turn"""
nt = copy.deepcopy(self.table)
for y in range(0, self.height):
for x in range(0, self.width):
neighbours = self.liveNeighbours(y, x)
if self.table[y][x] == 0:
if neighbours == 3:
nt[y][x] = 1
else:
if (neighbours < 2) or (neighbours > 3):
nt[y][x] = 0
self._oldStates.append(self.table)
if len(self._oldStates) > 3:
self._oldStates.popleft()
self.table = nt