def __init__(self, width, height): # oscillation stuff self.angle = Vector(0, 0) self.angleVelocity = Vector(random.uniform(-.05, .05), random.uniform(-.05, .05)) self.amplitude = Vector(randint(0, width / 2), randint(0, height / 2)) self.location = Vector(0, 0)
def update_velocity(self, paretofront, pareto_index, best_fitness, k): inertia = 0.4 c1 = 3 c2 = 1.5 h = 0 toss = random.uniform(0, 1) # does a toss if ( toss < 0.8 ): # with a 0.8 probability, it chooses from the fittest values in the repository h = random.randint(0, len(best_fitness) - 1) h = best_fitness[h] else: # else it chooses a random value from the repository h = random.randint(0, len(pareto_index) - 1) h = pareto_index[h] r1 = random.uniform(0, 1) r2 = random.uniform(0, 1) # finds vector to the personal best v2per_best = c1 * r1 * np.subtract(self.pos_best_i, self.position_i) # finds vector to one of the points on the repository decided by the toss v2glo_best = c2*r2 * \ np.subtract(paretofront[h, 0:self.dimension], self.position_i) for i in self.exclude: v2glo_best[:, i] = 0 v2per_best[:, i] = 0 self.velocity_i = inertia * \ np.add(np.add(self.velocity_i, v2per_best), v2glo_best)
def select_parents_roulette(population): popsize = len(population) #print("imprime la longitud del popsize",popsize) # Escoje el primer padre sumfitness = sum([indiv.fitness for indiv in population ]) # suma total del fitness de la poblacion pickfitness = random.uniform( 0, sumfitness) # escoge un numero aleatorio entre 0 y sumfitness cumfitness = 0 # fitness acumulado for i in range(popsize): cumfitness += population[i].fitness if cumfitness < pickfitness: #esta bien iParent1 = i break #print("paso el break del primero",i) # Escoje el segundo padre, desconsiderando el primer padre sumfitness = sumfitness - population[ iParent1].fitness # retira el fitness del padre ya escogido pickfitness = random.uniform( 0, sumfitness) # escoge un numero aleatorio entre 0 y sumfitness cumfitness = 0 # fitness acumulado for i in range(popsize): if i == iParent1: continue # si es el primer padre cumfitness += population[i].fitness if cumfitness < pickfitness: #print("encontrado") iParent2 = i #print("paso el break 2",i) break return (population[iParent1], population[iParent2])
def select(): cnt = 2 sum_fit = sum([fitness(ind) for ind in population]) pop = population[:] random.shuffle(pop) pairs = [] for i in range(cnt): n = random.uniform(0, sum_fit) m = random.uniform(0, sum_fit) tmp_sum = 0 first, second = None, None for ind in pop: tmp_sum += fitness(ind) if tmp_sum >= n: first = ind break tmp_sum = 0 for ind in pop: tmp_sum += fitness(ind) if tmp_sum >= m: second = ind break if first is None or second is None: print("FAILED") raise RuntimeError("Ooops") pairs.append((first, second)) print(str(pairs)) return pairs
def update_velocity( self, paretofront, pareto_index, best_fitness, k): #this function decides the velocity for the next iteration inertia = 0.4 c1 = 3 c2 = 1.5 h = 0 toss = random.uniform(0, 1) #does a toss if ( toss < 0.8 ): #with a 0.8 probability, it chooses from the fittest values in the repository h = random.randint(0, len(best_fitness) - 1) h = best_fitness[h] else: #else it chooses a random value from the repository h = random.randint(0, len(pareto_index) - 1) h = pareto_index[h] for i in range( 0, self.dimension): #updates the velocity for each dimension if i not in exclude: #doesn't update for paramters we exclude. r1 = random.uniform(0, 1) r2 = random.uniform(0, 1) v2per_best = c1 * r1 * (self.pos_best_i[i] - self.position_i[i] ) #finds vector to the personal best v2glo_best = c2 * r2 * ( paretofront[h, i] - self.position_i[i] ) #finds vector to one of the points on the repository decided by the toss self.velocity_i[i] = inertia * self.velocity_i[ i] + v2per_best + v2glo_best #finds the velocity for the next iteration
def new_square(): global x2, y2, r2, i2, flag_del2, flag_movement2, color2, vx2, vy2 flag_in2 = True i2 += 1 if i2 == 4: i2 = 0 flag_del2 = True flag_movement2 = True if flag_del: rect(screen, (0, 0, 0), (x2[i2] - r2[i2], y2[i2] - r2[i2], 2 * r2[i2], 2 * r2[i2])) r2[i2] = randint(40, 50) x2[i2] = randint(100 + r2[i2], 700 - r2[i2]) y2[i2] = randint(100 + r2[i2], 300 - r2[i2]) if randint(0, 1): vx2[i2] = random.uniform(1, 2) else: vx2[i2] = -random.uniform(1, 2) vy2[i2] = random.uniform(0, 5) while flag_in2: flag_in2 = False for j in range(4): if i2 != j: if (x2[i2] - x2[j])**2 + (y2[i2] - y2[j])**2 <= (r2[i2] + r2[j])**2: flag_in2 = True x2[i2] = randint(100, 700) y2[i2] = randint(100, 500) r2[i2] = randint(20, 30) color2[i2] = COLORS[randint(0, 4)] rect(screen, color2[i2], (x2[i2] - r2[i2], y2[i2] - r2[i2], 2 * r2[i2], 2 * r2[i2])) flag_exist2[i] = True
def photometric_distort(image): """ Distort brightness, contrast, saturation, and hue, each with a 50% chance, in random order. :param image: image, a PIL Image :return: distorted image """ new_image = image distortions = [ FT.adjust_brightness, FT.adjust_contrast, FT.adjust_saturation, FT.adjust_hue ] random.shuffle(distortions) for d in distortions: if random.random() < 0.5: if d.__name__ is 'adjust_hue': # Caffe repo uses a 'hue_delta' of 18 - we divide by 255 because PyTorch needs a normalized value adjust_factor = random.uniform(-18 / 255., 18 / 255.) else: # Caffe repo uses 'lower' and 'upper' values of 0.5 and 1.5 for brightness, contrast, and saturation adjust_factor = random.uniform(0.5, 1.5) # Apply this distortion new_image = d(new_image, adjust_factor) return new_image
def rand_list(p): l = [] for i in range(p): x = random.uniform(-100, 100) y = random.uniform(-100, 100) l.append([x, y]) return l
def new_ball(): global x, y, r, i, flag_del, flag_movement, color, vx, vy flag_in = True i += 1 if i == 4: i = 0 flag_del = True flag_movement = True if flag_del: circle(screen, (0, 0, 0), (x[i], y[i]), r[i]) x[i] = randint(100, 700) y[i] = randint(100, 500) r[i] = randint(30, 50) vx[i] = random.uniform(-3, 3) vy[i] = random.uniform(-3, 3) while flag_in: flag_in = False for j in range(4): if i != j: if (x[i] - x[j])**2 + (y[i] - y[j])**2 <= (r[i] + r[j])**2: flag_in = True x[i] = randint(100, 700) y[i] = randint(100, 500) r[i] = randint(10, 30) color[i] = COLORS[randint(0, 4)] circle(screen, color[i], (x[i], y[i]), r[i]) flag_exist[i] = True
def get_transition_yz(classes, num_interps, truncation): noise_seed_A, noise_seed_B = random.uniform(10, 100), random.uniform( 20, 120) # fix this! return get_interpolated_yz(classes, num_interps, noise_seed_A, noise_seed_B, truncation=truncation)
def __init__(self, x, y): self.center = array([float(x), float(y)]) self.tendrils = [] self.next_id = 0 self.num_generated_tendrils = 0 for i in range(1,int(random.uniform(1,30))): self.add_tendril(self.center,self.center, random.uniform(1.2, 2.0))
def rand_list(p, r): l = [] for i in range(p): x = random.uniform(-r, r) y = random.uniform(-r, r) l.append([x, y]) return l
def __obtain_crossover(self, q_i, q_m): q_c = [] cr = random.uniform(0, 1) rnbr_i = random.randint(0, len(q_i) - 1) for j in range(len(q_i)): q_c.append(q_m[j] if random.uniform(0, 1) <= cr or rnbr_i == j else q_i[j]) return q_c
def ball_volume(R, N): n = 0 cube_volume = (2 * R)**3 for _ in range(N): x = random.uniform(-R, R) y = random.uniform(-R, R) z = random.uniform(-R, R) if x**2 + y**2 + z**2 <= R**2: #check if the ball includes the point n += 1 return (n / N) * cube_volume
def __init__(self, parent, tendril_id, loc, center, r): PlantSmarts.__init__(self, parent, center.copy(), loc.copy()) self.tendril_id = tendril_id self.vel = array([random.uniform(-0.5,0.5), random.uniform(-0.5,0.5)]) self.acc = array([0.0, 0.0]) self.radius = r self.maxspeed = 1.0 self.connected = False self.separateFactor = 1
def cone_volume(R, H, N): n = 0 cube_volume = (2 * R)**2 * H for _ in range(N): x = random.uniform(-R, R) y = random.uniform(-R, R) z = random.uniform(-R, R) if x**2 + y**2 <= ( (z * R) / H)**2: #check if the cone includes the point n += 1 return (n / N) * cube_volume
def getTuple(): """ returns "x" between [0, 1] uniformly """ x = random.uniform(-1, 1) y = random.uniform(-1, 1) while x**2 + y**2 > 1: x = random.uniform(-1, 1) y = random.uniform(-1, 1) return (x, y)
def randomize(self): """ Randomizes all parameters of the hmm """ # Initialize random parameters for x in range(0, self.num_states): self.initial_matrix[x] = Decimal(random.uniform(0, 1.0)) for y in range(0, self.num_states): self.transition_matrix[x][y] = Decimal(random.uniform(0, 1.0)) for s in range(0, self.num_symbols + 1): self.emission_matrix[x][s] = Decimal(random.uniform(0, 1.0)) self.normalize()
def ball_cylinder_difference_volume(R_ball, R_cylinder, H, N): n = 0 block_volume = (2 * R_ball)**3 for _ in range(N): x = random.uniform(-R, R) y = random.uniform(-R, R) z = random.uniform(-R, R) if in_ball(x, y, z, R_ball) and not in_cylinder( x, y, z, R_cylinder, H): #check if point is in the ball and is not in the cylinder n += 1 return (n / N) * block_volume
def randPoint(self) -> List[float]: x = random.uniform(self.x - self.r, self.x + self.r) y = random.uniform(self.y - self.r, self.y + self.r) # print(x,y) if (x - self.x) ** 2 + (y - self.y) ** 2 <= self.r ** 2: return [x, y] else: return self.randPoint() # Your Solution object will be instantiated and called as such: # obj = Solution(radius, x_center, y_center) # param_1 = obj.randPoint()
def generatePolygon(ctrX, ctrY, aveRadius, irregularity, spikeyness, numVerts): '''Start with the centre of the polygon at ctrX, ctrY, then creates the polygon by sampling points on a circle around the centre. Randon noise is added by varying the angular spacing between sequential points, and by varying the radial distance of each point from the centre. https://github.com/the-mikedavis/randompolygons Params: ctrX, ctrY - coordinates of the "centre" of the polygon aveRadius - in px, the average radius of this polygon, this roughly controls how large the polygon is, really only useful for order of magnitude. irregularity - [0,1] indicating how much variance there is in the angular spacing of vertices. [0,1] will map to [0, 2pi/numberOfVerts] spikeyness - [0,1] indicating how much variance there is in each vertex from the circle of radius aveRadius. [0,1] will map to [0, aveRadius] numVerts - self-explanatory Returns a list of vertices, in CCW order. ''' import math, random irregularity = clip(irregularity, 0, 1) * 2 * math.pi / numVerts spikeyness = clip(spikeyness, 0, 1) * aveRadius # generate n angle steps angleSteps = [] lower = (2 * math.pi / numVerts) - irregularity upper = (2 * math.pi / numVerts) + irregularity sum = 0 for i in range(numVerts): tmp = random.uniform(lower, upper) angleSteps.append(tmp) sum = sum + tmp # normalize the steps so that point 0 and point n+1 are the same k = sum / (2 * math.pi) for i in range(numVerts): angleSteps[i] = angleSteps[i] / k # now generate the points points = [] angle = random.uniform(0, 2 * math.pi) for i in range(numVerts): r_i = clip(random.gauss(aveRadius, spikeyness), 0, 2 * aveRadius) x = ctrX + r_i * math.cos(angle) y = ctrY + r_i * math.sin(angle) points.append((int(x), int(y))) angle = angle + angleSteps[i] return points
def update_SEIR_persons_first(self, SEIR_lambda, SEIR_gamma): for agent in self.agents: if agent.infected == True or agent.exposed == True: agent.disease_day += 1 if SEIR_lambda > 0 and agent.exposed == True: random_float = random.uniform(0, 1.0) if random_float < SEIR_lambda: agent.exposed = False agent.infected = True random_float = random.uniform(0, 1.0) if agent.infected == True and random_float < SEIR_gamma: agent.infected = False agent.immune = True
def train_against_random(number, player): #this function trains an agent against a random opponent, the player is the agent to be trained #the agent is trained for as many games as the number input global Xwins, Owins, ties, player_X if (player != "X" and player != "O"): while (player != "X" and player != "O"): z = input("wrong input to train, type X or O") player = z for x in range(number): player_X = 1 reset() update_board() while (check_win() == 0): if (player_X == 0): if (player == "O"): y = random.uniform(0, 1) if (y < float(.3)): explore(player_X) else: exploit(player_X) else: explore(player_X) else: if (player == "X"): y = random.uniform(0, 1) if (y < float(.3)): explore(player_X) else: exploit(player_X) else: explore(player_X) update_board() if (check_win() == 1): #X won Xwins = Xwins + 1 reward(1) elif (check_win() == 2): #O won Owins = Owins + 1 reward(2) elif (check_win() == -1): #tie ties = ties + 1 reward_tie() changesides()
def build_neural_network(input_dimension, hidden_dimension, output_dimension): myNeuralNetwork = [] hidden_layer = [] second_hidden_layer = [] output_layer = [] bias = 1 # Hidden Layer Weights: for i in range(hidden_dimension): hidden_layer_neuron = { "Connection_Weight": [], "Bias": random.uniform(0, 0.01) } # Each weight is a connection to this neuron from the input layer for j in range(input_dimension): # Initialize the weight to a value between -0.01 and 0.01 (we want a very small number close to 0) # for the initial weight (page 289 in psuedo code) hidden_layer_neuron["Connection_Weight"].append(random.uniform(0, 0.01)) # Keep this particular neuron and all its "connections" or weights. hidden_layer.append(hidden_layer_neuron) for i in range(output_dimension): output_layer_neuron = { "Connection_Weight": [], "Bias": random.uniform(0, 0.01) } # Again, each weight is a connection to this neuron except this time from the hidden layer: for j in range(hidden_dimension): # Like before, initialize to a value between -0.01 and 0.01 output_layer_neuron["Connection_Weight"].append(random.uniform(0, 0.01)) # Once finished, append into the output_layer list to keep all of its "connections" or weights output_layer.append(output_layer_neuron) # Now put both the hidden and output layer into myNeuralNetwork list myNeuralNetwork.append(hidden_layer) # myNeuralNetwork.append(second_hidden_layer) myNeuralNetwork.append(output_layer) return myNeuralNetwork
def _take_action(self, action): # Set the current price to a random price within the time step current_price = random.uniform( self.df.loc[self.current_step, "Open"], self.df.loc[self.current_step, "Close"]) action_type = action[0] amount = action[1] if action_type < 1: # Buy amount % of balance in shares total_possible = self.balance / current_price shares_bought = total_possible * amount prev_cost = self.cost_basis * self.shares_held additional_cost = shares_bought * current_price self.balance -= additional_cost self.cost_basis = (prev_cost + additional_cost) / (self.shares_held + shares_bought) self.shares_held += shares_bought elif action_type < 2: # Sell amount % of shares held shares_sold = self.shares_held * amount self.balance += shares_sold * current_price self.shares_held -= shares_sold self.total_shares_sold += shares_sold self.total_sales_value += shares_sold * current_price self.netWorth = self.balance + self.shares_held * current_price if self.net_worth > self.max_net_worth: self.max_net_worth = self.net_worth if self.shares_held == 0: self.cost_basis = 0
def hill_climbing_with_random_walk(initial_prop_of_items, random_walk_prob, max_super_best_steps): print("Hill Climbing with random walk\n") # print("Initial Prop of items:", initial_prop_of_items) # print("Random walk probability", random_walk_prob) # print("Max No. of steps without improvement", max_super_best_steps) import random solutionsChecked = 0 coverage = 0 x_curr = Initial_solution(initial_prop_of_items) # x_curr will hold the current solution coverage = np.sum(x_curr)/n best_count = 1 x_super_best = x_curr[:] # x_best will hold the best solution f_curr = evaluate(x_curr)[:] # f_curr will hold the evaluation of the current soluton f_best = f_curr[:] #Best solution in neighbourhood f_super_best = f_curr[:] # begin local search overall logic ---------------- count = 0 #number of iteration with out improvement change = 0 while (count < max_super_best_steps) : # create a list of all neighbors in the neighborhood of x_curr Neighborhood = OneflipNeighborhood(x_curr) eeta = random.uniform(0, 1) if (eeta >= random_walk_prob): f_best[0]=0 for s in Neighborhood: # evaluate every member in the neighborhood of x_curr solutionsChecked = solutionsChecked + 1 if (evaluate(s)[0] > f_best[0]): # and (evaluate(s)[1]< maxWeight): x_curr = s[:] # find the best member and keep track of that solution f_best = evaluate(s)[:] # and store its evaluation coverage += np.sum(x_curr)/n best_count+=1 else: x_curr = Neighborhood[random.randint(0, len(Neighborhood) - 1)] if (evaluate(x_curr)[0] > f_super_best[0]): #to remember best solution f_super_best = evaluate(x_curr)[:] #best solution so far x_super_best = x_curr[:] change = 1 #To record change count = count + 1 #counting number of iterations without improvement if(change == 1): #Reseting count and change count=0 change=0 print_results(solutionsChecked,f_super_best, x_super_best,coverage,best_count)
def RandomGraph(nodes=list(range(10)), min_links=2, width=400, height=300, curvature=lambda: random.uniform(1.1, 1.5)): """Construct a random graph, with the specified nodes, and random links. The nodes are laid out randomly on a (width x height) rectangle. Then each node is connected to the min_links nearest neighbors. Because inverse links are added, some nodes will have more connections. The distance between nodes is the hypotenuse times curvature(), where curvature() defaults to a random number between 1.1 and 1.5.""" g = UndirectedGraph() g.locations = {} # Build the cities for node in nodes: g.locations[node] = (random.randrange(width), random.randrange(height)) # Build roads from each city to at least min_links nearest neighbors. for i in range(min_links): for node in nodes: if len(g.get(node)) < min_links: here = g.locations[node] def distance_to_node(n): if n is node or g.get(node, n): return math.inf return distance(g.locations[n], here) neighbor = nodes.index(min(nodes, key=distance_to_node)) d = distance(g.locations[neighbor], here) * curvature() g.connect(node, neighbor, int(d)) return g
def is_correlation(): test = random.uniform(0,1) correlation_pro = 0.4 if test < correlation_pro: return 1 else: return 0
def execute_main(bot, trigger, triggerargsarray): channel = trigger.sender instigator = trigger.nick deckchoice = randint(1, 3) payment = random.uniform(0.1, 0.3) balance = Spicebucks.bank(bot, instigator) payout = int(payment * balance) if Spicebucks.transfer(bot, trigger.nick, 'SpiceBank', monopolyfee) == 1: if deckchoice == 1: chancecard = get_trigger_arg(bot, gooddeck, 'random') msg = chancecard + " and wins " + str(payout) + " Spicebucks" elif deckchoice == 2: chancecard = get_trigger_arg(bot, baddeck, 'random') msg = chancecard + " and loses " + str(payout) + " Spicebucks" payout = -payout elif deckchoice == 3: msg = get_trigger_arg(bot, neutraldeck, 'random') payout = 0 bot.say(instigator + " risks " + str(monopolyfee) + " Spicebucks to draw a card from the chance deck! " + instigator + " gets " + msg + ".") if (balance + payout) < 0: payout = balance adjust_botdatabase_value(bot, instigator, 'spicebucks_bank', payout) else: bot.notice( "You need " + str(monopolyfee) + " Spicebucks to use this command.", instigator)
def test(): total_time_two = 0 total_time_four = 0 start = time.time() runs = 1000 for i in range(1000): print('run') n_iter = 2000 radius = .01 stepSize = .35 threshold = 2 num_obstacles = 1 bounds = [[-.05, .05], [-.05, .05], [-.05, .05]] # start_node = RRTNode([7.4883959080999105, -0.9802836168249124, 2.7119532197892307, 2.690692578970348, 1.4327288698060625]) # end_node = RRTNode([0.80873032, 0.58529255 , 1.57082885 , 2.15507481 ,-0.80873048]) start_node, end_node, obstacles, _ = random_start_environment( num_obstacles, bounds) location = random.uniform(.1, .1) prism = [location, location, location, .2, .2, .2] obstacles = [prism] start_time = time.time() print("RRT started") try: G = rrt(start_node.angles, end_node.angles, obstacles, n_iter, radius, stepSize=stepSize) size1 = 0 if G.success: path = dijkstra(G) size1 = len(path) runTime = time.time() - start_time optimize_start_time2 = time.time() path2 = path_optimizer_two(path, prism) size2 = len(path2) if checkPath(path2, prism): optimizeTime2 = time.time() - optimize_start_time2 total_time_two += optimizeTime2 optimize_start_time4 = time.time() path4 = path_optimizer_four(path, prism) size4 = len(path4) if checkPath(path4, prism): optimizeTime4 = time.time() - optimize_start_time4 total_time_four += optimizeTime4 except Exception: print("Exception thrown") runs -= 1 full_runtime = time.time() - start print("total time for 2s", total_time_two) print("total time for 4s", total_time_four) print("total runs", runs) print("time per run for 2s", total_time_two / runs) print("time per run for 4s", total_time_four / runs) print("full run time:", full_runtime)
def createUnitVectors(dim, t): vectors = [] for i in range(t): list = [] for j in range(dim): u = random.uniform(0.0, 1.0) unot = random.uniform(0.0, 1.0) g = np.sqrt(-2 * np.log(u)) * np.cos(2 * np.pi * unot) list.append(g) #At this point U is generated so we need to normalize it vecG = np.array(list) normG = np.linalg.norm(vecG) unitG = vecG / normG vectors.append(unitG) return vectors
def conectaAleatorio(self, p): for (x1, y1) in self.nodos: for (x2, y2) in self.nodos: #if (x1,y1) is not (x2,y2): rand = random.uniform(0, 1) if rand < p: if ((x1, y1), (x2, y2)) not in self.aristas: if ((x2, y2), (x1, y1)) not in self.aristas: self.kmax = floor(i / 2) u = self.nodos.index((x1, y1)) v = self.nodos.index((x2, y2)) if u is not v: dis = abs(u - v) print("huele a canela") print(u, v, dis) if dis > self.kmax: dis2 = i - dis self.aristas[((x1, y1), ( x2, y2))] = self.aristas[((x2, y2), ( x1, y1))] = dis2 #para impares else: self.aristas[((x1, y1), ( x2, y2))] = self.aristas[((x2, y2), ( x1, y1 ))] = dis #para pares porque coincide if (x1, y1) not in self.vecinos[(x2, y2)]: if (x1, y1) is not (x2, y2): if (x2, y2) is not (x1, y1): self.vecinos[(x2, y2)].append( (x1, y1)) if (x2, y2) not in self.vecinos[(x1, y1)]: if (x2, y2) is not (x1, y1): if (x1, y1) is not (x2, y2): self.vecinos[(x1, y1)].append( (x2, y2))
def conectaAleatorio(self, p): for (x1, y1) in self.nodos: for (x2, y2) in self.nodos: rand = random.uniform(0, 1) if rand < p: if ((x1, y1), (x2, y2)) not in self.aristas: if ((x2, y2), (x1, y1)) not in self.aristas: self.s = floor((3 * Tk) - (i / 4)) u = self.nodos.index((x1, y1)) v = self.nodos.index((x2, y2)) if u is not v: dis = abs(u - v) self.aristas[((x1, y1), (x2, y2))] = self.aristas[( (x2, y2), (x1, y1))] = distancia( (x2, y2), (x1, y1)) if (x1, y1) not in self.vecinos[(x2, y2)]: if (x1, y1) is not (x2, y2): if (x2, y2) is not (x1, y1): self.vecinos[(x2, y2)].append( (x1, y1)) if (x2, y2) not in self.vecinos[(x1, y1)]: if (x2, y2) is not (x1, y1): if (x1, y1) is not (x2, y2): self.vecinos[(x1, y1)].append( (x2, y2))
def multiple_runs(): n_iter = 1000 radius = .07 stepSize = .35 threshold = 2 num_obstacles = 1 bounds = [[-.4, .4], [0, .4], [-.4, .4]] # start_node = RRTNode([7.4883959080999105, -0.9802836168249124, 2.7119532197892307, 2.690692578970348, 1.4327288698060625]) # end_node = RRTNode([0.80873032, 0.58529255 , 1.57082885 , 2.15507481 ,-0.80873048]) start_node, end_node, obstacles = random_start_environment( num_obstacles, bounds) print("Start:", start_node.angles) print("End:", end_node.angles) print("Obstacles:", obstacles) location = random.uniform(.1, .1) prism = [location, location, location, .2, .2, .2] obstacles = [prism] G = rrt(start_node.angles, end_node.angles, obstacles, n_iter, radius, stepSize=stepSize) size1 = 0 if G.success: path = dijkstra(G) size1 = len(path) print("Original Path Size:", size1) plot_3d(G, path, obstacles, None) bestPath = optimize(path, obstacles) print("Optimal Path Size:", len(bestPath)) plot_3d(G, bestPath, obstacles, None) else: print("Path not found. :(") plot_3d(G, [start_node, end_node], obstacles, None)
def __init__(self, **kwargs): kwargs.setdefault('instrument', 0) self.filename = kwargs.get('filename') img = Loader.image(self.filename) x = int(random.uniform(300, 600)) y = int(random.uniform(100, 500)) # make sequence for this instrument self.seq = EventManager.getInstance().createSequence() ''' TODO auswahl des instruments muss hier noch rein ''' self.seq.setInstrument(kwargs.get('instrument')) self.volume = Constants.SEQUENCE_START_VOLUME # this is used to ensure that the on_touch_up handler just # executes one time. see on_touch_up event handler self.touch_up_oneTime = 0.0 super(MusicBubble, self).__init__(image=img, pos=(x,y), scale=0.8, **kwargs) self.register_event_type('on_tap')
def separate(self, hypha): sum = array([0.0,0.0]) desiredseparation = 0 for h in hypha: if (h == self.parent): desiredseparation = random.uniform(1,40) * self.separateFactor for t in h.tendrils: d = linalg.norm(self.loc - t.loc) # If the distance is greater than 0 and less than an # arbitrary amount (0 when you are yourself) if ((d > 0) and (d < desiredseparation)): diff = self.loc - t.loc if (linalg.norm(diff) != 0.0): # avoid NaN diff /= linalg.norm(diff) # normalize # Weight by distance sum += diff return sum
# print 'next timeout:',w.get_min() while True: if w.get_min() is 0: break relative = int(w.get_min() - time.time()) if relative > 60: relative = 60 print 'relative:%s,min:%s' % (relative,w.get_min()) if relative <= 0: print 'do_action in relative less than 0' w.do_action() else: s.enter(relative,PRIORITY_CHUNK,w.do_action,()) break #s.enter(int(random.uniform(0,40)),PRIORITY_CLIENT,upload,(clist,4)) s.enter(90,PRIORITY_CLIENT,download,(clist,int(random.uniform(0,50)))) s.enter(90,PRIORITY_CLIENT,update,(clist,int(random.uniform(0,30)))) s.enter(60,PRIORITY_CLIENT,remove,(clist,int(random.uniform(0,3)))) s.enter(60,PRIORITY_MASTER,master.check_migarate,()) s.enter(150,PRIORITY_CHUNK,add_chunk,(cclist, int(random.uniform(0,5)),master)) s.enter(120,PRIORITY_CHUNK,down,cclist) s.enter(120,PRIORITY_CHUNK,up,cclist) s.run() # register master to collect some info
def branch(self, hypha): k = linalg.norm(self.loc - self.tcenter) r = random.uniform(0,(100/(k+0.5))) if ((r <= 0.2) and (self.parent.num_generated_tendrils < 50)): self.parent.add_tendril( self.loc, self.tcenter, 1.0)
def wander(self): w = array([random.uniform(-0.1,0.1), random.uniform(-0.1,0.1)]) if (linalg.norm(w) != 0.0): # avoid NaN w /= linalg.norm(w) # normalize return w
"(node, value, datetime, lat, lon) " "VALUES (%s, %s, %s, %s, %s);") # Sets up cursor object to interact with MYSQL connection cursor = cnx.cursor() time.sleep(2) print("node, value, datetime, lat, lon") # 3) opens file to write results to and start reading from serial with open('arduinoOutput.txt', 'w') as f: while True: # assign the observation counter to id and value to value from the split string array node1 = str(1) value1 = str(random.uniform(8.0, 12.0)) datetimestr1 = str(datetime.datetime.now()) lat1 = str(44.704985) lon1 = str(-67.881473) query1 = "INSERT INTO MoistureDataFAKE (node, value, datetime, lat, lon) VALUES ('{}', '{}', '{}', '{}', '{}');".format(node1, value1, datetimestr1, lat1, lon1) tuple1 = node1 + ", " + value1 + ", " + datetimestr1 + ", " + lat1 + ", " + lon1 # print response print(tuple1) # write tuple to file f.write(str(tuple1)) # flush to make sure all writes are committed f.flush() # generate the query to insert the value into the SensorData table print("Query is: " + query1) print("\n" + "*" * 80) # ping the connection before cursor execution so the connection is re-opened if it went idle in downtime
def __init__(self, width, height): self.location = Vector(randint(0, width), randint(0, height)) self.velocity = Vector(random.uniform(-1, 1), random.uniform(-1, 1)) self.acceleration = Vector(0, 0) self.mass = randint(1, 10) self.g = 0.1
def n(max): return int(random.uniform(0,max))
def method(delay): scale = random.uniform(-spread, spread) return delay + scale
def MCint_vec(f, a, b, n): x = random.uniform(a, b, n) s = sum(f(x)) I = (float(b - a) / n) * s return I
import matplotlib import matplotlib.pyplot as plt n = 1000 #number of points to create xcord0 = [] ycord0 = [] xcord1 = [] ycord1 = [] markers =[] colors =[] fw = open('testSet.txt','w') for i in range(n): [r0,r1] = random.standard_normal(2) myClass = random.uniform(0,1) if (myClass <= 0.5): fFlyer = r0 + 9.0 tats = 1.0*r1 + fFlyer - 9.0 xcord0.append(fFlyer) ycord0.append(tats) else: fFlyer = r0 + 2.0 tats = r1+fFlyer - 2.0 xcord1.append(fFlyer) ycord1.append(tats) #fw.write("%f\t%f\t%d\n" % (fFlyer, tats, classLabel)) fw.close() fig = plt.figure() ax = fig.add_subplot(111)