def __dip__(self, p: int, kmax: int, f: LambdaType, x: list, eps: float) -> tuple: """ Calculates the df(s) = (s-1)-th derivative of f at O , for s = 1 .. p+1. Uses k-th degree polynomial for some k satisfying p <= k <= kmax. If the relative change in df(s) from k - 1 to k is less than eps then this determines k and success is true. Otherwise k = kmax and success is false. :param p: maximum derivative to calculate; p <= length(x) <= kmax :param kmax: maximum degree of the interpolating polynomial :param f: function to derive :param x: array of values around 0 :param eps: desired tolerance :return: array of derivatives at 0 """ self.C = mp.zeros(1, int(kmax * (kmax + 3) / 2) + 1) df = mp.zeros(1, p + 1) for k in range(0, kmax + 1): self.__update__(int(k), int(p), x, f(x[int(k)])) if k < p: continue self.r = mp.mpf(1) for s in range(0, p + 1): if self.r: self.r = mp.mpf( mp.fabs(self.C[k - s] - df[s]) <= eps * mp.fabs(self.C[k - s])) df[s] = self.C[k - s] if self.r: break for s in range(1, p + 1): df[s] = mp.factorial(s) * df[s] return df
def my_forward_subst(L, i): """ This function performs the forward substitution for solution of the system Lx = e_i where L - is a lower triangular matrix with 1s on the main diagonal e_i - i-th identity vector All the computations are done exactly with MPMATH Parameters ---------- L - n x n lower-triangular matrix with ones on the diagonal i - index for the canonical vector Returns ------- x - n x 1 vector of the solution """ n = L.rows x = mpmath.zeros(n, 1) e = mpmath.zeros(n, 1) e[i, 0] = mpmath.mp.one x[0,0] = e[0,0] for i in range(1, n): x[i,0] = e[i] for j in range(0, i): tmp = mpmath.fmul(L[i,j], x[j,0], exact=True) x[i,0] = mpmath.fsub(x[i,0], tmp, exact=True) return x
def zero_matrix(rows, cols=None): if cols is None: cols = rows if mode == mode_python: return np.matrix(np.zeros((rows, cols), dtype=np.complex128)) else: return mpmath.zeros(rows, cols)
def KMR_Markov_matrix_sequential(N, p, epsilon): """ Generate a Markov matrix arising from a certain game-theoretic model Parameters ---------- N : int p : float Between 0 and 1 epsilon : float Between 0 and 1 Returns ------- P : matrix of shape (N+1, N+1) """ P = mp.zeros(N+1, N+1) P[0, 0], P[0, 1] = 1 - epsilon * (1/2), epsilon * (1/2) for n in range(1, N): P[n, n-1] = \ (n/N) * (epsilon * (1/2) + (1 - epsilon) * (((n-1)/(N-1) < p) + ((n-1)/(N-1) == p) * (1/2)) ) 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
def iv_P_norm_expm(P_sqrt_T, M1, A, M2, tau): """ Bound on P-ellipsoid norm of (M1 (expm(A*t) - I) M2) for |t| < tau using the theorem in arXiv:1911.02537, section "Norm bounding of summands" @param P_sqrt_T: see iv_P_norm() """ P_sqrt_T = iv.matrix(P_sqrt_T) M1 = iv.matrix(M1) A = iv.matrix(A) M2 = iv.matrix(M2) # coerce tau to maximum tau = abs(iv.mpf(tau)).b # P-ellipsoid norms M1_p = iv_P_norm(M=M1, P_sqrt_T=P_sqrt_T) M2_p = iv_P_norm(M=M2, P_sqrt_T=P_sqrt_T) A_p = iv_P_norm(M=A, P_sqrt_T=P_sqrt_T) # A_pow[i] = A ** i A_pow = _iv_matrix_powers(A) # Work around bug in mpmath, see comment in iv_P_norm() zero = iv.matrix(mp.zeros(len(A))) M1 = zero + M1 # terms from [arXiv:1911.02537] M1_Ai_M2_p = lambda i: iv_P_norm(M=M1 @ A_pow[i] @ M2, P_sqrt_T=P_sqrt_T) gamma = lambda i: 1 / math.factorial(i) * (M1_Ai_M2_p(i) - M1_p * A_p ** i * M2_p) max_norm = sum([gamma(i) * (tau ** i) for i in range(1, IV_NORM_EVAL_ORDER + 1)]) + M1_p * M2_p * (iv.exp(A_p * tau) - 1) # the lower bound is always 0 (for t=0) return mp.mpi([0, max_norm.b])
def qr_solve_lsq(M, b): Vt = mp.qr_solve(M, b) V = mp.zeros(M.cols,1) for i in range(M.cols): V[i] = Vt[0][i] return V
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 test_mpf_matrix_fsub(self): A = numpy.matrix(numpy.random.rand(5, 5)) AA = mpf_matrix_fsub(A, A) Z = mpmath.zeros(5,5) self.assertEqual(AA, Z) AA = mpf_matrix_fadd(AA, A) self.assertEqual(AA, python2mpf_matrix(A))
def rotate_mp(pts, x, y): out = mpm.zeros(pts.rows, pts.cols) v = x/mpm.norm(x) cos = mpm.fdot(x,y) / (mpm.norm(x), mpm.norm(y)) sin = mpm.sqrt(1.-cos**2) u = y - mpm.fdot(v, y) * v mat = mpm.eye(x.cols) - u.T * u - v.T * v \ + cos * u.T * u - sin * v.T * u + sin * u.T * v + cos * v.T * v return mat
def cauchy_eigen(mu, dps): mu = np.atleast_1d(mu) n = len(mu) with mp.workdps(dps): mu = mp.matrix(mu) M = mp.zeros(n, n) for i, j in product(range(n), range(n)): M[i, j] = (mu[i] + mu[j].conjugate())**(-1) ewL, QL = mp.eighe(M) return ewL, QL
def test_add_exact(): A = numpy.random.rand(5, 5) A = MPFMatrix(A) B = MPFMatrix(mpmath.zeros(5, 5)) C0 = A.add_exact(B) assert C0.equal(A) C1 = A.add_exact(A) C1 = C1.sub_exact(A) assert C1.equal(A)
def python2mpf_matrix(M): if not isinstance(M, numpy.matrix): raise ValueError('Expected a numpy matrix, instead have %s' % type(M)) n, m = M.shape Mmp = mp.zeros(n, m) for i in range(0, n): for j in range(0, m): Mmp[i, j] = mp.mpf(M[i, j]) return Mmp
def subspace_angle_V_M_mp(mu, lam, dps=100): r"""Multiprecision implementation computing the subspace angle between V(mu) and M(lam) """ n = len(mu) lam = np.atleast_1d(lam) m = len(lam) with mp.workdps(dps): mu = mp.matrix(mu) lam = mp.matrix(lam) # Construct the Cauchy mass matrix #M = mp.zeros(n,n) #for i,j in product(range(n), range(n)): # M[i,j] = (mu[i] + mu[j].conjugate())**(-1) #ewL, QL = mp.eighe(M) ewL, QL = cauchy_eigen(mu, dps) # Construct the right hand side Mhat matrix Mhat = mp.zeros(2 * m, 2 * m) for i, j in product(range(m), range(m)): Mhat[i, j] = (-lam[i] - lam[j].conjugate())**(-1) Mhat[i, m + j] = (-lam[i] - lam[j].conjugate())**(-2) Mhat[m + i, j] = (-lam[i] - lam[j].conjugate())**(-2).conjugate() Mhat[m + i, m + j] = 2 * (-lam[i] - lam[j].conjugate())**(-3) # Construct the interior matrix A = mp.zeros(n, 2 * m) for i, j in product(range(n), range(m)): A[i, j] = (mu[i] - lam[j])**(-1) A[i, m + j] = (mu[i] - lam[j])**(-2) ewR, QR = mp.eighe(Mhat) AA = mp.diag([1 / mp.sqrt(ewL[i]) for i in range(n)]) * (QL.H * A * QR) * mp.diag( [1 / mp.sqrt(ewR[i]) for i in range(2 * m)]) U, s, VH = mp.svd(AA) phi = np.array([float(mp.acos(si)) for si in s]) return phi
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 example_matrices(self, include_singular=True, random=100): examples = [ iv.matrix([[1, 2], [4, 5]]) + iv.mpf([-1, +1]) * mp.mpf(1e-10), iv.eye(2) * 0.5, iv.diag([1, 1e-10]), iv.eye(2) * 1e-302 ] for n in [1, 4, 17]: for i in range(random // n): examples.append(iv.matrix(mp.randmatrix(n))) if include_singular: examples.append(iv.matrix(mp.zeros(4))) examples.append(iv.diag([1, 1e-200])) return examples
def comp_pw_coal_cont(m, Ne_inv): """Function to evaluate the coal. intensities for the given migration and effective population sizes, in the time window of t generations. Here we use compute an infinitesimal rate matrix Q from the migration rates and population sizes and use the exponentiation of this rate matrix to compute the transition probabilities. """ numdemes = len(Ne_inv) if np.shape(m) != (numdemes, numdemes): raise Exception('Migration matrix and population size vector indicate different number of demes.') nr = numdemes * (numdemes + 1) / 2 + 1 Q = mp.zeros(nr, nr) rnum = -1 demePairs = {} for p1 in xrange(numdemes): for p2 in xrange(p1, numdemes): rnum += 1 demePairs[p1, p2] = rnum for dp1 in demePairs.keys(): if dp1[0] == dp1[1]: Q[demePairs[dp1], nr - 1] = 0.5 * Ne_inv[dp1[0]] for dp2 in demePairs.keys(): if dp1 == dp2: continue if dp1[0] == dp1[1]: if dp2[0] == dp2[1]: continue elif dp2[0] == dp1[0]: Q[demePairs[dp1], demePairs[dp2]] = 2 * m[dp1[1]][dp2[1]] elif dp2[1] == dp1[1]: Q[demePairs[dp1], demePairs[dp2]] = 2 * m[dp1[0]][dp2[0]] elif dp2[0] in dp1: if dp1[0] == dp2[0]: Q[demePairs[dp1], demePairs[dp2]] = m[dp1[1]][dp2[1]] else: Q[demePairs[dp1], demePairs[dp2]] = m[dp1[0]][dp2[1]] elif dp2[1] in dp1: if dp1[0] == dp2[1]: Q[demePairs[dp1], demePairs[dp2]] = m[dp1[1]][dp2[0]] else: Q[demePairs[dp1], demePairs[dp2]] = m[dp1[0]][dp2[0]] for dp1 in demePairs.keys(): Q[demePairs[dp1], demePairs[dp1]] = -sum(Q[demePairs[dp1], :]) return Q
def test_construction(): A = mpmath.zeros(5, 5) Amp = MPFMatrix(A) assert (Amp.almost_close(A)) assert A == Amp.matrix A = numpy.matrix(numpy.zeros([5, 5])) Amp = MPFMatrix(A) assert (Amp.almost_close(A)) A = numpy.zeros(5) Amp = MPFMatrix(A) assert (Amp.almost_close(A)) B = MPFMatrix(A) assert (B.almost_close(A))
def divided_diff_coeffs_all_mpmath(x, y): """ Function to calculate the divided differences table """ n = len(y) coeffs = mpmath.zeros(n) knots = mpmath.matrix(x) # the first column is y for i in range(n): coeffs[i, 0] = y[i] for j in range(1, n): for i in range(n - j): coeffs[i, j] = (coeffs[i + 1, j - 1] - coeffs[i, j - 1]) / (knots[i + j] - knots[i]) return coeffs
def converge_pops(popDict, scramb): """Changes the scrambling matrix appropriately upon the merging of populations. """ npop = scramb.cols npop = int(np.real(np.sqrt(8 * npop - 7)) / 2) nr = scramb.rows nc = len(popDict) nc = nc * (nc + 1) / 2 + 1 temp = mp.zeros(nr, nc) temp[:, -1] = scramb[:, -1] ptc = pop_to_col(popDict, npop) for j in xrange(nc - 1): for k in xrange(len(ptc[j])): temp[:, j] = temp[:, j] + scramb[:, ptc[j][k]] return temp
def compute_pw_coal_rates(Nes, ms, ts, popmaps): """Given a list of population sizes and the migration matrix, one for each time slice, compute the expected coalescent rates for all possible pairs of lines. Uses the comp_pw_coal_cont function to do this for each time slice. The lists ms and Nes must be ordered from most recent to most ancient. Here ts is the list of time slice lengths - in the same order. popmaps is a list which tells which pops merge back in time at the beginning of this time slice. Each entry of popmaps is a list of arrays or tuples with all pops that merge into one """ numslices = len(ts) numpops = len(Nes[0]) nr = numpops * (numpops + 1) / 2 + 1 exp_rates = mp.zeros(nr - 1, numslices) P0 = mp.eye(nr) for i in xrange(numslices): Ne_inv = [ 1.0 / x for x in Nes[i] ] mtemp = ms[i] oldnumpops = numpops numpops = len(Ne_inv) m = np.zeros((numpops, numpops)) cnt = 0 if len(popmaps[i]) == numpops: P0 = converge_pops(popmaps[i], P0) elif len(popmaps[i]) > 0: raise Exception('Population map and other parameters do not match ' + str(i)) for ii in xrange(numpops): for jj in xrange(ii + 1, numpops): m[ii, jj] = m[jj, ii] = mtemp[cnt] cnt += 1 Q = comp_pw_coal_cont(m, Ne_inv) eQ = expM(ts[i] * Q) P = P0 * eQ exp_rates[:, i] = P[0:nr - 1, P.cols - 1] P0 = P0 * conv_scrambling_matrix(eQ) for r in xrange(exp_rates.rows): for c in xrange(exp_rates.cols): if exp_rates[r, c] < 0: exp_rates[r, c] = 0 return exp_rates
def test_mul(): A = numpy.random.rand(5, 5) I = numpy.eye(5) Z = numpy.zeros([5, 5]) Impmath = mpmath.eye(5) Zmpmath = mpmath.zeros(5, 5) A = MPFMatrix(A) C0 = A * I assert C0.almost_close(A) C1 = A * Impmath assert C1.almost_close(A) C2 = MPFMatrix(I) * A assert C2.almost_close(A) C3 = A * Z assert C3.almost_close(Z) C4 = A * Zmpmath assert C4.almost_close(Zmpmath)
def remezStep(self, control): # eval at control points fxn = mp.matrix([self.evalFunc(c) for c in control]) # create linear system with chebyshev polynomials size = self.order + 2 system = mp.zeros(size) for n in range(self.order + 1): for i in range(self.order + 2): system[i, n] = mp.chebyt(n, control[i]) # last column is oscillating error for i in range(size): sign = -1 if ((i & 1) == 0) else +1 scale = 0.0 if i in [0, size - 1] else 1.0 system[i, size - 1] = sign * scale * mp.fabs(self.evalWeight(control[i])) #print(system) # solve the system solved = system**-1 #print(solved) # compute polynomial estimate (as Chebyshev weights) weights = vzeros(size - 1) for n in range(size - 1): weights[n] = mp.fdot(solved[n, :], fxn) #print(f' weights: {weights}') # estimate error # self.weights = weights # est = [self.evalEstimate(x) for x in control] # print(' est:', est) # print(' fxn:', fxn.T) return weights
def initRemez(self): #print('Remez.init()') # constants for domain (xMin, xMax) = self.domain self.k1 = (xMax + xMin) * 0.5 self.k2 = (xMax - xMin) * 0.5 # initial estimates for function roots (where error == 0.0) size = self.order + 1 roots = vzeros(size) fxn = vzeros(size) # \todo [petri] use linspace for i in range(size): roots[i] = (2.0 * i - self.order) / size fxn[i] = self.evalFunc(roots[i]) # build matrix of Chebyshev evaluations system = mp.zeros(size) for order in range(size): for i in range(size): system[i, order] = mp.chebyt(order, roots[i]) # solve system solved = system**-1 # compute Chebyshev weights of new approximation weights = vzeros(size) for n in range(size): weights[n] = mp.fdot(solved[n, :], fxn) #print(f' weights: {weights.T}') # store roots & weights self.roots = roots self.weights = weights self.maxError = 1000.0
def eqn42_solve( geom, Nmax ): # eqn 4.2 NMAX = Nmax # where to truncate the infinite system of eqns S = geom['S'] distanceqp = geom['distanceqp'] thetaqp = geom['thetaqp'] phiqp = geom['phiqp'] radii = geom['radii'] # coefficient matrix if USEMPMATH: CM = mpmath.zeros( S*NMAX*(2*NMAX+1) ) else: CM = np.zeros( (S*NMAX*(2*NMAX+1), S*NMAX*(2*NMAX+1)) ) for sprimei,sprime in enumerate(range(S)): for nprimei,nprime in enumerate(range(NMAX)): for mprimei,mprime in enumerate(range(-nprime,nprime+1)): # row index ri = sprimei*NMAX*(2*NMAX+1) + nprimei*(2*NMAX+1) + mprimei # row prefactors prefac = (-1)**(nprime+mprime) * radii[sprimei]**(nprime+1) \ * 1./factorial(nprime+mprime) for si,s in enumerate(range(S)): if sprimei != si: for ni,n in enumerate(range(NMAX)): for mi,m in enumerate(range(-n,n+1)): # column index ci = si*NMAX*(2*NMAX+1) + ni*(2*NMAX+1) + mi f1 = distanceqp[sprimei,si]**(-(n+1)) f2 = (radii[sprimei]/distanceqp[sprimei,si])**nprime f3 = factorial(n-m+nprime+mprime)/factorial(n-m) if USEMPMATH: f4 = mpmath.legenp( n+nprime, m-mprime, \ np.cos(thetaqp[sprimei,si]) ) else: f4 = scipy.special.lpmv( m-mprime, n+nprime, \ np.cos(thetaqp[sprimei,si]) ) f5 = np.exp( 1j*(m-mprime)*phiqp[sprimei,si] ) CM[ri,ci] = prefac*f1*f2*f3*f4*f5 if USEMPMATH: CM += mpmath.diag(np.ones(S*NMAX*(2*NMAX+1))) Qs = mpmath.zeros(S) else: CM += np.diag(np.ones(S*NMAX*(2*NMAX+1))) Qs = np.zeros((S,S)) for si in range(S): if USEMPMATH: rhs = mpmath.zeros( S*NMAX*(2*NMAX+1), 1 ) else: rhs = np.zeros((CM.shape[0],)) rhs[si*NMAX*(2*NMAX+1):(si*NMAX+1)*(2*NMAX+1)] = radii[si] if USEMPMATH: sol = mpmath.lu_solve( CM, rhs ) else: sol = np.linalg.solve( CM, rhs ) #print sol[::(NMAX*(2*NMAX+1))] Qs[si,:] = sol[::(NMAX*(2*NMAX+1))] return Qs
def QSsqZeros(sz): if QSMODE == MODE_NORM: return np.matrix(np.zeros((sz, sz), dtype=np.complex128)) else: return mpmath.zeros(sz)
def nashEquilibria(A,B=None,select='all'): ''' Calculate all extreme equilibria or one equilibrium of a bimatrix game. A and B are list of lists.''' if B is None: # zero-sum game A = np.asmatrix(A) return (minimax(A)+minimax(-A.T)) if select =='all': # complete vertex enumeration with Avis-Fukuda (lrslib) m = len(A) n = len(A[0]) # generate rational fraction game string g = str(m)+' '+str(n)+'\n\n' for i in range(m): for j in range (n): aij = fract(A[i][j],asfloat=False) g += str(aij)+' ' g += '\n' g += '\n' for i in range(m): for j in range (n): bij = fract(B[i][j],asfloat=False) g += str(bij)+' ' g += '\n' # write game file to disk f = open('game','w') print >>f, g f.close() # invoke nash from lrslib subprocess.call(['setnash','game','game1','game2'], stdout=subprocess.PIPE) p2 = subprocess.Popen(['nash','game1','game2'], stdout=subprocess.PIPE) # collate the equilibria result = []; qs = []; H1s = [] line = p2.stdout.readline() while line: if line[0] == '2' or line[0] == '1': line = line.replace('/','./').split() if line[0] == '2': qs.append(map(eval,line[1:-1])) H1s.append(eval(line[-1])) else: p = map(eval,line[1:-1]) H2 = eval(line[-1]) for i in range(len(H1s)): result.append( (p,H1s[i],qs[i],H2) ) qs = [] H1s = [] line = p2.stdout.readline() return result elif select=='perfect': # select the normal form perfect equilibria eqs = nashEquilibria(A,B,select='all') perfect = [] A = np.asmatrix(A) Bt = np.asmatrix(B).T for eq in eqs: P = np.asmatrix(eq[0]) Q = np.asmatrix(eq[2]) if undominated(P,A) and undominated(Q,Bt): perfect.append(eq) return perfect elif select=='one': # Lemke Howson algorithm for one equilibrium. # setup tableau with np matrices A = [ map(fract,row) for row in A ] B = [ map(fract,row) for row in B ] a = np.matrix(A) b = np.matrix(B) m, n = a.shape m = int(m) n = int(n) smallest = min(np.min(a),np.min(b)) A = a - np.ones((m,n))*(smallest - 1) B = b - np.ones((m,n))*(smallest - 1) k = m + n M = np.bmat([ [np.zeros((m,m)), A],[B.T, np.zeros((n,n))] ]) T = np.bmat( [-np.ones((k,1)), M, np.eye(k)] ) # convert it to mpmath matrix T = mp.matrix(T) # initialize beta = range(k,2*k) s = 0 br = -1 # complementary pivoting while (br != 0) and (br != k): tmp = mp.zeros(k,2*k+1) r = leaving(T,s) for i in range(k): for j in range(2*k+1): tmp[i,j] = pivot(i,j,r,s,T) T = tmp br = beta[r] beta[r] = s if br >= k: s = br-k else: s = br+k Y = np.zeros(2*k) for i in range(k): Y[beta[i]] = -T[i,0] P = Y[0:m] P = Matrix(P/np.sum(P)) Q = Y[m:k] Q = Matrix(Q/np.sum(Q)) H1 = np.array((P.T*a*Q)).astype(np.float64)[0][0] H2 = np.array((P.T*b*Q)).astype(np.float64)[0][0] P = list(P) Q = list(Q) return [(P,H1,Q,H2)]
def comp_N_m_mp(obs_rates, t, merge_threshold, useMigration): """This function estimates the N and m parameters for the various time slices. The time slices are given in a vector form 't'. t specifies the length of the time slice, not the time from present to end of time slice (not cumulative but atomic) Also, the obs_rates are given, for each time slice are given in columns of the obs_rates matrix. Both obs_rates and time slice lengths are given from present to past. """ FTOL = 10.0 PTOL = 1e-20 EPSILON = 1e-11 RESTARTS = 10 FLIMIT = 1e-20 numslices = len(t) nr = obs_rates.rows + 1 numdemes = int(np.real(np.sqrt(8 * nr - 7)) / 2) print 'Starting iterations' P0 = mp.eye(nr) xopts = [] pdlist = [] for i in xrange(numslices): bestxopt = None bestfval = 1e+200 print 'Running for slice ', i if i > 0: x0 = xopt[0:nr - 1].copy() try: xopt = mp.findroot(lambda x: compute_Frob_norm_mig(x, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)), x0) fun = compute_Frob_norm_mig(xopt, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)) bestxopt = xopt bestfval = fun except ValueError as e: print 'Error:', e.message for lll in xrange(numdemes * (numdemes - 1) / 2): x01 = x0[0:nr - 1].copy() x01[numdemes + lll] = 0.0099 try: xopt = mp.findroot(lambda x: compute_Frob_norm_mig(x, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)), x01) fun = compute_Frob_norm_mig(xopt, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)) if fun < bestfval: bestfval = fun bestxopt = xopt except ValueError as e: print 'Error:', e.message reestimate = True while reestimate: pdslice = make_merged_pd(pdlist) print 'pdslice:', pdslice N0_inv = np.random.uniform(5e-05, 0.001, numdemes) m0 = np.random.uniform(0.008, 0.001, numdemes * (numdemes - 1) / 2) x0 = [ mp.convert(rrr) for rrr in N0_inv ] for zz in range(len(m0)): x0.append(mp.convert(m0[zz])) lims = [(1e-15, 0.1)] * numdemes lims += [(1e-15, 0.1)] * (numdemes * (numdemes - 1) / 2) try: xopt = mp.findroot(lambda x: compute_Frob_norm_mig(x, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)), x0) fun = compute_Frob_norm_mig(xopt, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)) if fun < bestfval: bestfval = fun bestxopt = xopt except ValueError as e: print 'Error:', e.message N0_inv = np.random.uniform(5e-05, 0.001, numdemes) m0 = np.random.uniform(1e-08, 0.001, numdemes * (numdemes - 1) / 2) x0 = [ mp.convert(rrr) for rrr in N0_inv ] for zz in range(len(m0)): x0.append(mp.convert(m0[zz])) nrestarts = 0 try: xopt = mp.findroot(lambda x: compute_Frob_norm_mig(x, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)), x0) fun = compute_Frob_norm_mig(xopt, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)) if fun < bestfval: bestxopt = xopt bestfval = fun except ValueError as e: print 'Error:', e.message print nrestarts while nrestarts < RESTARTS and bestfval > FLIMIT: N0_inv = np.random.uniform(5e-05, 0.001, numdemes) m0 = np.random.uniform(1e-08, 0.001, numdemes * (numdemes - 1) / 2) x0 = mp.zeros(len(N0_inv) + len(m0)) for zz in range(len(N0_inv)): x0[zz] = N0_inv[zz] for zz in range(len(m0)): x0[zz + len(N0_inv)] = m0[i] try: xopt = mp.findroot(lambda x: compute_Frob_norm_mig(x, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)), x0) fun = compute_Frob_norm_mig(xopt, t[i], obs_rates[:, i], P0, make_merged_pd(pdlist)) if fun < bestfval: bestfval = fun bestxopt = xopt except ValueError as e: print 'Error:', e.message print nrestarts nrestarts += 1 print bestfval, i, bestxopt[0:numdemes], bestxopt[numdemes:] Ne_inv = bestxopt[0:numdemes] mtemp = bestxopt[numdemes:] popdict = find_pop_merges(Ne_inv, mtemp, t[i], P0, merge_threshold, useMigration) reestimate = False if len(popdict) < numdemes: print 'Merging populations and reestimating parameters:', popdict print bestxopt P0 = converge_pops(popdict, P0) reestimate = True pdlist.append(popdict) numdemes = len(popdict) nr = numdemes * (numdemes + 1) / 2 + 1 lims[:] = [] bestfval = 1e+200 bestxopt = None else: modXopt = [ 1.0 / x for x in bestxopt[0:numdemes] ] cnt = 0 for ii in xrange(numdemes): for jj in xrange(ii + 1, numdemes): modXopt.append(bestxopt[numdemes + cnt]) cnt = cnt + 1 xopts.append(np.array(modXopt)) Ne_inv = bestxopt[0:numdemes] mtemp = bestxopt[numdemes:] m = np.zeros((numdemes, numdemes)) cnt = 0 for ii in xrange(numdemes): for jj in xrange(ii + 1, numdemes): m[ii, jj] = m[jj, ii] = mtemp[cnt] cnt += 1 Q = comp_pw_coal_cont(m, Ne_inv) P = expM(t[i] * Q) print 'est rates', i print np.real(P0 * P)[0:-1, -1] print 'obs rates', i print np.real(obs_rates[:, i]) print 'Min func value', bestfval P0 = P0 * conv_scrambling_matrix(P) ist = raw_input('Waiting for input...') return (xopts, pdlist)
], 'agm': [ 'primitive', [lambda x, y: mp.agm(x) if y is None else mp.agm(x, y[0]), None] ], # 'matrix': [ 'primitive', [ lambda x, y: mp.matrix(x) if isa(x, Vector) else mp.matrix(x) if y is None else mp.matrix(x, y[0]), None ] ], 'matrix-ref': ['primitive', [lambda x, y: x[y[0], y[1], [0]], None]], 'matrix-set': [ 'primitive', [lambda x, y: matrix_set(x, y[0], y[1][0], y[1][1][0]), None] ], 'zeros': ['primitive', [lambda x, y: mp.zeros(x), None]], 'ones': ['primitive', [lambda x, y: mp.ones(x), None]], 'eye': ['primitive', [lambda x, y: mp.eye(x), None]], 'diag': ['primitive', [lambda x, y: mp.diag(x), None]], 'randmatrix': ['primitive', [lambda x, y: mp.randmatrix(x), None]], 'matrix-inv': ['primitive', [lambda x, y: x**(-1), None]], 'norm': [ 'primitive', [lambda x, y: mp.norm(x) if y is None else mp.norm(x, y[0]), None] ], 'mnorm': ['primitive', [lambda x, y: mp.mnorm(x, y[0]), None]], }
def Gauss(mat, prec, piv, pivT): título("Eliminação de Gauss", "=") # Precisão de Dígitos mm.mp.dps = prec # Número de Variáveis nV = len(mat) # Matriz A matA = [] for l in range(nV): matA.append([]) for c in range(nV): matA[l].append(mat[l][c]) matA = mm.matrix(matA) # print("Matriz A") # print(str(matA)) # Matriz B matB = [] c = nV for l in range(nV): matB.append(mat[l][c]) matB = mm.matrix(matB) # print("Matriz B") # print(str(matB)) # Matriz mat = mm.matrix(mat) print("Matriz") print(str(mat)) # Matriz Fatorada matFat, index = fM(mat, prec, piv, pivT) print("Matriz Fatorada") print(str(matFat)) # Matriz X matX = mm.zeros(nV, 1) for d in range(nV - 1, -1, -1): sub = mm.mpf('0.0') for c in range(d + 1, nV): sub = mm.mpf(sub + (matFat[d, c] * matX[c])) matX[d] = mm.mpf((matFat[d, nV] - sub) / matFat[d, d]) print("Matriz X") print(str(matX)) # Erro matE = mm.residual(matA, matX, matB) print("Matriz Erro Residual") print(str(matE)) # Resposta e Resíduo resp = "Eliminação de Gauss:" for l in range(nV): resp += "\nx(" + str(int(index[l])) + ") = " + str(matX[l]) ress = "Resíduo:" for l in range(nV): ress += "\nx(" + str(int(index[l])) + ") = " + str(matE[l]) return resp, ress
def nashEquilibria(A,B=None,select='one',s1=0): ''' Calculate all extreme equilibria or one equilibrium of a bimatrix game. A and B are list of lists.''' if B is None: # zero-sum game A = np.asmatrix(A) return (minimax(A)+minimax(-A.T)) if select =='all': # complete vertex enumeration with Avis-Fukuda (lrslib) m = len(A) n = len(A[0]) # generate rational fraction game string g = str(m)+' '+str(n)+'\n\n' for i in range(m): for j in range (n): aij = fract(A[i][j],asfloat=False) g += str(aij)+' ' g += '\n' g += '\n' for i in range(m): for j in range (n): bij = fract(B[i][j],asfloat=False) g += str(bij)+' ' g += '\n' # write game file to disk f = open('game','w') print >>f, g f.close() # invoke nash from lrslib subprocess.call(['setupnash','game','game1','game2'], stdout=subprocess.PIPE) p2 = subprocess.Popen(['nash','game1','game2'], stdout=subprocess.PIPE) # collate the equilibria result = []; qs = []; H1s = [] line = p2.stdout.readline() while line: if line[0] == '2' or line[0] == '1': line = line.replace('/','./').split() if line[0] == '2': qs.append(map(eval,line[1:-1])) H1s.append(eval(line[-1])) else: p = map(eval,line[1:-1]) H2 = eval(line[-1]) for i in range(len(H1s)): result.append( (p,H1s[i],qs[i],H2) ) qs = [] H1s = [] line = p2.stdout.readline() return result elif select=='perfect': # select the normal form perfect equilibria eqs = nashEquilibria(A,B,select='all') perfect = [] A = np.asmatrix(A) Bt = np.asmatrix(B).T for eq in eqs: P = np.asmatrix(eq[0]) Q = np.asmatrix(eq[2]) if undominated(P,A) and undominated(Q,Bt): perfect.append(eq) return perfect elif select=='one': # Lemke Howson algorithm for one equilibrium. # setup tableau with np matrices A = [ map(fract,row) for row in A ] B = [ map(fract,row) for row in B ] a = np.matrix(A) b = np.matrix(B) m, n = a.shape m = int(m) n = int(n) smallest = min(np.min(a),np.min(b)) A = a - np.ones((m,n))*(smallest - 1) B = b - np.ones((m,n))*(smallest - 1) k = m + n M = np.bmat([ [np.zeros((m,m)), A],[B.T, np.zeros((n,n))] ]) T = np.bmat( [-np.ones((k,1)), M, np.eye(k)] ) # convert it to mpmath matrix T = mp.matrix(T) # initialize beta = range(k,2*k) if s1 > k-1: s1 = 0 s = s1 br = -1 # complementary pivoting while (br != s1) and (br != k+s1): tmp = mp.zeros(k,2*k+1) r = leaving(T,s) for i in range(k): for j in range(2*k+1): tmp[i,j] = pivot(i,j,r,s,T) T = tmp br = beta[r] beta[r] = s if br >= k: s = br-k else: s = br+k Y = np.zeros(2*k) for i in range(k): Y[beta[i]] = -T[i,0] P = Y[0:m] P = Matrix(P/np.sum(P)) Q = Y[m:k] Q = Matrix(Q/np.sum(Q)) H1 = (P*a*Q.T)[0] H2 = (P*b*Q.T)[0] P = list(P) Q = list(Q) return [(P,H1,Q,H2)]
print(times, mpmath.nstr(new_norm_r / init_norm_r)) if (new_norm_r <= (rtol * init_norm_r + atol)): break p = r + beta * p old_norm_r = new_norm_r return times, vec_x # 行列サイズ str_dim = input('正方行列サイズ dim = ') dim = int(str_dim) # 文字列→整数 # (1) mat_a = mpmath.zeros(dim, dim) for i in range(dim): for j in range(dim): mat_a[i, j] = mpmath.mpf(dim - max(i, j)) mat_a = mat_a.T * mat_a # print(mat_a) # x = [1 2 ... dim] vec_true_x = mpmath.matrix([i for i in range(1, dim + 1)]) # nprint(vec_true_x) # b = A * x vec_b = mat_a * vec_true_x # CG法実行
def get_unary(self, item): return { **{ k: calc2.UnaryOperator(s, f, 80) for k, s, f in [ ('abs', 'abs', abs), ('fac', 'fac', mpmath.factorial), ('sqrt', 'sqrt', mpmath.sqrt), ('_/', 'sqrt', mpmath.sqrt), ('√', 'sqrt', mpmath.sqrt), ('ln', 'ln', mpmath.ln), ('lg', 'log10', mpmath.log10), ('exp', 'e^', mpmath.exp), ('floor', 'floor', mpmath.floor), ('ceil', 'ceil', mpmath.ceil), ('det', 'det', mpmath.det), ] }, 'pcn': calc2.UnaryOperator('a%', lambda x: x / 100, 80), '+': calc2.UnaryOperator('(+)', lambda x: x, 0), '-': calc2.UnaryOperator('+/-', lambda x: -x, 80), 'conj': calc2.UnaryOperator( 'conj', lambda x: x.conjugate() if isinstance(x, mpmath.matrix) else mpmath.conj(x), 80), '~': calc2.UnaryOperator( 'conj', lambda x: x.conjugate() if isinstance(x, mpmath.matrix) else mpmath.conj(x), 80), 'O': calc2.UnaryOperator( '[O]', lambda x: mpmath.zeros(*OpList.__analyse_as_pair(x)), 80), 'I': calc2.UnaryOperator( '[I]', lambda x: mpmath.ones(*OpList.__analyse_as_pair(x)), 80), 'E': calc2.UnaryOperator('[E]', lambda x: mpmath.eye(int(x)), 80), 'diag': calc2.UnaryOperator( '[diag]', lambda x: mpmath.diag(OpList.__analyse_list(x)), 80), 'log': calc2.UnaryOperator( 'logbA', lambda x: OpList.__log(*OpList.__analyse_pair(x)), 80), 'tran': calc2.UnaryOperator( '[T]', lambda x: x.transpose() if isinstance(x, mpmath.matrix) else x, 80), **{ k: calc2.UnaryOperator(k, (lambda u: lambda x: u(self._drg2r(x)))(v), 80) for k, v in { 'sin': mpmath.sinpi, 'cos': mpmath.cospi, 'tan': lambda x: mpmath.sinpi(x) / mpmath.cospi(x), 'cot': lambda x: mpmath.cospi(x) / mpmath.sinpi(x), 'sec': lambda x: 1 / mpmath.cospi(x), 'csc': lambda x: 1 / mpmath.sinpi(x), }.items() }, **{ k: calc2.UnaryOperator(k, (lambda u: lambda x: self._r2drg(1 / v(x)))(v), 80) for k, v in { 'asin': mpmath.asin, 'acos': mpmath.acos, 'atan': mpmath.atan, 'acot': mpmath.acot, 'asec': mpmath.asec, 'acsc': mpmath.acsc }.items() }, **{ k: calc2.UnaryOperator(k, v, 80) for k, v in { 'sinh': mpmath.sinh, 'cosh': mpmath.cosh, 'tanh': mpmath.tanh, 'coth': mpmath.coth, 'sech': mpmath.sech, 'csch': mpmath.csch, 'asinh': mpmath.asinh, 'acosh': mpmath.acosh, 'atanh': mpmath.atanh, 'acoth': mpmath.acoth, 'asech': mpmath.asech, 'acsch': mpmath.acsch }.items() } }[item]
def sarkar_embedding(tree, root, **kwargs): ''' Embed a tree in the Poincare disc using Sarkar's algorithm from "Low Distortion Delaunay Embedding of Trees in Hyperbolic Plane. Args: tree (networkx.Graph) : The tree represented with int node labels. Weighted trees should have the edge attribute "weight" root (int): The node to use as the root of the embedding Keyword Args: weighted (bool): True if the tree is weighted (default True) tau (float): the scaling factor for distances. By default it is calculated based on statistics of the tree. epsilon (float): parameter >0 controlling distortion bound (default 0.1). precision (int): number of bits of precision to use. By default it is calculated based on tau and epsilon. Returns: size N x 2 mpmath.matrix containing the coordinates of embedded nodes ''' eps = kwargs.get("epsilon",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,2) place = [] # place the children of root for i, v in enumerate(tree[root]): if weighted: r = mpm.tanh( tau*tree[root][v]["weight"]) else: r = mpm.tanh(tau) theta = 2*i*mpm.pi / tree.degree[root] emb[v,0] = r*mpm.cos(theta) emb[v,1] = r*mpm.sin(theta) place.append((root,v)) # TODO parallelize this while place: u, v = place.pop() # u is the parent of v p, x = emb[u,:], emb[v,:] rp = poincare_reflect0(x, p, precision=prc) arg = mpm.acos(rp[0]/mpm.norm(rp)) if rp[1] < 0: arg = 2*mpm.pi - arg theta = 2*mpm.pi / tree.degree[v] i=0 for w in tree[v]: if w == u: continue i+=1 if weighted: r = mpm.tanh(tau*tree[v][w]["weight"]) else: r = mpm.tanh(tau) w_emb = r * mpm.matrix([mpm.cos(arg+theta*i),mpm.sin(arg+theta*i)]).T w_emb = poincare_reflect0(x, w_emb, precision=prc) emb[w,:] = w_emb place.append((v,w)) return emb
def czeros(n): """Returns a numpy array with n repetitions of mp.mpc(0)""" return np.array(mp.zeros(n,1)) * mp.mpc(0,0)
title = 'base = ' + str(base) + ' humerous = ' + str( humerus) + ' radius = ' + str(radius) fig.suptitle(title) plt.grid(True) for angleL in anglesL: for angleR in anglesR: if forward(base, humerus, radius, angleL, angleR): [x, y] = forward(base, humerus, radius, angleL, angleR) if x >= base / 2: ax.plot(x, y, 'o', color='blue') ax.plot(base - x, y, 'o', color='blue') baselineX = mpmath.linspace(0, 10, 100) baselineY = mpmath.zeros(100, 1) xMin = -10 xMax = 15 yMin = -5 yMax = 30 plotArea(10, 5, 10) ax.plot(baselineX, baselineY, color='black') plt.xlim([xMin, xMax]) plt.ylim([yMin, yMax]) plt.show() plotArea(10, 10, 5) ax.plot(baselineX, baselineY, color='black') plt.xlim([xMin, xMax])