def workload_generator():
    workload = []
    # random.seed(RANDOM_SEED)      #due to result unstable
    for i in range(WORKLOAD_LENGTH):
        t = random.paretovariate(1) - 1
        if t > 2:
            t = random.paretovariate(1) - 1
            if t > 2:
                t = 2
            # t = 3
        workload.append(int(t/2*97*1000 + 3000))
    return workload
Esempio n. 2
0
    def simulate_once(self, servers, track_history = False):

        if(track_history): self.one_sim_once_hist = []

        # set up some useful variables
        max_wait = 5
        total_minutes = 60 * 24

        # prepare array of request slots
        request_slots = [0.0] * servers

        # start simulation
        requests = dropped = 0
        t = random.expovariate(1.0)
        while(t < total_minutes):

            # check if request can be served on any servers
            request_taken = False
            for i in range(0, servers):
                server_finish_time = request_slots[i]

                if(not request_taken):
                    # request not taken, serve if possible
                    if(server_finish_time < t):
                        # server is open, assign new req with finish time
                        request_slots[i] = t + 5 * random.paretovariate(2.5)
                        request_taken = True
                        break
                    elif(server_finish_time < t + max_wait):
                        # server will be open sometime within the max wait
                        #   threshold, calc new time as finish time + new time
                        request_slots[i] = server_finish_time + 5 * random.paretovariate(2.5)
                        request_taken = True
                        break

            # track some variables
            if(not request_taken): dropped += 1
            requests += 1

            if(track_history): self.one_sim_once_hist.append((t, requests, dropped))

            # calculate next request time
            t += random.expovariate(1.0)

        # scale simulation up to 1 year
        days = 365
        requests *= days
        dropped *= days
        # calculate cost
        cost = servers * 300 + dropped * 10

        return cost
Esempio n. 3
0
def bounded_pareto_variate(alpha, upper_bound):
    """Repeatedly draws a random variable from the Pareto distribution
    until the variable meets the given upper bound.

    `alpha` is the parameter for the Pareto distribution.

    `upper_bound` is the upper bound which the random variable must
    meet.

    """
    result = random.paretovariate(alpha)
    while result >= upper_bound:
        result = random.paretovariate(alpha)
    return result
Esempio n. 4
0
 def __init__(self, options={}):
     super(CellMazeMap, self).__init__(options)
     report('random seed {0}'.format(self.random_seed))
     self.name = 'cell_maze'
     self.players = self.get_random_option(options.get('players', max(2, min(10, int((betavariate(2.5, 3.0) * 10) + 1)))))
     report('players {0}'.format(self.players))
     self.area = self.get_random_option(options.get('area', self.players * randrange(400, 40000 / self.players)))
     report('area {0}'.format(self.area))
     self.cell_width = self.get_random_option(options.get('cell_width', min(paretovariate(2), 7.0)))
     report('cell width: {0}'.format(self.cell_width))
     self.cell_size = self.get_random_option(options.get('cell_size', int(min(paretovariate(2) + 4.0, 20.0) + int(self.cell_width) + 1)))
     report('cell size: {0}'.format(self.cell_size))
     self.openness = self.get_random_option(options.get('openness', betavariate(1.0, 3.0)))
     report('openness: {0}'.format(self.openness))
Esempio n. 5
0
def TallestPareto(iters=2, n=10000, xmin=100, alpha=1.7):
    """Find the tallest person in Pareto World."""
    tallest = 0
    for i in range(iters):
        t = [xmin * random.paretovariate(alpha) for i in range(n)]
        tallest = max(max(t), tallest)
    return tallest
Esempio n. 6
0
    def simulate_once(self):
        """Simulate once.

        Return
        ------
            This will return the amount of operational loss simulated for the
            given time period.

        Example:
        r=OpRiskModel(stor4)
        lower, mu, upper = r.simulate_many()
        print "Bootstrap: ",lower,mu,upper

        Output:
        0.68% between 127760271.155 and 162467836.895
        0.8% between 122874286.419 and 167353821.63
        0.9% between 116569621.33 and 173658486.72
        0.95% between 111101264.604 and 179126843.445
        0.98% between 104743118.138 and 185484989.911
        0.99% between 100413671.581 and 189814436.469
        0.995% between 96401399.4999 and 193826708.549
        0.998% between 91486833.5654 and 198741274.484
        0.999% between 88010967.5982 and 202217140.451
        0.9999% between 77597567.1919 and 212630540.857
        0.99999% between 68459385.7079 and 221768722.341
        Bootstrap:  138714608.714 145114054.025 150873917.501 
        """
        t=random.expovariate(self.params.lamb)
        loss=0.0
        while t<self.params.days:
            t+=random.expovariate(self.params.lamb)
            amount=self.params.xm*random.paretovariate(self.params.alpha)
            loss+=amount
        return loss
