def generateMesh(n_points): points = [] # Simple 2D for initial testing for i in range(n_points): r = random.gauss(10,0.05) theta = random.vonmisesvariate(math.pi,0) phi = random.vonmisesvariate(math.pi, 0) x= r * math.sin(theta) * math.cos(phi) y= r * math.sin(theta) * math.sin(phi) z= r * math.cos(theta) points.append([x,y,z]) # Now just to check we have the target number of unique points nppoints = np.asarray(points) meshgen = pymesh.tetgen(); meshgen.points = nppoints; meshgen.merge_coplanar = True meshgen.coarsening = False meshgen.verbosity = 0 meshgen.run() mesh = pymesh.subdivide(meshgen.mesh, order = 5, method="loop") mesh = meshgen.mesh return(mesh)
def noise_gen(xland, yland, Dely, Delx): # generating von Mises noise around landing location kappa = 1 xout = (rnd.vonmisesvariate(math.pi, kappa) - math.pi) * (Delx / (2 * math.pi)) + xland yout = (rnd.vonmisesvariate(math.pi, kappa) - math.pi) * (Dely / (2 * math.pi)) + yland return [xout, yout]
def do_airstrike(self, x, y, z): if self.name is None: return direction = 1 if self.team.id == 0 else -1 # forward randomization range jitter = (3.0 * direction, 4.0 * direction) spread = 0.6 # symmetric Y up and down radius = 30.0 # maximum reach from ground zero estimate_travel = 32 * z / 64 # to offset spawn coordinates x = max(0, min(511, x - estimate_travel * direction)) grenade_z = 1 self.airstrike_grenade_calls = [] for i in range(10): angle = vonmisesvariate(0.0, 0.0) # fancy for uniform(0, 2*pi) distance = bellrand(-radius, radius) grenade_x = x + cos(angle) * distance grenade_y = y + sin(angle) * distance for j in range(5): grenade_x += uniform(*jitter) grenade_y += uniform(-spread, spread) delay = i * 0.85 + j * 0.11 call = reactor.callLater(delay, self.create_airstrike_grenade, grenade_x, grenade_y, grenade_z) self.airstrike_grenade_calls.append(call)
def selectionbiais(self, x, newlist): # biais de direction if newlist != []: D = Counter( newlist[int(random.vonmisesvariate(mu, kappa) * 4 / np.pi)] for _ in range(nG)) D2 = sorted(D.elements()) else: D2 = [] # biais de position r = [] for u in range(self.nU): y = self.discreteProb(self.P[x, u, :].reshape(self.nX, 1)) r.append(self.r[y]) P = Counter({ N: int(r[0]), S: int(r[1]), E: int(r[2]), W: int(r[3]), NE: int(r[4]), NW: int(r[5]), SE: int(r[6]), SW: int(r[7]), NoOp: int(r[8]) }) P2 = sorted(P.elements()) # choix C = P2 + D2 return C
def generate_random_number(f): """ランダム値を1000個生成 各関数のパラメータは適当に決め打ち。 """ if f == 'random': return [random.random() for n in range(1000)] elif f == 'uniform': return [random.uniform(10, 20) for n in range(1000)] elif f == 'triangular': return [random.triangular(0, 1) for n in range(1000)] elif f == 'betabariate': return [random.betavariate(4, 7) for n in range(1000)] elif f == 'expovariate': return [random.expovariate(1 / 0.5) for n in range(1000)] elif f == 'gammavariate': return [random.gammavariate(4, 7) for n in range(1000)] elif f == 'gauss': return [random.gauss(1, 0.2) for n in range(1000)] elif f == 'gauss': return [random.gauss(1, 0.2) for n in range(1000)] elif f == 'lognormvariate': return [random.lognormvariate(1, 0.2) for n in range(1000)] elif f == 'normalvariate': return [random.normalvariate(1, 0.2) for n in range(1000)] elif f == 'vonmisesvariate': return [random.vonmisesvariate(math.pi / 2, 5) for n in range(1000)] elif f == 'paretovariate': return [random.paretovariate(100) for n in range(1000)] elif f == 'weibullvariate': return [random.weibullvariate(4, 2) for n in range(1000)]
def explode(self): """Exploding the Rocket. """ self.exploded = True for p in range(self.particles_amount): ptype = choice( [SquareParticle, TriangleParticle, CircularParticle]) if self.pattern is not None and callable(self.pattern): speed, angle = self.pattern() else: angle = vonmisesvariate(2 * pi, 0) speed = uniform(0, 80) lifespan = gauss(2, .5) vx = sin(angle) * speed + self.vx vy = cos(angle) * speed + self.vy + 5 self.particles.append( ptype(cv=self.cv, x=self.x, y=self.y, color=self.pcolor, vx=vx, vy=vy, lifespan=lifespan))
def update(self, dt): """Continuously emits new random particles and updates them. Args: dt (float): the time that has passed after the last update (in s). """ self.age += dt for p in self.particles: p.update(dt) self._tospawn += self.rps * dt color = choice(self.colors) for i in range(int(self._tospawn)): angle = uniform(-0.25, 0.25) speed = -uniform(80.0, 200.0) pattern = choice([ lambda: (uniform(0, 80), uniform(-.25, .25) + angle), lambda: (-uniform(0, 80), uniform(-.45, .45) + angle), lambda: (-uniform(20, 80), vonmisesvariate(2 * pi, 0)), None ]) vx = sin(angle) * speed vy = cos(angle) * speed self.particles.append( Rocket(cv=self.cv, x=self.x, y=500, pcolor=color, vx=vx, vy=vy, pattern=pattern)) self._tospawn -= int(self._tospawn)
def randlog(eps): """Return a random complex number, clustered near 0. The value returned has modulus in [eps, 1], with uniformly distributed logarithm. Its argument is uniformly distributed. """ return rect(math.exp(uniform(math.log(eps), 0)), vonmisesvariate(0, 0))
def _execute(self, sources, alignment_stream, interval): if alignment_stream is None: raise ToolExecutionError("Alignment stream expected") for ti, _ in alignment_stream.window(interval, force_calculation=True): yield StreamInstance( ti, random.vonmisesvariate(mu=self.mu, kappa=self.kappa))
def my_Funh(): random.seed() print('random = ', random.random()) print('getstate = ', random.getstate()) state = random.getstate() random.setstate(state) print('setstate = ',random.random()) print('getrandbits = ',random.getrandbits(6)) print('randrange = ',random.randrange(3, 9)) print('randint = ',random.randint(3, 9)) x = 2,1,3,5,4,6,7,8,9,10,6 print('choice = ',random.choice(x) + random.choice(x)+random.choice(x)) mylist = [1, 2, 3,4,5,6,7,8,9,0] random.shuffle(mylist) print('shuffle =',*mylist) print("sample:", *random.sample(x, 8)) print('uniform = ', random.uniform(20, 60)) print('triangular = ',random.triangular(20, 60, 30)) print('betavariate =',random.betavariate(5, 10)) print('expovariate = ',random.expovariate(1.5)) print('gammavariate =',random.gammavariate(100, 2)) print('gauss =',random.gauss(100, 50)) print('lognormvariate =',random.lognormvariate(0, 0.25)) print('normalvariate =',random.normalvariate(0, 0.25)) print('vonmisesvariate = ',random.vonmisesvariate(0,4)) print('paretovariate = ',random.paretovariate(3)) print('weibullvariate = ',random.weibullvariate(1, 1.5)) b = input('New ? (y / n) = ') if b == 'y': my_Funh()
def random_move(self): """ This method should determine the jump length and direction of a specific agent and makes the move. """ while True: max_jump_length = self.determine_max_jump() jump_length = self.determine_jump_length(max_jump_length) bias = self.determine_bias() angle_bias = random.vonmisesvariate(bias, self.model.parameters["kappa"]) pos_change = np.array([ jump_length * np.cos(angle_bias), jump_length * np.sin(angle_bias) ]) new_pos = np.array(self.pos) + pos_change if not self.model.area.out_of_bounds(new_pos): self.model.area.move_agent(self, tuple(new_pos)) break # HIER MOET NOG EEN CHECK KOMEN OF DE AGENT NAAR EEN ANDERE REGIO # VERPLAATST pass
def drop_needle(L): m=random.random() #a=2*3.141592653589793*random.random() a=random.vonmisesvariate(0,0) if abs(math.ceil(m+L*math.sin(a))-math.ceil(m))>0.1: return True else: return False
def drop_needle(L): x0 = random.random() theta = random.vonmisesvariate(0,0) x1 = x0 + L*math.cos(theta) if x1 >= 1 or x1 <= 0: return True else: return False
def randline(): x0 = random.random() a = random.vonmisesvariate(0,0) x1 = x0+l*math.sin(a) if math.floor(x0) != math.floor(x1): return 1 return 0
def habeck_rot(F): ''' Generate a random 3D rotation matrix ''' u, d, v = np.linalg.svd(F) U, D, tV = [np.matrix(x) for x in (u, d, v)] D = D.T if np.linalg.det(U * tV) < 0: U[:, 2] *= -1 D[2] *= -1 lamda1, lamda2, lamda3 = np.array(D).flatten() ### generate Euler angles: Beta_val = 0 kappa_phi = (lamda1 + lamda2) * (cos(Beta_val / 2))**2 kappa_shi = (lamda1 - lamda2) * (sin(Beta_val / 2))**2 phi = random.uniform( 0, 2 * pi) if kappa_phi == 0 else random.vonmisesvariate(0, kappa_phi) shi = random.uniform( 0, 2 * pi) if kappa_shi == 0 else random.vonmisesvariate(0, kappa_shi) u = float(np.random.binomial(1, 0.5, size=1)) alpha = 0.5 * (phi + shi) + pi * u gamma = 0.5 * (phi - shi) + pi * u kappa_Beta = (lamda1 + lamda2) * cos(phi) + ( lamda1 - lamda2) * cos(shi) + 2 * lamda3 r = random.uniform(0, 1) x = 1 + 2 * log(r + (1 - r) * exp(-kappa_Beta)) / kappa_Beta Beta_val = acos(x) ### build rotation matrix: a11 = cos(alpha) * cos(Beta_val) * cos(gamma) - sin(alpha) * sin(gamma) a21 = -cos(alpha) * cos(Beta_val) * sin(gamma) - sin(alpha) * cos(gamma) a31 = cos(alpha) * sin(Beta_val) a12 = sin(alpha) * cos(Beta_val) * cos(gamma) + cos(alpha) * sin(gamma) a22 = -sin(alpha) * cos(Beta_val) * sin(gamma) + cos(alpha) * cos(gamma) a32 = sin(alpha) * sin(Beta_val) a13 = -sin(Beta_val) * cos(gamma) a23 = sin(Beta_val) * sin(gamma) a33 = cos(Beta_val) S = np.matrix([[a11, a12, a13], [a21, a22, a23], [a31, a32, a33]]) R = U * S * tV return R
def drop_needle(L): x0 = random.random() a = random.vonmisesvariate(0,0) x1 = x0 + L*math.cos(a) if x1>0: if x1<1: return False return True
def naald(L): x=random.random() a=random.vonmisesvariate(0,0) eind=x+L*math.cos(a) if eind <= 1 and eind >= 0: return False else: return True
def drop_needle(L): x1 = random.random() hoek = random.vonmisesvariate(0,0) x2 = x1 + L * math.sin(hoek) if x2 > 1 or x2 < 0: return True else: return False
def drop_needle(L): x = random.random() a = random.vonmisesvariate(0,0) x2 = (x + L*math.cos(a)) if x2 > 1 or x2 < 0: return True else: return False
def drop_needle(l): x0 = random.random() a = random.vonmisesvariate(0,0) xeind = x0+l*math.cos(a) if xeind <0 or xeind >1: return True else: return False
def update_non_amcl(self, scan, pf): self.weight_particles(scan, pf) resampledPoses = [] notAccepted = True numParticles = len(pf.particlecloud.poses) #Resamples the poses for i in range(0,numParticles): notAccepted = True while (notAccepted): index = random.randint(0,numParticles-1) posX = pf.particlecloud.poses[index].position.x posY = pf.particlecloud.poses[index].position.y if (random.uniform(0,1) < particleWeights[index]/totalWeight): notAccepted = False resampledPoses.append(pf.particlecloud.poses[index]) cont = True pArray = PoseArray() temp = [] val = Pose() count = 0 #Smudges the poses while cont: temp = [] val = resampledPoses[0] count = 0 #Removes the duplicate poses from the list for i in range(0, len(resampledPoses)): if (resampledPoses[i] == val): count = count + 1 else: temp.append(resampledPoses[i]) resampledPoses = temp #Checks that we have allocated all particles to be smudged if (len(resampledPoses) == 0): cont = False #Apply smuding to all but one of the same resampled particle for i in range(0, count): if i > 0: newPose = Pose() newPose.position.x = random.gauss(val.position.x, 0.35) #TEST THIS newPose.position.y = random.gauss(val.position.y, 0.35) newPose.orientation = rotateQuaternion(val.orientation, random.vonmisesvariate(0, 7)) #MAKE SURE TO TEST pArray.poses.append(newPose) else: pArray.poses.append(val) return pArray
def drop_needle(L) : x = random.random() a = random.vonmisesvariate(0,0) x1 = x + L * math.cos(a) if x1 <= 0 or x1 >= 1: return(True) else: return(False)
def random_sensor_data(): max_position = query.get_track_length('Tracks', random.choice(query.get_collection_docs('Tracks'))) max_position_int = int(max_position) position = random.randrange(2000,max_position_int) angle = random.vonmisesvariate(180,0)*(180/3.14) humidity = [random.randint(0,100)] temperature = [random.randint(15,40)] data = c_class.Sensor(position,angle,humidity,temperature).to_dict() return data
def drop_needle(integer): x = random.random() a = random.vonmisesvariate(0,0) verschil = math.cos(a) eindpunt = x + (integer * math.cos(a)) if 0 < eindpunt and eindpunt < 1: return False else: return True
def drop_needle(L): x_1 = random.random() hoek = random.vonmisesvariate(0,0) x_2 = x_1 + l*math.cos(hoek) if x_2 > 1 or x_2 < 0: return True else: return False
def drop_neelde(L): x = random.random() y = random.random() a = random.vonmisesvariate(0,0) xEnd = x+L*math.cos(a) yEnd = y+L*math.sin(a) if xEnd<0 or xEnd>1: return True else: return False
def vonmises(): VONMISES_USAGE = 'Usage: ' + url_for('.vonmises') + '?mu=<integer>&kappa=<integer>[k=<integer>&test=true|false]' func = lambda args: random.vonmisesvariate(mu=float(args['mu']), kappa=float(args['kappa'])) + float(request.args.get('k')) validate = lambda args: abort(500, 'kappa must be greater or equal to zero') if float(args['kappa']) < 0 else True mu = request.args.get('mu') kappa = request.args.get('kappa') return get_response(request, VONMISES_USAGE, func, validate, mu=mu, kappa=kappa)
def drop_needle(L): x0 = random.random() theta = random.vonmisesvariate(0,0) xe = x0 + L * math.cos(theta) if xe < 0: return True elif xe > 1: return True return False
def drop_needle(L): x = random.random() theta = random.vonmisesvariate(0,0) end_x = x + L * math.cos(theta) if end_x > 1 or end_x < 0: return True else: return False
def drop_needle(L): x1=random.random() phi=random.vonmisesvariate(0,0) x2=x1+L*math.cos(phi) if x1==1 or x1==0: return True elif x2<=0 or x2>=1: return True else: return False
def drop_needle(L): x0 = random.random() y0 = random.random() angle = random.vonmisesvariate(0,0) punt2 = (x0+L*math.cos(angle),y0+L*math.sin(angle)) if punt2[0]<=0 or punt2[0]>=1: hit = True else: hit = False return hit
def drop_needle(L): startX = random.random() + L #startY = random.random() angle = random.vonmisesvariate(0,0) endX = startX + L*math.cos(angle) #endY = startY + L*math.sin(angle) diffX = abs(int(startX) - int(endX)) #print("xb:", startX, "xe:", endX, "=", diffX) return diffX > 0
def drop_needle(L): # uniform in [0,1] x0 = random.random() # uniform in [0,2pi] a = random.vonmisesvariate(0,0) x1 = x0 + L*math.cos(a) if x1>0: if x1<1: return False return True
def drop_needle(L): needleX = random.random() angle = random.vonmisesvariate(0,0) needleX2 = needleX + L* math.cos(angle) if needleX2 > 1 or needleX2 < 0: #print(needleX, angle, needleX2) return True else: return False
def drop_needle(L): # uniform in [0,1] x1 = random.random() # uniform in [0,2pi] a = random.vonmisesvariate(0,0) x2 = x1+L*math.sin(a) if x2>=1 or x2<=0: return True else: return False
def drop_needle(L): needleX = random.random() angle = random.vonmisesvariate(0, 0) needleX2 = needleX + L * math.cos(angle) if needleX2 > 1 or needleX2 < 0: #print(needleX, angle, needleX2) return True else: return False
def drop_needle(L): # uniform in [0,1] x0 = random.random() # uniform in [0,2\pi] a = random.vonmisesvariate(0,0) xeind = x0 + L * math.cos(a) if xeind < 0 or xeind > 1: return True else: return False
def drop_needle(L): x = random.random() y = random.random() a = random.vonmisesvariate(0,0) x1 = x + L * math.cos(a) y1 = y + L * math.sin(a) if (x >= 0 and x1 < 0) or (x < 1 and x1 >= 1): return True return False
def drop_needle(L): x0 = random.random() y0 = random.random() a = random.vonmisesvariate(0,0) x1 = x0 + L*math.cos(a) y1 = y0 + L*math.sin(a) if x1 >= 1 or x1 <= 0: return True else: return False
def drop_needle(L) : #aslongasitsnotsoap x = random.random() y = random.random() a = random.vonmisesvariate(0,0) x2 = x + L * math.cos(a) y2 = y + L * math.sin(a) #check if it crosses the line if (x >= 0 and x2 < 0) or (x < 1 and x2 >= 1) : return True return False
def drop_needle(L): x_0 = random.random() #uniform in [0,1] # y_0 = random.random() a = random.vonmisesvariate(0,0) #uniform in [0, 2*pi] x_1 = x_0 + L*math.cos(a) # y_1 = y_0 + L*math.sin(a) if x_1 >= 1: return True elif x_1 <= 0: return True else: return False
async def random_von_mises_variate_command(self, ctx, mu: float, kappa: float): """ Mu is the mean angle, expressed in radians between 0 and 2*pi, and kappa is the concentration parameter, which must be greater than or equal to zero. If kappa is equal to zero, this distribution reduces to a uniform random angle over the range 0 to 2*pi. """ try: await ctx.send(random.vonmisesvariate(mu, kappa)) except Exception as ex: await self._error(ctx, ex)
def NewHeading(heading): """ Draws a new heading based on the current heading """ coinflip = random.random() if coinflip <= p: heading = random.vonmisesvariate(heading, kappa1) # draw new heading from forward van mises distribution else: if heading >= numpy.pi: heading = random.vonmisesvariate(heading - numpy.pi, kappa2) else: heading = random.vonmisesvariate(2 * numpy.pi + (heading - numpy.pi), kappa2) return heading
def move_SBLN(self): """ """ while True: # First determines maximum possible jump lenght x, y = self.pos road_dens = self.model.config.road_dens[int(y), int(x)] H = ((1 - road_dens) * self.model.upper_max_jump + self.model.lower_max_jump) # Inverse random sampling bounded pareto distribution (jump length) L, k = self.min_jump, self.bounded_pareto U = random.uniform(0, 1) jump = ((-(U * H**k - U * L**k - H**k) / (H**k * L**k))**(-1 / k)) # Copies gang information for coordinates set spaces gang_info = self.model.config.gang_info.copy() bias_home_x, bias_home_y = self.bias_home(gang_info) bias_rivals_x, bias_rivals_y = self.bias_rivals(gang_info) bias_x = bias_home_x + bias_rivals_x bias_y = bias_home_y + bias_rivals_y bias = 0 if bias_x: bias = math.atan(bias_y / bias_x) else: bias = math.pi / 2 # Determine angle direction movement agent angle_bias = random.vonmisesvariate(bias, self.kappa) change_x = jump * math.cos(angle_bias) change_y = jump * math.sin(angle_bias) old_region = self.model.config.areas[(int(x), int(y))] x += change_x y += change_y if not self.model.area.out_of_bounds((x, y)): new_region = self.model.config.areas[(int(x), int(y))] if new_region == 24: continue boundaries = self.model.config.boundaries[old_region, new_region] chance = self.beta**boundaries if random.uniform(0, 1) < chance: self.model.area.move_agent(self, (x, y)) # self.model.grid.move_agent(self, (int(x), int(y))) break
def angle_jittered_line(self, line): """ """ if geom.is_zero(self.angle_jitter): return line # This produces a random angle between -pi and pi kappa = self.angle_jitter_kappa norm_angle = random.vonmisesvariate(math.pi, kappa) - math.pi jitter_angle = norm_angle * self.angle_jitter / math.pi if not geom.is_zero(jitter_angle): mat = transform2d.matrix_rotate(jitter_angle, origin=line.midpoint()) line = line.transform(mat) return line
def myVonMises(mean, kappa): # WARNING!! in Python version 2.7.3, vonmisesvariate(0,K) variates from # -pi to +pi. This bug (as in the official documentation it goes well from # 0 to 2*pi) was fixed in Pyhton 2.7.4 if sys.version_info <= (2, 7, 3): vmrv = random.vonmisesvariate(0, kappa) / math.pi else: vmrv = random.vonmisesvariate(math.pi, kappa) / math.pi - 1 # vmrv = a von-Mises random variable between -1 and 1, mean = 0 r = vmrv * float(1 - mean) # r is in [- 1 + mean, + (1 - mean)] r = r + mean # r is in [-1 + 2 * mean, 1] if r < 0: # abs(r) is in [0, 1 - 2 * mean] return mean * abs(r) / (1 - 2 * mean) elif r <= 1: return r else: print(r, file=sys.stderr) raise ValueError('this case should not happen' + "mean=%s, kappa=%s and r=%s" % (mean, kappa, r))
def get_random_timeseries(configuration): """ @param configuration: timeseries configuration defining attributes of data points @return: a list of randomly generated data points based on given configuration """ samples = [] type = configuration.get('type', 'uniform') if type == 'triangular': for index in xrange(get_num_points(configuration)): samples.append( random.triangular(low=get_signal_min(configuration), high=get_signal_max(configuration))) else: for index in xrange(get_num_points(configuration)): datapoint = 0 if type == 'uniform': datapoint = random.random() elif type in ['betavariate', 'gammavariate', 'weibullvariate']: datapoint = call_obj_method( type, { 'alpha': configuration.get('alpha', 1.0), 'beta': configuration.get('beta', 1.0) }) elif type in ['gauss', 'normalvariate', 'lognormvariate']: datapoint = call_obj_method( type, { 'mu': configuration.get('mu', 0.0), 'sigma': configuration.get('sigma', 1.0) }) elif type == 'expovariate': datapoint = random.expovariate( lambd=configuration.get('lambda', 1.0)) elif type == 'vonmisesvariate': datapoint = random.vonmisesvariate( mu=configuration.get('mu', 0.0), kappa=configuration.get('kappa', 1.0)) elif type == 'paretovariate': datapoint = random.paretovariate( alpha=configuration.get('alpha', 1.0)) samples.append(datapoint) samples = scale_signal(samples, configuration).tolist() return samples
def __call__(self): """ Generate a random vector sampled from the current Von Mises distribution. @return: random angle @rtype: float """ try: value = vonmisesvariate(float(self.mu), float(self.k)) except: print("ERROR: vonmisesvariate(%s,%s)" % (float(self.mu), float(self.k))) raise return mod2pi(value)
def randomXValue(tag, params): if tag == "normal": mu = number(params.get("mu", 0.0)) sigma = number(params.get("sigma", 1.0)) return XValue(lambda: random.normalvariate(mu, sigma)) if tag == "pnormal": mu = number(params.get("mu", 0.0)) sigma = number(params.get("sigma", 1.0)) return XValue(lambda: max(random.normalvariate(mu, sigma), 0.0)) elif tag == "uniform": mn = number(params.get("min", 0.0)) mx = number(params.get("max", 1.0)) return XValue(lambda: random.uniform(mn, mx)) elif tag == "triangular": low = number(params.get("low", 0.0)) high = number(params.get("high", 1.0)) mode = number(params.get("mode", 1.0)) return XValue(lambda: random.triangular(low, high, mode)) elif tag == "beta": alpha = number(params.get("alpha", 0.0)) beta = number(params.get("beta", 1.0)) return XValue(lambda: random.betavariate(alpha, beta)) elif tag == "gamma": alpha = number(params.get("alpha", 0.0)) beta = number(params.get("beta", 1.0)) return XValue(lambda: random.gammavariate(alpha, beta)) elif tag == "lognormal": mu = number(params.get("mu", 0.0)) sigma = number(params.get("sigma", 1.0)) return XValue(lambda: random.lognormvariate(mu, sigma)) elif tag == "vonmises": mu = number(params.get("mu", 0.0)) kappa = number(params.get("kappa", 1.0)) return XValue(lambda: random.vonmisesvariate(mu, kappa)) elif tag == "pareto": alpha = number(params.get("alpha", 0.0)) return XValue(lambda: random.paretovariate(alpha)) elif tag == "weibull": alpha = number(params.get("alpha", 0.0)) beta = number(params.get("beta", 1.0)) return XValue(lambda: random.weibullvariate(alpha, beta)) elif tag == "exponential": lamda = number(params.get("lambda", 1.0)) return XValue(lambda: random.expovariate(lamda)) else: raise InvalidXMLException("unsupported attribute value")
def from_parameters(cls, N, data_params=default_data_parameters, hypers=None, gen_seed=0): """ Initialize a continuous component model with sufficient statistics generated from random data. Inputs: N: the number of data points data_params: a dict with the following keys mu: the mean of the data kappa: the precision of the data hypers: a dict with the following keys a: the prior precision of the mean b: the prior mean of the kappa: precision parameter gen_seed: an integer from which the rng is seeded """ check_model_params_dict(data_params) data_kappa = data_params['kappa'] data_mean = data_params['mu'] random.seed(gen_seed) X = [[ random.vonmisesvariate(data_mean - math.pi, data_kappa) + math.pi ] for i in range(N)] X = numpy.array(X) check_data_type_column_data(X) if hypers is None: hypers = cls.draw_hyperparameters(X, n_draws=1, gen_seed=next_seed())[0] check_hyperparams_dict(hypers) sum_sin_x = numpy.sum(numpy.sin(X)) sum_cos_x = numpy.sum(numpy.cos(X)) hypers['fixed'] = 0.0 return cls(hypers, float(N), sum_sin_x, sum_cos_x)
def myVonMises(mean, kappa): # vonmisesvariate returns a value between 0 and 2*pi. We want a value # between -1 and 1 (mean 0) vmrv = random.vonmisesvariate(math.pi, kappa) / math.pi - 1 r = vmrv * float(1 - mean) # r is in [- 1 + mean, + (1 - mean)] r = r + mean # r is in [-1 + 2 * mean, 1] if r < 0: # abs(r) is in [0, 1 - 2 * mean] return mean * abs(r) / (1 - 2 * mean) elif r <= 1: return r else: print(r, file=sys.stderr) raise ValueError('this case should not happen' + "mean=%s, kappa=%s and r=%s" % (mean, kappa, r))
def rand_particles(self, N): ret = PoseArray() width = self.occupancy_map.info.width height = self.occupancy_map.info.height particles = 0 while particles < N: generated_angle = random.vonmisesvariate(mu=0, kappa=0) x = random.randint(0, width - 1) # maybe use gauss y = random.randint(0, height - 1) new_pose = Pose() new_pose.position.x = x * 0.05 new_pose.position.y = y * 0.05 new_pose.orientation = rotateQuaternion(Quaternion(w=1.0), generated_angle) if self.occupancy_map.data[x + y * width] == 0: ret.poses.append(new_pose) particles += 1 return ret
def funs(): # seed(a=None, version=2) // 初始换生成器的随机数 random.seed() random.getstate() # 获取生成器内部状态 random.setstate(random.getstate()) # 设置生成器内部状态 # 获取随机数 num = random.getrandbits(8) # 获取x位(bit)随机整数 # randrange(stop) / randrange(start, stop[, step]) // 生成随机整数 num = random.randrange(0, 100, 2) # [0,100)产生的随机整数+2 # randint(a, b) == randrange(a, b + 1) // [a, b] num = random.randint(0, 1) fnum = random.random() # 获取浮点随机数 [0.0, 1.0) fnum = random.uniform(1, 2) # 获取指定范围内的浮点随机数 [1.0, 2.0) # triangular(low, high, mode) // 获取随机浮点数, low低边界(默认0),high高边界(默认1),模式(默认边界中点) fnum = random.triangular(0, 1, 1.5) # betavariate(alpha, beta) // Beta分布,[0.0, 1.0] fnum = random.betavariate(1, 1) # expovariate(lambd) // 指数分布, lambd返回整,值[0, +∞]; lanbd返回负,值[-∞, 0] fnum = random.expovariate( (lambda arg1, arg2: arg1 + arg2)(1, 2)) # lambd返回值越小,获得值越大 # gammavariate(alpha, beta) // 伽玛分布 fnum = random.gammavariate(1, 1) # gauss(mu, sigma) // 高斯分布 mu:平均值, sigma:标准偏差 fnum = random.gauss(1, 1) # lognormvariate(mu, sigma) // 对数正态分布,获得平均值mu和标准偏差sigma的正态分布; mu:任何值,sigma:>0。 fnum = random.lognormvariate(1, 1) # normalvariate(mu, sigma) // 正态分布, mu是平均值, sigma是标准偏差 fnum = random.normalvariate(1, 1) # vonmisesvariate(mu, kappa) // 冯米塞斯分布的随机数。mu:平均角度(弧度[0, 2*pi]), kappa:集中程度>=0 fnum = random.vonmisesvariate(1, 1) # paretovariate(alpha) // 帕累托分布, alpha:形状 fnum = random.paretovariate(1) # weibullvariate(alpha, beta) // 韦伯分布, alpha:缩放, beta:形状 fnum = random.weibullvariate(1, 1) elem = random.choice(lists) # 非空序列中取出随机元素, 序列为空抛IndexError elems = random.sample(lists, 3) # 从列表中随机获取3个元素, 范围>列表大小,抛ValueError # 打乱顺序 random.shuffle(lists) # 打乱序列
def vonmises(): VONMISES_USAGE = 'Usage: ' + url_for( '.vonmises' ) + '?mu=<integer>&kappa=<integer>[k=<integer>&test=true|false]' func = lambda args: random.vonmisesvariate( mu=float(args['mu']), kappa=float(args['kappa'])) + float( request.args.get('k')) validate = lambda args: abort(500, 'kappa must be greater or equal to zero' ) if float(args['kappa']) < 0 else True mu = request.args.get('mu') kappa = request.args.get('kappa') return get_response(request, VONMISES_USAGE, func, validate, mu=mu, kappa=kappa)
def generate_time(): mass = random.uniform(0, sum(p.scale for p in PEAKS)) for i, p in enumerate(PEAKS): if mass < p.scale: break mass -= p.scale # Approximate parameters for von Mises distribution. day = date.today() start = datetime.combine(day, p.start) - datetime.combine(day, time()) mu = ((start + p.duration / 2) / timedelta(days=1) % 1 * (2 * math.pi)) stddev = p.duration / timedelta(days=1) * math.pi r = 1 - stddev * stddev / 2 kappa = r * (2 - r * r) / (1 - r * r) return str((datetime.combine(day, time()) + timedelta(days=random.vonmisesvariate(mu, kappa) / (2 * math.pi))).time())
def getnextlocation(x, y, g_mu, g_sig, v_mu, v_kap): ret_x = 0 ret_y = 0 v_mu_rad = math.pi * v_mu / 180 dist = random.normalvariate(g_mu, g_sig) ang = random.vonmisesvariate(abs(v_mu_rad), v_kap) sin_val = abs(math.sin(abs(ang))) cos_val = abs(math.cos(abs(ang))) add_x = dist * cos_val add_y = dist * sin_val if v_mu_rad < 0: add_y = -1 * add_y if abs(ang) > (math.pi / 2): add_x = -1 * add_x ret_x = x + add_x ret_y = y + add_y return ret_x, ret_y
def read_sensors(): ''' generate random data simulating sensors. returns: -temperature -humidity -wind_direction -wind_intensity -rain_height ''' gaussian_noise = r.gauss(GLOBAL_PARAMS.NOISE_MEAN, GLOBAL_PARAMS.NOISE_STD) temperature = r.uniform(GLOBAL_PARAMS.TEMP_MIN, GLOBAL_PARAMS.TEMP_MAX) + gaussian_noise temperature = clip_value(GLOBAL_PARAMS.TEMP_MIN, GLOBAL_PARAMS.TEMP_MAX, temperature) # (-50 ... 50 Celsius) gaussian_noise = r.gauss(GLOBAL_PARAMS.NOISE_MEAN, GLOBAL_PARAMS.NOISE_STD) humidity = r.gauss(GLOBAL_PARAMS.HUM_MEAN, GLOBAL_PARAMS.HUM_STD) + gaussian_noise humidity = clip_value(GLOBAL_PARAMS.HUM_MIN, GLOBAL_PARAMS.HUM_MAX, humidity) # (0 ... 100%) wind_direction = math.degrees( r.vonmisesvariate(GLOBAL_PARAMS.WIND_D_MU, GLOBAL_PARAMS.WIND_D_K)) gaussian_noise = r.gauss(GLOBAL_PARAMS.NOISE_MEAN, GLOBAL_PARAMS.NOISE_STD) wind_intensity = r.uniform(GLOBAL_PARAMS.WIND_I_MIN, GLOBAL_PARAMS.WIND_I_MAX) + gaussian_noise wind_intensity = clip_value(GLOBAL_PARAMS.WIND_I_MIN, GLOBAL_PARAMS.WIND_I_MAX, wind_intensity) # (0 ... 100 m/s) gaussian_noise = r.gauss(GLOBAL_PARAMS.NOISE_MEAN, GLOBAL_PARAMS.NOISE_STD) rain_height = r.triangular( GLOBAL_PARAMS.RAIN_H_LOW, GLOBAL_PARAMS.RAIN_H_HIGH, GLOBAL_PARAMS.RAIN_H_MODE) + gaussian_noise # (0 ... 50 mm / h) rain_height = clip_value(GLOBAL_PARAMS.RAIN_H_MIN, GLOBAL_PARAMS.RAIN_H_MAX, rain_height) return temperature, humidity, wind_direction, wind_intensity, rain_height
def generate_sample_pose(source_pose, noise): """ Generates a new pose around a source one, adding noise to it :param source_pose: (geometry_msgs.msg.Pose) the pose around the new one will be created :param noise: (float) noise added to the pose :return: (geometry_msgs.msg.Pose) The new pose """ new_pose = Pose() # Generate random x and y based on a gaussian distribution, adding noise afterwards new_pose.position.x = random.gauss(source_pose.position.x, noise) new_pose.position.y = random.gauss(source_pose.position.y, noise) new_pose.position.z = 0 heading = getHeading(source_pose.orientation) # Get the heading of the source pose new_pose.orientation.w = 1 # Set the orientation of the new pose by rotating an Pose with the heading of 0 by a random value # generated according to a Von Misses distribution (in radians) new_pose.orientation = rotateQuaternion( new_pose.orientation, random.vonmisesvariate(heading, 35) ) return new_pose
def test_von_mises_large_kappa(self): # Issue #17141: vonmisesvariate() was hang for large kappas random.vonmisesvariate(0, 1e15) random.vonmisesvariate(0, 1e100)