Python random.normalvariate() Examples

The following are code examples for showing how to use random.normalvariate(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: MuscleSpindleCircuitsModel   Author: FormentoEmanuele   File: AfferentFiber.py    MIT License 6 votes vote down vote up
def set_firing_rate(self,fr,noise=True):
		""" Set the afferent firing rate.

		Keyword arguments:
		fr -- firing rate in Hz
		"""

		if fr == self._oldFr: return
		if fr<=0:
			self._interval = 99999.
		elif fr>=self.maxFiringRate:
			self._interval = 1000.0/self.maxFiringRate
		elif fr<self.maxFiringRate and noise:
			mean = 1000.0/fr #ms
			sigma = mean*0.2
			self._interval = rnd.normalvariate(mean,sigma)
		else: self._interval = 1000.0/fr #ms
		self._oldFr = fr

		# Check whether after setting the new fr the fiber is ready to fire
		if (h.t-self._lastNaturalSpikeTime)>=self._interval-(self.__class__.__updatePeriod/2.):
			# In this case, shift a bit randomly the last natural spike time in order to reduce an
			# artificially induced synchronized activity between the different modeled fibers
			self._lastNaturalSpikeTime = h.t-np.random.uniform(self._interval/2.,self._interval,1) 
Example 2
Project: IE_MBom   Author: mikewolfli   File: populate.py    The Unlicense 6 votes vote down vote up
def createData(rows=20, cols=5):
    """Creare random dict for test data"""

    data = {}
    names = createRandomStrings(rows,16)
    colnames = createRandomStrings(cols,5)
    for n in names:
        data[n]={}
        data[n]['label'] = n
    for c in range(0,cols):
        colname=colnames[c]
        vals = [round(random.normalvariate(100,50),2) for i in range(0,len(names))]
        vals = sorted(vals)
        i=0
        for n in names:
            data[n][colname] = vals[i]
            i+=1
    return data 
Example 3
Project: PTBot   Author: whocares-openscene   File: gaming.py    GNU General Public License v3.0 6 votes vote down vote up
def n_rolls(count, n):
    """roll an n-sided die count times
    :type count: int
    :type n: int | str
    """
    if n == "F":
        return [random.randint(-1, 1) for x in range(min(count, 100))]
    if n < 2:  # it's a coin
        if count < 100:
            return [random.randint(0, 1) for x in range(count)]
        else:  # fake it
            return [int(random.normalvariate(.5 * count, (.75 * count) ** .5))]
    else:
        if count < 100:
            return [random.randint(1, n) for x in range(count)]
        else:  # fake it
            return [int(random.normalvariate(.5 * (1 + n) * count,
                                             (((n + 1) * (2 * n + 1) / 6. -
                                               (.5 * (1 + n)) ** 2) * count) ** .5))] 
Example 4
Project: PTBot   Author: whocares-openscene   File: gaming.py    GNU General Public License v3.0 6 votes vote down vote up
def coin(text, notice, action):
    """[amount] - flips [amount] coins
    :type text: str
    """

    if text:
        try:
            amount = int(text)
        except (ValueError, TypeError):
            notice("Invalid input '{}': not a number".format(text))
            return
    else:
        amount = 1

    if amount == 1:
        action("flips a coin and gets {}.".format(random.choice(["heads", "tails"])))
    elif amount == 0:
        action("makes a coin flipping motion")
    else:
        heads = int(random.normalvariate(.5 * amount, (.75 * amount) ** .5))
        tails = amount - heads
        action("flips {} coins and gets {} heads and {} tails.".format(amount, heads, tails)) 
Example 5
Project: CoDeepNEAT   Author: sash-a   File: module_node.py    MIT License 6 votes vote down vote up
def get_new_linear_parameter_mutagens():
    return {
        "regularisation": Option("regularisation", None, nn.BatchNorm1d,
                                 current_value=nn.BatchNorm1d if random.random() < config.module_node_batchnorm_chance else None,
                                 mutation_chance=0.15),

        "dropout": Option("regularisation", None, nn.Dropout,
                          current_value=nn.Dropout if random.random() < config.module_node_dropout_chance else None,
                          submutagens=
                          {
                              nn.Dropout: {
                                  "dropout_factor": ContinuousVariable("dropout_factor", current_value=0.15,
                                                                       start_range=0, end_range=0.75,
                                                                       mutation_chance=0.15)
                              }
                          }, mutation_chance=0.08),

        "out_features": IntegerVariable("out_features", current_value=int(random.normalvariate(mu=200, sigma=50)),
                                        start_range=10,
                                        end_range=1024, mutation_chance=0.22)
    } 
Example 6
Project: CoDeepNEAT   Author: sash-a   File: module_node.py    MIT License 6 votes vote down vote up
def get_new_regulariser_only_parameter_mutagens():
    return {
        "regularisation": Option("regularisation", None, 'batchnorm',
                                 current_value='batchnorm' if random.random() < config.module_node_batchnorm_chance else None,
                                 mutation_chance=0.15),

        "dropout": Option("regularisation", None, nn.Dropout,
                          current_value=nn.Dropout if random.random() < config.module_node_dropout_chance else None,
                          submutagens=
                          {
                              nn.Dropout: {
                                  "dropout_factor": ContinuousVariable("dropout_factor", current_value=0.15,
                                                                       start_range=0, end_range=0.75,
                                                                       mutation_chance=0.15)
                              }
                          }, mutation_chance=0.08),

        "out_features": IntegerVariable("out_features", current_value=int(random.normalvariate(mu=200, sigma=50)),
                                        start_range=10,
                                        end_range=1024, mutation_chance=0.22)
    } 
Example 7
Project: dl-cliche   Author: daisukelab   File: test_math.py    Apache License 2.0 6 votes vote down vote up
def test_online_stats(self):
        import random
        k = 50
        n = 1000
        a = np.array([[random.normalvariate(_k, 2) for _k in range(k)] for _ in range(n)])
        onstat = OnlineStats(k)

        for _a in a:
            onstat.put(_a)

        def is_in_range(value, amin=-1, amax=1):
            return (amin < value) and (value < amax)

        self.assertTrue(np.all([is_in_range(_1 - _2) for _1, _2 in zip(onstat.mean(), range(k))]))
        self.assertTrue(np.all([is_in_range(v, amin=3, amax=5) for v in onstat.variance()]))
        self.assertTrue(np.all([is_in_range(v, amin=1.7, amax=2.2) for v in onstat.sigma()]))
        self.assertEqual(onstat.count(), n) 
Example 8
Project: Tools   Author: bartlomiejduda   File: Testing.py    GNU General Public License v3.0 6 votes vote down vote up
def createData(rows=20, cols=5):
	"""Creare random dict for test data"""

	data = {}
	names = createRandomStrings(rows,16)
	colnames = createRandomStrings(cols,5)
	for n in names:
		data[n]={}
		data[n]['label'] = n
	for c in range(0,cols):
		colname=colnames[c]
		vals = [round(random.normalvariate(100,50),2) for i in range(0,len(names))]
		vals = sorted(vals)
		i=0
		for n in names:
			data[n][colname] = vals[i]
			i+=1
	return data 
Example 9
Project: CloudBot   Author: paris-ci   File: gaming.py    GNU General Public License v3.0 6 votes vote down vote up
def n_rolls(count, n):
    """roll an n-sided die count times
    :type count: int
    :type n: int | str
    """
    if n == "F":
        return [random.randint(-1, 1) for x in range(min(count, 100))]
    if n < 2:  # it's a coin
        if count < 100:
            return [random.randint(0, 1) for x in range(count)]
        else:  # fake it
            return [int(random.normalvariate(.5 * count, (.75 * count) ** .5))]
    else:
        if count < 100:
            return [random.randint(1, n) for x in range(count)]
        else:  # fake it
            return [int(random.normalvariate(.5 * (1 + n) * count,
                                             (((n + 1) * (2 * n + 1) / 6. -
                                               (.5 * (1 + n)) ** 2) * count) ** .5))] 
Example 10
Project: CloudBot   Author: paris-ci   File: gaming.py    GNU General Public License v3.0 6 votes vote down vote up
def coin(text, notice, action):
    """[amount] - flips [amount] coins
    :type text: str
    """

    if text:
        try:
            amount = int(text)
        except (ValueError, TypeError):
            notice("Invalid input '{}': not a number".format(text))
            return
    else:
        amount = 1

    if amount == 1:
        action("flips a coin and gets {}.".format(random.choice(["heads", "tails"])))
    elif amount == 0:
        action("makes a coin flipping motion")
    else:
        heads = int(random.normalvariate(.5 * amount, (.75 * amount) ** .5))
        tails = amount - heads
        action("flips {} coins and gets {} heads and {} tails.".format(amount, heads, tails)) 
Example 11
Project: rectpack   Author: secnot   File: test_stats.py    Apache License 2.0 6 votes vote down vote up
def random_rectangle(max_side, min_side, sigma=0.5, ratio=1.0, coherce=True):

    assert min_side <= max_side

    #
    half_side = (max_side-min_side)/2
    center = max_side-half_side
    width  = random.normalvariate(0, sigma)*half_side
    height = random.normalvariate(0, sigma)*half_side

    #
    if ratio > 1:
        height = height/ratio
    else:
        width = width*ratio
   
    # Coherce value to max
    if coherce:
        width  = coherce_to(max_side, min_side, width+center)
        height = coherce_to(max_side, min_side, height+center)
    
    return width, height 
Example 12
Project: ipynb   Author: OpenBookProjects   File: wordfreq.py    MIT License 6 votes vote down vote up
def tagcloud(worddict, n=10, minsize=25, maxsize=50, minalpha=0.5, maxalpha=1.0):
    from matplotlib import pyplot as plt
    import random

    worddict = wordfreq_to_weightsize(worddict, minsize, maxsize, minalpha, maxalpha)

    fig = plt.figure()
    ax = fig.add_subplot(111)
    ax.set_position([0.0,0.0,1.0,1.0])
    plt.xticks([])
    plt.yticks([])

    words = worddict.keys()
    alphas = [v[0] for v in worddict.values()]
    sizes = [v[1] for v in worddict.values()]
    items = zip(alphas, sizes, words)
    items.sort(reverse=True)
    for alpha, size, word in items[:n]:
        # xpos = random.normalvariate(0.5, 0.3)
        # ypos = random.normalvariate(0.5, 0.3)
        xpos = random.uniform(0.0,1.0)
        ypos = random.uniform(0.0,1.0)
        ax.text(xpos, ypos, word.lower(), alpha=alpha, fontsize=size)
    ax.autoscale_view()
    return ax 
Example 13
Project: pcornet   Author: Duke-Translational-Bioinformatics   File: vital_factory.py    GNU General Public License v3.0 6 votes vote down vote up
def systolic(self):
        return random.normalvariate(126.32, 18.83)
    # @factory.lazy_attribute
    # def original_bmi(self):
    #     wt_convert = self.wt*0.45
    #     ht_convert = np.square(self.ht*0.025)
    #     bmi = np.divide(wt_convert, ht_convert)
    #     return bmi
    # bp_position =
    # smoking =
    # tobacco =
    # tobacco_type =
    # raw_diastolic =
    # raw_systolic =
    # raw_bp_position =
    # raw_smoking =
    # raw_tobacco =
    # raw_tobacco_type =
    # raw_encounterid = 
Example 14
Project: straplay   Author: theonewolf   File: straplay.py    MIT License 6 votes vote down vote up
def replay_strace(events, theseed, sigma, mu, percent):
    lasttime = None
    files = {0 : 'stdout', 1 : 'stdin', 2 : 'stderr'}

    if theseed is not None: seed(theseed)

    for event in events:
        if DEBUG:
            print('Running event: %s' % (event))
            print('\tFiles: %s' % (files))

        time = event.timestamp * 10e6 + event.microseconds

        if lasttime is not None:
            sleeptime = (time - lasttime) / 10e6
            if mu is not None and sigma is not None:
                if randint(0,100) < percent:
                    sleeptime += abs(normalvariate(mu, sigma))
            if DEBUG: print('sleeping: %f' % (sleeptime))
            sleep(sleeptime)

        event.do_event(files)
        lasttime = time

        if DEBUG: print('\tFiles now: %s' % (files)) 
Example 15
Project: straplay   Author: theonewolf   File: straplay.py    MIT License 6 votes vote down vote up
def replay_strace(events, theseed, sigma, mu, percent):
    lasttime = None
    files = {0 : 'stdout', 1 : 'stdin', 2 : 'stderr'}

    if theseed is not None: seed(theseed)

    for event in events:
        if DEBUG:
            print('Running event: %s' % (event))
            print('\tFiles: %s' % (files))

        time = event.timestamp * 10e6 + event.microseconds

        if lasttime is not None:
            sleeptime = (time - lasttime) / 10e6
            if mu is not None and sigma is not None:
                if randint(0,100) < percent:
                    sleeptime += abs(normalvariate(mu, sigma))
            if DEBUG: print('sleeping: %f' % (sleeptime))
            sleep(sleeptime)

        event.do_event(files)
        lasttime = time

        if DEBUG: print('\tFiles now: %s' % (files)) 
Example 16
Project: numerai-concorde   Author: oerlikon   File: concorde.py    The Unlicense 6 votes vote down vote up
def noize(p):
    if p == 0.5:
        return 0
    if p < 0.5:
        if p < 0.25:
            q = p
        else:
            q = 0.5 - p
    else:
        if p < 0.75:
            q = p - 0.5
        else:
            q = 1 - p
    z = random.normalvariate(0, 0.005 * sqrt(q))
    asterisk = ''
    if (p > 0.5 and p + z < 0.5) or (p < 0.5 and p + z > 0.5):
        asterisk = ' *'
    if abs(z) > 0.01 or (asterisk and abs(z) > 0.0001):
        print >>sys.stderr, '# %+.7f %+.7f %+.7f %+.7f%s' % (p, q, z, abs(z / max(p-0.5, 0.5-p)), asterisk)
    return z 
Example 17
Project: IDTxl   Author: pwollstadt   File: test_estimators_jidt.py    GNU General Public License v3.0 6 votes vote down vote up
def _get_gauss_data(n=10000, covariance=0.4, expand=True):
    """Generate correlated and uncorrelated Gaussian variables.

    Generate two sets of random normal data, where one set has a given
    covariance and the second is uncorrelated.
    """
    corr_expected = covariance / (1 * np.sqrt(covariance**2 + (1-covariance)**2))
    expected_mi = calculate_mi(corr_expected)
    src_corr = [rn.normalvariate(0, 1) for r in range(n)]  # correlated src
    src_uncorr = [rn.normalvariate(0, 1) for r in range(n)]  # uncorrelated src
    target = [sum(pair) for pair in zip(
                    [covariance * y for y in src_corr[0:n]],
                    [(1-covariance) * y for y in [
                        rn.normalvariate(0, 1) for r in range(n)]])]
    # Make everything numpy arrays so jpype understands it. Add an additional
    # axis if requested (MI/CMI estimators accept 2D arrays, TE/AIS only 1D).
    if expand:
        src_corr = np.expand_dims(np.array(src_corr), axis=1)
        src_uncorr = np.expand_dims(np.array(src_uncorr), axis=1)
        target = np.expand_dims(np.array(target), axis=1)
    else:
        src_corr = np.array(src_corr)
        src_uncorr = np.array(src_uncorr)
        target = np.array(target)
    return expected_mi, src_corr, src_uncorr, target 
Example 18
Project: IDTxl   Author: pwollstadt   File: test_active_information_storage.py    GNU General Public License v3.0 6 votes vote down vote up
def test_single_source_storage_gaussian():
    n = 1000
    proc_1 = [rn.normalvariate(0, 1) for r in range(n)]  # correlated src
    proc_2 = [rn.normalvariate(0, 1) for r in range(n)]  # correlated src
    # Cast everything to numpy so the idtxl estimator understands it.
    data = Data(np.array([proc_1, proc_2]), dim_order='ps')
    settings = {
        'cmi_estimator': 'JidtKraskovCMI',
        'alpha_mi': 0.05,
        'tail_mi': 'one_bigger',
        'n_perm_max_stat': 21,
        'n_perm_min_stat': 21,
        'n_perm_mi': 21,
        'max_lag': 5,
        'tau': 1
        }
    processes = [1]
    network_analysis = ActiveInformationStorage()
    results = network_analysis.analyse_network(settings, data, processes)
    print('AIS for random normal data without memory (expected is NaN): '
          '{0}'.format(results._single_process[1].ais))
    assert results._single_process[1].ais is np.nan, (
        'Estimator did not return nan for memoryless data.') 
Example 19
Project: Pinterest_scraper   Author: eamander   File: pinterest_scraper.py    MIT License 6 votes vote down vote up
def login(self):
        try:
            login_elem = self.driver.find_element_by_class_name('lightGrey')
            login_elem.send_keys(Keys.ENTER)
            sleep(abs(normalvariate(3, 0.2)))
            email_elem = self.driver.find_element_by_name('id')
            email_elem.send_keys(self.login_name)
            sleep(abs(normalvariate(3, 0.2)))
            pw_elem = self.driver.find_element_by_name('password')
            pw_elem.send_keys(self.login_pass)
            sleep(abs(normalvariate(3, 0.2)))
            login_elem = self.driver.find_element_by_class_name('SignupButton')
            login_elem.send_keys(Keys.RETURN)
        except NoSuchElementException:
            sleep(abs(normalvariate(3, 0.2)))
            email_elem = self.driver.find_element_by_name('id')
            email_elem.send_keys(self.login_name)
            sleep(abs(normalvariate(3, 0.2)))
            pw_elem = self.driver.find_element_by_name('password')
            pw_elem.send_keys(self.login_pass)
            sleep(abs(normalvariate(3, 0.2)))
            login_elem = self.driver.find_element_by_class_name('SignupButton')
            login_elem.send_keys(Keys.ENTER) 
Example 20
Project: BayesRate   Author: schnitzler-j   File: prior.py    MIT License 5 votes vote down vote up
def wiener_process(m, s, lowest, greatest):  # NORMAL VARIATION
	k= random.normalvariate(m, s)
	if k<lowest: k= random.uniform(lowest, m)
	if k>greatest: k= random.uniform(m, greatest)
	return k 
Example 21
Project: BayesRate   Author: schnitzler-j   File: prior.py    MIT License 5 votes vote down vote up
def update_parameter(i, std, m, M, freq): 
	if random.random()<=freq:
		i=fabs(random.normalvariate(i,std))
		if i>m: i=fabs(i-m)+m
		if i>M: i=fabs(M-(i-M))
	return i 
Example 22
Project: timerit   Author: Erotemic   File: test_timerit.py    Apache License 2.0 5 votes vote down vote up
def __call__(self):
        self.time += abs(self.inc + random.normalvariate(0, self.noise))
        return self.time 
Example 23
Project: deepbond   Author: mtreviso   File: iterator.py    MIT License 5 votes vote down vote up
def set_random_bptt_len(self):
        self.cur_bptt_len = self.bptt_len
        if random.random() > 0.95:
            self.cur_bptt_len = self.bptt_len // 2
        self.cur_bptt_len = int(random.normalvariate(self.cur_bptt_len, 5))
        self.cur_bptt_len = max(10, self.cur_bptt_len) 
Example 24
Project: Jtyoui   Author: jtyoui   File: fm.py    MIT License 5 votes vote down vote up
def initialize_v(n: int, k: int):
    """初始化交叉项

    :param n: 特征个数
    :param k: FM模型的度
    :return: 交叉项的系数权重
    """
    v = np.mat(np.zeros(shape=(n, k)))
    for i in range(n):
        for j in range(k):
            v[i, j] = normalvariate(0, 0.2)
    return v 
Example 25
Project: yosbot   Author: craisins   File: dice.py    The Unlicense 5 votes vote down vote up
def nrolls(count, n):
    "roll an n-sided die count times"
    if n == "F":
        return [random.randint(-1, 1) for x in xrange(min(count, 100))]
    if n < 2:  # it's a coin
        if count < 5000:
            return [random.randint(0, 1) for x in xrange(count)]
        else:  # fake it
            return [int(random.normalvariate(.5 * count, (.75 * count) ** .5))]
    else:
        if count < 5000:
            return [random.randint(1, n) for x in xrange(count)]
        else:  # fake it
            return [int(random.normalvariate(.5 * (1 + n) * count,
                                             (((n + 1) * (2 * n + 1) / 6. - (.5 * (1 + n)) ** 2) * count) ** .5))] 
Example 26
Project: keypoint-network   Author: ihankyang   File: render.py    Apache License 2.0 5 votes vote down vote up
def random_top_sphere():
  xyz = [random.normalvariate(0, 1) for x in range(3)]
  normalize(xyz)

  if xyz[2] < 0:
    xyz[2] *= -1
  return xyz 
Example 27
Project: keypoint-network   Author: ihankyang   File: render.py    Apache License 2.0 5 votes vote down vote up
def perturb_sphere(loc, size):
  while True:
    xyz = [random.normalvariate(0, 1) for x in range(3)]
    normalize(xyz)

    nloc = [loc[i] + xyz[i] * random.random() * size for i in range(3)]
    normalize(nloc)

    if nloc[2] >= 0:
      return nloc 
Example 28
Project: KittiSeg   Author: MarvinTeichmann   File: kitti_seg_input.py    MIT License 5 votes vote down vote up
def random_resize(image, gt_image, lower_size, upper_size, sig):
    factor = random.normalvariate(1, sig)
    if factor < lower_size:
        factor = lower_size
    if factor > upper_size:
        factor = upper_size
    image = scipy.misc.imresize(image, factor)
    shape = gt_image.shape
    gt_zero = np.zeros([shape[0], shape[1], 1])
    gt_image = np.concatenate((gt_image, gt_zero), axis=2)
    gt_image = scipy.misc.imresize(gt_image, factor, interp='nearest')
    gt_image = gt_image[:, :, 0:2]/255
    return image, gt_image 
Example 29
Project: easy_gene   Author: thomsn   File: easy_gene.py    The Unlicense 5 votes vote down vote up
def evolve(population, scores, num_parents=2, mutation_rates=None):
    """
    Evolve a population based on provided scores
    :param population: a list of dictionaries. Each entry in the dict represents a parameter
    :param scores: a list of positive scores. Scale doesnt matter.
    :param num_parents: The number of parents to use when breeding the next population
    :param mutation_rate: The percent of change to apply to each individual in the population
    :return: the new population which is a list of dictionaries
    """
    start_num = len(population)
    params = list(population[0].keys())
    # selection
    selection_scores = [score * random.random() for score in scores]
    sorted_pop = sorted(zip(selection_scores, population), key=lambda scored_gene: scored_gene[0])
    population = [scored_parent[1] for scored_parent in sorted_pop[-num_parents:]]
    #crossover
    for _ in range(start_num - num_parents):
        child = {}
        for param in params:
            child[param] = population[random.randint(0,num_parents-1)][param]
        population.append(child)
    #mutation
    if mutation_rates:
        for gene in population:
            for param in params:
                if isinstance(gene[param], float):
                    gene[param] = gene[param]  + random.normalvariate(0, mutation_rates[param])
                elif isinstance(gene[param], bool):
                    if random.random() < mutation_rates[param]:
                        gene[param] = not gene[param]
                else:
                    raise RuntimeError('Can only mutate floats and booleans')

    return population 
Example 30
Project: pycolab   Author: deepmind   File: cued_catch.py    Apache License 2.0 5 votes vote down vote up
def update(self, actions, board, layers, backdrop, things, the_plot):
    # Our motions are quite constrained: we can only move up or down one spot.
    if actions == 1 and self.virtual_position.row > 1:    # go up?
      self._north(board, the_plot)
    elif actions == 2 and self.virtual_position.row < 2:  # go down?
      self._south(board, the_plot)
    elif actions in [0, 4]:                               # quit the game?
      the_plot.terminate_episode()
    else:                                                 # do nothing?
      self._stay(board, the_plot)                         # (or can't move?)

    # Give ourselves a point if we landed on the correct ball.
    correct_ball = 'a' if the_plot.get('which_ball') == 'top' else 'b'
    if self._reward_sigma:
      if (self.position.col == things[correct_ball].position.col and
          self._trials_till_reward <= 0):
        the_plot.add_reward(
            float(self.position == things[correct_ball].position) +
            random.normalvariate(mu=0, sigma=self._reward_sigma))
      else:
        the_plot.add_reward(0)

    else:
      the_plot.add_reward(int(
          self.position == things[correct_ball].position and
          self._trials_till_reward <= 0
      ))

    # Decrement trials left till reward.
    if (self.position.col == things[correct_ball].position.col and
        self._trials_till_reward > 0):
      self._trials_till_reward -= 1 
Example 31
Project: MuscleSpindleCircuitsModel   Author: FormentoEmanuele   File: AfferentFiber.py    MIT License 5 votes vote down vote up
def __init__(self,delay):
		""" Object initialization.

		Keyword arguments:
		delay -- time delay in ms needed by a spike to travel the whole fiber
		"""

		Cell.__init__(self)
		self._debug = False

		#Initialise cell parameters
		self._set_delay(delay)

		self.maxFiringRate = 200 # This should be lower than the frequency allowed by the refractory period
		self._maxSensorySpikesXtime = int(float(self._delay)/1000.*float(self.maxFiringRate)+2)
		self._maxEesSpikesXtime = int(float(self._delay)/1000.*float(self.__class__.__maxEesFrequency)+2)
		#Mean refractory period of 1.6 ms - 625 Hz
		noisePerc = 0.1
		self._refractoryPeriod = rnd.normalvariate(1.6,1.6*noisePerc)
		if self._refractoryPeriod>1000./self.maxFiringRate:
			self._refractoryPeriod=1000./self.maxFiringRate
			print "Warning: refractory period bigger than period between 2 natural pulses"
		#Position along the fiber recruited by the stimulation
		self._stimPosition = self._delay-0.5

		self.initialise()
		#Create an ARTIFICIAL_CELL Neuron mechanism that will be the source of a netCon object.
		#This will be used to comunicate the APs to target cells
		self.cell = h.AfferentFiber()

		#Create a netcon to make the fiber fire
		self._fire = h.NetCon(None,self.cell)

		# Boolean flag to record a segment of the fiber over time
		self._record = False 
Example 32
Project: MuscleSpindleCircuitsModel   Author: FormentoEmanuele   File: IntFireMn.py    MIT License 5 votes vote down vote up
def __init__(self):
		""" Object initialization. """
		Cell.__init__(self)

		noisePerc = 0.05

		#Create IntFire4
		self.cell = h.IntFireMn()
		self.cell.taue= 0.25
		self.cell.taui1=2
		self.cell.taui2=4.5
		self.cell.taum= rnd.normalvariate(6,6*noisePerc)
		if self.cell.taum <= self.cell.taui2: self.cell.taum = self.cell.taui2 + 0.25
		self.cell.refrac=rnd.normalvariate(20,20*noisePerc) # mean 50Hz 
Example 33
Project: PythonTrainingExercises   Author: man-group   File: DictHistogram.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    LEN = 1000000
    bucket_size = 1
    # This will give us a normal distribution centred around 0.0 with a standard
    # deviation of 1.0
    mu, sigma = 0.0, 1.0
    lst = [random.normalvariate(mu, sigma) for _ in range(LEN)]
    d = float_list_to_int_dict(lst, bucket_size)
    pprint.pprint(d)
    pprint_histogram(d, bucket_size) 
Example 34
Project: PythonTrainingExercises   Author: man-group   File: DictHistogram.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    LEN = 1000000
    bucket_size = 1
    # This will give us a normal distribution centred around 0.0 with a standard
    # deviation of 1.0
    mu, sigma = 0.0, 1.0
    lst = [random.normalvariate(mu, sigma) for _ in range(LEN)]
    d = float_list_to_int_dict(lst, bucket_size)
    pprint.pprint(d)
    pprint_histogram(d, bucket_size) 
Example 35
Project: CoDeepNEAT   Author: sash-a   File: module_node.py    MIT License 5 votes vote down vote up
def get_new_depthwise_conv_parameter_mutagens():
    conv_params = get_new_conv_parameter_mutagens()
    conv_params["kernels_per_layer"] = IntegerVariable("kernels_per_layer",
                                                       current_value=int(random.normalvariate(mu=15, sigma=2)),
                                                       start_range=1, end_range=50, mutation_chance=0.15)
    conv_params["conv_window_size"] = Option("conv_window_size", 3, 5, 7, current_value=random.choice([3, 5, 7]),
                                             mutation_chance=0.13)
    return conv_params 
Example 36
Project: CoDeepNEAT   Author: sash-a   File: continuous_variable.py    MIT License 5 votes vote down vote up
def mutate(self) -> MutationReport:
        mutation_report = MutationReport()

        if random.random() > self.mutation_chance:
            return mutation_report

        range = self.end_range - self.start_range

        if random.random() < 0.25:
            # random reset
            new_current_value = random.uniform(self.start_range, self.end_range)
            mutation_report += self.name + " changed from " + repr(self.current_value) + " to " + repr(
                new_current_value)

            self.current_value = new_current_value

        else:
            # random deviation
            deviation = random.normalvariate(0,range/8)
            new_current_value = self.current_value + deviation
            new_current_value = self.start_range + ((new_current_value - self.start_range) % range)

            mutation_report += self.name + " deviated from " + repr(self.current_value) + " to " + repr(
                new_current_value)
            self.current_value = new_current_value

        if mutation_report is None:
            raise Exception("none mutation report in " + self.name)

        # print("returning from cont var mutagen: ", mutation_report)

        return mutation_report 
Example 37
Project: open-recipe   Author: dspray95   File: protocol.py    The Unlicense 5 votes vote down vote up
def retry(self, connector=None):
        """
        Have this connector connect again, after a suitable delay.
        """
        if not self.continueTrying:
            if self.noisy:
                log.msg("Abandoning %s on explicit request" % (connector,))
            return

        if connector is None:
            if self.connector is None:
                raise ValueError("no connector to retry")
            else:
                connector = self.connector

        self.retries += 1
        if self.maxRetries is not None and (self.retries > self.maxRetries):
            if self.noisy:
                log.msg("Abandoning %s after %d retries." %
                        (connector, self.retries))
            return

        self.delay = min(self.delay * self.factor, self.maxDelay)
        if self.jitter:
            self.delay = random.normalvariate(self.delay,
                                              self.delay * self.jitter)

        if self.noisy:
            log.msg("%s will retry in %d seconds" % (connector, self.delay,))

        def reconnector():
            self._callID = None
            connector.connect()
        if self.clock is None:
            from twisted.internet import reactor
            self.clock = reactor
        self._callID = self.clock.callLater(self.delay, reconnector) 
Example 38
Project: bptc_wallet   Author: ceddie   File: network.py    MIT License 5 votes vote down vote up
def run(self):
        while not self.stopped():
            self.network.push_to_random()
            time.sleep(max(random.normalvariate(bptc.push_waiting_time_mu, bptc.push_waiting_time_sigma), 0)) 
Example 39
Project: Blockly-rduino-communication   Author: technologiescollege   File: component.py    GNU General Public License v3.0 5 votes vote down vote up
def next_delay(self):
        if self.connect_attempts == 0:
            # if we never tried before, try immediately
            return 0
        elif self.max_retries != -1 and self.connect_attempts >= self.max_retries + 1:
            raise RuntimeError('max reconnects reached')
        else:
            self.retry_delay = self.retry_delay * self.retry_delay_growth
            self.retry_delay = random.normalvariate(self.retry_delay, self.retry_delay * self.retry_delay_jitter)
            if self.retry_delay > self.max_retry_delay:
                self.retry_delay = self.max_retry_delay
            return self.retry_delay 
Example 40
Project: HyperStream   Author: IRC-SPHERE   File: 2017-06-20_v1.0.0.py    MIT License 5 votes vote down vote up
def _execute(self, sources, alignment_stream, interval):
        if alignment_stream is None:
            raise ToolExecutionError("Alignment stream expected")

        for ti, _ in alignment_stream.window(interval, force_calculation=True):
            yield StreamInstance(ti, random.normalvariate(mu=self.mu, sigma=self.sigma)) 
Example 41
Project: raidex   Author: raiden-network   File: bots.py    MIT License 5 votes vote down vote up
def set_new_goal(self):
        price = self.raidex_node.market_price() or self.initial_price
        delta = price * abs(random.normalvariate(self.goal_delta_average, self.goal_delta_sigma))
        sign = random.choice([+1, -1])
        self.goal = (price, sign * delta)
        self.log.info('new goal set', price_delta=self.goal[1], current_price=price) 
Example 42
Project: Python-TinyEvolver   Author: olliemath   File: _core.py    GNU General Public License v2.0 5 votes vote down vote up
def int_mutator(gene, bounds):
    naive = int(gene + random.normalvariate(0, 1))
    return max(min(naive, bounds[1]), bounds[0]) 
Example 43
Project: deep_lung_segmentation   Author: pedrocwb   File: kitti_seg_input.py    MIT License 5 votes vote down vote up
def random_resize(image, gt_image, lower_size, upper_size, sig):
    factor = random.normalvariate(1, sig)
    if factor < lower_size:
        factor = lower_size
    if factor > upper_size:
        factor = upper_size
    image = scipy.misc.imresize(image, factor)
    shape = gt_image.shape
    gt_zero = np.zeros([shape[0], shape[1], 1])
    gt_image = np.concatenate((gt_image, gt_zero), axis=2)
    gt_image = scipy.misc.imresize(gt_image, factor, interp='nearest')
    gt_image = gt_image[:, :, 0:2]/255
    return image, gt_image 
Example 44
Project: Safejumper-for-Desktop   Author: proxysh   File: protocol.py    GNU General Public License v2.0 5 votes vote down vote up
def retry(self, connector=None):
        """
        Have this connector connect again, after a suitable delay.
        """
        if not self.continueTrying:
            if self.noisy:
                log.msg("Abandoning %s on explicit request" % (connector,))
            return

        if connector is None:
            if self.connector is None:
                raise ValueError("no connector to retry")
            else:
                connector = self.connector

        self.retries += 1
        if self.maxRetries is not None and (self.retries > self.maxRetries):
            if self.noisy:
                log.msg("Abandoning %s after %d retries." %
                        (connector, self.retries))
            return

        self.delay = min(self.delay * self.factor, self.maxDelay)
        if self.jitter:
            self.delay = random.normalvariate(self.delay,
                                              self.delay * self.jitter)

        if self.noisy:
            log.msg("%s will retry in %d seconds" % (connector, self.delay,))

        def reconnector():
            self._callID = None
            connector.connect()
        if self.clock is None:
            from twisted.internet import reactor
            self.clock = reactor
        self._callID = self.clock.callLater(self.delay, reconnector) 
Example 45
Project: graph_slam   Author: Bazs   File: path_generator.py    MIT License 5 votes vote down vote up
def add_noise_to_control(control, velocity_control_deviation, turn_rate_control_deviation):
    noisy_control = np.zeros(control.shape)
    noisy_control[0] = control[0] + rnd.normalvariate(0, velocity_control_deviation)
    noisy_control[1] = control[1] + rnd.normalvariate(0, turn_rate_control_deviation)
    return noisy_control 
Example 46
Project: graph_slam   Author: Bazs   File: measurement_model.py    MIT License 5 votes vote down vote up
def add_noise_to_measurements_for_state(measurements_for_state, distance_deviation, heading_deviation):
    for measurement in measurements_for_state:
        measurement[0] = measurement[0] + rnd.normalvariate(0, distance_deviation)
        measurement[1] = measurement[1] + rnd.normalvariate(0, heading_deviation)
        measurement[1] = normalize_angle_pi_minus_pi(measurement[1])

    return measurements_for_state 
Example 47
Project: VOCSeg   Author: lxh-123   File: voc_seg_input.py    MIT License 5 votes vote down vote up
def random_resize(image, gt_image, lower_size, upper_size, sig):
    factor = random.normalvariate(1, sig)
    if factor < lower_size:
        factor = lower_size
    if factor > upper_size:
        factor = upper_size
    image = scipy.misc.imresize(image, factor)
    gt_image = scipy.misc.imresize(gt_image, factor, interp='nearest')

    return image, gt_image 
Example 48
Project: RLSchool   Author: PaddlePaddle   File: custom_generator.py    Apache License 2.0 5 votes vote down vote up
def _weight_generator(self):
        MIN_WEIGHT = 20
        MAX_WEIGHT = 100
        weight = random.normalvariate(50, 10)
        while weight < MIN_WEIGHT or weight > MAX_WEIGHT:
            weight = random.normalvariate(50, 10)
        return weight 
Example 49
Project: pcornet   Author: Duke-Translational-Bioinformatics   File: lab_result_cm_factory.py    GNU General Public License v3.0 5 votes vote down vote up
def result_num(self):
        return random.normalvariate(75.32, 11.31)
    # result_modifier
    # result_unit
    # norm_range_low
    # norm_modifier_low
    # norm_range_high
    # norm_modifier_high
    # abn_ind
    # raw_lab_name
    # raw_lab_code
    # raw_panel
    # raw_result 
Example 50
Project: pcornet   Author: Duke-Translational-Bioinformatics   File: vital_factory.py    GNU General Public License v3.0 5 votes vote down vote up
def ht(self):
        if fake.random.uniform(0, 1) > 0.5:
            return random.normalvariate(66.14, 4.3) 
Example 51
Project: pcornet   Author: Duke-Translational-Bioinformatics   File: vital_factory.py    GNU General Public License v3.0 5 votes vote down vote up
def wt(self):
        if fake.random.uniform(0,1)>0.5:
            return random.normalvariate(186.23, 53.10) 
Example 52
Project: pcornet   Author: Duke-Translational-Bioinformatics   File: vital_factory.py    GNU General Public License v3.0 5 votes vote down vote up
def diastolic(self):
        return random.normalvariate(75.32, 11.31) 
Example 53
Project: txnats   Author: johnwlockwood   File: backoff.py    MIT License 5 votes vote down vote up
def get_delay(self):
        if self.retries == 0:
            self.retries += 1
            return self.delay
        
        self.retries += 1
        self.delay = min(self.delay * self.factor, self.max_delay)
        if self.jitter:
            self.delay = random.normalvariate(self.delay,
                                              self.delay * self.jitter)
        return self.delay 
Example 54
Project: ez-segway   Author: thanh-nguyen-dang   File: switch.py    Apache License 2.0 5 votes vote down vote up
def send_to_ctrl(self, msg):
        debug = self.log.debug

        delay = global_vars.sw_to_ctrl_delays[self.id] + \
            random.normalvariate(constants.NW_LATENCY_MU,
                                 constants.NW_LATENCY_SIGMA)
        debug("sending msg %s to %s @:%f, delay time: %f" % (msg, self.ctrl, Simulation.now(), delay))
        deliver = DeliverMessageWithDelay()
        Simulation.activate(deliver,
                            deliver.run(msg, delay, self.ctrl),
                            at=Simulation.now()) 
Example 55
Project: ez-segway   Author: thanh-nguyen-dang   File: switch.py    Apache License 2.0 5 votes vote down vote up
def send_to_switch(self, msg, dst_id):
        debug = self.log.debug
        dst_sw = utils.get_item_with_lambda(global_vars.switches, lambda item: dst_id - item.id)
        delay = global_vars.sw_to_sw_delays[(self.id, dst_sw.id)] + \
                random.normalvariate(constants.NW_LATENCY_MU,
                                     constants.NW_LATENCY_SIGMA)
        debug("sending msg %s to %s @:%f, delay: %f" % (msg, dst_sw, Simulation.now(), delay))
        deliver = DeliverMessageWithDelay()
        Simulation.activate(deliver,
                            deliver.run(msg, delay, dst_sw),
                            at=Simulation.now()) 
Example 56
Project: ez-segway   Author: thanh-nguyen-dang   File: controller.py    Apache License 2.0 5 votes vote down vote up
def send(self, msg, dst):
        debug = self.log.debug

        delay = global_vars.sw_to_ctrl_delays[dst.id] + \
            random.normalvariate(constants.NW_LATENCY_MU,
                                 constants.NW_LATENCY_SIGMA)
        debug("sending msg %s from controller to %s @:%f, delay time: %f" % (msg, dst, Simulation.now(), delay))
        deliver = DeliverMessageWithDelay()
        Simulation.activate(deliver,
                            deliver.run(msg, delay, dst),
                            at=Simulation.now()) 
Example 57
Project: tf-adnet-tracking   Author: ildoonet   File: boundingbox.py    GNU General Public License v3.0 5 votes vote down vote up
def gen_noise_samples(self, imgwh, noise_type, num, **kwargs):
        center_xy = self.xy + self.wh * 0.5
        mean_wh = sum(self.wh) / 2.0

        gaussian_translation_f = kwargs.get('gaussian_translation_f', 0.1)
        uniform_translation_f = kwargs.get('uniform_translation_f', 1)
        uniform_scale_f = kwargs.get('uniform_scale_f', 10)

        samples = []
        if noise_type == 'whole':
            grid_x = range(self.wh.x // 2, imgwh.x - self.wh.x // 2, self.wh.x // 5)
            grid_y = range(self.wh.y // 2, imgwh.y - self.wh.y // 2, self.wh.y // 5)
            samples_tmp = []
            for dx, dy, ds in itertools.product(grid_x, grid_y, range(-5, 5, 1)):
                box = BoundingBox(dx, dy, self.wh.x*(1.05**ds), self.wh.y*(1.05**ds))
                box.fit_image(imgwh)
                samples_tmp.append(box)

            for _ in range(num):
                samples.append(random.choice(samples_tmp))
        else:
            for _ in range(num):
                if noise_type == 'gaussian':
                    dx = gaussian_translation_f * mean_wh * minmax(0.5 * random.normalvariate(0, 1), -1, 1)
                    dy = gaussian_translation_f * mean_wh * minmax(0.5 * random.normalvariate(0, 1), -1, 1)
                    dwh = 1.05 ** (3 * minmax(0.5 * random.normalvariate(0, 1), -1, 1))
                elif noise_type == 'uniform':
                    dx = uniform_translation_f * mean_wh * random.uniform(-1.0, 1.0)
                    dy = uniform_translation_f * mean_wh * random.uniform(-1.0, 1.0)
                    dwh = 1.05 ** (uniform_scale_f * random.uniform(-1.0, 1.0))
                else:
                    raise
                new_cxy = center_xy + (dx, dy)
                new_wh = self.wh * dwh
                box = BoundingBox(new_cxy.x - new_wh.x / 2.0, new_cxy.y - new_wh.y / 2.0, new_wh.x, new_wh.y)
                box.fit_image(imgwh)
                samples.append(box)

        return samples 
Example 58
Project: tcnc   Author: utlco   File: lines.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def spacing_jitter_scale(self):
        """
        """
        mu = 0
        sigma = 0.4
        jitter = random.normalvariate(mu, sigma)
        return jitter * self.spacing_jitter 
Example 59
Project: dirichletprocess   Author: tdhopper   File: test_dirichlet.py    MIT License 5 votes vote down vote up
def test_basic():
    dp = DirichletProcess(lambda: normalvariate(0, 1), alpha=0.1)
    for _ in range(1000):
        dp() 
Example 60
Project: dirichletprocess   Author: tdhopper   File: test_dirichlet.py    MIT License 5 votes vote down vote up
def test_bad_alpha():
    with pytest.raises(ValueError):
        DirichletProcess(lambda: normalvariate(0, 1), alpha=-1) 
Example 61
Project: deep_image_model   Author: tobegit3hub   File: generate_testdata.py    Apache License 2.0 5 votes vote down vote up
def WriteHistogramSeries(writer, tag, mu_sigma_tuples, n=20):
  """Write a sequence of normally distributed histograms to writer."""
  step = 0
  wall_time = _start_time
  for [mean, stddev] in mu_sigma_tuples:
    data = [random.normalvariate(mean, stddev) for _ in xrange(n)]
    histo = _MakeHistogram(data)
    summary = tf.Summary(value=[tf.Summary.Value(tag=tag, histo=histo)])
    event = tf.Event(wall_time=wall_time, step=step, summary=summary)
    writer.add_event(event)
    step += 10
    wall_time += 100 
Example 62
Project: Python-iBeacon-Scan   Author: NikNitro   File: crv_types.py    GNU General Public License v3.0 5 votes vote down vote up
def sample(self):
        return random.normalvariate(self.mean, self.std) 
Example 63
Project: weibo_twitter_earnings_analysis   Author: lynings   File: protocol.py    Apache License 2.0 5 votes vote down vote up
def retry(self, connector=None):
        """
        Have this connector connect again, after a suitable delay.
        """
        if not self.continueTrying:
            if self.noisy:
                log.msg("Abandoning %s on explicit request" % (connector,))
            return

        if connector is None:
            if self.connector is None:
                raise ValueError("no connector to retry")
            else:
                connector = self.connector

        self.retries += 1
        if self.maxRetries is not None and (self.retries > self.maxRetries):
            if self.noisy:
                log.msg("Abandoning %s after %d retries." %
                        (connector, self.retries))
            return

        self.delay = min(self.delay * self.factor, self.maxDelay)
        if self.jitter:
            self.delay = random.normalvariate(self.delay,
                                              self.delay * self.jitter)

        if self.noisy:
            log.msg("%s will retry in %d seconds" % (connector, self.delay,))

        def reconnector():
            self._callID = None
            connector.connect()
        if self.clock is None:
            from twisted.internet import reactor
            self.clock = reactor
        self._callID = self.clock.callLater(self.delay, reconnector) 
Example 64
Project: IDTxl   Author: pwollstadt   File: test_estimators_jidt.py    GNU General Public License v3.0 5 votes vote down vote up
def test_lagged_mi():
    """Test estimation of lagged MI."""
    n = 10000
    cov = 0.4
    source = [rn.normalvariate(0, 1) for r in range(n)]
    target = [0] + [sum(pair) for pair in zip(
                        [cov * y for y in source[0:n - 1]],
                        [(1 - cov) * y for y in
                            [rn.normalvariate(0, 1) for r in range(n - 1)]])]
    source = np.array(source)
    target = np.array(target)
    settings = {
        'discretise_method': 'equal',
        'n_discrete_bins': 4,
        'history': 1,
        'history_target': 1,
        'lag_mi': 1,
        'source_target_delay': 1}

    est_te_k = JidtKraskovTE(settings)
    te_k = est_te_k.estimate(source, target)
    est_te_d = JidtDiscreteTE(settings)
    te_d = est_te_d.estimate(source, target)
    est_d = JidtDiscreteMI(settings)
    mi_d = est_d.estimate(source, target)
    est_k = JidtKraskovMI(settings)
    mi_k = est_k.estimate(source, target)
    est_g = JidtGaussianMI(settings)
    mi_g = est_g.estimate(source, target)
    _compare_result(mi_d, te_d, 'JidtDiscreteMI', 'JidtDiscreteTE',
                    'lagged MI', tol=0.05)
    _compare_result(mi_k, te_k, 'JidtKraskovMI', 'JidtKraskovTE',
                    'lagged MI', tol=0.05)
    _compare_result(mi_g, te_k, 'JidtGaussianMI', 'JidtKraskovTE',
                    'lagged MI', tol=0.05) 
Example 65
Project: IDTxl   Author: pwollstadt   File: test_estimators_jidt.py    GNU General Public License v3.0 5 votes vote down vote up
def test_jidt_kraskov_alg1And2():
    """ Test that JIDT estimate changes properly when we change KSG algorithm """
    n = 100;
    source = [sum(pair) for pair in zip(
                        [y for y in range(n)],
                        [rn.normalvariate(0, 0.000001) for r in range(n)])]
    source = np.array(source)
    target = np.array(source) # Target copies source on purpose
    # We've generated simple data 0:99, plus a little noise to ensure
    #  we only even get K nearest neighbours in each space.
    # So result should be:
    settings = {
        'lag': 0,
        'kraskov_k': 4,
        'noise_level': 0,
        'algorithm_num': 1}
    for k in range(4,16):
        settings['kraskov_k'] = k;
        settings['algorithm_num'] = 1;
        est1 = JidtKraskovMI(settings)
        mi_alg1 = est1.estimate(source, target)
        # Neighbour counts n_x and n_y will be k-1 because they are
        #  *strictly* within the boundary
        expected_alg1 = digamma(k) - 2*digamma((k-1)+1) + digamma(n);
        _compare_result(mi_alg1, expected_alg1, 'JidtDiscreteMI_alg1', 'Analytic',
                    'MI', tol=0.00001)
        settings['algorithm_num'] = 2;
        est2 = JidtKraskovMI(settings)
        mi_alg2 = est2.estimate(source, target)
        expected_alg2 = digamma(k) - 1/k - 2*digamma(k) + digamma(n);
        _compare_result(mi_alg2, expected_alg2, 'JidtDiscreteMI_alg2', 'Analytic',
                    'MI', tol=0.00001)
        # And now check that it doesn't work for algorithm "3"
        settings['algorithm_num'] = 3;
        caughtAssertionError = False;
        try:
            est3 = JidtKraskovMI(settings);
        except AssertionError:
            caughtAssertionError = True;
        assert caughtAssertionError, 'Assertion error not raised for KSG algorithm 3 request' 
Example 66
Project: Pinterest_scraper   Author: eamander   File: pinterest_scraper.py    MIT License 5 votes vote down vote up
def scrape_pictures(self, query, n_pgdn=500):

        if ' ' in query:
            query.replace(' ', '  ')  # Pinterest likes to bring up a history
                                      # instead of letting you type your first space
        search_input = self.driver.find_element_by_class_name('searchInput')
        search_input.send_keys(query)

        # We have to reacquire the element after the page changes at all
        search_input = self.driver.find_element_by_class_name('searchInput')
        search_input.send_keys(Keys.RETURN)

        sleep(3)  # this is just a hack to get the page to load properly
        # cur_pgdn = 0
        for i in range(n_pgdn):
            pics_list = self.driver.find_elements_by_class_name('_mi')
            pics_list = pics_list[1:]
            pic_url_list = [pic_elem.get_attribute('srcset').split(' ')[-2] for pic_elem in pics_list]
            for pic_url in pic_url_list:
                pic_name = pic_url.split('/')[-1]
                if pic_name not in self.scraped_list:
                    pic = requests.get(pic_url)
                    file = open(os.path.join(self.path, pic_name), 'wb')
                    file.write(pic.content)
                    file.close()
                    self.scraped_list.append(pic_name)
                    sleep(abs(normalvariate(abs(normalvariate(1.2, 0.2)), abs(normalvariate(0.4, 0.1)))))
                # This way we save an image about every 1.2 seconds. That's plenty of images in not much time.
                # I chose to do this variable sleep time just because I saw someone else doing the same thing.
                # I do not know if Pinterest is looking for automated activity, so it might be unnecessary.
            body = self.driver.find_element_by_css_selector('body')
            for j in range(2):
                body.send_keys(Keys.PAGE_DOWN)
            sleep(2)  # this give the page time to actually SCROLL!
            # cur_pgdn += 1 
Example 67
Project: SUMO_dy_public   Author: DayuanTan   File: createVehTypeDistribution.py    GNU General Public License v3.0 5 votes vote down vote up
def _sampleValue(self):
        return random.normalvariate(self._params[0], self._params[1]) 
Example 68
Project: learn_python3_spider   Author: wistbean   File: protocol.py    MIT License 5 votes vote down vote up
def retry(self, connector=None):
        """
        Have this connector connect again, after a suitable delay.
        """
        if not self.continueTrying:
            if self.noisy:
                log.msg("Abandoning %s on explicit request" % (connector,))
            return

        if connector is None:
            if self.connector is None:
                raise ValueError("no connector to retry")
            else:
                connector = self.connector

        self.retries += 1
        if self.maxRetries is not None and (self.retries > self.maxRetries):
            if self.noisy:
                log.msg("Abandoning %s after %d retries." %
                        (connector, self.retries))
            return

        self.delay = min(self.delay * self.factor, self.maxDelay)
        if self.jitter:
            self.delay = random.normalvariate(self.delay,
                                              self.delay * self.jitter)

        if self.noisy:
            log.msg("%s will retry in %d seconds" % (connector, self.delay,))

        def reconnector():
            self._callID = None
            connector.connect()
        if self.clock is None:
            from twisted.internet import reactor
            self.clock = reactor
        self._callID = self.clock.callLater(self.delay, reconnector) 
Example 69
Project: PyMineHub   Author: nosix   File: multiplay.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _move_position(position: Vector3[float]) -> Vector3[float]:
    return position + tuple(random.normalvariate(0, 1) for _ in range(3)) 
Example 70
Project: PyMineHub   Author: nosix   File: multiplay.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def run_multiplay(max_workers: int, session_num: int, ave_lifespan: float, acts: Tuple[Act, ...]):
    def start_task(i: int):
        lifespan = random.normalvariate(ave_lifespan, 10)
        return pool.apply_async(run_client, ('Player-{}'.format(i), lifespan, acts))

    with multiprocessing.Pool(max_workers) as pool:
        tasks = tuple(start_task(i) for i in range(session_num))
        try:
            for task in tasks:
                task.wait()
        except KeyboardInterrupt:
            pass 
Example 71
Project: PlaqueRL   Author: luogongning   File: boundingbox.py    GNU General Public License v3.0 5 votes vote down vote up
def gen_noise_samples(self, imgwh, noise_type, num, **kwargs):
        center_xy = self.xy + self.wh * 0.5
        mean_wh = sum(self.wh) / 2.0

        gaussian_translation_f = kwargs.get('gaussian_translation_f', 0.1)
        uniform_translation_f = kwargs.get('uniform_translation_f', 1)
        uniform_scale_f = kwargs.get('uniform_scale_f', 10)

        samples = []
        if noise_type == 'whole':
            grid_x = range(self.wh.x // 2, imgwh.x - self.wh.x // 2, self.wh.x // 5)
            grid_y = range(self.wh.y // 2, imgwh.y - self.wh.y // 2, self.wh.y // 5)
            samples_tmp = []
            for dx, dy, ds in itertools.product(grid_x, grid_y, range(-5, 5, 1)):
                box = BoundingBox(dx, dy, self.wh.x*(1.05**ds), self.wh.y*(1.05**ds))
                box.fit_image(imgwh)
                samples_tmp.append(box)

            for _ in range(num):
                samples.append(random.choice(samples_tmp))
        else:
            for _ in range(num):
                if noise_type == 'gaussian':
                    dx = gaussian_translation_f * mean_wh * minmax(0.5 * random.normalvariate(0, 1), -1, 1)
                    dy = gaussian_translation_f * mean_wh * minmax(0.5 * random.normalvariate(0, 1), -1, 1)
                    dwh = 1.05 ** (3 * minmax(0.5 * random.normalvariate(0, 1), -1, 1))
                elif noise_type == 'uniform':
                    dx = uniform_translation_f * mean_wh * random.uniform(-1.0, 1.0)
                    dy = uniform_translation_f * mean_wh * random.uniform(-1.0, 1.0)
                    dwh = 1.05 ** (uniform_scale_f * random.uniform(-1.0, 1.0))
                else:
                    raise
                new_cxy = center_xy + (dx, dy)
                new_wh = self.wh * dwh
                box = BoundingBox(new_cxy.x - new_wh.x / 2.0, new_cxy.y - new_wh.y / 2.0, new_wh.x, new_wh.y)
                box.fit_image(imgwh)
                samples.append(box)

        return samples 
Example 72
Project: aiomongo   Author: ZeoAlliance   File: utils.py    Apache License 2.0 5 votes vote down vote up
def sleep(self) -> None:
        new_delay = min(self.delay * self.factor, self.max_delay)
        self.delay = random.normalvariate(new_delay, new_delay*self.jitter)

        await asyncio.sleep(self.delay, loop=self.loop) 
Example 73
Project: embedded-jubatus-python-obsolete   Author: kazuki   File: test_bandit.py    GNU Lesser General Public License v2.1 5 votes vote down vote up
def test(self):
        x = Bandit(CONFIG)

        player = 'player'
        slots = {
            'a': [
                lambda: random.random() < 0.1,
                lambda: random.normalvariate(50, 10),
            ],
            'b': [
                lambda: random.random() < 0.01,
                lambda: random.normalvariate(600, 100),
            ],
            'c': [
                lambda: random.random() < 0.001,
                lambda: random.normalvariate(8000, 1000),
            ],
        }
        keys = list(slots.keys())
        for k in keys:
            self.assertTrue(x.register_arm(k))
        self.assertFalse(x.register_arm(keys[0]))
        self.assertFalse(x.reset(player))

        for _ in range(10):
            arm = x.select_arm(player)
            f0, f1 = slots[arm]
            self.assertTrue(arm in keys)
            x.register_reward(player, arm, f1() if f0() else 0.0)
        info = x.get_arm_info(player)
        self.assertEqual(3, len(info))
        self.assertTrue(isinstance(info[keys[0]], ArmInfo))

        model = x.save_bytes()
        x = Bandit(CONFIG)
        x.load_bytes(model)
        self.assertEqual(CONFIG, json.loads(x.get_config()))
        info = x.get_arm_info(player)
        self.assertEqual(3, len(info))
        self.assertTrue(isinstance(info[keys[0]], ArmInfo)) 
Example 74
Project: MuscleSpindleCircuitsModel   Author: FormentoEmanuele   File: NeuralNetwork.py    MIT License 4 votes vote down vote up
def _connect(self,sourcesId,targetsId,conRatio,conNum,conWeight,synType, conDelay=1):
		""" Connect source cells to target cells.

		Keyword arguments:
		sourcesId -- List with the id of the source cells.
		targetsId -- List with the id of the target cells.
		conRatio -- Define how the source cells are connected to the target cells;
		It can be either "unique"  or "random". With "unique" every source cell is connected
		to every target cell, while with "random" every target cell is connected to n=conNum
		randomly selected source cells.
		conNum -- Number of source cells connected to every target cell. Note that with "unique"
		conRation this parameter is still mandatory for double checking.
		conWeight -- Connection weight.
		synType -- Type of synapse that form the connection. It could be either "artificial" for
		artificial cells or "excitatory"/"inhibitory" for realistic cell models.
		conDelay -- Delay of the synapse in ms (default = 1).
		"""
		noisePerc = 0.2
		for targetId in targetsId:
			# check whether this id is associated with a cell in this host
			if not self._pc.gid_exists(targetId): continue
			if conRatio == "unique" and len(sourcesId)!=conNum:
				raise Exception("Wrong connections number parameter. If the synapses ratio is 'unique' the number of synapses has to be the same as the number of source cells")
			# retrieve the target for artificial cells
			if synType == "artificial":
				target = self._pc.gid2cell(targetId)
			# retrieve the cell for realistic cells
			elif synType == "excitatory" or synType == "inhibitory":
				cell = self._pc.gid2cell(targetId)
			else: raise Exception("Wrong synType")

			# create the connections
			for i in range(conNum):
				# create the target for realistic cells
				if synType == "excitatory" or synType == "inhibitory": target = cell.create_synapse(synType)
				if conRatio == "unique": source = sourcesId[i]
				elif conRatio == "random": source = rnd.choice(sourcesId)
				else : raise Exception("Wrong connections ratio parameter")
				nc = self._pc.gid_connect(source,target)
				nc.weight[0] = rnd.normalvariate(conWeight,conWeight*noisePerc)
				nc.delay = conDelay+rnd.normalvariate(0.25,0.25*noisePerc)
				self._connections.append(nc)
		comm.Barrier() 
Example 75
Project: CoDeepNEAT   Author: sash-a   File: module_node.py    MIT License 4 votes vote down vote up
def get_new_conv_parameter_mutagens():
    return {
        "conv_window_size": Option("conv_window_size", 1, 3, 5, 7, current_value=random.choice([1, 3, 5, 7]),
                                   mutation_chance=0.13),

        "conv_stride": IntegerVariable("conv_stride", current_value=1, start_range=1, end_range=5, mutation_chance=0.1),

        "reduction": Option("reduction", None, nn.MaxPool2d#, nn.AvgPool2d
                            ,current_value=nn.MaxPool2d if random.random() < config.module_node_max_pool_chance else None,
                            submutagens=
                            {
                                nn.MaxPool2d: {
                                    "pool_size": IntegerVariable("pool_size",
                                                                 current_value=2,
                                                                 start_range=2,
                                                                 end_range=5,
                                                                 mutation_chance=0.1)}

                                # ,nn.AvgPool2d: {
                                #     "pool_size": IntegerVariable("pool_size",
                                #                                  current_value=2,
                                #                                  start_range=2,
                                #                                  end_range=5,
                                #                                  mutation_chance=0.1)}
                            }
                            , mutation_chance=0.15),

        "regularisation": Option("regularisation", None, nn.BatchNorm2d,
                                 current_value=nn.BatchNorm2d if random.random() < config.module_node_batchnorm_chance else None,
                                 mutation_chance=0.15),

        "dropout": Option("dropout", None, nn.Dropout2d,
                          current_value=nn.Dropout2d if random.random() < config.module_node_dropout_chance else None,
                          submutagens=
                          {
                              nn.Dropout2d: {
                                  "dropout_factor": ContinuousVariable("dropout_factor", current_value=0.1,
                                                                       start_range=0, end_range=0.75,
                                                                       mutation_chance=0.15)
                              }
                          },
                          mutation_chance=0.08),

        "out_features": IntegerVariable("out_features", current_value=int(random.normalvariate(mu=50, sigma=20)),
                                        start_range=1,
                                        end_range=100, mutation_chance=0.22),

        "pad_output": Option("pad_output", True, False,
                             current_value=random.choices([True, False], weights=[0.65, 0.35])[0])
    } 
Example 76
Project: graph_slam   Author: Bazs   File: path_generator.py    MIT License 4 votes vote down vote up
def generate_ground_truth_path(ground_truth_map, max_velocity, velocity_deviation, max_turn_rate, turn_rate_deviation,
                               step_count, velocity_control_deviation, turn_rate_control_deviation):
    """Generates a random path using a constant velocity and turn rate motion model. Also returns the velocity and turn
    rate for each state, after adding some zero mean Gaussian noise to them.

    Generates a sequence of step_count consecutive [x, y, theta].T states. The velocity and turn rate is piecewise
    constant between two states, and they change by a random value at each state, which is sampled from a zero mean
    gaussian distribution, whose standard deviation is given by the parameters velocity_deviation and
    turn_rate_deviation. The velocity and turn rate are also limited to the range of [0, max_velocity] and
    [-max_turn_rate, max_turn_rate], respectively.
    Additionally, each generated node is ensured to be collision free with respect to the specified map.
    """
    start_x, start_y = generate_random_free_coordinate(ground_truth_map)
    start_x = start_x + rnd.random() - 1
    start_y = start_y + rnd.random() - 1
    start_th = math.pi * (2 * rnd.random() - 1)

    current_state = np.array([[start_x, start_y, start_th]]).T
    ground_truth_states = [current_state]

    # velocity and turn rate
    v, omega = 0, 0
    controls = [add_noise_to_control(np.array([[v, omega]]).T, velocity_control_deviation=velocity_control_deviation,
                turn_rate_control_deviation=turn_rate_control_deviation)]

    for step in range(step_count - 1):
        proposal_state_is_valid = False

        while proposal_state_is_valid is False:
            v_proposal = v + rnd.normalvariate(0, velocity_deviation)
            v_proposal = clip(v_proposal, 0, max_velocity)

            omega_proposal = omega + rnd.normalvariate(0, turn_rate_deviation)
            omega_proposal = clip(omega_proposal, -max_turn_rate, max_turn_rate)

            # CTRV motion model
            delta_pos = calculate_odometry_from_controls(v_proposal, omega_proposal, current_state)
            proposal_state = current_state + delta_pos

            proposal_x = round(proposal_state.item(0))
            proposal_y = round(proposal_state.item(1))

            proposal_state_is_within_map = (0 <= proposal_y < ground_truth_map.shape[0] and
                                            0 <= proposal_x < ground_truth_map.shape[1])
            proposal_state_is_valid = (proposal_state_is_within_map and
                                       0 == ground_truth_map.item(proposal_y, proposal_x))

        v = v_proposal
        omega = omega_proposal

        controls.append(add_noise_to_control(np.array([[v, omega]]).T,
                                             velocity_control_deviation=velocity_control_deviation,
                                             turn_rate_control_deviation=turn_rate_control_deviation))

        proposal_state[2] = normalize_angle_pi_minus_pi(proposal_state[2])

        ground_truth_states.append(proposal_state)
        current_state = proposal_state

    return ground_truth_states, controls 
Example 77
Project: graph_slam   Author: Bazs   File: measurement_model.py    MIT License 4 votes vote down vote up
def generate_measurements(ground_truth_states, landmarks, max_sensing_range, sensing_range_deviation,
                          distance_deviation, heading_deviation):
    """
    Generates a list of measurements for every state in ground_truth_states. Measurements are numpy arrays of
    [r, phi, s].T, r being the distance to landmark, phi is heading (positive X direction is 0 rad, grows
    counter-clockwise), s is the landmark descriptor - an integer. Measurements contain additional zero-mean gaussian
    noise for the distance and heading, as specified by distance_deviation and heading_deviation.

    For each state, only landmarks within max_sensing_range are considered. From this group of landmarks, detections
    are sampled using the absolute values of random samples from a zero mean, sensing_range_deviation normal
    distribution as distance threshold.
    """

    measurements = []
    correspondences = []

    for ground_truth_state in ground_truth_states:
        landmark_distance_index_list = get_landmarks_in_range(ground_truth_state, landmarks,
                                                              max_sensing_range)

        # Sample obstacles from the in-range ones, using the absolute values of samples from a zero-mean normal
        # distribution as distance thresholds
        landmark_distance_index_list = [landmark_distance_index for landmark_distance_index in
                                        landmark_distance_index_list if
                                        abs(rnd.normalvariate(0, sensing_range_deviation))
                                        >= landmark_distance_index.distance]

        measurements_for_state = [
            calculate_measurement_vector_for_detection(ground_truth_state, landmark_distance_index) for
            landmark_distance_index in landmark_distance_index_list]
        correspondences_for_state = [landmark_distance_index.index for landmark_distance_index in
                                     landmark_distance_index_list]

        add_noise_to_measurements_for_state(measurements_for_state, distance_deviation, heading_deviation)

        assert len(measurements_for_state) == len(correspondences_for_state)

        measurements.append(measurements_for_state)
        correspondences.append(correspondences_for_state)

    compress_correspondences(correspondences)

    assert len(measurements) == len(correspondences)
    for index, correspondence_for_state in enumerate(correspondences):
        assert len(measurements[index]) == len(correspondence_for_state)

    return measurements, correspondences 
Example 78
Project: DB12   Author: DIRACGrid   File: DIRACbenchmark.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def singleDiracBenchmark( iterations = 1, measuredCopies = None ):
  """ Get Normalized Power of one CPU in DIRAC Benchmark 2012 units (DB12)
  """

  # This number of iterations corresponds to 1kHS2k.seconds, i.e. 250 HS06 seconds

  n = int( 1000 * 1000 * 12.5 )
  calib = 250.0

  m = long( 0 )
  m2 = long( 0 )
  p = 0
  p2 = 0
  # Do one iteration extra to allow CPUs with variable speed (we ignore zeroth iteration)
  # Do one or more extra iterations to avoid tail effects when copies run in parallel
  i = 0
  while (i <= iterations) or (measuredCopies is not None and measuredCopies.value > 0):
    if i == 1:
      start = os.times()

    # Now the iterations
    for _j in xrange( n ):
      t = random.normalvariate( 10, 1 )
      m += t
      m2 += t * t
      p += t
      p2 += t * t

    if i == iterations:
      end = os.times()
      if measuredCopies is not None:
        # Reduce the total of running copies by one
        measuredCopies.value -= 1

    i += 1
    
  cput = sum( end[:4] ) - sum( start[:4] )
  wall = end[4] - start[4]

  if not cput:
    return None
  
  # Return DIRAC-compatible values
  return { 'CPU' : cput, 'WALL' : wall, 'NORM' : calib * iterations / cput, 'UNIT' : 'DB12' } 
Example 79
Project: WarshipGrilsRobot   Author: PaleNeutron   File: zrobot.py    Apache License 2.0 4 votes vote down vote up
def __init__(self, name,
                 node_type=NODE_SIMPLE,
                 formation=2,
                 night_flag=0,
                 big_broken_protect=True,
                 enemy_target=None,
                 enemy_avoid=None,
                 additional_spy_filter=None,
                 sleep_time=None):
        """we have 3 node_types: simple, resource, skip"""
        super(Node, self).__init__()
        self.name = str.upper(name)
        self.node_id = 0

        self.big_broken_protect = big_broken_protect
        self.next_nodes = []
        if node_type not in self._node_types:
            raise ValueError('{} is not a node type'.format(node_type))
        self.node_type = node_type
        self.night_flag = night_flag
        self.battle_result = {}
        self.formation = formation
        self.enemy_target = enemy_target
        self.enemy_avoid = enemy_avoid
        self.skip_rate_limit = 0
        self.skip_rate = 0

        if sleep_time:
            self.sleep_mu = sleep_time
        else:
            self.sleep_mu = Node.DEFAULT_SLEEP_TIME
        self.sleep_sigma = 2
        rd = random.normalvariate(self.sleep_mu, self.sleep_sigma)
        if rd < self.sleep_mu - 3 * self.sleep_sigma or \
                rd > self.sleep_mu + 3 * self.sleep_sigma:
            self.battle_length = self.sleep_mu
        else:
            self.battle_length = rd

        self.additional_spy_filter = additional_spy_filter

        self.boss_hp = -1
        self.ze = None 
Example 80
Project: fake_exporter   Author: filippog   File: fake_exporter.py    GNU General Public License v3.0 4 votes vote down vote up
def fake_metrics():
    """Yield fake prometheus metrics.

    Each metric will be repeated random(0, metric_repeat) times, each with
    different tags (possibly none) up to random(0, max_tags).
    """

    metric_repeat = int(request.args.get('metric_repeat', 5))
    metrics = int(request.args.get('metrics', 128))
    max_tags = int(request.args.get('max_tags', 4))
    prefix = request.args.get('prefix', 'fake_')
    seed = int(request.args.get('seed', time.time()))

    # generate "truly" random values first, then seed the PRNG
    start_values = [random.randint(0, 2**15) for x in range(metrics)]
    random.seed(seed)

    all_tags = ['key%d' % x for x in range(max_tags)]

    result = []
    seen_metrics = {}
    while len(result) < metrics:
        m = random.choice(WORDS)
        tag_keys = all_tags[:random.randint(0, len(all_tags))]
        for repeat in range(random.randint(1, metric_repeat)):
            m_tags = ['%s="%s"' % (x, random.choice(WORDS)) for x in tag_keys]
            m_name = "%s%s{%s}" % (prefix, m, ','.join(m_tags))
            if not m_tags:
                m_name = "%s%s" % (prefix, m)

            if m_name in seen_metrics:
                break
            seen_metrics[m_name] = 1

            if m_name not in METRIC_VALUES:
                m_hash = sum([ord(x) for x in m_name])
                METRIC_VALUES[m_name] = start_values[m_hash % len(start_values)]

            # http://users.ecs.soton.ac.uk/jn2/teaching/pythonLecture.html
            # meanIncrease, stdDevIncrease
            delta = random.normalvariate(0.2, 1.2)
            # XXX force all metrics to increase
            if delta < 0:
                delta *= -1
            METRIC_VALUES[m_name] += delta
            result.append("%s %f" % (m_name, METRIC_VALUES[m_name]))
    return '\n'.join(result) + '\n'