Esempio n. 7
0
def my_Funh():
    random.seed()
    print('random = ', random.random())
    print('getstate = ', random.getstate())
    state = random.getstate()
    random.setstate(state)
    print('setstate = ',random.random())
    print('getrandbits = ',random.getrandbits(6))
    print('randrange = ',random.randrange(3, 9))
    print('randint = ',random.randint(3, 9))
    x = 2,1,3,5,4,6,7,8,9,10,6

    print('choice = ',random.choice(x) + random.choice(x)+random.choice(x))
    mylist = [1, 2, 3,4,5,6,7,8,9,0]
    random.shuffle(mylist)

    print('shuffle =',*mylist)

    print("sample:", *random.sample(x, 8))
    print('uniform = ', random.uniform(20, 60))
    print('triangular = ',random.triangular(20, 60, 30))
    print('betavariate =',random.betavariate(5, 10))
    print('expovariate = ',random.expovariate(1.5))
    print('gammavariate =',random.gammavariate(100, 2))
    print('gauss =',random.gauss(100, 50))
    print('lognormvariate =',random.lognormvariate(0, 0.25))
    print('normalvariate =',random.normalvariate(0, 0.25))
    print('vonmisesvariate = ',random.vonmisesvariate(0,4))
    print('paretovariate = ',random.paretovariate(3))
    print('weibullvariate = ',random.weibullvariate(1, 1.5))
    b = input('New ? (y / n) = ')
    if b == 'y':
        my_Funh()
def mock_lag(lower_bound = 1.0 / 16, upper_bound = 4.0):
    '''Randomly generate seconds of network lag.
    >>> lags = [mock_lag() for i in range(1000)]
    >>> get_out_of_bounds(lags)
    >>> lags = [mock_lag() for i in range(1000)]
    >>> get_out_of_bounds(lags)
    >>> lags = [mock_lag() for i in range(1000)]
    >>> get_out_of_bounds(lags)

    Speed up for tests.
    >>> mock_speed = 16
    >>> lo, hi = 0.5 / mock_speed, 1.0 / mock_speed
    >>> lags = [mock_lag(lo, hi) for i in range(1000)]
    >>> out = get_out_of_bounds(lags, lo, hi)
    >>> if out:
    ...     lo, out, hi

    Other values.  Thin tail means upper bound is rarely approached.
    >>> lags = [mock_lag(1.0, 2.0) for i in range(1000)]
    >>> get_out_of_bounds(lags, 1.0, 2.0)
    '''
    lag = random.paretovariate(14) - 1
    range = upper_bound - lower_bound
    unfiltered = lag * range + lower_bound
    high_pass = max(lower_bound, unfiltered)
    bounded = min(upper_bound, high_pass)
    return bounded
Esempio n. 9
0
def generate(num_uniques, alpha):
    # generate unique lines
    uniques = set()
    for _ in xrange(int(num_uniques)):
        s = randstr(random.randrange(1, 6))

        # make sure it's actually unique
        while s in uniques:
            s = randstr(random.randrange(1, 6))

        uniques.add(s)

    uniques = list(uniques)

    # make sure each unique is in there once
    output = list(uniques)

    # add random uniques to the output until we have enough
    for _ in xrange(int(1e6) - len(uniques)):
        index = int(round(random.paretovariate(alpha) -1))
        index = min(index, len(uniques))
        output.append(uniques[index - 1])

    # shuffle so the uniques are no longer in the beginning
    random.shuffle(output)

    return output
Esempio n. 10
0
def make_dummy_wallets(n, blind):
    # Not a realistic shape, but for an alphanet faucet it's better to
    # have less variance.
    amounts = [random.paretovariate(10.0) - 1 for i in range(n)]
    amounts = [i / sum(amounts) * 700e6 for i in amounts]
    wallets = {}
    secrets = {}
    # initialize random functions so that we generate a determistic
    # set of keys based on the seed passed in.  We wait until after
    # we have set the balances for compatibility with older code.
    # This is also the reason that we consume an int to start.
    random.seed(a=blind, version=2)
    random.randint(0, 2**32)
    for i in range(0, n):
        entropy = blake2b(str(i).encode('utf-8'), 20, key=blind).digest()
        mnemonic = m.to_mnemonic(entropy).split(' ')
        password = ''.join(
            random.choice(string.ascii_letters + string.digits)
            for _ in range(10))
        email = random_email()
        sk, pk, pkh, pkh_b58 = get_keys(' '.join(mnemonic), email, password)
        amount = tez_to_int(amounts[i])
        wallets[pkh_b58] = amount
        secret = secret_code(pkh, blind)
        secrets[pkh_b58] = (mnemonic, email, password, amount,
                            binascii.hexlify(secret))
    return wallets, secrets
def pickPareto(maxNum):
    while True:
        parNum = random.paretovariate(1) - 1
        if parNum <= factor - 1:
            break
    n = int((parNum / (factor - 1)) * testWorldBalls) + 1
    return n
