def updateweights(n1, n2):
    #Initialising a random number and if that number exceeds the crossingover rate then proceeding ahead for crossing over
    #else returning the 2 NeuralNets as it is
    a= random.random()
    if a < crossingoverrate:
        #Creating a list of weights of both the NeuralNets for easy processing ahead
	weightslist1 = np.array(n1.nettolist())
	weightslist2 = np.array(n2.nettolist())
	#Main Crossing over step- We take an element-wise average of the weights of 
	#both the NeuralNets . This incorporates the weights of both the NeuralNets
	#in equal proportion. We make 2 such lists , this is the crossing over step 
	#since we are taking characters from both the NeuralNets that too equally.
	child1 = [i * 0.5 for i in np.add(weightslist1, weightslist2)]
	child2 = [i * 0.5 for i in np.add(weightslist1, weightslist2)]
	#Initialising a random number and if that number exceeds the mutation rate then proceeding ahead for mutation
	#else the child remains as it is
	b= random.random()
	c= random.random()
	if b < mutationrate:
            print "Hi"
            #Randomly picking any one index of the list to be mutated
	    index = random.randint(0, len(child1) - 1)
            #perturbing the value slightly by adding a small component proportional to the original value of the weight
	    #for that index (it is being multiplied by a random number generated from a triangular distribution)
	    #This step is similar to mutation in genetics, where the genome gets randomly perturbed by external mutagens.
	    child1[index] += random.triangular(-1, 1) * child1[index]
	if c < mutationrate:
            print "Hello"
	    index = random.randint(0, len(child2) - 1)
	    child2[index] += random.triangular(-1, 1) * child2[index]
        #After the crossing over and mutation (if any), the list of weights is converted back to weights for the NeuralNets.
	n1.listtonet(child1)
	n2.listtonet(child2)
    return (n1, n2)
Exemplo n.º 2
0
def specimen_generator():
    global random_specimen
    global mated_specimen
    
    while True:
        r = get_results()
        result_count = len(r)
        if result_count < 10 or  mated_specimen > 10*random_specimen:
            dna = map(lambda x: x+97, range(26))
            dna = map(chr, dna)

            shuffle(dna)

            dna = "".join(dna)

            #print "random: %s" % dna
            with random_specimen_lock:
                random_specimen += 1
                
            yield {"dna" : dna, "parents" : [], "id" : next_id(), "guesses" : None, "wrong" : None, "winrate" : None}

        else:
            dna_i = int(triangular(0, len(r), 0))
            dnb_i = int(triangular(0, len(r), 0))
            dna = r[dna_i]
            dnb = r[dnb_i]

            dnc = merge_dna(dna["dna"], dnb["dna"])

            print "mated  %s & %s -> %s\n" % (dna["dna"], dnb["dna"], dnc)
            with mated_specimen_lock:
                mated_specimen += 1
            yield {"dna" : dnc, "parents" : ["%s (%s)" % (dna_link(dna["dna"]), dna["winrate"]),
                                             "%s (%s)" % (dna_link(dnb["dna"]), dnb["winrate"])],
                   "id" : next_id(), "guesses" : None, "wrong" : None, "winrate" : None}
Exemplo n.º 3
0
def tickle_bids(low, high, amountlow=.02, amounthigh=.09, concurrent=4, pause=33.5):
    try:
        while True:
            time.sleep(pause)
            clear_all_bids()
            amount_midpoint = amounthigh - ((amounthigh - amountlow) / 2)
            bid_amounts = []
            for i in range(concurrent):
                bid_btc_amount = float("{0:.4f}".format(random.triangular(amountlow,
                                                                      amounthigh,
                                                                      amount_midpoint)))
                bid_amounts.append(bid_btc_amount)
            
            bid_price_midpoint = float(high) - ((float(high) - float(low)) / 2)
            print 'Bid price midpoint: %f' % bid_price_midpoint
            for bid_btc_amount in bid_amounts:
                bid = float("{0:.2f}".format(random.triangular(low, high, bid_price_midpoint)))
                print 'Bid: %f [%f]' % (bid, bid_btc_amount)
                total_btc_int = int(bid_btc_amount * BTC_INT_FACTOR)
                buy_price_int = int(bid * USD_INT_FACTOR)
                res = API.add_order('bid', total_btc_int, buy_price_int)
                print res
            
    except KeyboardInterrupt:
        print '\nStopping...'
        clear_all_bids()
Exemplo n.º 4
0
    def advance_epoch(self):
        """Pass the time."""
        # Sort ascending because this is cost rather than fitness.
        self.population.sort(key=fitness, reverse=True)
        new_population = []

        # Clone our best people.
        iters = int(Pool.population_size * 0.4)
        for counter in range(iters):
            new_individual = self.population[counter].copy()
            new_population.append(new_individual)

        # Breed our best people, producing four offspring for each couple.
        iters = int(Pool.population_size * 0.6)
        for counter in range(0, iters, 2):
            # Perform rank roulette selection.
            father = self.population[int(triangular(0, iters, 0))]
            mother = self.population[int(triangular(0, iters, 0))]
            children = self.crossover(father, mother)
            children[0].mutate()
            new_population += children

        self.population = new_population
        for person in self.population:
            person.update_fitness()
        self.epoch += 1
Exemplo n.º 5
0
def create_expression():
    """This function takes no arguments and returns an expression that
    generates a number between -1.0 and 1.0, given x and y coordinates."""
    # expr = lambda x, y: (random.random() - 2 * 81) - 1
    # expr_dict= {'A': lambda x, y: sin(sin(sin(cos(x * y)))),
    #             'B': lambda x, y: sin(pi) * 2,
    #             'C': lambda x, y: sin(3 * pi(sin(21))),
    #             'D': lambda x, y: (cos(sin((pi * 8)))),
    #             'E': lambda x, y: cos(cos(sin(7)))
    #             }
    # expr_dict = {'sure': lambda x, y: sin(sin(sin(cos(pi)))),
    #              'the': lambda x, y: random.triangular(0.2, 0.9),
    #              'dang': lambda x, y: sin(pi(sin(pi(sin(cos(-1)))))),
    #              'should': lambda x, y: cos(x * cos(sin(pi))),
    #              'make': lambda x, y: random.uniform(1278, 900000),
    #              'art': lambda x, y: random.gauss(x, y)}

    expr_list = [lambda x, y: (random.random() * 21) - 1 / 3,
                 lambda x, y: (random.triangular(0, 1) * 2) - 1,
                 lambda x, y: (random.uniform(x, y) * 2) - 1,
                 lambda x, y: ((x**3) - sin(3)),
                 lambda x, y: (random.triangular(0.2, 0.8) / 2) - 1,
                 lambda x, y: sin(pi * 2) - 3 / 4,
                 lambda x, y: sqrt(sin(pi / 2) * cos(x)),
                 lambda x, y: sin(cos(sin(cos(sin(cos(sin(cos(pi)))))))),
                 lambda x, y: 7 + sin(pi) / sqrt(2**4),
                 lambda x, y: sqrt(3) * sin(sin(sin(pi) - 1)),
                 lambda x, y: (random.random() * 8) + sqrt(66) / 2,
                 lambda x, y: sin(sin(sin(sin(sin(sin(sin(sin(sin(7 * x - y))))))))),
                 lambda x, y: random.uniform(sin(1), pi) **8 / 2]



    return random.choice(expr_list)
def simulation_per_month_model(input_model):
    """ 
        Model to solve the problem 
    """    
    # Static model data
    cold_start_initial_users = 400
    cost_per_request = 0.01
    request_per_user = 4
    
    # Model
    
    # Select randomly input parameters
    events = random.triangular(input_model[1][0], input_model[1][1], input_model[1][2])
    
    # Calculate the cost
    cost = 0
    
    # For each event in the month
    for event in range(0, round(events)):
        event_duration = random.triangular(input_model[2][0], input_model[2][1], input_model[2][2])
        
        # For each day of the event
        for day in range(0, round(event_duration)):
            
            # Get users to track
            users_to_track = random.triangular(input_model[0][0], input_model[0][1], input_model[0][2])
            cost += event_duration * users_to_track * request_per_user * cost_per_request
        cost += cold_start_initial_users * request_per_user * cost_per_request
    return cost
