本文整理汇总了Python中random.betavariate函数的典型用法代码示例。如果您正苦于以下问题:Python betavariate函数的具体用法?Python betavariate怎么用?Python betavariate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了betavariate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: main
def main(args):
request_id = 0
fake = Faker()
fake.seed(0)
with open(filename, "w+") as f:
f.write("request id|client name|room type|request type|start date|end date|#adults|#children\n")
for i in range(0, number_of_lines):
request_id += 1
client_name = fake.name()
room_type = random.choice(data.rooms.keys())
request_type = random.choice(["wedding", "party", "conference"]) if "conference" in room_type else random.choice(["holiday", "business"])
start_date = data.random_date_between(datetime(2016, 1, 1).date(), datetime(2016, 3, 31))
end_date = start_date + timedelta(1 + int(random.gammavariate(2, 2)))
num_adults = max(1, int(random.betavariate(2, 5) * 10))
num_children = int(random.betavariate(1, 5) * 10)
if request_type == "conference":
num_adults = max(1, int(random.normalvariate(25, 9)))
num_children = 0
elif request_type == "wedding":
num_adults = max(2, int(random.normalvariate(25, 9)))
num_children = max(0, int(random.normalvariate(25, 12)))
elif request_type == "party":
num_adults = max(1, int(random.normalvariate(25, 9)))
num_children = max(0, int(random.normalvariate(25, 12)))
elif request_type == "business":
num_children /= 2
f.write("{}|{}|{}|{}|{}|{}|{}|{}\n".format(request_id, client_name,
room_type, request_type, start_date, end_date, num_adults,
num_children))
开发者ID:MOOCDataAnalysis,项目名称:datasets,代码行数:29,代码来源:generate_requests.py
示例2: valueAt
def valueAt(self, evaluationTime):
alpha = evaluateAt(self.alpha, evaluationTime)
beta = evaluateAt(self.beta, evaluationTime)
if self.rng.random() > 0.5:
return 1.0 - random.betavariate(alpha, beta)
else:
return random.betavariate(alpha, beta)
开发者ID:kunstmusik,项目名称:blue,代码行数:7,代码来源:rng.py
示例3: showLuckGraph
def showLuckGraph():
name = str(window.charList.currentText())
name2 = str(window.char2List.currentText())
data1 = []
data2 = []
for x in range (0,20):
char1Roll = 20*round(random.betavariate(dataFiles.Characters[name]['luck'],1),1)
char2Roll = 20*round(random.betavariate(dataFiles.Characters[name2]['luck'],1),1)
data1.append(char1Roll)
data2.append(char2Roll)
crits1 = []
crits2 = []
for i in data1:
if i == 20:
crits1.append(i)
for i in data2:
if i == 20:
crits2.append(i)
output = "CHAR1 CRITS: "+ str(len(crits1))+" FOR "+str(len(data1))+" ROLLS"
output += "\nCHAR 2CRITS: "+ str(len(crits2))+" FOR "+str(len(data2))+" ROLLS"
showOutput(output)
#pw = pg.plot(data, pen='r') # data can be a list of values or a numpy array
#pw.plot(data2,pen='b')
graphDialog.pGraph.clear()
graphDialog.pGraph.plot(data1, pen='r')
graphDialog.pGraph.plot(data2, pen='b')
log ("Luck graph plotted.")
开发者ID:ShadeAnimator,项目名称:GMHelper,代码行数:30,代码来源:GMH.py
示例4: populate
def populate(num_srs = 10, num_users = 1000, num_links = 100, num_comments = 20, num_votes = 50):
try:
a = Account._by_name(g.system_user)
except NotFound:
a = register(g.system_user, "password", "127.0.0.1")
srs = []
for i in range(num_srs):
name = "reddit_test%d" % i
try:
sr = Subreddit._new(name = name, title = "everything about #%d"%i,
ip = '0.0.0.0', author_id = a._id)
sr._downs = 10
sr.lang = "en"
sr._commit()
except SubredditExists:
sr = Subreddit._by_name(name)
srs.append(sr)
accounts = []
for i in range(num_users):
name_ext = ''.join([ random.choice(string.letters)
for x
in range(int(random.uniform(1, 10))) ])
name = 'test_' + name_ext
try:
a = register(name, name, "127.0.0.1")
except AccountExists:
a = Account._by_name(name)
accounts.append(a)
for i in range(num_links):
id = random.uniform(1,100)
title = url = 'http://google.com/?q=' + str(id)
user = random.choice(accounts)
sr = random.choice(srs)
l = Link._submit(title, url, user, sr, '127.0.0.1')
queries.new_link(l)
comments = [ None ]
for i in range(int(random.betavariate(2, 8) * 5 * num_comments)):
user = random.choice(accounts)
body = ' '.join([ random_word(1, 10)
for x
in range(int(200 * random.betavariate(2, 6))) ])
parent = random.choice(comments)
(c, inbox_rel) = Comment._new(user, l, parent, body, '127.0.0.1')
queries.new_comment(c, inbox_rel)
comments.append(c)
for i in range(int(random.betavariate(2, 8) * 10)):
another_user = random.choice(accounts)
queries.queue_vote(another_user, c, True, '127.0.0.1')
like = random.randint(50,100)
for i in range(int(random.betavariate(2, 8) * 5 * num_votes)):
user = random.choice(accounts)
queries.queue_vote(user, l, random.randint(0, 100) <= like, '127.0.0.1')
queries.worker.join()
开发者ID:Robert77168,项目名称:reddit,代码行数:59,代码来源:populatedb.py
示例5: __init__
def __init__(self,parents=None,separators=None,vision=None,memory=None,responses=None,heuristics=None):
self.parents=parents
self.generation = 0
if self.parents != None:
self.generation = parents.generation + 1
self.living_instantiations =0 #add one for each born with this genome subtract for each death
self.instantiations =0 #add one for each born with this genome DO NOT subtract for each death
if vision==None:
self.vision = abs(int(random.gauss(0,2)))
else:
self.vision = vision
if memory==None:
self.memory = abs(int(random.gauss(0,2)))
else:
self.memory = memory
if separators==None:
num_separators = abs(int(random.gauss(0,1)))+1
self.separators = []
#TODO Problem A
for i in range(num_separators):
self.separators = self.separators + [random_sep()]
self.separators.sort()
else:
self.separators=separators
if (responses==None):
if (self.memory != 0 and num_separators > 0):
num_responses = int(1/random.betavariate(2,1))-1
self.responses = []
for i in range(num_responses):
#TODO ensure that there are no responses to
# the same coordinates
# or to empty coordinates
num_coordinates = random.choice(range(self.memory*self.vision+2)[1:])
coords = tuple(random_configuration(self.vision,self.memory,self.separators) for i in range(num_coordinates))
agent_action = random_action()
if len(coords)>0:
self.responses.append((coords,agent_action))
else:
self.responses = []
else:
self.responses= responses
if heuristics==None:
self.heuristics=[]
num_heuristics = int(1/random.betavariate(2,1))
for i in range(num_heuristics):
agent_action = random_action()
self.heuristics.append(agent_action)
if num_heuristics == 0:
self.heuristics.append(random_action())
else:
self.heuristics= heuristics
assert len(self.heuristics)>0,pdb.set_trace()
self.responses, self.heuristics = prune(self.responses,self.heuristics,self.vision,self.memory,self.separators)
self.complexity = self.complexity_estimate()
#assign the minimum fitness of parents
self.fitness =0
self.reproductions = 0
开发者ID:rjunior911,项目名称:ALifePhilComp,代码行数:58,代码来源:genetics.py
示例6: die
def die(self,aArea,vPInParameters,vPMoveParameters,aPDie):
# Remove the mosquito from the target
if self.inside == 1:
self.target.removeInsideMosquito(self)
else:
self.target.removeOutsideMosquito(self)
# Select a random target for the mosquito and create it
# Get PIn parameters
cPInHeterogeneityIndicator = vPInParameters[0]
cPInMaleAll = vPInParameters[1]
cPInMaleBetaA = vPInParameters[2]
cPInMaleBetaB = vPInParameters[3]
cPInFemaleAll = vPInParameters[4]
cPInFemaleBetaA = vPInParameters[5]
cPInFemaleBetaB = vPInParameters[6]
# Get the PMove parameters
cPMoveHeterogeneityIndicator = vPMoveParameters[0]
cPMoveMaleAll = vPMoveParameters[1]
cPMoveMaleBetaA = vPMoveParameters[2]
cPMoveMaleBetaB = vPMoveParameters[3]
cPMoveFemaleAll = vPMoveParameters[4]
cPMoveFemaleBetaA = vPMoveParameters[5]
cPMoveFemaleBetaB = vPMoveParameters[6]
if self.getSex()=="male":
vTargets = aArea.getSwarmList()
if cPInHeterogeneityIndicator == 0:
aPIn = cPInMaleAll
else:
aPIn = random.betavariate(cPInMaleBetaA,cPInMaleBetaB)
if cPMoveHeterogeneityIndicator == 0:
aPMove = cPMoveMaleAll
else:
aPMove = random.betavariate(cPMoveMaleBetaA,cPMoveMaleBetaB)
else:
vTargets = aArea.getHouseList()
if cPInHeterogeneityIndicator == 0:
aPIn = cPInFemaleAll
else:
aPIn = random.betavariate(cPInFemaleBetaA,cPInFemaleBetaB)
if cPMoveHeterogeneityIndicator == 0:
aPMove = cPMoveFemaleAll
else:
aPMove = random.betavariate(cPMoveFemaleBetaA,cPMoveFemaleBetaB)
CRandIndex = random.randint(0,len(vTargets)-1)
aMosquito = mosquito(vTargets[CRandIndex],self.getSex(),aPIn,aPMove,aPDie)
# Move new mosquito inside with probability
cRandIn = random.random()
if cRandIn < aPIn:
aMosquito.moveInside()
开发者ID:ben18785,项目名称:malaria-captureMonteCarlo,代码行数:54,代码来源:basic.py
示例7: inversion
def inversion(self):
''' simulate twin-priming inversion, return header note, seq '''
offset = int(.3*len(self.dna)*betavariate(1.5,2))
inv_pt = len(self.dna) - offset # inversion point
t_start = int((len(self.dna)-offset)*betavariate(4,1)) # start relative to insertion ref
delta = int(uniform(-10,10)) # internal dup/del
note = 'trunc_start=%d,inv_loc=%d,inv_slop=%d,ins_len=%d' % (t_start, inv_pt, delta, len(self.dna))
end5p = self.dna[t_start:inv_pt]
end3p = self.dna[inv_pt-delta:len(self.dna)]
return note, rc(end5p) + end3p
开发者ID:adamewing,项目名称:tebreak,代码行数:13,代码来源:simulate_insref.py
示例8: getTrueValue_beta
def getTrueValue_beta(true_value_set, multiplier):
# to pick the true value using a beta distribution
# Attention!! processing in this way the beta, it tends to be a exponential curve ---_> we named it EXP distribution
rndm_nb = int(random.betavariate(1,2) * multiplier)
value_index = int (((rndm_nb * len(true_value_set))) / multiplier)
#in this way every index is ok. it works when true value set len is < 100 or multiplier
while value_index < 0 or value_index >= len(true_value_set):
rndm_nb = int(random.betavariate(1,2) * multiplier)
value_index = int (((rndm_nb * len(true_value_set))) / multiplier)
value = true_value_set[value_index]
#do not remove it, it could be choosen again
return value
开发者ID:valentinaberetta,项目名称:TDO,代码行数:13,代码来源:Main_dataset_generation.py
示例9: generate_user_file
def generate_user_file(
limit, artists_per_user_limit=100, artist_id_limit=1000000):
"""
generates files like
4587|547:1|6984:0.98|147856:0.05
uid|artist_id:score|artist_id:score
"""
with open(user_file, 'w+') as f:
for i in range(limit):
line = [str(i)]
nb_artists = int(betavariate(2, 2) * artists_per_user_limit)
for _ in range(nb_artists):
line.append(str(int(
betavariate(2, 5) * artist_id_limit)) + ':' + str(random()))
f.write('|'.join(line) + '\n')
开发者ID:lboudard,项目名称:simple_search,代码行数:15,代码来源:generate_fixtures.py
示例10: sampleMixture
def sampleMixture(self):
"""Once solve has been called and a distribution over models determined
this allows you to draw a specific model. Returns a 2-tuple, where the
first entry is an array of weights and the second entry a list of Gaussian
distributions - they line up, to give a specific Gaussian mixture model. For
density estimation the probability of a specific point is then the sum of each
weight multiplied by the probability of it comming from the associated Gaussian.
For clustering the probability of a specific point belonging to a cluster is
the weight multiplied by the probability of it comming from a specific Gaussian,
normalised for all clusters. Note that this includes an additional term to cover
the infinite number of terms that follow, which is really an approximation, but
tends to be such a small amount as to not matter. Be warned that if doing clustering
a point could be assigned to this 'null cluster', indicating that the model thinks the
point belongs to an unknown cluster (i.e. one that it doesn't have enough information,
or possibly sticks, to instanciate.)."""
weight = numpy.empty(self.stickCap+1, dtype=numpy.float64)
stick = 1.0
for i in xrange(self.stickCap):
val = random.betavariate(self.v[i,0], self.v[i,1])
weight[i] = stick * val
stick *= 1.0 - val
weight[-1] = stick
gauss = map(lambda x: x.sample(), self.n)
gauss.append(self.prior.sample())
return (weight,gauss)
开发者ID:hjanime,项目名称:CSI,代码行数:27,代码来源:dpgmm.py
示例11: get_random_date
def get_random_date():
# http://www.wolframalpha.com/input/?i=beta+distribution%2C+alpha%3D1.5%2C+beta%3D5
random_year = date.today().year - int(MAX_YEARS_BACK * random.betavariate(1.1, 7))
start_date = date(random_year, 1, 1).toordinal()
end_date = date(random_year, 12, 31).toordinal()
return date.fromordinal(random.randint(start_date, end_date))
开发者ID:numegil,项目名称:dotfiles,代码行数:7,代码来源:day_of_week.py
示例12: generateBetaRVs
def generateBetaRVs(alpha, beta, count, histDelta):
rVec = numpy.zeros(count)
rMax = 0.
for ii in range(count):
rVec[ii] = random.betavariate(alpha, beta)
if (rMax < rVec[ii]):
rMax = rVec[ii]
# build the histogram ...
deltaR = histDelta
rMinHist = 0.
rMaxHist = rMax + 2. * deltaR
numBins = (rMaxHist - rMinHist) / deltaR
numBins = int(numBins) + 2
rHist = numpy.zeros(numBins)
print ' making histogram ... ', deltaR, rMaxHist
for ii in range(count):
iBin = int((rVec[ii] - rMinHist) / deltaR + 0.0001)
rHist[iBin] += 1
for iBin in range(numBins):
rHist[iBin] /= float(count)
return (rVec, rHist)
开发者ID:cancerregulome,项目名称:gidget,代码行数:27,代码来源:miscMath.py
示例13: _beta_distrib
def _beta_distrib(self):
"""
Define a pseudorandom size according to a beta distribution giving alpha and beta,
comprise between sonic_min and sonic_max
@return A size of the fragment (int)
"""
return int(betavariate(self.alpha, self.beta) * (self.sonic_max - self.sonic_min) + self.sonic_min)
开发者ID:a-slide,项目名称:Isis,代码行数:7,代码来源:SlicePicker.py
示例14: _decorator
def _decorator(citation_id):
t = random.betavariate(cfg.SLEEP_ALPHA, cfg.SLEEP_BETA) \
* (cfg.SLEEP_TIME_RANGE[1] - cfg.SLEEP_TIME_RANGE[0]) + cfg.SLEEP_TIME_RANGE[0]
time.sleep(t)
text = func(citation_id)
# time.sleep(random.uniform(cfg.SLEEP_TIME_RANGE[0], cfg.SLEEP_TIME_RANGE[1]))
return text
开发者ID:czxxjtu,项目名称:acm-citation-crawler,代码行数:7,代码来源:crawler.py
示例15: thompson_sampling
def thompson_sampling(p,numSamples):
###########################################################################
# Thompason Sampling Algorthm
#
# a = # numbers of successes of each variant
# b = # numbers of failures of each variant
# Initialize priors with ignorant state of Beta(1,1) (Uniform distribution)
#
a = np.ones( np.size(p) )
b = np.ones( np.size(p) )
# draw from beta distribution for each variant
for i in range(numSamples):
draw = np.zeros( np.size(p) )
for i in range( np.size(a) ):
draw[i] = random.betavariate(a[i],b[i])
# Select the variant with the largest numbers drawn from the beta distribution
selected_arm = np.amax(draw) == draw
# Test and observe the result of the selcted arm
U = random.random()
success = U < p[selected_arm]
failure = U > p[selected_arm]
# Update prior beta distribution for selected arm
a[selected_arm] = a[selected_arm] + success
b[selected_arm] = b[selected_arm] + failure
return a, b
开发者ID:robertdavidwest,项目名称:thompson_sampling,代码行数:30,代码来源:thompson_sampling.py
示例16: psa
def psa(parameters, parnames, predictions, prednames, ss):
with open(os.path.join(rootDir, 'output', 'PSA_' + SA_id + '_wide.txt'), 'wb') as outfile_wide,\
open(os.path.join(rootDir, 'output', 'PSA_' + SA_id + '_long.txt'), 'wb') as outfile_long:
wide_writer = csv.writer(outfile_wide, delimiter='\t')
wide_writer.writerow(parnames + prednames)
long_writer = csv.writer(outfile_long, delimiter='\t')
long_writer.writerow(['parname', 'parvalue', 'outcome', 'value'])
for sample in range(n_samples):
parvalues = []
for param in parameters:
if not param['distribution']:
continue
distribution = param['distribution'].split(':')
if distribution[0] == 'triangular':
value = random.triangular(float(distribution[1]), float(distribution[2]), float(distribution[3]))
elif distribution[0] == 'uniform':
value = random.uniform(float(distribution[1]), float(distribution[2]))
elif distribution[0] == 'integer':
value = random.randint(float(distribution[1]), float(distribution[2]))
elif distribution[0] == 'beta':
value = random.betavariate(float(distribution[1]), float(distribution[2]))
else:
# this is a constant, just use mode
value = float(param['mode'])
parvalues.append(value)
param_sheet = ss.Sheets(param['sheet'])
set_param_values(param, param_sheet, value)
predvalues = []
for pred, predname in zip(predictions, prednames):
shOut = ss.Sheets(pred['sheet'])
value = shOut.Cells(pred['row'], pred['col']).Value
predvalues.append(value)
for paramvalue, parname in zip(parvalues, parnames):
long_writer.writerow([parname, paramvalue, predname, value])
wide_writer.writerow(parvalues + predvalues)
开发者ID:SwissTPH,项目名称:XLSA,代码行数:35,代码来源:XLSA.py
示例17: __init__
def __init__(self, n_ants, n_sites, search_prob, quorum_size, site_qual, test = False):
self.n_ants = n_ants
self.site_quals = [None]*n_sites
for site in range(n_sites):
if site_qual == 'random':
self.site_quals[site] = random.betavariate(1,1)
else:
assert site_qual > 0 and site_qual < 1
self.site_quals[site] = site_qual
self.n_sites = len(self.site_quals)
self.search_prob = search_prob
self.ants = [[AT_HOME, None] for i in range(self.n_ants)]
self.at_home = dict(zip(range(self.n_ants), self.n_ants*[True]))
self.at_site = [0]*self.n_sites
self.know_site = [0]*self.n_sites
self.quorum_size = quorum_size
self.going_home = {}
self.going_to_site = {}
self.quorum_times = {}
self.test = test
开发者ID:pkrafft,项目名称:house-hunting,代码行数:26,代码来源:simulate.py
示例18: _arm_guess
def _arm_guess(self, participant_count, completed_count):
fairness_score = 7
a = max([participant_count, 0])
b = max([participant_count - completed_count, 0])
return random.betavariate(a + fairness_score, b + fairness_score)
开发者ID:rnoldo,项目名称:sixpack,代码行数:7,代码来源:models.py
示例19: simulate
def simulate(n, alpha, iterations):
SUM=0
for j in alpha:
SUM+=j
l=len(alpha)
avgValues = list()
for i in range(0, l):
avgValues.append(0)
for i in range(iterations):
alphaSum=SUM
variates=list()
for j in range(l-1):
variates.append(random.betavariate(alpha[j], alphaSum-alpha[j]))
alphaSum-=alpha[j]
#print(variates) // uncomment this to print variates.
prod=1
sample = list()
for j in range(l-1):
sample.append(variates[j]*prod)
avgValues[j]+=variates[j]*prod
prod*=(1-variates[j])
avgValues[l-1]+=(1-sum(sample)) #the order is important here...
sample.append(1-sum(sample))
for i in range(0,l):
avgValues[i]/=iterations
print(avgValues)
开发者ID:jayantgupta,项目名称:topic-models,代码行数:26,代码来源:stick.py
示例20: random
def random():
names = RACES
colours = COLOURS
languages = LANGUAGES
origins = Origins()
# Returns a beta random rumber, closer to 1 than len(RACES). This allows a random number of different origins.
number_of_ethnicities = int(random.betavariate(2, 3) * len(names)) + 1
ethnicities = random.sample(names, number_of_ethnicities)
for i, this_ethnicity in enumerate(ethnicities):
others = names.copy()
others.remove(this_ethnicity)
liked_ethnicities = random.sample(others, number_of_ethnicities-1)
hated_ethnicities = random.sample(others, number_of_ethnicities-1)
eth = Ethnicity(this_ethnicity, colours[i], languages[i], liked_ethnicities, hated_ethnicities)
origins[eth] = random.uniform(0, 1)
total_weight = sum(o[1] for o in origins.items())
for key in origins.keys():
origins[key] /= total_weight
return origins
开发者ID:hypeserver,项目名称:ajan,代码行数:27,代码来源:agent.py
注:本文中的random.betavariate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论