Python random.normalvariate() Examples

The following are 30 code examples of random.normalvariate(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module random , or try the search function .
Example #1
Source File: heston.py    From tensortrade with Apache License 2.0 6 votes vote down vote up
def heston_construct_correlated_path(params: ModelParameters,
                                     brownian_motion_one: np.array):
    """
    This method is a simplified version of the Cholesky decomposition method
    for just two assets. It does not make use of matrix algebra and is therefore
    quite easy to implement.

    Arguments:
        params : ModelParameters
            The parameters for the stochastic model.
        brownian_motion_one : np.array
            (Not filled)

    Returns:
        A correlated brownian motion path.
    """
    # We do not multiply by sigma here, we do that in the Heston model
    sqrt_delta = np.sqrt(params.all_delta)
    # Construct a path correlated to the first path
    brownian_motion_two = []
    for i in range(params.all_time - 1):
        term_one = params.cir_rho * brownian_motion_one[i]
        term_two = np.sqrt(1 - pow(params.cir_rho, 2)) * random.normalvariate(0, sqrt_delta)
        brownian_motion_two.append(term_one + term_two)
    return np.array(brownian_motion_one), np.array(brownian_motion_two) 
Example #2
Source File: __main__.py    From slicesim with MIT License 6 votes vote down vote up
def get_dist(d):
    return {
        'randrange': random.randrange, # start, stop, step
        'randint': random.randint, # a, b
        'random': random.random,
        'uniform': random, # a, b
        'triangular': random.triangular, # low, high, mode
        'beta': random.betavariate, # alpha, beta
        'expo': random.expovariate, # lambda
        'gamma': random.gammavariate, # alpha, beta
        'gauss': random.gauss, # mu, sigma
        'lognorm': random.lognormvariate, # mu, sigma
        'normal': random.normalvariate, # mu, sigma
        'vonmises': random.vonmisesvariate, # mu, kappa
        'pareto': random.paretovariate, # alpha
        'weibull': random.weibullvariate # alpha, beta
    }.get(d) 
Example #3
Source File: gaming.py    From CloudBot with 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 #4
Source File: gaming.py    From CloudBot with 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 #5
Source File: data_generator.py    From py_stringsimjoin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_table(mean, std_dev, tokens, num_records,
                   id_col_name, attr_col_name):
    records = []
    cnt = 0
    num_tokens = len(tokens)
    while cnt < num_records:
        size = int(round(random.normalvariate(mean,
                                              std_dev)))
        new_string = ''
        for i in range(size):
            rand = random.randint(0, num_tokens - 1)
            if i == 0:
                new_string += tokens[rand]
            else:
                new_string += ' ' + tokens[rand]

        records.append([cnt, new_string])
        cnt += 1
    return pd.DataFrame(records, columns=[id_col_name, attr_col_name]) 
Example #6
Source File: data_generator.py    From py_stringsimjoin with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def generate_tokens(mean, std_dev, num_tokens):
    tokens = {}
    cnt = 0
    while cnt < num_tokens:
        length = int(round(random.normalvariate(mean,
                                                std_dev)))
        if length < 2:
            continue
        flag = True
        while flag:
            new_token = ''.join(random.choice(string.ascii_lowercase)
                                for i in range(length))
            if tokens.get(new_token) is None:
                tokens[new_token] = True
                flag = False
        cnt += 1
    return list(tokens.keys()) 
Example #7
Source File: test_var.py    From ray with Apache License 2.0 6 votes vote down vote up
def testDependentGridSearchCallable(self):
        class Normal:
            def __call__(self, _config):
                return random.normalvariate(mu=0, sigma=1)

        class Single:
            def __call__(self, _config):
                return 20

        trials = self.generate_trials({
            "run": "PPO",
            "config": {
                "x": grid_search(
                    [tune.sample_from(Normal()),
                     tune.sample_from(Normal())]),
                "y": tune.sample_from(Single()),
            },
        }, "dependent_grid_search")
        trials = list(trials)
        self.assertEqual(len(trials), 2)
        self.assertEqual(trials[0].config["y"], 20)
        self.assertEqual(trials[1].config["y"], 20) 
Example #8
Source File: test_active_information_storage.py    From IDTxl with 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 #9
Source File: test_estimators_jidt.py    From IDTxl with 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 #10
Source File: gaming.py    From CloudBot with 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 in ('f', 'F'):
        return [random.randint(-1, 1) for _ in range(min(count, 100))]

    if count < 100:
        return [random.randint(1, n) for _ in range(count)]

    # Calculate a random sum approximated using a randomized normal variate with the midpoint used as the mu
    # and an approximated standard deviation based on variance as the sigma
    mid = .5 * (n + 1) * count
    var = (n ** 2 - 1) / 12
    adj_var = (var * count) ** 0.5

    return [int(random.normalvariate(mid, adj_var))] 
Example #11
Source File: test_stats.py    From rectpack with 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
Source File: fm.py    From Jtyoui with 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 #13
Source File: optimize.py    From traversing_knowledge_graphs with MIT License 5 votes vote down vote up
def random(cls, x, sigma=1.0):
        """
        Generate a random vector with the same keys and dimensions as x
        """
        rand = cls()
        for key, val in x.iteritems():
            if isinstance(val, float):
                d = random.normalvariate(0, sigma)
            else:
                d = np.random.normal(scale=sigma, size=x[key].shape)
            rand[key] = d
        return rand 
Example #14
Source File: protocol.py    From BitTorrent with GNU General Public License v3.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,))
        from twisted.internet import reactor

        def reconnector():
            self._callID = None
            connector.connect()
        self._callID = reactor.callLater(self.delay, reconnector) 