Esempio n. 12
0
def generate_matrix_sparse2(matrix_order):
    matrix_c_lstoflst = []
    lst = []
    m = matrix_order
    f = open("matrix_in22.txt", 'w')
    f.writelines(str(matrix_order))
    f.writelines('\n')
    row = 0
    col = 0
    while m > 0:
        n = matrix_order
        lst = []
        while n > 0:
            pareto_par = random.paretovariate(1)
            if pareto_par > 5.0:
                var = random.randrange(1, 10)
                lst.append(var)
                f.writelines('(')
                f.writelines(str(row + 1))
                f.writelines(',')
                f.writelines(str(col + 1))
                f.writelines(',')
                f.writelines(str(var))
                f.writelines(')')
                f.writelines('\n')
            else:
                lst.append(0)
            n = n - 1
            col = col + 1
        matrix_c_lstoflst.append(lst)
        m = m - 1
        row = row + 1
        col = 0
    f.close()
    return matrix_c_lstoflst
    def generate(self, packet_params):  # generates bursts
        meanTBA = packet_params["mean-arrival"]
        min_packet_duration = packet_params["min-duration"]
        packet_duration_concentration = packet_params["duration-concentration"]

        i = 0
        while True:
            # initialize burst at random time in future with random duration
            burst = Burst(name="Burst %s" % i, sim=self.sim)

            # generate next burst time
            # yield to next burst time
            # arrival time of burst a Poisson distr
            interarrival_time = expovariate(1.0 / meanTBA)
            # hold suspends until interarrival time has passed
            yield hold, self, interarrival_time
            #print "%s arrived at %s" % (self.name, self.sim.now())

            # generate duration
            # Pareto distribution for burst durtion
            duration = ceil(paretovariate(packet_duration_concentration)) +
                       min_packet_duration

            # activate burst with a duration and load balancer
            self.sim.activate(burst, burst.visit(duration))

            i += 1
Esempio n. 14
0
def pareto_dist_orgs(organism, alpha=1):
    """Implementation of the Pareto distribution for species member counts.
    
    See http://en.wikipedia.org/wiki/Pareto_distribution#Generating_bounded_Pareto_random_variables
    """
    rand = random.paretovariate(alpha)
    return rand
Esempio n. 15
0
def generate_users(student_count, reputation_alpha=REPUTATION_SHAPE):
    role_distribution = (
        ('student', student_count, 0),
        ('staff', int(student_count * STAFF_PER_STUDENT),
            REPUTATION_STAFF_SHIFT),
        ('other', int(student_count * OTHER_PER_STUDENT), 0),
    )

    users = []
    i = 1
    counts = dict((r, 0) for r in zip(*role_distribution)[0])
    for role, n, rep_shift in role_distribution:
        for _ in itertools.repeat(None, n):
            reputation = math.floor(random.paretovariate(reputation_alpha))
            reputation += rep_shift
            user = User(id=i, role=role, reputation=reputation)
            counts[role] += 1
            users.append(user)
            i += 1
    print "User statistics: "
    total = 0
    for role, count in counts.items():
        print "  %s: %d" % (role, count)
        total += count
    print "  total: %d" % total
    return users
def libretas():
    'Generador de un sample de una distribución (inventada) de libretas'
    ano = -1
    while ano < 0:
        ano = 15 - 1 * int(random.paretovariate(6))
    num = int(random.uniform(1, 5000))
    return '{:0>2}{:0>4}'.format(ano, num)
Esempio n. 17
0
    def simulate_once(self, n_traders, a_capital, days_per_year = 365):
        history = []
        traders = []

        # calculate day of the first jump
        t_jump = random.expovariate(lambd = 1.0 / (days_per_year * 10))
        for d in range(days_per_year):

            # calculate jump time here, since 100% corr between all traders
            jump = 0
            if ceil(t_jump) == d:
                # time of the jump is equal to today, jump occurs
                jump = 1
                # calculate next jump
                t_jump += random.expovariate(lambd = 1.0 / (days_per_year * 10))

            # simulate actions of each trader
            for n in range(n_traders):
                if len(traders) < n + 1:
                    # create new trader if there isn't one
                    starting_capital = a_capital * 1.0 / n_traders
                    traders.append(Trader(n, starting_capital))

                trader = traders[n]
                
                r_log_return = 0.0
                if jump:
                    # jump occurs
                    r_log_return = -0.33 * random.paretovariate(alpha = 1.5)
                else:
                    # no jump
                    r_log_return = random.gauss(mu = 0.0005, sigma = 0.04)

                # log trader info, and add to return
                trader.addLogReturn(d, r_log_return)

            # add to history
            day_profit = sum([t.current_capital for t in traders])
            day_log = sum([t.getTotLogReturn() for t in traders])
            day_arith = sum([t.getTotArithReturn() for t in traders])
            day_avg_profit = day_profit / n_traders
            day_avg_log = day_log / n_traders
            day_avg_arith = day_arith / n_traders
            
            history.append((d, day_profit, day_log, day_arith,
                            day_avg_profit, day_avg_log, day_avg_arith,
                            jump))

        # figure out bonus amount
        tot_return = sum([t.current_capital for t in traders]) - a_capital

        # figure bonus, if total_return - bonus <= 0, the company
        #   has made no money and I assume the manager won't get their bonus
        bonus = 0.01 * tot_return
        if tot_return <= 0:
            # if loss, no bonus recieved
            bonus = 0.0
        
        return (bonus, traders, history)
