def apply_along_axis(func1d,axis,arr,*args): """ Execute func1d(arr[i],*args) where func1d takes 1-D arrays and arr is an N-d array. i varies so as to apply the function along the given axis for each 1-d subarray in arr. """ arr = asarray(arr) nd = arr.ndim if axis < 0: axis += nd if (axis >= nd): raise ValueError("axis must be less than arr.ndim; axis=%d, rank=%d." % (axis,nd)) ind = [0]*(nd-1) i = zeros(nd,'O') indlist = range(nd) indlist.remove(axis) i[axis] = slice(None,None) outshape = asarray(arr.shape).take(indlist) i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())],*args) # if res is a number, then we have a smaller output array if isscalar(res): outarr = zeros(outshape,asarray(res).dtype) outarr[tuple(ind)] = res Ntot = product(outshape) k = 1 while k < Ntot: # increment the index ind[-1] += 1 n = -1 while (ind[n] >= outshape[n]) and (n > (1-nd)): ind[n-1] += 1 ind[n] = 0 n -= 1 i.put(indlist,ind) res = func1d(arr[tuple(i.tolist())],*args) outarr[tuple(ind)] = res k += 1 return outarr else: Ntot = product(outshape) holdshape = outshape outshape = list(arr.shape) outshape[axis] = len(res) outarr = zeros(outshape,asarray(res).dtype) outarr[tuple(i.tolist())] = res k = 1 while k < Ntot: # increment the index ind[-1] += 1 n = -1 while (ind[n] >= holdshape[n]) and (n > (1-nd)): ind[n-1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())],*args) outarr[tuple(i.tolist())] = res k += 1 return outarr
def __train__(self, data, labels): l = labels.reshape((-1,1)) self.__trainingData__ = data self.__trainingLabels__ = l N = len(l) H = zeros((N,N)) for i in range(N): for j in range(N): H[i,j] = self.__trainingLabels__[i]*self.__trainingLabels__[j]*self.__kernelFunc__(self.__trainingData__[i],self.__trainingData__[j]) f = -1.0*ones(labels.shape) lb = zeros(labels.shape) ub = self.C * ones(labels.shape) Aeq = labels beq = 0.0 suppressOut = True if suppressOut: devnull = open('/dev/null', 'w') oldstdout_fno = os.dup(sys.stdout.fileno()) os.dup2(devnull.fileno(), 1) p = QP(matrix(H),f.tolist(),lb=lb.tolist(),ub=ub.tolist(),Aeq=Aeq.tolist(),beq=beq) r = p.solve('cvxopt_qp') if suppressOut: os.dup2(oldstdout_fno, 1) lim = 1e-4 r.xf[where(abs(r.xf)<lim)] = 0 self.__lambdas__ = r.xf nonzeroindexes = where(r.xf>lim)[0] # l1 = nonzeroindexes[0] # self.w0 = 1.0/labels[l1]-dot(self.w,data[l1]) self.numSupportVectors = len(nonzeroindexes)
def polyint(p, m=1, k=None): """Return the mth analytical integral of the polynomial p. If k is None, then zero-valued constants of integration are used. otherwise, k should be a list of length m (or a scalar if m=1) to represent the constants of integration to use for each integration (starting with k[0]) """ m = int(m) if m < 0: raise ValueError, "Order of integral must be positive (see polyder)" if k is None: k = NX.zeros(m, float) k = atleast_1d(k) if len(k) == 1 and m > 1: k = k[0]*NX.ones(m, float) if len(k) < m: raise ValueError, \ "k must be a scalar or a rank-1 array of length 1 or >m." if m == 0: return p else: truepoly = isinstance(p, poly1d) p = NX.asarray(p) y = NX.zeros(len(p)+1, float) y[:-1] = p*1.0/NX.arange(len(p), 0, -1) y[-1] = k[0] val = polyint(y, m-1, k=k[1:]) if truepoly: val = poly1d(val) return val
def polyadd(a1, a2): """ Find the sum of two polynomials. Returns the polynomial resulting from the sum of two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree. Parameters ---------- a1, a2 : array_like or poly1d object Input polynomials. Returns ------- out : ndarray or poly1d object The sum of the inputs. If either input is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree. See Also -------- poly1d : A one-dimensional polynomial class. poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval Examples -------- >>> np.polyadd([1, 2], [9, 5, 4]) array([9, 6, 6]) Using poly1d objects: >>> p1 = np.poly1d([1, 2]) >>> p2 = np.poly1d([9, 5, 4]) >>> print p1 1 x + 2 >>> print p2 2 9 x + 5 x + 4 >>> print np.polyadd(p1, p2) 2 9 x + 6 x + 6 """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: val = a1 + a2 elif diff > 0: zr = NX.zeros(diff, a1.dtype) val = NX.concatenate((zr, a1)) + a2 else: zr = NX.zeros(abs(diff), a2.dtype) val = a1 + NX.concatenate((zr, a2)) if truepoly: val = poly1d(val) return val
def estimateGaussian(trainData, trainLabels): numClasses = max(trainLabels) + 1 N = [0]* numClasses mu = [0.0] * numClasses Slist = [zeros((trainData.shape[1], trainData.shape[1]))] * numClasses pList = [0.0] * numClasses #calculate N, and sum x's for mu for x,t in izip(trainData, trainLabels): N[t] += 1 mu[t] += x #normalize mu for i in range(numClasses): mu[i] = mu[i] / float(N[i]) #calculate the class probabilities for i in range(numClasses): pList[i] = float(N[i]) / sum(N) #calculate S0 and S1 for x,t in izip(trainData, trainLabels): Slist[t] += outer(x - mu[t], x - mu[t]) try: inv(Slist[t]) except LinAlgError: Slist[t] += 0.1 * identity(Slist[t].shape[0], Float64) return (numClasses, N, mu, Slist, pList)
def GetFlow(self): ''' Calculating inlet flow (coefficients of the FFT x(t)=A0+sum(2*Ck*exp(j*k*2*pi*f*t))) Timestep and period from SimulationContext are necessary. ''' try: timestep = self.SimulationContext.Context['timestep'] except KeyError: print "Error, Please set timestep in Simulation Context XML File" raise try: period = self.SimulationContext.Context['period'] except KeyError: print "Error, Please set period in Simulation Context XML File" raise t = arange(0.0,period+timestep,timestep).reshape((1,ceil(period/timestep+1.0))) Cc = self.f_coeff*1.0/2.0*1e-6 Flow = zeros((1, ceil(period/timestep+1.0))) for freq in arange(0,ceil(period/timestep+1.0)): Flow[0, freq] = self.A0_v for k in arange(0,self.f_coeff.shape[0]): Flow[0, freq] = Flow[0, freq]+real(2.0*complex(Cc[k,0],Cc[k,1])*exp(1j*(k+1)*2.0*pi*t[0,freq]/period)) self.Flow = Flow return Flow
def myEnhance(self,img): self.img = img self.statx = zeros(256) print len(self.statx) # print len(self.img) # print img.shape() # for i in range(256): # self.statx[i]=self.statx.append(1) # np.histogram(self.img, bins=60) # for i in range(len(self.img)): # for j in range(len(self.img[i])): ## print img[i] ## if self.img[i][j]<100: ## self.img[i][j] = 0 ## else: ## self.img[i][j]=255 ## print self.img[i][j] # self.statx[self.img[i][j]] = self.statx[self.img[i][j]] + 1 # pass # return self.statx
def createKernel(xList, yList, kernelFunct, *kernelFunctArgs): #remember, examples are rows, not columns k = zeros((len(xList), len(yList))) for i in range(len(xList)): for j in range(len(yList)): k[i,j] = kernelFunct(xList[i], yList[j], *kernelFunctArgs) return k
def calcN(classKernels, trainLabels): N = zeros((len(trainLabels), len(trainLabels))) for i, l in enumerate(unique(trainLabels)): numExamplesWithLabel = len(where(trainLabels == l)[0]) Idiff = identity(numExamplesWithLabel, Float64) - (1.0 / numExamplesWithLabel) * ones(numExamplesWithLabel, Float64) firstDot = dot(classKernels[i], Idiff) labelTerm = dot(firstDot, transpose(classKernels[i])) N += labelTerm N = nan_to_num(N) #make N more numerically stable #if I had more time, I would train this parameter, but I don't additionToN = ((mean(diag(N)) + 1) / 100.0) * identity(N.shape[0], Float64) N += additionToN #make sure N is invertable for i in range(1000): try: inv(N) except LinAlgError: #doing this to make sure the maxtrix is invertable #large value supported by section titled #"numerical issues and regularization" in the paper N += additionToN return N
def triu(m, k=0): """ Upper triangle of an array. Return a copy of a matrix with the elements below the `k`-th diagonal zeroed. Please refer to the documentation for `tril` for further details. See Also -------- tril : lower triangle of an array Examples -------- >>> np.triu([[1,2,3],[4,5,6],[7,8,9],[10,11,12]], -1) array([[ 1, 2, 3], [ 4, 5, 6], [ 0, 8, 9], [ 0, 0, 12]]) """ m = asanyarray(m) mask = tri(*m.shape[-2:], k=k-1, dtype=bool) return where(mask, zeros(1, m.dtype), m)
def __init__(self, *shape): if len(shape) == 1 and isinstance(shape[0], tuple): shape = shape[0] x = as_strided(_nx.zeros(1), shape=shape, strides=_nx.zeros_like(shape)) self._it = _nx.nditer(x, flags=['multi_index', 'zerosize_ok'], order='C')
def iscomplex(x): """ Returns a bool array, where True if input element is complex. What is tested is whether the input has a non-zero imaginary part, not if the input type is complex. Parameters ---------- x : array_like Input array. Returns ------- out : ndarray of bools Output array. See Also -------- isreal iscomplexobj : Return True if x is a complex type or an array of complex numbers. Examples -------- >>> np.iscomplex([1+1j, 1+0j, 4.5, 3, 2, 2j]) array([ True, False, False, False, False, True]) """ ax = asanyarray(x) if issubclass(ax.dtype.type, _nx.complexfloating): return ax.imag != 0 res = zeros(ax.shape, bool) return res[()] # convert to scalar if needed
def fishersLinearDiscriminent(trainData, trainLabels, testData, testLabels): numClasses = max(trainLabels) + 1 N = [0] * numClasses m = [0] * numClasses for x,t in izip(trainData,trainLabels): m[t] += x N[t] += 1 for i in range(numClasses): m[i] /= N[i] Sw = zeros((trainData.shape[1], trainData.shape[1])) for x,t in izip(trainData, trainLabels): Sw += outer(x-m[t], x-m[t]) try: inv(Sw) except LinAlgError: Sw += 0.1 * identity(Sw.shape[0], Float64) w = dot(inv(Sw),(m[0] - m[1])) meanVect = (N[0]*m[0] + N[1]*m[1]) / sum(N) numCorrect = 0 for x,t in izip(testData, testLabels): if dot(w, (x-meanVect)) > 0: if t == 1: numCorrect += 1 else: if t == 0: numCorrect += 1 return float(numCorrect) / float(len(testLabels))
def diag(v, k=0): """ returns a copy of the the k-th diagonal if v is a 2-d array or returns a 2-d array with v as the k-th diagonal if v is a 1-d array. """ v = asarray(v) s = v.shape if len(s)==1: n = s[0]+abs(k) res = zeros((n,n), v.dtype) if (k>=0): i = arange(0,n-k) fi = i+k+i*n else: i = arange(0,n+k) fi = i+(i-k)*n res.flat[fi] = v return res elif len(s)==2: N1,N2 = s if k >= 0: M = min(N1,N2-k) i = arange(0,M) fi = i+k+i*N2 else: M = min(N1+k,N2) i = arange(0,M) fi = i + (i-k)*N2 return v.flat[fi] else: raise ValueError, "Input must be 1- or 2-d."
def diagflat(v,k=0): """Return a 2D array whose k'th diagonal is a flattened v and all other elements are zero. Examples -------- >>> diagflat([[1,2],[3,4]]]) array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]) >>> diagflat([1,2], 1) array([[0, 1, 0], [0, 0, 2], [0, 0, 0]]) """ try: wrap = v.__array_wrap__ except AttributeError: wrap = None v = asarray(v).ravel() s = len(v) n = s + abs(k) res = zeros((n,n), v.dtype) if (k>=0): i = arange(0,n-k) fi = i+k+i*n else: i = arange(0,n+k) fi = i+(i-k)*n res.flat[fi] = v if not wrap: return res return wrap(res)
def PlotWss(self, meshid, imagpath): ''' This method plots Wss signal and returns peak wss. ''' try: import matplotlib matplotlib.use('Agg') #switch to matplotlib.use('WXAgg') if you want to show and not save velocity profile. from matplotlib.pyplot import plot, xlabel, ylabel, title, legend, savefig, close, ylim except: sys.exit("PlotWss method requires matplotlib package (http://matplotlib.sourceforge.net.\n") tplot = linspace(0, self.tPeriod, len(self.Tauplot)) plot(tplot, self.Tauplot,'g-',linewidth = 3, label = 'WSS') minY = 0 for w in self.Tauplot: if w < minY: minY = w if minY != 0: plot(tplot, zeros(len(self.Tauplot)),':',linewidth = 1) ylim(ymin=minY) xlabel('Time ($s$)') ylabel('Wall shear stress ($dyne/cm^2$)') title ('Wss'+' peak:'+str(round(max(self.Tauplot),1))+' mean:'+str(round(mean(self.Tauplot),1))+' min:'+str(round(min(self.Tauplot),1))) legend() savefig(imagpath+str(meshid)+'_'+str(self.Name)+'_wss.png') print "Wss, MeshId", meshid, self.Name, "=", str(round(max(self.Tauplot),1)), "$dyne/cm^2$" close() return (round(max(self.Tauplot),1))
def gmmEM(data, K, it,show=False,usekmeans=True): #data += finfo(float128).eps*100 centroid = kmeans2(data, K)[0] if usekmeans else ((max(data) - min(data))*random_sample((K,data.shape[1])) + min(data)) N = data.shape[0] gmm = GaussianMM(centroid) if show: gmm.draw(data) while it > 0: print it," iterations remaining" it = it - 1 # e-step gausses = zeros((K, N), dtype = data.dtype) for k in range(0, K): gausses[k] = gmm.c[k]*mulnormpdf(data, gmm.mean[k], gmm.covm[k]) sums = sum(gausses, axis=0) if count_nonzero(sums) != sums.size: raise "Divide by Zero" gausses /= sums # m step sg = sum(gausses, axis=1) if count_nonzero(sg) != sg.size: raise "Divide by Zero" gmm.c = ones(sg.shape) / N * sg for k in range(0, K): gmm.mean[k] = sum(data * gausses[k].reshape((-1,1)), axis=0) / sg[k] d = data - gmm.mean[k] d1 = d.transpose()*gausses[k] gmm.covm[k]=dot(d1,d)/sg[k] if show: gmm.draw(data) return gmm
def polysub(a1, a2): """ Returns difference from subtraction of two polynomials input as sequences. Returns difference of polynomials; `a1` - `a2`. Input polynomials are represented as an array_like sequence of terms or a poly1d object. Parameters ---------- a1 : {array_like, poly1d} Minuend polynomial as sequence of terms. a2 : {array_like, poly1d} Subtrahend polynomial as sequence of terms. Returns ------- out : {ndarray, poly1d} Array representing the polynomial terms. See Also -------- polyval, polydiv, polymul, polyadd Examples -------- .. math:: (2 x^2 + 10 x - 2) - (3 x^2 + 10 x -4) = (-x^2 + 2) >>> np.polysub([2, 10, -2], [3, 10, -4]) array([-1, 0, 2]) """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: val = a1 - a2 elif diff > 0: zr = NX.zeros(diff, a1.dtype) val = NX.concatenate((zr, a1)) - a2 else: zr = NX.zeros(abs(diff), a2.dtype) val = a1 - NX.concatenate((zr, a2)) if truepoly: val = poly1d(val) return val
def mediff1d(array, to_end=None, to_begin=None): """Array difference with prefixed and/or appended value.""" a = masked_array(array, copy=True) if a.ndim > 1: a.reshape((a.size,)) (d, m, n) = (a._data, a._mask, a.size-1) dd = d[1:]-d[:-1] if m is nomask: dm = nomask else: dm = m[1:]-m[:-1] # if to_end is not None: to_end = asarray(to_end) nend = to_end.size if to_begin is not None: to_begin = asarray(to_begin) nbegin = to_begin.size r_data = numeric.empty((n+nend+nbegin,), dtype=a.dtype) r_mask = numeric.zeros((n+nend+nbegin,), dtype=bool_) r_data[:nbegin] = to_begin._data r_mask[:nbegin] = to_begin._mask r_data[nbegin:-nend] = dd r_mask[nbegin:-nend] = dm else: r_data = numeric.empty((n+nend,), dtype=a.dtype) r_mask = numeric.zeros((n+nend,), dtype=bool_) r_data[:-nend] = dd r_mask[:-nend] = dm r_data[-nend:] = to_end._data r_mask[-nend:] = to_end._mask # elif to_begin is not None: to_begin = asarray(to_begin) nbegin = to_begin.size r_data = numeric.empty((n+nbegin,), dtype=a.dtype) r_mask = numeric.zeros((n+nbegin,), dtype=bool_) r_data[:nbegin] = to_begin._data r_mask[:nbegin] = to_begin._mask r_data[nbegin:] = dd r_mask[nbegin:] = dm # else: r_data = dd r_mask = dm return masked_array(r_data, mask=r_mask)
def polysub(a1, a2): """ Difference (subtraction) of two polynomials. Given two polynomials `a1` and `a2`, returns ``a1 - a2``. `a1` and `a2` can be either array_like sequences of the polynomials' coefficients (including coefficients equal to zero), or `poly1d` objects. Parameters ---------- a1, a2 : array_like or poly1d Minuend and subtrahend polynomials, respectively. Returns ------- out : ndarray or poly1d Array or `poly1d` object of the difference polynomial's coefficients. See Also -------- polyval, polydiv, polymul, polyadd Examples -------- .. math:: (2 x^2 + 10 x - 2) - (3 x^2 + 10 x -4) = (-x^2 + 2) >>> np.polysub([2, 10, -2], [3, 10, -4]) array([-1, 0, 2]) """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: val = a1 - a2 elif diff > 0: zr = NX.zeros(diff, a1.dtype) val = NX.concatenate((zr, a1)) - a2 else: zr = NX.zeros(abs(diff), a2.dtype) val = a1 - NX.concatenate((zr, a2)) if truepoly: val = poly1d(val) return val
def AssembleBoundaryConditions(self, simulationContext): ''' This method assembles arrays of prescribed pressures ''' self.DofMap = DofMap() self.DofMap.SetNetworkMesh(self.NetworkMesh) self.DofMap.Build() # Searching for prescribed pressure output/input numberOfElements = 0 for element in self.NetworkMesh.Elements: for dof in element.GetExternalPressureLocalDofs(): numberOfElements+=1 if self.BoundaryConditions.OutsP is not None: numberOfElements+=len(self.BoundaryConditions.PressureOut) if self.BoundaryConditions.InP is not None: numberOfElements+=1 # Setting Transmural Pressures for windkessel elements and wave propagation elements PrescribedPressures = zeros((numberOfElements,2)) done = 0 i = 0 for element in self.NetworkMesh.Elements: for dof in element.GetExternalPressureLocalDofs(): for el, elProps in self.BoundaryConditions.PressureOut.iteritems(): if element.Id == el.Id: if done < len(self.BoundaryConditions.PressureOut): value1 = self.DofMap.DofMap[(el.Id,el.GetLocalDof(int(elProps['node'])))] value2 = elProps['value'] if value1 not in PrescribedPressures: PrescribedPressures[i,0] = value1 PrescribedPressures[i,1] = value2 done+=1 i+=1 if self.BoundaryConditions.InP is not None: if element.Id == self.BoundaryConditions.elementIn.Id: if done == 0: value1 = self.DofMap.DofMap[(self.BoundaryConditions.elementIn.Id,self.BoundaryConditions.elementIn.GetLocalDof(int(self.BoundaryConditions.NodeIn)))] value2 = self.BoundaryConditions.InP PrescribedPressures[i,0] = value1 PrescribedPressures[i,1] = value2 done = 1 i+=1 value1 = self.DofMap.DofMap[(element.Id,dof)] value2 = self.BoundaryConditions.PressureValues[element.Id] PrescribedPressures[i,0] = value1 PrescribedPressures[i,1] = value2 i+=1 self.BoundaryConditions.SetSimulationContext(simulationContext) for el in self.BoundaryConditions.elementFlow: self.FlowDof[el.Id] = self.DofMap.DofMap[(el.Id,el.GetLocalDof(int(self.BoundaryConditions.NodeFlow[el.Id])))] self.PrescribedPressures = PrescribedPressures.astype(int32) return self.PrescribedPressures
def diagflat(v, k=0): """ Create a two-dimensional array with the flattened input as a diagonal. Parameters ---------- v : array_like Input data, which is flattened and set as the `k`-th diagonal of the output. k : int, optional Diagonal to set; 0, the default, corresponds to the "main" diagonal, a positive (negative) `k` giving the number of the diagonal above (below) the main. Returns ------- out : ndarray The 2-D output array. See Also -------- diag : MATLAB work-alike for 1-D and 2-D arrays. diagonal : Return specified diagonals. trace : Sum along diagonals. Examples -------- >>> np.diagflat([[1,2], [3,4]]) array([[1, 0, 0, 0], [0, 2, 0, 0], [0, 0, 3, 0], [0, 0, 0, 4]]) >>> np.diagflat([1,2], 1) array([[0, 1, 0], [0, 0, 2], [0, 0, 0]]) """ try: wrap = v.__array_wrap__ except AttributeError: wrap = None v = asarray(v).ravel() s = len(v) n = s + abs(k) res = zeros((n,n), v.dtype) if (k >= 0): i = arange(0,n-k) fi = i+k+i*n else: i = arange(0,n+k) fi = i+(i-k)*n res.flat[fi] = v if not wrap: return res return wrap(res)
def polysub(a1, a2): """Subtracts two polynomials represented as sequences """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: val = a1 - a2 elif diff > 0: zr = NX.zeros(diff, a1.dtype) val = NX.concatenate((zr, a1)) - a2 else: zr = NX.zeros(abs(diff), a2.dtype) val = a1 - NX.concatenate((zr, a2)) if truepoly: val = poly1d(val) return val
def diag(v, k=0): """ Extract a diagonal or construct a diagonal array. Parameters ---------- v : array_like If `v` is a 2-dimensional array, return a copy of its `k`-th diagonal. If `v` is a 1-dimensional array, return a 2-dimensional array with `v` on the `k`-th diagonal. k : int, optional Diagonal in question. The defaults is 0. Examples -------- >>> x = np.arange(9).reshape((3,3)) >>> x array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.diag(x) array([0, 4, 8]) >>> np.diag(np.diag(x)) array([[0, 0, 0], [0, 4, 0], [0, 0, 8]]) """ v = asarray(v) s = v.shape if len(s)==1: n = s[0]+abs(k) res = zeros((n,n), v.dtype) if (k>=0): i = arange(0,n-k) fi = i+k+i*n else: i = arange(0,n+k) fi = i+(i-k)*n res.flat[fi] = v return res elif len(s)==2: N1,N2 = s if k >= 0: M = min(N1,N2-k) i = arange(0,M) fi = i+k+i*N2 else: M = min(N1+k,N2) i = arange(0,M) fi = i + (i-k)*N2 return v.flat[fi] else: raise ValueError, "Input must be 1- or 2-d."
def __setitem__(self, key, val): ind = self.order - key if key < 0: raise ValueError("Does not support negative powers.") if key > self.order: zr = NX.zeros(key-self.order, self.coeffs.dtype) self._coeffs = NX.concatenate((zr, self.coeffs)) ind = 0 self._coeffs[ind] = val return
def polydiv(u, v): """ Returns the quotient and remainder of polynomial division. The input arrays specify the polynomial terms in turn with a length equal to the polynomial degree plus 1. Parameters ---------- u : {array_like, poly1d} Dividend polynomial. v : {array_like, poly1d} Divisor polynomial. Returns ------- q : ndarray Polynomial terms of quotient. r : ndarray Remainder of polynomial division. See Also -------- poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub, polyval Examples -------- .. math:: \\frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25 >>> x = np.array([3.0, 5.0, 2.0]) >>> y = np.array([2.0, 1.0]) >>> np.polydiv(x, y) >>> (array([ 1.5 , 1.75]), array([ 0.25])) """ truepoly = (isinstance(u, poly1d) or isinstance(u, poly1d)) u = atleast_1d(u) + 0.0 v = atleast_1d(v) + 0.0 # w has the common type w = u[0] + v[0] m = len(u) - 1 n = len(v) - 1 scale = 1. / v[0] q = NX.zeros((max(m - n + 1, 1),), w.dtype) r = u.copy() for k in range(0, m-n+1): d = scale * r[k] q[k] = d r[k:k+n+1] -= d*v while NX.allclose(r[0], 0, rtol=1e-14) and (r.shape[-1] > 1): r = r[1:] if truepoly: return poly1d(q), poly1d(r) return q, r
def eye(N, M=None, k=0, dtype=float, order='C'): """ Return a 2-D array with ones on the diagonal and zeros elsewhere. Parameters ---------- N : int Number of rows in the output. M : int, optional Number of columns in the output. If None, defaults to `N`. k : int, optional Index of the diagonal: 0 (the default) refers to the main diagonal, a positive value refers to an upper diagonal, and a negative value to a lower diagonal. dtype : data-type, optional Data-type of the returned array. order : {'C', 'F'}, optional Whether the output should be stored in row-major (C-style) or column-major (Fortran-style) order in memory. .. versionadded:: 1.14.0 Returns ------- I : ndarray of shape (N,M) An array where all elements are equal to zero, except for the `k`-th diagonal, whose values are equal to one. See Also -------- identity : (almost) equivalent function diag : diagonal 2-D array from a 1-D array specified by the user. Examples -------- >>> np.eye(2, dtype=int) array([[1, 0], [0, 1]]) >>> np.eye(3, k=1) array([[ 0., 1., 0.], [ 0., 0., 1.], [ 0., 0., 0.]]) """ if M is None: M = N m = zeros((N, M), dtype=dtype, order=order) if k >= M: return m if k >= 0: i = k else: i = (-k) * M m[:M-k].flat[i::M+1] = 1 return m
def iscomplex(x): """Return a boolean array where elements are True if that element is complex (has non-zero imaginary part). For scalars, return a boolean. """ ax = asanyarray(x) if issubclass(ax.dtype.type, _nx.complexfloating): return ax.imag != 0 res = zeros(ax.shape, bool) return +res # convet to array-scalar if needed
def __setitem__(self, key, val): ind = self.order - key if key < 0: raise ValueError, "Does not support negative powers." if key > self.order: zr = NX.zeros(key-self.order, self.coeffs.dtype) self.__dict__['coeffs'] = NX.concatenate((zr, self.coeffs)) self.__dict__['order'] = key ind = 0 self.__dict__['coeffs'][ind] = val return
def prepare(self): figure(figsize=(18, 10)) if self.distribution is not None: self.P = zeros((len(self.Xs), len(self.Ys))) for i in range(len(self.Xs)): for j in range(len(self.Ys)): x = array([[self.Xs[i], self.Ys[j]]]) self.P[j, i] = self.distribution.log_pdf(x) self.P = exp(self.P)
def main(): #intitialize counters ##photon## njetsSel =0. cTotPhotons = 0. cRealSieie = 0. cFakeSieie = 0. cHoverE = 0. cNeuIso = 0. cREALCHIso = 0. cFAKECHIso = 0. cFakePhoIso = 0. cRealPhoIso =0. cPhoID = 0. cPhoEta = 0. cNFake =0. cNReal =0. cSieieRealTest = 0. cSieieFakeTest = 0. cLeadEt=0. cPhoEle=0. cPhoEtAll=0. cPixelSeed = 0. #incremental countsers iHoverE = 0. iNeuIso = 0. iFakeCHIso = 0. iRealCHIso = 0. iPhoIso = 0. iRealPhoIso =0. iPhoID = 0. iRealSieie = 0. iFakeSieie = 0. iRealLeadEt=0. iFakeLeadEt=0. iFakePhoEle=0. iRealPhoEle=0. iRealPhoEtAll=0. iFakePhoEtAll=0. iFakePixelSeed=0. iR9=0. # iPixelSeed = 0. #jets cJets = 0. cJetEta = 0. cJetID = 0. #Veto cHLT = 0. cDRCut= 0. cFakeRej = 0. cRealRej =0. cNPhotons=0. cMu =0. cEle = 0. cPhoEta = 0. cNFRPhotons = 0. cBarrel = 0. cHT=0. rejReal = 0. rejFake=0. # Keep time sw = ROOT.TStopwatch() sw.Start() # For DeltaR cut minDeltaRij = 100. nJetsTot = 0. # Load input TTrees into TChain # eosDir = "/eos/cms/store/user/mandrews/" # ggInStr = "%s/DATA/ggSKIMS/DoubleEG_Run2016%s_ReminiAOD_HLTDiPho3018M90_SKIM*.root"%(eosDir,runEra) eosDir = "/eos/cms/store/group/phys_smp/ggNtuples/13TeV/data/V08_00_26_04" ggInStr = "root://cmseos.fnal.gov//store/group/lpcsusystealth/ggNtuple_leppho/FebReminiAOD/skim-DoubleEG_FebReminiAOD.root" ggIn = ROOT.TChain("ggNtuplizer/EventTree") #InputList = "/afs/cern.ch/user/t/tmudholk/public/research/stealth/from_michael/STEALTH/inputFiles_2016%s.txt"%(runEra) # with open(InputList,'r') as f: # for ijt in f: # ggInStr = ijt.strip('\n') # ggIn.Add(ggInStr) eosDir = "/eos/uscms/store/user/lpcsusystealth" ggIn.Add(ggInStr) nEvts = ggIn.GetEntries() print " >> Input file(s):",ggInStr print " >> nEvts:",nEvts # Initialize output file as empty clone eosOut = "/eos/user/n/nbower/Stealth/Ntuples/FakeReal/Jan20/2f" outFileStr = "%s/CutReminiAOD_Run2016%s_sel%s_evts_HT%d_evt%sto%s_%sf_%sr.root"%(eosOut,runEra,args.sel,HTcut_,iEventStart,iEventEnd,nFake,nReal) outFile = ROOT.TFile(outFileStr, "RECREATE") outDir = outFile.mkdir("ggNtuplizer") outDir.cd() ggOut = ggIn.CloneTree(0) print " >> Output file:",outFileStr # Initialize output branches nJets_ = np.zeros(1, dtype=int) evtST_ = np.zeros(1, dtype=float) b_nJets = ggOut.Branch("b_nJets", nJets_, "b_nJets/I") b_evtST = ggOut.Branch("b_evtST", evtST_, "b_evtST/D") ##### EVENT SELECTION START ##### # Event range to process iEvtStart = iEventStart iEvtEnd = iEventEnd # iEvtEnd = 1000000 print " >> Processing entries: [",iEvtStart,"->",iEvtEnd,")" nTested= 0. nAcc = 0 for jEvt in range(iEvtStart,iEvtEnd): # Initialize event if jEvt > nEvts: break treeStatus = ggIn.LoadTree(jEvt) if treeStatus < 0: break evtStatus = ggIn.GetEntry(jEvt) if evtStatus <= 0: continue if jEvt % 100000 == 0: print " .. Processing entry",jEvt evtST = 0. nTested+=1 # Photon selection if ggIn.HLTPho>>14&1 == False: # HLT_Diphoton30_18_R9Id_OR_IsoCaloId_AND_HE_R9Id_Mass90 cHLT+=1 continue phoIdx = [] # for DeltaR check: keep a list of photon indices passing photon selection nPhotons = 0. nFakepho = 0. chIso = 0. neuIso = 0. phoIso = 0. HoverE= 0. Sieie = 0. R9 = 0. passesFakeSieie = True passesFakechIso = True passesFakeEither = True LeadPho = True ############################Photon Selection################################### for i in range(ggIn.nPho): if abs(ggIn.phoEta[i]) > 1.442: cPhoEta +=1. continue cBarrel+=1 HoverE = ggIn.phoHoverE[i] Sieie = ggIn.phoSigmaIEtaIEtaFull5x5[i] R9 = ggIn.phoR9[i] ##########################Iso correction############################## if abs(ggIn.phoEta[i]) < 1.0: chIso = max(ggIn.phoPFChIso[i] - ggIn.rho*.0360, 0.) neuIso = max(ggIn.phoPFNeuIso[i] - ggIn.rho*.0597, 0.) phoIso = max(ggIn.phoPFPhoIso[i] - ggIn.rho*.1210, 0.) else: chIso = max(ggIn.phoPFChIso[i] - ggIn.rho*.0377, 0.) neuIso = max(ggIn.phoPFNeuIso[i] - ggIn.rho*.0807, 0.) phoIso = max(ggIn.phoPFPhoIso[i] - ggIn.rho*.1107, 0.) #I'm trying a new implimentation of the photon specific curs because I'm not confident in my understanding of #python's implimentation of booleans so lets give this a whirl, its fairly similar to tanmay's implimentation ########################Fake specific cuts################################ if Sieie > .01022 and Sieie < .015: passesFakeSieie = True else: passesFakeSieie = False if (chIso > .441 and chIso < 15.): passesFakechIso = True else: passesFakechIso = False if passesFakechIso or passesFakeSieie: passesFakeEither=True else : passesFakeEither=False ####################Fake Photon Selection ############## if ( ggIn.phoEt[i] > PhoEtAll and neuIso < 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2 and phoIso < 2.571+0.0047*float(ggIn.phoEt[i]) and HoverE < .0396 and passesFakeEither== True and ggIn.phohasPixelSeed[i] == 0 and R9 < 1.0 ): if LeadPho == True and ggIn.phoEt[i] < PhoEtLead: LeadPho = False cLeadEt+=(ggIn.nPho-i) break LeadPho = False nFakepho+=1 cNFake+=1 evtST += ggIn.phoEt[i] phoIdx.append(i) else: rejFake+=1 ####################Real Photon Selection ############## if (ggIn.phoEt[i] > PhoEtAll and ((ggIn.phoIDbit[i] >> 1) & 1) == 1 and ggIn.phoEleVeto[i] == True ): if LeadPho == True and ggIn.phoEt[i] <PhoEtLead: LeadPho = False cLeadEt+=(ggIn.nPho-i) break LeadPho=False nPhotons+=1 cNReal+=1 evtST += ggIn.phoEt[i] phoIdx.append(i) else: rejReal += 1 #############UpdateCounters###################### cBarrel+=1 if ggIn.phoEleVeto[i] == False: cPhoEle+=1 if abs(ggIn.phoEta[i]) < 1.442: if ggIn.phoIDbit[i]>>1&1 == 1 and Sieie== .01022: cSieieRealTest +=1 if not ggIn.phoIDbit[i]>>1&1 == 1: cPhoID+=1. if Sieie== .01022: cSieieFakeTest+=1 if HoverE >.0306: cHoverE+=1. if Sieie >.01022: cRealSieie+=1. else: cFakeSieie+=1. if neuIso > 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2: cNeuIso +=1. ##########Reversed counters######### if phoIso > 2.571+0.0047*float(ggIn.phoEt[i]): cRealPhoIso+=1. if phoIso < 2.571+0.0047*float(ggIn.phoEt[i]) or phoIso<15: cFakePhoIso += 1. if chIso <.441: cREALCHIso+=1. if chIso<.441 or chIso> 15.: cFAKECHIso +=1 if ggIn.phoEt[i]> PhoEtAll: cPhoEtAll+=1 #######################incremental counters###################### if HoverE >.0306: iHoverE +=1. if neuIso > 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2 or HoverE >.0306: iNeuIso +=1. if phoIso > 2.571+0.0047*float(ggIn.phoEt[i]) or neuIso > 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2 or HoverE >.0306: iPhoIso +=1. ############## Fake########## if passesFakeEither== False or phoIso > 2.571+0.0047*float(ggIn.phoEt[i]) or neuIso > 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2 or HoverE> .0306: iFakeSieie +=1. if ggIn.phoEt[i] < PhoEtAll or passesFakeEither== False or phoIso < 2.571+0.0047*float(ggIn.phoEt[i]) or neuIso > 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2 or HoverE >.0306: iFakePhoEtAll +=1. if ggIn.phohasPixelSeed[i] != 0 or ggIn.phoEt[i] <= PhoEtAll or passesFakeEither== False or phoIso >= 2.571+0.0047*float(ggIn.phoEt[i]) or neuIso > 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2 or HoverE >.0306: iFakePixelSeed += 1. if ggIn.phohasPixelSeed[i] != 0 or ggIn.phoEt[i] >= PhoEtAll or passesFakeEither== False or phoIso >= 2.571+0.0047*float(ggIn.phoEt[i]) or neuIso > 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2 or HoverE >.0306 or R9>=1.0: iR9 += 1. ####################REAL###################### if Sieie > .01022 or phoIso > 2.571+0.0047*float(ggIn.phoEt[i]) or neuIso > 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2 or HoverE >.0306: iRealSieie +=1. if (chIso > .441) or Sieie > .01022 or phoIso > 2.571+0.0047*float(ggIn.phoEt[i]) or neuIso > 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2 or HoverE >.0306: iRealCHIso +=1 if ggIn.phoEt[i] < PhoEtAll or (chIso > .441) or Sieie > .01022 or phoIso > 2.571+0.0047*float(ggIn.phoEt[i]) or neuIso > 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2 or HoverE >.0306: iRealPhoEtAll +=1. if ggIn.phoEleVeto[i] == False or ggIn.phoEt[i] < PhoEtAll or (chIso > .441) or Sieie > .01022 or phoIso > 2.571+0.0047*float(ggIn.phoEt[i]) or neuIso > 2.725+0.0148*float(ggIn.phoEt[i])+0.000017*float(ggIn.phoEt[i])**2 or HoverE>.0306: iRealPhoEle += 1. if nFakepho!=nFake: cFakeRej+=1 if nReal!=nPhotons: cRealRej+=1 if nPhotons != nReal or nFakepho != nFake: cNFRPhotons+=1 if nPhotons != nReal or nFakepho != nFake: continue # Jet selection nJets = 0 nJetsDR = 0 evtHT = 0 for i in range(ggIn.nJet): cJets+=1 if (ggIn.jetPt[i] > 30.0 and abs(ggIn.jetEta[i]) < 2.4 ): if not (ggIn.jetPFLooseId[i] != False and ggIn.jetPUID[i] > 0.61 and ggIn.jetID[i] == 6): cJetID +=1 if not (ggIn.jetPt[i] > 30.0 and abs(ggIn.jetEta[i]) < 2.4 and ggIn.jetPFLooseId[i] != False # for some reason == True doesnt work and ggIn.jetPUID[i] > 0.62 # formerly jetPUidFullDiscriminant and ggIn.jetID[i] == 6 # loose:2, tight:6 ): continue nJets += 1. evtHT += ggIn.jetPt[i] # Add jet pT to HT (even though not sure if it's photon) # DeltaR check: ensure this jet is well-separated from any of the good photons # To avoid double-counting, only add jet pT to ST if we're sure its not a photon minDeltaRij = 100. for j in phoIdx: # loop over "good" photon indices dR = np.hypot(ggIn.phoEta[j]-ggIn.jetEta[i],ggIn.phoPhi[j]-ggIn.jetPhi[i]) #DeltaR(pho[j],jet[i]) if dR < minDeltaRij: minDeltaRij = dR if minDeltaRij < minDeltaRcut_: continue nJetsDR += 1 # nJets passing the DeltaR check evtST += ggIn.jetPt[i] nJetsTot += nJetsDR if evtHT < HTcut_: cHT+=1 # continue # Electron veto nEle = 0 for i in range(ggIn.nEle): if not (ggIn.elePt[i] > 15.0 and ggIn.eleIDbit[i]>>3&1 == True # >>0:veto, >>1:loose, >>2:medium, >>3:tight and abs(ggIn.eleEta[i]) < 2.5 and abs(ggIn.eleDz[i]) < 0.1 and ggIn.elePFPUIso[i] < 0.1 ): continue nEle += 1. if nEle != 0: cEle+=1. # Muon veto nMu = 0 for i in range(ggIn.nMu): if not (ggIn.muPt[i] > 15.0 and ggIn.muPFPUIso[i] < 0.12 and ggIn.muIDbit[i]>>2&1 == True # >>0:loose, >>1:med, >>2:tight, >>3:soft, >>4:highpt ): continue nMu += 1 if nMu != 0: cMu+=1 if nPhotons != nReal or nFakepho != nFake: continue if nMu != 0: continue if nEle != 0: continue # Photon selection # MET selection if ggIn.pfMET > 15.: evtST += ggIn.pfMET # Write this evt to output tree evtST_[0] = evtST nJets_[0] = nJetsDR ggOut.Fill() nAcc += 1. if nJetsDR >=2: njetsSel +=1 ##### EVENT SELECTION END ##### outFile.Write() outFile.Close() # cBarrel = cTotPhotons - cPhoEta-cLeadEt#number of photon candidates within the barrel with Et passing the leading cut) sw.Stop() totalFakeCut = cBarrel-cLeadEt-cNFake totalRealCut = cBarrel-cLeadEt-cNReal efHoverE = cHoverE/cBarrel*100 efSieieReal = cRealSieie/cBarrel*100 efNeuIso = cNeuIso/cBarrel*100 efRealPhoIso = cRealPhoIso/cBarrel*100 efFakeSieie = cFakeSieie/cBarrel*100 with open('/afs/cern.ch/user/n/nbower/public/CMU/Stealth_SUSY/ST_plotting/CMSSW_8_0_24/src/STEALTH_PLAY/FakeReal/Selection_Outputs/Jan20/2f/Menglei2016%s_evt%sto%s_%sf_%sr.txt'%(runEra,iEvtStart,iEvtEnd,nFake,nReal),'w') as f: f.write(" Total Events in Era = " + str(nEvts)+"\n") f.write( " >> nAccepted evts:"+str(nAcc)+"/"+str(iEvtEnd-iEvtStart)+"("+str(100.*nAcc/(iEvtEnd-iEvtStart))+"% )"+"\n") f.write( " >> nJetsTot:"+str(nJetsTot)+"\n") f.write( " >> Real time:"+str(sw.RealTime()/60.)+"minutes"+"\n") f.write( " >> CPU time: "+str(sw.CpuTime() /60.)+"minutes"+"\n") f.write( "========================CounterResults==========================="+"\n") f.write( "####Photon Cut Effieciency#####"+"\n") f.write("LeadEt Cut = " + str(cLeadEt/(cBarrel)*100)+"%"+"\n") f.write("failing ID " +str(cPhoID)+"\n") f.write( "Total Photon candidates = " +str(cTotPhotons)+"\n") # f.write( "Barrel Efficiency = " +str(efBar) + "%"+"\n") f.write( "-Efficiency within Barel-"+"\n") f.write( "***REAL CUTS***"+"\n") f.write( "Photon ID = " + str(cPhoID/cBarrel*100)+"%"+"\n") f.write( "HoverE = " + str(efHoverE)+"%"+"\n") f.write( "SieieREAL = " + str(efSieieReal)+"%"+"\n") f.write( "Real Charged Hadron Iso = "+ str(cREALCHIso/cBarrel*100) + "%"+"\n") f.write( "Fake Charged Hadron Iso = "+ str(cFAKECHIso/cBarrel*100) + "%"+"\n") f.write( "Neutral Hadron Iso = " +str (efNeuIso)+ "%"+"\n") f.write( "Pho Iso = "+ str(efRealPhoIso)+"%"+"\n") f.write("Pho Et General cut (25 GeV) = " + str (cPhoEtAll/(cBarrel)*100)+"%"+"\n") f.write("Pho Electron Veto " + str(cPhoEle)+ " || " + str(cPhoEle/cBarrel*100)+ "%"+"\n") f.write( "***Fake Cuts***"+"\n") f.write("SieieFAKE = " + str(cFakeSieie/cBarrel*100)+"%"+"\n") f.write( "Pho Iso Fake = "+ str(cFakePhoIso/cBarrel*100)+"%"+"\n") f.write( "####Total number of Fake/ Real(passing efficiency)####"+"\n") f.write("Fake Photons = "+ str(cNFake)+"|| Passing Efficiency = " + str(cNFake/(cBarrel)*100)+"%"+"\n") f.write( "Real Photons = "+ str(cNReal)+"|| Passing Efficiency = " + str(cNReal/(cBarrel)*100)+"%"+"\n") f.write( "========================Incremental Counter Results==========================="+"\n") f.write( "-Efficiency within Barel-"+"\n") f.write( "***REAL CUTS***"+"\n") f.write( "HoverE = " + str(iHoverE/rejReal*100)+"%"+"\n") f.write( "Neutral Hadron Iso = " +str (iNeuIso/rejReal*100)+ "%"+"\n") f.write( "Pho Iso = "+ str(iPhoIso/rejReal*100)+"%"+"\n") f.write("Sieie = " + str(iRealSieie/rejReal*100)+"%"+"\n") f.write("Charge Hadron Iso = " + str(iRealCHIso/rejReal*100) + "%"+"\n") f.write("Pho ET all = " + str (iRealPhoEtAll/rejReal*100) + "%"+"\n") f.write("Pho Electron Veto = " + str(iRealPhoEle/rejReal*100)+ "%"+"\n") f.write( "***FAKE CUTS***"+"\n") f.write( "HoverE = " + str(iHoverE/rejFake*100)+"%"+"\n") f.write( "Neutral Hadron Iso = " +str (iNeuIso/rejFake*100)+ "%"+"\n") f.write( "Pho Iso = "+ str(iPhoIso/rejFake*100)+"%"+"\n") f.write("Sieie = " + str(iFakeSieie/rejFake*100)+"%"+"\n") f.write("Charge Hadron Iso = " + str(iFakeCHIso/rejFake*100) + "%"+"\n") f.write("Pho ET all = " + str (iFakePhoEtAll/rejFake*100) + "%"+"\n") f.write("Pho Pixel Veto = " + str(iFakePixelSeed/rejFake*100)+ "%"+"\n") f.write("R9 = " + str(iR9/rejFake*100)+ "%"+"\n") f.write( "===========Event Rejection=========="+"\n") f.write ( "HLT Eficiency=" + str(cHLT/nTested*100)+"%"+"\n") f.write( "Rejection due to combined number of fake and Real = "+ str(cNFRPhotons/(nTested-cHLT)*100)+"%"+"\n") f.write("HT<60GeV cut = " +str(cHT/(nTested-cNFRPhotons)*100)+"%" +"\n") f.write( "Muon Rejection = " + str(cMu/(nTested-cHLT-cNFRPhotons-cHT)*100)+"%"+"\n") f.write( "Electron Rejection = " + str (cEle/(nTested-cHLT-cHT-cNFRPhotons)*100)+"%"+"\n") f.write('=================Jet Selection=============\n') f.write('events passing jet selection = ' + str(njetsSel/nTested*100)+"%/n") f.write('Total Jet candidates '+ str(cJets)+'\n') f.write("Passing Cuts = " + str(cJetID/cJets*100)+"% \n")
def polyadd(a1, a2): """ Find the sum of two polynomials. .. note:: This forms part of the old polynomial API. Since version 1.4, the new polynomial API defined in `numpy.polynomial` is preferred. A summary of the differences can be found in the :doc:`transition guide </reference/routines.polynomials>`. Returns the polynomial resulting from the sum of two input polynomials. Each input must be either a poly1d object or a 1D sequence of polynomial coefficients, from highest to lowest degree. Parameters ---------- a1, a2 : array_like or poly1d object Input polynomials. Returns ------- out : ndarray or poly1d object The sum of the inputs. If either input is a poly1d object, then the output is also a poly1d object. Otherwise, it is a 1D array of polynomial coefficients from highest to lowest degree. See Also -------- poly1d : A one-dimensional polynomial class. poly, polyadd, polyder, polydiv, polyfit, polyint, polysub, polyval Examples -------- >>> np.polyadd([1, 2], [9, 5, 4]) array([9, 6, 6]) Using poly1d objects: >>> p1 = np.poly1d([1, 2]) >>> p2 = np.poly1d([9, 5, 4]) >>> print(p1) 1 x + 2 >>> print(p2) 2 9 x + 5 x + 4 >>> print(np.polyadd(p1, p2)) 2 9 x + 6 x + 6 """ truepoly = (isinstance(a1, poly1d) or isinstance(a2, poly1d)) a1 = atleast_1d(a1) a2 = atleast_1d(a2) diff = len(a2) - len(a1) if diff == 0: val = a1 + a2 elif diff > 0: zr = NX.zeros(diff, a1.dtype) val = NX.concatenate((zr, a1)) + a2 else: zr = NX.zeros(abs(diff), a2.dtype) val = a1 + NX.concatenate((zr, a2)) if truepoly: val = poly1d(val) return val
def roots(p): """ Return the roots of a polynomial with coefficients given in p. The values in the rank-1 array `p` are coefficients of a polynomial. If the length of `p` is n+1 then the polynomial is described by:: p[0] * x**n + p[1] * x**(n-1) + ... + p[n-1]*x + p[n] Parameters ---------- p : array_like Rank-1 array of polynomial coefficients. Returns ------- out : ndarray An array containing the roots of the polynomial. Raises ------ ValueError When `p` cannot be converted to a rank-1 array. See also -------- poly : Find the coefficients of a polynomial with a given sequence of roots. polyval : Compute polynomial values. polyfit : Least squares polynomial fit. poly1d : A one-dimensional polynomial class. Notes ----- The algorithm relies on computing the eigenvalues of the companion matrix [1]_. References ---------- .. [1] R. A. Horn & C. R. Johnson, *Matrix Analysis*. Cambridge, UK: Cambridge University Press, 1999, pp. 146-7. Examples -------- >>> coeff = [3.2, 2, 1] >>> np.roots(coeff) array([-0.3125+0.46351241j, -0.3125-0.46351241j]) """ # If input is scalar, this makes it an array p = atleast_1d(p) if p.ndim != 1: raise ValueError("Input must be a rank-1 array.") # find non-zero array entries non_zero = NX.nonzero(NX.ravel(p))[0] # Return an empty array if polynomial is all zeros if len(non_zero) == 0: return NX.array([]) # find the number of trailing zeros -- this is the number of roots at 0. trailing_zeros = len(p) - non_zero[-1] - 1 # strip leading and trailing zeros p = p[int(non_zero[0]):int(non_zero[-1])+1] # casting: if incoming array isn't floating point, make it floating point. if not issubclass(p.dtype.type, (NX.floating, NX.complexfloating)): p = p.astype(float) N = len(p) if N > 1: # build companion matrix and find its eigenvalues (the roots) A = diag(NX.ones((N-2,), p.dtype), -1) A[0,:] = -p[1:] / p[0] roots = eigvals(A) else: roots = NX.array([]) # tack any zeros onto the back of the array roots = hstack((roots, NX.zeros(trailing_zeros, roots.dtype))) return roots
len_strategy = 5 print "Nr Agents: ",nr_agent," nr bit strategy",len_strategy," for ",max_steps_sim," time steps" lista_divisori = [] for i in range(2,nr_agent): if nr_agent%i==0: primo=False lista_divisori.append(i) lista_divisori.append(nr_agent) payoff_list = [-1.0, -0.9, -0.8, -0.7, -0.6, -0.5, -0.4, -0.3, -0.2, -0.1, 0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0] div = 0 res_matrix = zeros((len(lista_divisori),len(payoff_list)),float) res_matrix_b = zeros((len(lista_divisori),len(payoff_list)),float) while div < len(lista_divisori): group_size = lista_divisori[div] pay_ind = 0 while pay_ind < len(payoff_list): payoff = payoff_list[pay_ind] result = 0.0 res_b = 0.0 result,res_b = simulation.perform_sim(nr_agent, group_size, payoff,nr_simulation,len_strategy,max_steps_sim) print "Nr agents ",nr_agent," group size ",group_size," payoff ",payoff," RESULT: ",result," breaking ",res_b res_matrix[div][pay_ind] = result res_matrix_b[div][pay_ind] = res_b
def apply_along_axis(func1d, axis, arr, *args, **kwargs): """ Apply a function to 1-D slices along the given axis. Execute `func1d(a, *args)` where `func1d` operates on 1-D arrays and `a` is a 1-D slice of `arr` along `axis`. Parameters ---------- func1d : function This function should accept 1-D arrays. It is applied to 1-D slices of `arr` along the specified axis. axis : integer Axis along which `arr` is sliced. arr : ndarray Input array. args : any Additional arguments to `func1d`. kwargs : any Additional named arguments to `func1d`. .. versionadded:: 1.9.0 Returns ------- apply_along_axis : ndarray The output array. The shape of `outarr` is identical to the shape of `arr`, except along the `axis` dimension. This axis is removed, and replaced with new dimensions equal to the shape of the return value of `func1d`. So if `func1d` returns a scalar `outarr` will have one fewer dimensions than `arr`. See Also -------- apply_over_axes : Apply a function repeatedly over multiple axes. Examples -------- >>> def my_func(a): ... \"\"\"Average first and last element of a 1-D array\"\"\" ... return (a[0] + a[-1]) * 0.5 >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> np.apply_along_axis(my_func, 0, b) array([ 4., 5., 6.]) >>> np.apply_along_axis(my_func, 1, b) array([ 2., 5., 8.]) For a function that returns a 1D array, the number of dimensions in `outarr` is the same as `arr`. >>> b = np.array([[8,1,7], [4,3,9], [5,2,6]]) >>> np.apply_along_axis(sorted, 1, b) array([[1, 7, 8], [3, 4, 9], [2, 5, 6]]) For a function that returns a higher dimensional array, those dimensions are inserted in place of the `axis` dimension. >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> np.apply_along_axis(np.diag, -1, b) array([[[1, 0, 0], [0, 2, 0], [0, 0, 3]], [[4, 0, 0], [0, 5, 0], [0, 0, 6]], [[7, 0, 0], [0, 8, 0], [0, 0, 9]]]) """ # handle negative axes arr = asanyarray(arr) nd = arr.ndim if not (-nd <= axis < nd): raise IndexError('axis {0} out of bounds [-{1}, {1})'.format(axis, nd)) if axis < 0: axis += nd # arr, with the iteration axis at the end in_dims = list(range(nd)) inarr_view = transpose(arr, in_dims[:axis] + in_dims[axis+1:] + [axis]) # compute indices for the iteration axes inds = ndindex(inarr_view.shape[:-1]) # invoke the function on the first item ind0 = next(inds) res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs)) # build a buffer for storing evaluations of func1d. # remove the requested axis, and add the new ones on the end. # laid out so that each write is contiguous. # for a tuple index inds, buff[inds] = func1d(inarr_view[inds]) buff = zeros(inarr_view.shape[:-1] + res.shape, res.dtype) # permutation of axes such that out = buff.transpose(buff_permute) buff_dims = list(range(buff.ndim)) buff_permute = ( buff_dims[0 : axis] + buff_dims[buff.ndim-res.ndim : buff.ndim] + buff_dims[axis : buff.ndim-res.ndim] ) # matrices have a nasty __array_prepare__ and __array_wrap__ if not isinstance(res, matrix): buff = res.__array_prepare__(buff) # save the first result, then compute and save all remaining results buff[ind0] = res for ind in inds: buff[ind] = asanyarray(func1d(inarr_view[ind], *args, **kwargs)) if not isinstance(res, matrix): # wrap the array, to preserve subclasses buff = res.__array_wrap__(buff) # finally, rotate the inserted axes back to where they belong return transpose(buff, buff_permute) else: # matrices have to be transposed first, because they collapse dimensions! out_arr = transpose(buff, buff_permute) return res.__array_wrap__(out_arr)
def apply_along_axis(func1d, axis, arr, *args, **kwargs): """ Apply a function to 1-D slices along the given axis. Execute `func1d(a, *args)` where `func1d` operates on 1-D arrays and `a` is a 1-D slice of `arr` along `axis`. This is equivalent to (but faster than) the following use of `ndindex` and `s_`, which sets each of ``ii``, ``jj``, and ``kk`` to a tuple of indices:: Ni, Nk = a.shape[:axis], a.shape[axis+1:] for ii in ndindex(Ni): for kk in ndindex(Nk): f = func1d(arr[ii + s_[:,] + kk]) Nj = f.shape for jj in ndindex(Nj): out[ii + jj + kk] = f[jj] Equivalently, eliminating the inner loop, this can be expressed as:: Ni, Nk = a.shape[:axis], a.shape[axis+1:] for ii in ndindex(Ni): for kk in ndindex(Nk): out[ii + s_[...,] + kk] = func1d(arr[ii + s_[:,] + kk]) Parameters ---------- func1d : function (M,) -> (Nj...) This function should accept 1-D arrays. It is applied to 1-D slices of `arr` along the specified axis. axis : integer Axis along which `arr` is sliced. arr : ndarray (Ni..., M, Nk...) Input array. args : any Additional arguments to `func1d`. kwargs : any Additional named arguments to `func1d`. .. versionadded:: 1.9.0 Returns ------- out : ndarray (Ni..., Nj..., Nk...) The output array. The shape of `out` is identical to the shape of `arr`, except along the `axis` dimension. This axis is removed, and replaced with new dimensions equal to the shape of the return value of `func1d`. So if `func1d` returns a scalar `out` will have one fewer dimensions than `arr`. See Also -------- apply_over_axes : Apply a function repeatedly over multiple axes. Examples -------- >>> def my_func(a): ... \"\"\"Average first and last element of a 1-D array\"\"\" ... return (a[0] + a[-1]) * 0.5 >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> np.apply_along_axis(my_func, 0, b) array([ 4., 5., 6.]) >>> np.apply_along_axis(my_func, 1, b) array([ 2., 5., 8.]) For a function that returns a 1D array, the number of dimensions in `outarr` is the same as `arr`. >>> b = np.array([[8,1,7], [4,3,9], [5,2,6]]) >>> np.apply_along_axis(sorted, 1, b) array([[1, 7, 8], [3, 4, 9], [2, 5, 6]]) For a function that returns a higher dimensional array, those dimensions are inserted in place of the `axis` dimension. >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> np.apply_along_axis(np.diag, -1, b) array([[[1, 0, 0], [0, 2, 0], [0, 0, 3]], [[4, 0, 0], [0, 5, 0], [0, 0, 6]], [[7, 0, 0], [0, 8, 0], [0, 0, 9]]]) """ # handle negative axes arr = asanyarray(arr) nd = arr.ndim axis = normalize_axis_index(axis, nd) # arr, with the iteration axis at the end in_dims = list(range(nd)) inarr_view = transpose(arr, in_dims[:axis] + in_dims[axis + 1:] + [axis]) # compute indices for the iteration axes, and append a trailing ellipsis to # prevent 0d arrays decaying to scalars, which fixes gh-8642 inds = ndindex(inarr_view.shape[:-1]) inds = (ind + (Ellipsis, ) for ind in inds) # invoke the function on the first item try: ind0 = next(inds) except StopIteration: raise ValueError( 'Cannot apply_along_axis when any iteration dimensions are 0') res = asanyarray(func1d(inarr_view[ind0], *args, **kwargs)) # build a buffer for storing evaluations of func1d. # remove the requested axis, and add the new ones on the end. # laid out so that each write is contiguous. # for a tuple index inds, buff[inds] = func1d(inarr_view[inds]) buff = zeros(inarr_view.shape[:-1] + res.shape, res.dtype) # permutation of axes such that out = buff.transpose(buff_permute) buff_dims = list(range(buff.ndim)) buff_permute = (buff_dims[0:axis] + buff_dims[buff.ndim - res.ndim:buff.ndim] + buff_dims[axis:buff.ndim - res.ndim]) # matrices have a nasty __array_prepare__ and __array_wrap__ if not isinstance(res, matrix): buff = res.__array_prepare__(buff) # save the first result, then compute and save all remaining results buff[ind0] = res for ind in inds: buff[ind] = asanyarray(func1d(inarr_view[ind], *args, **kwargs)) if not isinstance(res, matrix): # wrap the array, to preserve subclasses buff = res.__array_wrap__(buff) # finally, rotate the inserted axes back to where they belong return transpose(buff, buff_permute) else: # matrices have to be transposed first, because they collapse dimensions! out_arr = transpose(buff, buff_permute) return res.__array_wrap__(out_arr)
def histogramdd(sample, bins=10, range=None, normed=False, weights=None): """histogramdd(sample, bins=10, range=None, normed=False, weights=None) Return the N-dimensional histogram of the sample. Parameters: sample : sequence or array A sequence containing N arrays or an NxM array. Input data. bins : sequence or scalar A sequence of edge arrays, a sequence of bin counts, or a scalar which is the bin count for all dimensions. Default is 10. range : sequence A sequence of lower and upper bin edges. Default is [min, max]. normed : boolean If False, return the number of samples in each bin, if True, returns the density. weights : array Array of weights. The weights are normed only if normed is True. Should the sum of the weights not equal N, the total bin count will not be equal to the number of samples. Returns: hist : array Histogram array. edges : list List of arrays defining the lower bin edges. SeeAlso: histogram Example >>> x = random.randn(100,3) >>> hist3d, edges = histogramdd(x, bins = (5, 6, 7)) """ try: # Sample is an ND-array. N, D = sample.shape except (AttributeError, ValueError): # Sample is a sequence of 1D arrays. sample = atleast_2d(sample).T N, D = sample.shape nbin = empty(D, int) edges = D*[None] dedges = D*[None] if weights is not None: weights = asarray(weights) try: M = len(bins) if M != D: raise AttributeError, 'The dimension of bins must be a equal to the dimension of the sample x.' except TypeError: bins = D*[bins] # Select range for each dimension # Used only if number of bins is given. if range is None: smin = atleast_1d(array(sample.min(0), float)) smax = atleast_1d(array(sample.max(0), float)) else: smin = zeros(D) smax = zeros(D) for i in arange(D): smin[i], smax[i] = range[i] # Make sure the bins have a finite width. for i in arange(len(smin)): if smin[i] == smax[i]: smin[i] = smin[i] - .5 smax[i] = smax[i] + .5 # Create edge arrays for i in arange(D): if isscalar(bins[i]): nbin[i] = bins[i] + 2 # +2 for outlier bins edges[i] = linspace(smin[i], smax[i], nbin[i]-1) else: edges[i] = asarray(bins[i], float) nbin[i] = len(edges[i])+1 # +1 for outlier bins dedges[i] = diff(edges[i]) nbin = asarray(nbin) # Compute the bin number each sample falls into. Ncount = {} for i in arange(D): Ncount[i] = digitize(sample[:,i], edges[i]) # Using digitize, values that fall on an edge are put in the right bin. # For the rightmost bin, we want values equal to the right # edge to be counted in the last bin, and not as an outlier. outliers = zeros(N, int) for i in arange(D): # Rounding precision decimal = int(-log10(dedges[i].min())) +6 # Find which points are on the rightmost edge. on_edge = where(around(sample[:,i], decimal) == around(edges[i][-1], decimal))[0] # Shift these points one bin to the left. Ncount[i][on_edge] -= 1 # Flattened histogram matrix (1D) hist = zeros(nbin.prod(), float) # Compute the sample indices in the flattened histogram matrix. ni = nbin.argsort() shape = [] xy = zeros(N, int) for i in arange(0, D-1): xy += Ncount[ni[i]] * nbin[ni[i+1:]].prod() xy += Ncount[ni[-1]] # Compute the number of repetitions in xy and assign it to the flattened histmat. if len(xy) == 0: return zeros(nbin-2, int), edges flatcount = bincount(xy, weights) a = arange(len(flatcount)) hist[a] = flatcount # Shape into a proper matrix hist = hist.reshape(sort(nbin)) for i in arange(nbin.size): j = ni[i] hist = hist.swapaxes(i,j) ni[i],ni[j] = ni[j],ni[i] # Remove outliers (indices 0 and -1 for each dimension). core = D*[slice(1,-1)] hist = hist[core] # Normalize if normed is True if normed: s = hist.sum() for i in arange(D): shape = ones(D, int) shape[i] = nbin[i]-2 hist = hist / dedges[i].reshape(shape) hist /= s return hist, edges
def polydiv(u, v): """ Returns the quotient and remainder of polynomial division. The input arrays are the coefficients (including any coefficients equal to zero) of the "numerator" (dividend) and "denominator" (divisor) polynomials, respectively. Parameters ---------- u : array_like or poly1d Dividend polynomial's coefficients. v : array_like or poly1d Divisor polynomial's coefficients. Returns ------- q : ndarray Coefficients, including those equal to zero, of the quotient. r : ndarray Coefficients, including those equal to zero, of the remainder. See Also -------- poly, polyadd, polyder, polydiv, polyfit, polyint, polymul, polysub, polyval Notes ----- Both `u` and `v` must be 0-d or 1-d (ndim = 0 or 1), but `u.ndim` need not equal `v.ndim`. In other words, all four possible combinations - ``u.ndim = v.ndim = 0``, ``u.ndim = v.ndim = 1``, ``u.ndim = 1, v.ndim = 0``, and ``u.ndim = 0, v.ndim = 1`` - work. Examples -------- .. math:: \\frac{3x^2 + 5x + 2}{2x + 1} = 1.5x + 1.75, remainder 0.25 >>> x = np.array([3.0, 5.0, 2.0]) >>> y = np.array([2.0, 1.0]) >>> np.polydiv(x, y) (array([ 1.5 , 1.75]), array([ 0.25])) """ truepoly = (isinstance(u, poly1d) or isinstance(u, poly1d)) u = atleast_1d(u) + 0.0 v = atleast_1d(v) + 0.0 # w has the common type w = u[0] + v[0] m = len(u) - 1 n = len(v) - 1 scale = 1. / v[0] q = NX.zeros((max(m - n + 1, 1),), w.dtype) r = u.astype(w.dtype) for k in range(0, m-n+1): d = scale * r[k] q[k] = d r[k:k+n+1] -= d*v while NX.allclose(r[0], 0, rtol=1e-14) and (r.shape[-1] > 1): r = r[1:] if truepoly: return poly1d(q), poly1d(r) return q, r
def gradient(f, *varargs): """Calculate the gradient of an N-dimensional scalar function. Uses central differences on the interior and first differences on boundaries to give the same shape. Inputs: f -- An N-dimensional array giving samples of a scalar function varargs -- 0, 1, or N scalars giving the sample distances in each direction Outputs: N arrays of the same shape as f giving the derivative of f with respect to each dimension. """ N = len(f.shape) # number of dimensions n = len(varargs) if n == 0: dx = [1.0]*N elif n == 1: dx = [varargs[0]]*N elif n == N: dx = list(varargs) else: raise SyntaxError, "invalid number of arguments" # use central differences on interior and first differences on endpoints outvals = [] # create slice objects --- initially all are [:, :, ..., :] slice1 = [slice(None)]*N slice2 = [slice(None)]*N slice3 = [slice(None)]*N otype = f.dtype.char if otype not in ['f', 'd', 'F', 'D']: otype = 'd' for axis in range(N): # select out appropriate parts for this dimension out = zeros(f.shape, f.dtype.char) slice1[axis] = slice(1, -1) slice2[axis] = slice(2, None) slice3[axis] = slice(None, -2) # 1D equivalent -- out[1:-1] = (f[2:] - f[:-2])/2.0 out[slice1] = (f[slice2] - f[slice3])/2.0 slice1[axis] = 0 slice2[axis] = 1 slice3[axis] = 0 # 1D equivalent -- out[0] = (f[1] - f[0]) out[slice1] = (f[slice2] - f[slice3]) slice1[axis] = -1 slice2[axis] = -1 slice3[axis] = -2 # 1D equivalent -- out[-1] = (f[-1] - f[-2]) out[slice1] = (f[slice2] - f[slice3]) # divide by step size outvals.append(out / dx[axis]) # reset the slice object in this dimension to ":" slice1[axis] = slice(None) slice2[axis] = slice(None) slice3[axis] = slice(None) if N == 1: return outvals[0] else: return outvals
def diag(v, k=0): """ Extract a diagonal or construct a diagonal array. Parameters ---------- v : array_like If `v` is a 2-D array, return a copy of its `k`-th diagonal. If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th diagonal. k : int, optional Diagonal in question. The default is 0. Use `k>0` for diagonals above the main diagonal, and `k<0` for diagonals below the main diagonal. Returns ------- out : ndarray The extracted diagonal or constructed diagonal array. See Also -------- diagonal : Return specified diagonals. diagflat : Create a 2-D array with the flattened input as a diagonal. trace : Sum along diagonals. triu : Upper triangle of an array. tril : Lower triange of an array. Examples -------- >>> x = np.arange(9).reshape((3,3)) >>> x array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.diag(x) array([0, 4, 8]) >>> np.diag(x, k=1) array([1, 5]) >>> np.diag(x, k=-1) array([3, 7]) >>> np.diag(np.diag(x)) array([[0, 0, 0], [0, 4, 0], [0, 0, 8]]) """ v = asarray(v) s = v.shape if len(s) == 1: n = s[0]+abs(k) res = zeros((n,n), v.dtype) if k >= 0: i = k else: i = (-k) * n res[:n-k].flat[i::n+1] = v return res elif len(s) == 2: if k >= s[1]: return empty(0, dtype=v.dtype) if v.flags.f_contiguous: # faster slicing v, k, s = v.T, -k, s[::-1] if k >= 0: i = k else: i = (-k) * s[1] return v[:s[1]-k].flat[i::s[1]+1] else: raise ValueError("Input must be 1- or 2-d.")
def polyint(p, m=1, k=None): """ Return an antiderivative (indefinite integral) of a polynomial. The returned order `m` antiderivative `P` of polynomial `p` satisfies :math:`\\frac{d^m}{dx^m}P(x) = p(x)` and is defined up to `m - 1` integration constants `k`. The constants determine the low-order polynomial part .. math:: \\frac{k_{m-1}}{0!} x^0 + \\ldots + \\frac{k_0}{(m-1)!}x^{m-1} of `P` so that :math:`P^{(j)}(0) = k_{m-j-1}`. Parameters ---------- p : array_like or poly1d Polynomial to differentiate. A sequence is interpreted as polynomial coefficients, see `poly1d`. m : int, optional Order of the antiderivative. (Default: 1) k : list of `m` scalars or scalar, optional Integration constants. They are given in the order of integration: those corresponding to highest-order terms come first. If ``None`` (default), all constants are assumed to be zero. If `m = 1`, a single scalar can be given instead of a list. See Also -------- polyder : derivative of a polynomial poly1d.integ : equivalent method Examples -------- The defining property of the antiderivative: >>> p = np.poly1d([1,1,1]) >>> P = np.polyint(p) >>> P poly1d([ 0.33333333, 0.5 , 1. , 0. ]) >>> np.polyder(P) == p True The integration constants default to zero, but can be specified: >>> P = np.polyint(p, 3) >>> P(0) 0.0 >>> np.polyder(P)(0) 0.0 >>> np.polyder(P, 2)(0) 0.0 >>> P = np.polyint(p, 3, k=[6,5,3]) >>> P poly1d([ 0.01666667, 0.04166667, 0.16666667, 3. , 5. , 3. ]) Note that 3 = 6 / 2!, and that the constants are given in the order of integrations. Constant of the highest-order polynomial term comes first: >>> np.polyder(P, 2)(0) 6.0 >>> np.polyder(P, 1)(0) 5.0 >>> P(0) 3.0 """ m = int(m) if m < 0: raise ValueError("Order of integral must be positive (see polyder)") if k is None: k = NX.zeros(m, float) k = atleast_1d(k) if len(k) == 1 and m > 1: k = k[0]*NX.ones(m, float) if len(k) < m: raise ValueError( "k must be a scalar or a rank-1 array of length 1 or >m.") truepoly = isinstance(p, poly1d) p = NX.asarray(p) if m == 0: if truepoly: return poly1d(p) return p else: # Note: this must work also with object and integer arrays y = NX.concatenate((p.__truediv__(NX.arange(len(p), 0, -1)), [k[0]])) val = polyint(y, m - 1, k=k[1:]) if truepoly: return poly1d(val) return val
def Solve(self): ''' This method builds System Matrix and gets Solution ''' if self.SimulationContext.Id != self.NetworkMesh.Id: raise self.SimulationContext.XMLIdError() try: self.TimeStep = self.SimulationContext.Context['timestep'] self.SquareTimeStep = self.TimeStep*self.TimeStep except KeyError: print "Error, Please set timestep in Simulation Context XML File" raise try: self.Period = self.SimulationContext.Context['period'] self.TimeStepFreq = int(self.Period/self.TimeStep) except KeyError: print "Error, Please set period in Simulation Context XML File" raise try: self.Cycles = self.SimulationContext.Context['cycles'] self.NumberOfIncrements = (self.Cycles*self.TimeStepFreq) except KeyError: print "Error, Please set cycles number in Simulation Context XML File" raise history = [] assembler = Assembler() assembler.SetNetworkMesh(self.NetworkMesh) assembler.SetBoundaryConditions(self.BoundaryConditions) info = {'dofmap':assembler.DofMap,'solution':None,'incrementNumber':self.IncrementNumber,'history':history} self.Evaluator.SetInfo(info) self.PrescribedPressures = assembler.AssembleBoundaryConditions(self.SimulationContext) self.LinearZeroOrderGlobalMatrix, self.LinearFirstOrderGlobalMatrix, self.LinearSecondOrderGlobalMatrix = \ assembler.AssembleInit(self.SimulationContext, self.Evaluator) self.ZeroOrderGlobalMatrix = assembler.ZeroOrderGlobalMatrix self.FirstOrderGlobalMatrix = assembler.FirstOrderGlobalMatrix self.SecondOrderGlobalMatrix = assembler.SecondOrderGlobalMatrix NumberOfGlobalDofs = assembler.GetNumberOfGlobalDofs() # number of dofs self.UnknownPressures = arange(0,NumberOfGlobalDofs).reshape(NumberOfGlobalDofs,1) # unknown pressures self.UnknownPressures = delete(self.UnknownPressures, s_[self.PrescribedPressures[:,0]], axis=0) PressuresMatrix = zeros((NumberOfGlobalDofs, self.NumberOfIncrements)) self.p = zeros((NumberOfGlobalDofs,1)) self.pt = zeros((NumberOfGlobalDofs,1)) self.ptt = zeros((NumberOfGlobalDofs,1)) self.dp = zeros((NumberOfGlobalDofs,1)) self.ddp = zeros((NumberOfGlobalDofs,1)) self.dpt = zeros((NumberOfGlobalDofs,1)) self.ddpt = zeros((NumberOfGlobalDofs,1)) self.fe = zeros((NumberOfGlobalDofs,1)) self.fet = zeros((NumberOfGlobalDofs,1)) self.dfe = zeros((NumberOfGlobalDofs,1)) self.dfet = zeros((NumberOfGlobalDofs,1)) self.fi = zeros((NumberOfGlobalDofs,1)) self.fit = zeros((NumberOfGlobalDofs,1)) self.sumv = zeros((NumberOfGlobalDofs,1)) sumvbk = zeros((NumberOfGlobalDofs,1)) nonLinear = False for el in self.NetworkMesh.Elements: if el.IsNonLinear() == True: nonLinear = True break while self.IncrementNumber<=self.NumberOfIncrements: icc = (self.IncrementNumber%self.TimeStepFreq) if icc == 0: icc = self.TimeStepFreq #for flow in self.BoundaryConditions.elementFlow: for el in self.BoundaryConditions.elementFlow: if self.steady == True: self.Flow = assembler.BoundaryConditions.GetSteadyFlow(el, self.TimeStep,icc*self.TimeStep) else: self.Flow = assembler.BoundaryConditions.GetTimeFlow(el, icc*self.TimeStep) self.fe[assembler.FlowDof[el.Id]]= self.Flow CoeffRelax = 0.9 nltol = self.nltol self.pi = None pI = None sumvbk[:,:] = self.sumv[:,:] counter = 0 while True: #Build the algebric equation system for the increment SystemMatrix = (2.0/self.TimeStep)*self.SecondOrderGlobalMatrix + self.FirstOrderGlobalMatrix + (self.TimeStep/2.0)*self.ZeroOrderGlobalMatrix #system matrix RightVector = self.fe + (2.0/self.TimeStep)*dot(self.SecondOrderGlobalMatrix,(self.pt)) + dot(self.SecondOrderGlobalMatrix,(self.dpt)) - dot(self.ZeroOrderGlobalMatrix,(self.sumv))-(self.TimeStep/2.0)*dot(self.ZeroOrderGlobalMatrix,(self.pt)) # right hand side vector #The reduced (partioned) system of equations is generated. RightVector[:,:] = RightVector[:,:] - dot(SystemMatrix[:,self.PrescribedPressures[:,0]],self.PrescribedPressures[:,1:]) SystemMatrix = SystemMatrix[:,s_[self.UnknownPressures[:,0]]] if SystemMatrix.shape[0]> 0.0: SystemMatrix = SystemMatrix[s_[self.UnknownPressures[:,0]],:] RightVector = RightVector[s_[self.UnknownPressures[:,0]],:] #Unknown nodal point values are solved from this system. # Prescribed nodal values are inserted in the solution vector. Solution = solve(SystemMatrix,RightVector) # solutions, unknown pressures self.p[self.UnknownPressures,0] = Solution[:,:] self.p[self.PrescribedPressures[:,0],0] = self.PrescribedPressures[:,1] #Calculating derivatives. #Calculating internal nodal flow values. self.dp = dot((2.0/self.TimeStep),(self.p-self.pt)) - self.dpt self.ddp = dot((4.0/self.SquareTimeStep),(self.p-self.pt)) - dot((4.0/self.TimeStep),self.dpt) -self.ddpt self.sumv = sumvbk + dot((self.TimeStep/2.0),(self.pt+self.p)) self.fi = dot(self.SecondOrderGlobalMatrix,(self.dp)) + dot(self.FirstOrderGlobalMatrix,(self.p)) + dot(self.ZeroOrderGlobalMatrix,(self.sumv)) if not nonLinear : break if self.pi is None: self.pi = zeros((NumberOfGlobalDofs,1)) self.pi[:,:] = self.pt[:,:] pI = CoeffRelax * self.p + self.pi * (1.0-CoeffRelax) self.p[:,:] = pI[:,:] den = norm(self.pi,Inf) if den < 1e-12: den = 1.0 nlerr = norm(self.p-self.pi,Inf) / den info = {'dofmap':assembler.DofMap,'solution':[self.p, self.pt, self.ptt],'incrementNumber':self.IncrementNumber,'history':history} self.Evaluator.SetInfo(info) assembler.Assemble(self.SimulationContext, self.Evaluator, self.LinearZeroOrderGlobalMatrix, self.LinearFirstOrderGlobalMatrix, self.LinearSecondOrderGlobalMatrix) self.ZeroOrderGlobalMatrix = assembler.ZeroOrderGlobalMatrix self.FirstOrderGlobalMatrix = assembler.FirstOrderGlobalMatrix self.SecondOrderGlobalMatrix = assembler.SecondOrderGlobalMatrix #Dynamic nonlinear relaxing coefficient if counter == 100: print "relaxing..." print nlerr, nltol, CoeffRelax counter = 0 self.pi[:,:] = None self.sumv[:,:] = sumvbk[:,:] CoeffRelax *= 0.6 nltol *= 0.95 if nlerr < nltol: nltol = self.nltol counter = 0 break counter+=1 self.pi[:,:] = self.p[:,:] self.ptt[:,:] = self.pt[:,:] self.pt[:,:] = self.p[:,:] self.dpt[:,:] = self.dp[:,:] self.ddpt[:,:] = self.ddp[:,:] self.fet[:,:] = self.fe[:,:] self.fit[:,:] = self.fi[:,:] PressuresMatrix[:,(self.IncrementNumber-1)] = self.p[:,0] history.insert(0,self.IncrementNumber) history = history[:3] if self.steady == True: self.MinimumIncrementNumber = 0.01* self.NumberOfIncrements if norm(self.fi-self.fe,Inf)<self.convergence and self.IncrementNumber > self.MinimumIncrementNumber: self.IncrementNumber = self.NumberOfIncrements else: pass if self.IncrementNumber==ceil(0.05*self.NumberOfIncrements): print "->5%" if self.IncrementNumber==ceil(0.25*self.NumberOfIncrements): print "->25%" if self.IncrementNumber==ceil(0.5*self.NumberOfIncrements): print "->50%" if self.IncrementNumber==ceil(0.70*self.NumberOfIncrements): print "->70%" if self.IncrementNumber==ceil(0.90*self.NumberOfIncrements): print "->90%" if self.IncrementNumber==ceil(0.99*self.NumberOfIncrements): print "->99%" self.IncrementNumber = self.IncrementNumber+1 self.EndIncrementTime = self.EndIncrementTime + self.TimeStep # increment info = {'dofmap':assembler.DofMap,'solution':[self.p, self.pt, self.ptt],'incrementNumber':self.IncrementNumber,'history':history,'allSolution':PressuresMatrix} self.Evaluator.SetInfo(info) self.Solutions = PressuresMatrix return PressuresMatrix
def mapNeighborhood(self, ngbhdAllowed): ngbhd = zeros(len(ngbhdAllowed), int) for i in arange(len(ngbhdAllowed)): ngbhd[i] = self.mapAllowedToAll(ngbhdAllowed[i], self.lbdAllowed) return ngbhd
def diag(v, k=0): """ Extract a diagonal or construct a diagonal array. See the more detailed documentation for ``numpy.diagonal`` if you use this function to extract a diagonal and wish to write to the resulting array; whether it returns a copy or a view depends on what version of numpy you are using. Parameters ---------- v : array_like If `v` is a 2-D array, return a copy of its `k`-th diagonal. If `v` is a 1-D array, return a 2-D array with `v` on the `k`-th diagonal. k : int, optional Diagonal in question. The default is 0. Use `k>0` for diagonals above the main diagonal, and `k<0` for diagonals below the main diagonal. Returns ------- out : ndarray The extracted diagonal or constructed diagonal array. See Also -------- diagonal : Return specified diagonals. diagflat : Create a 2-D array with the flattened input as a diagonal. trace : Sum along diagonals. triu : Upper triangle of an array. tril : Lower triangle of an array. Examples -------- >>> x = np.arange(9).reshape((3,3)) >>> x array([[0, 1, 2], [3, 4, 5], [6, 7, 8]]) >>> np.diag(x) array([0, 4, 8]) >>> np.diag(x, k=1) array([1, 5]) >>> np.diag(x, k=-1) array([3, 7]) >>> np.diag(np.diag(x)) array([[0, 0, 0], [0, 4, 0], [0, 0, 8]]) """ v = asanyarray(v) s = v.shape if len(s) == 1: n = s[0] + abs(k) res = zeros((n, n), v.dtype) if k >= 0: i = k else: i = (-k) * n res[:n - k].flat[i::n + 1] = v return res elif len(s) == 2: return diagonal(v, k) else: raise ValueError("Input must be 1- or 2-d.")
def myEnhance(self, img): self.img = img self.statx = zeros(256) print len(self.statx)
def apply_along_axis(func1d, axis, arr, *args): """ Apply a function to 1-D slices along the given axis. Execute `func1d(a, *args)` where `func1d` operates on 1-D arrays and `a` is a 1-D slice of `arr` along `axis`. Parameters ---------- func1d : function This function should accept 1-D arrays. It is applied to 1-D slices of `arr` along the specified axis. axis : integer Axis along which `arr` is sliced. arr : ndarray Input array. args : any Additional arguments to `func1d`. Returns ------- apply_along_axis : ndarray The output array. The shape of `outarr` is identical to the shape of `arr`, except along the `axis` dimension, where the length of `outarr` is equal to the size of the return value of `func1d`. If `func1d` returns a scalar `outarr` will have one fewer dimensions than `arr`. See Also -------- apply_over_axes : Apply a function repeatedly over multiple axes. Examples -------- >>> def my_func(a): ... \"\"\"Average first and last element of a 1-D array\"\"\" ... return (a[0] + a[-1]) * 0.5 >>> b = np.array([[1,2,3], [4,5,6], [7,8,9]]) >>> np.apply_along_axis(my_func, 0, b) array([ 4., 5., 6.]) >>> np.apply_along_axis(my_func, 1, b) array([ 2., 5., 8.]) For a function that doesn't return a scalar, the number of dimensions in `outarr` is the same as `arr`. >>> b = np.array([[8,1,7], [4,3,9], [5,2,6]]) >>> np.apply_along_axis(sorted, 1, b) array([[1, 7, 8], [3, 4, 9], [2, 5, 6]]) """ arr = asarray(arr) nd = arr.ndim if axis < 0: axis += nd if (axis >= nd): raise ValueError("axis must be less than arr.ndim; axis=%d, rank=%d." % (axis, nd)) ind = [0] * (nd - 1) i = zeros(nd, 'O') indlist = list(range(nd)) indlist.remove(axis) i[axis] = slice(None, None) outshape = asarray(arr.shape).take(indlist) i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())], *args) # if res is a number, then we have a smaller output array if isscalar(res): outarr = zeros(outshape, asarray(res).dtype) outarr[tuple(ind)] = res Ntot = product(outshape) k = 1 while k < Ntot: # increment the index ind[-1] += 1 n = -1 while (ind[n] >= outshape[n]) and (n > (1 - nd)): ind[n - 1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())], *args) outarr[tuple(ind)] = res k += 1 return outarr else: Ntot = product(outshape) holdshape = outshape outshape = list(arr.shape) outshape[axis] = len(res) outarr = zeros(outshape, asarray(res).dtype) outarr[tuple(i.tolist())] = res k = 1 while k < Ntot: # increment the index ind[-1] += 1 n = -1 while (ind[n] >= holdshape[n]) and (n > (1 - nd)): ind[n - 1] += 1 ind[n] = 0 n -= 1 i.put(indlist, ind) res = func1d(arr[tuple(i.tolist())], *args) outarr[tuple(i.tolist())] = res k += 1 return outarr