rem
stringlengths
1
322k
add
stringlengths
0
2.05M
context
stringlengths
4
228k
meta
stringlengths
156
215
Lsource = makelist(sourcebetweens,Nfactors+1) Bbtwnonsourcedims = ~source & Bbetweens Lbtwnonsourcedims = makelist(Bbtwnonsourcedims,Nfactors+1) btwnonsourcedims = (array(map(Bscols.index,Lbtwnonsourcedims))-1).tolist()
Lsource = makelist(sourcebetweens,Nfactors+1) Bbtwnonsourcedims = ~source & Bbetweens Lbtwnonsourcedims = makelist(Bbtwnonsourcedims,Nfactors+1) btwnonsourcedims = (array(map(Bscols.index,Lbtwnonsourcedims))-1).tolist()
def d_restrict_source(workd,subjslots,source): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
sourceDMarray = DM[dindex] *1.0 for dim in btwnonsourcedims: if dim == len(DM[dindex].shape)-1: raise ValueError, "Crashing ... shouldn't ever collapse ACROSS variables" sourceDMarray = expand_dims(mean(sourceDMarray,dim),dim)
sourceDMarray = DM[dindex] *1.0 for dim in btwnonsourcedims: if dim == len(DM[dindex].shape)-1: raise ValueError, "Crashing ... shouldn't ever collapse ACROSS variables" sourceDMarray = expand_dims(mean(sourceDMarray,dim),dim)
def d_restrict_source(workd,subjslots,source): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
sourceDNarray = apply_over_axes(hmean, DN[dindex],btwnonsourcedims)
sourceDNarray = apply_over_axes(hmean, DN[dindex],btwnonsourcedims)
def d_restrict_source(workd,subjslots,source): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
variableNs = apply_over_axes(sum, sourceDNarray, range(len(sourceDMarray.shape)-1)) ga = apply_over_axes(sum, (sourceDMarray*sourceDNarray) / \ variableNs, range(len(sourceDMarray.shape)-1))
variableNs = apply_over_axes(sum, sourceDNarray, range(len(sourceDMarray.shape)-1)) ga = apply_over_axes(sum, (sourceDMarray*sourceDNarray) / \ variableNs, range(len(sourceDMarray.shape)-1))
def d_restrict_source(workd,subjslots,source): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
if source == Nallsources-1: sourceDNarray = hmean(DN[dindex], range(len(sourceDMarray.shape)-1))
if source == Nallsources-1: sourceDNarray = hmean(DN[dindex], range(len(sourceDMarray.shape)-1))
def d_restrict_source(workd,subjslots,source): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
sub_effects = ga *1.0 for subsource in range(3,source-2,2):
sub_effects = ga *1.0 for subsource in range(3,source-2,2):
def d_restrict_source(workd,subjslots,source): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
if (propersubset(subsource-1,source-1) and (subsource-1)&Bwithins == (source-1)&Bwithins and (subsource-1) != (source-1)&Bwithins): sub_effects = (sub_effects +
if (propersubset(subsource-1,source-1) and (subsource-1)&Bwithins == (source-1)&Bwithins and (subsource-1) != (source-1)&Bwithins): sub_effects = (sub_effects +
def d_restrict_source(workd,subjslots,source): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
effect = sourceDMarray - sub_effects
effect = sourceDMarray - sub_effects
def d_restrict_source(workd,subjslots,source): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
alleffects.append(effect) alleffsources.append(source)
alleffects.append(effect) alleffsources.append(source)
def d_restrict_source(workd,subjslots,source): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
SS = zeros((levels,levels),'f') SS = sum((effect**2 *sourceDNarray) * multiply.reduce(take(DM[dindex].shape,btwnonsourcedims)), range(len(sourceDMarray.shape)-1))
SS = zeros((levels,levels),'f') SS = sum((effect**2 *sourceDNarray) * multiply.reduce(take(DM[dindex].shape,btwnonsourcedims)), range(len(sourceDMarray.shape)-1))
def d_restrict_source(workd,subjslots,source): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
SSlist.append(SS) SSsources.append(source) return SS
SSlist.append(SS) SSsources.append(source) return SS
def d_restrict_source(workd,subjslots,source): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
if len(workd.shape) == 1: levels = 1 else: levels = workd.shape[0] sserr = zeros((levels,levels),'f') for i in range(levels): for j in range(i,levels): ssval = add.reduce(workd[i]*workd[j]) sserr[i,j] = ssval sserr[j,i] = ssval return sserr
if len(workd.shape) == 1: levels = 1 else: levels = workd.shape[0] sserr = zeros((levels,levels),'f') for i in range(levels): for j in range(i,levels): ssval = add.reduce(workd[i]*workd[j]) sserr[i,j] = ssval sserr[j,i] = ssval return sserr
def multivar_sscalc(workd):
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
""" Subtract all cell means when within-subjects factors are present ... i.e., calculate full-model using a D-variable. """ sourcedims = makelist(Bbetweens,Nfactors+1) transidx = range(len(subjslots.shape))[1:] + [0] tsubjslots = transpose(subjslots,transidx) tworkd = transpose(workd) errors = 1.0 * tworkd if len(sourcedims) == 0: idx = [-1] loopcap = [0] if len(sourcedims) != 0: btwsourcedims = map(Bscols.index,sourcedims) idx = [0] * len(btwsourcedims) idx[0] = -1 loopcap = take(array(Nlevels),sourcedims)-1
""" Subtract all cell means when within-subjects factors are present ... i.e., calculate full-model using a D-variable. """ sourcedims = makelist(Bbetweens,Nfactors+1) transidx = range(len(subjslots.shape))[1:] + [0] tsubjslots = transpose(subjslots,transidx) tworkd = transpose(workd) errors = 1.0 * tworkd if len(sourcedims) == 0: idx = [-1] loopcap = [0] if len(sourcedims) != 0: btwsourcedims = map(Bscols.index,sourcedims) idx = [0] * len(btwsourcedims) idx[0] = -1 loopcap = take(array(Nlevels),sourcedims)-1
def subtr_cellmeans(workd,subjslots): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
while incr(idx,loopcap) != -1: mask = tsubjslots[idx] thisgroup = tworkd*mask[NewAxis,:] groupmns = mean(compress(mask,thisgroup),1)
while incr(idx,loopcap) != -1: mask = tsubjslots[idx] thisgroup = tworkd*mask[NewAxis,:] groupmns = mean(compress(mask,thisgroup),1)
def subtr_cellmeans(workd,subjslots): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
errors = errors - multiply.outer(groupmns,mask) return errors
errors = errors - multiply.outer(groupmns,mask) return errors
def subtr_cellmeans(workd,subjslots): """
3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/3bb739baad4fb4f21aa19b39fbb10f6aa5c1a041/stats.py
if __name__ == "__main__":
def _testme():
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)
01b070b28212b3a1a02ca1e68c2a9b52e29c4443 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/01b070b28212b3a1a02ca1e68c2a9b52e29c4443/sparse.py
_endprint(x, flag, fval, maxfun, tol, disp)
_endprint(x, flag, fval, maxfun, xtol, disp)
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
57ee28ebf2c56ff23c90606b449d465aad5b8402 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/57ee28ebf2c56ff23c90606b449d465aad5b8402/optimize.py
raise ValuError, "Bracketing interval must be length 2 or 3 sequence."
raise ValueError, "Bracketing interval must be length 2 or 3 sequence."
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
57ee28ebf2c56ff23c90606b449d465aad5b8402 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/57ee28ebf2c56ff23c90606b449d465aad5b8402/optimize.py
raise ValuError, "Bracketing interval must be length 2 or 3 sequence."
raise ValueError, "Bracketing interval must be length 2 or 3 sequence."
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
57ee28ebf2c56ff23c90606b449d465aad5b8402 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/57ee28ebf2c56ff23c90606b449d465aad5b8402/optimize.py
raise RunTimeError, "Too many iterations."
raise RuntimeError, "Too many iterations."
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
57ee28ebf2c56ff23c90606b449d465aad5b8402 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/57ee28ebf2c56ff23c90606b449d465aad5b8402/optimize.py
(-10,1):0L, (10,-1):0L, (-10,-3):0L,(10,11),0L}
(-10,1):0L, (10,-1):0L, (-10,-3):0L,(10,11):0L}
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])
5724580f929252a402a0f94ec5f44c7dad72ff5a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5724580f929252a402a0f94ec5f44c7dad72ff5a/test_common.py
def getH(self): return self.transpose().conj() # csc = self.tocsc() # new = csc.transpose() # new.data = conj(new.data) # return new
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
except (AttributeError, TypeError): try: return self.matvec(asarray(other)) except: raise TypeError, "x.dot(y): y must be matrix, vector, or seq" except ValueError: K2 = other.shape[0] N = 1 if N == 1:
elif len(other.shape) == 1: K2, N = other.shape[0], 1 else: raise ValueError, "could not interpret dimensions" if N == 1 or K2 == 1:
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
def save( self, file_name, format = '%d %d %f\n' ):
def save(self, file_name, format = '%d %d %f\n'):
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()
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
fd = open( file_name, 'w' )
fd = open(file_name, 'w')
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()
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
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.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))
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()
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
with a dense matrix d
with a dense array or matrix d
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()
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False):
def __init__(self, arg1, dims=None, nzmax=100, dtype='d', copy=False):
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"
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
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"
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
s = asarray(arg1)
s = arg1
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"
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
dtype = s.dtype.char func = getattr(sparsetools, _transtabl[dtype]+'fulltocsc')
dtype = s.dtype func = getattr(sparsetools, _transtabl[dtype.char]+'fulltocsc')
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"
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
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:
except (AssertionError, TypeError, ValueError):
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"
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
try: tr = other.transpose() except AttributeError: tr = asarray(other).transpose() return self.transpose().dot(tr).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()
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
if (rank(other) != 1) or (len(other) != self.shape[1]): raise ValueError, "dimension mismatch"
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"
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
if (rank(other) != 1) or (len(other) != self.shape[0]): raise ValueError, "dimension mismatch"
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"
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
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"
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
raise KeyError, "index out of bounds"
raise IndexError, "index out of bounds"
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
raise KeyError, "key out of bounds"
raise IndexError, "index out of bounds"
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
with a dense matrix d
with a dense array or matrix d
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
def __init__(self, arg1, dims=(None,None), nzmax=100, dtype='d', copy=False):
def __init__(self, arg1, dims=None, nzmax=100, dtype='d', copy=False):
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])
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
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])
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
s = asarray(arg1)
s = arg1
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])
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
ijnew = ij.copy() ijnew[:, 0] = ij[:, 1] ijnew[:, 1] = ij[:, 0] temp = coo_matrix(s, ijnew, dims=dims, nzmax=nzmax, dtype=dtype).tocsr() self.shape = temp.shape self.data = temp.data self.colind = temp.colind self.indptr = temp.indptr except:
except (AssertionError, TypeError, ValueError, AttributeError):
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])
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
raise NotImplementedError, 'adding a scalar to a sparse matrix ' \
raise NotImplementedError, 'adding a scalar to a CSR matrix ' \
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"
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
try: tr = other.transpose() except AttributeError: tr = asarray(other).transpose() return self.transpose().dot(tr).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: other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
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
if isdense(other): func = getattr(sparsetools, self.ftype+'csrmux') y = func(self.data, self.colind, self.indptr, other) return y else: raise TypeError, "need a dense vector"
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
if (rank(other) != 1) or (len(other) != self.shape[0]): raise ValueError, "dimension mismatch"
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
raise KeyError, "index out of bounds"
raise IndexError, "index out of bounds"
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
raise KeyError, "key out of bounds"
raise IndexError, "index out of bounds"
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
""" A dictionary of keys based matrix. This is relatively efficient for constructing sparse matrices for conversion to other sparse matrix types. It does type checking on input by default. To disable this type checking and speed up element accesses slightly, set self._validate to False.
""" A dictionary of keys based matrix. This is an efficient structure for constructing sparse matrices for conversion to other sparse matrix types.
# def csc_cmp(x, y):
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
def __init__(self, A=None):
def __init__(self, A=None, dtype='d'):
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"
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
A = asarray(A)
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"
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
new.shape = self.shape for key in other.keys():
for key in other:
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
for key in other.keys():
for key in other:
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
else:
elif isdense(other):
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
new = dok_matrix() for key in self.keys():
new = dok_matrix(self.shape, dtype=self.dtype) for key in self:
def __neg__(self): new = dok_matrix() for key in self.keys(): new[key] = -self[key] return new
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
for (key, val) in self.items():
for (key, val) in self.iteritems():
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
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()
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
for (key, val) in self.items():
for (key, val) in self.iteritems():
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()
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
other = asarray(other) return self.transpose().dot(other.transpose()).transpose()
try: tr = other.transpose() except AttributeError: tr = asarray(other).transpose() return self.transpose().dot(tr).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()
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
newshape = (self.shape[1], self.shape[0]) new = dok_matrix(newshape) for key in self.keys(): new[key[1], key[0]] = self[key]
m, n = self.shape new = dok_matrix((n, m), dtype=self.dtype) for key, value in self.iteritems(): new[key[1], key[0]] = value
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
new = dok_matrix() for key in self.keys(): new[key[1], key[0]] = conj(self[key])
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)
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
def copy(self): new = dok_matrix() new.update(self) new.shape = self.shape return new
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
new = dok_matrix()
new = dok_matrix(self.shape, dtype=self.dtype)
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
for key in self.keys():
for key in self:
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
for key in self.keys():
for key in self:
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
for key in self.keys():
for key in self:
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
for key in self.keys():
for key in self:
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
for key in self.keys():
for key in self:
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
if other.shape[-1] != self.shape[0]: raise ValueError, "dimensions do not match" new = [0]*self.shape[1] for key in self.keys(): new[int(key[1])] += other[..., int(key[0])] * conj(self[key]) return array(new)
if other.shape[-1] != self.shape[0]: raise ValueError, "dimensions do not match" new = [0]*self.shape[1] for key in self: new[int(key[1])] += other[..., int(key[0])] * conj(self[key]) return array(new)
def rmatvec(self, other, conjugate=True): other = asarray(other)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
data = [0]*nzmax colind = [0]*nzmax
data = zeros(nzmax, dtype=self.dtype) colind = zeros(nzmax, dtype=self.dtype)
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
row_ptr = [nnz]*(self.shape[0]+1)
row_ptr = empty(self.shape[0]+1, dtype=int) row_ptr[:] = nnz
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
row_ptr[current_row+1:ikey0+1] = [k]*N
row_ptr[current_row+1:ikey0+1] = k
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
keys = [(k[1], k[0]) for k in self.keys()]
keys = [(k[1], k[0]) for k in self]
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
data = [0]*nzmax rowind = [0]*nzmax
data = zeros(nzmax, dtype=self.dtype) rowind = zeros(nzmax, dtype=self.dtype)
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
col_ptr = [nnz]*(self.shape[1]+1)
col_ptr = empty(self.shape[1]+1) col_ptr[:] = nnz
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
col_ptr[current_col+1:ikey1+1] = [k]*N
col_ptr[current_col+1:ikey1+1] = k
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
data = array(data) rowind = array(rowind) col_ptr = array(col_ptr)
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)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
for key in self.keys():
for key in self:
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
if isdense( ij_in ) and (ij_in.shape[1] == 2):
if isdense(ij_in) and (ij_in.shape[1] == 2):
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
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
def isspmatrix_csr( x ):
def isspmatrix_csr(x):
def isspmatrix_csr( x ): return isinstance(x, csr_matrix)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
def isspmatrix_csc( x ):
def isspmatrix_csc(x):
def isspmatrix_csc( x ): return isinstance(x, csc_matrix)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
def isspmatrix_dok( x ):
def isspmatrix_dok(x):
def isspmatrix_dok( x ): return isinstance(x, dok_matrix)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
def isspmatrix_dod( x ):
def isspmatrix_dod(x):
def isspmatrix_dod( x ): return isinstance(x, dod_matrix)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
def isspmatrix_lnk( x ):
def isspmatrix_lnk(x):
def isspmatrix_lnk( x ): return isinstance(x, lnk_matrix)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
def isspmatrix_coo( x ):
def isspmatrix_coo(x):
def isspmatrix_coo( x ): return isinstance(x, coo_matrix)
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
"""Return a sparse matrix in CSR format given its diagonals.
"""Return a sparse matrix in CSC format given its diagonals.
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))
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
diagfunc = eval('sparsetools.'+_transtabl[mtype]+'diatocsr')
diagfunc = eval('sparsetools.'+_transtabl[mtype]+'diatocsc')
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))
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
if hasattr(A, 'tocsc') and not isspmatrix_csr( A ):
if hasattr(A, 'tocsc') and not isspmatrix_csr(A):
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]
cc9a850083c66543ac7901fd68022fbe73610704 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/cc9a850083c66543ac7901fd68022fbe73610704/sparse.py
return 1.0/(1+exp(-1.0/b*norm.ppf(q)-a))
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))
05b92c52116db8f043e416d3056416410d288665 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/05b92c52116db8f043e416d3056416410d288665/distributions.py
if isinstance(system, lti):
if isinstance(system, lti):
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
e8fcc876d2f5bd4ab71bfa836f3d3ce06de5b617 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/e8fcc876d2f5bd4ab71bfa836f3d3ce06de5b617/ltisys.py
yout -- impulse response of system.
yout -- impulse response of system (except possible singularities at 0).
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
e8fcc876d2f5bd4ab71bfa836f3d3ce06de5b617 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/e8fcc876d2f5bd4ab71bfa836f3d3ce06de5b617/ltisys.py
buffer=raw_tag[4:])
buffer=raw_tag[4:4+byte_count])
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
480afd5e75d2805992c5f44fabda71fe19a0a93a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/480afd5e75d2805992c5f44fabda71fe19a0a93a/mio5.py
return self.current_getter().get_array()
return self.current_getter(byte_count).get_array()
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
480afd5e75d2805992c5f44fabda71fe19a0a93a /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/480afd5e75d2805992c5f44fabda71fe19a0a93a/mio5.py