def enhanceNormal(tensor, dim, baseInitMethod, baseInitMethodParams): #Calcukate the std if baseInitMethod == 'kaiming': mean, std = getNormalKaimingStd(tensor, **baseInitMethodParams) elif baseInitMethod == 'xavier': mean, std = getNormalKaimingStd(tensor, **baseInitMethodParams) else: raise UnsupportedInitMethod('enhanceNormal.'+ str(baseInitMethod) +' unsupported method. Use \'kaiming\' or \'xavier\'') if dim == 0: #Regular case. This means we initialize the entire tensor from same normal distribution like baseInitMethod (both ) torchInit._no_grad_normal_(tensor, mean = 0, std = std) return for filt in tensor.data: #If dim is 1, then we initialize each filter if dim == 1: r = gengamma.rvs(a = 0.5, c = 1, loc = 0, scale = 2*((std)**2), size=1)[0] torchInit._no_grad_normal_(filt, mean = 0, std = r**0.5) continue #If we got here, dim is 2, and initialize for each sub-filter #Sample variance from gamma distribution r = gengamma.rvs(a = 0.5, c = 1, loc = 0, scale = 2*((std)**2), size=filt.shape[0]) for subfiltIdx, subfilt in enumerate(filt): torchInit._no_grad_normal_(subfilt, mean = 0, std = r[subfiltIdx]**0.5) return
def __init__(self, sigma, n, d, S=None, G=None, Pi=None, B=None): self.sigma = sigma self.n = n self.d = d if G is None: G = np.random.randn(self.d) self.G = G if S is None: samples = gengamma.rvs(self.d * 0.5, 2, size=self.d) S = samples / (np.sqrt(2) * np.linalg.norm(self.G)) self.S = S if Pi is None: Pi = RPM(d=self.d) self.Pi = Pi if B is None: B = np.rademacher(size=self.d) self.B = B
def generate_bound_step(self, prev_step, prev_angle): angle = self.astepper.generate_angle() new_theta = prev_angle + angle magnitude = gengamma.rvs(self.bound_shape, self.bound_rate, 1) x_step = np.cos(new_theta) * magnitude y_step = np.sin(new_theta) * magnitude return np.array([x_step, y_step]).reshape(2)
def generate_bound_step(self, prev_step=None, prev_angle=None): magnitude = gengamma.rvs(self.bound_shape, self.bound_rate, 1) angle = np.random.uniform(low=-180, high=180, size=1) x_drag, y_drag = self.compute_drag(prev_step, self.spring_constant) x_step = np.cos(angle * deg) * magnitude + x_drag y_step = np.sin(angle * deg) * magnitude + y_drag return np.array((x_step, y_step))
def generate_step(self, prev_step: np.ndarray = None, prev_angle: float = 0): angle = self.astepper.generate_angle() new_theta = prev_angle + angle magnitude = gengamma.rvs(self.shape, self.rate, 1) x_step = np.cos(new_theta) * magnitude y_step = np.sin(new_theta) * magnitude return np.array([x_step, y_step]).reshape(2)
def uniform_from_p_ball(p=1, n=2): a, c = 1 / p, p # 1. Sample n real scalars i.i.d. from the generalized Gamma distribution ξi ∼ G ̃ ( 1 , p). p r = gengamma.rvs(a, c, size=n) signs = random.choices([1, -1], k=n) # 2. Construct a vector x ∈ Rn with components xi = siξi, where si are independent uniformly random signs. vec = r * signs # 3. Compute z = w1/n, where w is a random variable uniformly distributed in the interval [0,1]. z = random.random()**(1 / n) y = z * 1 / p_norm(vec, p) * vec # 4. Return y = z x , where ∥x∥p = (∑n |xi|p)1/p. return y
def get_month(off, org_lim, col_lim, period): start = 100000 # Sentinel while start + period > col_lim or start < 0: # Emulate seasonality rv = random.uniform(0, 1) if rv < 0.35: start = int(gengamma.rvs(3, 3, loc=6, scale=1)) elif rv < 0.65: start = int(gengamma.rvs(2, 9, loc=12, scale=2)) elif rv < 0.85: start = int(gengamma.rvs(2, 15, loc=18, scale=1)) else: start = int(random.uniform(0, org_lim)) month = math.floor(off / 100) * 100 \ + (off % 100 + start % 12) % 12 \ + math.floor((off % 100 + start % 12) / 12) * 100 \ + math.floor(start / 12) * 100 if month % 100 == 0: month = month - 100 + 12 return int(month)
def main(): ## set the printfiles option to false and you will simply read in the s_collection_ft etc. from ../data_fs/exter/*.npy collection = simulate_tof(nwaveforms=16,nelectrons=12,e_retardation=530,e_photon=600,printfiles = False) ### Writing output files ### print('### Writing output files ###') collection_name = '../data_fs/extern/CookieBox_waveforms.randomsources.dat' print(collection_name) savetxt(collection_name,collection,fmt='%4f') collection_name = '../data_fs/extern/CookieBox_waveforms.randomsources' print(collection_name) npsave(collection_name,collection) integration_name = '../data_fs/extern/integration.randomsources.dat' print(integration_name) out = column_stack((collection[:,0],npsum(collection[:,1:],axis=1))) savetxt(integration_name,out,fmt='%4f') imageoutpath = '../data_fs/raw/' nimages = int(10) xrayintensities = gengamma.rvs(a=2,c=1,loc=0,scale=1,size=nimages) (nu_center, nu_width) = (560.,2.5) photonenergies = nu_center+nu_width*randn(nimages) (s,n,f,t) = readimpulseresponses('../data_fs/extern/') img = int(0) nwaveforms = int(16) retvec = ones(nwaveforms,dtype=float) * 520. transvec = ones(nwaveforms,dtype=float) collection = simulate_cb(s,n,f,t,retardations=retvec,transmissions=transvec,intensity = xrayintensities[img],photonenergy=photonenergies[img]) ### Writing output files ### print('### Writing output files ###') collection_name = imageoutpath + 'CookieBox_waveforms.image%04i.dat' % img print(collection_name) savetxt(collection_name,collection[:,1:],fmt='%4f') collection_name = imageoutpath + 'CookieBox_waveforms.times.dat' print(collection_name) savetxt(collection_name,collection[:,0],fmt='%4f')
def next_ttr(final_downtime_model, CRN=None): dist = final_downtime_model[0] params = final_downtime_model[1] if dist == "uniform": return uniform.rvs(*params, random_state=CRN) elif dist == "expon": return expon.rvs(*params, random_state=CRN) elif dist == "rayleigh": return rayleigh.rvs(*params, random_state=CRN) elif dist == "weibull_min": return weibull_min.rvs(*params, random_state=CRN) elif dist == "gamma": return gamma.rvs(*params, random_state=CRN) elif dist == "gengamma": return gengamma.rvs(*params, random_state=CRN) elif dist == "invgamma": return invgamma.rvs(*params, random_state=CRN) elif dist == "gompertz": return gompertz.rvs(*params, random_state=CRN) elif dist == "lognorm": return lognorm.rvs(*params, random_state=CRN) elif dist == "exponweib": return exponweib.rvs(*params, random_state=CRN)
* version 3 along with this program. If not, see http://www.gnu.org/licenses/ * * If you have any problem about this python version code, please contact: Rong Gong * [email protected] * * * If you want to refer this code, please use this article: * ''' from scipy.stats import gengamma import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) a, c = 4.41623854294, 3.11930916792 r = gengamma.rvs(a, c, size=10000) o1, o2, c1, a1 = gengamma.fit(r) x = np.linspace(gengamma.ppf(0.01, a1, c1), gengamma.ppf(0.99, a1, c1), 100) rv = gengamma(a1, c1) ax.hist(r, normed=True, histtype='stepfilled', alpha=0.2) ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') plt.show()
def _monte_carlo_b_to_a(logm, z, seed): alpha = _b_to_a_gengamma_alpha(logm, z) beta = _b_to_a_gengamma_beta(logm, z) r = 1 - 1. / (1 + gengamma.rvs(alpha, beta, random_state=seed)) return r
def monte_carlo_c_to_b(logmhalo): alpha, beta = _get_gengamma_c_to_b_params(logmhalo) return 1.65 - gengamma.rvs(alpha, beta)
def gengamma_b_to_a(alpha, beta): r = 1 - 1. / (1 + gengamma.rvs(alpha, beta)) return r
* * If you have any problem about this python version code, please contact: Rong Gong * [email protected] * * * If you want to refer this code, please use this article: * ''' from scipy.stats import gengamma import numpy as np import matplotlib.pyplot as plt fig, ax = plt.subplots(1, 1) a, c = 4.41623854294, 3.11930916792 r = gengamma.rvs(a, c, size=10000) o1,o2,c1,a1 = gengamma.fit(r) x = np.linspace(gengamma.ppf(0.01, a1, c1),gengamma.ppf(0.99, a1, c1), 100) rv = gengamma(a1, c1) ax.hist(r, normed=True, histtype='stepfilled', alpha=0.2) ax.plot(x, rv.pdf(x), 'k-', lw=2, label='frozen pdf') plt.show()
def samplegamma(a,c,loc,scale,n): #mean, var, skew, kurt = gamma.stats(a=a, c=c, loc = loc,scale=scale, moments='mvsk') #outstring = 'mean: %f\tvariance: %f' % (mean,var) #print(outstring) #v = gamma.rvs(a=a,c=c,loc=loc,scale=scale,size=n) return gamma.rvs(a=a,c=c,loc=loc,scale=scale,size=n)
def _monte_carlo_c_to_b(logmhalo, z, seed, shift=1.65): alpha, beta = _get_gengamma_c_to_b_params(logmhalo, z) return shift - gengamma.rvs(alpha, beta, random_state=seed)
#!/usr/bin/env python import os import sys from scipy.stats import gengamma if __name__ == '__main__': shape = float(sys.argv[1]) power = float(sys.argv[2]) numrv = int(sys.argv[3]) for i in xrange(numrv): rvs = gengamma.rvs(shape, power) print "%.15f" % rvs sys.exit(0)
#!/usr/bin/env python import os import sys from scipy.stats import gengamma if __name__=='__main__': shape = float(sys.argv[1]) power = float(sys.argv[2]) numrv = int(sys.argv[3]) for i in xrange(numrv): rvs = gengamma.rvs(shape, power) print "%.15f" % rvs sys.exit(0)