def _gen_mtxnormsdp(self,p,q,r,d,seed): """ Random data generator for matrix norm minimization SDP. """ setseed(seed) n = p + q; I = matrix([ i for j in range(q) for i in range(q,n)]) J = matrix([ j for j in range(q) for i in range(q,n)]) Il = list(misc.sub2ind((n,n),I,J)) if type(d) is float: nz = min(max(1, int(round(d*p*q))), p*q) A = sparse([[spmatrix(normal(p*q,1),Il,[0 for i in range(p*q)],(n**2,1))], [spmatrix(normal(nz*r,1), [i for j in range(r) for i in random.sample(Il,nz)], [j for j in range(r) for i in range(nz)],(n**2,r))]]) elif type(d) is list: if len(d) == r: nz = [min(max(1, int(round(v*p*q))), p*q) for v in d] nnz = sum(nz) A = sparse([[spmatrix(normal(p*q,1),Il,[0 for i in range(p*q)],(n**2,1))], [spmatrix(normal(nnz,1), [i for j in range(r) for i in random.sample(Il,nz[j])], [j for j in range(r) for i in range(nz[j])],(n**2,r))]]) else: raise TypeError self._A = sparse([[A],[spmatrix(-1.,list(range(0,n**2,n+1)),[0 for i in range(n)],(n**2,1))]]) self._b = matrix(0.,(r+1,1)) self._b[-1] = -1.
def _gen_randsdp(self,V,m,d,seed): """ Random data generator """ setseed(seed) n = self._n V = chompack.tril(V) N = len(V) I = V.I; J = V.J Il = misc.sub2ind((n,n),I,J) Id = matrix([i for i in range(len(Il)) if I[i]==J[i]]) # generate random y with norm 1 y0 = normal(m,1) y0 /= blas.nrm2(y0) # generate random S0, X0 S0 = mk_rand(V,cone='posdef',seed=seed) X0 = mk_rand(V,cone='completable',seed=seed) # generate random A1,...,Am if type(d) is float: nz = min(max(1, int(round(d*N))), N) A = sparse([[spmatrix(normal(N,1),Il,[0 for i in range(N)],(n**2,1))], [spmatrix(normal(nz*m,1), [i for j in range(m) for i in random.sample(Il,nz)], [j for j in range(m) for i in range(nz)],(n**2,m))]]) elif type(d) is list: if len(d) == m: nz = [min(max(1, int(round(v*N))), N) for v in d] nnz = sum(nz) A = sparse([[spmatrix(normal(N,1),Il,[0 for i in range(N)],(n**2,1))], [spmatrix(normal(nnz,1), [i for j in range(m) for i in random.sample(Il,nz[j])], [j for j in range(m) for i in range(nz[j])],(n**2,m))]]) else: raise TypeError # compute A0 u = +S0.V for k in range(m): base.gemv(A[:,k+1][Il],matrix(y0[k]),u,beta=1.0,trans='N') A[Il,0] = u self._A = A # compute b X0[Il[Id]] *= 0.5 self._b = matrix(0.,(m,1)) u = matrix(0.) for k in range(m): base.gemv(A[:,k+1][Il],X0.V,u,trans='T',alpha=2.0) self._b[k] = u
def _gen_mtxnormsdp(self, p, q, r, d, seed): """ Random data generator for matrix norm minimization SDP. """ setseed(seed) n = p + q I = matrix([i for j in range(q) for i in range(q, n)]) J = matrix([j for j in range(q) for i in range(q, n)]) Il = misc.sub2ind((n, n), I, J) if type(d) is float: nz = min(max(1, int(round(d * p * q))), p * q) A = sparse( [[ spmatrix(normal(p * q, 1), Il, [0 for i in range(p * q)], (n**2, 1)) ], [ spmatrix( normal(nz * r, 1), [i for j in range(r) for i in random.sample(Il, nz)], [j for j in range(r) for i in range(nz)], (n**2, r)) ]]) elif type(d) is list: if len(d) == r: nz = [min(max(1, int(round(v * p * q))), p * q) for v in d] nnz = sum(nz) A = sparse([[ spmatrix(normal(p * q, 1), Il, [0 for i in range(p * q)], (n**2, 1)) ], [ spmatrix(normal(nnz, 1), [ i for j in range(r) for i in random.sample(Il, nz[j]) ], [j for j in range(r) for i in range(nz[j])], (n**2, r)) ]]) else: raise TypeError self._A = sparse([[A], [ spmatrix(-1., range(0, n**2, n + 1), [0 for i in range(n)], (n**2, 1)) ]]) self._b = matrix(0., (r + 1, 1)) self._b[-1] = -1.
def calcInc(): global F system.Line.gcall() system.PQ.gcall() system.Shunt.gcall() system.PV.gcall() system.SW.gcall() system.Line.Gycall() system.PQ.Gycall() system.Shunt.Gycall() system.PV.Gycall() system.SW.Gycall() A = sparse(system.DAE.Gy) inc = matrix(system.DAE.g) if system.DAE.factorize: F = symbolic(A) #重新排列A矩阵以减少填充并执行LU分解,返回为可以传递的不透明 C object到umfpack.numeric()。 system.DAE.factorize = False try: N = numeric(A, F) solve(A, N, inc) except: print('unexpect') F = symbolic(A) solve(A, numeric(A, F), inc) return inc
def Gycall(self): system.DAE.y = matrix(system.DAE.y) U = exp(system.DAE.y[system.Bus.a] * 1j) V = mul(system.DAE.y[system.Bus.v] + 0j, U) I = self.Y * V nb = len(system.Bus.a) diagU = spmatrix(U, system.Bus.a, system.Bus.a, (nb, nb), 'z') diagV = spmatrix(V, system.Bus.a, system.Bus.a, (nb, nb), 'z') diagI = spmatrix(I, system.Bus.a, system.Bus.a, (nb, nb), 'z') dS = self.Y * diagU dS = diagV * dS.H.T dS += diagI.H.T * diagU dR = diagI dR = dR - self.Y * diagV dR = diagV.H.T * dR # system.DAE.Gy = matrix(0.0, (system.DAE.ny, system.DAE.ny)) # # system.DAE._list2matrix() # system.DAE.Gy = spmatrix(dR.imag().V, dR.imag().I, dR.imag().J, (system.DAE.ny, system.DAE.ny)) \ # + spmatrix(dR.real().V, dR.real().I, dR.real().J+system.Bus.n, (system.DAE.ny, system.DAE.ny)) \ # + spmatrix(dS.real().V, dS.real().I+system.Bus.n, dS.real().J, (system.DAE.ny, system.DAE.ny)) \ # + spmatrix(dS.imag().V, dS.imag().I+system.Bus.n, dS.imag().J+system.Bus.n, (system.DAE.ny, system.DAE.ny)) Gy = sparse([[dR.imag(), dR.real()], [dS.real(), dS.imag()]]) # system.DAE.Gy = zeros([system.DAE.ny,system.DAE.ny]) system.DAE.Gy = spmatrix(Gy.V, Gy.I, Gy.J, (system.DAE.ny, system.DAE.ny)) system.DAE.Gy = matrix(system.DAE.Gy)
def calcInc(): global F system.Line.gcall() system.PQ.gcall() system.Shunt.gcall() system.PV.gcall() system.SW.gcall() system.Ind3.gcall() system.Line.Gycall() system.Shunt.Gycall() system.PV.Gycall() system.SW.Gycall() system.Ind3.Gycall() system.Ind3.fcall() system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) system.Ind3.Fxcall() system.PV.Fxcall() system.SW.Fxcall() system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Fx = sparse(system.DAE.Fx) system.DAE.Fy = sparse(system.DAE.Fy) system.DAE.Gx = sparse(system.DAE.Gx) A = sparse([[system.DAE.Fx, system.DAE.Gx], [system.DAE.Fy, system.DAE.Gy]]) inc = matrix([system.DAE.f, system.DAE.g]) if system.DAE.factorize: F = symbolic( A ) # 重新排列A矩阵以减少填充并执行LU分解,返回为可以传递的不透明 C object到umfpack.numeric()。 system.DAE.factorize = False try: N = numeric(A, F) solve(A, N, inc) except: print('unexpect') F = symbolic(A) solve(A, numeric(A, F), inc) return inc
def _update_weight(self,Q,G,Wc,F,gold_deps,gold_features,trees): constraints,L = [],[] print 'creating constraints...' for i,tree in enumerate(trees): print '\tfor tree %d'%(i) deps = map(lambda x:(x[0],x[2]), tree) deps.sort() L += [-self._loss_score(gold_deps,deps)] fc = [] for s,x,t in tree: if s > t: fc += F['%d-%d-L'%(t,s)] else: fc += F['%d-%d-R'%(s,t)] fg = [] for f in gold_features: if f in fc: fc.remove(f) else: fg.append(f) constraints += map(lambda x:(fg.count(x),i,x),fg) constraints += map(lambda x:(-fc.count(x),i,x),fc) print 'preparing parameters...' G = sparse(G*0) for s,i,j in constraints: G[(i,j)] = -s h = matrix(L) p = matrix(-2*Wc) sol = solvers.qp(Q,p,G,h) Wn = sparse(sol['x']) print L sg = gold_features.prod(Wn) for tree in trees: fc = Features() for s,x,t in tree: if s > t: fc += F['%d-%d-L'%(t,s)] else: fc += F['%d-%d-R'%(s,t)] sc = fc.prod(Wn) print sg,'-',sc,'=',sg-sc return Wn
def merge_constraints(multiplier_1: matrix, constr_values_1: matrix, multiplier_2: matrix, constr_values_2: matrix) \ -> Tuple[matrix, matrix]: """ Combines two constraints into one constraint. """ multiplier = sparse([[multiplier_1, multiplier_2]]) constr_values = matrix([[constr_values_1, constr_values_2]]) return multiplier, constr_values
def state_matrix(): Gyx = matrix(system.DAE.Gx) linsolve(sparse(system.DAE.Gy), Gyx) I = [] J = [] for i in range(system.DAE.nx): I.append(i) J.append(i) return system.DAE.Fx - system.DAE.Fy * Gyx - spmatrix(1e-6, I, J)
def robustLS_toep(q, r, delta=None, seed=0): """ Random data generator for matrix norm minimization SDP. Al,b = robustLS_toep(q,r,delta=0.1,seed=0]) PURPOSE Generates random data for a robust least squares problem with Toeplitz structure: minimize e_wc(x)^2 where e_wc(x)=sup_{norm(u)<=1} norm((Ab+A1*u1+...+Ar*ur)*x - b), Ab,A1,...,Ar \in \reals^{p \times q} The parameter r determines the number of nonzero diagonals in Ab (1 <= r <= p). ARGUMENTS q integer r integer delta float RETURNS Al list of CVXOPT matrices, [Ab,A1,...,Ar] b CVXOPT matrix """ setseed(seed) p = q + r - 1 Alist = [ sparse( misc.toeplitz( matrix([normal(r, 1), matrix(0., (p - r, 1))], (p, 1)), matrix(0., (q, 1)))) ] x = normal(q, 1) b = normal(p, 1, std=0.1) b += Alist[0] * x if delta is None: delta = 1. / r for i in xrange(r): Alist.append( spmatrix(delta, xrange(i, min(p, q + i)), xrange(min(q, p - i)), (p, q))) return robustLS_SDP(Alist, b)
def robustLS_toep(q,r,delta=None,seed=0): """ Random data generator for matrix norm minimization SDP. Al,b = robustLS_toep(q,r,delta=0.1,seed=0]) PURPOSE Generates random data for a robust least squares problem with Toeplitz structure: minimize e_wc(x)^2 where e_wc(x)=sup_{norm(u)<=1} norm((Ab+A1*u1+...+Ar*ur)*x - b), Ab,A1,...,Ar \in \reals^{p \times q} The parameter r determines the number of nonzero diagonals in Ab (1 <= r <= p). ARGUMENTS q integer r integer delta float RETURNS Al list of CVXOPT matrices, [Ab,A1,...,Ar] b CVXOPT matrix """ setseed(seed) p = q+r-1 Alist = [sparse(misc.toeplitz(matrix([normal(r,1),matrix(0.,(p-r,1))],(p,1)),matrix(0.,(q,1))))] x = normal(q,1) b = normal(p,1,std=0.1) b += Alist[0]*x if delta is None: delta = 1./r for i in range(r): Alist.append(spmatrix(delta,range(i,min(p,q+i)),range(min(q,p-i)),(p,q))) return robustLS_SDP(Alist, b)
def calcInc(): global F print('y') print(system.DAE.y) system.Line.gcall() system.Statcom.gcall() system.Sssc.gcall() system.PQ.gcall() system.Shunt.gcall() system.PV.gcall() system.SW.gcall() print('g') print(system.DAE.g) system.Line.Gycall() system.Statcom.Gycall() system.Sssc.Gycall() system.Shunt.Gycall() system.PV.Gycall() system.SW.Gycall() # system.Statcom.Gycall() print('Gy') print(system.DAE.Gy) # for i in range(30): # print(system.DAE.Gy[13, i]) # for i in range(30): # print(system.DAE.Gy[27, i]) # for i in range(30): # print(system.DAE.Gy[28, i]) # for i in range(30): # print(system.DAE.Gy[29, i]) A = sparse(system.DAE.Gy) inc = matrix(system.DAE.g) if system.DAE.factorize: F = symbolic( A) #重新排列A矩阵以减少填充并执行LU分解,返回为可以传递的不透明 C object到umfpack.numeric()。 system.DAE.factorize = False try: N = numeric(A, F) solve(A, N, inc) except: print('unexpect') F = symbolic(A) solve(A, numeric(A, F), inc) return inc
def cvxopt_svm(K, labels, c, D=None): log = logging.getLogger('golem.nodes.svm.cvxopt_svm') c = float(c) m = K.shape[0] if D == None: # normal SVM D = cvx.spmatrix(1, range(m), range(m)) else: # latent error SVM with spread matrix D D = cvx.matrix(D) labels = np.atleast_2d(labels) assert np.all(np.unique(labels) == [-1, 1]) assert K.shape[0] == K.shape[1] log.debug('Creating QP-target') # (4) min W(a) = (1/2) * a^T * P * a - \vec{1}^T a label_matrix = np.dot(labels.T, labels) P = cvx.matrix(K * label_matrix) q = cvx.matrix([-1. for i in range(m)]) log.debug('Creating QP-constraints') # (2) 0 < all alphas < c/m, using Ga <= h # (3) sum(a_i * y_i) = 0, using Aa = b # (2) is solved in two parts, first 0 < alphas, then alphas < c / m G1 = cvx.spmatrix(-1, range(m), range(m)) G2 = D.T G = cvx.sparse([G1, G2]) h = cvx.matrix([0. for i in range(m)] + [c/m for i in range(m)]) A = cvx.matrix(labels) r = cvx.matrix(0.) log.debug('Solving QP') cvxopt.solvers.options['show_progress'] = False sol = cvxopt.solvers.qp(P, q, G, h, A, r) if sol['status'] != 'optimal': log.warning('QP solution status: ' + sol['status']) log.debug('solver.status = ' + sol['status']) alphas = np.asarray(sol['x']) # column vector! bias = np.mean(labels.flatten() - np.dot(labels.flatten() * alphas.T, K)) # alpha_i gets close to zero, but does not always equal zero: alphas[alphas < np.max(alphas) * ALPHA_RTOL] = 0 return alphas.flatten(), bias
def Gycall(self): system.DAE.y = matrix(system.DAE.y) V = 2 * system.DAE.y[self.v] #shunt bus 的索引? conductance = self.g #网络中每条母线的电导列向量 conductance = matrix(conductance) susceptance = self.b #电纳列向量 susceptance = matrix(susceptance) m = len(system.DAE.y) #代数变量的个数 conducv = mul(conductance, V) suscepv = mul(susceptance, V) spconducv = spmatrix(conducv, self.a, self.v, (m, m), 'z') spcsuscepv = spmatrix(suscepv, self.v, self.v, (m, m), 'z') system.DAE.Gy = system.DAE.Gy + spmatrix(conducv, self.a, self.v, (m, m), 'z') - spmatrix( suscepv, self.v, self.v, (m, m), 'z') system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Gy = matrix(system.DAE.Gy.real())
if system.DAE.nx > 0: system.DAE.Fx = spmatrix([], [], [], (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = spmatrix([], [], [], (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = spmatrix([], [], [], (system.DAE.ny, system.DAE.nx)) system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) system.Syn6.Fxcall() system.Avr1.Fxcall() system.Avr2.Fxcall() system.Tg1.Fxcall() system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Fx = sparse(system.DAE.Fx) system.DAE.Fy = sparse(system.DAE.Fy) system.DAE.Gx = sparse(system.DAE.Gx) # print(system.DAE.f) system.DAE.tn = system.DAE.f # 初始化 t = system.Settings.t0 k = 1 # 步长选择
def sssa(datafile): start = clock() system.Bus._init_data() system.PV._init_data() system.PQ._init_data() system.SW._init_data() system.Shunt._init_data() system.Line._init_data() system.Syn6._init_data() system.Avr1._init_data() system.Avr2._init_data() system.Tg1._init_data() system.Ind3._init_data() # system.Pss1._init_data() case = open(datafile) for each_line in case: data = each_line.split() if data[0] == 'Bus': bus = data[0] + '_' + str(data[1]) Vb = float(data[2]) bus_case = {'bus': bus, 'Vb': Vb} system.Bus.add(idx=bus, **bus_case) if data[0] == 'PV': bus = 'Bus_' + str(data[1]) Sn = float(data[2]) Vn = float(data[3]) Pg = float(data[4]) V0 = float(data[5]) qgmax = float(data[6]) qgmin = float(data[7]) Vmax = float(data[8]) Vmin = float(data[9]) PV_case = { 'bus': bus, 'Sn': Sn, 'Vn': Vn, 'Pg': Pg, 'V0': V0, 'qgmax': qgmax, 'qgmin': qgmin, 'Vmax': Vmax, 'Vmin': Vmin } system.PV.add(**PV_case) if data[0] == 'PQ': bus = 'Bus_' + str(data[1]) Sn = float(data[2]) Vn = float(data[3]) Pl = float(data[4]) Ql = float(data[5]) Vmax = float(data[6]) Vmin = float(data[7]) z = float(data[8]) PQ_case = { 'bus': bus, 'Sn': Sn, 'Vn': Vn, 'Pl': Pl, 'Ql': Ql, 'Vmax': Vmax, 'Vmin': Vmin, 'z': z } system.PQ.add(**PQ_case) if data[0] == 'SW': bus = 'Bus_' + str(data[1]) Sn = float(data[2]) Vn = float(data[3]) V0 = float(data[4]) Va = float(data[5]) qgmax = float(data[6]) qgmin = float(data[7]) Vmax = float(data[8]) Vmin = float(data[9]) SW_case = { 'bus': bus, 'Sn': Sn, 'Vn': Vn, 'V0': V0, 'Va': Va, 'qgmax': qgmax, 'qgmin': qgmin, 'Vmax': Vmax, 'Vmin': Vmin } system.SW.add(**SW_case) if data[0] == 'Shunt': bus = 'Bus_' + str(data[1]) Sn = float(data[2]) Vn = float(data[3]) fn = float(data[4]) g = float(data[5]) b = float(data[6]) Shunt_case = { 'bus': bus, 'Sn': Sn, 'Vn': Vn, 'fn': fn, 'g': g, 'b': b } system.Shunt.add(**Shunt_case) if data[0] == 'Line': f_bus = 'Bus_' + str(data[1]) to_bus = 'Bus_' + str(data[2]) Sn = float(data[3]) Vn = float(data[4]) fn = float(data[5]) l = float(data[6]) kT = float(data[7]) r = float(data[8]) x = float(data[9]) b = float(data[10]) tap_ratio = float(data[11]) theta = float(data[12]) Imax = float(data[13]) Pmax = float(data[14]) Smax = float(data[15]) Line_case = { 'f_bus': f_bus, 'to_bus': to_bus, 'Sn': Sn, 'Vn': Vn, 'fn': fn, 'l': l, 'kT': kT, 'r': r, 'x': x, 'b': b, 'tap_ratio': tap_ratio, 'theta': theta, 'Imax': Imax, 'Pmax': Pmax, 'Smax': Smax } system.Line.add(**Line_case) if data[0] == 'Syn6': bus = 'Bus_' + str(data[1]) Sn = float(data[2]) Vn = float(data[3]) fn = float(data[4]) m_model = float(data[5]) xl = float(data[6]) ra = float(data[7]) xd = float(data[8]) xd1 = float(data[9]) xd2 = float(data[10]) Td01 = float(data[11]) Td02 = float(data[12]) xq = float(data[13]) xq1 = float(data[14]) xq2 = float(data[15]) Tq01 = float(data[16]) Tq02 = float(data[17]) M = float(data[18]) # M = 2H D = float(data[19]) Syn6_case = { 'bus': bus, 'Sn': Sn, 'Vn': Vn, 'fn': fn, 'm_model': m_model, 'xl': xl, 'ra': ra, 'xd': xd, 'xd1': xd1, 'xd2': xd2, 'Td01': Td01, 'Td02': Td02, 'xq': xq, 'xq1': xq1, 'xq2': xq2, 'Tq01': Tq01, 'Tq02': Tq02, 'M': M, 'D': D } system.Syn6.add(**Syn6_case) if data[0] == 'Avr2': bus = 'Bus_' + str(data[1]) Type = float(data[2]) vrmax = float(data[3]) vrmin = float(data[4]) Ka = float(data[5]) Ta = float(data[6]) Kf = float(data[7]) Tf = float(data[8]) Ke = float(data[9]) Te = float(data[10]) Tr = float(data[11]) Ae = float(data[12]) Be = float(data[13]) Avr2_case = { 'bus': bus, 'Type': Type, 'vrmax': vrmax, 'vrmin': vrmin, 'Ka': Ka, 'Ta': Ta, 'Kf': Kf, 'Tf': Tf, 'Ke': Ke, 'Te': Te, 'Tr': Tr, 'Ae': Ae, 'Be': Be } system.Avr2.add(**Avr2_case) if data[0] == 'Avr1': bus = 'Bus_' + str(data[1]) Type = float(data[2]) vrmax = float(data[3]) vrmin = float(data[4]) K0 = float(data[5]) T1 = float(data[6]) T2 = float(data[7]) T3 = float(data[8]) T4 = float(data[9]) Te = float(data[10]) Tr = float(data[11]) Ae = float(data[12]) Be = float(data[13]) Avr1_case = { 'bus': bus, 'Type': Type, 'vrmax': vrmax, 'vrmin': vrmin, 'K0': K0, 'T1': T1, 'T2': T2, 'T3': T3, 'T4': T4, 'Te': Te, 'Tr': Tr, 'Ae': Ae, 'Be': Be } system.Avr1.add(**Avr1_case) if data[0] == 'Tg1': bus = 'Bus_' + str(data[1]) Type = float(data[2]) wref0 = float(data[3]) R = float(data[4]) Pmax = float(data[5]) Pmin = float(data[6]) Ts = float(data[7]) Tc = float(data[8]) T3 = float(data[9]) T4 = float(data[10]) T5 = float(data[11]) Tg1_case = { 'bus': bus, 'Type': Type, 'wref0': wref0, 'R': R, 'Pmax': Pmax, 'Pmin': Pmin, 'Ts': Ts, 'Tc': Tc, 'T3': T3, 'T4': T4, 'T5': T5 } system.Tg1.add(**Tg1_case) if data[0] == 'Ind3': bus = 'Bus_' + str(data[1]) Sn = float(data[2]) Vn = float(data[3]) fn = float(data[4]) type = float(data[5]) rs = float(data[7]) xs = float(data[8]) rr1 = float(data[9]) xr1 = float(data[10]) rr2 = float(data[11]) xr2 = float(data[12]) xm = float(data[13]) Hm = float(data[14]) a1 = float(data[15]) b = float(data[16]) c = float(data[17]) tup = float(data[18]) sup = float(data[6]) allow = float(data[19]) Ind3_case = { 'bus': bus, 'Sn': Sn, 'Vn': Vn, 'fn': fn, 'type': type, 'sup': sup, 'xs': xs, 'rs': rs, 'rr1': rr1, 'xr1': xr1, 'rr2': rr2, 'xr2': xr2, 'xm': xm, 'Hm': Hm, 'a1': a1, 'b': b, 'c': c, 'allow': allow } system.Ind3.add(**Ind3_case) case.close() # Bus system.Bus._xy_index() system.Bus._bus_index() system.Bus._list2matrix() system.Bus.yinit(system.DAE) # PV system.PV._bus_index() system.PV._list2matrix() system.PV.base(Vb=system.Bus.Vb[system.PV.a]) system.PV.yinit(system.DAE) system.PV._matrix2list() # PQ system.PQ._bus_index() system.PQ._list2matrix() system.PQ.base(Vb=system.Bus.Vb[system.PQ.a]) system.PQ.yinit(system.DAE) system.PQ._matrix2list() # SW system.SW._bus_index() system.SW.yinit(system.DAE) # Shunt system.Shunt._bus_index() system.Shunt._list2matrix() system.Shunt.base(Vb=system.Bus.Vb[system.Shunt.a]) system.Shunt._matrix2list() # Line system.Line._bus_index() system.Line.build_y() # 测试Ind3 system.Ind3._bus_index() system.Ind3._list2matrix() system.Ind3.base(Sb=system.Settings.mva, Vb=system.Bus.Vb[system.Ind3.a]) system.Ind3.setdata() # print(system.Ind3.__dict__) system.Ind3._dxy_index() # system.Ind3._matrix2list() # print(system.Ind3.__dict__) # system.DAE.Y = sparse(system.DAE.Y) # print(system.DAE.Y) # system.Line.gcall() # system.PQ.gcall() # system.Shunt.gcall() # system.PV.gcall() # system.SW.gcall() # print(system.DAE.g) # print(system.DAE.y) def calcInc(): global F system.Line.gcall() system.PQ.gcall() system.Shunt.gcall() system.PV.gcall() system.SW.gcall() system.Ind3.gcall() system.Line.Gycall() system.Shunt.Gycall() system.PV.Gycall() system.SW.Gycall() system.Ind3.Gycall() system.Ind3.fcall() system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) system.Ind3.Fxcall() system.PV.Fxcall() system.SW.Fxcall() system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Fx = sparse(system.DAE.Fx) system.DAE.Fy = sparse(system.DAE.Fy) system.DAE.Gx = sparse(system.DAE.Gx) A = sparse([[system.DAE.Fx, system.DAE.Gx], [system.DAE.Fy, system.DAE.Gy]]) inc = matrix([system.DAE.f, system.DAE.g]) if system.DAE.factorize: F = symbolic( A ) # 重新排列A矩阵以减少填充并执行LU分解,返回为可以传递的不透明 C object到umfpack.numeric()。 system.DAE.factorize = False try: N = numeric(A, F) solve(A, N, inc) except: print('unexpect') F = symbolic(A) solve(A, numeric(A, F), inc) return inc if system.DAE.nx != 0: system.DAE.f = matrix(1.0, (system.DAE.nx, 1)) system.DAE.x = matrix(1.0, (system.DAE.nx, 1)) system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) system.DAE.Gy = matrix(0.0, (system.DAE.ny, system.DAE.ny)) system.Ind3.xinit() system.DAE.g = np.array(system.DAE.g) iteration = 1 iter_max = system.Settings.iter convergence = True # 收敛 tol = system.Settings.error cycle = True err = [] # main loop while cycle or (max(abs(system.DAE.g)) > tol and iteration <= iter_max): inc = calcInc() cycle = False for i in range(system.DAE.nx): system.DAE.x[i] = system.DAE.x[i] - inc[i] for i in range(system.DAE.ny): system.DAE.y[i] = system.DAE.y[i] - inc[i + system.DAE.nx] err.append(max(abs(system.DAE.g))) print('第%i次迭代最大误差为:<%f>' % (iteration, err[iteration - 1])) iteration += 1 system.DAE.g = np.array(system.DAE.g) # stop if the error increases too much if iteration > iter_max: print('Reached maximum number of iterations') convergence = False # 结束时间 finish = clock() t = finish - start print('潮流计算运行时间:%f' % t) for i in range(system.DAE.ny): system.DAE.y[i] = round(system.DAE.y[i], 5) # 计算Pl和Ql system.DAE.g = matrix(0.0, (system.DAE.ny, 1)) # print(system.DAE.g) system.PQ.gcall() system.Shunt.gcall() system.DAE._list2matrix() system.Bus.Pl = system.DAE.g[system.Bus.a] # print(system.Bus.Pl) system.Bus.Ql = system.DAE.g[system.Bus.v] # print(system.Bus.Ql) # 计算Pg 和 Qg system.Line.gcall() system.PQ.gcall() system.Shunt.gcall() system.DAE._list2matrix() system.Bus.Pg = system.DAE.g[system.Bus.a] system.Bus.Qg = system.DAE.g[system.Bus.v] # print('Bus.Pg、Qg') # print(system.Bus.Pg) # print(system.Bus.Qg) nx_old = system.DAE.nx # 测试Syn6 system.Syn6._bus_index() system.Syn6._dxy_index() # 测试Avr system.Avr1._bus_index() system.Avr2._bus_index() system.Avr1.getbus() system.Avr2.getbus() system.Avr2._dxy_index() system.Avr1._dxy_index() # 测试Tg1 system.Tg1._bus_index() system.Tg1._dxy_index() system.Tg1.getbus() # 重新生成对应维度的x, y, g, f newx = [0] * (system.DAE.nx - nx_old) system.DAE.x = list(system.DAE.x) system.DAE.f = list(system.DAE.f) system.DAE.x.extend(newx) system.DAE.f.extend(newx) system.DAE.y = list(system.DAE.y) system.DAE.g = list(system.DAE.g) # 重新生成雅可比矩阵 system.DAE.Gy = matrix(0.0, (system.DAE.ny, system.DAE.ny)) system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) newy = [0] * (system.DAE.ny - system.Bus.n * 2) system.DAE.y.extend(newy) system.DAE.g.extend(newy) system.DAE.y = matrix(system.DAE.y) # 测试Syn6 setx0 system.Syn6._list2matrix() system.Syn6.base(Vb=system.Bus.Vb[system.Syn6.a]) system.Syn6.setx0() # print('Syn6 setx0') # print(system.DAE.x) # 测试Avr setx0 system.Avr1._list2matrix() system.Avr2._list2matrix() # system.Avr1.base(Vb=system.Bus.Vb[system.Avr1.a]) # system.Avr2.base(Vb=system.Bus.Vb[system.Avr2.a]) system.Avr1.setx0() system.Avr2.setx0() # print('Avr setx0') # print(system.DAE.y) # 测试Tg1 system.Tg1._list2matrix() system.DAE._list2matrix() system.Tg1.base() system.Tg1.setx0() # system.Tg1._matrix2list() # system.Tg1.pmech = matrix(system.Tg1.pmech) # print(system.Tg1.pmech) # print(system.Tg1.__dict__) # print(system.DAE.f) # print(system.DAE.x) # print(system.DAE.y) # 重新生成微分代数方程和雅可比矩阵 system.DAE.g = matrix(0.0, (system.DAE.ny, 1)) # call system.DAE._list2matrix() system.Line.gcall() system.PQ.gcall() system.Shunt.gcall() system.Syn6.gcall() system.Avr1.gcall() system.Avr2.gcall() system.Tg1.gcall() system.Ind3.gcall() system.PV.gcall() system.SW.gcall() system.Line.Gycall() system.PQ.Gycall() system.Shunt.Gycall() system.Syn6.Gycall() system.Avr1.Gycall() system.Avr2.Gycall() system.Tg1.Gycall() system.Ind3.Gycall() system.PV.Gycall() system.SW.Gycall() system.Syn6.fcall() system.Avr1.fcall() system.Avr2.fcall() system.Tg1.fcall() system.Ind3.fcall() # print(system.DAE.f) system.Syn6.Fxcall() system.Avr1.Fxcall() system.Avr2.Fxcall() system.Tg1.Fxcall() system.Ind3.Fxcall() system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Fx = sparse(system.DAE.Fx) system.DAE.Fy = sparse(system.DAE.Fy) system.DAE.Gx = sparse(system.DAE.Gx) # print(system.DAE.Fx.V) # print(system.DAE.Fx.V) # 生成状态矩阵 def state_matrix(): Gyx = matrix(system.DAE.Gx) linsolve(sparse(system.DAE.Gy), Gyx) I = [] J = [] for i in range(system.DAE.nx): I.append(i) J.append(i) return system.DAE.Fx - system.DAE.Fy * Gyx - spmatrix(1e-6, I, J) Gyx = matrix(system.DAE.Gx) linsolve(sparse(system.DAE.Gy), Gyx) # state_matrix() As = state_matrix() # print(As) # As = sparse(As) # 计算特征值 # cvxopt def eigs(): As = state_matrix() return eigvals(As) eigen = eigs() # print(matrix(eigs())) # numpy # w = np.linalg.eigvals(As) # w = matrix(w) # print(np.linalg.eigvals(As)) # scipy w, v = linalg.eig(As) # w = matrix(w) # a = w[0] # print(matrix(w)) # print(a) for i in range(system.DAE.nx): w[i] = round(w[i], 5) print(w[i]) # 计算参与因子 # set_printoptions(threshold = 'nan') def compute_eig(As): mu, N = eig(matrix(As)) N = matrix(N) n = len(mu) idx = range(n) W = matrix(spmatrix(1.0, idx, idx, (n, n), N.typecode)) gesv(N, W) pf = mul(abs(W.T), abs(N)) b = matrix(1.0, (1, n)) WN = b * pf pf = pf.T for item in idx: mur = mu[item].real mui = mu[item].imag mu[item] = complex(round(mur, 5), round(mui, 5)) pf[item, :] /= WN[item] return pf # print(pf) return As, Gyx pf = compute_eig(As) # print(pf) w = w.T sio.savemat('eig.mat', {'eig': w, 'pf': pf}) f = open('indpf.txt', 'w+') for i in range(system.DAE.nx): pfrow = [] for j in range(system.DAE.nx): p = str(round(pf[i, j], 12)) # pfrow.append(round(pf[i, j], 12)) f.write(p + ' ') f.write('\n') # f.writelines(pfrow) # print(pfrow) f.close()
system.SW.Gycall() system.Syn6.fcall() system.Avr1.fcall() system.Avr2.fcall() system.Tg1.fcall() system.Ind3.fcall() # print(system.DAE.f) system.Syn6.Fxcall() system.Avr1.Fxcall() system.Avr2.Fxcall() system.Tg1.Fxcall() system.Ind3.Fxcall() system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Fx = sparse(system.DAE.Fx) system.DAE.Fy = sparse(system.DAE.Fy) system.DAE.Gx = sparse(system.DAE.Gx) # print(system.DAE.Fx.V) # print(system.DAE.Fx.V) # 生成状态矩阵 def state_matrix(): Gyx = matrix(system.DAE.Gx) linsolve(sparse(system.DAE.Gy), Gyx) I = [] J = []
def td(htype, syst, Pl, Ql, sn, ssvw, tf, tc): # 输出采用的时域仿真算法 tstart = time.time() print('time domain simulation ') print('Trapezoidal integration method') # 检查设置 iter_max = 20 tol = 0.00001 Dn = 1 if system.DAE.nx: Dn = system.DAE.nx identica = spmatrix(1.0, range(max(Dn, 1)), range(max(Dn, 1)), (max(Dn, 1), max(Dn, 1))) # 把PQ负荷转化为并联阻抗 system.PQ.pqshunt() # 建立变量 system.DAE.t = system.Settings.t0 # call system.DAE._list2matrix() system.Line.gcall() system.PQ.gcall() system.Syn6.gcall() system.Avr2.gcall() system.Dfig.gcall() system.Wind.gcall() system.PV.gcall() system.SW.gcall() system.Line.Gycall() system.PQ.Gycall() system.Syn6.Gycall() system.Avr2.Gycall() system.Dfig.Gycall() system.Wind.Gycall() system.PV.Gycall() system.SW.Gycall() system.Syn6.fcall() system.Avr2.fcall() system.Dfig.fcall() system.Wind.fcall() if system.DAE.nx > 0: system.DAE.Fx = spmatrix([], [], [], (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = spmatrix([], [], [], (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = spmatrix([], [], [], (system.DAE.ny, system.DAE.nx)) system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) system.Syn6.Fxcall() system.Avr2.Fxcall() system.Dfig.Fxcall() system.Wind.Fxcall() system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Fx = sparse(system.DAE.Fx) system.DAE.Fy = sparse(system.DAE.Fy) system.DAE.Gx = sparse(system.DAE.Gx) # print(system.DAE.f) system.DAE.tn = system.DAE.f # 初始化 t = system.Settings.t0 # t1 = time.time() # for i in range(sn): # syst.put(t) # 有多少随机模块就把系统同样个数的仿真时间传入多进程Queue队列 syst.value = t # t2 = time.time() # print('queue队列通信时间:%s' % (t2-t1)) k = 1 system.Varout.store(t, k) # 步长选择 if htype == 'fixed': h = 0.01 else: h = firsttime_tstep() inc = matrix(0.0, (system.DAE.nx + system.DAE.ny, 1)) # 故障时间排序 fixed_times = system.Fault.gettimes() if fixed_times is not None: if len(fixed_times) > 1: fixed_times = sorted(fixed_times) # 计算最大转子间相对摇摆(先忽略) def anglediff(): diff_max = 0 delta = system.DAE.x[system.Syn6.delta].real() delta_diff = abs(delta - min(delta)) diff_max = (max(delta_diff) * 180 / math.pi) > system.Settings.deltadelta diff_max = 0 # diff_max = anglediff() switch = False system.DAE.factorize = True # 主循环 while t < system.Settings.tf and t + h > t and not diff_max: t3 = time.time() if t + h > system.Settings.tf: h = system.Settings.tf - t # print(system.DAE.t) actual_time = t + h # 检查不要跳过扰动(后续修改为更简洁形式) if fixed_times is not None: for item in fixed_times: if item > t and item < t + h: actual_time = item h = actual_time - t switch = True break system.DAE.t = actual_time # 备份变量 xa = matrix(system.DAE.x) ya = matrix(system.DAE.y) # 初始化牛拉法循环 iteration = 1 fn = matrix(system.DAE.f) # 微分方程 inc[0] = 1 # 执行扰动 if switch: system.Fault.intervention(actual_time) system.Line.intervention(actual_time) # system.Breaker.intervention(actual_time) switch = False # 牛拉循环 system.Settings.error = tol + 1 # 强迫进入循环一次 # 线路随机故障模拟 fixed_times = [] system.Line.tf = tf system.Line.tc = tc fixed_times = system.Line.gettimes(fixed_times) if fixed_times is not None: if len(fixed_times) > 1: fixed_times = sorted(fixed_times) t1 = time.time() # print('主进程经过%ss后将进行下一步长计算' % (t1-t3)) # 随机负荷波动 system.PQ.Pl = Pl system.PQ.Ql = Ql t2 = time.time() # print('多进程通信耗时1:%s' % (t2 - t1)) # 风速波动 system.Wind.svw = ssvw # 调用随机模块产生下一时刻随机值 # for i in range(sn): # syst.put(actual_time) # 有多少随机模块就把系统同样个数的仿真时间传入多进程Queue队列 syst.value = actual_time # t2 = time.time() # print('多进程通信耗时2:%s' % (t2-t1)) td1 = time.time() while system.Settings.error > tol and iteration < iter_max: td5 = time.time() system.Line.gcall() system.PQ.gcall() system.Syn6.gcall() system.Avr2.gcall() system.Dfig.gcall() system.Wind.gcall() system.PV.gcall() system.SW.gcall() system.Line.Gycall() system.PQ.Gycall() system.Syn6.Gycall() system.Avr2.Gycall() system.Dfig.Gycall() system.Wind.Gycall() system.PV.Gycall() system.SW.Gycall() system.Syn6.fcall() system.Avr2.fcall() system.Dfig.fcall() system.Wind.fcall() if system.DAE.nx > 0: system.DAE.Fx = spmatrix([], [], [], (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = spmatrix([], [], [], (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = spmatrix([], [], [], (system.DAE.ny, system.DAE.nx)) system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) system.Syn6.Fxcall() system.Avr2.Fxcall() system.Dfig.Fxcall() system.Wind.Fxcall() system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Fx = sparse(system.DAE.Fx) system.DAE.Fy = sparse(system.DAE.Fy) system.DAE.Gx = sparse(system.DAE.Gx) td6 = time.time() # print('生成雅可比矩阵时间:%s' % (td6-td5)) # 计算雅可比矩阵 if system.Settings.method == 1: # 采用欧拉法 system.DAE.Ac = sparse( [[identica - h * system.DAE.Fx, system.DAE.Gx], [-h * system.DAE.Fy, system.DAE.Gy]]) system.DAE.tn = system.DAE.x - xa - h * system.DAE.f elif system.Settings.method == 2: # 采用隐式梯形法 system.DAE.Ac = sparse( [[identica - h * 0.5 * system.DAE.Fx, system.DAE.Gx], [-h * 0.5 * system.DAE.Fy, system.DAE.Gy]]) system.DAE.tn = system.DAE.x - xa - h * 0.5 * (system.DAE.f + fn) # 限幅器 system.Avr2.windup('td') system.Dfig.windup_final() # gg = -matrix([system.DAE.tn, system.DAE.g]) # linsolve(system.DAE.Ac, gg) # inc = gg td3 = time.time() if system.DAE.factorize: F = symbolic(system.DAE.Ac) system.DAE.factorize = False inc = -matrix([system.DAE.tn, system.DAE.g]) try: umfsolve(system.DAE.Ac, numeric(system.DAE.Ac, F), inc) except ArithmeticError: print('Singular matrix') iteration = iter_max + 1 except ValueError: F = symbolic(system.DAE.Ac) try: umfsolve(system.DAE.Ac, numeric(system.DAE.Ac, F), inc) except ArithmeticError: print('Singular matrix') iteration = iter_max + 1 td4 = time.time() # print('一次牛拉迭代时间为:%s' % (td4-td3)) system.DAE.x = system.DAE.x + inc[:system.DAE.nx] system.DAE.y = system.DAE.y + inc[system.DAE.nx:system.DAE.nx + system.DAE.ny] iteration = iteration + 1 system.Settings.error = max(abs(inc)) td2 = time.time() # print('一个步长仿真时间:%s' % (td2 - td1)) # print('一个步长牛拉迭代次数:%s' % iteration) # 计算新的时间步长 if iteration > iter_max: h = time_step(False, iteration, t) print('减小步长(delta t = %.5f s)' % h) system.DAE.x = matrix(xa) system.DAE.y = matrix(ya) system.DAE.f = matrix(fn) else: # h = time_step(True, iteration, t) # t = actual_time h = 0.01 t = actual_time # syst.put(t) # 把系统仿真时间放入多进程Queue队列 k = k + 1 system.Varout.store(t, k) var = system.Varout.var t0 = matrix(system.Varout.t) var = matrix(var) var = var.T sio.savemat( 'C://Users//user//Desktop//平台//余伟洲//仿真结果//RES 时域仿真//restdvar.mat', { 'var': var, 't': t0 }) # sio.savemat('C://Users//user//Desktop//restdvar.mat', {'var': var, 't': t0}) print('time domain simulation completed') print('仿真次数%s', k) tend = time.time() print('机电暂态仿真总时间%s', tend - tstart)
def td(htype): # 输出采用的时域仿真算法 tstart = time.time() print('time domain simulation ') print('Trapezoidal integration method') # 检查设置 iter_max = 20 tol = 0.00001 Dn = 1 if system.DAE.nx: Dn = system.DAE.nx identica = spmatrix(1.0, range(max(Dn, 1)), range(max(Dn, 1)), (max(Dn, 1), max(Dn, 1))) # 把PQ负荷转化为并联阻抗 system.PQ.pqshunt() # 建立变量 system.DAE.t = system.Settings.t0 # call system.DAE._list2matrix() system.Line.gcall() system.PQ.gcall() system.Syn6.gcall() system.Avr2.gcall() system.Dfig.gcall() system.Wind.gcall() system.PV.gcall() system.SW.gcall() system.Line.Gycall() system.PQ.Gycall() system.Syn6.Gycall() system.Avr2.Gycall() system.Dfig.Gycall() system.Wind.Gycall() system.PV.Gycall() system.SW.Gycall() system.Syn6.fcall() system.Avr2.fcall() system.Dfig.fcall() system.Wind.fcall() if system.DAE.nx > 0: system.DAE.Fx = spmatrix([], [], [], (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = spmatrix([], [], [], (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = spmatrix([], [], [], (system.DAE.ny, system.DAE.nx)) system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) system.Syn6.Fxcall() system.Avr2.Fxcall() system.Dfig.Fxcall() system.Wind.Fxcall() system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Fx = sparse(system.DAE.Fx) system.DAE.Fy = sparse(system.DAE.Fy) system.DAE.Gx = sparse(system.DAE.Gx) # print(system.DAE.f) system.DAE.tn = system.DAE.f # 初始化 t = system.Settings.t0 k = 1 system.Varout.store(t, k) # 步长选择 if htype == 'fixed': h = 0.01 else: h = firsttime_tstep() inc = matrix(0.0, (system.DAE.nx + system.DAE.ny, 1)) # 故障时间排序 fixed_times = [] fixed_times = system.Fault.gettimes() # fixed_times = sorted(fixed_times) # 计算最大转子间相对摇摆(先忽略) def anglediff(): diff_max = 0 delta = system.DAE.x[system.Syn6.delta].real() delta_diff = abs(delta - min(delta)) diff_max = (max(delta_diff) * 180 / math.pi) > system.Settings.deltadelta diff_max = 0 # diff_max = anglediff() switch = False system.DAE.factorize = True # print(MWs) # 随机负荷波动参数 mup = copy.deepcopy(system.PQ.Pl) muq = copy.deepcopy(system.PQ.Ql) sigmap = 0.01 sigmaq = 0.01 # 风力发电机随机风速参数 suijih = 0.01 sigmavw = 0.01 ssvw = system.Wind.svw # 发电机随机出力 # system.Dfig.suiji(sigmavw, t, suijih, ssvw, '2') # yu 随机负荷波动 # system.PQ.suiji(mup, muq, sigmap, sigmaq, t, suijih, '2') # 发电机机械功率波动 # system.Syn6.suiji(musynp, sigmasynp, t, suijih) # 主循环 while t < system.Settings.tf and t + h > t and not diff_max: t3 = time.time() if t + h > system.Settings.tf: h = system.Settings.tf - t # print(system.DAE.t) actual_time = t + h # 检查不要跳过扰动(后续修改为更简洁形式) if fixed_times is not None: for item in fixed_times: if item > t and item < t + h: actual_time = item h = actual_time - t switch = True break system.DAE.t = actual_time # 备份变量 xa = matrix(system.DAE.x) ya = matrix(system.DAE.y) # 初始化牛拉法循环 iteration = 1 fn = matrix(system.DAE.f) # 微分方程 inc[0] = 1 # 执行扰动 if switch: system.Fault.intervention(actual_time) system.Line.intervention(actual_time) # system.Breaker.intervention(actual_time) switch = False ts1 = time.time() # system.Line.tf = tf[k] # system.Line.tc = tc[k] # system.Line.gettimes(fixed_times) # system.PQ.Pl = Pl[k] # system.PQ.Ql = Ql[k] # system.DAE.x[system.Wind.vw] = vw[k] # if system.Wind.n == 1: # system.Wind.vwt[0] = vw[k] # else: # system.Wind.vwt = vw[k] # # 输电线路故障模拟 # system.Line.settimes(t) # system.Line.gettimes(fixed_times) # # yu 随机负荷波动 # system.PQ.suiji(mup, muq, sigmap, sigmaq, suijih, t, type='2') # # 风力发电机随机风速波动 # vw = system.DAE.x[system.Wind.vw] # system.Dfig.suiji(sigmavw, suijih, vw, t, '2') ts2 = time.time() # print('一个步长随机波动模块仿真耗时:%s' % (ts2-ts1)) # 牛拉循环 system.Settings.error = tol + 1 # 强迫进入循环一次 td1 = time.time() while system.Settings.error > tol and iteration < iter_max: td5 = time.time() system.Line.gcall() system.PQ.gcall() system.Syn6.gcall() system.Avr2.gcall() system.Dfig.gcall() system.Wind.gcall() system.PV.gcall() system.SW.gcall() system.Line.Gycall() system.PQ.Gycall() system.Syn6.Gycall() system.Avr2.Gycall() system.Dfig.Gycall() system.Wind.Gycall() system.PV.Gycall() system.SW.Gycall() system.Syn6.fcall() system.Avr2.fcall() system.Dfig.fcall() system.Wind.fcall() if system.DAE.nx > 0: system.DAE.Fx = spmatrix([], [], [], (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = spmatrix([], [], [], (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = spmatrix([], [], [], (system.DAE.ny, system.DAE.nx)) system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) system.Syn6.Fxcall() system.Avr2.Fxcall() system.Dfig.Fxcall() system.Wind.Fxcall() system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Fx = sparse(system.DAE.Fx) system.DAE.Fy = sparse(system.DAE.Fy) system.DAE.Gx = sparse(system.DAE.Gx) td6 = time.time() # print('生成雅可比矩阵时间:%s' % (td6-td5)) # 计算雅可比矩阵 if system.Settings.method == 1: # 采用欧拉法 system.DAE.Ac = sparse( [[identica - h * system.DAE.Fx, system.DAE.Gx], [-h * system.DAE.Fy, system.DAE.Gy]]) system.DAE.tn = system.DAE.x - xa - h * system.DAE.f elif system.Settings.method == 2: # 采用隐式梯形法 system.DAE.Ac = sparse( [[identica - h * 0.5 * system.DAE.Fx, system.DAE.Gx], [-h * 0.5 * system.DAE.Fy, system.DAE.Gy]]) system.DAE.tn = system.DAE.x - xa - h * 0.5 * (system.DAE.f + fn) # 限幅器 system.Avr2.windup('td') system.Dfig.windup_final() # gg = -matrix([system.DAE.tn, system.DAE.g]) # linsolve(system.DAE.Ac, gg) # inc = gg td3 = time.time() if system.DAE.factorize: F = symbolic(system.DAE.Ac) system.DAE.factorize = False inc = -matrix([matrix(system.DAE.tn), system.DAE.g]) try: umfsolve(system.DAE.Ac, numeric(system.DAE.Ac, F), inc) except ArithmeticError: print('Singular matrix') iteration = iter_max + 1 except ValueError: F = symbolic(system.DAE.Ac) try: umfsolve(system.DAE.Ac, numeric(system.DAE.Ac, F), inc) except ArithmeticError: print('Singular matrix') iteration = iter_max + 1 td4 = time.time() # print('一次牛拉迭代时间为:%s' % (td4-td3)) # print('一次牛拉求解总耗时:%s' % (td4 - td5)) system.DAE.x = system.DAE.x + inc[:system.DAE.nx] system.DAE.y = system.DAE.y + inc[system.DAE.nx:system.DAE.nx + system.DAE.ny] iteration = iteration + 1 system.Settings.error = max(abs(inc)) td2 = time.time() # print('一个步长仿真时间:%s' % (td2 - td1)) # print('一个步长牛拉迭代次数:%s' % iteration) # 计算新的时间步长 if iteration > iter_max: h = time_step(False, iteration, t) print('减小步长(delta t = %.5f s)' % h) system.DAE.x = matrix(xa) system.DAE.y = matrix(ya) system.DAE.f = matrix(fn) else: # h = time_step(True, iteration, t) # t = actual_time h = 0.01 t = actual_time k = k + 1 system.Varout.store(t, k) t4 = time.time() # print('一个步长总仿真耗时:%s' % (t4-t3)) var = system.Varout.var t0 = matrix(system.Varout.t) var = matrix(var) var = var.T sio.savemat( 'C://Users//user//Desktop//平台//余伟洲//仿真结果//RES 时域仿真//restdvar.mat', { 'var': var, 't': t0 }) # sio.savemat('C://Users//user//Desktop//restdvar.mat', {'var': var, 't': t0}) print('time domain simulation completed') print('仿真次数%s', k) tend = time.time() print('机电暂态仿真总时间%s', tend - tstart)
def td20180410(): # avr vref随机波动 muvref01 = copy.deepcopy(system.Avr1.vref0) muvref02 = copy.deepcopy(system.Avr2.vref0) muvref = [] sigmavref = 0.1 # system.Avr1.suiji(muvref01, sigmavref) # system.Avr2.suiji(muvref02, sigmavref) # print('Avr setx0') # print(system.DAE.y) # print(system.Syn6.delta) # print('new') # # print(system.DAE.x) # print(system.DAE.x[system.Syn6.delta]) # system.PQ.Vmin = system.DAE.y[system.PQ.v] # 输出采用的时域仿真算法 # td_start = clock() print('time domain simulation ') print('Trapezoidal integration method') # 检查设置 iter_max = 20 tol = 0.00001 Dn = 1 if system.DAE.nx: Dn = system.DAE.nx identica = spmatrix(1.0, range(max(Dn, 1)), range(max(Dn, 1)), (max(Dn, 1), max(Dn, 1))) # 把PQ负荷转化为并联阻抗 system.PQ.pqshunt() # 建立变量 system.DAE.t = system.Settings.t0 # call system.DAE._list2matrix() system.Line.gcall() system.PQ.gcall() system.Shunt.gcall() system.Fault.gcall() system.Syn6.gcall() system.Avr1.gcall() system.Avr2.gcall() # system.PV.gcall() # system.SW.gcall() system.Line.Gycall() system.PQ.Gycall() system.Shunt.Gycall() # 故障 system.Fault.Gycall() system.Syn6.Gycall() system.Avr1.Gycall() system.Avr2.Gycall() # system.PV.Gycall() # system.SW.Gycall() system.Syn6.fcall() system.Avr1.fcall() system.Avr2.fcall() if system.DAE.nx > 0: system.DAE.Fx = spmatrix([], [], [], (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = spmatrix([], [], [], (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = spmatrix([], [], [], (system.DAE.ny, system.DAE.nx)) system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) system.Syn6.Fxcall() system.Avr1.Fxcall() system.Avr2.Fxcall() system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Fx = sparse(system.DAE.Fx) system.DAE.Fy = sparse(system.DAE.Fy) system.DAE.Gx = sparse(system.DAE.Gx) # print(system.DAE.f) system.DAE.tn = system.DAE.f # 初始化 t = system.Settings.t0 k = 1 # 存储初始输出 system.Varout.store(t, k) # 步长选择 def state_matrix(): Gyx = matrix(system.DAE.Gx) linsolve(sparse(system.DAE.Gy), Gyx) I = [] J = [] for i in range(system.DAE.nx): I.append(i) J.append(i) return system.DAE.Fx - system.DAE.Fy * Gyx - spmatrix(1e-6, I, J) def firsttime_tstep(): if system.DAE.nx == 0: freq = 1.0 elif system.DAE.nx == 1: AS = state_matrix() freq = max(abs(AS)) else: # 后续修改 freq = 40 if freq > system.Settings.freq: freq = float(system.Settings.freq) if not freq: freq = 40.0 # 设置最小时间步长 deltaT = abs(system.Settings.tf - system.Settings.t0) Tstep = 1 / freq system.Settings.deltatmax = min(5 * Tstep, deltaT / 100.0) system.Settings.deltat = min(Tstep, deltaT / 100.0) system.Settings.deltatmin = min(Tstep / 64, system.Settings.deltatmax / 20) if system.Settings.fixt: if system.Settings.tstep <= 0: print('Fixed time step is negative or zero') print('Automatic time step has been set') system.Settings.fixt = 1 elif system.Settings.tstep < system.Settings.deltatmin: print( 'Fixed time step is less than estimated minimum time step') system.Settings.deltat = system.Settings.tstep else: system.Settings.deltat = system.Settings.tstep return system.Settings.deltat # 初始时间步长 # h = firsttime_tstep() h = 0.01 inc = matrix(0.0, (system.DAE.nx + system.DAE.ny, 1)) # 故障时间排序 fixed_times = system.Fault.gettimes() fixed_times = sorted(fixed_times) # 计算最大转子间相对摇摆(先忽略) def anglediff(): diff_max = 0 delta = system.DAE.x[system.Syn6.delta].real() delta_diff = abs(delta - min(delta)) diff_max = (max(delta_diff) * 180 / math.pi) > system.Settings.deltadelta diff_max = 0 # diff_max = anglediff() switch = False def time_step(convergency, iteration, t): if convergency == False: system.Settings.deltat = system.Settings.deltat * 0.5 if system.Settings.deltat < system.Settings.deltatmin: system.Settings.deltat = 0 if convergency == True: if iteration >= 15: system.Settings.deltat = max(system.Settings.deltat * 0.9, system.Settings.deltatmin) if iteration <= 10: system.Settings.deltat = min(system.Settings.deltat * 1.3, system.Settings.deltatmax) if system.Settings.fixt: system.Settings.deltat = min(system.Settings.tstep, system.Settings.deltat) if system.Fault.istime(t): system.Settings.deltat = min(system.Settings.deltat, 0.0025) return system.Settings.deltat system.DAE.factorize = True vv = [round(system.DAE.y[system.Bus.a[0]], 14)] tt = [0.0] pyiter = [] # 设置线路最大传输容量 system.Line.SetSmax() # 输电线路故障模拟 # system.Line.settimes(t) # system.Line.gettimes(fixed_times) # fixed_times = sorted(fixed_times) # print(MWs) # 随机负荷波动参数 mup = copy.deepcopy(system.PQ.Pl) muq = copy.deepcopy(system.PQ.Ql) sigmap = 0.8 sigmaq = 0.8 # 随机发电机机械功率参数 musynp = copy.deepcopy(system.Syn6.pm0) sigmasynp = 0.1 suijih = 0.01 # yu 随机负荷波动 system.PQ.suiji(mup, muq, sigmap, sigmaq, t, suijih) # 发电机机械功率波动 # system.Syn6.suiji(musynp, sigmasynp, t, suijih) # avr vref0随机波动 # system.Avr1.suiji(muvref01, sigmavref) # system.Avr2.suiji(muvref02, sigmavref) muvref.append(system.Avr1.vref0[0]) # 主循环 while t < system.Settings.tf and t + h > t and not diff_max: if t + h > system.Settings.tf: h = system.Settings.tf - t actual_time = t + h # 检查不要跳过扰动(后续修改为更简洁形式) for item in fixed_times: if item > t and item < t + h: actual_time = item h = actual_time - t switch = True break # print(actual_time) system.DAE.t = actual_time # 备份变量 xa = matrix(system.DAE.x) ya = matrix(system.DAE.y) # 初始化牛拉法循环 iteration = 1 fn = matrix(system.DAE.f) # 微分方程 inc[0] = 1 # 执行扰动 if switch: system.Fault.intervention(actual_time) system.Line.intervention(actual_time) # system.Breaker.intervention(actual_time) switch = False # 牛拉循环 system.Settings.error = tol + 1 # 强迫进入循环一次 # # yu 随机负荷波动 # # system.PQ.suiji(mup, muq, sigmap, sigmaq, t, suijih) # # # 发电机机械功率波动 # system.Syn6.suiji(musynp, sigmasynp, t, suijih) # # # # avr vref0随机波动 # # # system.Avr1.suiji(muvref01, sigmavref) # # system.Avr2.suiji(muvref02, sigmavref) # muvref.append(system.Avr1.vref0[0]) while system.Settings.error > tol and iteration < iter_max: system.Line.gcall() system.PQ.gcall() system.Shunt.gcall() system.Fault.gcall() system.Syn6.gcall() system.Avr1.gcall() system.Avr2.gcall() # system.PV.gcall() # system.SW.gcall() system.Line.Gycall() system.PQ.Gycall() system.Shunt.Gycall() # 故障 system.Fault.Gycall() system.Syn6.Gycall() system.Avr1.Gycall() system.Avr2.Gycall() # system.PV.Gycall() # system.SW.Gycall() system.Syn6.fcall() system.Avr1.fcall() system.Avr2.fcall() if system.DAE.nx > 0: system.DAE.Fx = spmatrix([], [], [], (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = spmatrix([], [], [], (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = spmatrix([], [], [], (system.DAE.ny, system.DAE.nx)) system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) system.Syn6.Fxcall() system.Avr1.Fxcall() system.Avr2.Fxcall() system.DAE.Gy = sparse(system.DAE.Gy) system.DAE.Fx = sparse(system.DAE.Fx) system.DAE.Fy = sparse(system.DAE.Fy) system.DAE.Gx = sparse(system.DAE.Gx) # 计算雅可比矩阵 if system.Settings.method == 1: # 采用欧拉法 system.DAE.Ac = sparse( [[identica - h * system.DAE.Fx, system.DAE.Gx], [-h * system.DAE.Fy, system.DAE.Gy]]) system.DAE.tn = system.DAE.x - xa - h * system.DAE.f elif system.Settings.method == 2: # 采用隐式梯形法 system.DAE.Ac = sparse( [[identica - h * 0.5 * system.DAE.Fx, system.DAE.Gx], [-h * 0.5 * system.DAE.Fy, system.DAE.Gy]]) system.DAE.tn = system.DAE.x - xa - h * 0.5 * (system.DAE.f + fn) # 限幅器 system.Avr2.windup('td') # gg = -matrix([system.DAE.tn, system.DAE.g]) # linsolve(system.DAE.Ac, gg) # inc = gg if system.DAE.factorize: F = symbolic(system.DAE.Ac) system.DAE.factorize = False inc = -matrix([system.DAE.tn, system.DAE.g]) try: umfsolve(system.DAE.Ac, numeric(system.DAE.Ac, F), inc) except ArithmeticError: print('Singular matrix') iteration = iter_max + 1 except ValueError: F = symbolic(system.DAE.Ac) try: umfsolve(system.DAE.Ac, numeric(system.DAE.Ac, F), inc) except ArithmeticError: print('Singular matrix') iteration = iter_max + 1 system.DAE.x = system.DAE.x + inc[:system.DAE.nx] system.DAE.y = system.DAE.y + inc[system.DAE.nx:system.DAE.nx + system.DAE.ny] iteration = iteration + 1 system.Settings.error = max(abs(inc)) # 计算新的时间步长 pyiter.append(iteration) # print(iteration) if iteration > iter_max: h = time_step(False, iteration, t) print('减小步长(delta t = %.5f s)' % h) system.DAE.x = matrix(xa) system.DAE.y = matrix(ya) system.DAE.f = matrix(fn) else: # h = time_step(True, iteration, t) h = 0.01 t = actual_time # yu 随机负荷波动 system.PQ.suiji(mup, muq, sigmap, sigmaq, t, suijih) # 发电机机械功率波动 # system.Syn6.suiji(musynp, sigmasynp, t, suijih) # 输电线路故障模拟 # system.Line.settimes(t) # system.Line.gettimes(fixed_times) # fixed_times = sorted(fixed_times) # avr vref0随机波动 # system.Avr1.suiji(muvref01, sigmavref) # system.Avr2.suiji(muvref02, sigmavref) muvref.append(system.Avr1.vref0[0]) k = k + 1 # 更新输出 system.Varout.store(t, k) vv15 = round(system.DAE.y[system.Bus.a[0]].real, 14) # print(vv15) vv.append(vv15) tt.append(system.DAE.t) [MWs, MWr] = system.Line.flow() var = system.Varout.var # print(system.Varout.t) var = matrix(var) var = var.T # print(var[:, 76]) tt = matrix(tt) vv = matrix(vv)
(system.DAE.nx, system.DAE.ny)) system.DAE.Gx = spmatrix([], [], [], (system.DAE.ny, system.DAE.nx)) system.DAE.Fx = matrix(0.0, (system.DAE.nx, system.DAE.nx)) system.DAE.Fy = matrix(0.0, (system.DAE.nx, system.DAE.ny)) system.DAE.Gx = matrix(0.0, (system.DAE.ny, system.DAE.nx)) system.Syn6.Fxcall() system.Avr1.Fxcall() system.Avr2.Fxcall() #计算雅可比矩阵 if system.Settings.method == 'euler': system.DAE.Ac = sparse([[In - h * system.DAE.Fx, system.DAE.Gx], [-h * system.DAE.Fy, system.DAE.Gy]]) system.DAE.q = system.DAE.x - xa - h * system.DAE.f else: system.DAE.Ac = sparse( [[In - h * 0.5 * system.DAE.Fx, system.DAE.Gx], [-h * 0.5 * system.DAE.Fy, system.DAE.Gy]]) system.DAE.q = system.DAE.x - xa - h * 0.5 * (system.DAE.f + fn) if fth2: if iteration >= 2: system.Avr2.windup() # #限幅器
def setx0(self): if self.n == 0: return check = 1 Pc = system.Bus.Pg[self.a] Qc = system.Bus.Qg[self.a] Vc = system.DAE.y[self.v] ac = system.DAE.y[self.a] vds = mul(-Vc, sin(ac)) # 角度还是弧度 vqs = mul(Vc, cos(ac)) rho = system.Wind.rho[self.wind] ones = matrix(1, (self.n, 1)) # 常数 # xs + xm self.dat1 = self.xs + self.xm self.dat2 = self.xr + self.xm self.dat3 = div(ones, mul(2 * ones, self.Hm)) self.dat4 = div( mul(4 * math.pi * system.Settings.freq * self.R, self.nGB), self.np) self.dat5 = math.pi * mul(self.R, self.R) self.dat6 = Vc self.dat8 = mul(div(-self.pmin, self.xm), self.dat1) self.dat9 = mul(div(-self.pmax, self.xm), self.dat1) self.dat10 = -mul(div(div(ones, self.xm) + self.qmin, self.xm), self.dat1) self.dat11 = -mul(div(div(ones, self.xm) + self.qmax, self.xm), self.dat1) # 初始化状态变量 for i in range(self.n): # 参数 Vds = vds[i] Vqs = vqs[i] Rs = self.rs[i] Rr = self.rr[i] Xm = self.xm[i] x1 = self.dat1[i] x2 = self.dat2[i] Pg = Pc[i] Qg = Qc[i] # 转子速度 Pci = Pc[i] * system.Settings.mva if (Pci < self.Sn[i]) & (Pc[i] > 0): omega = 0.5 * Pc[i] * system.Settings.mva / self.Sn + 0.5 elif Pci >= self.Sn[i]: omega = 1 else: omega = 0.5 slip = 1 - omega iqr = -x1 * self.Sn * ( 2 * omega - 1) / Vc[i] / Xm / system.Settings.mva / omega A = [[-Rs, Vqs], [x1, -Vds]] B = [Vds - Xm * iqr, Qg] A = sparse(A) B = matrix(B) umfpack.linsolve(A, B) # B = numpy.array(B) # Is = numpy.linalg.solve(A, B) ids = B[0] iqs = B[1] idr = -(Vqs + Rs * iqs + x1 * ids) / Xm vdr = -Rr * idr + slip * (x2 * iqr + Xm * iqs) vqr = -Rr * iqr - slip * (x2 * idr + Xm * ids) jac = matrix(0.0, (6, 6)) eqn = matrix(1.0, (6, 1)) inc = matrix(1.0, (6, 1)) x = matrix(0.0, (6, 1)) x[0] = ids x[1] = iqs x[2] = idr x[3] = iqr x[4] = vdr x[5] = vqr rows = [0, 0, 0, 1, 1, 1, 2, 2, 3, 3, 4, 4, 5] cols = [0, 1, 3, 0, 1, 2, 2, 4, 3, 5, 0, 1, 2] vals = [ -Rs, x1, Xm, -x1, -Rs, -Xm, -Rr, -1, -Rr, -1, Vds, Vqs, -Xm * Vc[i] / x1 ] jac0 = spmatrix(vals, rows, cols, (6, 6), 'd') # jac0 = jac + spmatrix(-Rs, [0], [0], (6, 6)) # jac0 = jac + spmatrix(x1, [0], [1], (6, 6)) # jac0 = jac + spmatrix(Xm, [0], [3], (6, 6)) # jac0 = jac + spmatrix(-x1, [1], [0], (6, 6)) # jac0 = jac + spmatrix(-Rs, [1], [1], (6, 6)) # jac0 = jac + spmatrix(-Xm, [1], [2], (6, 6)) # jac0 = jac + spmatrix(-Rr, [2], [2], (6, 6)) # jac0 = jac + spmatrix(-1, [2], [4], (6, 6)) # jac0 = jac + spmatrix(-Rr, [3], [3], (6, 6)) # jac0 = jac + spmatrix(-1, [3], [5], (6, 6)) # jac0 = jac + spmatrix(Vds, [4], [0], (6, 6)) # jac0 = jac + spmatrix(Vqs, [4], [1], (6, 6)) # jac0 = jac + spmatrix(-Xm*Vc[i]/x1, [5], [2], (6, 6)) k = x1 * self.Sn[i] / Vc[i] / Xm / system.Settings.mva iter = 0 while max(abs(eqn)) > 1e-8: if iter > 20: print('双馈风力发电机%i初始化失败' % i) check = 0 break eqn[0] = -Rs * x[0] + x1 * x[1] + Xm * x[3] - Vds eqn[1] = -Rs * x[1] - x1 * x[0] - Xm * x[2] - Vqs eqn[2] = -Rr * x[2] + slip * (x2 * x[3] + Xm * x[1]) - x[4] eqn[3] = -Rr * x[3] - slip * (x2 * x[2] + Xm * x[0]) - x[5] eqn[4] = Vds * x[0] + Vqs * x[1] + x[4] * x[2] + x[5] * x[ 3] - Pg eqn[5] = -Xm * Vc[i] * x[2] / x1 - Vc[i] * Vc[i] / x1 - Qg rows = [2, 2, 3, 3, 4, 4, 4, 4] cols = [1, 3, 0, 2, 2, 3, 4, 5] vals = [ slip[i] * Xm, slip[i] * x2, -slip[i] * Xm, -slip[i] * x2, x[4], x[5], x[2], x[3] ] jac = jac0 + spmatrix(vals, rows, cols, (6, 6), 'd') # jac = jac + spmatrix(slip * Xm, [2], [1], (6, 6)) # jac = jac + spmatrix(slip * x2, [2], [3], (6, 6)) # jac = jac + spmatrix(-slip * Xm, [3], [0], (6, 6)) # jac = jac + spmatrix(-slip * x2, [3], [2], (6, 6)) # jac = jac + spmatrix(x[4], [4], [2], (6, 6)) # jac = jac + spmatrix(x[5], [4], [3], (6, 6)) # jac = jac + spmatrix(x[2], [4], [4], (6, 6)) # jac = jac + spmatrix(x[3], [4], [5], (6, 6)) jac = sparse(jac) umfpack.linsolve(jac, eqn) #inc = -numpy.linalg.solve(jac, eqn) x = x - eqn iter = iter + 1 ids = x[0] iqs = x[1] idr = x[2] iqr = x[3] vdr = x[4] vqr = x[5] if iqr > self.dat8[i]: print( 'Warning: Dfig %i at Bus %s : iqr is over its max limit' % (i, self.a[i])) check = 0 if iqr < self.dat9[i]: print( 'Warning: Dfig %i at Bus %s : iqr is under its min limit' % (i, self.a[i])) check = 0 if idr > self.dat10[i]: print( 'Warning: Dfig %i at Bus %s : idr is over its max limit' % (i, self.a[i])) check = 0 if idr < self.dat11[i]: print( 'Warning: Dfig %i at Bus %s : idr is under its min limit' % (i, self.a[i])) check = 0 # theta_p contex = decimal.getcontext() contex.rounding = decimal.ROUND_05UP theta = self.Kp * round(Decimal(1000 * (omega[i] - 1))) / 1000 theta = max([theta[0], 0]) # wind turbine state variables system.DAE.x[self.idr[i]] = idr system.DAE.x[self.iqr[i]] = iqr system.DAE.x[self.omega_m[i]] = omega system.DAE.x[self.theta_p[i]] = theta # Vref Kv = self.Kv[i] if Kv == 0: # 没有电压控制 self.dat6 = 0 else: self.dat6 = Vc[i] - (idr + Vc[i] / Xm) / Kv self.dat7 = -k * max([min([2 * omega[i] - 1, 1]), 0 ]) / omega[i] - iqr # electric torque Tel = Xm * (iqr * ids - idr * iqs) if Pg < 0: print('** Turbine power is negative at Bus %i' % self.a[i]) print('Wind speed % i can not be initialized.' % self.wind[i]) system.DAE.x[system.Wind.vw[self.wind[i]]] = 1 continue # wind power [MW] Pw = Tel * omega * system.Settings.mva * 1e6 / self.ng # wind speed iter = 0 incvw = matrix(1.0, (1, 1)) eqnvw = [1] R = self.dat4[i] AA = self.dat5[i] # initial guess wind speed vw = 0.9 * system.Wind.vwn[self.wind[i]] while abs(incvw[0]) > 1e-7: if iter > 50: print( '**Initialization of wind speed %i failed(converge problem)' % self.wind[i]) print('Tip: Try increasing the nominal wind speed') check = 0 break output = system.Dfig.windpower(rho[i], vw, AA, R, omega, theta, 1) eqnvw = output - Pw jacvw = system.Dfig.windpower(rho[i], vw, AA, R, omega, theta, 2) # incvw = -numpy.linalg.solve(jacvw[2], eqnvw) incvw = -eqnvw / jacvw[1] vw = vw + incvw[0] iter = iter + 1 # average initial wind speed system.DAE.x[system.Wind.vw[ self.wind[i]]] = vw / system.Wind.vwn[self.wind[i]] # find and delete static generators for bj in range(self.n): for bk in range(system.PV.n): if self.u[bj] * self.a[bj] == system.PV.a[bk]: idx = 'PV_' + str(bk + 1) system.PV.remove(idx) for bk in range(system.SW.n): if self.u[bj] * self.a[bj] == system.SW.a[bk]: system.SW.remove(idx='SW_1') system.DAE.x[self.idr] = mul(self.u, system.DAE.x[self.idr]) system.DAE.x[self.iqr] = mul(self.u, system.DAE.x[self.iqr]) system.DAE.x[self.omega_m] = mul(self.u, system.DAE.x[self.omega_m]) system.DAE.x[self.theta_p] = mul(self.u, system.DAE.x[self.theta_p]) system.DAE.y[self.vref] = mul(self.u, self.dat6) xomega = system.DAE.x[self.omega_m] xomega1 = matrix(0.0, (self.n, 1)) for i in range(self.n): xomega1[i] = max([min([2 * xomega[i] - 1, 1]), 0]) system.DAE.y[self.pwa] = mul(self.Sn, div(xomega1, system.Settings.mva)) if not check: print('双馈风力发电机初始化失败') else: print('双馈风力发电机初始化完成')
def _gen_randsdp(self, V, m, d, seed): """ Random data generator """ setseed(seed) n = self._n V = chompack.tril(V) N = len(V) I = V.I J = V.J Il = misc.sub2ind((n, n), I, J) Id = matrix([i for i in xrange(len(Il)) if I[i] == J[i]]) # generate random y with norm 1 y0 = normal(m, 1) y0 /= blas.nrm2(y0) # generate random S0, X0 S0 = mk_rand(V, cone='posdef', seed=seed) X0 = mk_rand(V, cone='completable', seed=seed) # generate random A1,...,Am if type(d) is float: nz = min(max(1, int(round(d * N))), N) A = sparse( [[ spmatrix(normal(N, 1), Il, [0 for i in xrange(N)], (n**2, 1)) ], [ spmatrix( normal(nz * m, 1), [i for j in xrange(m) for i in random.sample(Il, nz)], [j for j in xrange(m) for i in xrange(nz)], (n**2, m)) ]]) elif type(d) is list: if len(d) == m: nz = [min(max(1, int(round(v * N))), N) for v in d] nnz = sum(nz) A = sparse( [[ spmatrix(normal(N, 1), Il, [0 for i in xrange(N)], (n**2, 1)) ], [ spmatrix(normal(nnz, 1), [ i for j in xrange(m) for i in random.sample(Il, nz[j]) ], [j for j in xrange(m) for i in xrange(nz[j])], (n**2, m)) ]]) else: raise TypeError # compute A0 u = +S0.V for k in xrange(m): base.gemv(A[:, k + 1][Il], matrix(y0[k]), u, beta=1.0, trans='N') A[Il, 0] = u self._A = A # compute b X0[Il[Id]] *= 0.5 self._b = matrix(0., (m, 1)) u = matrix(0.) for k in xrange(m): base.gemv(A[:, k + 1][Il], X0.V, u, trans='T', alpha=2.0) self._b[k] = u
def what_is_the_matrix(X, Z): """find the optimal morphing matrix A such that A * src_dist = target_dist""" #print "============ What is the Matrix? ===============" n = len(Z) N = n**2 #print "X =", X.T #print "Z =", Z.T # Equality Constraints A_list = [] b_list = [] # -- the columns of the matrix must be valid PDF's A_pdf = matrix(0.0, (n, N), 'd') for i in range(n): A_pdf[i, n * i:n * i + n] = 1.0 b_pdf = matrix(1.0, (n, 1), 'd') #print "A_pdf =" #print A_pdf #print "b_pdf =" #print b_pdf A_list.append(A_pdf) b_list.append(b_pdf) # -- the matrix must morph X to Z A_morph = matrix(0.0, (n, N), 'd') for i in range(n): matrix_vers = matrix(0.0, (n, n), 'd') matrix_vers[i, :] = X.T row = matrix(matrix_vers, (1, N), 'd') A_morph[i, :] = row b_morph = matrix(Z, (n, 1), 'd') A_list.append(A_morph) b_list.append(b_morph) #print "A_morph =" #print A_morph #print "b_morph =" #print b_morph # concatenate all our equality constraints into one coeff matrix and one b vector #A_list = [A_morph, A_pdf] #b_list = [b_morph, b_pdf] #A_list = [A_pdf] #b_list = [b_pdf] #A = matrix(A_list) A = sparse(A_list) b = matrix(b_list) #print "A =" #print A #print "b =" #print b # Inequality Constraints -- in order to be a valid PDF, each cell a_ij must be 0 <= a_ij <= 1 G_list = [] h_list = [] G_lt = spdiag(matrix(1.0, (N, 1), 'd')) h_lt = matrix(1.0, (N, 1), 'd') # cvw: as mentioned in the comment above in find_the_one(), the "less than" constraints are # in fact redundant given that we already require the columns to sum to 1.0 and require # (below) that each prob is >= 0. yay for smaller KKT matrices. #G_list.append(G_lt) #h_list.append(h_lt) G_gt = spdiag(matrix(-1.0, (N, 1), 'd')) h_gt = matrix(0.0, (N, 1), 'd') G_list.append(G_gt) h_list.append(h_gt) # cvw: I guess we could add some more constraints if we really wanted to.. # i.e. only downgrade the bit rate 10% of the time or less # but for now these'll do G = sparse(G_list) h = matrix(h_list) #print "G =" #print G #print "h =" #print h #print "vectorized cost matrix =" #print c.T # now run the cvxopt solver to get our answer #print "running cvxopt lp() solver..." ans = solvers.lp(cost_matrix, G=G, h=h, A=A, b=b, solver='glpk') ##print ans['x'] #print "answer = ", ans A = None if ans['x']: cost = cost_matrix.T * ans['x'] # A is the morphing matrix A = matrix(ans['x'], (n, n), 'd') return A
def what_is_the_matrix(X, Z): """find the optimal morphing matrix A such that A * src_dist = target_dist""" #print "============ What is the Matrix? ===============" n = len(Z) N = n**2 #print "X =", X.T #print "Z =", Z.T # Equality Constraints A_list = [] b_list = [] # -- the columns of the matrix must be valid PDF's A_pdf = matrix(0.0, (n,N), 'd') for i in range(n): A_pdf[i,n*i:n*i+n] = 1.0 b_pdf = matrix(1.0, (n,1), 'd') #print "A_pdf =" #print A_pdf #print "b_pdf =" #print b_pdf A_list.append(A_pdf) b_list.append(b_pdf) # -- the matrix must morph X to Z A_morph = matrix(0.0, (n,N), 'd') for i in range(n): matrix_vers = matrix(0.0, (n,n), 'd') matrix_vers[i,:] = X.T row = matrix(matrix_vers, (1,N), 'd') A_morph[i,:] = row b_morph = matrix(Z, (n,1), 'd') A_list.append(A_morph) b_list.append(b_morph) #print "A_morph =" #print A_morph #print "b_morph =" #print b_morph # concatenate all our equality constraints into one coeff matrix and one b vector #A_list = [A_morph, A_pdf] #b_list = [b_morph, b_pdf] #A_list = [A_pdf] #b_list = [b_pdf] #A = matrix(A_list) A = sparse(A_list) b = matrix(b_list) #print "A =" #print A #print "b =" #print b # Inequality Constraints -- in order to be a valid PDF, each cell a_ij must be 0 <= a_ij <= 1 G_list = [] h_list = [] G_lt = spdiag(matrix(1.0, (N,1), 'd')) h_lt = matrix(1.0, (N,1), 'd') # cvw: as mentioned in the comment above in find_the_one(), the "less than" constraints are # in fact redundant given that we already require the columns to sum to 1.0 and require # (below) that each prob is >= 0. yay for smaller KKT matrices. #G_list.append(G_lt) #h_list.append(h_lt) G_gt = spdiag(matrix(-1.0, (N,1), 'd')) h_gt = matrix(0.0, (N,1), 'd') G_list.append(G_gt) h_list.append(h_gt) # cvw: I guess we could add some more constraints if we really wanted to.. # i.e. only downgrade the bit rate 10% of the time or less # but for now these'll do G = sparse(G_list) h = matrix(h_list) #print "G =" #print G #print "h =" #print h #print "vectorized cost matrix =" #print c.T # now run the cvxopt solver to get our answer #print "running cvxopt lp() solver..." ans = solvers.lp(cost_matrix, G=G, h=h, A=A, b=b, solver='glpk') ##print ans['x'] #print "answer = ", ans A = None if ans['x']: cost = cost_matrix.T * ans['x'] # A is the morphing matrix A = matrix(ans['x'], (n,n), 'd') return A