Exemplo n.º 7
0
def random_position(a, b):
    """Draw from a bimodal distribution with support in (a,b).

    This is just two triangular distributions glued together.  Empirically
    it's a nice way to build the word clouds, but it should be replaced at
    some point with something more sophisticated.  See the note below.

    Here's the idea behind the crazy bimodal distribution:
        *   If we drop the words too close to the axes they'll just stack up
            and we get something that looks like a plus
        *   If we drop a word at the corner of the region it'll stack right
            above the previous word dropped from that direction, then get
            shoved left.  The result looks like a square.
        *   Dropping halfway between the axis and the corner will result in
            something halfway in-between (usually a hexagon)

    I think that what this method is `approximating' is the following:
        *   Divide the area into quadrants
        *   Keep track of the area covered in each quadrant
        *   Drop the new word in a random position on the edge of the
            quadrant with the least coverage
    """
    if random.choice([ 0, 1 ]):
        return random.triangular(a, 0.5*(a+b))
    else:
        return random.triangular(0.5*(a+b), b)
Exemplo n.º 8
0
 def randomize(self, random_state=1):
     """Randomize."""
     self.random_state = random_state
     random.seed(self.random_state)
     self.nearest_neighbors_threshold = \
         int(random.triangular(0,
                               2 * self.nearest_neighbors_threshold,
                               self.nearest_neighbors_threshold))
     self.true_class_bias = \
         random.triangular(0,
                           2 * self.true_class_bias,
                           self.true_class_bias)
     self.multi_class_bias = \
         random.triangular(0,
                           2 * self.multi_class_bias,
                           self.multi_class_bias)
     self.multi_class_threshold = \
         random.triangular(0,
                           2 * self.multi_class_threshold,
                           self.multi_class_threshold)
     self.true_class_threshold = \
         random.triangular(0,
                           2 * self.true_class_threshold,
                           self.true_class_threshold)
     logger.debug(self.__str__())
Exemplo n.º 9
0
 def impulse(self):
     for body in self.group.dynamicBodies():
         if body.acc.z == 0:
             body.vel.x = round(random.triangular(-.5,.5), self.group.precision)
             body.vel.y = round(random.triangular(-.5,.5), self.group.precision)
             body.vel.z = round(random.triangular(0,1.5), self.group.precision)
             self.group.wakeBody(body)
Exemplo n.º 10
0
def create_fake_financial_support():
    semesters = list(Semester.objects.all())
    for _ in range(50):
        s = Scholarship(
                scholarship_type=random.choice(ScholarshipType.objects.all()),
                student=random.choice(all_gradstudents.values()),
                amount=random.triangular(100.0, 20000.0, 5000.0),
                start_semester=random.choice(semesters),
                end_semester=random.choice(semesters),
                )
        s.save()
        all_financial_support.append(s)
    for _ in range(20):
        of = OtherFunding(
                student=random.choice(all_gradstudents.values()),
                semester=random.choice(semesters),
                description=randdesc(40),
                amount=random.triangular(100.0, 20000.0, 5000.0),
                eligible=randbool())
        of.save()
        all_financial_support.append(of)
    for _ in range(40):
        p = Promise(
                student=random.choice(all_gradstudents.values()),
                amount=random.triangular(100.0, 40000.0, 20000.0),
                start_semester=random.choice(semesters),
                end_semester=random.choice(semesters),
                )
        p.save()
        all_financial_support.append(p)
Exemplo n.º 11
0
	def step(self, prev_xy):
		if self.map.player_xy in self.map.objs:
			for obj in self.map.objs[self.map.player_xy]:
				if isinstance(obj, StairUp) and prev_xy != self.map.player_xy:
					self.map = self.map.prev
				elif isinstance(obj, StairDown) and prev_xy != self.map.player_xy:
					if not self.map.next:
						t = copy.copy(self.map.type)
						t.stairup = True
						t.stairdown = True
						t.size = random.choice((t.tiny, t.small, t.medium))
						t.treasure_level = int(random.triangular(0.0, 9.9, math.sqrt(self.map.level)))
						t.monster_level = int(random.triangular(0.0, 9.9, math.sqrt(self.map.level)))
						self.map.next = Map(t)
						self.map.next.prev = self.map
					self.map = self.map.next
					return
				obj.on_player(self.player)
			self.map.objs[self.map.player_xy][:] = [x for x in self.map.objs[self.map.player_xy] if x.delete == False]
			
		self.map.objs_lock = True
		for pos, objs in self.map.objs.items():
			for obj in objs:
				obj.step(pos, self.map, self.player)
		self.map.objs = {k: [x for x in self.map.objs[k] if x.delete == False] for k in self.map.objs.keys()}
		self.map.objs_lock = False
		
		self.player.lust += 1
Exemplo n.º 12
0
def modify_surface():
    
    perlin = True
    sel = mc.ls(selection=True,long=True)
    for verts in sel:
        totalVerts = mc.polyEvaluate(verts, vertex=True)
        for number in xrange(totalVerts):
            if perlin == True:
				frequency = 1.0
				amplitude = 1.5
				octaves = 8
				for o in xrange(octaves):
				    randX = random.triangular(-0.2 , 0.0, 0.2)
				    posX = perlinNoise(randX ,0,0)
				    
				    randY = random.triangular(-0.4 , 0.0, 0.6)
				    posY = perlinNoise(0,randY,0)
				    
				    randZ = random.triangular(-0.2 , 0.0, 0.2)
				    posZ = perlinNoise(0,0,randZ)
				    
				    posX *= frequency
				    posY *= frequency
				    posZ *= frequency 
				    
				    mc.select(verts+'.vtx[{number}]'.format(number=number))
				    mc.move(posX,posY*amplitude,posZ,relative=True)
				    mc.rotate(posY*amplitude,y=True)
    mc.select(sel, replace=True)
    mc.makeIdentity(s=True, a=True, t=True,r=True)
Exemplo n.º 13
0
    def create_noble(self, mode = "manual"):
        if mode == "manual":
            intel = self.Controller.get_input("What is the Nobles intelligence? (0 - 10)", "int")
            ambition = self.Controller.get_input("What is the Nobles ambition? (0 - 10)", "int")
            network = self.Controller.get_input("How strong is the Nobles network? (0 - 10)", "int")
            wealth = self.Controller.get_input("How wealthy is the Noble? (0 - 10)", "int")
            while True:
                gender = str(input("Male or Female? (m/f)"))
                gender = gender.lower()
                if gender == "m" or gender == "f":
                    break
                print("Sorry, I don't have enough programming skill to deal with non-binary genders")

        elif mode == "random":
            intel = int(round(random.triangular(0, 10)))
            ambition = int(round(random.triangular(0, 10)))
            network = int(round(random.triangular(0, 10)))
            wealth = int(round(random.triangular(0, 10)))
            gender = random.choice(["m", "f"])

        nobility = (network + wealth) / 2

        names = self.create_noble_name(gender, nobility)
        egg = self.egg_checker(names[0])
        if egg:
            names = egg
            stats = egg[3]
            intel = stats[0]
            ambition = stats[1]
            network = stats[2]
            wealth = stats[3]
            gender = stats[4]

        full_name = names[0]
        full_title = names[1]
        extended_title = title = names[2]

        stats = {
            "full_name": full_name,
            "full_title": full_title,
            "extended_title": extended_title,
            "intel": intel,
            "ambition": ambition,
            "network": network,
            "wealth": wealth,
            "gender": gender,
            "employed": False                   #Adding an "employed" stat here
        }
        self.nobles[full_name] = stats

        self.save_file()
        print("")
        print("New noble added!\nName: %s\nIntelligence: %d\nAmbition: %d\nNetwork: %d\nWealth: %s" % (
            extended_title,
            intel,
            ambition,
            network,
            wealth
            ))
        print("")