Example #15
Source File: auxiliary.py    From Ciw with MIT License 5 votes vote down vote up
def truncated_normal(mean, sd):
	"""
	Sample from a Normal distribution, with mean and standard
	deviation (sd). This truncates the distribution at 0 (lower bound
	of 0). If samples less than 0 are sampled, they are resampled
    until a positive value is sampled.
	"""
	sample = random.normalvariate(mean, sd)
	while sample <= 0.0:
		sample = random.normalvariate(mean, sd)
	return sample 
Example #16
Source File: support.py    From joinmarket-clientserver with GNU General Public License v3.0 5 votes vote down vote up
def rand_norm_array(mu, sigma, n):
    # use normalvariate instead of gauss for thread safety
    return [random.normalvariate(mu, sigma) for _ in range(n)] 
Example #17
Source File: params.py    From intrinsic with MIT License 5 votes vote down vote up
def random_perterbation(
            self, mean_num_params=8, std_delta=0.5, seed=None):
        """ Return a new set of parameters with a random perterbation.  The
        number of variables modified is Poisson-distributed with mean
        ``mean_num_params`` , and each changed variable is multiplied by exp(x)
        where x is normally distributed with mean 0 and standard deviation
        ``std_delta`` """

        if seed is not None:
            random.seed(seed)
            np.random.seed(seed)

        # choose a random subset to modify
        num_params = len(IntrinsicParameters.TRAIN_PARAMS)
        n = np.clip(np.random.poisson(mean_num_params), 1, num_params)
        keys = random.sample(IntrinsicParameters.TRAIN_PARAMS, n)

        # modify the subset
        ret = copy.deepcopy(self)
        for k in keys:
            v = getattr(ret, k)
            t = type(v)

            if k in IntrinsicParameters.PARAM_CHOICES:
                v = random.choice(IntrinsicParameters.PARAM_CHOICES[k])
            elif t == bool:
                v = random.choice((False, True))
            else:
                v *= np.exp(random.normalvariate(0, std_delta))

            if t in (int, long):
                v = round(v)
            setattr(ret, k, t(v))

        ret.clip()
        return ret 
Example #18
Source File: timeutil.py    From conary with Apache License 2.0 5 votes vote down vote up
def sleep(self):
        time.sleep(self.delay)
        self.delay *= self.factor
        self.delay = random.normalvariate(self.delay, self.delay * self.jitter) 
Example #19
Source File: distributions.py    From research with MIT License 5 votes vote down vote up
def normal_distribution(mean, standev):
    def f():
        return int(random.normalvariate(mean, standev))

    return f 
Example #20
Source File: distributions.py    From research with MIT License 5 votes vote down vote up
def normal_distribution(mean, standev):
    def f():
        return int(random.normalvariate(mean, standev))

    return f 
Example #21
Source File: distributions.py    From research with MIT License 5 votes vote down vote up
def normal_distribution(mean, standev):
    def f():
        return int(random.normalvariate(mean, standev))

    return f 
