本文整理汇总了Python中random.gammavariate函数的典型用法代码示例。如果您正苦于以下问题:Python gammavariate函数的具体用法?Python gammavariate怎么用?Python gammavariate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了gammavariate函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: sample
def sample(self, scale=1):
csample = [random.gammavariate(a, 1) for a in self.alphas]
for aidx, (sampprob, alpha) in enumerate(zip(csample, self.alphas)):
while sampprob == 0:
sampprob = random.gammavariate(alpha, 1)
csample[aidx] = sampprob
return scale * scipy.array(csample) / sum(csample)
示例2: createPatches
def createPatches(self,vCovarianceParams,aBreedGamma,bBreedGamma,aFeedGamma,bFeedGamma,aInitialPopulation,aSize):
cNumPatches = np.random.poisson(vCovarianceParams[3])
vPatches = []
for i in range(0,cNumPatches):
cNumBreedRand = random.gammavariate(aBreedGamma,bBreedGamma)
cNumFeedRand = random.gammavariate(aFeedGamma,bFeedGamma)
vPatches.append(self.addPatch(vCovarianceParams,cNumBreedRand,cNumFeedRand,mosquitoGroup(aInitialPopulation,aInitialPopulation,0,0,0,0,0,0,0,0),aSize))
return vPatches
示例3: generate_raw_data
def generate_raw_data(gene_ids, path):
"""Generate random DE data."""
de_data = {}
header = ['test_id', 'gene_id', 'gene', 'locus', 'sample_1',
'sample_2', 'status', 'value_1', 'value_2',
'log2(fold_change)', 'test_stat', 'p_value', 'q_value',
'significant']
with gzip.open(gene_ids, mode='rt') as gene_ids:
all_genes = [line.strip() for line in gene_ids]
n_of_genes = len(all_genes)
de_data['test_id'] = all_genes
de_data['gene_id'] = all_genes
de_data['gene'] = all_genes
de_data['locus'] = ['chr20:463337-524482'] * n_of_genes
de_data['sample_1'] = ['control'] * n_of_genes
de_data['sample_2'] = ['case'] * n_of_genes
de_data['status'] = ['OK'] * n_of_genes
de_data['value_1'] = [random.gammavariate(1, 100) for _ in all_genes]
de_data['value_2'] = [random.gammavariate(1, 100) for _ in all_genes]
de_data['log2(fold_change)'] = [random.uniform(-10, 10) for _ in all_genes]
de_data['test_stat'] = [random.uniform(-3, 3) for _ in all_genes]
de_data['p_value'] = [random.uniform(0, 1) for _ in all_genes]
de_data['q_value'] = [random.uniform(0, 1) for _ in all_genes]
de_data['significant'] = [random.choice(['yes', 'no']) for _ in all_genes]
rows = zip(de_data['test_id'], de_data['gene_id'], de_data['gene'],
de_data['locus'], de_data['sample_1'], de_data['sample_2'],
de_data['status'], de_data['value_1'], de_data['value_2'],
de_data['log2(fold_change)'], de_data['test_stat'],
de_data['p_value'], de_data['q_value'], de_data['significant'])
with gzip.open(os.path.join(path, 'de_raw.tab.gz'), 'wt') as raw_df:
writer = csv.writer(raw_df, delimiter=str('\t'), lineterminator='\n')
writer.writerow(header)
for row in rows:
writer.writerow(row)
with open(os.path.join(path, 'de_json.json'), 'w') as json_file:
de_data_std = {
'stat': de_data['test_stat'],
'logfc': de_data['log2(fold_change)'],
'pvalue': de_data['p_value'],
'fdr': de_data['q_value'],
'gene_id': de_data['gene_id']
}
json.dump(de_data_std, json_file, indent=4, sort_keys=True)
rows = zip(de_data_std['gene_id'], de_data_std['logfc'], de_data_std['fdr'],
de_data_std['pvalue'], de_data_std['stat'])
with gzip.open(os.path.join(path, 'de_file.tab.gz'), 'wt') as de_file:
writer = csv.writer(de_file, delimiter=str('\t'), lineterminator='\n')
writer.writerow(['gene_id', 'logfc', 'fdr', 'pvalue', 'stat'])
for row in rows:
writer.writerow(row)
示例4: createInputs
def createInputs(filename, N, S, dS, B, dB):
# create input file for blimit.py
out = open(filename, 'w')
out.write('#----------------------------------------------------------\n')
out.write('# Format:\n')
out.write('# M number of bins\n')
out.write('# N1 N2 ...\n')
out.write('# K number of sampled points\n')
out.write('# S1 S2 ...\n')
out.write('# B1 B2 ...\n')
out.write('# : :\n')
out.write('# The item is the number of bins. This is followed\n')
out.write('# by the observed counts, the signal counts, then\n')
out.write('# the background counts\n')
out.write('#\n')
out.write('# In order to account for uncertainties whatever their origin\n')
out.write('# repeat the last pair of lines with different random samplings\n')
out.write('# of signal and background counts.\n')
out.write('#----------------------------------------------------------\n')
out.write('# number of bins\n')
out.write('\t1\n')
out.write('# observed counts\n')
out.write('\t%d\n' % int(N))
if dS == 0 and dB == 0:
out.write('# number of points\n')
out.write('\t1\n')
out.write('# signals or effective luminosities (eff x Lumi)\n')
out.write('\t%10.4e\n' % S)
out.write('# backgrounds\n')
out.write('\t%10.4e\n' % B)
else:
ntrial = 400
gamma_S, beta_S = computeGammaConstants(S, dS)
gamma_B, beta_B = computeGammaConstants(B, dB)
out.write('# number of sampled points\n')
out.write('\t%d\n' % ntrial)
for ii in xrange(ntrial):
jj = ii+1
if dS > 0:
sig = gammavariate(gamma_S, beta_S)
else:
sig = 0.0
out.write('# %4d signal\n' % jj)
out.write('\t%10.3f\n' % sig)
if dB > 0:
bkg = gammavariate(gamma_B, beta_B)
else:
bkg = 0.0
out.write('# %4d background\n' % jj)
out.write('\t%10.3f\n' % bkg)
out.close()
示例5: __init__
def __init__(self,anumPatches,aSize,aInitialPopulation,aBreedGamma,bBreedGamma,aFeedGamma,bFeedGamma,vCovarianceParams):
self.vPatches = []
if vCovarianceParams[0] == 0:
for i in range(0,anumPatches):
cNumBreedRand = random.gammavariate(aBreedGamma,bBreedGamma)
cNumFeedRand = random.gammavariate(aFeedGamma,bFeedGamma)
self.vPatches.append(patch(randomLocation(aSize),cNumBreedRand,cNumFeedRand,mosquitoGroup(aInitialPopulation,aInitialPopulation,0,0,0,0,0,0,0,0)))
self.numPatches = anumPatches
else:
self.vPatches = randomCovariancePatches(aSize,vCovarianceParams,aBreedGamma,bBreedGamma,aFeedGamma,bFeedGamma,aInitialPopulation)
self.numPatches = len(self.vPatches)
self.Size = aSize
示例6: generateHits
def generateHits(thread, signal, pulse, eventType):
if eventType != 'trues' and eventType != 'dark':
return
# skip those with 0 rate (disable)
if _conf['eventRate'][eventType] == 0:
return
channel = thread.status.getChannel()
fileName = _conf['directory'] + _conf['filename'][eventType].format(channel=int(channel))
if _conf['enableSaving']:
f = file(fileName, 'w')
t = float(0)
while True:
saveThisEvent = True
t_wait = random.gammavariate(1.0, 1/_conf['eventRate'][eventType])
progress = int(round(t / _runTime * 100))
if progress > thread.status.getProgress():
thread.status.setProgress(progress)
time.sleep(0.001) # give the output some time to print
# time of the next event
t_next = t + t_wait
if t_next > _runTime:
break
# generate pulse (maximum at 5 fC (=MIP))
if eventType == 'trues':
fC = random.gammavariate(_conf['chargeDistAlpha'], _conf['chargeDistBeta'])
t_thr, length = pulse.addEvent(signal, fC, t_next)
if fC < 2:
saveThisEvent = False
else:
fC = 0.01; # calculated integral, done with WolframAlpha (http://wolfr.am/1jJtxac)
t_thr, length = addDarkPulse(signal, t_next)
# write to file
if _conf['enableSaving'] and saveThisEvent:
f.write("{0:.12f} {1:06.3f}\n".format(t_thr, fC))
# time for the next event
if length > t_wait:
t += length # fix pile-up
t += t_wait
if _conf['enableSaving']:
f.close()
示例7: getCvalue
def getCvalue(self, hyperparameters):
#The c value used to compute myopic-VPI. See Dearden et al. 1998.
#a gamma distribution with one parameter corresponds to gamma(a,1)
mu = hyperparameters[0];
lambdu = hyperparameters[1];
alpha = hyperparameters[2];
beta = hyperparameters[3];
num1 = (alpha * random.gammavariate(alpha+0.5, 1) * math.sqrt(beta));
denom1 = ((alpha-0.5)*random.gammavariate(alpha,1)*random.gammavariate(0.5,1)*alpha*math.sqrt(2*lambdu));
prod1 = (1.0 + mu**2/(2*alpha));
pow1 = -1.0 * alpha+0.5;
c = (num1/denom1) * prod1**pow1;
return c;
示例8: WstawStatki
def WstawStatki(self, N):
for n in range(N):
statek = Statek(1 / 2 * WIDTH_GAME, 0)
x = random.uniform(30 + statek.NW.x(), WIDTH_GAME - statek.NE.x() - 40)
y = random.gammavariate(1,1)
statek.UstawPozycje(x,y)
self.lista_enemy.append(statek)
示例9: WstawBalony
def WstawBalony(self, N):
for n in range(N):
balon = Balon(0, 0)
x = random.uniform(0 + balon.NW.x(), WIDTH_GAME - balon.NE.x())
y = random.gammavariate(1,1)
balon.UstawPozycje(x,y)
self.lista_enemy.append(balon)
示例10: generateGammaRVs
def generateGammaRVs(aShape, bScale, count, histDelta):
rVec = numpy.zeros(count)
rMax = 0.
for ii in range(count):
rVec[ii] = random.gammavariate(aShape, bScale)
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)
示例11: 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))
示例12: Dirichlet
def Dirichlet(n=1000, alphas=[1,1,1]):
''' Generate a Dirichlet Distribution;
Default: #points is 1000;
plot 3-dim space;
2-dim simplex with uniform distribution;
'''
dim = len(alphas)
samples = np.array([([None] * dim) for row in xrange(n)])
for i in range(n):
for j in range(dim):
alpha = alphas[j]
samples[i, j] = random.gammavariate(alpha, 1)
samples[i, :] = samples[i, :]/sum(samples[i, :])
if dim==3:
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
ax.scatter(samples[:, 0], samples[:, 1] , samples[:, 2])
plt.show()
return samples
示例13: WstawStacje
def WstawStacje(self, N):
for n in range(N):
stacja = Stacja(0, 0)
x = random.uniform(0 + stacja.NW.x(), WIDTH_GAME - stacja.NE.x())
y = random.gammavariate(1,1)
stacja.UstawPozycje(x,y)
self.lista_friend.append(stacja)
示例14: WstawMysliwce
def WstawMysliwce(self, N):
for n in range(N):
mysliwiec = Mysliwiec(0, 0)
x = random.uniform(0 + mysliwiec.NW.x(), WIDTH_GAME - mysliwiec.NE.x())
y = random.gammavariate(1,1)
mysliwiec.UstawPozycje(x,y)
self.lista_enemy.append(mysliwiec)
示例15: tally
def tally(candidates, vote_counts, nballots):
ncandidates = len(candidates)
gvariates = [gammavariate(1 + vote_counts[i], 1) for i in xrange(ncandidates)]
gvsum = float(sum(gvariates))
result = tuple(vote_counts[i] + (nballots - sum(vote_counts)) \
* gvariates[i] / gvsum for i in xrange(ncandidates))
return result.index(max(result))