def id3_date(self):
d = self._fake.date_object()
full_date = random.choices(["y", "n"], cum_weights=[15, 85]) == "y"
return Date(year=d.year,
month=d.month if full_date else None,
day=d.day if full_date else None)
python类choices()的实例源码
def categories(self, create, extracted, **kwargs):
categories = models.Category.objects.all()
for category in random.choices(categories, k=random.randint(1, len(categories))):
self.categories.add(category)
def random_user_name():
return ''.join(random.choices(string.ascii_uppercase + string.digits, k=8))
def get_record_crystal(scout: Scout, seed: int=None) -> int:
record_crystal = 0
if scout.record_crystal:
cases: List[int] = []
chances: List[float] = []
random.seed(seed)
for case, chance in scout.record_crystal:
cases.append(case)
chances.append(chance)
record_crystal = random.choices(cases, chances)[0]
random.seed(None)
return record_crystal
def test_new_subvoat_creation():
api_token = get_api_token()
result = requests.post('%s/create_subvoat' % (base_address), {'username':'test_username',
'api_token':api_token,
'subvoat_name':'test_%s' % (''.join(random.choices(string.ascii_letters, k=10)))})
print(result.json())
# Try to create the same subvoat that already exists
def test_posting():
api_token = get_api_token()
body = ''.join(random.choices(string.ascii_letters, k=100))
title = ''.join(random.choices(string.ascii_letters, k=10))
print(requests.post('%s/submit_thread' % (base_address), {'username':'test_username',
'api_token':api_token,
'subvoat_name':'test_exists',
'title':title,
'body':body}).json())
def test_posting_comment():
api_token = get_api_token()
body = ''.join(random.choices(string.ascii_letters, k=100))
data = requests.post('%s/get_threads' % (base_address), {'subvoat_name':'test_exists'}).json()
thread_uuid = data['result'][0]['uuid']
print(requests.post('%s/submit_comment' % (base_address), {'thread_uuid':thread_uuid,
'username':'test_username',
'api_token':api_token,
'body':body}).text)
def generate_threads(self, count):
api_token = self.get_api_token()
for x in range(count):
title = ''.join(random.choices(string.ascii_letters, k=10))
body = ''.join(random.choices(string.ascii_letters, k=100))
result = requests.post('%s/submit_thread' % (self.base_address), {'username':'test_username',
'api_token':api_token,
'subvoat_name':'test_exists',
'title':title,
'body':body}).json()
def choices(l, k):
for _ in range(k):
yield random.choice(l)
def rand_string(min_length, max_length, corpus=ALL):
return ''.join(random.choices(corpus, k=random.randrange(min_length, max_length)))
def numberwang():
return random.choices(STRINGS, weights=WEIGHTS)
def shout(message):
parts = message.split('.')
out = ''
for part in parts:
out += part.upper() + ''.join(random.choices(['!', '1'], weights=[5, 1], k=random.randint(2, 8)))
return out
def pick_n_random_parents(population, n_parents=2):
return choices(population, k=n_parents)
def test_breed_amount_works(self):
pop1 = Population(chromosomes=self.chromosomes, eval_function=self.eval_func)
pop1.survive(n=50).breed(parent_picker=lambda population: choices(population, k=2),
combiner=lambda mom, dad: (mom + dad) / 2)
assert len(pop1) == 200
pop2 = Population(chromosomes=self.chromosomes, eval_function=self.eval_func)
pop2.survive(n=50).breed(parent_picker=lambda population: choices(population, k=2),
combiner=lambda mom, dad: (mom + dad) / 2, population_size=400)
assert len(pop2) == 400
assert pop2.intended_size == 400
def survive(self, fraction=None, n=None, luck=False) -> 'Population':
"""Let part of the population survive.
Remove part of the population. If both fraction and n are specified,
the minimum resulting population size is taken.
:param fraction: Fraction of the original population that survives.
Defaults to None.
:type fraction: float/None
:param n: Number of individuals of the population that survive.
Defaults to None.
:type n: int/None
:param luck: If True, individuals randomly survive (with replacement!)
with chances proportional to their fitness. Defaults to False.
:type luck: bool
:return: self
"""
if fraction is None:
if n is None:
raise ValueError('everyone survives! must provide either "fraction" and/or "n".')
resulting_size = n
elif n is None:
resulting_size = round(fraction*len(self.individuals))
else:
resulting_size = min(round(fraction*len(self.individuals)), n)
self.evaluate(lazy=True)
if resulting_size == 0:
raise RuntimeError('no one survived!')
if resulting_size > len(self.individuals):
raise ValueError('everyone survives! must provide "fraction" and/or "n" < population size')
if luck:
self.individuals = choices(self.individuals, k=resulting_size,
weights=[individual.fitness for individual in self.individuals])
else:
sorted_individuals = sorted(self.individuals, key=lambda x: x.fitness, reverse=self.maximize)
self.individuals = sorted_individuals[:resulting_size]
return self
def random_string(n):
return ''.join(random.choices(string.ascii_uppercase + string.ascii_lowercase + string.digits, k=n))
def run(self):
# Create directory contain POSCARs
import random
import string
import tempfile
rd_suffix = ''.join(random.choices(string.ascii_uppercase
+ string.digits, k=5))
working_path = os.getcwd()
poscars_dir = os.path.join(working_path,
'STRUCTURES_{0:}_{1:}'.format(self.comment,
rd_suffix))
if not os.path.exists(poscars_dir):
os.makedirs(poscars_dir)
else:
shutil.rmtree(poscars_dir)
os.makedirs(poscars_dir)
ogg = OccupyGenerator(self.cell)
g = ogg.gen_nodup_trinary_alloy(Specie(self.s1), self.n1,
Specie(self.s2), self.n2)
if self.tr is not None:
tr = (Specie(self.tr[0]), self.tr[1])
applied_restriction = MinDistanceRestriction(tr)
# For diff outmode
if self.outmode == 'vasp':
Output = VaspPOSCAR
prefix = 'POSCAR_A{:}B{:}C{:}_'
suffix = '.vasp'
else:
Output = YamlOutput
prefix = 'STRUCTURE_A{:}B{:}C{:}_'
suffix = '.yaml'
for n_count, c in enumerate(g):
if self.mpr:
if self.tr is not None:
condition = c.is_primitive() and applied_restriction.is_satisfied(c)
else:
condition = c.is_primitive()
else:
if self.tr is not None:
condition = applied_restriction.is_satisfied(c)
else:
condition = True
if condition:
if self.refined:
c = c.get_refined_pcell()
poscar = Output(c, 1)
tf = tempfile.NamedTemporaryFile(mode='w+b', dir=poscars_dir,
prefix=prefix.format(self.n0, self.n1, self.n2),
suffix=suffix, delete=False)
poscar.write(tf.name)
def run(self):
# Create directory contain POSCARs
import random
import string
rd_suffix = ''.join(random.choices(string.ascii_uppercase
+ string.digits, k=5))
working_path = os.getcwd()
out_dir = os.path.join(working_path,
'STRUCTURES_{0:}_{1:}'.format(self.comment,
rd_suffix))
if not os.path.exists(out_dir):
os.makedirs(out_dir)
else:
shutil.rmtree(out_dir)
os.makedirs(out_dir)
ogg = OccupyGenerator(self.cell)
g = ogg.gen_nodup_exch(Specie(self.exch1), Specie(self.exch2), self.n)
if self.tr is not None:
tr = (Specie(self.tr[0]), self.tr[1])
applied_restriction = MinDistanceRestriction(tr)
for n_count, c in enumerate(g):
if self.mpr:
if self.tr is not None:
condition = c.is_primitive() and applied_restriction.is_satisfied(c)
else:
condition = c.is_primitive()
else:
if self.tr is not None:
condition = applied_restriction.is_satisfied(c)
else:
condition = True
if condition:
if self.refined:
c = c.get_refined_pcell()
out = GeneralIO(c)
f_suffix = ''.join(random.choices(string.ascii_uppercase
+ string.digits, k=4))
ofname = "STRUCTURE_{:}_{:}.{:}".format(c.comment, f_suffix, self.outmode)
lastpath = os.path.join(out_dir, ofname)
out.write_file(lastpath)
def run(self):
# Create directory contain POSCARs
import random
import string
rd_suffix = ''.join(random.choices(string.ascii_uppercase
+ string.digits, k=5))
working_path = os.getcwd()
out_dir = os.path.join(working_path,
'STRUCTURES_{0:}_{1:}'.format(self.comment,
rd_suffix))
if not os.path.exists(out_dir):
os.makedirs(out_dir)
else:
shutil.rmtree(out_dir)
os.makedirs(out_dir)
ogg = OccupyGenerator(self.cell)
g = ogg.gen_nodup_of_ele(self.ele, self.n, self.speckle)
# sym for getting degeneracy
sym_perm = self.cell.get_symmetry_permutation()
if self.tr is not None:
tr = (Specie(self.tr[0]), self.tr[1])
applied_restriction = MinDistanceRestriction(tr)
for n_count, c in enumerate(g):
if self.mpr:
if self.tr is not None:
condition = c.is_primitive() and applied_restriction.is_satisfied(c)
else:
condition = c.is_primitive()
else:
if self.tr is not None:
condition = applied_restriction.is_satisfied(c)
else:
condition = True
if condition:
if self.refined:
c = c.get_refined_pcell()
out = GeneralIO(c)
f_suffix = ''.join(random.choices(string.ascii_uppercase
+ string.digits, k=4))
ofname = "STRUCTURE_{:}_D{:}D_{:}.{:}".format(c.comment, c.get_degeneracy(sym_perm),
f_suffix, self.outmode)
lastpath = os.path.join(out_dir, ofname)
out.write_file(lastpath)
def run(self):
# Create directory contain POSCARs
import random
import string
rd_suffix = ''.join(random.choices(string.ascii_uppercase
+ string.digits, k=5))
working_path = os.getcwd()
out_dir = os.path.join(working_path,
'STRUCTURES_{0:}_{1:}'.format(self.comment,
rd_suffix))
if not os.path.exists(out_dir):
os.makedirs(out_dir)
else:
shutil.rmtree(out_dir)
os.makedirs(out_dir)
ogg = OccupyGenerator(self.cell)
if self.tr is not None:
tr = (Specie(self.tr[0]), self.tr[1])
applied_restriction = MinDistanceRestriction(tr)
for n1 in range(1, self.n - 1):
for n2 in range(1, self.n - n1):
g = ogg.gen_nodup_trinary_alloy(Specie(self.s1), n1,
Specie(self.s2), n2)
for n_count, c in enumerate(g):
if self.tr is not None:
condition = c.is_primitive() and applied_restriction.is_satisfied(c)
else:
condition = c.is_primitive()
if condition:
if self.refined:
c = c.get_refined_pcell()
out = GeneralIO(c)
f_suffix = ''.join(random.choices(string.ascii_uppercase
+ string.digits, k=4))
ofname = "STRUCTURE_{:}_{:}.{:}".format(c.comment, f_suffix, self.outmode)
lastpath = os.path.join(out_dir, ofname)
out.write_file(lastpath)