def check_random_sample(obj): sample = rnp.random_sample(obj, 100) ndim = getattr(obj, 'GetDimension', getattr(obj, 'GetNdim', None))() if ndim > 1: assert_equal(sample.shape, (100, ndim)) else: assert_equal(sample.shape, (100, )) a = rnp.random_sample(obj, 10, seed=1) b = rnp.random_sample(obj, 10, seed=1) c = rnp.random_sample(obj, 10, seed=2) assert_array_equal(a, b) assert_true((a != c).any())
def __populate(self, muons): # For each muon in the batch, draw injection times and kinematics variables. if self.sourceMode == "Mixture": offsets = self.sourceTimeDistribution.draw(choices=muons) kinematics = self.sourceKinematicsDistribution.draw(choices=muons) elif self.sourceMode == "Histogram1D": offsets = rnp.random_sample(self.sourceTimeHistogram, muons) kinematics = rnp.random_sample(self.sourceKinematicsHistogram, muons) elif self.sourceMode == "Histogram2D": samples = rnp.random_sample(self.sourceJointHistogram, muons) offsets = samples[:, 0] kinematics = samples[:, 1] else: raise ValueError(f"Input mode '{self.sourceMode}' not recognized.") # Apply the correlation polynomial to the kinematics variables. if self.sourceMode in ["Mixture", "Histogram1D"]: kinematics += np.polyval(self.sourceCorrelation, offsets) # Convert injection times to nanoseconds. if self.sourceTimeUnits == "nanoseconds": pass elif self.sourceTimeUnits == "microseconds": offsets *= 1E3 elif self.sourceTimeUnits == "seconds": offsets *= 1E9 else: raise ValueError( f"Time unit '{self.sourceTimeUnits}' not recognized.") # Center the mean injection time to zero (as a definition). offsets -= np.average(offsets) # Convert kinematics parameters to cyclotron frequencies. if self.sourceKinematicsVariable == "frequency": frequencies = kinematics elif self.sourceKinematicsVariable == "momentum": frequencies = utilities.momentumToFrequency(kinematics) elif self.sourceKinematicsVariable == "offset": frequencies = utilities.offsetToFrequency(kinematics) else: raise ValueError( f"Kinematics variable '{self.sourceKinematicsVariable}' not recognized." ) # Mask unphysical frequencies. mask = (frequencies >= utilities.min["f"]) & (frequencies <= utilities.max["f"]) return offsets[mask], frequencies[mask]
def check_random_sample(obj): sample = rnp.random_sample(obj, 100) ndim = getattr(obj, 'GetDimension', getattr(obj, 'GetNdim', None))() if ndim > 1: assert_equal(sample.shape, (100, ndim)) else: assert_equal(sample.shape, (100,)) a = rnp.random_sample(obj, 10, seed=1) b = rnp.random_sample(obj, 10, seed=1) c = rnp.random_sample(obj, 10, seed=2) assert_array_equal(a, b) assert_true((a != c).any())
def generate_zmq_package(n_events=1): #n_events -> package with that many events package = {} for feature in hists.keys(): hist = hists[feature] arr = random_sample(hist, n_events) package[feature] = arr return package
def random_sample_hist(hist, nsamples=1, seed=0): """ return a numpy array with random samples (samplings) which are taken randomly from a histogram. The sampling sequence starts with a random seed if seed == 0 Inputs : histogram (TH1, TH2, TH3) , # of samplings, seed (default=0) """ from ROOT import TH1, TH2, TH3 from root_numpy import random_sample info('(random_sample_hist) getting random sample of %f with seed %f from histogram ' %(nsamples, seed)) return random_sample(hist, nsamples, seed)
def random_sample_func(func, nsamplings=1, seed=0): """ return a numpy array with random samples (samplings) which are taken randomly from a function. The sampling sequence starts with a random seed if seed == 0 Inputs : function (TF1, TF2, TF3) , # of samplings, seed (default=0) """ from ROOT import TF1, TF2, TF3 from root_numpy import random_sample info('(random_sample_hist) getting random sample of %f with seed %f from function ' % (nsamplings, seed)) return random_sample(func, nsamplings, seed)
def test_random_sample_h3(): hist = TH3D("h3", "h3", 10, -3, 3, 10, -3, 3, 10, -3, 3) sample = rnp.random_sample(hist, 100) assert_equal(sample.shape, (100, 3))
def test_random_sample_h2(): hist = TH2D("h2", "h2", 10, -3, 3, 10, -3, 3) sample = rnp.random_sample(hist, 100) assert_equal(sample.shape, (100, 2))
def test_random_sample_h1(): hist = TH1D("h1", "h1", 10, -3, 3) sample = rnp.random_sample(hist, 100) assert_equal(sample.shape, (100,))
def test_random_sample_f3(): func = TF3("f3", "sin(x)*sin(y)*sin(z)/(x*y*z)") sample = rnp.random_sample(func, 100) assert_equal(sample.shape, (100, 3))
def test_random_sample_f2(): func = TF2("f2", "sin(x)*sin(y)/(x*y)") sample = rnp.random_sample(func, 100) assert_equal(sample.shape, (100, 2))
def test_random_sample_f1(): func = TF1("f1", "TMath::DiLog(x)") sample = rnp.random_sample(func, 100) assert_equal(sample.shape, (100,)) rnp.random_sample(func, 100, seed=1)
import matplotlib as mat import matplotlib.pyplot as plt import seaborn as sns import numpy as np import ROOT import root_numpy as rnp import pylandau # Seaborn configuration an Latex sns.set(rc={"figure.figsize":(8,4)}) sns.set_context('paper',font_scale=1.0,rc={'lines.linewidth':1.0}) sns.set_style('whitegrid') mat.rc('text',usetex=True) mat.rc('font',family='serif',serif='palatino') mat.rcParams['text.latex.preamble']=[r'\usepackage[utf8]{inputenc}',r'\usepackage[T1]{fontenc}',r'\usepackage[spanish]{babel}',r'\usepackage{amsmath,amsfonts,amssymb}',r'\usepackage{siunitx}'] # I will generate random variable "time" with a Landau distribution -- useful to model single photoelectron response from PMT time=np.arange(400,700,0.01) dtau=ROOT.TF1('tau0','TMath::Landau(x,492.145,7.59229,1)') tau=rnp.evaluate(dtau,time) # PDF --it may also be generated with pylandau # generate Nevents random samples from the distribution Nevents=1000000 rnd_tau=rnp.random_sample(ROOT.TF1('tau0','TMath::Landau(x,492.145,7.59229,1)',400,700),Nevents,seed=1) c=sns.color_palette(sns.cubehelix_palette(8,start=.25,rot=-.75,reverse=True)) fig,ax=plt.subplots(nrows=1,ncols=1) plt.plot(time,tau,color=c[0]) #plotting the PDF and the distribution of the samples sns.distplot(rnd_tau,hist=True,kde=False,rug=False,ax=ax,norm_hist=True, hist_kws={'histtype':'stepfilled','alpha':0.9},color=c[1]) plt.show()
tpeaks=[75,100,125,150,175] mpar=np.size(cf)*np.size(rf)*np.size(tpeaks) j=0 jphoton=0 for line in f: p[j,jphoton]=t0 nphe[j]=jphoton+1 k=np.fromstring(line,dtype=np.float,count=4,sep=' ') nevent=k[0] t0=k[2] if n0!=nevent: n0=nevent ptimes=p[j,p[j,:]!=0] if np.all(ptimes<200.0): rnd_tau=rnp.random_sample(taud,jphoton+1) q=stats.norm.rvs(loc=Qpmt,scale=sqpmt,size=jphoton+1) k=q/(2.0*rnd_tau) tnorm=(t-np.transpose(ptimes[np.newaxis]))/np.transpose(rnd_tau[np.newaxis]) u=t>np.transpose(ptimes[np.newaxis]) izero=np.transpose(k[np.newaxis])*np.power(tnorm,alpha)*np.exp(-1.0*tnorm)*u iphe[j,:]=np.sum(izero,axis=0) j+=1 jphoton=0 else: jphoton+=1 test=np.logical_and(nphe!=0,np.sum(p!=0,axis=1)>=1.0) nphe=nphe[test] p=p[test] iphe=iphe[test,:]