本文整理汇总了Python中random.betavariate函数的典型用法代码示例。如果您正苦于以下问题:Python betavariate函数的具体用法?Python betavariate怎么用?Python betavariate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了betavariate函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的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))
示例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)
示例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.")
示例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()
示例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
示例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()
示例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
示例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
示例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')
示例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)
示例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))
示例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)
示例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)
示例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
示例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