Esempio n. 18
0
 def getDuration(self):
     if self.flowDurationMode == "pareto":
         return random.paretovariate(1.02)
     elif self.flowDurationMode == "expo":
         return random.expovariate(0.02)
     else:
         dur = random.random()
         return 120 * dur
def pareto():
    PARETO_USAGE = 'Usage: ' + url_for('.pareto') + '?alpha=&lt;integer&gt;[k=&lt;integer&gt;&amp;test=true|false]'

    func = lambda args: random.paretovariate(alpha=float(args['alpha'])) + float(request.args.get('k'))

    alpha = request.args.get('alpha')

    return get_response(request, PARETO_USAGE, func, None, alpha=alpha)
Esempio n. 20
0
def sendhttp(iplist,a):
	ip = iplist[random.randint(0,len(iplist)-1)]
	page = int(random.paretovariate(a))
	print page
	url = "http://" + str(ip) + "/html/" +  str(page) +".html"
	c = pycurl.Curl()
	c.setopt(c.URL, url)
	c.perform()
Esempio n. 21
0
def main(script, *args):
    values = [random.expovariate(10) for i in range(1000)]
    pylab.subplot(2, 1, 1)
    plot_ccdf(values, 'linear', 'log')
    pylab.subplot(2, 1, 2)
    values = [random.paretovariate(1) for i in range(1000)]
    plot_ccdf(values, 'log', 'log')
    pylab.show()
Esempio n. 22
0
 def paretovariate_random(name: str, num_of_agents: int,
                          sign_multiple: float, alpha):
     import random
     values = [
         round(sign_multiple * abs(random.paretovariate(alpha)))
         for _ in range(num_of_agents)
     ]
     return AgentCategory(name, values)
Esempio n. 23
0
 def set_level(self, level):
     try:
         self.level = level
         if self.level == 'Random' or self.level == 'random':
             self.level = random.paretovariate(2)
             self.level = math.floor(self.level)
         self.level = int(self.level)
     except:
         self.level = -1
Esempio n. 24
0
 def simulate_once(self):
     total_loss = 0.0
     t = 0.0
     while t < 260:
         dt = random.expovariate(self.lamb)
         amount = self.xm * random.paretovariate(self.alpha)
         t += dt
         total_loss += amount
     return total_loss
def workload_generator():
    workload = []
    random.seed(RANDOM_SEED)
    for i in range(WORKLOAD_LENGTH):
        t = random.paretovariate(2)-1
        if t > 3:
            t = 3
        workload.append(int(t/3*100*1000))
    return workload
Esempio n. 26
0
 def next_vehicle(self):
     vehicle = Vehicle()
     vehicle.lane = self.lane
     vehicle.v0 = random.gauss(vehicle.v0, 4.)
     vehicle.th0 = vehicle.th0 + random.paretovariate(3.)
     vehicle.a = random.gauss(vehicle.a, 0.05)
     vehicle.b = random.gauss(vehicle.b, 0.05)
     vehicle.p = random.gauss(0.5, 0.3)
     return vehicle
Esempio n. 27
0
def workload_generator():
    workload = []
    random.seed(RANDOM_SEED)
    for i in range(WORKLOAD_LENGTH):
        t = random.paretovariate(2) - 1
        if t > 3:
            t = 3
        workload.append(int(t / 3 * 100 * 1000))
    return workload
Esempio n. 28
0
def pareto(low, high, alfa, n):
    for j in range(n):
        x1 = rd.paretovariate(alfa)
        if x1 > low and x1 < high:
            x.append(x1)
        else:
            j -= 1

    return x
Esempio n. 29
0
def respond(msg):
    for c in msg:
        print(c, end='', flush=True)
        if c == '\n':
            sleep(0.2)

        sleep((paretovariate(5) - 1) / 5)
    print('\n', flush=True)
    sleep(0.4)
Esempio n. 30
0
def sf_sequence(size,exponent,max_deg):
  '''
  Generate powerlaw sequence 
  Input: size, exponent, max degree
  '''
  seq=[random.paretovariate(exponent-1) for i in range(size)]
  #round to desired range
  dseq = [min(max_deg, max(int(round(s)),0)) for s in seq]
  return dseq
Esempio n. 31
0
 def get(self):
     if len(self.key) == 0:
         return None
     key = self.rb + 1
     while key > self.rb:
         key = random.paretovariate(pareto_const) - 1
     key = min(len(self.key), floor(len(self.key) * key / (self.rb - self.lb)))
     key = self.key[key]
     val = None if self.val is None else random.choice(self.val)
     return (key, val)
