def qr(a,overwrite_a=0,lwork=None): """QR decomposition of an M x N matrix a. Description: Find a unitary matrix, q, and an upper-trapezoidal matrix r such that q * r = a Inputs: a -- the matrix overwrite_a=0 -- if non-zero then discard the contents of a, i.e. a is used as a work array if possible. lwork=None -- >= shape(a)[1]. If None (or -1) compute optimal work array size. Outputs: q, r -- matrices such that q * r = a """ a1 = asarray_chkfinite(a) if len(a1.shape) != 2: raise ValueError, 'expected matrix' M,N = a1.shape overwrite_a = overwrite_a or (a1 is not a and not hasattr(a,'__array__')) geqrf, = get_lapack_funcs(('geqrf',),(a1,)) if lwork is None or lwork == -1: # get optimal work array qr,tau,work,info = geqrf(a1,lwork=-1,overwrite_a=1) lwork = work[0] qr,tau,work,info = geqrf(a1,lwork=lwork,overwrite_a=overwrite_a) if info<0: raise ValueError,\ 'illegal value in %-th argument of internal geqrf'%(-info) gemm, = get_blas_funcs(('gemm',),(qr,)) t = qr.typecode() R = basic.triu(qr) Q = scipy_base.identity(M,typecode=t) ident = scipy_base.identity(M,typecode=t) zeros = scipy_base.zeros for i in range(min(M,N)): v = zeros((M,),t) v[i] = 1 v[i+1:M] = qr[i+1:M,i] H = gemm(-tau[i],v,v,1+0j,ident,trans_b=2) Q = gemm(1,Q,H) return Q, R
def pinv(a, cond=None): """ pinv(a, cond=None) -> a_pinv Compute generalized inverse of A using least-squares solver. """ a = asarray_chkfinite(a) t = a.typecode() b = scipy_base.identity(a.shape[0],t) return lstsq(a, b, cond=cond)[0]