Exemplo n.º 14
0
def pytest_generate_tests(metafunc):
    """
    Generate the arguments for test functions.
    """

    if "graph" in metafunc.funcargnames:
        wgraphs = []

        # 100 vertex random graph
        a = nx.gnp_random_graph(100, 0.1)
        for e in a.edges_iter(data = True):
            e[2]['weight'] = triangular(-2, 2, 0)
        deg = sg.wgraph.make_deg(a.order(), create_iter(a.edges_iter(data = True)))
        b = sg.wgraph.make(a.order(), a.size(), create_iter(a.edges_iter(data = True)), deg)
        wgraphs.append((a, b))
        
        # 100 vertex random graph with parallel edges
        a = nx.gnp_random_graph(100, 0.1)
        for e in a.edges_iter(data = True):
            e[2]['weight'] = triangular(-2, 2, 0)
        deg = sg.wgraph.make_deg(a.order(), chain(create_iter(a.edges_iter(data = True)), create_iter(a.edges_iter(data = True))))
        b = sg.wgraph.make(a.order(), 2 * a.size(), chain(create_iter(a.edges_iter(data = True)), create_iter(a.edges_iter(data = True))), deg)
        wgraphs.append((a, b))
        
        # 100 vertex random graph with overestimated edge count
        a = nx.gnp_random_graph(100, 0.1)
        for e in a.edges_iter(data = True):
            e[2]['weight'] = triangular(-2, 2, 0)
        deg = sg.wgraph.make_deg(a.order(), create_iter(a.edges_iter(data = True)))
        b = sg.wgraph.make(a.order(), 2 * a.size(), create_iter(a.edges_iter(data = True)), deg)
        wgraphs.append((a, b))
        
        metafunc.parametrize("graph", wgraphs)
Exemplo n.º 15
0
    def __init__(self, n_cols=MAP_COL_COUNT, n_rows=MAP_ROW_COUNT):
        self.size = (n_cols, n_rows)
        self.columns = list()

        #generate the tiles for the map
        for col in range(n_cols):
            column = list()
            for row in range(n_rows):
                column.append(Tile([col, row]))

            self.columns.append(column)

        #select starting location for town
        start_loc = [   int(random.triangular(0,n_cols)),
                        int(random.triangular(0,n_rows))]
                    
        self.start_tile = self.tileAt(start_loc)

        self.generateLandmassAround(start_loc)
        self.generateForests()
        self.generateMountains()

        self.start_tile.setTerrain(Terrain.GRASS)
        self.start_tile.addNewUnit(UnitType.SETTLER)
        
        self.selected_tile = None
Exemplo n.º 16
0
def assign_carbs(sugar, last_carbs, sugar_in_range):
    """ Assign next 'meal' event based on:
        sugar -- the current glucose level 
        last_carb -- the previous carb value
        sugar_in_range -- list of previous consecutive 'in range' sugar events 
    """
    if sugar >= 240:
        carbs = random.uniform(-300, -290)
    elif sugar >= 200:
        carbs = random.triangular(-250, -180, -220)
    elif len(sugar_in_range) >= 3:
        high_or_low = random.randint(0,1) #if sugar in range, randomley generate high or low event
        if high_or_low == 0:
            carbs = random.uniform(230, 250)
        else:
            carbs = random.uniform(-250, 250)
    elif sugar <= 50:
        carbs = random.triangular(270, 300, 290)
    elif sugar <= 80:
        carbs = random.triangular(200, 250, 230)
    elif last_carbs > 50:
        carbs = random.uniform(-190, -170)
    else:
        carbs = random.triangular(-50, 100, 60)
    return carbs
Exemplo n.º 17
0
def generate_random_data(start_date, end_date, imei, name, lat, lon):
    try:
        start_time = datetime(*[int(i) for i in start_date.split("-")])
        end_time = datetime(*[int(i) for i in end_date.split("-")])
        #assert (imei=="" or imei== None), "IMEI cannot be blank"
        #assert (name=="" or name== None), "Name cannot be blank"
        #assert (lat=="" or lat== None), "Lat cannot be blank"
        #assert (lon=="" or lon== None), "Long cannot be blank"
        for ts in datespan(start_time, end_time, delta=timedelta(minutes=5)):
            aqf = AQFeed()
            aqf.imei=imei
            aqf.name=name            
            aqf.humidity = random.random(1,100) + random.random()
            aqf.temperature = random.random(15,45) + random.random()
            aqf.pm10 = random.random(1,500) + random.random()
            aqf.pm25 = random.random(1,1000) + random.random()
            aqf.count_large = random.triangular(1,500) + random.random()
            aqf.count_small = random.triangular(1,900) + random.random()
            aqf.lat = lat
            aqf.lon = lon
            aqf.created_on=ts
            aqf.save()                    
            
    except: 
        print "Usage::"
        print  "generate_random_data(start_date, end_date, imei, name, lat, lon)" 
        print "Format of dates must be as :: YYYY-MM-DD-HH-MM "
        return 
Exemplo n.º 18
0
Arquivo: lab07.py Projeto: nhaliday/ai
def genetic(n, popsize=None, rate=0.5):
  if popsize is None:
    popsize = 2 * n
  if rate is None:
    rate = random.random()
  m = int(rate * popsize)

  population = []
  for i in range(popsize):
    population.append(Chromosome(n))
  population.sort()

  generations = 0
  while not is_solution(population[0]):
    del population[-m:]
    for i in range(math.floor(m / 2) if len(population) > 1 else 0):
      j = int(random.triangular(0, len(population) - 1, 0))
      k = int(random.triangular(j + 1, len(population), j + 1))
      # triangular distribution is biased toward low end
      chrom1, chrom2 = crossover(population[j], population[k])
      bisect.insort(population, chrom1)
      bisect.insort(population, chrom2)
    for i in range(math.ceil(m / 2) if len(population) > 1 else m):
      j = int(random.triangular(0, len(population), 0))
      bisect.insort(population, mutate(population[j]))
    generations += 1

  return True, population[0]
Exemplo n.º 19
0
        def create_sub_strands(splines, points=None):
            new_splines = []
            if not points:
                resolution_points = [curve_tools.get_nurbs_points(spline)
                                     for spline in splines]
            else:
                resolution_points = points
            for _ in range(0, len(resolution_points), 2):
                # Pick a random spline to start from
                spline1 = random.choice(resolution_points)
                # Pick a random spline to end which is not the start spline
                for _ in range(9999):
                    spline2 = random.choice(resolution_points)
                    if not spline2 == spline1:
                        break
                # Pick a random start point from spline1
                start_index = int(random.triangular(0, len(spline1)))
                start_point = spline1[start_index]
                # Pick a ranomd end point from spline2
                end_index = int(random.triangular(0, len(spline2)))
                end_point = spline2[end_index]
                # Create the mid point
                mid_point = start_point + (end_point - start_point) * 0.5
                new_spline = (start_point, mid_point, end_point)
                # Drape the spline
                new_spline = drape_spline(new_spline)
                new_splines.append(new_spline)
                splines.append(new_spline)

            return new_splines
Exemplo n.º 20
0
def partially_matched(parent1, parent2):
    """Return a new chromosome created via partially matched crossover (PMX).

    This is suitable for permutation encoded GAs. Partially matched crossover
    respects the absolute position of alleles.
    """
    third = len(parent1) // 3
    l1 = int(random.triangular(1, third, third * 2))
    l2 = int(random.triangular(third, third * 2, len(parent1) - 1))

    if l2 < l1:
        l1, l2 = l2, l1

    matching = parent2[l1:l2]
    displaced = parent1[l1:l2]
    child = parent1[0:l1] + matching + parent1[l2:]

    tofind = [item for item in displaced if item not in matching]
    tomatch = [item for item in matching if item not in displaced]

    for k, v in enumerate(tofind):
        subj = tomatch[k]
        locus = parent1.index(subj)
        child[locus] = v

    return child
Exemplo n.º 21
0
def write_songs(artist, song_list, parsed_url):
    length = len(song_list)
    count = 0
    selected_indices = []
    while count < length:
        # Find a random index from the song_list and ensure it is new.
        rand_idx = random.randint(0, length - 1)
        while rand_idx in selected_indices:
            rand_idx = random.randint(0, length - 1)

        song           = song_list[rand_idx]
        song_path      = os.path.join(DATA_PATH, artist)
        song_file_name = filey.scrub_file_name(song.name + SONG_EXT)

        if filey.already_exists(song_path, song_file_name):
            print "%s already exists. Continuing." % (song_file_name)
        else:
            # Be like human.
            sleep(random.triangular(4.8, 7.23, 12.4))
            rand_int = random.randint(0, 10)
            if rand_int == 9:
                sleep(random.triangular(2.6, 10, 7))
            song_data = get_song_lyrics(parsed_url, song.url)
            filey.write_to_file(song_path, song_file_name, song_data)

        selected_indices.append(rand_idx)
        count += 1
