def run(self): data = list() fig = plt.figure() fig2 = plt.figure() ax3 = fig.add_subplot(111, projection='3d') ax2 = fig2.add_subplot(111) for i in range(0, 500): x = -1 + (2 * random.random()) y = -1 + (2 * random.random()) z = random.normal(-3, 2) / 10 ax2.scatter(x, y, c="r", s=6) ax3.scatter(x, y, z, c="r", s=6) data.append((x, y, z, "b")) for i in range(0, 500): x = -1 + (2 * random.random()) y = -1 + (2 * random.random()) z = random.normal(3, 2) / 10 ax2.scatter(x, y, c="b", s=6) ax3.scatter(x, y, z, c="b", s=6) data.append((x, y, z, "r")) plt.show() return (data)
def _determine_base_personality_feature(self, feature_type): """Determine a value for a Big Five personality trait.""" config = self.person.cosmos.config # Determine whether feature will be inherited feature_will_get_inherited = ( self.person.biological_mother and random.random() < config.big_five_heritability_chance[feature_type] ) # Inherit a feature value if feature_will_get_inherited: # Inherit this trait (with slight variance) takes_after = random.choice([self.person.biological_father, self.person.biological_mother]) feature_value = normal( self._get_a_persons_feature_of_type(person=takes_after, feature_type=feature_type), config.big_five_inheritance_sd[feature_type] ) # Generate a feature value else: takes_after = None # Generate from the population mean feature_value = normal( config.big_five_mean[feature_type], config.big_five_sd[feature_type] ) # Clamp the value if feature_value < config.big_five_floor: feature_value = config.big_five_floor elif feature_value > config.big_five_cap: feature_value = config.big_five_cap # Cast the feature value as a Feature object feature_object = Feature(value=feature_value, inherited_from=takes_after) return feature_object
def g2plusplus(x0, y0, a, b, sd, eta, rho, phi0, phi_t, dt, N, steps, t, T): T_index = int(T / dt) t_index = int(t / dt) steps = T_index - t_index x = zeros((N, steps + 1)) y = zeros((N, steps + 1)) r = zeros((N, steps + 1)) x[:, 0] = x0 y[:, 0] = y0 r[:, 0] = x0 + y0 + phi0 dW_1 = sqrt(dt) * random.normal(0, 1, int(N / 2) * steps).reshape( int(N / 2), steps) dW_1 = concatenate((dW_1, -dW_1), axis=0) dW_2 = sqrt(dt) * random.normal(0, 1, int(N / 2) * steps).reshape( int(N / 2), steps) dW_2 = concatenate((dW_2, -dW_2), axis=0) #dW = sqrt(dt)*z for i in range(1, steps + 1, 1): x[:, i] = x[:, i - 1] - a * x[:, i - 1] * dt + sd * dW_1[:, i - 1] y[:, i] = y[:, i - 1] - b * y[:, i - 1] * dt + eta * ( rho * dW_1[:, i - 1] + sqrt(1 - rho * rho) * dW_2[:, i - 1]) r[:, i] = x[:, i] + y[:, i] + phi_t return (r, x, y)
def def_pos(self,distance,k): major_axis = True # Project along major or minor axes? # Load Ellipticity Data for 100 Halos pkl_file = open(self.root+'/nkern/Stacking/Halo_Shape/100_halo_ellipticities.pkl','rb') input = pkl.Unpickler(pkl_file) d = input.load() eig_vec = d['eig_vec'] eig_val = d['eig_val'] # Define theta and phi for unit vector and construt unit vector in cartesian coordinates if major_axis == True: eig_vec = eig_vec[k][0] r = norm(eig_vec) theta = np.arccos(eig_vec[2]/r) phi = np.arctan(eig_vec[1]/eig_vec[0]) if major_axis == False: eig_vec = eig_vec[k][1] r = norm(eig_vec) theta = np.arccos(eig_vec[2]/r) phi = np.arctan(eig_vec[1]/eig_vec[0]) # if random.random()<.5: # eig_vec *= -1. theta = random.normal(theta,.075) phi = random.normal(phi,.075) x = np.sin(theta)*np.cos(phi) y = np.sin(theta)*np.sin(phi) z = np.cos(theta) unit = np.array([x,y,z])/norm(np.array([x,y,z])) return unit*distance
def BenignTraffic(): background = random.uniform(1000,10000) benign_traffic = {'SYN':0,'DATA':0} #Total Connections = Page views per user * Number of users of the website (5.54 * 1821.6*10^3) #Number of users of the website = (Reach per million * total internet users)/10^6 = (414*4.4*10^9)/10^6 benign_traffic['SYN'] = random.normal(10092000,3129000) #Assuming the data traffic is 5 times the SYN connections received benign_traffic['DATA'] = random.normal(10092000,3129000)*5 return background, benign_traffic
def getNextColor(index): #get color palate if index < len(rgb_colors): return rgb_colors[index] else: index_mod = index % len(rgb_colors) r, g, b = rgb_colors[index_mod] r = max(min(random.normal(r, 25), 255), 0) g = max(min(random.normal(g, 25), 255), 0) b = max(min(random.normal(b, 25), 255), 0) return (r, g, b)
def generate_particle(self): p = Particle() if self.biased_particles > 0: p.pose.x = random.normal(self.normalx) p.pose.y = random.normal(self.normaly) p.pose.theta = random.normal(self.normalt) else: p.pose.x = random.uniform(self.min_x, self.max_x) p.pose.y = random.uniform(self.min_y, self.max_y) p.pose.theta = random.uniform(-math.pi, math.pi) self.biased_particles -= 1 p.weight = 0.0 return p
def create_sample_atom(inNumberOfAtoms, inAtomType): """Creates a mostly spherical atom with inNumberOfAtoms atoms and all of element inAtomType. inAtomType MUST BE A STRING. For example, 'Pt79' for Platinum and 79 atoms.""" positionList = [] halfOfRadius = 3 standardDeviation = 1.65 for x in range(0, inNumberOfAtoms): atomX = random.normal(halfOfRadius, standardDeviation) * plusOrMinus() atomY = random.normal(halfOfRadius, standardDeviation) * plusOrMinus() atomZ = random.normal(halfOfRadius, standardDeviation) * plusOrMinus() positionList.append((atomX, atomY, atomZ)) sample_atom = Atoms(inAtomType, numpy.asarray(positionList)) return sample_atom
def _init_generate_physical_attributes(self): """Generate physical attributes for this person.""" # Prepare these now, for speedier access config = self.person.cosmos.config year = self.person.cosmos.year male = self.person.male # Determine age of physical peak, i.e., baseball prime self.age_of_physical_peak = config.determine_age_of_physical_peak() # Determine handedness self.lefty = True if random.random() < config.chance_of_being_left_handed else False self.righty = not self.lefty self.left_handed = 1.0 if self.lefty else 0.0 self.right_handed = 1.0 if self.righty else 0.0 # Determine hustle self.hustle = config.determine_hustle() # Determine adult height this person will attain, in inches if male: self.adult_height = normal( config.adult_male_height_mean(year=year), config.adult_male_height_sd(year=year) ) else: self.adult_height = normal( config.adult_female_height_mean(year=year), config.adult_female_height_sd(year=year) ) # Determine this person's BMI TODO BMI INCREASES AS ADULTHOOD PROGRESSES if male: self.bmi = normal( config.young_adult_male_bmi_mean(year=year), config.young_adult_male_bmi_sd(year=year) ) else: self.bmi = normal( config.young_adult_female_bmi_mean(year=year), config.young_adult_female_bmi_sd(year=year) ) # Determine propensities for coordination, reflexes, agility, jumping... self.coordination_propensity = config.determine_coordination_propensity() self.reflexes_propensity = config.determine_reflexes_propensity( coordination_propensity=self.coordination_propensity ) self.agility_propensity = config.determine_agility_propensity() self.jumping_propensity = config.determine_jumping_propensity() # Number of inches added/subtracted to base # ...and finally footspeed propensity, which is a bit more convoluted to compute primitive_coordination = config.determine_primitive_coordination(bmi=self.bmi) if self.bmi > 24 else 1.0 adult_coordination = primitive_coordination * self.coordination_propensity primitive_footspeed = config.determine_primitive_footspeed( coordination=adult_coordination, height=self.adult_height ) self.footspeed_propensity = config.determine_footspeed_propensity(primitive_footspeed=primitive_footspeed) # Finally, fit these potentials to the person's current age self.develop()
def getRandom_1(inf, sup): mu = (inf + sup) / 2 sigma = (sup - inf) / 6 res = .0 while not (inf < res < sup): res = normal(mu, sigma) return res
def cir_r(r0, sd, t, T, r_bar, kappa, dt, N): # Initialize the seed so that every simulation can have the same process of random numbers # ==> Needed for the duration and convexity calculation random.seed(123456789) # Calculate the steps for the simulation T_index = int(T / dt) t_index = int(t / dt) steps = T_index - t_index # Initialize and generate interest rate paths using antithetic variates method dW = sqrt(dt) * random.normal(0, 1, int(N / 2) * steps).reshape( int(N / 2), steps) dW = concatenate((dW, -dW), axis=0) rates = zeros((N, steps + 1)) rates[:, 0] = r0 # using full truncation method for i in range(1, steps + 1, 1): rates[:, i] = maximum(rates[:, i - 1], 0) + kappa * ( r_bar - maximum(rates[:, i - 1], 0)) * dt + sd * sqrt( maximum(rates[:, i - 1], 0)) * dW[:, i - 1] return rates
def generateSequences(number=1, means = [0.1, 0.3, 0.5, 0.7, 0.9], meanBlockLength=1000, sdBlockLength=200, regLength=100000): from random import gauss as normal for i in xrange(1,number+1): totalLength = 0; sequences = [] for mean in means: loop = 0; while loop < regLength: length = max(0, int(normal( meanBlockLength, sdBlockLength ))) if random() <= mean: sequences.append([totalLength+loop, totalLength+loop+length]) loop += ( length + 2 ) sequences[-1][-1] = min(sequences[-1][-1], totalLength+regLength-1) totalLength += regLength of = open('sim_output_%i.bed' % i, 'w') for entry in sequences: of.write( "name\t%i\t%i\n" % tuple(entry) ) of.close() of = open('sim_lengths.txt', 'w') of.write("name\t0\t%i" % totalLength ) of.close()
def hypersphere(n_dimensions,n_samples=1000,k_space=20,section=False,offset=0,\ offset_dimension=0,noise=False,noise_amplitude=.01,comb_noise=False): random.seed() data = np.zeros((n_samples,k_space)) i = 0 while i < n_samples: j = 0 while j < n_dimensions:# actually seeding Values if section == True: a = random.random() else: a = random.normal(0,1) data[i,j]=a j += 1 norm = np.linalg.norm(data[i]) if noise == False:# making each vector into sphere data[i] = data[i]/norm if noise==True: noise_term = (random.uniform(-1,1) * noise_amplitude) #print(noise_term) data[i] = (data[i]/norm) + noise_term i += 1 if comb_noise == True: for num in range(0, n_samples): for zero_dim in range(n_dimensions, k_space): data[num,zero_dim]= (random.uniform(-1,1) * noise_amplitude) j = offset_dimension if offset != 0: i = 0 while i < n_samples: data[i,j] = offset i += 1 data= pd.DataFrame(data) # print(data) return data
def perturb_particles(self, perturb=True): for i, p in enumerate(self.particles): newpos = array(self.refpos[i]) if perturb: newpos += random.normal(0, self.tau, 3) newpos = IMP.algebra.Vector3D(newpos) IMP.core.XYZ(p).set_coordinates(newpos)
def hypersphere(n_dimensions,n_samples=1000,k_space=20,section=False,offset=0,\ offset_dimension=0,noise=False,noise_amplitude=.01): random.seed() data = np.zeros((n_samples, k_space)) i = 0 while i < n_samples: j = 0 while j < n_dimensions: if section == True: a = random.random() else: a = random.normal(0, 1) data[i, j] = a j += 1 norm = np.linalg.norm(data[i]) if noise == False: data[i] = data[i] / norm if noise == True: noise_term = (random.uniform(-1, 1) * noise_amplitude) print(noise_term) data[i] = (data[i] / norm) + noise_term i += 1 j = offset_dimension if offset != 0: i = 0 while i < n_samples: data[i, j] = offset i += 1 data = pd.DataFrame(data) # print(data) return data
def _continuous_with_edges(neighbors, x_ij, WP, WL): weight = lambda x_kl: WP / (0.01 + (x_ij - x_kl)**2) variance = 0.5 / (sum([weight(z[0]) for z in neighbors]) + WL) mean = 2*variance * (WL*x_ij + sum([weight(z[0]) * z[1] for z in neighbors])) stdev = variance**0.5 z = normal(mean, stdev) return clamp(mean + z*stdev, 0.0, 1.0)
def change_weights(x): p = random.uniform(0, 1) if p < 0.1: gaus = random.normal(0, 0.1) return x + gaus else: return x
def _continuous_with_edges(neighbors, x_ij, WP, WL): weight = lambda x_kl: WP / (0.01 + (x_ij - x_kl)**2) variance = 0.5 / (sum([weight(z[0]) for z in neighbors]) + WL) mean = 2 * variance * (WL * x_ij + sum([weight(z[0]) * z[1] for z in neighbors])) stdev = variance**0.5 z = normal(mean, stdev) return clamp(mean + z * stdev, 0.0, 1.0)
def _continuous(neighbors, x_ij, WP, WL): # Calculate the parameters for our normal distribution (from equations # 8 and 12 in the assignment sheet.) variance = 0.5 / (WP * len(neighbors) + WL) mean = 2 * variance * (WL * x_ij + sum([WP * z[1] for z in neighbors])) stdev = variance**0.5 z = normal(mean, stdev) return clamp(mean + z * stdev, 0.0, 1.0)
def _continuous(neighbors, x_ij, WP, WL): # Calculate the parameters for our normal distribution (from equations # 8 and 12 in the assignment sheet.) variance = 0.5 / (WP * len(neighbors) + WL) mean = 2*variance * (WL*x_ij + sum([WP*z[1] for z in neighbors])) stdev = variance**0.5 z = normal(mean, stdev) return clamp(mean + z*stdev, 0.0, 1.0)
def call_fly_out_or_trap(self, batted_ball): """Call a fielding act either a fly out or a trap.""" # First, determine the crucial timestep, which is the timestep in which the # ball truly landed such that no fly out should be scored -- this will depend on # the rules and whether they allow for bounding fly outs if batted_ball.in_foul_territory: if batted_ball.at_bat.game.rules.foul_ball_on_first_bounce_is_out: if batted_ball.second_landing_timestep: crucial_timestep = batted_ball.second_landing_timestep else: # Ball just plopped down on its first timestep, so there's no chance for # a bounding catch -- as such, give arbitrary high number for crucial timestep, # which will never allow for a FlyOut call crucial_timestep = 999 else: crucial_timestep = batted_ball.landing_timestep else: # elif not batted_ball.in_foul_territory: if batted_ball.at_bat.game.rules.fair_ball_on_first_bounce_is_out: if batted_ball.second_landing_timestep: crucial_timestep = batted_ball.second_landing_timestep else: crucial_timestep = 999 else: crucial_timestep = batted_ball.landing_timestep # Next, determine the true difference, in seconds, between the current timestep, # which is when the fielding act in question has occurred, and the crucial timestep # in which the ball bounced to preclude any true fly out -- negative values represent # the ball landing first, and thus cases where the true call is a trap true_difference_between_ball_landing_and_fielding_act = crucial_timestep - batted_ball.time_since_contact if true_difference_between_ball_landing_and_fielding_act < -0.1: # If the ball landed two or more timesteps ago, it's not even a trap, so # don't bother making a call pass else: if true_difference_between_ball_landing_and_fielding_act > 0: true_call = "Out" else: true_call = "Trap" # To simulate umpire imperfection and inconsistency, pollute the perfect (though # coarse-grained) representation of the difference in time umpire_perceived_difference = normal( true_difference_between_ball_landing_and_fielding_act, 0.04) if umpire_perceived_difference > 0: FlyOutCall( umpire=self, call="Out", true_call=true_call, true_difference= true_difference_between_ball_landing_and_fielding_act, batted_ball=batted_ball) else: FlyOutCall( umpire=self, call="Trap", true_call=true_call, true_difference= true_difference_between_ball_landing_and_fielding_act, batted_ball=batted_ball)
def cir_r(r0, sd, T, N, r_bar, kappa, dt, steps): rates = zeros((N, steps+1)) rates[:, 0] = r0 z = random.normal(0, 1, N*steps).reshape(N, steps) dW = sqrt(dt)*z for i in range(1, steps+1, 1): rates[:, i] = rates[:, i-1] + kappa*(r_bar - rates[:, i-1])*dt + sd*sqrt(rates[:, i-1])*dW[:, i-1] return rates
def GenerateDataset(n): """ GENERATEDATASET generates a sample dataset :param n: (scalar) nb of pts. :param f: (function handle) function along which to sample :return: """ data = np.zeros((n, 3)) # parameters (changable) p = 0.5 # data generation for i in range(0, n): t = rdm.binomial(1, p) data[i, 0] = t data[i, 1] = t * rdm.normal(0, 1) * (1 - t) * rdm.normal(2, 1) data[i, 2] = t * rdm.normal(0, 1) * (1 - t) * rdm.normal(2, 1) return data
def getRandomness(self): if (self.varianceType == "uniform"): return (self.mean + random.randint(0, self.var)) if (self.varianceType == "normal"): return int(round(random.normal(self.mean, self.var))) if (self.varianceType == "exponential"): return int(round(np.random.exponential(self.mean))) else: return 0
def f(x): """ :param x: numpy array st. each row is an observation """ n = x.shape[0] y = [] for i in range(0, n): ni = rdm.normal() y.append(mu + a * (x[i] - Ex) + sig * ni) return np.array(y)
def reset(self): self.sim_time = 0 # satellite state self.pos = 0 self.orbit = 0 self.last_action = None # memory state self.memory_level = 0 self.images = [-1] * self.MEMORY_SIZE self.analysis = [False] * self.MEMORY_SIZE self.satellite_busy_time = 0 # Generate Targets self.initRandomTargets(int(round(random.normal(8, 4)))) # Generate Ground Stations self.initRandomStations(int(round(random.normal(2, 1))))
def vasicek_r(r0, sd, T, N, r_bar, kappa, dt, steps): rates = zeros((N, steps+1)) rates[:, 0] = r0 z = random.normal(0, 1, N*steps).reshape(N, steps) dW = sqrt(dt)*z # r_tk = k*(r_bar - r_tk-1)*dt + sd*sqrt(r_tk-1)*dW(sqrt(dt)*z) for i in range(1, steps+1, 1): rates[:, i] = rates[:, i-1] + kappa*(r_bar - rates[:, i-1])*dt + sd*dW[:, i-1] return rates #np.mean(rates, axis = 0) # not sure 1 path or the entire paths?
def rand_pos(self,distance): '''Picks a random position for the observer a given distance away from the center''' theta = random.normal(np.pi/2,np.pi/4) phi = random.uniform(0,2*np.pi) x = np.sin(theta)*np.cos(phi) y = np.sin(theta)*np.sin(phi) z = np.cos(theta) unit = np.array([x,y,z])/(x**2+y**2+z**2)**(.5) # move the position a random 'distance' Mpc away return distance*unit
def add_student(df): if len(df)==0: studentnum = 1 else: studentnum = df.tail(1)['student'].values[0] + 1 majornum = rand.choice(list(range(0,1000,10))) coursenum = rand.normal(majornum-3,majornum+3) temp = pd.DataFrame({'student':[studentnum],'major':[majornum],'course':[coursenum],'semester':['S1']}) df = pd.concat([df,temp]) for i in range(4): coursenum = rand.normal(majornum-5,majornum+5) for i in range(5): prev_courses = df.tail(5)['course'].values if coursenum in prev_courses: coursenum = rand.normal(majornum-5,majornum+5) temp = pd.DataFrame({'student':[studentnum],'major':[majornum],'course':[coursenum],'semester':['S1']}) df = pd.concat([df,temp]) return df
def generateX(Ex, Vx, n): """ GENERATEX generates the dataset of n points xi st. xi~N(Ex, sqrt(Vx)) :param Ex: (scalar) expectance of x :param Vx: (scalar) variance of x :param n: (scalar) number of wanted samples :return: """ y = [] for i in range(0, n): y.append(rdm.normal(Ex, np.sqrt(Vx))) return np.array(y)
def get_source_radius(default=DEF_RAD, rand=True, uni=True, minm=38 * ONE, maxm=62 * ONE, sd=7): if (rand): if (uni): return random.uniform(minm, maxm) else: return random.normal(default, sd) else: return default
def GaussianNoise(src, means, sigma, percetage): NoiseImg = src NoiseNum = int(percetage * src.shape[0] * src.shape[1]) for i in range(NoiseNum): randX = random.randint(0, src.shape[0] - 1) randY = random.randint(0, src.shape[1] - 1) # NoiseImg[randX, randY] = NoiseImg[randX, randY] + random.gauss(means, sigma) NoiseImg[randX, randY] = NoiseImg[randX, randY] + random.normal(means, sigma) if NoiseImg[randX, randY] < 0: NoiseImg[randX, randY] = 0 elif NoiseImg[randX, randY] > 255: NoiseImg[randX, randY] = 255 return NoiseImg
def fft_random(n): """ Brainless number crunching just to have a substantial task: """ for i in range(n): x = random.normal(0, 0.1, 2000) # y = fft(x) y = 2 * x if (i % 30 == 0): process_percent = int(100 * float(i) / float(n)) current_task.update_state( state='PROGRESS', meta={'process_percent': process_percent}) return random.random()
def call_fly_out_or_trap(self, batted_ball): """Call a fielding act either a fly out or a trap.""" # First, determine the crucial timestep, which is the timestep in which the # ball truly landed such that no fly out should be scored -- this will depend on # the rules and whether they allow for bounding fly outs if batted_ball.in_foul_territory: if batted_ball.at_bat.game.rules.foul_ball_on_first_bounce_is_out: if batted_ball.second_landing_timestep: crucial_timestep = batted_ball.second_landing_timestep else: # Ball just plopped down on its first timestep, so there's no chance for # a bounding catch -- as such, give arbitrary high number for crucial timestep, # which will never allow for a FlyOut call crucial_timestep = 999 else: crucial_timestep = batted_ball.landing_timestep else: # elif not batted_ball.in_foul_territory: if batted_ball.at_bat.game.rules.fair_ball_on_first_bounce_is_out: if batted_ball.second_landing_timestep: crucial_timestep = batted_ball.second_landing_timestep else: crucial_timestep = 999 else: crucial_timestep = batted_ball.landing_timestep # Next, determine the true difference, in seconds, between the current timestep, # which is when the fielding act in question has occurred, and the crucial timestep # in which the ball bounced to preclude any true fly out -- negative values represent # the ball landing first, and thus cases where the true call is a trap true_difference_between_ball_landing_and_fielding_act = crucial_timestep - batted_ball.time_since_contact if true_difference_between_ball_landing_and_fielding_act < -0.1: # If the ball landed two or more timesteps ago, it's not even a trap, so # don't bother making a call pass else: if true_difference_between_ball_landing_and_fielding_act > 0: true_call = "Out" else: true_call = "Trap" # To simulate umpire imperfection and inconsistency, pollute the perfect (though # coarse-grained) representation of the difference in time umpire_perceived_difference = normal(true_difference_between_ball_landing_and_fielding_act, 0.04) if umpire_perceived_difference > 0: FlyOutCall(umpire=self, call="Out", true_call=true_call, true_difference=true_difference_between_ball_landing_and_fielding_act, batted_ball=batted_ball) else: FlyOutCall(umpire=self, call="Trap", true_call=true_call, true_difference=true_difference_between_ball_landing_and_fielding_act, batted_ball=batted_ball)
def generete_2D_points( groups: int = 100, min_num_in_group: int = 10, max_num_in_group: int = 50, precision: int = 9, random_state: int = 123, ) -> None: f = open("2d_points.txt", mode="w", encoding="utf-8") f.write("{} {}\n".format(groups, precision)) seed(random_state) for group in range(groups): num_points = randint(min_num_in_group, max_num_in_group) points = [] for _ in range(num_points): x = round(normal(0, 10), 2) y = round(normal(0, 20), 2) points.append(Point(x, y)) min_dist = round(brute_force(points), precision) f.write("{} {}\n".format(num_points, min_dist)) for point in points: x, y = point.x, point.y f.write(f"{x} {y}\n") f.close()
def multivariate_normal(meanMat, covMat, n): """ this constructs 2D multivariate dist, given a mean and cov list """ from math import sqrt from random import gauss as normal # make sure that the mean and cov entries make sense assert len(meanMat) == 2 assert len(covMat) == 2 assert len(covMat[0]) == 2 assert len(covMat[1]) == 2 # make sure that cov matrix is symmetric assert covMat[0][1] == covMat[1][0] # first, calculate the cholesky decomposition of the cov matrix # I'll use an explicit Cholesky-Crout algorithm since I know it's 2x2 L11 = sqrt(covMat[0][0]) L12 = covMat[0][1] / L11 # I add +0.000001 to covMat[1][1] - L12**2 because rounding errors sometimes # give me very small negative values, and then sqrt raises a domain error # I could use a try-catch, but I like to avoid the overhead since this # is a potentially hot spot in the algorithm - and it doesnt really matter L22 = sqrt(covMat[1][1] - L12**2 + 0.000001) mvn = [[], []] # then I'll build a 2xn vector of MVN random samples for loop in xrange(n): z1 = normal(0, 1) z2 = normal(0, 1) mvn[0].append(meanMat[0] + L11 * z1) mvn[1].append(meanMat[1] + L12 * z1 + L22 * z2) return zip(mvn[0], mvn[1])
def multivariate_normal(meanMat, covMat, n): """ this constructs 2D multivariate dist, given a mean and cov list """ from math import sqrt from random import gauss as normal # make sure that the mean and cov entries make sense assert len(meanMat) == 2 assert len(covMat) == 2 assert len(covMat[0]) == 2 assert len(covMat[1]) == 2 # make sure that cov matrix is symmetric assert covMat[0][1] == covMat[1][0] # first, calculate the cholesky decomposition of the cov matrix # I'll use an explicit Cholesky-Crout algorithm since I know it's 2x2 L11 = sqrt( covMat[0][0] ) L12 = covMat[0][1]/L11 # I add +0.000001 to covMat[1][1] - L12**2 because rounding errors sometimes # give me very small negative values, and then sqrt raises a domain error # I could use a try-catch, but I like to avoid the overhead since this # is a potentially hot spot in the algorithm - and it doesnt really matter L22 = sqrt( covMat[1][1] - L12**2 + 0.000001) mvn = [ [], [] ] # then I'll build a 2xn vector of MVN random samples for loop in xrange(n): z1 = normal(0,1) z2 = normal(0,1) mvn[0].append( meanMat[0] + L11*z1 ) mvn[1].append( meanMat[1] + L12*z1 + L22*z2 ) return zip(mvn[0], mvn[1])
def _init_inherit_physical_attributes(self): """Inherit physical attributes from this person's parents.""" config = self.person.cosmos.config mother, father = self.person.biological_mother, self.person.biological_father parents = (mother.body, father.body) # Handedness if random.random() < config.heritability_of_handedness: takes_after = random.choice(parents) self.left_handed = Feature(value=takes_after.left_handed, inherited_from=takes_after) self.right_handed = Feature(value=takes_after.right_handed, inherited_from=takes_after) # Hustle if random.random() < config.heritability_of_hustle: takes_after = random.choice(parents) inherited_hustle = takes_after.hustle mutated_hustle = normal(inherited_hustle, config.hustle_mutation_sd) self.hustle = Feature(value=mutated_hustle, inherited_from=takes_after) else: pass # TODO SET UP GENERATING FROM NOTHING
def nearlySphericalAtom(definingString, inRadius, number): """definingString should be something like " 'Pt80' ", for example. inRadius should be the radius that you wish to have for the atom. number should be the number of atoms that will be in the molecule.""" positionList = [] for x in range(number): xDistance = random.uniform(0, inRadius) * plusOrMinus() remainingX = ((inRadius ** 2) - (xDistance ** 2)) ** 0.5 yDistance = random.uniform(0, remainingX) * plusOrMinus() zDistance = random.uniform( 0, (((remainingX ** 2) - (yDistance ** 2)) ** 0.5) * plusOrMinus() + random.normal(0, 0.1) ) coordinates = (xDistance, yDistance, zDistance) positionList.append(coordinates) newAtom = Atoms(definingString, positionList) calc = EMT() newAtom.set_calculator(calc) dyn = LBFGSLineSearch(atoms=newAtom) dyn.run(steps=200000) dyn = FIRE(atoms=newAtom) dyn.run(fmax=0.01) return newAtom
def find_best_tau(x, mu): """ returns the value of tau which maximizes normal loglik for a fixed (x,mu) :param x: :param mu: """ if mu == 0: tau = 1. / (mu + 1) else: tau = 1. / mu #starting point ll = Normal(x, mu, tau) i = 0; j = 0 while i < 1000 and j < 100000: taun = tau + random.normal() l = Normal(x, mu, taun) if l > ll: tau = taun ll = l i += 1 j += 1 return tau
def createNoise(nPoints, background,gain,readnoise,exptime,ncombine): """ Create an image with Poisson + Gaussian noise corresponding to the sky background and the exposure time """ import numpy from numpy import random absBackground = background*gain # now in electrons # generate the Poisson and Gaussian signal error=0 while error==0: try: ran_arr = random.poisson(absBackground, nPoints) + ncombine*random.normal(0., readnoise, nPoints) #ran_arr = absBackground + ncombine*random.normal(0., readnoise, nPoints) error=1 except: error=0 float_arr = numpy.array(ran_arr/gain, dtype=numpy.float32) return float_arr
def __init__(self): self.weight = normal(32.5, 1.5)
def __init__(self): self.weight = normal(5.125, 0.0625) self.yarn_synthetic_composition = 0.0
import pylab as P import mpl_toolkits.mplot3d.axes3d as P3 P0=150 mu=.15 s=0.04 t=1 m=7 X=[] Y=[] Pt=P0 for t in [0,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,6,6.5,7,7.5]: tendencia = (mu-s**2/2)*t ruido = s*sqrt(t)*normal(0,1) Pt = P0*exp(tendencia+ruido) X.append(t) Y.append(Pt) P.plot(X,Y) P.show()
def _init_umpire_biases(self): """Initialize umpire biases for a person. These biases are triggered in tandem by Umpire.call_pitch(). Primary source: http://www.sloansportsconference.com/wp-content/ uploads/2014/02/2014_SSAC_What-Does-it-Take-to-Call-a-Strike.pdf """ # Pitch-call inconsistency represents how consistent an # umpire will be in attributing a certain call to a specific # pitch location over multiple pitches; we represent this as # a standard deviation in number of ball widths (the same units # with which we represent the strike zone) self.pitch_call_inconsistency = abs(normal(0, 0.15)) # Pitch-edge biases represent the umpire's mean deviation # from a true edge of the strike zone in how he # represents that edge inasmuch as the calls he makes # (studies show that umpires show huge bias for the top edge, # considerable bias for the left and bottom edges, and less bias # for the right edge) self.pitch_call_left_edge_bias = normal(-0.3, 0.15) self.pitch_call_right_edge_bias = normal(-0.15, 0.05) self.pitch_call_top_edge_bias = normal(-0.65, 0.35) self.pitch_call_bottom_edge_bias = normal(1.25, 0.5) # Count biases represent whether and how the umpire expands # the strike zone when there is three balls and/or constricts # the strike zone when there is two strikes -- this bias # will affect the ump's representation of all four edges of # the strike zone for this pitch, thus they have no sign # [Note: these biases are not enacted on a full count] self.pitch_call_two_strikes_bias = normal(1, 0.25) self.pitch_call_three_balls_bias = normal(0.3, 0.1) # Previous-call biases represent whether and how the umpire expands # the strike zone after calling a ball and/or constricts the # strike zone after calling a strike [Note: these biases ar not # enacted on a full-count] self.pitch_call_just_called_strike_bias = normal(1, 0.25) self.pitch_call_just_called_ball_bias = normal(0.3, 0.1) # Left-handedness bias represents how the umpire moves the # vertical edges of the strike zone further left for # left-handed hitters (Source: http://www.lookoutlanding.com/ # 2012/10/29/3561060/the-strike-zone) self.pitch_call_lefty_bias = normal(-0.07, 0.03) # Home-team pitch-call bias represents how the umpire expands # the strike zone slightly for home-team pitchers -- this value # will be used to expand all four edges of the strike zone, so # it small self.pitch_call_home_team_bias = abs(normal(0.0, 0.1)) # Tie-at-base policy represents whether the umpire's procedure # for calls at a base is to enforce that the tag must precede # the runner reaching the base ('tie goes to the runner', which # is not an actual rule) or that the runner must beat the tag -- # the value represents the number of seconds that will be # subtracted from the true time at which the runner reached base if random.random() < 0.7: # Tie given to runner self.play_at_base_tie_policy = 0.01 else: self.play_at_base_tie_policy = -0.01 # Prior-entry bias makes an umpire call a batter-runner out at # first when he is truly safe, due to perceiving the auditory # stimulus of the ball embedding in the glove as occurring # slightly earlier than it actually does -- this represents # the number of seconds that will be subtracted from the true # time at which the runner reached base self.play_at_first_prior_entry_bias = abs(normal(0.0, 0.015)) # Play-at-base inconsistency represents how consistent the # umpire will be in how he calls plays at a base. The value # represents a standard error in number of seconds, which # will be either added to or subtracted from the true time # at which the baserunner reached self.play_at_base_inconsistency = abs(normal(0.0, 0.005))
def call_play_at_base(self, playing_action, baserunner, base, throw=None, fielder_afoot=None): """Call a baserunner either safe or out.""" # This is some housekeeping that can probably be deleted if the specified errors never pop up if base == "1B": assert baserunner is playing_action.running_to_first or baserunner is playing_action.retreating_to_first, "" \ "Umpire was tasked with calling out {} at first, but that runner " \ "is not attempting to take that base.".format(baserunner.last_name) elif base == "2B": assert baserunner is playing_action.running_to_second or baserunner is playing_action.retreating_to_second, "" \ "Umpire was tasked with calling out {} at second, but that runner " \ "is not attempting to take that base.".format(baserunner.last_name) elif base == "3B": assert baserunner is playing_action.running_to_third or baserunner is playing_action.retreating_to_third, "" \ "Umpire was tasked with calling out {} at third, but that runner " \ "is not attempting to take that base.".format(baserunner.last_name) elif base == "H": assert baserunner is playing_action.running_to_home or baserunner.safely_on_base, "" \ "Umpire was tasked with calling out {} at home, but that runner " \ "is not attempting to take that base.".format(baserunner.last_name) # If the baserunner hasn't reached base yet, we need to calculate at what timestep # they *will/would have* reached base if not baserunner.timestep_reached_base: dist_from_baserunner_to_base = 90 - (baserunner.percent_to_base*90) time_until_baserunner_reaches_base = dist_from_baserunner_to_base * baserunner.full_speed_seconds_per_foot baserunner.timestep_reached_base = ( playing_action.batted_ball.time_since_contact + time_until_baserunner_reaches_base ) # If the ball has reached the base via throw, we know the timestep it reached base; # if it reached base via a fielder's on-foot approach, we need to calculate it if throw: timestep_ball_reached_base = throw.timestep_reached_target else: # elif fielder_afoot dist_from_fielder_to_base = math.hypot( fielder_afoot.immediate_goal[0]-fielder_afoot.location[0], fielder_afoot.immediate_goal[1]-fielder_afoot.location[1] ) time_until_fielder_reaches_base = dist_from_fielder_to_base * fielder_afoot.full_speed_seconds_per_foot timestep_ball_reached_base = ( playing_action.batted_ball.time_since_contact + time_until_fielder_reaches_base ) # Get the difference in time between the baserunner reaching base # and the throw reached the first baseman's glove -- this will be # negative if the runner beat the throw baserunner_diff_from_throw = true_difference = ( baserunner.timestep_reached_base - timestep_ball_reached_base ) # Make note of the true call for this play -- we'll say that ties go to the runner, # though the chance of one is extremely unlikely if baserunner_diff_from_throw <= 0: true_call = "Safe" else: true_call = "Out" # Pollute this perfectly accurate difference for whether the # umpire believes the throw must beat the runner ('tie goes to # the runner') or vice versa baserunner_diff_from_throw -= self.play_at_base_tie_policy # If play is at first, further pollute the difference for how susceptible the umpire # is to a prior-entry bias, explained in _init_umpire_biases() if base == "1B": baserunner_diff_from_throw += self.play_at_first_prior_entry_bias # Finally, *to simulate umpire inconsistency*, further pollute the # difference by regenerating it from a normal distribution around # itself with the umpire's inconsistency standard error as the # standard deviation baserunner_diff_from_throw = ( normal(baserunner_diff_from_throw, self.play_at_base_inconsistency) ) if baserunner_diff_from_throw <= 0: PlayAtBaseCall(at_bat=playing_action.at_bat, umpire=self, call="Safe", true_call=true_call, true_difference=true_difference, baserunner=baserunner, base=base, throw=throw, fielder_afoot=fielder_afoot) else: PlayAtBaseCall(at_bat=playing_action.at_bat, umpire=self, call="Out", true_call=true_call, true_difference=true_difference, baserunner=baserunner, base=base, throw=throw, fielder_afoot=fielder_afoot)
elif 2 < pitch.actual_x < 4: # Pull down toward [0, 0] framed_x = pitch.actual_x - pitch.catcher.pitch_framing else: framed_x = pitch.actual_x if -5 < pitch.actual_y < -3: framed_y = pitch.actual_y + pitch.catcher.pitch_framing elif 3 < pitch.actual_x < 5: framed_y = pitch.actual_y - pitch.catcher.pitch_framing else: framed_y = pitch.actual_y # Finally, *to simulate umpire inconsistency*, pollute the # framed position of the pitch using the umpire's rating # for pitch call consistency as a standard deviation pitch_location = ( normal(framed_x, self.pitch_call_inconsistency), normal(framed_y, self.pitch_call_inconsistency) ) # Now, make the call if consideration of the polluted pitch # location (which is only offset as a trick to represent umpire # inconsistency) relative to the umpire's biased model of the # trick zone if (left_edge < pitch_location[0] < right_edge and bottom_edge < pitch_location[1] < top_edge): return "Strike" else: return "Ball" def call_play_at_base(self, playing_action, baserunner, base, throw=None, fielder_afoot=None): """Call a baserunner either safe or out.""" # This is some housekeeping that can probably be deleted if the specified errors never pop up
def repair_duration(self): # Normal deviation with avg 15 min and dev 1 min return normal(15 * 60, 1 * 60)