Esempio n. 32
0
def getRandomString(type_spec):
    alpha = 0.5  # 0.5 is the shape of the pareto distribution used to bias towards smaller strings
    len_min = 0
    len_max = 100
    if 'maxLength' in type_spec:
        len_min = type_spec['maxLength']
    if 'minLength' in type_spec:
        len_max = type_spec['minLength']
    str_len = min(len_min + int(random.paretovariate(alpha)) - 1, len_max)
    return ''.join(random.choice(string.lowercase) for i in xrange(str_len))
Esempio n. 33
0
    def __sample_pareto_dist(self, l, max=None):
        l = list(l)
        alpha = 1.16  # from the pareto principle, i.e. 80/20 rule
        bp = 5.0
        bucket_width = bp / len(l)

        # sample number, need to subtract 1 so that distro starts at zero.
        # pareto normally starts at one.
        num = random.paretovariate(alpha) - 1

        while max and max < num:
            num = random.paretovariate(alpha) - 1

        # find corresponding bucket
        bucket = math.floor(num / bucket_width)
        logging.debug(
            f"num={num}; bucket-width={bucket_width}; bucket={bucket}; node={l[bucket]}"
        )
        return l[bucket]
Esempio n. 34
0
def ParetovariateTest():
	results = []
	a=1
	xm=0.5
	for i in range(1000):
		results.append(random.paretovariate(a)*xm)
	cdf = Cdf.MakeCdfFromList(results)
	myplot.Clf()
	myplot.Cdf(cdf,complement=True,xscale = 'log',yscale = 'log')
	myplot.show()
Esempio n. 35
0
 def get(self):
     if len(self.key) == 0:
         return None
     key = self.rb + 1
     while key > self.rb:
         key = random.paretovariate(pareto_const) - 1
     key = min(len(self.key), floor(len(self.key) * key / (self.rb - self.lb)))
     key = self.key[key]
     val = None if self.val is None else random.choice(self.val)
     return (key, val)
Esempio n. 36
0
def genflow(hosts):
    flow = {}
    nodes = list(hosts)
    for src in nodes:
        bw = random.paretovariate(2.5)
        dst = random.choice(nodes)
        while src == dst:
            dst = random.choice(nodes)
        flow[(src, dst)] = bw
    return flow
Esempio n. 37
0
def scheduleDepartures(queue, time, FES, strategy):
    unassigned_users = [user for user in queue if not user.is_assigned]
    for i in range(min(cluster.freeServersNumber(), len(unassigned_users))):
        unassigned_users[-1 + i].is_assigned = True
        server = cluster.assignJob(strategy, time)
        #service_time = random.expovariate(SERVICE)
        service_time = random.paretovariate(SERVICE)  #MG1
        #service_time = 1 + random.uniform(0, SEVICE_TIME)
        # schedule when the client will finish the server
        FES.put((time + service_time, "departure_" + str(server.index)))
Esempio n. 38
0
def next_point(prev,ALPHA):
    angle = random.uniform(0,(2*math.pi))
#    angle = random.normalvariate(0,1.8)
    distance = 2 * random.paretovariate(ALPHA)/1100
#    distance = 2 * random.weibullvariate(1.0, 0.9)
    # cap distance at DMAX
#    if distance > DMAX:
#        distance = DMAX
    point = ((math.sin(angle) * distance)+prev[0], (math.cos(angle) * distance)+prev[1])
    return point
def apply_pareto(list):
    """
        Given a list length as a distribution size, determine the probabilty
        that each item in the list is called on using a pareto distribution.
    """
    distribution = np.array(
        [random.paretovariate(1.16) for x in range(0, len(list))])
    distribution /= np.sum(distribution)

    # return np.concatenate((np.array(list).reshape(-1,1), np.array(distribution).reshape(-1,1)),axis=1).tolist()
    return list, distribution.flatten().tolist()
Esempio n. 40
0
def pareto():
    PARETO_USAGE = 'Usage: ' + url_for(
        '.pareto'
    ) + '?alpha=&lt;integer&gt;[k=&lt;integer&gt;&amp;test=true|false]'

    func = lambda args: random.paretovariate(alpha=float(args['alpha'])
                                             ) + float(request.args.get('k'))

    alpha = request.args.get('alpha')

    return get_response(request, PARETO_USAGE, func, None, alpha=alpha)
Esempio n. 41
0
def paretovariate(alpha, xm):
    """Wrapper function around random.paretovariate that returns values from a
    two-parameter Pareto distribution.

    Arguments:
    alpha -- the shape parameter
    xm -- the minimum possible value of X (ie. "x sub m")
    """
    pareto_v = random.paretovariate(alpha)
    pareto_v = xm * pareto_v
    return pareto_v
Esempio n. 42
0
async def fill_data(conn):
    async with conn.begin():
        for name in random.sample(names, len(names)):
            uid = await conn.scalar(users.insert().values(
                name=name, birthday=gen_birthday()))
            emails_count = int(random.paretovariate(2))
            for num in random.sample(range(10000), emails_count):
                is_private = random.uniform(0, 1) < 0.8
                await conn.execute(emails.insert().values(
                    user_id=uid,
                    email='{}+{}@gmail.com'.format(name, num),
                    private=is_private))
