def overlay_generator(hexgrid, depth=params.shells, major=params.major):
# GPolygon.RegularPoly(coord,major,poly,rot,"#000000",strokeOpacity,linethick,"#00ffff",fillalpha)
s1 = ''
numhextiles = float(len(hexgrid))
for idx, hexel in enumerate(hexgrid):
speckle = random.gauss(1, 0.5)
rank = int((speckle * idx / numhextiles) * 15)
invrank = 15 - rank
blue = hex(rank)[2:]
red = hex(invrank)[2:]
tilecolor = red + red + '00' + blue + blue
ts = "map.addOverlay(GPolygon.RegularPoly(new GLatLng{coord},\
{major},6,90,\"\#{strokeColor}\",{strokeOpacity},{strokeWeight},\"\#{fillColor}\",{fillalpha}))\
\n".format(coord=hexel, major=major, strokeColor=tilecolor, strokeOpacity=params.opacity,
strokeWeight=params.strokeWeight, fillColor=tilecolor, fillalpha=params.opacity)
s1 += ts
return s1
python类gauss()的实例源码
def overlay_generator(self, hexgrid, depth=params.shells, major=params.major):
# GPolygon.RegularPoly(coord,major,poly,rot,"#000000",strokeOpacity,linethick,"#00ffff",fillalpha)
s1 = ''
numhextiles = float(len(hexgrid))
for idx, hexel in enumerate(hexgrid):
speckle = random.gauss(1, 0.5)
rank = int((speckle * idx / numhextiles) * 15)
invrank = 15 - rank
blue = hex(rank)[2:]
red = hex(invrank)[2:]
tilecolor = red + red + '00' + blue + blue
ts = "map.addOverlay(GPolygon.RegularPoly(new GLatLng{coord},\
{major},6,90,\"\#{strokeColor}\",{strokeOpacity},{strokeWeight},\"\#{fillColor}\",{fillalpha}))\
\n".format(coord=hexel, major=major, strokeColor=tilecolor, strokeOpacity=params.opacity,
strokeWeight=params.strokeWeight, fillColor=tilecolor, fillalpha=params.opacity)
s1 += ts
return s1
def get_pretrained_embeddings(filepath):
embeddings = dict()
with open(filepath, 'r') as f:
for line in f:
info = line.strip().split()
#lines = [line.strip().split() for line in f.readlines()]
#embeddings = dict([(line[0], [float(r) for r in line[1:]]) for line in lines])
embeddings[info[0]] = [float(r) for r in info[1:]]
f.close()
embedding_size = len(embeddings.values()[0])
print 'Embedding size={}'.format(embedding_size)
embeddings[START_MARKER] = [random.gauss(0, 0.01) for _ in range(embedding_size)]
embeddings[END_MARKER] = [random.gauss(0, 0.01) for _ in range(embedding_size)]
if not UNKNOWN_TOKEN in embeddings:
embeddings[UNKNOWN_TOKEN] = [random.gauss(0, 0.01) for _ in range(embedding_size)]
return embeddings
def _fix(self, n=0):
o = random.choice(self.objlist)
if issubclass(o, ASN1_INTEGER):
return o(int(random.gauss(0,1000)))
elif issubclass(o, ASN1_IPADDRESS):
z = RandIP()._fix()
return o(z)
elif issubclass(o, ASN1_STRING):
z = int(random.expovariate(0.05)+1)
return o("".join([random.choice(self.chars) for i in range(z)]))
elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
z = int(random.expovariate(0.08)+1)
return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
return ASN1_INTEGER(int(random.gauss(0,1000)))
##############
#### ASN1 ####
##############
def _fix(self, n=0):
o = random.choice(self.objlist)
if issubclass(o, ASN1_INTEGER):
return o(int(random.gauss(0,1000)))
elif issubclass(o, ASN1_IPADDRESS):
z = RandIP()._fix()
return o(z)
elif issubclass(o, ASN1_STRING):
z = int(random.expovariate(0.05)+1)
return o("".join([random.choice(self.chars) for i in range(z)]))
elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
z = int(random.expovariate(0.08)+1)
return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
return ASN1_INTEGER(int(random.gauss(0,1000)))
##############
#### ASN1 ####
##############
def _bootstraped():
def worker(n=1000,
mu1=10, sigma1=1,
mu2=10.2, sigma2=1):
def g(mu, sigma): return random.gauss(mu, sigma)
x = [g(mu1, sigma1) for i in range(n)]
y = [g(mu2, sigma2) for i in range(n)]
return n, mu1, sigma1, mu2, sigma2, \
'different' if bootstrap(x, y) else 'same'
# very different means, same std
print worker(mu1=10, sigma1=10,
mu2=100, sigma2=10)
# similar means and std
print worker(mu1=10.1, sigma1=1,
mu2=10.2, sigma2=1)
# slightly different means, same std
print worker(mu1=10.1, sigma1=1,
mu2=10.8, sigma2=1)
# different in mu eater by large std
print worker(mu1=10.1, sigma1=10,
mu2=10.8, sigma2=1)
def _ediv():
"Demo code to test the above."
import random
bell= random.gauss
random.seed(1)
def go(lst):
print ""; print sorted(lst)[:10],"..."
for d in ediv(lst,tiny=2):
rprint(d); nl()
X,Y="X","Y"
l=[(1,X),(2,X),(3,X),(4,X),(11,Y),(12,Y),(13,Y),(14,Y)]
go(l)
l[0] = (1,Y)
go(l)
go(l*2)
go([(1,X),(2,X),(3,X),(4,X),(11,X),(12,X),(13,X),(14,X)])
go([(64,X),(65,Y),(68,X),(69,Y),(70,X),(71,Y),
(72,X),(72,Y),(75,X),(75,X),
(80,Y),(81,Y),(83,Y),(85,Y)]*2)
l=[]
for _ in range(1000):
l += [(bell(20,1), X),(bell(10,1),Y),
(bell(30,1),'Z'),(bell(40,1),'W')]
go(l)
go([(1,X)])
def _sdiv():
"Demo code to test the above."
import random
bell= random.gauss
random.seed(1)
def go(lst,cohen=0.3,
num1=lambda x:x[0],
num2=lambda x:x[1]):
print ""; print sorted(lst)[:10],"..."
for d in sdiv(lst,cohen=cohen,num1=num1,num2=num2):
print d[1][0][0]
l = [ (1,10), (2,11), (3,12), (4,13),
(20,20),(21,21), (22,22), (23,23), (24,24),
(30,30),(31,31), (32,32), (33,33),(34,34)]
go(l,cohen=0.3)
go(map(lambda x:(x[1],x[1]),l))
ten = lambda: bell(10,2)
twenty = lambda: bell(20,2)
thirty = lambda: bell(30,2)
l=[]
for _ in range(1000):
l += [(ten(), ten()),
(twenty(),twenty()),
(thirty(),thirty())]
go(l,cohen=0.5)
def _bootstraped():
def worker(n=1000,
mu1=10, sigma1=1,
mu2=10.2, sigma2=1):
def g(mu, sigma):
return random.gauss(mu, sigma)
x = [g(mu1, sigma1) for i in range(n)]
y = [g(mu2, sigma2) for i in range(n)]
return n, mu1, sigma1, mu2, sigma2, \
'different' if bootstrap(x, y) else 'same'
# very different means, same std
print worker(mu1=10, sigma1=10,
mu2=100, sigma2=10)
# similar means and std
print worker(mu1=10.1, sigma1=1,
mu2=10.2, sigma2=1)
# slightly different means, same std
print worker(mu1=10.1, sigma1=1,
mu2=10.8, sigma2=1)
# different in mu eater by large std
print worker(mu1=10.1, sigma1=10,
mu2=10.8, sigma2=1)
def _fix(self, n=0):
o = random.choice(self.objlist)
if issubclass(o, ASN1_INTEGER):
return o(int(random.gauss(0,1000)))
elif issubclass(o, ASN1_IPADDRESS):
z = RandIP()._fix()
return o(z)
elif issubclass(o, ASN1_STRING):
z = int(random.expovariate(0.05)+1)
return o("".join([random.choice(self.chars) for i in range(z)]))
elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
z = int(random.expovariate(0.08)+1)
return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
return ASN1_INTEGER(int(random.gauss(0,1000)))
##############
#### ASN1 ####
##############
def rnd(shape, mean=0.0, stddev=0.01):
"""Return a list with the given shape with random float elements.
The values are generated from a Gaussian distribution.
Args:
shape (tuple, list): A shape to generate random floats for. 1 or 2 dimensional.
mean (float): Mean of the Gaussian distribution.
stddev (float): Standard deviation of the distribution.
Returns:
list: A list with random float elements with the dimensions specified by `shape`.
"""
if not isinstance(shape, (tuple, list)):
raise TypeError('Invalid shape. The shape must be a tuple or a list.')
dimension = len(shape)
if dimension is 1:
# Create a 1 dimensional array with random elements
return [random.gauss(mean, stddev) for _ in range(shape[0])]
elif dimension is 2:
# Create a 2 dimensional matrix with random elements
return [[random.gauss(mean, stddev) for _ in range(shape[1])] for _ in range(shape[0])]
else:
raise NotImplementedError('Random generation with dimensions > 2 is not yet implemented.')
def _makeFakeTrade(self):
"Generate a realistic-looking trade"
tp = self._t_price
tpf = self._t_price_sigma
tv = self._t_vol
tvf = self._t_vol_sigma
t_exec = self._prev_time + self._frequency
t_update = t_exec + random.uniform(0, self.FAKE_LATENCY)
self._fake_trade_id += 1
self._prev_time = t_update
return Trade(
exchange_id = self.EXCHANGE_ID,
price = tp if tpf is None else random.gauss(tp, tpf),
volume = tv if tvf is None else random.gauss(tv, tvf),
ts_exec = t_exec,
ts_update = t_update,
trade_id = self._fake_trade_id
)
def current(self, deltat=None):
"""Return current wind speed and direction as a tuple
speed is in m/s, direction in degrees."""
if deltat is None:
tnow = time.time()
deltat = tnow - self.tlast
self.tlast = tnow
# update turbulance random walk
w_delta = math.sqrt(deltat) * (1.0 - random.gauss(1.0, self.turbulance))
w_delta -= (self.turbulance_mul - 1.0) * (deltat / self.turbulance_time_constant)
self.turbulance_mul += w_delta
speed = self.speed * math.fabs(self.turbulance_mul)
return (speed, self.direction)
# Calculate drag.
def _fix(self, n=0):
o = random.choice(self.objlist)
if issubclass(o, ASN1_INTEGER):
return o(int(random.gauss(0,1000)))
elif issubclass(o, ASN1_IPADDRESS):
z = RandIP()._fix()
return o(z)
elif issubclass(o, ASN1_STRING):
z = int(random.expovariate(0.05)+1)
return o(bytes([random.choice(self.chars) for i in range(z)]))
elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
z = int(random.expovariate(0.08)+1)
# return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
return o([ x._fix(n+1) for x in [self.__class__(objlist=self.objlist)]*z])
return ASN1_INTEGER(int(random.gauss(0,1000)))
##############
#### ASN1 ####
##############
def create_simple_tree(nevents):
"""Create a simple TTree with a couple of branches."""
t = TTree('aTTree','A TTree')
t.Branch('run', AddressOf(pytree, 'run'),'run/I')
t.Branch('evt', AddressOf(pytree, 'evt'),'evt/I')
t.Branch('x', AddressOf(pytree, 'x'),'x/F')
t.Branch('y', AddressOf(pytree, 'y'),'y/F')
t.Branch('z', AddressOf(pytree, 'z'),'z/F')
for i in range(nevents):
pytree.run = 1 if (i<500) else 2
pytree.evt = i
pytree.x = gauss(0., 10.)
pytree.y = gauss(0, 10.)
pytree.z = gauss(5., 50.)
t.Fill()
return t
def build_normal_distribution(maximum, minimum, mean, deviation, integer=False):
"""
Build a normal distribution to use for randomizing values for input into transformation functions\n
:param maximum: Float or int, The maximum value the value can be]\n
:param minimum: Float or int, The minimum value the value can be\n
:param mean: Float, the mean (mu) of the normal distribution\n
:param deviation: Float, the deviation (sigma) of the normal distribution\n
:param integer: OPTIONAL, whether the value is required to be an integer, otherwise False\n
:return: Float or int, The value to insert into the transform function
"""
value = random.gauss(mean, deviation)
if integer is True:
value = round(value)
if value > maximum:
value = maximum
elif value < minimum:
value = minimum
return value
def _fix(self, n=0):
o = random.choice(self.objlist)
if issubclass(o, ASN1_INTEGER):
return o(int(random.gauss(0,1000)))
elif issubclass(o, ASN1_IPADDRESS):
z = RandIP()._fix()
return o(z)
elif issubclass(o, ASN1_STRING):
z = int(random.expovariate(0.05)+1)
return o("".join([random.choice(self.chars) for i in range(z)]))
elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
z = int(random.expovariate(0.08)+1)
return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
return ASN1_INTEGER(int(random.gauss(0,1000)))
##############
#### ASN1 ####
##############
def _fix(self, n=0):
o = random.choice(self.objlist)
if issubclass(o, ASN1_INTEGER):
return o(int(random.gauss(0,1000)))
elif issubclass(o, ASN1_IPADDRESS):
z = RandIP()._fix()
return o(z)
elif issubclass(o, ASN1_STRING):
z = int(random.expovariate(0.05)+1)
return o(bytes([random.choice(self.chars) for i in range(z)]))
elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
z = int(random.expovariate(0.08)+1)
# return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
return o([ x._fix(n+1) for x in [self.__class__(objlist=self.objlist)]*z])
return ASN1_INTEGER(int(random.gauss(0,1000)))
##############
#### ASN1 ####
##############
def move(self, turn, forward):
if forward < 0:
raise ValueError('Robot cant move backwards')
# turn, and add randomness to the turning command
orientation = self.orientation + float(turn) + random.gauss(0.0, self.turn_noise)
orientation %= 2 * pi
# move, and add randomness to the motion command
dist = float(forward) + random.gauss(0.0, self.forward_noise)
x = self.x + (cos(orientation) * dist)
y = self.y + (sin(orientation) * dist)
x %= world_size # cyclic truncate
y %= world_size
# set particle
res = robot()
res.set(x, y, orientation)
res.set_noise(self.forward_noise, self.turn_noise, self.sense_noise)
return res
def sense(self, add_noise=1):
Z=[]
for i in range(len(landmarks)):
deltay=landmarks[i][0]-self.y
deltax=landmarks[i][1]-self.x
bearing=atan2(deltay, deltax)-self.orientation
if add_noise:
bearing += random.gauss(0.0, self.bearing_noise)
bearing %=2*pi
Z.append(bearing)
return Z
# copy your code from the previous exercise
# and modify it so that it simulates bearing noise
# according to
# self.bearing_noise
############## ONLY ADD/MODIFY CODE ABOVE HERE ####################
# --------
#
# extract position from a particle set
#
def _fix(self, n=0):
o = random.choice(self.objlist)
if issubclass(o, ASN1_INTEGER):
return o(int(random.gauss(0,1000)))
elif issubclass(o, ASN1_IPADDRESS):
z = RandIP()._fix()
return o(z)
elif issubclass(o, ASN1_STRING):
z = int(random.expovariate(0.05)+1)
return o("".join(random.choice(self.chars) for _ in xrange(z)))
elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
z = int(random.expovariate(0.08)+1)
return o([self.__class__(objlist=self.objlist)._fix(n + 1)
for _ in xrange(z)])
return ASN1_INTEGER(int(random.gauss(0,1000)))
##############
#### ASN1 ####
##############
def _fix(self, n=0):
o = random.choice(self.objlist)
if issubclass(o, ASN1_INTEGER):
return o(int(random.gauss(0,1000)))
elif issubclass(o, ASN1_IPADDRESS):
z = RandIP()._fix()
return o(z)
elif issubclass(o, ASN1_STRING):
z = int(random.expovariate(0.05)+1)
return o("".join([random.choice(self.chars) for i in range(z)]))
elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
z = int(random.expovariate(0.08)+1)
return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
return ASN1_INTEGER(int(random.gauss(0,1000)))
##############
#### ASN1 ####
##############
def _fix(self, n=0):
o = random.choice(self.objlist)
if issubclass(o, ASN1_INTEGER):
return o(int(random.gauss(0,1000)))
elif issubclass(o, ASN1_IPADDRESS):
z = RandIP()._fix()
return o(z)
elif issubclass(o, ASN1_STRING):
z = int(random.expovariate(0.05)+1)
return o("".join([random.choice(self.chars) for i in range(z)]))
elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
z = int(random.expovariate(0.08)+1)
return o(map(lambda x:x._fix(n+1), [self.__class__(objlist=self.objlist)]*z))
return ASN1_INTEGER(int(random.gauss(0,1000)))
##############
#### ASN1 ####
##############
def acquireDiskResource(ngamsCfgObj,
slotId):
"""
Acquire access right to a disk resource.
ngamsCfgObj: NG/AMS Configuration Object (ngamsConfig).
slotId: Slot ID referring to the disk resource (string).
Returns: Void.
"""
T = TRACE()
storageSet = ngamsCfgObj.getStorageSetFromSlotId(slotId)
if (not storageSet.getMutex()): return
global _diskMutexSems
if (not _diskMutexSems.has_key(slotId)):
_diskMutexSems[slotId] = threading.Semaphore(1)
code = string.split(str(abs(random.gauss(10000000,10000000))), ".")[0]
logger.debug("Requesting access to disk resource with Slot ID: %s (Code: %s)",
slotId, str(code))
_diskMutexSems[slotId].acquire()
logger.debug("Access granted")
def _fix(self, n=0):
o = random.choice(self.objlist)
if issubclass(o, ASN1_INTEGER):
return o(int(random.gauss(0,1000)))
elif issubclass(o, ASN1_IPADDRESS):
z = RandIP()._fix()
return o(z)
elif issubclass(o, ASN1_STRING):
z = int(random.expovariate(0.05)+1)
return o("".join(random.choice(self.chars) for _ in xrange(z)))
elif issubclass(o, ASN1_SEQUENCE) and (n < 10):
z = int(random.expovariate(0.08)+1)
return o([self.__class__(objlist=self.objlist)._fix(n + 1)
for _ in xrange(z)])
return ASN1_INTEGER(int(random.gauss(0,1000)))
##############
#### ASN1 ####
##############
def _bootstraped():
def worker(n=1000,
mu1=10, sigma1=1,
mu2=10.2, sigma2=1):
def g(mu,sigma) : return random.gauss(mu,sigma)
x = [g(mu1,sigma1) for i in range(n)]
y = [g(mu2,sigma2) for i in range(n)]
return n,mu1,sigma1,mu2,sigma2,\
'different' if bootstrap(x,y) else 'same'
# very different means, same std
print(worker(mu1=10, sigma1=10,
mu2=100, sigma2=10))
# similar means and std
print(worker(mu1= 10.1, sigma1=1,
mu2= 10.2, sigma2=1))
# slightly different means, same std
print(worker(mu1= 10.1, sigma1= 1,
mu2= 10.8, sigma2= 1))
# different in mu eater by large std
print(worker(mu1= 10.1, sigma1= 10,
mu2= 10.8, sigma2= 1))
def gradient(train,
labels,
coef,
bias,
learn_rate,
nepoch):
for epoch in range(nepoch):
sum_error = 0.0
for index in range(len(train)):
pred = predict(train[index], coef, bias)
sum_error += (labels[index] - pred)
bias = (bias + learn_rate * sum_error * pred * (1 - pred))
for i in range(len(coef)):
coef[i] = (coef[i] + learn_rate * sum_error * pred * (1 - pred) * train[index][i])
return coef, bias
#generate standard normal distribution
#TODO the function random.gauss() can not generate stable distribution which causes diffusion gradient
def move(self, turn, forward):
if forward < 0:
raise ValueError, 'Cant move backwards'
self.orientation = self.orientation + turn + random.gauss(0.0, self.turn_noise)
self.orientation %= 2*pi
dist = forward + random.gauss(0.0, self.forward_noise)
self.x = self.x + dist*cos(self.orientation)
self.y = self.y - dist*sin(self.orientation)
self.x %= world_size
self.y %= world_size
temp = robot()
temp.set_noise(0.001, 0.1, 0.1)
temp.set(self.x, self.y, self.orientation)
temp.set_noise(self.forward_noise, self.turn_noise, self.sense_noise)
return temp
def generateRandomData(self, event=None):
print "X-Direction:", self.distribution[0]
print "Y-Direction:", self.distribution[1]
dx = 3
dy = 3
for i in range(int(self.num_pts.get())):
if self.distribution[0] == "Uniform":
x = random.randint(dx, self.canvas.winfo_width() - dx)
else:
# According to Adam Carlson, there's 99.8% chance that data in a normal distribution is within 3 standard deviations of the mean.
# mu = mean, sigma = standard deviation. Look and infer.
x = random.gauss(mu=(self.canvas.winfo_width() - dx) / 2, sigma=self.canvas.winfo_width() / 6)
if self.distribution[1] == "Uniform":
y = random.randint(dy, self.canvas.winfo_height() - dy)
else:
y = random.gauss(mu=(self.canvas.winfo_height() - dy) / 2, sigma=self.canvas.winfo_height() / 6)
# make sure that the coords are not out of bounds!
x %= self.canvas.winfo_width() - dx / 2
y %= self.canvas.winfo_height() - dy / 2
pt = self.canvas.create_oval(x - dx, y - dy, x + dx, y + dy, fill=self.colorOption.get(), outline='')
self.objects.append(pt)
# handle the clear command
def _generate_gradient(self):
# Generate a random unit vector at each grid point -- this is the
# "gradient" vector, in that the grid tile slopes towards it
# 1 dimension is special, since the only unit vector is trivial;
# instead, use a slope between -1 and 1
if self.dimension == 1:
return (random.uniform(-1, 1),)
# Generate a random point on the surface of the unit n-hypersphere;
# this is the same as a random unit vector in n dimensions. Thanks
# to: http://mathworld.wolfram.com/SpherePointPicking.html
# Pick n normal random variables with stddev 1
random_point = [random.gauss(0, 1) for _ in range(self.dimension)]
# Then scale the result to a unit vector
scale = sum(n * n for n in random_point) ** -0.5
return tuple(coord * scale for coord in random_point)