rem
stringlengths
1
322k
add
stringlengths
0
2.05M
context
stringlengths
4
228k
meta
stringlengths
156
215
return special.bdtrik(q,n,pr)
vals = scipy.ceil(special.bdtrik(q,n,pr)) temp = special.bdtr(vals-1,n,pr) return where(temp >= q, vals-1, vals)
def binomppf(q, n, pr=0.5): return special.bdtrik(q,n,pr)
708f55b4b3e8081e9554c6e78bbc04ba3bdbb4ca /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/708f55b4b3e8081e9554c6e78bbc04ba3bdbb4ca/distributions.py
return special.bdtrik(1-p,n,pr)
return binomppf(1-p,n,pr)
def binomisf(p, n, pr=0.5): return special.bdtrik(1-p,n,pr)
708f55b4b3e8081e9554c6e78bbc04ba3bdbb4ca /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/708f55b4b3e8081e9554c6e78bbc04ba3bdbb4ca/distributions.py
def binomstats(n, pr=0.5, full=0): q = 1.0-pr mu = n * pr var = n * pr * q if not full: return mu, var g1 = (q-pr) / sqrt(n*pr*q) g2 = (1.0-6*pr*q)/(n*pr*q) return mu, var, g1, g2
708f55b4b3e8081e9554c6e78bbc04ba3bdbb4ca /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/708f55b4b3e8081e9554c6e78bbc04ba3bdbb4ca/distributions.py
out = where(lVar > noise, lMean, im)
res = (im - lMean) res *= (1-noise / lVar) res += lMean out = where(lVar < noise, lMean, res)
def wiener(im,mysize=None,noise=None): """Perform a wiener filter on an N-dimensional array. Description: Apply a wiener filter to the N-dimensional array in. Inputs: in -- an N-dimensional array. kernel_size -- A scalar or an N-length list giving the size of the median filter window in each dimension. Elements of kernel_size should be odd. If kernel_size is a scalar, then this scalar is used as the size in each dimension. noise -- The noise-power to use. If None, then noise is estimated as the average of the local variance of the input. Outputs: (out,) out -- Wiener filtered result with the same shape as in. """ im = asarray(im) if mysize is None: mysize = [3] * len(im.shape) mysize = asarray(mysize); # Estimate the local mean lMean = correlate(im,Numeric.ones(mysize),1) / Numeric.product(mysize) # Estimate the local variance lVar = correlate(im**2,Numeric.ones(mysize),1) / Numeric.product(mysize) - lMean**2 # Estimate the noise power if needed. if noise==None: noise = mean(Numeric.ravel(lVar)) out = where(lVar > noise, lMean, im) return out
4837ca0cb43382e7b8ccff3580109ad5e79a1a77 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/4837ca0cb43382e7b8ccff3580109ad5e79a1a77/signaltools.py
int dim[2] = {upper-lower, Nx[0]};
npy_intp dim[2] = {upper-lower, Nx[0]};
def setup_bspline_module(): """ Builds an extension module with Bspline basis calculators using weave. """ mod = ext_tools.ext_module('_bspline', compiler='gcc') knots = N.linspace(0,1,11).astype(N.float64) nknots = knots.shape[0] x = N.array([0.4,0.5], N.float64) nx = x.shape[0] m = 4 d = 0 lower = 0 upper = 13 # Bspline code in C eval_code = ''' double *bspline(double **output, double *x, int nx, double *knots, int nknots, int m, int d, int lower, int upper) { int nbasis; int index, i, j, k; double *result, *b, *b0, *b1; double *f0, *f1; double denom; nbasis = upper - lower; result = *((double **) output); f0 = (double *) malloc(sizeof(*f0) * nx); f1 = (double *) malloc(sizeof(*f1) * nx); if (m == 1) { for(i=0; i<nbasis; i++) { index = i + lower; if(index < nknots - 1) { if ((knots[index] != knots[index+1]) && (d <= 0)) { for (k=0; k<nx; k++) { *result = (double) (x[k] >= knots[index]) * (x[k] < knots[index+1]); result++; } } else { for (k=0; k<nx; k++) { *result = 0.; result++; } } } else { for (k=0; k<nx; k++) { *result = 0.; result++; } } } } else { b = (double *) malloc(sizeof(*b) * (nbasis+1) * nx); bspline(&b, x, nx, knots, nknots, m-1, d-1, lower, upper+1); for(i=0; i<nbasis; i++) { b0 = b + nx*i; b1 = b + nx*(i+1); index = i+lower; if ((knots[index] != knots[index+m-1]) && (index+m-1 < nknots)) { denom = knots[index+m-1] - knots[index]; if (d <= 0) { for (k=0; k<nx; k++) { f0[k] = (x[k] - knots[index]) / denom; } } else { for (k=0; k<nx; k++) { f0[k] = (m-1) / (knots[index+m-1] - knots[index]); } } } else { for (k=0; k<nx; k++) { f0[k] = 0.; } } index = i+lower+1; if ((knots[index] != knots[index+m-1]) && (index+m-1 < nknots)) { denom = knots[index+m-1] - knots[index]; if (d <= 0) { for (k=0; k<nx; k++) { f1[k] = (knots[index+m-1] - x[k]) / denom; } } else { for (k=0; k<nx; k++) { f1[k] = -(m-1) / (knots[index+m-1] - knots[index]); } } } else { for (k=0; k<nx; k++) { f1[k] = 0.; } } for (k=0; k<nx; k++) { *result = f0[k]*(*b0) + f1[k]*(*b1); b0++; b1++; result++; } } free(b); } free(f0); free(f1); result = result - nx * nbasis; return(result); } ''' eval_ext_code = ''' int dim[2] = {upper-lower, Nx[0]}; PyArrayObject *basis; double *data; basis = (PyArrayObject *) PyArray_SimpleNew(2, dim, PyArray_DOUBLE); data = (double *) basis->data; bspline(&data, x, Nx[0], knots, Nknots[0], m, d, lower, upper); return_val = (PyObject *) basis; ''' bspline_eval = ext_tools.ext_function('evaluate', eval_ext_code, ['x', 'knots', 'm', 'd', 'lower', 'upper']) mod.add_function(bspline_eval) bspline_eval.customize.add_support_code(eval_code) nq = 18 qx, qw = scipy.special.orthogonal.p_roots(nq) dl = dr = 2 gram_code = ''' double *bspline_prod(double *x, int nx, double *knots, int nknots, int m, int l, int r, int dl, int dr) { double *result, *bl, *br; int k; if (fabs(r - l) <= m) { result = (double *) malloc(sizeof(*result) * nx); bl = (double *) malloc(sizeof(*bl) * nx); br = (double *) malloc(sizeof(*br) * nx); bl = bspline(&bl, x, nx, knots, nknots, m, dl, l, l+1); br = bspline(&br, x, nx, knots, nknots, m, dr, r, r+1); for (k=0; k<nx; k++) { result[k] = bl[k] * br[k]; } free(bl); free(br); } else { for (k=0; k<nx; k++) { result[k] = 0.; } } return(result); } double bspline_quad(double *knots, int nknots, int m, int l, int r, int dl, int dr) /* This is based on scipy.integrate.fixed_quad */ { double *y; double qx[%(nq)d]={%(qx)s}; double qw[%(nq)d]={%(qw)s}; double x[%(nq)d]; int nq=%(nq)d; int k, kk; int lower, upper; double result, a, b, partial; result = 0; /* TO DO: figure out knot span more efficiently */ lower = l - m - 1; if (lower < 0) { lower = 0;} upper = lower + 2 * m + 4; if (upper > nknots - 1) {upper = nknots-1;}
b6ac452f1e9fa776dec03294acafc891d6bb3877 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b6ac452f1e9fa776dec03294acafc891d6bb3877/bspline_module.py
int dim[2] = {Nknots[0]-m, m};
npy_intp dim[2] = {Nknots[0]-m, m};
def setup_bspline_module(): """ Builds an extension module with Bspline basis calculators using weave. """ mod = ext_tools.ext_module('_bspline', compiler='gcc') knots = N.linspace(0,1,11).astype(N.float64) nknots = knots.shape[0] x = N.array([0.4,0.5], N.float64) nx = x.shape[0] m = 4 d = 0 lower = 0 upper = 13 # Bspline code in C eval_code = ''' double *bspline(double **output, double *x, int nx, double *knots, int nknots, int m, int d, int lower, int upper) { int nbasis; int index, i, j, k; double *result, *b, *b0, *b1; double *f0, *f1; double denom; nbasis = upper - lower; result = *((double **) output); f0 = (double *) malloc(sizeof(*f0) * nx); f1 = (double *) malloc(sizeof(*f1) * nx); if (m == 1) { for(i=0; i<nbasis; i++) { index = i + lower; if(index < nknots - 1) { if ((knots[index] != knots[index+1]) && (d <= 0)) { for (k=0; k<nx; k++) { *result = (double) (x[k] >= knots[index]) * (x[k] < knots[index+1]); result++; } } else { for (k=0; k<nx; k++) { *result = 0.; result++; } } } else { for (k=0; k<nx; k++) { *result = 0.; result++; } } } } else { b = (double *) malloc(sizeof(*b) * (nbasis+1) * nx); bspline(&b, x, nx, knots, nknots, m-1, d-1, lower, upper+1); for(i=0; i<nbasis; i++) { b0 = b + nx*i; b1 = b + nx*(i+1); index = i+lower; if ((knots[index] != knots[index+m-1]) && (index+m-1 < nknots)) { denom = knots[index+m-1] - knots[index]; if (d <= 0) { for (k=0; k<nx; k++) { f0[k] = (x[k] - knots[index]) / denom; } } else { for (k=0; k<nx; k++) { f0[k] = (m-1) / (knots[index+m-1] - knots[index]); } } } else { for (k=0; k<nx; k++) { f0[k] = 0.; } } index = i+lower+1; if ((knots[index] != knots[index+m-1]) && (index+m-1 < nknots)) { denom = knots[index+m-1] - knots[index]; if (d <= 0) { for (k=0; k<nx; k++) { f1[k] = (knots[index+m-1] - x[k]) / denom; } } else { for (k=0; k<nx; k++) { f1[k] = -(m-1) / (knots[index+m-1] - knots[index]); } } } else { for (k=0; k<nx; k++) { f1[k] = 0.; } } for (k=0; k<nx; k++) { *result = f0[k]*(*b0) + f1[k]*(*b1); b0++; b1++; result++; } } free(b); } free(f0); free(f1); result = result - nx * nbasis; return(result); } ''' eval_ext_code = ''' int dim[2] = {upper-lower, Nx[0]}; PyArrayObject *basis; double *data; basis = (PyArrayObject *) PyArray_SimpleNew(2, dim, PyArray_DOUBLE); data = (double *) basis->data; bspline(&data, x, Nx[0], knots, Nknots[0], m, d, lower, upper); return_val = (PyObject *) basis; ''' bspline_eval = ext_tools.ext_function('evaluate', eval_ext_code, ['x', 'knots', 'm', 'd', 'lower', 'upper']) mod.add_function(bspline_eval) bspline_eval.customize.add_support_code(eval_code) nq = 18 qx, qw = scipy.special.orthogonal.p_roots(nq) dl = dr = 2 gram_code = ''' double *bspline_prod(double *x, int nx, double *knots, int nknots, int m, int l, int r, int dl, int dr) { double *result, *bl, *br; int k; if (fabs(r - l) <= m) { result = (double *) malloc(sizeof(*result) * nx); bl = (double *) malloc(sizeof(*bl) * nx); br = (double *) malloc(sizeof(*br) * nx); bl = bspline(&bl, x, nx, knots, nknots, m, dl, l, l+1); br = bspline(&br, x, nx, knots, nknots, m, dr, r, r+1); for (k=0; k<nx; k++) { result[k] = bl[k] * br[k]; } free(bl); free(br); } else { for (k=0; k<nx; k++) { result[k] = 0.; } } return(result); } double bspline_quad(double *knots, int nknots, int m, int l, int r, int dl, int dr) /* This is based on scipy.integrate.fixed_quad */ { double *y; double qx[%(nq)d]={%(qx)s}; double qw[%(nq)d]={%(qw)s}; double x[%(nq)d]; int nq=%(nq)d; int k, kk; int lower, upper; double result, a, b, partial; result = 0; /* TO DO: figure out knot span more efficiently */ lower = l - m - 1; if (lower < 0) { lower = 0;} upper = lower + 2 * m + 4; if (upper > nknots - 1) {upper = nknots-1;}
b6ac452f1e9fa776dec03294acafc891d6bb3877 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b6ac452f1e9fa776dec03294acafc891d6bb3877/bspline_module.py
int dim[2] = {NL[0], NL[1]};
npy_intp dim[2] = {NL[0], NL[1]};
def setup_bspline_module(): """ Builds an extension module with Bspline basis calculators using weave. """ mod = ext_tools.ext_module('_bspline', compiler='gcc') knots = N.linspace(0,1,11).astype(N.float64) nknots = knots.shape[0] x = N.array([0.4,0.5], N.float64) nx = x.shape[0] m = 4 d = 0 lower = 0 upper = 13 # Bspline code in C eval_code = ''' double *bspline(double **output, double *x, int nx, double *knots, int nknots, int m, int d, int lower, int upper) { int nbasis; int index, i, j, k; double *result, *b, *b0, *b1; double *f0, *f1; double denom; nbasis = upper - lower; result = *((double **) output); f0 = (double *) malloc(sizeof(*f0) * nx); f1 = (double *) malloc(sizeof(*f1) * nx); if (m == 1) { for(i=0; i<nbasis; i++) { index = i + lower; if(index < nknots - 1) { if ((knots[index] != knots[index+1]) && (d <= 0)) { for (k=0; k<nx; k++) { *result = (double) (x[k] >= knots[index]) * (x[k] < knots[index+1]); result++; } } else { for (k=0; k<nx; k++) { *result = 0.; result++; } } } else { for (k=0; k<nx; k++) { *result = 0.; result++; } } } } else { b = (double *) malloc(sizeof(*b) * (nbasis+1) * nx); bspline(&b, x, nx, knots, nknots, m-1, d-1, lower, upper+1); for(i=0; i<nbasis; i++) { b0 = b + nx*i; b1 = b + nx*(i+1); index = i+lower; if ((knots[index] != knots[index+m-1]) && (index+m-1 < nknots)) { denom = knots[index+m-1] - knots[index]; if (d <= 0) { for (k=0; k<nx; k++) { f0[k] = (x[k] - knots[index]) / denom; } } else { for (k=0; k<nx; k++) { f0[k] = (m-1) / (knots[index+m-1] - knots[index]); } } } else { for (k=0; k<nx; k++) { f0[k] = 0.; } } index = i+lower+1; if ((knots[index] != knots[index+m-1]) && (index+m-1 < nknots)) { denom = knots[index+m-1] - knots[index]; if (d <= 0) { for (k=0; k<nx; k++) { f1[k] = (knots[index+m-1] - x[k]) / denom; } } else { for (k=0; k<nx; k++) { f1[k] = -(m-1) / (knots[index+m-1] - knots[index]); } } } else { for (k=0; k<nx; k++) { f1[k] = 0.; } } for (k=0; k<nx; k++) { *result = f0[k]*(*b0) + f1[k]*(*b1); b0++; b1++; result++; } } free(b); } free(f0); free(f1); result = result - nx * nbasis; return(result); } ''' eval_ext_code = ''' int dim[2] = {upper-lower, Nx[0]}; PyArrayObject *basis; double *data; basis = (PyArrayObject *) PyArray_SimpleNew(2, dim, PyArray_DOUBLE); data = (double *) basis->data; bspline(&data, x, Nx[0], knots, Nknots[0], m, d, lower, upper); return_val = (PyObject *) basis; ''' bspline_eval = ext_tools.ext_function('evaluate', eval_ext_code, ['x', 'knots', 'm', 'd', 'lower', 'upper']) mod.add_function(bspline_eval) bspline_eval.customize.add_support_code(eval_code) nq = 18 qx, qw = scipy.special.orthogonal.p_roots(nq) dl = dr = 2 gram_code = ''' double *bspline_prod(double *x, int nx, double *knots, int nknots, int m, int l, int r, int dl, int dr) { double *result, *bl, *br; int k; if (fabs(r - l) <= m) { result = (double *) malloc(sizeof(*result) * nx); bl = (double *) malloc(sizeof(*bl) * nx); br = (double *) malloc(sizeof(*br) * nx); bl = bspline(&bl, x, nx, knots, nknots, m, dl, l, l+1); br = bspline(&br, x, nx, knots, nknots, m, dr, r, r+1); for (k=0; k<nx; k++) { result[k] = bl[k] * br[k]; } free(bl); free(br); } else { for (k=0; k<nx; k++) { result[k] = 0.; } } return(result); } double bspline_quad(double *knots, int nknots, int m, int l, int r, int dl, int dr) /* This is based on scipy.integrate.fixed_quad */ { double *y; double qx[%(nq)d]={%(qx)s}; double qw[%(nq)d]={%(qw)s}; double x[%(nq)d]; int nq=%(nq)d; int k, kk; int lower, upper; double result, a, b, partial; result = 0; /* TO DO: figure out knot span more efficiently */ lower = l - m - 1; if (lower < 0) { lower = 0;} upper = lower + 2 * m + 4; if (upper > nknots - 1) {upper = nknots-1;}
b6ac452f1e9fa776dec03294acafc891d6bb3877 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b6ac452f1e9fa776dec03294acafc891d6bb3877/bspline_module.py
return
return {}
def configuration(parent_package=''): """ gist only works with an X-windows server This will install *.gs and *.gp files to '%spython%s/site-packages/scipy/xplt' % (sys.prefix,sys.version[:3]) """ x11 = x11_info().get_info() if not x11: return config = default_config_dict('xplt',parent_package) local_path = get_path(__name__) sources = ['gistCmodule.c'] sources = [os.path.join(local_path,x) for x in sources] ext_arg = {'name':dot_join(parent_package,'xplt.gistC'), 'sources':sources} dict_append(ext_arg,**x11) dict_append(ext_arg,libraries=['m']) ext = Extension (**ext_arg) config['ext_modules'].append(ext) from glob import glob gist = glob(os.path.join(local_path,'gist','*.c')) # libraries are C static libraries config['libraries'].append(('gist',{'sources':gist, 'macros':[('STDC_HEADERS',1)]})) file_ext = ['*.gs','*.gp', '*.ps', '*.help'] xplt_files = [glob(os.path.join(local_path,x)) for x in file_ext] xplt_files = reduce(lambda x,y:x+y,xplt_files,[]) xplt_path = os.path.join(parent_package,'xplt') config['data_files'].extend( [(xplt_path,xplt_files)]) return config
0c72b32ad5b5f0664a32da92c9d5cd3adb8d0fbb /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/0c72b32ad5b5f0664a32da92c9d5cd3adb8d0fbb/setup_xplt.py
axis_range = array((self.x_axis.range(),self.y_axis.range()),Float) scale = self.graph_box.size() / axis_range * array((1.,-1.)) offset = self.graph_to_window(array((0.,0.))) self.image_list.scale_and_shift(scale,offset) self.line_list.scale_and_shift(scale,offset)
axis_range = array((self.x_axis.range(),self.y_axis.range()),Float) scale = self.graph_box.size() / axis_range * array((1.,-1.)) offset = self.graph_to_window(array((0.,0.))) self.image_list.scale_and_shift(scale,offset) self.line_list.scale_and_shift(scale,offset)
def layout_data(self): # get scale and offset axis_range = array((self.x_axis.range(),self.y_axis.range()),Float) # negative y to account for positve down in window coordinates scale = self.graph_box.size() / axis_range * array((1.,-1.)) offset = self.graph_to_window(array((0.,0.))) self.image_list.scale_and_shift(scale,offset) self.line_list.scale_and_shift(scale,offset) #self.legend #self.text_list #self.overlays
a213b5ad25e11f85b416deac9b90f96de37b72ae /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/a213b5ad25e11f85b416deac9b90f96de37b72ae/wxplt.py
self.draw_graph_area(dc)
self.draw_graph_area(dc)
def draw(self,dc=None): #if not len(self.line_list) or len(self.image_list): # return # resize if necessary #print 'draw'
a213b5ad25e11f85b416deac9b90f96de37b72ae /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/a213b5ad25e11f85b416deac9b90f96de37b72ae/wxplt.py
self.Refresh()
self.Refresh()
def update(self): #print 'update' #print 'plot_canvas.update:', self self.client_size = (0,0) # forces the layout self.Refresh()
a213b5ad25e11f85b416deac9b90f96de37b72ae /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/a213b5ad25e11f85b416deac9b90f96de37b72ae/wxplt.py
self.log.WriteText("Print Preview failed." \ "Check that default printer is configured\n")
print "Print Preview failed." \ "Check that default printer is configured\n"
def OnFilePreview(self, event): printout = graph_printout(self.client) printout2 = graph_printout(self.client) self.preview = wx.wxPrintPreview(printout, printout2, self.print_data) if not self.preview.Ok(): self.log.WriteText("Print Preview failed." \ "Check that default printer is configured\n") return
a213b5ad25e11f85b416deac9b90f96de37b72ae /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/a213b5ad25e11f85b416deac9b90f96de37b72ae/wxplt.py
f = rv.norm(old,w)[0]
f = rv.norm.rvs(old,w)[0]
def evaluate(self,gene): """ return a new value from the genes allele set """ size = len(gene.allele_set) if size == 1: return gene.allele_set[0] w = self.dev_width * size old = gene.index() new = -1; f = -1 while not (0 <= new < size): f = rv.norm(old,w)[0] new = round(f) if(old == new and f > new): new = new + 1 if(old == new and f < new): new = new - 1 return gene.allele_set[int(new)]
7898005e3c685bb409186e856d9751f46583c586 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7898005e3c685bb409186e856d9751f46583c586/gene.py
def evaluate(self,gene): dev = (gene.bounds[1]-gene.bounds[0]) * self.dev_width new = gene.bounds[1]
7898005e3c685bb409186e856d9751f46583c586 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7898005e3c685bb409186e856d9751f46583c586/gene.py
new = rv.norm(gene._value,dev).rvs()[0]
new = rv.norm.rvs(gene._value,dev)[0]
def evaluate(self,gene): dev = (gene.bounds[1]-gene.bounds[0]) * self.dev_width new = gene.bounds[1]
7898005e3c685bb409186e856d9751f46583c586 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7898005e3c685bb409186e856d9751f46583c586/gene.py
alpha_k, fc, gc, old_fval_backup, old_old_fval_backup, gfkp1 = \
alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \
def fmin_cg(f, x0, fprime=None, args=(), gtol=1e-5, norm=Inf, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function with nonlinear conjugate gradient algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the nonlinear conjugate gradient algorithm of Polak and Ribiere See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 120-122. Inputs: f -- the Python function or method to be minimized. x0 -- the initial guess for the minimizer. fprime -- a function to compute the gradient of f. args -- extra arguments to f and fprime. gtol -- stop when norm of gradient is less than gtol norm -- order of vector norm to use epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, func_calls, grad_calls, warnflag}, {allvecs}) xopt -- the minimizer of f. fopt -- the value of f(xopt). func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- if retall then this vector of the iterates is returned Additional Inputs: maxiter -- the maximum number of iterations. full_output -- if non-zero then return fopt, func_calls, grad_calls, and warnflag in addition to xopt. disp -- print convergence message if non-zero. retall -- return a list of results at each iteration if True """ x0 = asarray(x0) if maxiter is None: maxiter = len(x0)*200 func_calls, f = wrap_function(f, args) if fprime is None: grad_calls, myfprime = wrap_function(approx_fprime, (f, epsilon)) else: grad_calls, myfprime = wrap_function(fprime, args) gfk = myfprime(x0) k = 0 N = len(x0) xk = x0 old_fval = f(xk) old_old_fval = old_fval + 5000 if retall: allvecs = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk gnorm = vecnorm(gfk,ord=norm) while (gnorm > gtol) and (k < maxiter): deltak = numpy.dot(gfk,gfk) # These values are modified by the line search, even if it fails old_fval_backup = old_fval old_old_fval_backup = old_old_fval alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ linesearch.line_search(f,myfprime,xk,pk,gfk,old_fval, old_old_fval,c2=0.4) if alpha_k is None: # line search failed -- use different one. alpha_k, fc, gc, old_fval_backup, old_old_fval_backup, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk, old_fval,old_old_fval) if alpha_k is None or alpha_k == 0: # This line search also failed to find a better solution. warnflag = 2 break xk = xk + alpha_k*pk if retall: allvecs.append(xk) if gfkp1 is None: gfkp1 = myfprime(xk) yk = gfkp1 - gfk beta_k = pymax(0,numpy.dot(yk,gfkp1)/deltak) pk = -gfkp1 + beta_k * pk gfk = gfkp1 gnorm = vecnorm(gfk,ord=norm) k = k + 1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls[0] print " Gradient evaluations: %d" % grad_calls[0] elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls[0] print " Gradient evaluations: %d" % grad_calls[0] else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls[0] print " Gradient evaluations: %d" % grad_calls[0] if full_output: retlist = xk, fval, func_calls[0], grad_calls[0], warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist
42e0b5dd1cb619b8189a987ae434ae4af145f49b /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/42e0b5dd1cb619b8189a987ae434ae4af145f49b/optimize.py
old_fval,old_old_fval)
old_fval_backup,old_old_fval_backup)
def fmin_cg(f, x0, fprime=None, args=(), gtol=1e-5, norm=Inf, epsilon=_epsilon, maxiter=None, full_output=0, disp=1, retall=0): """Minimize a function with nonlinear conjugate gradient algorithm. Description: Optimize the function, f, whose gradient is given by fprime using the nonlinear conjugate gradient algorithm of Polak and Ribiere See Wright, and Nocedal 'Numerical Optimization', 1999, pg. 120-122. Inputs: f -- the Python function or method to be minimized. x0 -- the initial guess for the minimizer. fprime -- a function to compute the gradient of f. args -- extra arguments to f and fprime. gtol -- stop when norm of gradient is less than gtol norm -- order of vector norm to use epsilon -- if fprime is approximated use this value for the step size (can be scalar or vector) Outputs: (xopt, {fopt, func_calls, grad_calls, warnflag}, {allvecs}) xopt -- the minimizer of f. fopt -- the value of f(xopt). func_calls -- the number of function_calls. grad_calls -- the number of gradient calls. warnflag -- an integer warning flag: 1 : 'Maximum number of iterations exceeded.' 2 : 'Gradient and/or function calls not changing' allvecs -- if retall then this vector of the iterates is returned Additional Inputs: maxiter -- the maximum number of iterations. full_output -- if non-zero then return fopt, func_calls, grad_calls, and warnflag in addition to xopt. disp -- print convergence message if non-zero. retall -- return a list of results at each iteration if True """ x0 = asarray(x0) if maxiter is None: maxiter = len(x0)*200 func_calls, f = wrap_function(f, args) if fprime is None: grad_calls, myfprime = wrap_function(approx_fprime, (f, epsilon)) else: grad_calls, myfprime = wrap_function(fprime, args) gfk = myfprime(x0) k = 0 N = len(x0) xk = x0 old_fval = f(xk) old_old_fval = old_fval + 5000 if retall: allvecs = [xk] sk = [2*gtol] warnflag = 0 pk = -gfk gnorm = vecnorm(gfk,ord=norm) while (gnorm > gtol) and (k < maxiter): deltak = numpy.dot(gfk,gfk) # These values are modified by the line search, even if it fails old_fval_backup = old_fval old_old_fval_backup = old_old_fval alpha_k, fc, gc, old_fval, old_old_fval, gfkp1 = \ linesearch.line_search(f,myfprime,xk,pk,gfk,old_fval, old_old_fval,c2=0.4) if alpha_k is None: # line search failed -- use different one. alpha_k, fc, gc, old_fval_backup, old_old_fval_backup, gfkp1 = \ line_search(f,myfprime,xk,pk,gfk, old_fval,old_old_fval) if alpha_k is None or alpha_k == 0: # This line search also failed to find a better solution. warnflag = 2 break xk = xk + alpha_k*pk if retall: allvecs.append(xk) if gfkp1 is None: gfkp1 = myfprime(xk) yk = gfkp1 - gfk beta_k = pymax(0,numpy.dot(yk,gfkp1)/deltak) pk = -gfkp1 + beta_k * pk gfk = gfkp1 gnorm = vecnorm(gfk,ord=norm) k = k + 1 if disp or full_output: fval = old_fval if warnflag == 2: if disp: print "Warning: Desired error not necessarily achieved due to precision loss" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls[0] print " Gradient evaluations: %d" % grad_calls[0] elif k >= maxiter: warnflag = 1 if disp: print "Warning: Maximum number of iterations has been exceeded" print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls[0] print " Gradient evaluations: %d" % grad_calls[0] else: if disp: print "Optimization terminated successfully." print " Current function value: %f" % fval print " Iterations: %d" % k print " Function evaluations: %d" % func_calls[0] print " Gradient evaluations: %d" % grad_calls[0] if full_output: retlist = xk, fval, func_calls[0], grad_calls[0], warnflag if retall: retlist += (allvecs,) else: retlist = xk if retall: retlist = (xk, allvecs) return retlist
42e0b5dd1cb619b8189a987ae434ae4af145f49b /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/42e0b5dd1cb619b8189a987ae434ae4af145f49b/optimize.py
def asformat(self, format): # default converter goes through the CSC format csc = self.tocsc() return eval('%s_matrix' % format)(csc)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
format = self.getformat()
def __add__(self, other): format = self.getformat() csc = self.tocsc() res = csc + other return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
return eval('%s_matrix'%format)(res)
return res
def __add__(self, other): format = self.getformat() csc = self.tocsc() res = csc + other return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
format = self.getformat()
def __sub__(self, other): format = self.getformat() csc = self.tocsc() res = csc - other return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
return eval('%s_matrix'%format)(res)
return res
def __sub__(self, other): format = self.getformat() csc = self.tocsc() res = csc - other return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
format = self.getformat()
def __rsub__(self, other): # other - self format = self.getformat() csc = self.tocsc() res = csc.__rsub__(other) return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
return eval('%s_matrix'%format)(res)
return res
def __rsub__(self, other): # other - self format = self.getformat() csc = self.tocsc() res = csc.__rsub__(other) return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
format = self.getformat()
def __mul__(self, other): format = self.getformat() csc = self.tocsc() res = csc * other return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
return eval('%s_matrix'%format)(res)
return res
def __mul__(self, other): format = self.getformat() csc = self.tocsc() res = csc * other return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
format = self.getformat()
def __rmul__(self, other): format = self.getformat() csc = self.tocsc() res = csc.__rmul__(other) return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
return eval('%s_matrix'%format)(res)
return res
def __rmul__(self, other): format = self.getformat() csc = self.tocsc() res = csc.__rmul__(other) return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
format = self.getformat()
def __neg__(self): format = self.getformat() csc = self.tocsc() res = -csc return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
return eval('%s_matrix'%format)(res)
return res def matmat(self, other): csc = self.tocsc() res = csc.matmat(other) return res
def __neg__(self): format = self.getformat() csc = self.tocsc() res = -csc return eval('%s_matrix'%format)(res)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
format = self.getformat()
def matvec(self, vec): format = self.getformat() csc = self.tocsc() res = csc.matvec(vec) return res
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
M = max(self.rowind)
M = max(self.rowind) + 1
def __init__(self,s,ij=None,M=None,N=None,nzmax=100,typecode=Float,copy=0): spmatrix.__init__(self, 'csc') if isinstance(s,spmatrix): 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 tcode = s.typecode func = getattr(sparsetools,tcode+'transp') self.data, self.rowind, self.indptr = \ func(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 isinstance(s,type(3)): M=s N=ij self.data = zeros((nzmax,),typecode) self.rowind = zeros((nzmax,),'i') self.indptr = zeros((N+1,),'i') self.shape = (M,N) elif (isinstance(s,ArrayType) or \ isinstance(s,type([]))): s = asarray(s) if (rank(s) == 2): # converting from a full array M, N = s.shape s = asarray(s) if s.typecode() not in 'fdFD': s = s*1.0 typecode = s.typecode() func = getattr(sparsetools,_transtabl[typecode]+'fulltocsc') ierr = irow = jcol = 0 nnz = sum(ravel(s != 0.0)) a = zeros((nnz,),typecode) 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)
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
if (len(self.data) != len(self.rowind)):
if (len(self.data) != nzmax):
def _check(self): M,N = self.shape if (rank(self.data) != 1) or (rank(self.rowind) != 1) or \ (rank(self.indptr) != 1): raise ValueError, "Data, rowind, and indptr arrays "\ "should be rank 1." if (len(self.data) != len(self.rowind)): raise ValueError, "Data and row list should have same length" if (len(self.indptr) != N+1): raise ValueError, "Index pointer should be of of size N+1" if (len(self.rowind)>0) and (max(self.rowind) >= M): raise ValueError, "Row-values must be < M." if (self.indptr[-1] > len(self.rowind)): raise ValueError, \ "Last value of index list should be less than "\ "the size of data list" self.nnz = self.indptr[-1] self.nzmax = len(self.rowind) self.typecode = self.data.typecode() if self.typecode not in 'fdFD': raise ValueError, "Only floating point sparse matrix types allowed" self.ftype = _transtabl[self.typecode]
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
if (len(self.rowind)>0) and (max(self.rowind) >= M):
if (nzmax>0) and (max(self.rowind[:nnz]) >= M):
def _check(self): M,N = self.shape if (rank(self.data) != 1) or (rank(self.rowind) != 1) or \ (rank(self.indptr) != 1): raise ValueError, "Data, rowind, and indptr arrays "\ "should be rank 1." if (len(self.data) != len(self.rowind)): raise ValueError, "Data and row list should have same length" if (len(self.indptr) != N+1): raise ValueError, "Index pointer should be of of size N+1" if (len(self.rowind)>0) and (max(self.rowind) >= M): raise ValueError, "Row-values must be < M." if (self.indptr[-1] > len(self.rowind)): raise ValueError, \ "Last value of index list should be less than "\ "the size of data list" self.nnz = self.indptr[-1] self.nzmax = len(self.rowind) self.typecode = self.data.typecode() if self.typecode not in 'fdFD': raise ValueError, "Only floating point sparse matrix types allowed" self.ftype = _transtabl[self.typecode]
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
self.nnz = self.indptr[-1] self.nzmax = len(self.rowind)
self.nnz = nnz self.nzmax = nzmax
def _check(self): M,N = self.shape if (rank(self.data) != 1) or (rank(self.rowind) != 1) or \ (rank(self.indptr) != 1): raise ValueError, "Data, rowind, and indptr arrays "\ "should be rank 1." if (len(self.data) != len(self.rowind)): raise ValueError, "Data and row list should have same length" if (len(self.indptr) != N+1): raise ValueError, "Index pointer should be of of size N+1" if (len(self.rowind)>0) and (max(self.rowind) >= M): raise ValueError, "Row-values must be < M." if (self.indptr[-1] > len(self.rowind)): raise ValueError, \ "Last value of index list should be less than "\ "the size of data list" self.nnz = self.indptr[-1] self.nzmax = len(self.rowind) self.typecode = self.data.typecode() if self.typecode not in 'fdFD': raise ValueError, "Only floating point sparse matrix types allowed" self.ftype = _transtabl[self.typecode]
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
if not (0<=row<M) or not (0<=col<N): raise KeyError, "Index out of bounds."
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)
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 not (0<=row<M) or not (0<=col<N): raise KeyError, "Index out of bounds." 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
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
if not (0<=row<M) or not (0<=col<N): raise KeyError, "Index out of bounds."
if (row < 0): row = M + row if (col < 0): col = N + col if (row >= M ) or (col >= N) or (row < 0) or (col < 0): 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.colind, self.indptr, col, row) return val elif isinstance(key,type(3)): return self.data[key] else: raise NotImplementedError
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
if not (0<=row<M) or not (0<=col<N):
if (row < 0): row = M + row if (col < 0): col = N + col if (row < 0) or (col < 0):
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 not (0<=row<M) or not (0<=col<N): raise KeyError, "Index out of bounds." 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
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
def copy(self): M, N = self.shape typecode = self.typecode new = csr_matrix(M, N, nzmax=0, typecode=typecode) new.data = self.data.copy() new.colind = self.colind.copy() new.indptr = self.indptr.copy() new._check() return new
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
def csc_cmp(x,y): if (x == y): return 0 elif (x[1] == y[1]): if (x[0] > y[0]): return 1 elif (x[0] == y[0]): return 0 else: return -1 elif (x[1] > y[1]): return 1 else: return -1
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
self.typecode = None
self.nnz = 0
def __init__(self,A=None): dict.__init__(self) spmatrix.__init__(self,'dok') self.shape = (0,0) self.typecode = None if A is not None: A = asarray(A) N,M = A.shape for n in range(N): for m in range(M): if A[n,m] != 0: self[n,m] = A[n,m]
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
res = dictmatrix()
res = dok_matrix()
def __add__(self, other): res = dictmatrix() res.update(self) res.shape = self.shape for key in other.keys(): try: res[key] += other[key] except KeyError: res[key] = other[key] return res
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
res = dictmatrix()
res = dok_matrix()
def __sub__(self, other): res = dictmatrix() res.update(self) res.shape = self.shape for key in other.keys(): try: res[key] -= other[key] except KeyError: res[key] = -other[key] return res
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
res = dictmatrix()
res = dok_matrix()
def __neg__(self): res = dictmatrix() for key in self.keys(): res[key] = -self[key] return res
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
if isinstance(other, dictmatrix):
if isinstance(other, dok_matrix):
def __mul__(self, other): if isinstance(other, dictmatrix): return self.matmat(other) other = asarray(other) if rank(other) > 0: return self.matvec(other) res = dictmatrix() for key in self.keys(): res[key] = other * self[key] return res
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
res = dictmatrix()
res = dok_matrix()
def __mul__(self, other): if isinstance(other, dictmatrix): return self.matmat(other) other = asarray(other) if rank(other) > 0: return self.matvec(other) res = dictmatrix() for key in self.keys(): res[key] = other * self[key] return res
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
return len(self.keys())
return len(self.keys())
def __len__(self): return len(self.keys())
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
new = dictmatrix()
new = dok_matrix()
def transp(self): # Transpose (return the transposed) new = dictmatrix() for key in self.keys(): new[key[1],key[0]] = self[key] return new
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
def matmat(self, other): res = dictmatrix() spself = spmatrix(self) spother = spmatrix(other) spres = spself * spother return spres.todict()
def matmat(self, other): res = dictmatrix() spself = spmatrix(self) spother = spmatrix(other) spres = spself * spother return spres.todict()
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
res = dictmatrix()
res = dok_matrix()
def take(self, cols_or_rows, columns=1): # Extract columns or rows as indictated from matrix # assume cols_or_rows is sorted res = dictmatrix() 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) res[newkey] = self[key] else: for key in self.keys(): num = searchsorted(cols_or_rows,key[0]) if num < N: newkey = (num,key[1]) res[newkey] = self[key] return res
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
base = dictmatrix() ext = dictmatrix()
base = dok_matrix() ext = dok_matrix()
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 = dictmatrix() ext = dictmatrix() 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
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
def getCSR(self):
def tocsr(self):
def getCSR(self): # Return Compressed Sparse Row format arrays for this matrix keys = self.keys() keys.sort() nnz = len(keys) data = [0]*nnz colind = [0]*nnz row_ptr = [0]*(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: current_row = ikey0 row_ptr[ikey0] = k data[k] = self[key] colind[k] = ikey1 k += 1 row_ptr[-1] = nnz data = array(data) colind = array(colind) row_ptr = array(row_ptr) ptype = data.typecode() if ptype not in ['d','D','f','F']: data = data.astype('d') ptype = 'd' return _transtabl[ptype], nnz, data, colind, row_ptr
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
ptype = data.typecode() if ptype not in ['d','D','f','F']: data = data.astype('d') ptype = 'd' return _transtabl[ptype], nnz, data, colind, row_ptr def getCSC(self):
return csr_matrix(data,(colind, row_ptr)) def tocsc(self):
def getCSR(self): # Return Compressed Sparse Row format arrays for this matrix keys = self.keys() keys.sort() nnz = len(keys) data = [0]*nnz colind = [0]*nnz row_ptr = [0]*(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: current_row = ikey0 row_ptr[ikey0] = k data[k] = self[key] colind[k] = ikey1 k += 1 row_ptr[-1] = nnz data = array(data) colind = array(colind) row_ptr = array(row_ptr) ptype = data.typecode() if ptype not in ['d','D','f','F']: data = data.astype('d') ptype = 'd' return _transtabl[ptype], nnz, data, colind, row_ptr
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
ptype = data.typecode() if ptype not in ['d','D','f','F']: data = data.astype('d') ptype = 'd' return _transtabl[ptype], nnz, data, colind, col_ptr def dense(self,typecode=None): if typecode is None: typecode = self.type
return csc_matrix(data, (colind, col_ptr)) def todense(self,typecode=None):
def getCSC(self): # Return Compressed Sparse Column format arrays for this matrix keys = self.keys() keys.sort(csc_cmp) nnz = len(keys) data = [None]*nnz colind = [None]*nnz col_ptr = [None]*(self.shape[1]+1) current_col = -1 k = 0 for key in keys: ikey0 = int(key[0]) ikey1 = int(key[1]) if ikey1 != current_col: current_col = ikey1 col_ptr[ikey1] = k data[k] = self[key] colind[k] = ikey0 k += 1 col_ptr[-1] = nnz data = array(data) colind = array(colind) col_ptr = array(col_ptr) ptype = data.typecode() if ptype not in ['d','D','f','F']: data = data.astype('d') ptype = 'd' return _transtabl[ptype], nnz, data, colind, col_ptr
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
pass
def __init__(self, obj, ij, M=None, N=None, nzmax=None, typecode=None): aobj = asarray(obj) aij = asarray(ij) if M is None: M = amax(aij[:,0]) if N is None: N = amax(aij[:,1]) self.shape = (M,N) if nzmax is None: nzmax = len(aobj) self.nzmax = nzmax self.data = aobj self.row = aij[:,0] self.col = aij[:,1] self.typecode = aobj.typecode() self._check() def _check(self): nnz = len(self.data) if (nnz != len(self.row)) or (nnz != len(self.col)): raise ValueError, "Row, column, and data array must all be "\ "the same length." if (self.nzmax < nnz): raise ValueError, "nzmax must be >= nnz" self.ftype = _transtabl[self.typecode] def tocsc(self): func = getattr(sparsetools,self.ftype+"cootocsc") a, rowa, ptra, ierr = func(self.data, self.row, self.col) if ierr: raise RuntimeError, "Error in conversion." return csc_matrix(a, (rowa, ptra))
def dense(self,typecode=None): if typecode is None: typecode = self.type if typecode is None: typecode = 'd' new = zeros(self.shape,typecode) for key in self.keys(): ikey0 = int(key[0]) ikey1 = int(key[1]) new[ikey0,ikey1] = self[key] return new
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
diagfunc = eval('_sparsekit.'+_transtabl[mtype]+'diacsr') nzmax = diags.shape[0]*diags.shape[1] s = spmatrix(m,n,nzmax,typecode=mtype) diagfunc(array(m), array(n), array(0), diags, offsets, s.data, s.index[0], s.index[1], array(diags.shape[1]),array(diags.shape[0])) s.lastel = min([m,n])*len(offsets) - 1 - \ sum(_spdiags_tosub(offsets, a=min([n-m,0]), b=max([n-m,0]))) return s
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),M=m,N=n)
def spdiags(diags,offsets,m,n): """Return a sparse matrix given it's 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=1) if diags.typecode() not in 'fdFD': diags = diags.astype('d') offsets = array(offsets,copy=0) mtype = diags.typecode() assert(len(offsets) == diags.shape[1]) # set correct diagonal to csr conversion routine for this type diagfunc = eval('_sparsekit.'+_transtabl[mtype]+'diacsr') # construct empty sparse matrix and pass it's main parameters to # the diagonal to csr conversion routine. nzmax = diags.shape[0]*diags.shape[1] s = spmatrix(m,n,nzmax,typecode=mtype) diagfunc(array(m), array(n), array(0), diags, offsets, s.data, s.index[0], s.index[1], array(diags.shape[1]),array(diags.shape[0])) # compute how-many elements were actually filled s.lastel = min([m,n])*len(offsets) - 1 - \ sum(_spdiags_tosub(offsets, a=min([n-m,0]), b=max([n-m,0]))) return s
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
A.ftype, A.nnz, A.data, A.rowind, A.indptr
mat.ftype, mat.nnz, mat.data, mat.rowind, mat.indptr
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'): mat = A.tocsc() ftype, lastel, data, index0, index1 = \ A.ftype, A.nnz, A.data, A.rowind, A.indptr csc = 1 else: mat = A.tocsr() ftype, lastel, data, index0, index1 = \ A.ftype, A.nnz, A.data, A.colind, A.indptr csc = 0 gssv = eval('_superlu.' + ftype + 'gssv') return gssv(N,lastel,data,index0,index1,b,csc,permc_spec)[0]
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
A.ftype, A.nnz, A.data, A.colind, A.indptr
mat.ftype, mat.nnz, mat.data, mat.colind, mat.indptr
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'): mat = A.tocsc() ftype, lastel, data, index0, index1 = \ A.ftype, A.nnz, A.data, A.rowind, A.indptr csc = 1 else: mat = A.tocsr() ftype, lastel, data, index0, index1 = \ A.ftype, A.nnz, A.data, A.colind, A.indptr csc = 0 gssv = eval('_superlu.' + ftype + 'gssv') return gssv(N,lastel,data,index0,index1,b,csc,permc_spec)[0]
b14552c4a5780327bf9ca40b82d78bbf0d40722e /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/b14552c4a5780327bf9ca40b82d78bbf0d40722e/Sparse.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_simple(self):
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x0),[1,0])
assert_array_almost_equal(numpy.dot(a,x0),[1,0])
def check_20Feb04_bug(self): a = [[1,1],[1.0,0]] # ok x0 = solve(a,[1,0j]) assert_array_almost_equal(numpy.matrixmultiply(a,x0),[1,0])
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x0),[1,0])
assert_array_almost_equal(numpy.dot(a,x0),[1,0])
def check_20Feb04_bug(self): a = [[1,1],[1.0,0]] # ok x0 = solve(a,[1,0j]) assert_array_almost_equal(numpy.matrixmultiply(a,x0),[1,0])
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_simple(self): a = [[1,20],[-30,4]] for b in ([[1,0],[0,1]],[1,0], [[2,1],[-30,4]]): x = solve(a,b) assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_simple_sym(self): a = [[2,3],[3,5]] for lower in [0,1]: for b in ([[1,0],[0,1]],[1,0]): x = solve(a,b,sym_pos=1,lower=lower) assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_simple_sym_complex(self): a = [[5,2],[2,4]] for b in [[1j,0], [[1j,1j], [0,2]], ]: x = solve(a,b,sym_pos=1) assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_simple_complex(self): a = array([[5,2],[2j,4]],'D') for b in [[1j,0], [[1j,1j], [0,2]], [1,0j], array([1,0],'D'), ]: x = solve(a,b) assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_random(self):
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_random_complex(self): n = 20 a = random([n,n]) + 1j * random([n,n]) for i in range(n): a[i,i] = 20*(.1+a[i,i]) for i in range(2): b = random([n,3]) x = solve(a,b) assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_random_sym(self): n = 20 a = random([n,n]) for i in range(n): a[i,i] = abs(20*(.1+a[i,i])) for j in range(i): a[i,j] = a[j,i] for i in range(4): b = random([n]) x = solve(a,b,sym_pos=1) assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_random_sym_complex(self): n = 20 a = random([n,n]) #a = a + 1j*random([n,n]) # XXX: with this the accuracy will be very low for i in range(n): a[i,i] = abs(20*(.1+a[i,i])) for j in range(i): a[i,j] = numpy.conjugate(a[j,i]) b = random([n])+2j*random([n]) for i in range(2): x = solve(a,b,sym_pos=1) assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,a_inv),
assert_array_almost_equal(numpy.dot(a,a_inv),
def check_simple(self): a = [[1,2],[3,4]] a_inv = inv(a) assert_array_almost_equal(numpy.matrixmultiply(a,a_inv), [[1,0],[0,1]]) a = [[1,2,3],[4,5,6],[7,8,10]] a_inv = inv(a) assert_array_almost_equal(numpy.matrixmultiply(a,a_inv), [[1,0,0],[0,1,0],[0,0,1]])
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,a_inv),
assert_array_almost_equal(numpy.dot(a,a_inv),
def check_simple(self): a = [[1,2],[3,4]] a_inv = inv(a) assert_array_almost_equal(numpy.matrixmultiply(a,a_inv), [[1,0],[0,1]]) a = [[1,2,3],[4,5,6],[7,8,10]] a_inv = inv(a) assert_array_almost_equal(numpy.matrixmultiply(a,a_inv), [[1,0,0],[0,1,0],[0,0,1]])
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,a_inv),
assert_array_almost_equal(numpy.dot(a,a_inv),
def check_random(self): n = 20 for i in range(4): a = random([n,n]) for i in range(n): a[i,i] = 20*(.1+a[i,i]) a_inv = inv(a) assert_array_almost_equal(numpy.matrixmultiply(a,a_inv), numpy.identity(n))
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,a_inv),
assert_array_almost_equal(numpy.dot(a,a_inv),
def check_simple_complex(self): a = [[1,2],[3,4j]] a_inv = inv(a) assert_array_almost_equal(numpy.matrixmultiply(a,a_inv), [[1,0],[0,1]])
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,a_inv),
assert_array_almost_equal(numpy.dot(a,a_inv),
def check_random_complex(self): n = 20 for i in range(4): a = random([n,n])+2j*random([n,n]) for i in range(n): a[i,i] = 20*(.1+a[i,i]) a_inv = inv(a) assert_array_almost_equal(numpy.matrixmultiply(a,a_inv), numpy.identity(n))
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
a1 = numpy.matrixmultiply(numpy.transpose(a),a) b1 = numpy.matrixmultiply(numpy.transpose(a),b)
a1 = numpy.dot(numpy.transpose(a),a) b1 = numpy.dot(numpy.transpose(a),b)
def direct_lstsq(a,b): a1 = numpy.matrixmultiply(numpy.transpose(a),a) b1 = numpy.matrixmultiply(numpy.transpose(a),b) return solve(a1,b1)
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_simple_exact(self): a = [[1,20],[-30,4]] for b in ([[1,0],[0,1]],[1,0], [[2,1],[-30,4]]): x = lstsq(a,b)[0] assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_random_exact(self):
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
assert_array_almost_equal(numpy.dot(a,x),b)
def check_random_complex_exact(self): n = 20 a = random([n,n]) + 1j * random([n,n]) for i in range(n): a[i,i] = 20*(.1+a[i,i]) for i in range(2): b = random([n,3]) x = lstsq(a,b)[0] assert_array_almost_equal(numpy.matrixmultiply(a,x),b)
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert_array_almost_equal(x,direct_lstsq(a,b),1e-3)
assert_array_almost_equal(x,direct_lstsq(a,b),3)
def check_random_complex_overdet(self): n = 20 m = 15 a = random([n,m]) + 1j * random([n,m]) for i in range(m): a[i,i] = 20*(.1+a[i,i]) for i in range(2): b = random([n,3]) x,res,r,s = lstsq(a,b) assert r==m,'unexpected efficient rank' #XXX: check definition of res assert_array_almost_equal(x,direct_lstsq(a,b),1e-3) #XXX: tolerance 1e-3 is quite large, investigate the reason
9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/9bd2ebf847b7c0e4bdf3e5d49ab67f415145df68/test_basic.py
assert(allclose(abs(actual.flat),abs(desired.flat),1e-4,1e-6))
assert(allclose(abs(actual.ravel()),abs(desired.ravel()),1e-4,1e-6))
def generic_test(self,expr,arg_dict,type,size,mod_location): clean_result = array(arg_dict['result'],copy=1) t1 = time.time() exec expr in globals(),arg_dict t2 = time.time() standard = t2 - t1 desired = arg_dict['result'] arg_dict['result'] = clean_result t1 = time.time() old_env = os.environ.get('PYTHONCOMPILED','') os.environ['PYTHONCOMPILED'] = mod_location blitz_tools.blitz(expr,arg_dict,{},verbose=0) #, #extra_compile_args = ['-O3','-malign-double','-funroll-loops']) os.environ['PYTHONCOMPILED'] = old_env t2 = time.time() compiled = t2 - t1 actual = arg_dict['result'] # this really should give more info... try: # this isn't very stringent. Need to tighten this up and # learn where failures are occuring. assert(allclose(abs(actual.flat),abs(desired.flat),1e-4,1e-6)) except: diff = actual-desired print diff[:4,:4] print diff[:4,-4:] print diff[-4:,:4] print diff[-4:,-4:] print sum(abs(diff.flat)) raise AssertionError return standard,compiled
5c32156d4cdb054f09e85875794a5a8dc1411be6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5c32156d4cdb054f09e85875794a5a8dc1411be6/test_blitz_tools.py
print sum(abs(diff.flat))
print sum(abs(diff.ravel()))
def generic_test(self,expr,arg_dict,type,size,mod_location): clean_result = array(arg_dict['result'],copy=1) t1 = time.time() exec expr in globals(),arg_dict t2 = time.time() standard = t2 - t1 desired = arg_dict['result'] arg_dict['result'] = clean_result t1 = time.time() old_env = os.environ.get('PYTHONCOMPILED','') os.environ['PYTHONCOMPILED'] = mod_location blitz_tools.blitz(expr,arg_dict,{},verbose=0) #, #extra_compile_args = ['-O3','-malign-double','-funroll-loops']) os.environ['PYTHONCOMPILED'] = old_env t2 = time.time() compiled = t2 - t1 actual = arg_dict['result'] # this really should give more info... try: # this isn't very stringent. Need to tighten this up and # learn where failures are occuring. assert(allclose(abs(actual.flat),abs(desired.flat),1e-4,1e-6)) except: diff = actual-desired print diff[:4,:4] print diff[:4,-4:] print diff[-4:,:4] print diff[-4:,-4:] print sum(abs(diff.flat)) raise AssertionError return standard,compiled
5c32156d4cdb054f09e85875794a5a8dc1411be6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5c32156d4cdb054f09e85875794a5a8dc1411be6/test_blitz_tools.py
arg_dict[arg].savespace(1)
def generic_2d(self,expr,typ): """ The complex testing is pretty lame... """ mod_location = empty_temp_dir() import parser ast = parser.suite(expr) arg_list = harvest_variables(ast.tolist()) #print arg_list all_sizes = [(10,10), (50,50), (100,100), (500,500), (1000,1000)] print '\nExpression:', expr for size in all_sizes: result = zeros(size,typ) arg_dict = {} for arg in arg_list: arg_dict[arg] = random.normal(0,1,size).astype(typ) arg_dict[arg].savespace(1) # set imag part of complex values to non-zero value try: arg_dict[arg].imag = arg_dict[arg].real except: pass print 'Run:', size,typ standard,compiled = self.generic_test(expr,arg_dict,type,size, mod_location) try: speed_up = standard/compiled except: speed_up = -1. print "1st run(numpy.numerix,compiled,speed up): %3.4f, %3.4f, " \ "%3.4f" % (standard,compiled,speed_up) standard,compiled = self.generic_test(expr,arg_dict,type,size, mod_location) try: speed_up = standard/compiled except: speed_up = -1. print "2nd run(numpy.numerix,compiled,speed up): %3.4f, %3.4f, " \ "%3.4f" % (standard,compiled,speed_up) cleanup_temp_dir(mod_location)
5c32156d4cdb054f09e85875794a5a8dc1411be6 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/5c32156d4cdb054f09e85875794a5a8dc1411be6/test_blitz_tools.py
return = N.array([score])
return N.array([score])
def score(self, b, ties='breslow'):
7b85ea93c38525504baa6c05234ecaa4312d1aab /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/7b85ea93c38525504baa6c05234ecaa4312d1aab/cox.py
var = exp(-lambda_)/(1-exp(-lambda))**2
var = exp(-lambda_)/(1-exp(-lambda_))**2
def _stats(self, lambda_): m2, m1 = arr(lambda_) mu = 1/(exp(lambda_)-1) var = exp(-lambda_)/(1-exp(-lambda))**2 g1 = 2*cosh(lambda_/2.0) g2 = 4+2*cosh(lambda_) return mu, var, g1, g2
8a4682bd7af0347f95143e11c28e4922c100d870 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/8a4682bd7af0347f95143e11c28e4922c100d870/distributions.py
assert(isnan(array(0+0j)/0.) == 0)
assert(isnan(array(0+0j)/0.) == 1)
def check_complex1(self): assert(isnan(array(0+0j)/0.) == 0)
101dcb7f910052295ecaf3834877928181f3f081 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/101dcb7f910052295ecaf3834877928181f3f081/test_misc.py
return scipy.special.gamma(n+1)
return special.gamma(n+1)
def factorial(n): return scipy.special.gamma(n+1)
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
lgam = scipy.special.lgam
lgam = special.lgam
def comb(N,k): lgam = scipy.special.lgam return exp(lgam(N+1) - lgam(N-k+1) - lgam(k+1))
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
def freqs(b,a,w=None,N=None): pass
def freqs(b,a,worN=None): factor = 1.4 if worN is None: z, p, k = tf2zpk(b,a) maximag = max(concatenate((z.imag,p.imag))) minimag = min(concatenate((z.imag,p.imag))) w = scipy.grid[minimag*factor:maximag*factor:200] if isinstance(worN, types.IntType): N = worN z, p, k = tf2zpk(b,a) maximag = max(concatenate((z.imag,p.imag))) minimag = min(concatenate((z.imag,p.imag))) w = scipy.linspace(minimag*factor,maximag*factor,N) else: w = worN w = r1array(w) s = 1j*w return polyval(b, s) / polyval(a, s), w def freqz(b, a, worN=None, whole=0): b, a = map(r1array, (b,a)) if whole: lastpoint = 2*pi else: lastpoint = pi if worN is None: N = 512 w = Num.arange(0,lastpoint,lastpoint/N) elif isinstance(worN, types.IntType): N = worN w = Num.arange(0,lastpoint,lastpoint/N) else: w = worN w = r1array(w) zm1 = exp(-1j*w) return polyval(b[::-1], zm1) / polyval(a[::-1], zm1), w
def freqs(b,a,w=None,N=None): pass
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
z = roots(b) p = roots(a)
z = MLab.roots(b) p = MLab.roots(a)
def tf2zpk(b,a): b = (b+0.0) / a[0] a = (a+0.0) / a[0] k = b[0] b /= b[0] z = roots(b) p = roots(a) return z, p, k
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
b,a = map(MLab.asarray,(b,a)) while a[0] == 0.0:
b,a = map(r1array,(b,a)) while a[0] == 0.0 and len(a) > 1:
def normalize(b,a): b,a = map(MLab.asarray,(b,a)) while a[0] == 0.0: a = a[1:] while b[0] == 0.0: b = b[1:] outb = b * (1.0) / a[0] outa = a * (1.0) / a[0] return outb, outa
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
while b[0] == 0.0:
while b[0] == 0.0 and len(b) > 1:
def normalize(b,a): b,a = map(MLab.asarray,(b,a)) while a[0] == 0.0: a = a[1:] while b[0] == 0.0: b = b[1:] outb = b * (1.0) / a[0] outa = a * (1.0) / a[0] return outb, outa
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
pwo = pow(wo,arange(M-1,-1,-1))
pwo = pow(wo,Num.arange(M-1,-1,-1))
def lp2lp(b,a,wo=1.0): """Return a low-pass filter with cuttoff frequency wo from a low-pass filter prototype with unity cutoff frequency. """ a,b = map(r1array,(a,b)) if type(wo) is type(a): wo = wo[0] wo = float(wo) d = len(a) n = len(b) M = max((d,n)) pwo = pow(wo,arange(M-1,-1,-1)) start1 = max((n-d,0)) start2 = max((d-n,0)) b = b / pwo[start2:] a = a / pwo[start1:] return normalize(b, a)
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
def lp2hp(b,a,wo=1):
def lp2hp(b,a,wo=1.0):
def lp2hp(b,a,wo=1): """Return a high-pass filter with cuttoff frequency wo from a low-pass filter prototype with unity cutoff frequency. """ a,b = map(r1array,(a,b)) if type(wo) is type(a): wo = wo[0] d = len(a) n = len(b) if wo != 1: pwo = pow(wo,arange(max((d,n)))) else: pwo = ones(max((d,n)),b.typecode()) if d >= n: outa = a[::-1] * pwo outb = Numeric.resize(b,d) outb[:n] = b[::-1] * pwo[:n] else: outb = b[::-1] * pwo outa = Numeric.resize(a,n) outa[:d] = a[::-1] * pwo[:d] return normalize(outb, outa)
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
pwo = pow(wo,arange(max((d,n)))) else: pwo = ones(max((d,n)),b.typecode())
pwo = pow(wo,Num.arange(max((d,n)))) else: pwo = Num.ones(max((d,n)),b.typecode())
def lp2hp(b,a,wo=1): """Return a high-pass filter with cuttoff frequency wo from a low-pass filter prototype with unity cutoff frequency. """ a,b = map(r1array,(a,b)) if type(wo) is type(a): wo = wo[0] d = len(a) n = len(b) if wo != 1: pwo = pow(wo,arange(max((d,n)))) else: pwo = ones(max((d,n)),b.typecode()) if d >= n: outa = a[::-1] * pwo outb = Numeric.resize(b,d) outb[:n] = b[::-1] * pwo[:n] else: outb = b[::-1] * pwo outa = Numeric.resize(a,n) outa[:d] = a[::-1] * pwo[:d] return normalize(outb, outa)
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
outb = Numeric.resize(b,d) outb[:n] = b[::-1] * pwo[:n]
outb = Numeric.resize(b,(d,)) outb[n:] = 0.0 outb[:n] = b[::-1] * pwo[:n]
def lp2hp(b,a,wo=1): """Return a high-pass filter with cuttoff frequency wo from a low-pass filter prototype with unity cutoff frequency. """ a,b = map(r1array,(a,b)) if type(wo) is type(a): wo = wo[0] d = len(a) n = len(b) if wo != 1: pwo = pow(wo,arange(max((d,n)))) else: pwo = ones(max((d,n)),b.typecode()) if d >= n: outa = a[::-1] * pwo outb = Numeric.resize(b,d) outb[:n] = b[::-1] * pwo[:n] else: outb = b[::-1] * pwo outa = Numeric.resize(a,n) outa[:d] = a[::-1] * pwo[:d] return normalize(outb, outa)
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
outa = Numeric.resize(a,n)
outa = Numeric.resize(a,(n,)) outa[d:] = 0.0
def lp2hp(b,a,wo=1): """Return a high-pass filter with cuttoff frequency wo from a low-pass filter prototype with unity cutoff frequency. """ a,b = map(r1array,(a,b)) if type(wo) is type(a): wo = wo[0] d = len(a) n = len(b) if wo != 1: pwo = pow(wo,arange(max((d,n)))) else: pwo = ones(max((d,n)),b.typecode()) if d >= n: outa = a[::-1] * pwo outb = Numeric.resize(b,d) outb[:n] = b[::-1] * pwo[:n] else: outb = b[::-1] * pwo outa = Numeric.resize(a,n) outa[:d] = a[::-1] * pwo[:d] return normalize(outb, outa)
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
artype = Float
artype = Num.Float
def lp2bp(b,a,wo=1.0, bw=1.0): """Return a band-pass filter with center frequency wo and bandwidth bw from a low-pass filter prototype with unity cutoff frequency. """ a,b = map(r1array,(a,b)) D = len(a) - 1 N = len(b) - 1 artype = b.typecode() if artype not in ['F','D','f','d']: artype = Float ma = max([N,D]) Np = N + ma Dp = D + ma bprime = zeros(Np+1,artype) aprime = zeros(Dp+1,artype) wosq = wo*wo for j in range(Np+1): val = 0.0 for i in range(0,N+1): for k in range(0,i+1): if ma-i+2*k == j: val += comb(i,k)*b[N-i]*(wosq)**(i-k) / bw**i bprime[Np-j] = val for j in range(Dp+1): val = 0.0 for i in range(0,D+1): for k in range(0,i+1): if ma-i+2*k == j: val += comb(i,k)*a[D-i]*(wosq)**(i-k) / bw**i aprime[Dp-j] = val return normalize(bprime, aprime)
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
bprime = zeros(Np+1,artype) aprime = zeros(Dp+1,artype)
bprime = Num.zeros(Np+1,artype) aprime = Num.zeros(Dp+1,artype)
def lp2bp(b,a,wo=1.0, bw=1.0): """Return a band-pass filter with center frequency wo and bandwidth bw from a low-pass filter prototype with unity cutoff frequency. """ a,b = map(r1array,(a,b)) D = len(a) - 1 N = len(b) - 1 artype = b.typecode() if artype not in ['F','D','f','d']: artype = Float ma = max([N,D]) Np = N + ma Dp = D + ma bprime = zeros(Np+1,artype) aprime = zeros(Dp+1,artype) wosq = wo*wo for j in range(Np+1): val = 0.0 for i in range(0,N+1): for k in range(0,i+1): if ma-i+2*k == j: val += comb(i,k)*b[N-i]*(wosq)**(i-k) / bw**i bprime[Np-j] = val for j in range(Dp+1): val = 0.0 for i in range(0,D+1): for k in range(0,i+1): if ma-i+2*k == j: val += comb(i,k)*a[D-i]*(wosq)**(i-k) / bw**i aprime[Dp-j] = val return normalize(bprime, aprime)
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
artype = Float
artype = Num.Float
def lp2bs(b,a,wo=1,bw=1): """Return a band-stop filter with center frequency wo and bandwidth bw from a low-pass filter prototype with unity cutoff frequency. """ a,b = map(r1array,(a,b)) D = len(a) - 1 N = len(b) - 1 artype = b.typecode() if artype not in ['F','D','f','d']: artype = Float M = max([N,D]) Np = M + M Dp = M + M bprime = zeros(Np+1,artype) aprime = zeros(Dp+1,artype) wosq = wo*wo for j in range(Np+1): val = 0.0 for i in range(0,N+1): for k in range(0,M-i+1): if i+2*k == j: val += comb(M-i,k)*b[N-i]*(wosq)**(M-i-k) * bw**i bprime[Np-j] = val for j in range(Dp+1): val = 0.0 for i in range(0,D+1): for k in range(0,M-i+1): if i+2*k == j: val += comb(M-i,k)*a[D-i]*(wosq)**(M-i-k) * bw**i aprime[Dp-j] = val return normalize(bprime, aprime)
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py
bprime = zeros(Np+1,artype) aprime = zeros(Dp+1,artype)
bprime = Num.zeros(Np+1,artype) aprime = Num.zeros(Dp+1,artype)
def lp2bs(b,a,wo=1,bw=1): """Return a band-stop filter with center frequency wo and bandwidth bw from a low-pass filter prototype with unity cutoff frequency. """ a,b = map(r1array,(a,b)) D = len(a) - 1 N = len(b) - 1 artype = b.typecode() if artype not in ['F','D','f','d']: artype = Float M = max([N,D]) Np = M + M Dp = M + M bprime = zeros(Np+1,artype) aprime = zeros(Dp+1,artype) wosq = wo*wo for j in range(Np+1): val = 0.0 for i in range(0,N+1): for k in range(0,M-i+1): if i+2*k == j: val += comb(M-i,k)*b[N-i]*(wosq)**(M-i-k) * bw**i bprime[Np-j] = val for j in range(Dp+1): val = 0.0 for i in range(0,D+1): for k in range(0,M-i+1): if i+2*k == j: val += comb(M-i,k)*a[D-i]*(wosq)**(M-i-k) * bw**i aprime[Dp-j] = val return normalize(bprime, aprime)
78dbcc11384c4361dd850305b138d97d4c6ff715 /local1/tlutelli/issta_data/temp/all_python//python/2006_temp/2006/12971/78dbcc11384c4361dd850305b138d97d4c6ff715/filter_design.py