本文整理汇总了Python中random.getstate函数的典型用法代码示例。如果您正苦于以下问题:Python getstate函数的具体用法?Python getstate怎么用?Python getstate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了getstate函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: __init__
def __init__(self, data: Dict[str, List[Tuple[Any, Any]]],
seed: int = None, shuffle: bool = True,
*args, **kwargs) -> None:
r""" Dataiterator takes a dict with fields 'train', 'test', 'valid'. A list of samples (pairs x, y) is stored
in each field.
Args:
data: list of (x, y) pairs. Each pair is a sample from the dataset. x as well as y can be a tuple
of different input features.
seed (int): random seed for data shuffling. Defaults to None
shuffle: whether to shuffle data when batching (from config)
"""
self.shuffle = shuffle
rs = random.getstate()
random.seed(seed)
self.random_state = random.getstate()
random.setstate(rs)
self.train = data.get('train', [])
self.valid = data.get('valid', [])
self.test = data.get('test', [])
self.split(*args, **kwargs)
self.data = {
'train': self.train,
'valid': self.valid,
'test': self.test,
'all': self.train + self.test + self.valid
}
示例2: __call__
def __call__(self):
random.setstate(self.randstate)
if self.game.day < 0:
return True
if self.state.winner() is not None:
self.game.day = -1
self.game.save()
return True
a = [None for i in xrange(len(self.players))]
if not self.read_actions(a) and time.time() < self.game.countdown:
return False
if self.game.phase == qwr.PHASE_NIGHT:
self.apply(a)
self.state += 1
self.game.day = self.state.day
self.game.phase = qwr.PHASE_DAY
self.game.countdown = int(time.time()) + (1000000 if self.game.limit_day is None else self.game.limit_day)
self.game.save()
self.randstate = random.getstate()
return False
if not self.lynch(a):
self.game.phase += 1
self.game.countdown = int(time.time()) + (1000000 if self.game.limit_day is None else self.game.limit_day)
self.game.save()
return False
self.game.phase = qwr.PHASE_NIGHT
self.game.countdown = int(time.time()) + (1000000 if self.game.limit_night is None else self.game.limit_night)
self.game.save()
self.randstate = random.getstate()
return False
示例3: batch_generator
def batch_generator(self, batch_size: int, data_type: str = 'train',
shuffle: bool = None) -> Generator:
r"""This function returns a generator, which serves for generation of raw
(no preprocessing such as tokenization)
batches
Args:
batch_size (int): number of samples in batch
data_type (str): can be either 'train', 'test', or 'valid'
shuffle (bool): whether to shuffle dataset before batching
Returns:
batch_gen (Generator): a generator, that iterates through the part (defined by data_type) of the dataset
"""
if shuffle is None:
shuffle = self.shuffle
data = self.data[data_type]
data_len = len(data)
order = list(range(data_len))
if shuffle:
rs = random.getstate()
random.setstate(self.random_state)
random.shuffle(order)
self.random_state = random.getstate()
random.setstate(rs)
for i in range((data_len - 1) // batch_size + 1):
yield list(zip(*[data[o] for o in order[i * batch_size:(i + 1) * batch_size]]))
示例4: __init__
def __init__(self, data, seed=None, classes=None,
fields_to_merge=None, merged_field=None,
field_to_split=None, splitted_fields=None, splitting_proportions=None,
*args, **kwargs):
rs = random.getstate()
random.seed(seed)
self.random_state = random.getstate()
random.setstate(rs)
self.train = data.get('train', [])
self.test = data.get('test', [])
self.data = {
'train': self.train,
'test': self.test,
'all': self.train + self.test
}
self.classes = classes
if fields_to_merge is not None:
if merged_field is not None:
# print("Merging fields <<{}>> to new field <<{}>>".format(fields_to_merge, merged_field))
self._merge_data(fields_to_merge=fields_to_merge.split(' '), merged_field=merged_field)
else:
raise IOError("Given fields to merge BUT not given name of merged field")
if field_to_split is not None:
if splitted_fields is not None:
# print("Splitting field <<{}>> to new fields <<{}>>".format(field_to_split, splitted_fields))
self._split_data(field_to_split=field_to_split,
splitted_fields=splitted_fields.split(" "),
splitting_proportions=[float(s) for s in splitting_proportions.split(" ")])
else:
raise IOError("Given field to split BUT not given names of splitted fields")
示例5: determine_action
def determine_action(state, dict, random_state, score, max_score):
#print state
random.setstate(random_state[1])
state_click = dict.get((state, True), 0)
state_nothing = dict.get((state, False), 0)
print state
print state_click
print state_nothing
value = random.randint(1,10)
random_state[1] = random.getstate()
if value < 3 and score >= max_score:
value = random.randint(0,1)
random_state[1] = random.getstate()
if value == 1:
print "RNG VALUE OF 1"
return True
else:
print "RNG VALUE OF 0"
return False
elif state_click > state_nothing:
print "state_click greater than state_nothing"
return True
print "state_nothing greater than state_click"
return False
示例6: use_internal_state
def use_internal_state(self):
"""Use a specific RNG state."""
old_state = random.getstate()
random.setstate(self._random_state)
yield
self._random_state = random.getstate()
random.setstate(old_state)
示例7: custom_random
def custom_random(*args, **kwargs):
test = random.getstate() == unit.random_state
msg = ('Use no other method from the random ' +
'module other than random().')
unit.assertTrue(test, msg)
result = temp_random(*args, **kwargs)
unit.random_state = random.getstate()
return result
示例8: passGen
def passGen(password):
''' Generator that yields eight bits of psudo random data at a time seeded with the supplied password '''
random.seed(password)
state = random.getstate()
while True:
random.setstate(state)
out = random.getrandbits(8)
state = random.getstate()
yield out
示例9: main
def main(args):
#Setup that does not use the random number generator.
randstate=random.getstate()#Just for verification purposes
sm, original_sm, ofilename, energy, energies_to_track = setup_deterministic(args)
assert randstate==random.getstate()#Just for verification purposes
fud.pv("energies_to_track")
#Eval-energy mode
if args.eval_energy:
sm.bg.add_all_virtual_residues()
fud.pv('energy.eval_energy(sm, verbose=True, background=False)')
if sm.constraint_energy:
fud.pv('sm.constraint_energy.eval_energy(sm, verbose=True, background=False)')
if sm.junction_constraint_energy:
fud.pv('sm.junction_constraint_energy.eval_energy(sm, verbose=True, background=False)')
for track_energy in energies_to_track:
fud.pv('track_energy.eval_energy(sm, verbose=True, background=False)')
sys.exit(0)
#Set-up the random Number generator.
#Until here, no call to random should be made.
if args.seed:
seed_num=args.seed
else:
seed_num = random.randint(0,4294967295) #sys.maxint) #4294967295 is maximal value for numpy
random.seed(seed_num)
np.random.seed(seed_num)
#Main function, dependent on random.seed
with open_for_out(ofilename) as out_file:
if isinstance(energy, fbe.CombinedEnergy):
energies_to_track+=energy.uncalibrated_energies
elif isinstance(energy, fbe.CoarseGrainEnergy):
energies_to_track+=[energy]
stat=setup_stat(out_file, sm, args, energies_to_track, original_sm)
try:
print ("# Random Seed: {}".format(seed_num), file=out_file)
print ("# Command: `{}`".format(" ".join(sys.argv)), file=out_file)
for e in energy.iterate_energies():
if isinstance(e, fbe.FPPEnergy):
print("# Used FPP energy with options: --scale {} --ref-img {} "
"--fpp-landmarks {}".format(e.scale, e.ref_image,
":".join(",".join(map(str,x)) for x in e.landmarks)),
file=out_file)
if args.exhaustive:
sampler = fbs.ExhaustiveExplorer(sm, energy, stat, args.exhaustive, args.start_from_scratch)
elif args.new_ml:
sampler = fbs.ImprovedMultiloopMCMC(sm, energy, stat,
start_from_scratch=args.start_from_scratch,
dump_measures=args.dump_energies)
else:
sampler = fbs.MCMCSampler(sm, energy, stat,
start_from_scratch=args.start_from_scratch,
dump_measures=args.dump_energies)
for i in range(args.iterations):
sampler.step()
finally: #Clean-up
print("INFO: Random seed was {}".format(seed_num), file=sys.stderr)
示例10: __iter__
def __iter__(self):
y = self._y
num_rows = self.__num_rows
seed(self.__random_state_seed)
random_state = getstate()
for rows in num_rows:
setstate(random_state)
all_indices = np.sort(sample(np.arange(0, y.shape[0]), rows))
yield (all_indices, self._col_names, {'rows': rows})
random_state=getstate()
示例11: test_find_does_not_pollute_state
def test_find_does_not_pollute_state():
with deterministic_PRNG():
find(st.random_module(), lambda r: True)
state_a = random.getstate()
find(st.random_module(), lambda r: True)
state_b = random.getstate()
assert state_a != state_b
示例12: test_uses_provided_seed
def test_uses_provided_seed():
import random
initial = random.getstate()
@given(integers())
@seed(42)
def test_foo(x):
pass
test_foo()
assert random.getstate() == initial
示例13: randomize
def randomize():
global im
listoper = [shifter,degrader,tear,blur, pixelate, disperse, graindrip, seamer]
randint1 = random.randint(0, 30)
randint2 = random.randint(0,2000)
randint3 = random.randint(0,2000)
randint4 = random.randint(1,3)
randint5 = random.randint(1, 300)
cmd = random.choice(listoper)
print cmd
if cmd == pixelate:
im2 = pixelate(im, randint1)
im = im2
tkimage2 = ImageTk.PhotoImage(im2)
canvas.configure(image = tkimage2)
canvas.image = tkimage2
imagecopy = im2.copy()
imagelist.append(imagecopy)
statelist.append(random.getstate())
operationlist.append('pixelate')
elif cmd == disperse:
im2 = disperse(im, randint1, randint2, randint3)
im = im2
tkimage2 = ImageTk.PhotoImage(im2)
canvas.configure(image = tkimage2)
canvas.image = tkimage2
imagecopy = im2.copy()
imagelist.append(imagecopy)
statelist.append(random.getstate())
operationlist.append('disperse')
elif cmd == graindrip:
Gain = float(random.random())
Height = int(randint2)
im2 = graindrip(im, Gain, Height)
tkimage2 = ImageTk.PhotoImage(im2)
canvas.configure(image = tkimage2)
canvas.image = tkimage2
imagecopy = im2.copy()
imagelist.append(imagecopy)
statelist.append(random.getstate())
operationlist.append('ndrip')
elif cmd == seamer:
im2 = seamer(im,randint5, randint4)
im = im2
tkimage2 = ImageTk.PhotoImage(im2)
canvas.configure(image = tkimage2)
canvas.image = tkimage2
imagecopy = im2.copy()
imagelist.append(imagecopy)
statelist.append(random.getstate())
operationlist.append('seamer')
else:
cmd()
示例14: test_uses_provided_seed
def test_uses_provided_seed():
import random
random.seed(0)
initial = random.getstate()
@given(integers())
@seed(42)
def test_foo(x):
pass
test_foo()
assert hash(repr(random.getstate())) == hash(repr(initial))
示例15: test_prng_state_unpolluted_by_given_issue_1266
def test_prng_state_unpolluted_by_given_issue_1266():
# Checks that @given doesn't leave the global PRNG in a particular
# modified state; there may be no effect or random effect but not
# a consistent end-state.
first = random.getstate()
random_func()
second = random.getstate()
random_func()
third = random.getstate()
if first == second:
assert second == third
else:
assert second != third