bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def d_restrict_source(workd,subjslots,source): """
def d_restrict_source(workd,subjslots,source): """
800
def d_restrict_source(workd,subjslots,source): """
def d_restrict_source(workd,subjslots,source): """
801
def d_restrict_source(workd,subjslots,source): """
def d_restrict_source(workd,subjslots,source): """
802
def d_restrict_source(workd,subjslots,source): """
def d_restrict_source(workd,subjslots,source): """
803
def d_restrict_source(workd,subjslots,source): """
def d_restrict_source(workd,subjslots,source): """
804
def d_restrict_source(workd,subjslots,source): """
def d_restrict_source(workd,subjslots,source): """
805
def d_restrict_source(workd,subjslots,source): """
def d_restrict_source(workd,subjslots,source): """
806
def d_restrict_source(workd,subjslots,source): """
def d_restrict_source(workd,subjslots,source): """
807
def d_restrict_source(workd,subjslots,source): """
def d_restrict_source(workd,subjslots,source): """
808
def d_restrict_source(workd,subjslots,source): """
def d_restrict_source(workd,subjslots,source): """
809
def d_restrict_source(workd,subjslots,source): """
def d_restrict_source(workd,subjslots,source): """
810
def multivar_sscalc(workd):
def multivar_sscalc(workd):
811
def subtr_cellmeans(workd,subjslots): """
def subtr_cellmeans(workd,subjslots): """
812
def subtr_cellmeans(workd,subjslots): """
def subtr_cellmeans(workd,subjslots): """
813
def subtr_cellmeans(workd,subjslots): """
def subtr_cellmeans(workd,subjslots): """
814
def speye(n, m = None, k = 0, dtype = 'd'): """ speye(n, m) returns a (n x m) matrix stored in CSC sparse matrix format, where the k-th diagonal is all ones, and everything else is zeros. """ diags = ones((1, n), dtype = dtype) return spdiags(diags, k, n, m)
def speye(n, m = None, k = 0, dtype = 'd'): """ speye(n, m) returns a (n x m) matrix stored in CSC sparse matrix format, where the k-th diagonal is all ones, and everything else is zeros. """ diags = ones((1, n), dtype = dtype) return spdiags(diags, k, n, m)
815
def fminbound(func, x1, x2, args=(), xtol=1e-5, maxfun=500, full_output=0, disp=1): """Bounded minimization for scalar functions. Description: Finds a local minimizer of the scalar function func in the interval x1 < xopt < x2 using Brent's method. (See brent for auto-bracketing). Inputs: func -- the function to be minimized (must accept scalar input and return scalar output). x1, x2 -- the optimization bounds. args -- extra arguments to pass to function. xtol -- the convergence tolerance. maxfun -- maximum function evaluations. full_output -- Non-zero to return optional outputs. disp -- Non-zero to print messages. 0 : no message printing. 1 : non-convergence notification messages only. 2 : print a message on convergence too. 3 : print iteration results. Outputs: (xopt, {fval, ierr, numfunc}) xopt -- The minimizer of the function over the interval. fval -- The function value at the minimum point. ierr -- An error flag (0 if converged, 1 if maximum number of function calls reached). numfunc -- The number of function calls. """ if x1 > x2: raise ValueError, "The lower bound exceeds the upper bound." flag = 0 header = ' Func-count x f(x) Procedure' step=' initial' sqrt_eps = sqrt(2.2e-16) golden_mean = 0.5*(3.0-sqrt(5.0)) a, b = x1, x2 fulc = a + golden_mean*(b-a) nfc, xf = fulc, fulc rat = e = 0.0 x = xf fx = func(x,*args) num = 1 fmin_data = (1, xf, fx) ffulc = fnfc = fx xm = 0.5*(a+b) tol1 = sqrt_eps*abs(xf) + xtol / 3.0 tol2 = 2.0*tol1 if disp > 2: print (" ") print (header) print "%5.0f %12.6g %12.6g %s" % (fmin_data + (step,)) while ( abs(xf-xm) > (tol2 - 0.5*(b-a)) ): golden = 1 # Check for parabolic fit if abs(e) > tol1: golden = 0 r = (xf-nfc)*(fx-ffulc) q = (xf-fulc)*(fx-fnfc) p = (xf-fulc)*q - (xf-nfc)*r q = 2.0*(q-r) if q > 0.0: p = -p q = abs(q) r = e e = rat # Check for acceptability of parabola if ( (abs(p) < abs(0.5*q*r)) and (p > q*(a-xf)) and (p < q*(b-xf))): rat = (p+0.0) / q; x = xf + rat step = ' parabolic' if ((x-a) < tol2) or ((b-x) < tol2): si = Numeric.sign(xm-xf) + ((xm-xf)==0) rat = tol1*si else: # do a golden section step golden = 1 if golden: # Do a golden-section step if xf >= xm: e=a-xf else: e=b-xf rat = golden_mean*e step = ' golden' si = Numeric.sign(rat) + (rat == 0) x = xf + si*max([abs(rat), tol1]) fu = func(x,*args) num += 1 fmin_data = (num, x, fu) if disp > 2: print "%5.0f %12.6g %12.6g %s" % (fmin_data + (step,)) if fu <= fx: if x >= xf: a = xf else: b = xf fulc, ffulc = nfc, fnfc nfc, fnfc = xf, fx xf, fx = x, fu else: if x < xf: a = x else: b = x if (fu <= fnfc) or (nfc == xf): fulc, ffulc = nfc, fnfc nfc, fnfc = x, fu elif (fu <= ffulc) or (fulc == xf) or (fulc == nfc): fulc, ffulc = x, fu xm = 0.5*(a+b) tol1 = sqrt_eps*abs(xf) + xtol/3.0 tol2 = 2.0*tol1 if num >= maxfun: flag = 1 fval = fx if disp > 0: _endprint(x, flag, fval, maxfun, tol, disp) if full_output: return xf, fval, flag, num else: return xf fval = fx if disp > 0: _endprint(x, flag, fval, maxfun, xtol, disp) if full_output: return xf, fval, flag, num else: return xf
def fminbound(func, x1, x2, args=(), xtol=1e-5, maxfun=500, full_output=0, disp=1): """Bounded minimization for scalar functions. Description: Finds a local minimizer of the scalar function func in the interval x1 < xopt < x2 using Brent's method. (See brent for auto-bracketing). Inputs: func -- the function to be minimized (must accept scalar input and return scalar output). x1, x2 -- the optimization bounds. args -- extra arguments to pass to function. xtol -- the convergence tolerance. maxfun -- maximum function evaluations. full_output -- Non-zero to return optional outputs. disp -- Non-zero to print messages. 0 : no message printing. 1 : non-convergence notification messages only. 2 : print a message on convergence too. 3 : print iteration results. Outputs: (xopt, {fval, ierr, numfunc}) xopt -- The minimizer of the function over the interval. fval -- The function value at the minimum point. ierr -- An error flag (0 if converged, 1 if maximum number of function calls reached). numfunc -- The number of function calls. """ if x1 > x2: raise ValueError, "The lower bound exceeds the upper bound." flag = 0 header = ' Func-count x f(x) Procedure' step=' initial' sqrt_eps = sqrt(2.2e-16) golden_mean = 0.5*(3.0-sqrt(5.0)) a, b = x1, x2 fulc = a + golden_mean*(b-a) nfc, xf = fulc, fulc rat = e = 0.0 x = xf fx = func(x,*args) num = 1 fmin_data = (1, xf, fx) ffulc = fnfc = fx xm = 0.5*(a+b) tol1 = sqrt_eps*abs(xf) + xtol / 3.0 tol2 = 2.0*tol1 if disp > 2: print (" ") print (header) print "%5.0f %12.6g %12.6g %s" % (fmin_data + (step,)) while ( abs(xf-xm) > (tol2 - 0.5*(b-a)) ): golden = 1 # Check for parabolic fit if abs(e) > tol1: golden = 0 r = (xf-nfc)*(fx-ffulc) q = (xf-fulc)*(fx-fnfc) p = (xf-fulc)*q - (xf-nfc)*r q = 2.0*(q-r) if q > 0.0: p = -p q = abs(q) r = e e = rat # Check for acceptability of parabola if ( (abs(p) < abs(0.5*q*r)) and (p > q*(a-xf)) and (p < q*(b-xf))): rat = (p+0.0) / q; x = xf + rat step = ' parabolic' if ((x-a) < tol2) or ((b-x) < tol2): si = Numeric.sign(xm-xf) + ((xm-xf)==0) rat = tol1*si else: # do a golden section step golden = 1 if golden: # Do a golden-section step if xf >= xm: e=a-xf else: e=b-xf rat = golden_mean*e step = ' golden' si = Numeric.sign(rat) + (rat == 0) x = xf + si*max([abs(rat), tol1]) fu = func(x,*args) num += 1 fmin_data = (num, x, fu) if disp > 2: print "%5.0f %12.6g %12.6g %s" % (fmin_data + (step,)) if fu <= fx: if x >= xf: a = xf else: b = xf fulc, ffulc = nfc, fnfc nfc, fnfc = xf, fx xf, fx = x, fu else: if x < xf: a = x else: b = x if (fu <= fnfc) or (nfc == xf): fulc, ffulc = nfc, fnfc nfc, fnfc = x, fu elif (fu <= ffulc) or (fulc == xf) or (fulc == nfc): fulc, ffulc = x, fu xm = 0.5*(a+b) tol1 = sqrt_eps*abs(xf) + xtol/3.0 tol2 = 2.0*tol1 if num >= maxfun: flag = 1 fval = fx if disp > 0: _endprint(x, flag, fval, maxfun, xtol, disp) if full_output: return xf, fval, flag, num else: return xf fval = fx if disp > 0: _endprint(x, flag, fval, maxfun, xtol, disp) if full_output: return xf, fval, flag, num else: return xf
816
def brent(func, args=(), brack=None, tol=1.48e-8, full_output=0, maxiter=500): """ Given a function of one-variable and a possible bracketing interval, return the minimum of the function isolated to a fractional precision of tol. A bracketing interval is a triple (a,b,c) where (a<b<c) and func(b) < func(a),func(c). If bracket is two numbers then they are assumed to be a starting interval for a downhill bracket search (see bracket) Uses inverse parabolic interpolation when possible to speed up convergence of golden section method. """ _mintol = 1.0e-11 _cg = 0.3819660 if brack is None: xa,xb,xc,fa,fb,fc,funcalls = bracket(func, args=args) elif len(brack) == 2: xa,xb,xc,fa,fb,fc,funcalls = bracket(func, xa=brack[0], xb=brack[1], args=args) elif len(brack) == 3: xa,xb,xc = brack if (xa > xc): # swap so xa < xc can be assumed dum = xa; xa=xc; xc=dum assert ((xa < xb) and (xb < xc)), "Not a bracketing interval." fa = apply(func, (xa,)+args) fb = apply(func, (xb,)+args) fc = apply(func, (xc,)+args) assert ((fb<fa) and (fb < fc)), "Not a bracketing interval." funcalls = 3 else: raise ValuError, "Bracketing interval must be length 2 or 3 sequence." x=w=v=xb fw=fv=fx=apply(func, (x,)+args) if (xa < xc): a = xa; b = xc else: a = xc; b = xa deltax= 0.0 funcalls = 1 iter = 0 while (iter < maxiter): tol1 = tol*abs(x) + _mintol tol2 = 2.0*tol1 xmid = 0.5*(a+b) if abs(x-xmid) < (tol2-0.5*(b-a)): # check for convergence xmin=x; fval=fx break if (abs(deltax) <= tol1): if (x>=xmid): deltax=a-x # do a golden section step else: deltax=b-x rat = _cg*deltax else: # do a parabolic step tmp1 = (x-w)*(fx-fv) tmp2 = (x-v)*(fx-fw) p = (x-v)*tmp2 - (x-w)*tmp1; tmp2 = 2.0*(tmp2-tmp1) if (tmp2 > 0.0): p = -p tmp2 = abs(tmp2) dx_temp = deltax deltax= rat # check parabolic fit if ((p > tmp2*(a-x)) and (p < tmp2*(b-x)) and (abs(p) < abs(0.5*tmp2*dx_temp))): rat = p*1.0/tmp2 # if parabolic step is useful. u = x + rat if ((u-a) < tol2 or (b-u) < tol2): if xmid-x >= 0: rat = tol1 else: rat = -tol1 else: if (x>=xmid): deltax=a-x # if it's not do a golden section step else: deltax=b-x rat = _cg*deltax if (abs(rat) < tol1): # update by at least tol1 if rat >= 0: u = x + tol1 else: u = x - tol1 else: u = x + rat fu = apply(func, (u,)+args) # calculate new output value funcalls += 1 if (fu > fx): # if it's bigger than current if (u<x): a=u else: b=u if (fu<=fw) or (w==x): v=w; w=u; fv=fw; fw=fu elif (fu<=fv) or (v==x) or (v==w): v=u; fv=fu else: if (u >= x): a = x else: b = x v=w; w=x; x=u fv=fw; fw=fx; fx=fu xmin = x fval = fx if full_output: return xmin, fval, iter, funcalls else: return xmin
def brent(func, args=(), brack=None, tol=1.48e-8, full_output=0, maxiter=500): """ Given a function of one-variable and a possible bracketing interval, return the minimum of the function isolated to a fractional precision of tol. A bracketing interval is a triple (a,b,c) where (a<b<c) and func(b) < func(a),func(c). If bracket is two numbers then they are assumed to be a starting interval for a downhill bracket search (see bracket) Uses inverse parabolic interpolation when possible to speed up convergence of golden section method. """ _mintol = 1.0e-11 _cg = 0.3819660 if brack is None: xa,xb,xc,fa,fb,fc,funcalls = bracket(func, args=args) elif len(brack) == 2: xa,xb,xc,fa,fb,fc,funcalls = bracket(func, xa=brack[0], xb=brack[1], args=args) elif len(brack) == 3: xa,xb,xc = brack if (xa > xc): # swap so xa < xc can be assumed dum = xa; xa=xc; xc=dum assert ((xa < xb) and (xb < xc)), "Not a bracketing interval." fa = apply(func, (xa,)+args) fb = apply(func, (xb,)+args) fc = apply(func, (xc,)+args) assert ((fb<fa) and (fb < fc)), "Not a bracketing interval." funcalls = 3 else: raise ValueError, "Bracketing interval must be length 2 or 3 sequence." x=w=v=xb fw=fv=fx=apply(func, (x,)+args) if (xa < xc): a = xa; b = xc else: a = xc; b = xa deltax= 0.0 funcalls = 1 iter = 0 while (iter < maxiter): tol1 = tol*abs(x) + _mintol tol2 = 2.0*tol1 xmid = 0.5*(a+b) if abs(x-xmid) < (tol2-0.5*(b-a)): # check for convergence xmin=x; fval=fx break if (abs(deltax) <= tol1): if (x>=xmid): deltax=a-x # do a golden section step else: deltax=b-x rat = _cg*deltax else: # do a parabolic step tmp1 = (x-w)*(fx-fv) tmp2 = (x-v)*(fx-fw) p = (x-v)*tmp2 - (x-w)*tmp1; tmp2 = 2.0*(tmp2-tmp1) if (tmp2 > 0.0): p = -p tmp2 = abs(tmp2) dx_temp = deltax deltax= rat # check parabolic fit if ((p > tmp2*(a-x)) and (p < tmp2*(b-x)) and (abs(p) < abs(0.5*tmp2*dx_temp))): rat = p*1.0/tmp2 # if parabolic step is useful. u = x + rat if ((u-a) < tol2 or (b-u) < tol2): if xmid-x >= 0: rat = tol1 else: rat = -tol1 else: if (x>=xmid): deltax=a-x # if it's not do a golden section step else: deltax=b-x rat = _cg*deltax if (abs(rat) < tol1): # update by at least tol1 if rat >= 0: u = x + tol1 else: u = x - tol1 else: u = x + rat fu = apply(func, (u,)+args) # calculate new output value funcalls += 1 if (fu > fx): # if it's bigger than current if (u<x): a=u else: b=u if (fu<=fw) or (w==x): v=w; w=u; fv=fw; fw=fu elif (fu<=fv) or (v==x) or (v==w): v=u; fv=fu else: if (u >= x): a = x else: b = x v=w; w=x; x=u fv=fw; fw=fx; fx=fu xmin = x fval = fx if full_output: return xmin, fval, iter, funcalls else: return xmin
817
def golden(func, args=(), brack=None, tol=_epsilon, full_output=0): """ Given a function of one-variable and a possible bracketing interval, return the minimum of the function isolated to a fractional precision of tol. A bracketing interval is a triple (a,b,c) where (a<b<c) and func(b) < func(a),func(c). If bracket is two numbers then they are assumed to be a starting interval for a downhill bracket search (see bracket) Uses analog of bisection method to decrease the bracketed interval. """ if brack is None: xa,xb,xc,fa,fb,fc,funcalls = bracket(func, args=args) elif len(brack) == 2: xa,xb,xc,fa,fb,fc,funcalls = bracket(func, xa=brack[0], xb=brack[1], args=args) elif len(brack) == 3: xa,xb,xc = brack if (xa > xc): # swap so xa < xc can be assumed dum = xa; xa=xc; xc=dum assert ((xa < xb) and (xb < xc)), "Not a bracketing interval." fa = apply(func, (xa,)+args) fb = apply(func, (xb,)+args) fc = apply(func, (xc,)+args) assert ((fb<fa) and (fb < fc)), "Not a bracketing interval." funcalls = 3 else: raise ValuError, "Bracketing interval must be length 2 or 3 sequence." _gR = 0.61803399 _gC = 1.0-_gR x3 = xc x0 = xa if (abs(xc-xb) > abs(xb-xa)): x1 = xb x2 = xb + _gC*(xc-xb) else: x2 = xb x1 = xb - _gC*(xb-xa) f1 = apply(func, (x1,)+args) f2 = apply(func, (x2,)+args) funcalls += 2 while (abs(x3-x0) > tol*(abs(x1)+abs(x2))): if (f2 < f1): x0 = x1; x1 = x2; x2 = _gR*x1 + _gC*x3 f1 = f2; f2 = apply(func, (x2,)+args) else: x3 = x2; x2 = x1; x1 = _gR*x2 + _gC*x0 f2 = f1; f1 = apply(func, (x1,)+args) funcalls += 1 if (f1 < f2): xmin = x1 fval = f1 else: xmin = x2 fval = f2 if full_output: return xmin, fval, funcalls else: return xmin
def golden(func, args=(), brack=None, tol=_epsilon, full_output=0): """ Given a function of one-variable and a possible bracketing interval, return the minimum of the function isolated to a fractional precision of tol. A bracketing interval is a triple (a,b,c) where (a<b<c) and func(b) < func(a),func(c). If bracket is two numbers then they are assumed to be a starting interval for a downhill bracket search (see bracket) Uses analog of bisection method to decrease the bracketed interval. """ if brack is None: xa,xb,xc,fa,fb,fc,funcalls = bracket(func, args=args) elif len(brack) == 2: xa,xb,xc,fa,fb,fc,funcalls = bracket(func, xa=brack[0], xb=brack[1], args=args) elif len(brack) == 3: xa,xb,xc = brack if (xa > xc): # swap so xa < xc can be assumed dum = xa; xa=xc; xc=dum assert ((xa < xb) and (xb < xc)), "Not a bracketing interval." fa = apply(func, (xa,)+args) fb = apply(func, (xb,)+args) fc = apply(func, (xc,)+args) assert ((fb<fa) and (fb < fc)), "Not a bracketing interval." funcalls = 3 else: raise ValueError, "Bracketing interval must be length 2 or 3 sequence." _gR = 0.61803399 _gC = 1.0-_gR x3 = xc x0 = xa if (abs(xc-xb) > abs(xb-xa)): x1 = xb x2 = xb + _gC*(xc-xb) else: x2 = xb x1 = xb - _gC*(xb-xa) f1 = apply(func, (x1,)+args) f2 = apply(func, (x2,)+args) funcalls += 2 while (abs(x3-x0) > tol*(abs(x1)+abs(x2))): if (f2 < f1): x0 = x1; x1 = x2; x2 = _gR*x1 + _gC*x3 f1 = f2; f2 = apply(func, (x2,)+args) else: x3 = x2; x2 = x1; x1 = _gR*x2 + _gC*x0 f2 = f1; f1 = apply(func, (x1,)+args) funcalls += 1 if (f1 < f2): xmin = x1 fval = f1 else: xmin = x2 fval = f2 if full_output: return xmin, fval, funcalls else: return xmin
818
def bracket(func, xa=0.0, xb=1.0, args=(), grow_limit=110.0): """Given a function and distinct initial points, search in the downhill direction (as defined by the initital points) and return new points xa, xb, xc that bracket the minimum of the function: f(xa) > f(xb) < f(xc) """ _gold = 1.618034 _verysmall_num = 1e-21 fa = apply(func, (xa,)+args) fb = apply(func, (xb,)+args) if (fa < fb): # Switch so fa > fb dum = xa; xa = xb; xb = dum dum = fa; fa = fb; fb = dum xc = xb + _gold*(xb-xa) fc = apply(func, (xc,)+args) funcalls = 3 iter = 0 while (fc < fb): tmp1 = (xb - xa)*(fb-fc) tmp2 = (xb - xc)*(fb-fa) val = tmp2-tmp1 if abs(val) < _verysmall_num: denom = 2.0*_verysmall_num else: denom = 2.0*val w = xb - ((xb-xc)*tmp2-(xb-xa)*tmp1)/denom wlim = xb + grow_limit*(xc-xb) if iter > 1000: raise RunTimeError, "Too many iterations." if (w-xc)*(xb-w) > 0.0: fw = apply(func, (w,)+args) funcalls += 1 if (fw < fc): xa = xb; xb=w; fa=fb; fb=fw return xa, xb, xc, fa, fb, fc, funcalls elif (fw > fb): xc = w; fc=fw return xa, xb, xc, fa, fb, fc, funcalls w = xc + _gold*(xc-xb) fw = apply(func, (w,)+args) funcalls += 1 elif (w-wlim)*(wlim-xc) >= 0.0: w = wlim fw = apply(func, (w,)+args) funcalls += 1 elif (w-wlim)*(xc-w) > 0.0: fw = apply(func, (w,)+args) funcalls += 1 if (fw < fc): xb=xc; xc=w; w=xc+_gold*(xc-xb) fb=fc; fc=fw; fw=apply(func, (w,)+args) funcalls += 1 else: w = xc + _gold*(xc-xb) fw = apply(func, (w,)+args) funcalls += 1 xa=xb; xb=xc; xc=w fa=fb; fb=fc; fc=fw return xa, xb, xc, fa, fb, fc, funcalls
def bracket(func, xa=0.0, xb=1.0, args=(), grow_limit=110.0): """Given a function and distinct initial points, search in the downhill direction (as defined by the initital points) and return new points xa, xb, xc that bracket the minimum of the function: f(xa) > f(xb) < f(xc) """ _gold = 1.618034 _verysmall_num = 1e-21 fa = apply(func, (xa,)+args) fb = apply(func, (xb,)+args) if (fa < fb): # Switch so fa > fb dum = xa; xa = xb; xb = dum dum = fa; fa = fb; fb = dum xc = xb + _gold*(xb-xa) fc = apply(func, (xc,)+args) funcalls = 3 iter = 0 while (fc < fb): tmp1 = (xb - xa)*(fb-fc) tmp2 = (xb - xc)*(fb-fa) val = tmp2-tmp1 if abs(val) < _verysmall_num: denom = 2.0*_verysmall_num else: denom = 2.0*val w = xb - ((xb-xc)*tmp2-(xb-xa)*tmp1)/denom wlim = xb + grow_limit*(xc-xb) if iter > 1000: raise RuntimeError, "Too many iterations." if (w-xc)*(xb-w) > 0.0: fw = apply(func, (w,)+args) funcalls += 1 if (fw < fc): xa = xb; xb=w; fa=fb; fb=fw return xa, xb, xc, fa, fb, fc, funcalls elif (fw > fb): xc = w; fc=fw return xa, xb, xc, fa, fb, fc, funcalls w = xc + _gold*(xc-xb) fw = apply(func, (w,)+args) funcalls += 1 elif (w-wlim)*(wlim-xc) >= 0.0: w = wlim fw = apply(func, (w,)+args) funcalls += 1 elif (w-wlim)*(xc-w) > 0.0: fw = apply(func, (w,)+args) funcalls += 1 if (fw < fc): xb=xc; xc=w; w=xc+_gold*(xc-xb) fb=fc; fc=fw; fw=apply(func, (w,)+args) funcalls += 1 else: w = xc + _gold*(xc-xb) fw = apply(func, (w,)+args) funcalls += 1 xa=xb; xb=xc; xc=w fa=fb; fb=fc; fc=fw return xa, xb, xc, fa, fb, fc, funcalls
819
def check_exact(self): resdict = {(10,2):45L, (10,5):252L, (1000,20):339482811302457603895512614793686020778700L, (1000,975):47641862536236518640933948075167736642053976275040L, (-10,1):0L, (10,-1):0L, (-10,-3):0L,(10,11),0L} for key in resdict.keys(): assert_equal(comb(key[0],key[1],exact=1),resdict[key])
def check_exact(self): resdict = {(10,2):45L, (10,5):252L, (1000,20):339482811302457603895512614793686020778700L, (1000,975):47641862536236518640933948075167736642053976275040L, (-10,1):0L, (10,-1):0L, (-10,-3):0L,(10,11):0L} for key in resdict.keys(): assert_equal(comb(key[0],key[1],exact=1),resdict[key])
820
def getH(self): return self.transpose().conj() # csc = self.tocsc() # new = csc.transpose() # new.data = conj(new.data) # return new
def getH(self): return self.transpose().conj() # csc = self.tocsc() # new = csc.transpose() # new.data = conj(new.data) # return new
821
def dot(self, other): """ A generic interface for matrix-matrix or matrix-vector multiplication. Returns A.transpose().conj() * other or A.transpose() * other. """ M, K1 = self.shape try: K2, N = other.shape except (AttributeError, TypeError): # Not sparse or dense. Interpret it as a sequence. try: return self.matvec(asarray(other)) except: raise TypeError, "x.dot(y): y must be matrix, vector, or seq" except ValueError: # Assume it's a rank-1 array K2 = other.shape[0] N = 1 if N == 1: return self.matvec(other) else: if K1 != K2: raise ValueError, "dimension mismatch" return self.matmat(other)
def dot(self, other): """ A generic interface for matrix-matrix or matrix-vector multiplication. Returns A.transpose().conj() * other or A.transpose() * other. """ M, K1 = self.shape try: K2, N = other.shape except (AttributeError, TypeError): # Not sparse or dense. Interpret it as a sequence. try: return self.matvec(asarray(other)) except: raise TypeError, "x.dot(y): y must be matrix, vector, or seq" except ValueError: # Assume it's a rank-1 array K2 = other.shape[0] N = 1 if N == 1: return self.matvec(other) else: if K1 != K2: raise ValueError, "dimension mismatch" return self.matmat(other)
822
def save( self, file_name, format = '%d %d %f\n' ): try: fd = open( file_name, 'w' ) except Exception, e: raise e, file_name fd.write( '%d %d\n' % self.shape ) fd.write( '%d\n' % self.size ) for ii in xrange( self.size ): ir, ic = self.rowcol( ii ) data = self.getdata( ii ) fd.write( format % (ir, ic, data) ) fd.close()
def save(self, file_name, format = '%d %d %f\n'): try: fd = open( file_name, 'w' ) except Exception, e: raise e, file_name fd.write( '%d %d\n' % self.shape ) fd.write( '%d\n' % self.size ) for ii in xrange( self.size ): ir, ic = self.rowcol( ii ) data = self.getdata( ii ) fd.write( format % (ir, ic, data) ) fd.close()
823
def save( self, file_name, format = '%d %d %f\n' ): try: fd = open( file_name, 'w' ) except Exception, e: raise e, file_name fd.write( '%d %d\n' % self.shape ) fd.write( '%d\n' % self.size ) for ii in xrange( self.size ): ir, ic = self.rowcol( ii ) data = self.getdata( ii ) fd.write( format % (ir, ic, data) ) fd.close()
def save( self, file_name, format = '%d %d %f\n' ): try: fd = open(file_name, 'w') except Exception, e: raise e, file_name fd.write( '%d %d\n' % self.shape ) fd.write( '%d\n' % self.size ) for ii in xrange( self.size ): ir, ic = self.rowcol( ii ) data = self.getdata( ii ) fd.write( format % (ir, ic, data) ) fd.close()
824
def save( self, file_name, format = '%d %d %f\n' ): try: fd = open( file_name, 'w' ) except Exception, e: raise e, file_name fd.write( '%d %d\n' % self.shape ) fd.write( '%d\n' % self.size ) for ii in xrange( self.size ): ir, ic = self.rowcol( ii ) data = self.getdata( ii ) fd.write( format % (ir, ic, data) ) fd.close()
def save( self, file_name, format = '%d %d %f\n' ): try: fd = open( file_name, 'w' ) except Exception, e: raise e, file_name fd.write('%d %d\n' % self.shape) fd.write('%d\n' % self.size) for ii in xrange(self.size): ir, ic = self.rowcol(ii) data = self.getdata(ii) fd.write(format % (ir, ic, data)) fd.close()
825
def save( self, file_name, format = '%d %d %f\n' ): try: fd = open( file_name, 'w' ) except Exception, e: raise e, file_name fd.write( '%d %d\n' % self.shape ) fd.write( '%d\n' % self.size ) for ii in xrange( self.size ): ir, ic = self.rowcol( ii ) data = self.getdata( ii ) fd.write( format % (ir, ic, data) ) fd.close()
def save( self, file_name, format = '%d %d %f\n' ): try: fd = open( file_name, 'w' ) except Exception, e: raise e, file_name fd.write( '%d %d\n' % self.shape ) fd.write( '%d\n' % self.size ) for ii in xrange( self.size ): ir, ic = self.rowcol( ii ) data = self.getdata( ii ) fd.write( format % (ir, ic, data) ) fd.close()
826
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSC format if rank(arg1) == 2: s = asarray(arg1) if s.dtype.char not in 'fdFD': # Use a double array as the source (but leave it alone) s = s*1.0 if (rank(s) == 2): M, N = s.shape dtype = s.dtype.char func = getattr(sparsetools, _transtabl[dtype]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,), dtype) rowa = zeros((nnz,), 'i') ptra = zeros((N+1,), 'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz) self.data = a self.rowind = rowa self.indptr = ptra self.shape = (M, N) # s = dok_matrix(arg1).tocsc(nzmax) # self.shape = s.shape # self.data = s.data # self.rowind = s.rowind # self.indptr = s.indptr else: raise ValueError, "dense array does not have rank 1 or 2" elif isspmatrix(arg1): s = arg1 if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = arg1 M = int(M) # will raise TypeError if (data, ij) N = int(N) self.data = zeros((nzmax,), dtype) self.rowind = zeros((nzmax,), int) self.indptr = zeros((N+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: # Try interpreting it as (data, ij) (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) temp = coo_matrix( s, ij, dims=dims, nzmax=nzmax, \ dtype=dtype).tocsc() self.shape = temp.shape self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr except: try: # Try interpreting it as (data, rowind, indptr) (s, rowind, indptr) = arg1 if copy: self.data = array(s) self.rowind = array(rowind) self.indptr = array(indptr) else: self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csc_matrix constructor" else: raise ValueError, "unrecognized form for csc_matrix constructor"
def __init__(self, arg1, dims=None, nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSC format if rank(arg1) == 2: s = asarray(arg1) if s.dtype.char not in 'fdFD': # Use a double array as the source (but leave it alone) s = s*1.0 if (rank(s) == 2): M, N = s.shape dtype = s.dtype.char func = getattr(sparsetools, _transtabl[dtype]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,), dtype) rowa = zeros((nnz,), 'i') ptra = zeros((N+1,), 'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz) self.data = a self.rowind = rowa self.indptr = ptra self.shape = (M, N) # s = dok_matrix(arg1).tocsc(nzmax) # self.shape = s.shape # self.data = s.data # self.rowind = s.rowind # self.indptr = s.indptr else: raise ValueError, "dense array does not have rank 1 or 2" elif isspmatrix(arg1): s = arg1 if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = arg1 M = int(M) # will raise TypeError if (data, ij) N = int(N) self.data = zeros((nzmax,), dtype) self.rowind = zeros((nzmax,), int) self.indptr = zeros((N+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: # Try interpreting it as (data, ij) (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) temp = coo_matrix( s, ij, dims=dims, nzmax=nzmax, \ dtype=dtype).tocsc() self.shape = temp.shape self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr except: try: # Try interpreting it as (data, rowind, indptr) (s, rowind, indptr) = arg1 if copy: self.data = array(s) self.rowind = array(rowind) self.indptr = array(indptr) else: self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csc_matrix constructor" else: raise ValueError, "unrecognized form for csc_matrix constructor"
827
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSC format if rank(arg1) == 2: s = asarray(arg1) if s.dtype.char not in 'fdFD': # Use a double array as the source (but leave it alone) s = s*1.0 if (rank(s) == 2): M, N = s.shape dtype = s.dtype.char func = getattr(sparsetools, _transtabl[dtype]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,), dtype) rowa = zeros((nnz,), 'i') ptra = zeros((N+1,), 'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz) self.data = a self.rowind = rowa self.indptr = ptra self.shape = (M, N) # s = dok_matrix(arg1).tocsc(nzmax) # self.shape = s.shape # self.data = s.data # self.rowind = s.rowind # self.indptr = s.indptr else: raise ValueError, "dense array does not have rank 1 or 2" elif isspmatrix(arg1): s = arg1 if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = arg1 M = int(M) # will raise TypeError if (data, ij) N = int(N) self.data = zeros((nzmax,), dtype) self.rowind = zeros((nzmax,), int) self.indptr = zeros((N+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: # Try interpreting it as (data, ij) (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) temp = coo_matrix( s, ij, dims=dims, nzmax=nzmax, \ dtype=dtype).tocsc() self.shape = temp.shape self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr except: try: # Try interpreting it as (data, rowind, indptr) (s, rowind, indptr) = arg1 if copy: self.data = array(s) self.rowind = array(rowind) self.indptr = array(indptr) else: self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csc_matrix constructor" else: raise ValueError, "unrecognized form for csc_matrix constructor"
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSC format if rank(arg1) == 2: s = asarray(arg1) if s.dtype.char not in 'fdFD': # Use a double array as the source (but leave it alone) s = s*1.0 if (rank(s) == 2): M, N = s.shape dtype = s.dtype.char func = getattr(sparsetools, _transtabl[dtype]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,), dtype) rowa = zeros((nnz,), 'i') ptra = zeros((N+1,), 'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz) self.data = a self.rowind = rowa self.indptr = ptra self.shape = (M, N) # s = dok_matrix(arg1).tocsc(nzmax) # self.shape = s.shape # self.data = s.data # self.rowind = s.rowind # self.indptr = s.indptr else: raise ValueError, "dense array does not have rank 1 or 2" elif isspmatrix(arg1): s = arg1 if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = arg1 M = int(M) # will raise TypeError if (data, ij) N = int(N) self.data = zeros((nzmax,), dtype) self.rowind = zeros((nzmax,), int) self.indptr = zeros((N+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: # Try interpreting it as (data, ij) (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) temp = coo_matrix( s, ij, dims=dims, nzmax=nzmax, \ dtype=dtype).tocsc() self.shape = temp.shape self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr except: try: # Try interpreting it as (data, rowind, indptr) (s, rowind, indptr) = arg1 if copy: self.data = array(s) self.rowind = array(rowind) self.indptr = array(indptr) else: self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csc_matrix constructor" else: raise ValueError, "unrecognized form for csc_matrix constructor"
828
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSC format if rank(arg1) == 2: s = asarray(arg1) if s.dtype.char not in 'fdFD': # Use a double array as the source (but leave it alone) s = s*1.0 if (rank(s) == 2): M, N = s.shape dtype = s.dtype.char func = getattr(sparsetools, _transtabl[dtype]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,), dtype) rowa = zeros((nnz,), 'i') ptra = zeros((N+1,), 'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz) self.data = a self.rowind = rowa self.indptr = ptra self.shape = (M, N) # s = dok_matrix(arg1).tocsc(nzmax) # self.shape = s.shape # self.data = s.data # self.rowind = s.rowind # self.indptr = s.indptr else: raise ValueError, "dense array does not have rank 1 or 2" elif isspmatrix(arg1): s = arg1 if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = arg1 M = int(M) # will raise TypeError if (data, ij) N = int(N) self.data = zeros((nzmax,), dtype) self.rowind = zeros((nzmax,), int) self.indptr = zeros((N+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: # Try interpreting it as (data, ij) (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) temp = coo_matrix( s, ij, dims=dims, nzmax=nzmax, \ dtype=dtype).tocsc() self.shape = temp.shape self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr except: try: # Try interpreting it as (data, rowind, indptr) (s, rowind, indptr) = arg1 if copy: self.data = array(s) self.rowind = array(rowind) self.indptr = array(indptr) else: self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csc_matrix constructor" else: raise ValueError, "unrecognized form for csc_matrix constructor"
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSC format if rank(arg1) == 2: s = arg1 if s.dtype.char not in 'fdFD': # Use a double array as the source (but leave it alone) s = s*1.0 if (rank(s) == 2): M, N = s.shape dtype = s.dtype.char func = getattr(sparsetools, _transtabl[dtype]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,), dtype) rowa = zeros((nnz,), 'i') ptra = zeros((N+1,), 'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz) self.data = a self.rowind = rowa self.indptr = ptra self.shape = (M, N) # s = dok_matrix(arg1).tocsc(nzmax) # self.shape = s.shape # self.data = s.data # self.rowind = s.rowind # self.indptr = s.indptr else: raise ValueError, "dense array does not have rank 1 or 2" elif isspmatrix(arg1): s = arg1 if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = arg1 M = int(M) # will raise TypeError if (data, ij) N = int(N) self.data = zeros((nzmax,), dtype) self.rowind = zeros((nzmax,), int) self.indptr = zeros((N+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: # Try interpreting it as (data, ij) (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) temp = coo_matrix( s, ij, dims=dims, nzmax=nzmax, \ dtype=dtype).tocsc() self.shape = temp.shape self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr except: try: # Try interpreting it as (data, rowind, indptr) (s, rowind, indptr) = arg1 if copy: self.data = array(s) self.rowind = array(rowind) self.indptr = array(indptr) else: self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csc_matrix constructor" else: raise ValueError, "unrecognized form for csc_matrix constructor"
829
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSC format if rank(arg1) == 2: s = asarray(arg1) if s.dtype.char not in 'fdFD': # Use a double array as the source (but leave it alone) s = s*1.0 if (rank(s) == 2): M, N = s.shape dtype = s.dtype.char func = getattr(sparsetools, _transtabl[dtype]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,), dtype) rowa = zeros((nnz,), 'i') ptra = zeros((N+1,), 'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz) self.data = a self.rowind = rowa self.indptr = ptra self.shape = (M, N) # s = dok_matrix(arg1).tocsc(nzmax) # self.shape = s.shape # self.data = s.data # self.rowind = s.rowind # self.indptr = s.indptr else: raise ValueError, "dense array does not have rank 1 or 2" elif isspmatrix(arg1): s = arg1 if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = arg1 M = int(M) # will raise TypeError if (data, ij) N = int(N) self.data = zeros((nzmax,), dtype) self.rowind = zeros((nzmax,), int) self.indptr = zeros((N+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: # Try interpreting it as (data, ij) (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) temp = coo_matrix( s, ij, dims=dims, nzmax=nzmax, \ dtype=dtype).tocsc() self.shape = temp.shape self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr except: try: # Try interpreting it as (data, rowind, indptr) (s, rowind, indptr) = arg1 if copy: self.data = array(s) self.rowind = array(rowind) self.indptr = array(indptr) else: self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csc_matrix constructor" else: raise ValueError, "unrecognized form for csc_matrix constructor"
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSC format if rank(arg1) == 2: s = asarray(arg1) if s.dtype.char not in 'fdFD': # Use a double array as the source (but leave it alone) s = s*1.0 if (rank(s) == 2): M, N = s.shape dtype = s.dtype func = getattr(sparsetools, _transtabl[dtype.char]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,), dtype) rowa = zeros((nnz,), 'i') ptra = zeros((N+1,), 'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz) self.data = a self.rowind = rowa self.indptr = ptra self.shape = (M, N) # s = dok_matrix(arg1).tocsc(nzmax) # self.shape = s.shape # self.data = s.data # self.rowind = s.rowind # self.indptr = s.indptr else: raise ValueError, "dense array does not have rank 1 or 2" elif isspmatrix(arg1): s = arg1 if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = arg1 M = int(M) # will raise TypeError if (data, ij) N = int(N) self.data = zeros((nzmax,), dtype) self.rowind = zeros((nzmax,), int) self.indptr = zeros((N+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: # Try interpreting it as (data, ij) (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) temp = coo_matrix( s, ij, dims=dims, nzmax=nzmax, \ dtype=dtype).tocsc() self.shape = temp.shape self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr except: try: # Try interpreting it as (data, rowind, indptr) (s, rowind, indptr) = arg1 if copy: self.data = array(s) self.rowind = array(rowind) self.indptr = array(indptr) else: self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csc_matrix constructor" else: raise ValueError, "unrecognized form for csc_matrix constructor"
830
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSC format if rank(arg1) == 2: s = asarray(arg1) if s.dtype.char not in 'fdFD': # Use a double array as the source (but leave it alone) s = s*1.0 if (rank(s) == 2): M, N = s.shape dtype = s.dtype.char func = getattr(sparsetools, _transtabl[dtype]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,), dtype) rowa = zeros((nnz,), 'i') ptra = zeros((N+1,), 'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz) self.data = a self.rowind = rowa self.indptr = ptra self.shape = (M, N) # s = dok_matrix(arg1).tocsc(nzmax) # self.shape = s.shape # self.data = s.data # self.rowind = s.rowind # self.indptr = s.indptr else: raise ValueError, "dense array does not have rank 1 or 2" elif isspmatrix(arg1): s = arg1 if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = arg1 M = int(M) # will raise TypeError if (data, ij) N = int(N) self.data = zeros((nzmax,), dtype) self.rowind = zeros((nzmax,), int) self.indptr = zeros((N+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: # Try interpreting it as (data, ij) (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) temp = coo_matrix( s, ij, dims=dims, nzmax=nzmax, \ dtype=dtype).tocsc() self.shape = temp.shape self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr except: try: # Try interpreting it as (data, rowind, indptr) (s, rowind, indptr) = arg1 if copy: self.data = array(s) self.rowind = array(rowind) self.indptr = array(indptr) else: self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csc_matrix constructor" else: raise ValueError, "unrecognized form for csc_matrix constructor"
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSC format if rank(arg1) == 2: s = asarray(arg1) if s.dtype.char not in 'fdFD': # Use a double array as the source (but leave it alone) s = s*1.0 if (rank(s) == 2): M, N = s.shape dtype = s.dtype.char func = getattr(sparsetools, _transtabl[dtype]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,), dtype) rowa = zeros((nnz,), 'i') ptra = zeros((N+1,), 'i') while 1: a, rowa, ptra, irow, jcol, ierr = \ func(s, a, rowa, ptra, irow, jcol, ierr) if (ierr == 0): break nnz = nnz + ALLOCSIZE a = resize1d(a, nnz) rowa = resize1d(rowa, nnz) self.data = a self.rowind = rowa self.indptr = ptra self.shape = (M, N) # s = dok_matrix(arg1).tocsc(nzmax) # self.shape = s.shape # self.data = s.data # self.rowind = s.rowind # self.indptr = s.indptr else: raise ValueError, "dense array does not have rank 1 or 2" elif isspmatrix(arg1): s = arg1 if isinstance(s, csc_matrix): # do nothing but copy information self.shape = s.shape if copy: self.data = s.data.copy() self.rowind = s.rowind.copy() self.indptr = s.indptr.copy() else: self.data = s.data self.rowind = s.rowind self.indptr = s.indptr elif isinstance(s, csr_matrix): self.shape = s.shape func = getattr(sparsetools, s.ftype+'transp') self.data, self.rowind, self.indptr = \ func(s.shape[1], s.data, s.colind, s.indptr) else: temp = s.tocsc() self.data = temp.data self.rowind = temp.rowind self.indptr = temp.indptr self.shape = temp.shape elif type(arg1) == tuple: try: # Assume it's a tuple of matrix dimensions (M, N) (M, N) = arg1 M = int(M) # will raise TypeError if (data, ij) N = int(N) self.data = zeros((nzmax,), dtype) self.rowind = zeros((nzmax,), int) self.indptr = zeros((N+1,), int) self.shape = (M, N) except (ValueError, TypeError): try: # Try interpreting it as (data, ij) (s, ij) = arg1 assert isinstance(ij, ArrayType) and (rank(ij) == 2) and (shape(ij) == (len(s), 2)) except (AssertionError, TypeError, ValueError): try: # Try interpreting it as (data, rowind, indptr) (s, rowind, indptr) = arg1 if copy: self.data = array(s) self.rowind = array(rowind) self.indptr = array(indptr) else: self.data = asarray(s) self.rowind = asarray(rowind) self.indptr = asarray(indptr) except: raise ValueError, "unrecognized form for csc_matrix constructor" else: raise ValueError, "unrecognized form for csc_matrix constructor"
831
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data = other * new.data new.dtype = new.data.dtype new.ftype = _transtabl[new.dtype.char] return new else: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data = other * new.data new.dtype = new.data.dtype new.ftype = _transtabl[new.dtype.char] return new else: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
832
def matvec(self, other): if isdense(other): if (rank(other) != 1) or (len(other) != self.shape[1]): raise ValueError, "dimension mismatch" func = getattr(sparsetools, self.ftype+'cscmux') y = func(self.data, self.rowind, self.indptr, other, self.shape[0]) return y elif isspmatrix(other): raise NotImplementedError, "use matmat() for sparse * sparse" else: raise TypeError, "need a dense vector"
def matvec(self, other): if isdense(other): func = getattr(sparsetools, self.ftype+'cscmux') y = func(self.data, self.rowind, self.indptr, other, self.shape[0]) return y elif isspmatrix(other): raise NotImplementedError, "use matmat() for sparse * sparse" else: raise TypeError, "need a dense vector"
833
def rmatvec(self, other, conjugate=True): if isdense(other): if (rank(other) != 1) or (len(other) != self.shape[0]): raise ValueError, "dimension mismatch" func = getattr(sparsetools, self.ftype+'csrmux') if conjugate: cd = conj(self.data) else: cd = self.data y = func(cd, self.rowind, self.indptr, other) return y elif isspmatrix(other): raise NotImplementedError, "use matmat() for sparse * sparse" else: raise TypeError, "need a dense vector"
def rmatvec(self, other, conjugate=True): if isdense(other): func = getattr(sparsetools, self.ftype+'csrmux') if conjugate: cd = conj(self.data) else: cd = self.data y = func(cd, self.rowind, self.indptr, other) return y elif isspmatrix(other): raise NotImplementedError, "use matmat() for sparse * sparse" else: raise TypeError, "need a dense vector"
834
def matmat(self, other): if isspmatrix(other): M, K1 = self.shape K2, N = other.shape if (K1 != K2): raise ValueError, "shape mismatch error" a, rowa, ptra = self.data, self.rowind, self.indptr if isinstance(other, csr_matrix): other._check() dtypechar = _coerce_rules[(self.dtype.char, other.dtype.char)] ftype = _transtabl[dtypechar] func = getattr(sparsetools, ftype+'cscmucsr') b = other.data rowb = other.colind ptrb = other.indptr elif isinstance(other, csc_matrix): other._check() dtypechar = _coerce_rules[(self.dtype.char, other.dtype.char)] ftype = _transtabl[dtypechar] func = getattr(sparsetools, ftype+'cscmucsc') b = other.data rowb = other.rowind ptrb = other.indptr else: other = other.tocsc() dtypechar = _coerce_rules[(self.dtype.char, other.dtype.char)] ftype = _transtabl[dtypechar] func = getattr(sparsetools, ftype+'cscmucsc') b = other.data rowb = other.rowind ptrb = other.indptr a, b = _convert_data(a, b, dtypechar) newshape = (M, N) ptrc = zeros((N+1,), 'i') nnzc = 2*max(ptra[-1], ptrb[-1]) c = zeros((nnzc,), dtypechar) rowc = zeros((nnzc,), 'i') ierr = irow = kcol = 0 while 1: c, rowc, ptrc, irow, kcol, ierr = func(M, a, rowa, ptra, b, rowb, ptrb, c, rowc, ptrc, irow, kcol, ierr) if (ierr==0): break # otherwise we were too small and must resize # calculations continue where they left off... percent_to_go = 1- (1.0*kcol) / N newnnzc = int(ceil((1+percent_to_go)*nnzc)) c = resize1d(c, newnnzc) rowc = resize1d(rowc, newnnzc) nnzc = newnnzc return csc_matrix((c, rowc, ptrc), dims=(M, N)) elif isdense(other): # This is SLOW! We need a more efficient implementation # of sparse * dense matrix multiplication! return self.matmat(csc_matrix(other)) else: raise TypeError, "need a dense or sparse matrix"
def matmat(self, other): if isspmatrix(other): M, K1 = self.shape K2, N = other.shape if (K1 != K2): raise ValueError, "shape mismatch error" a, rowa, ptra = self.data, self.rowind, self.indptr if isinstance(other, csr_matrix): other._check() dtypechar = _coerce_rules[(self.dtype.char, other.dtype.char)] ftype = _transtabl[dtypechar] func = getattr(sparsetools, ftype+'cscmucsr') b = other.data rowb = other.colind ptrb = other.indptr elif isinstance(other, csc_matrix): other._check() dtypechar = _coerce_rules[(self.dtype.char, other.dtype.char)] ftype = _transtabl[dtypechar] func = getattr(sparsetools, ftype+'cscmucsc') b = other.data rowb = other.rowind ptrb = other.indptr else: other = other.tocsc() dtypechar = _coerce_rules[(self.dtype.char, other.dtype.char)] ftype = _transtabl[dtypechar] func = getattr(sparsetools, ftype+'cscmucsc') b = other.data rowb = other.rowind ptrb = other.indptr a, b = _convert_data(a, b, dtypechar) newshape = (M, N) ptrc = zeros((N+1,), 'i') nnzc = 2*max(ptra[-1], ptrb[-1]) c = zeros((nnzc,), dtypechar) rowc = zeros((nnzc,), 'i') ierr = irow = kcol = 0 while 1: c, rowc, ptrc, irow, kcol, ierr = func(M, a, rowa, ptra, b, rowb, ptrb, c, rowc, ptrc, irow, kcol, ierr) if (ierr==0): break # otherwise we were too small and must resize # calculations continue where they left off... percent_to_go = 1- (1.0*kcol) / N newnnzc = int(ceil((1+percent_to_go)*nnzc)) c = resize1d(c, newnnzc) rowc = resize1d(rowc, newnnzc) nnzc = newnnzc return csc_matrix((c, rowc, ptrc), dims=(M, N)) elif isdense(other): # This is SLOW! We need a more efficient implementation # of sparse * dense matrix multiplication! return self.matmat(csc_matrix(other)) else: raise TypeError, "need a dense or sparse matrix"
835
def __getitem__(self, key): if isinstance(key, types.TupleType): row = key[0] col = key[1] func = getattr(sparsetools, self.ftype+'cscgetel') M, N = self.shape if not (0<=row<M) or not (0<=col<N): raise KeyError, "index out of bounds" ind, val = func(self.data, self.rowind, self.indptr, row, col) return val #elif isinstance(key, type(3)): elif type(key) == int: return self.data[key] else: raise NotImplementedError
def __getitem__(self, key): if isinstance(key, types.TupleType): row = key[0] col = key[1] func = getattr(sparsetools, self.ftype+'cscgetel') M, N = self.shape if not (0<=row<M) or not (0<=col<N): raise IndexError, "index out of bounds" ind, val = func(self.data, self.rowind, self.indptr, row, col) return val #elif isinstance(key, type(3)): elif type(key) == int: return self.data[key] else: raise NotImplementedError
836
def __setitem__(self, key, val): if isinstance(key, types.TupleType): row = key[0] col = key[1] func = getattr(sparsetools, self.ftype+'cscsetel') M, N = self.shape if (row < 0): row = M + row if (col < 0): col = N + col if (row < 0) or (col < 0): raise IndexError, "index out of bounds" if (col >= N): self.indptr = resize1d(self.indptr, col+2) self.indptr[N+1:] = self.indptr[N] N = col+1 if (row >= M): M = row+1 self.shape = (M, N) nzmax = self.nzmax if (nzmax < self.nnz+1): # need more room alloc = max(1, self.allocsize) self.data = resize1d(self.data, nzmax + alloc) self.rowind = resize1d(self.rowind, nzmax + alloc) func(self.data, self.rowind, self.indptr, row, col, val) self._check() elif isinstance(key, types.IntType): if (key < self.nnz): self.data[key] = val else: raise KeyError, "key out of bounds" else: raise NotImplementedError
def __setitem__(self, key, val): if isinstance(key, types.TupleType): row = key[0] col = key[1] func = getattr(sparsetools, self.ftype+'cscsetel') M, N = self.shape if (row < 0): row = M + row if (col < 0): col = N + col if (row < 0) or (col < 0): raise IndexError, "index out of bounds" if (col >= N): self.indptr = resize1d(self.indptr, col+2) self.indptr[N+1:] = self.indptr[N] N = col+1 if (row >= M): M = row+1 self.shape = (M, N) nzmax = self.nzmax if (nzmax < self.nnz+1): # need more room alloc = max(1, self.allocsize) self.data = resize1d(self.data, nzmax + alloc) self.rowind = resize1d(self.rowind, nzmax + alloc) func(self.data, self.rowind, self.indptr, row, col, val) self._check() elif isinstance(key, types.IntType): if (key < self.nnz): self.data[key] = val else: raise IndexError, "index out of bounds" else: raise NotImplementedError
837
def copy(self): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtype) new.data = self.data.copy() new.rowind = self.rowind.copy() new.indptr = self.indptr.copy() new._check() return new
def copy(self): new = csc_matrix(self.shape, nzmax=self.nzmax, dtype=self.dtype) new.data = self.data.copy() new.rowind = self.rowind.copy() new.indptr = self.indptr.copy() new._check() return new
838
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSR format if rank(arg1) == 2: s = asarray(arg1) ocsc = csc_matrix(transpose(s)) self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data self.shape = (ocsc.shape[1], ocsc.shape[0])
def __init__(self, arg1, dims=None, nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSR format if rank(arg1) == 2: s = asarray(arg1) ocsc = csc_matrix(transpose(s)) self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data self.shape = (ocsc.shape[1], ocsc.shape[0])
839
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSR format if rank(arg1) == 2: s = asarray(arg1) ocsc = csc_matrix(transpose(s)) self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data self.shape = (ocsc.shape[1], ocsc.shape[0])
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSR format if rank(arg1) == 2: s = asarray(arg1) ocsc = csc_matrix(transpose(s)) self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data self.shape = (ocsc.shape[1], ocsc.shape[0])
840
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSR format if rank(arg1) == 2: s = asarray(arg1) ocsc = csc_matrix(transpose(s)) self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data self.shape = (ocsc.shape[1], ocsc.shape[0])
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSR format if rank(arg1) == 2: s = arg1 ocsc = csc_matrix(transpose(s)) self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data self.shape = (ocsc.shape[1], ocsc.shape[0])
841
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSR format if rank(arg1) == 2: s = asarray(arg1) ocsc = csc_matrix(transpose(s)) self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data self.shape = (ocsc.shape[1], ocsc.shape[0])
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False): spmatrix.__init__(self) if isdense(arg1): # Convert the dense matrix arg1 to CSR format if rank(arg1) == 2: s = asarray(arg1) ocsc = csc_matrix(transpose(s)) self.colind = ocsc.rowind self.indptr = ocsc.indptr self.data = ocsc.data self.shape = (ocsc.shape[1], ocsc.shape[0])
842
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): # Now we would add this scalar to every element. raise NotImplementedError, 'adding a scalar to a sparse matrix ' \ 'is not yet supported' elif isspmatrix(other): ocs = other.tocsr() if (ocs.shape != self.shape): raise ValueError, "inconsistent shapes"
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): # Now we would add this scalar to every element. raise NotImplementedError, 'adding a scalar to a CSR matrix ' \ 'is not yet supported' elif isspmatrix(other): ocs = other.tocsr() if (ocs.shape != self.shape): raise ValueError, "inconsistent shapes"
843
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data = other * new.data # allows type conversion new.dtype = new.data.dtype new.ftype = _transtabl[new.dtype.char] return new else: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = self.copy() new.data = other * new.data # allows type conversion new.dtype = new.data.dtype new.ftype = _transtabl[new.dtype.char] return new else: try: tr = other.transpose() except AttributeError: tr = asarray(other).transpose() return self.transpose().dot(tr).transpose()
844
def matvec(self, other): if (rank(other) != 1) or (len(other) != self.shape[1]): raise ValueError, "dimension mismatch" func = getattr(sparsetools, self.ftype+'csrmux') y = func(self.data, self.colind, self.indptr, other) return y
def matvec(self, other): if (rank(other) != 1) or (len(other) != self.shape[1]): raise ValueError, "dimension mismatch" func = getattr(sparsetools, self.ftype+'csrmux') y = func(self.data, self.colind, self.indptr, other) return y
845
def rmatvec(self, other, conjugate=True): if (rank(other) != 1) or (len(other) != self.shape[0]): raise ValueError, "dimension mismatch" func = getattr(sparsetools, self.ftype+'cscmux') if conjugate: cd = conj(self.data) else: cd = self.data y = func(cd, self.colind, self.indptr, other, self.shape[1]) return y
def rmatvec(self, other, conjugate=True): func = getattr(sparsetools, self.ftype+'cscmux') if conjugate: cd = conj(self.data) else: cd = self.data y = func(cd, self.colind, self.indptr, other, self.shape[1]) return y
846
def __setitem__(self, key, val): if isinstance(key, types.TupleType): row = key[0] col = key[1] func = getattr(sparsetools, self.ftype+'cscsetel') M, N = self.shape if (row < 0): row = M + row if (col < 0): col = N + col if (row < 0) or (col < 0): raise KeyError, "index out of bounds" if (row >= M): self.indptr = resize1d(self.indptr, row+2) self.indptr[M+1:] = self.indptr[M] M = row+1 elif (row < 0): row = M - row if (col >= N): N = col+1 elif (col < 0): col = N - col self.shape = (M, N) nzmax = self.nzmax if (nzmax < self.nnz+1): # need more room alloc = max(1, self.allocsize) self.data = resize1d(self.data, nzmax + alloc) self.colind = resize1d(self.colind, nzmax + alloc) func(self.data, self.colind, self.indptr, col, row, val) self._check() elif isinstance(key, types.IntType): if (key < self.nnz): self.data[key] = val else: raise KeyError, "key out of bounds" else: raise NotImplementedError
def __setitem__(self, key, val): if isinstance(key, types.TupleType): row = key[0] col = key[1] func = getattr(sparsetools, self.ftype+'cscsetel') M, N = self.shape if (row < 0): row = M + row if (col < 0): col = N + col if (row < 0) or (col < 0): raise IndexError, "index out of bounds" if (row >= M): self.indptr = resize1d(self.indptr, row+2) self.indptr[M+1:] = self.indptr[M] M = row+1 elif (row < 0): row = M - row if (col >= N): N = col+1 elif (col < 0): col = N - col self.shape = (M, N) nzmax = self.nzmax if (nzmax < self.nnz+1): # need more room alloc = max(1, self.allocsize) self.data = resize1d(self.data, nzmax + alloc) self.colind = resize1d(self.colind, nzmax + alloc) func(self.data, self.colind, self.indptr, col, row, val) self._check() elif isinstance(key, types.IntType): if (key < self.nnz): self.data[key] = val else: raise KeyError, "key out of bounds" else: raise NotImplementedError
847
def __setitem__(self, key, val): if isinstance(key, types.TupleType): row = key[0] col = key[1] func = getattr(sparsetools, self.ftype+'cscsetel') M, N = self.shape if (row < 0): row = M + row if (col < 0): col = N + col if (row < 0) or (col < 0): raise KeyError, "index out of bounds" if (row >= M): self.indptr = resize1d(self.indptr, row+2) self.indptr[M+1:] = self.indptr[M] M = row+1 elif (row < 0): row = M - row if (col >= N): N = col+1 elif (col < 0): col = N - col self.shape = (M, N) nzmax = self.nzmax if (nzmax < self.nnz+1): # need more room alloc = max(1, self.allocsize) self.data = resize1d(self.data, nzmax + alloc) self.colind = resize1d(self.colind, nzmax + alloc) func(self.data, self.colind, self.indptr, col, row, val) self._check() elif isinstance(key, types.IntType): if (key < self.nnz): self.data[key] = val else: raise KeyError, "key out of bounds" else: raise NotImplementedError
def __setitem__(self, key, val): if isinstance(key, types.TupleType): row = key[0] col = key[1] func = getattr(sparsetools, self.ftype+'cscsetel') M, N = self.shape if (row < 0): row = M + row if (col < 0): col = N + col if (row < 0) or (col < 0): raise KeyError, "index out of bounds" if (row >= M): self.indptr = resize1d(self.indptr, row+2) self.indptr[M+1:] = self.indptr[M] M = row+1 elif (row < 0): row = M - row if (col >= N): N = col+1 elif (col < 0): col = N - col self.shape = (M, N) nzmax = self.nzmax if (nzmax < self.nnz+1): # need more room alloc = max(1, self.allocsize) self.data = resize1d(self.data, nzmax + alloc) self.colind = resize1d(self.colind, nzmax + alloc) func(self.data, self.colind, self.indptr, col, row, val) self._check() elif isinstance(key, types.IntType): if (key < self.nnz): self.data[key] = val else: raise IndexError, "index out of bounds" else: raise NotImplementedError
848
# def csc_cmp(x, y):
# def csc_cmp(x, y):
849
def __init__(self, A=None): """ Create a new dictionary-of-keys sparse matrix. An optional argument A is accepted, which initializes the dok_matrix with it. This can be a tuple of dimensions (m, n) or a (dense) array to copy. """ dict.__init__(self) spmatrix.__init__(self) self.shape = (0, 0) # If _validate is True, ensure __setitem__ keys are integer tuples self._validate = True if A is not None: if type(A) == tuple: # Interpret as dimensions try: dims = A (M, N) = dims assert M == int(M) and M > 0 assert N == int(N) and N > 0 self.shape = (int(M), int(N)) return except (TypeError, ValueError, AssertionError): raise TypeError, "dimensions must be a 2-tuple of positive"\ " integers" if isspmatrix(A): # For sparse matrices, this is too inefficient; we need # something else. raise NotImplementedError, "initializing a dok_matrix with " \ "a sparse matrix is not yet supported" elif isdense(A): A = asarray(A) if rank(A) == 2: M, N = A.shape self.shape = (M, N) for i in range(M): for j in range(N): if A[i, j] != 0: self[i, j] = A[i, j] elif rank(A) == 1: M = A.shape[0] self.shape = (M, 1) for i in range(M): if A[i] != 0: self[i, 0] = A[i] else: raise TypeError, "array for initialization must have rank 2" else: raise TypeError, "argument should be a tuple of dimensions " \ "or a sparse or dense matrix"
def __init__(self, A=None, dtype='d'): """ Create a new dictionary-of-keys sparse matrix. An optional argument A is accepted, which initializes the dok_matrix with it. This can be a tuple of dimensions (m, n) or a (dense) array to copy. """ dict.__init__(self) spmatrix.__init__(self) self.shape = (0, 0) # If _validate is True, ensure __setitem__ keys are integer tuples self._validate = True if A is not None: if type(A) == tuple: # Interpret as dimensions try: dims = A (M, N) = dims assert M == int(M) and M > 0 assert N == int(N) and N > 0 self.shape = (int(M), int(N)) return except (TypeError, ValueError, AssertionError): raise TypeError, "dimensions must be a 2-tuple of positive"\ " integers" if isspmatrix(A): # For sparse matrices, this is too inefficient; we need # something else. raise NotImplementedError, "initializing a dok_matrix with " \ "a sparse matrix is not yet supported" elif isdense(A): A = asarray(A) if rank(A) == 2: M, N = A.shape self.shape = (M, N) for i in range(M): for j in range(N): if A[i, j] != 0: self[i, j] = A[i, j] elif rank(A) == 1: M = A.shape[0] self.shape = (M, 1) for i in range(M): if A[i] != 0: self[i, 0] = A[i] else: raise TypeError, "array for initialization must have rank 2" else: raise TypeError, "argument should be a tuple of dimensions " \ "or a sparse or dense matrix"
850
def __init__(self, A=None): """ Create a new dictionary-of-keys sparse matrix. An optional argument A is accepted, which initializes the dok_matrix with it. This can be a tuple of dimensions (m, n) or a (dense) array to copy. """ dict.__init__(self) spmatrix.__init__(self) self.shape = (0, 0) # If _validate is True, ensure __setitem__ keys are integer tuples self._validate = True if A is not None: if type(A) == tuple: # Interpret as dimensions try: dims = A (M, N) = dims assert M == int(M) and M > 0 assert N == int(N) and N > 0 self.shape = (int(M), int(N)) return except (TypeError, ValueError, AssertionError): raise TypeError, "dimensions must be a 2-tuple of positive"\ " integers" if isspmatrix(A): # For sparse matrices, this is too inefficient; we need # something else. raise NotImplementedError, "initializing a dok_matrix with " \ "a sparse matrix is not yet supported" elif isdense(A): A = asarray(A) if rank(A) == 2: M, N = A.shape self.shape = (M, N) for i in range(M): for j in range(N): if A[i, j] != 0: self[i, j] = A[i, j] elif rank(A) == 1: M = A.shape[0] self.shape = (M, 1) for i in range(M): if A[i] != 0: self[i, 0] = A[i] else: raise TypeError, "array for initialization must have rank 2" else: raise TypeError, "argument should be a tuple of dimensions " \ "or a sparse or dense matrix"
def __init__(self, A=None): """ Create a new dictionary-of-keys sparse matrix. An optional argument A is accepted, which initializes the dok_matrix with it. This can be a tuple of dimensions (m, n) or a (dense) array to copy. """ dict.__init__(self) spmatrix.__init__(self) self.shape = (0, 0) # If _validate is True, ensure __setitem__ keys are integer tuples self._validate = True if A is not None: if type(A) == tuple: # Interpret as dimensions try: dims = A (M, N) = dims assert M == int(M) and M > 0 assert N == int(N) and N > 0 self.shape = (int(M), int(N)) return except (TypeError, ValueError, AssertionError): raise TypeError, "dimensions must be a 2-tuple of positive"\ " integers" if isspmatrix(A): # For sparse matrices, this is too inefficient; we need # something else. raise NotImplementedError, "initializing a dok_matrix with " \ "a sparse matrix is not yet supported" elif isdense(A): if rank(A) == 2: M, N = A.shape self.shape = (M, N) for i in range(M): for j in range(N): if A[i, j] != 0: self[i, j] = A[i, j] elif rank(A) == 1: M = A.shape[0] self.shape = (M, 1) for i in range(M): if A[i] != 0: self[i, 0] = A[i] else: raise TypeError, "array for initialization must have rank 2" else: raise TypeError, "argument should be a tuple of dimensions " \ "or a sparse or dense matrix"
851
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = self.todense() + other return new
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix(self.shape, dtype=self.dtype) # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix(self.shape, dtype=self.dtype) new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = self.todense() + other return new
852
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = self.todense() + other return new
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix(self.shape, dtype=self.dtype) # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix(self.shape, dtype=self.dtype) new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = self.todense() + other return new
853
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = self.todense() + other return new
def __add__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) for key in other: new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = self.todense() + other return new
854
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix(self.shape, dtype=self.dtype) # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix(self.shape, dtype=self.dtype) new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
855
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
def__radd__(self,other):#Firstcheckifargumentisascalarifisscalar(other)or(isdense(other)andrank(other)==0):new=dok_matrix()#Addthisscalartoeveryelement.M,N=self.shapeforiinrange(M):forjinrange(N):aij=self.get((i,j),0)+otherifaij!=0:new[i,j]=aij#new.dtype.char=self.dtype.charelifisinstance(other,dok_matrix):new=dok_matrix()new.update(self)new.shape=self.shapeforkeyinother.keys():new[key]+=other[key]elifisspmatrix(other):csc=self.tocsc()new=csc+otherelse:#Perhapsit'sadensematrix?new=other+self.todense()returnnew
856
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix(self.shape, dtype=self.dtype) # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix(self.shape, dtype=self.dtype) new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
857
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other: new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
858
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
def __radd__(self, other): # First check if argument is a scalar if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Add this scalar to every element. M, N = self.shape for i in range(M): for j in range(N): aij = self.get((i, j), 0) + other if aij != 0: new[i, j] = aij #new.dtype.char = self.dtype.char elif isinstance(other, dok_matrix): new = dok_matrix() new.update(self) new.shape = self.shape for key in other.keys(): new[key] += other[key] elif isspmatrix(other): csc = self.tocsc() new = csc + other else: # Perhaps it's a dense matrix? new = other + self.todense() return new
859
def __neg__(self): new = dok_matrix() for key in self.keys(): new[key] = -self[key] return new
def __neg__(self): new = dok_matrix(self.shape, dtype=self.dtype) for key in self: new[key] = -self[key] return new
860
def __mul__(self, other): # self * other if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = val * other #new.dtype.char = self.dtype.char return new else: return self.dot(other)
def __mul__(self, other): # self * other if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix(self.shape, dtype=self.dtype) # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = val * other #new.dtype.char = self.dtype.char return new else: return self.dot(other)
861
def __mul__(self, other): # self * other if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = val * other #new.dtype.char = self.dtype.char return new else: return self.dot(other)
def __mul__(self, other): # self * other if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.iteritems(): new[key] = val * other #new.dtype.char = self.dtype.char return new else: return self.dot(other)
862
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = other * val #new.dtype.char = self.dtype.char return new else: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix(self.shape, dtype=self.dtype) # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = other * val #new.dtype.char = self.dtype.char return new else: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
863
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = other * val #new.dtype.char = self.dtype.char return new else: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.iteritems(): new[key] = other * val #new.dtype.char = self.dtype.char return new else: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
864
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = other * val #new.dtype.char = self.dtype.char return new else: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
def __rmul__(self, other): # other * self if isscalar(other) or (isdense(other) and rank(other)==0): new = dok_matrix() # Multiply this scalar by every element. for (key, val) in self.items(): new[key] = other * val #new.dtype.char = self.dtype.char return new else: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
865
def transpose(self): """ Return the transpose """ newshape = (self.shape[1], self.shape[0]) new = dok_matrix(newshape) for key in self.keys(): new[key[1], key[0]] = self[key] return new
def transpose(self): """ Return the transpose """ m, n = self.shape new = dok_matrix((n, m), dtype=self.dtype) for key, value in self.iteritems(): new[key[1], key[0]] = value return new
866
def conjtransp(self): """ Return the conjugate transpose """ new = dok_matrix() for key in self.keys(): new[key[1], key[0]] = conj(self[key]) return new
def conjtransp(self): """ Return the conjugate transpose """ m, n = self.shape new = dok_matrix((n, m), dtype=self.dtype) for key, value in self.iteritems(): new[key[1], key[0]] = conj(value) return new
867
def copy(self): new = dok_matrix() new.update(self) new.shape = self.shape return new
def copy(self): new = dok_matrix(self.shape, dtype=self.dtype) new.update(self) new.shape = self.shape return new
868
def take(self, cols_or_rows, columns=1): # Extract columns or rows as indictated from matrix # assume cols_or_rows is sorted new = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: # columns for key in self.keys(): num = searchsorted(cols_or_rows, key[1]) if num < N: newkey = (key[0], num) new[newkey] = self[key] else: for key in self.keys(): num = searchsorted(cols_or_rows, key[0]) if num < N: newkey = (num, key[1]) new[newkey] = self[key] return new
def take(self, cols_or_rows, columns=1): # Extract columns or rows as indictated from matrix # assume cols_or_rows is sorted new = dok_matrix(self.shape, dtype=self.dtype) indx = int((columns == 1)) N = len(cols_or_rows) if indx: # columns for key in self.keys(): num = searchsorted(cols_or_rows, key[1]) if num < N: newkey = (key[0], num) new[newkey] = self[key] else: for key in self.keys(): num = searchsorted(cols_or_rows, key[0]) if num < N: newkey = (num, key[1]) new[newkey] = self[key] return new
869
def take(self, cols_or_rows, columns=1): # Extract columns or rows as indictated from matrix # assume cols_or_rows is sorted new = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: # columns for key in self.keys(): num = searchsorted(cols_or_rows, key[1]) if num < N: newkey = (key[0], num) new[newkey] = self[key] else: for key in self.keys(): num = searchsorted(cols_or_rows, key[0]) if num < N: newkey = (num, key[1]) new[newkey] = self[key] return new
def take(self, cols_or_rows, columns=1): # Extract columns or rows as indictated from matrix # assume cols_or_rows is sorted new = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: # columns for key in self: num = searchsorted(cols_or_rows, key[1]) if num < N: newkey = (key[0], num) new[newkey] = self[key] else: for key in self: num = searchsorted(cols_or_rows, key[0]) if num < N: newkey = (num, key[1]) new[newkey] = self[key] return new
870
def take(self, cols_or_rows, columns=1): # Extract columns or rows as indictated from matrix # assume cols_or_rows is sorted new = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: # columns for key in self.keys(): num = searchsorted(cols_or_rows, key[1]) if num < N: newkey = (key[0], num) new[newkey] = self[key] else: for key in self.keys(): num = searchsorted(cols_or_rows, key[0]) if num < N: newkey = (num, key[1]) new[newkey] = self[key] return new
def take(self, cols_or_rows, columns=1): # Extract columns or rows as indictated from matrix # assume cols_or_rows is sorted new = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: # columns for key in self: num = searchsorted(cols_or_rows, key[1]) if num < N: newkey = (key[0], num) new[newkey] = self[key] else: for key in self: num = searchsorted(cols_or_rows, key[0]) if num < N: newkey = (num, key[1]) new[newkey] = self[key] return new
871
def split(self, cols_or_rows, columns=1): # similar to take but returns two array, the extracted # columns plus the resulting array # assumes cols_or_rows is sorted base = dok_matrix() ext = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: for key in self.keys(): num = searchsorted(cols_or_rows, key[1]) if cols_or_rows[num]==key[1]: newkey = (key[0], num) ext[newkey] = self[key] else: newkey = (key[0], key[1]-num) base[newkey] = self[key] else: for key in self.keys(): num = searchsorted(cols_or_rows, key[0]) if cols_or_rows[num]==key[0]: newkey = (num, key[1]) ext[newkey] = self[key] else: newkey = (key[0]-num, key[1]) base[newkey] = self[key] return base, ext
def split(self, cols_or_rows, columns=1): # similar to take but returns two array, the extracted # columns plus the resulting array # assumes cols_or_rows is sorted base = dok_matrix() ext = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: for key in self: num = searchsorted(cols_or_rows, key[1]) if cols_or_rows[num]==key[1]: newkey = (key[0], num) ext[newkey] = self[key] else: newkey = (key[0], key[1]-num) base[newkey] = self[key] else: for key in self: num = searchsorted(cols_or_rows, key[0]) if cols_or_rows[num]==key[0]: newkey = (num, key[1]) ext[newkey] = self[key] else: newkey = (key[0]-num, key[1]) base[newkey] = self[key] return base, ext
872
def split(self, cols_or_rows, columns=1): # similar to take but returns two array, the extracted # columns plus the resulting array # assumes cols_or_rows is sorted base = dok_matrix() ext = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: for key in self.keys(): num = searchsorted(cols_or_rows, key[1]) if cols_or_rows[num]==key[1]: newkey = (key[0], num) ext[newkey] = self[key] else: newkey = (key[0], key[1]-num) base[newkey] = self[key] else: for key in self.keys(): num = searchsorted(cols_or_rows, key[0]) if cols_or_rows[num]==key[0]: newkey = (num, key[1]) ext[newkey] = self[key] else: newkey = (key[0]-num, key[1]) base[newkey] = self[key] return base, ext
def split(self, cols_or_rows, columns=1): # similar to take but returns two array, the extracted # columns plus the resulting array # assumes cols_or_rows is sorted base = dok_matrix() ext = dok_matrix() indx = int((columns == 1)) N = len(cols_or_rows) if indx: for key in self: num = searchsorted(cols_or_rows, key[1]) if cols_or_rows[num]==key[1]: newkey = (key[0], num) ext[newkey] = self[key] else: newkey = (key[0], key[1]-num) base[newkey] = self[key] else: for key in self: num = searchsorted(cols_or_rows, key[0]) if cols_or_rows[num]==key[0]: newkey = (num, key[1]) ext[newkey] = self[key] else: newkey = (key[0]-num, key[1]) base[newkey] = self[key] return base, ext
873
def matvec(self, other): other = asarray(other) if other.shape[0] != self.shape[1]: raise ValueError, "dimensions do not match" new = [0]*self.shape[0] for key in self.keys(): new[int(key[0])] += self[key] * other[int(key[1]), ...] return array(new)
def matvec(self, other): other = asarray(other) if other.shape[0] != self.shape[1]: raise ValueError, "dimensions do not match" new = [0]*self.shape[0] for key in self: new[int(key[0])] += self[key] * other[int(key[1]), ...] return array(new)
874
def rmatvec(self, other, conjugate=True): other = asarray(other)
def rmatvec(self, other, conjugate=True): other = asarray(other)
875
def tocsr(self, nzmax=None): """ Return Compressed Sparse Row format arrays for this matrix """ keys = self.keys() keys.sort() nnz = len(keys) nzmax = max(nnz, nzmax) data = [0]*nzmax colind = [0]*nzmax # Empty rows will leave row_ptr dangling. We assign row_ptr[i] # for each empty row i to point off the end. Is this sufficient?? row_ptr = [nnz]*(self.shape[0]+1) current_row = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey0 != current_row: N = ikey0-current_row row_ptr[current_row+1:ikey0+1] = [k]*N current_row = ikey0 data[k] = dict.__getitem__(self, key) colind[k] = ikey1 k += 1 data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix((data, colind, row_ptr), dims=self.shape, nzmax=nzmax)
def tocsr(self, nzmax=None): """ Return Compressed Sparse Row format arrays for this matrix """ keys = self.keys() keys.sort() nnz = len(keys) nzmax = max(nnz, nzmax) data = zeros(nzmax, dtype=self.dtype) colind = zeros(nzmax, dtype=self.dtype) # Empty rows will leave row_ptr dangling. We assign row_ptr[i] # for each empty row i to point off the end. Is this sufficient?? row_ptr = [nnz]*(self.shape[0]+1) current_row = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey0 != current_row: N = ikey0-current_row row_ptr[current_row+1:ikey0+1] = [k]*N current_row = ikey0 data[k] = dict.__getitem__(self, key) colind[k] = ikey1 k += 1 data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix((data, colind, row_ptr), dims=self.shape, nzmax=nzmax)
876
def tocsr(self, nzmax=None): """ Return Compressed Sparse Row format arrays for this matrix """ keys = self.keys() keys.sort() nnz = len(keys) nzmax = max(nnz, nzmax) data = [0]*nzmax colind = [0]*nzmax # Empty rows will leave row_ptr dangling. We assign row_ptr[i] # for each empty row i to point off the end. Is this sufficient?? row_ptr = [nnz]*(self.shape[0]+1) current_row = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey0 != current_row: N = ikey0-current_row row_ptr[current_row+1:ikey0+1] = [k]*N current_row = ikey0 data[k] = dict.__getitem__(self, key) colind[k] = ikey1 k += 1 data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix((data, colind, row_ptr), dims=self.shape, nzmax=nzmax)
def tocsr(self, nzmax=None): """ Return Compressed Sparse Row format arrays for this matrix """ keys = self.keys() keys.sort() nnz = len(keys) nzmax = max(nnz, nzmax) data = [0]*nzmax colind = [0]*nzmax # Empty rows will leave row_ptr dangling. We assign row_ptr[i] # for each empty row i to point off the end. Is this sufficient?? row_ptr = empty(self.shape[0]+1, dtype=int) row_ptr[:] = nnz current_row = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey0 != current_row: N = ikey0-current_row row_ptr[current_row+1:ikey0+1] = [k]*N current_row = ikey0 data[k] = dict.__getitem__(self, key) colind[k] = ikey1 k += 1 data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix((data, colind, row_ptr), dims=self.shape, nzmax=nzmax)
877
def tocsr(self, nzmax=None): """ Return Compressed Sparse Row format arrays for this matrix """ keys = self.keys() keys.sort() nnz = len(keys) nzmax = max(nnz, nzmax) data = [0]*nzmax colind = [0]*nzmax # Empty rows will leave row_ptr dangling. We assign row_ptr[i] # for each empty row i to point off the end. Is this sufficient?? row_ptr = [nnz]*(self.shape[0]+1) current_row = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey0 != current_row: N = ikey0-current_row row_ptr[current_row+1:ikey0+1] = [k]*N current_row = ikey0 data[k] = dict.__getitem__(self, key) colind[k] = ikey1 k += 1 data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix((data, colind, row_ptr), dims=self.shape, nzmax=nzmax)
def tocsr(self, nzmax=None): """ Return Compressed Sparse Row format arrays for this matrix """ keys = self.keys() keys.sort() nnz = len(keys) nzmax = max(nnz, nzmax) data = [0]*nzmax colind = [0]*nzmax # Empty rows will leave row_ptr dangling. We assign row_ptr[i] # for each empty row i to point off the end. Is this sufficient?? row_ptr = [nnz]*(self.shape[0]+1) current_row = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey0 != current_row: N = ikey0-current_row row_ptr[current_row+1:ikey0+1] = k current_row = ikey0 data[k] = dict.__getitem__(self, key) colind[k] = ikey1 k += 1 data = array(data) colind = array(colind) row_ptr = array(row_ptr) return csr_matrix((data, colind, row_ptr), dims=self.shape, nzmax=nzmax)
878
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
879
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
880
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
881
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
882
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
def tocsc(self, nzmax=None): """ Return Compressed Sparse Column format arrays for this matrix """ # Sort based on columns # This works, but is very slow for matrices with many non-zero # elements (requiring a function call for every element) #keys.sort(csc_cmp)
883
def todense(self, dtype=None): if dtype is None: dtype = 'd' new = zeros(self.shape, dtype=dtype) for key in self.keys(): ikey0 = int(key[0]) ikey1 = int(key[1]) new[ikey0, ikey1] = self[key] if amax(ravel(abs(new.imag))) == 0: new = new.real return new
def todense(self, dtype=None): if dtype is None: dtype = 'd' new = zeros(self.shape, dtype=dtype) for key in self: ikey0 = int(key[0]) ikey1 = int(key[1]) new[ikey0, ikey1] = self[key] if amax(ravel(abs(new.imag))) == 0: new = new.real return new
884
def __init__(self, obj, ij_in, dims=None, nzmax=None, dtype=None): spmatrix.__init__(self) try: # Assume the first calling convention # assert len(ij) == 2 if len(ij_in) != 2: if isdense( ij_in ) and (ij_in.shape[1] == 2): ij = (ij_in[:,0], ij_in[:,1]) else: raise AssertionError else: ij = ij_in if dims is None: M = int(amax(ij[0])) + 1 N = int(amax(ij[1])) + 1 self.shape = (M, N) else: # Use 2 steps to ensure dims has length 2. M, N = dims self.shape = (M, N) self.row = asarray(ij[0]) self.col = asarray(ij[1]) self.data = asarray(obj, dtype=dtype) self.dtype = self.data.dtype if nzmax is None: nzmax = len(self.data) self.nzmax = nzmax self._check() except Exception: print "invalid input format" raise
def __init__(self, obj, ij_in, dims=None, nzmax=None, dtype=None): spmatrix.__init__(self) try: # Assume the first calling convention # assert len(ij) == 2 if len(ij_in) != 2: if isdense(ij_in) and (ij_in.shape[1] == 2): ij = (ij_in[:,0], ij_in[:,1]) else: raise AssertionError else: ij = ij_in if dims is None: M = int(amax(ij[0])) + 1 N = int(amax(ij[1])) + 1 self.shape = (M, N) else: # Use 2 steps to ensure dims has length 2. M, N = dims self.shape = (M, N) self.row = asarray(ij[0]) self.col = asarray(ij[1]) self.data = asarray(obj, dtype=dtype) self.dtype = self.data.dtype if nzmax is None: nzmax = len(self.data) self.nzmax = nzmax self._check() except Exception: print "invalid input format" raise
885
def isspmatrix_csr( x ): return isinstance(x, csr_matrix)
def isspmatrix_csr(x): return isinstance(x, csr_matrix)
886
def isspmatrix_csc( x ): return isinstance(x, csc_matrix)
def isspmatrix_csc(x): return isinstance(x, csc_matrix)
887
def isspmatrix_dok( x ): return isinstance(x, dok_matrix)
def isspmatrix_dok(x): return isinstance(x, dok_matrix)
888
def isspmatrix_dod( x ): return isinstance(x, dod_matrix)
def isspmatrix_dod(x): return isinstance(x, dod_matrix)
889
def isspmatrix_lnk( x ): return isinstance(x, lnk_matrix)
def isspmatrix_lnk(x): return isinstance(x, lnk_matrix)
890
def isspmatrix_coo( x ): return isinstance(x, coo_matrix)
def isspmatrix_coo(x): return isinstance(x, coo_matrix)
891
def spdiags(diags, offsets, M, N): """Return a sparse matrix in CSR format given its diagonals. B = spdiags(diags, offsets, M, N) Inputs: diags -- rows contain diagonal values offsets -- diagonals to set (0 is main) M, N -- sparse matrix returned is M X N """ diags = array(transpose(diags), copy=True) if diags.dtype.char not in 'fdFD': diags = diags.astype('d') offsets = array(offsets, copy=False) mtype = diags.dtype.char assert(len(offsets) == diags.shape[1]) # set correct diagonal to csr conversion routine for this type diagfunc = eval('sparsetools.'+_transtabl[mtype]+'diatocsr') a, rowa, ptra, ierr = diagfunc(M, N, diags, offsets) if ierr: raise ValueError, "ran out of memory (shouldn't have happened)" return csc_matrix((a, rowa, ptra), dims=(M, N))
def spdiags(diags, offsets, M, N): """Return a sparse matrix in CSC format given its diagonals. B = spdiags(diags, offsets, M, N) Inputs: diags -- rows contain diagonal values offsets -- diagonals to set (0 is main) M, N -- sparse matrix returned is M X N """ diags = array(transpose(diags), copy=True) if diags.dtype.char not in 'fdFD': diags = diags.astype('d') offsets = array(offsets, copy=False) mtype = diags.dtype.char assert(len(offsets) == diags.shape[1]) # set correct diagonal to csr conversion routine for this type diagfunc = eval('sparsetools.'+_transtabl[mtype]+'diatocsr') a, rowa, ptra, ierr = diagfunc(M, N, diags, offsets) if ierr: raise ValueError, "ran out of memory (shouldn't have happened)" return csc_matrix((a, rowa, ptra), dims=(M, N))
892
def spdiags(diags, offsets, M, N): """Return a sparse matrix in CSR format given its diagonals. B = spdiags(diags, offsets, M, N) Inputs: diags -- rows contain diagonal values offsets -- diagonals to set (0 is main) M, N -- sparse matrix returned is M X N """ diags = array(transpose(diags), copy=True) if diags.dtype.char not in 'fdFD': diags = diags.astype('d') offsets = array(offsets, copy=False) mtype = diags.dtype.char assert(len(offsets) == diags.shape[1]) # set correct diagonal to csr conversion routine for this type diagfunc = eval('sparsetools.'+_transtabl[mtype]+'diatocsr') a, rowa, ptra, ierr = diagfunc(M, N, diags, offsets) if ierr: raise ValueError, "ran out of memory (shouldn't have happened)" return csc_matrix((a, rowa, ptra), dims=(M, N))
def spdiags(diags, offsets, M, N): """Return a sparse matrix in CSR format given its diagonals. B = spdiags(diags, offsets, M, N) Inputs: diags -- rows contain diagonal values offsets -- diagonals to set (0 is main) M, N -- sparse matrix returned is M X N """ diags = array(transpose(diags), copy=True) if diags.dtype.char not in 'fdFD': diags = diags.astype('d') offsets = array(offsets, copy=False) mtype = diags.dtype.char assert(len(offsets) == diags.shape[1]) # set correct diagonal to csr conversion routine for this type diagfunc = eval('sparsetools.'+_transtabl[mtype]+'diatocsc') a, rowa, ptra, ierr = diagfunc(M, N, diags, offsets) if ierr: raise ValueError, "ran out of memory (shouldn't have happened)" return csc_matrix((a, rowa, ptra), dims=(M, N))
893
def solve(A, b, permc_spec=2): if not hasattr(A, 'tocsr') and not hasattr(A, 'tocsc'): raise ValueError, "sparse matrix must be able to return CSC format--"\ "A.tocsc()--or CSR format--A.tocsr()" if not hasattr(A, 'shape'): raise ValueError, "sparse matrix must be able to return shape (rows, cols) = A.shape" M, N = A.shape if (M != N): raise ValueError, "matrix must be square" if hasattr(A, 'tocsc') and not isspmatrix_csr( A ): mat = A.tocsc() ftype, lastel, data, index0, index1 = \ mat.ftype, mat.nnz, mat.data, mat.rowind, mat.indptr csc = 1 else: mat = A.tocsr() ftype, lastel, data, index0, index1 = \ mat.ftype, mat.nnz, mat.data, mat.colind, mat.indptr csc = 0 gssv = eval('_superlu.' + ftype + 'gssv') return gssv(N, lastel, data, index0, index1, b, csc, permc_spec)[0]
def solve(A, b, permc_spec=2): if not hasattr(A, 'tocsr') and not hasattr(A, 'tocsc'): raise ValueError, "sparse matrix must be able to return CSC format--"\ "A.tocsc()--or CSR format--A.tocsr()" if not hasattr(A, 'shape'): raise ValueError, "sparse matrix must be able to return shape (rows, cols) = A.shape" M, N = A.shape if (M != N): raise ValueError, "matrix must be square" if hasattr(A, 'tocsc') and not isspmatrix_csr(A): mat = A.tocsc() ftype, lastel, data, index0, index1 = \ mat.ftype, mat.nnz, mat.data, mat.rowind, mat.indptr csc = 1 else: mat = A.tocsr() ftype, lastel, data, index0, index1 = \ mat.ftype, mat.nnz, mat.data, mat.colind, mat.indptr csc = 0 gssv = eval('_superlu.' + ftype + 'gssv') return gssv(N, lastel, data, index0, index1, b, csc, permc_spec)[0]
894
def _ppf(self, q, a, b): return 1.0/(1+exp(-1.0/b*norm.ppf(q)-a))
def _ppf(self, q, a, b): return 1.0/(1+exp(-1.0/b*norm.ppf(q)-a))
895
def lsim2(system, U, T, X0=None): """Simulate output of a continuous-time linear system, using ODE solver. Inputs: system -- an instance of the LTI class or a tuple describing the system. The following gives the number of elements in the tuple and the interpretation. 2 (num, den) 3 (zeros, poles, gain) 4 (A, B, C, D) U -- an input array describing the input at each time T (linear interpolation is assumed between given times). If there are multiple inputs, then each column of the rank-2 array represents an input. T -- the time steps at which the input is defined and at which the output is desired. X0 -- (optional, default=0) the initial conditions on the state vector. Outputs: (T, yout, xout) T -- the time values for the output. yout -- the response of the system. xout -- the time-evolution of the state-vector. """ # system is an lti system or a sequence # with 2 (num, den) # 3 (zeros, poles, gain) # 4 (A, B, C, D) # describing the system # U is an input vector at times T # if system describes multiple outputs # then U can be a rank-2 array with the number of columns # being the number of inputs if isinstance(system, lti): sys = system else: sys = lti(*system) U = r1array(U) T = r1array(T) if len(U.shape) == 1: U.shape = (U.shape[0],1) sU = U.shape if len(T.shape) != 1: raise ValueError, "T must be a rank-1 array." if sU[0] != len(T): raise ValueError, "U must have the same number of rows as elements in T." if sU[1] != sys.inputs: raise ValueError, "System does not define that many inputs." if X0 is None: X0 = zeros(sys.B.shape[0],sys.A.typecode()) ufunc = interpolate.linear_1d(T, U, axis=0, bounds_error=0, fill_value=0) def fprime(x, t, sys, ufunc): return dot(sys.A,x) + squeeze(dot(sys.B,ufunc([t]))) xout = integrate.odeint(fprime, X0, T, args=(sys, ufunc)) yout = dot(sys.C,transpose(xout)) + dot(sys.D,transpose(U)) return T, squeeze(transpose(yout)), xout
def lsim2(system, U, T, X0=None): """Simulate output of a continuous-time linear system, using ODE solver. Inputs: system -- an instance of the LTI class or a tuple describing the system. The following gives the number of elements in the tuple and the interpretation. 2 (num, den) 3 (zeros, poles, gain) 4 (A, B, C, D) U -- an input array describing the input at each time T (linear interpolation is assumed between given times). If there are multiple inputs, then each column of the rank-2 array represents an input. T -- the time steps at which the input is defined and at which the output is desired. X0 -- (optional, default=0) the initial conditions on the state vector. Outputs: (T, yout, xout) T -- the time values for the output. yout -- the response of the system. xout -- the time-evolution of the state-vector. """ # system is an lti system or a sequence # with 2 (num, den) # 3 (zeros, poles, gain) # 4 (A, B, C, D) # describing the system # U is an input vector at times T # if system describes multiple outputs # then U can be a rank-2 array with the number of columns # being the number of inputs if isinstance(system, lti): sys = system else: sys = lti(*system) U = r1array(U) T = r1array(T) if len(U.shape) == 1: U.shape = (U.shape[0],1) sU = U.shape if len(T.shape) != 1: raise ValueError, "T must be a rank-1 array." if sU[0] != len(T): raise ValueError, "U must have the same number of rows as elements in T." if sU[1] != sys.inputs: raise ValueError, "System does not define that many inputs." if X0 is None: X0 = zeros(sys.B.shape[0],sys.A.typecode()) ufunc = interpolate.linear_1d(T, U, axis=0, bounds_error=0, fill_value=0) def fprime(x, t, sys, ufunc): return dot(sys.A,x) + squeeze(dot(sys.B,ufunc([t]))) xout = integrate.odeint(fprime, X0, T, args=(sys, ufunc)) yout = dot(sys.C,transpose(xout)) + dot(sys.D,transpose(U)) return T, squeeze(transpose(yout)), xout
896
def impulse(system, X0=None, T=None, N=None): """Impulse response of continuous-time system. Inputs: system -- an instance of the LTI class or a tuple with 2, 3, or 4 elements representing (num, den), (zero, pole, gain), or (A, B, C, D) representation of the system. X0 -- (optional, default = 0) inital state-vector. T -- (optional) time points (autocomputed if not given). N -- (optional) number of time points to autocompute (100 if not given). Ouptuts: (T, yout) T -- output time points, yout -- impulse response of system. """ if isinstance(system, lti): sys = system else: sys = lti(*system) if X0 is None: B = sys.B else: B = sys.B + X0 if N is None: N = 100 if T is None: vals = linalg.eigvals(sys.A) tc = 1.0/min(abs(real(vals))) T = arange(0,5*tc,5*tc / float(N)) h = zeros(T.shape, sys.A.typecode()) for k in range(len(h)): eA = Mat(linalg.expm(sys.A*T[k])) B,C = map(Mat, (B,sys.C)) h[k] = squeeze(C*eA*B) return T, h
def impulse(system, X0=None, T=None, N=None): """Impulse response of continuous-time system. Inputs: system -- an instance of the LTI class or a tuple with 2, 3, or 4 elements representing (num, den), (zero, pole, gain), or (A, B, C, D) representation of the system. X0 -- (optional, default = 0) inital state-vector. T -- (optional) time points (autocomputed if not given). N -- (optional) number of time points to autocompute (100 if not given). Ouptuts: (T, yout) T -- output time points, yout -- impulse response of system (except possible singularities at 0). """ if isinstance(system, lti): sys = system else: sys = lti(*system) if X0 is None: B = sys.B else: B = sys.B + X0 if N is None: N = 100 if T is None: vals = linalg.eigvals(sys.A) tc = 1.0/min(abs(real(vals))) T = arange(0,5*tc,5*tc / float(N)) h = zeros(T.shape, sys.A.typecode()) for k in range(len(h)): eA = Mat(linalg.expm(sys.A*T[k])) B,C = map(Mat, (B,sys.C)) h[k] = squeeze(C*eA*B) return T, h
897
def read_element(self, copy=True): raw_tag = self.mat_stream.read(8) tag = ndarray(shape=(), dtype=self.dtypes['tag_full'], buffer = raw_tag) mdtype = tag['mdtype'] byte_count = mdtype >> 16 if byte_count: # small data element format if byte_count > 4: raise ValueError, 'Too many bytes for sde format' mdtype = mdtype & 0xFFFF dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize return ndarray(shape=(el_count,), dtype=dt, buffer=raw_tag[4:]) byte_count = tag['byte_count'] if mdtype == miMATRIX: return self.current_getter().get_array() if mdtype in self.codecs: # encoded char data raw_str = self.mat_stream.read(byte_count) codec = self.codecs[mdtype] if not codec: raise TypeError, 'Do not support encoding %d' % mdtype el = raw_str.decode(codec) else: # numeric data dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize el = ndarray(shape=(el_count,), dtype=dt, buffer=self.mat_stream.read(byte_count)) if copy: el = el.copy() mod8 = byte_count % 8 if mod8: self.mat_stream.seek(8 - mod8, 1) return el
def read_element(self, copy=True): raw_tag = self.mat_stream.read(8) tag = ndarray(shape=(), dtype=self.dtypes['tag_full'], buffer = raw_tag) mdtype = tag['mdtype'] byte_count = mdtype >> 16 if byte_count: # small data element format if byte_count > 4: raise ValueError, 'Too many bytes for sde format' mdtype = mdtype & 0xFFFF dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize return ndarray(shape=(el_count,), dtype=dt, buffer=raw_tag[4:4+byte_count]) byte_count = tag['byte_count'] if mdtype == miMATRIX: return self.current_getter().get_array() if mdtype in self.codecs: # encoded char data raw_str = self.mat_stream.read(byte_count) codec = self.codecs[mdtype] if not codec: raise TypeError, 'Do not support encoding %d' % mdtype el = raw_str.decode(codec) else: # numeric data dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize el = ndarray(shape=(el_count,), dtype=dt, buffer=self.mat_stream.read(byte_count)) if copy: el = el.copy() mod8 = byte_count % 8 if mod8: self.mat_stream.seek(8 - mod8, 1) return el
898
def read_element(self, copy=True): raw_tag = self.mat_stream.read(8) tag = ndarray(shape=(), dtype=self.dtypes['tag_full'], buffer = raw_tag) mdtype = tag['mdtype'] byte_count = mdtype >> 16 if byte_count: # small data element format if byte_count > 4: raise ValueError, 'Too many bytes for sde format' mdtype = mdtype & 0xFFFF dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize return ndarray(shape=(el_count,), dtype=dt, buffer=raw_tag[4:]) byte_count = tag['byte_count'] if mdtype == miMATRIX: return self.current_getter().get_array() if mdtype in self.codecs: # encoded char data raw_str = self.mat_stream.read(byte_count) codec = self.codecs[mdtype] if not codec: raise TypeError, 'Do not support encoding %d' % mdtype el = raw_str.decode(codec) else: # numeric data dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize el = ndarray(shape=(el_count,), dtype=dt, buffer=self.mat_stream.read(byte_count)) if copy: el = el.copy() mod8 = byte_count % 8 if mod8: self.mat_stream.seek(8 - mod8, 1) return el
def read_element(self, copy=True): raw_tag = self.mat_stream.read(8) tag = ndarray(shape=(), dtype=self.dtypes['tag_full'], buffer = raw_tag) mdtype = tag['mdtype'] byte_count = mdtype >> 16 if byte_count: # small data element format if byte_count > 4: raise ValueError, 'Too many bytes for sde format' mdtype = mdtype & 0xFFFF dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize return ndarray(shape=(el_count,), dtype=dt, buffer=raw_tag[4:]) byte_count = tag['byte_count'] if mdtype == miMATRIX: return self.current_getter(byte_count).get_array() if mdtype in self.codecs: # encoded char data raw_str = self.mat_stream.read(byte_count) codec = self.codecs[mdtype] if not codec: raise TypeError, 'Do not support encoding %d' % mdtype el = raw_str.decode(codec) else: # numeric data dt = self.dtypes[mdtype] el_count = byte_count / dt.itemsize el = ndarray(shape=(el_count,), dtype=dt, buffer=self.mat_stream.read(byte_count)) if copy: el = el.copy() mod8 = byte_count % 8 if mod8: self.mat_stream.seek(8 - mod8, 1) return el
899