Exemplo n.º 22
0
    def _generate(self):
        self.card_list = [1]
        while sum(self.card_list) >= -150:
            bad_cards = [int(random.triangular(-1250, -450, -600)) for i in range(self.NUM_CARDS / 2)]
            good_cards = [int(random.triangular(250, 900, 300)) for i in range(self.NUM_CARDS / 2)]
            self.card_list = good_cards + bad_cards

        self.save()
Exemplo n.º 23
0
	def generate(self):
		y = int(random.triangular(100, self.height-300, self.height/2-100))
		yield y
		dy = 0
		for _ in range(self.width):
			dy += 1 if random.triangular(-3, 3, 0) > dy else -1
			y = max(100, min(self.height-300, y+dy))
			yield y
Exemplo n.º 24
0
 def updateActor(self, interval, world):
     """Update this smoke"""
     super(Smoke, self).updateActor(interval, world)
     #
     dx = random.triangular(*self.vx_range)*interval/1000.0
     dy = random.triangular(*self.vy_range)*interval/1000.0
     #
     self.move(dx, dy)
Exemplo n.º 25
0
def get_location(radius=90):
    lng_min = longitude - radius / abs(math.cos(math.radians(latitude)) * 69)
    lng_max = longitude + radius / abs(math.cos(math.radians(latitude)) * 69)
    lat_min = latitude - (radius / 69)
    lat_max = latitude + (radius / 69)
    lng = random.triangular(lng_min, lng_max)
    lat = random.triangular(lat_min, lat_max)
    return [lng, lat]
 def addRandomSpacesToString(self,maxNumSpaces,str):
     import random,math
     numSpaces=math.ceil(random.triangular(1,maxNumSpaces))
     i = 0
     while(i<numSpaces):
         pos = math.ceil(random.triangular(1,len(str)))
         str = str[:pos] + " " + str[pos:]
         i+=1
     return str
Exemplo n.º 27
0
 def render(self):
     glClear(GL_COLOR_BUFFER_BIT)
     glLoadIdentity()
     with engine_lock:
         self.scope.request_update()
         for note in midi_engine.notes.itervalues():
             if not hasattr(note, 'firefly'):
                 note.firefly = {
                     'pos': [note.midipitch - 21, 0, 0],
                     'xvel': random.triangular(-1, 1),
                     'yvel': random.triangular(-1, 1),
                     'size': 8 * note.volume**2.5 + 0.5,
                 }
                 self.notes.append(note)
                 prev_notes = self.notes_by_midipitch[note.midipitch]
                 if prev_notes:
                     for n in prev_notes[1:]:
                         n.weight *= prev_notes[0].weight
                 prev_notes.insert(0, note)
                 self.note_density += 1
         for n in reversed(self.notes):
             (color, norm_weight) = self.scope.get_note_color(n)
             pressed_note = self.notes_by_midipitch[n.midipitch][0]
             if n is pressed_note:
                 if norm_weight > 1:
                     color = apply_whitening_bonus(color, norm_weight)
                 alpha = min(norm_weight, 1.0)
             else:
                 alpha = n.weight * pressed_note.weight
             for i in range(3):
                 self.colors.data[:38,i].fill(color[i])
             remaining = max(0.001, 1 - n.firefly['pos'][1] / self.height)
             self.colors.data[:19,3].fill(alpha**0.33/3)#(alpha ** 0.33 + remaining) / 2)
             #self.colors.data[19:38,3].fill(0)#(alpha ** 0.5 * 0.1 + remaining**3) / 5)
             self.colors.data[38,3] = alpha ** 0.33 * 0.25 + 0.75
             self.colors.set_array(self.colors.data)
             with translated(*n.firefly['pos']):
                 with scaled(n.firefly['size'] * (remaining * max(0.05, alpha))**0.1):
                     with self.verts:
                         glVertexPointer(3, GL_FLOAT, 0, self.verts)
                     with self.colors:
                         glColorPointer(4, GL_FLOAT, 0, self.colors)
                     with self.indices:
                         glDrawElements(GL_TRIANGLES, 3*3*19, GL_UNSIGNED_INT, None)
     elapsed = self.scope.frame_elapsed
     self.note_density *= math.exp(-elapsed)  # ranges from 0 to 20
     for n in self.notes:
         n.firefly['xvel'] += random.triangular(-0.5, 0.5) * elapsed
         n.firefly['xvel'] = min(5, max(-5, n.firefly['xvel']))
         n.firefly['yvel'] += random.triangular(-0.5, 0.5) * elapsed
         n.firefly['yvel'] = min(5, max(-5, n.firefly['yvel']))
         n.firefly['pos'][0] += n.firefly['xvel'] * elapsed
         n.firefly['pos'][1] += (4 + 2.5*math.log1p(self.note_density) + n.firefly['yvel']) * elapsed
     remove = [n for n in self.notes if n.firefly['pos'][1] - n.firefly['size'] > self.height]
     for n in remove:
         self.notes.remove(n)
         self.notes_by_midipitch[n.midipitch].remove(n)
Exemplo n.º 28
0
 def do_damage(self,Enemy):
     if self.sword==True:
         damage_player=int(random.triangular(7,10))
         #random.triangular c'est fantastique, la proba du médian est supérieur à la proba des extrémités
         Enemy.hp -= damage_player
         return Enemy.hp
     else:
         damage_player=int(random.triangular(3,7))
         Enemy.hp -= damage_player
         return Enemy.hp
Exemplo n.º 29
0
    def getRandomPosition(self):
        """
        Return a random position inside the room.

        returns: a Position object.
        """
        x = random.triangular(0, self.width - 1)
        y = random.triangular(0, self.height - 1)
        
        return Position(x, y)
Exemplo n.º 30
0
    def generateNextTarget(self):
        tgtID=self.count
        tgtIntelValue=random.triangular(1,100,60)
        tgtIntelPriority=tgtIntelValue
        if(self.Tartype==0): #want all Pedestrians
            tgtType='Pedestrian'
            tgtStealth=random.triangular(0.1, 0.9, 0.5)
            tgtSpeed=random.normalvariate(1.44, 0.288)#based on project 1 data
        elif(self.Tartype==1): #want all Vehicles
            tgtType='Vehicle'
            tgtStealth=random.triangular(0.5, 0.95, 0.8)
            tgtSpeed=random.triangular(11.11, 19.44, 15.28)#based on average urban speed for several countries

        else:
            r=random.random()
            if r<0.5:
                tgtType='Vehicle'
                tgtStealth=random.triangular(0.5, 0.95, 0.8)
                tgtSpeed=random.triangular(11.11, 19.44, 15.28)#based on average urban speed for several countries
            else:
                tgtType='Pedestrian'
                tgtStealth=random.triangular(0.1, 0.9, 0.5)
                tgtSpeed=random.normalvariate(1.44, 0.288)#based on project 1 data
        tgtPredLoc=self.randNodes[self.count]
        tgtGoalTrackTime=random.triangular(60,600,300)
        tgtActualTrackTime=0
        tgtTrackAttempts=0
        self.currTargetTimestamp=self.currTargetTimestamp+random.triangular(1380,4200,2100)
        tgtData = [tgtID,tgtIntelValue,tgtIntelPriority,tgtType,tgtStealth,tgtSpeed,tgtPredLoc,tgtGoalTrackTime,tgtActualTrackTime,tgtTrackAttempts]
        self.targetTimestamps.append(self.currTargetTimestamp)
        self.targets[self.currTargetTimestamp] = tgtData
        self.count = self.count + 1
# The end-point value b may or may not be included in the range depending on floating-point rounding in the equation a + (b-a) * random().
a = 1
b = SAMPLE_SIZE
res = []
for _ in xrange(1, SAMPLE_SIZE):
    res.append(random.uniform(a, b))
