def _ang2xsys(z,phi): if sc.fabs(z) <= 2./3.: return [phi,3.*sc.pi/8.*z] else: phit= (phi % (sc.pi/2.)) sigz= bovy_healpy._sigma(z) return [phi-(sc.fabs(sigz)-1.)*(phit-sc.pi/4.),sc.pi/4.*sigz]
def rekernel(self): dcontrol = self.control[ord('d')] econtrol = self.control[ord('e')] rcontrol = self.control[ord('r')] radius = rcontrol.val dvalue = dcontrol.val evalue = econtrol.val rmax = rcontrol.limit[2] if self.rlast != radius: inner, outer = float(radius-1), float(radius) shape = (self.edge, self.edge) self.radii = list(product(arange(-rmax,rmax+1,1.0), repeat=2)) self.radii = array([sqrt(x*x+y*y) for x,y in self.radii]).reshape(shape) if True: self.negative = -exp(-dvalue*(self.radii-outer)**2) self.positive = +exp(-dvalue*(self.radii-inner)**2) else: self.radii = around(self.radii) self.negative = zeros((self.edge,self.edge),dtype=float) self.negative[self.radii == outer] = -1.0 self.positive = zeros(shape,dtype=float) self.positive[self.radii == inner] = +1.0 self.negative /= fabs(self.negative.sum()) self.positive /= fabs(self.positive.sum()) self.kernel = self.negative + self.positive self.rlast = radius if self.elast != evalue: self.gauss = exp(-evalue * self.radii**2) self.gauss /= self.gauss.sum() self.elast = evalue
def _ang2xsys(z, phi): if sc.fabs(z) <= 2. / 3.: return [phi, 3. * sc.pi / 8. * z] else: phit = (phi % (sc.pi / 2.)) sigz = bovy_healpy._sigma(z) return [ phi - (sc.fabs(sigz) - 1.) * (phit - sc.pi / 4.), sc.pi / 4. * sigz ]
def _xsys2ang(xs,ys): if sc.fabs(ys) <= sc.pi/4.: return [sc.arccos(8./3./sc.pi*ys),xs] else: xt= (xs % (sc.pi/2.)) fabsys= sc.fabs(ys) theta= sc.arccos((1.-1./3.*(2.-4.*fabsys/sc.pi)**2.)*ys/fabsys) if fabsys == sc.pi/2.: phi= xs-fabsys+sc.pi/4. else: phi= xs-(fabsys-sc.pi/4.)/(fabsys-sc.pi/2.)*(xt-sc.pi/4.) return [theta % (sc.pi+0.0000000001),phi % (2.*sc.pi)] #Hack
def _xsys2ang(xs, ys): if sc.fabs(ys) <= sc.pi / 4.: return [sc.arccos(8. / 3. / sc.pi * ys), xs] else: xt = (xs % (sc.pi / 2.)) fabsys = sc.fabs(ys) theta = sc.arccos( (1. - 1. / 3. * (2. - 4. * fabsys / sc.pi)**2.) * ys / fabsys) if fabsys == sc.pi / 2.: phi = xs - fabsys + sc.pi / 4. else: phi = xs - (fabsys - sc.pi / 4.) / (fabsys - sc.pi / 2.) * ( xt - sc.pi / 4.) return [theta % (sc.pi + 0.0000000001), phi % (2. * sc.pi)] #Hack
def nmoffat(x, p): n = (p.size - 1) / 4 value = scipy.zeros(x.size) value += p[0] for i in range(n): k = i * 4 amp = p[k + 1] cent = p[k + 2] fwhm = p[k + 3] b = scipy.fabs(p[k + 4]) a = 0.5 * fwhm / scipy.sqrt(scipy.power(2., 1. / b) - 1.) r = x - cent value += amp * scipy.power(1. + (r / a) * (r / a), -1. * b) p[k + 3] = scipy.fabs(p[k + 3]) return value
def get_initial_configurations(self, pose_st): ret_configurations = [] #propose all the destinations and the first alignments # for each of the first elements s_I = kNN_index(pose_st[0:2], transpose(self.start_poses)[0:2], 10); s_i = None for i in s_I: if(fabs(tklib_normalize_theta(self.start_poses[int(i)][2]-pose_st[2])) < pi/4.0): s_i = int(i) break; if(s_i == None): print "couldn't fine a candidate start location" return [] for d_i, dst in enumerate(self.dest_poses): #print "starting d_i=", d_i, 'of', len(self.dest_poses) if(tklib_euclidean_distance(dst[0:2], pose_st[0:2]) < 10e-5): continue start_confs = self.partitions[s_i][d_i].init_alignments(s_i, d_i) ret_configurations.extend(start_confs) return ret_configurations
def neo_p0(setup, *args): ntemps, nwalkers, nsteps = setup t = args[0] ndim = args[1] C = args[2] pos = sp.zeros((ntemps, nwalkers, ndim)) for temp in range(ntemps): for j in range(ndim): boundaries = t[C[j]].lims fact = sp.absolute(boundaries[0] - boundaries[1]) / nwalkers rnd = sp.random.uniform(0.9, 0.9999) dif = sp.arange(nwalkers) * fact * sp.random.uniform(0.9, 0.9999) if (t[C[j]].cv and t[C[j]].tag() != 'Period'): for i in range(nwalkers): pos[temp][i][j] = (boundaries[1] + 3 * boundaries[0]) / \ 4 + (dif[i] * 2. / 5. + fact / 2.0) elif t[C[j]].tag() == 'Jitter': jitt_ini = sp.sort(sp.fabs(sp.random.normal(0, 1, nwalkers))) * 0.1 dif = jitt_ini * sp.random.uniform(0.9, 0.9999) for i in range(nwalkers): pos[temp][i][j] = boundaries[0] + (dif[i] + fact / 2.0) pos[temp][i][j] *= 0.1 else: for i in range(nwalkers): pos[temp][i][j] = boundaries[0] + (dif[i] + fact / 2.0) return pos
def get_exog(N, num_nonconst_covariates, cor_length): """ Returns an exog array with correlations determined by cor_length. The covariance matrix of exog will have (asymptotically, as :math:'N\\to\\inf') .. math:: Cov[i,j] = \\exp(-|i-j| / cor_length) Higher cor_length makes the problem more ill-posed, and easier to screw up with noise. BEWARE: With very long correlation lengths, you often get a singular KKT matrix (during the l1_cvxopt_cp fit) """ ## Create the noiseless exog uncorrelated_exog = sp.randn(N, num_nonconst_covariates) if cor_length == 0: exog = uncorrelated_exog else: cov_matrix = sp.zeros( (num_nonconst_covariates, num_nonconst_covariates)) j = sp.arange(num_nonconst_covariates) for i in range(num_nonconst_covariates): cov_matrix[i, :] = sp.exp(-sp.fabs(i - j) / cor_length) chol = linalg.cholesky(cov_matrix) # cov_matrix = sp.dot(chol.T, chol) exog = sp.dot(uncorrelated_exog, chol) ## Return return exog
def get_exog(N, num_nonconst_covariates, cor_length): """ Returns an exog array with correlations determined by cor_length. The covariance matrix of exog will have (asymptotically, as :math:'N\\to\\inf') .. math:: Cov[i,j] = \\exp(-|i-j| / cor_length) Higher cor_length makes the problem more ill-posed, and easier to screw up with noise. BEWARE: With very long correlation lengths, you often get a singular KKT matrix (during the l1_cvxopt_cp fit) """ ## Create the noiseless exog uncorrelated_exog = sp.randn(N, num_nonconst_covariates) if cor_length == 0: exog = uncorrelated_exog else: cov_matrix = sp.zeros((num_nonconst_covariates, num_nonconst_covariates)) j = sp.arange(num_nonconst_covariates) for i in xrange(num_nonconst_covariates): cov_matrix[i, :] = sp.exp(-sp.fabs(i - j) / cor_length) chol = linalg.cholesky(cov_matrix) # cov_matrix = sp.dot(chol.T, chol) exog = sp.dot(uncorrelated_exog, chol) ## Return return exog
def test_both(): """signed and unsigned volumes should agree up to sign""" random.seed(0) #make tests repeatable for N in range(1,10): pts = rand(N+1,N) assert_almost_equal(fabs(signed_volume(pts)), unsigned_volume(pts))
def MethodeStochastique(x0, y0, pas, epsilon, maxiter): # initialisation erreur = 2. * epsilon x = x0 y = y0 i = 0 if (x == 0.0) and (y == 0.0): X = 0.0 Y = 0.0 maximum = 1.0 else: fmax = Fonction(x, y) fmax1 = fmax / 2.0 # boucle principale de calcul while ((erreur > epsilon) and (i < maxiter)): j = 0 # boucle de choix aléatoire du pas et de la direction de déplacement while (fmax1 <= fmax) and (j < nbtirages): x1 = x + pas * gauss(mu, sigma) y1 = y + pas * gauss(mu, sigma) fmax1 = Fonction(x1, y1) j += 1 if (fmax1 > fmax): x = x1 y = y1 erreur = fabs(fmax1 - fmax) fmax = fmax1 else: pas /= 2.0 i += 1 X = x Y = y maximum = fmax1 return (X, Y, maximum, i)
def MethodeGradientPF(x0, y0, pas, epsilon, maxiter): erreur = 2. * epsilon x = x0 y = y0 i = 0 if (x == 0.0) and (y == 0.0): X = 0.0 Y = 0.0 maximum = 1.0 else: fmax = Fonction(x, y) while ((erreur > epsilon) and (i < maxiter)): dx = Fonction(x + pas, y) - Fonction(x - pas, y) dy = Fonction(x, y + pas) - Fonction(x, y - pas) gradF = hypot(dx, dy) x1 = x + pas * dx / gradF y1 = y + pas * dy / gradF fmax1 = Fonction(x1, y1) if (fmax1 > fmax): x = x1 y = y1 erreur = fabs(fmax1 - fmax) fmax = fmax1 else: pas /= 2.0 i += 1 X = x Y = y maximum = fmax1 return (X, Y, maximum, i)
def save_fit_image(self, fname): """ Save image with border ==================== fname: name of the file to be saved """ A, B, x0, y0, sx, sy, theta = self._p sx, sy = scipy.fabs([sx, sy]) # First draw an upright ellipse shape = (self._shape[1], self._shape[0]) border = Image.new('L', shape, "black") draw = ImageDraw.Draw(border) bbox = ( y0-sy/2, x0-sx/2, y0+sy/2, x0+sx/2 ) draw.ellipse(bbox, outline='white') # Then rotate the ellipse around (x0, y0) with angle theta c, s = scipy.cos(theta), -scipy.sin(theta) matrix = ( c, -s, y0 * (1-c) + x0 * s, s, c, x0 * (1-c) - y0 * s ) border = border.transform(shape, Image.AFFINE, matrix) # Finally paste rescaled = (255.0 / self._orig_image.max() * self._orig_image).astype(scipy.uint8) new_img = Image.fromarray(rescaled) new_img.paste(border, new_img) new_img.save(fname)
def LyapunovFitFunc(p, traj_diff): """ Given a trajectory difference traj_diff and a tuple p = (lyapExponent, lyapLogPrefactor) returns the residuals log(|y_n|) - log( exp(lyapLogPrefactor + lyapExponent * n) ) The residual is the difference between the data and the fit: if the residuals were zero, the trajectory difference would be perfectly described as a growing exponential. That is, the growth of the difference between two trajectories is expected to be of the form |x_n - y_n| \sim lyapPrefactor * exp(lyapExponent n) We take the log of the difference so that the least--squares fit will emphasize the initial points and final points roughly equally. We use the log of the lyapPrefactor because it must be positive: it's a standard trick in nonlinear fitting to change variables like this to enforce ranges in parameters. Used by FitLyapunovExponent to generate a least-squares fit for the Lyapunov exponent and prefactor. """ lyapExponent, lyapLogPrefactor = p residuals = \ scipy.log(scipy.fabs(traj_diff)) - \ (lyapLogPrefactor + lyapExponent*scipy.arange(len(traj_diff))) return residuals
def unique_rows(A, tol=1e-13): ''' Find the unique rows of a matrix A given a tolerance Parameters: A [] Returns: tuple [] ''' duplicate_ks = [] for r1 in range(A.shape[0]): for r2 in range(r1 + 1, A.shape[0]): # check if row 1 is equal to row 2 to within tol if sp.all(sp.fabs(A[r1, :] - A[r2, :]) <= tol): # only add if row 2 has not already been added from a previous # pass if r2 not in duplicate_ks: duplicate_ks.append(r2) # generate a list of unique indices unique_ks = [idx for idx in range(A.shape[0]) if idx not in duplicate_ks] # return matrix of unique rows and associated indices return (A[unique_ks, :], unique_ks)
def jacob(a, b, x, y, order=4): """Calculation of relative area using the Jacobian | da_dx db_dx | Jacobian = | | | da_dy db_dy | Then the relative area is the absolute value of the determinant of the Jacobian. Parameters ---------- a set of polynomial coefficients converting from (x,y) to u b set of polynomial coefficients converting from (x,y) to v x x pixel position or array of x positions y y pixel position or array of y positions matching the y positions x and y will usually be Science coordinates while u and v are Ideal coordinates order: order of the polynomials Returns ------- area area in (u,v) coordinates matching unit area in the (x,y) coordinates. """ j = dpdx(a, x, y, order) * dpdy(b, x, y, order) - dpdx( b, x, y, order) * dpdy(a, x, y, order) area = sp.fabs(j) return area
def WriteFileX(X_L,WriteMax,de_dec,header,filename): ''' writes data arrays to file, writes multiple complex arrays at once X_L is a list of complex arrays, WriteMax is the cutoff in energies, de_dec is the density of the output and header is the header line ''' LN = len(X_L) f = open(filename,'w') f.write("# file written "+ctime()+'\n') f.write(header+'\n') line = '' for i in range(len(En_A)): if sp.fabs(En_A[i]) <= WriteMax and sp.fabs(En_A[i] - sp.around(En_A[i],de_dec)) == 0: line = '{0: .6f}\t'.format(float(En_A[i])) for k in range(LN): line += '{0: .6f}\t{1: .6f}\t'.format(float(sp.real(X_L[k][i])),float(sp.imag(X_L[k][i]))) f.write(line+'\n') f.close if chat: print('# File '+filename+' written.')
def nmodelfit(data, p, model, weight=0): if p.ndim == 2: if p.shape[0] == 2: p = p.T mask = p[:, 1].copy() t = scipy.zeros(mask.sum()) static = scipy.zeros(mask.size - t.size) j = 0 k = 0 for i in range(mask.size): if mask[i] > 0: t[j] = p[i, 0] j += 1 else: static[k] = p[i, 0] k += 1 p = t.copy() else: mask = scipy.ones(p.size) static = scipy.zeros(0) if data.ndim == 1: x = scipy.arange(0., data.size, 1.) z = data.copy() else: x = data[:, 0] z = data[:, 1] good = scipy.isfinite(z) x = x[good] z = z[good] pars, cov, info, mesg, ier = optimize.leastsq(domodel, p, args=(x, z, mask, static, model, weight), maxfev=10000, full_output=True) chi2 = info['fvec'] chi2 = chi2 * chi2 if weight == 0: chi2 /= abs(z) chi2 = chi2.sum() p = scipy.zeros(mask.size) j = 0 k = 0 for i in range(mask.size): if mask[i] > 0: p[i] = pars[j] j += 1 else: p[i] = static[k] k += 1 if i % 3 == 0: p[i] = scipy.fabs(p[i]) return p, chi2
def angle_bounds2(theta, phi): ''' Sets two spherical angles in bounds, -90<theta<90; 0<phi<360''' if type(theta) != type(arr): theta = sp.array([theta]) if type(phi) != type(arr): phi = sp.array([phi]) for i in range(len(theta)): theta[i] = angle_bounds(theta[i], -180.0, 180.0) for i in range(len(theta)): if sp.fabs(theta[i]) > 90.0: theta[i] = 180.0 - theta[i] phi[i] = phi[i] + 180.0 for i in range(len(theta)): theta[i] = angle_bounds(theta[i], -180.0, 180.0) phi[i] = angle_bounds(phi[i], 0.0, 360.0) for i in range(len(theta)): if (sp.fabs(theta[i]) == 90.0): phi[i] = 0.0 if len(theta) == 1: theta, phi = theta[0], phi[0] return theta, phi
def angle_bounds2 (theta, phi): """ Sets two spherical angles in bounds, -90<theta<90; 0<phi<360""" if type(theta) != type(arr): theta = sc.array([theta]) if type(phi) != type(arr): phi = sc.array([phi]) for i in range(len(theta)): theta[i] = angle_bounds(theta[i], -180.0, 180.0) for i in range(len(theta)): if sc.fabs(theta[i]) > 90.0: theta[i] = 180.0 - theta[i] phi[i] = phi[i] + 180.0 for i in range(len(theta)): theta[i] = angle_bounds(theta[i], -180.0, 180.0) phi[i] = angle_bounds(phi[i], 0.0, 360.0) for i in range(len(theta)): if (sc.fabs(theta[i]) == 90.0): phi[i] = 0.0 if len(theta)==1: theta, phi = theta[0], phi[0] return theta, phi
def show(arr, ax=None, cbar=True, **kwargs): if isinstance(arr, dict): lim = max(sp.fabs(a).max() for a in arr.values()) fig, axes = plt.subplots(1, len(arr)) for (k, v), ax in zip(arr.items(), axes): show(v, ax, vmin=-lim, vmax=lim, cbar=False) ax.set_title(k) return axes ax = plt.subplot() if ax is None else ax lim = sp.fabs(arr).max() kwargs = {'vmin': -lim, 'vmax': lim, 'cmap': 'RdBu', **kwargs} im = ax.imshow(arr, **kwargs) ax.set_xticks([]) ax.set_yticks([]) if cbar: plt.colorbar(im, fraction=.02) return ax
def PlotFit(traj_diff, p): """ Given a trajectory difference and p=(lyapExponent, lyapPrefactor), plot |traj_diff| and the fit on a semilog y axis. """ pylab.plot(scipy.fabs(traj_diff), 'b-', linewidth=4) fit = scipy.exp(p[1] + p[0] * scipy.arange(len(traj_diff))) pylab.semilogy(fit, 'r-', linewidth=2) pylab.show()
def DNL(k,muk,pk,q1,kv,av,bv,kp,model): dnl = 1 if model == "mcdonald": kvel = 1.22*(1+k/0.923)**0.451 dnl = sp.exp((k/6.4)**0.569-(k/15.3)**2.01-(k*muk/kvel)**1.5) elif model == "arinyo": growth = q1*k*k*k*pk/(2*sp.pi*sp.pi) pecvelocity = np.power(k/kv,av)*np.power(sp.fabs(muk),bv) pressure = (k/kp)*(k/kp) dnl = sp.exp(growth*(1-pecvelocity)-pressure) return dnl
def __init__(self, radial=1): self.radial = radial div1 = 1 + 2 * radial div2 = 1 if radial < 1 else 2 + 1.0 / radial seq = [0] if radial == 0 else scipy.linspace(-1.0, 1.0, div1) / div2 if len(seq) > 1: """Assert that the pickets are evenly spaced.""" one = 2 * seq[-1] + seq[1 + len(seq) / 2] epsilon = scipy.fabs(1.0 - one) assert epsilon < 1e-10 self.pickets = list(itertools.product(seq, repeat=2))
def gen_model(theta, time, MOAV, residuals): """Stellar moving average. In goes residuals, and out too! """ for i in range(len(time)): for c in range(MOAV): if i > c: MA = theta[2 * c] * sp.exp( -sp.fabs(time[i - 1 - c] - time[i]) / theta[2 * c + 1]) * residuals[i - 1 - c] residuals[i] -= MA return residuals
def absolute_distance(fingerprint1, fingerprint2): """Calculate absolute distance .. note: Length of fingerprints must be the same :param fingerprint1: List with numbers :param fingerprint2: List with numbers """ absolute_distance = 0 for i, cipher in enumerate(fingerprint1): absolute_distance += scipy.fabs(cipher-fingerprint2[i]) return absolute_distance
def stellar_moav(theta, time, star_moav, residuals): """Calculate the stellar moving average model.""" moav = sp.zeros_like(time) for i in range(len(time)): for c in range(star_moav): if i > c: dt = sp.fabs(time[i - 1 - c] - time[i]) timescale = theta[2 * c + 1] MA = theta[2 * c] * sp.exp(-dt / timescale) MA *= residuals[i - 1 - c] moav[i] = MA return moav
def dnl_arinyo(k, pk_lin, tracer1, tracer2, pk_fid, **kwargs): assert tracer1['name'] == "LYA" and tracer2['name'] == "LYA" q1 = kwargs["dnl_arinyo_q1"] kv = kwargs["dnl_arinyo_kv"] av = kwargs["dnl_arinyo_av"] bv = kwargs["dnl_arinyo_bv"] kp = kwargs["dnl_arinyo_kp"] growth = q1 * k * k * k * pk_fid / (2 * sp.pi * sp.pi) pecvelocity = sp.power(k / kv, av) * sp.power(sp.fabs(muk), bv) pressure = (k / kp) * (k / kp) dnl = sp.exp(growth * (1 - pecvelocity) - pressure) return dnl
def add_absorber(self,lambda_absorber): if not hasattr(self,'ll'): return w = np.ones(self.ll.size, dtype=bool) w &= sp.fabs(1.e4*(self.ll-np.log10(lambda_absorber)))>forest.absorber_mask ps = ['iv','ll','fl','T_dla','Fbar','mmef','diff','reso'] for p in ps: if hasattr(self,p) and (getattr(self,p) is not None): setattr(self,p,getattr(self,p)[w]) return
def add_absorber(self, lambda_absorber): if not hasattr(self, 'll'): return w = sp.ones(self.ll.size, dtype=bool) w &= sp.fabs( 1.e4 * (self.ll - sp.log10(lambda_absorber))) > forest.absorber_mask self.iv = self.iv[w] self.ll = self.ll[w] self.fl = self.fl[w] if self.diff is not None: self.diff = self.diff[w] self.reso = self.reso[w]
def PlotTrajectoryDifference(g, x1, x2, N): """ Calls TrajectoryDifference to find the difference, then plots the absolute value of the difference using pylab.semilogy(scipy.fabs(dx)). (Given just one array, pylab assumes the other axis is just the index into the array.) Notice that the differences stop growing when they become of order one (naturally). Don't use such long trajectories to calculate the Lyapunov exponents: it will bias the results downward. """ dx = TrajectoryDifference(g, x1, x2, N) pylab.semilogy(scipy.fabs(dx)) pylab.show()
def readbyu(self, byufile): with open(byufile,'r') as fbyu: ln0 = fbyu.readline() ln = ln0.split() # read header ncomponents = int(ln[0]) # number of components npoints = int(ln[1]) # number of vertices nfaces = int(ln[2]) # number of faces #fscanf(fbyu,'%d',1); % number of edges #%ntest = fscanf(fbyu,'%d',1); % number of edges for k in range(ncomponents): fbyu.readline() # components (ignored) # read data self.vertices = np.empty([npoints, 3]) k=-1 while k < npoints-1: ln = fbyu.readline().split() k=k+1 ; self.vertices[k, 0] = float(ln[0]) self.vertices[k, 1] = float(ln[1]) self.vertices[k, 2] = float(ln[2]) if len(ln) > 3: k=k+1 ; self.vertices[k, 0] = float(ln[3]) self.vertices[k, 1] = float(ln[4]) self.vertices[k, 2] = float(ln[5]) self.faces = np.empty([nfaces, 3]) ln = fbyu.readline().split() kf = 0 j = 0 while ln: if kf >= nfaces: break #print nfaces, kf, ln for s in ln: self.faces[kf,j] = int(sp.fabs(int(s))) j = j+1 if j == 3: kf=kf+1 j=0 ln = fbyu.readline().split() self.faces = np.int_(self.faces) - 1 xDef1 = self.vertices[self.faces[:, 0], :] xDef2 = self.vertices[self.faces[:, 1], :] xDef3 = self.vertices[self.faces[:, 2], :] self.centers = (xDef1 + xDef2 + xDef3) / 3 self.surfel = np.cross(xDef2-xDef1, xDef3-xDef1)
def _apply_bounds(self): ret = 0 for k,v in self.sim.get_model_params().iteritems(): if self.bounds[k][0] != None and v < self.bounds[k][0]: self.sim.set_model_param(k, self.bounds[k][0]) ret += scipy.fabs((self.bounds[k][0] - v) / self.bounds[k][0]) if self.verbose: print "itc_fit: Boundary violation for \"%s\" (%f<%f)"%(k,v,self.bounds[k][0]) elif self.bounds[k][1] != None and v > self.bounds[k][1]: self.sim.set_model_param(k, self.bounds[k][1]) ret += fabs((v - self.bounds[k][1]) / self.bounds[k][1]) if self.verbose: print "itc_fit: Boundary violation for \"%s\" (%f>%f)"%(k,v,self.bounds[k][1]) return ret
def CalculateHWHM(GF_A): ''' calculates the half-width at half-maximum of the Kondo resonance and the maximum of the spectral function ''' N = len(En_A) IntMin = int((N+1)/2-int(0.5/dE)) IntMax = int((N+1)/2+int(0.5/dE)) DOSmaxPos = sp.argmax(-sp.imag(GF_A[IntMin:IntMax])/sp.pi) DOSmax = -sp.imag(GF_A[IntMin+DOSmaxPos])/sp.pi # maximum of DoS wmax = En_A[IntMin+DOSmaxPos] # position of the maximum at energy axis DOS = InterpolatedUnivariateSpline(En_A-1e-12,-sp.imag(GF_A)/sp.pi-DOSmax/2.0) ## 1e-12 breaks symmetry for half-filling, otherway DOS.roots() loses one solution. DOSroots_A = sp.sort(sp.fabs(DOS.roots())) try: HWHM = (DOSroots_A[0] + DOSroots_A[1])/2.0 except IndexError: HWHM = 0.0 return [HWHM,DOSmax,wmax]
def _apply_bounds(self): ret = 0 for k, v in self.sim.get_model_params().items(): if self.bounds[k][0] != None and v < self.bounds[k][0]: self.sim.set_model_param(k, self.bounds[k][0]) ret += scipy.fabs((self.bounds[k][0] - v) / self.bounds[k][0]) if self.verbose: print("itc_fit: Boundary violation for \"%s\" (%f<%f)" % (k, v, self.bounds[k][0])) elif self.bounds[k][1] != None and v > self.bounds[k][1]: self.sim.set_model_param(k, self.bounds[k][1]) ret += fabs((v - self.bounds[k][1]) / self.bounds[k][1]) if self.verbose: print("itc_fit: Boundary violation for \"%s\" (%f>%f)" % (k, v, self.bounds[k][1])) return ret
def readCurve(self, infile): with open(infile,'r') as fbyu: ln0 = fbyu.readline() ln = ln0.split() # read header ncomponents = int(ln[0]) # number of components npoints = int(ln[1]) # number of vertices nfaces = int(ln[2]) # number of faces for k in range(ncomponents): fbyu.readline() # components (ignored) # read data self.vertices = np.empty([npoints, 2]) ; k=-1 while k < npoints-1: ln = fbyu.readline().split() k=k+1 ; self.vertices[k, 0] = float(ln[0]) self.vertices[k, 1] = float(ln[1]) if len(ln) > 2: k=k+1 ; self.vertices[k, 0] = float(ln[2]) self.vertices[k, 1] = float(ln[3]) self.faces = np.empty([nfaces, 2]) ln = fbyu.readline().split() kf = 0 j = 0 while ln: if kf >= nfaces: break #print nfaces, kf, ln for s in ln: self.faces[kf,j] = int(sp.fabs(int(s))) j = j+1 if j == 2: kf=kf+1 j=0 ln = fbyu.readline().split() self.faces = np.int_(self.faces) - 1 xDef1 = self.vertices[self.faces[:, 0], :] xDef2 = self.vertices[self.faces[:, 1], :] self.centers = (xDef1 + xDef2) / 2 #self.lenel = np.zeros(self.faces.shape[0], self.vertices.shape[1]) ; self.lenel = xDef2 - xDef1 ;
def angle_bounds3 (theta, phi, phi_max=360.0): """ Sets two spherical angles in bounds, 0<theta<180; (phi_max-360.0)<phi<phi_max""" phi_min = phi_max-360.0 if type(theta) != type(arr): theta = sc.array([theta]) if type(phi) != type(arr): phi = sc.array([phi]) for i in range(len(theta)): theta[i] = angle_bounds(theta[i], -180.0, 180.0) for i in range(len(theta)): if theta[i] < 0.0: theta[i] = -1.0*theta[i] phi[i] = phi[i] + 180.0 for i in range(len(theta)): theta[i] = angle_bounds(theta[i], -180.0, 180.0) phi[i] = angle_bounds(phi[i], phi_min, phi_max) for i in range(len(theta)): if (sc.fabs(theta[i]) == 180.0): phi[i] = 0.0 if len(theta)==1: theta, phi = theta[0], phi[0] return theta, phi
def inst_moav(theta, time, ins, nins, moav, residuals): """Calculate the instrumental moving average model.""" counter = 0 insmoav = sp.zeros_like(time) for i in range(nins): idx = ins == i time_ins = time[idx] for t in range(len(time_ins)): for c in range(moav[i]): th = theta[counter:counter + moav[i] * 2] if t > c: res = residuals[i - 1 - c] dt = sp.fabs(time_ins[t - 1 - c] - time_ins[t]) coeff = th[c].val timescale = th[c + 1].val MA = coeff * sp.exp(-dt / timescale) * res insmoav[i] = MA counter += moav[i] * 2 return insmoav
def _calc_fit_param(self): def gaussian(A, B, x0, y0, sx, sy, theta): """ Returns a gaussian function centered at (x0, y0) with stdev = (sx, sy), and rotated at angle theta """ c, s = scipy.cos(theta), scipy.sin(theta) def f(x, y): xx = (c * (x-x0) - s * (y-y0)) / sx yy = (s * (x-x0) + c * (y-y0)) / sy return A*scipy.exp( -(xx**2+yy**2)/2 ) + B return f def error(p): X, Y = scipy.indices(self._shape) g = gaussian(*p) return (g(X, Y) - self._orig_image).ravel() estimate = self._estimate_fit_param() p, cov, infodict, mesg, ier = optimize.leastsq(error, estimate, full_output=True) success = ier in [1,2,3,4] if not success: raise Gaussian2dFitError else: # Make sure sx and sy are positive p[4], p[5] = scipy.fabs([p[4], p[5]]) dof = self._orig_image.size - len(p) s_sq = (infodict['fvec']**2).sum() / dof cov = cov * s_sq return p, cov
def _mad(data, center=None, constant=None, axis=0): """calculate the median average deviation for multi channel input :param ndarray data: multi channeled input data [sample, channel] :param float|ndarray center: will be used to calculate the residual in X, if None use the median of X Default=None :param float constant: constant to bias the result, if None use the constant corresponding to a normal distribution Default=None :param int axis: axis to use for the median calculation Default=0 """ # init and check data = sp.asarray(data) ns, nc = data.shape center = sp.ones(nc) * (center or sp.median(data, axis=axis)) return (constant or NORM_PPF_CONST) * sp.median(sp.fabs(data - center), axis=axis)
calcSusc = bool(int(config.get('params','calcSusc'))) if config.has_option('params','GFmethod'): GFmethod = str(config.get('params','GFmethod')) ## I/O parameters if config.has_option('IO','WriteOutput'): chat = bool(int(config.get('IO','WriteOutput'))) if config.has_option('IO','WriteFileGreenF'): WriteGF = bool(int(config.get('IO','WriteFileGreenF'))) if config.has_option('IO','WriteFileVertex'): WriteVertex = bool(int(config.get('IO','WriteFileVertex'))) if config.has_option('IO','WriteDataFile'): WriteNpz = bool(int(config.get('IO','WriteDataFile'))) if config.has_option('IO','WriteMax'): WriteMax = sp.fabs(float(config.get('IO','WriteMax'))) if config.has_option('IO','WriteStep'): WriteStep = int(config.get('IO','WriteStep')) ########################################################### ## energy axis ############################################ ## RuntimeWarning: invalid value encountered in power: ## for KK we need range(N)**3, for large arrays it can hit the limit of ## 9223372036854775808 == 2**63 of signed int, then decrease number of energy points def FillEnergies(dE,N): """ returns the symmetric array of energies [Emin,Emin+dE,...,0,...,-Emin-dE,-Emin] of length N """ dE_dec = int(-sp.log10(dE)) En_A = sp.linspace(-(N-1)/2*dE,(N-1)/2*dE,N) return sp.around(En_A,dE_dec+2)
def hand_move_incremental(goalangles, maxincrement = None, anglethreshold = .01, currentfingerangs = None): verbose = 0 sentcommand = 0 #track which motors to move individually moveindmotors = scipy.array([1,1,1,1]) #how much are we trying to move by? if currentfingerangs == None: currentfingerangs = hand_get_finger_angles() currentfingerangs = scipy.array(currentfingerangs[0:4]) angdiffs = scipy.array(goalangles) - currentfingerangs if verbose: print "currentfingerangs:", ppdoublearray(currentfingerangs) print "angdiffs:", ppdoublearray(angdiffs) #don't move any motor by more than maxincrement in one step if maxincrement: posmove = hand_angleToPosition(1, maxincrement) #if all fingers are trying to bend by at least maxincrement, move them all at once if all(angdiffs[1:4] > maxincrement): if verbose: print "moving all fingers in by maxincrement" cmd = "GIC " + str(posmove) hand_send_raw_cmd(cmd) sentcommand = 1 moveindmotors[1:4] = [0,0,0] elif all(angdiffs[1:4] < -maxincrement): if verbose: print "moving all fingers out by maxincrement" cmd = "GIO " + str(posmove) hand_send_raw_cmd(cmd) sentcommand = 1 moveindmotors[1:4] = [0,0,0] #clip moves to at most maxincrement clipArrayMag(angdiffs, maxincrement) goalangles = list(angdiffs + currentfingerangs) if verbose: print "clipped goalangles:", ppdoublearray(goalangles) #if no max increment, and all fingers are trying to bend to the same place, also move them all at once else: if math.fabs(angdiffs[1]) > anglethreshold and not any(scipy.fabs(scipy.array(goalangles) - goalangles[1])[1:4] > anglethreshold): posmove = hand_angleToPosition(1, goalangles[1]) cmd = "GM " + str(posmove) hand_send_raw_cmd(cmd) sentcommand = 1 moveindmotors[1:4] = [0,0,0] if verbose: print "moving all fingers to angle %.3f"%goalangles[1] #only move joints that aren't already close to the goal moveindmotors[scipy.fabs(angdiffs)<anglethreshold] = 0 #if we're still moving all 4 motors, send all four angles as one command if all(moveindmotors): hand_set_all_finger_angles(goalangles) sentcommand = 1 if verbose: print "moving to goalangles:", ppdoublearray(goalangles) #otherwise, move the relevant motors one at a time else: if verbose: print "moveindmotors:", moveindmotors for motor in range(4): if moveindmotors[motor]: hand_set_finger_angle(motor, goalangles[motor]) sentcommand = 1 if verbose: print "moving motor", motor, "to angle %.3f"%goalangles[motor] return sentcommand
#/usr/bin/python import matplotlib.pyplot as plt import Classes.DM_structure as DM_structure import scipy import Classes.Gadget2 as Gadget2 FileName='Hq1e6_000' A = DM_structure.DM_structure(FileName) S = A.Snapshot R = scipy.sqrt( S.x**2 + S.y**2 + S.z**2 ) Beta = 0.05 S.vx *= scipy.sqrt(Beta) S.vy *= scipy.sqrt(Beta) S.vz *= scipy.sqrt(Beta) T = scipy.sum(0.5*S.m*(S.vx**2+S.vy**2+S.vz**2)) U = 0.5*scipy.sum(S.m*S.V) print 2*T/scipy.fabs(U) Gadget2.WriteGadget2(FileName + '_Beta' + str(Beta) , S ) print 'Created file',FileName + '_Beta' + str(Beta) #plt.semilogx() #plt.plot(R,S.V) #plt.show()
if chat: print('# calculating the fully static vertex at half-filling as a starting point:') GFzero_A = GFlambda(En_A) Bubble_A = TwoParticleBubble(GFzero_A,GFzero_A,'eh') Lambda0 = CalculateLambda(Bubble_A,GFzero_A,GFzero_A) if chat: print('# - Lambda0 = {0: .8f}'.format(Lambda0)) else: if chat: print('# Initial guess for Lambda: L(++) = {0: .6f}, L(+-) = {1: .6f}'.format(LppIn,LmpIn)) ######################################################## ## calculate filling of the thermodynamic Green function if chat: print('#\n# calculating the initial thermodynamic Green function:') [nTup,nTdn] = [0.5,0.5] [nTupOld,nTdnOld] = [1e8,1e8] k = 1 while any([sp.fabs(nTupOld-nTup) > epsn, sp.fabs(nTdnOld-nTdn) > epsn]): [nTupOld,nTdnOld] = [nTup,nTdn] if T == 0.0: nup_dens = lambda x: DensityLambda(ed+U/2.0*(x+nTdn-1.0)-h) - x ndn_dens = lambda x: DensityLambda(ed+U/2.0*(nTup+x-1.0)+h) - x else: nup_dens = lambda x: Filling(GFlambda(En_A-ed-U/2.0*(x+nTdn-1.0)+h)) - x ndn_dens = lambda x: Filling(GFlambda(En_A-ed-U/2.0*(nTup+x-1.0)-h)) - x nTup = brentq(nup_dens,0.0,1.0,xtol = epsn) nTdn = brentq(ndn_dens,0.0,1.0,xtol = epsn) if chat: print('# - - {0: 3d}: nUp: {1: .8f}, nDn: {2: .8f}'.format(k,nTup,nTdn)) k += 1 ## fill the Green functions GFTup_A = GFlambda(En_A-ed-U/2.0*(nTup+nTdn-1.0)+h) GFTdn_A = GFlambda(En_A-ed-U/2.0*(nTup+nTdn-1.0)-h)
def filter(x,cutoff = 0.5): return exp(-pow(scipy.fabs(real(x))/cutoff,2.0) )
def jacob(a, b, x, y, order): '''Calculation of Jacobean, or relative area''' j = dpdx(a, x, y, order) * dpdy(b, x, y, order) - dpdx( b, x, y, order) * dpdy(a, x, y, order) j = scipy.fabs(j) return j
SC = bool(int(config.get('params', 'SC'))) if config.has_option('params', 'FSC'): FSC = bool(int(config.get('params', 'FSC'))) ## I/O parameters if config.has_option('IO', 'WriteOutput'): chat = bool(int(config.get('IO', 'WriteOutput'))) if config.has_option('IO', 'WriteFileGreenF'): WriteGF = bool(int(config.get('IO', 'WriteFileGreenF'))) if config.has_option('IO', 'WriteFileVertex'): WriteVertex = bool(int(config.get('IO', 'WriteFileVertex'))) if config.has_option('IO', 'WriteDataFile'): WriteNpz = bool(int(config.get('IO', 'WriteDataFile'))) if config.has_option('IO', 'WriteMax'): WriteMax = sp.fabs(float(config.get('IO', 'WriteMax'))) if config.has_option('IO', 'WriteStep'): WriteStep = int(config.get('IO', 'WriteStep')) ########################################################### ## reading parameters from command line ################### if GFtype in ['sc', 'scinf']: ## superconducting model, run super_parquet.py U = float(argv[1]) DeltaS = float(argv[2]) GammaS = float(argv[3]) GammaN = float(argv[4]) P = float(argv[5]) T = eps = h = 0.0 Phi = P * sp.pi else: ## normal model, run siam_parquet.py or siam_static.py U = float(argv[1])
def Fonction(x, y): z = fabs(sinc(x) * sinc(y)) return z
def main(): if sys.platform=='darwin' or os.path.exists("/nomad"): s=nomad("/nomad") else: s=nomad("/nfs/slac/g/ki/ki19/des/nomad") print "Nomad loading from",s.get_dir() if 1==2: flist=s.all_cat_files() flist.reverse() for f in flist: print f data=s.load_cat(f) print " Loaded %d stars"%(len(data)) s.set_data(data) b,l=s.get_bl() cut1=scipy.fabs(b)>30 cut2=s.get_cut('R',15,'>') cut3=s.get_cut('R',19,'<') cut=cut1*cut2*cut3 print " Writing %d stars"%((cut1*cut2*cut3).sum()) s.rewrite_file(f,odir="/nomad2",cut=cut1*cut2*cut3) return if 1==1: print "Nomad loading from",s.get_dir() N=200 n=scipy.zeros(N) blist=scipy.zeros(N) i=-1 while (i<N-1): i+=1 dec=random.randrange(-20,90) ra=random.randrange(0,360) b,l=s.get_bl(ra=ra,dec=dec) #print "DEC=%6.1f RA=%7.1f b=%5.1f l=%5.1f"%(dec,ra,b,l) if math.fabs(b)<30: i-=1 continue tot=0 curdec=dec curra=ra # Load list of stars at RA, DEC s.load_cats(dec=curdec,ra=curra,radius=0.107) #print "#1",i,len(s.get_data()) # Cut on R>15 cut=s.get_cut('R',15,'>') data=s.apply_cut(cut) s.set_data(data) #print "#2",i,len(s.get_data()) # Cut on R<19 cut=s.get_cut('R',19,'<') data=s.apply_cut(cut) s.set_data(data) #print " #3",i,len(s.get_data()) tot+=len(s.get_data()) if 1==2: # Array of circle sizes to draw stars star_size=5.0+scipy.power(19-s.get_column('R'),3) # Draw stars s.plot(x="RA",y='DEC',s=star_size) n[i]=tot blist[i]=b print "Total",i,b,tot s.plot(y=n,x=blist) return s return for i in range(10): # Active area of 1 GFA is 0.006 deg sq # Active area of 6 GFA is 0.036 # Total area is equal to a circle with radius 0.107 degrees # Pi r^2 = 3 * 0.1 * 0.1 = 0.03 ra=random.randrange(0,360) dec=random.randrange(45,90) # Load list of stars at RA, DEC s.load_cats(dec=dec,ra=ra,radius=0.107) # Array of circle sizes to draw stars star_size=5.0+scipy.power(19-s.get_column('R'),3) # Draw stars s.plot(x="RA",y='DEC',s=star_size) break return s for dec in range(-90,91,10): files=s.dec_to_file(dec) #s.load_acc(files['acc']) s.load_cat(files['cat']) print dec,s.dec_to_file(dec)
def KondoTemperature(U,Gamma,en): ''' calculating Kondo temperature ''' if U!=0.0 and Gamma!=0.0: return sp.sqrt(U*Gamma/2.0)*sp.exp(-sp.pi*sp.fabs(U**2-4.0*en**2)/(8.0*U*Gamma)) else: return 0.0
def SpecHWHM(GFint_A): ''' Half-width at half-maximum of the spectral function ''' N = len(En_A) DOSF = -sp.imag(GFint_A[N/2])/sp.pi # value at Fermi energy DOS = InterpolatedUnivariateSpline(En_A,-sp.imag(GFint_A)/sp.pi-DOSF/2.0) return sp.amin(sp.fabs(DOS.roots()))
def stoich_subspace(Cf0s, stoich_mat): """ Compute the bounds of the stoichiometric subspace, S, from multiple feed points and a stoichoimetric coefficient matrix. Parameters: stoich_mat (n x d) array. Each row in stoich_mat corresponds to a component and each column corresponds to a reaction. Cf0s (M x n) matrix. Each row in Cf0s corresponds to an individual feed and each column corresponds to a component. Returns: S_attributes dictionary that contains the vertices stoichiometric subspace in extent and concentration space for individual feeds as well as overall stoichiometric subspace for multiple feeds. keys: all_Es vertices of the individual stoichiometric subspaces in extent space. all_Cs vertices of the individual stoichiometric subspaces in concentration space. all_Es_mat list of vertices of the overall stoichiometric subspace in extent space. all_Cs_mat list of vertices of the overall stoichiometric subspace in concentration space. hull_Es extreme vertices of the overall stoichiometric subspace in the extent space. hull_Cs extreme vertices of the overall stoichiometric subspace in concentration space. bounds bounds of the stoichiometric subspace in concentration space. """ # create an empty list of bounds/ axis_lims min_lims = [] max_lims = [] # to store stoichSubspace_attributes S_attributes = {} # to store vertices for each feed and stoich_mat in extent and # concentration space all_Es = [] all_Cs = [] # if user input is not a list, then convert into a list if not isinstance(Cf0s, list) and not Cf0s.shape[0] > 1 or not Cf0s.shape[1] > 1: # if not isinstance(Cf0s, list): # is Cf0s a matrix of feed(s), or just a single row/column vector? # if Cf0s.ndim == 1 or ((Cf0s.ndim == 2) and (Cf0s.shape[0] > 1 and Cf0s.shape[1] == 1) or (Cf0s.shape[0] == 1 and Cf0s.shape[1] > 1)): # put it in a list Cf0s = [Cf0s] for Cf0 in Cf0s: # loop through each feed point, Cf0, and check if it is a column vector # with ndim = 2, or a (L, ) array with ndim = 1 only if Cf0.ndim == 2: Cf0 = Cf0.flatten() # converts into (L,) # raise an error if the no. of components is inconsistent between # the feed and stoichiometric matrix if len(Cf0) != stoich_mat.shape[0]: raise Exception( "The number of components in the feed does not match the number of rows in the stoichiometric matrix.") # always treat stoich_mat as a matrix for consistency, convert if not if stoich_mat.ndim == 1: # converts a 'single rxn' row into column vector stoich_mat = stoich_mat.reshape((len(stoich_mat), 1)) # check if a single reaction or multiple reactions are occuring if stoich_mat.shape[1] == 1 or stoich_mat.ndim == 1: # if stoich_mat is (L,) array this'stoich_mat.shape[1]' raises an # error 'tuple out of range' # converts into (L,) stoich_mat = stoich_mat.flatten() # calculate the limiting requirements limiting = Cf0 / stoich_mat # only choose negative coefficients as these indicate reactants k = limiting < 0.0 # calc maximum extent based on limiting reactant and calc C # we take max() because of the negative convention of the limiting # requirements e_max = sp.fabs(max(limiting[k])) # calc the corresponding point in concentration space C = Cf0 + stoich_mat * e_max # form Cs and Es and return Cs = sp.vstack([Cf0, C]) Es = sp.array([[0., e_max]]).T else: # extent associated with each feed vector Es = con2vert(-stoich_mat, Cf0) # calc the corresponding point in concentration space Cs = (Cf0[:, None] + sp.dot(stoich_mat, Es.T)).T # vertices for each feed and stoich_mat in extent and concentration # space all_Es.append(Es) all_Cs.append(Cs) # stack vertices in one list and find the overall stoichiometric # subspace(convex hull) all_Es_mat = sp.vstack(all_Es) all_Cs_mat = sp.vstack(all_Cs) # compute the convexhull of the overall stoichiometric subspace # if n > d + 1, then hull_Cs is returned as the full list of vertices if len(Cf0) > rank(stoich_mat) + 1: # convexHull vertices are returned as the whole stack of points hull_Es = all_Es_mat hull_Cs = all_Cs_mat else: # convexHull vertices for the overall stoichiometric subspace in extent # space hull_all = scipy.spatial.ConvexHull(all_Es_mat) ks = hull_all.vertices hull_Es = all_Es_mat[ks, :] # convexHull vertices for the overall stoichiometric subspace in # concentration space hull_all = scipy.spatial.ConvexHull(all_Cs_mat) ks = hull_all.vertices hull_Cs = all_Cs_mat[ks, :] hull_Es = all_Es_mat hull_Cs = all_Cs_mat # no. of components N = stoich_mat.shape[0] # create a matrix of indices components = sp.linspace(0, N - 1, num=N) for i in components: # loop through each component and find the (min, max) => bounds of the # axis minMatrix = min(hull_Cs[:, i]) maxMatrix = max(hull_Cs[:, i]) # append limits into preallocated lists (min_lims, max_lims) min_lims.append(minMatrix) max_lims.append(maxMatrix) # stack them into an ndarray and flatten() into a row vector bounds = sp.vstack((min_lims, max_lims)).T bounds = bounds.flatten() # alternating min, max values # create a dictionary containing all the attributes of the stoich_subspace S_attributes = { 'all_Es': all_Es, 'all_Cs': all_Cs, 'all_Es_mat': all_Es_mat, 'all_Cs_mat': all_Cs_mat, 'hull_Es': hull_Es, 'hull_Cs': hull_Cs, 'bounds': bounds } return S_attributes
def calc_cstr_locus(Cf, rate_fn, NUM_PTS, axis_lims, tol=1e-6, N=2e4): ''' Brute-force CSTR locus solver using geometric CSTR colinearity condition between r(C) and (C - Cf). Parameters: Cf [] rate_fn [] NUM_PTS [] axis_lims [] tol Optional. Default value is 1e-6. N Optional. Default value is 2e4. Returns: cstr_cs A list of cstr effluent concentrations. cstr_ts CSTR residence times corresponding to cstr_cs. ''' Cs = Cf ts = [0.0] N = int(N) # block length while Cs.shape[0] < NUM_PTS: # update display print "%.2f%% complete..." % (float(Cs.shape[0]) / float(NUM_PTS) * 100.0) # generate random points within the axis limits in blocks of N points Xs = rand_pts(N, axis_lims) # loop through each point and determine if it is a CSTR point ks = [] for i, ci in enumerate(Xs): # calculate rate vector ri and mixing vector vi ri = rate_fn(ci, 1) vi = ci - Cf # normalise ri and vi vn = vi / scipy.linalg.norm(vi) rn = ri / scipy.linalg.norm(ri) # calculate colinearity between rn and vn if sp.fabs(sp.fabs(sp.dot(vn, rn) - 1.0)) <= tol: ks.append(i) # calc corresponding cstr residence time (based on 1st element) tau = vi[0] / ri[0] ts.append(tau) # append colinear points to current list of CSTR points Cs = sp.vstack([Cs, Xs[ks, :]]) # chop to desired number of points Cs = Cs[0:NUM_PTS, :] ts = sp.array(ts[0:NUM_PTS]) return Cs, ts