Example #22
Source File: mol_sim.py    From cellblender with GNU General Public License v2.0 5 votes vote down vote up
def __init__ ( self, num, dist, center_x, center_y, center_z, seed, method='slow' ):

    # Create a distribution as requested
    
    global fixed_points
    global fixed_index

    if len(fixed_points) <= 0:
        print ( "Generating normal distribution" )
        random.seed ( seed )
        for i in range(100000):
            fixed_points.append ( point ( random.normalvariate(center_x,dist), random.normalvariate(center_y,dist), random.normalvariate(center_z,dist) ) )

    self.points = [];
    self.faces = [];
    
    if method == 'slow':    # Use random number generator (slowest)
        for i in range(num):
            self.points.append ( point ( random.normalvariate(center_x,dist), random.normalvariate(center_y,dist), random.normalvariate(center_z,dist) ) )
    elif method == 'med':  # Use precalculated random points (faster, but repeats points)
        fixed_index = random.randint ( 0, len(fixed_points)-4 )
        for i in range(num):
            if fixed_index >= len(fixed_points):
                fixed_index = random.randint ( 0, len(fixed_points)-1 )
            self.points.append ( fixed_points[fixed_index] )
            fixed_index += 1
    elif method == 'fast':     # Use a single fixed value (fastest, all points are the same!!)
        single_point = point ( center_x, center_y, center_z )
        for i in range(num):
            self.points.append ( single_point ) 
Example #23
Source File: kitti_seg_input.py    From KittiSeg with 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 #24
Source File: heston.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def get_correlated_geometric_brownian_motions(params: ModelParameters,
                                              correlation_matrix: np.array,
                                              n: int):
    """
    Constructs a basket of correlated asset paths using the Cholesky
    decomposition method.

    Arguments:
        params : ModelParameters
            The parameters for the stochastic model.
        correlation_matrix : np.array
            An n x n correlation matrix.
        n : int
            Number of assets (number of paths to return)

    Returns:
        n correlated log return geometric brownian motion processes
    """
    decomposition = sp.linalg.cholesky(correlation_matrix, lower=False)
    uncorrelated_paths = []
    sqrt_delta_sigma = np.sqrt(params.all_delta) * params.all_sigma
    # Construct uncorrelated paths to convert into correlated paths
    for i in range(params.all_time):
        uncorrelated_random_numbers = []
        for j in range(n):
            uncorrelated_random_numbers.append(random.normalvariate(0, sqrt_delta_sigma))
        uncorrelated_paths.append(np.array(uncorrelated_random_numbers))
    uncorrelated_matrix = np.asmatrix(uncorrelated_paths)
    correlated_matrix = uncorrelated_matrix * decomposition
    assert isinstance(correlated_matrix, np.matrix)
    # The rest of this method just extracts paths from the matrix
    extracted_paths = []
    for i in range(1, n + 1):
        extracted_paths.append([])
    for j in range(0, len(correlated_matrix) * n - n, n):
        for i in range(n):
            extracted_paths[i].append(correlated_matrix.item(j + i))
    return extracted_paths 
Example #25
Source File: dns-queue.py    From dns-parallel-prober with GNU General Public License v3.0 5 votes vote down vote up
def run(self):
        # sleep for a small amount of time, between 0.1 and 0.9
        _sleep_for = abs(random.normalvariate(0.5, 0.5))
        log.debug("Mock probe {} sleeping for {}...".format(self.name, _sleep_for))
        time.sleep(_sleep_for)
        if random.random() > 0.7:
            log.debug("Mock probe {} found a result.")
            res.append("{} | {}".format(self.target, '127.0.0.1'))
        log.debug("Mock prober {} done".format(self.name)) 
Example #26
Source File: heston.py    From tensortrade with Apache License 2.0 5 votes vote down vote up
def jump_diffusion_process(params: ModelParameters):
    """
    Produces a sequence of Jump Sizes which represent a jump
    diffusion process. These jumps are combined with a geometric brownian
    motion (log returns) to produce the Merton model.

    Arguments:
        params : ModelParameters
            The parameters for the stochastic model.

    Returns:
        jump sizes for each point in time (mostly zeroes if jumps are infrequent)
    """
    s_n = time = 0
    small_lamda = -(1.0 / params.lamda)
    jump_sizes = []
    for k in range(params.all_time):
        jump_sizes.append(0.0)
    while s_n < params.all_time:
        s_n += small_lamda * np.log(np.random.uniform(0, 1))
        for j in range(params.all_time):
            if time * params.all_delta <= s_n * params.all_delta <= (j + 1) * params.all_delta:
                jump_sizes[j] += random.normalvariate(params.jumps_mu, params.jumps_sigma)
                break
        time += 1
    return jump_sizes 
Example #27
Source File: render.py    From g-tensorflow-models with 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 #28
Source File: render.py    From g-tensorflow-models with 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 #29
Source File: render.py    From models with 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 #30
Source File: render.py    From models with 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