def generate_random_gaussian_validator_set(
protocol,
num_validators=5,
mu=60,
sigma=40,
min_weight=20
):
"""Generates a random validator set."""
# Give the validators random weights in 0.,BIGINT;
# this "big" integer's job is to guarantee the "tie-breaking property"
# that no two subsets of validator's total weights are exactly equal.
# In prod, we will add a random epsilon to weights given by bond amounts,
# however, for the purposes of the current work, this will suffice.
BIGINT = 1000000000000
names = set(range(num_validators))
weights = {
i: max(min_weight, r.gauss(mu, sigma))
+ 1.0/(BIGINT + r.uniform(0, 1)) + r.random()
for i in names
}
return ValidatorSet(weights, protocol)
python类gauss()的实例源码
def validator_generator(config, protocol):
if config['gen_type'] == 'gauss':
def gauss_generator():
return generate_random_gaussian_validator_set(
protocol,
config['num_validators'],
config['mu'],
config['sigma'],
config['min_weight']
)
return gauss_generator
if config['gen_type'] == 'weights':
jitter_weights = {
i: weight + r.random()
for i, weight in enumerate(config['weights'])
}
def weights_generator():
return ValidatorSet(jitter_weights, protocol)
return weights_generator
def find_paste_location(self, bbox, already_pasted_bboxes):
while True:
x_derivation = random.gauss(0, self.variance) * (self.image_size // 2)
y_derivation = random.gauss(0, self.variance) * (self.image_size // 2)
center = Point(x=self.image_size // 2, y=self.image_size // 2)
bbox.left = max(min(center.x + x_derivation, self.image_size), 0)
bbox.top = max(min(center.y + y_derivation, self.image_size), 0)
if bbox.left + bbox.width > self.image_size:
bbox.left = self.image_size - bbox.width
if bbox.top + bbox.height > self.image_size:
bbox.top = self.image_size - bbox.height
if not any(intersects(bbox, box) for box in already_pasted_bboxes):
return bbox
def _provisioning_timer(self, timeout):
# REVISIT(ivc): consider integrating with Retry
interval = 3
max_interval = 15
with timeutils.StopWatch(duration=timeout) as timer:
while not timer.expired():
yield timer.leftover()
interval = interval * 2 * random.gauss(0.8, 0.05)
interval = min(interval, max_interval)
interval = min(interval, timer.leftover())
if interval:
time.sleep(interval)
def brownian(cls, dt):
return random.gauss(0, math.sqrt(dt))
def next(self, message, backoff_exchange_name):
total_attempts = 0
for deadlettered in message.headers.get('x-death', ()):
if deadlettered['exchange'] == backoff_exchange_name:
total_attempts += int(deadlettered['count'])
if self.limit and total_attempts >= self.limit:
expired = Backoff.Expired(
"Backoff aborted after '{}' retries (~{:.0f} seconds)".format(
self.limit, self.max_delay / 1000
)
)
six.raise_from(expired, self)
expiration = self.get_next_schedule_item(total_attempts)
if self.random_sigma:
randomised = int(random.gauss(expiration, self.random_sigma))
group_size = self.random_sigma / self.random_groups_per_sigma
expiration = round_to_nearest(randomised, interval=group_size)
# Prevent any negative values created by randomness
expiration = abs(expiration)
# store calculation results on self.
self._next_expiration = expiration
self._total_attempts = total_attempts
return expiration
def test():
for j in xrange(1000):
vals = [7, 1e100, -7, -1e100, -9e-20, 8e-20] * 10
s = 0
for i in range(200):
v = gauss(0, random()) ** 7 - s
s += v
vals.append(v)
shuffle(vals)
assert msum(vals) == lsum(vals) == dsum(vals) == frsum(vals) == lsum_26(vals)
print '.',
print 'Tests Passed'
def generateMaze(seed = None):
if not seed:
seed = random.randint(1,MAX_DIFFERENT_MAZES)
random.seed(seed)
maze = Maze(16,16)
gapfactor = min(0.65,random.gauss(0.5,0.1))
skip = make_with_prison(maze, depth=0, gaps=3, vert=True, min_width=1, gapfactor=gapfactor)
maze.to_map()
add_pacman_stuff(maze, 2*(maze.r*maze.c/20), 4, skip)
return str(maze)
def h(self,xk,uk):
#---------------
y = xk[0]
y += random.gauss(0.0,self.noisestd)
return y
#=======================
def output(self):
if self._params['mu'] is None:
mu = self.DEFAULT_MU
else:
mu = self._params['mu']
if self._params['sigma'] is None:
sigma = self.DEFAULT_SIGMA
else:
sigma = self._params['sigma']
return random.gauss(mu, sigma)
def mutate_response(self):
self.response = random.gauss(0.5 , 0.15)
def _fix(self):
return int(round(random.gauss(self.mu, self.sigma)))
def _fix(self):
return int(round(random.gauss(self.mu, self.sigma)))
def randomize_time(mean):
allowed_range = mean * STDEV
stdev = allowed_range / 3 # 99.73% chance to be in the allowed range
t = 0
while abs(mean - t) > allowed_range:
t = gauss(mean, stdev)
return t
def test_sharpe_noise(self, small, large):
index = pd.date_range('2000-1-30', periods=1000, freq='D')
smaller_normal = pd.Series(
[random.gauss(.01, small) for i in range(1000)],
index=index
)
larger_normal = pd.Series(
[random.gauss(.01, large) for i in range(1000)],
index=index
)
assert self.empyrical.sharpe_ratio(smaller_normal, 0.001) > \
self.empyrical.sharpe_ratio(larger_normal, 0.001)
# Regressive downside risk tests
def test_downside_risk_std(self, smaller_std, larger_std):
less_noise = pd.Series(
[random.gauss(0, smaller_std) for i in range(1000)],
index=pd.date_range('2000-1-30', periods=1000, freq='D')
)
more_noise = pd.Series(
[random.gauss(0, larger_std) for i in range(1000)],
index=pd.date_range('2000-1-30', periods=1000, freq='D')
)
assert self.empyrical.downside_risk(less_noise) < \
self.empyrical.downside_risk(more_noise)
# Regressive sortino ratio tests
def _gauss(mean, sigma) -> int:
return int(random.gauss(mean, sigma))
def make_control_vectors(num_cv, pos_stddev, angle_stddev, scale_stddev):
"""
Argument num_cv is the approximate number of control vectors to create
Arguments pos_stddev, angle_stddev, and scale_stddev are the standard
deviations of the controls effects of position, angle, and
scale.
Returns pair of control_vectors, control_sdr
The control_vectors determines what happens for each output. Each
control is a 4-tuple of (X, Y, Angle, Scale) movements. To move,
active controls are summed and applied to the current location.
control_sdr contains the shape of the control_vectors.
"""
cv_sz = int(round(num_cv // 6))
control_shape = (6*cv_sz,)
pos_controls = [
(random.gauss(0, pos_stddev), random.gauss(0, pos_stddev), 0, 0)
for i in range(4*cv_sz)]
angle_controls = [
(0, 0, random.gauss(0, angle_stddev), 0)
for angle_control in range(cv_sz)]
scale_controls = [
(0, 0, 0, random.gauss(0, scale_stddev))
for scale_control in range(cv_sz)]
control_vectors = pos_controls + angle_controls + scale_controls
random.shuffle(control_vectors)
control_vectors = np.array(control_vectors)
# Add a little noise to all control vectors
control_vectors[:, 0] += np.random.normal(0, pos_stddev/10, control_shape)
control_vectors[:, 1] += np.random.normal(0, pos_stddev/10, control_shape)
control_vectors[:, 2] += np.random.normal(0, angle_stddev/10, control_shape)
control_vectors[:, 3] += np.random.normal(0, scale_stddev/10, control_shape)
return control_vectors, SDR(control_shape)
def mutate_standard(self, percent, population):
"""
Randomly change some parameters. The change in value uses the populations
standard deviation.
"""
def mutate_value(value, pop_values):
if random.random() > percent:
return value
pop_values = [v for v in pop_values if v is not None]
if len(np.unique(pop_values)) < 3:
# Use alternative method when diversity is very low.
return value * 1.5 ** (random.random()*2-1)
else:
std = np.std(pop_values)
return float(random.gauss(value, std))
for param in self.parameters:
value = getattr(self, param)
pop_values = [getattr(indiv, param) for indiv in population]
if value is None:
continue # cant mutate.
elif isinstance(value, Parameters):
value.mutate_standard(percent, pop_values)
elif isinstance(value, tuple):
new_tup = []
for index, value_indexed in enumerate(value):
pop_values_indexed = [v[index] for v in pop_values]
new_value = mutate_value(value_indexed, pop_values_indexed)
new_tup.append(new_value)
setattr(self, param, tuple(new_tup))
else: # Mutate a floating point or boolean number.
setattr(self, param, mutate_value(value, pop_values))
def _fix(self):
return int(round(random.gauss(self.mu, self.sigma)))