def calcCDF(sample,graph=0): """Example: Calculate a cumulative distribution function from a sample, using a specified set of bins. sSize= 100 mySample=sc.randn(sSize) Cdf = calcCDF(bins=myBins, sample=mySample) """ mySample=sc.copy(sample) mySample.sort() bins= sc.unique(mySample) nBins = len(bins) sSize= sc.float32(len(mySample)) #print(bins,nBins) #print(mySample,sSize) cdf = sc.zeros(nBins) for n in sc.arange(nBins): A= sc.where(mySample<bins[n])[0] cdf[n]=len(A)/sSize #print(cdf,cdf.sum()) f = sc.vectorize(lambda x : sc.interp(x, bins,cdf)) fInverse = sc.vectorize(lambda y: sc.interp(y,cdf, bins)) if graph: gr.figure() gr.plot(bins,cdf,'wo') #gr.plot(sample[30:-20],f(sample[30:-20]),'.') return f,fInverse
def expect_1s_1s(self, op1, op2, n1, n2, return_intermediates=False): """Computes the expectation value of two single site operators acting on two different sites. The result is < op1 op2 >. See expect_1s(). Requires n1 < n2. The state must be up-to-date -- see self.update()! Parameters ---------- op1 : ndarray or callable The first operator, acting on the first site. op2 : ndarray or callable The second operator, acting on the second site. n1 : int The site number of the first site. n2 : int The site number of the second site (must be > n1). return_intermediates : bool Whether to return results for intermediate sites. Returns ------- expval : complex128 or sequence of complex128 The expectation value (data type may be complex), or values if return_intermediates == True. """ if callable(op1): op1 = sp.vectorize(op1, otypes=[sp.complex128]) op1 = sp.fromfunction(op1, (self.q[n1], self.q[n1])) if callable(op2): op2 = sp.vectorize(op2, otypes=[sp.complex128]) op2 = sp.fromfunction(op2, (self.q[n2], self.q[n2])) d = n2 - n1 res = sp.zeros((d + 1), dtype=sp.complex128) lj = tm.eps_l_op_1s(self.l[n1 - 1], self.A[n1], self.A[n1], op1) if return_intermediates: res[0] = self.expect_1s(op1.dot(op1), n1) for j in range(1, d + 1): if return_intermediates or j == d: lj_op = tm.eps_l_op_1s(lj, self.A[n1 + j], self.A[n1 + j], op2) res[j] = m.adot(lj_op, self.r[n1 + j]) if j < d: lj = tm.eps_l_noop(lj, self.A[n1 + j], self.A[n1 + j]) if return_intermediates: return res else: return res[-1]
def expect_1s_1s(self, op1, op2, n1, n2, return_intermediates=False): """Computes the expectation value of two single site operators acting on two different sites. The result is < op1 op2 >. See expect_1s(). Requires n1 < n2. The state must be up-to-date -- see self.update()! Parameters ---------- op1 : ndarray or callable The first operator, acting on the first site. op2 : ndarray or callable The second operator, acting on the second site. n1 : int The site number of the first site. n2 : int The site number of the second site (must be > n1). return_intermediates : bool Whether to return results for intermediate sites. Returns ------- expval : complex128 or sequence of complex128 The expectation value (data type may be complex), or values if return_intermediates == True. """ if callable(op1): op1 = sp.vectorize(op1, otypes=[sp.complex128]) op1 = sp.fromfunction(op1, (self.q[n1], self.q[n1])) if callable(op2): op2 = sp.vectorize(op2, otypes=[sp.complex128]) op2 = sp.fromfunction(op2, (self.q[n2], self.q[n2])) d = n2 - n1 res = sp.zeros((d + 1), dtype=sp.complex128) lj = tm.eps_l_op_1s(self.l[n1 - 1], self.A[n1], self.A[n1], op1) if return_intermediates: res[0] = self.expect_1s(op1.dot(op1), n1) for j in xrange(1, d + 1): if return_intermediates or j == d: lj_op = tm.eps_l_op_1s(lj, self.A[n1 + j], self.A[n1 + j], op2) res[j] = m.adot(lj_op, self.r[n1 + j]) if j < d: lj = tm.eps_l_noop(lj, self.A[n1 + j], self.A[n1 + j]) if return_intermediates: return res else: return res[-1]
def setStateVars(self, stateVarList): # state var is the cake size self.m_cakeSize = stateVarList[0] # calculate the array of utilities that will be searched for the optimal value controlGrid = self.getControlGridList(stateVarList)[0] vectorized_utilityFn = scipy.vectorize(self.m_utilityFn) vectorized_nextVFn = scipy.vectorize(lambda c: self.m_PrevIterFn(self.m_cakeSize - c)) # u(c) + beta * V(cakeSize - c) newFnArray = vectorized_utilityFn(controlGrid) + self.m_beta * vectorized_nextVFn(controlGrid) mx.TestParamsArray.setFunctionArray1d(self, controlGrid, newFnArray)
def __init__(self, occs, nmax, L=None, m=None, fast=False, checkAtRest=True): """ Args: occs (list of ints): occupation number list nmax (int): wave number of the last element in occs fast (bool): a flag for when occs and nmax are all that are needed (see transformState in oscillators.py) checkAtRest (bool): a flag to check if the total momentum is zero For instance, State([1,0,1],nmax=1) is a state with one excitation in the n=-1 mode and one in the n=+1 mode. State([1,0,1],nmax=2), however, is a state with one excitation in the n=0 mode and one in the n=+2 mode. """ #assert m >= 0, "Negative or zero mass" #assert L > 0, "Circumference must be positive" self.occs = occs self.size = len(self.occs) self.nmax = nmax self.fast = fast if fast == True: return #make a list of ns of size running from nmax-occs.size+1 to nmax wavenum = scipy.vectorize(lambda i: i - self.size + self.nmax + 1)( range(self.size)) #compute the corresponding energies energies = scipy.vectorize(lambda k: omega(k, L, m))(wavenum) #and compute the sum of the ns, multiplied by the occupation numbers self.totalWN = (wavenum * self.occs).sum() if checkAtRest: if self.totalWN != 0: raise ValueError("State not at rest") if self.size == 2 * self.nmax + 1 and self.occs[::-1] == self.occs: self.__parityEigenstate = True else: self.__parityEigenstate = False self.L = L self.m = m self.energy = sum(energies * self.occs) #couldn't we just use the k function for this? IL self.momentum = (2. * pi / self.L) * self.totalWN
def calc_B_1s_diss(self,op,n): """Applies a single-site operator to a single site and returns the parameter tensor for that site after the change with the change in the norm of the state projected out. Parameters ---------- op : ndarray or callable The single-site operator. See self.expect_1s(). n: int The site to apply the operator to. """ if callable(op): op = sp.vectorize(op, otypes=[sp.complex128]) op = sp.fromfunction(op, (self.q[n], self.q[n])) newAn = sp.zeros_like(self.A[n]) for s in range(self.q[n]): for t in range(self.q[n]): newAn[s] += self.A[n][t] * op[s, t] r_nm1 = TDVP.tm.eps_r_noop(self.r[n], newAn, newAn) ev = mm.adot(self.l[n - 1], r_nm1) newAn -= ev * self.A[n] #norm-fixing return newAn
def expect_2s(self, op, n, AA=None): """Computes the expectation value of a nearest-neighbour two-site operator. The operator should be a q[n] x q[n + 1] x q[n] x q[n + 1] array such that op[s, t, u, v] = <st|op|uv> or a function of the form op(s, t, u, v) = <st|op|uv>. The state must be up-to-date -- see self.update()! Parameters ---------- op : ndarray or callable The operator array or function. n : int The leftmost site number (operator acts on n, n + 1). Returns ------- expval : floating point number The expectation value (data type may be complex) """ A = self.A[n] Ap1 = self.A[n + 1] if AA is None: AA = tm.calc_AA(A, Ap1) if callable(op): op = sp.vectorize(op, otypes=[sp.complex128]) op = sp.fromfunction(op, (A.shape[0], Ap1.shape[0], A.shape[0], Ap1.shape[0])) C = tm.calc_C_mat_op_AA(op, AA) res = tm.eps_r_op_2s_C12_AA34(self.r[n + 1], C, AA) return m.adot(self.l[n - 1], res)
def expect_3s(self, op, n): """Computes the expectation value of a nearest-neighbour three-site operator. The operator should be a q[n] x q[n + 1] x q[n + 2] x q[n] x q[n + 1] x q[n + 2] array such that op[s, t, u, v, w, x] = <stu|op|vwx> or a function of the form op(s, t, u, v, w, x) = <stu|op|vwx>. The state must be up-to-date -- see self.update()! Parameters ---------- op : ndarray or callable The operator array or function. n : int The leftmost site number (operator acts on n, n + 1, n + 2). Returns ------- expval : floating point number The expectation value (data type may be complex) """ A = self.A[n] Ap1 = self.A[n + 1] Ap2 = self.A[n + 2] AAA = tm.calc_AAA(A, Ap1, Ap2) if callable(op): op = sp.vectorize(op, otypes=[sp.complex128]) op = sp.fromfunction(op, (A.shape[0], Ap1.shape[0], Ap2.shape[0], A.shape[0], Ap1.shape[0], Ap2.shape[0])) C = tm.calc_C_3s_mat_op_AAA(op, AAA) res = tm.eps_r_op_3s_C123_AAA456(self.r[n + 2], C, AAA) return m.adot(self.l[n - 1], res)
def interp2d(qx, qy, qz): Vandermonde = sp.zeros((4, 4)) Vandermonde[:, 0] = 1 Vandermonde[:, 1] = qx Vandermonde[:, 2] = qy Vandermonde[:, 3] = qx * qy Vinv = sp.linalg.inv(Vandermonde) print 'Vandermonde\n', Vandermonde print print 'Vandermonde inverse official \n', Vinv Vinv = inverse(Vandermonde, 4) print 'Vandermonde inverse Gauss \n', Vinv V22 = sp.copy(Vinv.T) print 'Identity check' print sp.dot(Vinv, Vandermonde) print 'Transpose official' print V22 for i in range(3): for j in range(i + 1, 4): d = Vinv[i, j] Vinv[i, j] = Vinv[j, i] Vinv[j, i] = d print 'Index ranspose\n', Vinv print 'Check transpose\n', Vinv - V22 def SU2(x, y): RHS = sp.array([1, x, y, x * y]) b = sp.dot(Vinv, RHS) return sp.dot(b, qz.T) SU2 = sp.vectorize(SU2) return SU2
def simple_wf(): wf = WorkFlow() # declare docs: wf.docs = [ Doc("Testing advanced 1", "a b c c c d d d d e"), Doc("Testing advanced 2", "a a a a a b c c c d d d e e"), Doc("Testing advanced 3", "b b b b f f f f"), ] # declare preprocessing wf.title_index = [ doc.title for doc in wf.docs] wf.word_index = ['a', 'b', 'c', 'd', 'e', 'f'] # prepare tf matrix wf.count_matrix = array([ [1, 5, 0], #a [1, 1, 4], #b [3, 3, 0], #c [4, 3, 0], #d [1, 2, 0], #e [0, 0, 4], #f ]) count_to_tf = vectorize(math_utils.count_to_tf) wf.tf_mat = count_to_tf(wf.count_matrix) # prepare lidf vector: log of inverted df wf.n_docs = float(len(wf.docs)) wf.df_vec = array([2.0, 3.0, 2.0, 2.0, 2.0, 1.0]) wf.idf_vec = wf.n_docs / wf.df_vec wf.log_idf_vec = log(wf.idf_vec) wf.wieghts_mat = matrix(wf.tf_mat * wf.log_idf_vec[:,None]) return wf
def interp2d(qx, qy, qz): Vandermonde = sp.zeros((4,4)) Vandermonde[:,0] = 1 Vandermonde[:,1] = qx Vandermonde[:,2] = qy Vandermonde[:,3] = qx*qy Vinv = sp.linalg.inv(Vandermonde) print 'Vandermonde\n', Vandermonde print print 'Vandermonde inverse official \n', Vinv Vinv = inverse(Vandermonde, 4) print 'Vandermonde inverse Gauss \n', Vinv V22 = sp.copy(Vinv.T) print 'Identity check' print sp.dot(Vinv,Vandermonde) print 'Transpose official' print V22 for i in range(3): for j in range(i+1,4): d = Vinv[i,j] Vinv[i,j]= Vinv[j,i] Vinv[j,i]= d print 'Index ranspose\n', Vinv print 'Check transpose\n', Vinv-V22 def SU2(x,y): RHS = sp.array([1,x,y,x*y]) b = sp.dot(Vinv,RHS) return sp.dot(b,qz.T) SU2 = sp.vectorize(SU2) return SU2
def expect_1s(self, op, n): """Computes the expectation value of a single-site operator. The operator should be a q[n] x q[n] matrix or generating function such that op[s, t] or op(s, t) equals <s|op|t>. The state must be up-to-date -- see self.update()! Parameters ---------- op : ndarray or callable The operator. n : int The site number (1 <= n <= N). Returns ------- expval : floating point number The expectation value (data type may be complex) """ if callable(op): op = sp.vectorize(op, otypes=[sp.complex128]) op = sp.fromfunction(op, (self.q[n], self.q[n])) res = tm.eps_r_op_1s(self.r[n], self.A[n], self.A[n], op) return m.adot(self.l[n - 1], res)
def simple_wf(): wf = WorkFlow() # declare docs: wf.docs = [ Doc("Testing advanced 1", "a b c c c d d d d e"), Doc("Testing advanced 2", "a a a a a b c c c d d d e e"), Doc("Testing advanced 3", "b b b b f f f f"), ] # declare preprocessing wf.title_index = [doc.title for doc in wf.docs] wf.word_index = ['a', 'b', 'c', 'd', 'e', 'f'] # prepare tf matrix wf.count_matrix = array([ [1, 5, 0], #a [1, 1, 4], #b [3, 3, 0], #c [4, 3, 0], #d [1, 2, 0], #e [0, 0, 4], #f ]) count_to_tf = vectorize(math_utils.count_to_tf) wf.tf_mat = count_to_tf(wf.count_matrix) # prepare lidf vector: log of inverted df wf.n_docs = float(len(wf.docs)) wf.df_vec = array([2.0, 3.0, 2.0, 2.0, 2.0, 1.0]) wf.idf_vec = wf.n_docs / wf.df_vec wf.log_idf_vec = log(wf.idf_vec) wf.wieghts_mat = matrix(wf.tf_mat * wf.log_idf_vec[:, None]) return wf
def expect_2s(self, op, n): """Computes the expectation value of a nearest-neighbour two-site operator. The operator should be a q[n] x q[n + 1] x q[n] x q[n + 1] array such that op[s, t, u, v] = <st|op|uv> or a function of the form op(s, t, u, v) = <st|op|uv>. Parameters ---------- o : ndarray or callable The operator array or function. n : int The leftmost site number (operator acts on n, n + 1). """ A = self.get_A(n) Ap1 = self.get_A(n + 1) AA = tm.calc_AA(A, Ap1) if callable(op): op = sp.vectorize(op, otypes=[sp.complex128]) op = sp.fromfunction(op, (A.shape[0], Ap1.shape[0], A.shape[0], Ap1.shape[0])) C = tm.calc_C_mat_op_AA(op, AA) res = tm.eps_r_op_2s_C12_AA34(self.get_r(n + 1), C, AA) return mm.adot(self.get_l(n - 1), res)
def compute_estimator(self, svm, validation_set): """Compute least-square estimator for validation set""" val_set_dp = validation_set['dtp'] val_set_cl = validation_set['cl'] estimator = 0.0 validation_size = len(val_set_dp) print "Computing estimator with validation part..." val_output = svm.get_output_2d(val_set_dp) # Compute estimator diff = val_set_cl - val_output estimator = diff.dot(diff).sum() # See p. 183 estimator *= 1.0 * self.M / self.n classify_vect = s.vectorize(svm.classify_output) output_classes = classify_vect(val_output) diff_classes = output_classes - val_set_cl errors = s.count_nonzero(diff_classes) classified_correctly = validation_size - errors print "Classified correctly: %u/%u (%.2f%%)" % \ (classified_correctly, validation_size, 100.0 * classified_correctly / validation_size) return estimator
def expect_1s_diss(self, op, n): """Applies a single-site operator to a single site and returns the value after the change. In contrast to mps_gen.apply_op_1s, this routine does not change the state itself. Also, this does not perform self.update(). Parameters ---------- op : ndarray or callable The single-site operator. See self.expect_1s(). n: int The site to apply the operator to. """ if callable(op): op = sp.vectorize(op, otypes=[sp.complex128]) op = sp.fromfunction(op, (self.q[n], self.q[n])) newAn = sp.zeros_like(self.A[n]) for s in xrange(self.q[n]): for t in xrange(self.q[n]): newAn[s] += self.A[n][t] * op[s, t] return newAn
def plotprob(mean, variance): maxrange = 50 maxlim = 15 x = np.linspace(-maxlim, maxlim, maxrange) #points on the x axis simlen = int(1e5) #number of samples err = [] #declaring probability list pdf = [] #declaring pdf list h = 2 * maxlim / (maxrange - 1) n = np.random.normal(mean, variance, simlen) a = np.zeros(500) for i in range(0, maxrange): err_ind = np.nonzero(n < x[i]) #checking probability condition err_n = np.size(err_ind) #computing the probability err.append(err_n / simlen) #storing the probability values in a list for i in range(0, maxrange - 1): test = (err[i + 1] - err[i]) / (x[i + 1] - x[i]) pdf.append(test) #storing the pdf values in a list def gauss_pdf(x): return 1 / mp.sqrt(2 * np.pi * variance) * np.exp(-(x - mean)**2 / (2.0 * variance)) vec_gauss_pdf = scipy.vectorize(gauss_pdf) plt.plot(x, vec_gauss_pdf(x)) #plotting the CDF plt.grid() #creating the grid plt.xlabel('$x_i$') plt.ylabel('$p_X(x_i)$') plt.legend(["Numerical", "Theory"]) plt.show() #opening the plot window
def classify_2d(self, xs): """Classify array of data points, return an array of 1 and -1""" size = len(xs) output = self.get_output_2d(xs) classify_vect = s.vectorize(self.classify_output) output_classes = classify_vect(output) return output_classes
def parse_eq(eq: str) -> vectorize: parsed = eq a = Equations.__wrong_power.findall(parsed) for e in a: ne = e[0] + '*' + e[1] parsed = parsed.replace(e, ne) return vectorize(make_fun_stable(eval('lambda x: ' + parsed)))
def apply_op_1s(self, op, n, do_update=True): """Applies a single-site operator to a single site. By default, this performs self.update(), which also restores state normalization. Parameters ---------- op : ndarray or callable The single-site operator. See self.expect_1s(). n: int The site to apply the operator to. do_update : bool Whether to update after applying the operator. """ if callable(op): op = sp.vectorize(op, otypes=[sp.complex128]) op = sp.fromfunction(op, (self.q[n], self.q[n])) newAn = sp.zeros_like(self.A[n]) for s in xrange(self.q[n]): for t in xrange(self.q[n]): newAn[s] += self.A[n][t] * op[s, t] self.A[n] = newAn if do_update: self.update()
def expect_1s_diss(self,op,n): """Applies a single-site operator to a single site and returns the value after the change. In contrast to mps_gen.apply_op_1s, this routine does not change the state itself. Also, this does not perform self.update(). Parameters ---------- op : ndarray or callable The single-site operator. See self.expect_1s(). n: int The site to apply the operator to. """ if callable(op): op = sp.vectorize(op, otypes=[sp.complex128]) op = sp.fromfunction(op, (self.q[n], self.q[n])) newAn = sp.zeros_like(self.A[n]) for s in xrange(self.q[n]): for t in xrange(self.q[n]): newAn[s] += self.A[n][t] * op[s, t] return newAn
def demodulate_qpsk(num_bits, snrdb): num_bits = int(num_bits) bits = np.random.randint(2, size=2 * num_bits) qpsk_bits1 = qpsk1(bits, 2 * num_bits) # qpsk symbols generation noise = scipy.vectorize(complex) noise = noise( (np.random.normal(0, np.sqrt(10**(-snrdb * 0.1)), num_bits)) / np.sqrt(2), (np.random.normal(0, np.sqrt(10**(-snrdb * 0.1)), num_bits)) / np.sqrt(2)) qpsk_bits = qpsk_bits1 + noise bits_hat = [] for i in range(len(qpsk_bits)): var = np.angle(qpsk_bits[i]) if var >= 0 and var < np.pi / 2: bits_hat.append(complex(1, 1)) elif var >= np.pi / 2 and var < np.pi: bits_hat.append(complex(-1, 1)) elif var >= -np.pi and var < (-1 * np.pi) / 2: bits_hat.append(complex(-1, -1)) elif var >= (-1 * np.pi) / 2 and var < 0: bits_hat.append(complex(1, -1)) # decoding part bits_hat[i] = bits_hat[i] / np.sqrt(2) difference = 0 for i in range(0, num_bits): if bits_hat[i] != qpsk_bits1[i]: difference = difference + 1 return difference / (1.0 * num_bits)
def solveTransistor(t_values, V_values, R, C, Js, T): voltage = interpolate.interp1d(t_values, V_values) def integrand(t): return voltage(t) * sp.exp(2*t/(R*C)) #We need to firstly solve the top section of the circuit. All that needs to be done is computing the RHS integral. def q(t): return sp.exp(-2*t/(R*C))/R * quad(integrand, 0, t)[0] q = sp.vectorize(q) # Allow q(t) to take arrays as input #Solve the ODE q_values = q(t_values) #Now we must consider the transistor def V1(t): return voltage(t) - q(t) / C def transJ(t): return Js * (sp.exp(e*V1(t)/(kB*T)) - sp.exp(e*(V1(t)-voltage(t))/(kB*T))) V1_values = V1(t_values) J_values = transJ(t_values) return q_values, V1_values, J_values
def relabel_map(label_image, mapping, key=lambda x, y: x[y]): """ Relabel an image using the supplied mapping. The mapping can be any kind of subscriptable object. The respective region id is used to access the new value from the mapping. The key keyword parameter can be used to supply another access function. The key function must have the signature key(mapping, region-id) and return the new region-id to assign. @param label_image A nD label_image @type label_image sequence @param mapping A mapping object @type mapping subscriptable object @return A binary image @rtype numpy.ndarray @raise ArgumentError If a region id is missing in the supplied mapping """ label_image = scipy.array(label_image) def _map(x): try: return key(mapping, x) except Exception as e: raise ArgumentError('No conversion for region id {} found in the supplied mapping. Error: {}'.format(x, e)) vmap = scipy.vectorize(_map, otypes=[label_image.dtype]) return vmap(label_image)
def normalizeHistogram(data): histogram = scipy.ndimage.histogram(data.astype("f"), 0, 255, 256) cumulatedHistogram = scipy.cumsum(histogram) nch = cumulatedHistogram.astype("f")/len(data.flat) inch = (nch*255).astype("i") normalize = scipy.vectorize(lambda i: inch[i]) return normalize(data)
def calc_B_1s_diss(self, op, n): """Applies a single-site operator to a single site and returns the parameter tensor for that site after the change with the change in the norm of the state projected out. Parameters ---------- op : ndarray or callable The single-site operator. See self.expect_1s(). n: int The site to apply the operator to. """ if callable(op): op = sp.vectorize(op, otypes=[sp.complex128]) op = sp.fromfunction(op, (self.q[n], self.q[n])) newAn = sp.zeros_like(self.A[n]) for s in xrange(self.q[n]): for t in xrange(self.q[n]): newAn[s] += self.A[n][t] * op[s, t] r_nm1 = TDVP.tm.eps_r_noop(self.r[n], newAn, newAn) ev = mm.adot(self.l[n - 1], r_nm1) newAn -= ev * self.A[n] #norm-fixing return newAn
def fit_cambridge(self, t, vmax, nc, k): if nc < 0 or nc > 10 or k < 0 or k > 1e12: return 0 ins = (nc * k * self.mtot**nc)**0.5 try: outs = scipy.vectorize(math.cosh)(ins * t) except OverflowError, e: return 0
def expect_1s_1s(self, op1, op2, d): """Computes the expectation value of two single site operators acting on two different sites. The result is < op1_n op2_n+d > with the operators acting on sites n and n + d. See expect_1s(). Requires d > 0. The state must be up-to-date -- see self.update()! Parameters ---------- op1 : ndarray or callable The first operator, acting on the first site. op2 : ndarray or callable The second operator, acting on the second site. d : int The distance (number of sites) between the two sites acted on non-trivially. Returns ------- expval : floating point number The expectation value (data type may be complex) """ assert d > 0, 'd must be greater than 1' if callable(op1): op1 = sp.vectorize(op1, otypes=[sp.complex128]) op1 = sp.fromfunction(op1, (self.q, self.q)) if callable(op2): op2 = sp.vectorize(op2, otypes=[sp.complex128]) op2 = sp.fromfunction(op2, (self.q, self.q)) r_n = tm.eps_r_op_1s(self.r, self.A, self.A, op2) for n in xrange(d - 1): r_n = tm.eps_r_noop(r_n, self.A, self.A) r_n = tm.eps_r_op_1s(r_n, self.A, self.A, op1) return m.adot(self.l, r_n)
def funapprox(self, f): """Polynomial approximation of a function""" c = self.funfitf(f) basis = self.basis def fhat(x): return sum([ cj * phi(self._trans(x)) for phi, cj in zip(basis, c)]) return sp.vectorize(fhat)
def expect_1s_1s(self, op1, op2, n1, n2): """Computes the expectation value of two single site operators acting on two different sites. The result is < op1 op2 >. See expect_1s(). Requires n1 < n2. The state must be up-to-date -- see self.update()! Parameters ---------- op1 : ndarray or callable The first operator, acting on the first site. op2 : ndarray or callable The second operator, acting on the second site. n1 : int The site number of the first site. n2 : int The site number of the second site (must be > n1). Returns ------- expval : floating point number The expectation value (data type may be complex) """ if callable(op1): op1 = sp.vectorize(op1, otypes=[sp.complex128]) op1 = sp.fromfunction(op1, (self.q[n1], self.q[n1])) if callable(op2): op2 = sp.vectorize(op2, otypes=[sp.complex128]) op2 = sp.fromfunction(op2, (self.q[n2], self.q[n2])) r_n = tm.eps_r_op_1s(self.r[n2], self.A[n2], self.A[n2], op2) for n in reversed(xrange(n1 + 1, n2)): r_n = tm.eps_r_noop(r_n, self.A[n], self.A[n]) r_n = tm.eps_r_op_1s(r_n, self.A[n1], self.A[n1], op1) return m.adot(self.l[n1 - 1], r_n)
def _convert_snps_to_binary(self,reference_ecotype='6909'): missingVal = 'NA' decoder = {missingVal:-1} #Might cause errors somewhere???!!! coding_fun = scipy.vectorize(lambda x: decoder[x], otypes=['int8']) if reference_ecotype in self.accessions: ref_i = self.accessions.index(reference_ecotype) else: ref_i = 0 log.warning("Given reference ecotype %s wasn't found, using %s as 0-reference." % \ (reference_ecotype, self.accessions[ref_i])) snps = [] num = len(self.positions) positions = [] chr_region_removed_snps = [0] * len(self.chr_regions) for snp_i, (snp, pos) in enumerate(itertools.izip(self._snps, self.positions)): chr_region_ix,chr_region = self.get_chr_region_from_index(snp_i) if snp_i % (num / 10) == 0: log.info('Converted %s/%s of SNPs.' % (snp_i,num)) unique_nts = scipy.unique(snp).tolist() if missingVal in unique_nts: if len(unique_nts) != 3: chr_region_removed_snps[chr_region_ix] +=1 continue #Skipping non-binary SNP else: unique_nts.remove(self.missingVal) else: if len(unique_nts) != 2: chr_region_removed_snps[chr_region_ix] +=1 continue #Skipping non-binary SNP if snp[ref_i] != missingVal: ref_nt = snp[ref_i] decoder[ref_nt] = 0 unique_nts.remove(ref_nt) decoder[unique_nts[0]] = 1 else: decoder[unique_nts[0]] = 0 decoder[unique_nts[1]] = 1 snps.append(coding_fun(snp)) positions.append(pos) log.info('Removed %d non-binary SNPs out of %d, when converting to binary SNPs.'\ % (len(self.positions) - len(positions), len(self.positions))) assert len(snps) == len(positions), 'Somthing odd with the lengths.' chr_regions = self.chr_regions[:] sum_removed_snps = 0 for i,num_snps in enumerate(chr_region_removed_snps): sum_removed_snps +=num_snps if i == 0: chr_regions[0] = (0,chr_regions[0][1] - num_snps) else: chr_regions[i] = (chr_regions[i-1][1],chr_regions[i][1] - sum_removed_snps) self._chr_regions = chr_regions self._snps = snps self._positions = positions self._data_format = 'binary'
def ber(numbits, snrdb): num_bits = int(numbits) bits = np.random.randint(2, size=2 * num_bits) qpsk_bits = qpsk1(bits, 2 * num_bits) # qpsk symbols generation os = 8 bits_os = [] for i in range(0, num_bits): bits_os.append(qpsk_bits[i]) for j in range(0, os - 1): bits_os.append(0) output_of_srrc_filterr = np.convolve(bits_os, p) # pulse shaping # noise = np.random.normal(0,np.sqrt(10**(-snrdb*0.1)),len(output_of_srrc_filterr)) noise = scipy.vectorize(complex) noise = noise( (np.random.normal(0, np.sqrt(10**(-snrdb * 0.1)), len(output_of_srrc_filterr))) / np.sqrt(2), (np.random.normal(0, np.sqrt(10**(-snrdb * 0.1)), len(output_of_srrc_filterr))) / np.sqrt(2)) for i in range(0, len(output_of_srrc_filterr)): output_of_srrc_filterr[i] = output_of_srrc_filterr[i] + noise[i] y = np.convolve(output_of_srrc_filterr, p) # matched filtering y_truncated = y[len(t) - 1:len( y)] #This number 65 will change is oversampling rate is changed y_down = [] for i in range(0, num_bits): y_down.append(y_truncated[0 + 8 * i]) bits_hat = [] # recovered bits. difference = 0 # for i in range(0, num_bits): # if (y_down[i]>0 and bits[i]==0 ) or (y_down[i]<0 and bits[i]==1 ) : # difference = difference+1 for i in range(len(y_down)): var = np.angle(y_down[i]) if var >= 0 and var < np.pi / 2: bits_hat.append(complex(1, 1)) elif var >= np.pi / 2 and var < np.pi: bits_hat.append(complex(-1, 1)) elif var >= -np.pi and var < (-1 * np.pi) / 2: bits_hat.append(complex(-1, -1)) elif var >= (-1 * np.pi) / 2 and var < 0: bits_hat.append(complex(1, -1)) # decoding part bits_hat[i] = bits_hat[i] / np.sqrt(2) for i in range(0, num_bits): if bits_hat[i] != qpsk_bits[i]: difference = difference + 1 #print "bits="+str(num_bits)+" snrdb="+str(snrdb)+" difference="+str(difference) return difference / (1.0 * num_bits)
def __init__(self, type, slen=4, alen=1, lexsize=256): """ Initialize an agent with an exhaustive lexicon made up of 4-vowel stems (TODO: incorporate consonants, affixes & variable word-lengths) """ # vowels {i,u,e,o} in articulatory features (hi, bk, rd) \in {-1,0,1} self.vowels = N.array(((1.0, 0.0, 0.0), (1.0, 1.0, 0.0), (0.0, 0.0, 0.0), (0.0, 1.0, 0.0))) self.vf = {(1.0, 0.0, 0.0): "i", (1.0, 1.0, 0.0): "u", (0.0, 0.0, 0.0): "e", (0.0, 1.0, 0.0): "o"} self.consonants = list("bcdfghjklmnpqrstvwxyz") # acoustic:articulatory mapping fxn for vowel prototypes # acoustic reps are F1,F2' pairs, articulatory reps are feature-based self.vowel_map = {} self.vowel_spread = 0 self.memory = N.empty((lexsize, slen, 2)) # each agent has its own articulatory variability #TODO: maybe this should be inferred by the learners # on the basis of their data? self.alpha = N.random.normal(15, 2) self.beta = N.random.normal(2, 0.25) if self.beta < 1.0: self.beta = 1.1 if type == "learner": self.stems = N.empty((lexsize, 4, 3), dtype=float) #self.affixes = N.empty((1,4)) elif type == "speaker": tmp = [[x, y, 0.0] for x in [0.0, 1.0] for y in [0.0, 1.0]] self.stems = N.array([[a, b, c, d] for a in tmp for b in tmp for c in tmp for d in tmp]) else: sys.exit("Undefined agent type. Aborting.") # vectorized versions of some fxns self.vec_perceive = vectorize(self.perceive) self.vec_articulate = vectorize(self.articulate) self.vec_acoustify = vectorize(self.acoustify)
def sign(v) : """Elementwise sign function. Arguments: v -- Input (scipy.array) Return: A scipy.array 'r' such that r_i = cmp(v_i, 0). """ return scipy.vectorize(lambda x : cmp(x, 0))(v)
def pm(m, digits=5): def get_digits(x): if x == 0: return 0 return int(math.log(abs(x) * 10.0, 10.0)) vd = scipy.vectorize(get_digits) dm = vd(m) widths = dm.max(0) (l, c) = m.shape for i in xrange(l): EigenBase.pv(m[i, :], digits=digits, left_digits=widths)
def chebyshev_vec(values, degree=1): """Calculate the Chebyshev Polynobials This implementation uses sp.vectorize to vectorize python's math functions)""" values = sp.asarray(values) A = sp.zeros((degree, len(values))) A[0,:]=1 try: A[1,:]=values except IndexError: return A cos = sp.vectorize(sp.math.cos) acos = sp.vectorize(sp.math.acos) for i in range(2,degree): A[i,:] = cos(i*acos(values)) return A
def pm(m, digits=5): def get_digits(x): if x == 0: return 0 return int(math.log(abs(x) * 10.0, 10.0)) vd = scipy.vectorize(get_digits) dm = vd(m) widths = dm.max(0) (l, c) = m.shape for i in xrange(l): EigenBase.pv(m[i,:], digits=digits, left_digits=widths)
def para(): import numpy as np import scipy as sp N = 10000000 f = lambda x: arctan(x) / (x**2 + x * sin(x)) # 要求积分的函数 f = sp.vectorize(f) xs = np.array([random() for _ in range(N)]) # 生成N个积分区间(0,1)的数据 fs = f(xs) mean = fs.mean() print(mean) var = fs.var() print(var)
def chebyshev_vec(values, degree=1): """Calculate the Chebyshev Polynobials This implementation uses sp.vectorize to vectorize python's math functions)""" values = sp.asarray(values) A = sp.zeros((degree, len(values))) A[0, :] = 1 try: A[1, :] = values except IndexError: return A cos = sp.vectorize(sp.math.cos) acos = sp.vectorize(sp.math.acos) for i in range(2, degree): A[i, :] = cos(i * acos(values)) return A
def expect_1s_cor(self, op1, op2, n1, n2): """Computes the correlation of two single site operators acting on two different sites. See expect_1S(). n1 must be smaller than n2. Assumes that the state is normalized. Parameters ---------- op1 : function The first operator, acting on the first site. op2 : function The second operator, acting on the second site. n1 : int The site number of the first site. n2 : int The site number of the second site (must be > n1). """ A1 = self.get_A(n1) A2 = self.get_A(n2) if callable(op1): op1 = sp.vectorize(op1, otypes=[sp.complex128]) op1 = sp.fromfunction(op1, (A1.shape[0], A1.shape[0])) if callable(op2): op2 = sp.vectorize(op2, otypes=[sp.complex128]) op2 = sp.fromfunction(op2, (A2.shape[0], A2.shape[0])) r_n = tm.eps_r_op_1s(self.get_r(n2), A2, A2, op2) for n in reversed(xrange(n1 + 1, n2)): r_n = tm.eps_r_noop(r_n, self.get_A(n), self.get_A(n)) r_n = tm.eps_r_op_1s(r_n, A1, A1, op1) return mm.adot(self.get_l(n1 - 1), r_n)
def expect_1s_cor(self, op1, op2, n1, n2): """Computes the correlation of two single site operators acting on two different sites. See expect_1S(). n1 must be smaller than n2. Assumes that the state is normalized. Parameters ---------- op1 : function The first operator, acting on the first site. op2 : function The second operator, acting on the second site. n1 : int The site number of the first site. n2 : int The site number of the second site (must be > n1). """ A1 = self.get_A(n1) A2 = self.get_A(n2) if callable(op1): op1 = sp.vectorize(op1, otypes=[sp.complex128]) op1 = sp.fromfunction(op1, (A1.shape[0], A1.shape[0])) if callable(op2): op2 = sp.vectorize(op2, otypes=[sp.complex128]) op2 = sp.fromfunction(op2, (A2.shape[0], A2.shape[0])) r_n = tm.eps_r_op_1s(self.get_r(n2), A2, A2, op2) for n in reversed(range(n1 + 1, n2)): r_n = tm.eps_r_noop(r_n, self.get_A(n), self.get_A(n)) r_n = tm.eps_r_op_1s(r_n, A1, A1, op1) return mm.adot(self.get_l(n1 - 1), r_n)
def __init__(self,c,grid,thresh=0.0000001,maxiter=30,req=None): self.grid = grid self.thresh = thresh self.maxiter = maxiter self.lapmat = disclap.disclap(grid) if req == None: self.req = 0.9*self.grid.r else: self.req = req self.c = c self.cvec = vectorize(c)(self.grid.zv) self.csqvec = abs(self.cvec*self.cvec) self.u = self._iterate()
def _iterate(self): self.uzero = vectorize(uinitfunc)(self.req,self.grid.zv,self.csqvec) u = np.copy(self.uzero) n = 0 delta = max(abs(self.op_bvec(u))) sys.stderr.write('PDE: GOAL=%f\n' % self.thresh) while (n < self.maxiter) and (delta > self.thresh): udot = self.step(u) u = u + 0.9*udot delta = max(abs(self.op_bvec(u))) udotnorm = max(abs(udot)) n = n + 1 sys.stderr.write('PDE: error=%f delta=%f\n' % (delta,udotnorm)) return u
def get_net_integral_for_epochs(rates, epochs): """Given a set of epochs, integrate rates over those start and stop times""" # vectorize the integral function to take our rates array as input vec_integrate = vectorize(get_integral_over_times) # scipy.integrate returns tuple of (integral, upper-error-bound) # TODO: figure out how we want to handle diff. time intervals here epochs_results = {} for span in epochs: name = "{0}-{1}".format(span[0],span[1]) assert span[0] < span[1], \ "Start time [{0}] is sooner than end time [{1}]".format(span[0],span[1]) integral, error = vec_integrate(span[0],span[1], rates) epochs_results[name] = {'sum(integral)':sum(integral), 'sum(error)':sum(error)} return epochs_results
def calc_C(self, n_low=-1, n_high=-1): """Generates the C tensors used to calculate the K's and ultimately the B's. This is called automatically by self.update(). C[n] contains a contraction of the Hamiltonian self.ham with the parameter tensors over the local basis indices. This is prerequisite for calculating the tangent vector parameters B, which optimally approximate the exact time evolution. These are to be used on one side of the super-operator when applying the nearest-neighbour Hamiltonian, similarly to C in eqn. (44) of arXiv:1103.0936v2 [cond-mat.str-el], for the non-norm-preserving case. Makes use only of the nearest-neighbour Hamiltonian, and of the A's. C[n] depends on A[n] through A[n + self.ham_sites - 1]. """ if self.ham is None: return 0 if n_low < 1: n_low = 1 if n_high < 1: n_high = self.N - self.ham_sites + 1 for n in xrange(1, self.N): self.AA[n] = tm.calc_AA(self.A[n], self.A[n + 1]) if self.ham_sites == 3: for n in xrange(1, self.N - 1): self.AAA[n] = tm.calc_AAA_AA(self.AA[n], self.A[n + 2]) else: self.AAA.fill(None) for n in xrange(n_low, n_high + 1): if callable(self.ham): ham_n = lambda *args: self.ham(n, *args) ham_n = sp.vectorize(ham_n, otypes=[sp.complex128]) ham_n = sp.fromfunction(ham_n, tuple(self.C[n].shape[:-2] * 2)) else: ham_n = self.ham[n] if self.ham_sites == 2: self.C[n] = tm.calc_C_mat_op_AA(ham_n, self.AA[n]) else: self.C[n] = tm.calc_C_3s_mat_op_AAA(ham_n, self.AAA[n])
def expect_string_1s(self, op, n, d): """Calculates the expectation values of finite strings with lengths 1 to d, starting at position n. """ if callable(op): op = sp.vectorize(op, otypes=[sp.complex128]) op = sp.fromfunction(op, (self.q, self.q)) res = sp.zeros((d), dtype=self.A[1].dtype) x = self.l[n - 1] for j in xrange(n, n + d + 1): Aop = sp.tensordot(op, self.A[j], axes=([1],[0])) x = tm.eps_l_noop(x, self.A[j], Aop) res[j - n - 1] = m.adot(x, self.r[j]) return res
def load_wider_face(path_to_mat): ## load dataset event labels, bboxes ## works with mat files < v7.3, other case it should to be converted r_dict = {} mat = loadmat(path_to_mat) files = mat['file_list'] bboxs = mat['face_bbx_list'] for cell1,cell2 in zip(files,bboxs): for img,bx in zip(cell1[0],cell2[0]): fname = img[0][0] bbox_r = [] for b in bx: b = sp.vectorize(lambda x: int(round(x)))(b) bbox_r.append(b) bbox_r = sp.array(bbox_r[0]) r_dict[(fname)] = bbox_r return r_dict
def apply_op_1s(self, op, n): """Applies a one-site operator op to site n. Can be used to create excitations. """ if not (0 < n <= self.N): raise ValueError("Operators can only be applied to sites 1 to N!") newA = sp.zeros_like(self.A[n]) if callable(op): op = sp.vectorize(op, otypes=[sp.complex128]) op = sp.fromfunction(op, (self.q[n], self.q[n])) for s in xrange(self.q[n]): for t in xrange(self.q[n]): newA[s] += self.A[n][t] * op[s, t] self.A[n] = newA
def getNextStateArray(n, zState): opt_d = bellman.getIter(n)['opt_d'] opt_r = bellman.getIter(n)['opt_r'] # k = d + D - M k_fn = lambda x: opt_d(x) + x[1] - x[0] f_fn = lambda x: p_fns.testf(k_fn(x), opt_r(x)) rho_fn = lambda x: rhoFn(x, f_fn, k_fn) def nextStateFn(M,D): (nextM, nextD) = getNextMD(M, D, n, zState) # if current state is A (bankrupt with certainty), then next state has no meaning. color it black currentState = classifyState(M, D, rho_fn, opt_d) if (currentState == g.STATE_RED): return g.STATE_BLACK # if current state is B (bankrupt if zLow occurs) and zLow occurs, next state is in bankruptcy if (currentState == g.STATE_BLUE and zState == 0): return g.STATE_BLACK return classifyState(nextM, nextD, rho_fn, opt_d) nextStateArray = scipy.vectorize(nextStateFn)(g.mesh_M, g.mesh_D) return scipy.transpose(nextStateArray)