Esempio n. 43
0
File: sa.py Progetto: aio-libs/aiopg
async def fill_data(conn):
    async with conn.begin():
        for name in random.sample(names, len(names)):
            uid = await conn.scalar(
                users.insert().values(name=name, birthday=gen_birthday()))
            emails_count = int(random.paretovariate(2))
            for num in random.sample(range(10000), emails_count):
                is_private = random.uniform(0, 1) < 0.8
                await conn.execute(emails.insert().values(
                    user_id=uid,
                    email='{}+{}@gmail.com'.format(name, num),
                    private=is_private))
Esempio n. 44
0
def testErrors(ntrials=1000,npts=100):
    results = [0] * ntrials
    for i in xrange(ntrials):
        s = 0   # sum of random points
        for j in xrange(npts):
            s += random.paretovariate(100)
        results[i] =s
    # plot results in a histogram
    pylab.hist(results,bins=50)
    pylab.title('Sum of 100 random points -- Triangular PDF (10,000 trials)')
    pylab.xlabel('Sum')
    pylab.ylabel('Number of trials')
Esempio n. 45
0
def powerlaw_sequence(n, gamma, avrdeg):
    """
    Generate power-law degree sequence by pareto distribution.

    :param int   n:      The number of nodes
    :param float gamma:  Exponent of distribution
    :param float avrdeg: Average degree
    :return: Degree distribution
    :rtype: list
    """
    return [random.paretovariate(gamma-1)*
            avrdeg*(gamma-2)/(gamma-1) for _ in range(n)]
Esempio n. 46
0
def ftp_downfile(ftp,a):
	filename = int(random.paretovariate(a))
	print filename
	filename = str(filename) + ".html"
	try:
		file_handler = open("down"+filename,'w') #以写模式在本地打开文件
		bufsize = 1024 
		ftp.retrbinary('RETR %s' % os.path.basename(filename),file_handler.write,bufsize)#接收服务器上文件并写入本地文件 
		file_handler.close() 
	except Exception,e:   
		print Exception,":",e 
		return	
Esempio n. 47
0
 def intParetoMean(alpha, precision, niter):
     s = 0.
     n = 0
     lastm = 0
     while True:
         for _ in xrange(niter):
             s += int(random.paretovariate(alpha))
             n += 1
         newm = s/n
         if abs(lastm-newm) < precision:
             return newm
         lastm = newm
Esempio n. 48
0
 def intParetoMean(alpha, precision, niter):
     s = 0.
     n = 0
     lastm = 0
     while True:
         for _ in range(niter):
             s += int(random.paretovariate(alpha))
             n += 1
         newm = s / n  # Float division
         if abs(lastm - newm) < precision:
             return newm
         lastm = newm
Esempio n. 49
0
File: rand.py Progetto: vzois/TopK
def create_file2(n, d, distr):
    global stats_only

    sample = []
    if distr == "g":
        sample = [lognormvariate(0, 1) for i in range(n)]
        m = max(sample)
        w = min(sample)
        print "m:", str(m), "w:", str(w)
        sample = [(v - w) / (m - w) for v in sample]
    elif distr == "z":
        sample = np.random.zipf(1.8, n)
        mx = float(max(sample))
        sample = [v / mx for v in sample]
        sample = sorted(sample, reverse=True)
    elif distr == "p":
        sample = [paretovariate(10) for i in range(n)]
        m = max(sample)
        w = min(sample)
        print "m:", str(m), "w:", str(w)
        sample = [(v - w) / (m - w) for v in sample]

    #print sorted(sample,reverse=True
    #print sample
    gather_stats(sample)
    if stats_only:
        print "No file written!!!"
        return
    else:
        if distr == "g":
            print "Creating file < logvariate > !!!"
        elif distr == "z":
            print "Creating file < zipf > !!!"
        elif distr == "p":
            print "Creating file < pareto > !!!"

    fname = "d_" + str(n) + "_" + str(d) + "_" + distr
    fp = open(fname, 'w')
    i = 0
    if distr == "z":
        while (i < n):
            fp.write(create_zipf_sample(sample, d, 0.1))
            i += 1
    elif distr == "g":
        while (i < n):
            fp.write(create_log_sample(sample, d, 0.1))
            i += 1
    elif distr == "p":
        while (i < n):
            fp.write(create_pareto_sample(sample, d, 0.1))
            i += 1

    fp.close()
Esempio n. 50
0
def fitPareto(cdf, minIncome=90000, n=5000, plot=True):
    values = sorted(x for x in cdf.Sample(n) if x >= minIncome)
    xMin = min(values)
    xMinLog = math.log(xMin)
    index = len(values) / sum(math.log(x) - xMinLog for x in values)
    print "x_{min} = %f; a = %f" % (xMin, index)

    pareto = Cdf.MakeCdfFromList([xMin * random.paretovariate(index) for _ in range(n)], "Pareto Fit")

    if plot:
        myplot.Cdfs([cdf, pareto], transform="pareto", show=True)

    return (xMin, index), pareto
