本文整理汇总了Python中random.gammavariate函数的典型用法代码示例。如果您正苦于以下问题:Python gammavariate函数的具体用法?Python gammavariate怎么用?Python gammavariate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了gammavariate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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)
开发者ID:coventry,项目名称:snppns,代码行数:7,代码来源:Dirichlet.py
示例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
开发者ID:ben18785,项目名称:malaria-metapopulations,代码行数:8,代码来源:classes.py
示例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)
开发者ID:hadalin,项目名称:resolwe-bio,代码行数:56,代码来源:generate_diffexpr_cuffdiff.py
示例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()
开发者ID:hbprosper,项目名称:limits,代码行数:53,代码来源:example1.py
示例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
开发者ID:ben18785,项目名称:malaria-metapopulations,代码行数:13,代码来源:classes.py
示例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()
开发者ID:Nepomuk,项目名称:ASIC_generator,代码行数:50,代码来源:generate_asic_data.py
示例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;
开发者ID:sgriffith7,项目名称:IML,代码行数:15,代码来源:BayesianQLearning.py
示例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)
开发者ID:gargass,项目名称:River_Raid,代码行数:7,代码来源:game.py
示例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)
开发者ID:gargass,项目名称:River_Raid,代码行数:7,代码来源:game.py
示例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)
开发者ID:cancerregulome,项目名称:gidget,代码行数:27,代码来源:miscMath.py
示例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))
开发者ID:MOOCDataAnalysis,项目名称:datasets,代码行数:29,代码来源:generate_requests.py
示例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
开发者ID:akbari59,项目名称:python-ml,代码行数:25,代码来源:dirichlet_distribution.py
示例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)
开发者ID:gargass,项目名称:River_Raid,代码行数:7,代码来源:game.py
示例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)
开发者ID:gargass,项目名称:River_Raid,代码行数:7,代码来源:game.py
示例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))
开发者ID:berjc,项目名称:election-engine,代码行数:7,代码来源:bayes.py
示例16: sample_parameters_given_hyper
def sample_parameters_given_hyper(self, gen_seed=0):
"""
Samples a Gaussian parameter given the current hyperparameters.
Inputs:
gen_seed: integer used to seed the rng
"""
if type(gen_seed) is not int:
raise TypeError("gen_seed should be an int")
random.seed(gen_seed)
hypers = self.get_hypers()
s = hypers['s']
r = hypers['r']
nu = hypers['nu']
m = hypers['mu']
rho = random.gammavariate(nu/2.0, s)
mu = random.normalvariate(m, (r/rho)**.5)
assert(rho > 0)
params = {'mu': mu, 'rho': rho}
return params
开发者ID:campustimes,项目名称:crosscat,代码行数:25,代码来源:ContinuousComponentModel.py
示例17: pux_sampling
def pux_sampling(x, A, C, invC, sampleNr):
h = size(x, 0)
w = size(x, 1)
s2 = 0.5; # sigma squared
x = x.reshape(h*w)
zarr = zeros(size(x))
ident = identity(size(x))
c = zeros(sampleNr)
m = zeros((sampleNr, h*w))
s = zeros((sampleNr, h*w, h*w))
zsum = 0
nsum = 0
acat = dot(A, dot(C, A.T))
ata = dot(A.T, A)
for i in range(0, sampleNr):
z = random.gammavariate(2,2)
c[i] = multi_norm(x, zarr, s2*ident + z**2*acat)
zsum += z*c[i]
nsum += c[i]
s[i] = linalg.inv(invC + z/s2*ata)
m[i] = z/s2*dot(s[i]*A.T,x)
c = c/sum(c); # normalization
return [c, m, s, zsum/nsum]
开发者ID:zsomko,项目名称:visualcortex,代码行数:25,代码来源:pux.py
示例18: find_distributions
def find_distributions(self, n, c, source):
"""
Finds distribution functions
"""
if source[c][n] == 'NoArrivals':
return lambda : 'Inf'
if source[c][n][0] == 'Uniform':
return lambda : uniform(source[c][n][1], source[c][n][2])
if source[c][n][0] == 'Deterministic':
return lambda : source[c][n][1]
if source[c][n][0] == 'Triangular':
return lambda : triangular(source[c][n][1], source[c][n][2], source[c][n][3])
if source[c][n][0] == 'Exponential':
return lambda : expovariate(source[c][n][1])
if source[c][n][0] == 'Gamma':
return lambda : gammavariate(source[c][n][1], source[c][n][2])
if source[c][n][0] == 'Lognormal':
return lambda : lognormvariate(source[c][n][1], source[c][n][2])
if source[c][n][0] == 'Weibull':
return lambda : weibullvariate(source[c][n][1], source[c][n][2])
if source[c][n][0] == 'Custom':
P, V = zip(*self.parameters[source[c][n][1]])
probs = list(P)
cum_probs = [sum(probs[0:i+1]) for i in range(len(probs))]
values = list(V)
return lambda : self.custom_pdf(cum_probs, values)
if source[c][n][0] == 'Empirical':
if isinstance(source[c][n][1], str):
empirical_dist = self.import_empirical_dist(source[c][n][1])
return lambda : choice(empirical_dist)
return lambda : choice(source[c][n][1])
return False
开发者ID:gitter-badger,项目名称:Ciw,代码行数:32,代码来源:simulation.py
示例19: rand_student_t
def rand_student_t(df, mu=0, std=1):
"""return random number distributed by student's t distribution with
`df` degrees of freedom with the specified mean and standard deviation.
"""
x = random.gauss(0, std)
y = 2.0*random.gammavariate(0.5*df, 2.0)
return x / (math.sqrt(y/df)) + mu
开发者ID:BrianGasberg,项目名称:filterpy,代码行数:7,代码来源:stats.py
示例20: observations_r
def observations_r(obs, shape = 10):
"""
Parameters
----------
x A realization of the hidden variable
shape The shape parameter of the added noise
Returns
-------
xb, xd The path of the hidden variables
inc, splits Noisy observations
"""
nb_cells = len(obs['incr'])
nb_splits = len(obs['splits'])
xb = [None]*nb_cells
xd = [None]*nb_splits
xb[0] = 1.0
for ii in range(nb_splits):
xd[ii] = xb[ii] + obs['incr'][ii]
xb[2*ii+1+obs['delta'][ii]] = xd[ii]*obs['splits'][ii]
xb[2*ii+2-obs['delta'][ii]] = xd[ii]-xb[2*ii+1+obs['delta'][ii]]
growth_rate = [gammavariate(shape, 1.0/(x+sys.float_info.epsilon)) for x in xb]
x_hat = [shape/gg for gg in growth_rate]
return {'x_hat': x_hat }
开发者ID:pbourguignon,项目名称:python-abc,代码行数:32,代码来源:lineageTree.py
注:本文中的random.gammavariate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论