def _update_square(self, terrain, x, y, square_len):
"""Update the midpoint of a square.
Midpoint becomes average of square corners plus a random offset determined by noise.
Args:
terrain (Terrain): Terrain to update.
x (int): X coordinate of center of square.
y (int): Y coordinate of center of square.
square_len (int): Length of one side of square.
Returns:
Terrain: New terrain with updated square center.
"""
half_len = square_len / 2
# Impossible to attempt to access neighbours out of terrain bounds
mean_height = sum([terrain[x - half_len, y - half_len],
terrain[x - half_len, y + half_len],
terrain[x + half_len, y - half_len],
terrain[x + half_len, y + half_len]]) / 4.0
frequency = terrain.length / square_len
offset = (random.random() - 0.5) * self.amp_from_freq(frequency)
if not 0 <= mean_height + offset <= 1:
if mean_height + offset > 1:
terrain[x, y] = 1
else:
terrain[x, y] = 0
else:
terrain[x, y] = mean_height + offset
return terrain
python类random()的实例源码
def _update_diamond(self, terrain, x, y, diamond_len):
"""Update the midpoint of a diamond.
Midpoint becomes average of diamond corners plus a random offset determined by noise.
Args:
terrain (Terrain): Terrain to update.
x (int): X coordinate of center of diamond.
y (int): Y coordinate of center of diamond.
diamond_len (int): Length of one corner of diamond to other.
Returns:
Terrain: New terrain with updated square center.
"""
half_len = diamond_len / 2
# If on edge of terrain, only access 3 neighbours to avoid leaving terrain bounds
neighbours = []
if x != 0:
neighbours.append(terrain[x - half_len, y])
if y != 0:
neighbours.append(terrain[x, y - half_len])
if x != terrain.width - 1:
neighbours.append(terrain[x + half_len, y])
if y != terrain.length - 1:
neighbours.append(terrain[x, y + half_len])
mean_height = sum(neighbours) / float(len(neighbours))
frequency = terrain.length / diamond_len
offset = (random.random() - 0.5) * self.amp_from_freq(frequency)
if not 0 <= mean_height + offset <= 1:
if mean_height + offset > 1:
terrain[x, y] = 1
else:
terrain[x, y] = 0
else:
terrain[x, y] = mean_height + offset
return terrain
def _init_gradients(self, vec_magnitude):
"""Initialize all gradient vectors to be in random directions with the same magnitude.
Args:
vec_magnitude (float): Magnitude of all gradient vectors.
"""
self._grad_vecs = [[(0, 0) for _ in range(self._width_in_squares+1)] for _ in range(self._length_in_squares+1)]
"""list[list[tuple(float, float)]]: Grid of gradient vectors."""
for x in range(self._width_in_squares+1):
for y in range(self._length_in_squares+1):
x_val = (random.random() - 0.5) * 2 * vec_magnitude
y_val = math.sqrt(vec_magnitude**2 - x_val**2) * random.choice([1, -1])
self._grad_vecs[y][x] = (x_val, y_val)
def _get_noise_at(self, x, y):
"""Get perlin noise at a point in terrain.
Does this by choosing a random gradient vector for each grid corner (done at initialization)
and taking their dot products with the displacement vectors to each point in the grid.
The generated values are then interpolated between based on distance to each corner from the desired point.
Args:
x (int): X coordinate of requested point.
y (int): Y coordinate of requested point.
Returns:
float: Height of point on terrain, between 0 and 1 inclusive.
"""
grid_x = x / float(self._square_len) # X value within grid of gradient vectors
grid_y = y / float(self._square_len) # Y value within grid of gradient vectors
left_x, right_x, upper_y, lower_y = self._get_corners(grid_x, grid_y)
x_weight = grid_x - left_x
y_weight = grid_y - upper_y
# ul = upper left, lr = lower right, etc.
ul_influence_val = self._get_influence_val(left_x, upper_y, grid_x, grid_y)
ur_influence_val = self._get_influence_val(right_x, upper_y, grid_x, grid_y)
ll_influence_val = self._get_influence_val(left_x, lower_y, grid_x, grid_y)
lr_influence_val = self._get_influence_val(right_x, lower_y, grid_x, grid_y)
# Interpolate between top two and bottom two influence vals, then interpolate between them using y_weight
upper_influence_val = self._interpolate_between(ul_influence_val, ur_influence_val, x_weight)
lower_influence_val = self._interpolate_between(ll_influence_val, lr_influence_val, x_weight)
interpolated_val = self._interpolate_between(upper_influence_val, lower_influence_val, y_weight)
# Normalize interpolated_val to be between 0 and 1, return as height
# Can range from 0.5 to -0.5, add 0.5 to achieve proper result
height = interpolated_val + 0.5
# Some margin of error, ensure is still between 0 and 1
return round(height) if not 0 <= height <= 1 else height
def generate_synthetic():
import random
max_nodes=200
min_nodes=100
community_num_nodes=10
graphs=[]
labels=[]
com_1= nx.caveman_graph(1, community_num_nodes)
com_2= nx.star_graph(community_num_nodes)
for i in range(500):
num_nodes= random.randint(min_nodes, max_nodes)
graph= nx.fast_gnp_random_graph(num_nodes, 0.1)
graph = nx.disjoint_union(graph,com_1)
for i in range(num_nodes,graph.number_of_nodes()):
for j in range(num_nodes):
if random.random() > 0.9:
graph.add_edge(graph.nodes()[i], graph.nodes()[j])
graphs.append(graph)
labels.append(1)
num_nodes = random.randint(min_nodes, max_nodes)
graph = nx.fast_gnp_random_graph(num_nodes, 0.1)
for i in range(num_nodes, graph.number_of_nodes()):
for j in range(num_nodes):
if random.random() > 0.9:
graph.add_edge(graph.nodes[i], graph.nodes[j])
graphs.append(graph)
labels.append(0)
return graphs,labels
def _real_upload_video(self, insert_request):
response = None
error = None
retry = 0
print('File upload in progress...', end='')
while response is None:
try:
status, response = insert_request.next_chunk()
print('.', end='')
if 'id' in response:
print()
return response['id']
except HttpError as err:
if err.resp.status in RETRIABLE_STATUS_CODES:
error = True
else:
raise
except RETRIABLE_EXCEPTIONS:
error = True
if error:
retry += 1
if retry > MAX_RETRIES:
raise Exception('Maximum retry are fail')
sleep_seconds = random.random() * 2 ** retry
time.sleep(sleep_seconds)
def random():
"""Normalised vector containing random entries in all dimensions"""
vec = Vector([random.random(), random.random(), random.random()])
vec.normalize()
return vec
def rand_for_param_var():
"""Generate random number between -1 and 1"""
return random.choice([-1, 1]) * rand_in_range(0, 1)
def rand_in_range(lower, upper):
"""Generate random number between lower and upper"""
return (random.random() * (upper - lower)) + lower
def points_for_floor_split(self):
"""Calculate Poissonly distributed points for stem start points"""
array = []
# calculate approx spacing radius for dummy stem
self.tree_scale = self.param.g_scale + self.param.g_scale_v
stem = Stem(0, None)
stem.length = self.calc_stem_length(stem)
rad = 2.5 * self.calc_stem_radius(stem)
# generate points
for _ in range(self.param.floor_splits + 1):
point_ok = False
while not point_ok:
# distance from center proportional for number of splits, tree scale and stem radius
dis = sqrt(rand_in_range(0, 1) * self.param.floor_splits / 2.5 * self.param.g_scale * self.param.ratio)
# angle random in circle
theta = rand_in_range(0, 2 * pi)
pos = Vector([dis * cos(theta), dis * sin(theta), 0])
# test point against those already in array to ensure it will not intersect
point_m_ok = True
for point in array:
if (point[0] - pos).magnitude < rad:
point_m_ok = False
break
if point_m_ok:
point_ok = True
array.append((pos, theta))
return array
def construct(params, seed=0, render=False, out_path=None):
"""Construct the tree"""
if seed == 0:
seed = int(random.random() * 9999999)
# print('Seed: ', seed)
random.seed(seed)
Tree(TreeParam(params)).make()
if render:
bpy.data.scenes['Scene'].render.filepath = out_path
bpy.ops.render.render(write_still=True)
#mod = __import__('ch_trees.parametric.tree_params.quaking_aspen', fromlist=[''])
#reload(mod)
#construct(mod.params)
def q_prod(sym):
"""Production rule for Q"""
ret = []
prev_ang = 0
n = int(random() * 2 + 7)
for ind in range(8):
offset = 1 - (__base_width__ - sym.parameters["w"]) / __base_width__
offset += ind / 8 / 12
dang = 30 + 85 * offset
if offset <= 0.7:
b_len = 0.4 + 0.6 * offset / 0.7
else:
b_len = 0.4 + 0.6 * (1.0 - offset) / 0.3
ret.extend([LSymbol("/", {"a": prev_ang + 75 + random() * 10}),
LSymbol("&", {"a": dang}),
LSymbol("!", {"w": sym.parameters["w"] * 0.08 * b_len}),
LSymbol("["),
LSymbol("F", {"l": sym.parameters["w"] / 2}),
LSymbol("A", {"w": 0.08 * b_len,
"l": 0.6 * b_len}),
LSymbol("]"),
LSymbol("!", {"w": sym.parameters["w"]}),
LSymbol("^", {"a": dang}),
LSymbol("F", {"l": sym.parameters["l"]})])
ret.append(LSymbol("Q", {"w": max(0, sym.parameters["w"] - __base_width__ / 11),
"l": sym.parameters["l"]}))
return ret
def a_prod(sym):
"""Production rule for A"""
ret = []
w_d = sym.parameters["w"] / 14
prev_rot = 0
n = int(random() * 3 + 15.5)
for ind in range(n):
wid = sym.parameters["w"] - ind * w_d
l_count = int((sqrt(n - ind) + 2) * 4 * sym.parameters["l"])
ret.extend([LSymbol("!", {"w": wid}),
LSymbol("F", {"l": sym.parameters["l"] / 3}),
LSymbol("/", {"a": prev_rot + 140}),
LSymbol("&", {"a": 60}),
LSymbol("!", {"w": wid * 0.4}),
LSymbol("["),
LSymbol("F", {"l": sqrt(n - ind) * sym.parameters["l"] / 3,
"leaves": l_count,
"leaf_d_ang": 40,
"leaf_r_ang": 140}),
LSymbol("^", {"a": random() * 30 + 30}),
LSymbol("F", {"l": sqrt(n - ind) * sym.parameters["l"] / 4,
"leaves": l_count,
"leaf_d_ang": 40,
"leaf_r_ang": 140}),
LSymbol("%"),
LSymbol("]"),
LSymbol("!", {"w": wid}),
LSymbol("^", {"a": 60}),
LSymbol("\\", {"a": prev_rot + 140}),
LSymbol("+", {"a": -5 + random() * 10}),
LSymbol("^", {"a": -7.5 + random() * 15})])
prev_rot += 140
ret.append(LSymbol("F", {"l": sym.parameters["l"] / 2}))
return ret
def q_prod(sym):
"""Production rule for Q"""
prop_off = sym.parameters["t"] / __t_max__
if prop_off < 1:
res = [LSymbol("!", {"w": 0.85 + 0.15 * sin(sym.parameters["t"])}),
LSymbol("^", {"a": random() - 0.65})]
if prop_off > __p_max__:
d_ang = 1 / (1 - __p_max__) * (1 - prop_off) * 110 + 15
res.extend([LSymbol("!", {"w": 0.1})])
for ind in range(int(random() * 2 + 5)):
r_ang = sym.parameters["t"] * 10 + ind * (random() * 50 + 40)
e_d_ang = d_ang * (random() * 0.4 + 0.8)
res.extend([LSymbol("/", {"a": r_ang}),
LSymbol("&", {"a": e_d_ang}),
LSymbol("["),
LSymbol("A"),
LSymbol("]"),
LSymbol("^", {"a": e_d_ang}),
LSymbol("\\", {"a": r_ang})],)
res.append(LSymbol("F", {"l": 0.05}))
else:
res.append(LSymbol("F", {"l": 0.15}))
res.append(LSymbol("Q", {"t": sym.parameters["t"] + __d_t__}))
else:
res = [LSymbol("!", {"w": 0}),
LSymbol("F", {"l": 0.15})]
return res
def system():
"""initialize and iterate the system as appropriate"""
l_sys = LSystem(axiom=[LSymbol("!", {"w": 0.2}),
LSymbol("/", {"a": random() * 360}),
LSymbol("Q", {"t": 0})],
rules={"Q": q_prod, "A": a_prod},
tropism=Vector([0, 0, -1]),
thickness=0.2,
bendiness=0,
leaf_shape=10,
leaf_scale=1,
leaf_scale_x=0.1,
leaf_bend=0)
l_sys.iterate_n(100)
return l_sys
def a_prod(sym):
"""Production rule for A"""
ret = []
n = int(random() * 5 + 22.5)
w_d = sym.parameters["w"] / (n - 1)
prev_rot = 0
for ind in range(n):
wid = sym.parameters["w"] - ind * w_d
ang = random() * 10 + 25
ret.extend([LSymbol("!", {"w": wid}),
LSymbol("F", {"l": sym.parameters["l"] / 3}),
LSymbol("/", {"a": prev_rot + 140}),
LSymbol("&", {"a": ang}),
LSymbol("!", {"w": wid * 0.3}),
LSymbol("["),
LSymbol("F", {"l": 0.75 * sqrt(n - ind) * sym.parameters["l"] / 3,
"leaves": 25,
"leaf_d_ang": 40,
"leaf_r_ang": 140}),
LSymbol("^", {"a": 20}),
LSymbol("F", {"l": 0.75 * sqrt(n - ind) * sym.parameters["l"] / 3,
"leaves": 25,
"leaf_d_ang": 40,
"leaf_r_ang": 140}),
LSymbol("%"),
LSymbol("]"),
LSymbol("!", {"w": wid}),
LSymbol("^", {"a": ang}),
LSymbol("\\", {"a": prev_rot + 140}),
LSymbol("^", {"a": 1.2})])
prev_rot += 140
return ret
def d1_ang():
"""return random first split angle"""
return random() * 40 + 60
def d2_ang():
"""return random second split angle"""
return random() * 40 + 100
def q_prod(sym):
"""Production rule for Q"""
ret = [LSymbol("!", {"w": sym.parameters["w"]}),
LSymbol("&", {"a": 90}),
LSymbol("+", {"a": random() * 360}),
LSymbol("!", {"w": sym.parameters["bw"]})]
b_count = int(random() * 2) + 5
for _ in range(b_count):
rand = random() * 130 / b_count
ret.extend([LSymbol("+", {"a": rand}),
LSymbol("["),
LSymbol("^", {"a": 5 / max(sym.parameters["bl"] * sym.parameters["bl"], 0.05
) - 30 * (random() * 0.2 + 0.9)}),
LSymbol("A", {"l": sym.parameters["bl"], "w": sym.parameters["bw"]}),
LSymbol("]"),
LSymbol("+", {"a": (360 / b_count) - rand})])
ret.extend([LSymbol("!", {"w": sym.parameters["w"]}),
LSymbol("$"),
LSymbol("F", {"l": sym.parameters["l"],
"leaves": int(sym.parameters["l"] * __n_leaves__ / 3),
"leaf_d_ang": 20,
"leaf_r_ang": 140}),
LSymbol("Q", {"w": sym.parameters["w"] - 0.2 / 15,
"l": sym.parameters["l"] * 0.95,
"bw": sym.parameters["bw"] * __width_r__,
"bl": sym.parameters["bl"] * __branch_length_r__}),
LSymbol("%")])
return ret
def a_prod(sym):
"""Production rule for A"""
if random() < sym.parameters["l"]:
ang = random() * __sec_branch_ang_v__ + __sec_branch_ang__
return [LSymbol("!", {"w": sym.parameters["w"]}),
LSymbol("^", {"a": random() * 15 - 5}),
LSymbol("F", {"l": sym.parameters["l"],
"leaves": int(sym.parameters["l"] * __n_leaves__),
"leaf_d_ang": 40,
"leaf_r_ang": 140}),
LSymbol("-", {"a": ang / 2}),
LSymbol("["),
LSymbol("A", {"l": sym.parameters["l"] * __length_r__,
"w": sym.parameters["w"] * __width_r__}),
LSymbol("]"),
LSymbol("+", {"a": ang}),
LSymbol("["),
LSymbol("A", {"l": sym.parameters["l"] * __length_r__,
"w": sym.parameters["w"] * __width_r__}),
LSymbol("]"),
LSymbol("-", {"a": ang / 2}),
LSymbol("A", {"l": sym.parameters["l"] * __length_r__,
"w": sym.parameters["w"] * __width_r__})]
else:
return [LSymbol("!", {"w": sym.parameters["w"]}),
LSymbol("^", {"a": random() * 15 - 5}),
LSymbol("F", {"l": sym.parameters["l"],
"leaves": int(sym.parameters["l"] * __n_leaves__),
"leaf_d_ang": 40,
"leaf_r_ang": 140}),
LSymbol("A", {"l": sym.parameters["l"] * __length_r__,
"w": sym.parameters["w"] * __width_r__})]
def gen_values(self, n, reversed = False, shuffled = False, gen_dupes = False):
if reversed:
keys = xrange(n-1,-1,-1)
else:
keys = xrange(n)
if shuffled:
keys = list(keys)
r = random.Random(1234827)
r.shuffle(keys)
if gen_dupes:
return itertools.chain(
itertools.izip(keys, xrange(0, 2*n, 2)),
itertools.islice(itertools.izip(keys, xrange(0, 2*n, 2)), 10, None),
)
else:
return itertools.izip(keys, xrange(0, 2*n, 2))
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
self.forever = forever
self.renewkeys = renewkeys
self.inf = inf
self.rnd = random.Random(seed)
self.sbox_size = 256
self.top = sup-inf+1
n=0
while (1<<n) < self.top:
n += 1
self.n =n
self.fs = min(3,(n+1)/2)
self.fsmask = 2**self.fs-1
self.rounds = max(self.n,3)
self.turns = 0
self.i = 0
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
self.forever = forever
self.renewkeys = renewkeys
self.inf = inf
self.rnd = random.Random(seed)
self.sbox_size = 256
self.top = sup-inf+1
n=0
while (1<<n) < self.top:
n += 1
self.n =n
self.fs = min(3,(n+1)/2)
self.fsmask = 2**self.fs-1
self.rounds = max(self.n,3)
self.turns = 0
self.i = 0
def show_page(page, rating=True):
attribution = page.build_attribution_string(
templates=dict(
author='written {hdate} by {user}',
rewrite='rewritten {hdate} by {user}',
translator='translated {hdate} by {user}',
maintainer='maintained {hdate} by {user}'),
group_templates=dict(
author='co-written {hdate} by {users} and {last_user}',
rewrite='rewritten {hdate} by {users} and {last_user}',
translator='translated {hdate} by {users} and {last_user}',
maintainer='maintained {hdate} by {users} and {last_user}'))
out = lex.page_lookup.summary if rating else lex.page_lookup.nr_summary
if page.name == 'scp-1848':
r = rand.Random(int(arrow.now().format('YYYYMMDDHH')))
rating = r.randrange(-160, -140)
else:
rating = page.rating
return out(page=page, rating=rating, attribution=attribution)
def run_with_fixed_seeds(count=128, master_seed=0x243F6A8885A308D3):
"""
decorator run test method w/ multiple fixed seeds.
"""
def builder(func):
@wraps(func)
def wrapper(*args, **kwds):
rng = random.Random(master_seed)
for _ in irange(count):
kwds['seed'] = rng.getrandbits(32)
func(*args, **kwds)
return wrapper
return builder
#=============================================================================
# custom test harness
#=============================================================================
def getrandbytes(rng, count):
"""return byte-string containing *count* number of randomly generated bytes, using specified rng"""
# NOTE: would be nice if this was present in stdlib Random class
###just in case rng provides this...
##meth = getattr(rng, "getrandbytes", None)
##if meth:
## return meth(count)
if not count:
return _BEMPTY
def helper():
# XXX: break into chunks for large number of bits?
value = rng.getrandbits(count<<3)
i = 0
while i < count:
yield value & 0xff
value >>= 3
i += 1
return join_byte_values(helper())
def shuffle_and_batch(items: List[T], batch_size: int,
rng: Optional[random.Random] = None) \
-> Iterator[List[T]]:
"""Optionally shuffles and batches items in a list.
Args:
- items: List of items to shuffle & batch.
- batch_size: size of batches.
- rng: random number generator if items should be shuffles, else None.
Returns: Batch iterator
"""
todo = list(range(len(items)))
if rng is not None:
rng.shuffle(todo)
while todo:
indices = todo[:batch_size]
todo = todo[batch_size:]
items_batch = [items[i] for i in indices]
yield items_batch
def __init__(self, inf, sup, seed=None, forever=1, renewkeys=0):
self.forever = forever
self.renewkeys = renewkeys
self.inf = inf
self.rnd = random.Random(seed)
self.sbox_size = 256
self.top = sup-inf+1
n=0
while (1<<n) < self.top:
n += 1
self.n =n
self.fs = min(3,(n+1)/2)
self.fsmask = 2**self.fs-1
self.rounds = max(self.n,3)
self.turns = 0
self.i = 0
def random_str(randomlength=8,
just_number=False):
"""????????????
:param randomlength: ?????????
:param just_number: ?????
:return:
"""
string = ""
if just_number:
chars = '0123456789'
else:
chars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789'
length = len(chars) - 1
random = Random()
for i in range(randomlength):
string += chars[random.randint(0, length)]
return string
def generate_hold_out_split (dataset, training = 0.8, base_dir="splits"):
r = random.Random()
r.seed(1489215)
article_ids = list(dataset.articles.keys()) # get a list of article ids
r.shuffle(article_ids) # and shuffle that list
training_ids = article_ids[:int(training * len(article_ids))]
hold_out_ids = article_ids[int(training * len(article_ids)):]
# write the split body ids out to files for future use
with open(base_dir+ "/"+ "training_ids.txt", "w+") as f:
f.write("\n".join([str(id) for id in training_ids]))
with open(base_dir+ "/"+ "hold_out_ids.txt", "w+") as f:
f.write("\n".join([str(id) for id in hold_out_ids]))