plt.hist(res, buckets)

plt.subplot(623)
plt.xlabel("random.triangular")
# Return a random floating point number N such that low <= N <= high and with the specified mode between those bounds. The low and high bounds default to zero and one. The mode argument defaults to the midpoint between the bounds, giving a symmetric distribution.
low = 1
high = SAMPLE_SIZE
res = []
for _ in xrange(1, SAMPLE_SIZE):
    res.append(random.triangular(low, high))
plt.hist(res, buckets)

plt.subplot(624)
plt.xlabel("random.betavariate")
# Beta distribution. Conditions on the parameters are alpha > 0 and beta > 0. Returned values range between 0 and 1.
alpha = 1
beta = 10
res = []
for _ in xrange(1, SAMPLE_SIZE):
    res.append(random.betavariate(alpha, beta))
plt.hist(res, buckets)

plt.subplot(625)
plt.xlabel("random.expovariate")
# Exponential distribution. lambd is 1.0 divided by the desired mean. It should be nonzero. (The parameter would be called “lambda”, but that is a reserved word in Python.) Returned values range from 0 to positive infinity if lambd is positive, and from negative infinity to 0 if lambd is negative.
Exemplo n.º 32
0
blens = [] 
blens += [beat * 0.25] * 5 
blens += [beat * 0.5] * 25 
blens += [beat] * 25 