Esempio n. 51
0
    def __init__(self, options={}):
        options['name'] = 'cell maze'
        super(CellMazeMap, self).__init__(options)
        self.players = options.get('players', max(2, min(10, int((betavariate(2.5, 3.0) * 10) + 1))))
        self.area = options.get('area', randrange(900 * self.players, min(25000, 5000 * self.players)))
        self.cell_width = options.get('cell_width', min(paretovariate(2), 7.0))
        self.cell_size = options.get('cell_size', min(paretovariate(2) + max(5.0 + self.cell_width, self.cell_width * 2), 20.0))
        self.openness = options.get('openness', betavariate(1.0, 3.0))
        self.aspect_ratio = options.get('aspect_ratio', None)
        self.grid = options.get('grid', None)
        self.maze_type = options.get('maze_type', choice(['prims','backtrack','growing']))
        self.v_sym = options.get('v_sym', None)
        self.v_step = options.get('v_step', None)
        self.h_sym = options.get('h_sym', None)
        self.h_step = options.get('h_step', None)
        self.hills = options.get('hills', None)
        self.grandularity = options.get('grandularity', 1)

        self.report('players {0}'.format(self.players))
        self.report('area {0}, {1} ({2:.1f}^2) per player'.format(self.area, self.area//self.players, sqrt(self.area/self.players)))
        self.report('cell width: {0}'.format(self.cell_width))
        self.report('cell size: {0}'.format(self.cell_size))
        self.report('openness: {0}'.format(self.openness))
        if self.grid is not None:
            self.report('grid: {0}'.format(self.grid))
        self.report('maze type {0}'.format(self.maze_type))
        if self.v_sym is not None:
            self.report('vertical symmetry: {0}'.format(self.v_sym))
        if self.v_step is not None:
            self.report('vertical shear step: {0}'.format(self.v_step))
        if self.h_sym is not None:
            self.report('horizontal symmetry: {0}'.format(self.h_sym))
        if self.h_step is not None:
            self.report('horizontal shear step: {0}'.format(self.h_step))
        if self.hills is not None:
            self.report('hills per player: {0}'.format(self.hills))
            
        self.min_hill_dist = 20
        self.max_hill_dist = 150
Esempio n. 52
0
def MakeFigure(xmin=100, alpha=1.7, mu=150, sigma=25):

    t1 = [xmin * random.paretovariate(alpha) for i in range(10000)]
    cdf1 = Cdf.MakeCdfFromList(t1, name='pareto')

    t2 = [random.normalvariate(mu, sigma) for i in range(10000)]
    cdf2 = Cdf.MakeCdfFromList(t2, name='normal')

    myplot.Cdfs([cdf1, cdf2],
                root='pareto_world2',
                title='Pareto World',
                xlabel='height (cm)',
                ylabel='CDF')
Esempio n. 53
0
def TallestPareto(iters=2, n=10000, xmin=100, alpha=1.7):
    """Find the tallest person in Pareto World.

    iters: how many samples to generate
    n: how many in each sample
    xmin: parameter of the Pareto distribution
    alpha: parameter of the Pareto distribution
    """
    tallest = 0
    for i in range(iters):
        t = [xmin * random.paretovariate(alpha) for i in range(n)]
        tallest = max(max(t), tallest)
    return tallest
Esempio n. 54
0
    def __init__(self, options={}):
        options['name'] = 'cell maze'
        super(CellMazeMap, self).__init__(options)
        self.players = options.get('players', max(2, min(10, int((betavariate(2.5, 3.0) * 10) + 1))))
        self.area = options.get('area', randrange(900 * self.players, min(25000, 5000 * self.players)))
        self.cell_width = options.get('cell_width', min(paretovariate(2), 7.0))
        self.cell_size = options.get('cell_size', min(paretovariate(2) + max(5.0 + self.cell_width, self.cell_width * 2), 20.0))
        self.openness = options.get('openness', betavariate(1.0, 3.0))
        self.aspect_ratio = options.get('aspect_ratio', None)
        self.grid = options.get('grid', None)
        self.maze_type = options.get('maze_type', choice(['prims','backtrack','growing']))
        self.v_sym = options.get('v_sym', None)
        self.v_step = options.get('v_step', None)
        self.h_sym = options.get('h_sym', None)
        self.h_step = options.get('h_step', None)
        self.hills = options.get('hills', None)
        self.grandularity = options.get('grandularity', 1)

        self.report('players {0}'.format(self.players))
        self.report('area {0}, {1} ({2:.1f}^2) per player'.format(self.area, self.area//self.players, sqrt(self.area/self.players)))
        self.report('cell width: {0}'.format(self.cell_width))
        self.report('cell size: {0}'.format(self.cell_size))
        self.report('openness: {0}'.format(self.openness))
        if self.grid is not None:
            self.report('grid: {0}'.format(self.grid))
        self.report('maze type {0}'.format(self.maze_type))
        if self.v_sym is not None:
            self.report('vertical symmetry: {0}'.format(self.v_sym))
        if self.v_step is not None:
            self.report('vertical shear step: {0}'.format(self.v_step))
        if self.h_sym is not None:
            self.report('horizontal symmetry: {0}'.format(self.h_sym))
        if self.h_step is not None:
            self.report('horizontal shear step: {0}'.format(self.h_step))
        if self.hills is not None:
            self.report('hills per player: {0}'.format(self.hills))
            
        self.min_hill_dist = 20
        self.max_hill_dist = 150
def TallestPareto(iters=2, n=10000, xmin=100, alpha=1.7):
    """Find the tallest person in Pareto World.

    iters: how many samples to generate
    n: how many in each sample
    xmin: parameter of the Pareto distribution
    alpha: parameter of the Pareto distribution
    """
    tallest = 0
    for i in range(iters):
        t = [xmin * random.paretovariate(alpha) for i in range(n)]
        tallest = max(max(t), tallest)
    return tallest
Esempio n. 56
0
   def grow(self, num_nodes):
       self.growing = True
       #keep taking stes to grows teh network using random joins until num_nodes are participating
       while len(self.nodes) < num_nodes:
           
           #some joins will occur
           for i in range(paretovariate(self.concurent_join_alpha)):
               n = Node(self.get_unique_id())
               hook = self.add_node(n) #also returns a hook for the node to join at
               n.join(hook)
 
        
           self.tick()
       self.growing = False
Esempio n. 57
0
    def sample_value(self, year: int = 0) -> float:
        """
        Sample a random value for the year

        Args:
            year: Year of sampling

        Returns:
            sampled value if year in active interval, 0 otherwise
        """
        if (year >= self.start_year and year <= self.end_year):
            return random.paretovariate(self.alpha)
        else:
            return 0.0
def network_construct(net_size, k_min, k_max, *arg):
    degree_distribution_type = arg[0]

    origin_net = nx.Graph()
    z = list()
    is_degree_sequence_valid = False

    if degree_distribution_type == "power law":
        sf_exponent = arg[1]
        while not is_degree_sequence_valid:
            z = list()
            while len(z) < net_size:
                newsample = round(random.paretovariate(sf_exponent - 1))
                if newsample <= k_max and newsample >= k_min:
                    z.extend([newsample])

            is_degree_sequence_valid = sum(z) % 2 == 0

        connected_test = False

        print("Got valid z")
        while not connected_test:
            origin_net = CM.configuration_model(z)
            connected_test = nx.is_connected(origin_net)
            print("Connected?:", connected_test)

    elif degree_distribution_type == "BA model":  # Barabasi-Albert model
        origin_net = nx.barabasi_albert_graph(net_size, m_links)

    elif degree_distribution_type == "Poisson":
        ave_degree = arg[1]
        while not is_degree_sequence_valid:
            z = list()
            while len(z) < net_size:
                newsample = round(numpy.random.poisson(ave_degree))
                if newsample <= k_max and newsample >= k_min:
                    z.extend([newsample])

            # is_degree_sequence_valid = nx.is_valid_degree_sequence(z)
            is_degree_sequence_valid = sum(z) % 2 == 0
        connected_test = False
        while not connected_test:
            origin_net = CM.configuration_model(z)
            connected_test = nx.is_connected(origin_net)

    # Remove parallel edges:
    origin_net = nx.Graph(origin_net)
    # Remove self loops:
    origin_net.remove_edges_from(nx.selfloop_edges(origin_net))
    return origin_net
Esempio n. 59
0
    def setOffTime(self, shape=1.0, scale=2.0, minTime=2.0, maxTime=3600.0):
        """Set the parameters of the OFF time distribution (Pareto dist.)

        Arguments:
          shape:Float -- Shape parameter of the Pareto distribution.
          scale:Float -- Scale parameter of the Pareto distribution.
          minTime:Float -- Minimum OFF time, in seconds.
          maxTime:Float -- Maximum OFF time, in seconds.
        Return value: None.
        """
        # Attention: python random uses scale==1, simply multiply with scale
        self._offTimeRNG = lambda : random.paretovariate(shape)*scale
        self._offTimeMin = minTime
        self._offTimeMax = maxTime
Esempio n. 60
0
def gen_bids(num_bidders, total_purchase_amount, median_valuation,
             std_deviation):
    bids = []
    for i in range(num_bidders):
        i = Bid(value=random.paretovariate(2),
                valuation=random.normalvariate(median_valuation,
                                               std_deviation))
        bids.append(i)
    # norm
    f = total_purchase_amount / sum(i.value for i in bids)
    bids = [Bid(b.value * f, b.valuation) for b in bids]
    bids.sort(key=attrgetter('valuation'), reverse=True)
    assert bids[0].valuation > bids[-1].valuation
    return bids