def d_theta(angle,k_v,R_v,alpha_v,An): '''Off-axis level, :math:`D_{\\theta}`, for piston in a sphere Parameters ---------- angle : mpmath.mpf Azimuth/elevation angle in radians k_v : mpmath.mpf Wavenumber alpha: mpmath.mpf Piston equivalent aperture in radians. An : mpmath.matrix An is a required pre-calculated matrix which results from the satisfying the conditions of the model - specific to each parameter set. Returns ------- abs(rel_level()) : mpmath.mpf The off-axis value at angle :math:`\theta` ''' num = 4 N_v = An.rows denom = (k_v**2)*(R_v**2)*mpmath.sin(alpha_v)**2 part1 = num/denom jn_matrix = mpmath.matrix([I**f for f in range(N_v)]) legendre_matrix = mpmath.matrix([legendre(n_v, mpmath.cos(angle)) for n_v in range(N_v)]) Anjn = HP(An,jn_matrix).doit() part2_matrix = HP(Anjn,legendre_matrix).doit() part2 = sum(part2_matrix) rel_level = lambdify([], -part1*part2, 'mpmath') return abs(rel_level())
def jac_Diode_In_mpmath(x, b, c, y): """ [Реестровая] непосредственная проверка невозможна :param x: :param b: :param c: :param y: :return: """ global FT dfdbMPM = lambda y, x, b, c: mpm.matrix([[ mpm.exp((-b[2] * y[0] + x[0]) / (FT * b[1])) - 1, -b[0] * (-b[2] * y[0] + x[0]) * mpm.exp((-b[2] * y[0] + x[0]) / (FT * b[1])) / (FT * b[1]**2), -b[0] * y[0] * mpm.exp((-b[2] * y[0] + x[0]) / (FT * b[1])) / (FT * b[1]) ]]) dfdyMPM = lambda y, x, b, c: mpm.matrix([[ -1 - b[0] * b[2] * mpm.exp((-b[2] * y[0] + x[0]) / (FT * b[1])) / (FT * b[1]) ]]) jacf = dfdyMPM(y, x, b, c)**-1 * dfdbMPM(y, x, b, c) return jacf
def SL(pts, prec): título("Sistema Linear", "=") # Definir Precisão mm.mp.dps = prec nv = len(pts[0]) pol = [] # Criar Matriz Polinômio matA = [] matY = [] for i in range(len(pts[0])): matA.append([]) for g in range(nv): matA[i].append(pts[0][i]**g) matY.append(pts[1][i]) # Resolver Matriz matA = mm.matrix(matA) print("Matriz A") print(str(matA)) matY = mm.matrix(matY) print("\nMatriz Y") print(str(matY)) matInvA = matA**-1 print("\nMatriz Inversa A") print(str(matInvA)) matX = matInvA * matY print("\nMatriz X") print(str(matX)) # Transformar Resposta em String Polinômio sPol = pol2str(matX) print("\nPolinômio: ",sPol) return sPol
def Newton(pts, prec): título("Newton", "=") # Definir Precisão mm.mp.dps = prec nv = len(pts[0]) matX = pts[0] matY = [pts[1]] for i in range(1, nv): matY.append([]) for j in range(nv - i): matY[i].append((matY[i - 1][j + 1] - matY[i - 1][j]) / (matX[j + i] - matX[j])) print("\nTabela\n\n", mm.matrix(matY)) # matP = [matY[1][0]] # for i in range(nv-1): # mult = 1 # for n in range(i): # mult *= -matX[n] # matP.append(mult) matX = pts[0] matY = pts[1] matP = mm.matrix(list(reversed(Polynomial(lagrange(matX, matY)).coef))) # Transformar Resposta em String Polinômio sPol = pol2str(matP) print("\nPolinômio: ", sPol) return sPol
def cons(o1, p11): b = matrix(o1) # print('b = ',o) c = matrix(p11) # print('c = ', c) a = b * c # print('a = ', a) return a
def test_poincare_reflect0(): z = mpm.matrix([[0., 0., 0.5]]) x = mpm.matrix([[0.1, -0.2, 0.1]]) assert mpm.norm(poincare_reflect0(z, z)) < TOL y = poincare_reflect0(z, x) assert mpm.norm(poincare_reflect0(z, y) - x) < TOL
def test_poincare_reflect(): x = mpm.matrix([[0.3, -0.3, 0.0]]) a = mpm.matrix([[0.5, 0., 0.0]]) y = poincare_reflect(a, x) R = mpm.norm(a) r1 = mpm.norm(x - a) r2 = mpm.norm(y - a) assert R**2 - r1 * r2 < TOL
def zero(): #this function resets the initial position, velocity, and time variables; called when restarting global time, s0, v0 time = 0 s0 = matrix([[orbrad['earth']], [0]]) v0 = matrix([[0], [-30000]])
def test_poincare_dist(): x = mpm.matrix([[0., 0., -0.4]]) y = mpm.matrix([[0.0, 0.0, 0.1]]) o = mpm.zeros(1, 3) assert poincare_dist(o, y) - poincare_dist0(y) < TOL assert poincare_dist(o, x) - poincare_dist0(x) < TOL assert poincare_dist(o, x) + poincare_dist(o, y) - poincare_dist(x, y) < TOL
def CF_bounded_Pareto(u, P): """ Use: CF_bounded_Pareto(u, P) This function returns the characteristic function of an FPP with exponential pulses and bounded Pareto amplitudes [3] as a complex (u.size, 1)-matrix. The parameters are: gamma, the shape parameter of the distribution, alpha, the scale of the Pareto distribution, L, the lower bound of the Pareto distribution, H, the upper bound of the Pareto distribution. Input: u: The variable of the characteristic function. .......... 1D np array P=[gamma, alpha, L, H]: The parameters of the distribution. ... list Output: res: the characteristic function. ........ complex (u.size,1) np array References: [1] A. Theodorsen and O. E. Garcia, PPCF 60 (2018) 034006 https://doi.org/10.1088/1361-6587/aa9f9c [2] O. E. Garcia and A. Theodorsen POP 25 (2018) 014506 https://doi.org/10.1063/1.5020555 [3] https://en.wikipedia.org/wiki/Pareto_distribution """ import numpy as np import mpmath as mm #res = np.zeros([u.size, 1], dtype=complex) g_m = mm.mpf(P[0]) a_m = mm.mpf(P[1]) L_m = mm.mpf(P[2]) H_m = mm.mpf(P[3]) u_m = mm.matrix(-1.j * u) C = mm.matrix(u.size, 1) def tmp(x, a): return -mm.log(x) - mm.gammainc(0, x) + x**a * mm.gammainc(-a, x) const_0 = -g_m * (a_m**(-1) + mm.euler) const_1 = g_m / (H_m**a_m - L_m**a_m) for i in range(u.size): if u_m[i] == 0: lnC = 0 else: lnCtmp = (H_m**a_m * tmp(L_m * u_m[i], a_m) - L_m**a_m * tmp(H_m * u_m[i], a_m)) lnC = const_0 + const_1 * lnCtmp C[i] = mm.exp(lnC) return np.array(C.tolist(), dtype=np.cfloat)
def runTest(self): data = {} data[1.] = mpmath.matrix([[1., 1.], [1., 1.]]) data[2.] = mpmath.matrix([[2., 2.], [2., 2.]]) rk.use_mpmath_types() cal = rk.get_asym_calc(cu.rydbergs, [0, 0]) dmat = rk.get_dmat_from_discrete(rk.Smat, data, cal, "dum2") self.assertEqual(nw.mode, nw.mode_mpmath) self.assertEqual(nw.dps, nw.dps_default_mpmath) for mat in dmat.values(): nw.shape(mat) # Will get an exception if types are wrong.
def poly_fixed(p, a, b, x_exp, bits, y_exp=None, dtype=numpy.int64, epsilon=EPSILON): c, shr, exp = poly_fixed_multi(p.transpose(), mpmath.matrix([a]), mpmath.matrix([b]), x_exp, bits, y_exp, dtype, epsilon) return c[0, :], shr, exp
def absposition(planet): #this function is used to get the position of all planets other than the earth #it is assumed that they are perfectly circular in orbit if(planet == 'sun'): #the sun is always at the origin pos = matrix([[0], [0]]) else: angle = angularvelocity(planet)*time pos = matrix([[orbrad[planet]*cos(angle)], [orbrad[planet]*sin(angle)]]) return pos
def main(): # Initialise initial conditions mpm.dps = 32 # Quadruple precision calculations #T = 2. * mpm.mpf(1.657935803684451) #x0 = mpm.matrix([1.006057199440406, 0.0, 0.0, 0.022036094262319]) #x0 = mpm.matrix([1.009433860747752, 0.0, 0.0, 0.003760276142823]) x0 = mpm.matrix([ 1.0060556387918027, 2.4281528205782993e-06, -8.1318569756237198e-06, 0.022040604156795093 ]) # Velocities have been inverted (+ -> -) to spoof reverse time # T = mpm.mpf(2 * 3.061660616555952) x_des = mpm.matrix([ 1.0039053449563018, 0.0024706864707973696, -0.012281740632575283, 0.024133313701580495 ]) # Call the Taylor integrator f = mpm.odefun(PCR3BP, 0.0, x0, tol=1e-30, degree=100, verbose=True) #for i in range(4): # print(f(T)[i] - f(0.0)[i]) print(mpm.pi) min_dist = 10. with open('output.dat', 'w+') as fiyul: for time in mpm.linspace(0., 2 * mpm.pi, 1000): temp = f(time) distance = mpm.sqrt((temp[0] - x_des[0])**mpm.mpf(2.0) + (temp[1] - x_des[1])**mpm.mpf(2.0)) print("Distance between desired point: %s" % (distance)) if distance < min_dist: min_dist = distance fiyul.write("%s, %s, %s, %s\n" % (temp[0], temp[1], temp[2], temp[3])) print("Minimum distance was %s" % min_dist) return None
def multivariate_normalization(data, variables_size): mpmath.mp.dps = 20 for j in range(0, len(data[0])): means = [] ts_s = [] for u in range(0, variables_size): means.append(numpy.mean(data[u][j])) ts_s.append(data[u][j]) covariance_matrix = mpmath.matrix(numpy.cov(ts_s)) w, v = mpmath.eig(covariance_matrix) diagonal = mpmath.diag(w) try: result = mpmath.sqrtm(diagonal) except ZeroDivisionError as error: print("j: ", j) print("ts:", ts_s) print("not invertible sqrtm") print("covariance_matrix:", covariance_matrix) sys.exit() B = v * result try: inverse_B = B**-1 except ZeroDivisionError as error: # Not invertible. Skip this one. # Non invertable cases Uwave print("j: ", j) print("ts:", ts_s) print("not invertible") print("covariance_matrix:", covariance_matrix) sys.exit() except Exception as exception: # Not invertible. Skip this one. print("j: ", j) print("ts:", ts_s) print("not invertible") print("covariance_matrix:", covariance_matrix) sys.exit() for i in range(0, len(data[0][j])): atributes_together = [] for u in range(0, variables_size): atributes_together.append(data[u][j][i]) atributes_together = mpmath.matrix(atributes_together) result = atributes_together - mpmath.matrix(means) result = inverse_B * result for u in range(0, variables_size): if type(result[u]) is mpmath.mpc: data[u][j][i] = result[u].real else: data[u][j][i] = result[u] return data
def g(theta): # calculate output of alpha-max-beta-min for each theta-value y = utils.poly.eval_multi(p_alpha_cos_beta_sin, mpmath.matrix(theta)) # optionally apply some iterations of Newton-Raphson square root # this means the alpha, beta will be optimized to return the best # error AFTER the Newton-Raphson has been applied at run-time for i in range(NEWTON_ITERS): y = mpmath.matrix( [.5 * (y[j] + 1. / y[j]) for j in range(y.rows)]) return y - 1.
def _semicolon(a, b): if not isinstance(a, mpmath.matrix): a = mpmath.matrix([[a]]) if not isinstance(b, mpmath.matrix): b = mpmath.matrix([[b]]) assert a.cols == b.cols, 'matrix cols not equal' r = mpmath.matrix(a.rows + b.rows, a.cols) for j in range(a.cols): for i in range(a.rows): r[(i, j)] = a[(i, j)] for i in range(b.rows): r[(i + a.rows, j)] = b[(i, j)] return r
def tranformRectangle(self, orignalRectangle, uVector, vVector): LeftButton = mpmath.matrix([orignalRectangle[0], orignalRectangle[1]]) LeftButton = self.tranformCoordinate(LeftButton, uVector, vVector) RightUp = mpmath.matrix([orignalRectangle[2], orignalRectangle[3]]) RightUp = self.tranformCoordinate(RightUp, uVector, vVector) Left = min(LeftButton[0], RightUp[0]) Button = min(LeftButton[1], RightUp[1]) Right = max(LeftButton[0], RightUp[0]) Up = max(LeftButton[1], RightUp[1]) return [Left, Button, Right, Up]
def d_theta(angle, k_v, R_v, alpha_v, An): num = 4 N_v = An.rows denom = (k_v**2) * (R_v**2) * mpmath.sin(alpha_v)**2 part1 = num / denom jn_matrix = mpmath.matrix([I**f for f in range(N_v)]) legendre_matrix = mpmath.matrix( [legendre(n_v, mpmath.cos(angle)) for n_v in range(N_v)]) Anjn = HP(An, jn_matrix).doit() part2_matrix = HP(Anjn, legendre_matrix).doit() part2 = sum(part2_matrix) rel_level = lambdify([], -part1 * part2, 'mpmath') return abs(rel_level())
def traverseTheHierarchy(self, startingStructureName=None, delegateFunction = None, transformPath = [], rotateAngle = 0, transFlags = (0,0,0), coordinates = (0,0)): #since this is a recursive function, must deal with the default #parameters explicitly if startingStructureName == None: startingStructureName = self.rootStructureName #set up the rotation matrix if(rotateAngle == None or rotateAngle == ""): rotateAngle = 0 else: rotateAngle = math.radians(float(rotateAngle)) mRotate = mpmath.matrix([[math.cos(rotateAngle),-math.sin(rotateAngle),0.0], [math.sin(rotateAngle),math.cos(rotateAngle),0.0],[0.0,0.0,1.0],]) #set up the translation matrix translateX = float(coordinates[0]) translateY = float(coordinates[1]) mTranslate = mpmath.matrix([[1.0,0.0,translateX],[0.0,1.0,translateY],[0.0,0.0,1.0]]) #set up the scale matrix (handles mirror X) scaleX = 1.0 if(transFlags[0]): scaleY = -1.0 else: scaleY = 1.0 mScale = mpmath.matrix([[scaleX,0.0,0.0],[0.0,scaleY,0.0],[0.0,0.0,1.0]]) #we need to keep track of all transforms in the hierarchy #when we add an element to the xy tree, we apply all transforms from the bottom up transformPath += [(mRotate,mScale,mTranslate)] if delegateFunction != None: delegateFunction(startingStructureName, transformPath) #starting with a particular structure, we will recursively traverse the tree #********might have to set the recursion level deeper for big layouts! if(len(self.structures[startingStructureName].srefs)>0): #does this structure reference any others? #if so, go through each and call this function again #if not, return back to the caller (caller can be this function) for sref in self.structures[startingStructureName].srefs: #here, we are going to modify the sref coordinates based on the parent objects rotation # if (sref.sName.count("via") == 0): self.traverseTheHierarchy(startingStructureName = sref.sName, delegateFunction = delegateFunction, transformPath = transformPath, rotateAngle = sref.rotateAngle, transFlags = sref.transFlags, coordinates = sref.coordinates) # else: # print "WARNING: via encountered, ignoring:", sref.sName #MUST HANDLE AREFs HERE AS WELL #when we return, drop the last transform from the transformPath del transformPath[-1] return
def sarkar_embedding_3D(tree, root, **kwargs): eps = kwargs.get("eps",0.1) weighted = kwargs.get("weighted", True) tau = kwargs.get("tau") max_deg = max(tree.degree)[1] if tau is None: tau = (1+eps)/eps * mpm.log(2*max_deg/ mpm.pi) prc = kwargs.get("precision") if prc is None: prc = _embedding_precision(tree,root,eps) mpm.mp.dps = prc n = tree.order() emb = mpm.zeros(n,3) place = [] # place the children of root fib = fib_2D_code(tree.degree[root]) for i, v in enumerate(tree[root]): r = mpm.tanh(tau*tree[root][v].get("weight",1.)) v_emb = r * mpm.matrix([[fib[i,0],fib[i,1],fib[i,2]]]) emb[v,:]=v_emb place.append((root,v)) while place: u, v = place.pop() # u is the parent of v u_emb, v_emb = emb[u,:], emb[v,:] # reflect and rotate so that embedding(v) is at (0,0,0) # and embedding(u) is in the direction of (0,0,1) u_emb = poincare_reflect0(v_emb, u_emb, precision=prc) R = rotate_3D_mp(mpm.matrix([[0.,0.,1.]]), u_emb) #u_emb = (R.T * u_emb).T # place children of v fib = fib_2D_code(tree.degree[v]) i=0 for w in tree[v]: if w == u: # i=0 is for u (parent of v) continue i+=1 r = mpm.tanh(tau*tree[w][v].get("weight",1.)) w_emb = r * mpm.matrix([[fib[i,0],fib[i,1],fib[i,2]]]) #undo reflection and rotation w_emb = (R * w_emb.T).T w_emb = poincare_reflect0(v_emb, w_emb, precision=prc) emb[w,:] = w_emb place.append((v,w)) return emb
def evolution(self, pathways, dt, ddt, stationary=False): # print(self.size) # eng = matlab.engine.start_matlab() rate_matrix = mp.matrix(self.size, self.size) species_list = list(self.species.items()) population_array = mp.matrix([0 for i in range(self.size)]) # TODO: parallel optimization self.timestamp += dt time_array = np.arange(0, dt, ddt) + self.timestamp + ddt for i in range(self.size): diag_i = 0 population_array[i] = species_list[i][1] for j in range(self.size): if j == i: continue rate_temp = pathways.get_rate(species_list[i][0], species_list[j][0]) diag_i += rate_temp rate_matrix[i, j] = rate_temp rate_matrix[i, i] = -diag_i # rate_matrix = matlab.double(rate_matrix) # population_array = matlab.double(population_array) if stationary: intermediate_population_arrays = \ preprocessing.normalize([[boltzmann_factor(species[0].get_G()) for species in species_list] for t in time_array], norm='l1', axis=1) # intermediate_population_arrays = Propagate_stationary(rate_matrix, population_array, dt, ddt=ddt) else: ''' k_fastest = np.max(rate_matrix) for i in range(self.size): # Make it a REAL sparse matrix for j in range(self.size): if rate_matrix[i][j] < k_fastest * rate_cutoff: rate_matrix[i][j] = 0 rate_matrix[i][i] = -np.sum(rate_matrix[i]) ''' # Master Equation intermediate_population_arrays = Propagate_sp(rate_matrix, population_array, dt, ddt=ddt) # TODO: Modify here! population_array = intermediate_population_arrays[-1] # Remapping for i in range(self.size): self.update_population(species_list[i][0], population_array[i]) return species_list, intermediate_population_arrays, time_array
def __init__(self, side, extended, distance): self.distance = mp.mpf(distance) rightPointX = mp.mpf('1.41949302') if extended else mp.sqrt(2) self.side = side # side length of square self.d = side / mp.cos(mp.pi / 12) # length of left edge sin60 = mp.sqrt(3) / 2 self.top = matrix([self.d / 2, sin60 * self.d]) self.right = matrix([side * rightPointX, 0]) self.nleft = matrix([[-sin60, 0.5]]) self.ndown = matrix([[0, -1]]) v = self.right - self.top norm = mp.norm(v) self.nright = matrix([[-v[1] / norm, v[0] / norm]]) self.offset = self.nright * self.right
def solve_lu_mp(A, b): """ Solve a linear system using mpmath :param ndarray A: The linear system :param ndarray b: The right hand side :return: ndarray """ A_mp = mpmath.matrix([list(row) for row in A]) b_mp = mpmath.matrix([list(row) for row in b]) x_mp = mpmath.lu_solve(A_mp, b_mp) x = numpy.array(x_mp.tolist(), 'f8') return x
def reduce_to_fpp(self, z): # TODO: need to check what happens here when periods are infinite. from mpmath import floor, matrix, lu_solve T1, T2 = self.periods R1, R2 = T1.real, T2.real I1, I2 = T1.imag, T2.imag A = matrix([[R1, R2], [I1, I2]]) b = matrix([z.real, z.imag]) x = lu_solve(A, b) N = int(floor(x[0])) M = int(floor(x[1])) alpha = x[0] - N beta = x[1] - M assert (alpha >= 0 and beta >= 0) return alpha, beta, N, M
def reduce_to_fpp(self,z): # TODO: need to check what happens here when periods are infinite. from mpmath import floor, matrix, lu_solve T1, T2 = self.__periods R1, R2 = T1.real, T2.real I1, I2 = T1.imag, T2.imag A = matrix([[R1,R2],[I1,I2]]) b = matrix([z.real,z.imag]) x = lu_solve(A,b) N = int(floor(x[0])) M = int(floor(x[1])) alpha = x[0] - N beta = x[1] - M assert(alpha >= 0 and beta >= 0) return alpha,beta,N,M
def iv_matrix_mid_as_mp(M): """ entrywise midpoint of interval matrix, as (non-interval) mpmath matrix. If the input is a mpmath matrix, it is returned unchanged. If the input is a 2-dimensional numpy.ndarray, it is converted to mpmath. """ if isinstance(M, numpy.ndarray): return mp.matrix(M) Y = mp.matrix(M.rows, M.cols) for i in range(M.rows): for j in range(M.cols): Y[i, j] = mp.mpi(M[i, j]).mid return Y
def polish(self, init_shapes, flag_initial_error=True): """Use Newton's method to compute precise shapes from rough ones.""" precision = self._precision manifold = self.manifold #working_prec = precision + 32 working_prec = precision + 64 mpmath.mp.prec = working_prec target_epsilon = mpmath.mpmathify(2.0)**-precision det_epsilon = mpmath.mpmathify(2.0)**(32 - precision) #shapes = [mpmath.mpmathify(z) for z in init_shapes] shapes = mpmath.matrix(init_shapes) init_equations = manifold.gluing_equations('rect') target = mpmath.mpmathify(self.target_holonomy) error = self._gluing_equation_error(init_equations, shapes, target) if flag_initial_error and error > 0.000001: raise GoodShapesNotFound( 'Initial solution not very good: error=%s' % error) # Now begin the actual computation eqns = enough_gluing_equations(manifold) assert eqns[-1] == manifold.gluing_equations('rect')[-1] for i in range(100): errors = self._gluing_equation_errors(eqns, shapes, target) if infinity_norm(errors) < target_epsilon: break derivative = [[ int(eqn[0][i]) / z - int(eqn[1][i]) / (1 - z) for i, z in enumerate(shapes) ] for eqn in eqns] derivative[-1] = [target * x for x in derivative[-1]] derivative = mpmath.matrix(derivative) #det = derivative.matdet().abs() det = abs(mpmath.det(derivative)) if min(det, 1 / det) < det_epsilon: raise GoodShapesNotFound( 'Gluing system is too singular (|det| = %s).' % det) delta = mpmath.lu_solve(derivative, errors) shapes = shapes - delta # Check to make sure things worked out ok. error = self._gluing_equation_error(init_equations, shapes, target) #total_change = infinity_norm(init_shapes - shapes) if error > 1000 * target_epsilon: raise GoodShapesNotFound('Failed to find solution') #if flag_initial_error and total_change > pari(0.0000001): # raise GoodShapesNotFound('Moved too far finding a good solution') self.shapelist = [Number(z, precision=precision) for z in shapes]
def makeMeasAccToPlan_lognorm(func, expplan:list, b:list, c:dict, Ve=[], n=1, outfilename="", listOfOutvars=None): """ MPMATH+CAPABLE :param func: векторная функция :param expplan: план эксперимента (список значений вектора x) :param b: вектор b :param c: вектор c :param Ve: ковариационная матрица (np.array) :param n: объём выборки y :param outfilename: имя выходного файла, куда писать план :param listOfOutvars: список выносимых переменных :return: список экспериментальных данных в формате списка словарей 'x':..., 'y':... """ res = list() for i in range(len(expplan)): y=makeMeasOneDot_lognorm(func, expplan[i], b, c, Ve) if y is None: #если функция вернула чушь, то в measdata её не записывать! continue res.append({'x':mpm.matrix(expplan[i]), 'y':y}) #res.append({'x':expplan[i], 'y':y}) return res
def dfdb (y,x,b,c): global FT,XO,XT,XF ft=FT v=x[0] i=y[0] iss=IS=b[0] n=N=b[1] ikf=IKF=b[2] isr=ISR=b[3] nr=NR=b[4] vj=VJ=b[5] m=M=b[6] rs=RS=b[7] #ещё раз: ВСЕ константы должны быть в перспективе либо глобальными переменными, как FT, либо составляющими вектора c, но он кривой, потому лучше уж глобальными. return mpm.matrix ([[iss*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(-mpm.exp((-i*rs + v)/(ft*n)) + XO)*(mpm.exp((-i*rs + v)/(ft*n)) - XO)/(XT*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))) + mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(mpm.exp((-i*rs + v)/(ft*n)) - XO), iss**XT*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(-i*rs + v)*(mpm.exp((-i*rs + v)/(ft*n)) - XO)*mpm.exp((-i*rs + v)/(ft*n))/(XT*ft*n**XT*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))) - iss*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(-i*rs + v)*mpm.exp((-i*rs + v)/(ft*n))/(ft*n**XT), iss*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))*(-ikf/(XT*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))**XT) + XO/(XT*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))))*(mpm.exp((-i*rs + v)/(ft*n)) - XO)/ikf, ((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*(mpm.exp((-i*rs + v)/(ft*nr)) - XO), -isr*(-i*rs + v)*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*mpm.exp((-i*rs + v)/(ft*nr))/(ft*nr**XT), isr*m*(XO - (-i*rs + v)/vj)*(-i*rs + v)*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*(mpm.exp((-i*rs + v)/(ft*nr)) - XO)/(vj**XT*((XO - (-i*rs + v)/vj)**XT + XF)), isr*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*(mpm.exp((-i*rs + v)/(ft*nr)) - XO)*mpm.log((XO - (-i*rs + v)/vj)**XT + XF)/XT, i*iss**XT*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(mpm.exp((-i*rs + v)/(ft*n)) - XO)*mpm.exp((-i*rs + v)/(ft*n))/(XT*ft*n*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))) - i*iss*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*mpm.exp((-i*rs + v)/(ft*n))/(ft*n)+ \ i*isr*m*(XO - (-i*rs + v)/vj)*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*(mpm.exp((-i*rs + v)/(ft*nr)) - XO)/(vj*((XO - (-i*rs + v)/vj)**XT + XF)) - i*isr*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*mpm.exp((-i*rs + v)/(ft*nr))/(ft*nr) ]])
def test_gth_solve_high_prec(): n = 1e-100 with mp.workdps(100): P = mp.matrix([[-3*(mp.exp(n)-1), 3*(mp.exp(n)-1)], [mp.exp(n)-1 , -(mp.exp(n)-1) ]]) run_gth_solve(P, verbose=VERBOSE)
def test_stoch_eig_high_prec(): n = 1e-100 with mp.workdps(100): P = mp.matrix([[1-3*(mp.exp(n)-1), 3*(mp.exp(n)-1)], [mp.exp(n)-1 , 1-(mp.exp(n)-1)]]) run_stoch_eig(P, verbose=VERBOSE)
def countNMpmath(A, b, bstart, bend): N = mpm.matrix(len(b), len(b)) for j in range(len(b)): partone = mpm.mpf(2) * A[j, 0] / (b[j] - bstart[j])**mpm.mpf(3) parttwo = mpm.mpf(2) * A[j, 1] / (bend[j] - b[j])**mpm.mpf(3) N[j, j] += parttwo + partone #так как матрица нулевая return N
def vawe_func_plot(self, Energy): x_min = min(self.structure_width_vector) #x_max = max(self.structure_width_vector) x = np.linspace(x_min, self.x_max, 150) U = np.zeros_like(x) for ind in range(len(x)): U[ind] = self.U(x[ind]) v_F_vector = mp.matrix(len(Energy), len(x)) for energy in range(len(Energy)): for ind in range(len(x)): v_F_vector[energy, ind] = self.vawe_function(x[ind], Energy[energy]) plt.plot(x / 10**(-7), U, color='k', linestyle='--', linewidth=1) for energy in range(len(Energy)): plt.plot(x / 10**(-7), v_F_vector[energy, :], linewidth=2) plt.ylabel(r'$\Psi_{k}(x), U(x)$') plt.xlabel(r'$x,10^{-9} м$') plt.show()
def test_msvd(): output("""\ msvd_:{[b;x] $[3<>count usv:.qml.msvd x;::; not (.qml.mdim[u:usv 0]~2#d 0) and (.qml.mdim[v:usv 2]~2#d 1) and .qml.mdim[s:usv 1]~d:.qml.mdim x;::; not mortho[u] and mortho[v] and all[0<=f:.qml.mdiag s] and mzero s _'til d 0;::; not mzero x-.qml.mm[u] .qml.mm[s] flip v;::; b;1b;(p*/:m#/:u;m#m#/:s; (p:(f>.qml.eps*f[0]*max d)*1-2*0>m#u 0)*/:(m:min d)#/:v)]};""") for A in subjects: U, S, V = map(mp.matrix, mp.svd(mp.matrix(A))) m = min(A.rows, A.cols) p = mp.diag([mp.sign(s * u) for s, u in zip(mp.chop(S), U[0, :])]) U *= p S = mp.diag(S) V = V.T * p test("msvd_[0b", A, (U, S, V)) reps(250) for Aq in large_subjects: test("msvd_[1b", qstr(Aq), qstr("1b")) reps(10000)
def countNMpmath (A, b, bstart, bend): N=mpm.matrix(len(b),len(b)) for j in range (len(b)): partone=mpm.mpf(2)*A[j,0]/(b[j]-bstart[j])**mpm.mpf(3) parttwo=mpm.mpf(2)*A[j,1]/(bend[j]-b[j])**mpm.mpf(3) N[j,j]+=parttwo+partone #так как матрица нулевая return N
def solver_Diode_In_mpmath (x,b,c=None): """ [Реестровая] + :param x: :param b: :param c: :return: """ global numnone global FT #первая часть решения: находим корень с небольшой точностью через numpy dfdy=lambda y,x,b,c=None: np.array ([[ -1 - b[0]*b[2]*math.exp((-b[2]*y[0] + x[0])/(FT*b[1]))/(FT*b[1])]]) func = lambda y,x,b,c: [np.float(x) for x in func_Diode_In_mpmath(y,x,b,c)] solvinit=[0.5] try: #solx=optimize.root(func, solvinit, args=(x,b,c), jac=dfdy, method='lm').x solx=optimize.root(func, solvinit, args=(x,b,c), method='lm').x #http://stackoverflow.com/questions/2566412/find-nearest-value-in-numpy-array #http://codereview.stackexchange.com/questions/28207/is-this-the-fastest-way-to-find-the-closest-point-to-a-list-of-points-using-nump except BaseException as e: numnone+=1 print ("solver: ERROR: "+e.__str__()) return [None] #вторая часть решения: находим корень с увеличенной точностью через mpmath funcMPM = lambda y: func_Diode_In_mpmath ([y],x,b,c) dfdyMPM=lambda y: mpm.matrix ([[ -1 - b[0]*b[2]*mpm.exp((-b[2]*[y][0] + x[0])/(FT*b[1]))/(FT*b[1])]]) solvinitMPM=solx[0] try: precsolx=mpm.calculus.optimization.findroot(mpm.mp, f=funcMPM, x0=solvinitMPM, solver=MDNewton, multidimensional=True, J=dfdyMPM, verify=False) except BaseException as e: numnone+=1 print ("solver MPM: ERROR: "+e.__str__()) return [None] return precsolx
def dfdy (y,x,b,c): global FT,XO,XT,XF ft=FT v=x[0] i=y[0] iss=IS=b[0] n=N=b[1] ikf=IKF=b[2] isr=ISR=b[3] nr=NR=b[4] vj=VJ=b[5] m=M=b[6] rs=RS=b[7] #fh = iss**mpm.mpf(2)*rs*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - mpm.mpf(1))))*(mpm.exp((-i*rs + v)/(ft*n)) - mpm.mpf(1))*mpm.exp((-i*rs + v)/(ft*n))/(mpm.mpf(2)*ft*n*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - mpm.mpf(1)))) - iss*rs*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - mpm.mpf(1))))*mpm.exp((-i*rs + v)/(ft*n))/(ft*n) #sh = isr*m*rs*(mpm.mpf(1) - (-i*rs + v)/vj)*((mpm.mpf(1) - (-i*rs + v)/vj)**mpm.mpf(2) + mpm.mpf('0.005'))**(m/mpm.mpf(2))*(mpm.exp((-i*rs + v)/(ft*nr)) - mpm.mpf(1))/(vj*((mpm.mpf(1) - (-i*rs + v)/vj)**mpm.mpf(2) + mpm.mpf('0.005'))) - isr*rs*((mpm.mpf(1) - (-i*rs + v)/vj)**mpm.mpf(2) + mpm.mpf('0.005'))**(m/mpm.mpf(2))*mpm.exp((-i*rs + v)/(ft*nr))/(ft*nr) fh = iss**XT*rs*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*(mpm.exp((-i*rs + v)/(ft*n)) - XO)*mpm.exp((-i*rs + v)/(ft*n))/(XT*ft*n*(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO))) - iss*rs*mpm.sqrt(ikf/(ikf + iss*(mpm.exp((-i*rs + v)/(ft*n)) - XO)))*mpm.exp((-i*rs + v)/(ft*n))/(ft*n) sh = isr*m*rs*(XO - (-i*rs + v)/vj)*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*(mpm.exp((-i*rs + v)/(ft*nr)) - XO)/(vj*((XO - (-i*rs + v)/vj)**XT + XF)) - isr*rs*((XO - (-i*rs + v)/vj)**XT + XF)**(m/XT)*mpm.exp((-i*rs + v)/(ft*nr))/(ft*nr) return mpm.matrix ([[fh+sh]])
def numerical_coeffs(Mn, n, dict_ss): """Numerical coefficients of polynomial of order (n - 3)! obtianed from determinant of elimination theory matrix.""" Mn = Mn.tolist() Mn = [[_zs_sub(_ss_sub(str(entry))) for entry in line] for line in Mn] zs = punctures(n) values = [ mpmath.e**(2 * mpmath.pi * 1j * j / (math.factorial(n - 3) + 1)) for j in range(math.factorial(n - 3) + 1) ] A = [[ value**exponent for exponent in range(math.factorial(n - 3) + 1)[::-1] ] for value in values] b = [] for i, value in enumerate(values): dict_zs = { str(zs[-2]): value, str(zs[-3]): 1 } # noqa --- used in eval function nMn = mpmath.matrix([[eval(entry, None) for entry in line] for line in Mn]) b += [mpmath.det(nMn)] return mpmath.lu_solve(A, b).T.tolist()[0]
def test_gth_solve_iv(): P = mp.iv.matrix([[-0.1, 0.075, 0.025], [0.15, -0.2 , 0.05 ], [0.25, 0.25 , -0.5 ]]) x_expected = mp.matrix([[0.625, 0.3125, 0.0625]]) x_iv = mp.iv.gth_solve(P) for value, interval in zip(x_expected, x_iv): assert value in interval
def test_stoch_eig_iv(): P = mp.iv.matrix([[0.9 , 0.075, 0.025], [0.15, 0.8 , 0.05 ], [0.25, 0.25 , 0.5 ]]) x_expected = mp.matrix([[0.625, 0.3125, 0.0625]]) x_iv = mp.iv.stoch_eig(P) for value, interval in zip(x_expected, x_iv): assert value in interval
def QSdiagonalise(mat): if QSMODE == MODE_NORM: w, v = np.linalg.eig(mat) P = np.transpose(np.matrix(v, dtype=np.complex128)) return np.dot(P, np.dot(mat, np.linalg.inv(P))) else: w, v = mpmath.eig(mat) P = mpmath.matrix(v).T return P * mat * P**-1
def QSatanElements(mat): if QSMODE == MODE_NORM: return np.arctan(mat) else: at = mpmath.matrix(mat.rows, mat.cols) for i in range(mat.rows): for j in range(mat.cols): at[i,j] = mpmath.atan(mat[i,j]) return at
def ufrac_to_ucart(A, cell, uvals): U11, U22, U33, U23, U13, U12 = uvals U21 = U12 U32 = U23 U31 = U13 Uij = mpm.matrix([[U11, U12, U13], [U21, U22, U23], [U31, U32, U33]]) a, b, c, alpha, beta, gamma = cell V = vol_unitcell(*cell) # calculate reciprocal lattice vectors: astar = (b * c * sin(radians(alpha))) / V bstar = (c * a * sin(radians(beta))) / V cstar = (a * b * sin(radians(gamma))) / V # matrix with the reciprocal lattice vectors: N = mpm.matrix([[astar, 0, 0], [0, bstar, 0], [0, 0, cstar]]) # Finally transform Uij values from fractional to cartesian axis system: Ucart = A * N * Uij * N.T * A.T return Ucart
def jac_Diode_In_mpmath (x,b,c,y): """ [Реестровая] непосредственная проверка невозможна :param x: :param b: :param c: :param y: :return: """ global FT dfdbMPM=lambda y,x,b,c: mpm.matrix( [ [mpm.exp((-b[2]*y[0] + x[0])/(FT*b[1])) - 1, -b[0]*(-b[2]*y[0] + x[0])*mpm.exp((-b[2]*y[0] + x[0])/(FT*b[1]))/(FT*b[1]**2), -b[0]*y[0]*mpm.exp((-b[2]*y[0] + x[0])/(FT*b[1]))/(FT*b[1])] ]) dfdyMPM=lambda y,x,b,c: mpm.matrix ([[ -1 - b[0]*b[2]*mpm.exp((-b[2]*y[0] + x[0])/(FT*b[1]))/(FT*b[1])]]) jacf=dfdyMPM(y,x,b,c)**-1 * dfdbMPM(y,x,b,c) return jacf
def test_nstr(): m = matrix([[0.75, 0.190940654, -0.0299195971], [0.190940654, 0.65625, 0.205663228], [-0.0299195971, 0.205663228, 0.64453125e-20]]) assert nstr(m, 4, min_fixed=-inf) == \ '''[ 0.75 0.1909 -0.02992] [ 0.1909 0.6563 0.2057] [-0.02992 0.2057 0.000000000000000000006445]''' assert nstr(m, 4) == \ '''[ 0.75 0.1909 -0.02992]
def _readCoefficientsForFit(self, fit, ci, typeString): fileName = self.resultFileHandler.getCoeffFileName(fit, ci, typeString) if QSMODE == MODE_NORM: return np.asmatrix(np.loadtxt(fileName, dtype=np.complex128, delimiter=",")) else: f = open( fileName, "r" ) s1 = f.read() l1 = s1.split("\n") l2 = [self._splitmpRows(s) for s in l1] l3 = [map(lambda s:s.replace("[","").replace("]","").replace("[","").replace(")",""),l) for l in l2] return mpmath.matrix(l3)
def orthogonal_matrix(self): """ Converts von fractional to cartesian. Invert the matrix to do the opposite. """ import mpmath as mpm Am = mpm.matrix([[self.a, self.b * cos(self.gamma), self.c * cos(self.beta)], [0, self.b * sin(self.gamma), (self.c * (cos(self.alpha) - cos(self.beta) * cos(self.gamma)) / sin(self.gamma))], [0, 0, self.V / (self.a * self.b * sin(self.gamma))]]) return Am
def diodeResistorIMPLICITJac(x, b, c, y): FT = 0.02586419 # подогнанное по pspice dfdb = lambda y, x, b, c: mpm.matrix( [ [ math.exp((-b[2] * y[0] + x[0]) / (FT * b[1])) - 1, -b[0] * (-b[2] * y[0] + x[0]) * math.exp((-b[2] * y[0] + x[0]) / (FT * b[1])) / (FT * b[1] ** 2), -b[0] * y[0] * math.exp((-b[2] * y[0] + x[0]) / (FT * b[1])) / (FT * b[1]), ] ] ) dfdy = lambda y, x, b, c: mpm.matrix( [-1 - b[0] * b[2] * math.exp((-b[2] * y[0] + x[0]) / (FT * b[1])) / (FT * b[1])] ) # возвращает структурную матрицу # jacf=lambda x,b,c,y: jjacf(x,b,c,y,dfdb,dfdy) jacf = (dfdy(y, x, b, c) ** -1) * dfdb(y, x, b, c) return jacf
def test_mev(): output("""\ reim:{$[0>type x;1 0*x;2=count x;x;'`]}; mc:{((x[0]*y 0)-x[1]*y 1;(x[0]*y 1)+x[1]*y 0)}; mmc:{((.qml.mm[x 0]y 0)-.qml.mm[x 1]y 1;(.qml.mm[x 0]y 1)+.qml.mm[x 1]y 0)}; mev_:{[b;x] if[2<>count wv:.qml.mev x;'`length]; if[not all over prec>=abs mmc[flip vc;flip(flip')(reim'')flip x]- flip(w:reim'[wv 0])mc'vc:(flip')(reim'')(v:wv 1);'`check]; / Normalize sign; LAPACK already normalized to real v*:1-2*0>{x a?max a:abs x}each vc[;0]; (?'[prec>=abs w[;1];w[;0];w];?'[b;v;0n])};""") for A in eigenvalue_subjects: if A.rows <= 3: V = [] for w, n, r in A.eigenvects(): w = sp.simplify(sp.expand_complex(w)) if len(r) == 1: r = r[0] r = sp.simplify(sp.expand_complex(r)) r = r.normalized() / sp.sign(max(r, key=abs)) r = sp.simplify(sp.expand_complex(r)) else: r = None V.extend([(w, r)]*n) V.sort(key=lambda (x, _): (-abs(x), -sp.im(x))) else: Am = mp.matrix(A) # extra precision for complex pairs to be equal in sort with mp.extradps(mp.mp.dps): W, R = mp.eig(Am) V = [] for w, r in zip(W, (R.column(i) for i in range(R.cols))): w = mp.chop(w) with mp.extradps(mp.mp.dps): _, S, _ = mp.svd(Am - w*mp.eye(A.rows)) if sum(x == 0 for x in mp.chop(S)) == 1: # nullity 1, so normalized eigenvector is unique r /= mp.norm(r) * mp.sign(max(r, key=abs)) r = mp.chop(r) else: r = None V.append((w, r)) V.sort(key=lambda (x, _): (-abs(x), -x.imag)) W, R = zip(*V) test("mev_[%sb" % "".join("0" if r is None else "1" for r in R), A, (W, [r if r is None else list(r) for r in R]), complex_pair=True)
def solve(cls, left_mat, right_mat): """Solve ``Ax = b`` for ``x``. ``A`` is given by ``left_mat`` and ``b`` by ``right_mat``. This method seeks to mirror :meth:`mpmath.matrices.linalg.LinearAlgebraMethods.lu_solve`, which uses :meth:`mpmath.matrices.linalg.LinearAlgebraMethods.LU_decomp`, :meth:`mpmath.matrices.linalg.LinearAlgebraMethods.L_solve` and :meth:`mpmath.matrices.linalg.LinearAlgebraMethods.U_solve`. Due to limitations of :mod:`mpmath` we use modified helpers to accomplish the upper- and lower-triangular solves. We also cache the LU-factorization for future uses. It's worth pointing out that :func:`numpy.linalg.solve` works in exactly this fashion. From the `C source`_ there is a ``lapack_func`` that gets defined and is eventually used `in Python`_ as ``gufunc``. Notice that the ``lapack_func`` is ``dgesv`` for doubles. Checking the `LAPACK docs`_ verifies the ``dgesv`` does an LU and then two triangular solves. .. _C source: https://github.com/numpy/numpy/blob/\ 4123a2d55c353e71f665712b4de578f933bd4135/numpy/\ linalg/umath_linalg.c.src#L1579 .. _in Python: https://github.com/numpy/numpy/blob/\ 4123a2d55c353e71f665712b4de578f933bd4135/\ numpy/linalg/linalg.py#L384 .. _LAPACK docs: http://www.netlib.org/lapack/explore-html/d7/d3b/\ group__double_g_esolve.html\ #ga5ee879032a8365897c3ba91e3dc8d512 """ left_mat_id = id(left_mat) if left_mat_id not in cls._solve_lu_cache: # left_mat is a NumPy matrix, so must first be # converted to a mpmath matrix. lu_parts, pivots = mpmath.mp.LU_decomp( mpmath.matrix(left_mat.tolist())) # Convert back to a NumPy matrix. lu_parts = np.array(lu_parts.tolist()) cls._solve_lu_cache[left_mat_id] = lu_parts, pivots lu_parts, pivots = cls._solve_lu_cache[left_mat_id] solution = _forward_substitution(lu_parts, right_mat, pivots) solution = _back_substitution(lu_parts, solution) return solution
def makeAinitMpmath (bstart, bend, Skbinit, binit, isBinitGood=True): """ расчёт ведётся по правилу "binit есть хорошее предположение в рамках области" :param bstart: :param bend: :param Skbinit: :param binit: :return: """ A=mpm.matrix( len(binit), 2 ) for i in range (len(binit)): if isBinitGood: A[i,0] = mpm.mpf('0.001')*(binit[i]-bstart[i])*Skbinit A[i,1] = mpm.mpf('0.001')*(bend[i]-binit[i])*Skbinit else: A[i,0] = A[i,1] = mpm.mpf('0.001')*(bend[i]-bstart[i])*Skbinit #универсально return A
def __init__(self, screen, placement = (0, 0), scene_dimensions = None, bg_color = (100, 100, 100)): self._world = None #the target screen which the final image of the screen is blitted onto self.screen = screen #the placement of the final image of the scene on the screen defaults to the top left corner #these are screen coordinates self.screen_placement = placement self.scr_t = mp.matrix([[1, 0, placement[X]], [0, 1, placement[Y]], [0, 0, 1]]) #Scene is a surface which everything in the world is blitted onto if not scene_dimensions: #the scene's width and height defaults to the width and height of the screen scene_dimensions = (screen.get_width(), screen.get_height()) self.scene = pygame.Surface(scene_dimensions) self.scene_rect = self.scene.get_rect() #the placement of the viewport in terms of global coordinates self.scene_placement = (0, 0) self.scene_scale = 1 self.bg_color = bg_color
def global_to_map(self, global_coordinates): """ Maps global coordinates to map coordinates. Mainly used to tell which voxel the mouse pointer is on. Implementation based on article: http://www.alcove-games.com/advanced-tutorials/isometric-tile-picking/ """ (gx, gy) = global_coordinates #depth info comes from the currently activated layer mz = self._active_layer #turn the global coordinates into a homogenous vector g_coord = mp.matrix([[gx], [gy + mz * self._voxel_dimensions[DEPTH]], [1]]) #Apply the isometric unprojection matrix from common_util g_coord = UNPROJECT * g_coord #divide and round the coordinates to get integer indexes. mx = int(mp.nint(g_coord[X]) / self._side_length) my = int(mp.nint(g_coord[Y]) / self._side_length) return (mx, my, mz)
def apply_dephasing(number_of_spins, alpha, B,fm_str = 'AFM',kT = 0.0): ''' takes number of spins, alpha, and the magnetic field and returns the hamiltonian along with its ground state and the dephased ground state choose fm_str = 'FM' for ferromagnetic interaction, and 'AFM' for anti-ferromagnetic ''' if fm_str == 'FM': calc = ising_calculator_FM(number_of_spins, alpha, B) elif fm_str == 'AFM': calc = ising_calculator_AFM(number_of_spins, alpha, B) H = calc.get_H() if kT == 0.0: energy,groundstate = H.groundstate() dm_groundstate = ket2dm(groundstate) else: Hdata = H.data.todense() arr_mp = mp.matrix(-Hdata /kT) exp_mp = mp.expm(arr_mp) trace = np.array(exp_mp.tolist()).trace() normalized_mp = exp_mp / trace normalized_np = np.array(normalized_mp.tolist(), dtype = np.complex) dm_groundstate = Qobj(normalized_np, dims = 2 * [number_of_spins*[2]]) dephased = do_dephasing_dm(dm_groundstate, number_of_spins) return H, dm_groundstate, dephased
def QSmatrix(val): if QSMODE == MODE_NORM: return np.matrix(val, dtype=np.complex128) else: return mpmath.matrix(val)
def __init__(self,rang=10,acc=100): # Generates the coefficients of Legendre polynomial of n-th order. # acc is the number of decimal characters of the coefficients. # self.cf is the list with coefficients. self.rang = rang self.acc = mp.dps = acc cn = mpf(0.0) k = mpf(0) n = mpf(rang) m = mpf(n/2) cf = [] for k in range(n+1): cn = (- 1)**(n+k)*factorial(n+k)/(factorial(nk)*factorial(k)*factorial(k)) cf.append(cn) cf.reverse() # Generates the coefficients of of the implicit Runge-Kutta scheme of Gauss-Legendre type. # acc is the number of the decimal characters of the coefficients. # Gives back the cortege (r,b,a), the terms of which correspond to Butcher scheme # # r1 | a11 . . . а1n # . | . . # . | . . # . | . . # rn | an1 . . . ann # ---+-------------- # | b1 . . . bn self.r = polyroots(cf) A1 = matrix(rang) for j in range(n): for k in range(n): A1[k,j] = self.r[j]**k bn = [] for j in range(n): bn.append(mpf(1.0)/mpf(j+1)) B = matrix(bn) self.b = lu_solve(A1,B) self.a = matrix(rang) for i in range(1,n+1): A1 = matrix(rang) cil = [] for l in range(1,n+1): cil.append(mpf(self.r[i- 1])**l/mpf(l)) for j in range(n): A1[l-1,j] = self.r[j]**(l-1) Cil = matrix(cil) an = lu_solve(A1,Cil) for k in range(n): self.a[i-1,k] = an[k] def init(self,f,t,h,initvalues): self.size = len(initvalues) self.f = f 31 self.t = t self.h = h self.yb = matrix(initvalues) self.ks = matrix(self.size,self.rang) for k in range(self.size): for i in range(self.rang): self.ks[k,i] = self.r[i] self.tn = matrix(1,self.rang) for i in range(self.rang): self.tn[i] = t + h*self.r[i] self.y = matrix(self.size,self.rang) for k in range(self.size): for i in range(self.rang): self.y[k,i] = self.yb[k] temp = mpf(0.0) for j in range(self.rang): temp += self.a[i,j]*self.ks[k,j] self.y[k,i] += temp self.yn = matrix(self.yb) def iterate(self,tn,y,yn,ks): # Generates the coefficients of the implicit Runge-Kutta scheme for the given step # with the method of the simple iteration with an initial value, coinciding with the coefficients, # calculated at the previous step. At sufficiently small step this must # work. There exists such a value of the step, Under which convergence is guaranteed. # No automatic re-setup of the step is foreseen in this procedure. mp.dps = self.acc y0 = matrix(yn) norme = mpf(1.0) #eps0 = pow(eps,mpf(3.0)/mpf(4.0)) eps0 = sqrt(eps) ks1 = matrix(self.size,self.rang) yt = matrix(1,self.size) count = 0 while True: count += 1 for i in range(self.rang): for k in range(self.size): yt[k] = y[k,i] for k in range(self.size): ks1[k,i] = self.f(tn,yt)[k] norme = mpf(0.0) 2 for k in range(self.size): for i in range(self.rang): norme += (ks1[k,i]- ks[k,i])*(ks1[k,i]-ks[k,i]) norme = sqrt(norme) for k in range(self.size): for i in range(self.rang): ks[k,i] = ks1[k,i] for k in range(self.size): for i in range(self.rang): y[k,i] = y0[k] for j in range(self.rang): y[k,i] += self.h*self.a[i,j]*ks[k,j] if norme <= eps0: break if count >= 100: print unicode('No convergence','UTF-8') exit(0) return ks1 def step(self): mp.dps = self.acc self.ks = self.iterate(self.tn,self.y,self.yn,self.ks) for k in range(self.size): for i in range(self.rang): self.yn[k] += self.h*self.b[i]*self.ks[k,i] for k in range(self.size): for i in range(self.rang): self.y[k,i] = self.yn[k] for j in range(self.rang): self.y[k,i] += self.a[i,j]*self.ks[k,j] self.t += self.h for i in range(self.rang): self.tn[i] = self.t + self.h*self.r[i] return self.yn
def convert_mpmath_mat( M): return mpmath.matrix([i for i in M.tolist()])
) P[n, n+1] = \ ((N-n)/N) * (epsilon * (1/2) + (1 - epsilon) * ((n/(N-1) > p) + (n/(N-1) == p) * (1/2)) ) P[n, n] = 1 - P[n, n-1] - P[n, n+1] P[N, N-1], P[N, N] = epsilon * (1/2), 1 - epsilon * (1/2) return P # Stochastic matrix instances Ps = [] Ps.append( mp.matrix([[0.9 , 0.075, 0.025], [0.15, 0.8 , 0.05 ], [0.25, 0.25 , 0.5 ]]) ) Ps.append(KMR_Markov_matrix_sequential(N=3, p=1./3, epsilon=1e-14)) Ps.append(KMR_Markov_matrix_sequential(N=27, p=1./3, epsilon=1e-2)) # Transition rate matrix instances As = [P.copy() for P in Ps] for A in As: for i in range(A.rows): A[i, i] = -mp.fsum((A[i, j] for j in range(A.cols) if j != i)) def run_stoch_eig(P, verbose=0): """ stoch_eig returns a stochastic vector x such that x P = x
def inv_trafo(self): if self._inv_trafo is None: M = mpmath.matrix(self.trafo.tolist()) self._inv_trafo = ndarray.Array((M**-1).tolist()) return self._inv_trafo