random.seed(1992)
drift = 0 
while pos < tlength:
    length = random.choice(blens)
    freqs = get_freqs(count // 3)
    params = []
    reps = random.choice([1,2,3,4,8])
    dist = random.choice(blens) / reps

    for _ in range(reps):
        freq = freqs[(count2 // random.randint(1,3)) % len(freqs)] * 2**random.randint(0, 3)
        amp = random.triangular(0.05, 0.15)
        note = make_note(freq, amp, length)
        out.dub(note, pos)
        count2 += 1
        pos += dist + drift
        drift += random.triangular(-0.002, 0.005)

    count += 1

out.write('%s/osc2d_out.wav' % PATH)

elapsed_time = time.time() - start_time
print('Render time: %s seconds' % round(elapsed_time, 2))
print('Output length: %s seconds' % out.dur)
Exemplo n.º 33
0
# depending on floating-point rounding in the equation a + (b-a)*random()
a = 1
b = SAMPLE_SIZE
res = [random.uniform(a, b) for _ in range(1, SAMPLE_SIZE)]
plt.hist(res, buckets)

plt.subplot(623)
plt.xlabel("random.triangular")
# Return a random floating point number N such that low <= N <= high
# and with the specified mode between those bounds
# The low and high bounds default to zero and one
# The mode argument defaults to the midpoint between the bounds, giving
# a symmetric distribution
low = 1
high = SAMPLE_SIZE
res = [random.triangular(low, high) for _ in range(1, SAMPLE_SIZE)]
plt.hist(res, buckets)

plt.subplot(624)
plt.xlabel("random.betavariate")
alpha = 1
beta = 10
res = [random.betavariate(alpha, beta) for _ in range(1, SAMPLE_SIZE)]
plt.hist(res, buckets)

plt.subplot(625)
plt.xlabel("random.expovaraite")
lambd = 1.0 / ((SAMPLE_SIZE + 1) / 2.)
res = [random.expovariate(lambd) for _ in range(1, SAMPLE_SIZE)]
plt.hist(res, buckets)
Exemplo n.º 34
0
    def _build_main_request(self, subrequests, player_position=None):
        self.log.debug('Generating main RPC request...')

        request = RequestEnvelope()
        request.status_code = 2
        request.request_id = self.get_rpc_id()
        request.accuracy = random.choice(
            (5, 5, 5, 5, 10, 10, 10, 30, 30, 50, 65, random.uniform(66, 80)))

        if player_position:
            request.latitude, request.longitude, altitude = player_position

        # generate sub requests before Signature generation
        request = self._build_sub_requests(request, subrequests)

        ticket = self._auth_provider.get_ticket()
        if ticket:
            self.log.debug(
                'Found Session Ticket - using this instead of oauth token')
            request.auth_ticket.expire_timestamp_ms, request.auth_ticket.start, request.auth_ticket.end = ticket
            ticket_serialized = request.auth_ticket.SerializeToString()

        else:
            self.log.debug(
                'No Session Ticket found - using OAUTH Access Token')
            request.auth_info.provider = self._auth_provider.get_name()
            request.auth_info.token.contents = self._auth_provider.get_access_token(
            )
            request.auth_info.token.unknown2 = self.token2
            ticket_serialized = request.auth_info.SerializeToString(
            )  #Sig uses this when no auth_ticket available

        sig = Signature()

        sig.session_hash = self.session_hash
        sig.timestamp = get_time(ms=True)
        sig.timestamp_since_start = get_time(ms=True) - RpcApi.START_TIME
        if sig.timestamp_since_start < 5000:
            sig.timestamp_since_start = random.randint(5000, 8000)

        self._hash_engine.hash(sig.timestamp, request.latitude,
                               request.longitude, request.accuracy,
                               ticket_serialized, sig.session_hash,
                               request.requests)
        sig.location_hash1 = self._hash_engine.get_location_auth_hash()
        sig.location_hash2 = self._hash_engine.get_location_hash()
        for req_hash in self._hash_engine.get_request_hashes():
            sig.request_hash.append(ctypes.c_uint64(req_hash).value)

        loc = sig.location_fix.add()
        sen = sig.sensor_info.add()

        sen.timestamp_snapshot = random.randint(
            sig.timestamp_since_start - 5000, sig.timestamp_since_start - 100)
        loc.timestamp_snapshot = random.randint(
            sig.timestamp_since_start - 5000, sig.timestamp_since_start - 1000)

        loc.provider = random.choice(
            ('network', 'network', 'network', 'network', 'fused'))
        loc.latitude = request.latitude
        loc.longitude = request.longitude

        loc.altitude = altitude or random.triangular(300, 400, 350)

        if random.random() > .95:
            # no reading for roughly 1 in 20 updates
            loc.course = -1
            loc.speed = -1
        else:
            self.course = random.triangular(0, 360, self.course)
            loc.course = self.course
            loc.speed = random.triangular(0.2, 4.25, 1)

        loc.provider_status = 3
        loc.location_type = 1
        if request.accuracy >= 65:
            loc.vertical_accuracy = random.triangular(35, 100, 65)
            loc.horizontal_accuracy = random.choice(
                (request.accuracy, 65, 65, random.uniform(66, 80), 200))
        else:
            if request.accuracy > 10:
                loc.vertical_accuracy = random.choice(
                    (24, 32, 48, 48, 64, 64, 96, 128))
            else:
                loc.vertical_accuracy = random.choice((3, 4, 6, 6, 8, 12, 24))
            loc.horizontal_accuracy = request.accuracy

        sen.linear_acceleration_x = random.triangular(-3, 1, 0)
        sen.linear_acceleration_y = random.triangular(-2, 3, 0)
        sen.linear_acceleration_z = random.triangular(-4, 2, 0)
        sen.magnetic_field_x = random.triangular(-50, 50, 0)
        sen.magnetic_field_y = random.triangular(-60, 50, -5)
        sen.magnetic_field_z = random.triangular(-60, 40, -30)
        sen.magnetic_field_accuracy = random.choice((-1, 1, 1, 2, 2, 2, 2))
        sen.attitude_pitch = random.triangular(-1.5, 1.5, 0.2)
        sen.attitude_yaw = random.uniform(-3, 3)
        sen.attitude_roll = random.triangular(-2.8, 2.5, 0.25)
        sen.rotation_rate_x = random.triangular(-6, 4, 0)
        sen.rotation_rate_y = random.triangular(-5.5, 5, 0)
        sen.rotation_rate_z = random.triangular(-5, 3, 0)
        sen.gravity_x = random.triangular(-1, 1, 0.15)
        sen.gravity_y = random.triangular(-1, 1, -.2)
        sen.gravity_z = random.triangular(-1, .7, -0.8)
        sen.status = 3

        sig.unknown25 = 5348175887752539474

        if self.device_info:
            for key in self.device_info:
                setattr(sig.device_info, key, self.device_info[key])
            if self.device_info['device_brand'] == 'Apple':
                sig.activity_status.stationary = True
        else:
            sig.activity_status.stationary = True

        signature_proto = sig.SerializeToString()

        try:
            if request.requests[0].request_type in (
                    RequestType.Value('GET_MAP_OBJECTS'),
                    RequestType.Value('GET_PLAYER')):
                plat_eight = UnknownPtr8Request()
                plat_eight.message = '15c79df0558009a4242518d2ab65de2a59e09499'
                plat8 = request.platform_requests.add()
                plat8.type = 8
                plat8.request_message = plat_eight.SerializeToString()
        except (IndexError, AttributeError):
            pass

        sig_request = SendEncryptedSignatureRequest()
        sig_request.encrypted_signature = pycrypt(signature_proto,
                                                  sig.timestamp_since_start)
        plat = request.platform_requests.add()
        plat.type = 6
        plat.request_message = sig_request.SerializeToString()

        request.ms_since_last_locationfix = int(
            random.triangular(300, 30000, 10000))

        self.log.debug('Generated protobuf request: \n\r%s', request)

        return request
Exemplo n.º 35
0
def gerar_dados_aleatorios():

    global VEL, APPS, TM, IMD, BMS, BSPD, PRESS1, HV

    sinal = [("0", 1), ("1", 50)]                                  
    list = [prize for prize, weight in sinal for i in range(weight)]
    bateria = 100
    temperatura = random.uniform(24,25)
    vel = 40
    pressao = 5

    while 1:

        # Dados de dois estados dos componentes do Shutdown
        IMD = random.choice(list)
        BMS = random.choice(list)
        BSPD = random.choice(list)

        # Dados do nível da bateria do HV
        aux1 = random.randrange(2)
        bateria = bateria - aux1 
        if bateria > 0 :
            HV = bateria
        else:
            HV = 0   

        # Dados da temperatura do motor
        aux2= random.random()
        temperatura = temperatura + aux2/2
        if temperatura < 60:
            TM = temperatura
        else:
            TM = 60

        # Dados da velocidade
        aux3=random.triangular(-3,3,0)
        vel = vel + aux3
        if 0 < vel < 90:
            VEL = vel

        # Dados das Pressões no fluido de freio
        aux4 = random.uniform(-3,3)
        pressao = pressao + aux4
        if 0 < pressao <= 80:
            PRESS1 = pressao
        if -2 < pressao < 0:
            PRESS1 = PRESS2 = random.uniform(60,70)
        if -4 < pressao < -2:
            PRESS1 = PRESS2 = random.uniform(0,3)
        if pressao <= -4:
            PRESS1 = PRESS2 = random.uniform(50,70)
        if pressao > 80:
            PRESS1 = PRESS2 = random.uniform(0,10)    
        if 0 < pressao < 2:
            PRESS2 = pressao 
        if 2 <= pressao < 10:
            PRESS2 = pressao - random.random()
        if 10 <= pressao <= 80:
            PRESS2 = pressao - random.uniform(0,5)  
        APPS = (PRESS1 + PRESS2) /2 * 1.25

        print(VEL)
 def service(self, patient):
     service_time = random.triangular(8, 20, 12)
     yield self.env.timeout(service_time)
     print("Imaging service started for patient %s." % (patient))
Exemplo n.º 37
0
    def _build_main_request(self,
                            subrequests,
                            platforms,
                            player_position=None):
        self.log.debug('Generating main RPC request...')

        request = RequestEnvelope()
        request.status_code = 2
        request.request_id = self.request_id
        # 5: 43%, 10: 30%, 30: 5%, 50: 4%, 65: 10%, 200: 1%, float: 7%
        request.accuracy = weighted_choice([(5, 43), (10, 30), (30, 5),
                                            (50, 4), (65, 10), (200, 1),
                                            (random.uniform(65, 200), 7)])

        if player_position:
            request.latitude, request.longitude, altitude = player_position

        # generate sub requests before Signature generation
        request = self._build_sub_requests(request, subrequests)
        request = self._build_platform_requests(request, platforms)

        ticket = self._auth_provider.get_ticket()
        if ticket:
            self.log.debug(
                'Found Session Ticket - using this instead of oauth token')
            request.auth_ticket.expire_timestamp_ms, request.auth_ticket.start, request.auth_ticket.end = ticket
            ticket_serialized = request.auth_ticket.SerializeToString()

        else:
            self.log.debug(
                'No Session Ticket found - using OAUTH Access Token')
            auth_provider = self._auth_provider
            request.auth_info.provider = auth_provider.get_name()
            request.auth_info.token.contents = auth_provider.get_access_token()
            request.auth_info.token.unknown2 = self.token2
            # Sig uses this when no auth_ticket available.
            ticket_serialized = request.auth_info.SerializeToString()

        sig = Signature()

        sig.session_hash = self.state.session_hash
        sig.timestamp = get_time(ms=True)
        sig.timestamp_since_start = get_time(ms=True) - self.start_time

        self._hash_engine.hash(sig.timestamp, request.latitude,
                               request.longitude, request.accuracy,
                               ticket_serialized, sig.session_hash,
                               request.requests)
        sig.location_hash1 = self._hash_engine.get_location_auth_hash()
        sig.location_hash2 = self._hash_engine.get_location_hash()
        for req_hash in self._hash_engine.get_request_hashes():
            sig.request_hash.append(ctypes.c_uint64(req_hash).value)

        loc = sig.location_fix.add()
        sen = sig.sensor_info.add()

        sen.timestamp_snapshot = sig.timestamp_since_start - int(
            random.triangular(93, 4900, 3000))
        loc.timestamp_snapshot = sig.timestamp_since_start - int(
            random.triangular(320, 3000, 1000))

        loc.provider = 'fused'
        loc.latitude = request.latitude
        loc.longitude = request.longitude

        loc.altitude = altitude or random.uniform(150, 250)

        if random.random() > .85:
            # no reading for roughly 1 in 7 updates
            loc.course = -1
            loc.speed = -1
        else:
            loc.course = self.state.course
            loc.speed = random.triangular(0.25, 9.7, 8.2)

        loc.provider_status = 3
        loc.location_type = 1
        if isinstance(request.accuracy, float):
            loc.horizontal_accuracy = weighted_choice([(request.accuracy, 50),
                                                       (65, 40), (200, 10)])
            loc.vertical_accuracy = weighted_choice([(random.uniform(10,
                                                                     96), 50),
                                                     (10, 34), (12, 5),
                                                     (16, 3), (24, 4), (32, 2),
                                                     (48, 1), (96, 1)])
        else:
            loc.horizontal_accuracy = request.accuracy
            if request.accuracy >= 10:
                loc.vertical_accuracy = weighted_choice([(6, 4), (8, 34),
                                                         (10, 35), (12, 11),
                                                         (16, 4), (24, 8),
                                                         (32, 3), (48, 1)])
            else:
                loc.vertical_accuracy = weighted_choice([(3, 15), (4, 39),
                                                         (6, 14), (8, 13),
                                                         (10, 14), (12, 5)])

        sen.magnetic_field_accuracy = weighted_choice([(-1, 8), (0, 2),
                                                       (1, 42), (2, 48)])
        if sen.magnetic_field_accuracy == -1:
            sen.magnetic_field_x = 0
            sen.magnetic_field_y = 0
            sen.magnetic_field_z = 0
        else:
            sen.magnetic_field_x = self.state.magnetic_field_x
            sen.magnetic_field_y = self.state.magnetic_field_y
            sen.magnetic_field_z = self.state.magnetic_field_z

        sen.linear_acceleration_x = random.triangular(-1.5, 2.5, 0)
        sen.linear_acceleration_y = random.triangular(-1.2, 1.4, 0)
        sen.linear_acceleration_z = random.triangular(-1.4, .9, 0)
        sen.attitude_pitch = random.triangular(-1.56, 1.57, 0.475)
        sen.attitude_yaw = random.triangular(-1.56, 3.14, .1)
        sen.attitude_roll = random.triangular(-3.14, 3.14, 0)
        sen.rotation_rate_x = random.triangular(-3.2, 3.52, 0)
        sen.rotation_rate_y = random.triangular(-3.1, 4.88, 0)
        sen.rotation_rate_z = random.triangular(-6, 3.7, 0)
        sen.gravity_x = random.triangular(-1, 1, 0.01)
        sen.gravity_y = random.triangular(-1, 1, -.4)
        sen.gravity_z = random.triangular(-1, 1, -.4)
        sen.status = 3

        sig.unknown25 = 0x4AE22D4661C83701

        if self.device_info:
            for key in self.device_info:
                setattr(sig.device_info, key, self.device_info[key])
            if self.device_info['device_brand'] == 'Apple':
                sig.activity_status.stationary = True
        else:
            sig.activity_status.stationary = True

        signature_proto = sig.SerializeToString()

        if self._needsPtr8(subrequests):
            plat_eight = UnknownPtr8Request()
            plat_eight.message = '15c79df0558009a4242518d2ab65de2a59e09499'
            plat8 = request.platform_requests.add()
            plat8.type = 8
            plat8.request_message = plat_eight.SerializeToString()

        sig_request = SendEncryptedSignatureRequest()
        sig_request.encrypted_signature = pycrypt(signature_proto,
                                                  sig.timestamp_since_start)
        plat = request.platform_requests.add()
        plat.type = 6
        plat.request_message = sig_request.SerializeToString()

        request.ms_since_last_locationfix = sig.timestamp_since_start - loc.timestamp_snapshot

        self.log.debug('Generated protobuf request: \n\r%s', request)

        return request
Exemplo n.º 38
0
 def test_mul(self):
     t = self.random_time()
     i = random.randint(1, 1000)
     self.assertEqual(t * i, sf.Time(microseconds=t.as_microseconds() * i))
     f = random.triangular(0.0, 100.0)
     self.assertEqual(t * f, sf.Time(seconds=t.as_seconds() * f))
Exemplo n.º 39
0
 def test_div(self):
     t = self.random_time()
     i = random.randint(1, 1000)
     self.assertEqual(t / i, sf.Time(microseconds=t.as_microseconds() / i))
     f = random.triangular(0.0, 100.0)
     self.assertEqual(t / f, sf.Time(seconds=t.as_seconds() / f))
Exemplo n.º 40
0
def triangular_sample(n):
    return [random.triangular(0, 100) for i in range(n)]
Exemplo n.º 41
0
#!/usr/bin/env python
# simple script emulating an executor generating benchmark results
from __future__ import print_function

import sys
import random

print(sys.argv)

print("Harness Name: ", sys.argv[1])
print("Bench Name:", sys.argv[2])
print("Warmup: ", sys.argv[3])

WARMUP = int(sys.argv[3])

for i in range(0, WARMUP):
    print("RESULT-total: ", random.triangular(700, 850) * 2)

print("RESULT-total: ", random.triangular(700, 850))
Exemplo n.º 42
0
 def _create_creature_pos(self):
     x = random.triangular(0, self.world.size)
     y = random.triangular(0, self.world.size)
     return int(x), int(y)
Exemplo n.º 43
0
def triangular_random(length):
    return triangular(0, length, length)
Exemplo n.º 44
0
def main():

    count = 0

    kafka_topic = re.sub('[^a-zA-Z0-9]', '_', channel)
    kafka_producer = kafka.KafkaProducer(bootstrap_servers=kafka_endpoint)

    print('[ INFO ] Using Kafka Topic = ' + str(kafka_topic))
    time.sleep(5)

    if simulate_feed == False:

        from satori.rtm.client import make_client, SubscriptionMode

        with make_client(endpoint=endpoint, appkey=appkey) as client:

            class SubscriptionObserver(object):
                def on_subscription_data(self, data):
                    for message in data['messages']:
                        message['_timestamp'] = int(time.time())
                        kafka_producer.send(kafka_topic,
                                            bytes(json.dumps(message)))
                        count += 1

            subscription_observer = SubscriptionObserver()
            client.subscribe(channel, SubscriptionMode.SIMPLE,
                             subscription_observer)

            try:
                while True:
                    time.sleep(1)
                    print("Messages sent to Kafka: " + str(count))
            except KeyboardInterrupt:
                pass

    elif simulate_feed == True:
        while True:
            time.sleep(1)
            # Simulate Data Feed
            datetimestamp = datetime.datetime.now()
            payload = random.choice([
                {
                    "cryptocurrency": "BTC",
                    "name": "bitcoin",
                    "price": round(random.triangular(7000, 13000, 9282), 2)
                },
                {
                    "cryptocurrency": "BCH",
                    "name": "bitcoin cash",
                    "price": round(random.triangular(400, 800, 650), 2)
                },
                {
                    "cryptocurrency": "ETH",
                    "name": "ethereum",
                    "price": round(random.triangular(400, 800, 650), 2)
                },
                {
                    "cryptocurrency": "LTC",
                    "name": "litecoin",
                    "price": round(random.triangular(1200, 1600, 1400), 2)
                },
            ])
            message = {
                "exchange":
                random.choice(
                    ['Coinbase', 'Coinmama', 'Bitpanda', 'Kraken', 'cex.io']),
                "cryptocurrency":
                payload['cryptocurrency'],
                "basecurrency":
                "USD",
                "type":
                "market",
                "price":
                payload['price'],
                "size":
                random.randint(1, 100),
                "bid":
                round(payload['price'] * random.triangular(0.95, 1, 0.98), 2),
                "ask":
                round(payload['price'] * random.triangular(1, 1.05, 1.1), 2),
                "open":
                round(payload['price'] * random.triangular(0.95, 1.05, 1), 2),
                "high":
                round(payload['price'] * random.triangular(0.95, 1.05, 1), 2),
                "low":
                round(payload['price'] * random.triangular(0.95, 1.05, 1), 2),
                "volume":
                random.randint(1, 10000),
                "_timestamp":
                int(time.time()),
                "timestamp":
                datetimestamp.strftime('%Y-%m-%dT%H:%M:%S.%fZ')
            }
            kafka_producer.send(kafka_topic,
                                json.dumps(message).encode('utf-8'))
            count += 1
            print("Messages sent to Kafka: " + str(count))
            print(json.dumps(message))

    else:
        print(
            '[ ERROR ] Simulate_feed variable may not set and also check to make sure Kafka host and port are correct.'
        )
        sys.exit()
Exemplo n.º 45
0
def get_index(num_samples):
    return int((num_samples * DIFF_POS) + random.triangular(-RAND_DIFF_WIDTH, RAND_DIFF_WIDTH))
Exemplo n.º 46
0
 def random_transform(self):
     return sf.Transform(*[random.triangular(0.0, 5.0) for i in range(9)])
Exemplo n.º 47
0
def populate(num_rats, min_wt, max_wt, mode_wt):
    """Initialize a population with a triangular distribution of weights."""
    return [int(random.triangular(min_wt, max_wt, mode_wt))\
            for i in range(num_rats)]
Exemplo n.º 48
0
 def random_rect(self):
     return sf.FloatRect(random.triangular(0.0, 100.0),
                         random.triangular(0.0, 100.0),
                         random.triangular(0.0, 100.0),
                         random.triangular(0.0, 100.0))
 def service(self, patient):
     service_time = random.triangular(4, 10, 6)
     yield self.env.timeout(service_time)
     print("Lab service started for patient %s." % (patient))
Exemplo n.º 50
0
def randomORF(length, maxlength=None):
    length -= 2
    if maxlength and maxlength > length:
        length = int(round(random.triangular(length, maxlength - 2)))

    cdns = (
        "TTT",
        "TTC",
        "TTA",
        "TTG",
        "TCT",
        "TCC",
        "TCA",
        "TCG",
        "TAT",
        "TAC",
        "TGT",
        "TGC",
        "TGG",
        "CTT",
        "CTC",
        "CTA",
        "CTG",
        "CCT",
        "CCC",
        "CCA",
        "CCG",
        "CAT",
        "CAC",
        "CAA",
        "CAG",
        "CGT",
        "CGC",
        "CGA",
        "CGG",
        "ATT",
        "ATC",
        "ATA",
        "ATG",
        "ACT",
        "ACC",
        "ACA",
        "ACG",
        "AAT",
        "AAC",
        "AAA",
        "AAG",
        "AGT",
        "AGC",
        "AGA",
        "AGG",
        "GTT",
        "GTC",
        "GTA",
        "GTG",
        "GCT",
        "GCC",
        "GCA",
        "GCG",
        "GAT",
        "GAC",
        "GAA",
        "GAG",
        "GGT",
        "GGC",
        "GGA",
        "GGG",
    )

    starts = ("ATG", )
    stops = ("TAA", "TAG", "TGA")

    return (random.choice(starts) +
            "".join([random.choice(cdns)
                     for x in range(length)]) + random.choice(stops))
Exemplo n.º 51
0
 def course(self):
     self._course = random.triangular(0, 359.99, self._course)
     return self._course
Exemplo n.º 52
0
def crossover_triangular(xs, ys):
    return [
        random.triangular(low=min(x, y), high=max(x, y))
        for x, y in zip(xs, ys)
    ]
Exemplo n.º 53
0
def randomDNA(length, maxlength=None):
    """ string! """
    if maxlength and maxlength > length:
        length = int(round(random.triangular(length, maxlength)))
    return "".join([random.choice("GATC") for x in range(length)])
Exemplo n.º 54
0
assert x1 == x2

tries = 8000
stat = [0, 0, 0, 0, 0, 0]

for i in range(tries):
    dice = random.randint(1, 6)
    stat[dice - 1] += 1

print("STATISTICS ON {0} DICE THROWS".format(tries))
print("-----------------------------")
for i in range(0, 6):
    percent = (float(stat[i]) * 100.) / float(tries)
    print("{0} : {1} ({2:.1f}%)".format(i + 1, stat[i], percent))

random.triangular(10, 20, 17)
random.normalvariate(10, 4)
random.lognormvariate(3, 1.6)
random.expovariate(3)
random.vonmisesvariate(2, 1)
random.gauss(10, 4)
random.betavariate(10, 4)
random.paretovariate(5)
random.weibullvariate(10, 6)

# issue 169
first = list(range(20))
random.seed(31416)
random.shuffle(first)
second = list(range(20))
random.seed(31416)
Exemplo n.º 55
0
import uuid
import random
import datetime
import time

services = []
clients = []
for i in range(0, 20):
    services.append(uuid.uuid4())

for i in range(0, 100):
    clients.append('.'.join('%s' % random.randint(0, 255)
                            for i in range(4)) + "," + str(uuid.uuid4()))

print "client-address,client-guid,request-time,service-guid,retries-request,packets-requested,packets-serviced,max-hole-size"
for i in range(0, 300):
    #print str(random.choice(clients)) + "," + (datetime.datetime.now() + datetime.timedelta(seconds=random.randint(0, 86400))).strftime("%Y-%m-%d %H:%M:%S ADT") + "," + str(random.choice(services)) \
    print str(random.choice(clients)) + "," + str(int(time.mktime((datetime.datetime.now() + datetime.timedelta(seconds=random.randint(0, 86400))).timetuple()))*1000 + random.randint(0,999)) + "," + str(random.choice(services)) \
    + "," + str(int(random.triangular(0, 10, 7))) + "," + str(int(random.triangular(0, 20, 15))) + "," + str(int(random.triangular(0, 20, 15))) + "," + str(int(random.triangular(0, 20, 15)))
Exemplo n.º 56
0
def make_wavetable():
    wtsize = random.randint(2, random.randint(3, 50))
    wavetable = [0] + [random.triangular(-1, 1)
                       for _ in range(wtsize - 2)] + [0]
    return wavetable
Exemplo n.º 57
0
 def r():
     return random.triangular(0.0, 100.0)
Exemplo n.º 58
0
# -*- encoding: utf-8 -*-
import random

print(random.seed())
print(random.random())  # 0~1
print(random.uniform(10, 1))  # same as print(random.uniform(1,10)
print(random.randint(1, 10))  # [1, 10]
print(random.randrange(1, 10))  # [1,10)

print(random.triangular(0, 10, 3))  # 三角分布
print(random.gauss(5, 10))  # 高斯分布
print(random.betavariate(2, 5))  # beta β分布
print(random.expovariate(10))  # 指数分布
print(random.gammavariate(5, 10))  # 伽马分布
print(random.lognormvariate(5, 10))  # 对数正态分布
print(random.normalvariate(5, 10))  # 正态分布
print(random.vonmisesvariate(2, 5))  # 冯米塞斯分布
print(random.paretovariate(2))  # 帕累托分布
print(random.weibullvariate(2, 5))  # 韦伯分布

li = [random.randint(1, 100) for x in range(0, 10)]
print(li)
random.shuffle(li)  # return None
print(li)
print(random.choice(li))
print(random.choices(li, weights=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], k=3))
# same as print(random.choices(li,cum_weights=[1,3,6,10,15,21,28,36,45,55],k=3))
# means li[0] has 1/55 probability to be selected, etc
print(random.sample(li, 3))
Exemplo n.º 59
0
def make_note(freq, amp, length):
    lfo = dsp.SINE
    lfo_freq = random.triangular(0.001, 15)

    # Frequency modulation wavetable
    mod = wavetables.randline(random.randint(10, 30))

    # Frequency of the freq mod wavetable
    mod_freq = random.triangular(0.001, 2)

    # Range / depth of the freq mod wavetable
    mod_range = random.triangular(0, 0.025)

    pulsewidth = random.random()

    # Fill up a stack of wavetables to give to the Osc.
    # The lfo wavetable above will control the morph position 
    # in the wavetable stack during the render.
    stack = []
    numtables = random.randint(3, 30)
    for _ in range(numtables):
        if random.random() > 0.25:
           stack += [ random.choice([dsp.SINE, dsp.TRI]) ]
        else:
           stack += [ wavetables.randline(random.randint(3, random.randint(5, 50))) ]

    # ADSR params
    a = random.triangular(0.1, 1)
    d = random.triangular(0.01, 3)
    s = random.triangular(0.03, 0.15)
    r = random.triangular(0.1, 10)

    # Render a note
    note = oscs.Osc(
                stack=stack, 
                window=dsp.SINE,
                mod=mod, 
                pulsewidth=pulsewidth, 
                mod_freq=mod_freq, 
                mod_range=mod_range, 
                lfo=lfo, 
                lfo_freq=lfo_freq
            ).play(length=length, freq=freq, amp=amp).adsr(a=a,d=d,s=s,r=r)

    # Sometimes mix in a granulated layer of the note
    if random.random() > 0.75:
        a = random.triangular(5, 10)
        d = random.triangular(0.1, 20)
        s = random.triangular(0.01, 0.1)
        r = random.triangular(5, 10)
        minlength = (note.dur/50)*1000
        maxlength = (note.dur/3)*1000 

        arp = note.cloud(length * random.triangular(1.5, 3), 
                    window=dsp.HANN, 
                    grainlength=wavetables.randline(random.randint(10, 100), lowvalue=minlength, highvalue=maxlength),
                    spread=1, 
                    speed=random.choice([1, 1.5, 2]),
                    jitter=random.triangular(0, 0.05),
                    grid=wavetables.randline(random.randint(5, 50), lowvalue=0.1, highvalue=random.triangular(0.25, 0.75)),
                ).adsr(a,d,s,r)
        note.dub(arp, 0)

    return note
Exemplo n.º 60
0

def make_wavetable():
    wtsize = random.randint(2, random.randint(3, 50))
    wavetable = [0] + [random.triangular(-1, 1)
                       for _ in range(wtsize - 2)] + [0]
    return wavetable


out = dsp.buffer()

chords = 'ii vi V7 I69'

dubhead = 0
for chord in chords.split(' ') * 8:
    chordlength = random.triangular(2, 3)  # in seconds
    freqs = tune.chord(chord, key='e', octave=2)
    numnotes = random.randint(3, 6)

    notes = []

    for _ in range(numnotes):
        notelength = random.triangular(0.1, 2)
        freq = random.choice(freqs)
        amp = random.triangular(0.1, 0.25)

        note = oscs.Osc(wavetable=make_wavetable()).play(notelength, freq, amp)
        note = note.env(dsp.RND)
        note = note.taper(0.01)
        note = note.pan(random.random())